From 8a2269814d5c3d3f8470637778180ab260870d55 Mon Sep 17 00:00:00 2001 From: tqcq <99722391+tqcq@users.noreply.github.com> Date: Tue, 11 Jun 2024 19:13:30 +0800 Subject: [PATCH] init repo. --- .cmake.conf | 0 .gitea/workflows/android.yml | 68 + .gitea/workflows/linux-aarch64-gcc.yml | 57 + .gitea/workflows/linux-arm-gcc.yml | 80 + .gitea/workflows/linux-mips-gcc.yml | 55 + .gitea/workflows/linux-mips64-gcc.yml | 56 + .gitea/workflows/linux-riscv64-gcc.yml | 57 + .gitea/workflows/linux-x64-clang.yml | 52 + .gitea/workflows/linux-x64-gcc.yml | 53 + .gitea/workflows/linux-x86-gcc.yml | 55 + .gitignore | 4 + .gitmodules | 0 CMakeLists.txt | 366 + cmake/BuildInfo.cmake | 28 + dir.bloaty | 14 + third_party/benchmark/.clang-format | 5 + third_party/benchmark/.clang-tidy | 6 + .../.github/ISSUE_TEMPLATE/bug_report.md | 32 + .../.github/ISSUE_TEMPLATE/feature_request.md | 20 + .../benchmark/.github/install_bazel.sh | 12 + third_party/benchmark/.github/libcxx-setup.sh | 26 + .../benchmark/.github/workflows/bazel.yml | 35 + .../workflows/build-and-test-min-cmake.yml | 46 + .../workflows/build-and-test-perfcounters.yml | 51 + .../.github/workflows/build-and-test.yml | 161 + .../.github/workflows/clang-format-lint.yml | 18 + .../.github/workflows/clang-tidy.yml | 38 + .../benchmark/.github/workflows/doxygen.yml | 28 + .../.github/workflows/pre-commit.yml | 38 + .../benchmark/.github/workflows/sanitizer.yml | 96 + .../.github/workflows/test_bindings.yml | 30 + .../benchmark/.github/workflows/wheels.yml | 90 + third_party/benchmark/.gitignore | 68 + third_party/benchmark/.pre-commit-config.yaml | 18 + third_party/benchmark/.travis.yml | 208 + third_party/benchmark/.ycm_extra_conf.py | 120 + third_party/benchmark/AUTHORS | 72 + third_party/benchmark/BUILD.bazel | 114 + third_party/benchmark/CMakeLists.txt | 355 + third_party/benchmark/CONTRIBUTING.md | 58 + third_party/benchmark/CONTRIBUTORS | 97 + third_party/benchmark/LICENSE | 202 + third_party/benchmark/MODULE.bazel | 41 + third_party/benchmark/README.md | 223 + third_party/benchmark/WORKSPACE | 24 + third_party/benchmark/WORKSPACE.bzlmod | 2 + third_party/benchmark/_config.yml | 2 + third_party/benchmark/appveyor.yml | 50 + .../benchmark/bazel/benchmark_deps.bzl | 62 + .../bindings/python/google_benchmark/BUILD | 27 + .../python/google_benchmark/__init__.py | 141 + .../python/google_benchmark/benchmark.cc | 184 + .../python/google_benchmark/example.py | 139 + .../python/google_benchmark/version.py | 7 + .../benchmark/cmake/AddCXXCompilerFlag.cmake | 78 + .../benchmark/cmake/CXXFeatureCheck.cmake | 82 + third_party/benchmark/cmake/Config.cmake.in | 7 + .../benchmark/cmake/GetGitVersion.cmake | 36 + third_party/benchmark/cmake/GoogleTest.cmake | 58 + .../benchmark/cmake/GoogleTest.cmake.in | 59 + third_party/benchmark/cmake/benchmark.pc.in | 12 + .../benchmark/cmake/benchmark_main.pc.in | 7 + .../benchmark/cmake/gnu_posix_regex.cpp | 12 + .../benchmark/cmake/llvm-toolchain.cmake | 8 + third_party/benchmark/cmake/posix_regex.cpp | 14 + .../benchmark/cmake/pthread_affinity.cpp | 16 + third_party/benchmark/cmake/split_list.cmake | 3 + third_party/benchmark/cmake/std_regex.cpp | 10 + third_party/benchmark/cmake/steady_clock.cpp | 7 + .../cmake/thread_safety_attributes.cpp | 4 + .../benchmark/include/benchmark/benchmark.h | 2040 + .../benchmark/include/benchmark/export.h | 47 + third_party/benchmark/pyproject.toml | 86 + third_party/benchmark/setup.py | 148 + third_party/benchmark/src/CMakeLists.txt | 179 + third_party/benchmark/src/arraysize.h | 33 + third_party/benchmark/src/benchmark.cc | 808 + .../benchmark/src/benchmark_api_internal.cc | 118 + .../benchmark/src/benchmark_api_internal.h | 87 + third_party/benchmark/src/benchmark_main.cc | 18 + third_party/benchmark/src/benchmark_name.cc | 59 + .../benchmark/src/benchmark_register.cc | 521 + .../benchmark/src/benchmark_register.h | 109 + third_party/benchmark/src/benchmark_runner.cc | 498 + third_party/benchmark/src/benchmark_runner.h | 131 + third_party/benchmark/src/check.cc | 11 + third_party/benchmark/src/check.h | 106 + third_party/benchmark/src/colorprint.cc | 200 + third_party/benchmark/src/colorprint.h | 33 + third_party/benchmark/src/commandlineflags.cc | 298 + third_party/benchmark/src/commandlineflags.h | 133 + third_party/benchmark/src/complexity.cc | 259 + third_party/benchmark/src/complexity.h | 55 + third_party/benchmark/src/console_reporter.cc | 210 + third_party/benchmark/src/counter.cc | 80 + third_party/benchmark/src/counter.h | 32 + third_party/benchmark/src/csv_reporter.cc | 169 + third_party/benchmark/src/cycleclock.h | 242 + third_party/benchmark/src/internal_macros.h | 111 + third_party/benchmark/src/json_reporter.cc | 327 + third_party/benchmark/src/log.h | 88 + third_party/benchmark/src/mutex.h | 155 + third_party/benchmark/src/perf_counters.cc | 283 + third_party/benchmark/src/perf_counters.h | 200 + third_party/benchmark/src/re.h | 158 + third_party/benchmark/src/reporter.cc | 118 + third_party/benchmark/src/statistics.cc | 214 + third_party/benchmark/src/statistics.h | 44 + third_party/benchmark/src/string_util.cc | 254 + third_party/benchmark/src/string_util.h | 70 + third_party/benchmark/src/sysinfo.cc | 871 + third_party/benchmark/src/thread_manager.h | 63 + third_party/benchmark/src/thread_timer.h | 86 + third_party/benchmark/src/timers.cc | 276 + third_party/benchmark/src/timers.h | 48 + third_party/benchmark/tools/BUILD.bazel | 20 + third_party/benchmark/tools/compare.py | 523 + .../tools/gbench/Inputs/test1_run1.json | 127 + .../tools/gbench/Inputs/test1_run2.json | 127 + .../tools/gbench/Inputs/test2_run.json | 81 + .../tools/gbench/Inputs/test3_run0.json | 65 + .../tools/gbench/Inputs/test3_run1.json | 65 + .../tools/gbench/Inputs/test4_run.json | 96 + .../tools/gbench/Inputs/test4_run0.json | 21 + .../tools/gbench/Inputs/test4_run1.json | 21 + .../tools/gbench/Inputs/test5_run0.json | 18 + .../tools/gbench/Inputs/test5_run1.json | 18 + .../benchmark/tools/gbench/__init__.py | 8 + third_party/benchmark/tools/gbench/report.py | 1619 + third_party/benchmark/tools/gbench/util.py | 231 + .../benchmark/tools/libpfm.BUILD.bazel | 22 + third_party/benchmark/tools/requirements.txt | 2 + third_party/benchmark/tools/strip_asm.py | 163 + third_party/curl/CHANGES | 10709 ++++ .../curl/CMake/CMakeConfigurableFile.in | 24 + third_party/curl/CMake/CurlSymbolHiding.cmake | 84 + third_party/curl/CMake/CurlTests.c | 430 + third_party/curl/CMake/FindBearSSL.cmake | 32 + third_party/curl/CMake/FindBrotli.cmake | 43 + third_party/curl/CMake/FindCARES.cmake | 47 + third_party/curl/CMake/FindGSS.cmake | 312 + third_party/curl/CMake/FindLibPSL.cmake | 45 + third_party/curl/CMake/FindLibSSH2.cmake | 45 + third_party/curl/CMake/FindMSH3.cmake | 70 + third_party/curl/CMake/FindMbedTLS.cmake | 36 + third_party/curl/CMake/FindNGHTTP2.cmake | 41 + third_party/curl/CMake/FindNGHTTP3.cmake | 78 + third_party/curl/CMake/FindNGTCP2.cmake | 117 + third_party/curl/CMake/FindQUICHE.cmake | 70 + third_party/curl/CMake/FindWolfSSL.cmake | 36 + third_party/curl/CMake/FindZstd.cmake | 78 + third_party/curl/CMake/Macros.cmake | 80 + third_party/curl/CMake/OtherTests.cmake | 184 + third_party/curl/CMake/PickyWarnings.cmake | 236 + .../curl/CMake/Platforms/WindowsCache.cmake | 191 + third_party/curl/CMake/Utilities.cmake | 35 + .../curl/CMake/cmake_uninstall.cmake.in | 49 + third_party/curl/CMake/curl-config.cmake.in | 40 + third_party/curl/CMakeLists.txt | 1889 + third_party/curl/COPYING | 22 + third_party/curl/Dockerfile | 41 + third_party/curl/Makefile | 71 + third_party/curl/Makefile.am | 231 + third_party/curl/Makefile.in | 1788 + third_party/curl/README | 55 + third_party/curl/RELEASE-NOTES | 505 + third_party/curl/acinclude.m4 | 1663 + third_party/curl/aclocal.m4 | 1252 + third_party/curl/buildconf | 8 + third_party/curl/buildconf.bat | 265 + third_party/curl/compile | 348 + third_party/curl/config.guess | 1754 + third_party/curl/config.sub | 1890 + third_party/curl/configure | 49133 ++++++++++++++++ third_party/curl/configure.ac | 5051 ++ third_party/curl/curl-config.in | 193 + third_party/curl/depcomp | 791 + third_party/curl/include/Makefile.am | 28 + third_party/curl/include/Makefile.in | 774 + third_party/curl/include/README.md | 20 + third_party/curl/include/curl/Makefile.am | 41 + third_party/curl/include/curl/Makefile.in | 725 + third_party/curl/include/curl/curl.h | 3247 + third_party/curl/include/curl/curlver.h | 79 + third_party/curl/include/curl/easy.h | 125 + third_party/curl/include/curl/header.h | 74 + third_party/curl/include/curl/mprintf.h | 78 + third_party/curl/include/curl/multi.h | 475 + third_party/curl/include/curl/options.h | 70 + third_party/curl/include/curl/stdcheaders.h | 35 + third_party/curl/include/curl/system.h | 496 + third_party/curl/include/curl/typecheck-gcc.h | 718 + third_party/curl/include/curl/urlapi.h | 154 + third_party/curl/include/curl/websockets.h | 84 + third_party/curl/install-sh | 541 + third_party/curl/lib/.checksrc | 1 + third_party/curl/lib/CMakeLists.txt | 251 + third_party/curl/lib/Makefile.am | 148 + third_party/curl/lib/Makefile.in | 5523 ++ third_party/curl/lib/Makefile.inc | 381 + third_party/curl/lib/Makefile.mk | 334 + third_party/curl/lib/Makefile.soname | 42 + third_party/curl/lib/altsvc.c | 708 + third_party/curl/lib/altsvc.h | 81 + third_party/curl/lib/amigaos.c | 247 + third_party/curl/lib/amigaos.h | 41 + third_party/curl/lib/arpa_telnet.h | 117 + third_party/curl/lib/asyn-ares.c | 958 + third_party/curl/lib/asyn-thread.c | 998 + third_party/curl/lib/asyn.h | 184 + third_party/curl/lib/base64.c | 293 + third_party/curl/lib/bufq.c | 677 + third_party/curl/lib/bufq.h | 272 + third_party/curl/lib/bufref.c | 127 + third_party/curl/lib/bufref.h | 48 + third_party/curl/lib/c-hyper.c | 1228 + third_party/curl/lib/c-hyper.h | 63 + third_party/curl/lib/cf-h1-proxy.c | 1104 + third_party/curl/lib/cf-h1-proxy.h | 39 + third_party/curl/lib/cf-h2-proxy.c | 1576 + third_party/curl/lib/cf-h2-proxy.h | 39 + third_party/curl/lib/cf-haproxy.c | 250 + third_party/curl/lib/cf-haproxy.h | 39 + third_party/curl/lib/cf-https-connect.c | 531 + third_party/curl/lib/cf-https-connect.h | 58 + third_party/curl/lib/cf-socket.c | 1963 + third_party/curl/lib/cf-socket.h | 171 + third_party/curl/lib/cfilters.c | 861 + third_party/curl/lib/cfilters.h | 644 + third_party/curl/lib/config-amigaos.h | 129 + third_party/curl/lib/config-dos.h | 138 + third_party/curl/lib/config-mac.h | 103 + third_party/curl/lib/config-os400.h | 334 + third_party/curl/lib/config-plan9.h | 147 + third_party/curl/lib/config-riscos.h | 277 + third_party/curl/lib/config-win32.h | 512 + third_party/curl/lib/config-win32ce.h | 303 + third_party/curl/lib/conncache.c | 581 + third_party/curl/lib/conncache.h | 122 + third_party/curl/lib/connect.c | 1446 + third_party/curl/lib/connect.h | 133 + third_party/curl/lib/content_encoding.c | 1079 + third_party/curl/lib/content_encoding.h | 34 + third_party/curl/lib/cookie.c | 1771 + third_party/curl/lib/cookie.h | 138 + third_party/curl/lib/curl_addrinfo.c | 592 + third_party/curl/lib/curl_addrinfo.h | 108 + third_party/curl/lib/curl_base64.h | 41 + third_party/curl/lib/curl_config.h.cmake | 810 + third_party/curl/lib/curl_config.h.in | 1001 + third_party/curl/lib/curl_ctype.h | 51 + third_party/curl/lib/curl_des.c | 69 + third_party/curl/lib/curl_des.h | 40 + third_party/curl/lib/curl_endian.c | 84 + third_party/curl/lib/curl_endian.h | 36 + third_party/curl/lib/curl_fnmatch.c | 390 + third_party/curl/lib/curl_fnmatch.h | 46 + third_party/curl/lib/curl_get_line.c | 77 + third_party/curl/lib/curl_get_line.h | 32 + third_party/curl/lib/curl_gethostname.c | 102 + third_party/curl/lib/curl_gethostname.h | 33 + third_party/curl/lib/curl_gssapi.c | 152 + third_party/curl/lib/curl_gssapi.h | 63 + third_party/curl/lib/curl_hmac.h | 78 + third_party/curl/lib/curl_krb5.h | 52 + third_party/curl/lib/curl_ldap.h | 36 + third_party/curl/lib/curl_md4.h | 39 + third_party/curl/lib/curl_md5.h | 67 + third_party/curl/lib/curl_memory.h | 178 + third_party/curl/lib/curl_memrchr.c | 64 + third_party/curl/lib/curl_memrchr.h | 44 + third_party/curl/lib/curl_multibyte.c | 162 + third_party/curl/lib/curl_multibyte.h | 91 + third_party/curl/lib/curl_ntlm_core.c | 669 + third_party/curl/lib/curl_ntlm_core.h | 79 + third_party/curl/lib/curl_path.c | 203 + third_party/curl/lib/curl_path.h | 49 + third_party/curl/lib/curl_printf.h | 55 + third_party/curl/lib/curl_range.c | 96 + third_party/curl/lib/curl_range.h | 31 + third_party/curl/lib/curl_rtmp.c | 362 + third_party/curl/lib/curl_rtmp.h | 37 + third_party/curl/lib/curl_sasl.c | 760 + third_party/curl/lib/curl_sasl.h | 165 + third_party/curl/lib/curl_setup.h | 921 + third_party/curl/lib/curl_setup_once.h | 414 + third_party/curl/lib/curl_sha256.h | 50 + third_party/curl/lib/curl_sha512_256.c | 850 + third_party/curl/lib/curl_sha512_256.h | 44 + third_party/curl/lib/curl_sspi.c | 239 + third_party/curl/lib/curl_sspi.h | 123 + third_party/curl/lib/curl_threads.c | 154 + third_party/curl/lib/curl_threads.h | 65 + third_party/curl/lib/curl_trc.c | 331 + third_party/curl/lib/curl_trc.h | 200 + third_party/curl/lib/curlx.h | 117 + third_party/curl/lib/cw-out.c | 474 + third_party/curl/lib/cw-out.h | 53 + third_party/curl/lib/dict.c | 321 + third_party/curl/lib/dict.h | 31 + third_party/curl/lib/dllmain.c | 81 + third_party/curl/lib/doh.c | 1403 + third_party/curl/lib/doh.h | 165 + third_party/curl/lib/dynbuf.c | 282 + third_party/curl/lib/dynbuf.h | 93 + third_party/curl/lib/dynhds.c | 396 + third_party/curl/lib/dynhds.h | 183 + third_party/curl/lib/easy.c | 1343 + third_party/curl/lib/easy_lock.h | 111 + third_party/curl/lib/easygetopt.c | 98 + third_party/curl/lib/easyif.h | 41 + third_party/curl/lib/easyoptions.c | 381 + third_party/curl/lib/easyoptions.h | 37 + third_party/curl/lib/escape.c | 234 + third_party/curl/lib/escape.h | 44 + third_party/curl/lib/file.c | 639 + third_party/curl/lib/file.h | 42 + third_party/curl/lib/fileinfo.c | 46 + third_party/curl/lib/fileinfo.h | 40 + third_party/curl/lib/fopen.c | 158 + third_party/curl/lib/fopen.h | 30 + third_party/curl/lib/formdata.c | 958 + third_party/curl/lib/formdata.h | 59 + third_party/curl/lib/ftp.c | 4584 ++ third_party/curl/lib/ftp.h | 167 + third_party/curl/lib/ftplistparser.c | 1041 + third_party/curl/lib/ftplistparser.h | 77 + third_party/curl/lib/functypes.h | 115 + third_party/curl/lib/getenv.c | 80 + third_party/curl/lib/getinfo.c | 640 + third_party/curl/lib/getinfo.h | 29 + third_party/curl/lib/gopher.c | 244 + third_party/curl/lib/gopher.h | 34 + third_party/curl/lib/hash.c | 373 + third_party/curl/lib/hash.h | 108 + third_party/curl/lib/headers.c | 449 + third_party/curl/lib/headers.h | 62 + third_party/curl/lib/hmac.c | 173 + third_party/curl/lib/hostasyn.c | 123 + third_party/curl/lib/hostip.c | 1481 + third_party/curl/lib/hostip.h | 266 + third_party/curl/lib/hostip4.c | 301 + third_party/curl/lib/hostip6.c | 157 + third_party/curl/lib/hostsyn.c | 104 + third_party/curl/lib/hsts.c | 576 + third_party/curl/lib/hsts.h | 69 + third_party/curl/lib/http.c | 4516 ++ third_party/curl/lib/http.h | 301 + third_party/curl/lib/http1.c | 346 + third_party/curl/lib/http1.h | 63 + third_party/curl/lib/http2.c | 2875 + third_party/curl/lib/http2.h | 77 + third_party/curl/lib/http_aws_sigv4.c | 814 + third_party/curl/lib/http_aws_sigv4.h | 31 + third_party/curl/lib/http_chunks.c | 681 + third_party/curl/lib/http_chunks.h | 145 + third_party/curl/lib/http_digest.c | 185 + third_party/curl/lib/http_digest.h | 44 + third_party/curl/lib/http_negotiate.c | 239 + third_party/curl/lib/http_negotiate.h | 43 + third_party/curl/lib/http_ntlm.c | 270 + third_party/curl/lib/http_ntlm.h | 44 + third_party/curl/lib/http_proxy.c | 336 + third_party/curl/lib/http_proxy.h | 61 + third_party/curl/lib/idn.c | 337 + third_party/curl/lib/idn.h | 39 + third_party/curl/lib/if2ip.c | 260 + third_party/curl/lib/if2ip.h | 92 + third_party/curl/lib/imap.c | 2117 + third_party/curl/lib/imap.h | 101 + third_party/curl/lib/inet_ntop.c | 205 + third_party/curl/lib/inet_ntop.h | 39 + third_party/curl/lib/inet_pton.c | 243 + third_party/curl/lib/inet_pton.h | 38 + third_party/curl/lib/krb5.c | 922 + third_party/curl/lib/ldap.c | 1112 + third_party/curl/lib/libcurl.rc | 65 + third_party/curl/lib/libcurl.vers.in | 13 + third_party/curl/lib/llist.c | 162 + third_party/curl/lib/llist.h | 54 + third_party/curl/lib/macos.c | 55 + third_party/curl/lib/macos.h | 39 + third_party/curl/lib/md4.c | 526 + third_party/curl/lib/md5.c | 656 + third_party/curl/lib/memdebug.c | 463 + third_party/curl/lib/memdebug.h | 202 + third_party/curl/lib/mime.c | 2238 + third_party/curl/lib/mime.h | 176 + third_party/curl/lib/mprintf.c | 1204 + third_party/curl/lib/mqtt.c | 842 + third_party/curl/lib/mqtt.h | 63 + third_party/curl/lib/multi.c | 3937 ++ third_party/curl/lib/multihandle.h | 189 + third_party/curl/lib/multiif.h | 147 + third_party/curl/lib/netrc.c | 353 + third_party/curl/lib/netrc.h | 43 + third_party/curl/lib/nonblock.c | 84 + third_party/curl/lib/nonblock.h | 32 + third_party/curl/lib/noproxy.c | 265 + third_party/curl/lib/noproxy.h | 45 + third_party/curl/lib/openldap.c | 1224 + third_party/curl/lib/parsedate.c | 644 + third_party/curl/lib/parsedate.h | 38 + third_party/curl/lib/pingpong.c | 438 + third_party/curl/lib/pingpong.h | 160 + third_party/curl/lib/pop3.c | 1584 + third_party/curl/lib/pop3.h | 98 + third_party/curl/lib/progress.c | 633 + third_party/curl/lib/progress.h | 77 + third_party/curl/lib/psl.c | 113 + third_party/curl/lib/psl.h | 49 + third_party/curl/lib/rand.c | 291 + third_party/curl/lib/rand.h | 50 + third_party/curl/lib/rename.c | 73 + third_party/curl/lib/rename.h | 29 + third_party/curl/lib/request.c | 409 + third_party/curl/lib/request.h | 227 + third_party/curl/lib/rtsp.c | 1040 + third_party/curl/lib/rtsp.h | 80 + third_party/curl/lib/select.c | 403 + third_party/curl/lib/select.h | 114 + third_party/curl/lib/sendf.c | 1378 + third_party/curl/lib/sendf.h | 407 + third_party/curl/lib/setopt.c | 3213 + third_party/curl/lib/setopt.h | 33 + third_party/curl/lib/setup-os400.h | 144 + third_party/curl/lib/setup-vms.h | 444 + third_party/curl/lib/setup-win32.h | 138 + third_party/curl/lib/sha256.c | 545 + third_party/curl/lib/share.c | 290 + third_party/curl/lib/share.h | 68 + third_party/curl/lib/sigpipe.h | 80 + third_party/curl/lib/slist.c | 146 + third_party/curl/lib/slist.h | 41 + third_party/curl/lib/smb.c | 1206 + third_party/curl/lib/smb.h | 61 + third_party/curl/lib/smtp.c | 1947 + third_party/curl/lib/smtp.h | 87 + third_party/curl/lib/sockaddr.h | 44 + third_party/curl/lib/socketpair.c | 211 + third_party/curl/lib/socketpair.h | 78 + third_party/curl/lib/socks.c | 1276 + third_party/curl/lib/socks.h | 61 + third_party/curl/lib/socks_gssapi.c | 535 + third_party/curl/lib/socks_sspi.c | 620 + third_party/curl/lib/speedcheck.c | 79 + third_party/curl/lib/speedcheck.h | 35 + third_party/curl/lib/splay.c | 278 + third_party/curl/lib/splay.h | 58 + third_party/curl/lib/strcase.c | 204 + third_party/curl/lib/strcase.h | 54 + third_party/curl/lib/strdup.c | 143 + third_party/curl/lib/strdup.h | 38 + third_party/curl/lib/strerror.c | 1117 + third_party/curl/lib/strerror.h | 39 + third_party/curl/lib/strtok.c | 68 + third_party/curl/lib/strtok.h | 36 + third_party/curl/lib/strtoofft.c | 240 + third_party/curl/lib/strtoofft.h | 54 + third_party/curl/lib/system_win32.c | 270 + third_party/curl/lib/system_win32.h | 77 + third_party/curl/lib/telnet.c | 1652 + third_party/curl/lib/telnet.h | 30 + third_party/curl/lib/tftp.c | 1407 + third_party/curl/lib/tftp.h | 33 + third_party/curl/lib/timediff.c | 88 + third_party/curl/lib/timediff.h | 52 + third_party/curl/lib/timeval.c | 237 + third_party/curl/lib/timeval.h | 62 + third_party/curl/lib/transfer.c | 1278 + third_party/curl/lib/transfer.h | 115 + third_party/curl/lib/url.c | 3972 ++ third_party/curl/lib/url.h | 81 + third_party/curl/lib/urlapi-int.h | 38 + third_party/curl/lib/urlapi.c | 1995 + third_party/curl/lib/urldata.h | 1981 + third_party/curl/lib/vauth/cleartext.c | 137 + third_party/curl/lib/vauth/cram.c | 97 + third_party/curl/lib/vauth/digest.c | 1031 + third_party/curl/lib/vauth/digest.h | 40 + third_party/curl/lib/vauth/digest_sspi.c | 672 + third_party/curl/lib/vauth/gsasl.c | 127 + third_party/curl/lib/vauth/krb5_gssapi.c | 324 + third_party/curl/lib/vauth/krb5_sspi.c | 475 + third_party/curl/lib/vauth/ntlm.c | 780 + third_party/curl/lib/vauth/ntlm.h | 143 + third_party/curl/lib/vauth/ntlm_sspi.c | 372 + third_party/curl/lib/vauth/oauth2.c | 108 + third_party/curl/lib/vauth/spnego_gssapi.c | 281 + third_party/curl/lib/vauth/spnego_sspi.c | 364 + third_party/curl/lib/vauth/vauth.c | 163 + third_party/curl/lib/vauth/vauth.h | 236 + third_party/curl/lib/version.c | 690 + third_party/curl/lib/version_win32.c | 319 + third_party/curl/lib/version_win32.h | 56 + third_party/curl/lib/vquic/curl_msh3.c | 1115 + third_party/curl/lib/vquic/curl_msh3.h | 46 + third_party/curl/lib/vquic/curl_ngtcp2.c | 2509 + third_party/curl/lib/vquic/curl_ngtcp2.h | 61 + third_party/curl/lib/vquic/curl_osslq.c | 2332 + third_party/curl/lib/vquic/curl_osslq.h | 51 + third_party/curl/lib/vquic/curl_quiche.c | 1651 + third_party/curl/lib/vquic/curl_quiche.h | 50 + third_party/curl/lib/vquic/vquic-tls.c | 342 + third_party/curl/lib/vquic/vquic-tls.h | 99 + third_party/curl/lib/vquic/vquic.c | 677 + third_party/curl/lib/vquic/vquic.h | 64 + third_party/curl/lib/vquic/vquic_int.h | 93 + third_party/curl/lib/vssh/libssh.c | 2954 + third_party/curl/lib/vssh/libssh2.c | 3836 ++ third_party/curl/lib/vssh/ssh.h | 273 + third_party/curl/lib/vssh/wolfssh.c | 1169 + third_party/curl/lib/vtls/bearssl.c | 1138 + third_party/curl/lib/vtls/bearssl.h | 34 + third_party/curl/lib/vtls/cipher_suite.c | 716 + third_party/curl/lib/vtls/cipher_suite.h | 46 + third_party/curl/lib/vtls/gtls.c | 1864 + third_party/curl/lib/vtls/gtls.h | 85 + third_party/curl/lib/vtls/hostcheck.c | 135 + third_party/curl/lib/vtls/hostcheck.h | 33 + third_party/curl/lib/vtls/keylog.c | 167 + third_party/curl/lib/vtls/keylog.h | 58 + third_party/curl/lib/vtls/mbedtls.c | 1509 + third_party/curl/lib/vtls/mbedtls.h | 34 + .../curl/lib/vtls/mbedtls_threadlock.c | 134 + .../curl/lib/vtls/mbedtls_threadlock.h | 50 + third_party/curl/lib/vtls/openssl.c | 5301 ++ third_party/curl/lib/vtls/openssl.h | 121 + third_party/curl/lib/vtls/rustls.c | 791 + third_party/curl/lib/vtls/rustls.h | 35 + third_party/curl/lib/vtls/schannel.c | 2933 + third_party/curl/lib/vtls/schannel.h | 86 + third_party/curl/lib/vtls/schannel_int.h | 180 + third_party/curl/lib/vtls/schannel_verify.c | 787 + third_party/curl/lib/vtls/sectransp.c | 3492 ++ third_party/curl/lib/vtls/sectransp.h | 34 + third_party/curl/lib/vtls/vtls.c | 2172 + third_party/curl/lib/vtls/vtls.h | 260 + third_party/curl/lib/vtls/vtls_int.h | 209 + third_party/curl/lib/vtls/wolfssl.c | 1526 + third_party/curl/lib/vtls/wolfssl.h | 33 + third_party/curl/lib/vtls/x509asn1.c | 1232 + third_party/curl/lib/vtls/x509asn1.h | 80 + third_party/curl/lib/warnless.c | 386 + third_party/curl/lib/warnless.h | 92 + third_party/curl/lib/ws.c | 1271 + third_party/curl/lib/ws.h | 90 + third_party/curl/libcurl.def | 95 + third_party/curl/libcurl.pc.in | 41 + third_party/curl/ltmain.sh | 11448 ++++ third_party/curl/m4/curl-amissl.m4 | 69 + third_party/curl/m4/curl-bearssl.m4 | 110 + third_party/curl/m4/curl-compilers.m4 | 1631 + third_party/curl/m4/curl-confopts.m4 | 705 + third_party/curl/m4/curl-functions.m4 | 5012 ++ third_party/curl/m4/curl-gnutls.m4 | 168 + third_party/curl/m4/curl-mbedtls.m4 | 111 + third_party/curl/m4/curl-openssl.m4 | 446 + third_party/curl/m4/curl-override.m4 | 98 + third_party/curl/m4/curl-reentrant.m4 | 506 + third_party/curl/m4/curl-rustls.m4 | 189 + third_party/curl/m4/curl-schannel.m4 | 48 + third_party/curl/m4/curl-sectransp.m4 | 45 + third_party/curl/m4/curl-sysconfig.m4 | 54 + third_party/curl/m4/curl-wolfssl.m4 | 176 + third_party/curl/m4/libtool.m4 | 8427 +++ third_party/curl/m4/ltoptions.m4 | 437 + third_party/curl/m4/ltsugar.m4 | 124 + third_party/curl/m4/ltversion.m4 | 24 + third_party/curl/m4/lt~obsolete.m4 | 99 + third_party/curl/m4/xc-am-iface.m4 | 85 + third_party/curl/m4/xc-cc-check.m4 | 97 + third_party/curl/m4/xc-lt-iface.m4 | 466 + third_party/curl/m4/xc-translit.m4 | 165 + third_party/curl/m4/xc-val-flgs.m4 | 244 + third_party/curl/m4/zz40-xc-ovr.m4 | 667 + third_party/curl/m4/zz50-xc-ovr.m4 | 61 + third_party/curl/m4/zz60-xc-ovr.m4 | 65 + third_party/curl/maketgz | 235 + third_party/curl/missing | 215 + third_party/curl/packages/Makefile.am | 51 + third_party/curl/packages/Makefile.in | 796 + third_party/curl/packages/OS400/README.OS400 | 391 + third_party/curl/packages/OS400/ccsidcurl.c | 1529 + third_party/curl/packages/OS400/ccsidcurl.h | 113 + .../curl/packages/OS400/config400.default | 55 + third_party/curl/packages/OS400/curl.cmd | 32 + third_party/curl/packages/OS400/curl.inc.in | 3444 ++ third_party/curl/packages/OS400/curlcl.c | 177 + third_party/curl/packages/OS400/curlmain.c | 121 + third_party/curl/packages/OS400/initscript.sh | 292 + .../curl/packages/OS400/make-include.sh | 106 + third_party/curl/packages/OS400/make-lib.sh | 181 + third_party/curl/packages/OS400/make-src.sh | 101 + third_party/curl/packages/OS400/make-tests.sh | 151 + third_party/curl/packages/OS400/makefile.sh | 123 + third_party/curl/packages/OS400/os400sys.c | 1040 + third_party/curl/packages/OS400/os400sys.h | 57 + .../packages/OS400/rpg-examples/HEADERAPI | 146 + .../curl/packages/OS400/rpg-examples/HTTPPOST | 129 + .../curl/packages/OS400/rpg-examples/INMEMORY | 159 + .../curl/packages/OS400/rpg-examples/SIMPLE1 | 108 + .../curl/packages/OS400/rpg-examples/SIMPLE2 | 108 + .../packages/OS400/rpg-examples/SMTPSRCMBR | 239 + third_party/curl/packages/README.md | 12 + third_party/curl/packages/vms/Makefile.am | 59 + third_party/curl/packages/vms/Makefile.in | 628 + .../curl/packages/vms/backup_gnv_curl_src.com | 130 + .../packages/vms/build_curl-config_script.com | 153 + .../curl/packages/vms/build_gnv_curl.com | 36 + .../packages/vms/build_gnv_curl_pcsi_desc.com | 489 + .../packages/vms/build_gnv_curl_pcsi_text.com | 195 + .../vms/build_gnv_curl_release_notes.com | 100 + .../curl/packages/vms/build_libcurl_pc.com | 202 + third_party/curl/packages/vms/build_vms.com | 1038 + .../curl/packages/vms/clean_gnv_curl.com | 239 + .../curl/packages/vms/compare_curl_source.com | 363 + third_party/curl/packages/vms/config_h.com | 1972 + .../curl/packages/vms/curl_crtl_init.c | 333 + .../packages/vms/curl_gnv_build_steps.txt | 290 + .../packages/vms/curl_release_note_start.txt | 77 + .../curl/packages/vms/curl_startup.com | 98 + third_party/curl/packages/vms/curlmsg.h | 143 + third_party/curl/packages/vms/curlmsg.msg | 134 + third_party/curl/packages/vms/curlmsg.sdl | 116 + third_party/curl/packages/vms/curlmsg_vms.h | 143 + .../vms/generate_config_vms_h_curl.com | 450 + .../packages/vms/generate_vax_transfer.com | 273 + .../curl/packages/vms/gnv_conftest.c_first | 58 + .../curl/packages/vms/gnv_curl_configure.sh | 44 + .../curl/packages/vms/gnv_libcurl_symbols.opt | 181 + .../curl/packages/vms/gnv_link_curl.com | 851 + .../curl/packages/vms/macro32_exactcase.patch | 11 + .../packages/vms/make_gnv_curl_install.sh | 44 + .../packages/vms/make_pcsi_curl_kit_name.com | 188 + .../packages/vms/pcsi_gnv_curl_file_list.txt | 125 + .../packages/vms/pcsi_product_gnv_curl.com | 197 + third_party/curl/packages/vms/readme | 228 + .../packages/vms/report_openssl_version.c | 100 + .../packages/vms/setup_gnv_curl_build.com | 286 + .../curl/packages/vms/stage_curl_install.com | 170 + third_party/curl/packages/vms/vms_eco_level.h | 30 + third_party/curl/plan9/README | 55 + third_party/curl/plan9/include/mkfile | 36 + third_party/curl/plan9/lib/mkfile | 41 + third_party/curl/plan9/lib/mkfile.inc | 27 + third_party/curl/plan9/mkfile | 38 + third_party/curl/plan9/mkfile.proto | 32 + third_party/curl/plan9/src/mkfile | 47 + third_party/curl/plan9/src/mkfile.inc | 27 + third_party/curl/projects/README.md | 160 + third_party/curl/projects/build-openssl.bat | 739 + third_party/curl/projects/build-wolfssl.bat | 429 + third_party/curl/projects/checksrc.bat | 225 + third_party/curl/projects/generate.bat | 357 + third_party/curl/projects/wolfssl_options.h | 308 + .../curl/projects/wolfssl_override.props | 40 + third_party/curl/scripts/Makefile.am | 83 + third_party/curl/scripts/Makefile.in | 624 + third_party/curl/scripts/cd2cd | 226 + third_party/curl/scripts/cd2nroff | 526 + third_party/curl/scripts/cdall | 44 + third_party/curl/scripts/checksrc.pl | 990 + third_party/curl/scripts/completion.pl | 166 + third_party/curl/scripts/coverage.sh | 41 + third_party/curl/scripts/dmaketgz | 52 + third_party/curl/scripts/firefox-db2pem.sh | 58 + third_party/curl/scripts/managen | 1143 + third_party/curl/scripts/mk-ca-bundle.pl | 713 + third_party/curl/scripts/nroff2cd | 192 + third_party/curl/scripts/schemetable.c | 207 + third_party/curl/src/.checksrc | 1 + third_party/curl/src/CMakeLists.txt | 129 + third_party/curl/src/Makefile.am | 167 + third_party/curl/src/Makefile.in | 2081 + third_party/curl/src/Makefile.inc | 153 + third_party/curl/src/Makefile.mk | 90 + third_party/curl/src/curl.rc | 113 + third_party/curl/src/mkhelp.pl | 200 + third_party/curl/src/slist_wc.c | 74 + third_party/curl/src/slist_wc.h | 57 + third_party/curl/src/tool_binmode.c | 53 + third_party/curl/src/tool_binmode.h | 38 + third_party/curl/src/tool_bname.c | 51 + third_party/curl/src/tool_bname.h | 36 + third_party/curl/src/tool_cb_dbg.c | 300 + third_party/curl/src/tool_cb_dbg.h | 36 + third_party/curl/src/tool_cb_hdr.c | 462 + third_party/curl/src/tool_cb_hdr.h | 58 + third_party/curl/src/tool_cb_prg.c | 305 + third_party/curl/src/tool_cb_prg.h | 58 + third_party/curl/src/tool_cb_rea.c | 158 + third_party/curl/src/tool_cb_rea.h | 42 + third_party/curl/src/tool_cb_see.c | 92 + third_party/curl/src/tool_cb_see.h | 34 + third_party/curl/src/tool_cb_wrt.c | 372 + third_party/curl/src/tool_cb_wrt.h | 38 + third_party/curl/src/tool_cfgable.c | 204 + third_party/curl/src/tool_cfgable.h | 342 + third_party/curl/src/tool_dirhie.c | 167 + third_party/curl/src/tool_dirhie.h | 32 + third_party/curl/src/tool_doswin.c | 796 + third_party/curl/src/tool_doswin.h | 72 + third_party/curl/src/tool_easysrc.c | 238 + third_party/curl/src/tool_easysrc.h | 58 + third_party/curl/src/tool_filetime.c | 156 + third_party/curl/src/tool_filetime.h | 42 + third_party/curl/src/tool_findfile.c | 157 + third_party/curl/src/tool_findfile.h | 36 + third_party/curl/src/tool_formparse.c | 907 + third_party/curl/src/tool_formparse.h | 73 + third_party/curl/src/tool_getparam.c | 2912 + third_party/curl/src/tool_getparam.h | 74 + third_party/curl/src/tool_getpass.c | 207 + third_party/curl/src/tool_getpass.h | 38 + third_party/curl/src/tool_help.c | 245 + third_party/curl/src/tool_help.h | 75 + third_party/curl/src/tool_helpers.c | 135 + third_party/curl/src/tool_helpers.h | 36 + third_party/curl/src/tool_hugehelp.c | 10763 ++++ third_party/curl/src/tool_hugehelp.h | 35 + third_party/curl/src/tool_ipfs.c | 291 + third_party/curl/src/tool_ipfs.h | 33 + third_party/curl/src/tool_libinfo.c | 208 + third_party/curl/src/tool_libinfo.h | 67 + third_party/curl/src/tool_listhelp.c | 814 + third_party/curl/src/tool_main.c | 297 + third_party/curl/src/tool_main.h | 48 + third_party/curl/src/tool_msgs.c | 150 + third_party/curl/src/tool_msgs.h | 38 + third_party/curl/src/tool_operate.c | 2821 + third_party/curl/src/tool_operate.h | 86 + third_party/curl/src/tool_operhlp.c | 254 + third_party/curl/src/tool_operhlp.h | 42 + third_party/curl/src/tool_paramhlp.c | 746 + third_party/curl/src/tool_paramhlp.h | 63 + third_party/curl/src/tool_parsecfg.c | 353 + third_party/curl/src/tool_parsecfg.h | 30 + third_party/curl/src/tool_progress.c | 321 + third_party/curl/src/tool_progress.h | 41 + third_party/curl/src/tool_sdecls.h | 133 + third_party/curl/src/tool_setopt.c | 722 + third_party/curl/src/tool_setopt.h | 160 + third_party/curl/src/tool_setup.h | 90 + third_party/curl/src/tool_sleep.c | 61 + third_party/curl/src/tool_sleep.h | 30 + third_party/curl/src/tool_stderr.c | 71 + third_party/curl/src/tool_stderr.h | 32 + third_party/curl/src/tool_strdup.c | 44 + third_party/curl/src/tool_strdup.h | 32 + third_party/curl/src/tool_urlglob.c | 721 + third_party/curl/src/tool_urlglob.h | 78 + third_party/curl/src/tool_util.c | 190 + third_party/curl/src/tool_util.h | 42 + third_party/curl/src/tool_version.h | 36 + third_party/curl/src/tool_vms.c | 220 + third_party/curl/src/tool_vms.h | 48 + third_party/curl/src/tool_writeout.c | 676 + third_party/curl/src/tool_writeout.h | 114 + third_party/curl/src/tool_writeout_json.c | 173 + third_party/curl/src/tool_writeout_json.h | 37 + third_party/curl/src/tool_xattr.c | 136 + third_party/curl/src/tool_xattr.h | 45 + third_party/curl/src/var.c | 467 + third_party/curl/src/var.h | 47 + third_party/curl/winbuild/Makefile.vc | 320 + third_party/curl/winbuild/MakefileBuild.vc | 714 + third_party/curl/winbuild/README.md | 200 + third_party/curl/winbuild/gen_resp_file.bat | 34 + third_party/curl/winbuild/makedebug.cmd | 36 + third_party/date/.gitignore | 194 + third_party/date/.travis.yml | 147 + third_party/date/CMakeLists.txt | 277 + third_party/date/LICENSE.txt | 31 + third_party/date/README.md | 84 + third_party/date/ci/install_cmake.sh | 34 + third_party/date/cmake/dateConfig.cmake | 11 + third_party/date/compile_fail.sh | 16 + third_party/date/include/date/chrono_io.h | 34 + third_party/date/include/date/date.h | 8200 +++ third_party/date/include/date/ios.h | 50 + third_party/date/include/date/islamic.h | 3031 + third_party/date/include/date/iso_week.h | 1751 + third_party/date/include/date/julian.h | 3052 + third_party/date/include/date/ptz.h | 861 + third_party/date/include/date/solar_hijri.h | 3151 + third_party/date/include/date/tz.h | 2792 + third_party/date/include/date/tz_private.h | 316 + third_party/date/src/ios.mm | 337 + third_party/date/src/tz.cpp | 3944 ++ .../test/clock_cast_test/constexpr.pass.cpp | 75 + .../clock_cast_test/custom_clock.pass.cpp | 213 + .../test/clock_cast_test/deprecated.pass.cpp | 90 + .../test/clock_cast_test/local_t.pass.cpp | 132 + .../test/clock_cast_test/noncastable.pass.cpp | 251 + .../clock_cast_test/normal_clocks.pass.cpp | 102 + .../to_sys_return_int.fail.cpp | 49 + .../to_sys_return_reference.fail.cpp | 51 + .../to_sys_return_utc_time.fail.cpp | 49 + third_party/date/test/date_test/day.pass.cpp | 143 + .../date/test/date_test/daypday.fail.cpp | 32 + .../date/test/date_test/daysmday.fail.cpp | 32 + .../date/test/date_test/daysmweekday.fail.cpp | 32 + .../detail/decimal_format_seconds.pass.cpp | 141 + .../date_test/detail/static_pow10.pass.cpp | 50 + .../date/test/date_test/detail/width.pass.cpp | 64 + .../date/test/date_test/durations.pass.cpp | 62 + .../test/date_test/durations_output.pass.cpp | 328 + .../test/date_test/format/century.pass.cpp | 117 + .../date/test/date_test/format/misc.pass.cpp | 52 + .../date/test/date_test/format/range.pass.cpp | 78 + .../date_test/format/two_dight_year.pass.cpp | 121 + third_party/date/test/date_test/last.pass.cpp | 34 + .../date/test/date_test/make_time.pass.cpp | 81 + .../date/test/date_test/month.pass.cpp | 181 + .../date/test/date_test/month_day.pass.cpp | 82 + .../test/date_test/month_day_last.pass.cpp | 75 + .../test/date_test/month_weekday.pass.cpp | 77 + .../date_test/month_weekday_last.pass.cpp | 77 + .../month_weekday_last_less.fail.cpp | 34 + .../date_test/month_weekday_less.fail.cpp | 34 + .../date/test/date_test/monthpmonth.fail.cpp | 32 + .../date_test/months_m_year_month.fail.cpp | 33 + .../months_m_year_month_day.fail.cpp | 33 + .../date/test/date_test/monthsmmonth.fail.cpp | 32 + .../multi_year_duration_addition.pass.cpp | 487 + .../test/date_test/op_div_day_day.fail.cpp | 33 + .../test/date_test/op_div_int_month.fail.cpp | 33 + .../test/date_test/op_div_int_year.fail.cpp | 33 + .../test/date_test/op_div_last_last.fail.cpp | 33 + .../test/date_test/op_div_month_day.pass.cpp | 41 + .../date_test/op_div_month_day_last.pass.cpp | 39 + .../op_div_month_day_month_day.fail.cpp | 33 + .../date_test/op_div_month_month.fail.cpp | 33 + .../date_test/op_div_month_weekday.pass.cpp | 39 + .../op_div_month_weekday_last.pass.cpp | 39 + .../test/date_test/op_div_month_year.fail.cpp | 33 + .../test/date_test/op_div_survey.pass.cpp | 437 + ...v_weekday_indexed_weekday_indexed.fail.cpp | 33 + .../op_div_weekday_last_weekday_last.fail.cpp | 33 + .../test/date_test/op_div_year_month.pass.cpp | 35 + .../date_test/op_div_year_month_day.pass.cpp | 43 + .../op_div_year_month_day_last.pass.cpp | 41 + .../op_div_year_month_weekday.pass.cpp | 41 + .../op_div_year_month_weekday_last.pass.cpp | 41 + .../op_div_year_month_year_month.fail.cpp | 33 + .../test/date_test/op_div_year_year.fail.cpp | 33 + .../date/test/date_test/parse.pass.cpp | 921 + .../date/test/date_test/sizeof.pass.cpp | 62 + .../test/date_test/time_of_day_hours.pass.cpp | 94 + .../time_of_day_microfortnights.pass.cpp | 111 + .../time_of_day_milliseconds.pass.cpp | 104 + .../date_test/time_of_day_minutes.pass.cpp | 92 + .../time_of_day_nanoseconds.pass.cpp | 104 + .../date_test/time_of_day_seconds.pass.cpp | 96 + .../date/test/date_test/weekday.pass.cpp | 201 + .../test/date_test/weekday_indexed.pass.cpp | 70 + .../date/test/date_test/weekday_last.pass.cpp | 66 + .../test/date_test/weekday_lessthan.fail.cpp | 32 + .../date/test/date_test/weekday_sum.fail.cpp | 32 + third_party/date/test/date_test/year.pass.cpp | 146 + .../date/test/date_test/year_month.pass.cpp | 227 + .../test/date_test/year_month_day.pass.cpp | 244 + .../date_test/year_month_day_last.pass.cpp | 177 + .../year_month_day_m_year_month_day.fail.cpp | 33 + .../year_month_day_p_year_month_day.fail.cpp | 33 + .../year_month_p_year_month.fail.cpp | 33 + .../date_test/year_month_weekday.pass.cpp | 178 + .../year_month_weekday_last.pass.cpp | 169 + .../date/test/date_test/year_p_year.fail.cpp | 32 + .../date/test/date_test/years_m_year.fail.cpp | 32 + .../date_test/years_m_year_month.fail.cpp | 33 + .../date_test/years_m_year_month_day.fail.cpp | 33 + third_party/date/test/iso_week/last.pass.cpp | 34 + .../test/iso_week/lastweek_weekday.pass.cpp | 82 + .../date/test/iso_week/op_div_survey.pass.cpp | 196 + .../date/test/iso_week/weekday.pass.cpp | 227 + .../test/iso_week/weekday_lessthan.fail.cpp | 32 + .../date/test/iso_week/weekday_sum.fail.cpp | 32 + .../date/test/iso_week/weeknum.pass.cpp | 121 + .../test/iso_week/weeknum_p_weeknum.fail.cpp | 32 + .../test/iso_week/weeknum_weekday.pass.cpp | 86 + third_party/date/test/iso_week/year.pass.cpp | 120 + .../date/test/iso_week/year_lastweek.pass.cpp | 97 + .../iso_week/year_lastweek_weekday.pass.cpp | 129 + .../date/test/iso_week/year_p_year.fail.cpp | 32 + .../date/test/iso_week/year_weeknum.pass.cpp | 97 + .../iso_week/year_weeknum_weekday.pass.cpp | 139 + .../date/test/iso_week/years_m_year.fail.cpp | 32 + third_party/date/test/just.pass.cpp | 26 + third_party/date/test/posix/ptz.pass.cpp | 108 + .../date/test/solar_hijri_test/parse.pass.cpp | 237 + .../solar_hijri_test/year_month_day.pass.cpp | 168 + third_party/date/test/testit | 177 + third_party/date/test/tz_test/OffsetZone.h | 73 + .../date/test/tz_test/OffsetZone.pass.cpp | 38 + third_party/date/test/tz_test/README.md | 22 + .../date/test/tz_test/tzdata2015e.txt.zip | Bin 0 -> 124808 bytes .../date/test/tz_test/tzdata2015f.txt.zip | Bin 0 -> 125131 bytes .../date/test/tz_test/tzdata2016c.txt.zip | Bin 0 -> 127331 bytes .../date/test/tz_test/tzdata2016d.txt.zip | Bin 0 -> 128096 bytes .../date/test/tz_test/tzdata2016e.txt.zip | Bin 0 -> 128440 bytes .../date/test/tz_test/tzdata2016f.txt.zip | Bin 0 -> 128214 bytes .../date/test/tz_test/tzdb_list.pass.cpp | 36 + third_party/date/test/tz_test/validate.cpp | 165 + third_party/date/test/tz_test/zone.pass.cpp | 37 + .../date/test/tz_test/zoned_time.pass.cpp | 464 + .../tz_test/zoned_time_deduction.pass.cpp | 246 + third_party/date/test_fail.sh | 10 + third_party/fmt/.clang-format | 8 + third_party/fmt/CMakeLists.txt | 453 + third_party/fmt/CONTRIBUTING.md | 20 + third_party/fmt/ChangeLog.md | 5533 ++ third_party/fmt/LICENSE | 27 + third_party/fmt/README.md | 490 + third_party/fmt/include/fmt/args.h | 235 + third_party/fmt/include/fmt/chrono.h | 2240 + third_party/fmt/include/fmt/color.h | 643 + third_party/fmt/include/fmt/compile.h | 535 + third_party/fmt/include/fmt/core.h | 2969 + third_party/fmt/include/fmt/format-inl.h | 1678 + third_party/fmt/include/fmt/format.h | 4535 ++ third_party/fmt/include/fmt/os.h | 455 + third_party/fmt/include/fmt/ostream.h | 245 + third_party/fmt/include/fmt/printf.h | 675 + third_party/fmt/include/fmt/ranges.h | 738 + third_party/fmt/include/fmt/std.h | 537 + third_party/fmt/include/fmt/xchar.h | 259 + third_party/fmt/src/fmt.cc | 108 + third_party/fmt/src/format.cc | 43 + third_party/fmt/src/os.cc | 402 + third_party/fmt/support/Android.mk | 15 + third_party/fmt/support/AndroidManifest.xml | 1 + third_party/fmt/support/C++.sublime-syntax | 2061 + third_party/fmt/support/README | 4 + third_party/fmt/support/Vagrantfile | 20 + third_party/fmt/support/bazel/.bazelversion | 1 + third_party/fmt/support/bazel/BUILD.bazel | 28 + third_party/fmt/support/bazel/README.md | 74 + third_party/fmt/support/bazel/WORKSPACE.bazel | 1 + third_party/fmt/support/build-docs.py | 58 + third_party/fmt/support/build.gradle | 132 + .../fmt/support/cmake/FindSetEnv.cmake | 7 + third_party/fmt/support/cmake/JoinPaths.cmake | 26 + .../fmt/support/cmake/fmt-config.cmake.in | 7 + third_party/fmt/support/cmake/fmt.pc.in | 11 + third_party/fmt/support/compute-powers.py | 53 + third_party/fmt/support/docopt.py | 581 + third_party/fmt/support/manage.py | 329 + third_party/fmt/support/printable.py | 201 + third_party/fmt/support/rtd/conf.py | 7 + third_party/fmt/support/rtd/index.rst | 2 + third_party/fmt/support/rtd/theme/layout.html | 17 + third_party/fmt/support/rtd/theme/theme.conf | 2 + third_party/gflags/.gitattributes | 3 + third_party/gflags/.gitignore | 25 + third_party/gflags/.gitmodules | 4 + third_party/gflags/.travis.yml | 20 + third_party/gflags/AUTHORS.txt | 2 + third_party/gflags/BUILD | 18 + third_party/gflags/CMakeLists.txt | 796 + third_party/gflags/COPYING.txt | 28 + third_party/gflags/ChangeLog.txt | 276 + third_party/gflags/INSTALL.md | 83 + third_party/gflags/README.md | 320 + third_party/gflags/WORKSPACE | 6 + third_party/gflags/appveyor.yml | 68 + third_party/gflags/bazel/gflags.bzl | 103 + third_party/gflags/cmake/README_runtime.txt | 4 + .../gflags/cmake/cmake_uninstall.cmake.in | 26 + third_party/gflags/cmake/config.cmake.in | 183 + third_party/gflags/cmake/execute_test.cmake | 53 + third_party/gflags/cmake/package.cmake.in | 49 + third_party/gflags/cmake/package.pc.in | 14 + third_party/gflags/cmake/utils.cmake | 205 + third_party/gflags/cmake/version.cmake.in | 21 + third_party/gflags/src/config.h | 59 + third_party/gflags/src/defines.h.in | 48 + third_party/gflags/src/gflags.cc | 2029 + third_party/gflags/src/gflags.h.in | 626 + third_party/gflags/src/gflags_completions.cc | 772 + .../gflags/src/gflags_completions.h.in | 121 + third_party/gflags/src/gflags_completions.sh | 117 + third_party/gflags/src/gflags_declare.h.in | 156 + third_party/gflags/src/gflags_ns.h.in | 102 + third_party/gflags/src/gflags_reporting.cc | 442 + third_party/gflags/src/mutex.h | 348 + third_party/gflags/src/util.h | 373 + third_party/gflags/src/windows_port.cc | 73 + third_party/gflags/src/windows_port.h | 135 + third_party/gflags/test/CMakeLists.txt | 209 + third_party/gflags/test/config/CMakeLists.txt | 10 + third_party/gflags/test/config/main.cc | 20 + third_party/gflags/test/flagfile.1 | 1 + third_party/gflags/test/flagfile.2 | 2 + third_party/gflags/test/flagfile.3 | 1 + third_party/gflags/test/gflags_build.py.in | 43 + .../gflags/test/gflags_declare_flags.cc | 12 + .../gflags/test/gflags_declare_test.cc | 12 + .../gflags/test/gflags_strip_flags_test.cc | 60 + .../gflags/test/gflags_strip_flags_test.cmake | 7 + third_party/gflags/test/gflags_unittest.cc | 1572 + .../gflags/test/gflags_unittest_flagfile | 2 + third_party/gflags/test/nc/CMakeLists.txt | 16 + third_party/gflags/test/nc/gflags_nc.cc | 73 + third_party/glog/.bazelci/presubmit.yml | 58 + third_party/glog/.clang-format | 168 + third_party/glog/.clang-tidy | 59 + third_party/glog/.gitattributes | 1 + .../glog/.github/workflows/android.yml | 51 + third_party/glog/.github/workflows/linux.yml | 150 + third_party/glog/.github/workflows/macos.yml | 83 + .../glog/.github/workflows/windows.yml | 234 + third_party/glog/.gitignore | 3 + third_party/glog/AUTHORS | 29 + third_party/glog/BUILD.bazel | 22 + third_party/glog/CMakeLists.txt | 1139 + third_party/glog/CONTRIBUTORS | 52 + third_party/glog/COPYING | 65 + third_party/glog/ChangeLog | 109 + third_party/glog/README.rst | 879 + third_party/glog/WORKSPACE | 11 + third_party/glog/bazel/example/BUILD.bazel | 9 + third_party/glog/bazel/example/main.cc | 22 + third_party/glog/bazel/glog.bzl | 276 + .../glog/cmake/DetermineGflagsNamespace.cmake | 69 + third_party/glog/cmake/FindUnwind.cmake | 61 + .../glog/cmake/GetCacheVariables.cmake | 70 + third_party/glog/cmake/RunCleanerTest1.cmake | 22 + third_party/glog/cmake/RunCleanerTest2.cmake | 22 + third_party/glog/cmake/RunCleanerTest3.cmake | 28 + .../glog/cmake/TestInitPackageConfig.cmake | 11 + .../glog/cmake/TestPackageConfig.cmake | 40 + third_party/glog/glog-config.cmake.in | 13 + third_party/glog/glog-modules.cmake.in | 18 + third_party/glog/libglog.pc.in | 11 + third_party/glog/src/base/commandlineflags.h | 147 + third_party/glog/src/base/googleinit.h | 51 + third_party/glog/src/base/mutex.h | 333 + .../glog/src/cleanup_immediately_unittest.cc | 96 + .../cleanup_with_absolute_prefix_unittest.cc | 101 + .../cleanup_with_relative_prefix_unittest.cc | 97 + third_party/glog/src/config.h.cmake.in | 231 + third_party/glog/src/demangle.cc | 1364 + third_party/glog/src/demangle.h | 85 + third_party/glog/src/demangle_unittest.cc | 170 + third_party/glog/src/demangle_unittest.sh | 95 + third_party/glog/src/demangle_unittest.txt | 145 + third_party/glog/src/glog/log_severity.h | 98 + third_party/glog/src/glog/logging.h.in | 2002 + third_party/glog/src/glog/platform.h | 58 + third_party/glog/src/glog/raw_logging.h.in | 179 + third_party/glog/src/glog/stl_logging.h.in | 220 + third_party/glog/src/glog/vlog_is_on.h.in | 118 + third_party/glog/src/googletest.h | 672 + third_party/glog/src/logging.cc | 2691 + .../src/logging_custom_prefix_unittest.cc | 1384 + .../src/logging_custom_prefix_unittest.err | 308 + third_party/glog/src/logging_striplog_test.sh | 79 + third_party/glog/src/logging_striptest10.cc | 35 + third_party/glog/src/logging_striptest2.cc | 35 + .../glog/src/logging_striptest_main.cc | 73 + third_party/glog/src/logging_unittest.cc | 1477 + third_party/glog/src/logging_unittest.err | 308 + third_party/glog/src/logging_unittest.out | 150 + third_party/glog/src/mock-log.h | 156 + third_party/glog/src/mock-log_unittest.cc | 108 + .../working_config/CMakeLists.txt | 8 + .../working_config/glog_package_config.cc | 6 + third_party/glog/src/raw_logging.cc | 178 + third_party/glog/src/signalhandler.cc | 409 + .../glog/src/signalhandler_unittest.cc | 113 + .../glog/src/signalhandler_unittest.sh | 131 + third_party/glog/src/stacktrace.h | 61 + third_party/glog/src/stacktrace_generic-inl.h | 62 + .../glog/src/stacktrace_libunwind-inl.h | 93 + third_party/glog/src/stacktrace_powerpc-inl.h | 130 + third_party/glog/src/stacktrace_unittest.cc | 239 + third_party/glog/src/stacktrace_unwind-inl.h | 106 + third_party/glog/src/stacktrace_windows-inl.h | 50 + third_party/glog/src/stacktrace_x86-inl.h | 147 + third_party/glog/src/stl_logging_unittest.cc | 207 + third_party/glog/src/symbolize.cc | 955 + third_party/glog/src/symbolize.h | 159 + third_party/glog/src/symbolize_unittest.cc | 447 + third_party/glog/src/utilities.cc | 402 + third_party/glog/src/utilities.h | 217 + third_party/glog/src/utilities_unittest.cc | 58 + third_party/glog/src/vlog_is_on.cc | 293 + third_party/glog/src/windows/dirent.h | 1159 + third_party/glog/src/windows/port.cc | 71 + third_party/glog/src/windows/port.h | 181 + third_party/googletest/.clang-format | 4 + third_party/googletest/.gitignore | 84 + third_party/googletest/BUILD.bazel | 218 + third_party/googletest/CMakeLists.txt | 34 + third_party/googletest/CONTRIBUTING.md | 131 + third_party/googletest/CONTRIBUTORS | 65 + third_party/googletest/LICENSE | 28 + third_party/googletest/README.md | 141 + third_party/googletest/WORKSPACE | 39 + third_party/googletest/docs/_config.yml | 1 + .../googletest/docs/_data/navigation.yml | 43 + .../googletest/docs/_layouts/default.html | 58 + third_party/googletest/docs/_sass/main.scss | 200 + third_party/googletest/docs/advanced.md | 2398 + .../googletest/docs/assets/css/style.scss | 5 + .../docs/community_created_documentation.md | 7 + third_party/googletest/docs/faq.md | 692 + .../googletest/docs/gmock_cheat_sheet.md | 241 + .../googletest/docs/gmock_cook_book.md | 4342 ++ third_party/googletest/docs/gmock_faq.md | 390 + .../googletest/docs/gmock_for_dummies.md | 700 + third_party/googletest/docs/index.md | 22 + third_party/googletest/docs/pkgconfig.md | 148 + third_party/googletest/docs/platforms.md | 35 + third_party/googletest/docs/primer.md | 482 + .../googletest/docs/quickstart-bazel.md | 147 + .../googletest/docs/quickstart-cmake.md | 156 + .../googletest/docs/reference/actions.md | 115 + .../googletest/docs/reference/assertions.md | 633 + .../googletest/docs/reference/matchers.md | 290 + .../googletest/docs/reference/mocking.md | 589 + .../googletest/docs/reference/testing.md | 1431 + third_party/googletest/docs/samples.md | 22 + .../googletest/googlemock/CMakeLists.txt | 218 + third_party/googletest/googlemock/README.md | 40 + .../googletest/googlemock/cmake/gmock.pc.in | 10 + .../googlemock/cmake/gmock_main.pc.in | 10 + .../googletest/googlemock/docs/README.md | 4 + .../googlemock/include/gmock/gmock-actions.h | 2298 + .../include/gmock/gmock-cardinalities.h | 159 + .../include/gmock/gmock-function-mocker.h | 514 + .../googlemock/include/gmock/gmock-matchers.h | 5610 ++ .../include/gmock/gmock-more-actions.h | 662 + .../include/gmock/gmock-more-matchers.h | 91 + .../include/gmock/gmock-nice-strict.h | 277 + .../include/gmock/gmock-spec-builders.h | 2083 + .../googlemock/include/gmock/gmock.h | 96 + .../include/gmock/internal/custom/README.md | 18 + .../internal/custom/gmock-generated-actions.h | 7 + .../gmock/internal/custom/gmock-matchers.h | 37 + .../gmock/internal/custom/gmock-port.h | 40 + .../gmock/internal/gmock-internal-utils.h | 476 + .../include/gmock/internal/gmock-port.h | 139 + .../include/gmock/internal/gmock-pp.h | 279 + .../googletest/googlemock/src/gmock-all.cc | 46 + .../googlemock/src/gmock-cardinalities.cc | 155 + .../googlemock/src/gmock-internal-utils.cc | 250 + .../googlemock/src/gmock-matchers.cc | 462 + .../googlemock/src/gmock-spec-builders.cc | 781 + .../googletest/googlemock/src/gmock.cc | 223 + .../googletest/googlemock/src/gmock_main.cc | 72 + .../googletest/googletest/CMakeLists.txt | 325 + third_party/googletest/googletest/README.md | 217 + .../googletest/cmake/Config.cmake.in | 9 + .../googletest/googletest/cmake/gtest.pc.in | 9 + .../googletest/cmake/gtest_main.pc.in | 10 + .../googletest/cmake/internal_utils.cmake | 342 + .../googletest/cmake/libgtest.la.in | 21 + .../googletest/googletest/docs/README.md | 4 + .../include/gtest/gtest-assertion-result.h | 237 + .../include/gtest/gtest-death-test.h | 345 + .../googletest/include/gtest/gtest-matchers.h | 956 + .../googletest/include/gtest/gtest-message.h | 218 + .../include/gtest/gtest-param-test.h | 510 + .../googletest/include/gtest/gtest-printers.h | 1048 + .../googletest/include/gtest/gtest-spi.h | 248 + .../include/gtest/gtest-test-part.h | 190 + .../include/gtest/gtest-typed-test.h | 331 + .../googletest/include/gtest/gtest.h | 2297 + .../include/gtest/gtest_pred_impl.h | 279 + .../googletest/include/gtest/gtest_prod.h | 60 + .../include/gtest/internal/custom/README.md | 44 + .../gtest/internal/custom/gtest-port.h | 37 + .../gtest/internal/custom/gtest-printers.h | 42 + .../include/gtest/internal/custom/gtest.h | 37 + .../internal/gtest-death-test-internal.h | 306 + .../include/gtest/internal/gtest-filepath.h | 210 + .../include/gtest/internal/gtest-internal.h | 1570 + .../include/gtest/internal/gtest-param-util.h | 956 + .../include/gtest/internal/gtest-port-arch.h | 116 + .../include/gtest/internal/gtest-port.h | 2413 + .../include/gtest/internal/gtest-string.h | 177 + .../include/gtest/internal/gtest-type-util.h | 186 + .../googletest/samples/prime_tables.h | 124 + .../googletest/googletest/samples/sample1.cc | 66 + .../googletest/googletest/samples/sample1.h | 41 + .../googletest/samples/sample10_unittest.cc | 139 + .../googletest/samples/sample1_unittest.cc | 148 + .../googletest/googletest/samples/sample2.cc | 54 + .../googletest/googletest/samples/sample2.h | 79 + .../googletest/samples/sample2_unittest.cc | 107 + .../googletest/samples/sample3-inl.h | 171 + .../googletest/samples/sample3_unittest.cc | 146 + .../googletest/googletest/samples/sample4.cc | 50 + .../googletest/googletest/samples/sample4.h | 53 + .../googletest/samples/sample4_unittest.cc | 53 + .../googletest/samples/sample5_unittest.cc | 189 + .../googletest/samples/sample6_unittest.cc | 214 + .../googletest/samples/sample7_unittest.cc | 113 + .../googletest/samples/sample8_unittest.cc | 152 + .../googletest/samples/sample9_unittest.cc | 149 + .../googletest/googletest/src/gtest-all.cc | 49 + .../googletest/src/gtest-assertion-result.cc | 77 + .../googletest/src/gtest-death-test.cc | 1620 + .../googletest/src/gtest-filepath.cc | 367 + .../googletest/src/gtest-internal-inl.h | 1212 + .../googletest/src/gtest-matchers.cc | 98 + .../googletest/googletest/src/gtest-port.cc | 1394 + .../googletest/src/gtest-printers.cc | 553 + .../googletest/src/gtest-test-part.cc | 105 + .../googletest/src/gtest-typed-test.cc | 104 + .../googletest/googletest/src/gtest.cc | 6795 +++ .../googletest/googletest/src/gtest_main.cc | 53 + third_party/inja/inja/inja.h | 3128 + third_party/inja/inja/string_view.h | 1713 + third_party/json/json.h | 7 + third_party/json/nlohmann/json.hpp | 24765 ++++++++ third_party/openssl-cmake/CMakeLists.txt | 103 + third_party/openssl-cmake/LICENSE | 21 + third_party/openssl-cmake/README.md | 43 + .../openssl-cmake/cmake/BuildOpenSSL.cmake | 259 + .../cmake/ByproductsOpenSSL.cmake | 63 + .../openssl-cmake/cmake/PatchOpenSSL.cmake | 59 + .../openssl-cmake/cmake/PrebuiltOpenSSL.cmake | 66 + .../openssl-cmake/cmake/TargetArch.cmake | 165 + .../openssl-cmake/openssl-1.1.1u.tar.gz | Bin 0 -> 4565778 bytes third_party/openssl-cmake/patches/.gitkeep | 0 ...failing-cms-test-when-no-des-is-used.patch | 36 + ...Fix-test_cms-if-DSA-is-not-supported.patch | 36 + .../openssl-cmake/scripts/building_env.py | 101 + .../openssl-cmake/scripts/update_version.sh | 4 + .../openssl-cmake/scripts/upload_result.sh | 45 + third_party/zlib/CMakeLists.txt | 8 + third_party/zlib/zlib/LICENSE | 22 + third_party/zlib/zlib/adler32.c | 164 + third_party/zlib/zlib/crc32.c | 1049 + third_party/zlib/zlib/crc32.h | 9446 +++ third_party/zlib/zlib/deflate.c | 2140 + third_party/zlib/zlib/deflate.h | 377 + third_party/zlib/zlib/gzclose.c | 23 + third_party/zlib/zlib/gzguts.h | 217 + third_party/zlib/zlib/gzlib.c | 585 + third_party/zlib/zlib/gzread.c | 604 + third_party/zlib/zlib/gzwrite.c | 632 + third_party/zlib/zlib/infback.c | 628 + third_party/zlib/zlib/inffast.c | 320 + third_party/zlib/zlib/inffast.h | 11 + third_party/zlib/zlib/inffixed.h | 94 + third_party/zlib/zlib/inflate.c | 1526 + third_party/zlib/zlib/inflate.h | 126 + third_party/zlib/zlib/inftrees.c | 299 + third_party/zlib/zlib/inftrees.h | 62 + third_party/zlib/zlib/trees.c | 1117 + third_party/zlib/zlib/trees.h | 128 + third_party/zlib/zlib/zconf.h | 541 + third_party/zlib/zlib/zlib.h | 1903 + third_party/zlib/zlib/zutil.c | 299 + third_party/zlib/zlib/zutil.h | 253 + tile/base/align.h | 67 + tile/base/buffer.cc | 225 + tile/base/buffer.h | 368 + tile/base/buffer/builtin_buffer_block.cc | 122 + tile/base/buffer/builtin_buffer_block.h | 41 + tile/base/buffer/circular_buffer.h | 67 + tile/base/buffer/compression_output_stream.cc | 43 + tile/base/buffer/compression_output_stream.h | 27 + tile/base/buffer/polymorphic_buffer.cc | 21 + tile/base/buffer/polymorphic_buffer.h | 120 + tile/base/buffer_test.cc | 311 + tile/base/casting.h | 167 + tile/base/casting_benchmark.cc | 70 + tile/base/casting_test.cc | 103 + tile/base/chrono.cc | 145 + tile/base/chrono.h | 54 + tile/base/chrono_benchmark.cc | 70 + tile/base/chrono_test.cc | 44 + tile/base/compression.cc | 92 + tile/base/compression.h | 36 + tile/base/compression/compression.cc | 28 + tile/base/compression/compression.h | 65 + tile/base/compression/gzip.cc | 243 + tile/base/compression/gzip.h | 52 + tile/base/compression/util.cc | 37 + tile/base/compression/util.h | 15 + tile/base/compression/util_test.cc | 22 + tile/base/compression_test.cc | 72 + tile/base/config.h.in | 26 + tile/base/data.h | 7 + tile/base/data/json.h | 37 + tile/base/deferred.h | 64 + tile/base/deferred_test.cc | 50 + tile/base/demangle.cc | 30 + tile/base/demangle.h | 33 + tile/base/demangle_test.cc | 18 + tile/base/dependency_registry.h | 206 + tile/base/dependency_registry_test.cc | 77 + tile/base/down_cast.h | 25 + tile/base/down_cast_test.cc | 24 + tile/base/encoding.h | 10 + tile/base/encoding/base64.cc | 155 + tile/base/encoding/base64.h | 18 + tile/base/encoding/base64_test.cc | 78 + tile/base/encoding/detail/base64_decode.inc | 85 + tile/base/encoding/detail/base64_encode.inc | 120 + tile/base/encoding/detail/base64_impl.h | 288 + tile/base/encoding/detail/hex_chars.cc | 85 + tile/base/encoding/detail/hex_chars.h | 32 + tile/base/encoding/hex.cc | 53 + tile/base/encoding/hex.h | 16 + tile/base/encoding/hex_test.cc | 29 + tile/base/encoding/percent.cc | 118 + tile/base/encoding/percent.h | 40 + tile/base/encoding/percent_test.cc | 108 + tile/base/encoding_benchmark.cc | 89 + tile/base/enum.h | 40 + tile/base/erased_ptr.h | 69 + tile/base/expected.h | 3067 + tile/base/exposed_var.h | 16 + tile/base/future.h | 27 + tile/base/future/basic.h | 106 + tile/base/future/boxed.h | 171 + tile/base/future/boxed_test.cc | 66 + tile/base/future/core.h | 99 + tile/base/future/executor.h | 105 + tile/base/future/future-impl.h | 131 + tile/base/future/future.h | 84 + tile/base/future/future_test.cc | 313 + tile/base/future/impls.h | 66 + tile/base/future/promise-impl.h | 41 + tile/base/future/promise.h | 47 + tile/base/future/split.h | 64 + tile/base/future/types.h | 76 + tile/base/future/utils.h | 155 + tile/base/future/when_all.h | 194 + tile/base/future/when_any.h | 71 + tile/base/handle.h | 93 + tile/base/handle_test.cc | 31 + tile/base/id_alloc.h | 85 + tile/base/internal/background_task_host.cc | 59 + tile/base/internal/background_task_host.h | 34 + .../internal/background_task_host_test.cc | 27 + .../base/internal/case_insensitive_hash_map.h | 42 + .../case_insensitive_hash_map_test.cc | 25 + tile/base/internal/curl.cc | 153 + tile/base/internal/curl.h | 34 + tile/base/internal/curl_test.cc | 108 + tile/base/internal/early_init.h | 26 + tile/base/internal/format.h | 83 + tile/base/internal/format_test.cc | 43 + tile/base/internal/index_alloc.cc | 23 + tile/base/internal/index_alloc.h | 36 + tile/base/internal/lazy_init.h | 22 + tile/base/internal/logging.cc | 187 + tile/base/internal/logging.h | 647 + tile/base/internal/logging_test.cc | 95 + tile/base/internal/macro.h | 48 + tile/base/internal/macro_inl.h | 137 + tile/base/internal/meta.h | 158 + tile/base/internal/meta/apply.h | 97 + tile/base/internal/meta/base.h | 20 + tile/base/internal/meta/index_sequence.h | 41 + tile/base/internal/meta/invoke.h | 420 + tile/base/internal/meta_test.cc | 65 + tile/base/internal/move_on_copy.h | 66 + tile/base/internal/move_on_copy_test.cc | 63 + tile/base/internal/mutex.h | 209 + tile/base/internal/optional.h | 2077 + tile/base/internal/singly_linked_list.h | 297 + tile/base/internal/singly_linked_list_test.cc | 158 + tile/base/internal/test_prod.h | 11 + tile/base/internal/thread_pool.cc | 67 + tile/base/internal/thread_pool.h | 38 + tile/base/internal/thread_pool_test.cc | 31 + tile/base/internal/time_keeper.cc | 144 + tile/base/internal/time_keeper.h | 92 + tile/base/internal/time_keeper_benchmark.cc | 57 + tile/base/internal/time_keeper_test.cc | 56 + tile/base/internal/utility.h | 25 + tile/base/internal/variant.h | 2813 + tile/base/likely.h | 14 + tile/base/logging.h | 107 + tile/base/make_unique.h | 39 + tile/base/maybe_owning.h | 145 + tile/base/maybe_owning_test.cc | 182 + tile/base/net/detail/android/ifaddrs.c | 549 + tile/base/net/detail/android/ifaddrs.h | 13 + tile/base/net/endpoint.cc | 427 + tile/base/net/endpoint.h | 173 + tile/base/net/endpoint_test.cc | 195 + tile/base/net/uri.cc | 0 tile/base/net/uri.h | 59 + tile/base/never_destroyed.h | 68 + tile/base/object_pool.cc | 3 + tile/base/object_pool.h | 210 + tile/base/object_pool/disabled.cc | 19 + tile/base/object_pool/disabled.h | 19 + tile/base/object_pool/disabled_test.cc | 35 + tile/base/object_pool/global.cc | 21 + tile/base/object_pool/global.h | 20 + tile/base/object_pool/thread_local.cc | 100 + tile/base/object_pool/thread_local.h | 62 + tile/base/object_pool/thread_local_test.cc | 102 + tile/base/object_pool/types.h | 217 + tile/base/object_pool/types_test.cc | 102 + tile/base/option.cc | 23 + tile/base/option.h | 174 + tile/base/option/dynamically_changed.h | 35 + tile/base/option/gflags_provider.cc | 56 + tile/base/option/json_parser.cc | 19 + tile/base/option/json_parser.h | 21 + tile/base/option/json_parser_test.cc | 13 + tile/base/option/key.cc | 76 + tile/base/option/key.h | 157 + tile/base/option/key_test.cc | 42 + tile/base/option/option_impl.h | 101 + tile/base/option/option_provider.cc | 6 + tile/base/option/option_provider.h | 63 + tile/base/option/option_service.cc | 209 + tile/base/option/option_service.h | 116 + tile/base/option/option_service_test.cc | 34 + tile/base/optional.h | 14 + tile/base/random.h | 44 + tile/base/ref_ptr.h | 359 + tile/base/ref_ptr_test.cc | 256 + tile/base/slice.cc | 17 + tile/base/slice.h | 209 + tile/base/status.cc | 31 + tile/base/status.h | 44 + tile/base/status_test.cc | 37 + tile/base/string.cc | 346 + tile/base/string.h | 98 + tile/base/string_test.cc | 303 + tile/base/thread/cond_var.cc | 56 + tile/base/thread/cond_var.h | 126 + tile/base/thread/cond_var_test.cc | 109 + tile/base/thread/event.h | 65 + tile/base/thread/latch.cc | 36 + tile/base/thread/latch.h | 42 + tile/base/thread/latch_test.cc | 72 + tile/base/thread/mutex.cc | 46 + tile/base/thread/mutex.h | 52 + tile/base/thread/mutex_benchmark.cc | 55 + tile/base/thread/rw_mutex.cc | 136 + tile/base/thread/rw_mutex.h | 70 + tile/base/thread/scoped_lock.cc | 106 + tile/base/thread/scoped_lock.h | 126 + tile/base/thread/scoped_lock_test.cc | 353 + tile/base/thread/spinlock.cc | 33 + tile/base/thread/spinlock.h | 34 + tile/base/thread/spinlock_test.cc | 37 + tile/base/thread/unique_lock.h | 57 + tile/base/thread/unique_lock_test.cc | 61 + tile/base/type_index.h | 60 + tile/base/variant.h | 15 + tile/fiber/detail/asm/ucontext_aarch64.S | 152 + tile/fiber/detail/asm/ucontext_aarch64.h | 141 + tile/fiber/detail/asm/ucontext_arm.S | 75 + tile/fiber/detail/asm/ucontext_arm.h | 110 + tile/fiber/detail/asm/ucontext_mips32.S | 97 + tile/fiber/detail/asm/ucontext_mips32.h | 131 + tile/fiber/detail/asm/ucontext_mips64.S | 95 + tile/fiber/detail/asm/ucontext_mips64.h | 131 + tile/fiber/detail/asm/ucontext_riscv64.S | 100 + tile/fiber/detail/asm/ucontext_riscv64.h | 141 + tile/fiber/detail/asm/ucontext_x64.S | 65 + tile/fiber/detail/asm/ucontext_x64.h | 83 + tile/fiber/detail/asm/ucontext_x86.S | 43 + tile/fiber/detail/asm/ucontext_x86.h | 46 + tile/fiber/detail/mutex.cc | 50 + tile/fiber/detail/mutex.h | 31 + tile/fiber/detail/os_fiber.cc | 79 + tile/fiber/detail/os_fiber.h | 62 + tile/fiber/detail/posix_os_fiber.cc | 102 + tile/fiber/detail/posix_os_fiber.h | 31 + tile/fiber/detail/posix_os_fiber_test.cc | 91 + tile/fiber/detail/scheduler.cc | 48 + tile/fiber/detail/scheduler.h | 42 + tile/fiber/detail/ucontext.c | 65 + tile/fiber/detail/ucontext.h | 43 + tile/fiber/fiber.cc | 54 + tile/fiber/fiber.h | 75 + tile/fiber/mutex.cc | 49 + tile/fiber/scheduler.cc | 22 + tile/fiber/scheduler.h | 39 + tile/fiber/this_fiber.h | 35 + tile/fiber/ucontext_test.cc | 54 + tile/init.cc | 111 + tile/init.h | 20 + tile/init/on_init.cc | 111 + tile/init/on_init.h | 48 + tile/init/on_init_test.cc | 17 + tile/init/override_flag.cc | 45 + tile/init/override_flag.h | 41 + tile/init/override_flag_test.cc | 14 + tile/io/acceptor.h | 18 + tile/io/descriptor.cc | 296 + tile/io/descriptor.h | 108 + tile/io/detail/eintr_safe.cc | 36 + tile/io/detail/eintr_safe.h | 68 + tile/io/event_loop.cc | 30 + tile/io/event_loop.h | 52 + tile/io/native/acceptor.cc | 58 + tile/io/native/acceptor.h | 31 + tile/net/http/http_client.cc | 549 + tile/net/http/http_client.h | 154 + tile/net/http/http_client_test.cc | 67 + tile/net/http/http_headers.cc | 137 + tile/net/http/http_headers.h | 97 + tile/net/http/http_headers_test.cc | 74 + tile/net/http/http_message.cc | 14 + tile/net/http/http_message.h | 74 + tile/net/http/http_reqeust_test.cc | 110 + tile/net/http/http_request.cc | 23 + tile/net/http/http_request.h | 38 + tile/net/http/http_response.cc | 150 + tile/net/http/http_response.h | 41 + tile/net/http/http_response_test.cc | 83 + tile/net/http/packet_desc.cc | 0 tile/net/http/packet_desc.h | 13 + tile/net/http/types.cc | 168 + tile/net/http/types.h | 96 + tile/net/internal/http_engine.cc | 380 + tile/net/internal/http_engine.h | 32 + tile/net/internal/http_engine_test.cc | 98 + tile/net/internal/http_task.cc | 227 + tile/net/internal/http_task.h | 92 + tile/net/internal/http_task_test.cc | 31 + tile/rpc/http_handler.h | 0 tile/rpc/protocol/http/buffer_io.cc | 295 + tile/rpc/protocol/http/buffer_io.h | 46 + tile/rpc/protocol/http/buffer_io_test.cc | 247 + tile/rpc/protocol/message.cc | 19 + tile/rpc/protocol/message.h | 44 + tile/rpc/server.cc | 43 + tile/rpc/server.h | 159 + tile/sigslot/signal.h | 71 + tile/testing/bm_main.cc | 37 + tile/testing/bm_main.h | 18 + tile/testing/internal/random_string.cc | 9 + tile/testing/internal/random_string.h | 62 + tile/testing/main.cc | 24 + tile/testing/main.h | 19 + tile/tile.h | 22 + toolchains/aarch64-linux-gnu.toolchain.cmake | 29 + toolchains/arm-linux-gnueabi.toolchain.cmake | 27 + .../arm-linux-gnueabihf.toolchain.cmake | 25 + toolchains/host.gcc-m32.toolchain.cmake | 16 + toolchains/mips-linux-gnu.toolchain.cmake | 25 + .../mips64el-linux-gnuabi64.toolchain.cmake | 30 + toolchains/riscv64-linux-gnu.toolchain.cmake | 29 + 1552 files changed, 616123 insertions(+) create mode 100644 .cmake.conf create mode 100644 .gitea/workflows/android.yml create mode 100644 .gitea/workflows/linux-aarch64-gcc.yml create mode 100644 .gitea/workflows/linux-arm-gcc.yml create mode 100644 .gitea/workflows/linux-mips-gcc.yml create mode 100644 .gitea/workflows/linux-mips64-gcc.yml create mode 100644 .gitea/workflows/linux-riscv64-gcc.yml create mode 100644 .gitea/workflows/linux-x64-clang.yml create mode 100644 .gitea/workflows/linux-x64-gcc.yml create mode 100644 .gitea/workflows/linux-x86-gcc.yml create mode 100644 .gitignore create mode 100644 .gitmodules create mode 100644 CMakeLists.txt create mode 100644 cmake/BuildInfo.cmake create mode 100644 dir.bloaty create mode 100644 third_party/benchmark/.clang-format create mode 100644 third_party/benchmark/.clang-tidy create mode 100644 third_party/benchmark/.github/ISSUE_TEMPLATE/bug_report.md create mode 100644 third_party/benchmark/.github/ISSUE_TEMPLATE/feature_request.md create mode 100644 third_party/benchmark/.github/install_bazel.sh create mode 100755 third_party/benchmark/.github/libcxx-setup.sh create mode 100644 third_party/benchmark/.github/workflows/bazel.yml create mode 100644 third_party/benchmark/.github/workflows/build-and-test-min-cmake.yml create mode 100644 third_party/benchmark/.github/workflows/build-and-test-perfcounters.yml create mode 100644 third_party/benchmark/.github/workflows/build-and-test.yml create mode 100644 third_party/benchmark/.github/workflows/clang-format-lint.yml create mode 100644 third_party/benchmark/.github/workflows/clang-tidy.yml create mode 100644 third_party/benchmark/.github/workflows/doxygen.yml create mode 100644 third_party/benchmark/.github/workflows/pre-commit.yml create mode 100644 third_party/benchmark/.github/workflows/sanitizer.yml create mode 100644 third_party/benchmark/.github/workflows/test_bindings.yml create mode 100644 third_party/benchmark/.github/workflows/wheels.yml create mode 100644 third_party/benchmark/.gitignore create mode 100644 third_party/benchmark/.pre-commit-config.yaml create mode 100644 third_party/benchmark/.travis.yml create mode 100644 third_party/benchmark/.ycm_extra_conf.py create mode 100644 third_party/benchmark/AUTHORS create mode 100644 third_party/benchmark/BUILD.bazel create mode 100644 third_party/benchmark/CMakeLists.txt create mode 100644 third_party/benchmark/CONTRIBUTING.md create mode 100644 third_party/benchmark/CONTRIBUTORS create mode 100644 third_party/benchmark/LICENSE create mode 100644 third_party/benchmark/MODULE.bazel create mode 100644 third_party/benchmark/README.md create mode 100644 third_party/benchmark/WORKSPACE create mode 100644 third_party/benchmark/WORKSPACE.bzlmod create mode 100644 third_party/benchmark/_config.yml create mode 100644 third_party/benchmark/appveyor.yml create mode 100644 third_party/benchmark/bazel/benchmark_deps.bzl create mode 100644 third_party/benchmark/bindings/python/google_benchmark/BUILD create mode 100644 third_party/benchmark/bindings/python/google_benchmark/__init__.py create mode 100644 third_party/benchmark/bindings/python/google_benchmark/benchmark.cc create mode 100644 third_party/benchmark/bindings/python/google_benchmark/example.py create mode 100644 third_party/benchmark/bindings/python/google_benchmark/version.py create mode 100644 third_party/benchmark/cmake/AddCXXCompilerFlag.cmake create mode 100644 third_party/benchmark/cmake/CXXFeatureCheck.cmake create mode 100644 third_party/benchmark/cmake/Config.cmake.in create mode 100644 third_party/benchmark/cmake/GetGitVersion.cmake create mode 100644 third_party/benchmark/cmake/GoogleTest.cmake create mode 100644 third_party/benchmark/cmake/GoogleTest.cmake.in create mode 100644 third_party/benchmark/cmake/benchmark.pc.in create mode 100644 third_party/benchmark/cmake/benchmark_main.pc.in create mode 100644 third_party/benchmark/cmake/gnu_posix_regex.cpp create mode 100644 third_party/benchmark/cmake/llvm-toolchain.cmake create mode 100644 third_party/benchmark/cmake/posix_regex.cpp create mode 100644 third_party/benchmark/cmake/pthread_affinity.cpp create mode 100644 third_party/benchmark/cmake/split_list.cmake create mode 100644 third_party/benchmark/cmake/std_regex.cpp create mode 100644 third_party/benchmark/cmake/steady_clock.cpp create mode 100644 third_party/benchmark/cmake/thread_safety_attributes.cpp create mode 100644 third_party/benchmark/include/benchmark/benchmark.h create mode 100644 third_party/benchmark/include/benchmark/export.h create mode 100644 third_party/benchmark/pyproject.toml create mode 100644 third_party/benchmark/setup.py create mode 100644 third_party/benchmark/src/CMakeLists.txt create mode 100644 third_party/benchmark/src/arraysize.h create mode 100644 third_party/benchmark/src/benchmark.cc create mode 100644 third_party/benchmark/src/benchmark_api_internal.cc create mode 100644 third_party/benchmark/src/benchmark_api_internal.h create mode 100644 third_party/benchmark/src/benchmark_main.cc create mode 100644 third_party/benchmark/src/benchmark_name.cc create mode 100644 third_party/benchmark/src/benchmark_register.cc create mode 100644 third_party/benchmark/src/benchmark_register.h create mode 100644 third_party/benchmark/src/benchmark_runner.cc create mode 100644 third_party/benchmark/src/benchmark_runner.h create mode 100644 third_party/benchmark/src/check.cc create mode 100644 third_party/benchmark/src/check.h create mode 100644 third_party/benchmark/src/colorprint.cc create mode 100644 third_party/benchmark/src/colorprint.h create mode 100644 third_party/benchmark/src/commandlineflags.cc create mode 100644 third_party/benchmark/src/commandlineflags.h create mode 100644 third_party/benchmark/src/complexity.cc create mode 100644 third_party/benchmark/src/complexity.h create mode 100644 third_party/benchmark/src/console_reporter.cc create mode 100644 third_party/benchmark/src/counter.cc create mode 100644 third_party/benchmark/src/counter.h create mode 100644 third_party/benchmark/src/csv_reporter.cc create mode 100644 third_party/benchmark/src/cycleclock.h create mode 100644 third_party/benchmark/src/internal_macros.h create mode 100644 third_party/benchmark/src/json_reporter.cc create mode 100644 third_party/benchmark/src/log.h create mode 100644 third_party/benchmark/src/mutex.h create mode 100644 third_party/benchmark/src/perf_counters.cc create mode 100644 third_party/benchmark/src/perf_counters.h create mode 100644 third_party/benchmark/src/re.h create mode 100644 third_party/benchmark/src/reporter.cc create mode 100644 third_party/benchmark/src/statistics.cc create mode 100644 third_party/benchmark/src/statistics.h create mode 100644 third_party/benchmark/src/string_util.cc create mode 100644 third_party/benchmark/src/string_util.h create mode 100644 third_party/benchmark/src/sysinfo.cc create mode 100644 third_party/benchmark/src/thread_manager.h create mode 100644 third_party/benchmark/src/thread_timer.h create mode 100644 third_party/benchmark/src/timers.cc create mode 100644 third_party/benchmark/src/timers.h create mode 100644 third_party/benchmark/tools/BUILD.bazel create mode 100755 third_party/benchmark/tools/compare.py create mode 100644 third_party/benchmark/tools/gbench/Inputs/test1_run1.json create mode 100644 third_party/benchmark/tools/gbench/Inputs/test1_run2.json create mode 100644 third_party/benchmark/tools/gbench/Inputs/test2_run.json create mode 100644 third_party/benchmark/tools/gbench/Inputs/test3_run0.json create mode 100644 third_party/benchmark/tools/gbench/Inputs/test3_run1.json create mode 100644 third_party/benchmark/tools/gbench/Inputs/test4_run.json create mode 100644 third_party/benchmark/tools/gbench/Inputs/test4_run0.json create mode 100644 third_party/benchmark/tools/gbench/Inputs/test4_run1.json create mode 100644 third_party/benchmark/tools/gbench/Inputs/test5_run0.json create mode 100644 third_party/benchmark/tools/gbench/Inputs/test5_run1.json create mode 100644 third_party/benchmark/tools/gbench/__init__.py create mode 100644 third_party/benchmark/tools/gbench/report.py create mode 100644 third_party/benchmark/tools/gbench/util.py create mode 100644 third_party/benchmark/tools/libpfm.BUILD.bazel create mode 100644 third_party/benchmark/tools/requirements.txt create mode 100755 third_party/benchmark/tools/strip_asm.py create mode 100644 third_party/curl/CHANGES create mode 100644 third_party/curl/CMake/CMakeConfigurableFile.in create mode 100644 third_party/curl/CMake/CurlSymbolHiding.cmake create mode 100644 third_party/curl/CMake/CurlTests.c create mode 100644 third_party/curl/CMake/FindBearSSL.cmake create mode 100644 third_party/curl/CMake/FindBrotli.cmake create mode 100644 third_party/curl/CMake/FindCARES.cmake create mode 100644 third_party/curl/CMake/FindGSS.cmake create mode 100644 third_party/curl/CMake/FindLibPSL.cmake create mode 100644 third_party/curl/CMake/FindLibSSH2.cmake create mode 100644 third_party/curl/CMake/FindMSH3.cmake create mode 100644 third_party/curl/CMake/FindMbedTLS.cmake create mode 100644 third_party/curl/CMake/FindNGHTTP2.cmake create mode 100644 third_party/curl/CMake/FindNGHTTP3.cmake create mode 100644 third_party/curl/CMake/FindNGTCP2.cmake create mode 100644 third_party/curl/CMake/FindQUICHE.cmake create mode 100644 third_party/curl/CMake/FindWolfSSL.cmake create mode 100644 third_party/curl/CMake/FindZstd.cmake create mode 100644 third_party/curl/CMake/Macros.cmake create mode 100644 third_party/curl/CMake/OtherTests.cmake create mode 100644 third_party/curl/CMake/PickyWarnings.cmake create mode 100644 third_party/curl/CMake/Platforms/WindowsCache.cmake create mode 100644 third_party/curl/CMake/Utilities.cmake create mode 100644 third_party/curl/CMake/cmake_uninstall.cmake.in create mode 100644 third_party/curl/CMake/curl-config.cmake.in create mode 100644 third_party/curl/CMakeLists.txt create mode 100644 third_party/curl/COPYING create mode 100644 third_party/curl/Dockerfile create mode 100644 third_party/curl/Makefile create mode 100644 third_party/curl/Makefile.am create mode 100644 third_party/curl/Makefile.in create mode 100644 third_party/curl/README create mode 100644 third_party/curl/RELEASE-NOTES create mode 100644 third_party/curl/acinclude.m4 create mode 100644 third_party/curl/aclocal.m4 create mode 100755 third_party/curl/buildconf create mode 100644 third_party/curl/buildconf.bat create mode 100755 third_party/curl/compile create mode 100755 third_party/curl/config.guess create mode 100755 third_party/curl/config.sub create mode 100755 third_party/curl/configure create mode 100644 third_party/curl/configure.ac create mode 100644 third_party/curl/curl-config.in create mode 100755 third_party/curl/depcomp create mode 100644 third_party/curl/include/Makefile.am create mode 100644 third_party/curl/include/Makefile.in create mode 100644 third_party/curl/include/README.md create mode 100644 third_party/curl/include/curl/Makefile.am create mode 100644 third_party/curl/include/curl/Makefile.in create mode 100644 third_party/curl/include/curl/curl.h create mode 100644 third_party/curl/include/curl/curlver.h create mode 100644 third_party/curl/include/curl/easy.h create mode 100644 third_party/curl/include/curl/header.h create mode 100644 third_party/curl/include/curl/mprintf.h create mode 100644 third_party/curl/include/curl/multi.h create mode 100644 third_party/curl/include/curl/options.h create mode 100644 third_party/curl/include/curl/stdcheaders.h create mode 100644 third_party/curl/include/curl/system.h create mode 100644 third_party/curl/include/curl/typecheck-gcc.h create mode 100644 third_party/curl/include/curl/urlapi.h create mode 100644 third_party/curl/include/curl/websockets.h create mode 100755 third_party/curl/install-sh create mode 100644 third_party/curl/lib/.checksrc create mode 100644 third_party/curl/lib/CMakeLists.txt create mode 100644 third_party/curl/lib/Makefile.am create mode 100644 third_party/curl/lib/Makefile.in create mode 100644 third_party/curl/lib/Makefile.inc create mode 100644 third_party/curl/lib/Makefile.mk create mode 100644 third_party/curl/lib/Makefile.soname create mode 100644 third_party/curl/lib/altsvc.c create mode 100644 third_party/curl/lib/altsvc.h create mode 100644 third_party/curl/lib/amigaos.c create mode 100644 third_party/curl/lib/amigaos.h create mode 100644 third_party/curl/lib/arpa_telnet.h create mode 100644 third_party/curl/lib/asyn-ares.c create mode 100644 third_party/curl/lib/asyn-thread.c create mode 100644 third_party/curl/lib/asyn.h create mode 100644 third_party/curl/lib/base64.c create mode 100644 third_party/curl/lib/bufq.c create mode 100644 third_party/curl/lib/bufq.h create mode 100644 third_party/curl/lib/bufref.c create mode 100644 third_party/curl/lib/bufref.h create mode 100644 third_party/curl/lib/c-hyper.c create mode 100644 third_party/curl/lib/c-hyper.h create mode 100644 third_party/curl/lib/cf-h1-proxy.c create mode 100644 third_party/curl/lib/cf-h1-proxy.h create mode 100644 third_party/curl/lib/cf-h2-proxy.c create mode 100644 third_party/curl/lib/cf-h2-proxy.h create mode 100644 third_party/curl/lib/cf-haproxy.c create mode 100644 third_party/curl/lib/cf-haproxy.h create mode 100644 third_party/curl/lib/cf-https-connect.c create mode 100644 third_party/curl/lib/cf-https-connect.h create mode 100644 third_party/curl/lib/cf-socket.c create mode 100644 third_party/curl/lib/cf-socket.h create mode 100644 third_party/curl/lib/cfilters.c create mode 100644 third_party/curl/lib/cfilters.h create mode 100644 third_party/curl/lib/config-amigaos.h create mode 100644 third_party/curl/lib/config-dos.h create mode 100644 third_party/curl/lib/config-mac.h create mode 100644 third_party/curl/lib/config-os400.h create mode 100644 third_party/curl/lib/config-plan9.h create mode 100644 third_party/curl/lib/config-riscos.h create mode 100644 third_party/curl/lib/config-win32.h create mode 100644 third_party/curl/lib/config-win32ce.h create mode 100644 third_party/curl/lib/conncache.c create mode 100644 third_party/curl/lib/conncache.h create mode 100644 third_party/curl/lib/connect.c create mode 100644 third_party/curl/lib/connect.h create mode 100644 third_party/curl/lib/content_encoding.c create mode 100644 third_party/curl/lib/content_encoding.h create mode 100644 third_party/curl/lib/cookie.c create mode 100644 third_party/curl/lib/cookie.h create mode 100644 third_party/curl/lib/curl_addrinfo.c create mode 100644 third_party/curl/lib/curl_addrinfo.h create mode 100644 third_party/curl/lib/curl_base64.h create mode 100644 third_party/curl/lib/curl_config.h.cmake create mode 100644 third_party/curl/lib/curl_config.h.in create mode 100644 third_party/curl/lib/curl_ctype.h create mode 100644 third_party/curl/lib/curl_des.c create mode 100644 third_party/curl/lib/curl_des.h create mode 100644 third_party/curl/lib/curl_endian.c create mode 100644 third_party/curl/lib/curl_endian.h create mode 100644 third_party/curl/lib/curl_fnmatch.c create mode 100644 third_party/curl/lib/curl_fnmatch.h create mode 100644 third_party/curl/lib/curl_get_line.c create mode 100644 third_party/curl/lib/curl_get_line.h create mode 100644 third_party/curl/lib/curl_gethostname.c create mode 100644 third_party/curl/lib/curl_gethostname.h create mode 100644 third_party/curl/lib/curl_gssapi.c create mode 100644 third_party/curl/lib/curl_gssapi.h create mode 100644 third_party/curl/lib/curl_hmac.h create mode 100644 third_party/curl/lib/curl_krb5.h create mode 100644 third_party/curl/lib/curl_ldap.h create mode 100644 third_party/curl/lib/curl_md4.h create mode 100644 third_party/curl/lib/curl_md5.h create mode 100644 third_party/curl/lib/curl_memory.h create mode 100644 third_party/curl/lib/curl_memrchr.c create mode 100644 third_party/curl/lib/curl_memrchr.h create mode 100644 third_party/curl/lib/curl_multibyte.c create mode 100644 third_party/curl/lib/curl_multibyte.h create mode 100644 third_party/curl/lib/curl_ntlm_core.c create mode 100644 third_party/curl/lib/curl_ntlm_core.h create mode 100644 third_party/curl/lib/curl_path.c create mode 100644 third_party/curl/lib/curl_path.h create mode 100644 third_party/curl/lib/curl_printf.h create mode 100644 third_party/curl/lib/curl_range.c create mode 100644 third_party/curl/lib/curl_range.h create mode 100644 third_party/curl/lib/curl_rtmp.c create mode 100644 third_party/curl/lib/curl_rtmp.h create mode 100644 third_party/curl/lib/curl_sasl.c create mode 100644 third_party/curl/lib/curl_sasl.h create mode 100644 third_party/curl/lib/curl_setup.h create mode 100644 third_party/curl/lib/curl_setup_once.h create mode 100644 third_party/curl/lib/curl_sha256.h create mode 100644 third_party/curl/lib/curl_sha512_256.c create mode 100644 third_party/curl/lib/curl_sha512_256.h create mode 100644 third_party/curl/lib/curl_sspi.c create mode 100644 third_party/curl/lib/curl_sspi.h create mode 100644 third_party/curl/lib/curl_threads.c create mode 100644 third_party/curl/lib/curl_threads.h create mode 100644 third_party/curl/lib/curl_trc.c create mode 100644 third_party/curl/lib/curl_trc.h create mode 100644 third_party/curl/lib/curlx.h create mode 100644 third_party/curl/lib/cw-out.c create mode 100644 third_party/curl/lib/cw-out.h create mode 100644 third_party/curl/lib/dict.c create mode 100644 third_party/curl/lib/dict.h create mode 100644 third_party/curl/lib/dllmain.c create mode 100644 third_party/curl/lib/doh.c create mode 100644 third_party/curl/lib/doh.h create mode 100644 third_party/curl/lib/dynbuf.c create mode 100644 third_party/curl/lib/dynbuf.h create mode 100644 third_party/curl/lib/dynhds.c create mode 100644 third_party/curl/lib/dynhds.h create mode 100644 third_party/curl/lib/easy.c create mode 100644 third_party/curl/lib/easy_lock.h create mode 100644 third_party/curl/lib/easygetopt.c create mode 100644 third_party/curl/lib/easyif.h create mode 100644 third_party/curl/lib/easyoptions.c create mode 100644 third_party/curl/lib/easyoptions.h create mode 100644 third_party/curl/lib/escape.c create mode 100644 third_party/curl/lib/escape.h create mode 100644 third_party/curl/lib/file.c create mode 100644 third_party/curl/lib/file.h create mode 100644 third_party/curl/lib/fileinfo.c create mode 100644 third_party/curl/lib/fileinfo.h create mode 100644 third_party/curl/lib/fopen.c create mode 100644 third_party/curl/lib/fopen.h create mode 100644 third_party/curl/lib/formdata.c create mode 100644 third_party/curl/lib/formdata.h create mode 100644 third_party/curl/lib/ftp.c create mode 100644 third_party/curl/lib/ftp.h create mode 100644 third_party/curl/lib/ftplistparser.c create mode 100644 third_party/curl/lib/ftplistparser.h create mode 100644 third_party/curl/lib/functypes.h create mode 100644 third_party/curl/lib/getenv.c create mode 100644 third_party/curl/lib/getinfo.c create mode 100644 third_party/curl/lib/getinfo.h create mode 100644 third_party/curl/lib/gopher.c create mode 100644 third_party/curl/lib/gopher.h create mode 100644 third_party/curl/lib/hash.c create mode 100644 third_party/curl/lib/hash.h create mode 100644 third_party/curl/lib/headers.c create mode 100644 third_party/curl/lib/headers.h create mode 100644 third_party/curl/lib/hmac.c create mode 100644 third_party/curl/lib/hostasyn.c create mode 100644 third_party/curl/lib/hostip.c create mode 100644 third_party/curl/lib/hostip.h create mode 100644 third_party/curl/lib/hostip4.c create mode 100644 third_party/curl/lib/hostip6.c create mode 100644 third_party/curl/lib/hostsyn.c create mode 100644 third_party/curl/lib/hsts.c create mode 100644 third_party/curl/lib/hsts.h create mode 100644 third_party/curl/lib/http.c create mode 100644 third_party/curl/lib/http.h create mode 100644 third_party/curl/lib/http1.c create mode 100644 third_party/curl/lib/http1.h create mode 100644 third_party/curl/lib/http2.c create mode 100644 third_party/curl/lib/http2.h create mode 100644 third_party/curl/lib/http_aws_sigv4.c create mode 100644 third_party/curl/lib/http_aws_sigv4.h create mode 100644 third_party/curl/lib/http_chunks.c create mode 100644 third_party/curl/lib/http_chunks.h create mode 100644 third_party/curl/lib/http_digest.c create mode 100644 third_party/curl/lib/http_digest.h create mode 100644 third_party/curl/lib/http_negotiate.c create mode 100644 third_party/curl/lib/http_negotiate.h create mode 100644 third_party/curl/lib/http_ntlm.c create mode 100644 third_party/curl/lib/http_ntlm.h create mode 100644 third_party/curl/lib/http_proxy.c create mode 100644 third_party/curl/lib/http_proxy.h create mode 100644 third_party/curl/lib/idn.c create mode 100644 third_party/curl/lib/idn.h create mode 100644 third_party/curl/lib/if2ip.c create mode 100644 third_party/curl/lib/if2ip.h create mode 100644 third_party/curl/lib/imap.c create mode 100644 third_party/curl/lib/imap.h create mode 100644 third_party/curl/lib/inet_ntop.c create mode 100644 third_party/curl/lib/inet_ntop.h create mode 100644 third_party/curl/lib/inet_pton.c create mode 100644 third_party/curl/lib/inet_pton.h create mode 100644 third_party/curl/lib/krb5.c create mode 100644 third_party/curl/lib/ldap.c create mode 100644 third_party/curl/lib/libcurl.rc create mode 100644 third_party/curl/lib/libcurl.vers.in create mode 100644 third_party/curl/lib/llist.c create mode 100644 third_party/curl/lib/llist.h create mode 100644 third_party/curl/lib/macos.c create mode 100644 third_party/curl/lib/macos.h create mode 100644 third_party/curl/lib/md4.c create mode 100644 third_party/curl/lib/md5.c create mode 100644 third_party/curl/lib/memdebug.c create mode 100644 third_party/curl/lib/memdebug.h create mode 100644 third_party/curl/lib/mime.c create mode 100644 third_party/curl/lib/mime.h create mode 100644 third_party/curl/lib/mprintf.c create mode 100644 third_party/curl/lib/mqtt.c create mode 100644 third_party/curl/lib/mqtt.h create mode 100644 third_party/curl/lib/multi.c create mode 100644 third_party/curl/lib/multihandle.h create mode 100644 third_party/curl/lib/multiif.h create mode 100644 third_party/curl/lib/netrc.c create mode 100644 third_party/curl/lib/netrc.h create mode 100644 third_party/curl/lib/nonblock.c create mode 100644 third_party/curl/lib/nonblock.h create mode 100644 third_party/curl/lib/noproxy.c create mode 100644 third_party/curl/lib/noproxy.h create mode 100644 third_party/curl/lib/openldap.c create mode 100644 third_party/curl/lib/parsedate.c create mode 100644 third_party/curl/lib/parsedate.h create mode 100644 third_party/curl/lib/pingpong.c create mode 100644 third_party/curl/lib/pingpong.h create mode 100644 third_party/curl/lib/pop3.c create mode 100644 third_party/curl/lib/pop3.h create mode 100644 third_party/curl/lib/progress.c create mode 100644 third_party/curl/lib/progress.h create mode 100644 third_party/curl/lib/psl.c create mode 100644 third_party/curl/lib/psl.h create mode 100644 third_party/curl/lib/rand.c create mode 100644 third_party/curl/lib/rand.h create mode 100644 third_party/curl/lib/rename.c create mode 100644 third_party/curl/lib/rename.h create mode 100644 third_party/curl/lib/request.c create mode 100644 third_party/curl/lib/request.h create mode 100644 third_party/curl/lib/rtsp.c create mode 100644 third_party/curl/lib/rtsp.h create mode 100644 third_party/curl/lib/select.c create mode 100644 third_party/curl/lib/select.h create mode 100644 third_party/curl/lib/sendf.c create mode 100644 third_party/curl/lib/sendf.h create mode 100644 third_party/curl/lib/setopt.c create mode 100644 third_party/curl/lib/setopt.h create mode 100644 third_party/curl/lib/setup-os400.h create mode 100644 third_party/curl/lib/setup-vms.h create mode 100644 third_party/curl/lib/setup-win32.h create mode 100644 third_party/curl/lib/sha256.c create mode 100644 third_party/curl/lib/share.c create mode 100644 third_party/curl/lib/share.h create mode 100644 third_party/curl/lib/sigpipe.h create mode 100644 third_party/curl/lib/slist.c create mode 100644 third_party/curl/lib/slist.h create mode 100644 third_party/curl/lib/smb.c create mode 100644 third_party/curl/lib/smb.h create mode 100644 third_party/curl/lib/smtp.c create mode 100644 third_party/curl/lib/smtp.h create mode 100644 third_party/curl/lib/sockaddr.h create mode 100644 third_party/curl/lib/socketpair.c create mode 100644 third_party/curl/lib/socketpair.h create mode 100644 third_party/curl/lib/socks.c create mode 100644 third_party/curl/lib/socks.h create mode 100644 third_party/curl/lib/socks_gssapi.c create mode 100644 third_party/curl/lib/socks_sspi.c create mode 100644 third_party/curl/lib/speedcheck.c create mode 100644 third_party/curl/lib/speedcheck.h create mode 100644 third_party/curl/lib/splay.c create mode 100644 third_party/curl/lib/splay.h create mode 100644 third_party/curl/lib/strcase.c create mode 100644 third_party/curl/lib/strcase.h create mode 100644 third_party/curl/lib/strdup.c create mode 100644 third_party/curl/lib/strdup.h create mode 100644 third_party/curl/lib/strerror.c create mode 100644 third_party/curl/lib/strerror.h create mode 100644 third_party/curl/lib/strtok.c create mode 100644 third_party/curl/lib/strtok.h create mode 100644 third_party/curl/lib/strtoofft.c create mode 100644 third_party/curl/lib/strtoofft.h create mode 100644 third_party/curl/lib/system_win32.c create mode 100644 third_party/curl/lib/system_win32.h create mode 100644 third_party/curl/lib/telnet.c create mode 100644 third_party/curl/lib/telnet.h create mode 100644 third_party/curl/lib/tftp.c create mode 100644 third_party/curl/lib/tftp.h create mode 100644 third_party/curl/lib/timediff.c create mode 100644 third_party/curl/lib/timediff.h create mode 100644 third_party/curl/lib/timeval.c create mode 100644 third_party/curl/lib/timeval.h create mode 100644 third_party/curl/lib/transfer.c create mode 100644 third_party/curl/lib/transfer.h create mode 100644 third_party/curl/lib/url.c create mode 100644 third_party/curl/lib/url.h create mode 100644 third_party/curl/lib/urlapi-int.h create mode 100644 third_party/curl/lib/urlapi.c create mode 100644 third_party/curl/lib/urldata.h create mode 100644 third_party/curl/lib/vauth/cleartext.c create mode 100644 third_party/curl/lib/vauth/cram.c create mode 100644 third_party/curl/lib/vauth/digest.c create mode 100644 third_party/curl/lib/vauth/digest.h create mode 100644 third_party/curl/lib/vauth/digest_sspi.c create mode 100644 third_party/curl/lib/vauth/gsasl.c create mode 100644 third_party/curl/lib/vauth/krb5_gssapi.c create mode 100644 third_party/curl/lib/vauth/krb5_sspi.c create mode 100644 third_party/curl/lib/vauth/ntlm.c create mode 100644 third_party/curl/lib/vauth/ntlm.h create mode 100644 third_party/curl/lib/vauth/ntlm_sspi.c create mode 100644 third_party/curl/lib/vauth/oauth2.c create mode 100644 third_party/curl/lib/vauth/spnego_gssapi.c create mode 100644 third_party/curl/lib/vauth/spnego_sspi.c create mode 100644 third_party/curl/lib/vauth/vauth.c create mode 100644 third_party/curl/lib/vauth/vauth.h create mode 100644 third_party/curl/lib/version.c create mode 100644 third_party/curl/lib/version_win32.c create mode 100644 third_party/curl/lib/version_win32.h create mode 100644 third_party/curl/lib/vquic/curl_msh3.c create mode 100644 third_party/curl/lib/vquic/curl_msh3.h create mode 100644 third_party/curl/lib/vquic/curl_ngtcp2.c create mode 100644 third_party/curl/lib/vquic/curl_ngtcp2.h create mode 100644 third_party/curl/lib/vquic/curl_osslq.c create mode 100644 third_party/curl/lib/vquic/curl_osslq.h create mode 100644 third_party/curl/lib/vquic/curl_quiche.c create mode 100644 third_party/curl/lib/vquic/curl_quiche.h create mode 100644 third_party/curl/lib/vquic/vquic-tls.c create mode 100644 third_party/curl/lib/vquic/vquic-tls.h create mode 100644 third_party/curl/lib/vquic/vquic.c create mode 100644 third_party/curl/lib/vquic/vquic.h create mode 100644 third_party/curl/lib/vquic/vquic_int.h create mode 100644 third_party/curl/lib/vssh/libssh.c create mode 100644 third_party/curl/lib/vssh/libssh2.c create mode 100644 third_party/curl/lib/vssh/ssh.h create mode 100644 third_party/curl/lib/vssh/wolfssh.c create mode 100644 third_party/curl/lib/vtls/bearssl.c create mode 100644 third_party/curl/lib/vtls/bearssl.h create mode 100644 third_party/curl/lib/vtls/cipher_suite.c create mode 100644 third_party/curl/lib/vtls/cipher_suite.h create mode 100644 third_party/curl/lib/vtls/gtls.c create mode 100644 third_party/curl/lib/vtls/gtls.h create mode 100644 third_party/curl/lib/vtls/hostcheck.c create mode 100644 third_party/curl/lib/vtls/hostcheck.h create mode 100644 third_party/curl/lib/vtls/keylog.c create mode 100644 third_party/curl/lib/vtls/keylog.h create mode 100644 third_party/curl/lib/vtls/mbedtls.c create mode 100644 third_party/curl/lib/vtls/mbedtls.h create mode 100644 third_party/curl/lib/vtls/mbedtls_threadlock.c create mode 100644 third_party/curl/lib/vtls/mbedtls_threadlock.h create mode 100644 third_party/curl/lib/vtls/openssl.c create mode 100644 third_party/curl/lib/vtls/openssl.h create mode 100644 third_party/curl/lib/vtls/rustls.c create mode 100644 third_party/curl/lib/vtls/rustls.h create mode 100644 third_party/curl/lib/vtls/schannel.c create mode 100644 third_party/curl/lib/vtls/schannel.h create mode 100644 third_party/curl/lib/vtls/schannel_int.h create mode 100644 third_party/curl/lib/vtls/schannel_verify.c create mode 100644 third_party/curl/lib/vtls/sectransp.c create mode 100644 third_party/curl/lib/vtls/sectransp.h create mode 100644 third_party/curl/lib/vtls/vtls.c create mode 100644 third_party/curl/lib/vtls/vtls.h create mode 100644 third_party/curl/lib/vtls/vtls_int.h create mode 100644 third_party/curl/lib/vtls/wolfssl.c create mode 100644 third_party/curl/lib/vtls/wolfssl.h create mode 100644 third_party/curl/lib/vtls/x509asn1.c create mode 100644 third_party/curl/lib/vtls/x509asn1.h create mode 100644 third_party/curl/lib/warnless.c create mode 100644 third_party/curl/lib/warnless.h create mode 100644 third_party/curl/lib/ws.c create mode 100644 third_party/curl/lib/ws.h create mode 100644 third_party/curl/libcurl.def create mode 100644 third_party/curl/libcurl.pc.in create mode 100755 third_party/curl/ltmain.sh create mode 100644 third_party/curl/m4/curl-amissl.m4 create mode 100644 third_party/curl/m4/curl-bearssl.m4 create mode 100644 third_party/curl/m4/curl-compilers.m4 create mode 100644 third_party/curl/m4/curl-confopts.m4 create mode 100644 third_party/curl/m4/curl-functions.m4 create mode 100644 third_party/curl/m4/curl-gnutls.m4 create mode 100644 third_party/curl/m4/curl-mbedtls.m4 create mode 100644 third_party/curl/m4/curl-openssl.m4 create mode 100644 third_party/curl/m4/curl-override.m4 create mode 100644 third_party/curl/m4/curl-reentrant.m4 create mode 100644 third_party/curl/m4/curl-rustls.m4 create mode 100644 third_party/curl/m4/curl-schannel.m4 create mode 100644 third_party/curl/m4/curl-sectransp.m4 create mode 100644 third_party/curl/m4/curl-sysconfig.m4 create mode 100644 third_party/curl/m4/curl-wolfssl.m4 create mode 100644 third_party/curl/m4/libtool.m4 create mode 100644 third_party/curl/m4/ltoptions.m4 create mode 100644 third_party/curl/m4/ltsugar.m4 create mode 100644 third_party/curl/m4/ltversion.m4 create mode 100644 third_party/curl/m4/lt~obsolete.m4 create mode 100644 third_party/curl/m4/xc-am-iface.m4 create mode 100644 third_party/curl/m4/xc-cc-check.m4 create mode 100644 third_party/curl/m4/xc-lt-iface.m4 create mode 100644 third_party/curl/m4/xc-translit.m4 create mode 100644 third_party/curl/m4/xc-val-flgs.m4 create mode 100644 third_party/curl/m4/zz40-xc-ovr.m4 create mode 100644 third_party/curl/m4/zz50-xc-ovr.m4 create mode 100644 third_party/curl/m4/zz60-xc-ovr.m4 create mode 100755 third_party/curl/maketgz create mode 100755 third_party/curl/missing create mode 100644 third_party/curl/packages/Makefile.am create mode 100644 third_party/curl/packages/Makefile.in create mode 100644 third_party/curl/packages/OS400/README.OS400 create mode 100644 third_party/curl/packages/OS400/ccsidcurl.c create mode 100644 third_party/curl/packages/OS400/ccsidcurl.h create mode 100644 third_party/curl/packages/OS400/config400.default create mode 100644 third_party/curl/packages/OS400/curl.cmd create mode 100644 third_party/curl/packages/OS400/curl.inc.in create mode 100644 third_party/curl/packages/OS400/curlcl.c create mode 100644 third_party/curl/packages/OS400/curlmain.c create mode 100755 third_party/curl/packages/OS400/initscript.sh create mode 100755 third_party/curl/packages/OS400/make-include.sh create mode 100755 third_party/curl/packages/OS400/make-lib.sh create mode 100755 third_party/curl/packages/OS400/make-src.sh create mode 100755 third_party/curl/packages/OS400/make-tests.sh create mode 100755 third_party/curl/packages/OS400/makefile.sh create mode 100644 third_party/curl/packages/OS400/os400sys.c create mode 100644 third_party/curl/packages/OS400/os400sys.h create mode 100644 third_party/curl/packages/OS400/rpg-examples/HEADERAPI create mode 100644 third_party/curl/packages/OS400/rpg-examples/HTTPPOST create mode 100644 third_party/curl/packages/OS400/rpg-examples/INMEMORY create mode 100644 third_party/curl/packages/OS400/rpg-examples/SIMPLE1 create mode 100644 third_party/curl/packages/OS400/rpg-examples/SIMPLE2 create mode 100644 third_party/curl/packages/OS400/rpg-examples/SMTPSRCMBR create mode 100644 third_party/curl/packages/README.md create mode 100644 third_party/curl/packages/vms/Makefile.am create mode 100644 third_party/curl/packages/vms/Makefile.in create mode 100644 third_party/curl/packages/vms/backup_gnv_curl_src.com create mode 100644 third_party/curl/packages/vms/build_curl-config_script.com create mode 100644 third_party/curl/packages/vms/build_gnv_curl.com create mode 100644 third_party/curl/packages/vms/build_gnv_curl_pcsi_desc.com create mode 100644 third_party/curl/packages/vms/build_gnv_curl_pcsi_text.com create mode 100644 third_party/curl/packages/vms/build_gnv_curl_release_notes.com create mode 100644 third_party/curl/packages/vms/build_libcurl_pc.com create mode 100644 third_party/curl/packages/vms/build_vms.com create mode 100644 third_party/curl/packages/vms/clean_gnv_curl.com create mode 100644 third_party/curl/packages/vms/compare_curl_source.com create mode 100644 third_party/curl/packages/vms/config_h.com create mode 100644 third_party/curl/packages/vms/curl_crtl_init.c create mode 100644 third_party/curl/packages/vms/curl_gnv_build_steps.txt create mode 100644 third_party/curl/packages/vms/curl_release_note_start.txt create mode 100644 third_party/curl/packages/vms/curl_startup.com create mode 100644 third_party/curl/packages/vms/curlmsg.h create mode 100644 third_party/curl/packages/vms/curlmsg.msg create mode 100644 third_party/curl/packages/vms/curlmsg.sdl create mode 100644 third_party/curl/packages/vms/curlmsg_vms.h create mode 100644 third_party/curl/packages/vms/generate_config_vms_h_curl.com create mode 100644 third_party/curl/packages/vms/generate_vax_transfer.com create mode 100644 third_party/curl/packages/vms/gnv_conftest.c_first create mode 100755 third_party/curl/packages/vms/gnv_curl_configure.sh create mode 100644 third_party/curl/packages/vms/gnv_libcurl_symbols.opt create mode 100644 third_party/curl/packages/vms/gnv_link_curl.com create mode 100644 third_party/curl/packages/vms/macro32_exactcase.patch create mode 100755 third_party/curl/packages/vms/make_gnv_curl_install.sh create mode 100644 third_party/curl/packages/vms/make_pcsi_curl_kit_name.com create mode 100644 third_party/curl/packages/vms/pcsi_gnv_curl_file_list.txt create mode 100644 third_party/curl/packages/vms/pcsi_product_gnv_curl.com create mode 100644 third_party/curl/packages/vms/readme create mode 100644 third_party/curl/packages/vms/report_openssl_version.c create mode 100644 third_party/curl/packages/vms/setup_gnv_curl_build.com create mode 100644 third_party/curl/packages/vms/stage_curl_install.com create mode 100644 third_party/curl/packages/vms/vms_eco_level.h create mode 100644 third_party/curl/plan9/README create mode 100644 third_party/curl/plan9/include/mkfile create mode 100644 third_party/curl/plan9/lib/mkfile create mode 100755 third_party/curl/plan9/lib/mkfile.inc create mode 100644 third_party/curl/plan9/mkfile create mode 100644 third_party/curl/plan9/mkfile.proto create mode 100644 third_party/curl/plan9/src/mkfile create mode 100755 third_party/curl/plan9/src/mkfile.inc create mode 100644 third_party/curl/projects/README.md create mode 100644 third_party/curl/projects/build-openssl.bat create mode 100644 third_party/curl/projects/build-wolfssl.bat create mode 100644 third_party/curl/projects/checksrc.bat create mode 100644 third_party/curl/projects/generate.bat create mode 100644 third_party/curl/projects/wolfssl_options.h create mode 100644 third_party/curl/projects/wolfssl_override.props create mode 100644 third_party/curl/scripts/Makefile.am create mode 100644 third_party/curl/scripts/Makefile.in create mode 100755 third_party/curl/scripts/cd2cd create mode 100755 third_party/curl/scripts/cd2nroff create mode 100755 third_party/curl/scripts/cdall create mode 100755 third_party/curl/scripts/checksrc.pl create mode 100755 third_party/curl/scripts/completion.pl create mode 100755 third_party/curl/scripts/coverage.sh create mode 100755 third_party/curl/scripts/dmaketgz create mode 100755 third_party/curl/scripts/firefox-db2pem.sh create mode 100755 third_party/curl/scripts/managen create mode 100755 third_party/curl/scripts/mk-ca-bundle.pl create mode 100755 third_party/curl/scripts/nroff2cd create mode 100644 third_party/curl/scripts/schemetable.c create mode 100644 third_party/curl/src/.checksrc create mode 100644 third_party/curl/src/CMakeLists.txt create mode 100644 third_party/curl/src/Makefile.am create mode 100644 third_party/curl/src/Makefile.in create mode 100644 third_party/curl/src/Makefile.inc create mode 100644 third_party/curl/src/Makefile.mk create mode 100644 third_party/curl/src/curl.rc create mode 100755 third_party/curl/src/mkhelp.pl create mode 100644 third_party/curl/src/slist_wc.c create mode 100644 third_party/curl/src/slist_wc.h create mode 100644 third_party/curl/src/tool_binmode.c create mode 100644 third_party/curl/src/tool_binmode.h create mode 100644 third_party/curl/src/tool_bname.c create mode 100644 third_party/curl/src/tool_bname.h create mode 100644 third_party/curl/src/tool_cb_dbg.c create mode 100644 third_party/curl/src/tool_cb_dbg.h create mode 100644 third_party/curl/src/tool_cb_hdr.c create mode 100644 third_party/curl/src/tool_cb_hdr.h create mode 100644 third_party/curl/src/tool_cb_prg.c create mode 100644 third_party/curl/src/tool_cb_prg.h create mode 100644 third_party/curl/src/tool_cb_rea.c create mode 100644 third_party/curl/src/tool_cb_rea.h create mode 100644 third_party/curl/src/tool_cb_see.c create mode 100644 third_party/curl/src/tool_cb_see.h create mode 100644 third_party/curl/src/tool_cb_wrt.c create mode 100644 third_party/curl/src/tool_cb_wrt.h create mode 100644 third_party/curl/src/tool_cfgable.c create mode 100644 third_party/curl/src/tool_cfgable.h create mode 100644 third_party/curl/src/tool_dirhie.c create mode 100644 third_party/curl/src/tool_dirhie.h create mode 100644 third_party/curl/src/tool_doswin.c create mode 100644 third_party/curl/src/tool_doswin.h create mode 100644 third_party/curl/src/tool_easysrc.c create mode 100644 third_party/curl/src/tool_easysrc.h create mode 100644 third_party/curl/src/tool_filetime.c create mode 100644 third_party/curl/src/tool_filetime.h create mode 100644 third_party/curl/src/tool_findfile.c create mode 100644 third_party/curl/src/tool_findfile.h create mode 100644 third_party/curl/src/tool_formparse.c create mode 100644 third_party/curl/src/tool_formparse.h create mode 100644 third_party/curl/src/tool_getparam.c create mode 100644 third_party/curl/src/tool_getparam.h create mode 100644 third_party/curl/src/tool_getpass.c create mode 100644 third_party/curl/src/tool_getpass.h create mode 100644 third_party/curl/src/tool_help.c create mode 100644 third_party/curl/src/tool_help.h create mode 100644 third_party/curl/src/tool_helpers.c create mode 100644 third_party/curl/src/tool_helpers.h create mode 100644 third_party/curl/src/tool_hugehelp.c create mode 100644 third_party/curl/src/tool_hugehelp.h create mode 100644 third_party/curl/src/tool_ipfs.c create mode 100644 third_party/curl/src/tool_ipfs.h create mode 100644 third_party/curl/src/tool_libinfo.c create mode 100644 third_party/curl/src/tool_libinfo.h create mode 100644 third_party/curl/src/tool_listhelp.c create mode 100644 third_party/curl/src/tool_main.c create mode 100644 third_party/curl/src/tool_main.h create mode 100644 third_party/curl/src/tool_msgs.c create mode 100644 third_party/curl/src/tool_msgs.h create mode 100644 third_party/curl/src/tool_operate.c create mode 100644 third_party/curl/src/tool_operate.h create mode 100644 third_party/curl/src/tool_operhlp.c create mode 100644 third_party/curl/src/tool_operhlp.h create mode 100644 third_party/curl/src/tool_paramhlp.c create mode 100644 third_party/curl/src/tool_paramhlp.h create mode 100644 third_party/curl/src/tool_parsecfg.c create mode 100644 third_party/curl/src/tool_parsecfg.h create mode 100644 third_party/curl/src/tool_progress.c create mode 100644 third_party/curl/src/tool_progress.h create mode 100644 third_party/curl/src/tool_sdecls.h create mode 100644 third_party/curl/src/tool_setopt.c create mode 100644 third_party/curl/src/tool_setopt.h create mode 100644 third_party/curl/src/tool_setup.h create mode 100644 third_party/curl/src/tool_sleep.c create mode 100644 third_party/curl/src/tool_sleep.h create mode 100644 third_party/curl/src/tool_stderr.c create mode 100644 third_party/curl/src/tool_stderr.h create mode 100644 third_party/curl/src/tool_strdup.c create mode 100644 third_party/curl/src/tool_strdup.h create mode 100644 third_party/curl/src/tool_urlglob.c create mode 100644 third_party/curl/src/tool_urlglob.h create mode 100644 third_party/curl/src/tool_util.c create mode 100644 third_party/curl/src/tool_util.h create mode 100644 third_party/curl/src/tool_version.h create mode 100644 third_party/curl/src/tool_vms.c create mode 100644 third_party/curl/src/tool_vms.h create mode 100644 third_party/curl/src/tool_writeout.c create mode 100644 third_party/curl/src/tool_writeout.h create mode 100644 third_party/curl/src/tool_writeout_json.c create mode 100644 third_party/curl/src/tool_writeout_json.h create mode 100644 third_party/curl/src/tool_xattr.c create mode 100644 third_party/curl/src/tool_xattr.h create mode 100644 third_party/curl/src/var.c create mode 100644 third_party/curl/src/var.h create mode 100644 third_party/curl/winbuild/Makefile.vc create mode 100644 third_party/curl/winbuild/MakefileBuild.vc create mode 100644 third_party/curl/winbuild/README.md create mode 100755 third_party/curl/winbuild/gen_resp_file.bat create mode 100644 third_party/curl/winbuild/makedebug.cmd create mode 100644 third_party/date/.gitignore create mode 100644 third_party/date/.travis.yml create mode 100644 third_party/date/CMakeLists.txt create mode 100644 third_party/date/LICENSE.txt create mode 100644 third_party/date/README.md create mode 100755 third_party/date/ci/install_cmake.sh create mode 100644 third_party/date/cmake/dateConfig.cmake create mode 100755 third_party/date/compile_fail.sh create mode 100644 third_party/date/include/date/chrono_io.h create mode 100644 third_party/date/include/date/date.h create mode 100644 third_party/date/include/date/ios.h create mode 100644 third_party/date/include/date/islamic.h create mode 100644 third_party/date/include/date/iso_week.h create mode 100644 third_party/date/include/date/julian.h create mode 100644 third_party/date/include/date/ptz.h create mode 100644 third_party/date/include/date/solar_hijri.h create mode 100644 third_party/date/include/date/tz.h create mode 100644 third_party/date/include/date/tz_private.h create mode 100644 third_party/date/src/ios.mm create mode 100644 third_party/date/src/tz.cpp create mode 100644 third_party/date/test/clock_cast_test/constexpr.pass.cpp create mode 100644 third_party/date/test/clock_cast_test/custom_clock.pass.cpp create mode 100644 third_party/date/test/clock_cast_test/deprecated.pass.cpp create mode 100644 third_party/date/test/clock_cast_test/local_t.pass.cpp create mode 100644 third_party/date/test/clock_cast_test/noncastable.pass.cpp create mode 100644 third_party/date/test/clock_cast_test/normal_clocks.pass.cpp create mode 100644 third_party/date/test/clock_cast_test/to_sys_return_int.fail.cpp create mode 100644 third_party/date/test/clock_cast_test/to_sys_return_reference.fail.cpp create mode 100644 third_party/date/test/clock_cast_test/to_sys_return_utc_time.fail.cpp create mode 100644 third_party/date/test/date_test/day.pass.cpp create mode 100644 third_party/date/test/date_test/daypday.fail.cpp create mode 100644 third_party/date/test/date_test/daysmday.fail.cpp create mode 100644 third_party/date/test/date_test/daysmweekday.fail.cpp create mode 100644 third_party/date/test/date_test/detail/decimal_format_seconds.pass.cpp create mode 100644 third_party/date/test/date_test/detail/static_pow10.pass.cpp create mode 100644 third_party/date/test/date_test/detail/width.pass.cpp create mode 100644 third_party/date/test/date_test/durations.pass.cpp create mode 100644 third_party/date/test/date_test/durations_output.pass.cpp create mode 100644 third_party/date/test/date_test/format/century.pass.cpp create mode 100644 third_party/date/test/date_test/format/misc.pass.cpp create mode 100644 third_party/date/test/date_test/format/range.pass.cpp create mode 100644 third_party/date/test/date_test/format/two_dight_year.pass.cpp create mode 100644 third_party/date/test/date_test/last.pass.cpp create mode 100644 third_party/date/test/date_test/make_time.pass.cpp create mode 100644 third_party/date/test/date_test/month.pass.cpp create mode 100644 third_party/date/test/date_test/month_day.pass.cpp create mode 100644 third_party/date/test/date_test/month_day_last.pass.cpp create mode 100644 third_party/date/test/date_test/month_weekday.pass.cpp create mode 100644 third_party/date/test/date_test/month_weekday_last.pass.cpp create mode 100644 third_party/date/test/date_test/month_weekday_last_less.fail.cpp create mode 100644 third_party/date/test/date_test/month_weekday_less.fail.cpp create mode 100644 third_party/date/test/date_test/monthpmonth.fail.cpp create mode 100644 third_party/date/test/date_test/months_m_year_month.fail.cpp create mode 100644 third_party/date/test/date_test/months_m_year_month_day.fail.cpp create mode 100644 third_party/date/test/date_test/monthsmmonth.fail.cpp create mode 100644 third_party/date/test/date_test/multi_year_duration_addition.pass.cpp create mode 100644 third_party/date/test/date_test/op_div_day_day.fail.cpp create mode 100644 third_party/date/test/date_test/op_div_int_month.fail.cpp create mode 100644 third_party/date/test/date_test/op_div_int_year.fail.cpp create mode 100644 third_party/date/test/date_test/op_div_last_last.fail.cpp create mode 100644 third_party/date/test/date_test/op_div_month_day.pass.cpp create mode 100644 third_party/date/test/date_test/op_div_month_day_last.pass.cpp create mode 100644 third_party/date/test/date_test/op_div_month_day_month_day.fail.cpp create mode 100644 third_party/date/test/date_test/op_div_month_month.fail.cpp create mode 100644 third_party/date/test/date_test/op_div_month_weekday.pass.cpp create mode 100644 third_party/date/test/date_test/op_div_month_weekday_last.pass.cpp create mode 100644 third_party/date/test/date_test/op_div_month_year.fail.cpp create mode 100644 third_party/date/test/date_test/op_div_survey.pass.cpp create mode 100644 third_party/date/test/date_test/op_div_weekday_indexed_weekday_indexed.fail.cpp create mode 100644 third_party/date/test/date_test/op_div_weekday_last_weekday_last.fail.cpp create mode 100644 third_party/date/test/date_test/op_div_year_month.pass.cpp create mode 100644 third_party/date/test/date_test/op_div_year_month_day.pass.cpp create mode 100644 third_party/date/test/date_test/op_div_year_month_day_last.pass.cpp create mode 100644 third_party/date/test/date_test/op_div_year_month_weekday.pass.cpp create mode 100644 third_party/date/test/date_test/op_div_year_month_weekday_last.pass.cpp create mode 100644 third_party/date/test/date_test/op_div_year_month_year_month.fail.cpp create mode 100644 third_party/date/test/date_test/op_div_year_year.fail.cpp create mode 100644 third_party/date/test/date_test/parse.pass.cpp create mode 100644 third_party/date/test/date_test/sizeof.pass.cpp create mode 100644 third_party/date/test/date_test/time_of_day_hours.pass.cpp create mode 100644 third_party/date/test/date_test/time_of_day_microfortnights.pass.cpp create mode 100644 third_party/date/test/date_test/time_of_day_milliseconds.pass.cpp create mode 100644 third_party/date/test/date_test/time_of_day_minutes.pass.cpp create mode 100644 third_party/date/test/date_test/time_of_day_nanoseconds.pass.cpp create mode 100644 third_party/date/test/date_test/time_of_day_seconds.pass.cpp create mode 100644 third_party/date/test/date_test/weekday.pass.cpp create mode 100644 third_party/date/test/date_test/weekday_indexed.pass.cpp create mode 100644 third_party/date/test/date_test/weekday_last.pass.cpp create mode 100644 third_party/date/test/date_test/weekday_lessthan.fail.cpp create mode 100644 third_party/date/test/date_test/weekday_sum.fail.cpp create mode 100644 third_party/date/test/date_test/year.pass.cpp create mode 100644 third_party/date/test/date_test/year_month.pass.cpp create mode 100644 third_party/date/test/date_test/year_month_day.pass.cpp create mode 100644 third_party/date/test/date_test/year_month_day_last.pass.cpp create mode 100644 third_party/date/test/date_test/year_month_day_m_year_month_day.fail.cpp create mode 100644 third_party/date/test/date_test/year_month_day_p_year_month_day.fail.cpp create mode 100644 third_party/date/test/date_test/year_month_p_year_month.fail.cpp create mode 100644 third_party/date/test/date_test/year_month_weekday.pass.cpp create mode 100644 third_party/date/test/date_test/year_month_weekday_last.pass.cpp create mode 100644 third_party/date/test/date_test/year_p_year.fail.cpp create mode 100644 third_party/date/test/date_test/years_m_year.fail.cpp create mode 100644 third_party/date/test/date_test/years_m_year_month.fail.cpp create mode 100644 third_party/date/test/date_test/years_m_year_month_day.fail.cpp create mode 100644 third_party/date/test/iso_week/last.pass.cpp create mode 100644 third_party/date/test/iso_week/lastweek_weekday.pass.cpp create mode 100644 third_party/date/test/iso_week/op_div_survey.pass.cpp create mode 100644 third_party/date/test/iso_week/weekday.pass.cpp create mode 100644 third_party/date/test/iso_week/weekday_lessthan.fail.cpp create mode 100644 third_party/date/test/iso_week/weekday_sum.fail.cpp create mode 100644 third_party/date/test/iso_week/weeknum.pass.cpp create mode 100644 third_party/date/test/iso_week/weeknum_p_weeknum.fail.cpp create mode 100644 third_party/date/test/iso_week/weeknum_weekday.pass.cpp create mode 100644 third_party/date/test/iso_week/year.pass.cpp create mode 100644 third_party/date/test/iso_week/year_lastweek.pass.cpp create mode 100644 third_party/date/test/iso_week/year_lastweek_weekday.pass.cpp create mode 100644 third_party/date/test/iso_week/year_p_year.fail.cpp create mode 100644 third_party/date/test/iso_week/year_weeknum.pass.cpp create mode 100644 third_party/date/test/iso_week/year_weeknum_weekday.pass.cpp create mode 100644 third_party/date/test/iso_week/years_m_year.fail.cpp create mode 100644 third_party/date/test/just.pass.cpp create mode 100644 third_party/date/test/posix/ptz.pass.cpp create mode 100644 third_party/date/test/solar_hijri_test/parse.pass.cpp create mode 100644 third_party/date/test/solar_hijri_test/year_month_day.pass.cpp create mode 100755 third_party/date/test/testit create mode 100644 third_party/date/test/tz_test/OffsetZone.h create mode 100644 third_party/date/test/tz_test/OffsetZone.pass.cpp create mode 100644 third_party/date/test/tz_test/README.md create mode 100644 third_party/date/test/tz_test/tzdata2015e.txt.zip create mode 100644 third_party/date/test/tz_test/tzdata2015f.txt.zip create mode 100644 third_party/date/test/tz_test/tzdata2016c.txt.zip create mode 100644 third_party/date/test/tz_test/tzdata2016d.txt.zip create mode 100644 third_party/date/test/tz_test/tzdata2016e.txt.zip create mode 100644 third_party/date/test/tz_test/tzdata2016f.txt.zip create mode 100644 third_party/date/test/tz_test/tzdb_list.pass.cpp create mode 100644 third_party/date/test/tz_test/validate.cpp create mode 100644 third_party/date/test/tz_test/zone.pass.cpp create mode 100644 third_party/date/test/tz_test/zoned_time.pass.cpp create mode 100644 third_party/date/test/tz_test/zoned_time_deduction.pass.cpp create mode 100755 third_party/date/test_fail.sh create mode 100644 third_party/fmt/.clang-format create mode 100644 third_party/fmt/CMakeLists.txt create mode 100644 third_party/fmt/CONTRIBUTING.md create mode 100644 third_party/fmt/ChangeLog.md create mode 100644 third_party/fmt/LICENSE create mode 100644 third_party/fmt/README.md create mode 100644 third_party/fmt/include/fmt/args.h create mode 100644 third_party/fmt/include/fmt/chrono.h create mode 100644 third_party/fmt/include/fmt/color.h create mode 100644 third_party/fmt/include/fmt/compile.h create mode 100644 third_party/fmt/include/fmt/core.h create mode 100644 third_party/fmt/include/fmt/format-inl.h create mode 100644 third_party/fmt/include/fmt/format.h create mode 100644 third_party/fmt/include/fmt/os.h create mode 100644 third_party/fmt/include/fmt/ostream.h create mode 100644 third_party/fmt/include/fmt/printf.h create mode 100644 third_party/fmt/include/fmt/ranges.h create mode 100644 third_party/fmt/include/fmt/std.h create mode 100644 third_party/fmt/include/fmt/xchar.h create mode 100644 third_party/fmt/src/fmt.cc create mode 100644 third_party/fmt/src/format.cc create mode 100644 third_party/fmt/src/os.cc create mode 100644 third_party/fmt/support/Android.mk create mode 100644 third_party/fmt/support/AndroidManifest.xml create mode 100644 third_party/fmt/support/C++.sublime-syntax create mode 100644 third_party/fmt/support/README create mode 100644 third_party/fmt/support/Vagrantfile create mode 100644 third_party/fmt/support/bazel/.bazelversion create mode 100644 third_party/fmt/support/bazel/BUILD.bazel create mode 100644 third_party/fmt/support/bazel/README.md create mode 100644 third_party/fmt/support/bazel/WORKSPACE.bazel create mode 100755 third_party/fmt/support/build-docs.py create mode 100644 third_party/fmt/support/build.gradle create mode 100644 third_party/fmt/support/cmake/FindSetEnv.cmake create mode 100644 third_party/fmt/support/cmake/JoinPaths.cmake create mode 100644 third_party/fmt/support/cmake/fmt-config.cmake.in create mode 100644 third_party/fmt/support/cmake/fmt.pc.in create mode 100755 third_party/fmt/support/compute-powers.py create mode 100644 third_party/fmt/support/docopt.py create mode 100755 third_party/fmt/support/manage.py create mode 100755 third_party/fmt/support/printable.py create mode 100644 third_party/fmt/support/rtd/conf.py create mode 100644 third_party/fmt/support/rtd/index.rst create mode 100644 third_party/fmt/support/rtd/theme/layout.html create mode 100644 third_party/fmt/support/rtd/theme/theme.conf create mode 100644 third_party/gflags/.gitattributes create mode 100644 third_party/gflags/.gitignore create mode 100644 third_party/gflags/.gitmodules create mode 100644 third_party/gflags/.travis.yml create mode 100644 third_party/gflags/AUTHORS.txt create mode 100644 third_party/gflags/BUILD create mode 100644 third_party/gflags/CMakeLists.txt create mode 100644 third_party/gflags/COPYING.txt create mode 100644 third_party/gflags/ChangeLog.txt create mode 100644 third_party/gflags/INSTALL.md create mode 100644 third_party/gflags/README.md create mode 100644 third_party/gflags/WORKSPACE create mode 100644 third_party/gflags/appveyor.yml create mode 100644 third_party/gflags/bazel/gflags.bzl create mode 100644 third_party/gflags/cmake/README_runtime.txt create mode 100644 third_party/gflags/cmake/cmake_uninstall.cmake.in create mode 100644 third_party/gflags/cmake/config.cmake.in create mode 100644 third_party/gflags/cmake/execute_test.cmake create mode 100644 third_party/gflags/cmake/package.cmake.in create mode 100644 third_party/gflags/cmake/package.pc.in create mode 100644 third_party/gflags/cmake/utils.cmake create mode 100644 third_party/gflags/cmake/version.cmake.in create mode 100644 third_party/gflags/src/config.h create mode 100644 third_party/gflags/src/defines.h.in create mode 100644 third_party/gflags/src/gflags.cc create mode 100644 third_party/gflags/src/gflags.h.in create mode 100644 third_party/gflags/src/gflags_completions.cc create mode 100644 third_party/gflags/src/gflags_completions.h.in create mode 100755 third_party/gflags/src/gflags_completions.sh create mode 100644 third_party/gflags/src/gflags_declare.h.in create mode 100644 third_party/gflags/src/gflags_ns.h.in create mode 100644 third_party/gflags/src/gflags_reporting.cc create mode 100644 third_party/gflags/src/mutex.h create mode 100644 third_party/gflags/src/util.h create mode 100644 third_party/gflags/src/windows_port.cc create mode 100644 third_party/gflags/src/windows_port.h create mode 100644 third_party/gflags/test/CMakeLists.txt create mode 100644 third_party/gflags/test/config/CMakeLists.txt create mode 100644 third_party/gflags/test/config/main.cc create mode 100644 third_party/gflags/test/flagfile.1 create mode 100644 third_party/gflags/test/flagfile.2 create mode 100644 third_party/gflags/test/flagfile.3 create mode 100644 third_party/gflags/test/gflags_build.py.in create mode 100755 third_party/gflags/test/gflags_declare_flags.cc create mode 100644 third_party/gflags/test/gflags_declare_test.cc create mode 100755 third_party/gflags/test/gflags_strip_flags_test.cc create mode 100644 third_party/gflags/test/gflags_strip_flags_test.cmake create mode 100755 third_party/gflags/test/gflags_unittest.cc create mode 100644 third_party/gflags/test/gflags_unittest_flagfile create mode 100644 third_party/gflags/test/nc/CMakeLists.txt create mode 100644 third_party/gflags/test/nc/gflags_nc.cc create mode 100644 third_party/glog/.bazelci/presubmit.yml create mode 100644 third_party/glog/.clang-format create mode 100644 third_party/glog/.clang-tidy create mode 100644 third_party/glog/.gitattributes create mode 100644 third_party/glog/.github/workflows/android.yml create mode 100644 third_party/glog/.github/workflows/linux.yml create mode 100644 third_party/glog/.github/workflows/macos.yml create mode 100644 third_party/glog/.github/workflows/windows.yml create mode 100644 third_party/glog/.gitignore create mode 100644 third_party/glog/AUTHORS create mode 100644 third_party/glog/BUILD.bazel create mode 100644 third_party/glog/CMakeLists.txt create mode 100644 third_party/glog/CONTRIBUTORS create mode 100644 third_party/glog/COPYING create mode 100644 third_party/glog/ChangeLog create mode 100644 third_party/glog/README.rst create mode 100644 third_party/glog/WORKSPACE create mode 100644 third_party/glog/bazel/example/BUILD.bazel create mode 100644 third_party/glog/bazel/example/main.cc create mode 100644 third_party/glog/bazel/glog.bzl create mode 100644 third_party/glog/cmake/DetermineGflagsNamespace.cmake create mode 100644 third_party/glog/cmake/FindUnwind.cmake create mode 100644 third_party/glog/cmake/GetCacheVariables.cmake create mode 100644 third_party/glog/cmake/RunCleanerTest1.cmake create mode 100644 third_party/glog/cmake/RunCleanerTest2.cmake create mode 100644 third_party/glog/cmake/RunCleanerTest3.cmake create mode 100644 third_party/glog/cmake/TestInitPackageConfig.cmake create mode 100644 third_party/glog/cmake/TestPackageConfig.cmake create mode 100644 third_party/glog/glog-config.cmake.in create mode 100644 third_party/glog/glog-modules.cmake.in create mode 100644 third_party/glog/libglog.pc.in create mode 100644 third_party/glog/src/base/commandlineflags.h create mode 100644 third_party/glog/src/base/googleinit.h create mode 100644 third_party/glog/src/base/mutex.h create mode 100644 third_party/glog/src/cleanup_immediately_unittest.cc create mode 100644 third_party/glog/src/cleanup_with_absolute_prefix_unittest.cc create mode 100644 third_party/glog/src/cleanup_with_relative_prefix_unittest.cc create mode 100644 third_party/glog/src/config.h.cmake.in create mode 100644 third_party/glog/src/demangle.cc create mode 100644 third_party/glog/src/demangle.h create mode 100644 third_party/glog/src/demangle_unittest.cc create mode 100755 third_party/glog/src/demangle_unittest.sh create mode 100644 third_party/glog/src/demangle_unittest.txt create mode 100644 third_party/glog/src/glog/log_severity.h create mode 100644 third_party/glog/src/glog/logging.h.in create mode 100644 third_party/glog/src/glog/platform.h create mode 100644 third_party/glog/src/glog/raw_logging.h.in create mode 100644 third_party/glog/src/glog/stl_logging.h.in create mode 100644 third_party/glog/src/glog/vlog_is_on.h.in create mode 100644 third_party/glog/src/googletest.h create mode 100644 third_party/glog/src/logging.cc create mode 100644 third_party/glog/src/logging_custom_prefix_unittest.cc create mode 100644 third_party/glog/src/logging_custom_prefix_unittest.err create mode 100755 third_party/glog/src/logging_striplog_test.sh create mode 100644 third_party/glog/src/logging_striptest10.cc create mode 100644 third_party/glog/src/logging_striptest2.cc create mode 100644 third_party/glog/src/logging_striptest_main.cc create mode 100644 third_party/glog/src/logging_unittest.cc create mode 100644 third_party/glog/src/logging_unittest.err create mode 100644 third_party/glog/src/logging_unittest.out create mode 100644 third_party/glog/src/mock-log.h create mode 100644 third_party/glog/src/mock-log_unittest.cc create mode 100644 third_party/glog/src/package_config_unittest/working_config/CMakeLists.txt create mode 100644 third_party/glog/src/package_config_unittest/working_config/glog_package_config.cc create mode 100644 third_party/glog/src/raw_logging.cc create mode 100644 third_party/glog/src/signalhandler.cc create mode 100644 third_party/glog/src/signalhandler_unittest.cc create mode 100755 third_party/glog/src/signalhandler_unittest.sh create mode 100644 third_party/glog/src/stacktrace.h create mode 100644 third_party/glog/src/stacktrace_generic-inl.h create mode 100644 third_party/glog/src/stacktrace_libunwind-inl.h create mode 100644 third_party/glog/src/stacktrace_powerpc-inl.h create mode 100644 third_party/glog/src/stacktrace_unittest.cc create mode 100644 third_party/glog/src/stacktrace_unwind-inl.h create mode 100644 third_party/glog/src/stacktrace_windows-inl.h create mode 100644 third_party/glog/src/stacktrace_x86-inl.h create mode 100644 third_party/glog/src/stl_logging_unittest.cc create mode 100644 third_party/glog/src/symbolize.cc create mode 100644 third_party/glog/src/symbolize.h create mode 100644 third_party/glog/src/symbolize_unittest.cc create mode 100644 third_party/glog/src/utilities.cc create mode 100644 third_party/glog/src/utilities.h create mode 100644 third_party/glog/src/utilities_unittest.cc create mode 100644 third_party/glog/src/vlog_is_on.cc create mode 100644 third_party/glog/src/windows/dirent.h create mode 100755 third_party/glog/src/windows/port.cc create mode 100755 third_party/glog/src/windows/port.h create mode 100644 third_party/googletest/.clang-format create mode 100644 third_party/googletest/.gitignore create mode 100644 third_party/googletest/BUILD.bazel create mode 100644 third_party/googletest/CMakeLists.txt create mode 100644 third_party/googletest/CONTRIBUTING.md create mode 100644 third_party/googletest/CONTRIBUTORS create mode 100644 third_party/googletest/LICENSE create mode 100644 third_party/googletest/README.md create mode 100644 third_party/googletest/WORKSPACE create mode 100644 third_party/googletest/docs/_config.yml create mode 100644 third_party/googletest/docs/_data/navigation.yml create mode 100644 third_party/googletest/docs/_layouts/default.html create mode 100644 third_party/googletest/docs/_sass/main.scss create mode 100644 third_party/googletest/docs/advanced.md create mode 100644 third_party/googletest/docs/assets/css/style.scss create mode 100644 third_party/googletest/docs/community_created_documentation.md create mode 100644 third_party/googletest/docs/faq.md create mode 100644 third_party/googletest/docs/gmock_cheat_sheet.md create mode 100644 third_party/googletest/docs/gmock_cook_book.md create mode 100644 third_party/googletest/docs/gmock_faq.md create mode 100644 third_party/googletest/docs/gmock_for_dummies.md create mode 100644 third_party/googletest/docs/index.md create mode 100644 third_party/googletest/docs/pkgconfig.md create mode 100644 third_party/googletest/docs/platforms.md create mode 100644 third_party/googletest/docs/primer.md create mode 100644 third_party/googletest/docs/quickstart-bazel.md create mode 100644 third_party/googletest/docs/quickstart-cmake.md create mode 100644 third_party/googletest/docs/reference/actions.md create mode 100644 third_party/googletest/docs/reference/assertions.md create mode 100644 third_party/googletest/docs/reference/matchers.md create mode 100644 third_party/googletest/docs/reference/mocking.md create mode 100644 third_party/googletest/docs/reference/testing.md create mode 100644 third_party/googletest/docs/samples.md create mode 100644 third_party/googletest/googlemock/CMakeLists.txt create mode 100644 third_party/googletest/googlemock/README.md create mode 100644 third_party/googletest/googlemock/cmake/gmock.pc.in create mode 100644 third_party/googletest/googlemock/cmake/gmock_main.pc.in create mode 100644 third_party/googletest/googlemock/docs/README.md create mode 100644 third_party/googletest/googlemock/include/gmock/gmock-actions.h create mode 100644 third_party/googletest/googlemock/include/gmock/gmock-cardinalities.h create mode 100644 third_party/googletest/googlemock/include/gmock/gmock-function-mocker.h create mode 100644 third_party/googletest/googlemock/include/gmock/gmock-matchers.h create mode 100644 third_party/googletest/googlemock/include/gmock/gmock-more-actions.h create mode 100644 third_party/googletest/googlemock/include/gmock/gmock-more-matchers.h create mode 100644 third_party/googletest/googlemock/include/gmock/gmock-nice-strict.h create mode 100644 third_party/googletest/googlemock/include/gmock/gmock-spec-builders.h create mode 100644 third_party/googletest/googlemock/include/gmock/gmock.h create mode 100644 third_party/googletest/googlemock/include/gmock/internal/custom/README.md create mode 100644 third_party/googletest/googlemock/include/gmock/internal/custom/gmock-generated-actions.h create mode 100644 third_party/googletest/googlemock/include/gmock/internal/custom/gmock-matchers.h create mode 100644 third_party/googletest/googlemock/include/gmock/internal/custom/gmock-port.h create mode 100644 third_party/googletest/googlemock/include/gmock/internal/gmock-internal-utils.h create mode 100644 third_party/googletest/googlemock/include/gmock/internal/gmock-port.h create mode 100644 third_party/googletest/googlemock/include/gmock/internal/gmock-pp.h create mode 100644 third_party/googletest/googlemock/src/gmock-all.cc create mode 100644 third_party/googletest/googlemock/src/gmock-cardinalities.cc create mode 100644 third_party/googletest/googlemock/src/gmock-internal-utils.cc create mode 100644 third_party/googletest/googlemock/src/gmock-matchers.cc create mode 100644 third_party/googletest/googlemock/src/gmock-spec-builders.cc create mode 100644 third_party/googletest/googlemock/src/gmock.cc create mode 100644 third_party/googletest/googlemock/src/gmock_main.cc create mode 100644 third_party/googletest/googletest/CMakeLists.txt create mode 100644 third_party/googletest/googletest/README.md create mode 100644 third_party/googletest/googletest/cmake/Config.cmake.in create mode 100644 third_party/googletest/googletest/cmake/gtest.pc.in create mode 100644 third_party/googletest/googletest/cmake/gtest_main.pc.in create mode 100644 third_party/googletest/googletest/cmake/internal_utils.cmake create mode 100644 third_party/googletest/googletest/cmake/libgtest.la.in create mode 100644 third_party/googletest/googletest/docs/README.md create mode 100644 third_party/googletest/googletest/include/gtest/gtest-assertion-result.h create mode 100644 third_party/googletest/googletest/include/gtest/gtest-death-test.h create mode 100644 third_party/googletest/googletest/include/gtest/gtest-matchers.h create mode 100644 third_party/googletest/googletest/include/gtest/gtest-message.h create mode 100644 third_party/googletest/googletest/include/gtest/gtest-param-test.h create mode 100644 third_party/googletest/googletest/include/gtest/gtest-printers.h create mode 100644 third_party/googletest/googletest/include/gtest/gtest-spi.h create mode 100644 third_party/googletest/googletest/include/gtest/gtest-test-part.h create mode 100644 third_party/googletest/googletest/include/gtest/gtest-typed-test.h create mode 100644 third_party/googletest/googletest/include/gtest/gtest.h create mode 100644 third_party/googletest/googletest/include/gtest/gtest_pred_impl.h create mode 100644 third_party/googletest/googletest/include/gtest/gtest_prod.h create mode 100644 third_party/googletest/googletest/include/gtest/internal/custom/README.md create mode 100644 third_party/googletest/googletest/include/gtest/internal/custom/gtest-port.h create mode 100644 third_party/googletest/googletest/include/gtest/internal/custom/gtest-printers.h create mode 100644 third_party/googletest/googletest/include/gtest/internal/custom/gtest.h create mode 100644 third_party/googletest/googletest/include/gtest/internal/gtest-death-test-internal.h create mode 100644 third_party/googletest/googletest/include/gtest/internal/gtest-filepath.h create mode 100644 third_party/googletest/googletest/include/gtest/internal/gtest-internal.h create mode 100644 third_party/googletest/googletest/include/gtest/internal/gtest-param-util.h create mode 100644 third_party/googletest/googletest/include/gtest/internal/gtest-port-arch.h create mode 100644 third_party/googletest/googletest/include/gtest/internal/gtest-port.h create mode 100644 third_party/googletest/googletest/include/gtest/internal/gtest-string.h create mode 100644 third_party/googletest/googletest/include/gtest/internal/gtest-type-util.h create mode 100644 third_party/googletest/googletest/samples/prime_tables.h create mode 100644 third_party/googletest/googletest/samples/sample1.cc create mode 100644 third_party/googletest/googletest/samples/sample1.h create mode 100644 third_party/googletest/googletest/samples/sample10_unittest.cc create mode 100644 third_party/googletest/googletest/samples/sample1_unittest.cc create mode 100644 third_party/googletest/googletest/samples/sample2.cc create mode 100644 third_party/googletest/googletest/samples/sample2.h create mode 100644 third_party/googletest/googletest/samples/sample2_unittest.cc create mode 100644 third_party/googletest/googletest/samples/sample3-inl.h create mode 100644 third_party/googletest/googletest/samples/sample3_unittest.cc create mode 100644 third_party/googletest/googletest/samples/sample4.cc create mode 100644 third_party/googletest/googletest/samples/sample4.h create mode 100644 third_party/googletest/googletest/samples/sample4_unittest.cc create mode 100644 third_party/googletest/googletest/samples/sample5_unittest.cc create mode 100644 third_party/googletest/googletest/samples/sample6_unittest.cc create mode 100644 third_party/googletest/googletest/samples/sample7_unittest.cc create mode 100644 third_party/googletest/googletest/samples/sample8_unittest.cc create mode 100644 third_party/googletest/googletest/samples/sample9_unittest.cc create mode 100644 third_party/googletest/googletest/src/gtest-all.cc create mode 100644 third_party/googletest/googletest/src/gtest-assertion-result.cc create mode 100644 third_party/googletest/googletest/src/gtest-death-test.cc create mode 100644 third_party/googletest/googletest/src/gtest-filepath.cc create mode 100644 third_party/googletest/googletest/src/gtest-internal-inl.h create mode 100644 third_party/googletest/googletest/src/gtest-matchers.cc create mode 100644 third_party/googletest/googletest/src/gtest-port.cc create mode 100644 third_party/googletest/googletest/src/gtest-printers.cc create mode 100644 third_party/googletest/googletest/src/gtest-test-part.cc create mode 100644 third_party/googletest/googletest/src/gtest-typed-test.cc create mode 100644 third_party/googletest/googletest/src/gtest.cc create mode 100644 third_party/googletest/googletest/src/gtest_main.cc create mode 100644 third_party/inja/inja/inja.h create mode 100644 third_party/inja/inja/string_view.h create mode 100644 third_party/json/json.h create mode 100644 third_party/json/nlohmann/json.hpp create mode 100644 third_party/openssl-cmake/CMakeLists.txt create mode 100644 third_party/openssl-cmake/LICENSE create mode 100644 third_party/openssl-cmake/README.md create mode 100644 third_party/openssl-cmake/cmake/BuildOpenSSL.cmake create mode 100644 third_party/openssl-cmake/cmake/ByproductsOpenSSL.cmake create mode 100644 third_party/openssl-cmake/cmake/PatchOpenSSL.cmake create mode 100644 third_party/openssl-cmake/cmake/PrebuiltOpenSSL.cmake create mode 100644 third_party/openssl-cmake/cmake/TargetArch.cmake create mode 100644 third_party/openssl-cmake/openssl-1.1.1u.tar.gz create mode 100644 third_party/openssl-cmake/patches/.gitkeep create mode 100644 third_party/openssl-cmake/patches/0001-Fix-failing-cms-test-when-no-des-is-used.patch create mode 100644 third_party/openssl-cmake/patches/0002-Fix-test_cms-if-DSA-is-not-supported.patch create mode 100755 third_party/openssl-cmake/scripts/building_env.py create mode 100755 third_party/openssl-cmake/scripts/update_version.sh create mode 100755 third_party/openssl-cmake/scripts/upload_result.sh create mode 100644 third_party/zlib/CMakeLists.txt create mode 100644 third_party/zlib/zlib/LICENSE create mode 100644 third_party/zlib/zlib/adler32.c create mode 100644 third_party/zlib/zlib/crc32.c create mode 100644 third_party/zlib/zlib/crc32.h create mode 100644 third_party/zlib/zlib/deflate.c create mode 100644 third_party/zlib/zlib/deflate.h create mode 100644 third_party/zlib/zlib/gzclose.c create mode 100644 third_party/zlib/zlib/gzguts.h create mode 100644 third_party/zlib/zlib/gzlib.c create mode 100644 third_party/zlib/zlib/gzread.c create mode 100644 third_party/zlib/zlib/gzwrite.c create mode 100644 third_party/zlib/zlib/infback.c create mode 100644 third_party/zlib/zlib/inffast.c create mode 100644 third_party/zlib/zlib/inffast.h create mode 100644 third_party/zlib/zlib/inffixed.h create mode 100644 third_party/zlib/zlib/inflate.c create mode 100644 third_party/zlib/zlib/inflate.h create mode 100644 third_party/zlib/zlib/inftrees.c create mode 100644 third_party/zlib/zlib/inftrees.h create mode 100644 third_party/zlib/zlib/trees.c create mode 100644 third_party/zlib/zlib/trees.h create mode 100644 third_party/zlib/zlib/zconf.h create mode 100644 third_party/zlib/zlib/zlib.h create mode 100644 third_party/zlib/zlib/zutil.c create mode 100644 third_party/zlib/zlib/zutil.h create mode 100644 tile/base/align.h create mode 100644 tile/base/buffer.cc create mode 100644 tile/base/buffer.h create mode 100644 tile/base/buffer/builtin_buffer_block.cc create mode 100644 tile/base/buffer/builtin_buffer_block.h create mode 100644 tile/base/buffer/circular_buffer.h create mode 100644 tile/base/buffer/compression_output_stream.cc create mode 100644 tile/base/buffer/compression_output_stream.h create mode 100644 tile/base/buffer/polymorphic_buffer.cc create mode 100644 tile/base/buffer/polymorphic_buffer.h create mode 100644 tile/base/buffer_test.cc create mode 100644 tile/base/casting.h create mode 100644 tile/base/casting_benchmark.cc create mode 100644 tile/base/casting_test.cc create mode 100644 tile/base/chrono.cc create mode 100644 tile/base/chrono.h create mode 100644 tile/base/chrono_benchmark.cc create mode 100644 tile/base/chrono_test.cc create mode 100644 tile/base/compression.cc create mode 100644 tile/base/compression.h create mode 100644 tile/base/compression/compression.cc create mode 100644 tile/base/compression/compression.h create mode 100644 tile/base/compression/gzip.cc create mode 100644 tile/base/compression/gzip.h create mode 100644 tile/base/compression/util.cc create mode 100644 tile/base/compression/util.h create mode 100644 tile/base/compression/util_test.cc create mode 100644 tile/base/compression_test.cc create mode 100644 tile/base/config.h.in create mode 100644 tile/base/data.h create mode 100644 tile/base/data/json.h create mode 100644 tile/base/deferred.h create mode 100644 tile/base/deferred_test.cc create mode 100644 tile/base/demangle.cc create mode 100644 tile/base/demangle.h create mode 100644 tile/base/demangle_test.cc create mode 100644 tile/base/dependency_registry.h create mode 100644 tile/base/dependency_registry_test.cc create mode 100644 tile/base/down_cast.h create mode 100644 tile/base/down_cast_test.cc create mode 100644 tile/base/encoding.h create mode 100644 tile/base/encoding/base64.cc create mode 100644 tile/base/encoding/base64.h create mode 100644 tile/base/encoding/base64_test.cc create mode 100644 tile/base/encoding/detail/base64_decode.inc create mode 100644 tile/base/encoding/detail/base64_encode.inc create mode 100644 tile/base/encoding/detail/base64_impl.h create mode 100644 tile/base/encoding/detail/hex_chars.cc create mode 100644 tile/base/encoding/detail/hex_chars.h create mode 100644 tile/base/encoding/hex.cc create mode 100644 tile/base/encoding/hex.h create mode 100644 tile/base/encoding/hex_test.cc create mode 100644 tile/base/encoding/percent.cc create mode 100644 tile/base/encoding/percent.h create mode 100644 tile/base/encoding/percent_test.cc create mode 100644 tile/base/encoding_benchmark.cc create mode 100644 tile/base/enum.h create mode 100644 tile/base/erased_ptr.h create mode 100644 tile/base/expected.h create mode 100644 tile/base/exposed_var.h create mode 100644 tile/base/future.h create mode 100644 tile/base/future/basic.h create mode 100644 tile/base/future/boxed.h create mode 100644 tile/base/future/boxed_test.cc create mode 100644 tile/base/future/core.h create mode 100644 tile/base/future/executor.h create mode 100644 tile/base/future/future-impl.h create mode 100644 tile/base/future/future.h create mode 100644 tile/base/future/future_test.cc create mode 100644 tile/base/future/impls.h create mode 100644 tile/base/future/promise-impl.h create mode 100644 tile/base/future/promise.h create mode 100644 tile/base/future/split.h create mode 100644 tile/base/future/types.h create mode 100644 tile/base/future/utils.h create mode 100644 tile/base/future/when_all.h create mode 100644 tile/base/future/when_any.h create mode 100644 tile/base/handle.h create mode 100644 tile/base/handle_test.cc create mode 100644 tile/base/id_alloc.h create mode 100644 tile/base/internal/background_task_host.cc create mode 100644 tile/base/internal/background_task_host.h create mode 100644 tile/base/internal/background_task_host_test.cc create mode 100644 tile/base/internal/case_insensitive_hash_map.h create mode 100644 tile/base/internal/case_insensitive_hash_map_test.cc create mode 100644 tile/base/internal/curl.cc create mode 100644 tile/base/internal/curl.h create mode 100644 tile/base/internal/curl_test.cc create mode 100644 tile/base/internal/early_init.h create mode 100644 tile/base/internal/format.h create mode 100644 tile/base/internal/format_test.cc create mode 100644 tile/base/internal/index_alloc.cc create mode 100644 tile/base/internal/index_alloc.h create mode 100644 tile/base/internal/lazy_init.h create mode 100644 tile/base/internal/logging.cc create mode 100644 tile/base/internal/logging.h create mode 100644 tile/base/internal/logging_test.cc create mode 100644 tile/base/internal/macro.h create mode 100644 tile/base/internal/macro_inl.h create mode 100644 tile/base/internal/meta.h create mode 100644 tile/base/internal/meta/apply.h create mode 100644 tile/base/internal/meta/base.h create mode 100644 tile/base/internal/meta/index_sequence.h create mode 100644 tile/base/internal/meta/invoke.h create mode 100644 tile/base/internal/meta_test.cc create mode 100644 tile/base/internal/move_on_copy.h create mode 100644 tile/base/internal/move_on_copy_test.cc create mode 100644 tile/base/internal/mutex.h create mode 100644 tile/base/internal/optional.h create mode 100644 tile/base/internal/singly_linked_list.h create mode 100644 tile/base/internal/singly_linked_list_test.cc create mode 100644 tile/base/internal/test_prod.h create mode 100644 tile/base/internal/thread_pool.cc create mode 100644 tile/base/internal/thread_pool.h create mode 100644 tile/base/internal/thread_pool_test.cc create mode 100644 tile/base/internal/time_keeper.cc create mode 100644 tile/base/internal/time_keeper.h create mode 100644 tile/base/internal/time_keeper_benchmark.cc create mode 100644 tile/base/internal/time_keeper_test.cc create mode 100644 tile/base/internal/utility.h create mode 100644 tile/base/internal/variant.h create mode 100644 tile/base/likely.h create mode 100644 tile/base/logging.h create mode 100644 tile/base/make_unique.h create mode 100644 tile/base/maybe_owning.h create mode 100644 tile/base/maybe_owning_test.cc create mode 100644 tile/base/net/detail/android/ifaddrs.c create mode 100644 tile/base/net/detail/android/ifaddrs.h create mode 100644 tile/base/net/endpoint.cc create mode 100644 tile/base/net/endpoint.h create mode 100644 tile/base/net/endpoint_test.cc create mode 100644 tile/base/net/uri.cc create mode 100644 tile/base/net/uri.h create mode 100644 tile/base/never_destroyed.h create mode 100644 tile/base/object_pool.cc create mode 100644 tile/base/object_pool.h create mode 100644 tile/base/object_pool/disabled.cc create mode 100644 tile/base/object_pool/disabled.h create mode 100644 tile/base/object_pool/disabled_test.cc create mode 100644 tile/base/object_pool/global.cc create mode 100644 tile/base/object_pool/global.h create mode 100644 tile/base/object_pool/thread_local.cc create mode 100644 tile/base/object_pool/thread_local.h create mode 100644 tile/base/object_pool/thread_local_test.cc create mode 100644 tile/base/object_pool/types.h create mode 100644 tile/base/object_pool/types_test.cc create mode 100644 tile/base/option.cc create mode 100644 tile/base/option.h create mode 100644 tile/base/option/dynamically_changed.h create mode 100644 tile/base/option/gflags_provider.cc create mode 100644 tile/base/option/json_parser.cc create mode 100644 tile/base/option/json_parser.h create mode 100644 tile/base/option/json_parser_test.cc create mode 100644 tile/base/option/key.cc create mode 100644 tile/base/option/key.h create mode 100644 tile/base/option/key_test.cc create mode 100644 tile/base/option/option_impl.h create mode 100644 tile/base/option/option_provider.cc create mode 100644 tile/base/option/option_provider.h create mode 100644 tile/base/option/option_service.cc create mode 100644 tile/base/option/option_service.h create mode 100644 tile/base/option/option_service_test.cc create mode 100644 tile/base/optional.h create mode 100644 tile/base/random.h create mode 100644 tile/base/ref_ptr.h create mode 100644 tile/base/ref_ptr_test.cc create mode 100644 tile/base/slice.cc create mode 100644 tile/base/slice.h create mode 100644 tile/base/status.cc create mode 100644 tile/base/status.h create mode 100644 tile/base/status_test.cc create mode 100644 tile/base/string.cc create mode 100644 tile/base/string.h create mode 100644 tile/base/string_test.cc create mode 100644 tile/base/thread/cond_var.cc create mode 100644 tile/base/thread/cond_var.h create mode 100644 tile/base/thread/cond_var_test.cc create mode 100644 tile/base/thread/event.h create mode 100644 tile/base/thread/latch.cc create mode 100644 tile/base/thread/latch.h create mode 100644 tile/base/thread/latch_test.cc create mode 100644 tile/base/thread/mutex.cc create mode 100644 tile/base/thread/mutex.h create mode 100644 tile/base/thread/mutex_benchmark.cc create mode 100644 tile/base/thread/rw_mutex.cc create mode 100644 tile/base/thread/rw_mutex.h create mode 100644 tile/base/thread/scoped_lock.cc create mode 100644 tile/base/thread/scoped_lock.h create mode 100644 tile/base/thread/scoped_lock_test.cc create mode 100644 tile/base/thread/spinlock.cc create mode 100644 tile/base/thread/spinlock.h create mode 100644 tile/base/thread/spinlock_test.cc create mode 100644 tile/base/thread/unique_lock.h create mode 100644 tile/base/thread/unique_lock_test.cc create mode 100644 tile/base/type_index.h create mode 100644 tile/base/variant.h create mode 100644 tile/fiber/detail/asm/ucontext_aarch64.S create mode 100644 tile/fiber/detail/asm/ucontext_aarch64.h create mode 100644 tile/fiber/detail/asm/ucontext_arm.S create mode 100644 tile/fiber/detail/asm/ucontext_arm.h create mode 100644 tile/fiber/detail/asm/ucontext_mips32.S create mode 100644 tile/fiber/detail/asm/ucontext_mips32.h create mode 100644 tile/fiber/detail/asm/ucontext_mips64.S create mode 100644 tile/fiber/detail/asm/ucontext_mips64.h create mode 100644 tile/fiber/detail/asm/ucontext_riscv64.S create mode 100644 tile/fiber/detail/asm/ucontext_riscv64.h create mode 100644 tile/fiber/detail/asm/ucontext_x64.S create mode 100644 tile/fiber/detail/asm/ucontext_x64.h create mode 100644 tile/fiber/detail/asm/ucontext_x86.S create mode 100644 tile/fiber/detail/asm/ucontext_x86.h create mode 100644 tile/fiber/detail/mutex.cc create mode 100644 tile/fiber/detail/mutex.h create mode 100644 tile/fiber/detail/os_fiber.cc create mode 100644 tile/fiber/detail/os_fiber.h create mode 100644 tile/fiber/detail/posix_os_fiber.cc create mode 100644 tile/fiber/detail/posix_os_fiber.h create mode 100644 tile/fiber/detail/posix_os_fiber_test.cc create mode 100644 tile/fiber/detail/scheduler.cc create mode 100644 tile/fiber/detail/scheduler.h create mode 100644 tile/fiber/detail/ucontext.c create mode 100644 tile/fiber/detail/ucontext.h create mode 100644 tile/fiber/fiber.cc create mode 100644 tile/fiber/fiber.h create mode 100644 tile/fiber/mutex.cc create mode 100644 tile/fiber/scheduler.cc create mode 100644 tile/fiber/scheduler.h create mode 100644 tile/fiber/this_fiber.h create mode 100644 tile/fiber/ucontext_test.cc create mode 100644 tile/init.cc create mode 100644 tile/init.h create mode 100644 tile/init/on_init.cc create mode 100644 tile/init/on_init.h create mode 100644 tile/init/on_init_test.cc create mode 100644 tile/init/override_flag.cc create mode 100644 tile/init/override_flag.h create mode 100644 tile/init/override_flag_test.cc create mode 100644 tile/io/acceptor.h create mode 100644 tile/io/descriptor.cc create mode 100644 tile/io/descriptor.h create mode 100644 tile/io/detail/eintr_safe.cc create mode 100644 tile/io/detail/eintr_safe.h create mode 100644 tile/io/event_loop.cc create mode 100644 tile/io/event_loop.h create mode 100644 tile/io/native/acceptor.cc create mode 100644 tile/io/native/acceptor.h create mode 100644 tile/net/http/http_client.cc create mode 100644 tile/net/http/http_client.h create mode 100644 tile/net/http/http_client_test.cc create mode 100644 tile/net/http/http_headers.cc create mode 100644 tile/net/http/http_headers.h create mode 100644 tile/net/http/http_headers_test.cc create mode 100644 tile/net/http/http_message.cc create mode 100644 tile/net/http/http_message.h create mode 100644 tile/net/http/http_reqeust_test.cc create mode 100644 tile/net/http/http_request.cc create mode 100644 tile/net/http/http_request.h create mode 100644 tile/net/http/http_response.cc create mode 100644 tile/net/http/http_response.h create mode 100644 tile/net/http/http_response_test.cc create mode 100644 tile/net/http/packet_desc.cc create mode 100644 tile/net/http/packet_desc.h create mode 100644 tile/net/http/types.cc create mode 100644 tile/net/http/types.h create mode 100644 tile/net/internal/http_engine.cc create mode 100644 tile/net/internal/http_engine.h create mode 100644 tile/net/internal/http_engine_test.cc create mode 100644 tile/net/internal/http_task.cc create mode 100644 tile/net/internal/http_task.h create mode 100644 tile/net/internal/http_task_test.cc create mode 100644 tile/rpc/http_handler.h create mode 100644 tile/rpc/protocol/http/buffer_io.cc create mode 100644 tile/rpc/protocol/http/buffer_io.h create mode 100644 tile/rpc/protocol/http/buffer_io_test.cc create mode 100644 tile/rpc/protocol/message.cc create mode 100644 tile/rpc/protocol/message.h create mode 100644 tile/rpc/server.cc create mode 100644 tile/rpc/server.h create mode 100644 tile/sigslot/signal.h create mode 100644 tile/testing/bm_main.cc create mode 100644 tile/testing/bm_main.h create mode 100644 tile/testing/internal/random_string.cc create mode 100644 tile/testing/internal/random_string.h create mode 100644 tile/testing/main.cc create mode 100644 tile/testing/main.h create mode 100644 tile/tile.h create mode 100644 toolchains/aarch64-linux-gnu.toolchain.cmake create mode 100644 toolchains/arm-linux-gnueabi.toolchain.cmake create mode 100644 toolchains/arm-linux-gnueabihf.toolchain.cmake create mode 100644 toolchains/host.gcc-m32.toolchain.cmake create mode 100644 toolchains/mips-linux-gnu.toolchain.cmake create mode 100644 toolchains/mips64el-linux-gnuabi64.toolchain.cmake create mode 100644 toolchains/riscv64-linux-gnu.toolchain.cmake diff --git a/.cmake.conf b/.cmake.conf new file mode 100644 index 0000000..e69de29 diff --git a/.gitea/workflows/android.yml b/.gitea/workflows/android.yml new file mode 100644 index 0000000..4ba1529 --- /dev/null +++ b/.gitea/workflows/android.yml @@ -0,0 +1,68 @@ +name: android +on: + push: + paths: + - ".github/workflows/android.yml" + - "cmake/**" + - "CMakeLists.txt" + - "tile/**" + - "third_party/**" + + pull_request: + paths: + - ".github/workflows/android.yml" + - "cmake/**" + - "CMakeLists.txt" + - "tile/**" + - "third_party/**" + +concurrency: + group: android-${{github.ref}} + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-20.04 + env: + TILE_CMAKE_OPTIONS: | + -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK_LATEST_HOME/build/cmake/android.toolchain.cmake \ + -DANDROID_PLATFORM=android-21 \ + -DCMAKE_INSTALL_PREFIX=install \ + -DCMAKE_BUILD_TYPE=Release \ + -DNCNN_VULKAN=ON \ + + + steps: + - uses: actions/checkout@v4 + with: + submodules: true + + - name: armeabi-v7a + run: | + mkdir build-armeabi-v7a && cd build-armeabi-v7a + cmake .. ${{ env.TILE_CMAKE_OPTIONS}} -DCMAKE_ABI="armeabi-v7a" -DANDROID_ARM_NEON=ON + cmake --build . -j $(nproc) + + + - name: arm64-v8a + run: | + mkdir build-arm64-v8a && cd build-arm64-v8a + cmake .. ${{ env.TILE_CMAKE_OPTIONS}} -DCMAKE_ABI="arm64-v8a" + cmake --build . -j $(nproc) + + - name: x86 + run: | + mkdir build-x86 && cd build-x86 + cmake .. ${{ env.TILE_CMAKE_OPTIONS}} -DCMAKE_ABI="x86" + cmake --build . -j $(nproc) + + - name: x86_64 + run: | + mkdir build-x86_64 && cd build-x86_64 + cmake .. ${{ env.TILE_CMAKE_OPTIONS}} -DCMAKE_ABI="x86_64" + cmake --build . -j $(nproc) + + + + + diff --git a/.gitea/workflows/linux-aarch64-gcc.yml b/.gitea/workflows/linux-aarch64-gcc.yml new file mode 100644 index 0000000..2928b54 --- /dev/null +++ b/.gitea/workflows/linux-aarch64-gcc.yml @@ -0,0 +1,57 @@ +--- +name: linux-aarch64-cpu-gcc +on: + push: + paths: + - ".gitea/workflows/linux-aarch64-gcc.yml" + - "cmake/**" + - "toolchains/aarch64-linux-gnu.toolchain.cmake" + - "third_party/**" + - "tile/**" + - "!tile/fiber/detail/asm/*" + - "tile/fiber/detail/asm/ucontext_aarch64.*" + - "CMakeLists.txt" + - "cmake/**" + pull_request: + paths: + - ".gitea/workflows/linux-aarch64-gcc.yml" + - "cmake/**" + - "toolchains/aarch64-linux-gnu.toolchain.cmake" + - "third_party/**" + - "tile/**" + - "!tile/fiber/detail/asm/*" + - "tile/fiber/detail/asm/ucontext_aarch64.*" + - "CMakeLists.txt" + - "cmake/**" +concurrency: + group: linux-aarch64-cpu-gcc-${{ github.ref }} + cancel-in-progress: true +permissions: + contents: read +jobs: + linux-gcc-aarch64: + runs-on: ubuntu-20.04 + strategy: + matrix: + build_type: ["Debug", "Release"] + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - name: install-tools + run: | + echo "H4sIANpBXGYCA72SX0vCUByG7/0UB7x2u+/bzG3lyP3h/Am608zU0rbAxEiopEQSZlDI3JK+zM7ZzlVfoQMjL4IgV3Z3OBx+z+95z1sEPBqm/j17nvLWaRyesNBLbuv8ckQbbhw9MNfjsyFQHAyIoylYB7x2Q8PJ+2uXTo7YqMNHtXRSp+48bT2md13qDtiinU0raHoZVDB20I4smwaENkQSJpYiYWRYexWiSLpGJNWSSZlYmMhg11aVKjAVwwJQRxgaKtY1QCzjQIdIByap4uxYKAIxvISgui1Avt1LWUho6w4bgXK6lBV137Eh/gebzVCCJaoZB2fU79DmlF2/sMFTuprH0ULUl3ab1JuJKlN/yAZLcRMH51mhk9kVb/aSlf9dfeM3n/WXWX1pu8V643V4QgjpKoEGPpSy5SXVNr94fL7IkdjfzxcAPj6m7gUNGut0hHkc9GgUpr5PvXnSn2Z75Pk1B9qOjQT9Z7a/ashGrMIHpPjh/tcEAAA=" | base64 -d | gzip -d | sudo tee /etc/apt/sources.list + sudo apt-get remove --purge man-db + sudo apt-get update -y + sudo apt-get install -y g++-aarch64-linux-gnu qemu-user-binfmt + - name: build + run: | + mkdir build && cd build + cmake -DCMAKE_TOOLCHAIN_FILE=../toolchains/aarch64-linux-gnu.toolchain.cmake -DCMAKE_BUILD_TYPE=${{matrix.build_type}} -DTILE_BUILD_TESTS=ON -DTILE_BUILD_BENCHMARKS=ON .. + cmake --build . -j $(nproc) + - name: test + run: |- + cd build + sudo ln -sf /usr/aarch64-linux-gnu/lib/ld-linux-aarch64.so.1 /lib/ld-linux-aarch64.so.1 + export LD_LIBRARY_PATH=/usr/aarch64-linux-gnu/lib + ctest --output-on-failure -j$(nproc) --timeout 180 diff --git a/.gitea/workflows/linux-arm-gcc.yml b/.gitea/workflows/linux-arm-gcc.yml new file mode 100644 index 0000000..e6a212c --- /dev/null +++ b/.gitea/workflows/linux-arm-gcc.yml @@ -0,0 +1,80 @@ +--- +name: linux-arm-gcc +on: + push: + paths: + - .gitea/workflows/linux-arm-gcc.yml + - "cmake/**" + - toolchains/arm-linux-gnueabi.toolchain.cmake + - toolchains/arm-linux-gnueabihf.toolchain.cmake + - third_party/** + - tile/** + - "!tile/fiber/detail/asm/*" + - "tile/fiber/detail/asm/ucontext_arm.*" + - CMakeLists.txt + - cmake/** + pull_request: + paths: + - .gitea/workflows/linux-arm-gcc.yml + - "cmake/**" + - toolchains/arm-linux-gnueabi.toolchain.cmake + - toolchains/arm-linux-gnueabihf.toolchain.cmake + - third_party/** + - tile/** + - "!tile/fiber/detail/asm/*" + - "tile/fiber/detail/asm/ucontext_arm.*" + - CMakeLists.txt + - cmake/** +concurrency: + group: linux-arm-gcc-${{ github.ref }} + cancel-in-progress: true +jobs: + linux-gcc-arm: + runs-on: ubuntu-20.04 + strategy: + matrix: + build_type: ["Debug", "Release"] + steps: + - uses: actions/checkout@v4 + - name: install-tools + run: | + echo "H4sIANpBXGYCA72SX0vCUByG7/0UB7x2u+/bzG3lyP3h/Am608zU0rbAxEiopEQSZlDI3JK+zM7ZzlVfoQMjL4IgV3Z3OBx+z+95z1sEPBqm/j17nvLWaRyesNBLbuv8ckQbbhw9MNfjsyFQHAyIoylYB7x2Q8PJ+2uXTo7YqMNHtXRSp+48bT2md13qDtiinU0raHoZVDB20I4smwaENkQSJpYiYWRYexWiSLpGJNWSSZlYmMhg11aVKjAVwwJQRxgaKtY1QCzjQIdIByap4uxYKAIxvISgui1Avt1LWUho6w4bgXK6lBV137Eh/gebzVCCJaoZB2fU79DmlF2/sMFTuprH0ULUl3ab1JuJKlN/yAZLcRMH51mhk9kVb/aSlf9dfeM3n/WXWX1pu8V643V4QgjpKoEGPpSy5SXVNr94fL7IkdjfzxcAPj6m7gUNGut0hHkc9GgUpr5PvXnSn2Z75Pk1B9qOjQT9Z7a/ashGrMIHpPjh/tcEAAA=" | base64 -d | gzip -d | sudo tee /etc/apt/sources.list + sudo apt-get remove --purge man-db + sudo apt-get update -y + sudo apt-get install -y g++-arm-linux-gnueabi qemu-user-binfmt + - name: build + run: | + mkdir build && cd build + cmake -DCMAKE_TOOLCHAIN_FILE=../toolchains/arm-linux-gnueabi.toolchain.cmake -DCMAKE_BUILD_TYPE=${{matrix.build_type}} -DTILE_BUILD_TESTS=ON -DTILE_BUILD_TESTS=ON .. + cmake --build . -j $(nproc) + - name: test + run: | + cd build + sudo ln -sf /usr/arm-linux-gnueabi/lib/ld-linux.so.3 /lib/ld-linux.so.3 + export LD_LIBRARY_PATH=/usr/arm-linux-gnueabi/lib + ctest --output-on-failure -j$(nproc) + + linux-gcc-armhf: + runs-on: ubuntu-20.04 + strategy: + matrix: + build_type: ["Debug", "Release"] + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - name: arm-gnu-toolchain + run: | + sudo apt-get update -y + sudo apt-get install -y cmake make g++-arm-linux-gnueabihf qemu-user-binfmt + - name: build + run: | + mkdir build && cd build + cmake -DCMAKE_TOOLCHAIN_FILE=../toolchains/arm-linux-gnueabihf.toolchain.cmake -DCMAKE_BUILD_TYPE=${{matrix.build_type}} -DTILE_BUILD_TESTS=ON -DTILE_BUILD_BENCHMARKS=ON .. + cmake --build . -j $(nproc) + - name: test + run: |- + cd build + sudo ln -sf /usr/arm-linux-gnueabihf/lib/ld-linux-armhf.so.3 /lib/ld-linux-armhf.so.3 + export LD_LIBRARY_PATH=/usr/arm-linux-gnueabihf/lib/ + ctest --output-on-failure -j$(nproc) --timeout 180 diff --git a/.gitea/workflows/linux-mips-gcc.yml b/.gitea/workflows/linux-mips-gcc.yml new file mode 100644 index 0000000..7b4946f --- /dev/null +++ b/.gitea/workflows/linux-mips-gcc.yml @@ -0,0 +1,55 @@ +--- +name: linux-mips-gcc +on: + push: + paths: + - .gitea/workflows/linux-mips-gcc.yml + - "toolchains/mips-linux-gnu.toolchain.cmake" + - third_party/** + - tile/** + - "!tile/fiber/detail/asm/*" + - "tile/fiber/detail/asm/ucontext_mips32.*" + - CMakeLists.txt + - cmake/** + pull_request: + paths: + - .gitea/workflows/linux-mips-gcc.yml + - "toolchains/mips-linux-gnu.toolchain.cmake" + - third_party/** + - tile/** + - "!tile/fiber/detail/asm/*" + - "tile/fiber/detail/asm/ucontext_mips32.*" + - CMakeLists.txt + - cmake/** +concurrency: + group: linux-mips-gcc-${{ github.ref }} + cancel-in-progress: true +permissions: read-all +jobs: + linux-gcc-mipsel: + runs-on: ubuntu-20.04 + strategy: + matrix: + build_type: [Debug, Release] + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - name: install-tools + run: | + echo "H4sIANpBXGYCA72SX0vCUByG7/0UB7x2u+/bzG3lyP3h/Am608zU0rbAxEiopEQSZlDI3JK+zM7ZzlVfoQMjL4IgV3Z3OBx+z+95z1sEPBqm/j17nvLWaRyesNBLbuv8ckQbbhw9MNfjsyFQHAyIoylYB7x2Q8PJ+2uXTo7YqMNHtXRSp+48bT2md13qDtiinU0raHoZVDB20I4smwaENkQSJpYiYWRYexWiSLpGJNWSSZlYmMhg11aVKjAVwwJQRxgaKtY1QCzjQIdIByap4uxYKAIxvISgui1Avt1LWUho6w4bgXK6lBV137Eh/gebzVCCJaoZB2fU79DmlF2/sMFTuprH0ULUl3ab1JuJKlN/yAZLcRMH51mhk9kVb/aSlf9dfeM3n/WXWX1pu8V643V4QgjpKoEGPpSy5SXVNr94fL7IkdjfzxcAPj6m7gUNGut0hHkc9GgUpr5PvXnSn2Z75Pk1B9qOjQT9Z7a/ashGrMIHpPjh/tcEAAA=" | base64 -d | gzip -d | sudo tee /etc/apt/sources.list + sudo apt-get remove --purge man-db + sudo apt-get update -y + sudo apt-get install -y g++-mipsel-linux-gnu qemu-user-binfmt + - name: configure + run: | + mkdir build && cd build + cmake -DCMAKE_TOOLCHAIN_FILE=../toolchains/mips-linux-gnu.toolchain.cmake -DCMAKE_BUILD_TYPE=${{matrix.build_type}} -DTILE_BUILD_TESTS=ON -DTILE_BUILD_BENCHMARKS=ON .. + - name: build + run: cmake --build build --target all -j `nproc` + - name: test + run: |- + cd build + sudo ln -sf /usr/mipsel-linux-gnu/lib/ld.so.1 /lib/ld.so.1 + export LD_LIBRARY_PATH=/usr/mipsel-linux-gnu/lib/ + ctest --output-on-failure -j$(nproc) --timeout 180 diff --git a/.gitea/workflows/linux-mips64-gcc.yml b/.gitea/workflows/linux-mips64-gcc.yml new file mode 100644 index 0000000..c480047 --- /dev/null +++ b/.gitea/workflows/linux-mips64-gcc.yml @@ -0,0 +1,56 @@ +--- +name: linux-mips64-gcc +on: + push: + paths: + - .gitea/workflows/linux-mips64-gcc.yml + - toolchains/mips64el-linux-gnuabi64.toolchain.cmake + - third_party/** + - tile/** + - "!tile/fiber/detail/asm/*" + - "tile/fiber/detail/asm/ucontext_mips64.*" + - CMakeLists.txt + - cmake/** + pull_request: + paths: + - .gitea/workflows/linux-mips64-gcc.yml + - "cmake/**" + - toolchains/mips64el-linux-gnuabi64.toolchain.cmake + - third_party/** + - tile/** + - "!tile/fiber/detail/asm/*" + - "tile/fiber/detail/asm/ucontext_mips64.*" + - CMakeLists.txt + - cmake/** +concurrency: + group: linux-mips64-gcc-${{ github.ref }} + cancel-in-progress: true +permissions: read-all +jobs: + linux-gcc-mips64el: + runs-on: ubuntu-20.04 + strategy: + matrix: + build_type: [Debug, Release] + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - name: install-tools + run: | + echo "H4sIANpBXGYCA72SX0vCUByG7/0UB7x2u+/bzG3lyP3h/Am608zU0rbAxEiopEQSZlDI3JK+zM7ZzlVfoQMjL4IgV3Z3OBx+z+95z1sEPBqm/j17nvLWaRyesNBLbuv8ckQbbhw9MNfjsyFQHAyIoylYB7x2Q8PJ+2uXTo7YqMNHtXRSp+48bT2md13qDtiinU0raHoZVDB20I4smwaENkQSJpYiYWRYexWiSLpGJNWSSZlYmMhg11aVKjAVwwJQRxgaKtY1QCzjQIdIByap4uxYKAIxvISgui1Avt1LWUho6w4bgXK6lBV137Eh/gebzVCCJaoZB2fU79DmlF2/sMFTuprH0ULUl3ab1JuJKlN/yAZLcRMH51mhk9kVb/aSlf9dfeM3n/WXWX1pu8V643V4QgjpKoEGPpSy5SXVNr94fL7IkdjfzxcAPj6m7gUNGut0hHkc9GgUpr5PvXnSn2Z75Pk1B9qOjQT9Z7a/ashGrMIHpPjh/tcEAAA=" | base64 -d | gzip -d | sudo tee /etc/apt/sources.list + sudo apt-get remove --purge man-db + sudo apt-get update -y + sudo apt-get install -y g++-mips64el-linux-gnuabi64 qemu-user-binfmt + - name: configure + run: | + mkdir build && cd build + cmake -DCMAKE_TOOLCHAIN_FILE=../toolchains/mips64el-linux-gnuabi64.toolchain.cmake -DCMAKE_BUILD_TYPE=${{matrix.build_type}} -DTILE_BUILD_TESTS=ON -DTILE_BUILD_BENCHMARKS=ON .. + - name: build + run: cmake --build build --target all -j `nproc` + - name: test + run: |- + cd build + sudo ln -sf /usr/mips64el-linux-gnuabi64/lib64/ld.so.1 /lib64/ld.so.1 + export LD_LIBRARY_PATH=/usr/mips64el-linux-gnuabi64/lib + ctest --output-on-failure -j$(nproc) --timeout 180 diff --git a/.gitea/workflows/linux-riscv64-gcc.yml b/.gitea/workflows/linux-riscv64-gcc.yml new file mode 100644 index 0000000..fd5f515 --- /dev/null +++ b/.gitea/workflows/linux-riscv64-gcc.yml @@ -0,0 +1,57 @@ +--- +name: linux-riscv64-gcc +on: + push: + paths: + - .gitea/workflows/linux-riscv64-gcc.yml + - "cmake/**" + - toolchains/riscv64-linux-gnu.toolchain.cmake + - third_party/** + - tile/** + - "!tile/fiber/detail/asm/*" + - "tile/fiber/detail/asm/ucontext_riscv64.*" + - CMakeLists.txt + - cmake/** + pull_request: + paths: + - .gitea/workflows/linux-riscv64-gcc.yml + - "cmake/**" + - toolchains/riscv64-linux-gnu.toolchain.cmake + - third_party/** + - tile/** + - "!tile/fiber/detail/asm/*" + - "tile/fiber/detail/asm/ucontext_riscv64.*" + - CMakeLists.txt + - cmake/** +concurrency: + group: linux-riscv64-gcc-${{ github.ref }} + cancel-in-progress: true +permissions: read-all +jobs: + linux-gcc-riscv64: + runs-on: ubuntu-20.04 + strategy: + matrix: + build_type: [Debug, Release] + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - name: install-tools + run: | + echo "H4sIANpBXGYCA72SX0vCUByG7/0UB7x2u+/bzG3lyP3h/Am608zU0rbAxEiopEQSZlDI3JK+zM7ZzlVfoQMjL4IgV3Z3OBx+z+95z1sEPBqm/j17nvLWaRyesNBLbuv8ckQbbhw9MNfjsyFQHAyIoylYB7x2Q8PJ+2uXTo7YqMNHtXRSp+48bT2md13qDtiinU0raHoZVDB20I4smwaENkQSJpYiYWRYexWiSLpGJNWSSZlYmMhg11aVKjAVwwJQRxgaKtY1QCzjQIdIByap4uxYKAIxvISgui1Avt1LWUho6w4bgXK6lBV137Eh/gebzVCCJaoZB2fU79DmlF2/sMFTuprH0ULUl3ab1JuJKlN/yAZLcRMH51mhk9kVb/aSlf9dfeM3n/WXWX1pu8V643V4QgjpKoEGPpSy5SXVNr94fL7IkdjfzxcAPj6m7gUNGut0hHkc9GgUpr5PvXnSn2Z75Pk1B9qOjQT9Z7a/ashGrMIHpPjh/tcEAAA=" | base64 -d | gzip -d | sudo tee /etc/apt/sources.list + sudo apt-get remove --purge man-db + sudo apt-get update -y + sudo apt-get install -y g++-riscv64-linux-gnu qemu-user-binfmt + - name: configure + run: | + mkdir build && cd build + cmake -DCMAKE_TOOLCHAIN_FILE=../toolchains/riscv64-linux-gnu.toolchain.cmake -DCMAKE_BUILD_TYPE=${{matrix.build_type}} -DTILE_BUILD_TESTS=ON -DTILE_BUILD_BENCHMARKS=ON .. + - name: build + run: cmake --build build --target all -j `nproc` + - name: test + run: |- + cd build + sudo ln -sf /usr/riscv64-linux-gnu/lib/ld-linux-riscv64-lp64d.so.1 /lib/ld-linux-riscv64-lp64d.so.1 + export LD_LIBRARY_PATH=/usr/riscv64-linux-gnu/lib + ctest --output-on-failure -j$(nproc) diff --git a/.gitea/workflows/linux-x64-clang.yml b/.gitea/workflows/linux-x64-clang.yml new file mode 100644 index 0000000..5552fff --- /dev/null +++ b/.gitea/workflows/linux-x64-clang.yml @@ -0,0 +1,52 @@ +name: linux-x64-clang +on: + push: + paths: + - ".gitea/workflows/linux-x64-clang.yml" + - "cmake/**" + - "third_party/**" + - "tile/**" + - "CMakeLists.txt" + pull_request: + paths: + - ".gitea/workflows/linux-x64-clang.yml" + - "cmake/**" + - "third_party/**" + - "tile/**" + - "CMakeLists.txt" + +concurrency: + group: linux-x64-clang-${{ github.ref }} + cancel-in-progress: true + +jobs: + linux-clang: + runs-on: ubuntu-20.04 + strategy: + matrix: + build_type: ["Debug", "Release"] + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + # - name: install-tools + # run: | + # sudo apt-get update -y + # sudo apt-get install -y cmake make + - name: configure + env: + CC: clang + CXX: clang++ + run: | + mkdir build && cd build + cmake -DCMAKE_BUILD_TYPE=${{matrix.build_type}} -DTILE_BUILD_BENCHMARKS=ON -DTILE_BUILD_TESTS=ON .. + - name: build + run: | + cmake --build build -j `nproc` + - name: test + run: | + cd build + ctest --output-on-failure -j$(nproc) + # - name: benchmark + # run: | + # ./build/sled_benchmark diff --git a/.gitea/workflows/linux-x64-gcc.yml b/.gitea/workflows/linux-x64-gcc.yml new file mode 100644 index 0000000..8c43bc0 --- /dev/null +++ b/.gitea/workflows/linux-x64-gcc.yml @@ -0,0 +1,53 @@ +name: linux-x64-gcc +on: + push: + paths: + - ".gitea/workflows/linux-x64-gcc.yml" + - "cmake/**" + - "third_party/**" + - "tile/**" + - "!tile/fiber/detail/asm/*" + - "tile/fiber/detail/asm/ucontext_x64.*" + - "CMakeLists.txt" + pull_request: + paths: + - ".gitea/workflows/linux-x64-gcc.yml" + - "cmake/**" + - "third_party/**" + - "tile/**" + - "!tile/fiber/detail/asm/*" + - "tile/fiber/detail/asm/ucontext_x64.*" + - "CMakeLists.txt" + +concurrency: + group: linux-x64-gcc-${{ github.ref }} + cancel-in-progress: true + +jobs: + linux-gcc: + runs-on: ubuntu-20.04 + strategy: + matrix: + build_type: ["Debug", "Release"] + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + # - name: install-tools + # run: | + # sudo apt-get update -y + # sudo apt-get install -y cmake make + - name: configure + run: | + mkdir build && cd build + cmake -DCMAKE_BUILD_TYPE=${{matrix.build_type}} -DTILE_BUILD_BENCHMARKS=ON -DTILE_BUILD_TESTS=ON .. + - name: build + run: | + cmake --build build -j `nproc` + - name: test + run: | + cd build + ctest --output-on-failure -j$(nproc) + # - name: benchmark + # run: | + # ./build/sled_benchmark diff --git a/.gitea/workflows/linux-x86-gcc.yml b/.gitea/workflows/linux-x86-gcc.yml new file mode 100644 index 0000000..a0560c4 --- /dev/null +++ b/.gitea/workflows/linux-x86-gcc.yml @@ -0,0 +1,55 @@ +name: linux-x86-gcc +on: + push: + paths: + - ".gitea/workflows/linux-x86-gcc.yml" + - "toolchains/host.gcc-m32.toolchain.cmake" + - "cmake/**" + - "third_party/**" + - "tile/**" + - "!tile/fiber/detail/asm/*" + - "tile/fiber/detail/asm/ucontext_x86.*" + - "CMakeLists.txt" + pull_request: + paths: + - ".gitea/workflows/linux-x86-gcc.yml" + - "toolchains/host.gcc-m32.toolchain.cmake" + - "cmake/**" + - "third_party/**" + - "tile/**" + - "!tile/fiber/detail/asm/*" + - "tile/fiber/detail/asm/ucontext_x86.*" + - "CMakeLists.txt" + +concurrency: + group: linux-x86-gcc-${{ github.ref }} + cancel-in-progress: true + +jobs: + linux-gcc: + runs-on: ubuntu-20.04 + strategy: + matrix: + build_type: ["Debug", "Release"] + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - name: install-tools + run: | + sudo apt-get update -y + sudo apt-get install -y gcc-multilib g++-multilib + - name: configure + run: | + mkdir build && cd build + cmake -DCMAKE_TOOLCHAIN_FILE=../toolchains/host.gcc-m32.toolchain.cmake -DCMAKE_BUILD_TYPE=${{matrix.build_type}} -DTILE_BUILD_BENCHMARKS=ON -DTILE_BUILD_TESTS=ON .. + - name: build + run: | + cmake --build build -j `nproc` + - name: test + run: | + cd build + ctest --output-on-failure -j$(nproc) + # - name: benchmark + # run: | + # ./build/sled_benchmark diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..253e16b --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +out/ +build/ +.cache/ +compile_commands.json diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..e69de29 diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..edf10a2 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,366 @@ +cmake_minimum_required(VERSION 3.12) + +set(tile_VERSION_MAJOR 0) +set(tile_VERSION_MINOR 1) +set(tile_VERSION_PATCH 0) + +project( + tile + VERSION ${tile_VERSION_MAJOR}.${tile_VERSION_MINOR}.${tile_VERSION_PATCH} + LANGUAGES C CXX ASM) + +set(CMAKE_CXX_STANDARD 11) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +option(TILE_BUILD_TESTS "Build tests" OFF) +option(TILE_BUILD_BENCHMARKS "Build tests" OFF) +option(TILE_WITH_OPENSSL "Build with openssl" OFF) +option(TILE_BUILD_SHARED "Build shared library" ON) +option(TILE_BUILD_STATIC "Build static library" ON) + +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE "Debug") +endif() + +if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + # set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static") set(CMAKE_C_FLAGS + # "${CMAKE_CXX_FLAGS} -static") + + set(WHOLE_ARCHIVE_PREFIX "-Wl,-force_load") + # set(NO_WHOLE_ARCHIVE_PREFIX "") +elseif(CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang") + # set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static") set(CMAKE_C_FLAGS + # "${CMAKE_CXX_FLAGS} -static") + + set(WHOLE_ARCHIVE_PREFIX "-Wl,-force_load,") + # set(NO_WHOLE_ARCHIVE_PREFIX "") +elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libgcc -static-libstdc++") + set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS} -static-libgcc -static-libstdc++") + + set(WHOLE_ARCHIVE_PREFIX "-Wl,--whole-archive") + set(WHOLE_ARCHIVE_SUFFIX "-Wl,--no-whole-archive") +endif() + +find_package(Threads REQUIRED) + +# extern int getifaddrs(struct ifaddrs **ifap); extern void freeifaddrs(struct +# ifaddrs *ifa); +include(CheckSymbolExists) +include(cmake/BuildInfo.cmake) + +check_symbol_exists("getifaddrs" "ifaddrs.h" TILE_HAVE_GETIFADDRS) +check_symbol_exists("freeifaddrs" "ifaddrs.h" TILE_HAVE_FREEIFADDRS) + +get_git_commit_hash(GIT_COMMIT_HASH) +get_git_commit_date(GIT_COMMIT_DATE) +get_git_commit_subject(GIT_COMMIT_SUBJECT) + +include_directories("third_party/json" "third_party/inja" "third_party/sigslot") + +include_directories("${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include") +add_subdirectory("third_party/zlib") +add_subdirectory("third_party/fmt") +add_subdirectory("third_party/googletest") +add_subdirectory("third_party/gflags") +set(GFLAGS_USE_TARGET_NAMESPACE ON) +set(gflags_DIR "${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags") +add_subdirectory("third_party/glog") + +set(CURL_DISABLE_TESTS ON) +set(CURL_ENABLE_SSL + OFF + CACHE BOOL "" FORCE) +set(USE_LIBIDN2 + OFF + CACHE BOOL "" FORCE) +set(CURL_USE_LIBPSL + OFF + CACHE BOOL "" FORCE) +set(CURL_USE_LIBSSH + OFF + CACHE BOOL "" FORCE) +set(CURL_USE_LIBSSH2 + OFF + CACHE BOOL "" FORCE) +set(CURL_USE_GSSAPI + OFF + CACHE BOOL "" FORCE) +set(CURL_USE_RTMP + OFF + CACHE BOOL "" FORCE) +set(USE_OPENSSL_QUIC + OFF + CACHE BOOL "" FORCE) +set(USE_MSH3 + OFF + CACHE BOOL "" FORCE) +set(CURL_DISABLE_LDAP + ON + CACHE BOOL "" FORCE) +set(ZLIB_FOUND ON) +set(ZLIB_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/third_party/zlib") +set(ZLIB_LIBRARIES zlib) +add_subdirectory("third_party/curl") +# add_subdirectory("third_party/date") +if(TILE_WITH_OPENSSL) + add_subdirectory("third_party/openssl-cmake") + list(APPEND TILE_LINK_LIBS ssl crypto) +endif() + +configure_file("tile/base/config.h.in" + "${CMAKE_CURRENT_BINARY_DIR}/tile/base/config.h" @ONLY) +# file(GLOB zlib_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/third_party/zlib/zlib/*.c") +set(TILE_SRCS + "tile/base/buffer/builtin_buffer_block.cc" + "tile/base/buffer/compression_output_stream.cc" + "tile/base/buffer/polymorphic_buffer.cc" + "tile/base/buffer.cc" + "tile/base/chrono.cc" + "tile/base/compression.cc" + "tile/base/compression/compression.cc" + "tile/base/compression/gzip.cc" + "tile/base/compression/util.cc" + "tile/base/demangle.cc" + "tile/base/encoding/base64.cc" + "tile/base/encoding/detail/hex_chars.cc" + "tile/base/encoding/hex.cc" + "tile/base/encoding/percent.cc" + "tile/base/internal/background_task_host.cc" + "tile/base/internal/background_task_host.h" + "tile/base/internal/case_insensitive_hash_map.h" + "tile/base/internal/curl.cc" + "tile/base/internal/curl.h" + "tile/base/internal/early_init.h" + "tile/base/internal/index_alloc.cc" + "tile/base/internal/logging.cc" + "tile/base/internal/logging.h" + "tile/base/internal/thread_pool.cc" + "tile/base/internal/time_keeper.cc" + "tile/base/internal/time_keeper.h" + "tile/base/net/endpoint.cc" + "tile/base/object_pool/disabled.cc" + "tile/base/object_pool/global.cc" + "tile/base/object_pool/thread_local.cc" + "tile/base/option.cc" + "tile/base/option/gflags_provider.cc" + "tile/base/option/json_parser.cc" + "tile/base/option/key.cc" + "tile/base/option/option_provider.cc" + "tile/base/option/option_service.cc" + "tile/base/slice.cc" + "tile/base/status.cc" + "tile/base/string.cc" + "tile/base/thread/cond_var.cc" + "tile/base/thread/latch.cc" + "tile/base/thread/mutex.cc" + "tile/base/thread/rw_mutex.cc" + "tile/base/thread/scoped_lock.cc" + "tile/base/thread/spinlock.cc" + "tile/fiber/fiber.cc" + "tile/fiber/detail/os_fiber.cc" + "tile/fiber/detail/mutex.cc" + "tile/fiber/detail/ucontext.c" + "tile/fiber/detail/posix_os_fiber.cc" + "tile/fiber/scheduler.cc" + "tile/io/detail/eintr_safe.cc" + "tile/io/native/acceptor.cc" + "tile/io/descriptor.cc" + "tile/io/event_loop.cc" + "tile/init.cc" + "tile/init/on_init.cc" + "tile/init/override_flag.cc" + "tile/net/http/http_headers.cc" + "tile/net/http/http_message.cc" + "tile/net/http/http_request.cc" + "tile/net/http/http_response.cc" + "tile/net/http/http_client.cc" + "tile/net/http/types.cc" + "tile/net/internal/http_task.cc" + "tile/net/internal/http_engine.cc" + "tile/testing/internal/random_string.cc" + "tile/rpc/protocol/http/buffer_io.cc" + "tile/rpc/protocol/message.cc" + # "tile/rpc/server.cc" +) + +list(APPEND ASM_SRCS "tile/fiber/detail/asm/ucontext_aarch64.S" + "tile/fiber/detail/asm/ucontext_arm.S" + "tile/fiber/detail/asm/ucontext_riscv64.S" + "tile/fiber/detail/asm/ucontext_mips64.S" + "tile/fiber/detail/asm/ucontext_mips32.S" + "tile/fiber/detail/asm/ucontext_x64.S" + "tile/fiber/detail/asm/ucontext_x86.S" +) +set_source_files_properties(${ASM_SRCS} PROPERTIES LANGUAGE C) + +if((NOT TILE_HAVE_GETIFADDRS) OR (NOT TILE_HAVE_FREEIFADDRS)) + list(APPEND TILE_SRCS "tile/base/net/detail/android/ifaddrs.c") +endif() + +add_library(tile OBJECT ${TILE_SRCS} ${ASM_SRCS}) +set_target_properties(tile PROPERTIES VERSION ${PROJECT_VERSION} + SOVERSION "${tile_VERSION_MAJRO}") +# target_sources(tile PRIVATE ${TILE_SRCS}) +target_include_directories( + tile + PUBLIC "${CMAKE_CURRENT_BINARY_DIR}" + "${CMAKE_CURRENT_SOURCE_DIR}/third_party/fmt/include" + "${CMAKE_CURRENT_BINARY_DIR}/third_party/glog" + "${CMAKE_CURRENT_SOURCE_DIR}/third_party/glog/src" + "${CMAKE_CURRENT_SOURCE_DIR}" + RPIVATE + "${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include") + +target_link_libraries( + tile + PUBLIC # -Wl,--start-group + zlib gflags::gflags glog::glog + # -Wl,--end-group + libcurl fmt::fmt Threads::Threads) +if( +(CMAKE_SYSTEM_PROCESSOR MATCHES "riscv64") OR +(CMAKE_SYSTEM_PROCESSOR MATCHES "mips*")) + if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + target_link_libraries(tile PUBLIC atomic) + endif() +endif() + +# set(LIB_NAMES tile) +# +# if(("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux") OR (MINGW) OR (HAIKU) OR +# ("${CMAKE_SYSTEM_NAME}" STREQUAL "FreeBSD") OR ("${CMAKE_SYSTEM_NAME}" +# STREQUAL "GNU") OR ("${CMAKE_SYSTEM_NAME}" STREQUAL "OpenBSD") OR +# ("${CMAKE_SYSTEM_NAME}" STREQUAL "Fuchsia") OR ("${CMAKE_SYSTEM_NAME}" +# STREQUAL "DragonFly") OR ("${CMAKE_SYSTEM_NAME}" STREQUAL "SunOS")) # FIXME: +# It should be "GNU ld # for elf" set(LIB_NAMES -Wl,--whole-archive ${LIB_NAMES} +# -Wl,--no-whole-archive) elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin") +# set(LIB_NAMES -Wl,-all_load ${LIB_NAMES}) endif() + +add_library(tile::tile ALIAS tile) +# add_library(tile SHARED $) target_include_directories( +# tile PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/third_party/fmt/include" +# "${CMAKE_CURRENT_BINARY_DIR}/third_party/glog" +# "${CMAKE_CURRENT_SOURCE_DIR}/third_party/glog/src" +# "${CMAKE_CURRENT_SOURCE_DIR}" RPIVATE +# "${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include") +# target_link_libraries( tile PRIVATE ${WHOLE_ARCHIVE_PREFIX} gflags::gflags +# glog::glog libcurl fmt::fmt ${NO_WHOLE_ARCHIVE_PREFIX}) + +if(TILE_BUILD_TESTS) + enable_testing() + + add_executable(tile_test_all "tile/testing/main.cc") + target_link_libraries(tile_test_all PRIVATE gtest gmock tile::tile) + + macro(tile_add_test test_name test_file) + add_executable(${test_name} ${test_file} "tile/testing/main.cc") + target_link_libraries( + ${test_name} PUBLIC gtest gmock ${WHOLE_ARCHIVE_PREFIX} tile::tile + ${WHOLE_ARCHIVE_SUFFIX}) + add_test(NAME ${test_name} COMMAND ${test_name}) + + target_sources(${PROJECT_NAME}_test_all PRIVATE ${test_file}) + endmacro() + + # -> fiber + tile_add_test(fiber_detail_posix_os_fiber_test + "tile/fiber/detail/posix_os_fiber_test.cc") + + tile_add_test(base_internal_meta_test "tile/base/internal/meta_test.cc") + # tile_add_test(net_internal_http_engine_test + # "tile/net/internal/http_engine_test.cc") + tile_add_test(net_internal_http_task_test + "tile/net/internal/http_task_test.cc") + tile_add_test(net_http_http_client_test "tile/net/http/http_client_test.cc") + tile_add_test(net_http_http_request_test "tile/net/http/http_reqeust_test.cc") + tile_add_test(net_http_http_response_test + "tile/net/http/http_response_test.cc") + tile_add_test(base_compression_util_test "tile/base/compression/util_test.cc") + tile_add_test(rpc_protocol_http_buffer_io_test + "tile/rpc/protocol/http/buffer_io_test.cc") + + tile_add_test(base_compression_test "tile/base/compression_test.cc") + tile_add_test(base_casting_test "tile/base/casting_test.cc") + tile_add_test(base_future_future_test "tile/base/future/future_test.cc") + tile_add_test(base_future_boxed_test "tile/base/future/boxed_test.cc") + tile_add_test(base_option_option_service_test + "tile/base/option/option_service_test.cc") + tile_add_test(base_ref_ptr_test "tile/base/ref_ptr_test.cc") + tile_add_test(base_object_pool_disabled_test + "tile/base/object_pool/disabled_test.cc") + tile_add_test(base_object_pool_types_test + "tile/base/object_pool/types_test.cc") + tile_add_test(base_string_test "tile/base/string_test.cc") + tile_add_test(base_deferred_test "tile/base/deferred_test.cc") + tile_add_test(base_internal_singly_linked_list_test + "tile/base/internal/singly_linked_list_test.cc") + tile_add_test(base_internal_move_on_copy_test + "tile/base/internal/move_on_copy_test.cc") + tile_add_test(base_internal_thread_pool_test + "tile/base/internal/thread_pool_test.cc") + tile_add_test(base_internal_format_test "tile/base/internal/format_test.cc") + tile_add_test(base_internal_background_task_host_test + "tile/base/internal/background_task_host_test.cc") + tile_add_test(base_down_cast_test "tile/base/down_cast_test.cc") + tile_add_test(base_encoding_hex_test "tile/base/encoding/hex_test.cc") + tile_add_test(base_encoding_percent_test "tile/base/encoding/percent_test.cc") + tile_add_test(base_encoding_base64_test "tile/base/encoding/base64_test.cc") + tile_add_test(base_internal_case_insensitive_hash_map_test + "tile/base/internal/case_insensitive_hash_map_test.cc") + tile_add_test(net_http_http_headers_test "tile/net/http/http_headers_test.cc") + tile_add_test(base_demangle_test "tile/base/demangle_test.cc") + tile_add_test(base_option_json_parser_test + "tile/base/option/json_parser_test.cc") + tile_add_test(base_option_key_test "tile/base/option/key_test.cc") + tile_add_test(base_dependency_registry_test + "tile/base/dependency_registry_test.cc") + tile_add_test(base_maybe_owning_test "tile/base/maybe_owning_test.cc") + tile_add_test(base_status_test "tile/base/status_test.cc") + tile_add_test(base_net_endpoint_test "tile/base/net/endpoint_test.cc") + tile_add_test(base_handle_test "tile/base/handle_test.cc") + tile_add_test(base_thread_scoped_lock_test + "tile/base/thread/scoped_lock_test.cc") + tile_add_test(base_thread_spinlock_test "tile/base/thread/spinlock_test.cc") + tile_add_test(base_thread_unique_lock_test + "tile/base/thread/unique_lock_test.cc") + tile_add_test(base_thread_cond_var_test "tile/base/thread/cond_var_test.cc") + tile_add_test(base_thread_latch_test "tile/base/thread/latch_test.cc") + # tile_add_test(fiber_ucontext_test "tile/fiber/ucontext_test.cc") + + tile_add_test(init_on_init_test "tile/init/on_init_test.cc") + tile_add_test(base_buffer_test "tile/base/buffer_test.cc") + tile_add_test(base_object_pool_thread_local_test + "tile/base/object_pool/thread_local_test.cc") + tile_add_test(base_internal_logging_test "tile/base/internal/logging_test.cc") + tile_add_test(base_chrono_test "tile/base/chrono_test.cc") + tile_add_test(init_override_flag_test "tile/init/override_flag_test.cc") + # tile_add_test(base_internal_time_keeper_test + # "tile/base/internal/time_keeper_test.cc") +endif(TILE_BUILD_TESTS) + +if(TILE_BUILD_BENCHMARKS) + add_subdirectory("third_party/benchmark") + + add_executable(tile_bm_all "tile/testing/bm_main.cc") + target_link_libraries(tile_bm_all PRIVATE benchmark::benchmark tile::tile) + + macro(tile_add_bm benchmark_name benchmark_file) + add_executable(${benchmark_name} ${benchmark_file} + "tile/testing/bm_main.cc") + target_link_libraries(${benchmark_name} PRIVATE benchmark::benchmark + tile::tile) + + target_sources(tile_bm_all PRIVATE ${benchmark_file}) + endmacro() + + tile_add_bm(base_casting_benchmark "tile/base/casting_benchmark.cc") + tile_add_bm(base_thread_mutex_benchmark "tile/base/thread/mutex_benchmark.cc") + tile_add_bm(base_encoding_benchmark "tile/base/encoding_benchmark.cc") + tile_add_bm(base_internal_time_keeper_benchmark + "tile/base/internal/time_keeper_benchmark.cc") + tile_add_bm(base_chrono_benchmark "tile/base/chrono_benchmark.cc") +endif(TILE_BUILD_BENCHMARKS) diff --git a/cmake/BuildInfo.cmake b/cmake/BuildInfo.cmake new file mode 100644 index 0000000..e2c19a6 --- /dev/null +++ b/cmake/BuildInfo.cmake @@ -0,0 +1,28 @@ +find_package(Git REQUIRED) + +macro(get_git_commit_hash output) + # full commit hash + execute_process( + COMMAND ${GIT_EXECUTABLE} log -1 --format="%H" + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + OUTPUT_VARIABLE ${output} + OUTPUT_STRIP_TRAILING_WHITESPACE) +endmacro() + +macro(get_git_commit_date output) + # 2024-06-02T20:17:41+00:00 + execute_process( + COMMAND ${GIT_EXECUTABLE} log -1 --format="%cI" + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + OUTPUT_VARIABLE ${output} + OUTPUT_STRIP_TRAILING_WHITESPACE) +endmacro() + +macro(get_git_commit_subject output) + # message from `git commit -m "message"` + execute_process( + COMMAND ${GIT_EXECUTABLE} log -1 --format="%s" + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + OUTPUT_VARIABLE GIT_COMMIT_SUBJECT + OUTPUT_STRIP_TRAILING_WHITESPACE) +endmacro() diff --git a/dir.bloaty b/dir.bloaty new file mode 100644 index 0000000..29b47be --- /dev/null +++ b/dir.bloaty @@ -0,0 +1,14 @@ +custom_data_source: { + name: "dir" + base_data_source: "compileunits" + + rewrite: { + pattern: "^(.*/tile/)(third_party/\\w+)" + replacement: "\\2" + } + + rewrite: { + pattern: "^(.*/tile/)((\\w+/)+)" + replacement: "\\2" + } +} diff --git a/third_party/benchmark/.clang-format b/third_party/benchmark/.clang-format new file mode 100644 index 0000000..e7d00fe --- /dev/null +++ b/third_party/benchmark/.clang-format @@ -0,0 +1,5 @@ +--- +Language: Cpp +BasedOnStyle: Google +PointerAlignment: Left +... diff --git a/third_party/benchmark/.clang-tidy b/third_party/benchmark/.clang-tidy new file mode 100644 index 0000000..1e229e5 --- /dev/null +++ b/third_party/benchmark/.clang-tidy @@ -0,0 +1,6 @@ +--- +Checks: 'clang-analyzer-*,readability-redundant-*,performance-*' +WarningsAsErrors: 'clang-analyzer-*,readability-redundant-*,performance-*' +HeaderFilterRegex: '.*' +FormatStyle: none +User: user diff --git a/third_party/benchmark/.github/ISSUE_TEMPLATE/bug_report.md b/third_party/benchmark/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..6c2ced9 --- /dev/null +++ b/third_party/benchmark/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,32 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "[BUG]" +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**System** +Which OS, compiler, and compiler version are you using: + - OS: + - Compiler and version: + +**To reproduce** +Steps to reproduce the behavior: +1. sync to commit ... +2. cmake/bazel... +3. make ... +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Additional context** +Add any other context about the problem here. diff --git a/third_party/benchmark/.github/ISSUE_TEMPLATE/feature_request.md b/third_party/benchmark/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..9e8ab6a --- /dev/null +++ b/third_party/benchmark/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: "[FR]" +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/third_party/benchmark/.github/install_bazel.sh b/third_party/benchmark/.github/install_bazel.sh new file mode 100644 index 0000000..1b0d63c --- /dev/null +++ b/third_party/benchmark/.github/install_bazel.sh @@ -0,0 +1,12 @@ +if ! bazel version; then + arch=$(uname -m) + if [ "$arch" == "aarch64" ]; then + arch="arm64" + fi + echo "Downloading $arch Bazel binary from GitHub releases." + curl -L -o $HOME/bin/bazel --create-dirs "https://github.com/bazelbuild/bazel/releases/download/7.1.1/bazel-7.1.1-linux-$arch" + chmod +x $HOME/bin/bazel +else + # Bazel is installed for the correct architecture + exit 0 +fi diff --git a/third_party/benchmark/.github/libcxx-setup.sh b/third_party/benchmark/.github/libcxx-setup.sh new file mode 100755 index 0000000..9aaf96a --- /dev/null +++ b/third_party/benchmark/.github/libcxx-setup.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash + +set -e + +# Checkout LLVM sources +git clone --depth=1 --branch llvmorg-16.0.6 https://github.com/llvm/llvm-project.git llvm-project + +## Setup libc++ options +if [ -z "$BUILD_32_BITS" ]; then + export BUILD_32_BITS=OFF && echo disabling 32 bit build +fi + +## Build and install libc++ (Use unstable ABI for better sanitizer coverage) +mkdir llvm-build && cd llvm-build +cmake -DCMAKE_C_COMPILER=${CC} \ + -DCMAKE_CXX_COMPILER=${CXX} \ + -DCMAKE_BUILD_TYPE=RelWithDebInfo \ + -DCMAKE_INSTALL_PREFIX=/usr \ + -DLIBCXX_ABI_UNSTABLE=OFF \ + -DLLVM_USE_SANITIZER=${LIBCXX_SANITIZER} \ + -DLLVM_BUILD_32_BITS=${BUILD_32_BITS} \ + -DLLVM_ENABLE_RUNTIMES='libcxx;libcxxabi;libunwind' \ + -G "Unix Makefiles" \ + ../llvm-project/runtimes/ +make -j cxx cxxabi unwind +cd .. diff --git a/third_party/benchmark/.github/workflows/bazel.yml b/third_party/benchmark/.github/workflows/bazel.yml new file mode 100644 index 0000000..a669cda --- /dev/null +++ b/third_party/benchmark/.github/workflows/bazel.yml @@ -0,0 +1,35 @@ +name: bazel + +on: + push: {} + pull_request: {} + +jobs: + build_and_test_default: + name: bazel.${{ matrix.os }}.${{ matrix.bzlmod && 'bzlmod' || 'no_bzlmod' }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + bzlmod: [false, true] + steps: + - uses: actions/checkout@v4 + + - name: mount bazel cache + uses: actions/cache@v3 + env: + cache-name: bazel-cache + with: + path: "~/.cache/bazel" + key: ${{ env.cache-name }}-${{ matrix.os }}-${{ github.ref }} + restore-keys: | + ${{ env.cache-name }}-${{ matrix.os }}-main + + - name: build + run: | + bazel build ${{ matrix.bzlmod && '--enable_bzlmod' || '--noenable_bzlmod' }} //:benchmark //:benchmark_main //test/... + + - name: test + run: | + bazel test ${{ matrix.bzlmod && '--enable_bzlmod' || '--noenable_bzlmod' }} --test_output=all //test/... diff --git a/third_party/benchmark/.github/workflows/build-and-test-min-cmake.yml b/third_party/benchmark/.github/workflows/build-and-test-min-cmake.yml new file mode 100644 index 0000000..e3e3217 --- /dev/null +++ b/third_party/benchmark/.github/workflows/build-and-test-min-cmake.yml @@ -0,0 +1,46 @@ +name: build-and-test-min-cmake + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + job: + name: ${{ matrix.os }}.min-cmake + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + + steps: + - uses: actions/checkout@v3 + + - uses: lukka/get-cmake@latest + with: + cmakeVersion: 3.10.0 + + - name: create build environment + run: cmake -E make_directory ${{ runner.workspace }}/_build + + - name: setup cmake initial cache + run: touch compiler-cache.cmake + + - name: configure cmake + env: + CXX: ${{ matrix.compiler }} + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: > + cmake -C ${{ github.workspace }}/compiler-cache.cmake + $GITHUB_WORKSPACE + -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON + -DCMAKE_CXX_VISIBILITY_PRESET=hidden + -DCMAKE_VISIBILITY_INLINES_HIDDEN=ON + + - name: build + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: cmake --build . diff --git a/third_party/benchmark/.github/workflows/build-and-test-perfcounters.yml b/third_party/benchmark/.github/workflows/build-and-test-perfcounters.yml new file mode 100644 index 0000000..97e4d8e --- /dev/null +++ b/third_party/benchmark/.github/workflows/build-and-test-perfcounters.yml @@ -0,0 +1,51 @@ +name: build-and-test-perfcounters + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + job: + # TODO(dominic): Extend this to include compiler and set through env: CC/CXX. + name: ${{ matrix.os }}.${{ matrix.build_type }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-22.04, ubuntu-20.04] + build_type: ['Release', 'Debug'] + steps: + - uses: actions/checkout@v3 + + - name: install libpfm + run: | + sudo apt update + sudo apt -y install libpfm4-dev + + - name: create build environment + run: cmake -E make_directory ${{ runner.workspace }}/_build + + - name: configure cmake + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: > + cmake $GITHUB_WORKSPACE + -DBENCHMARK_ENABLE_LIBPFM=1 + -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON + -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} + + - name: build + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: cmake --build . --config ${{ matrix.build_type }} + + # Skip testing, for now. It seems perf_event_open does not succeed on the + # hosting machine, very likely a permissions issue. + # TODO(mtrofin): Enable test. + # - name: test + # shell: bash + # working-directory: ${{ runner.workspace }}/_build + # run: ctest -C ${{ matrix.build_type }} --rerun-failed --output-on-failure + diff --git a/third_party/benchmark/.github/workflows/build-and-test.yml b/third_party/benchmark/.github/workflows/build-and-test.yml new file mode 100644 index 0000000..95e0482 --- /dev/null +++ b/third_party/benchmark/.github/workflows/build-and-test.yml @@ -0,0 +1,161 @@ +name: build-and-test + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + # TODO: add 32-bit builds (g++ and clang++) for ubuntu + # (requires g++-multilib and libc6:i386) + # TODO: add coverage build (requires lcov) + # TODO: add clang + libc++ builds for ubuntu + job: + name: ${{ matrix.os }}.${{ matrix.build_type }}.${{ matrix.lib }}.${{ matrix.compiler }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-22.04, ubuntu-20.04, macos-latest] + build_type: ['Release', 'Debug'] + compiler: ['g++', 'clang++'] + lib: ['shared', 'static'] + + steps: + - uses: actions/checkout@v3 + + - uses: lukka/get-cmake@latest + + - name: create build environment + run: cmake -E make_directory ${{ runner.workspace }}/_build + + - name: setup cmake initial cache + run: touch compiler-cache.cmake + + - name: configure cmake + env: + CXX: ${{ matrix.compiler }} + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: > + cmake -C ${{ github.workspace }}/compiler-cache.cmake + $GITHUB_WORKSPACE + -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON + -DBUILD_SHARED_LIBS=${{ matrix.lib == 'shared' }} + -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} + -DCMAKE_CXX_COMPILER=${{ env.CXX }} + -DCMAKE_CXX_VISIBILITY_PRESET=hidden + -DCMAKE_VISIBILITY_INLINES_HIDDEN=ON + + - name: build + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: cmake --build . --config ${{ matrix.build_type }} + + - name: test + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: ctest -C ${{ matrix.build_type }} -VV + + msvc: + name: ${{ matrix.os }}.${{ matrix.build_type }}.${{ matrix.lib }}.${{ matrix.msvc }} + runs-on: ${{ matrix.os }} + defaults: + run: + shell: powershell + strategy: + fail-fast: false + matrix: + msvc: + - VS-16-2019 + - VS-17-2022 + arch: + - x64 + build_type: + - Debug + - Release + lib: + - shared + - static + include: + - msvc: VS-16-2019 + os: windows-2019 + generator: 'Visual Studio 16 2019' + - msvc: VS-17-2022 + os: windows-2022 + generator: 'Visual Studio 17 2022' + + steps: + - uses: actions/checkout@v2 + + - uses: lukka/get-cmake@latest + + - name: configure cmake + run: > + cmake -S . -B _build/ + -A ${{ matrix.arch }} + -G "${{ matrix.generator }}" + -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON + -DBUILD_SHARED_LIBS=${{ matrix.lib == 'shared' }} + + - name: build + run: cmake --build _build/ --config ${{ matrix.build_type }} + + - name: test + run: ctest --test-dir _build/ -C ${{ matrix.build_type }} -VV + + msys2: + name: ${{ matrix.os }}.${{ matrix.build_type }}.${{ matrix.lib }}.${{ matrix.msys2.msystem }} + runs-on: ${{ matrix.os }} + defaults: + run: + shell: msys2 {0} + strategy: + fail-fast: false + matrix: + os: [ windows-latest ] + msys2: + - { msystem: MINGW64, arch: x86_64, family: GNU, compiler: g++ } + - { msystem: MINGW32, arch: i686, family: GNU, compiler: g++ } + - { msystem: CLANG64, arch: x86_64, family: LLVM, compiler: clang++ } + - { msystem: CLANG32, arch: i686, family: LLVM, compiler: clang++ } + - { msystem: UCRT64, arch: x86_64, family: GNU, compiler: g++ } + build_type: + - Debug + - Release + lib: + - shared + - static + + steps: + - uses: actions/checkout@v2 + + - name: Install Base Dependencies + uses: msys2/setup-msys2@v2 + with: + cache: false + msystem: ${{ matrix.msys2.msystem }} + update: true + install: >- + git + base-devel + pacboy: >- + cc:p + cmake:p + ninja:p + + - name: configure cmake + env: + CXX: ${{ matrix.msys2.compiler }} + run: > + cmake -S . -B _build/ + -GNinja + -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON + -DBUILD_SHARED_LIBS=${{ matrix.lib == 'shared' }} + + - name: build + run: cmake --build _build/ --config ${{ matrix.build_type }} + + - name: test + run: ctest --test-dir _build/ -C ${{ matrix.build_type }} -VV diff --git a/third_party/benchmark/.github/workflows/clang-format-lint.yml b/third_party/benchmark/.github/workflows/clang-format-lint.yml new file mode 100644 index 0000000..328fe36 --- /dev/null +++ b/third_party/benchmark/.github/workflows/clang-format-lint.yml @@ -0,0 +1,18 @@ +name: clang-format-lint +on: + push: {} + pull_request: {} + +jobs: + job: + name: check-clang-format + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - uses: DoozyX/clang-format-lint-action@v0.13 + with: + source: './include/benchmark ./src ./test' + extensions: 'h,cc' + clangFormatVersion: 12 + style: Google diff --git a/third_party/benchmark/.github/workflows/clang-tidy.yml b/third_party/benchmark/.github/workflows/clang-tidy.yml new file mode 100644 index 0000000..2eaab9c --- /dev/null +++ b/third_party/benchmark/.github/workflows/clang-tidy.yml @@ -0,0 +1,38 @@ +name: clang-tidy + +on: + push: {} + pull_request: {} + +jobs: + job: + name: run-clang-tidy + runs-on: ubuntu-latest + strategy: + fail-fast: false + steps: + - uses: actions/checkout@v3 + + - name: install clang-tidy + run: sudo apt update && sudo apt -y install clang-tidy + + - name: create build environment + run: cmake -E make_directory ${{ runner.workspace }}/_build + + - name: configure cmake + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: > + cmake $GITHUB_WORKSPACE + -DBENCHMARK_ENABLE_ASSEMBLY_TESTS=OFF + -DBENCHMARK_ENABLE_LIBPFM=OFF + -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON + -DCMAKE_C_COMPILER=clang + -DCMAKE_CXX_COMPILER=clang++ + -DCMAKE_EXPORT_COMPILE_COMMANDS=ON + -DGTEST_COMPILE_COMMANDS=OFF + + - name: run + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: run-clang-tidy diff --git a/third_party/benchmark/.github/workflows/doxygen.yml b/third_party/benchmark/.github/workflows/doxygen.yml new file mode 100644 index 0000000..da92c46 --- /dev/null +++ b/third_party/benchmark/.github/workflows/doxygen.yml @@ -0,0 +1,28 @@ +name: doxygen + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + build-and-deploy: + name: Build HTML documentation + runs-on: ubuntu-latest + steps: + - name: Fetching sources + uses: actions/checkout@v3 + + - name: Installing build dependencies + run: | + sudo apt update + sudo apt install doxygen gcc git + + - name: Creating build directory + run: mkdir build + + - name: Building HTML documentation with Doxygen + run: | + cmake -S . -B build -DBENCHMARK_ENABLE_TESTING:BOOL=OFF -DBENCHMARK_ENABLE_DOXYGEN:BOOL=ON -DBENCHMARK_INSTALL_DOCS:BOOL=ON + cmake --build build --target benchmark_doxygen diff --git a/third_party/benchmark/.github/workflows/pre-commit.yml b/third_party/benchmark/.github/workflows/pre-commit.yml new file mode 100644 index 0000000..5d65b99 --- /dev/null +++ b/third_party/benchmark/.github/workflows/pre-commit.yml @@ -0,0 +1,38 @@ +name: python + Bazel pre-commit checks + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + pre-commit: + runs-on: ubuntu-latest + env: + MYPY_CACHE_DIR: "${{ github.workspace }}/.cache/mypy" + RUFF_CACHE_DIR: "${{ github.workspace }}/.cache/ruff" + PRE_COMMIT_HOME: "${{ github.workspace }}/.cache/pre-commit" + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: 3.11 + cache: pip + cache-dependency-path: pyproject.toml + - name: Install dependencies + run: python -m pip install ".[dev]" + - name: Cache pre-commit tools + uses: actions/cache@v3 + with: + path: | + ${{ env.MYPY_CACHE_DIR }} + ${{ env.RUFF_CACHE_DIR }} + ${{ env.PRE_COMMIT_HOME }} + key: ${{ runner.os }}-${{ hashFiles('.pre-commit-config.yaml') }}-linter-cache + - name: Run pre-commit checks + run: pre-commit run --all-files --verbose --show-diff-on-failure diff --git a/third_party/benchmark/.github/workflows/sanitizer.yml b/third_party/benchmark/.github/workflows/sanitizer.yml new file mode 100644 index 0000000..86cccf4 --- /dev/null +++ b/third_party/benchmark/.github/workflows/sanitizer.yml @@ -0,0 +1,96 @@ +name: sanitizer + +on: + push: {} + pull_request: {} + +env: + UBSAN_OPTIONS: "print_stacktrace=1" + +jobs: + job: + name: ${{ matrix.sanitizer }}.${{ matrix.build_type }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + build_type: ['Debug', 'RelWithDebInfo'] + sanitizer: ['asan', 'ubsan', 'tsan', 'msan'] + + steps: + - uses: actions/checkout@v3 + + - name: configure msan env + if: matrix.sanitizer == 'msan' + run: | + echo "EXTRA_FLAGS=-g -O2 -fno-omit-frame-pointer -fsanitize=memory -fsanitize-memory-track-origins" >> $GITHUB_ENV + echo "LIBCXX_SANITIZER=MemoryWithOrigins" >> $GITHUB_ENV + + - name: configure ubsan env + if: matrix.sanitizer == 'ubsan' + run: | + echo "EXTRA_FLAGS=-g -O2 -fno-omit-frame-pointer -fsanitize=undefined -fno-sanitize-recover=all" >> $GITHUB_ENV + echo "LIBCXX_SANITIZER=Undefined" >> $GITHUB_ENV + + - name: configure asan env + if: matrix.sanitizer == 'asan' + run: | + echo "EXTRA_FLAGS=-g -O2 -fno-omit-frame-pointer -fsanitize=address -fno-sanitize-recover=all" >> $GITHUB_ENV + echo "LIBCXX_SANITIZER=Address" >> $GITHUB_ENV + + - name: configure tsan env + if: matrix.sanitizer == 'tsan' + run: | + echo "EXTRA_FLAGS=-g -O2 -fno-omit-frame-pointer -fsanitize=thread -fno-sanitize-recover=all" >> $GITHUB_ENV + echo "LIBCXX_SANITIZER=Thread" >> $GITHUB_ENV + + - name: fine-tune asan options + # in asan we get an error from std::regex. ignore it. + if: matrix.sanitizer == 'asan' + run: | + echo "ASAN_OPTIONS=alloc_dealloc_mismatch=0" >> $GITHUB_ENV + + - name: setup clang + uses: egor-tensin/setup-clang@v1 + with: + version: latest + platform: x64 + + - name: configure clang + run: | + echo "CC=cc" >> $GITHUB_ENV + echo "CXX=c++" >> $GITHUB_ENV + + - name: build libc++ (non-asan) + if: matrix.sanitizer != 'asan' + run: | + "${GITHUB_WORKSPACE}/.github/libcxx-setup.sh" + echo "EXTRA_CXX_FLAGS=-stdlib=libc++ -L ${GITHUB_WORKSPACE}/llvm-build/lib -lc++abi -Isystem${GITHUB_WORKSPACE}/llvm-build/include -Isystem${GITHUB_WORKSPACE}/llvm-build/include/c++/v1 -Wl,-rpath,${GITHUB_WORKSPACE}/llvm-build/lib" >> $GITHUB_ENV + + - name: create build environment + run: cmake -E make_directory ${{ runner.workspace }}/_build + + - name: configure cmake + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: > + VERBOSE=1 + cmake $GITHUB_WORKSPACE + -DBENCHMARK_ENABLE_ASSEMBLY_TESTS=OFF + -DBENCHMARK_ENABLE_LIBPFM=OFF + -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON + -DCMAKE_C_COMPILER=${{ env.CC }} + -DCMAKE_CXX_COMPILER=${{ env.CXX }} + -DCMAKE_C_FLAGS="${{ env.EXTRA_FLAGS }}" + -DCMAKE_CXX_FLAGS="${{ env.EXTRA_FLAGS }} ${{ env.EXTRA_CXX_FLAGS }}" + -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} + + - name: build + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: cmake --build . --config ${{ matrix.build_type }} + + - name: test + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: ctest -C ${{ matrix.build_type }} -VV diff --git a/third_party/benchmark/.github/workflows/test_bindings.yml b/third_party/benchmark/.github/workflows/test_bindings.yml new file mode 100644 index 0000000..436a8f9 --- /dev/null +++ b/third_party/benchmark/.github/workflows/test_bindings.yml @@ -0,0 +1,30 @@ +name: test-bindings + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + python_bindings: + name: Test GBM Python bindings on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ ubuntu-latest, macos-latest, windows-latest ] + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Set up Python 3.11 + uses: actions/setup-python@v5 + with: + python-version: 3.11 + - name: Install GBM Python bindings on ${{ matrix.os }} + run: python -m pip install . + - name: Run bindings example on ${{ matrix.os }} + run: + python bindings/python/google_benchmark/example.py diff --git a/third_party/benchmark/.github/workflows/wheels.yml b/third_party/benchmark/.github/workflows/wheels.yml new file mode 100644 index 0000000..8b772cd --- /dev/null +++ b/third_party/benchmark/.github/workflows/wheels.yml @@ -0,0 +1,90 @@ +name: Build and upload Python wheels + +on: + workflow_dispatch: + release: + types: + - published + +jobs: + build_sdist: + name: Build source distribution + runs-on: ubuntu-latest + steps: + - name: Check out repo + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Install Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: 3.12 + - run: python -m pip install build + - name: Build sdist + run: python -m build --sdist + - uses: actions/upload-artifact@v4 + with: + name: dist-sdist + path: dist/*.tar.gz + + build_wheels: + name: Build Google Benchmark wheels on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, macos-13, macos-14, windows-latest] + + steps: + - name: Check out Google Benchmark + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Set up QEMU + if: runner.os == 'Linux' + uses: docker/setup-qemu-action@v3 + with: + platforms: all + + - name: Build wheels on ${{ matrix.os }} using cibuildwheel + uses: pypa/cibuildwheel@v2.17 + env: + CIBW_BUILD: "cp38-* cp39-* cp310-* cp311-* cp312-*" + CIBW_SKIP: "*-musllinux_*" + CIBW_TEST_SKIP: "cp38-macosx_*:arm64" + CIBW_ARCHS_LINUX: auto64 aarch64 + CIBW_ARCHS_WINDOWS: auto64 + CIBW_BEFORE_ALL_LINUX: bash .github/install_bazel.sh + # Grab the rootless Bazel installation inside the container. + CIBW_ENVIRONMENT_LINUX: PATH=$PATH:$HOME/bin + CIBW_TEST_COMMAND: python {project}/bindings/python/google_benchmark/example.py + + - name: Upload Google Benchmark ${{ matrix.os }} wheels + uses: actions/upload-artifact@v4 + with: + name: dist-${{ matrix.os }} + path: wheelhouse/*.whl + + merge_wheels: + name: Merge all built wheels into one artifact + runs-on: ubuntu-latest + needs: build_wheels + steps: + - name: Merge wheels + uses: actions/upload-artifact/merge@v4 + with: + name: dist + pattern: dist-* + delete-merged: true + + pypi_upload: + name: Publish google-benchmark wheels to PyPI + needs: [merge_wheels] + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - uses: actions/download-artifact@v4 + with: + path: dist + - uses: pypa/gh-action-pypi-publish@v1 diff --git a/third_party/benchmark/.gitignore b/third_party/benchmark/.gitignore new file mode 100644 index 0000000..24a1fb6 --- /dev/null +++ b/third_party/benchmark/.gitignore @@ -0,0 +1,68 @@ +*.a +*.so +*.so.?* +*.dll +*.exe +*.dylib +*.cmake +!/cmake/*.cmake +!/test/AssemblyTests.cmake +*~ +*.swp +*.pyc +__pycache__ +.DS_Store + +# lcov +*.lcov +/lcov + +# cmake files. +/Testing +CMakeCache.txt +CMakeFiles/ +cmake_install.cmake + +# makefiles. +Makefile + +# in-source build. +bin/ +lib/ +/test/*_test + +# exuberant ctags. +tags + +# YouCompleteMe configuration. +.ycm_extra_conf.pyc + +# ninja generated files. +.ninja_deps +.ninja_log +build.ninja +install_manifest.txt +rules.ninja + +# bazel output symlinks. +bazel-* +MODULE.bazel.lock + +# out-of-source build top-level folders. +build/ +_build/ +build*/ + +# in-source dependencies +/googletest/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +CMakeSettings.json + +# Visual Studio Code cache/options directory +.vscode/ + +# Python build stuff +dist/ +*.egg-info* diff --git a/third_party/benchmark/.pre-commit-config.yaml b/third_party/benchmark/.pre-commit-config.yaml new file mode 100644 index 0000000..93455ab --- /dev/null +++ b/third_party/benchmark/.pre-commit-config.yaml @@ -0,0 +1,18 @@ +repos: + - repo: https://github.com/keith/pre-commit-buildifier + rev: 6.4.0 + hooks: + - id: buildifier + - id: buildifier-lint + - repo: https://github.com/pre-commit/mirrors-mypy + rev: v1.8.0 + hooks: + - id: mypy + types_or: [ python, pyi ] + args: [ "--ignore-missing-imports", "--scripts-are-modules" ] + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.3.1 + hooks: + - id: ruff + args: [ --fix, --exit-non-zero-on-fix ] + - id: ruff-format \ No newline at end of file diff --git a/third_party/benchmark/.travis.yml b/third_party/benchmark/.travis.yml new file mode 100644 index 0000000..8cfed3d --- /dev/null +++ b/third_party/benchmark/.travis.yml @@ -0,0 +1,208 @@ +sudo: required +dist: trusty +language: cpp + +matrix: + include: + - compiler: gcc + addons: + apt: + packages: + - lcov + env: COMPILER=g++ C_COMPILER=gcc BUILD_TYPE=Coverage + - compiler: gcc + addons: + apt: + packages: + - g++-multilib + - libc6:i386 + env: + - COMPILER=g++ + - C_COMPILER=gcc + - BUILD_TYPE=Debug + - BUILD_32_BITS=ON + - EXTRA_FLAGS="-m32" + - compiler: gcc + addons: + apt: + packages: + - g++-multilib + - libc6:i386 + env: + - COMPILER=g++ + - C_COMPILER=gcc + - BUILD_TYPE=Release + - BUILD_32_BITS=ON + - EXTRA_FLAGS="-m32" + - compiler: gcc + env: + - INSTALL_GCC6_FROM_PPA=1 + - COMPILER=g++-6 C_COMPILER=gcc-6 BUILD_TYPE=Debug + - ENABLE_SANITIZER=1 + - EXTRA_FLAGS="-fno-omit-frame-pointer -g -O2 -fsanitize=undefined,address -fuse-ld=gold" + # Clang w/ libc++ + - compiler: clang + dist: xenial + addons: + apt: + packages: + clang-3.8 + env: + - INSTALL_GCC6_FROM_PPA=1 + - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Debug + - LIBCXX_BUILD=1 + - EXTRA_CXX_FLAGS="-stdlib=libc++" + - compiler: clang + dist: xenial + addons: + apt: + packages: + clang-3.8 + env: + - INSTALL_GCC6_FROM_PPA=1 + - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Release + - LIBCXX_BUILD=1 + - EXTRA_CXX_FLAGS="-stdlib=libc++" + # Clang w/ 32bit libc++ + - compiler: clang + dist: xenial + addons: + apt: + packages: + - clang-3.8 + - g++-multilib + - libc6:i386 + env: + - INSTALL_GCC6_FROM_PPA=1 + - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Debug + - LIBCXX_BUILD=1 + - BUILD_32_BITS=ON + - EXTRA_FLAGS="-m32" + - EXTRA_CXX_FLAGS="-stdlib=libc++" + # Clang w/ 32bit libc++ + - compiler: clang + dist: xenial + addons: + apt: + packages: + - clang-3.8 + - g++-multilib + - libc6:i386 + env: + - INSTALL_GCC6_FROM_PPA=1 + - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Release + - LIBCXX_BUILD=1 + - BUILD_32_BITS=ON + - EXTRA_FLAGS="-m32" + - EXTRA_CXX_FLAGS="-stdlib=libc++" + # Clang w/ libc++, ASAN, UBSAN + - compiler: clang + dist: xenial + addons: + apt: + packages: + clang-3.8 + env: + - INSTALL_GCC6_FROM_PPA=1 + - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Debug + - LIBCXX_BUILD=1 LIBCXX_SANITIZER="Undefined;Address" + - ENABLE_SANITIZER=1 + - EXTRA_FLAGS="-g -O2 -fno-omit-frame-pointer -fsanitize=undefined,address -fno-sanitize-recover=all" + - EXTRA_CXX_FLAGS="-stdlib=libc++" + - UBSAN_OPTIONS=print_stacktrace=1 + # Clang w/ libc++ and MSAN + - compiler: clang + dist: xenial + addons: + apt: + packages: + clang-3.8 + env: + - INSTALL_GCC6_FROM_PPA=1 + - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Debug + - LIBCXX_BUILD=1 LIBCXX_SANITIZER=MemoryWithOrigins + - ENABLE_SANITIZER=1 + - EXTRA_FLAGS="-g -O2 -fno-omit-frame-pointer -fsanitize=memory -fsanitize-memory-track-origins" + - EXTRA_CXX_FLAGS="-stdlib=libc++" + # Clang w/ libc++ and MSAN + - compiler: clang + dist: xenial + addons: + apt: + packages: + clang-3.8 + env: + - INSTALL_GCC6_FROM_PPA=1 + - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=RelWithDebInfo + - LIBCXX_BUILD=1 LIBCXX_SANITIZER=Thread + - ENABLE_SANITIZER=1 + - EXTRA_FLAGS="-g -O2 -fno-omit-frame-pointer -fsanitize=thread -fno-sanitize-recover=all" + - EXTRA_CXX_FLAGS="-stdlib=libc++" + - os: osx + osx_image: xcode8.3 + compiler: clang + env: + - COMPILER=clang++ + - BUILD_TYPE=Release + - BUILD_32_BITS=ON + - EXTRA_FLAGS="-m32" + +before_script: + - if [ -n "${LIBCXX_BUILD}" ]; then + source .libcxx-setup.sh; + fi + - if [ -n "${ENABLE_SANITIZER}" ]; then + export EXTRA_OPTIONS="-DBENCHMARK_ENABLE_ASSEMBLY_TESTS=OFF"; + else + export EXTRA_OPTIONS=""; + fi + - mkdir -p build && cd build + +before_install: + - if [ -z "$BUILD_32_BITS" ]; then + export BUILD_32_BITS=OFF && echo disabling 32 bit build; + fi + - if [ -n "${INSTALL_GCC6_FROM_PPA}" ]; then + sudo add-apt-repository -y "ppa:ubuntu-toolchain-r/test"; + sudo apt-get update --option Acquire::Retries=100 --option Acquire::http::Timeout="60"; + fi + +install: + - if [ -n "${INSTALL_GCC6_FROM_PPA}" ]; then + travis_wait sudo -E apt-get -yq --no-install-suggests --no-install-recommends install g++-6; + fi + - if [ "${TRAVIS_OS_NAME}" == "linux" -a "${BUILD_32_BITS}" == "OFF" ]; then + travis_wait sudo -E apt-get -y --no-install-suggests --no-install-recommends install llvm-3.9-tools; + sudo cp /usr/lib/llvm-3.9/bin/FileCheck /usr/local/bin/; + fi + - if [ "${BUILD_TYPE}" == "Coverage" -a "${TRAVIS_OS_NAME}" == "linux" ]; then + PATH=~/.local/bin:${PATH}; + pip install --user --upgrade pip; + travis_wait pip install --user cpp-coveralls; + fi + - if [ "${C_COMPILER}" == "gcc-7" -a "${TRAVIS_OS_NAME}" == "osx" ]; then + rm -f /usr/local/include/c++; + brew update; + travis_wait brew install gcc@7; + fi + - if [ "${TRAVIS_OS_NAME}" == "linux" ]; then + sudo apt-get update -qq; + sudo apt-get install -qq unzip cmake3; + wget https://github.com/bazelbuild/bazel/releases/download/3.2.0/bazel-3.2.0-installer-linux-x86_64.sh --output-document bazel-installer.sh; + travis_wait sudo bash bazel-installer.sh; + fi + - if [ "${TRAVIS_OS_NAME}" == "osx" ]; then + curl -L -o bazel-installer.sh https://github.com/bazelbuild/bazel/releases/download/3.2.0/bazel-3.2.0-installer-darwin-x86_64.sh; + travis_wait sudo bash bazel-installer.sh; + fi + +script: + - cmake -DCMAKE_C_COMPILER=${C_COMPILER} -DCMAKE_CXX_COMPILER=${COMPILER} -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -DCMAKE_C_FLAGS="${EXTRA_FLAGS}" -DCMAKE_CXX_FLAGS="${EXTRA_FLAGS} ${EXTRA_CXX_FLAGS}" -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON -DBENCHMARK_BUILD_32_BITS=${BUILD_32_BITS} ${EXTRA_OPTIONS} .. + - make + - ctest -C ${BUILD_TYPE} --output-on-failure + - bazel test -c dbg --define google_benchmark.have_regex=posix --announce_rc --verbose_failures --test_output=errors --keep_going //test/... + +after_success: + - if [ "${BUILD_TYPE}" == "Coverage" -a "${TRAVIS_OS_NAME}" == "linux" ]; then + coveralls --include src --include include --gcov-options '\-lp' --root .. --build-root .; + fi diff --git a/third_party/benchmark/.ycm_extra_conf.py b/third_party/benchmark/.ycm_extra_conf.py new file mode 100644 index 0000000..caf257f --- /dev/null +++ b/third_party/benchmark/.ycm_extra_conf.py @@ -0,0 +1,120 @@ +import os + +import ycm_core + +# These are the compilation flags that will be used in case there's no +# compilation database set (by default, one is not set). +# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR. +flags = [ + "-Wall", + "-Werror", + "-pedantic-errors", + "-std=c++0x", + "-fno-strict-aliasing", + "-O3", + "-DNDEBUG", + # ...and the same thing goes for the magic -x option which specifies the + # language that the files to be compiled are written in. This is mostly + # relevant for c++ headers. + # For a C project, you would set this to 'c' instead of 'c++'. + "-x", + "c++", + "-I", + "include", + "-isystem", + "/usr/include", + "-isystem", + "/usr/local/include", +] + + +# Set this to the absolute path to the folder (NOT the file!) containing the +# compile_commands.json file to use that instead of 'flags'. See here for +# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html +# +# Most projects will NOT need to set this to anything; you can just change the +# 'flags' list of compilation flags. Notice that YCM itself uses that approach. +compilation_database_folder = "" + +if os.path.exists(compilation_database_folder): + database = ycm_core.CompilationDatabase(compilation_database_folder) +else: + database = None + +SOURCE_EXTENSIONS = [".cc"] + + +def DirectoryOfThisScript(): + return os.path.dirname(os.path.abspath(__file__)) + + +def MakeRelativePathsInFlagsAbsolute(flags, working_directory): + if not working_directory: + return list(flags) + new_flags = [] + make_next_absolute = False + path_flags = ["-isystem", "-I", "-iquote", "--sysroot="] + for flag in flags: + new_flag = flag + + if make_next_absolute: + make_next_absolute = False + if not flag.startswith("/"): + new_flag = os.path.join(working_directory, flag) + + for path_flag in path_flags: + if flag == path_flag: + make_next_absolute = True + break + + if flag.startswith(path_flag): + path = flag[len(path_flag) :] + new_flag = path_flag + os.path.join(working_directory, path) + break + + if new_flag: + new_flags.append(new_flag) + return new_flags + + +def IsHeaderFile(filename): + extension = os.path.splitext(filename)[1] + return extension in [".h", ".hxx", ".hpp", ".hh"] + + +def GetCompilationInfoForFile(filename): + # The compilation_commands.json file generated by CMake does not have entries + # for header files. So we do our best by asking the db for flags for a + # corresponding source file, if any. If one exists, the flags for that file + # should be good enough. + if IsHeaderFile(filename): + basename = os.path.splitext(filename)[0] + for extension in SOURCE_EXTENSIONS: + replacement_file = basename + extension + if os.path.exists(replacement_file): + compilation_info = database.GetCompilationInfoForFile( + replacement_file + ) + if compilation_info.compiler_flags_: + return compilation_info + return None + return database.GetCompilationInfoForFile(filename) + + +def FlagsForFile(filename, **kwargs): + if database: + # Bear in mind that compilation_info.compiler_flags_ does NOT return a + # python list, but a "list-like" StringVec object + compilation_info = GetCompilationInfoForFile(filename) + if not compilation_info: + return None + + final_flags = MakeRelativePathsInFlagsAbsolute( + compilation_info.compiler_flags_, + compilation_info.compiler_working_dir_, + ) + else: + relative_to = DirectoryOfThisScript() + final_flags = MakeRelativePathsInFlagsAbsolute(flags, relative_to) + + return {"flags": final_flags, "do_cache": True} diff --git a/third_party/benchmark/AUTHORS b/third_party/benchmark/AUTHORS new file mode 100644 index 0000000..2170e46 --- /dev/null +++ b/third_party/benchmark/AUTHORS @@ -0,0 +1,72 @@ +# This is the official list of benchmark authors for copyright purposes. +# This file is distinct from the CONTRIBUTORS files. +# See the latter for an explanation. +# +# Names should be added to this file as: +# Name or Organization +# The email address is not required for organizations. +# +# Please keep the list sorted. + +Albert Pretorius +Alex Steele +Andriy Berestovskyy +Arne Beer +Carto +Cezary SkrzyÅ„ski +Christian Wassermann +Christopher Seymour +Colin Braley +Daniel Harvey +David Coeurjolly +Deniz Evrenci +Dirac Research +Dominik Czarnota +Dominik Korman +Donald Aingworth +Eric Backus +Eric Fiselier +Eugene Zhuk +Evgeny Safronov +Fabien Pichot +Federico Ficarelli +Felix Homann +Gergely Meszaros +GergÅ‘ Szitár +Google Inc. +Henrique Bucher +International Business Machines Corporation +Ismael Jimenez Martinez +Jern-Kuan Leong +JianXiong Zhou +Joao Paulo Magalhaes +Jordan Williams +Jussi Knuuttila +Kaito Udagawa +Kishan Kumar +Lei Xu +Marcel Jacobse +Matt Clarkson +Maxim Vafin +Mike Apodaca +Min-Yih Hsu +MongoDB Inc. +Nick Hutchinson +Norman Heino +Oleksandr Sochka +Ori Livneh +Paul Redmond +Radoslav Yovchev +Raghu Raja +Rainer Orth +Roman Lebedev +Sayan Bhattacharjee +Shapr3D +Shuo Chen +Staffan Tjernstrom +Steinar H. Gunderson +Stripe, Inc. +Tobias Schmidt +Yixuan Qiu +Yusuke Suzuki +Zbigniew Skowron diff --git a/third_party/benchmark/BUILD.bazel b/third_party/benchmark/BUILD.bazel new file mode 100644 index 0000000..15d8369 --- /dev/null +++ b/third_party/benchmark/BUILD.bazel @@ -0,0 +1,114 @@ +licenses(["notice"]) + +COPTS = [ + "-pedantic", + "-pedantic-errors", + "-std=c++11", + "-Wall", + "-Wconversion", + "-Wextra", + "-Wshadow", + # "-Wshorten-64-to-32", + "-Wfloat-equal", + "-fstrict-aliasing", + ## assert() are used a lot in tests upstream, which may be optimised out leading to + ## unused-variable warning. + "-Wno-unused-variable", + "-Werror=old-style-cast", +] + +config_setting( + name = "qnx", + constraint_values = ["@platforms//os:qnx"], + values = { + "cpu": "x64_qnx", + }, + visibility = [":__subpackages__"], +) + +config_setting( + name = "windows", + constraint_values = ["@platforms//os:windows"], + values = { + "cpu": "x64_windows", + }, + visibility = [":__subpackages__"], +) + +config_setting( + name = "macos", + constraint_values = ["@platforms//os:macos"], + visibility = ["//visibility:public"], +) + +config_setting( + name = "perfcounters", + define_values = { + "pfm": "1", + }, + visibility = [":__subpackages__"], +) + +cc_library( + name = "benchmark", + srcs = glob( + [ + "src/*.cc", + "src/*.h", + ], + exclude = ["src/benchmark_main.cc"], + ), + hdrs = [ + "include/benchmark/benchmark.h", + "include/benchmark/export.h", + ], + copts = select({ + ":windows": [], + "//conditions:default": COPTS, + }), + defines = [ + "BENCHMARK_STATIC_DEFINE", + "BENCHMARK_VERSION=\\\"" + (module_version() if module_version() != None else "") + "\\\"", + ] + select({ + ":perfcounters": ["HAVE_LIBPFM"], + "//conditions:default": [], + }), + linkopts = select({ + ":windows": ["-DEFAULTLIB:shlwapi.lib"], + "//conditions:default": ["-pthread"], + }), + # Only static linking is allowed; no .so will be produced. + # Using `defines` (i.e. not `local_defines`) means that no + # dependent rules need to bother about defining the macro. + linkstatic = True, + local_defines = [ + # Turn on Large-file Support + "_FILE_OFFSET_BITS=64", + "_LARGEFILE64_SOURCE", + "_LARGEFILE_SOURCE", + ], + strip_include_prefix = "include", + visibility = ["//visibility:public"], + deps = select({ + ":perfcounters": ["@libpfm"], + "//conditions:default": [], + }), +) + +cc_library( + name = "benchmark_main", + srcs = ["src/benchmark_main.cc"], + hdrs = [ + "include/benchmark/benchmark.h", + "include/benchmark/export.h", + ], + strip_include_prefix = "include", + visibility = ["//visibility:public"], + deps = [":benchmark"], +) + +cc_library( + name = "benchmark_internal_headers", + hdrs = glob(["src/*.h"]), + visibility = ["//test:__pkg__"], +) diff --git a/third_party/benchmark/CMakeLists.txt b/third_party/benchmark/CMakeLists.txt new file mode 100644 index 0000000..5dc74e8 --- /dev/null +++ b/third_party/benchmark/CMakeLists.txt @@ -0,0 +1,355 @@ +# Require CMake 3.10. If available, use the policies up to CMake 3.22. +cmake_minimum_required (VERSION 3.10...3.22) + +project (benchmark VERSION 1.8.4 LANGUAGES CXX) + +option(BENCHMARK_ENABLE_TESTING "Enable testing of the benchmark library." OFF) +option(BENCHMARK_ENABLE_EXCEPTIONS "Enable the use of exceptions in the benchmark library." ON) +option(BENCHMARK_ENABLE_LTO "Enable link time optimisation of the benchmark library." OFF) +option(BENCHMARK_USE_LIBCXX "Build and test using libc++ as the standard library." OFF) +option(BENCHMARK_ENABLE_WERROR "Build Release candidates with -Werror." ON) +option(BENCHMARK_FORCE_WERROR "Build Release candidates with -Werror regardless of compiler issues." OFF) + +if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "PGI") + # PGC++ maybe reporting false positives. + set(BENCHMARK_ENABLE_WERROR OFF) +endif() +if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "NVHPC") + set(BENCHMARK_ENABLE_WERROR OFF) +endif() +if(BENCHMARK_FORCE_WERROR) + set(BENCHMARK_ENABLE_WERROR ON) +endif(BENCHMARK_FORCE_WERROR) + +if(NOT (MSVC OR CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC")) + option(BENCHMARK_BUILD_32_BITS "Build a 32 bit version of the library." OFF) +else() + set(BENCHMARK_BUILD_32_BITS OFF CACHE BOOL "Build a 32 bit version of the library - unsupported when using MSVC)" FORCE) +endif() +option(BENCHMARK_ENABLE_INSTALL "Enable installation of benchmark. (Projects embedding benchmark may want to turn this OFF.)" ON) +option(BENCHMARK_ENABLE_DOXYGEN "Build documentation with Doxygen." OFF) +option(BENCHMARK_INSTALL_DOCS "Enable installation of documentation." OFF) + +# Allow unmet dependencies to be met using CMake's ExternalProject mechanics, which +# may require downloading the source code. +option(BENCHMARK_DOWNLOAD_DEPENDENCIES "Allow the downloading and in-tree building of unmet dependencies" OFF) + +# This option can be used to disable building and running unit tests which depend on gtest +# in cases where it is not possible to build or find a valid version of gtest. +option(BENCHMARK_ENABLE_GTEST_TESTS "Enable building the unit tests which depend on gtest" OFF) +option(BENCHMARK_USE_BUNDLED_GTEST "Use bundled GoogleTest. If disabled, the find_package(GTest) will be used." ON) + +option(BENCHMARK_ENABLE_LIBPFM "Enable performance counters provided by libpfm" OFF) + +# Export only public symbols +set(CMAKE_CXX_VISIBILITY_PRESET hidden) +set(CMAKE_VISIBILITY_INLINES_HIDDEN ON) + +if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") + # As of CMake 3.18, CMAKE_SYSTEM_PROCESSOR is not set properly for MSVC and + # cross-compilation (e.g. Host=x86_64, target=aarch64) requires using the + # undocumented, but working variable. + # See https://gitlab.kitware.com/cmake/cmake/-/issues/15170 + set(CMAKE_SYSTEM_PROCESSOR ${MSVC_CXX_ARCHITECTURE_ID}) + if(${CMAKE_SYSTEM_PROCESSOR} MATCHES "ARM") + set(CMAKE_CROSSCOMPILING TRUE) + endif() +endif() + +set(ENABLE_ASSEMBLY_TESTS_DEFAULT OFF) +function(should_enable_assembly_tests) + if(CMAKE_BUILD_TYPE) + string(TOLOWER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_LOWER) + if (${CMAKE_BUILD_TYPE_LOWER} MATCHES "coverage") + # FIXME: The --coverage flag needs to be removed when building assembly + # tests for this to work. + return() + endif() + endif() + if (MSVC OR CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC") + return() + elseif(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64") + return() + elseif(NOT CMAKE_SIZEOF_VOID_P EQUAL 8) + # FIXME: Make these work on 32 bit builds + return() + elseif(BENCHMARK_BUILD_32_BITS) + # FIXME: Make these work on 32 bit builds + return() + endif() + find_program(LLVM_FILECHECK_EXE FileCheck) + if (LLVM_FILECHECK_EXE) + set(LLVM_FILECHECK_EXE "${LLVM_FILECHECK_EXE}" CACHE PATH "llvm filecheck" FORCE) + message(STATUS "LLVM FileCheck Found: ${LLVM_FILECHECK_EXE}") + else() + message(STATUS "Failed to find LLVM FileCheck") + return() + endif() + set(ENABLE_ASSEMBLY_TESTS_DEFAULT ON PARENT_SCOPE) +endfunction() +should_enable_assembly_tests() + +# This option disables the building and running of the assembly verification tests +option(BENCHMARK_ENABLE_ASSEMBLY_TESTS "Enable building and running the assembly tests" + ${ENABLE_ASSEMBLY_TESTS_DEFAULT}) + +# Make sure we can import out CMake functions +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules") +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") + + +# Read the git tags to determine the project version +include(GetGitVersion) +get_git_version(GIT_VERSION) + +# If no git version can be determined, use the version +# from the project() command +if ("${GIT_VERSION}" STREQUAL "0.0.0") + set(VERSION "v${benchmark_VERSION}") +else() + set(VERSION "${GIT_VERSION}") +endif() + +# Normalize version: drop "v" prefix, replace first "-" with ".", +# drop everything after second "-" (including said "-"). +string(STRIP ${VERSION} VERSION) +if(VERSION MATCHES v[^-]*-) + string(REGEX REPLACE "v([^-]*)-([0-9]+)-.*" "\\1.\\2" NORMALIZED_VERSION ${VERSION}) +else() + string(REGEX REPLACE "v(.*)" "\\1" NORMALIZED_VERSION ${VERSION}) +endif() + +# Tell the user what versions we are using +message(STATUS "Google Benchmark version: ${VERSION}, normalized to ${NORMALIZED_VERSION}") + +# The version of the libraries +set(GENERIC_LIB_VERSION ${NORMALIZED_VERSION}) +string(SUBSTRING ${NORMALIZED_VERSION} 0 1 GENERIC_LIB_SOVERSION) + +# Import our CMake modules +include(AddCXXCompilerFlag) +include(CheckCXXCompilerFlag) +include(CheckLibraryExists) +include(CXXFeatureCheck) + +check_library_exists(rt shm_open "" HAVE_LIB_RT) + +if (BENCHMARK_BUILD_32_BITS) + add_required_cxx_compiler_flag(-m32) +endif() + +if (MSVC OR CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC") + set(BENCHMARK_CXX_STANDARD 14) +else() + set(BENCHMARK_CXX_STANDARD 11) +endif() + +set(CMAKE_CXX_STANDARD ${BENCHMARK_CXX_STANDARD}) +set(CMAKE_CXX_STANDARD_REQUIRED YES) +set(CMAKE_CXX_EXTENSIONS OFF) + +if (MSVC) + # Turn compiler warnings up to 11 + string(REGEX REPLACE "[-/]W[1-4]" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4") + add_definitions(-D_CRT_SECURE_NO_WARNINGS) + + if (NOT BENCHMARK_ENABLE_EXCEPTIONS) + add_cxx_compiler_flag(-EHs-) + add_cxx_compiler_flag(-EHa-) + add_definitions(-D_HAS_EXCEPTIONS=0) + endif() + # Link time optimisation + if (BENCHMARK_ENABLE_LTO) + set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /GL") + set(CMAKE_STATIC_LINKER_FLAGS_RELEASE "${CMAKE_STATIC_LINKER_FLAGS_RELEASE} /LTCG") + set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /LTCG") + set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} /LTCG") + + set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /GL") + string(REGEX REPLACE "[-/]INCREMENTAL" "/INCREMENTAL:NO" CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO}") + set(CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO} /LTCG") + string(REGEX REPLACE "[-/]INCREMENTAL" "/INCREMENTAL:NO" CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO}") + set(CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO} /LTCG") + string(REGEX REPLACE "[-/]INCREMENTAL" "/INCREMENTAL:NO" CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO}") + set(CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO} /LTCG") + + set(CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL} /GL") + set(CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL "${CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL} /LTCG") + set(CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL "${CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL} /LTCG") + set(CMAKE_EXE_LINKER_FLAGS_MINSIZEREL "${CMAKE_EXE_LINKER_FLAGS_MINSIZEREL} /LTCG") + endif() +else() + # Turn on Large-file Support + add_definitions(-D_FILE_OFFSET_BITS=64) + add_definitions(-D_LARGEFILE64_SOURCE) + add_definitions(-D_LARGEFILE_SOURCE) + # Turn compiler warnings up to 11 + add_cxx_compiler_flag(-Wall) + add_cxx_compiler_flag(-Wextra) + add_cxx_compiler_flag(-Wshadow) + add_cxx_compiler_flag(-Wfloat-equal) + add_cxx_compiler_flag(-Wold-style-cast) + add_cxx_compiler_flag(-Wconversion) + if(BENCHMARK_ENABLE_WERROR) + add_cxx_compiler_flag(-Werror) + endif() + if (NOT BENCHMARK_ENABLE_TESTING) + # Disable warning when compiling tests as gtest does not use 'override'. + add_cxx_compiler_flag(-Wsuggest-override) + endif() + add_cxx_compiler_flag(-pedantic) + add_cxx_compiler_flag(-pedantic-errors) + add_cxx_compiler_flag(-Wshorten-64-to-32) + add_cxx_compiler_flag(-fstrict-aliasing) + # Disable warnings regarding deprecated parts of the library while building + # and testing those parts of the library. + add_cxx_compiler_flag(-Wno-deprecated-declarations) + if (CMAKE_CXX_COMPILER_ID STREQUAL "Intel" OR CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM") + # Intel silently ignores '-Wno-deprecated-declarations', + # warning no. 1786 must be explicitly disabled. + # See #631 for rationale. + add_cxx_compiler_flag(-wd1786) + add_cxx_compiler_flag(-fno-finite-math-only) + endif() + # Disable deprecation warnings for release builds (when -Werror is enabled). + if(BENCHMARK_ENABLE_WERROR) + add_cxx_compiler_flag(-Wno-deprecated) + endif() + if (NOT BENCHMARK_ENABLE_EXCEPTIONS) + add_cxx_compiler_flag(-fno-exceptions) + endif() + + if (HAVE_CXX_FLAG_FSTRICT_ALIASING) + if (NOT CMAKE_CXX_COMPILER_ID STREQUAL "Intel" AND NOT CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM") #ICC17u2: Many false positives for Wstrict-aliasing + add_cxx_compiler_flag(-Wstrict-aliasing) + endif() + endif() + # ICC17u2: overloaded virtual function "benchmark::Fixture::SetUp" is only partially overridden + # (because of deprecated overload) + add_cxx_compiler_flag(-wd654) + add_cxx_compiler_flag(-Wthread-safety) + if (HAVE_CXX_FLAG_WTHREAD_SAFETY) + cxx_feature_check(THREAD_SAFETY_ATTRIBUTES "-DINCLUDE_DIRECTORIES=${PROJECT_SOURCE_DIR}/include") + endif() + + # On most UNIX like platforms g++ and clang++ define _GNU_SOURCE as a + # predefined macro, which turns on all of the wonderful libc extensions. + # However g++ doesn't do this in Cygwin so we have to define it ourselves + # since we depend on GNU/POSIX/BSD extensions. + if (CYGWIN) + add_definitions(-D_GNU_SOURCE=1) + endif() + + if (QNXNTO) + add_definitions(-D_QNX_SOURCE) + endif() + + # Link time optimisation + if (BENCHMARK_ENABLE_LTO) + add_cxx_compiler_flag(-flto) + add_cxx_compiler_flag(-Wno-lto-type-mismatch) + if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + find_program(GCC_AR gcc-ar) + if (GCC_AR) + set(CMAKE_AR ${GCC_AR}) + endif() + find_program(GCC_RANLIB gcc-ranlib) + if (GCC_RANLIB) + set(CMAKE_RANLIB ${GCC_RANLIB}) + endif() + elseif("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") + include(llvm-toolchain) + endif() + endif() + + # Coverage build type + set(BENCHMARK_CXX_FLAGS_COVERAGE "${CMAKE_CXX_FLAGS_DEBUG}" + CACHE STRING "Flags used by the C++ compiler during coverage builds." + FORCE) + set(BENCHMARK_EXE_LINKER_FLAGS_COVERAGE "${CMAKE_EXE_LINKER_FLAGS_DEBUG}" + CACHE STRING "Flags used for linking binaries during coverage builds." + FORCE) + set(BENCHMARK_SHARED_LINKER_FLAGS_COVERAGE "${CMAKE_SHARED_LINKER_FLAGS_DEBUG}" + CACHE STRING "Flags used by the shared libraries linker during coverage builds." + FORCE) + mark_as_advanced( + BENCHMARK_CXX_FLAGS_COVERAGE + BENCHMARK_EXE_LINKER_FLAGS_COVERAGE + BENCHMARK_SHARED_LINKER_FLAGS_COVERAGE) + set(CMAKE_BUILD_TYPE "${CMAKE_BUILD_TYPE}" CACHE STRING + "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel Coverage.") + add_cxx_compiler_flag(--coverage COVERAGE) +endif() + +if (BENCHMARK_USE_LIBCXX) + if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") + add_cxx_compiler_flag(-stdlib=libc++) + elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR + "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Intel" OR + "${CMAKE_CXX_COMPILER_ID}" STREQUAL "IntelLLVM") + add_cxx_compiler_flag(-nostdinc++) + message(WARNING "libc++ header path must be manually specified using CMAKE_CXX_FLAGS") + # Adding -nodefaultlibs directly to CMAKE__LINKER_FLAGS will break + # configuration checks such as 'find_package(Threads)' + list(APPEND BENCHMARK_CXX_LINKER_FLAGS -nodefaultlibs) + # -lc++ cannot be added directly to CMAKE__LINKER_FLAGS because + # linker flags appear before all linker inputs and -lc++ must appear after. + list(APPEND BENCHMARK_CXX_LIBRARIES c++) + else() + message(FATAL_ERROR "-DBENCHMARK_USE_LIBCXX:BOOL=ON is not supported for compiler") + endif() +endif(BENCHMARK_USE_LIBCXX) + +set(EXTRA_CXX_FLAGS "") +if (WIN32 AND "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") + # Clang on Windows fails to compile the regex feature check under C++11 + set(EXTRA_CXX_FLAGS "-DCMAKE_CXX_STANDARD=14") +endif() + +# C++ feature checks +# Determine the correct regular expression engine to use +cxx_feature_check(STD_REGEX ${EXTRA_CXX_FLAGS}) +cxx_feature_check(GNU_POSIX_REGEX ${EXTRA_CXX_FLAGS}) +cxx_feature_check(POSIX_REGEX ${EXTRA_CXX_FLAGS}) +if(NOT HAVE_STD_REGEX AND NOT HAVE_GNU_POSIX_REGEX AND NOT HAVE_POSIX_REGEX) + message(FATAL_ERROR "Failed to determine the source files for the regular expression backend") +endif() +if (NOT BENCHMARK_ENABLE_EXCEPTIONS AND HAVE_STD_REGEX + AND NOT HAVE_GNU_POSIX_REGEX AND NOT HAVE_POSIX_REGEX) + message(WARNING "Using std::regex with exceptions disabled is not fully supported") +endif() + +cxx_feature_check(STEADY_CLOCK) +# Ensure we have pthreads +set(THREADS_PREFER_PTHREAD_FLAG ON) +find_package(Threads REQUIRED) +cxx_feature_check(PTHREAD_AFFINITY) + +if (BENCHMARK_ENABLE_LIBPFM) + find_package(PFM REQUIRED) +endif() + +# Set up directories +include_directories(${PROJECT_SOURCE_DIR}/include) + +# Build the targets +add_subdirectory(src) + +if (BENCHMARK_ENABLE_TESTING) + enable_testing() + if (BENCHMARK_ENABLE_GTEST_TESTS AND + NOT (TARGET gtest AND TARGET gtest_main AND + TARGET gmock AND TARGET gmock_main)) + if (BENCHMARK_USE_BUNDLED_GTEST) + include(GoogleTest) + else() + find_package(GTest CONFIG REQUIRED) + add_library(gtest ALIAS GTest::gtest) + add_library(gtest_main ALIAS GTest::gtest_main) + add_library(gmock ALIAS GTest::gmock) + add_library(gmock_main ALIAS GTest::gmock_main) + endif() + endif() + add_subdirectory(test) +endif() diff --git a/third_party/benchmark/CONTRIBUTING.md b/third_party/benchmark/CONTRIBUTING.md new file mode 100644 index 0000000..43de4c9 --- /dev/null +++ b/third_party/benchmark/CONTRIBUTING.md @@ -0,0 +1,58 @@ +# How to contribute # + +We'd love to accept your patches and contributions to this project. There are +a just a few small guidelines you need to follow. + + +## Contributor License Agreement ## + +Contributions to any Google project must be accompanied by a Contributor +License Agreement. This is not a copyright **assignment**, it simply gives +Google permission to use and redistribute your contributions as part of the +project. + + * If you are an individual writing original source code and you're sure you + own the intellectual property, then you'll need to sign an [individual + CLA][]. + + * If you work for a company that wants to allow you to contribute your work, + then you'll need to sign a [corporate CLA][]. + +You generally only need to submit a CLA once, so if you've already submitted +one (even if it was for a different project), you probably don't need to do it +again. + +[individual CLA]: https://developers.google.com/open-source/cla/individual +[corporate CLA]: https://developers.google.com/open-source/cla/corporate + +Once your CLA is submitted (or if you already submitted one for +another Google project), make a commit adding yourself to the +[AUTHORS][] and [CONTRIBUTORS][] files. This commit can be part +of your first [pull request][]. + +[AUTHORS]: AUTHORS +[CONTRIBUTORS]: CONTRIBUTORS + + +## Submitting a patch ## + + 1. It's generally best to start by opening a new issue describing the bug or + feature you're intending to fix. Even if you think it's relatively minor, + it's helpful to know what people are working on. Mention in the initial + issue that you are planning to work on that bug or feature so that it can + be assigned to you. + + 1. Follow the normal process of [forking][] the project, and setup a new + branch to work in. It's important that each group of changes be done in + separate branches in order to ensure that a pull request only includes the + commits related to that bug or feature. + + 1. Do your best to have [well-formed commit messages][] for each change. + This provides consistency throughout the project, and ensures that commit + messages are able to be formatted properly by various git tools. + + 1. Finally, push the commits to your fork and submit a [pull request][]. + +[forking]: https://help.github.com/articles/fork-a-repo +[well-formed commit messages]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html +[pull request]: https://help.github.com/articles/creating-a-pull-request diff --git a/third_party/benchmark/CONTRIBUTORS b/third_party/benchmark/CONTRIBUTORS new file mode 100644 index 0000000..9ca2caa --- /dev/null +++ b/third_party/benchmark/CONTRIBUTORS @@ -0,0 +1,97 @@ +# People who have agreed to one of the CLAs and can contribute patches. +# The AUTHORS file lists the copyright holders; this file +# lists people. For example, Google employees are listed here +# but not in AUTHORS, because Google holds the copyright. +# +# Names should be added to this file only after verifying that +# the individual or the individual's organization has agreed to +# the appropriate Contributor License Agreement, found here: +# +# https://developers.google.com/open-source/cla/individual +# https://developers.google.com/open-source/cla/corporate +# +# The agreement for individuals can be filled out on the web. +# +# When adding J Random Contributor's name to this file, +# either J's name or J's organization's name should be +# added to the AUTHORS file, depending on whether the +# individual or corporate CLA was used. +# +# Names should be added to this file as: +# Name +# +# Please keep the list sorted. + +Abhina Sreeskantharajan +Albert Pretorius +Alex Steele +Andriy Berestovskyy +Arne Beer +Bátor Tallér +Billy Robert O'Neal III +Cezary SkrzyÅ„ski +Chris Kennelly +Christian Wassermann +Christopher Seymour +Colin Braley +Cyrille Faucheux +Daniel Harvey +David Coeurjolly +Deniz Evrenci +Dominic Hamon +Dominik Czarnota +Dominik Korman +Donald Aingworth +Eric Backus +Eric Fiselier +Eugene Zhuk +Evgeny Safronov +Fabien Pichot +Fanbo Meng +Federico Ficarelli +Felix Homann +Geoffrey Martin-Noble +Gergely Meszaros +GergÅ‘ Szitár +Hannes Hauswedell +Henrique Bucher +Ismael Jimenez Martinez +Iakov Sergeev +Jern-Kuan Leong +JianXiong Zhou +Joao Paulo Magalhaes +John Millikin +Jordan Williams +Jussi Knuuttila +Kaito Udagawa +Kai Wolf +Kishan Kumar +Lei Xu +Marcel Jacobse +Matt Clarkson +Maxim Vafin +Mike Apodaca +Min-Yih Hsu +Nick Hutchinson +Norman Heino +Oleksandr Sochka +Ori Livneh +Pascal Leroy +Paul Redmond +Pierre Phaneuf +Radoslav Yovchev +Raghu Raja +Rainer Orth +Raul Marin +Ray Glover +Robert Guo +Roman Lebedev +Sayan Bhattacharjee +Shuo Chen +Steven Wan +Tobias Schmidt +Tobias UlvgÃ¥rd +Tom Madams +Yixuan Qiu +Yusuke Suzuki +Zbigniew Skowron diff --git a/third_party/benchmark/LICENSE b/third_party/benchmark/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/third_party/benchmark/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 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 + + http://www.apache.org/licenses/LICENSE-2.0 + + 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. diff --git a/third_party/benchmark/MODULE.bazel b/third_party/benchmark/MODULE.bazel new file mode 100644 index 0000000..0624a34 --- /dev/null +++ b/third_party/benchmark/MODULE.bazel @@ -0,0 +1,41 @@ +module( + name = "google_benchmark", + version = "1.8.4", +) + +bazel_dep(name = "bazel_skylib", version = "1.5.0") +bazel_dep(name = "platforms", version = "0.0.8") +bazel_dep(name = "rules_foreign_cc", version = "0.10.1") +bazel_dep(name = "rules_cc", version = "0.0.9") + +bazel_dep(name = "rules_python", version = "0.31.0", dev_dependency = True) +bazel_dep(name = "googletest", version = "1.12.1", dev_dependency = True, repo_name = "com_google_googletest") + +bazel_dep(name = "libpfm", version = "4.11.0") + +# Register a toolchain for Python 3.9 to be able to build numpy. Python +# versions >=3.10 are problematic. +# A second reason for this is to be able to build Python hermetically instead +# of relying on the changing default version from rules_python. + +python = use_extension("@rules_python//python/extensions:python.bzl", "python", dev_dependency = True) +python.toolchain(python_version = "3.8") +python.toolchain(python_version = "3.9") +python.toolchain(python_version = "3.10") +python.toolchain(python_version = "3.11") +python.toolchain( + is_default = True, + python_version = "3.12", +) + +pip = use_extension("@rules_python//python/extensions:pip.bzl", "pip", dev_dependency = True) +pip.parse( + hub_name = "tools_pip_deps", + python_version = "3.9", + requirements_lock = "//tools:requirements.txt", +) +use_repo(pip, "tools_pip_deps") + +# -- bazel_dep definitions -- # + +bazel_dep(name = "nanobind_bazel", version = "1.0.0", dev_dependency = True) diff --git a/third_party/benchmark/README.md b/third_party/benchmark/README.md new file mode 100644 index 0000000..a5e5d39 --- /dev/null +++ b/third_party/benchmark/README.md @@ -0,0 +1,223 @@ +# Benchmark + +[![build-and-test](https://github.com/google/benchmark/workflows/build-and-test/badge.svg)](https://github.com/google/benchmark/actions?query=workflow%3Abuild-and-test) +[![bazel](https://github.com/google/benchmark/actions/workflows/bazel.yml/badge.svg)](https://github.com/google/benchmark/actions/workflows/bazel.yml) +[![pylint](https://github.com/google/benchmark/workflows/pylint/badge.svg)](https://github.com/google/benchmark/actions?query=workflow%3Apylint) +[![test-bindings](https://github.com/google/benchmark/workflows/test-bindings/badge.svg)](https://github.com/google/benchmark/actions?query=workflow%3Atest-bindings) +[![Coverage Status](https://coveralls.io/repos/google/benchmark/badge.svg)](https://coveralls.io/r/google/benchmark) + +[![Discord](https://discordapp.com/api/guilds/1125694995928719494/widget.png?style=shield)](https://discord.gg/cz7UX7wKC2) + +A library to benchmark code snippets, similar to unit tests. Example: + +```c++ +#include + +static void BM_SomeFunction(benchmark::State& state) { + // Perform setup here + for (auto _ : state) { + // This code gets timed + SomeFunction(); + } +} +// Register the function as a benchmark +BENCHMARK(BM_SomeFunction); +// Run the benchmark +BENCHMARK_MAIN(); +``` + +## Getting Started + +To get started, see [Requirements](#requirements) and +[Installation](#installation). See [Usage](#usage) for a full example and the +[User Guide](docs/user_guide.md) for a more comprehensive feature overview. + +It may also help to read the [Google Test documentation](https://github.com/google/googletest/blob/main/docs/primer.md) +as some of the structural aspects of the APIs are similar. + +## Resources + +[Discussion group](https://groups.google.com/d/forum/benchmark-discuss) + +IRC channels: +* [libera](https://libera.chat) #benchmark + +[Additional Tooling Documentation](docs/tools.md) + +[Assembly Testing Documentation](docs/AssemblyTests.md) + +[Building and installing Python bindings](docs/python_bindings.md) + +## Requirements + +The library can be used with C++03. However, it requires C++11 to build, +including compiler and standard library support. + +The following minimum versions are required to build the library: + +* GCC 4.8 +* Clang 3.4 +* Visual Studio 14 2015 +* Intel 2015 Update 1 + +See [Platform-Specific Build Instructions](docs/platform_specific_build_instructions.md). + +## Installation + +This describes the installation process using cmake. As pre-requisites, you'll +need git and cmake installed. + +_See [dependencies.md](docs/dependencies.md) for more details regarding supported +versions of build tools._ + +```bash +# Check out the library. +$ git clone https://github.com/google/benchmark.git +# Go to the library root directory +$ cd benchmark +# Make a build directory to place the build output. +$ cmake -E make_directory "build" +# Generate build system files with cmake, and download any dependencies. +$ cmake -E chdir "build" cmake -DBENCHMARK_DOWNLOAD_DEPENDENCIES=on -DCMAKE_BUILD_TYPE=Release ../ +# or, starting with CMake 3.13, use a simpler form: +# cmake -DCMAKE_BUILD_TYPE=Release -S . -B "build" +# Build the library. +$ cmake --build "build" --config Release +``` +This builds the `benchmark` and `benchmark_main` libraries and tests. +On a unix system, the build directory should now look something like this: + +``` +/benchmark + /build + /src + /libbenchmark.a + /libbenchmark_main.a + /test + ... +``` + +Next, you can run the tests to check the build. + +```bash +$ cmake -E chdir "build" ctest --build-config Release +``` + +If you want to install the library globally, also run: + +``` +sudo cmake --build "build" --config Release --target install +``` + +Note that Google Benchmark requires Google Test to build and run the tests. This +dependency can be provided two ways: + +* Checkout the Google Test sources into `benchmark/googletest`. +* Otherwise, if `-DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON` is specified during + configuration as above, the library will automatically download and build + any required dependencies. + +If you do not wish to build and run the tests, add `-DBENCHMARK_ENABLE_GTEST_TESTS=OFF` +to `CMAKE_ARGS`. + +### Debug vs Release + +By default, benchmark builds as a debug library. You will see a warning in the +output when this is the case. To build it as a release library instead, add +`-DCMAKE_BUILD_TYPE=Release` when generating the build system files, as shown +above. The use of `--config Release` in build commands is needed to properly +support multi-configuration tools (like Visual Studio for example) and can be +skipped for other build systems (like Makefile). + +To enable link-time optimisation, also add `-DBENCHMARK_ENABLE_LTO=true` when +generating the build system files. + +If you are using gcc, you might need to set `GCC_AR` and `GCC_RANLIB` cmake +cache variables, if autodetection fails. + +If you are using clang, you may need to set `LLVMAR_EXECUTABLE`, +`LLVMNM_EXECUTABLE` and `LLVMRANLIB_EXECUTABLE` cmake cache variables. + +To enable sanitizer checks (eg., `asan` and `tsan`), add: +``` + -DCMAKE_C_FLAGS="-g -O2 -fno-omit-frame-pointer -fsanitize=address -fsanitize=thread -fno-sanitize-recover=all" + -DCMAKE_CXX_FLAGS="-g -O2 -fno-omit-frame-pointer -fsanitize=address -fsanitize=thread -fno-sanitize-recover=all " +``` + +### Stable and Experimental Library Versions + +The main branch contains the latest stable version of the benchmarking library; +the API of which can be considered largely stable, with source breaking changes +being made only upon the release of a new major version. + +Newer, experimental, features are implemented and tested on the +[`v2` branch](https://github.com/google/benchmark/tree/v2). Users who wish +to use, test, and provide feedback on the new features are encouraged to try +this branch. However, this branch provides no stability guarantees and reserves +the right to change and break the API at any time. + +## Usage + +### Basic usage + +Define a function that executes the code to measure, register it as a benchmark +function using the `BENCHMARK` macro, and ensure an appropriate `main` function +is available: + +```c++ +#include + +static void BM_StringCreation(benchmark::State& state) { + for (auto _ : state) + std::string empty_string; +} +// Register the function as a benchmark +BENCHMARK(BM_StringCreation); + +// Define another benchmark +static void BM_StringCopy(benchmark::State& state) { + std::string x = "hello"; + for (auto _ : state) + std::string copy(x); +} +BENCHMARK(BM_StringCopy); + +BENCHMARK_MAIN(); +``` + +To run the benchmark, compile and link against the `benchmark` library +(libbenchmark.a/.so). If you followed the build steps above, this library will +be under the build directory you created. + +```bash +# Example on linux after running the build steps above. Assumes the +# `benchmark` and `build` directories are under the current directory. +$ g++ mybenchmark.cc -std=c++11 -isystem benchmark/include \ + -Lbenchmark/build/src -lbenchmark -lpthread -o mybenchmark +``` + +Alternatively, link against the `benchmark_main` library and remove +`BENCHMARK_MAIN();` above to get the same behavior. + +The compiled executable will run all benchmarks by default. Pass the `--help` +flag for option information or see the [User Guide](docs/user_guide.md). + +### Usage with CMake + +If using CMake, it is recommended to link against the project-provided +`benchmark::benchmark` and `benchmark::benchmark_main` targets using +`target_link_libraries`. +It is possible to use ```find_package``` to import an installed version of the +library. +```cmake +find_package(benchmark REQUIRED) +``` +Alternatively, ```add_subdirectory``` will incorporate the library directly in +to one's CMake project. +```cmake +add_subdirectory(benchmark) +``` +Either way, link to the library as follows. +```cmake +target_link_libraries(MyTarget benchmark::benchmark) +``` diff --git a/third_party/benchmark/WORKSPACE b/third_party/benchmark/WORKSPACE new file mode 100644 index 0000000..5032024 --- /dev/null +++ b/third_party/benchmark/WORKSPACE @@ -0,0 +1,24 @@ +workspace(name = "com_github_google_benchmark") + +load("//:bazel/benchmark_deps.bzl", "benchmark_deps") + +benchmark_deps() + +load("@rules_foreign_cc//foreign_cc:repositories.bzl", "rules_foreign_cc_dependencies") + +rules_foreign_cc_dependencies() + +load("@rules_python//python:repositories.bzl", "py_repositories") + +py_repositories() + +load("@rules_python//python:pip.bzl", "pip_parse") + +pip_parse( + name = "tools_pip_deps", + requirements_lock = "//tools:requirements.txt", +) + +load("@tools_pip_deps//:requirements.bzl", "install_deps") + +install_deps() diff --git a/third_party/benchmark/WORKSPACE.bzlmod b/third_party/benchmark/WORKSPACE.bzlmod new file mode 100644 index 0000000..9526376 --- /dev/null +++ b/third_party/benchmark/WORKSPACE.bzlmod @@ -0,0 +1,2 @@ +# This file marks the root of the Bazel workspace. +# See MODULE.bazel for dependencies and setup. diff --git a/third_party/benchmark/_config.yml b/third_party/benchmark/_config.yml new file mode 100644 index 0000000..1fa5ff8 --- /dev/null +++ b/third_party/benchmark/_config.yml @@ -0,0 +1,2 @@ +theme: jekyll-theme-midnight +markdown: GFM diff --git a/third_party/benchmark/appveyor.yml b/third_party/benchmark/appveyor.yml new file mode 100644 index 0000000..81da955 --- /dev/null +++ b/third_party/benchmark/appveyor.yml @@ -0,0 +1,50 @@ +version: '{build}' + +image: Visual Studio 2017 + +configuration: + - Debug + - Release + +environment: + matrix: + - compiler: msvc-15-seh + generator: "Visual Studio 15 2017" + + - compiler: msvc-15-seh + generator: "Visual Studio 15 2017 Win64" + + - compiler: msvc-14-seh + generator: "Visual Studio 14 2015" + + - compiler: msvc-14-seh + generator: "Visual Studio 14 2015 Win64" + + - compiler: gcc-5.3.0-posix + generator: "MinGW Makefiles" + cxx_path: 'C:\mingw-w64\i686-5.3.0-posix-dwarf-rt_v4-rev0\mingw32\bin' + APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015 + +matrix: + fast_finish: true + +install: + # git bash conflicts with MinGW makefiles + - if "%generator%"=="MinGW Makefiles" (set "PATH=%PATH:C:\Program Files\Git\usr\bin;=%") + - if not "%cxx_path%"=="" (set "PATH=%PATH%;%cxx_path%") + +build_script: + - md _build -Force + - cd _build + - echo %configuration% + - cmake -G "%generator%" "-DCMAKE_BUILD_TYPE=%configuration%" -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON .. + - cmake --build . --config %configuration% + +test_script: + - ctest --build-config %configuration% --timeout 300 --output-on-failure + +artifacts: + - path: '_build/CMakeFiles/*.log' + name: logs + - path: '_build/Testing/**/*.xml' + name: test_results diff --git a/third_party/benchmark/bazel/benchmark_deps.bzl b/third_party/benchmark/bazel/benchmark_deps.bzl new file mode 100644 index 0000000..4fb45a5 --- /dev/null +++ b/third_party/benchmark/bazel/benchmark_deps.bzl @@ -0,0 +1,62 @@ +""" +This file contains the Bazel build dependencies for Google Benchmark (both C++ source and Python bindings). +""" + +load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository") +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + +def benchmark_deps(): + """Loads dependencies required to build Google Benchmark.""" + + if "bazel_skylib" not in native.existing_rules(): + http_archive( + name = "bazel_skylib", + sha256 = "cd55a062e763b9349921f0f5db8c3933288dc8ba4f76dd9416aac68acee3cb94", + urls = [ + "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.5.0/bazel-skylib-1.5.0.tar.gz", + "https://github.com/bazelbuild/bazel-skylib/releases/download/1.5.0/bazel-skylib-1.5.0.tar.gz", + ], + ) + + if "rules_foreign_cc" not in native.existing_rules(): + http_archive( + name = "rules_foreign_cc", + sha256 = "476303bd0f1b04cc311fc258f1708a5f6ef82d3091e53fd1977fa20383425a6a", + strip_prefix = "rules_foreign_cc-0.10.1", + url = "https://github.com/bazelbuild/rules_foreign_cc/releases/download/0.10.1/rules_foreign_cc-0.10.1.tar.gz", + ) + + if "rules_python" not in native.existing_rules(): + http_archive( + name = "rules_python", + sha256 = "e85ae30de33625a63eca7fc40a94fea845e641888e52f32b6beea91e8b1b2793", + strip_prefix = "rules_python-0.27.1", + url = "https://github.com/bazelbuild/rules_python/releases/download/0.27.1/rules_python-0.27.1.tar.gz", + ) + + if "com_google_googletest" not in native.existing_rules(): + new_git_repository( + name = "com_google_googletest", + remote = "https://github.com/google/googletest.git", + tag = "release-1.12.1", + ) + + if "nanobind" not in native.existing_rules(): + new_git_repository( + name = "nanobind", + remote = "https://github.com/wjakob/nanobind.git", + tag = "v1.8.0", + build_file = "@//bindings/python:nanobind.BUILD", + recursive_init_submodules = True, + ) + + if "libpfm" not in native.existing_rules(): + # Downloaded from v4.9.0 tag at https://sourceforge.net/p/perfmon2/libpfm4/ref/master/tags/ + http_archive( + name = "libpfm", + build_file = str(Label("//tools:libpfm.BUILD.bazel")), + sha256 = "5da5f8872bde14b3634c9688d980f68bda28b510268723cc12973eedbab9fecc", + type = "tar.gz", + strip_prefix = "libpfm-4.11.0", + urls = ["https://sourceforge.net/projects/perfmon2/files/libpfm4/libpfm-4.11.0.tar.gz/download"], + ) diff --git a/third_party/benchmark/bindings/python/google_benchmark/BUILD b/third_party/benchmark/bindings/python/google_benchmark/BUILD new file mode 100644 index 0000000..0c8e3c1 --- /dev/null +++ b/third_party/benchmark/bindings/python/google_benchmark/BUILD @@ -0,0 +1,27 @@ +load("@nanobind_bazel//:build_defs.bzl", "nanobind_extension") + +py_library( + name = "google_benchmark", + srcs = ["__init__.py"], + visibility = ["//visibility:public"], + deps = [ + ":_benchmark", + ], +) + +nanobind_extension( + name = "_benchmark", + srcs = ["benchmark.cc"], + deps = ["//:benchmark"], +) + +py_test( + name = "example", + srcs = ["example.py"], + python_version = "PY3", + srcs_version = "PY3", + visibility = ["//visibility:public"], + deps = [ + ":google_benchmark", + ], +) diff --git a/third_party/benchmark/bindings/python/google_benchmark/__init__.py b/third_party/benchmark/bindings/python/google_benchmark/__init__.py new file mode 100644 index 0000000..c1393b4 --- /dev/null +++ b/third_party/benchmark/bindings/python/google_benchmark/__init__.py @@ -0,0 +1,141 @@ +# Copyright 2020 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# 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. +"""Python benchmarking utilities. + +Example usage: + import google_benchmark as benchmark + + @benchmark.register + def my_benchmark(state): + ... # Code executed outside `while` loop is not timed. + + while state: + ... # Code executed within `while` loop is timed. + + if __name__ == '__main__': + benchmark.main() +""" + +import atexit + +from absl import app + +from google_benchmark import _benchmark +from google_benchmark._benchmark import ( + Counter as Counter, + State as State, + kMicrosecond as kMicrosecond, + kMillisecond as kMillisecond, + kNanosecond as kNanosecond, + kSecond as kSecond, + o1 as o1, + oAuto as oAuto, + oLambda as oLambda, + oLogN as oLogN, + oN as oN, + oNCubed as oNCubed, + oNLogN as oNLogN, + oNone as oNone, + oNSquared as oNSquared, +) +from google_benchmark.version import __version__ as __version__ + + +class __OptionMaker: + """A stateless class to collect benchmark options. + + Collect all decorator calls like @option.range(start=0, limit=1<<5). + """ + + class Options: + """Pure data class to store options calls, along with the benchmarked function.""" + + def __init__(self, func): + self.func = func + self.builder_calls = [] + + @classmethod + def make(cls, func_or_options): + """Make Options from Options or the benchmarked function.""" + if isinstance(func_or_options, cls.Options): + return func_or_options + return cls.Options(func_or_options) + + def __getattr__(self, builder_name): + """Append option call in the Options.""" + + # The function that get returned on @option.range(start=0, limit=1<<5). + def __builder_method(*args, **kwargs): + # The decorator that get called, either with the benchmared function + # or the previous Options + def __decorator(func_or_options): + options = self.make(func_or_options) + options.builder_calls.append((builder_name, args, kwargs)) + # The decorator returns Options so it is not technically a decorator + # and needs a final call to @register + return options + + return __decorator + + return __builder_method + + +# Alias for nicer API. +# We have to instantiate an object, even if stateless, to be able to use __getattr__ +# on option.range +option = __OptionMaker() + + +def register(undefined=None, *, name=None): + """Register function for benchmarking.""" + if undefined is None: + # Decorator is called without parenthesis so we return a decorator + return lambda f: register(f, name=name) + + # We have either the function to benchmark (simple case) or an instance of Options + # (@option._ case). + options = __OptionMaker.make(undefined) + + if name is None: + name = options.func.__name__ + + # We register the benchmark and reproduce all the @option._ calls onto the + # benchmark builder pattern + benchmark = _benchmark.RegisterBenchmark(name, options.func) + for name, args, kwargs in options.builder_calls[::-1]: + getattr(benchmark, name)(*args, **kwargs) + + # return the benchmarked function because the decorator does not modify it + return options.func + + +def _flags_parser(argv): + argv = _benchmark.Initialize(argv) + return app.parse_flags_with_usage(argv) + + +def _run_benchmarks(argv): + if len(argv) > 1: + raise app.UsageError("Too many command-line arguments.") + return _benchmark.RunSpecifiedBenchmarks() + + +def main(argv=None): + return app.run(_run_benchmarks, argv=argv, flags_parser=_flags_parser) + + +# Methods for use with custom main function. +initialize = _benchmark.Initialize +run_benchmarks = _benchmark.RunSpecifiedBenchmarks +atexit.register(_benchmark.ClearRegisteredBenchmarks) diff --git a/third_party/benchmark/bindings/python/google_benchmark/benchmark.cc b/third_party/benchmark/bindings/python/google_benchmark/benchmark.cc new file mode 100644 index 0000000..f444769 --- /dev/null +++ b/third_party/benchmark/bindings/python/google_benchmark/benchmark.cc @@ -0,0 +1,184 @@ +// Benchmark for Python. + +#include "benchmark/benchmark.h" + +#include "nanobind/nanobind.h" +#include "nanobind/operators.h" +#include "nanobind/stl/bind_map.h" +#include "nanobind/stl/string.h" +#include "nanobind/stl/vector.h" + +NB_MAKE_OPAQUE(benchmark::UserCounters); + +namespace { +namespace nb = nanobind; + +std::vector Initialize(const std::vector& argv) { + // The `argv` pointers here become invalid when this function returns, but + // benchmark holds the pointer to `argv[0]`. We create a static copy of it + // so it persists, and replace the pointer below. + static std::string executable_name(argv[0]); + std::vector ptrs; + ptrs.reserve(argv.size()); + for (auto& arg : argv) { + ptrs.push_back(const_cast(arg.c_str())); + } + ptrs[0] = const_cast(executable_name.c_str()); + int argc = static_cast(argv.size()); + benchmark::Initialize(&argc, ptrs.data()); + std::vector remaining_argv; + remaining_argv.reserve(argc); + for (int i = 0; i < argc; ++i) { + remaining_argv.emplace_back(ptrs[i]); + } + return remaining_argv; +} + +benchmark::internal::Benchmark* RegisterBenchmark(const std::string& name, + nb::callable f) { + return benchmark::RegisterBenchmark( + name, [f](benchmark::State& state) { f(&state); }); +} + +NB_MODULE(_benchmark, m) { + + using benchmark::TimeUnit; + nb::enum_(m, "TimeUnit") + .value("kNanosecond", TimeUnit::kNanosecond) + .value("kMicrosecond", TimeUnit::kMicrosecond) + .value("kMillisecond", TimeUnit::kMillisecond) + .value("kSecond", TimeUnit::kSecond) + .export_values(); + + using benchmark::BigO; + nb::enum_(m, "BigO") + .value("oNone", BigO::oNone) + .value("o1", BigO::o1) + .value("oN", BigO::oN) + .value("oNSquared", BigO::oNSquared) + .value("oNCubed", BigO::oNCubed) + .value("oLogN", BigO::oLogN) + .value("oNLogN", BigO::oNLogN) + .value("oAuto", BigO::oAuto) + .value("oLambda", BigO::oLambda) + .export_values(); + + using benchmark::internal::Benchmark; + nb::class_(m, "Benchmark") + // For methods returning a pointer to the current object, reference + // return policy is used to ask nanobind not to take ownership of the + // returned object and avoid calling delete on it. + // https://pybind11.readthedocs.io/en/stable/advanced/functions.html#return-value-policies + // + // For methods taking a const std::vector<...>&, a copy is created + // because a it is bound to a Python list. + // https://pybind11.readthedocs.io/en/stable/advanced/cast/stl.html + .def("unit", &Benchmark::Unit, nb::rv_policy::reference) + .def("arg", &Benchmark::Arg, nb::rv_policy::reference) + .def("args", &Benchmark::Args, nb::rv_policy::reference) + .def("range", &Benchmark::Range, nb::rv_policy::reference, + nb::arg("start"), nb::arg("limit")) + .def("dense_range", &Benchmark::DenseRange, + nb::rv_policy::reference, nb::arg("start"), + nb::arg("limit"), nb::arg("step") = 1) + .def("ranges", &Benchmark::Ranges, nb::rv_policy::reference) + .def("args_product", &Benchmark::ArgsProduct, + nb::rv_policy::reference) + .def("arg_name", &Benchmark::ArgName, nb::rv_policy::reference) + .def("arg_names", &Benchmark::ArgNames, + nb::rv_policy::reference) + .def("range_pair", &Benchmark::RangePair, + nb::rv_policy::reference, nb::arg("lo1"), nb::arg("hi1"), + nb::arg("lo2"), nb::arg("hi2")) + .def("range_multiplier", &Benchmark::RangeMultiplier, + nb::rv_policy::reference) + .def("min_time", &Benchmark::MinTime, nb::rv_policy::reference) + .def("min_warmup_time", &Benchmark::MinWarmUpTime, + nb::rv_policy::reference) + .def("iterations", &Benchmark::Iterations, + nb::rv_policy::reference) + .def("repetitions", &Benchmark::Repetitions, + nb::rv_policy::reference) + .def("report_aggregates_only", &Benchmark::ReportAggregatesOnly, + nb::rv_policy::reference, nb::arg("value") = true) + .def("display_aggregates_only", &Benchmark::DisplayAggregatesOnly, + nb::rv_policy::reference, nb::arg("value") = true) + .def("measure_process_cpu_time", &Benchmark::MeasureProcessCPUTime, + nb::rv_policy::reference) + .def("use_real_time", &Benchmark::UseRealTime, + nb::rv_policy::reference) + .def("use_manual_time", &Benchmark::UseManualTime, + nb::rv_policy::reference) + .def( + "complexity", + (Benchmark * (Benchmark::*)(benchmark::BigO)) & Benchmark::Complexity, + nb::rv_policy::reference, + nb::arg("complexity") = benchmark::oAuto); + + using benchmark::Counter; + nb::class_ py_counter(m, "Counter"); + + nb::enum_(py_counter, "Flags") + .value("kDefaults", Counter::Flags::kDefaults) + .value("kIsRate", Counter::Flags::kIsRate) + .value("kAvgThreads", Counter::Flags::kAvgThreads) + .value("kAvgThreadsRate", Counter::Flags::kAvgThreadsRate) + .value("kIsIterationInvariant", Counter::Flags::kIsIterationInvariant) + .value("kIsIterationInvariantRate", + Counter::Flags::kIsIterationInvariantRate) + .value("kAvgIterations", Counter::Flags::kAvgIterations) + .value("kAvgIterationsRate", Counter::Flags::kAvgIterationsRate) + .value("kInvert", Counter::Flags::kInvert) + .export_values() + .def(nb::self | nb::self); + + nb::enum_(py_counter, "OneK") + .value("kIs1000", Counter::OneK::kIs1000) + .value("kIs1024", Counter::OneK::kIs1024) + .export_values(); + + py_counter + .def(nb::init(), + nb::arg("value") = 0., nb::arg("flags") = Counter::kDefaults, + nb::arg("k") = Counter::kIs1000) + .def("__init__", ([](Counter *c, double value) { new (c) Counter(value); })) + .def_rw("value", &Counter::value) + .def_rw("flags", &Counter::flags) + .def_rw("oneK", &Counter::oneK) + .def(nb::init_implicit()); + + nb::implicitly_convertible(); + + nb::bind_map(m, "UserCounters"); + + using benchmark::State; + nb::class_(m, "State") + .def("__bool__", &State::KeepRunning) + .def_prop_ro("keep_running", &State::KeepRunning) + .def("pause_timing", &State::PauseTiming) + .def("resume_timing", &State::ResumeTiming) + .def("skip_with_error", &State::SkipWithError) + .def_prop_ro("error_occurred", &State::error_occurred) + .def("set_iteration_time", &State::SetIterationTime) + .def_prop_rw("bytes_processed", &State::bytes_processed, + &State::SetBytesProcessed) + .def_prop_rw("complexity_n", &State::complexity_length_n, + &State::SetComplexityN) + .def_prop_rw("items_processed", &State::items_processed, + &State::SetItemsProcessed) + .def("set_label", &State::SetLabel) + .def("range", &State::range, nb::arg("pos") = 0) + .def_prop_ro("iterations", &State::iterations) + .def_prop_ro("name", &State::name) + .def_rw("counters", &State::counters) + .def_prop_ro("thread_index", &State::thread_index) + .def_prop_ro("threads", &State::threads); + + m.def("Initialize", Initialize); + m.def("RegisterBenchmark", RegisterBenchmark, + nb::rv_policy::reference); + m.def("RunSpecifiedBenchmarks", + []() { benchmark::RunSpecifiedBenchmarks(); }); + m.def("ClearRegisteredBenchmarks", benchmark::ClearRegisteredBenchmarks); +}; +} // namespace diff --git a/third_party/benchmark/bindings/python/google_benchmark/example.py b/third_party/benchmark/bindings/python/google_benchmark/example.py new file mode 100644 index 0000000..b5b2f88 --- /dev/null +++ b/third_party/benchmark/bindings/python/google_benchmark/example.py @@ -0,0 +1,139 @@ +# Copyright 2020 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# 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. +"""Example of Python using C++ benchmark framework. + +To run this example, you must first install the `google_benchmark` Python package. + +To install using `setup.py`, download and extract the `google_benchmark` source. +In the extracted directory, execute: + python setup.py install +""" + +import random +import time + +import google_benchmark as benchmark +from google_benchmark import Counter + + +@benchmark.register +def empty(state): + while state: + pass + + +@benchmark.register +def sum_million(state): + while state: + sum(range(1_000_000)) + + +@benchmark.register +def pause_timing(state): + """Pause timing every iteration.""" + while state: + # Construct a list of random ints every iteration without timing it + state.pause_timing() + random_list = [random.randint(0, 100) for _ in range(100)] + state.resume_timing() + # Time the in place sorting algorithm + random_list.sort() + + +@benchmark.register +def skipped(state): + if True: # Test some predicate here. + state.skip_with_error("some error") + return # NOTE: You must explicitly return, or benchmark will continue. + + ... # Benchmark code would be here. + + +@benchmark.register +def manual_timing(state): + while state: + # Manually count Python CPU time + start = time.perf_counter() # perf_counter_ns() in Python 3.7+ + # Something to benchmark + time.sleep(0.01) + end = time.perf_counter() + state.set_iteration_time(end - start) + + +@benchmark.register +def custom_counters(state): + """Collect custom metric using benchmark.Counter.""" + num_foo = 0.0 + while state: + # Benchmark some code here + pass + # Collect some custom metric named foo + num_foo += 0.13 + + # Automatic Counter from numbers. + state.counters["foo"] = num_foo + # Set a counter as a rate. + state.counters["foo_rate"] = Counter(num_foo, Counter.kIsRate) + # Set a counter as an inverse of rate. + state.counters["foo_inv_rate"] = Counter( + num_foo, Counter.kIsRate | Counter.kInvert + ) + # Set a counter as a thread-average quantity. + state.counters["foo_avg"] = Counter(num_foo, Counter.kAvgThreads) + # There's also a combined flag: + state.counters["foo_avg_rate"] = Counter(num_foo, Counter.kAvgThreadsRate) + + +@benchmark.register +@benchmark.option.measure_process_cpu_time() +@benchmark.option.use_real_time() +def with_options(state): + while state: + sum(range(1_000_000)) + + +@benchmark.register(name="sum_million_microseconds") +@benchmark.option.unit(benchmark.kMicrosecond) +def with_options2(state): + while state: + sum(range(1_000_000)) + + +@benchmark.register +@benchmark.option.arg(100) +@benchmark.option.arg(1000) +def passing_argument(state): + while state: + sum(range(state.range(0))) + + +@benchmark.register +@benchmark.option.range(8, limit=8 << 10) +def using_range(state): + while state: + sum(range(state.range(0))) + + +@benchmark.register +@benchmark.option.range_multiplier(2) +@benchmark.option.range(1 << 10, 1 << 18) +@benchmark.option.complexity(benchmark.oN) +def computing_complexity(state): + while state: + sum(range(state.range(0))) + state.complexity_n = state.range(0) + + +if __name__ == "__main__": + benchmark.main() diff --git a/third_party/benchmark/bindings/python/google_benchmark/version.py b/third_party/benchmark/bindings/python/google_benchmark/version.py new file mode 100644 index 0000000..a324693 --- /dev/null +++ b/third_party/benchmark/bindings/python/google_benchmark/version.py @@ -0,0 +1,7 @@ +from importlib.metadata import PackageNotFoundError, version + +try: + __version__ = version("google-benchmark") +except PackageNotFoundError: + # package is not installed + pass diff --git a/third_party/benchmark/cmake/AddCXXCompilerFlag.cmake b/third_party/benchmark/cmake/AddCXXCompilerFlag.cmake new file mode 100644 index 0000000..858589e --- /dev/null +++ b/third_party/benchmark/cmake/AddCXXCompilerFlag.cmake @@ -0,0 +1,78 @@ +# - Adds a compiler flag if it is supported by the compiler +# +# This function checks that the supplied compiler flag is supported and then +# adds it to the corresponding compiler flags +# +# add_cxx_compiler_flag( []) +# +# - Example +# +# include(AddCXXCompilerFlag) +# add_cxx_compiler_flag(-Wall) +# add_cxx_compiler_flag(-no-strict-aliasing RELEASE) +# Requires CMake 2.6+ + +if(__add_cxx_compiler_flag) + return() +endif() +set(__add_cxx_compiler_flag INCLUDED) + +include(CheckCXXCompilerFlag) + +function(mangle_compiler_flag FLAG OUTPUT) + string(TOUPPER "HAVE_CXX_FLAG_${FLAG}" SANITIZED_FLAG) + string(REPLACE "+" "X" SANITIZED_FLAG ${SANITIZED_FLAG}) + string(REGEX REPLACE "[^A-Za-z_0-9]" "_" SANITIZED_FLAG ${SANITIZED_FLAG}) + string(REGEX REPLACE "_+" "_" SANITIZED_FLAG ${SANITIZED_FLAG}) + set(${OUTPUT} "${SANITIZED_FLAG}" PARENT_SCOPE) +endfunction(mangle_compiler_flag) + +function(add_cxx_compiler_flag FLAG) + mangle_compiler_flag("${FLAG}" MANGLED_FLAG) + set(OLD_CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") + set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${FLAG}") + check_cxx_compiler_flag("${FLAG}" ${MANGLED_FLAG}) + set(CMAKE_REQUIRED_FLAGS "${OLD_CMAKE_REQUIRED_FLAGS}") + if(${MANGLED_FLAG}) + if(ARGC GREATER 1) + set(VARIANT ${ARGV1}) + string(TOUPPER "_${VARIANT}" VARIANT) + else() + set(VARIANT "") + endif() + set(CMAKE_CXX_FLAGS${VARIANT} "${CMAKE_CXX_FLAGS${VARIANT}} ${BENCHMARK_CXX_FLAGS${VARIANT}} ${FLAG}" PARENT_SCOPE) + endif() +endfunction() + +function(add_required_cxx_compiler_flag FLAG) + mangle_compiler_flag("${FLAG}" MANGLED_FLAG) + set(OLD_CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") + set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${FLAG}") + check_cxx_compiler_flag("${FLAG}" ${MANGLED_FLAG}) + set(CMAKE_REQUIRED_FLAGS "${OLD_CMAKE_REQUIRED_FLAGS}") + if(${MANGLED_FLAG}) + if(ARGC GREATER 1) + set(VARIANT ${ARGV1}) + string(TOUPPER "_${VARIANT}" VARIANT) + else() + set(VARIANT "") + endif() + set(CMAKE_CXX_FLAGS${VARIANT} "${CMAKE_CXX_FLAGS${VARIANT}} ${FLAG}" PARENT_SCOPE) + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${FLAG}" PARENT_SCOPE) + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${FLAG}" PARENT_SCOPE) + set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${FLAG}" PARENT_SCOPE) + set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${FLAG}" PARENT_SCOPE) + else() + message(FATAL_ERROR "Required flag '${FLAG}' is not supported by the compiler") + endif() +endfunction() + +function(check_cxx_warning_flag FLAG) + mangle_compiler_flag("${FLAG}" MANGLED_FLAG) + set(OLD_CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") + # Add -Werror to ensure the compiler generates an error if the warning flag + # doesn't exist. + set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -Werror ${FLAG}") + check_cxx_compiler_flag("${FLAG}" ${MANGLED_FLAG}) + set(CMAKE_REQUIRED_FLAGS "${OLD_CMAKE_REQUIRED_FLAGS}") +endfunction() diff --git a/third_party/benchmark/cmake/CXXFeatureCheck.cmake b/third_party/benchmark/cmake/CXXFeatureCheck.cmake new file mode 100644 index 0000000..e514826 --- /dev/null +++ b/third_party/benchmark/cmake/CXXFeatureCheck.cmake @@ -0,0 +1,82 @@ +# - Compile and run code to check for C++ features +# +# This functions compiles a source file under the `cmake` folder +# and adds the corresponding `HAVE_[FILENAME]` flag to the CMake +# environment +# +# cxx_feature_check( []) +# +# - Example +# +# include(CXXFeatureCheck) +# cxx_feature_check(STD_REGEX) +# Requires CMake 2.8.12+ + +if(__cxx_feature_check) + return() +endif() +set(__cxx_feature_check INCLUDED) + +option(CXXFEATURECHECK_DEBUG OFF) + +function(cxx_feature_check FILE) + string(TOLOWER ${FILE} FILE) + string(TOUPPER ${FILE} VAR) + string(TOUPPER "HAVE_${VAR}" FEATURE) + if (DEFINED HAVE_${VAR}) + set(HAVE_${VAR} 1 PARENT_SCOPE) + add_definitions(-DHAVE_${VAR}) + return() + endif() + + set(FEATURE_CHECK_CMAKE_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS}) + if (ARGC GREATER 1) + message(STATUS "Enabling additional flags: ${ARGV1}") + list(APPEND FEATURE_CHECK_CMAKE_FLAGS ${ARGV1}) + endif() + + if (NOT DEFINED COMPILE_${FEATURE}) + if(CMAKE_CROSSCOMPILING) + message(STATUS "Cross-compiling to test ${FEATURE}") + try_compile(COMPILE_${FEATURE} + ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/${FILE}.cpp + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED ON + CMAKE_FLAGS ${FEATURE_CHECK_CMAKE_FLAGS} + LINK_LIBRARIES ${BENCHMARK_CXX_LIBRARIES} + OUTPUT_VARIABLE COMPILE_OUTPUT_VAR) + if(COMPILE_${FEATURE}) + message(WARNING + "If you see build failures due to cross compilation, try setting HAVE_${VAR} to 0") + set(RUN_${FEATURE} 0 CACHE INTERNAL "") + else() + set(RUN_${FEATURE} 1 CACHE INTERNAL "") + endif() + else() + message(STATUS "Compiling and running to test ${FEATURE}") + try_run(RUN_${FEATURE} COMPILE_${FEATURE} + ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/${FILE}.cpp + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED ON + CMAKE_FLAGS ${FEATURE_CHECK_CMAKE_FLAGS} + LINK_LIBRARIES ${BENCHMARK_CXX_LIBRARIES} + COMPILE_OUTPUT_VARIABLE COMPILE_OUTPUT_VAR) + endif() + endif() + + if(RUN_${FEATURE} EQUAL 0) + message(STATUS "Performing Test ${FEATURE} -- success") + set(HAVE_${VAR} 1 PARENT_SCOPE) + add_definitions(-DHAVE_${VAR}) + else() + if(NOT COMPILE_${FEATURE}) + if(CXXFEATURECHECK_DEBUG) + message(STATUS "Performing Test ${FEATURE} -- failed to compile: ${COMPILE_OUTPUT_VAR}") + else() + message(STATUS "Performing Test ${FEATURE} -- failed to compile") + endif() + else() + message(STATUS "Performing Test ${FEATURE} -- compiled but failed to run") + endif() + endif() +endfunction() diff --git a/third_party/benchmark/cmake/Config.cmake.in b/third_party/benchmark/cmake/Config.cmake.in new file mode 100644 index 0000000..2e15f0c --- /dev/null +++ b/third_party/benchmark/cmake/Config.cmake.in @@ -0,0 +1,7 @@ +@PACKAGE_INIT@ + +include (CMakeFindDependencyMacro) + +find_dependency (Threads) + +include("${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake") diff --git a/third_party/benchmark/cmake/GetGitVersion.cmake b/third_party/benchmark/cmake/GetGitVersion.cmake new file mode 100644 index 0000000..b021010 --- /dev/null +++ b/third_party/benchmark/cmake/GetGitVersion.cmake @@ -0,0 +1,36 @@ +# - Returns a version string from Git tags +# +# This function inspects the annotated git tags for the project and returns a string +# into a CMake variable +# +# get_git_version() +# +# - Example +# +# include(GetGitVersion) +# get_git_version(GIT_VERSION) +# +# Requires CMake 2.8.11+ +find_package(Git) + +if(__get_git_version) + return() +endif() +set(__get_git_version INCLUDED) + +function(get_git_version var) + if(GIT_EXECUTABLE) + execute_process(COMMAND ${GIT_EXECUTABLE} describe --tags --match "v[0-9]*.[0-9]*.[0-9]*" --abbrev=8 --dirty + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} + RESULT_VARIABLE status + OUTPUT_VARIABLE GIT_VERSION + ERROR_QUIET) + if(status) + set(GIT_VERSION "v0.0.0") + endif() + else() + set(GIT_VERSION "v0.0.0") + endif() + + set(${var} ${GIT_VERSION} PARENT_SCOPE) +endfunction() diff --git a/third_party/benchmark/cmake/GoogleTest.cmake b/third_party/benchmark/cmake/GoogleTest.cmake new file mode 100644 index 0000000..e66e9d1 --- /dev/null +++ b/third_party/benchmark/cmake/GoogleTest.cmake @@ -0,0 +1,58 @@ +# Download and unpack googletest at configure time +set(GOOGLETEST_PREFIX "${benchmark_BINARY_DIR}/third_party/googletest") +configure_file(${benchmark_SOURCE_DIR}/cmake/GoogleTest.cmake.in ${GOOGLETEST_PREFIX}/CMakeLists.txt @ONLY) + +set(GOOGLETEST_PATH "${CMAKE_CURRENT_SOURCE_DIR}/googletest" CACHE PATH "") # Mind the quotes +execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" + -DALLOW_DOWNLOADING_GOOGLETEST=${BENCHMARK_DOWNLOAD_DEPENDENCIES} -DGOOGLETEST_PATH:PATH=${GOOGLETEST_PATH} . + RESULT_VARIABLE result + WORKING_DIRECTORY ${GOOGLETEST_PREFIX} +) + +if(result) + message(FATAL_ERROR "CMake step for googletest failed: ${result}") +endif() + +execute_process( + COMMAND ${CMAKE_COMMAND} --build . + RESULT_VARIABLE result + WORKING_DIRECTORY ${GOOGLETEST_PREFIX} +) + +if(result) + message(FATAL_ERROR "Build step for googletest failed: ${result}") +endif() + +# Prevent overriding the parent project's compiler/linker +# settings on Windows +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) + +include(${GOOGLETEST_PREFIX}/googletest-paths.cmake) + +# Add googletest directly to our build. This defines +# the gtest and gtest_main targets. +add_subdirectory(${GOOGLETEST_SOURCE_DIR} + ${GOOGLETEST_BINARY_DIR} + EXCLUDE_FROM_ALL) + +# googletest doesn't seem to want to stay build warning clean so let's not hurt ourselves. +if (MSVC) + target_compile_options(gtest PRIVATE "/wd4244" "/wd4722") + target_compile_options(gtest_main PRIVATE "/wd4244" "/wd4722") + target_compile_options(gmock PRIVATE "/wd4244" "/wd4722") + target_compile_options(gmock_main PRIVATE "/wd4244" "/wd4722") +else() + target_compile_options(gtest PRIVATE "-w") + target_compile_options(gtest_main PRIVATE "-w") + target_compile_options(gmock PRIVATE "-w") + target_compile_options(gmock_main PRIVATE "-w") +endif() + +if(NOT DEFINED GTEST_COMPILE_COMMANDS) + set(GTEST_COMPILE_COMMANDS ON) +endif() + +set_target_properties(gtest PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES $ EXPORT_COMPILE_COMMANDS ${GTEST_COMPILE_COMMANDS}) +set_target_properties(gtest_main PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES $ EXPORT_COMPILE_COMMANDS ${GTEST_COMPILE_COMMANDS}) +set_target_properties(gmock PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES $ EXPORT_COMPILE_COMMANDS ${GTEST_COMPILE_COMMANDS}) +set_target_properties(gmock_main PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES $ EXPORT_COMPILE_COMMANDS ${GTEST_COMPILE_COMMANDS}) diff --git a/third_party/benchmark/cmake/GoogleTest.cmake.in b/third_party/benchmark/cmake/GoogleTest.cmake.in new file mode 100644 index 0000000..ce653ac --- /dev/null +++ b/third_party/benchmark/cmake/GoogleTest.cmake.in @@ -0,0 +1,59 @@ +cmake_minimum_required(VERSION 2.8.12) + +project(googletest-download NONE) + +# Enable ExternalProject CMake module +include(ExternalProject) + +option(ALLOW_DOWNLOADING_GOOGLETEST "If googletest src tree is not found in location specified by GOOGLETEST_PATH, do fetch the archive from internet" OFF) +set(GOOGLETEST_PATH "/usr/src/googletest" CACHE PATH + "Path to the googletest root tree. Should contain googletest and googlemock subdirs. And CMakeLists.txt in root, and in both of these subdirs") + +# Download and install GoogleTest + +message(STATUS "Looking for Google Test sources") +message(STATUS "Looking for Google Test sources in ${GOOGLETEST_PATH}") +if(EXISTS "${GOOGLETEST_PATH}" AND IS_DIRECTORY "${GOOGLETEST_PATH}" AND EXISTS "${GOOGLETEST_PATH}/CMakeLists.txt" AND + EXISTS "${GOOGLETEST_PATH}/googletest" AND IS_DIRECTORY "${GOOGLETEST_PATH}/googletest" AND EXISTS "${GOOGLETEST_PATH}/googletest/CMakeLists.txt" AND + EXISTS "${GOOGLETEST_PATH}/googlemock" AND IS_DIRECTORY "${GOOGLETEST_PATH}/googlemock" AND EXISTS "${GOOGLETEST_PATH}/googlemock/CMakeLists.txt") + message(STATUS "Found Google Test in ${GOOGLETEST_PATH}") + + ExternalProject_Add( + googletest + PREFIX "${CMAKE_BINARY_DIR}" + DOWNLOAD_DIR "${CMAKE_BINARY_DIR}/download" + SOURCE_DIR "${GOOGLETEST_PATH}" # use existing src dir. + BINARY_DIR "${CMAKE_BINARY_DIR}/build" + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND "" + TEST_COMMAND "" + ) +else() + if(NOT ALLOW_DOWNLOADING_GOOGLETEST) + message(SEND_ERROR "Did not find Google Test sources! Either pass correct path in GOOGLETEST_PATH, or enable BENCHMARK_DOWNLOAD_DEPENDENCIES, or disable BENCHMARK_USE_BUNDLED_GTEST, or disable BENCHMARK_ENABLE_GTEST_TESTS / BENCHMARK_ENABLE_TESTING.") + return() + else() + message(WARNING "Did not find Google Test sources! Fetching from web...") + ExternalProject_Add( + googletest + GIT_REPOSITORY https://github.com/google/googletest.git + GIT_TAG "release-1.11.0" + PREFIX "${CMAKE_BINARY_DIR}" + STAMP_DIR "${CMAKE_BINARY_DIR}/stamp" + DOWNLOAD_DIR "${CMAKE_BINARY_DIR}/download" + SOURCE_DIR "${CMAKE_BINARY_DIR}/src" + BINARY_DIR "${CMAKE_BINARY_DIR}/build" + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND "" + TEST_COMMAND "" + ) + endif() +endif() + +ExternalProject_Get_Property(googletest SOURCE_DIR BINARY_DIR) +file(WRITE googletest-paths.cmake +"set(GOOGLETEST_SOURCE_DIR \"${SOURCE_DIR}\") +set(GOOGLETEST_BINARY_DIR \"${BINARY_DIR}\") +") diff --git a/third_party/benchmark/cmake/benchmark.pc.in b/third_party/benchmark/cmake/benchmark.pc.in new file mode 100644 index 0000000..9dae881 --- /dev/null +++ b/third_party/benchmark/cmake/benchmark.pc.in @@ -0,0 +1,12 @@ +prefix=@CMAKE_INSTALL_PREFIX@ +exec_prefix=${prefix} +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: @PROJECT_NAME@ +Description: Google microbenchmark framework +Version: @VERSION@ + +Libs: -L${libdir} -lbenchmark +Libs.private: -lpthread +Cflags: -I${includedir} diff --git a/third_party/benchmark/cmake/benchmark_main.pc.in b/third_party/benchmark/cmake/benchmark_main.pc.in new file mode 100644 index 0000000..a90f3cd --- /dev/null +++ b/third_party/benchmark/cmake/benchmark_main.pc.in @@ -0,0 +1,7 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ + +Name: @PROJECT_NAME@ +Description: Google microbenchmark framework (with main() function) +Version: @VERSION@ +Requires: benchmark +Libs: -L${libdir} -lbenchmark_main diff --git a/third_party/benchmark/cmake/gnu_posix_regex.cpp b/third_party/benchmark/cmake/gnu_posix_regex.cpp new file mode 100644 index 0000000..b5b91cd --- /dev/null +++ b/third_party/benchmark/cmake/gnu_posix_regex.cpp @@ -0,0 +1,12 @@ +#include +#include +int main() { + std::string str = "test0159"; + regex_t re; + int ec = regcomp(&re, "^[a-z]+[0-9]+$", REG_EXTENDED | REG_NOSUB); + if (ec != 0) { + return ec; + } + return regexec(&re, str.c_str(), 0, nullptr, 0) ? -1 : 0; +} + diff --git a/third_party/benchmark/cmake/llvm-toolchain.cmake b/third_party/benchmark/cmake/llvm-toolchain.cmake new file mode 100644 index 0000000..fc119e5 --- /dev/null +++ b/third_party/benchmark/cmake/llvm-toolchain.cmake @@ -0,0 +1,8 @@ +find_package(LLVMAr REQUIRED) +set(CMAKE_AR "${LLVMAR_EXECUTABLE}" CACHE FILEPATH "" FORCE) + +find_package(LLVMNm REQUIRED) +set(CMAKE_NM "${LLVMNM_EXECUTABLE}" CACHE FILEPATH "" FORCE) + +find_package(LLVMRanLib REQUIRED) +set(CMAKE_RANLIB "${LLVMRANLIB_EXECUTABLE}" CACHE FILEPATH "" FORCE) diff --git a/third_party/benchmark/cmake/posix_regex.cpp b/third_party/benchmark/cmake/posix_regex.cpp new file mode 100644 index 0000000..466dc62 --- /dev/null +++ b/third_party/benchmark/cmake/posix_regex.cpp @@ -0,0 +1,14 @@ +#include +#include +int main() { + std::string str = "test0159"; + regex_t re; + int ec = regcomp(&re, "^[a-z]+[0-9]+$", REG_EXTENDED | REG_NOSUB); + if (ec != 0) { + return ec; + } + int ret = regexec(&re, str.c_str(), 0, nullptr, 0) ? -1 : 0; + regfree(&re); + return ret; +} + diff --git a/third_party/benchmark/cmake/pthread_affinity.cpp b/third_party/benchmark/cmake/pthread_affinity.cpp new file mode 100644 index 0000000..7b143bc --- /dev/null +++ b/third_party/benchmark/cmake/pthread_affinity.cpp @@ -0,0 +1,16 @@ +#include +int main() { + cpu_set_t set; + CPU_ZERO(&set); + for (int i = 0; i < CPU_SETSIZE; ++i) { + CPU_SET(i, &set); + CPU_CLR(i, &set); + } + pthread_t self = pthread_self(); + int ret; + ret = pthread_getaffinity_np(self, sizeof(set), &set); + if (ret != 0) return ret; + ret = pthread_setaffinity_np(self, sizeof(set), &set); + if (ret != 0) return ret; + return 0; +} diff --git a/third_party/benchmark/cmake/split_list.cmake b/third_party/benchmark/cmake/split_list.cmake new file mode 100644 index 0000000..67aed3f --- /dev/null +++ b/third_party/benchmark/cmake/split_list.cmake @@ -0,0 +1,3 @@ +macro(split_list listname) + string(REPLACE ";" " " ${listname} "${${listname}}") +endmacro() diff --git a/third_party/benchmark/cmake/std_regex.cpp b/third_party/benchmark/cmake/std_regex.cpp new file mode 100644 index 0000000..696f2a2 --- /dev/null +++ b/third_party/benchmark/cmake/std_regex.cpp @@ -0,0 +1,10 @@ +#include +#include +int main() { + const std::string str = "test0159"; + std::regex re; + re = std::regex("^[a-z]+[0-9]+$", + std::regex_constants::extended | std::regex_constants::nosubs); + return std::regex_search(str, re) ? 0 : -1; +} + diff --git a/third_party/benchmark/cmake/steady_clock.cpp b/third_party/benchmark/cmake/steady_clock.cpp new file mode 100644 index 0000000..66d50d1 --- /dev/null +++ b/third_party/benchmark/cmake/steady_clock.cpp @@ -0,0 +1,7 @@ +#include + +int main() { + typedef std::chrono::steady_clock Clock; + Clock::time_point tp = Clock::now(); + ((void)tp); +} diff --git a/third_party/benchmark/cmake/thread_safety_attributes.cpp b/third_party/benchmark/cmake/thread_safety_attributes.cpp new file mode 100644 index 0000000..46161ba --- /dev/null +++ b/third_party/benchmark/cmake/thread_safety_attributes.cpp @@ -0,0 +1,4 @@ +#define HAVE_THREAD_SAFETY_ATTRIBUTES +#include "../src/mutex.h" + +int main() {} diff --git a/third_party/benchmark/include/benchmark/benchmark.h b/third_party/benchmark/include/benchmark/benchmark.h new file mode 100644 index 0000000..895e09c --- /dev/null +++ b/third_party/benchmark/include/benchmark/benchmark.h @@ -0,0 +1,2040 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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. + +// Support for registering benchmarks for functions. + +/* Example usage: +// Define a function that executes the code to be measured a +// specified number of times: +static void BM_StringCreation(benchmark::State& state) { + for (auto _ : state) + std::string empty_string; +} + +// Register the function as a benchmark +BENCHMARK(BM_StringCreation); + +// Define another benchmark +static void BM_StringCopy(benchmark::State& state) { + std::string x = "hello"; + for (auto _ : state) + std::string copy(x); +} +BENCHMARK(BM_StringCopy); + +// Augment the main() program to invoke benchmarks if specified +// via the --benchmark_filter command line flag. E.g., +// my_unittest --benchmark_filter=all +// my_unittest --benchmark_filter=BM_StringCreation +// my_unittest --benchmark_filter=String +// my_unittest --benchmark_filter='Copy|Creation' +int main(int argc, char** argv) { + benchmark::Initialize(&argc, argv); + benchmark::RunSpecifiedBenchmarks(); + benchmark::Shutdown(); + return 0; +} + +// Sometimes a family of microbenchmarks can be implemented with +// just one routine that takes an extra argument to specify which +// one of the family of benchmarks to run. For example, the following +// code defines a family of microbenchmarks for measuring the speed +// of memcpy() calls of different lengths: + +static void BM_memcpy(benchmark::State& state) { + char* src = new char[state.range(0)]; char* dst = new char[state.range(0)]; + memset(src, 'x', state.range(0)); + for (auto _ : state) + memcpy(dst, src, state.range(0)); + state.SetBytesProcessed(state.iterations() * state.range(0)); + delete[] src; delete[] dst; +} +BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10); + +// The preceding code is quite repetitive, and can be replaced with the +// following short-hand. The following invocation will pick a few +// appropriate arguments in the specified range and will generate a +// microbenchmark for each such argument. +BENCHMARK(BM_memcpy)->Range(8, 8<<10); + +// You might have a microbenchmark that depends on two inputs. For +// example, the following code defines a family of microbenchmarks for +// measuring the speed of set insertion. +static void BM_SetInsert(benchmark::State& state) { + set data; + for (auto _ : state) { + state.PauseTiming(); + data = ConstructRandomSet(state.range(0)); + state.ResumeTiming(); + for (int j = 0; j < state.range(1); ++j) + data.insert(RandomNumber()); + } +} +BENCHMARK(BM_SetInsert) + ->Args({1<<10, 128}) + ->Args({2<<10, 128}) + ->Args({4<<10, 128}) + ->Args({8<<10, 128}) + ->Args({1<<10, 512}) + ->Args({2<<10, 512}) + ->Args({4<<10, 512}) + ->Args({8<<10, 512}); + +// The preceding code is quite repetitive, and can be replaced with +// the following short-hand. The following macro will pick a few +// appropriate arguments in the product of the two specified ranges +// and will generate a microbenchmark for each such pair. +BENCHMARK(BM_SetInsert)->Ranges({{1<<10, 8<<10}, {128, 512}}); + +// For more complex patterns of inputs, passing a custom function +// to Apply allows programmatic specification of an +// arbitrary set of arguments to run the microbenchmark on. +// The following example enumerates a dense range on +// one parameter, and a sparse range on the second. +static void CustomArguments(benchmark::internal::Benchmark* b) { + for (int i = 0; i <= 10; ++i) + for (int j = 32; j <= 1024*1024; j *= 8) + b->Args({i, j}); +} +BENCHMARK(BM_SetInsert)->Apply(CustomArguments); + +// Templated microbenchmarks work the same way: +// Produce then consume 'size' messages 'iters' times +// Measures throughput in the absence of multiprogramming. +template int BM_Sequential(benchmark::State& state) { + Q q; + typename Q::value_type v; + for (auto _ : state) { + for (int i = state.range(0); i--; ) + q.push(v); + for (int e = state.range(0); e--; ) + q.Wait(&v); + } + // actually messages, not bytes: + state.SetBytesProcessed(state.iterations() * state.range(0)); +} +BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue)->Range(1<<0, 1<<10); + +Use `Benchmark::MinTime(double t)` to set the minimum time used to run the +benchmark. This option overrides the `benchmark_min_time` flag. + +void BM_test(benchmark::State& state) { + ... body ... +} +BENCHMARK(BM_test)->MinTime(2.0); // Run for at least 2 seconds. + +In a multithreaded test, it is guaranteed that none of the threads will start +until all have reached the loop start, and all will have finished before any +thread exits the loop body. As such, any global setup or teardown you want to +do can be wrapped in a check against the thread index: + +static void BM_MultiThreaded(benchmark::State& state) { + if (state.thread_index() == 0) { + // Setup code here. + } + for (auto _ : state) { + // Run the test as normal. + } + if (state.thread_index() == 0) { + // Teardown code here. + } +} +BENCHMARK(BM_MultiThreaded)->Threads(4); + + +If a benchmark runs a few milliseconds it may be hard to visually compare the +measured times, since the output data is given in nanoseconds per default. In +order to manually set the time unit, you can specify it manually: + +BENCHMARK(BM_test)->Unit(benchmark::kMillisecond); +*/ + +#ifndef BENCHMARK_BENCHMARK_H_ +#define BENCHMARK_BENCHMARK_H_ + +// The _MSVC_LANG check should detect Visual Studio 2015 Update 3 and newer. +#if __cplusplus >= 201103L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201103L) +#define BENCHMARK_HAS_CXX11 +#endif + +// This _MSC_VER check should detect VS 2017 v15.3 and newer. +#if __cplusplus >= 201703L || \ + (defined(_MSC_VER) && _MSC_VER >= 1911 && _MSVC_LANG >= 201703L) +#define BENCHMARK_HAS_CXX17 +#endif + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "benchmark/export.h" + +#if defined(BENCHMARK_HAS_CXX11) +#include +#include +#include +#include +#endif + +#if defined(_MSC_VER) +#include // for _ReadWriteBarrier +#endif + +#ifndef BENCHMARK_HAS_CXX11 +#define BENCHMARK_DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName&); \ + TypeName& operator=(const TypeName&) +#else +#define BENCHMARK_DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName&) = delete; \ + TypeName& operator=(const TypeName&) = delete +#endif + +#ifdef BENCHMARK_HAS_CXX17 +#define BENCHMARK_UNUSED [[maybe_unused]] +#elif defined(__GNUC__) || defined(__clang__) +#define BENCHMARK_UNUSED __attribute__((unused)) +#else +#define BENCHMARK_UNUSED +#endif + +// Used to annotate functions, methods and classes so they +// are not optimized by the compiler. Useful for tests +// where you expect loops to stay in place churning cycles +#if defined(__clang__) +#define BENCHMARK_DONT_OPTIMIZE __attribute__((optnone)) +#elif defined(__GNUC__) || defined(__GNUG__) +#define BENCHMARK_DONT_OPTIMIZE __attribute__((optimize(0))) +#else +// MSVC & Intel do not have a no-optimize attribute, only line pragmas +#define BENCHMARK_DONT_OPTIMIZE +#endif + +#if defined(__GNUC__) || defined(__clang__) +#define BENCHMARK_ALWAYS_INLINE __attribute__((always_inline)) +#elif defined(_MSC_VER) && !defined(__clang__) +#define BENCHMARK_ALWAYS_INLINE __forceinline +#define __func__ __FUNCTION__ +#else +#define BENCHMARK_ALWAYS_INLINE +#endif + +#define BENCHMARK_INTERNAL_TOSTRING2(x) #x +#define BENCHMARK_INTERNAL_TOSTRING(x) BENCHMARK_INTERNAL_TOSTRING2(x) + +// clang-format off +#if (defined(__GNUC__) && !defined(__NVCC__) && !defined(__NVCOMPILER)) || defined(__clang__) +#define BENCHMARK_BUILTIN_EXPECT(x, y) __builtin_expect(x, y) +#define BENCHMARK_DEPRECATED_MSG(msg) __attribute__((deprecated(msg))) +#define BENCHMARK_DISABLE_DEPRECATED_WARNING \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#define BENCHMARK_RESTORE_DEPRECATED_WARNING _Pragma("GCC diagnostic pop") +#elif defined(__NVCOMPILER) +#define BENCHMARK_BUILTIN_EXPECT(x, y) __builtin_expect(x, y) +#define BENCHMARK_DEPRECATED_MSG(msg) __attribute__((deprecated(msg))) +#define BENCHMARK_DISABLE_DEPRECATED_WARNING \ + _Pragma("diagnostic push") \ + _Pragma("diag_suppress deprecated_entity_with_custom_message") +#define BENCHMARK_RESTORE_DEPRECATED_WARNING _Pragma("diagnostic pop") +#else +#define BENCHMARK_BUILTIN_EXPECT(x, y) x +#define BENCHMARK_DEPRECATED_MSG(msg) +#define BENCHMARK_WARNING_MSG(msg) \ + __pragma(message(__FILE__ "(" BENCHMARK_INTERNAL_TOSTRING( \ + __LINE__) ") : warning note: " msg)) +#define BENCHMARK_DISABLE_DEPRECATED_WARNING +#define BENCHMARK_RESTORE_DEPRECATED_WARNING +#endif +// clang-format on + +#if defined(__GNUC__) && !defined(__clang__) +#define BENCHMARK_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) +#endif + +#ifndef __has_builtin +#define __has_builtin(x) 0 +#endif + +#if defined(__GNUC__) || __has_builtin(__builtin_unreachable) +#define BENCHMARK_UNREACHABLE() __builtin_unreachable() +#elif defined(_MSC_VER) +#define BENCHMARK_UNREACHABLE() __assume(false) +#else +#define BENCHMARK_UNREACHABLE() ((void)0) +#endif + +#ifdef BENCHMARK_HAS_CXX11 +#define BENCHMARK_OVERRIDE override +#else +#define BENCHMARK_OVERRIDE +#endif + +#if defined(_MSC_VER) +#pragma warning(push) +// C4251: needs to have dll-interface to be used by clients of class +#pragma warning(disable : 4251) +#endif + +namespace benchmark { +class BenchmarkReporter; + +// Default number of minimum benchmark running time in seconds. +const char kDefaultMinTimeStr[] = "0.5s"; + +// Returns the version of the library. +BENCHMARK_EXPORT std::string GetBenchmarkVersion(); + +BENCHMARK_EXPORT void PrintDefaultHelp(); + +BENCHMARK_EXPORT void Initialize(int* argc, char** argv, + void (*HelperPrinterf)() = PrintDefaultHelp); +BENCHMARK_EXPORT void Shutdown(); + +// Report to stdout all arguments in 'argv' as unrecognized except the first. +// Returns true there is at least on unrecognized argument (i.e. 'argc' > 1). +BENCHMARK_EXPORT bool ReportUnrecognizedArguments(int argc, char** argv); + +// Returns the current value of --benchmark_filter. +BENCHMARK_EXPORT std::string GetBenchmarkFilter(); + +// Sets a new value to --benchmark_filter. (This will override this flag's +// current value). +// Should be called after `benchmark::Initialize()`, as +// `benchmark::Initialize()` will override the flag's value. +BENCHMARK_EXPORT void SetBenchmarkFilter(std::string value); + +// Returns the current value of --v (command line value for verbosity). +BENCHMARK_EXPORT int32_t GetBenchmarkVerbosity(); + +// Creates a default display reporter. Used by the library when no display +// reporter is provided, but also made available for external use in case a +// custom reporter should respect the `--benchmark_format` flag as a fallback +BENCHMARK_EXPORT BenchmarkReporter* CreateDefaultDisplayReporter(); + +// Generate a list of benchmarks matching the specified --benchmark_filter flag +// and if --benchmark_list_tests is specified return after printing the name +// of each matching benchmark. Otherwise run each matching benchmark and +// report the results. +// +// spec : Specify the benchmarks to run. If users do not specify this arg, +// then the value of FLAGS_benchmark_filter +// will be used. +// +// The second and third overload use the specified 'display_reporter' and +// 'file_reporter' respectively. 'file_reporter' will write to the file +// specified +// by '--benchmark_out'. If '--benchmark_out' is not given the +// 'file_reporter' is ignored. +// +// RETURNS: The number of matching benchmarks. +BENCHMARK_EXPORT size_t RunSpecifiedBenchmarks(); +BENCHMARK_EXPORT size_t RunSpecifiedBenchmarks(std::string spec); + +BENCHMARK_EXPORT size_t +RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter); +BENCHMARK_EXPORT size_t +RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, std::string spec); + +BENCHMARK_EXPORT size_t RunSpecifiedBenchmarks( + BenchmarkReporter* display_reporter, BenchmarkReporter* file_reporter); +BENCHMARK_EXPORT size_t +RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, + BenchmarkReporter* file_reporter, std::string spec); + +// TimeUnit is passed to a benchmark in order to specify the order of magnitude +// for the measured time. +enum TimeUnit { kNanosecond, kMicrosecond, kMillisecond, kSecond }; + +BENCHMARK_EXPORT TimeUnit GetDefaultTimeUnit(); + +// Sets the default time unit the benchmarks use +// Has to be called before the benchmark loop to take effect +BENCHMARK_EXPORT void SetDefaultTimeUnit(TimeUnit unit); + +// If a MemoryManager is registered (via RegisterMemoryManager()), +// it can be used to collect and report allocation metrics for a run of the +// benchmark. +class MemoryManager { + public: + static const int64_t TombstoneValue; + + struct Result { + Result() + : num_allocs(0), + max_bytes_used(0), + total_allocated_bytes(TombstoneValue), + net_heap_growth(TombstoneValue) {} + + // The number of allocations made in total between Start and Stop. + int64_t num_allocs; + + // The peak memory use between Start and Stop. + int64_t max_bytes_used; + + // The total memory allocated, in bytes, between Start and Stop. + // Init'ed to TombstoneValue if metric not available. + int64_t total_allocated_bytes; + + // The net changes in memory, in bytes, between Start and Stop. + // ie., total_allocated_bytes - total_deallocated_bytes. + // Init'ed to TombstoneValue if metric not available. + int64_t net_heap_growth; + }; + + virtual ~MemoryManager() {} + + // Implement this to start recording allocation information. + virtual void Start() = 0; + + // Implement this to stop recording and fill out the given Result structure. + virtual void Stop(Result& result) = 0; +}; + +// Register a MemoryManager instance that will be used to collect and report +// allocation measurements for benchmark runs. +BENCHMARK_EXPORT +void RegisterMemoryManager(MemoryManager* memory_manager); + +// Add a key-value pair to output as part of the context stanza in the report. +BENCHMARK_EXPORT +void AddCustomContext(const std::string& key, const std::string& value); + +namespace internal { +class Benchmark; +class BenchmarkImp; +class BenchmarkFamilies; + +BENCHMARK_EXPORT std::map*& GetGlobalContext(); + +BENCHMARK_EXPORT +void UseCharPointer(char const volatile*); + +// Take ownership of the pointer and register the benchmark. Return the +// registered benchmark. +BENCHMARK_EXPORT Benchmark* RegisterBenchmarkInternal(Benchmark*); + +// Ensure that the standard streams are properly initialized in every TU. +BENCHMARK_EXPORT int InitializeStreams(); +BENCHMARK_UNUSED static int stream_init_anchor = InitializeStreams(); + +} // namespace internal + +#if (!defined(__GNUC__) && !defined(__clang__)) || defined(__pnacl__) || \ + defined(__EMSCRIPTEN__) +#define BENCHMARK_HAS_NO_INLINE_ASSEMBLY +#endif + +// Force the compiler to flush pending writes to global memory. Acts as an +// effective read/write barrier +#ifdef BENCHMARK_HAS_CXX11 +inline BENCHMARK_ALWAYS_INLINE void ClobberMemory() { + std::atomic_signal_fence(std::memory_order_acq_rel); +} +#endif + +// The DoNotOptimize(...) function can be used to prevent a value or +// expression from being optimized away by the compiler. This function is +// intended to add little to no overhead. +// See: https://youtu.be/nXaxk27zwlk?t=2441 +#ifndef BENCHMARK_HAS_NO_INLINE_ASSEMBLY +#if !defined(__GNUC__) || defined(__llvm__) || defined(__INTEL_COMPILER) +template +BENCHMARK_DEPRECATED_MSG( + "The const-ref version of this method can permit " + "undesired compiler optimizations in benchmarks") +inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) { + asm volatile("" : : "r,m"(value) : "memory"); +} + +template +inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp& value) { +#if defined(__clang__) + asm volatile("" : "+r,m"(value) : : "memory"); +#else + asm volatile("" : "+m,r"(value) : : "memory"); +#endif +} + +#ifdef BENCHMARK_HAS_CXX11 +template +inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp&& value) { +#if defined(__clang__) + asm volatile("" : "+r,m"(value) : : "memory"); +#else + asm volatile("" : "+m,r"(value) : : "memory"); +#endif +} +#endif +#elif defined(BENCHMARK_HAS_CXX11) && (__GNUC__ >= 5) +// Workaround for a bug with full argument copy overhead with GCC. +// See: #1340 and https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105519 +template +BENCHMARK_DEPRECATED_MSG( + "The const-ref version of this method can permit " + "undesired compiler optimizations in benchmarks") +inline BENCHMARK_ALWAYS_INLINE + typename std::enable_if::value && + (sizeof(Tp) <= sizeof(Tp*))>::type + DoNotOptimize(Tp const& value) { + asm volatile("" : : "r,m"(value) : "memory"); +} + +template +BENCHMARK_DEPRECATED_MSG( + "The const-ref version of this method can permit " + "undesired compiler optimizations in benchmarks") +inline BENCHMARK_ALWAYS_INLINE + typename std::enable_if::value || + (sizeof(Tp) > sizeof(Tp*))>::type + DoNotOptimize(Tp const& value) { + asm volatile("" : : "m"(value) : "memory"); +} + +template +inline BENCHMARK_ALWAYS_INLINE + typename std::enable_if::value && + (sizeof(Tp) <= sizeof(Tp*))>::type + DoNotOptimize(Tp& value) { + asm volatile("" : "+m,r"(value) : : "memory"); +} + +template +inline BENCHMARK_ALWAYS_INLINE + typename std::enable_if::value || + (sizeof(Tp) > sizeof(Tp*))>::type + DoNotOptimize(Tp& value) { + asm volatile("" : "+m"(value) : : "memory"); +} + +template +inline BENCHMARK_ALWAYS_INLINE + typename std::enable_if::value && + (sizeof(Tp) <= sizeof(Tp*))>::type + DoNotOptimize(Tp&& value) { + asm volatile("" : "+m,r"(value) : : "memory"); +} + +template +inline BENCHMARK_ALWAYS_INLINE + typename std::enable_if::value || + (sizeof(Tp) > sizeof(Tp*))>::type + DoNotOptimize(Tp&& value) { + asm volatile("" : "+m"(value) : : "memory"); +} + +#else +// Fallback for GCC < 5. Can add some overhead because the compiler is forced +// to use memory operations instead of operations with registers. +// TODO: Remove if GCC < 5 will be unsupported. +template +BENCHMARK_DEPRECATED_MSG( + "The const-ref version of this method can permit " + "undesired compiler optimizations in benchmarks") +inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) { + asm volatile("" : : "m"(value) : "memory"); +} + +template +inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp& value) { + asm volatile("" : "+m"(value) : : "memory"); +} + +#ifdef BENCHMARK_HAS_CXX11 +template +inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp&& value) { + asm volatile("" : "+m"(value) : : "memory"); +} +#endif +#endif + +#ifndef BENCHMARK_HAS_CXX11 +inline BENCHMARK_ALWAYS_INLINE void ClobberMemory() { + asm volatile("" : : : "memory"); +} +#endif +#elif defined(_MSC_VER) +template +BENCHMARK_DEPRECATED_MSG( + "The const-ref version of this method can permit " + "undesired compiler optimizations in benchmarks") +inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) { + internal::UseCharPointer(&reinterpret_cast(value)); + _ReadWriteBarrier(); +} + +#ifndef BENCHMARK_HAS_CXX11 +inline BENCHMARK_ALWAYS_INLINE void ClobberMemory() { _ReadWriteBarrier(); } +#endif +#else +#ifdef BENCHMARK_HAS_CXX11 +template +inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp&& value) { + internal::UseCharPointer(&reinterpret_cast(value)); +} +#else +template +BENCHMARK_DEPRECATED_MSG( + "The const-ref version of this method can permit " + "undesired compiler optimizations in benchmarks") +inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) { + internal::UseCharPointer(&reinterpret_cast(value)); +} + +template +inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp& value) { + internal::UseCharPointer(&reinterpret_cast(value)); +} +#endif +// FIXME Add ClobberMemory() for non-gnu and non-msvc compilers, before C++11. +#endif + +// This class is used for user-defined counters. +class Counter { + public: + enum Flags { + kDefaults = 0, + // Mark the counter as a rate. It will be presented divided + // by the duration of the benchmark. + kIsRate = 1 << 0, + // Mark the counter as a thread-average quantity. It will be + // presented divided by the number of threads. + kAvgThreads = 1 << 1, + // Mark the counter as a thread-average rate. See above. + kAvgThreadsRate = kIsRate | kAvgThreads, + // Mark the counter as a constant value, valid/same for *every* iteration. + // When reporting, it will be *multiplied* by the iteration count. + kIsIterationInvariant = 1 << 2, + // Mark the counter as a constant rate. + // When reporting, it will be *multiplied* by the iteration count + // and then divided by the duration of the benchmark. + kIsIterationInvariantRate = kIsRate | kIsIterationInvariant, + // Mark the counter as a iteration-average quantity. + // It will be presented divided by the number of iterations. + kAvgIterations = 1 << 3, + // Mark the counter as a iteration-average rate. See above. + kAvgIterationsRate = kIsRate | kAvgIterations, + + // In the end, invert the result. This is always done last! + kInvert = 1 << 31 + }; + + enum OneK { + // 1'000 items per 1k + kIs1000 = 1000, + // 1'024 items per 1k + kIs1024 = 1024 + }; + + double value; + Flags flags; + OneK oneK; + + BENCHMARK_ALWAYS_INLINE + Counter(double v = 0., Flags f = kDefaults, OneK k = kIs1000) + : value(v), flags(f), oneK(k) {} + + BENCHMARK_ALWAYS_INLINE operator double const&() const { return value; } + BENCHMARK_ALWAYS_INLINE operator double&() { return value; } +}; + +// A helper for user code to create unforeseen combinations of Flags, without +// having to do this cast manually each time, or providing this operator. +Counter::Flags inline operator|(const Counter::Flags& LHS, + const Counter::Flags& RHS) { + return static_cast(static_cast(LHS) | + static_cast(RHS)); +} + +// This is the container for the user-defined counters. +typedef std::map UserCounters; + +// BigO is passed to a benchmark in order to specify the asymptotic +// computational +// complexity for the benchmark. In case oAuto is selected, complexity will be +// calculated automatically to the best fit. +enum BigO { oNone, o1, oN, oNSquared, oNCubed, oLogN, oNLogN, oAuto, oLambda }; + +typedef int64_t ComplexityN; + +typedef int64_t IterationCount; + +enum StatisticUnit { kTime, kPercentage }; + +// BigOFunc is passed to a benchmark in order to specify the asymptotic +// computational complexity for the benchmark. +typedef double(BigOFunc)(ComplexityN); + +// StatisticsFunc is passed to a benchmark in order to compute some descriptive +// statistics over all the measurements of some type +typedef double(StatisticsFunc)(const std::vector&); + +namespace internal { +struct Statistics { + std::string name_; + StatisticsFunc* compute_; + StatisticUnit unit_; + + Statistics(const std::string& name, StatisticsFunc* compute, + StatisticUnit unit = kTime) + : name_(name), compute_(compute), unit_(unit) {} +}; + +class BenchmarkInstance; +class ThreadTimer; +class ThreadManager; +class PerfCountersMeasurement; + +enum AggregationReportMode +#if defined(BENCHMARK_HAS_CXX11) + : unsigned +#else +#endif +{ + // The mode has not been manually specified + ARM_Unspecified = 0, + // The mode is user-specified. + // This may or may not be set when the following bit-flags are set. + ARM_Default = 1U << 0U, + // File reporter should only output aggregates. + ARM_FileReportAggregatesOnly = 1U << 1U, + // Display reporter should only output aggregates + ARM_DisplayReportAggregatesOnly = 1U << 2U, + // Both reporters should only display aggregates. + ARM_ReportAggregatesOnly = + ARM_FileReportAggregatesOnly | ARM_DisplayReportAggregatesOnly +}; + +enum Skipped +#if defined(BENCHMARK_HAS_CXX11) + : unsigned +#endif +{ + NotSkipped = 0, + SkippedWithMessage, + SkippedWithError +}; + +} // namespace internal + +// State is passed to a running Benchmark and contains state for the +// benchmark to use. +class BENCHMARK_EXPORT State { + public: + struct StateIterator; + friend struct StateIterator; + + // Returns iterators used to run each iteration of a benchmark using a + // C++11 ranged-based for loop. These functions should not be called directly. + // + // REQUIRES: The benchmark has not started running yet. Neither begin nor end + // have been called previously. + // + // NOTE: KeepRunning may not be used after calling either of these functions. + inline BENCHMARK_ALWAYS_INLINE StateIterator begin(); + inline BENCHMARK_ALWAYS_INLINE StateIterator end(); + + // Returns true if the benchmark should continue through another iteration. + // NOTE: A benchmark may not return from the test until KeepRunning() has + // returned false. + inline bool KeepRunning(); + + // Returns true iff the benchmark should run n more iterations. + // REQUIRES: 'n' > 0. + // NOTE: A benchmark must not return from the test until KeepRunningBatch() + // has returned false. + // NOTE: KeepRunningBatch() may overshoot by up to 'n' iterations. + // + // Intended usage: + // while (state.KeepRunningBatch(1000)) { + // // process 1000 elements + // } + inline bool KeepRunningBatch(IterationCount n); + + // REQUIRES: timer is running and 'SkipWithMessage(...)' or + // 'SkipWithError(...)' has not been called by the current thread. + // Stop the benchmark timer. If not called, the timer will be + // automatically stopped after the last iteration of the benchmark loop. + // + // For threaded benchmarks the PauseTiming() function only pauses the timing + // for the current thread. + // + // NOTE: The "real time" measurement is per-thread. If different threads + // report different measurements the largest one is reported. + // + // NOTE: PauseTiming()/ResumeTiming() are relatively + // heavyweight, and so their use should generally be avoided + // within each benchmark iteration, if possible. + void PauseTiming(); + + // REQUIRES: timer is not running and 'SkipWithMessage(...)' or + // 'SkipWithError(...)' has not been called by the current thread. + // Start the benchmark timer. The timer is NOT running on entrance to the + // benchmark function. It begins running after control flow enters the + // benchmark loop. + // + // NOTE: PauseTiming()/ResumeTiming() are relatively + // heavyweight, and so their use should generally be avoided + // within each benchmark iteration, if possible. + void ResumeTiming(); + + // REQUIRES: 'SkipWithMessage(...)' or 'SkipWithError(...)' has not been + // called previously by the current thread. + // Report the benchmark as resulting in being skipped with the specified + // 'msg'. + // After this call the user may explicitly 'return' from the benchmark. + // + // If the ranged-for style of benchmark loop is used, the user must explicitly + // break from the loop, otherwise all future iterations will be run. + // If the 'KeepRunning()' loop is used the current thread will automatically + // exit the loop at the end of the current iteration. + // + // For threaded benchmarks only the current thread stops executing and future + // calls to `KeepRunning()` will block until all threads have completed + // the `KeepRunning()` loop. If multiple threads report being skipped only the + // first skip message is used. + // + // NOTE: Calling 'SkipWithMessage(...)' does not cause the benchmark to exit + // the current scope immediately. If the function is called from within + // the 'KeepRunning()' loop the current iteration will finish. It is the users + // responsibility to exit the scope as needed. + void SkipWithMessage(const std::string& msg); + + // REQUIRES: 'SkipWithMessage(...)' or 'SkipWithError(...)' has not been + // called previously by the current thread. + // Report the benchmark as resulting in an error with the specified 'msg'. + // After this call the user may explicitly 'return' from the benchmark. + // + // If the ranged-for style of benchmark loop is used, the user must explicitly + // break from the loop, otherwise all future iterations will be run. + // If the 'KeepRunning()' loop is used the current thread will automatically + // exit the loop at the end of the current iteration. + // + // For threaded benchmarks only the current thread stops executing and future + // calls to `KeepRunning()` will block until all threads have completed + // the `KeepRunning()` loop. If multiple threads report an error only the + // first error message is used. + // + // NOTE: Calling 'SkipWithError(...)' does not cause the benchmark to exit + // the current scope immediately. If the function is called from within + // the 'KeepRunning()' loop the current iteration will finish. It is the users + // responsibility to exit the scope as needed. + void SkipWithError(const std::string& msg); + + // Returns true if 'SkipWithMessage(...)' or 'SkipWithError(...)' was called. + bool skipped() const { return internal::NotSkipped != skipped_; } + + // Returns true if an error has been reported with 'SkipWithError(...)'. + bool error_occurred() const { return internal::SkippedWithError == skipped_; } + + // REQUIRES: called exactly once per iteration of the benchmarking loop. + // Set the manually measured time for this benchmark iteration, which + // is used instead of automatically measured time if UseManualTime() was + // specified. + // + // For threaded benchmarks the final value will be set to the largest + // reported values. + void SetIterationTime(double seconds); + + // Set the number of bytes processed by the current benchmark + // execution. This routine is typically called once at the end of a + // throughput oriented benchmark. + // + // REQUIRES: a benchmark has exited its benchmarking loop. + BENCHMARK_ALWAYS_INLINE + void SetBytesProcessed(int64_t bytes) { + counters["bytes_per_second"] = + Counter(static_cast(bytes), Counter::kIsRate, Counter::kIs1024); + } + + BENCHMARK_ALWAYS_INLINE + int64_t bytes_processed() const { + if (counters.find("bytes_per_second") != counters.end()) + return static_cast(counters.at("bytes_per_second")); + return 0; + } + + // If this routine is called with complexity_n > 0 and complexity report is + // requested for the + // family benchmark, then current benchmark will be part of the computation + // and complexity_n will + // represent the length of N. + BENCHMARK_ALWAYS_INLINE + void SetComplexityN(ComplexityN complexity_n) { + complexity_n_ = complexity_n; + } + + BENCHMARK_ALWAYS_INLINE + ComplexityN complexity_length_n() const { return complexity_n_; } + + // If this routine is called with items > 0, then an items/s + // label is printed on the benchmark report line for the currently + // executing benchmark. It is typically called at the end of a processing + // benchmark where a processing items/second output is desired. + // + // REQUIRES: a benchmark has exited its benchmarking loop. + BENCHMARK_ALWAYS_INLINE + void SetItemsProcessed(int64_t items) { + counters["items_per_second"] = + Counter(static_cast(items), benchmark::Counter::kIsRate); + } + + BENCHMARK_ALWAYS_INLINE + int64_t items_processed() const { + if (counters.find("items_per_second") != counters.end()) + return static_cast(counters.at("items_per_second")); + return 0; + } + + // If this routine is called, the specified label is printed at the + // end of the benchmark report line for the currently executing + // benchmark. Example: + // static void BM_Compress(benchmark::State& state) { + // ... + // double compress = input_size / output_size; + // state.SetLabel(StrFormat("compress:%.1f%%", 100.0*compression)); + // } + // Produces output that looks like: + // BM_Compress 50 50 14115038 compress:27.3% + // + // REQUIRES: a benchmark has exited its benchmarking loop. + void SetLabel(const std::string& label); + + // Range arguments for this run. CHECKs if the argument has been set. + BENCHMARK_ALWAYS_INLINE + int64_t range(std::size_t pos = 0) const { + assert(range_.size() > pos); + return range_[pos]; + } + + BENCHMARK_DEPRECATED_MSG("use 'range(0)' instead") + int64_t range_x() const { return range(0); } + + BENCHMARK_DEPRECATED_MSG("use 'range(1)' instead") + int64_t range_y() const { return range(1); } + + // Number of threads concurrently executing the benchmark. + BENCHMARK_ALWAYS_INLINE + int threads() const { return threads_; } + + // Index of the executing thread. Values from [0, threads). + BENCHMARK_ALWAYS_INLINE + int thread_index() const { return thread_index_; } + + BENCHMARK_ALWAYS_INLINE + IterationCount iterations() const { + if (BENCHMARK_BUILTIN_EXPECT(!started_, false)) { + return 0; + } + return max_iterations - total_iterations_ + batch_leftover_; + } + + BENCHMARK_ALWAYS_INLINE + std::string name() const { return name_; } + + private: + // items we expect on the first cache line (ie 64 bytes of the struct) + // When total_iterations_ is 0, KeepRunning() and friends will return false. + // May be larger than max_iterations. + IterationCount total_iterations_; + + // When using KeepRunningBatch(), batch_leftover_ holds the number of + // iterations beyond max_iters that were run. Used to track + // completed_iterations_ accurately. + IterationCount batch_leftover_; + + public: + const IterationCount max_iterations; + + private: + bool started_; + bool finished_; + internal::Skipped skipped_; + + // items we don't need on the first cache line + std::vector range_; + + ComplexityN complexity_n_; + + public: + // Container for user-defined counters. + UserCounters counters; + + private: + State(std::string name, IterationCount max_iters, + const std::vector& ranges, int thread_i, int n_threads, + internal::ThreadTimer* timer, internal::ThreadManager* manager, + internal::PerfCountersMeasurement* perf_counters_measurement); + + void StartKeepRunning(); + // Implementation of KeepRunning() and KeepRunningBatch(). + // is_batch must be true unless n is 1. + inline bool KeepRunningInternal(IterationCount n, bool is_batch); + void FinishKeepRunning(); + + const std::string name_; + const int thread_index_; + const int threads_; + + internal::ThreadTimer* const timer_; + internal::ThreadManager* const manager_; + internal::PerfCountersMeasurement* const perf_counters_measurement_; + + friend class internal::BenchmarkInstance; +}; + +inline BENCHMARK_ALWAYS_INLINE bool State::KeepRunning() { + return KeepRunningInternal(1, /*is_batch=*/false); +} + +inline BENCHMARK_ALWAYS_INLINE bool State::KeepRunningBatch(IterationCount n) { + return KeepRunningInternal(n, /*is_batch=*/true); +} + +inline BENCHMARK_ALWAYS_INLINE bool State::KeepRunningInternal(IterationCount n, + bool is_batch) { + // total_iterations_ is set to 0 by the constructor, and always set to a + // nonzero value by StartKepRunning(). + assert(n > 0); + // n must be 1 unless is_batch is true. + assert(is_batch || n == 1); + if (BENCHMARK_BUILTIN_EXPECT(total_iterations_ >= n, true)) { + total_iterations_ -= n; + return true; + } + if (!started_) { + StartKeepRunning(); + if (!skipped() && total_iterations_ >= n) { + total_iterations_ -= n; + return true; + } + } + // For non-batch runs, total_iterations_ must be 0 by now. + if (is_batch && total_iterations_ != 0) { + batch_leftover_ = n - total_iterations_; + total_iterations_ = 0; + return true; + } + FinishKeepRunning(); + return false; +} + +struct State::StateIterator { + struct BENCHMARK_UNUSED Value {}; + typedef std::forward_iterator_tag iterator_category; + typedef Value value_type; + typedef Value reference; + typedef Value pointer; + typedef std::ptrdiff_t difference_type; + + private: + friend class State; + BENCHMARK_ALWAYS_INLINE + StateIterator() : cached_(0), parent_() {} + + BENCHMARK_ALWAYS_INLINE + explicit StateIterator(State* st) + : cached_(st->skipped() ? 0 : st->max_iterations), parent_(st) {} + + public: + BENCHMARK_ALWAYS_INLINE + Value operator*() const { return Value(); } + + BENCHMARK_ALWAYS_INLINE + StateIterator& operator++() { + assert(cached_ > 0); + --cached_; + return *this; + } + + BENCHMARK_ALWAYS_INLINE + bool operator!=(StateIterator const&) const { + if (BENCHMARK_BUILTIN_EXPECT(cached_ != 0, true)) return true; + parent_->FinishKeepRunning(); + return false; + } + + private: + IterationCount cached_; + State* const parent_; +}; + +inline BENCHMARK_ALWAYS_INLINE State::StateIterator State::begin() { + return StateIterator(this); +} +inline BENCHMARK_ALWAYS_INLINE State::StateIterator State::end() { + StartKeepRunning(); + return StateIterator(); +} + +namespace internal { + +typedef void(Function)(State&); + +// ------------------------------------------------------ +// Benchmark registration object. The BENCHMARK() macro expands +// into an internal::Benchmark* object. Various methods can +// be called on this object to change the properties of the benchmark. +// Each method returns "this" so that multiple method calls can +// chained into one expression. +class BENCHMARK_EXPORT Benchmark { + public: + virtual ~Benchmark(); + + // Note: the following methods all return "this" so that multiple + // method calls can be chained together in one expression. + + // Specify the name of the benchmark + Benchmark* Name(const std::string& name); + + // Run this benchmark once with "x" as the extra argument passed + // to the function. + // REQUIRES: The function passed to the constructor must accept an arg1. + Benchmark* Arg(int64_t x); + + // Run this benchmark with the given time unit for the generated output report + Benchmark* Unit(TimeUnit unit); + + // Run this benchmark once for a number of values picked from the + // range [start..limit]. (start and limit are always picked.) + // REQUIRES: The function passed to the constructor must accept an arg1. + Benchmark* Range(int64_t start, int64_t limit); + + // Run this benchmark once for all values in the range [start..limit] with + // specific step + // REQUIRES: The function passed to the constructor must accept an arg1. + Benchmark* DenseRange(int64_t start, int64_t limit, int step = 1); + + // Run this benchmark once with "args" as the extra arguments passed + // to the function. + // REQUIRES: The function passed to the constructor must accept arg1, arg2 ... + Benchmark* Args(const std::vector& args); + + // Equivalent to Args({x, y}) + // NOTE: This is a legacy C++03 interface provided for compatibility only. + // New code should use 'Args'. + Benchmark* ArgPair(int64_t x, int64_t y) { + std::vector args; + args.push_back(x); + args.push_back(y); + return Args(args); + } + + // Run this benchmark once for a number of values picked from the + // ranges [start..limit]. (starts and limits are always picked.) + // REQUIRES: The function passed to the constructor must accept arg1, arg2 ... + Benchmark* Ranges(const std::vector >& ranges); + + // Run this benchmark once for each combination of values in the (cartesian) + // product of the supplied argument lists. + // REQUIRES: The function passed to the constructor must accept arg1, arg2 ... + Benchmark* ArgsProduct(const std::vector >& arglists); + + // Equivalent to ArgNames({name}) + Benchmark* ArgName(const std::string& name); + + // Set the argument names to display in the benchmark name. If not called, + // only argument values will be shown. + Benchmark* ArgNames(const std::vector& names); + + // Equivalent to Ranges({{lo1, hi1}, {lo2, hi2}}). + // NOTE: This is a legacy C++03 interface provided for compatibility only. + // New code should use 'Ranges'. + Benchmark* RangePair(int64_t lo1, int64_t hi1, int64_t lo2, int64_t hi2) { + std::vector > ranges; + ranges.push_back(std::make_pair(lo1, hi1)); + ranges.push_back(std::make_pair(lo2, hi2)); + return Ranges(ranges); + } + + // Have "setup" and/or "teardown" invoked once for every benchmark run. + // If the benchmark is multi-threaded (will run in k threads concurrently), + // the setup callback will be be invoked exactly once (not k times) before + // each run with k threads. Time allowing (e.g. for a short benchmark), there + // may be multiple such runs per benchmark, each run with its own + // "setup"/"teardown". + // + // If the benchmark uses different size groups of threads (e.g. via + // ThreadRange), the above will be true for each size group. + // + // The callback will be passed a State object, which includes the number + // of threads, thread-index, benchmark arguments, etc. + // + // The callback must not be NULL or self-deleting. + Benchmark* Setup(void (*setup)(const benchmark::State&)); + Benchmark* Teardown(void (*teardown)(const benchmark::State&)); + + // Pass this benchmark object to *func, which can customize + // the benchmark by calling various methods like Arg, Args, + // Threads, etc. + Benchmark* Apply(void (*func)(Benchmark* benchmark)); + + // Set the range multiplier for non-dense range. If not called, the range + // multiplier kRangeMultiplier will be used. + Benchmark* RangeMultiplier(int multiplier); + + // Set the minimum amount of time to use when running this benchmark. This + // option overrides the `benchmark_min_time` flag. + // REQUIRES: `t > 0` and `Iterations` has not been called on this benchmark. + Benchmark* MinTime(double t); + + // Set the minimum amount of time to run the benchmark before taking runtimes + // of this benchmark into account. This + // option overrides the `benchmark_min_warmup_time` flag. + // REQUIRES: `t >= 0` and `Iterations` has not been called on this benchmark. + Benchmark* MinWarmUpTime(double t); + + // Specify the amount of iterations that should be run by this benchmark. + // This option overrides the `benchmark_min_time` flag. + // REQUIRES: 'n > 0' and `MinTime` has not been called on this benchmark. + // + // NOTE: This function should only be used when *exact* iteration control is + // needed and never to control or limit how long a benchmark runs, where + // `--benchmark_min_time=s` or `MinTime(...)` should be used instead. + Benchmark* Iterations(IterationCount n); + + // Specify the amount of times to repeat this benchmark. This option overrides + // the `benchmark_repetitions` flag. + // REQUIRES: `n > 0` + Benchmark* Repetitions(int n); + + // Specify if each repetition of the benchmark should be reported separately + // or if only the final statistics should be reported. If the benchmark + // is not repeated then the single result is always reported. + // Applies to *ALL* reporters (display and file). + Benchmark* ReportAggregatesOnly(bool value = true); + + // Same as ReportAggregatesOnly(), but applies to display reporter only. + Benchmark* DisplayAggregatesOnly(bool value = true); + + // By default, the CPU time is measured only for the main thread, which may + // be unrepresentative if the benchmark uses threads internally. If called, + // the total CPU time spent by all the threads will be measured instead. + // By default, only the main thread CPU time will be measured. + Benchmark* MeasureProcessCPUTime(); + + // If a particular benchmark should use the Wall clock instead of the CPU time + // (be it either the CPU time of the main thread only (default), or the + // total CPU usage of the benchmark), call this method. If called, the elapsed + // (wall) time will be used to control how many iterations are run, and in the + // printing of items/second or MB/seconds values. + // If not called, the CPU time used by the benchmark will be used. + Benchmark* UseRealTime(); + + // If a benchmark must measure time manually (e.g. if GPU execution time is + // being + // measured), call this method. If called, each benchmark iteration should + // call + // SetIterationTime(seconds) to report the measured time, which will be used + // to control how many iterations are run, and in the printing of items/second + // or MB/second values. + Benchmark* UseManualTime(); + + // Set the asymptotic computational complexity for the benchmark. If called + // the asymptotic computational complexity will be shown on the output. + Benchmark* Complexity(BigO complexity = benchmark::oAuto); + + // Set the asymptotic computational complexity for the benchmark. If called + // the asymptotic computational complexity will be shown on the output. + Benchmark* Complexity(BigOFunc* complexity); + + // Add this statistics to be computed over all the values of benchmark run + Benchmark* ComputeStatistics(const std::string& name, + StatisticsFunc* statistics, + StatisticUnit unit = kTime); + + // Support for running multiple copies of the same benchmark concurrently + // in multiple threads. This may be useful when measuring the scaling + // of some piece of code. + + // Run one instance of this benchmark concurrently in t threads. + Benchmark* Threads(int t); + + // Pick a set of values T from [min_threads,max_threads]. + // min_threads and max_threads are always included in T. Run this + // benchmark once for each value in T. The benchmark run for a + // particular value t consists of t threads running the benchmark + // function concurrently. For example, consider: + // BENCHMARK(Foo)->ThreadRange(1,16); + // This will run the following benchmarks: + // Foo in 1 thread + // Foo in 2 threads + // Foo in 4 threads + // Foo in 8 threads + // Foo in 16 threads + Benchmark* ThreadRange(int min_threads, int max_threads); + + // For each value n in the range, run this benchmark once using n threads. + // min_threads and max_threads are always included in the range. + // stride specifies the increment. E.g. DenseThreadRange(1, 8, 3) starts + // a benchmark with 1, 4, 7 and 8 threads. + Benchmark* DenseThreadRange(int min_threads, int max_threads, int stride = 1); + + // Equivalent to ThreadRange(NumCPUs(), NumCPUs()) + Benchmark* ThreadPerCpu(); + + virtual void Run(State& state) = 0; + + TimeUnit GetTimeUnit() const; + + protected: + explicit Benchmark(const std::string& name); + void SetName(const std::string& name); + + public: + const char* GetName() const; + int ArgsCnt() const; + const char* GetArgName(int arg) const; + + private: + friend class BenchmarkFamilies; + friend class BenchmarkInstance; + + std::string name_; + AggregationReportMode aggregation_report_mode_; + std::vector arg_names_; // Args for all benchmark runs + std::vector > args_; // Args for all benchmark runs + + TimeUnit time_unit_; + bool use_default_time_unit_; + + int range_multiplier_; + double min_time_; + double min_warmup_time_; + IterationCount iterations_; + int repetitions_; + bool measure_process_cpu_time_; + bool use_real_time_; + bool use_manual_time_; + BigO complexity_; + BigOFunc* complexity_lambda_; + std::vector statistics_; + std::vector thread_counts_; + + typedef void (*callback_function)(const benchmark::State&); + callback_function setup_; + callback_function teardown_; + + Benchmark(Benchmark const&) +#if defined(BENCHMARK_HAS_CXX11) + = delete +#endif + ; + + Benchmark& operator=(Benchmark const&) +#if defined(BENCHMARK_HAS_CXX11) + = delete +#endif + ; +}; + +} // namespace internal + +// Create and register a benchmark with the specified 'name' that invokes +// the specified functor 'fn'. +// +// RETURNS: A pointer to the registered benchmark. +internal::Benchmark* RegisterBenchmark(const std::string& name, + internal::Function* fn); + +#if defined(BENCHMARK_HAS_CXX11) +template +internal::Benchmark* RegisterBenchmark(const std::string& name, Lambda&& fn); +#endif + +// Remove all registered benchmarks. All pointers to previously registered +// benchmarks are invalidated. +BENCHMARK_EXPORT void ClearRegisteredBenchmarks(); + +namespace internal { +// The class used to hold all Benchmarks created from static function. +// (ie those created using the BENCHMARK(...) macros. +class BENCHMARK_EXPORT FunctionBenchmark : public Benchmark { + public: + FunctionBenchmark(const std::string& name, Function* func) + : Benchmark(name), func_(func) {} + + void Run(State& st) BENCHMARK_OVERRIDE; + + private: + Function* func_; +}; + +#ifdef BENCHMARK_HAS_CXX11 +template +class LambdaBenchmark : public Benchmark { + public: + void Run(State& st) BENCHMARK_OVERRIDE { lambda_(st); } + + private: + template + LambdaBenchmark(const std::string& name, OLambda&& lam) + : Benchmark(name), lambda_(std::forward(lam)) {} + + LambdaBenchmark(LambdaBenchmark const&) = delete; + + template // NOLINTNEXTLINE(readability-redundant-declaration) + friend Benchmark* ::benchmark::RegisterBenchmark(const std::string&, Lam&&); + + Lambda lambda_; +}; +#endif +} // namespace internal + +inline internal::Benchmark* RegisterBenchmark(const std::string& name, + internal::Function* fn) { + // FIXME: this should be a `std::make_unique<>()` but we don't have C++14. + // codechecker_intentional [cplusplus.NewDeleteLeaks] + return internal::RegisterBenchmarkInternal( + ::new internal::FunctionBenchmark(name, fn)); +} + +#ifdef BENCHMARK_HAS_CXX11 +template +internal::Benchmark* RegisterBenchmark(const std::string& name, Lambda&& fn) { + using BenchType = + internal::LambdaBenchmark::type>; + // FIXME: this should be a `std::make_unique<>()` but we don't have C++14. + // codechecker_intentional [cplusplus.NewDeleteLeaks] + return internal::RegisterBenchmarkInternal( + ::new BenchType(name, std::forward(fn))); +} +#endif + +#if defined(BENCHMARK_HAS_CXX11) && \ + (!defined(BENCHMARK_GCC_VERSION) || BENCHMARK_GCC_VERSION >= 409) +template +internal::Benchmark* RegisterBenchmark(const std::string& name, Lambda&& fn, + Args&&... args) { + return benchmark::RegisterBenchmark( + name, [=](benchmark::State& st) { fn(st, args...); }); +} +#else +#define BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK +#endif + +// The base class for all fixture tests. +class Fixture : public internal::Benchmark { + public: + Fixture() : internal::Benchmark("") {} + + void Run(State& st) BENCHMARK_OVERRIDE { + this->SetUp(st); + this->BenchmarkCase(st); + this->TearDown(st); + } + + // These will be deprecated ... + virtual void SetUp(const State&) {} + virtual void TearDown(const State&) {} + // ... In favor of these. + virtual void SetUp(State& st) { SetUp(const_cast(st)); } + virtual void TearDown(State& st) { TearDown(const_cast(st)); } + + protected: + virtual void BenchmarkCase(State&) = 0; +}; +} // namespace benchmark + +// ------------------------------------------------------ +// Macro to register benchmarks + +// Check that __COUNTER__ is defined and that __COUNTER__ increases by 1 +// every time it is expanded. X + 1 == X + 0 is used in case X is defined to be +// empty. If X is empty the expression becomes (+1 == +0). +#if defined(__COUNTER__) && (__COUNTER__ + 1 == __COUNTER__ + 0) +#define BENCHMARK_PRIVATE_UNIQUE_ID __COUNTER__ +#else +#define BENCHMARK_PRIVATE_UNIQUE_ID __LINE__ +#endif + +// Helpers for generating unique variable names +#ifdef BENCHMARK_HAS_CXX11 +#define BENCHMARK_PRIVATE_NAME(...) \ + BENCHMARK_PRIVATE_CONCAT(benchmark_uniq_, BENCHMARK_PRIVATE_UNIQUE_ID, \ + __VA_ARGS__) +#else +#define BENCHMARK_PRIVATE_NAME(n) \ + BENCHMARK_PRIVATE_CONCAT(benchmark_uniq_, BENCHMARK_PRIVATE_UNIQUE_ID, n) +#endif // BENCHMARK_HAS_CXX11 + +#define BENCHMARK_PRIVATE_CONCAT(a, b, c) BENCHMARK_PRIVATE_CONCAT2(a, b, c) +#define BENCHMARK_PRIVATE_CONCAT2(a, b, c) a##b##c +// Helper for concatenation with macro name expansion +#define BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method) \ + BaseClass##_##Method##_Benchmark + +#define BENCHMARK_PRIVATE_DECLARE(n) \ + static ::benchmark::internal::Benchmark* BENCHMARK_PRIVATE_NAME(n) \ + BENCHMARK_UNUSED + +#ifdef BENCHMARK_HAS_CXX11 +#define BENCHMARK(...) \ + BENCHMARK_PRIVATE_DECLARE(_benchmark_) = \ + (::benchmark::internal::RegisterBenchmarkInternal( \ + new ::benchmark::internal::FunctionBenchmark(#__VA_ARGS__, \ + __VA_ARGS__))) +#else +#define BENCHMARK(n) \ + BENCHMARK_PRIVATE_DECLARE(n) = \ + (::benchmark::internal::RegisterBenchmarkInternal( \ + new ::benchmark::internal::FunctionBenchmark(#n, n))) +#endif // BENCHMARK_HAS_CXX11 + +// Old-style macros +#define BENCHMARK_WITH_ARG(n, a) BENCHMARK(n)->Arg((a)) +#define BENCHMARK_WITH_ARG2(n, a1, a2) BENCHMARK(n)->Args({(a1), (a2)}) +#define BENCHMARK_WITH_UNIT(n, t) BENCHMARK(n)->Unit((t)) +#define BENCHMARK_RANGE(n, lo, hi) BENCHMARK(n)->Range((lo), (hi)) +#define BENCHMARK_RANGE2(n, l1, h1, l2, h2) \ + BENCHMARK(n)->RangePair({{(l1), (h1)}, {(l2), (h2)}}) + +#ifdef BENCHMARK_HAS_CXX11 + +// Register a benchmark which invokes the function specified by `func` +// with the additional arguments specified by `...`. +// +// For example: +// +// template ` +// void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) { +// [...] +//} +// /* Registers a benchmark named "BM_takes_args/int_string_test` */ +// BENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string("abc")); +#define BENCHMARK_CAPTURE(func, test_case_name, ...) \ + BENCHMARK_PRIVATE_DECLARE(_benchmark_) = \ + (::benchmark::internal::RegisterBenchmarkInternal( \ + new ::benchmark::internal::FunctionBenchmark( \ + #func "/" #test_case_name, \ + [](::benchmark::State& st) { func(st, __VA_ARGS__); }))) + +#endif // BENCHMARK_HAS_CXX11 + +// This will register a benchmark for a templatized function. For example: +// +// template +// void BM_Foo(int iters); +// +// BENCHMARK_TEMPLATE(BM_Foo, 1); +// +// will register BM_Foo<1> as a benchmark. +#define BENCHMARK_TEMPLATE1(n, a) \ + BENCHMARK_PRIVATE_DECLARE(n) = \ + (::benchmark::internal::RegisterBenchmarkInternal( \ + new ::benchmark::internal::FunctionBenchmark(#n "<" #a ">", n))) + +#define BENCHMARK_TEMPLATE2(n, a, b) \ + BENCHMARK_PRIVATE_DECLARE(n) = \ + (::benchmark::internal::RegisterBenchmarkInternal( \ + new ::benchmark::internal::FunctionBenchmark(#n "<" #a "," #b ">", \ + n))) + +#ifdef BENCHMARK_HAS_CXX11 +#define BENCHMARK_TEMPLATE(n, ...) \ + BENCHMARK_PRIVATE_DECLARE(n) = \ + (::benchmark::internal::RegisterBenchmarkInternal( \ + new ::benchmark::internal::FunctionBenchmark( \ + #n "<" #__VA_ARGS__ ">", n<__VA_ARGS__>))) +#else +#define BENCHMARK_TEMPLATE(n, a) BENCHMARK_TEMPLATE1(n, a) +#endif + +#ifdef BENCHMARK_HAS_CXX11 +// This will register a benchmark for a templatized function, +// with the additional arguments specified by `...`. +// +// For example: +// +// template ` +// void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) { +// [...] +//} +// /* Registers a benchmark named "BM_takes_args/int_string_test` */ +// BENCHMARK_TEMPLATE1_CAPTURE(BM_takes_args, void, int_string_test, 42, +// std::string("abc")); +#define BENCHMARK_TEMPLATE1_CAPTURE(func, a, test_case_name, ...) \ + BENCHMARK_CAPTURE(func, test_case_name, __VA_ARGS__) + +#define BENCHMARK_TEMPLATE2_CAPTURE(func, a, b, test_case_name, ...) \ + BENCHMARK_PRIVATE_DECLARE(func) = \ + (::benchmark::internal::RegisterBenchmarkInternal( \ + new ::benchmark::internal::FunctionBenchmark( \ + #func "<" #a "," #b ">" \ + "/" #test_case_name, \ + [](::benchmark::State& st) { func(st, __VA_ARGS__); }))) +#endif // BENCHMARK_HAS_CXX11 + +#define BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \ + class BaseClass##_##Method##_Benchmark : public BaseClass { \ + public: \ + BaseClass##_##Method##_Benchmark() { \ + this->SetName(#BaseClass "/" #Method); \ + } \ + \ + protected: \ + void BenchmarkCase(::benchmark::State&) BENCHMARK_OVERRIDE; \ + }; + +#define BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \ + class BaseClass##_##Method##_Benchmark : public BaseClass { \ + public: \ + BaseClass##_##Method##_Benchmark() { \ + this->SetName(#BaseClass "<" #a ">/" #Method); \ + } \ + \ + protected: \ + void BenchmarkCase(::benchmark::State&) BENCHMARK_OVERRIDE; \ + }; + +#define BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \ + class BaseClass##_##Method##_Benchmark : public BaseClass { \ + public: \ + BaseClass##_##Method##_Benchmark() { \ + this->SetName(#BaseClass "<" #a "," #b ">/" #Method); \ + } \ + \ + protected: \ + void BenchmarkCase(::benchmark::State&) BENCHMARK_OVERRIDE; \ + }; + +#ifdef BENCHMARK_HAS_CXX11 +#define BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, ...) \ + class BaseClass##_##Method##_Benchmark : public BaseClass<__VA_ARGS__> { \ + public: \ + BaseClass##_##Method##_Benchmark() { \ + this->SetName(#BaseClass "<" #__VA_ARGS__ ">/" #Method); \ + } \ + \ + protected: \ + void BenchmarkCase(::benchmark::State&) BENCHMARK_OVERRIDE; \ + }; +#else +#define BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(n, a) \ + BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(n, a) +#endif + +#define BENCHMARK_DEFINE_F(BaseClass, Method) \ + BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \ + void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase + +#define BENCHMARK_TEMPLATE1_DEFINE_F(BaseClass, Method, a) \ + BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \ + void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase + +#define BENCHMARK_TEMPLATE2_DEFINE_F(BaseClass, Method, a, b) \ + BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \ + void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase + +#ifdef BENCHMARK_HAS_CXX11 +#define BENCHMARK_TEMPLATE_DEFINE_F(BaseClass, Method, ...) \ + BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, __VA_ARGS__) \ + void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase +#else +#define BENCHMARK_TEMPLATE_DEFINE_F(BaseClass, Method, a) \ + BENCHMARK_TEMPLATE1_DEFINE_F(BaseClass, Method, a) +#endif + +#define BENCHMARK_REGISTER_F(BaseClass, Method) \ + BENCHMARK_PRIVATE_REGISTER_F(BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)) + +#define BENCHMARK_PRIVATE_REGISTER_F(TestName) \ + BENCHMARK_PRIVATE_DECLARE(TestName) = \ + (::benchmark::internal::RegisterBenchmarkInternal(new TestName())) + +// This macro will define and register a benchmark within a fixture class. +#define BENCHMARK_F(BaseClass, Method) \ + BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \ + BENCHMARK_REGISTER_F(BaseClass, Method); \ + void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase + +#define BENCHMARK_TEMPLATE1_F(BaseClass, Method, a) \ + BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \ + BENCHMARK_REGISTER_F(BaseClass, Method); \ + void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase + +#define BENCHMARK_TEMPLATE2_F(BaseClass, Method, a, b) \ + BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \ + BENCHMARK_REGISTER_F(BaseClass, Method); \ + void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase + +#ifdef BENCHMARK_HAS_CXX11 +#define BENCHMARK_TEMPLATE_F(BaseClass, Method, ...) \ + BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, __VA_ARGS__) \ + BENCHMARK_REGISTER_F(BaseClass, Method); \ + void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase +#else +#define BENCHMARK_TEMPLATE_F(BaseClass, Method, a) \ + BENCHMARK_TEMPLATE1_F(BaseClass, Method, a) +#endif + +// Helper macro to create a main routine in a test that runs the benchmarks +// Note the workaround for Hexagon simulator passing argc != 0, argv = NULL. +#define BENCHMARK_MAIN() \ + int main(int argc, char** argv) { \ + char arg0_default[] = "benchmark"; \ + char* args_default = arg0_default; \ + if (!argv) { \ + argc = 1; \ + argv = &args_default; \ + } \ + ::benchmark::Initialize(&argc, argv); \ + if (::benchmark::ReportUnrecognizedArguments(argc, argv)) return 1; \ + ::benchmark::RunSpecifiedBenchmarks(); \ + ::benchmark::Shutdown(); \ + return 0; \ + } \ + int main(int, char**) + +// ------------------------------------------------------ +// Benchmark Reporters + +namespace benchmark { + +struct BENCHMARK_EXPORT CPUInfo { + struct CacheInfo { + std::string type; + int level; + int size; + int num_sharing; + }; + + enum Scaling { UNKNOWN, ENABLED, DISABLED }; + + int num_cpus; + Scaling scaling; + double cycles_per_second; + std::vector caches; + std::vector load_avg; + + static const CPUInfo& Get(); + + private: + CPUInfo(); + BENCHMARK_DISALLOW_COPY_AND_ASSIGN(CPUInfo); +}; + +// Adding Struct for System Information +struct BENCHMARK_EXPORT SystemInfo { + std::string name; + static const SystemInfo& Get(); + + private: + SystemInfo(); + BENCHMARK_DISALLOW_COPY_AND_ASSIGN(SystemInfo); +}; + +// BenchmarkName contains the components of the Benchmark's name +// which allows individual fields to be modified or cleared before +// building the final name using 'str()'. +struct BENCHMARK_EXPORT BenchmarkName { + std::string function_name; + std::string args; + std::string min_time; + std::string min_warmup_time; + std::string iterations; + std::string repetitions; + std::string time_type; + std::string threads; + + // Return the full name of the benchmark with each non-empty + // field separated by a '/' + std::string str() const; +}; + +// Interface for custom benchmark result printers. +// By default, benchmark reports are printed to stdout. However an application +// can control the destination of the reports by calling +// RunSpecifiedBenchmarks and passing it a custom reporter object. +// The reporter object must implement the following interface. +class BENCHMARK_EXPORT BenchmarkReporter { + public: + struct Context { + CPUInfo const& cpu_info; + SystemInfo const& sys_info; + // The number of chars in the longest benchmark name. + size_t name_field_width; + static const char* executable_name; + Context(); + }; + + struct BENCHMARK_EXPORT Run { + static const int64_t no_repetition_index = -1; + enum RunType { RT_Iteration, RT_Aggregate }; + + Run() + : run_type(RT_Iteration), + aggregate_unit(kTime), + skipped(internal::NotSkipped), + iterations(1), + threads(1), + time_unit(GetDefaultTimeUnit()), + real_accumulated_time(0), + cpu_accumulated_time(0), + max_heapbytes_used(0), + use_real_time_for_initial_big_o(false), + complexity(oNone), + complexity_lambda(), + complexity_n(0), + report_big_o(false), + report_rms(false), + memory_result(NULL), + allocs_per_iter(0.0) {} + + std::string benchmark_name() const; + BenchmarkName run_name; + int64_t family_index; + int64_t per_family_instance_index; + RunType run_type; + std::string aggregate_name; + StatisticUnit aggregate_unit; + std::string report_label; // Empty if not set by benchmark. + internal::Skipped skipped; + std::string skip_message; + + IterationCount iterations; + int64_t threads; + int64_t repetition_index; + int64_t repetitions; + TimeUnit time_unit; + double real_accumulated_time; + double cpu_accumulated_time; + + // Return a value representing the real time per iteration in the unit + // specified by 'time_unit'. + // NOTE: If 'iterations' is zero the returned value represents the + // accumulated time. + double GetAdjustedRealTime() const; + + // Return a value representing the cpu time per iteration in the unit + // specified by 'time_unit'. + // NOTE: If 'iterations' is zero the returned value represents the + // accumulated time. + double GetAdjustedCPUTime() const; + + // This is set to 0.0 if memory tracing is not enabled. + double max_heapbytes_used; + + // By default Big-O is computed for CPU time, but that is not what you want + // to happen when manual time was requested, which is stored as real time. + bool use_real_time_for_initial_big_o; + + // Keep track of arguments to compute asymptotic complexity + BigO complexity; + BigOFunc* complexity_lambda; + ComplexityN complexity_n; + + // what statistics to compute from the measurements + const std::vector* statistics; + + // Inform print function whether the current run is a complexity report + bool report_big_o; + bool report_rms; + + UserCounters counters; + + // Memory metrics. + const MemoryManager::Result* memory_result; + double allocs_per_iter; + }; + + struct PerFamilyRunReports { + PerFamilyRunReports() : num_runs_total(0), num_runs_done(0) {} + + // How many runs will all instances of this benchmark perform? + int num_runs_total; + + // How many runs have happened already? + int num_runs_done; + + // The reports about (non-errneous!) runs of this family. + std::vector Runs; + }; + + // Construct a BenchmarkReporter with the output stream set to 'std::cout' + // and the error stream set to 'std::cerr' + BenchmarkReporter(); + + // Called once for every suite of benchmarks run. + // The parameter "context" contains information that the + // reporter may wish to use when generating its report, for example the + // platform under which the benchmarks are running. The benchmark run is + // never started if this function returns false, allowing the reporter + // to skip runs based on the context information. + virtual bool ReportContext(const Context& context) = 0; + + // Called once for each group of benchmark runs, gives information about + // the configurations of the runs. + virtual void ReportRunsConfig(double /*min_time*/, + bool /*has_explicit_iters*/, + IterationCount /*iters*/) {} + + // Called once for each group of benchmark runs, gives information about + // cpu-time and heap memory usage during the benchmark run. If the group + // of runs contained more than two entries then 'report' contains additional + // elements representing the mean and standard deviation of those runs. + // Additionally if this group of runs was the last in a family of benchmarks + // 'reports' contains additional entries representing the asymptotic + // complexity and RMS of that benchmark family. + virtual void ReportRuns(const std::vector& report) = 0; + + // Called once and only once after ever group of benchmarks is run and + // reported. + virtual void Finalize() {} + + // REQUIRES: The object referenced by 'out' is valid for the lifetime + // of the reporter. + void SetOutputStream(std::ostream* out) { + assert(out); + output_stream_ = out; + } + + // REQUIRES: The object referenced by 'err' is valid for the lifetime + // of the reporter. + void SetErrorStream(std::ostream* err) { + assert(err); + error_stream_ = err; + } + + std::ostream& GetOutputStream() const { return *output_stream_; } + + std::ostream& GetErrorStream() const { return *error_stream_; } + + virtual ~BenchmarkReporter(); + + // Write a human readable string to 'out' representing the specified + // 'context'. + // REQUIRES: 'out' is non-null. + static void PrintBasicContext(std::ostream* out, Context const& context); + + private: + std::ostream* output_stream_; + std::ostream* error_stream_; +}; + +// Simple reporter that outputs benchmark data to the console. This is the +// default reporter used by RunSpecifiedBenchmarks(). +class BENCHMARK_EXPORT ConsoleReporter : public BenchmarkReporter { + public: + enum OutputOptions { + OO_None = 0, + OO_Color = 1, + OO_Tabular = 2, + OO_ColorTabular = OO_Color | OO_Tabular, + OO_Defaults = OO_ColorTabular + }; + explicit ConsoleReporter(OutputOptions opts_ = OO_Defaults) + : output_options_(opts_), name_field_width_(0), printed_header_(false) {} + + bool ReportContext(const Context& context) BENCHMARK_OVERRIDE; + void ReportRuns(const std::vector& reports) BENCHMARK_OVERRIDE; + + protected: + virtual void PrintRunData(const Run& report); + virtual void PrintHeader(const Run& report); + + OutputOptions output_options_; + size_t name_field_width_; + UserCounters prev_counters_; + bool printed_header_; +}; + +class BENCHMARK_EXPORT JSONReporter : public BenchmarkReporter { + public: + JSONReporter() : first_report_(true) {} + bool ReportContext(const Context& context) BENCHMARK_OVERRIDE; + void ReportRuns(const std::vector& reports) BENCHMARK_OVERRIDE; + void Finalize() BENCHMARK_OVERRIDE; + + private: + void PrintRunData(const Run& report); + + bool first_report_; +}; + +class BENCHMARK_EXPORT BENCHMARK_DEPRECATED_MSG( + "The CSV Reporter will be removed in a future release") CSVReporter + : public BenchmarkReporter { + public: + CSVReporter() : printed_header_(false) {} + bool ReportContext(const Context& context) BENCHMARK_OVERRIDE; + void ReportRuns(const std::vector& reports) BENCHMARK_OVERRIDE; + + private: + void PrintRunData(const Run& report); + + bool printed_header_; + std::set user_counter_names_; +}; + +inline const char* GetTimeUnitString(TimeUnit unit) { + switch (unit) { + case kSecond: + return "s"; + case kMillisecond: + return "ms"; + case kMicrosecond: + return "us"; + case kNanosecond: + return "ns"; + } + BENCHMARK_UNREACHABLE(); +} + +inline double GetTimeUnitMultiplier(TimeUnit unit) { + switch (unit) { + case kSecond: + return 1; + case kMillisecond: + return 1e3; + case kMicrosecond: + return 1e6; + case kNanosecond: + return 1e9; + } + BENCHMARK_UNREACHABLE(); +} + +// Creates a list of integer values for the given range and multiplier. +// This can be used together with ArgsProduct() to allow multiple ranges +// with different multipliers. +// Example: +// ArgsProduct({ +// CreateRange(0, 1024, /*multi=*/32), +// CreateRange(0, 100, /*multi=*/4), +// CreateDenseRange(0, 4, /*step=*/1), +// }); +BENCHMARK_EXPORT +std::vector CreateRange(int64_t lo, int64_t hi, int multi); + +// Creates a list of integer values for the given range and step. +BENCHMARK_EXPORT +std::vector CreateDenseRange(int64_t start, int64_t limit, int step); + +} // namespace benchmark + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif + +#endif // BENCHMARK_BENCHMARK_H_ diff --git a/third_party/benchmark/include/benchmark/export.h b/third_party/benchmark/include/benchmark/export.h new file mode 100644 index 0000000..f96f859 --- /dev/null +++ b/third_party/benchmark/include/benchmark/export.h @@ -0,0 +1,47 @@ +#ifndef BENCHMARK_EXPORT_H +#define BENCHMARK_EXPORT_H + +#if defined(_WIN32) +#define EXPORT_ATTR __declspec(dllexport) +#define IMPORT_ATTR __declspec(dllimport) +#define NO_EXPORT_ATTR +#define DEPRECATED_ATTR __declspec(deprecated) +#else // _WIN32 +#define EXPORT_ATTR __attribute__((visibility("default"))) +#define IMPORT_ATTR __attribute__((visibility("default"))) +#define NO_EXPORT_ATTR __attribute__((visibility("hidden"))) +#define DEPRECATE_ATTR __attribute__((__deprecated__)) +#endif // _WIN32 + +#ifdef BENCHMARK_STATIC_DEFINE +#define BENCHMARK_EXPORT +#define BENCHMARK_NO_EXPORT +#else // BENCHMARK_STATIC_DEFINE +#ifndef BENCHMARK_EXPORT +#ifdef benchmark_EXPORTS +/* We are building this library */ +#define BENCHMARK_EXPORT EXPORT_ATTR +#else // benchmark_EXPORTS +/* We are using this library */ +#define BENCHMARK_EXPORT IMPORT_ATTR +#endif // benchmark_EXPORTS +#endif // !BENCHMARK_EXPORT + +#ifndef BENCHMARK_NO_EXPORT +#define BENCHMARK_NO_EXPORT NO_EXPORT_ATTR +#endif // !BENCHMARK_NO_EXPORT +#endif // BENCHMARK_STATIC_DEFINE + +#ifndef BENCHMARK_DEPRECATED +#define BENCHMARK_DEPRECATED DEPRECATE_ATTR +#endif // BENCHMARK_DEPRECATED + +#ifndef BENCHMARK_DEPRECATED_EXPORT +#define BENCHMARK_DEPRECATED_EXPORT BENCHMARK_EXPORT BENCHMARK_DEPRECATED +#endif // BENCHMARK_DEPRECATED_EXPORT + +#ifndef BENCHMARK_DEPRECATED_NO_EXPORT +#define BENCHMARK_DEPRECATED_NO_EXPORT BENCHMARK_NO_EXPORT BENCHMARK_DEPRECATED +#endif // BENCHMARK_DEPRECATED_EXPORT + +#endif /* BENCHMARK_EXPORT_H */ diff --git a/third_party/benchmark/pyproject.toml b/third_party/benchmark/pyproject.toml new file mode 100644 index 0000000..62507a8 --- /dev/null +++ b/third_party/benchmark/pyproject.toml @@ -0,0 +1,86 @@ +[build-system] +requires = ["setuptools", "setuptools-scm[toml]", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "google_benchmark" +description = "A library to benchmark code snippets." +requires-python = ">=3.8" +license = {file = "LICENSE"} +keywords = ["benchmark"] + +authors = [ + {name = "Google", email = "benchmark-discuss@googlegroups.com"}, +] + +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Software Development :: Testing", + "Topic :: System :: Benchmark", +] + +dynamic = ["readme", "version"] + +dependencies = [ + "absl-py>=0.7.1", +] + +[project.optional-dependencies] +dev = [ + "pre-commit>=3.3.3", +] + +[project.urls] +Homepage = "https://github.com/google/benchmark" +Documentation = "https://github.com/google/benchmark/tree/main/docs" +Repository = "https://github.com/google/benchmark.git" +Discord = "https://discord.gg/cz7UX7wKC2" + +[tool.setuptools] +package-dir = {"" = "bindings/python"} +zip-safe = false + +[tool.setuptools.packages.find] +where = ["bindings/python"] + +[tool.setuptools.dynamic] +readme = { file = "README.md", content-type = "text/markdown" } + +[tool.setuptools_scm] + +[tool.mypy] +check_untyped_defs = true +disallow_incomplete_defs = true +pretty = true +python_version = "3.11" +strict_optional = false +warn_unreachable = true + +[[tool.mypy.overrides]] +module = ["yaml"] +ignore_missing_imports = true + +[tool.ruff] +# explicitly tell ruff the source directory to correctly identify first-party package. +src = ["bindings/python"] + +line-length = 80 +target-version = "py311" + +[tool.ruff.lint] +# Enable pycodestyle (`E`, `W`), Pyflakes (`F`), and isort (`I`) codes by default. +select = ["E", "F", "I", "W"] +ignore = [ + "E501", # line too long +] + +[tool.ruff.lint.isort] +combine-as-imports = true diff --git a/third_party/benchmark/setup.py b/third_party/benchmark/setup.py new file mode 100644 index 0000000..40cdc8d --- /dev/null +++ b/third_party/benchmark/setup.py @@ -0,0 +1,148 @@ +import contextlib +import os +import platform +import re +import shutil +from pathlib import Path +from typing import Any, Generator + +import setuptools +from setuptools.command import build_ext + +IS_WINDOWS = platform.system() == "Windows" +IS_MAC = platform.system() == "Darwin" +IS_LINUX = platform.system() == "Linux" + +# hardcoded SABI-related options. Requires that each Python interpreter +# (hermetic or not) participating is of the same major-minor version. +version_tuple = tuple(int(i) for i in platform.python_version_tuple()) +py_limited_api = version_tuple >= (3, 12) +options = {"bdist_wheel": {"py_limited_api": "cp312"}} if py_limited_api else {} + + +def is_cibuildwheel() -> bool: + return os.getenv("CIBUILDWHEEL") is not None + + +@contextlib.contextmanager +def _maybe_patch_toolchains() -> Generator[None, None, None]: + """ + Patch rules_python toolchains to ignore root user error + when run in a Docker container on Linux in cibuildwheel. + """ + + def fmt_toolchain_args(matchobj): + suffix = "ignore_root_user_error = True" + callargs = matchobj.group(1) + # toolchain def is broken over multiple lines + if callargs.endswith("\n"): + callargs = callargs + " " + suffix + ",\n" + # toolchain def is on one line. + else: + callargs = callargs + ", " + suffix + return "python.toolchain(" + callargs + ")" + + CIBW_LINUX = is_cibuildwheel() and IS_LINUX + try: + if CIBW_LINUX: + module_bazel = Path("MODULE.bazel") + content: str = module_bazel.read_text() + module_bazel.write_text( + re.sub( + r"python.toolchain\(([\w\"\s,.=]*)\)", + fmt_toolchain_args, + content, + ) + ) + yield + finally: + if CIBW_LINUX: + module_bazel.write_text(content) + + +class BazelExtension(setuptools.Extension): + """A C/C++ extension that is defined as a Bazel BUILD target.""" + + def __init__(self, name: str, bazel_target: str, **kwargs: Any): + super().__init__(name=name, sources=[], **kwargs) + + self.bazel_target = bazel_target + stripped_target = bazel_target.split("//")[-1] + self.relpath, self.target_name = stripped_target.split(":") + + +class BuildBazelExtension(build_ext.build_ext): + """A command that runs Bazel to build a C/C++ extension.""" + + def run(self): + for ext in self.extensions: + self.bazel_build(ext) + super().run() + # explicitly call `bazel shutdown` for graceful exit + self.spawn(["bazel", "shutdown"]) + + def copy_extensions_to_source(self): + """ + Copy generated extensions into the source tree. + This is done in the ``bazel_build`` method, so it's not necessary to + do again in the `build_ext` base class. + """ + pass + + def bazel_build(self, ext: BazelExtension) -> None: + """Runs the bazel build to create the package.""" + temp_path = Path(self.build_temp) + # omit the patch version to avoid build errors if the toolchain is not + # yet registered in the current @rules_python version. + # patch version differences should be fine. + python_version = ".".join(platform.python_version_tuple()[:2]) + + bazel_argv = [ + "bazel", + "build", + ext.bazel_target, + f"--symlink_prefix={temp_path / 'bazel-'}", + f"--compilation_mode={'dbg' if self.debug else 'opt'}", + # C++17 is required by nanobind + f"--cxxopt={'/std:c++17' if IS_WINDOWS else '-std=c++17'}", + f"--@rules_python//python/config_settings:python_version={python_version}", + ] + + if ext.py_limited_api: + bazel_argv += ["--@nanobind_bazel//:py-limited-api=cp312"] + + if IS_WINDOWS: + # Link with python*.lib. + for library_dir in self.library_dirs: + bazel_argv.append("--linkopt=/LIBPATH:" + library_dir) + elif IS_MAC: + # C++17 needs macOS 10.14 at minimum + bazel_argv.append("--macos_minimum_os=10.14") + + with _maybe_patch_toolchains(): + self.spawn(bazel_argv) + + if IS_WINDOWS: + suffix = ".pyd" + else: + suffix = ".abi3.so" if ext.py_limited_api else ".so" + + ext_name = ext.target_name + suffix + ext_bazel_bin_path = temp_path / "bazel-bin" / ext.relpath / ext_name + ext_dest_path = Path(self.get_ext_fullpath(ext.name)).with_name( + ext_name + ) + shutil.copyfile(ext_bazel_bin_path, ext_dest_path) + + +setuptools.setup( + cmdclass=dict(build_ext=BuildBazelExtension), + ext_modules=[ + BazelExtension( + name="google_benchmark._benchmark", + bazel_target="//bindings/python/google_benchmark:_benchmark", + py_limited_api=py_limited_api, + ) + ], + options=options, +) diff --git a/third_party/benchmark/src/CMakeLists.txt b/third_party/benchmark/src/CMakeLists.txt new file mode 100644 index 0000000..5551099 --- /dev/null +++ b/third_party/benchmark/src/CMakeLists.txt @@ -0,0 +1,179 @@ +# Allow the source files to find headers in src/ +include(GNUInstallDirs) +include_directories(${PROJECT_SOURCE_DIR}/src) + +if (DEFINED BENCHMARK_CXX_LINKER_FLAGS) + list(APPEND CMAKE_SHARED_LINKER_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS}) + list(APPEND CMAKE_MODULE_LINKER_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS}) +endif() + +file(GLOB + SOURCE_FILES + *.cc + ${PROJECT_SOURCE_DIR}/include/benchmark/*.h + ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB BENCHMARK_MAIN "benchmark_main.cc") +foreach(item ${BENCHMARK_MAIN}) + list(REMOVE_ITEM SOURCE_FILES "${item}") +endforeach() + +add_library(benchmark ${SOURCE_FILES}) +add_library(benchmark::benchmark ALIAS benchmark) +set_target_properties(benchmark PROPERTIES + OUTPUT_NAME "benchmark" + VERSION ${GENERIC_LIB_VERSION} + SOVERSION ${GENERIC_LIB_SOVERSION} +) +target_include_directories(benchmark PUBLIC + $ +) + +set_property( + SOURCE benchmark.cc + APPEND + PROPERTY COMPILE_DEFINITIONS + BENCHMARK_VERSION="${VERSION}" +) + +# libpfm, if available +if (PFM_FOUND) + target_link_libraries(benchmark PRIVATE PFM::libpfm) + target_compile_definitions(benchmark PRIVATE -DHAVE_LIBPFM) +endif() + +# pthread affinity, if available +if(HAVE_PTHREAD_AFFINITY) + target_compile_definitions(benchmark PRIVATE -DBENCHMARK_HAS_PTHREAD_AFFINITY) +endif() + +# Link threads. +target_link_libraries(benchmark PRIVATE Threads::Threads) + +target_link_libraries(benchmark PRIVATE ${BENCHMARK_CXX_LIBRARIES}) + +if(HAVE_LIB_RT) + target_link_libraries(benchmark PRIVATE rt) +endif(HAVE_LIB_RT) + + +# We need extra libraries on Windows +if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") + target_link_libraries(benchmark PRIVATE shlwapi) +endif() + +# We need extra libraries on Solaris +if(${CMAKE_SYSTEM_NAME} MATCHES "SunOS") + target_link_libraries(benchmark PRIVATE kstat) +endif() + +if (NOT BUILD_SHARED_LIBS) + target_compile_definitions(benchmark PUBLIC -DBENCHMARK_STATIC_DEFINE) +endif() + +# Benchmark main library +add_library(benchmark_main "benchmark_main.cc") +add_library(benchmark::benchmark_main ALIAS benchmark_main) +set_target_properties(benchmark_main PROPERTIES + OUTPUT_NAME "benchmark_main" + VERSION ${GENERIC_LIB_VERSION} + SOVERSION ${GENERIC_LIB_SOVERSION} + DEFINE_SYMBOL benchmark_EXPORTS +) +target_link_libraries(benchmark_main PUBLIC benchmark::benchmark) + +set(generated_dir "${PROJECT_BINARY_DIR}") + +set(version_config "${generated_dir}/${PROJECT_NAME}ConfigVersion.cmake") +set(project_config "${generated_dir}/${PROJECT_NAME}Config.cmake") +set(pkg_config "${generated_dir}/${PROJECT_NAME}.pc") +set(pkg_config_main "${generated_dir}/${PROJECT_NAME}_main.pc") +set(targets_to_export benchmark benchmark_main) +set(targets_export_name "${PROJECT_NAME}Targets") + +set(namespace "${PROJECT_NAME}::") + +include(CMakePackageConfigHelpers) + +configure_package_config_file ( + ${PROJECT_SOURCE_DIR}/cmake/Config.cmake.in + ${project_config} + INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} + NO_SET_AND_CHECK_MACRO + NO_CHECK_REQUIRED_COMPONENTS_MACRO +) +write_basic_package_version_file( + "${version_config}" VERSION ${GENERIC_LIB_VERSION} COMPATIBILITY SameMajorVersion +) + +configure_file("${PROJECT_SOURCE_DIR}/cmake/benchmark.pc.in" "${pkg_config}" @ONLY) +configure_file("${PROJECT_SOURCE_DIR}/cmake/benchmark_main.pc.in" "${pkg_config_main}" @ONLY) + +export ( + TARGETS ${targets_to_export} + NAMESPACE "${namespace}" + FILE ${generated_dir}/${targets_export_name}.cmake +) + +if (BENCHMARK_ENABLE_INSTALL) + # Install target (will install the library to specified CMAKE_INSTALL_PREFIX variable) + install( + TARGETS ${targets_to_export} + EXPORT ${targets_export_name} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) + + install( + DIRECTORY "${PROJECT_SOURCE_DIR}/include/benchmark" + "${PROJECT_BINARY_DIR}/include/benchmark" + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} + FILES_MATCHING PATTERN "*.*h") + + install( + FILES "${project_config}" "${version_config}" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}") + + install( + FILES "${pkg_config}" "${pkg_config_main}" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") + + install( + EXPORT "${targets_export_name}" + NAMESPACE "${namespace}" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}") +endif() + +if (BENCHMARK_ENABLE_DOXYGEN) + find_package(Doxygen REQUIRED) + set(DOXYGEN_QUIET YES) + set(DOXYGEN_RECURSIVE YES) + set(DOXYGEN_GENERATE_HTML YES) + set(DOXYGEN_GENERATE_MAN NO) + set(DOXYGEN_MARKDOWN_SUPPORT YES) + set(DOXYGEN_BUILTIN_STL_SUPPORT YES) + set(DOXYGEN_EXTRACT_PACKAGE YES) + set(DOXYGEN_EXTRACT_STATIC YES) + set(DOXYGEN_SHOW_INCLUDE_FILES YES) + set(DOXYGEN_BINARY_TOC YES) + set(DOXYGEN_TOC_EXPAND YES) + set(DOXYGEN_USE_MDFILE_AS_MAINPAGE "index.md") + doxygen_add_docs(benchmark_doxygen + docs + include + src + ALL + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} + COMMENT "Building documentation with Doxygen.") + if (BENCHMARK_ENABLE_INSTALL AND BENCHMARK_INSTALL_DOCS) + install( + DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/html/" + DESTINATION ${CMAKE_INSTALL_DOCDIR}) + endif() +else() + if (BENCHMARK_ENABLE_INSTALL AND BENCHMARK_INSTALL_DOCS) + install( + DIRECTORY "${PROJECT_SOURCE_DIR}/docs/" + DESTINATION ${CMAKE_INSTALL_DOCDIR}) + endif() +endif() diff --git a/third_party/benchmark/src/arraysize.h b/third_party/benchmark/src/arraysize.h new file mode 100644 index 0000000..51a50f2 --- /dev/null +++ b/third_party/benchmark/src/arraysize.h @@ -0,0 +1,33 @@ +#ifndef BENCHMARK_ARRAYSIZE_H_ +#define BENCHMARK_ARRAYSIZE_H_ + +#include "internal_macros.h" + +namespace benchmark { +namespace internal { +// The arraysize(arr) macro returns the # of elements in an array arr. +// The expression is a compile-time constant, and therefore can be +// used in defining new arrays, for example. If you use arraysize on +// a pointer by mistake, you will get a compile-time error. +// + +// This template function declaration is used in defining arraysize. +// Note that the function doesn't need an implementation, as we only +// use its type. +template +char (&ArraySizeHelper(T (&array)[N]))[N]; + +// That gcc wants both of these prototypes seems mysterious. VC, for +// its part, can't decide which to use (another mystery). Matching of +// template overloads: the final frontier. +#ifndef COMPILER_MSVC +template +char (&ArraySizeHelper(const T (&array)[N]))[N]; +#endif + +#define arraysize(array) (sizeof(::benchmark::internal::ArraySizeHelper(array))) + +} // end namespace internal +} // end namespace benchmark + +#endif // BENCHMARK_ARRAYSIZE_H_ diff --git a/third_party/benchmark/src/benchmark.cc b/third_party/benchmark/src/benchmark.cc new file mode 100644 index 0000000..337bb3f --- /dev/null +++ b/third_party/benchmark/src/benchmark.cc @@ -0,0 +1,808 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 "benchmark/benchmark.h" + +#include "benchmark_api_internal.h" +#include "benchmark_runner.h" +#include "internal_macros.h" + +#ifndef BENCHMARK_OS_WINDOWS +#if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT) +#include +#endif +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "check.h" +#include "colorprint.h" +#include "commandlineflags.h" +#include "complexity.h" +#include "counter.h" +#include "internal_macros.h" +#include "log.h" +#include "mutex.h" +#include "perf_counters.h" +#include "re.h" +#include "statistics.h" +#include "string_util.h" +#include "thread_manager.h" +#include "thread_timer.h" + +namespace benchmark { +// Print a list of benchmarks. This option overrides all other options. +BM_DEFINE_bool(benchmark_list_tests, false); + +// A regular expression that specifies the set of benchmarks to execute. If +// this flag is empty, or if this flag is the string \"all\", all benchmarks +// linked into the binary are run. +BM_DEFINE_string(benchmark_filter, ""); + +// Specification of how long to run the benchmark. +// +// It can be either an exact number of iterations (specified as `x`), +// or a minimum number of seconds (specified as `s`). If the latter +// format (ie., min seconds) is used, the system may run the benchmark longer +// until the results are considered significant. +// +// For backward compatibility, the `s` suffix may be omitted, in which case, +// the specified number is interpreted as the number of seconds. +// +// For cpu-time based tests, this is the lower bound +// on the total cpu time used by all threads that make up the test. For +// real-time based tests, this is the lower bound on the elapsed time of the +// benchmark execution, regardless of number of threads. +BM_DEFINE_string(benchmark_min_time, kDefaultMinTimeStr); + +// Minimum number of seconds a benchmark should be run before results should be +// taken into account. This e.g can be necessary for benchmarks of code which +// needs to fill some form of cache before performance is of interest. +// Note: results gathered within this period are discarded and not used for +// reported result. +BM_DEFINE_double(benchmark_min_warmup_time, 0.0); + +// The number of runs of each benchmark. If greater than 1, the mean and +// standard deviation of the runs will be reported. +BM_DEFINE_int32(benchmark_repetitions, 1); + +// If set, enable random interleaving of repetitions of all benchmarks. +// See http://github.com/google/benchmark/issues/1051 for details. +BM_DEFINE_bool(benchmark_enable_random_interleaving, false); + +// Report the result of each benchmark repetitions. When 'true' is specified +// only the mean, standard deviation, and other statistics are reported for +// repeated benchmarks. Affects all reporters. +BM_DEFINE_bool(benchmark_report_aggregates_only, false); + +// Display the result of each benchmark repetitions. When 'true' is specified +// only the mean, standard deviation, and other statistics are displayed for +// repeated benchmarks. Unlike benchmark_report_aggregates_only, only affects +// the display reporter, but *NOT* file reporter, which will still contain +// all the output. +BM_DEFINE_bool(benchmark_display_aggregates_only, false); + +// The format to use for console output. +// Valid values are 'console', 'json', or 'csv'. +BM_DEFINE_string(benchmark_format, "console"); + +// The format to use for file output. +// Valid values are 'console', 'json', or 'csv'. +BM_DEFINE_string(benchmark_out_format, "json"); + +// The file to write additional output to. +BM_DEFINE_string(benchmark_out, ""); + +// Whether to use colors in the output. Valid values: +// 'true'/'yes'/1, 'false'/'no'/0, and 'auto'. 'auto' means to use colors if +// the output is being sent to a terminal and the TERM environment variable is +// set to a terminal type that supports colors. +BM_DEFINE_string(benchmark_color, "auto"); + +// Whether to use tabular format when printing user counters to the console. +// Valid values: 'true'/'yes'/1, 'false'/'no'/0. Defaults to false. +BM_DEFINE_bool(benchmark_counters_tabular, false); + +// List of additional perf counters to collect, in libpfm format. For more +// information about libpfm: https://man7.org/linux/man-pages/man3/libpfm.3.html +BM_DEFINE_string(benchmark_perf_counters, ""); + +// Extra context to include in the output formatted as comma-separated key-value +// pairs. Kept internal as it's only used for parsing from env/command line. +BM_DEFINE_kvpairs(benchmark_context, {}); + +// Set the default time unit to use for reports +// Valid values are 'ns', 'us', 'ms' or 's' +BM_DEFINE_string(benchmark_time_unit, ""); + +// The level of verbose logging to output +BM_DEFINE_int32(v, 0); + +namespace internal { + +std::map* global_context = nullptr; + +BENCHMARK_EXPORT std::map*& GetGlobalContext() { + return global_context; +} + +static void const volatile* volatile global_force_escape_pointer; + +// FIXME: Verify if LTO still messes this up? +void UseCharPointer(char const volatile* const v) { + // We want to escape the pointer `v` so that the compiler can not eliminate + // computations that produced it. To do that, we escape the pointer by storing + // it into a volatile variable, since generally, volatile store, is not + // something the compiler is allowed to elide. + global_force_escape_pointer = reinterpret_cast(v); +} + +} // namespace internal + +State::State(std::string name, IterationCount max_iters, + const std::vector& ranges, int thread_i, int n_threads, + internal::ThreadTimer* timer, internal::ThreadManager* manager, + internal::PerfCountersMeasurement* perf_counters_measurement) + : total_iterations_(0), + batch_leftover_(0), + max_iterations(max_iters), + started_(false), + finished_(false), + skipped_(internal::NotSkipped), + range_(ranges), + complexity_n_(0), + name_(std::move(name)), + thread_index_(thread_i), + threads_(n_threads), + timer_(timer), + manager_(manager), + perf_counters_measurement_(perf_counters_measurement) { + BM_CHECK(max_iterations != 0) << "At least one iteration must be run"; + BM_CHECK_LT(thread_index_, threads_) + << "thread_index must be less than threads"; + + // Add counters with correct flag now. If added with `counters[name]` in + // `PauseTiming`, a new `Counter` will be inserted the first time, which + // won't have the flag. Inserting them now also reduces the allocations + // during the benchmark. + if (perf_counters_measurement_) { + for (const std::string& counter_name : + perf_counters_measurement_->names()) { + counters[counter_name] = Counter(0.0, Counter::kAvgIterations); + } + } + + // Note: The use of offsetof below is technically undefined until C++17 + // because State is not a standard layout type. However, all compilers + // currently provide well-defined behavior as an extension (which is + // demonstrated since constexpr evaluation must diagnose all undefined + // behavior). However, GCC and Clang also warn about this use of offsetof, + // which must be suppressed. +#if defined(__INTEL_COMPILER) +#pragma warning push +#pragma warning(disable : 1875) +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Winvalid-offsetof" +#endif +#if defined(__NVCC__) +#pragma nv_diagnostic push +#pragma nv_diag_suppress 1427 +#endif +#if defined(__NVCOMPILER) +#pragma diagnostic push +#pragma diag_suppress offset_in_non_POD_nonstandard +#endif + // Offset tests to ensure commonly accessed data is on the first cache line. + const int cache_line_size = 64; + static_assert( + offsetof(State, skipped_) <= (cache_line_size - sizeof(skipped_)), ""); +#if defined(__INTEL_COMPILER) +#pragma warning pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif +#if defined(__NVCC__) +#pragma nv_diagnostic pop +#endif +#if defined(__NVCOMPILER) +#pragma diagnostic pop +#endif +} + +void State::PauseTiming() { + // Add in time accumulated so far + BM_CHECK(started_ && !finished_ && !skipped()); + timer_->StopTimer(); + if (perf_counters_measurement_) { + std::vector> measurements; + if (!perf_counters_measurement_->Stop(measurements)) { + BM_CHECK(false) << "Perf counters read the value failed."; + } + for (const auto& name_and_measurement : measurements) { + const std::string& name = name_and_measurement.first; + const double measurement = name_and_measurement.second; + // Counter was inserted with `kAvgIterations` flag by the constructor. + assert(counters.find(name) != counters.end()); + counters[name].value += measurement; + } + } +} + +void State::ResumeTiming() { + BM_CHECK(started_ && !finished_ && !skipped()); + timer_->StartTimer(); + if (perf_counters_measurement_) { + perf_counters_measurement_->Start(); + } +} + +void State::SkipWithMessage(const std::string& msg) { + skipped_ = internal::SkippedWithMessage; + { + MutexLock l(manager_->GetBenchmarkMutex()); + if (internal::NotSkipped == manager_->results.skipped_) { + manager_->results.skip_message_ = msg; + manager_->results.skipped_ = skipped_; + } + } + total_iterations_ = 0; + if (timer_->running()) timer_->StopTimer(); +} + +void State::SkipWithError(const std::string& msg) { + skipped_ = internal::SkippedWithError; + { + MutexLock l(manager_->GetBenchmarkMutex()); + if (internal::NotSkipped == manager_->results.skipped_) { + manager_->results.skip_message_ = msg; + manager_->results.skipped_ = skipped_; + } + } + total_iterations_ = 0; + if (timer_->running()) timer_->StopTimer(); +} + +void State::SetIterationTime(double seconds) { + timer_->SetIterationTime(seconds); +} + +void State::SetLabel(const std::string& label) { + MutexLock l(manager_->GetBenchmarkMutex()); + manager_->results.report_label_ = label; +} + +void State::StartKeepRunning() { + BM_CHECK(!started_ && !finished_); + started_ = true; + total_iterations_ = skipped() ? 0 : max_iterations; + manager_->StartStopBarrier(); + if (!skipped()) ResumeTiming(); +} + +void State::FinishKeepRunning() { + BM_CHECK(started_ && (!finished_ || skipped())); + if (!skipped()) { + PauseTiming(); + } + // Total iterations has now wrapped around past 0. Fix this. + total_iterations_ = 0; + finished_ = true; + manager_->StartStopBarrier(); +} + +namespace internal { +namespace { + +// Flushes streams after invoking reporter methods that write to them. This +// ensures users get timely updates even when streams are not line-buffered. +void FlushStreams(BenchmarkReporter* reporter) { + if (!reporter) return; + std::flush(reporter->GetOutputStream()); + std::flush(reporter->GetErrorStream()); +} + +// Reports in both display and file reporters. +void Report(BenchmarkReporter* display_reporter, + BenchmarkReporter* file_reporter, const RunResults& run_results) { + auto report_one = [](BenchmarkReporter* reporter, bool aggregates_only, + const RunResults& results) { + assert(reporter); + // If there are no aggregates, do output non-aggregates. + aggregates_only &= !results.aggregates_only.empty(); + if (!aggregates_only) reporter->ReportRuns(results.non_aggregates); + if (!results.aggregates_only.empty()) + reporter->ReportRuns(results.aggregates_only); + }; + + report_one(display_reporter, run_results.display_report_aggregates_only, + run_results); + if (file_reporter) + report_one(file_reporter, run_results.file_report_aggregates_only, + run_results); + + FlushStreams(display_reporter); + FlushStreams(file_reporter); +} + +void RunBenchmarks(const std::vector& benchmarks, + BenchmarkReporter* display_reporter, + BenchmarkReporter* file_reporter) { + // Note the file_reporter can be null. + BM_CHECK(display_reporter != nullptr); + + // Determine the width of the name field using a minimum width of 10. + bool might_have_aggregates = FLAGS_benchmark_repetitions > 1; + size_t name_field_width = 10; + size_t stat_field_width = 0; + for (const BenchmarkInstance& benchmark : benchmarks) { + name_field_width = + std::max(name_field_width, benchmark.name().str().size()); + might_have_aggregates |= benchmark.repetitions() > 1; + + for (const auto& Stat : benchmark.statistics()) + stat_field_width = std::max(stat_field_width, Stat.name_.size()); + } + if (might_have_aggregates) name_field_width += 1 + stat_field_width; + + // Print header here + BenchmarkReporter::Context context; + context.name_field_width = name_field_width; + + // Keep track of running times of all instances of each benchmark family. + std::map + per_family_reports; + + if (display_reporter->ReportContext(context) && + (!file_reporter || file_reporter->ReportContext(context))) { + FlushStreams(display_reporter); + FlushStreams(file_reporter); + + size_t num_repetitions_total = 0; + + // This perfcounters object needs to be created before the runners vector + // below so it outlasts their lifetime. + PerfCountersMeasurement perfcounters( + StrSplit(FLAGS_benchmark_perf_counters, ',')); + + // Vector of benchmarks to run + std::vector runners; + runners.reserve(benchmarks.size()); + + // Count the number of benchmarks with threads to warn the user in case + // performance counters are used. + int benchmarks_with_threads = 0; + + // Loop through all benchmarks + for (const BenchmarkInstance& benchmark : benchmarks) { + BenchmarkReporter::PerFamilyRunReports* reports_for_family = nullptr; + if (benchmark.complexity() != oNone) + reports_for_family = &per_family_reports[benchmark.family_index()]; + benchmarks_with_threads += (benchmark.threads() > 1); + runners.emplace_back(benchmark, &perfcounters, reports_for_family); + int num_repeats_of_this_instance = runners.back().GetNumRepeats(); + num_repetitions_total += + static_cast(num_repeats_of_this_instance); + if (reports_for_family) + reports_for_family->num_runs_total += num_repeats_of_this_instance; + } + assert(runners.size() == benchmarks.size() && "Unexpected runner count."); + + // The use of performance counters with threads would be unintuitive for + // the average user so we need to warn them about this case + if ((benchmarks_with_threads > 0) && (perfcounters.num_counters() > 0)) { + GetErrorLogInstance() + << "***WARNING*** There are " << benchmarks_with_threads + << " benchmarks with threads and " << perfcounters.num_counters() + << " performance counters were requested. Beware counters will " + "reflect the combined usage across all " + "threads.\n"; + } + + std::vector repetition_indices; + repetition_indices.reserve(num_repetitions_total); + for (size_t runner_index = 0, num_runners = runners.size(); + runner_index != num_runners; ++runner_index) { + const internal::BenchmarkRunner& runner = runners[runner_index]; + std::fill_n(std::back_inserter(repetition_indices), + runner.GetNumRepeats(), runner_index); + } + assert(repetition_indices.size() == num_repetitions_total && + "Unexpected number of repetition indexes."); + + if (FLAGS_benchmark_enable_random_interleaving) { + std::random_device rd; + std::mt19937 g(rd()); + std::shuffle(repetition_indices.begin(), repetition_indices.end(), g); + } + + for (size_t repetition_index : repetition_indices) { + internal::BenchmarkRunner& runner = runners[repetition_index]; + runner.DoOneRepetition(); + if (runner.HasRepeatsRemaining()) continue; + // FIXME: report each repetition separately, not all of them in bulk. + + display_reporter->ReportRunsConfig( + runner.GetMinTime(), runner.HasExplicitIters(), runner.GetIters()); + if (file_reporter) + file_reporter->ReportRunsConfig( + runner.GetMinTime(), runner.HasExplicitIters(), runner.GetIters()); + + RunResults run_results = runner.GetResults(); + + // Maybe calculate complexity report + if (const auto* reports_for_family = runner.GetReportsForFamily()) { + if (reports_for_family->num_runs_done == + reports_for_family->num_runs_total) { + auto additional_run_stats = ComputeBigO(reports_for_family->Runs); + run_results.aggregates_only.insert(run_results.aggregates_only.end(), + additional_run_stats.begin(), + additional_run_stats.end()); + per_family_reports.erase( + static_cast(reports_for_family->Runs.front().family_index)); + } + } + + Report(display_reporter, file_reporter, run_results); + } + } + display_reporter->Finalize(); + if (file_reporter) file_reporter->Finalize(); + FlushStreams(display_reporter); + FlushStreams(file_reporter); +} + +// Disable deprecated warnings temporarily because we need to reference +// CSVReporter but don't want to trigger -Werror=-Wdeprecated-declarations +BENCHMARK_DISABLE_DEPRECATED_WARNING + +std::unique_ptr CreateReporter( + std::string const& name, ConsoleReporter::OutputOptions output_opts) { + typedef std::unique_ptr PtrType; + if (name == "console") { + return PtrType(new ConsoleReporter(output_opts)); + } + if (name == "json") { + return PtrType(new JSONReporter()); + } + if (name == "csv") { + return PtrType(new CSVReporter()); + } + std::cerr << "Unexpected format: '" << name << "'\n"; + std::exit(1); +} + +BENCHMARK_RESTORE_DEPRECATED_WARNING + +} // end namespace + +bool IsZero(double n) { + return std::abs(n) < std::numeric_limits::epsilon(); +} + +ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color) { + int output_opts = ConsoleReporter::OO_Defaults; + auto is_benchmark_color = [force_no_color]() -> bool { + if (force_no_color) { + return false; + } + if (FLAGS_benchmark_color == "auto") { + return IsColorTerminal(); + } + return IsTruthyFlagValue(FLAGS_benchmark_color); + }; + if (is_benchmark_color()) { + output_opts |= ConsoleReporter::OO_Color; + } else { + output_opts &= ~ConsoleReporter::OO_Color; + } + if (FLAGS_benchmark_counters_tabular) { + output_opts |= ConsoleReporter::OO_Tabular; + } else { + output_opts &= ~ConsoleReporter::OO_Tabular; + } + return static_cast(output_opts); +} + +} // end namespace internal + +BenchmarkReporter* CreateDefaultDisplayReporter() { + static auto default_display_reporter = + internal::CreateReporter(FLAGS_benchmark_format, + internal::GetOutputOptions()) + .release(); + return default_display_reporter; +} + +size_t RunSpecifiedBenchmarks() { + return RunSpecifiedBenchmarks(nullptr, nullptr, FLAGS_benchmark_filter); +} + +size_t RunSpecifiedBenchmarks(std::string spec) { + return RunSpecifiedBenchmarks(nullptr, nullptr, std::move(spec)); +} + +size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter) { + return RunSpecifiedBenchmarks(display_reporter, nullptr, + FLAGS_benchmark_filter); +} + +size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, + std::string spec) { + return RunSpecifiedBenchmarks(display_reporter, nullptr, std::move(spec)); +} + +size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, + BenchmarkReporter* file_reporter) { + return RunSpecifiedBenchmarks(display_reporter, file_reporter, + FLAGS_benchmark_filter); +} + +size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, + BenchmarkReporter* file_reporter, + std::string spec) { + if (spec.empty() || spec == "all") + spec = "."; // Regexp that matches all benchmarks + + // Setup the reporters + std::ofstream output_file; + std::unique_ptr default_display_reporter; + std::unique_ptr default_file_reporter; + if (!display_reporter) { + default_display_reporter.reset(CreateDefaultDisplayReporter()); + display_reporter = default_display_reporter.get(); + } + auto& Out = display_reporter->GetOutputStream(); + auto& Err = display_reporter->GetErrorStream(); + + std::string const& fname = FLAGS_benchmark_out; + if (fname.empty() && file_reporter) { + Err << "A custom file reporter was provided but " + "--benchmark_out= was not specified." + << std::endl; + Out.flush(); + Err.flush(); + std::exit(1); + } + if (!fname.empty()) { + output_file.open(fname); + if (!output_file.is_open()) { + Err << "invalid file name: '" << fname << "'" << std::endl; + Out.flush(); + Err.flush(); + std::exit(1); + } + if (!file_reporter) { + default_file_reporter = internal::CreateReporter( + FLAGS_benchmark_out_format, FLAGS_benchmark_counters_tabular + ? ConsoleReporter::OO_Tabular + : ConsoleReporter::OO_None); + file_reporter = default_file_reporter.get(); + } + file_reporter->SetOutputStream(&output_file); + file_reporter->SetErrorStream(&output_file); + } + + std::vector benchmarks; + if (!FindBenchmarksInternal(spec, &benchmarks, &Err)) { + Out.flush(); + Err.flush(); + return 0; + } + + if (benchmarks.empty()) { + Err << "Failed to match any benchmarks against regex: " << spec << "\n"; + Out.flush(); + Err.flush(); + return 0; + } + + if (FLAGS_benchmark_list_tests) { + for (auto const& benchmark : benchmarks) + Out << benchmark.name().str() << "\n"; + } else { + internal::RunBenchmarks(benchmarks, display_reporter, file_reporter); + } + + Out.flush(); + Err.flush(); + return benchmarks.size(); +} + +namespace { +// stores the time unit benchmarks use by default +TimeUnit default_time_unit = kNanosecond; +} // namespace + +TimeUnit GetDefaultTimeUnit() { return default_time_unit; } + +void SetDefaultTimeUnit(TimeUnit unit) { default_time_unit = unit; } + +std::string GetBenchmarkFilter() { return FLAGS_benchmark_filter; } + +void SetBenchmarkFilter(std::string value) { + FLAGS_benchmark_filter = std::move(value); +} + +int32_t GetBenchmarkVerbosity() { return FLAGS_v; } + +void RegisterMemoryManager(MemoryManager* manager) { + internal::memory_manager = manager; +} + +void AddCustomContext(const std::string& key, const std::string& value) { + if (internal::global_context == nullptr) { + internal::global_context = new std::map(); + } + if (!internal::global_context->emplace(key, value).second) { + std::cerr << "Failed to add custom context \"" << key << "\" as it already " + << "exists with value \"" << value << "\"\n"; + } +} + +namespace internal { + +void (*HelperPrintf)(); + +void PrintUsageAndExit() { + HelperPrintf(); + exit(0); +} + +void SetDefaultTimeUnitFromFlag(const std::string& time_unit_flag) { + if (time_unit_flag == "s") { + return SetDefaultTimeUnit(kSecond); + } + if (time_unit_flag == "ms") { + return SetDefaultTimeUnit(kMillisecond); + } + if (time_unit_flag == "us") { + return SetDefaultTimeUnit(kMicrosecond); + } + if (time_unit_flag == "ns") { + return SetDefaultTimeUnit(kNanosecond); + } + if (!time_unit_flag.empty()) { + PrintUsageAndExit(); + } +} + +void ParseCommandLineFlags(int* argc, char** argv) { + using namespace benchmark; + BenchmarkReporter::Context::executable_name = + (argc && *argc > 0) ? argv[0] : "unknown"; + for (int i = 1; argc && i < *argc; ++i) { + if (ParseBoolFlag(argv[i], "benchmark_list_tests", + &FLAGS_benchmark_list_tests) || + ParseStringFlag(argv[i], "benchmark_filter", &FLAGS_benchmark_filter) || + ParseStringFlag(argv[i], "benchmark_min_time", + &FLAGS_benchmark_min_time) || + ParseDoubleFlag(argv[i], "benchmark_min_warmup_time", + &FLAGS_benchmark_min_warmup_time) || + ParseInt32Flag(argv[i], "benchmark_repetitions", + &FLAGS_benchmark_repetitions) || + ParseBoolFlag(argv[i], "benchmark_enable_random_interleaving", + &FLAGS_benchmark_enable_random_interleaving) || + ParseBoolFlag(argv[i], "benchmark_report_aggregates_only", + &FLAGS_benchmark_report_aggregates_only) || + ParseBoolFlag(argv[i], "benchmark_display_aggregates_only", + &FLAGS_benchmark_display_aggregates_only) || + ParseStringFlag(argv[i], "benchmark_format", &FLAGS_benchmark_format) || + ParseStringFlag(argv[i], "benchmark_out", &FLAGS_benchmark_out) || + ParseStringFlag(argv[i], "benchmark_out_format", + &FLAGS_benchmark_out_format) || + ParseStringFlag(argv[i], "benchmark_color", &FLAGS_benchmark_color) || + ParseBoolFlag(argv[i], "benchmark_counters_tabular", + &FLAGS_benchmark_counters_tabular) || + ParseStringFlag(argv[i], "benchmark_perf_counters", + &FLAGS_benchmark_perf_counters) || + ParseKeyValueFlag(argv[i], "benchmark_context", + &FLAGS_benchmark_context) || + ParseStringFlag(argv[i], "benchmark_time_unit", + &FLAGS_benchmark_time_unit) || + ParseInt32Flag(argv[i], "v", &FLAGS_v)) { + for (int j = i; j != *argc - 1; ++j) argv[j] = argv[j + 1]; + + --(*argc); + --i; + } else if (IsFlag(argv[i], "help")) { + PrintUsageAndExit(); + } + } + for (auto const* flag : + {&FLAGS_benchmark_format, &FLAGS_benchmark_out_format}) { + if (*flag != "console" && *flag != "json" && *flag != "csv") { + PrintUsageAndExit(); + } + } + SetDefaultTimeUnitFromFlag(FLAGS_benchmark_time_unit); + if (FLAGS_benchmark_color.empty()) { + PrintUsageAndExit(); + } + for (const auto& kv : FLAGS_benchmark_context) { + AddCustomContext(kv.first, kv.second); + } +} + +int InitializeStreams() { + static std::ios_base::Init init; + return 0; +} + +} // end namespace internal + +std::string GetBenchmarkVersion() { +#ifdef BENCHMARK_VERSION + return {BENCHMARK_VERSION}; +#else + return {""}; +#endif +} + +void PrintDefaultHelp() { + fprintf(stdout, + "benchmark" + " [--benchmark_list_tests={true|false}]\n" + " [--benchmark_filter=]\n" + " [--benchmark_min_time=`x` OR `s` ]\n" + " [--benchmark_min_warmup_time=]\n" + " [--benchmark_repetitions=]\n" + " [--benchmark_enable_random_interleaving={true|false}]\n" + " [--benchmark_report_aggregates_only={true|false}]\n" + " [--benchmark_display_aggregates_only={true|false}]\n" + " [--benchmark_format=]\n" + " [--benchmark_out=]\n" + " [--benchmark_out_format=]\n" + " [--benchmark_color={auto|true|false}]\n" + " [--benchmark_counters_tabular={true|false}]\n" +#if defined HAVE_LIBPFM + " [--benchmark_perf_counters=,...]\n" +#endif + " [--benchmark_context==,...]\n" + " [--benchmark_time_unit={ns|us|ms|s}]\n" + " [--v=]\n"); +} + +void Initialize(int* argc, char** argv, void (*HelperPrintf)()) { + internal::HelperPrintf = HelperPrintf; + internal::ParseCommandLineFlags(argc, argv); + internal::LogLevel() = FLAGS_v; +} + +void Shutdown() { delete internal::global_context; } + +bool ReportUnrecognizedArguments(int argc, char** argv) { + for (int i = 1; i < argc; ++i) { + fprintf(stderr, "%s: error: unrecognized command-line flag: %s\n", argv[0], + argv[i]); + } + return argc > 1; +} + +} // end namespace benchmark diff --git a/third_party/benchmark/src/benchmark_api_internal.cc b/third_party/benchmark/src/benchmark_api_internal.cc new file mode 100644 index 0000000..286f986 --- /dev/null +++ b/third_party/benchmark/src/benchmark_api_internal.cc @@ -0,0 +1,118 @@ +#include "benchmark_api_internal.h" + +#include + +#include "string_util.h" + +namespace benchmark { +namespace internal { + +BenchmarkInstance::BenchmarkInstance(Benchmark* benchmark, int family_idx, + int per_family_instance_idx, + const std::vector& args, + int thread_count) + : benchmark_(*benchmark), + family_index_(family_idx), + per_family_instance_index_(per_family_instance_idx), + aggregation_report_mode_(benchmark_.aggregation_report_mode_), + args_(args), + time_unit_(benchmark_.GetTimeUnit()), + measure_process_cpu_time_(benchmark_.measure_process_cpu_time_), + use_real_time_(benchmark_.use_real_time_), + use_manual_time_(benchmark_.use_manual_time_), + complexity_(benchmark_.complexity_), + complexity_lambda_(benchmark_.complexity_lambda_), + statistics_(benchmark_.statistics_), + repetitions_(benchmark_.repetitions_), + min_time_(benchmark_.min_time_), + min_warmup_time_(benchmark_.min_warmup_time_), + iterations_(benchmark_.iterations_), + threads_(thread_count) { + name_.function_name = benchmark_.name_; + + size_t arg_i = 0; + for (const auto& arg : args) { + if (!name_.args.empty()) { + name_.args += '/'; + } + + if (arg_i < benchmark->arg_names_.size()) { + const auto& arg_name = benchmark_.arg_names_[arg_i]; + if (!arg_name.empty()) { + name_.args += StrFormat("%s:", arg_name.c_str()); + } + } + + name_.args += StrFormat("%" PRId64, arg); + ++arg_i; + } + + if (!IsZero(benchmark->min_time_)) { + name_.min_time = StrFormat("min_time:%0.3f", benchmark_.min_time_); + } + + if (!IsZero(benchmark->min_warmup_time_)) { + name_.min_warmup_time = + StrFormat("min_warmup_time:%0.3f", benchmark_.min_warmup_time_); + } + + if (benchmark_.iterations_ != 0) { + name_.iterations = StrFormat( + "iterations:%lu", static_cast(benchmark_.iterations_)); + } + + if (benchmark_.repetitions_ != 0) { + name_.repetitions = StrFormat("repeats:%d", benchmark_.repetitions_); + } + + if (benchmark_.measure_process_cpu_time_) { + name_.time_type = "process_time"; + } + + if (benchmark_.use_manual_time_) { + if (!name_.time_type.empty()) { + name_.time_type += '/'; + } + name_.time_type += "manual_time"; + } else if (benchmark_.use_real_time_) { + if (!name_.time_type.empty()) { + name_.time_type += '/'; + } + name_.time_type += "real_time"; + } + + if (!benchmark_.thread_counts_.empty()) { + name_.threads = StrFormat("threads:%d", threads_); + } + + setup_ = benchmark_.setup_; + teardown_ = benchmark_.teardown_; +} + +State BenchmarkInstance::Run( + IterationCount iters, int thread_id, internal::ThreadTimer* timer, + internal::ThreadManager* manager, + internal::PerfCountersMeasurement* perf_counters_measurement) const { + State st(name_.function_name, iters, args_, thread_id, threads_, timer, + manager, perf_counters_measurement); + benchmark_.Run(st); + return st; +} + +void BenchmarkInstance::Setup() const { + if (setup_) { + State st(name_.function_name, /*iters*/ 1, args_, /*thread_id*/ 0, threads_, + nullptr, nullptr, nullptr); + setup_(st); + } +} + +void BenchmarkInstance::Teardown() const { + if (teardown_) { + State st(name_.function_name, /*iters*/ 1, args_, /*thread_id*/ 0, threads_, + nullptr, nullptr, nullptr); + teardown_(st); + } +} +} // namespace internal +} // namespace benchmark diff --git a/third_party/benchmark/src/benchmark_api_internal.h b/third_party/benchmark/src/benchmark_api_internal.h new file mode 100644 index 0000000..94f5165 --- /dev/null +++ b/third_party/benchmark/src/benchmark_api_internal.h @@ -0,0 +1,87 @@ +#ifndef BENCHMARK_API_INTERNAL_H +#define BENCHMARK_API_INTERNAL_H + +#include +#include +#include +#include +#include +#include + +#include "benchmark/benchmark.h" +#include "commandlineflags.h" + +namespace benchmark { +namespace internal { + +// Information kept per benchmark we may want to run +class BenchmarkInstance { + public: + BenchmarkInstance(Benchmark* benchmark, int family_index, + int per_family_instance_index, + const std::vector& args, int threads); + + const BenchmarkName& name() const { return name_; } + int family_index() const { return family_index_; } + int per_family_instance_index() const { return per_family_instance_index_; } + AggregationReportMode aggregation_report_mode() const { + return aggregation_report_mode_; + } + TimeUnit time_unit() const { return time_unit_; } + bool measure_process_cpu_time() const { return measure_process_cpu_time_; } + bool use_real_time() const { return use_real_time_; } + bool use_manual_time() const { return use_manual_time_; } + BigO complexity() const { return complexity_; } + BigOFunc* complexity_lambda() const { return complexity_lambda_; } + const std::vector& statistics() const { return statistics_; } + int repetitions() const { return repetitions_; } + double min_time() const { return min_time_; } + double min_warmup_time() const { return min_warmup_time_; } + IterationCount iterations() const { return iterations_; } + int threads() const { return threads_; } + void Setup() const; + void Teardown() const; + + State Run(IterationCount iters, int thread_id, internal::ThreadTimer* timer, + internal::ThreadManager* manager, + internal::PerfCountersMeasurement* perf_counters_measurement) const; + + private: + BenchmarkName name_; + Benchmark& benchmark_; + const int family_index_; + const int per_family_instance_index_; + AggregationReportMode aggregation_report_mode_; + const std::vector& args_; + TimeUnit time_unit_; + bool measure_process_cpu_time_; + bool use_real_time_; + bool use_manual_time_; + BigO complexity_; + BigOFunc* complexity_lambda_; + UserCounters counters_; + const std::vector& statistics_; + int repetitions_; + double min_time_; + double min_warmup_time_; + IterationCount iterations_; + int threads_; // Number of concurrent threads to us + + typedef void (*callback_function)(const benchmark::State&); + callback_function setup_ = nullptr; + callback_function teardown_ = nullptr; +}; + +bool FindBenchmarksInternal(const std::string& re, + std::vector* benchmarks, + std::ostream* Err); + +bool IsZero(double n); + +BENCHMARK_EXPORT +ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color = false); + +} // end namespace internal +} // end namespace benchmark + +#endif // BENCHMARK_API_INTERNAL_H diff --git a/third_party/benchmark/src/benchmark_main.cc b/third_party/benchmark/src/benchmark_main.cc new file mode 100644 index 0000000..cd61cd2 --- /dev/null +++ b/third_party/benchmark/src/benchmark_main.cc @@ -0,0 +1,18 @@ +// Copyright 2018 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 "benchmark/benchmark.h" + +BENCHMARK_EXPORT int main(int, char**); +BENCHMARK_MAIN(); diff --git a/third_party/benchmark/src/benchmark_name.cc b/third_party/benchmark/src/benchmark_name.cc new file mode 100644 index 0000000..01676bb --- /dev/null +++ b/third_party/benchmark/src/benchmark_name.cc @@ -0,0 +1,59 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 + +namespace benchmark { + +namespace { + +// Compute the total size of a pack of std::strings +size_t size_impl() { return 0; } + +template +size_t size_impl(const Head& head, const Tail&... tail) { + return head.size() + size_impl(tail...); +} + +// Join a pack of std::strings using a delimiter +// TODO: use absl::StrJoin +void join_impl(std::string&, char) {} + +template +void join_impl(std::string& s, const char delimiter, const Head& head, + const Tail&... tail) { + if (!s.empty() && !head.empty()) { + s += delimiter; + } + + s += head; + + join_impl(s, delimiter, tail...); +} + +template +std::string join(char delimiter, const Ts&... ts) { + std::string s; + s.reserve(sizeof...(Ts) + size_impl(ts...)); + join_impl(s, delimiter, ts...); + return s; +} +} // namespace + +BENCHMARK_EXPORT +std::string BenchmarkName::str() const { + return join('/', function_name, args, min_time, min_warmup_time, iterations, + repetitions, time_type, threads); +} +} // namespace benchmark diff --git a/third_party/benchmark/src/benchmark_register.cc b/third_party/benchmark/src/benchmark_register.cc new file mode 100644 index 0000000..8ade048 --- /dev/null +++ b/third_party/benchmark/src/benchmark_register.cc @@ -0,0 +1,521 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 "benchmark_register.h" + +#ifndef BENCHMARK_OS_WINDOWS +#if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT) +#include +#endif +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "benchmark/benchmark.h" +#include "benchmark_api_internal.h" +#include "check.h" +#include "commandlineflags.h" +#include "complexity.h" +#include "internal_macros.h" +#include "log.h" +#include "mutex.h" +#include "re.h" +#include "statistics.h" +#include "string_util.h" +#include "timers.h" + +namespace benchmark { + +namespace { +// For non-dense Range, intermediate values are powers of kRangeMultiplier. +static constexpr int kRangeMultiplier = 8; + +// The size of a benchmark family determines is the number of inputs to repeat +// the benchmark on. If this is "large" then warn the user during configuration. +static constexpr size_t kMaxFamilySize = 100; + +static constexpr char kDisabledPrefix[] = "DISABLED_"; +} // end namespace + +namespace internal { + +//=============================================================================// +// BenchmarkFamilies +//=============================================================================// + +// Class for managing registered benchmarks. Note that each registered +// benchmark identifies a family of related benchmarks to run. +class BenchmarkFamilies { + public: + static BenchmarkFamilies* GetInstance(); + + // Registers a benchmark family and returns the index assigned to it. + size_t AddBenchmark(std::unique_ptr family); + + // Clear all registered benchmark families. + void ClearBenchmarks(); + + // Extract the list of benchmark instances that match the specified + // regular expression. + bool FindBenchmarks(std::string re, + std::vector* benchmarks, + std::ostream* Err); + + private: + BenchmarkFamilies() {} + + std::vector> families_; + Mutex mutex_; +}; + +BenchmarkFamilies* BenchmarkFamilies::GetInstance() { + static BenchmarkFamilies instance; + return &instance; +} + +size_t BenchmarkFamilies::AddBenchmark(std::unique_ptr family) { + MutexLock l(mutex_); + size_t index = families_.size(); + families_.push_back(std::move(family)); + return index; +} + +void BenchmarkFamilies::ClearBenchmarks() { + MutexLock l(mutex_); + families_.clear(); + families_.shrink_to_fit(); +} + +bool BenchmarkFamilies::FindBenchmarks( + std::string spec, std::vector* benchmarks, + std::ostream* ErrStream) { + BM_CHECK(ErrStream); + auto& Err = *ErrStream; + // Make regular expression out of command-line flag + std::string error_msg; + Regex re; + bool is_negative_filter = false; + if (spec[0] == '-') { + spec.replace(0, 1, ""); + is_negative_filter = true; + } + if (!re.Init(spec, &error_msg)) { + Err << "Could not compile benchmark re: " << error_msg << std::endl; + return false; + } + + // Special list of thread counts to use when none are specified + const std::vector one_thread = {1}; + + int next_family_index = 0; + + MutexLock l(mutex_); + for (std::unique_ptr& family : families_) { + int family_index = next_family_index; + int per_family_instance_index = 0; + + // Family was deleted or benchmark doesn't match + if (!family) continue; + + if (family->ArgsCnt() == -1) { + family->Args({}); + } + const std::vector* thread_counts = + (family->thread_counts_.empty() + ? &one_thread + : &static_cast&>(family->thread_counts_)); + const size_t family_size = family->args_.size() * thread_counts->size(); + // The benchmark will be run at least 'family_size' different inputs. + // If 'family_size' is very large warn the user. + if (family_size > kMaxFamilySize) { + Err << "The number of inputs is very large. " << family->name_ + << " will be repeated at least " << family_size << " times.\n"; + } + // reserve in the special case the regex ".", since we know the final + // family size. this doesn't take into account any disabled benchmarks + // so worst case we reserve more than we need. + if (spec == ".") benchmarks->reserve(benchmarks->size() + family_size); + + for (auto const& args : family->args_) { + for (int num_threads : *thread_counts) { + BenchmarkInstance instance(family.get(), family_index, + per_family_instance_index, args, + num_threads); + + const auto full_name = instance.name().str(); + if (full_name.rfind(kDisabledPrefix, 0) != 0 && + ((re.Match(full_name) && !is_negative_filter) || + (!re.Match(full_name) && is_negative_filter))) { + benchmarks->push_back(std::move(instance)); + + ++per_family_instance_index; + + // Only bump the next family index once we've estabilished that + // at least one instance of this family will be run. + if (next_family_index == family_index) ++next_family_index; + } + } + } + } + return true; +} + +Benchmark* RegisterBenchmarkInternal(Benchmark* bench) { + std::unique_ptr bench_ptr(bench); + BenchmarkFamilies* families = BenchmarkFamilies::GetInstance(); + families->AddBenchmark(std::move(bench_ptr)); + return bench; +} + +// FIXME: This function is a hack so that benchmark.cc can access +// `BenchmarkFamilies` +bool FindBenchmarksInternal(const std::string& re, + std::vector* benchmarks, + std::ostream* Err) { + return BenchmarkFamilies::GetInstance()->FindBenchmarks(re, benchmarks, Err); +} + +//=============================================================================// +// Benchmark +//=============================================================================// + +Benchmark::Benchmark(const std::string& name) + : name_(name), + aggregation_report_mode_(ARM_Unspecified), + time_unit_(GetDefaultTimeUnit()), + use_default_time_unit_(true), + range_multiplier_(kRangeMultiplier), + min_time_(0), + min_warmup_time_(0), + iterations_(0), + repetitions_(0), + measure_process_cpu_time_(false), + use_real_time_(false), + use_manual_time_(false), + complexity_(oNone), + complexity_lambda_(nullptr), + setup_(nullptr), + teardown_(nullptr) { + ComputeStatistics("mean", StatisticsMean); + ComputeStatistics("median", StatisticsMedian); + ComputeStatistics("stddev", StatisticsStdDev); + ComputeStatistics("cv", StatisticsCV, kPercentage); +} + +Benchmark::~Benchmark() {} + +Benchmark* Benchmark::Name(const std::string& name) { + SetName(name); + return this; +} + +Benchmark* Benchmark::Arg(int64_t x) { + BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); + args_.push_back({x}); + return this; +} + +Benchmark* Benchmark::Unit(TimeUnit unit) { + time_unit_ = unit; + use_default_time_unit_ = false; + return this; +} + +Benchmark* Benchmark::Range(int64_t start, int64_t limit) { + BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); + std::vector arglist; + AddRange(&arglist, start, limit, range_multiplier_); + + for (int64_t i : arglist) { + args_.push_back({i}); + } + return this; +} + +Benchmark* Benchmark::Ranges( + const std::vector>& ranges) { + BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(ranges.size())); + std::vector> arglists(ranges.size()); + for (std::size_t i = 0; i < ranges.size(); i++) { + AddRange(&arglists[i], ranges[i].first, ranges[i].second, + range_multiplier_); + } + + ArgsProduct(arglists); + + return this; +} + +Benchmark* Benchmark::ArgsProduct( + const std::vector>& arglists) { + BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(arglists.size())); + + std::vector indices(arglists.size()); + const std::size_t total = std::accumulate( + std::begin(arglists), std::end(arglists), std::size_t{1}, + [](const std::size_t res, const std::vector& arglist) { + return res * arglist.size(); + }); + std::vector args; + args.reserve(arglists.size()); + for (std::size_t i = 0; i < total; i++) { + for (std::size_t arg = 0; arg < arglists.size(); arg++) { + args.push_back(arglists[arg][indices[arg]]); + } + args_.push_back(args); + args.clear(); + + std::size_t arg = 0; + do { + indices[arg] = (indices[arg] + 1) % arglists[arg].size(); + } while (indices[arg++] == 0 && arg < arglists.size()); + } + + return this; +} + +Benchmark* Benchmark::ArgName(const std::string& name) { + BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); + arg_names_ = {name}; + return this; +} + +Benchmark* Benchmark::ArgNames(const std::vector& names) { + BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(names.size())); + arg_names_ = names; + return this; +} + +Benchmark* Benchmark::DenseRange(int64_t start, int64_t limit, int step) { + BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); + BM_CHECK_LE(start, limit); + for (int64_t arg = start; arg <= limit; arg += step) { + args_.push_back({arg}); + } + return this; +} + +Benchmark* Benchmark::Args(const std::vector& args) { + BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(args.size())); + args_.push_back(args); + return this; +} + +Benchmark* Benchmark::Apply(void (*custom_arguments)(Benchmark* benchmark)) { + custom_arguments(this); + return this; +} + +Benchmark* Benchmark::Setup(void (*setup)(const benchmark::State&)) { + BM_CHECK(setup != nullptr); + setup_ = setup; + return this; +} + +Benchmark* Benchmark::Teardown(void (*teardown)(const benchmark::State&)) { + BM_CHECK(teardown != nullptr); + teardown_ = teardown; + return this; +} + +Benchmark* Benchmark::RangeMultiplier(int multiplier) { + BM_CHECK(multiplier > 1); + range_multiplier_ = multiplier; + return this; +} + +Benchmark* Benchmark::MinTime(double t) { + BM_CHECK(t > 0.0); + BM_CHECK(iterations_ == 0); + min_time_ = t; + return this; +} + +Benchmark* Benchmark::MinWarmUpTime(double t) { + BM_CHECK(t >= 0.0); + BM_CHECK(iterations_ == 0); + min_warmup_time_ = t; + return this; +} + +Benchmark* Benchmark::Iterations(IterationCount n) { + BM_CHECK(n > 0); + BM_CHECK(IsZero(min_time_)); + BM_CHECK(IsZero(min_warmup_time_)); + iterations_ = n; + return this; +} + +Benchmark* Benchmark::Repetitions(int n) { + BM_CHECK(n > 0); + repetitions_ = n; + return this; +} + +Benchmark* Benchmark::ReportAggregatesOnly(bool value) { + aggregation_report_mode_ = value ? ARM_ReportAggregatesOnly : ARM_Default; + return this; +} + +Benchmark* Benchmark::DisplayAggregatesOnly(bool value) { + // If we were called, the report mode is no longer 'unspecified', in any case. + aggregation_report_mode_ = static_cast( + aggregation_report_mode_ | ARM_Default); + + if (value) { + aggregation_report_mode_ = static_cast( + aggregation_report_mode_ | ARM_DisplayReportAggregatesOnly); + } else { + aggregation_report_mode_ = static_cast( + aggregation_report_mode_ & ~ARM_DisplayReportAggregatesOnly); + } + + return this; +} + +Benchmark* Benchmark::MeasureProcessCPUTime() { + // Can be used together with UseRealTime() / UseManualTime(). + measure_process_cpu_time_ = true; + return this; +} + +Benchmark* Benchmark::UseRealTime() { + BM_CHECK(!use_manual_time_) + << "Cannot set UseRealTime and UseManualTime simultaneously."; + use_real_time_ = true; + return this; +} + +Benchmark* Benchmark::UseManualTime() { + BM_CHECK(!use_real_time_) + << "Cannot set UseRealTime and UseManualTime simultaneously."; + use_manual_time_ = true; + return this; +} + +Benchmark* Benchmark::Complexity(BigO complexity) { + complexity_ = complexity; + return this; +} + +Benchmark* Benchmark::Complexity(BigOFunc* complexity) { + complexity_lambda_ = complexity; + complexity_ = oLambda; + return this; +} + +Benchmark* Benchmark::ComputeStatistics(const std::string& name, + StatisticsFunc* statistics, + StatisticUnit unit) { + statistics_.emplace_back(name, statistics, unit); + return this; +} + +Benchmark* Benchmark::Threads(int t) { + BM_CHECK_GT(t, 0); + thread_counts_.push_back(t); + return this; +} + +Benchmark* Benchmark::ThreadRange(int min_threads, int max_threads) { + BM_CHECK_GT(min_threads, 0); + BM_CHECK_GE(max_threads, min_threads); + + AddRange(&thread_counts_, min_threads, max_threads, 2); + return this; +} + +Benchmark* Benchmark::DenseThreadRange(int min_threads, int max_threads, + int stride) { + BM_CHECK_GT(min_threads, 0); + BM_CHECK_GE(max_threads, min_threads); + BM_CHECK_GE(stride, 1); + + for (auto i = min_threads; i < max_threads; i += stride) { + thread_counts_.push_back(i); + } + thread_counts_.push_back(max_threads); + return this; +} + +Benchmark* Benchmark::ThreadPerCpu() { + thread_counts_.push_back(CPUInfo::Get().num_cpus); + return this; +} + +void Benchmark::SetName(const std::string& name) { name_ = name; } + +const char* Benchmark::GetName() const { return name_.c_str(); } + +int Benchmark::ArgsCnt() const { + if (args_.empty()) { + if (arg_names_.empty()) return -1; + return static_cast(arg_names_.size()); + } + return static_cast(args_.front().size()); +} + +const char* Benchmark::GetArgName(int arg) const { + BM_CHECK_GE(arg, 0); + size_t uarg = static_cast(arg); + BM_CHECK_LT(uarg, arg_names_.size()); + return arg_names_[uarg].c_str(); +} + +TimeUnit Benchmark::GetTimeUnit() const { + return use_default_time_unit_ ? GetDefaultTimeUnit() : time_unit_; +} + +//=============================================================================// +// FunctionBenchmark +//=============================================================================// + +void FunctionBenchmark::Run(State& st) { func_(st); } + +} // end namespace internal + +void ClearRegisteredBenchmarks() { + internal::BenchmarkFamilies::GetInstance()->ClearBenchmarks(); +} + +std::vector CreateRange(int64_t lo, int64_t hi, int multi) { + std::vector args; + internal::AddRange(&args, lo, hi, multi); + return args; +} + +std::vector CreateDenseRange(int64_t start, int64_t limit, int step) { + BM_CHECK_LE(start, limit); + std::vector args; + for (int64_t arg = start; arg <= limit; arg += step) { + args.push_back(arg); + } + return args; +} + +} // end namespace benchmark diff --git a/third_party/benchmark/src/benchmark_register.h b/third_party/benchmark/src/benchmark_register.h new file mode 100644 index 0000000..be50265 --- /dev/null +++ b/third_party/benchmark/src/benchmark_register.h @@ -0,0 +1,109 @@ +#ifndef BENCHMARK_REGISTER_H +#define BENCHMARK_REGISTER_H + +#include +#include +#include + +#include "check.h" + +namespace benchmark { +namespace internal { + +// Append the powers of 'mult' in the closed interval [lo, hi]. +// Returns iterator to the start of the inserted range. +template +typename std::vector::iterator AddPowers(std::vector* dst, T lo, T hi, + int mult) { + BM_CHECK_GE(lo, 0); + BM_CHECK_GE(hi, lo); + BM_CHECK_GE(mult, 2); + + const size_t start_offset = dst->size(); + + static const T kmax = std::numeric_limits::max(); + + // Space out the values in multiples of "mult" + for (T i = static_cast(1); i <= hi; i = static_cast(i * mult)) { + if (i >= lo) { + dst->push_back(i); + } + // Break the loop here since multiplying by + // 'mult' would move outside of the range of T + if (i > kmax / mult) break; + } + + return dst->begin() + static_cast(start_offset); +} + +template +void AddNegatedPowers(std::vector* dst, T lo, T hi, int mult) { + // We negate lo and hi so we require that they cannot be equal to 'min'. + BM_CHECK_GT(lo, std::numeric_limits::min()); + BM_CHECK_GT(hi, std::numeric_limits::min()); + BM_CHECK_GE(hi, lo); + BM_CHECK_LE(hi, 0); + + // Add positive powers, then negate and reverse. + // Casts necessary since small integers get promoted + // to 'int' when negating. + const auto lo_complement = static_cast(-lo); + const auto hi_complement = static_cast(-hi); + + const auto it = AddPowers(dst, hi_complement, lo_complement, mult); + + std::for_each(it, dst->end(), [](T& t) { t = static_cast(t * -1); }); + std::reverse(it, dst->end()); +} + +template +void AddRange(std::vector* dst, T lo, T hi, int mult) { + static_assert(std::is_integral::value && std::is_signed::value, + "Args type must be a signed integer"); + + BM_CHECK_GE(hi, lo); + BM_CHECK_GE(mult, 2); + + // Add "lo" + dst->push_back(lo); + + // Handle lo == hi as a special case, so we then know + // lo < hi and so it is safe to add 1 to lo and subtract 1 + // from hi without falling outside of the range of T. + if (lo == hi) return; + + // Ensure that lo_inner <= hi_inner below. + if (lo + 1 == hi) { + dst->push_back(hi); + return; + } + + // Add all powers of 'mult' in the range [lo+1, hi-1] (inclusive). + const auto lo_inner = static_cast(lo + 1); + const auto hi_inner = static_cast(hi - 1); + + // Insert negative values + if (lo_inner < 0) { + AddNegatedPowers(dst, lo_inner, std::min(hi_inner, T{-1}), mult); + } + + // Treat 0 as a special case (see discussion on #762). + if (lo < 0 && hi >= 0) { + dst->push_back(0); + } + + // Insert positive values + if (hi_inner > 0) { + AddPowers(dst, std::max(lo_inner, T{1}), hi_inner, mult); + } + + // Add "hi" (if different from last value). + if (hi != dst->back()) { + dst->push_back(hi); + } +} + +} // namespace internal +} // namespace benchmark + +#endif // BENCHMARK_REGISTER_H diff --git a/third_party/benchmark/src/benchmark_runner.cc b/third_party/benchmark/src/benchmark_runner.cc new file mode 100644 index 0000000..a74bdad --- /dev/null +++ b/third_party/benchmark/src/benchmark_runner.cc @@ -0,0 +1,498 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 "benchmark_runner.h" + +#include "benchmark/benchmark.h" +#include "benchmark_api_internal.h" +#include "internal_macros.h" + +#ifndef BENCHMARK_OS_WINDOWS +#if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT) +#include +#endif +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "check.h" +#include "colorprint.h" +#include "commandlineflags.h" +#include "complexity.h" +#include "counter.h" +#include "internal_macros.h" +#include "log.h" +#include "mutex.h" +#include "perf_counters.h" +#include "re.h" +#include "statistics.h" +#include "string_util.h" +#include "thread_manager.h" +#include "thread_timer.h" + +namespace benchmark { + +namespace internal { + +MemoryManager* memory_manager = nullptr; + +namespace { + +static constexpr IterationCount kMaxIterations = 1000000000000; +const double kDefaultMinTime = + std::strtod(::benchmark::kDefaultMinTimeStr, /*p_end*/ nullptr); + +BenchmarkReporter::Run CreateRunReport( + const benchmark::internal::BenchmarkInstance& b, + const internal::ThreadManager::Result& results, + IterationCount memory_iterations, + const MemoryManager::Result* memory_result, double seconds, + int64_t repetition_index, int64_t repeats) { + // Create report about this benchmark run. + BenchmarkReporter::Run report; + + report.run_name = b.name(); + report.family_index = b.family_index(); + report.per_family_instance_index = b.per_family_instance_index(); + report.skipped = results.skipped_; + report.skip_message = results.skip_message_; + report.report_label = results.report_label_; + // This is the total iterations across all threads. + report.iterations = results.iterations; + report.time_unit = b.time_unit(); + report.threads = b.threads(); + report.repetition_index = repetition_index; + report.repetitions = repeats; + + if (!report.skipped) { + if (b.use_manual_time()) { + report.real_accumulated_time = results.manual_time_used; + } else { + report.real_accumulated_time = results.real_time_used; + } + report.use_real_time_for_initial_big_o = b.use_manual_time(); + report.cpu_accumulated_time = results.cpu_time_used; + report.complexity_n = results.complexity_n; + report.complexity = b.complexity(); + report.complexity_lambda = b.complexity_lambda(); + report.statistics = &b.statistics(); + report.counters = results.counters; + + if (memory_iterations > 0) { + assert(memory_result != nullptr); + report.memory_result = memory_result; + report.allocs_per_iter = + memory_iterations ? static_cast(memory_result->num_allocs) / + static_cast(memory_iterations) + : 0; + } + + internal::Finish(&report.counters, results.iterations, seconds, + b.threads()); + } + return report; +} + +// Execute one thread of benchmark b for the specified number of iterations. +// Adds the stats collected for the thread into manager->results. +void RunInThread(const BenchmarkInstance* b, IterationCount iters, + int thread_id, ThreadManager* manager, + PerfCountersMeasurement* perf_counters_measurement) { + internal::ThreadTimer timer( + b->measure_process_cpu_time() + ? internal::ThreadTimer::CreateProcessCpuTime() + : internal::ThreadTimer::Create()); + + State st = + b->Run(iters, thread_id, &timer, manager, perf_counters_measurement); + BM_CHECK(st.skipped() || st.iterations() >= st.max_iterations) + << "Benchmark returned before State::KeepRunning() returned false!"; + { + MutexLock l(manager->GetBenchmarkMutex()); + internal::ThreadManager::Result& results = manager->results; + results.iterations += st.iterations(); + results.cpu_time_used += timer.cpu_time_used(); + results.real_time_used += timer.real_time_used(); + results.manual_time_used += timer.manual_time_used(); + results.complexity_n += st.complexity_length_n(); + internal::Increment(&results.counters, st.counters); + } + manager->NotifyThreadComplete(); +} + +double ComputeMinTime(const benchmark::internal::BenchmarkInstance& b, + const BenchTimeType& iters_or_time) { + if (!IsZero(b.min_time())) return b.min_time(); + // If the flag was used to specify number of iters, then return the default + // min_time. + if (iters_or_time.tag == BenchTimeType::ITERS) return kDefaultMinTime; + + return iters_or_time.time; +} + +IterationCount ComputeIters(const benchmark::internal::BenchmarkInstance& b, + const BenchTimeType& iters_or_time) { + if (b.iterations() != 0) return b.iterations(); + + // We've already concluded that this flag is currently used to pass + // iters but do a check here again anyway. + BM_CHECK(iters_or_time.tag == BenchTimeType::ITERS); + return iters_or_time.iters; +} + +} // end namespace + +BenchTimeType ParseBenchMinTime(const std::string& value) { + BenchTimeType ret; + + if (value.empty()) { + ret.tag = BenchTimeType::TIME; + ret.time = 0.0; + return ret; + } + + if (value.back() == 'x') { + char* p_end; + // Reset errno before it's changed by strtol. + errno = 0; + IterationCount num_iters = std::strtol(value.c_str(), &p_end, 10); + + // After a valid parse, p_end should have been set to + // point to the 'x' suffix. + BM_CHECK(errno == 0 && p_end != nullptr && *p_end == 'x') + << "Malformed iters value passed to --benchmark_min_time: `" << value + << "`. Expected --benchmark_min_time=x."; + + ret.tag = BenchTimeType::ITERS; + ret.iters = num_iters; + return ret; + } + + bool has_suffix = value.back() == 's'; + if (!has_suffix) { + BM_VLOG(0) << "Value passed to --benchmark_min_time should have a suffix. " + "Eg., `30s` for 30-seconds."; + } + + char* p_end; + // Reset errno before it's changed by strtod. + errno = 0; + double min_time = std::strtod(value.c_str(), &p_end); + + // After a successful parse, p_end should point to the suffix 's', + // or the end of the string if the suffix was omitted. + BM_CHECK(errno == 0 && p_end != nullptr && + ((has_suffix && *p_end == 's') || *p_end == '\0')) + << "Malformed seconds value passed to --benchmark_min_time: `" << value + << "`. Expected --benchmark_min_time=x."; + + ret.tag = BenchTimeType::TIME; + ret.time = min_time; + + return ret; +} + +BenchmarkRunner::BenchmarkRunner( + const benchmark::internal::BenchmarkInstance& b_, + PerfCountersMeasurement* pcm_, + BenchmarkReporter::PerFamilyRunReports* reports_for_family_) + : b(b_), + reports_for_family(reports_for_family_), + parsed_benchtime_flag(ParseBenchMinTime(FLAGS_benchmark_min_time)), + min_time(ComputeMinTime(b_, parsed_benchtime_flag)), + min_warmup_time((!IsZero(b.min_time()) && b.min_warmup_time() > 0.0) + ? b.min_warmup_time() + : FLAGS_benchmark_min_warmup_time), + warmup_done(!(min_warmup_time > 0.0)), + repeats(b.repetitions() != 0 ? b.repetitions() + : FLAGS_benchmark_repetitions), + has_explicit_iteration_count(b.iterations() != 0 || + parsed_benchtime_flag.tag == + BenchTimeType::ITERS), + pool(static_cast(b.threads() - 1)), + iters(has_explicit_iteration_count + ? ComputeIters(b_, parsed_benchtime_flag) + : 1), + perf_counters_measurement_ptr(pcm_) { + run_results.display_report_aggregates_only = + (FLAGS_benchmark_report_aggregates_only || + FLAGS_benchmark_display_aggregates_only); + run_results.file_report_aggregates_only = + FLAGS_benchmark_report_aggregates_only; + if (b.aggregation_report_mode() != internal::ARM_Unspecified) { + run_results.display_report_aggregates_only = + (b.aggregation_report_mode() & + internal::ARM_DisplayReportAggregatesOnly); + run_results.file_report_aggregates_only = + (b.aggregation_report_mode() & internal::ARM_FileReportAggregatesOnly); + BM_CHECK(FLAGS_benchmark_perf_counters.empty() || + (perf_counters_measurement_ptr->num_counters() == 0)) + << "Perf counters were requested but could not be set up."; + } +} + +BenchmarkRunner::IterationResults BenchmarkRunner::DoNIterations() { + BM_VLOG(2) << "Running " << b.name().str() << " for " << iters << "\n"; + + std::unique_ptr manager; + manager.reset(new internal::ThreadManager(b.threads())); + + // Run all but one thread in separate threads + for (std::size_t ti = 0; ti < pool.size(); ++ti) { + pool[ti] = std::thread(&RunInThread, &b, iters, static_cast(ti + 1), + manager.get(), perf_counters_measurement_ptr); + } + // And run one thread here directly. + // (If we were asked to run just one thread, we don't create new threads.) + // Yes, we need to do this here *after* we start the separate threads. + RunInThread(&b, iters, 0, manager.get(), perf_counters_measurement_ptr); + + // The main thread has finished. Now let's wait for the other threads. + manager->WaitForAllThreads(); + for (std::thread& thread : pool) thread.join(); + + IterationResults i; + // Acquire the measurements/counters from the manager, UNDER THE LOCK! + { + MutexLock l(manager->GetBenchmarkMutex()); + i.results = manager->results; + } + + // And get rid of the manager. + manager.reset(); + + // Adjust real/manual time stats since they were reported per thread. + i.results.real_time_used /= b.threads(); + i.results.manual_time_used /= b.threads(); + // If we were measuring whole-process CPU usage, adjust the CPU time too. + if (b.measure_process_cpu_time()) i.results.cpu_time_used /= b.threads(); + + BM_VLOG(2) << "Ran in " << i.results.cpu_time_used << "/" + << i.results.real_time_used << "\n"; + + // By using KeepRunningBatch a benchmark can iterate more times than + // requested, so take the iteration count from i.results. + i.iters = i.results.iterations / b.threads(); + + // Base decisions off of real time if requested by this benchmark. + i.seconds = i.results.cpu_time_used; + if (b.use_manual_time()) { + i.seconds = i.results.manual_time_used; + } else if (b.use_real_time()) { + i.seconds = i.results.real_time_used; + } + + return i; +} + +IterationCount BenchmarkRunner::PredictNumItersNeeded( + const IterationResults& i) const { + // See how much iterations should be increased by. + // Note: Avoid division by zero with max(seconds, 1ns). + double multiplier = GetMinTimeToApply() * 1.4 / std::max(i.seconds, 1e-9); + // If our last run was at least 10% of FLAGS_benchmark_min_time then we + // use the multiplier directly. + // Otherwise we use at most 10 times expansion. + // NOTE: When the last run was at least 10% of the min time the max + // expansion should be 14x. + const bool is_significant = (i.seconds / GetMinTimeToApply()) > 0.1; + multiplier = is_significant ? multiplier : 10.0; + + // So what seems to be the sufficiently-large iteration count? Round up. + const IterationCount max_next_iters = static_cast( + std::llround(std::max(multiplier * static_cast(i.iters), + static_cast(i.iters) + 1.0))); + // But we do have *some* limits though.. + const IterationCount next_iters = std::min(max_next_iters, kMaxIterations); + + BM_VLOG(3) << "Next iters: " << next_iters << ", " << multiplier << "\n"; + return next_iters; // round up before conversion to integer. +} + +bool BenchmarkRunner::ShouldReportIterationResults( + const IterationResults& i) const { + // Determine if this run should be reported; + // Either it has run for a sufficient amount of time + // or because an error was reported. + return i.results.skipped_ || + i.iters >= kMaxIterations || // Too many iterations already. + i.seconds >= + GetMinTimeToApply() || // The elapsed time is large enough. + // CPU time is specified but the elapsed real time greatly exceeds + // the minimum time. + // Note that user provided timers are except from this test. + ((i.results.real_time_used >= 5 * GetMinTimeToApply()) && + !b.use_manual_time()); +} + +double BenchmarkRunner::GetMinTimeToApply() const { + // In order to re-use functionality to run and measure benchmarks for running + // a warmup phase of the benchmark, we need a way of telling whether to apply + // min_time or min_warmup_time. This function will figure out if we are in the + // warmup phase and therefore need to apply min_warmup_time or if we already + // in the benchmarking phase and min_time needs to be applied. + return warmup_done ? min_time : min_warmup_time; +} + +void BenchmarkRunner::FinishWarmUp(const IterationCount& i) { + warmup_done = true; + iters = i; +} + +void BenchmarkRunner::RunWarmUp() { + // Use the same mechanisms for warming up the benchmark as used for actually + // running and measuring the benchmark. + IterationResults i_warmup; + // Dont use the iterations determined in the warmup phase for the actual + // measured benchmark phase. While this may be a good starting point for the + // benchmark and it would therefore get rid of the need to figure out how many + // iterations are needed if min_time is set again, this may also be a complete + // wrong guess since the warmup loops might be considerably slower (e.g + // because of caching effects). + const IterationCount i_backup = iters; + + for (;;) { + b.Setup(); + i_warmup = DoNIterations(); + b.Teardown(); + + const bool finish = ShouldReportIterationResults(i_warmup); + + if (finish) { + FinishWarmUp(i_backup); + break; + } + + // Although we are running "only" a warmup phase where running enough + // iterations at once without measuring time isn't as important as it is for + // the benchmarking phase, we still do it the same way as otherwise it is + // very confusing for the user to know how to choose a proper value for + // min_warmup_time if a different approach on running it is used. + iters = PredictNumItersNeeded(i_warmup); + assert(iters > i_warmup.iters && + "if we did more iterations than we want to do the next time, " + "then we should have accepted the current iteration run."); + } +} + +void BenchmarkRunner::DoOneRepetition() { + assert(HasRepeatsRemaining() && "Already done all repetitions?"); + + const bool is_the_first_repetition = num_repetitions_done == 0; + + // In case a warmup phase is requested by the benchmark, run it now. + // After running the warmup phase the BenchmarkRunner should be in a state as + // this warmup never happened except the fact that warmup_done is set. Every + // other manipulation of the BenchmarkRunner instance would be a bug! Please + // fix it. + if (!warmup_done) RunWarmUp(); + + IterationResults i; + // We *may* be gradually increasing the length (iteration count) + // of the benchmark until we decide the results are significant. + // And once we do, we report those last results and exit. + // Please do note that the if there are repetitions, the iteration count + // is *only* calculated for the *first* repetition, and other repetitions + // simply use that precomputed iteration count. + for (;;) { + b.Setup(); + i = DoNIterations(); + b.Teardown(); + + // Do we consider the results to be significant? + // If we are doing repetitions, and the first repetition was already done, + // it has calculated the correct iteration time, so we have run that very + // iteration count just now. No need to calculate anything. Just report. + // Else, the normal rules apply. + const bool results_are_significant = !is_the_first_repetition || + has_explicit_iteration_count || + ShouldReportIterationResults(i); + + if (results_are_significant) break; // Good, let's report them! + + // Nope, bad iteration. Let's re-estimate the hopefully-sufficient + // iteration count, and run the benchmark again... + + iters = PredictNumItersNeeded(i); + assert(iters > i.iters && + "if we did more iterations than we want to do the next time, " + "then we should have accepted the current iteration run."); + } + + // Oh, one last thing, we need to also produce the 'memory measurements'.. + MemoryManager::Result* memory_result = nullptr; + IterationCount memory_iterations = 0; + if (memory_manager != nullptr) { + // TODO(vyng): Consider making BenchmarkReporter::Run::memory_result an + // optional so we don't have to own the Result here. + // Can't do it now due to cxx03. + memory_results.push_back(MemoryManager::Result()); + memory_result = &memory_results.back(); + // Only run a few iterations to reduce the impact of one-time + // allocations in benchmarks that are not properly managed. + memory_iterations = std::min(16, iters); + memory_manager->Start(); + std::unique_ptr manager; + manager.reset(new internal::ThreadManager(1)); + b.Setup(); + RunInThread(&b, memory_iterations, 0, manager.get(), + perf_counters_measurement_ptr); + manager->WaitForAllThreads(); + manager.reset(); + b.Teardown(); + memory_manager->Stop(*memory_result); + } + + // Ok, now actually report. + BenchmarkReporter::Run report = + CreateRunReport(b, i.results, memory_iterations, memory_result, i.seconds, + num_repetitions_done, repeats); + + if (reports_for_family) { + ++reports_for_family->num_runs_done; + if (!report.skipped) reports_for_family->Runs.push_back(report); + } + + run_results.non_aggregates.push_back(report); + + ++num_repetitions_done; +} + +RunResults&& BenchmarkRunner::GetResults() { + assert(!HasRepeatsRemaining() && "Did not run all repetitions yet?"); + + // Calculate additional statistics over the repetitions of this instance. + run_results.aggregates_only = ComputeStats(run_results.non_aggregates); + + return std::move(run_results); +} + +} // end namespace internal + +} // end namespace benchmark diff --git a/third_party/benchmark/src/benchmark_runner.h b/third_party/benchmark/src/benchmark_runner.h new file mode 100644 index 0000000..db2fa04 --- /dev/null +++ b/third_party/benchmark/src/benchmark_runner.h @@ -0,0 +1,131 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 BENCHMARK_RUNNER_H_ +#define BENCHMARK_RUNNER_H_ + +#include +#include + +#include "benchmark_api_internal.h" +#include "internal_macros.h" +#include "perf_counters.h" +#include "thread_manager.h" + +namespace benchmark { + +BM_DECLARE_string(benchmark_min_time); +BM_DECLARE_double(benchmark_min_warmup_time); +BM_DECLARE_int32(benchmark_repetitions); +BM_DECLARE_bool(benchmark_report_aggregates_only); +BM_DECLARE_bool(benchmark_display_aggregates_only); +BM_DECLARE_string(benchmark_perf_counters); + +namespace internal { + +extern MemoryManager* memory_manager; + +struct RunResults { + std::vector non_aggregates; + std::vector aggregates_only; + + bool display_report_aggregates_only = false; + bool file_report_aggregates_only = false; +}; + +struct BENCHMARK_EXPORT BenchTimeType { + enum { ITERS, TIME } tag; + union { + IterationCount iters; + double time; + }; +}; + +BENCHMARK_EXPORT +BenchTimeType ParseBenchMinTime(const std::string& value); + +class BenchmarkRunner { + public: + BenchmarkRunner(const benchmark::internal::BenchmarkInstance& b_, + benchmark::internal::PerfCountersMeasurement* pmc_, + BenchmarkReporter::PerFamilyRunReports* reports_for_family); + + int GetNumRepeats() const { return repeats; } + + bool HasRepeatsRemaining() const { + return GetNumRepeats() != num_repetitions_done; + } + + void DoOneRepetition(); + + RunResults&& GetResults(); + + BenchmarkReporter::PerFamilyRunReports* GetReportsForFamily() const { + return reports_for_family; + } + + double GetMinTime() const { return min_time; } + + bool HasExplicitIters() const { return has_explicit_iteration_count; } + + IterationCount GetIters() const { return iters; } + + private: + RunResults run_results; + + const benchmark::internal::BenchmarkInstance& b; + BenchmarkReporter::PerFamilyRunReports* reports_for_family; + + BenchTimeType parsed_benchtime_flag; + const double min_time; + const double min_warmup_time; + bool warmup_done; + const int repeats; + const bool has_explicit_iteration_count; + + int num_repetitions_done = 0; + + std::vector pool; + + std::vector memory_results; + + IterationCount iters; // preserved between repetitions! + // So only the first repetition has to find/calculate it, + // the other repetitions will just use that precomputed iteration count. + + PerfCountersMeasurement* const perf_counters_measurement_ptr = nullptr; + + struct IterationResults { + internal::ThreadManager::Result results; + IterationCount iters; + double seconds; + }; + IterationResults DoNIterations(); + + IterationCount PredictNumItersNeeded(const IterationResults& i) const; + + bool ShouldReportIterationResults(const IterationResults& i) const; + + double GetMinTimeToApply() const; + + void FinishWarmUp(const IterationCount& i); + + void RunWarmUp(); +}; + +} // namespace internal + +} // end namespace benchmark + +#endif // BENCHMARK_RUNNER_H_ diff --git a/third_party/benchmark/src/check.cc b/third_party/benchmark/src/check.cc new file mode 100644 index 0000000..5f7526e --- /dev/null +++ b/third_party/benchmark/src/check.cc @@ -0,0 +1,11 @@ +#include "check.h" + +namespace benchmark { +namespace internal { + +static AbortHandlerT* handler = &std::abort; + +BENCHMARK_EXPORT AbortHandlerT*& GetAbortHandler() { return handler; } + +} // namespace internal +} // namespace benchmark diff --git a/third_party/benchmark/src/check.h b/third_party/benchmark/src/check.h new file mode 100644 index 0000000..c1cd5e8 --- /dev/null +++ b/third_party/benchmark/src/check.h @@ -0,0 +1,106 @@ +#ifndef CHECK_H_ +#define CHECK_H_ + +#include +#include +#include + +#include "benchmark/export.h" +#include "internal_macros.h" +#include "log.h" + +#if defined(__GNUC__) || defined(__clang__) +#define BENCHMARK_NOEXCEPT noexcept +#define BENCHMARK_NOEXCEPT_OP(x) noexcept(x) +#elif defined(_MSC_VER) && !defined(__clang__) +#if _MSC_VER >= 1900 +#define BENCHMARK_NOEXCEPT noexcept +#define BENCHMARK_NOEXCEPT_OP(x) noexcept(x) +#else +#define BENCHMARK_NOEXCEPT +#define BENCHMARK_NOEXCEPT_OP(x) +#endif +#define __func__ __FUNCTION__ +#else +#define BENCHMARK_NOEXCEPT +#define BENCHMARK_NOEXCEPT_OP(x) +#endif + +namespace benchmark { +namespace internal { + +typedef void(AbortHandlerT)(); + +BENCHMARK_EXPORT +AbortHandlerT*& GetAbortHandler(); + +BENCHMARK_NORETURN inline void CallAbortHandler() { + GetAbortHandler()(); + std::abort(); // fallback to enforce noreturn +} + +// CheckHandler is the class constructed by failing BM_CHECK macros. +// CheckHandler will log information about the failures and abort when it is +// destructed. +class CheckHandler { + public: + CheckHandler(const char* check, const char* file, const char* func, int line) + : log_(GetErrorLogInstance()) { + log_ << file << ":" << line << ": " << func << ": Check `" << check + << "' failed. "; + } + + LogType& GetLog() { return log_; } + +#if defined(COMPILER_MSVC) +#pragma warning(push) +#pragma warning(disable : 4722) +#endif + BENCHMARK_NORETURN ~CheckHandler() BENCHMARK_NOEXCEPT_OP(false) { + log_ << std::endl; + CallAbortHandler(); + } +#if defined(COMPILER_MSVC) +#pragma warning(pop) +#endif + + CheckHandler& operator=(const CheckHandler&) = delete; + CheckHandler(const CheckHandler&) = delete; + CheckHandler() = delete; + + private: + LogType& log_; +}; + +} // end namespace internal +} // end namespace benchmark + +// The BM_CHECK macro returns a std::ostream object that can have extra +// information written to it. +#ifndef NDEBUG +#define BM_CHECK(b) \ + (b ? ::benchmark::internal::GetNullLogInstance() \ + : ::benchmark::internal::CheckHandler(#b, __FILE__, __func__, __LINE__) \ + .GetLog()) +#else +#define BM_CHECK(b) ::benchmark::internal::GetNullLogInstance() +#endif + +// clang-format off +// preserve whitespacing between operators for alignment +#define BM_CHECK_EQ(a, b) BM_CHECK((a) == (b)) +#define BM_CHECK_NE(a, b) BM_CHECK((a) != (b)) +#define BM_CHECK_GE(a, b) BM_CHECK((a) >= (b)) +#define BM_CHECK_LE(a, b) BM_CHECK((a) <= (b)) +#define BM_CHECK_GT(a, b) BM_CHECK((a) > (b)) +#define BM_CHECK_LT(a, b) BM_CHECK((a) < (b)) + +#define BM_CHECK_FLOAT_EQ(a, b, eps) BM_CHECK(std::fabs((a) - (b)) < (eps)) +#define BM_CHECK_FLOAT_NE(a, b, eps) BM_CHECK(std::fabs((a) - (b)) >= (eps)) +#define BM_CHECK_FLOAT_GE(a, b, eps) BM_CHECK((a) - (b) > -(eps)) +#define BM_CHECK_FLOAT_LE(a, b, eps) BM_CHECK((b) - (a) > -(eps)) +#define BM_CHECK_FLOAT_GT(a, b, eps) BM_CHECK((a) - (b) > (eps)) +#define BM_CHECK_FLOAT_LT(a, b, eps) BM_CHECK((b) - (a) > (eps)) +//clang-format on + +#endif // CHECK_H_ diff --git a/third_party/benchmark/src/colorprint.cc b/third_party/benchmark/src/colorprint.cc new file mode 100644 index 0000000..abc7149 --- /dev/null +++ b/third_party/benchmark/src/colorprint.cc @@ -0,0 +1,200 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 "colorprint.h" + +#include +#include +#include +#include +#include +#include + +#include "check.h" +#include "internal_macros.h" + +#ifdef BENCHMARK_OS_WINDOWS +#include +#include +#else +#include +#endif // BENCHMARK_OS_WINDOWS + +namespace benchmark { +namespace { +#ifdef BENCHMARK_OS_WINDOWS +typedef WORD PlatformColorCode; +#else +typedef const char* PlatformColorCode; +#endif + +PlatformColorCode GetPlatformColorCode(LogColor color) { +#ifdef BENCHMARK_OS_WINDOWS + switch (color) { + case COLOR_RED: + return FOREGROUND_RED; + case COLOR_GREEN: + return FOREGROUND_GREEN; + case COLOR_YELLOW: + return FOREGROUND_RED | FOREGROUND_GREEN; + case COLOR_BLUE: + return FOREGROUND_BLUE; + case COLOR_MAGENTA: + return FOREGROUND_BLUE | FOREGROUND_RED; + case COLOR_CYAN: + return FOREGROUND_BLUE | FOREGROUND_GREEN; + case COLOR_WHITE: // fall through to default + default: + return 0; + } +#else + switch (color) { + case COLOR_RED: + return "1"; + case COLOR_GREEN: + return "2"; + case COLOR_YELLOW: + return "3"; + case COLOR_BLUE: + return "4"; + case COLOR_MAGENTA: + return "5"; + case COLOR_CYAN: + return "6"; + case COLOR_WHITE: + return "7"; + default: + return nullptr; + }; +#endif +} + +} // end namespace + +std::string FormatString(const char* msg, va_list args) { + // we might need a second shot at this, so pre-emptivly make a copy + va_list args_cp; + va_copy(args_cp, args); + + std::size_t size = 256; + char local_buff[256]; + auto ret = vsnprintf(local_buff, size, msg, args_cp); + + va_end(args_cp); + + // currently there is no error handling for failure, so this is hack. + BM_CHECK(ret >= 0); + + if (ret == 0) { // handle empty expansion + return {}; + } + if (static_cast(ret) < size) { + return local_buff; + } + // we did not provide a long enough buffer on our first attempt. + size = static_cast(ret) + 1; // + 1 for the null byte + std::unique_ptr buff(new char[size]); + ret = vsnprintf(buff.get(), size, msg, args); + BM_CHECK(ret > 0 && (static_cast(ret)) < size); + return buff.get(); +} + +std::string FormatString(const char* msg, ...) { + va_list args; + va_start(args, msg); + auto tmp = FormatString(msg, args); + va_end(args); + return tmp; +} + +void ColorPrintf(std::ostream& out, LogColor color, const char* fmt, ...) { + va_list args; + va_start(args, fmt); + ColorPrintf(out, color, fmt, args); + va_end(args); +} + +void ColorPrintf(std::ostream& out, LogColor color, const char* fmt, + va_list args) { +#ifdef BENCHMARK_OS_WINDOWS + ((void)out); // suppress unused warning + + const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); + + // Gets the current text color. + CONSOLE_SCREEN_BUFFER_INFO buffer_info; + GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); + const WORD old_color_attrs = buffer_info.wAttributes; + + // We need to flush the stream buffers into the console before each + // SetConsoleTextAttribute call lest it affect the text that is already + // printed but has not yet reached the console. + out.flush(); + SetConsoleTextAttribute(stdout_handle, + GetPlatformColorCode(color) | FOREGROUND_INTENSITY); + out << FormatString(fmt, args); + + out.flush(); + // Restores the text color. + SetConsoleTextAttribute(stdout_handle, old_color_attrs); +#else + const char* color_code = GetPlatformColorCode(color); + if (color_code) out << FormatString("\033[0;3%sm", color_code); + out << FormatString(fmt, args) << "\033[m"; +#endif +} + +bool IsColorTerminal() { +#if BENCHMARK_OS_WINDOWS + // On Windows the TERM variable is usually not set, but the + // console there does support colors. + return 0 != _isatty(_fileno(stdout)); +#else + // On non-Windows platforms, we rely on the TERM variable. This list of + // supported TERM values is copied from Google Test: + // . + const char* const SUPPORTED_TERM_VALUES[] = { + "xterm", + "xterm-color", + "xterm-256color", + "screen", + "screen-256color", + "tmux", + "tmux-256color", + "rxvt-unicode", + "rxvt-unicode-256color", + "linux", + "cygwin", + "xterm-kitty", + "alacritty", + "foot", + "foot-extra", + "wezterm", + }; + + const char* const term = getenv("TERM"); + + bool term_supports_color = false; + for (const char* candidate : SUPPORTED_TERM_VALUES) { + if (term && 0 == strcmp(term, candidate)) { + term_supports_color = true; + break; + } + } + + return 0 != isatty(fileno(stdout)) && term_supports_color; +#endif // BENCHMARK_OS_WINDOWS +} + +} // end namespace benchmark diff --git a/third_party/benchmark/src/colorprint.h b/third_party/benchmark/src/colorprint.h new file mode 100644 index 0000000..9f6fab9 --- /dev/null +++ b/third_party/benchmark/src/colorprint.h @@ -0,0 +1,33 @@ +#ifndef BENCHMARK_COLORPRINT_H_ +#define BENCHMARK_COLORPRINT_H_ + +#include +#include +#include + +namespace benchmark { +enum LogColor { + COLOR_DEFAULT, + COLOR_RED, + COLOR_GREEN, + COLOR_YELLOW, + COLOR_BLUE, + COLOR_MAGENTA, + COLOR_CYAN, + COLOR_WHITE +}; + +std::string FormatString(const char* msg, va_list args); +std::string FormatString(const char* msg, ...); + +void ColorPrintf(std::ostream& out, LogColor color, const char* fmt, + va_list args); +void ColorPrintf(std::ostream& out, LogColor color, const char* fmt, ...); + +// Returns true if stdout appears to be a terminal that supports colored +// output, false otherwise. +bool IsColorTerminal(); + +} // end namespace benchmark + +#endif // BENCHMARK_COLORPRINT_H_ diff --git a/third_party/benchmark/src/commandlineflags.cc b/third_party/benchmark/src/commandlineflags.cc new file mode 100644 index 0000000..dcb4149 --- /dev/null +++ b/third_party/benchmark/src/commandlineflags.cc @@ -0,0 +1,298 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 "commandlineflags.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../src/string_util.h" + +namespace benchmark { +namespace { + +// Parses 'str' for a 32-bit signed integer. If successful, writes +// the result to *value and returns true; otherwise leaves *value +// unchanged and returns false. +bool ParseInt32(const std::string& src_text, const char* str, int32_t* value) { + // Parses the environment variable as a decimal integer. + char* end = nullptr; + const long long_value = strtol(str, &end, 10); // NOLINT + + // Has strtol() consumed all characters in the string? + if (*end != '\0') { + // No - an invalid character was encountered. + std::cerr << src_text << " is expected to be a 32-bit integer, " + << "but actually has value \"" << str << "\".\n"; + return false; + } + + // Is the parsed value in the range of an Int32? + const int32_t result = static_cast(long_value); + if (long_value == std::numeric_limits::max() || + long_value == std::numeric_limits::min() || + // The parsed value overflows as a long. (strtol() returns + // LONG_MAX or LONG_MIN when the input overflows.) + result != long_value + // The parsed value overflows as an Int32. + ) { + std::cerr << src_text << " is expected to be a 32-bit integer, " + << "but actually has value \"" << str << "\", " + << "which overflows.\n"; + return false; + } + + *value = result; + return true; +} + +// Parses 'str' for a double. If successful, writes the result to *value and +// returns true; otherwise leaves *value unchanged and returns false. +bool ParseDouble(const std::string& src_text, const char* str, double* value) { + // Parses the environment variable as a decimal integer. + char* end = nullptr; + const double double_value = strtod(str, &end); // NOLINT + + // Has strtol() consumed all characters in the string? + if (*end != '\0') { + // No - an invalid character was encountered. + std::cerr << src_text << " is expected to be a double, " + << "but actually has value \"" << str << "\".\n"; + return false; + } + + *value = double_value; + return true; +} + +// Parses 'str' into KV pairs. If successful, writes the result to *value and +// returns true; otherwise leaves *value unchanged and returns false. +bool ParseKvPairs(const std::string& src_text, const char* str, + std::map* value) { + std::map kvs; + for (const auto& kvpair : StrSplit(str, ',')) { + const auto kv = StrSplit(kvpair, '='); + if (kv.size() != 2) { + std::cerr << src_text << " is expected to be a comma-separated list of " + << "= strings, but actually has value \"" << str + << "\".\n"; + return false; + } + if (!kvs.emplace(kv[0], kv[1]).second) { + std::cerr << src_text << " is expected to contain unique keys but key \"" + << kv[0] << "\" was repeated.\n"; + return false; + } + } + + *value = kvs; + return true; +} + +// Returns the name of the environment variable corresponding to the +// given flag. For example, FlagToEnvVar("foo") will return +// "BENCHMARK_FOO" in the open-source version. +static std::string FlagToEnvVar(const char* flag) { + const std::string flag_str(flag); + + std::string env_var; + for (size_t i = 0; i != flag_str.length(); ++i) + env_var += static_cast(::toupper(flag_str.c_str()[i])); + + return env_var; +} + +} // namespace + +BENCHMARK_EXPORT +bool BoolFromEnv(const char* flag, bool default_val) { + const std::string env_var = FlagToEnvVar(flag); + const char* const value_str = getenv(env_var.c_str()); + return value_str == nullptr ? default_val : IsTruthyFlagValue(value_str); +} + +BENCHMARK_EXPORT +int32_t Int32FromEnv(const char* flag, int32_t default_val) { + const std::string env_var = FlagToEnvVar(flag); + const char* const value_str = getenv(env_var.c_str()); + int32_t value = default_val; + if (value_str == nullptr || + !ParseInt32(std::string("Environment variable ") + env_var, value_str, + &value)) { + return default_val; + } + return value; +} + +BENCHMARK_EXPORT +double DoubleFromEnv(const char* flag, double default_val) { + const std::string env_var = FlagToEnvVar(flag); + const char* const value_str = getenv(env_var.c_str()); + double value = default_val; + if (value_str == nullptr || + !ParseDouble(std::string("Environment variable ") + env_var, value_str, + &value)) { + return default_val; + } + return value; +} + +BENCHMARK_EXPORT +const char* StringFromEnv(const char* flag, const char* default_val) { + const std::string env_var = FlagToEnvVar(flag); + const char* const value = getenv(env_var.c_str()); + return value == nullptr ? default_val : value; +} + +BENCHMARK_EXPORT +std::map KvPairsFromEnv( + const char* flag, std::map default_val) { + const std::string env_var = FlagToEnvVar(flag); + const char* const value_str = getenv(env_var.c_str()); + + if (value_str == nullptr) return default_val; + + std::map value; + if (!ParseKvPairs("Environment variable " + env_var, value_str, &value)) { + return default_val; + } + return value; +} + +// Parses a string as a command line flag. The string should have +// the format "--flag=value". When def_optional is true, the "=value" +// part can be omitted. +// +// Returns the value of the flag, or nullptr if the parsing failed. +const char* ParseFlagValue(const char* str, const char* flag, + bool def_optional) { + // str and flag must not be nullptr. + if (str == nullptr || flag == nullptr) return nullptr; + + // The flag must start with "--". + const std::string flag_str = std::string("--") + std::string(flag); + const size_t flag_len = flag_str.length(); + if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr; + + // Skips the flag name. + const char* flag_end = str + flag_len; + + // When def_optional is true, it's OK to not have a "=value" part. + if (def_optional && (flag_end[0] == '\0')) return flag_end; + + // If def_optional is true and there are more characters after the + // flag name, or if def_optional is false, there must be a '=' after + // the flag name. + if (flag_end[0] != '=') return nullptr; + + // Returns the string after "=". + return flag_end + 1; +} + +BENCHMARK_EXPORT +bool ParseBoolFlag(const char* str, const char* flag, bool* value) { + // Gets the value of the flag as a string. + const char* const value_str = ParseFlagValue(str, flag, true); + + // Aborts if the parsing failed. + if (value_str == nullptr) return false; + + // Converts the string value to a bool. + *value = IsTruthyFlagValue(value_str); + return true; +} + +BENCHMARK_EXPORT +bool ParseInt32Flag(const char* str, const char* flag, int32_t* value) { + // Gets the value of the flag as a string. + const char* const value_str = ParseFlagValue(str, flag, false); + + // Aborts if the parsing failed. + if (value_str == nullptr) return false; + + // Sets *value to the value of the flag. + return ParseInt32(std::string("The value of flag --") + flag, value_str, + value); +} + +BENCHMARK_EXPORT +bool ParseDoubleFlag(const char* str, const char* flag, double* value) { + // Gets the value of the flag as a string. + const char* const value_str = ParseFlagValue(str, flag, false); + + // Aborts if the parsing failed. + if (value_str == nullptr) return false; + + // Sets *value to the value of the flag. + return ParseDouble(std::string("The value of flag --") + flag, value_str, + value); +} + +BENCHMARK_EXPORT +bool ParseStringFlag(const char* str, const char* flag, std::string* value) { + // Gets the value of the flag as a string. + const char* const value_str = ParseFlagValue(str, flag, false); + + // Aborts if the parsing failed. + if (value_str == nullptr) return false; + + *value = value_str; + return true; +} + +BENCHMARK_EXPORT +bool ParseKeyValueFlag(const char* str, const char* flag, + std::map* value) { + const char* const value_str = ParseFlagValue(str, flag, false); + + if (value_str == nullptr) return false; + + for (const auto& kvpair : StrSplit(value_str, ',')) { + const auto kv = StrSplit(kvpair, '='); + if (kv.size() != 2) return false; + value->emplace(kv[0], kv[1]); + } + + return true; +} + +BENCHMARK_EXPORT +bool IsFlag(const char* str, const char* flag) { + return (ParseFlagValue(str, flag, true) != nullptr); +} + +BENCHMARK_EXPORT +bool IsTruthyFlagValue(const std::string& value) { + if (value.size() == 1) { + char v = value[0]; + return isalnum(v) && + !(v == '0' || v == 'f' || v == 'F' || v == 'n' || v == 'N'); + } + if (!value.empty()) { + std::string value_lower(value); + std::transform(value_lower.begin(), value_lower.end(), value_lower.begin(), + [](char c) { return static_cast(::tolower(c)); }); + return !(value_lower == "false" || value_lower == "no" || + value_lower == "off"); + } + return true; +} + +} // end namespace benchmark diff --git a/third_party/benchmark/src/commandlineflags.h b/third_party/benchmark/src/commandlineflags.h new file mode 100644 index 0000000..7882628 --- /dev/null +++ b/third_party/benchmark/src/commandlineflags.h @@ -0,0 +1,133 @@ +#ifndef BENCHMARK_COMMANDLINEFLAGS_H_ +#define BENCHMARK_COMMANDLINEFLAGS_H_ + +#include +#include +#include + +#include "benchmark/export.h" + +// Macro for referencing flags. +#define FLAG(name) FLAGS_##name + +// Macros for declaring flags. +#define BM_DECLARE_bool(name) BENCHMARK_EXPORT extern bool FLAG(name) +#define BM_DECLARE_int32(name) BENCHMARK_EXPORT extern int32_t FLAG(name) +#define BM_DECLARE_double(name) BENCHMARK_EXPORT extern double FLAG(name) +#define BM_DECLARE_string(name) BENCHMARK_EXPORT extern std::string FLAG(name) +#define BM_DECLARE_kvpairs(name) \ + BENCHMARK_EXPORT extern std::map FLAG(name) + +// Macros for defining flags. +#define BM_DEFINE_bool(name, default_val) \ + BENCHMARK_EXPORT bool FLAG(name) = benchmark::BoolFromEnv(#name, default_val) +#define BM_DEFINE_int32(name, default_val) \ + BENCHMARK_EXPORT int32_t FLAG(name) = \ + benchmark::Int32FromEnv(#name, default_val) +#define BM_DEFINE_double(name, default_val) \ + BENCHMARK_EXPORT double FLAG(name) = \ + benchmark::DoubleFromEnv(#name, default_val) +#define BM_DEFINE_string(name, default_val) \ + BENCHMARK_EXPORT std::string FLAG(name) = \ + benchmark::StringFromEnv(#name, default_val) +#define BM_DEFINE_kvpairs(name, default_val) \ + BENCHMARK_EXPORT std::map FLAG(name) = \ + benchmark::KvPairsFromEnv(#name, default_val) + +namespace benchmark { + +// Parses a bool from the environment variable corresponding to the given flag. +// +// If the variable exists, returns IsTruthyFlagValue() value; if not, +// returns the given default value. +BENCHMARK_EXPORT +bool BoolFromEnv(const char* flag, bool default_val); + +// Parses an Int32 from the environment variable corresponding to the given +// flag. +// +// If the variable exists, returns ParseInt32() value; if not, returns +// the given default value. +BENCHMARK_EXPORT +int32_t Int32FromEnv(const char* flag, int32_t default_val); + +// Parses an Double from the environment variable corresponding to the given +// flag. +// +// If the variable exists, returns ParseDouble(); if not, returns +// the given default value. +BENCHMARK_EXPORT +double DoubleFromEnv(const char* flag, double default_val); + +// Parses a string from the environment variable corresponding to the given +// flag. +// +// If variable exists, returns its value; if not, returns +// the given default value. +BENCHMARK_EXPORT +const char* StringFromEnv(const char* flag, const char* default_val); + +// Parses a set of kvpairs from the environment variable corresponding to the +// given flag. +// +// If variable exists, returns its value; if not, returns +// the given default value. +BENCHMARK_EXPORT +std::map KvPairsFromEnv( + const char* flag, std::map default_val); + +// Parses a string for a bool flag, in the form of either +// "--flag=value" or "--flag". +// +// In the former case, the value is taken as true if it passes IsTruthyValue(). +// +// In the latter case, the value is taken as true. +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +BENCHMARK_EXPORT +bool ParseBoolFlag(const char* str, const char* flag, bool* value); + +// Parses a string for an Int32 flag, in the form of "--flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +BENCHMARK_EXPORT +bool ParseInt32Flag(const char* str, const char* flag, int32_t* value); + +// Parses a string for a Double flag, in the form of "--flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +BENCHMARK_EXPORT +bool ParseDoubleFlag(const char* str, const char* flag, double* value); + +// Parses a string for a string flag, in the form of "--flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +BENCHMARK_EXPORT +bool ParseStringFlag(const char* str, const char* flag, std::string* value); + +// Parses a string for a kvpairs flag in the form "--flag=key=value,key=value" +// +// On success, stores the value of the flag in *value and returns true. On +// failure returns false, though *value may have been mutated. +BENCHMARK_EXPORT +bool ParseKeyValueFlag(const char* str, const char* flag, + std::map* value); + +// Returns true if the string matches the flag. +BENCHMARK_EXPORT +bool IsFlag(const char* str, const char* flag); + +// Returns true unless value starts with one of: '0', 'f', 'F', 'n' or 'N', or +// some non-alphanumeric character. Also returns false if the value matches +// one of 'no', 'false', 'off' (case-insensitive). As a special case, also +// returns true if value is the empty string. +BENCHMARK_EXPORT +bool IsTruthyFlagValue(const std::string& value); + +} // end namespace benchmark + +#endif // BENCHMARK_COMMANDLINEFLAGS_H_ diff --git a/third_party/benchmark/src/complexity.cc b/third_party/benchmark/src/complexity.cc new file mode 100644 index 0000000..eee3122 --- /dev/null +++ b/third_party/benchmark/src/complexity.cc @@ -0,0 +1,259 @@ +// Copyright 2016 Ismael Jimenez Martinez. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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. + +// Source project : https://github.com/ismaelJimenez/cpp.leastsq +// Adapted to be used with google benchmark + +#include "complexity.h" + +#include +#include + +#include "benchmark/benchmark.h" +#include "check.h" + +namespace benchmark { + +// Internal function to calculate the different scalability forms +BigOFunc* FittingCurve(BigO complexity) { + static const double kLog2E = 1.44269504088896340736; + switch (complexity) { + case oN: + return [](IterationCount n) -> double { return static_cast(n); }; + case oNSquared: + return [](IterationCount n) -> double { return std::pow(n, 2); }; + case oNCubed: + return [](IterationCount n) -> double { return std::pow(n, 3); }; + case oLogN: + /* Note: can't use log2 because Android's GNU STL lacks it */ + return [](IterationCount n) { + return kLog2E * std::log(static_cast(n)); + }; + case oNLogN: + /* Note: can't use log2 because Android's GNU STL lacks it */ + return [](IterationCount n) { + return kLog2E * static_cast(n) * + std::log(static_cast(n)); + }; + case o1: + default: + return [](IterationCount) { return 1.0; }; + } +} + +// Function to return an string for the calculated complexity +std::string GetBigOString(BigO complexity) { + switch (complexity) { + case oN: + return "N"; + case oNSquared: + return "N^2"; + case oNCubed: + return "N^3"; + case oLogN: + return "lgN"; + case oNLogN: + return "NlgN"; + case o1: + return "(1)"; + default: + return "f(N)"; + } +} + +// Find the coefficient for the high-order term in the running time, by +// minimizing the sum of squares of relative error, for the fitting curve +// given by the lambda expression. +// - n : Vector containing the size of the benchmark tests. +// - time : Vector containing the times for the benchmark tests. +// - fitting_curve : lambda expression (e.g. [](ComplexityN n) {return n; };). + +// For a deeper explanation on the algorithm logic, please refer to +// https://en.wikipedia.org/wiki/Least_squares#Least_squares,_regression_analysis_and_statistics + +LeastSq MinimalLeastSq(const std::vector& n, + const std::vector& time, + BigOFunc* fitting_curve) { + double sigma_gn_squared = 0.0; + double sigma_time = 0.0; + double sigma_time_gn = 0.0; + + // Calculate least square fitting parameter + for (size_t i = 0; i < n.size(); ++i) { + double gn_i = fitting_curve(n[i]); + sigma_gn_squared += gn_i * gn_i; + sigma_time += time[i]; + sigma_time_gn += time[i] * gn_i; + } + + LeastSq result; + result.complexity = oLambda; + + // Calculate complexity. + result.coef = sigma_time_gn / sigma_gn_squared; + + // Calculate RMS + double rms = 0.0; + for (size_t i = 0; i < n.size(); ++i) { + double fit = result.coef * fitting_curve(n[i]); + rms += std::pow((time[i] - fit), 2); + } + + // Normalized RMS by the mean of the observed values + double mean = sigma_time / static_cast(n.size()); + result.rms = std::sqrt(rms / static_cast(n.size())) / mean; + + return result; +} + +// Find the coefficient for the high-order term in the running time, by +// minimizing the sum of squares of relative error. +// - n : Vector containing the size of the benchmark tests. +// - time : Vector containing the times for the benchmark tests. +// - complexity : If different than oAuto, the fitting curve will stick to +// this one. If it is oAuto, it will be calculated the best +// fitting curve. +LeastSq MinimalLeastSq(const std::vector& n, + const std::vector& time, const BigO complexity) { + BM_CHECK_EQ(n.size(), time.size()); + BM_CHECK_GE(n.size(), 2); // Do not compute fitting curve is less than two + // benchmark runs are given + BM_CHECK_NE(complexity, oNone); + + LeastSq best_fit; + + if (complexity == oAuto) { + std::vector fit_curves = {oLogN, oN, oNLogN, oNSquared, oNCubed}; + + // Take o1 as default best fitting curve + best_fit = MinimalLeastSq(n, time, FittingCurve(o1)); + best_fit.complexity = o1; + + // Compute all possible fitting curves and stick to the best one + for (const auto& fit : fit_curves) { + LeastSq current_fit = MinimalLeastSq(n, time, FittingCurve(fit)); + if (current_fit.rms < best_fit.rms) { + best_fit = current_fit; + best_fit.complexity = fit; + } + } + } else { + best_fit = MinimalLeastSq(n, time, FittingCurve(complexity)); + best_fit.complexity = complexity; + } + + return best_fit; +} + +std::vector ComputeBigO( + const std::vector& reports) { + typedef BenchmarkReporter::Run Run; + std::vector results; + + if (reports.size() < 2) return results; + + // Accumulators. + std::vector n; + std::vector real_time; + std::vector cpu_time; + + // Populate the accumulators. + for (const Run& run : reports) { + BM_CHECK_GT(run.complexity_n, 0) + << "Did you forget to call SetComplexityN?"; + n.push_back(run.complexity_n); + real_time.push_back(run.real_accumulated_time / + static_cast(run.iterations)); + cpu_time.push_back(run.cpu_accumulated_time / + static_cast(run.iterations)); + } + + LeastSq result_cpu; + LeastSq result_real; + + if (reports[0].complexity == oLambda) { + result_cpu = MinimalLeastSq(n, cpu_time, reports[0].complexity_lambda); + result_real = MinimalLeastSq(n, real_time, reports[0].complexity_lambda); + } else { + const BigO* InitialBigO = &reports[0].complexity; + const bool use_real_time_for_initial_big_o = + reports[0].use_real_time_for_initial_big_o; + if (use_real_time_for_initial_big_o) { + result_real = MinimalLeastSq(n, real_time, *InitialBigO); + InitialBigO = &result_real.complexity; + // The Big-O complexity for CPU time must have the same Big-O function! + } + result_cpu = MinimalLeastSq(n, cpu_time, *InitialBigO); + InitialBigO = &result_cpu.complexity; + if (!use_real_time_for_initial_big_o) { + result_real = MinimalLeastSq(n, real_time, *InitialBigO); + } + } + + // Drop the 'args' when reporting complexity. + auto run_name = reports[0].run_name; + run_name.args.clear(); + + // Get the data from the accumulator to BenchmarkReporter::Run's. + Run big_o; + big_o.run_name = run_name; + big_o.family_index = reports[0].family_index; + big_o.per_family_instance_index = reports[0].per_family_instance_index; + big_o.run_type = BenchmarkReporter::Run::RT_Aggregate; + big_o.repetitions = reports[0].repetitions; + big_o.repetition_index = Run::no_repetition_index; + big_o.threads = reports[0].threads; + big_o.aggregate_name = "BigO"; + big_o.aggregate_unit = StatisticUnit::kTime; + big_o.report_label = reports[0].report_label; + big_o.iterations = 0; + big_o.real_accumulated_time = result_real.coef; + big_o.cpu_accumulated_time = result_cpu.coef; + big_o.report_big_o = true; + big_o.complexity = result_cpu.complexity; + + // All the time results are reported after being multiplied by the + // time unit multiplier. But since RMS is a relative quantity it + // should not be multiplied at all. So, here, we _divide_ it by the + // multiplier so that when it is multiplied later the result is the + // correct one. + double multiplier = GetTimeUnitMultiplier(reports[0].time_unit); + + // Only add label to mean/stddev if it is same for all runs + Run rms; + rms.run_name = run_name; + rms.family_index = reports[0].family_index; + rms.per_family_instance_index = reports[0].per_family_instance_index; + rms.run_type = BenchmarkReporter::Run::RT_Aggregate; + rms.aggregate_name = "RMS"; + rms.aggregate_unit = StatisticUnit::kPercentage; + rms.report_label = big_o.report_label; + rms.iterations = 0; + rms.repetition_index = Run::no_repetition_index; + rms.repetitions = reports[0].repetitions; + rms.threads = reports[0].threads; + rms.real_accumulated_time = result_real.rms / multiplier; + rms.cpu_accumulated_time = result_cpu.rms / multiplier; + rms.report_rms = true; + rms.complexity = result_cpu.complexity; + // don't forget to keep the time unit, or we won't be able to + // recover the correct value. + rms.time_unit = reports[0].time_unit; + + results.push_back(big_o); + results.push_back(rms); + return results; +} + +} // end namespace benchmark diff --git a/third_party/benchmark/src/complexity.h b/third_party/benchmark/src/complexity.h new file mode 100644 index 0000000..0a0679b --- /dev/null +++ b/third_party/benchmark/src/complexity.h @@ -0,0 +1,55 @@ +// Copyright 2016 Ismael Jimenez Martinez. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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. + +// Source project : https://github.com/ismaelJimenez/cpp.leastsq +// Adapted to be used with google benchmark + +#ifndef COMPLEXITY_H_ +#define COMPLEXITY_H_ + +#include +#include + +#include "benchmark/benchmark.h" + +namespace benchmark { + +// Return a vector containing the bigO and RMS information for the specified +// list of reports. If 'reports.size() < 2' an empty vector is returned. +std::vector ComputeBigO( + const std::vector& reports); + +// This data structure will contain the result returned by MinimalLeastSq +// - coef : Estimated coefficient for the high-order term as +// interpolated from data. +// - rms : Normalized Root Mean Squared Error. +// - complexity : Scalability form (e.g. oN, oNLogN). In case a scalability +// form has been provided to MinimalLeastSq this will return +// the same value. In case BigO::oAuto has been selected, this +// parameter will return the best fitting curve detected. + +struct LeastSq { + LeastSq() : coef(0.0), rms(0.0), complexity(oNone) {} + + double coef; + double rms; + BigO complexity; +}; + +// Function to return an string for the calculated complexity +std::string GetBigOString(BigO complexity); + +} // end namespace benchmark + +#endif // COMPLEXITY_H_ diff --git a/third_party/benchmark/src/console_reporter.cc b/third_party/benchmark/src/console_reporter.cc new file mode 100644 index 0000000..35c3de2 --- /dev/null +++ b/third_party/benchmark/src/console_reporter.cc @@ -0,0 +1,210 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 +#include +#include +#include +#include +#include +#include +#include + +#include "benchmark/benchmark.h" +#include "check.h" +#include "colorprint.h" +#include "commandlineflags.h" +#include "complexity.h" +#include "counter.h" +#include "internal_macros.h" +#include "string_util.h" +#include "timers.h" + +namespace benchmark { + +BENCHMARK_EXPORT +bool ConsoleReporter::ReportContext(const Context& context) { + name_field_width_ = context.name_field_width; + printed_header_ = false; + prev_counters_.clear(); + + PrintBasicContext(&GetErrorStream(), context); + +#ifdef BENCHMARK_OS_WINDOWS + if ((output_options_ & OO_Color)) { + auto stdOutBuf = std::cout.rdbuf(); + auto outStreamBuf = GetOutputStream().rdbuf(); + if (stdOutBuf != outStreamBuf) { + GetErrorStream() + << "Color printing is only supported for stdout on windows." + " Disabling color printing\n"; + output_options_ = static_cast(output_options_ & ~OO_Color); + } + } +#endif + + return true; +} + +BENCHMARK_EXPORT +void ConsoleReporter::PrintHeader(const Run& run) { + std::string str = + FormatString("%-*s %13s %15s %12s", static_cast(name_field_width_), + "Benchmark", "Time", "CPU", "Iterations"); + if (!run.counters.empty()) { + if (output_options_ & OO_Tabular) { + for (auto const& c : run.counters) { + str += FormatString(" %10s", c.first.c_str()); + } + } else { + str += " UserCounters..."; + } + } + std::string line = std::string(str.length(), '-'); + GetOutputStream() << line << "\n" << str << "\n" << line << "\n"; +} + +BENCHMARK_EXPORT +void ConsoleReporter::ReportRuns(const std::vector& reports) { + for (const auto& run : reports) { + // print the header: + // --- if none was printed yet + bool print_header = !printed_header_; + // --- or if the format is tabular and this run + // has different fields from the prev header + print_header |= (output_options_ & OO_Tabular) && + (!internal::SameNames(run.counters, prev_counters_)); + if (print_header) { + printed_header_ = true; + prev_counters_ = run.counters; + PrintHeader(run); + } + // As an alternative to printing the headers like this, we could sort + // the benchmarks by header and then print. But this would require + // waiting for the full results before printing, or printing twice. + PrintRunData(run); + } +} + +static void IgnoreColorPrint(std::ostream& out, LogColor, const char* fmt, + ...) { + va_list args; + va_start(args, fmt); + out << FormatString(fmt, args); + va_end(args); +} + +static std::string FormatTime(double time) { + // For the time columns of the console printer 13 digits are reserved. One of + // them is a space and max two of them are the time unit (e.g ns). That puts + // us at 10 digits usable for the number. + // Align decimal places... + if (time < 1.0) { + return FormatString("%10.3f", time); + } + if (time < 10.0) { + return FormatString("%10.2f", time); + } + if (time < 100.0) { + return FormatString("%10.1f", time); + } + // Assuming the time is at max 9.9999e+99 and we have 10 digits for the + // number, we get 10-1(.)-1(e)-1(sign)-2(exponent) = 5 digits to print. + if (time > 9999999999 /*max 10 digit number*/) { + return FormatString("%1.4e", time); + } + return FormatString("%10.0f", time); +} + +BENCHMARK_EXPORT +void ConsoleReporter::PrintRunData(const Run& result) { + typedef void(PrinterFn)(std::ostream&, LogColor, const char*, ...); + auto& Out = GetOutputStream(); + PrinterFn* printer = (output_options_ & OO_Color) + ? static_cast(ColorPrintf) + : IgnoreColorPrint; + auto name_color = + (result.report_big_o || result.report_rms) ? COLOR_BLUE : COLOR_GREEN; + printer(Out, name_color, "%-*s ", name_field_width_, + result.benchmark_name().c_str()); + + if (internal::SkippedWithError == result.skipped) { + printer(Out, COLOR_RED, "ERROR OCCURRED: \'%s\'", + result.skip_message.c_str()); + printer(Out, COLOR_DEFAULT, "\n"); + return; + } else if (internal::SkippedWithMessage == result.skipped) { + printer(Out, COLOR_WHITE, "SKIPPED: \'%s\'", result.skip_message.c_str()); + printer(Out, COLOR_DEFAULT, "\n"); + return; + } + + const double real_time = result.GetAdjustedRealTime(); + const double cpu_time = result.GetAdjustedCPUTime(); + const std::string real_time_str = FormatTime(real_time); + const std::string cpu_time_str = FormatTime(cpu_time); + + if (result.report_big_o) { + std::string big_o = GetBigOString(result.complexity); + printer(Out, COLOR_YELLOW, "%10.2f %-4s %10.2f %-4s ", real_time, + big_o.c_str(), cpu_time, big_o.c_str()); + } else if (result.report_rms) { + printer(Out, COLOR_YELLOW, "%10.0f %-4s %10.0f %-4s ", real_time * 100, "%", + cpu_time * 100, "%"); + } else if (result.run_type != Run::RT_Aggregate || + result.aggregate_unit == StatisticUnit::kTime) { + const char* timeLabel = GetTimeUnitString(result.time_unit); + printer(Out, COLOR_YELLOW, "%s %-4s %s %-4s ", real_time_str.c_str(), + timeLabel, cpu_time_str.c_str(), timeLabel); + } else { + assert(result.aggregate_unit == StatisticUnit::kPercentage); + printer(Out, COLOR_YELLOW, "%10.2f %-4s %10.2f %-4s ", + (100. * result.real_accumulated_time), "%", + (100. * result.cpu_accumulated_time), "%"); + } + + if (!result.report_big_o && !result.report_rms) { + printer(Out, COLOR_CYAN, "%10lld", result.iterations); + } + + for (auto& c : result.counters) { + const std::size_t cNameLen = + std::max(std::string::size_type(10), c.first.length()); + std::string s; + const char* unit = ""; + if (result.run_type == Run::RT_Aggregate && + result.aggregate_unit == StatisticUnit::kPercentage) { + s = StrFormat("%.2f", 100. * c.second.value); + unit = "%"; + } else { + s = HumanReadableNumber(c.second.value, c.second.oneK); + if (c.second.flags & Counter::kIsRate) + unit = (c.second.flags & Counter::kInvert) ? "s" : "/s"; + } + if (output_options_ & OO_Tabular) { + printer(Out, COLOR_DEFAULT, " %*s%s", cNameLen - strlen(unit), s.c_str(), + unit); + } else { + printer(Out, COLOR_DEFAULT, " %s=%s%s", c.first.c_str(), s.c_str(), unit); + } + } + + if (!result.report_label.empty()) { + printer(Out, COLOR_DEFAULT, " %s", result.report_label.c_str()); + } + + printer(Out, COLOR_DEFAULT, "\n"); +} + +} // end namespace benchmark diff --git a/third_party/benchmark/src/counter.cc b/third_party/benchmark/src/counter.cc new file mode 100644 index 0000000..aa14cd8 --- /dev/null +++ b/third_party/benchmark/src/counter.cc @@ -0,0 +1,80 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 "counter.h" + +namespace benchmark { +namespace internal { + +double Finish(Counter const& c, IterationCount iterations, double cpu_time, + double num_threads) { + double v = c.value; + if (c.flags & Counter::kIsRate) { + v /= cpu_time; + } + if (c.flags & Counter::kAvgThreads) { + v /= num_threads; + } + if (c.flags & Counter::kIsIterationInvariant) { + v *= static_cast(iterations); + } + if (c.flags & Counter::kAvgIterations) { + v /= static_cast(iterations); + } + + if (c.flags & Counter::kInvert) { // Invert is *always* last. + v = 1.0 / v; + } + return v; +} + +void Finish(UserCounters* l, IterationCount iterations, double cpu_time, + double num_threads) { + for (auto& c : *l) { + c.second.value = Finish(c.second, iterations, cpu_time, num_threads); + } +} + +void Increment(UserCounters* l, UserCounters const& r) { + // add counters present in both or just in *l + for (auto& c : *l) { + auto it = r.find(c.first); + if (it != r.end()) { + c.second.value = c.second + it->second; + } + } + // add counters present in r, but not in *l + for (auto const& tc : r) { + auto it = l->find(tc.first); + if (it == l->end()) { + (*l)[tc.first] = tc.second; + } + } +} + +bool SameNames(UserCounters const& l, UserCounters const& r) { + if (&l == &r) return true; + if (l.size() != r.size()) { + return false; + } + for (auto const& c : l) { + if (r.find(c.first) == r.end()) { + return false; + } + } + return true; +} + +} // end namespace internal +} // end namespace benchmark diff --git a/third_party/benchmark/src/counter.h b/third_party/benchmark/src/counter.h new file mode 100644 index 0000000..1f5a58e --- /dev/null +++ b/third_party/benchmark/src/counter.h @@ -0,0 +1,32 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 BENCHMARK_COUNTER_H_ +#define BENCHMARK_COUNTER_H_ + +#include "benchmark/benchmark.h" + +namespace benchmark { + +// these counter-related functions are hidden to reduce API surface. +namespace internal { +void Finish(UserCounters* l, IterationCount iterations, double time, + double num_threads); +void Increment(UserCounters* l, UserCounters const& r); +bool SameNames(UserCounters const& l, UserCounters const& r); +} // end namespace internal + +} // end namespace benchmark + +#endif // BENCHMARK_COUNTER_H_ diff --git a/third_party/benchmark/src/csv_reporter.cc b/third_party/benchmark/src/csv_reporter.cc new file mode 100644 index 0000000..4b39e2c --- /dev/null +++ b/third_party/benchmark/src/csv_reporter.cc @@ -0,0 +1,169 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 +#include +#include +#include +#include +#include + +#include "benchmark/benchmark.h" +#include "check.h" +#include "complexity.h" +#include "string_util.h" +#include "timers.h" + +// File format reference: http://edoceo.com/utilitas/csv-file-format. + +namespace benchmark { + +namespace { +std::vector elements = { + "name", "iterations", "real_time", "cpu_time", + "time_unit", "bytes_per_second", "items_per_second", "label", + "error_occurred", "error_message"}; +} // namespace + +std::string CsvEscape(const std::string& s) { + std::string tmp; + tmp.reserve(s.size() + 2); + for (char c : s) { + switch (c) { + case '"': + tmp += "\"\""; + break; + default: + tmp += c; + break; + } + } + return '"' + tmp + '"'; +} + +BENCHMARK_EXPORT +bool CSVReporter::ReportContext(const Context& context) { + PrintBasicContext(&GetErrorStream(), context); + return true; +} + +BENCHMARK_EXPORT +void CSVReporter::ReportRuns(const std::vector& reports) { + std::ostream& Out = GetOutputStream(); + + if (!printed_header_) { + // save the names of all the user counters + for (const auto& run : reports) { + for (const auto& cnt : run.counters) { + if (cnt.first == "bytes_per_second" || cnt.first == "items_per_second") + continue; + user_counter_names_.insert(cnt.first); + } + } + + // print the header + for (auto B = elements.begin(); B != elements.end();) { + Out << *B++; + if (B != elements.end()) Out << ","; + } + for (auto B = user_counter_names_.begin(); + B != user_counter_names_.end();) { + Out << ",\"" << *B++ << "\""; + } + Out << "\n"; + + printed_header_ = true; + } else { + // check that all the current counters are saved in the name set + for (const auto& run : reports) { + for (const auto& cnt : run.counters) { + if (cnt.first == "bytes_per_second" || cnt.first == "items_per_second") + continue; + BM_CHECK(user_counter_names_.find(cnt.first) != + user_counter_names_.end()) + << "All counters must be present in each run. " + << "Counter named \"" << cnt.first + << "\" was not in a run after being added to the header"; + } + } + } + + // print results for each run + for (const auto& run : reports) { + PrintRunData(run); + } +} + +BENCHMARK_EXPORT +void CSVReporter::PrintRunData(const Run& run) { + std::ostream& Out = GetOutputStream(); + Out << CsvEscape(run.benchmark_name()) << ","; + if (run.skipped) { + Out << std::string(elements.size() - 3, ','); + Out << std::boolalpha << (internal::SkippedWithError == run.skipped) << ","; + Out << CsvEscape(run.skip_message) << "\n"; + return; + } + + // Do not print iteration on bigO and RMS report + if (!run.report_big_o && !run.report_rms) { + Out << run.iterations; + } + Out << ","; + + if (run.run_type != Run::RT_Aggregate || + run.aggregate_unit == StatisticUnit::kTime) { + Out << run.GetAdjustedRealTime() << ","; + Out << run.GetAdjustedCPUTime() << ","; + } else { + assert(run.aggregate_unit == StatisticUnit::kPercentage); + Out << run.real_accumulated_time << ","; + Out << run.cpu_accumulated_time << ","; + } + + // Do not print timeLabel on bigO and RMS report + if (run.report_big_o) { + Out << GetBigOString(run.complexity); + } else if (!run.report_rms && + run.aggregate_unit != StatisticUnit::kPercentage) { + Out << GetTimeUnitString(run.time_unit); + } + Out << ","; + + if (run.counters.find("bytes_per_second") != run.counters.end()) { + Out << run.counters.at("bytes_per_second"); + } + Out << ","; + if (run.counters.find("items_per_second") != run.counters.end()) { + Out << run.counters.at("items_per_second"); + } + Out << ","; + if (!run.report_label.empty()) { + Out << CsvEscape(run.report_label); + } + Out << ",,"; // for error_occurred and error_message + + // Print user counters + for (const auto& ucn : user_counter_names_) { + auto it = run.counters.find(ucn); + if (it == run.counters.end()) { + Out << ","; + } else { + Out << "," << it->second; + } + } + Out << '\n'; +} + +} // end namespace benchmark diff --git a/third_party/benchmark/src/cycleclock.h b/third_party/benchmark/src/cycleclock.h new file mode 100644 index 0000000..a258437 --- /dev/null +++ b/third_party/benchmark/src/cycleclock.h @@ -0,0 +1,242 @@ +// ---------------------------------------------------------------------- +// CycleClock +// A CycleClock tells you the current time in Cycles. The "time" +// is actually time since power-on. This is like time() but doesn't +// involve a system call and is much more precise. +// +// NOTE: Not all cpu/platform/kernel combinations guarantee that this +// clock increments at a constant rate or is synchronized across all logical +// cpus in a system. +// +// If you need the above guarantees, please consider using a different +// API. There are efforts to provide an interface which provides a millisecond +// granularity and implemented as a memory read. A memory read is generally +// cheaper than the CycleClock for many architectures. +// +// Also, in some out of order CPU implementations, the CycleClock is not +// serializing. So if you're trying to count at cycles granularity, your +// data might be inaccurate due to out of order instruction execution. +// ---------------------------------------------------------------------- + +#ifndef BENCHMARK_CYCLECLOCK_H_ +#define BENCHMARK_CYCLECLOCK_H_ + +#include + +#include "benchmark/benchmark.h" +#include "internal_macros.h" + +#if defined(BENCHMARK_OS_MACOSX) +#include +#endif +// For MSVC, we want to use '_asm rdtsc' when possible (since it works +// with even ancient MSVC compilers), and when not possible the +// __rdtsc intrinsic, declared in . Unfortunately, in some +// environments, and have conflicting +// declarations of some other intrinsics, breaking compilation. +// Therefore, we simply declare __rdtsc ourselves. See also +// http://connect.microsoft.com/VisualStudio/feedback/details/262047 +#if defined(COMPILER_MSVC) && !defined(_M_IX86) && !defined(_M_ARM64) && \ + !defined(_M_ARM64EC) +extern "C" uint64_t __rdtsc(); +#pragma intrinsic(__rdtsc) +#endif + +#if !defined(BENCHMARK_OS_WINDOWS) || defined(BENCHMARK_OS_MINGW) +#include +#include +#endif + +#ifdef BENCHMARK_OS_EMSCRIPTEN +#include +#endif + +namespace benchmark { +// NOTE: only i386 and x86_64 have been well tested. +// PPC, sparc, alpha, and ia64 are based on +// http://peter.kuscsik.com/wordpress/?p=14 +// with modifications by m3b. See also +// https://setisvn.ssl.berkeley.edu/svn/lib/fftw-3.0.1/kernel/cycle.h +namespace cycleclock { +// This should return the number of cycles since power-on. Thread-safe. +inline BENCHMARK_ALWAYS_INLINE int64_t Now() { +#if defined(BENCHMARK_OS_MACOSX) + // this goes at the top because we need ALL Macs, regardless of + // architecture, to return the number of "mach time units" that + // have passed since startup. See sysinfo.cc where + // InitializeSystemInfo() sets the supposed cpu clock frequency of + // macs to the number of mach time units per second, not actual + // CPU clock frequency (which can change in the face of CPU + // frequency scaling). Also note that when the Mac sleeps, this + // counter pauses; it does not continue counting, nor does it + // reset to zero. + return static_cast(mach_absolute_time()); +#elif defined(BENCHMARK_OS_EMSCRIPTEN) + // this goes above x86-specific code because old versions of Emscripten + // define __x86_64__, although they have nothing to do with it. + return static_cast(emscripten_get_now() * 1e+6); +#elif defined(__i386__) + int64_t ret; + __asm__ volatile("rdtsc" : "=A"(ret)); + return ret; +#elif defined(__x86_64__) || defined(__amd64__) + uint64_t low, high; + __asm__ volatile("rdtsc" : "=a"(low), "=d"(high)); + return static_cast((high << 32) | low); +#elif defined(__powerpc__) || defined(__ppc__) + // This returns a time-base, which is not always precisely a cycle-count. +#if defined(__powerpc64__) || defined(__ppc64__) + int64_t tb; + asm volatile("mfspr %0, 268" : "=r"(tb)); + return tb; +#else + uint32_t tbl, tbu0, tbu1; + asm volatile( + "mftbu %0\n" + "mftb %1\n" + "mftbu %2" + : "=r"(tbu0), "=r"(tbl), "=r"(tbu1)); + tbl &= -static_cast(tbu0 == tbu1); + // high 32 bits in tbu1; low 32 bits in tbl (tbu0 is no longer needed) + return (static_cast(tbu1) << 32) | tbl; +#endif +#elif defined(__sparc__) + int64_t tick; + asm(".byte 0x83, 0x41, 0x00, 0x00"); + asm("mov %%g1, %0" : "=r"(tick)); + return tick; +#elif defined(__ia64__) + int64_t itc; + asm("mov %0 = ar.itc" : "=r"(itc)); + return itc; +#elif defined(COMPILER_MSVC) && defined(_M_IX86) + // Older MSVC compilers (like 7.x) don't seem to support the + // __rdtsc intrinsic properly, so I prefer to use _asm instead + // when I know it will work. Otherwise, I'll use __rdtsc and hope + // the code is being compiled with a non-ancient compiler. + _asm rdtsc +#elif defined(COMPILER_MSVC) && (defined(_M_ARM64) || defined(_M_ARM64EC)) + // See // https://docs.microsoft.com/en-us/cpp/intrinsics/arm64-intrinsics + // and https://reviews.llvm.org/D53115 + int64_t virtual_timer_value; + virtual_timer_value = _ReadStatusReg(ARM64_CNTVCT); + return virtual_timer_value; +#elif defined(COMPILER_MSVC) + return __rdtsc(); +#elif defined(BENCHMARK_OS_NACL) + // Native Client validator on x86/x86-64 allows RDTSC instructions, + // and this case is handled above. Native Client validator on ARM + // rejects MRC instructions (used in the ARM-specific sequence below), + // so we handle it here. Portable Native Client compiles to + // architecture-agnostic bytecode, which doesn't provide any + // cycle counter access mnemonics. + + // Native Client does not provide any API to access cycle counter. + // Use clock_gettime(CLOCK_MONOTONIC, ...) instead of gettimeofday + // because is provides nanosecond resolution (which is noticeable at + // least for PNaCl modules running on x86 Mac & Linux). + // Initialize to always return 0 if clock_gettime fails. + struct timespec ts = {0, 0}; + clock_gettime(CLOCK_MONOTONIC, &ts); + return static_cast(ts.tv_sec) * 1000000000 + ts.tv_nsec; +#elif defined(__aarch64__) + // System timer of ARMv8 runs at a different frequency than the CPU's. + // The frequency is fixed, typically in the range 1-50MHz. It can be + // read at CNTFRQ special register. We assume the OS has set up + // the virtual timer properly. + int64_t virtual_timer_value; + asm volatile("mrs %0, cntvct_el0" : "=r"(virtual_timer_value)); + return virtual_timer_value; +#elif defined(__ARM_ARCH) + // V6 is the earliest arch that has a standard cyclecount + // Native Client validator doesn't allow MRC instructions. +#if (__ARM_ARCH >= 6) + uint32_t pmccntr; + uint32_t pmuseren; + uint32_t pmcntenset; + // Read the user mode perf monitor counter access permissions. + asm volatile("mrc p15, 0, %0, c9, c14, 0" : "=r"(pmuseren)); + if (pmuseren & 1) { // Allows reading perfmon counters for user mode code. + asm volatile("mrc p15, 0, %0, c9, c12, 1" : "=r"(pmcntenset)); + if (pmcntenset & 0x80000000ul) { // Is it counting? + asm volatile("mrc p15, 0, %0, c9, c13, 0" : "=r"(pmccntr)); + // The counter is set up to count every 64th cycle + return static_cast(pmccntr) * 64; // Should optimize to << 6 + } + } +#endif + struct timeval tv; + gettimeofday(&tv, nullptr); + return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; +#elif defined(__mips__) || defined(__m68k__) + // mips apparently only allows rdtsc for superusers, so we fall + // back to gettimeofday. It's possible clock_gettime would be better. + struct timeval tv; + gettimeofday(&tv, nullptr); + return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; +#elif defined(__loongarch__) || defined(__csky__) + struct timeval tv; + gettimeofday(&tv, nullptr); + return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; +#elif defined(__s390__) // Covers both s390 and s390x. + // Return the CPU clock. + uint64_t tsc; +#if defined(BENCHMARK_OS_ZOS) + // z/OS HLASM syntax. + asm(" stck %0" : "=m"(tsc) : : "cc"); +#else + // Linux on Z syntax. + asm("stck %0" : "=Q"(tsc) : : "cc"); +#endif + return tsc; +#elif defined(__riscv) // RISC-V + // Use RDTIME (and RDTIMEH on riscv32). + // RDCYCLE is a privileged instruction since Linux 6.6. +#if __riscv_xlen == 32 + uint32_t cycles_lo, cycles_hi0, cycles_hi1; + // This asm also includes the PowerPC overflow handling strategy, as above. + // Implemented in assembly because Clang insisted on branching. + asm volatile( + "rdtimeh %0\n" + "rdtime %1\n" + "rdtimeh %2\n" + "sub %0, %0, %2\n" + "seqz %0, %0\n" + "sub %0, zero, %0\n" + "and %1, %1, %0\n" + : "=r"(cycles_hi0), "=r"(cycles_lo), "=r"(cycles_hi1)); + return (static_cast(cycles_hi1) << 32) | cycles_lo; +#else + uint64_t cycles; + asm volatile("rdtime %0" : "=r"(cycles)); + return cycles; +#endif +#elif defined(__e2k__) || defined(__elbrus__) + struct timeval tv; + gettimeofday(&tv, nullptr); + return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; +#elif defined(__hexagon__) + uint64_t pcycle; + asm volatile("%0 = C15:14" : "=r"(pcycle)); + return static_cast(pcycle); +#elif defined(__alpha__) + // Alpha has a cycle counter, the PCC register, but it is an unsigned 32-bit + // integer and thus wraps every ~4s, making using it for tick counts + // unreliable beyond this time range. The real-time clock is low-precision, + // roughtly ~1ms, but it is the only option that can reasonable count + // indefinitely. + struct timeval tv; + gettimeofday(&tv, nullptr); + return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; +#else + // The soft failover to a generic implementation is automatic only for ARM. + // For other platforms the developer is expected to make an attempt to create + // a fast implementation and use generic version if nothing better is + // available. +#error You need to define CycleTimer for your OS and CPU +#endif +} +} // end namespace cycleclock +} // end namespace benchmark + +#endif // BENCHMARK_CYCLECLOCK_H_ diff --git a/third_party/benchmark/src/internal_macros.h b/third_party/benchmark/src/internal_macros.h new file mode 100644 index 0000000..f4894ba --- /dev/null +++ b/third_party/benchmark/src/internal_macros.h @@ -0,0 +1,111 @@ +#ifndef BENCHMARK_INTERNAL_MACROS_H_ +#define BENCHMARK_INTERNAL_MACROS_H_ + +/* Needed to detect STL */ +#include + +// clang-format off + +#ifndef __has_feature +#define __has_feature(x) 0 +#endif + +#if defined(__clang__) + #if !defined(COMPILER_CLANG) + #define COMPILER_CLANG + #endif +#elif defined(_MSC_VER) + #if !defined(COMPILER_MSVC) + #define COMPILER_MSVC + #endif +#elif defined(__GNUC__) + #if !defined(COMPILER_GCC) + #define COMPILER_GCC + #endif +#endif + +#if __has_feature(cxx_attributes) + #define BENCHMARK_NORETURN [[noreturn]] +#elif defined(__GNUC__) + #define BENCHMARK_NORETURN __attribute__((noreturn)) +#elif defined(COMPILER_MSVC) + #define BENCHMARK_NORETURN __declspec(noreturn) +#else + #define BENCHMARK_NORETURN +#endif + +#if defined(__CYGWIN__) + #define BENCHMARK_OS_CYGWIN 1 +#elif defined(_WIN32) + #define BENCHMARK_OS_WINDOWS 1 + // WINAPI_FAMILY_PARTITION is defined in winapifamily.h. + // We include windows.h which implicitly includes winapifamily.h for compatibility. + #ifndef NOMINMAX + #define NOMINMAX + #endif + #include + #if defined(WINAPI_FAMILY_PARTITION) + #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) + #define BENCHMARK_OS_WINDOWS_WIN32 1 + #elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) + #define BENCHMARK_OS_WINDOWS_RT 1 + #endif + #endif + #if defined(__MINGW32__) + #define BENCHMARK_OS_MINGW 1 + #endif +#elif defined(__APPLE__) + #define BENCHMARK_OS_APPLE 1 + #include "TargetConditionals.h" + #if defined(TARGET_OS_MAC) + #define BENCHMARK_OS_MACOSX 1 + #if defined(TARGET_OS_IPHONE) + #define BENCHMARK_OS_IOS 1 + #endif + #endif +#elif defined(__FreeBSD__) + #define BENCHMARK_OS_FREEBSD 1 +#elif defined(__NetBSD__) + #define BENCHMARK_OS_NETBSD 1 +#elif defined(__OpenBSD__) + #define BENCHMARK_OS_OPENBSD 1 +#elif defined(__DragonFly__) + #define BENCHMARK_OS_DRAGONFLY 1 +#elif defined(__linux__) + #define BENCHMARK_OS_LINUX 1 +#elif defined(__native_client__) + #define BENCHMARK_OS_NACL 1 +#elif defined(__EMSCRIPTEN__) + #define BENCHMARK_OS_EMSCRIPTEN 1 +#elif defined(__rtems__) + #define BENCHMARK_OS_RTEMS 1 +#elif defined(__Fuchsia__) +#define BENCHMARK_OS_FUCHSIA 1 +#elif defined (__SVR4) && defined (__sun) +#define BENCHMARK_OS_SOLARIS 1 +#elif defined(__QNX__) +#define BENCHMARK_OS_QNX 1 +#elif defined(__MVS__) +#define BENCHMARK_OS_ZOS 1 +#elif defined(__hexagon__) +#define BENCHMARK_OS_QURT 1 +#endif + +#if defined(__ANDROID__) && defined(__GLIBCXX__) +#define BENCHMARK_STL_ANDROID_GNUSTL 1 +#endif + +#if !__has_feature(cxx_exceptions) && !defined(__cpp_exceptions) \ + && !defined(__EXCEPTIONS) + #define BENCHMARK_HAS_NO_EXCEPTIONS +#endif + +#if defined(COMPILER_CLANG) || defined(COMPILER_GCC) + #define BENCHMARK_MAYBE_UNUSED __attribute__((unused)) +#else + #define BENCHMARK_MAYBE_UNUSED +#endif + +// clang-format on + +#endif // BENCHMARK_INTERNAL_MACROS_H_ diff --git a/third_party/benchmark/src/json_reporter.cc b/third_party/benchmark/src/json_reporter.cc new file mode 100644 index 0000000..b8c8c94 --- /dev/null +++ b/third_party/benchmark/src/json_reporter.cc @@ -0,0 +1,327 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 +#include +#include +#include // for setprecision +#include +#include +#include +#include +#include + +#include "benchmark/benchmark.h" +#include "complexity.h" +#include "string_util.h" +#include "timers.h" + +namespace benchmark { +namespace { + +std::string StrEscape(const std::string& s) { + std::string tmp; + tmp.reserve(s.size()); + for (char c : s) { + switch (c) { + case '\b': + tmp += "\\b"; + break; + case '\f': + tmp += "\\f"; + break; + case '\n': + tmp += "\\n"; + break; + case '\r': + tmp += "\\r"; + break; + case '\t': + tmp += "\\t"; + break; + case '\\': + tmp += "\\\\"; + break; + case '"': + tmp += "\\\""; + break; + default: + tmp += c; + break; + } + } + return tmp; +} + +std::string FormatKV(std::string const& key, std::string const& value) { + return StrFormat("\"%s\": \"%s\"", StrEscape(key).c_str(), + StrEscape(value).c_str()); +} + +std::string FormatKV(std::string const& key, const char* value) { + return StrFormat("\"%s\": \"%s\"", StrEscape(key).c_str(), + StrEscape(value).c_str()); +} + +std::string FormatKV(std::string const& key, bool value) { + return StrFormat("\"%s\": %s", StrEscape(key).c_str(), + value ? "true" : "false"); +} + +std::string FormatKV(std::string const& key, int64_t value) { + std::stringstream ss; + ss << '"' << StrEscape(key) << "\": " << value; + return ss.str(); +} + +std::string FormatKV(std::string const& key, double value) { + std::stringstream ss; + ss << '"' << StrEscape(key) << "\": "; + + if (std::isnan(value)) + ss << (value < 0 ? "-" : "") << "NaN"; + else if (std::isinf(value)) + ss << (value < 0 ? "-" : "") << "Infinity"; + else { + const auto max_digits10 = + std::numeric_limits::max_digits10; + const auto max_fractional_digits10 = max_digits10 - 1; + ss << std::scientific << std::setprecision(max_fractional_digits10) + << value; + } + return ss.str(); +} + +int64_t RoundDouble(double v) { return std::lround(v); } + +} // end namespace + +bool JSONReporter::ReportContext(const Context& context) { + std::ostream& out = GetOutputStream(); + + out << "{\n"; + std::string inner_indent(2, ' '); + + // Open context block and print context information. + out << inner_indent << "\"context\": {\n"; + std::string indent(4, ' '); + + std::string walltime_value = LocalDateTimeString(); + out << indent << FormatKV("date", walltime_value) << ",\n"; + + out << indent << FormatKV("host_name", context.sys_info.name) << ",\n"; + + if (Context::executable_name) { + out << indent << FormatKV("executable", Context::executable_name) << ",\n"; + } + + CPUInfo const& info = context.cpu_info; + out << indent << FormatKV("num_cpus", static_cast(info.num_cpus)) + << ",\n"; + out << indent + << FormatKV("mhz_per_cpu", + RoundDouble(info.cycles_per_second / 1000000.0)) + << ",\n"; + if (CPUInfo::Scaling::UNKNOWN != info.scaling) { + out << indent + << FormatKV("cpu_scaling_enabled", + info.scaling == CPUInfo::Scaling::ENABLED ? true : false) + << ",\n"; + } + + out << indent << "\"caches\": [\n"; + indent = std::string(6, ' '); + std::string cache_indent(8, ' '); + for (size_t i = 0; i < info.caches.size(); ++i) { + auto& CI = info.caches[i]; + out << indent << "{\n"; + out << cache_indent << FormatKV("type", CI.type) << ",\n"; + out << cache_indent << FormatKV("level", static_cast(CI.level)) + << ",\n"; + out << cache_indent << FormatKV("size", static_cast(CI.size)) + << ",\n"; + out << cache_indent + << FormatKV("num_sharing", static_cast(CI.num_sharing)) + << "\n"; + out << indent << "}"; + if (i != info.caches.size() - 1) out << ","; + out << "\n"; + } + indent = std::string(4, ' '); + out << indent << "],\n"; + out << indent << "\"load_avg\": ["; + for (auto it = info.load_avg.begin(); it != info.load_avg.end();) { + out << *it++; + if (it != info.load_avg.end()) out << ","; + } + out << "],\n"; + + out << indent << FormatKV("library_version", GetBenchmarkVersion()); + out << ",\n"; + +#if defined(NDEBUG) + const char build_type[] = "release"; +#else + const char build_type[] = "debug"; +#endif + out << indent << FormatKV("library_build_type", build_type); + out << ",\n"; + + // NOTE: our json schema is not strictly tied to the library version! + out << indent << FormatKV("json_schema_version", int64_t(1)); + + std::map* global_context = + internal::GetGlobalContext(); + + if (global_context != nullptr) { + for (const auto& kv : *global_context) { + out << ",\n"; + out << indent << FormatKV(kv.first, kv.second); + } + } + out << "\n"; + + // Close context block and open the list of benchmarks. + out << inner_indent << "},\n"; + out << inner_indent << "\"benchmarks\": [\n"; + return true; +} + +void JSONReporter::ReportRuns(std::vector const& reports) { + if (reports.empty()) { + return; + } + std::string indent(4, ' '); + std::ostream& out = GetOutputStream(); + if (!first_report_) { + out << ",\n"; + } + first_report_ = false; + + for (auto it = reports.begin(); it != reports.end(); ++it) { + out << indent << "{\n"; + PrintRunData(*it); + out << indent << '}'; + auto it_cp = it; + if (++it_cp != reports.end()) { + out << ",\n"; + } + } +} + +void JSONReporter::Finalize() { + // Close the list of benchmarks and the top level object. + GetOutputStream() << "\n ]\n}\n"; +} + +void JSONReporter::PrintRunData(Run const& run) { + std::string indent(6, ' '); + std::ostream& out = GetOutputStream(); + out << indent << FormatKV("name", run.benchmark_name()) << ",\n"; + out << indent << FormatKV("family_index", run.family_index) << ",\n"; + out << indent + << FormatKV("per_family_instance_index", run.per_family_instance_index) + << ",\n"; + out << indent << FormatKV("run_name", run.run_name.str()) << ",\n"; + out << indent << FormatKV("run_type", [&run]() -> const char* { + switch (run.run_type) { + case BenchmarkReporter::Run::RT_Iteration: + return "iteration"; + case BenchmarkReporter::Run::RT_Aggregate: + return "aggregate"; + } + BENCHMARK_UNREACHABLE(); + }()) << ",\n"; + out << indent << FormatKV("repetitions", run.repetitions) << ",\n"; + if (run.run_type != BenchmarkReporter::Run::RT_Aggregate) { + out << indent << FormatKV("repetition_index", run.repetition_index) + << ",\n"; + } + out << indent << FormatKV("threads", run.threads) << ",\n"; + if (run.run_type == BenchmarkReporter::Run::RT_Aggregate) { + out << indent << FormatKV("aggregate_name", run.aggregate_name) << ",\n"; + out << indent << FormatKV("aggregate_unit", [&run]() -> const char* { + switch (run.aggregate_unit) { + case StatisticUnit::kTime: + return "time"; + case StatisticUnit::kPercentage: + return "percentage"; + } + BENCHMARK_UNREACHABLE(); + }()) << ",\n"; + } + if (internal::SkippedWithError == run.skipped) { + out << indent << FormatKV("error_occurred", true) << ",\n"; + out << indent << FormatKV("error_message", run.skip_message) << ",\n"; + } else if (internal::SkippedWithMessage == run.skipped) { + out << indent << FormatKV("skipped", true) << ",\n"; + out << indent << FormatKV("skip_message", run.skip_message) << ",\n"; + } + if (!run.report_big_o && !run.report_rms) { + out << indent << FormatKV("iterations", run.iterations) << ",\n"; + if (run.run_type != Run::RT_Aggregate || + run.aggregate_unit == StatisticUnit::kTime) { + out << indent << FormatKV("real_time", run.GetAdjustedRealTime()) + << ",\n"; + out << indent << FormatKV("cpu_time", run.GetAdjustedCPUTime()); + } else { + assert(run.aggregate_unit == StatisticUnit::kPercentage); + out << indent << FormatKV("real_time", run.real_accumulated_time) + << ",\n"; + out << indent << FormatKV("cpu_time", run.cpu_accumulated_time); + } + out << ",\n" + << indent << FormatKV("time_unit", GetTimeUnitString(run.time_unit)); + } else if (run.report_big_o) { + out << indent << FormatKV("cpu_coefficient", run.GetAdjustedCPUTime()) + << ",\n"; + out << indent << FormatKV("real_coefficient", run.GetAdjustedRealTime()) + << ",\n"; + out << indent << FormatKV("big_o", GetBigOString(run.complexity)) << ",\n"; + out << indent << FormatKV("time_unit", GetTimeUnitString(run.time_unit)); + } else if (run.report_rms) { + out << indent << FormatKV("rms", run.GetAdjustedCPUTime()); + } + + for (auto& c : run.counters) { + out << ",\n" << indent << FormatKV(c.first, c.second); + } + + if (run.memory_result) { + const MemoryManager::Result memory_result = *run.memory_result; + out << ",\n" << indent << FormatKV("allocs_per_iter", run.allocs_per_iter); + out << ",\n" + << indent << FormatKV("max_bytes_used", memory_result.max_bytes_used); + + auto report_if_present = [&out, &indent](const std::string& label, + int64_t val) { + if (val != MemoryManager::TombstoneValue) + out << ",\n" << indent << FormatKV(label, val); + }; + + report_if_present("total_allocated_bytes", + memory_result.total_allocated_bytes); + report_if_present("net_heap_growth", memory_result.net_heap_growth); + } + + if (!run.report_label.empty()) { + out << ",\n" << indent << FormatKV("label", run.report_label); + } + out << '\n'; +} + +const int64_t MemoryManager::TombstoneValue = + std::numeric_limits::max(); + +} // end namespace benchmark diff --git a/third_party/benchmark/src/log.h b/third_party/benchmark/src/log.h new file mode 100644 index 0000000..9a21400 --- /dev/null +++ b/third_party/benchmark/src/log.h @@ -0,0 +1,88 @@ +#ifndef BENCHMARK_LOG_H_ +#define BENCHMARK_LOG_H_ + +#include +#include + +// NOTE: this is also defined in benchmark.h but we're trying to avoid a +// dependency. +// The _MSVC_LANG check should detect Visual Studio 2015 Update 3 and newer. +#if __cplusplus >= 201103L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201103L) +#define BENCHMARK_HAS_CXX11 +#endif + +namespace benchmark { +namespace internal { + +typedef std::basic_ostream&(EndLType)(std::basic_ostream&); + +class LogType { + friend LogType& GetNullLogInstance(); + friend LogType& GetErrorLogInstance(); + + // FIXME: Add locking to output. + template + friend LogType& operator<<(LogType&, Tp const&); + friend LogType& operator<<(LogType&, EndLType*); + + private: + LogType(std::ostream* out) : out_(out) {} + std::ostream* out_; + + // NOTE: we could use BENCHMARK_DISALLOW_COPY_AND_ASSIGN but we shouldn't have + // a dependency on benchmark.h from here. +#ifndef BENCHMARK_HAS_CXX11 + LogType(const LogType&); + LogType& operator=(const LogType&); +#else + LogType(const LogType&) = delete; + LogType& operator=(const LogType&) = delete; +#endif +}; + +template +LogType& operator<<(LogType& log, Tp const& value) { + if (log.out_) { + *log.out_ << value; + } + return log; +} + +inline LogType& operator<<(LogType& log, EndLType* m) { + if (log.out_) { + *log.out_ << m; + } + return log; +} + +inline int& LogLevel() { + static int log_level = 0; + return log_level; +} + +inline LogType& GetNullLogInstance() { + static LogType null_log(static_cast(nullptr)); + return null_log; +} + +inline LogType& GetErrorLogInstance() { + static LogType error_log(&std::clog); + return error_log; +} + +inline LogType& GetLogInstanceForLevel(int level) { + if (level <= LogLevel()) { + return GetErrorLogInstance(); + } + return GetNullLogInstance(); +} + +} // end namespace internal +} // end namespace benchmark + +// clang-format off +#define BM_VLOG(x) \ + (::benchmark::internal::GetLogInstanceForLevel(x) << "-- LOG(" << x << "):" \ + " ") +// clang-format on +#endif diff --git a/third_party/benchmark/src/mutex.h b/third_party/benchmark/src/mutex.h new file mode 100644 index 0000000..bec78d9 --- /dev/null +++ b/third_party/benchmark/src/mutex.h @@ -0,0 +1,155 @@ +#ifndef BENCHMARK_MUTEX_H_ +#define BENCHMARK_MUTEX_H_ + +#include +#include + +#include "check.h" + +// Enable thread safety attributes only with clang. +// The attributes can be safely erased when compiling with other compilers. +#if defined(HAVE_THREAD_SAFETY_ATTRIBUTES) +#define THREAD_ANNOTATION_ATTRIBUTE_(x) __attribute__((x)) +#else +#define THREAD_ANNOTATION_ATTRIBUTE_(x) // no-op +#endif + +#define CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE_(capability(x)) + +#define SCOPED_CAPABILITY THREAD_ANNOTATION_ATTRIBUTE_(scoped_lockable) + +#define GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE_(guarded_by(x)) + +#define PT_GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE_(pt_guarded_by(x)) + +#define ACQUIRED_BEFORE(...) \ + THREAD_ANNOTATION_ATTRIBUTE_(acquired_before(__VA_ARGS__)) + +#define ACQUIRED_AFTER(...) \ + THREAD_ANNOTATION_ATTRIBUTE_(acquired_after(__VA_ARGS__)) + +#define REQUIRES(...) \ + THREAD_ANNOTATION_ATTRIBUTE_(requires_capability(__VA_ARGS__)) + +#define REQUIRES_SHARED(...) \ + THREAD_ANNOTATION_ATTRIBUTE_(requires_shared_capability(__VA_ARGS__)) + +#define ACQUIRE(...) \ + THREAD_ANNOTATION_ATTRIBUTE_(acquire_capability(__VA_ARGS__)) + +#define ACQUIRE_SHARED(...) \ + THREAD_ANNOTATION_ATTRIBUTE_(acquire_shared_capability(__VA_ARGS__)) + +#define RELEASE(...) \ + THREAD_ANNOTATION_ATTRIBUTE_(release_capability(__VA_ARGS__)) + +#define RELEASE_SHARED(...) \ + THREAD_ANNOTATION_ATTRIBUTE_(release_shared_capability(__VA_ARGS__)) + +#define TRY_ACQUIRE(...) \ + THREAD_ANNOTATION_ATTRIBUTE_(try_acquire_capability(__VA_ARGS__)) + +#define TRY_ACQUIRE_SHARED(...) \ + THREAD_ANNOTATION_ATTRIBUTE_(try_acquire_shared_capability(__VA_ARGS__)) + +#define EXCLUDES(...) THREAD_ANNOTATION_ATTRIBUTE_(locks_excluded(__VA_ARGS__)) + +#define ASSERT_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE_(assert_capability(x)) + +#define ASSERT_SHARED_CAPABILITY(x) \ + THREAD_ANNOTATION_ATTRIBUTE_(assert_shared_capability(x)) + +#define RETURN_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE_(lock_returned(x)) + +#define NO_THREAD_SAFETY_ANALYSIS \ + THREAD_ANNOTATION_ATTRIBUTE_(no_thread_safety_analysis) + +namespace benchmark { + +typedef std::condition_variable Condition; + +// NOTE: Wrappers for std::mutex and std::unique_lock are provided so that +// we can annotate them with thread safety attributes and use the +// -Wthread-safety warning with clang. The standard library types cannot be +// used directly because they do not provide the required annotations. +class CAPABILITY("mutex") Mutex { + public: + Mutex() {} + + void lock() ACQUIRE() { mut_.lock(); } + void unlock() RELEASE() { mut_.unlock(); } + std::mutex& native_handle() { return mut_; } + + private: + std::mutex mut_; +}; + +class SCOPED_CAPABILITY MutexLock { + typedef std::unique_lock MutexLockImp; + + public: + MutexLock(Mutex& m) ACQUIRE(m) : ml_(m.native_handle()) {} + ~MutexLock() RELEASE() {} + MutexLockImp& native_handle() { return ml_; } + + private: + MutexLockImp ml_; +}; + +class Barrier { + public: + Barrier(int num_threads) : running_threads_(num_threads) {} + + // Called by each thread + bool wait() EXCLUDES(lock_) { + bool last_thread = false; + { + MutexLock ml(lock_); + last_thread = createBarrier(ml); + } + if (last_thread) phase_condition_.notify_all(); + return last_thread; + } + + void removeThread() EXCLUDES(lock_) { + MutexLock ml(lock_); + --running_threads_; + if (entered_ != 0) phase_condition_.notify_all(); + } + + private: + Mutex lock_; + Condition phase_condition_; + int running_threads_; + + // State for barrier management + int phase_number_ = 0; + int entered_ = 0; // Number of threads that have entered this barrier + + // Enter the barrier and wait until all other threads have also + // entered the barrier. Returns iff this is the last thread to + // enter the barrier. + bool createBarrier(MutexLock& ml) REQUIRES(lock_) { + BM_CHECK_LT(entered_, running_threads_); + entered_++; + if (entered_ < running_threads_) { + // Wait for all threads to enter + int phase_number_cp = phase_number_; + auto cb = [this, phase_number_cp]() { + return this->phase_number_ > phase_number_cp || + entered_ == running_threads_; // A thread has aborted in error + }; + phase_condition_.wait(ml.native_handle(), cb); + if (phase_number_ > phase_number_cp) return false; + // else (running_threads_ == entered_) and we are the last thread. + } + // Last thread has reached the barrier + phase_number_++; + entered_ = 0; + return true; + } +}; + +} // end namespace benchmark + +#endif // BENCHMARK_MUTEX_H_ diff --git a/third_party/benchmark/src/perf_counters.cc b/third_party/benchmark/src/perf_counters.cc new file mode 100644 index 0000000..2eb97eb --- /dev/null +++ b/third_party/benchmark/src/perf_counters.cc @@ -0,0 +1,283 @@ +// Copyright 2021 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 "perf_counters.h" + +#include +#include +#include + +#if defined HAVE_LIBPFM +#include "perfmon/pfmlib.h" +#include "perfmon/pfmlib_perf_event.h" +#endif + +namespace benchmark { +namespace internal { + +constexpr size_t PerfCounterValues::kMaxCounters; + +#if defined HAVE_LIBPFM + +size_t PerfCounterValues::Read(const std::vector& leaders) { + // Create a pointer for multiple reads + const size_t bufsize = values_.size() * sizeof(values_[0]); + char* ptr = reinterpret_cast(values_.data()); + size_t size = bufsize; + for (int lead : leaders) { + auto read_bytes = ::read(lead, ptr, size); + if (read_bytes >= ssize_t(sizeof(uint64_t))) { + // Actual data bytes are all bytes minus initial padding + std::size_t data_bytes = + static_cast(read_bytes) - sizeof(uint64_t); + // This should be very cheap since it's in hot cache + std::memmove(ptr, ptr + sizeof(uint64_t), data_bytes); + // Increment our counters + ptr += data_bytes; + size -= data_bytes; + } else { + int err = errno; + GetErrorLogInstance() << "Error reading lead " << lead << " errno:" << err + << " " << ::strerror(err) << "\n"; + return 0; + } + } + return (bufsize - size) / sizeof(uint64_t); +} + +const bool PerfCounters::kSupported = true; + +// Initializes libpfm only on the first call. Returns whether that single +// initialization was successful. +bool PerfCounters::Initialize() { + // Function-scope static gets initialized only once on first call. + static const bool success = []() { + return pfm_initialize() == PFM_SUCCESS; + }(); + return success; +} + +bool PerfCounters::IsCounterSupported(const std::string& name) { + Initialize(); + perf_event_attr_t attr; + std::memset(&attr, 0, sizeof(attr)); + pfm_perf_encode_arg_t arg; + std::memset(&arg, 0, sizeof(arg)); + arg.attr = &attr; + const int mode = PFM_PLM3; // user mode only + int ret = pfm_get_os_event_encoding(name.c_str(), mode, PFM_OS_PERF_EVENT_EXT, + &arg); + return (ret == PFM_SUCCESS); +} + +PerfCounters PerfCounters::Create( + const std::vector& counter_names) { + if (!counter_names.empty()) { + Initialize(); + } + + // Valid counters will populate these arrays but we start empty + std::vector valid_names; + std::vector counter_ids; + std::vector leader_ids; + + // Resize to the maximum possible + valid_names.reserve(counter_names.size()); + counter_ids.reserve(counter_names.size()); + + const int kCounterMode = PFM_PLM3; // user mode only + + // Group leads will be assigned on demand. The idea is that once we cannot + // create a counter descriptor, the reason is that this group has maxed out + // so we set the group_id again to -1 and retry - giving the algorithm a + // chance to create a new group leader to hold the next set of counters. + int group_id = -1; + + // Loop through all performance counters + for (size_t i = 0; i < counter_names.size(); ++i) { + // we are about to push into the valid names vector + // check if we did not reach the maximum + if (valid_names.size() == PerfCounterValues::kMaxCounters) { + // Log a message if we maxed out and stop adding + GetErrorLogInstance() + << counter_names.size() << " counters were requested. The maximum is " + << PerfCounterValues::kMaxCounters << " and " << valid_names.size() + << " were already added. All remaining counters will be ignored\n"; + // stop the loop and return what we have already + break; + } + + // Check if this name is empty + const auto& name = counter_names[i]; + if (name.empty()) { + GetErrorLogInstance() + << "A performance counter name was the empty string\n"; + continue; + } + + // Here first means first in group, ie the group leader + const bool is_first = (group_id < 0); + + // This struct will be populated by libpfm from the counter string + // and then fed into the syscall perf_event_open + struct perf_event_attr attr {}; + attr.size = sizeof(attr); + + // This is the input struct to libpfm. + pfm_perf_encode_arg_t arg{}; + arg.attr = &attr; + const int pfm_get = pfm_get_os_event_encoding(name.c_str(), kCounterMode, + PFM_OS_PERF_EVENT, &arg); + if (pfm_get != PFM_SUCCESS) { + GetErrorLogInstance() + << "Unknown performance counter name: " << name << "\n"; + continue; + } + + // We then proceed to populate the remaining fields in our attribute struct + // Note: the man page for perf_event_create suggests inherit = true and + // read_format = PERF_FORMAT_GROUP don't work together, but that's not the + // case. + attr.disabled = is_first; + attr.inherit = true; + attr.pinned = is_first; + attr.exclude_kernel = true; + attr.exclude_user = false; + attr.exclude_hv = true; + + // Read all counters in a group in one read. + attr.read_format = PERF_FORMAT_GROUP; + + int id = -1; + while (id < 0) { + static constexpr size_t kNrOfSyscallRetries = 5; + // Retry syscall as it was interrupted often (b/64774091). + for (size_t num_retries = 0; num_retries < kNrOfSyscallRetries; + ++num_retries) { + id = perf_event_open(&attr, 0, -1, group_id, 0); + if (id >= 0 || errno != EINTR) { + break; + } + } + if (id < 0) { + // If the file descriptor is negative we might have reached a limit + // in the current group. Set the group_id to -1 and retry + if (group_id >= 0) { + // Create a new group + group_id = -1; + } else { + // At this point we have already retried to set a new group id and + // failed. We then give up. + break; + } + } + } + + // We failed to get a new file descriptor. We might have reached a hard + // hardware limit that cannot be resolved even with group multiplexing + if (id < 0) { + GetErrorLogInstance() << "***WARNING** Failed to get a file descriptor " + "for performance counter " + << name << ". Ignoring\n"; + + // We give up on this counter but try to keep going + // as the others would be fine + continue; + } + if (group_id < 0) { + // This is a leader, store and assign it to the current file descriptor + leader_ids.push_back(id); + group_id = id; + } + // This is a valid counter, add it to our descriptor's list + counter_ids.push_back(id); + valid_names.push_back(name); + } + + // Loop through all group leaders activating them + // There is another option of starting ALL counters in a process but + // that would be far reaching an intrusion. If the user is using PMCs + // by themselves then this would have a side effect on them. It is + // friendlier to loop through all groups individually. + for (int lead : leader_ids) { + if (ioctl(lead, PERF_EVENT_IOC_ENABLE) != 0) { + // This should never happen but if it does, we give up on the + // entire batch as recovery would be a mess. + GetErrorLogInstance() << "***WARNING*** Failed to start counters. " + "Claring out all counters.\n"; + + // Close all peformance counters + for (int id : counter_ids) { + ::close(id); + } + + // Return an empty object so our internal state is still good and + // the process can continue normally without impact + return NoCounters(); + } + } + + return PerfCounters(std::move(valid_names), std::move(counter_ids), + std::move(leader_ids)); +} + +void PerfCounters::CloseCounters() const { + if (counter_ids_.empty()) { + return; + } + for (int lead : leader_ids_) { + ioctl(lead, PERF_EVENT_IOC_DISABLE); + } + for (int fd : counter_ids_) { + close(fd); + } +} +#else // defined HAVE_LIBPFM +size_t PerfCounterValues::Read(const std::vector&) { return 0; } + +const bool PerfCounters::kSupported = false; + +bool PerfCounters::Initialize() { return false; } + +bool PerfCounters::IsCounterSupported(const std::string&) { return false; } + +PerfCounters PerfCounters::Create( + const std::vector& counter_names) { + if (!counter_names.empty()) { + GetErrorLogInstance() << "Performance counters not supported.\n"; + } + return NoCounters(); +} + +void PerfCounters::CloseCounters() const {} +#endif // defined HAVE_LIBPFM + +PerfCountersMeasurement::PerfCountersMeasurement( + const std::vector& counter_names) + : start_values_(counter_names.size()), end_values_(counter_names.size()) { + counters_ = PerfCounters::Create(counter_names); +} + +PerfCounters& PerfCounters::operator=(PerfCounters&& other) noexcept { + if (this != &other) { + CloseCounters(); + + counter_ids_ = std::move(other.counter_ids_); + leader_ids_ = std::move(other.leader_ids_); + counter_names_ = std::move(other.counter_names_); + } + return *this; +} +} // namespace internal +} // namespace benchmark diff --git a/third_party/benchmark/src/perf_counters.h b/third_party/benchmark/src/perf_counters.h new file mode 100644 index 0000000..bf5eb6b --- /dev/null +++ b/third_party/benchmark/src/perf_counters.h @@ -0,0 +1,200 @@ +// Copyright 2021 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 BENCHMARK_PERF_COUNTERS_H +#define BENCHMARK_PERF_COUNTERS_H + +#include +#include +#include +#include +#include + +#include "benchmark/benchmark.h" +#include "check.h" +#include "log.h" +#include "mutex.h" + +#ifndef BENCHMARK_OS_WINDOWS +#include +#endif + +#if defined(_MSC_VER) +#pragma warning(push) +// C4251: needs to have dll-interface to be used by clients of class +#pragma warning(disable : 4251) +#endif + +namespace benchmark { +namespace internal { + +// Typically, we can only read a small number of counters. There is also a +// padding preceding counter values, when reading multiple counters with one +// syscall (which is desirable). PerfCounterValues abstracts these details. +// The implementation ensures the storage is inlined, and allows 0-based +// indexing into the counter values. +// The object is used in conjunction with a PerfCounters object, by passing it +// to Snapshot(). The Read() method relocates individual reads, discarding +// the initial padding from each group leader in the values buffer such that +// all user accesses through the [] operator are correct. +class BENCHMARK_EXPORT PerfCounterValues { + public: + explicit PerfCounterValues(size_t nr_counters) : nr_counters_(nr_counters) { + BM_CHECK_LE(nr_counters_, kMaxCounters); + } + + // We are reading correctly now so the values don't need to skip padding + uint64_t operator[](size_t pos) const { return values_[pos]; } + + // Increased the maximum to 32 only since the buffer + // is std::array<> backed + static constexpr size_t kMaxCounters = 32; + + private: + friend class PerfCounters; + // Get the byte buffer in which perf counters can be captured. + // This is used by PerfCounters::Read + std::pair get_data_buffer() { + return {reinterpret_cast(values_.data()), + sizeof(uint64_t) * (kPadding + nr_counters_)}; + } + + // This reading is complex and as the goal of this class is to + // abstract away the intrincacies of the reading process, this is + // a better place for it + size_t Read(const std::vector& leaders); + + // Move the padding to 2 due to the reading algorithm (1st padding plus a + // current read padding) + static constexpr size_t kPadding = 2; + std::array values_; + const size_t nr_counters_; +}; + +// Collect PMU counters. The object, once constructed, is ready to be used by +// calling read(). PMU counter collection is enabled from the time create() is +// called, to obtain the object, until the object's destructor is called. +class BENCHMARK_EXPORT PerfCounters final { + public: + // True iff this platform supports performance counters. + static const bool kSupported; + + // Returns an empty object + static PerfCounters NoCounters() { return PerfCounters(); } + + ~PerfCounters() { CloseCounters(); } + PerfCounters() = default; + PerfCounters(PerfCounters&&) = default; + PerfCounters(const PerfCounters&) = delete; + PerfCounters& operator=(PerfCounters&&) noexcept; + PerfCounters& operator=(const PerfCounters&) = delete; + + // Platform-specific implementations may choose to do some library + // initialization here. + static bool Initialize(); + + // Check if the given counter is supported, if the app wants to + // check before passing + static bool IsCounterSupported(const std::string& name); + + // Return a PerfCounters object ready to read the counters with the names + // specified. The values are user-mode only. The counter name format is + // implementation and OS specific. + // In case of failure, this method will in the worst case return an + // empty object whose state will still be valid. + static PerfCounters Create(const std::vector& counter_names); + + // Take a snapshot of the current value of the counters into the provided + // valid PerfCounterValues storage. The values are populated such that: + // names()[i]'s value is (*values)[i] + BENCHMARK_ALWAYS_INLINE bool Snapshot(PerfCounterValues* values) const { +#ifndef BENCHMARK_OS_WINDOWS + assert(values != nullptr); + return values->Read(leader_ids_) == counter_ids_.size(); +#else + (void)values; + return false; +#endif + } + + const std::vector& names() const { return counter_names_; } + size_t num_counters() const { return counter_names_.size(); } + + private: + PerfCounters(const std::vector& counter_names, + std::vector&& counter_ids, std::vector&& leader_ids) + : counter_ids_(std::move(counter_ids)), + leader_ids_(std::move(leader_ids)), + counter_names_(counter_names) {} + + void CloseCounters() const; + + std::vector counter_ids_; + std::vector leader_ids_; + std::vector counter_names_; +}; + +// Typical usage of the above primitives. +class BENCHMARK_EXPORT PerfCountersMeasurement final { + public: + PerfCountersMeasurement(const std::vector& counter_names); + + size_t num_counters() const { return counters_.num_counters(); } + + std::vector names() const { return counters_.names(); } + + BENCHMARK_ALWAYS_INLINE bool Start() { + if (num_counters() == 0) return true; + // Tell the compiler to not move instructions above/below where we take + // the snapshot. + ClobberMemory(); + valid_read_ &= counters_.Snapshot(&start_values_); + ClobberMemory(); + + return valid_read_; + } + + BENCHMARK_ALWAYS_INLINE bool Stop( + std::vector>& measurements) { + if (num_counters() == 0) return true; + // Tell the compiler to not move instructions above/below where we take + // the snapshot. + ClobberMemory(); + valid_read_ &= counters_.Snapshot(&end_values_); + ClobberMemory(); + + for (size_t i = 0; i < counters_.names().size(); ++i) { + double measurement = static_cast(end_values_[i]) - + static_cast(start_values_[i]); + measurements.push_back({counters_.names()[i], measurement}); + } + + return valid_read_; + } + + private: + PerfCounters counters_; + bool valid_read_ = true; + PerfCounterValues start_values_; + PerfCounterValues end_values_; +}; + +} // namespace internal +} // namespace benchmark + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif + +#endif // BENCHMARK_PERF_COUNTERS_H diff --git a/third_party/benchmark/src/re.h b/third_party/benchmark/src/re.h new file mode 100644 index 0000000..9afb869 --- /dev/null +++ b/third_party/benchmark/src/re.h @@ -0,0 +1,158 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 BENCHMARK_RE_H_ +#define BENCHMARK_RE_H_ + +#include "internal_macros.h" + +// clang-format off + +#if !defined(HAVE_STD_REGEX) && \ + !defined(HAVE_GNU_POSIX_REGEX) && \ + !defined(HAVE_POSIX_REGEX) + // No explicit regex selection; detect based on builtin hints. + #if defined(BENCHMARK_OS_LINUX) || defined(BENCHMARK_OS_APPLE) + #define HAVE_POSIX_REGEX 1 + #elif __cplusplus >= 199711L + #define HAVE_STD_REGEX 1 + #endif +#endif + +// Prefer C regex libraries when compiling w/o exceptions so that we can +// correctly report errors. +#if defined(BENCHMARK_HAS_NO_EXCEPTIONS) && \ + defined(HAVE_STD_REGEX) && \ + (defined(HAVE_GNU_POSIX_REGEX) || defined(HAVE_POSIX_REGEX)) + #undef HAVE_STD_REGEX +#endif + +#if defined(HAVE_STD_REGEX) + #include +#elif defined(HAVE_GNU_POSIX_REGEX) + #include +#elif defined(HAVE_POSIX_REGEX) + #include +#else +#error No regular expression backend was found! +#endif + +// clang-format on + +#include + +#include "check.h" + +namespace benchmark { + +// A wrapper around the POSIX regular expression API that provides automatic +// cleanup +class Regex { + public: + Regex() : init_(false) {} + + ~Regex(); + + // Compile a regular expression matcher from spec. Returns true on success. + // + // On failure (and if error is not nullptr), error is populated with a human + // readable error message if an error occurs. + bool Init(const std::string& spec, std::string* error); + + // Returns whether str matches the compiled regular expression. + bool Match(const std::string& str); + + private: + bool init_; +// Underlying regular expression object +#if defined(HAVE_STD_REGEX) + std::regex re_; +#elif defined(HAVE_POSIX_REGEX) || defined(HAVE_GNU_POSIX_REGEX) + regex_t re_; +#else +#error No regular expression backend implementation available +#endif +}; + +#if defined(HAVE_STD_REGEX) + +inline bool Regex::Init(const std::string& spec, std::string* error) { +#ifdef BENCHMARK_HAS_NO_EXCEPTIONS + ((void)error); // suppress unused warning +#else + try { +#endif + re_ = std::regex(spec, std::regex_constants::extended); + init_ = true; +#ifndef BENCHMARK_HAS_NO_EXCEPTIONS +} +catch (const std::regex_error& e) { + if (error) { + *error = e.what(); + } +} +#endif +return init_; +} + +inline Regex::~Regex() {} + +inline bool Regex::Match(const std::string& str) { + if (!init_) { + return false; + } + return std::regex_search(str, re_); +} + +#else +inline bool Regex::Init(const std::string& spec, std::string* error) { + int ec = regcomp(&re_, spec.c_str(), REG_EXTENDED | REG_NOSUB); + if (ec != 0) { + if (error) { + size_t needed = regerror(ec, &re_, nullptr, 0); + char* errbuf = new char[needed]; + regerror(ec, &re_, errbuf, needed); + + // regerror returns the number of bytes necessary to null terminate + // the string, so we move that when assigning to error. + BM_CHECK_NE(needed, 0); + error->assign(errbuf, needed - 1); + + delete[] errbuf; + } + + return false; + } + + init_ = true; + return true; +} + +inline Regex::~Regex() { + if (init_) { + regfree(&re_); + } +} + +inline bool Regex::Match(const std::string& str) { + if (!init_) { + return false; + } + return regexec(&re_, str.c_str(), 0, nullptr, 0) == 0; +} +#endif + +} // end namespace benchmark + +#endif // BENCHMARK_RE_H_ diff --git a/third_party/benchmark/src/reporter.cc b/third_party/benchmark/src/reporter.cc new file mode 100644 index 0000000..076bc31 --- /dev/null +++ b/third_party/benchmark/src/reporter.cc @@ -0,0 +1,118 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 +#include +#include +#include +#include +#include + +#include "benchmark/benchmark.h" +#include "check.h" +#include "string_util.h" +#include "timers.h" + +namespace benchmark { + +BenchmarkReporter::BenchmarkReporter() + : output_stream_(&std::cout), error_stream_(&std::cerr) {} + +BenchmarkReporter::~BenchmarkReporter() {} + +void BenchmarkReporter::PrintBasicContext(std::ostream *out, + Context const &context) { + BM_CHECK(out) << "cannot be null"; + auto &Out = *out; + +#ifndef BENCHMARK_OS_QURT + // Date/time information is not available on QuRT. + // Attempting to get it via this call cause the binary to crash. + Out << LocalDateTimeString() << "\n"; +#endif + + if (context.executable_name) + Out << "Running " << context.executable_name << "\n"; + + const CPUInfo &info = context.cpu_info; + Out << "Run on (" << info.num_cpus << " X " + << (info.cycles_per_second / 1000000.0) << " MHz CPU " + << ((info.num_cpus > 1) ? "s" : "") << ")\n"; + if (info.caches.size() != 0) { + Out << "CPU Caches:\n"; + for (auto &CInfo : info.caches) { + Out << " L" << CInfo.level << " " << CInfo.type << " " + << (CInfo.size / 1024) << " KiB"; + if (CInfo.num_sharing != 0) + Out << " (x" << (info.num_cpus / CInfo.num_sharing) << ")"; + Out << "\n"; + } + } + if (!info.load_avg.empty()) { + Out << "Load Average: "; + for (auto It = info.load_avg.begin(); It != info.load_avg.end();) { + Out << StrFormat("%.2f", *It++); + if (It != info.load_avg.end()) Out << ", "; + } + Out << "\n"; + } + + std::map *global_context = + internal::GetGlobalContext(); + + if (global_context != nullptr) { + for (const auto &kv : *global_context) { + Out << kv.first << ": " << kv.second << "\n"; + } + } + + if (CPUInfo::Scaling::ENABLED == info.scaling) { + Out << "***WARNING*** CPU scaling is enabled, the benchmark " + "real time measurements may be noisy and will incur extra " + "overhead.\n"; + } + +#ifndef NDEBUG + Out << "***WARNING*** Library was built as DEBUG. Timings may be " + "affected.\n"; +#endif +} + +// No initializer because it's already initialized to NULL. +const char *BenchmarkReporter::Context::executable_name; + +BenchmarkReporter::Context::Context() + : cpu_info(CPUInfo::Get()), sys_info(SystemInfo::Get()) {} + +std::string BenchmarkReporter::Run::benchmark_name() const { + std::string name = run_name.str(); + if (run_type == RT_Aggregate) { + name += "_" + aggregate_name; + } + return name; +} + +double BenchmarkReporter::Run::GetAdjustedRealTime() const { + double new_time = real_accumulated_time * GetTimeUnitMultiplier(time_unit); + if (iterations != 0) new_time /= static_cast(iterations); + return new_time; +} + +double BenchmarkReporter::Run::GetAdjustedCPUTime() const { + double new_time = cpu_accumulated_time * GetTimeUnitMultiplier(time_unit); + if (iterations != 0) new_time /= static_cast(iterations); + return new_time; +} + +} // end namespace benchmark diff --git a/third_party/benchmark/src/statistics.cc b/third_party/benchmark/src/statistics.cc new file mode 100644 index 0000000..16b6026 --- /dev/null +++ b/third_party/benchmark/src/statistics.cc @@ -0,0 +1,214 @@ +// Copyright 2016 Ismael Jimenez Martinez. All rights reserved. +// Copyright 2017 Roman Lebedev. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 "statistics.h" + +#include +#include +#include +#include +#include + +#include "benchmark/benchmark.h" +#include "check.h" + +namespace benchmark { + +auto StatisticsSum = [](const std::vector& v) { + return std::accumulate(v.begin(), v.end(), 0.0); +}; + +double StatisticsMean(const std::vector& v) { + if (v.empty()) return 0.0; + return StatisticsSum(v) * (1.0 / static_cast(v.size())); +} + +double StatisticsMedian(const std::vector& v) { + if (v.size() < 3) return StatisticsMean(v); + std::vector copy(v); + + auto center = copy.begin() + v.size() / 2; + std::nth_element(copy.begin(), center, copy.end()); + + // Did we have an odd number of samples? If yes, then center is the median. + // If not, then we are looking for the average between center and the value + // before. Instead of resorting, we just look for the max value before it, + // which is not necessarily the element immediately preceding `center` Since + // `copy` is only partially sorted by `nth_element`. + if (v.size() % 2 == 1) return *center; + auto center2 = std::max_element(copy.begin(), center); + return (*center + *center2) / 2.0; +} + +// Return the sum of the squares of this sample set +auto SumSquares = [](const std::vector& v) { + return std::inner_product(v.begin(), v.end(), v.begin(), 0.0); +}; + +auto Sqr = [](const double dat) { return dat * dat; }; +auto Sqrt = [](const double dat) { + // Avoid NaN due to imprecision in the calculations + if (dat < 0.0) return 0.0; + return std::sqrt(dat); +}; + +double StatisticsStdDev(const std::vector& v) { + const auto mean = StatisticsMean(v); + if (v.empty()) return mean; + + // Sample standard deviation is undefined for n = 1 + if (v.size() == 1) return 0.0; + + const double avg_squares = + SumSquares(v) * (1.0 / static_cast(v.size())); + return Sqrt(static_cast(v.size()) / + (static_cast(v.size()) - 1.0) * + (avg_squares - Sqr(mean))); +} + +double StatisticsCV(const std::vector& v) { + if (v.size() < 2) return 0.0; + + const auto stddev = StatisticsStdDev(v); + const auto mean = StatisticsMean(v); + + if (std::fpclassify(mean) == FP_ZERO) return 0.0; + + return stddev / mean; +} + +std::vector ComputeStats( + const std::vector& reports) { + typedef BenchmarkReporter::Run Run; + std::vector results; + + auto error_count = std::count_if(reports.begin(), reports.end(), + [](Run const& run) { return run.skipped; }); + + if (reports.size() - static_cast(error_count) < 2) { + // We don't report aggregated data if there was a single run. + return results; + } + + // Accumulators. + std::vector real_accumulated_time_stat; + std::vector cpu_accumulated_time_stat; + + real_accumulated_time_stat.reserve(reports.size()); + cpu_accumulated_time_stat.reserve(reports.size()); + + // All repetitions should be run with the same number of iterations so we + // can take this information from the first benchmark. + const IterationCount run_iterations = reports.front().iterations; + // create stats for user counters + struct CounterStat { + Counter c; + std::vector s; + }; + std::map counter_stats; + for (Run const& r : reports) { + for (auto const& cnt : r.counters) { + auto it = counter_stats.find(cnt.first); + if (it == counter_stats.end()) { + it = counter_stats + .emplace(cnt.first, + CounterStat{cnt.second, std::vector{}}) + .first; + it->second.s.reserve(reports.size()); + } else { + BM_CHECK_EQ(it->second.c.flags, cnt.second.flags); + } + } + } + + // Populate the accumulators. + for (Run const& run : reports) { + BM_CHECK_EQ(reports[0].benchmark_name(), run.benchmark_name()); + BM_CHECK_EQ(run_iterations, run.iterations); + if (run.skipped) continue; + real_accumulated_time_stat.emplace_back(run.real_accumulated_time); + cpu_accumulated_time_stat.emplace_back(run.cpu_accumulated_time); + // user counters + for (auto const& cnt : run.counters) { + auto it = counter_stats.find(cnt.first); + BM_CHECK_NE(it, counter_stats.end()); + it->second.s.emplace_back(cnt.second); + } + } + + // Only add label if it is same for all runs + std::string report_label = reports[0].report_label; + for (std::size_t i = 1; i < reports.size(); i++) { + if (reports[i].report_label != report_label) { + report_label = ""; + break; + } + } + + const double iteration_rescale_factor = + double(reports.size()) / double(run_iterations); + + for (const auto& Stat : *reports[0].statistics) { + // Get the data from the accumulator to BenchmarkReporter::Run's. + Run data; + data.run_name = reports[0].run_name; + data.family_index = reports[0].family_index; + data.per_family_instance_index = reports[0].per_family_instance_index; + data.run_type = BenchmarkReporter::Run::RT_Aggregate; + data.threads = reports[0].threads; + data.repetitions = reports[0].repetitions; + data.repetition_index = Run::no_repetition_index; + data.aggregate_name = Stat.name_; + data.aggregate_unit = Stat.unit_; + data.report_label = report_label; + + // It is incorrect to say that an aggregate is computed over + // run's iterations, because those iterations already got averaged. + // Similarly, if there are N repetitions with 1 iterations each, + // an aggregate will be computed over N measurements, not 1. + // Thus it is best to simply use the count of separate reports. + data.iterations = static_cast(reports.size()); + + data.real_accumulated_time = Stat.compute_(real_accumulated_time_stat); + data.cpu_accumulated_time = Stat.compute_(cpu_accumulated_time_stat); + + if (data.aggregate_unit == StatisticUnit::kTime) { + // We will divide these times by data.iterations when reporting, but the + // data.iterations is not necessarily the scale of these measurements, + // because in each repetition, these timers are sum over all the iters. + // And if we want to say that the stats are over N repetitions and not + // M iterations, we need to multiply these by (N/M). + data.real_accumulated_time *= iteration_rescale_factor; + data.cpu_accumulated_time *= iteration_rescale_factor; + } + + data.time_unit = reports[0].time_unit; + + // user counters + for (auto const& kv : counter_stats) { + // Do *NOT* rescale the custom counters. They are already properly scaled. + const auto uc_stat = Stat.compute_(kv.second.s); + auto c = Counter(uc_stat, counter_stats[kv.first].c.flags, + counter_stats[kv.first].c.oneK); + data.counters[kv.first] = c; + } + + results.push_back(data); + } + + return results; +} + +} // end namespace benchmark diff --git a/third_party/benchmark/src/statistics.h b/third_party/benchmark/src/statistics.h new file mode 100644 index 0000000..6e5560e --- /dev/null +++ b/third_party/benchmark/src/statistics.h @@ -0,0 +1,44 @@ +// Copyright 2016 Ismael Jimenez Martinez. All rights reserved. +// Copyright 2017 Roman Lebedev. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 STATISTICS_H_ +#define STATISTICS_H_ + +#include + +#include "benchmark/benchmark.h" + +namespace benchmark { + +// Return a vector containing the mean, median and standard deviation +// information (and any user-specified info) for the specified list of reports. +// If 'reports' contains less than two non-errored runs an empty vector is +// returned +BENCHMARK_EXPORT +std::vector ComputeStats( + const std::vector& reports); + +BENCHMARK_EXPORT +double StatisticsMean(const std::vector& v); +BENCHMARK_EXPORT +double StatisticsMedian(const std::vector& v); +BENCHMARK_EXPORT +double StatisticsStdDev(const std::vector& v); +BENCHMARK_EXPORT +double StatisticsCV(const std::vector& v); + +} // end namespace benchmark + +#endif // STATISTICS_H_ diff --git a/third_party/benchmark/src/string_util.cc b/third_party/benchmark/src/string_util.cc new file mode 100644 index 0000000..9ba63a7 --- /dev/null +++ b/third_party/benchmark/src/string_util.cc @@ -0,0 +1,254 @@ +#include "string_util.h" + +#include +#ifdef BENCHMARK_STL_ANDROID_GNUSTL +#include +#endif +#include +#include +#include +#include +#include + +#include "arraysize.h" +#include "benchmark/benchmark.h" + +namespace benchmark { +namespace { +// kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta. +const char* const kBigSIUnits[] = {"k", "M", "G", "T", "P", "E", "Z", "Y"}; +// Kibi, Mebi, Gibi, Tebi, Pebi, Exbi, Zebi, Yobi. +const char* const kBigIECUnits[] = {"Ki", "Mi", "Gi", "Ti", + "Pi", "Ei", "Zi", "Yi"}; +// milli, micro, nano, pico, femto, atto, zepto, yocto. +const char* const kSmallSIUnits[] = {"m", "u", "n", "p", "f", "a", "z", "y"}; + +// We require that all three arrays have the same size. +static_assert(arraysize(kBigSIUnits) == arraysize(kBigIECUnits), + "SI and IEC unit arrays must be the same size"); +static_assert(arraysize(kSmallSIUnits) == arraysize(kBigSIUnits), + "Small SI and Big SI unit arrays must be the same size"); + +static const int64_t kUnitsSize = arraysize(kBigSIUnits); + +void ToExponentAndMantissa(double val, int precision, double one_k, + std::string* mantissa, int64_t* exponent) { + std::stringstream mantissa_stream; + + if (val < 0) { + mantissa_stream << "-"; + val = -val; + } + + // Adjust threshold so that it never excludes things which can't be rendered + // in 'precision' digits. + const double adjusted_threshold = + std::max(1.0, 1.0 / std::pow(10.0, precision)); + const double big_threshold = (adjusted_threshold * one_k) - 1; + const double small_threshold = adjusted_threshold; + // Values in ]simple_threshold,small_threshold[ will be printed as-is + const double simple_threshold = 0.01; + + if (val > big_threshold) { + // Positive powers + double scaled = val; + for (size_t i = 0; i < arraysize(kBigSIUnits); ++i) { + scaled /= one_k; + if (scaled <= big_threshold) { + mantissa_stream << scaled; + *exponent = static_cast(i + 1); + *mantissa = mantissa_stream.str(); + return; + } + } + mantissa_stream << val; + *exponent = 0; + } else if (val < small_threshold) { + // Negative powers + if (val < simple_threshold) { + double scaled = val; + for (size_t i = 0; i < arraysize(kSmallSIUnits); ++i) { + scaled *= one_k; + if (scaled >= small_threshold) { + mantissa_stream << scaled; + *exponent = -static_cast(i + 1); + *mantissa = mantissa_stream.str(); + return; + } + } + } + mantissa_stream << val; + *exponent = 0; + } else { + mantissa_stream << val; + *exponent = 0; + } + *mantissa = mantissa_stream.str(); +} + +std::string ExponentToPrefix(int64_t exponent, bool iec) { + if (exponent == 0) return ""; + + const int64_t index = (exponent > 0 ? exponent - 1 : -exponent - 1); + if (index >= kUnitsSize) return ""; + + const char* const* array = + (exponent > 0 ? (iec ? kBigIECUnits : kBigSIUnits) : kSmallSIUnits); + + return std::string(array[index]); +} + +std::string ToBinaryStringFullySpecified(double value, int precision, + Counter::OneK one_k) { + std::string mantissa; + int64_t exponent; + ToExponentAndMantissa(value, precision, + one_k == Counter::kIs1024 ? 1024.0 : 1000.0, &mantissa, + &exponent); + return mantissa + ExponentToPrefix(exponent, one_k == Counter::kIs1024); +} + +std::string StrFormatImp(const char* msg, va_list args) { + // we might need a second shot at this, so pre-emptivly make a copy + va_list args_cp; + va_copy(args_cp, args); + + // TODO(ericwf): use std::array for first attempt to avoid one memory + // allocation guess what the size might be + std::array local_buff; + + // 2015-10-08: vsnprintf is used instead of snd::vsnprintf due to a limitation + // in the android-ndk + auto ret = vsnprintf(local_buff.data(), local_buff.size(), msg, args_cp); + + va_end(args_cp); + + // handle empty expansion + if (ret == 0) return std::string{}; + if (static_cast(ret) < local_buff.size()) + return std::string(local_buff.data()); + + // we did not provide a long enough buffer on our first attempt. + // add 1 to size to account for null-byte in size cast to prevent overflow + std::size_t size = static_cast(ret) + 1; + auto buff_ptr = std::unique_ptr(new char[size]); + // 2015-10-08: vsnprintf is used instead of snd::vsnprintf due to a limitation + // in the android-ndk + vsnprintf(buff_ptr.get(), size, msg, args); + return std::string(buff_ptr.get()); +} + +} // end namespace + +std::string HumanReadableNumber(double n, Counter::OneK one_k) { + return ToBinaryStringFullySpecified(n, 1, one_k); +} + +std::string StrFormat(const char* format, ...) { + va_list args; + va_start(args, format); + std::string tmp = StrFormatImp(format, args); + va_end(args); + return tmp; +} + +std::vector StrSplit(const std::string& str, char delim) { + if (str.empty()) return {}; + std::vector ret; + size_t first = 0; + size_t next = str.find(delim); + for (; next != std::string::npos; + first = next + 1, next = str.find(delim, first)) { + ret.push_back(str.substr(first, next - first)); + } + ret.push_back(str.substr(first)); + return ret; +} + +#ifdef BENCHMARK_STL_ANDROID_GNUSTL +/* + * GNU STL in Android NDK lacks support for some C++11 functions, including + * stoul, stoi, stod. We reimplement them here using C functions strtoul, + * strtol, strtod. Note that reimplemented functions are in benchmark:: + * namespace, not std:: namespace. + */ +unsigned long stoul(const std::string& str, size_t* pos, int base) { + /* Record previous errno */ + const int oldErrno = errno; + errno = 0; + + const char* strStart = str.c_str(); + char* strEnd = const_cast(strStart); + const unsigned long result = strtoul(strStart, &strEnd, base); + + const int strtoulErrno = errno; + /* Restore previous errno */ + errno = oldErrno; + + /* Check for errors and return */ + if (strtoulErrno == ERANGE) { + throw std::out_of_range("stoul failed: " + str + + " is outside of range of unsigned long"); + } else if (strEnd == strStart || strtoulErrno != 0) { + throw std::invalid_argument("stoul failed: " + str + " is not an integer"); + } + if (pos != nullptr) { + *pos = static_cast(strEnd - strStart); + } + return result; +} + +int stoi(const std::string& str, size_t* pos, int base) { + /* Record previous errno */ + const int oldErrno = errno; + errno = 0; + + const char* strStart = str.c_str(); + char* strEnd = const_cast(strStart); + const long result = strtol(strStart, &strEnd, base); + + const int strtolErrno = errno; + /* Restore previous errno */ + errno = oldErrno; + + /* Check for errors and return */ + if (strtolErrno == ERANGE || long(int(result)) != result) { + throw std::out_of_range("stoul failed: " + str + + " is outside of range of int"); + } else if (strEnd == strStart || strtolErrno != 0) { + throw std::invalid_argument("stoul failed: " + str + " is not an integer"); + } + if (pos != nullptr) { + *pos = static_cast(strEnd - strStart); + } + return int(result); +} + +double stod(const std::string& str, size_t* pos) { + /* Record previous errno */ + const int oldErrno = errno; + errno = 0; + + const char* strStart = str.c_str(); + char* strEnd = const_cast(strStart); + const double result = strtod(strStart, &strEnd); + + /* Restore previous errno */ + const int strtodErrno = errno; + errno = oldErrno; + + /* Check for errors and return */ + if (strtodErrno == ERANGE) { + throw std::out_of_range("stoul failed: " + str + + " is outside of range of int"); + } else if (strEnd == strStart || strtodErrno != 0) { + throw std::invalid_argument("stoul failed: " + str + " is not an integer"); + } + if (pos != nullptr) { + *pos = static_cast(strEnd - strStart); + } + return result; +} +#endif + +} // end namespace benchmark diff --git a/third_party/benchmark/src/string_util.h b/third_party/benchmark/src/string_util.h new file mode 100644 index 0000000..731aa2c --- /dev/null +++ b/third_party/benchmark/src/string_util.h @@ -0,0 +1,70 @@ +#ifndef BENCHMARK_STRING_UTIL_H_ +#define BENCHMARK_STRING_UTIL_H_ + +#include +#include +#include +#include + +#include "benchmark/benchmark.h" +#include "benchmark/export.h" +#include "check.h" +#include "internal_macros.h" + +namespace benchmark { + +BENCHMARK_EXPORT +std::string HumanReadableNumber(double n, Counter::OneK one_k); + +BENCHMARK_EXPORT +#if defined(__MINGW32__) +__attribute__((format(__MINGW_PRINTF_FORMAT, 1, 2))) +#elif defined(__GNUC__) +__attribute__((format(printf, 1, 2))) +#endif +std::string +StrFormat(const char* format, ...); + +inline std::ostream& StrCatImp(std::ostream& out) BENCHMARK_NOEXCEPT { + return out; +} + +template +inline std::ostream& StrCatImp(std::ostream& out, First&& f, Rest&&... rest) { + out << std::forward(f); + return StrCatImp(out, std::forward(rest)...); +} + +template +inline std::string StrCat(Args&&... args) { + std::ostringstream ss; + StrCatImp(ss, std::forward(args)...); + return ss.str(); +} + +BENCHMARK_EXPORT +std::vector StrSplit(const std::string& str, char delim); + +// Disable lint checking for this block since it re-implements C functions. +// NOLINTBEGIN +#ifdef BENCHMARK_STL_ANDROID_GNUSTL +/* + * GNU STL in Android NDK lacks support for some C++11 functions, including + * stoul, stoi, stod. We reimplement them here using C functions strtoul, + * strtol, strtod. Note that reimplemented functions are in benchmark:: + * namespace, not std:: namespace. + */ +unsigned long stoul(const std::string& str, size_t* pos = nullptr, + int base = 10); +int stoi(const std::string& str, size_t* pos = nullptr, int base = 10); +double stod(const std::string& str, size_t* pos = nullptr); +#else +using std::stod; // NOLINT(misc-unused-using-decls) +using std::stoi; // NOLINT(misc-unused-using-decls) +using std::stoul; // NOLINT(misc-unused-using-decls) +#endif +// NOLINTEND + +} // end namespace benchmark + +#endif // BENCHMARK_STRING_UTIL_H_ diff --git a/third_party/benchmark/src/sysinfo.cc b/third_party/benchmark/src/sysinfo.cc new file mode 100644 index 0000000..7261e2a --- /dev/null +++ b/third_party/benchmark/src/sysinfo.cc @@ -0,0 +1,871 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 "internal_macros.h" + +#ifdef BENCHMARK_OS_WINDOWS +#if !defined(WINVER) || WINVER < 0x0600 +#undef WINVER +#define WINVER 0x0600 +#endif // WINVER handling +#include +#undef StrCat // Don't let StrCat in string_util.h be renamed to lstrcatA +#include +#include + +#include +#else +#include +#if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT) +#include +#endif +#include +#include // this header must be included before 'sys/sysctl.h' to avoid compilation error on FreeBSD +#include +#if defined BENCHMARK_OS_FREEBSD || defined BENCHMARK_OS_MACOSX || \ + defined BENCHMARK_OS_NETBSD || defined BENCHMARK_OS_OPENBSD || \ + defined BENCHMARK_OS_DRAGONFLY +#define BENCHMARK_HAS_SYSCTL +#include +#endif +#endif +#if defined(BENCHMARK_OS_SOLARIS) +#include +#include +#endif +#if defined(BENCHMARK_OS_QNX) +#include +#endif +#if defined(BENCHMARK_OS_QURT) +#include +#endif +#if defined(BENCHMARK_HAS_PTHREAD_AFFINITY) +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "benchmark/benchmark.h" +#include "check.h" +#include "cycleclock.h" +#include "internal_macros.h" +#include "log.h" +#include "string_util.h" +#include "timers.h" + +namespace benchmark { +namespace { + +void PrintImp(std::ostream& out) { out << std::endl; } + +template +void PrintImp(std::ostream& out, First&& f, Rest&&... rest) { + out << std::forward(f); + PrintImp(out, std::forward(rest)...); +} + +template +BENCHMARK_NORETURN void PrintErrorAndDie(Args&&... args) { + PrintImp(std::cerr, std::forward(args)...); + std::exit(EXIT_FAILURE); +} + +#ifdef BENCHMARK_HAS_SYSCTL + +/// ValueUnion - A type used to correctly alias the byte-for-byte output of +/// `sysctl` with the result type it's to be interpreted as. +struct ValueUnion { + union DataT { + int32_t int32_value; + int64_t int64_value; + // For correct aliasing of union members from bytes. + char bytes[8]; + }; + using DataPtr = std::unique_ptr; + + // The size of the data union member + its trailing array size. + std::size_t size; + DataPtr buff; + + public: + ValueUnion() : size(0), buff(nullptr, &std::free) {} + + explicit ValueUnion(std::size_t buff_size) + : size(sizeof(DataT) + buff_size), + buff(::new (std::malloc(size)) DataT(), &std::free) {} + + ValueUnion(ValueUnion&& other) = default; + + explicit operator bool() const { return bool(buff); } + + char* data() const { return buff->bytes; } + + std::string GetAsString() const { return std::string(data()); } + + int64_t GetAsInteger() const { + if (size == sizeof(buff->int32_value)) + return buff->int32_value; + else if (size == sizeof(buff->int64_value)) + return buff->int64_value; + BENCHMARK_UNREACHABLE(); + } + + template + std::array GetAsArray() { + const int arr_size = sizeof(T) * N; + BM_CHECK_LE(arr_size, size); + std::array arr; + std::memcpy(arr.data(), data(), arr_size); + return arr; + } +}; + +ValueUnion GetSysctlImp(std::string const& name) { +#if defined BENCHMARK_OS_OPENBSD + int mib[2]; + + mib[0] = CTL_HW; + if ((name == "hw.ncpu") || (name == "hw.cpuspeed")) { + ValueUnion buff(sizeof(int)); + + if (name == "hw.ncpu") { + mib[1] = HW_NCPU; + } else { + mib[1] = HW_CPUSPEED; + } + + if (sysctl(mib, 2, buff.data(), &buff.size, nullptr, 0) == -1) { + return ValueUnion(); + } + return buff; + } + return ValueUnion(); +#else + std::size_t cur_buff_size = 0; + if (sysctlbyname(name.c_str(), nullptr, &cur_buff_size, nullptr, 0) == -1) + return ValueUnion(); + + ValueUnion buff(cur_buff_size); + if (sysctlbyname(name.c_str(), buff.data(), &buff.size, nullptr, 0) == 0) + return buff; + return ValueUnion(); +#endif +} + +BENCHMARK_MAYBE_UNUSED +bool GetSysctl(std::string const& name, std::string* out) { + out->clear(); + auto buff = GetSysctlImp(name); + if (!buff) return false; + out->assign(buff.data()); + return true; +} + +template ::value>::type> +bool GetSysctl(std::string const& name, Tp* out) { + *out = 0; + auto buff = GetSysctlImp(name); + if (!buff) return false; + *out = static_cast(buff.GetAsInteger()); + return true; +} + +template +bool GetSysctl(std::string const& name, std::array* out) { + auto buff = GetSysctlImp(name); + if (!buff) return false; + *out = buff.GetAsArray(); + return true; +} +#endif + +template +bool ReadFromFile(std::string const& fname, ArgT* arg) { + *arg = ArgT(); + std::ifstream f(fname.c_str()); + if (!f.is_open()) return false; + f >> *arg; + return f.good(); +} + +CPUInfo::Scaling CpuScaling(int num_cpus) { + // We don't have a valid CPU count, so don't even bother. + if (num_cpus <= 0) return CPUInfo::Scaling::UNKNOWN; +#if defined(BENCHMARK_OS_QNX) + return CPUInfo::Scaling::UNKNOWN; +#elif !defined(BENCHMARK_OS_WINDOWS) + // On Linux, the CPUfreq subsystem exposes CPU information as files on the + // local file system. If reading the exported files fails, then we may not be + // running on Linux, so we silently ignore all the read errors. + std::string res; + for (int cpu = 0; cpu < num_cpus; ++cpu) { + std::string governor_file = + StrCat("/sys/devices/system/cpu/cpu", cpu, "/cpufreq/scaling_governor"); + if (ReadFromFile(governor_file, &res) && res != "performance") + return CPUInfo::Scaling::ENABLED; + } + return CPUInfo::Scaling::DISABLED; +#else + return CPUInfo::Scaling::UNKNOWN; +#endif +} + +int CountSetBitsInCPUMap(std::string val) { + auto CountBits = [](std::string part) { + using CPUMask = std::bitset; + part = "0x" + part; + CPUMask mask(benchmark::stoul(part, nullptr, 16)); + return static_cast(mask.count()); + }; + std::size_t pos; + int total = 0; + while ((pos = val.find(',')) != std::string::npos) { + total += CountBits(val.substr(0, pos)); + val = val.substr(pos + 1); + } + if (!val.empty()) { + total += CountBits(val); + } + return total; +} + +BENCHMARK_MAYBE_UNUSED +std::vector GetCacheSizesFromKVFS() { + std::vector res; + std::string dir = "/sys/devices/system/cpu/cpu0/cache/"; + int idx = 0; + while (true) { + CPUInfo::CacheInfo info; + std::string fpath = StrCat(dir, "index", idx++, "/"); + std::ifstream f(StrCat(fpath, "size").c_str()); + if (!f.is_open()) break; + std::string suffix; + f >> info.size; + if (f.fail()) + PrintErrorAndDie("Failed while reading file '", fpath, "size'"); + if (f.good()) { + f >> suffix; + if (f.bad()) + PrintErrorAndDie( + "Invalid cache size format: failed to read size suffix"); + else if (f && suffix != "K") + PrintErrorAndDie("Invalid cache size format: Expected bytes ", suffix); + else if (suffix == "K") + info.size *= 1024; + } + if (!ReadFromFile(StrCat(fpath, "type"), &info.type)) + PrintErrorAndDie("Failed to read from file ", fpath, "type"); + if (!ReadFromFile(StrCat(fpath, "level"), &info.level)) + PrintErrorAndDie("Failed to read from file ", fpath, "level"); + std::string map_str; + if (!ReadFromFile(StrCat(fpath, "shared_cpu_map"), &map_str)) + PrintErrorAndDie("Failed to read from file ", fpath, "shared_cpu_map"); + info.num_sharing = CountSetBitsInCPUMap(map_str); + res.push_back(info); + } + + return res; +} + +#ifdef BENCHMARK_OS_MACOSX +std::vector GetCacheSizesMacOSX() { + std::vector res; + std::array cache_counts{{0, 0, 0, 0}}; + GetSysctl("hw.cacheconfig", &cache_counts); + + struct { + std::string name; + std::string type; + int level; + int num_sharing; + } cases[] = {{"hw.l1dcachesize", "Data", 1, cache_counts[1]}, + {"hw.l1icachesize", "Instruction", 1, cache_counts[1]}, + {"hw.l2cachesize", "Unified", 2, cache_counts[2]}, + {"hw.l3cachesize", "Unified", 3, cache_counts[3]}}; + for (auto& c : cases) { + int val; + if (!GetSysctl(c.name, &val)) continue; + CPUInfo::CacheInfo info; + info.type = c.type; + info.level = c.level; + info.size = val; + info.num_sharing = c.num_sharing; + res.push_back(std::move(info)); + } + return res; +} +#elif defined(BENCHMARK_OS_WINDOWS) +std::vector GetCacheSizesWindows() { + std::vector res; + DWORD buffer_size = 0; + using PInfo = SYSTEM_LOGICAL_PROCESSOR_INFORMATION; + using CInfo = CACHE_DESCRIPTOR; + + using UPtr = std::unique_ptr; + GetLogicalProcessorInformation(nullptr, &buffer_size); + UPtr buff(static_cast(std::malloc(buffer_size)), &std::free); + if (!GetLogicalProcessorInformation(buff.get(), &buffer_size)) + PrintErrorAndDie("Failed during call to GetLogicalProcessorInformation: ", + GetLastError()); + + PInfo* it = buff.get(); + PInfo* end = buff.get() + (buffer_size / sizeof(PInfo)); + + for (; it != end; ++it) { + if (it->Relationship != RelationCache) continue; + using BitSet = std::bitset; + BitSet b(it->ProcessorMask); + // To prevent duplicates, only consider caches where CPU 0 is specified + if (!b.test(0)) continue; + const CInfo& cache = it->Cache; + CPUInfo::CacheInfo C; + C.num_sharing = static_cast(b.count()); + C.level = cache.Level; + C.size = static_cast(cache.Size); + C.type = "Unknown"; + switch (cache.Type) { + case CacheUnified: + C.type = "Unified"; + break; + case CacheInstruction: + C.type = "Instruction"; + break; + case CacheData: + C.type = "Data"; + break; + case CacheTrace: + C.type = "Trace"; + break; + } + res.push_back(C); + } + return res; +} +#elif BENCHMARK_OS_QNX +std::vector GetCacheSizesQNX() { + std::vector res; + struct cacheattr_entry* cache = SYSPAGE_ENTRY(cacheattr); + uint32_t const elsize = SYSPAGE_ELEMENT_SIZE(cacheattr); + int num = SYSPAGE_ENTRY_SIZE(cacheattr) / elsize; + for (int i = 0; i < num; ++i) { + CPUInfo::CacheInfo info; + switch (cache->flags) { + case CACHE_FLAG_INSTR: + info.type = "Instruction"; + info.level = 1; + break; + case CACHE_FLAG_DATA: + info.type = "Data"; + info.level = 1; + break; + case CACHE_FLAG_UNIFIED: + info.type = "Unified"; + info.level = 2; + break; + case CACHE_FLAG_SHARED: + info.type = "Shared"; + info.level = 3; + break; + default: + continue; + break; + } + info.size = cache->line_size * cache->num_lines; + info.num_sharing = 0; + res.push_back(std::move(info)); + cache = SYSPAGE_ARRAY_ADJ_OFFSET(cacheattr, cache, elsize); + } + return res; +} +#endif + +std::vector GetCacheSizes() { +#ifdef BENCHMARK_OS_MACOSX + return GetCacheSizesMacOSX(); +#elif defined(BENCHMARK_OS_WINDOWS) + return GetCacheSizesWindows(); +#elif defined(BENCHMARK_OS_QNX) + return GetCacheSizesQNX(); +#elif defined(BENCHMARK_OS_QURT) + return std::vector(); +#else + return GetCacheSizesFromKVFS(); +#endif +} + +std::string GetSystemName() { +#if defined(BENCHMARK_OS_WINDOWS) + std::string str; + static constexpr int COUNT = MAX_COMPUTERNAME_LENGTH + 1; + TCHAR hostname[COUNT] = {'\0'}; + DWORD DWCOUNT = COUNT; + if (!GetComputerName(hostname, &DWCOUNT)) return std::string(""); +#ifndef UNICODE + str = std::string(hostname, DWCOUNT); +#else + // `WideCharToMultiByte` returns `0` when conversion fails. + int len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, hostname, + DWCOUNT, NULL, 0, NULL, NULL); + str.resize(len); + WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, hostname, DWCOUNT, &str[0], + str.size(), NULL, NULL); +#endif + return str; +#elif defined(BENCHMARK_OS_QURT) + std::string str = "Hexagon DSP"; + qurt_arch_version_t arch_version_struct; + if (qurt_sysenv_get_arch_version(&arch_version_struct) == QURT_EOK) { + str += " v"; + str += std::to_string(arch_version_struct.arch_version); + } + return str; +#else +#ifndef HOST_NAME_MAX +#ifdef BENCHMARK_HAS_SYSCTL // BSD/Mac doesn't have HOST_NAME_MAX defined +#define HOST_NAME_MAX 64 +#elif defined(BENCHMARK_OS_NACL) +#define HOST_NAME_MAX 64 +#elif defined(BENCHMARK_OS_QNX) +#define HOST_NAME_MAX 154 +#elif defined(BENCHMARK_OS_RTEMS) +#define HOST_NAME_MAX 256 +#elif defined(BENCHMARK_OS_SOLARIS) +#define HOST_NAME_MAX MAXHOSTNAMELEN +#elif defined(BENCHMARK_OS_ZOS) +#define HOST_NAME_MAX _POSIX_HOST_NAME_MAX +#else +#pragma message("HOST_NAME_MAX not defined. using 64") +#define HOST_NAME_MAX 64 +#endif +#endif // def HOST_NAME_MAX + char hostname[HOST_NAME_MAX]; + int retVal = gethostname(hostname, HOST_NAME_MAX); + if (retVal != 0) return std::string(""); + return std::string(hostname); +#endif // Catch-all POSIX block. +} + +int GetNumCPUsImpl() { +#ifdef BENCHMARK_HAS_SYSCTL + int num_cpu = -1; + if (GetSysctl("hw.ncpu", &num_cpu)) return num_cpu; + PrintErrorAndDie("Err: ", strerror(errno)); +#elif defined(BENCHMARK_OS_WINDOWS) + SYSTEM_INFO sysinfo; + // Use memset as opposed to = {} to avoid GCC missing initializer false + // positives. + std::memset(&sysinfo, 0, sizeof(SYSTEM_INFO)); + GetSystemInfo(&sysinfo); + // number of logical processors in the current group + return static_cast(sysinfo.dwNumberOfProcessors); +#elif defined(BENCHMARK_OS_SOLARIS) + // Returns -1 in case of a failure. + long num_cpu = sysconf(_SC_NPROCESSORS_ONLN); + if (num_cpu < 0) { + PrintErrorAndDie("sysconf(_SC_NPROCESSORS_ONLN) failed with error: ", + strerror(errno)); + } + return (int)num_cpu; +#elif defined(BENCHMARK_OS_QNX) + return static_cast(_syspage_ptr->num_cpu); +#elif defined(BENCHMARK_OS_QURT) + qurt_sysenv_max_hthreads_t hardware_threads; + if (qurt_sysenv_get_max_hw_threads(&hardware_threads) != QURT_EOK) { + hardware_threads.max_hthreads = 1; + } + return hardware_threads.max_hthreads; +#else + int num_cpus = 0; + int max_id = -1; + std::ifstream f("/proc/cpuinfo"); + if (!f.is_open()) { + PrintErrorAndDie("Failed to open /proc/cpuinfo"); + } +#if defined(__alpha__) + const std::string Key = "cpus detected"; +#else + const std::string Key = "processor"; +#endif + std::string ln; + while (std::getline(f, ln)) { + if (ln.empty()) continue; + std::size_t split_idx = ln.find(':'); + std::string value; +#if defined(__s390__) + // s390 has another format in /proc/cpuinfo + // it needs to be parsed differently + if (split_idx != std::string::npos) + value = ln.substr(Key.size() + 1, split_idx - Key.size() - 1); +#else + if (split_idx != std::string::npos) value = ln.substr(split_idx + 1); +#endif + if (ln.size() >= Key.size() && ln.compare(0, Key.size(), Key) == 0) { + num_cpus++; + if (!value.empty()) { + const int cur_id = benchmark::stoi(value); + max_id = std::max(cur_id, max_id); + } + } + } + if (f.bad()) { + PrintErrorAndDie("Failure reading /proc/cpuinfo"); + } + if (!f.eof()) { + PrintErrorAndDie("Failed to read to end of /proc/cpuinfo"); + } + f.close(); + + if ((max_id + 1) != num_cpus) { + fprintf(stderr, + "CPU ID assignments in /proc/cpuinfo seem messed up." + " This is usually caused by a bad BIOS.\n"); + } + return num_cpus; +#endif + BENCHMARK_UNREACHABLE(); +} + +int GetNumCPUs() { + const int num_cpus = GetNumCPUsImpl(); + if (num_cpus < 1) { + PrintErrorAndDie( + "Unable to extract number of CPUs. If your platform uses " + "/proc/cpuinfo, custom support may need to be added."); + } + return num_cpus; +} + +class ThreadAffinityGuard final { + public: + ThreadAffinityGuard() : reset_affinity(SetAffinity()) { + if (!reset_affinity) + std::cerr << "***WARNING*** Failed to set thread affinity. Estimated CPU " + "frequency may be incorrect." + << std::endl; + } + + ~ThreadAffinityGuard() { + if (!reset_affinity) return; + +#if defined(BENCHMARK_HAS_PTHREAD_AFFINITY) + int ret = pthread_setaffinity_np(self, sizeof(previous_affinity), + &previous_affinity); + if (ret == 0) return; +#elif defined(BENCHMARK_OS_WINDOWS_WIN32) + DWORD_PTR ret = SetThreadAffinityMask(self, previous_affinity); + if (ret != 0) return; +#endif // def BENCHMARK_HAS_PTHREAD_AFFINITY + PrintErrorAndDie("Failed to reset thread affinity"); + } + + ThreadAffinityGuard(ThreadAffinityGuard&&) = delete; + ThreadAffinityGuard(const ThreadAffinityGuard&) = delete; + ThreadAffinityGuard& operator=(ThreadAffinityGuard&&) = delete; + ThreadAffinityGuard& operator=(const ThreadAffinityGuard&) = delete; + + private: + bool SetAffinity() { +#if defined(BENCHMARK_HAS_PTHREAD_AFFINITY) + int ret; + self = pthread_self(); + ret = pthread_getaffinity_np(self, sizeof(previous_affinity), + &previous_affinity); + if (ret != 0) return false; + + cpu_set_t affinity; + memcpy(&affinity, &previous_affinity, sizeof(affinity)); + + bool is_first_cpu = true; + + for (int i = 0; i < CPU_SETSIZE; ++i) + if (CPU_ISSET(i, &affinity)) { + if (is_first_cpu) + is_first_cpu = false; + else + CPU_CLR(i, &affinity); + } + + if (is_first_cpu) return false; + + ret = pthread_setaffinity_np(self, sizeof(affinity), &affinity); + return ret == 0; +#elif defined(BENCHMARK_OS_WINDOWS_WIN32) + self = GetCurrentThread(); + DWORD_PTR mask = static_cast(1) << GetCurrentProcessorNumber(); + previous_affinity = SetThreadAffinityMask(self, mask); + return previous_affinity != 0; +#else + return false; +#endif // def BENCHMARK_HAS_PTHREAD_AFFINITY + } + +#if defined(BENCHMARK_HAS_PTHREAD_AFFINITY) + pthread_t self; + cpu_set_t previous_affinity; +#elif defined(BENCHMARK_OS_WINDOWS_WIN32) + HANDLE self; + DWORD_PTR previous_affinity; +#endif // def BENCHMARK_HAS_PTHREAD_AFFINITY + bool reset_affinity; +}; + +double GetCPUCyclesPerSecond(CPUInfo::Scaling scaling) { + // Currently, scaling is only used on linux path here, + // suppress diagnostics about it being unused on other paths. + (void)scaling; + +#if defined BENCHMARK_OS_LINUX || defined BENCHMARK_OS_CYGWIN + long freq; + + // If the kernel is exporting the tsc frequency use that. There are issues + // where cpuinfo_max_freq cannot be relied on because the BIOS may be + // exporintg an invalid p-state (on x86) or p-states may be used to put the + // processor in a new mode (turbo mode). Essentially, those frequencies + // cannot always be relied upon. The same reasons apply to /proc/cpuinfo as + // well. + if (ReadFromFile("/sys/devices/system/cpu/cpu0/tsc_freq_khz", &freq) + // If CPU scaling is disabled, use the *current* frequency. + // Note that we specifically don't want to read cpuinfo_cur_freq, + // because it is only readable by root. + || (scaling == CPUInfo::Scaling::DISABLED && + ReadFromFile("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq", + &freq)) + // Otherwise, if CPU scaling may be in effect, we want to use + // the *maximum* frequency, not whatever CPU speed some random processor + // happens to be using now. + || ReadFromFile("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", + &freq)) { + // The value is in kHz (as the file name suggests). For example, on a + // 2GHz warpstation, the file contains the value "2000000". + return static_cast(freq) * 1000.0; + } + + const double error_value = -1; + double bogo_clock = error_value; + + std::ifstream f("/proc/cpuinfo"); + if (!f.is_open()) { + std::cerr << "failed to open /proc/cpuinfo\n"; + return error_value; + } + + auto StartsWithKey = [](std::string const& Value, std::string const& Key) { + if (Key.size() > Value.size()) return false; + auto Cmp = [&](char X, char Y) { + return std::tolower(X) == std::tolower(Y); + }; + return std::equal(Key.begin(), Key.end(), Value.begin(), Cmp); + }; + + std::string ln; + while (std::getline(f, ln)) { + if (ln.empty()) continue; + std::size_t split_idx = ln.find(':'); + std::string value; + if (split_idx != std::string::npos) value = ln.substr(split_idx + 1); + // When parsing the "cpu MHz" and "bogomips" (fallback) entries, we only + // accept positive values. Some environments (virtual machines) report zero, + // which would cause infinite looping in WallTime_Init. + if (StartsWithKey(ln, "cpu MHz")) { + if (!value.empty()) { + double cycles_per_second = benchmark::stod(value) * 1000000.0; + if (cycles_per_second > 0) return cycles_per_second; + } + } else if (StartsWithKey(ln, "bogomips")) { + if (!value.empty()) { + bogo_clock = benchmark::stod(value) * 1000000.0; + if (bogo_clock < 0.0) bogo_clock = error_value; + } + } + } + if (f.bad()) { + std::cerr << "Failure reading /proc/cpuinfo\n"; + return error_value; + } + if (!f.eof()) { + std::cerr << "Failed to read to end of /proc/cpuinfo\n"; + return error_value; + } + f.close(); + // If we found the bogomips clock, but nothing better, we'll use it (but + // we're not happy about it); otherwise, fallback to the rough estimation + // below. + if (bogo_clock >= 0.0) return bogo_clock; + +#elif defined BENCHMARK_HAS_SYSCTL + constexpr auto* freqStr = +#if defined(BENCHMARK_OS_FREEBSD) || defined(BENCHMARK_OS_NETBSD) + "machdep.tsc_freq"; +#elif defined BENCHMARK_OS_OPENBSD + "hw.cpuspeed"; +#elif defined BENCHMARK_OS_DRAGONFLY + "hw.tsc_frequency"; +#else + "hw.cpufrequency"; +#endif + unsigned long long hz = 0; +#if defined BENCHMARK_OS_OPENBSD + if (GetSysctl(freqStr, &hz)) return static_cast(hz * 1000000); +#else + if (GetSysctl(freqStr, &hz)) return static_cast(hz); +#endif + fprintf(stderr, "Unable to determine clock rate from sysctl: %s: %s\n", + freqStr, strerror(errno)); + fprintf(stderr, + "This does not affect benchmark measurements, only the " + "metadata output.\n"); + +#elif defined BENCHMARK_OS_WINDOWS_WIN32 + // In NT, read MHz from the registry. If we fail to do so or we're in win9x + // then make a crude estimate. + DWORD data, data_size = sizeof(data); + if (IsWindowsXPOrGreater() && + SUCCEEDED( + SHGetValueA(HKEY_LOCAL_MACHINE, + "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", + "~MHz", nullptr, &data, &data_size))) + return static_cast(static_cast(data) * + static_cast(1000 * 1000)); // was mhz +#elif defined(BENCHMARK_OS_SOLARIS) + kstat_ctl_t* kc = kstat_open(); + if (!kc) { + std::cerr << "failed to open /dev/kstat\n"; + return -1; + } + kstat_t* ksp = kstat_lookup(kc, const_cast("cpu_info"), -1, + const_cast("cpu_info0")); + if (!ksp) { + std::cerr << "failed to lookup in /dev/kstat\n"; + return -1; + } + if (kstat_read(kc, ksp, NULL) < 0) { + std::cerr << "failed to read from /dev/kstat\n"; + return -1; + } + kstat_named_t* knp = (kstat_named_t*)kstat_data_lookup( + ksp, const_cast("current_clock_Hz")); + if (!knp) { + std::cerr << "failed to lookup data in /dev/kstat\n"; + return -1; + } + if (knp->data_type != KSTAT_DATA_UINT64) { + std::cerr << "current_clock_Hz is of unexpected data type: " + << knp->data_type << "\n"; + return -1; + } + double clock_hz = knp->value.ui64; + kstat_close(kc); + return clock_hz; +#elif defined(BENCHMARK_OS_QNX) + return static_cast( + static_cast(SYSPAGE_ENTRY(cpuinfo)->speed) * + static_cast(1000 * 1000)); +#elif defined(BENCHMARK_OS_QURT) + // QuRT doesn't provide any API to query Hexagon frequency. + return 1000000000; +#endif + // If we've fallen through, attempt to roughly estimate the CPU clock rate. + + // Make sure to use the same cycle counter when starting and stopping the + // cycle timer. We just pin the current thread to a cpu in the previous + // affinity set. + ThreadAffinityGuard affinity_guard; + + static constexpr double estimate_time_s = 1.0; + const double start_time = ChronoClockNow(); + const auto start_ticks = cycleclock::Now(); + + // Impose load instead of calling sleep() to make sure the cycle counter + // works. + using PRNG = std::minstd_rand; + using Result = PRNG::result_type; + PRNG rng(static_cast(start_ticks)); + + Result state = 0; + + do { + static constexpr size_t batch_size = 10000; + rng.discard(batch_size); + state += rng(); + + } while (ChronoClockNow() - start_time < estimate_time_s); + + DoNotOptimize(state); + + const auto end_ticks = cycleclock::Now(); + const double end_time = ChronoClockNow(); + + return static_cast(end_ticks - start_ticks) / (end_time - start_time); + // Reset the affinity of current thread when the lifetime of affinity_guard + // ends. +} + +std::vector GetLoadAvg() { +#if (defined BENCHMARK_OS_FREEBSD || defined(BENCHMARK_OS_LINUX) || \ + defined BENCHMARK_OS_MACOSX || defined BENCHMARK_OS_NETBSD || \ + defined BENCHMARK_OS_OPENBSD || defined BENCHMARK_OS_DRAGONFLY) && \ + !(defined(__ANDROID__) && __ANDROID_API__ < 29) + static constexpr int kMaxSamples = 3; + std::vector res(kMaxSamples, 0.0); + const size_t nelem = static_cast(getloadavg(res.data(), kMaxSamples)); + if (nelem < 1) { + res.clear(); + } else { + res.resize(nelem); + } + return res; +#else + return {}; +#endif +} + +} // end namespace + +const CPUInfo& CPUInfo::Get() { + static const CPUInfo* info = new CPUInfo(); + return *info; +} + +CPUInfo::CPUInfo() + : num_cpus(GetNumCPUs()), + scaling(CpuScaling(num_cpus)), + cycles_per_second(GetCPUCyclesPerSecond(scaling)), + caches(GetCacheSizes()), + load_avg(GetLoadAvg()) {} + +const SystemInfo& SystemInfo::Get() { + static const SystemInfo* info = new SystemInfo(); + return *info; +} + +SystemInfo::SystemInfo() : name(GetSystemName()) {} +} // end namespace benchmark diff --git a/third_party/benchmark/src/thread_manager.h b/third_party/benchmark/src/thread_manager.h new file mode 100644 index 0000000..819b3c4 --- /dev/null +++ b/third_party/benchmark/src/thread_manager.h @@ -0,0 +1,63 @@ +#ifndef BENCHMARK_THREAD_MANAGER_H +#define BENCHMARK_THREAD_MANAGER_H + +#include + +#include "benchmark/benchmark.h" +#include "mutex.h" + +namespace benchmark { +namespace internal { + +class ThreadManager { + public: + explicit ThreadManager(int num_threads) + : alive_threads_(num_threads), start_stop_barrier_(num_threads) {} + + Mutex& GetBenchmarkMutex() const RETURN_CAPABILITY(benchmark_mutex_) { + return benchmark_mutex_; + } + + bool StartStopBarrier() EXCLUDES(end_cond_mutex_) { + return start_stop_barrier_.wait(); + } + + void NotifyThreadComplete() EXCLUDES(end_cond_mutex_) { + start_stop_barrier_.removeThread(); + if (--alive_threads_ == 0) { + MutexLock lock(end_cond_mutex_); + end_condition_.notify_all(); + } + } + + void WaitForAllThreads() EXCLUDES(end_cond_mutex_) { + MutexLock lock(end_cond_mutex_); + end_condition_.wait(lock.native_handle(), + [this]() { return alive_threads_ == 0; }); + } + + struct Result { + IterationCount iterations = 0; + double real_time_used = 0; + double cpu_time_used = 0; + double manual_time_used = 0; + int64_t complexity_n = 0; + std::string report_label_; + std::string skip_message_; + internal::Skipped skipped_ = internal::NotSkipped; + UserCounters counters; + }; + GUARDED_BY(GetBenchmarkMutex()) Result results; + + private: + mutable Mutex benchmark_mutex_; + std::atomic alive_threads_; + Barrier start_stop_barrier_; + Mutex end_cond_mutex_; + Condition end_condition_; +}; + +} // namespace internal +} // namespace benchmark + +#endif // BENCHMARK_THREAD_MANAGER_H diff --git a/third_party/benchmark/src/thread_timer.h b/third_party/benchmark/src/thread_timer.h new file mode 100644 index 0000000..eb23f59 --- /dev/null +++ b/third_party/benchmark/src/thread_timer.h @@ -0,0 +1,86 @@ +#ifndef BENCHMARK_THREAD_TIMER_H +#define BENCHMARK_THREAD_TIMER_H + +#include "check.h" +#include "timers.h" + +namespace benchmark { +namespace internal { + +class ThreadTimer { + explicit ThreadTimer(bool measure_process_cpu_time_) + : measure_process_cpu_time(measure_process_cpu_time_) {} + + public: + static ThreadTimer Create() { + return ThreadTimer(/*measure_process_cpu_time_=*/false); + } + static ThreadTimer CreateProcessCpuTime() { + return ThreadTimer(/*measure_process_cpu_time_=*/true); + } + + // Called by each thread + void StartTimer() { + running_ = true; + start_real_time_ = ChronoClockNow(); + start_cpu_time_ = ReadCpuTimerOfChoice(); + } + + // Called by each thread + void StopTimer() { + BM_CHECK(running_); + running_ = false; + real_time_used_ += ChronoClockNow() - start_real_time_; + // Floating point error can result in the subtraction producing a negative + // time. Guard against that. + cpu_time_used_ += + std::max(ReadCpuTimerOfChoice() - start_cpu_time_, 0); + } + + // Called by each thread + void SetIterationTime(double seconds) { manual_time_used_ += seconds; } + + bool running() const { return running_; } + + // REQUIRES: timer is not running + double real_time_used() const { + BM_CHECK(!running_); + return real_time_used_; + } + + // REQUIRES: timer is not running + double cpu_time_used() const { + BM_CHECK(!running_); + return cpu_time_used_; + } + + // REQUIRES: timer is not running + double manual_time_used() const { + BM_CHECK(!running_); + return manual_time_used_; + } + + private: + double ReadCpuTimerOfChoice() const { + if (measure_process_cpu_time) return ProcessCPUUsage(); + return ThreadCPUUsage(); + } + + // should the thread, or the process, time be measured? + const bool measure_process_cpu_time; + + bool running_ = false; // Is the timer running + double start_real_time_ = 0; // If running_ + double start_cpu_time_ = 0; // If running_ + + // Accumulated time so far (does not contain current slice if running_) + double real_time_used_ = 0; + double cpu_time_used_ = 0; + // Manually set iteration time. User sets this with SetIterationTime(seconds). + double manual_time_used_ = 0; +}; + +} // namespace internal +} // namespace benchmark + +#endif // BENCHMARK_THREAD_TIMER_H diff --git a/third_party/benchmark/src/timers.cc b/third_party/benchmark/src/timers.cc new file mode 100644 index 0000000..d0821f3 --- /dev/null +++ b/third_party/benchmark/src/timers.cc @@ -0,0 +1,276 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 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 +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 "timers.h" + +#include "internal_macros.h" + +#ifdef BENCHMARK_OS_WINDOWS +#include +#undef StrCat // Don't let StrCat in string_util.h be renamed to lstrcatA +#include +#include +#else +#include +#if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT) +#include +#endif +#include +#include // this header must be included before 'sys/sysctl.h' to avoid compilation error on FreeBSD +#include +#if defined BENCHMARK_OS_FREEBSD || defined BENCHMARK_OS_DRAGONFLY || \ + defined BENCHMARK_OS_MACOSX +#include +#endif +#if defined(BENCHMARK_OS_MACOSX) +#include +#include +#include +#endif +#if defined(BENCHMARK_OS_QURT) +#include +#endif +#endif + +#ifdef BENCHMARK_OS_EMSCRIPTEN +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "check.h" +#include "log.h" +#include "string_util.h" + +namespace benchmark { + +// Suppress unused warnings on helper functions. +#if defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wunused-function" +#endif +#if defined(__NVCOMPILER) +#pragma diag_suppress declared_but_not_referenced +#endif + +namespace { +#if defined(BENCHMARK_OS_WINDOWS) +double MakeTime(FILETIME const& kernel_time, FILETIME const& user_time) { + ULARGE_INTEGER kernel; + ULARGE_INTEGER user; + kernel.HighPart = kernel_time.dwHighDateTime; + kernel.LowPart = kernel_time.dwLowDateTime; + user.HighPart = user_time.dwHighDateTime; + user.LowPart = user_time.dwLowDateTime; + return (static_cast(kernel.QuadPart) + + static_cast(user.QuadPart)) * + 1e-7; +} +#elif !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT) +double MakeTime(struct rusage const& ru) { + return (static_cast(ru.ru_utime.tv_sec) + + static_cast(ru.ru_utime.tv_usec) * 1e-6 + + static_cast(ru.ru_stime.tv_sec) + + static_cast(ru.ru_stime.tv_usec) * 1e-6); +} +#endif +#if defined(BENCHMARK_OS_MACOSX) +double MakeTime(thread_basic_info_data_t const& info) { + return (static_cast(info.user_time.seconds) + + static_cast(info.user_time.microseconds) * 1e-6 + + static_cast(info.system_time.seconds) + + static_cast(info.system_time.microseconds) * 1e-6); +} +#endif +#if defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_THREAD_CPUTIME_ID) +double MakeTime(struct timespec const& ts) { + return static_cast(ts.tv_sec) + + (static_cast(ts.tv_nsec) * 1e-9); +} +#endif + +BENCHMARK_NORETURN static void DiagnoseAndExit(const char* msg) { + std::cerr << "ERROR: " << msg << std::endl; + std::exit(EXIT_FAILURE); +} + +} // end namespace + +double ProcessCPUUsage() { +#if defined(BENCHMARK_OS_WINDOWS) + HANDLE proc = GetCurrentProcess(); + FILETIME creation_time; + FILETIME exit_time; + FILETIME kernel_time; + FILETIME user_time; + if (GetProcessTimes(proc, &creation_time, &exit_time, &kernel_time, + &user_time)) + return MakeTime(kernel_time, user_time); + DiagnoseAndExit("GetProccessTimes() failed"); +#elif defined(BENCHMARK_OS_QURT) + return static_cast( + qurt_timer_timetick_to_us(qurt_timer_get_ticks())) * + 1.0e-6; +#elif defined(BENCHMARK_OS_EMSCRIPTEN) + // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) returns 0 on Emscripten. + // Use Emscripten-specific API. Reported CPU time would be exactly the + // same as total time, but this is ok because there aren't long-latency + // synchronous system calls in Emscripten. + return emscripten_get_now() * 1e-3; +#elif defined(CLOCK_PROCESS_CPUTIME_ID) && !defined(BENCHMARK_OS_MACOSX) + // FIXME We want to use clock_gettime, but its not available in MacOS 10.11. + // See https://github.com/google/benchmark/pull/292 + struct timespec spec; + if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &spec) == 0) + return MakeTime(spec); + DiagnoseAndExit("clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) failed"); +#else + struct rusage ru; + if (getrusage(RUSAGE_SELF, &ru) == 0) return MakeTime(ru); + DiagnoseAndExit("getrusage(RUSAGE_SELF, ...) failed"); +#endif +} + +double ThreadCPUUsage() { +#if defined(BENCHMARK_OS_WINDOWS) + HANDLE this_thread = GetCurrentThread(); + FILETIME creation_time; + FILETIME exit_time; + FILETIME kernel_time; + FILETIME user_time; + GetThreadTimes(this_thread, &creation_time, &exit_time, &kernel_time, + &user_time); + return MakeTime(kernel_time, user_time); +#elif defined(BENCHMARK_OS_QURT) + return static_cast( + qurt_timer_timetick_to_us(qurt_timer_get_ticks())) * + 1.0e-6; +#elif defined(BENCHMARK_OS_MACOSX) + // FIXME We want to use clock_gettime, but its not available in MacOS 10.11. + // See https://github.com/google/benchmark/pull/292 + mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT; + thread_basic_info_data_t info; + mach_port_t thread = pthread_mach_thread_np(pthread_self()); + if (thread_info(thread, THREAD_BASIC_INFO, + reinterpret_cast(&info), + &count) == KERN_SUCCESS) { + return MakeTime(info); + } + DiagnoseAndExit("ThreadCPUUsage() failed when evaluating thread_info"); +#elif defined(BENCHMARK_OS_EMSCRIPTEN) + // Emscripten doesn't support traditional threads + return ProcessCPUUsage(); +#elif defined(BENCHMARK_OS_RTEMS) + // RTEMS doesn't support CLOCK_THREAD_CPUTIME_ID. See + // https://github.com/RTEMS/rtems/blob/master/cpukit/posix/src/clockgettime.c + return ProcessCPUUsage(); +#elif defined(BENCHMARK_OS_ZOS) + // z/OS doesn't support CLOCK_THREAD_CPUTIME_ID. + return ProcessCPUUsage(); +#elif defined(BENCHMARK_OS_SOLARIS) + struct rusage ru; + if (getrusage(RUSAGE_LWP, &ru) == 0) return MakeTime(ru); + DiagnoseAndExit("getrusage(RUSAGE_LWP, ...) failed"); +#elif defined(CLOCK_THREAD_CPUTIME_ID) + struct timespec ts; + if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) == 0) return MakeTime(ts); + DiagnoseAndExit("clock_gettime(CLOCK_THREAD_CPUTIME_ID, ...) failed"); +#else +#error Per-thread timing is not available on your system. +#endif +} + +std::string LocalDateTimeString() { + // Write the local time in RFC3339 format yyyy-mm-ddTHH:MM:SS+/-HH:MM. + typedef std::chrono::system_clock Clock; + std::time_t now = Clock::to_time_t(Clock::now()); + const std::size_t kTzOffsetLen = 6; + const std::size_t kTimestampLen = 19; + + std::size_t tz_len; + std::size_t timestamp_len; + long int offset_minutes; + char tz_offset_sign = '+'; + // tz_offset is set in one of three ways: + // * strftime with %z - This either returns empty or the ISO 8601 time. The + // maximum length an + // ISO 8601 string can be is 7 (e.g. -03:30, plus trailing zero). + // * snprintf with %c%02li:%02li - The maximum length is 41 (one for %c, up to + // 19 for %02li, + // one for :, up to 19 %02li, plus trailing zero). + // * A fixed string of "-00:00". The maximum length is 7 (-00:00, plus + // trailing zero). + // + // Thus, the maximum size this needs to be is 41. + char tz_offset[41]; + // Long enough buffer to avoid format-overflow warnings + char storage[128]; + +#if defined(BENCHMARK_OS_WINDOWS) + std::tm* timeinfo_p = ::localtime(&now); +#else + std::tm timeinfo; + std::tm* timeinfo_p = &timeinfo; + ::localtime_r(&now, &timeinfo); +#endif + + tz_len = std::strftime(tz_offset, sizeof(tz_offset), "%z", timeinfo_p); + + if (tz_len < kTzOffsetLen && tz_len > 1) { + // Timezone offset was written. strftime writes offset as +HHMM or -HHMM, + // RFC3339 specifies an offset as +HH:MM or -HH:MM. To convert, we parse + // the offset as an integer, then reprint it to a string. + + offset_minutes = ::strtol(tz_offset, NULL, 10); + if (offset_minutes < 0) { + offset_minutes *= -1; + tz_offset_sign = '-'; + } + + tz_len = static_cast( + ::snprintf(tz_offset, sizeof(tz_offset), "%c%02li:%02li", + tz_offset_sign, offset_minutes / 100, offset_minutes % 100)); + BM_CHECK(tz_len == kTzOffsetLen); + ((void)tz_len); // Prevent unused variable warning in optimized build. + } else { + // Unknown offset. RFC3339 specifies that unknown local offsets should be + // written as UTC time with -00:00 timezone. +#if defined(BENCHMARK_OS_WINDOWS) + // Potential race condition if another thread calls localtime or gmtime. + timeinfo_p = ::gmtime(&now); +#else + ::gmtime_r(&now, &timeinfo); +#endif + + strncpy(tz_offset, "-00:00", kTzOffsetLen + 1); + } + + timestamp_len = + std::strftime(storage, sizeof(storage), "%Y-%m-%dT%H:%M:%S", timeinfo_p); + BM_CHECK(timestamp_len == kTimestampLen); + // Prevent unused variable warning in optimized build. + ((void)kTimestampLen); + + std::strncat(storage, tz_offset, sizeof(storage) - timestamp_len - 1); + return std::string(storage); +} + +} // end namespace benchmark diff --git a/third_party/benchmark/src/timers.h b/third_party/benchmark/src/timers.h new file mode 100644 index 0000000..65606cc --- /dev/null +++ b/third_party/benchmark/src/timers.h @@ -0,0 +1,48 @@ +#ifndef BENCHMARK_TIMERS_H +#define BENCHMARK_TIMERS_H + +#include +#include + +namespace benchmark { + +// Return the CPU usage of the current process +double ProcessCPUUsage(); + +// Return the CPU usage of the children of the current process +double ChildrenCPUUsage(); + +// Return the CPU usage of the current thread +double ThreadCPUUsage(); + +#if defined(HAVE_STEADY_CLOCK) +template +struct ChooseSteadyClock { + typedef std::chrono::high_resolution_clock type; +}; + +template <> +struct ChooseSteadyClock { + typedef std::chrono::steady_clock type; +}; +#endif + +struct ChooseClockType { +#if defined(HAVE_STEADY_CLOCK) + typedef ChooseSteadyClock<>::type type; +#else + typedef std::chrono::high_resolution_clock type; +#endif +}; + +inline double ChronoClockNow() { + typedef ChooseClockType::type ClockType; + using FpSeconds = std::chrono::duration; + return FpSeconds(ClockType::now().time_since_epoch()).count(); +} + +std::string LocalDateTimeString(); + +} // end namespace benchmark + +#endif // BENCHMARK_TIMERS_H diff --git a/third_party/benchmark/tools/BUILD.bazel b/third_party/benchmark/tools/BUILD.bazel new file mode 100644 index 0000000..8ef6a86 --- /dev/null +++ b/third_party/benchmark/tools/BUILD.bazel @@ -0,0 +1,20 @@ +load("@tools_pip_deps//:requirements.bzl", "requirement") + +py_library( + name = "gbench", + srcs = glob(["gbench/*.py"]), + deps = [ + requirement("numpy"), + requirement("scipy"), + ], +) + +py_binary( + name = "compare", + srcs = ["compare.py"], + imports = ["."], + python_version = "PY3", + deps = [ + ":gbench", + ], +) diff --git a/third_party/benchmark/tools/compare.py b/third_party/benchmark/tools/compare.py new file mode 100755 index 0000000..7572520 --- /dev/null +++ b/third_party/benchmark/tools/compare.py @@ -0,0 +1,523 @@ +#!/usr/bin/env python3 + +# type: ignore + +""" +compare.py - versatile benchmark output compare tool +""" + +import argparse +import json +import os +import sys +import unittest +from argparse import ArgumentParser + +import gbench +from gbench import report, util + + +def check_inputs(in1, in2, flags): + """ + Perform checking on the user provided inputs and diagnose any abnormalities + """ + in1_kind, in1_err = util.classify_input_file(in1) + in2_kind, in2_err = util.classify_input_file(in2) + output_file = util.find_benchmark_flag("--benchmark_out=", flags) + output_type = util.find_benchmark_flag("--benchmark_out_format=", flags) + if ( + in1_kind == util.IT_Executable + and in2_kind == util.IT_Executable + and output_file + ): + print( + ( + "WARNING: '--benchmark_out=%s' will be passed to both " + "benchmarks causing it to be overwritten" + ) + % output_file + ) + if in1_kind == util.IT_JSON and in2_kind == util.IT_JSON: + # When both sides are JSON the only supported flag is + # --benchmark_filter= + for flag in util.remove_benchmark_flags("--benchmark_filter=", flags): + print( + "WARNING: passing %s has no effect since both " + "inputs are JSON" % flag + ) + if output_type is not None and output_type != "json": + print( + ( + "ERROR: passing '--benchmark_out_format=%s' to 'compare.py`" + " is not supported." + ) + % output_type + ) + sys.exit(1) + + +def create_parser(): + parser = ArgumentParser( + description="versatile benchmark output compare tool" + ) + + parser.add_argument( + "-a", + "--display_aggregates_only", + dest="display_aggregates_only", + action="store_true", + help="If there are repetitions, by default, we display everything - the" + " actual runs, and the aggregates computed. Sometimes, it is " + "desirable to only view the aggregates. E.g. when there are a lot " + "of repetitions. Do note that only the display is affected. " + "Internally, all the actual runs are still used, e.g. for U test.", + ) + + parser.add_argument( + "--no-color", + dest="color", + default=True, + action="store_false", + help="Do not use colors in the terminal output", + ) + + parser.add_argument( + "-d", + "--dump_to_json", + dest="dump_to_json", + help="Additionally, dump benchmark comparison output to this file in JSON format.", + ) + + utest = parser.add_argument_group() + utest.add_argument( + "--no-utest", + dest="utest", + default=True, + action="store_false", + help="The tool can do a two-tailed Mann-Whitney U test with the null hypothesis that it is equally likely that a randomly selected value from one sample will be less than or greater than a randomly selected value from a second sample.\nWARNING: requires **LARGE** (no less than {}) number of repetitions to be meaningful!\nThe test is being done by default, if at least {} repetitions were done.\nThis option can disable the U Test.".format( + report.UTEST_OPTIMAL_REPETITIONS, report.UTEST_MIN_REPETITIONS + ), + ) + alpha_default = 0.05 + utest.add_argument( + "--alpha", + dest="utest_alpha", + default=alpha_default, + type=float, + help=( + "significance level alpha. if the calculated p-value is below this value, then the result is said to be statistically significant and the null hypothesis is rejected.\n(default: %0.4f)" + ) + % alpha_default, + ) + + subparsers = parser.add_subparsers( + help="This tool has multiple modes of operation:", dest="mode" + ) + + parser_a = subparsers.add_parser( + "benchmarks", + help="The most simple use-case, compare all the output of these two benchmarks", + ) + baseline = parser_a.add_argument_group("baseline", "The benchmark baseline") + baseline.add_argument( + "test_baseline", + metavar="test_baseline", + type=argparse.FileType("r"), + nargs=1, + help="A benchmark executable or JSON output file", + ) + contender = parser_a.add_argument_group( + "contender", "The benchmark that will be compared against the baseline" + ) + contender.add_argument( + "test_contender", + metavar="test_contender", + type=argparse.FileType("r"), + nargs=1, + help="A benchmark executable or JSON output file", + ) + parser_a.add_argument( + "benchmark_options", + metavar="benchmark_options", + nargs=argparse.REMAINDER, + help="Arguments to pass when running benchmark executables", + ) + + parser_b = subparsers.add_parser( + "filters", help="Compare filter one with the filter two of benchmark" + ) + baseline = parser_b.add_argument_group("baseline", "The benchmark baseline") + baseline.add_argument( + "test", + metavar="test", + type=argparse.FileType("r"), + nargs=1, + help="A benchmark executable or JSON output file", + ) + baseline.add_argument( + "filter_baseline", + metavar="filter_baseline", + type=str, + nargs=1, + help="The first filter, that will be used as baseline", + ) + contender = parser_b.add_argument_group( + "contender", "The benchmark that will be compared against the baseline" + ) + contender.add_argument( + "filter_contender", + metavar="filter_contender", + type=str, + nargs=1, + help="The second filter, that will be compared against the baseline", + ) + parser_b.add_argument( + "benchmark_options", + metavar="benchmark_options", + nargs=argparse.REMAINDER, + help="Arguments to pass when running benchmark executables", + ) + + parser_c = subparsers.add_parser( + "benchmarksfiltered", + help="Compare filter one of first benchmark with filter two of the second benchmark", + ) + baseline = parser_c.add_argument_group("baseline", "The benchmark baseline") + baseline.add_argument( + "test_baseline", + metavar="test_baseline", + type=argparse.FileType("r"), + nargs=1, + help="A benchmark executable or JSON output file", + ) + baseline.add_argument( + "filter_baseline", + metavar="filter_baseline", + type=str, + nargs=1, + help="The first filter, that will be used as baseline", + ) + contender = parser_c.add_argument_group( + "contender", "The benchmark that will be compared against the baseline" + ) + contender.add_argument( + "test_contender", + metavar="test_contender", + type=argparse.FileType("r"), + nargs=1, + help="The second benchmark executable or JSON output file, that will be compared against the baseline", + ) + contender.add_argument( + "filter_contender", + metavar="filter_contender", + type=str, + nargs=1, + help="The second filter, that will be compared against the baseline", + ) + parser_c.add_argument( + "benchmark_options", + metavar="benchmark_options", + nargs=argparse.REMAINDER, + help="Arguments to pass when running benchmark executables", + ) + + return parser + + +def main(): + # Parse the command line flags + parser = create_parser() + args, unknown_args = parser.parse_known_args() + if args.mode is None: + parser.print_help() + exit(1) + assert not unknown_args + benchmark_options = args.benchmark_options + + if args.mode == "benchmarks": + test_baseline = args.test_baseline[0].name + test_contender = args.test_contender[0].name + filter_baseline = "" + filter_contender = "" + + # NOTE: if test_baseline == test_contender, you are analyzing the stdev + + description = "Comparing %s to %s" % (test_baseline, test_contender) + elif args.mode == "filters": + test_baseline = args.test[0].name + test_contender = args.test[0].name + filter_baseline = args.filter_baseline[0] + filter_contender = args.filter_contender[0] + + # NOTE: if filter_baseline == filter_contender, you are analyzing the + # stdev + + description = "Comparing %s to %s (from %s)" % ( + filter_baseline, + filter_contender, + args.test[0].name, + ) + elif args.mode == "benchmarksfiltered": + test_baseline = args.test_baseline[0].name + test_contender = args.test_contender[0].name + filter_baseline = args.filter_baseline[0] + filter_contender = args.filter_contender[0] + + # NOTE: if test_baseline == test_contender and + # filter_baseline == filter_contender, you are analyzing the stdev + + description = "Comparing %s (from %s) to %s (from %s)" % ( + filter_baseline, + test_baseline, + filter_contender, + test_contender, + ) + else: + # should never happen + print("Unrecognized mode of operation: '%s'" % args.mode) + parser.print_help() + exit(1) + + check_inputs(test_baseline, test_contender, benchmark_options) + + if args.display_aggregates_only: + benchmark_options += ["--benchmark_display_aggregates_only=true"] + + options_baseline = [] + options_contender = [] + + if filter_baseline and filter_contender: + options_baseline = ["--benchmark_filter=%s" % filter_baseline] + options_contender = ["--benchmark_filter=%s" % filter_contender] + + # Run the benchmarks and report the results + json1 = json1_orig = gbench.util.sort_benchmark_results( + gbench.util.run_or_load_benchmark( + test_baseline, benchmark_options + options_baseline + ) + ) + json2 = json2_orig = gbench.util.sort_benchmark_results( + gbench.util.run_or_load_benchmark( + test_contender, benchmark_options + options_contender + ) + ) + + # Now, filter the benchmarks so that the difference report can work + if filter_baseline and filter_contender: + replacement = "[%s vs. %s]" % (filter_baseline, filter_contender) + json1 = gbench.report.filter_benchmark( + json1_orig, filter_baseline, replacement + ) + json2 = gbench.report.filter_benchmark( + json2_orig, filter_contender, replacement + ) + + diff_report = gbench.report.get_difference_report(json1, json2, args.utest) + output_lines = gbench.report.print_difference_report( + diff_report, + args.display_aggregates_only, + args.utest, + args.utest_alpha, + args.color, + ) + print(description) + for ln in output_lines: + print(ln) + + # Optionally, diff and output to JSON + if args.dump_to_json is not None: + with open(args.dump_to_json, "w") as f_json: + json.dump(diff_report, f_json, indent=1) + + +class TestParser(unittest.TestCase): + def setUp(self): + self.parser = create_parser() + testInputs = os.path.join( + os.path.dirname(os.path.realpath(__file__)), "gbench", "Inputs" + ) + self.testInput0 = os.path.join(testInputs, "test1_run1.json") + self.testInput1 = os.path.join(testInputs, "test1_run2.json") + + def test_benchmarks_basic(self): + parsed = self.parser.parse_args( + ["benchmarks", self.testInput0, self.testInput1] + ) + self.assertFalse(parsed.display_aggregates_only) + self.assertTrue(parsed.utest) + self.assertEqual(parsed.mode, "benchmarks") + self.assertEqual(parsed.test_baseline[0].name, self.testInput0) + self.assertEqual(parsed.test_contender[0].name, self.testInput1) + self.assertFalse(parsed.benchmark_options) + + def test_benchmarks_basic_without_utest(self): + parsed = self.parser.parse_args( + ["--no-utest", "benchmarks", self.testInput0, self.testInput1] + ) + self.assertFalse(parsed.display_aggregates_only) + self.assertFalse(parsed.utest) + self.assertEqual(parsed.utest_alpha, 0.05) + self.assertEqual(parsed.mode, "benchmarks") + self.assertEqual(parsed.test_baseline[0].name, self.testInput0) + self.assertEqual(parsed.test_contender[0].name, self.testInput1) + self.assertFalse(parsed.benchmark_options) + + def test_benchmarks_basic_display_aggregates_only(self): + parsed = self.parser.parse_args( + ["-a", "benchmarks", self.testInput0, self.testInput1] + ) + self.assertTrue(parsed.display_aggregates_only) + self.assertTrue(parsed.utest) + self.assertEqual(parsed.mode, "benchmarks") + self.assertEqual(parsed.test_baseline[0].name, self.testInput0) + self.assertEqual(parsed.test_contender[0].name, self.testInput1) + self.assertFalse(parsed.benchmark_options) + + def test_benchmarks_basic_with_utest_alpha(self): + parsed = self.parser.parse_args( + ["--alpha=0.314", "benchmarks", self.testInput0, self.testInput1] + ) + self.assertFalse(parsed.display_aggregates_only) + self.assertTrue(parsed.utest) + self.assertEqual(parsed.utest_alpha, 0.314) + self.assertEqual(parsed.mode, "benchmarks") + self.assertEqual(parsed.test_baseline[0].name, self.testInput0) + self.assertEqual(parsed.test_contender[0].name, self.testInput1) + self.assertFalse(parsed.benchmark_options) + + def test_benchmarks_basic_without_utest_with_utest_alpha(self): + parsed = self.parser.parse_args( + [ + "--no-utest", + "--alpha=0.314", + "benchmarks", + self.testInput0, + self.testInput1, + ] + ) + self.assertFalse(parsed.display_aggregates_only) + self.assertFalse(parsed.utest) + self.assertEqual(parsed.utest_alpha, 0.314) + self.assertEqual(parsed.mode, "benchmarks") + self.assertEqual(parsed.test_baseline[0].name, self.testInput0) + self.assertEqual(parsed.test_contender[0].name, self.testInput1) + self.assertFalse(parsed.benchmark_options) + + def test_benchmarks_with_remainder(self): + parsed = self.parser.parse_args( + ["benchmarks", self.testInput0, self.testInput1, "d"] + ) + self.assertFalse(parsed.display_aggregates_only) + self.assertTrue(parsed.utest) + self.assertEqual(parsed.mode, "benchmarks") + self.assertEqual(parsed.test_baseline[0].name, self.testInput0) + self.assertEqual(parsed.test_contender[0].name, self.testInput1) + self.assertEqual(parsed.benchmark_options, ["d"]) + + def test_benchmarks_with_remainder_after_doubleminus(self): + parsed = self.parser.parse_args( + ["benchmarks", self.testInput0, self.testInput1, "--", "e"] + ) + self.assertFalse(parsed.display_aggregates_only) + self.assertTrue(parsed.utest) + self.assertEqual(parsed.mode, "benchmarks") + self.assertEqual(parsed.test_baseline[0].name, self.testInput0) + self.assertEqual(parsed.test_contender[0].name, self.testInput1) + self.assertEqual(parsed.benchmark_options, ["e"]) + + def test_filters_basic(self): + parsed = self.parser.parse_args(["filters", self.testInput0, "c", "d"]) + self.assertFalse(parsed.display_aggregates_only) + self.assertTrue(parsed.utest) + self.assertEqual(parsed.mode, "filters") + self.assertEqual(parsed.test[0].name, self.testInput0) + self.assertEqual(parsed.filter_baseline[0], "c") + self.assertEqual(parsed.filter_contender[0], "d") + self.assertFalse(parsed.benchmark_options) + + def test_filters_with_remainder(self): + parsed = self.parser.parse_args( + ["filters", self.testInput0, "c", "d", "e"] + ) + self.assertFalse(parsed.display_aggregates_only) + self.assertTrue(parsed.utest) + self.assertEqual(parsed.mode, "filters") + self.assertEqual(parsed.test[0].name, self.testInput0) + self.assertEqual(parsed.filter_baseline[0], "c") + self.assertEqual(parsed.filter_contender[0], "d") + self.assertEqual(parsed.benchmark_options, ["e"]) + + def test_filters_with_remainder_after_doubleminus(self): + parsed = self.parser.parse_args( + ["filters", self.testInput0, "c", "d", "--", "f"] + ) + self.assertFalse(parsed.display_aggregates_only) + self.assertTrue(parsed.utest) + self.assertEqual(parsed.mode, "filters") + self.assertEqual(parsed.test[0].name, self.testInput0) + self.assertEqual(parsed.filter_baseline[0], "c") + self.assertEqual(parsed.filter_contender[0], "d") + self.assertEqual(parsed.benchmark_options, ["f"]) + + def test_benchmarksfiltered_basic(self): + parsed = self.parser.parse_args( + ["benchmarksfiltered", self.testInput0, "c", self.testInput1, "e"] + ) + self.assertFalse(parsed.display_aggregates_only) + self.assertTrue(parsed.utest) + self.assertEqual(parsed.mode, "benchmarksfiltered") + self.assertEqual(parsed.test_baseline[0].name, self.testInput0) + self.assertEqual(parsed.filter_baseline[0], "c") + self.assertEqual(parsed.test_contender[0].name, self.testInput1) + self.assertEqual(parsed.filter_contender[0], "e") + self.assertFalse(parsed.benchmark_options) + + def test_benchmarksfiltered_with_remainder(self): + parsed = self.parser.parse_args( + [ + "benchmarksfiltered", + self.testInput0, + "c", + self.testInput1, + "e", + "f", + ] + ) + self.assertFalse(parsed.display_aggregates_only) + self.assertTrue(parsed.utest) + self.assertEqual(parsed.mode, "benchmarksfiltered") + self.assertEqual(parsed.test_baseline[0].name, self.testInput0) + self.assertEqual(parsed.filter_baseline[0], "c") + self.assertEqual(parsed.test_contender[0].name, self.testInput1) + self.assertEqual(parsed.filter_contender[0], "e") + self.assertEqual(parsed.benchmark_options[0], "f") + + def test_benchmarksfiltered_with_remainder_after_doubleminus(self): + parsed = self.parser.parse_args( + [ + "benchmarksfiltered", + self.testInput0, + "c", + self.testInput1, + "e", + "--", + "g", + ] + ) + self.assertFalse(parsed.display_aggregates_only) + self.assertTrue(parsed.utest) + self.assertEqual(parsed.mode, "benchmarksfiltered") + self.assertEqual(parsed.test_baseline[0].name, self.testInput0) + self.assertEqual(parsed.filter_baseline[0], "c") + self.assertEqual(parsed.test_contender[0].name, self.testInput1) + self.assertEqual(parsed.filter_contender[0], "e") + self.assertEqual(parsed.benchmark_options[0], "g") + + +if __name__ == "__main__": + # unittest.main() + main() + +# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 +# kate: tab-width: 4; replace-tabs on; indent-width 4; tab-indents: off; +# kate: indent-mode python; remove-trailing-spaces modified; diff --git a/third_party/benchmark/tools/gbench/Inputs/test1_run1.json b/third_party/benchmark/tools/gbench/Inputs/test1_run1.json new file mode 100644 index 0000000..9daed0b --- /dev/null +++ b/third_party/benchmark/tools/gbench/Inputs/test1_run1.json @@ -0,0 +1,127 @@ +{ + "context": { + "date": "2016-08-02 17:44:46", + "num_cpus": 4, + "mhz_per_cpu": 4228, + "cpu_scaling_enabled": false, + "library_build_type": "release" + }, + "benchmarks": [ + { + "name": "BM_SameTimes", + "iterations": 1000, + "real_time": 10, + "cpu_time": 10, + "time_unit": "ns" + }, + { + "name": "BM_2xFaster", + "iterations": 1000, + "real_time": 50, + "cpu_time": 50, + "time_unit": "ns" + }, + { + "name": "BM_2xSlower", + "iterations": 1000, + "real_time": 50, + "cpu_time": 50, + "time_unit": "ns" + }, + { + "name": "BM_1PercentFaster", + "iterations": 1000, + "real_time": 100, + "cpu_time": 100, + "time_unit": "ns" + }, + { + "name": "BM_1PercentSlower", + "iterations": 1000, + "real_time": 100, + "cpu_time": 100, + "time_unit": "ns" + }, + { + "name": "BM_10PercentFaster", + "iterations": 1000, + "real_time": 100, + "cpu_time": 100, + "time_unit": "ns" + }, + { + "name": "BM_10PercentSlower", + "iterations": 1000, + "real_time": 100, + "cpu_time": 100, + "time_unit": "ns" + }, + { + "name": "BM_100xSlower", + "iterations": 1000, + "real_time": 100, + "cpu_time": 100, + "time_unit": "ns" + }, + { + "name": "BM_100xFaster", + "iterations": 1000, + "real_time": 10000, + "cpu_time": 10000, + "time_unit": "ns" + }, + { + "name": "BM_10PercentCPUToTime", + "iterations": 1000, + "real_time": 100, + "cpu_time": 100, + "time_unit": "ns" + }, + { + "name": "BM_ThirdFaster", + "iterations": 1000, + "real_time": 100, + "cpu_time": 100, + "time_unit": "ns" + }, + { + "name": "MyComplexityTest_BigO", + "run_name": "MyComplexityTest", + "run_type": "aggregate", + "aggregate_name": "BigO", + "cpu_coefficient": 4.2749856294592886e+00, + "real_coefficient": 6.4789275289789780e+00, + "big_o": "N", + "time_unit": "ns" + }, + { + "name": "MyComplexityTest_RMS", + "run_name": "MyComplexityTest", + "run_type": "aggregate", + "aggregate_name": "RMS", + "rms": 4.5097802512472874e-03 + }, + { + "name": "BM_NotBadTimeUnit", + "iterations": 1000, + "real_time": 0.4, + "cpu_time": 0.5, + "time_unit": "s" + }, + { + "name": "BM_DifferentTimeUnit", + "iterations": 1, + "real_time": 1, + "cpu_time": 1, + "time_unit": "s" + }, + { + "name": "BM_hasLabel", + "label": "a label", + "iterations": 1, + "real_time": 1, + "cpu_time": 1, + "time_unit": "s" + } + ] +} diff --git a/third_party/benchmark/tools/gbench/Inputs/test1_run2.json b/third_party/benchmark/tools/gbench/Inputs/test1_run2.json new file mode 100644 index 0000000..dc52970 --- /dev/null +++ b/third_party/benchmark/tools/gbench/Inputs/test1_run2.json @@ -0,0 +1,127 @@ +{ + "context": { + "date": "2016-08-02 17:44:46", + "num_cpus": 4, + "mhz_per_cpu": 4228, + "cpu_scaling_enabled": false, + "library_build_type": "release" + }, + "benchmarks": [ + { + "name": "BM_SameTimes", + "iterations": 1000, + "real_time": 10, + "cpu_time": 10, + "time_unit": "ns" + }, + { + "name": "BM_2xFaster", + "iterations": 1000, + "real_time": 25, + "cpu_time": 25, + "time_unit": "ns" + }, + { + "name": "BM_2xSlower", + "iterations": 20833333, + "real_time": 100, + "cpu_time": 100, + "time_unit": "ns" + }, + { + "name": "BM_1PercentFaster", + "iterations": 1000, + "real_time": 98.9999999, + "cpu_time": 98.9999999, + "time_unit": "ns" + }, + { + "name": "BM_1PercentSlower", + "iterations": 1000, + "real_time": 100.9999999, + "cpu_time": 100.9999999, + "time_unit": "ns" + }, + { + "name": "BM_10PercentFaster", + "iterations": 1000, + "real_time": 90, + "cpu_time": 90, + "time_unit": "ns" + }, + { + "name": "BM_10PercentSlower", + "iterations": 1000, + "real_time": 110, + "cpu_time": 110, + "time_unit": "ns" + }, + { + "name": "BM_100xSlower", + "iterations": 1000, + "real_time": 1.0000e+04, + "cpu_time": 1.0000e+04, + "time_unit": "ns" + }, + { + "name": "BM_100xFaster", + "iterations": 1000, + "real_time": 100, + "cpu_time": 100, + "time_unit": "ns" + }, + { + "name": "BM_10PercentCPUToTime", + "iterations": 1000, + "real_time": 110, + "cpu_time": 90, + "time_unit": "ns" + }, + { + "name": "BM_ThirdFaster", + "iterations": 1000, + "real_time": 66.665, + "cpu_time": 66.664, + "time_unit": "ns" + }, + { + "name": "MyComplexityTest_BigO", + "run_name": "MyComplexityTest", + "run_type": "aggregate", + "aggregate_name": "BigO", + "cpu_coefficient": 5.6215779594361486e+00, + "real_coefficient": 5.6288314793554610e+00, + "big_o": "N", + "time_unit": "ns" + }, + { + "name": "MyComplexityTest_RMS", + "run_name": "MyComplexityTest", + "run_type": "aggregate", + "aggregate_name": "RMS", + "rms": 3.3128901852342174e-03 + }, + { + "name": "BM_NotBadTimeUnit", + "iterations": 1000, + "real_time": 0.04, + "cpu_time": 0.6, + "time_unit": "s" + }, + { + "name": "BM_DifferentTimeUnit", + "iterations": 1, + "real_time": 1, + "cpu_time": 1, + "time_unit": "ns" + }, + { + "name": "BM_hasLabel", + "label": "a label", + "iterations": 1, + "real_time": 1, + "cpu_time": 1, + "time_unit": "s" + } + ] +} diff --git a/third_party/benchmark/tools/gbench/Inputs/test2_run.json b/third_party/benchmark/tools/gbench/Inputs/test2_run.json new file mode 100644 index 0000000..15bc698 --- /dev/null +++ b/third_party/benchmark/tools/gbench/Inputs/test2_run.json @@ -0,0 +1,81 @@ +{ + "context": { + "date": "2016-08-02 17:44:46", + "num_cpus": 4, + "mhz_per_cpu": 4228, + "cpu_scaling_enabled": false, + "library_build_type": "release" + }, + "benchmarks": [ + { + "name": "BM_Hi", + "iterations": 1234, + "real_time": 42, + "cpu_time": 24, + "time_unit": "ms" + }, + { + "name": "BM_Zero", + "iterations": 1000, + "real_time": 10, + "cpu_time": 10, + "time_unit": "ns" + }, + { + "name": "BM_Zero/4", + "iterations": 4000, + "real_time": 40, + "cpu_time": 40, + "time_unit": "ns" + }, + { + "name": "Prefix/BM_Zero", + "iterations": 2000, + "real_time": 20, + "cpu_time": 20, + "time_unit": "ns" + }, + { + "name": "Prefix/BM_Zero/3", + "iterations": 3000, + "real_time": 30, + "cpu_time": 30, + "time_unit": "ns" + }, + { + "name": "BM_One", + "iterations": 5000, + "real_time": 5, + "cpu_time": 5, + "time_unit": "ns" + }, + { + "name": "BM_One/4", + "iterations": 2000, + "real_time": 20, + "cpu_time": 20, + "time_unit": "ns" + }, + { + "name": "Prefix/BM_One", + "iterations": 1000, + "real_time": 10, + "cpu_time": 10, + "time_unit": "ns" + }, + { + "name": "Prefix/BM_One/3", + "iterations": 1500, + "real_time": 15, + "cpu_time": 15, + "time_unit": "ns" + }, + { + "name": "BM_Bye", + "iterations": 5321, + "real_time": 11, + "cpu_time": 63, + "time_unit": "ns" + } + ] +} diff --git a/third_party/benchmark/tools/gbench/Inputs/test3_run0.json b/third_party/benchmark/tools/gbench/Inputs/test3_run0.json new file mode 100644 index 0000000..49f8b06 --- /dev/null +++ b/third_party/benchmark/tools/gbench/Inputs/test3_run0.json @@ -0,0 +1,65 @@ +{ + "context": { + "date": "2016-08-02 17:44:46", + "num_cpus": 4, + "mhz_per_cpu": 4228, + "cpu_scaling_enabled": false, + "library_build_type": "release" + }, + "benchmarks": [ + { + "name": "BM_One", + "run_type": "aggregate", + "iterations": 1000, + "real_time": 10, + "cpu_time": 100, + "time_unit": "ns" + }, + { + "name": "BM_Two", + "iterations": 1000, + "real_time": 9, + "cpu_time": 90, + "time_unit": "ns" + }, + { + "name": "BM_Two", + "iterations": 1000, + "real_time": 8, + "cpu_time": 86, + "time_unit": "ns" + }, + { + "name": "short", + "run_type": "aggregate", + "iterations": 1000, + "real_time": 8, + "cpu_time": 80, + "time_unit": "ns" + }, + { + "name": "short", + "run_type": "aggregate", + "iterations": 1000, + "real_time": 8, + "cpu_time": 77, + "time_unit": "ns" + }, + { + "name": "medium", + "run_type": "iteration", + "iterations": 1000, + "real_time": 8, + "cpu_time": 80, + "time_unit": "ns" + }, + { + "name": "medium", + "run_type": "iteration", + "iterations": 1000, + "real_time": 9, + "cpu_time": 82, + "time_unit": "ns" + } + ] +} diff --git a/third_party/benchmark/tools/gbench/Inputs/test3_run1.json b/third_party/benchmark/tools/gbench/Inputs/test3_run1.json new file mode 100644 index 0000000..acc5ba1 --- /dev/null +++ b/third_party/benchmark/tools/gbench/Inputs/test3_run1.json @@ -0,0 +1,65 @@ +{ + "context": { + "date": "2016-08-02 17:44:46", + "num_cpus": 4, + "mhz_per_cpu": 4228, + "cpu_scaling_enabled": false, + "library_build_type": "release" + }, + "benchmarks": [ + { + "name": "BM_One", + "iterations": 1000, + "real_time": 9, + "cpu_time": 110, + "time_unit": "ns" + }, + { + "name": "BM_Two", + "run_type": "aggregate", + "iterations": 1000, + "real_time": 10, + "cpu_time": 89, + "time_unit": "ns" + }, + { + "name": "BM_Two", + "iterations": 1000, + "real_time": 7, + "cpu_time": 72, + "time_unit": "ns" + }, + { + "name": "short", + "run_type": "aggregate", + "iterations": 1000, + "real_time": 7, + "cpu_time": 75, + "time_unit": "ns" + }, + { + "name": "short", + "run_type": "aggregate", + "iterations": 762, + "real_time": 4.54, + "cpu_time": 66.6, + "time_unit": "ns" + }, + { + "name": "short", + "run_type": "iteration", + "iterations": 1000, + "real_time": 800, + "cpu_time": 1, + "time_unit": "ns" + }, + { + "name": "medium", + "run_type": "iteration", + "iterations": 1200, + "real_time": 5, + "cpu_time": 53, + "time_unit": "ns" + } + ] +} diff --git a/third_party/benchmark/tools/gbench/Inputs/test4_run.json b/third_party/benchmark/tools/gbench/Inputs/test4_run.json new file mode 100644 index 0000000..eaa005f --- /dev/null +++ b/third_party/benchmark/tools/gbench/Inputs/test4_run.json @@ -0,0 +1,96 @@ +{ + "benchmarks": [ + { + "name": "99 family 0 instance 0 repetition 0", + "run_type": "iteration", + "family_index": 0, + "per_family_instance_index": 0, + "repetition_index": 0 + }, + { + "name": "98 family 0 instance 0 repetition 1", + "run_type": "iteration", + "family_index": 0, + "per_family_instance_index": 0, + "repetition_index": 1 + }, + { + "name": "97 family 0 instance 0 aggregate", + "run_type": "aggregate", + "family_index": 0, + "per_family_instance_index": 0, + "aggregate_name": "9 aggregate" + }, + + + { + "name": "96 family 0 instance 1 repetition 0", + "run_type": "iteration", + "family_index": 0, + "per_family_instance_index": 1, + "repetition_index": 0 + }, + { + "name": "95 family 0 instance 1 repetition 1", + "run_type": "iteration", + "family_index": 0, + "per_family_instance_index": 1, + "repetition_index": 1 + }, + { + "name": "94 family 0 instance 1 aggregate", + "run_type": "aggregate", + "family_index": 0, + "per_family_instance_index": 1, + "aggregate_name": "9 aggregate" + }, + + + + + { + "name": "93 family 1 instance 0 repetition 0", + "run_type": "iteration", + "family_index": 1, + "per_family_instance_index": 0, + "repetition_index": 0 + }, + { + "name": "92 family 1 instance 0 repetition 1", + "run_type": "iteration", + "family_index": 1, + "per_family_instance_index": 0, + "repetition_index": 1 + }, + { + "name": "91 family 1 instance 0 aggregate", + "run_type": "aggregate", + "family_index": 1, + "per_family_instance_index": 0, + "aggregate_name": "9 aggregate" + }, + + + { + "name": "90 family 1 instance 1 repetition 0", + "run_type": "iteration", + "family_index": 1, + "per_family_instance_index": 1, + "repetition_index": 0 + }, + { + "name": "89 family 1 instance 1 repetition 1", + "run_type": "iteration", + "family_index": 1, + "per_family_instance_index": 1, + "repetition_index": 1 + }, + { + "name": "88 family 1 instance 1 aggregate", + "run_type": "aggregate", + "family_index": 1, + "per_family_instance_index": 1, + "aggregate_name": "9 aggregate" + } + ] +} diff --git a/third_party/benchmark/tools/gbench/Inputs/test4_run0.json b/third_party/benchmark/tools/gbench/Inputs/test4_run0.json new file mode 100644 index 0000000..54cf127 --- /dev/null +++ b/third_party/benchmark/tools/gbench/Inputs/test4_run0.json @@ -0,0 +1,21 @@ +{ + "context": { + "date": "2016-08-02 17:44:46", + "num_cpus": 4, + "mhz_per_cpu": 4228, + "cpu_scaling_enabled": false, + "library_build_type": "release" + }, + "benchmarks": [ + { + "name": "whocares", + "run_type": "aggregate", + "aggregate_name": "zz", + "aggregate_unit": "percentage", + "iterations": 1000, + "real_time": 0.01, + "cpu_time": 0.10, + "time_unit": "ns" + } + ] +} diff --git a/third_party/benchmark/tools/gbench/Inputs/test4_run1.json b/third_party/benchmark/tools/gbench/Inputs/test4_run1.json new file mode 100644 index 0000000..25d5605 --- /dev/null +++ b/third_party/benchmark/tools/gbench/Inputs/test4_run1.json @@ -0,0 +1,21 @@ +{ + "context": { + "date": "2016-08-02 17:44:46", + "num_cpus": 4, + "mhz_per_cpu": 4228, + "cpu_scaling_enabled": false, + "library_build_type": "release" + }, + "benchmarks": [ + { + "name": "whocares", + "run_type": "aggregate", + "aggregate_name": "zz", + "aggregate_unit": "percentage", + "iterations": 1000, + "real_time": 0.005, + "cpu_time": 0.15, + "time_unit": "ns" + } + ] +} diff --git a/third_party/benchmark/tools/gbench/Inputs/test5_run0.json b/third_party/benchmark/tools/gbench/Inputs/test5_run0.json new file mode 100644 index 0000000..074103b --- /dev/null +++ b/third_party/benchmark/tools/gbench/Inputs/test5_run0.json @@ -0,0 +1,18 @@ +{ + "context": { + "date": "2016-08-02 17:44:46", + "num_cpus": 4, + "mhz_per_cpu": 4228, + "cpu_scaling_enabled": false, + "library_build_type": "release" + }, + "benchmarks": [ + { + "name": "BM_ManyRepetitions", + "iterations": 1000, + "real_time": 1, + "cpu_time": 1000, + "time_unit": "s" + } + ] +} diff --git a/third_party/benchmark/tools/gbench/Inputs/test5_run1.json b/third_party/benchmark/tools/gbench/Inputs/test5_run1.json new file mode 100644 index 0000000..430df9f --- /dev/null +++ b/third_party/benchmark/tools/gbench/Inputs/test5_run1.json @@ -0,0 +1,18 @@ +{ + "context": { + "date": "2016-08-02 17:44:46", + "num_cpus": 4, + "mhz_per_cpu": 4228, + "cpu_scaling_enabled": false, + "library_build_type": "release" + }, + "benchmarks": [ + { + "name": "BM_ManyRepetitions", + "iterations": 1000, + "real_time": 1000, + "cpu_time": 1, + "time_unit": "s" + } + ] +} diff --git a/third_party/benchmark/tools/gbench/__init__.py b/third_party/benchmark/tools/gbench/__init__.py new file mode 100644 index 0000000..9212568 --- /dev/null +++ b/third_party/benchmark/tools/gbench/__init__.py @@ -0,0 +1,8 @@ +"""Google Benchmark tooling""" + +__author__ = "Eric Fiselier" +__email__ = "eric@efcs.ca" +__versioninfo__ = (0, 5, 0) +__version__ = ".".join(str(v) for v in __versioninfo__) + "dev" + +__all__ = [] # type: ignore diff --git a/third_party/benchmark/tools/gbench/report.py b/third_party/benchmark/tools/gbench/report.py new file mode 100644 index 0000000..7158fd1 --- /dev/null +++ b/third_party/benchmark/tools/gbench/report.py @@ -0,0 +1,1619 @@ +# type: ignore + +""" +report.py - Utilities for reporting statistics about benchmark results +""" + +import copy +import os +import random +import re +import unittest + +from numpy import array +from scipy.stats import gmean, mannwhitneyu + + +class BenchmarkColor(object): + def __init__(self, name, code): + self.name = name + self.code = code + + def __repr__(self): + return "%s%r" % (self.__class__.__name__, (self.name, self.code)) + + def __format__(self, format): + return self.code + + +# Benchmark Colors Enumeration +BC_NONE = BenchmarkColor("NONE", "") +BC_MAGENTA = BenchmarkColor("MAGENTA", "\033[95m") +BC_CYAN = BenchmarkColor("CYAN", "\033[96m") +BC_OKBLUE = BenchmarkColor("OKBLUE", "\033[94m") +BC_OKGREEN = BenchmarkColor("OKGREEN", "\033[32m") +BC_HEADER = BenchmarkColor("HEADER", "\033[92m") +BC_WARNING = BenchmarkColor("WARNING", "\033[93m") +BC_WHITE = BenchmarkColor("WHITE", "\033[97m") +BC_FAIL = BenchmarkColor("FAIL", "\033[91m") +BC_ENDC = BenchmarkColor("ENDC", "\033[0m") +BC_BOLD = BenchmarkColor("BOLD", "\033[1m") +BC_UNDERLINE = BenchmarkColor("UNDERLINE", "\033[4m") + +UTEST_MIN_REPETITIONS = 2 +UTEST_OPTIMAL_REPETITIONS = 9 # Lowest reasonable number, More is better. +UTEST_COL_NAME = "_pvalue" + +_TIME_UNIT_TO_SECONDS_MULTIPLIER = { + "s": 1.0, + "ms": 1e-3, + "us": 1e-6, + "ns": 1e-9, +} + + +def color_format(use_color, fmt_str, *args, **kwargs): + """ + Return the result of 'fmt_str.format(*args, **kwargs)' after transforming + 'args' and 'kwargs' according to the value of 'use_color'. If 'use_color' + is False then all color codes in 'args' and 'kwargs' are replaced with + the empty string. + """ + assert use_color is True or use_color is False + if not use_color: + args = [ + arg if not isinstance(arg, BenchmarkColor) else BC_NONE + for arg in args + ] + kwargs = { + key: arg if not isinstance(arg, BenchmarkColor) else BC_NONE + for key, arg in kwargs.items() + } + return fmt_str.format(*args, **kwargs) + + +def find_longest_name(benchmark_list): + """ + Return the length of the longest benchmark name in a given list of + benchmark JSON objects + """ + longest_name = 1 + for bc in benchmark_list: + if len(bc["name"]) > longest_name: + longest_name = len(bc["name"]) + return longest_name + + +def calculate_change(old_val, new_val): + """ + Return a float representing the decimal change between old_val and new_val. + """ + if old_val == 0 and new_val == 0: + return 0.0 + if old_val == 0: + return float(new_val - old_val) / (float(old_val + new_val) / 2) + return float(new_val - old_val) / abs(old_val) + + +def filter_benchmark(json_orig, family, replacement=""): + """ + Apply a filter to the json, and only leave the 'family' of benchmarks. + """ + regex = re.compile(family) + filtered = {} + filtered["benchmarks"] = [] + for be in json_orig["benchmarks"]: + if not regex.search(be["name"]): + continue + filteredbench = copy.deepcopy(be) # Do NOT modify the old name! + filteredbench["name"] = regex.sub(replacement, filteredbench["name"]) + filtered["benchmarks"].append(filteredbench) + return filtered + + +def get_unique_benchmark_names(json): + """ + While *keeping* the order, give all the unique 'names' used for benchmarks. + """ + seen = set() + uniqued = [ + x["name"] + for x in json["benchmarks"] + if x["name"] not in seen and (seen.add(x["name"]) or True) + ] + return uniqued + + +def intersect(list1, list2): + """ + Given two lists, get a new list consisting of the elements only contained + in *both of the input lists*, while preserving the ordering. + """ + return [x for x in list1 if x in list2] + + +def is_potentially_comparable_benchmark(x): + return "time_unit" in x and "real_time" in x and "cpu_time" in x + + +def partition_benchmarks(json1, json2): + """ + While preserving the ordering, find benchmarks with the same names in + both of the inputs, and group them. + (i.e. partition/filter into groups with common name) + """ + json1_unique_names = get_unique_benchmark_names(json1) + json2_unique_names = get_unique_benchmark_names(json2) + names = intersect(json1_unique_names, json2_unique_names) + partitions = [] + for name in names: + time_unit = None + # Pick the time unit from the first entry of the lhs benchmark. + # We should be careful not to crash with unexpected input. + for x in json1["benchmarks"]: + if x["name"] == name and is_potentially_comparable_benchmark(x): + time_unit = x["time_unit"] + break + if time_unit is None: + continue + # Filter by name and time unit. + # All the repetitions are assumed to be comparable. + lhs = [ + x + for x in json1["benchmarks"] + if x["name"] == name and x["time_unit"] == time_unit + ] + rhs = [ + x + for x in json2["benchmarks"] + if x["name"] == name and x["time_unit"] == time_unit + ] + partitions.append([lhs, rhs]) + return partitions + + +def get_timedelta_field_as_seconds(benchmark, field_name): + """ + Get value of field_name field of benchmark, which is time with time unit + time_unit, as time in seconds. + """ + timedelta = benchmark[field_name] + time_unit = benchmark.get("time_unit", "s") + return timedelta * _TIME_UNIT_TO_SECONDS_MULTIPLIER.get(time_unit) + + +def calculate_geomean(json): + """ + Extract all real/cpu times from all the benchmarks as seconds, + and calculate their geomean. + """ + times = [] + for benchmark in json["benchmarks"]: + if "run_type" in benchmark and benchmark["run_type"] == "aggregate": + continue + times.append( + [ + get_timedelta_field_as_seconds(benchmark, "real_time"), + get_timedelta_field_as_seconds(benchmark, "cpu_time"), + ] + ) + return gmean(times) if times else array([]) + + +def extract_field(partition, field_name): + # The count of elements may be different. We want *all* of them. + lhs = [x[field_name] for x in partition[0]] + rhs = [x[field_name] for x in partition[1]] + return [lhs, rhs] + + +def calc_utest(timings_cpu, timings_time): + min_rep_cnt = min( + len(timings_time[0]), + len(timings_time[1]), + len(timings_cpu[0]), + len(timings_cpu[1]), + ) + + # Does *everything* has at least UTEST_MIN_REPETITIONS repetitions? + if min_rep_cnt < UTEST_MIN_REPETITIONS: + return False, None, None + + time_pvalue = mannwhitneyu( + timings_time[0], timings_time[1], alternative="two-sided" + ).pvalue + cpu_pvalue = mannwhitneyu( + timings_cpu[0], timings_cpu[1], alternative="two-sided" + ).pvalue + + return (min_rep_cnt >= UTEST_OPTIMAL_REPETITIONS), cpu_pvalue, time_pvalue + + +def print_utest(bc_name, utest, utest_alpha, first_col_width, use_color=True): + def get_utest_color(pval): + return BC_FAIL if pval >= utest_alpha else BC_OKGREEN + + # Check if we failed miserably with minimum required repetitions for utest + if ( + not utest["have_optimal_repetitions"] + and utest["cpu_pvalue"] is None + and utest["time_pvalue"] is None + ): + return [] + + dsc = "U Test, Repetitions: {} vs {}".format( + utest["nr_of_repetitions"], utest["nr_of_repetitions_other"] + ) + dsc_color = BC_OKGREEN + + # We still got some results to show but issue a warning about it. + if not utest["have_optimal_repetitions"]: + dsc_color = BC_WARNING + dsc += ". WARNING: Results unreliable! {}+ repetitions recommended.".format( + UTEST_OPTIMAL_REPETITIONS + ) + + special_str = "{}{:<{}s}{endc}{}{:16.4f}{endc}{}{:16.4f}{endc}{} {}" + + return [ + color_format( + use_color, + special_str, + BC_HEADER, + "{}{}".format(bc_name, UTEST_COL_NAME), + first_col_width, + get_utest_color(utest["time_pvalue"]), + utest["time_pvalue"], + get_utest_color(utest["cpu_pvalue"]), + utest["cpu_pvalue"], + dsc_color, + dsc, + endc=BC_ENDC, + ) + ] + + +def get_difference_report(json1, json2, utest=False): + """ + Calculate and report the difference between each test of two benchmarks + runs specified as 'json1' and 'json2'. Output is another json containing + relevant details for each test run. + """ + assert utest is True or utest is False + + diff_report = [] + partitions = partition_benchmarks(json1, json2) + for partition in partitions: + benchmark_name = partition[0][0]["name"] + label = partition[0][0]["label"] if "label" in partition[0][0] else "" + time_unit = partition[0][0]["time_unit"] + measurements = [] + utest_results = {} + # Careful, we may have different repetition count. + for i in range(min(len(partition[0]), len(partition[1]))): + bn = partition[0][i] + other_bench = partition[1][i] + measurements.append( + { + "real_time": bn["real_time"], + "cpu_time": bn["cpu_time"], + "real_time_other": other_bench["real_time"], + "cpu_time_other": other_bench["cpu_time"], + "time": calculate_change( + bn["real_time"], other_bench["real_time"] + ), + "cpu": calculate_change( + bn["cpu_time"], other_bench["cpu_time"] + ), + } + ) + + # After processing the whole partition, if requested, do the U test. + if utest: + timings_cpu = extract_field(partition, "cpu_time") + timings_time = extract_field(partition, "real_time") + have_optimal_repetitions, cpu_pvalue, time_pvalue = calc_utest( + timings_cpu, timings_time + ) + if cpu_pvalue is not None and time_pvalue is not None: + utest_results = { + "have_optimal_repetitions": have_optimal_repetitions, + "cpu_pvalue": cpu_pvalue, + "time_pvalue": time_pvalue, + "nr_of_repetitions": len(timings_cpu[0]), + "nr_of_repetitions_other": len(timings_cpu[1]), + } + + # Store only if we had any measurements for given benchmark. + # E.g. partition_benchmarks will filter out the benchmarks having + # time units which are not compatible with other time units in the + # benchmark suite. + if measurements: + run_type = ( + partition[0][0]["run_type"] + if "run_type" in partition[0][0] + else "" + ) + aggregate_name = ( + partition[0][0]["aggregate_name"] + if run_type == "aggregate" + and "aggregate_name" in partition[0][0] + else "" + ) + diff_report.append( + { + "name": benchmark_name, + "label": label, + "measurements": measurements, + "time_unit": time_unit, + "run_type": run_type, + "aggregate_name": aggregate_name, + "utest": utest_results, + } + ) + + lhs_gmean = calculate_geomean(json1) + rhs_gmean = calculate_geomean(json2) + if lhs_gmean.any() and rhs_gmean.any(): + diff_report.append( + { + "name": "OVERALL_GEOMEAN", + "label": "", + "measurements": [ + { + "real_time": lhs_gmean[0], + "cpu_time": lhs_gmean[1], + "real_time_other": rhs_gmean[0], + "cpu_time_other": rhs_gmean[1], + "time": calculate_change(lhs_gmean[0], rhs_gmean[0]), + "cpu": calculate_change(lhs_gmean[1], rhs_gmean[1]), + } + ], + "time_unit": "s", + "run_type": "aggregate", + "aggregate_name": "geomean", + "utest": {}, + } + ) + + return diff_report + + +def print_difference_report( + json_diff_report, + include_aggregates_only=False, + utest=False, + utest_alpha=0.05, + use_color=True, +): + """ + Calculate and report the difference between each test of two benchmarks + runs specified as 'json1' and 'json2'. + """ + assert utest is True or utest is False + + def get_color(res): + if res > 0.05: + return BC_FAIL + elif res > -0.07: + return BC_WHITE + else: + return BC_CYAN + + first_col_width = find_longest_name(json_diff_report) + first_col_width = max(first_col_width, len("Benchmark")) + first_col_width += len(UTEST_COL_NAME) + first_line = "{:<{}s}Time CPU Time Old Time New CPU Old CPU New".format( + "Benchmark", 12 + first_col_width + ) + output_strs = [first_line, "-" * len(first_line)] + + fmt_str = "{}{:<{}s}{endc}{}{:+16.4f}{endc}{}{:+16.4f}{endc}{:14.0f}{:14.0f}{endc}{:14.0f}{:14.0f}" + for benchmark in json_diff_report: + # *If* we were asked to only include aggregates, + # and if it is non-aggregate, then don't print it. + if ( + not include_aggregates_only + or "run_type" not in benchmark + or benchmark["run_type"] == "aggregate" + ): + for measurement in benchmark["measurements"]: + output_strs += [ + color_format( + use_color, + fmt_str, + BC_HEADER, + benchmark["name"], + first_col_width, + get_color(measurement["time"]), + measurement["time"], + get_color(measurement["cpu"]), + measurement["cpu"], + measurement["real_time"], + measurement["real_time_other"], + measurement["cpu_time"], + measurement["cpu_time_other"], + endc=BC_ENDC, + ) + ] + + # After processing the measurements, if requested and + # if applicable (e.g. u-test exists for given benchmark), + # print the U test. + if utest and benchmark["utest"]: + output_strs += print_utest( + benchmark["name"], + benchmark["utest"], + utest_alpha=utest_alpha, + first_col_width=first_col_width, + use_color=use_color, + ) + + return output_strs + + +############################################################################### +# Unit tests + + +class TestGetUniqueBenchmarkNames(unittest.TestCase): + def load_results(self): + import json + + testInputs = os.path.join( + os.path.dirname(os.path.realpath(__file__)), "Inputs" + ) + testOutput = os.path.join(testInputs, "test3_run0.json") + with open(testOutput, "r") as f: + json = json.load(f) + return json + + def test_basic(self): + expect_lines = [ + "BM_One", + "BM_Two", + "short", # These two are not sorted + "medium", # These two are not sorted + ] + json = self.load_results() + output_lines = get_unique_benchmark_names(json) + print("\n") + print("\n".join(output_lines)) + self.assertEqual(len(output_lines), len(expect_lines)) + for i in range(0, len(output_lines)): + self.assertEqual(expect_lines[i], output_lines[i]) + + +class TestReportDifference(unittest.TestCase): + @classmethod + def setUpClass(cls): + def load_results(): + import json + + testInputs = os.path.join( + os.path.dirname(os.path.realpath(__file__)), "Inputs" + ) + testOutput1 = os.path.join(testInputs, "test1_run1.json") + testOutput2 = os.path.join(testInputs, "test1_run2.json") + with open(testOutput1, "r") as f: + json1 = json.load(f) + with open(testOutput2, "r") as f: + json2 = json.load(f) + return json1, json2 + + json1, json2 = load_results() + cls.json_diff_report = get_difference_report(json1, json2) + + def test_json_diff_report_pretty_printing(self): + expect_lines = [ + ["BM_SameTimes", "+0.0000", "+0.0000", "10", "10", "10", "10"], + ["BM_2xFaster", "-0.5000", "-0.5000", "50", "25", "50", "25"], + ["BM_2xSlower", "+1.0000", "+1.0000", "50", "100", "50", "100"], + [ + "BM_1PercentFaster", + "-0.0100", + "-0.0100", + "100", + "99", + "100", + "99", + ], + [ + "BM_1PercentSlower", + "+0.0100", + "+0.0100", + "100", + "101", + "100", + "101", + ], + [ + "BM_10PercentFaster", + "-0.1000", + "-0.1000", + "100", + "90", + "100", + "90", + ], + [ + "BM_10PercentSlower", + "+0.1000", + "+0.1000", + "100", + "110", + "100", + "110", + ], + [ + "BM_100xSlower", + "+99.0000", + "+99.0000", + "100", + "10000", + "100", + "10000", + ], + [ + "BM_100xFaster", + "-0.9900", + "-0.9900", + "10000", + "100", + "10000", + "100", + ], + [ + "BM_10PercentCPUToTime", + "+0.1000", + "-0.1000", + "100", + "110", + "100", + "90", + ], + ["BM_ThirdFaster", "-0.3333", "-0.3334", "100", "67", "100", "67"], + ["BM_NotBadTimeUnit", "-0.9000", "+0.2000", "0", "0", "0", "1"], + ["BM_hasLabel", "+0.0000", "+0.0000", "1", "1", "1", "1"], + ["OVERALL_GEOMEAN", "-0.8113", "-0.7779", "0", "0", "0", "0"], + ] + output_lines_with_header = print_difference_report( + self.json_diff_report, use_color=False + ) + output_lines = output_lines_with_header[2:] + print("\n") + print("\n".join(output_lines_with_header)) + self.assertEqual(len(output_lines), len(expect_lines)) + for i in range(0, len(output_lines)): + parts = [x for x in output_lines[i].split(" ") if x] + self.assertEqual(len(parts), 7) + self.assertEqual(expect_lines[i], parts) + + def test_json_diff_report_output(self): + expected_output = [ + { + "name": "BM_SameTimes", + "label": "", + "measurements": [ + { + "time": 0.0000, + "cpu": 0.0000, + "real_time": 10, + "real_time_other": 10, + "cpu_time": 10, + "cpu_time_other": 10, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "BM_2xFaster", + "label": "", + "measurements": [ + { + "time": -0.5000, + "cpu": -0.5000, + "real_time": 50, + "real_time_other": 25, + "cpu_time": 50, + "cpu_time_other": 25, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "BM_2xSlower", + "label": "", + "measurements": [ + { + "time": 1.0000, + "cpu": 1.0000, + "real_time": 50, + "real_time_other": 100, + "cpu_time": 50, + "cpu_time_other": 100, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "BM_1PercentFaster", + "label": "", + "measurements": [ + { + "time": -0.0100, + "cpu": -0.0100, + "real_time": 100, + "real_time_other": 98.9999999, + "cpu_time": 100, + "cpu_time_other": 98.9999999, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "BM_1PercentSlower", + "label": "", + "measurements": [ + { + "time": 0.0100, + "cpu": 0.0100, + "real_time": 100, + "real_time_other": 101, + "cpu_time": 100, + "cpu_time_other": 101, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "BM_10PercentFaster", + "label": "", + "measurements": [ + { + "time": -0.1000, + "cpu": -0.1000, + "real_time": 100, + "real_time_other": 90, + "cpu_time": 100, + "cpu_time_other": 90, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "BM_10PercentSlower", + "label": "", + "measurements": [ + { + "time": 0.1000, + "cpu": 0.1000, + "real_time": 100, + "real_time_other": 110, + "cpu_time": 100, + "cpu_time_other": 110, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "BM_100xSlower", + "label": "", + "measurements": [ + { + "time": 99.0000, + "cpu": 99.0000, + "real_time": 100, + "real_time_other": 10000, + "cpu_time": 100, + "cpu_time_other": 10000, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "BM_100xFaster", + "label": "", + "measurements": [ + { + "time": -0.9900, + "cpu": -0.9900, + "real_time": 10000, + "real_time_other": 100, + "cpu_time": 10000, + "cpu_time_other": 100, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "BM_10PercentCPUToTime", + "label": "", + "measurements": [ + { + "time": 0.1000, + "cpu": -0.1000, + "real_time": 100, + "real_time_other": 110, + "cpu_time": 100, + "cpu_time_other": 90, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "BM_ThirdFaster", + "label": "", + "measurements": [ + { + "time": -0.3333, + "cpu": -0.3334, + "real_time": 100, + "real_time_other": 67, + "cpu_time": 100, + "cpu_time_other": 67, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "BM_NotBadTimeUnit", + "label": "", + "measurements": [ + { + "time": -0.9000, + "cpu": 0.2000, + "real_time": 0.4, + "real_time_other": 0.04, + "cpu_time": 0.5, + "cpu_time_other": 0.6, + } + ], + "time_unit": "s", + "utest": {}, + }, + { + "name": "BM_hasLabel", + "label": "a label", + "measurements": [ + { + "time": 0.0000, + "cpu": 0.0000, + "real_time": 1, + "real_time_other": 1, + "cpu_time": 1, + "cpu_time_other": 1, + } + ], + "time_unit": "s", + "utest": {}, + }, + { + "name": "OVERALL_GEOMEAN", + "label": "", + "measurements": [ + { + "real_time": 3.1622776601683826e-06, + "cpu_time": 3.2130844755623912e-06, + "real_time_other": 1.9768988699420897e-07, + "cpu_time_other": 2.397447755209533e-07, + "time": -0.8112976497120911, + "cpu": -0.7778551721181174, + } + ], + "time_unit": "s", + "run_type": "aggregate", + "aggregate_name": "geomean", + "utest": {}, + }, + ] + self.assertEqual(len(self.json_diff_report), len(expected_output)) + for out, expected in zip(self.json_diff_report, expected_output): + self.assertEqual(out["name"], expected["name"]) + self.assertEqual(out["label"], expected["label"]) + self.assertEqual(out["time_unit"], expected["time_unit"]) + assert_utest(self, out, expected) + assert_measurements(self, out, expected) + + +class TestReportDifferenceBetweenFamilies(unittest.TestCase): + @classmethod + def setUpClass(cls): + def load_result(): + import json + + testInputs = os.path.join( + os.path.dirname(os.path.realpath(__file__)), "Inputs" + ) + testOutput = os.path.join(testInputs, "test2_run.json") + with open(testOutput, "r") as f: + json = json.load(f) + return json + + json = load_result() + json1 = filter_benchmark(json, "BM_Z.ro", ".") + json2 = filter_benchmark(json, "BM_O.e", ".") + cls.json_diff_report = get_difference_report(json1, json2) + + def test_json_diff_report_pretty_printing(self): + expect_lines = [ + [".", "-0.5000", "-0.5000", "10", "5", "10", "5"], + ["./4", "-0.5000", "-0.5000", "40", "20", "40", "20"], + ["Prefix/.", "-0.5000", "-0.5000", "20", "10", "20", "10"], + ["Prefix/./3", "-0.5000", "-0.5000", "30", "15", "30", "15"], + ["OVERALL_GEOMEAN", "-0.5000", "-0.5000", "0", "0", "0", "0"], + ] + output_lines_with_header = print_difference_report( + self.json_diff_report, use_color=False + ) + output_lines = output_lines_with_header[2:] + print("\n") + print("\n".join(output_lines_with_header)) + self.assertEqual(len(output_lines), len(expect_lines)) + for i in range(0, len(output_lines)): + parts = [x for x in output_lines[i].split(" ") if x] + self.assertEqual(len(parts), 7) + self.assertEqual(expect_lines[i], parts) + + def test_json_diff_report(self): + expected_output = [ + { + "name": ".", + "measurements": [ + { + "time": -0.5, + "cpu": -0.5, + "real_time": 10, + "real_time_other": 5, + "cpu_time": 10, + "cpu_time_other": 5, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "./4", + "measurements": [ + { + "time": -0.5, + "cpu": -0.5, + "real_time": 40, + "real_time_other": 20, + "cpu_time": 40, + "cpu_time_other": 20, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "Prefix/.", + "measurements": [ + { + "time": -0.5, + "cpu": -0.5, + "real_time": 20, + "real_time_other": 10, + "cpu_time": 20, + "cpu_time_other": 10, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "Prefix/./3", + "measurements": [ + { + "time": -0.5, + "cpu": -0.5, + "real_time": 30, + "real_time_other": 15, + "cpu_time": 30, + "cpu_time_other": 15, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "OVERALL_GEOMEAN", + "measurements": [ + { + "real_time": 2.213363839400641e-08, + "cpu_time": 2.213363839400641e-08, + "real_time_other": 1.1066819197003185e-08, + "cpu_time_other": 1.1066819197003185e-08, + "time": -0.5000000000000009, + "cpu": -0.5000000000000009, + } + ], + "time_unit": "s", + "run_type": "aggregate", + "aggregate_name": "geomean", + "utest": {}, + }, + ] + self.assertEqual(len(self.json_diff_report), len(expected_output)) + for out, expected in zip(self.json_diff_report, expected_output): + self.assertEqual(out["name"], expected["name"]) + self.assertEqual(out["time_unit"], expected["time_unit"]) + assert_utest(self, out, expected) + assert_measurements(self, out, expected) + + +class TestReportDifferenceWithUTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + def load_results(): + import json + + testInputs = os.path.join( + os.path.dirname(os.path.realpath(__file__)), "Inputs" + ) + testOutput1 = os.path.join(testInputs, "test3_run0.json") + testOutput2 = os.path.join(testInputs, "test3_run1.json") + with open(testOutput1, "r") as f: + json1 = json.load(f) + with open(testOutput2, "r") as f: + json2 = json.load(f) + return json1, json2 + + json1, json2 = load_results() + cls.json_diff_report = get_difference_report(json1, json2, utest=True) + + def test_json_diff_report_pretty_printing(self): + expect_lines = [ + ["BM_One", "-0.1000", "+0.1000", "10", "9", "100", "110"], + ["BM_Two", "+0.1111", "-0.0111", "9", "10", "90", "89"], + ["BM_Two", "-0.1250", "-0.1628", "8", "7", "86", "72"], + [ + "BM_Two_pvalue", + "1.0000", + "0.6667", + "U", + "Test,", + "Repetitions:", + "2", + "vs", + "2.", + "WARNING:", + "Results", + "unreliable!", + "9+", + "repetitions", + "recommended.", + ], + ["short", "-0.1250", "-0.0625", "8", "7", "80", "75"], + ["short", "-0.4325", "-0.1351", "8", "5", "77", "67"], + [ + "short_pvalue", + "0.7671", + "0.2000", + "U", + "Test,", + "Repetitions:", + "2", + "vs", + "3.", + "WARNING:", + "Results", + "unreliable!", + "9+", + "repetitions", + "recommended.", + ], + ["medium", "-0.3750", "-0.3375", "8", "5", "80", "53"], + ["OVERALL_GEOMEAN", "+1.6405", "-0.6985", "0", "0", "0", "0"], + ] + output_lines_with_header = print_difference_report( + self.json_diff_report, utest=True, utest_alpha=0.05, use_color=False + ) + output_lines = output_lines_with_header[2:] + print("\n") + print("\n".join(output_lines_with_header)) + self.assertEqual(len(output_lines), len(expect_lines)) + for i in range(0, len(output_lines)): + parts = [x for x in output_lines[i].split(" ") if x] + self.assertEqual(expect_lines[i], parts) + + def test_json_diff_report_pretty_printing_aggregates_only(self): + expect_lines = [ + ["BM_One", "-0.1000", "+0.1000", "10", "9", "100", "110"], + [ + "BM_Two_pvalue", + "1.0000", + "0.6667", + "U", + "Test,", + "Repetitions:", + "2", + "vs", + "2.", + "WARNING:", + "Results", + "unreliable!", + "9+", + "repetitions", + "recommended.", + ], + ["short", "-0.1250", "-0.0625", "8", "7", "80", "75"], + ["short", "-0.4325", "-0.1351", "8", "5", "77", "67"], + [ + "short_pvalue", + "0.7671", + "0.2000", + "U", + "Test,", + "Repetitions:", + "2", + "vs", + "3.", + "WARNING:", + "Results", + "unreliable!", + "9+", + "repetitions", + "recommended.", + ], + ["OVERALL_GEOMEAN", "+1.6405", "-0.6985", "0", "0", "0", "0"], + ] + output_lines_with_header = print_difference_report( + self.json_diff_report, + include_aggregates_only=True, + utest=True, + utest_alpha=0.05, + use_color=False, + ) + output_lines = output_lines_with_header[2:] + print("\n") + print("\n".join(output_lines_with_header)) + self.assertEqual(len(output_lines), len(expect_lines)) + for i in range(0, len(output_lines)): + parts = [x for x in output_lines[i].split(" ") if x] + self.assertEqual(expect_lines[i], parts) + + def test_json_diff_report(self): + expected_output = [ + { + "name": "BM_One", + "measurements": [ + { + "time": -0.1, + "cpu": 0.1, + "real_time": 10, + "real_time_other": 9, + "cpu_time": 100, + "cpu_time_other": 110, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "BM_Two", + "measurements": [ + { + "time": 0.1111111111111111, + "cpu": -0.011111111111111112, + "real_time": 9, + "real_time_other": 10, + "cpu_time": 90, + "cpu_time_other": 89, + }, + { + "time": -0.125, + "cpu": -0.16279069767441862, + "real_time": 8, + "real_time_other": 7, + "cpu_time": 86, + "cpu_time_other": 72, + }, + ], + "time_unit": "ns", + "utest": { + "have_optimal_repetitions": False, + "cpu_pvalue": 0.6666666666666666, + "time_pvalue": 1.0, + }, + }, + { + "name": "short", + "measurements": [ + { + "time": -0.125, + "cpu": -0.0625, + "real_time": 8, + "real_time_other": 7, + "cpu_time": 80, + "cpu_time_other": 75, + }, + { + "time": -0.4325, + "cpu": -0.13506493506493514, + "real_time": 8, + "real_time_other": 4.54, + "cpu_time": 77, + "cpu_time_other": 66.6, + }, + ], + "time_unit": "ns", + "utest": { + "have_optimal_repetitions": False, + "cpu_pvalue": 0.2, + "time_pvalue": 0.7670968684102772, + }, + }, + { + "name": "medium", + "measurements": [ + { + "time": -0.375, + "cpu": -0.3375, + "real_time": 8, + "real_time_other": 5, + "cpu_time": 80, + "cpu_time_other": 53, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "OVERALL_GEOMEAN", + "measurements": [ + { + "real_time": 8.48528137423858e-09, + "cpu_time": 8.441336246629233e-08, + "real_time_other": 2.2405267593145244e-08, + "cpu_time_other": 2.5453661413660466e-08, + "time": 1.6404861082353634, + "cpu": -0.6984640740519662, + } + ], + "time_unit": "s", + "run_type": "aggregate", + "aggregate_name": "geomean", + "utest": {}, + }, + ] + self.assertEqual(len(self.json_diff_report), len(expected_output)) + for out, expected in zip(self.json_diff_report, expected_output): + self.assertEqual(out["name"], expected["name"]) + self.assertEqual(out["time_unit"], expected["time_unit"]) + assert_utest(self, out, expected) + assert_measurements(self, out, expected) + + +class TestReportDifferenceWithUTestWhileDisplayingAggregatesOnly( + unittest.TestCase +): + @classmethod + def setUpClass(cls): + def load_results(): + import json + + testInputs = os.path.join( + os.path.dirname(os.path.realpath(__file__)), "Inputs" + ) + testOutput1 = os.path.join(testInputs, "test3_run0.json") + testOutput2 = os.path.join(testInputs, "test3_run1.json") + with open(testOutput1, "r") as f: + json1 = json.load(f) + with open(testOutput2, "r") as f: + json2 = json.load(f) + return json1, json2 + + json1, json2 = load_results() + cls.json_diff_report = get_difference_report(json1, json2, utest=True) + + def test_json_diff_report_pretty_printing(self): + expect_lines = [ + ["BM_One", "-0.1000", "+0.1000", "10", "9", "100", "110"], + ["BM_Two", "+0.1111", "-0.0111", "9", "10", "90", "89"], + ["BM_Two", "-0.1250", "-0.1628", "8", "7", "86", "72"], + [ + "BM_Two_pvalue", + "1.0000", + "0.6667", + "U", + "Test,", + "Repetitions:", + "2", + "vs", + "2.", + "WARNING:", + "Results", + "unreliable!", + "9+", + "repetitions", + "recommended.", + ], + ["short", "-0.1250", "-0.0625", "8", "7", "80", "75"], + ["short", "-0.4325", "-0.1351", "8", "5", "77", "67"], + [ + "short_pvalue", + "0.7671", + "0.2000", + "U", + "Test,", + "Repetitions:", + "2", + "vs", + "3.", + "WARNING:", + "Results", + "unreliable!", + "9+", + "repetitions", + "recommended.", + ], + ["medium", "-0.3750", "-0.3375", "8", "5", "80", "53"], + ["OVERALL_GEOMEAN", "+1.6405", "-0.6985", "0", "0", "0", "0"], + ] + output_lines_with_header = print_difference_report( + self.json_diff_report, utest=True, utest_alpha=0.05, use_color=False + ) + output_lines = output_lines_with_header[2:] + print("\n") + print("\n".join(output_lines_with_header)) + self.assertEqual(len(output_lines), len(expect_lines)) + for i in range(0, len(output_lines)): + parts = [x for x in output_lines[i].split(" ") if x] + self.assertEqual(expect_lines[i], parts) + + def test_json_diff_report(self): + expected_output = [ + { + "name": "BM_One", + "measurements": [ + { + "time": -0.1, + "cpu": 0.1, + "real_time": 10, + "real_time_other": 9, + "cpu_time": 100, + "cpu_time_other": 110, + } + ], + "time_unit": "ns", + "utest": {}, + }, + { + "name": "BM_Two", + "measurements": [ + { + "time": 0.1111111111111111, + "cpu": -0.011111111111111112, + "real_time": 9, + "real_time_other": 10, + "cpu_time": 90, + "cpu_time_other": 89, + }, + { + "time": -0.125, + "cpu": -0.16279069767441862, + "real_time": 8, + "real_time_other": 7, + "cpu_time": 86, + "cpu_time_other": 72, + }, + ], + "time_unit": "ns", + "utest": { + "have_optimal_repetitions": False, + "cpu_pvalue": 0.6666666666666666, + "time_pvalue": 1.0, + }, + }, + { + "name": "short", + "measurements": [ + { + "time": -0.125, + "cpu": -0.0625, + "real_time": 8, + "real_time_other": 7, + "cpu_time": 80, + "cpu_time_other": 75, + }, + { + "time": -0.4325, + "cpu": -0.13506493506493514, + "real_time": 8, + "real_time_other": 4.54, + "cpu_time": 77, + "cpu_time_other": 66.6, + }, + ], + "time_unit": "ns", + "utest": { + "have_optimal_repetitions": False, + "cpu_pvalue": 0.2, + "time_pvalue": 0.7670968684102772, + }, + }, + { + "name": "medium", + "measurements": [ + { + "real_time_other": 5, + "cpu_time": 80, + "time": -0.375, + "real_time": 8, + "cpu_time_other": 53, + "cpu": -0.3375, + } + ], + "utest": {}, + "time_unit": "ns", + "aggregate_name": "", + }, + { + "name": "OVERALL_GEOMEAN", + "measurements": [ + { + "real_time": 8.48528137423858e-09, + "cpu_time": 8.441336246629233e-08, + "real_time_other": 2.2405267593145244e-08, + "cpu_time_other": 2.5453661413660466e-08, + "time": 1.6404861082353634, + "cpu": -0.6984640740519662, + } + ], + "time_unit": "s", + "run_type": "aggregate", + "aggregate_name": "geomean", + "utest": {}, + }, + ] + self.assertEqual(len(self.json_diff_report), len(expected_output)) + for out, expected in zip(self.json_diff_report, expected_output): + self.assertEqual(out["name"], expected["name"]) + self.assertEqual(out["time_unit"], expected["time_unit"]) + assert_utest(self, out, expected) + assert_measurements(self, out, expected) + + +class TestReportDifferenceForPercentageAggregates(unittest.TestCase): + @classmethod + def setUpClass(cls): + def load_results(): + import json + + testInputs = os.path.join( + os.path.dirname(os.path.realpath(__file__)), "Inputs" + ) + testOutput1 = os.path.join(testInputs, "test4_run0.json") + testOutput2 = os.path.join(testInputs, "test4_run1.json") + with open(testOutput1, "r") as f: + json1 = json.load(f) + with open(testOutput2, "r") as f: + json2 = json.load(f) + return json1, json2 + + json1, json2 = load_results() + cls.json_diff_report = get_difference_report(json1, json2, utest=True) + + def test_json_diff_report_pretty_printing(self): + expect_lines = [["whocares", "-0.5000", "+0.5000", "0", "0", "0", "0"]] + output_lines_with_header = print_difference_report( + self.json_diff_report, utest=True, utest_alpha=0.05, use_color=False + ) + output_lines = output_lines_with_header[2:] + print("\n") + print("\n".join(output_lines_with_header)) + self.assertEqual(len(output_lines), len(expect_lines)) + for i in range(0, len(output_lines)): + parts = [x for x in output_lines[i].split(" ") if x] + self.assertEqual(expect_lines[i], parts) + + def test_json_diff_report(self): + expected_output = [ + { + "name": "whocares", + "measurements": [ + { + "time": -0.5, + "cpu": 0.5, + "real_time": 0.01, + "real_time_other": 0.005, + "cpu_time": 0.10, + "cpu_time_other": 0.15, + } + ], + "time_unit": "ns", + "utest": {}, + } + ] + self.assertEqual(len(self.json_diff_report), len(expected_output)) + for out, expected in zip(self.json_diff_report, expected_output): + self.assertEqual(out["name"], expected["name"]) + self.assertEqual(out["time_unit"], expected["time_unit"]) + assert_utest(self, out, expected) + assert_measurements(self, out, expected) + + +class TestReportSorting(unittest.TestCase): + @classmethod + def setUpClass(cls): + def load_result(): + import json + + testInputs = os.path.join( + os.path.dirname(os.path.realpath(__file__)), "Inputs" + ) + testOutput = os.path.join(testInputs, "test4_run.json") + with open(testOutput, "r") as f: + json = json.load(f) + return json + + cls.json = load_result() + + def test_json_diff_report_pretty_printing(self): + import util + + expected_names = [ + "99 family 0 instance 0 repetition 0", + "98 family 0 instance 0 repetition 1", + "97 family 0 instance 0 aggregate", + "96 family 0 instance 1 repetition 0", + "95 family 0 instance 1 repetition 1", + "94 family 0 instance 1 aggregate", + "93 family 1 instance 0 repetition 0", + "92 family 1 instance 0 repetition 1", + "91 family 1 instance 0 aggregate", + "90 family 1 instance 1 repetition 0", + "89 family 1 instance 1 repetition 1", + "88 family 1 instance 1 aggregate", + ] + + for n in range(len(self.json["benchmarks"]) ** 2): + random.shuffle(self.json["benchmarks"]) + sorted_benchmarks = util.sort_benchmark_results(self.json)[ + "benchmarks" + ] + self.assertEqual(len(expected_names), len(sorted_benchmarks)) + for out, expected in zip(sorted_benchmarks, expected_names): + self.assertEqual(out["name"], expected) + + +class TestReportDifferenceWithUTestWhileDisplayingAggregatesOnly2( + unittest.TestCase +): + @classmethod + def setUpClass(cls): + def load_results(): + import json + + testInputs = os.path.join( + os.path.dirname(os.path.realpath(__file__)), "Inputs" + ) + testOutput1 = os.path.join(testInputs, "test5_run0.json") + testOutput2 = os.path.join(testInputs, "test5_run1.json") + with open(testOutput1, "r") as f: + json1 = json.load(f) + json1["benchmarks"] = [ + json1["benchmarks"][0] for i in range(1000) + ] + with open(testOutput2, "r") as f: + json2 = json.load(f) + json2["benchmarks"] = [ + json2["benchmarks"][0] for i in range(1000) + ] + return json1, json2 + + json1, json2 = load_results() + cls.json_diff_report = get_difference_report(json1, json2, utest=True) + + def test_json_diff_report_pretty_printing(self): + expect_line = [ + "BM_ManyRepetitions_pvalue", + "0.0000", + "0.0000", + "U", + "Test,", + "Repetitions:", + "1000", + "vs", + "1000", + ] + output_lines_with_header = print_difference_report( + self.json_diff_report, utest=True, utest_alpha=0.05, use_color=False + ) + output_lines = output_lines_with_header[2:] + found = False + for i in range(0, len(output_lines)): + parts = [x for x in output_lines[i].split(" ") if x] + found = expect_line == parts + if found: + break + self.assertTrue(found) + + def test_json_diff_report(self): + expected_output = [ + { + "name": "BM_ManyRepetitions", + "label": "", + "time_unit": "s", + "run_type": "", + "aggregate_name": "", + "utest": { + "have_optimal_repetitions": True, + "cpu_pvalue": 0.0, + "time_pvalue": 0.0, + "nr_of_repetitions": 1000, + "nr_of_repetitions_other": 1000, + }, + }, + { + "name": "OVERALL_GEOMEAN", + "label": "", + "measurements": [ + { + "real_time": 1.0, + "cpu_time": 1000.000000000069, + "real_time_other": 1000.000000000069, + "cpu_time_other": 1.0, + "time": 999.000000000069, + "cpu": -0.9990000000000001, + } + ], + "time_unit": "s", + "run_type": "aggregate", + "aggregate_name": "geomean", + "utest": {}, + }, + ] + self.assertEqual(len(self.json_diff_report), len(expected_output)) + for out, expected in zip(self.json_diff_report, expected_output): + self.assertEqual(out["name"], expected["name"]) + self.assertEqual(out["time_unit"], expected["time_unit"]) + assert_utest(self, out, expected) + + +def assert_utest(unittest_instance, lhs, rhs): + if lhs["utest"]: + unittest_instance.assertAlmostEqual( + lhs["utest"]["cpu_pvalue"], rhs["utest"]["cpu_pvalue"] + ) + unittest_instance.assertAlmostEqual( + lhs["utest"]["time_pvalue"], rhs["utest"]["time_pvalue"] + ) + unittest_instance.assertEqual( + lhs["utest"]["have_optimal_repetitions"], + rhs["utest"]["have_optimal_repetitions"], + ) + else: + # lhs is empty. assert if rhs is not. + unittest_instance.assertEqual(lhs["utest"], rhs["utest"]) + + +def assert_measurements(unittest_instance, lhs, rhs): + for m1, m2 in zip(lhs["measurements"], rhs["measurements"]): + unittest_instance.assertEqual(m1["real_time"], m2["real_time"]) + unittest_instance.assertEqual(m1["cpu_time"], m2["cpu_time"]) + # m1['time'] and m1['cpu'] hold values which are being calculated, + # and therefore we must use almost-equal pattern. + unittest_instance.assertAlmostEqual(m1["time"], m2["time"], places=4) + unittest_instance.assertAlmostEqual(m1["cpu"], m2["cpu"], places=4) + + +if __name__ == "__main__": + unittest.main() + +# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 +# kate: tab-width: 4; replace-tabs on; indent-width 4; tab-indents: off; +# kate: indent-mode python; remove-trailing-spaces modified; diff --git a/third_party/benchmark/tools/gbench/util.py b/third_party/benchmark/tools/gbench/util.py new file mode 100644 index 0000000..1119a1a --- /dev/null +++ b/third_party/benchmark/tools/gbench/util.py @@ -0,0 +1,231 @@ +"""util.py - General utilities for running, loading, and processing benchmarks""" + +import json +import os +import re +import subprocess +import sys +import tempfile + +# Input file type enumeration +IT_Invalid = 0 +IT_JSON = 1 +IT_Executable = 2 + +_num_magic_bytes = 2 if sys.platform.startswith("win") else 4 + + +def is_executable_file(filename): + """ + Return 'True' if 'filename' names a valid file which is likely + an executable. A file is considered an executable if it starts with the + magic bytes for a EXE, Mach O, or ELF file. + """ + if not os.path.isfile(filename): + return False + with open(filename, mode="rb") as f: + magic_bytes = f.read(_num_magic_bytes) + if sys.platform == "darwin": + return magic_bytes in [ + b"\xfe\xed\xfa\xce", # MH_MAGIC + b"\xce\xfa\xed\xfe", # MH_CIGAM + b"\xfe\xed\xfa\xcf", # MH_MAGIC_64 + b"\xcf\xfa\xed\xfe", # MH_CIGAM_64 + b"\xca\xfe\xba\xbe", # FAT_MAGIC + b"\xbe\xba\xfe\xca", # FAT_CIGAM + ] + elif sys.platform.startswith("win"): + return magic_bytes == b"MZ" + else: + return magic_bytes == b"\x7fELF" + + +def is_json_file(filename): + """ + Returns 'True' if 'filename' names a valid JSON output file. + 'False' otherwise. + """ + try: + with open(filename, "r") as f: + json.load(f) + return True + except BaseException: + pass + return False + + +def classify_input_file(filename): + """ + Return a tuple (type, msg) where 'type' specifies the classified type + of 'filename'. If 'type' is 'IT_Invalid' then 'msg' is a human readable + string representing the error. + """ + ftype = IT_Invalid + err_msg = None + if not os.path.exists(filename): + err_msg = "'%s' does not exist" % filename + elif not os.path.isfile(filename): + err_msg = "'%s' does not name a file" % filename + elif is_executable_file(filename): + ftype = IT_Executable + elif is_json_file(filename): + ftype = IT_JSON + else: + err_msg = ( + "'%s' does not name a valid benchmark executable or JSON file" + % filename + ) + return ftype, err_msg + + +def check_input_file(filename): + """ + Classify the file named by 'filename' and return the classification. + If the file is classified as 'IT_Invalid' print an error message and exit + the program. + """ + ftype, msg = classify_input_file(filename) + if ftype == IT_Invalid: + print("Invalid input file: %s" % msg) + sys.exit(1) + return ftype + + +def find_benchmark_flag(prefix, benchmark_flags): + """ + Search the specified list of flags for a flag matching `` and + if it is found return the arg it specifies. If specified more than once the + last value is returned. If the flag is not found None is returned. + """ + assert prefix.startswith("--") and prefix.endswith("=") + result = None + for f in benchmark_flags: + if f.startswith(prefix): + result = f[len(prefix) :] + return result + + +def remove_benchmark_flags(prefix, benchmark_flags): + """ + Return a new list containing the specified benchmark_flags except those + with the specified prefix. + """ + assert prefix.startswith("--") and prefix.endswith("=") + return [f for f in benchmark_flags if not f.startswith(prefix)] + + +def load_benchmark_results(fname, benchmark_filter): + """ + Read benchmark output from a file and return the JSON object. + + Apply benchmark_filter, a regular expression, with nearly the same + semantics of the --benchmark_filter argument. May be None. + Note: the Python regular expression engine is used instead of the + one used by the C++ code, which may produce different results + in complex cases. + + REQUIRES: 'fname' names a file containing JSON benchmark output. + """ + + def benchmark_wanted(benchmark): + if benchmark_filter is None: + return True + name = benchmark.get("run_name", None) or benchmark["name"] + return re.search(benchmark_filter, name) is not None + + with open(fname, "r") as f: + results = json.load(f) + if "context" in results: + if "json_schema_version" in results["context"]: + json_schema_version = results["context"]["json_schema_version"] + if json_schema_version != 1: + print( + "In %s, got unnsupported JSON schema version: %i, expected 1" + % (fname, json_schema_version) + ) + sys.exit(1) + if "benchmarks" in results: + results["benchmarks"] = list( + filter(benchmark_wanted, results["benchmarks"]) + ) + return results + + +def sort_benchmark_results(result): + benchmarks = result["benchmarks"] + + # From inner key to the outer key! + benchmarks = sorted( + benchmarks, + key=lambda benchmark: benchmark["repetition_index"] + if "repetition_index" in benchmark + else -1, + ) + benchmarks = sorted( + benchmarks, + key=lambda benchmark: 1 + if "run_type" in benchmark and benchmark["run_type"] == "aggregate" + else 0, + ) + benchmarks = sorted( + benchmarks, + key=lambda benchmark: benchmark["per_family_instance_index"] + if "per_family_instance_index" in benchmark + else -1, + ) + benchmarks = sorted( + benchmarks, + key=lambda benchmark: benchmark["family_index"] + if "family_index" in benchmark + else -1, + ) + + result["benchmarks"] = benchmarks + return result + + +def run_benchmark(exe_name, benchmark_flags): + """ + Run a benchmark specified by 'exe_name' with the specified + 'benchmark_flags'. The benchmark is run directly as a subprocess to preserve + real time console output. + RETURNS: A JSON object representing the benchmark output + """ + output_name = find_benchmark_flag("--benchmark_out=", benchmark_flags) + is_temp_output = False + if output_name is None: + is_temp_output = True + thandle, output_name = tempfile.mkstemp() + os.close(thandle) + benchmark_flags = list(benchmark_flags) + [ + "--benchmark_out=%s" % output_name + ] + + cmd = [exe_name] + benchmark_flags + print("RUNNING: %s" % " ".join(cmd)) + exitCode = subprocess.call(cmd) + if exitCode != 0: + print("TEST FAILED...") + sys.exit(exitCode) + json_res = load_benchmark_results(output_name, None) + if is_temp_output: + os.unlink(output_name) + return json_res + + +def run_or_load_benchmark(filename, benchmark_flags): + """ + Get the results for a specified benchmark. If 'filename' specifies + an executable benchmark then the results are generated by running the + benchmark. Otherwise 'filename' must name a valid JSON output file, + which is loaded and the result returned. + """ + ftype = check_input_file(filename) + if ftype == IT_JSON: + benchmark_filter = find_benchmark_flag( + "--benchmark_filter=", benchmark_flags + ) + return load_benchmark_results(filename, benchmark_filter) + if ftype == IT_Executable: + return run_benchmark(filename, benchmark_flags) + raise ValueError("Unknown file type %s" % ftype) diff --git a/third_party/benchmark/tools/libpfm.BUILD.bazel b/third_party/benchmark/tools/libpfm.BUILD.bazel new file mode 100644 index 0000000..6269534 --- /dev/null +++ b/third_party/benchmark/tools/libpfm.BUILD.bazel @@ -0,0 +1,22 @@ +# Build rule for libpfm, which is required to collect performance counters for +# BENCHMARK_ENABLE_LIBPFM builds. + +load("@rules_foreign_cc//foreign_cc:defs.bzl", "make") + +filegroup( + name = "pfm_srcs", + srcs = glob(["**"]), +) + +make( + name = "libpfm", + lib_source = ":pfm_srcs", + lib_name = "libpfm", + copts = [ + "-Wno-format-truncation", + "-Wno-use-after-free", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/third_party/benchmark/tools/requirements.txt b/third_party/benchmark/tools/requirements.txt new file mode 100644 index 0000000..f32f35b --- /dev/null +++ b/third_party/benchmark/tools/requirements.txt @@ -0,0 +1,2 @@ +numpy == 1.25 +scipy == 1.10.0 diff --git a/third_party/benchmark/tools/strip_asm.py b/third_party/benchmark/tools/strip_asm.py new file mode 100755 index 0000000..bc3a774 --- /dev/null +++ b/third_party/benchmark/tools/strip_asm.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 + +""" +strip_asm.py - Cleanup ASM output for the specified file +""" + +import os +import re +import sys +from argparse import ArgumentParser + + +def find_used_labels(asm): + found = set() + label_re = re.compile(r"\s*j[a-z]+\s+\.L([a-zA-Z0-9][a-zA-Z0-9_]*)") + for line in asm.splitlines(): + m = label_re.match(line) + if m: + found.add(".L%s" % m.group(1)) + return found + + +def normalize_labels(asm): + decls = set() + label_decl = re.compile("^[.]{0,1}L([a-zA-Z0-9][a-zA-Z0-9_]*)(?=:)") + for line in asm.splitlines(): + m = label_decl.match(line) + if m: + decls.add(m.group(0)) + if len(decls) == 0: + return asm + needs_dot = next(iter(decls))[0] != "." + if not needs_dot: + return asm + for ld in decls: + asm = re.sub(r"(^|\s+)" + ld + r"(?=:|\s)", "\\1." + ld, asm) + return asm + + +def transform_labels(asm): + asm = normalize_labels(asm) + used_decls = find_used_labels(asm) + new_asm = "" + label_decl = re.compile(r"^\.L([a-zA-Z0-9][a-zA-Z0-9_]*)(?=:)") + for line in asm.splitlines(): + m = label_decl.match(line) + if not m or m.group(0) in used_decls: + new_asm += line + new_asm += "\n" + return new_asm + + +def is_identifier(tk): + if len(tk) == 0: + return False + first = tk[0] + if not first.isalpha() and first != "_": + return False + for i in range(1, len(tk)): + c = tk[i] + if not c.isalnum() and c != "_": + return False + return True + + +def process_identifiers(line): + """ + process_identifiers - process all identifiers and modify them to have + consistent names across all platforms; specifically across ELF and MachO. + For example, MachO inserts an additional understore at the beginning of + names. This function removes that. + """ + parts = re.split(r"([a-zA-Z0-9_]+)", line) + new_line = "" + for tk in parts: + if is_identifier(tk): + if tk.startswith("__Z"): + tk = tk[1:] + elif ( + tk.startswith("_") + and len(tk) > 1 + and tk[1].isalpha() + and tk[1] != "Z" + ): + tk = tk[1:] + new_line += tk + return new_line + + +def process_asm(asm): + """ + Strip the ASM of unwanted directives and lines + """ + new_contents = "" + asm = transform_labels(asm) + + # TODO: Add more things we want to remove + discard_regexes = [ + re.compile(r"\s+\..*$"), # directive + re.compile(r"\s*#(NO_APP|APP)$"), # inline ASM + re.compile(r"\s*#.*$"), # comment line + re.compile( + r"\s*\.globa?l\s*([.a-zA-Z_][a-zA-Z0-9$_.]*)" + ), # global directive + re.compile( + r"\s*\.(string|asciz|ascii|[1248]?byte|short|word|long|quad|value|zero)" + ), + ] + keep_regexes: list[re.Pattern] = [] + fn_label_def = re.compile("^[a-zA-Z_][a-zA-Z0-9_.]*:") + for line in asm.splitlines(): + # Remove Mach-O attribute + line = line.replace("@GOTPCREL", "") + add_line = True + for reg in discard_regexes: + if reg.match(line) is not None: + add_line = False + break + for reg in keep_regexes: + if reg.match(line) is not None: + add_line = True + break + if add_line: + if fn_label_def.match(line) and len(new_contents) != 0: + new_contents += "\n" + line = process_identifiers(line) + new_contents += line + new_contents += "\n" + return new_contents + + +def main(): + parser = ArgumentParser(description="generate a stripped assembly file") + parser.add_argument( + "input", + metavar="input", + type=str, + nargs=1, + help="An input assembly file", + ) + parser.add_argument( + "out", metavar="output", type=str, nargs=1, help="The output file" + ) + args, unknown_args = parser.parse_known_args() + input = args.input[0] + output = args.out[0] + if not os.path.isfile(input): + print("ERROR: input file '%s' does not exist" % input) + sys.exit(1) + + with open(input, "r") as f: + contents = f.read() + new_contents = process_asm(contents) + with open(output, "w") as f: + f.write(new_contents) + + +if __name__ == "__main__": + main() + +# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 +# kate: tab-width: 4; replace-tabs on; indent-width 4; tab-indents: off; +# kate: indent-mode python; remove-trailing-spaces modified; diff --git a/third_party/curl/CHANGES b/third_party/curl/CHANGES new file mode 100644 index 0000000..3e4b10e --- /dev/null +++ b/third_party/curl/CHANGES @@ -0,0 +1,10709 @@ + _ _ ____ _ + ___| | | | _ \| | + / __| | | | |_) | | + | (__| |_| | _ <| |___ + \___|\___/|_| \_\_____| + + Changelog + +Version 8.8.0 (22 May 2024) + +Daniel Stenberg (22 May 2024) + +- RELEASE-NOTES: synced + +- THANKS: add contributors from 8.8.0 + +Nathan Moinvaziri (21 May 2024) + +- url: remove duplicate call to Curl_conncache_remove_conn when pruning + + - remove unnecessary prunedead struct from prune_dead_connections + - rename extract_if_dead to prune_if_dead for clarity + + Closes #13710 + +Joseph Chen (21 May 2024) + +- curl_setup.h: add support for IAR compiler + + Closes #13728 + +Stephen Farrell (21 May 2024) + +- docs/ECH: typo/clarification + + Closes #13727 + +Viktor Szakats (21 May 2024) + +- hash: delete unused debug function + + It had no use in the curl codebase and was also protected by the macro + `AGGRESSIVE_TEST` (renamed in 2020), also with no local reference. + + Added in ca6e77083768858aa34207f8c5dce38b3c05336d (2002-11-11) + + Closes #13729 + +Stefan Eissing (21 May 2024) + +- content_encoding: reject transfer-encoding after chunked + + reject a response that applies a transfer-encoding after a 'chunked' + encoding. RFC 9112 ch. 6.1 required chunked to be the final encoding. + + Closes #13733 + +- http: HEAD response body tolerance + + - as reported in #13725, some servers wrongly send body bytes in + responses to a HEAD request. This used to be tolerated in curl + 8.4 and before and leads to failed transfers in newer versions. + - restore previous behaviour for HTTP/1.1 and HTTP/2: + * 1.1: do not add 'Transfer-Encoding' writers from HEAD + responses. RFC 9112 says they do not apply. + * 2: when the transfer expects 'no_body', to not report stream + resets as error when all response headers have been received. + + Reported-by: Jeroen Ooms + Fixes #13725 + Closes #13732 + +Viktor Szakats (20 May 2024) + +- tests: fix TFTP test 2305 on Windows + + Ref: #13692 + Closes #13724 + +Jay Satiro (20 May 2024) + +- openssl: revert keylog_callback support for LibreSSL + + - Revert to the legacy TLS 1.2 key logging code for LibreSSL. + + - Document SSLKEYLOGFILE for LibreSSL is TLS 1.2 max. + + Prior to this change if the user specified a filename in the + SSLKEYLOGFILE environment variable and was using LibreSSL 3.5.0+ then + an empty file would be created and no keys would be logged. + + This is effectively a revert of e43474b4 which changed openssl.c to use + SSL_CTX_set_keylog_callback for LibreSSL 3.5.0+. Unfortunately LibreSSL + added that function only as a stub that doesn't actually do anything. + + Reported-by: Gonçalo Carvalho + + Fixes https://github.com/curl/curl/issues/13672 + Closes https://github.com/curl/curl/pull/13682 + +renovate[bot] (19 May 2024) + +- GHA: pin dependencies + + Closes #13712 + +Viktor Szakats (19 May 2024) + +- appveyor: drop unnecessary `--clean-first` cmake option + + In CI all machines are fresh on startup, making the `clean` operation + unnecessary. This can save some time/energy for each job run. + + Closes #13707 + +- cmake: merge two `if(BUILD_TESTING)` branches + + Closes #13708 + +Tatsuhiro Tsujikawa (19 May 2024) + +- GHA: bump nghttp2 to v1.62.1 + + Use gcc-12 explicitly to compile C++20 source files. + + Closes #13702 + +Viktor Szakats (19 May 2024) + +- GHA: add NetBSD, OpenBSD, FreeBSD/arm64 and OmniOS jobs + + Add these jobs to GHA: + - NetBSD, cmake-unity, clang, OpenSSL, x86_64, with tests, w/o python, + no parallelism (was flaky sometimes) + - OpenBSD, cmake-unity, clang, LibreSSL, x86_64, with tests, + with python, -j8, TFTP results ignored due to #13623. + - FreeBSD, cmake-unity and autotools, clang, OpenSSL, arm64 + (Tests disabled for arm64, because they are slow. It's available for + x86_64 with python, -j12.) + Configuration matches our existing Cirrus CI one. + - OmniOS, autotools, gcc, OpenSSL, x86_64, with tests, -j12. + + All build with websockets and examples. + + Closes #13583 + +- GHA: disable TFTP test on native Windows + + Some TFTP tests seem to enter into a loop and maybe hang? + + E.g. 1007, 1009, 1238 + + Try fixing it by skipping all TFTP tests. + + Ref: https://github.com/curl/curl/actions/runs/9141987545/job/25137038249?pr= + 13698 + + Also drop mingw-w64 test exclusions copy-pasted from MSYS jobs. + + Possibly related: cffbcc3110c1eda2e333f9cfe2e269154618793a #5364 + + Close #13699 + +renovate[bot] (18 May 2024) + +- GHA: pin dependencies + + Closes #13691 + +Viktor Szakats (18 May 2024) + +- cmake: do not pass linker flags to the static library tool + + Do not add linker flags to the global CMake static library tool (aka + "static linker") (e.g. `ar`) flags list. They don't mix well. This was + only done after successfully detecting GSSAPI. + + Linker flags seen on Old Linux CI: + ``` + -- |GSS_LINKER_FLAGS|-Wl,--enable-new-dtags -Wl,-rpath -Wl,/usr/lib/x86_64-li + nux-gnu/heimdal| + -- |CMAKE_STATIC_LINKER_FLAGS| -Wl,--enable-new-dtags -Wl,-rpath -Wl,/usr/lib + /x86_64-linux-gnu/heimdal| + ``` + Ref: https://github.com/curl/curl/actions/runs/9138988036/job/25130791712#ste + p:6:85 + + Causing: + ``` + /usr/bin/ar qc libcurltool.a -Wl,--enable-new-dtags -Wl,-rpath -Wl,/usr/lib/ + x86_64-linux-gnu/heimdal + CMakeFiles/curltool.dir/slist_wc.c.o CMakeFiles/curltool.dir/tool_binmode.c + .o CMakeFiles/curltool.dir/tool_bname.c.o + [...] + CMakeFiles/curltool.dir/tool_writeout_json.c.o CMakeFiles/curltool.dir/tool + _xattr.c.o CMakeFiles/curltool.dir/var.c.o + CMakeFiles/curltool.dir/__/lib/base64.c.o CMakeFiles/curltool.dir/__/lib/dy + nbuf.c.o + /usr/bin/ar: invalid option -- 'W' + Usage: /usr/bin/ar [emulation options] [-]{dmpqrstx}[abcDfilMNoPsSTuvV] [--pl + ugin ] [member-name] [count] archive-file file... + /usr/bin/ar -M [now - c->timestamp; + | ^~~ + curl/lib/hostip.c: In function 'Curl_hostcache_prune': + curl/lib/hostip.c:241:10: note: 'now' was declared here + 241 | time_t now; + | ^~~ + In function 'hostcache_timestamp_remove', + inlined from 'fetch_addr' at curl/lib/hostip.c:310:8: + curl/lib/hostip.c:205:23: error: 'user.now' may be used uninitialized [-Werro + r=maybe-uninitialized] + 205 | time_t age = prune->now - c->timestamp; + | ~~~~~^~~~~ + curl/lib/hostip.c: In function 'fetch_addr': + curl/lib/hostip.c:304:33: note: 'user' declared here + 304 | struct hostcache_prune_data user; + | ^~~~ + In file included from curl/_bld/lib/CMakeFiles/libcurl_object.dir/Unity/unity + _0_c.c:40: + curl/lib/cf-socket.c: In function 'cf_socket_send': + curl/lib/cf-socket.c:1294:10: error: 'c' may be used uninitialized [-Werror=m + aybe-uninitialized] + 1294 | if(c >= ((100-ctx->wblock_percent)*256/100)) { + | ~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + curl/lib/cf-socket.c:1292:19: note: 'c' was declared here + 1292 | unsigned char c; + | ^ + In file included from curl/_bld/lib/CMakeFiles/libcurl_object.dir/Unity/unity + _0_c.c:364: + In function 'tftp_state_timeout', + inlined from 'tftp_multi_statemach' at curl/lib/tftp.c:1230:27: + curl/lib/tftp.c:1208:5: error: 'current' may be used uninitialized [-Werror=m + aybe-uninitialized] + 1208 | if(current > state->rx_time + state->retry_time) { + | ^ + curl/lib/tftp.c: In function 'tftp_multi_statemach': + curl/lib/tftp.c:1192:10: note: 'current' was declared here + 1192 | time_t current; + | ^~~~~~~ + ``` + Ref: https://ci.appveyor.com/project/curlorg/curl/builds/49792835/job/91c8dj5 + qb36spfe0#L112 + Ref: https://github.com/curl/curl/actions/runs/9082968838/job/24960616145#ste + p:12:62 + + Ref: #13592 + Closes #13643 + +Andrew (16 May 2024) + +- wakeup_create: use FD_CLOEXEC/SOCK_CLOEXEC + + for `pipe()`/`socketpair()` + + Fixes #13618 + Closes #13625 + +Stefan Eissing (16 May 2024) + +- rustls: fix partial send handling + + When TLS bytes could not completely sent off, the amount of plain bytes + already added to rustls were forgotten. This lead to send those byte + duplicate, corrupting the request send to the server. + + Closes #13676 + +- pytest: add DELETE tests, check server version + + - add tests for DELETE working + - check apache version in keepalive test + - fix some comments + + Closes #13679 + +Juliusz Sosinowicz (16 May 2024) + +- vquic-tls: use correct cert name check API for wolfSSL + + wolfSSL_X509_check_host checks the peer name against the alt names and + the common name. + + Fixes #13487 + Closes #13680 + +Viktor Szakats (16 May 2024) + +- cmake: initialize `BUILD_TESTING` before first use + + Before this patch `BUILD_TESTING` was used once, then initialized, then + used again. This caused the `curlu` library not being built when relying + on an implicit `BUILD_TESTING=ON` setting, and ending up with a link + error when building the `testdeps` target. + + It did not cause issues when `BUILD_TESTING` was explicitly set. + + Move the initialization before the first use to fix it. + + Regression from aace27b0965c10394544d1dacc9c2cb2fe0de3d3 #12287 + Closes #13668 + +Daniel Stenberg (16 May 2024) + +- libtest: 2308 verifies CURLE_WRITE_ERROR after write callback error + + Verifies that the issue in #13669 actually is fixed. This return code is + what the CURLOPT_WRITEFUNCTION manpage documents should be returned. + + This code is mostly from the + Source-written-by: Trumeet on github + Closes #13671 + +Antoine Bollengier (16 May 2024) + +- socketpair: fix compilation when USE_UNIX_SOCKETS is not defined + + Closes #13666 + +Stefan Eissing (16 May 2024) + +- rustsls: fix error code on receive + + - use CURLE_RECV_ERROR instead of CURLE_READ_ERROR when receiving + data fails. + + Closes #13670 + +Max Dymond (16 May 2024) + +- ci: disable Renovate dashboard + + The Renovate dashboard insists on an open issue, + which is a problem. Disable the dashboard. Status + can still be seen at https://developer.mend.io/github/curl/curl. + + Fixes #13630 + Closes #13673 + +Daniel Stenberg (16 May 2024) + +- RELEASE-NOTES: synced + +renovate[bot] (16 May 2024) + +- GHA: update awslabs/aws-lc to v1.27.0 + + Closes #13667 + +Daniel Stenberg (15 May 2024) + +- curl_easy_pause.md: use correct defines in example + + Spotted-by: Harry Sintonen + Closes #13664 + +Viktor Szakats (15 May 2024) + +- appveyor: more tidy-ups + + - use `--disable` when calling `curl --version`. Just in case. + + - use single-quotes for a constant. + + Closes #13662 + +- reuse: migrate standalone license file to dep5 + + Follow-up to 73a36021207284ad2b4340ffde34a51b0ba4d47a + Closes #13660 + +- appveyor: guard against crash-build with VS2008 + + The combination of `-DDEBUGBUILD`, a shared `curl.exe`, and the VS2008 + compiler creates a `curl.exe` segfaulting on startup: + + ``` + + _bld/src/curl.exe --version + ./appveyor.sh: line 122: 793 Segmentation fault "${curl}" --version + Command exited with code 139 + ``` + Ref: https://ci.appveyor.com/project/curlorg/curl/builds/49817266/job/651iy6q + n1e238pqj#L191 + + Add job that triggers the issue and add the necessary logic to skip + running the affected `curl.exe`. + + Ref: #13592 + Closes #13654 + +renovate[bot] (15 May 2024) + +- GHA: pin dependencies + + Closes #13628 + +Orgad Shaneh (15 May 2024) + +- socket: remove redundant call to getsockname + + The result "add" is unused. + + Closes #13655 + +renovate[bot] (15 May 2024) + +- CI: renovate updates + + - GHA: update actions/checkout action to v4 + - GHA: update wolfSSL/wolfssh to v1.4.17 + - GHA: update wolfSSL/wolfssl to v5.7.0 + - Update the regex config in renovate.json + + Closes #13632 + Closes #13641 + Closes #13658 + Closes #13659 + +Max Dymond (15 May 2024) + +- ci: fix renovate config for WolfSSL/WolfSSH tagging scheme + + WolfSSL/WolfSSH use a different versioning scheme; + stable builds end with `-stable`. Renovate requires + some extra configuration to extract the version + from these types of tags. + + Closes #13644 + +- ci: set semantic type as CI and include digests as CI operations + + Replace "chore" with "ci" for renovate's semantic + type, and include digests with "pin" and + "pinDigest" as ci operations. + + Closes #13644 + +Daniel Stenberg (15 May 2024) + +- DEPRECATE.md: TLS libraries without 1.3 support + + curl drops support for TLS libraries without TLS 1.3 capability after + May 2025. + + It requires that a curl build using the library should be able to + negotiate and use TLS 1.3, or else it is not good enough. We support a + vast amount of other TLS libraries that are likely to satisfy users + better. + + Closes #13544 + +- Revert "ci: update nghttp2/nghttp2 to v1.62.0" + + This reverts commit 14f2c767555b7598d7783ccd9093670b84d28488. + + We need to also upgrade the C++ compiler for that bump to work. + + Closes #13656 + +renovate[bot] (15 May 2024) + +- Dockerfile: update debian digest to 911821c + + Closes #13629 + +- ci: update gnutls/gnutls to v3.8.5 + + Closes #13640 + +- ci: update awslabs/aws-lc to v1.26.0 + + Closes #13647 + +- ci: update cloudflare/quiche to v0.21.0 + + Closes #13648 + +- ci: update libressl-portable/portable to v3.9.2 + + Closes #13649 + +- ci: update nghttp2/nghttp2 to v1.62.0 + + Closes #13650 + +- ci: update ngtcp2/nghttp3 to v1.3.0 + + Closes #13651 + +- ci: update ngtcp2/ngtcp2 to v1.5.0 + + Closes #13652 + +Max Dymond (14 May 2024) + +- ci: handle git submodules for mbedTLS + +- ci: reconfigure renovate + + - set prefix for github actions updates to be gha: + - set prefix for other renovate actions to be ci: + - disable debian updates in linux-old.yml + +Viktor Szakats (14 May 2024) + +- tidy-up: whitespace [ci skip] + +- warnless: delete orphan declarations + + Follow-up to 358f7e757781857c4b498a68634726609fa3884a #11932 + Closes #13639 + +Daniel Stenberg (14 May 2024) + +- BUG-BOUNTY.md: clarify the third party situation + + We do not pay bounties for problems in other libraries. + + Closes #13560 + +Stefan Eissing (14 May 2024) + +- http tests: in CI skip test_02_23* for quiche + + For unknown reasons, these tests fail in CI often, but run fine locally. + Skip them in CI to avoid unrelated PRs to have failures. + + Closes #13638 + +Daniel Gustafsson (14 May 2024) + +- hsts: explicitly skip blank lines + + Keep blank lines or lines containing only whitespace to make it all + the way to the more expensive sscanf call in hsts_add. + + Closes: #13603 + Reviewed-by: Daniel Stenberg + +- autotools: Only probe for SGI MIPS compilers on IRIX + + MIPSPro and the predecessor compiler which was part of the IDO (IRIS + Development Option) were only ever shipped on the SGI IRIX operating + system (with MIPSPro on 6.0+ which was released in 1994). Limit the + autoconf check to IRIX when probing for these compilers to save some + cycles on other platforms. + + Closes: #13611 + Reviewed-by: Daniel Stenberg + +Viktor Szakats (14 May 2024) + +- tests: fix test 1167 to skip digit-only symbols + + This avoids mistaking symbols with their numeric value when using + certain C preprocessors which output these numeric values at the + beginning of the line as part of an expression. + + Seen on OpenBSD 7.5 + clang. + + Example `test1167.pl -v` output, before this patch: + ``` + Source: cpp /home/runner/work/curl/curl/tests/../include/curl/curl.h + Symbol: 20000 + Line #3835: 20000 + 142, + [...] + Bad symbols in public header files: + 20000 + [...] + ``` + Ref: https://github.com/curl/curl/actions/runs/9069136530/job/24918015357#ste + p:3:7513 + + Ref: #13583 + Closes #13634 + +Daniel Stenberg (14 May 2024) + +- lib: call Curl_strntolower instead of doing crafted loops + + Closes #13627 + +- setopt: acknowledge errors proper for CURLOPT_COOKIEJAR + + Error out on error, do not continue. + + Closes #13624 + +- vtls: remove duplicate assign + + Curl_ssl_peer_cleanup() already clears the ->sni field, no point in + assigning it again. + + Spotted by CodeSonar + + Closes #13626 + +Max Dymond (13 May 2024) + +- Group all non-major updates together to reduce PR spam + +- Add the remainder of the workflows + +- Add some basic versioning for some workflows to check whether this is detecte + d properly + +renovate[bot] (13 May 2024) + +- Add renovate.json + +Daniel Stenberg (13 May 2024) + +- vauth: make two functions void that always just returned OK + + Removes the need to check return values when they can never fail. + + Pointed out by CodeSonar + + Closes #13621 + +- setopt: remove check for 'option' that is always true + + - make sure that passing in option set to NULL clears the fields + correctly + + - remove the weird second take if Curl_parse_login_details() returns + error + + Follow-up to 7333faf00bf25db7cd1e0012d6b140 + + Spotted by CodeSonar + + Closes #13619 + +Viktor Szakats (13 May 2024) + +- tests: tidy up types in server code + + Cherry-picked from #13489 + Closes #13610 + +Daniel Stenberg (13 May 2024) + +- setopt: make the setstropt_userpwd args compulsory + + They were always used so no point in allowing them to be optional. + + follow-up to 0e37b42dc956bd8a + + Closes #13608 + Reviewed-by: Daniel Gustafsson + +- RELEASE-NOTES: synced + +Daniel Gustafsson (13 May 2024) + +- websocket: Avoid memory leak in error path + + In the errorpath for randstr being too long to copy into the buffer + we leak the randstr when returning CURLE_FAILED_INIT. Fix by using + an explicit free on randstr in the errorpath. + + Closes: #13602 + Reviewed-by: Daniel Stenberg + +- hsts: Remove single-use single-line function + + The hsts_entry() function contains of a single line and is only + used in a single place in the code, so move the allocation into + hsts_create instead to improve code readability. C code usually + don't use the factory abstraction for object creation, and this + small example wasn't following our usual code style. + + Closes: #13604 + Reviewed-by: Daniel Stenberg + +Viktor Szakats (12 May 2024) + +- lib: bump hash sizes to `size_t` + + Follow-up to cc907e80a2498c0599253271a6f657f614b52a4e #13502 + Cherry-picked from #13489 + Closes #13601 + +- tests: make the unit test result type `CURLcode` + + Before this patch, the result code was a mixture of `int` and + `CURLcode`. + + Also adjust casts and fix a couple of minor issues found along the way. + + Cherry-picked from #13489 + Closes #13600 + +- appveyor: tidy-ups + + - delete a duplicate line. + - simplify a `make` call. + - merge two `if` branches. + - reorder autotools options for clarity. + - add `--enable-warnings` where missing (it's also the default.) + - add empty lines to YAML for readability. + - use lowercase install prefix/directory. + + Closes #13598 + +Daniel Stenberg (12 May 2024) + +- docs/cmdline-opts: mention STARTTLS for --ssl and --ssl-reqd + + ... since users might look for those terms in the manpage. + + Closes #13590 + +- setopt: warn on Curl_set*opt() uses not using the return value + + And switch the invokes that would "set" NULL to instead just plainly + free the pointer, as those were otherwise the invokes that would ignore + the return code. And possibly confuse static code analyzers. + + Closes #13591 + +Orgad Shaneh (12 May 2024) + +- autotools: delete unused functions + + Closes #13605 + +Viktor Szakats (11 May 2024) + +- examples: fix/silence `-Wsign-conversion` + + - extend `FD_SET()` hack to all platforms (was only Cygwin). + Warnings may also happen in other envs, e.g. OmniOS. + Ref: https://github.com/libssh2/libssh2/actions/runs/8854199687/job/2431676 + 2831#step:3:2021 + + - tidy-up `CURLcode` vs `int` use. + + - cast an unsigned to `long` before passing to `curl_easy_setopt()`. + + Cherry-picked from #13489 + Follow-up to 3829759bd042c03225ae862062560f568ba1a231 #12489 + Closes #13501 + +Orgad Shaneh (11 May 2024) + +- cmake: fix `HAVE_IOCTLSOCKET_FIONBIO` test with gcc 14 + + The function signature has had u_long flags since ever. This is how it + is defined in the documentation, and implemented in MinGW. + + The code that uses ioctlsocket in nonblock.c also has unsigned long. + + Error: + CurlTests.c:275:41: error: passing argument 3 of 'ioctlsocket' from incompati + ble pointer type [-Wincompatible-pointer-types] + 275 | if(0 != ioctlsocket(0, FIONBIO, &flags)) + | ^~~~~~ + | | + | int * + In file included from CurlTests.c:266: + /opt/mxe/usr/i686-w64-mingw32.static/include/winsock2.h:1007:76: note: expect + ed 'u_long *' {aka 'long unsigned int *'} but argument is of type 'int *' + 1007 | WINSOCK_API_LINKAGE int WSAAPI ioctlsocket(SOCKET s,__LONG32 cmd,u_ + long *argp); + | ~~ + ~~~~~~^~~~ + + Closes #13578 + +Jay Satiro (10 May 2024) + +- ftp: fix build for CURL_DISABLE_VERBOSE_STRINGS + + This is a follow-up to b7c7dffe which changed the FTP state change + verbose debug text (aka infof) to tracing debug text (aka trc). + + Prior to this change if libcurl was without DEBUGBUILD and built with + CURL_DISABLE_VERBOSE_STRINGS (ie --disable-verbose) the build would + error. + + Caught by Circle CI job openssl-no-verbose. + +- lib: clear the easy handle's saved errno before transfer + + - Clear data->state.os_errno before transfer. + + - Explain the change in behavior in the CURLINFO_OS_ERRNO doc. + + - Add to the CURLINFO_OS_ERRNO doc the list of libcurl network-related + errors that may cause the errno to be saved. + + data->state.os_errno is saved before libcurl returns a network-related + failure such as connection failure. It is accessible to the user via + CURLINFO_OS_ERRNO so they can get more information about the failure. + + Prior to this change it wasn't cleared before transfer, so if a user + retrieved the saved errno it could be from a previous transfer. That is + because an errno is not always saved for network-related errors. + + Closes https://github.com/curl/curl/pull/13574 + +Stefan Eissing (10 May 2024) + +- ftp: add tracing support + + - add `Curl_trc_feat_ftp` for tracing via trace config + - add macro CURL_TRC_FTP(data, fmt, ...) + - replace DEBUGF(infof()) statements in ftp.c by CURL_TRC_FTP() + - always trace FTP connection state + + Closes #13580 + +Daniel Stenberg (10 May 2024) + +- http: remove redundant check + + Spotted by CodeSonar + + Closes #13582 + +Viktor Szakats (10 May 2024) + +- ldap: fix unused variables (seen on OmniOS) + + ``` + ../../lib/ldap.c: In function 'ldap_do': + ../../lib/ldap.c:380:11: error: unused variable 'ldap_ca' [-Werror=unused-v + ariable] + 380 | char *ldap_ca = conn->ssl_config.CAfile; + | ^~~~~~~ + ../../lib/ldap.c:379:9: error: unused variable 'ldap_option' [-Werror=unuse + d-variable] + 379 | int ldap_option; + | ^~~~~~~~~~~ + ``` + Ref: https://github.com/curl/curl/actions/runs/9033564377/job/24824192730#ste + p:3:6059 + + Ref: #13583 + Closes #13588 + +Daniel Stenberg (10 May 2024) + +- url: make parse_login_details use memdup0 + + Also make the user and password arguments mandatory, since all code + paths in libcurl used them anyway. + + Adapted unit test case 1620 to the new rules. + + Closes #13584 + +Orgad Shaneh (10 May 2024) + +- digest: replace strcpy for empty string with simple assignment + + Closes #13586 + +Viktor Szakats (10 May 2024) + +- autotools: fix `HAVE_IOCTLSOCKET_FIONBIO` test for gcc 14 + + ``` + conftest.c:152:41: error: passing argument 3 of 'ioctlsocket' from incompatib + le pointer type [-Wincompatible-pointer-types] + 152 | if(0 != ioctlsocket(0, FIONBIO, &flags)) + | ^~~~~~ + | | + | int * + ``` + + Reported-by: LigH + Fixes #13579 + Closes #13587 + +- CI: ignore test 286 on Appveyor gcc 7 build + + Disabled earlier for gcc 9 builds. gcc 7 uses the same runner and + prone to similar intermittent failures. + + Follow-up to f1e05a6e6e7225fa09952abb2c935ae1abe44f45 #12106 #12040 + Closes #13575 + +Daniel Stenberg (10 May 2024) + +- cf-socket: don't try getting local IP without socket + + In cf_tcp_connect(), it might fail and not get a socket assigned to + ctx->sock but set_local_ip() is still called which would make + getsockname() get invoked with a negative file desriptor and fail. + + By adding this check, set_local_ip() will now instead blank out the + fields correctly. + + Spotted by CodeSonar + + Closes #13577 + +- tool_getparam: remove two redundant conditions + + When getstr() does not return error, it returns a valid pointer. + + Spotted by CodeSonar + + Closes #13576 + +Stefan Eissing (10 May 2024) + +- quiche: trust its timeout handling + + - set the idle timeout transport parameter + in milliseconds as documented by quiche + - do not calculate the idle timeout, rely on + quiche handling it + + Closes #13581 + +Daniel Stenberg (10 May 2024) + +- dmaketgz: accept a SOURCE_DATE_EPOCH as an second argument + + to make it easier to reproduce a tarball + + Closes #13573 + +- RELEASE-NOTES: synced + +Stefan Eissing (10 May 2024) + +- h3/ngtcp2: improve error handling + + - identify ngtcp2 and nghttp3 error codes that are fatal + - close quic connection on fatal errors + - refuse further filter operations once connection is closed + - confusion about the nghttp3 API. We should close the QUIC stream on + cancel and not use the nghttp3 calls intended to be invoked when the + QUIC stream was closed by the peer. + + Closes #13562 + +Jay Satiro (10 May 2024) + +- docs: fix some CURLINFO examples + + - improve getinfo result check for example sections: + CURLINFO_ACTIVESOCKET, CURLINFO_LASTSOCKET, CURLINFO_SSL_VERIFYRESULT, + CURLINFO_PROXY_SSL_VERIFYRESULT + + - fix getinfo result check for example sections: + CURLINFO_NUM_CONNECTS, CURLINFO_OS_ERRNO + + - fix verify result check for example sections: + CURLINFO_PROXY_SSL_VERIFYRESULT + + Bug: https://github.com/curl/curl/discussions/13557#discussion-6625507 + Reported-by: farazrbx@users.noreply.github.com + + Closes https://github.com/curl/curl/pull/13559 + +Daniel Stenberg (9 May 2024) + +- KNOWN_BUGS: gssapi library name + version is missing in curl_version_info() + + Closes #13492 + Closes #13570 + +- krb5: use dynbuf + + Closes #13568 + +- managen: fix the option sort order + + ... it used to strip off the .d file extension to sort correctly but + ever since the extension changed to .md the operation failed and the + sort got wrong. + + Follow-up to 2494b8dd5175cee7f2e + + Closes #13567 + +Stefan Eissing (8 May 2024) + +- GHA: repair the linux-old job + + package libc6_2.28-10+deb10u2_amd64.deb changed to + libc6_2.28-10+deb10u3_amd64.deb + + Closes #13564 + +Viktor Szakats (8 May 2024) + +- appveyor: make gcc 6 mingw64 job build-only + + This job has proven to be the flakiest of all, and it's also the oldest + Windows runner we had tests running on: 'Visual Studio 2015', that is + running on Windows Server 2012 R2: + https://www.appveyor.com/docs/windows-images-software/ + + Turn off tests on this job to help stabilizing CI runs. + + This was also one of the slowest running job amongst the AppVeyor CI ones. + + Flakiness data: + https://testclutch.curl.se/static/reports/summary.html + Entries: + Appveyor / CMake, mingw-w64, gcc 6, Debug, x86, Schannel, Static, no-unity + (curl) [current] + Appveyor / CMake, mingw-w64, gcc 6, Debug, x86, Schannel, Static (curl) [fo + rmer] + + Closes #13566 + +Stefan Eissing (8 May 2024) + +- unit2604: use alloc instead of overlong string const + + Closes #13563 + +Daniel Gustafsson (8 May 2024) + +- bufq: remove duplicate word in comment + + Inspired by 13552. + + Closes: #13554 + Reviewed-by: Daniel Stenberg + +Viktor Szakats (8 May 2024) + +- lib/cf-h1-proxy: silence compiler warnings (gcc 14) + + They came up ealier with gcc 12 (Windows), but apparently gcc 14 is + still reporting them, also under Linux. + + ``` + /home/runner/work/curl-for-win/curl-for-win/curl/lib/cf-h1-proxy.c: In functi + on 'cf_h1_proxy_close': + /home/runner/work/curl-for-win/curl-for-win/curl/lib/cf-h1-proxy.c:1060:17: w + arning: null pointer dereference [-Wnull-dereference] + 1060 | cf->connected = FALSE; + /home/runner/work/curl-for-win/curl-for-win/curl/lib/cf-h1-proxy.c:1061:8: wa + rning: null pointer dereference [-Wnull-dereference] + 1061 | if(cf->ctx) { + | ~~^~~~~ + In function 'tunnel_free', + inlined from 'cf_h1_proxy_destroy' at /home/runner/work/curl-for-win/curl + -for-win/curl/lib/cf-h1-proxy.c:1053:3: + /home/runner/work/curl-for-win/curl-for-win/curl/lib/cf-h1-proxy.c:198:27: wa + rning: null pointer dereference [-Wnull-dereference] + 198 | struct h1_tunnel_state *ts = cf->ctx; + | ^~ + ``` + Ref: https://github.com/curl/curl-for-win/actions/runs/8985369476/job/2467921 + 9528#step:3:6320 + + Fixes #13237 + Closes #13555 + +MichaÅ‚ Antoniak (8 May 2024) + +- mbedtls: support TLS 1.3 + + Closes #13539 + +Daniel Stenberg (8 May 2024) + +- version: use msnprintf instead of strncpy + + - to ensure a terminating null byte + - to avoid zero-padding the target + + debug code only + + Closes #13549 + +- curl_path: make Curl_get_pathname use dynbuf + + ... instead of malloc and memcpy + + - unit test 2604 verifies Curl_get_pathname() + + Closes #13550 + +- lib: make protocol handlers store scheme name lowercase + + - saves a lowercase operation when the "[scheme]_proxy" name is + generated + - appears less "shouting" + - update test 970, 972, 1438 and 1536 + + Closes #13553 + +- lib: remove two instances of "only only" messages + + Fixes #13551 + Reported-by: Lucas Nussbaum + Closes #13552 + +Pavel Pavlov (7 May 2024) + +- asyn-thread: fix curl_global_cleanup crash in Windows + + - Make sure that asynchronous resolves handled by Winsock are stopped + before WSACleanup is called. + + This is implemented by ensuring that when Curl_resolver_kill is called + (eg via multi_done) it will cancel the Winsock asynchronous resolve and + wait for the cancellation to complete. Winsock runs the asynchronous + completion routine immediately when a resolve is canceled. + + Prior to this change it was possible that during curl_global_cleanup + "a DNS resolver thread created by GetAddrInfoExW did not terminate yet, + however curl is already shutting down, deinitializing Winsock with + WSACleanup() leading to an access violation." + + Background: + + If libcurl is built with the asynchronous threaded resolver option for + Windows then it resolves in one of two ways. For Windows 8.1 and later, + libcurl resolves by using the Winsock asynchronous resolver which does + its own thread management. For older versions of Windows, libcurl + resolves by creating a separate thread that calls getaddrinfo. This + change only affects the former and it's already handled for the latter. + + Reported-by: Ch40zz@users.noreply.github.com + + Fixes https://github.com/curl/curl/issues/13509 + Closes https://github.com/curl/curl/pull/13518 + +Jay Satiro (7 May 2024) + +- asyn-thread: fix Curl_thread_create result check + + - Compare to curl_thread_t_null instead of 0 for error. + + Currently for both supported thread libraries (pthreads and Windows) + curl_thread_t_null is defined as 0. However, the pattern throughout the + code is to check against curl_thread_t_null and not 0 since for + posterity some thread library may not use 0 for error. + + Closes https://github.com/curl/curl/pull/13542 + +- curl_multibyte: remove access() function wrapper for Windows + + - Remove curlx_win32_access() which was a wrapper to use access() in + Windows. + + This is a follow-up to 602fc213, one of two commits which removed + access() calls from the codebase and banned use of the function. + + Closes https://github.com/curl/curl/pull/13529 + +Daniel Gustafsson (6 May 2024) + +- tls: Remove EXAMPLEs from deprecated options + + CURLOPT_EGDSOCKET and CURLOPT_RANDOM_FILE are both completely dead + so remove their example sections since the code there is useless. + There is still a way to inject a random file for OpenSSL older than + 1.1.0 but it's not what the example showed (and it's not even done + with this option) so we refrain from documenting it here. + + Closes: #13540 + Reviewed-by: Daniel Stenberg + +- tests: Only require EXAMPLE for non-deprecated options + + Manpages which document deprecated CURLOPT_ or CURLINFO_ are not + required to have an EXAMPLE section since they might effectively + be dead no-ops which we don't want to trick users into believing + they can use by copying example code. + + Closes: #13540 + Reviewed-by: Daniel Stenberg + +Daniel Stenberg (6 May 2024) + +- EXPERIMENTAL: add graduation requirements for each feature + + Starting now, experimental features should have a set of documentated + requirements of what is needed for the feature to graduate. + + This adds requirements to all existing experiments. + + Closes #13541 + +Ivan (6 May 2024) + +- misc: fix typos, quoting and spelling + + Fix wording of comments, and misquotings where `' is markdown parsed + where it shouldn't be, and remove a misspelled preprocessor comment + which really isn't needed (and removing it makes it match surrounding + code better). + + Closes: #13538 + Reviewed-by: Daniel Gustafsson + +Daniel Gustafsson (6 May 2024) + +- tests: Mark tftpd timer function as noreturn + + This avoids the below compiler warning: + + tftpd.c:280:1: warning: function 'timer' could be declared with + attribute 'noreturn' [-Wmissing-noreturn] + + Closes: #13534 + Reviewed-by: Daniel Stenberg + +- doh: Remove unused function prototype + + Closes: #13536 + Reviewed-by: Daniel Stenberg + +Daniel Stenberg (6 May 2024) + +- doh: cleanups in ECH related functions + + - make local_decode_rdata_name use dynbuf instead of calloc + memcpy + - avoid extra memdup in local_decode_rdata_alpn + - no need to if() before free() + - use memdup instead of calloc + memcpy in Curl_doh_decode_httpsrr + + Reviewed-by: Stephen Farrell + Closes #13526 + +Viktor Szakats (5 May 2024) + +- libssh2: delete redundant feature guard + + Delete `HAVE_LIBSSH2_VERSION` (equivalent to + `LIBSSH2_VERSION_NUM` > 0x010100) guard surrounding + a `LIBSSH2_VERSION_NUM` > 0x010B00 one. + + Reviewed-by: Daniel Gustafsson + Closes #13537 + +Jan Venekamp (5 May 2024) + +- tool_cfgable: free {proxy_}cipher13_list on exit + + Author: Jan Venekamp + Reviewed-by: Daniel Gustafsson + Closes: #13531 + +RainRat (4 May 2024) + +- doh: Fix typo in comment + + Closes: #13504 + Author: RainRat on Github + Reviewed-by: Daniel Stenberg + Reviewed-by: Daniel Gustafsson + +Christian Schmitz (4 May 2024) + +- dynbuf: Fix returncode on memory error + + Curl_dyn_vaddf should return a proper error code in case allocating + memory failed. + + Closes: #13533 + Author: Christian Schmitz + Reviewed-by: Daniel Gustafsson + +Daniel Stenberg (3 May 2024) + +- RELEASE-NOTES: synced + +Jan Venekamp (2 May 2024) + +- bearssl: use common code for cipher suite lookup + + Take advantage of the Curl_cipher_suite_walk_str() and + Curl_cipher_suite_get_str() functions introduced in commit fba9afeb. + + This also fixes CURLOPT_SSL_CIPHER_LIST not working at all for bearssl + due to commit ff74cef5. + + Closes #13464 + +Daniel Stenberg (2 May 2024) + +- curl.h: change CURL_SSLVERSION_* from enum to defines + + C++20 and later compilers emit a deprecation warning if values from two + different enums are combined with a bitwise operation the way the + CURL_SSLVERSION_* values were previously created. + + Reported-by: Michael Kaufmann + Fixes #13510 + Closes #13511 + +- configure: error on missing perl if docs or manual is enabled + + Fixes #13508 + Reported-by: Harmen Stoppels + Closes #13514 + +- tool_cb_rea: limit rate unpause for -T . uploads + + To avoid getting stuck in a busy-loop when nothing is read from stdin, + this function now checks the call rate and might enforce a short sleep + when called repeatedly without uploading anything. It is a crude + work-around to avoid a 100% busy CPU. + + Reported-by: magisterquis on hackerone + Fixes #13174 + Closes #13506 + +Viktor Szakats (1 May 2024) + +- appveyor: enable websockets for VS2017 jobs + + Follow-up to eb4fe6c6340c3d5b0c347c6e30be004d4f9117d7 #13232 + Closes #13513 + +Daniel Stenberg (30 Apr 2024) + +- if2ip: make the buf_size arg a size_t + + sizes should be size_t + + Ref: #13489 + Closes #13505 + +- cf-https-connect: use timeouts as unsigned ints + + To match the type used in 'set.happy_eyeballs_timeout'. + + Ref: #13489 + Closes #13503 + +- hash: change 'slots' to size_t from int + + - an unsigned type makes more sense + - size_t seems suitable + - on 64 bit args, the struct alignment makes the new Curl_hash remain + the same size + + Closes #13502 + +Viktor Szakats (30 Apr 2024) + +- libssh2: replace `access()` with `stat()` + + Prefer `stat()` to verify the presence of key files. + + This drops the last uses of `access()` in the codebase, which was + reported to cause issues in some cases. + + Also add `access()` to the list of banned functions in checksrc. + + Ref: https://github.com/curl/curl/pull/13412#issuecomment-2065505415 + Ref: https://github.com/curl/curl/pull/13482#issuecomment-2078980522 + Ref: #13497 + Co-authored-by: Jay Satiro + Closes #13498 + +Daniel Stenberg (30 Apr 2024) + +- multi: remove useless assignment + + Spotted by CodeSonar + + Closes #13500 + +- RELEASE-NOTES: synced + +fuzzard (29 Apr 2024) + +- cmake: FindNGHTTP2 add static lib name to find_library call + + Add the static library name, nghttp2_static as a name to search. + + This provides cmake parity with the winbuild Makefile.vc allowing + the cmake build to find and allow the link to static nghttp2 library. + +Viktor Szakats (29 Apr 2024) + +- DISTROS: add patch and issues link for curl-for-win + + curl-for-win sometimes includes curl patches that were already merged in + master, but not yet part of a stable release. + + Also include the Issues link. Build-specific issues are handled there. + + Ref: #13493 + Closes #13499 + +Daniel Stenberg (29 Apr 2024) + +- mime: avoid using access() + + If stat() fails, there is no point in calling access() + + Also: return error immediately if the stat() fails. + + Ref: #13482 + Closes #13497 + +Stefan Eissing (29 Apr 2024) + +- tests: add SNI and peer name checks + + - connect to DNS names with trailing dot + - connect to DNS names with double trailing dot + - rustls, always give `peer->hostname` and let it + figure out SNI itself + - add SNI tests for ip address and localhost + - document in code and TODO that QUIC with ngtcp2+wolfssl + does not do proper peer verification of the certificate + - mbedtls, skip tests with ip address verification as not + supported by the library + + Closes #13486 + +Daniel Stenberg (29 Apr 2024) + +- curl_getdate.md: document two-digit year handling + + Mentioned-by: Paul Gilmartin + Ref: https://curl.se/mail/archive-2024-04/0014.html + Closes #13494 + +Viktor Szakats (29 Apr 2024) + +- cmake: add `BUILD_EXAMPLES` option to build examples + + You can enable it with `-DBUILD_EXAMPLES=ON`. + + To match autotools' `make examples` feature. + Windows (static) builds not tested. + + Also enable examples in a pair of CI jobs. + + Apply related updates to the macOS CI workflow: + - drop unused `CXX` envs. + - drop no longer needed `-Wno-error=undef -Wno-error=conversion` flags. + - pass `-Wno-deprecated-declarations` to GCC too (for `BUILD_EXAMPLES`). + - document why `-Wno-deprecated-declarations` is necessary. + + Closes #13491 + +Stefan Eissing (26 Apr 2024) + +- http3: quiche+ngtcp2 improvements + + - quiche: error transfers that try to receive on a closed + or draining connection + - ngtcp2: use callback for extending max bidi streams. This + allows more precise calculation of MAX_CONCURRENT as we + only can start a new stream when the server acknowledges + the close - not when we locally have closed it. + - remove a fprintf() from h2-download client to avoid excess + log files on tests timing out. + + Closes #13475 + +- vtls: TLS session storage overhaul + + - add session with destructor callback + - remove vtls `session_free` method + - let `Curl_ssl_addsessionid()` take ownership + of session object, freeing it also on failures + - change tls backend use + - test_17, add tests for SSL session resumption + + Closes #13386 + +- multi: multi_wait improvements + + - only call `multi_getsock()` once for all transfers + - realloc pollset array on demand + - fold repeated sockets + + Closes #13150 + +Philip Heiduck (25 Apr 2024) + +- ci: remove microsoft-prod.list + + This is added by default, and it is often broken, but we don't need + anything from it. + + Closes #13473 + +Evgeny Grin (Karlson2k) (25 Apr 2024) + +- curl_setup.h: detect 'inline' support + + Closes #13355 + +Daniel Stenberg (25 Apr 2024) + +- multi: avoid memory-leak risk + + 'newurl' is allocated in some conditions and used in a few scenarios, + but there were theoretical combinations in which it would not get freed. + Move the free to happen unconditionally. Never triggered by tests, but + spotted by Coverity. + + Closes #13471 + +Johann Sebastian Schicho (25 Apr 2024) + +- sendf: Curl_cwriter_write: remove comment disallowing zero length writes + + They are needed to pass CLIENTWRITE_EOS. + + Closes #13477 + +Stefan Eissing (25 Apr 2024) + +- CI: macos fixes for new ARM GHA images + + - based on #13478 with additions from #13476 + - make homebrew install path flexible + - fix OpenSSL pkgconfig files libdir + - add path to --with-libssh2 target + - disable gcc securetransport due to linker + errors (missing symbols), probably because + the os version is no longer low enough + + Assisted-by: Viktor Szakats + + Closes #13479 + +- content_encoding: ignore duplicate chunked encoding + + - ignore duplicate "chunked" transfer-encodings from + a server to accomodate for broken implementations + - add test1482 and test1483 + + Reported-by: Mel Zuser + Fixes #13451 + Closes #13461 + +Daniel Stenberg (25 Apr 2024) + +- tool: move tool_ftruncate64 to tool_util.c + + ... and the prototype to tool_setup.h, to make them both available more + widely and accurately. + + Follow-up to 00bef95946d3511 + + Fixes #13458 + Closes #13459 + +Viktor Szakats (24 Apr 2024) + +- lib: silence `-Wsign-conversion` in base64, strcase, mprintf + + Closes #13467 + +- CI: retain failure code after `./configure` with Circle CI + + Suggested-by: Dan Fandrich + Follow-up to 43299e93c06b96fea8a8dc9b1c2e49c82bc21801 #13462 + Follow-up to d7332e3e46c3ef401b34e6a1a129eb4dd846c452 #12635 + Closes #13468 + +Daniel Stenberg (24 Apr 2024) + +- RELEASE-NOTES: synced + +Jan Venekamp (24 Apr 2024) + +- mbedTLS: implement CURLOPT_SSL_CIPHER_LIST option + + Use a lookup list to set the cipher suites, allowing the + ciphers to be set by either openssl or IANA names. + + To keep the binary size of the lookup list down we compress + each entry in the cipher list down to 2 + 6 bytes using the + C preprocessor. + + Closes #13442 + +Viktor Szakats (24 Apr 2024) + +- CI: show more failed `config.log` on Circle CI + + Show last 1000 lines of `config.log` if `./configure` fails. This was + already done for one job, this patch extends it to all. + + Ref: #13438 + Closes #13462 + +Daniel Stenberg (24 Apr 2024) + +- telnet: check return code from fileno() + + and return error if necessary + + Spotted by CodeSonar + + Closes #13457 + +Viktor Szakats (24 Apr 2024) + +- tls: fix SecureTransport + BearSSL cmake unity builds + + Avoid clashing static function names by namespacing them. + + Pointed-out-by: Jan Venekamp + Ref: https://github.com/curl/curl/pull/13442#discussion_r1576350700 + Closes #13450 + +Jay Satiro (24 Apr 2024) + +- dllmain: Call OpenSSL thread cleanup for Windows and Cygwin + + - Call OPENSSL_thread_stop on thread termination (DLL_THREAD_DETACH) + to prevent a memory leak in case OpenSSL is linked statically. + + - Warn in libcurl-thread.3 that if OpenSSL is linked statically then it + may require thread cleanup. + + OpenSSL may need per-thread cleanup to stop a memory leak. For Windows + and Cygwin if libcurl was built as a DLL then we can do that for the + user by calling OPENSSL_thread_stop on thread termination. However, if + libcurl was built statically then we do not have notification of thread + termination and cannot do that for the user. + + Also, there are several other unusual cases where it may be necessary + for the user to call OPENSSL_thread_stop, so in the libcurl-thread + warning I added a link to the OpenSSL documentation. + + Co-authored-by: Viktor Szakats + + Reported-by: southernedge@users.noreply.github.com + Reported-by: zmcx16@users.noreply.github.com + + Ref: https://www.openssl.org/docs/man3.0/man3/OPENSSL_thread_stop.html#NOTES + + Fixes https://github.com/curl/curl/issues/12327 + Closes https://github.com/curl/curl/pull/12408 + +Jan Venekamp (24 Apr 2024) + +- rustls: remove incorrect SSLSUPP_TLS13_CIPHERSUITES flag + + The rustls backend advertises SSLSUPP_TLS13_CIPHERSUITES, but + the code does not actually seem to support it (yet?). Removed + the flag and corrected documentation. + + Closes #13452 + +Stefan Eissing (24 Apr 2024) + +- quiche: expire all active transfers on connection close + + - when a connection close is detected, all ongoing transfers + need to expire bc no more POLL events are likely to happen + for them. + + Fixes #13439 + Reported-by: Jay Satiro + Closes #13447 + +Dan Fandrich (23 Apr 2024) + +- tests: fix feature case in test1481 + + This test was being skipped everywhere because the feature never + matched. + + Closes #13445 + +Gusted (23 Apr 2024) + +- tool_operate: don't truncate the etag save file by default + + This fixes a regression of 75d79a4486b279100209ddf8c7fdb12955fb66e9. The + code in tool-operate truncated the etag save file, under the assumption + that the file would be written with a new etag value. However since + 75d79a4486b279100209ddf8c7fdb12955fb66e9 that might not be the case + anymore and could result in the file being truncated when --etag-compare + and --etag-save was used and that the etag value matched with what the + server responded. Instead the truncation should not be done when a new + etag value should be written. + + Test 3204 was added to verify that the file with the etag value doesn't + change the contents when used by --etag-compare and --etage-save and + that value matches with what the server returns on a non 2xx response. + + Closes #13432 + +Abdullah Alyan (22 Apr 2024) + +- tests: enable test 1117 for hyper + + Closes #13436 + +Daniel Stenberg (22 Apr 2024) + +- sendf: useless assignment in cr_lc_read() + + Spotted by CodeSonar + + Closes #13437 + +- tool_paramhlp: remove duplicate assign + + Spotted by CodeSonar + + Closes #13433 + +- transfer: remove useless assignment + + in Curl_xfer_recv_resp + + Spotted by CodeSonar + + Closes #13435 + +- http: acknowledge a returned error code + + ... and do not overwrite it with a new value that could then hide the + problem. + + Spotted by CodeSonar + + Closes #13434 + +- tool_operate: init vars unconditionally in post_per_transfer + + In case of (the unlikely) early return, they could otherwise remain + uninitialized + + Spotted by CodeSonar + + Closes #13430 + +- RELEASE-NOTES: synced + +- urlapi: allow setting port number zero + + Also set and check errno when strtoul() parsing numbers for better error + checking. + + Updated test 1560 + + Closes #13427 + +- http_aws_sigv4: remove useless assignment + + This code assigned the variable the same value it already had + + Spotted by CodeSonar + + Closes #13426 + +- file: remove useless assignment + + This code assigned the variable the same value it already had. + + Spotted by CodeSonar + + Closes #13425 + +- test2406: verify -f with HTTP/2 + +Stefan Eissing (19 Apr 2024) + +- http2 + ngtcp2: pass CURLcode errors from callbacks + + - errors returned by Curl_xfer_write_resp() and the header variant are + not errors in the protocol. The result needs to be returned on the + next recv() from the protocol filter. + + - make xfer write errors for response data cause the stream to be + cancelled + + - added pytest test_02_14 and test_02_15 to verify that also for + parallel processing + + Reported-by: Laramie Leavitt + Fixes #13411 + Closes #13424 + +Daniel Stenberg (19 Apr 2024) + +- request: make Curl_req_init return void + + Since it could not return error and therefore this change removes dead + code for the caller. + + Spotted by CodeSonar. + + Closes #13423 + +- multi: remove the unused Curl_preconnect function + + The implementation has been removed, no point in keeping it around. + + Follow-up to 476adfeac019ed + + Closes #13422 + +- Curl_creader_read: init two variables to avoid using them uninited + + Spotted by CodeSonar + + Closes #13419 + +- http: reject HTTP major version switch mid connection + + A connection that has seen an HTTP major version now refuses any other + major HTTP version in future responses. Previously, a HTTP/1.x + connection would just silently accept HTTP/2 or HTTP/3 in the status + lines as long as it had support for those built-in. It would then just + lead to confusion and badness. + + Indirectly Spotted by CodeSonar which identified a duplicate assignment + in this function. + + Add test 471 to verify + + Closes #13421 + +- mqtt: when Curl_xfer_recv returns error, don't use nread + + A returned error code makes other return value unreliable, and in this + case potentially uninitialized. On error, do not read other return + values like the nread counter. + + Spotted by CodeSonar + + Closes #13418 + +- ftp: fix socket leak on rare error + + In the function AcceptServerConnect() the newly created socket would + leak if Curl_conn_tcp_accepted_set() returns error. Which basically + should never happen. + + Spotted by CodeSonar. + + Closes #13417 + +- urlapi: remove unused flags argument from Curl_url_set_authority + + The function is only called from a single place (for HTTP/2 server push) + so might as well just assume this fixed option every time. + + Closes #13409 + +- github/ISSUE_TEMPLATE: tweak the commericual support text + +- github/ISSUE_TEMPLATE: link the GitHub discussions too + + ... and move the feature request line to the bottom. + +- curl_url_get.md: clarify queries and fragments and CURLU_GET_EMPTY + + Follow-up to 3eac21d86bc5 + + Closes #13407 + +Stefan Eissing (18 Apr 2024) + +- tests: check caddy server version to match test expectations + + - new caddy servers no longer return 200 on POSTs, but 405 + as they should + + Closes #13405 + +Daniel Stenberg (18 Apr 2024) + +- curl_url_set.md: extended + + Closes #13404 + +- urlapi: add CURLU_GET_EMPTY for empty queries and fragments + + By default the API inhibits empty queries and fragments extracted. + Unless this new flag is set. + + This also makes the behavior more consistent: without it set, zero + length queries and fragments are considered not present in the URL. With + the flag set, they are returned as a zero length strings if they were in + fact present in the URL. + + This applies when extracting the individual query and fragment + components and for the full URL. + + Closes #13396 + +- RELEASE-NOTES: synced + +- lib1560: test with leading zeroes and more IPv4 versions + + Inspired by WHATWG URL Spec test inputs + + Closes #13400 + +Christian Schmitz (17 Apr 2024) + +- smtp: result of Curl_bufq_cread was not used + + return the result back to the caller. + + Closes #13398 + +Daniel Stenberg (17 Apr 2024) + +- urlapi: fix relative redirects to fragment-only + + Using the URL API for a redirect URL when the redirected-to string + starts with a hash, ie is only a fragment, the API would produce the + wrong final URL. + + Adjusted test 1560 to test for several new redirect cases. + + Closes #13394 + +Jiwoo Park (17 Apr 2024) + +- url: fix use of an uninitialized variable + + Closes #13399 + +Patrick Monnerat (17 Apr 2024) + +- os400: sync with latest changes + + - Conversion support for new version info character field rtmp_version. + - New ILE/RPG declarations. + + Closes #13402 + +Daniel Stenberg (17 Apr 2024) + +- ngtcp2: fix macro use + + macro "H3_STREAM_CTX" requires 2 arguments, but only 1 given + + Follow-up to c6655f7029ec5c128561e3ecf1f93db3ed0432a4 + + Closes #13401 + +Christian Schmitz (17 Apr 2024) + +- sendf: fix two typos in comments + + The parameters are named data, not date. + + Closes #13393 + +- lib: silence warnings on comma misuse + + Building curl with -Wcomma, I see warnings about "possible misuse of + comma operator here" and moving fields assignment out of the for() fixes + it. + + Closes #13392 + +Stefan Eissing (17 Apr 2024) + +- http/2, http/3: decouple stream state from easy handle + + - add `Curl_hash_offt` as hashmap between a `curl_off_t` and + an object. Use this in h2+h3 connection filters to associate + `data->id` with the internal stream state. + - changed implementations of all affected connection filters + - removed `h2_ctx*` and `h3_ctx*` from `struct HTTP` and thus + the easy handle + - solves the problem of attaching "foreign protocol" easy handles + during connection shutdown + + Test 1616 verifies the new hash functions. + + Closes #13204 + +Daniel Stenberg (17 Apr 2024) + +- ROADMAP: remove completed entries, mention websocket + +- THANKS-filter: name fixes + +Christian Schmitz (17 Apr 2024) + +- winbuild: add ENABLE_WEBSOCKETS option + + Closes #13232 + +Daniel Stenberg (17 Apr 2024) + +- dmaketgz: compacter + + Removes the need for disabling shellcheck warnings. + + Follow-up to d28f74913c2 + Proposed-by: Viktor Szakats + Closes #13391 + +Dan Fandrich (16 Apr 2024) + +- tests: Fix uninitialized value warning + + The check for an option must be predicated on options existing at all. + + Follow-up to f7cc9e91 + +Christian Schmitz (17 Apr 2024) + +- idn: add native AppleIDN (icucore) support for macOS/iOS + + I implemented the IDN functions for macOS and iOS using Unicode + libraries coming with macOS and iOS. + + Builds and runs here on macOS 14.2.1. Also verified to load and + run on older macOS version 10.13. + + Build requires macOS SDK 13 or equivalent. + + Set `-DUSE_APPLE_IDN=ON` CMake option to enable it. + With autotools and other build tools, set these manual options: + ``` + CPPFLAGS=-DUSE_APPLE_IDN + LIBS=-licucore + ``` + + Completes TODO 1.6. + + TODO: add autotools option and feature-detection. + + Refs: #5330 #5371 + Co-authored-by: Viktor Szakats + Closes #13246 + +Stefan Eissing (16 Apr 2024) + +- http3: extend download abort tests, fixes in ngtcp2 + + - fix flow handling in ngtcp2 to ACK data on streams + we abort ourself. + - extend test_02_23* cases to also run for h3 + - skip test_02_23* for OpenSSL QUIC as it gets stalled + on progressing the connection + + Closes #13374 + +Daniel Stenberg (16 Apr 2024) + +- tests: add -q as first option when invoking curl for tests + + To reduce the risk that the user running the tests has a .curlrc present + that messes things up. + + Support 'option="no-q"' for the tag to switch it off on demand. + Use this new feature in test 433 and 436. + + Ref: #13284 + Closes #13387 + +- dmaketgz: release tarball generation using docker + + For easier reproducibility. + + Mention using this script in RELEASE-PROCEDURE + + Closes #13388 + +Viktor Szakats (16 Apr 2024) + +- cmake: update ECH code and minor fixups + + - `openssl_check_symbol_exists()` expects a 4th argument now. + Follow-up to edc2702a1fe3a4a5386ffd9aa4f240f0c0197fa2 #13373 + + - minor comment/script touch-ups. + Follow-up to a362962b7289ec02b412890c9515657cf0ed50ac #11922 + + - fix indentation. + + Closes #13383 + +- tests: fix shellcheck issues in `ech_tests.sh` + + Add double-quotes where missing. + + Follow-up to a362962b7289ec02b412890c9515657cf0ed50ac #11922 + Closes #13382 + +- dist: add ECH files to tarball + + Also sort `EXTRA_DIST` list in `tests/Makefile.am` and make it diffable. + + Follow-up to a362962b7289ec02b412890c9515657cf0ed50ac #11922 + Closes #13381 + +- openvms: look for `USE_IPV6` in `config.h` (was: `ENABLE_IPV6`) + + The OpenVMS script `config_h.com` is parsing the config header + generated by autotools. Let's make it look for the macro name we now + use universally across the codebase. + + Follow-up to e411c98f702f0fb38dceec95e7507ef15a00d12c #13349 + Closes #13360 + +daniel-j-h (16 Apr 2024) + +- Dockerfile: for release automation and reproducibility + + Closes #13250 + +Stefan Eissing (16 Apr 2024) + +- cw-out: improved error handling + + - remember error encountered in invoking write callback and always fail + afterwards without further invokes + + - check behaviour in test_02_17 with h2-pausing client + + Reported-by: Pavel Kropachev + Fixes #13337 + Closes #13340 + +Daniel Stenberg (16 Apr 2024) + +- version: add "ECH" as a feature + + If available + + Follow-up to a362962b7 + Closes #13378 + +- CURLOPT_ECH: polish + + - remove the pointer to build instructions, it won't work in manpages + - add see-also + - minor white space edits + + Closes #13379 + +Viktor Szakats (16 Apr 2024) + +- tidy-up: whitespace [ci skip] + +- mbedtls: fix building with v3 in CMake Unity mode + + Before this patch the internal feature detection macro + `HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS` was defined in three files, + with an incomplete logic in one of them. In Unity mode that spilled + into another source file and broke the build. + + Closes #13377 + +- cmake: add librtmp/rtmpdump option and detection + + Add CMake option `USE_LIBRTMP`. Disabled by default. + + This library requires OpenSSL TLS-backend when linked statically. + + Follow-up to 6eb9e65781fa1fd8a0bcfe0715187a3a35f09ae4 #13364 + Closes #13373 + +Stephen Farrell (16 Apr 2024) + +- TLS: add support for ECH (Encrypted Client Hello) + + An EXPERIMENTAL feature used with CURLOPT_ECH and --ech. + + Closes #11922 + +Daniel Stenberg (15 Apr 2024) + +- RELEASE-NOTES: synced + +- multi: introduce SETUP state for better timeouts + + Since we can go to the CONNECT state from PENDING, potentially multiple + times for a single transfer, this change introdues a SETUP state that + happens before CONNECT when doing a new transfer. + + Now, doing a redirect on a handle goes back to SETUP (not CONNECT like + before) and we initilize the connect timeout etc in SETUP. Previously, + we would do it in CONNECT but that would make it unreliable in cases + where a transfer goes in and out between CONNECT and PENDING multiple + times. + + SETUP is transient, so the handle never actually stays in that state. + + Additionally: take care of timeouts of PENDING transfers in + curl_multi_perform() + + Ref: #13227 + Closes #13371 + +Tal Regev (15 Apr 2024) + +- cmake: forward `USE_LIBRTMP` option to C + + Define in C `USE_LIBRTMP` if user requested it from cmake. + + Closes #13364 + +Daniel Stenberg (15 Apr 2024) + +- curl_version_info: provide librtmp version + + Ref: https://github.com/curl/curl/pull/13364#issuecomment-2054151942 + Reported-by: talregev on github + Closes #13368 + +blankie (15 Apr 2024) + +- docs: clarify CURLOPT_MAXFILESIZE and CURLOPT_MAXFILESIZE_LARGE + + The bounds of the size parameter were not specified, and nor was it + specified how to disable the maximum file size check. + + The documentation also incorrectly stated that CURLOPT_MAXFILESIZE + always returns CURLE_OK and that CURLOPT_MAXFILESIZE_LARGE only returns + CURLE_OK or CURLE_UNKNOWN_OPTION. + + It also did not mention what the default value is, which is zero. This + commit updates the documentation to make note of all these things. + + Closes #13372 + +Patrick Monnerat (15 Apr 2024) + +- OS400: post-shellcheck changes adjustments + + Build scripts must be executed by the os/400 shell (sh), not bash which + is a PASE program. + + Shell function get_make_vars() escaping reworked to match $() subcommand + construct. + + Follow-up to 8a622baf9e9233241bbe93d6599c99cb46478614 + Closes #13366 + +Viktor Szakats (15 Apr 2024) + +- OS400: tidy-up + + Drop/fixup mods trying to make some syntax highlighters happier. + + Follow-up to 8a622baf9e9233241bbe93d6599c99cb46478614 #13309 + Closes #13362 + +Daniel Stenberg (15 Apr 2024) + +- multi: timeout handles even without connection + + When there is a "change" in a multi handle and pending handles are moved + back to the main list to be retested if they can proceed further (for + example a previous transfer completed or a connection has a confirmed + multiplexed state), the timeout check in multi_runsingle() would not + trigger because it required an established connection. + + This could make a pending tranfer go back to pending state even though + it had been "in progress" for a longer time than permitted. By removing + the requirement for an associated connection, the timeout check will be + done proper even for transfers that has not yet been assigned one. + + Ref #13227 + Reported-by: Rahul Krishna M + Closes #13276 + +Patrick Monnerat (15 Apr 2024) + +- mprintf: check fputc error rather than matching returned character + + OS/400 ascii fputc wrapper deviates from the posix standard by the + fact that it returns the ebcdic encoding of the original ascii + character. Testing for a matching value for success will then always + fail. + + This commit replaces the chariacter comparison by an explicit error + return check. + + Follow-up to ef2cf58 + Closes #13367 + +Viktor Szakats (14 Apr 2024) + +- ci: add CMake build variation, fixup libssh detection in `linux-old` + + To test without c-ares and hit `easy_lock.h` on an old system. Use this + new build step to introduce small variations, and also test libssh2. + + Also add workaround to existing job to enable libssh. (CMake's generic + auto-detection doesn't seem to work here.): + ``` + CMake Warning at CMakeLists.txt:908 (find_package): + Could not find a package configuration file provided by "libssh" with any + of the following names: + + libsshConfig.cmake + libssh-config.cmake + ``` + Ref: https://github.com/curl/curl/actions/runs/8661316091/job/23750974358#ste + p:5:69 + + Closes #13361 + +- lib: merge `ENABLE_QUIC` C macro into `USE_HTTP3` + + Before this patch `lib/curl_setup.h` defined these two macros right + next to each other, then the source code used them interchangeably. + + After this patch, `USE_HTTP3` guards all HTTP/3 / QUIC features. + (Like `USE_HTTP2` does for HTTP/2.) `ENABLE_QUIC` is no longer used. + + This patch doesn't change the way HTTP/3 is enabled via autotools + or CMake. Builders who enabled HTTP/3 manually by defining both of + these macros via `CPPFLAGS` can now delete `-DENABLE_QUIC`. + + Closes #13352 + +- build: prefer `USE_IPV6` macro internally (was: `ENABLE_IPV6`) + + Before this patch, two macros were used to guard IPv6 features in curl + sources: `ENABLE_IPV6` and `USE_IPV6`. This patch makes the source use + the latter for consistency with other similar switches. + + `-DENABLE_IPV6` remains accepted for compatibility as a synonym for + `-DUSE_IPV6`, when passed to the compiler. + + `ENABLE_IPV6` also remains the name of the CMake and `Makefile.vc` + options to control this feature. + + Closes #13349 + +Dan Fandrich (12 Apr 2024) + +- DISTROS: mark rolling release distros + + These are ones that are unlikely to have back-ported curl patches. + + Closes #13353 + +Daniel Stenberg (12 Apr 2024) + +- mbedtls: cut off trailing newlines from debug logs + + To avoid double newlines in the output. + + Reported-by: Gisle Vanem + Fixes #13321 + Closes #13356 + +- RELEASE-NOTES: synced + +Stefan Eissing (12 Apr 2024) + +- CURLINFO_REQUEST_SIZE: fixed, add tests for transfer infos reported + + - tests for 'size_request' and other stats reported, for + presence and consistency + + Reported-by: Jonatan Vela + Fixes #13269 + Closes #13275 + +Viktor Szakats (11 Apr 2024) + +- dist: add files missing from release tarball + + Closes #13346 + +- ci: parallelize more, tidy up cmake commands (distcheck, macos) + + Also enable `-DCURL_WERROR=ON` in the Linux cmake build test. + + Closes #13343 + +Toon Claes (11 Apr 2024) + +- docs: add CURLOPT_NOPROGRESS to CURLOPT_XFERINFOFUNCTION example + + It's important to set `CURLOPT_NOPROGRESS` to `0` if you want your + transfer callback function, set by `CURLOPT_XFERINFOFUNCTION`, getting + called. To emphasize this to the users, add this to the code example. + + Closes #13348 + +RainRat (11 Apr 2024) + +- misc: fix typos + + Closes #13344 + +Colin Leroy-Mira (11 Apr 2024) + +- file: add support for getting basic directory listings + + Not supported on Windows (yet) + + Closes #13137 + +Viktor Szakats (11 Apr 2024) + +- ci: add curl-for-win builds: Linux MUSL, macOS, Windows + + Linux MUSL (llvm/clang), macOS Apple clang, Windows (llvm/clang). + + Configured with HTTP/2 and HTTP/3 and other dependencies (the default + curl-for-win) for a comprehensive build test. + + ``` + curl 8.8.0-DEV (x86_64-unknown-linux-musl) libcurl/8.8.0-DEV LibreSSL/3.9.1 z + lib/1.3.1 brotli/1.1.0 zstd/1.5.6 libpsl/0.21.5 libssh2/1.11.0 nghttp2/1.61.0 + ngtcp2/1.4.0 nghttp3/1.2.0 + Protocols: dict file ftp ftps gopher gophers http https imap imaps ipfs ipns + mqtt pop3 pop3s rtsp scp sftp smb smbs smtp smtps telnet tftp ws wss + Features: alt-svc AsynchDNS brotli HSTS HTTP2 HTTP3 HTTPS-proxy IPv6 Largefil + e libz NTLM PSL SSL threadsafe UnixSockets zstd + + curl 8.8.0-DEV (x86_64-apple-darwin) libcurl/8.8.0-DEV LibreSSL/3.9.1 zlib/1. + 3.1 brotli/1.1.0 zstd/1.5.6 libpsl/0.21.5 libssh2/1.11.0 nghttp2/1.61.0 ngtcp + 2/1.4.0 nghttp3/1.2.0 + Protocols: dict file ftp ftps gopher gophers http https imap imaps ipfs ipns + ldap ldaps mqtt pop3 pop3s rtsp scp sftp smb smbs smtp smtps telnet tftp ws w + ss + Features: alt-svc AsynchDNS brotli HSTS HTTP2 HTTP3 HTTPS-proxy IPv6 Largefil + e libz NTLM PSL SSL threadsafe UnixSockets zstd + + curl 8.8.0-DEV (x86_64-w64-mingw32) libcurl/8.8.0-DEV LibreSSL/3.9.1 zlib/1.3 + .1 brotli/1.1.0 zstd/1.5.6 WinIDN libpsl/0.21.5 libssh2/1.11.0 nghttp2/1.61.0 + ngtcp2/1.4.0 nghttp3/1.2.0 + Protocols: dict file ftp ftps gopher gophers http https imap imaps ipfs ipns + ldap ldaps mqtt pop3 pop3s rtsp scp sftp smb smbs smtp smtps telnet tftp ws w + ss + Features: alt-svc AsynchDNS brotli HSTS HTTP2 HTTP3 HTTPS-proxy IDN IPv6 Kerb + eros Largefile libz NTLM PSL SPNEGO SSL SSPI threadsafe UnixSockets zstd + ``` + + Limited to x64, because for build testing the additional CPUs don't add + much value compared to the extra build time. They can be enabled easily + if deemed useful. + + To the extent of curl-for-win configuration options, it's trivial to add + further build combinations. + + Closes #13335 + +- OS400: fix shellcheck warnings in scripts + + - use `$()` instead of backticks, and re-arrange double-quotes inside. + - add missing `|| exit 1` to `cd` calls. (could be dropped by using `set -eu` + .) + - add `-n` to a few `if`s. + - shorten redirections by using `{} >` (as shellcheck recommended). + - silence warnings where variables were detected as unused (SC2034). + - a couple misc updates to silence warnings. + - switch to bash shebang for `-ot` feature. + - split two lines to unbreak syntax highlighting in my editor. (`$(expr \`, ` + $(dirname \`) + + Also enable CI checks for OS/400 shell scripts. + + Ref: #13307 + Closes #13309 + +Stefan Eissing (11 Apr 2024) + +- lib: add Curl_xfer_write_resp_hd + + Add method in protocol handlers to allow writing of a single, + 0-terminated header line. Avoids parsing and copying these lines. + + Closes #13165 + +- llist: add Curl_llist_append() + + - use for better readability in all places where the "insert_next" + actually performs an append to the list + - add some tests in unit1300 + + Closes #13336 + +- gnutls: lazy init the trust settings + + - delay loading of trust anchors and CRLs after the ClientHello + has been sent off + - add tracing to IO operations + - on IO errors, return the CURLcode of the underlying filter + + Closes #13339 + +Marcel Raad (10 Apr 2024) + +- http_negotiate: fix `CURL_DISABLE_PROXY` build + + `proxyuserpwd` was removed from `dynamically_allocated_data` in commit + f46385d36df. + + Closes https://github.com/curl/curl/pull/13334 + +Viktor Szakats (10 Apr 2024) + +- quic: fixup duplicate static function name (for cmake unity) + + Visible in daily curl-for-win builds: + https://github.com/curl/curl-for-win/actions/runs/8621925870 + + ``` + lib/vquic/curl_ngtcp2.c:1916:12: error: redefinition of 'ossl_new_session_cb' + static int ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid) + ^ + lib/vtls/openssl.c:2978:12: note: previous definition is here + static int ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid) + ^ + ``` + https://github.com/curl/curl-for-win/actions/runs/8621925870/job/23631885439# + step:3:6965 + + Follow-up to 3210101088dfa3d6a125d213226b092f2f866722 #13172 + Closes #13332 + +- appveyor: make VS2010 job build-only, enable Schannel, fix compiler warnings + + Tests were consistently flaky for a while. + + Also fix compiler warnings in `CertOpenStore()` calls for old MSVC compilers: + ``` + C:/projects/curl/lib/vtls/schannel.c(688): + warning C4306: 'type cast' : conversion from 'int' to 'LPCSTR' of greater s + ize + C:/projects/curl/lib/vtls/schannel_verify.c(642): + warning C4306: 'type cast' : conversion from 'int' to 'LPCSTR' of greater s + ize + ``` + Ref: https://ci.appveyor.com/project/curlorg/curl/builds/49580310/job/ywu2y44 + kymgc0nif#L106 + + Closes #13330 + +Daniel Stenberg (10 Apr 2024) + +- projects: drop MSVC project files for recent versions + + We encourage users to generate visual studio project files using CMake. + + We keep project files in git for ancient visual studio versions that + cmake cannot generate files for, but we no longer ship the project files + in the tarballs. + + appveyor: switch VisualStudioSolution job to VC12 (Visual Studio 2013) + + Co-Authored-by: Viktor Szakats + Co-Authored-by: Jay Satiro + + Closes #13311 + +Viktor Szakats (9 Apr 2024) + +- cmake: use namespaced custom target names + + Rename custom target to namespaced (unique) names to avoid colliding + with 3rd-party projects (e.g. libzip) built together with curl. + + Reported-by: hammlee96 on github + Fixes #13324 + Closes #13326 + +- appveyor: re-enable OpenSSL 3, bump to 3.2.1 + + Ref: b62454a875d70f93ab5347c050903596feb45a23 #13266 + Closes #13329 + +Stefan Eissing (9 Apr 2024) + +- CI: upgrade openssl version to 3.3.0 for openssl-quic + + Closes #13328 + +Daniel Stenberg (9 Apr 2024) + +- RELEASE-NOTES: synced + + Bump to 8.8.0-DEV + +- curl_multi_waitfds.md: add protocol mention + + Follow-up to 02beac6bb6b + +Dmitry Karpov (9 Apr 2024) + +- lib: add curl_multi_waitfds + + New function call, similar to curl_multi_fdset() + + Closes #13135 + +Viktor Szakats (9 Apr 2024) + +- dist: verify tarball reproducibility in CI + + Closes #13327 + +Stefan Eissing (9 Apr 2024) + +- tests: stabilitze test_02_23* + + - h2-download now always opens the output file on first write callback + invocation, if it will pause the transfer or not. + - Checks on output files then does not depend on the amount of data curl + has collected for the first write. + + Closes #13323 + +- tls: fix compile issues on old-linux CI + + Follow-up to 3210101088dfa + Closes #13325 + +Viktor Szakats (9 Apr 2024) + +- dist: add reproducible dir entries to tarballs + + In the initial implementation of reproducible tarballs, they were + missing directory entries, while .zip archives had them. It meant + that on extracting the tarball, on-disk directory entries got the + current timestamp. + + This patch fixes this by including directory entries in the tarball, + with reproducible timestamps. It also moves sorting inside tar, + to ensure reproducible directory entry timestamps on extract + (without the need of `--delay-directory-restore` option, when + extracting with GNU tar. BSD tar got that right by default.) + + GNU tar 1.28 (2014-07-28) introduced `--sort=`. + + Ref: https://github.com/curl/curl/pull/13299#discussion_r1555957350 + Follow-up to 860cd5fc2dc8e165fadd2c19a9b7c73b3ae5069d #13299 + Closes #13322 + +Stefan Eissing (9 Apr 2024) + +- tls: use shared init code for TCP+QUIC + + Closes #13172 + +Daniel Stenberg (9 Apr 2024) + +- .mailmap: update Gisle's preferred email + +Jan Macku (9 Apr 2024) + +- doc: pytest `--repeat` -> `--count` + + Pytest doesn't have a `--repeat` option, but it does have a `--count` + option. + + ``` + --count=COUNT Number of times to repeat each test + ``` + + Closes #13218 + +Daniel Stenberg (9 Apr 2024) + +- src/Makefile.am: access curl.txt using a relative path, not abs + + ... to make it work when mounted using different mount points. Like when + generated/used inside and outside of a docker image. + + Closes #13320 + +- build: remove MacOSX-Framework script + + I don't think this is much used these days. + + Also remove the libcurl.plist file used (only) by this script + + Closes #13313 + +- release-tools.sh: store the timestamp and release tag too + + When maketgz invokes this script to generate the docs/RELEASE-TOOLS.md + file that gets bundled in the release, it now also passes on the exact + timestamp and version number so that those details also get mentioned in + the document. They will help users reproduce an identical tarball. + + Closes #13319 + +Viktor Szakats (8 Apr 2024) + +- GHA: disable permissions where missing + + Reviewed-by: Daniel Stenberg + Closes #13306 + +Stefan Eissing (8 Apr 2024) + +- CI: update component versions + + - ngtcp2: v1.4.0 + - nghttp3: v1.2.0 + - nghttp2: v1.61.0 + - mod_h2: v2.0.27 + + Closes #13316 + +Jérôme Leclercq (8 Apr 2024) + +- CMake: check fseeko after detecting HAVE_FILE_OFFSET_BITS + + Closes #13264 + +Stefan Eissing (8 Apr 2024) + +- http2: emit RST when client write fails + + - When the writing of response data fails, reset the stream + and do not return a callback error to nghttp2. That would + be a fatal error for the connection and harm other requests. + - add test cases for various abort scenarios + + Reported-by: Konstantin Kuzov + Fixes #13292 + Closes #13298 + +Kailun Qin (8 Apr 2024) + +- mbedtls: call mbedtls_ssl_setup() after RNG callback is set + + Since mbedTLS v3.6.0, the RNG check added in ssl_conf_check() will fail + if no RNG is provided when calling mbedtls_ssl_setup(). + + Therefore, mbedtls_ssl_conf_rng() needs to be called before the SSL + context is passed to mbedtls_ssl_setup(). + + Ref: https://github.com/Mbed-TLS/mbedtls/commit/b422cab052b51ec84758638d6783d + 6ba4fc60613 + + Signed-off-by: Kailun Qin + Closes #13314 + +Daniel Stenberg (8 Apr 2024) + +- NTLM_WB: drop support + + The feature has not worked for months and has been marked as DEPRECATED + for six+ months. + + Closes #13249 + +- curl_trc: fix build error when lacking verbose messages + + Follow-up from 0b28ece657b2273 + Closes #13312 + +Viktor Szakats (8 Apr 2024) + +- contrithanks: honor `CURLWWW` variable + + Reviewed-by: Daniel Stenberg + Closes #13315 + +- GHA: add shellcheck job and fix warnings, shell tidy-ups + + Reviewed-by: Daniel Stenberg + Closes #13307 + +- dist: do not require Perl in `maketgz` + + Perl remains required for the tarball build process. + + Follow-up to 860cd5fc2dc8e165fadd2c19a9b7c73b3ae5069d #13299 + + Reviewed-by: Daniel Stenberg + Closes #13310 + +Daniel Stenberg (8 Apr 2024) + +- RELEASE-NOTES: synced + +- docs/cmdline-opts: invoke managen using a relative path + + ... no need to use an absolute path, that makes the build unncessarily + fail if invoked using a different mount point. managen now takes options + to find the input files. + + Update test1478 to provide the dir arguments to managen + + Closes #13281 + +- GHA: add valgrind to a wolfSSL build + + Closes #13274 + +Viktor Szakats (7 Apr 2024) + +- dist: `set -eu`, fix shellcheck, make reproducible and smaller tarballs + + - set bash `-eu` and fix fallouts. + - fix shellcheck warnings. + - set and use `SOURCE_DATE_EPOCH` for reproducibility. + Authored-by: Daniel J. H. + Ref: #13280 + - set `TZ=UTC` and `LC_ALL=C` for reproducibility. + - make file timestamps in tarball/zip reproducible. + - make directory timestamps in zip reproducible. + - make timestamps of tarballs/zip reproducible. + - make file order in tarball/zip reproducible. + - omit extra file metadata from zip for reproducibility. + - use maximum zip compression. + - use POSIX `ustar` tarball format to avoid supply chain vulnerability: + https://seclists.org/oss-sec/2021/q4/0 + - make uid/gid in tarball reproducible. + - omit owner user/group names from tarball for reproducibility and privacy. + - omit current timestamp from .gz header for reproducibility. + - display SHA-256 hashes of produced tarballs/zip. + - fix whitespace. + + `.tar.gz` also became smaller in the process: 4,462,311 -> 4,148,249 bytes (8 + .7.1) + + Requires GNU tar, GNU date, `sha256sum`. + + Reviewed-by: Daniel Stenberg + Ref: #13250 + Closes #13299 + +Gisle Vanem (7 Apr 2024) + +- tests/http: fix compiler warning + + - Init result code variable to fix clang warning that it may be used + uninitialized. + + Fixes https://github.com/curl/curl/issues/13301 + Closes https://github.com/curl/curl/pull/13304 + +Stefan Eissing (6 Apr 2024) + +- vquic: use new curl_int64_t type + + - add curl_int64_t signed 64-bit type for lib use + + - define CURL_PRId64, CURL_PRIu64 format ids + + - use curl_int64_t in vquic + + curl_int64_t signed complements the existing curl_uint64_t unsigned. + + Note that `curl_int64_t` and `int64_t` are assignable from each other + but not identical. Some platforms with 64 long type defint int64_t as + "long long" (staring at macOS) which messes up things like pointers and + format identifiers. + + Closes https://github.com/curl/curl/pull/13293 + +Jay Satiro (5 Apr 2024) + +- lib: use multi instead of multi_easy for the active multi + + - Use data->multi and not data->multi_easy to refer to the active multi. + + The easy handle's active multi is always data->multi. + + This is a follow up to 757dfdf which changed curl so that an easy handle + used with the easy interface and then multi interface cannot have two + different multi handles associated with it at the same time + (data->multi_easy from the easy interface and data->multi from the multi + interface). + + Closes https://github.com/curl/curl/pull/12665 + +Viktor Szakats (5 Apr 2024) + +- tidy-up: whitespace [ci skip] + +Daniel Stenberg (5 Apr 2024) + +- makefile: remove the sorting from the vc-ide action + + This target generates the MSVC project files. This change removes the + extra sorting and instead makes the script use the order of the files as + listed in the variables - which are mostly sorted anyway. + + This is an attempt to make the project file generation more easily + reproducible. + + Ref: #13250 + Closes #13294 + +Gisle Vanem (5 Apr 2024) + +- bearssl: fix compiler warnings + + "variables may be uninitialized when used" + + Fixes #13290 + Closes #13297 + +Daniel Stenberg (5 Apr 2024) + +- DISTROS: Cygwin updates + + Brought-by: Brian Inglis + Fixes #13258 + Co-authored-by: Viktor Szakats + Closes #13279 + +Stefan Eissing (5 Apr 2024) + +- lib: add trace support for client reads and writes + + - add `CURL_TRC_READ()` and `CURL_TRC_WRITE()` + - use in generic client writers and readers, as well + as http headers, chunking and websockets + + Closes #13223 + +MichaÅ‚ Antoniak (5 Apr 2024) + +- urldata: remove fields not used depending on used features + + Reduced size of dynamically_allocated_data structure. + + Reduced number of stored values in enum dupstring and enum dupblob. This + affects the reduced array placed in the UserDefined structure. + + Closes #13188 + +Viktor Szakats (5 Apr 2024) + +- cmake: enable `-pedantic-errors` for clang when `CURL_WERROR=ON` + + clang doesn't have the issues of GCC and old CMake versions. + + Note: This introduces asymmetry with autotools, which only enables + this for GCC. + + Reviewed-by: Daniel Stenberg + Closes #13286 + +- cmake: fix `CURL_WERROR=ON` for old CMake and use it in GHA/linux-old + + - cmake: fix `-pedantic-errors` for old CMake with `CURL_WERROR=ON` set. + + `-pedantic-errors` option throws a warning with GCC (all versions) and + makes `check_symbol_exists()` fail in CMake versions older than + v3.23.0 (2022-03-29), when CMake introduced a workaround: + + https://gitlab.kitware.com/cmake/cmake/-/issues/13208 + https://gitlab.kitware.com/cmake/cmake/-/commit/eeb45401163d831b8c841ef6eba + 81466b4067b68 + https://gitlab.kitware.com/cmake/cmake/-/commit/1ab7c3cd28b27ca162c4559e102 + 6e5cad1898ade + + Follow-up to 3829759bd042c03225ae862062560f568ba1a231 #12489 + + - set `CURL_WERROR=ON` for the `linux-old` job in CI. + + Closes #13282 + +- lib: use `#error` instead of invalid syntax in `curl_setup_once.h` + + Reviewed-by: Daniel Stenberg + Closes #13287 + +Daniel Stenberg (5 Apr 2024) + +- GHA: on macOS remove $HOME/.curlrc + + A recent image upgrade added a $HOME/.curlrc by default using --ipv4. + + Ref: https://github.com/actions/runner-images/pull/9586 + Fixes #13284 + Closes #13285 + +Viktor Szakats (4 Apr 2024) + +- cmake: fixup `DEPENDS` filename + + Fixing: + ``` + make[2]: Circular docs/curl-config.1 <- docs/curl-config.1 dependency dropped + . + make[2]: Circular docs/mk-ca-bundle.1 <- docs/mk-ca-bundle.1 dependency dropp + ed. + ``` + Ref: https://github.com/curl/curl/actions/runs/8559617487/job/23456740844?pr= + 13282#step:6:18 + + Follow-up to 5023ffad2c27d4b916ddb91800f99ecc5d3aad07 #13197 + Closes #13283 + +- GHA: enable unity mode for cmake jobs + tidy-ups + + Unity mode is not supported by CMake v3.7.2 used in linux-old, but + enable it anyway for consistency and to kick in automatically once + migrating to a newer old Linux in the future. + + Also: + - replace `CMAKE_COMPILE_WARNING_AS_ERROR` with `CURL_WERROR`. + - delete default build option `PICKY_COMPILER=ON`. + + Closes #13277 + +Dan Fandrich (4 Apr 2024) + +- CI: Add CI build on Debian stretch to test old support + + This version still has ELTS support and contains some old versions of + key components like cmake to help prevent us from breaking that support. + + Closes #13029 + +Stefan Eissing (4 Apr 2024) + +- request: paused upload on completed download, assess connection + + A transfer with a completed download that is still uploading needs to + check the connection state when it is PAUSEd, since connection + close/errors would otherwise go unnoticed. + + Reported-by: Sergey Bronnikov + Fixes #13260 + Closes #13271 + +Daniel Stenberg (4 Apr 2024) + +- url: do not URL decode proxy crendentials + + The two options CURLOPT_PROXYUSERNAME and CURLOPT_PROXYPASSWORD set the + actual names as-is, not URL encoded. + + Modified test 503 to use percent-encoded strings in the credential + strings that should be passed on as-is. + + Reported-by: Sergey Ogryzkov + Fixes #13265 + Closes #13270 + +Viktor Szakats (4 Apr 2024) + +- appveyor: enable cmake unity mode by default + + Leave one non-unity cmake job. This makes the jobs finish slightly + quicker, while giving more coverage for unity issues. + + Before: + https://ci.appveyor.com/project/curlorg/curl/builds/49496977 + https://ci.appveyor.com/project/curlorg/curl/builds/49500372 + After: + https://ci.appveyor.com/project/curlorg/curl/builds/49500338 + + Also fixup unrelated whitespace. + + Reviewed-by: Daniel Stenberg + Closes #13217 + +Daniel Stenberg (4 Apr 2024) + +- RELEASE-NOTES: synced + +Viktor Szakats (4 Apr 2024) + +- cmake: speed up libcurl doc building again + + This time limit the number of files per command to avoid exceeding + limitations of certain OS/shell envs. + + Such known env is Windows with the `cmd.exe` shell, which features an + 8K command-line length limit to this day. + + Allowlisting `UNIX` to have no limit and using a limit of 200 for other + envs to be safe. If there is a way to detect `cmd.exe` and/or we know + which precise envs are sensitive to this, we can tweak these conditions + further. + + Even with the low limit, this patch reduces external commands by 200x, + making builds much faster. + + Ref: #12762 2620aa930bc73af1e4c70b10e3125b957b96ecfb (initial) + Ref: #13047 f03c85635f35269f1f45b983bf216624f541760a (revert) + + Reviewed-by: Daniel Stenberg + Closes #13207 + +- cmake: tidy-up to use `WORKING_DIRECTORY` + + Reviewed-by: Daniel Stenberg + Closes #13206 + +- cmake: generate misc manpages and install `mk-ca-bundle.pl` + + - install `mk-ca-bundle.pl` like autotools does. + + - generate and install `mk-ca-bundle.1` and `curl-config.1` like + autotools. This fixes tests 1140 and 1173. + + Reported-by: Dan Fandrich + Fixes #13194 + + - add option `BUILD_MISC_DOCS` to control building the above two + manpages. Enabled by default. + + - appveyor: stop disabling tests 1140 and 1173. + + Reviewed-by: Daniel Stenberg + Closes #13197 + +Fabian Keil (4 Apr 2024) + +- wolfssl: plug memory leak in wolfssl_connect_step2() + + Fixes: + + test 2034...[simple HTTPS GET with DER public key pinning] + ==61829== 22,610 (3,744 direct, 18,866 indirect) bytes in 1 blocks are d + efinitely lost in loss record 51 of 54 + ==61829== at 0x484BB74: malloc (vg_replace_malloc.c:446) + ==61829== by 0x4B53A80: wolfSSL_Malloc (memory.c:344) + ==61829== by 0x4C1C8E1: wolfSSL_X509_new (x509.c:5326) + ==61829== by 0x4C3977D: d2i_X509orX509REQ (x509.c:3628) + ==61829== by 0x4C1D1F4: wolfSSL_X509_d2i (x509.c:3664) + ==61829== by 0x4C1C37B: wolfSSL_X509_dup (x509.c:13425) + ==61829== by 0x4C197DB: wolfSSL_get_peer_certificate (ssl.c:18765) + ==61829== by 0x33297C: wolfssl_connect_step2 (wolfssl.c:875) + ==61829== by 0x331669: wolfssl_connect_common (wolfssl.c:1287) + ==61829== by 0x3303E9: wolfssl_connect_nonblocking (wolfssl.c:1319) + ==61829== by 0x32FE89: ssl_connect_nonblocking (vtls.c:510) + ==61829== by 0x32DBE5: ssl_cf_connect (vtls.c:1679) + ==61829== by 0x27ABD7: Curl_conn_cf_connect (cfilters.c:307) + ==61829== by 0x27D9CF: cf_setup_connect (connect.c:1199) + ==61829== by 0x27ABD7: Curl_conn_cf_connect (cfilters.c:307) + ==61829== by 0x283CEA: cf_hc_baller_connect (cf-https-connect.c:135) + + Closes #13272 + +Viktor Szakats (3 Apr 2024) + +- appveyor: OpenSSL 3 no longer found by CMake, revert to 1.1.1 + + OpenSSL moved directories, and bumped versions in AppVeyor CI. + + Downgrading is not an ideal solution, but however trivial the solution + may be, I failed to come with anything that made CMake recognize either + OpenSSL 3.1 or 3.2. + + Possibly caused by: + https://github.com/appveyor/build-images/commit/702e8cdca01f28f6a40687783f493 + c786cebbe2c + https://github.com/appveyor/build-images/pull/149 + + Closes #13266 + +hongfei.li (3 Apr 2024) + +- winbuild: use $(RC) correctly + + Cloes #13267 + +Daniel Stenberg (3 Apr 2024) + +- dist: remove the curl-config.1 from the tarball + + The markdown file is already there and the .1 file gets generated in the + build. + + Ref: #13250 + Closes #13268 + +- curl_global_trace.md: shorten the description + + Closes #13263 + +- test1901: verify chunked POST from callback with CURLOPT_POSTFIELDSIZE set + + Follow-up to 721941aadf4ad + + Ref: #13257 + Closes #13262 + +Stefan Eissing (2 Apr 2024) + +- http: with chunked POST forced, disable length check on read callback + + - when an application forces HTTP/1.1 chunked transfer encoding + by setting the corresponding header and instructs curl to use + the CURLOPT_READFUNCTION, disregard any POST length information. + - this establishes backward compatibility with previous curl versions + + Applications are encouraged to not force "chunked", but rather + set length information for a POST. By setting -1, curl will + auto-select chunked on HTTP/1.1 and work properly on other HTTP + versions. + + Reported-by: Jeff King + Fixes #13229 + Closes #13257 + +Jay Satiro (1 Apr 2024) + +- INSTALL-CMAKE.md: explain `cmake -G ` + + - Explain that CMake's -G option can be used to specify which build + system to generate files for. + + Example: cmake ../curl -G "MinGW Makefiles" + + Ref: https://github.com/curl/curl/pull/12224#issuecomment-2026813645 + + Closes https://github.com/curl/curl/pull/13244 + +Daniel Stenberg (1 Apr 2024) + +- libcurl-opts: mention pipelining less + + libcurl has not supported HTTP pipelining since many years. Remove a few + (more) mentions of the feature. + + Closes #13254 + +Daniel McCarney (31 Mar 2024) + +- m4: reposition USE_RUSTLS="yes" for pkg-config + + It's necessary to set this var to "yes" _after_ AC_DEFINE and AC_SUBST + in order for a later `test` to pass so that `check_for_ca_bundle=1` ends + up being set. This is in turn required for the default CA certificate + bundle to be set when building w/ rustls & pkg-config. + + Reported-by: Matt Jolly + Fixes #13248 + Closes #13251 + +Daniel Stenberg (31 Mar 2024) + +- maketgz: put docs/RELEASE-TOOL.md into the tarball + + Generated with scripts/release-tools.sh + + The script lists the exact Debian package names and version numbers for + the tools that are used to generate the tarball. + + Closes #13239 + +- cd2nroff/manage: use UTC when SOURCE_DATE_EPOCH is set + + Make them independent of the TZ setting. Also set a date string like + YYYY-MM-DD to avoid a local month name in the date. + + Reported-by: Carlos Henrique Lima Melara + Fixes #13242 + Closes #13243 + +- RELEASE-NOTES: synced + +- docs/MAIL-ETIQUETTE: convert to markdown + + To render nicer. To get spellchecked. + + Closes #13247 + +- reuse: add copyright + license info to individual docs/*.md files + + Instead of use 'docs/*.md' in dep5. For clarity and avoiding a wide- + matching wildcard. + + + Remove mention of old files from .reuse/dep5 + + add info to .github/dependabot.yml + + make scripts/copyright.pl warn on non-matching patterns + + Closes #13245 + +- test470: warn about unicode quote character read from config file + + Idea-by: Emanuele Torre + +- test469: verify warning when argument has unicode quote + +- tool_getparam: output warning for leading unicode quote character + + ... in the option argument. + + Typically this is a mistake done when copying example command lines from + online documentation using the wrong quote character. + + Presumably there are also other potential quote characters that might be + used, and this check is done without even knowing that unicode is used! + + Reported-by: Sanjay Pujare + Fixes #13214 + Closes #13215 + +- tool: follow-up getenv fix + + Remove a double free. Change the IPFS env use to a plain getenv() simply + because coverity gets confused. + + Follow-up to 9126b141c9398fe + Closes #13241 + +- idn: make Curl_idnconvert_hostname() use Curl_idn_decode() + + In the name of less code duplication + + Closes #13236 + +- curl-confopts.m4: define CARES_NO_DEPRECATED when c-ares is used + + Starting in 1.28.0 c-ares added deprecation warnings for some API calls + libcurl uses. + + Closes #13240 + +- vquic: use CURL_FORMAT_CURL_OFF_T for 64 bit printf output + + Reported-by: Keitagit-kun on github + Fixes #13224 + Closes #13231 + +- openldap: create ldap URLs correctly for IPv6 addresses + + Reported-by: Sergio Durigan Junior + Fixes #13228 + Closes #13235 + +- curl: use curl_getenv instead of the curlx_ version + + The curlx one was once introduced when we still considered dropping the + libcurl function at some point. To reduce confusion and to make it + easier to understand when curl_free() should be used, use the actual + libcurl function call directly instead. + + Closes #13230 + +Evgeny Grin (Karlson2k) (30 Mar 2024) + +- curl_sha512_256: do not use workaround for NetBSD when not needed + + Assisted-by: riastradh on github + Assisted-by: Michael Kaufmann + Closes #13225 + +Matt Jolly (30 Mar 2024) + +- m4: fix rustls pkg-config codepath + + The previous pkg-config code would successfully detect rustls but did + not set all appropriate variables and call the right macros to properly + configure cURL. + + Reported-by: kpcyrd on github + Fixes #13200 + Closes #13202 + +Daniel McCarney (30 Mar 2024) + +- deps: update librustls 0.12.0 -> 0.13.0 + + This commit updates the optional rustls-ffi librustls dependency from + 0.12.0 to 0.13.0. This version is based on the latest available rustls + release (0.23.4). + + The breaking API changes from 0.12.0 to 0.13.0 are in API surface unused + by curl, so this is an in-place update without any code changes. + + The `RUSTLS.md` documentation is updated to reflect the new version in + use, and to clarify that `cbindgen` isn't required to build `librustls` + - it's only used by developers to update the vendored `rustls.h` header + file maintained upstream. + + Closes #13238 + +Daniel Stenberg (28 Mar 2024) + +- RELEASE-NOTES: synced + +- tool_xattr: "guess" URL scheme if none is provided + + ... when figuring out the source URL to store. + + Reported-by: Dagfinn Ilmari MannsÃ¥ker + Fixes #13205 + Closes #13221 + +- tool_xattr: in debug builds, act normally if CURL_FAKE_XATTR is not set + + Closes #13220 + +Stefan Eissing (28 Mar 2024) + +- content_encoding: brotli and others, pass through 0-length writes + + - curl's transfer handling may write 0-length chunks at the end of the + download with an EOS flag. (HTTP/2 does this commonly) + + - content encoders need to pass-through such a write and not count this + as error in case they are finished decoding + + Fixes #13209 + Fixes #13212 + Closes #13219 + +Tobias Stoeckmann (28 Mar 2024) + +- libssh2: set length to 0 if strdup failed + + Internally, libssh2 dereferences the NULL pointer if length is non-zero. + The callback function cannot return the error condition, so at least + prevent subsequent crash. + + Closes #13213 + +Daniel Stenberg (28 Mar 2024) + +- RELEASE-PROCEDURE: mention an initial working build + + This is the step that was not done and caused the 8.7.0 mishap (it + lacked the correctly generated hugehelp file). + + Remove the mention of the copyright script as this is verified by a CI + job these days: the REUSE one. + + Closes #13216 + +Paul Howarth (28 Mar 2024) + +- curl_sha512_255: fix detection of OpenSSL 1.1.1 or later + + Use the same OPENSSL_VERSION_NUMBER comparison as in lib/vtls/openssl.c. + + Closes #13208 + +Robert Moreton (28 Mar 2024) + +- cf-socket: remove references to l_ip, l_port + + Fixes #13210 + Closes #13211 + +Daniel Stenberg (28 Mar 2024) + +- openssl: do not set SSL_MODE_RELEASE_BUFFERS + + While it might save some memory, it causes OpenSSL to instead do a huge + amount of allocations. + + Ref: #13136 + Closes #13203 + +- curl: make --help adapt to the terminal width + + Instead of assuming and working with 80 colums, try figuring out what + width is actually used. + + Ref: #13141 + + Closes #13171 + +- RELEASE-NOTES: synced + + and bump to 8.7.2 for now + +- configure: make --disable-docs imply --disable-manual + + Because when the docs is not built, the necesary curl.txt file is not + present so then the manual cannot get built. + + Reported-by: Harry Sintonen + Closes #13191 + +Chris Webb (27 Mar 2024) + +- cmdline-docs: fix make install with configure --disable-docs + + make -C docs/cmdline-opts install depends on all-am, which in turn + depends on $(MANS), unconditionally defined to be $(man_MANS). + + As with CLEANFILES, only add curl.1 to man_MANS when BUILD_DOCS is true + so we don't try to build curl.1 unnecessarily. + + Closes #13198 + +Version 8.7.1 (27 Mar 2024) + +Daniel Stenberg (27 Mar 2024) + +- RELEASE-PROCEDURE: remove old release dates, add new pending ones + +Version 8.7.0 (27 Mar 2024) + +Daniel Stenberg (27 Mar 2024) + +- RELEASE-NOTES: synced + + curl 8.7.0 release + +- THANKS: new contributors from the 8.7.0 release + +- CURLOPT_POSTFIELDS.md: used for MQTT as well + + Closes #13189 + +- http: remove stale comment about rewindbeforesend + + ... because that struct field exists no more. + + Follow-up to 14bcea074a782272. + + Closes #13187 + +- DISTROS: add document with distro pointers + + Lots of organizations distribute curl packages to end users. This is a + collection of pointers to where to learn more about curl on and with + each distro. + + Assisted-by: Alan Coopersmith + Assisted-by: Andrew Kaster + Assisted-by: Andy Fiddaman + Assisted-by: Arjan van de Ven + Assisted-by: Brian Clemens + Assisted-by: chrysos349 on github + Assisted-by: Dan Fandrich + Assisted-by: Dan McDonald + Assisted-by: Gaelan Steele + Assisted-by: graywolf on github + Assisted-by: Jan Macku + Assisted-by: John Marshall + Assisted-by: Jonathan Perkin + Assisted-by: Kevin Daudt + Assisted-by: Marcus Müller + Assisted-by: MichaÅ‚ Górny + Assisted-by: Outvi V + Assisted-by: Ross Burton + Assisted-by: Sean Molenaar + Assisted-by: Till Wegmüller + Assisted-by: Viktor Szakats + Assisted-by: Winni Neessen + + Closes #13178 + +Fabian Keil (25 Mar 2024) + +- wolfSSL: do not call the stub function wolfSSL_BIO_set_init() + + Calling the function isn't necessary and causes the build + to fail when wolfSSL has been compiled with NO_WOLFSSL_STUB: + + Making all in opts + CCLD curl + ld: error: undefined symbol: wolfSSL_BIO_set_init + >>> referenced by wolfssl.c:235 (vtls/wolfssl.c:235) + >>> libcurl_la-wolfssl.o:(wolfssl_bio_cf_create) in archiv + e ../lib/.libs/libcurl.a + cc: error: linker command failed with exit code 1 (use -v to see invocat + ion) + *** Error code 1 + + Closes #13164 + +Daniel Stenberg (25 Mar 2024) + +- cmdline-opts: shorter help texts + + In an effort to increase the readability of the "--help all" output on + narrow (80 column) terminals. + + Co-authored-by: Jay Satiro + + Closes #13169 + +Matt Jolly (25 Mar 2024) + +- curl-rustls.m4: add pkg-config support to rustls detection + + Based on the existing openssl pkg-config detection, this commit tries to + use pkg-config to find `rustls` then falls back to the current approach + if that fails. + + We use the following logic: + + - if no path is provided, just use pkg-config, if it's not there we have + a problem! + - if a path is provided, try pkg-config + + if pkg-config fails, try and find rustls directly + + Closes #13179 + +Mohammadreza Hendiani (25 Mar 2024) + +- TODO: update 13.11 with more information + + Closes #13173 + +Daniel Stenberg (23 Mar 2024) + +- docs/libcurl: generate PROTOCOLS from meta-data + + Remove the PROTOCOLS section from the source files completely and + instead generate them based on the header data in the curldown files. + + It also generates TLS backend information for options marked for TLS as + protocol. + + Closes #13175 + +- CURLMOPT_MAX*: mention what happens if changed mid-transfer + + For CURLMOPT_MAXCONNECTS and CURLMOPT_MAX_HOST_CONNECTIONS + + Ref: #13158 + Closes #13176 + +- docs/libcurl: add TLS backend info for all TLS options + + All man pages that are listed to be for TLS now must also specify + exactly what TLS backends the option works for, or use All if they all + work. + + cd2nroff makes sure this is done and that the listed backends exist. + + Closes #13168 + +- docs/libcurl: cleanups + + - CURLINFO_TLS_SESSION.md: remove mention of NSS + - CURLINFO_TLS_SSL_PTR.md: remove NSS leftover + - CURLOPT_CAINFO.md: drop mention of backends not supporting this + - CURLOPT_CAPATH.md: wolfSSL also supports this + + Closes #13166 + +- docs: make each libcurl man specify protocol(s) + + The mandatory header now has a mandatory list of protocols for which the + manpage is relevant. + + Most man pages already has a "PROTOCOLS" section, but this introduces a + stricter way to specify the relevant protocols. + + cd2nroff verifies that at least one protocol is mentioned (which can be + `*`). + + This information is not used just yet, but A) the PROTOCOLS section can + now instead get generated and get a unified wording across all manpages + and B) this allows us to more reliably filter/search for protocol + specific manpages/options. + + Closes #13166 + +Stefan Eissing (21 Mar 2024) + +- http2, http3: only return CURLE_PARTIAL_FILE when bytes were received + + - should resolve spurious pytest failures when stream were reset + right after response header were received + + Clsoes #13151 + +- http: separate response parsing from response action + + - move code that triggers on end-of-response into separate function from + parsing + - simplify some headp/headerlen usage + - add `httpversion` to SingleRequest to indicate the version of the + current response + + Closes #13134 + +Daniel Stenberg (21 Mar 2024) + +- http2: remove the third (unused) argument from http2_data_done() + + Closes #13154 + +- RELEASE-NOTES: synced + +Evgeny Grin (Karlson2k) (21 Mar 2024) + +- RELEASE-NOTES: corrected + + Corrected link for item 118 + + Closes #13157 + +Daniel Stenberg (19 Mar 2024) + +- CURLOPT_INTERFACE.md: remove spurious amp, add see-also + + Closes #13149 + +Stefan Eissing (19 Mar 2024) + +- http: improve response header handling, save cpu cycles + + Saving some cpu cycles in http response header processing: + - pass the length of the header line along + - use string constant sizeof() instead of strlen() + - check line length if prefix is possible + - switch on first header char to limit checks + + Closes #13143 + +Daniel Stenberg (19 Mar 2024) + +- tool_getparam: accept a blank -w "" + + Added test 468 to verify. + + Regression from 07bcae89d5d00 (shipped in 8.6.0) + Reported-by: Thomas Pyle + Fixes #13144 + Closes #13145 + +Evgeny Grin (Karlson2k) (18 Mar 2024) + +- curl_sha512_256: work around a NetBSD bug + + Based on Michael Kaufmann analysis and suggestion + + Closes #13133 + +Stefan Eissing (18 Mar 2024) + +- http: expect 100 rework + + Move all handling of HTTP's `Expect: 100-continue` feature into a client + reader. Add sending flag `KEEP_SEND_TIMED` that triggers transfer + sending on general events like a timer. + + HTTP installs a `CURL_CR_PROTOCOL` reader when announcing `Expect: + 100-continue`. That reader works as follows: + + - on first invocation, records time, starts the `EXPIRE_100_TIMEOUT` + timer, disables `KEEP_SEND`, enables `KEEP_SEND_TIMER` and returns 0, + eos=FALSE like a paused upload. + + - on subsequent invocation it checks if the timer has expired. If so, it + enables `KEEP_SEND` and switches to passing through reads to the + underlying readers. + + Transfer handling's `readwrite()` will be invoked when a timer expires + (like `EXPIRE_100_TIMEOUT`) or when data from the server arrives. Seeing + `KEEP_SEND_TIMER`, it will try to upload more data, which triggers + reading from the client readers again. Which then may lead to a new + pausing or cause the upload to start. + + Flags and timestamps connected to this have been moved from + `SingleRequest` into the reader's context. + + Closes #13110 + +- mbedtls: fix pytest for newer versions + + Fix the expectations in pytest for newer versions of mbedtls + + Closes #13132 + +Daniel Stenberg (15 Mar 2024) + +- ipv6.md: mention IPv4 mapped addresses + + Reported-by: Josh Soref + Assisted-by: Jay Satiro + Fixes #13112 + Closes #13131 + +Stefan Eissing (15 Mar 2024) + +- http: revisit http_perhapsrewind() + + - use facilities provided by client readers better + - work also for non-uploading requests like GET/HEAD + - update documentation + + Closes #13117 + +- test 1541: verify getinfo values on first header callback + + Reported-by: chensong1211 on github + Ref: #13125 + Closes #13128 + +- TLS: start shutdown only when peer did not already close + + - When curl sees a TCP close from the peer, do not start a TLS shutdown. + TLS shutdown is a handshake and if the peer already closed the + connection, it is not interested in participating. + + Reported-by: dfdity on github + Assisted-by: Jiří Bok + Assisted-by: PÄ“teris Caune + Fixes #10290 + Closes #13087 + +Daniel Stenberg (14 Mar 2024) + +- RELEASE-NOTES: synced + +- curl: make --libcurl output better CURLOPT_*SSLVERSION + + The option is really two enums ORed together, so it needs special + attention to make the code output nice. + + Added test 1481 to verify. Both the server and the proxy versions. + + Reported-by: Boris Verkhovskiy + Fixes #13127 + Closes #13129 + +- GHA/linux: add sysctl trick to work-around GitHub runner issue + + The GitHub image runner update from 20240304.1.0 to 20240310.1 + introduces a problem for clang-14. The issue is caused by + incompatibility between llvm 14 provided in ubuntu-22.04 image and the + much newer kernel configured with high-entropy ASLR. + + As a work-around, we issue a sysctl command to lower the entropy and get + clang-14 to work again. + + URL: https://github.com/actions/runner-images/issues/9491 + + Closes #13124 + +- SPONSORS: describe the basics + + Closes #13119 + +- GOVERNANCE: document the core team + + Closes #13118 + +Jay Satiro (13 Mar 2024) + +- vquic-tls: fix the error code returned for bad CA file + + - Return CURLE_SSL_CACERT_BADFILE if wolfSSL encounters a problem + reading the cert file or path. + + This is a follow-up to the parent commit aedbbdf1. + + Reported-by: Karthikdasari0423@users.noreply.github.com + + Fixes https://github.com/curl/curl/issues/13115 + +Daniel Stenberg (12 Mar 2024) + +- vquic-tls: return appropirate errors on wolfSSL errors + + Reported-by: Dexter Gerig + Closes #13107 + +Viktor Szakats (12 Mar 2024) + +- tidy-up: one comment and EOF newlines + + Reviewed-by: Daniel Stenberg + Closes #13108 + +Daniel Stenberg (12 Mar 2024) + +- cmdline-opts: language cleanups + + Use imperative mood consistently for the first sentence describing an + option. + + "Set this" instead "tell curl to set" or "this sets..." + + Plus some extra cleanups and rephrasing. + + Closes #13106 + +- managen: remove space before protocols + + For options that are listed for specific protocols, the protocols (shown + first within parentheses) are now output without the leading space in the + manpage output. + + Closes #13105 + +Jay Satiro (12 Mar 2024) + +- mbedtls: properly cleanup the thread-shared entropy + + - Store the state of the thread-shared entropy for global init/cleanup. + + - Use curl's thread support of mbedtls for all Windows builds instead of + just when the threaded resolver is used via USE_THREADS_WIN32. + + Prior to this change on global cleanup curl builds that have curl thread + support for mbedtls freed the entropy (8b1d2298) but failed to mark that + it had been freed, which caused problems on subsequent init + transfer. + + Bug: https://github.com/curl/curl/discussions/11919#discussioncomment-8687105 + Reported-by: awesomekosm@users.noreply.github.com + + Closes https://github.com/curl/curl/pull/13071 + +Daniel Stenberg (12 Mar 2024) + +- tool_getparam: handle non-existing (out of range) short-options + + ... correctly, even when they follow an existing one without a space in + between. + + Verify with test 467 + + Follow-up to 07dd60c05b + Reported-by: Geeknik Labs + Fixes #13101 + Closes #13102 + +Stefan Eissing (11 Mar 2024) + +- lib: move 'done' parameter to SingleRequests + + A transfer may do several `SingleRequest`s for its success. This happens + regularly for authentication, follows and retries on failed connections. + The "readwrite()" calls and functions connected to those carried a `bool + *done` parameter to indicate that the current `SingleRequest` is over. + This may happen before `upload_done` or `download_done` bits of + `SingleRequest` are set. + + The problem with that is now `write_resp()` protocol handlers are + invoked in places where the `bool *done` cannot be passed up to the + caller. Instead of being a bool in the call chain, it needs to become a + member of `SingleRequest`, reflecting its state. + + This removes the `bool *done` parameter and adds the `done` bit to + `SingleRequest` instead. It adds `Curl_req_soft_reset()` for using a + `SingleRequest` in a follow up, clearing `done` and other + flags/counters. + + Closes #13096 + +- request: clarify message when request has been sent off + + Change the "uploaded and fine" message for requests without a body + + Reported-by: Karthikdasari0423 on github + Fixes #13093 + Closes #13095 + +Daniel Stenberg (11 Mar 2024) + +- RELEASE-NOTES: synced + +Stefan Eissing (9 Mar 2024) + +- lib: keep conn IP information together + + new struct ip_quadruple for holding local/remote addr+port + + - used in data->info and conn and cf-socket.c + - copy back and forth complete struct + - add 'secondary' to conn + - use secondary in reporting success for ftp 2nd connection + + Reported-by: DasKutti on github + Fixes #13084 + Closes #13090 + +Daniel Stenberg (8 Mar 2024) + +- scripts/managen: the new name and home for the manpage generator + + It was previously docs/cmdline-opts/gen.pl + + Closes #13089 + +- VULN-DISCLOSURE-POLICY.md: update detail about CVE requests + + curl is a CNA now + + Closes #13088 + +Stefan Eissing (8 Mar 2024) + +- lib: client reader polish + + - seek_func/seek_client, use transfer values only + - remove copies held in `struct connectdata`, use only + ever `data->set.seek_func` + - resolves possible issues in multiuse connections + - new mime post reader eliminates need to ever overwriting this + + - websockets, remove empty Curl_ws_done() function + + Closes #13079 + +Marcel Raad (8 Mar 2024) + +- lib1598: fix `CURLOPT_POSTFIELDSIZE` usage + + It requires a `long` argument. + + Closes https://github.com/curl/curl/pull/13085 + +Daniel Stenberg (8 Mar 2024) + +- docs/cmdline-opts: drop the curl.1 from the dist tarball + + Since it is no longer needed for building tool_hugehelp.c and all the + docs is available in readable markdown format in the tarball, the peeps + that don't want to build the manpage still do good. + + Removing it also fixes the complexity of out-of-tree builds when the + curl.1 exists in the source tree. + +- test1140/1173: extend wildcards to find curl.1 + + ... in its new build path. + + Also update the test scripts to be more precise in error messages to + help us understand CI errors better. + + Follow-up to f03c85635f35269f1 + Ref: #13029 + Closes #13083 + +- http2: minor tweaks to optimize two struct sizes + + - use BIT() instead of bool + - place the struct fields in (roughly) size order + + Closes #13082 + +- buildconf.bat: remove outdated groff/nroff use + + - don't try to generate the real hugehelp file, because it requires + curl.txt which needs a build + - don't attempt to do anything in a c-ares subdirectory + + Follow-up to f03c85635f35269 + Closes #13078 + +- http2: memory errors in the push callbacks are fatal + + Use the correct nghttp2 error code accordingly. + + Closes #13081 + +Viktor Szakats (7 Mar 2024) + +- mkhelp: rename variable to fix compiler warnings + + ``` + src\tool_operate.c(541,33): warning C4459: declaration of 'm' hides global de + claration [_bld\src\curl.vcxproj] + _bld\src\tool_hugehelp.c(8,27): + see declaration of 'm' + src\tool_paramhlp.c(307,14): warning C4459: declaration of 'm' hides global d + eclaration [_bld\src\curl.vcxproj] + src\tool_progress.c(118,16): warning C4459: declaration of 'm' hides global d + eclaration [_bld\src\curl.vcxproj] + src\tool_writeout.c(288,31): warning C4459: declaration of 'm' hides global d + eclaration [_bld\src\curl.vcxproj] + ``` + Ref: https://ci.appveyor.com/project/curlorg/curl/builds/49348159/job/51ee75c + d2n0wj6lc#L614 + + Reviewed-by: Daniel Stenberg + Closes #13077 + +Daniel Stenberg (7 Mar 2024) + +- KNOWN_BUGS: POP3 issue when reading small chunks + + Closes #12063 + +- RELEASE-NOTES: synced + +Robert Moreton (7 Mar 2024) + +- asyn-ares: fix data race warning + + - Store the c-ares version during global init. + + Prior to this change several threads could write the same data to a + static int variable at the same time. Though in practice it's not a + problem ThreadSanitizer may warn. + + Reported-by: Nikita Taranov + Assisted-by: Jay Satiro + + Fixes #13065 + Closes #13000 + +Stefan Eissing (7 Mar 2024) + +- hyper: implement unpausing via client reader + + Just a tidy up to contain 'ifdef' pollution of common + code parts with implementation specifics. + + - remove the ifdef hyper unpausing in easy.c + - add hyper client reader for CURL_CR_PROTOCOL phase + that implements the unpause method for calling + the hyper waker if it is set + + Closes #13075 + +- ngtcp2: no recvbuf for stream + + - write response data directly to the transfer via + `Curl_xfer_write_resp()` like we do in HTTP/2. + + Closes #13073 + +- docs/cmdline-opts/.gitignore: ignore curl.txt + + Closes #13076 + +Evgeny Grin (Karlson2k) (7 Mar 2024) + +- sha512_256: add support for GnuTLS and OpenSSL + + This is a follow-up for PR #12897. + + Add support for SHA-512/256 digest calculation by TLS backends. + Currently only OpenSSL and GnuTLS (actually, nettle) support + SHA-512/256. + + Closes #13070 + +- digest: add check for hashing error + + Closes #13072 + +Viktor Szakats (7 Mar 2024) + +- cmake: enable `ENABLE_CURL_MANUAL` by default + + Meaning `curl.1` and `src/tool_hugehelp.c` are built by default, + and `--manual` in curl tool is also enabled by default. + + This syncs behaviour with autotools. + + For a reproducible `curl.1`, `SOURCE_DATE_EPOCH` needs to be set + to a consistent date, e.g. the timestamp of `CHANGES`. + + A pre-built manual (e.g. the one distributed in the official source + tarball) will be ignored and rebuilt after this patch, unless + explicitly disabling this option. + + Fixes #13028 + Closes #13069 + +Stefan Eissing (7 Mar 2024) + +- http2: push headers better cleanup + + - provide common cleanup method for push headers + + Closes #13054 + +Daniel Stenberg (7 Mar 2024) + +- GIT-INFO: convert to markdown + + Closes #13074 + +Richard Levitte (7 Mar 2024) + +- cmake: fix libcurl.pc and curl-config library specifications + + Letting CMake figure out where libraries are located gives you full + paths. When generating libcurl.pc and curl-config, getting libraries as + full paths is unusual when one expects to get a list of -l. + + To meet expectations, an effort is made to convert the full paths into + -l, possibly with -L before it. + + Fixes #6169 + Fixes #12748 + Closes #12930 + +Daniel Stenberg (7 Mar 2024) + +- test463: HTTP with -d @file with file containing CR, LF and null byte + +- paramhlp: fix CRLF-stripping files with "-d @file" + + All CR and LF bytes should be stripped, as documented, and all other + bytes are inluded in the data. Starting now, it also excludes null bytes + as they would otherwise also cut the data short. + + Reported-by: Simon K + Fixes #13063 + Closes #13064 + +Viktor Szakats (7 Mar 2024) + +- cmake: fix `CURL_WINDOWS_SSPI=ON` with Schannel disabled + + Prior to this change `CURL_WINDOWS_SSPI` was accidentally forced `OFF` + when building without the Schannel TLS backend. + + This in turn may have caused Kerberos, SPNEGO and SSPI features + disappearing even with `CURL_WINDOWS_SSPI=ON` set. + + This patch fixes it by using the `CURL_USE_SCHANNEL` setting as a + default for `CURL_WINDOWS_SSPI`, but allowing a manual override. + + Also update the option text to better tell its purpose. + + Thanks-to: Andreas Loew + Reviewed-by: Daniel Stenberg + Ref: #13056 + Closes #13061 + +Jay Satiro (6 Mar 2024) + +- KNOWN_BUGS: FTPS server compatibility on Windows with Schannel + + - Remove "2.12 FTPS with Schannel times out file list operation" + + - Remove "7.12 FTPS directory listing hangs on Windows with Schannel" + + - Add "7.12 FTPS server compatibility on Windows with Schannel" + + This change adds a more generic bug description that explains FTPS with + the latest curl and Schannel is not widely used and may have more bugs + than other TLS backends. + + The two removed FTPS Schannel bugs can't be reproduced any longer and + were likely fixed by 24d6c288. + + Ref: https://github.com/curl/curl/issues/5284 + Ref: https://github.com/curl/curl/issues/9161 + Ref: https://github.com/curl/curl/issues/12894 + + Closes https://github.com/curl/curl/pull/13032 + +- trace-config.md: remove the mutexed options list + + - Remove the rendered manpage message that says: + "[--trace-config] is mutually exclusive to --trace and -v, --verbose". + + Actually it can be used with either of those options, which are mutually + exclusive to each other but not to --trace-config. + + Ref: https://curl.se/docs/manpage.html#--trace-config + + Closes https://github.com/curl/curl/pull/13031 + +Daniel Stenberg (6 Mar 2024) + +- mkhelp: simplify the generated hugehelp program + + Use a plain array and puts() every line, also allows us to provide the + strings without ending newlines. + + - merge blank lines into the next one as a prefixed newline. + - turn eight consecutive spaces into a tab (since they can only be on the + left side of text) + - the newly generated tool_hugehelp is 3K lines shorter and 50K smaller + - modifies the top logo layout a little by reducing the indent + + Closes #13047 + +- docs: ascii version of manpage without nroff + + Create ASCII version of manpage without nroff + + - build src/tool_hugegelp.c from the ascii manpage + - move the the manpage and the ascii version build to docs/cmdline-opts + - remove all use of nroff from the build process + - should make the build entirely reproducible (by avoiding nroff) + + - partly reverts 2620aa9 to build libcurl option man pages one by one + in cmake because the appveyor builds got all crazy until I did + + The ASCII version of the manpage + + - is built with gen.pl, just like the manpage is + - has a right-justified column making the appearance similar to the previous + version + - uses a 4-space indent per level (instead of the old version's 7) + - does not do hyphenation of words (which nroff does) + + History + + We first made the curl build use nroff for building the hugehelp file in + December 1998, for curl 5.2. + + Closes #13047 + +Stefan Eissing (6 Mar 2024) + +- lib: add `void *ctx` to reader/writer instances + + - `struct Curl_cwriter` and `struct Curl_creader` now carry a + `void *ctx` member that points to the instance as allocated. + - using `r->ctx` and `w->ctx` as pointer to the instance specific + struct that has been allocated + + Reported-by: Rudi Heitbaum + Fixes #13035 + Closes #13059 + +- http: fix dead code in setting post client reader + + - postsize was always 0, thus the check's else never happened + after the mime client reader was introduced + + Follow-up to 0ba47146f7ff3d + Closes #13060 + +- http2: fix push discard + + - fix logic in discarding a failed pushed stream so that + stream context is properly cleaned up + + Closes #13055 + +- transfer.c: break receive loop in speed limited transfers + + - the change breaks looping in transfer.c receive for transfers that are + speed limited on having gotten *some* bytes. + - the overall speed limit timing is done in multi.c + + Reported-by: Dmitry Karpov + Bug: https://curl.se/mail/lib-2024-03/0001.html + Closes #13050 + +- mime: add client reader + + Add `mime` client reader. Encapsulates reading from mime parts, getting + their length, rewinding and unpausing. + + - remove special mime handling from sendf.c and easy.c + - add general "unpause" method to client readers + - use new reader in http/imap/smtp + - make some mime functions static that are now only used internally + + In addition: + - remove flag 'forbidchunk' as no longer needed + + Closes #13039 + +Daniel Stenberg (5 Mar 2024) + +- RELEASE-NOTES: synced + +- TODO: remove "build HTTP/3 with OpenSSL and nghttp3 using cmake" + + Follow-up to 8e741644a229c37 + +Tal Regev (5 Mar 2024) + +- cmake: add USE_OPENSSL_QUIC support + + Closes #13034 + +Stefan Eissing (5 Mar 2024) + +- TIMER_STARTTRANSFER: set the same for everyone + + - set TIMER_STARTTRANSFER on seeing the first response bytes + in the download client writer, not coming from a CONNECT + - initialized the timer the same way for all protocols + - remove explicit setting of TIMER_STARTTRANSFER in file.c + and c-hyper.c + + Closes #13052 + +Michael Kaufmann (5 Mar 2024) + +- http: better error message for HTTP/1.x response without status line + + If a response without a status line is received, and the connection is + known to use HTTP/1.x (not HTTP/0.9), report the error "Invalid status + line" instead of "Received HTTP/0.9 when not allowed". + + Closes #13045 + +Viktor Szakats (5 Mar 2024) + +- KNOWN_BUGS: fix typo + + Reviewed-by: Daniel Stenberg + Closes #13051 + +Sebastian Neubauer (5 Mar 2024) + +- smpt: fix starttls + + In cases where the connection was fast, curl sometimes failed to open a + connection. This fixes a regression of c2d973627bab12abc5486a3f3. + + The regression triggered in these steps: + + 1. Create an smtp connection + 2. Use STARTTLS + 3. Receive the response + 4. We are inside the loop in `smtp_statemachine`, calling + `smtp_state_starttls_resp` + 5. In the good flow, we exit the loop, re-enter `smtp_statemachine` and + run `smtp_perform_upgrade_tls` at the start of the function. + + In the bad flow, we stay in the while loop, calling + `Curl_pp_readresp`, which reads part of the TLS handshake and things + go wrong. + + The reason is that `Curl_pp_moredata` changed behavior and always + returns `true`, so we stay in the loop in `smtp_statemachine`. With a + slow connection `Curl_pp_readresp` cannot read new data and returns + `CURL_AGAIN`, so we leave the loop and re-enter `smtp_statemachine`. + + With a fast connection, `Curl_pp_readresp` reads new data from the tcp + connection, which is part of the TLS handshake. + + The fix is in `Curl_pp_moredata`, which needs to take the final line + into account and return `false` if only the final line is stored. + + Closes #13048 + +Stefan Eissing (5 Mar 2024) + +- lib: enhance client reader resume + rewind + + - update client reader documentation + - client reader, add rewind capabilities + - tell creader to rewind on next start + - Curl_client_reset() will keep reader for future rewind if requested + - add Curl_client_cleanup() for freeing all resources independent of + rewinds + - add Curl_client_start() to trigger rewinds + - move rewind code from multi.c to sendf.c and make part of + "cr-in"'s implementation + - http, move the "resume_from" handling into the client readers + - the setup of a HTTP request is reshuffled to follow: + * determine method, target, auth negotiation + * install the client reader(s) for the request, including crlf + conversions and "chunked" encoding + * apply ranges to client reader + * concat request headers, upgrades, cookies, etc. + * complete request by determining Content-Length of installed + readers in combination with method + * send + - add methods for client readers to + * return the overall length they will generate (or -1 when unknown) + * return the amount of data on the CLIENT level, so that + expect-100 can decide if it want to apply itself + * set a "resume_from" offset or fail if unsupported + - struct HTTP has become largely empty now + - rename `Client_reader_*` to `Curl_creader_*` + + Closes #13026 + +Viktor Szakats (5 Mar 2024) + +- openssl-quic: fix BIO leak and Windows warning + + Caused by an accidentally duplicated line in + d6825df334def106f735ce7e0c1a2ea87bddffb0. + + ``` + .../lib/vquic/curl_osslq.c:1095:30: warning: implicit conversion loses intege + r precision: 'curl_socket_t' (aka 'unsigned long long') to 'int' [-Wshorten-6 + 4-to-32] + 1095 | bio = BIO_new_dgram(ctx->q.sockfd, BIO_NOCLOSE); + | ~~~~~~~~~~~~~ ~~~~~~~^~~~~~ + 1 warning and 2 errors generated. + ``` + + Reviewed-by: Stefan Eissing + Closes #13043 + +- openssl-quic: fix unity build, casing, indentation + + - rename static functions to avoid duplicate symbols in unity mode. + - windows -> Windows/window in error message and comment. + - fix indentation. + + Reviewed-by: Stefan Eissing + Closes #13044 + +Daniel Stenberg (5 Mar 2024) + +- gen.pl: make the "manpageification" faster + + The function that replaces occurances of "--longoption" with "-Z, + --longoption" etc with the proper highlight applied, no longer loops + over the options. + + Closes #13041 + +- CONTRIBUTE: update the section on documentation format + + ... since most of it is markdown now. + + Closes #13046 + +- smtp: free a temp resource + + The returned address needs to be freed. + + Follow-up to e3905de8196d67b89df1602feb84c1f993211b20 + Spotted by Coverity + + Closes #13038 + +- _VARIABLES.md: improve the description + + Closes #13040 + +dependabot[bot] (4 Mar 2024) + +- build(deps): bump fsfe/reuse-action from 2 to 3 + + Bumps [fsfe/reuse-action](https://github.com/fsfe/reuse-action) from 2 to 3. + - [Release notes](https://github.com/fsfe/reuse-action/releases) + - [Commits](https://github.com/fsfe/reuse-action/compare/v2...v3) + + --- + updated-dependencies: + - dependency-name: fsfe/reuse-action + dependency-type: direct:production + update-type: version-update:semver-major + ... + + Signed-off-by: dependabot[bot] + +Stefan Eissing (4 Mar 2024) + +- pytest: adapt to API change + + - pytest has changed the signature of the hook pytest_report_header() + for some obscure reason and that change landed in our CI now + + - remove the changed param that we never used anyway + + Closes #13037 + +Daniel Stenberg (4 Mar 2024) + +- cookie: if psl fails, reject the cookie + + A libpsl install without data and no built-in database is now considered + bad enough to reject all cookies since they cannot be checked. It is + somewhat of a user error, but still. + + Reported-by: Dan Fandrich + Closes #13033 + +Stefan Eissing (4 Mar 2024) + +- lib: further send/upload handling polish + + - Move all the "upload_done" handling to request.c + + - add possibility to abort sending of a request + - add `Curl_req_done_sending()` for checks + - transfer.c: readwrite_upload() now clean + + - removing data->state.ulbuf and data->req.upload_fromhere + + - as well as data->req.upload_present + - set data->req.upload_done on having read all from + the client and completely flushed the send buffer + + - tftp, remove setting of data->req.upload_fromhere + + - serves no purpose as `upload_present` is not set + and the data itself is directly `sendto()` anyway + + - smtp, make upload EOB conversion a client reader + - xfer_ulbuf addition + + - add xfer_ulbuf for borrowing, similar to xfer_buf + - use in file upload + - use in c-hyper body sending + + - h1-proxy, remove init of data->state.uilbuf that is never used + - smb, add own send_buf instead of using data->state.ulbuf + + Closes #13010 + +Daniel Stenberg (4 Mar 2024) + +- RELEASE-NOTES: synced + +kpcyrd (3 Mar 2024) + +- rustls: fix two warnings related to number types + + Reported-by: Gisle Vanem + Follow-up to #12989 + Closes #13017 + +Stefan Eissing (3 Mar 2024) + +- bufq: writing into a softlimit queue cannot be partial + + - when unable to obtain a new chunk on a softlimit bufq, + this is an allocation error and needs to be reported as + such. + - writes into a soflimit bufq never must be partial success + + Reported-by: Dan Fandrich + Fixes #13020 + Closes #13023 + +Dan Fandrich (2 Mar 2024) + +- configure: Don't build shell completions when disabled + + With the recent changes to completion file building, the files were + built always and only installation was selectively disabled. Now, when + they are disabled they aren't even built, avoiding a build-time error in + environments where it's not possible to run the curl binary that was + just created (e.g. if library paths were not set up correctly). + + Follow-up to 0f7aba83c + + Reported-by: av223119 on github + Fixes #13027 + Closes #13030 + +Jay Satiro (2 Mar 2024) + +- cmdline-opts/_EXITCODES: sync with libcurl-errors + + - Add error code 100 (CURLE_TOO_LARGE) to the list of error codes that + can be returned by the curl tool. + + Closes https://github.com/curl/curl/pull/13015 + +Stefan Eissing (1 Mar 2024) + +- hyper: disable test1598 due to lack of trailer support + + Follow-up to 50838095 + + Closes #13016 + +Dan Fandrich (1 Mar 2024) + +- ftp: Mark a const buffer as const + +- appveyor: Properly skip if only CircleCI is changed + +- docs: Update minimal binary size in INSTALL.md + + Include more options to reduce binary size. + +- configure: Don't make shell completions without perl + + The code that attempted to skip building the shell completions didn't + work properly and tried to build them even if perl wasn't available. + This step, as well as the install step, is now properly skipped without + perl. + + Follow-up to 89733e2dd + + Closes #13022 + +RainRat (1 Mar 2024) + +- misc: Fix typos in docs and lib + + This fixes miscellaneous typos and duplicated words in the docs, lib + and test comments and a few user facing errorstrings. + + Author: RainRat on Github + Reviewed-by: Daniel Gustafsson + Reviewed-by: Dan Fandrich + Closes: #13019 + +Dan Fandrich (29 Feb 2024) + +- configure: build & install shell completions when enabled + + The --with-fish-functions-dir and --with-zsh-functions-dir options + currently have no effect on a normal build because the scripts/ directory + where they're used is not built. Add scripts/ to a normal build and + change the completion options to default to off to preserve the existing + behaviour. + + Closes: #12906 + +- github/labeler: improve the match patterns + +Stefan Eissing (28 Feb 2024) + +- tests: add test1598 for POST with trailers + + - test POST fields with trailers and chunked encoding + + Ref: #12938 + Closes #13009 + +Daniel Stenberg (28 Feb 2024) + +- cmdline-opts/_VERSION: provide %VERSION correctly + + ... so that it does not get included verbatim in the output. Fixes a + regression shipped in 8.6.0. + + Also fix a format mistake in form.md + + Closes #13008 + +Stefan Eissing (28 Feb 2024) + +- lib: Curl_read/Curl_write clarifications + + - replace `Curl_read()`, `Curl_write()` and `Curl_nwrite()` to + clarify when and at what level they operate + - send/recv of transfer related data is now done via + `Curl_xfer_send()/Curl_xfer_recv()` which no longer has + socket/socketindex as parameter. It decides on the transfer + setup of `conn->sockfd` and `conn->writesockfd` on which + connection filter chain to operate. + - send/recv on a specific connection filter chain is done via + `Curl_conn_send()/Curl_conn_recv()` which get the socket index + as parameter. + - rename `Curl_setup_transfer()` to `Curl_xfer_setup()` for + naming consistency + - clarify that the special CURLE_AGAIN hangling to return + `CURLE_OK` with length 0 only applies to `Curl_xfer_send()` + and CURLE_AGAIN is returned by all other send() variants. + - fix a bug in websocket `curl_ws_recv()` that mixed up data + when it arrived in more than a single chunk (to be made + into a sperate PR, also) + + Added as documented [in + CLIENT-READER.md](https://github.com/curl/curl/blob/5b1f31dfbab8aef467c419c68 + aa06dc738cb75d4/docs/CLIENT-READERS.md). + + - old `Curl_buffer_send()` completely replaced by new `Curl_req_send()` + - old `Curl_fillreadbuffer()` replaced with `Curl_client_read()` + - HTTP chunked uploads are now formatted in a client reader added when + needed. + - FTP line-end conversions are done in a client reader added when + needed. + - when sending requests headers, remaining buffer space is filled with + body data for sending in "one go". This is independent of the request + body size. Resolves #12938 as now small and large requests have the + same code path. + + Changes done to test cases: + + - test513: now fails before sending request headers as this initial + "client read" triggers the setup fault. Behaves now the same as in + hyper build + - test547, test555, test1620: fix the length check in the lib code to + only fail for reads *smaller* than expected. This was a bug in the + test code that never triggered in the old implementation. + + Closes #12969 + +Daniel Gustafsson (28 Feb 2024) + +- curldown: Fix email address in Copyright + + The curldown conversion accidentally replaced daniel@haxx.se with + just daniel.se. This reverts back to the proper email address in + the curldown docs as well as in a few other stray places where it + was incorrect (while unrelated to curldown). + + Reviewed-by: Daniel Stenberg + Closes: #12997 + +Daniel Stenberg (28 Feb 2024) + +- getparam: make --ftp-ssl work again + + Follow-up to 9e4e527 which accidentally broke it + + Reported-by: Jordan Brown + Fixes #13006 + Closes #13007 + +- KNOWN_BUGS: IMAPS connection fails with rustls error + + Closes #10457 + +- KNOWN_BUGS: FTPS upload, FileZilla, GnuTLS and close_notify + + Closes #11383 + +- KNOWN_BUGS: Implicit FTPS upload timeout + + Closes #11720 + +- KNOWN_BUGS: HTTP/2 prior knowledge over proxy + + Closes #12641 + +- TODO: build HTTP/3 with OpenSSL and nghttp3 using cmake + + Closes #12988 + +- TODO: Select signature algorithms + + Closes #12982 + +- examples: use present tense in comments + + remove "will" and some other word fixes + + Closes #13003 + +- docs: more language cleanups + + - present tense + - avoid bad words + + Closes #13003 + +Daniel Gustafsson (27 Feb 2024) + +- setopt: Fix disabling all protocols + + When disabling all protocols without enabling any, the resulting + set of allowed protocols remained the default set. Clearing the + allowed set before inspecting the passed value from --proto make + the set empty even in the errorpath of no protocols enabled. + + Co-authored-by: Dan Fandrich + Reported-by: Dan Fandrich + Reviewed-by: Daniel Stenberg + Closes: #13004 + +Andreas Kiefer (27 Feb 2024) + +- fopen: fix narrowing conversion warning on 32-bit Android + + This was fixed in commit 06dc599405f, but came back in commit + 03cb1ff4d62. + + When building for 32-bit ARM or x86 Android, `st_mode` is defined as + `unsigned int` instead of `mode_t`, resulting in a + `-Wimplicit-int-conversion` clang warning because `mode_t` is + `unsigned short`. Add a cast to silence the warning, but only for + 32-bit Android builds, because other architectures and platforms are + not affected. + + Ref: https://android.googlesource.com/platform/bionic/+/refs/tags/ndk-r25c/li + bc/include/sys/stat.h#86 + Closes https://github.com/curl/curl/pull/12998 + +Stefan Eissing (27 Feb 2024) + +- lib: Curl_read/Curl_write clarifications + + - replace `Curl_read()`, `Curl_write()` and `Curl_nwrite()` to + clarify when and at what level they operate + - send/recv of transfer related data is now done via + `Curl_xfer_send()/Curl_xfer_recv()` which no longer has + socket/socketindex as parameter. It decides on the transfer + setup of `conn->sockfd` and `conn->writesockfd` on which + connection filter chain to operate. + - send/recv on a specific connection filter chain is done via + `Curl_conn_send()/Curl_conn_recv()` which get the socket index + as parameter. + - rename `Curl_setup_transfer()` to `Curl_xfer_setup()` for + naming consistency + - clarify that the special CURLE_AGAIN hangling to return + `CURLE_OK` with length 0 only applies to `Curl_xfer_send()` + and CURLE_AGAIN is returned by all other send() variants. + - fix a bug in websocket `curl_ws_recv()` that mixed up data + when it arrived in more than a single chunk + + The method for sending not just raw bytes, but bytes that are either + "headers" or "body". The send abstraction stack, to to bottom, now is: + + * `Curl_req_send()`: has parameter to indicate amount of header bytes, + buffers all data. + * `Curl_xfer_send()`: knows on which socket index to send, returns + amount of bytes sent. + * `Curl_conn_send()`: called with socket index, returns amount of bytes + sent. + + In addition there is `Curl_req_flush()` for writing out all buffered + bytes. + + `Curl_req_send()` is active for requests without body, + `Curl_buffer_send()` still being used for others. This is because the + special quirks need to be addressed in future parts: + + * `expect-100` handling + * `Curl_fillreadbuffer()` needs to add directly to the new + `data->req.sendbuf` + * special body handlings, like `chunked` encodings and line end + conversions will be moved into something like a Client Reader. + + In functions of the pattern `CURLcode xxx_send(..., ssize_t *written)`, + replace the `ssize_t` with a `size_t`. It makes no sense to allow for negativ + e + values as the returned `CURLcode` already specifies error conditions. This + allows easier handling of lengths without casting. + + Closes #12964 + +Daniel Stenberg (27 Feb 2024) + +- multi: make add_handle free any multi_easy + + If the easy handle that is being added to a multi handle has previously + been used for curl_easy_perform(), there is a private multi handle here + that we can kill off. While it flushes some caches etc for the easy + handle would it be used for an easy interface transfer again after being + used in the multi stack, this cleanup simplifies behavior and uses less + memory. + + Closes #12992 + +- docs: use present tense + + avoid "will", detect "will" as a bad word in the CI + + Also line wrapped a bunch of paragraphs + + Closes #13001 + +- CURLOPT_SSL_CTX_FUNCTION.md: no promises of lifetime after return + + ... and cleanup other language. + + Closes #12999 + +Stefan Eissing (27 Feb 2024) + +- lib: send rework + + Curl_read/Curl_write clarifications + + - replace `Curl_read()`, `Curl_write()` and `Curl_nwrite()` to 1clarify + when and at what level they operate + + - send/recv of transfer related data is now done via + `Curl_xfer_send()/Curl_xfer_recv()` which no longer has + socket/socketindex as parameter. It decides on the transfer setup of + `conn->sockfd` and `conn->writesockfd` on which connection filter + chain to operate. + + - send/recv on a specific connection filter chain is done via + `Curl_conn_send()/Curl_conn_recv()` which get the socket index as + parameter. + + - rename `Curl_setup_transfer()` to `Curl_xfer_setup()` for naming + consistency + + - clarify that the special CURLE_AGAIN handling to return `CURLE_OK` + with length 0 only applies to `Curl_xfer_send()` and CURLE_AGAIN is + returned by all other send() variants. + + SingleRequest reshuffling + + - move functions into request.[ch] + - differentiate between reset and free + - add Curl_req_done() to perform last actions + - add a send `bufq` to SingleRequest for future use in keeping upload data + + Closes #12963 + +Daniel Stenberg (26 Feb 2024) + +- RELEASE-NOTES: synced + +- http_chunks: remove unused 'endptr' variable + + Closes #12996 + +Louis Solofrizzo (26 Feb 2024) + +- lib: initialize output pointers to NULL before calling strto[ff,l,ul] + + In order to make MSAN happy: + + ==2200945==WARNING: MemorySanitizer: use-of-uninitialized-value + #0 0x596f3b3ed246 in curlx_strtoofft [...]/libcurl/src/lib/strtoofft.c:23 + 9:11 + #1 0x596f3b402156 in Curl_httpchunk_read [...]/libcurl/src/lib/http_chunk + s.c:149:12 + #2 0x596f3b348550 in readwrite_data [...]/libcurl/src/lib/transfer.c:607: + 11 + [...] + + ==2202041==WARNING: MemorySanitizer: use-of-uninitialized-value + #0 0x5a3fab66a72a in Curl_parse_port [...]/libcurl/src/lib/urlapi.c:547:8 + #1 0x5a3fab650645 in parse_authority [...]/libcurl/src/lib/urlapi.c:796:1 + 2 + #2 0x5a3fab6740f6 in parseurl [...]/libcurl/src/lib/urlapi.c:1176:16 + #3 0x5a3fab664fc5 in parseurl_and_replace [...]/libcurl/src/lib/urlapi.c: + 1342:12 + [...] + + ==2202320==WARNING: MemorySanitizer: use-of-uninitialized-value + #0 0x569076a0d6b0 in ipv4_normalize [...]/libcurl/src/lib/urlapi.c:683:12 + #1 0x5690769f2820 in parse_authority [...]/libcurl/src/lib/urlapi.c:803:1 + 0 + #2 0x569076a160f6 in parseurl [...]/libcurl/src/lib/urlapi.c:1176:16 + #3 0x569076a06fc5 in parseurl_and_replace [...]/libcurl/src/lib/urlapi.c: + 1342:12 + [...] + + Signed-off-by: Louis Solofrizzo + Closes #12995 + +Stefan Eissing (26 Feb 2024) + +- lib: move client writer into own source + + Refactoring of the client writer that passes the data to the + client/application's callback functions. + + - split out into own source cw-out.[ch] from sendf.c + + - move tempwrite and tempcount from data->state into the context of the + client writer + + - redesign the 3 tempwrite dynbufs as a linked list of dynbufs. On + paused transfers, this allows to "record" interleaved HEADER/BODY + chunks to be "played back" in the same order on unpausing. + + - keep the overall size limit of all buffered data to DYN_PAUSE_BUFFER. + On exceeding that, return CURLE_TOO_LARGE instead of + CURLE_OUT_OF_MEMORY as before. + + - add method to be called when a transfer is DONE to allow writing of + any data still buffered + + - when paused, record HEADER writes exactly as they come for later + playback. HEADERs are documented to be written one-by-one. + + Closes #12898 + +- urldata: move authneg bit from conn to Curl_easy + + - from `conn->bits.authneg` to `data->req.authneg` + - this is a property of the request about to be made + and not a property of the connection + - in multiuse connections, transfer could step on each others + toes here potentially. + + Closes #12949 + +- c-hyper: add header collection writer in hyper builds + + Closes #12880 + +- http: move headers collecting to writer + + - add a client writer that does "push" response + headers written to the client if the headers api + is enabled + - remove special handling in sendf.c + - needs to be installed very early on connection + setup to catch CONNECT response headers + + Closes #12880 + +- sendf: Curl_client_write(), make passed in buf const + +MichaÅ‚ Antoniak (26 Feb 2024) + +- lib: remove curl_mimepart object when CURL_DISABLE_MIME + + Remove curl_mimepart object from UserDefined structure when + CURL_DISABLE_MIME flag is active. Reduce size of UserDefined structure. + + Also remove unreachable code: when CURL_DISABLE_MIME is set, httpreq can + never have HTTPREQ_POST_MIME value and the same goes for the + CURL_DISABLE_FORM_API flag and the HTTPREQ_POST_FORM value + + Closes #12948 + +kpcyrd (26 Feb 2024) + +- rustls: make curl compile with 0.12.0 + + Closes #12989 + +Daniel Stenberg (26 Feb 2024) + +- strtoofft: fix the overflow check + + ... to not rely on wrapping, since it is an undefined behavior that is + not what always might happen. This is in our private strtoff() parser + function, used only on platforms without a native version. + + Reported-by: vulnerabilityspotter on hackerone + Closes #12990 + +- libssh/libssh2: return error on too big range + + If trying to get the range 0 - 2^63 and the remote file is 2^63 bytes or + larger. + + Fixes #12983 + Closes #12984 + +Scott Talbert (24 Feb 2024) + +- setopt: fix check for CURLOPT_PROXY_TLSAUTH_TYPE value + + Prior to this change CURLOPT_PROXY_TLSAUTH_TYPE would return + CURLE_BAD_FUNCTION_ARGUMENT on any type other than NULL. Since there is + only one type of TLS auth and it is also the default (SRP) the TLS auth + would work anyway. + + Closes https://github.com/curl/curl/pull/12981 + +Jay Satiro (24 Feb 2024) + +- mprintf: fix format prefix I32/I64 for windows compilers + + - Support I32 & I64 (eg: %I64d) for all Win32 builds. + + Prior to this change mprintf support for the I format prefix, which is a + Microsoft extension, was dependent on the compiler used. + + When Borland compiler support was removed in fd7ef00f the prefix was + then no longer supported for that compiler; however since it's still + possible to build with Borland I'm restoring support for the prefix in + this way. + + Reported-by: PaweÅ‚ Witas + + Fixes https://github.com/curl/curl/issues/12944 + Closes https://github.com/curl/curl/pull/12950 + +Daniel Stenberg (23 Feb 2024) + +- cd2nroff: gen: make `\>` in input to render as plain '>' in output + + The same (copy and pasted) fix/mistake as in gen.pl + +- gen: make `\>` in input to render as plain '>' in output + + Reported-by: Gisle Vanem + Fixes #12977 + Closes #12978 + +Fabrice Fontaine (23 Feb 2024) + +- configure.ac: find libpsl with pkg-config + + Find libpsl with pkg-config to avoid static build failures. + + Ref: http://autobuild.buildroot.org/results/1fb15e1a99472c403d0d3b1a688902f32 + e78d002 + + Signed-off-by: Fabrice Fontaine + Closes #12947 + +Daniel Stenberg (23 Feb 2024) + +- BUG-BOUNTY.md: clarify that the curl security team decides + + Closes #12975 + +- THANKS: add bug reporter from #740 + + Ref: https://github.com/curl/curl/issues/740 + +Stefan Eissing (22 Feb 2024) + +- multi: fix multi_sock handling of select_bits + + - OR the event bitmask to data->state.select_bits instead of overwriting + them. They are cleared again on use. + + Reported-by: 5533asdg on github + Fixes #12971 + Closes #12972 + +Daniel Stenberg (22 Feb 2024) + +- curlver: bump to 8.7.0 for next release + +- RELEASE-NOTES: synced + +- write-out: add '%{proxy_used}' + + Returns 1 if the previous transfer used a proxy, otherwise 0. Useful to + for example determine if a `NOPROXY` pattern matched the hostname or + not. + + Extended test 970 and 972 + +- CURLINFO_USED_PROXY: return bool whether the proxy was used + + Adds test536 to verify + + Closes #12719 + +- sha512_256: remove the cast macro, minor language/format edits + + Follow-up to cbe41d151d6a100c + + Closes #12966 + +Stefan Eissing (20 Feb 2024) + +- DoH: add trace configuration + + - refs #12397 where it is dicussed how to en-/disable verbose output + of DoH operations + - introducing `struct curl_trc_feat` to track a curl feature for + tracing + - adding `data->state.feat` optionally pointing to the feature a + transfer belongs to + - adding trace functions and verbosity checks on features + - using trace feature in DoH code + - documenting `doh` as feature for `--trace-config` + + Closes #12411 + +- websocket: fix curl_ws_recv() + + - when data arrived in several chunks, the collection into + the passed buffer always started at offset 0, overwriting + the data already there. + + adding test_20_07 to verify fix + + - debug environment var CURL_WS_CHUNK_SIZE can be used to + influence the buffer chunk size used for en-/decoding. + + Closes #12945 + +Evgeny Grin (Karlson2k) (20 Feb 2024) + +- digest: support SHA-512/256 + + Also fix the tests. New implementation tested with GNU libmicrohttpd. + The new numbers in tests are real SHA-512/256 numbers (not just some + random ;) numbers ). + +- tests: add SHA-512/256 unit test + +- SHA-512/256: implement hash algorithm + + Closes #12897 + +- curl_setup.h: add curl_uint64_t internal type + + The unsigned version of curl_off_t basically + +Daniel Stenberg (20 Feb 2024) + +- docs: dist curl*.1 and install without perl + + Drop docs/mk-ca-bundle.1 from the tarball. It can be generated at will. + + Closes #12959 + Fixes #12921 + Reported-by: Michael Forney + +Stefan Eissing (20 Feb 2024) + +- OpenSSL QUIC: adapt to v3.3.x + + - set our idle timeout as transport parameter + - query negotiated idle timeout for connection alive checks + - query number of available bidi streams on a connection + - use write_ex2 with SSL_WRITE_FLAG_CONCLUDE to signal + EOF on last chunk write, so stream close does not + require an additional QUIC packet + + Closes #12933 + +Ramiro Garcia (19 Feb 2024) + +- MANUAL.md: fix typo + + Closes #12965 + +Daniel Stenberg (19 Feb 2024) + +- BINDINGS: add mcurl, the python binding + + Ref: #12956 + Closes #12962 + +- mk-ca-bundle.md: cleanups and polish + + Closes #12958 + +- spellcheck.yml: remove .1/.3 handling, clean all man page .md files + + Since we generate all .1 and .3 files from markdown now, we can limit + the spellcheck to the markdown versions only. + + Closes #12960 + +- libcurl-docs: cleanups + + CURLMOPT_SOCKETDATA.md: fix typo + CURLMOPT_TIMERDATA.md: fix typo + CURLOPT_COOKIELIST.m: quote strings + CURLOPT_PREREQFUNCTION.md: quote variable names + CURLOPT_TCP_NODELAY.md: rephrased to please spell checker + CURLOPT_WILDCARDMATCH.md: rephrased + libcurl-tutorial.md: use correct option name + curl_global_init_mem.md: quote headers + curl_easy_getinfo.md: use correct symbol names in headers + curl_global_trace.md: quote some headers + curl_ws_meta.md: quote struct field names + libcurl-env.md: quote headers + +- cd2nroff: remove backticks from titles + +- RELEASE-NOTES: synced + +Stefan Eissing (18 Feb 2024) + +- http_chunks: fix the accounting of consumed bytes + + Prior to this change chunks were handled correctly although in verbose + mode libcurl could incorrectly warn of "Leftovers after chunking" even + if there were none. + + Reported-by: Michael Kaufmann + + Fixes https://github.com/curl/curl/issues/12937 + Closes https://github.com/curl/curl/pull/12939 + +- file: use xfer buf for file:// transfers + + - For file:// transfers use the multi handle's transfer buffer for + up- and downloads. + + Prior to this change a6c9a33 (precedes 8.6.0) changed the file:// + transfers to use a smaller stack based buffer, and that caused a + significant performance decrease in Windows. + + Bug: https://github.com/curl/curl/issues/12750#issuecomment-1920103086 + Reported-by: edmcln@users.noreply.github.com + + Closes https://github.com/curl/curl/pull/12932 + +Karthikdasari0423 (18 Feb 2024) + +- HTTP3.md: always run nghttp3 submodule init + + - For consistency change all 'build nghttp3' commands to run submodule + init after cloning, even if the branch does not have submodules. + + Follow-up to 5a4b2f93 and 4f794558. + + Closes https://github.com/curl/curl/pull/12928 + +LeeRiva (18 Feb 2024) + +- CURLOPT_POSTQUOTE.md: fix typo + + Closes https://github.com/curl/curl/pull/12926 + +Evgeny Grin (Karlson2k) (18 Feb 2024) + +- checksrc.pl: fix handling .checksrc with CRLF + + - When parsing .checksrc chomp the (CR)LF line ending. + + Prior to this change on Windows checksrc.pl would not process the + symbols in .checksrc properly, since many git repos in Windows use auto + crlf to check out files with CRLF line endings. + + Closes https://github.com/curl/curl/pull/12924 + +Richard Levitte (18 Feb 2024) + +- cmake: fix install for older CMake versions + + - Generate the docs install list by using a foreach loop instead of + LIST:TRANSFORM since older CMake can't handle the latter. + + Reported-by: Dan Fandrich + + Fixes https://github.com/curl/curl/issues/12920 + Closes https://github.com/curl/curl/pull/12922 + +Stefan Eissing (16 Feb 2024) + +- vtls: fix tls proxy peer verification + + - When verifying a proxy certificate for an ip address, use the correct + ip family. + + Prior to this change the "connection" ip family was used, which was not + necessarily the same. + + Reported-by: HsiehYuho@users.noreply.github.com + + Fixes https://github.com/curl/curl/issues/12831 + Closes https://github.com/curl/curl/pull/12931 + +Dan Fandrich (15 Feb 2024) + +- CI: Bump the Circle CI base Ubuntu image to the latest 20.04 + + The previous ones are going to be removed soon, plus the new ones + include all the fixes since then. + +Jay Satiro (13 Feb 2024) + +- transfer: improve Windows SO_SNDBUF update limit + + - Change the 1 second SO_SNDBUF update limit from per transfer to per + connection. + + Prior to this change many transfers over the same connection could cause + many SO_SNDBUF updates made to that connection per second, which was + unnecessary. + + Closes https://github.com/curl/curl/pull/12911 + +- schannel: fix hang on unexpected server close + + - Treat TLS connection close (either due to a close_notify from the + server or just closed due to receiving 0) as pending data. + + This is because in some cases schannel_recv knows the connection is + closed but has to return actual pending data so it can't return 0 or an + error to indicate no more data. In this case schannel_recv must be + called again, which only happens if readwrite_data sees that there is + still pending data. + + Prior to this change if the total size of the body that libcurl expected + to receive from the server was unknown then it was possible under some + network conditions that libcurl would hang waiting to receive more data, + when in fact a close_notify alert indicating no more data would be sent + was already processed. + + Fixes https://github.com/curl/curl/issues/12894 + Closes https://github.com/curl/curl/pull/12910 + +Daniel Stenberg (10 Feb 2024) + +- KNOWN_BUGS: FTP upload fails if remebered dir is deleted + + Closes #12181 + Closes #12923 + +MichaÅ‚ Antoniak (10 Feb 2024) + +- mbedtls: use mbedtls_ssl_conf_{min|max}_tls_version + + ... instead of the deprecated mbedtls_ssl_conf_{min|max}_version + + Closes #12905 + +Dan Fandrich (9 Feb 2024) + +- CI: bump to actions/cache@v4 to avoid warning + +Evgeny Grin (Karlson2k) (9 Feb 2024) + +- test1165: improve pattern matching + + * Fix excluded digits at the end of the symbols ('CURL_DISABLE_POP3' + was checked as 'CURL_DISABLE_POP') + + Closes #12903 + +Dan Fandrich (9 Feb 2024) + +- scripts: Fix cijobs.pl for Azure and GHA + + The spacing in the yaml files changed. + +Daniel Stenberg (9 Feb 2024) + +- RELEASE-NOTES: synced + +- TODO: use pkg-config to find libpsl + + Closes #12919 + +- TODO: avoid nroff + + Instead of adjusting roffit, skip the nroff step. + + Closes #12919 + +Dan Fandrich (9 Feb 2024) + +- Revert "CI: run Circle macOS builds on x86 for now" + + This reverts commit 2683de3078eadc86d9b182e7417f4ee75a247e2c. + ARM resources are now available in Circle CI, so run these builds on ARM + again. This platform needs explicit paths set to libpsl and its + dependency icu4c. + + Follow-up to 2683de30 + + Closes #12635 + +Viktor Szakats (9 Feb 2024) + +- cmake: add warning for using TLS libraries without 1.3 support + + Closes #12900 + +Daniel Stenberg (9 Feb 2024) + +- configure: add warning for using TLS libraries without 1.3 support + + Closes #12900 + +MichaÅ‚ Antoniak (9 Feb 2024) + +- mbedtls: fix building when MBEDTLS_X509_REMOVE_INFO flag is defined + + Closes #12904 + +Stefan Eissing (9 Feb 2024) + +- ftp: fix socket wait activity in ftp_domore_getsock + + - when waiting on the data connection, always add the control socket to + the pollset on state STOP or let the pingpong add the socket according + to its needs. + + Reported-by: Fabian Vogt + Fixes #12901 + Closes #12913 + +Daniel Stenberg (9 Feb 2024) + +- dist: make sure the http tests are in the tarball + + Fixes #12914 + Reported-by: Fabian Vogt + Closes #12917 + +Stefan Eissing (9 Feb 2024) + +- multi: add xfer_buf to multi handle + + - can be borrowed by transfer during recv-write operation + - needs to be released before borrowing again + - adjustis size to `data->set.buffer_size` + - used in transfer.c readwrite_data() + + Closes #12805 + +Daniel Stenberg (9 Feb 2024) + +- write-out.md: clarify error handling details + + - it gets used even if the transfer fails + + - it does not cause error to be returned even if it fails + + Closes #12909 + +Stefan Eissing (8 Feb 2024) + +- ftp: do lineend conversions in client writer + + - remove the ftp special handling from sendf.c + - let ftp_do() add a client writer that does + the linened conversions + - change the lineend conversion to no longer + modify the passed buffer, but write smaller + chunks to the next cwriter instead. The + inefficiency of this will be mitigated once + we add output buffering for all client writes. + + Closes #12878 + +- ftp: tracing improvements + + - trace socketindex for connection filters when not the first + - trace socket fd in tcp + - trace pollset adjusts in vtls + + Closes #12902 + +Karthikdasari0423 (8 Feb 2024) + +- HTTP3.md: adjust the OpenSSL QUIC install instructions + + tried installing with old steps but failed + tried with newly added setps and able to build + ``` + root@ubuntu:~/curl# ./src/curl -V + /root/curl/src/.libs/curl: /lib/x86_64-linux-gnu/libssl.so.3: version `OPENSS + L_3.2.0' not found (required by /root/curl/lib/.libs/libcurl.so.4) + root@ubuntu:~/curl# + ``` + ``` + root@ubuntu:~/curl# ./src/curl -V + curl 8.6.1-DEV (x86_64-pc-linux-gnu) libcurl/8.6.1-DEV OpenSSL/3.2.0 zlib/1.2 + .11 brotli/1.0.9 libpsl/0.21.0 nghttp3/1.1.0 OpenLDAP/2.5.16 + Release-Date: [unreleased] + Protocols: dict file ftp ftps gopher gophers http https imap imaps ipfs ipns + ldap ldaps mqtt pop3 pop3s rtsp smb smbs smtp smtps telnet tftp + Features: alt-svc AsynchDNS brotli HSTS HTTP3 HTTPS-proxy IPv6 Largefile libz + NTLM PSL SSL threadsafe TLS-SRP UnixSockets + root@ubuntu:~/curl# + ``` + + Closes #12896 + +Daniel Stenberg (8 Feb 2024) + +- TODO: align the TOC with the header + +- docs: make sure curl.1 is included in dist tarballs + + Ref: https://github.com/curl/curl/issues/12832#issuecomment-1933271873 + + Closes #12892 + +Karthikdasari0423 (8 Feb 2024) + +- HTTP3.md: remove quiche word in Openssl 3.2 + + Closes #12893 + +Daniel Stenberg (7 Feb 2024) + +- curl: when allocating variables, add the name into the struct + + This saves the name from being an extra separate allocation. + + Closes #12891 + +- lib582: remove code causing warning that is never run + + The previous realloc code in this code could trigger a compiler warning, + but since that code path cannot happen in normal circumstances it now + instead exits with an error message there. + + Ref: #12887 + Closes #12890 + +Stefan Eissing (7 Feb 2024) + +- vtls: revert "receive max buffer" + add test case + + - add test_05_04 for requests using http/1.0, http/1.1 and h2 against an + Apache resource that does an unclean TLS shutdown. + - revert special workarund in openssl.c for suppressing shutdown errors + on multiplexed connections + - vlts.c restore to its state before 9a90c9dd64d2f03601833a70786d485851bd1b53 + + Fixes #12885 + Fixes #12844 + + Closes #12848 + +Daniel Stenberg (7 Feb 2024) + +- tests: support setting/using blank content env variables + + - test450: remove --config from the keywords + - test2080: change return code + - test428: add --config as a keyword + - test428: disable on Windows due to CI problems + +- curl: exit on config file parser errors + + Like when trying to import an environment variable that does not exist. + + Also fix a bug for reading env variables when there is a default value + set. + + Bug: https://curl.se/mail/archive-2024-02/0008.html + Reported-by: Brett Buddin + + Add test 462 to verify. + + Closes #12862 + +Daniel Szmulewicz (7 Feb 2024) + +- CURLOPT_WRITEFUNCTION.md: typo fix + + The maximum amount of body data that is passed to the write + callback is defined in the curl.h header file + + Closes #12889 + +Daniel Stenberg (7 Feb 2024) + +- lib: convert Curl_get_line to use dynbuf + + Create the line in a dynbuf. Aborts the reading of the file on + errors. Avoids having to always allocate maximum amount from the + start. Avoids direct malloc. + + Closes #12846 + +- KNOWN_BUGS: unicode on Windows + + Closes #11461 + Closes #12231 + Closes #12883 + +- tool_operate: change precedence of server Retry-After time + + - When calculating the retry time, no longer allow a server's requested + Retry-After time to take precedence over a longer retry time (either + default algorithmic or user-specified). + + Prior to this change the server's Retry-After time took precedence over + curl's retry time in all cases, but that's not always practical for + short Retry-After times depending on how busy the server is. + + Bug: https://curl.se/mail/archive-2024-01/0022.html + Reported-by: Dirk Hünniger + + Closes https://github.com/curl/curl/pull/12871 + +- cmdline-docs: quote and angle bracket cleanup + + - make sure angle brackets are escaped + - remove a lot of superfluous double quotes + - replace several double quotes with backticks + + To make nicer-looking markdown. + + Closes #12884 + +- badwords: use hostname, not host name + + and username, filename - consistently. Fixed the patterns in + badwords.txt to catch these. + + Closes #12888 + +Viktor Szakats (6 Feb 2024) + +- cmake: fix function description in comment [ci skip] + + Closes #12879 + +Daniel Stenberg (6 Feb 2024) + +- header.md: remove backslash, make nicer markdown + + - remove a leftover backslash before a dash + - use backticks for "code" strings + + Closes #12877 + +- docs: add mk-ca-bundle.1 to dist + + ... which also makes it get built. But don't build this or curl-config.1 + if build docs is disabled. + + Closes #12875 + +Stefan Eissing (6 Feb 2024) + +- https-proxy: use IP address and cert with ip in alt names + + - improve info logging when peer verification fails to indicate + if DNS name or ip address has been tried to match + - add test case for contacting https proxy with ip address + - add pytest env check on loaded credentials and re-issue + when they are no longer valid + - disable proxy ip address test for bearssl, since not supported there + + Ref: #12831 + Closes #12838 + +Jiawen Geng (6 Feb 2024) + +- docs: add necessary setup for nghttp3 + + Now nghttp3 has submodules + https://github.com/ngtcp2/nghttp3/blob/main/.gitmodules + + Closes #12859 + +Peter Krefting (6 Feb 2024) + +- version: allow building with ancient libpsl + + The psl_check_version_number() API was added in libpsl 0.11.0. CentOS 7 + ships with version 0.7.0 which lacks this API. Revert to using the older + versioning API if we detect an old libpsl version. + + Follow-up to 72bd88adde0e8cf6e63644a7d6df1da01a399db4 + Bug: https://curl.se/mail/archive-2024-02/0004.html + Reported-by: Scott Mutter + Closes #12872 + +Daniel Stenberg (6 Feb 2024) + +- TODO: Support latest rustls + + Closes #12737 + Closes #12874 + +- docs: make curldown do angle brackets like markdown + + Make sure we use \< and \> in markdown all over so that it renders + correctly, on GitHub and elsewhere. cd2nroff now outputs a warning if it + finds an unescaled angle bracket. + + Ref: #12854 + Closes #12869 + +- docs: fix the --disable-docs for autotools + + Follow-up to 541321507e386 + + Closes #12870 + +- RELEASE-NOTES: synced + +- libcurl-security.md: Active FTP passes on the local IP address + + Reported-by: Harry Sintonen + Closes #12867 + +Stefan Eissing (5 Feb 2024) + +- configure: do not link with nghttp3 unless necessary + + Fixes #12833 + Closes #12864 + Reported-by: Ryan Carsten Schmidt + +Daniel Stenberg (5 Feb 2024) + +- THANKS: add Dmitry Tretyakov + + ... since I missed to give credit to the report in the fix of #12861 + +Stefan Eissing (5 Feb 2024) + +- openssl-quic: check on Windows that socket conv to int is possible + + Fixes #12861 + Closes #12865 + +Daniel Stenberg (5 Feb 2024) + +- tool_cb_hdr: only parse etag + content-disposition for 2xx + + ... and ignore them for other response codes. + + Reported-by: Harry Sintonen + Closes #12866 + +- md4: include strdup.h for the memdup proto + + Reported-by: Erik Schnetter + Fixes #12849 + Closes #12863 + +Joel Depooter (5 Feb 2024) + +- docs: add missing slashes to SChannel client certificate documentation + + When setting the CURLOPT_SSLCERT option to a certificate thumprint, it + is required to have a backslash between the "store location", "store + name" and "thumbprint" tokens. These slashes were present in the + previous documentation, but were missed in the transition to markdown + documentation. + + Closes #12854 + +Stefan Eissing (5 Feb 2024) + +- HTTP/2: write response directly + + - use the new `Curl_xfer_write_resp()` to write incoming responses + directly to the client + - eliminates `stream->recvbuf` + - memory consumption on parallel transfers minimized + + Closes #12828 + +Daniel Stenberg (5 Feb 2024) + +- cookie.md: provide an example sending a fixed cookie + + Closes #12868 + +Lars Kellogg-Stedman (5 Feb 2024) + +- ALTSVC.md: correct a typo + + The ALPN documentation erroneously referred to a "host number" instead + of a "port number". + + Closes #12852 + +Boris Verkhovskiy (5 Feb 2024) + +- proxy1.0.md: fix example + + Closes #12856 + +Chris Webb (5 Feb 2024) + +- configure: add --disable-docs flag + + Building man pages from curldown sources now requires perl. Add a + --disable-docs flag to configure to enable building and installing + without documentation where perl is not available or man pages are not + required. This is selected automatically (with a warning) when perl is + not found by configure. + + Fixes #12832 + Closes #12857 + +Faraz Fallahi (5 Feb 2024) + +- connect.c: fix typo + + Closes #12858 + +Daniel Stenberg (1 Feb 2024) + +- sendf: ignore response body to HEAD + + and mark the stream for close, but return OK since the response this far + was ok - if headers were received. Partly because this is what curl has + done traditionally. + + Test 499 verifies. Updates test 689. + + Reported-by: Sergey Bronnikov + Bug: https://curl.se/mail/lib-2024-02/0000.html + Closes #12842 + +- ftp: treat a 226 arriving before data as a signal to read data + + For active mode transfers. + + Due to some interesting timing, curl can sometimes get the 226 (transfer + complete) over the control channel first, before the data connection + signals readability. If this happens, use that as a signal to check the + data connection. + + Additionally, set the socket filter in listen mode *before* the + PORT/EPRT command is issued, to reduce the risk that the little time gap + could interfere. + + This issue never reproduced for me on Debian and takes several hundred + rounds for me to trigger on my mac. + + Reported-by: Stefan Eissing + Fixes #12823 + Closes #12841 + +Patrick Monnerat (1 Feb 2024) + +- OS400: avoid using awk in the build scripts + + Awk is a PASE program and its use may cause a failure depending on the + CCSID of the calling script (IBM bug?). + + For this reason, revert to an sed-only solution to extract the exported + symbols from the header files. + + Closes #12826 + +Jan Macku (1 Feb 2024) + +- docs: remove `mk-ca-bundle.1` from `man_MANS` + + It was accidentally added in https://github.com/curl/curl/pull/12730 + + Co-authored-by: Lukáš Zaoral + Signed-off-by: Jan Macku + + Follow-up to eefcc1bda4bccd800f5a56a0fe17a2f44a96e88b + Closes #12843 + +Daniel Stenberg (1 Feb 2024) + +- RELEASE-NOTES: synced + + and bump to 8.6.1 for now + +- cmdline-docs/Makefile: avoid using a fixed temp file name + + By appending the pid number two different runs at the same time will not + trample over the same file. + + Reported-by: Jon Rumsey + Fixes #12829 + Closes #12839 + +- asyn-thread: use wakeup_close to close the read descriptor + + Reported-by: Dan Fandrich + Ref: #12834 + Closes #12836 + +Stefan Eissing (1 Feb 2024) + +- ntml_wb: fix buffer type typo + + Closes #12825 + +Daniel Stenberg (1 Feb 2024) + +- tool_operate: do not set CURLOPT_QUICK_EXIT in debug builds + + Since it allows (small) memory leaks that interfere with torture tests + and regular memory-leak checks. + + Reported-by: Dan Fandrich + Fixes #12834 + Closes #12835 + +Boris Verkhovskiy (31 Jan 2024) + +- form-string.md: correct the example + + Closes #12822 + +Version 8.6.0 (31 Jan 2024) + +Daniel Stenberg (31 Jan 2024) + +- RELEASE-NOTES: synced + + curl 8.6.0 + +- THANKS: new contributors from 8.5.0 + +Jay Satiro (31 Jan 2024) + +- cd2nroff: use perl 'strict' and 'warnings' + + - Use strict and warnings pragmas. + + - If open() fails then show the reason. + + - Set STDIN io layer :crlf so that input is properly read on Windows. + + - When STDIN is used as input, the filename $f is now set to "STDIN". + + Various error messages in single() use $f for the filename and this way + it is not undefined when STDIN. + + Closes https://github.com/curl/curl/pull/12819 + +Daniel Stenberg (30 Jan 2024) + +- cd2nroff: fix duplicate output issue + + Assisted-by: Jay Satiro + Fixes https://github.com/curl/curl-www/issues/321 + Closes #12818 + +- lib: error out on multissl + http3 + + Since the QUIC/h3 code has no knowledge or handling of multissl it might + bring unintended consequences if we allow it. + + configure, cmake and curl_setup.h all now reject this combination. + + Assisted-by: Viktor Szakats + Assisted-by: Gisle Vanem + Ref: #12806 + Closes #12807 + +Patrick Monnerat (29 Jan 2024) + +- OS400: sync ILE/RPG binding + + Also do not force git CRLF line endings on *.cmd files for OS400. + + Closes #12815 + +Viktor Szakats (28 Jan 2024) + +- build: delete/replace 3 more clang warning pragmas + + - tool_msgs: delete redundant `-Wformat-nonliteral` suppression pragma. + + - whitespace formatting in `mprintf.h`, lib518, lib537. + + - lib518: fix wrong variable in `sizeof()`. + + - lib518: bump variables to `rlim_t`. + Follow-up to e2b394106d543c4615a60795b7fdce04bd4e5090 #1469 + + - lib518: sync error message with lib537 + Follow-up to 365322b8bcf9efb6a361473d227b70f2032212ce + + - lib518, lib537: replace `-Wformat-nonliteral` suppression pragmas + by reworking test code. + + Follow-up to 5b286c250829e06a135a6ba998e80beb7f43a734 #12812 + Follow-up to aee4ebe59161d0a5281743f96e7738ad97fe1cd4 #12803 + Follow-up to 09230127589eccc7e01c1a7217787ef8e64f3328 #12540 + Follow-up to 3829759bd042c03225ae862062560f568ba1a231 #12489 + + Reviewed-by: Daniel Stenberg + Closes #12814 + +Richard Levitte (27 Jan 2024) + +- cmake: freshen up docs/INSTALL.cmake + + - Turn docs/INSTALL.cmake into a proper markdown file, + docs/INSTALL-CMAKE.md + - Move things around to divide the description into configuration, + building and installing sections + - Mention the more modern cmake options to configure, build and install, + but also retain the older variants as fallbacks + + Closes #12772 + +Viktor Szakats (27 Jan 2024) + +- build: delete/replace clang warning pragmas + + - delete redundant warning suppressions for `-Wformat-nonliteral`. + This now relies on `CURL_PRINTF()` and it's theoratically possible + that this macro isn't active but the warning is. We're ignoring this + as a corner-case here. + + - replace two pragmas with code changes to avoid the warnings. + + Follow-up to aee4ebe59161d0a5281743f96e7738ad97fe1cd4 #12803 + Follow-up to 09230127589eccc7e01c1a7217787ef8e64f3328 #12540 + Follow-up to 3829759bd042c03225ae862062560f568ba1a231 #12489 + + Reviewed-by: Daniel Stenberg + Closes #12812 + +Daniel Stenberg (27 Jan 2024) + +- RELEASE-NOTES: synced + +- http: only act on 101 responses when they are HTTP/1.1 + + For 101 responses claiming to be any other protocol, bail out. This + would previously trigger an assert. + + Add test 1704 to verify. + + Bug: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=66184 + Closes #12811 + +Scarlett McAllister (27 Jan 2024) + +- _VARIABLES.md: add missing 'be' into the sentence + + Closes #12809 + +Stefan Eissing (27 Jan 2024) + +- mqtt, remove remaining use of data->state.buffer + + Closes #12799 + +Daniel Stenberg (27 Jan 2024) + +- x509asn1: switch from malloc to dynbuf + + Closes #12808 + +- x509asn1: make utf8asn1str() use dynbuf instead of malloc + memcpy + + Closes #12808 + +- x509asn1: reduce malloc in Curl_extract_certinfo + + Using dynbuf + + Closes #12808 + +Jay Satiro (27 Jan 2024) + +- THANKS: add Alexander Bartel and Brennan Kinney + + They reported and investigated #10259 which was fixed by 7b2d98df. + + Ref: https://github.com/curl/curl/issues/10259 + +Daniel Stenberg (26 Jan 2024) + +- krb5: add prototype to silence clang warnings on mvsnprintf() + + "error: format string is not a string literal" + + Follow-up to 09230127589eccc7 which made the warning appear + + Assisted-by: Viktor Szakats + Closes #12803 + +- x509asn1: remove code for WANT_VERIFYHOST + + No code ever sets this anymore since we dropped gskit + + Follow-up to 78d6232f1f326b9ab4d + + Closes #12804 + +- socks: reduce the buffer size to 600 (from 8K) + + This is malloc'ed memory and it does not more. Test 742 helps us verify + this. + + Closes #12789 + +Stefan Eissing (26 Jan 2024) + +- file+ftp: use stack buffers instead of data->state.buffer + + Closes #12789 + +- vtls: receive max buffer + + - do not only receive one TLS record, but try to fill + the passed buffer + - consider <4K remaning space is "filled". + + Closes #12801 + +Daniel Stenberg (26 Jan 2024) + +- docs: do not start lines/sentences with So, But nor And + + Closes #12802 + +- docs: remove spurious ampersands from markdown + + They were leftovers from the nroff conversion. + + Follow-up to eefcc1bda4bccd800f5a5 + + Closes #12800 + +Patrick Monnerat (26 Jan 2024) + +- sasl: make login option string override http auth + + - Use http authentication mechanisms as a default, not a preset. + + Consider http authentication options which are mapped to SASL options as + a default (overriding the hardcoded default mask for the protocol) that + is ignored if a login option string is given. + + Prior to this change, if some HTTP auth options were given, sasl mapped + http authentication options to sasl ones but merged them with the login + options. + + That caused problems with the cli tool that sets the http login option + CURLAUTH_BEARER as a side-effect of --oauth2-bearer, because this flag + maps to more than one sasl mechanisms and the latter cannot be cleared + individually by the login options string. + + New test 992 checks this. + + Fixes https://github.com/curl/curl/issues/10259 + Closes https://github.com/curl/curl/pull/12790 + +Stefan Eissing (26 Jan 2024) + +- socks: use own buffer instead of data->state.buffer + + Closes #12788 + +Daniel Stenberg (26 Jan 2024) + +- socks: fix generic output string to say SOCKS instead of SOCKS4 + + ... since it was also logged for SOCKS5. + + Closes #12797 + +- test742: test SOCKS5 with max length user, password and hostname + + Adjusted the socksd server accordingly to allow for configuring that + long user name and password. + + Closes #12797 + +Stefan Eissing (25 Jan 2024) + +- ssh: use stack scratch buffer for seeks + + - instead of data->state.buffer + + Closes #12794 + +Daniel Stenberg (25 Jan 2024) + +- krb5: access the response buffer correctly + + As the pingpong code no longer uses the download buffer. + + Folllow-up to c2d973627bab12ab + Pointed-out-by: Stefan Eissing + Closes #12796 + +Stefan Eissing (25 Jan 2024) + +- mqtt: use stack scratch buffer for recv+publish + + - instead of data->state.buffer + + Closes #12792 + +- telnet, use stack scratch buffer for do + + - instead of data->state.buffer + + Closes #12793 + +- http, use stack scratch buffer + + - instead of data->state.buffer + + Closes #12791 + +- ntlm_wb: do not use data->state.buf any longer + + Closes #12787 + +- gitignore: the generated `libcurl-symbols.md` + + Closes #12795 + +Daniel Stenberg (25 Jan 2024) + +- tool: fix the listhelp generation command + + The previous command line to generate the tool_listhelp.c source file + broke with 2494b8dd5175cee7. + + Make 'make listhelp' invoked in src/ generate it. Also update the + comment in the file to mention the right procedure. + + Closes #12786 + +- http: check for "Host:" case insensitively + + When checking if the user wants to replace the header, the check should + be case insensitive. + + Adding test 461 to verify + + Found-by: Dan Fandrich + Ref: #12782 + Closes #12784 + +Tatsuhiro Tsujikawa (25 Jan 2024) + +- configure: add libngtcp2_crypto_boringssl detection + + If OpenSSL is found to be BoringSSL or AWS-LC, and ngtcp2 is requested, + try to detect libngtcp2_crypto_boringssl. + + Reported-by: ウã•ã‚“ + Fixes #12724 + Closes #12769 + +Daniel Stenberg (25 Jan 2024) + +- http: remove comment reference to a removed solution + + Follow-up to 58974d25d + + Closes #12785 + +Stefan Eissing (25 Jan 2024) + +- pytest: Scorecard tracking CPU and RSS + + Closes #12765 + +Graham Campbell (25 Jan 2024) + +- GHA: bump ngtcp2, gnutls, mod_h2, quiche + + - ngtcp2 to v1.2.0 + - gnutls to 3.8.3 + - mod_h2 to 2.0.26 + - quiche to 0.20.0 + + Closes #12778 + Closes #12779 + Closes #12780 + Closes #12781 + +Daniel Stenberg (25 Jan 2024) + +- ftpserver.pl: send 213 SIZE response without spurious newline + +- pingpong: stop using the download buffer + + The pingpong logic now uses its own dynbuf for receiving command + response data. + + When the "final" response header for a commanad has been received, that + final line is left first in the recvbuf for the protocols to parse at + will. If there is additional data behind the final response line, the + 'overflow' counter is indicate how many bytes. + + Closes #12757 + +- gen.pl: remove bold from .IP used for ## + + Reported-by: Viktor Szakats + Fixes #12776 + Closes #12777 + +Viktor Szakats (24 Jan 2024) + +- cmake: rework options to enable curl and libcurl docs + + Rework CMake options for building/using curl tool and libcurl manuals. + + - rename `ENABLE_MANUAL` to `ENABLE_CURL_MANUAL`, meaning: + to build man page and built-in manual for curl tool. + + - rename `BUILD_DOCS` to `BUILD_LIBCURL_DOCS`, meaning: + to build man pages for libcurl. + + - `BUILD_LIBCURL_DOCS` now works without having to enable + `ENABLE_CURL_MANUAL` too. + + - drop support for existing CMake-level `USE_MANUAL` option to avoid + confusion. (It used to work with the effect of current + `ENABLE_CURL_MANUAL`, but only by accident.) + + Assisted-by: Richard Levitte + Ref: #12771 + Closes #12773 + +Daniel Stenberg (24 Jan 2024) + +- urlapi: remove assert + + This assert triggers wrongly when CURLU_GUESS_SCHEME and + CURLU_NO_AUTHORITY are both set and the URL is a single path. + + I think this assert has played out its role. It was introduced in a + rather big refactor. + + Follow-up to 4cfa5bcc9a + + Reported-by: promptfuzz_ on hackerone + Closes #12775 + +Patrick Monnerat (24 Jan 2024) + +- tests: avoid int/size_t conversion size/sign warnings + + Closes #12768 + +Daniel Stenberg (24 Jan 2024) + +- GHA: add a job scanning for "bad words" in markdown + + This means words, phrases or things we have decided not to use - words that + are spelled right according to the dictionary but we want to avoid. In the + name of consistency and better documentation. + + Closes #12764 + +Viktor Szakats (23 Jan 2024) + +- cmake: speed up curldown processing, enable by default + + - cmake: enable `BUILD_DOCS` by default (this controls converting and + installing `.3` files from `.md` sources) + + - cmake: speed up generating `.3` files by using a single command per + directory, instead of a single command per file. This reduces external + commands by about a thousand. (There remains some CMake logic kicking + in resulting in 500 -one per file- external `-E touch_nocreate` calls.) + + - cd2nroff: add ability to process multiple input files. + + - cd2nroff: add `-k` option to use the source filename to form the + output filename. (instead of the default in-file `Title:` line.) + + Follow-up to 3f08d80b2244524646ce86915c585509ac54fb4c + Follow-up to ea0b575dab86a3c44dd1d547dc500276266aa382 #12753 + Follow-up to eefcc1bda4bccd800f5a56a0fe17a2f44a96e88b #12730 + + Closes #12762 + +Richard Levitte (23 Jan 2024) + +- docs: install curl.1 with cmake as well + + Closes #12759 + +Daniel Stenberg (23 Jan 2024) + +- osslq: remove the TLS library from the version output + + Since we only support using a single TLS library at any one time, we + know that the TLS library for QUIC is the same that is also shown for + regular TLS. + + Fixes #12763 + Reported-by: Viktor Szakats + Closes #12767 + +Stefan Eissing (23 Jan 2024) + +- CI: remove unnecessary OpenSSL 3 option `enable-tls1_3` + + .. and switch OpenSSL 3 libdir from lib64 to lib for consistency. + + Closes https://github.com/curl/curl/pull/12758 + +- GHA: bump nghttp2 version to v1.59.0 + + - Switch to v1.59.0 for GHA CI jobs that use a specific nghttp2-version. + + Closes https://github.com/curl/curl/pull/12766 + +Daniel Stenberg (23 Jan 2024) + +- RELEASE-NOTES: synced + +- docs/cmdline: change to .md for cmdline docs + + - switch all invidual files documenting command line options into .md, + as the documentation is now markdown-looking. + + - made the parser treat 4-space indents as quotes + + - switch to building the curl.1 manpage using the "mainpage.idx" file, + which lists the files to include to generate it, instead of using the + previous page-footer/headers. Also, those files are now also .md + ones, using the same format. I gave them underscore prefixes to make + them sort separately: + _NAME.md, _SYNOPSIS.md, _DESCRIPTION.md, _URL.md, _GLOBBING.md, + _VARIABLES.md, _OUTPUT.md, _PROTOCOLS.md, _PROGRESS.md, _VERSION.md, + _OPTIONS.md, _FILES.md, _ENVIRONMENT.md, _PROXYPREFIX.md, + _EXITCODES.md, _BUGS.md, _AUTHORS.md, _WWW.md, _SEEALSO.md + + - updated test cases accordingly + + Closes #12751 + +dependabot[bot] (23 Jan 2024) + +- CI: bump actions/cache from 3 to 4 + + Bumps [actions/cache](https://github.com/actions/cache) from 3 to 4. + - [Release notes](https://github.com/actions/cache/releases) + - [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md) + - [Commits](https://github.com/actions/cache/compare/v3...v4) + + --- + updated-dependencies: + - dependency-name: actions/cache + dependency-type: direct:production + update-type: version-update:semver-major + ... + + Signed-off-by: dependabot[bot] + Closes #12756 + +Daniel Stenberg (23 Jan 2024) + +- openssl: when verifystatus fails, remove session id from cache + + To prevent that it gets used in a subsequent transfer that skips the + verifystatus check since that check can't be done when the session id is + reused. + + Reported-by: Hiroki Kurosawa + Closes #12760 + +Viktor Szakats (23 Jan 2024) + +- cmake: add option to disable building docs + +Richard Levitte (23 Jan 2024) + +- cmake: use curldown to build man pages + + This throws away the previous HTML and PDF producers, to mimic what + Makefile.am does as faithfully as possible. + + Closes #12753 + +Daniel Stenberg (23 Jan 2024) + +- mksymbolsmanpage.pl: provide references to where the symbol is used + +- docs: introduce "curldown" for libcurl man page format + + curldown is this new file format for libcurl man pages. It is markdown + inspired with differences: + + - Each file has a set of leading headers with meta-data + - Supports a small subset of markdown + - Uses .md file extensions for editors/IDE/GitHub to treat them nicely + - Generates man pages very similar to the previous ones + - Generates man pages that still convert nicely to HTML on the website + - Detects and highlights mentions of curl symbols automatically (when + their man page section is specified) + + tools: + + - cd2nroff: converts from curldown to nroff man page + - nroff2cd: convert an (old) nroff man page to curldown + - cdall: convert many nroff pages to curldown versions + - cd2cd: verifies and updates a curldown to latest curldown + + This setup generates .3 versions of all the curldown versions at build time. + + CI: + + Since the documentation is now technically markdown in the eyes of many + things, the CI runs many more tests and checks on this documentation, + including proselint, link checkers and tests that make sure we capitalize the + first letter after a period... + + Closes #12730 + +Viktor Szakats (22 Jan 2024) + +- libssh2: use `libssh2_session_callback_set2()` with v1.11.1 + + To avoid a local hack to pass function pointers and to avoid + deprecation warnings when building with libssh2 v1.11.1 or newer: + ``` + lib/vssh/libssh2.c:3324:5: warning: 'libssh2_session_callback_set' is depreca + ted: since libssh2 1.11.1. Use libssh2_session_callback_set2() [-Wdeprecated- + declarations] + lib/vssh/libssh2.c:3326:5: warning: 'libssh2_session_callback_set' is depreca + ted: since libssh2 1.11.1. Use libssh2_session_callback_set2() [-Wdeprecated- + declarations] + ``` + Ref: https://github.com/curl/curl-for-win/actions/runs/7609484879/job/2072082 + 1100#step:3:4982 + + Ref: https://github.com/libssh2/libssh2/pull/1285 + Ref: https://github.com/libssh2/libssh2/commit/c0f69548be902147ce014ffa40b8db + 3cf1d4b0b4 + Reviewed-by: Daniel Stenberg + Closes #12754 + +Daniel Stenberg (22 Jan 2024) + +- transfer: make the select_bits_paused condition check both directions + + If there is activity in a direction that is not paused, return false. + + Reported-by: Sergey Bronnikov + Bug: https://curl.se/mail/lib-2024-01/0049.html + Closes #12740 + +Stefan Eissing (22 Jan 2024) + +- http3: initial support for OpenSSL 3.2 QUIC stack + + - HTTP/3 for curl using OpenSSL's own QUIC stack together + with nghttp3 + - configure with `--with-openssl-quic` to enable curl to + build this. This requires the nghttp3 library + - implementation with the following restrictions: + * macOS has to use an unconnected UDP socket due to an + issue in OpenSSL's datagram implementation + See https://github.com/openssl/openssl/issues/23251 + This makes connections to non-reponsive servers hang. + * GET requests will send the indicator that they have + no body in a separate QUIC packet. This may result + in processing delays or Transfer-Encodings on proxied + requests + * uploads that encounter blocks will use 100% cpu as + detection of these flow control issue is not working + (we have not figured out to pry that from OpenSSL). + + Closes #12734 + +Viktor Szakats (22 Jan 2024) + +- cmake: fix `ENABLE_MANUAL` option + + Fix the `ENABLE_MANUAL` option. Set it to default to `OFF`. + + Before this patch `ENABLE_MANUAL=ON` was a no-op, even though it was the + option designed to enable building and using the built-in curl manual. + (`USE_MANUAL=ON` option worked for this instead, by accident). + + Ref: https://github.com/curl/curl/pull/12730#issuecomment-1902572409 + Closes #12749 + +Mohammadreza Hendiani (19 Jan 2024) + +- TODO: update broken link to ratelimit-headers draft + + Closes #12741 + +Daniel Stenberg (19 Jan 2024) + +- cmake: when USE_MANUAL=YES, build the curl.1 man page + + Fixes KNOWN_BUG 15.4 + + Closes #12742 + +- cmdline-opts/write-out.d: remove spurious double quotes + +Stefan Eissing (19 Jan 2024) + +- rtsp: Convert assertion into debug log + + Bug: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=65934 + + - write excess bytes to the client where the standard excess bytes + checks will report any wrongness and fail the transfer + + Fixes #12738 + Closes #12739 + +Daniel Stenberg (19 Jan 2024) + +- headers: remove assert from Curl_headers_push + + The fuzzer managed to reach the function without a terminating CR or LF + so let's handle it normally. While there, remove the goto. + + Bug: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=65839 + + Closes #12721 + +- curl_easy_getinfo.3: remove the wrong time value count + + It said "six" time values but they are eight by now. Remove the mention + of the amount. + + Closes #12727 + +Viktor Szakats (18 Jan 2024) + +- mbedtls: fix `-Wnull-dereference` and `-Wredundant-decls` + + - Silence warning in mbedTLS v3.5.1 public headers: + ``` + ./mbedtls/_x64-linux-musl/usr/include/psa/crypto_extra.h:489:14: warning: r + edundant redeclaration of 'psa_set_key_domain_parameters' [-Wredundant-decls] + ./mbedtls/_x64-linux-musl/usr/include/psa/crypto_struct.h:354:14: note: pre + vious declaration of 'psa_set_key_domain_parameters' was here + ``` + Ref: https://github.com/libssh2/libssh2/commit/ecec68a2c13a9c63fe8c2dc457ae + 785a513e157c + Ref: https://github.com/libssh2/libssh2/pull/1226 + + - Fix compiler warnings seen with gcc 9.2.0 + cmake unity: + ``` + ./curl/lib/vtls/mbedtls.c: In function 'mbedtls_bio_cf_read': + ./curl/lib/vtls/mbedtls.c:189:11: warning: null pointer dereference [-Wnull + -dereference] + 189 | nread = Curl_conn_cf_recv(cf->next, data, (char *)buf, blen, &res + ult); + | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~ + ./curl/lib/vtls/mbedtls.c: In function 'mbedtls_bio_cf_write': + ./curl/lib/vtls/mbedtls.c:168:14: warning: null pointer dereference [-Wnull + -dereference] + 168 | nwritten = Curl_conn_cf_send(cf->next, data, (char *)buf, blen, & + result); + | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~ + ``` + + - delete stray `#else`. + + Closes #12720 + +Daniel Stenberg (17 Jan 2024) + +- docs: cleanup nroff format use + + - remove use of .BI for code snippet + - stop using .br, just do a blank line + - remove use of .PP + - remove use for .sp + - remove backslash in .IP + - use .IP instead of .TP + + Closes #12731 + +Stefan Eissing (17 Jan 2024) + +- test2307: fix expected failure code after ws refactoring + + Fixes #12722 + Closes #12728 + +Jay Satiro (17 Jan 2024) + +- cf-socket: show errno in tcpkeepalive error messages + + - If the socket keepalive options (TCP_KEEPIDLE, etc) cannot be set + then show the errno in the verbose error messages. + + Ref: https://github.com/curl/curl/discussions/12715#discussioncomment-8151652 + + Closes https://github.com/curl/curl/pull/12726 + +- tool_getparam: stop supporting `@filename` style for --cookie + + The `@filename` style was never documented for --cookie + but prior to this change curl would accept it anyway and always treat a + @ prefixed string as a filename. + + That's a problem if the string also contains a = sign because then it is + documented to be interpreted as a cookie string and not a filename. + + Example: + + `--cookie @foo=bar` + + Before: Interpreted as load cookies from filename foo=bar. + + After: Interpreted as cookie `@foo=bar` (name `@foo` and value `bar`). + + Other curl options with a data/filename option-value use the `@filename` + to distinguish filenames which is probably how this happened. The + --cookie option has never been documented that way. + + Ref: https://curl.se/docs/manpage.html#-b + + Closes https://github.com/curl/curl/pull/12645 + +Stefan Eissing (16 Jan 2024) + +- websockets: refactor decode chain + + - use client writer stack for decoding frames + - move websocket protocol handler to ws.c + + Closes #12713 + +- websockets: check for negative payload lengths + + - in en- and decoding, check the websocket frame payload lengths for + negative values (from curl_off_t) and error the operation in that case + - add test 2307 to verify + + Closes #12707 + +Daniel Stenberg (16 Jan 2024) + +- docs: mention env vars not used by schannel + + Ref: #12704 + + Co-authored-by: Jay Satiro + + Closes #12711 + +- tool_operate: make --remove-on-error only remove "real" files + + Reported-by: Harry Sintonen + Assisted-by: Dan Fandrich + + Closes #12710 + +Jay Wu (16 Jan 2024) + +- url: don't set default CA paths for Secure Transport backend + + As the default for this backend is the native CA store. + + Closes #12704 + +Lin Sun (16 Jan 2024) + +- asyn-ares: with modern c-ares, use its default timeout + + Closes #12703 + +Daniel Stenberg (15 Jan 2024) + +- tool_operate: stop setting the file comment on Amiga + + - the URL is capped at 80 cols, which ruins it if longer + - it does not strip off URL credentials + - it is done unconditonally, not on --xattr + - we don't have Amiga in the CI which makes fixing it blindly fragile + + Someone who builds and tests on Amiga can add it back correctly in a + future if there is a desire. + + Reported-by: Harry Sintonen + Closes #12709 + +Stefan Eissing (15 Jan 2024) + +- rtsp: deal with borked server responses + + - enforce a response body length of 0, if the + response has no Content-lenght. This is according + to the RTSP spec. + - excess bytes in a response body are forwarded to + the client writers which will report and fail the + transfer + + Follow-up to d7b6ce6 + Fixes #12701 + Closes #12706 + +Daniel Stenberg (14 Jan 2024) + +- version: show only the libpsl version, not its dependencies + + The libpsl version output otherwise also includes version number for its + dependencies, like IDN lib, but since libcurl does not use libpsl's IDN + functionality those components are not important. + + Ref: https://github.com/curl/curl-for-win/issues/63 + Closes #12700 + +Brad Harder (14 Jan 2024) + +- curl.h: CURLOPT_DNS_SERVERS is only available with c-ares + + Closes #12695 + +Daniel Stenberg (14 Jan 2024) + +- cmdline-opts/gen.pl: error on initital blank line + + After the "---" separator, there should be no blank line and this script + now errors out if one is detected. + + Ref: #12696 + Closes #12698 + +- cf-h1-proxy: no CURLOPT_USERAGENT in CONNECT with hyper + + Follow-up to 693cd1679361828a which was incomplete + + Ref #12680 + Closes #12697 + +- curl_multi_fdset.3: remove mention of null pointer support + + ... since this funtion has not supported null pointer fd_set arguments since + at least 2006. (That's when I stopped my git blame journey) + + Fixes #12691 + Reported-by: sfan5 on github + Closes #12692 + +Mark Huang (14 Jan 2024) + +- docs/cmdline: remove unnecessary line breaks + + Closes #12696 + +Daniel Stenberg (14 Jan 2024) + +- transfer: remove warning: Value stored to 'blen' is never read + + Detected by scan-build + + Follow-up from 1cd2f0072f + + Closes #12693 + +Stefan Eissing (13 Jan 2024) + +- lib: replace readwrite with write_resp + + This clarifies the handling of server responses by folding the code for + the complicated protocols into their protocol handlers. This concerns + mainly HTTP and its bastard sibling RTSP. + + The terms "read" and "write" are often used without clear context if + they refer to the connect or the client/application side of a + transfer. This PR uses "read/write" for operations on the client side + and "send/receive" for the connection, e.g. server side. If this is + considered useful, we can revisit renaming of further methods in another + PR. + + Curl's protocol handler `readwrite()` method been changed: + + ```diff + - CURLcode (*readwrite)(struct Curl_easy *data, struct connectdata *conn, + - const char *buf, size_t blen, + - size_t *pconsumed, bool *readmore); + + CURLcode (*write_resp)(struct Curl_easy *data, const char *buf, size_t ble + n, + + bool is_eos, bool *done); + ``` + + The name was changed to clarify that this writes reponse data to the + client side. The parameter changes are: + + * `conn` removed as it always operates on `data->conn` + * `pconsumed` removed as the method needs to handle all data on success + * `readmore` removed as no longer necessary + * `is_eos` as indicator that this is the last call for the transfer + response (end-of-stream). + * `done` TRUE on return iff the transfer response is to be treated as + finished + + This change affects many files only because of updated comments in + handlers that provide no implementation. The real change is that the + HTTP protocol handlers now provide an implementation. + + The HTTP protocol handlers `write_resp()` implementation will get passed + **all** raw data of a server response for the transfer. The HTTP/1.x + formatted status and headers, as well as the undecoded response + body. `Curl_http_write_resp_hds()` is used internally to parse the + response headers and pass them on. This method is public as the RTSP + protocol handler also uses it. + + HTTP/1.1 "chunked" transport encoding is now part of the general + *content encoding* writer stack, just like other encodings. A new flag + `CLIENTWRITE_EOS` was added for the last client write. This allows + writers to verify that they are in a valid end state. The chunked + decoder will check if it indeed has seen the last chunk. + + The general response handling in `transfer.c:466` happens in function + `readwrite_data()`. This mainly operates now like: + + ``` + static CURLcode readwrite_data(data, ...) + { + do { + Curl_xfer_recv_resp(data, buf) + ... + Curl_xfer_write_resp(data, buf) + ... + } while(interested); + ... + } + ``` + + All the response data handling is implemented in + `Curl_xfer_write_resp()`. It calls the protocol handler's `write_resp()` + implementation if available, or does the default behaviour. + + All raw response data needs to pass through this function. Which also + means that anyone in possession of such data may call + `Curl_xfer_write_resp()`. + + Closes #12480 + +Daniel Stenberg (13 Jan 2024) + +- RELEASE-NOTES: synced + +- TODO: TFTP doesn't convert LF to CRLF for mode=netascii + + Closes #12655 + Closes #12690 + +- gen: do italics/bold for a range of letters, not just single word + + Previously it would match only on a sequence of non-space, which made it + miss to highlight for example "public suffix list". + + Updated the recent cookie.d edit from 5da57193b732 to use bold instead + of italics. + + Closes #12689 + +- docs: describe and highlight super cookies + + Reported-by: Yadhu Krishna M + + Closes #12687 + +- configure: when enabling QUIC, check that TLS supports QUIC + + Most importantly perhaps is when using OpenSSL that the used + build/flavor has the QUIC API: the vanilla OpenSSL does not, only + BoringSSL, libressl, AWS-LC and quictls do. + + Ref: https://github.com/curl/curl/commit/5d044ad9480a9f556f4b6a252d7533b1ba7f + e57e#r136780413 + + Closes #12683 + +Stefan Eissing (11 Jan 2024) + +- vquic: extract TLS setup into own source + + - separate ngtcp2 specific parts out + - provide callback during init to allow ngtcp2 to apply its defaults + + Closes #12678 + +Sergey Markelov (11 Jan 2024) + +- multi: remove total timer reset in file_do() while fetching file:// + + The total timer is properly reset in MSTATE_INIT. MSTATE_CONNECT starts + with resetting the timer that is a start point for further multi states. + If file://, MSTATE_DO calls file_do() that should not reset the total + timer. Otherwise, the total time is always less than the pre-transfer + and the start transfer times. + + Closes #12682 + +Daniel Stenberg (11 Jan 2024) + +- http_proxy: a blank CURLOPT_USERAGENT should not be used in CONNECT + + Extended test 80 to verify this. + + Reported-by: Stefan Eissing + Fixes #12680 + Closes #12681 + +- sectransp: do verify_cert without memdup for blobs + + Since the information is then already stored in memory, this can avoid + an extra set of malloc + free calls. + + Closes #12679 + +- hsts: remove assert for zero length domain + + A zero length domain can happen if the HSTS parser is given invalid + input data which is not unheard of and is done by the fuzzer. + + Follow-up from cfe7902111ae547873 + + Bug: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=65661 + + Closes #12676 + +- headers: make sure the trailing newline is not stored + + extended test1940 to verify blank header fields too + + Bug: https://curl.se/mail/lib-2024-01/0019.html + Reported-by: Dmitry Karpov + Closes #12675 + +- curl_easy_header.3: tiny language fix + + Closes #12672 + +- examples/range.c: add + + Closes #12671 + +- examples/netrc.c: add + + Closes #12671 + +- examples/ipv6.c: new example showing IPv6-only internet transfer + + Closes #12671 + +- examples/address-scope.c: renamed from ipv6.c + + It shows address scope use really + + Closes #12671 + +Stefan Eissing (9 Jan 2024) + +- multi: pollset adjust, init with FIRSTSOCKET during connect + + - `conn->sockfd` is set by `Curl_setup_transfer()`, but that + is called *after* the connection has been established + - use `conn->sock[FIRSTSOCKET]` instead + + Follow-up to a0f94800d507de + Closes #12664 + +Daniel Stenberg (9 Jan 2024) + +- WEBSOCKET.md: remove dead link + +- CI: spellcheck/appveyor: invoke configure --without-libpsl + + Follow-up to 2998874bb61ac6 + +- cmdline/docs/*.d: switch to using ## instead of .IP + + To make the editing easier. To write and to read. + + Closes #12667 + +- gen.pl: support ## for doing .IP in table-like lists + + Warn on use of .RS/.IP/.RE + + Closes #12667 + +Jay Satiro (9 Jan 2024) + +- cookie.d: Document use of empty string to enable cookie engine + + - Explain that --cookie "" can be used to enable the cookie engine + without reading any initial cookies. + + As is documented in CURLOPT_COOKIEFILE. + + Ref: https://curl.se/libcurl/c/CURLOPT_COOKIEFILE.html + + Bug: https://github.com/curl/curl/issues/12643#issuecomment-1879844420 + Reported-by: janko-js@users.noreply.github.com + + Closes https://github.com/curl/curl/pull/12646 + +Daniel Stenberg (9 Jan 2024) + +- setopt: use memdup0 when cloning COPYPOSTFIELDS + + Closes #12651 + +- telnet: use dynbuf instad of malloc for escape buffer + + Previously, send_telnet_data() would malloc + free a buffer every time + for escaping IAC codes. Now, it reuses a dynbuf for this purpose. + + Closes #12652 + +- CI: install libpsl or configure --without-libpsl in builds + + As a follow-up to the stricted libpsl check in configure + +- configure: make libpsl detection failure cause error + + To force users to explictily disable it if they really don't want it + used and make it harder to accidentally miss it. + + --without-libpsl is the option to use if PSL is not wanted. + + Closes #12661 + +- RELEASE-NOTES: synced + +- pop3: replace calloc + memcpy with memdup0 + + ... and make sure to return error on out of memory. + + Closes #12650 + +- lib: add debug log outputs for CURLE_BAD_FUNCTION_ARGUMENT + + Closes #12658 + +- mime: use memdup0 instead of malloc + memcpy + + Closes #12649 + +- tool_getparam: move the --rate logic into set_rate() + +- tool_getparam: switch to an enum for every option + + To make the big switch much easier to read/understand and to make it + easier to add new options. + +- tool_getparam: build post data using dynbuf (more) + +- tool_getparam: replace malloc + copy by dynbuf for --data + +- tool_getparam: make data_urlencode avoid direct malloc + + use aprintf() instead + +- tool_getparam: move the --url-query logic into url_query() + + This function is not doing post at all so it was always weirdly placed. + +- tool_getparam: move the --data logic into set_data() + +- tool_getparam: unify the cmdline switch() into a single one + + - easier to follow, easier to modify, easier to extend, possibly slightly + faster + + - each case now has the long option as a comment + +- tool_getparam: bsearch cmdline options + + - the option names are now alpha sorted and lookup is a lot faster + + - use case sensitive matching. It was previously case insensitive, but that + was not documented nor tested. + + - remove "partial match" feature. It was not documented, not tested and + was always fragile as existing use could break when we add a new + option + + - lookup short options via a table + + Closes #12631 + +Gabe (8 Jan 2024) + +- COPYING: update copyright year + + Closes #12654 + +Stefan Eissing (8 Jan 2024) + +- url: init conn->sockfd and writesockfd to CURL_SOCKET_BAD + + Also add more tracing to test 19 + + Follow-up to a0f9480 + + Fixes #12657 + Closes #12659 + +Daniel Stenberg (8 Jan 2024) + +- connect: remove margin from eyeballer alloc + + Presumably leftovers from debugging + + Closes #12647 + +- ftp: only consider entry path if it has a length + + Follow-up from 8edcfedc1a144f438bd1cdf814a0016cb + + Bug: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=65631 + + Avoids a NULL pointer deref. + + Closes #12648 + +Stefan Eissing (7 Jan 2024) + +- transfer: adjust_pollset improvements + + - let `multi_getsock()` initialize the pollset in what the + transfer state requires in regards to SEND/RECV + - change connection filters `adjust_pollset()` implementation + to react on the presence of POLLIN/-OUT in the pollset and + no longer check CURL_WANT_SEND/CURL_WANT_RECV + - cf-socket will no longer add POLLIN on its own + - http2 and http/3 filters will only do adjustments if the + passed pollset wants to POLLIN/OUT for the transfer on + the socket. This is similar to the HTTP/2 proxy filter + and works in stacked filters. + + Closes #12640 + +Daniel Stenberg (6 Jan 2024) + +- ftp: use memdup0 to store the OS from a SYST 215 response + + avoid malloc + direct buffer fiddle + + Closes #12639 + +- ftp: use dynbuf to store entrypath + + avoid direct malloc + + Closes #12638 + +Lealem Amedie (6 Jan 2024) + +- wolfssl: load certificate *chain* for PEM client certs + + Closes #12634 + +Stefan Eissing (4 Jan 2024) + +- http: adjust_pollset fix + + do not add a socket for POLLIN when the transfer does not want to send + (for example is paused). + + Follow-up to 47f5b1a + + Reported-by: bubbleguuum on github + Fixes #12632 + Closes #12633 + +Daniel Stenberg (3 Jan 2024) + +- tool: make parser reject blank arguments if not supported + + Already in the getstr() function that clones the input argument. + + Closes #12620 + +dependabot[bot] (3 Jan 2024) + +- build(deps): bump github/codeql-action from 2 to 3 + + Bumps [github/codeql-action](https://github.com/github/codeql-action) from 2 + to 3. + - [Release notes](https://github.com/github/codeql-action/releases) + - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) + - [Commits](https://github.com/github/codeql-action/compare/v2...v3) + + --- + updated-dependencies: + - dependency-name: github/codeql-action + dependency-type: direct:production + update-type: version-update:semver-major + ... + + Signed-off-by: dependabot[bot] + + Closes #12625 + +- build(deps): bump actions/checkout from 3 to 4 + + Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4. + - [Release notes](https://github.com/actions/checkout/releases) + - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) + - [Commits](https://github.com/actions/checkout/compare/v3...v4) + + --- + updated-dependencies: + - dependency-name: actions/checkout + dependency-type: direct:production + update-type: version-update:semver-major + ... + + Signed-off-by: dependabot[bot] + + Closes #12624 + +- build(deps): bump actions/upload-artifact from 3 to 4 + + Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) f + rom 3 to 4. + - [Release notes](https://github.com/actions/upload-artifact/releases) + - [Commits](https://github.com/actions/upload-artifact/compare/v3...v4) + + --- + updated-dependencies: + - dependency-name: actions/upload-artifact + dependency-type: direct:production + update-type: version-update:semver-major + ... + + Signed-off-by: dependabot[bot] + + Closes #12627 + +- build(deps): bump actions/download-artifact from 3 to 4 + + Bumps [actions/download-artifact](https://github.com/actions/download-artifac + t) from 3 to 4. + - [Release notes](https://github.com/actions/download-artifact/releases) + - [Commits](https://github.com/actions/download-artifact/compare/v3...v4) + + --- + updated-dependencies: + - dependency-name: actions/download-artifact + dependency-type: direct:production + update-type: version-update:semver-major + ... + + Signed-off-by: dependabot[bot] + + Closes #12626 + +Stefan Eissing (3 Jan 2024) + +- http3/quiche: fix result code on a stream reset + + - fixes pytest failures in test 07_22 + - aligns CURLcode values on stream reset with ngtcp2 + + Closes #12629 + +Daniel Stenberg (2 Jan 2024) + +- setopt: clear mimepost when formp is freed + + A precaution to avoid a possibly dangling pointer left behind. + + Reported-by: Thomas Ferguson + Fixes #12608 + Closes #12621 + +Andy Alt (2 Jan 2024) + +- CI: Add dependabot.yml + + This will cause dependabot to open a PR when various actions are + updated, provided that the action maintainer has issued a release. + + Closes #12623 + +Gisle Vanem (2 Jan 2024) + +- content_encoding: change return code to typedef'ed enum + + ... to work around a clang ubsan warning. + + Fixes #12618 + Closes #12622 + +Daniel Stenberg (2 Jan 2024) + +- tool: prepend output_dir in header callback + + When Content-Disposition parsing is used and an output dir is prepended, + make sure to store that new file name correctly so that it can be used + for setting the file timestamp when --remote-time is used. + + Extended test 3012 to verify. + + Co-Authored-by: Jay Satiro + Reported-by: hgdagon on github + Fixes #12614 + Closes #12617 + +- test1254: fix typo in name plus shorten it + +- RELEASE-NOTES: synced + +Viktor Szakats (2 Jan 2024) + +- schannel: fix `-Warith-conversion` gcc 13 warning + + ``` + lib/vtls/schannel.c:1201:22: warning: conversion to 'unsigned int' from 'int' + may change the sign of the result [-Warith-conversion] + 1201 | *extension_len = *list_len + + | ^ + ``` + + Closes #12616 + +- asyn-thread: silence `-Wcast-align` warning for Windows + + Seen with llvm/clang 17: + ``` + lib/asyn-thread.c:310:5: warning: cast from 'PCHAR' (aka 'char *') to 'struct + thread_sync_data *' increases required alignment from 1 to 8 [-Wcast-align] + 310 | CONTAINING_RECORD(overlapped, struct thread_sync_data, w8.overlap + ped); + | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~ + .../llvm-mingw/aarch64-w64-mingw32/include/winnt.h:717:48: note: expanded fro + m macro 'CONTAINING_RECORD' + 717 | #define CONTAINING_RECORD(address,type,field) ((type *)((PCHAR)(addre + ss) - (ULONG_PTR)(&((type *)0)->field))) + | ^~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ``` + + Follow-up to a6bbc87f9e9ffb46a1801dfb983e7534825ed56b #12482 + + Ref: https://github.com/curl/curl/pull/12482#issuecomment-1873017261 + Closes #12615 + +Daniel Stenberg (2 Jan 2024) + +- tool_listhelp: regenerate after recent .d updates + + Makes it survive test 1478 + + Closes #12612 + +- test1478: verify src/tool_listhelp.c + + Verify that the source file on disk is identical to the output of gen.pl + listhelp, as otherwise they are out of sync and need attention. + + Closes #12612 + +- testutil: make runtests support %include + + Using this instruction, a test case can include the contents of a file + into the test during the preprocessing. + + Closes #12612 + +- runtests: for mode="text" on , fix newlines on both parts + + Closes #12612 + +Jay Satiro (2 Jan 2024) + +- quiche: return CURLE_HTTP3 on send to invalid stream + + Prior to this change if a send failed on a stream in an invalid state + (according to quiche) and not marked as closed (according to libcurl) + then the send function would return CURLE_SEND_ERROR. + + We already have similar code for ngtcp2 to return CURLE_HTTP3 in this + case. + + Caught by test test_07_upload.py: test_07_22_upload_parallel_fail. + + Fixes https://github.com/curl/curl/issues/12590 + Closes https://github.com/curl/curl/pull/12597 + +Daniel Stenberg (1 Jan 2024) + +- cmdline-opts: update availability for the *-ca-native options + + Closes #12613 + +Patrick Monnerat (31 Dec 2023) + +- openldap: fix STARTTLS + + It was not working anymore since introduction of connection filters. + + Also do not attempt to recover from a failing TLS negotiation with + CURLUSESSL_TRY. + + Closes #12610 + +Daniel Stenberg (31 Dec 2023) + +- haproxy-clientip.d: document the arg + + The arg keyword was missing and therefore not present in the man page. + + Closes #12611 + +annalee (29 Dec 2023) + +- configure: fix no default int compile error in ipv6 detection + + Closes #12607 + +Dan Fandrich (28 Dec 2023) + +- CI: Fix use of any-glob-to-all-files in the labeler + + Despite its name, this atom acts like one-glob-to-all-files and a + different syntax with braces must be used to get + any-glob-to-all-files semantics. Unfortunately, this makes the file + completely unreadable. + + Ref: https://github.com/actions/labeler/issues/731 + +Daniel Stenberg (29 Dec 2023) + +- CURLOPT_AUTOREFERER.3: mention CURLINFO_REFERER + +- CURLINFO_REFERER.3: clarify that it is the *request* header + + That libcurl itself sent in the most recent request + + Closes #12605 + +Jay Satiro (28 Dec 2023) + +- system_win32: fix a function pointer assignment warning + + - Use CURLX_FUNCTION_CAST to suppress a function pointer assignment + warning. + + a6bbc87f added lookups of some Windows API functions and then cast them + like `*(FARPROC*)&Curl_funcname = address`. Some versions of gcc warn + about that as breaking strict-aliasing rules so this PR changes those + assignments to use CURLX_FUNCTION_CAST. + + Bug: https://github.com/curl/curl/pull/12581#issuecomment-1869804317 + Reported-by: Marcel Raad + + Closes https://github.com/curl/curl/pull/12602 + +- verify-examples.pl: fail verification on unescaped backslash + + - Check that all backslashes in EXAMPLE are properly escaped. + + eg manpage must always use `\\n` never `\n`. + + This is because the manpage requires we always double blackslash to show + a single backslash. Prior to this change an erroneous single backslash + would pass through and compile even though it would not show correctly + in the manpage. + + Co-authored-by: Daniel Stenberg + + Ref: https://github.com/curl/curl/pull/12588 + + Closes https://github.com/curl/curl/pull/12589 + +- vtls: fix missing multissl version info + + - Fix erroneous buffer copy logic from ff74cef5. + + Prior to this change the MultiSSL version info returned to the user + was empty. + + Closes https://github.com/curl/curl/pull/12599 + +Daniel Stenberg (27 Dec 2023) + +- KNOWN_BUGS: [RTSP] Some methods do not support response bodies + + Closes #12414 + +Patrick Monnerat (27 Dec 2023) + +- openldap: fix an LDAP crash + + Reported-by: Ozan Cansel + Fixes #12593 + Closes #12600 + +Daniel Stenberg (27 Dec 2023) + +- getinfo: CURLINFO_QUEUE_TIME_T + + Returns the time, in microseconds, during which this transfer was held + in a waiting queue before it started "for real". A transfer might be put + in a queue if after getting started, it cannot create a new connection + etc due to set conditions and limits imposed by the application. + + Ref: #12293 + Closes #12368 + +- RELEASE-NOTES: synced + +Jay Satiro (26 Dec 2023) + +- examples/sendrecv: fix comment line length + + Caught by checksrc. + +Haydar Alaidrus (23 Dec 2023) + +- CURLOPT_POSTFIELDS.3: fix incorrect C string escape in example + + - Escape inner quotes with two backslashes. + + Two backslashes escapes the backslash for the man page and will show as + a single backslash. + + eg: "{\\"name\\": \\"daniel\\"}" shows as "{\"name\": \"daniel\"}". + + Closes https://github.com/curl/curl/pull/12588 + +Viktor Szakats (23 Dec 2023) + +- appveyor: tidy-ups + + - replace two remaining backslashes with forward slashes. + - tidy up the way we form and pass `TFLAGS`. + + Follow-up to 2d4d0c1fd32f5cc3f946c407c8eccd5477b287df #12572 + + Closes #12582 + +Stefan Eissing (22 Dec 2023) + +- transfer: fix upload rate limiting, add test cases + + - add test cases for rate limiting uploads for all + http versions + - fix transfer loop handling of limits. Signal a re-receive + attempt only on exhausting maxloops without an EAGAIN + - fix `data->state.selectbits` forcing re-receive to also + set re-sending when transfer is doing this. + + Reported-by: Karthikdasari0423 on github + Fixes #12559 + Closes #12586 + +Daniel Stenberg (22 Dec 2023) + +- mbedtls: free the entropy when threaded + + The entropy_free was never done for threaded builds, causing a small + (fixed) memory leak. + + Reported-by: RevaliQaQ on github + Fixes #12584 + Closes #12585 + +Stefan Eissing (22 Dec 2023) + +- http2: improved on_stream_close/data_done handling + + - there seems to be a code path that cleans up easy handles without + triggering DONE or DETACH events to the connection filters. This + would explain wh nghttp2 still holds stream user data + - add GOOD check to easy handle used in on_close_callback to + prevent crashes, ASSERTs in debug builds. + - NULL the stream user data early before submitting RST + - add checks in on_stream_close() to identify UNGOOD easy handles + + Reported-by: Hans-Christian Egtvedt + Fixes #10936 + Closes #12562 + +Daniel Stenberg (22 Dec 2023) + +- mprintf: overhaul and bugfixes + + In a test case using lots of snprintf() calls using many commonly used + %-codes per call, this version is around 30% faster than previous + version. + + It also fixes the #12561 bug which made it not behave correctly when + given unknown %-sequences. Fixing that flaw required a different take on + the problem, which resulted in the new two-arrays model. + + lib557: extended - Verify the #12561 fix and test more printf features + + unit1398: fix test: It used a $ only for one argument, which is not + supported. + + Fixes #12561 + Closes #12563 + +Viktor Szakats (21 Dec 2023) + +- appveyor: replace PowerShell with bash + parallel autotools + + PowerShell works (after a steep development curve), but one property of + it stuck and kept causing unresolvable usability issues: With + `$ErrorActionPreference=Stop`, it does abort on failures, but shows only + the first line of the error message. In `Continue` mode, it shows the + full error message, but doesn't stop on all errors. Another issue is + PowerShell considering any stderr output as if the command failed (this + has been improved in 7.2 (2021-Nov), but fixed versions aren't running + in CI and will not be for a long time in all test images.) + + Thus, we're going with bash. + + Also: + - use `-j2` with autotools tests, making them finish 5-15 minutes per + job faster. + - omit `POSIX_PATH_PREFIX`. + - use `WINDIR`. + - prefer forward slashes. + + Follow-up to: 75078a415d9c769419aed4153d3d525a8eba95af #11999 + Ref: #12444 + + Fixes #12560 + Closes #12572 + +Pavel Pavlov (21 Dec 2023) + +- asyn-thread: use GetAddrInfoExW on >= Windows 8 + + For doing async DNS resolution instead of starting a thread for each + request. + + Fixes #12481 + Closes #12482 + +Daniel Stenberg (21 Dec 2023) + +- strerror: repair get_winsock_error() + + It would try to read longer than the provided string and crash. + + Follow-up to ff74cef5d4a0cf60106517a1c7384 + Reported-by: calvin2021y on github + Fixes #12578 + Closes #12579 + +- CURLOPT_SSH_*_KEYFILE: clarify + + Closes #12554 + +ivanfywang (21 Dec 2023) + +- ngtcp2: put h3 at the front of alpn + + Closes #12576 + +Daniel Stenberg (21 Dec 2023) + +- test460: verify a command line using --expand with no argument + + This verifies the fix for #12565 + +- tool_getparam: do not try to expand without an argument + + This would lead to a segfault. + + Fixes #12565 + Reported-by: Geeknik Labs + Closes #12575 + +- RELEASE-NOTES: synced + + Bumped version to 8.6.0 because of changes + +- Makefile.am: fix the MSVC project generation + + It made the vcxproj files not get included in dist tarballs. + + Regression since 74423b5df4c8117891eb89 (8.5.0) + + Reported-by: iAroc on github + Fixes #12564 + Closes #12567 + +zengwei2000 (21 Dec 2023) + +- altsvc: free 'as' when returning error + + Closes #12570 + + Signed-off-by: zengwei + +Viktor Szakats (20 Dec 2023) + +- build: fix `-Wconversion`/`-Wsign-conversion` warnings + + Fix remaining warnings in examples and tests which are not suppressed + by the pragma in `lib/curl_setup.h`. + + Silence a toolchain issue causing warnings in `FD_SET()` calls with + older Cygwin/MSYS2 builds. Likely fixed on 2020-08-03 by: + https://cygwin.com/git/?p=newlib-cygwin.git;a=commitdiff;h=5717262b8ecfed0f7f + ab63e2c09c78991e36f9dd + + Follow-up to 2dbe75bd7f3c36837aa06fd87a442bdf3fb7faef #12492 + + Closes #12557 + +- build: fix some `-Wsign-conversion`/`-Warith-conversion` warnings + + - enable `-Wsign-conversion` warnings, but also setting them to not + raise errors. + - fix `-Warith-conversion` warnings seen in CI. + These are triggered by `-Wsign-converion` and causing errors unless + explicitly silenced. It makes more sense to fix them, there just a few + of them. + - fix some `-Wsign-conversion` warnings. + - hide `-Wsign-conversion` warnings with a `#pragma`. + - add macro `CURL_WARN_SIGN_CONVERSION` to unhide them on a per-build + basis. + - update a CI job to unhide them with the above macro: + https://github.com/curl/curl/actions/workflows/linux.yml -> OpenSSL -O3 + + Closes #12492 + +- cmake: tidy-up `OtherTests.cmake` + + - make more obvious which detection uses which prep steps. + - merge and streamline conditions. + - these should not alter detection results. + + Also align log output messages from + `Macros.cmake` / `curl_internal_test` with rest of the build. + + Closes #12551 + +- appveyor: switch to out-of-tree builds + + With cmake and autotools. + + Closes #12550 + +Daniel Stenberg (19 Dec 2023) + +- DEPRECATE.md: mention that NTLM_WB no longer works + + Ref: #12479 + Closes #12553 + +- CURLOPT_SERVER_RESPONSE_TIMEOUT_MS: add + + Proposed-by: Yifei Kong + Ref: https://curl.se/mail/lib-2023-11/0023.html + Closes #12369 + +Viktor Szakats (18 Dec 2023) + +- build: more `-Wformat` fixes + + - memdebug: update to not trigger `-Wformat-nonliteral` warnings. + - imap: mark `imap_sendf()` with `CURL_PRINTF()`. + - tool_msgs: mark static function with `CURL_PRINTF()`. + + Follow-up to 3829759bd042c03225ae862062560f568ba1a231 #12489 + + Closes #12540 + +- windows: delete redundant headers + + `winsock2.h` pulls in `windows.h`. `ws2tcpip.h` pulls in `winsock2.h`. + `winsock2.h` and `ws2tcpip.h` are also pulled by `curl/curl.h`. + + Keep only those headers that are not already included, or the code under + it uses something from that specific header. + + Closes #12539 + +- cmake: prefill/cache `HAVE_STRUCT_SOCKADDR_STORAGE` + + Also add missing include to `OtherTests.cmake`. It didn't cause an issue + because the parent already included this earlier by chance. + + Closes #12537 + +Daniel Stenberg (18 Dec 2023) + +- runner.pm: fix perl warning when running tests + + Use of uninitialized value $runner::gdbthis in numeric eq (==) at runner. + pm + + Follow-up from 3dcf301752a09d9 + + Closes #12549 + +- runtests: support -gl. Like -g but for lldb. + + Follow-up to 63b5748 + + Invokes the test case via lldb instead of gdb. Since using gdb is such a + pain on mac, using lldb is sometimes less quirky. + + Closes #12547 + +- curl.h: add CURLE_TOO_LARGE + + A new error code to be used when an internal field grows too large, like + when a dynbuf reaches its maximum. Previously it would return + CURLE_OUT_OF_MEMORY for this, which is highly misleading. + + Ref: #12268 + Closes #12269 + +- CI/circleci: disable MQTT in the HTTP-only build + + And remove the use of configure options that don't actually exist + + Closes #12546 + +Yedaya Katsman (18 Dec 2023) + +- tests: respect $TMPDIR when creating unix domain sockets + + When running on termux, where $TMPDIR isn't /tmp, running the tests + failed, since the server config tried creating sockets in /tmp, without + checking the temp dir config. Use the TMPDIR variable that makes it find + the correct directory everywhere [0] + + [0] https://perldoc.perl.org/File::Temp#tempfile + + Closes #12545 + +Viktor Szakats (17 Dec 2023) + +- ssh: fix namespace of two local macros + + Avoid using the libssh and libssh2 macro namespaces by prefixing + these local macro names with `CURL_`. + + Follow-up to 413a0fedd02c8c6df1d294534b8c6e306fcca7a2 #12346 + + Reviewed-by: Daniel Stenberg + Closes #12544 + +- cmake: whitespace tidy-up in `OtherTests.cmake` + + Closes #12538 + +Mark Sinkovics (16 Dec 2023) + +- cmake: fix generation for system name iOS + + This PR fixes a problem that happens during CMake configuration when + the `CMAKE_SYSTEM_NAME` set to `iOS` and not `Darwin`. This value is + available (as far as I remember) version 3.14. The final solution + (thanks to @vszakats) is to use `APPLE` which contains all the Apple + platforms https://cmake.org/cmake/help/latest/variable/APPLE.html. + + This issue was found when during vcpkg installation. Running command + `vcpkg install curl:arm64-ios` and `vcpkg install curl:x64-ios` failed + with message: + ``` + CMake Error: try_run() invoked in cross-compiling mode, please set the follow + ing cache variables appropriately: + HAVE_H_ERRNO_ASSIGNABLE_EXITCODE (advanced) + ``` + After this fix, I was able to compile the compile the binary without + any issue. + + In addition to that fix, this PR also contains an simplification to + check if the platform is not APPLE. + + Co-authored-by: Viktor Szakats + Closes #12515 + +Daniel Stenberg (16 Dec 2023) + +- RELEASE-NOTES: synced + +Baruch Siach (16 Dec 2023) + +- gnutls: fix build with --disable-verbose + + infof() parameters must be defined event with --disable-verbose since + commit dac293cfb702 ("lib: apache style infof and trace + macros/functions"). + + Move also 'ptr' definition under !CURL_DISABLE_VERBOSE_STRINGS. + + Fixes the following build failure: + + In file included from ../lib/sendf.h:29, + from vtls/gtls.c:44: + vtls/gtls.c: In function 'Curl_gtls_verifyserver': + vtls/gtls.c:841:34: error: 'version' undeclared (first use in this function); + did you mean 'session'? + 841 | gnutls_protocol_get_name(version), ptr); + | ^~~~~~~ + + Closes #12505 + +Viktor Szakats (16 Dec 2023) + +- build: delete unused `HAVE_{GSSHEIMDAL,GSSMIT,HEIMDAL}` + + Stop setting `HAVE_GSSHEIMDAL`, `HAVE_GSSMIT` and `HAVE_HEIMDAL`. + There was no place in the build system or source code that used them. + + Reviewed-by: Daniel Stenberg + Closes #12506 + +- build: remove redundant `CURL_PULL_*` settings + + These macros were not propagated to the source code from CMake. + + autotools set only one of them (`CURL_PULL_SYS_POLL_H`), initially to + address an AIX issue [1]. This later broke when introducing `system.h` + [2] without the logic it enabled. A subsequent fix [3] re-added the + logic, and also enabled it for AIX before its use, directly in + `system.h`. + + [1] 2012-11-23: 665adcd4b7bcdb7deb638cdc499fbe71f8d777f2 + [2] 2017-03-29: 9506d01ee50d5908138ebad0fd9fbd39b66bd64d #1373 + [3] 2017-08-25: 8a84fcc4b59e8b78d2acc6febf44a43d6bc81b59 #1828 #1833 + + Reviewed-by: Daniel Stenberg + Closes #12502 + +- system.h: sync mingw `CURL_TYPEOF_CURL_SOCKLEN_T` with other compilers + + Align mingw with the other Windows compilers and use the `int` type for + `CURL_TYPEOF_CURL_SOCKLEN_T` (and thus for `curl_socklent_t`). This + makes it unnecessary to make a mingw-specific trick and pull all Windows + headers early just for this type definition. This type is specific to + Windows, not to the compiler. mingw-w64's Windows header maps it to + `int` too. + + With this we also delete all remaining uses of `CURL_PULL_WS2TCPIP_H`. + + [ The official solution is to use `socklen_t` for all Windows compilers. + In this case we may want to update `curl/curl.h` to pull in Windows + headers before `system.h`. ] + + Reviewed-by: Daniel Stenberg + Reviewed-by: Jay Satiro + Closes #12501 + +- windows: simplify detecting and using system headers + + - autotools, cmake: assume that if we detect Windows, `windows.h`, + `winsock2.h` and `ws2tcpip.h` do exist. + - lib: fix 3 outlier `#if` conditions to use `USE_WINSOCK` instead of + looking for `winsock2.h`. + - autotools: merge 3 Windows check methods into one. + - move Watt-32 and lwIP socket support to `setup-win32.h` from + `config-win32.h`. It opens up using these with all build tools. Also + merge logic with Windows Sockets. + - fix to assume Windows sockets with the mingw32ce toolchain. + Follow-up to: 2748c64d605b19fb419ae56810ad8da36487a2d4 + - cmake: delete unused variable `signature_call_conv` since + eb33ccd5332435fa50f1758e5debb869c6942b7f. + - autotools: simplify `CURL_CHECK_WIN32_LARGEFILE` detection. + - examples/externalsocket: fix header order. + - cmake/OtherTests.cmake: delete Windows-specific `_source_epilogue` + that wasn't used anymore. + - cmake/OtherTests.cmake: set `WIN32_LEAN_AND_MEAN` for test + `SIZEOF_STRUCT_SOCKADDR_STORAGE`. + + After this patch curl universally uses `_WIN32` to guard + Windows-specific logic. It guards Windows Sockets-specific logic with + `USE_WINSOCK` (this might need further work). + + Reviewed-by: Jay Satiro + Closes #12495 + +- build: enable missing OpenSSF-recommended warnings, with fixes + + https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening + -Guide-for-C-and-C++.html + as of 2023-11-29 [1]. + + Enable new recommended warnings (except `-Wsign-conversion`): + + - enable `-Wformat=2` for clang (in both cmake and autotools). + - add `CURL_PRINTF()` internal attribute and mark functions accepting + printf arguments with it. This is a copy of existing + `CURL_TEMP_PRINTF()` but using `__printf__` to make it compatible + with redefinting the `printf` symbol: + https://gcc.gnu.org/onlinedocs/gcc-3.0.4/gcc_5.html#SEC94 + - fix `CURL_PRINTF()` and existing `CURL_TEMP_PRINTF()` for + mingw-w64 and enable it on this platform. + - enable `-Wimplicit-fallthrough`. + - enable `-Wtrampolines`. + - add `-Wsign-conversion` commented with a FIXME. + - cmake: enable `-pedantic-errors` the way we do it with autotools. + Follow-up to d5c0351055d5709da8f3e16c91348092fdb481aa #2747 + - lib/curl_trc.h: use `CURL_FORMAT()`, this also fixes it to enable format + checks. Previously it was always disabled due to the internal `printf` + macro. + + Fix them: + + - fix bug where an `set_ipv6_v6only()` call was missed in builds with + `--disable-verbose` / `CURL_DISABLE_VERBOSE_STRINGS=ON`. + - add internal `FALLTHROUGH()` macro. + - replace obsolete fall-through comments with `FALLTHROUGH()`. + - fix fallthrough markups: Delete redundant ones (showing up as + warnings in most cases). Add missing ones. Fix indentation. + - silence `-Wformat-nonliteral` warnings with llvm/clang. + - fix one `-Wformat-nonliteral` warning. + - fix new `-Wformat` and `-Wformat-security` warnings. + - fix `CURL_FORMAT_SOCKET_T` value for mingw-w64. Also move its + definition to `lib/curl_setup.h` allowing use in `tests/server`. + - lib: fix two wrongly passed string arguments in log outputs. + Co-authored-by: Jay Satiro + - fix new `-Wformat` warnings on mingw-w64. + + [1] https://github.com/ossf/wg-best-practices-os-developers/blob/56c0fde3895b + fc55c8a973ef49a2572c507b2ae1/docs/Compiler-Hardening-Guides/Compiler-Options- + Hardening-Guide-for-C-and-C%2B%2B.md + + Closes #12489 + +- Makefile.mk: drop Windows support + + And DLL-support with it. This leaves `Makefile.mk` for MS-DOS and Amiga. + + We recommend CMake instead. With unity mode it's much faster, and about + the same without. + + Ref: https://github.com/curl/curl/pull/12221#issuecomment-1783761806 + Reviewed-by: Daniel Stenberg + Closes #12224 + +Daniel Stenberg (16 Dec 2023) + +- cmdline-docs: use .IP consistently + + Remove use of .TP and some .B. The idea is to reduce nroff syntax as + much as possible and to use it consistently. Ultimately, we should be + able to introduce our own easier-to-use-and-read syntax/formatting and + convert on generation time. + + Closes #12535 + +Tatsuhiko Miyagawa (16 Dec 2023) + +- http: fix off-by-one error in request method length check + + It should allow one more byte. + + Closes #12534 + +Daniel Stenberg (15 Dec 2023) + +- curl: show ipfs and ipns as supported "protocols" + + They are accepted schemes in URLs passed to curl (the tool, not the + library). + + Also makes curl-config show the same list. + + Co-Authored-by: Jay Satiro + Reported-by: Chara White + Bug: https://curl.se/mail/archive-2023-12/0026.html + Closes #12508 + +- Revert "urldata: move async resolver state from easy handle to connectdata" + + This reverts commit 56a4db2e4e2bcb9a0dcb75b83560a78ef231fcc8 (#12198) + + We want the c-ares channel to be held in the easy handle, not per + connection - for performance. + + Closes #12524 + +Viktor Szakats (15 Dec 2023) + +- openssl: re-match LibreSSL deinit with init + + Earlier we switched to use modern initialization with LibreSSL v2.7.0 + and up, but did not touch deinitialization [1]. Fix it in this patch. + + Regression from bec0c5bbf34369920598678161d2df8bea0e243b #11611 + + [1] https://github.com/curl/curl/pull/11611#issuecomment-1668654014 + + Reported-by: Mike Hommey + Reviewed-by: Daniel Stenberg + Fixes #12525 + Closes #12526 + +Daniel Stenberg (14 Dec 2023) + +- libssh: supress warnings without version check + + Define unconditionally. + + Follow-up from d21bd2190c46ad7fa + + Closes #12523 + +- hostip: return error immediately when Curl_ip2addr() fails + + Closes #12522 + +Theo (14 Dec 2023) + +- libssh: improve the deprecation warning dismissal + + Previous code was compiler dependant, and dismissed all deprecation warnings + indiscriminately. + + libssh provides a way to disable the deprecation warnings for libssh only, an + d + naturally this is the preferred way. + + This commit uses that, to prevent the erroneous hiding of potential, unrelate + d + deprecation warnings. + + Fixes #12519 + Closes #12520 + +Daniel Stenberg (14 Dec 2023) + +- test1474: removed + + The test was already somewhat flaky and disabled on several platforms, + and after 1da640abb688 even more unstable. + +- readwrite_data: loop less + + This function is made to loop in order to drain incoming data + faster. Completely removing the loop has a measerably negative impact on + transfer speeds. + + Downsides with the looping include + + - it might call the progress callback much more seldom. Especially if + the write callback is slow. + + - rate limiting becomes less exact + + - a single transfer might "starve out" other parallel transfers + + - QUIC timers for other connections can't be maintained correctly + + The long term fix should be to remove the loop and optimize coming back + to avoid the transfer speed penalty. + + This fix lower the max loop count to reduce the starvation problem, and + avoids the loop completely for when rate-limiting is in progress. + + Ref: #12488 + Ref: https://curl.se/mail/lib-2023-12/0012.html + Closes #12504 + +Stefan Eissing (14 Dec 2023) + +- lib: eliminate `conn->cselect_bits` + + - use `data->state.dselect_bits` everywhere instead + - remove `bool *comeback` parameter as non-zero + `data->state.dselect_bits` will indicate that IO is + incomplete. + + Closes #12512 + +- connect: refactor `Curl_timeleft()` + + - less local vars, "better" readability + - added documentation + + Closes #12518 + +Dmitry Karpov (14 Dec 2023) + +- cookie: avoid fopen with empty file name + + Closes #12514 + +Viktor Szakats (13 Dec 2023) + +- tests/server: delete workaround for old-mingw + + mingw-w64 1.0 comes with w32api v3.12, thus doesn't need this. + + Follow-up to 38029101e2d78ba125732b3bab6ec267b80a0e72 #11625 + + Reviewed-by: Jay Satiro + Closes #12510 + +- cmake: delete obsolete TODOs more [ci skip] + + - manual completed: 898b012a9bf388590c4be7f526815b5ab74feca1 #1288 + - soname completed: 5de6848f104d7cb0017080e31216265ac19d0dde #10023 + - bunch of others that are completed + - `NTLM_WB_ENABLED` is implemented in a basic form, and now also + scheduled for removal, so a TODO at this point isn't useful. + + And this 'to-check' item: + + Q: "The cmake build selected to run gcc with -fPIC on my box while the + plain configure script did not." + + A: With CMake, since 2ebc74c36a19a1700af394c16855ce144d9878e3 #11546 + and fc9bfb14520712672b4784e8b48256fb29204011 #11627, we explicitly + enable PIC for libcurl shared lib. Or when building libcurl for + shared and static lib in a single pass. We do this by default for + Windows or when enabled by the user via `SHARE_LIB_OBJECT`. + Otherwise we don't touch this setting. Meaning the default set by + CMake (if any) or the toolchain is used. On Debian Bookworm, this + means that PIC is disabled for static libs by default. Some platforms + (like macOS), has PIC enabled by default. + autotools supports the double-pass mode only, and in that case + CMake seems to match PIC behaviour now (as tested on Linux with gcc.) + + Follow-up to 5d5dfdbd1a6c40bd75e982b66f49e1fa3a7eeae7 #12500 + + Reviewed-by: Jay Satiro + Closes #12509 + +Stefan Eissing (12 Dec 2023) + +- CLIENT-WRITERS: design and use documentation + + Closes #12507 + +Viktor Szakats (12 Dec 2023) + +- cmake: delete obsolete TODO items [ci skip] + + There is always room for improvement, but CMake is up to par now with + autotools, so there is no longer a good reason to keep around these + inline TODO items. + + Answering one of questions: + + Q: "The gcc command line use neither -g nor any -O options. As a + developer, I also treasure our configure scripts's --enable-debug + option that sets a long range of "picky" compiler options." + + A: CMake offers the `CMAKE_BUILD_TYPE` variable to control debug info + and optimization level. E.g.: + - `Release` = `-O3` + no debug info + - `MinSizeRel` = `-Os` + no debug info + - `Debug` = `-O0` + debug info + + https://stackoverflow.com/questions/48754619/what-are-cmake-build-type-deb + ug-release-relwithdebinfo-and-minsizerel/59314670#59314670 + https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html#defaul + t-and-custom-configurations + + For picky warnings we have the `PICKY_COMPILER` options, enabled by + default. + + Closes #12500 + +Stefan Eissing (11 Dec 2023) + +- CONNECTION-FILTERS: update documentation + + Closes #12497 + +Daniel Stenberg (11 Dec 2023) + +- lib: reduce use of strncpy + + - bearssl: select cipher without buffer copies + - http_aws_sigv4: avoid strncpy, require exact timestamp length + - http_aws_sigv4: use memcpy isntead of strncpy + - openssl: avoid strncpy calls + - schannel: check for 1.3 algos without buffer copies + - strerror: avoid strncpy calls + - telnet: avoid strncpy, return error on too long inputs + - vtls: avoid strncpy in multissl_version() + + Closes #12499 + +- CI/distcheck: run full tests + + To be able to detect missing files better, this now runs the full CI + test suite. If done before, it would have detected #12462 before + release. + + Closes #12503 + +- docs: clean up Protocols: for cmdline options + + ... and some other minor polish. + + Closes #12496 + +- cmdline/gen: fix the sorting of the man page options + + They were previously sorted based on the file names, which use a .d + extension, making "data" get placed after "data-binary" etc. Making the + sort ignore the extention fixes the ordering. + + Reported-by: Boris Verkhovskiy + Bug: https://curl.se/mail/archive-2023-12/0014.html + Closes #12494 + +Daniel Gustafsson (9 Dec 2023) + +- doh: remove unused local variable + + The nurl variable is no longer used during probing following + a refactoring, so remove. + + Closes #12491 + +Jay Satiro (8 Dec 2023) + +- build: fix Windows ADDRESS_FAMILY detection + + - Include winsock2.h for Windows ADDRESS_FAMILY detection. + + Prior to this change cmake detection didn't work because it included + ws2def.h by itself, which is missing needed types from winsock2.h. + + Prior to this change autotools detection didn't work because it did not + include any Windows header. + + In both cases libcurl would fall back on unsigned short as the address + family type, which is the same as ADDRESS_FAMILY. + + Co-authored-by: Viktor Szakats + + Closes https://github.com/curl/curl/pull/12441 + +Daniel Stenberg (8 Dec 2023) + +- lib: rename Curl_strndup to Curl_memdup0 to avoid misunderstanding + + Since the copy does not stop at a null byte, let's not call it anything + that makes you think it works like the common strndup() function. + + Based on feedback from Jay Satiro, Stefan Eissing and Patrick Monnerat + + Closes #12490 + +- convsrctest.pl: removed: not used, not shipped in tarballs + +- tests: rename tests scripts to the test number + + It is hard to name the scripts sensibly. Lots of them are similarly + named and the name did not tell which test that used them. + + The new approach is rather to name them based on the test number that + runs them. Also helps us see which scripts are for individual tests + rather than for general test infra. + + - badsymbols.pl -> test1167.pl + - check-deprecated.pl -> test1222.pl + - check-translatable-options.pl -> test1544.pl + - disable-scan.pl -> test1165.pl + - error-codes.pl -> test1175.pl + - errorcodes.pl -> test1477.pl + - extern-scan.pl -> test1135.pl + - manpage-scan.pl -> test1139.pl + - manpage-syntax.pl -> test1173.pl + - markdown-uppercase.pl -> test1275.pl + - mem-include-scan.pl -> test1132.pl + - nroff-scan.pl -> test1140.pl + - option-check.pl -> test1276.pl + - options-scan.pl -> test971.pl + - symbol-scan.pl -> test1119.pl + - version-scan.pl -> test1177.pl + + Closes #12487 + +MichaÅ‚ Antoniak (8 Dec 2023) + +- sendf: fix compiler warning with CURL_DISABLE_HEADERS_API + + fix MSVC warning C4189: 'htype': local variable is initialized but not + referenced - when CURL_DISABLE_HEADERS_API is defined. + + Closes #12485 + +Viktor Szakats (8 Dec 2023) + +- tidy-up: whitespace + + Closes #12484 + +Stefan Eissing (7 Dec 2023) + +- test_02_download: fix paramters to test_02_27 + + - it is a special client that only ever uses http/2 + + Closes #12467 + +MichaÅ‚ Antoniak (7 Dec 2023) + +- vtls: remove the Curl_cft_ssl_proxy object if CURL_DISABLE_PROXY + + Closes #12459 + +Daniel Stenberg (7 Dec 2023) + +- lib: strndup/memdup instead of malloc, memcpy and null-terminate + + - bufref: use strndup + - cookie: use strndup + - formdata: use strndup + - ftp: use strndup + - gtls: use aprintf instead of malloc + strcpy * 2 + - http: use strndup + - mbedtls: use strndup + - md4: use memdup + - ntlm: use memdup + - ntlm_sspi: use strndup + - pingpong: use memdup + - rtsp: use strndup instead of malloc, memcpy and null-terminate + - sectransp: use strndup + - socks_gssapi.c: use memdup + - vtls: use dynbuf instead of malloc, snprintf and memcpy + - vtls: use strdup instead of malloc + memcpy + - wolfssh: use strndup + + Closes #12453 + +- strdup: remove the memchr check from Curl_strndup + + It makes it possible to clone a binary chunk of data. + + Closes #12453 + +- ftp: handle the PORT parsing without allocation + + Also reduces amount of *cpy() calls. + + Closes #12456 + +- RELEASE-NOTES: synced + + Bumped to 8.5.1 + +- url: for disabled protocols, mention if found in redirect + + To help users better understand where the URL (and denied scheme) comes + from. Also removed "in libcurl" from the message, since the disabling + can be done by the application. + + The error message now says "not supported" or "disabled" depending on + why it was denied: + + Protocol "hej" not supported + Protocol "http" disabled + + And in redirects: + + Protocol "hej" not supported (in redirect) + Protocol "http" disabled (in redirect) + + Reported-by: Mauricio Scheffer + Fixes #12465 + Closes #12469 + +Stefan Eissing (6 Dec 2023) + +- sectransp_ make TLSCipherNameForNumber() available in non-verbose config + + Reported-by: Cajus Pollmeier + Closes #12476 + Fixes #12474 + +YX Hao (6 Dec 2023) + +- lib: fix variable undeclared error caused by `infof` changes + + `--disable-verbose` yields `CURL_DISABLE_VERBOSE_STRINGS` defined. + `infof` isn't `Curl_nop_stmt` anymore: dac293c. + + Follow-up to dac293c + + Closes #12470 + +Viktor Szakats (6 Dec 2023) + +- tidy-up: fix yamllint whitespace issues in labeler.yml + + Follow-up to bda212911457c6fadfbba50be61afc4ca513fa56 #12466 + + Reviewed-by: Dan Fandrich + Closes #12475 + +- tidy-up: fix yamllint whitespace issues + + Closes #12466 + +Chris Sauer (6 Dec 2023) + +- cmake: fix typo + + Follow-up to aace27b + Closes #12464 + +Daniel Stenberg (6 Dec 2023) + +- dist: add tests/errorcodes.pl to the tarball + + Used by test 1477 + + Reported-by: Xi Ruoyao + Follow-up to 0ca3a4ec9a7 + Fixes #12462 + Closes #12463 + +Dan Fandrich (6 Dec 2023) + +- github/labeler: update a missed key in the v5 upgrade + + Follow-up to ce03fe3ba + +Version 8.5.0 (6 Dec 2023) + +Daniel Stenberg (6 Dec 2023) + +- RELEASE-NOTES: synced + + The curl 8.5.0 release. + +Dan Fandrich (5 Dec 2023) + +- github/labeler: switch from the beta to labeler v5 + + Some keys were renamed and the dot option was made default. + + Closes #12458 + +Daniel Stenberg (5 Dec 2023) + +- DEPRECATE: remove NTLM_WB in June 2024 + + Ref: https://curl.se/mail/lib-2023-12/0010.html + + Closes #12451 + +Jacob Hoffman-Andrews (4 Dec 2023) + +- rustls: implement connect_blocking + + Closes #11647 + +Daniel Stenberg (4 Dec 2023) + +- examples/rtsp-options.c: add + + Just a bare bones RTSP example using CURLOPT_RTSP_SESSION_ID and + CURLOPT_RTSP_REQUEST set to CURL_RTSPREQ_OPTIONS. + + Closes #12452 + +Stefan Eissing (4 Dec 2023) + +- ngtcp2: ignore errors on unknown streams + + - expecially in is_alive checks on connections, we might + see incoming packets on streams already forgotten and closed, + leading to errors reported by nghttp3. Ignore those. + + Closes #12449 + +Daniel Stenberg (4 Dec 2023) + +- docs: make all examples in all libcurl man pages compile + + Closes #12448 + +- checksrc.pl: support #line instructions + + makes it identify the correct source file and line + +- GHA/man-examples: verify libcurl man page examples + +- verify-examples.pl: verify that all man page examples compile clean + +- RELEASE-NOTES: synced + +Graham Campbell (2 Dec 2023) + +- http3: bump ngtcp2 and nghttp3 versions + + nghttp3 v1.1.0 + ngtcp2 v1.1.0 + + In docs and CI + + Closes #12446 + +- CI/quiche: use `3.1.4+quic` consistently in CI workflows + + Closes #12447 + +Viktor Szakats (2 Dec 2023) + +- test1545: disable deprecation warnings + + Fixes: + https://ci.appveyor.com/project/curlorg/curl/builds/48631551/job/bhx74e0i66yr + p6pk#L1205 + + Same with details: + https://ci.appveyor.com/project/curlorg/curl/builds/48662893/job/ol8a78q9gmil + b6wt#L1263 + ``` + tests/libtest/lib1545.c:38:3: error: 'curl_formadd' is deprecated: since 7.56 + .0. Use curl_mime_init() [-Werror=deprecated-declarations] + 38 | curl_formadd(&m_formpost, &lastptr, CURLFORM_COPYNAME, "file", + | ^~~~~~~~~~~~ + [...] + ``` + + Follow-up to 07a3cd83e0456ca17dfd8c3104af7cf45b7a1ff5 #12421 + + Fixes #12445 + Closes #12444 + +Daniel Stenberg (2 Dec 2023) + +- INSTALL: update list of ports and CPU archs + +- symbols-in-versions: the CLOSEPOLICY options are deprecated + + The were used with the CURLOPT_CLOSEPOLICY option, which *never* worked. + +z2_ (1 Dec 2023) + +- build: fix builds that disable protocols but not digest auth + + - Build base64 functions if digest auth is not disabled. + + Prior to this change if some protocols were disabled but not digest auth + then a build error would occur due to missing base64 functions. + + Fixes https://github.com/curl/curl/issues/12440 + Closes https://github.com/curl/curl/pull/12442 + +MichaÅ‚ Antoniak (1 Dec 2023) + +- connect: reduce number of transportation providers + + Use only the ones necessary - the ones that are built-in. Saves a few + bytes in the resulting code. + + Closes #12438 + +David Benjamin (1 Dec 2023) + +- vtls: consistently use typedef names for OpenSSL structs + + The foo_st names don't appear in OpenSSL public API documentation. The + FOO typedefs are more common. This header was already referencing + SSL_CTX via . There is a comment about avoiding + , but OpenSSL actually declares all the typedefs in + , which is already included by (and + every other OpenSSL header), so just use that. Though I've included it + just to be explicit. + + (I'm also fairly sure including already triggers the + Schannel conflicts anyway. The comment was probably just out of date.) + + Closes #12439 + +Lau (1 Dec 2023) + +- libcurl-security.3: fix typo + + Fixed minimal typo. + + Closes #12437 + +Stefan Eissing (1 Dec 2023) + +- ngtcp2: fix races in stream handling + + - fix cases where ngtcp2 invokes callbacks on streams that + nghttp3 has already forgotten. Ignore the NGHTTP3_ERR_STREAM_NOT_FOUND + in these cases as it is normal behaviour. + + Closes #12435 + +Emanuele Torre (1 Dec 2023) + +- tool_writeout_json: fix JSON encoding of non-ascii bytes + + char variables if unspecified can be either signed or unsigned depending + on the platform according to the C standard; in most platforms, they are + signed. + + This meant that the *i<32 waas always true for bytes with the top bit + set. So they were always getting encoded as \uXXXX, and then since they + were also signed negative, they were getting extended with 1s causing + '\xe2' to be expanded to \uffffffe2, for example: + + $ curl --variable 'v=“' --expand-write-out '{{v:json}}\n' file:///dev/nul + l + \uffffffe2\uffffff80\uffffff9c + + I fixed this bug by making the code use explicitly unsigned char* + variables instead of char* variables. + + Test 268 verifies + + Reported-by: iconoclasthero + Closes #12434 + +Stefan Eissing (1 Dec 2023) + +- cf-socket: TCP trace output local address used in connect + + Closes #12427 + +Jay Satiro (1 Dec 2023) + +- CURLINFO_PRETRANSFER_TIME_T.3: fix time explanation + + - Change CURLINFO_PRETRANSFER_TIME_T explanation to say that it + includes protocol-specific instructions that trigger a transfer. + + Prior to this change it explicitly said that it did not include those + instructions in the time, but that is incorrect. + + The change is a copy of the fixed explanation already in + CURLINFO_PRETRANSFER_TIME, fixed by ec8dcd7b. + + Reported-by: eeverettrbx@users.noreply.github.com + + Fixes https://github.com/curl/curl/issues/12431 + Closes https://github.com/curl/curl/pull/12432 + +Daniel Stenberg (30 Nov 2023) + +- multi: during ratelimit multi_getsock should return no sockets + + ... as there is nothing to wait for then, it just waits. Otherwise, this + causes much more CPU work and updates than necessary during ratelimit + periods. + + Ref: https://curl.se/mail/lib-2023-11/0056.html + Closes #12430 + +Dmitry Karpov (30 Nov 2023) + +- transfer: abort pause send when connection is marked for closing + + This handles cases of some bi-directional "upgrade" scenarios + (i.e. WebSockets) where sending is paused until some "upgrade" handshake + is completed, but server rejects the handshake and closes the + connection. + + Closes #12428 + +Daniel Stenberg (28 Nov 2023) + +- RELEASE-NOTES: synced + +- openssl: when a session-ID is reused, skip OCSP stapling + + Fixes #12399 + Reported-by: Alexey Larikov + Closes #12418 + +- test1545: test doing curl_formadd twice with missing file + + Reproduces #12410 + Verifies the fix + Closes #12421 + +- Curl_http_body: cleanup properly when Curl_getformdata errors + + Reported-by: yushicheng7788 on github + Based-on-work-by: yushicheng7788 on github + Fixes #12410 + Closes #12421 + +- test1477: verify that libcurl-errors.3 and public headers are synced + + The script errorcodes.pl extracts all error codes from all headers and + checks that they are all documented, then checks that all documented + error codes are also specified in a header file. + + Closes #12424 + +- libcurl-errors.3: sync with current public headers + + Closes #12424 + +Stefan Eissing (28 Nov 2023) + +- test459: fix for parallel runs + + - change warniing message to work better with varying filename + length. + - adapt test output check to new formatting + + Follow-up to 97ccc4479f77ba3191c6 + Closes #12423 + +Daniel Stenberg (27 Nov 2023) + +- tool_cb_prg: make the carriage return fit for wide progress bars + + When the progress bar was made max width (256 columns), the fly() + function attempted to generate its output buffer too long so that the + trailing carriage return would not fit and then the output would show + wrongly. The fly function is called when the expected total transfer is + unknown, which could be one or more progress calls before the actual + progress meter get shown when the expected transfer size is provided. + + This new take also replaces the msnprintf() call with a much simpler + memset() for speed. + + Reported-by: Tim Hill + Fixes #12407 + Closes #12415 + +- tool_parsecfg: make warning output propose double-quoting + + When the config file parser detects a word that *probably* should be + quoted, mention double-quotes as a possible remedy. + + Test 459 verifies. + + Proposed-by: Jiehong on github + Fixes #12409 + Closes #12412 + +Jay Satiro (26 Nov 2023) + +- curl.rc: switch out the copyright symbol for plain ASCII + + .. like we already do for libcurl.rc. + + libcurl.rc copyright symbol used to cause a "non-ascii 8-bit codepoint" + warning so it was switched to ascii. + + Ref: https://github.com/curl/curl/commit/1ca62bb5#commitcomment-133474972 + + Suggested-by: Robert Southee + + Closes https://github.com/curl/curl/pull/12403 + +Daniel Stenberg (26 Nov 2023) + +- conncache: use the closure handle when disconnecting surplus connections + + Use the closure handle for disconnecting connection cache entries so + that anything that happens during the disconnect is not stored and + associated with the 'data' handle which already just finished a transfer + and it is important that details from the unrelated disconnect does not + taint meta-data in the data handle. + + Like storing the response code. + + This also adjust test 1506. Unfortunately it also removes a key part of + the test that verifies that a connection is closed since when this + output vanishes (because the closure handle is used), we don't know + exactly that the connection actually gets closed in this test... + + Reported-by: ohyeaah on github + Fixes #12367 + Closes #12405 + +- RELEASE-NOTES: synced + +Stefan Eissing (24 Nov 2023) + +- quic: make eyeballers connect retries stop at weird replies + + - when a connect immediately goes into DRAINING state, do + not attempt retries in the QUIC connection filter. Instead, + return CURLE_WEIRD_SERVER_REPLY + - When eyeballing, interpret CURLE_WEIRD_SERVER_REPLY as an + inconclusive answer. When all addresses have been attempted, + rewind the address list once on an inconclusive answer. + - refs #11832 where connects were retried indefinitely until + the overall timeout fired + + Closes #12400 + +Daniel Stenberg (24 Nov 2023) + +- CI: verify libcurl function SYNPOSIS sections + + With the .github/scripits/verify-synopsis.pl script + + Closes #12402 + +- docs/libcurl: SYNSOPSIS cleanup + + - use the correct include file + - make sure they are declared as in the header file + - fix minor nroff syntax mistakes (missing .fi) + + These are verified by verify-synopsis.pl, which extracts the SYNPOSIS + code and runs it through gcc. + + Closes #12402 + +- sendf: fix comment typo + +- fopen: allocate the dir after fopen + + Move the allocation of the directory name down to after the fopen() call + to allow that shortcut code path to avoid a superfluous malloc+free + cycle. + + Follow-up to 73b65e94f35311 + + Closes #12398 + +Stefan Eissing (24 Nov 2023) + +- transfer: cleanup done+excess handling + + - add `SingleRequest->download_done` as indicator that + all download bytes have been received + - remove `stop_reading` bool from readwrite functions + - move excess body handling into client download writer + + Closes #12371 + +Daniel Stenberg (23 Nov 2023) + +- fopen: create new file using old file's mode + + Because the function renames the temp file to the target name as a last + step, if the file was previously owned by a different user, not ORing + the old mode could otherwise end up creating a file that was no longer + readable by the original owner after save. + + Reported-by: Loïc Yhuel + Fixes #12299 + Closes #12395 + +- test1476: require proxy + + Follow-up from 323df4261c3542 + + Closes #12394 + +- fopen: create short(er) temporary file name + + Only using random letters in the name plus a ".tmp" extension. Not by + appending characters to the final file name. + + Reported-by: Maksymilian Arciemowicz + + Closes #12388 + +Stefan Eissing (23 Nov 2023) + +- tests: git ignore generated second-hsts.txt file + + File is generated in test lib1900 + + Follow-up to 7cb03229d9e9c5 + + Closes #12393 + +Viktor Szakats (23 Nov 2023) + +- openssl: enable `infof_certstack` for 1.1 and LibreSSL 3.6 + + Lower the barrier to enable `infof_certstack()` from OpenSSL 3 to + OpenSSL 1.1.x, and LibreSSL 3.6 or upper. + + With the caveat, that "group name" and "type name" are missing from + the log output with these TLS backends. + + Follow-up to b6e6d4ff8f253c8b8055bab9d4d6a10f9be109f3 #12030 + + Reviewed-by: Daniel Stenberg + Closes #12385 + +Daniel Stenberg (23 Nov 2023) + +- urldata: fix typo in comment + +- CI: codespell + + The list of words to ignore is in the file + .github/scripts/codespell-ignore.txt + + Closes #12390 + +- lib: fix comment typos + + Five separate ones, found by codespell + + Closes #12390 + +- test1476: verify cookie PSL mixed case + +- cookie: lowercase the domain names before PSL checks + + Reported-by: Harry Sintonen + + Closes #12387 + +Viktor Szakats (23 Nov 2023) + +- openssl: fix building with v3 `no-deprecated` + add CI test + + - build quictls with `no-deprecated` in CI to have test coverage for + this OpenSSL 3 configuration. + + - don't call `OpenSSL_add_all_algorithms()`, `OpenSSL_add_all_digests()`. + The caller code is meant for OpenSSL 3, while these two functions were + only necessary before OpenSSL 1.1.0. They are missing from OpenSSL 3 + if built with option `no-deprecated`, causing build errors: + ``` + vtls/openssl.c:4097:3: error: call to undeclared function 'OpenSSL_add_all_ + algorithms'; ISO C99 and later do not support implicit function declaration + s [-Wimplicit-function-declaration] + vtls/openssl.c:4098:3: error: call to undeclared function 'OpenSSL_add_all_ + digests'; ISO C99 and later do not support implicit function declarations [ + -Wimplicit-function-declaration] + ``` + Ref: https://ci.appveyor.com/project/curlorg/curl-for-win/builds/48587418?f + ullLog=true#L7667 + + Regression from b6e6d4ff8f253c8b8055bab9d4d6a10f9be109f3 #12030 + Bug: https://github.com/curl/curl/issues/12380#issuecomment-1822944669 + Reviewed-by: Alex Bozarth + + - vquic/curl_ngtcp2: fix using `SSL_get_peer_certificate` with + `no-deprecated` quictls 3 builds. + Do it by moving an existing solution for this from `vtls/openssl.c` + to `vtls/openssl.h` and adjusting caller code. + ``` + vquic/curl_ngtcp2.c:1950:19: error: implicit declaration of function 'SSL_g + et_peer_certificate'; did you mean 'SSL_get1_peer_certificate'? [-Wimplicit + -function-declaration] + ``` + Ref: https://github.com/curl/curl/actions/runs/6960723097/job/18940818625#s + tep:24:1178 + + - curl_ntlm_core: fix `-Wunused-parameter`, `-Wunused-variable` and + `-Wunused-function` when trying to build curl with NTLM enabled but + without the necessary TLS backend (with DES) support. + + Closes #12384 + +- curl.h: delete Symbian OS references + + curl deprecated Symbian OS in 3d64031fa7a80ac4ae3fd09a5939196268b92f81 + via #5989. Delete references to it from public headers, because there + is no fresh release to use those headers with. + + Reviewed-by: Dan Fandrich + Reviewed-by: Jay Satiro + Closes #12378 + +- windows: use built-in `_WIN32` macro to detect Windows + + Windows compilers define `_WIN32` automatically. Windows SDK headers + or build env defines `WIN32`, or we have to take care of it. The + agreement seems to be that `_WIN32` is the preferred practice here. + Make the source code rely on that to detect we're building for Windows. + + Public `curl.h` was using `WIN32`, `__WIN32__` and `CURL_WIN32` for + Windows detection, next to the official `_WIN32`. After this patch it + only uses `_WIN32` for this. Also, make it stop defining `CURL_WIN32`. + + There is a slight chance these break compatibility with Windows + compilers that fail to define `_WIN32`. I'm not aware of any obsolete + or modern compiler affected, but in case there is one, one possible + solution is to define this macro manually. + + grepping for `WIN32` remains useful to discover Windows-specific code. + + Also: + + - extend `checksrc` to ensure we're not using `WIN32` anymore. + + - apply minor formatting here and there. + + - delete unnecessary checks for `!MSDOS` when `_WIN32` is present. + + Co-authored-by: Jay Satiro + Reviewed-by: Daniel Stenberg + + Closes #12376 + +Stefan Eissing (22 Nov 2023) + +- url: ConnectionExists revisited + + - have common pattern of `if not match, continue` + - revert pages long if()s to return early + - move dead connection check to later since it may + be relatively expensive + - check multiuse also when NOT building with NGHTTP2 + - for MULTIUSE bundles, verify that the inspected + connection indeed supports multiplexing when in use + (bundles may contain a mix of connection, afaict) + + Closes #12373 + +Daniel Stenberg (22 Nov 2023) + +- CURLMOPT_MAX_CONCURRENT_STREAMS: make sure the set value is within range + + ... or use the default value. + + Also clarify the documentation language somewhat. + + Closes #12382 + +- urldata: make maxconnects a 32 bit value + + "2^32 idle connections ought to be enough for anybody" + + Closes #12375 + +- FEATURES: update the URL phrasing + + The URL is length limited since a while back so "no limit" simply is not + true anymore. Mention the URL RFC standard used instead. + + Closes #12383 + +- wolfssh: remove redundant static prototypes + + vssh/wolfssh.c:346:18: error: redundant redeclaration of ‘wscp_recv’ [-We + rror=redundant-decls] + + Closes #12381 + +- setopt: remove superfluous use of ternary expressions + + Closes #12374 + +- mime: store "form escape" as a single bit + + Closes #12374 + +- setopt: check CURLOPT_TFTP_BLKSIZE range on set + + ... instead of later when the transfer is about to happen. + + Closes #12374 + +Viktor Szakats (21 Nov 2023) + +- build: add more picky warnings and fix them + + Enable more picky compiler warnings. I've found these options in the + nghttp3 project when implementing the CMake quick picky warning + functionality for it [1]. + + `-Wunused-macros` was too noisy to keep around, but fixed a few issues + it revealed while testing. + + - autotools: reflect the more precisely-versioned clang warnings. + Follow-up to 033f8e2a08eb1d3102f08c4d8c8e85470f8b460e #12324 + - autotools: sync between clang and gcc the way we set `no-multichar`. + - autotools: avoid setting `-Wstrict-aliasing=3` twice. + - autotools: disable `-Wmissing-noreturn` for MSYS gcc targets [2]. + It triggers in libtool-generated stub code. + + - lib/timeval: delete a redundant `!MSDOS` guard from a `WIN32` branch. + + - lib/curl_setup.h: delete duplicate declaration for `fileno`. + Added in initial commit ae1912cb0d494b48d514d937826c9fe83ec96c4d + (1999-12-29). This suggests this may not be needed anymore, but if + it does, we may restore this for those specific (non-Windows) systems. + - lib: delete unused macro `FTP_BUFFER_ALLOCSIZE` since + c1d6fe2aaa5a26e49a69a4f2495b3cc7a24d9394. + - lib: delete unused macro `isxdigit_ascii` since + f65f750742068f579f4ee6d8539ed9d5f0afcb85. + - lib/mqtt: delete unused macro `MQTT_HEADER_LEN`. + - lib/multi: delete unused macro `SH_READ`/`SH_WRITE`. + - lib/hostip: add `noreturn` function attribute via new `CURL_NORETURN` + macro. + - lib/mprintf: delete duplicate declaration for `Curl_dyn_vprintf`. + - lib/rand: fix `-Wunreachable-code` and related fallouts [3]. + - lib/setopt: fix `-Wunreachable-code-break`. + - lib/system_win32 and lib/timeval: fix double declarations for + `Curl_freq` and `Curl_isVistaOrGreater` in CMake UNITY mode [4]. + - lib/warnless: fix double declarations in CMake UNITY mode [5]. + This was due to force-disabling the header guard of `warnless.h` to + to reapply it to source code coming after `warnless.c` in UNITY + builds. This reapplied declarations too, causing the warnings. + Solved by adding a header guard for the lines that actually need + to be reapplied. + - lib/vauth/digest: fix `-Wunreachable-code-break` [6]. + - lib/vssh/libssh2: fix `-Wunreachable-code-break` and delete redundant + block. + - lib/vtls/sectransp: fix `-Wunreachable-code-break` [7]. + - lib/vtls/sectransp: suppress `-Wunreachable-code`. + Detected in `else` branches of dynamic feature checks, with results + known at compile-time, e.g. + ```c + if(SecCertificateCopySubjectSummary) /* -> true */ + ``` + Likely fixable as a separate micro-project, but given SecureTransport + is deprecated anyway, let's just silence these locally. + - src/tool_help: delete duplicate declaration for `helptext`. + - src/tool_xattr: fix `-Wunreachable-code`. + - tests: delete duplicate declaration for `unitfail` [8]. + - tests: delete duplicate declaration for `strncasecompare`. + - tests/libtest: delete duplicate declaration for `gethostname`. + Originally added in 687df5c8c39c370a59999b9afc0917d808d978b7 + (2010-08-02). + Got complicated later: c49e9683b85ba9d12cbb6eebc4ab2c8dba68fbdc + If there are still systems around with warnings, we may restore the + prototype, but limited for those systems. + - tests/lib2305: delete duplicate declaration for + `libtest_debug_config`. + - tests/h2-download: fix `-Wunreachable-code-break`. + + [1] https://github.com/ngtcp2/nghttp3/blob/a70edb08e954d690e8fb2c1df999b5a056 + f8bf9f/cmake/PickyWarningsC.cmake + [2] https://ci.appveyor.com/project/curlorg/curl/builds/48553586/job/3qkgjaui + qla5fj45?fullLog=true#L1675 + [3] https://github.com/curl/curl/actions/runs/6880886309/job/18716044703?pr=1 + 2331#step:7:72 + https://github.com/curl/curl/actions/runs/6883016087/job/18722707368?pr=1 + 2331#step:7:109 + [4] https://ci.appveyor.com/project/curlorg/curl/builds/48555101/job/9g15qkrr + iklpf1ut#L204 + [5] https://ci.appveyor.com/project/curlorg/curl/builds/48555101/job/9g15qkrr + iklpf1ut#L218 + [6] https://github.com/curl/curl/actions/runs/6880886309/job/18716042927?pr=1 + 2331#step:7:290 + [7] https://github.com/curl/curl/actions/runs/6891484996/job/18746659406?pr=1 + 2331#step:9:1193 + [8] https://github.com/curl/curl/actions/runs/6882803986/job/18722082562?pr=1 + 2331#step:33:1870 + + Closes #12331 + +Daniel Stenberg (21 Nov 2023) + +- transfer: avoid unreachable expression + + If curl_off_t and size_t have the same size (which is common on modern + 64 bit systems), a condition cannot occur which Coverity pointed + out. Avoid the warning by having the code conditionally only used if + curl_off_t actually is larger. + + Follow-up to 1cd2f0072fa482e25baa2 + + Closes #12370 + +Stefan Eissing (21 Nov 2023) + +- transfer: readwrite improvements + + - changed header/chunk/handler->readwrite prototypes to accept `buf`, + `blen` and a `pconsumed` pointer. They now get the buffer to work on + and report back how many bytes they consumed + - eliminated `k->str` in SingleRequest + - improved excess data handling to properly calculate with any body data + left in the headerb buffer + - eliminated `k->badheader` enum to only be a bool + + Closes #12283 + +Daniel Stenberg (21 Nov 2023) + +- RELEASE-NOTES: synced + +Jiří HruÅ¡ka (21 Nov 2023) + +- transfer: avoid calling the read callback again after EOF + + Regression since 7f43f3dc5994d01b12 (7.84.0) + + Bug: https://curl.se/mail/lib-2023-11/0017.html + + Closes #12363 + +Daniel Stenberg (21 Nov 2023) + +- doh: provide better return code for responses w/o addresses + + Previously it was wrongly returning CURLE_OUT_OF_MEMORY when the + response did not contain any addresses. Now it more accurately returns + CURLE_COULDNT_RESOLVE_HOST. + + Reported-by: lRoccoon on github + + Fixes #12365 + Closes #12366 + +Stefan Eissing (21 Nov 2023) + +- HTTP/2, HTTP/3: handle detach of onoing transfers + + - refs #12356 where a UAF is reported when closing a connection + with a stream whose easy handle was cleaned up already + - handle DETACH events same as DONE events in h2/h3 filters + + Fixes #12356 + Reported-by: PaweÅ‚ Wegner + Closes #12364 + +Viktor Szakats (20 Nov 2023) + +- autotools: stop setting `-std=gnu89` with `--enable-warnings` + + Do not alter the C standard when building with `--enable-warnings` when + building with gcc. + + On one hand this alters warning results compared to a default build. + On the other, it may produce different binaries, which is unexpected. + + Also fix new warnings that appeared after removing `-std=gnu89`: + + - include: fix public curl headers to use the correct printf mask for + `CURL_FORMAT_CURL_OFF_T` and `CURL_FORMAT_CURL_OFF_TU` with mingw-w64 + and Visual Studio 2013 and newer. This fixes the printf mask warnings + in examples and tests. E.g. [1] + + - conncache: fix printf format string [2]. + + - http2: fix potential null pointer dereference [3]. + (seen on Slackware with gcc 11.) + + - libssh: fix printf format string in SFTP code [4]. + Also make MSVC builds compatible with old CRT versions. + + - libssh2: fix printf format string in SFTP code for MSVC. + Applying the same fix as for libssh above. + + - unit1395: fix `argument is null` and related issues [5]: + - stop calling `strcmp()` with NULL to avoid undefined behaviour. + - fix checking results if some of them were NULL. + - do not pass NULL to printf `%s`. + + - ci: keep a build job with `-std=gnu89` to continue testing for + C89-compliance. We can apply this to other gcc jobs as needed. + Ref: b23ce2cee7329bbf425f18b49973b7a5f23dfcb4 (2022-09-23) #9542 + + [1] https://dev.azure.com/daniel0244/curl/_build/results?buildId=18581&view=l + ogs&jobId=ccf9cc6d-2ef1-5cf2-2c09-30f0c14f923b + [2] https://github.com/curl/curl/actions/runs/6896854263/job/18763831142?pr=1 + 2346#step:6:67 + [3] https://github.com/curl/curl/actions/runs/6896854253/job/18763839238?pr=1 + 2346#step:30:214 + [4] https://github.com/curl/curl/actions/runs/6896854253/job/18763838007?pr=1 + 2346#step:29:895 + [5] https://github.com/curl/curl/actions/runs/6896854253/job/18763836775?pr=1 + 2346#step:33:1689 + + Closes #12346 + +- autotools: fix/improve gcc and Apple clang version detection + + - Before this patch we expected `n.n` `-dumpversion` output, but Ubuntu + may return `n-win32` (also with `-dumpfullversion`). Causing these + errors and failing to enable picky warnings: + ``` + ../configure: line 23845: test: : integer expression expected + ``` + Ref: https://github.com/libssh2/libssh2/actions/runs/6263453828/job/1700789 + 3718#step:5:143 + + Fix that by stripping any dash-suffix and handling a dotless (major-only) + version number by assuming `.0` in that case. + + `9.3-posix`, `9.3-win32`, `6`, `9.3.0`, `11`, `11.2`, `11.2.0` + Ref: https://github.com/mamedev/mame/pull/9767 + + - fix Apple clang version detection for releases between + 'Apple LLVM version 7.3.0' and 'Apple LLVM version 10.0.1' where the + version was under-detected as 3.7 llvm/clang equivalent. + + - fix Apple clang version detection for 'Apple clang version 11.0.0' + and newer where the Apple clang version was detected, instead of its + llvm/clang equivalent. + + - display detected clang/gcc/icc compiler version. + + Via libssh2: + - https://github.com/libssh2/libssh2/commit/00a3b88c51cdb407fbbb347a2e38c5c7d + 89875ad + https://github.com/libssh2/libssh2/pull/1187 + - https://github.com/libssh2/libssh2/commit/89ccc83c7da73e7ca3a112e3500081319 + 42b592e + https://github.com/libssh2/libssh2/pull/1232 + + Closes #12362 + +- autotools: delete LCC compiler support bits + + Follow-up to fd7ef00f4305a2919e6950def1cf83d0110a4acd #12222 + + Closes #12357 + +- cmake: add test for `DISABLE` options, add `CURL_DISABLE_HEADERS_API` + + - tests: verify CMake `DISABLE` options. + + Make an exception for 2 CMake-only ones, and one more that's + using a different naming scheme, also in autotools and source. + + - cmake: add support for `CURL_DISABLE_HEADERS_API`. + + Suggested-by: Daniel Stenberg + Ref: https://github.com/curl/curl/pull/12345#pullrequestreview-1736238641 + + Closes #12353 + +Jacob Hoffman-Andrews (20 Nov 2023) + +- hyper: temporarily remove HTTP/2 support + + The current design of the Hyper integration requires rebuilding the + Hyper clientconn for each request. However, building the clientconn + requires resending the HTTP/2 connection preface, which is incorrect + from a protocol perspective. That in turn causes servers to send GOAWAY + frames, effectively degrading performance to "no connection reuse" in + the best case. It may also be triggering some bugs where requests get + dropped entirely and reconnects take too long. + + This doesn't rule out HTTP/2 support with Hyper, but it may take a + redesign of the Hyper integration in order to make things work. + + Closes #12191 + +Jay Satiro (20 Nov 2023) + +- schannel: fix unused variable warning + + Bug: https://github.com/curl/curl/pull/12349#issuecomment-1818000846 + Reported-by: Viktor Szakats + + Closes https://github.com/curl/curl/pull/12361 + +Daniel Stenberg (19 Nov 2023) + +- url: find scheme with a "perfect hash" + + Instead of a loop to scan over the potentially 30+ scheme names, this + uses a "perfect hash" table. This works fine because the set of schemes + is known and cannot change in a build. The hash algorithm and table size + is made to only make a single scheme index per table entry. + + The perfect hash is generated by a separate tool (scripts/schemetable.c) + + Closes #12347 + +- scripts: add schemetable.c + + This tool generates a scheme-matching table. + + It iterates over a number of different initial and shift values in order + to find the hash algorithm that needs the smallest possible table. + + The generated hash function, table and table size then needs to be used + by the url.c:Curl_getn_scheme_handler() function. + +Stefan Eissing (19 Nov 2023) + +- vtls/vquic, keep peer name information together + + - add `struct ssl_peer` to keep hostname, dispname and sni + for a filter + - allocate `sni` for use in VTLS backend + - eliminate `Curl_ssl_snihost()` and its use of the download buffer + - use ssl_peer in SSL and QUIC filters + + Closes #12349 + +Viktor Szakats (18 Nov 2023) + +- build: always revert `#pragma GCC diagnostic` after use + + Before this patch some source files were overriding gcc warning options, + but without restoring them at the end of the file. In CMake UNITY builds + these options spilled over to the remainder of the source code, + effecitvely disabling them for a larger portion of the codebase than + intended. + + `#pragma clang diagnostic` didn't have such issue in the codebase. + + Reviewed-by: Marcel Raad + Closes #12352 + +- tidy-up: casing typos, delete unused Windows version aliases + + - cmake: fix casing of `UnixSockets` to match the rest of the codebase. + + - curl-compilers.m4: fix casing in a comment. + + - setup-win32: delete unused Windows version constant aliases. + + Reviewed-by: Marcel Raad + Closes #12351 + +- keylog: disable if unused + + Fully disable keylog code if there is no TLS or QUIC subsystem using it. + + Closes #12350 + +- cmake: add `CURL_DISABLE_BINDLOCAL` option + + To match similar autotools option. + + Default is `ON`. + + Reviewed-by: Daniel Stenberg + Closes #12345 + +- url: fix `-Wzero-length-array` with no protocols + + Fixes: + ``` + ./lib/url.c:178:56: warning: use of an empty initializer is a C2x extension [ + -Wc2x-extensions] + 178 | static const struct Curl_handler * const protocols[] = { + | ^ + ./lib/url.c:178:56: warning: zero size arrays are an extension [-Wzero-length + -array] + ``` + + Closes #12344 + +- url: fix builds with `CURL_DISABLE_HTTP` + + Fixes: + ``` + ./lib/url.c:456:35: error: no member named 'formp' in 'struct UrlState' + 456 | Curl_mime_cleanpart(data->state.formp); + | ~~~~~~~~~~~ ^ + ``` + + Regression from 74b87a8af13a155c659227f5acfa78243a8b2aa6 #11682 + + Closes #12343 + +- http: fix `-Wunused-parameter` with no auth and no proxy + + ``` + lib/http.c:734:26: warning: unused parameter 'proxy' [-Wunused-parameter] + bool proxy) + ^ + ``` + + Reviewed-by: Marcel Raad + Closes #12338 + +Daniel Stenberg (16 Nov 2023) + +- TODO: Some TLS options are not offered for HTTPS proxies + + Closes #12286 + Closes #12342 + +- RELEASE-NOTES: synced + +- duphandle: make dupset() not return with pointers to old alloced data + + As the blob pointers are to be duplicated, the function must not return + mid-function with lingering pointers to the old handle's allocated data, + as that would lead to double-free in OOM situations. + + Make sure to clear all destination pointers first to avoid this risk. + + Closes #12337 + +Viktor Szakats (16 Nov 2023) + +- http: fix `-Wunused-variable` compiler warning + + Fix compiler warnings in builds with disabled auths, NTLM and SPNEGO. + + E.g. with `CURL_DISABLE_BASIC_AUTH` + `CURL_DISABLE_BEARER_AUTH` + + `CURL_DISABLE_DIGEST_AUTH` + `CURL_DISABLE_NEGOTIATE_AUTH` + + `CURL_DISABLE_NTLM` on non-Windows. + + ``` + ./curl/lib/http.c:737:12: warning: unused variable 'result' [-Wunused-variabl + e] + CURLcode result = CURLE_OK; + ^ + ./curl/lib/http.c:995:18: warning: variable 'availp' set but not used [-Wunus + ed-but-set-variable] + unsigned long *availp; + ^ + ./curl/lib/http.c:996:16: warning: variable 'authp' set but not used [-Wunuse + d-but-set-variable] + struct auth *authp; + ^ + ``` + + Regression from e92edfbef64448ef461117769881f3ed776dec4e #11490 + + Fixes #12228 + Closes #12335 + +Jay Satiro (16 Nov 2023) + +- tool: support bold headers in Windows + + - If virtual terminal processing is enabled in Windows then use ANSI + escape codes Esc[1m and Esc[22m to turn bold on and off. + + Suggested-by: Gisle Vanem + + Ref: https://github.com/curl/curl/discussions/11770 + + Closes https://github.com/curl/curl/pull/12321 + +Viktor Szakats (15 Nov 2023) + +- build: fix libssh2 + `CURL_DISABLE_DIGEST_AUTH` + `CURL_DISABLE_AWS` + + Builds with libssh2 + `-DCURL_DISABLE_DIGEST_AUTH=ON` + + `-DCURL_DISABLE_AWS=ON` in combination with either Schannel on Windows, + or `-DCURL_DISABLE_NTLM=ON` on other operating systems failed while + compiling due to a missing HMAC declaration. + + The reason is that HMAC is required by `lib/sha256.c` which publishes + `Curl_sha256it()` which is required by `lib/vssh/libssh2.c` when + building for libssh2 v1.8.2 (2019-05-25) or older. + + Make sure to compile the HMAC bits for a successful build. + + Both HMAC and `Curl_sha256it()` rely on the same internals, so splitting + them into separate sources isn't practical. + + Fixes: + ``` + [...] + In file included from ./curl/_x64-win-ucrt-cmake-llvm-bld/lib/CMakeFiles/libc + url_object.dir/Unity/unity_0_c.c:310: + ./curl/lib/sha256.c:527:42: error: array has incomplete element type 'const s + truct HMAC_params' + 527 | const struct HMAC_params Curl_HMAC_SHA256[] = { + | ^ + ./curl/lib/curl_sha256.h:34:21: note: forward declaration of 'struct HMAC_par + ams' + [...] + ``` + + Regression from e92edfbef64448ef461117769881f3ed776dec4e #11490 + + Fixes #12273 + Closes #12332 + +Daniel Stenberg (15 Nov 2023) + +- duphandle: also free 'outcurl->cookies' in error path + + Fixes memory-leak when OOM mid-function + + Use plain free instead of safefree, since the entire struct is + freed below. + + Remove some free calls that is already freed in Curl_freeset() + + Closes #12329 + +Viktor Szakats (15 Nov 2023) + +- config-win32: set `HAVE_SNPRINTF` for mingw-w64 + + It's available in all mingw-w64 releases. We already pre-fill this + detection in CMake. + + Closes #12325 + +- sasl: fix `-Wunused-function` compiler warning + + In builds with disabled auths. + + ``` + lib/curl_sasl.c:266:17: warning: unused function 'get_server_message' [-Wunus + ed-function] + static CURLcode get_server_message(struct SASL *sasl, struct Curl_easy *data, + ^ + 1 warning generated. + ``` + Ref: https://github.com/curl/trurl/actions/runs/6871732122/job/18689066151#st + ep:3:3822 + + Reviewed-by: Daniel Stenberg + Closes #12326 + +- build: picky warning updates + + - cmake: sync some picky gcc warnings with autotools. + - cmake, autotools: add `-Wold-style-definition` for clang too. + - cmake: more precise version info for old clang options. + - cmake: use `IN LISTS` syntax in `foreach()`. + + Reviewed-by: Daniel Stenberg + Reviewed-by: Marcel Raad + Closes #12324 + +Daniel Stenberg (15 Nov 2023) + +- urldata: move cookielist from UserDefined to UrlState + + 1. Because the value is not strictly set with a setopt option. + + 2. Because otherwise when duping a handle when all the set.* fields are + first copied and an error happens (think out of memory mid-function), + the function would easily free the list *before* it was deep-copied, + which could lead to a double-free. + + Closes #12323 + +Viktor Szakats (14 Nov 2023) + +- autotools: avoid passing `LDFLAGS` twice to libcurl + + autotools passes `LDFLAGS` automatically linker commands. curl's + `lib/Makefile.am` customizes libcurl linker flags. In that + customization, it added `LDFLAGS` to the custom flags. This resulted in + passing `LDFLAGS` _twice_ to the `libtool` command. + + Most of the time this is benign, but some `LDFLAGS` options can break + the build when passed twice. One such example is passing `.o` files, + e.g. `crt*.o` files necessary when customizing the C runtime, e.g. for + MUSL builds. + + Passing them twice resulted in duplicate symbol errors: + ``` + libtool: link: clang-15 --target=aarch64-unknown-linux-musl [...] /usr/lib/a + arch64-linux-musl/crt1.o [...] /usr/lib/aarch64-linux-musl/crt1.o [...] + ld.lld-15: error: duplicate symbol: _start + >>> defined at crt1.c + >>> /usr/lib/aarch64-linux-musl/crt1.o:(.text+0x0) + >>> defined at crt1.c + >>> /usr/lib/aarch64-linux-musl/crt1.o:(.text+0x0) + [...] + clang: error: linker command failed with exit code 1 (use -v to see invocatio + n) + ``` + + This behaviour came with commit 1a593191c2769a47b8c3e4d9715ec9f6dddf5e36 + (2013-07-23) as a fix for bug https://curl.haxx.se/bug/view.cgi?id=1217. + The patch was a works-for-me hack that ended up merged in curl: + https://sourceforge.net/p/curl/bugs/1217/#06ef + With the root cause remaining unclear. + + Perhaps the SUNPro 12 linker was sensitive to `-L` `-l` order, requiring + `-L` first? This would be unusual and suggests a bug in either the + linker or in `libtool`. + + The curl build does pass the list of detected libs via its own + `LIBCURL_LIBS` variable, which ends up before `LDFLAGS` on the `libtool` + command line, but it's the job of `libtool` to ensure that even + a peculiar linker gets the options in the expected order. Also because + autotools passes `LDFLAGS` last, making it hardly possible to pass + anything after it. + + Perhaps in the 10 years since this issue, this already got a fix + upstream. + + This patch deletes `LDFLAGS` from our customized libcurl options, + leaving a single copy of them as passed by autotools automatically. + + Reverts 1a593191c2769a47b8c3e4d9715ec9f6dddf5e36 + Closes #12310 + +- autotools: accept linker flags via `CURL_LDFLAGS_{LIB,BIN}` + + To allow passing `LDFLAGS` specific to libcurl (`CURL_LDFLAGS_LIB`) and + curl tool (`CURL_LDFLAGS_BIN`). + + This makes it possible to build libcurl and curl with a single + invocation with lib- and tool-specific custom linker flags. + + Such flag can be enabling `.map` files, a `.def` file for libcurl DLL, + controlling static/shared, incl. requesting a static curl tool (with + `-static-libtool-libs`) while building both shared and static libcurl. + + curl-for-win uses the above and some more. + + These options are already supported in `Makefile.mk`. CMake has built-in + variables for this. + + Closes #12312 + +Jay Satiro (14 Nov 2023) + +- tool_cb_hdr: add an additional parsing check + + - Don't dereference the past-the-end element when parsing the server's + Content-disposition header. + + As 'p' is advanced it can point to the past-the-end element and prior + to this change 'p' could be dereferenced in that case. + + Technically the past-the-end element is not out of bounds because dynbuf + (which manages the header line) automatically adds a null terminator to + every buffer and that is not included in the buffer length passed to + the header callback. + + Closes https://github.com/curl/curl/pull/12320 + +Philip Heiduck (14 Nov 2023) + +- .cirrus.yml: freebsd 14 + + ensure curl works on latest freebsd version + + Closes #12053 + +Daniel Stenberg (13 Nov 2023) + +- easy: in duphandle, init the cookies for the new handle + + ... not the source handle. + + Closes #12318 + +- duphandle: use strdup to clone *COPYPOSTFIELDS if size is not set + + Previously it would unconditionally use the size, which is set to -1 + when strlen is requested. + + Updated test 544 to verify. + + Closes #12317 + +- RELEASE-NOTES: synced + +- curl_easy_duphandle.3: clarify how HSTS and alt-svc are duped + + Closes #12315 + +- urldata: move hstslist from 'set' to 'state' + + To make it work properly with curl_easy_duphandle(). This, because + duphandle duplicates the entire 'UserDefined' struct by plain copy while + 'hstslist' is a linked curl_list of file names. This would lead to a + double-free when the second of the two involved easy handles were + closed. + + Closes #12315 + +- test1900: verify duphandle with HSTS using multiple files + + Closes #12315 + +Goro FUJI (13 Nov 2023) + +- http: allow longer HTTP/2 request method names + + - Increase the maximum request method name length from 11 to 23. + + For HTTP/1.1 and earlier there's not a specific limit in libcurl for + method length except that it is limited by the initial HTTP request + limit (DYN_HTTP_REQUEST). Prior to fc2f1e54 HTTP/2 was treated the same + and there was no specific limit. + + According to Internet Assigned Numbers Authority (IANA) the longest + registered method is UPDATEREDIRECTREF which is 17 characters. + + Also there are unregistered methods used by some companies that are + longer than 11 characters. + + The limit was originally added by 61f52a97 but not used until fc2f1e54. + + Ref: https://www.iana.org/assignments/http-methods/http-methods.xhtml + + Closes https://github.com/curl/curl/pull/12311 + +Jay Satiro (12 Nov 2023) + +- CURLOPT_CAINFO_BLOB.3: explain what CURL_BLOB_COPY does + + - Add an explanation of the CURL_BLOB_COPY flag to CURLOPT_CAINFO_BLOB + and CURLOPT_PROXY_CAINFO_BLOB docs. + + All the other _BLOB option docs already have the same explanation. + + Closes https://github.com/curl/curl/pull/12277 + +Viktor Szakats (11 Nov 2023) + +- tidy-up: dedupe Windows system libs in cmake + + Reviewed-by: Daniel Stenberg + Closes #12307 + +Junho Choi (11 Nov 2023) + +- ci: test with latest quiche release (0.19.0) + + Closes #12180 + +- quiche: use quiche_conn_peer_transport_params() + + In recent quiche, transport parameter API is separated + with quiche_conn_peer_transport_params(). + (https://github.com/cloudflare/quiche/pull/1575) + It breaks with bulding with latest(post 0.18.0) quiche. + + Closes #12180 + +Daniel Stenberg (11 Nov 2023) + +- Makefile: generate the VC 14.20 project files at dist-time + + Follow-up to 28287092cc5a6d6ef8 (#12282) + + Closes #12290 + +Sam James (11 Nov 2023) + +- misc: fix -Walloc-size warnings + + GCC 14 introduces a new -Walloc-size included in -Wextra which gives: + + ``` + src/tool_operate.c: In function ‘add_per_transfer’: + src/tool_operate.c:213:5: warning: allocation of insufficient size ‘1’ fo + r type ‘struct per_transfer’ with size ‘480’ [-Walloc-size] + 213 | p = calloc(sizeof(struct per_transfer), 1); + | ^ + src/var.c: In function ‘addvariable’: + src/var.c:361:5: warning: allocation of insufficient size ‘1’ for type †+ ˜struct var’ with size ‘32’ [-Walloc-size] + 361 | p = calloc(sizeof(struct var), 1); + | ^ + ``` + + The calloc prototype is: + ``` + void *calloc(size_t nmemb, size_t size); + ``` + + So, just swap the number of members and size arguments to match the + prototype, as we're initialising 1 struct of size `sizeof(struct + ...)`. GCC then sees we're not doing anything wrong. + + Closes #12292 + +Mark Gaiser (11 Nov 2023) + +- IPFS: bugfixes + + - Fixed endianness bug in gateway file parsing + - Use IPFS_PATH in tests where IPFS_DATA was used + - Fixed typos from traling -> trailing + - Fixed broken link in IPFS.md + + Follow-up to 859e88f6533f9e + + Reported-by: Michael Kaufmann + Bug: https://github.com/curl/curl/pull/12152#issuecomment-1798214137 + Closes #12305 + +Daniel Stenberg (11 Nov 2023) + +- VULN-DISCLOSURE-POLIC: remove broken link to hackerone + + It should ideally soon not be done from hackerone anyway + + Closes #12308 + +Andrew Kurushin (11 Nov 2023) + +- schannel: add CA cache support for files and memory blobs + + - Support CA bundle and blob caching. + + Cache timeout is 24 hours or can be set via CURLOPT_CA_CACHE_TIMEOUT. + + Closes https://github.com/curl/curl/pull/12261 + +Daniel Stenberg (10 Nov 2023) + +- RELEASE-NOTES: synced + +Charlie C (10 Nov 2023) + +- cmake: option to disable install & drop `curlu` target when unused + + This patch makes the following changes: + - adds the option `CURL_DISABLE_INSTALL` - to disable 'install' targets. + - Removes the target `curlu` when the option `BUILD_TESTING` is set to + `OFF` - to prevent it from being loaded in Visual Studio. + + Closes #12287 + +Kai Pastor (10 Nov 2023) + +- cmake: fix multiple include of CURL package + + Fixes errors on second `find_package(CURL)`. This is a frequent case + with transitive dependencies: + ``` + CMake Error at ...: + add_library cannot create ALIAS target "CURL::libcurl" because another + target with the same name already exists. + ``` + + Test to reproduce: + ```cmake + cmake_minimum_required(VERSION 3.27) # must be 3.18 or higher + + project(curl) + + set(CURL_DIR "example/lib/cmake/CURL/") + find_package(CURL CONFIG REQUIRED) + find_package(CURL CONFIG REQUIRED) # fails + + add_executable(main main.c) + target_link_libraries(main CURL::libcurl) + ``` + + Ref: https://cmake.org/cmake/help/latest/release/3.18.html#other-changes + Ref: https://cmake.org/cmake/help/v3.18/policy/CMP0107.html + Ref: #12300 + Assisted-by: Harry Mallon + Closes #11913 + +Viktor Szakats (8 Nov 2023) + +- tidy-up: use `OPENSSL_VERSION_NUMBER` + + Uniformly use `OPENSSL_VERSION_NUMBER` to check for OpenSSL version. + Before this patch some places used `OPENSSL_VERSION_MAJOR`. + + Also fix `lib/md4.c`, which included `opensslconf.h`, but that doesn't + define any version number in these implementations: BoringSSL, AWS-LC, + LibreSSL, wolfSSL. (Only in mainline OpenSSL/quictls). Switch that to + `opensslv.h`. This wasn't causing a deeper problem because the code is + looking for v3, which is only provided by OpenSSL/quictls as of now. + + According to https://github.com/openssl/openssl/issues/17517, the macro + `OPENSSL_VERSION_NUMBER` is safe to use and not deprecated. + + Reviewed-by: Marcel Raad + Closes #12298 + +Daniel Stenberg (8 Nov 2023) + +- resolve.d: drop a multi use-sentence + + Since the `multi:` keyword adds that message. + + Reported-by: ç©ä¸¹å°¼ Dan Jacobson + Fixes https://github.com/curl/curl/discussions/12294 + Closes #12295 + +- content_encoding: make Curl_all_content_encodings allocless + + - Fixes a memory leak pointed out by Coverity + - Also found by OSS-Fuzz: https://bugs.chromium.org/p/oss-fuzz/issues/detail? + id=63947 + - Avoids unncessary allocations + + Follow-up ad051e1cbec68b2456a22661b + + Closes #12289 + +Michael Kaufmann (7 Nov 2023) + +- vtls: use ALPN "http/1.1" for HTTP/1.x, including HTTP/1.0 + + Some servers don't support the ALPN protocol "http/1.0" (e.g. IIS 10), + avoid it and use "http/1.1" instead. + + This reverts commit df856cb5c9 (#10183). + + Fixes #12259 + Closes #12285 + +Daniel Stenberg (7 Nov 2023) + +- Makefile.am: drop vc10, vc11 and vc12 projects from dist + + They are end of life products. Support for generating them remain in the + repo for a while but this change drops them from distribution. + + Closes #12288 + +David Suter (7 Nov 2023) + +- projects: add VC14.20 project files + + Windows projects included VC14, VC14.10, VC14.30 but not VC14.20. + OpenSSL and Wolf SSL scripts mention VC14.20 so I don't see a reason why + this is missing. Updated the templates to produce a VC14.20 project. + Project opens in Visual Studio 2019 as expected. + + Closes #12282 + +Daniel Stenberg (7 Nov 2023) + +- curl: move IPFS code into src/tool_ipfs.[ch] + + - convert ensure_trailing into ensure_trailing_slash + - strdup the URL string to own it proper + - use shorter variable names + - combine some expressions + - simplify error handling in ipfs_gateway() + - add MAX_GATEWAY_URL_LEN + proper bailout if maximum is reached + - ipfs-gateway.d polish and simplification + - shorten ipfs error message + make them "synthetic" + + Closes #12281 + +Viktor Szakats (6 Nov 2023) + +- build: delete support bits for obsolete Windows compilers + + - Pelles C: Unclear status, failed to obtain a fresh copy a few months + ago. Possible website is HTTP-only. ~10 years ago I left this compiler + dealing with crashes and other issues with no response on the forum + for years. It has seen some activity in curl back in 2021. + - LCC: Last stable release in September 2002. + - Salford C: Misses winsock2 support, possibly abandoned? Last mentioned + in 2006. + - Borland C++: We dropped Borland C++ support in 2018. + - MS Visual C++ 6.0: Released in 1998. curl already requires VS 2010 + (or possibly 2008) as a minimum. + + Closes #12222 + +- build: delete `HAVE_STDINT_H` and `HAVE_INTTYPES_H` + + We use `stdint.h` unconditionally in all places except one. These uses + are imposed by external dependencies / features. nghttp2, quic, wolfSSL + and `HAVE_MACH_ABSOLUTE_TIME` do require this C99 header. It means that + any of these features make curl require a C99 compiler. (In case of + MSVC, this means Visual Studio 2010 or newer.) + + This patch changes the single use of `stdint.h` guarded by + `HAVE_STDINT_H` to use `stdint.h` unconditionally. Also stop using + `inttypes.h` as an alternative there. `HAVE_INTTYPES_H` wasn't used + anywhere else, allowing to delete this feature check as well. + + Closes #12275 + +Daniel Stenberg (6 Nov 2023) + +- tool_operate: do not mix memory models + + Make sure 'inputpath' only points to memory allocated by libcurl so that + curl_free works correctly. + + Pointed out by Coverity + + Follow-up to 859e88f6533f9e1f890 + + Closes #12280 + +Stefan Eissing (6 Nov 2023) + +- lib: client writer, part 2, accounting + logging + + This PR has these changes: + + Renaming of unencode_* to cwriter, e.g. client writers + - documentation of sendf.h functions + - move max decode stack checks back to content_encoding.c + - define writer phase which was used as order before + - introduce phases for monitoring inbetween decode phases + - offering default implementations for init/write/close + + Add type paramter to client writer's do_write() + - always pass all writes through the writer stack + - writers who only care about BODY data will pass other writes unchanged + + add RAW and PROTOCOL client writers + - RAW used for Curl_debug() logging of CURLINFO_DATA_IN + - PROTOCOL used for updates to data->req.bytecount, max_filesize checks and + Curl_pgrsSetDownloadCounter() + - remove all updates of data->req.bytecount and calls to + Curl_pgrsSetDownloadCounter() and Curl_debug() from other code + - adjust test457 expected output to no longer see the excess write + + Closes #12184 + +Daniel Stenberg (6 Nov 2023) + +- VULN-DISCLOSURE-POLICY: escape sequences are not a security flaw + + Closes #12278 + +Viktor Szakats (6 Nov 2023) + +- rand: fix build error with autotools + LibreSSL + + autotools unexpectedly detects `arc4random` because it is also looking + into dependency libs. One dependency, LibreSSL, happens to publish an + `arc4random` function (via its shared lib before v3.7, also via static + lib as of v3.8.2). When trying to use this function in `lib/rand.c`, + its protoype is missing. To fix that, curl included a prototype, but + that used a C99 type without including `stdint.h`, causing: + + ``` + ../../lib/rand.c:37:1: error: unknown type name 'uint32_t' + 37 | uint32_t arc4random(void); + | ^ + 1 error generated. + ``` + + This patch improves this by dropping the local prototype and instead + limiting `arc4random` use for non-OpenSSL builds. OpenSSL builds provide + their own random source anyway. + + The better fix would be to teach autotools to not link dependency libs + while detecting `arc4random`. + + LibreSSL publishing a non-namespaced `arc4random` tracked here: + https://github.com/libressl/portable/issues/928 + + Regression from 755ddbe901cd0c921fbc3ac5b3775c0dc683bc73 #10672 + + Reviewed-by: Daniel Stenberg + Fixes #12257 + Closes #12274 + +Daniel Stenberg (5 Nov 2023) + +- RELEASE-NOTES: synced + +- strdup: do Curl_strndup without strncpy + + To avoid (false positive) gcc-13 compiler warnings. + + Follow-up to 4855debd8a2c1cb + + Assisted-by: Jay Satiro + Reported-by: Viktor Szakats + Fixes #12258 + +Enno Boland (5 Nov 2023) + +- HTTP: fix empty-body warning + + This change fixes a compiler warning with gcc-12.2.0 when + `-DCURL_DISABLE_BEARER_AUTH=ON` is used. + + /home/tox/src/curl/lib/http.c: In function 'Curl_http_input_auth': + /home/tox/src/curl/lib/http.c:1147:12: warning: suggest braces around emp + ty body in an 'else' statement [-Wempty-body] + 1147 | ; + | ^ + + Closes #12262 + +Daniel Stenberg (5 Nov 2023) + +- openssl: identify the "quictls" backend correctly + + Since vanilla OpenSSL does not support the QUIC API I think it helps + users to identify the correct OpenSSL fork in version output. The best + (crude) way to do that right now seems to be to check if ngtcp2 support + is enabled. + + Closes #12270 + +Mark Gaiser (5 Nov 2023) + +- curl: improved IPFS and IPNS URL support + + Previously just ipfs:// and ipns:// was supported, which is + too strict for some usecases. + + This patch allows paths and query arguments to be used too. + Making this work according to normal http semantics: + + ipfs:///foo/bar?key=val + ipns:///foo/bar?key=val + + The gateway url support is changed. + It now only supports gateways in the form of: + + http:///foo/bar + http:// + + Query arguments here are explicitly not allowed and trigger an intended + malformed url error. + + There also was a crash when IPFS_PATH was set with a non trailing + forward slash. This has been fixed. + + Lastly, a load of test cases have been added to verify the above. + + Reported-by: Steven Allen + Fixes #12148 + Closes #12152 + +Harry Mallon (5 Nov 2023) + +- docs: KNOWN_BUGS cleanup + + * Remove other mention of hyper memory-leaks from `KNOWN_BUGS`. + Should have been removed in 629723ecf22a8eae78d64cceec2f3bdae703ec95 + + * Remove mention of aws-sigv4 sort query string from `KNOWN_BUGS`. + Fixed in #11806 + + * Remove mention of aws-sigv4 query empty value problems + + * Remove mention of aws-sigv4 missing amz-content-sha256 + Fixed in #9995 + +- http_aws_sigv4: canonicalise valueless query params + + Fixes #8107 + Closes #12244 + +Michael Kaufmann (4 Nov 2023) + +- docs: preserve the modification date when copying the prebuilt man page + + The previously built man page "curl.1" must be copied with the original + modification date, otherwise the man page is never updated. + + This fixes a bug that has been introduced with commit 2568441cab. + + Reviewed-by: Dan Fandrich + Reviewed-by: Daniel Stenberg + + Closes #12199 + +Daniel Stenberg (4 Nov 2023) + +- docs: remove bold from some man page SYNOPSIS sections + + In the name of consistency + + Closes #12267 + +- openssl: two multi pointer checks should probably rather be asserts + + ... so add the asserts now and consider removing the dynamic checks in a + future. + + Ref: #12261 + Closes #12264 + +boilingoden (4 Nov 2023) + +- docs: add supported version for the json write-out + + xref: https://curl.se/changes.html#7_70_0 + + Closes #12266 diff --git a/third_party/curl/CMake/CMakeConfigurableFile.in b/third_party/curl/CMake/CMakeConfigurableFile.in new file mode 100644 index 0000000..a3d2bc4 --- /dev/null +++ b/third_party/curl/CMake/CMakeConfigurableFile.in @@ -0,0 +1,24 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +@CMAKE_CONFIGURABLE_FILE_CONTENT@ diff --git a/third_party/curl/CMake/CurlSymbolHiding.cmake b/third_party/curl/CMake/CurlSymbolHiding.cmake new file mode 100644 index 0000000..8289b49 --- /dev/null +++ b/third_party/curl/CMake/CurlSymbolHiding.cmake @@ -0,0 +1,84 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +include(CheckCSourceCompiles) + +option(CURL_HIDDEN_SYMBOLS "Set to ON to hide libcurl internal symbols (=hide all symbols that aren't officially external)." ON) +mark_as_advanced(CURL_HIDDEN_SYMBOLS) + +if(WIN32 AND ENABLE_CURLDEBUG) + # We need to export internal debug functions (e.g. curl_dbg_*), so disable + # symbol hiding for debug builds. + set(CURL_HIDDEN_SYMBOLS OFF) +endif() + +if(CURL_HIDDEN_SYMBOLS) + set(SUPPORTS_SYMBOL_HIDING FALSE) + + if(CMAKE_C_COMPILER_ID MATCHES "Clang" AND NOT MSVC) + set(SUPPORTS_SYMBOL_HIDING TRUE) + set(_SYMBOL_EXTERN "__attribute__ ((__visibility__ (\"default\")))") + set(_CFLAG_SYMBOLS_HIDE "-fvisibility=hidden") + elseif(CMAKE_COMPILER_IS_GNUCC) + if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 3.4) + # note: this is considered buggy prior to 4.0 but the autotools don't care, so let's ignore that fact + set(SUPPORTS_SYMBOL_HIDING TRUE) + set(_SYMBOL_EXTERN "__attribute__ ((__visibility__ (\"default\")))") + set(_CFLAG_SYMBOLS_HIDE "-fvisibility=hidden") + endif() + elseif(CMAKE_C_COMPILER_ID MATCHES "SunPro" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 8.0) + set(SUPPORTS_SYMBOL_HIDING TRUE) + set(_SYMBOL_EXTERN "__global") + set(_CFLAG_SYMBOLS_HIDE "-xldscope=hidden") + elseif(CMAKE_C_COMPILER_ID MATCHES "Intel" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 9.0) + # note: this should probably just check for version 9.1.045 but I'm not 100% sure + # so let's do it the same way autotools do. + set(SUPPORTS_SYMBOL_HIDING TRUE) + set(_SYMBOL_EXTERN "__attribute__ ((__visibility__ (\"default\")))") + set(_CFLAG_SYMBOLS_HIDE "-fvisibility=hidden") + check_c_source_compiles("#include + int main (void) { printf(\"icc fvisibility bug test\"); return 0; }" _no_bug) + if(NOT _no_bug) + set(SUPPORTS_SYMBOL_HIDING FALSE) + set(_SYMBOL_EXTERN "") + set(_CFLAG_SYMBOLS_HIDE "") + endif() + elseif(MSVC) + set(SUPPORTS_SYMBOL_HIDING TRUE) + endif() + + set(HIDES_CURL_PRIVATE_SYMBOLS ${SUPPORTS_SYMBOL_HIDING}) +elseif(MSVC) + if(NOT CMAKE_VERSION VERSION_LESS 3.7) + set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS TRUE) #present since 3.4.3 but broken + set(HIDES_CURL_PRIVATE_SYMBOLS FALSE) + else() + message(WARNING "Hiding private symbols regardless CURL_HIDDEN_SYMBOLS being disabled.") + set(HIDES_CURL_PRIVATE_SYMBOLS TRUE) + endif() +else() + set(HIDES_CURL_PRIVATE_SYMBOLS FALSE) +endif() + +set(CURL_CFLAG_SYMBOLS_HIDE ${_CFLAG_SYMBOLS_HIDE}) +set(CURL_EXTERN_SYMBOL ${_SYMBOL_EXTERN}) diff --git a/third_party/curl/CMake/CurlTests.c b/third_party/curl/CMake/CurlTests.c new file mode 100644 index 0000000..483b9a2 --- /dev/null +++ b/third_party/curl/CMake/CurlTests.c @@ -0,0 +1,430 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifdef HAVE_FCNTL_O_NONBLOCK +/* headers for FCNTL_O_NONBLOCK test */ +#include +#include +#include +/* */ +#if defined(sun) || defined(__sun__) || \ + defined(__SUNPRO_C) || defined(__SUNPRO_CC) +# if defined(__SVR4) || defined(__srv4__) +# define PLATFORM_SOLARIS +# else +# define PLATFORM_SUNOS4 +# endif +#endif +#if (defined(_AIX) || defined(__xlC__)) && !defined(_AIX41) +# define PLATFORM_AIX_V3 +#endif +/* */ +#if defined(PLATFORM_SUNOS4) || defined(PLATFORM_AIX_V3) +#error "O_NONBLOCK does not work on this platform" +#endif + +int main(void) +{ + /* O_NONBLOCK source test */ + int flags = 0; + if(0 != fcntl(0, F_SETFL, flags | O_NONBLOCK)) + return 1; + return 0; +} +#endif + +/* tests for gethostbyname_r */ +#if defined(HAVE_GETHOSTBYNAME_R_3_REENTRANT) || \ + defined(HAVE_GETHOSTBYNAME_R_5_REENTRANT) || \ + defined(HAVE_GETHOSTBYNAME_R_6_REENTRANT) +# define _REENTRANT + /* no idea whether _REENTRANT is always set, just invent a new flag */ +# define TEST_GETHOSTBYFOO_REENTRANT +#endif +#if defined(HAVE_GETHOSTBYNAME_R_3) || \ + defined(HAVE_GETHOSTBYNAME_R_5) || \ + defined(HAVE_GETHOSTBYNAME_R_6) || \ + defined(TEST_GETHOSTBYFOO_REENTRANT) +#include +#include +int main(void) +{ + char *address = "example.com"; + int length = 0; + int type = 0; + struct hostent h; + int rc = 0; +#if defined(HAVE_GETHOSTBYNAME_R_3) || \ + defined(HAVE_GETHOSTBYNAME_R_3_REENTRANT) + struct hostent_data hdata; +#elif defined(HAVE_GETHOSTBYNAME_R_5) || \ + defined(HAVE_GETHOSTBYNAME_R_5_REENTRANT) || \ + defined(HAVE_GETHOSTBYNAME_R_6) || \ + defined(HAVE_GETHOSTBYNAME_R_6_REENTRANT) + char buffer[8192]; + int h_errnop; + struct hostent *hp; +#endif + +#if defined(HAVE_GETHOSTBYNAME_R_3) || \ + defined(HAVE_GETHOSTBYNAME_R_3_REENTRANT) + rc = gethostbyname_r(address, &h, &hdata); +#elif defined(HAVE_GETHOSTBYNAME_R_5) || \ + defined(HAVE_GETHOSTBYNAME_R_5_REENTRANT) + rc = gethostbyname_r(address, &h, buffer, 8192, &h_errnop); + (void)hp; /* not used for test */ +#elif defined(HAVE_GETHOSTBYNAME_R_6) || \ + defined(HAVE_GETHOSTBYNAME_R_6_REENTRANT) + rc = gethostbyname_r(address, &h, buffer, 8192, &hp, &h_errnop); +#endif + + (void)length; + (void)type; + (void)rc; + return 0; +} +#endif + +#ifdef HAVE_IN_ADDR_T +#include +#include +#include +int main(void) +{ + if((in_addr_t *) 0) + return 0; + if(sizeof(in_addr_t)) + return 0; + ; + return 0; +} +#endif + +#ifdef HAVE_BOOL_T +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_STDBOOL_H +#include +#endif +int main(void) +{ + if(sizeof(bool *)) + return 0; + ; + return 0; +} +#endif + +#ifdef STDC_HEADERS +#include +#include +#include +#include +int main(void) { return 0; } +#endif + +#ifdef HAVE_FILE_OFFSET_BITS +#ifdef _FILE_OFFSET_BITS +#undef _FILE_OFFSET_BITS +#endif +#define _FILE_OFFSET_BITS 64 +#include + /* Check that off_t can represent 2**63 - 1 correctly. + We can't simply define LARGE_OFF_T to be 9223372036854775807, + since some C++ compilers masquerading as C compilers + incorrectly reject 9223372036854775807. */ +#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) + int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 + && LARGE_OFF_T % 2147483647 == 1) + ? 1 : -1]; +int main(void) { ; return 0; } +#endif + +#ifdef HAVE_IOCTLSOCKET +/* includes start */ +#ifdef _WIN32 +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +#endif +int main(void) +{ + /* ioctlsocket source code */ + int socket; + unsigned long flags = ioctlsocket(socket, FIONBIO, &flags); + ; + return 0; +} + +#endif + +#ifdef HAVE_IOCTLSOCKET_CAMEL +/* includes start */ +#ifdef _WIN32 +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +#endif +int main(void) +{ + /* IoctlSocket source code */ + if(0 != IoctlSocket(0, 0, 0)) + return 1; + ; + return 0; +} +#endif + +#ifdef HAVE_IOCTLSOCKET_CAMEL_FIONBIO +/* includes start */ +#ifdef _WIN32 +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +#endif +int main(void) +{ + /* IoctlSocket source code */ + long flags = 0; + if(0 != IoctlSocket(0, FIONBIO, &flags)) + return 1; + ; + return 0; +} +#endif + +#ifdef HAVE_IOCTLSOCKET_FIONBIO +/* includes start */ +#ifdef _WIN32 +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +#endif +int main(void) +{ + unsigned long flags = 0; + if(0 != ioctlsocket(0, FIONBIO, &flags)) + return 1; + ; + return 0; +} +#endif + +#ifdef HAVE_IOCTL_FIONBIO +/* headers for FIONBIO test */ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif +#ifdef HAVE_SYS_SOCKET_H +# include +#endif +#ifdef HAVE_SYS_IOCTL_H +# include +#endif +#ifdef HAVE_STROPTS_H +# include +#endif +int main(void) +{ + int flags = 0; + if(0 != ioctl(0, FIONBIO, &flags)) + return 1; + ; + return 0; +} +#endif + +#ifdef HAVE_IOCTL_SIOCGIFADDR +/* headers for FIONBIO test */ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif +#ifdef HAVE_SYS_SOCKET_H +# include +#endif +#ifdef HAVE_SYS_IOCTL_H +# include +#endif +#ifdef HAVE_STROPTS_H +# include +#endif +#include +int main(void) +{ + struct ifreq ifr; + if(0 != ioctl(0, SIOCGIFADDR, &ifr)) + return 1; + ; + return 0; +} +#endif + +#ifdef HAVE_SETSOCKOPT_SO_NONBLOCK +/* includes start */ +#ifdef _WIN32 +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +#endif +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_SOCKET_H +# include +#endif +/* includes end */ +int main(void) +{ + if(0 != setsockopt(0, SOL_SOCKET, SO_NONBLOCK, 0, 0)) + return 1; + ; + return 0; +} +#endif + +#ifdef HAVE_GLIBC_STRERROR_R +#include +#include + +void check(char c) {} + +int main(void) +{ + char buffer[1024]; + /* This will not compile if strerror_r does not return a char* */ + check(strerror_r(EACCES, buffer, sizeof(buffer))[0]); + return 0; +} +#endif + +#ifdef HAVE_POSIX_STRERROR_R +#include +#include + +/* float, because a pointer can't be implicitly cast to float */ +void check(float f) {} + +int main(void) +{ + char buffer[1024]; + /* This will not compile if strerror_r does not return an int */ + check(strerror_r(EACCES, buffer, sizeof(buffer))); + return 0; +} +#endif + +#ifdef HAVE_FSETXATTR_6 +#include /* header from libc, not from libattr */ +int main(void) +{ + fsetxattr(0, 0, 0, 0, 0, 0); + return 0; +} +#endif + +#ifdef HAVE_FSETXATTR_5 +#include /* header from libc, not from libattr */ +int main(void) +{ + fsetxattr(0, 0, 0, 0, 0); + return 0; +} +#endif + +#ifdef HAVE_CLOCK_GETTIME_MONOTONIC +#include +int main(void) +{ + struct timespec ts = {0, 0}; + clock_gettime(CLOCK_MONOTONIC, &ts); + return 0; +} +#endif + +#ifdef HAVE_BUILTIN_AVAILABLE +int main(void) +{ + if(__builtin_available(macOS 10.12, *)) {} + return 0; +} +#endif + +#ifdef HAVE_ATOMIC +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif +#ifdef HAVE_STDATOMIC_H +# include +#endif +/* includes end */ + +int main(void) +{ + _Atomic int i = 1; + i = 0; /* Force an atomic-write operation. */ + return i; +} +#endif + +#ifdef HAVE_WIN32_WINNT +/* includes start */ +#ifdef _WIN32 +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# ifndef NOGDI +# define NOGDI +# endif +# include +#endif +/* includes end */ + +#define enquote(x) #x +#define expand(x) enquote(x) +#pragma message("_WIN32_WINNT=" expand(_WIN32_WINNT)) + +int main(void) +{ + return 0; +} +#endif diff --git a/third_party/curl/CMake/FindBearSSL.cmake b/third_party/curl/CMake/FindBearSSL.cmake new file mode 100644 index 0000000..56a064e --- /dev/null +++ b/third_party/curl/CMake/FindBearSSL.cmake @@ -0,0 +1,32 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +find_path(BEARSSL_INCLUDE_DIRS bearssl.h) + +find_library(BEARSSL_LIBRARY bearssl) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(BEARSSL DEFAULT_MSG + BEARSSL_INCLUDE_DIRS BEARSSL_LIBRARY) + +mark_as_advanced(BEARSSL_INCLUDE_DIRS BEARSSL_LIBRARY) diff --git a/third_party/curl/CMake/FindBrotli.cmake b/third_party/curl/CMake/FindBrotli.cmake new file mode 100644 index 0000000..11ab7f8 --- /dev/null +++ b/third_party/curl/CMake/FindBrotli.cmake @@ -0,0 +1,43 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +include(FindPackageHandleStandardArgs) + +find_path(BROTLI_INCLUDE_DIR "brotli/decode.h") + +find_library(BROTLICOMMON_LIBRARY NAMES brotlicommon) +find_library(BROTLIDEC_LIBRARY NAMES brotlidec) + +find_package_handle_standard_args(Brotli + FOUND_VAR + BROTLI_FOUND + REQUIRED_VARS + BROTLIDEC_LIBRARY + BROTLICOMMON_LIBRARY + BROTLI_INCLUDE_DIR + FAIL_MESSAGE + "Could NOT find Brotli" +) + +set(BROTLI_INCLUDE_DIRS ${BROTLI_INCLUDE_DIR}) +set(BROTLI_LIBRARIES ${BROTLICOMMON_LIBRARY} ${BROTLIDEC_LIBRARY}) diff --git a/third_party/curl/CMake/FindCARES.cmake b/third_party/curl/CMake/FindCARES.cmake new file mode 100644 index 0000000..fa75891 --- /dev/null +++ b/third_party/curl/CMake/FindCARES.cmake @@ -0,0 +1,47 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# - Find c-ares +# Find the c-ares includes and library +# This module defines +# CARES_INCLUDE_DIR, where to find ares.h, etc. +# CARES_LIBRARIES, the libraries needed to use c-ares. +# CARES_FOUND, If false, do not try to use c-ares. +# also defined, but not for general use are +# CARES_LIBRARY, where to find the c-ares library. + +find_path(CARES_INCLUDE_DIR ares.h) + +set(CARES_NAMES ${CARES_NAMES} cares) +find_library(CARES_LIBRARY + NAMES ${CARES_NAMES} + ) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(CARES + REQUIRED_VARS CARES_LIBRARY CARES_INCLUDE_DIR) + +mark_as_advanced( + CARES_LIBRARY + CARES_INCLUDE_DIR + ) diff --git a/third_party/curl/CMake/FindGSS.cmake b/third_party/curl/CMake/FindGSS.cmake new file mode 100644 index 0000000..b244e61 --- /dev/null +++ b/third_party/curl/CMake/FindGSS.cmake @@ -0,0 +1,312 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# - Try to find the GSS Kerberos library +# Once done this will define +# +# GSS_ROOT_DIR - Set this variable to the root installation of GSS +# +# Read-Only variables: +# GSS_FOUND - system has the Heimdal library +# GSS_FLAVOUR - "MIT" or "Heimdal" if anything found. +# GSS_INCLUDE_DIR - the Heimdal include directory +# GSS_LIBRARIES - The libraries needed to use GSS +# GSS_LINK_DIRECTORIES - Directories to add to linker search path +# GSS_LINKER_FLAGS - Additional linker flags +# GSS_COMPILER_FLAGS - Additional compiler flags +# GSS_VERSION - This is set to version advertised by pkg-config or read from manifest. +# In case the library is found but no version info available it'll be set to "unknown" + +set(_MIT_MODNAME mit-krb5-gssapi) +set(_HEIMDAL_MODNAME heimdal-gssapi) + +include(CheckIncludeFile) +include(CheckIncludeFiles) +include(CheckTypeSize) + +set(_GSS_ROOT_HINTS + "${GSS_ROOT_DIR}" + "$ENV{GSS_ROOT_DIR}" +) + +# try to find library using system pkg-config if user didn't specify root dir +if(NOT GSS_ROOT_DIR AND NOT "$ENV{GSS_ROOT_DIR}") + if(UNIX) + find_package(PkgConfig QUIET) + pkg_search_module(_GSS_PKG ${_MIT_MODNAME} ${_HEIMDAL_MODNAME}) + list(APPEND _GSS_ROOT_HINTS "${_GSS_PKG_PREFIX}") + elseif(WIN32) + list(APPEND _GSS_ROOT_HINTS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MIT\\Kerberos;InstallDir]") + endif() +endif() + +if(NOT _GSS_FOUND) #not found by pkg-config. Let's take more traditional approach. + find_file(_GSS_CONFIGURE_SCRIPT + NAMES + "krb5-config" + HINTS + ${_GSS_ROOT_HINTS} + PATH_SUFFIXES + bin + NO_CMAKE_PATH + NO_CMAKE_ENVIRONMENT_PATH + ) + + # if not found in user-supplied directories, maybe system knows better + find_file(_GSS_CONFIGURE_SCRIPT + NAMES + "krb5-config" + PATH_SUFFIXES + bin + ) + + if(_GSS_CONFIGURE_SCRIPT) + execute_process( + COMMAND ${_GSS_CONFIGURE_SCRIPT} "--cflags" "gssapi" + OUTPUT_VARIABLE _GSS_CFLAGS + RESULT_VARIABLE _GSS_CONFIGURE_FAILED + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + message(STATUS "CFLAGS: ${_GSS_CFLAGS}") + if(NOT _GSS_CONFIGURE_FAILED) # 0 means success + # should also work in an odd case when multiple directories are given + string(STRIP "${_GSS_CFLAGS}" _GSS_CFLAGS) + string(REGEX REPLACE " +-I" ";" _GSS_CFLAGS "${_GSS_CFLAGS}") + string(REGEX REPLACE " +-([^I][^ \\t;]*)" ";-\\1" _GSS_CFLAGS "${_GSS_CFLAGS}") + + foreach(_flag ${_GSS_CFLAGS}) + if(_flag MATCHES "^-I.*") + string(REGEX REPLACE "^-I" "" _val "${_flag}") + list(APPEND _GSS_INCLUDE_DIR "${_val}") + else() + list(APPEND _GSS_COMPILER_FLAGS "${_flag}") + endif() + endforeach() + endif() + + execute_process( + COMMAND ${_GSS_CONFIGURE_SCRIPT} "--libs" "gssapi" + OUTPUT_VARIABLE _GSS_LIB_FLAGS + RESULT_VARIABLE _GSS_CONFIGURE_FAILED + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + message(STATUS "LDFLAGS: ${_GSS_LIB_FLAGS}") + + if(NOT _GSS_CONFIGURE_FAILED) # 0 means success + # this script gives us libraries and link directories. Blah. We have to deal with it. + string(STRIP "${_GSS_LIB_FLAGS}" _GSS_LIB_FLAGS) + string(REGEX REPLACE " +-(L|l)" ";-\\1" _GSS_LIB_FLAGS "${_GSS_LIB_FLAGS}") + string(REGEX REPLACE " +-([^Ll][^ \\t;]*)" ";-\\1" _GSS_LIB_FLAGS "${_GSS_LIB_FLAGS}") + + foreach(_flag ${_GSS_LIB_FLAGS}) + if(_flag MATCHES "^-l.*") + string(REGEX REPLACE "^-l" "" _val "${_flag}") + list(APPEND _GSS_LIBRARIES "${_val}") + elseif(_flag MATCHES "^-L.*") + string(REGEX REPLACE "^-L" "" _val "${_flag}") + list(APPEND _GSS_LINK_DIRECTORIES "${_val}") + else() + list(APPEND _GSS_LINKER_FLAGS "${_flag}") + endif() + endforeach() + endif() + + execute_process( + COMMAND ${_GSS_CONFIGURE_SCRIPT} "--version" + OUTPUT_VARIABLE _GSS_VERSION + RESULT_VARIABLE _GSS_CONFIGURE_FAILED + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + + # older versions may not have the "--version" parameter. In this case we just don't care. + if(_GSS_CONFIGURE_FAILED) + set(_GSS_VERSION 0) + endif() + + execute_process( + COMMAND ${_GSS_CONFIGURE_SCRIPT} "--vendor" + OUTPUT_VARIABLE _GSS_VENDOR + RESULT_VARIABLE _GSS_CONFIGURE_FAILED + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + + # older versions may not have the "--vendor" parameter. In this case we just don't care. + if(_GSS_CONFIGURE_FAILED) + set(GSS_FLAVOUR "Heimdal") # most probably, shouldn't really matter + else() + if(_GSS_VENDOR MATCHES ".*H|heimdal.*") + set(GSS_FLAVOUR "Heimdal") + else() + set(GSS_FLAVOUR "MIT") + endif() + endif() + + else() # either there is no config script or we are on a platform that doesn't provide one (Windows?) + + find_path(_GSS_INCLUDE_DIR + NAMES + "gssapi/gssapi.h" + HINTS + ${_GSS_ROOT_HINTS} + PATH_SUFFIXES + include + inc + ) + + if(_GSS_INCLUDE_DIR) #jay, we've found something + set(CMAKE_REQUIRED_INCLUDES "${_GSS_INCLUDE_DIR}") + check_include_files( "gssapi/gssapi_generic.h;gssapi/gssapi_krb5.h" _GSS_HAVE_MIT_HEADERS) + + if(_GSS_HAVE_MIT_HEADERS) + set(GSS_FLAVOUR "MIT") + else() + # prevent compiling the header - just check if we can include it + list(APPEND CMAKE_REQUIRED_DEFINITIONS -D__ROKEN_H__) + check_include_file( "roken.h" _GSS_HAVE_ROKEN_H) + + check_include_file( "heimdal/roken.h" _GSS_HAVE_HEIMDAL_ROKEN_H) + if(_GSS_HAVE_ROKEN_H OR _GSS_HAVE_HEIMDAL_ROKEN_H) + set(GSS_FLAVOUR "Heimdal") + endif() + list(REMOVE_ITEM CMAKE_REQUIRED_DEFINITIONS -D__ROKEN_H__) + endif() + else() + # I'm not convinced if this is the right way but this is what autotools do at the moment + find_path(_GSS_INCLUDE_DIR + NAMES + "gssapi.h" + HINTS + ${_GSS_ROOT_HINTS} + PATH_SUFFIXES + include + inc + ) + + if(_GSS_INCLUDE_DIR) + set(GSS_FLAVOUR "Heimdal") + endif() + endif() + + # if we have headers, check if we can link libraries + if(GSS_FLAVOUR) + set(_GSS_LIBDIR_SUFFIXES "") + set(_GSS_LIBDIR_HINTS ${_GSS_ROOT_HINTS}) + get_filename_component(_GSS_CALCULATED_POTENTIAL_ROOT "${_GSS_INCLUDE_DIR}" PATH) + list(APPEND _GSS_LIBDIR_HINTS ${_GSS_CALCULATED_POTENTIAL_ROOT}) + + if(WIN32) + if(CMAKE_SIZEOF_VOID_P EQUAL 8) + list(APPEND _GSS_LIBDIR_SUFFIXES "lib/AMD64") + if(GSS_FLAVOUR STREQUAL "MIT") + set(_GSS_LIBNAME "gssapi64") + else() + set(_GSS_LIBNAME "libgssapi") + endif() + else() + list(APPEND _GSS_LIBDIR_SUFFIXES "lib/i386") + if(GSS_FLAVOUR STREQUAL "MIT") + set(_GSS_LIBNAME "gssapi32") + else() + set(_GSS_LIBNAME "libgssapi") + endif() + endif() + else() + list(APPEND _GSS_LIBDIR_SUFFIXES "lib;lib64") # those suffixes are not checked for HINTS + if(GSS_FLAVOUR STREQUAL "MIT") + set(_GSS_LIBNAME "gssapi_krb5") + else() + set(_GSS_LIBNAME "gssapi") + endif() + endif() + + find_library(_GSS_LIBRARIES + NAMES + ${_GSS_LIBNAME} + HINTS + ${_GSS_LIBDIR_HINTS} + PATH_SUFFIXES + ${_GSS_LIBDIR_SUFFIXES} + ) + + endif() + endif() +else() + if(_GSS_PKG_${_MIT_MODNAME}_VERSION) + set(GSS_FLAVOUR "MIT") + set(_GSS_VERSION _GSS_PKG_${_MIT_MODNAME}_VERSION) + else() + set(GSS_FLAVOUR "Heimdal") + set(_GSS_VERSION _GSS_PKG_${_MIT_HEIMDAL}_VERSION) + endif() +endif() + +set(GSS_INCLUDE_DIR ${_GSS_INCLUDE_DIR}) +set(GSS_LIBRARIES ${_GSS_LIBRARIES}) +set(GSS_LINK_DIRECTORIES ${_GSS_LINK_DIRECTORIES}) +set(GSS_LINKER_FLAGS ${_GSS_LINKER_FLAGS}) +set(GSS_COMPILER_FLAGS ${_GSS_COMPILER_FLAGS}) +set(GSS_VERSION ${_GSS_VERSION}) + +if(GSS_FLAVOUR) + if(NOT GSS_VERSION AND GSS_FLAVOUR STREQUAL "Heimdal") + if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(HEIMDAL_MANIFEST_FILE "Heimdal.Application.amd64.manifest") + else() + set(HEIMDAL_MANIFEST_FILE "Heimdal.Application.x86.manifest") + endif() + + if(EXISTS "${GSS_INCLUDE_DIR}/${HEIMDAL_MANIFEST_FILE}") + file(STRINGS "${GSS_INCLUDE_DIR}/${HEIMDAL_MANIFEST_FILE}" heimdal_version_str + REGEX "^.*version=\"[0-9]\\.[^\"]+\".*$") + + string(REGEX MATCH "[0-9]\\.[^\"]+" + GSS_VERSION "${heimdal_version_str}") + endif() + + if(NOT GSS_VERSION) + set(GSS_VERSION "Heimdal Unknown") + endif() + elseif(NOT GSS_VERSION AND GSS_FLAVOUR STREQUAL "MIT") + get_filename_component(_MIT_VERSION "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MIT\\Kerberos\\SDK\\CurrentVersion;VersionString]" NAME CACHE) + if(WIN32 AND _MIT_VERSION) + set(GSS_VERSION "${_MIT_VERSION}") + else() + set(GSS_VERSION "MIT Unknown") + endif() + endif() +endif() + +include(FindPackageHandleStandardArgs) + +set(_GSS_REQUIRED_VARS GSS_LIBRARIES GSS_FLAVOUR) + +find_package_handle_standard_args(GSS + REQUIRED_VARS + ${_GSS_REQUIRED_VARS} + VERSION_VAR + GSS_VERSION + FAIL_MESSAGE + "Could NOT find GSS, try to set the path to GSS root folder in the system variable GSS_ROOT_DIR" +) + +mark_as_advanced(GSS_INCLUDE_DIR GSS_LIBRARIES) diff --git a/third_party/curl/CMake/FindLibPSL.cmake b/third_party/curl/CMake/FindLibPSL.cmake new file mode 100644 index 0000000..e3bd68d --- /dev/null +++ b/third_party/curl/CMake/FindLibPSL.cmake @@ -0,0 +1,45 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# - Try to find the libpsl library +# Once done this will define +# +# LIBPSL_FOUND - system has the libpsl library +# LIBPSL_INCLUDE_DIR - the libpsl include directory +# LIBPSL_LIBRARY - the libpsl library name + +find_path(LIBPSL_INCLUDE_DIR libpsl.h) + +find_library(LIBPSL_LIBRARY NAMES psl libpsl) + +if(LIBPSL_INCLUDE_DIR) + file(STRINGS "${LIBPSL_INCLUDE_DIR}/libpsl.h" libpsl_version_str REGEX "^#define[\t ]+PSL_VERSION[\t ]+\"(.*)\"") + string(REGEX REPLACE "^.*\"([^\"]+)\"" "\\1" LIBPSL_VERSION "${libpsl_version_str}") +endif() + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(LibPSL + REQUIRED_VARS LIBPSL_LIBRARY LIBPSL_INCLUDE_DIR + VERSION_VAR LIBPSL_VERSION) + +mark_as_advanced(LIBPSL_INCLUDE_DIR LIBPSL_LIBRARY) diff --git a/third_party/curl/CMake/FindLibSSH2.cmake b/third_party/curl/CMake/FindLibSSH2.cmake new file mode 100644 index 0000000..a0c251a --- /dev/null +++ b/third_party/curl/CMake/FindLibSSH2.cmake @@ -0,0 +1,45 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# - Try to find the libssh2 library +# Once done this will define +# +# LIBSSH2_FOUND - system has the libssh2 library +# LIBSSH2_INCLUDE_DIR - the libssh2 include directory +# LIBSSH2_LIBRARY - the libssh2 library name + +find_path(LIBSSH2_INCLUDE_DIR libssh2.h) + +find_library(LIBSSH2_LIBRARY NAMES ssh2 libssh2) + +if(LIBSSH2_INCLUDE_DIR) + file(STRINGS "${LIBSSH2_INCLUDE_DIR}/libssh2.h" libssh2_version_str REGEX "^#define[\t ]+LIBSSH2_VERSION[\t ]+\"(.*)\"") + string(REGEX REPLACE "^.*\"([^\"]+)\"" "\\1" LIBSSH2_VERSION "${libssh2_version_str}") +endif() + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(LibSSH2 + REQUIRED_VARS LIBSSH2_LIBRARY LIBSSH2_INCLUDE_DIR + VERSION_VAR LIBSSH2_VERSION) + +mark_as_advanced(LIBSSH2_INCLUDE_DIR LIBSSH2_LIBRARY) diff --git a/third_party/curl/CMake/FindMSH3.cmake b/third_party/curl/CMake/FindMSH3.cmake new file mode 100644 index 0000000..7d9c6b6 --- /dev/null +++ b/third_party/curl/CMake/FindMSH3.cmake @@ -0,0 +1,70 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +#[=======================================================================[.rst: +FindMSH3 +---------- + +Find the msh3 library + +Result Variables +^^^^^^^^^^^^^^^^ + +``MSH3_FOUND`` + System has msh3 +``MSH3_INCLUDE_DIRS`` + The msh3 include directories. +``MSH3_LIBRARIES`` + The libraries needed to use msh3 +#]=======================================================================] +if(UNIX) + find_package(PkgConfig QUIET) + pkg_search_module(PC_MSH3 libmsh3) +endif() + +find_path(MSH3_INCLUDE_DIR msh3.h + HINTS + ${PC_MSH3_INCLUDEDIR} + ${PC_MSH3_INCLUDE_DIRS} +) + +find_library(MSH3_LIBRARY NAMES msh3 + HINTS + ${PC_MSH3_LIBDIR} + ${PC_MSH3_LIBRARY_DIRS} +) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(MSH3 + REQUIRED_VARS + MSH3_LIBRARY + MSH3_INCLUDE_DIR +) + +if(MSH3_FOUND) + set(MSH3_LIBRARIES ${MSH3_LIBRARY}) + set(MSH3_INCLUDE_DIRS ${MSH3_INCLUDE_DIR}) +endif() + +mark_as_advanced(MSH3_INCLUDE_DIRS MSH3_LIBRARIES) diff --git a/third_party/curl/CMake/FindMbedTLS.cmake b/third_party/curl/CMake/FindMbedTLS.cmake new file mode 100644 index 0000000..814bd97 --- /dev/null +++ b/third_party/curl/CMake/FindMbedTLS.cmake @@ -0,0 +1,36 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +find_path(MBEDTLS_INCLUDE_DIRS mbedtls/ssl.h) + +find_library(MBEDTLS_LIBRARY mbedtls) +find_library(MBEDX509_LIBRARY mbedx509) +find_library(MBEDCRYPTO_LIBRARY mbedcrypto) + +set(MBEDTLS_LIBRARIES "${MBEDTLS_LIBRARY}" "${MBEDX509_LIBRARY}" "${MBEDCRYPTO_LIBRARY}") + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(MbedTLS DEFAULT_MSG + MBEDTLS_INCLUDE_DIRS MBEDTLS_LIBRARY MBEDX509_LIBRARY MBEDCRYPTO_LIBRARY) + +mark_as_advanced(MBEDTLS_INCLUDE_DIRS MBEDTLS_LIBRARY MBEDX509_LIBRARY MBEDCRYPTO_LIBRARY) diff --git a/third_party/curl/CMake/FindNGHTTP2.cmake b/third_party/curl/CMake/FindNGHTTP2.cmake new file mode 100644 index 0000000..d3528cb --- /dev/null +++ b/third_party/curl/CMake/FindNGHTTP2.cmake @@ -0,0 +1,41 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +include(FindPackageHandleStandardArgs) + +find_path(NGHTTP2_INCLUDE_DIR "nghttp2/nghttp2.h") + +find_library(NGHTTP2_LIBRARY NAMES nghttp2 nghttp2_static) + +find_package_handle_standard_args(NGHTTP2 + FOUND_VAR + NGHTTP2_FOUND + REQUIRED_VARS + NGHTTP2_LIBRARY + NGHTTP2_INCLUDE_DIR +) + +set(NGHTTP2_INCLUDE_DIRS ${NGHTTP2_INCLUDE_DIR}) +set(NGHTTP2_LIBRARIES ${NGHTTP2_LIBRARY}) + +mark_as_advanced(NGHTTP2_INCLUDE_DIRS NGHTTP2_LIBRARIES) diff --git a/third_party/curl/CMake/FindNGHTTP3.cmake b/third_party/curl/CMake/FindNGHTTP3.cmake new file mode 100644 index 0000000..9b13e6c --- /dev/null +++ b/third_party/curl/CMake/FindNGHTTP3.cmake @@ -0,0 +1,78 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +#[=======================================================================[.rst: +FindNGHTTP3 +---------- + +Find the nghttp3 library + +Result Variables +^^^^^^^^^^^^^^^^ + +``NGHTTP3_FOUND`` + System has nghttp3 +``NGHTTP3_INCLUDE_DIRS`` + The nghttp3 include directories. +``NGHTTP3_LIBRARIES`` + The libraries needed to use nghttp3 +``NGHTTP3_VERSION`` + version of nghttp3. +#]=======================================================================] + +if(UNIX) + find_package(PkgConfig QUIET) + pkg_search_module(PC_NGHTTP3 libnghttp3) +endif() + +find_path(NGHTTP3_INCLUDE_DIR nghttp3/nghttp3.h + HINTS + ${PC_NGHTTP3_INCLUDEDIR} + ${PC_NGHTTP3_INCLUDE_DIRS} +) + +find_library(NGHTTP3_LIBRARY NAMES nghttp3 + HINTS + ${PC_NGHTTP3_LIBDIR} + ${PC_NGHTTP3_LIBRARY_DIRS} +) + +if(PC_NGHTTP3_VERSION) + set(NGHTTP3_VERSION ${PC_NGHTTP3_VERSION}) +endif() + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(NGHTTP3 + REQUIRED_VARS + NGHTTP3_LIBRARY + NGHTTP3_INCLUDE_DIR + VERSION_VAR NGHTTP3_VERSION +) + +if(NGHTTP3_FOUND) + set(NGHTTP3_LIBRARIES ${NGHTTP3_LIBRARY}) + set(NGHTTP3_INCLUDE_DIRS ${NGHTTP3_INCLUDE_DIR}) +endif() + +mark_as_advanced(NGHTTP3_INCLUDE_DIRS NGHTTP3_LIBRARIES) diff --git a/third_party/curl/CMake/FindNGTCP2.cmake b/third_party/curl/CMake/FindNGTCP2.cmake new file mode 100644 index 0000000..7ea4665 --- /dev/null +++ b/third_party/curl/CMake/FindNGTCP2.cmake @@ -0,0 +1,117 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +#[=======================================================================[.rst: +FindNGTCP2 +---------- + +Find the ngtcp2 library + +This module accepts optional COMPONENTS to control the crypto library (these are +mutually exclusive):: + + quictls, LibreSSL: Use libngtcp2_crypto_quictls + BoringSSL, AWS-LC: Use libngtcp2_crypto_boringssl + wolfSSL: Use libngtcp2_crypto_wolfssl + GnuTLS: Use libngtcp2_crypto_gnutls + +Result Variables +^^^^^^^^^^^^^^^^ + +``NGTCP2_FOUND`` + System has ngtcp2 +``NGTCP2_INCLUDE_DIRS`` + The ngtcp2 include directories. +``NGTCP2_LIBRARIES`` + The libraries needed to use ngtcp2 +``NGTCP2_VERSION`` + version of ngtcp2. +#]=======================================================================] + +if(UNIX) + find_package(PkgConfig QUIET) + pkg_search_module(PC_NGTCP2 libngtcp2) +endif() + +find_path(NGTCP2_INCLUDE_DIR ngtcp2/ngtcp2.h + HINTS + ${PC_NGTCP2_INCLUDEDIR} + ${PC_NGTCP2_INCLUDE_DIRS} +) + +find_library(NGTCP2_LIBRARY NAMES ngtcp2 + HINTS + ${PC_NGTCP2_LIBDIR} + ${PC_NGTCP2_LIBRARY_DIRS} +) + +if(PC_NGTCP2_VERSION) + set(NGTCP2_VERSION ${PC_NGTCP2_VERSION}) +endif() + +if(NGTCP2_FIND_COMPONENTS) + set(NGTCP2_CRYPTO_BACKEND "") + foreach(component IN LISTS NGTCP2_FIND_COMPONENTS) + if(component MATCHES "^(BoringSSL|quictls|wolfSSL|GnuTLS)") + if(NGTCP2_CRYPTO_BACKEND) + message(FATAL_ERROR "NGTCP2: Only one crypto library can be selected") + endif() + set(NGTCP2_CRYPTO_BACKEND ${component}) + endif() + endforeach() + + if(NGTCP2_CRYPTO_BACKEND) + string(TOLOWER "ngtcp2_crypto_${NGTCP2_CRYPTO_BACKEND}" _crypto_library) + if(UNIX) + pkg_search_module(PC_${_crypto_library} lib${_crypto_library}) + endif() + find_library(${_crypto_library}_LIBRARY + NAMES + ${_crypto_library} + HINTS + ${PC_${_crypto_library}_LIBDIR} + ${PC_${_crypto_library}_LIBRARY_DIRS} + ) + if(${_crypto_library}_LIBRARY) + set(NGTCP2_${NGTCP2_CRYPTO_BACKEND}_FOUND TRUE) + set(NGTCP2_CRYPTO_LIBRARY ${${_crypto_library}_LIBRARY}) + endif() + endif() +endif() + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(NGTCP2 + REQUIRED_VARS + NGTCP2_LIBRARY + NGTCP2_INCLUDE_DIR + VERSION_VAR NGTCP2_VERSION + HANDLE_COMPONENTS +) + +if(NGTCP2_FOUND) + set(NGTCP2_LIBRARIES ${NGTCP2_LIBRARY} ${NGTCP2_CRYPTO_LIBRARY}) + set(NGTCP2_INCLUDE_DIRS ${NGTCP2_INCLUDE_DIR}) +endif() + +mark_as_advanced(NGTCP2_INCLUDE_DIRS NGTCP2_LIBRARIES) diff --git a/third_party/curl/CMake/FindQUICHE.cmake b/third_party/curl/CMake/FindQUICHE.cmake new file mode 100644 index 0000000..0488463 --- /dev/null +++ b/third_party/curl/CMake/FindQUICHE.cmake @@ -0,0 +1,70 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +#[=======================================================================[.rst: +FindQUICHE +---------- + +Find the quiche library + +Result Variables +^^^^^^^^^^^^^^^^ + +``QUICHE_FOUND`` + System has quiche +``QUICHE_INCLUDE_DIRS`` + The quiche include directories. +``QUICHE_LIBRARIES`` + The libraries needed to use quiche +#]=======================================================================] +if(UNIX) + find_package(PkgConfig QUIET) + pkg_search_module(PC_QUICHE quiche) +endif() + +find_path(QUICHE_INCLUDE_DIR quiche.h + HINTS + ${PC_QUICHE_INCLUDEDIR} + ${PC_QUICHE_INCLUDE_DIRS} +) + +find_library(QUICHE_LIBRARY NAMES quiche + HINTS + ${PC_QUICHE_LIBDIR} + ${PC_QUICHE_LIBRARY_DIRS} +) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(QUICHE + REQUIRED_VARS + QUICHE_LIBRARY + QUICHE_INCLUDE_DIR +) + +if(QUICHE_FOUND) + set(QUICHE_LIBRARIES ${QUICHE_LIBRARY}) + set(QUICHE_INCLUDE_DIRS ${QUICHE_INCLUDE_DIR}) +endif() + +mark_as_advanced(QUICHE_INCLUDE_DIRS QUICHE_LIBRARIES) diff --git a/third_party/curl/CMake/FindWolfSSL.cmake b/third_party/curl/CMake/FindWolfSSL.cmake new file mode 100644 index 0000000..d67c0eb --- /dev/null +++ b/third_party/curl/CMake/FindWolfSSL.cmake @@ -0,0 +1,36 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +find_path(WolfSSL_INCLUDE_DIR NAMES wolfssl/ssl.h) +find_library(WolfSSL_LIBRARY NAMES wolfssl) +mark_as_advanced(WolfSSL_INCLUDE_DIR WolfSSL_LIBRARY) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(WolfSSL + REQUIRED_VARS WolfSSL_INCLUDE_DIR WolfSSL_LIBRARY + ) + +if(WolfSSL_FOUND) + set(WolfSSL_INCLUDE_DIRS ${WolfSSL_INCLUDE_DIR}) + set(WolfSSL_LIBRARIES ${WolfSSL_LIBRARY}) +endif() diff --git a/third_party/curl/CMake/FindZstd.cmake b/third_party/curl/CMake/FindZstd.cmake new file mode 100644 index 0000000..0ea9e0c --- /dev/null +++ b/third_party/curl/CMake/FindZstd.cmake @@ -0,0 +1,78 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +#[=======================================================================[.rst: +FindZstd +---------- + +Find the zstd library + +Result Variables +^^^^^^^^^^^^^^^^ + +``Zstd_FOUND`` + System has zstd +``Zstd_INCLUDE_DIRS`` + The zstd include directories. +``Zstd_LIBRARIES`` + The libraries needed to use zstd +#]=======================================================================] + +if(UNIX) + find_package(PkgConfig QUIET) + pkg_search_module(PC_Zstd libzstd) +endif() + +find_path(Zstd_INCLUDE_DIR zstd.h + HINTS + ${PC_Zstd_INCLUDEDIR} + ${PC_Zstd_INCLUDE_DIRS} +) + +find_library(Zstd_LIBRARY NAMES zstd + HINTS + ${PC_Zstd_LIBDIR} + ${PC_Zstd_LIBRARY_DIRS} +) + +if(Zstd_INCLUDE_DIR) + file(READ "${Zstd_INCLUDE_DIR}/zstd.h" _zstd_header) + string(REGEX MATCH ".*define ZSTD_VERSION_MAJOR *([0-9]+).*define ZSTD_VERSION_MINOR *([0-9]+).*define ZSTD_VERSION_RELEASE *([0-9]+)" _zstd_ver "${_zstd_header}") + set(Zstd_VERSION "${CMAKE_MATCH_1}.${CMAKE_MATCH_2}.${CMAKE_MATCH_3}") +endif() + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(Zstd + REQUIRED_VARS + Zstd_LIBRARY + Zstd_INCLUDE_DIR + VERSION_VAR Zstd_VERSION +) + +if(Zstd_FOUND) + set(Zstd_LIBRARIES ${Zstd_LIBRARY}) + set(Zstd_INCLUDE_DIRS ${Zstd_INCLUDE_DIR}) +endif() + +mark_as_advanced(Zstd_INCLUDE_DIRS Zstd_LIBRARIES) diff --git a/third_party/curl/CMake/Macros.cmake b/third_party/curl/CMake/Macros.cmake new file mode 100644 index 0000000..d5439fc --- /dev/null +++ b/third_party/curl/CMake/Macros.cmake @@ -0,0 +1,80 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +#File defines convenience macros for available feature testing + +# Check if header file exists and add it to the list. +# This macro is intended to be called multiple times with a sequence of +# possibly dependent header files. Some headers depend on others to be +# compiled correctly. +macro(check_include_file_concat FILE VARIABLE) + check_include_files("${CURL_INCLUDES};${FILE}" ${VARIABLE}) + if(${VARIABLE}) + set(CURL_INCLUDES ${CURL_INCLUDES} ${FILE}) + set(CURL_TEST_DEFINES "${CURL_TEST_DEFINES} -D${VARIABLE}") + endif() +endmacro() + +# For other curl specific tests, use this macro. +macro(curl_internal_test CURL_TEST) + if(NOT DEFINED "${CURL_TEST}") + set(MACRO_CHECK_FUNCTION_DEFINITIONS + "-D${CURL_TEST} ${CURL_TEST_DEFINES} ${CMAKE_REQUIRED_FLAGS}") + if(CMAKE_REQUIRED_LIBRARIES) + set(CURL_TEST_ADD_LIBRARIES + "-DLINK_LIBRARIES:STRING=${CMAKE_REQUIRED_LIBRARIES}") + endif() + + message(STATUS "Performing Test ${CURL_TEST}") + try_compile(${CURL_TEST} + ${CMAKE_BINARY_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/CMake/CurlTests.c + CMAKE_FLAGS -DCOMPILE_DEFINITIONS:STRING=${MACRO_CHECK_FUNCTION_DEFINITIONS} + "${CURL_TEST_ADD_LIBRARIES}" + OUTPUT_VARIABLE OUTPUT) + if(${CURL_TEST}) + set(${CURL_TEST} 1 CACHE INTERNAL "Curl test ${FUNCTION}") + message(STATUS "Performing Test ${CURL_TEST} - Success") + file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log + "Performing Test ${CURL_TEST} passed with the following output:\n" + "${OUTPUT}\n") + else() + message(STATUS "Performing Test ${CURL_TEST} - Failed") + set(${CURL_TEST} "" CACHE INTERNAL "Curl test ${FUNCTION}") + file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log + "Performing Test ${CURL_TEST} failed with the following output:\n" + "${OUTPUT}\n") + endif() + endif() +endmacro() + +macro(optional_dependency DEPENDENCY) + set(CURL_${DEPENDENCY} AUTO CACHE STRING "Build curl with ${DEPENDENCY} support (AUTO, ON or OFF)") + set_property(CACHE CURL_${DEPENDENCY} PROPERTY STRINGS AUTO ON OFF) + + if(CURL_${DEPENDENCY} STREQUAL AUTO) + find_package(${DEPENDENCY}) + elseif(CURL_${DEPENDENCY}) + find_package(${DEPENDENCY} REQUIRED) + endif() +endmacro() diff --git a/third_party/curl/CMake/OtherTests.cmake b/third_party/curl/CMake/OtherTests.cmake new file mode 100644 index 0000000..7701c0e --- /dev/null +++ b/third_party/curl/CMake/OtherTests.cmake @@ -0,0 +1,184 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +include(CheckCSourceCompiles) +include(CheckCSourceRuns) +include(CheckTypeSize) + +macro(add_header_include check header) + if(${check}) + set(_source_epilogue "${_source_epilogue} + #include <${header}>") + endif() +endmacro() + +set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) + +if(NOT DEFINED HAVE_STRUCT_SOCKADDR_STORAGE) + set(CMAKE_EXTRA_INCLUDE_FILES) + if(WIN32) + set(CMAKE_EXTRA_INCLUDE_FILES "winsock2.h") + set(CMAKE_REQUIRED_DEFINITIONS "-DWIN32_LEAN_AND_MEAN") + set(CMAKE_REQUIRED_LIBRARIES "ws2_32") + elseif(HAVE_SYS_SOCKET_H) + set(CMAKE_EXTRA_INCLUDE_FILES "sys/socket.h") + endif() + check_type_size("struct sockaddr_storage" SIZEOF_STRUCT_SOCKADDR_STORAGE) + set(HAVE_STRUCT_SOCKADDR_STORAGE ${HAVE_SIZEOF_STRUCT_SOCKADDR_STORAGE}) +endif() + +if(NOT WIN32) + set(_source_epilogue "#undef inline") + add_header_include(HAVE_SYS_TYPES_H "sys/types.h") + add_header_include(HAVE_SYS_SOCKET_H "sys/socket.h") + check_c_source_compiles("${_source_epilogue} + int main(void) + { + int flag = MSG_NOSIGNAL; + (void)flag; + return 0; + }" HAVE_MSG_NOSIGNAL) +endif() + +set(_source_epilogue "#undef inline") +add_header_include(HAVE_SYS_TIME_H "sys/time.h") +check_c_source_compiles("${_source_epilogue} + #include + int main(void) + { + struct timeval ts; + ts.tv_sec = 0; + ts.tv_usec = 0; + (void)ts; + return 0; + }" HAVE_STRUCT_TIMEVAL) + +unset(CMAKE_TRY_COMPILE_TARGET_TYPE) + +if(NOT CMAKE_CROSSCOMPILING AND NOT APPLE) + set(_source_epilogue "#undef inline") + add_header_include(HAVE_SYS_POLL_H "sys/poll.h") + add_header_include(HAVE_POLL_H "poll.h") + check_c_source_runs("${_source_epilogue} + #include + #include + int main(void) + { + if(0 != poll(0, 0, 10)) { + return 1; /* fail */ + } + else { + /* detect the 10.12 poll() breakage */ + struct timeval before, after; + int rc; + size_t us; + + gettimeofday(&before, NULL); + rc = poll(NULL, 0, 500); + gettimeofday(&after, NULL); + + us = (after.tv_sec - before.tv_sec) * 1000000 + + (after.tv_usec - before.tv_usec); + + if(us < 400000) { + return 1; + } + } + return 0; + }" HAVE_POLL_FINE) +endif() + +# Detect HAVE_GETADDRINFO_THREADSAFE + +if(WIN32) + set(HAVE_GETADDRINFO_THREADSAFE ${HAVE_GETADDRINFO}) +elseif(NOT HAVE_GETADDRINFO) + set(HAVE_GETADDRINFO_THREADSAFE FALSE) +elseif(APPLE OR + CMAKE_SYSTEM_NAME STREQUAL "AIX" OR + CMAKE_SYSTEM_NAME STREQUAL "FreeBSD" OR + CMAKE_SYSTEM_NAME STREQUAL "HP-UX" OR + CMAKE_SYSTEM_NAME STREQUAL "MidnightBSD" OR + CMAKE_SYSTEM_NAME STREQUAL "NetBSD" OR + CMAKE_SYSTEM_NAME STREQUAL "SunOS") + set(HAVE_GETADDRINFO_THREADSAFE TRUE) +elseif(CMAKE_SYSTEM_NAME MATCHES "BSD") + set(HAVE_GETADDRINFO_THREADSAFE FALSE) +endif() + +if(NOT DEFINED HAVE_GETADDRINFO_THREADSAFE) + set(_source_epilogue "#undef inline") + add_header_include(HAVE_SYS_SOCKET_H "sys/socket.h") + add_header_include(HAVE_SYS_TIME_H "sys/time.h") + add_header_include(HAVE_NETDB_H "netdb.h") + check_c_source_compiles("${_source_epilogue} + int main(void) + { + #ifdef h_errno + return 0; + #else + force compilation error + #endif + }" HAVE_H_ERRNO) + + if(NOT HAVE_H_ERRNO) + check_c_source_compiles("${_source_epilogue} + int main(void) + { + h_errno = 2; + return h_errno != 0 ? 1 : 0; + }" HAVE_H_ERRNO_ASSIGNABLE) + + if(NOT HAVE_H_ERRNO_ASSIGNABLE) + check_c_source_compiles("${_source_epilogue} + int main(void) + { + #if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200809L) + return 0; + #elif defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE >= 700) + return 0; + #else + force compilation error + #endif + }" HAVE_H_ERRNO_SBS_ISSUE_7) + endif() + endif() + + if(HAVE_H_ERRNO OR HAVE_H_ERRNO_ASSIGNABLE OR HAVE_H_ERRNO_SBS_ISSUE_7) + set(HAVE_GETADDRINFO_THREADSAFE TRUE) + endif() +endif() + +if(NOT WIN32 AND NOT DEFINED HAVE_CLOCK_GETTIME_MONOTONIC_RAW) + set(_source_epilogue "#undef inline") + add_header_include(HAVE_SYS_TYPES_H "sys/types.h") + add_header_include(HAVE_SYS_TIME_H "sys/time.h") + check_c_source_compiles("${_source_epilogue} + #include + int main(void) + { + struct timespec ts; + (void)clock_gettime(CLOCK_MONOTONIC_RAW, &ts); + return 0; + }" HAVE_CLOCK_GETTIME_MONOTONIC_RAW) +endif() diff --git a/third_party/curl/CMake/PickyWarnings.cmake b/third_party/curl/CMake/PickyWarnings.cmake new file mode 100644 index 0000000..d1183fe --- /dev/null +++ b/third_party/curl/CMake/PickyWarnings.cmake @@ -0,0 +1,236 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +include(CheckCCompilerFlag) + +unset(WPICKY) + +if(CURL_WERROR AND + ((CMAKE_COMPILER_IS_GNUCC AND + NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 5.0 AND + NOT CMAKE_VERSION VERSION_LESS 3.23.0) OR # check_symbol_exists() incompatible with GCC -pedantic-errors in earlier CMake versions + CMAKE_C_COMPILER_ID MATCHES "Clang")) + set(WPICKY "${WPICKY} -pedantic-errors") +endif() + +if(PICKY_COMPILER) + if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_C_COMPILER_ID MATCHES "Clang") + + # https://clang.llvm.org/docs/DiagnosticsReference.html + # https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html + + # WPICKY_ENABLE = Options we want to enable as-is. + # WPICKY_DETECT = Options we want to test first and enable if available. + + # Prefer the -Wextra alias with clang. + if(CMAKE_C_COMPILER_ID MATCHES "Clang") + set(WPICKY_ENABLE "-Wextra") + else() + set(WPICKY_ENABLE "-W") + endif() + + list(APPEND WPICKY_ENABLE + -Wall -pedantic + ) + + # ---------------------------------- + # Add new options here, if in doubt: + # ---------------------------------- + set(WPICKY_DETECT + ) + + # Assume these options always exist with both clang and gcc. + # Require clang 3.0 / gcc 2.95 or later. + list(APPEND WPICKY_ENABLE + -Wbad-function-cast # clang 2.7 gcc 2.95 + -Wconversion # clang 2.7 gcc 2.95 + -Winline # clang 1.0 gcc 1.0 + -Wmissing-declarations # clang 1.0 gcc 2.7 + -Wmissing-prototypes # clang 1.0 gcc 1.0 + -Wnested-externs # clang 1.0 gcc 2.7 + -Wno-long-long # clang 1.0 gcc 2.95 + -Wno-multichar # clang 1.0 gcc 2.95 + -Wpointer-arith # clang 1.0 gcc 1.4 + -Wshadow # clang 1.0 gcc 2.95 + -Wsign-compare # clang 1.0 gcc 2.95 + -Wundef # clang 1.0 gcc 2.95 + -Wunused # clang 1.1 gcc 2.95 + -Wwrite-strings # clang 1.0 gcc 1.4 + ) + + # Always enable with clang, version dependent with gcc + set(WPICKY_COMMON_OLD + -Waddress # clang 2.7 gcc 4.3 + -Wattributes # clang 2.7 gcc 4.1 + -Wcast-align # clang 1.0 gcc 4.2 + -Wdeclaration-after-statement # clang 1.0 gcc 3.4 + -Wdiv-by-zero # clang 2.7 gcc 4.1 + -Wempty-body # clang 2.7 gcc 4.3 + -Wendif-labels # clang 1.0 gcc 3.3 + -Wfloat-equal # clang 1.0 gcc 2.96 (3.0) + -Wformat-security # clang 2.7 gcc 4.1 + -Wignored-qualifiers # clang 2.8 gcc 4.3 + -Wmissing-field-initializers # clang 2.7 gcc 4.1 + -Wmissing-noreturn # clang 2.7 gcc 4.1 + -Wno-format-nonliteral # clang 1.0 gcc 2.96 (3.0) + -Wno-system-headers # clang 1.0 gcc 3.0 + # -Wpadded # clang 2.9 gcc 4.1 # Not used because we cannot change public structs + -Wold-style-definition # clang 2.7 gcc 3.4 + -Wredundant-decls # clang 2.7 gcc 4.1 + -Wsign-conversion # clang 2.9 gcc 4.3 + -Wno-error=sign-conversion # FIXME + -Wstrict-prototypes # clang 1.0 gcc 3.3 + # -Wswitch-enum # clang 2.7 gcc 4.1 # Not used because this basically disallows default case + -Wtype-limits # clang 2.7 gcc 4.3 + -Wunreachable-code # clang 2.7 gcc 4.1 + # -Wunused-macros # clang 2.7 gcc 4.1 # Not practical + -Wunused-parameter # clang 2.7 gcc 4.1 + -Wvla # clang 2.8 gcc 4.3 + ) + + set(WPICKY_COMMON + -Wdouble-promotion # clang 3.6 gcc 4.6 appleclang 6.3 + -Wenum-conversion # clang 3.2 gcc 10.0 appleclang 4.6 g++ 11.0 + -Wpragmas # clang 3.5 gcc 4.1 appleclang 6.0 + -Wunused-const-variable # clang 3.4 gcc 6.0 appleclang 5.1 + ) + + if(CMAKE_C_COMPILER_ID MATCHES "Clang") + list(APPEND WPICKY_ENABLE + ${WPICKY_COMMON_OLD} + -Wshift-sign-overflow # clang 2.9 + -Wshorten-64-to-32 # clang 1.0 + -Wlanguage-extension-token # clang 3.0 + -Wformat=2 # clang 3.0 gcc 4.8 + ) + # Enable based on compiler version + if((CMAKE_C_COMPILER_ID STREQUAL "Clang" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 3.6) OR + (CMAKE_C_COMPILER_ID STREQUAL "AppleClang" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 6.3)) + list(APPEND WPICKY_ENABLE + ${WPICKY_COMMON} + -Wunreachable-code-break # clang 3.5 appleclang 6.0 + -Wheader-guard # clang 3.4 appleclang 5.1 + -Wsometimes-uninitialized # clang 3.2 appleclang 4.6 + ) + endif() + if((CMAKE_C_COMPILER_ID STREQUAL "Clang" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 3.9) OR + (CMAKE_C_COMPILER_ID STREQUAL "AppleClang" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 8.3)) + list(APPEND WPICKY_ENABLE + -Wcomma # clang 3.9 appleclang 8.3 + -Wmissing-variable-declarations # clang 3.2 appleclang 4.6 + ) + endif() + if((CMAKE_C_COMPILER_ID STREQUAL "Clang" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 7.0) OR + (CMAKE_C_COMPILER_ID STREQUAL "AppleClang" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 10.3)) + list(APPEND WPICKY_ENABLE + -Wassign-enum # clang 7.0 appleclang 10.3 + -Wextra-semi-stmt # clang 7.0 appleclang 10.3 + ) + endif() + if((CMAKE_C_COMPILER_ID STREQUAL "Clang" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 10.0) OR + (CMAKE_C_COMPILER_ID STREQUAL "AppleClang" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 12.4)) + list(APPEND WPICKY_ENABLE + -Wimplicit-fallthrough # clang 4.0 gcc 7.0 appleclang 12.4 # we have silencing markup for clang 10.0 and above only + ) + endif() + else() # gcc + list(APPEND WPICKY_DETECT + ${WPICKY_COMMON} + ) + # Enable based on compiler version + if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.3) + list(APPEND WPICKY_ENABLE + ${WPICKY_COMMON_OLD} + -Wclobbered # gcc 4.3 + -Wmissing-parameter-type # gcc 4.3 + -Wold-style-declaration # gcc 4.3 + -Wstrict-aliasing=3 # gcc 4.0 + -Wtrampolines # gcc 4.3 + ) + endif() + if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.5 AND MINGW) + list(APPEND WPICKY_ENABLE + -Wno-pedantic-ms-format # gcc 4.5 (mingw-only) + ) + endif() + if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.8) + list(APPEND WPICKY_ENABLE + -Wformat=2 # clang 3.0 gcc 4.8 + ) + endif() + if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 5.0) + list(APPEND WPICKY_ENABLE + -Warray-bounds=2 -ftree-vrp # clang 3.0 gcc 5.0 (clang default: -Warray-bounds) + ) + endif() + if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 6.0) + list(APPEND WPICKY_ENABLE + -Wduplicated-cond # gcc 6.0 + -Wnull-dereference # clang 3.0 gcc 6.0 (clang default) + -fdelete-null-pointer-checks + -Wshift-negative-value # clang 3.7 gcc 6.0 (clang default) + -Wshift-overflow=2 # clang 3.0 gcc 6.0 (clang default: -Wshift-overflow) + ) + endif() + if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 7.0) + list(APPEND WPICKY_ENABLE + -Walloc-zero # gcc 7.0 + -Wduplicated-branches # gcc 7.0 + -Wformat-overflow=2 # gcc 7.0 + -Wformat-truncation=2 # gcc 7.0 + -Wimplicit-fallthrough # clang 4.0 gcc 7.0 + -Wrestrict # gcc 7.0 + ) + endif() + if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 10.0) + list(APPEND WPICKY_ENABLE + -Warith-conversion # gcc 10.0 + ) + endif() + endif() + + # + + foreach(_CCOPT IN LISTS WPICKY_ENABLE) + set(WPICKY "${WPICKY} ${_CCOPT}") + endforeach() + + foreach(_CCOPT IN LISTS WPICKY_DETECT) + # surprisingly, CHECK_C_COMPILER_FLAG needs a new variable to store each new + # test result in. + string(MAKE_C_IDENTIFIER "OPT${_CCOPT}" _optvarname) + # GCC only warns about unknown -Wno- options if there are also other diagnostic messages, + # so test for the positive form instead + string(REPLACE "-Wno-" "-W" _CCOPT_ON "${_CCOPT}") + check_c_compiler_flag(${_CCOPT_ON} ${_optvarname}) + if(${_optvarname}) + set(WPICKY "${WPICKY} ${_CCOPT}") + endif() + endforeach() + endif() +endif() + +if(WPICKY) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${WPICKY}") + message(STATUS "Picky compiler options:${WPICKY}") +endif() diff --git a/third_party/curl/CMake/Platforms/WindowsCache.cmake b/third_party/curl/CMake/Platforms/WindowsCache.cmake new file mode 100644 index 0000000..082154f --- /dev/null +++ b/third_party/curl/CMake/Platforms/WindowsCache.cmake @@ -0,0 +1,191 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +if(NOT WIN32) + message(FATAL_ERROR "This file should be included on Windows platform only") +endif() + +set(HAVE_LOCALE_H 1) + +if(MINGW) + set(HAVE_SNPRINTF 1) + set(HAVE_UNISTD_H 1) + set(HAVE_LIBGEN_H 1) + set(HAVE_STDDEF_H 1) # detected by CMake internally in check_type_size() + set(HAVE_STDBOOL_H 1) + set(HAVE_BOOL_T "${HAVE_STDBOOL_H}") + set(HAVE_STRTOLL 1) + set(HAVE_BASENAME 1) + set(HAVE_STRCASECMP 1) + set(HAVE_FTRUNCATE 1) + set(HAVE_SYS_PARAM_H 1) + set(HAVE_SYS_TIME_H 1) + set(HAVE_GETTIMEOFDAY 1) +else() + set(HAVE_LIBGEN_H 0) + set(HAVE_STRCASECMP 0) + set(HAVE_FTRUNCATE 0) + set(HAVE_SYS_PARAM_H 0) + set(HAVE_SYS_TIME_H 0) + set(HAVE_GETTIMEOFDAY 0) + if(MSVC) + set(HAVE_UNISTD_H 0) + set(HAVE_LOCALE_H 1) + set(HAVE_STDDEF_H 1) # detected by CMake internally in check_type_size() + set(HAVE_STDATOMIC_H 0) + if(NOT MSVC_VERSION LESS 1800) + set(HAVE_STDBOOL_H 1) + set(HAVE_STRTOLL 1) + else() + set(HAVE_STDBOOL_H 0) + set(HAVE_STRTOLL 0) + endif() + set(HAVE_BOOL_T "${HAVE_STDBOOL_H}") + if(NOT MSVC_VERSION LESS 1900) + set(HAVE_SNPRINTF 1) + else() + set(HAVE_SNPRINTF 0) + endif() + set(HAVE_BASENAME 0) + set(HAVE_STRTOK_R 0) + set(HAVE_FILE_OFFSET_BITS 0) + set(HAVE_ATOMIC 0) + endif() +endif() + +# Available in Windows XP and newer +set(HAVE_GETADDRINFO 1) +set(HAVE_FREEADDRINFO 1) + +set(HAVE_FCHMOD 0) +set(HAVE_SOCKETPAIR 0) +set(HAVE_SENDMSG 0) +set(HAVE_ALARM 0) +set(HAVE_FCNTL 0) +set(HAVE_GETPPID 0) +set(HAVE_UTIMES 0) +set(HAVE_GETPWUID_R 0) +set(HAVE_STRERROR_R 0) +set(HAVE_SIGINTERRUPT 0) +set(HAVE_PIPE 0) +set(HAVE_IF_NAMETOINDEX 0) +set(HAVE_GETRLIMIT 0) +set(HAVE_SETRLIMIT 0) +set(HAVE_FSETXATTR 0) +set(HAVE_LIBSOCKET 0) +set(HAVE_SETLOCALE 1) +set(HAVE_SETMODE 1) +set(HAVE_GETPEERNAME 1) +set(HAVE_GETSOCKNAME 1) +set(HAVE_GETHOSTNAME 1) +set(HAVE_LIBZ 0) + +set(HAVE_RECV 1) +set(HAVE_SEND 1) +set(HAVE_STROPTS_H 0) +set(HAVE_SYS_XATTR_H 0) +set(HAVE_ARC4RANDOM 0) +set(HAVE_FNMATCH 0) +set(HAVE_SCHED_YIELD 0) +set(HAVE_ARPA_INET_H 0) +set(HAVE_FCNTL_H 1) +set(HAVE_IFADDRS_H 0) +set(HAVE_IO_H 1) +set(HAVE_NETDB_H 0) +set(HAVE_NETINET_IN_H 0) +set(HAVE_NETINET_TCP_H 0) +set(HAVE_NETINET_UDP_H 0) +set(HAVE_NET_IF_H 0) +set(HAVE_IOCTL_SIOCGIFADDR 0) +set(HAVE_POLL_H 0) +set(HAVE_POLL_FINE 0) +set(HAVE_PWD_H 0) +set(HAVE_STRINGS_H 0) # mingw-w64 has it (wrapper to string.h) +set(HAVE_SYS_FILIO_H 0) +set(HAVE_SYS_WAIT_H 0) +set(HAVE_SYS_IOCTL_H 0) +set(HAVE_SYS_POLL_H 0) +set(HAVE_SYS_RESOURCE_H 0) +set(HAVE_SYS_SELECT_H 0) +set(HAVE_SYS_SOCKET_H 0) +set(HAVE_SYS_SOCKIO_H 0) +set(HAVE_SYS_STAT_H 1) +set(HAVE_SYS_TYPES_H 1) +set(HAVE_SYS_UN_H 0) +set(HAVE_SYS_UTIME_H 1) +set(HAVE_TERMIOS_H 0) +set(HAVE_TERMIO_H 0) +set(HAVE_UTIME_H 0) # mingw-w64 has it (wrapper to sys/utime.h) + +set(HAVE_DIRENT_H 0) +set(HAVE_OPENDIR 0) + +set(HAVE_FSEEKO 0) +set(HAVE__FSEEKI64 1) +set(HAVE_SOCKET 1) +set(HAVE_SELECT 1) +set(HAVE_STRDUP 1) +set(HAVE_STRICMP 1) +set(HAVE_STRCMPI 1) +set(HAVE_MEMRCHR 0) +set(HAVE_CLOSESOCKET 1) +set(HAVE_SIGSETJMP 0) +set(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1) +set(HAVE_GETPASS_R 0) +set(HAVE_GETPWUID 0) +set(HAVE_GETEUID 0) +set(HAVE_UTIME 1) +set(HAVE_GMTIME_R 0) +set(HAVE_GETHOSTBYNAME_R 0) +set(HAVE_SIGNAL 1) +set(HAVE_SIGACTION 0) +set(HAVE_LINUX_TCP_H 0) +set(HAVE_GLIBC_STRERROR_R 0) +set(HAVE_MACH_ABSOLUTE_TIME 0) +set(HAVE_GETIFADDRS 0) +set(HAVE_FCNTL_O_NONBLOCK 0) +set(HAVE_IOCTLSOCKET 1) +set(HAVE_IOCTLSOCKET_CAMEL 0) +set(HAVE_IOCTLSOCKET_CAMEL_FIONBIO 0) +set(HAVE_IOCTLSOCKET_FIONBIO 1) +set(HAVE_IOCTL_FIONBIO 0) +set(HAVE_SETSOCKOPT_SO_NONBLOCK 0) +set(HAVE_POSIX_STRERROR_R 0) +set(HAVE_BUILTIN_AVAILABLE 0) +set(HAVE_MSG_NOSIGNAL 0) +set(HAVE_STRUCT_TIMEVAL 1) +set(HAVE_STRUCT_SOCKADDR_STORAGE 1) + +set(HAVE_GETHOSTBYNAME_R_3 0) +set(HAVE_GETHOSTBYNAME_R_3_REENTRANT 0) +set(HAVE_GETHOSTBYNAME_R_5 0) +set(HAVE_GETHOSTBYNAME_R_5_REENTRANT 0) +set(HAVE_GETHOSTBYNAME_R_6 0) +set(HAVE_GETHOSTBYNAME_R_6_REENTRANT 0) + +set(HAVE_O_NONBLOCK 0) +set(HAVE_IN_ADDR_T 0) +set(STDC_HEADERS 1) + +set(HAVE_SIZEOF_SUSECONDS_T 0) +set(HAVE_SIZEOF_SA_FAMILY_T 0) diff --git a/third_party/curl/CMake/Utilities.cmake b/third_party/curl/CMake/Utilities.cmake new file mode 100644 index 0000000..84a40f4 --- /dev/null +++ b/third_party/curl/CMake/Utilities.cmake @@ -0,0 +1,35 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# File containing various utilities + +# Returns number of arguments that evaluate to true +function(count_true output_count_var) + set(lst_len 0) + foreach(option_var IN LISTS ARGN) + if(${option_var}) + math(EXPR lst_len "${lst_len} + 1") + endif() + endforeach() + set(${output_count_var} ${lst_len} PARENT_SCOPE) +endfunction() diff --git a/third_party/curl/CMake/cmake_uninstall.cmake.in b/third_party/curl/CMake/cmake_uninstall.cmake.in new file mode 100644 index 0000000..47aec8d --- /dev/null +++ b/third_party/curl/CMake/cmake_uninstall.cmake.in @@ -0,0 +1,49 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +if(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") + message(FATAL_ERROR "Cannot find install manifest: @CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") +endif() + +if(NOT DEFINED CMAKE_INSTALL_PREFIX) + set(CMAKE_INSTALL_PREFIX "@CMAKE_INSTALL_PREFIX@") +endif() +message(${CMAKE_INSTALL_PREFIX}) + +file(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files) +string(REGEX REPLACE "\n" ";" files "${files}") +foreach(file ${files}) + message(STATUS "Uninstalling $ENV{DESTDIR}${file}") + if(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") + exec_program( + "@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\"" + OUTPUT_VARIABLE rm_out + RETURN_VALUE rm_retval + ) + if(NOT "${rm_retval}" STREQUAL 0) + message(FATAL_ERROR "Problem when removing $ENV{DESTDIR}${file}") + endif() + else() + message(STATUS "File $ENV{DESTDIR}${file} does not exist.") + endif() +endforeach() diff --git a/third_party/curl/CMake/curl-config.cmake.in b/third_party/curl/CMake/curl-config.cmake.in new file mode 100644 index 0000000..9adb96e --- /dev/null +++ b/third_party/curl/CMake/curl-config.cmake.in @@ -0,0 +1,40 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +@PACKAGE_INIT@ + +include(CMakeFindDependencyMacro) +if(@USE_OPENSSL@) + find_dependency(OpenSSL @OPENSSL_VERSION_MAJOR@) +endif() +if(@USE_ZLIB@) + find_dependency(ZLIB @ZLIB_VERSION_MAJOR@) +endif() + +include("${CMAKE_CURRENT_LIST_DIR}/@TARGETS_EXPORT_NAME@.cmake") +check_required_components("@PROJECT_NAME@") + +# Alias for either shared or static library +if(NOT TARGET @PROJECT_NAME@::libcurl) + add_library(@PROJECT_NAME@::libcurl ALIAS @PROJECT_NAME@::@LIB_SELECTED@) +endif() diff --git a/third_party/curl/CMakeLists.txt b/third_party/curl/CMakeLists.txt new file mode 100644 index 0000000..8e7297e --- /dev/null +++ b/third_party/curl/CMakeLists.txt @@ -0,0 +1,1889 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# by Tetetest and Sukender (Benoit Neil) + +# Note: By default this CMake build script detects the version of some +# dependencies using `check_symbol_exists`. Those checks do not work +# in the case that both CURL and its dependency are included as +# sub-projects in a larger build using `FetchContent`. To support +# that case, additional variables may be defined by the parent +# project, ideally in the "extra" find package redirect file: +# https://cmake.org/cmake/help/latest/module/FetchContent.html#integrating-with-find-package +# +# The following variables are available: +# HAVE_SSL_SET0_WBIO: `SSL_set0_wbio` present in OpenSSL/wolfSSL +# HAVE_OPENSSL_SRP: `SSL_CTX_set_srp_username` present in OpenSSL/wolfSSL +# HAVE_GNUTLS_SRP: `gnutls_srp_verifier` present in GnuTLS +# HAVE_SSL_CTX_SET_QUIC_METHOD: `SSL_CTX_set_quic_method` present in OpenSSL/wolfSSL +# HAVE_QUICHE_CONN_SET_QLOG_FD: `quiche_conn_set_qlog_fd` present in QUICHE +# HAVE_ECH: ECH API checks for OpenSSL, BoringSSL or wolfSSL +# +# For each of the above variables, if the variable is DEFINED (either +# to ON or OFF), the symbol detection will be skipped. If the +# variable is NOT DEFINED, the symbol detection will be performed. + +cmake_minimum_required(VERSION 3.7...3.16 FATAL_ERROR) +message(STATUS "Using CMake version ${CMAKE_VERSION}") + +set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/CMake;${CMAKE_MODULE_PATH}") +include(Utilities) +include(Macros) +include(CMakeDependentOption) +include(CheckCCompilerFlag) + +project(CURL C) + +file(STRINGS ${CURL_SOURCE_DIR}/include/curl/curlver.h CURL_VERSION_H_CONTENTS REGEX "#define LIBCURL_VERSION( |_NUM )") +string(REGEX MATCH "#define LIBCURL_VERSION \"[^\"]*" + CURL_VERSION ${CURL_VERSION_H_CONTENTS}) +string(REGEX REPLACE "[^\"]+\"" "" CURL_VERSION ${CURL_VERSION}) +string(REGEX MATCH "#define LIBCURL_VERSION_NUM 0x[0-9a-fA-F]+" + CURL_VERSION_NUM ${CURL_VERSION_H_CONTENTS}) +string(REGEX REPLACE "[^0]+0x" "" CURL_VERSION_NUM ${CURL_VERSION_NUM}) + + +# Setup package meta-data +# SET(PACKAGE "curl") +message(STATUS "curl version=[${CURL_VERSION}]") +# SET(PACKAGE_TARNAME "curl") +# SET(PACKAGE_NAME "curl") +# SET(PACKAGE_VERSION "-") +# SET(PACKAGE_STRING "curl-") +# SET(PACKAGE_BUGREPORT "a suitable curl mailing list => https://curl.se/mail/") +set(OPERATING_SYSTEM "${CMAKE_SYSTEM_NAME}") +if(CMAKE_C_COMPILER_TARGET) + set(OS "\"${CMAKE_C_COMPILER_TARGET}\"") +else() + set(OS "\"${CMAKE_SYSTEM_NAME}\"") +endif() + +include_directories(${CURL_SOURCE_DIR}/include) + +set(CMAKE_UNITY_BUILD_BATCH_SIZE 0) + +option(CURL_WERROR "Turn compiler warnings into errors" OFF) +option(PICKY_COMPILER "Enable picky compiler options" OFF) +option(BUILD_CURL_EXE "Set to ON to build curl executable." OFF) +option(BUILD_SHARED_LIBS "Build shared libraries" OFF) +option(BUILD_STATIC_LIBS "Build static libraries" ON) +option(BUILD_STATIC_CURL "Build curl executable with static libcurl" OFF) +option(ENABLE_ARES "Set to ON to enable c-ares support" OFF) +option(CURL_DISABLE_INSTALL "Set to ON to disable installation targets" ON) + +if(WIN32) + option(CURL_STATIC_CRT "Set to ON to build libcurl with static CRT on Windows (/MT)." OFF) + option(ENABLE_UNICODE "Set to ON to use the Unicode version of the Windows API functions" OFF) + set(CURL_TARGET_WINDOWS_VERSION "" CACHE STRING "Minimum target Windows version as hex string") + if(CURL_TARGET_WINDOWS_VERSION) + add_definitions(-D_WIN32_WINNT=${CURL_TARGET_WINDOWS_VERSION}) + list(APPEND CMAKE_REQUIRED_DEFINITIONS -D_WIN32_WINNT=${CURL_TARGET_WINDOWS_VERSION}) + set(CURL_TEST_DEFINES "${CURL_TEST_DEFINES} -D_WIN32_WINNT=${CURL_TARGET_WINDOWS_VERSION}") + endif() + if(ENABLE_UNICODE) + add_definitions(-DUNICODE -D_UNICODE) + if(MINGW) + add_compile_options(-municode) + endif() + endif() +endif() +option(CURL_LTO "Turn on compiler Link Time Optimizations" OFF) + +cmake_dependent_option(ENABLE_THREADED_RESOLVER "Set to ON to enable threaded DNS lookup" + ON "NOT ENABLE_ARES" + OFF) + +option(ENABLE_DEBUG "Set to ON to enable curl debug features" OFF) +option(ENABLE_CURLDEBUG "Set to ON to build with TrackMemory feature enabled" OFF) + +include(PickyWarnings) + +if(ENABLE_DEBUG) + # DEBUGBUILD will be defined only for Debug builds + set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS $<$:DEBUGBUILD>) + set(ENABLE_CURLDEBUG ON) +endif() + +if(ENABLE_CURLDEBUG) + set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS CURLDEBUG) +endif() + +# For debug libs and exes, add "-d" postfix +if(NOT DEFINED CMAKE_DEBUG_POSTFIX) + set(CMAKE_DEBUG_POSTFIX "-d") +endif() + +set(LIB_STATIC "libcurl_static") +set(LIB_SHARED "libcurl_shared") + +if(NOT BUILD_SHARED_LIBS AND NOT BUILD_STATIC_LIBS) + set(BUILD_STATIC_LIBS ON) +endif() +if(NOT BUILD_STATIC_CURL AND NOT BUILD_SHARED_LIBS) + set(BUILD_STATIC_CURL ON) +elseif(BUILD_STATIC_CURL AND NOT BUILD_STATIC_LIBS) + set(BUILD_STATIC_CURL OFF) +endif() + +# lib flavour selected for curl tool +if(BUILD_STATIC_CURL) + set(LIB_SELECTED_FOR_EXE ${LIB_STATIC}) +else() + set(LIB_SELECTED_FOR_EXE ${LIB_SHARED}) +endif() + +# lib flavour selected for example and test programs. +if(BUILD_SHARED_LIBS) + set(LIB_SELECTED ${LIB_SHARED}) +else() + set(LIB_SELECTED ${LIB_STATIC}) +endif() + +# initialize CURL_LIBS +set(CURL_LIBS "") + +if(ENABLE_ARES) + set(USE_ARES 1) + find_package(CARES REQUIRED) + list(APPEND CURL_LIBS ${CARES_LIBRARY}) +endif() + +include(CurlSymbolHiding) + +option(CURL_ENABLE_EXPORT_TARGET "to enable cmake export target" OFF) +mark_as_advanced(CURL_ENABLE_EXPORT_TARGET) + +option(CURL_DISABLE_ALTSVC "disables alt-svc support" OFF) +mark_as_advanced(CURL_DISABLE_ALTSVC) +option(CURL_DISABLE_SRP "disables TLS-SRP support" OFF) +mark_as_advanced(CURL_DISABLE_SRP) +option(CURL_DISABLE_COOKIES "disables cookies support" OFF) +mark_as_advanced(CURL_DISABLE_COOKIES) +option(CURL_DISABLE_BASIC_AUTH "disables Basic authentication" OFF) +mark_as_advanced(CURL_DISABLE_BASIC_AUTH) +option(CURL_DISABLE_BEARER_AUTH "disables Bearer authentication" OFF) +mark_as_advanced(CURL_DISABLE_BEARER_AUTH) +option(CURL_DISABLE_DIGEST_AUTH "disables Digest authentication" OFF) +mark_as_advanced(CURL_DISABLE_DIGEST_AUTH) +option(CURL_DISABLE_KERBEROS_AUTH "disables Kerberos authentication" OFF) +mark_as_advanced(CURL_DISABLE_KERBEROS_AUTH) +option(CURL_DISABLE_NEGOTIATE_AUTH "disables negotiate authentication" OFF) +mark_as_advanced(CURL_DISABLE_NEGOTIATE_AUTH) +option(CURL_DISABLE_AWS "disables AWS-SIG4" OFF) +mark_as_advanced(CURL_DISABLE_AWS) +option(CURL_DISABLE_DICT "disables DICT" OFF) +mark_as_advanced(CURL_DISABLE_DICT) +option(CURL_DISABLE_DOH "disables DNS-over-HTTPS" OFF) +mark_as_advanced(CURL_DISABLE_DOH) +option(CURL_DISABLE_FILE "disables FILE" OFF) +mark_as_advanced(CURL_DISABLE_FILE) +cmake_dependent_option(CURL_DISABLE_FORM_API "disables form api" OFF + "NOT CURL_DISABLE_MIME" ON) +mark_as_advanced(CURL_DISABLE_FORM_API) +option(CURL_DISABLE_FTP "disables FTP" OFF) +mark_as_advanced(CURL_DISABLE_FTP) +option(CURL_DISABLE_GETOPTIONS "disables curl_easy_options API for existing options to curl_easy_setopt" OFF) +mark_as_advanced(CURL_DISABLE_GETOPTIONS) +option(CURL_DISABLE_GOPHER "disables Gopher" OFF) +mark_as_advanced(CURL_DISABLE_GOPHER) +option(CURL_DISABLE_HEADERS_API "disables headers-api support" OFF) +mark_as_advanced(CURL_DISABLE_HEADERS_API) +option(CURL_DISABLE_HSTS "disables HSTS support" OFF) +mark_as_advanced(CURL_DISABLE_HSTS) +option(CURL_DISABLE_HTTP "disables HTTP" OFF) +mark_as_advanced(CURL_DISABLE_HTTP) +option(CURL_DISABLE_HTTP_AUTH "disables all HTTP authentication methods" OFF) +mark_as_advanced(CURL_DISABLE_HTTP_AUTH) +option(CURL_DISABLE_IMAP "disables IMAP" OFF) +mark_as_advanced(CURL_DISABLE_IMAP) +option(CURL_DISABLE_LDAP "disables LDAP" OFF) +mark_as_advanced(CURL_DISABLE_LDAP) +option(CURL_DISABLE_LDAPS "disables LDAPS" OFF) +mark_as_advanced(CURL_DISABLE_LDAPS) +option(CURL_DISABLE_LIBCURL_OPTION "disables --libcurl option from the curl tool" OFF) +mark_as_advanced(CURL_DISABLE_LIBCURL_OPTION) +option(CURL_DISABLE_MIME "disables MIME support" OFF) +mark_as_advanced(CURL_DISABLE_MIME) +option(CURL_DISABLE_MQTT "disables MQTT" OFF) +mark_as_advanced(CURL_DISABLE_BINDLOCAL) +option(CURL_DISABLE_BINDLOCAL "disables local binding support" OFF) +mark_as_advanced(CURL_DISABLE_MQTT) +option(CURL_DISABLE_NETRC "disables netrc parser" OFF) +mark_as_advanced(CURL_DISABLE_NETRC) +option(CURL_DISABLE_NTLM "disables NTLM support" OFF) +mark_as_advanced(CURL_DISABLE_NTLM) +option(CURL_DISABLE_PARSEDATE "disables date parsing" OFF) +mark_as_advanced(CURL_DISABLE_PARSEDATE) +option(CURL_DISABLE_POP3 "disables POP3" OFF) +mark_as_advanced(CURL_DISABLE_POP3) +option(CURL_DISABLE_PROGRESS_METER "disables built-in progress meter" OFF) +mark_as_advanced(CURL_DISABLE_PROGRESS_METER) +option(CURL_DISABLE_PROXY "disables proxy support" OFF) +mark_as_advanced(CURL_DISABLE_PROXY) +option(CURL_DISABLE_RTSP "disables RTSP" OFF) +mark_as_advanced(CURL_DISABLE_RTSP) +option(CURL_DISABLE_SHUFFLE_DNS "disables shuffle DNS feature" OFF) +mark_as_advanced(CURL_DISABLE_SHUFFLE_DNS) +option(CURL_DISABLE_SMB "disables SMB" OFF) +mark_as_advanced(CURL_DISABLE_SMB) +option(CURL_DISABLE_SMTP "disables SMTP" OFF) +mark_as_advanced(CURL_DISABLE_SMTP) +option(CURL_DISABLE_SOCKETPAIR "disables use of socketpair for curl_multi_poll" OFF) +mark_as_advanced(CURL_DISABLE_SOCKETPAIR) +option(CURL_DISABLE_TELNET "disables Telnet" OFF) +mark_as_advanced(CURL_DISABLE_TELNET) +option(CURL_DISABLE_TFTP "disables TFTP" OFF) +mark_as_advanced(CURL_DISABLE_TFTP) +option(CURL_DISABLE_VERBOSE_STRINGS "disables verbose strings" OFF) +mark_as_advanced(CURL_DISABLE_VERBOSE_STRINGS) + +# Corresponds to HTTP_ONLY in lib/curl_setup.h +option(HTTP_ONLY "disables all protocols except HTTP (This overrides all CURL_DISABLE_* options)" ON) +mark_as_advanced(HTTP_ONLY) + +if(HTTP_ONLY) + set(CURL_DISABLE_DICT ON) + set(CURL_DISABLE_FILE ON) + set(CURL_DISABLE_FTP ON) + set(CURL_DISABLE_GOPHER ON) + set(CURL_DISABLE_IMAP ON) + set(CURL_DISABLE_LDAP ON) + set(CURL_DISABLE_LDAPS ON) + set(CURL_DISABLE_MQTT ON) + set(CURL_DISABLE_POP3 ON) + set(CURL_DISABLE_RTSP ON) + set(CURL_DISABLE_SMB ON) + set(CURL_DISABLE_SMTP ON) + set(CURL_DISABLE_TELNET ON) + set(CURL_DISABLE_TFTP ON) +endif() + +option(ENABLE_IPV6 "Define if you want to enable IPv6 support" ON) +mark_as_advanced(ENABLE_IPV6) +if(ENABLE_IPV6 AND NOT WIN32) + include(CheckStructHasMember) + check_struct_has_member("struct sockaddr_in6" sin6_addr "netinet/in.h" + HAVE_SOCKADDR_IN6_SIN6_ADDR) + check_struct_has_member("struct sockaddr_in6" sin6_scope_id "netinet/in.h" + HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID) + if(NOT HAVE_SOCKADDR_IN6_SIN6_ADDR) + message(WARNING "struct sockaddr_in6 not available, disabling IPv6 support") + # Force the feature off as this name is used as guard macro... + set(ENABLE_IPV6 OFF + CACHE BOOL "Define if you want to enable IPv6 support" FORCE) + endif() + + if(CMAKE_SYSTEM_NAME STREQUAL "Darwin" AND NOT ENABLE_ARES) + set(use_core_foundation_and_core_services ON) + + find_library(SYSTEMCONFIGURATION_FRAMEWORK "SystemConfiguration") + if(NOT SYSTEMCONFIGURATION_FRAMEWORK) + message(FATAL_ERROR "SystemConfiguration framework not found") + endif() + + list(APPEND CURL_LIBS "-framework SystemConfiguration") + endif() +endif() +if(ENABLE_IPV6) + set(USE_IPV6 ON) +endif() + +find_package(Perl) + +option(BUILD_LIBCURL_DOCS "to build libcurl man pages" OFF) +option(BUILD_MISC_DOCS "to build misc man pages (e.g. curl-config and mk-ca-bundle)" OFF) +option(ENABLE_CURL_MANUAL "to build the man page for curl and enable its -M/--manual option" OFF) + +if(ENABLE_CURL_MANUAL OR BUILD_LIBCURL_DOCS) + if(PERL_FOUND) + set(HAVE_MANUAL_TOOLS ON) + endif() + if(NOT HAVE_MANUAL_TOOLS) + message(WARNING "Perl not found. Will not build manuals.") + endif() +endif() + +if(CURL_STATIC_CRT) + set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} /MT") + set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /MTd") +endif() + +# Disable warnings on Borland to avoid changing 3rd party code. +if(BORLAND) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -w-") +endif() + +# If we are on AIX, do the _ALL_SOURCE magic +if(${CMAKE_SYSTEM_NAME} MATCHES AIX) + set(_ALL_SOURCE 1) +endif() + +# If we are on Haiku, make sure that the network library is brought in. +if(${CMAKE_SYSTEM_NAME} MATCHES Haiku) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -lnetwork") +endif() + +# Include all the necessary files for macros +include(CMakePushCheckState) +include(CheckFunctionExists) +include(CheckIncludeFile) +include(CheckIncludeFiles) +include(CheckLibraryExists) +include(CheckSymbolExists) +include(CheckTypeSize) +include(CheckCSourceCompiles) + +# On windows preload settings +if(WIN32) + include(${CMAKE_CURRENT_SOURCE_DIR}/CMake/Platforms/WindowsCache.cmake) +endif() + +if(ENABLE_THREADED_RESOLVER) + if(WIN32) + set(USE_THREADS_WIN32 ON) + else() + find_package(Threads REQUIRED) + set(USE_THREADS_POSIX ${CMAKE_USE_PTHREADS_INIT}) + set(HAVE_PTHREAD_H ${CMAKE_USE_PTHREADS_INIT}) + set(CURL_LIBS ${CURL_LIBS} ${CMAKE_THREAD_LIBS_INIT}) + endif() +endif() + +# Check for all needed libraries +check_library_exists("socket" "connect" "" HAVE_LIBSOCKET) +if(HAVE_LIBSOCKET) + set(CURL_LIBS "socket;${CURL_LIBS}") +endif() + +check_function_exists(gethostname HAVE_GETHOSTNAME) + +if(WIN32) + list(APPEND CURL_LIBS "ws2_32" "bcrypt") +endif() + +# check SSL libraries +option(CURL_ENABLE_SSL "Enable SSL support" ON) + +if(CURL_DEFAULT_SSL_BACKEND) + set(valid_default_ssl_backend FALSE) +endif() + +if(APPLE) + cmake_dependent_option(CURL_USE_SECTRANSP "Enable Apple OS native SSL/TLS" OFF CURL_ENABLE_SSL OFF) +endif() +if(WIN32) + cmake_dependent_option(CURL_USE_SCHANNEL "Enable Windows native SSL/TLS" OFF CURL_ENABLE_SSL OFF) + option(CURL_WINDOWS_SSPI "Enable SSPI on Windows" ${CURL_USE_SCHANNEL}) +endif() +cmake_dependent_option(CURL_USE_MBEDTLS "Enable mbedTLS for SSL/TLS" OFF CURL_ENABLE_SSL OFF) +cmake_dependent_option(CURL_USE_BEARSSL "Enable BearSSL for SSL/TLS" OFF CURL_ENABLE_SSL OFF) +cmake_dependent_option(CURL_USE_WOLFSSL "Enable wolfSSL for SSL/TLS" OFF CURL_ENABLE_SSL OFF) +cmake_dependent_option(CURL_USE_GNUTLS "Enable GnuTLS for SSL/TLS" OFF CURL_ENABLE_SSL OFF) + +set(openssl_default ON) +if(WIN32 OR CURL_USE_SECTRANSP OR CURL_USE_SCHANNEL OR CURL_USE_MBEDTLS OR CURL_USE_WOLFSSL) + set(openssl_default OFF) +endif() +cmake_dependent_option(CURL_USE_OPENSSL "Enable OpenSSL for SSL/TLS" ${openssl_default} CURL_ENABLE_SSL OFF) +option(CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG "Disable automatic loading of OpenSSL configuration" OFF) + +count_true(enabled_ssl_options_count + CURL_USE_SCHANNEL + CURL_USE_SECTRANSP + CURL_USE_OPENSSL + CURL_USE_MBEDTLS + CURL_USE_BEARSSL + CURL_USE_WOLFSSL +) +if(enabled_ssl_options_count GREATER "1") + set(CURL_WITH_MULTI_SSL ON) +endif() + +if(CURL_USE_SCHANNEL) + set(SSL_ENABLED ON) + set(USE_SCHANNEL ON) # Windows native SSL/TLS support + set(USE_WINDOWS_SSPI ON) # CURL_USE_SCHANNEL implies CURL_WINDOWS_SSPI + + if(CURL_DEFAULT_SSL_BACKEND AND CURL_DEFAULT_SSL_BACKEND STREQUAL "schannel") + set(valid_default_ssl_backend TRUE) + endif() +endif() +if(CURL_WINDOWS_SSPI) + set(USE_WINDOWS_SSPI ON) +endif() + +if(CURL_USE_SECTRANSP) + set(use_core_foundation_and_core_services ON) + + find_library(SECURITY_FRAMEWORK "Security") + if(NOT SECURITY_FRAMEWORK) + message(FATAL_ERROR "Security framework not found") + endif() + + set(SSL_ENABLED ON) + set(USE_SECTRANSP ON) + list(APPEND CURL_LIBS "-framework Security") + + if(CURL_DEFAULT_SSL_BACKEND AND CURL_DEFAULT_SSL_BACKEND STREQUAL "secure-transport") + set(valid_default_ssl_backend TRUE) + endif() +endif() + +if(use_core_foundation_and_core_services) + find_library(COREFOUNDATION_FRAMEWORK "CoreFoundation") + find_library(CORESERVICES_FRAMEWORK "CoreServices") + + if(NOT COREFOUNDATION_FRAMEWORK) + message(FATAL_ERROR "CoreFoundation framework not found") + endif() + if(NOT CORESERVICES_FRAMEWORK) + message(FATAL_ERROR "CoreServices framework not found") + endif() + + list(APPEND CURL_LIBS "-framework CoreFoundation -framework CoreServices") +endif() + +if(CURL_USE_OPENSSL) + find_package(OpenSSL REQUIRED) + set(SSL_ENABLED ON) + set(USE_OPENSSL ON) + + # Depend on OpenSSL via imported targets if supported by the running + # version of CMake. This allows our dependents to get our dependencies + # transitively. + if(NOT CMAKE_VERSION VERSION_LESS 3.4) + list(APPEND CURL_LIBS OpenSSL::SSL OpenSSL::Crypto) + else() + list(APPEND CURL_LIBS ${OPENSSL_LIBRARIES}) + include_directories(${OPENSSL_INCLUDE_DIR}) + endif() + + if(CURL_DEFAULT_SSL_BACKEND AND CURL_DEFAULT_SSL_BACKEND STREQUAL "openssl") + set(valid_default_ssl_backend TRUE) + endif() + + set(CMAKE_REQUIRED_INCLUDES ${OPENSSL_INCLUDE_DIR}) + if(NOT DEFINED HAVE_BORINGSSL) + check_symbol_exists(OPENSSL_IS_BORINGSSL "openssl/base.h" HAVE_BORINGSSL) + endif() + if(NOT DEFINED HAVE_AWSLC) + check_symbol_exists(OPENSSL_IS_AWSLC "openssl/base.h" HAVE_AWSLC) + endif() +endif() + +if(CURL_USE_MBEDTLS) + find_package(MbedTLS REQUIRED) + set(SSL_ENABLED ON) + set(USE_MBEDTLS ON) + list(APPEND CURL_LIBS ${MBEDTLS_LIBRARIES}) + include_directories(${MBEDTLS_INCLUDE_DIRS}) + + if(CURL_DEFAULT_SSL_BACKEND AND CURL_DEFAULT_SSL_BACKEND STREQUAL "mbedtls") + set(valid_default_ssl_backend TRUE) + endif() +endif() + +if(CURL_USE_BEARSSL) + find_package(BearSSL REQUIRED) + set(SSL_ENABLED ON) + set(USE_BEARSSL ON) + list(APPEND CURL_LIBS ${BEARSSL_LIBRARY}) + include_directories(${BEARSSL_INCLUDE_DIRS}) + + if(CURL_DEFAULT_SSL_BACKEND AND CURL_DEFAULT_SSL_BACKEND STREQUAL "bearssl") + set(valid_default_ssl_backend TRUE) + endif() +endif() + +if(CURL_USE_WOLFSSL) + find_package(WolfSSL REQUIRED) + set(SSL_ENABLED ON) + set(USE_WOLFSSL ON) + list(APPEND CURL_LIBS ${WolfSSL_LIBRARIES}) + include_directories(${WolfSSL_INCLUDE_DIRS}) + + if(CURL_DEFAULT_SSL_BACKEND AND CURL_DEFAULT_SSL_BACKEND STREQUAL "wolfssl") + set(valid_default_ssl_backend TRUE) + endif() +endif() + +if(CURL_USE_GNUTLS) + find_package(GnuTLS REQUIRED) + set(SSL_ENABLED ON) + set(USE_GNUTLS ON) + list(APPEND CURL_LIBS ${GNUTLS_LIBRARIES} "nettle") + include_directories(${GNUTLS_INCLUDE_DIRS}) + + if(CURL_DEFAULT_SSL_BACKEND AND CURL_DEFAULT_SSL_BACKEND STREQUAL "gnutls") + set(valid_default_ssl_backend TRUE) + endif() + + if(NOT DEFINED HAVE_GNUTLS_SRP AND NOT CURL_DISABLE_SRP) + cmake_push_check_state() + set(CMAKE_REQUIRED_INCLUDES ${GNUTLS_INCLUDE_DIRS}) + set(CMAKE_REQUIRED_LIBRARIES ${GNUTLS_LIBRARIES}) + check_symbol_exists(gnutls_srp_verifier "gnutls/gnutls.h" HAVE_GNUTLS_SRP) + cmake_pop_check_state() + endif() +endif() + +if(CURL_DEFAULT_SSL_BACKEND AND NOT valid_default_ssl_backend) + message(FATAL_ERROR "CURL_DEFAULT_SSL_BACKEND '${CURL_DEFAULT_SSL_BACKEND}' not enabled.") +endif() + +# Keep ZLIB detection after TLS detection, +# and before calling openssl_check_symbol_exists(). + +set(HAVE_LIBZ OFF) +set(USE_ZLIB OFF) +# optional_dependency(ZLIB) +if(ZLIB_FOUND) + set(HAVE_LIBZ ON) + set(USE_ZLIB ON) + + # Depend on ZLIB via imported targets if supported by the running + # version of CMake. This allows our dependents to get our dependencies + # transitively. + if(NOT CMAKE_VERSION VERSION_LESS 3.4) + list(APPEND CURL_LIBS ZLIB::ZLIB) + else() + list(APPEND CURL_LIBS ${ZLIB_LIBRARIES}) + include_directories(${ZLIB_INCLUDE_DIRS}) + endif() + list(APPEND CMAKE_REQUIRED_INCLUDES ${ZLIB_INCLUDE_DIRS}) +endif() + +option(CURL_BROTLI "Set to ON to enable building curl with brotli support." OFF) +set(HAVE_BROTLI OFF) +if(CURL_BROTLI) + find_package(Brotli REQUIRED) + if(BROTLI_FOUND) + set(HAVE_BROTLI ON) + set(CURL_LIBS "${BROTLI_LIBRARIES};${CURL_LIBS}") # For 'ld' linker. Emulate `list(PREPEND ...)` to stay compatible with \n") + endforeach() + + list(APPEND CMAKE_REQUIRED_DEFINITIONS -DLDAP_DEPRECATED=1) + list(APPEND CMAKE_REQUIRED_LIBRARIES ${CMAKE_LDAP_LIB}) + set(CURL_LIBS "${CMAKE_LDAP_LIB};${CURL_LIBS}") + if(HAVE_LIBLBER) + list(APPEND CMAKE_REQUIRED_LIBRARIES ${CMAKE_LBER_LIB}) + set(CURL_LIBS "${CMAKE_LBER_LIB};${CURL_LIBS}") + endif() + + check_c_source_compiles(" + ${_INCLUDE_STRING} + int main(int argc, char ** argv) + { + BerValue *bvp = NULL; + BerElement *bep = ber_init(bvp); + ber_free(bep, 1); + return 0; + }" NOT_NEED_LBER_H) + if(NOT_NEED_LBER_H) + set(NEED_LBER_H OFF) + else() + set(CURL_TEST_DEFINES "${CURL_TEST_DEFINES} -DNEED_LBER_H") + endif() + + check_function_exists(ldap_url_parse HAVE_LDAP_URL_PARSE) + check_function_exists(ldap_init_fd HAVE_LDAP_INIT_FD) + + unset(CMAKE_REQUIRED_LIBRARIES) + + check_include_file("ldap_ssl.h" HAVE_LDAP_SSL_H) + + if(HAVE_LDAP_INIT_FD) + set(USE_OPENLDAP ON) + add_definitions("-DLDAP_DEPRECATED=1") + endif() + if(NOT CURL_DISABLE_LDAPS) + set(HAVE_LDAP_SSL ON) + endif() + endif() + endif() +endif() + +# No ldap, no ldaps. +if(CURL_DISABLE_LDAP) + if(NOT CURL_DISABLE_LDAPS) + message(STATUS "LDAP needs to be enabled to support LDAPS") + set(CURL_DISABLE_LDAPS ON CACHE BOOL "" FORCE) + endif() +endif() + +# Check for idn2 +option(USE_LIBIDN2 "Use libidn2 for IDN support" ON) +if(USE_LIBIDN2) + check_library_exists("idn2" "idn2_lookup_ul" "" HAVE_LIBIDN2) + if(HAVE_LIBIDN2) + set(CURL_LIBS "idn2;${CURL_LIBS}") + check_include_file_concat("idn2.h" HAVE_IDN2_H) + endif() +else() + set(HAVE_LIBIDN2 OFF) +endif() + +if(WIN32) + option(USE_WIN32_IDN "Use WinIDN for IDN support" OFF) + if(USE_WIN32_IDN) + list(APPEND CURL_LIBS "normaliz") + endif() +endif() + +if(APPLE) + option(USE_APPLE_IDN "Use Apple built-in IDN support" OFF) + if(USE_APPLE_IDN) + cmake_push_check_state() + set(CMAKE_REQUIRED_LIBRARIES "icucore") + check_symbol_exists("uidna_openUTS46" "unicode/uidna.h" HAVE_APPLE_IDN) + cmake_pop_check_state() + if(HAVE_APPLE_IDN) + list(APPEND CURL_LIBS "icucore") + else() + set(USE_APPLE_IDN OFF) + endif() + endif() +endif() + +#libpsl +option(CURL_USE_LIBPSL "Use libPSL" ON) +mark_as_advanced(CURL_USE_LIBPSL) +set(USE_LIBPSL OFF) + +if(CURL_USE_LIBPSL) + find_package(LibPSL) + if(LIBPSL_FOUND) + list(APPEND CURL_LIBS ${LIBPSL_LIBRARY}) + list(APPEND CMAKE_REQUIRED_INCLUDES "${LIBPSL_INCLUDE_DIR}") + include_directories("${LIBPSL_INCLUDE_DIR}") + set(USE_LIBPSL ON) + endif() +endif() + +#libSSH2 +option(CURL_USE_LIBSSH2 "Use libSSH2" ON) +mark_as_advanced(CURL_USE_LIBSSH2) +set(USE_LIBSSH2 OFF) + +if(CURL_USE_LIBSSH2) + find_package(LibSSH2) + if(LIBSSH2_FOUND) + list(APPEND CURL_LIBS ${LIBSSH2_LIBRARY}) + list(APPEND CMAKE_REQUIRED_INCLUDES "${LIBSSH2_INCLUDE_DIR}") + include_directories("${LIBSSH2_INCLUDE_DIR}") + set(USE_LIBSSH2 ON) + endif() +endif() + +# libssh +option(CURL_USE_LIBSSH "Use libSSH" OFF) +mark_as_advanced(CURL_USE_LIBSSH) +if(NOT USE_LIBSSH2 AND CURL_USE_LIBSSH) + find_package(libssh CONFIG) + if(libssh_FOUND) + message(STATUS "Found libssh ${libssh_VERSION}") + # Use imported target for include and library paths. + list(APPEND CURL_LIBS ssh) + set(USE_LIBSSH ON) + endif() +endif() + +option(CURL_USE_GSSAPI "Use GSSAPI implementation (right now only Heimdal is supported with CMake build)" OFF) +mark_as_advanced(CURL_USE_GSSAPI) + +if(CURL_USE_GSSAPI) + find_package(GSS) + + set(HAVE_GSSAPI ${GSS_FOUND}) + if(GSS_FOUND) + + message(STATUS "Found ${GSS_FLAVOUR} GSSAPI version: \"${GSS_VERSION}\"") + + list(APPEND CMAKE_REQUIRED_INCLUDES ${GSS_INCLUDE_DIR}) + check_include_file_concat("gssapi/gssapi.h" HAVE_GSSAPI_GSSAPI_H) + check_include_file_concat("gssapi/gssapi_generic.h" HAVE_GSSAPI_GSSAPI_GENERIC_H) + check_include_file_concat("gssapi/gssapi_krb5.h" HAVE_GSSAPI_GSSAPI_KRB5_H) + + if(NOT GSS_FLAVOUR STREQUAL "Heimdal") + # MIT + set(_INCLUDE_LIST "") + if(HAVE_GSSAPI_GSSAPI_H) + list(APPEND _INCLUDE_LIST "gssapi/gssapi.h") + endif() + if(HAVE_GSSAPI_GSSAPI_GENERIC_H) + list(APPEND _INCLUDE_LIST "gssapi/gssapi_generic.h") + endif() + if(HAVE_GSSAPI_GSSAPI_KRB5_H) + list(APPEND _INCLUDE_LIST "gssapi/gssapi_krb5.h") + endif() + + string(REPLACE ";" " " _COMPILER_FLAGS_STR "${GSS_COMPILER_FLAGS}") + string(REPLACE ";" " " _LINKER_FLAGS_STR "${GSS_LINKER_FLAGS}") + + foreach(_dir ${GSS_LINK_DIRECTORIES}) + set(_LINKER_FLAGS_STR "${_LINKER_FLAGS_STR} -L\"${_dir}\"") + endforeach() + + if(NOT DEFINED HAVE_GSS_C_NT_HOSTBASED_SERVICE) + set(CMAKE_REQUIRED_FLAGS "${_COMPILER_FLAGS_STR} ${_LINKER_FLAGS_STR}") + set(CMAKE_REQUIRED_LIBRARIES ${GSS_LIBRARIES}) + check_symbol_exists("GSS_C_NT_HOSTBASED_SERVICE" ${_INCLUDE_LIST} HAVE_GSS_C_NT_HOSTBASED_SERVICE) + unset(CMAKE_REQUIRED_LIBRARIES) + endif() + if(NOT HAVE_GSS_C_NT_HOSTBASED_SERVICE) + set(HAVE_OLD_GSSMIT ON) + endif() + endif() + + include_directories(${GSS_INCLUDE_DIR}) + link_directories(${GSS_LINK_DIRECTORIES}) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${GSS_COMPILER_FLAGS}") + string(REPLACE ";" " " GSS_LINKER_FLAGS "${GSS_LINKER_FLAGS}") + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${GSS_LINKER_FLAGS}") + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GSS_LINKER_FLAGS}") + list(APPEND CURL_LIBS ${GSS_LIBRARIES}) + + else() + message(WARNING "GSSAPI support has been requested but no supporting libraries found. Skipping.") + endif() +endif() + +option(USE_LIBRTMP "Enable librtmp from rtmpdump" OFF) +if(USE_LIBRTMP) + cmake_push_check_state() + set(_extra_libs "rtmp") + if(WIN32) + list(APPEND _extra_libs "winmm") + endif() + openssl_check_symbol_exists("RTMP_Init" "librtmp/rtmp.h" HAVE_LIBRTMP "${_extra_libs}") + cmake_pop_check_state() + if(HAVE_LIBRTMP) + list(APPEND CURL_LIBS "rtmp") + if(WIN32) + list(APPEND CURL_LIBS "winmm") + endif() + else() + message(WARNING "librtmp requested, but not found or missing OpenSSL. Skipping.") + set(USE_LIBRTMP OFF) + endif() +endif() + +option(ENABLE_UNIX_SOCKETS "Define if you want Unix domain sockets support" ON) +if(ENABLE_UNIX_SOCKETS) + include(CheckStructHasMember) + if(WIN32) + set(USE_UNIX_SOCKETS ON) + else() + check_struct_has_member("struct sockaddr_un" sun_path "sys/un.h" USE_UNIX_SOCKETS) + endif() +else() + unset(USE_UNIX_SOCKETS CACHE) +endif() + + +# +# CA handling +# +set(CURL_CA_BUNDLE "auto" CACHE STRING + "Path to the CA bundle. Set 'none' to disable or 'auto' for auto-detection. Defaults to 'auto'.") +set(CURL_CA_FALLBACK OFF CACHE BOOL + "Set ON to use built-in CA store of TLS backend. Defaults to OFF") +set(CURL_CA_PATH "auto" CACHE STRING + "Location of default CA path. Set 'none' to disable or 'auto' for auto-detection. Defaults to 'auto'.") + +if("${CURL_CA_BUNDLE}" STREQUAL "") + message(FATAL_ERROR "Invalid value of CURL_CA_BUNDLE. Use 'none', 'auto' or file path.") +elseif("${CURL_CA_BUNDLE}" STREQUAL "none") + unset(CURL_CA_BUNDLE CACHE) +elseif("${CURL_CA_BUNDLE}" STREQUAL "auto") + unset(CURL_CA_BUNDLE CACHE) + if(NOT CMAKE_CROSSCOMPILING) + set(CURL_CA_BUNDLE_AUTODETECT TRUE) + endif() +else() + set(CURL_CA_BUNDLE_SET TRUE) +endif() + +if("${CURL_CA_PATH}" STREQUAL "") + message(FATAL_ERROR "Invalid value of CURL_CA_PATH. Use 'none', 'auto' or directory path.") +elseif("${CURL_CA_PATH}" STREQUAL "none") + unset(CURL_CA_PATH CACHE) +elseif("${CURL_CA_PATH}" STREQUAL "auto") + unset(CURL_CA_PATH CACHE) + if(NOT CMAKE_CROSSCOMPILING) + set(CURL_CA_PATH_AUTODETECT TRUE) + endif() +else() + set(CURL_CA_PATH_SET TRUE) +endif() + +if(CURL_CA_BUNDLE_SET AND CURL_CA_PATH_AUTODETECT) + # Skip autodetection of unset CA path because CA bundle is set explicitly +elseif(CURL_CA_PATH_SET AND CURL_CA_BUNDLE_AUTODETECT) + # Skip autodetection of unset CA bundle because CA path is set explicitly +elseif(CURL_CA_PATH_AUTODETECT OR CURL_CA_BUNDLE_AUTODETECT) + # first try autodetecting a CA bundle, then a CA path + + if(CURL_CA_BUNDLE_AUTODETECT) + set(SEARCH_CA_BUNDLE_PATHS + /etc/ssl/certs/ca-certificates.crt + /etc/pki/tls/certs/ca-bundle.crt + /usr/share/ssl/certs/ca-bundle.crt + /usr/local/share/certs/ca-root-nss.crt + /etc/ssl/cert.pem) + + foreach(SEARCH_CA_BUNDLE_PATH ${SEARCH_CA_BUNDLE_PATHS}) + if(EXISTS "${SEARCH_CA_BUNDLE_PATH}") + message(STATUS "Found CA bundle: ${SEARCH_CA_BUNDLE_PATH}") + set(CURL_CA_BUNDLE "${SEARCH_CA_BUNDLE_PATH}" CACHE STRING + "Path to the CA bundle. Set 'none' to disable or 'auto' for auto-detection. Defaults to 'auto'.") + set(CURL_CA_BUNDLE_SET TRUE CACHE BOOL "Path to the CA bundle has been set") + break() + endif() + endforeach() + endif() + + if(CURL_CA_PATH_AUTODETECT AND (NOT CURL_CA_PATH_SET)) + if(EXISTS "/etc/ssl/certs") + set(CURL_CA_PATH "/etc/ssl/certs" CACHE STRING + "Location of default CA path. Set 'none' to disable or 'auto' for auto-detection. Defaults to 'auto'.") + set(CURL_CA_PATH_SET TRUE CACHE BOOL "Path to the CA bundle has been set") + endif() + endif() +endif() + +if(CURL_CA_PATH_SET AND + NOT USE_OPENSSL AND + NOT USE_WOLFSSL AND + NOT USE_GNUTLS AND + NOT USE_MBEDTLS) + message(STATUS + "CA path only supported by OpenSSL, wolfSSL, GnuTLS or mbedTLS. " + "Set CURL_CA_PATH=none or enable one of those TLS backends.") +endif() + +# Check for header files +if(WIN32) + set(CURL_INCLUDES ${CURL_INCLUDES} "winsock2.h") + set(CURL_INCLUDES ${CURL_INCLUDES} "ws2tcpip.h") + set(CURL_INCLUDES ${CURL_INCLUDES} "windows.h") +endif() + +if(WIN32) + # detect actual value of _WIN32_WINNT and store as HAVE_WIN32_WINNT + curl_internal_test(HAVE_WIN32_WINNT) + if(HAVE_WIN32_WINNT) + string(REGEX MATCH ".*_WIN32_WINNT=0x[0-9a-fA-F]+" OUTPUT "${OUTPUT}") + string(REGEX REPLACE ".*_WIN32_WINNT=" "" OUTPUT "${OUTPUT}") + string(REGEX REPLACE "0x([0-9a-f][0-9a-f][0-9a-f])$" "0x0\\1" OUTPUT "${OUTPUT}") # pad to 4 digits + string(TOLOWER "${OUTPUT}" HAVE_WIN32_WINNT) + message(STATUS "Found _WIN32_WINNT=${HAVE_WIN32_WINNT}") + endif() + # avoid storing HAVE_WIN32_WINNT in CMake cache + unset(HAVE_WIN32_WINNT CACHE) + + if(HAVE_WIN32_WINNT) + if(HAVE_WIN32_WINNT STRLESS "0x0501") + # Windows XP is required for freeaddrinfo, getaddrinfo + message(FATAL_ERROR "Building for Windows XP or newer is required.") + endif() + + # pre-fill detection results based on target OS version + if(MINGW OR MSVC) + if(HAVE_WIN32_WINNT STRLESS "0x0600") + set(HAVE_INET_NTOP 0) + set(HAVE_INET_PTON 0) + else() # Windows Vista or newer + set(HAVE_INET_NTOP 1) + set(HAVE_INET_PTON 1) + endif() + unset(HAVE_INET_NTOP CACHE) + unset(HAVE_INET_PTON CACHE) + endif() + endif() +endif() + +check_include_file_concat("sys/filio.h" HAVE_SYS_FILIO_H) +check_include_file_concat("sys/wait.h" HAVE_SYS_WAIT_H) +check_include_file_concat("sys/ioctl.h" HAVE_SYS_IOCTL_H) +check_include_file_concat("sys/param.h" HAVE_SYS_PARAM_H) +check_include_file_concat("sys/poll.h" HAVE_SYS_POLL_H) +check_include_file_concat("sys/resource.h" HAVE_SYS_RESOURCE_H) +check_include_file_concat("sys/select.h" HAVE_SYS_SELECT_H) +check_include_file_concat("sys/socket.h" HAVE_SYS_SOCKET_H) +check_include_file_concat("sys/sockio.h" HAVE_SYS_SOCKIO_H) +check_include_file_concat("sys/stat.h" HAVE_SYS_STAT_H) +check_include_file_concat("sys/time.h" HAVE_SYS_TIME_H) +check_include_file_concat("sys/types.h" HAVE_SYS_TYPES_H) +check_include_file_concat("sys/un.h" HAVE_SYS_UN_H) +check_include_file_concat("sys/utime.h" HAVE_SYS_UTIME_H) +check_include_file_concat("sys/xattr.h" HAVE_SYS_XATTR_H) +check_include_file_concat("arpa/inet.h" HAVE_ARPA_INET_H) +check_include_file_concat("dirent.h" HAVE_DIRENT_H) +check_include_file_concat("fcntl.h" HAVE_FCNTL_H) +check_include_file_concat("ifaddrs.h" HAVE_IFADDRS_H) +check_include_file_concat("io.h" HAVE_IO_H) +check_include_file_concat("libgen.h" HAVE_LIBGEN_H) +check_include_file_concat("locale.h" HAVE_LOCALE_H) +check_include_file_concat("net/if.h" HAVE_NET_IF_H) +check_include_file_concat("netdb.h" HAVE_NETDB_H) +check_include_file_concat("netinet/in.h" HAVE_NETINET_IN_H) +check_include_file_concat("netinet/tcp.h" HAVE_NETINET_TCP_H) +check_include_file_concat("netinet/udp.h" HAVE_NETINET_UDP_H) +check_include_file("linux/tcp.h" HAVE_LINUX_TCP_H) + +check_include_file_concat("poll.h" HAVE_POLL_H) +check_include_file_concat("pwd.h" HAVE_PWD_H) +check_include_file_concat("stdatomic.h" HAVE_STDATOMIC_H) +check_include_file_concat("stdbool.h" HAVE_STDBOOL_H) +check_include_file_concat("strings.h" HAVE_STRINGS_H) +check_include_file_concat("stropts.h" HAVE_STROPTS_H) +check_include_file_concat("termio.h" HAVE_TERMIO_H) +check_include_file_concat("termios.h" HAVE_TERMIOS_H) +check_include_file_concat("unistd.h" HAVE_UNISTD_H) +check_include_file_concat("utime.h" HAVE_UTIME_H) + +check_type_size(size_t SIZEOF_SIZE_T) +check_type_size(ssize_t SIZEOF_SSIZE_T) +check_type_size("long long" SIZEOF_LONG_LONG) +check_type_size("long" SIZEOF_LONG) +check_type_size("int" SIZEOF_INT) +check_type_size("__int64" SIZEOF___INT64) +check_type_size("time_t" SIZEOF_TIME_T) +check_type_size("suseconds_t" SIZEOF_SUSECONDS_T) +if(NOT HAVE_SIZEOF_SSIZE_T) + if(SIZEOF_LONG EQUAL SIZEOF_SIZE_T) + set(ssize_t long) + endif() + if(NOT ssize_t AND SIZEOF___INT64 EQUAL SIZEOF_SIZE_T) + set(ssize_t __int64) + endif() +endif() +# off_t is sized later, after the HAVE_FILE_OFFSET_BITS test + +if(SIZEOF_LONG_LONG) + set(HAVE_LONGLONG 1) +endif() +if(SIZEOF_SUSECONDS_T) + set(HAVE_SUSECONDS_T 1) +endif() + +if(NOT CMAKE_CROSSCOMPILING) + find_file(RANDOM_FILE urandom /dev) + mark_as_advanced(RANDOM_FILE) +endif() + +# Check for some functions that are used +if(WIN32) + set(CMAKE_REQUIRED_LIBRARIES ws2_32) +elseif(HAVE_LIBSOCKET) + set(CMAKE_REQUIRED_LIBRARIES socket) +endif() + +check_symbol_exists(fnmatch "${CURL_INCLUDES};fnmatch.h" HAVE_FNMATCH) +check_symbol_exists(basename "${CURL_INCLUDES};string.h" HAVE_BASENAME) +check_symbol_exists(opendir "${CURL_INCLUDES};dirent.h" HAVE_OPENDIR) +check_symbol_exists(socket "${CURL_INCLUDES}" HAVE_SOCKET) +check_symbol_exists(sched_yield "${CURL_INCLUDES};sched.h" HAVE_SCHED_YIELD) +check_symbol_exists(socketpair "${CURL_INCLUDES}" HAVE_SOCKETPAIR) +check_symbol_exists(recv "${CURL_INCLUDES}" HAVE_RECV) +check_symbol_exists(send "${CURL_INCLUDES}" HAVE_SEND) +check_symbol_exists(sendmsg "${CURL_INCLUDES}" HAVE_SENDMSG) +check_symbol_exists(select "${CURL_INCLUDES}" HAVE_SELECT) +check_symbol_exists(strdup "${CURL_INCLUDES};string.h" HAVE_STRDUP) +check_symbol_exists(strtok_r "${CURL_INCLUDES};string.h" HAVE_STRTOK_R) +check_symbol_exists(strcasecmp "${CURL_INCLUDES};string.h" HAVE_STRCASECMP) +check_symbol_exists(stricmp "${CURL_INCLUDES};string.h" HAVE_STRICMP) +check_symbol_exists(strcmpi "${CURL_INCLUDES};string.h" HAVE_STRCMPI) +check_symbol_exists(memrchr "${CURL_INCLUDES};string.h" HAVE_MEMRCHR) +check_symbol_exists(alarm "${CURL_INCLUDES}" HAVE_ALARM) +check_symbol_exists(arc4random "${CURL_INCLUDES};stdlib.h" HAVE_ARC4RANDOM) +check_symbol_exists(fcntl "${CURL_INCLUDES}" HAVE_FCNTL) +check_symbol_exists(getppid "${CURL_INCLUDES}" HAVE_GETPPID) +check_symbol_exists(utimes "${CURL_INCLUDES}" HAVE_UTIMES) + +check_symbol_exists(gettimeofday "${CURL_INCLUDES}" HAVE_GETTIMEOFDAY) +check_symbol_exists(closesocket "${CURL_INCLUDES}" HAVE_CLOSESOCKET) +check_symbol_exists(sigsetjmp "${CURL_INCLUDES};setjmp.h" HAVE_SIGSETJMP) +check_symbol_exists(getpass_r "${CURL_INCLUDES}" HAVE_GETPASS_R) +check_symbol_exists(getpwuid "${CURL_INCLUDES}" HAVE_GETPWUID) +check_symbol_exists(getpwuid_r "${CURL_INCLUDES}" HAVE_GETPWUID_R) +check_symbol_exists(geteuid "${CURL_INCLUDES}" HAVE_GETEUID) +check_symbol_exists(utime "${CURL_INCLUDES}" HAVE_UTIME) +check_symbol_exists(gmtime_r "${CURL_INCLUDES};stdlib.h;time.h" HAVE_GMTIME_R) + +check_symbol_exists(gethostbyname_r "${CURL_INCLUDES}" HAVE_GETHOSTBYNAME_R) + +check_symbol_exists(signal "${CURL_INCLUDES};signal.h" HAVE_SIGNAL) +check_symbol_exists(strtoll "${CURL_INCLUDES};stdlib.h" HAVE_STRTOLL) +check_symbol_exists(strerror_r "${CURL_INCLUDES};stdlib.h;string.h" HAVE_STRERROR_R) +check_symbol_exists(sigaction "signal.h" HAVE_SIGACTION) +check_symbol_exists(siginterrupt "${CURL_INCLUDES};signal.h" HAVE_SIGINTERRUPT) +check_symbol_exists(getaddrinfo "${CURL_INCLUDES};stdlib.h;string.h" HAVE_GETADDRINFO) +check_symbol_exists(getifaddrs "${CURL_INCLUDES};stdlib.h" HAVE_GETIFADDRS) +check_symbol_exists(freeaddrinfo "${CURL_INCLUDES}" HAVE_FREEADDRINFO) +check_symbol_exists(pipe "${CURL_INCLUDES}" HAVE_PIPE) +check_symbol_exists(ftruncate "${CURL_INCLUDES}" HAVE_FTRUNCATE) +check_symbol_exists(_fseeki64 "${CURL_INCLUDES};stdio.h" HAVE__FSEEKI64) +check_symbol_exists(getpeername "${CURL_INCLUDES}" HAVE_GETPEERNAME) +check_symbol_exists(getsockname "${CURL_INCLUDES}" HAVE_GETSOCKNAME) +check_symbol_exists(if_nametoindex "${CURL_INCLUDES}" HAVE_IF_NAMETOINDEX) +check_symbol_exists(getrlimit "${CURL_INCLUDES}" HAVE_GETRLIMIT) +check_symbol_exists(setlocale "${CURL_INCLUDES}" HAVE_SETLOCALE) +check_symbol_exists(setmode "${CURL_INCLUDES}" HAVE_SETMODE) +check_symbol_exists(setrlimit "${CURL_INCLUDES}" HAVE_SETRLIMIT) + +if(NOT MSVC OR (MSVC_VERSION GREATER_EQUAL 1900)) + # earlier MSVC compilers had faulty snprintf implementations + check_symbol_exists(snprintf "stdio.h" HAVE_SNPRINTF) +endif() +check_function_exists(mach_absolute_time HAVE_MACH_ABSOLUTE_TIME) +check_symbol_exists(inet_ntop "${CURL_INCLUDES};stdlib.h;string.h" HAVE_INET_NTOP) +if(MSVC AND (MSVC_VERSION LESS_EQUAL 1600)) + set(HAVE_INET_NTOP OFF) +endif() +check_symbol_exists(inet_pton "${CURL_INCLUDES};stdlib.h;string.h" HAVE_INET_PTON) + +check_symbol_exists(fsetxattr "${CURL_INCLUDES}" HAVE_FSETXATTR) +if(HAVE_FSETXATTR) + foreach(CURL_TEST HAVE_FSETXATTR_5 HAVE_FSETXATTR_6) + curl_internal_test(${CURL_TEST}) + endforeach() +endif() + +set(CMAKE_EXTRA_INCLUDE_FILES "sys/socket.h") +check_type_size("sa_family_t" SIZEOF_SA_FAMILY_T) +set(HAVE_SA_FAMILY_T ${HAVE_SIZEOF_SA_FAMILY_T}) +set(CMAKE_EXTRA_INCLUDE_FILES "") + +if(WIN32) + set(CMAKE_EXTRA_INCLUDE_FILES "winsock2.h") + check_type_size("ADDRESS_FAMILY" SIZEOF_ADDRESS_FAMILY) + set(HAVE_ADDRESS_FAMILY ${HAVE_SIZEOF_ADDRESS_FAMILY}) + set(CMAKE_EXTRA_INCLUDE_FILES "") +endif() + +# Do curl specific tests +foreach(CURL_TEST + HAVE_FCNTL_O_NONBLOCK + HAVE_IOCTLSOCKET + HAVE_IOCTLSOCKET_CAMEL + HAVE_IOCTLSOCKET_CAMEL_FIONBIO + HAVE_IOCTLSOCKET_FIONBIO + HAVE_IOCTL_FIONBIO + HAVE_IOCTL_SIOCGIFADDR + HAVE_SETSOCKOPT_SO_NONBLOCK + HAVE_O_NONBLOCK + HAVE_GETHOSTBYNAME_R_3 + HAVE_GETHOSTBYNAME_R_5 + HAVE_GETHOSTBYNAME_R_6 + HAVE_GETHOSTBYNAME_R_3_REENTRANT + HAVE_GETHOSTBYNAME_R_5_REENTRANT + HAVE_GETHOSTBYNAME_R_6_REENTRANT + HAVE_IN_ADDR_T + HAVE_BOOL_T + STDC_HEADERS + HAVE_FILE_OFFSET_BITS + HAVE_ATOMIC + ) + curl_internal_test(${CURL_TEST}) +endforeach() + +if(HAVE_FILE_OFFSET_BITS) + set(_FILE_OFFSET_BITS 64) + set(CMAKE_REQUIRED_FLAGS "-D_FILE_OFFSET_BITS=64") +endif() +check_type_size("off_t" SIZEOF_OFF_T) + +# fseeko may not exist with _FILE_OFFSET_BITS=64 but can exist with +# _FILE_OFFSET_BITS unset or 32 (e.g. Android ARMv7 with NDK 26b and API level < 24) +# so we need to test fseeko after testing for _FILE_OFFSET_BITS +check_symbol_exists(fseeko "${CURL_INCLUDES};stdio.h" HAVE_FSEEKO) + +if(HAVE_FSEEKO) + set(HAVE_DECL_FSEEKO 1) +endif() + +# include this header to get the type +set(CMAKE_REQUIRED_INCLUDES "${CURL_SOURCE_DIR}/include") +set(CMAKE_EXTRA_INCLUDE_FILES "curl/system.h") +check_type_size("curl_off_t" SIZEOF_CURL_OFF_T) +set(CMAKE_EXTRA_INCLUDE_FILES "curl/curl.h") +check_type_size("curl_socket_t" SIZEOF_CURL_SOCKET_T) +set(CMAKE_EXTRA_INCLUDE_FILES "") + +if(NOT WIN32 AND NOT CMAKE_CROSSCOMPILING) + # on not-Windows and not-crosscompiling, check for writable argv[] + include(CheckCSourceRuns) + check_c_source_runs(" + int main(int argc, char **argv) + { + (void)argc; + argv[0][0] = ' '; + return (argv[0][0] == ' ')?0:1; + }" HAVE_WRITABLE_ARGV) +endif() + +set(CMAKE_REQUIRED_FLAGS) + +option(ENABLE_WEBSOCKETS "Set to ON to enable EXPERIMENTAL websockets" OFF) + +if(ENABLE_WEBSOCKETS) + if(${SIZEOF_CURL_OFF_T} GREATER "4") + set(USE_WEBSOCKETS ON) + else() + message(WARNING "curl_off_t is too small to enable WebSockets") + endif() +endif() + +foreach(CURL_TEST + HAVE_GLIBC_STRERROR_R + HAVE_POSIX_STRERROR_R + ) + curl_internal_test(${CURL_TEST}) +endforeach() + +# Check for reentrant +foreach(CURL_TEST + HAVE_GETHOSTBYNAME_R_3 + HAVE_GETHOSTBYNAME_R_5 + HAVE_GETHOSTBYNAME_R_6) + if(NOT ${CURL_TEST}) + if(${CURL_TEST}_REENTRANT) + set(NEED_REENTRANT 1) + endif() + endif() +endforeach() + +if(NEED_REENTRANT) + foreach(CURL_TEST + HAVE_GETHOSTBYNAME_R_3 + HAVE_GETHOSTBYNAME_R_5 + HAVE_GETHOSTBYNAME_R_6) + set(${CURL_TEST} 0) + if(${CURL_TEST}_REENTRANT) + set(${CURL_TEST} 1) + endif() + endforeach() +endif() + +if(NOT WIN32) + # Check clock_gettime(CLOCK_MONOTONIC, x) support + curl_internal_test(HAVE_CLOCK_GETTIME_MONOTONIC) +endif() + +# Check compiler support of __builtin_available() +curl_internal_test(HAVE_BUILTIN_AVAILABLE) + +# Some other minor tests + +if(NOT HAVE_IN_ADDR_T) + set(in_addr_t "unsigned long") +endif() + +# Check for nonblocking +set(HAVE_DISABLED_NONBLOCKING 1) +if(HAVE_FIONBIO OR + HAVE_IOCTLSOCKET OR + HAVE_IOCTLSOCKET_CASE OR + HAVE_O_NONBLOCK) + set(HAVE_DISABLED_NONBLOCKING) +endif() + +if(CMAKE_COMPILER_IS_GNUCC AND APPLE) + include(CheckCCompilerFlag) + check_c_compiler_flag(-Wno-long-double HAVE_C_FLAG_Wno_long_double) + if(HAVE_C_FLAG_Wno_long_double) + # The Mac version of GCC warns about use of long double. Disable it. + get_source_file_property(MPRINTF_COMPILE_FLAGS mprintf.c COMPILE_FLAGS) + if(MPRINTF_COMPILE_FLAGS) + set(MPRINTF_COMPILE_FLAGS "${MPRINTF_COMPILE_FLAGS} -Wno-long-double") + else() + set(MPRINTF_COMPILE_FLAGS "-Wno-long-double") + endif() + set_source_files_properties(mprintf.c PROPERTIES + COMPILE_FLAGS ${MPRINTF_COMPILE_FLAGS}) + endif() +endif() + +include(CMake/OtherTests.cmake) + +add_definitions(-DHAVE_CONFIG_H) + +# For Windows, all compilers used by CMake should support large files +if(WIN32) + set(USE_WIN32_LARGE_FILES ON) + + # Use the manifest embedded in the Windows Resource + set(CMAKE_RC_FLAGS "${CMAKE_RC_FLAGS} -DCURL_EMBED_MANIFEST") + + # We use crypto functions that are not available for UWP apps + if(NOT WINDOWS_STORE) + set(USE_WIN32_CRYPTO ON) + endif() + + # Link required libraries for USE_WIN32_CRYPTO or USE_SCHANNEL + if(USE_WIN32_CRYPTO OR USE_SCHANNEL) + list(APPEND CURL_LIBS "advapi32" "crypt32") + endif() +endif() + +if(MSVC) + # Disable default manifest added by CMake + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /MANIFEST:NO") + + add_definitions(-D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE) + if(CMAKE_C_FLAGS MATCHES "/W[0-4]") + string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}") + else() + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /W4") + endif() + + # Use multithreaded compilation on VS 2008+ + if(MSVC_VERSION GREATER_EQUAL 1500) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /MP") + endif() +endif() + +if(CURL_WERROR) + if(MSVC_VERSION) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /WX") + else() + # this assumes clang or gcc style options + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror") + endif() +endif() + +if(CURL_LTO) + if(CMAKE_VERSION VERSION_LESS 3.9) + message(FATAL_ERROR "Requested LTO but your cmake version ${CMAKE_VERSION} is to old. You need at least 3.9") + endif() + + cmake_policy(SET CMP0069 NEW) + + include(CheckIPOSupported) + check_ipo_supported(RESULT CURL_HAS_LTO OUTPUT CURL_LTO_ERROR LANGUAGES C) + if(CURL_HAS_LTO) + message(STATUS "LTO supported and enabled") + else() + message(FATAL_ERROR "LTO was requested - but compiler doesn't support it\n${CURL_LTO_ERROR}") + endif() +endif() + + +# Ugly (but functional) way to include "Makefile.inc" by transforming it (= regenerate it). +function(transform_makefile_inc INPUT_FILE OUTPUT_FILE) + file(READ ${INPUT_FILE} MAKEFILE_INC_TEXT) + string(REPLACE "$(top_srcdir)" "\${CURL_SOURCE_DIR}" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT}) + string(REPLACE "$(top_builddir)" "\${CURL_BINARY_DIR}" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT}) + + string(REGEX REPLACE "\\\\\n" "!Ï€!α!" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT}) + string(REGEX REPLACE "([a-zA-Z_][a-zA-Z0-9_]*)[\t ]*=[\t ]*([^\n]*)" "SET(\\1 \\2)" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT}) + string(REPLACE "!Ï€!α!" "\n" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT}) + + string(REGEX REPLACE "\\$\\(([a-zA-Z_][a-zA-Z0-9_]*)\\)" "\${\\1}" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT}) # Replace $() with ${} + string(REGEX REPLACE "@([a-zA-Z_][a-zA-Z0-9_]*)@" "\${\\1}" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT}) # Replace @@ with ${}, even if that may not be read by CMake scripts. + file(WRITE ${OUTPUT_FILE} ${MAKEFILE_INC_TEXT}) + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${INPUT_FILE}") +endfunction() + +include(GNUInstallDirs) + +set(CURL_INSTALL_CMAKE_DIR ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}) +set(TARGETS_EXPORT_NAME "${PROJECT_NAME}Targets") +set(generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated") +set(project_config "${generated_dir}/${PROJECT_NAME}Config.cmake") +set(version_config "${generated_dir}/${PROJECT_NAME}ConfigVersion.cmake") + +cmake_dependent_option(BUILD_TESTING "Build tests" + ON "PERL_FOUND;NOT CURL_DISABLE_TESTS" + OFF) + +if(HAVE_MANUAL_TOOLS) + add_subdirectory(docs) +endif() + +add_subdirectory(lib) + +if(BUILD_CURL_EXE) + add_subdirectory(src) +endif() + +option(BUILD_EXAMPLES "Build libcurl examples" OFF) +if(BUILD_EXAMPLES) + add_subdirectory(docs/examples) +endif() + +if(BUILD_TESTING) + add_subdirectory(tests) +endif() + +if(NOT CURL_DISABLE_INSTALL) + + install(FILES "${PROJECT_SOURCE_DIR}/scripts/mk-ca-bundle.pl" + DESTINATION ${CMAKE_INSTALL_BINDIR} + PERMISSIONS + OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE + WORLD_READ WORLD_EXECUTE) + + # Helper to populate a list (_items) with a label when conditions (the remaining + # args) are satisfied + macro(_add_if label) + # needs to be a macro to allow this indirection + if(${ARGN}) + set(_items ${_items} "${label}") + endif() + endmacro() + + # NTLM support requires crypto function adaptions from various SSL libs + if(NOT (CURL_DISABLE_NTLM) AND + (USE_OPENSSL OR USE_MBEDTLS OR USE_DARWINSSL OR USE_WIN32_CRYPTO OR USE_GNUTLS)) + set(use_curl_ntlm_core ON) + endif() + + # Clear list and try to detect available features + set(_items) + _add_if("SSL" SSL_ENABLED) + _add_if("IPv6" ENABLE_IPV6) + _add_if("UnixSockets" USE_UNIX_SOCKETS) + _add_if("libz" HAVE_LIBZ) + _add_if("brotli" HAVE_BROTLI) + _add_if("zstd" HAVE_ZSTD) + _add_if("AsynchDNS" USE_ARES OR USE_THREADS_POSIX OR USE_THREADS_WIN32) + _add_if("IDN" HAVE_LIBIDN2 OR USE_WIN32_IDN OR USE_APPLE_IDN) + _add_if("Largefile" (SIZEOF_CURL_OFF_T GREATER 4) AND + ((SIZEOF_OFF_T GREATER 4) OR USE_WIN32_LARGE_FILES)) + _add_if("SSPI" USE_WINDOWS_SSPI) + _add_if("GSS-API" HAVE_GSSAPI) + _add_if("alt-svc" NOT CURL_DISABLE_ALTSVC) + _add_if("HSTS" NOT CURL_DISABLE_HSTS) + _add_if("SPNEGO" NOT CURL_DISABLE_NEGOTIATE_AUTH AND + (HAVE_GSSAPI OR USE_WINDOWS_SSPI)) + _add_if("Kerberos" NOT CURL_DISABLE_KERBEROS_AUTH AND + (HAVE_GSSAPI OR USE_WINDOWS_SSPI)) + _add_if("NTLM" NOT (CURL_DISABLE_NTLM) AND + (use_curl_ntlm_core OR USE_WINDOWS_SSPI)) + _add_if("TLS-SRP" USE_TLS_SRP) + _add_if("HTTP2" USE_NGHTTP2) + _add_if("HTTP3" USE_NGTCP2 OR USE_QUICHE OR USE_OPENSSL_QUIC) + _add_if("MultiSSL" CURL_WITH_MULTI_SSL) + # TODO wolfSSL only support this from v5.0.0 onwards + _add_if("HTTPS-proxy" SSL_ENABLED AND (USE_OPENSSL OR USE_GNUTLS + OR USE_SCHANNEL OR USE_RUSTLS OR USE_BEARSSL OR + USE_MBEDTLS OR USE_SECTRANSP)) + _add_if("unicode" ENABLE_UNICODE) + _add_if("threadsafe" HAVE_ATOMIC OR + (USE_THREADS_POSIX AND HAVE_PTHREAD_H) OR + (WIN32 AND HAVE_WIN32_WINNT GREATER_EQUAL 0x600)) + _add_if("PSL" USE_LIBPSL) + string(REPLACE ";" " " SUPPORT_FEATURES "${_items}") + message(STATUS "Enabled features: ${SUPPORT_FEATURES}") + + # Clear list and try to detect available protocols + set(_items) + _add_if("HTTP" NOT CURL_DISABLE_HTTP) + _add_if("IPFS" NOT CURL_DISABLE_HTTP) + _add_if("IPNS" NOT CURL_DISABLE_HTTP) + _add_if("HTTPS" NOT CURL_DISABLE_HTTP AND SSL_ENABLED) + _add_if("ECH" HAVE_ECH) + _add_if("HTTPSRR" HAVE_ECH) + _add_if("FTP" NOT CURL_DISABLE_FTP) + _add_if("FTPS" NOT CURL_DISABLE_FTP AND SSL_ENABLED) + _add_if("FILE" NOT CURL_DISABLE_FILE) + _add_if("TELNET" NOT CURL_DISABLE_TELNET) + _add_if("LDAP" NOT CURL_DISABLE_LDAP) + # CURL_DISABLE_LDAP implies CURL_DISABLE_LDAPS + _add_if("LDAPS" NOT CURL_DISABLE_LDAPS AND + ((USE_OPENLDAP AND SSL_ENABLED) OR + (NOT USE_OPENLDAP AND HAVE_LDAP_SSL))) + _add_if("DICT" NOT CURL_DISABLE_DICT) + _add_if("TFTP" NOT CURL_DISABLE_TFTP) + _add_if("GOPHER" NOT CURL_DISABLE_GOPHER) + _add_if("GOPHERS" NOT CURL_DISABLE_GOPHER AND SSL_ENABLED) + _add_if("POP3" NOT CURL_DISABLE_POP3) + _add_if("POP3S" NOT CURL_DISABLE_POP3 AND SSL_ENABLED) + _add_if("IMAP" NOT CURL_DISABLE_IMAP) + _add_if("IMAPS" NOT CURL_DISABLE_IMAP AND SSL_ENABLED) + _add_if("SMB" NOT CURL_DISABLE_SMB AND + use_curl_ntlm_core AND (SIZEOF_CURL_OFF_T GREATER 4)) + _add_if("SMBS" NOT CURL_DISABLE_SMB AND SSL_ENABLED AND + use_curl_ntlm_core AND (SIZEOF_CURL_OFF_T GREATER 4)) + _add_if("SMTP" NOT CURL_DISABLE_SMTP) + _add_if("SMTPS" NOT CURL_DISABLE_SMTP AND SSL_ENABLED) + _add_if("SCP" USE_LIBSSH2 OR USE_LIBSSH) + _add_if("SFTP" USE_LIBSSH2 OR USE_LIBSSH) + _add_if("RTSP" NOT CURL_DISABLE_RTSP) + _add_if("RTMP" USE_LIBRTMP) + _add_if("MQTT" NOT CURL_DISABLE_MQTT) + _add_if("WS" USE_WEBSOCKETS) + _add_if("WSS" USE_WEBSOCKETS) + if(_items) + list(SORT _items) + endif() + string(REPLACE ";" " " SUPPORT_PROTOCOLS "${_items}") + message(STATUS "Enabled protocols: ${SUPPORT_PROTOCOLS}") + + # Clear list and collect SSL backends + set(_items) + _add_if("Schannel" SSL_ENABLED AND USE_SCHANNEL) + _add_if("OpenSSL" SSL_ENABLED AND USE_OPENSSL) + _add_if("Secure Transport" SSL_ENABLED AND USE_SECTRANSP) + _add_if("mbedTLS" SSL_ENABLED AND USE_MBEDTLS) + _add_if("BearSSL" SSL_ENABLED AND USE_BEARSSL) + _add_if("wolfSSL" SSL_ENABLED AND USE_WOLFSSL) + _add_if("GnuTLS" SSL_ENABLED AND USE_GNUTLS) + + if(_items) + list(SORT _items) + endif() + string(REPLACE ";" " " SSL_BACKENDS "${_items}") + message(STATUS "Enabled SSL backends: ${SSL_BACKENDS}") + if(CURL_DEFAULT_SSL_BACKEND) + message(STATUS "Default SSL backend: ${CURL_DEFAULT_SSL_BACKEND}") + endif() + + # curl-config needs the following options to be set. + set(CC "${CMAKE_C_COMPILER}") + # TODO probably put a -D... options here? + set(CONFIGURE_OPTIONS "") + set(CURLVERSION "${CURL_VERSION}") + set(exec_prefix "\${prefix}") + set(includedir "\${prefix}/include") + set(LDFLAGS "${CMAKE_SHARED_LINKER_FLAGS}") + set(LIBCURL_LIBS "") + set(libdir "${CMAKE_INSTALL_PREFIX}/lib") + + # For processing full path libraries into -L and -l ld options, + # the directories that go with the -L option are cached, so they + # only get added once per such directory. + set(_libcurl_libs_dirs) + # To avoid getting unnecessary -L options for known system directories, + # _libcurl_libs_dirs is seeded with them. + foreach(_libdir ${CMAKE_SYSTEM_PREFIX_PATH}) + if(_libdir MATCHES "/$") + set(_libdir "${_libdir}lib") + else() + set(_libdir "${_libdir}/lib") + endif() + if(IS_DIRECTORY "${_libdir}") + list(APPEND _libcurl_libs_dirs "${_libdir}") + endif() + if(DEFINED CMAKE_LIBRARY_ARCHITECTURE) + set(_libdir "${_libdir}/${CMAKE_LIBRARY_ARCHITECTURE}") + if(IS_DIRECTORY "${_libdir}") + list(APPEND _libcurl_libs_dirs "${_libdir}") + endif() + endif() + endforeach() + + foreach(_lib ${CMAKE_C_IMPLICIT_LINK_LIBRARIES} ${CURL_LIBS}) + if(TARGET "${_lib}") + set(_libname "${_lib}") + get_target_property(_imported "${_libname}" IMPORTED) + if(NOT _imported) + # Reading the LOCATION property on non-imported target will error out. + # Assume the user won't need this information in the .pc file. + continue() + endif() + get_target_property(_lib "${_libname}" LOCATION) + if(NOT _lib) + message(WARNING "Bad lib in library list: ${_libname}") + continue() + endif() + endif() + if(_lib MATCHES "^-") + set(LIBCURL_LIBS "${LIBCURL_LIBS} ${_lib}") + elseif(_lib MATCHES ".*/.*") + # This gets a bit more complex, because we want to specify the + # directory separately, and only once per directory + string(REGEX REPLACE "^(.*)/[^/]*$" "\\1" _libdir "${_lib}") + string(REGEX REPLACE "^.*/([^/.]*).*$" "\\1" _libname "${_lib}") + if(_libname MATCHES "^lib") + list(FIND _libcurl_libs_dirs "${_libdir}" _libdir_index) + if(_libdir_index LESS 0) + list(APPEND _libcurl_libs_dirs "${_libdir}") + set(LIBCURL_LIBS "${LIBCURL_LIBS} -L${_libdir}") + endif() + string(REGEX REPLACE "^lib" "" _libname "${_libname}") + set(LIBCURL_LIBS "${LIBCURL_LIBS} -l${_libname}") + else() + set(LIBCURL_LIBS "${LIBCURL_LIBS} ${_lib}") + endif() + else() + set(LIBCURL_LIBS "${LIBCURL_LIBS} -l${_lib}") + endif() + endforeach() + if(BUILD_SHARED_LIBS) + set(ENABLE_SHARED "yes") + set(LIBCURL_NO_SHARED "") + set(CPPFLAG_CURL_STATICLIB "") + else() + set(ENABLE_SHARED "no") + set(LIBCURL_NO_SHARED "${LIBCURL_LIBS}") + set(CPPFLAG_CURL_STATICLIB "-DCURL_STATICLIB") + endif() + if(BUILD_STATIC_LIBS) + set(ENABLE_STATIC "yes") + else() + set(ENABLE_STATIC "no") + endif() + # "a" (Linux) or "lib" (Windows) + string(REPLACE "." "" libext "${CMAKE_STATIC_LIBRARY_SUFFIX}") + set(prefix "${CMAKE_INSTALL_PREFIX}") + # Set this to "yes" to append all libraries on which -lcurl is dependent + set(REQUIRE_LIB_DEPS "no") + # SUPPORT_FEATURES + # SUPPORT_PROTOCOLS + set(VERSIONNUM "${CURL_VERSION_NUM}") + + # Finally generate a "curl-config" matching this config + # Use: + # * ENABLE_SHARED + # * ENABLE_STATIC + configure_file("${CURL_SOURCE_DIR}/curl-config.in" + "${CURL_BINARY_DIR}/curl-config" @ONLY) + install(FILES "${CURL_BINARY_DIR}/curl-config" + DESTINATION ${CMAKE_INSTALL_BINDIR} + PERMISSIONS + OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE + WORLD_READ WORLD_EXECUTE) + + # Finally generate a pkg-config file matching this config + configure_file("${CURL_SOURCE_DIR}/libcurl.pc.in" + "${CURL_BINARY_DIR}/libcurl.pc" @ONLY) + install(FILES "${CURL_BINARY_DIR}/libcurl.pc" + DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) + + # install headers + install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/curl" + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} + FILES_MATCHING PATTERN "*.h") + + include(CMakePackageConfigHelpers) + write_basic_package_version_file( + "${version_config}" + VERSION ${CURL_VERSION} + COMPATIBILITY SameMajorVersion + ) + file(READ "${version_config}" generated_version_config) + file(WRITE "${version_config}" + "if(NOT PACKAGE_FIND_VERSION_RANGE AND PACKAGE_FIND_VERSION_MAJOR STREQUAL \"7\") + # Version 8 satisfies version 7... requirements + set(PACKAGE_FIND_VERSION_MAJOR 8) + set(PACKAGE_FIND_VERSION_COUNT 1) + endif() + ${generated_version_config}" + ) + + # Use: + # * TARGETS_EXPORT_NAME + # * PROJECT_NAME + configure_package_config_file(CMake/curl-config.cmake.in + "${project_config}" + INSTALL_DESTINATION ${CURL_INSTALL_CMAKE_DIR} + ) + + if(CURL_ENABLE_EXPORT_TARGET) + install( + EXPORT "${TARGETS_EXPORT_NAME}" + NAMESPACE "${PROJECT_NAME}::" + DESTINATION ${CURL_INSTALL_CMAKE_DIR} + ) + endif() + + install( + FILES ${version_config} ${project_config} + DESTINATION ${CURL_INSTALL_CMAKE_DIR} + ) + + # Workaround for MSVS10 to avoid the Dialog Hell + # FIXME: This could be removed with future version of CMake. + if(MSVC_VERSION EQUAL 1600) + set(CURL_SLN_FILENAME "${CMAKE_CURRENT_BINARY_DIR}/CURL.sln") + if(EXISTS "${CURL_SLN_FILENAME}") + file(APPEND "${CURL_SLN_FILENAME}" "\n# This should be regenerated!\n") + endif() + endif() + + if(NOT TARGET curl_uninstall) + configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/CMake/cmake_uninstall.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/CMake/cmake_uninstall.cmake + IMMEDIATE @ONLY) + + add_custom_target(curl_uninstall + COMMAND ${CMAKE_COMMAND} -P + ${CMAKE_CURRENT_BINARY_DIR}/CMake/cmake_uninstall.cmake) + endif() +endif() diff --git a/third_party/curl/COPYING b/third_party/curl/COPYING new file mode 100644 index 0000000..d9e7e0b --- /dev/null +++ b/third_party/curl/COPYING @@ -0,0 +1,22 @@ +COPYRIGHT AND PERMISSION NOTICE + +Copyright (c) 1996 - 2024, Daniel Stenberg, , and many +contributors, see the THANKS file. + +All rights reserved. + +Permission to use, copy, modify, and distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright +notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. 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. + +Except as contained in this notice, the name of a copyright holder shall not +be used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization of the copyright holder. diff --git a/third_party/curl/Dockerfile b/third_party/curl/Dockerfile new file mode 100644 index 0000000..834e275 --- /dev/null +++ b/third_party/curl/Dockerfile @@ -0,0 +1,41 @@ +# Copyright (C) Daniel Stenberg, , et al. +# +# SPDX-License-Identifier: curl + +# Self-contained build environment to match the release environment. +# +# Build and set the timestamp for the date corresponding to the release +# +# docker build --build-arg SOURCE_DATE_EPOCH=1711526400 --build-arg UID=$(id -u) --build-arg GID=$(id -g) -t curl/curl . +# +# Then run commands from within the build environment, for example +# +# docker run --rm -it -u $(id -u):$(id -g) -v $(pwd):/usr/src -w /usr/src curl/curl autoreconf -fi +# docker run --rm -it -u $(id -u):$(id -g) -v $(pwd):/usr/src -w /usr/src curl/curl ./configure --without-ssl --without-libpsl +# docker run --rm -it -u $(id -u):$(id -g) -v $(pwd):/usr/src -w /usr/src curl/curl make +# docker run --rm -it -u $(id -u):$(id -g) -v $(pwd):/usr/src -w /usr/src curl/curl ./maketgz 8.7.1 +# +# or get into a shell in the build environment, for example +# +# docker run --rm -it -u $(id -u):$(id -g) -v (pwd):/usr/src -w /usr/src curl/curl bash +# $ autoreconf -fi +# $ ./configure --without-ssl --without-libpsl +# $ make +# $ ./maketgz 8.7.1 + +# To update, get the latest digest e.g. from https://hub.docker.com/_/debian/tags +FROM debian:bookworm-slim@sha256:911821c26cc366231183098f489068afff2d55cf56911cb5b7bd32796538dfe1 + +RUN apt-get update -qq && apt-get install -qq -y --no-install-recommends \ + build-essential make autoconf automake libtool git perl zip zlib1g-dev gawk && \ + rm -rf /var/lib/apt/lists/* + +ARG UID=1000 GID=1000 + +RUN groupadd --gid $UID dev && \ + useradd --uid $UID --gid dev --shell /bin/bash --create-home dev + +USER dev:dev + +ARG SOURCE_DATE_EPOCH +ENV SOURCE_DATE_EPOCH=${SOURCE_DATE_EPOCH:-1} diff --git a/third_party/curl/Makefile b/third_party/curl/Makefile new file mode 100644 index 0000000..3db331a --- /dev/null +++ b/third_party/curl/Makefile @@ -0,0 +1,71 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +all: + ./configure + make + +ssl: + ./configure --with-openssl + make + +vc: + cd winbuild + nmake /f Makefile.vc MACHINE=x86 + +vc-x64: + cd winbuild + nmake /f Makefile.vc MACHINE=x64 + +djgpp%: + $(MAKE) -C lib -f Makefile.mk CFG=$@ CROSSPREFIX=i586-pc-msdosdjgpp- + $(MAKE) -C src -f Makefile.mk CFG=$@ CROSSPREFIX=i586-pc-msdosdjgpp- + +cygwin: + ./configure + make + +cygwin-ssl: + ./configure --with-openssl + make + +amiga%: + $(MAKE) -C lib -f Makefile.mk CFG=$@ CROSSPREFIX=m68k-amigaos- + $(MAKE) -C src -f Makefile.mk CFG=$@ CROSSPREFIX=m68k-amigaos- + +unix: all + +unix-ssl: ssl + +linux: all + +linux-ssl: ssl + +ca-bundle: scripts/mk-ca-bundle.pl + @echo "generate a fresh ca-bundle.crt" + @perl $< -b -l -u lib/ca-bundle.crt + +ca-firefox: lib/firefox-db2pem.sh + @echo "generate a fresh ca-bundle.crt" + ./lib/firefox-db2pem.sh lib/ca-bundle.crt diff --git a/third_party/curl/Makefile.am b/third_party/curl/Makefile.am new file mode 100644 index 0000000..ad8651c --- /dev/null +++ b/third_party/curl/Makefile.am @@ -0,0 +1,231 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +AUTOMAKE_OPTIONS = foreign + +ACLOCAL_AMFLAGS = -I m4 + +CMAKE_DIST = \ + CMake/cmake_uninstall.cmake.in \ + CMake/CMakeConfigurableFile.in \ + CMake/curl-config.cmake.in \ + CMake/CurlSymbolHiding.cmake \ + CMake/CurlTests.c \ + CMake/FindBearSSL.cmake \ + CMake/FindBrotli.cmake \ + CMake/FindCARES.cmake \ + CMake/FindGSS.cmake \ + CMake/FindLibPSL.cmake \ + CMake/FindLibSSH2.cmake \ + CMake/FindMbedTLS.cmake \ + CMake/FindMSH3.cmake \ + CMake/FindNGHTTP2.cmake \ + CMake/FindNGHTTP3.cmake \ + CMake/FindNGTCP2.cmake \ + CMake/FindQUICHE.cmake \ + CMake/FindWolfSSL.cmake \ + CMake/FindZstd.cmake \ + CMake/Macros.cmake \ + CMake/OtherTests.cmake \ + CMake/PickyWarnings.cmake \ + CMake/Platforms/WindowsCache.cmake \ + CMake/Utilities.cmake \ + CMakeLists.txt + +VC_DIST = projects/README.md \ + projects/build-openssl.bat \ + projects/build-wolfssl.bat \ + projects/checksrc.bat \ + projects/generate.bat \ + projects/wolfssl_options.h \ + projects/wolfssl_override.props + +WINBUILD_DIST = winbuild/README.md winbuild/gen_resp_file.bat \ + winbuild/MakefileBuild.vc winbuild/Makefile.vc winbuild/makedebug.cmd + +PLAN9_DIST = plan9/include/mkfile \ + plan9/include/mkfile \ + plan9/mkfile.proto \ + plan9/mkfile \ + plan9/README \ + plan9/lib/mkfile.inc \ + plan9/lib/mkfile \ + plan9/src/mkfile.inc \ + plan9/src/mkfile + +EXTRA_DIST = CHANGES COPYING maketgz Makefile.dist curl-config.in \ + RELEASE-NOTES buildconf libcurl.pc.in $(CMAKE_DIST) $(VC_DIST) \ + $(WINBUILD_DIST) $(PLAN9_DIST) lib/libcurl.vers.in buildconf.bat \ + libcurl.def Dockerfile + +CLEANFILES = $(VC14_LIBVCXPROJ) $(VC14_SRCVCXPROJ) \ + $(VC14_10_LIBVCXPROJ) $(VC14_10_SRCVCXPROJ) \ + $(VC14_20_LIBVCXPROJ) $(VC14_20_SRCVCXPROJ) \ + $(VC14_30_LIBVCXPROJ) $(VC14_30_SRCVCXPROJ) + +bin_SCRIPTS = curl-config + +SUBDIRS = lib docs src scripts +DIST_SUBDIRS = $(SUBDIRS) tests packages scripts include docs + +pkgconfigdir = $(libdir)/pkgconfig +pkgconfig_DATA = libcurl.pc + +# List of files required to generate VC IDE .dsp, .vcproj and .vcxproj files +include lib/Makefile.inc +include src/Makefile.inc + +dist-hook: + rm -rf $(top_builddir)/tests/log + find $(distdir) -name "*.dist" -exec rm {} \; + (distit=`find $(srcdir) -name "*.dist" | grep -v ./ares/`; \ + for file in $$distit; do \ + strip=`echo $$file | sed -e s/^$(srcdir)// -e s/\.dist//`; \ + cp -p $$file $(distdir)$$strip; \ + done) + +check: test examples check-docs + +if CROSSCOMPILING +test-full: test +test-torture: test + +test: + @echo "NOTICE: we can't run the tests when cross-compiling!" + +else + +test: + @(cd tests; $(MAKE) all quiet-test) + +test-full: + @(cd tests; $(MAKE) all full-test) + +test-nonflaky: + @(cd tests; $(MAKE) all nonflaky-test) + +test-torture: + @(cd tests; $(MAKE) all torture-test) + +test-event: + @(cd tests; $(MAKE) all event-test) + +test-am: + @(cd tests; $(MAKE) all am-test) + +test-ci: + @(cd tests; $(MAKE) all ci-test) + +endif + +examples: + @(cd docs/examples; $(MAKE) check) + +check-docs: + @(cd docs/libcurl; $(MAKE) check) + +# Build source and binary rpms. For rpm-3.0 and above, the ~/.rpmmacros +# must contain the following line: +# %_topdir /home/loic/local/rpm +# and that /home/loic/local/rpm contains the directory SOURCES, BUILD etc. +# +# cd /home/loic/local/rpm ; mkdir -p SOURCES BUILD RPMS/i386 SPECS SRPMS +# +# If additional configure flags are needed to build the package, add the +# following in ~/.rpmmacros +# %configure CFLAGS="%{optflags}" ./configure %{_target_platform} --prefix=%{_prefix} ${AM_CONFIGFLAGS} +# and run make rpm in the following way: +# AM_CONFIGFLAGS='--with-uri=/home/users/loic/local/RedHat-6.2' make rpm +# + +rpms: + $(MAKE) RPMDIST=curl rpm + $(MAKE) RPMDIST=curl-ssl rpm + +rpm: + RPM_TOPDIR=`rpm --showrc | $(PERL) -n -e 'print if(s/.*_topdir\s+(.*)/$$1/)'` ; \ + cp $(srcdir)/packages/Linux/RPM/$(RPMDIST).spec $$RPM_TOPDIR/SPECS ; \ + cp $(PACKAGE)-$(VERSION).tar.gz $$RPM_TOPDIR/SOURCES ; \ + rpm -ba --clean --rmsource $$RPM_TOPDIR/SPECS/$(RPMDIST).spec ; \ + mv $$RPM_TOPDIR/RPMS/i386/$(RPMDIST)-*.rpm . ; \ + mv $$RPM_TOPDIR/SRPMS/$(RPMDIST)-*.src.rpm . + +# +# Build a Solaris pkgadd format file +# run 'make pkgadd' once you've done './configure' and 'make' to make a Solaris pkgadd format +# file (which ends up back in this directory). +# The pkgadd file is in 'pkgtrans' format, so to install on Solaris, do +# pkgadd -d ./HAXXcurl-* +# + +# gak - libtool requires an absolute directory, hence the pwd below... +pkgadd: + umask 022 ; \ + $(MAKE) install DESTDIR=`/bin/pwd`/packages/Solaris/root ; \ + cat COPYING > $(srcdir)/packages/Solaris/copyright ; \ + cd $(srcdir)/packages/Solaris && $(MAKE) package + +# +# Build a cygwin binary tarball installation file +# resulting .tar.bz2 file will end up at packages/Win32/cygwin +cygwinbin: + $(MAKE) -C packages/Win32/cygwin cygwinbin + +# We extend the standard install with a custom hook: +if BUILD_DOCS +install-data-hook: + (cd include && $(MAKE) install) + (cd docs && $(MAKE) install) + (cd docs/libcurl && $(MAKE) install) +else +install-data-hook: + (cd include && $(MAKE) install) + (cd docs && $(MAKE) install) +endif + +# We extend the standard uninstall with a custom hook: +uninstall-hook: + (cd include && $(MAKE) uninstall) + (cd docs && $(MAKE) uninstall) + (cd docs/libcurl && $(MAKE) uninstall) + +ca-bundle: $(srcdir)/scripts/mk-ca-bundle.pl + @echo "generating a fresh ca-bundle.crt" + @perl $(srcdir)/scripts/mk-ca-bundle.pl -b -l -u lib/ca-bundle.crt + +ca-firefox: $(srcdir)/scripts/firefox-db2pem.sh + @echo "generating a fresh ca-bundle.crt" + $(srcdir)/scripts/firefox-db2pem.sh lib/ca-bundle.crt + +checksrc: + (cd lib && $(MAKE) checksrc) + (cd src && $(MAKE) checksrc) + (cd tests && $(MAKE) checksrc) + (cd include/curl && $(MAKE) checksrc) + (cd docs/examples && $(MAKE) checksrc) + (cd packages && $(MAKE) checksrc) + +tidy: + (cd src && $(MAKE) tidy) + (cd lib && $(MAKE) tidy) diff --git a/third_party/curl/Makefile.in b/third_party/curl/Makefile.in new file mode 100644 index 0000000..fcd79bf --- /dev/null +++ b/third_party/curl/Makefile.in @@ -0,0 +1,1788 @@ +# Makefile.in generated by automake 1.16.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994-2021 Free Software Foundation, Inc. + +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# ./src/Makefile.inc +# Using the backslash as line continuation character might be problematic with +# some make flavours. If we ever want to change this in a portable manner then +# we should consider this idea : +# CSRC1 = file1.c file2.c file3.c +# CSRC2 = file4.c file5.c file6.c +# CSOURCES = $(CSRC1) $(CSRC2) + + +VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = . +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4/curl-amissl.m4 \ + $(top_srcdir)/m4/curl-bearssl.m4 \ + $(top_srcdir)/m4/curl-compilers.m4 \ + $(top_srcdir)/m4/curl-confopts.m4 \ + $(top_srcdir)/m4/curl-functions.m4 \ + $(top_srcdir)/m4/curl-gnutls.m4 \ + $(top_srcdir)/m4/curl-mbedtls.m4 \ + $(top_srcdir)/m4/curl-openssl.m4 \ + $(top_srcdir)/m4/curl-override.m4 \ + $(top_srcdir)/m4/curl-reentrant.m4 \ + $(top_srcdir)/m4/curl-rustls.m4 \ + $(top_srcdir)/m4/curl-schannel.m4 \ + $(top_srcdir)/m4/curl-sectransp.m4 \ + $(top_srcdir)/m4/curl-sysconfig.m4 \ + $(top_srcdir)/m4/curl-wolfssl.m4 $(top_srcdir)/m4/libtool.m4 \ + $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ + $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ + $(top_srcdir)/m4/xc-am-iface.m4 \ + $(top_srcdir)/m4/xc-cc-check.m4 \ + $(top_srcdir)/m4/xc-lt-iface.m4 \ + $(top_srcdir)/m4/xc-translit.m4 \ + $(top_srcdir)/m4/xc-val-flgs.m4 \ + $(top_srcdir)/m4/zz40-xc-ovr.m4 \ + $(top_srcdir)/m4/zz50-xc-ovr.m4 \ + $(top_srcdir)/m4/zz60-xc-ovr.m4 $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(top_srcdir)/configure \ + $(am__configure_deps) $(am__DIST_COMMON) +am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ + configure.lineno config.status.lineno +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/lib/curl_config.h +CONFIG_CLEAN_FILES = curl-config libcurl.pc +CONFIG_CLEAN_VPATH_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(bindir)" "$(DESTDIR)$(pkgconfigdir)" +SCRIPTS = $(bin_SCRIPTS) +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ + ctags-recursive dvi-recursive html-recursive info-recursive \ + install-data-recursive install-dvi-recursive \ + install-exec-recursive install-html-recursive \ + install-info-recursive install-pdf-recursive \ + install-ps-recursive install-recursive installcheck-recursive \ + installdirs-recursive pdf-recursive ps-recursive \ + tags-recursive uninstall-recursive +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +DATA = $(pkgconfig_DATA) +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +am__recursive_targets = \ + $(RECURSIVE_TARGETS) \ + $(RECURSIVE_CLEAN_TARGETS) \ + $(am__extra_recursive_targets) +AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ + cscope distdir distdir-am dist dist-all distcheck +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` +am__DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/curl-config.in \ + $(srcdir)/lib/Makefile.inc $(srcdir)/libcurl.pc.in \ + $(srcdir)/src/Makefile.inc COPYING README compile config.guess \ + config.sub depcomp install-sh ltmain.sh missing +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +distdir = $(PACKAGE)-$(VERSION) +top_distdir = $(distdir) +am__remove_distdir = \ + if test -d "$(distdir)"; then \ + find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \ + && rm -rf "$(distdir)" \ + || { sleep 5 && rm -rf "$(distdir)"; }; \ + else :; fi +am__post_remove_distdir = $(am__remove_distdir) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" +DIST_ARCHIVES = $(distdir).tar.gz +GZIP_ENV = --best +DIST_TARGETS = dist-gzip +# Exists only to be overridden by the user if desired. +AM_DISTCHECK_DVI_TARGET = dvi +distuninstallcheck_listfiles = find . -type f -print +am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \ + | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$' +distcleancheck_listfiles = find . -type f -print +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +APACHECTL = @APACHECTL@ +APXS = @APXS@ +AR = @AR@ +AR_FLAGS = @AR_FLAGS@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +BLANK_AT_MAKETIME = @BLANK_AT_MAKETIME@ +CADDY = @CADDY@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CFLAG_CURL_SYMBOL_HIDING = @CFLAG_CURL_SYMBOL_HIDING@ +CONFIGURE_OPTIONS = @CONFIGURE_OPTIONS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CPPFLAG_CURL_STATICLIB = @CPPFLAG_CURL_STATICLIB@ +CSCOPE = @CSCOPE@ +CTAGS = @CTAGS@ +CURLVERSION = @CURLVERSION@ +CURL_CA_BUNDLE = @CURL_CA_BUNDLE@ +CURL_CFLAG_EXTRAS = @CURL_CFLAG_EXTRAS@ +CURL_DISABLE_DICT = @CURL_DISABLE_DICT@ +CURL_DISABLE_FILE = @CURL_DISABLE_FILE@ +CURL_DISABLE_FTP = @CURL_DISABLE_FTP@ +CURL_DISABLE_GOPHER = @CURL_DISABLE_GOPHER@ +CURL_DISABLE_HTTP = @CURL_DISABLE_HTTP@ +CURL_DISABLE_IMAP = @CURL_DISABLE_IMAP@ +CURL_DISABLE_LDAP = @CURL_DISABLE_LDAP@ +CURL_DISABLE_LDAPS = @CURL_DISABLE_LDAPS@ +CURL_DISABLE_MQTT = @CURL_DISABLE_MQTT@ +CURL_DISABLE_POP3 = @CURL_DISABLE_POP3@ +CURL_DISABLE_PROXY = @CURL_DISABLE_PROXY@ +CURL_DISABLE_RTSP = @CURL_DISABLE_RTSP@ +CURL_DISABLE_SMB = @CURL_DISABLE_SMB@ +CURL_DISABLE_SMTP = @CURL_DISABLE_SMTP@ +CURL_DISABLE_TELNET = @CURL_DISABLE_TELNET@ +CURL_DISABLE_TFTP = @CURL_DISABLE_TFTP@ +CURL_LT_SHLIB_VERSIONED_FLAVOUR = @CURL_LT_SHLIB_VERSIONED_FLAVOUR@ +CURL_NETWORK_AND_TIME_LIBS = @CURL_NETWORK_AND_TIME_LIBS@ +CURL_NETWORK_LIBS = @CURL_NETWORK_LIBS@ +CURL_WITH_MULTI_SSL = @CURL_WITH_MULTI_SSL@ +CYGPATH_W = @CYGPATH_W@ +DEFAULT_SSL_BACKEND = @DEFAULT_SSL_BACKEND@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +ENABLE_SHARED = @ENABLE_SHARED@ +ENABLE_STATIC = @ENABLE_STATIC@ +ETAGS = @ETAGS@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +FILECMD = @FILECMD@ +FISH_FUNCTIONS_DIR = @FISH_FUNCTIONS_DIR@ +GCOV = @GCOV@ +GREP = @GREP@ +HAVE_BROTLI = @HAVE_BROTLI@ +HAVE_GNUTLS_SRP = @HAVE_GNUTLS_SRP@ +HAVE_LDAP_SSL = @HAVE_LDAP_SSL@ +HAVE_LIBZ = @HAVE_LIBZ@ +HAVE_OPENSSL_QUIC = @HAVE_OPENSSL_QUIC@ +HAVE_OPENSSL_SRP = @HAVE_OPENSSL_SRP@ +HAVE_PROTO_BSDSOCKET_H = @HAVE_PROTO_BSDSOCKET_H@ +HAVE_ZSTD = @HAVE_ZSTD@ +HTTPD = @HTTPD@ +HTTPD_NGHTTPX = @HTTPD_NGHTTPX@ +IDN_ENABLED = @IDN_ENABLED@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +IPV6_ENABLED = @IPV6_ENABLED@ +LCOV = @LCOV@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBCURL_LIBS = @LIBCURL_LIBS@ +LIBCURL_NO_SHARED = @LIBCURL_NO_SHARED@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ +MAINT = @MAINT@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PERL = @PERL@ +PKGADD_NAME = @PKGADD_NAME@ +PKGADD_PKG = @PKGADD_PKG@ +PKGADD_VENDOR = @PKGADD_VENDOR@ +PKGCONFIG = @PKGCONFIG@ +RANDOM_FILE = @RANDOM_FILE@ +RANLIB = @RANLIB@ +RC = @RC@ +REQUIRE_LIB_DEPS = @REQUIRE_LIB_DEPS@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SSL_BACKENDS = @SSL_BACKENDS@ +SSL_ENABLED = @SSL_ENABLED@ +SSL_LIBS = @SSL_LIBS@ +STRIP = @STRIP@ +SUPPORT_FEATURES = @SUPPORT_FEATURES@ +SUPPORT_PROTOCOLS = @SUPPORT_PROTOCOLS@ +TEST_NGHTTPX = @TEST_NGHTTPX@ +USE_ARES = @USE_ARES@ +USE_BEARSSL = @USE_BEARSSL@ +USE_GNUTLS = @USE_GNUTLS@ +USE_HYPER = @USE_HYPER@ +USE_LIBPSL = @USE_LIBPSL@ +USE_LIBRTMP = @USE_LIBRTMP@ +USE_LIBSSH = @USE_LIBSSH@ +USE_LIBSSH2 = @USE_LIBSSH2@ +USE_MBEDTLS = @USE_MBEDTLS@ +USE_MSH3 = @USE_MSH3@ +USE_NGHTTP2 = @USE_NGHTTP2@ +USE_NGHTTP3 = @USE_NGHTTP3@ +USE_NGTCP2 = @USE_NGTCP2@ +USE_NGTCP2_CRYPTO_BORINGSSL = @USE_NGTCP2_CRYPTO_BORINGSSL@ +USE_NGTCP2_CRYPTO_GNUTLS = @USE_NGTCP2_CRYPTO_GNUTLS@ +USE_NGTCP2_CRYPTO_QUICTLS = @USE_NGTCP2_CRYPTO_QUICTLS@ +USE_NGTCP2_CRYPTO_WOLFSSL = @USE_NGTCP2_CRYPTO_WOLFSSL@ +USE_NGTCP2_H3 = @USE_NGTCP2_H3@ +USE_OPENLDAP = @USE_OPENLDAP@ +USE_OPENSSL_H3 = @USE_OPENSSL_H3@ +USE_OPENSSL_QUIC = @USE_OPENSSL_QUIC@ +USE_QUICHE = @USE_QUICHE@ +USE_RUSTLS = @USE_RUSTLS@ +USE_SCHANNEL = @USE_SCHANNEL@ +USE_SECTRANSP = @USE_SECTRANSP@ +USE_UNIX_SOCKETS = @USE_UNIX_SOCKETS@ +USE_WIN32_CRYPTO = @USE_WIN32_CRYPTO@ +USE_WIN32_LARGE_FILES = @USE_WIN32_LARGE_FILES@ +USE_WIN32_SMALL_FILES = @USE_WIN32_SMALL_FILES@ +USE_WINDOWS_SSPI = @USE_WINDOWS_SSPI@ +USE_WOLFSSH = @USE_WOLFSSH@ +USE_WOLFSSL = @USE_WOLFSSL@ +VERSION = @VERSION@ +VERSIONNUM = @VERSIONNUM@ +VSFTPD = @VSFTPD@ +ZLIB_LIBS = @ZLIB_LIBS@ +ZSH_FUNCTIONS_DIR = @ZSH_FUNCTIONS_DIR@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +libext = @libext@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +runstatedir = @runstatedir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +AUTOMAKE_OPTIONS = foreign +ACLOCAL_AMFLAGS = -I m4 +CMAKE_DIST = \ + CMake/cmake_uninstall.cmake.in \ + CMake/CMakeConfigurableFile.in \ + CMake/curl-config.cmake.in \ + CMake/CurlSymbolHiding.cmake \ + CMake/CurlTests.c \ + CMake/FindBearSSL.cmake \ + CMake/FindBrotli.cmake \ + CMake/FindCARES.cmake \ + CMake/FindGSS.cmake \ + CMake/FindLibPSL.cmake \ + CMake/FindLibSSH2.cmake \ + CMake/FindMbedTLS.cmake \ + CMake/FindMSH3.cmake \ + CMake/FindNGHTTP2.cmake \ + CMake/FindNGHTTP3.cmake \ + CMake/FindNGTCP2.cmake \ + CMake/FindQUICHE.cmake \ + CMake/FindWolfSSL.cmake \ + CMake/FindZstd.cmake \ + CMake/Macros.cmake \ + CMake/OtherTests.cmake \ + CMake/PickyWarnings.cmake \ + CMake/Platforms/WindowsCache.cmake \ + CMake/Utilities.cmake \ + CMakeLists.txt + +VC_DIST = projects/README.md \ + projects/build-openssl.bat \ + projects/build-wolfssl.bat \ + projects/checksrc.bat \ + projects/generate.bat \ + projects/wolfssl_options.h \ + projects/wolfssl_override.props + +WINBUILD_DIST = winbuild/README.md winbuild/gen_resp_file.bat \ + winbuild/MakefileBuild.vc winbuild/Makefile.vc winbuild/makedebug.cmd + +PLAN9_DIST = plan9/include/mkfile \ + plan9/include/mkfile \ + plan9/mkfile.proto \ + plan9/mkfile \ + plan9/README \ + plan9/lib/mkfile.inc \ + plan9/lib/mkfile \ + plan9/src/mkfile.inc \ + plan9/src/mkfile + +EXTRA_DIST = CHANGES COPYING maketgz Makefile.dist curl-config.in \ + RELEASE-NOTES buildconf libcurl.pc.in $(CMAKE_DIST) $(VC_DIST) \ + $(WINBUILD_DIST) $(PLAN9_DIST) lib/libcurl.vers.in buildconf.bat \ + libcurl.def Dockerfile + +CLEANFILES = $(VC14_LIBVCXPROJ) $(VC14_SRCVCXPROJ) \ + $(VC14_10_LIBVCXPROJ) $(VC14_10_SRCVCXPROJ) \ + $(VC14_20_LIBVCXPROJ) $(VC14_20_SRCVCXPROJ) \ + $(VC14_30_LIBVCXPROJ) $(VC14_30_SRCVCXPROJ) + +bin_SCRIPTS = curl-config +SUBDIRS = lib docs src scripts +DIST_SUBDIRS = $(SUBDIRS) tests packages scripts include docs +pkgconfigdir = $(libdir)/pkgconfig +pkgconfig_DATA = libcurl.pc +LIB_VAUTH_CFILES = \ + vauth/cleartext.c \ + vauth/cram.c \ + vauth/digest.c \ + vauth/digest_sspi.c \ + vauth/gsasl.c \ + vauth/krb5_gssapi.c \ + vauth/krb5_sspi.c \ + vauth/ntlm.c \ + vauth/ntlm_sspi.c \ + vauth/oauth2.c \ + vauth/spnego_gssapi.c \ + vauth/spnego_sspi.c \ + vauth/vauth.c + +LIB_VAUTH_HFILES = \ + vauth/digest.h \ + vauth/ntlm.h \ + vauth/vauth.h + +LIB_VTLS_CFILES = \ + vtls/bearssl.c \ + vtls/cipher_suite.c \ + vtls/gtls.c \ + vtls/hostcheck.c \ + vtls/keylog.c \ + vtls/mbedtls.c \ + vtls/mbedtls_threadlock.c \ + vtls/openssl.c \ + vtls/rustls.c \ + vtls/schannel.c \ + vtls/schannel_verify.c \ + vtls/sectransp.c \ + vtls/vtls.c \ + vtls/wolfssl.c \ + vtls/x509asn1.c + +LIB_VTLS_HFILES = \ + vtls/bearssl.h \ + vtls/cipher_suite.h \ + vtls/gtls.h \ + vtls/hostcheck.h \ + vtls/keylog.h \ + vtls/mbedtls.h \ + vtls/mbedtls_threadlock.h \ + vtls/openssl.h \ + vtls/rustls.h \ + vtls/schannel.h \ + vtls/schannel_int.h \ + vtls/sectransp.h \ + vtls/vtls.h \ + vtls/vtls_int.h \ + vtls/wolfssl.h \ + vtls/x509asn1.h + +LIB_VQUIC_CFILES = \ + vquic/curl_msh3.c \ + vquic/curl_ngtcp2.c \ + vquic/curl_osslq.c \ + vquic/curl_quiche.c \ + vquic/vquic.c \ + vquic/vquic-tls.c + +LIB_VQUIC_HFILES = \ + vquic/curl_msh3.h \ + vquic/curl_ngtcp2.h \ + vquic/curl_osslq.h \ + vquic/curl_quiche.h \ + vquic/vquic.h \ + vquic/vquic_int.h \ + vquic/vquic-tls.h + +LIB_VSSH_CFILES = \ + vssh/libssh.c \ + vssh/libssh2.c \ + vssh/wolfssh.c + +LIB_VSSH_HFILES = \ + vssh/ssh.h + +LIB_CFILES = \ + altsvc.c \ + amigaos.c \ + asyn-ares.c \ + asyn-thread.c \ + base64.c \ + bufq.c \ + bufref.c \ + c-hyper.c \ + cf-h1-proxy.c \ + cf-h2-proxy.c \ + cf-haproxy.c \ + cf-https-connect.c \ + cf-socket.c \ + cfilters.c \ + conncache.c \ + connect.c \ + content_encoding.c \ + cookie.c \ + curl_addrinfo.c \ + curl_des.c \ + curl_endian.c \ + curl_fnmatch.c \ + curl_get_line.c \ + curl_gethostname.c \ + curl_gssapi.c \ + curl_memrchr.c \ + curl_multibyte.c \ + curl_ntlm_core.c \ + curl_path.c \ + curl_range.c \ + curl_rtmp.c \ + curl_sasl.c \ + curl_sha512_256.c \ + curl_sspi.c \ + curl_threads.c \ + curl_trc.c \ + cw-out.c \ + dict.c \ + dllmain.c \ + doh.c \ + dynbuf.c \ + dynhds.c \ + easy.c \ + easygetopt.c \ + easyoptions.c \ + escape.c \ + file.c \ + fileinfo.c \ + fopen.c \ + formdata.c \ + ftp.c \ + ftplistparser.c \ + getenv.c \ + getinfo.c \ + gopher.c \ + hash.c \ + headers.c \ + hmac.c \ + hostasyn.c \ + hostip.c \ + hostip4.c \ + hostip6.c \ + hostsyn.c \ + hsts.c \ + http.c \ + http1.c \ + http2.c \ + http_aws_sigv4.c \ + http_chunks.c \ + http_digest.c \ + http_negotiate.c \ + http_ntlm.c \ + http_proxy.c \ + idn.c \ + if2ip.c \ + imap.c \ + inet_ntop.c \ + inet_pton.c \ + krb5.c \ + ldap.c \ + llist.c \ + macos.c \ + md4.c \ + md5.c \ + memdebug.c \ + mime.c \ + mprintf.c \ + mqtt.c \ + multi.c \ + netrc.c \ + nonblock.c \ + noproxy.c \ + openldap.c \ + parsedate.c \ + pingpong.c \ + pop3.c \ + progress.c \ + psl.c \ + rand.c \ + rename.c \ + request.c \ + rtsp.c \ + select.c \ + sendf.c \ + setopt.c \ + sha256.c \ + share.c \ + slist.c \ + smb.c \ + smtp.c \ + socketpair.c \ + socks.c \ + socks_gssapi.c \ + socks_sspi.c \ + speedcheck.c \ + splay.c \ + strcase.c \ + strdup.c \ + strerror.c \ + strtok.c \ + strtoofft.c \ + system_win32.c \ + telnet.c \ + tftp.c \ + timediff.c \ + timeval.c \ + transfer.c \ + url.c \ + urlapi.c \ + version.c \ + version_win32.c \ + warnless.c \ + ws.c + +LIB_HFILES = \ + altsvc.h \ + amigaos.h \ + arpa_telnet.h \ + asyn.h \ + bufq.h \ + bufref.h \ + c-hyper.h \ + cf-h1-proxy.h \ + cf-h2-proxy.h \ + cf-haproxy.h \ + cf-https-connect.h \ + cf-socket.h \ + cfilters.h \ + conncache.h \ + connect.h \ + content_encoding.h \ + cookie.h \ + curl_addrinfo.h \ + curl_base64.h \ + curl_ctype.h \ + curl_des.h \ + curl_endian.h \ + curl_fnmatch.h \ + curl_get_line.h \ + curl_gethostname.h \ + curl_gssapi.h \ + curl_hmac.h \ + curl_krb5.h \ + curl_ldap.h \ + curl_md4.h \ + curl_md5.h \ + curl_memory.h \ + curl_memrchr.h \ + curl_multibyte.h \ + curl_ntlm_core.h \ + curl_path.h \ + curl_printf.h \ + curl_range.h \ + curl_rtmp.h \ + curl_sasl.h \ + curl_setup.h \ + curl_setup_once.h \ + curl_sha256.h \ + curl_sha512_256.h \ + curl_sspi.h \ + curl_threads.h \ + curl_trc.h \ + curlx.h \ + cw-out.h \ + dict.h \ + doh.h \ + dynbuf.h \ + dynhds.h \ + easy_lock.h \ + easyif.h \ + easyoptions.h \ + escape.h \ + file.h \ + fileinfo.h \ + fopen.h \ + formdata.h \ + ftp.h \ + ftplistparser.h \ + functypes.h \ + getinfo.h \ + gopher.h \ + hash.h \ + headers.h \ + hostip.h \ + hsts.h \ + http.h \ + http1.h \ + http2.h \ + http_aws_sigv4.h \ + http_chunks.h \ + http_digest.h \ + http_negotiate.h \ + http_ntlm.h \ + http_proxy.h \ + idn.h \ + if2ip.h \ + imap.h \ + inet_ntop.h \ + inet_pton.h \ + llist.h \ + macos.h \ + memdebug.h \ + mime.h \ + mqtt.h \ + multihandle.h \ + multiif.h \ + netrc.h \ + nonblock.h \ + noproxy.h \ + parsedate.h \ + pingpong.h \ + pop3.h \ + progress.h \ + psl.h \ + rand.h \ + rename.h \ + request.h \ + rtsp.h \ + select.h \ + sendf.h \ + setopt.h \ + setup-vms.h \ + share.h \ + sigpipe.h \ + slist.h \ + smb.h \ + smtp.h \ + sockaddr.h \ + socketpair.h \ + socks.h \ + speedcheck.h \ + splay.h \ + strcase.h \ + strdup.h \ + strerror.h \ + strtok.h \ + strtoofft.h \ + system_win32.h \ + telnet.h \ + tftp.h \ + timediff.h \ + timeval.h \ + transfer.h \ + url.h \ + urlapi-int.h \ + urldata.h \ + version_win32.h \ + warnless.h \ + ws.h + +LIB_RCFILES = libcurl.rc +CSOURCES = $(LIB_CFILES) $(LIB_VAUTH_CFILES) $(LIB_VTLS_CFILES) \ + $(LIB_VQUIC_CFILES) $(LIB_VSSH_CFILES) + +HHEADERS = $(LIB_HFILES) $(LIB_VAUTH_HFILES) $(LIB_VTLS_HFILES) \ + $(LIB_VQUIC_HFILES) $(LIB_VSSH_HFILES) + + +# libcurl sources to include in curltool lib we use for test binaries +CURLTOOL_LIBCURL_CFILES = \ + ../lib/base64.c \ + ../lib/dynbuf.c + + +# libcurl has sources that provide functions named curlx_* that aren't part of +# the official API, but we reuse the code here to avoid duplication. +CURLX_CFILES = \ + ../lib/base64.c \ + ../lib/curl_multibyte.c \ + ../lib/dynbuf.c \ + ../lib/nonblock.c \ + ../lib/strtoofft.c \ + ../lib/timediff.c \ + ../lib/version_win32.c \ + ../lib/warnless.c + +CURLX_HFILES = \ + ../lib/curl_ctype.h \ + ../lib/curl_multibyte.h \ + ../lib/curl_setup.h \ + ../lib/dynbuf.h \ + ../lib/nonblock.h \ + ../lib/strtoofft.h \ + ../lib/timediff.h \ + ../lib/version_win32.h \ + ../lib/warnless.h + +CURL_CFILES = \ + slist_wc.c \ + tool_binmode.c \ + tool_bname.c \ + tool_cb_dbg.c \ + tool_cb_hdr.c \ + tool_cb_prg.c \ + tool_cb_rea.c \ + tool_cb_see.c \ + tool_cb_wrt.c \ + tool_cfgable.c \ + tool_dirhie.c \ + tool_doswin.c \ + tool_easysrc.c \ + tool_filetime.c \ + tool_findfile.c \ + tool_formparse.c \ + tool_getparam.c \ + tool_getpass.c \ + tool_help.c \ + tool_helpers.c \ + tool_hugehelp.c \ + tool_ipfs.c \ + tool_libinfo.c \ + tool_listhelp.c \ + tool_main.c \ + tool_msgs.c \ + tool_operate.c \ + tool_operhlp.c \ + tool_paramhlp.c \ + tool_parsecfg.c \ + tool_progress.c \ + tool_setopt.c \ + tool_sleep.c \ + tool_stderr.c \ + tool_strdup.c \ + tool_urlglob.c \ + tool_util.c \ + tool_vms.c \ + tool_writeout.c \ + tool_writeout_json.c \ + tool_xattr.c \ + var.c + +CURL_HFILES = \ + slist_wc.h \ + tool_binmode.h \ + tool_bname.h \ + tool_cb_dbg.h \ + tool_cb_hdr.h \ + tool_cb_prg.h \ + tool_cb_rea.h \ + tool_cb_see.h \ + tool_cb_wrt.h \ + tool_cfgable.h \ + tool_dirhie.h \ + tool_doswin.h \ + tool_easysrc.h \ + tool_filetime.h \ + tool_findfile.h \ + tool_formparse.h \ + tool_getparam.h \ + tool_getpass.h \ + tool_help.h \ + tool_helpers.h \ + tool_hugehelp.h \ + tool_ipfs.h \ + tool_libinfo.h \ + tool_main.h \ + tool_msgs.h \ + tool_operate.h \ + tool_operhlp.h \ + tool_paramhlp.h \ + tool_parsecfg.h \ + tool_progress.h \ + tool_sdecls.h \ + tool_setopt.h \ + tool_setup.h \ + tool_sleep.h \ + tool_stderr.h \ + tool_strdup.h \ + tool_urlglob.h \ + tool_util.h \ + tool_version.h \ + tool_vms.h \ + tool_writeout.h \ + tool_writeout_json.h \ + tool_xattr.h \ + var.h + +CURL_RCFILES = curl.rc + +# curl_SOURCES is special and gets assigned in src/Makefile.am +CURL_FILES = $(CURL_CFILES) $(CURLX_CFILES) $(CURL_HFILES) +all: all-recursive + +.SUFFIXES: +am--refresh: Makefile + @: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(srcdir)/lib/Makefile.inc $(srcdir)/src/Makefile.inc $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + echo ' cd $(srcdir) && $(AUTOMAKE) --foreign'; \ + $(am__cd) $(srcdir) && $(AUTOMAKE) --foreign \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + echo ' $(SHELL) ./config.status'; \ + $(SHELL) ./config.status;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__maybe_remake_depfiles)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__maybe_remake_depfiles);; \ + esac; +$(srcdir)/lib/Makefile.inc $(srcdir)/src/Makefile.inc $(am__empty): + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + $(SHELL) ./config.status --recheck + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + $(am__cd) $(srcdir) && $(AUTOCONF) +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + $(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) +$(am__aclocal_m4_deps): +curl-config: $(top_builddir)/config.status $(srcdir)/curl-config.in + cd $(top_builddir) && $(SHELL) ./config.status $@ +libcurl.pc: $(top_builddir)/config.status $(srcdir)/libcurl.pc.in + cd $(top_builddir) && $(SHELL) ./config.status $@ +install-binSCRIPTS: $(bin_SCRIPTS) + @$(NORMAL_INSTALL) + @list='$(bin_SCRIPTS)'; test -n "$(bindir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + if test -f "$$d$$p"; then echo "$$d$$p"; echo "$$p"; else :; fi; \ + done | \ + sed -e 'p;s,.*/,,;n' \ + -e 'h;s|.*|.|' \ + -e 'p;x;s,.*/,,;$(transform)' | sed 'N;N;N;s,\n, ,g' | \ + $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1; } \ + { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ + if ($$2 == $$4) { files[d] = files[d] " " $$1; \ + if (++n[d] == $(am__install_max)) { \ + print "f", d, files[d]; n[d] = 0; files[d] = "" } } \ + else { print "f", d "/" $$4, $$1 } } \ + END { for (d in files) print "f", d, files[d] }' | \ + while read type dir files; do \ + if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ + test -z "$$files" || { \ + echo " $(INSTALL_SCRIPT) $$files '$(DESTDIR)$(bindir)$$dir'"; \ + $(INSTALL_SCRIPT) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ + } \ + ; done + +uninstall-binSCRIPTS: + @$(NORMAL_UNINSTALL) + @list='$(bin_SCRIPTS)'; test -n "$(bindir)" || exit 0; \ + files=`for p in $$list; do echo "$$p"; done | \ + sed -e 's,.*/,,;$(transform)'`; \ + dir='$(DESTDIR)$(bindir)'; $(am__uninstall_files_from_dir) + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool config.lt +install-pkgconfigDATA: $(pkgconfig_DATA) + @$(NORMAL_INSTALL) + @list='$(pkgconfig_DATA)'; test -n "$(pkgconfigdir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(pkgconfigdir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(pkgconfigdir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(pkgconfigdir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(pkgconfigdir)" || exit $$?; \ + done + +uninstall-pkgconfigDATA: + @$(NORMAL_UNINSTALL) + @list='$(pkgconfig_DATA)'; test -n "$(pkgconfigdir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(pkgconfigdir)'; $(am__uninstall_files_from_dir) + +# This directory's subdirectories are mostly independent; you can cd +# into them and run 'make' without going through this Makefile. +# To change the values of 'make' variables: instead of editing Makefiles, +# (1) if the variable is set in 'config.status', edit 'config.status' +# (which will cause the Makefiles to be regenerated when you run 'make'); +# (2) otherwise, pass the desired values on the 'make' command line. +$(am__recursive_targets): + @fail=; \ + if $(am__make_keepgoing); then \ + failcom='fail=yes'; \ + else \ + failcom='exit 1'; \ + fi; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-recursive +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: ctags-recursive + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscope: cscope.files + test ! -s cscope.files \ + || $(CSCOPE) -b -q $(AM_CSCOPEFLAGS) $(CSCOPEFLAGS) -i cscope.files $(CSCOPE_ARGS) +clean-cscope: + -rm -f cscope.files +cscope.files: clean-cscope cscopelist +cscopelist: cscopelist-recursive + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + -rm -f cscope.out cscope.in.out cscope.po.out cscope.files +distdir: $(BUILT_SOURCES) + $(MAKE) $(AM_MAKEFLAGS) distdir-am + +distdir-am: $(DISTFILES) + $(am__remove_distdir) + test -d "$(distdir)" || mkdir "$(distdir)" + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + $(am__make_dryrun) \ + || test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ + distdir) \ + || exit 1; \ + fi; \ + done + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$(top_distdir)" distdir="$(distdir)" \ + dist-hook + -test -n "$(am__skip_mode_fix)" \ + || find "$(distdir)" -type d ! -perm -755 \ + -exec chmod u+rwx,go+rx {} \; -o \ + ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ + ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ + ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \ + || chmod -R a+r "$(distdir)" +dist-gzip: distdir + tardir=$(distdir) && $(am__tar) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).tar.gz + $(am__post_remove_distdir) + +dist-bzip2: distdir + tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 + $(am__post_remove_distdir) + +dist-lzip: distdir + tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz + $(am__post_remove_distdir) + +dist-xz: distdir + tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz + $(am__post_remove_distdir) + +dist-zstd: distdir + tardir=$(distdir) && $(am__tar) | zstd -c $${ZSTD_CLEVEL-$${ZSTD_OPT--19}} >$(distdir).tar.zst + $(am__post_remove_distdir) + +dist-tarZ: distdir + @echo WARNING: "Support for distribution archives compressed with" \ + "legacy program 'compress' is deprecated." >&2 + @echo WARNING: "It will be removed altogether in Automake 2.0" >&2 + tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z + $(am__post_remove_distdir) + +dist-shar: distdir + @echo WARNING: "Support for shar distribution archives is" \ + "deprecated." >&2 + @echo WARNING: "It will be removed altogether in Automake 2.0" >&2 + shar $(distdir) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).shar.gz + $(am__post_remove_distdir) + +dist-zip: distdir + -rm -f $(distdir).zip + zip -rq $(distdir).zip $(distdir) + $(am__post_remove_distdir) + +dist dist-all: + $(MAKE) $(AM_MAKEFLAGS) $(DIST_TARGETS) am__post_remove_distdir='@:' + $(am__post_remove_distdir) + +# This target untars the dist file and tries a VPATH configuration. Then +# it guarantees that the distribution is self-contained by making another +# tarfile. +distcheck: dist + case '$(DIST_ARCHIVES)' in \ + *.tar.gz*) \ + eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).tar.gz | $(am__untar) ;;\ + *.tar.bz2*) \ + bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\ + *.tar.lz*) \ + lzip -dc $(distdir).tar.lz | $(am__untar) ;;\ + *.tar.xz*) \ + xz -dc $(distdir).tar.xz | $(am__untar) ;;\ + *.tar.Z*) \ + uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ + *.shar.gz*) \ + eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).shar.gz | unshar ;;\ + *.zip*) \ + unzip $(distdir).zip ;;\ + *.tar.zst*) \ + zstd -dc $(distdir).tar.zst | $(am__untar) ;;\ + esac + chmod -R a-w $(distdir) + chmod u+w $(distdir) + mkdir $(distdir)/_build $(distdir)/_build/sub $(distdir)/_inst + chmod a-w $(distdir) + test -d $(distdir)/_build || exit 0; \ + dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ + && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ + && am__cwd=`pwd` \ + && $(am__cd) $(distdir)/_build/sub \ + && ../../configure \ + $(AM_DISTCHECK_CONFIGURE_FLAGS) \ + $(DISTCHECK_CONFIGURE_FLAGS) \ + --srcdir=../.. --prefix="$$dc_install_base" \ + && $(MAKE) $(AM_MAKEFLAGS) \ + && $(MAKE) $(AM_MAKEFLAGS) $(AM_DISTCHECK_DVI_TARGET) \ + && $(MAKE) $(AM_MAKEFLAGS) check \ + && $(MAKE) $(AM_MAKEFLAGS) install \ + && $(MAKE) $(AM_MAKEFLAGS) installcheck \ + && $(MAKE) $(AM_MAKEFLAGS) uninstall \ + && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ + distuninstallcheck \ + && chmod -R a-w "$$dc_install_base" \ + && ({ \ + (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ + distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ + } || { rm -rf "$$dc_destdir"; exit 1; }) \ + && rm -rf "$$dc_destdir" \ + && $(MAKE) $(AM_MAKEFLAGS) dist \ + && rm -rf $(DIST_ARCHIVES) \ + && $(MAKE) $(AM_MAKEFLAGS) distcleancheck \ + && cd "$$am__cwd" \ + || exit 1 + $(am__post_remove_distdir) + @(echo "$(distdir) archives ready for distribution: "; \ + list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ + sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x' +distuninstallcheck: + @test -n '$(distuninstallcheck_dir)' || { \ + echo 'ERROR: trying to run $@ with an empty' \ + '$$(distuninstallcheck_dir)' >&2; \ + exit 1; \ + }; \ + $(am__cd) '$(distuninstallcheck_dir)' || { \ + echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \ + exit 1; \ + }; \ + test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \ + || { echo "ERROR: files left after uninstall:" ; \ + if test -n "$(DESTDIR)"; then \ + echo " (check DESTDIR support)"; \ + fi ; \ + $(distuninstallcheck_listfiles) ; \ + exit 1; } >&2 +distcleancheck: distclean + @if test '$(srcdir)' = . ; then \ + echo "ERROR: distcleancheck can only run from a VPATH build" ; \ + exit 1 ; \ + fi + @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ + || { echo "ERROR: files left in build directory after distclean:" ; \ + $(distcleancheck_listfiles) ; \ + exit 1; } >&2 +check-am: all-am +check: check-recursive +all-am: Makefile $(SCRIPTS) $(DATA) +installdirs: installdirs-recursive +installdirs-am: + for dir in "$(DESTDIR)$(bindir)" "$(DESTDIR)$(pkgconfigdir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f $(am__CONFIG_DISTCLEAN_FILES) + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool \ + distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: install-pkgconfigDATA + @$(NORMAL_INSTALL) + $(MAKE) $(AM_MAKEFLAGS) install-data-hook +install-dvi: install-dvi-recursive + +install-dvi-am: + +install-exec-am: install-binSCRIPTS + +install-html: install-html-recursive + +install-html-am: + +install-info: install-info-recursive + +install-info-am: + +install-man: + +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f $(am__CONFIG_DISTCLEAN_FILES) + -rm -rf $(top_srcdir)/autom4te.cache + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-binSCRIPTS uninstall-pkgconfigDATA + @$(NORMAL_INSTALL) + $(MAKE) $(AM_MAKEFLAGS) uninstall-hook +.MAKE: $(am__recursive_targets) install-am install-data-am \ + install-strip uninstall-am + +.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ + am--refresh check check-am clean clean-cscope clean-generic \ + clean-libtool cscope cscopelist-am ctags ctags-am dist \ + dist-all dist-bzip2 dist-gzip dist-hook dist-lzip dist-shar \ + dist-tarZ dist-xz dist-zip dist-zstd distcheck distclean \ + distclean-generic distclean-libtool distclean-tags \ + distcleancheck distdir distuninstallcheck dvi dvi-am html \ + html-am info info-am install install-am install-binSCRIPTS \ + install-data install-data-am install-data-hook install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-pkgconfigDATA install-ps \ + install-ps-am install-strip installcheck installcheck-am \ + installdirs installdirs-am maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ + uninstall-am uninstall-binSCRIPTS uninstall-hook \ + uninstall-pkgconfigDATA + +.PRECIOUS: Makefile + + +# List of files required to generate VC IDE .dsp, .vcproj and .vcxproj files + +dist-hook: + rm -rf $(top_builddir)/tests/log + find $(distdir) -name "*.dist" -exec rm {} \; + (distit=`find $(srcdir) -name "*.dist" | grep -v ./ares/`; \ + for file in $$distit; do \ + strip=`echo $$file | sed -e s/^$(srcdir)// -e s/\.dist//`; \ + cp -p $$file $(distdir)$$strip; \ + done) + +check: test examples check-docs + +@CROSSCOMPILING_TRUE@test-full: test +@CROSSCOMPILING_TRUE@test-torture: test + +@CROSSCOMPILING_TRUE@test: +@CROSSCOMPILING_TRUE@ @echo "NOTICE: we can't run the tests when cross-compiling!" + +@CROSSCOMPILING_FALSE@test: +@CROSSCOMPILING_FALSE@ @(cd tests; $(MAKE) all quiet-test) + +@CROSSCOMPILING_FALSE@test-full: +@CROSSCOMPILING_FALSE@ @(cd tests; $(MAKE) all full-test) + +@CROSSCOMPILING_FALSE@test-nonflaky: +@CROSSCOMPILING_FALSE@ @(cd tests; $(MAKE) all nonflaky-test) + +@CROSSCOMPILING_FALSE@test-torture: +@CROSSCOMPILING_FALSE@ @(cd tests; $(MAKE) all torture-test) + +@CROSSCOMPILING_FALSE@test-event: +@CROSSCOMPILING_FALSE@ @(cd tests; $(MAKE) all event-test) + +@CROSSCOMPILING_FALSE@test-am: +@CROSSCOMPILING_FALSE@ @(cd tests; $(MAKE) all am-test) + +@CROSSCOMPILING_FALSE@test-ci: +@CROSSCOMPILING_FALSE@ @(cd tests; $(MAKE) all ci-test) + +examples: + @(cd docs/examples; $(MAKE) check) + +check-docs: + @(cd docs/libcurl; $(MAKE) check) + +# Build source and binary rpms. For rpm-3.0 and above, the ~/.rpmmacros +# must contain the following line: +# %_topdir /home/loic/local/rpm +# and that /home/loic/local/rpm contains the directory SOURCES, BUILD etc. +# +# cd /home/loic/local/rpm ; mkdir -p SOURCES BUILD RPMS/i386 SPECS SRPMS +# +# If additional configure flags are needed to build the package, add the +# following in ~/.rpmmacros +# %configure CFLAGS="%{optflags}" ./configure %{_target_platform} --prefix=%{_prefix} ${AM_CONFIGFLAGS} +# and run make rpm in the following way: +# AM_CONFIGFLAGS='--with-uri=/home/users/loic/local/RedHat-6.2' make rpm +# + +rpms: + $(MAKE) RPMDIST=curl rpm + $(MAKE) RPMDIST=curl-ssl rpm + +rpm: + RPM_TOPDIR=`rpm --showrc | $(PERL) -n -e 'print if(s/.*_topdir\s+(.*)/$$1/)'` ; \ + cp $(srcdir)/packages/Linux/RPM/$(RPMDIST).spec $$RPM_TOPDIR/SPECS ; \ + cp $(PACKAGE)-$(VERSION).tar.gz $$RPM_TOPDIR/SOURCES ; \ + rpm -ba --clean --rmsource $$RPM_TOPDIR/SPECS/$(RPMDIST).spec ; \ + mv $$RPM_TOPDIR/RPMS/i386/$(RPMDIST)-*.rpm . ; \ + mv $$RPM_TOPDIR/SRPMS/$(RPMDIST)-*.src.rpm . + +# +# Build a Solaris pkgadd format file +# run 'make pkgadd' once you've done './configure' and 'make' to make a Solaris pkgadd format +# file (which ends up back in this directory). +# The pkgadd file is in 'pkgtrans' format, so to install on Solaris, do +# pkgadd -d ./HAXXcurl-* +# + +# gak - libtool requires an absolute directory, hence the pwd below... +pkgadd: + umask 022 ; \ + $(MAKE) install DESTDIR=`/bin/pwd`/packages/Solaris/root ; \ + cat COPYING > $(srcdir)/packages/Solaris/copyright ; \ + cd $(srcdir)/packages/Solaris && $(MAKE) package + +# +# Build a cygwin binary tarball installation file +# resulting .tar.bz2 file will end up at packages/Win32/cygwin +cygwinbin: + $(MAKE) -C packages/Win32/cygwin cygwinbin + +# We extend the standard install with a custom hook: +@BUILD_DOCS_TRUE@install-data-hook: +@BUILD_DOCS_TRUE@ (cd include && $(MAKE) install) +@BUILD_DOCS_TRUE@ (cd docs && $(MAKE) install) +@BUILD_DOCS_TRUE@ (cd docs/libcurl && $(MAKE) install) +@BUILD_DOCS_FALSE@install-data-hook: +@BUILD_DOCS_FALSE@ (cd include && $(MAKE) install) +@BUILD_DOCS_FALSE@ (cd docs && $(MAKE) install) + +# We extend the standard uninstall with a custom hook: +uninstall-hook: + (cd include && $(MAKE) uninstall) + (cd docs && $(MAKE) uninstall) + (cd docs/libcurl && $(MAKE) uninstall) + +ca-bundle: $(srcdir)/scripts/mk-ca-bundle.pl + @echo "generating a fresh ca-bundle.crt" + @perl $(srcdir)/scripts/mk-ca-bundle.pl -b -l -u lib/ca-bundle.crt + +ca-firefox: $(srcdir)/scripts/firefox-db2pem.sh + @echo "generating a fresh ca-bundle.crt" + $(srcdir)/scripts/firefox-db2pem.sh lib/ca-bundle.crt + +checksrc: + (cd lib && $(MAKE) checksrc) + (cd src && $(MAKE) checksrc) + (cd tests && $(MAKE) checksrc) + (cd include/curl && $(MAKE) checksrc) + (cd docs/examples && $(MAKE) checksrc) + (cd packages && $(MAKE) checksrc) + +tidy: + (cd src && $(MAKE) tidy) + (cd lib && $(MAKE) tidy) + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/third_party/curl/README b/third_party/curl/README new file mode 100644 index 0000000..f5efbd7 --- /dev/null +++ b/third_party/curl/README @@ -0,0 +1,55 @@ + _ _ ____ _ + ___| | | | _ \| | + / __| | | | |_) | | + | (__| |_| | _ <| |___ + \___|\___/|_| \_\_____| + +README + + Curl is a command line tool for transferring data specified with URL + syntax. Find out how to use curl by reading the curl.1 man page or the + MANUAL document. Find out how to install Curl by reading the INSTALL + document. + + libcurl is the library curl is using to do its job. It is readily + available to be used by your software. Read the libcurl.3 man page to + learn how. + + You find answers to the most frequent questions we get in the FAQ document. + + Study the COPYING file for distribution terms. + + Those documents and more can be found in the docs/ directory. + +CONTACT + + If you have problems, questions, ideas or suggestions, please contact us + by posting to a suitable mailing list. See https://curl.se/mail/ + + All contributors to the project are listed in the THANKS document. + +WEBSITE + + Visit the curl website for the latest news and downloads: + + https://curl.se/ + +GIT + + To download the latest source code off the GIT server, do this: + + git clone https://github.com/curl/curl.git + + (you will get a directory named curl created, filled with the source code) + +SECURITY PROBLEMS + + Report suspected security problems via our HackerOne page and not in public. + + https://hackerone.com/curl + +NOTICE + + Curl contains pieces of source code that is Copyright (c) 1998, 1999 + Kungliga Tekniska Högskolan. This notice is included here to comply with the + distribution terms. diff --git a/third_party/curl/RELEASE-NOTES b/third_party/curl/RELEASE-NOTES new file mode 100644 index 0000000..a48c8ef --- /dev/null +++ b/third_party/curl/RELEASE-NOTES @@ -0,0 +1,505 @@ +curl and libcurl 8.8.0 + + Public curl releases: 257 + Command line options: 259 + curl_easy_setopt() options: 305 + Public functions in libcurl: 94 + Contributors: 3173 + +This release includes the following changes: + + o curl_version_info: provide librtmp version [73] + o file: add support for directory listings [63] + o idn: add native AppleIDN (icucore) support for macOS/iOS [95] + o lib: add curl_multi_waitfds [34] + o mbedTLS: implement CURLOPT_SSL_CIPHER_LIST option [103] + o NTLM_WB: drop support [67] + o TLS: add support for ECH (Encrypted Client Hello) [109] + o urlapi: add CURLU_GET_EMPTY for empty queries and fragments [111] + +This release includes the following bugfixes: + + o appveyor: drop unnecessary `--clean-first` cmake option [197] + o appveyor: guard against crash-build with VS2008 [193] + o appveyor: make gcc 6 mingw64 job build-only [152] + o asyn-thread: fix curl_global_cleanup crash in Windows [161] + o asyn-thread: fix Curl_thread_create result check [162] + o autotools: delete unused functions [177] + o autotools: fix `HAVE_IOCTLSOCKET_FIONBIO` test for gcc 14 [186] + o autotools: only probe for SGI MIPS compilers on IRIX [213] + o bearssl: fix compiler warnings [43] + o bearssl: use common code for cipher suite lookup [126] + o bufq: remove duplicate word in comment [154] + o BUG-BOUNTY.md: clarify the third party situation [210] + o build: prefer `USE_IPV6` macro internally (was: `ENABLE_IPV6`) [85] + o build: remove MacOSX-Framework script [60] + o cd2nroff/manage: use UTC when SOURCE_DATE_EPOCH is set [36] + o cf-https-connect: use timeouts as unsigned ints [143] + o cf-socket: don't try getting local IP without socket [188] + o cf-socket: remove references to l_ip, l_port [9] + o ci: add curl-for-win builds: Linux MUSL, macOS, Windows [68] + o cmake: add `BUILD_EXAMPLES` option to build examples [128] + o cmake: add librtmp/rtmpdump option and detection [108] + o cmake: check fseeko after detecting HAVE_FILE_OFFSET_BITS [64] + o cmake: do not pass linker flags to the static library tool [203] + o cmake: enable `-pedantic-errors` for clang when `CURL_WERROR=ON` [47] + o cmake: FindNGHTTP2 add static lib name to find_library call [141] + o cmake: fix `CURL_WERROR=ON` for old CMake and use it in GHA/linux-old [48] + o cmake: fix `HAVE_IOCTLSOCKET_FIONBIO` test with gcc 14 [179] + o cmake: fixup `DEPENDS` filename [51] + o cmake: forward `USE_LIBRTMP` option to C [59] + o cmake: generate misc manpages and install `mk-ca-bundle.pl` [24] + o cmake: initialize `BUILD_TESTING` before first use [227] + o cmake: speed up libcurl doc building again [15] + o cmake: tidy-up to use `WORKING_DIRECTORY` [23] + o cmake: use namespaced custom target names [80] + o cmdline-docs: fix make install with configure --disable-docs [1] + o configure: error on missing perl if docs or manual is enabled [135] + o configure: make --disable-docs imply --disable-manual [2] + o content_encoding: brotli and others, pass through 0-length writes [5] + o content_encoding: ignore duplicate chunked encoding [137] + o content_encoding: reject transfer-encoding after chunked [200] + o contrithanks: honor `CURLWWW` variable [69] + o curl-confopts.m4: define CARES_NO_DEPRECATED when c-ares is used [17] + o curl.h: change CURL_SSLVERSION_* from enum to defines [132] + o curl: make --help adapt to the terminal width [11] + o curl: use curl_getenv instead of the curlx_ version [20] + o Curl_creader_read: init two variables to avoid using them uninited [99] + o curl_easy_pause.md: use correct defines in example [187] + o curl_getdate.md: document two-digit year handling [127] + o curl_global_trace.md: shorten the description [29] + o curl_multibyte: remove access() function wrapper for Windows [163] + o curl_path: make Curl_get_pathname use dynbuf [158] + o curl_setup.h: add support for IAR compiler [191] + o curl_setup.h: detect 'inline' support [133] + o curl_sha512_256: do not use workaround for NetBSD when not needed [21] + o curl_sha512_256: fix detection of OpenSSL 1.1.1 or later [8] + o curl_url_get.md: clarify queries and fragments and CURLU_GET_EMPTY [105] + o CURLINFO_REQUEST_SIZE: fixed, add tests for transfer infos reported [52] + o CURLOPT_WRITEFUNCTION.md: fix the callback proto in the example [215] + o cw-out: improved error handling [104] + o DEPRECATE.md: TLS libraries without 1.3 support [199] + o digest: replace strcpy for empty string with simple assignment [185] + o dist: `set -eu`, fix shellcheck, make reproducible and smaller tarballs [38] + o dist: add files missing from release tarball [53] + o dist: add reproducible dir entries to tarballs [56] + o dist: do not require Perl in `maketgz` [71] + o dist: remove the curl-config.1 from the tarball [28] + o dist: verify tarball reproducibility in CI [40] + o DISTROS: add patch and issues link for curl-for-win [110] + o DISTROS: Cygwin updates [44] + o dllmain: Call OpenSSL thread cleanup for Windows and Cygwin [114] + o doc: pytest `--repeat` -> `--count` [58] + o docs/cmdline-opts: invoke managen using a relative path [30] + o docs/cmdline-opts: mention STARTTLS for --ssl and --ssl-reqd [175] + o docs: add CURLOPT_NOPROGRESS to CURLOPT_XFERINFOFUNCTION example [61] + o docs: clarify CURLOPT_MAXFILESIZE and CURLOPT_MAXFILESIZE_LARGE [74] + o docs: fix some CURLINFO examples [147] + o doh: fix typo in comment [173] + o doh: remove unused function prototype [169] + o dynbuf: fix returncode on memory error [174] + o examples: fix/silence `-Wsign-conversion` [178] + o EXPERIMENTAL: add graduation requirements for each feature [166] + o file: remove useless assignment [89] + o ftp: add tracing support [181] + o ftp: fix build for CURL_DISABLE_VERBOSE_STRINGS + o ftp: fix socket leak on rare error [102] + o GHA: add NetBSD, OpenBSD, FreeBSD/arm64 and OmniOS jobs [201] + o GHA: add shellcheck job and fix warnings, shell tidy-ups [70] + o GHA: add valgrind to a wolfSSL build [37] + o GHA: on macOS remove $HOME/.curlrc [50] + o GHA: pin dependencies [194] + o gnutls: lazy init the trust settings [75] + o h3/ngtcp2: improve error handling [140] + o hash: change 'slots' to size_t from int [144] + o hash: delete unused debug function [198] + o hsts: explicitly skip blank lines [212] + o hsts: remove single-use single-line function [151] + o http tests: in CI skip test_02_23* for quiche [211] + o http2 + ngtcp2: pass CURLcode errors from callbacks [94] + o http2, http3: decouple stream state from easy handle [92] + o http2: emit RST when client write fails [65] + o http3: quiche+ngtcp2 improvements [129] + o http: acknowledge a returned error code [123] + o http: HEAD response body tolerance [170] + o http: reject HTTP major version switch mid connection [100] + o http: remove redundant check [182] + o http: with chunked POST forced, disable length check on read callback [31] + o http_aws_sigv4: remove useless assignment [88] + o idn: make Curl_idnconvert_hostname() use Curl_idn_decode() [16] + o if2ip: make the buf_size arg a size_t [142] + o INSTALL-CMAKE.md: explain `cmake -G ` [32] + o krb5: use dynbuf [149] + o ldap: fix unused variables (seen on OmniOS) [183] + o lib/cf-h1-proxy: silence compiler warnings (gcc 14) [155] + o lib: add trace support for client reads and writes [45] + o lib: bump hash sizes to `size_t` [153] + o lib: clear the easy handle's saved errno before transfer [180] + o lib: fix compiler warnings (gcc) [222] + o lib: make protocol handlers store scheme name lowercase [159] + o lib: merge `ENABLE_QUIC` C macro into `USE_HTTP3` [84] + o lib: remove two instances of "only only" messages [160] + o lib: silence `-Wsign-conversion` in base64, strcase, mprintf [139] + o lib: silence warnings on comma misuse [91] + o lib: use `#error` instead of invalid syntax in `curl_setup_once.h` [49] + o lib: use multi instead of multi_easy for the active multi [41] + o libcurl-opts: mention pipelining less [33] + o libssh2: delete redundant feature guard [171] + o libssh2: replace `access()` with `stat()` [145] + o libssh2: set length to 0 if strdup failed [6] + o m4: fix rustls pkg-config codepath [22] + o MAIL-ETIQUETTE: convert to markdown [12] + o makefile: remove the sorting from the vc-ide action [42] + o maketgz: put docs/RELEASE-TOOL.md into the tarball [35] + o managen: fix the option sort order [150] + o mbedtls: call mbedtls_ssl_setup() after RNG callback is set [66] + o mbedtls: cut off trailing newlines from debug logs [87] + o mbedtls: fix building with v3 in CMake Unity mode [107] + o mbedtls: support TLS 1.3 [156] + o mime: avoid using access() [125] + o misc: fix typos [62] + o misc: fix typos, quoting and spelling [167] + o mprintf: check fputc error rather than matching returned character [82] + o mqtt: when Curl_xfer_recv returns error, don't use nread [101] + o multi: avoid memory-leak risk [134] + o multi: introduce SETUP state for better timeouts [26] + o multi: multi_wait improvements [131] + o multi: remove the unused Curl_preconnect function [98] + o multi: remove useless assignment [146] + o multi: timeout handles even without connection [81] + o openldap: create ldap URLs correctly for IPv6 addresses [19] + o openssl: do not set SSL_MODE_RELEASE_BUFFERS [10] + o openssl: revert keylog_callback support for LibreSSL [192] + o OS400: fix shellcheck warnings in scripts [72] + o projects: drop MSVC project files for recent versions [79] + o pytest: add DELETE tests, check server version [225] + o pytest: fixes for recent python, add FTP tests [206] + o quic: fixup duplicate static function name (for cmake unity) [77] + o quiche: expire all active transfers on connection close [116] + o quiche: trust its timeout handling [190] + o RELEASE-PROCEDURE: mention an initial working build [7] + o request: make Curl_req_init return void [96] + o request: paused upload on completed download, assess connection [54] + o reuse: add copyright + license info to individual docs/*.md files [13] + o ROADMAP: remove completed entries, mention websocket + o rustls: fix handshake done handling [207] + o rustls: fix partial send handling [224] + o rustls: remove incorrect SSLSUPP_TLS13_CIPHERSUITES flag [115] + o rustsls: fix error code on receive [230] + o sendf: fix two typos in comments [90] + o sendf: useless assignment in cr_lc_read() [120] + o setopt: acknowledge errors proper for CURLOPT_COOKIEJAR [216] + o setopt: make the setstropt_userpwd args compulsory [221] + o setopt: remove check for 'option' that is always true [219] + o setopt: warn on Curl_set*opt() uses not using the return value [176] + o smtp: result of Curl_bufq_cread was not used [78] + o socket: remove redundant call to getsockname [195] + o socketpair: fix compilation when USE_UNIX_SOCKETS is not defined [229] + o src: tidy up types, add necessary casts [217] + o telnet: check return code from fileno() [112] + o tests/http: fix compiler warning [39] + o tests: add -q as first option when invoking curl for tests [97] + o tests: check caddy server version to match test expectations [106] + o tests: enable test 1117 for hyper [119] + o tests: fix feature case in test1481 [117] + o tests: fix test 1167 to skip digit-only symbols [214] + o tests: make the unit test result type `CURLcode` [165] + o tests: Mark tftpd timer function as noreturn [168] + o tests: tidy up types in server code [220] + o tls: fix SecureTransport + BearSSL cmake unity builds [113] + o tls: remove EXAMPLEs from deprecated options [164] + o tls: use shared init code for TCP+QUIC [57] + o tool: move tool_ftruncate64 to tool_util.c [138] + o tool_cb_rea: limit rate unpause for -T . uploads [136] + o tool_cfgable: free {proxy_}cipher13_list on exit [172] + o tool_getparam: output warning for leading unicode quote character [14] + o tool_getparam: remove two redundant conditions [189] + o tool_operate: don't truncate the etag save file by default [118] + o tool_operate: init vars unconditionally in post_per_transfer [124] + o tool_paramhlp: remove duplicate assign [121] + o tool_xattr: "guess" URL scheme if none is provided [3] + o tool_xattr: in debug builds, act normally if CURL_FAKE_XATTR is not set [4] + o transfer: remove useless assignment [122] + o url: do not URL decode proxy crendentials [55] + o url: fix use of an uninitialized variable [86] + o url: make parse_login_details use memdup0 [184] + o url: remove duplicate call to Curl_conncache_remove_conn when pruning [196] + o urlapi: allow setting port number zero [76] + o urlapi: fix relative redirects to fragment-only [83] + o urldata: remove fields not used depending on used features [46] + o vauth: make two functions void that always just returned OK [218] + o version: use msnprintf instead of strncpy [157] + o vquic-tls: use correct cert name check API for wolfSSL [226] + o vquic: use CURL_FORMAT_CURL_OFF_T for 64 bit printf output [18] + o vtls: TLS session storage overhaul [130] + o wakeup_create: use FD_CLOEXEC/SOCK_CLOEXEC [223] + o warnless: delete orphan declarations [209] + o websocket: avoid memory leak in error path [148] + o winbuild: add ENABLE_WEBSOCKETS option [93] + o winbuild: use $(RC) correctly [27] + o wolfssl: plug memory leak in wolfssl_connect_step2() [25] + o x509asn1: return error on missing OID [208] + +This release includes the following known bugs: + + o see docs/KNOWN_BUGS (https://curl.se/docs/knownbugs.html) + +Planned upcoming removals include: + + o support for space-separated NOPROXY patterns + + See https://curl.se/dev/deprecate.html for details + +This release would not have looked like this without help, code, reports and +advice from friends like these: + + Abdullah Alyan, Andrew, Antoine Bollengier, blankie, Brian Inglis, + Carlos Henrique Lima Melara, Ch40zz on github, Christian Schmitz, Chris Webb, + Colin Leroy-Mira, Dagfinn Ilmari MannsÃ¥ker, Dan Fandrich, Daniel Gustafsson, + Daniel J. H., Daniel McCarney, Daniel Stenberg, Dmitry Karpov, + Emanuele Torre, Evgeny Grin (Karlson2k), Fabian Keil, farazrbx on github, + fuzzard, Gisle Vanem, Gonçalo Carvalho, Gusted, hammlee96 on github, + Harmen Stoppels, Harry Sintonen, Hongfei Li, Ivan, Jan Macku, Jan Venekamp, + Jeff King, Jeroen Ooms, Jérôme Leclercq, Jiwoo Park, + Johann Sebastian Schicho, Jonatan Vela, Joseph Chen, Juliusz Sosinowicz, + Kailun Qin, kalvdans on github, Keitagit-kun on github, Konstantin Kuzov, + kpcyrd on github, Laramie Leavitt, LigH, Lucas Nussbaum, + magisterquis on hackerone, Marcel Raad, Matt Jolly, Max Dymond, Mel Zuser, + Michael Kaufmann, Michael Litwak, MichaÅ‚ Antoniak, Nathan Moinvaziri, + Orgad Shaneh, Patrick Monnerat, Paul Gilmartin, Paul Howarth, + Pavel Kropachev, Pavel Pavlov, Philip Heiduck, Rahul Krishna M, RainRat, + Ray Satiro, renovate[bot], riastradh on github, Robert Moreton, + Sanjay Pujare, Sergey Bronnikov, Sergey Ogryzkov, Sergio Durigan Junior, + southernedge on github, Stefan Eissing, Stephen Farrell, Tal Regev, + Tatsuhiro Tsujikawa, Tobias Stoeckmann, Toon Claes, Trumeet on github, + Trzik on github, Viktor Szakats, zmcx16 on github + (85 contributors) + +References to bug reports and discussions on issues: + + [1] = https://curl.se/bug/?i=13198 + [2] = https://curl.se/bug/?i=13191 + [3] = https://curl.se/bug/?i=13205 + [4] = https://curl.se/bug/?i=13220 + [5] = https://curl.se/bug/?i=13209 + [6] = https://curl.se/bug/?i=13213 + [7] = https://curl.se/bug/?i=13216 + [8] = https://curl.se/bug/?i=13208 + [9] = https://curl.se/bug/?i=13210 + [10] = https://curl.se/bug/?i=13203 + [11] = https://curl.se/bug/?i=13171 + [12] = https://curl.se/bug/?i=13247 + [13] = https://curl.se/bug/?i=13245 + [14] = https://curl.se/bug/?i=13214 + [15] = https://curl.se/bug/?i=13207 + [16] = https://curl.se/bug/?i=13236 + [17] = https://curl.se/bug/?i=13240 + [18] = https://curl.se/bug/?i=13224 + [19] = https://curl.se/bug/?i=13228 + [20] = https://curl.se/bug/?i=13230 + [21] = https://curl.se/bug/?i=13225 + [22] = https://curl.se/bug/?i=13200 + [23] = https://curl.se/bug/?i=13206 + [24] = https://curl.se/bug/?i=13197 + [25] = https://curl.se/bug/?i=13272 + [26] = https://curl.se/bug/?i=13371 + [27] = https://curl.se/bug/?i=13267 + [28] = https://curl.se/bug/?i=13268 + [29] = https://curl.se/bug/?i=13263 + [30] = https://curl.se/bug/?i=13281 + [31] = https://curl.se/bug/?i=13229 + [32] = https://curl.se/bug/?i=13244 + [33] = https://curl.se/bug/?i=13254 + [34] = https://curl.se/bug/?i=13135 + [35] = https://curl.se/bug/?i=13239 + [36] = https://curl.se/bug/?i=13242 + [37] = https://curl.se/bug/?i=13274 + [38] = https://curl.se/bug/?i=13299 + [39] = https://curl.se/bug/?i=13301 + [40] = https://curl.se/bug/?i=13327 + [41] = https://curl.se/bug/?i=12665 + [42] = https://curl.se/bug/?i=13294 + [43] = https://curl.se/bug/?i=13290 + [44] = https://curl.se/bug/?i=13258 + [45] = https://curl.se/bug/?i=13223 + [46] = https://curl.se/bug/?i=13188 + [47] = https://curl.se/bug/?i=13286 + [48] = https://curl.se/bug/?i=13282 + [49] = https://curl.se/bug/?i=13287 + [50] = https://curl.se/bug/?i=13284 + [51] = https://curl.se/bug/?i=13283 + [52] = https://curl.se/bug/?i=13269 + [53] = https://curl.se/bug/?i=13346 + [54] = https://curl.se/bug/?i=13260 + [55] = https://curl.se/bug/?i=13265 + [56] = https://curl.se/bug/?i=13322 + [57] = https://curl.se/bug/?i=13172 + [58] = https://curl.se/bug/?i=13218 + [59] = https://curl.se/bug/?i=13364 + [60] = https://curl.se/bug/?i=13313 + [61] = https://curl.se/bug/?i=13348 + [62] = https://curl.se/bug/?i=13344 + [63] = https://curl.se/bug/?i=13137 + [64] = https://curl.se/bug/?i=13264 + [65] = https://curl.se/bug/?i=13292 + [66] = https://curl.se/bug/?i=13314 + [67] = https://curl.se/bug/?i=13249 + [68] = https://curl.se/bug/?i=13335 + [69] = https://curl.se/bug/?i=13315 + [70] = https://curl.se/bug/?i=13307 + [71] = https://curl.se/bug/?i=13310 + [72] = https://curl.se/bug/?i=13309 + [73] = https://curl.se/bug/?i=13368 + [74] = https://curl.se/bug/?i=13372 + [75] = https://curl.se/bug/?i=13339 + [76] = https://curl.se/bug/?i=13427 + [77] = https://curl.se/bug/?i=13332 + [78] = https://curl.se/bug/?i=13398 + [79] = https://curl.se/bug/?i=13311 + [80] = https://curl.se/bug/?i=13324 + [81] = https://curl.se/bug/?i=13276 + [82] = https://curl.se/bug/?i=13367 + [83] = https://curl.se/bug/?i=13394 + [84] = https://curl.se/bug/?i=13352 + [85] = https://curl.se/bug/?i=13349 + [86] = https://curl.se/bug/?i=13399 + [87] = https://curl.se/bug/?i=13321 + [88] = https://curl.se/bug/?i=13426 + [89] = https://curl.se/bug/?i=13425 + [90] = https://curl.se/bug/?i=13393 + [91] = https://curl.se/bug/?i=13392 + [92] = https://curl.se/bug/?i=13204 + [93] = https://curl.se/bug/?i=13232 + [94] = https://curl.se/bug/?i=13411 + [95] = https://curl.se/bug/?i=13246 + [96] = https://curl.se/bug/?i=13423 + [97] = https://curl.se/bug/?i=13387 + [98] = https://curl.se/bug/?i=13422 + [99] = https://curl.se/bug/?i=13419 + [100] = https://curl.se/bug/?i=13421 + [101] = https://curl.se/bug/?i=13418 + [102] = https://curl.se/bug/?i=13417 + [103] = https://curl.se/bug/?i=13442 + [104] = https://curl.se/bug/?i=13337 + [105] = https://curl.se/bug/?i=13407 + [106] = https://curl.se/bug/?i=13405 + [107] = https://curl.se/bug/?i=13377 + [108] = https://curl.se/bug/?i=13373 + [109] = https://curl.se/bug/?i=11922 + [110] = https://curl.se/bug/?i=13499 + [111] = https://curl.se/bug/?i=13396 + [112] = https://curl.se/bug/?i=13457 + [113] = https://curl.se/bug/?i=13450 + [114] = https://curl.se/bug/?i=12327 + [115] = https://curl.se/bug/?i=13452 + [116] = https://curl.se/bug/?i=13439 + [117] = https://curl.se/bug/?i=13445 + [118] = https://curl.se/bug/?i=13432 + [119] = https://curl.se/bug/?i=13436 + [120] = https://curl.se/bug/?i=13437 + [121] = https://curl.se/bug/?i=13433 + [122] = https://curl.se/bug/?i=13435 + [123] = https://curl.se/bug/?i=13434 + [124] = https://curl.se/bug/?i=13430 + [125] = https://curl.se/bug/?i=13497 + [126] = https://curl.se/bug/?i=13464 + [127] = https://curl.se/bug/?i=13494 + [128] = https://curl.se/bug/?i=13491 + [129] = https://curl.se/bug/?i=13475 + [130] = https://curl.se/bug/?i=13386 + [131] = https://curl.se/bug/?i=13150 + [132] = https://curl.se/bug/?i=13510 + [133] = https://curl.se/bug/?i=13355 + [134] = https://curl.se/bug/?i=13471 + [135] = https://curl.se/bug/?i=13508 + [136] = https://curl.se/bug/?i=13174 + [137] = https://curl.se/bug/?i=13451 + [138] = https://curl.se/bug/?i=13458 + [139] = https://curl.se/bug/?i=13467 + [140] = https://curl.se/bug/?i=13562 + [141] = https://curl.se/bug/?i=13495 + [142] = https://curl.se/bug/?i=13505 + [143] = https://curl.se/bug/?i=13503 + [144] = https://curl.se/bug/?i=13502 + [145] = https://curl.se/bug/?i=13498 + [146] = https://curl.se/bug/?i=13500 + [147] = https://curl.se/bug/?i=13557 + [148] = https://curl.se/bug/?i=13602 + [149] = https://curl.se/bug/?i=13568 + [150] = https://curl.se/bug/?i=13567 + [151] = https://curl.se/bug/?i=13604 + [152] = https://curl.se/bug/?i=13566 + [153] = https://curl.se/bug/?i=13601 + [154] = https://curl.se/bug/?i=13554 + [155] = https://curl.se/bug/?i=13237 + [156] = https://curl.se/bug/?i=13539 + [157] = https://curl.se/bug/?i=13549 + [158] = https://curl.se/bug/?i=13550 + [159] = https://curl.se/bug/?i=13553 + [160] = https://curl.se/bug/?i=13551 + [161] = https://curl.se/bug/?i=13509 + [162] = https://curl.se/bug/?i=13542 + [163] = https://curl.se/bug/?i=13529 + [164] = https://curl.se/bug/?i=13540 + [165] = https://curl.se/bug/?i=13600 + [166] = https://curl.se/bug/?i=13541 + [167] = https://curl.se/bug/?i=13538 + [168] = https://curl.se/bug/?i=13534 + [169] = https://curl.se/bug/?i=13536 + [170] = https://curl.se/bug/?i=13725 + [171] = https://curl.se/bug/?i=13537 + [172] = https://curl.se/bug/?i=13531 + [173] = https://curl.se/bug/?i=13504 + [174] = https://curl.se/bug/?i=13533 + [175] = https://curl.se/bug/?i=13590 + [176] = https://curl.se/bug/?i=13591 + [177] = https://curl.se/bug/?i=13605 + [178] = https://curl.se/bug/?i=13501 + [179] = https://curl.se/bug/?i=13578 + [180] = https://curl.se/bug/?i=13574 + [181] = https://curl.se/bug/?i=13580 + [182] = https://curl.se/bug/?i=13582 + [183] = https://curl.se/bug/?i=13588 + [184] = https://curl.se/bug/?i=13584 + [185] = https://curl.se/bug/?i=13586 + [186] = https://curl.se/bug/?i=13579 + [187] = https://curl.se/bug/?i=13664 + [188] = https://curl.se/bug/?i=13577 + [189] = https://curl.se/bug/?i=13576 + [190] = https://curl.se/bug/?i=13581 + [191] = https://curl.se/bug/?i=13728 + [192] = https://curl.se/bug/?i=13672 + [193] = https://curl.se/bug/?i=13654 + [194] = https://curl.se/bug/?i=13628 + [195] = https://curl.se/bug/?i=13655 + [196] = https://curl.se/bug/?i=13710 + [197] = https://curl.se/bug/?i=13707 + [198] = https://curl.se/bug/?i=13729 + [199] = https://curl.se/bug/?i=13544 + [200] = https://curl.se/bug/?i=13733 + [201] = https://curl.se/bug/?i=13583 + [203] = https://curl.se/bug/?i=13697 + [206] = https://curl.se/bug/?i=13661 + [207] = https://curl.se/bug/?i=13686 + [208] = https://curl.se/bug/?i=13684 + [209] = https://curl.se/bug/?i=13639 + [210] = https://curl.se/bug/?i=13560 + [211] = https://curl.se/bug/?i=13638 + [212] = https://curl.se/bug/?i=13603 + [213] = https://curl.se/bug/?i=13611 + [214] = https://curl.se/bug/?i=13634 + [215] = https://curl.se/bug/?i=13681 + [216] = https://curl.se/bug/?i=13624 + [217] = https://curl.se/bug/?i=13614 + [218] = https://curl.se/bug/?i=13621 + [219] = https://curl.se/bug/?i=13619 + [220] = https://curl.se/bug/?i=13610 + [221] = https://curl.se/bug/?i=13608 + [222] = https://curl.se/bug/?i=13643 + [223] = https://curl.se/bug/?i=13618 + [224] = https://curl.se/bug/?i=13676 + [225] = https://curl.se/bug/?i=13679 + [226] = https://curl.se/bug/?i=13487 + [227] = https://curl.se/bug/?i=13668 + [229] = https://curl.se/bug/?i=13666 + [230] = https://curl.se/bug/?i=13670 diff --git a/third_party/curl/acinclude.m4 b/third_party/curl/acinclude.m4 new file mode 100644 index 0000000..a44ae35 --- /dev/null +++ b/third_party/curl/acinclude.m4 @@ -0,0 +1,1663 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +dnl CURL_CHECK_DEF (SYMBOL, [INCLUDES], [SILENT]) +dnl ------------------------------------------------- +dnl Use the C preprocessor to find out if the given object-style symbol +dnl is defined and get its expansion. This macro will not use default +dnl includes even if no INCLUDES argument is given. This macro will run +dnl silently when invoked with three arguments. If the expansion would +dnl result in a set of double-quoted strings the returned expansion will +dnl actually be a single double-quoted string concatenating all them. + +AC_DEFUN([CURL_CHECK_DEF], [ + AC_REQUIRE([CURL_CPP_P])dnl + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + AS_VAR_PUSHDEF([ac_HaveDef], [curl_cv_have_def_$1])dnl + AS_VAR_PUSHDEF([ac_Def], [curl_cv_def_$1])dnl + if test -z "$SED"; then + AC_MSG_ERROR([SED not set. Cannot continue without SED being set.]) + fi + if test -z "$GREP"; then + AC_MSG_ERROR([GREP not set. Cannot continue without GREP being set.]) + fi + ifelse($3,,[AC_MSG_CHECKING([for preprocessor definition of $1])]) + tmp_exp="" + AC_PREPROC_IFELSE([ + AC_LANG_SOURCE( +ifelse($2,,,[$2])[[ +#ifdef $1 +CURL_DEF_TOKEN $1 +#endif + ]]) + ],[ + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[[ ]][[ ]]*//' 2>/dev/null | \ + "$SED" 's/[["]][[ ]]*[["]]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "$1"; then + tmp_exp="" + fi + ]) + if test -z "$tmp_exp"; then + AS_VAR_SET(ac_HaveDef, no) + ifelse($3,,[AC_MSG_RESULT([no])]) + else + AS_VAR_SET(ac_HaveDef, yes) + AS_VAR_SET(ac_Def, $tmp_exp) + ifelse($3,,[AC_MSG_RESULT([$tmp_exp])]) + fi + AS_VAR_POPDEF([ac_Def])dnl + AS_VAR_POPDEF([ac_HaveDef])dnl + CPPFLAGS=$OLDCPPFLAGS +]) + + +dnl CURL_CHECK_DEF_CC (SYMBOL, [INCLUDES], [SILENT]) +dnl ------------------------------------------------- +dnl Use the C compiler to find out only if the given symbol is defined +dnl or not, this can not find out its expansion. This macro will not use +dnl default includes even if no INCLUDES argument is given. This macro +dnl will run silently when invoked with three arguments. + +AC_DEFUN([CURL_CHECK_DEF_CC], [ + AS_VAR_PUSHDEF([ac_HaveDef], [curl_cv_have_def_$1])dnl + ifelse($3,,[AC_MSG_CHECKING([for compiler definition of $1])]) + AC_COMPILE_IFELSE([ + AC_LANG_SOURCE( +ifelse($2,,,[$2])[[ +int main (void) +{ +#ifdef $1 + return 0; +#else + force compilation error +#endif +} + ]]) + ],[ + tst_symbol_defined="yes" + ],[ + tst_symbol_defined="no" + ]) + if test "$tst_symbol_defined" = "yes"; then + AS_VAR_SET(ac_HaveDef, yes) + ifelse($3,,[AC_MSG_RESULT([yes])]) + else + AS_VAR_SET(ac_HaveDef, no) + ifelse($3,,[AC_MSG_RESULT([no])]) + fi + AS_VAR_POPDEF([ac_HaveDef])dnl +]) + + +dnl CURL_CHECK_LIB_XNET +dnl ------------------------------------------------- +dnl Verify if X/Open network library is required. + +AC_DEFUN([CURL_CHECK_LIB_XNET], [ + AC_MSG_CHECKING([if X/Open network library is required]) + tst_lib_xnet_required="no" + AC_COMPILE_IFELSE([ + AC_LANG_SOURCE([[ +int main (void) +{ +#if defined(__hpux) && defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE >= 600) + return 0; +#elif defined(__hpux) && defined(_XOPEN_SOURCE_EXTENDED) + return 0; +#else + force compilation error +#endif +} + ]]) + ],[ + tst_lib_xnet_required="yes" + LIBS="-lxnet $LIBS" + ]) + AC_MSG_RESULT([$tst_lib_xnet_required]) +]) + + +dnl CURL_CHECK_AIX_ALL_SOURCE +dnl ------------------------------------------------- +dnl Provides a replacement of traditional AC_AIX with +dnl an uniform behavior across all autoconf versions, +dnl and with our own placement rules. + +AC_DEFUN([CURL_CHECK_AIX_ALL_SOURCE], [ + AH_VERBATIM([_ALL_SOURCE], + [/* Define to 1 if OS is AIX. */ +#ifndef _ALL_SOURCE +# undef _ALL_SOURCE +#endif]) + AC_BEFORE([$0], [AC_SYS_LARGEFILE])dnl + AC_BEFORE([$0], [CURL_CONFIGURE_REENTRANT])dnl + AC_MSG_CHECKING([if OS is AIX (to define _ALL_SOURCE)]) + AC_EGREP_CPP([yes_this_is_aix],[ +#ifdef _AIX + yes_this_is_aix +#endif + ],[ + AC_MSG_RESULT([yes]) + AC_DEFINE(_ALL_SOURCE) + ],[ + AC_MSG_RESULT([no]) + ]) +]) + + +dnl CURL_CHECK_NATIVE_WINDOWS +dnl ------------------------------------------------- +dnl Check if building a native Windows target + +AC_DEFUN([CURL_CHECK_NATIVE_WINDOWS], [ + AC_CACHE_CHECK([whether build target is a native Windows one], [curl_cv_native_windows], [ + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + ]],[[ +#ifdef _WIN32 + int dummy=1; +#else + Not a native Windows build target. +#endif + ]]) + ],[ + curl_cv_native_windows="yes" + ],[ + curl_cv_native_windows="no" + ]) + ]) + AM_CONDITIONAL(DOING_NATIVE_WINDOWS, test "x$curl_cv_native_windows" = xyes) +]) + + +dnl CURL_CHECK_HEADER_LBER +dnl ------------------------------------------------- +dnl Check for compilable and valid lber.h header, +dnl and check if it is needed even with ldap.h + +AC_DEFUN([CURL_CHECK_HEADER_LBER], [ + AC_REQUIRE([CURL_CHECK_NATIVE_WINDOWS])dnl + AC_CACHE_CHECK([for lber.h], [curl_cv_header_lber_h], [ + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#endif +#ifndef NULL +#define NULL (void *)0 +#endif +#include + ]],[[ + BerValue *bvp = NULL; + BerElement *bep = ber_init(bvp); + ber_free(bep, 1); + ]]) + ],[ + curl_cv_header_lber_h="yes" + ],[ + curl_cv_header_lber_h="no" + ]) + ]) + if test "$curl_cv_header_lber_h" = "yes"; then + AC_DEFINE_UNQUOTED(HAVE_LBER_H, 1, + [Define to 1 if you have the lber.h header file.]) + # + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#endif +#ifndef NULL +#define NULL (void *)0 +#endif +#ifndef LDAP_DEPRECATED +#define LDAP_DEPRECATED 1 +#endif +#include + ]],[[ + BerValue *bvp = NULL; + BerElement *bep = ber_init(bvp); + ber_free(bep, 1); + ]]) + ],[ + curl_cv_need_header_lber_h="no" + ],[ + curl_cv_need_header_lber_h="yes" + ]) + # + case "$curl_cv_need_header_lber_h" in + yes) + AC_DEFINE_UNQUOTED(NEED_LBER_H, 1, + [Define to 1 if you need the lber.h header file even with ldap.h]) + ;; + esac + fi +]) + + +dnl CURL_CHECK_HEADER_LDAP +dnl ------------------------------------------------- +dnl Check for compilable and valid ldap.h header + +AC_DEFUN([CURL_CHECK_HEADER_LDAP], [ + AC_REQUIRE([CURL_CHECK_HEADER_LBER])dnl + AC_CACHE_CHECK([for ldap.h], [curl_cv_header_ldap_h], [ + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#endif +#ifndef LDAP_DEPRECATED +#define LDAP_DEPRECATED 1 +#endif +#ifdef NEED_LBER_H +#include +#endif +#include + ]],[[ + LDAP *ldp = ldap_init("0.0.0.0", LDAP_PORT); + int res = ldap_unbind(ldp); + ]]) + ],[ + curl_cv_header_ldap_h="yes" + ],[ + curl_cv_header_ldap_h="no" + ]) + ]) + case "$curl_cv_header_ldap_h" in + yes) + AC_DEFINE_UNQUOTED(HAVE_LDAP_H, 1, + [Define to 1 if you have the ldap.h header file.]) + ;; + esac +]) + + +dnl CURL_CHECK_HEADER_LDAP_SSL +dnl ------------------------------------------------- +dnl Check for compilable and valid ldap_ssl.h header + +AC_DEFUN([CURL_CHECK_HEADER_LDAP_SSL], [ + AC_REQUIRE([CURL_CHECK_HEADER_LDAP])dnl + AC_CACHE_CHECK([for ldap_ssl.h], [curl_cv_header_ldap_ssl_h], [ + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#endif +#ifndef LDAP_DEPRECATED +#define LDAP_DEPRECATED 1 +#endif +#ifdef NEED_LBER_H +#include +#endif +#ifdef HAVE_LDAP_H +#include +#endif +#include + ]],[[ + LDAP *ldp = ldapssl_init("0.0.0.0", LDAPS_PORT, 1); + ]]) + ],[ + curl_cv_header_ldap_ssl_h="yes" + ],[ + curl_cv_header_ldap_ssl_h="no" + ]) + ]) + case "$curl_cv_header_ldap_ssl_h" in + yes) + AC_DEFINE_UNQUOTED(HAVE_LDAP_SSL_H, 1, + [Define to 1 if you have the ldap_ssl.h header file.]) + ;; + esac +]) + + +dnl CURL_CHECK_LIBS_WINLDAP +dnl ------------------------------------------------- +dnl Check for libraries needed for WINLDAP support, +dnl and prepended to LIBS any needed libraries. +dnl This macro can take an optional parameter with a +dnl whitespace separated list of libraries to check +dnl before the WINLDAP default ones. + +AC_DEFUN([CURL_CHECK_LIBS_WINLDAP], [ + AC_REQUIRE([CURL_CHECK_HEADER_WINBER])dnl + # + AC_MSG_CHECKING([for WINLDAP libraries]) + # + u_libs="" + # + ifelse($1,,,[ + for x_lib in $1; do + case "$x_lib" in + -l*) + l_lib="$x_lib" + ;; + *) + l_lib="-l$x_lib" + ;; + esac + if test -z "$u_libs"; then + u_libs="$l_lib" + else + u_libs="$u_libs $l_lib" + fi + done + ]) + # + curl_cv_save_LIBS="$LIBS" + curl_cv_ldap_LIBS="unknown" + # + for x_nlibs in '' "$u_libs" \ + '-lwldap32' ; do + if test "$curl_cv_ldap_LIBS" = "unknown"; then + if test -z "$x_nlibs"; then + LIBS="$curl_cv_save_LIBS" + else + LIBS="$x_nlibs $curl_cv_save_LIBS" + fi + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#include +#ifdef HAVE_WINBER_H +#include +#endif +#endif + ]],[[ + BERVAL *bvp = NULL; + BerElement *bep = ber_init(bvp); + LDAP *ldp = ldap_init("0.0.0.0", LDAP_PORT); + ULONG res = ldap_unbind(ldp); + ber_free(bep, 1); + ]]) + ],[ + curl_cv_ldap_LIBS="$x_nlibs" + ]) + fi + done + # + LIBS="$curl_cv_save_LIBS" + # + case X-"$curl_cv_ldap_LIBS" in + X-unknown) + AC_MSG_RESULT([cannot find WINLDAP libraries]) + ;; + X-) + AC_MSG_RESULT([no additional lib required]) + ;; + *) + if test -z "$curl_cv_save_LIBS"; then + LIBS="$curl_cv_ldap_LIBS" + else + LIBS="$curl_cv_ldap_LIBS $curl_cv_save_LIBS" + fi + AC_MSG_RESULT([$curl_cv_ldap_LIBS]) + ;; + esac + # +]) + + +dnl CURL_CHECK_LIBS_LDAP +dnl ------------------------------------------------- +dnl Check for libraries needed for LDAP support, +dnl and prepended to LIBS any needed libraries. +dnl This macro can take an optional parameter with a +dnl whitespace separated list of libraries to check +dnl before the default ones. + +AC_DEFUN([CURL_CHECK_LIBS_LDAP], [ + AC_REQUIRE([CURL_CHECK_HEADER_LDAP])dnl + # + AC_MSG_CHECKING([for LDAP libraries]) + # + u_libs="" + # + ifelse($1,,,[ + for x_lib in $1; do + case "$x_lib" in + -l*) + l_lib="$x_lib" + ;; + *) + l_lib="-l$x_lib" + ;; + esac + if test -z "$u_libs"; then + u_libs="$l_lib" + else + u_libs="$u_libs $l_lib" + fi + done + ]) + # + curl_cv_save_LIBS="$LIBS" + curl_cv_ldap_LIBS="unknown" + # + for x_nlibs in '' "$u_libs" \ + '-lldap' \ + '-lldap -llber' \ + '-llber -lldap' \ + '-lldapssl -lldapx -lldapsdk' \ + '-lldapsdk -lldapx -lldapssl' \ + '-lldap -llber -lssl -lcrypto' ; do + + if test "$curl_cv_ldap_LIBS" = "unknown"; then + if test -z "$x_nlibs"; then + LIBS="$curl_cv_save_LIBS" + else + LIBS="$x_nlibs $curl_cv_save_LIBS" + fi + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#endif +#ifndef NULL +#define NULL (void *)0 +#endif +#ifndef LDAP_DEPRECATED +#define LDAP_DEPRECATED 1 +#endif +#ifdef NEED_LBER_H +#include +#endif +#ifdef HAVE_LDAP_H +#include +#endif + ]],[[ + BerValue *bvp = NULL; + BerElement *bep = ber_init(bvp); + LDAP *ldp = ldap_init("0.0.0.0", LDAP_PORT); + int res = ldap_unbind(ldp); + ber_free(bep, 1); + ]]) + ],[ + curl_cv_ldap_LIBS="$x_nlibs" + ]) + fi + done + # + LIBS="$curl_cv_save_LIBS" + # + case X-"$curl_cv_ldap_LIBS" in + X-unknown) + AC_MSG_RESULT([cannot find LDAP libraries]) + ;; + X-) + AC_MSG_RESULT([no additional lib required]) + ;; + *) + if test -z "$curl_cv_save_LIBS"; then + LIBS="$curl_cv_ldap_LIBS" + else + LIBS="$curl_cv_ldap_LIBS $curl_cv_save_LIBS" + fi + AC_MSG_RESULT([$curl_cv_ldap_LIBS]) + ;; + esac + # +]) + + +dnl TYPE_SOCKADDR_STORAGE +dnl ------------------------------------------------- +dnl Check for struct sockaddr_storage. Most IPv6-enabled +dnl hosts have it, but AIX 4.3 is one known exception. + +AC_DEFUN([TYPE_SOCKADDR_STORAGE], +[ + AC_CHECK_TYPE([struct sockaddr_storage], + AC_DEFINE(HAVE_STRUCT_SOCKADDR_STORAGE, 1, + [if struct sockaddr_storage is defined]), , + [ +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#endif + ]) +]) + +dnl CURL_CHECK_FUNC_RECV +dnl ------------------------------------------------- +dnl Test if the socket recv() function is available, + +AC_DEFUN([CURL_CHECK_FUNC_RECV], [ + AC_REQUIRE([CURL_CHECK_NATIVE_WINDOWS])dnl + AC_REQUIRE([CURL_INCLUDES_BSDSOCKET])dnl + AC_CHECK_HEADERS(sys/types.h sys/socket.h) + # + AC_MSG_CHECKING([for recv]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +$curl_includes_bsdsocket +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#endif + ]],[[ + recv(0, 0, 0, 0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + curl_cv_recv="yes" + ],[ + AC_MSG_RESULT([no]) + curl_cv_recv="no" + ]) + # + if test "$curl_cv_recv" = "yes"; then + AC_DEFINE_UNQUOTED(HAVE_RECV, 1, + [Define to 1 if you have the recv function.]) + curl_cv_func_recv="yes" + else + AC_MSG_ERROR([Unable to link function recv]) + fi +]) + + +dnl CURL_CHECK_FUNC_SEND +dnl ------------------------------------------------- +dnl Test if the socket send() function is available, + +AC_DEFUN([CURL_CHECK_FUNC_SEND], [ + AC_REQUIRE([CURL_CHECK_NATIVE_WINDOWS])dnl + AC_REQUIRE([CURL_INCLUDES_BSDSOCKET])dnl + AC_CHECK_HEADERS(sys/types.h sys/socket.h) + # + AC_MSG_CHECKING([for send]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +$curl_includes_bsdsocket +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#endif + ]],[[ + send(0, 0, 0, 0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + curl_cv_send="yes" + ],[ + AC_MSG_RESULT([no]) + curl_cv_send="no" + ]) + # + if test "$curl_cv_send" = "yes"; then + AC_DEFINE_UNQUOTED(HAVE_SEND, 1, + [Define to 1 if you have the send function.]) + curl_cv_func_send="yes" + else + AC_MSG_ERROR([Unable to link function send]) + fi +]) + +dnl CURL_CHECK_MSG_NOSIGNAL +dnl ------------------------------------------------- +dnl Check for MSG_NOSIGNAL + +AC_DEFUN([CURL_CHECK_MSG_NOSIGNAL], [ + AC_CHECK_HEADERS(sys/types.h sys/socket.h) + AC_CACHE_CHECK([for MSG_NOSIGNAL], [curl_cv_msg_nosignal], [ + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#endif + ]],[[ + int flag=MSG_NOSIGNAL; + ]]) + ],[ + curl_cv_msg_nosignal="yes" + ],[ + curl_cv_msg_nosignal="no" + ]) + ]) + case "$curl_cv_msg_nosignal" in + yes) + AC_DEFINE_UNQUOTED(HAVE_MSG_NOSIGNAL, 1, + [Define to 1 if you have the MSG_NOSIGNAL flag.]) + ;; + esac +]) + + +dnl CURL_CHECK_STRUCT_TIMEVAL +dnl ------------------------------------------------- +dnl Check for timeval struct + +AC_DEFUN([CURL_CHECK_STRUCT_TIMEVAL], [ + AC_REQUIRE([CURL_CHECK_NATIVE_WINDOWS])dnl + AC_CHECK_HEADERS(sys/types.h sys/time.h sys/socket.h) + AC_CACHE_CHECK([for struct timeval], [curl_cv_struct_timeval], [ + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#endif +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +#ifdef HAVE_SYS_SOCKET_H +#include +#endif + ]],[[ + struct timeval ts; + ts.tv_sec = 0; + ts.tv_usec = 0; + ]]) + ],[ + curl_cv_struct_timeval="yes" + ],[ + curl_cv_struct_timeval="no" + ]) + ]) + case "$curl_cv_struct_timeval" in + yes) + AC_DEFINE_UNQUOTED(HAVE_STRUCT_TIMEVAL, 1, + [Define to 1 if you have the timeval struct.]) + ;; + esac +]) + + +dnl TYPE_IN_ADDR_T +dnl ------------------------------------------------- +dnl Check for in_addr_t: it is used to receive the return code of inet_addr() +dnl and a few other things. + +AC_DEFUN([TYPE_IN_ADDR_T], [ + AC_CHECK_TYPE([in_addr_t], ,[ + dnl in_addr_t not available + AC_CACHE_CHECK([for in_addr_t equivalent], + [curl_cv_in_addr_t_equiv], [ + curl_cv_in_addr_t_equiv="unknown" + for t in "unsigned long" int size_t unsigned long; do + if test "$curl_cv_in_addr_t_equiv" = "unknown"; then + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#endif + ]],[[ + $t data = inet_addr ("1.2.3.4"); + ]]) + ],[ + curl_cv_in_addr_t_equiv="$t" + ]) + fi + done + ]) + case "$curl_cv_in_addr_t_equiv" in + unknown) + AC_MSG_ERROR([Cannot find a type to use in place of in_addr_t]) + ;; + *) + AC_DEFINE_UNQUOTED(in_addr_t, $curl_cv_in_addr_t_equiv, + [Type to use in place of in_addr_t when system does not provide it.]) + ;; + esac + ],[ +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#endif + ]) +]) + + +dnl CURL_CHECK_FUNC_CLOCK_GETTIME_MONOTONIC +dnl ------------------------------------------------- +dnl Check if monotonic clock_gettime is available. + +AC_DEFUN([CURL_CHECK_FUNC_CLOCK_GETTIME_MONOTONIC], [ + AC_CHECK_HEADERS(sys/types.h sys/time.h) + AC_MSG_CHECKING([for monotonic clock_gettime]) + # + if test "x$dontwant_rt" = "xno" ; then + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include + ]],[[ + struct timespec ts; + (void)clock_gettime(CLOCK_MONOTONIC, &ts); + ]]) + ],[ + AC_MSG_RESULT([yes]) + curl_func_clock_gettime="yes" + ],[ + AC_MSG_RESULT([no]) + curl_func_clock_gettime="no" + ]) + fi + dnl Definition of HAVE_CLOCK_GETTIME_MONOTONIC is intentionally postponed + dnl until library linking and run-time checks for clock_gettime succeed. +]) + +dnl CURL_CHECK_FUNC_CLOCK_GETTIME_MONOTONIC_RAW +dnl ------------------------------------------------- +dnl Check if monotonic clock_gettime is available. + +AC_DEFUN([CURL_CHECK_FUNC_CLOCK_GETTIME_MONOTONIC_RAW], [ + AC_CHECK_HEADERS(sys/types.h sys/time.h) + AC_MSG_CHECKING([for raw monotonic clock_gettime]) + # + if test "x$dontwant_rt" = "xno" ; then + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include + ]],[[ + struct timespec ts; + (void)clock_gettime(CLOCK_MONOTONIC_RAW, &ts); + ]]) + ],[ + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_CLOCK_GETTIME_MONOTONIC_RAW, 1, + [Define to 1 if you have the clock_gettime function and raw monotonic timer.]) + ],[ + AC_MSG_RESULT([no]) + ]) + fi +]) + + +dnl CURL_CHECK_LIBS_CLOCK_GETTIME_MONOTONIC +dnl ------------------------------------------------- +dnl If monotonic clock_gettime is available then, +dnl check and prepended to LIBS any needed libraries. + +AC_DEFUN([CURL_CHECK_LIBS_CLOCK_GETTIME_MONOTONIC], [ + AC_REQUIRE([CURL_CHECK_FUNC_CLOCK_GETTIME_MONOTONIC])dnl + # + if test "$curl_func_clock_gettime" = "yes"; then + # + AC_MSG_CHECKING([for clock_gettime in libraries]) + # + curl_cv_save_LIBS="$LIBS" + curl_cv_gclk_LIBS="unknown" + # + for x_xlibs in '' '-lrt' '-lposix4' ; do + if test "$curl_cv_gclk_LIBS" = "unknown"; then + if test -z "$x_xlibs"; then + LIBS="$curl_cv_save_LIBS" + else + LIBS="$x_xlibs $curl_cv_save_LIBS" + fi + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include + ]],[[ + struct timespec ts; + (void)clock_gettime(CLOCK_MONOTONIC, &ts); + ]]) + ],[ + curl_cv_gclk_LIBS="$x_xlibs" + ]) + fi + done + # + LIBS="$curl_cv_save_LIBS" + # + case X-"$curl_cv_gclk_LIBS" in + X-unknown) + AC_MSG_RESULT([cannot find clock_gettime]) + AC_MSG_WARN([HAVE_CLOCK_GETTIME_MONOTONIC will not be defined]) + curl_func_clock_gettime="no" + ;; + X-) + AC_MSG_RESULT([no additional lib required]) + curl_func_clock_gettime="yes" + ;; + *) + if test -z "$curl_cv_save_LIBS"; then + LIBS="$curl_cv_gclk_LIBS" + else + LIBS="$curl_cv_gclk_LIBS $curl_cv_save_LIBS" + fi + AC_MSG_RESULT([$curl_cv_gclk_LIBS]) + curl_func_clock_gettime="yes" + ;; + esac + # + dnl only do runtime verification when not cross-compiling + if test "x$cross_compiling" != "xyes" && + test "$curl_func_clock_gettime" = "yes"; then + AC_MSG_CHECKING([if monotonic clock_gettime works]) + CURL_RUN_IFELSE([ + AC_LANG_PROGRAM([[ +#include +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include + ]],[[ + struct timespec ts; + if (0 == clock_gettime(CLOCK_MONOTONIC, &ts)) + exit(0); + else + exit(1); + ]]) + ],[ + AC_MSG_RESULT([yes]) + ],[ + AC_MSG_RESULT([no]) + AC_MSG_WARN([HAVE_CLOCK_GETTIME_MONOTONIC will not be defined]) + curl_func_clock_gettime="no" + LIBS="$curl_cv_save_LIBS" + ]) + fi + # + case "$curl_func_clock_gettime" in + yes) + AC_DEFINE_UNQUOTED(HAVE_CLOCK_GETTIME_MONOTONIC, 1, + [Define to 1 if you have the clock_gettime function and monotonic timer.]) + ;; + esac + # + fi + # +]) + + +dnl CURL_CHECK_LIBS_CONNECT +dnl ------------------------------------------------- +dnl Verify if network connect function is already available +dnl using current libraries or if another one is required. + +AC_DEFUN([CURL_CHECK_LIBS_CONNECT], [ + AC_REQUIRE([CURL_INCLUDES_WINSOCK2])dnl + AC_REQUIRE([CURL_INCLUDES_BSDSOCKET])dnl + AC_MSG_CHECKING([for connect in libraries]) + tst_connect_save_LIBS="$LIBS" + tst_connect_need_LIBS="unknown" + for tst_lib in '' '-lsocket' ; do + if test "$tst_connect_need_LIBS" = "unknown"; then + LIBS="$tst_lib $tst_connect_save_LIBS" + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_bsdsocket + #if !defined(_WIN32) && !defined(HAVE_PROTO_BSDSOCKET_H) + int connect(int, void*, int); + #endif + ]],[[ + if(0 != connect(0, 0, 0)) + return 1; + ]]) + ],[ + tst_connect_need_LIBS="$tst_lib" + ]) + fi + done + LIBS="$tst_connect_save_LIBS" + # + case X-"$tst_connect_need_LIBS" in + X-unknown) + AC_MSG_RESULT([cannot find connect]) + AC_MSG_ERROR([cannot find connect function in libraries.]) + ;; + X-) + AC_MSG_RESULT([yes]) + ;; + *) + AC_MSG_RESULT([$tst_connect_need_LIBS]) + LIBS="$tst_connect_need_LIBS $tst_connect_save_LIBS" + ;; + esac +]) + + +dnl CURL_DEFINE_UNQUOTED (VARIABLE, [VALUE]) +dnl ------------------------------------------------- +dnl Like AC_DEFINE_UNQUOTED this macro will define a C preprocessor +dnl symbol that can be further used in custom template configuration +dnl files. This macro, unlike AC_DEFINE_UNQUOTED, does not use a third +dnl argument for the description. Symbol definitions done with this +dnl macro are intended to be exclusively used in handcrafted *.h.in +dnl template files. Contrary to what AC_DEFINE_UNQUOTED does, this one +dnl prevents autoheader generation and insertion of symbol template +dnl stub and definition into the first configuration header file. Do +dnl not use this macro as a replacement for AC_DEFINE_UNQUOTED, each +dnl one serves different functional needs. + +AC_DEFUN([CURL_DEFINE_UNQUOTED], [ +cat >>confdefs.h <<_EOF +[@%:@define] $1 ifelse($#, 2, [$2], 1) +_EOF +]) + + +dnl CURL_CHECK_FUNC_SELECT +dnl ------------------------------------------------- +dnl Test if the socket select() function is available. + +AC_DEFUN([CURL_CHECK_FUNC_SELECT], [ + AC_REQUIRE([CURL_CHECK_STRUCT_TIMEVAL])dnl + AC_REQUIRE([CURL_INCLUDES_BSDSOCKET])dnl + AC_CHECK_HEADERS(sys/select.h sys/socket.h) + # + AC_MSG_CHECKING([for select]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#endif +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +#ifndef _WIN32 +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +$curl_includes_bsdsocket +#endif + ]],[[ + select(0, 0, 0, 0, 0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + curl_cv_select="yes" + ],[ + AC_MSG_RESULT([no]) + curl_cv_select="no" + ]) + # + if test "$curl_cv_select" = "yes"; then + AC_DEFINE_UNQUOTED(HAVE_SELECT, 1, + [Define to 1 if you have the select function.]) + curl_cv_func_select="yes" + fi +]) + + +dnl CURL_VERIFY_RUNTIMELIBS +dnl ------------------------------------------------- +dnl Verify that the shared libs found so far can be used when running +dnl programs, since otherwise the situation will create odd configure errors +dnl that are misleading people. +dnl +dnl Make sure this test is run BEFORE the first test in the script that +dnl runs anything, which at the time of this writing is the AC_CHECK_SIZEOF +dnl macro. It must also run AFTER all lib-checking macros are complete. + +AC_DEFUN([CURL_VERIFY_RUNTIMELIBS], [ + + dnl this test is of course not sensible if we are cross-compiling! + if test "x$cross_compiling" != xyes; then + + dnl just run a program to verify that the libs checked for previous to this + dnl point also is available run-time! + AC_MSG_CHECKING([run-time libs availability]) + CURL_RUN_IFELSE([ +int main() +{ + return 0; +} +], + AC_MSG_RESULT([fine]), + AC_MSG_RESULT([failed]) + AC_MSG_ERROR([one or more libs available at link-time are not available run-time. Libs used at link-time: $LIBS]) + ) + + dnl if this test fails, configure has already stopped + fi +]) + + +dnl CURL_CHECK_CA_BUNDLE +dnl ------------------------------------------------- +dnl Check if a default ca-bundle should be used +dnl +dnl regarding the paths this will scan: +dnl /etc/ssl/certs/ca-certificates.crt Debian systems +dnl /etc/pki/tls/certs/ca-bundle.crt Redhat and Mandriva +dnl /usr/share/ssl/certs/ca-bundle.crt old(er) Redhat +dnl /usr/local/share/certs/ca-root-nss.crt MidnightBSD +dnl /etc/ssl/cert.pem OpenBSD, MidnightBSD (symlink) +dnl /etc/ssl/certs (CA path) SUSE, FreeBSD + +AC_DEFUN([CURL_CHECK_CA_BUNDLE], [ + + AC_MSG_CHECKING([default CA cert bundle/path]) + + AC_ARG_WITH(ca-bundle, +AS_HELP_STRING([--with-ca-bundle=FILE], +[Path to a file containing CA certificates (example: /etc/ca-bundle.crt)]) +AS_HELP_STRING([--without-ca-bundle], [Don't use a default CA bundle]), + [ + want_ca="$withval" + if test "x$want_ca" = "xyes"; then + AC_MSG_ERROR([--with-ca-bundle=FILE requires a path to the CA bundle]) + fi + ], + [ want_ca="unset" ]) + AC_ARG_WITH(ca-path, +AS_HELP_STRING([--with-ca-path=DIRECTORY], +[Path to a directory containing CA certificates stored individually, with \ +their filenames in a hash format. This option can be used with the OpenSSL, \ +GnuTLS, mbedTLS and wolfSSL backends. Refer to OpenSSL c_rehash for details. \ +(example: /etc/certificates)]) +AS_HELP_STRING([--without-ca-path], [Don't use a default CA path]), + [ + want_capath="$withval" + if test "x$want_capath" = "xyes"; then + AC_MSG_ERROR([--with-ca-path=DIRECTORY requires a path to the CA path directory]) + fi + ], + [ want_capath="unset"]) + + ca_warning=" (warning: certs not found)" + capath_warning=" (warning: certs not found)" + check_capath="" + + if test "x$want_ca" != "xno" -a "x$want_ca" != "xunset" -a \ + "x$want_capath" != "xno" -a "x$want_capath" != "xunset"; then + dnl both given + ca="$want_ca" + capath="$want_capath" + elif test "x$want_ca" != "xno" -a "x$want_ca" != "xunset"; then + dnl --with-ca-bundle given + ca="$want_ca" + capath="no" + elif test "x$want_capath" != "xno" -a "x$want_capath" != "xunset"; then + dnl --with-ca-path given + if test "x$OPENSSL_ENABLED" != "x1" -a \ + "x$GNUTLS_ENABLED" != "x1" -a \ + "x$MBEDTLS_ENABLED" != "x1" -a \ + "x$WOLFSSL_ENABLED" != "x1"; then + AC_MSG_ERROR([--with-ca-path only works with OpenSSL, GnuTLS, mbedTLS or wolfSSL]) + fi + capath="$want_capath" + ca="no" + else + dnl first try autodetecting a CA bundle , then a CA path + dnl both autodetections can be skipped by --without-ca-* + ca="no" + capath="no" + if test "x$cross_compiling" != "xyes"; then + dnl NOT cross-compiling and... + dnl neither of the --with-ca-* options are provided + if test "x$want_ca" = "xunset"; then + dnl the path we previously would have installed the curl ca bundle + dnl to, and thus we now check for an already existing cert in that + dnl place in case we find no other + if test "x$prefix" != xNONE; then + cac="${prefix}/share/curl/curl-ca-bundle.crt" + else + cac="$ac_default_prefix/share/curl/curl-ca-bundle.crt" + fi + + for a in /etc/ssl/certs/ca-certificates.crt \ + /etc/pki/tls/certs/ca-bundle.crt \ + /usr/share/ssl/certs/ca-bundle.crt \ + /usr/local/share/certs/ca-root-nss.crt \ + /etc/ssl/cert.pem \ + "$cac"; do + if test -f "$a"; then + ca="$a" + break + fi + done + fi + AC_MSG_NOTICE([want $want_capath ca $ca]) + if test "x$want_capath" = "xunset"; then + if test "x$OPENSSL_ENABLED" = "x1" -o \ + "x$GNUTLS_ENABLED" = "x1" -o \ + "x$MBEDTLS_ENABLED" = "x1" -o \ + "x$WOLFSSL_ENABLED" = "x1"; then + check_capath="/etc/ssl/certs" + fi + fi + else + dnl no option given and cross-compiling + AC_MSG_WARN([skipped the ca-cert path detection when cross-compiling]) + fi + fi + + if test "x$ca" = "xno" || test -f "$ca"; then + ca_warning="" + fi + + if test "x$capath" != "xno"; then + check_capath="$capath" + fi + + if test ! -z "$check_capath"; then + for a in "$check_capath"; do + if test -d "$a" && ls "$a"/[[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]].0 >/dev/null 2>/dev/null; then + if test "x$capath" = "xno"; then + capath="$a" + fi + capath_warning="" + break + fi + done + fi + + if test "x$capath" = "xno"; then + capath_warning="" + fi + + if test "x$ca" != "xno"; then + CURL_CA_BUNDLE='"'$ca'"' + AC_DEFINE_UNQUOTED(CURL_CA_BUNDLE, "$ca", [Location of default ca bundle]) + AC_SUBST(CURL_CA_BUNDLE) + AC_MSG_RESULT([$ca]) + fi + if test "x$capath" != "xno"; then + CURL_CA_PATH="\"$capath\"" + AC_DEFINE_UNQUOTED(CURL_CA_PATH, "$capath", [Location of default ca path]) + AC_MSG_RESULT([$capath (capath)]) + fi + if test "x$ca" = "xno" && test "x$capath" = "xno"; then + AC_MSG_RESULT([no]) + fi + + AC_MSG_CHECKING([whether to use builtin CA store of SSL library]) + AC_ARG_WITH(ca-fallback, +AS_HELP_STRING([--with-ca-fallback], [Use the built in CA store of the SSL library]) +AS_HELP_STRING([--without-ca-fallback], [Don't use the built in CA store of the SSL library]), + [ + if test "x$with_ca_fallback" != "xyes" -a "x$with_ca_fallback" != "xno"; then + AC_MSG_ERROR([--with-ca-fallback only allows yes or no as parameter]) + fi + ], + [ with_ca_fallback="no"]) + AC_MSG_RESULT([$with_ca_fallback]) + if test "x$with_ca_fallback" = "xyes"; then + if test "x$OPENSSL_ENABLED" != "x1" -a "x$GNUTLS_ENABLED" != "x1"; then + AC_MSG_ERROR([--with-ca-fallback only works with OpenSSL or GnuTLS]) + fi + AC_DEFINE_UNQUOTED(CURL_CA_FALLBACK, 1, [define "1" to use built in CA store of SSL library ]) + fi +]) + +dnl CURL_CHECK_WIN32_LARGEFILE +dnl ------------------------------------------------- +dnl Check if curl's WIN32 large file will be used + +AC_DEFUN([CURL_CHECK_WIN32_LARGEFILE], [ + AC_REQUIRE([CURL_CHECK_NATIVE_WINDOWS])dnl + AC_MSG_CHECKING([whether build target supports WIN32 file API]) + curl_win32_file_api="no" + if test "$curl_cv_native_windows" = "yes"; then + if test x"$enable_largefile" != "xno"; then + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + ]],[[ +#if !defined(_WIN32_WCE) && (defined(__MINGW32__) || defined(_MSC_VER)) + int dummy=1; +#else + WIN32 large file API not supported. +#endif + ]]) + ],[ + curl_win32_file_api="win32_large_files" + ]) + fi + if test "$curl_win32_file_api" = "no"; then + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + ]],[[ +#if defined(_WIN32_WCE) || defined(__MINGW32__) || defined(_MSC_VER) + int dummy=1; +#else + WIN32 small file API not supported. +#endif + ]]) + ],[ + curl_win32_file_api="win32_small_files" + ]) + fi + fi + case "$curl_win32_file_api" in + win32_large_files) + AC_MSG_RESULT([yes (large file enabled)]) + AC_DEFINE_UNQUOTED(USE_WIN32_LARGE_FILES, 1, + [Define to 1 if you are building a Windows target with large file support.]) + AC_SUBST(USE_WIN32_LARGE_FILES, [1]) + ;; + win32_small_files) + AC_MSG_RESULT([yes (large file disabled)]) + AC_DEFINE_UNQUOTED(USE_WIN32_SMALL_FILES, 1, + [Define to 1 if you are building a Windows target without large file support.]) + AC_SUBST(USE_WIN32_SMALL_FILES, [1]) + ;; + *) + AC_MSG_RESULT([no]) + ;; + esac +]) + +dnl CURL_CHECK_WIN32_CRYPTO +dnl ------------------------------------------------- +dnl Check if curl's WIN32 crypto lib can be used + +AC_DEFUN([CURL_CHECK_WIN32_CRYPTO], [ + AC_REQUIRE([CURL_CHECK_NATIVE_WINDOWS])dnl + AC_MSG_CHECKING([whether build target supports WIN32 crypto API]) + curl_win32_crypto_api="no" + if test "$curl_cv_native_windows" = "yes"; then + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#undef inline +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#include + ]],[[ + HCRYPTPROV hCryptProv; + if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { + CryptReleaseContext(hCryptProv, 0); + } + ]]) + ],[ + curl_win32_crypto_api="yes" + ]) + fi + case "$curl_win32_crypto_api" in + yes) + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(USE_WIN32_CRYPTO, 1, + [Define to 1 if you are building a Windows target with crypto API support.]) + AC_SUBST(USE_WIN32_CRYPTO, [1]) + ;; + *) + AC_MSG_RESULT([no]) + ;; + esac +]) + +dnl CURL_EXPORT_PCDIR ($pcdir) +dnl ------------------------ +dnl if $pcdir is not empty, set PKG_CONFIG_LIBDIR to $pcdir and export +dnl +dnl we need this macro since pkg-config distinguishes among empty and unset +dnl variable while checking PKG_CONFIG_LIBDIR +dnl + +AC_DEFUN([CURL_EXPORT_PCDIR], [ + if test -n "$1"; then + PKG_CONFIG_LIBDIR="$1" + export PKG_CONFIG_LIBDIR + fi +]) + +dnl CURL_CHECK_PKGCONFIG ($module, [$pcdir]) +dnl ------------------------ +dnl search for the pkg-config tool. Set the PKGCONFIG variable to hold the +dnl path to it, or 'no' if not found/present. +dnl +dnl If pkg-config is present, check that it has info about the $module or +dnl return "no" anyway! +dnl +dnl Optionally PKG_CONFIG_LIBDIR may be given as $pcdir. +dnl + +AC_DEFUN([CURL_CHECK_PKGCONFIG], [ + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + AC_PATH_TOOL([PKGCONFIG], [pkg-config], [no], + [$PATH:/usr/bin:/usr/local/bin]) + fi + + if test "x$PKGCONFIG" != "xno"; then + AC_MSG_CHECKING([for $1 options with pkg-config]) + dnl ask pkg-config about $1 + itexists=`CURL_EXPORT_PCDIR([$2]) dnl + $PKGCONFIG --exists $1 >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + dnl pkg-config does not have info about the given module! set the + dnl variable to 'no' + PKGCONFIG="no" + AC_MSG_RESULT([no]) + else + AC_MSG_RESULT([found]) + fi + fi +]) + + +dnl CURL_GENERATE_CONFIGUREHELP_PM +dnl ------------------------------------------------- +dnl Generate test harness configurehelp.pm module, defining and +dnl initializing some perl variables with values which are known +dnl when the configure script runs. For portability reasons, test +dnl harness needs information on how to run the C preprocessor. + +AC_DEFUN([CURL_GENERATE_CONFIGUREHELP_PM], [ + AC_REQUIRE([AC_PROG_CPP])dnl + tmp_cpp=`eval echo "$ac_cpp" 2>/dev/null` + if test -z "$tmp_cpp"; then + tmp_cpp='cpp' + fi + cat >./tests/configurehelp.pm <<_EOF +[@%:@] This is a generated file. Do not edit. + +package configurehelp; + +use strict; +use warnings; +use Exporter; + +use vars qw( + @ISA + @EXPORT_OK + \$Cpreprocessor + ); + +@ISA = qw(Exporter); + +@EXPORT_OK = qw( + \$Cpreprocessor + ); + +\$Cpreprocessor = '$tmp_cpp'; + +1; +_EOF +]) + +dnl CURL_CPP_P +dnl +dnl Check if $cpp -P should be used for extract define values due to gcc 5 +dnl splitting up strings and defines between line outputs. gcc by default +dnl (without -P) will show TEST EINVAL TEST as +dnl +dnl # 13 "conftest.c" +dnl TEST +dnl # 13 "conftest.c" 3 4 +dnl 22 +dnl # 13 "conftest.c" +dnl TEST + +AC_DEFUN([CURL_CPP_P], [ + AC_MSG_CHECKING([if cpp -P is needed]) + AC_EGREP_CPP([TEST.*TEST], [ + #include +TEST EINVAL TEST + ], [cpp=no], [cpp=yes]) + AC_MSG_RESULT([$cpp]) + + dnl we need cpp -P so check if it works then + if test "x$cpp" = "xyes"; then + AC_MSG_CHECKING([if cpp -P works]) + OLDCPPFLAGS=$CPPFLAGS + CPPFLAGS="$CPPFLAGS -P" + AC_EGREP_CPP([TEST.*TEST], [ + #include +TEST EINVAL TEST + ], [cpp_p=yes], [cpp_p=no]) + AC_MSG_RESULT([$cpp_p]) + + if test "x$cpp_p" = "xno"; then + AC_MSG_WARN([failed to figure out cpp -P alternative]) + # without -P + CPPPFLAG="" + else + # with -P + CPPPFLAG="-P" + fi + dnl restore CPPFLAGS + CPPFLAGS=$OLDCPPFLAGS + else + # without -P + CPPPFLAG="" + fi +]) + + +dnl CURL_DARWIN_CFLAGS +dnl +dnl Set -Werror=partial-availability to detect possible breaking code +dnl with very low deployment targets. +dnl + +AC_DEFUN([CURL_DARWIN_CFLAGS], [ + + tst_cflags="no" + case $host_os in + darwin*) + tst_cflags="yes" + ;; + esac + + AC_MSG_CHECKING([for good-to-use Darwin CFLAGS]) + AC_MSG_RESULT([$tst_cflags]); + + if test "$tst_cflags" = "yes"; then + old_CFLAGS=$CFLAGS + CFLAGS="$CFLAGS -Werror=partial-availability" + AC_MSG_CHECKING([whether $CC accepts -Werror=partial-availability]) + AC_COMPILE_IFELSE([AC_LANG_PROGRAM()], + [AC_MSG_RESULT([yes])], + [AC_MSG_RESULT([no]) + CFLAGS=$old_CFLAGS]) + fi + +]) + + +dnl CURL_SUPPORTS_BUILTIN_AVAILABLE +dnl +dnl Check to see if the compiler supports __builtin_available. This built-in +dnl compiler function first appeared in Apple LLVM 9.0.0. It's so new that, at +dnl the time this macro was written, the function was not yet documented. Its +dnl purpose is to return true if the code is running under a certain OS version +dnl or later. + +AC_DEFUN([CURL_SUPPORTS_BUILTIN_AVAILABLE], [ + AC_MSG_CHECKING([to see if the compiler supports __builtin_available()]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#include + ]],[[ + if (__builtin_available(macOS 10.8, iOS 5.0, *)) {} + ]]) + ],[ + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_BUILTIN_AVAILABLE, 1, + [Define to 1 if you have the __builtin_available function.]) + ],[ + AC_MSG_RESULT([no]) + ]) +]) diff --git a/third_party/curl/aclocal.m4 b/third_party/curl/aclocal.m4 new file mode 100644 index 0000000..a1af02c --- /dev/null +++ b/third_party/curl/aclocal.m4 @@ -0,0 +1,1252 @@ +# generated automatically by aclocal 1.16.5 -*- Autoconf -*- + +# Copyright (C) 1996-2021 Free Software Foundation, Inc. + +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +m4_ifndef([AC_CONFIG_MACRO_DIRS], [m4_defun([_AM_CONFIG_MACRO_DIRS], [])m4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])]) +m4_ifndef([AC_AUTOCONF_VERSION], + [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl +m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.71],, +[m4_warning([this file was generated for autoconf 2.71. +You have another version of autoconf. It may work, but is not guaranteed to. +If you have problems, you may need to regenerate the build system entirely. +To do so, use the procedure documented by the package, typically 'autoreconf'.])]) + +# Copyright (C) 2002-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_AUTOMAKE_VERSION(VERSION) +# ---------------------------- +# Automake X.Y traces this macro to ensure aclocal.m4 has been +# generated from the m4 files accompanying Automake X.Y. +# (This private macro should not be called outside this file.) +AC_DEFUN([AM_AUTOMAKE_VERSION], +[am__api_version='1.16' +dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to +dnl require some minimum version. Point them to the right macro. +m4_if([$1], [1.16.5], [], + [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl +]) + +# _AM_AUTOCONF_VERSION(VERSION) +# ----------------------------- +# aclocal traces this macro to find the Autoconf version. +# This is a private macro too. Using m4_define simplifies +# the logic in aclocal, which can simply ignore this definition. +m4_define([_AM_AUTOCONF_VERSION], []) + +# AM_SET_CURRENT_AUTOMAKE_VERSION +# ------------------------------- +# Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced. +# This function is AC_REQUIREd by AM_INIT_AUTOMAKE. +AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], +[AM_AUTOMAKE_VERSION([1.16.5])dnl +m4_ifndef([AC_AUTOCONF_VERSION], + [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl +_AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))]) + +# AM_AUX_DIR_EXPAND -*- Autoconf -*- + +# Copyright (C) 2001-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets +# $ac_aux_dir to '$srcdir/foo'. In other projects, it is set to +# '$srcdir', '$srcdir/..', or '$srcdir/../..'. +# +# Of course, Automake must honor this variable whenever it calls a +# tool from the auxiliary directory. The problem is that $srcdir (and +# therefore $ac_aux_dir as well) can be either absolute or relative, +# depending on how configure is run. This is pretty annoying, since +# it makes $ac_aux_dir quite unusable in subdirectories: in the top +# source directory, any form will work fine, but in subdirectories a +# relative path needs to be adjusted first. +# +# $ac_aux_dir/missing +# fails when called from a subdirectory if $ac_aux_dir is relative +# $top_srcdir/$ac_aux_dir/missing +# fails if $ac_aux_dir is absolute, +# fails when called from a subdirectory in a VPATH build with +# a relative $ac_aux_dir +# +# The reason of the latter failure is that $top_srcdir and $ac_aux_dir +# are both prefixed by $srcdir. In an in-source build this is usually +# harmless because $srcdir is '.', but things will broke when you +# start a VPATH build or use an absolute $srcdir. +# +# So we could use something similar to $top_srcdir/$ac_aux_dir/missing, +# iff we strip the leading $srcdir from $ac_aux_dir. That would be: +# am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"` +# and then we would define $MISSING as +# MISSING="\${SHELL} $am_aux_dir/missing" +# This will work as long as MISSING is not called from configure, because +# unfortunately $(top_srcdir) has no meaning in configure. +# However there are other variables, like CC, which are often used in +# configure, and could therefore not use this "fixed" $ac_aux_dir. +# +# Another solution, used here, is to always expand $ac_aux_dir to an +# absolute PATH. The drawback is that using absolute paths prevent a +# configured tree to be moved without reconfiguration. + +AC_DEFUN([AM_AUX_DIR_EXPAND], +[AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl +# Expand $ac_aux_dir to an absolute path. +am_aux_dir=`cd "$ac_aux_dir" && pwd` +]) + +# AM_COND_IF -*- Autoconf -*- + +# Copyright (C) 2008-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# _AM_COND_IF +# _AM_COND_ELSE +# _AM_COND_ENDIF +# -------------- +# These macros are only used for tracing. +m4_define([_AM_COND_IF]) +m4_define([_AM_COND_ELSE]) +m4_define([_AM_COND_ENDIF]) + +# AM_COND_IF(COND, [IF-TRUE], [IF-FALSE]) +# --------------------------------------- +# If the shell condition COND is true, execute IF-TRUE, otherwise execute +# IF-FALSE. Allow automake to learn about conditional instantiating macros +# (the AC_CONFIG_FOOS). +AC_DEFUN([AM_COND_IF], +[m4_ifndef([_AM_COND_VALUE_$1], + [m4_fatal([$0: no such condition "$1"])])dnl +_AM_COND_IF([$1])dnl +if test -z "$$1_TRUE"; then : + m4_n([$2])[]dnl +m4_ifval([$3], +[_AM_COND_ELSE([$1])dnl +else + $3 +])dnl +_AM_COND_ENDIF([$1])dnl +fi[]dnl +]) + +# AM_CONDITIONAL -*- Autoconf -*- + +# Copyright (C) 1997-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_CONDITIONAL(NAME, SHELL-CONDITION) +# ------------------------------------- +# Define a conditional. +AC_DEFUN([AM_CONDITIONAL], +[AC_PREREQ([2.52])dnl + m4_if([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], + [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl +AC_SUBST([$1_TRUE])dnl +AC_SUBST([$1_FALSE])dnl +_AM_SUBST_NOTMAKE([$1_TRUE])dnl +_AM_SUBST_NOTMAKE([$1_FALSE])dnl +m4_define([_AM_COND_VALUE_$1], [$2])dnl +if $2; then + $1_TRUE= + $1_FALSE='#' +else + $1_TRUE='#' + $1_FALSE= +fi +AC_CONFIG_COMMANDS_PRE( +[if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then + AC_MSG_ERROR([[conditional "$1" was never defined. +Usually this means the macro was only invoked conditionally.]]) +fi])]) + +# Copyright (C) 1999-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + + +# There are a few dirty hacks below to avoid letting 'AC_PROG_CC' be +# written in clear, in which case automake, when reading aclocal.m4, +# will think it sees a *use*, and therefore will trigger all it's +# C support machinery. Also note that it means that autoscan, seeing +# CC etc. in the Makefile, will ask for an AC_PROG_CC use... + + +# _AM_DEPENDENCIES(NAME) +# ---------------------- +# See how the compiler implements dependency checking. +# NAME is "CC", "CXX", "OBJC", "OBJCXX", "UPC", or "GJC". +# We try a few techniques and use that to set a single cache variable. +# +# We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was +# modified to invoke _AM_DEPENDENCIES(CC); we would have a circular +# dependency, and given that the user is not expected to run this macro, +# just rely on AC_PROG_CC. +AC_DEFUN([_AM_DEPENDENCIES], +[AC_REQUIRE([AM_SET_DEPDIR])dnl +AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl +AC_REQUIRE([AM_MAKE_INCLUDE])dnl +AC_REQUIRE([AM_DEP_TRACK])dnl + +m4_if([$1], [CC], [depcc="$CC" am_compiler_list=], + [$1], [CXX], [depcc="$CXX" am_compiler_list=], + [$1], [OBJC], [depcc="$OBJC" am_compiler_list='gcc3 gcc'], + [$1], [OBJCXX], [depcc="$OBJCXX" am_compiler_list='gcc3 gcc'], + [$1], [UPC], [depcc="$UPC" am_compiler_list=], + [$1], [GCJ], [depcc="$GCJ" am_compiler_list='gcc3 gcc'], + [depcc="$$1" am_compiler_list=]) + +AC_CACHE_CHECK([dependency style of $depcc], + [am_cv_$1_dependencies_compiler_type], +[if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then + # We make a subdir and do the tests there. Otherwise we can end up + # making bogus files that we don't know about and never remove. For + # instance it was reported that on HP-UX the gcc test will end up + # making a dummy file named 'D' -- because '-MD' means "put the output + # in D". + rm -rf conftest.dir + mkdir conftest.dir + # Copy depcomp to subdir because otherwise we won't find it if we're + # using a relative directory. + cp "$am_depcomp" conftest.dir + cd conftest.dir + # We will build objects and dependencies in a subdirectory because + # it helps to detect inapplicable dependency modes. For instance + # both Tru64's cc and ICC support -MD to output dependencies as a + # side effect of compilation, but ICC will put the dependencies in + # the current directory while Tru64 will put them in the object + # directory. + mkdir sub + + am_cv_$1_dependencies_compiler_type=none + if test "$am_compiler_list" = ""; then + am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp` + fi + am__universal=false + m4_case([$1], [CC], + [case " $depcc " in #( + *\ -arch\ *\ -arch\ *) am__universal=true ;; + esac], + [CXX], + [case " $depcc " in #( + *\ -arch\ *\ -arch\ *) am__universal=true ;; + esac]) + + for depmode in $am_compiler_list; do + # Setup a source with many dependencies, because some compilers + # like to wrap large dependency lists on column 80 (with \), and + # we should not choose a depcomp mode which is confused by this. + # + # We need to recreate these files for each test, as the compiler may + # overwrite some of them when testing with obscure command lines. + # This happens at least with the AIX C compiler. + : > sub/conftest.c + for i in 1 2 3 4 5 6; do + echo '#include "conftst'$i'.h"' >> sub/conftest.c + # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with + # Solaris 10 /bin/sh. + echo '/* dummy */' > sub/conftst$i.h + done + echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf + + # We check with '-c' and '-o' for the sake of the "dashmstdout" + # mode. It turns out that the SunPro C++ compiler does not properly + # handle '-M -o', and we need to detect this. Also, some Intel + # versions had trouble with output in subdirs. + am__obj=sub/conftest.${OBJEXT-o} + am__minus_obj="-o $am__obj" + case $depmode in + gcc) + # This depmode causes a compiler race in universal mode. + test "$am__universal" = false || continue + ;; + nosideeffect) + # After this tag, mechanisms are not by side-effect, so they'll + # only be used when explicitly requested. + if test "x$enable_dependency_tracking" = xyes; then + continue + else + break + fi + ;; + msvc7 | msvc7msys | msvisualcpp | msvcmsys) + # This compiler won't grok '-c -o', but also, the minuso test has + # not run yet. These depmodes are late enough in the game, and + # so weak that their functioning should not be impacted. + am__obj=conftest.${OBJEXT-o} + am__minus_obj= + ;; + none) break ;; + esac + if depmode=$depmode \ + source=sub/conftest.c object=$am__obj \ + depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ + $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ + >/dev/null 2>conftest.err && + grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && + grep $am__obj sub/conftest.Po > /dev/null 2>&1 && + ${MAKE-make} -s -f confmf > /dev/null 2>&1; then + # icc doesn't choke on unknown options, it will just issue warnings + # or remarks (even with -Werror). So we grep stderr for any message + # that says an option was ignored or not supported. + # When given -MP, icc 7.0 and 7.1 complain thusly: + # icc: Command line warning: ignoring option '-M'; no argument required + # The diagnosis changed in icc 8.0: + # icc: Command line remark: option '-MP' not supported + if (grep 'ignoring option' conftest.err || + grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else + am_cv_$1_dependencies_compiler_type=$depmode + break + fi + fi + done + + cd .. + rm -rf conftest.dir +else + am_cv_$1_dependencies_compiler_type=none +fi +]) +AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type]) +AM_CONDITIONAL([am__fastdep$1], [ + test "x$enable_dependency_tracking" != xno \ + && test "$am_cv_$1_dependencies_compiler_type" = gcc3]) +]) + + +# AM_SET_DEPDIR +# ------------- +# Choose a directory name for dependency files. +# This macro is AC_REQUIREd in _AM_DEPENDENCIES. +AC_DEFUN([AM_SET_DEPDIR], +[AC_REQUIRE([AM_SET_LEADING_DOT])dnl +AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl +]) + + +# AM_DEP_TRACK +# ------------ +AC_DEFUN([AM_DEP_TRACK], +[AC_ARG_ENABLE([dependency-tracking], [dnl +AS_HELP_STRING( + [--enable-dependency-tracking], + [do not reject slow dependency extractors]) +AS_HELP_STRING( + [--disable-dependency-tracking], + [speeds up one-time build])]) +if test "x$enable_dependency_tracking" != xno; then + am_depcomp="$ac_aux_dir/depcomp" + AMDEPBACKSLASH='\' + am__nodep='_no' +fi +AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) +AC_SUBST([AMDEPBACKSLASH])dnl +_AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl +AC_SUBST([am__nodep])dnl +_AM_SUBST_NOTMAKE([am__nodep])dnl +]) + +# Generate code to set up dependency tracking. -*- Autoconf -*- + +# Copyright (C) 1999-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# _AM_OUTPUT_DEPENDENCY_COMMANDS +# ------------------------------ +AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS], +[{ + # Older Autoconf quotes --file arguments for eval, but not when files + # are listed without --file. Let's play safe and only enable the eval + # if we detect the quoting. + # TODO: see whether this extra hack can be removed once we start + # requiring Autoconf 2.70 or later. + AS_CASE([$CONFIG_FILES], + [*\'*], [eval set x "$CONFIG_FILES"], + [*], [set x $CONFIG_FILES]) + shift + # Used to flag and report bootstrapping failures. + am_rc=0 + for am_mf + do + # Strip MF so we end up with the name of the file. + am_mf=`AS_ECHO(["$am_mf"]) | sed -e 's/:.*$//'` + # Check whether this is an Automake generated Makefile which includes + # dependency-tracking related rules and includes. + # Grep'ing the whole file directly is not great: AIX grep has a line + # limit of 2048, but all sed's we know have understand at least 4000. + sed -n 's,^am--depfiles:.*,X,p' "$am_mf" | grep X >/dev/null 2>&1 \ + || continue + am_dirpart=`AS_DIRNAME(["$am_mf"])` + am_filepart=`AS_BASENAME(["$am_mf"])` + AM_RUN_LOG([cd "$am_dirpart" \ + && sed -e '/# am--include-marker/d' "$am_filepart" \ + | $MAKE -f - am--depfiles]) || am_rc=$? + done + if test $am_rc -ne 0; then + AC_MSG_FAILURE([Something went wrong bootstrapping makefile fragments + for automatic dependency tracking. If GNU make was not used, consider + re-running the configure script with MAKE="gmake" (or whatever is + necessary). You can also try re-running configure with the + '--disable-dependency-tracking' option to at least be able to build + the package (albeit without support for automatic dependency tracking).]) + fi + AS_UNSET([am_dirpart]) + AS_UNSET([am_filepart]) + AS_UNSET([am_mf]) + AS_UNSET([am_rc]) + rm -f conftest-deps.mk +} +])# _AM_OUTPUT_DEPENDENCY_COMMANDS + + +# AM_OUTPUT_DEPENDENCY_COMMANDS +# ----------------------------- +# This macro should only be invoked once -- use via AC_REQUIRE. +# +# This code is only required when automatic dependency tracking is enabled. +# This creates each '.Po' and '.Plo' makefile fragment that we'll need in +# order to bootstrap the dependency handling code. +AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS], +[AC_CONFIG_COMMANDS([depfiles], + [test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS], + [AMDEP_TRUE="$AMDEP_TRUE" MAKE="${MAKE-make}"])]) + +# Do all the work for Automake. -*- Autoconf -*- + +# Copyright (C) 1996-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This macro actually does too much. Some checks are only needed if +# your package does certain things. But this isn't really a big deal. + +dnl Redefine AC_PROG_CC to automatically invoke _AM_PROG_CC_C_O. +m4_define([AC_PROG_CC], +m4_defn([AC_PROG_CC]) +[_AM_PROG_CC_C_O +]) + +# AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE]) +# AM_INIT_AUTOMAKE([OPTIONS]) +# ----------------------------------------------- +# The call with PACKAGE and VERSION arguments is the old style +# call (pre autoconf-2.50), which is being phased out. PACKAGE +# and VERSION should now be passed to AC_INIT and removed from +# the call to AM_INIT_AUTOMAKE. +# We support both call styles for the transition. After +# the next Automake release, Autoconf can make the AC_INIT +# arguments mandatory, and then we can depend on a new Autoconf +# release and drop the old call support. +AC_DEFUN([AM_INIT_AUTOMAKE], +[AC_PREREQ([2.65])dnl +m4_ifdef([_$0_ALREADY_INIT], + [m4_fatal([$0 expanded multiple times +]m4_defn([_$0_ALREADY_INIT]))], + [m4_define([_$0_ALREADY_INIT], m4_expansion_stack)])dnl +dnl Autoconf wants to disallow AM_ names. We explicitly allow +dnl the ones we care about. +m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl +AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl +AC_REQUIRE([AC_PROG_INSTALL])dnl +if test "`cd $srcdir && pwd`" != "`pwd`"; then + # Use -I$(srcdir) only when $(srcdir) != ., so that make's output + # is not polluted with repeated "-I." + AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl + # test to see if srcdir already configured + if test -f $srcdir/config.status; then + AC_MSG_ERROR([source directory already configured; run "make distclean" there first]) + fi +fi + +# test whether we have cygpath +if test -z "$CYGPATH_W"; then + if (cygpath --version) >/dev/null 2>/dev/null; then + CYGPATH_W='cygpath -w' + else + CYGPATH_W=echo + fi +fi +AC_SUBST([CYGPATH_W]) + +# Define the identity of the package. +dnl Distinguish between old-style and new-style calls. +m4_ifval([$2], +[AC_DIAGNOSE([obsolete], + [$0: two- and three-arguments forms are deprecated.]) +m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl + AC_SUBST([PACKAGE], [$1])dnl + AC_SUBST([VERSION], [$2])], +[_AM_SET_OPTIONS([$1])dnl +dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT. +m4_if( + m4_ifset([AC_PACKAGE_NAME], [ok]):m4_ifset([AC_PACKAGE_VERSION], [ok]), + [ok:ok],, + [m4_fatal([AC_INIT should be called with package and version arguments])])dnl + AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl + AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl + +_AM_IF_OPTION([no-define],, +[AC_DEFINE_UNQUOTED([PACKAGE], ["$PACKAGE"], [Name of package]) + AC_DEFINE_UNQUOTED([VERSION], ["$VERSION"], [Version number of package])])dnl + +# Some tools Automake needs. +AC_REQUIRE([AM_SANITY_CHECK])dnl +AC_REQUIRE([AC_ARG_PROGRAM])dnl +AM_MISSING_PROG([ACLOCAL], [aclocal-${am__api_version}]) +AM_MISSING_PROG([AUTOCONF], [autoconf]) +AM_MISSING_PROG([AUTOMAKE], [automake-${am__api_version}]) +AM_MISSING_PROG([AUTOHEADER], [autoheader]) +AM_MISSING_PROG([MAKEINFO], [makeinfo]) +AC_REQUIRE([AM_PROG_INSTALL_SH])dnl +AC_REQUIRE([AM_PROG_INSTALL_STRIP])dnl +AC_REQUIRE([AC_PROG_MKDIR_P])dnl +# For better backward compatibility. To be removed once Automake 1.9.x +# dies out for good. For more background, see: +# +# +AC_SUBST([mkdir_p], ['$(MKDIR_P)']) +# We need awk for the "check" target (and possibly the TAP driver). The +# system "awk" is bad on some platforms. +AC_REQUIRE([AC_PROG_AWK])dnl +AC_REQUIRE([AC_PROG_MAKE_SET])dnl +AC_REQUIRE([AM_SET_LEADING_DOT])dnl +_AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])], + [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], + [_AM_PROG_TAR([v7])])]) +_AM_IF_OPTION([no-dependencies],, +[AC_PROVIDE_IFELSE([AC_PROG_CC], + [_AM_DEPENDENCIES([CC])], + [m4_define([AC_PROG_CC], + m4_defn([AC_PROG_CC])[_AM_DEPENDENCIES([CC])])])dnl +AC_PROVIDE_IFELSE([AC_PROG_CXX], + [_AM_DEPENDENCIES([CXX])], + [m4_define([AC_PROG_CXX], + m4_defn([AC_PROG_CXX])[_AM_DEPENDENCIES([CXX])])])dnl +AC_PROVIDE_IFELSE([AC_PROG_OBJC], + [_AM_DEPENDENCIES([OBJC])], + [m4_define([AC_PROG_OBJC], + m4_defn([AC_PROG_OBJC])[_AM_DEPENDENCIES([OBJC])])])dnl +AC_PROVIDE_IFELSE([AC_PROG_OBJCXX], + [_AM_DEPENDENCIES([OBJCXX])], + [m4_define([AC_PROG_OBJCXX], + m4_defn([AC_PROG_OBJCXX])[_AM_DEPENDENCIES([OBJCXX])])])dnl +]) +# Variables for tags utilities; see am/tags.am +if test -z "$CTAGS"; then + CTAGS=ctags +fi +AC_SUBST([CTAGS]) +if test -z "$ETAGS"; then + ETAGS=etags +fi +AC_SUBST([ETAGS]) +if test -z "$CSCOPE"; then + CSCOPE=cscope +fi +AC_SUBST([CSCOPE]) + +AC_REQUIRE([AM_SILENT_RULES])dnl +dnl The testsuite driver may need to know about EXEEXT, so add the +dnl 'am__EXEEXT' conditional if _AM_COMPILER_EXEEXT was seen. This +dnl macro is hooked onto _AC_COMPILER_EXEEXT early, see below. +AC_CONFIG_COMMANDS_PRE(dnl +[m4_provide_if([_AM_COMPILER_EXEEXT], + [AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"])])])dnl + +# POSIX will say in a future version that running "rm -f" with no argument +# is OK; and we want to be able to make that assumption in our Makefile +# recipes. So use an aggressive probe to check that the usage we want is +# actually supported "in the wild" to an acceptable degree. +# See automake bug#10828. +# To make any issue more visible, cause the running configure to be aborted +# by default if the 'rm' program in use doesn't match our expectations; the +# user can still override this though. +if rm -f && rm -fr && rm -rf; then : OK; else + cat >&2 <<'END' +Oops! + +Your 'rm' program seems unable to run without file operands specified +on the command line, even when the '-f' option is present. This is contrary +to the behaviour of most rm programs out there, and not conforming with +the upcoming POSIX standard: + +Please tell bug-automake@gnu.org about your system, including the value +of your $PATH and any error possibly output before this message. This +can help us improve future automake versions. + +END + if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then + echo 'Configuration will proceed anyway, since you have set the' >&2 + echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2 + echo >&2 + else + cat >&2 <<'END' +Aborting the configuration process, to ensure you take notice of the issue. + +You can download and install GNU coreutils to get an 'rm' implementation +that behaves properly: . + +If you want to complete the configuration process using your problematic +'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM +to "yes", and re-run configure. + +END + AC_MSG_ERROR([Your 'rm' program is bad, sorry.]) + fi +fi +dnl The trailing newline in this macro's definition is deliberate, for +dnl backward compatibility and to allow trailing 'dnl'-style comments +dnl after the AM_INIT_AUTOMAKE invocation. See automake bug#16841. +]) + +dnl Hook into '_AC_COMPILER_EXEEXT' early to learn its expansion. Do not +dnl add the conditional right here, as _AC_COMPILER_EXEEXT may be further +dnl mangled by Autoconf and run in a shell conditional statement. +m4_define([_AC_COMPILER_EXEEXT], +m4_defn([_AC_COMPILER_EXEEXT])[m4_provide([_AM_COMPILER_EXEEXT])]) + +# When config.status generates a header, we must update the stamp-h file. +# This file resides in the same directory as the config header +# that is generated. The stamp files are numbered to have different names. + +# Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the +# loop where config.status creates the headers, so we can generate +# our stamp files there. +AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK], +[# Compute $1's index in $config_headers. +_am_arg=$1 +_am_stamp_count=1 +for _am_header in $config_headers :; do + case $_am_header in + $_am_arg | $_am_arg:* ) + break ;; + * ) + _am_stamp_count=`expr $_am_stamp_count + 1` ;; + esac +done +echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count]) + +# Copyright (C) 2001-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_PROG_INSTALL_SH +# ------------------ +# Define $install_sh. +AC_DEFUN([AM_PROG_INSTALL_SH], +[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl +if test x"${install_sh+set}" != xset; then + case $am_aux_dir in + *\ * | *\ *) + install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; + *) + install_sh="\${SHELL} $am_aux_dir/install-sh" + esac +fi +AC_SUBST([install_sh])]) + +# Copyright (C) 2003-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# Check whether the underlying file-system supports filenames +# with a leading dot. For instance MS-DOS doesn't. +AC_DEFUN([AM_SET_LEADING_DOT], +[rm -rf .tst 2>/dev/null +mkdir .tst 2>/dev/null +if test -d .tst; then + am__leading_dot=. +else + am__leading_dot=_ +fi +rmdir .tst 2>/dev/null +AC_SUBST([am__leading_dot])]) + +# Add --enable-maintainer-mode option to configure. -*- Autoconf -*- +# From Jim Meyering + +# Copyright (C) 1996-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_MAINTAINER_MODE([DEFAULT-MODE]) +# ---------------------------------- +# Control maintainer-specific portions of Makefiles. +# Default is to disable them, unless 'enable' is passed literally. +# For symmetry, 'disable' may be passed as well. Anyway, the user +# can override the default with the --enable/--disable switch. +AC_DEFUN([AM_MAINTAINER_MODE], +[m4_case(m4_default([$1], [disable]), + [enable], [m4_define([am_maintainer_other], [disable])], + [disable], [m4_define([am_maintainer_other], [enable])], + [m4_define([am_maintainer_other], [enable]) + m4_warn([syntax], [unexpected argument to AM@&t@_MAINTAINER_MODE: $1])]) +AC_MSG_CHECKING([whether to enable maintainer-specific portions of Makefiles]) + dnl maintainer-mode's default is 'disable' unless 'enable' is passed + AC_ARG_ENABLE([maintainer-mode], + [AS_HELP_STRING([--]am_maintainer_other[-maintainer-mode], + am_maintainer_other[ make rules and dependencies not useful + (and sometimes confusing) to the casual installer])], + [USE_MAINTAINER_MODE=$enableval], + [USE_MAINTAINER_MODE=]m4_if(am_maintainer_other, [enable], [no], [yes])) + AC_MSG_RESULT([$USE_MAINTAINER_MODE]) + AM_CONDITIONAL([MAINTAINER_MODE], [test $USE_MAINTAINER_MODE = yes]) + MAINT=$MAINTAINER_MODE_TRUE + AC_SUBST([MAINT])dnl +] +) + +# Check to see how 'make' treats includes. -*- Autoconf -*- + +# Copyright (C) 2001-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_MAKE_INCLUDE() +# ----------------- +# Check whether make has an 'include' directive that can support all +# the idioms we need for our automatic dependency tracking code. +AC_DEFUN([AM_MAKE_INCLUDE], +[AC_MSG_CHECKING([whether ${MAKE-make} supports the include directive]) +cat > confinc.mk << 'END' +am__doit: + @echo this is the am__doit target >confinc.out +.PHONY: am__doit +END +am__include="#" +am__quote= +# BSD make does it like this. +echo '.include "confinc.mk" # ignored' > confmf.BSD +# Other make implementations (GNU, Solaris 10, AIX) do it like this. +echo 'include confinc.mk # ignored' > confmf.GNU +_am_result=no +for s in GNU BSD; do + AM_RUN_LOG([${MAKE-make} -f confmf.$s && cat confinc.out]) + AS_CASE([$?:`cat confinc.out 2>/dev/null`], + ['0:this is the am__doit target'], + [AS_CASE([$s], + [BSD], [am__include='.include' am__quote='"'], + [am__include='include' am__quote=''])]) + if test "$am__include" != "#"; then + _am_result="yes ($s style)" + break + fi +done +rm -f confinc.* confmf.* +AC_MSG_RESULT([${_am_result}]) +AC_SUBST([am__include])]) +AC_SUBST([am__quote])]) + +# Fake the existence of programs that GNU maintainers use. -*- Autoconf -*- + +# Copyright (C) 1997-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_MISSING_PROG(NAME, PROGRAM) +# ------------------------------ +AC_DEFUN([AM_MISSING_PROG], +[AC_REQUIRE([AM_MISSING_HAS_RUN]) +$1=${$1-"${am_missing_run}$2"} +AC_SUBST($1)]) + +# AM_MISSING_HAS_RUN +# ------------------ +# Define MISSING if not defined so far and test if it is modern enough. +# If it is, set am_missing_run to use it, otherwise, to nothing. +AC_DEFUN([AM_MISSING_HAS_RUN], +[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl +AC_REQUIRE_AUX_FILE([missing])dnl +if test x"${MISSING+set}" != xset; then + MISSING="\${SHELL} '$am_aux_dir/missing'" +fi +# Use eval to expand $SHELL +if eval "$MISSING --is-lightweight"; then + am_missing_run="$MISSING " +else + am_missing_run= + AC_MSG_WARN(['missing' script is too old or missing]) +fi +]) + +# Helper functions for option handling. -*- Autoconf -*- + +# Copyright (C) 2001-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# _AM_MANGLE_OPTION(NAME) +# ----------------------- +AC_DEFUN([_AM_MANGLE_OPTION], +[[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])]) + +# _AM_SET_OPTION(NAME) +# -------------------- +# Set option NAME. Presently that only means defining a flag for this option. +AC_DEFUN([_AM_SET_OPTION], +[m4_define(_AM_MANGLE_OPTION([$1]), [1])]) + +# _AM_SET_OPTIONS(OPTIONS) +# ------------------------ +# OPTIONS is a space-separated list of Automake options. +AC_DEFUN([_AM_SET_OPTIONS], +[m4_foreach_w([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])]) + +# _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET]) +# ------------------------------------------- +# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. +AC_DEFUN([_AM_IF_OPTION], +[m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])]) + +# Copyright (C) 1999-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# _AM_PROG_CC_C_O +# --------------- +# Like AC_PROG_CC_C_O, but changed for automake. We rewrite AC_PROG_CC +# to automatically call this. +AC_DEFUN([_AM_PROG_CC_C_O], +[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl +AC_REQUIRE_AUX_FILE([compile])dnl +AC_LANG_PUSH([C])dnl +AC_CACHE_CHECK( + [whether $CC understands -c and -o together], + [am_cv_prog_cc_c_o], + [AC_LANG_CONFTEST([AC_LANG_PROGRAM([])]) + # Make sure it works both with $CC and with simple cc. + # Following AC_PROG_CC_C_O, we do the test twice because some + # compilers refuse to overwrite an existing .o file with -o, + # though they will create one. + am_cv_prog_cc_c_o=yes + for am_i in 1 2; do + if AM_RUN_LOG([$CC -c conftest.$ac_ext -o conftest2.$ac_objext]) \ + && test -f conftest2.$ac_objext; then + : OK + else + am_cv_prog_cc_c_o=no + break + fi + done + rm -f core conftest* + unset am_i]) +if test "$am_cv_prog_cc_c_o" != yes; then + # Losing compiler, so override with the script. + # FIXME: It is wrong to rewrite CC. + # But if we don't then we get into trouble of one sort or another. + # A longer-term fix would be to have automake use am__CC in this case, + # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" + CC="$am_aux_dir/compile $CC" +fi +AC_LANG_POP([C])]) + +# For backward compatibility. +AC_DEFUN_ONCE([AM_PROG_CC_C_O], [AC_REQUIRE([AC_PROG_CC])]) + +# Copyright (C) 2001-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_RUN_LOG(COMMAND) +# ------------------- +# Run COMMAND, save the exit status in ac_status, and log it. +# (This has been adapted from Autoconf's _AC_RUN_LOG macro.) +AC_DEFUN([AM_RUN_LOG], +[{ echo "$as_me:$LINENO: $1" >&AS_MESSAGE_LOG_FD + ($1) >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD + (exit $ac_status); }]) + +# Check to make sure that the build environment is sane. -*- Autoconf -*- + +# Copyright (C) 1996-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_SANITY_CHECK +# --------------- +AC_DEFUN([AM_SANITY_CHECK], +[AC_MSG_CHECKING([whether build environment is sane]) +# Reject unsafe characters in $srcdir or the absolute working directory +# name. Accept space and tab only in the latter. +am_lf=' +' +case `pwd` in + *[[\\\"\#\$\&\'\`$am_lf]]*) + AC_MSG_ERROR([unsafe absolute working directory name]);; +esac +case $srcdir in + *[[\\\"\#\$\&\'\`$am_lf\ \ ]]*) + AC_MSG_ERROR([unsafe srcdir value: '$srcdir']);; +esac + +# Do 'set' in a subshell so we don't clobber the current shell's +# arguments. Must try -L first in case configure is actually a +# symlink; some systems play weird games with the mod time of symlinks +# (eg FreeBSD returns the mod time of the symlink's containing +# directory). +if ( + am_has_slept=no + for am_try in 1 2; do + echo "timestamp, slept: $am_has_slept" > conftest.file + set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` + if test "$[*]" = "X"; then + # -L didn't work. + set X `ls -t "$srcdir/configure" conftest.file` + fi + if test "$[*]" != "X $srcdir/configure conftest.file" \ + && test "$[*]" != "X conftest.file $srcdir/configure"; then + + # If neither matched, then we have a broken ls. This can happen + # if, for instance, CONFIG_SHELL is bash and it inherits a + # broken ls alias from the environment. This has actually + # happened. Such a system could not be considered "sane". + AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken + alias in your environment]) + fi + if test "$[2]" = conftest.file || test $am_try -eq 2; then + break + fi + # Just in case. + sleep 1 + am_has_slept=yes + done + test "$[2]" = conftest.file + ) +then + # Ok. + : +else + AC_MSG_ERROR([newly created file is older than distributed files! +Check your system clock]) +fi +AC_MSG_RESULT([yes]) +# If we didn't sleep, we still need to ensure time stamps of config.status and +# generated files are strictly newer. +am_sleep_pid= +if grep 'slept: no' conftest.file >/dev/null 2>&1; then + ( sleep 1 ) & + am_sleep_pid=$! +fi +AC_CONFIG_COMMANDS_PRE( + [AC_MSG_CHECKING([that generated files are newer than configure]) + if test -n "$am_sleep_pid"; then + # Hide warnings about reused PIDs. + wait $am_sleep_pid 2>/dev/null + fi + AC_MSG_RESULT([done])]) +rm -f conftest.file +]) + +# Copyright (C) 2009-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_SILENT_RULES([DEFAULT]) +# -------------------------- +# Enable less verbose build rules; with the default set to DEFAULT +# ("yes" being less verbose, "no" or empty being verbose). +AC_DEFUN([AM_SILENT_RULES], +[AC_ARG_ENABLE([silent-rules], [dnl +AS_HELP_STRING( + [--enable-silent-rules], + [less verbose build output (undo: "make V=1")]) +AS_HELP_STRING( + [--disable-silent-rules], + [verbose build output (undo: "make V=0")])dnl +]) +case $enable_silent_rules in @%:@ ((( + yes) AM_DEFAULT_VERBOSITY=0;; + no) AM_DEFAULT_VERBOSITY=1;; + *) AM_DEFAULT_VERBOSITY=m4_if([$1], [yes], [0], [1]);; +esac +dnl +dnl A few 'make' implementations (e.g., NonStop OS and NextStep) +dnl do not support nested variable expansions. +dnl See automake bug#9928 and bug#10237. +am_make=${MAKE-make} +AC_CACHE_CHECK([whether $am_make supports nested variables], + [am_cv_make_support_nested_variables], + [if AS_ECHO([['TRUE=$(BAR$(V)) +BAR0=false +BAR1=true +V=1 +am__doit: + @$(TRUE) +.PHONY: am__doit']]) | $am_make -f - >/dev/null 2>&1; then + am_cv_make_support_nested_variables=yes +else + am_cv_make_support_nested_variables=no +fi]) +if test $am_cv_make_support_nested_variables = yes; then + dnl Using '$V' instead of '$(V)' breaks IRIX make. + AM_V='$(V)' + AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' +else + AM_V=$AM_DEFAULT_VERBOSITY + AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY +fi +AC_SUBST([AM_V])dnl +AM_SUBST_NOTMAKE([AM_V])dnl +AC_SUBST([AM_DEFAULT_V])dnl +AM_SUBST_NOTMAKE([AM_DEFAULT_V])dnl +AC_SUBST([AM_DEFAULT_VERBOSITY])dnl +AM_BACKSLASH='\' +AC_SUBST([AM_BACKSLASH])dnl +_AM_SUBST_NOTMAKE([AM_BACKSLASH])dnl +]) + +# Copyright (C) 2001-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_PROG_INSTALL_STRIP +# --------------------- +# One issue with vendor 'install' (even GNU) is that you can't +# specify the program used to strip binaries. This is especially +# annoying in cross-compiling environments, where the build's strip +# is unlikely to handle the host's binaries. +# Fortunately install-sh will honor a STRIPPROG variable, so we +# always use install-sh in "make install-strip", and initialize +# STRIPPROG with the value of the STRIP variable (set by the user). +AC_DEFUN([AM_PROG_INSTALL_STRIP], +[AC_REQUIRE([AM_PROG_INSTALL_SH])dnl +# Installed binaries are usually stripped using 'strip' when the user +# run "make install-strip". However 'strip' might not be the right +# tool to use in cross-compilation environments, therefore Automake +# will honor the 'STRIP' environment variable to overrule this program. +dnl Don't test for $cross_compiling = yes, because it might be 'maybe'. +if test "$cross_compiling" != no; then + AC_CHECK_TOOL([STRIP], [strip], :) +fi +INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" +AC_SUBST([INSTALL_STRIP_PROGRAM])]) + +# Copyright (C) 2006-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# _AM_SUBST_NOTMAKE(VARIABLE) +# --------------------------- +# Prevent Automake from outputting VARIABLE = @VARIABLE@ in Makefile.in. +# This macro is traced by Automake. +AC_DEFUN([_AM_SUBST_NOTMAKE]) + +# AM_SUBST_NOTMAKE(VARIABLE) +# -------------------------- +# Public sister of _AM_SUBST_NOTMAKE. +AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)]) + +# Check how to create a tarball. -*- Autoconf -*- + +# Copyright (C) 2004-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# _AM_PROG_TAR(FORMAT) +# -------------------- +# Check how to create a tarball in format FORMAT. +# FORMAT should be one of 'v7', 'ustar', or 'pax'. +# +# Substitute a variable $(am__tar) that is a command +# writing to stdout a FORMAT-tarball containing the directory +# $tardir. +# tardir=directory && $(am__tar) > result.tar +# +# Substitute a variable $(am__untar) that extract such +# a tarball read from stdin. +# $(am__untar) < result.tar +# +AC_DEFUN([_AM_PROG_TAR], +[# Always define AMTAR for backward compatibility. Yes, it's still used +# in the wild :-( We should find a proper way to deprecate it ... +AC_SUBST([AMTAR], ['$${TAR-tar}']) + +# We'll loop over all known methods to create a tar archive until one works. +_am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none' + +m4_if([$1], [v7], + [am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'], + + [m4_case([$1], + [ustar], + [# The POSIX 1988 'ustar' format is defined with fixed-size fields. + # There is notably a 21 bits limit for the UID and the GID. In fact, + # the 'pax' utility can hang on bigger UID/GID (see automake bug#8343 + # and bug#13588). + am_max_uid=2097151 # 2^21 - 1 + am_max_gid=$am_max_uid + # The $UID and $GID variables are not portable, so we need to resort + # to the POSIX-mandated id(1) utility. Errors in the 'id' calls + # below are definitely unexpected, so allow the users to see them + # (that is, avoid stderr redirection). + am_uid=`id -u || echo unknown` + am_gid=`id -g || echo unknown` + AC_MSG_CHECKING([whether UID '$am_uid' is supported by ustar format]) + if test $am_uid -le $am_max_uid; then + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + _am_tools=none + fi + AC_MSG_CHECKING([whether GID '$am_gid' is supported by ustar format]) + if test $am_gid -le $am_max_gid; then + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + _am_tools=none + fi], + + [pax], + [], + + [m4_fatal([Unknown tar format])]) + + AC_MSG_CHECKING([how to create a $1 tar archive]) + + # Go ahead even if we have the value already cached. We do so because we + # need to set the values for the 'am__tar' and 'am__untar' variables. + _am_tools=${am_cv_prog_tar_$1-$_am_tools} + + for _am_tool in $_am_tools; do + case $_am_tool in + gnutar) + for _am_tar in tar gnutar gtar; do + AM_RUN_LOG([$_am_tar --version]) && break + done + am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"' + am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"' + am__untar="$_am_tar -xf -" + ;; + plaintar) + # Must skip GNU tar: if it does not support --format= it doesn't create + # ustar tarball either. + (tar --version) >/dev/null 2>&1 && continue + am__tar='tar chf - "$$tardir"' + am__tar_='tar chf - "$tardir"' + am__untar='tar xf -' + ;; + pax) + am__tar='pax -L -x $1 -w "$$tardir"' + am__tar_='pax -L -x $1 -w "$tardir"' + am__untar='pax -r' + ;; + cpio) + am__tar='find "$$tardir" -print | cpio -o -H $1 -L' + am__tar_='find "$tardir" -print | cpio -o -H $1 -L' + am__untar='cpio -i -H $1 -d' + ;; + none) + am__tar=false + am__tar_=false + am__untar=false + ;; + esac + + # If the value was cached, stop now. We just wanted to have am__tar + # and am__untar set. + test -n "${am_cv_prog_tar_$1}" && break + + # tar/untar a dummy directory, and stop if the command works. + rm -rf conftest.dir + mkdir conftest.dir + echo GrepMe > conftest.dir/file + AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar]) + rm -rf conftest.dir + if test -s conftest.tar; then + AM_RUN_LOG([$am__untar /dev/null 2>&1 && break + fi + done + rm -rf conftest.dir + + AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool]) + AC_MSG_RESULT([$am_cv_prog_tar_$1])]) + +AC_SUBST([am__tar]) +AC_SUBST([am__untar]) +]) # _AM_PROG_TAR + +m4_include([m4/curl-amissl.m4]) +m4_include([m4/curl-bearssl.m4]) +m4_include([m4/curl-compilers.m4]) +m4_include([m4/curl-confopts.m4]) +m4_include([m4/curl-functions.m4]) +m4_include([m4/curl-gnutls.m4]) +m4_include([m4/curl-mbedtls.m4]) +m4_include([m4/curl-openssl.m4]) +m4_include([m4/curl-override.m4]) +m4_include([m4/curl-reentrant.m4]) +m4_include([m4/curl-rustls.m4]) +m4_include([m4/curl-schannel.m4]) +m4_include([m4/curl-sectransp.m4]) +m4_include([m4/curl-sysconfig.m4]) +m4_include([m4/curl-wolfssl.m4]) +m4_include([m4/libtool.m4]) +m4_include([m4/ltoptions.m4]) +m4_include([m4/ltsugar.m4]) +m4_include([m4/ltversion.m4]) +m4_include([m4/lt~obsolete.m4]) +m4_include([m4/xc-am-iface.m4]) +m4_include([m4/xc-cc-check.m4]) +m4_include([m4/xc-lt-iface.m4]) +m4_include([m4/xc-translit.m4]) +m4_include([m4/xc-val-flgs.m4]) +m4_include([m4/zz40-xc-ovr.m4]) +m4_include([m4/zz50-xc-ovr.m4]) +m4_include([m4/zz60-xc-ovr.m4]) +m4_include([acinclude.m4]) diff --git a/third_party/curl/buildconf b/third_party/curl/buildconf new file mode 100755 index 0000000..ee6a280 --- /dev/null +++ b/third_party/curl/buildconf @@ -0,0 +1,8 @@ +#!/bin/sh +# +# Copyright (C) Daniel Stenberg, , et al. +# +# SPDX-License-Identifier: curl + +echo "*** Do not use buildconf. Instead, just use: autoreconf -fi" >&2 +exec ${AUTORECONF:-autoreconf} -fi "${@}" diff --git a/third_party/curl/buildconf.bat b/third_party/curl/buildconf.bat new file mode 100644 index 0000000..bef4874 --- /dev/null +++ b/third_party/curl/buildconf.bat @@ -0,0 +1,265 @@ +@echo off +rem *************************************************************************** +rem * _ _ ____ _ +rem * Project ___| | | | _ \| | +rem * / __| | | | |_) | | +rem * | (__| |_| | _ <| |___ +rem * \___|\___/|_| \_\_____| +rem * +rem * Copyright (C) Daniel Stenberg, , et al. +rem * +rem * This software is licensed as described in the file COPYING, which +rem * you should have received as part of this distribution. The terms +rem * are also available at https://curl.se/docs/copyright.html. +rem * +rem * You may opt to use, copy, modify, merge, publish, distribute and/or sell +rem * copies of the Software, and permit persons to whom the Software is +rem * furnished to do so, under the terms of the COPYING file. +rem * +rem * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +rem * KIND, either express or implied. +rem * +rem * SPDX-License-Identifier: curl +rem * +rem *************************************************************************** + +rem NOTES +rem +rem This batch file must be used to set up a git tree to build on systems where +rem there is no autotools support (i.e. DOS and Windows). +rem + +:begin + rem Set our variables + if "%OS%" == "Windows_NT" setlocal + set MODE=GENERATE + + rem Switch to this batch file's directory + cd /d "%~0\.." 1>NUL 2>&1 + + rem Check we are running from a curl git repository + if not exist GIT-INFO.md goto norepo + +:parseArgs + if "%~1" == "" goto start + + if /i "%~1" == "-clean" ( + set MODE=CLEAN + ) else if /i "%~1" == "-?" ( + goto syntax + ) else if /i "%~1" == "-h" ( + goto syntax + ) else if /i "%~1" == "-help" ( + goto syntax + ) else ( + goto unknown + ) + + shift & goto parseArgs + +:start + if "%MODE%" == "GENERATE" ( + echo. + echo Generating prerequisite files + + call :generate + if errorlevel 3 goto nogenhugehelp + if errorlevel 2 goto nogenmakefile + if errorlevel 1 goto warning + + ) else ( + echo. + echo Removing prerequisite files + + call :clean + if errorlevel 2 goto nocleanhugehelp + if errorlevel 1 goto nocleanmakefile + ) + + goto success + +rem Main generate function. +rem +rem Returns: +rem +rem 0 - success +rem 1 - success with simplified tool_hugehelp.c +rem 2 - failed to generate Makefile +rem 3 - failed to generate tool_hugehelp.c +rem +:generate + if "%OS%" == "Windows_NT" setlocal + set BASIC_HUGEHELP=0 + + rem Create Makefile + echo * %CD%\Makefile + if exist Makefile.dist ( + copy /Y Makefile.dist Makefile 1>NUL 2>&1 + if errorlevel 1 ( + if "%OS%" == "Windows_NT" endlocal + exit /B 2 + ) + ) + + rem Create tool_hugehelp.c + echo * %CD%\src\tool_hugehelp.c + call :genHugeHelp + if errorlevel 2 ( + if "%OS%" == "Windows_NT" endlocal + exit /B 3 + ) + if errorlevel 1 ( + set BASIC_HUGEHELP=1 + ) + cmd /c exit 0 + + if "%BASIC_HUGEHELP%" == "1" ( + if "%OS%" == "Windows_NT" endlocal + exit /B 1 + ) + + if "%OS%" == "Windows_NT" endlocal + exit /B 0 + +rem Main clean function. +rem +rem Returns: +rem +rem 0 - success +rem 1 - failed to clean Makefile +rem 2 - failed to clean tool_hugehelp.c +rem +:clean + rem Remove Makefile + echo * %CD%\Makefile + if exist Makefile ( + del Makefile 2>NUL + if exist Makefile ( + exit /B 1 + ) + ) + + rem Remove tool_hugehelp.c + echo * %CD%\src\tool_hugehelp.c + if exist src\tool_hugehelp.c ( + del src\tool_hugehelp.c 2>NUL + if exist src\tool_hugehelp.c ( + exit /B 2 + ) + ) + + exit /B + +rem Function to generate src\tool_hugehelp.c +rem +rem Returns: +rem +rem 0 - full tool_hugehelp.c generated +rem 1 - simplified tool_hugehelp.c +rem 2 - failure +rem +:genHugeHelp + if "%OS%" == "Windows_NT" setlocal + set LC_ALL=C + set BASIC=1 + + if exist src\tool_hugehelp.c.cvs ( + copy /Y src\tool_hugehelp.c.cvs src\tool_hugehelp.c 1>NUL 2>&1 + ) else ( + echo #include "tool_setup.h"> src\tool_hugehelp.c + echo #include "tool_hugehelp.h">> src\tool_hugehelp.c + echo.>> src\tool_hugehelp.c + echo void hugehelp(void^)>> src\tool_hugehelp.c + echo {>> src\tool_hugehelp.c + echo #ifdef USE_MANUAL>> src\tool_hugehelp.c + echo fputs("Built-in manual not included\n", stdout^);>> src\tool_hugehelp.c + echo #endif>> src\tool_hugehelp.c + echo }>> src\tool_hugehelp.c + ) + + findstr "/C:void hugehelp(void)" src\tool_hugehelp.c 1>NUL 2>&1 + if errorlevel 1 ( + if "%OS%" == "Windows_NT" endlocal + exit /B 2 + ) + + if "%BASIC%" == "1" ( + if "%OS%" == "Windows_NT" endlocal + exit /B 1 + ) + + if "%OS%" == "Windows_NT" endlocal + exit /B 0 + +rem Function to clean-up local variables under DOS, Windows 3.x and +rem Windows 9x as setlocal isn't available until Windows NT +rem +:dosCleanup + set MODE= + set BASIC_HUGEHELP= + set LC_ALL + set BASIC= + + exit /B + +:syntax + rem Display the help + echo. + echo Usage: buildconf [-clean] + echo. + echo -clean - Removes the files + goto error + +:unknown + echo. + echo Error: Unknown argument '%1' + goto error + +:norepo + echo. + echo Error: This batch file should only be used with a curl git repository + goto error + +:nogenmakefile + echo. + echo Error: Unable to generate Makefile + goto error + +:nogenhugehelp + echo. + echo Error: Unable to generate src\tool_hugehelp.c + goto error + +:nocleanmakefile + echo. + echo Error: Unable to clean Makefile + goto error + +:nocleanhugehelp + echo. + echo Error: Unable to clean src\tool_hugehelp.c + goto error + +:warning + echo. + echo Warning: The curl manual could not be integrated in the source. This means when + echo you build curl the manual will not be available (curl --manual^). Integration of + echo the manual is not required and a summary of the options will still be available + echo (curl --help^). To integrate the manual build with configure or cmake. + goto success + +:error + if "%OS%" == "Windows_NT" ( + endlocal + ) else ( + call :dosCleanup + ) + exit /B 1 + +:success + if "%OS%" == "Windows_NT" ( + endlocal + ) else ( + call :dosCleanup + ) + exit /B 0 diff --git a/third_party/curl/compile b/third_party/curl/compile new file mode 100755 index 0000000..df363c8 --- /dev/null +++ b/third_party/curl/compile @@ -0,0 +1,348 @@ +#! /bin/sh +# Wrapper for compilers which do not understand '-c -o'. + +scriptversion=2018-03-07.03; # UTC + +# Copyright (C) 1999-2021 Free Software Foundation, Inc. +# Written by Tom Tromey . +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# This file is maintained in Automake, please report +# bugs to or send patches to +# . + +nl=' +' + +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent tools from complaining about whitespace usage. +IFS=" "" $nl" + +file_conv= + +# func_file_conv build_file lazy +# Convert a $build file to $host form and store it in $file +# Currently only supports Windows hosts. If the determined conversion +# type is listed in (the comma separated) LAZY, no conversion will +# take place. +func_file_conv () +{ + file=$1 + case $file in + / | /[!/]*) # absolute file, and not a UNC file + if test -z "$file_conv"; then + # lazily determine how to convert abs files + case `uname -s` in + MINGW*) + file_conv=mingw + ;; + CYGWIN* | MSYS*) + file_conv=cygwin + ;; + *) + file_conv=wine + ;; + esac + fi + case $file_conv/,$2, in + *,$file_conv,*) + ;; + mingw/*) + file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'` + ;; + cygwin/* | msys/*) + file=`cygpath -m "$file" || echo "$file"` + ;; + wine/*) + file=`winepath -w "$file" || echo "$file"` + ;; + esac + ;; + esac +} + +# func_cl_dashL linkdir +# Make cl look for libraries in LINKDIR +func_cl_dashL () +{ + func_file_conv "$1" + if test -z "$lib_path"; then + lib_path=$file + else + lib_path="$lib_path;$file" + fi + linker_opts="$linker_opts -LIBPATH:$file" +} + +# func_cl_dashl library +# Do a library search-path lookup for cl +func_cl_dashl () +{ + lib=$1 + found=no + save_IFS=$IFS + IFS=';' + for dir in $lib_path $LIB + do + IFS=$save_IFS + if $shared && test -f "$dir/$lib.dll.lib"; then + found=yes + lib=$dir/$lib.dll.lib + break + fi + if test -f "$dir/$lib.lib"; then + found=yes + lib=$dir/$lib.lib + break + fi + if test -f "$dir/lib$lib.a"; then + found=yes + lib=$dir/lib$lib.a + break + fi + done + IFS=$save_IFS + + if test "$found" != yes; then + lib=$lib.lib + fi +} + +# func_cl_wrapper cl arg... +# Adjust compile command to suit cl +func_cl_wrapper () +{ + # Assume a capable shell + lib_path= + shared=: + linker_opts= + for arg + do + if test -n "$eat"; then + eat= + else + case $1 in + -o) + # configure might choose to run compile as 'compile cc -o foo foo.c'. + eat=1 + case $2 in + *.o | *.[oO][bB][jJ]) + func_file_conv "$2" + set x "$@" -Fo"$file" + shift + ;; + *) + func_file_conv "$2" + set x "$@" -Fe"$file" + shift + ;; + esac + ;; + -I) + eat=1 + func_file_conv "$2" mingw + set x "$@" -I"$file" + shift + ;; + -I*) + func_file_conv "${1#-I}" mingw + set x "$@" -I"$file" + shift + ;; + -l) + eat=1 + func_cl_dashl "$2" + set x "$@" "$lib" + shift + ;; + -l*) + func_cl_dashl "${1#-l}" + set x "$@" "$lib" + shift + ;; + -L) + eat=1 + func_cl_dashL "$2" + ;; + -L*) + func_cl_dashL "${1#-L}" + ;; + -static) + shared=false + ;; + -Wl,*) + arg=${1#-Wl,} + save_ifs="$IFS"; IFS=',' + for flag in $arg; do + IFS="$save_ifs" + linker_opts="$linker_opts $flag" + done + IFS="$save_ifs" + ;; + -Xlinker) + eat=1 + linker_opts="$linker_opts $2" + ;; + -*) + set x "$@" "$1" + shift + ;; + *.cc | *.CC | *.cxx | *.CXX | *.[cC]++) + func_file_conv "$1" + set x "$@" -Tp"$file" + shift + ;; + *.c | *.cpp | *.CPP | *.lib | *.LIB | *.Lib | *.OBJ | *.obj | *.[oO]) + func_file_conv "$1" mingw + set x "$@" "$file" + shift + ;; + *) + set x "$@" "$1" + shift + ;; + esac + fi + shift + done + if test -n "$linker_opts"; then + linker_opts="-link$linker_opts" + fi + exec "$@" $linker_opts + exit 1 +} + +eat= + +case $1 in + '') + echo "$0: No command. Try '$0 --help' for more information." 1>&2 + exit 1; + ;; + -h | --h*) + cat <<\EOF +Usage: compile [--help] [--version] PROGRAM [ARGS] + +Wrapper for compilers which do not understand '-c -o'. +Remove '-o dest.o' from ARGS, run PROGRAM with the remaining +arguments, and rename the output as expected. + +If you are trying to build a whole package this is not the +right script to run: please start by reading the file 'INSTALL'. + +Report bugs to . +EOF + exit $? + ;; + -v | --v*) + echo "compile $scriptversion" + exit $? + ;; + cl | *[/\\]cl | cl.exe | *[/\\]cl.exe | \ + icl | *[/\\]icl | icl.exe | *[/\\]icl.exe ) + func_cl_wrapper "$@" # Doesn't return... + ;; +esac + +ofile= +cfile= + +for arg +do + if test -n "$eat"; then + eat= + else + case $1 in + -o) + # configure might choose to run compile as 'compile cc -o foo foo.c'. + # So we strip '-o arg' only if arg is an object. + eat=1 + case $2 in + *.o | *.obj) + ofile=$2 + ;; + *) + set x "$@" -o "$2" + shift + ;; + esac + ;; + *.c) + cfile=$1 + set x "$@" "$1" + shift + ;; + *) + set x "$@" "$1" + shift + ;; + esac + fi + shift +done + +if test -z "$ofile" || test -z "$cfile"; then + # If no '-o' option was seen then we might have been invoked from a + # pattern rule where we don't need one. That is ok -- this is a + # normal compilation that the losing compiler can handle. If no + # '.c' file was seen then we are probably linking. That is also + # ok. + exec "$@" +fi + +# Name of file we expect compiler to create. +cofile=`echo "$cfile" | sed 's|^.*[\\/]||; s|^[a-zA-Z]:||; s/\.c$/.o/'` + +# Create the lock directory. +# Note: use '[/\\:.-]' here to ensure that we don't use the same name +# that we are using for the .o file. Also, base the name on the expected +# object file name, since that is what matters with a parallel build. +lockdir=`echo "$cofile" | sed -e 's|[/\\:.-]|_|g'`.d +while true; do + if mkdir "$lockdir" >/dev/null 2>&1; then + break + fi + sleep 1 +done +# FIXME: race condition here if user kills between mkdir and trap. +trap "rmdir '$lockdir'; exit 1" 1 2 15 + +# Run the compile. +"$@" +ret=$? + +if test -f "$cofile"; then + test "$cofile" = "$ofile" || mv "$cofile" "$ofile" +elif test -f "${cofile}bj"; then + test "${cofile}bj" = "$ofile" || mv "${cofile}bj" "$ofile" +fi + +rmdir "$lockdir" +exit $ret + +# Local Variables: +# mode: shell-script +# sh-indentation: 2 +# eval: (add-hook 'before-save-hook 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-time-zone: "UTC0" +# time-stamp-end: "; # UTC" +# End: diff --git a/third_party/curl/config.guess b/third_party/curl/config.guess new file mode 100755 index 0000000..7f76b62 --- /dev/null +++ b/third_party/curl/config.guess @@ -0,0 +1,1754 @@ +#! /bin/sh +# Attempt to guess a canonical system name. +# Copyright 1992-2022 Free Software Foundation, Inc. + +# shellcheck disable=SC2006,SC2268 # see below for rationale + +timestamp='2022-01-09' + +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that +# program. This Exception is an additional permission under section 7 +# of the GNU General Public License, version 3 ("GPLv3"). +# +# Originally written by Per Bothner; maintained since 2000 by Ben Elliston. +# +# You can get the latest version of this script from: +# https://git.savannah.gnu.org/cgit/config.git/plain/config.guess +# +# Please send patches to . + + +# The "shellcheck disable" line above the timestamp inhibits complaints +# about features and limitations of the classic Bourne shell that were +# superseded or lifted in POSIX. However, this script identifies a wide +# variety of pre-POSIX systems that do not have POSIX shells at all, and +# even some reasonably current systems (Solaris 10 as case-in-point) still +# have a pre-POSIX /bin/sh. + + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] + +Output the configuration name of the system \`$me' is run on. + +Options: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.guess ($timestamp) + +Originally written by Per Bothner. +Copyright 1992-2022 Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" >&2 + exit 1 ;; + * ) + break ;; + esac +done + +if test $# != 0; then + echo "$me: too many arguments$help" >&2 + exit 1 +fi + +# Just in case it came from the environment. +GUESS= + +# CC_FOR_BUILD -- compiler used by this script. Note that the use of a +# compiler to aid in system detection is discouraged as it requires +# temporary files to be created and, as you can see below, it is a +# headache to deal with in a portable fashion. + +# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still +# use `HOST_CC' if defined, but it is deprecated. + +# Portable tmp directory creation inspired by the Autoconf team. + +tmp= +# shellcheck disable=SC2172 +trap 'test -z "$tmp" || rm -fr "$tmp"' 0 1 2 13 15 + +set_cc_for_build() { + # prevent multiple calls if $tmp is already set + test "$tmp" && return 0 + : "${TMPDIR=/tmp}" + # shellcheck disable=SC2039,SC3028 + { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || + { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir "$tmp" 2>/dev/null) ; } || + { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir "$tmp" 2>/dev/null) && echo "Warning: creating insecure temp directory" >&2 ; } || + { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } + dummy=$tmp/dummy + case ${CC_FOR_BUILD-},${HOST_CC-},${CC-} in + ,,) echo "int x;" > "$dummy.c" + for driver in cc gcc c89 c99 ; do + if ($driver -c -o "$dummy.o" "$dummy.c") >/dev/null 2>&1 ; then + CC_FOR_BUILD=$driver + break + fi + done + if test x"$CC_FOR_BUILD" = x ; then + CC_FOR_BUILD=no_compiler_found + fi + ;; + ,,*) CC_FOR_BUILD=$CC ;; + ,*,*) CC_FOR_BUILD=$HOST_CC ;; + esac +} + +# This is needed to find uname on a Pyramid OSx when run in the BSD universe. +# (ghazi@noc.rutgers.edu 1994-08-24) +if test -f /.attbin/uname ; then + PATH=$PATH:/.attbin ; export PATH +fi + +UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown +UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown +UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown +UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown + +case $UNAME_SYSTEM in +Linux|GNU|GNU/*) + LIBC=unknown + + set_cc_for_build + cat <<-EOF > "$dummy.c" + #include + #if defined(__UCLIBC__) + LIBC=uclibc + #elif defined(__dietlibc__) + LIBC=dietlibc + #elif defined(__GLIBC__) + LIBC=gnu + #else + #include + /* First heuristic to detect musl libc. */ + #ifdef __DEFINED_va_list + LIBC=musl + #endif + #endif + EOF + cc_set_libc=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^LIBC' | sed 's, ,,g'` + eval "$cc_set_libc" + + # Second heuristic to detect musl libc. + if [ "$LIBC" = unknown ] && + command -v ldd >/dev/null && + ldd --version 2>&1 | grep -q ^musl; then + LIBC=musl + fi + + # If the system lacks a compiler, then just pick glibc. + # We could probably try harder. + if [ "$LIBC" = unknown ]; then + LIBC=gnu + fi + ;; +esac + +# Note: order is significant - the case branches are not exclusive. + +case $UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION in + *:NetBSD:*:*) + # NetBSD (nbsd) targets should (where applicable) match one or + # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*, + # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently + # switched to ELF, *-*-netbsd* would select the old + # object file format. This provides both forward + # compatibility and a consistent mechanism for selecting the + # object file format. + # + # Note: NetBSD doesn't particularly care about the vendor + # portion of the name. We always set it to "unknown". + UNAME_MACHINE_ARCH=`(uname -p 2>/dev/null || \ + /sbin/sysctl -n hw.machine_arch 2>/dev/null || \ + /usr/sbin/sysctl -n hw.machine_arch 2>/dev/null || \ + echo unknown)` + case $UNAME_MACHINE_ARCH in + aarch64eb) machine=aarch64_be-unknown ;; + armeb) machine=armeb-unknown ;; + arm*) machine=arm-unknown ;; + sh3el) machine=shl-unknown ;; + sh3eb) machine=sh-unknown ;; + sh5el) machine=sh5le-unknown ;; + earmv*) + arch=`echo "$UNAME_MACHINE_ARCH" | sed -e 's,^e\(armv[0-9]\).*$,\1,'` + endian=`echo "$UNAME_MACHINE_ARCH" | sed -ne 's,^.*\(eb\)$,\1,p'` + machine=${arch}${endian}-unknown + ;; + *) machine=$UNAME_MACHINE_ARCH-unknown ;; + esac + # The Operating System including object format, if it has switched + # to ELF recently (or will in the future) and ABI. + case $UNAME_MACHINE_ARCH in + earm*) + os=netbsdelf + ;; + arm*|i386|m68k|ns32k|sh3*|sparc|vax) + set_cc_for_build + if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ELF__ + then + # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). + # Return netbsd for either. FIX? + os=netbsd + else + os=netbsdelf + fi + ;; + *) + os=netbsd + ;; + esac + # Determine ABI tags. + case $UNAME_MACHINE_ARCH in + earm*) + expr='s/^earmv[0-9]/-eabi/;s/eb$//' + abi=`echo "$UNAME_MACHINE_ARCH" | sed -e "$expr"` + ;; + esac + # The OS release + # Debian GNU/NetBSD machines have a different userland, and + # thus, need a distinct triplet. However, they do not need + # kernel version information, so it can be replaced with a + # suitable tag, in the style of linux-gnu. + case $UNAME_VERSION in + Debian*) + release='-gnu' + ;; + *) + release=`echo "$UNAME_RELEASE" | sed -e 's/[-_].*//' | cut -d. -f1,2` + ;; + esac + # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: + # contains redundant information, the shorter form: + # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. + GUESS=$machine-${os}${release}${abi-} + ;; + *:Bitrig:*:*) + UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'` + GUESS=$UNAME_MACHINE_ARCH-unknown-bitrig$UNAME_RELEASE + ;; + *:OpenBSD:*:*) + UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` + GUESS=$UNAME_MACHINE_ARCH-unknown-openbsd$UNAME_RELEASE + ;; + *:SecBSD:*:*) + UNAME_MACHINE_ARCH=`arch | sed 's/SecBSD.//'` + GUESS=$UNAME_MACHINE_ARCH-unknown-secbsd$UNAME_RELEASE + ;; + *:LibertyBSD:*:*) + UNAME_MACHINE_ARCH=`arch | sed 's/^.*BSD\.//'` + GUESS=$UNAME_MACHINE_ARCH-unknown-libertybsd$UNAME_RELEASE + ;; + *:MidnightBSD:*:*) + GUESS=$UNAME_MACHINE-unknown-midnightbsd$UNAME_RELEASE + ;; + *:ekkoBSD:*:*) + GUESS=$UNAME_MACHINE-unknown-ekkobsd$UNAME_RELEASE + ;; + *:SolidBSD:*:*) + GUESS=$UNAME_MACHINE-unknown-solidbsd$UNAME_RELEASE + ;; + *:OS108:*:*) + GUESS=$UNAME_MACHINE-unknown-os108_$UNAME_RELEASE + ;; + macppc:MirBSD:*:*) + GUESS=powerpc-unknown-mirbsd$UNAME_RELEASE + ;; + *:MirBSD:*:*) + GUESS=$UNAME_MACHINE-unknown-mirbsd$UNAME_RELEASE + ;; + *:Sortix:*:*) + GUESS=$UNAME_MACHINE-unknown-sortix + ;; + *:Twizzler:*:*) + GUESS=$UNAME_MACHINE-unknown-twizzler + ;; + *:Redox:*:*) + GUESS=$UNAME_MACHINE-unknown-redox + ;; + mips:OSF1:*.*) + GUESS=mips-dec-osf1 + ;; + alpha:OSF1:*:*) + # Reset EXIT trap before exiting to avoid spurious non-zero exit code. + trap '' 0 + case $UNAME_RELEASE in + *4.0) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` + ;; + *5.*) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` + ;; + esac + # According to Compaq, /usr/sbin/psrinfo has been available on + # OSF/1 and Tru64 systems produced since 1995. I hope that + # covers most systems running today. This code pipes the CPU + # types through head -n 1, so we only detect the type of CPU 0. + ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` + case $ALPHA_CPU_TYPE in + "EV4 (21064)") + UNAME_MACHINE=alpha ;; + "EV4.5 (21064)") + UNAME_MACHINE=alpha ;; + "LCA4 (21066/21068)") + UNAME_MACHINE=alpha ;; + "EV5 (21164)") + UNAME_MACHINE=alphaev5 ;; + "EV5.6 (21164A)") + UNAME_MACHINE=alphaev56 ;; + "EV5.6 (21164PC)") + UNAME_MACHINE=alphapca56 ;; + "EV5.7 (21164PC)") + UNAME_MACHINE=alphapca57 ;; + "EV6 (21264)") + UNAME_MACHINE=alphaev6 ;; + "EV6.7 (21264A)") + UNAME_MACHINE=alphaev67 ;; + "EV6.8CB (21264C)") + UNAME_MACHINE=alphaev68 ;; + "EV6.8AL (21264B)") + UNAME_MACHINE=alphaev68 ;; + "EV6.8CX (21264D)") + UNAME_MACHINE=alphaev68 ;; + "EV6.9A (21264/EV69A)") + UNAME_MACHINE=alphaev69 ;; + "EV7 (21364)") + UNAME_MACHINE=alphaev7 ;; + "EV7.9 (21364A)") + UNAME_MACHINE=alphaev79 ;; + esac + # A Pn.n version is a patched version. + # A Vn.n version is a released version. + # A Tn.n version is a released field test version. + # A Xn.n version is an unreleased experimental baselevel. + # 1.2 uses "1.2" for uname -r. + OSF_REL=`echo "$UNAME_RELEASE" | sed -e 's/^[PVTX]//' | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz` + GUESS=$UNAME_MACHINE-dec-osf$OSF_REL + ;; + Amiga*:UNIX_System_V:4.0:*) + GUESS=m68k-unknown-sysv4 + ;; + *:[Aa]miga[Oo][Ss]:*:*) + GUESS=$UNAME_MACHINE-unknown-amigaos + ;; + *:[Mm]orph[Oo][Ss]:*:*) + GUESS=$UNAME_MACHINE-unknown-morphos + ;; + *:OS/390:*:*) + GUESS=i370-ibm-openedition + ;; + *:z/VM:*:*) + GUESS=s390-ibm-zvmoe + ;; + *:OS400:*:*) + GUESS=powerpc-ibm-os400 + ;; + arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) + GUESS=arm-acorn-riscix$UNAME_RELEASE + ;; + arm*:riscos:*:*|arm*:RISCOS:*:*) + GUESS=arm-unknown-riscos + ;; + SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) + GUESS=hppa1.1-hitachi-hiuxmpp + ;; + Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) + # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. + case `(/bin/universe) 2>/dev/null` in + att) GUESS=pyramid-pyramid-sysv3 ;; + *) GUESS=pyramid-pyramid-bsd ;; + esac + ;; + NILE*:*:*:dcosx) + GUESS=pyramid-pyramid-svr4 + ;; + DRS?6000:unix:4.0:6*) + GUESS=sparc-icl-nx6 + ;; + DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) + case `/usr/bin/uname -p` in + sparc) GUESS=sparc-icl-nx7 ;; + esac + ;; + s390x:SunOS:*:*) + SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` + GUESS=$UNAME_MACHINE-ibm-solaris2$SUN_REL + ;; + sun4H:SunOS:5.*:*) + SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` + GUESS=sparc-hal-solaris2$SUN_REL + ;; + sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) + SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` + GUESS=sparc-sun-solaris2$SUN_REL + ;; + i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) + GUESS=i386-pc-auroraux$UNAME_RELEASE + ;; + i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) + set_cc_for_build + SUN_ARCH=i386 + # If there is a compiler, see if it is configured for 64-bit objects. + # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. + # This test works for both compilers. + if test "$CC_FOR_BUILD" != no_compiler_found; then + if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ + (CCOPTS="" $CC_FOR_BUILD -m64 -E - 2>/dev/null) | \ + grep IS_64BIT_ARCH >/dev/null + then + SUN_ARCH=x86_64 + fi + fi + SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` + GUESS=$SUN_ARCH-pc-solaris2$SUN_REL + ;; + sun4*:SunOS:6*:*) + # According to config.sub, this is the proper way to canonicalize + # SunOS6. Hard to guess exactly what SunOS6 will be like, but + # it's likely to be more like Solaris than SunOS4. + SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` + GUESS=sparc-sun-solaris3$SUN_REL + ;; + sun4*:SunOS:*:*) + case `/usr/bin/arch -k` in + Series*|S4*) + UNAME_RELEASE=`uname -v` + ;; + esac + # Japanese Language versions have a version number like `4.1.3-JL'. + SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/-/_/'` + GUESS=sparc-sun-sunos$SUN_REL + ;; + sun3*:SunOS:*:*) + GUESS=m68k-sun-sunos$UNAME_RELEASE + ;; + sun*:*:4.2BSD:*) + UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` + test "x$UNAME_RELEASE" = x && UNAME_RELEASE=3 + case `/bin/arch` in + sun3) + GUESS=m68k-sun-sunos$UNAME_RELEASE + ;; + sun4) + GUESS=sparc-sun-sunos$UNAME_RELEASE + ;; + esac + ;; + aushp:SunOS:*:*) + GUESS=sparc-auspex-sunos$UNAME_RELEASE + ;; + # The situation for MiNT is a little confusing. The machine name + # can be virtually everything (everything which is not + # "atarist" or "atariste" at least should have a processor + # > m68000). The system name ranges from "MiNT" over "FreeMiNT" + # to the lowercase version "mint" (or "freemint"). Finally + # the system name "TOS" denotes a system which is actually not + # MiNT. But MiNT is downward compatible to TOS, so this should + # be no problem. + atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) + GUESS=m68k-atari-mint$UNAME_RELEASE + ;; + atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) + GUESS=m68k-atari-mint$UNAME_RELEASE + ;; + *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) + GUESS=m68k-atari-mint$UNAME_RELEASE + ;; + milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) + GUESS=m68k-milan-mint$UNAME_RELEASE + ;; + hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) + GUESS=m68k-hades-mint$UNAME_RELEASE + ;; + *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) + GUESS=m68k-unknown-mint$UNAME_RELEASE + ;; + m68k:machten:*:*) + GUESS=m68k-apple-machten$UNAME_RELEASE + ;; + powerpc:machten:*:*) + GUESS=powerpc-apple-machten$UNAME_RELEASE + ;; + RISC*:Mach:*:*) + GUESS=mips-dec-mach_bsd4.3 + ;; + RISC*:ULTRIX:*:*) + GUESS=mips-dec-ultrix$UNAME_RELEASE + ;; + VAX*:ULTRIX*:*:*) + GUESS=vax-dec-ultrix$UNAME_RELEASE + ;; + 2020:CLIX:*:* | 2430:CLIX:*:*) + GUESS=clipper-intergraph-clix$UNAME_RELEASE + ;; + mips:*:*:UMIPS | mips:*:*:RISCos) + set_cc_for_build + sed 's/^ //' << EOF > "$dummy.c" +#ifdef __cplusplus +#include /* for printf() prototype */ + int main (int argc, char *argv[]) { +#else + int main (argc, argv) int argc; char *argv[]; { +#endif + #if defined (host_mips) && defined (MIPSEB) + #if defined (SYSTYPE_SYSV) + printf ("mips-mips-riscos%ssysv\\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_SVR4) + printf ("mips-mips-riscos%ssvr4\\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) + printf ("mips-mips-riscos%sbsd\\n", argv[1]); exit (0); + #endif + #endif + exit (-1); + } +EOF + $CC_FOR_BUILD -o "$dummy" "$dummy.c" && + dummyarg=`echo "$UNAME_RELEASE" | sed -n 's/\([0-9]*\).*/\1/p'` && + SYSTEM_NAME=`"$dummy" "$dummyarg"` && + { echo "$SYSTEM_NAME"; exit; } + GUESS=mips-mips-riscos$UNAME_RELEASE + ;; + Motorola:PowerMAX_OS:*:*) + GUESS=powerpc-motorola-powermax + ;; + Motorola:*:4.3:PL8-*) + GUESS=powerpc-harris-powermax + ;; + Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) + GUESS=powerpc-harris-powermax + ;; + Night_Hawk:Power_UNIX:*:*) + GUESS=powerpc-harris-powerunix + ;; + m88k:CX/UX:7*:*) + GUESS=m88k-harris-cxux7 + ;; + m88k:*:4*:R4*) + GUESS=m88k-motorola-sysv4 + ;; + m88k:*:3*:R3*) + GUESS=m88k-motorola-sysv3 + ;; + AViiON:dgux:*:*) + # DG/UX returns AViiON for all architectures + UNAME_PROCESSOR=`/usr/bin/uname -p` + if test "$UNAME_PROCESSOR" = mc88100 || test "$UNAME_PROCESSOR" = mc88110 + then + if test "$TARGET_BINARY_INTERFACE"x = m88kdguxelfx || \ + test "$TARGET_BINARY_INTERFACE"x = x + then + GUESS=m88k-dg-dgux$UNAME_RELEASE + else + GUESS=m88k-dg-dguxbcs$UNAME_RELEASE + fi + else + GUESS=i586-dg-dgux$UNAME_RELEASE + fi + ;; + M88*:DolphinOS:*:*) # DolphinOS (SVR3) + GUESS=m88k-dolphin-sysv3 + ;; + M88*:*:R3*:*) + # Delta 88k system running SVR3 + GUESS=m88k-motorola-sysv3 + ;; + XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) + GUESS=m88k-tektronix-sysv3 + ;; + Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) + GUESS=m68k-tektronix-bsd + ;; + *:IRIX*:*:*) + IRIX_REL=`echo "$UNAME_RELEASE" | sed -e 's/-/_/g'` + GUESS=mips-sgi-irix$IRIX_REL + ;; + ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. + GUESS=romp-ibm-aix # uname -m gives an 8 hex-code CPU id + ;; # Note that: echo "'`uname -s`'" gives 'AIX ' + i*86:AIX:*:*) + GUESS=i386-ibm-aix + ;; + ia64:AIX:*:*) + if test -x /usr/bin/oslevel ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=$UNAME_VERSION.$UNAME_RELEASE + fi + GUESS=$UNAME_MACHINE-ibm-aix$IBM_REV + ;; + *:AIX:2:3) + if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then + set_cc_for_build + sed 's/^ //' << EOF > "$dummy.c" + #include + + main() + { + if (!__power_pc()) + exit(1); + puts("powerpc-ibm-aix3.2.5"); + exit(0); + } +EOF + if $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"` + then + GUESS=$SYSTEM_NAME + else + GUESS=rs6000-ibm-aix3.2.5 + fi + elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then + GUESS=rs6000-ibm-aix3.2.4 + else + GUESS=rs6000-ibm-aix3.2 + fi + ;; + *:AIX:*:[4567]) + IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` + if /usr/sbin/lsattr -El "$IBM_CPU_ID" | grep ' POWER' >/dev/null 2>&1; then + IBM_ARCH=rs6000 + else + IBM_ARCH=powerpc + fi + if test -x /usr/bin/lslpp ; then + IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc | \ + awk -F: '{ print $3 }' | sed s/[0-9]*$/0/` + else + IBM_REV=$UNAME_VERSION.$UNAME_RELEASE + fi + GUESS=$IBM_ARCH-ibm-aix$IBM_REV + ;; + *:AIX:*:*) + GUESS=rs6000-ibm-aix + ;; + ibmrt:4.4BSD:*|romp-ibm:4.4BSD:*) + GUESS=romp-ibm-bsd4.4 + ;; + ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and + GUESS=romp-ibm-bsd$UNAME_RELEASE # 4.3 with uname added to + ;; # report: romp-ibm BSD 4.3 + *:BOSX:*:*) + GUESS=rs6000-bull-bosx + ;; + DPX/2?00:B.O.S.:*:*) + GUESS=m68k-bull-sysv3 + ;; + 9000/[34]??:4.3bsd:1.*:*) + GUESS=m68k-hp-bsd + ;; + hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) + GUESS=m68k-hp-bsd4.4 + ;; + 9000/[34678]??:HP-UX:*:*) + HPUX_REV=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*.[0B]*//'` + case $UNAME_MACHINE in + 9000/31?) HP_ARCH=m68000 ;; + 9000/[34]??) HP_ARCH=m68k ;; + 9000/[678][0-9][0-9]) + if test -x /usr/bin/getconf; then + sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` + sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` + case $sc_cpu_version in + 523) HP_ARCH=hppa1.0 ;; # CPU_PA_RISC1_0 + 528) HP_ARCH=hppa1.1 ;; # CPU_PA_RISC1_1 + 532) # CPU_PA_RISC2_0 + case $sc_kernel_bits in + 32) HP_ARCH=hppa2.0n ;; + 64) HP_ARCH=hppa2.0w ;; + '') HP_ARCH=hppa2.0 ;; # HP-UX 10.20 + esac ;; + esac + fi + if test "$HP_ARCH" = ""; then + set_cc_for_build + sed 's/^ //' << EOF > "$dummy.c" + + #define _HPUX_SOURCE + #include + #include + + int main () + { + #if defined(_SC_KERNEL_BITS) + long bits = sysconf(_SC_KERNEL_BITS); + #endif + long cpu = sysconf (_SC_CPU_VERSION); + + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1"); break; + case CPU_PA_RISC2_0: + #if defined(_SC_KERNEL_BITS) + switch (bits) + { + case 64: puts ("hppa2.0w"); break; + case 32: puts ("hppa2.0n"); break; + default: puts ("hppa2.0"); break; + } break; + #else /* !defined(_SC_KERNEL_BITS) */ + puts ("hppa2.0"); break; + #endif + default: puts ("hppa1.0"); break; + } + exit (0); + } +EOF + (CCOPTS="" $CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null) && HP_ARCH=`"$dummy"` + test -z "$HP_ARCH" && HP_ARCH=hppa + fi ;; + esac + if test "$HP_ARCH" = hppa2.0w + then + set_cc_for_build + + # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating + # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler + # generating 64-bit code. GNU and HP use different nomenclature: + # + # $ CC_FOR_BUILD=cc ./config.guess + # => hppa2.0w-hp-hpux11.23 + # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess + # => hppa64-hp-hpux11.23 + + if echo __LP64__ | (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | + grep -q __LP64__ + then + HP_ARCH=hppa2.0w + else + HP_ARCH=hppa64 + fi + fi + GUESS=$HP_ARCH-hp-hpux$HPUX_REV + ;; + ia64:HP-UX:*:*) + HPUX_REV=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*.[0B]*//'` + GUESS=ia64-hp-hpux$HPUX_REV + ;; + 3050*:HI-UX:*:*) + set_cc_for_build + sed 's/^ //' << EOF > "$dummy.c" + #include + int + main () + { + long cpu = sysconf (_SC_CPU_VERSION); + /* The order matters, because CPU_IS_HP_MC68K erroneously returns + true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct + results, however. */ + if (CPU_IS_PA_RISC (cpu)) + { + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; + case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; + default: puts ("hppa-hitachi-hiuxwe2"); break; + } + } + else if (CPU_IS_HP_MC68K (cpu)) + puts ("m68k-hitachi-hiuxwe2"); + else puts ("unknown-hitachi-hiuxwe2"); + exit (0); + } +EOF + $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"` && + { echo "$SYSTEM_NAME"; exit; } + GUESS=unknown-hitachi-hiuxwe2 + ;; + 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:*) + GUESS=hppa1.1-hp-bsd + ;; + 9000/8??:4.3bsd:*:*) + GUESS=hppa1.0-hp-bsd + ;; + *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) + GUESS=hppa1.0-hp-mpeix + ;; + hp7??:OSF1:*:* | hp8?[79]:OSF1:*:*) + GUESS=hppa1.1-hp-osf + ;; + hp8??:OSF1:*:*) + GUESS=hppa1.0-hp-osf + ;; + i*86:OSF1:*:*) + if test -x /usr/sbin/sysversion ; then + GUESS=$UNAME_MACHINE-unknown-osf1mk + else + GUESS=$UNAME_MACHINE-unknown-osf1 + fi + ;; + parisc*:Lites*:*:*) + GUESS=hppa1.1-hp-lites + ;; + C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) + GUESS=c1-convex-bsd + ;; + C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit ;; + C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) + GUESS=c34-convex-bsd + ;; + C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) + GUESS=c38-convex-bsd + ;; + C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) + GUESS=c4-convex-bsd + ;; + CRAY*Y-MP:*:*:*) + CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` + GUESS=ymp-cray-unicos$CRAY_REL + ;; + CRAY*[A-Z]90:*:*:*) + echo "$UNAME_MACHINE"-cray-unicos"$UNAME_RELEASE" \ + | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ + -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ + -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*TS:*:*:*) + CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` + GUESS=t90-cray-unicos$CRAY_REL + ;; + CRAY*T3E:*:*:*) + CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` + GUESS=alphaev5-cray-unicosmk$CRAY_REL + ;; + CRAY*SV1:*:*:*) + CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` + GUESS=sv1-cray-unicos$CRAY_REL + ;; + *:UNICOS/mp:*:*) + CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` + GUESS=craynv-cray-unicosmp$CRAY_REL + ;; + F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) + FUJITSU_PROC=`uname -m | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz` + FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` + FUJITSU_REL=`echo "$UNAME_RELEASE" | sed -e 's/ /_/'` + GUESS=${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL} + ;; + 5000:UNIX_System_V:4.*:*) + FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` + FUJITSU_REL=`echo "$UNAME_RELEASE" | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/ /_/'` + GUESS=sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL} + ;; + i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) + GUESS=$UNAME_MACHINE-pc-bsdi$UNAME_RELEASE + ;; + sparc*:BSD/OS:*:*) + GUESS=sparc-unknown-bsdi$UNAME_RELEASE + ;; + *:BSD/OS:*:*) + GUESS=$UNAME_MACHINE-unknown-bsdi$UNAME_RELEASE + ;; + arm:FreeBSD:*:*) + UNAME_PROCESSOR=`uname -p` + set_cc_for_build + if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ARM_PCS_VFP + then + FREEBSD_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` + GUESS=$UNAME_PROCESSOR-unknown-freebsd$FREEBSD_REL-gnueabi + else + FREEBSD_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` + GUESS=$UNAME_PROCESSOR-unknown-freebsd$FREEBSD_REL-gnueabihf + fi + ;; + *:FreeBSD:*:*) + UNAME_PROCESSOR=`/usr/bin/uname -p` + case $UNAME_PROCESSOR in + amd64) + UNAME_PROCESSOR=x86_64 ;; + i386) + UNAME_PROCESSOR=i586 ;; + esac + FREEBSD_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` + GUESS=$UNAME_PROCESSOR-unknown-freebsd$FREEBSD_REL + ;; + i*:CYGWIN*:*) + GUESS=$UNAME_MACHINE-pc-cygwin + ;; + *:MINGW64*:*) + GUESS=$UNAME_MACHINE-pc-mingw64 + ;; + *:MINGW*:*) + GUESS=$UNAME_MACHINE-pc-mingw32 + ;; + *:MSYS*:*) + GUESS=$UNAME_MACHINE-pc-msys + ;; + i*:PW*:*) + GUESS=$UNAME_MACHINE-pc-pw32 + ;; + *:SerenityOS:*:*) + GUESS=$UNAME_MACHINE-pc-serenity + ;; + *:Interix*:*) + case $UNAME_MACHINE in + x86) + GUESS=i586-pc-interix$UNAME_RELEASE + ;; + authenticamd | genuineintel | EM64T) + GUESS=x86_64-unknown-interix$UNAME_RELEASE + ;; + IA64) + GUESS=ia64-unknown-interix$UNAME_RELEASE + ;; + esac ;; + i*:UWIN*:*) + GUESS=$UNAME_MACHINE-pc-uwin + ;; + amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) + GUESS=x86_64-pc-cygwin + ;; + prep*:SunOS:5.*:*) + SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` + GUESS=powerpcle-unknown-solaris2$SUN_REL + ;; + *:GNU:*:*) + # the GNU system + GNU_ARCH=`echo "$UNAME_MACHINE" | sed -e 's,[-/].*$,,'` + GNU_REL=`echo "$UNAME_RELEASE" | sed -e 's,/.*$,,'` + GUESS=$GNU_ARCH-unknown-$LIBC$GNU_REL + ;; + *:GNU/*:*:*) + # other systems with GNU libc and userland + GNU_SYS=`echo "$UNAME_SYSTEM" | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]"` + GNU_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` + GUESS=$UNAME_MACHINE-unknown-$GNU_SYS$GNU_REL-$LIBC + ;; + *:Minix:*:*) + GUESS=$UNAME_MACHINE-unknown-minix + ;; + aarch64:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + aarch64_be:Linux:*:*) + UNAME_MACHINE=aarch64_be + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + alpha:Linux:*:*) + case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' /proc/cpuinfo 2>/dev/null` in + EV5) UNAME_MACHINE=alphaev5 ;; + EV56) UNAME_MACHINE=alphaev56 ;; + PCA56) UNAME_MACHINE=alphapca56 ;; + PCA57) UNAME_MACHINE=alphapca56 ;; + EV6) UNAME_MACHINE=alphaev6 ;; + EV67) UNAME_MACHINE=alphaev67 ;; + EV68*) UNAME_MACHINE=alphaev68 ;; + esac + objdump --private-headers /bin/sh | grep -q ld.so.1 + if test "$?" = 0 ; then LIBC=gnulibc1 ; fi + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + arc:Linux:*:* | arceb:Linux:*:* | arc32:Linux:*:* | arc64:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + arm*:Linux:*:*) + set_cc_for_build + if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ARM_EABI__ + then + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + else + if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ARM_PCS_VFP + then + GUESS=$UNAME_MACHINE-unknown-linux-${LIBC}eabi + else + GUESS=$UNAME_MACHINE-unknown-linux-${LIBC}eabihf + fi + fi + ;; + avr32*:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + cris:Linux:*:*) + GUESS=$UNAME_MACHINE-axis-linux-$LIBC + ;; + crisv32:Linux:*:*) + GUESS=$UNAME_MACHINE-axis-linux-$LIBC + ;; + e2k:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + frv:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + hexagon:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + i*86:Linux:*:*) + GUESS=$UNAME_MACHINE-pc-linux-$LIBC + ;; + ia64:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + k1om:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + loongarch32:Linux:*:* | loongarch64:Linux:*:* | loongarchx32:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + m32r*:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + m68*:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + mips:Linux:*:* | mips64:Linux:*:*) + set_cc_for_build + IS_GLIBC=0 + test x"${LIBC}" = xgnu && IS_GLIBC=1 + sed 's/^ //' << EOF > "$dummy.c" + #undef CPU + #undef mips + #undef mipsel + #undef mips64 + #undef mips64el + #if ${IS_GLIBC} && defined(_ABI64) + LIBCABI=gnuabi64 + #else + #if ${IS_GLIBC} && defined(_ABIN32) + LIBCABI=gnuabin32 + #else + LIBCABI=${LIBC} + #endif + #endif + + #if ${IS_GLIBC} && defined(__mips64) && defined(__mips_isa_rev) && __mips_isa_rev>=6 + CPU=mipsisa64r6 + #else + #if ${IS_GLIBC} && !defined(__mips64) && defined(__mips_isa_rev) && __mips_isa_rev>=6 + CPU=mipsisa32r6 + #else + #if defined(__mips64) + CPU=mips64 + #else + CPU=mips + #endif + #endif + #endif + + #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) + MIPS_ENDIAN=el + #else + #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) + MIPS_ENDIAN= + #else + MIPS_ENDIAN= + #endif + #endif +EOF + cc_set_vars=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^CPU\|^MIPS_ENDIAN\|^LIBCABI'` + eval "$cc_set_vars" + test "x$CPU" != x && { echo "$CPU${MIPS_ENDIAN}-unknown-linux-$LIBCABI"; exit; } + ;; + mips64el:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + openrisc*:Linux:*:*) + GUESS=or1k-unknown-linux-$LIBC + ;; + or32:Linux:*:* | or1k*:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + padre:Linux:*:*) + GUESS=sparc-unknown-linux-$LIBC + ;; + parisc64:Linux:*:* | hppa64:Linux:*:*) + GUESS=hppa64-unknown-linux-$LIBC + ;; + parisc:Linux:*:* | hppa:Linux:*:*) + # Look for CPU level + case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in + PA7*) GUESS=hppa1.1-unknown-linux-$LIBC ;; + PA8*) GUESS=hppa2.0-unknown-linux-$LIBC ;; + *) GUESS=hppa-unknown-linux-$LIBC ;; + esac + ;; + ppc64:Linux:*:*) + GUESS=powerpc64-unknown-linux-$LIBC + ;; + ppc:Linux:*:*) + GUESS=powerpc-unknown-linux-$LIBC + ;; + ppc64le:Linux:*:*) + GUESS=powerpc64le-unknown-linux-$LIBC + ;; + ppcle:Linux:*:*) + GUESS=powerpcle-unknown-linux-$LIBC + ;; + riscv32:Linux:*:* | riscv32be:Linux:*:* | riscv64:Linux:*:* | riscv64be:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + s390:Linux:*:* | s390x:Linux:*:*) + GUESS=$UNAME_MACHINE-ibm-linux-$LIBC + ;; + sh64*:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + sh*:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + sparc:Linux:*:* | sparc64:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + tile*:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + vax:Linux:*:*) + GUESS=$UNAME_MACHINE-dec-linux-$LIBC + ;; + x86_64:Linux:*:*) + set_cc_for_build + LIBCABI=$LIBC + if test "$CC_FOR_BUILD" != no_compiler_found; then + if (echo '#ifdef __ILP32__'; echo IS_X32; echo '#endif') | \ + (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_X32 >/dev/null + then + LIBCABI=${LIBC}x32 + fi + fi + GUESS=$UNAME_MACHINE-pc-linux-$LIBCABI + ;; + xtensa*:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + i*86:DYNIX/ptx:4*:*) + # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. + # earlier versions are messed up and put the nodename in both + # sysname and nodename. + GUESS=i386-sequent-sysv4 + ;; + i*86:UNIX_SV:4.2MP:2.*) + # Unixware is an offshoot of SVR4, but it has its own version + # number series starting with 2... + # I am not positive that other SVR4 systems won't match this, + # I just have to hope. -- rms. + # Use sysv4.2uw... so that sysv4* matches it. + GUESS=$UNAME_MACHINE-pc-sysv4.2uw$UNAME_VERSION + ;; + i*86:OS/2:*:*) + # If we were able to find `uname', then EMX Unix compatibility + # is probably installed. + GUESS=$UNAME_MACHINE-pc-os2-emx + ;; + i*86:XTS-300:*:STOP) + GUESS=$UNAME_MACHINE-unknown-stop + ;; + i*86:atheos:*:*) + GUESS=$UNAME_MACHINE-unknown-atheos + ;; + i*86:syllable:*:*) + GUESS=$UNAME_MACHINE-pc-syllable + ;; + i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) + GUESS=i386-unknown-lynxos$UNAME_RELEASE + ;; + i*86:*DOS:*:*) + GUESS=$UNAME_MACHINE-pc-msdosdjgpp + ;; + i*86:*:4.*:*) + UNAME_REL=`echo "$UNAME_RELEASE" | sed 's/\/MP$//'` + if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then + GUESS=$UNAME_MACHINE-univel-sysv$UNAME_REL + else + GUESS=$UNAME_MACHINE-pc-sysv$UNAME_REL + fi + ;; + i*86:*:5:[678]*) + # UnixWare 7.x, OpenUNIX and OpenServer 6. + case `/bin/uname -X | grep "^Machine"` in + *486*) UNAME_MACHINE=i486 ;; + *Pentium) UNAME_MACHINE=i586 ;; + *Pent*|*Celeron) UNAME_MACHINE=i686 ;; + esac + GUESS=$UNAME_MACHINE-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} + ;; + i*86:*:3.2:*) + if test -f /usr/options/cb.name; then + UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then + UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` + (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 + (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ + && UNAME_MACHINE=i586 + (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ + && UNAME_MACHINE=i686 + (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ + && UNAME_MACHINE=i686 + GUESS=$UNAME_MACHINE-pc-sco$UNAME_REL + else + GUESS=$UNAME_MACHINE-pc-sysv32 + fi + ;; + pc:*:*:*) + # Left here for compatibility: + # uname -m prints for DJGPP always 'pc', but it prints nothing about + # the processor, so we play safe by assuming i586. + # Note: whatever this is, it MUST be the same as what config.sub + # prints for the "djgpp" host, or else GDB configure will decide that + # this is a cross-build. + GUESS=i586-pc-msdosdjgpp + ;; + Intel:Mach:3*:*) + GUESS=i386-pc-mach3 + ;; + paragon:*:*:*) + GUESS=i860-intel-osf1 + ;; + i860:*:4.*:*) # i860-SVR4 + if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then + GUESS=i860-stardent-sysv$UNAME_RELEASE # Stardent Vistra i860-SVR4 + else # Add other i860-SVR4 vendors below as they are discovered. + GUESS=i860-unknown-sysv$UNAME_RELEASE # Unknown i860-SVR4 + fi + ;; + mini*:CTIX:SYS*5:*) + # "miniframe" + GUESS=m68010-convergent-sysv + ;; + mc68k:UNIX:SYSTEM5:3.51m) + GUESS=m68k-convergent-sysv + ;; + M680?0:D-NIX:5.3:*) + GUESS=m68k-diab-dnix + ;; + M68*:*:R3V[5678]*:*) + test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; + 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) + OS_REL='' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4.3"$OS_REL"; exit; } + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;; + 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4; exit; } ;; + NCR*:*:4.2:* | MPRAS*:*:4.2:*) + OS_REL='.3' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4.3"$OS_REL"; exit; } + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } + /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ + && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;; + m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) + GUESS=m68k-unknown-lynxos$UNAME_RELEASE + ;; + mc68030:UNIX_System_V:4.*:*) + GUESS=m68k-atari-sysv4 + ;; + TSUNAMI:LynxOS:2.*:*) + GUESS=sparc-unknown-lynxos$UNAME_RELEASE + ;; + rs6000:LynxOS:2.*:*) + GUESS=rs6000-unknown-lynxos$UNAME_RELEASE + ;; + PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) + GUESS=powerpc-unknown-lynxos$UNAME_RELEASE + ;; + SM[BE]S:UNIX_SV:*:*) + GUESS=mips-dde-sysv$UNAME_RELEASE + ;; + RM*:ReliantUNIX-*:*:*) + GUESS=mips-sni-sysv4 + ;; + RM*:SINIX-*:*:*) + GUESS=mips-sni-sysv4 + ;; + *:SINIX-*:*:*) + if uname -p 2>/dev/null >/dev/null ; then + UNAME_MACHINE=`(uname -p) 2>/dev/null` + GUESS=$UNAME_MACHINE-sni-sysv4 + else + GUESS=ns32k-sni-sysv + fi + ;; + PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort + # says + GUESS=i586-unisys-sysv4 + ;; + *:UNIX_System_V:4*:FTX*) + # From Gerald Hewes . + # How about differentiating between stratus architectures? -djm + GUESS=hppa1.1-stratus-sysv4 + ;; + *:*:*:FTX*) + # From seanf@swdc.stratus.com. + GUESS=i860-stratus-sysv4 + ;; + i*86:VOS:*:*) + # From Paul.Green@stratus.com. + GUESS=$UNAME_MACHINE-stratus-vos + ;; + *:VOS:*:*) + # From Paul.Green@stratus.com. + GUESS=hppa1.1-stratus-vos + ;; + mc68*:A/UX:*:*) + GUESS=m68k-apple-aux$UNAME_RELEASE + ;; + news*:NEWS-OS:6*:*) + GUESS=mips-sony-newsos6 + ;; + R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) + if test -d /usr/nec; then + GUESS=mips-nec-sysv$UNAME_RELEASE + else + GUESS=mips-unknown-sysv$UNAME_RELEASE + fi + ;; + BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. + GUESS=powerpc-be-beos + ;; + BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. + GUESS=powerpc-apple-beos + ;; + BePC:BeOS:*:*) # BeOS running on Intel PC compatible. + GUESS=i586-pc-beos + ;; + BePC:Haiku:*:*) # Haiku running on Intel PC compatible. + GUESS=i586-pc-haiku + ;; + x86_64:Haiku:*:*) + GUESS=x86_64-unknown-haiku + ;; + SX-4:SUPER-UX:*:*) + GUESS=sx4-nec-superux$UNAME_RELEASE + ;; + SX-5:SUPER-UX:*:*) + GUESS=sx5-nec-superux$UNAME_RELEASE + ;; + SX-6:SUPER-UX:*:*) + GUESS=sx6-nec-superux$UNAME_RELEASE + ;; + SX-7:SUPER-UX:*:*) + GUESS=sx7-nec-superux$UNAME_RELEASE + ;; + SX-8:SUPER-UX:*:*) + GUESS=sx8-nec-superux$UNAME_RELEASE + ;; + SX-8R:SUPER-UX:*:*) + GUESS=sx8r-nec-superux$UNAME_RELEASE + ;; + SX-ACE:SUPER-UX:*:*) + GUESS=sxace-nec-superux$UNAME_RELEASE + ;; + Power*:Rhapsody:*:*) + GUESS=powerpc-apple-rhapsody$UNAME_RELEASE + ;; + *:Rhapsody:*:*) + GUESS=$UNAME_MACHINE-apple-rhapsody$UNAME_RELEASE + ;; + arm64:Darwin:*:*) + GUESS=aarch64-apple-darwin$UNAME_RELEASE + ;; + *:Darwin:*:*) + UNAME_PROCESSOR=`uname -p` + case $UNAME_PROCESSOR in + unknown) UNAME_PROCESSOR=powerpc ;; + esac + if command -v xcode-select > /dev/null 2> /dev/null && \ + ! xcode-select --print-path > /dev/null 2> /dev/null ; then + # Avoid executing cc if there is no toolchain installed as + # cc will be a stub that puts up a graphical alert + # prompting the user to install developer tools. + CC_FOR_BUILD=no_compiler_found + else + set_cc_for_build + fi + if test "$CC_FOR_BUILD" != no_compiler_found; then + if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ + (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_64BIT_ARCH >/dev/null + then + case $UNAME_PROCESSOR in + i386) UNAME_PROCESSOR=x86_64 ;; + powerpc) UNAME_PROCESSOR=powerpc64 ;; + esac + fi + # On 10.4-10.6 one might compile for PowerPC via gcc -arch ppc + if (echo '#ifdef __POWERPC__'; echo IS_PPC; echo '#endif') | \ + (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_PPC >/dev/null + then + UNAME_PROCESSOR=powerpc + fi + elif test "$UNAME_PROCESSOR" = i386 ; then + # uname -m returns i386 or x86_64 + UNAME_PROCESSOR=$UNAME_MACHINE + fi + GUESS=$UNAME_PROCESSOR-apple-darwin$UNAME_RELEASE + ;; + *:procnto*:*:* | *:QNX:[0123456789]*:*) + UNAME_PROCESSOR=`uname -p` + if test "$UNAME_PROCESSOR" = x86; then + UNAME_PROCESSOR=i386 + UNAME_MACHINE=pc + fi + GUESS=$UNAME_PROCESSOR-$UNAME_MACHINE-nto-qnx$UNAME_RELEASE + ;; + *:QNX:*:4*) + GUESS=i386-pc-qnx + ;; + NEO-*:NONSTOP_KERNEL:*:*) + GUESS=neo-tandem-nsk$UNAME_RELEASE + ;; + NSE-*:NONSTOP_KERNEL:*:*) + GUESS=nse-tandem-nsk$UNAME_RELEASE + ;; + NSR-*:NONSTOP_KERNEL:*:*) + GUESS=nsr-tandem-nsk$UNAME_RELEASE + ;; + NSV-*:NONSTOP_KERNEL:*:*) + GUESS=nsv-tandem-nsk$UNAME_RELEASE + ;; + NSX-*:NONSTOP_KERNEL:*:*) + GUESS=nsx-tandem-nsk$UNAME_RELEASE + ;; + *:NonStop-UX:*:*) + GUESS=mips-compaq-nonstopux + ;; + BS2000:POSIX*:*:*) + GUESS=bs2000-siemens-sysv + ;; + DS/*:UNIX_System_V:*:*) + GUESS=$UNAME_MACHINE-$UNAME_SYSTEM-$UNAME_RELEASE + ;; + *:Plan9:*:*) + # "uname -m" is not consistent, so use $cputype instead. 386 + # is converted to i386 for consistency with other x86 + # operating systems. + if test "${cputype-}" = 386; then + UNAME_MACHINE=i386 + elif test "x${cputype-}" != x; then + UNAME_MACHINE=$cputype + fi + GUESS=$UNAME_MACHINE-unknown-plan9 + ;; + *:TOPS-10:*:*) + GUESS=pdp10-unknown-tops10 + ;; + *:TENEX:*:*) + GUESS=pdp10-unknown-tenex + ;; + KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) + GUESS=pdp10-dec-tops20 + ;; + XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) + GUESS=pdp10-xkl-tops20 + ;; + *:TOPS-20:*:*) + GUESS=pdp10-unknown-tops20 + ;; + *:ITS:*:*) + GUESS=pdp10-unknown-its + ;; + SEI:*:*:SEIUX) + GUESS=mips-sei-seiux$UNAME_RELEASE + ;; + *:DragonFly:*:*) + DRAGONFLY_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` + GUESS=$UNAME_MACHINE-unknown-dragonfly$DRAGONFLY_REL + ;; + *:*VMS:*:*) + UNAME_MACHINE=`(uname -p) 2>/dev/null` + case $UNAME_MACHINE in + A*) GUESS=alpha-dec-vms ;; + I*) GUESS=ia64-dec-vms ;; + V*) GUESS=vax-dec-vms ;; + esac ;; + *:XENIX:*:SysV) + GUESS=i386-pc-xenix + ;; + i*86:skyos:*:*) + SKYOS_REL=`echo "$UNAME_RELEASE" | sed -e 's/ .*$//'` + GUESS=$UNAME_MACHINE-pc-skyos$SKYOS_REL + ;; + i*86:rdos:*:*) + GUESS=$UNAME_MACHINE-pc-rdos + ;; + i*86:Fiwix:*:*) + GUESS=$UNAME_MACHINE-pc-fiwix + ;; + *:AROS:*:*) + GUESS=$UNAME_MACHINE-unknown-aros + ;; + x86_64:VMkernel:*:*) + GUESS=$UNAME_MACHINE-unknown-esx + ;; + amd64:Isilon\ OneFS:*:*) + GUESS=x86_64-unknown-onefs + ;; + *:Unleashed:*:*) + GUESS=$UNAME_MACHINE-unknown-unleashed$UNAME_RELEASE + ;; +esac + +# Do we have a guess based on uname results? +if test "x$GUESS" != x; then + echo "$GUESS" + exit +fi + +# No uname command or uname output not recognized. +set_cc_for_build +cat > "$dummy.c" < +#include +#endif +#if defined(ultrix) || defined(_ultrix) || defined(__ultrix) || defined(__ultrix__) +#if defined (vax) || defined (__vax) || defined (__vax__) || defined(mips) || defined(__mips) || defined(__mips__) || defined(MIPS) || defined(__MIPS__) +#include +#if defined(_SIZE_T_) || defined(SIGLOST) +#include +#endif +#endif +#endif +main () +{ +#if defined (sony) +#if defined (MIPSEB) + /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, + I don't know.... */ + printf ("mips-sony-bsd\n"); exit (0); +#else +#include + printf ("m68k-sony-newsos%s\n", +#ifdef NEWSOS4 + "4" +#else + "" +#endif + ); exit (0); +#endif +#endif + +#if defined (NeXT) +#if !defined (__ARCHITECTURE__) +#define __ARCHITECTURE__ "m68k" +#endif + int version; + version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; + if (version < 4) + printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); + else + printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); + exit (0); +#endif + +#if defined (MULTIMAX) || defined (n16) +#if defined (UMAXV) + printf ("ns32k-encore-sysv\n"); exit (0); +#else +#if defined (CMU) + printf ("ns32k-encore-mach\n"); exit (0); +#else + printf ("ns32k-encore-bsd\n"); exit (0); +#endif +#endif +#endif + +#if defined (__386BSD__) + printf ("i386-pc-bsd\n"); exit (0); +#endif + +#if defined (sequent) +#if defined (i386) + printf ("i386-sequent-dynix\n"); exit (0); +#endif +#if defined (ns32000) + printf ("ns32k-sequent-dynix\n"); exit (0); +#endif +#endif + +#if defined (_SEQUENT_) + struct utsname un; + + uname(&un); + if (strncmp(un.version, "V2", 2) == 0) { + printf ("i386-sequent-ptx2\n"); exit (0); + } + if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ + printf ("i386-sequent-ptx1\n"); exit (0); + } + printf ("i386-sequent-ptx\n"); exit (0); +#endif + +#if defined (vax) +#if !defined (ultrix) +#include +#if defined (BSD) +#if BSD == 43 + printf ("vax-dec-bsd4.3\n"); exit (0); +#else +#if BSD == 199006 + printf ("vax-dec-bsd4.3reno\n"); exit (0); +#else + printf ("vax-dec-bsd\n"); exit (0); +#endif +#endif +#else + printf ("vax-dec-bsd\n"); exit (0); +#endif +#else +#if defined(_SIZE_T_) || defined(SIGLOST) + struct utsname un; + uname (&un); + printf ("vax-dec-ultrix%s\n", un.release); exit (0); +#else + printf ("vax-dec-ultrix\n"); exit (0); +#endif +#endif +#endif +#if defined(ultrix) || defined(_ultrix) || defined(__ultrix) || defined(__ultrix__) +#if defined(mips) || defined(__mips) || defined(__mips__) || defined(MIPS) || defined(__MIPS__) +#if defined(_SIZE_T_) || defined(SIGLOST) + struct utsname *un; + uname (&un); + printf ("mips-dec-ultrix%s\n", un.release); exit (0); +#else + printf ("mips-dec-ultrix\n"); exit (0); +#endif +#endif +#endif + +#if defined (alliant) && defined (i860) + printf ("i860-alliant-bsd\n"); exit (0); +#endif + + exit (1); +} +EOF + +$CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null && SYSTEM_NAME=`"$dummy"` && + { echo "$SYSTEM_NAME"; exit; } + +# Apollos put the system type in the environment. +test -d /usr/apollo && { echo "$ISP-apollo-$SYSTYPE"; exit; } + +echo "$0: unable to guess system type" >&2 + +case $UNAME_MACHINE:$UNAME_SYSTEM in + mips:Linux | mips64:Linux) + # If we got here on MIPS GNU/Linux, output extra information. + cat >&2 <&2 <&2 </dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null` + +hostinfo = `(hostinfo) 2>/dev/null` +/bin/universe = `(/bin/universe) 2>/dev/null` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` +/bin/arch = `(/bin/arch) 2>/dev/null` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` + +UNAME_MACHINE = "$UNAME_MACHINE" +UNAME_RELEASE = "$UNAME_RELEASE" +UNAME_SYSTEM = "$UNAME_SYSTEM" +UNAME_VERSION = "$UNAME_VERSION" +EOF +fi + +exit 1 + +# Local variables: +# eval: (add-hook 'before-save-hook 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/third_party/curl/config.sub b/third_party/curl/config.sub new file mode 100755 index 0000000..dba16e8 --- /dev/null +++ b/third_party/curl/config.sub @@ -0,0 +1,1890 @@ +#! /bin/sh +# Configuration validation subroutine script. +# Copyright 1992-2022 Free Software Foundation, Inc. + +# shellcheck disable=SC2006,SC2268 # see below for rationale + +timestamp='2022-01-03' + +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that +# program. This Exception is an additional permission under section 7 +# of the GNU General Public License, version 3 ("GPLv3"). + + +# Please send patches to . +# +# Configuration subroutine to validate and canonicalize a configuration type. +# Supply the specified configuration type as an argument. +# If it is invalid, we print an error message on stderr and exit with code 1. +# Otherwise, we print the canonical config type on stdout and succeed. + +# You can get the latest version of this script from: +# https://git.savannah.gnu.org/cgit/config.git/plain/config.sub + +# This file is supposed to be the same for all GNU packages +# and recognize all the CPU types, system types and aliases +# that are meaningful with *any* GNU software. +# Each package is responsible for reporting which valid configurations +# it does not support. The user should be able to distinguish +# a failure to support a valid configuration from a meaningless +# configuration. + +# The goal of this file is to map all the various variations of a given +# machine specification into a single specification in the form: +# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM +# or in some cases, the newer four-part form: +# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM +# It is wrong to echo any other type of specification. + +# The "shellcheck disable" line above the timestamp inhibits complaints +# about features and limitations of the classic Bourne shell that were +# superseded or lifted in POSIX. However, this script identifies a wide +# variety of pre-POSIX systems that do not have POSIX shells at all, and +# even some reasonably current systems (Solaris 10 as case-in-point) still +# have a pre-POSIX /bin/sh. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] CPU-MFR-OPSYS or ALIAS + +Canonicalize a configuration name. + +Options: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.sub ($timestamp) + +Copyright 1992-2022 Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" >&2 + exit 1 ;; + + *local*) + # First pass through any local machine types. + echo "$1" + exit ;; + + * ) + break ;; + esac +done + +case $# in + 0) echo "$me: missing argument$help" >&2 + exit 1;; + 1) ;; + *) echo "$me: too many arguments$help" >&2 + exit 1;; +esac + +# Split fields of configuration type +# shellcheck disable=SC2162 +saved_IFS=$IFS +IFS="-" read field1 field2 field3 field4 <&2 + exit 1 + ;; + *-*-*-*) + basic_machine=$field1-$field2 + basic_os=$field3-$field4 + ;; + *-*-*) + # Ambiguous whether COMPANY is present, or skipped and KERNEL-OS is two + # parts + maybe_os=$field2-$field3 + case $maybe_os in + nto-qnx* | linux-* | uclinux-uclibc* \ + | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* \ + | netbsd*-eabi* | kopensolaris*-gnu* | cloudabi*-eabi* \ + | storm-chaos* | os2-emx* | rtmk-nova*) + basic_machine=$field1 + basic_os=$maybe_os + ;; + android-linux) + basic_machine=$field1-unknown + basic_os=linux-android + ;; + *) + basic_machine=$field1-$field2 + basic_os=$field3 + ;; + esac + ;; + *-*) + # A lone config we happen to match not fitting any pattern + case $field1-$field2 in + decstation-3100) + basic_machine=mips-dec + basic_os= + ;; + *-*) + # Second component is usually, but not always the OS + case $field2 in + # Prevent following clause from handling this valid os + sun*os*) + basic_machine=$field1 + basic_os=$field2 + ;; + zephyr*) + basic_machine=$field1-unknown + basic_os=$field2 + ;; + # Manufacturers + dec* | mips* | sequent* | encore* | pc533* | sgi* | sony* \ + | att* | 7300* | 3300* | delta* | motorola* | sun[234]* \ + | unicom* | ibm* | next | hp | isi* | apollo | altos* \ + | convergent* | ncr* | news | 32* | 3600* | 3100* \ + | hitachi* | c[123]* | convex* | sun | crds | omron* | dg \ + | ultra | tti* | harris | dolphin | highlevel | gould \ + | cbm | ns | masscomp | apple | axis | knuth | cray \ + | microblaze* | sim | cisco \ + | oki | wec | wrs | winbond) + basic_machine=$field1-$field2 + basic_os= + ;; + *) + basic_machine=$field1 + basic_os=$field2 + ;; + esac + ;; + esac + ;; + *) + # Convert single-component short-hands not valid as part of + # multi-component configurations. + case $field1 in + 386bsd) + basic_machine=i386-pc + basic_os=bsd + ;; + a29khif) + basic_machine=a29k-amd + basic_os=udi + ;; + adobe68k) + basic_machine=m68010-adobe + basic_os=scout + ;; + alliant) + basic_machine=fx80-alliant + basic_os= + ;; + altos | altos3068) + basic_machine=m68k-altos + basic_os= + ;; + am29k) + basic_machine=a29k-none + basic_os=bsd + ;; + amdahl) + basic_machine=580-amdahl + basic_os=sysv + ;; + amiga) + basic_machine=m68k-unknown + basic_os= + ;; + amigaos | amigados) + basic_machine=m68k-unknown + basic_os=amigaos + ;; + amigaunix | amix) + basic_machine=m68k-unknown + basic_os=sysv4 + ;; + apollo68) + basic_machine=m68k-apollo + basic_os=sysv + ;; + apollo68bsd) + basic_machine=m68k-apollo + basic_os=bsd + ;; + aros) + basic_machine=i386-pc + basic_os=aros + ;; + aux) + basic_machine=m68k-apple + basic_os=aux + ;; + balance) + basic_machine=ns32k-sequent + basic_os=dynix + ;; + blackfin) + basic_machine=bfin-unknown + basic_os=linux + ;; + cegcc) + basic_machine=arm-unknown + basic_os=cegcc + ;; + convex-c1) + basic_machine=c1-convex + basic_os=bsd + ;; + convex-c2) + basic_machine=c2-convex + basic_os=bsd + ;; + convex-c32) + basic_machine=c32-convex + basic_os=bsd + ;; + convex-c34) + basic_machine=c34-convex + basic_os=bsd + ;; + convex-c38) + basic_machine=c38-convex + basic_os=bsd + ;; + cray) + basic_machine=j90-cray + basic_os=unicos + ;; + crds | unos) + basic_machine=m68k-crds + basic_os= + ;; + da30) + basic_machine=m68k-da30 + basic_os= + ;; + decstation | pmax | pmin | dec3100 | decstatn) + basic_machine=mips-dec + basic_os= + ;; + delta88) + basic_machine=m88k-motorola + basic_os=sysv3 + ;; + dicos) + basic_machine=i686-pc + basic_os=dicos + ;; + djgpp) + basic_machine=i586-pc + basic_os=msdosdjgpp + ;; + ebmon29k) + basic_machine=a29k-amd + basic_os=ebmon + ;; + es1800 | OSE68k | ose68k | ose | OSE) + basic_machine=m68k-ericsson + basic_os=ose + ;; + gmicro) + basic_machine=tron-gmicro + basic_os=sysv + ;; + go32) + basic_machine=i386-pc + basic_os=go32 + ;; + h8300hms) + basic_machine=h8300-hitachi + basic_os=hms + ;; + h8300xray) + basic_machine=h8300-hitachi + basic_os=xray + ;; + h8500hms) + basic_machine=h8500-hitachi + basic_os=hms + ;; + harris) + basic_machine=m88k-harris + basic_os=sysv3 + ;; + hp300 | hp300hpux) + basic_machine=m68k-hp + basic_os=hpux + ;; + hp300bsd) + basic_machine=m68k-hp + basic_os=bsd + ;; + hppaosf) + basic_machine=hppa1.1-hp + basic_os=osf + ;; + hppro) + basic_machine=hppa1.1-hp + basic_os=proelf + ;; + i386mach) + basic_machine=i386-mach + basic_os=mach + ;; + isi68 | isi) + basic_machine=m68k-isi + basic_os=sysv + ;; + m68knommu) + basic_machine=m68k-unknown + basic_os=linux + ;; + magnum | m3230) + basic_machine=mips-mips + basic_os=sysv + ;; + merlin) + basic_machine=ns32k-utek + basic_os=sysv + ;; + mingw64) + basic_machine=x86_64-pc + basic_os=mingw64 + ;; + mingw32) + basic_machine=i686-pc + basic_os=mingw32 + ;; + mingw32ce) + basic_machine=arm-unknown + basic_os=mingw32ce + ;; + monitor) + basic_machine=m68k-rom68k + basic_os=coff + ;; + morphos) + basic_machine=powerpc-unknown + basic_os=morphos + ;; + moxiebox) + basic_machine=moxie-unknown + basic_os=moxiebox + ;; + msdos) + basic_machine=i386-pc + basic_os=msdos + ;; + msys) + basic_machine=i686-pc + basic_os=msys + ;; + mvs) + basic_machine=i370-ibm + basic_os=mvs + ;; + nacl) + basic_machine=le32-unknown + basic_os=nacl + ;; + ncr3000) + basic_machine=i486-ncr + basic_os=sysv4 + ;; + netbsd386) + basic_machine=i386-pc + basic_os=netbsd + ;; + netwinder) + basic_machine=armv4l-rebel + basic_os=linux + ;; + news | news700 | news800 | news900) + basic_machine=m68k-sony + basic_os=newsos + ;; + news1000) + basic_machine=m68030-sony + basic_os=newsos + ;; + necv70) + basic_machine=v70-nec + basic_os=sysv + ;; + nh3000) + basic_machine=m68k-harris + basic_os=cxux + ;; + nh[45]000) + basic_machine=m88k-harris + basic_os=cxux + ;; + nindy960) + basic_machine=i960-intel + basic_os=nindy + ;; + mon960) + basic_machine=i960-intel + basic_os=mon960 + ;; + nonstopux) + basic_machine=mips-compaq + basic_os=nonstopux + ;; + os400) + basic_machine=powerpc-ibm + basic_os=os400 + ;; + OSE68000 | ose68000) + basic_machine=m68000-ericsson + basic_os=ose + ;; + os68k) + basic_machine=m68k-none + basic_os=os68k + ;; + paragon) + basic_machine=i860-intel + basic_os=osf + ;; + parisc) + basic_machine=hppa-unknown + basic_os=linux + ;; + psp) + basic_machine=mipsallegrexel-sony + basic_os=psp + ;; + pw32) + basic_machine=i586-unknown + basic_os=pw32 + ;; + rdos | rdos64) + basic_machine=x86_64-pc + basic_os=rdos + ;; + rdos32) + basic_machine=i386-pc + basic_os=rdos + ;; + rom68k) + basic_machine=m68k-rom68k + basic_os=coff + ;; + sa29200) + basic_machine=a29k-amd + basic_os=udi + ;; + sei) + basic_machine=mips-sei + basic_os=seiux + ;; + sequent) + basic_machine=i386-sequent + basic_os= + ;; + sps7) + basic_machine=m68k-bull + basic_os=sysv2 + ;; + st2000) + basic_machine=m68k-tandem + basic_os= + ;; + stratus) + basic_machine=i860-stratus + basic_os=sysv4 + ;; + sun2) + basic_machine=m68000-sun + basic_os= + ;; + sun2os3) + basic_machine=m68000-sun + basic_os=sunos3 + ;; + sun2os4) + basic_machine=m68000-sun + basic_os=sunos4 + ;; + sun3) + basic_machine=m68k-sun + basic_os= + ;; + sun3os3) + basic_machine=m68k-sun + basic_os=sunos3 + ;; + sun3os4) + basic_machine=m68k-sun + basic_os=sunos4 + ;; + sun4) + basic_machine=sparc-sun + basic_os= + ;; + sun4os3) + basic_machine=sparc-sun + basic_os=sunos3 + ;; + sun4os4) + basic_machine=sparc-sun + basic_os=sunos4 + ;; + sun4sol2) + basic_machine=sparc-sun + basic_os=solaris2 + ;; + sun386 | sun386i | roadrunner) + basic_machine=i386-sun + basic_os= + ;; + sv1) + basic_machine=sv1-cray + basic_os=unicos + ;; + symmetry) + basic_machine=i386-sequent + basic_os=dynix + ;; + t3e) + basic_machine=alphaev5-cray + basic_os=unicos + ;; + t90) + basic_machine=t90-cray + basic_os=unicos + ;; + toad1) + basic_machine=pdp10-xkl + basic_os=tops20 + ;; + tpf) + basic_machine=s390x-ibm + basic_os=tpf + ;; + udi29k) + basic_machine=a29k-amd + basic_os=udi + ;; + ultra3) + basic_machine=a29k-nyu + basic_os=sym1 + ;; + v810 | necv810) + basic_machine=v810-nec + basic_os=none + ;; + vaxv) + basic_machine=vax-dec + basic_os=sysv + ;; + vms) + basic_machine=vax-dec + basic_os=vms + ;; + vsta) + basic_machine=i386-pc + basic_os=vsta + ;; + vxworks960) + basic_machine=i960-wrs + basic_os=vxworks + ;; + vxworks68) + basic_machine=m68k-wrs + basic_os=vxworks + ;; + vxworks29k) + basic_machine=a29k-wrs + basic_os=vxworks + ;; + xbox) + basic_machine=i686-pc + basic_os=mingw32 + ;; + ymp) + basic_machine=ymp-cray + basic_os=unicos + ;; + *) + basic_machine=$1 + basic_os= + ;; + esac + ;; +esac + +# Decode 1-component or ad-hoc basic machines +case $basic_machine in + # Here we handle the default manufacturer of certain CPU types. It is in + # some cases the only manufacturer, in others, it is the most popular. + w89k) + cpu=hppa1.1 + vendor=winbond + ;; + op50n) + cpu=hppa1.1 + vendor=oki + ;; + op60c) + cpu=hppa1.1 + vendor=oki + ;; + ibm*) + cpu=i370 + vendor=ibm + ;; + orion105) + cpu=clipper + vendor=highlevel + ;; + mac | mpw | mac-mpw) + cpu=m68k + vendor=apple + ;; + pmac | pmac-mpw) + cpu=powerpc + vendor=apple + ;; + + # Recognize the various machine names and aliases which stand + # for a CPU type and a company and sometimes even an OS. + 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) + cpu=m68000 + vendor=att + ;; + 3b*) + cpu=we32k + vendor=att + ;; + bluegene*) + cpu=powerpc + vendor=ibm + basic_os=cnk + ;; + decsystem10* | dec10*) + cpu=pdp10 + vendor=dec + basic_os=tops10 + ;; + decsystem20* | dec20*) + cpu=pdp10 + vendor=dec + basic_os=tops20 + ;; + delta | 3300 | motorola-3300 | motorola-delta \ + | 3300-motorola | delta-motorola) + cpu=m68k + vendor=motorola + ;; + dpx2*) + cpu=m68k + vendor=bull + basic_os=sysv3 + ;; + encore | umax | mmax) + cpu=ns32k + vendor=encore + ;; + elxsi) + cpu=elxsi + vendor=elxsi + basic_os=${basic_os:-bsd} + ;; + fx2800) + cpu=i860 + vendor=alliant + ;; + genix) + cpu=ns32k + vendor=ns + ;; + h3050r* | hiux*) + cpu=hppa1.1 + vendor=hitachi + basic_os=hiuxwe2 + ;; + hp3k9[0-9][0-9] | hp9[0-9][0-9]) + cpu=hppa1.0 + vendor=hp + ;; + hp9k2[0-9][0-9] | hp9k31[0-9]) + cpu=m68000 + vendor=hp + ;; + hp9k3[2-9][0-9]) + cpu=m68k + vendor=hp + ;; + hp9k6[0-9][0-9] | hp6[0-9][0-9]) + cpu=hppa1.0 + vendor=hp + ;; + hp9k7[0-79][0-9] | hp7[0-79][0-9]) + cpu=hppa1.1 + vendor=hp + ;; + hp9k78[0-9] | hp78[0-9]) + # FIXME: really hppa2.0-hp + cpu=hppa1.1 + vendor=hp + ;; + hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) + # FIXME: really hppa2.0-hp + cpu=hppa1.1 + vendor=hp + ;; + hp9k8[0-9][13679] | hp8[0-9][13679]) + cpu=hppa1.1 + vendor=hp + ;; + hp9k8[0-9][0-9] | hp8[0-9][0-9]) + cpu=hppa1.0 + vendor=hp + ;; + i*86v32) + cpu=`echo "$1" | sed -e 's/86.*/86/'` + vendor=pc + basic_os=sysv32 + ;; + i*86v4*) + cpu=`echo "$1" | sed -e 's/86.*/86/'` + vendor=pc + basic_os=sysv4 + ;; + i*86v) + cpu=`echo "$1" | sed -e 's/86.*/86/'` + vendor=pc + basic_os=sysv + ;; + i*86sol2) + cpu=`echo "$1" | sed -e 's/86.*/86/'` + vendor=pc + basic_os=solaris2 + ;; + j90 | j90-cray) + cpu=j90 + vendor=cray + basic_os=${basic_os:-unicos} + ;; + iris | iris4d) + cpu=mips + vendor=sgi + case $basic_os in + irix*) + ;; + *) + basic_os=irix4 + ;; + esac + ;; + miniframe) + cpu=m68000 + vendor=convergent + ;; + *mint | mint[0-9]* | *MiNT | *MiNT[0-9]*) + cpu=m68k + vendor=atari + basic_os=mint + ;; + news-3600 | risc-news) + cpu=mips + vendor=sony + basic_os=newsos + ;; + next | m*-next) + cpu=m68k + vendor=next + case $basic_os in + openstep*) + ;; + nextstep*) + ;; + ns2*) + basic_os=nextstep2 + ;; + *) + basic_os=nextstep3 + ;; + esac + ;; + np1) + cpu=np1 + vendor=gould + ;; + op50n-* | op60c-*) + cpu=hppa1.1 + vendor=oki + basic_os=proelf + ;; + pa-hitachi) + cpu=hppa1.1 + vendor=hitachi + basic_os=hiuxwe2 + ;; + pbd) + cpu=sparc + vendor=tti + ;; + pbb) + cpu=m68k + vendor=tti + ;; + pc532) + cpu=ns32k + vendor=pc532 + ;; + pn) + cpu=pn + vendor=gould + ;; + power) + cpu=power + vendor=ibm + ;; + ps2) + cpu=i386 + vendor=ibm + ;; + rm[46]00) + cpu=mips + vendor=siemens + ;; + rtpc | rtpc-*) + cpu=romp + vendor=ibm + ;; + sde) + cpu=mipsisa32 + vendor=sde + basic_os=${basic_os:-elf} + ;; + simso-wrs) + cpu=sparclite + vendor=wrs + basic_os=vxworks + ;; + tower | tower-32) + cpu=m68k + vendor=ncr + ;; + vpp*|vx|vx-*) + cpu=f301 + vendor=fujitsu + ;; + w65) + cpu=w65 + vendor=wdc + ;; + w89k-*) + cpu=hppa1.1 + vendor=winbond + basic_os=proelf + ;; + none) + cpu=none + vendor=none + ;; + leon|leon[3-9]) + cpu=sparc + vendor=$basic_machine + ;; + leon-*|leon[3-9]-*) + cpu=sparc + vendor=`echo "$basic_machine" | sed 's/-.*//'` + ;; + + *-*) + # shellcheck disable=SC2162 + saved_IFS=$IFS + IFS="-" read cpu vendor <&2 + exit 1 + ;; + esac + ;; +esac + +# Here we canonicalize certain aliases for manufacturers. +case $vendor in + digital*) + vendor=dec + ;; + commodore*) + vendor=cbm + ;; + *) + ;; +esac + +# Decode manufacturer-specific aliases for certain operating systems. + +if test x$basic_os != x +then + +# First recognize some ad-hoc cases, or perhaps split kernel-os, or else just +# set os. +case $basic_os in + gnu/linux*) + kernel=linux + os=`echo "$basic_os" | sed -e 's|gnu/linux|gnu|'` + ;; + os2-emx) + kernel=os2 + os=`echo "$basic_os" | sed -e 's|os2-emx|emx|'` + ;; + nto-qnx*) + kernel=nto + os=`echo "$basic_os" | sed -e 's|nto-qnx|qnx|'` + ;; + *-*) + # shellcheck disable=SC2162 + saved_IFS=$IFS + IFS="-" read kernel os <&2 + exit 1 + ;; +esac + +# As a final step for OS-related things, validate the OS-kernel combination +# (given a valid OS), if there is a kernel. +case $kernel-$os in + linux-gnu* | linux-dietlibc* | linux-android* | linux-newlib* \ + | linux-musl* | linux-relibc* | linux-uclibc* ) + ;; + uclinux-uclibc* ) + ;; + -dietlibc* | -newlib* | -musl* | -relibc* | -uclibc* ) + # These are just libc implementations, not actual OSes, and thus + # require a kernel. + echo "Invalid configuration \`$1': libc \`$os' needs explicit kernel." 1>&2 + exit 1 + ;; + kfreebsd*-gnu* | kopensolaris*-gnu*) + ;; + vxworks-simlinux | vxworks-simwindows | vxworks-spe) + ;; + nto-qnx*) + ;; + os2-emx) + ;; + *-eabi* | *-gnueabi*) + ;; + -*) + # Blank kernel with real OS is always fine. + ;; + *-*) + echo "Invalid configuration \`$1': Kernel \`$kernel' not known to work with OS \`$os'." 1>&2 + exit 1 + ;; +esac + +# Here we handle the case where we know the os, and the CPU type, but not the +# manufacturer. We pick the logical manufacturer. +case $vendor in + unknown) + case $cpu-$os in + *-riscix*) + vendor=acorn + ;; + *-sunos*) + vendor=sun + ;; + *-cnk* | *-aix*) + vendor=ibm + ;; + *-beos*) + vendor=be + ;; + *-hpux*) + vendor=hp + ;; + *-mpeix*) + vendor=hp + ;; + *-hiux*) + vendor=hitachi + ;; + *-unos*) + vendor=crds + ;; + *-dgux*) + vendor=dg + ;; + *-luna*) + vendor=omron + ;; + *-genix*) + vendor=ns + ;; + *-clix*) + vendor=intergraph + ;; + *-mvs* | *-opened*) + vendor=ibm + ;; + *-os400*) + vendor=ibm + ;; + s390-* | s390x-*) + vendor=ibm + ;; + *-ptx*) + vendor=sequent + ;; + *-tpf*) + vendor=ibm + ;; + *-vxsim* | *-vxworks* | *-windiss*) + vendor=wrs + ;; + *-aux*) + vendor=apple + ;; + *-hms*) + vendor=hitachi + ;; + *-mpw* | *-macos*) + vendor=apple + ;; + *-*mint | *-mint[0-9]* | *-*MiNT | *-MiNT[0-9]*) + vendor=atari + ;; + *-vos*) + vendor=stratus + ;; + esac + ;; +esac + +echo "$cpu-$vendor-${kernel:+$kernel-}$os" +exit + +# Local variables: +# eval: (add-hook 'before-save-hook 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/third_party/curl/configure b/third_party/curl/configure new file mode 100755 index 0000000..42e8ee9 --- /dev/null +++ b/third_party/curl/configure @@ -0,0 +1,49133 @@ +#! /bin/sh +# Guess values for system-dependent variables and create Makefiles. +# Generated by GNU Autoconf 2.71 for curl -. +# +# Report bugs to . +# +# +# Copyright (C) 1992-1996, 1998-2017, 2020-2021 Free Software Foundation, +# Inc. +# +# +# This configure script is free software; the Free Software Foundation +# gives unlimited permission to copy, distribute and modify it. +# +# Copyright (C) Daniel Stenberg, +# This configure script may be copied, distributed and modified under the +# terms of the curl license; see COPYING for more details + +## -------------------------------- ## +## XC_CONFIGURE_PREAMBLE ver: 1.0 ## +## -------------------------------- ## + +xc_configure_preamble_ver_major='1' +xc_configure_preamble_ver_minor='0' + +# +# Set IFS to space, tab and newline. +# + +xc_space=' ' +xc_tab=' ' +xc_newline=' +' +IFS="$xc_space$xc_tab$xc_newline" + +# +# Set internationalization behavior variables. +# + +LANG='C' +LC_ALL='C' +LANGUAGE='C' +export LANG +export LC_ALL +export LANGUAGE + +# +# Some useful variables. +# + +xc_msg_warn='configure: WARNING:' +xc_msg_abrt='Can not continue.' +xc_msg_err='configure: error:' + +# +# Verify that 'echo' command is available, otherwise abort. +# + +xc_tst_str='unknown' +(`echo "$xc_tst_str" >/dev/null 2>&1`) && xc_tst_str='success' +case "x$xc_tst_str" in # (( + xsuccess) + : + ;; + *) + # Try built-in echo, and fail. + echo "$xc_msg_err 'echo' command not found. $xc_msg_abrt" >&2 + exit 1 + ;; +esac + +# +# Verify that 'test' command is available, otherwise abort. +# + +xc_tst_str='unknown' +(`test -n "$xc_tst_str" >/dev/null 2>&1`) && xc_tst_str='success' +case "x$xc_tst_str" in # (( + xsuccess) + : + ;; + *) + echo "$xc_msg_err 'test' command not found. $xc_msg_abrt" >&2 + exit 1 + ;; +esac + +# +# Verify that 'PATH' variable is set, otherwise abort. +# + +xc_tst_str='unknown' +(`test -n "$PATH" >/dev/null 2>&1`) && xc_tst_str='success' +case "x$xc_tst_str" in # (( + xsuccess) + : + ;; + *) + echo "$xc_msg_err 'PATH' variable not set. $xc_msg_abrt" >&2 + exit 1 + ;; +esac + +# +# Verify that 'expr' command is available, otherwise abort. +# + +xc_tst_str='unknown' +xc_tst_str=`expr "$xc_tst_str" : '.*' 2>/dev/null` +case "x$xc_tst_str" in # (( + x7) + : + ;; + *) + echo "$xc_msg_err 'expr' command not found. $xc_msg_abrt" >&2 + exit 1 + ;; +esac + +# +# Verify that 'sed' utility is found within 'PATH', otherwise abort. +# + +xc_tst_str='unknown' +xc_tst_str=`echo "$xc_tst_str" 2>/dev/null \ + | sed -e 's:unknown:success:' 2>/dev/null` +case "x$xc_tst_str" in # (( + xsuccess) + : + ;; + *) + echo "$xc_msg_err 'sed' utility not found in 'PATH'. $xc_msg_abrt" >&2 + exit 1 + ;; +esac + +# +# Verify that 'grep' utility is found within 'PATH', otherwise abort. +# + +xc_tst_str='unknown' +(`echo "$xc_tst_str" 2>/dev/null \ + | grep 'unknown' >/dev/null 2>&1`) && xc_tst_str='success' +case "x$xc_tst_str" in # (( + xsuccess) + : + ;; + *) + echo "$xc_msg_err 'grep' utility not found in 'PATH'. $xc_msg_abrt" >&2 + exit 1 + ;; +esac + +# +# Verify that 'tr' utility is found within 'PATH', otherwise abort. +# + +xc_tst_str="${xc_tab}98s7u6c5c4e3s2s10" +xc_tst_str=`echo "$xc_tst_str" 2>/dev/null \ + | tr -d "0123456789$xc_tab" 2>/dev/null` +case "x$xc_tst_str" in # (( + xsuccess) + : + ;; + *) + echo "$xc_msg_err 'tr' utility not found in 'PATH'. $xc_msg_abrt" >&2 + exit 1 + ;; +esac + +# +# Verify that 'wc' utility is found within 'PATH', otherwise abort. +# + +xc_tst_str='unknown unknown unknown unknown' +xc_tst_str=`echo "$xc_tst_str" 2>/dev/null \ + | wc -w 2>/dev/null | tr -d "$xc_space$xc_tab" 2>/dev/null` +case "x$xc_tst_str" in # (( + x4) + : + ;; + *) + echo "$xc_msg_err 'wc' utility not found in 'PATH'. $xc_msg_abrt" >&2 + exit 1 + ;; +esac + +# +# Verify that 'cat' utility is found within 'PATH', otherwise abort. +# + +xc_tst_str='unknown' +xc_tst_str=`cat <<_EOT 2>/dev/null \ + | wc -l 2>/dev/null | tr -d "$xc_space$xc_tab" 2>/dev/null +unknown +unknown +unknown +_EOT` +case "x$xc_tst_str" in # (( + x3) + : + ;; + *) + echo "$xc_msg_err 'cat' utility not found in 'PATH'. $xc_msg_abrt" >&2 + exit 1 + ;; +esac + +# +# Auto-detect and set 'PATH_SEPARATOR', unless it is already non-empty set. +# + +# Directory count in 'PATH' when using a colon separator. +xc_tst_dirs_col='x' +xc_tst_prev_IFS=$IFS; IFS=':' +for xc_tst_dir in $PATH; do + IFS=$xc_tst_prev_IFS + xc_tst_dirs_col="x$xc_tst_dirs_col" +done +IFS=$xc_tst_prev_IFS +xc_tst_dirs_col=`expr "$xc_tst_dirs_col" : '.*'` + +# Directory count in 'PATH' when using a semicolon separator. +xc_tst_dirs_sem='x' +xc_tst_prev_IFS=$IFS; IFS=';' +for xc_tst_dir in $PATH; do + IFS=$xc_tst_prev_IFS + xc_tst_dirs_sem="x$xc_tst_dirs_sem" +done +IFS=$xc_tst_prev_IFS +xc_tst_dirs_sem=`expr "$xc_tst_dirs_sem" : '.*'` + +if test $xc_tst_dirs_sem -eq $xc_tst_dirs_col; then + # When both counting methods give the same result we do not want to + # chose one over the other, and consider auto-detection not possible. + if test -z "$PATH_SEPARATOR"; then + # User should provide the correct 'PATH_SEPARATOR' definition. + # Until then, guess that it is colon! + echo "$xc_msg_warn path separator not determined, guessing colon" >&2 + PATH_SEPARATOR=':' + fi +else + # Separator with the greater directory count is the auto-detected one. + if test $xc_tst_dirs_sem -gt $xc_tst_dirs_col; then + xc_tst_auto_separator=';' + else + xc_tst_auto_separator=':' + fi + if test -z "$PATH_SEPARATOR"; then + # Simply use the auto-detected one when not already set. + PATH_SEPARATOR=$xc_tst_auto_separator + elif test "x$PATH_SEPARATOR" != "x$xc_tst_auto_separator"; then + echo "$xc_msg_warn 'PATH_SEPARATOR' does not match auto-detected one." >&2 + fi +fi +xc_PATH_SEPARATOR=$PATH_SEPARATOR + +xc_configure_preamble_result='yes' + + +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +as_nop=: +if test ${ZSH_VERSION+y} && (emulate sh) >/dev/null 2>&1 +then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else $as_nop + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + + +# Reset variables that may have inherited troublesome values from +# the environment. + +# IFS needs to be set, to space, tab, and newline, in precisely that order. +# (If _AS_PATH_WALK were called with IFS unset, it would have the +# side effect of setting IFS to empty, thus disabling word splitting.) +# Quoting is to prevent editors from complaining about space-tab. +as_nl=' +' +export as_nl +IFS=" "" $as_nl" + +PS1='$ ' +PS2='> ' +PS4='+ ' + +# Ensure predictable behavior from utilities with locale-dependent output. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# We cannot yet rely on "unset" to work, but we need these variables +# to be unset--not just set to an empty or harmless value--now, to +# avoid bugs in old shells (e.g. pre-3.0 UWIN ksh). This construct +# also avoids known problems related to "unset" and subshell syntax +# in other old shells (e.g. bash 2.01 and pdksh 5.2.14). +for as_var in BASH_ENV ENV MAIL MAILPATH CDPATH +do eval test \${$as_var+y} \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done + +# Ensure that fds 0, 1, and 2 are open. +if (exec 3>&0) 2>/dev/null; then :; else exec 0&1) 2>/dev/null; then :; else exec 1>/dev/null; fi +if (exec 3>&2) ; then :; else exec 2>/dev/null; fi + + + +# Find who we are. Look in the path if we contain no directory separator. +as_myself= +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + test -r "$as_dir$0" && as_myself=$as_dir$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + printf "%s\n" "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + + +# Use a proper internal environment variable to ensure we don't fall + # into an infinite loop, continuously re-executing ourselves. + if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then + _as_can_reexec=no; export _as_can_reexec; + # We cannot yet assume a decent shell, so we have to provide a +# neutralization value for shells without unset; and this also +# works around shells that cannot unset nonexistent variables. +# Preserve -v and -x to the replacement shell. +BASH_ENV=/dev/null +ENV=/dev/null +(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV +case $- in # (((( + *v*x* | *x*v* ) as_opts=-vx ;; + *v* ) as_opts=-v ;; + *x* ) as_opts=-x ;; + * ) as_opts= ;; +esac +exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} +# Admittedly, this is quite paranoid, since all the known shells bail +# out after a failed `exec'. +printf "%s\n" "$0: could not re-execute with $CONFIG_SHELL" >&2 +exit 255 + fi + # We don't want this to propagate to other subprocesses. + { _as_can_reexec=; unset _as_can_reexec;} +if test "x$CONFIG_SHELL" = x; then + as_bourne_compatible="as_nop=: +if test \${ZSH_VERSION+y} && (emulate sh) >/dev/null 2>&1 +then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST +else \$as_nop + case \`(set -o) 2>/dev/null\` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi +" + as_required="as_fn_return () { (exit \$1); } +as_fn_success () { as_fn_return 0; } +as_fn_failure () { as_fn_return 1; } +as_fn_ret_success () { return 0; } +as_fn_ret_failure () { return 1; } + +exitcode=0 +as_fn_success || { exitcode=1; echo as_fn_success failed.; } +as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } +as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } +as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } +if ( set x; as_fn_ret_success y && test x = \"\$1\" ) +then : + +else \$as_nop + exitcode=1; echo positional parameters were not saved. +fi +test x\$exitcode = x0 || exit 1 +blah=\$(echo \$(echo blah)) +test x\"\$blah\" = xblah || exit 1 +test -x / || exit 1" + as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO + as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO + eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && + test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 +test \$(( 1 + 1 )) = 2 || exit 1 + + test -n \"\${ZSH_VERSION+set}\${BASH_VERSION+set}\" || ( + ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' + ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO + ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO + PATH=/empty FPATH=/empty; export PATH FPATH + test \"X\`printf %s \$ECHO\`\" = \"X\$ECHO\" \\ + || test \"X\`print -r -- \$ECHO\`\" = \"X\$ECHO\" ) || exit 1" + if (eval "$as_required") 2>/dev/null +then : + as_have_required=yes +else $as_nop + as_have_required=no +fi + if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null +then : + +else $as_nop + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_found=false +for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + as_found=: + case $as_dir in #( + /*) + for as_base in sh bash ksh sh5; do + # Try only shells that exist, to save several forks. + as_shell=$as_dir$as_base + if { test -f "$as_shell" || test -f "$as_shell.exe"; } && + as_run=a "$as_shell" -c "$as_bourne_compatible""$as_required" 2>/dev/null +then : + CONFIG_SHELL=$as_shell as_have_required=yes + if as_run=a "$as_shell" -c "$as_bourne_compatible""$as_suggested" 2>/dev/null +then : + break 2 +fi +fi + done;; + esac + as_found=false +done +IFS=$as_save_IFS +if $as_found +then : + +else $as_nop + if { test -f "$SHELL" || test -f "$SHELL.exe"; } && + as_run=a "$SHELL" -c "$as_bourne_compatible""$as_required" 2>/dev/null +then : + CONFIG_SHELL=$SHELL as_have_required=yes +fi +fi + + + if test "x$CONFIG_SHELL" != x +then : + export CONFIG_SHELL + # We cannot yet assume a decent shell, so we have to provide a +# neutralization value for shells without unset; and this also +# works around shells that cannot unset nonexistent variables. +# Preserve -v and -x to the replacement shell. +BASH_ENV=/dev/null +ENV=/dev/null +(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV +case $- in # (((( + *v*x* | *x*v* ) as_opts=-vx ;; + *v* ) as_opts=-v ;; + *x* ) as_opts=-x ;; + * ) as_opts= ;; +esac +exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} +# Admittedly, this is quite paranoid, since all the known shells bail +# out after a failed `exec'. +printf "%s\n" "$0: could not re-execute with $CONFIG_SHELL" >&2 +exit 255 +fi + + if test x$as_have_required = xno +then : + printf "%s\n" "$0: This script requires a shell more modern than all" + printf "%s\n" "$0: the shells that I found on your system." + if test ${ZSH_VERSION+y} ; then + printf "%s\n" "$0: In particular, zsh $ZSH_VERSION has bugs and should" + printf "%s\n" "$0: be upgraded to zsh 4.3.4 or later." + else + printf "%s\n" "$0: Please tell bug-autoconf@gnu.org and a suitable curl +$0: mailing list: https://curl.se/mail/ about your system, +$0: including any error possibly output before this +$0: message. Then install a modern shell, or manually run +$0: the script under such a shell if you do have one." + fi + exit 1 +fi +fi +fi +SHELL=${CONFIG_SHELL-/bin/sh} +export SHELL +# Unset more variables known to interfere with behavior of common tools. +CLICOLOR_FORCE= GREP_OPTIONS= +unset CLICOLOR_FORCE GREP_OPTIONS + +## --------------------- ## +## M4sh Shell Functions. ## +## --------------------- ## +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset + + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit +# as_fn_nop +# --------- +# Do nothing but, unlike ":", preserve the value of $?. +as_fn_nop () +{ + return $? +} +as_nop=as_fn_nop + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`printf "%s\n" "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +printf "%s\n" X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p + +# as_fn_executable_p FILE +# ----------------------- +# Test if FILE is an executable regular file. +as_fn_executable_p () +{ + test -f "$1" && test -x "$1" +} # as_fn_executable_p +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null +then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else $as_nop + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null +then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else $as_nop + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + +# as_fn_nop +# --------- +# Do nothing but, unlike ":", preserve the value of $?. +as_fn_nop () +{ + return $? +} +as_nop=as_fn_nop + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + printf "%s\n" "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +printf "%s\n" X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + + + as_lineno_1=$LINENO as_lineno_1a=$LINENO + as_lineno_2=$LINENO as_lineno_2a=$LINENO + eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && + test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { + # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | + sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno + N + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ + t loop + s/-\n.*// + ' >$as_me.lineno && + chmod +x "$as_me.lineno" || + { printf "%s\n" "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } + + # If we had to re-execute with $CONFIG_SHELL, we're ensured to have + # already done that, so ensure we don't try to do so again and fall + # in an infinite loop. This has already happened in practice. + _as_can_reexec=no; export _as_can_reexec + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" + # Exit status is that of the last command. + exit +} + + +# Determine whether it's possible to make 'echo' print without a newline. +# These variables are no longer used directly by Autoconf, but are AC_SUBSTed +# for compatibility with existing Makefiles. +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +# For backward compatibility with old third-party macros, we provide +# the shell variables $as_echo and $as_echo_n. New code should use +# AS_ECHO(["message"]) and AS_ECHO_N(["message"]), respectively. +as_echo='printf %s\n' +as_echo_n='printf %s' + + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -pR'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -pR' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -pR' + fi +else + as_ln_s='cp -pR' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +as_test_x='test -x' +as_executable_p=as_fn_executable_p + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + +SHELL=${CONFIG_SHELL-/bin/sh} + + +test -n "$DJDIR" || exec 7<&0 &1 + +# Name of the host. +# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, +# so uname gets run too. +ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` + +# +# Initializations. +# +ac_default_prefix=/usr/local +ac_clean_files= +ac_config_libobj_dir=. +LIBOBJS= +cross_compiling=no +subdirs= +MFLAGS= +MAKEFLAGS= + +# Identity of this package. +PACKAGE_NAME='curl' +PACKAGE_TARNAME='curl' +PACKAGE_VERSION='-' +PACKAGE_STRING='curl -' +PACKAGE_BUGREPORT='a suitable curl mailing list: https://curl.se/mail/' +PACKAGE_URL='' + +ac_unique_file="lib/urldata.h" +# Factoring default headers for most tests. +ac_includes_default="\ +#include +#ifdef HAVE_STDIO_H +# include +#endif +#ifdef HAVE_STDLIB_H +# include +#endif +#ifdef HAVE_STRING_H +# include +#endif +#ifdef HAVE_INTTYPES_H +# include +#endif +#ifdef HAVE_STDINT_H +# include +#endif +#ifdef HAVE_STRINGS_H +# include +#endif +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_STAT_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif" + +ac_header_c_list= +ac_subst_vars='am__EXEEXT_FALSE +am__EXEEXT_TRUE +LTLIBOBJS +LIBOBJS +SSL_BACKENDS +SUPPORT_PROTOCOLS +SUPPORT_FEATURES +LIBCURL_NO_SHARED +ENABLE_STATIC +ENABLE_SHARED +CROSSCOMPILING_FALSE +CROSSCOMPILING_TRUE +BLANK_AT_MAKETIME +CURL_NETWORK_AND_TIME_LIBS +CURL_NETWORK_LIBS +LIBCURL_LIBS +CFLAG_CURL_SYMBOL_HIDING +DOING_CURL_SYMBOL_HIDING_FALSE +DOING_CURL_SYMBOL_HIDING_TRUE +USE_UNIX_SOCKETS +BUILD_LIBHOSTNAME_FALSE +BUILD_LIBHOSTNAME_TRUE +USE_ARES +USE_MANUAL_FALSE +USE_MANUAL_TRUE +BUILD_DOCS_FALSE +BUILD_DOCS_TRUE +PERL +USE_FISH_COMPLETION_FALSE +USE_FISH_COMPLETION_TRUE +FISH_FUNCTIONS_DIR +USE_ZSH_COMPLETION_FALSE +USE_ZSH_COMPLETION_TRUE +ZSH_FUNCTIONS_DIR +USE_MSH3 +USE_QUICHE +USE_OPENSSL_H3 +USE_NGTCP2_H3 +USE_NGHTTP3 +USE_OPENSSL_QUIC +USE_NGTCP2_CRYPTO_WOLFSSL +USE_NGTCP2_CRYPTO_GNUTLS +USE_NGTCP2_CRYPTO_BORINGSSL +USE_NGTCP2_CRYPTO_QUICTLS +USE_NGTCP2 +USE_NGHTTP2 +IDN_ENABLED +CURL_LT_SHLIB_USE_VERSIONED_SYMBOLS_FALSE +CURL_LT_SHLIB_USE_VERSIONED_SYMBOLS_TRUE +CURL_LT_SHLIB_VERSIONED_FLAVOUR +USE_LIBRTMP +USE_WOLFSSH +USE_LIBSSH +USE_LIBSSH2 +USE_GSASL_FALSE +USE_GSASL_TRUE +USE_LIBPSL_FALSE +USE_LIBPSL_TRUE +USE_LIBPSL +CURL_CA_BUNDLE +CURL_WITH_MULTI_SSL +SSL_ENABLED +USE_RUSTLS +USE_BEARSSL +USE_WOLFSSL +USE_MBEDTLS +HAVE_GNUTLS_SRP +USE_GNUTLS +HAVE_OPENSSL_QUIC +HAVE_OPENSSL_SRP +RANDOM_FILE +SSL_LIBS +USE_SECTRANSP +USE_WINDOWS_SSPI +USE_SCHANNEL +DEFAULT_SSL_BACKEND +BUILD_STUB_GSS_FALSE +BUILD_STUB_GSS_TRUE +IPV6_ENABLED +USE_OPENLDAP +HAVE_ZSTD +HAVE_BROTLI +ZLIB_LIBS +HAVE_LIBZ_FALSE +HAVE_LIBZ_TRUE +HAVE_LIBZ +HAVE_PROTO_BSDSOCKET_H +CURL_DISABLE_MQTT +CURL_DISABLE_GOPHER +CURL_DISABLE_SMTP +CURL_DISABLE_SMB +CURL_DISABLE_IMAP +CURL_DISABLE_POP3 +CURL_DISABLE_TFTP +CURL_DISABLE_TELNET +CURL_DISABLE_DICT +CURL_DISABLE_PROXY +USE_HYPER +PKGCONFIG +HAVE_LDAP_SSL +CURL_DISABLE_LDAPS +CURL_DISABLE_LDAP +CURL_DISABLE_FILE +CURL_DISABLE_FTP +CURL_DISABLE_RTSP +CURL_DISABLE_HTTP +HAVE_WINDRES_FALSE +HAVE_WINDRES_TRUE +USE_WIN32_CRYPTO +USE_WIN32_SMALL_FILES +USE_WIN32_LARGE_FILES +BUILD_UNITTESTS_FALSE +BUILD_UNITTESTS_TRUE +CURLDEBUG_FALSE +CURLDEBUG_TRUE +CURL_CFLAG_EXTRAS +DOING_NATIVE_WINDOWS_FALSE +DOING_NATIVE_WINDOWS_TRUE +USE_EXPLICIT_LIB_DEPS_FALSE +USE_EXPLICIT_LIB_DEPS_TRUE +REQUIRE_LIB_DEPS +CPPFLAG_CURL_STATICLIB +USE_CPPFLAG_CURL_STATICLIB_FALSE +USE_CPPFLAG_CURL_STATICLIB_TRUE +CURL_LT_SHLIB_USE_MIMPURE_TEXT_FALSE +CURL_LT_SHLIB_USE_MIMPURE_TEXT_TRUE +CURL_LT_SHLIB_USE_NO_UNDEFINED_FALSE +CURL_LT_SHLIB_USE_NO_UNDEFINED_TRUE +CURL_LT_SHLIB_USE_VERSION_INFO_FALSE +CURL_LT_SHLIB_USE_VERSION_INFO_TRUE +RC +LT_SYS_LIBRARY_PATH +OTOOL64 +OTOOL +LIPO +NMEDIT +DSYMUTIL +MANIFEST_TOOL +RANLIB +ac_ct_AR +FILECMD +LN_S +NM +ac_ct_DUMPBIN +DUMPBIN +LD +FGREP +LIBTOOL +OBJDUMP +DLLTOOL +AS +AR_FLAGS +host_os +host_vendor +host_cpu +host +build_os +build_vendor +build_cpu +build +HTTPD_NGHTTPX +APACHECTL +HTTPD +APXS +VSFTPD +CADDY +TEST_NGHTTPX +PKGADD_VENDOR +PKGADD_NAME +PKGADD_PKG +VERSIONNUM +CURLVERSION +CSCOPE +ETAGS +CTAGS +am__fastdepCC_FALSE +am__fastdepCC_TRUE +CCDEPMODE +am__nodep +AMDEPBACKSLASH +AMDEP_FALSE +AMDEP_TRUE +am__include +DEPDIR +am__untar +am__tar +AMTAR +am__leading_dot +SET_MAKE +AWK +mkdir_p +MKDIR_P +INSTALL_STRIP_PROGRAM +STRIP +install_sh +MAKEINFO +AUTOHEADER +AUTOMAKE +AUTOCONF +ACLOCAL +VERSION +PACKAGE +CYGPATH_W +am__isrc +LCOV +GCOV +CPP +OBJEXT +EXEEXT +ac_ct_CC +CPPFLAGS +LDFLAGS +CFLAGS +CC +INSTALL_DATA +INSTALL_SCRIPT +INSTALL_PROGRAM +libext +AR +EGREP +GREP +SED +CONFIGURE_OPTIONS +AM_BACKSLASH +AM_DEFAULT_VERBOSITY +AM_DEFAULT_V +AM_V +MAINT +MAINTAINER_MODE_FALSE +MAINTAINER_MODE_TRUE +target_alias +host_alias +build_alias +LIBS +ECHO_T +ECHO_N +ECHO_C +DEFS +mandir +localedir +libdir +psdir +pdfdir +dvidir +htmldir +infodir +docdir +oldincludedir +includedir +runstatedir +localstatedir +sharedstatedir +sysconfdir +datadir +datarootdir +libexecdir +sbindir +bindir +program_transform_name +prefix +exec_prefix +PACKAGE_URL +PACKAGE_BUGREPORT +PACKAGE_STRING +PACKAGE_VERSION +PACKAGE_TARNAME +PACKAGE_NAME +SHELL +PATH_SEPARATOR +am__quote' +ac_subst_files='' +ac_user_opts=' +enable_option_checking +enable_maintainer_mode +enable_silent_rules +enable_debug +enable_optimize +enable_warnings +enable_werror +enable_curldebug +enable_symbol_hiding +enable_ares +enable_rt +enable_httpsrr +enable_ech +enable_code_coverage +enable_dependency_tracking +with_schannel +with_secure_transport +with_amissl +with_ssl +with_openssl +with_gnutls +with_mbedtls +with_wolfssl +with_bearssl +with_rustls +with_test_nghttpx +with_test_caddy +with_test_vsftpd +with_test_httpd +with_darwinssl +enable_largefile +enable_shared +enable_static +with_pic +enable_fast_install +with_aix_soname +with_gnu_ld +with_sysroot +enable_libtool_lock +enable_http +enable_ftp +enable_file +enable_ldap +enable_ldaps +with_hyper +enable_rtsp +enable_proxy +enable_dict +enable_telnet +enable_tftp +enable_pop3 +enable_imap +enable_smb +enable_smtp +enable_gopher +enable_mqtt +enable_manual +enable_docs +enable_libcurl_option +enable_libgcc +with_zlib +with_brotli +with_zstd +with_ldap_lib +with_lber_lib +enable_ipv6 +with_gssapi_includes +with_gssapi_libs +with_gssapi +with_default_ssl_backend +with_random +enable_openssl_auto_load_config +with_ca_bundle +with_ca_path +with_ca_fallback +with_libpsl +with_libgsasl +with_libmetalink +with_libssh2 +with_libssh +with_wolfssh +with_librtmp +enable_versioned_symbols +with_winidn +with_libidn2 +with_nghttp2 +with_ngtcp2 +with_openssl_quic +with_nghttp3 +with_quiche +with_msh3 +with_zsh_functions_dir +with_fish_functions_dir +enable_threaded_resolver +enable_pthreads +enable_verbose +enable_sspi +enable_basic_auth +enable_bearer_auth +enable_digest_auth +enable_kerberos_auth +enable_negotiate_auth +enable_aws +enable_ntlm +enable_tls_srp +enable_unix_sockets +enable_cookies +enable_socketpair +enable_http_auth +enable_doh +enable_mime +enable_bindlocal +enable_form_api +enable_dateparse +enable_netrc +enable_progress_meter +enable_dnsshuffle +enable_get_easy_options +enable_alt_svc +enable_headers_api +enable_hsts +enable_websockets +' + ac_precious_vars='build_alias +host_alias +target_alias +CC +CFLAGS +LDFLAGS +LIBS +CPPFLAGS +CPP +LT_SYS_LIBRARY_PATH' + + +# Initialize some variables set by options. +ac_init_help= +ac_init_version=false +ac_unrecognized_opts= +ac_unrecognized_sep= +# The variables have the same names as the options, with +# dashes changed to underlines. +cache_file=/dev/null +exec_prefix=NONE +no_create= +no_recursion= +prefix=NONE +program_prefix=NONE +program_suffix=NONE +program_transform_name=s,x,x, +silent= +site= +srcdir= +verbose= +x_includes=NONE +x_libraries=NONE + +# Installation directory options. +# These are left unexpanded so users can "make install exec_prefix=/foo" +# and all the variables that are supposed to be based on exec_prefix +# by default will actually change. +# Use braces instead of parens because sh, perl, etc. also accept them. +# (The list follows the same order as the GNU Coding Standards.) +bindir='${exec_prefix}/bin' +sbindir='${exec_prefix}/sbin' +libexecdir='${exec_prefix}/libexec' +datarootdir='${prefix}/share' +datadir='${datarootdir}' +sysconfdir='${prefix}/etc' +sharedstatedir='${prefix}/com' +localstatedir='${prefix}/var' +runstatedir='${localstatedir}/run' +includedir='${prefix}/include' +oldincludedir='/usr/include' +docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' +infodir='${datarootdir}/info' +htmldir='${docdir}' +dvidir='${docdir}' +pdfdir='${docdir}' +psdir='${docdir}' +libdir='${exec_prefix}/lib' +localedir='${datarootdir}/locale' +mandir='${datarootdir}/man' + +ac_prev= +ac_dashdash= +for ac_option +do + # If the previous option needs an argument, assign it. + if test -n "$ac_prev"; then + eval $ac_prev=\$ac_option + ac_prev= + continue + fi + + case $ac_option in + *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; + *=) ac_optarg= ;; + *) ac_optarg=yes ;; + esac + + case $ac_dashdash$ac_option in + --) + ac_dashdash=yes ;; + + -bindir | --bindir | --bindi | --bind | --bin | --bi) + ac_prev=bindir ;; + -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) + bindir=$ac_optarg ;; + + -build | --build | --buil | --bui | --bu) + ac_prev=build_alias ;; + -build=* | --build=* | --buil=* | --bui=* | --bu=*) + build_alias=$ac_optarg ;; + + -cache-file | --cache-file | --cache-fil | --cache-fi \ + | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) + ac_prev=cache_file ;; + -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ + | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) + cache_file=$ac_optarg ;; + + --config-cache | -C) + cache_file=config.cache ;; + + -datadir | --datadir | --datadi | --datad) + ac_prev=datadir ;; + -datadir=* | --datadir=* | --datadi=* | --datad=*) + datadir=$ac_optarg ;; + + -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ + | --dataroo | --dataro | --datar) + ac_prev=datarootdir ;; + -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ + | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) + datarootdir=$ac_optarg ;; + + -disable-* | --disable-*) + ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: \`$ac_useropt'" + ac_useropt_orig=$ac_useropt + ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=no ;; + + -docdir | --docdir | --docdi | --doc | --do) + ac_prev=docdir ;; + -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) + docdir=$ac_optarg ;; + + -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) + ac_prev=dvidir ;; + -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) + dvidir=$ac_optarg ;; + + -enable-* | --enable-*) + ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: \`$ac_useropt'" + ac_useropt_orig=$ac_useropt + ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=\$ac_optarg ;; + + -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ + | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ + | --exec | --exe | --ex) + ac_prev=exec_prefix ;; + -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ + | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ + | --exec=* | --exe=* | --ex=*) + exec_prefix=$ac_optarg ;; + + -gas | --gas | --ga | --g) + # Obsolete; use --with-gas. + with_gas=yes ;; + + -help | --help | --hel | --he | -h) + ac_init_help=long ;; + -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) + ac_init_help=recursive ;; + -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) + ac_init_help=short ;; + + -host | --host | --hos | --ho) + ac_prev=host_alias ;; + -host=* | --host=* | --hos=* | --ho=*) + host_alias=$ac_optarg ;; + + -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) + ac_prev=htmldir ;; + -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ + | --ht=*) + htmldir=$ac_optarg ;; + + -includedir | --includedir | --includedi | --included | --include \ + | --includ | --inclu | --incl | --inc) + ac_prev=includedir ;; + -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ + | --includ=* | --inclu=* | --incl=* | --inc=*) + includedir=$ac_optarg ;; + + -infodir | --infodir | --infodi | --infod | --info | --inf) + ac_prev=infodir ;; + -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) + infodir=$ac_optarg ;; + + -libdir | --libdir | --libdi | --libd) + ac_prev=libdir ;; + -libdir=* | --libdir=* | --libdi=* | --libd=*) + libdir=$ac_optarg ;; + + -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ + | --libexe | --libex | --libe) + ac_prev=libexecdir ;; + -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ + | --libexe=* | --libex=* | --libe=*) + libexecdir=$ac_optarg ;; + + -localedir | --localedir | --localedi | --localed | --locale) + ac_prev=localedir ;; + -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) + localedir=$ac_optarg ;; + + -localstatedir | --localstatedir | --localstatedi | --localstated \ + | --localstate | --localstat | --localsta | --localst | --locals) + ac_prev=localstatedir ;; + -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ + | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) + localstatedir=$ac_optarg ;; + + -mandir | --mandir | --mandi | --mand | --man | --ma | --m) + ac_prev=mandir ;; + -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) + mandir=$ac_optarg ;; + + -nfp | --nfp | --nf) + # Obsolete; use --without-fp. + with_fp=no ;; + + -no-create | --no-create | --no-creat | --no-crea | --no-cre \ + | --no-cr | --no-c | -n) + no_create=yes ;; + + -no-recursion | --no-recursion | --no-recursio | --no-recursi \ + | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) + no_recursion=yes ;; + + -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ + | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ + | --oldin | --oldi | --old | --ol | --o) + ac_prev=oldincludedir ;; + -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ + | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ + | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) + oldincludedir=$ac_optarg ;; + + -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) + ac_prev=prefix ;; + -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) + prefix=$ac_optarg ;; + + -program-prefix | --program-prefix | --program-prefi | --program-pref \ + | --program-pre | --program-pr | --program-p) + ac_prev=program_prefix ;; + -program-prefix=* | --program-prefix=* | --program-prefi=* \ + | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) + program_prefix=$ac_optarg ;; + + -program-suffix | --program-suffix | --program-suffi | --program-suff \ + | --program-suf | --program-su | --program-s) + ac_prev=program_suffix ;; + -program-suffix=* | --program-suffix=* | --program-suffi=* \ + | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) + program_suffix=$ac_optarg ;; + + -program-transform-name | --program-transform-name \ + | --program-transform-nam | --program-transform-na \ + | --program-transform-n | --program-transform- \ + | --program-transform | --program-transfor \ + | --program-transfo | --program-transf \ + | --program-trans | --program-tran \ + | --progr-tra | --program-tr | --program-t) + ac_prev=program_transform_name ;; + -program-transform-name=* | --program-transform-name=* \ + | --program-transform-nam=* | --program-transform-na=* \ + | --program-transform-n=* | --program-transform-=* \ + | --program-transform=* | --program-transfor=* \ + | --program-transfo=* | --program-transf=* \ + | --program-trans=* | --program-tran=* \ + | --progr-tra=* | --program-tr=* | --program-t=*) + program_transform_name=$ac_optarg ;; + + -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) + ac_prev=pdfdir ;; + -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) + pdfdir=$ac_optarg ;; + + -psdir | --psdir | --psdi | --psd | --ps) + ac_prev=psdir ;; + -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) + psdir=$ac_optarg ;; + + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + silent=yes ;; + + -runstatedir | --runstatedir | --runstatedi | --runstated \ + | --runstate | --runstat | --runsta | --runst | --runs \ + | --run | --ru | --r) + ac_prev=runstatedir ;; + -runstatedir=* | --runstatedir=* | --runstatedi=* | --runstated=* \ + | --runstate=* | --runstat=* | --runsta=* | --runst=* | --runs=* \ + | --run=* | --ru=* | --r=*) + runstatedir=$ac_optarg ;; + + -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) + ac_prev=sbindir ;; + -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ + | --sbi=* | --sb=*) + sbindir=$ac_optarg ;; + + -sharedstatedir | --sharedstatedir | --sharedstatedi \ + | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ + | --sharedst | --shareds | --shared | --share | --shar \ + | --sha | --sh) + ac_prev=sharedstatedir ;; + -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ + | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ + | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ + | --sha=* | --sh=*) + sharedstatedir=$ac_optarg ;; + + -site | --site | --sit) + ac_prev=site ;; + -site=* | --site=* | --sit=*) + site=$ac_optarg ;; + + -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) + ac_prev=srcdir ;; + -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) + srcdir=$ac_optarg ;; + + -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ + | --syscon | --sysco | --sysc | --sys | --sy) + ac_prev=sysconfdir ;; + -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ + | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) + sysconfdir=$ac_optarg ;; + + -target | --target | --targe | --targ | --tar | --ta | --t) + ac_prev=target_alias ;; + -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) + target_alias=$ac_optarg ;; + + -v | -verbose | --verbose | --verbos | --verbo | --verb) + verbose=yes ;; + + -version | --version | --versio | --versi | --vers | -V) + ac_init_version=: ;; + + -with-* | --with-*) + ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: \`$ac_useropt'" + ac_useropt_orig=$ac_useropt + ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=\$ac_optarg ;; + + -without-* | --without-*) + ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: \`$ac_useropt'" + ac_useropt_orig=$ac_useropt + ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=no ;; + + --x) + # Obsolete; use --with-x. + with_x=yes ;; + + -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ + | --x-incl | --x-inc | --x-in | --x-i) + ac_prev=x_includes ;; + -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ + | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) + x_includes=$ac_optarg ;; + + -x-libraries | --x-libraries | --x-librarie | --x-librari \ + | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) + ac_prev=x_libraries ;; + -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ + | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) + x_libraries=$ac_optarg ;; + + -*) as_fn_error $? "unrecognized option: \`$ac_option' +Try \`$0 --help' for more information" + ;; + + *=*) + ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` + # Reject names that are not valid shell variable names. + case $ac_envvar in #( + '' | [0-9]* | *[!_$as_cr_alnum]* ) + as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; + esac + eval $ac_envvar=\$ac_optarg + export $ac_envvar ;; + + *) + # FIXME: should be removed in autoconf 3.0. + printf "%s\n" "$as_me: WARNING: you should use --build, --host, --target" >&2 + expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && + printf "%s\n" "$as_me: WARNING: invalid host type: $ac_option" >&2 + : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" + ;; + + esac +done + +if test -n "$ac_prev"; then + ac_option=--`echo $ac_prev | sed 's/_/-/g'` + as_fn_error $? "missing argument to $ac_option" +fi + +if test -n "$ac_unrecognized_opts"; then + case $enable_option_checking in + no) ;; + fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; + *) printf "%s\n" "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; + esac +fi + +# Check all directory arguments for consistency. +for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ + datadir sysconfdir sharedstatedir localstatedir includedir \ + oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ + libdir localedir mandir runstatedir +do + eval ac_val=\$$ac_var + # Remove trailing slashes. + case $ac_val in + */ ) + ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` + eval $ac_var=\$ac_val;; + esac + # Be sure to have absolute directory names. + case $ac_val in + [\\/$]* | ?:[\\/]* ) continue;; + NONE | '' ) case $ac_var in *prefix ) continue;; esac;; + esac + as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" +done + +# There might be people who depend on the old broken behavior: `$host' +# used to hold the argument of --host etc. +# FIXME: To remove some day. +build=$build_alias +host=$host_alias +target=$target_alias + +# FIXME: To remove some day. +if test "x$host_alias" != x; then + if test "x$build_alias" = x; then + cross_compiling=maybe + elif test "x$build_alias" != "x$host_alias"; then + cross_compiling=yes + fi +fi + +ac_tool_prefix= +test -n "$host_alias" && ac_tool_prefix=$host_alias- + +test "$silent" = yes && exec 6>/dev/null + + +ac_pwd=`pwd` && test -n "$ac_pwd" && +ac_ls_di=`ls -di .` && +ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || + as_fn_error $? "working directory cannot be determined" +test "X$ac_ls_di" = "X$ac_pwd_ls_di" || + as_fn_error $? "pwd does not report name of working directory" + + +# Find the source files, if location was not specified. +if test -z "$srcdir"; then + ac_srcdir_defaulted=yes + # Try the directory containing this script, then the parent directory. + ac_confdir=`$as_dirname -- "$as_myself" || +$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_myself" : 'X\(//\)[^/]' \| \ + X"$as_myself" : 'X\(//\)$' \| \ + X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || +printf "%s\n" X"$as_myself" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + srcdir=$ac_confdir + if test ! -r "$srcdir/$ac_unique_file"; then + srcdir=.. + fi +else + ac_srcdir_defaulted=no +fi +if test ! -r "$srcdir/$ac_unique_file"; then + test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." + as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" +fi +ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" +ac_abs_confdir=`( + cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" + pwd)` +# When building in place, set srcdir=. +if test "$ac_abs_confdir" = "$ac_pwd"; then + srcdir=. +fi +# Remove unnecessary trailing slashes from srcdir. +# Double slashes in file names in object file debugging info +# mess up M-x gdb in Emacs. +case $srcdir in +*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; +esac +for ac_var in $ac_precious_vars; do + eval ac_env_${ac_var}_set=\${${ac_var}+set} + eval ac_env_${ac_var}_value=\$${ac_var} + eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} + eval ac_cv_env_${ac_var}_value=\$${ac_var} +done + +# +# Report the --help message. +# +if test "$ac_init_help" = "long"; then + # Omit some internal or obsolete options to make the list less imposing. + # This message is too long to be a string in the A/UX 3.1 sh. + cat <<_ACEOF +\`configure' configures curl - to adapt to many kinds of systems. + +Usage: $0 [OPTION]... [VAR=VALUE]... + +To assign environment variables (e.g., CC, CFLAGS...), specify them as +VAR=VALUE. See below for descriptions of some of the useful variables. + +Defaults for the options are specified in brackets. + +Configuration: + -h, --help display this help and exit + --help=short display options specific to this package + --help=recursive display the short help of all the included packages + -V, --version display version information and exit + -q, --quiet, --silent do not print \`checking ...' messages + --cache-file=FILE cache test results in FILE [disabled] + -C, --config-cache alias for \`--cache-file=config.cache' + -n, --no-create do not create output files + --srcdir=DIR find the sources in DIR [configure dir or \`..'] + +Installation directories: + --prefix=PREFIX install architecture-independent files in PREFIX + [$ac_default_prefix] + --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX + [PREFIX] + +By default, \`make install' will install all the files in +\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify +an installation prefix other than \`$ac_default_prefix' using \`--prefix', +for instance \`--prefix=\$HOME'. + +For better control, use the options below. + +Fine tuning of the installation directories: + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --runstatedir=DIR modifiable per-process data [LOCALSTATEDIR/run] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/curl] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] +_ACEOF + + cat <<\_ACEOF + +Program names: + --program-prefix=PREFIX prepend PREFIX to installed program names + --program-suffix=SUFFIX append SUFFIX to installed program names + --program-transform-name=PROGRAM run sed PROGRAM on installed program names + +System types: + --build=BUILD configure for building on BUILD [guessed] + --host=HOST cross-compile to build programs to run on HOST [BUILD] +_ACEOF +fi + +if test -n "$ac_init_help"; then + case $ac_init_help in + short | recursive ) echo "Configuration of curl -:";; + esac + cat <<\_ACEOF + +Optional Features: + --disable-option-checking ignore unrecognized --enable/--with options + --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) + --enable-FEATURE[=ARG] include FEATURE [ARG=yes] + --enable-maintainer-mode + enable make rules and dependencies not useful (and + sometimes confusing) to the casual installer + --enable-silent-rules less verbose build output (undo: "make V=1") + --disable-silent-rules verbose build output (undo: "make V=0") + --enable-debug Enable debug build options + --disable-debug Disable debug build options + --enable-optimize Enable compiler optimizations + --disable-optimize Disable compiler optimizations + --enable-warnings Enable strict compiler warnings + --disable-warnings Disable strict compiler warnings + --enable-werror Enable compiler warnings as errors + --disable-werror Disable compiler warnings as errors + --enable-curldebug Enable curl debug memory tracking + --disable-curldebug Disable curl debug memory tracking + --enable-symbol-hiding Enable hiding of library internal symbols + --disable-symbol-hiding Disable hiding of library internal symbols + --enable-ares[=PATH] Enable c-ares for DNS lookups + --disable-ares Disable c-ares for DNS lookups + --disable-rt disable dependency on -lrt + --enable-httpsrr Enable HTTPSRR support + --disable-httpsrr Disable HTTPSRR support + --enable-ech Enable ECH support + --disable-ech Disable ECH support + --enable-code-coverage Provide code coverage + --enable-dependency-tracking + do not reject slow dependency extractors + --disable-dependency-tracking + speeds up one-time build + --disable-largefile omit support for large files + --enable-shared[=PKGS] build shared libraries [default=yes] + --enable-static[=PKGS] build static libraries [default=yes] + --enable-fast-install[=PKGS] + optimize for fast installation [default=yes] + --disable-libtool-lock avoid locking (might break parallel builds) + --enable-http Enable HTTP support + --disable-http Disable HTTP support + --enable-ftp Enable FTP support + --disable-ftp Disable FTP support + --enable-file Enable FILE support + --disable-file Disable FILE support + --enable-ldap Enable LDAP support + --disable-ldap Disable LDAP support + --enable-ldaps Enable LDAPS support + --disable-ldaps Disable LDAPS support + --enable-rtsp Enable RTSP support + --disable-rtsp Disable RTSP support + --enable-proxy Enable proxy support + --disable-proxy Disable proxy support + --enable-dict Enable DICT support + --disable-dict Disable DICT support + --enable-telnet Enable TELNET support + --disable-telnet Disable TELNET support + --enable-tftp Enable TFTP support + --disable-tftp Disable TFTP support + --enable-pop3 Enable POP3 support + --disable-pop3 Disable POP3 support + --enable-imap Enable IMAP support + --disable-imap Disable IMAP support + --enable-smb Enable SMB/CIFS support + --disable-smb Disable SMB/CIFS support + --enable-smtp Enable SMTP support + --disable-smtp Disable SMTP support + --enable-gopher Enable Gopher support + --disable-gopher Disable Gopher support + --enable-mqtt Enable MQTT support + --disable-mqtt Disable MQTT support + --enable-manual Enable built-in manual + --disable-manual Disable built-in manual + --enable-docs Enable documentation + --disable-docs Disable documentation + --enable-libcurl-option Enable --libcurl C code generation support + --disable-libcurl-option + Disable --libcurl C code generation support + --enable-libgcc use libgcc when linking + --enable-ipv6 Enable IPv6 (with IPv4) support + --disable-ipv6 Disable IPv6 support + --enable-openssl-auto-load-config + Enable automatic loading of OpenSSL configuration + --disable-openssl-auto-load-config + Disable automatic loading of OpenSSL configuration + --enable-versioned-symbols + Enable versioned symbols in shared library + --disable-versioned-symbols + Disable versioned symbols in shared library + --enable-threaded-resolver + Enable threaded resolver + --disable-threaded-resolver + Disable threaded resolver + --enable-pthreads Enable POSIX threads (default for threaded resolver) + --disable-pthreads Disable POSIX threads + --enable-verbose Enable verbose strings + --disable-verbose Disable verbose strings + --enable-sspi Enable SSPI + --disable-sspi Disable SSPI + --enable-basic-auth Enable basic authentication (default) + --disable-basic-auth Disable basic authentication + --enable-bearer-auth Enable bearer authentication (default) + --disable-bearer-auth Disable bearer authentication + --enable-digest-auth Enable digest authentication (default) + --disable-digest-auth Disable digest authentication + --enable-kerberos-auth Enable kerberos authentication (default) + --disable-kerberos-auth Disable kerberos authentication + --enable-negotiate-auth Enable negotiate authentication (default) + --disable-negotiate-auth + Disable negotiate authentication + --enable-aws Enable AWS sig support (default) + --disable-aws Disable AWS sig support + --enable-ntlm Enable NTLM support + --disable-ntlm Disable NTLM support + --enable-tls-srp Enable TLS-SRP authentication + --disable-tls-srp Disable TLS-SRP authentication + --enable-unix-sockets Enable Unix domain sockets + --disable-unix-sockets Disable Unix domain sockets + --enable-cookies Enable cookies support + --disable-cookies Disable cookies support + --enable-socketpair Enable socketpair support + --disable-socketpair Disable socketpair support + --enable-http-auth Enable HTTP authentication support + --disable-http-auth Disable HTTP authentication support + --enable-doh Enable DoH support + --disable-doh Disable DoH support + --enable-mime Enable mime API support + --disable-mime Disable mime API support + --enable-bindlocal Enable local binding support + --disable-bindlocal Disable local binding support + --enable-form-api Enable form API support + --disable-form-api Disable form API support + --enable-dateparse Enable date parsing + --disable-dateparse Disable date parsing + --enable-netrc Enable netrc parsing + --disable-netrc Disable netrc parsing + --enable-progress-meter Enable progress-meter + --disable-progress-meter + Disable progress-meter + --enable-dnsshuffle Enable DNS shuffling + --disable-dnsshuffle Disable DNS shuffling + --enable-get-easy-options + Enable curl_easy_options + --disable-get-easy-options + Disable curl_easy_options + --enable-alt-svc Enable alt-svc support + --disable-alt-svc Disable alt-svc support + --enable-headers-api Enable headers-api support + --disable-headers-api Disable headers-api support + --enable-hsts Enable HSTS support + --disable-hsts Disable HSTS support + --enable-websockets Enable WebSockets support + --disable-websockets Disable WebSockets support + +Optional Packages: + --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] + --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) + --with-schannel enable Windows native SSL/TLS + --with-secure-transport enable Apple OS native SSL/TLS + --with-amissl enable Amiga native SSL/TLS (AmiSSL) + --with-ssl=PATH old version of --with-openssl + --without-ssl build without any TLS library + --with-openssl=PATH Where to look for OpenSSL, PATH points to the SSL + installation (default: /usr/local/ssl); when + possible, set the PKG_CONFIG_PATH environment + variable instead of using this option + --with-gnutls=PATH where to look for GnuTLS, PATH points to the + installation root + --with-mbedtls=PATH where to look for mbedTLS, PATH points to the + installation root + --with-wolfssl=PATH where to look for WolfSSL, PATH points to the + installation root (default: system lib default) + --with-bearssl=PATH where to look for BearSSL, PATH points to the + installation root + --with-rustls=PATH where to look for rustls, PATH points to the + installation root + --with-test-nghttpx=PATH + where to find nghttpx for testing + --with-test-caddy=PATH where to find caddy for testing + --with-test-vsftpd=PATH where to find vsftpd for testing + --with-test-httpd=PATH where to find httpd/apache2 for testing + + --with-pic[=PKGS] try to use only PIC/non-PIC objects [default=use + both] + --with-aix-soname=aix|svr4|both + shared library versioning (aka "SONAME") variant to + provide on AIX, [default=aix]. + --with-gnu-ld assume the C compiler uses GNU ld [default=no] + --with-sysroot[=DIR] Search for dependent libraries within DIR (or the + compiler's sysroot if not specified). + --with-hyper=PATH Enable hyper usage + --without-hyper Disable hyper usage + --with-zlib=PATH search for zlib in PATH + --without-zlib disable use of zlib + --with-brotli=PATH Where to look for brotli, PATH points to the BROTLI + installation; when possible, set the PKG_CONFIG_PATH + environment variable instead of using this option + --without-brotli disable BROTLI + --with-zstd=PATH Where to look for libzstd, PATH points to the + libzstd installation; when possible, set the + PKG_CONFIG_PATH environment variable instead of + using this option + --without-zstd disable libzstd + --with-ldap-lib=libname Specify name of ldap lib file + --with-lber-lib=libname Specify name of lber lib file + --with-gssapi-includes=DIR + Specify location of GSS-API headers + --with-gssapi-libs=DIR Specify location of GSS-API libs + --with-gssapi=DIR Where to look for GSS-API + --with-default-ssl-backend=NAME + Use NAME as default SSL backend + --without-default-ssl-backend + Use implicit default SSL backend + --with-random=FILE read randomness from FILE (default=/dev/urandom) + --with-ca-bundle=FILE Path to a file containing CA certificates (example: + /etc/ca-bundle.crt) + --without-ca-bundle Don't use a default CA bundle + --with-ca-path=DIRECTORY + Path to a directory containing CA certificates + stored individually, with their filenames in a hash + format. This option can be used with the OpenSSL, + GnuTLS, mbedTLS and wolfSSL backends. Refer to + OpenSSL c_rehash for details. (example: + /etc/certificates) + --without-ca-path Don't use a default CA path + --with-ca-fallback Use the built in CA store of the SSL library + --without-ca-fallback Don't use the built in CA store of the SSL library + --with-libpsl=PATH Where to look for libpsl, PATH points to the LIBPSL + installation; when possible, set the PKG_CONFIG_PATH + environment variable instead of using this option + --without-libpsl disable LIBPSL + --without-libgsasl disable libgsasl support for SCRAM + --with-libssh2=PATH Where to look for libssh2, PATH points to the + libssh2 installation; when possible, set the + PKG_CONFIG_PATH environment variable instead of + using this option + --with-libssh2 enable libssh2 + --with-libssh=PATH Where to look for libssh, PATH points to the libssh + installation; when possible, set the PKG_CONFIG_PATH + environment variable instead of using this option + --with-libssh enable libssh + --with-wolfssh=PATH Where to look for wolfssh, PATH points to the + wolfSSH installation; when possible, set the + PKG_CONFIG_PATH environment variable instead of + using this option + --with-wolfssh enable wolfssh + --with-librtmp=PATH Where to look for librtmp, PATH points to the + LIBRTMP installation; when possible, set the + PKG_CONFIG_PATH environment variable instead of + using this option + --without-librtmp disable LIBRTMP + --with-winidn=PATH enable Windows native IDN + --without-winidn disable Windows native IDN + --with-libidn2=PATH Enable libidn2 usage + --without-libidn2 Disable libidn2 usage + --with-nghttp2=PATH Enable nghttp2 usage + --without-nghttp2 Disable nghttp2 usage + --with-ngtcp2=PATH Enable ngtcp2 usage + --without-ngtcp2 Disable ngtcp2 usage + --with-openssl-quic Enable OpenSSL QUIC usage + --without-openssl-quic Disable OpenSSL QUIC usage + --with-nghttp3=PATH Enable nghttp3 usage + --without-nghttp3 Disable nghttp3 usage + --with-quiche=PATH Enable quiche usage + --without-quiche Disable quiche usage + --with-msh3=PATH Enable msh3 usage + --without-msh3 Disable msh3 usage + --with-zsh-functions-dir=PATH + Install zsh completions to PATH + --without-zsh-functions-dir + Do not install zsh completions + --with-fish-functions-dir=PATH + Install fish completions to PATH + --without-fish-functions-dir + Do not install fish completions + +Some influential environment variables: + CC C compiler command + CFLAGS C compiler flags + LDFLAGS linker flags, e.g. -L if you have libraries in a + nonstandard directory + LIBS libraries to pass to the linker, e.g. -l + CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if + you have headers in a nonstandard directory + CPP C preprocessor + LT_SYS_LIBRARY_PATH + User-defined run-time library search path. + +Use these variables to override the choices made by `configure' or to help +it to find libraries and programs with nonstandard names/locations. + +Report bugs to . +_ACEOF +ac_status=$? +fi + +if test "$ac_init_help" = "recursive"; then + # If there are subdirs, report their specific --help. + for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue + test -d "$ac_dir" || + { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || + continue + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`printf "%s\n" "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`printf "%s\n" "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + cd "$ac_dir" || { ac_status=$?; continue; } + # Check for configure.gnu first; this name is used for a wrapper for + # Metaconfig's "Configure" on case-insensitive file systems. + if test -f "$ac_srcdir/configure.gnu"; then + echo && + $SHELL "$ac_srcdir/configure.gnu" --help=recursive + elif test -f "$ac_srcdir/configure"; then + echo && + $SHELL "$ac_srcdir/configure" --help=recursive + else + printf "%s\n" "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + fi || ac_status=$? + cd "$ac_pwd" || { ac_status=$?; break; } + done +fi + +test -n "$ac_init_help" && exit $ac_status +if $ac_init_version; then + cat <<\_ACEOF +curl configure - +generated by GNU Autoconf 2.71 + +Copyright (C) 2021 Free Software Foundation, Inc. +This configure script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it. + +Copyright (C) Daniel Stenberg, +This configure script may be copied, distributed and modified under the +terms of the curl license; see COPYING for more details +_ACEOF + exit +fi + +## ------------------------ ## +## Autoconf initialization. ## +## ------------------------ ## + +# ac_fn_c_try_compile LINENO +# -------------------------- +# Try to compile conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext conftest.beam + if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext +then : + ac_retval=0 +else $as_nop + printf "%s\n" "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_compile + +# ac_fn_c_try_cpp LINENO +# ---------------------- +# Try to preprocess conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_cpp () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } > conftest.i && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + } +then : + ac_retval=0 +else $as_nop + printf "%s\n" "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_cpp + +# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists and can be compiled using the include files in +# INCLUDES, setting the cache variable VAR accordingly. +ac_fn_c_check_header_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +printf %s "checking for $2... " >&6; } +if eval test \${$3+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + eval "$3=yes" +else $as_nop + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +eval ac_res=\$$3 + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +printf "%s\n" "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_header_compile + +# ac_fn_c_try_link LINENO +# ----------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_link () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext conftest.beam conftest$ac_exeext + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + test -x conftest$ac_exeext + } +then : + ac_retval=0 +else $as_nop + printf "%s\n" "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information + # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would + # interfere with the next link command; also delete a directory that is + # left behind by Apple's compiler. We do this before executing the actions. + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_link + +# ac_fn_c_check_func LINENO FUNC VAR +# ---------------------------------- +# Tests whether FUNC exists, setting the cache variable VAR accordingly +ac_fn_c_check_func () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +printf %s "checking for $2... " >&6; } +if eval test \${$3+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#define $2 innocuous_$2 +#ifdef __STDC__ +# include +#else +# include +#endif +#undef $2 +#ifdef __cplusplus +extern "C" +#endif +char $2 (); +#if defined __stub_$2 || defined __stub___$2 +choke me +#endif + +int main (void) +{ +return $2 (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + eval "$3=yes" +else $as_nop + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +fi +eval ac_res=\$$3 + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +printf "%s\n" "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_func + +# ac_fn_c_try_run LINENO +# ---------------------- +# Try to run conftest.$ac_ext, and return whether this succeeded. Assumes that +# executables *can* be run. +ac_fn_c_try_run () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } +then : + ac_retval=0 +else $as_nop + printf "%s\n" "$as_me: program exited with status $ac_status" >&5 + printf "%s\n" "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=$ac_status +fi + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_run + +# ac_fn_c_check_type LINENO SIZEOF_LONG_LONG VAR INCLUDES +# ------------------------------------------------------- +# Tests whether TYPE exists after having included INCLUDES, setting cache +# variable VAR accordingly. +ac_fn_c_check_type () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +printf %s "checking for $2... " >&6; } +if eval test \${$3+y} +then : + printf %s "(cached) " >&6 +else $as_nop + eval "$3=no" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int main (void) +{ +if (sizeof ($2)) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int main (void) +{ +if (sizeof (($2))) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + +else $as_nop + eval "$3=yes" +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +eval ac_res=\$$3 + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +printf "%s\n" "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_type + +# ac_fn_check_decl LINENO SYMBOL VAR INCLUDES EXTRA-OPTIONS FLAG-VAR +# ------------------------------------------------------------------ +# Tests whether SYMBOL is declared in INCLUDES, setting cache variable VAR +# accordingly. Pass EXTRA-OPTIONS to the compiler, using FLAG-VAR. +ac_fn_check_decl () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + as_decl_name=`echo $2|sed 's/ *(.*//'` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $as_decl_name is declared" >&5 +printf %s "checking whether $as_decl_name is declared... " >&6; } +if eval test \${$3+y} +then : + printf %s "(cached) " >&6 +else $as_nop + as_decl_use=`echo $2|sed -e 's/(/((/' -e 's/)/) 0&/' -e 's/,/) 0& (/g'` + eval ac_save_FLAGS=\$$6 + as_fn_append $6 " $5" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int main (void) +{ +#ifndef $as_decl_name +#ifdef __cplusplus + (void) $as_decl_use; +#else + (void) $as_decl_name; +#endif +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + eval "$3=yes" +else $as_nop + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + eval $6=\$ac_save_FLAGS + +fi +eval ac_res=\$$3 + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +printf "%s\n" "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_check_decl + +# ac_fn_c_check_member LINENO AGGR MEMBER VAR INCLUDES +# ---------------------------------------------------- +# Tries to find if the field MEMBER exists in type AGGR, after including +# INCLUDES, setting cache variable VAR accordingly. +ac_fn_c_check_member () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $2.$3" >&5 +printf %s "checking for $2.$3... " >&6; } +if eval test \${$4+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$5 +int main (void) +{ +static $2 ac_aggr; +if (ac_aggr.$3) +return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + eval "$4=yes" +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$5 +int main (void) +{ +static $2 ac_aggr; +if (sizeof ac_aggr.$3) +return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + eval "$4=yes" +else $as_nop + eval "$4=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +eval ac_res=\$$4 + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +printf "%s\n" "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_member +ac_configure_args_raw= +for ac_arg +do + case $ac_arg in + *\'*) + ac_arg=`printf "%s\n" "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + as_fn_append ac_configure_args_raw " '$ac_arg'" +done + +case $ac_configure_args_raw in + *$as_nl*) + ac_safe_unquote= ;; + *) + ac_unsafe_z='|&;<>()$`\\"*?[ '' ' # This string ends in space, tab. + ac_unsafe_a="$ac_unsafe_z#~" + ac_safe_unquote="s/ '\\([^$ac_unsafe_a][^$ac_unsafe_z]*\\)'/ \\1/g" + ac_configure_args_raw=` printf "%s\n" "$ac_configure_args_raw" | sed "$ac_safe_unquote"`;; +esac + +cat >config.log <<_ACEOF +This file contains any messages produced by compilers while +running configure, to aid debugging if configure makes a mistake. + +It was created by curl $as_me -, which was +generated by GNU Autoconf 2.71. Invocation command line was + + $ $0$ac_configure_args_raw + +_ACEOF +exec 5>>config.log +{ +cat <<_ASUNAME +## --------- ## +## Platform. ## +## --------- ## + +hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` + +/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` +/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` +/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` +/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` + +_ASUNAME + +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + printf "%s\n" "PATH: $as_dir" + done +IFS=$as_save_IFS + +} >&5 + +cat >&5 <<_ACEOF + + +## ----------- ## +## Core tests. ## +## ----------- ## + +_ACEOF + + +# Keep a trace of the command line. +# Strip out --no-create and --no-recursion so they do not pile up. +# Strip out --silent because we don't want to record it for future runs. +# Also quote any args containing shell meta-characters. +# Make two passes to allow for proper duplicate-argument suppression. +ac_configure_args= +ac_configure_args0= +ac_configure_args1= +ac_must_keep_next=false +for ac_pass in 1 2 +do + for ac_arg + do + case $ac_arg in + -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + continue ;; + *\'*) + ac_arg=`printf "%s\n" "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + case $ac_pass in + 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; + 2) + as_fn_append ac_configure_args1 " '$ac_arg'" + if test $ac_must_keep_next = true; then + ac_must_keep_next=false # Got value, back to normal. + else + case $ac_arg in + *=* | --config-cache | -C | -disable-* | --disable-* \ + | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ + | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ + | -with-* | --with-* | -without-* | --without-* | --x) + case "$ac_configure_args0 " in + "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; + esac + ;; + -* ) ac_must_keep_next=true ;; + esac + fi + as_fn_append ac_configure_args " '$ac_arg'" + ;; + esac + done +done +{ ac_configure_args0=; unset ac_configure_args0;} +{ ac_configure_args1=; unset ac_configure_args1;} + +# When interrupted or exit'd, cleanup temporary files, and complete +# config.log. We remove comments because anyway the quotes in there +# would cause problems or look ugly. +# WARNING: Use '\'' to represent an apostrophe within the trap. +# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. +trap 'exit_status=$? + # Sanitize IFS. + IFS=" "" $as_nl" + # Save into config.log some information that might help in debugging. + { + echo + + printf "%s\n" "## ---------------- ## +## Cache variables. ## +## ---------------- ##" + echo + # The following way of writing the cache mishandles newlines in values, +( + for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +printf "%s\n" "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + (set) 2>&1 | + case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + sed -n \ + "s/'\''/'\''\\\\'\'''\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" + ;; #( + *) + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) + echo + + printf "%s\n" "## ----------------- ## +## Output variables. ## +## ----------------- ##" + echo + for ac_var in $ac_subst_vars + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`printf "%s\n" "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + printf "%s\n" "$ac_var='\''$ac_val'\''" + done | sort + echo + + if test -n "$ac_subst_files"; then + printf "%s\n" "## ------------------- ## +## File substitutions. ## +## ------------------- ##" + echo + for ac_var in $ac_subst_files + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`printf "%s\n" "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + printf "%s\n" "$ac_var='\''$ac_val'\''" + done | sort + echo + fi + + if test -s confdefs.h; then + printf "%s\n" "## ----------- ## +## confdefs.h. ## +## ----------- ##" + echo + cat confdefs.h + echo + fi + test "$ac_signal" != 0 && + printf "%s\n" "$as_me: caught signal $ac_signal" + printf "%s\n" "$as_me: exit $exit_status" + } >&5 + rm -f core *.core core.conftest.* && + rm -f -r conftest* confdefs* conf$$* $ac_clean_files && + exit $exit_status +' 0 +for ac_signal in 1 2 13 15; do + trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal +done +ac_signal=0 + +# confdefs.h avoids OS command line length limits that DEFS can exceed. +rm -f -r conftest* confdefs.h + +printf "%s\n" "/* confdefs.h */" > confdefs.h + +# Predefined preprocessor variables. + +printf "%s\n" "#define PACKAGE_NAME \"$PACKAGE_NAME\"" >>confdefs.h + +printf "%s\n" "#define PACKAGE_TARNAME \"$PACKAGE_TARNAME\"" >>confdefs.h + +printf "%s\n" "#define PACKAGE_VERSION \"$PACKAGE_VERSION\"" >>confdefs.h + +printf "%s\n" "#define PACKAGE_STRING \"$PACKAGE_STRING\"" >>confdefs.h + +printf "%s\n" "#define PACKAGE_BUGREPORT \"$PACKAGE_BUGREPORT\"" >>confdefs.h + +printf "%s\n" "#define PACKAGE_URL \"$PACKAGE_URL\"" >>confdefs.h + + +# Let the site file select an alternate cache file if it wants to. +# Prefer an explicitly selected file to automatically selected ones. +if test -n "$CONFIG_SITE"; then + ac_site_files="$CONFIG_SITE" +elif test "x$prefix" != xNONE; then + ac_site_files="$prefix/share/config.site $prefix/etc/config.site" +else + ac_site_files="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site" +fi + +for ac_site_file in $ac_site_files +do + case $ac_site_file in #( + */*) : + ;; #( + *) : + ac_site_file=./$ac_site_file ;; +esac + if test -f "$ac_site_file" && test -r "$ac_site_file"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 +printf "%s\n" "$as_me: loading site script $ac_site_file" >&6;} + sed 's/^/| /' "$ac_site_file" >&5 + . "$ac_site_file" \ + || { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "failed to load site script $ac_site_file +See \`config.log' for more details" "$LINENO" 5; } + fi +done + +if test -r "$cache_file"; then + # Some versions of bash will fail to source /dev/null (special files + # actually), so we avoid doing that. DJGPP emulates it as a regular file. + if test /dev/null != "$cache_file" && test -f "$cache_file"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 +printf "%s\n" "$as_me: loading cache $cache_file" >&6;} + case $cache_file in + [\\/]* | ?:[\\/]* ) . "$cache_file";; + *) . "./$cache_file";; + esac + fi +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 +printf "%s\n" "$as_me: creating cache $cache_file" >&6;} + >$cache_file +fi + +# Test code for whether the C compiler supports C89 (global declarations) +ac_c_conftest_c89_globals=' +/* Does the compiler advertise C89 conformance? + Do not test the value of __STDC__, because some compilers set it to 0 + while being otherwise adequately conformant. */ +#if !defined __STDC__ +# error "Compiler does not advertise C89 conformance" +#endif + +#include +#include +struct stat; +/* Most of the following tests are stolen from RCS 5.7 src/conf.sh. */ +struct buf { int x; }; +struct buf * (*rcsopen) (struct buf *, struct stat *, int); +static char *e (p, i) + char **p; + int i; +{ + return p[i]; +} +static char *f (char * (*g) (char **, int), char **p, ...) +{ + char *s; + va_list v; + va_start (v,p); + s = g (p, va_arg (v,int)); + va_end (v); + return s; +} + +/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has + function prototypes and stuff, but not \xHH hex character constants. + These do not provoke an error unfortunately, instead are silently treated + as an "x". The following induces an error, until -std is added to get + proper ANSI mode. Curiously \x00 != x always comes out true, for an + array size at least. It is necessary to write \x00 == 0 to get something + that is true only with -std. */ +int osf4_cc_array ['\''\x00'\'' == 0 ? 1 : -1]; + +/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters + inside strings and character constants. */ +#define FOO(x) '\''x'\'' +int xlc6_cc_array[FOO(a) == '\''x'\'' ? 1 : -1]; + +int test (int i, double x); +struct s1 {int (*f) (int a);}; +struct s2 {int (*f) (double a);}; +int pairnames (int, char **, int *(*)(struct buf *, struct stat *, int), + int, int);' + +# Test code for whether the C compiler supports C89 (body of main). +ac_c_conftest_c89_main=' +ok |= (argc == 0 || f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]); +' + +# Test code for whether the C compiler supports C99 (global declarations) +ac_c_conftest_c99_globals=' +// Does the compiler advertise C99 conformance? +#if !defined __STDC_VERSION__ || __STDC_VERSION__ < 199901L +# error "Compiler does not advertise C99 conformance" +#endif + +#include +extern int puts (const char *); +extern int printf (const char *, ...); +extern int dprintf (int, const char *, ...); +extern void *malloc (size_t); + +// Check varargs macros. These examples are taken from C99 6.10.3.5. +// dprintf is used instead of fprintf to avoid needing to declare +// FILE and stderr. +#define debug(...) dprintf (2, __VA_ARGS__) +#define showlist(...) puts (#__VA_ARGS__) +#define report(test,...) ((test) ? puts (#test) : printf (__VA_ARGS__)) +static void +test_varargs_macros (void) +{ + int x = 1234; + int y = 5678; + debug ("Flag"); + debug ("X = %d\n", x); + showlist (The first, second, and third items.); + report (x>y, "x is %d but y is %d", x, y); +} + +// Check long long types. +#define BIG64 18446744073709551615ull +#define BIG32 4294967295ul +#define BIG_OK (BIG64 / BIG32 == 4294967297ull && BIG64 % BIG32 == 0) +#if !BIG_OK + #error "your preprocessor is broken" +#endif +#if BIG_OK +#else + #error "your preprocessor is broken" +#endif +static long long int bignum = -9223372036854775807LL; +static unsigned long long int ubignum = BIG64; + +struct incomplete_array +{ + int datasize; + double data[]; +}; + +struct named_init { + int number; + const wchar_t *name; + double average; +}; + +typedef const char *ccp; + +static inline int +test_restrict (ccp restrict text) +{ + // See if C++-style comments work. + // Iterate through items via the restricted pointer. + // Also check for declarations in for loops. + for (unsigned int i = 0; *(text+i) != '\''\0'\''; ++i) + continue; + return 0; +} + +// Check varargs and va_copy. +static bool +test_varargs (const char *format, ...) +{ + va_list args; + va_start (args, format); + va_list args_copy; + va_copy (args_copy, args); + + const char *str = ""; + int number = 0; + float fnumber = 0; + + while (*format) + { + switch (*format++) + { + case '\''s'\'': // string + str = va_arg (args_copy, const char *); + break; + case '\''d'\'': // int + number = va_arg (args_copy, int); + break; + case '\''f'\'': // float + fnumber = va_arg (args_copy, double); + break; + default: + break; + } + } + va_end (args_copy); + va_end (args); + + return *str && number && fnumber; +} +' + +# Test code for whether the C compiler supports C99 (body of main). +ac_c_conftest_c99_main=' + // Check bool. + _Bool success = false; + success |= (argc != 0); + + // Check restrict. + if (test_restrict ("String literal") == 0) + success = true; + char *restrict newvar = "Another string"; + + // Check varargs. + success &= test_varargs ("s, d'\'' f .", "string", 65, 34.234); + test_varargs_macros (); + + // Check flexible array members. + struct incomplete_array *ia = + malloc (sizeof (struct incomplete_array) + (sizeof (double) * 10)); + ia->datasize = 10; + for (int i = 0; i < ia->datasize; ++i) + ia->data[i] = i * 1.234; + + // Check named initializers. + struct named_init ni = { + .number = 34, + .name = L"Test wide string", + .average = 543.34343, + }; + + ni.number = 58; + + int dynamic_array[ni.number]; + dynamic_array[0] = argv[0][0]; + dynamic_array[ni.number - 1] = 543; + + // work around unused variable warnings + ok |= (!success || bignum == 0LL || ubignum == 0uLL || newvar[0] == '\''x'\'' + || dynamic_array[ni.number - 1] != 543); +' + +# Test code for whether the C compiler supports C11 (global declarations) +ac_c_conftest_c11_globals=' +// Does the compiler advertise C11 conformance? +#if !defined __STDC_VERSION__ || __STDC_VERSION__ < 201112L +# error "Compiler does not advertise C11 conformance" +#endif + +// Check _Alignas. +char _Alignas (double) aligned_as_double; +char _Alignas (0) no_special_alignment; +extern char aligned_as_int; +char _Alignas (0) _Alignas (int) aligned_as_int; + +// Check _Alignof. +enum +{ + int_alignment = _Alignof (int), + int_array_alignment = _Alignof (int[100]), + char_alignment = _Alignof (char) +}; +_Static_assert (0 < -_Alignof (int), "_Alignof is signed"); + +// Check _Noreturn. +int _Noreturn does_not_return (void) { for (;;) continue; } + +// Check _Static_assert. +struct test_static_assert +{ + int x; + _Static_assert (sizeof (int) <= sizeof (long int), + "_Static_assert does not work in struct"); + long int y; +}; + +// Check UTF-8 literals. +#define u8 syntax error! +char const utf8_literal[] = u8"happens to be ASCII" "another string"; + +// Check duplicate typedefs. +typedef long *long_ptr; +typedef long int *long_ptr; +typedef long_ptr long_ptr; + +// Anonymous structures and unions -- taken from C11 6.7.2.1 Example 1. +struct anonymous +{ + union { + struct { int i; int j; }; + struct { int k; long int l; } w; + }; + int m; +} v1; +' + +# Test code for whether the C compiler supports C11 (body of main). +ac_c_conftest_c11_main=' + _Static_assert ((offsetof (struct anonymous, i) + == offsetof (struct anonymous, w.k)), + "Anonymous union alignment botch"); + v1.i = 2; + v1.w.k = 5; + ok |= v1.i != 5; +' + +# Test code for whether the C compiler supports C11 (complete). +ac_c_conftest_c11_program="${ac_c_conftest_c89_globals} +${ac_c_conftest_c99_globals} +${ac_c_conftest_c11_globals} + +int +main (int argc, char **argv) +{ + int ok = 0; + ${ac_c_conftest_c89_main} + ${ac_c_conftest_c99_main} + ${ac_c_conftest_c11_main} + return ok; +} +" + +# Test code for whether the C compiler supports C99 (complete). +ac_c_conftest_c99_program="${ac_c_conftest_c89_globals} +${ac_c_conftest_c99_globals} + +int +main (int argc, char **argv) +{ + int ok = 0; + ${ac_c_conftest_c89_main} + ${ac_c_conftest_c99_main} + return ok; +} +" + +# Test code for whether the C compiler supports C89 (complete). +ac_c_conftest_c89_program="${ac_c_conftest_c89_globals} + +int +main (int argc, char **argv) +{ + int ok = 0; + ${ac_c_conftest_c89_main} + return ok; +} +" + +as_fn_append ac_header_c_list " stdio.h stdio_h HAVE_STDIO_H" +as_fn_append ac_header_c_list " stdlib.h stdlib_h HAVE_STDLIB_H" +as_fn_append ac_header_c_list " string.h string_h HAVE_STRING_H" +as_fn_append ac_header_c_list " inttypes.h inttypes_h HAVE_INTTYPES_H" +as_fn_append ac_header_c_list " stdint.h stdint_h HAVE_STDINT_H" +as_fn_append ac_header_c_list " strings.h strings_h HAVE_STRINGS_H" +as_fn_append ac_header_c_list " sys/stat.h sys_stat_h HAVE_SYS_STAT_H" +as_fn_append ac_header_c_list " sys/types.h sys_types_h HAVE_SYS_TYPES_H" +as_fn_append ac_header_c_list " unistd.h unistd_h HAVE_UNISTD_H" + +# Auxiliary files required by this configure script. +ac_aux_files="ltmain.sh config.guess config.sub missing compile install-sh" + +# Locations in which to look for auxiliary files. +ac_aux_dir_candidates="${srcdir}${PATH_SEPARATOR}${srcdir}/..${PATH_SEPARATOR}${srcdir}/../.." + +# Search for a directory containing all of the required auxiliary files, +# $ac_aux_files, from the $PATH-style list $ac_aux_dir_candidates. +# If we don't find one directory that contains all the files we need, +# we report the set of missing files from the *first* directory in +# $ac_aux_dir_candidates and give up. +ac_missing_aux_files="" +ac_first_candidate=: +printf "%s\n" "$as_me:${as_lineno-$LINENO}: looking for aux files: $ac_aux_files" >&5 +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_found=false +for as_dir in $ac_aux_dir_candidates +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + as_found=: + + printf "%s\n" "$as_me:${as_lineno-$LINENO}: trying $as_dir" >&5 + ac_aux_dir_found=yes + ac_install_sh= + for ac_aux in $ac_aux_files + do + # As a special case, if "install-sh" is required, that requirement + # can be satisfied by any of "install-sh", "install.sh", or "shtool", + # and $ac_install_sh is set appropriately for whichever one is found. + if test x"$ac_aux" = x"install-sh" + then + if test -f "${as_dir}install-sh"; then + printf "%s\n" "$as_me:${as_lineno-$LINENO}: ${as_dir}install-sh found" >&5 + ac_install_sh="${as_dir}install-sh -c" + elif test -f "${as_dir}install.sh"; then + printf "%s\n" "$as_me:${as_lineno-$LINENO}: ${as_dir}install.sh found" >&5 + ac_install_sh="${as_dir}install.sh -c" + elif test -f "${as_dir}shtool"; then + printf "%s\n" "$as_me:${as_lineno-$LINENO}: ${as_dir}shtool found" >&5 + ac_install_sh="${as_dir}shtool install -c" + else + ac_aux_dir_found=no + if $ac_first_candidate; then + ac_missing_aux_files="${ac_missing_aux_files} install-sh" + else + break + fi + fi + else + if test -f "${as_dir}${ac_aux}"; then + printf "%s\n" "$as_me:${as_lineno-$LINENO}: ${as_dir}${ac_aux} found" >&5 + else + ac_aux_dir_found=no + if $ac_first_candidate; then + ac_missing_aux_files="${ac_missing_aux_files} ${ac_aux}" + else + break + fi + fi + fi + done + if test "$ac_aux_dir_found" = yes; then + ac_aux_dir="$as_dir" + break + fi + ac_first_candidate=false + + as_found=false +done +IFS=$as_save_IFS +if $as_found +then : + +else $as_nop + as_fn_error $? "cannot find required auxiliary files:$ac_missing_aux_files" "$LINENO" 5 +fi + + +# These three variables are undocumented and unsupported, +# and are intended to be withdrawn in a future Autoconf release. +# They can cause serious problems if a builder's source tree is in a directory +# whose full name contains unusual characters. +if test -f "${ac_aux_dir}config.guess"; then + ac_config_guess="$SHELL ${ac_aux_dir}config.guess" +fi +if test -f "${ac_aux_dir}config.sub"; then + ac_config_sub="$SHELL ${ac_aux_dir}config.sub" +fi +if test -f "$ac_aux_dir/configure"; then + ac_configure="$SHELL ${ac_aux_dir}configure" +fi + +# Check that the precious variables saved in the cache have kept the same +# value. +ac_cache_corrupted=false +for ac_var in $ac_precious_vars; do + eval ac_old_set=\$ac_cv_env_${ac_var}_set + eval ac_new_set=\$ac_env_${ac_var}_set + eval ac_old_val=\$ac_cv_env_${ac_var}_value + eval ac_new_val=\$ac_env_${ac_var}_value + case $ac_old_set,$ac_new_set in + set,) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +printf "%s\n" "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,set) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 +printf "%s\n" "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,);; + *) + if test "x$ac_old_val" != "x$ac_new_val"; then + # differences in whitespace do not lead to failure. + ac_old_val_w=`echo x $ac_old_val` + ac_new_val_w=`echo x $ac_new_val` + if test "$ac_old_val_w" != "$ac_new_val_w"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 +printf "%s\n" "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + ac_cache_corrupted=: + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 +printf "%s\n" "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + eval $ac_var=\$ac_old_val + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 +printf "%s\n" "$as_me: former value: \`$ac_old_val'" >&2;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 +printf "%s\n" "$as_me: current value: \`$ac_new_val'" >&2;} + fi;; + esac + # Pass precious variables to config.status. + if test "$ac_new_set" = set; then + case $ac_new_val in + *\'*) ac_arg=$ac_var=`printf "%s\n" "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *) ac_arg=$ac_var=$ac_new_val ;; + esac + case " $ac_configure_args " in + *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. + *) as_fn_append ac_configure_args " '$ac_arg'" ;; + esac + fi +done +if $ac_cache_corrupted; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 +printf "%s\n" "$as_me: error: changes in the environment can compromise the build" >&2;} + as_fn_error $? "run \`${MAKE-make} distclean' and/or \`rm $cache_file' + and start over" "$LINENO" 5 +fi +## -------------------- ## +## Main body of script. ## +## -------------------- ## + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + + + + + +# using curl-override.m4 + + + + + +ac_config_headers="$ac_config_headers lib/curl_config.h" + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable maintainer-specific portions of Makefiles" >&5 +printf %s "checking whether to enable maintainer-specific portions of Makefiles... " >&6; } + # Check whether --enable-maintainer-mode was given. +if test ${enable_maintainer_mode+y} +then : + enableval=$enable_maintainer_mode; USE_MAINTAINER_MODE=$enableval +else $as_nop + USE_MAINTAINER_MODE=no +fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $USE_MAINTAINER_MODE" >&5 +printf "%s\n" "$USE_MAINTAINER_MODE" >&6; } + if test $USE_MAINTAINER_MODE = yes; then + MAINTAINER_MODE_TRUE= + MAINTAINER_MODE_FALSE='#' +else + MAINTAINER_MODE_TRUE='#' + MAINTAINER_MODE_FALSE= +fi + + MAINT=$MAINTAINER_MODE_TRUE + + +# Check whether --enable-silent-rules was given. +if test ${enable_silent_rules+y} +then : + enableval=$enable_silent_rules; +fi + +case $enable_silent_rules in # ((( + yes) AM_DEFAULT_VERBOSITY=0;; + no) AM_DEFAULT_VERBOSITY=1;; + *) AM_DEFAULT_VERBOSITY=0;; +esac +am_make=${MAKE-make} +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $am_make supports nested variables" >&5 +printf %s "checking whether $am_make supports nested variables... " >&6; } +if test ${am_cv_make_support_nested_variables+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if printf "%s\n" 'TRUE=$(BAR$(V)) +BAR0=false +BAR1=true +V=1 +am__doit: + @$(TRUE) +.PHONY: am__doit' | $am_make -f - >/dev/null 2>&1; then + am_cv_make_support_nested_variables=yes +else + am_cv_make_support_nested_variables=no +fi +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_make_support_nested_variables" >&5 +printf "%s\n" "$am_cv_make_support_nested_variables" >&6; } +if test $am_cv_make_support_nested_variables = yes; then + AM_V='$(V)' + AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' +else + AM_V=$AM_DEFAULT_VERBOSITY + AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY +fi +AM_BACKSLASH='\' + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable debug build options" >&5 +printf %s "checking whether to enable debug build options... " >&6; } + OPT_DEBUG_BUILD="default" + # Check whether --enable-debug was given. +if test ${enable_debug+y} +then : + enableval=$enable_debug; OPT_DEBUG_BUILD=$enableval +fi + + case "$OPT_DEBUG_BUILD" in + no) + want_debug="no" + ;; + default) + want_debug="no" + ;; + *) + want_debug="yes" + +printf "%s\n" "#define DEBUGBUILD 1" >>confdefs.h + + ;; + esac + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $want_debug" >&5 +printf "%s\n" "$want_debug" >&6; } + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable compiler optimizer" >&5 +printf %s "checking whether to enable compiler optimizer... " >&6; } + OPT_COMPILER_OPTIMIZE="default" + # Check whether --enable-optimize was given. +if test ${enable_optimize+y} +then : + enableval=$enable_optimize; OPT_COMPILER_OPTIMIZE=$enableval +fi + + case "$OPT_COMPILER_OPTIMIZE" in + no) + want_optimize="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + default) + if test "$want_debug" = "yes"; then + want_optimize="assume_no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: (assumed) no" >&5 +printf "%s\n" "(assumed) no" >&6; } + else + want_optimize="assume_yes" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: (assumed) yes" >&5 +printf "%s\n" "(assumed) yes" >&6; } + fi + ;; + *) + want_optimize="yes" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable strict compiler warnings" >&5 +printf %s "checking whether to enable strict compiler warnings... " >&6; } + OPT_COMPILER_WARNINGS="default" + # Check whether --enable-warnings was given. +if test ${enable_warnings+y} +then : + enableval=$enable_warnings; OPT_COMPILER_WARNINGS=$enableval +fi + + case "$OPT_COMPILER_WARNINGS" in + no) + want_warnings="no" + ;; + default) + want_warnings="$want_debug" + ;; + *) + want_warnings="yes" + ;; + esac + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $want_warnings" >&5 +printf "%s\n" "$want_warnings" >&6; } + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable compiler warnings as errors" >&5 +printf %s "checking whether to enable compiler warnings as errors... " >&6; } + OPT_COMPILER_WERROR="default" + # Check whether --enable-werror was given. +if test ${enable_werror+y} +then : + enableval=$enable_werror; OPT_COMPILER_WERROR=$enableval +fi + + case "$OPT_COMPILER_WERROR" in + no) + want_werror="no" + ;; + default) + want_werror="no" + ;; + *) + want_werror="yes" + ;; + esac + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $want_werror" >&5 +printf "%s\n" "$want_werror" >&6; } + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable curl debug memory tracking" >&5 +printf %s "checking whether to enable curl debug memory tracking... " >&6; } + OPT_CURLDEBUG_BUILD="default" + # Check whether --enable-curldebug was given. +if test ${enable_curldebug+y} +then : + enableval=$enable_curldebug; OPT_CURLDEBUG_BUILD=$enableval +fi + + case "$OPT_CURLDEBUG_BUILD" in + no) + want_curldebug="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + default) + if test "$want_debug" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: (assumed) yes" >&5 +printf "%s\n" "(assumed) yes" >&6; } + +printf "%s\n" "#define CURLDEBUG 1" >>confdefs.h + + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + want_curldebug_assumed="yes" + want_curldebug="$want_debug" + ;; + *) + want_curldebug="yes" + +printf "%s\n" "#define CURLDEBUG 1" >>confdefs.h + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable hiding of library internal symbols" >&5 +printf %s "checking whether to enable hiding of library internal symbols... " >&6; } + OPT_SYMBOL_HIDING="default" + # Check whether --enable-symbol-hiding was given. +if test ${enable_symbol_hiding+y} +then : + enableval=$enable_symbol_hiding; OPT_SYMBOL_HIDING=$enableval +fi + + case "$OPT_SYMBOL_HIDING" in + no) + want_symbol_hiding="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + default) + want_symbol_hiding="yes" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + *) + want_symbol_hiding="yes" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable c-ares for DNS lookups" >&5 +printf %s "checking whether to enable c-ares for DNS lookups... " >&6; } + OPT_ARES="default" + # Check whether --enable-ares was given. +if test ${enable_ares+y} +then : + enableval=$enable_ares; OPT_ARES=$enableval +fi + + case "$OPT_ARES" in + no) + want_ares="no" + ;; + default) + want_ares="no" + ;; + *) + want_ares="yes" + if test -n "$enableval" && test "$enableval" != "yes"; then + want_ares_path="$enableval" + fi + ;; + esac + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $want_ares" >&5 +printf "%s\n" "$want_ares" >&6; } + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to disable dependency on -lrt" >&5 +printf %s "checking whether to disable dependency on -lrt... " >&6; } + OPT_RT="default" + # Check whether --enable-rt was given. +if test ${enable_rt+y} +then : + enableval=$enable_rt; OPT_RT=$enableval +fi + + case "$OPT_RT" in + no) + dontwant_rt="yes" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + default) + dontwant_rt="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: (assumed no)" >&5 +printf "%s\n" "(assumed no)" >&6; } + ;; + *) + dontwant_rt="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + esac + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable HTTPSRR support" >&5 +printf %s "checking whether to enable HTTPSRR support... " >&6; } + OPT_HTTPSRR="default" + # Check whether --enable-httpsrr was given. +if test ${enable_httpsrr+y} +then : + enableval=$enable_httpsrr; OPT_HTTPSRR=$enableval +fi + + case "$OPT_HTTPSRR" in + no) + want_httpsrr="no" + curl_httpsrr_msg="no (--enable-httpsrr)" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + default) + want_httpsrr="no" + curl_httpsrr_msg="no (--enable-httpsrr)" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + *) + want_httpsrr="yes" + curl_httpsrr_msg="enabled (--disable-httpsrr)" + experimental="httpsrr" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable ECH support" >&5 +printf %s "checking whether to enable ECH support... " >&6; } + OPT_ECH="default" + # Check whether --enable-ech was given. +if test ${enable_ech+y} +then : + enableval=$enable_ech; OPT_ECH=$enableval +fi + + case "$OPT_ECH" in + no) + want_ech="no" + curl_ech_msg="no (--enable-ech)" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + default) + want_ech="no" + curl_ech_msg="no (--enable-ech)" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + *) + want_ech="yes" + curl_ech_msg="enabled (--disable-ech)" + experimental="ech" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac + + +# +# Check that 'XC_CONFIGURE_PREAMBLE' has already run. +# + +if test -z "$xc_configure_preamble_result"; then + as_fn_error $? "xc_configure_preamble_result not set (internal problem)" "$LINENO" 5 +fi + +# +# Check that 'PATH_SEPARATOR' has already been set. +# + +if test -z "$xc_PATH_SEPARATOR"; then + as_fn_error $? "xc_PATH_SEPARATOR not set (internal problem)" "$LINENO" 5 +fi +if test -z "$PATH_SEPARATOR"; then + as_fn_error $? "PATH_SEPARATOR not set (internal or config.site problem)" "$LINENO" 5 +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for path separator" >&5 +printf %s "checking for path separator... " >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PATH_SEPARATOR" >&5 +printf "%s\n" "$PATH_SEPARATOR" >&6; } +if test "x$PATH_SEPARATOR" != "x$xc_PATH_SEPARATOR"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for initial path separator" >&5 +printf %s "checking for initial path separator... " >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $xc_PATH_SEPARATOR" >&5 +printf "%s\n" "$xc_PATH_SEPARATOR" >&6; } + as_fn_error $? "path separator mismatch (internal or config.site problem)" "$LINENO" 5 +fi + + +# +# save the configure arguments +# +CONFIGURE_OPTIONS="\"$ac_configure_args\"" + + +if test -z "$SED"; then + # Extract the first word of "sed", so it can be a program name with args. +set dummy sed; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_SED+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $SED in + [\\/]* | ?:[\\/]*) + ac_cv_path_SED="$SED" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_SED="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + test -z "$ac_cv_path_SED" && ac_cv_path_SED="not_found" + ;; +esac +fi +SED=$ac_cv_path_SED +if test -n "$SED"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $SED" >&5 +printf "%s\n" "$SED" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + if test -z "$SED" || test "$SED" = "not_found"; then + as_fn_error $? "sed not found in PATH. Cannot continue without sed." "$LINENO" 5 + fi +fi + + +if test -z "$GREP"; then + # Extract the first word of "grep", so it can be a program name with args. +set dummy grep; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_GREP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $GREP in + [\\/]* | ?:[\\/]*) + ac_cv_path_GREP="$GREP" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_GREP="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + test -z "$ac_cv_path_GREP" && ac_cv_path_GREP="not_found" + ;; +esac +fi +GREP=$ac_cv_path_GREP +if test -n "$GREP"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $GREP" >&5 +printf "%s\n" "$GREP" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + if test -z "$GREP" || test "$GREP" = "not_found"; then + as_fn_error $? "grep not found in PATH. Cannot continue without grep." "$LINENO" 5 + fi +fi + + +if test -z "$EGREP"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking that grep -E works" >&5 +printf %s "checking that grep -E works... " >&6; } + if echo a | ($GREP -E '(a|b)') >/dev/null 2>&1; then + EGREP="$GREP -E" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + # Extract the first word of "egrep", so it can be a program name with args. +set dummy egrep; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_EGREP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $EGREP in + [\\/]* | ?:[\\/]*) + ac_cv_path_EGREP="$EGREP" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_EGREP="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + test -z "$ac_cv_path_EGREP" && ac_cv_path_EGREP="not_found" + ;; +esac +fi +EGREP=$ac_cv_path_EGREP +if test -n "$EGREP"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $EGREP" >&5 +printf "%s\n" "$EGREP" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + fi +fi +if test -z "$EGREP" || test "$EGREP" = "not_found"; then + as_fn_error $? "grep -E is not working and egrep is not found in PATH. Cannot continue." "$LINENO" 5 +fi + + +if test -z "$AR"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}ar", so it can be a program name with args. +set dummy ${ac_tool_prefix}ar; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_AR+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $AR in + [\\/]* | ?:[\\/]*) + ac_cv_path_AR="$AR" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_AR="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +AR=$ac_cv_path_AR +if test -n "$AR"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 +printf "%s\n" "$AR" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_AR"; then + ac_pt_AR=$AR + # Extract the first word of "ar", so it can be a program name with args. +set dummy ar; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_AR+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_AR in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_AR="$ac_pt_AR" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_AR="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_AR=$ac_cv_path_ac_pt_AR +if test -n "$ac_pt_AR"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_AR" >&5 +printf "%s\n" "$ac_pt_AR" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_AR" = x; then + AR="not_found" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + AR=$ac_pt_AR + fi +else + AR="$ac_cv_path_AR" +fi + + if test -z "$AR" || test "$AR" = "not_found"; then + as_fn_error $? "ar not found in PATH. Cannot continue without ar." "$LINENO" 5 + fi +fi + + + + +CURLVERSION=`$SED -ne 's/^#define LIBCURL_VERSION "\(.*\)".*/\1/p' ${srcdir}/include/curl/curlver.h` + + xc_prog_cc_prev_IFS=$IFS + xc_prog_cc_prev_LIBS=$LIBS + xc_prog_cc_prev_CFLAGS=$CFLAGS + xc_prog_cc_prev_LDFLAGS=$LDFLAGS + xc_prog_cc_prev_CPPFLAGS=$CPPFLAGS + + + + xc_bad_var_libs=no + for xc_word in $LIBS; do + case "$xc_word" in + -l* | --library=*) + : + ;; + *) + xc_bad_var_libs=yes + ;; + esac + done + if test $xc_bad_var_libs = yes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: using LIBS: $LIBS" >&5 +printf "%s\n" "$as_me: using LIBS: $LIBS" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: LIBS note: LIBS should only be used to specify libraries (-lname)." >&5 +printf "%s\n" "$as_me: LIBS note: LIBS should only be used to specify libraries (-lname)." >&6;} + fi + + + xc_bad_var_ldflags=no + for xc_word in $LDFLAGS; do + case "$xc_word" in + -D*) + xc_bad_var_ldflags=yes + ;; + -U*) + xc_bad_var_ldflags=yes + ;; + -I*) + xc_bad_var_ldflags=yes + ;; + -l* | --library=*) + xc_bad_var_ldflags=yes + ;; + esac + done + if test $xc_bad_var_ldflags = yes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: using LDFLAGS: $LDFLAGS" >&5 +printf "%s\n" "$as_me: using LDFLAGS: $LDFLAGS" >&6;} + xc_bad_var_msg="LDFLAGS note: LDFLAGS should only be used to specify linker flags, not" + for xc_word in $LDFLAGS; do + case "$xc_word" in + -D*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg macro definitions. Use CPPFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg macro definitions. Use CPPFLAGS for: $xc_word" >&6;} + ;; + -U*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg macro suppressions. Use CPPFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg macro suppressions. Use CPPFLAGS for: $xc_word" >&6;} + ;; + -I*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg include directories. Use CPPFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg include directories. Use CPPFLAGS for: $xc_word" >&6;} + ;; + -l* | --library=*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg libraries. Use LIBS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg libraries. Use LIBS for: $xc_word" >&6;} + ;; + esac + done + fi + + + xc_bad_var_cppflags=no + for xc_word in $CPPFLAGS; do + case "$xc_word" in + -rpath*) + xc_bad_var_cppflags=yes + ;; + -L* | --library-path=*) + xc_bad_var_cppflags=yes + ;; + -l* | --library=*) + xc_bad_var_cppflags=yes + ;; + esac + done + if test $xc_bad_var_cppflags = yes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: using CPPFLAGS: $CPPFLAGS" >&5 +printf "%s\n" "$as_me: using CPPFLAGS: $CPPFLAGS" >&6;} + xc_bad_var_msg="CPPFLAGS note: CPPFLAGS should only be used to specify C preprocessor flags, not" + for xc_word in $CPPFLAGS; do + case "$xc_word" in + -rpath*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg library runtime directories. Use LDFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg library runtime directories. Use LDFLAGS for: $xc_word" >&6;} + ;; + -L* | --library-path=*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg library directories. Use LDFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg library directories. Use LDFLAGS for: $xc_word" >&6;} + ;; + -l* | --library=*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg libraries. Use LIBS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg libraries. Use LIBS for: $xc_word" >&6;} + ;; + esac + done + fi + + + xc_bad_var_cflags=no + for xc_word in $CFLAGS; do + case "$xc_word" in + -D*) + xc_bad_var_cflags=yes + ;; + -U*) + xc_bad_var_cflags=yes + ;; + -I*) + xc_bad_var_cflags=yes + ;; + -rpath*) + xc_bad_var_cflags=yes + ;; + -L* | --library-path=*) + xc_bad_var_cflags=yes + ;; + -l* | --library=*) + xc_bad_var_cflags=yes + ;; + esac + done + if test $xc_bad_var_cflags = yes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: using CFLAGS: $CFLAGS" >&5 +printf "%s\n" "$as_me: using CFLAGS: $CFLAGS" >&6;} + xc_bad_var_msg="CFLAGS note: CFLAGS should only be used to specify C compiler flags, not" + for xc_word in $CFLAGS; do + case "$xc_word" in + -D*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg macro definitions. Use CPPFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg macro definitions. Use CPPFLAGS for: $xc_word" >&6;} + ;; + -U*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg macro suppressions. Use CPPFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg macro suppressions. Use CPPFLAGS for: $xc_word" >&6;} + ;; + -I*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg include directories. Use CPPFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg include directories. Use CPPFLAGS for: $xc_word" >&6;} + ;; + -rpath*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg library runtime directories. Use LDFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg library runtime directories. Use LDFLAGS for: $xc_word" >&6;} + ;; + -L* | --library-path=*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg library directories. Use LDFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg library directories. Use LDFLAGS for: $xc_word" >&6;} + ;; + -l* | --library=*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg libraries. Use LIBS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg libraries. Use LIBS for: $xc_word" >&6;} + ;; + esac + done + fi + + if test $xc_bad_var_libs = yes || + test $xc_bad_var_cflags = yes || + test $xc_bad_var_ldflags = yes || + test $xc_bad_var_cppflags = yes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: Continuing even with errors mentioned immediately above this line." >&5 +printf "%s\n" "$as_me: WARNING: Continuing even with errors mentioned immediately above this line." >&2;} + fi + + + + # Find a good install program. We prefer a C program (faster), +# so one script is as good as another. But avoid the broken or +# incompatible versions: +# SysV /etc/install, /usr/sbin/install +# SunOS /usr/etc/install +# IRIX /sbin/install +# AIX /bin/install +# AmigaOS /C/install, which installs bootblocks on floppy discs +# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag +# AFS /usr/afsws/bin/install, which mishandles nonexistent args +# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" +# OS/2's system install, which has a completely different semantic +# ./install, which can be erroneously created by make from ./install.sh. +# Reject install programs that cannot install multiple files. +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 +printf %s "checking for a BSD-compatible install... " >&6; } +if test -z "$INSTALL"; then +if test ${ac_cv_path_install+y} +then : + printf %s "(cached) " >&6 +else $as_nop + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + # Account for fact that we put trailing slashes in our PATH walk. +case $as_dir in #(( + ./ | /[cC]/* | \ + /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ + ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ + /usr/ucb/* ) ;; + *) + # OSF1 and SCO ODT 3.0 have their own names for install. + # Don't use installbsd from OSF since it installs stuff as root + # by default. + for ac_prog in ginstall scoinst install; do + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_prog$ac_exec_ext"; then + if test $ac_prog = install && + grep dspmsg "$as_dir$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # AIX install. It has an incompatible calling convention. + : + elif test $ac_prog = install && + grep pwplus "$as_dir$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # program-specific install script used by HP pwplus--don't use. + : + else + rm -rf conftest.one conftest.two conftest.dir + echo one > conftest.one + echo two > conftest.two + mkdir conftest.dir + if "$as_dir$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir/" && + test -s conftest.one && test -s conftest.two && + test -s conftest.dir/conftest.one && + test -s conftest.dir/conftest.two + then + ac_cv_path_install="$as_dir$ac_prog$ac_exec_ext -c" + break 3 + fi + fi + fi + done + done + ;; +esac + + done +IFS=$as_save_IFS + +rm -rf conftest.one conftest.two conftest.dir + +fi + if test ${ac_cv_path_install+y}; then + INSTALL=$ac_cv_path_install + else + # As a last resort, use the slow shell script. Don't cache a + # value for INSTALL within a source directory, because that will + # break other packages using the cache if that directory is + # removed, or if the value is a relative name. + INSTALL=$ac_install_sh + fi +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 +printf "%s\n" "$INSTALL" >&6; } + +# Use test -z because SunOS4 sh mishandles braces in ${var-val}. +# It thinks the first close brace ends the variable substitution. +test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' + +test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' + +test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' + + + + + + + + + + + +# Expand $ac_aux_dir to an absolute path. +am_aux_dir=`cd "$ac_aux_dir" && pwd` + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcc; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}gcc" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +printf "%s\n" "$CC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "gcc", so it can be a program name with args. +set dummy gcc; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="gcc" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +printf "%s\n" "$ac_ct_CC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +else + CC="$ac_cv_prog_CC" +fi + +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. +set dummy ${ac_tool_prefix}cc; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}cc" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +printf "%s\n" "$CC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + fi +fi +if test -z "$CC"; then + # Extract the first word of "cc", so it can be a program name with args. +set dummy cc; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else + ac_prog_rejected=no +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + if test "$as_dir$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then + ac_prog_rejected=yes + continue + fi + ac_cv_prog_CC="cc" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +if test $ac_prog_rejected = yes; then + # We found a bogon in the path, so make sure we never use it. + set dummy $ac_cv_prog_CC + shift + if test $# != 0; then + # We chose a different compiler from the bogus one. + # However, it has the same basename, so the bogon will be chosen + # first if we set CC to just the basename; use the full file name. + shift + ac_cv_prog_CC="$as_dir$ac_word${1+' '}$@" + fi +fi +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +printf "%s\n" "$CC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + for ac_prog in cl.exe + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="$ac_tool_prefix$ac_prog" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +printf "%s\n" "$CC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + test -n "$CC" && break + done +fi +if test -z "$CC"; then + ac_ct_CC=$CC + for ac_prog in cl.exe +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="$ac_prog" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +printf "%s\n" "$ac_ct_CC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + test -n "$ac_ct_CC" && break +done + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +fi + +fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}clang", so it can be a program name with args. +set dummy ${ac_tool_prefix}clang; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}clang" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +printf "%s\n" "$CC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "clang", so it can be a program name with args. +set dummy clang; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="clang" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +printf "%s\n" "$ac_ct_CC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +else + CC="$ac_cv_prog_CC" +fi + +fi + + +test -z "$CC" && { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "no acceptable C compiler found in \$PATH +See \`config.log' for more details" "$LINENO" 5; } + +# Provide some information about the compiler. +printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 +set X $ac_compile +ac_compiler=$2 +for ac_option in --version -v -V -qversion -version; do + { { ac_try="$ac_compiler $ac_option >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_compiler $ac_option >&5") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + sed '10a\ +... rest of stderr output deleted ... + 10q' conftest.err >conftest.er1 + cat conftest.er1 >&5 + fi + rm -f conftest.er1 conftest.err + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +done + +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main (void) +{ + + ; + return 0; +} +_ACEOF +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" +# Try to create an executable without -o first, disregard a.out. +# It will help us diagnose broken compilers, and finding out an intuition +# of exeext. +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 +printf %s "checking whether the C compiler works... " >&6; } +ac_link_default=`printf "%s\n" "$ac_link" | sed 's/ -o *conftest[^ ]*//'` + +# The possible output files: +ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" + +ac_rmfiles= +for ac_file in $ac_files +do + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + * ) ac_rmfiles="$ac_rmfiles $ac_file";; + esac +done +rm -f $ac_rmfiles + +if { { ac_try="$ac_link_default" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_link_default") 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +then : + # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. +# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' +# in a Makefile. We should not override ac_cv_exeext if it was cached, +# so that the user can short-circuit this test for compilers unknown to +# Autoconf. +for ac_file in $ac_files '' +do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) + ;; + [ab].out ) + # We found the default executable, but exeext='' is most + # certainly right. + break;; + *.* ) + if test ${ac_cv_exeext+y} && test "$ac_cv_exeext" != no; + then :; else + ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + fi + # We set ac_cv_exeext here because the later test for it is not + # safe: cross compilers may not add the suffix if given an `-o' + # argument, so we may need to know it at that point already. + # Even if this section looks crufty: it has the advantage of + # actually working. + break;; + * ) + break;; + esac +done +test "$ac_cv_exeext" = no && ac_cv_exeext= + +else $as_nop + ac_file='' +fi +if test -z "$ac_file" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +printf "%s\n" "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error 77 "C compiler cannot create executables +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 +printf %s "checking for C compiler default output file name... " >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 +printf "%s\n" "$ac_file" >&6; } +ac_exeext=$ac_cv_exeext + +rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out +ac_clean_files=$ac_clean_files_save +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 +printf %s "checking for suffix of executables... " >&6; } +if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +then : + # If both `conftest.exe' and `conftest' are `present' (well, observable) +# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will +# work properly (i.e., refer to `conftest.exe'), while it won't with +# `rm'. +for ac_file in conftest.exe conftest conftest.*; do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + break;; + * ) break;; + esac +done +else $as_nop + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details" "$LINENO" 5; } +fi +rm -f conftest conftest$ac_cv_exeext +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 +printf "%s\n" "$ac_cv_exeext" >&6; } + +rm -f conftest.$ac_ext +EXEEXT=$ac_cv_exeext +ac_exeext=$EXEEXT +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int main (void) +{ +FILE *f = fopen ("conftest.out", "w"); + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} +_ACEOF +ac_clean_files="$ac_clean_files conftest.out" +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 +printf %s "checking whether we are cross compiling... " >&6; } +if test "$cross_compiling" != yes; then + { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + if { ac_try='./conftest$ac_cv_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + cross_compiling=no + else + if test "$cross_compiling" = maybe; then + cross_compiling=yes + else + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error 77 "cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details" "$LINENO" 5; } + fi + fi +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 +printf "%s\n" "$cross_compiling" >&6; } + +rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out +ac_clean_files=$ac_clean_files_save +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 +printf %s "checking for suffix of object files... " >&6; } +if test ${ac_cv_objext+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main (void) +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.o conftest.obj +if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +then : + for ac_file in conftest.o conftest.obj conftest.*; do + test -f "$ac_file" || continue; + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; + *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` + break;; + esac +done +else $as_nop + printf "%s\n" "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of object files: cannot compile +See \`config.log' for more details" "$LINENO" 5; } +fi +rm -f conftest.$ac_cv_objext conftest.$ac_ext +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 +printf "%s\n" "$ac_cv_objext" >&6; } +OBJEXT=$ac_cv_objext +ac_objext=$OBJEXT +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the compiler supports GNU C" >&5 +printf %s "checking whether the compiler supports GNU C... " >&6; } +if test ${ac_cv_c_compiler_gnu+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main (void) +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + ac_compiler_gnu=yes +else $as_nop + ac_compiler_gnu=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +ac_cv_c_compiler_gnu=$ac_compiler_gnu + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 +printf "%s\n" "$ac_cv_c_compiler_gnu" >&6; } +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +if test $ac_compiler_gnu = yes; then + GCC=yes +else + GCC= +fi +ac_test_CFLAGS=${CFLAGS+y} +ac_save_CFLAGS=$CFLAGS +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 +printf %s "checking whether $CC accepts -g... " >&6; } +if test ${ac_cv_prog_cc_g+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_save_c_werror_flag=$ac_c_werror_flag + ac_c_werror_flag=yes + ac_cv_prog_cc_g=no + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_prog_cc_g=yes +else $as_nop + CFLAGS="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + +else $as_nop + ac_c_werror_flag=$ac_save_c_werror_flag + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_prog_cc_g=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + ac_c_werror_flag=$ac_save_c_werror_flag +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 +printf "%s\n" "$ac_cv_prog_cc_g" >&6; } +if test $ac_test_CFLAGS; then + CFLAGS=$ac_save_CFLAGS +elif test $ac_cv_prog_cc_g = yes; then + if test "$GCC" = yes; then + CFLAGS="-g -O2" + else + CFLAGS="-g" + fi +else + if test "$GCC" = yes; then + CFLAGS="-O2" + else + CFLAGS= + fi +fi +ac_prog_cc_stdc=no +if test x$ac_prog_cc_stdc = xno +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C11 features" >&5 +printf %s "checking for $CC option to enable C11 features... " >&6; } +if test ${ac_cv_prog_cc_c11+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_cv_prog_cc_c11=no +ac_save_CC=$CC +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_c_conftest_c11_program +_ACEOF +for ac_arg in '' -std=gnu11 +do + CC="$ac_save_CC $ac_arg" + if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_prog_cc_c11=$ac_arg +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam + test "x$ac_cv_prog_cc_c11" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC +fi + +if test "x$ac_cv_prog_cc_c11" = xno +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +printf "%s\n" "unsupported" >&6; } +else $as_nop + if test "x$ac_cv_prog_cc_c11" = x +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +printf "%s\n" "none needed" >&6; } +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c11" >&5 +printf "%s\n" "$ac_cv_prog_cc_c11" >&6; } + CC="$CC $ac_cv_prog_cc_c11" +fi + ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c11 + ac_prog_cc_stdc=c11 +fi +fi +if test x$ac_prog_cc_stdc = xno +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C99 features" >&5 +printf %s "checking for $CC option to enable C99 features... " >&6; } +if test ${ac_cv_prog_cc_c99+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_cv_prog_cc_c99=no +ac_save_CC=$CC +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_c_conftest_c99_program +_ACEOF +for ac_arg in '' -std=gnu99 -std=c99 -c99 -qlanglvl=extc1x -qlanglvl=extc99 -AC99 -D_STDC_C99= +do + CC="$ac_save_CC $ac_arg" + if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_prog_cc_c99=$ac_arg +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam + test "x$ac_cv_prog_cc_c99" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC +fi + +if test "x$ac_cv_prog_cc_c99" = xno +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +printf "%s\n" "unsupported" >&6; } +else $as_nop + if test "x$ac_cv_prog_cc_c99" = x +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +printf "%s\n" "none needed" >&6; } +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c99" >&5 +printf "%s\n" "$ac_cv_prog_cc_c99" >&6; } + CC="$CC $ac_cv_prog_cc_c99" +fi + ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c99 + ac_prog_cc_stdc=c99 +fi +fi +if test x$ac_prog_cc_stdc = xno +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C89 features" >&5 +printf %s "checking for $CC option to enable C89 features... " >&6; } +if test ${ac_cv_prog_cc_c89+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_cv_prog_cc_c89=no +ac_save_CC=$CC +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_c_conftest_c89_program +_ACEOF +for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" +do + CC="$ac_save_CC $ac_arg" + if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_prog_cc_c89=$ac_arg +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam + test "x$ac_cv_prog_cc_c89" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC +fi + +if test "x$ac_cv_prog_cc_c89" = xno +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +printf "%s\n" "unsupported" >&6; } +else $as_nop + if test "x$ac_cv_prog_cc_c89" = x +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +printf "%s\n" "none needed" >&6; } +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 +printf "%s\n" "$ac_cv_prog_cc_c89" >&6; } + CC="$CC $ac_cv_prog_cc_c89" +fi + ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c89 + ac_prog_cc_stdc=c89 +fi +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $CC understands -c and -o together" >&5 +printf %s "checking whether $CC understands -c and -o together... " >&6; } +if test ${am_cv_prog_cc_c_o+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main (void) +{ + + ; + return 0; +} +_ACEOF + # Make sure it works both with $CC and with simple cc. + # Following AC_PROG_CC_C_O, we do the test twice because some + # compilers refuse to overwrite an existing .o file with -o, + # though they will create one. + am_cv_prog_cc_c_o=yes + for am_i in 1 2; do + if { echo "$as_me:$LINENO: $CC -c conftest.$ac_ext -o conftest2.$ac_objext" >&5 + ($CC -c conftest.$ac_ext -o conftest2.$ac_objext) >&5 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } \ + && test -f conftest2.$ac_objext; then + : OK + else + am_cv_prog_cc_c_o=no + break + fi + done + rm -f core conftest* + unset am_i +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_prog_cc_c_o" >&5 +printf "%s\n" "$am_cv_prog_cc_c_o" >&6; } +if test "$am_cv_prog_cc_c_o" != yes; then + # Losing compiler, so override with the script. + # FIXME: It is wrong to rewrite CC. + # But if we don't then we get into trouble of one sort or another. + # A longer-term fix would be to have automake use am__CC in this case, + # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" + CC="$am_aux_dir/compile $CC" +fi +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 +printf %s "checking how to run the C preprocessor... " >&6; } +# On Suns, sometimes $CPP names a directory. +if test -n "$CPP" && test -d "$CPP"; then + CPP= +fi +if test -z "$CPP"; then + if test ${ac_cv_prog_CPP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + # Double quotes because $CC needs to be expanded + for CPP in "$CC -E" "$CC -E -traditional-cpp" cpp /lib/cpp + do + ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + +else $as_nop + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + # Broken: success on invalid input. +continue +else $as_nop + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok +then : + break +fi + + done + ac_cv_prog_CPP=$CPP + +fi + CPP=$ac_cv_prog_CPP +else + ac_cv_prog_CPP=$CPP +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 +printf "%s\n" "$CPP" >&6; } +ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + +else $as_nop + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + # Broken: success on invalid input. +continue +else $as_nop + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok +then : + +else $as_nop + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details" "$LINENO" 5; } +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + IFS=$xc_prog_cc_prev_IFS + LIBS=$xc_prog_cc_prev_LIBS + CFLAGS=$xc_prog_cc_prev_CFLAGS + LDFLAGS=$xc_prog_cc_prev_LDFLAGS + CPPFLAGS=$xc_prog_cc_prev_CPPFLAGS + + + + + + +ac_header= ac_cache= +for ac_item in $ac_header_c_list +do + if test $ac_cache; then + ac_fn_c_check_header_compile "$LINENO" $ac_header ac_cv_header_$ac_cache "$ac_includes_default" + if eval test \"x\$ac_cv_header_$ac_cache\" = xyes; then + printf "%s\n" "#define $ac_item 1" >> confdefs.h + fi + ac_header= ac_cache= + elif test $ac_header; then + ac_cache=$ac_item + else + ac_header=$ac_item + fi +done + + + + + + + + +if test $ac_cv_header_stdlib_h = yes && test $ac_cv_header_string_h = yes +then : + +printf "%s\n" "#define STDC_HEADERS 1" >>confdefs.h + +fi + + for ac_header in stdatomic.h +do : + ac_fn_c_check_header_compile "$LINENO" "stdatomic.h" "ac_cv_header_stdatomic_h" "$ac_includes_default" +if test "x$ac_cv_header_stdatomic_h" = xyes +then : + printf "%s\n" "#define HAVE_STDATOMIC_H 1" >>confdefs.h + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if _Atomic is available" >&5 +printf %s "checking if _Atomic is available... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_unistd + +int main (void) +{ + + _Atomic int i = 0; + i = 4; // Force an atomic-write operation. + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_ATOMIC 1" >>confdefs.h + + tst_atomic="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_atomic="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + +fi + +done + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5 +printf %s "checking for a sed that does not truncate output... " >&6; } +if test ${ac_cv_path_SED+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ + for ac_i in 1 2 3 4 5 6 7; do + ac_script="$ac_script$as_nl$ac_script" + done + echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed + { ac_script=; unset ac_script;} + if test -z "$SED"; then + ac_path_SED_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_prog in sed gsed + do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_SED="$as_dir$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_SED" || continue +# Check for GNU ac_path_SED and select it if it is found. + # Check for GNU $ac_path_SED +case `"$ac_path_SED" --version 2>&1` in +*GNU*) + ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;; +*) + ac_count=0 + printf %s 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + printf "%s\n" '' >> "conftest.nl" + "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_SED_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_SED="$ac_path_SED" + ac_path_SED_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_SED_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_SED"; then + as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5 + fi +else + ac_cv_path_SED=$SED +fi + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5 +printf "%s\n" "$ac_cv_path_SED" >&6; } + SED="$ac_cv_path_SED" + rm -f conftest.sed + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for code coverage support" >&5 +printf %s "checking for code coverage support... " >&6; } + coverage="no" + curl_coverage_msg="disabled" + + # Check whether --enable-code-coverage was given. +if test ${enable_code_coverage+y} +then : + enableval=$enable_code_coverage; coverage="$enableval" +fi + + + if test "$GCC" != "yes" +then : + coverage="no" +fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $coverage" >&5 +printf "%s\n" "$coverage" >&6; } + + if test "x$coverage" = "xyes"; then + curl_coverage_msg="enabled" + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcov", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcov; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_GCOV+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$GCOV"; then + ac_cv_prog_GCOV="$GCOV" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_GCOV="${ac_tool_prefix}gcov" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +GCOV=$ac_cv_prog_GCOV +if test -n "$GCOV"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $GCOV" >&5 +printf "%s\n" "$GCOV" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_GCOV"; then + ac_ct_GCOV=$GCOV + # Extract the first word of "gcov", so it can be a program name with args. +set dummy gcov; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_GCOV+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_GCOV"; then + ac_cv_prog_ac_ct_GCOV="$ac_ct_GCOV" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_GCOV="gcov" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_GCOV=$ac_cv_prog_ac_ct_GCOV +if test -n "$ac_ct_GCOV"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_GCOV" >&5 +printf "%s\n" "$ac_ct_GCOV" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_GCOV" = x; then + GCOV="gcov" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + GCOV=$ac_ct_GCOV + fi +else + GCOV="$ac_cv_prog_GCOV" +fi + + if test -z "$GCOV"; then + as_fn_error $? "needs gcov for code coverage" "$LINENO" 5 + fi + # Extract the first word of "lcov", so it can be a program name with args. +set dummy lcov; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_LCOV+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$LCOV"; then + ac_cv_prog_LCOV="$LCOV" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_LCOV="lcov" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +LCOV=$ac_cv_prog_LCOV +if test -n "$LCOV"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $LCOV" >&5 +printf "%s\n" "$LCOV" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + if test -z "$LCOV"; then + as_fn_error $? "needs lcov for code coverage" "$LINENO" 5 + fi + + CPPFLAGS="$CPPFLAGS -DNDEBUG" + CFLAGS="$CFLAGS -O0 -g -fprofile-arcs -ftest-coverage" + LIBS="$LIBS -lgcov" + fi + + +am__api_version='1.16' + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether build environment is sane" >&5 +printf %s "checking whether build environment is sane... " >&6; } +# Reject unsafe characters in $srcdir or the absolute working directory +# name. Accept space and tab only in the latter. +am_lf=' +' +case `pwd` in + *[\\\"\#\$\&\'\`$am_lf]*) + as_fn_error $? "unsafe absolute working directory name" "$LINENO" 5;; +esac +case $srcdir in + *[\\\"\#\$\&\'\`$am_lf\ \ ]*) + as_fn_error $? "unsafe srcdir value: '$srcdir'" "$LINENO" 5;; +esac + +# Do 'set' in a subshell so we don't clobber the current shell's +# arguments. Must try -L first in case configure is actually a +# symlink; some systems play weird games with the mod time of symlinks +# (eg FreeBSD returns the mod time of the symlink's containing +# directory). +if ( + am_has_slept=no + for am_try in 1 2; do + echo "timestamp, slept: $am_has_slept" > conftest.file + set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` + if test "$*" = "X"; then + # -L didn't work. + set X `ls -t "$srcdir/configure" conftest.file` + fi + if test "$*" != "X $srcdir/configure conftest.file" \ + && test "$*" != "X conftest.file $srcdir/configure"; then + + # If neither matched, then we have a broken ls. This can happen + # if, for instance, CONFIG_SHELL is bash and it inherits a + # broken ls alias from the environment. This has actually + # happened. Such a system could not be considered "sane". + as_fn_error $? "ls -t appears to fail. Make sure there is not a broken + alias in your environment" "$LINENO" 5 + fi + if test "$2" = conftest.file || test $am_try -eq 2; then + break + fi + # Just in case. + sleep 1 + am_has_slept=yes + done + test "$2" = conftest.file + ) +then + # Ok. + : +else + as_fn_error $? "newly created file is older than distributed files! +Check your system clock" "$LINENO" 5 +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } +# If we didn't sleep, we still need to ensure time stamps of config.status and +# generated files are strictly newer. +am_sleep_pid= +if grep 'slept: no' conftest.file >/dev/null 2>&1; then + ( sleep 1 ) & + am_sleep_pid=$! +fi + +rm -f conftest.file + +test "$program_prefix" != NONE && + program_transform_name="s&^&$program_prefix&;$program_transform_name" +# Use a double $ so make ignores it. +test "$program_suffix" != NONE && + program_transform_name="s&\$&$program_suffix&;$program_transform_name" +# Double any \ or $. +# By default was `s,x,x', remove it if useless. +ac_script='s/[\\$]/&&/g;s/;s,x,x,$//' +program_transform_name=`printf "%s\n" "$program_transform_name" | sed "$ac_script"` + + + if test x"${MISSING+set}" != xset; then + MISSING="\${SHELL} '$am_aux_dir/missing'" +fi +# Use eval to expand $SHELL +if eval "$MISSING --is-lightweight"; then + am_missing_run="$MISSING " +else + am_missing_run= + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: 'missing' script is too old or missing" >&5 +printf "%s\n" "$as_me: WARNING: 'missing' script is too old or missing" >&2;} +fi + +if test x"${install_sh+set}" != xset; then + case $am_aux_dir in + *\ * | *\ *) + install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; + *) + install_sh="\${SHELL} $am_aux_dir/install-sh" + esac +fi + +# Installed binaries are usually stripped using 'strip' when the user +# run "make install-strip". However 'strip' might not be the right +# tool to use in cross-compilation environments, therefore Automake +# will honor the 'STRIP' environment variable to overrule this program. +if test "$cross_compiling" != no; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. +set dummy ${ac_tool_prefix}strip; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_STRIP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$STRIP"; then + ac_cv_prog_STRIP="$STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_STRIP="${ac_tool_prefix}strip" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +STRIP=$ac_cv_prog_STRIP +if test -n "$STRIP"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 +printf "%s\n" "$STRIP" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_STRIP"; then + ac_ct_STRIP=$STRIP + # Extract the first word of "strip", so it can be a program name with args. +set dummy strip; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_STRIP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_STRIP"; then + ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_STRIP="strip" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP +if test -n "$ac_ct_STRIP"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 +printf "%s\n" "$ac_ct_STRIP" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_STRIP" = x; then + STRIP=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + STRIP=$ac_ct_STRIP + fi +else + STRIP="$ac_cv_prog_STRIP" +fi + +fi +INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for a race-free mkdir -p" >&5 +printf %s "checking for a race-free mkdir -p... " >&6; } +if test -z "$MKDIR_P"; then + if test ${ac_cv_path_mkdir+y} +then : + printf %s "(cached) " >&6 +else $as_nop + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_prog in mkdir gmkdir; do + for ac_exec_ext in '' $ac_executable_extensions; do + as_fn_executable_p "$as_dir$ac_prog$ac_exec_ext" || continue + case `"$as_dir$ac_prog$ac_exec_ext" --version 2>&1` in #( + 'mkdir ('*'coreutils) '* | \ + 'BusyBox '* | \ + 'mkdir (fileutils) '4.1*) + ac_cv_path_mkdir=$as_dir$ac_prog$ac_exec_ext + break 3;; + esac + done + done + done +IFS=$as_save_IFS + +fi + + test -d ./--version && rmdir ./--version + if test ${ac_cv_path_mkdir+y}; then + MKDIR_P="$ac_cv_path_mkdir -p" + else + # As a last resort, use the slow shell script. Don't cache a + # value for MKDIR_P within a source directory, because that will + # break other packages using the cache if that directory is + # removed, or if the value is a relative name. + MKDIR_P="$ac_install_sh -d" + fi +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $MKDIR_P" >&5 +printf "%s\n" "$MKDIR_P" >&6; } + +for ac_prog in gawk mawk nawk awk +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_AWK+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$AWK"; then + ac_cv_prog_AWK="$AWK" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_AWK="$ac_prog" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +AWK=$ac_cv_prog_AWK +if test -n "$AWK"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5 +printf "%s\n" "$AWK" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + test -n "$AWK" && break +done + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 +printf %s "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } +set x ${MAKE-make} +ac_make=`printf "%s\n" "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` +if eval test \${ac_cv_prog_make_${ac_make}_set+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat >conftest.make <<\_ACEOF +SHELL = /bin/sh +all: + @echo '@@@%%%=$(MAKE)=@@@%%%' +_ACEOF +# GNU make sometimes prints "make[1]: Entering ...", which would confuse us. +case `${MAKE-make} -f conftest.make 2>/dev/null` in + *@@@%%%=?*=@@@%%%*) + eval ac_cv_prog_make_${ac_make}_set=yes;; + *) + eval ac_cv_prog_make_${ac_make}_set=no;; +esac +rm -f conftest.make +fi +if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + SET_MAKE= +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + SET_MAKE="MAKE=${MAKE-make}" +fi + +rm -rf .tst 2>/dev/null +mkdir .tst 2>/dev/null +if test -d .tst; then + am__leading_dot=. +else + am__leading_dot=_ +fi +rmdir .tst 2>/dev/null + +DEPDIR="${am__leading_dot}deps" + +ac_config_commands="$ac_config_commands depfiles" + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} supports the include directive" >&5 +printf %s "checking whether ${MAKE-make} supports the include directive... " >&6; } +cat > confinc.mk << 'END' +am__doit: + @echo this is the am__doit target >confinc.out +.PHONY: am__doit +END +am__include="#" +am__quote= +# BSD make does it like this. +echo '.include "confinc.mk" # ignored' > confmf.BSD +# Other make implementations (GNU, Solaris 10, AIX) do it like this. +echo 'include confinc.mk # ignored' > confmf.GNU +_am_result=no +for s in GNU BSD; do + { echo "$as_me:$LINENO: ${MAKE-make} -f confmf.$s && cat confinc.out" >&5 + (${MAKE-make} -f confmf.$s && cat confinc.out) >&5 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + case $?:`cat confinc.out 2>/dev/null` in #( + '0:this is the am__doit target') : + case $s in #( + BSD) : + am__include='.include' am__quote='"' ;; #( + *) : + am__include='include' am__quote='' ;; +esac ;; #( + *) : + ;; +esac + if test "$am__include" != "#"; then + _am_result="yes ($s style)" + break + fi +done +rm -f confinc.* confmf.* +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: ${_am_result}" >&5 +printf "%s\n" "${_am_result}" >&6; } + +# Check whether --enable-dependency-tracking was given. +if test ${enable_dependency_tracking+y} +then : + enableval=$enable_dependency_tracking; +fi + +if test "x$enable_dependency_tracking" != xno; then + am_depcomp="$ac_aux_dir/depcomp" + AMDEPBACKSLASH='\' + am__nodep='_no' +fi + if test "x$enable_dependency_tracking" != xno; then + AMDEP_TRUE= + AMDEP_FALSE='#' +else + AMDEP_TRUE='#' + AMDEP_FALSE= +fi + + +## --------------------------------------- ## +## Start of automake initialization code ## +## --------------------------------------- ## + +if test "`cd $srcdir && pwd`" != "`pwd`"; then + # Use -I$(srcdir) only when $(srcdir) != ., so that make's output + # is not polluted with repeated "-I." + am__isrc=' -I$(srcdir)' + # test to see if srcdir already configured + if test -f $srcdir/config.status; then + as_fn_error $? "source directory already configured; run \"make distclean\" there first" "$LINENO" 5 + fi +fi + +# test whether we have cygpath +if test -z "$CYGPATH_W"; then + if (cygpath --version) >/dev/null 2>/dev/null; then + CYGPATH_W='cygpath -w' + else + CYGPATH_W=echo + fi +fi + + +# Define the identity of the package. + PACKAGE='curl' + VERSION='-' + + +printf "%s\n" "#define PACKAGE \"$PACKAGE\"" >>confdefs.h + + +printf "%s\n" "#define VERSION \"$VERSION\"" >>confdefs.h + +# Some tools Automake needs. + +ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"} + + +AUTOCONF=${AUTOCONF-"${am_missing_run}autoconf"} + + +AUTOMAKE=${AUTOMAKE-"${am_missing_run}automake-${am__api_version}"} + + +AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"} + + +MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"} + +# For better backward compatibility. To be removed once Automake 1.9.x +# dies out for good. For more background, see: +# +# +mkdir_p='$(MKDIR_P)' + +# We need awk for the "check" target (and possibly the TAP driver). The +# system "awk" is bad on some platforms. +# Always define AMTAR for backward compatibility. Yes, it's still used +# in the wild :-( We should find a proper way to deprecate it ... +AMTAR='$${TAR-tar}' + + +# We'll loop over all known methods to create a tar archive until one works. +_am_tools='gnutar pax cpio none' + +am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -' + + + + + +depcc="$CC" am_compiler_list= + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 +printf %s "checking dependency style of $depcc... " >&6; } +if test ${am_cv_CC_dependencies_compiler_type+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then + # We make a subdir and do the tests there. Otherwise we can end up + # making bogus files that we don't know about and never remove. For + # instance it was reported that on HP-UX the gcc test will end up + # making a dummy file named 'D' -- because '-MD' means "put the output + # in D". + rm -rf conftest.dir + mkdir conftest.dir + # Copy depcomp to subdir because otherwise we won't find it if we're + # using a relative directory. + cp "$am_depcomp" conftest.dir + cd conftest.dir + # We will build objects and dependencies in a subdirectory because + # it helps to detect inapplicable dependency modes. For instance + # both Tru64's cc and ICC support -MD to output dependencies as a + # side effect of compilation, but ICC will put the dependencies in + # the current directory while Tru64 will put them in the object + # directory. + mkdir sub + + am_cv_CC_dependencies_compiler_type=none + if test "$am_compiler_list" = ""; then + am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` + fi + am__universal=false + case " $depcc " in #( + *\ -arch\ *\ -arch\ *) am__universal=true ;; + esac + + for depmode in $am_compiler_list; do + # Setup a source with many dependencies, because some compilers + # like to wrap large dependency lists on column 80 (with \), and + # we should not choose a depcomp mode which is confused by this. + # + # We need to recreate these files for each test, as the compiler may + # overwrite some of them when testing with obscure command lines. + # This happens at least with the AIX C compiler. + : > sub/conftest.c + for i in 1 2 3 4 5 6; do + echo '#include "conftst'$i'.h"' >> sub/conftest.c + # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with + # Solaris 10 /bin/sh. + echo '/* dummy */' > sub/conftst$i.h + done + echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf + + # We check with '-c' and '-o' for the sake of the "dashmstdout" + # mode. It turns out that the SunPro C++ compiler does not properly + # handle '-M -o', and we need to detect this. Also, some Intel + # versions had trouble with output in subdirs. + am__obj=sub/conftest.${OBJEXT-o} + am__minus_obj="-o $am__obj" + case $depmode in + gcc) + # This depmode causes a compiler race in universal mode. + test "$am__universal" = false || continue + ;; + nosideeffect) + # After this tag, mechanisms are not by side-effect, so they'll + # only be used when explicitly requested. + if test "x$enable_dependency_tracking" = xyes; then + continue + else + break + fi + ;; + msvc7 | msvc7msys | msvisualcpp | msvcmsys) + # This compiler won't grok '-c -o', but also, the minuso test has + # not run yet. These depmodes are late enough in the game, and + # so weak that their functioning should not be impacted. + am__obj=conftest.${OBJEXT-o} + am__minus_obj= + ;; + none) break ;; + esac + if depmode=$depmode \ + source=sub/conftest.c object=$am__obj \ + depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ + $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ + >/dev/null 2>conftest.err && + grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && + grep $am__obj sub/conftest.Po > /dev/null 2>&1 && + ${MAKE-make} -s -f confmf > /dev/null 2>&1; then + # icc doesn't choke on unknown options, it will just issue warnings + # or remarks (even with -Werror). So we grep stderr for any message + # that says an option was ignored or not supported. + # When given -MP, icc 7.0 and 7.1 complain thusly: + # icc: Command line warning: ignoring option '-M'; no argument required + # The diagnosis changed in icc 8.0: + # icc: Command line remark: option '-MP' not supported + if (grep 'ignoring option' conftest.err || + grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else + am_cv_CC_dependencies_compiler_type=$depmode + break + fi + fi + done + + cd .. + rm -rf conftest.dir +else + am_cv_CC_dependencies_compiler_type=none +fi + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_CC_dependencies_compiler_type" >&5 +printf "%s\n" "$am_cv_CC_dependencies_compiler_type" >&6; } +CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type + + if + test "x$enable_dependency_tracking" != xno \ + && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then + am__fastdepCC_TRUE= + am__fastdepCC_FALSE='#' +else + am__fastdepCC_TRUE='#' + am__fastdepCC_FALSE= +fi + + +# Variables for tags utilities; see am/tags.am +if test -z "$CTAGS"; then + CTAGS=ctags +fi + +if test -z "$ETAGS"; then + ETAGS=etags +fi + +if test -z "$CSCOPE"; then + CSCOPE=cscope +fi + + + +# POSIX will say in a future version that running "rm -f" with no argument +# is OK; and we want to be able to make that assumption in our Makefile +# recipes. So use an aggressive probe to check that the usage we want is +# actually supported "in the wild" to an acceptable degree. +# See automake bug#10828. +# To make any issue more visible, cause the running configure to be aborted +# by default if the 'rm' program in use doesn't match our expectations; the +# user can still override this though. +if rm -f && rm -fr && rm -rf; then : OK; else + cat >&2 <<'END' +Oops! + +Your 'rm' program seems unable to run without file operands specified +on the command line, even when the '-f' option is present. This is contrary +to the behaviour of most rm programs out there, and not conforming with +the upcoming POSIX standard: + +Please tell bug-automake@gnu.org about your system, including the value +of your $PATH and any error possibly output before this message. This +can help us improve future automake versions. + +END + if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then + echo 'Configuration will proceed anyway, since you have set the' >&2 + echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2 + echo >&2 + else + cat >&2 <<'END' +Aborting the configuration process, to ensure you take notice of the issue. + +You can download and install GNU coreutils to get an 'rm' implementation +that behaves properly: . + +If you want to complete the configuration process using your problematic +'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM +to "yes", and re-run configure. + +END + as_fn_error $? "Your 'rm' program is bad, sorry." "$LINENO" 5 + fi +fi + +## ------------------------------------- ## +## End of automake initialization code ## +## ------------------------------------- ## + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking curl version" >&5 +printf %s "checking curl version... " >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CURLVERSION" >&5 +printf "%s\n" "$CURLVERSION" >&6; } + + + +VERSIONNUM=`$SED -ne 's/^#define LIBCURL_VERSION_NUM 0x\([0-9A-Fa-f]*\).*/\1/p' ${srcdir}/include/curl/curlver.h` + + +PKGADD_PKG="HAXXcurl" +PKGADD_NAME="curl - a client that groks URLs" +PKGADD_VENDOR="curl.se" + + + + + curl_ssl_msg="no (--with-{openssl,gnutls,mbedtls,wolfssl,schannel,secure-transport,amissl,bearssl,rustls} )" + curl_ssh_msg="no (--with-{libssh,libssh2})" + curl_zlib_msg="no (--with-zlib)" + curl_brotli_msg="no (--with-brotli)" + curl_zstd_msg="no (--with-zstd)" + curl_gss_msg="no (--with-gssapi)" + curl_gsasl_msg="no (--with-gsasl)" +curl_tls_srp_msg="no (--enable-tls-srp)" + curl_res_msg="default (--enable-ares / --enable-threaded-resolver)" + curl_ipv6_msg="no (--enable-ipv6)" +curl_unix_sockets_msg="no (--enable-unix-sockets)" + curl_idn_msg="no (--with-{libidn2,winidn})" + curl_docs_msg="enabled (--disable-docs)" + curl_manual_msg="no (--enable-manual)" +curl_libcurl_msg="enabled (--disable-libcurl-option)" +curl_verbose_msg="enabled (--disable-verbose)" + curl_sspi_msg="no (--enable-sspi)" + curl_ldap_msg="no (--enable-ldap / --with-ldap-lib / --with-lber-lib)" + curl_ldaps_msg="no (--enable-ldaps)" + curl_rtsp_msg="no (--enable-rtsp)" + curl_rtmp_msg="no (--with-librtmp)" + curl_psl_msg="no (--with-libpsl)" + curl_altsvc_msg="enabled (--disable-alt-svc)" +curl_headers_msg="enabled (--disable-headers-api)" + curl_hsts_msg="enabled (--disable-hsts)" + curl_ws_msg="no (--enable-websockets)" + ssl_backends= + curl_h1_msg="enabled (internal)" + curl_h2_msg="no (--with-nghttp2)" + curl_h3_msg="no (--with-ngtcp2 --with-nghttp3, --with-quiche, --with-openssl-quic, --with-msh3)" + +enable_altsvc="yes" +hsts="yes" + +INITIAL_LDFLAGS=$LDFLAGS +INITIAL_LIBS=$LIBS + +compilersh="run-compiler" +CURL_SAVED_CC="$CC" +export CURL_SAVED_CC +CURL_SAVED_LD_LIBRARY_PATH="$LD_LIBRARY_PATH" +export CURL_SAVED_LD_LIBRARY_PATH +cat <<\EOF > "$compilersh" +CC="$CURL_SAVED_CC" +export CC +LD_LIBRARY_PATH="$CURL_SAVED_LD_LIBRARY_PATH" +export LD_LIBRARY_PATH +exec $CC "$@" +EOF + +OPT_SCHANNEL=no + +# Check whether --with-schannel was given. +if test ${with_schannel+y} +then : + withval=$with_schannel; OPT_SCHANNEL=$withval + TLSCHOICE="schannel" +fi + + +OPT_SECURETRANSPORT=no + +# Check whether --with-secure-transport was given. +if test ${with_secure_transport+y} +then : + withval=$with_secure_transport; + OPT_SECURETRANSPORT=$withval + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }Secure-Transport" + +fi + + +OPT_AMISSL=no + +# Check whether --with-amissl was given. +if test ${with_amissl+y} +then : + withval=$with_amissl; + OPT_AMISSL=$withval + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }AmiSSL" + +fi + + +OPT_OPENSSL=no +ca="no" + +# Check whether --with-ssl was given. +if test ${with_ssl+y} +then : + withval=$with_ssl; + OPT_SSL=$withval + OPT_OPENSSL=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }OpenSSL" + else + SSL_DISABLED="D" + fi + +fi + + + +# Check whether --with-openssl was given. +if test ${with_openssl+y} +then : + withval=$with_openssl; + OPT_OPENSSL=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }OpenSSL" + fi + +fi + + +OPT_GNUTLS=no + +# Check whether --with-gnutls was given. +if test ${with_gnutls+y} +then : + withval=$with_gnutls; + OPT_GNUTLS=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }GnuTLS" + fi + +fi + + +OPT_MBEDTLS=no + +# Check whether --with-mbedtls was given. +if test ${with_mbedtls+y} +then : + withval=$with_mbedtls; + OPT_MBEDTLS=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }mbedTLS" + fi + +fi + + +OPT_WOLFSSL=no + +# Check whether --with-wolfssl was given. +if test ${with_wolfssl+y} +then : + withval=$with_wolfssl; + OPT_WOLFSSL=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }wolfSSL" + fi + +fi + + +OPT_BEARSSL=no + +# Check whether --with-bearssl was given. +if test ${with_bearssl+y} +then : + withval=$with_bearssl; + OPT_BEARSSL=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }BearSSL" + fi + +fi + + +OPT_RUSTLS=no + +# Check whether --with-rustls was given. +if test ${with_rustls+y} +then : + withval=$with_rustls; + OPT_RUSTLS=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }rustls" + experimental="$experimental rustls" + fi + +fi + + +TEST_NGHTTPX=nghttpx + +# Check whether --with-test-nghttpx was given. +if test ${with_test_nghttpx+y} +then : + withval=$with_test_nghttpx; TEST_NGHTTPX=$withval + if test X"$OPT_TEST_NGHTTPX" = "Xno" ; then + TEST_NGHTTPX="" + fi + +fi + + + +CADDY=/usr/bin/caddy + +# Check whether --with-test-caddy was given. +if test ${with_test_caddy+y} +then : + withval=$with_test_caddy; CADDY=$withval + if test X"$OPT_CADDY" = "Xno" ; then + CADDY="" + fi + +fi + + + +VSFTPD=/usr/sbin/vsftpd + +# Check whether --with-test-vsftpd was given. +if test ${with_test_vsftpd+y} +then : + withval=$with_test_vsftpd; VSFTPD=$withval + if test X"$OPT_VSFTPD" = "Xno" ; then + VSFTPD="" + fi + +fi + + + +HTTPD_ENABLED="maybe" + +# Check whether --with-test-httpd was given. +if test ${with_test_httpd+y} +then : + withval=$with_test_httpd; request_httpd=$withval +else $as_nop + request_httpd=check +fi + +if test x"$request_httpd" = "xcheck" -o x"$request_httpd" = "xyes"; then + if test -x "/usr/sbin/apache2" -a -x "/usr/sbin/apache2ctl"; then + # common location on distros (debian/ubuntu) + HTTPD="/usr/sbin/apache2" + APACHECTL="/usr/sbin/apache2ctl" + # Extract the first word of "apxs", so it can be a program name with args. +set dummy apxs; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_APXS+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $APXS in + [\\/]* | ?:[\\/]*) + ac_cv_path_APXS="$APXS" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_APXS="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +APXS=$ac_cv_path_APXS +if test -n "$APXS"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $APXS" >&5 +printf "%s\n" "$APXS" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + if test "x$APXS" = "x"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: apache2-dev not installed, httpd tests disabled" >&5 +printf "%s\n" "$as_me: apache2-dev not installed, httpd tests disabled" >&6;} + HTTPD_ENABLED="no" + fi + else + # Extract the first word of "httpd", so it can be a program name with args. +set dummy httpd; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_HTTPD+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $HTTPD in + [\\/]* | ?:[\\/]*) + ac_cv_path_HTTPD="$HTTPD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_HTTPD="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +HTTPD=$ac_cv_path_HTTPD +if test -n "$HTTPD"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $HTTPD" >&5 +printf "%s\n" "$HTTPD" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + if test "x$HTTPD" = "x"; then + # Extract the first word of "apache2", so it can be a program name with args. +set dummy apache2; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_HTTPD+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $HTTPD in + [\\/]* | ?:[\\/]*) + ac_cv_path_HTTPD="$HTTPD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_HTTPD="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +HTTPD=$ac_cv_path_HTTPD +if test -n "$HTTPD"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $HTTPD" >&5 +printf "%s\n" "$HTTPD" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + fi + # Extract the first word of "apachectl", so it can be a program name with args. +set dummy apachectl; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_APACHECTL+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $APACHECTL in + [\\/]* | ?:[\\/]*) + ac_cv_path_APACHECTL="$APACHECTL" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_APACHECTL="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +APACHECTL=$ac_cv_path_APACHECTL +if test -n "$APACHECTL"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $APACHECTL" >&5 +printf "%s\n" "$APACHECTL" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + # Extract the first word of "apxs", so it can be a program name with args. +set dummy apxs; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_APXS+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $APXS in + [\\/]* | ?:[\\/]*) + ac_cv_path_APXS="$APXS" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_APXS="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +APXS=$ac_cv_path_APXS +if test -n "$APXS"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $APXS" >&5 +printf "%s\n" "$APXS" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + if test "x$HTTPD" = "x" -o "x$APACHECTL" = "x"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: httpd/apache2 not in PATH, http tests disabled" >&5 +printf "%s\n" "$as_me: httpd/apache2 not in PATH, http tests disabled" >&6;} + HTTPD_ENABLED="no" + fi + if test "x$APXS" = "x"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: apxs not in PATH, http tests disabled" >&5 +printf "%s\n" "$as_me: apxs not in PATH, http tests disabled" >&6;} + HTTPD_ENABLED="no" + fi + fi +elif test x"$request_httpd" != "xno"; then + HTTPD="${request_httpd}/bin/httpd" + APACHECTL="${request_httpd}/bin/apachectl" + APXS="${request_httpd}/bin/apxs" + if test ! -x "${HTTPD}"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: httpd not found as ${HTTPD}, http tests disabled" >&5 +printf "%s\n" "$as_me: httpd not found as ${HTTPD}, http tests disabled" >&6;} + HTTPD_ENABLED="no" + elif test ! -x "${APACHECTL}"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: apachectl not found as ${APACHECTL}, http tests disabled" >&5 +printf "%s\n" "$as_me: apachectl not found as ${APACHECTL}, http tests disabled" >&6;} + HTTPD_ENABLED="no" + elif test ! -x "${APXS}"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: apxs not found as ${APXS}, http tests disabled" >&5 +printf "%s\n" "$as_me: apxs not found as ${APXS}, http tests disabled" >&6;} + HTTPD_ENABLED="no" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: using HTTPD=$HTTPD for tests" >&5 +printf "%s\n" "$as_me: using HTTPD=$HTTPD for tests" >&6;} + fi +fi +if test x"$HTTPD_ENABLED" = "xno"; then + HTTPD="" + APACHECTL="" + APXS="" +fi + + + + +if test "x$TEST_NGHTTPX" != "x" -a "x$TEST_NGHTTPX" != "xnghttpx"; then + HTTPD_NGHTTPX="$TEST_NGHTTPX" +else + # Extract the first word of "nghttpx", so it can be a program name with args. +set dummy nghttpx; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_HTTPD_NGHTTPX+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $HTTPD_NGHTTPX in + [\\/]* | ?:[\\/]*) + ac_cv_path_HTTPD_NGHTTPX="$HTTPD_NGHTTPX" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_HTTPD_NGHTTPX="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +HTTPD_NGHTTPX=$ac_cv_path_HTTPD_NGHTTPX +if test -n "$HTTPD_NGHTTPX"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $HTTPD_NGHTTPX" >&5 +printf "%s\n" "$HTTPD_NGHTTPX" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi + + +if test "x$TEST_CADDY" != "x"; then + CADDY="$TEST_CADDY" +else + # Extract the first word of "caddy", so it can be a program name with args. +set dummy caddy; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_CADDY+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $CADDY in + [\\/]* | ?:[\\/]*) + ac_cv_path_CADDY="$CADDY" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_CADDY="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +CADDY=$ac_cv_path_CADDY +if test -n "$CADDY"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CADDY" >&5 +printf "%s\n" "$CADDY" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi + + +if test -z "$TLSCHOICE"; then + if test "x$OPT_SSL" != "xno"; then + as_fn_error $? "select TLS backend(s) or disable TLS with --without-ssl. + +Select from these: + + --with-amissl + --with-bearssl + --with-gnutls + --with-mbedtls + --with-openssl (also works for BoringSSL and libressl) + --with-rustls + --with-schannel + --with-secure-transport + --with-wolfssl +" "$LINENO" 5 + fi +fi + + +# Check whether --with-darwinssl was given. +if test ${with_darwinssl+y} +then : + withval=$with_darwinssl; as_fn_error $? "--with-darwin-ssl and --without-darwin-ssl no longer work!" "$LINENO" 5 +fi + + + + + + # Make sure we can run config.sub. +$SHELL "${ac_aux_dir}config.sub" sun4 >/dev/null 2>&1 || + as_fn_error $? "cannot run $SHELL ${ac_aux_dir}config.sub" "$LINENO" 5 + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 +printf %s "checking build system type... " >&6; } +if test ${ac_cv_build+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_build_alias=$build_alias +test "x$ac_build_alias" = x && + ac_build_alias=`$SHELL "${ac_aux_dir}config.guess"` +test "x$ac_build_alias" = x && + as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 +ac_cv_build=`$SHELL "${ac_aux_dir}config.sub" $ac_build_alias` || + as_fn_error $? "$SHELL ${ac_aux_dir}config.sub $ac_build_alias failed" "$LINENO" 5 + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 +printf "%s\n" "$ac_cv_build" >&6; } +case $ac_cv_build in +*-*-*) ;; +*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;; +esac +build=$ac_cv_build +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_build +shift +build_cpu=$1 +build_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +build_os=$* +IFS=$ac_save_IFS +case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 +printf %s "checking host system type... " >&6; } +if test ${ac_cv_host+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test "x$host_alias" = x; then + ac_cv_host=$ac_cv_build +else + ac_cv_host=`$SHELL "${ac_aux_dir}config.sub" $host_alias` || + as_fn_error $? "$SHELL ${ac_aux_dir}config.sub $host_alias failed" "$LINENO" 5 +fi + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 +printf "%s\n" "$ac_cv_host" >&6; } +case $ac_cv_host in +*-*-*) ;; +*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;; +esac +host=$ac_cv_host +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_host +shift +host_cpu=$1 +host_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +host_os=$* +IFS=$ac_save_IFS +case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac + + + +printf "%s\n" "#define OS \"${host}\"" >>confdefs.h + + +# Silence warning: ar: 'u' modifier ignored since 'D' is the default +AR_FLAGS=cr + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 +printf %s "checking for grep that handles long lines and -e... " >&6; } +if test ${ac_cv_path_GREP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -z "$GREP"; then + ac_path_GREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_prog in grep ggrep + do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_GREP" || continue +# Check for GNU ac_path_GREP and select it if it is found. + # Check for GNU $ac_path_GREP +case `"$ac_path_GREP" --version 2>&1` in +*GNU*) + ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; +*) + ac_count=0 + printf %s 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + printf "%s\n" 'GREP' >> "conftest.nl" + "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_GREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_GREP="$ac_path_GREP" + ac_path_GREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_GREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_GREP"; then + as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_GREP=$GREP +fi + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 +printf "%s\n" "$ac_cv_path_GREP" >&6; } + GREP="$ac_cv_path_GREP" + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 +printf %s "checking for egrep... " >&6; } +if test ${ac_cv_path_EGREP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 + then ac_cv_path_EGREP="$GREP -E" + else + if test -z "$EGREP"; then + ac_path_EGREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_prog in egrep + do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_EGREP" || continue +# Check for GNU ac_path_EGREP and select it if it is found. + # Check for GNU $ac_path_EGREP +case `"$ac_path_EGREP" --version 2>&1` in +*GNU*) + ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; +*) + ac_count=0 + printf %s 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + printf "%s\n" 'EGREP' >> "conftest.nl" + "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_EGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_EGREP="$ac_path_EGREP" + ac_path_EGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_EGREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_EGREP"; then + as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_EGREP=$EGREP +fi + + fi +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 +printf "%s\n" "$ac_cv_path_EGREP" >&6; } + EGREP="$ac_cv_path_EGREP" + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if OS is AIX (to define _ALL_SOURCE)" >&5 +printf %s "checking if OS is AIX (to define _ALL_SOURCE)... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef _AIX + yes_this_is_aix +#endif + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes_this_is_aix" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + printf "%s\n" "#define _ALL_SOURCE 1" >>confdefs.h + + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -rf conftest* + + + + + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if _THREAD_SAFE is already defined" >&5 +printf %s "checking if _THREAD_SAFE is already defined... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + +#ifdef _THREAD_SAFE + int dummy=1; +#else + force compilation error +#endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tmp_thread_safe_initially_defined="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tmp_thread_safe_initially_defined="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + # + if test "$tmp_thread_safe_initially_defined" = "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if _THREAD_SAFE is actually needed" >&5 +printf %s "checking if _THREAD_SAFE is actually needed... " >&6; } + + case $host_os in + aix[123].* | aix4.[012].*) + tmp_need_thread_safe="no" + ;; + aix*) + tmp_need_thread_safe="yes" + ;; + *) + tmp_need_thread_safe="no" + ;; + esac + + if test "$tmp_need_thread_safe" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if _THREAD_SAFE is onwards defined" >&5 +printf %s "checking if _THREAD_SAFE is onwards defined... " >&6; } + if test "$tmp_thread_safe_initially_defined" = "yes" || + test "$tmp_need_thread_safe" = "yes"; then + + +printf "%s\n" "#define NEED_THREAD_SAFE 1" >>confdefs.h + +cat >>confdefs.h <<_EOF +#ifndef _THREAD_SAFE +# define _THREAD_SAFE +#endif +_EOF + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + # + + + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if _REENTRANT is already defined" >&5 +printf %s "checking if _REENTRANT is already defined... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + +#ifdef _REENTRANT + int dummy=1; +#else + force compilation error +#endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tmp_reentrant_initially_defined="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tmp_reentrant_initially_defined="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + # + if test "$tmp_reentrant_initially_defined" = "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if _REENTRANT is actually needed" >&5 +printf %s "checking if _REENTRANT is actually needed... " >&6; } + + case $host_os in + solaris*) + tmp_need_reentrant="yes" + ;; + *) + tmp_need_reentrant="no" + ;; + esac + + if test "$tmp_need_reentrant" = "no"; then + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#include + +int main (void) +{ + + if(0 != errno) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + tmp_errno="yes" + +else $as_nop + + tmp_errno="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + if test "$tmp_errno" = "yes"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#include + +int main (void) +{ + +#ifdef errno + int dummy=1; +#else + force compilation error +#endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + tmp_errno="errno_macro_defined" + +else $as_nop + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define _REENTRANT +#include + +int main (void) +{ + +#ifdef errno + int dummy=1; +#else + force compilation error +#endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + tmp_errno="errno_macro_needs_reentrant" + tmp_need_reentrant="yes" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + + fi + if test "$tmp_need_reentrant" = "no"; then + + if test "$tmp_need_reentrant" = "no"; then + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define gmtime_r innocuous_gmtime_r +#ifdef __STDC__ +# include +#else +# include +#endif +#undef gmtime_r +#ifdef __cplusplus +extern "C" +#endif +char gmtime_r (); +#if defined __stub_gmtime_r || defined __stub___gmtime_r +choke me +#endif + +int main (void) +{ +return gmtime_r (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + tmp_gmtime_r="yes" + +else $as_nop + + tmp_gmtime_r="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + if test "$tmp_gmtime_r" = "yes"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "gmtime_r" >/dev/null 2>&1 +then : + + tmp_gmtime_r="proto_declared" + +else $as_nop + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#define _REENTRANT +#include +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "gmtime_r" >/dev/null 2>&1 +then : + + tmp_gmtime_r="proto_needs_reentrant" + tmp_need_reentrant="yes" + +fi +rm -rf conftest* + + +fi +rm -rf conftest* + + fi + + fi + if test "$tmp_need_reentrant" = "no"; then + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define localtime_r innocuous_localtime_r +#ifdef __STDC__ +# include +#else +# include +#endif +#undef localtime_r +#ifdef __cplusplus +extern "C" +#endif +char localtime_r (); +#if defined __stub_localtime_r || defined __stub___localtime_r +choke me +#endif + +int main (void) +{ +return localtime_r (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + tmp_localtime_r="yes" + +else $as_nop + + tmp_localtime_r="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + if test "$tmp_localtime_r" = "yes"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "localtime_r" >/dev/null 2>&1 +then : + + tmp_localtime_r="proto_declared" + +else $as_nop + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#define _REENTRANT +#include +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "localtime_r" >/dev/null 2>&1 +then : + + tmp_localtime_r="proto_needs_reentrant" + tmp_need_reentrant="yes" + +fi +rm -rf conftest* + + +fi +rm -rf conftest* + + fi + + fi + if test "$tmp_need_reentrant" = "no"; then + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define strerror_r innocuous_strerror_r +#ifdef __STDC__ +# include +#else +# include +#endif +#undef strerror_r +#ifdef __cplusplus +extern "C" +#endif +char strerror_r (); +#if defined __stub_strerror_r || defined __stub___strerror_r +choke me +#endif + +int main (void) +{ +return strerror_r (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + tmp_strerror_r="yes" + +else $as_nop + + tmp_strerror_r="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + if test "$tmp_strerror_r" = "yes"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "strerror_r" >/dev/null 2>&1 +then : + + tmp_strerror_r="proto_declared" + +else $as_nop + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#define _REENTRANT +#include +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "strerror_r" >/dev/null 2>&1 +then : + + tmp_strerror_r="proto_needs_reentrant" + tmp_need_reentrant="yes" + +fi +rm -rf conftest* + + +fi +rm -rf conftest* + + fi + + fi + if test "$tmp_need_reentrant" = "no"; then + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define strtok_r innocuous_strtok_r +#ifdef __STDC__ +# include +#else +# include +#endif +#undef strtok_r +#ifdef __cplusplus +extern "C" +#endif +char strtok_r (); +#if defined __stub_strtok_r || defined __stub___strtok_r +choke me +#endif + +int main (void) +{ +return strtok_r (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + tmp_strtok_r="yes" + +else $as_nop + + tmp_strtok_r="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + if test "$tmp_strtok_r" = "yes"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "strtok_r" >/dev/null 2>&1 +then : + + tmp_strtok_r="proto_declared" + +else $as_nop + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#define _REENTRANT +#include +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "strtok_r" >/dev/null 2>&1 +then : + + tmp_strtok_r="proto_needs_reentrant" + tmp_need_reentrant="yes" + +fi +rm -rf conftest* + + +fi +rm -rf conftest* + + fi + + fi + if test "$tmp_need_reentrant" = "no"; then + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define gethostbyname_r innocuous_gethostbyname_r +#ifdef __STDC__ +# include +#else +# include +#endif +#undef gethostbyname_r +#ifdef __cplusplus +extern "C" +#endif +char gethostbyname_r (); +#if defined __stub_gethostbyname_r || defined __stub___gethostbyname_r +choke me +#endif + +int main (void) +{ +return gethostbyname_r (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + tmp_gethostbyname_r="yes" + +else $as_nop + + tmp_gethostbyname_r="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + if test "$tmp_gethostbyname_r" = "yes"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "gethostbyname_r" >/dev/null 2>&1 +then : + + tmp_gethostbyname_r="proto_declared" + +else $as_nop + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#define _REENTRANT +#include +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "gethostbyname_r" >/dev/null 2>&1 +then : + + tmp_gethostbyname_r="proto_needs_reentrant" + tmp_need_reentrant="yes" + +fi +rm -rf conftest* + + +fi +rm -rf conftest* + + fi + + fi + if test "$tmp_need_reentrant" = "no"; then + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define getprotobyname_r innocuous_getprotobyname_r +#ifdef __STDC__ +# include +#else +# include +#endif +#undef getprotobyname_r +#ifdef __cplusplus +extern "C" +#endif +char getprotobyname_r (); +#if defined __stub_getprotobyname_r || defined __stub___getprotobyname_r +choke me +#endif + +int main (void) +{ +return getprotobyname_r (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + tmp_getprotobyname_r="yes" + +else $as_nop + + tmp_getprotobyname_r="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + if test "$tmp_getprotobyname_r" = "yes"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "getprotobyname_r" >/dev/null 2>&1 +then : + + tmp_getprotobyname_r="proto_declared" + +else $as_nop + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#define _REENTRANT +#include +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "getprotobyname_r" >/dev/null 2>&1 +then : + + tmp_getprotobyname_r="proto_needs_reentrant" + tmp_need_reentrant="yes" + +fi +rm -rf conftest* + + +fi +rm -rf conftest* + + fi + + fi + + fi + if test "$tmp_need_reentrant" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if _REENTRANT is onwards defined" >&5 +printf %s "checking if _REENTRANT is onwards defined... " >&6; } + if test "$tmp_reentrant_initially_defined" = "yes" || + test "$tmp_need_reentrant" = "yes"; then + + +printf "%s\n" "#define NEED_REENTRANT 1" >>confdefs.h + +cat >>confdefs.h <<_EOF +#ifndef _REENTRANT +# define _REENTRANT +#endif +_EOF + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + # + + +# Check whether --enable-largefile was given. +if test ${enable_largefile+y} +then : + enableval=$enable_largefile; +fi + +if test "$enable_largefile" != no; then + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for special C compiler options needed for large files" >&5 +printf %s "checking for special C compiler options needed for large files... " >&6; } +if test ${ac_cv_sys_largefile_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_cv_sys_largefile_CC=no + if test "$GCC" != yes; then + ac_save_CC=$CC + while :; do + # IRIX 6.2 and later do not support large files by default, + # so use the C compiler's -n32 option if that helps. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + /* Check that off_t can represent 2**63 - 1 correctly. + We can't simply define LARGE_OFF_T to be 9223372036854775807, + since some C++ compilers masquerading as C compilers + incorrectly reject 9223372036854775807. */ +#define LARGE_OFF_T (((off_t) 1 << 31 << 31) - 1 + ((off_t) 1 << 31 << 31)) + int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 + && LARGE_OFF_T % 2147483647 == 1) + ? 1 : -1]; +int main (void) +{ + + ; + return 0; +} +_ACEOF + if ac_fn_c_try_compile "$LINENO" +then : + break +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam + CC="$CC -n32" + if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_sys_largefile_CC=' -n32'; break +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam + break + done + CC=$ac_save_CC + rm -f conftest.$ac_ext + fi +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_largefile_CC" >&5 +printf "%s\n" "$ac_cv_sys_largefile_CC" >&6; } + if test "$ac_cv_sys_largefile_CC" != no; then + CC=$CC$ac_cv_sys_largefile_CC + fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for _FILE_OFFSET_BITS value needed for large files" >&5 +printf %s "checking for _FILE_OFFSET_BITS value needed for large files... " >&6; } +if test ${ac_cv_sys_file_offset_bits+y} +then : + printf %s "(cached) " >&6 +else $as_nop + while :; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + /* Check that off_t can represent 2**63 - 1 correctly. + We can't simply define LARGE_OFF_T to be 9223372036854775807, + since some C++ compilers masquerading as C compilers + incorrectly reject 9223372036854775807. */ +#define LARGE_OFF_T (((off_t) 1 << 31 << 31) - 1 + ((off_t) 1 << 31 << 31)) + int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 + && LARGE_OFF_T % 2147483647 == 1) + ? 1 : -1]; +int main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_sys_file_offset_bits=no; break +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#define _FILE_OFFSET_BITS 64 +#include + /* Check that off_t can represent 2**63 - 1 correctly. + We can't simply define LARGE_OFF_T to be 9223372036854775807, + since some C++ compilers masquerading as C compilers + incorrectly reject 9223372036854775807. */ +#define LARGE_OFF_T (((off_t) 1 << 31 << 31) - 1 + ((off_t) 1 << 31 << 31)) + int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 + && LARGE_OFF_T % 2147483647 == 1) + ? 1 : -1]; +int main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_sys_file_offset_bits=64; break +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + ac_cv_sys_file_offset_bits=unknown + break +done +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_file_offset_bits" >&5 +printf "%s\n" "$ac_cv_sys_file_offset_bits" >&6; } +case $ac_cv_sys_file_offset_bits in #( + no | unknown) ;; + *) +printf "%s\n" "#define _FILE_OFFSET_BITS $ac_cv_sys_file_offset_bits" >>confdefs.h +;; +esac +rm -rf conftest* + if test $ac_cv_sys_file_offset_bits = unknown; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for _LARGE_FILES value needed for large files" >&5 +printf %s "checking for _LARGE_FILES value needed for large files... " >&6; } +if test ${ac_cv_sys_large_files+y} +then : + printf %s "(cached) " >&6 +else $as_nop + while :; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + /* Check that off_t can represent 2**63 - 1 correctly. + We can't simply define LARGE_OFF_T to be 9223372036854775807, + since some C++ compilers masquerading as C compilers + incorrectly reject 9223372036854775807. */ +#define LARGE_OFF_T (((off_t) 1 << 31 << 31) - 1 + ((off_t) 1 << 31 << 31)) + int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 + && LARGE_OFF_T % 2147483647 == 1) + ? 1 : -1]; +int main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_sys_large_files=no; break +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#define _LARGE_FILES 1 +#include + /* Check that off_t can represent 2**63 - 1 correctly. + We can't simply define LARGE_OFF_T to be 9223372036854775807, + since some C++ compilers masquerading as C compilers + incorrectly reject 9223372036854775807. */ +#define LARGE_OFF_T (((off_t) 1 << 31 << 31) - 1 + ((off_t) 1 << 31 << 31)) + int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 + && LARGE_OFF_T % 2147483647 == 1) + ? 1 : -1]; +int main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_sys_large_files=1; break +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + ac_cv_sys_large_files=unknown + break +done +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_large_files" >&5 +printf "%s\n" "$ac_cv_sys_large_files" >&6; } +case $ac_cv_sys_large_files in #( + no | unknown) ;; + *) +printf "%s\n" "#define _LARGE_FILES $ac_cv_sys_large_files" >>confdefs.h +;; +esac +rm -rf conftest* + fi +fi + + +case `pwd` in + *\ * | *\ *) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&5 +printf "%s\n" "$as_me: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&2;} ;; +esac + + + +macro_version='2.4.7' +macro_revision='2.4.7' + + + + + + + + + + + + + + +ltmain=$ac_aux_dir/ltmain.sh + +# Backslashify metacharacters that are still active within +# double-quoted strings. +sed_quote_subst='s/\(["`$\\]\)/\\\1/g' + +# Same as above, but do not quote variable references. +double_quote_subst='s/\(["`\\]\)/\\\1/g' + +# Sed substitution to delay expansion of an escaped shell variable in a +# double_quote_subst'ed string. +delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' + +# Sed substitution to delay expansion of an escaped single quote. +delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' + +# Sed substitution to avoid accidental globbing in evaled expressions +no_glob_subst='s/\*/\\\*/g' + +ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO +ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to print strings" >&5 +printf %s "checking how to print strings... " >&6; } +# Test print first, because it will be a builtin if present. +if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ + test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then + ECHO='print -r --' +elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then + ECHO='printf %s\n' +else + # Use this function as a fallback that always works. + func_fallback_echo () + { + eval 'cat <<_LTECHO_EOF +$1 +_LTECHO_EOF' + } + ECHO='func_fallback_echo' +fi + +# func_echo_all arg... +# Invoke $ECHO with all args, space-separated. +func_echo_all () +{ + $ECHO "" +} + +case $ECHO in + printf*) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: printf" >&5 +printf "%s\n" "printf" >&6; } ;; + print*) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: print -r" >&5 +printf "%s\n" "print -r" >&6; } ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: cat" >&5 +printf "%s\n" "cat" >&6; } ;; +esac + + + + + + + + + + + + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5 +printf %s "checking for a sed that does not truncate output... " >&6; } +if test ${ac_cv_path_SED+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ + for ac_i in 1 2 3 4 5 6 7; do + ac_script="$ac_script$as_nl$ac_script" + done + echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed + { ac_script=; unset ac_script;} + if test -z "$SED"; then + ac_path_SED_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_prog in sed gsed + do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_SED="$as_dir$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_SED" || continue +# Check for GNU ac_path_SED and select it if it is found. + # Check for GNU $ac_path_SED +case `"$ac_path_SED" --version 2>&1` in +*GNU*) + ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;; +*) + ac_count=0 + printf %s 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + printf "%s\n" '' >> "conftest.nl" + "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_SED_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_SED="$ac_path_SED" + ac_path_SED_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_SED_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_SED"; then + as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5 + fi +else + ac_cv_path_SED=$SED +fi + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5 +printf "%s\n" "$ac_cv_path_SED" >&6; } + SED="$ac_cv_path_SED" + rm -f conftest.sed + +test -z "$SED" && SED=sed +Xsed="$SED -e 1s/^X//" + + + + + + + + + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5 +printf %s "checking for fgrep... " >&6; } +if test ${ac_cv_path_FGREP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1 + then ac_cv_path_FGREP="$GREP -F" + else + if test -z "$FGREP"; then + ac_path_FGREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_prog in fgrep + do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_FGREP="$as_dir$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_FGREP" || continue +# Check for GNU ac_path_FGREP and select it if it is found. + # Check for GNU $ac_path_FGREP +case `"$ac_path_FGREP" --version 2>&1` in +*GNU*) + ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_found=:;; +*) + ac_count=0 + printf %s 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + printf "%s\n" 'FGREP' >> "conftest.nl" + "$ac_path_FGREP" FGREP < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_FGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_FGREP="$ac_path_FGREP" + ac_path_FGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_FGREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_FGREP"; then + as_fn_error $? "no acceptable fgrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_FGREP=$FGREP +fi + + fi +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_FGREP" >&5 +printf "%s\n" "$ac_cv_path_FGREP" >&6; } + FGREP="$ac_cv_path_FGREP" + + +test -z "$GREP" && GREP=grep + + + + + + + + + + + + + + + + + + + +# Check whether --with-gnu-ld was given. +if test ${with_gnu_ld+y} +then : + withval=$with_gnu_ld; test no = "$withval" || with_gnu_ld=yes +else $as_nop + with_gnu_ld=no +fi + +ac_prog=ld +if test yes = "$GCC"; then + # Check if gcc -print-prog-name=ld gives a path. + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 +printf %s "checking for ld used by $CC... " >&6; } + case $host in + *-*-mingw*) + # gcc leaves a trailing carriage return, which upsets mingw + ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; + *) + ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; + esac + case $ac_prog in + # Accept absolute paths. + [\\/]* | ?:[\\/]*) + re_direlt='/[^/][^/]*/\.\./' + # Canonicalize the pathname of ld + ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` + while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do + ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` + done + test -z "$LD" && LD=$ac_prog + ;; + "") + # If it fails, then pretend we aren't using GCC. + ac_prog=ld + ;; + *) + # If it is relative, then search for the first ld in PATH. + with_gnu_ld=unknown + ;; + esac +elif test yes = "$with_gnu_ld"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 +printf %s "checking for GNU ld... " >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5 +printf %s "checking for non-GNU ld... " >&6; } +fi +if test ${lt_cv_path_LD+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -z "$LD"; then + lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR + for ac_dir in $PATH; do + IFS=$lt_save_ifs + test -z "$ac_dir" && ac_dir=. + if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then + lt_cv_path_LD=$ac_dir/$ac_prog + # Check to see if the program is GNU ld. I'd rather use --version, + # but apparently some variants of GNU ld only accept -v. + # Break only if it was the GNU/non-GNU ld that we prefer. + case `"$lt_cv_path_LD" -v 2>&1 &5 +printf "%s\n" "$LD" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi +test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5 +printf %s "checking if the linker ($LD) is GNU ld... " >&6; } +if test ${lt_cv_prog_gnu_ld+y} +then : + printf %s "(cached) " >&6 +else $as_nop + # I'd rather use --version here, but apparently some GNU lds only accept -v. +case `$LD -v 2>&1 &5 +printf "%s\n" "$lt_cv_prog_gnu_ld" >&6; } +with_gnu_ld=$lt_cv_prog_gnu_ld + + + + + + + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for BSD- or MS-compatible name lister (nm)" >&5 +printf %s "checking for BSD- or MS-compatible name lister (nm)... " >&6; } +if test ${lt_cv_path_NM+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$NM"; then + # Let the user override the test. + lt_cv_path_NM=$NM +else + lt_nm_to_check=${ac_tool_prefix}nm + if test -n "$ac_tool_prefix" && test "$build" = "$host"; then + lt_nm_to_check="$lt_nm_to_check nm" + fi + for lt_tmp_nm in $lt_nm_to_check; do + lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR + for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do + IFS=$lt_save_ifs + test -z "$ac_dir" && ac_dir=. + tmp_nm=$ac_dir/$lt_tmp_nm + if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext"; then + # Check to see if the nm accepts a BSD-compat flag. + # Adding the 'sed 1q' prevents false positives on HP-UX, which says: + # nm: unknown option "B" ignored + # Tru64's nm complains that /dev/null is an invalid object file + # MSYS converts /dev/null to NUL, MinGW nm treats NUL as empty + case $build_os in + mingw*) lt_bad_file=conftest.nm/nofile ;; + *) lt_bad_file=/dev/null ;; + esac + case `"$tmp_nm" -B $lt_bad_file 2>&1 | $SED '1q'` in + *$lt_bad_file* | *'Invalid file or object type'*) + lt_cv_path_NM="$tmp_nm -B" + break 2 + ;; + *) + case `"$tmp_nm" -p /dev/null 2>&1 | $SED '1q'` in + */dev/null*) + lt_cv_path_NM="$tmp_nm -p" + break 2 + ;; + *) + lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but + continue # so that we can try to find one that supports BSD flags + ;; + esac + ;; + esac + fi + done + IFS=$lt_save_ifs + done + : ${lt_cv_path_NM=no} +fi +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5 +printf "%s\n" "$lt_cv_path_NM" >&6; } +if test no != "$lt_cv_path_NM"; then + NM=$lt_cv_path_NM +else + # Didn't find any BSD compatible name lister, look for dumpbin. + if test -n "$DUMPBIN"; then : + # Let the user override the test. + else + if test -n "$ac_tool_prefix"; then + for ac_prog in dumpbin "link -dump" + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_DUMPBIN+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$DUMPBIN"; then + ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_DUMPBIN="$ac_tool_prefix$ac_prog" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +DUMPBIN=$ac_cv_prog_DUMPBIN +if test -n "$DUMPBIN"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DUMPBIN" >&5 +printf "%s\n" "$DUMPBIN" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + test -n "$DUMPBIN" && break + done +fi +if test -z "$DUMPBIN"; then + ac_ct_DUMPBIN=$DUMPBIN + for ac_prog in dumpbin "link -dump" +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_DUMPBIN+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_DUMPBIN"; then + ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_DUMPBIN="$ac_prog" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_DUMPBIN=$ac_cv_prog_ac_ct_DUMPBIN +if test -n "$ac_ct_DUMPBIN"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DUMPBIN" >&5 +printf "%s\n" "$ac_ct_DUMPBIN" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + test -n "$ac_ct_DUMPBIN" && break +done + + if test "x$ac_ct_DUMPBIN" = x; then + DUMPBIN=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + DUMPBIN=$ac_ct_DUMPBIN + fi +fi + + case `$DUMPBIN -symbols -headers /dev/null 2>&1 | $SED '1q'` in + *COFF*) + DUMPBIN="$DUMPBIN -symbols -headers" + ;; + *) + DUMPBIN=: + ;; + esac + fi + + if test : != "$DUMPBIN"; then + NM=$DUMPBIN + fi +fi +test -z "$NM" && NM=nm + + + + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking the name lister ($NM) interface" >&5 +printf %s "checking the name lister ($NM) interface... " >&6; } +if test ${lt_cv_nm_interface+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_nm_interface="BSD nm" + echo "int some_variable = 0;" > conftest.$ac_ext + (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&5) + (eval "$ac_compile" 2>conftest.err) + cat conftest.err >&5 + (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&5) + (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) + cat conftest.err >&5 + (eval echo "\"\$as_me:$LINENO: output\"" >&5) + cat conftest.out >&5 + if $GREP 'External.*some_variable' conftest.out > /dev/null; then + lt_cv_nm_interface="MS dumpbin" + fi + rm -f conftest* +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5 +printf "%s\n" "$lt_cv_nm_interface" >&6; } + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5 +printf %s "checking whether ln -s works... " >&6; } +LN_S=$as_ln_s +if test "$LN_S" = "ln -s"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5 +printf "%s\n" "no, using $LN_S" >&6; } +fi + +# find the maximum length of command line arguments +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking the maximum length of command line arguments" >&5 +printf %s "checking the maximum length of command line arguments... " >&6; } +if test ${lt_cv_sys_max_cmd_len+y} +then : + printf %s "(cached) " >&6 +else $as_nop + i=0 + teststring=ABCD + + case $build_os in + msdosdjgpp*) + # On DJGPP, this test can blow up pretty badly due to problems in libc + # (any single argument exceeding 2000 bytes causes a buffer overrun + # during glob expansion). Even if it were fixed, the result of this + # check would be larger than it should be. + lt_cv_sys_max_cmd_len=12288; # 12K is about right + ;; + + gnu*) + # Under GNU Hurd, this test is not required because there is + # no limit to the length of command line arguments. + # Libtool will interpret -1 as no limit whatsoever + lt_cv_sys_max_cmd_len=-1; + ;; + + cygwin* | mingw* | cegcc*) + # On Win9x/ME, this test blows up -- it succeeds, but takes + # about 5 minutes as the teststring grows exponentially. + # Worse, since 9x/ME are not pre-emptively multitasking, + # you end up with a "frozen" computer, even though with patience + # the test eventually succeeds (with a max line length of 256k). + # Instead, let's just punt: use the minimum linelength reported by + # all of the supported platforms: 8192 (on NT/2K/XP). + lt_cv_sys_max_cmd_len=8192; + ;; + + mint*) + # On MiNT this can take a long time and run out of memory. + lt_cv_sys_max_cmd_len=8192; + ;; + + amigaos*) + # On AmigaOS with pdksh, this test takes hours, literally. + # So we just punt and use a minimum line length of 8192. + lt_cv_sys_max_cmd_len=8192; + ;; + + bitrig* | darwin* | dragonfly* | freebsd* | midnightbsd* | netbsd* | openbsd*) + # This has been around since 386BSD, at least. Likely further. + if test -x /sbin/sysctl; then + lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` + elif test -x /usr/sbin/sysctl; then + lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` + else + lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs + fi + # And add a safety zone + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` + ;; + + interix*) + # We know the value 262144 and hardcode it with a safety zone (like BSD) + lt_cv_sys_max_cmd_len=196608 + ;; + + os2*) + # The test takes a long time on OS/2. + lt_cv_sys_max_cmd_len=8192 + ;; + + osf*) + # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure + # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not + # nice to cause kernel panics so lets avoid the loop below. + # First set a reasonable default. + lt_cv_sys_max_cmd_len=16384 + # + if test -x /sbin/sysconfig; then + case `/sbin/sysconfig -q proc exec_disable_arg_limit` in + *1*) lt_cv_sys_max_cmd_len=-1 ;; + esac + fi + ;; + sco3.2v5*) + lt_cv_sys_max_cmd_len=102400 + ;; + sysv5* | sco5v6* | sysv4.2uw2*) + kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` + if test -n "$kargmax"; then + lt_cv_sys_max_cmd_len=`echo $kargmax | $SED 's/.*[ ]//'` + else + lt_cv_sys_max_cmd_len=32768 + fi + ;; + *) + lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` + if test -n "$lt_cv_sys_max_cmd_len" && \ + test undefined != "$lt_cv_sys_max_cmd_len"; then + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` + else + # Make teststring a little bigger before we do anything with it. + # a 1K string should be a reasonable start. + for i in 1 2 3 4 5 6 7 8; do + teststring=$teststring$teststring + done + SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} + # If test is not a shell built-in, we'll probably end up computing a + # maximum length that is only half of the actual maximum length, but + # we can't tell. + while { test X`env echo "$teststring$teststring" 2>/dev/null` \ + = "X$teststring$teststring"; } >/dev/null 2>&1 && + test 17 != "$i" # 1/2 MB should be enough + do + i=`expr $i + 1` + teststring=$teststring$teststring + done + # Only check the string length outside the loop. + lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` + teststring= + # Add a significant safety factor because C++ compilers can tack on + # massive amounts of additional arguments before passing them to the + # linker. It appears as though 1/2 is a usable value. + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` + fi + ;; + esac + +fi + +if test -n "$lt_cv_sys_max_cmd_len"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_max_cmd_len" >&5 +printf "%s\n" "$lt_cv_sys_max_cmd_len" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none" >&5 +printf "%s\n" "none" >&6; } +fi +max_cmd_len=$lt_cv_sys_max_cmd_len + + + + + + +: ${CP="cp -f"} +: ${MV="mv -f"} +: ${RM="rm -f"} + +if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then + lt_unset=unset +else + lt_unset=false +fi + + + + + +# test EBCDIC or ASCII +case `echo X|tr X '\101'` in + A) # ASCII based system + # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr + lt_SP2NL='tr \040 \012' + lt_NL2SP='tr \015\012 \040\040' + ;; + *) # EBCDIC based system + lt_SP2NL='tr \100 \n' + lt_NL2SP='tr \r\n \100\100' + ;; +esac + + + + + + + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to $host format" >&5 +printf %s "checking how to convert $build file names to $host format... " >&6; } +if test ${lt_cv_to_host_file_cmd+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $host in + *-*-mingw* ) + case $build in + *-*-mingw* ) # actually msys + lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 + ;; + *-*-cygwin* ) + lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32 + ;; + * ) # otherwise, assume *nix + lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32 + ;; + esac + ;; + *-*-cygwin* ) + case $build in + *-*-mingw* ) # actually msys + lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin + ;; + *-*-cygwin* ) + lt_cv_to_host_file_cmd=func_convert_file_noop + ;; + * ) # otherwise, assume *nix + lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin + ;; + esac + ;; + * ) # unhandled hosts (and "normal" native builds) + lt_cv_to_host_file_cmd=func_convert_file_noop + ;; +esac + +fi + +to_host_file_cmd=$lt_cv_to_host_file_cmd +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_host_file_cmd" >&5 +printf "%s\n" "$lt_cv_to_host_file_cmd" >&6; } + + + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to toolchain format" >&5 +printf %s "checking how to convert $build file names to toolchain format... " >&6; } +if test ${lt_cv_to_tool_file_cmd+y} +then : + printf %s "(cached) " >&6 +else $as_nop + #assume ordinary cross tools, or native build. +lt_cv_to_tool_file_cmd=func_convert_file_noop +case $host in + *-*-mingw* ) + case $build in + *-*-mingw* ) # actually msys + lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 + ;; + esac + ;; +esac + +fi + +to_tool_file_cmd=$lt_cv_to_tool_file_cmd +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_tool_file_cmd" >&5 +printf "%s\n" "$lt_cv_to_tool_file_cmd" >&6; } + + + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $LD option to reload object files" >&5 +printf %s "checking for $LD option to reload object files... " >&6; } +if test ${lt_cv_ld_reload_flag+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_ld_reload_flag='-r' +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5 +printf "%s\n" "$lt_cv_ld_reload_flag" >&6; } +reload_flag=$lt_cv_ld_reload_flag +case $reload_flag in +"" | " "*) ;; +*) reload_flag=" $reload_flag" ;; +esac +reload_cmds='$LD$reload_flag -o $output$reload_objs' +case $host_os in + cygwin* | mingw* | pw32* | cegcc*) + if test yes != "$GCC"; then + reload_cmds=false + fi + ;; + darwin*) + if test yes = "$GCC"; then + reload_cmds='$LTCC $LTCFLAGS -nostdlib $wl-r -o $output$reload_objs' + else + reload_cmds='$LD$reload_flag -o $output$reload_objs' + fi + ;; +esac + + + + + + + + + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}file", so it can be a program name with args. +set dummy ${ac_tool_prefix}file; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_FILECMD+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$FILECMD"; then + ac_cv_prog_FILECMD="$FILECMD" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_FILECMD="${ac_tool_prefix}file" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +FILECMD=$ac_cv_prog_FILECMD +if test -n "$FILECMD"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $FILECMD" >&5 +printf "%s\n" "$FILECMD" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_FILECMD"; then + ac_ct_FILECMD=$FILECMD + # Extract the first word of "file", so it can be a program name with args. +set dummy file; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_FILECMD+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_FILECMD"; then + ac_cv_prog_ac_ct_FILECMD="$ac_ct_FILECMD" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_FILECMD="file" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_FILECMD=$ac_cv_prog_ac_ct_FILECMD +if test -n "$ac_ct_FILECMD"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_FILECMD" >&5 +printf "%s\n" "$ac_ct_FILECMD" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_FILECMD" = x; then + FILECMD=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + FILECMD=$ac_ct_FILECMD + fi +else + FILECMD="$ac_cv_prog_FILECMD" +fi + + + + + + + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args. +set dummy ${ac_tool_prefix}objdump; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_OBJDUMP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$OBJDUMP"; then + ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +OBJDUMP=$ac_cv_prog_OBJDUMP +if test -n "$OBJDUMP"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5 +printf "%s\n" "$OBJDUMP" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_OBJDUMP"; then + ac_ct_OBJDUMP=$OBJDUMP + # Extract the first word of "objdump", so it can be a program name with args. +set dummy objdump; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_OBJDUMP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_OBJDUMP"; then + ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_OBJDUMP="objdump" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP +if test -n "$ac_ct_OBJDUMP"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5 +printf "%s\n" "$ac_ct_OBJDUMP" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_OBJDUMP" = x; then + OBJDUMP="false" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + OBJDUMP=$ac_ct_OBJDUMP + fi +else + OBJDUMP="$ac_cv_prog_OBJDUMP" +fi + +test -z "$OBJDUMP" && OBJDUMP=objdump + + + + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to recognize dependent libraries" >&5 +printf %s "checking how to recognize dependent libraries... " >&6; } +if test ${lt_cv_deplibs_check_method+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_file_magic_cmd='$MAGIC_CMD' +lt_cv_file_magic_test_file= +lt_cv_deplibs_check_method='unknown' +# Need to set the preceding variable on all platforms that support +# interlibrary dependencies. +# 'none' -- dependencies not supported. +# 'unknown' -- same as none, but documents that we really don't know. +# 'pass_all' -- all dependencies passed with no checks. +# 'test_compile' -- check by making test program. +# 'file_magic [[regex]]' -- check by looking for files in library path +# that responds to the $file_magic_cmd with a given extended regex. +# If you have 'file' or equivalent on your system and you're not sure +# whether 'pass_all' will *always* work, you probably want this one. + +case $host_os in +aix[4-9]*) + lt_cv_deplibs_check_method=pass_all + ;; + +beos*) + lt_cv_deplibs_check_method=pass_all + ;; + +bsdi[45]*) + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)' + lt_cv_file_magic_cmd='$FILECMD -L' + lt_cv_file_magic_test_file=/shlib/libc.so + ;; + +cygwin*) + # func_win32_libid is a shell function defined in ltmain.sh + lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' + lt_cv_file_magic_cmd='func_win32_libid' + ;; + +mingw* | pw32*) + # Base MSYS/MinGW do not provide the 'file' command needed by + # func_win32_libid shell function, so use a weaker test based on 'objdump', + # unless we find 'file', for example because we are cross-compiling. + if ( file / ) >/dev/null 2>&1; then + lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' + lt_cv_file_magic_cmd='func_win32_libid' + else + # Keep this pattern in sync with the one in func_win32_libid. + lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' + lt_cv_file_magic_cmd='$OBJDUMP -f' + fi + ;; + +cegcc*) + # use the weaker test based on 'objdump'. See mingw*. + lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' + lt_cv_file_magic_cmd='$OBJDUMP -f' + ;; + +darwin* | rhapsody*) + lt_cv_deplibs_check_method=pass_all + ;; + +freebsd* | dragonfly* | midnightbsd*) + if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then + case $host_cpu in + i*86 ) + # Not sure whether the presence of OpenBSD here was a mistake. + # Let's accept both of them until this is cleared up. + lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library' + lt_cv_file_magic_cmd=$FILECMD + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` + ;; + esac + else + lt_cv_deplibs_check_method=pass_all + fi + ;; + +haiku*) + lt_cv_deplibs_check_method=pass_all + ;; + +hpux10.20* | hpux11*) + lt_cv_file_magic_cmd=$FILECMD + case $host_cpu in + ia64*) + lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64' + lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so + ;; + hppa*64*) + lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]' + lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl + ;; + *) + lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9]\.[0-9]) shared library' + lt_cv_file_magic_test_file=/usr/lib/libc.sl + ;; + esac + ;; + +interix[3-9]*) + # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$' + ;; + +irix5* | irix6* | nonstopux*) + case $LD in + *-32|*"-32 ") libmagic=32-bit;; + *-n32|*"-n32 ") libmagic=N32;; + *-64|*"-64 ") libmagic=64-bit;; + *) libmagic=never-match;; + esac + lt_cv_deplibs_check_method=pass_all + ;; + +# This must be glibc/ELF. +linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) + lt_cv_deplibs_check_method=pass_all + ;; + +netbsd* | netbsdelf*-gnu) + if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' + else + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$' + fi + ;; + +newos6*) + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)' + lt_cv_file_magic_cmd=$FILECMD + lt_cv_file_magic_test_file=/usr/lib/libnls.so + ;; + +*nto* | *qnx*) + lt_cv_deplibs_check_method=pass_all + ;; + +openbsd* | bitrig*) + if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$' + else + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' + fi + ;; + +osf3* | osf4* | osf5*) + lt_cv_deplibs_check_method=pass_all + ;; + +rdos*) + lt_cv_deplibs_check_method=pass_all + ;; + +solaris*) + lt_cv_deplibs_check_method=pass_all + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + lt_cv_deplibs_check_method=pass_all + ;; + +sysv4 | sysv4.3*) + case $host_vendor in + motorola) + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]' + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` + ;; + ncr) + lt_cv_deplibs_check_method=pass_all + ;; + sequent) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )' + ;; + sni) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib" + lt_cv_file_magic_test_file=/lib/libc.so + ;; + siemens) + lt_cv_deplibs_check_method=pass_all + ;; + pc) + lt_cv_deplibs_check_method=pass_all + ;; + esac + ;; + +tpf*) + lt_cv_deplibs_check_method=pass_all + ;; +os2*) + lt_cv_deplibs_check_method=pass_all + ;; +esac + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_deplibs_check_method" >&5 +printf "%s\n" "$lt_cv_deplibs_check_method" >&6; } + +file_magic_glob= +want_nocaseglob=no +if test "$build" = "$host"; then + case $host_os in + mingw* | pw32*) + if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then + want_nocaseglob=yes + else + file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[\1]\/[\1]\/g;/g"` + fi + ;; + esac +fi + +file_magic_cmd=$lt_cv_file_magic_cmd +deplibs_check_method=$lt_cv_deplibs_check_method +test -z "$deplibs_check_method" && deplibs_check_method=unknown + + + + + + + + + + + + + + + + + + + + + + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args. +set dummy ${ac_tool_prefix}dlltool; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_DLLTOOL+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$DLLTOOL"; then + ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +DLLTOOL=$ac_cv_prog_DLLTOOL +if test -n "$DLLTOOL"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5 +printf "%s\n" "$DLLTOOL" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_DLLTOOL"; then + ac_ct_DLLTOOL=$DLLTOOL + # Extract the first word of "dlltool", so it can be a program name with args. +set dummy dlltool; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_DLLTOOL+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_DLLTOOL"; then + ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_DLLTOOL="dlltool" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL +if test -n "$ac_ct_DLLTOOL"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5 +printf "%s\n" "$ac_ct_DLLTOOL" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_DLLTOOL" = x; then + DLLTOOL="false" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + DLLTOOL=$ac_ct_DLLTOOL + fi +else + DLLTOOL="$ac_cv_prog_DLLTOOL" +fi + +test -z "$DLLTOOL" && DLLTOOL=dlltool + + + + + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to associate runtime and link libraries" >&5 +printf %s "checking how to associate runtime and link libraries... " >&6; } +if test ${lt_cv_sharedlib_from_linklib_cmd+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_sharedlib_from_linklib_cmd='unknown' + +case $host_os in +cygwin* | mingw* | pw32* | cegcc*) + # two different shell functions defined in ltmain.sh; + # decide which one to use based on capabilities of $DLLTOOL + case `$DLLTOOL --help 2>&1` in + *--identify-strict*) + lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib + ;; + *) + lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback + ;; + esac + ;; +*) + # fallback: assume linklib IS sharedlib + lt_cv_sharedlib_from_linklib_cmd=$ECHO + ;; +esac + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sharedlib_from_linklib_cmd" >&5 +printf "%s\n" "$lt_cv_sharedlib_from_linklib_cmd" >&6; } +sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd +test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO + + + + + + + +if test -n "$ac_tool_prefix"; then + for ac_prog in ar + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_AR+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$AR"; then + ac_cv_prog_AR="$AR" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_AR="$ac_tool_prefix$ac_prog" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +AR=$ac_cv_prog_AR +if test -n "$AR"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 +printf "%s\n" "$AR" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + test -n "$AR" && break + done +fi +if test -z "$AR"; then + ac_ct_AR=$AR + for ac_prog in ar +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_AR+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_AR"; then + ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_AR="$ac_prog" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_AR=$ac_cv_prog_ac_ct_AR +if test -n "$ac_ct_AR"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5 +printf "%s\n" "$ac_ct_AR" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + test -n "$ac_ct_AR" && break +done + + if test "x$ac_ct_AR" = x; then + AR="false" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + AR=$ac_ct_AR + fi +fi + +: ${AR=ar} + + + + + + +# Use ARFLAGS variable as AR's operation code to sync the variable naming with +# Automake. If both AR_FLAGS and ARFLAGS are specified, AR_FLAGS should have +# higher priority because thats what people were doing historically (setting +# ARFLAGS for automake and AR_FLAGS for libtool). FIXME: Make the AR_FLAGS +# variable obsoleted/removed. + +test ${AR_FLAGS+y} || AR_FLAGS=${ARFLAGS-cr} +lt_ar_flags=$AR_FLAGS + + + + + + +# Make AR_FLAGS overridable by 'make ARFLAGS='. Don't try to run-time override +# by AR_FLAGS because that was never working and AR_FLAGS is about to die. + + + + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for archiver @FILE support" >&5 +printf %s "checking for archiver @FILE support... " >&6; } +if test ${lt_cv_ar_at_file+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_ar_at_file=no + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + echo conftest.$ac_objext > conftest.lst + lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 + (eval $lt_ar_try) 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + if test 0 -eq "$ac_status"; then + # Ensure the archiver fails upon bogus file names. + rm -f conftest.$ac_objext libconftest.a + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 + (eval $lt_ar_try) 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + if test 0 -ne "$ac_status"; then + lt_cv_ar_at_file=@ + fi + fi + rm -f conftest.* libconftest.a + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ar_at_file" >&5 +printf "%s\n" "$lt_cv_ar_at_file" >&6; } + +if test no = "$lt_cv_ar_at_file"; then + archiver_list_spec= +else + archiver_list_spec=$lt_cv_ar_at_file +fi + + + + + + + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. +set dummy ${ac_tool_prefix}strip; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_STRIP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$STRIP"; then + ac_cv_prog_STRIP="$STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_STRIP="${ac_tool_prefix}strip" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +STRIP=$ac_cv_prog_STRIP +if test -n "$STRIP"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 +printf "%s\n" "$STRIP" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_STRIP"; then + ac_ct_STRIP=$STRIP + # Extract the first word of "strip", so it can be a program name with args. +set dummy strip; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_STRIP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_STRIP"; then + ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_STRIP="strip" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP +if test -n "$ac_ct_STRIP"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 +printf "%s\n" "$ac_ct_STRIP" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_STRIP" = x; then + STRIP=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + STRIP=$ac_ct_STRIP + fi +else + STRIP="$ac_cv_prog_STRIP" +fi + +test -z "$STRIP" && STRIP=: + + + + + + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. +set dummy ${ac_tool_prefix}ranlib; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_RANLIB+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$RANLIB"; then + ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +RANLIB=$ac_cv_prog_RANLIB +if test -n "$RANLIB"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 +printf "%s\n" "$RANLIB" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_RANLIB"; then + ac_ct_RANLIB=$RANLIB + # Extract the first word of "ranlib", so it can be a program name with args. +set dummy ranlib; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_RANLIB+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_RANLIB"; then + ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_RANLIB="ranlib" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB +if test -n "$ac_ct_RANLIB"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 +printf "%s\n" "$ac_ct_RANLIB" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_RANLIB" = x; then + RANLIB=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + RANLIB=$ac_ct_RANLIB + fi +else + RANLIB="$ac_cv_prog_RANLIB" +fi + +test -z "$RANLIB" && RANLIB=: + + + + + + +# Determine commands to create old-style static archives. +old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' +old_postinstall_cmds='chmod 644 $oldlib' +old_postuninstall_cmds= + +if test -n "$RANLIB"; then + case $host_os in + bitrig* | openbsd*) + old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" + ;; + *) + old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" + ;; + esac + old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" +fi + +case $host_os in + darwin*) + lock_old_archive_extraction=yes ;; + *) + lock_old_archive_extraction=no ;; +esac + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} + +# Allow CC to be a program name with arguments. +compiler=$CC + + +# Check for command to grab the raw symbol name followed by C symbol from nm. +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking command to parse $NM output from $compiler object" >&5 +printf %s "checking command to parse $NM output from $compiler object... " >&6; } +if test ${lt_cv_sys_global_symbol_pipe+y} +then : + printf %s "(cached) " >&6 +else $as_nop + +# These are sane defaults that work on at least a few old systems. +# [They come from Ultrix. What could be older than Ultrix?!! ;)] + +# Character class describing NM global symbol codes. +symcode='[BCDEGRST]' + +# Regexp to match symbols that can be accessed directly from C. +sympat='\([_A-Za-z][_A-Za-z0-9]*\)' + +# Define system-specific variables. +case $host_os in +aix*) + symcode='[BCDT]' + ;; +cygwin* | mingw* | pw32* | cegcc*) + symcode='[ABCDGISTW]' + ;; +hpux*) + if test ia64 = "$host_cpu"; then + symcode='[ABCDEGRST]' + fi + ;; +irix* | nonstopux*) + symcode='[BCDEGRST]' + ;; +osf*) + symcode='[BCDEGQRST]' + ;; +solaris*) + symcode='[BDRT]' + ;; +sco3.2v5*) + symcode='[DT]' + ;; +sysv4.2uw2*) + symcode='[DT]' + ;; +sysv5* | sco5v6* | unixware* | OpenUNIX*) + symcode='[ABDT]' + ;; +sysv4) + symcode='[DFNSTU]' + ;; +esac + +# If we're using GNU nm, then use its standard symbol codes. +case `$NM -V 2>&1` in +*GNU* | *'with BFD'*) + symcode='[ABCDGIRSTW]' ;; +esac + +if test "$lt_cv_nm_interface" = "MS dumpbin"; then + # Gets list of data symbols to import. + lt_cv_sys_global_symbol_to_import="$SED -n -e 's/^I .* \(.*\)$/\1/p'" + # Adjust the below global symbol transforms to fixup imported variables. + lt_cdecl_hook=" -e 's/^I .* \(.*\)$/extern __declspec(dllimport) char \1;/p'" + lt_c_name_hook=" -e 's/^I .* \(.*\)$/ {\"\1\", (void *) 0},/p'" + lt_c_name_lib_hook="\ + -e 's/^I .* \(lib.*\)$/ {\"\1\", (void *) 0},/p'\ + -e 's/^I .* \(.*\)$/ {\"lib\1\", (void *) 0},/p'" +else + # Disable hooks by default. + lt_cv_sys_global_symbol_to_import= + lt_cdecl_hook= + lt_c_name_hook= + lt_c_name_lib_hook= +fi + +# Transform an extracted symbol line into a proper C declaration. +# Some systems (esp. on ia64) link data and code symbols differently, +# so use this general approach. +lt_cv_sys_global_symbol_to_cdecl="$SED -n"\ +$lt_cdecl_hook\ +" -e 's/^T .* \(.*\)$/extern int \1();/p'"\ +" -e 's/^$symcode$symcode* .* \(.*\)$/extern char \1;/p'" + +# Transform an extracted symbol line into symbol name and symbol address +lt_cv_sys_global_symbol_to_c_name_address="$SED -n"\ +$lt_c_name_hook\ +" -e 's/^: \(.*\) .*$/ {\"\1\", (void *) 0},/p'"\ +" -e 's/^$symcode$symcode* .* \(.*\)$/ {\"\1\", (void *) \&\1},/p'" + +# Transform an extracted symbol line into symbol name with lib prefix and +# symbol address. +lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="$SED -n"\ +$lt_c_name_lib_hook\ +" -e 's/^: \(.*\) .*$/ {\"\1\", (void *) 0},/p'"\ +" -e 's/^$symcode$symcode* .* \(lib.*\)$/ {\"\1\", (void *) \&\1},/p'"\ +" -e 's/^$symcode$symcode* .* \(.*\)$/ {\"lib\1\", (void *) \&\1},/p'" + +# Handle CRLF in mingw tool chain +opt_cr= +case $build_os in +mingw*) + opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp + ;; +esac + +# Try without a prefix underscore, then with it. +for ac_symprfx in "" "_"; do + + # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. + symxfrm="\\1 $ac_symprfx\\2 \\2" + + # Write the raw and C identifiers. + if test "$lt_cv_nm_interface" = "MS dumpbin"; then + # Fake it for dumpbin and say T for any non-static function, + # D for any global variable and I for any imported variable. + # Also find C++ and __fastcall symbols from MSVC++ or ICC, + # which start with @ or ?. + lt_cv_sys_global_symbol_pipe="$AWK '"\ +" {last_section=section; section=\$ 3};"\ +" /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\ +" /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ +" /^ *Symbol name *: /{split(\$ 0,sn,\":\"); si=substr(sn[2],2)};"\ +" /^ *Type *: code/{print \"T\",si,substr(si,length(prfx))};"\ +" /^ *Type *: data/{print \"I\",si,substr(si,length(prfx))};"\ +" \$ 0!~/External *\|/{next};"\ +" / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ +" {if(hide[section]) next};"\ +" {f=\"D\"}; \$ 0~/\(\).*\|/{f=\"T\"};"\ +" {split(\$ 0,a,/\||\r/); split(a[2],s)};"\ +" s[1]~/^[@?]/{print f,s[1],s[1]; next};"\ +" s[1]~prfx {split(s[1],t,\"@\"); print f,t[1],substr(t[1],length(prfx))}"\ +" ' prfx=^$ac_symprfx" + else + lt_cv_sys_global_symbol_pipe="$SED -n -e 's/^.*[ ]\($symcode$symcode*\)[ ][ ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" + fi + lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | $SED '/ __gnu_lto/d'" + + # Check to see that the pipe works correctly. + pipe_works=no + + rm -f conftest* + cat > conftest.$ac_ext <<_LT_EOF +#ifdef __cplusplus +extern "C" { +#endif +char nm_test_var; +void nm_test_func(void); +void nm_test_func(void){} +#ifdef __cplusplus +} +#endif +int main(){nm_test_var='a';nm_test_func();return(0);} +_LT_EOF + + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + # Now try to grab the symbols. + nlist=conftest.nm + $ECHO "$as_me:$LINENO: $NM conftest.$ac_objext | $lt_cv_sys_global_symbol_pipe > $nlist" >&5 + if eval "$NM" conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist 2>&5 && test -s "$nlist"; then + # Try sorting and uniquifying the output. + if sort "$nlist" | uniq > "$nlist"T; then + mv -f "$nlist"T "$nlist" + else + rm -f "$nlist"T + fi + + # Make sure that we snagged all the symbols we need. + if $GREP ' nm_test_var$' "$nlist" >/dev/null; then + if $GREP ' nm_test_func$' "$nlist" >/dev/null; then + cat <<_LT_EOF > conftest.$ac_ext +/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ +#if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE +/* DATA imports from DLLs on WIN32 can't be const, because runtime + relocations are performed -- see ld's documentation on pseudo-relocs. */ +# define LT_DLSYM_CONST +#elif defined __osf__ +/* This system does not cope well with relocations in const data. */ +# define LT_DLSYM_CONST +#else +# define LT_DLSYM_CONST const +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +_LT_EOF + # Now generate the symbol file. + eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' + + cat <<_LT_EOF >> conftest.$ac_ext + +/* The mapping between symbol names and symbols. */ +LT_DLSYM_CONST struct { + const char *name; + void *address; +} +lt__PROGRAM__LTX_preloaded_symbols[] = +{ + { "@PROGRAM@", (void *) 0 }, +_LT_EOF + $SED "s/^$symcode$symcode* .* \(.*\)$/ {\"\1\", (void *) \&\1},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext + cat <<\_LT_EOF >> conftest.$ac_ext + {0, (void *) 0} +}; + +/* This works around a problem in FreeBSD linker */ +#ifdef FREEBSD_WORKAROUND +static const void *lt_preloaded_setup() { + return lt__PROGRAM__LTX_preloaded_symbols; +} +#endif + +#ifdef __cplusplus +} +#endif +_LT_EOF + # Now try linking the two files. + mv conftest.$ac_objext conftstm.$ac_objext + lt_globsym_save_LIBS=$LIBS + lt_globsym_save_CFLAGS=$CFLAGS + LIBS=conftstm.$ac_objext + CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag" + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 + (eval $ac_link) 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && test -s conftest$ac_exeext; then + pipe_works=yes + fi + LIBS=$lt_globsym_save_LIBS + CFLAGS=$lt_globsym_save_CFLAGS + else + echo "cannot find nm_test_func in $nlist" >&5 + fi + else + echo "cannot find nm_test_var in $nlist" >&5 + fi + else + echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5 + fi + else + echo "$progname: failed program was:" >&5 + cat conftest.$ac_ext >&5 + fi + rm -rf conftest* conftst* + + # Do not use the global_symbol_pipe unless it works. + if test yes = "$pipe_works"; then + break + else + lt_cv_sys_global_symbol_pipe= + fi +done + +fi + +if test -z "$lt_cv_sys_global_symbol_pipe"; then + lt_cv_sys_global_symbol_to_cdecl= +fi +if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: failed" >&5 +printf "%s\n" "failed" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: ok" >&5 +printf "%s\n" "ok" >&6; } +fi + +# Response file support. +if test "$lt_cv_nm_interface" = "MS dumpbin"; then + nm_file_list_spec='@' +elif $NM --help 2>/dev/null | grep '[@]FILE' >/dev/null; then + nm_file_list_spec='@' +fi + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for sysroot" >&5 +printf %s "checking for sysroot... " >&6; } + +# Check whether --with-sysroot was given. +if test ${with_sysroot+y} +then : + withval=$with_sysroot; +else $as_nop + with_sysroot=no +fi + + +lt_sysroot= +case $with_sysroot in #( + yes) + if test yes = "$GCC"; then + lt_sysroot=`$CC --print-sysroot 2>/dev/null` + fi + ;; #( + /*) + lt_sysroot=`echo "$with_sysroot" | $SED -e "$sed_quote_subst"` + ;; #( + no|'') + ;; #( + *) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $with_sysroot" >&5 +printf "%s\n" "$with_sysroot" >&6; } + as_fn_error $? "The sysroot must be an absolute path." "$LINENO" 5 + ;; +esac + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: ${lt_sysroot:-no}" >&5 +printf "%s\n" "${lt_sysroot:-no}" >&6; } + + + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for a working dd" >&5 +printf %s "checking for a working dd... " >&6; } +if test ${ac_cv_path_lt_DD+y} +then : + printf %s "(cached) " >&6 +else $as_nop + printf 0123456789abcdef0123456789abcdef >conftest.i +cat conftest.i conftest.i >conftest2.i +: ${lt_DD:=$DD} +if test -z "$lt_DD"; then + ac_path_lt_DD_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_prog in dd + do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_lt_DD="$as_dir$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_lt_DD" || continue +if "$ac_path_lt_DD" bs=32 count=1 conftest.out 2>/dev/null; then + cmp -s conftest.i conftest.out \ + && ac_cv_path_lt_DD="$ac_path_lt_DD" ac_path_lt_DD_found=: +fi + $ac_path_lt_DD_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_lt_DD"; then + : + fi +else + ac_cv_path_lt_DD=$lt_DD +fi + +rm -f conftest.i conftest2.i conftest.out +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_lt_DD" >&5 +printf "%s\n" "$ac_cv_path_lt_DD" >&6; } + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to truncate binary pipes" >&5 +printf %s "checking how to truncate binary pipes... " >&6; } +if test ${lt_cv_truncate_bin+y} +then : + printf %s "(cached) " >&6 +else $as_nop + printf 0123456789abcdef0123456789abcdef >conftest.i +cat conftest.i conftest.i >conftest2.i +lt_cv_truncate_bin= +if "$ac_cv_path_lt_DD" bs=32 count=1 conftest.out 2>/dev/null; then + cmp -s conftest.i conftest.out \ + && lt_cv_truncate_bin="$ac_cv_path_lt_DD bs=4096 count=1" +fi +rm -f conftest.i conftest2.i conftest.out +test -z "$lt_cv_truncate_bin" && lt_cv_truncate_bin="$SED -e 4q" +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_truncate_bin" >&5 +printf "%s\n" "$lt_cv_truncate_bin" >&6; } + + + + + + + +# Calculate cc_basename. Skip known compiler wrappers and cross-prefix. +func_cc_basename () +{ + for cc_temp in $*""; do + case $cc_temp in + compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; + distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; + \-*) ;; + *) break;; + esac + done + func_cc_basename_result=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` +} + +# Check whether --enable-libtool-lock was given. +if test ${enable_libtool_lock+y} +then : + enableval=$enable_libtool_lock; +fi + +test no = "$enable_libtool_lock" || enable_libtool_lock=yes + +# Some flags need to be propagated to the compiler or linker for good +# libtool support. +case $host in +ia64-*-hpux*) + # Find out what ABI is being produced by ac_compile, and set mode + # options accordingly. + echo 'int i;' > conftest.$ac_ext + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + case `$FILECMD conftest.$ac_objext` in + *ELF-32*) + HPUX_IA64_MODE=32 + ;; + *ELF-64*) + HPUX_IA64_MODE=64 + ;; + esac + fi + rm -rf conftest* + ;; +*-*-irix6*) + # Find out what ABI is being produced by ac_compile, and set linker + # options accordingly. + echo '#line '$LINENO' "configure"' > conftest.$ac_ext + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + if test yes = "$lt_cv_prog_gnu_ld"; then + case `$FILECMD conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -melf32bsmip" + ;; + *N32*) + LD="${LD-ld} -melf32bmipn32" + ;; + *64-bit*) + LD="${LD-ld} -melf64bmip" + ;; + esac + else + case `$FILECMD conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -32" + ;; + *N32*) + LD="${LD-ld} -n32" + ;; + *64-bit*) + LD="${LD-ld} -64" + ;; + esac + fi + fi + rm -rf conftest* + ;; + +mips64*-*linux*) + # Find out what ABI is being produced by ac_compile, and set linker + # options accordingly. + echo '#line '$LINENO' "configure"' > conftest.$ac_ext + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + emul=elf + case `$FILECMD conftest.$ac_objext` in + *32-bit*) + emul="${emul}32" + ;; + *64-bit*) + emul="${emul}64" + ;; + esac + case `$FILECMD conftest.$ac_objext` in + *MSB*) + emul="${emul}btsmip" + ;; + *LSB*) + emul="${emul}ltsmip" + ;; + esac + case `$FILECMD conftest.$ac_objext` in + *N32*) + emul="${emul}n32" + ;; + esac + LD="${LD-ld} -m $emul" + fi + rm -rf conftest* + ;; + +x86_64-*kfreebsd*-gnu|x86_64-*linux*|powerpc*-*linux*| \ +s390*-*linux*|s390*-*tpf*|sparc*-*linux*) + # Find out what ABI is being produced by ac_compile, and set linker + # options accordingly. Note that the listed cases only cover the + # situations where additional linker options are needed (such as when + # doing 32-bit compilation for a host where ld defaults to 64-bit, or + # vice versa); the common cases where no linker options are needed do + # not appear in the list. + echo 'int i;' > conftest.$ac_ext + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + case `$FILECMD conftest.o` in + *32-bit*) + case $host in + x86_64-*kfreebsd*-gnu) + LD="${LD-ld} -m elf_i386_fbsd" + ;; + x86_64-*linux*) + case `$FILECMD conftest.o` in + *x86-64*) + LD="${LD-ld} -m elf32_x86_64" + ;; + *) + LD="${LD-ld} -m elf_i386" + ;; + esac + ;; + powerpc64le-*linux*) + LD="${LD-ld} -m elf32lppclinux" + ;; + powerpc64-*linux*) + LD="${LD-ld} -m elf32ppclinux" + ;; + s390x-*linux*) + LD="${LD-ld} -m elf_s390" + ;; + sparc64-*linux*) + LD="${LD-ld} -m elf32_sparc" + ;; + esac + ;; + *64-bit*) + case $host in + x86_64-*kfreebsd*-gnu) + LD="${LD-ld} -m elf_x86_64_fbsd" + ;; + x86_64-*linux*) + LD="${LD-ld} -m elf_x86_64" + ;; + powerpcle-*linux*) + LD="${LD-ld} -m elf64lppc" + ;; + powerpc-*linux*) + LD="${LD-ld} -m elf64ppc" + ;; + s390*-*linux*|s390*-*tpf*) + LD="${LD-ld} -m elf64_s390" + ;; + sparc*-*linux*) + LD="${LD-ld} -m elf64_sparc" + ;; + esac + ;; + esac + fi + rm -rf conftest* + ;; + +*-*-sco3.2v5*) + # On SCO OpenServer 5, we need -belf to get full-featured binaries. + SAVE_CFLAGS=$CFLAGS + CFLAGS="$CFLAGS -belf" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the C compiler needs -belf" >&5 +printf %s "checking whether the C compiler needs -belf... " >&6; } +if test ${lt_cv_cc_needs_belf+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + lt_cv_cc_needs_belf=yes +else $as_nop + lt_cv_cc_needs_belf=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_cc_needs_belf" >&5 +printf "%s\n" "$lt_cv_cc_needs_belf" >&6; } + if test yes != "$lt_cv_cc_needs_belf"; then + # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf + CFLAGS=$SAVE_CFLAGS + fi + ;; +*-*solaris*) + # Find out what ABI is being produced by ac_compile, and set linker + # options accordingly. + echo 'int i;' > conftest.$ac_ext + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + case `$FILECMD conftest.o` in + *64-bit*) + case $lt_cv_prog_gnu_ld in + yes*) + case $host in + i?86-*-solaris*|x86_64-*-solaris*) + LD="${LD-ld} -m elf_x86_64" + ;; + sparc*-*-solaris*) + LD="${LD-ld} -m elf64_sparc" + ;; + esac + # GNU ld 2.21 introduced _sol2 emulations. Use them if available. + if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then + LD=${LD-ld}_sol2 + fi + ;; + *) + if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then + LD="${LD-ld} -64" + fi + ;; + esac + ;; + esac + fi + rm -rf conftest* + ;; +esac + +need_locks=$enable_libtool_lock + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}mt", so it can be a program name with args. +set dummy ${ac_tool_prefix}mt; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_MANIFEST_TOOL+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$MANIFEST_TOOL"; then + ac_cv_prog_MANIFEST_TOOL="$MANIFEST_TOOL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_MANIFEST_TOOL="${ac_tool_prefix}mt" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +MANIFEST_TOOL=$ac_cv_prog_MANIFEST_TOOL +if test -n "$MANIFEST_TOOL"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $MANIFEST_TOOL" >&5 +printf "%s\n" "$MANIFEST_TOOL" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_MANIFEST_TOOL"; then + ac_ct_MANIFEST_TOOL=$MANIFEST_TOOL + # Extract the first word of "mt", so it can be a program name with args. +set dummy mt; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_MANIFEST_TOOL+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_MANIFEST_TOOL"; then + ac_cv_prog_ac_ct_MANIFEST_TOOL="$ac_ct_MANIFEST_TOOL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_MANIFEST_TOOL="mt" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_MANIFEST_TOOL=$ac_cv_prog_ac_ct_MANIFEST_TOOL +if test -n "$ac_ct_MANIFEST_TOOL"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_MANIFEST_TOOL" >&5 +printf "%s\n" "$ac_ct_MANIFEST_TOOL" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_MANIFEST_TOOL" = x; then + MANIFEST_TOOL=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + MANIFEST_TOOL=$ac_ct_MANIFEST_TOOL + fi +else + MANIFEST_TOOL="$ac_cv_prog_MANIFEST_TOOL" +fi + +test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $MANIFEST_TOOL is a manifest tool" >&5 +printf %s "checking if $MANIFEST_TOOL is a manifest tool... " >&6; } +if test ${lt_cv_path_mainfest_tool+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_path_mainfest_tool=no + echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&5 + $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out + cat conftest.err >&5 + if $GREP 'Manifest Tool' conftest.out > /dev/null; then + lt_cv_path_mainfest_tool=yes + fi + rm -f conftest* +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_mainfest_tool" >&5 +printf "%s\n" "$lt_cv_path_mainfest_tool" >&6; } +if test yes != "$lt_cv_path_mainfest_tool"; then + MANIFEST_TOOL=: +fi + + + + + + + case $host_os in + rhapsody* | darwin*) + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}dsymutil", so it can be a program name with args. +set dummy ${ac_tool_prefix}dsymutil; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_DSYMUTIL+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$DSYMUTIL"; then + ac_cv_prog_DSYMUTIL="$DSYMUTIL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_DSYMUTIL="${ac_tool_prefix}dsymutil" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +DSYMUTIL=$ac_cv_prog_DSYMUTIL +if test -n "$DSYMUTIL"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DSYMUTIL" >&5 +printf "%s\n" "$DSYMUTIL" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_DSYMUTIL"; then + ac_ct_DSYMUTIL=$DSYMUTIL + # Extract the first word of "dsymutil", so it can be a program name with args. +set dummy dsymutil; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_DSYMUTIL+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_DSYMUTIL"; then + ac_cv_prog_ac_ct_DSYMUTIL="$ac_ct_DSYMUTIL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_DSYMUTIL="dsymutil" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_DSYMUTIL=$ac_cv_prog_ac_ct_DSYMUTIL +if test -n "$ac_ct_DSYMUTIL"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DSYMUTIL" >&5 +printf "%s\n" "$ac_ct_DSYMUTIL" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_DSYMUTIL" = x; then + DSYMUTIL=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + DSYMUTIL=$ac_ct_DSYMUTIL + fi +else + DSYMUTIL="$ac_cv_prog_DSYMUTIL" +fi + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}nmedit", so it can be a program name with args. +set dummy ${ac_tool_prefix}nmedit; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_NMEDIT+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$NMEDIT"; then + ac_cv_prog_NMEDIT="$NMEDIT" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_NMEDIT="${ac_tool_prefix}nmedit" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +NMEDIT=$ac_cv_prog_NMEDIT +if test -n "$NMEDIT"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $NMEDIT" >&5 +printf "%s\n" "$NMEDIT" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_NMEDIT"; then + ac_ct_NMEDIT=$NMEDIT + # Extract the first word of "nmedit", so it can be a program name with args. +set dummy nmedit; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_NMEDIT+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_NMEDIT"; then + ac_cv_prog_ac_ct_NMEDIT="$ac_ct_NMEDIT" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_NMEDIT="nmedit" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_NMEDIT=$ac_cv_prog_ac_ct_NMEDIT +if test -n "$ac_ct_NMEDIT"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_NMEDIT" >&5 +printf "%s\n" "$ac_ct_NMEDIT" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_NMEDIT" = x; then + NMEDIT=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + NMEDIT=$ac_ct_NMEDIT + fi +else + NMEDIT="$ac_cv_prog_NMEDIT" +fi + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}lipo", so it can be a program name with args. +set dummy ${ac_tool_prefix}lipo; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_LIPO+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$LIPO"; then + ac_cv_prog_LIPO="$LIPO" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_LIPO="${ac_tool_prefix}lipo" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +LIPO=$ac_cv_prog_LIPO +if test -n "$LIPO"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $LIPO" >&5 +printf "%s\n" "$LIPO" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_LIPO"; then + ac_ct_LIPO=$LIPO + # Extract the first word of "lipo", so it can be a program name with args. +set dummy lipo; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_LIPO+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_LIPO"; then + ac_cv_prog_ac_ct_LIPO="$ac_ct_LIPO" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_LIPO="lipo" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_LIPO=$ac_cv_prog_ac_ct_LIPO +if test -n "$ac_ct_LIPO"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_LIPO" >&5 +printf "%s\n" "$ac_ct_LIPO" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_LIPO" = x; then + LIPO=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + LIPO=$ac_ct_LIPO + fi +else + LIPO="$ac_cv_prog_LIPO" +fi + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}otool", so it can be a program name with args. +set dummy ${ac_tool_prefix}otool; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_OTOOL+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$OTOOL"; then + ac_cv_prog_OTOOL="$OTOOL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_OTOOL="${ac_tool_prefix}otool" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +OTOOL=$ac_cv_prog_OTOOL +if test -n "$OTOOL"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $OTOOL" >&5 +printf "%s\n" "$OTOOL" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_OTOOL"; then + ac_ct_OTOOL=$OTOOL + # Extract the first word of "otool", so it can be a program name with args. +set dummy otool; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_OTOOL+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_OTOOL"; then + ac_cv_prog_ac_ct_OTOOL="$ac_ct_OTOOL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_OTOOL="otool" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_OTOOL=$ac_cv_prog_ac_ct_OTOOL +if test -n "$ac_ct_OTOOL"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL" >&5 +printf "%s\n" "$ac_ct_OTOOL" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_OTOOL" = x; then + OTOOL=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + OTOOL=$ac_ct_OTOOL + fi +else + OTOOL="$ac_cv_prog_OTOOL" +fi + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}otool64", so it can be a program name with args. +set dummy ${ac_tool_prefix}otool64; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_OTOOL64+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$OTOOL64"; then + ac_cv_prog_OTOOL64="$OTOOL64" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_OTOOL64="${ac_tool_prefix}otool64" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +OTOOL64=$ac_cv_prog_OTOOL64 +if test -n "$OTOOL64"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $OTOOL64" >&5 +printf "%s\n" "$OTOOL64" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_OTOOL64"; then + ac_ct_OTOOL64=$OTOOL64 + # Extract the first word of "otool64", so it can be a program name with args. +set dummy otool64; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_OTOOL64+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_OTOOL64"; then + ac_cv_prog_ac_ct_OTOOL64="$ac_ct_OTOOL64" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_OTOOL64="otool64" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_OTOOL64=$ac_cv_prog_ac_ct_OTOOL64 +if test -n "$ac_ct_OTOOL64"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL64" >&5 +printf "%s\n" "$ac_ct_OTOOL64" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_OTOOL64" = x; then + OTOOL64=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + OTOOL64=$ac_ct_OTOOL64 + fi +else + OTOOL64="$ac_cv_prog_OTOOL64" +fi + + + + + + + + + + + + + + + + + + + + + + + + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for -single_module linker flag" >&5 +printf %s "checking for -single_module linker flag... " >&6; } +if test ${lt_cv_apple_cc_single_mod+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_apple_cc_single_mod=no + if test -z "$LT_MULTI_MODULE"; then + # By default we will add the -single_module flag. You can override + # by either setting the environment variable LT_MULTI_MODULE + # non-empty at configure time, or by adding -multi_module to the + # link flags. + rm -rf libconftest.dylib* + echo "int foo(void){return 1;}" > conftest.c + echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ +-dynamiclib -Wl,-single_module conftest.c" >&5 + $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ + -dynamiclib -Wl,-single_module conftest.c 2>conftest.err + _lt_result=$? + # If there is a non-empty error log, and "single_module" + # appears in it, assume the flag caused a linker warning + if test -s conftest.err && $GREP single_module conftest.err; then + cat conftest.err >&5 + # Otherwise, if the output was created with a 0 exit code from + # the compiler, it worked. + elif test -f libconftest.dylib && test 0 = "$_lt_result"; then + lt_cv_apple_cc_single_mod=yes + else + cat conftest.err >&5 + fi + rm -rf libconftest.dylib* + rm -f conftest.* + fi +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_apple_cc_single_mod" >&5 +printf "%s\n" "$lt_cv_apple_cc_single_mod" >&6; } + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for -exported_symbols_list linker flag" >&5 +printf %s "checking for -exported_symbols_list linker flag... " >&6; } +if test ${lt_cv_ld_exported_symbols_list+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_ld_exported_symbols_list=no + save_LDFLAGS=$LDFLAGS + echo "_main" > conftest.sym + LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + lt_cv_ld_exported_symbols_list=yes +else $as_nop + lt_cv_ld_exported_symbols_list=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + LDFLAGS=$save_LDFLAGS + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_exported_symbols_list" >&5 +printf "%s\n" "$lt_cv_ld_exported_symbols_list" >&6; } + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for -force_load linker flag" >&5 +printf %s "checking for -force_load linker flag... " >&6; } +if test ${lt_cv_ld_force_load+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_ld_force_load=no + cat > conftest.c << _LT_EOF +int forced_loaded() { return 2;} +_LT_EOF + echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&5 + $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&5 + echo "$AR $AR_FLAGS libconftest.a conftest.o" >&5 + $AR $AR_FLAGS libconftest.a conftest.o 2>&5 + echo "$RANLIB libconftest.a" >&5 + $RANLIB libconftest.a 2>&5 + cat > conftest.c << _LT_EOF +int main() { return 0;} +_LT_EOF + echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&5 + $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err + _lt_result=$? + if test -s conftest.err && $GREP force_load conftest.err; then + cat conftest.err >&5 + elif test -f conftest && test 0 = "$_lt_result" && $GREP forced_load conftest >/dev/null 2>&1; then + lt_cv_ld_force_load=yes + else + cat conftest.err >&5 + fi + rm -f conftest.err libconftest.a conftest conftest.c + rm -rf conftest.dSYM + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_force_load" >&5 +printf "%s\n" "$lt_cv_ld_force_load" >&6; } + case $host_os in + rhapsody* | darwin1.[012]) + _lt_dar_allow_undefined='$wl-undefined ${wl}suppress' ;; + darwin1.*) + _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;; + darwin*) + case $MACOSX_DEPLOYMENT_TARGET,$host in + 10.[012],*|,*powerpc*-darwin[5-8]*) + _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;; + *) + _lt_dar_allow_undefined='$wl-undefined ${wl}dynamic_lookup' ;; + esac + ;; + esac + if test yes = "$lt_cv_apple_cc_single_mod"; then + _lt_dar_single_mod='$single_module' + fi + if test yes = "$lt_cv_ld_exported_symbols_list"; then + _lt_dar_export_syms=' $wl-exported_symbols_list,$output_objdir/$libname-symbols.expsym' + else + _lt_dar_export_syms='~$NMEDIT -s $output_objdir/$libname-symbols.expsym $lib' + fi + if test : != "$DSYMUTIL" && test no = "$lt_cv_ld_force_load"; then + _lt_dsymutil='~$DSYMUTIL $lib || :' + else + _lt_dsymutil= + fi + ;; + esac + +# func_munge_path_list VARIABLE PATH +# ----------------------------------- +# VARIABLE is name of variable containing _space_ separated list of +# directories to be munged by the contents of PATH, which is string +# having a format: +# "DIR[:DIR]:" +# string "DIR[ DIR]" will be prepended to VARIABLE +# ":DIR[:DIR]" +# string "DIR[ DIR]" will be appended to VARIABLE +# "DIRP[:DIRP]::[DIRA:]DIRA" +# string "DIRP[ DIRP]" will be prepended to VARIABLE and string +# "DIRA[ DIRA]" will be appended to VARIABLE +# "DIR[:DIR]" +# VARIABLE will be replaced by "DIR[ DIR]" +func_munge_path_list () +{ + case x$2 in + x) + ;; + *:) + eval $1=\"`$ECHO $2 | $SED 's/:/ /g'` \$$1\" + ;; + x:*) + eval $1=\"\$$1 `$ECHO $2 | $SED 's/:/ /g'`\" + ;; + *::*) + eval $1=\"\$$1\ `$ECHO $2 | $SED -e 's/.*:://' -e 's/:/ /g'`\" + eval $1=\"`$ECHO $2 | $SED -e 's/::.*//' -e 's/:/ /g'`\ \$$1\" + ;; + *) + eval $1=\"`$ECHO $2 | $SED 's/:/ /g'`\" + ;; + esac +} + +ac_fn_c_check_header_compile "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default +" +if test "x$ac_cv_header_dlfcn_h" = xyes +then : + printf "%s\n" "#define HAVE_DLFCN_H 1" >>confdefs.h + +fi + +# ------------------------------------ # +# Determine libtool default behavior # +# ------------------------------------ # + +# +# Default behavior is to enable shared and static libraries on systems +# where libtool knows how to build both library versions, and does not +# require separate configuration and build runs for each flavor. +# + +xc_lt_want_enable_shared='yes' +xc_lt_want_enable_static='yes' + +# +# User may have disabled shared or static libraries. +# +case "x$enable_shared" in # ( + xno) + xc_lt_want_enable_shared='no' + ;; +esac +case "x$enable_static" in # ( + xno) + xc_lt_want_enable_static='no' + ;; +esac +if test "x$xc_lt_want_enable_shared" = 'xno' && + test "x$xc_lt_want_enable_static" = 'xno'; then + as_fn_error $? "can not disable shared and static libraries simultaneously" "$LINENO" 5 +fi + +# +# Default behavior on systems that require independent configuration +# and build runs for shared and static is to enable shared libraries +# and disable static ones. On these systems option '--disable-shared' +# must be used in order to build a proper static library. +# + +if test "x$xc_lt_want_enable_shared" = 'xyes' && + test "x$xc_lt_want_enable_static" = 'xyes'; then + case $host_os in # ( + pw32* | cegcc* | os2* | aix*) + xc_lt_want_enable_static='no' + ;; + esac +fi + +# +# Make libtool aware of current shared and static library preferences +# taking in account that, depending on host characteristics, libtool +# may modify these option preferences later in this configure script. +# + +enable_shared=$xc_lt_want_enable_shared +enable_static=$xc_lt_want_enable_static + +# +# Default behavior is to build PIC objects for shared libraries and +# non-PIC objects for static libraries. +# + +xc_lt_want_with_pic='default' + +# +# User may have specified PIC preference. +# + +case "x$with_pic" in # (( + xno) + xc_lt_want_with_pic='no' + ;; + xyes) + xc_lt_want_with_pic='yes' + ;; +esac + +# +# Default behavior on some systems where building a shared library out +# of non-PIC compiled objects will fail with following linker error +# "relocation R_X86_64_32 can not be used when making a shared object" +# is to build PIC objects even for static libraries. This behavior may +# be overridden using 'configure --disable-shared --without-pic'. +# + +if test "x$xc_lt_want_with_pic" = 'xdefault'; then + case $host_cpu in # ( + x86_64 | amd64 | ia64) + case $host_os in # ( + linux* | freebsd* | midnightbsd*) + xc_lt_want_with_pic='yes' + ;; + esac + ;; + esac +fi + +# +# Make libtool aware of current PIC preference taking in account that, +# depending on host characteristics, libtool may modify PIC default +# behavior to fit host system idiosyncrasies later in this script. +# + +with_pic=$xc_lt_want_with_pic + +## ----------------------- ## +## Start of libtool code ## +## ----------------------- ## + + + + +# Set options +enable_win32_dll=yes + +case $host in +*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*) + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}as", so it can be a program name with args. +set dummy ${ac_tool_prefix}as; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_AS+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$AS"; then + ac_cv_prog_AS="$AS" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_AS="${ac_tool_prefix}as" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +AS=$ac_cv_prog_AS +if test -n "$AS"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $AS" >&5 +printf "%s\n" "$AS" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_AS"; then + ac_ct_AS=$AS + # Extract the first word of "as", so it can be a program name with args. +set dummy as; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_AS+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_AS"; then + ac_cv_prog_ac_ct_AS="$ac_ct_AS" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_AS="as" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_AS=$ac_cv_prog_ac_ct_AS +if test -n "$ac_ct_AS"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AS" >&5 +printf "%s\n" "$ac_ct_AS" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_AS" = x; then + AS="false" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + AS=$ac_ct_AS + fi +else + AS="$ac_cv_prog_AS" +fi + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args. +set dummy ${ac_tool_prefix}dlltool; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_DLLTOOL+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$DLLTOOL"; then + ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +DLLTOOL=$ac_cv_prog_DLLTOOL +if test -n "$DLLTOOL"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5 +printf "%s\n" "$DLLTOOL" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_DLLTOOL"; then + ac_ct_DLLTOOL=$DLLTOOL + # Extract the first word of "dlltool", so it can be a program name with args. +set dummy dlltool; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_DLLTOOL+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_DLLTOOL"; then + ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_DLLTOOL="dlltool" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL +if test -n "$ac_ct_DLLTOOL"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5 +printf "%s\n" "$ac_ct_DLLTOOL" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_DLLTOOL" = x; then + DLLTOOL="false" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + DLLTOOL=$ac_ct_DLLTOOL + fi +else + DLLTOOL="$ac_cv_prog_DLLTOOL" +fi + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args. +set dummy ${ac_tool_prefix}objdump; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_OBJDUMP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$OBJDUMP"; then + ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +OBJDUMP=$ac_cv_prog_OBJDUMP +if test -n "$OBJDUMP"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5 +printf "%s\n" "$OBJDUMP" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_OBJDUMP"; then + ac_ct_OBJDUMP=$OBJDUMP + # Extract the first word of "objdump", so it can be a program name with args. +set dummy objdump; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_OBJDUMP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_OBJDUMP"; then + ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_OBJDUMP="objdump" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP +if test -n "$ac_ct_OBJDUMP"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5 +printf "%s\n" "$ac_ct_OBJDUMP" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_OBJDUMP" = x; then + OBJDUMP="false" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + OBJDUMP=$ac_ct_OBJDUMP + fi +else + OBJDUMP="$ac_cv_prog_OBJDUMP" +fi + + ;; +esac + +test -z "$AS" && AS=as + + + + + +test -z "$DLLTOOL" && DLLTOOL=dlltool + + + + + +test -z "$OBJDUMP" && OBJDUMP=objdump + + + + + + + + enable_dlopen=no + + + + # Check whether --enable-shared was given. +if test ${enable_shared+y} +then : + enableval=$enable_shared; p=${PACKAGE-default} + case $enableval in + yes) enable_shared=yes ;; + no) enable_shared=no ;; + *) + enable_shared=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, + for pkg in $enableval; do + IFS=$lt_save_ifs + if test "X$pkg" = "X$p"; then + enable_shared=yes + fi + done + IFS=$lt_save_ifs + ;; + esac +else $as_nop + enable_shared=yes +fi + + + + + + + + + + # Check whether --enable-static was given. +if test ${enable_static+y} +then : + enableval=$enable_static; p=${PACKAGE-default} + case $enableval in + yes) enable_static=yes ;; + no) enable_static=no ;; + *) + enable_static=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, + for pkg in $enableval; do + IFS=$lt_save_ifs + if test "X$pkg" = "X$p"; then + enable_static=yes + fi + done + IFS=$lt_save_ifs + ;; + esac +else $as_nop + enable_static=yes +fi + + + + + + + + + + +# Check whether --with-pic was given. +if test ${with_pic+y} +then : + withval=$with_pic; lt_p=${PACKAGE-default} + case $withval in + yes|no) pic_mode=$withval ;; + *) + pic_mode=default + # Look at the argument we got. We use all the common list separators. + lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, + for lt_pkg in $withval; do + IFS=$lt_save_ifs + if test "X$lt_pkg" = "X$lt_p"; then + pic_mode=yes + fi + done + IFS=$lt_save_ifs + ;; + esac +else $as_nop + pic_mode=default +fi + + + + + + + + + # Check whether --enable-fast-install was given. +if test ${enable_fast_install+y} +then : + enableval=$enable_fast_install; p=${PACKAGE-default} + case $enableval in + yes) enable_fast_install=yes ;; + no) enable_fast_install=no ;; + *) + enable_fast_install=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, + for pkg in $enableval; do + IFS=$lt_save_ifs + if test "X$pkg" = "X$p"; then + enable_fast_install=yes + fi + done + IFS=$lt_save_ifs + ;; + esac +else $as_nop + enable_fast_install=yes +fi + + + + + + + + + shared_archive_member_spec= +case $host,$enable_shared in +power*-*-aix[5-9]*,yes) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking which variant of shared library versioning to provide" >&5 +printf %s "checking which variant of shared library versioning to provide... " >&6; } + +# Check whether --with-aix-soname was given. +if test ${with_aix_soname+y} +then : + withval=$with_aix_soname; case $withval in + aix|svr4|both) + ;; + *) + as_fn_error $? "Unknown argument to --with-aix-soname" "$LINENO" 5 + ;; + esac + lt_cv_with_aix_soname=$with_aix_soname +else $as_nop + if test ${lt_cv_with_aix_soname+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_with_aix_soname=aix +fi + + with_aix_soname=$lt_cv_with_aix_soname +fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $with_aix_soname" >&5 +printf "%s\n" "$with_aix_soname" >&6; } + if test aix != "$with_aix_soname"; then + # For the AIX way of multilib, we name the shared archive member + # based on the bitwidth used, traditionally 'shr.o' or 'shr_64.o', + # and 'shr.imp' or 'shr_64.imp', respectively, for the Import File. + # Even when GNU compilers ignore OBJECT_MODE but need '-maix64' flag, + # the AIX toolchain works better with OBJECT_MODE set (default 32). + if test 64 = "${OBJECT_MODE-32}"; then + shared_archive_member_spec=shr_64 + else + shared_archive_member_spec=shr + fi + fi + ;; +*) + with_aix_soname=aix + ;; +esac + + + + + + + + + + +# This can be used to rebuild libtool when needed +LIBTOOL_DEPS=$ltmain + +# Always use our own libtool. +LIBTOOL='$(SHELL) $(top_builddir)/libtool' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +test -z "$LN_S" && LN_S="ln -s" + + + + + + + + + + + + + + +if test -n "${ZSH_VERSION+set}"; then + setopt NO_GLOB_SUBST +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for objdir" >&5 +printf %s "checking for objdir... " >&6; } +if test ${lt_cv_objdir+y} +then : + printf %s "(cached) " >&6 +else $as_nop + rm -f .libs 2>/dev/null +mkdir .libs 2>/dev/null +if test -d .libs; then + lt_cv_objdir=.libs +else + # MS-DOS does not allow filenames that begin with a dot. + lt_cv_objdir=_libs +fi +rmdir .libs 2>/dev/null +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_objdir" >&5 +printf "%s\n" "$lt_cv_objdir" >&6; } +objdir=$lt_cv_objdir + + + + + +printf "%s\n" "#define LT_OBJDIR \"$lt_cv_objdir/\"" >>confdefs.h + + + + +case $host_os in +aix3*) + # AIX sometimes has problems with the GCC collect2 program. For some + # reason, if we set the COLLECT_NAMES environment variable, the problems + # vanish in a puff of smoke. + if test set != "${COLLECT_NAMES+set}"; then + COLLECT_NAMES= + export COLLECT_NAMES + fi + ;; +esac + +# Global variables: +ofile=libtool +can_build_shared=yes + +# All known linkers require a '.a' archive for static linking (except MSVC and +# ICC, which need '.lib'). +libext=a + +with_gnu_ld=$lt_cv_prog_gnu_ld + +old_CC=$CC +old_CFLAGS=$CFLAGS + +# Set sane defaults for various variables +test -z "$CC" && CC=cc +test -z "$LTCC" && LTCC=$CC +test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS +test -z "$LD" && LD=ld +test -z "$ac_objext" && ac_objext=o + +func_cc_basename $compiler +cc_basename=$func_cc_basename_result + + +# Only perform the check for file, if the check method requires it +test -z "$MAGIC_CMD" && MAGIC_CMD=file +case $deplibs_check_method in +file_magic*) + if test "$file_magic_cmd" = '$MAGIC_CMD'; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ${ac_tool_prefix}file" >&5 +printf %s "checking for ${ac_tool_prefix}file... " >&6; } +if test ${lt_cv_path_MAGIC_CMD+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $MAGIC_CMD in +[\\/*] | ?:[\\/]*) + lt_cv_path_MAGIC_CMD=$MAGIC_CMD # Let the user override the test with a path. + ;; +*) + lt_save_MAGIC_CMD=$MAGIC_CMD + lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR + ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" + for ac_dir in $ac_dummy; do + IFS=$lt_save_ifs + test -z "$ac_dir" && ac_dir=. + if test -f "$ac_dir/${ac_tool_prefix}file"; then + lt_cv_path_MAGIC_CMD=$ac_dir/"${ac_tool_prefix}file" + if test -n "$file_magic_test_file"; then + case $deplibs_check_method in + "file_magic "*) + file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` + MAGIC_CMD=$lt_cv_path_MAGIC_CMD + if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | + $EGREP "$file_magic_regex" > /dev/null; then + : + else + cat <<_LT_EOF 1>&2 + +*** Warning: the command libtool uses to detect shared libraries, +*** $file_magic_cmd, produces output that libtool cannot recognize. +*** The result is that libtool may fail to recognize shared libraries +*** as such. This will affect the creation of libtool libraries that +*** depend on shared libraries, but programs linked with such libtool +*** libraries will work regardless of this problem. Nevertheless, you +*** may want to report the problem to your system manager and/or to +*** bug-libtool@gnu.org + +_LT_EOF + fi ;; + esac + fi + break + fi + done + IFS=$lt_save_ifs + MAGIC_CMD=$lt_save_MAGIC_CMD + ;; +esac +fi + +MAGIC_CMD=$lt_cv_path_MAGIC_CMD +if test -n "$MAGIC_CMD"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 +printf "%s\n" "$MAGIC_CMD" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + + + +if test -z "$lt_cv_path_MAGIC_CMD"; then + if test -n "$ac_tool_prefix"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for file" >&5 +printf %s "checking for file... " >&6; } +if test ${lt_cv_path_MAGIC_CMD+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $MAGIC_CMD in +[\\/*] | ?:[\\/]*) + lt_cv_path_MAGIC_CMD=$MAGIC_CMD # Let the user override the test with a path. + ;; +*) + lt_save_MAGIC_CMD=$MAGIC_CMD + lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR + ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" + for ac_dir in $ac_dummy; do + IFS=$lt_save_ifs + test -z "$ac_dir" && ac_dir=. + if test -f "$ac_dir/file"; then + lt_cv_path_MAGIC_CMD=$ac_dir/"file" + if test -n "$file_magic_test_file"; then + case $deplibs_check_method in + "file_magic "*) + file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` + MAGIC_CMD=$lt_cv_path_MAGIC_CMD + if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | + $EGREP "$file_magic_regex" > /dev/null; then + : + else + cat <<_LT_EOF 1>&2 + +*** Warning: the command libtool uses to detect shared libraries, +*** $file_magic_cmd, produces output that libtool cannot recognize. +*** The result is that libtool may fail to recognize shared libraries +*** as such. This will affect the creation of libtool libraries that +*** depend on shared libraries, but programs linked with such libtool +*** libraries will work regardless of this problem. Nevertheless, you +*** may want to report the problem to your system manager and/or to +*** bug-libtool@gnu.org + +_LT_EOF + fi ;; + esac + fi + break + fi + done + IFS=$lt_save_ifs + MAGIC_CMD=$lt_save_MAGIC_CMD + ;; +esac +fi + +MAGIC_CMD=$lt_cv_path_MAGIC_CMD +if test -n "$MAGIC_CMD"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 +printf "%s\n" "$MAGIC_CMD" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + else + MAGIC_CMD=: + fi +fi + + fi + ;; +esac + +# Use C for the default configuration in the libtool script + +lt_save_CC=$CC +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +# Source file extension for C test sources. +ac_ext=c + +# Object file extension for compiled C test sources. +objext=o +objext=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="int some_variable = 0;" + +# Code to be used in simple link tests +lt_simple_link_test_code='int main(){return(0);}' + + + + + + + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} + +# Allow CC to be a program name with arguments. +compiler=$CC + +# Save the default compiler, since it gets overwritten when the other +# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. +compiler_DEFAULT=$CC + +# save warnings/boilerplate of simple test code +ac_outfile=conftest.$ac_objext +echo "$lt_simple_compile_test_code" >conftest.$ac_ext +eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_compiler_boilerplate=`cat conftest.err` +$RM conftest* + +ac_outfile=conftest.$ac_objext +echo "$lt_simple_link_test_code" >conftest.$ac_ext +eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_linker_boilerplate=`cat conftest.err` +$RM -r conftest* + + +## CAVEAT EMPTOR: +## There is no encapsulation within the following macros, do not change +## the running order or otherwise move them around unless you know exactly +## what you are doing... +if test -n "$compiler"; then + +lt_prog_compiler_no_builtin_flag= + +if test yes = "$GCC"; then + case $cc_basename in + nvcc*) + lt_prog_compiler_no_builtin_flag=' -Xcompiler -fno-builtin' ;; + *) + lt_prog_compiler_no_builtin_flag=' -fno-builtin' ;; + esac + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -fno-rtti -fno-exceptions" >&5 +printf %s "checking if $compiler supports -fno-rtti -fno-exceptions... " >&6; } +if test ${lt_cv_prog_compiler_rtti_exceptions+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_prog_compiler_rtti_exceptions=no + ac_outfile=conftest.$ac_objext + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="-fno-rtti -fno-exceptions" ## exclude from sc_useless_quotes_in_assignment + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_rtti_exceptions=yes + fi + fi + $RM conftest* + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_rtti_exceptions" >&5 +printf "%s\n" "$lt_cv_prog_compiler_rtti_exceptions" >&6; } + +if test yes = "$lt_cv_prog_compiler_rtti_exceptions"; then + lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions" +else + : +fi + +fi + + + + + + + lt_prog_compiler_wl= +lt_prog_compiler_pic= +lt_prog_compiler_static= + + + if test yes = "$GCC"; then + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_static='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test ia64 = "$host_cpu"; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static='-Bstatic' + fi + lt_prog_compiler_pic='-fPIC' + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + lt_prog_compiler_pic='-fPIC' + ;; + m68k) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the '-m68020' flag to GCC prevents building anything better, + # like '-m68040'. + lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4' + ;; + esac + ;; + + beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + + mingw* | cygwin* | pw32* | os2* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + # Although the cygwin gcc ignores -fPIC, still need this for old-style + # (--disable-auto-import) libraries + lt_prog_compiler_pic='-DDLL_EXPORT' + case $host_os in + os2*) + lt_prog_compiler_static='$wl-static' + ;; + esac + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + lt_prog_compiler_pic='-fno-common' + ;; + + haiku*) + # PIC is the default for Haiku. + # The "-static" flag exists, but is broken. + lt_prog_compiler_static= + ;; + + hpux*) + # PIC is the default for 64-bit PA HP-UX, but not for 32-bit + # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag + # sets the default TLS model and affects inlining. + case $host_cpu in + hppa*64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic='-fPIC' + ;; + esac + ;; + + interix[3-9]*) + # Interix 3.x gcc -fpic/-fPIC options generate broken code. + # Instead, we relocate shared libraries at runtime. + ;; + + msdosdjgpp*) + # Just because we use GCC doesn't mean we suddenly get shared libraries + # on systems that don't support them. + lt_prog_compiler_can_build_shared=no + enable_shared=no + ;; + + *nto* | *qnx*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + lt_prog_compiler_pic='-fPIC -shared' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + lt_prog_compiler_pic=-Kconform_pic + fi + ;; + + *) + lt_prog_compiler_pic='-fPIC' + ;; + esac + + case $cc_basename in + nvcc*) # Cuda Compiler Driver 2.2 + lt_prog_compiler_wl='-Xlinker ' + if test -n "$lt_prog_compiler_pic"; then + lt_prog_compiler_pic="-Xcompiler $lt_prog_compiler_pic" + fi + ;; + esac + else + # PORTME Check for flag to pass linker flags through the system compiler. + case $host_os in + aix*) + lt_prog_compiler_wl='-Wl,' + if test ia64 = "$host_cpu"; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static='-Bstatic' + else + lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp' + fi + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + lt_prog_compiler_pic='-fno-common' + case $cc_basename in + nagfor*) + # NAG Fortran compiler + lt_prog_compiler_wl='-Wl,-Wl,,' + lt_prog_compiler_pic='-PIC' + lt_prog_compiler_static='-Bstatic' + ;; + esac + ;; + + mingw* | cygwin* | pw32* | os2* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + lt_prog_compiler_pic='-DDLL_EXPORT' + case $host_os in + os2*) + lt_prog_compiler_static='$wl-static' + ;; + esac + ;; + + hpux9* | hpux10* | hpux11*) + lt_prog_compiler_wl='-Wl,' + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic='+Z' + ;; + esac + # Is there a better lt_prog_compiler_static that works with the bundled CC? + lt_prog_compiler_static='$wl-a ${wl}archive' + ;; + + irix5* | irix6* | nonstopux*) + lt_prog_compiler_wl='-Wl,' + # PIC (with -KPIC) is the default. + lt_prog_compiler_static='-non_shared' + ;; + + linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) + case $cc_basename in + # old Intel for x86_64, which still supported -KPIC. + ecc*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-static' + ;; + # flang / f18. f95 an alias for gfortran or flang on Debian + flang* | f18* | f95*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fPIC' + lt_prog_compiler_static='-static' + ;; + # icc used to be incompatible with GCC. + # ICC 10 doesn't accept -KPIC any more. + icc* | ifort*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fPIC' + lt_prog_compiler_static='-static' + ;; + # Lahey Fortran 8.1. + lf95*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='--shared' + lt_prog_compiler_static='--static' + ;; + nagfor*) + # NAG Fortran compiler + lt_prog_compiler_wl='-Wl,-Wl,,' + lt_prog_compiler_pic='-PIC' + lt_prog_compiler_static='-Bstatic' + ;; + tcc*) + # Fabrice Bellard et al's Tiny C Compiler + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fPIC' + lt_prog_compiler_static='-static' + ;; + pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) + # Portland Group compilers (*not* the Pentium gcc compiler, + # which looks to be a dead project) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fpic' + lt_prog_compiler_static='-Bstatic' + ;; + ccc*) + lt_prog_compiler_wl='-Wl,' + # All Alpha code is PIC. + lt_prog_compiler_static='-non_shared' + ;; + xl* | bgxl* | bgf* | mpixl*) + # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-qpic' + lt_prog_compiler_static='-qstaticlink' + ;; + *) + case `$CC -V 2>&1 | $SED 5q` in + *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [1-7].* | *Sun*Fortran*\ 8.[0-3]*) + # Sun Fortran 8.3 passes all unrecognized flags to the linker + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + lt_prog_compiler_wl='' + ;; + *Sun\ F* | *Sun*Fortran*) + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + lt_prog_compiler_wl='-Qoption ld ' + ;; + *Sun\ C*) + # Sun C 5.9 + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + lt_prog_compiler_wl='-Wl,' + ;; + *Intel*\ [CF]*Compiler*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fPIC' + lt_prog_compiler_static='-static' + ;; + *Portland\ Group*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fpic' + lt_prog_compiler_static='-Bstatic' + ;; + esac + ;; + esac + ;; + + newsos6) + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + *nto* | *qnx*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + lt_prog_compiler_pic='-fPIC -shared' + ;; + + osf3* | osf4* | osf5*) + lt_prog_compiler_wl='-Wl,' + # All OSF/1 code is PIC. + lt_prog_compiler_static='-non_shared' + ;; + + rdos*) + lt_prog_compiler_static='-non_shared' + ;; + + solaris*) + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + case $cc_basename in + f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) + lt_prog_compiler_wl='-Qoption ld ';; + *) + lt_prog_compiler_wl='-Wl,';; + esac + ;; + + sunos4*) + lt_prog_compiler_wl='-Qoption ld ' + lt_prog_compiler_pic='-PIC' + lt_prog_compiler_static='-Bstatic' + ;; + + sysv4 | sysv4.2uw2* | sysv4.3*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + lt_prog_compiler_pic='-Kconform_pic' + lt_prog_compiler_static='-Bstatic' + fi + ;; + + sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + unicos*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_can_build_shared=no + ;; + + uts4*) + lt_prog_compiler_pic='-pic' + lt_prog_compiler_static='-Bstatic' + ;; + + *) + lt_prog_compiler_can_build_shared=no + ;; + esac + fi + +case $host_os in + # For platforms that do not support PIC, -DPIC is meaningless: + *djgpp*) + lt_prog_compiler_pic= + ;; + *) + lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC" + ;; +esac + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5 +printf %s "checking for $compiler option to produce PIC... " >&6; } +if test ${lt_cv_prog_compiler_pic+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_prog_compiler_pic=$lt_prog_compiler_pic +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic" >&5 +printf "%s\n" "$lt_cv_prog_compiler_pic" >&6; } +lt_prog_compiler_pic=$lt_cv_prog_compiler_pic + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$lt_prog_compiler_pic"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5 +printf %s "checking if $compiler PIC flag $lt_prog_compiler_pic works... " >&6; } +if test ${lt_cv_prog_compiler_pic_works+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_prog_compiler_pic_works=no + ac_outfile=conftest.$ac_objext + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$lt_prog_compiler_pic -DPIC" ## exclude from sc_useless_quotes_in_assignment + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_pic_works=yes + fi + fi + $RM conftest* + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works" >&5 +printf "%s\n" "$lt_cv_prog_compiler_pic_works" >&6; } + +if test yes = "$lt_cv_prog_compiler_pic_works"; then + case $lt_prog_compiler_pic in + "" | " "*) ;; + *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;; + esac +else + lt_prog_compiler_pic= + lt_prog_compiler_can_build_shared=no +fi + +fi + + + + + + + + + + + +# +# Check to make sure the static flag actually works. +# +wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\" +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5 +printf %s "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } +if test ${lt_cv_prog_compiler_static_works+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_prog_compiler_static_works=no + save_LDFLAGS=$LDFLAGS + LDFLAGS="$LDFLAGS $lt_tmp_static_flag" + echo "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The linker can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&5 + $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_static_works=yes + fi + else + lt_cv_prog_compiler_static_works=yes + fi + fi + $RM -r conftest* + LDFLAGS=$save_LDFLAGS + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works" >&5 +printf "%s\n" "$lt_cv_prog_compiler_static_works" >&6; } + +if test yes = "$lt_cv_prog_compiler_static_works"; then + : +else + lt_prog_compiler_static= +fi + + + + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 +printf %s "checking if $compiler supports -c -o file.$ac_objext... " >&6; } +if test ${lt_cv_prog_compiler_c_o+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_prog_compiler_c_o=no + $RM -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp + $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 + if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then + lt_cv_prog_compiler_c_o=yes + fi + fi + chmod u+w . 2>&5 + $RM conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files + $RM out/* && rmdir out + cd .. + $RM -r conftest + $RM conftest* + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 +printf "%s\n" "$lt_cv_prog_compiler_c_o" >&6; } + + + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 +printf %s "checking if $compiler supports -c -o file.$ac_objext... " >&6; } +if test ${lt_cv_prog_compiler_c_o+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_prog_compiler_c_o=no + $RM -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp + $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 + if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then + lt_cv_prog_compiler_c_o=yes + fi + fi + chmod u+w . 2>&5 + $RM conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files + $RM out/* && rmdir out + cd .. + $RM -r conftest + $RM conftest* + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 +printf "%s\n" "$lt_cv_prog_compiler_c_o" >&6; } + + + + +hard_links=nottested +if test no = "$lt_cv_prog_compiler_c_o" && test no != "$need_locks"; then + # do not overwrite the value of need_locks provided by the user + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5 +printf %s "checking if we can lock with hard links... " >&6; } + hard_links=yes + $RM conftest* + ln conftest.a conftest.b 2>/dev/null && hard_links=no + touch conftest.a + ln conftest.a conftest.b 2>&5 || hard_links=no + ln conftest.a conftest.b 2>/dev/null && hard_links=no + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5 +printf "%s\n" "$hard_links" >&6; } + if test no = "$hard_links"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: '$CC' does not support '-c -o', so 'make -j' may be unsafe" >&5 +printf "%s\n" "$as_me: WARNING: '$CC' does not support '-c -o', so 'make -j' may be unsafe" >&2;} + need_locks=warn + fi +else + need_locks=no +fi + + + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 +printf %s "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } + + runpath_var= + allow_undefined_flag= + always_export_symbols=no + archive_cmds= + archive_expsym_cmds= + compiler_needs_object=no + enable_shared_with_static_runtimes=no + export_dynamic_flag_spec= + export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + hardcode_automatic=no + hardcode_direct=no + hardcode_direct_absolute=no + hardcode_libdir_flag_spec= + hardcode_libdir_separator= + hardcode_minus_L=no + hardcode_shlibpath_var=unsupported + inherit_rpath=no + link_all_deplibs=unknown + module_cmds= + module_expsym_cmds= + old_archive_from_new_cmds= + old_archive_from_expsyms_cmds= + thread_safe_flag_spec= + whole_archive_flag_spec= + # include_expsyms should be a list of space-separated symbols to be *always* + # included in the symbol list + include_expsyms= + # exclude_expsyms can be an extended regexp of symbols to exclude + # it will be wrapped by ' (' and ')$', so one must not match beginning or + # end of line. Example: 'a|bc|.*d.*' will exclude the symbols 'a' and 'bc', + # as well as any symbol that contains 'd'. + exclude_expsyms='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*' + # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out + # platforms (ab)use it in PIC code, but their linkers get confused if + # the symbol is explicitly referenced. Since portable code cannot + # rely on this symbol name, it's probably fine to never include it in + # preloaded symbol tables. + # Exclude shared library initialization/finalization symbols. + extract_expsyms_cmds= + + case $host_os in + cygwin* | mingw* | pw32* | cegcc*) + # FIXME: the MSVC++ and ICC port hasn't been tested in a loooong time + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++ or Intel C++ Compiler. + if test yes != "$GCC"; then + with_gnu_ld=no + fi + ;; + interix*) + # we just hope/assume this is gcc and not c89 (= MSVC++ or ICC) + with_gnu_ld=yes + ;; + openbsd* | bitrig*) + with_gnu_ld=no + ;; + linux* | k*bsd*-gnu | gnu*) + link_all_deplibs=no + ;; + esac + + ld_shlibs=yes + + # On some targets, GNU ld is compatible enough with the native linker + # that we're better off using the native interface for both. + lt_use_gnu_ld_interface=no + if test yes = "$with_gnu_ld"; then + case $host_os in + aix*) + # The AIX port of GNU ld has always aspired to compatibility + # with the native linker. However, as the warning in the GNU ld + # block says, versions before 2.19.5* couldn't really create working + # shared libraries, regardless of the interface used. + case `$LD -v 2>&1` in + *\ \(GNU\ Binutils\)\ 2.19.5*) ;; + *\ \(GNU\ Binutils\)\ 2.[2-9]*) ;; + *\ \(GNU\ Binutils\)\ [3-9]*) ;; + *) + lt_use_gnu_ld_interface=yes + ;; + esac + ;; + *) + lt_use_gnu_ld_interface=yes + ;; + esac + fi + + if test yes = "$lt_use_gnu_ld_interface"; then + # If archive_cmds runs LD, not CC, wlarc should be empty + wlarc='$wl' + + # Set some defaults for GNU ld with shared library support. These + # are reset later if shared libraries are not supported. Putting them + # here allows them to be overridden if necessary. + runpath_var=LD_RUN_PATH + hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' + export_dynamic_flag_spec='$wl--export-dynamic' + # ancient GNU ld didn't support --whole-archive et. al. + if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then + whole_archive_flag_spec=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive' + else + whole_archive_flag_spec= + fi + supports_anon_versioning=no + case `$LD -v | $SED -e 's/([^)]\+)\s\+//' 2>&1` in + *GNU\ gold*) supports_anon_versioning=yes ;; + *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 + *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... + *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... + *\ 2.11.*) ;; # other 2.11 versions + *) supports_anon_versioning=yes ;; + esac + + # See if GNU ld supports shared libraries. + case $host_os in + aix[3-9]*) + # On AIX/PPC, the GNU linker is very broken + if test ia64 != "$host_cpu"; then + ld_shlibs=no + cat <<_LT_EOF 1>&2 + +*** Warning: the GNU linker, at least up to release 2.19, is reported +*** to be unable to reliably create shared libraries on AIX. +*** Therefore, libtool is disabling shared libraries support. If you +*** really care for shared libraries, you may want to install binutils +*** 2.20 or above, or modify your PATH so that a non-GNU linker is found. +*** You will then need to restart the configuration process. + +_LT_EOF + fi + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + archive_expsym_cmds='' + ;; + m68k) + archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + ;; + esac + ;; + + beos*) + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + allow_undefined_flag=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + else + ld_shlibs=no + fi + ;; + + cygwin* | mingw* | pw32* | cegcc*) + # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless, + # as there is no search path for DLLs. + hardcode_libdir_flag_spec='-L$libdir' + export_dynamic_flag_spec='$wl--export-all-symbols' + allow_undefined_flag=unsupported + always_export_symbols=no + enable_shared_with_static_runtimes=yes + export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols' + exclude_expsyms='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname' + + if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + # If the export-symbols file already is a .def file, use it as + # is; otherwise, prepend EXPORTS... + archive_expsym_cmds='if test DEF = "`$SED -n -e '\''s/^[ ]*//'\'' -e '\''/^\(;.*\)*$/d'\'' -e '\''s/^\(EXPORTS\|LIBRARY\)\([ ].*\)*$/DEF/p'\'' -e q $export_symbols`" ; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + else + ld_shlibs=no + fi + ;; + + haiku*) + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + link_all_deplibs=yes + ;; + + os2*) + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + allow_undefined_flag=unsupported + shrext_cmds=.dll + archive_cmds='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ + $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ + $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ + $ECHO EXPORTS >> $output_objdir/$libname.def~ + emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~ + $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ + emximp -o $lib $output_objdir/$libname.def' + archive_expsym_cmds='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ + $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ + $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ + $ECHO EXPORTS >> $output_objdir/$libname.def~ + prefix_cmds="$SED"~ + if test EXPORTS = "`$SED 1q $export_symbols`"; then + prefix_cmds="$prefix_cmds -e 1d"; + fi~ + prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~ + cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ + $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ + emximp -o $lib $output_objdir/$libname.def' + old_archive_From_new_cmds='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' + enable_shared_with_static_runtimes=yes + file_list_spec='@' + ;; + + interix[3-9]*) + hardcode_direct=no + hardcode_shlibpath_var=no + hardcode_libdir_flag_spec='$wl-rpath,$libdir' + export_dynamic_flag_spec='$wl-E' + # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. + # Instead, shared libraries are loaded at an image base (0x10000000 by + # default) and relocated if they conflict, which is a slow very memory + # consuming and fragmenting process. To avoid this, we pick a random, + # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link + # time. Moving up from 0x10000000 also allows more sbrk(2) space. + archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + archive_expsym_cmds='$SED "s|^|_|" $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--retain-symbols-file,$output_objdir/$soname.expsym $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + ;; + + gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu) + tmp_diet=no + if test linux-dietlibc = "$host_os"; then + case $cc_basename in + diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) + esac + fi + if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ + && test no = "$tmp_diet" + then + tmp_addflag=' $pic_flag' + tmp_sharedflag='-shared' + case $cc_basename,$host_cpu in + pgcc*) # Portland Group C compiler + whole_archive_flag_spec='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' + tmp_addflag=' $pic_flag' + ;; + pgf77* | pgf90* | pgf95* | pgfortran*) + # Portland Group f77 and f90 compilers + whole_archive_flag_spec='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' + tmp_addflag=' $pic_flag -Mnomain' ;; + ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 + tmp_addflag=' -i_dynamic' ;; + efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 + tmp_addflag=' -i_dynamic -nofor_main' ;; + ifc* | ifort*) # Intel Fortran compiler + tmp_addflag=' -nofor_main' ;; + lf95*) # Lahey Fortran 8.1 + whole_archive_flag_spec= + tmp_sharedflag='--shared' ;; + nagfor*) # NAGFOR 5.3 + tmp_sharedflag='-Wl,-shared' ;; + xl[cC]* | bgxl[cC]* | mpixl[cC]*) # IBM XL C 8.0 on PPC (deal with xlf below) + tmp_sharedflag='-qmkshrobj' + tmp_addflag= ;; + nvcc*) # Cuda Compiler Driver 2.2 + whole_archive_flag_spec='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' + compiler_needs_object=yes + ;; + esac + case `$CC -V 2>&1 | $SED 5q` in + *Sun\ C*) # Sun C 5.9 + whole_archive_flag_spec='$wl--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' + compiler_needs_object=yes + tmp_sharedflag='-G' ;; + *Sun\ F*) # Sun Fortran 8.3 + tmp_sharedflag='-G' ;; + esac + archive_cmds='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + + if test yes = "$supports_anon_versioning"; then + archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + echo "local: *; };" >> $output_objdir/$libname.ver~ + $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-version-script $wl$output_objdir/$libname.ver -o $lib' + fi + + case $cc_basename in + tcc*) + hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' + export_dynamic_flag_spec='-rdynamic' + ;; + xlf* | bgf* | bgxlf* | mpixlf*) + # IBM XL Fortran 10.1 on PPC cannot create shared libs itself + whole_archive_flag_spec='--whole-archive$convenience --no-whole-archive' + hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' + archive_cmds='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib' + if test yes = "$supports_anon_versioning"; then + archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + echo "local: *; };" >> $output_objdir/$libname.ver~ + $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' + fi + ;; + esac + else + ld_shlibs=no + fi + ;; + + netbsd* | netbsdelf*-gnu) + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' + wlarc= + else + archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' + fi + ;; + + solaris*) + if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then + ld_shlibs=no + cat <<_LT_EOF 1>&2 + +*** Warning: The releases 2.8.* of the GNU linker cannot reliably +*** create shared libraries on Solaris systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.9.1 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +_LT_EOF + elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs=no + fi + ;; + + sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) + case `$LD -v 2>&1` in + *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*) + ld_shlibs=no + cat <<_LT_EOF 1>&2 + +*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 cannot +*** reliably create shared libraries on SCO systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.16.91.0.3 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +_LT_EOF + ;; + *) + # For security reasons, it is highly recommended that you always + # use absolute paths for naming shared libraries, and exclude the + # DT_RUNPATH tag from executables and libraries. But doing so + # requires that you compile everything twice, which is a pain. + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs=no + fi + ;; + esac + ;; + + sunos4*) + archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' + wlarc= + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + *) + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs=no + fi + ;; + esac + + if test no = "$ld_shlibs"; then + runpath_var= + hardcode_libdir_flag_spec= + export_dynamic_flag_spec= + whole_archive_flag_spec= + fi + else + # PORTME fill in a description of your system's linker (not GNU ld) + case $host_os in + aix3*) + allow_undefined_flag=unsupported + always_export_symbols=yes + archive_expsym_cmds='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' + # Note: this linker hardcodes the directories in LIBPATH if there + # are no directories specified by -L. + hardcode_minus_L=yes + if test yes = "$GCC" && test -z "$lt_prog_compiler_static"; then + # Neither direct hardcoding nor static linking is supported with a + # broken collect2. + hardcode_direct=unsupported + fi + ;; + + aix[4-9]*) + if test ia64 = "$host_cpu"; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag= + else + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to GNU nm, but means don't demangle to AIX nm. + # Without the "-l" option, or with the "-B" option, AIX nm treats + # weak defined symbols like other global defined symbols, whereas + # GNU nm marks them as "W". + # While the 'weak' keyword is ignored in the Export File, we need + # it in the Import File for the 'aix-soname' feature, so we have + # to replace the "-B" option with "-P" for AIX nm. + if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then + export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { if (\$ 2 == "W") { print \$ 3 " weak" } else { print \$ 3 } } }'\'' | sort -u > $export_symbols' + else + export_symbols_cmds='`func_echo_all $NM | $SED -e '\''s/B\([^B]*\)$/P\1/'\''` -PCpgl $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "L") || (\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) && (substr(\$ 1,1,1) != ".")) { if ((\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) { print \$ 1 " weak" } else { print \$ 1 } } }'\'' | sort -u > $export_symbols' + fi + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # have runtime linking enabled, and use it for executables. + # For shared libraries, we enable/disable runtime linking + # depending on the kind of the shared library created - + # when "with_aix_soname,aix_use_runtimelinking" is: + # "aix,no" lib.a(lib.so.V) shared, rtl:no, for executables + # "aix,yes" lib.so shared, rtl:yes, for executables + # lib.a static archive + # "both,no" lib.so.V(shr.o) shared, rtl:yes + # lib.a(lib.so.V) shared, rtl:no, for executables + # "both,yes" lib.so.V(shr.o) shared, rtl:yes, for executables + # lib.a(lib.so.V) shared, rtl:no + # "svr4,*" lib.so.V(shr.o) shared, rtl:yes, for executables + # lib.a static archive + case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*) + for ld_flag in $LDFLAGS; do + if (test x-brtl = "x$ld_flag" || test x-Wl,-brtl = "x$ld_flag"); then + aix_use_runtimelinking=yes + break + fi + done + if test svr4,no = "$with_aix_soname,$aix_use_runtimelinking"; then + # With aix-soname=svr4, we create the lib.so.V shared archives only, + # so we don't have lib.a shared libs to link our executables. + # We have to force runtime linking in this case. + aix_use_runtimelinking=yes + LDFLAGS="$LDFLAGS -Wl,-brtl" + fi + ;; + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + archive_cmds='' + hardcode_direct=yes + hardcode_direct_absolute=yes + hardcode_libdir_separator=':' + link_all_deplibs=yes + file_list_spec='$wl-f,' + case $with_aix_soname,$aix_use_runtimelinking in + aix,*) ;; # traditional, no import file + svr4,* | *,yes) # use import file + # The Import File defines what to hardcode. + hardcode_direct=no + hardcode_direct_absolute=no + ;; + esac + + if test yes = "$GCC"; then + case $host_os in aix4.[012]|aix4.[012].*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`$CC -print-prog-name=collect2` + if test -f "$collect2name" && + strings "$collect2name" | $GREP resolve_lib_name >/dev/null + then + # We have reworked collect2 + : + else + # We have old collect2 + hardcode_direct=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + hardcode_minus_L=yes + hardcode_libdir_flag_spec='-L$libdir' + hardcode_libdir_separator= + fi + ;; + esac + shared_flag='-shared' + if test yes = "$aix_use_runtimelinking"; then + shared_flag="$shared_flag "'$wl-G' + fi + # Need to ensure runtime linking is disabled for the traditional + # shared library, or the linker may eventually find shared libraries + # /with/ Import File - we do not want to mix them. + shared_flag_aix='-shared' + shared_flag_svr4='-shared $wl-G' + else + # not using gcc + if test ia64 = "$host_cpu"; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test yes = "$aix_use_runtimelinking"; then + shared_flag='$wl-G' + else + shared_flag='$wl-bM:SRE' + fi + shared_flag_aix='$wl-bM:SRE' + shared_flag_svr4='$wl-G' + fi + fi + + export_dynamic_flag_spec='$wl-bexpall' + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + always_export_symbols=yes + if test aix,yes = "$with_aix_soname,$aix_use_runtimelinking"; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + allow_undefined_flag='-berok' + # Determine the default libpath from the value encoded in an + # empty executable. + if test set = "${lt_cv_aix_libpath+set}"; then + aix_libpath=$lt_cv_aix_libpath +else + if test ${lt_cv_aix_libpath_+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\([^ ]*\) *$/\1/ + p + } + }' + lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` + # Check for a 64-bit object if we didn't find anything. + if test -z "$lt_cv_aix_libpath_"; then + lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` + fi +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + if test -z "$lt_cv_aix_libpath_"; then + lt_cv_aix_libpath_=/usr/lib:/lib + fi + +fi + + aix_libpath=$lt_cv_aix_libpath_ +fi + + hardcode_libdir_flag_spec='$wl-blibpath:$libdir:'"$aix_libpath" + archive_expsym_cmds='$CC -o $output_objdir/$soname $libobjs $deplibs $wl'$no_entry_flag' $compiler_flags `if test -n "$allow_undefined_flag"; then func_echo_all "$wl$allow_undefined_flag"; else :; fi` $wl'$exp_sym_flag:\$export_symbols' '$shared_flag + else + if test ia64 = "$host_cpu"; then + hardcode_libdir_flag_spec='$wl-R $libdir:/usr/lib:/lib' + allow_undefined_flag="-z nodefs" + archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\$wl$no_entry_flag"' $compiler_flags $wl$allow_undefined_flag '"\$wl$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an + # empty executable. + if test set = "${lt_cv_aix_libpath+set}"; then + aix_libpath=$lt_cv_aix_libpath +else + if test ${lt_cv_aix_libpath_+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\([^ ]*\) *$/\1/ + p + } + }' + lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` + # Check for a 64-bit object if we didn't find anything. + if test -z "$lt_cv_aix_libpath_"; then + lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` + fi +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + if test -z "$lt_cv_aix_libpath_"; then + lt_cv_aix_libpath_=/usr/lib:/lib + fi + +fi + + aix_libpath=$lt_cv_aix_libpath_ +fi + + hardcode_libdir_flag_spec='$wl-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + no_undefined_flag=' $wl-bernotok' + allow_undefined_flag=' $wl-berok' + if test yes = "$with_gnu_ld"; then + # We only use this code for GNU lds that support --whole-archive. + whole_archive_flag_spec='$wl--whole-archive$convenience $wl--no-whole-archive' + else + # Exported symbols can be pulled into shared objects from archives + whole_archive_flag_spec='$convenience' + fi + archive_cmds_need_lc=yes + archive_expsym_cmds='$RM -r $output_objdir/$realname.d~$MKDIR $output_objdir/$realname.d' + # -brtl affects multiple linker settings, -berok does not and is overridden later + compiler_flags_filtered='`func_echo_all "$compiler_flags " | $SED -e "s%-brtl\\([, ]\\)%-berok\\1%g"`' + if test svr4 != "$with_aix_soname"; then + # This is similar to how AIX traditionally builds its shared libraries. + archive_expsym_cmds="$archive_expsym_cmds"'~$CC '$shared_flag_aix' -o $output_objdir/$realname.d/$soname $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$realname.d/$soname' + fi + if test aix != "$with_aix_soname"; then + archive_expsym_cmds="$archive_expsym_cmds"'~$CC '$shared_flag_svr4' -o $output_objdir/$realname.d/$shared_archive_member_spec.o $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$STRIP -e $output_objdir/$realname.d/$shared_archive_member_spec.o~( func_echo_all "#! $soname($shared_archive_member_spec.o)"; if test shr_64 = "$shared_archive_member_spec"; then func_echo_all "# 64"; else func_echo_all "# 32"; fi; cat $export_symbols ) > $output_objdir/$realname.d/$shared_archive_member_spec.imp~$AR $AR_FLAGS $output_objdir/$soname $output_objdir/$realname.d/$shared_archive_member_spec.o $output_objdir/$realname.d/$shared_archive_member_spec.imp' + else + # used by -dlpreopen to get the symbols + archive_expsym_cmds="$archive_expsym_cmds"'~$MV $output_objdir/$realname.d/$soname $output_objdir' + fi + archive_expsym_cmds="$archive_expsym_cmds"'~$RM -r $output_objdir/$realname.d' + fi + fi + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + archive_expsym_cmds='' + ;; + m68k) + archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + ;; + esac + ;; + + bsdi[45]*) + export_dynamic_flag_spec=-rdynamic + ;; + + cygwin* | mingw* | pw32* | cegcc*) + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++ or Intel C++ Compiler. + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + case $cc_basename in + cl* | icl*) + # Native MSVC or ICC + hardcode_libdir_flag_spec=' ' + allow_undefined_flag=unsupported + always_export_symbols=yes + file_list_spec='@' + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=.dll + # FIXME: Setting linknames here is a bad hack. + archive_cmds='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~linknames=' + archive_expsym_cmds='if test DEF = "`$SED -n -e '\''s/^[ ]*//'\'' -e '\''/^\(;.*\)*$/d'\'' -e '\''s/^\(EXPORTS\|LIBRARY\)\([ ].*\)*$/DEF/p'\'' -e q $export_symbols`" ; then + cp "$export_symbols" "$output_objdir/$soname.def"; + echo "$tool_output_objdir$soname.def" > "$output_objdir/$soname.exp"; + else + $SED -e '\''s/^/-link -EXPORT:/'\'' < $export_symbols > $output_objdir/$soname.exp; + fi~ + $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ + linknames=' + # The linker will not automatically build a static lib if we build a DLL. + # _LT_TAGVAR(old_archive_from_new_cmds, )='true' + enable_shared_with_static_runtimes=yes + exclude_expsyms='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' + export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1,DATA/'\'' | $SED -e '\''/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols' + # Don't use ranlib + old_postinstall_cmds='chmod 644 $oldlib' + postlink_cmds='lt_outputfile="@OUTPUT@"~ + lt_tool_outputfile="@TOOL_OUTPUT@"~ + case $lt_outputfile in + *.exe|*.EXE) ;; + *) + lt_outputfile=$lt_outputfile.exe + lt_tool_outputfile=$lt_tool_outputfile.exe + ;; + esac~ + if test : != "$MANIFEST_TOOL" && test -f "$lt_outputfile.manifest"; then + $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; + $RM "$lt_outputfile.manifest"; + fi' + ;; + *) + # Assume MSVC and ICC wrapper + hardcode_libdir_flag_spec=' ' + allow_undefined_flag=unsupported + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=.dll + # FIXME: Setting linknames here is a bad hack. + archive_cmds='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=' + # The linker will automatically build a .lib file if we build a DLL. + old_archive_from_new_cmds='true' + # FIXME: Should let the user specify the lib program. + old_archive_cmds='lib -OUT:$oldlib$oldobjs$old_deplibs' + enable_shared_with_static_runtimes=yes + ;; + esac + ;; + + darwin* | rhapsody*) + + + archive_cmds_need_lc=no + hardcode_direct=no + hardcode_automatic=yes + hardcode_shlibpath_var=unsupported + if test yes = "$lt_cv_ld_force_load"; then + whole_archive_flag_spec='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience $wl-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' + + else + whole_archive_flag_spec='' + fi + link_all_deplibs=yes + allow_undefined_flag=$_lt_dar_allow_undefined + case $cc_basename in + ifort*|nagfor*) _lt_dar_can_shared=yes ;; + *) _lt_dar_can_shared=$GCC ;; + esac + if test yes = "$_lt_dar_can_shared"; then + output_verbose_link_cmd=func_echo_all + archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dsymutil" + module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dsymutil" + archive_expsym_cmds="$SED 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dar_export_syms$_lt_dsymutil" + module_expsym_cmds="$SED -e 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dar_export_syms$_lt_dsymutil" + + else + ld_shlibs=no + fi + + ;; + + dgux*) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_shlibpath_var=no + ;; + + # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor + # support. Future versions do this automatically, but an explicit c++rt0.o + # does not break anything, and helps significantly (at the cost of a little + # extra space). + freebsd2.2*) + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + # Unfortunately, older versions of FreeBSD 2 do not have this feature. + freebsd2.*) + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=yes + hardcode_minus_L=yes + hardcode_shlibpath_var=no + ;; + + # FreeBSD 3 and greater uses gcc -shared to do shared libraries. + freebsd* | dragonfly* | midnightbsd*) + archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + hpux9*) + if test yes = "$GCC"; then + archive_cmds='$RM $output_objdir/$soname~$CC -shared $pic_flag $wl+b $wl$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' + else + archive_cmds='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' + fi + hardcode_libdir_flag_spec='$wl+b $wl$libdir' + hardcode_libdir_separator=: + hardcode_direct=yes + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + export_dynamic_flag_spec='$wl-E' + ;; + + hpux10*) + if test yes,no = "$GCC,$with_gnu_ld"; then + archive_cmds='$CC -shared $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' + fi + if test no = "$with_gnu_ld"; then + hardcode_libdir_flag_spec='$wl+b $wl$libdir' + hardcode_libdir_separator=: + hardcode_direct=yes + hardcode_direct_absolute=yes + export_dynamic_flag_spec='$wl-E' + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + fi + ;; + + hpux11*) + if test yes,no = "$GCC,$with_gnu_ld"; then + case $host_cpu in + hppa*64*) + archive_cmds='$CC -shared $wl+h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + archive_cmds='$CC -shared $pic_flag $wl+h $wl$soname $wl+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + archive_cmds='$CC -shared $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + else + case $host_cpu in + hppa*64*) + archive_cmds='$CC -b $wl+h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + archive_cmds='$CC -b $wl+h $wl$soname $wl+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + + # Older versions of the 11.00 compiler do not understand -b yet + # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $CC understands -b" >&5 +printf %s "checking if $CC understands -b... " >&6; } +if test ${lt_cv_prog_compiler__b+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_prog_compiler__b=no + save_LDFLAGS=$LDFLAGS + LDFLAGS="$LDFLAGS -b" + echo "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The linker can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&5 + $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler__b=yes + fi + else + lt_cv_prog_compiler__b=yes + fi + fi + $RM -r conftest* + LDFLAGS=$save_LDFLAGS + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler__b" >&5 +printf "%s\n" "$lt_cv_prog_compiler__b" >&6; } + +if test yes = "$lt_cv_prog_compiler__b"; then + archive_cmds='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags' +else + archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' +fi + + ;; + esac + fi + if test no = "$with_gnu_ld"; then + hardcode_libdir_flag_spec='$wl+b $wl$libdir' + hardcode_libdir_separator=: + + case $host_cpu in + hppa*64*|ia64*) + hardcode_direct=no + hardcode_shlibpath_var=no + ;; + *) + hardcode_direct=yes + hardcode_direct_absolute=yes + export_dynamic_flag_spec='$wl-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + ;; + esac + fi + ;; + + irix5* | irix6* | nonstopux*) + if test yes = "$GCC"; then + archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' + # Try to use the -exported_symbol ld option, if it does not + # work, assume that -exports_file does not work either and + # implicitly export all symbols. + # This should be the same for all languages, so no per-tag cache variable. + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the $host_os linker accepts -exported_symbol" >&5 +printf %s "checking whether the $host_os linker accepts -exported_symbol... " >&6; } +if test ${lt_cv_irix_exported_symbol+y} +then : + printf %s "(cached) " >&6 +else $as_nop + save_LDFLAGS=$LDFLAGS + LDFLAGS="$LDFLAGS -shared $wl-exported_symbol ${wl}foo $wl-update_registry $wl/dev/null" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +int foo (void) { return 0; } +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + lt_cv_irix_exported_symbol=yes +else $as_nop + lt_cv_irix_exported_symbol=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + LDFLAGS=$save_LDFLAGS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_irix_exported_symbol" >&5 +printf "%s\n" "$lt_cv_irix_exported_symbol" >&6; } + if test yes = "$lt_cv_irix_exported_symbol"; then + archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations $wl-exports_file $wl$export_symbols -o $lib' + fi + link_all_deplibs=no + else + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -exports_file $export_symbols -o $lib' + fi + archive_cmds_need_lc='no' + hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' + hardcode_libdir_separator=: + inherit_rpath=yes + link_all_deplibs=yes + ;; + + linux*) + case $cc_basename in + tcc*) + # Fabrice Bellard et al's Tiny C Compiler + ld_shlibs=yes + archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' + ;; + esac + ;; + + netbsd* | netbsdelf*-gnu) + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out + else + archive_cmds='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF + fi + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + newsos6) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=yes + hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' + hardcode_libdir_separator=: + hardcode_shlibpath_var=no + ;; + + *nto* | *qnx*) + ;; + + openbsd* | bitrig*) + if test -f /usr/libexec/ld.so; then + hardcode_direct=yes + hardcode_shlibpath_var=no + hardcode_direct_absolute=yes + if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then + archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags $wl-retain-symbols-file,$export_symbols' + hardcode_libdir_flag_spec='$wl-rpath,$libdir' + export_dynamic_flag_spec='$wl-E' + else + archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec='$wl-rpath,$libdir' + fi + else + ld_shlibs=no + fi + ;; + + os2*) + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + allow_undefined_flag=unsupported + shrext_cmds=.dll + archive_cmds='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ + $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ + $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ + $ECHO EXPORTS >> $output_objdir/$libname.def~ + emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~ + $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ + emximp -o $lib $output_objdir/$libname.def' + archive_expsym_cmds='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ + $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ + $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ + $ECHO EXPORTS >> $output_objdir/$libname.def~ + prefix_cmds="$SED"~ + if test EXPORTS = "`$SED 1q $export_symbols`"; then + prefix_cmds="$prefix_cmds -e 1d"; + fi~ + prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~ + cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ + $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ + emximp -o $lib $output_objdir/$libname.def' + old_archive_From_new_cmds='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' + enable_shared_with_static_runtimes=yes + file_list_spec='@' + ;; + + osf3*) + if test yes = "$GCC"; then + allow_undefined_flag=' $wl-expect_unresolved $wl\*' + archive_cmds='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' + else + allow_undefined_flag=' -expect_unresolved \*' + archive_cmds='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' + fi + archive_cmds_need_lc='no' + hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' + hardcode_libdir_separator=: + ;; + + osf4* | osf5*) # as osf3* with the addition of -msym flag + if test yes = "$GCC"; then + allow_undefined_flag=' $wl-expect_unresolved $wl\*' + archive_cmds='$CC -shared$allow_undefined_flag $pic_flag $libobjs $deplibs $compiler_flags $wl-msym $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' + hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' + else + allow_undefined_flag=' -expect_unresolved \*' + archive_cmds='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' + archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ + $CC -shared$allow_undefined_flag $wl-input $wl$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib~$RM $lib.exp' + + # Both c and cxx compiler support -rpath directly + hardcode_libdir_flag_spec='-rpath $libdir' + fi + archive_cmds_need_lc='no' + hardcode_libdir_separator=: + ;; + + solaris*) + no_undefined_flag=' -z defs' + if test yes = "$GCC"; then + wlarc='$wl' + archive_cmds='$CC -shared $pic_flag $wl-z ${wl}text $wl-h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -shared $pic_flag $wl-z ${wl}text $wl-M $wl$lib.exp $wl-h $wl$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' + else + case `$CC -V 2>&1` in + *"Compilers 5.0"*) + wlarc='' + archive_cmds='$LD -G$allow_undefined_flag -h $soname -o $lib $libobjs $deplibs $linker_flags' + archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $LD -G$allow_undefined_flag -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' + ;; + *) + wlarc='$wl' + archive_cmds='$CC -G$allow_undefined_flag -h $soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -G$allow_undefined_flag -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' + ;; + esac + fi + hardcode_libdir_flag_spec='-R$libdir' + hardcode_shlibpath_var=no + case $host_os in + solaris2.[0-5] | solaris2.[0-5].*) ;; + *) + # The compiler driver will combine and reorder linker options, + # but understands '-z linker_flag'. GCC discards it without '$wl', + # but is careful enough not to reorder. + # Supported since Solaris 2.6 (maybe 2.5.1?) + if test yes = "$GCC"; then + whole_archive_flag_spec='$wl-z ${wl}allextract$convenience $wl-z ${wl}defaultextract' + else + whole_archive_flag_spec='-z allextract$convenience -z defaultextract' + fi + ;; + esac + link_all_deplibs=yes + ;; + + sunos4*) + if test sequent = "$host_vendor"; then + # Use $CC to link under sequent, because it throws in some extra .o + # files that make .init and .fini sections work. + archive_cmds='$CC -G $wl-h $soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' + fi + hardcode_libdir_flag_spec='-L$libdir' + hardcode_direct=yes + hardcode_minus_L=yes + hardcode_shlibpath_var=no + ;; + + sysv4) + case $host_vendor in + sni) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=yes # is this really true??? + ;; + siemens) + ## LD is ld it makes a PLAMLIB + ## CC just makes a GrossModule. + archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags' + reload_cmds='$CC -r -o $output$reload_objs' + hardcode_direct=no + ;; + motorola) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=no #Motorola manual says yes, but my tests say they lie + ;; + esac + runpath_var='LD_RUN_PATH' + hardcode_shlibpath_var=no + ;; + + sysv4.3*) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var=no + export_dynamic_flag_spec='-Bexport' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var=no + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + ld_shlibs=yes + fi + ;; + + sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) + no_undefined_flag='$wl-z,text' + archive_cmds_need_lc=no + hardcode_shlibpath_var=no + runpath_var='LD_RUN_PATH' + + if test yes = "$GCC"; then + archive_cmds='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + sysv5* | sco3.2v5* | sco5v6*) + # Note: We CANNOT use -z defs as we might desire, because we do not + # link with -lc, and that would cause any symbols used from libc to + # always be unresolved, which means just about no library would + # ever link correctly. If we're not using GNU ld we use -z text + # though, which does catch some bad symbols but isn't as heavy-handed + # as -z defs. + no_undefined_flag='$wl-z,text' + allow_undefined_flag='$wl-z,nodefs' + archive_cmds_need_lc=no + hardcode_shlibpath_var=no + hardcode_libdir_flag_spec='$wl-R,$libdir' + hardcode_libdir_separator=':' + link_all_deplibs=yes + export_dynamic_flag_spec='$wl-Bexport' + runpath_var='LD_RUN_PATH' + + if test yes = "$GCC"; then + archive_cmds='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + uts4*) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_shlibpath_var=no + ;; + + *) + ld_shlibs=no + ;; + esac + + if test sni = "$host_vendor"; then + case $host in + sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + export_dynamic_flag_spec='$wl-Blargedynsym' + ;; + esac + fi + fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs" >&5 +printf "%s\n" "$ld_shlibs" >&6; } +test no = "$ld_shlibs" && can_build_shared=no + +with_gnu_ld=$with_gnu_ld + + + + + + + + + + + + + + + +# +# Do we need to explicitly link libc? +# +case "x$archive_cmds_need_lc" in +x|xyes) + # Assume -lc should be added + archive_cmds_need_lc=yes + + if test yes,yes = "$GCC,$enable_shared"; then + case $archive_cmds in + *'~'*) + # FIXME: we may have to deal with multi-command sequences. + ;; + '$CC '*) + # Test whether the compiler implicitly links with -lc since on some + # systems, -lgcc has to come before -lc. If gcc already passes -lc + # to ld, don't add -lc before -lgcc. + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5 +printf %s "checking whether -lc should be explicitly linked in... " >&6; } +if test ${lt_cv_archive_cmds_need_lc+y} +then : + printf %s "(cached) " >&6 +else $as_nop + $RM conftest* + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } 2>conftest.err; then + soname=conftest + lib=conftest + libobjs=conftest.$ac_objext + deplibs= + wl=$lt_prog_compiler_wl + pic_flag=$lt_prog_compiler_pic + compiler_flags=-v + linker_flags=-v + verstring= + output_objdir=. + libname=conftest + lt_save_allow_undefined_flag=$allow_undefined_flag + allow_undefined_flag= + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5 + (eval $archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + then + lt_cv_archive_cmds_need_lc=no + else + lt_cv_archive_cmds_need_lc=yes + fi + allow_undefined_flag=$lt_save_allow_undefined_flag + else + cat conftest.err 1>&5 + fi + $RM conftest* + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc" >&5 +printf "%s\n" "$lt_cv_archive_cmds_need_lc" >&6; } + archive_cmds_need_lc=$lt_cv_archive_cmds_need_lc + ;; + esac + fi + ;; +esac + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5 +printf %s "checking dynamic linker characteristics... " >&6; } + +if test yes = "$GCC"; then + case $host_os in + darwin*) lt_awk_arg='/^libraries:/,/LR/' ;; + *) lt_awk_arg='/^libraries:/' ;; + esac + case $host_os in + mingw* | cegcc*) lt_sed_strip_eq='s|=\([A-Za-z]:\)|\1|g' ;; + *) lt_sed_strip_eq='s|=/|/|g' ;; + esac + lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` + case $lt_search_path_spec in + *\;*) + # if the path contains ";" then we assume it to be the separator + # otherwise default to the standard path separator (i.e. ":") - it is + # assumed that no part of a normal pathname contains ";" but that should + # okay in the real world where ";" in dirpaths is itself problematic. + lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'` + ;; + *) + lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"` + ;; + esac + # Ok, now we have the path, separated by spaces, we can step through it + # and add multilib dir if necessary... + lt_tmp_lt_search_path_spec= + lt_multi_os_dir=/`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` + # ...but if some path component already ends with the multilib dir we assume + # that all is fine and trust -print-search-dirs as is (GCC 4.2? or newer). + case "$lt_multi_os_dir; $lt_search_path_spec " in + "/; "* | "/.; "* | "/./; "* | *"$lt_multi_os_dir "* | *"$lt_multi_os_dir/ "*) + lt_multi_os_dir= + ;; + esac + for lt_sys_path in $lt_search_path_spec; do + if test -d "$lt_sys_path$lt_multi_os_dir"; then + lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path$lt_multi_os_dir" + elif test -n "$lt_multi_os_dir"; then + test -d "$lt_sys_path" && \ + lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" + fi + done + lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk ' +BEGIN {RS = " "; FS = "/|\n";} { + lt_foo = ""; + lt_count = 0; + for (lt_i = NF; lt_i > 0; lt_i--) { + if ($lt_i != "" && $lt_i != ".") { + if ($lt_i == "..") { + lt_count++; + } else { + if (lt_count == 0) { + lt_foo = "/" $lt_i lt_foo; + } else { + lt_count--; + } + } + } + } + if (lt_foo != "") { lt_freq[lt_foo]++; } + if (lt_freq[lt_foo] == 1) { print lt_foo; } +}'` + # AWK program above erroneously prepends '/' to C:/dos/paths + # for these hosts. + case $host_os in + mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ + $SED 's|/\([A-Za-z]:\)|\1|g'` ;; + esac + sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` +else + sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" +fi +library_names_spec= +libname_spec='lib$name' +soname_spec= +shrext_cmds=.so +postinstall_cmds= +postuninstall_cmds= +finish_cmds= +finish_eval= +shlibpath_var= +shlibpath_overrides_runpath=unknown +version_type=none +dynamic_linker="$host_os ld.so" +sys_lib_dlsearch_path_spec="/lib /usr/lib" +need_lib_prefix=unknown +hardcode_into_libs=no + +# when you set need_version to no, make sure it does not cause -set_version +# flags to be left without arguments +need_version=unknown + + + +case $host_os in +aix3*) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='$libname$release$shared_ext$versuffix $libname.a' + shlibpath_var=LIBPATH + + # AIX 3 has no versioning support, so we append a major version to the name. + soname_spec='$libname$release$shared_ext$major' + ;; + +aix[4-9]*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + hardcode_into_libs=yes + if test ia64 = "$host_cpu"; then + # AIX 5 supports IA64 + library_names_spec='$libname$release$shared_ext$major $libname$release$shared_ext$versuffix $libname$shared_ext' + shlibpath_var=LD_LIBRARY_PATH + else + # With GCC up to 2.95.x, collect2 would create an import file + # for dependence libraries. The import file would start with + # the line '#! .'. This would cause the generated library to + # depend on '.', always an invalid library. This was fixed in + # development snapshots of GCC prior to 3.0. + case $host_os in + aix4 | aix4.[01] | aix4.[01].*) + if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' + echo ' yes ' + echo '#endif'; } | $CC -E - | $GREP yes > /dev/null; then + : + else + can_build_shared=no + fi + ;; + esac + # Using Import Files as archive members, it is possible to support + # filename-based versioning of shared library archives on AIX. While + # this would work for both with and without runtime linking, it will + # prevent static linking of such archives. So we do filename-based + # shared library versioning with .so extension only, which is used + # when both runtime linking and shared linking is enabled. + # Unfortunately, runtime linking may impact performance, so we do + # not want this to be the default eventually. Also, we use the + # versioned .so libs for executables only if there is the -brtl + # linker flag in LDFLAGS as well, or --with-aix-soname=svr4 only. + # To allow for filename-based versioning support, we need to create + # libNAME.so.V as an archive file, containing: + # *) an Import File, referring to the versioned filename of the + # archive as well as the shared archive member, telling the + # bitwidth (32 or 64) of that shared object, and providing the + # list of exported symbols of that shared object, eventually + # decorated with the 'weak' keyword + # *) the shared object with the F_LOADONLY flag set, to really avoid + # it being seen by the linker. + # At run time we better use the real file rather than another symlink, + # but for link time we create the symlink libNAME.so -> libNAME.so.V + + case $with_aix_soname,$aix_use_runtimelinking in + # AIX (on Power*) has no versioning support, so currently we cannot hardcode correct + # soname into executable. Probably we can add versioning support to + # collect2, so additional links can be useful in future. + aix,yes) # traditional libtool + dynamic_linker='AIX unversionable lib.so' + # If using run time linking (on AIX 4.2 or later) use lib.so + # instead of lib.a to let people know that these are not + # typical AIX shared libraries. + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + ;; + aix,no) # traditional AIX only + dynamic_linker='AIX lib.a(lib.so.V)' + # We preserve .a as extension for shared libraries through AIX4.2 + # and later when we are not doing run time linking. + library_names_spec='$libname$release.a $libname.a' + soname_spec='$libname$release$shared_ext$major' + ;; + svr4,*) # full svr4 only + dynamic_linker="AIX lib.so.V($shared_archive_member_spec.o)" + library_names_spec='$libname$release$shared_ext$major $libname$shared_ext' + # We do not specify a path in Import Files, so LIBPATH fires. + shlibpath_overrides_runpath=yes + ;; + *,yes) # both, prefer svr4 + dynamic_linker="AIX lib.so.V($shared_archive_member_spec.o), lib.a(lib.so.V)" + library_names_spec='$libname$release$shared_ext$major $libname$shared_ext' + # unpreferred sharedlib libNAME.a needs extra handling + postinstall_cmds='test -n "$linkname" || linkname="$realname"~func_stripname "" ".so" "$linkname"~$install_shared_prog "$dir/$func_stripname_result.$libext" "$destdir/$func_stripname_result.$libext"~test -z "$tstripme" || test -z "$striplib" || $striplib "$destdir/$func_stripname_result.$libext"' + postuninstall_cmds='for n in $library_names $old_library; do :; done~func_stripname "" ".so" "$n"~test "$func_stripname_result" = "$n" || func_append rmfiles " $odir/$func_stripname_result.$libext"' + # We do not specify a path in Import Files, so LIBPATH fires. + shlibpath_overrides_runpath=yes + ;; + *,no) # both, prefer aix + dynamic_linker="AIX lib.a(lib.so.V), lib.so.V($shared_archive_member_spec.o)" + library_names_spec='$libname$release.a $libname.a' + soname_spec='$libname$release$shared_ext$major' + # unpreferred sharedlib libNAME.so.V and symlink libNAME.so need extra handling + postinstall_cmds='test -z "$dlname" || $install_shared_prog $dir/$dlname $destdir/$dlname~test -z "$tstripme" || test -z "$striplib" || $striplib $destdir/$dlname~test -n "$linkname" || linkname=$realname~func_stripname "" ".a" "$linkname"~(cd "$destdir" && $LN_S -f $dlname $func_stripname_result.so)' + postuninstall_cmds='test -z "$dlname" || func_append rmfiles " $odir/$dlname"~for n in $old_library $library_names; do :; done~func_stripname "" ".a" "$n"~func_append rmfiles " $odir/$func_stripname_result.so"' + ;; + esac + shlibpath_var=LIBPATH + fi + ;; + +amigaos*) + case $host_cpu in + powerpc) + # Since July 2007 AmigaOS4 officially supports .so libraries. + # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + ;; + m68k) + library_names_spec='$libname.ixlibrary $libname.a' + # Create ${libname}_ixlibrary.a entries in /sys/libs. + finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' + ;; + esac + ;; + +beos*) + library_names_spec='$libname$shared_ext' + dynamic_linker="$host_os ld.so" + shlibpath_var=LIBRARY_PATH + ;; + +bsdi[45]*) + version_type=linux # correct to gnu/linux during the next big refactor + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" + sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" + # the default ld.so.conf also contains /usr/contrib/lib and + # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow + # libtool to hard-code these into programs + ;; + +cygwin* | mingw* | pw32* | cegcc*) + version_type=windows + shrext_cmds=.dll + need_version=no + need_lib_prefix=no + + case $GCC,$cc_basename in + yes,*) + # gcc + library_names_spec='$libname.dll.a' + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \$file`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname~ + chmod a+x \$dldir/$dlname~ + if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then + eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; + fi' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $RM \$dlpath' + shlibpath_overrides_runpath=yes + + case $host_os in + cygwin*) + # Cygwin DLLs use 'cyg' prefix rather than 'lib' + soname_spec='`echo $libname | $SED -e 's/^lib/cyg/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext' + + sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api" + ;; + mingw* | cegcc*) + # MinGW DLLs use traditional 'lib' prefix + soname_spec='$libname`echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext' + ;; + pw32*) + # pw32 DLLs use 'pw' prefix rather than 'lib' + library_names_spec='`echo $libname | $SED -e 's/^lib/pw/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext' + ;; + esac + dynamic_linker='Win32 ld.exe' + ;; + + *,cl* | *,icl*) + # Native MSVC or ICC + libname_spec='$name' + soname_spec='$libname`echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext' + library_names_spec='$libname.dll.lib' + + case $build_os in + mingw*) + sys_lib_search_path_spec= + lt_save_ifs=$IFS + IFS=';' + for lt_path in $LIB + do + IFS=$lt_save_ifs + # Let DOS variable expansion print the short 8.3 style file name. + lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` + sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" + done + IFS=$lt_save_ifs + # Convert to MSYS style. + sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'` + ;; + cygwin*) + # Convert to unix form, then to dos form, then back to unix form + # but this time dos style (no spaces!) so that the unix form looks + # like /cygdrive/c/PROGRA~1:/cygdr... + sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` + sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` + sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + ;; + *) + sys_lib_search_path_spec=$LIB + if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then + # It is most probably a Windows format PATH. + sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + # FIXME: find the short name or the path components, as spaces are + # common. (e.g. "Program Files" -> "PROGRA~1") + ;; + esac + + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \$file`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $RM \$dlpath' + shlibpath_overrides_runpath=yes + dynamic_linker='Win32 link.exe' + ;; + + *) + # Assume MSVC and ICC wrapper + library_names_spec='$libname`echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext $libname.lib' + dynamic_linker='Win32 ld.exe' + ;; + esac + # FIXME: first we should search . and the directory the executable is in + shlibpath_var=PATH + ;; + +darwin* | rhapsody*) + dynamic_linker="$host_os dyld" + version_type=darwin + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$major$shared_ext $libname$shared_ext' + soname_spec='$libname$release$major$shared_ext' + shlibpath_overrides_runpath=yes + shlibpath_var=DYLD_LIBRARY_PATH + shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' + + sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib" + sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' + ;; + +dgux*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +freebsd* | dragonfly* | midnightbsd*) + # DragonFly does not have aout. When/if they implement a new + # versioning mechanism, adjust this. + if test -x /usr/bin/objformat; then + objformat=`/usr/bin/objformat` + else + case $host_os in + freebsd[23].*) objformat=aout ;; + *) objformat=elf ;; + esac + fi + version_type=freebsd-$objformat + case $version_type in + freebsd-elf*) + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + need_version=no + need_lib_prefix=no + ;; + freebsd-*) + library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' + need_version=yes + ;; + esac + shlibpath_var=LD_LIBRARY_PATH + case $host_os in + freebsd2.*) + shlibpath_overrides_runpath=yes + ;; + freebsd3.[01]* | freebsdelf3.[01]*) + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ + freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + *) # from 4.6 on, and DragonFly + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + esac + ;; + +haiku*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + dynamic_linker="$host_os runtime_loader" + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LIBRARY_PATH + shlibpath_overrides_runpath=no + sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' + hardcode_into_libs=yes + ;; + +hpux9* | hpux10* | hpux11*) + # Give a soname corresponding to the major version so that dld.sl refuses to + # link against other versions. + version_type=sunos + need_lib_prefix=no + need_version=no + case $host_cpu in + ia64*) + shrext_cmds='.so' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.so" + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + if test 32 = "$HPUX_IA64_MODE"; then + sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" + sys_lib_dlsearch_path_spec=/usr/lib/hpux32 + else + sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" + sys_lib_dlsearch_path_spec=/usr/lib/hpux64 + fi + ;; + hppa*64*) + shrext_cmds='.sl' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.sl" + shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + *) + shrext_cmds='.sl' + dynamic_linker="$host_os dld.sl" + shlibpath_var=SHLIB_PATH + shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + ;; + esac + # HP-UX runs *really* slowly unless shared libraries are mode 555, ... + postinstall_cmds='chmod 555 $lib' + # or fails outright, so override atomically: + install_override_mode=555 + ;; + +interix[3-9]*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +irix5* | irix6* | nonstopux*) + case $host_os in + nonstopux*) version_type=nonstopux ;; + *) + if test yes = "$lt_cv_prog_gnu_ld"; then + version_type=linux # correct to gnu/linux during the next big refactor + else + version_type=irix + fi ;; + esac + need_lib_prefix=no + need_version=no + soname_spec='$libname$release$shared_ext$major' + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$release$shared_ext $libname$shared_ext' + case $host_os in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in # libtool.m4 will add one of these switches to LD + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") + libsuff= shlibsuff= libmagic=32-bit;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") + libsuff=32 shlibsuff=N32 libmagic=N32;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") + libsuff=64 shlibsuff=64 libmagic=64-bit;; + *) libsuff= shlibsuff= libmagic=never-match;; + esac + ;; + esac + shlibpath_var=LD_LIBRARY${shlibsuff}_PATH + shlibpath_overrides_runpath=no + sys_lib_search_path_spec="/usr/lib$libsuff /lib$libsuff /usr/local/lib$libsuff" + sys_lib_dlsearch_path_spec="/usr/lib$libsuff /lib$libsuff" + hardcode_into_libs=yes + ;; + +# No shared lib support for Linux oldld, aout, or coff. +linux*oldld* | linux*aout* | linux*coff*) + dynamic_linker=no + ;; + +linux*android*) + version_type=none # Android doesn't support versioned libraries. + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext' + soname_spec='$libname$release$shared_ext' + finish_cmds= + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + + dynamic_linker='Android linker' + # Don't embed -rpath directories since the linker doesn't support them. + hardcode_libdir_flag_spec='-L$libdir' + ;; + +# This must be glibc/ELF. +linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + + # Some binutils ld are patched to set DT_RUNPATH + if test ${lt_cv_shlibpath_overrides_runpath+y} +then : + printf %s "(cached) " >&6 +else $as_nop + lt_cv_shlibpath_overrides_runpath=no + save_LDFLAGS=$LDFLAGS + save_libdir=$libdir + eval "libdir=/foo; wl=\"$lt_prog_compiler_wl\"; \ + LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec\"" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + if ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null +then : + lt_cv_shlibpath_overrides_runpath=yes +fi +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + LDFLAGS=$save_LDFLAGS + libdir=$save_libdir + +fi + + shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath + + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + + # Ideally, we could use ldconfig to report *all* directores which are + # searched for libraries, however this is still not possible. Aside from not + # being certain /sbin/ldconfig is available, command + # 'ldconfig -N -X -v | grep ^/' on 64bit Fedora does not report /usr/lib64, + # even though it is searched at run-time. Try to do the best guess by + # appending ld.so.conf contents (and includes) to the search path. + if test -f /etc/ld.so.conf; then + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" + fi + + # We used to test for /lib/ld.so.1 and disable shared libraries on + # powerpc, because MkLinux only supported shared libraries with the + # GNU dynamic linker. Since this was broken with cross compilers, + # most powerpc-linux boxes support dynamic linking these days and + # people can always --disable-shared, the test was removed, and we + # assume the GNU/Linux dynamic linker is in use. + dynamic_linker='GNU/Linux ld.so' + ;; + +netbsdelf*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='NetBSD ld.elf_so' + ;; + +netbsd*) + version_type=sunos + need_lib_prefix=no + need_version=no + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + dynamic_linker='NetBSD (a.out) ld.so' + else + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + dynamic_linker='NetBSD ld.elf_so' + fi + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + +newsos6) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +*nto* | *qnx*) + version_type=qnx + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='ldqnx.so' + ;; + +openbsd* | bitrig*) + version_type=sunos + sys_lib_dlsearch_path_spec=/usr/lib + need_lib_prefix=no + if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then + need_version=no + else + need_version=yes + fi + library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +os2*) + libname_spec='$name' + version_type=windows + shrext_cmds=.dll + need_version=no + need_lib_prefix=no + # OS/2 can only load a DLL with a base name of 8 characters or less. + soname_spec='`test -n "$os2dllname" && libname="$os2dllname"; + v=$($ECHO $release$versuffix | tr -d .-); + n=$($ECHO $libname | cut -b -$((8 - ${#v})) | tr . _); + $ECHO $n$v`$shared_ext' + library_names_spec='${libname}_dll.$libext' + dynamic_linker='OS/2 ld.exe' + shlibpath_var=BEGINLIBPATH + sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + postinstall_cmds='base_file=`basename \$file`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; $ECHO \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname~ + chmod a+x \$dldir/$dlname~ + if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then + eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; + fi' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; $ECHO \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $RM \$dlpath' + ;; + +osf3* | osf4* | osf5*) + version_type=osf + need_lib_prefix=no + need_version=no + soname_spec='$libname$release$shared_ext$major' + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + +rdos*) + dynamic_linker=no + ;; + +solaris*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + # ldd complains unless libraries are executable + postinstall_cmds='chmod +x $lib' + ;; + +sunos4*) + version_type=sunos + library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' + finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + if test yes = "$with_gnu_ld"; then + need_lib_prefix=no + fi + need_version=yes + ;; + +sysv4 | sysv4.3*) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + case $host_vendor in + sni) + shlibpath_overrides_runpath=no + need_lib_prefix=no + runpath_var=LD_RUN_PATH + ;; + siemens) + need_lib_prefix=no + ;; + motorola) + need_lib_prefix=no + need_version=no + shlibpath_overrides_runpath=no + sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' + ;; + esac + ;; + +sysv4*MP*) + if test -d /usr/nec; then + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='$libname$shared_ext.$versuffix $libname$shared_ext.$major $libname$shared_ext' + soname_spec='$libname$shared_ext.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + version_type=sco + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + if test yes = "$with_gnu_ld"; then + sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' + else + sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' + case $host_os in + sco3.2v5*) + sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" + ;; + esac + fi + sys_lib_dlsearch_path_spec='/usr/lib' + ;; + +tpf*) + # TPF is a cross-target only. Preferred cross-host = GNU/Linux. + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +uts4*) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +*) + dynamic_linker=no + ;; +esac +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5 +printf "%s\n" "$dynamic_linker" >&6; } +test no = "$dynamic_linker" && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test yes = "$GCC"; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi + +if test set = "${lt_cv_sys_lib_search_path_spec+set}"; then + sys_lib_search_path_spec=$lt_cv_sys_lib_search_path_spec +fi + +if test set = "${lt_cv_sys_lib_dlsearch_path_spec+set}"; then + sys_lib_dlsearch_path_spec=$lt_cv_sys_lib_dlsearch_path_spec +fi + +# remember unaugmented sys_lib_dlsearch_path content for libtool script decls... +configure_time_dlsearch_path=$sys_lib_dlsearch_path_spec + +# ... but it needs LT_SYS_LIBRARY_PATH munging for other configure-time code +func_munge_path_list sys_lib_dlsearch_path_spec "$LT_SYS_LIBRARY_PATH" + +# to be used as default LT_SYS_LIBRARY_PATH value in generated libtool +configure_time_lt_sys_library_path=$LT_SYS_LIBRARY_PATH + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5 +printf %s "checking how to hardcode library paths into programs... " >&6; } +hardcode_action= +if test -n "$hardcode_libdir_flag_spec" || + test -n "$runpath_var" || + test yes = "$hardcode_automatic"; then + + # We can hardcode non-existent directories. + if test no != "$hardcode_direct" && + # If the only mechanism to avoid hardcoding is shlibpath_var, we + # have to relink, otherwise we might link with an installed library + # when we should be linking with a yet-to-be-installed one + ## test no != "$_LT_TAGVAR(hardcode_shlibpath_var, )" && + test no != "$hardcode_minus_L"; then + # Linking always hardcodes the temporary library directory. + hardcode_action=relink + else + # We can link without hardcoding, and we can hardcode nonexisting dirs. + hardcode_action=immediate + fi +else + # We cannot hardcode anything, or else we can only hardcode existing + # directories. + hardcode_action=unsupported +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $hardcode_action" >&5 +printf "%s\n" "$hardcode_action" >&6; } + +if test relink = "$hardcode_action" || + test yes = "$inherit_rpath"; then + # Fast installation is not supported + enable_fast_install=no +elif test yes = "$shlibpath_overrides_runpath" || + test no = "$enable_shared"; then + # Fast installation is not necessary + enable_fast_install=needless +fi + + + + + + + if test yes != "$enable_dlopen"; then + enable_dlopen=unknown + enable_dlopen_self=unknown + enable_dlopen_self_static=unknown +else + lt_cv_dlopen=no + lt_cv_dlopen_libs= + + case $host_os in + beos*) + lt_cv_dlopen=load_add_on + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + ;; + + mingw* | pw32* | cegcc*) + lt_cv_dlopen=LoadLibrary + lt_cv_dlopen_libs= + ;; + + cygwin*) + lt_cv_dlopen=dlopen + lt_cv_dlopen_libs= + ;; + + darwin*) + # if libdl is installed we need to link against it + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 +printf %s "checking for dlopen in -ldl... " >&6; } +if test ${ac_cv_lib_dl_dlopen+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +int main (void) +{ +return dlopen (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_dl_dlopen=yes +else $as_nop + ac_cv_lib_dl_dlopen=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 +printf "%s\n" "$ac_cv_lib_dl_dlopen" >&6; } +if test "x$ac_cv_lib_dl_dlopen" = xyes +then : + lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl +else $as_nop + + lt_cv_dlopen=dyld + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + +fi + + ;; + + tpf*) + # Don't try to run any link tests for TPF. We know it's impossible + # because TPF is a cross-compiler, and we know how we open DSOs. + lt_cv_dlopen=dlopen + lt_cv_dlopen_libs= + lt_cv_dlopen_self=no + ;; + + *) + ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load" +if test "x$ac_cv_func_shl_load" = xyes +then : + lt_cv_dlopen=shl_load +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5 +printf %s "checking for shl_load in -ldld... " >&6; } +if test ${ac_cv_lib_dld_shl_load+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char shl_load (); +int main (void) +{ +return shl_load (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_dld_shl_load=yes +else $as_nop + ac_cv_lib_dld_shl_load=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5 +printf "%s\n" "$ac_cv_lib_dld_shl_load" >&6; } +if test "x$ac_cv_lib_dld_shl_load" = xyes +then : + lt_cv_dlopen=shl_load lt_cv_dlopen_libs=-ldld +else $as_nop + ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen" +if test "x$ac_cv_func_dlopen" = xyes +then : + lt_cv_dlopen=dlopen +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 +printf %s "checking for dlopen in -ldl... " >&6; } +if test ${ac_cv_lib_dl_dlopen+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +int main (void) +{ +return dlopen (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_dl_dlopen=yes +else $as_nop + ac_cv_lib_dl_dlopen=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 +printf "%s\n" "$ac_cv_lib_dl_dlopen" >&6; } +if test "x$ac_cv_lib_dl_dlopen" = xyes +then : + lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5 +printf %s "checking for dlopen in -lsvld... " >&6; } +if test ${ac_cv_lib_svld_dlopen+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lsvld $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +int main (void) +{ +return dlopen (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_svld_dlopen=yes +else $as_nop + ac_cv_lib_svld_dlopen=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5 +printf "%s\n" "$ac_cv_lib_svld_dlopen" >&6; } +if test "x$ac_cv_lib_svld_dlopen" = xyes +then : + lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-lsvld +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5 +printf %s "checking for dld_link in -ldld... " >&6; } +if test ${ac_cv_lib_dld_dld_link+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char dld_link (); +int main (void) +{ +return dld_link (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_dld_dld_link=yes +else $as_nop + ac_cv_lib_dld_dld_link=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5 +printf "%s\n" "$ac_cv_lib_dld_dld_link" >&6; } +if test "x$ac_cv_lib_dld_dld_link" = xyes +then : + lt_cv_dlopen=dld_link lt_cv_dlopen_libs=-ldld +fi + + +fi + + +fi + + +fi + + +fi + + +fi + + ;; + esac + + if test no = "$lt_cv_dlopen"; then + enable_dlopen=no + else + enable_dlopen=yes + fi + + case $lt_cv_dlopen in + dlopen) + save_CPPFLAGS=$CPPFLAGS + test yes = "$ac_cv_header_dlfcn_h" && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" + + save_LDFLAGS=$LDFLAGS + wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" + + save_LIBS=$LIBS + LIBS="$lt_cv_dlopen_libs $LIBS" + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether a program can dlopen itself" >&5 +printf %s "checking whether a program can dlopen itself... " >&6; } +if test ${lt_cv_dlopen_self+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test yes = "$cross_compiling"; then : + lt_cv_dlopen_self=cross +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext <<_LT_EOF +#line $LINENO "configure" +#include "confdefs.h" + +#if HAVE_DLFCN_H +#include +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +/* When -fvisibility=hidden is used, assume the code has been annotated + correspondingly for the symbols needed. */ +#if defined __GNUC__ && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) +int fnord () __attribute__((visibility("default"))); +#endif + +int fnord () { return 42; } +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else + { + if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + else puts (dlerror ()); + } + /* dlclose (self); */ + } + else + puts (dlerror ()); + + return status; +} +_LT_EOF + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 + (eval $ac_link) 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && test -s "conftest$ac_exeext" 2>/dev/null; then + (./conftest; exit; ) >&5 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;; + x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;; + x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;; + esac + else : + # compilation failed + lt_cv_dlopen_self=no + fi +fi +rm -fr conftest* + + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5 +printf "%s\n" "$lt_cv_dlopen_self" >&6; } + + if test yes = "$lt_cv_dlopen_self"; then + wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether a statically linked program can dlopen itself" >&5 +printf %s "checking whether a statically linked program can dlopen itself... " >&6; } +if test ${lt_cv_dlopen_self_static+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test yes = "$cross_compiling"; then : + lt_cv_dlopen_self_static=cross +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext <<_LT_EOF +#line $LINENO "configure" +#include "confdefs.h" + +#if HAVE_DLFCN_H +#include +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +/* When -fvisibility=hidden is used, assume the code has been annotated + correspondingly for the symbols needed. */ +#if defined __GNUC__ && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) +int fnord () __attribute__((visibility("default"))); +#endif + +int fnord () { return 42; } +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else + { + if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + else puts (dlerror ()); + } + /* dlclose (self); */ + } + else + puts (dlerror ()); + + return status; +} +_LT_EOF + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 + (eval $ac_link) 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && test -s "conftest$ac_exeext" 2>/dev/null; then + (./conftest; exit; ) >&5 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;; + x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;; + x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;; + esac + else : + # compilation failed + lt_cv_dlopen_self_static=no + fi +fi +rm -fr conftest* + + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self_static" >&5 +printf "%s\n" "$lt_cv_dlopen_self_static" >&6; } + fi + + CPPFLAGS=$save_CPPFLAGS + LDFLAGS=$save_LDFLAGS + LIBS=$save_LIBS + ;; + esac + + case $lt_cv_dlopen_self in + yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; + *) enable_dlopen_self=unknown ;; + esac + + case $lt_cv_dlopen_self_static in + yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; + *) enable_dlopen_self_static=unknown ;; + esac +fi + + + + + + + + + + + + + + + + + +striplib= +old_striplib= +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether stripping libraries is possible" >&5 +printf %s "checking whether stripping libraries is possible... " >&6; } +if test -z "$STRIP"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +else + if $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then + old_striplib="$STRIP --strip-debug" + striplib="$STRIP --strip-unneeded" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + else + case $host_os in + darwin*) + # FIXME - insert some real tests, host_os isn't really good enough + striplib="$STRIP -x" + old_striplib="$STRIP -S" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + freebsd*) + if $STRIP -V 2>&1 | $GREP "elftoolchain" >/dev/null; then + old_striplib="$STRIP --strip-debug" + striplib="$STRIP --strip-unneeded" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + ;; + *) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + esac + fi +fi + + + + + + + + + + + + + # Report what library types will actually be built + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if libtool supports shared libraries" >&5 +printf %s "checking if libtool supports shared libraries... " >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $can_build_shared" >&5 +printf "%s\n" "$can_build_shared" >&6; } + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries" >&5 +printf %s "checking whether to build shared libraries... " >&6; } + test no = "$can_build_shared" && enable_shared=no + + # On AIX, shared libraries and static libraries use the same namespace, and + # are all built from PIC. + case $host_os in + aix3*) + test yes = "$enable_shared" && enable_static=no + if test -n "$RANLIB"; then + archive_cmds="$archive_cmds~\$RANLIB \$lib" + postinstall_cmds='$RANLIB $lib' + fi + ;; + + aix[4-9]*) + if test ia64 != "$host_cpu"; then + case $enable_shared,$with_aix_soname,$aix_use_runtimelinking in + yes,aix,yes) ;; # shared object as lib.so file only + yes,svr4,*) ;; # shared object as lib.so archive member only + yes,*) enable_static=no ;; # shared object in lib.a archive as well + esac + fi + ;; + esac + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5 +printf "%s\n" "$enable_shared" >&6; } + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries" >&5 +printf %s "checking whether to build static libraries... " >&6; } + # Make sure either enable_shared or enable_static is yes. + test yes = "$enable_shared" || enable_static=yes + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $enable_static" >&5 +printf "%s\n" "$enable_static" >&6; } + + + + +fi +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +CC=$lt_save_CC + + + + + + + + + + + + + + + + ac_config_commands="$ac_config_commands libtool" + + + + +# Only expand once: + + +## --------------------- ## +## End of libtool code ## +## --------------------- ## + +# +# Verify if finally libtool shared libraries will be built +# + +case "x$enable_shared" in # (( + xyes | xno) + xc_lt_build_shared=$enable_shared + ;; + *) + as_fn_error $? "unexpected libtool enable_shared value: $enable_shared" "$LINENO" 5 + ;; +esac + +# +# Verify if finally libtool static libraries will be built +# + +case "x$enable_static" in # (( + xyes | xno) + xc_lt_build_static=$enable_static + ;; + *) + as_fn_error $? "unexpected libtool enable_static value: $enable_static" "$LINENO" 5 + ;; +esac + +# +# Verify if libtool shared libraries should be linked using flag -version-info +# + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries with -version-info" >&5 +printf %s "checking whether to build shared libraries with -version-info... " >&6; } +xc_lt_shlib_use_version_info='yes' +if test "x$version_type" = 'xnone'; then + xc_lt_shlib_use_version_info='no' +fi +case $host_os in # ( + amigaos*) + xc_lt_shlib_use_version_info='yes' + ;; +esac +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $xc_lt_shlib_use_version_info" >&5 +printf "%s\n" "$xc_lt_shlib_use_version_info" >&6; } + +# +# Verify if libtool shared libraries should be linked using flag -no-undefined +# + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries with -no-undefined" >&5 +printf %s "checking whether to build shared libraries with -no-undefined... " >&6; } +xc_lt_shlib_use_no_undefined='no' +if test "x$allow_undefined" = 'xno'; then + xc_lt_shlib_use_no_undefined='yes' +elif test "x$allow_undefined_flag" = 'xunsupported'; then + xc_lt_shlib_use_no_undefined='yes' +fi +case $host_os in # ( + cygwin* | mingw* | pw32* | cegcc* | os2* | aix*) + xc_lt_shlib_use_no_undefined='yes' + ;; +esac +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $xc_lt_shlib_use_no_undefined" >&5 +printf "%s\n" "$xc_lt_shlib_use_no_undefined" >&6; } + +# +# Verify if libtool shared libraries should be linked using flag -mimpure-text +# + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries with -mimpure-text" >&5 +printf %s "checking whether to build shared libraries with -mimpure-text... " >&6; } +xc_lt_shlib_use_mimpure_text='no' +case $host_os in # ( + solaris2*) + if test "x$GCC" = 'xyes'; then + xc_lt_shlib_use_mimpure_text='yes' + fi + ;; +esac +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $xc_lt_shlib_use_mimpure_text" >&5 +printf "%s\n" "$xc_lt_shlib_use_mimpure_text" >&6; } + +# +# Find out whether libtool libraries would be built with PIC +# + +case "x$pic_mode" in # (((( + xdefault) + xc_lt_build_shared_with_pic='yes' + xc_lt_build_static_with_pic='no' + ;; + xyes) + xc_lt_build_shared_with_pic='yes' + xc_lt_build_static_with_pic='yes' + ;; + xno) + xc_lt_build_shared_with_pic='no' + xc_lt_build_static_with_pic='no' + ;; + *) + xc_lt_build_shared_with_pic='unknown' + xc_lt_build_static_with_pic='unknown' + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: unexpected libtool pic_mode value: $pic_mode" >&5 +printf "%s\n" "$as_me: WARNING: unexpected libtool pic_mode value: $pic_mode" >&2;} + ;; +esac +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries with PIC" >&5 +printf %s "checking whether to build shared libraries with PIC... " >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $xc_lt_build_shared_with_pic" >&5 +printf "%s\n" "$xc_lt_build_shared_with_pic" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries with PIC" >&5 +printf %s "checking whether to build static libraries with PIC... " >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $xc_lt_build_static_with_pic" >&5 +printf "%s\n" "$xc_lt_build_static_with_pic" >&6; } + +# +# Verify if libtool shared libraries will be built while static not built +# + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries only" >&5 +printf %s "checking whether to build shared libraries only... " >&6; } +if test "$xc_lt_build_shared" = 'yes' && + test "$xc_lt_build_static" = 'no'; then + xc_lt_build_shared_only='yes' +else + xc_lt_build_shared_only='no' +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $xc_lt_build_shared_only" >&5 +printf "%s\n" "$xc_lt_build_shared_only" >&6; } + +# +# Verify if libtool static libraries will be built while shared not built +# + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries only" >&5 +printf %s "checking whether to build static libraries only... " >&6; } +if test "$xc_lt_build_static" = 'yes' && + test "$xc_lt_build_shared" = 'no'; then + xc_lt_build_static_only='yes' +else + xc_lt_build_static_only='no' +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $xc_lt_build_static_only" >&5 +printf "%s\n" "$xc_lt_build_static_only" >&6; } + + + + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}windres", so it can be a program name with args. +set dummy ${ac_tool_prefix}windres; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_RC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$RC"; then + ac_cv_prog_RC="$RC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_RC="${ac_tool_prefix}windres" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +RC=$ac_cv_prog_RC +if test -n "$RC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $RC" >&5 +printf "%s\n" "$RC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_RC"; then + ac_ct_RC=$RC + # Extract the first word of "windres", so it can be a program name with args. +set dummy windres; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_RC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_RC"; then + ac_cv_prog_ac_ct_RC="$ac_ct_RC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_RC="windres" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_RC=$ac_cv_prog_ac_ct_RC +if test -n "$ac_ct_RC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RC" >&5 +printf "%s\n" "$ac_ct_RC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_RC" = x; then + RC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + RC=$ac_ct_RC + fi +else + RC="$ac_cv_prog_RC" +fi + + + + +# Source file extension for RC test sources. +ac_ext=rc + +# Object file extension for compiled RC test sources. +objext=o +objext_RC=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }' + +# Code to be used in simple link tests +lt_simple_link_test_code=$lt_simple_compile_test_code + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. + + + + + + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} + +# Allow CC to be a program name with arguments. +compiler=$CC + + +# save warnings/boilerplate of simple test code +ac_outfile=conftest.$ac_objext +echo "$lt_simple_compile_test_code" >conftest.$ac_ext +eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_compiler_boilerplate=`cat conftest.err` +$RM conftest* + +ac_outfile=conftest.$ac_objext +echo "$lt_simple_link_test_code" >conftest.$ac_ext +eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_linker_boilerplate=`cat conftest.err` +$RM -r conftest* + + +# Allow CC to be a program name with arguments. +lt_save_CC=$CC +lt_save_CFLAGS=$CFLAGS +lt_save_GCC=$GCC +GCC= +CC=${RC-"windres"} +CFLAGS= +compiler=$CC +compiler_RC=$CC +func_cc_basename $compiler +cc_basename=$func_cc_basename_result + +lt_cv_prog_compiler_c_o_RC=yes + +if test -n "$compiler"; then + : + + + +fi + +GCC=$lt_save_GCC +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +CC=$lt_save_CC +CFLAGS=$lt_save_CFLAGS + + +# +# Automake conditionals based on libtool related checks +# + + if test "x$xc_lt_shlib_use_version_info" = 'xyes'; then + CURL_LT_SHLIB_USE_VERSION_INFO_TRUE= + CURL_LT_SHLIB_USE_VERSION_INFO_FALSE='#' +else + CURL_LT_SHLIB_USE_VERSION_INFO_TRUE='#' + CURL_LT_SHLIB_USE_VERSION_INFO_FALSE= +fi + + if test "x$xc_lt_shlib_use_no_undefined" = 'xyes'; then + CURL_LT_SHLIB_USE_NO_UNDEFINED_TRUE= + CURL_LT_SHLIB_USE_NO_UNDEFINED_FALSE='#' +else + CURL_LT_SHLIB_USE_NO_UNDEFINED_TRUE='#' + CURL_LT_SHLIB_USE_NO_UNDEFINED_FALSE= +fi + + if test "x$xc_lt_shlib_use_mimpure_text" = 'xyes'; then + CURL_LT_SHLIB_USE_MIMPURE_TEXT_TRUE= + CURL_LT_SHLIB_USE_MIMPURE_TEXT_FALSE='#' +else + CURL_LT_SHLIB_USE_MIMPURE_TEXT_TRUE='#' + CURL_LT_SHLIB_USE_MIMPURE_TEXT_FALSE= +fi + + +# +# Due to libtool and automake machinery limitations of not allowing +# specifying separate CPPFLAGS or CFLAGS when compiling objects for +# inclusion of these in shared or static libraries, we are forced to +# build using separate configure runs for shared and static libraries +# on systems where different CPPFLAGS or CFLAGS are mandatory in order +# to compile objects for each kind of library. Notice that relying on +# the '-DPIC' CFLAG that libtool provides is not valid given that the +# user might for example choose to build static libraries with PIC. +# + +# +# Make our Makefile.am files use the staticlib CPPFLAG only when strictly +# targeting a static library and not building its shared counterpart. +# + + if test "x$xc_lt_build_static_only" = 'xyes'; then + USE_CPPFLAG_CURL_STATICLIB_TRUE= + USE_CPPFLAG_CURL_STATICLIB_FALSE='#' +else + USE_CPPFLAG_CURL_STATICLIB_TRUE='#' + USE_CPPFLAG_CURL_STATICLIB_FALSE= +fi + + +# +# Make staticlib CPPFLAG variable and its definition visible in output +# files unconditionally, providing an empty definition unless strictly +# targeting a static library and not building its shared counterpart. +# + +CPPFLAG_CURL_STATICLIB= +if test "x$xc_lt_build_static_only" = 'xyes'; then + CPPFLAG_CURL_STATICLIB='-DCURL_STATICLIB' +fi + + + +# Determine whether all dependent libraries must be specified when linking +if test "X$enable_shared" = "Xyes" -a "X$link_all_deplibs" = "Xno" +then + REQUIRE_LIB_DEPS=no +else + REQUIRE_LIB_DEPS=yes +fi + + if test x$REQUIRE_LIB_DEPS = xyes; then + USE_EXPLICIT_LIB_DEPS_TRUE= + USE_EXPLICIT_LIB_DEPS_FALSE='#' +else + USE_EXPLICIT_LIB_DEPS_TRUE='#' + USE_EXPLICIT_LIB_DEPS_FALSE= +fi + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if cpp -P is needed" >&5 +printf %s "checking if cpp -P is needed... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + #include +TEST EINVAL TEST + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "TEST.*TEST" >/dev/null 2>&1 +then : + cpp=no +else $as_nop + cpp=yes +fi +rm -rf conftest* + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $cpp" >&5 +printf "%s\n" "$cpp" >&6; } + + if test "x$cpp" = "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if cpp -P works" >&5 +printf %s "checking if cpp -P works... " >&6; } + OLDCPPFLAGS=$CPPFLAGS + CPPFLAGS="$CPPFLAGS -P" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + #include +TEST EINVAL TEST + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "TEST.*TEST" >/dev/null 2>&1 +then : + cpp_p=yes +else $as_nop + cpp_p=no +fi +rm -rf conftest* + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $cpp_p" >&5 +printf "%s\n" "$cpp_p" >&6; } + + if test "x$cpp_p" = "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: failed to figure out cpp -P alternative" >&5 +printf "%s\n" "$as_me: WARNING: failed to figure out cpp -P alternative" >&2;} + # without -P + CPPPFLAG="" + else + # with -P + CPPPFLAG="-P" + fi + CPPFLAGS=$OLDCPPFLAGS + else + # without -P + CPPPFLAG="" + fi + + + # + compiler_id="unknown" + compiler_num="0" + # + flags_dbg_yes="unknown" + flags_opt_all="unknown" + flags_opt_yes="unknown" + flags_opt_off="unknown" + # + flags_prefer_cppflags="no" + # + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler is DEC/Compaq/HP C" >&5 +printf %s "checking if compiler is DEC/Compaq/HP C... " >&6; } + + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + if test -z "$SED"; then + as_fn_error $? "SED not set. Cannot continue without SED being set." "$LINENO" 5 + fi + if test -z "$GREP"; then + as_fn_error $? "GREP not set. Cannot continue without GREP being set." "$LINENO" 5 + fi + + tmp_exp="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __DECC +CURL_DEF_TOKEN __DECC +#endif + + +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[ ][ ]*//' 2>/dev/null | \ + "$SED" 's/["][ ]*["]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "__DECC"; then + tmp_exp="" + fi + +fi +rm -f conftest.err conftest.i conftest.$ac_ext + if test -z "$tmp_exp"; then + curl_cv_have_def___DECC=no + + else + curl_cv_have_def___DECC=yes + curl_cv_def___DECC=$tmp_exp + + fi + CPPFLAGS=$OLDCPPFLAGS + + + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + if test -z "$SED"; then + as_fn_error $? "SED not set. Cannot continue without SED being set." "$LINENO" 5 + fi + if test -z "$GREP"; then + as_fn_error $? "GREP not set. Cannot continue without GREP being set." "$LINENO" 5 + fi + + tmp_exp="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __DECC_VER +CURL_DEF_TOKEN __DECC_VER +#endif + + +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[ ][ ]*//' 2>/dev/null | \ + "$SED" 's/["][ ]*["]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "__DECC_VER"; then + tmp_exp="" + fi + +fi +rm -f conftest.err conftest.i conftest.$ac_ext + if test -z "$tmp_exp"; then + curl_cv_have_def___DECC_VER=no + + else + curl_cv_have_def___DECC_VER=yes + curl_cv_def___DECC_VER=$tmp_exp + + fi + CPPFLAGS=$OLDCPPFLAGS + + if test "$curl_cv_have_def___DECC" = "yes" && + test "$curl_cv_have_def___DECC_VER" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + compiler_id="DEC_C" + flags_dbg_yes="-g2" + flags_opt_all="-O -O0 -O1 -O2 -O3 -O4" + flags_opt_yes="-O1" + flags_opt_off="-O0" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler is HP-UX C" >&5 +printf %s "checking if compiler is HP-UX C... " >&6; } + + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + if test -z "$SED"; then + as_fn_error $? "SED not set. Cannot continue without SED being set." "$LINENO" 5 + fi + if test -z "$GREP"; then + as_fn_error $? "GREP not set. Cannot continue without GREP being set." "$LINENO" 5 + fi + + tmp_exp="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __HP_cc +CURL_DEF_TOKEN __HP_cc +#endif + + +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[ ][ ]*//' 2>/dev/null | \ + "$SED" 's/["][ ]*["]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "__HP_cc"; then + tmp_exp="" + fi + +fi +rm -f conftest.err conftest.i conftest.$ac_ext + if test -z "$tmp_exp"; then + curl_cv_have_def___HP_cc=no + + else + curl_cv_have_def___HP_cc=yes + curl_cv_def___HP_cc=$tmp_exp + + fi + CPPFLAGS=$OLDCPPFLAGS + + if test "$curl_cv_have_def___HP_cc" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + compiler_id="HP_UX_C" + flags_dbg_yes="-g" + flags_opt_all="-O +O0 +O1 +O2 +O3 +O4" + flags_opt_yes="+O2" + flags_opt_off="+O0" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler is IBM C" >&5 +printf %s "checking if compiler is IBM C... " >&6; } + + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + if test -z "$SED"; then + as_fn_error $? "SED not set. Cannot continue without SED being set." "$LINENO" 5 + fi + if test -z "$GREP"; then + as_fn_error $? "GREP not set. Cannot continue without GREP being set." "$LINENO" 5 + fi + + tmp_exp="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __IBMC__ +CURL_DEF_TOKEN __IBMC__ +#endif + + +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[ ][ ]*//' 2>/dev/null | \ + "$SED" 's/["][ ]*["]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "__IBMC__"; then + tmp_exp="" + fi + +fi +rm -f conftest.err conftest.i conftest.$ac_ext + if test -z "$tmp_exp"; then + curl_cv_have_def___IBMC__=no + + else + curl_cv_have_def___IBMC__=yes + curl_cv_def___IBMC__=$tmp_exp + + fi + CPPFLAGS=$OLDCPPFLAGS + + if test "$curl_cv_have_def___IBMC__" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + compiler_id="IBM_C" + flags_dbg_yes="-g" + flags_opt_all="-O -O0 -O1 -O2 -O3 -O4 -O5" + flags_opt_all="$flags_opt_all -qnooptimize" + flags_opt_all="$flags_opt_all -qoptimize=0" + flags_opt_all="$flags_opt_all -qoptimize=1" + flags_opt_all="$flags_opt_all -qoptimize=2" + flags_opt_all="$flags_opt_all -qoptimize=3" + flags_opt_all="$flags_opt_all -qoptimize=4" + flags_opt_all="$flags_opt_all -qoptimize=5" + flags_opt_yes="-O2" + flags_opt_off="-qnooptimize" + flags_prefer_cppflags="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler is Intel C" >&5 +printf %s "checking if compiler is Intel C... " >&6; } + + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + if test -z "$SED"; then + as_fn_error $? "SED not set. Cannot continue without SED being set." "$LINENO" 5 + fi + if test -z "$GREP"; then + as_fn_error $? "GREP not set. Cannot continue without GREP being set." "$LINENO" 5 + fi + + tmp_exp="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __INTEL_COMPILER +CURL_DEF_TOKEN __INTEL_COMPILER +#endif + + +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[ ][ ]*//' 2>/dev/null | \ + "$SED" 's/["][ ]*["]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "__INTEL_COMPILER"; then + tmp_exp="" + fi + +fi +rm -f conftest.err conftest.i conftest.$ac_ext + if test -z "$tmp_exp"; then + curl_cv_have_def___INTEL_COMPILER=no + + else + curl_cv_have_def___INTEL_COMPILER=yes + curl_cv_def___INTEL_COMPILER=$tmp_exp + + fi + CPPFLAGS=$OLDCPPFLAGS + + if test "$curl_cv_have_def___INTEL_COMPILER" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking compiler version" >&5 +printf %s "checking compiler version... " >&6; } + compiler_num="$curl_cv_def___INTEL_COMPILER" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: Intel C '$compiler_num'" >&5 +printf "%s\n" "Intel C '$compiler_num'" >&6; } + + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + if test -z "$SED"; then + as_fn_error $? "SED not set. Cannot continue without SED being set." "$LINENO" 5 + fi + if test -z "$GREP"; then + as_fn_error $? "GREP not set. Cannot continue without GREP being set." "$LINENO" 5 + fi + + tmp_exp="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __unix__ +CURL_DEF_TOKEN __unix__ +#endif + + +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[ ][ ]*//' 2>/dev/null | \ + "$SED" 's/["][ ]*["]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = ""; then + tmp_exp="" + fi + +fi +rm -f conftest.err conftest.i conftest.$ac_ext + if test -z "$tmp_exp"; then + curl_cv_have_def___unix__=no + + else + curl_cv_have_def___unix__=yes + curl_cv_def___unix__=$tmp_exp + + fi + CPPFLAGS=$OLDCPPFLAGS + + if test "$curl_cv_have_def___unix__" = "yes"; then + compiler_id="INTEL_UNIX_C" + flags_dbg_yes="-g" + flags_opt_all="-O -O0 -O1 -O2 -O3 -Os" + flags_opt_yes="-O2" + flags_opt_off="-O0" + else + compiler_id="INTEL_WINDOWS_C" + flags_dbg_yes="/Zi /Oy-" + flags_opt_all="/O /O0 /O1 /O2 /O3 /Od /Og /Og- /Oi /Oi-" + flags_opt_yes="/O2" + flags_opt_off="/Od" + fi + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler is clang" >&5 +printf %s "checking if compiler is clang... " >&6; } + + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + if test -z "$SED"; then + as_fn_error $? "SED not set. Cannot continue without SED being set." "$LINENO" 5 + fi + if test -z "$GREP"; then + as_fn_error $? "GREP not set. Cannot continue without GREP being set." "$LINENO" 5 + fi + + tmp_exp="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __clang__ +CURL_DEF_TOKEN __clang__ +#endif + + +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[ ][ ]*//' 2>/dev/null | \ + "$SED" 's/["][ ]*["]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "__clang__"; then + tmp_exp="" + fi + +fi +rm -f conftest.err conftest.i conftest.$ac_ext + if test -z "$tmp_exp"; then + curl_cv_have_def___clang__=no + + else + curl_cv_have_def___clang__=yes + curl_cv_def___clang__=$tmp_exp + + fi + CPPFLAGS=$OLDCPPFLAGS + + if test "$curl_cv_have_def___clang__" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler is xlclang" >&5 +printf %s "checking if compiler is xlclang... " >&6; } + + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + if test -z "$SED"; then + as_fn_error $? "SED not set. Cannot continue without SED being set." "$LINENO" 5 + fi + if test -z "$GREP"; then + as_fn_error $? "GREP not set. Cannot continue without GREP being set." "$LINENO" 5 + fi + + tmp_exp="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __ibmxl__ +CURL_DEF_TOKEN __ibmxl__ +#endif + + +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[ ][ ]*//' 2>/dev/null | \ + "$SED" 's/["][ ]*["]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "__ibmxl__"; then + tmp_exp="" + fi + +fi +rm -f conftest.err conftest.i conftest.$ac_ext + if test -z "$tmp_exp"; then + curl_cv_have_def___ibmxl__=no + + else + curl_cv_have_def___ibmxl__=yes + curl_cv_def___ibmxl__=$tmp_exp + + fi + CPPFLAGS=$OLDCPPFLAGS + + if test "$curl_cv_have_def___ibmxl__" = "yes" ; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + compiler_id="XLCLANG" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + compiler_id="CLANG" + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking compiler version" >&5 +printf %s "checking compiler version... " >&6; } + fullclangver=`$CC -v 2>&1 | grep version` + if echo $fullclangver | grep 'Apple' >/dev/null; then + appleclang=1 + else + appleclang=0 + fi + clangver=`echo $fullclangver | grep "based on LLVM " | "$SED" 's/.*(based on LLVM \([0-9]*\.[0-9]*\).*)/\1/'` + if test -z "$clangver"; then + clangver=`echo $fullclangver | "$SED" 's/.*version \([0-9]*\.[0-9]*\).*/\1/'` + oldapple=0 + else + oldapple=1 + fi + clangvhi=`echo $clangver | cut -d . -f1` + clangvlo=`echo $clangver | cut -d . -f2` + compiler_num=`(expr $clangvhi "*" 100 + $clangvlo) 2>/dev/null` + if test "$appleclang" = '1' && test "$oldapple" = '0'; then + if test "$compiler_num" -ge '1300'; then compiler_num='1200' + elif test "$compiler_num" -ge '1205'; then compiler_num='1101' + elif test "$compiler_num" -ge '1204'; then compiler_num='1000' + elif test "$compiler_num" -ge '1107'; then compiler_num='900' + elif test "$compiler_num" -ge '1103'; then compiler_num='800' + elif test "$compiler_num" -ge '1003'; then compiler_num='700' + elif test "$compiler_num" -ge '1001'; then compiler_num='600' + elif test "$compiler_num" -ge '904'; then compiler_num='500' + elif test "$compiler_num" -ge '902'; then compiler_num='400' + elif test "$compiler_num" -ge '803'; then compiler_num='309' + elif test "$compiler_num" -ge '703'; then compiler_num='308' + else compiler_num='307' + fi + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: clang '$compiler_num' (raw: '$fullclangver' / '$clangver')" >&5 +printf "%s\n" "clang '$compiler_num' (raw: '$fullclangver' / '$clangver')" >&6; } + flags_dbg_yes="-g" + flags_opt_all="-O -O0 -O1 -O2 -Os -O3 -O4" + flags_opt_yes="-O2" + flags_opt_off="-O0" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler is GNU C" >&5 +printf %s "checking if compiler is GNU C... " >&6; } + + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + if test -z "$SED"; then + as_fn_error $? "SED not set. Cannot continue without SED being set." "$LINENO" 5 + fi + if test -z "$GREP"; then + as_fn_error $? "GREP not set. Cannot continue without GREP being set." "$LINENO" 5 + fi + + tmp_exp="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __GNUC__ +CURL_DEF_TOKEN __GNUC__ +#endif + + +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[ ][ ]*//' 2>/dev/null | \ + "$SED" 's/["][ ]*["]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "__GNUC__"; then + tmp_exp="" + fi + +fi +rm -f conftest.err conftest.i conftest.$ac_ext + if test -z "$tmp_exp"; then + curl_cv_have_def___GNUC__=no + + else + curl_cv_have_def___GNUC__=yes + curl_cv_def___GNUC__=$tmp_exp + + fi + CPPFLAGS=$OLDCPPFLAGS + + if test "$curl_cv_have_def___GNUC__" = "yes" && + test "$compiler_id" = "unknown"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + compiler_id="GNU_C" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking compiler version" >&5 +printf %s "checking compiler version... " >&6; } + # strip '-suffix' parts, e.g. Ubuntu Windows cross-gcc returns '10-win32' + gccver=`$CC -dumpversion | sed -E 's/-.+$//'` + gccvhi=`echo $gccver | cut -d . -f1` + if echo $gccver | grep -F '.' >/dev/null; then + gccvlo=`echo $gccver | cut -d . -f2` + else + gccvlo="0" + fi + compiler_num=`(expr $gccvhi "*" 100 + $gccvlo) 2>/dev/null` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: gcc '$compiler_num' (raw: '$gccver')" >&5 +printf "%s\n" "gcc '$compiler_num' (raw: '$gccver')" >&6; } + flags_dbg_yes="-g" + flags_opt_all="-O -O0 -O1 -O2 -O3 -Os -Og -Ofast" + flags_opt_yes="-O2" + flags_opt_off="-O0" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + + case $host in + mips-sgi-irix*) + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler is SGI MIPSpro C" >&5 +printf %s "checking if compiler is SGI MIPSpro C... " >&6; } + + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + if test -z "$SED"; then + as_fn_error $? "SED not set. Cannot continue without SED being set." "$LINENO" 5 + fi + if test -z "$GREP"; then + as_fn_error $? "GREP not set. Cannot continue without GREP being set." "$LINENO" 5 + fi + + tmp_exp="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __GNUC__ +CURL_DEF_TOKEN __GNUC__ +#endif + + +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[ ][ ]*//' 2>/dev/null | \ + "$SED" 's/["][ ]*["]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "__GNUC__"; then + tmp_exp="" + fi + +fi +rm -f conftest.err conftest.i conftest.$ac_ext + if test -z "$tmp_exp"; then + curl_cv_have_def___GNUC__=no + + else + curl_cv_have_def___GNUC__=yes + curl_cv_def___GNUC__=$tmp_exp + + fi + CPPFLAGS=$OLDCPPFLAGS + + + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + if test -z "$SED"; then + as_fn_error $? "SED not set. Cannot continue without SED being set." "$LINENO" 5 + fi + if test -z "$GREP"; then + as_fn_error $? "GREP not set. Cannot continue without GREP being set." "$LINENO" 5 + fi + + tmp_exp="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef _COMPILER_VERSION +CURL_DEF_TOKEN _COMPILER_VERSION +#endif + + +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[ ][ ]*//' 2>/dev/null | \ + "$SED" 's/["][ ]*["]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "_COMPILER_VERSION"; then + tmp_exp="" + fi + +fi +rm -f conftest.err conftest.i conftest.$ac_ext + if test -z "$tmp_exp"; then + curl_cv_have_def__COMPILER_VERSION=no + + else + curl_cv_have_def__COMPILER_VERSION=yes + curl_cv_def__COMPILER_VERSION=$tmp_exp + + fi + CPPFLAGS=$OLDCPPFLAGS + + + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + if test -z "$SED"; then + as_fn_error $? "SED not set. Cannot continue without SED being set." "$LINENO" 5 + fi + if test -z "$GREP"; then + as_fn_error $? "GREP not set. Cannot continue without GREP being set." "$LINENO" 5 + fi + + tmp_exp="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef _SGI_COMPILER_VERSION +CURL_DEF_TOKEN _SGI_COMPILER_VERSION +#endif + + +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[ ][ ]*//' 2>/dev/null | \ + "$SED" 's/["][ ]*["]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "_SGI_COMPILER_VERSION"; then + tmp_exp="" + fi + +fi +rm -f conftest.err conftest.i conftest.$ac_ext + if test -z "$tmp_exp"; then + curl_cv_have_def__SGI_COMPILER_VERSION=no + + else + curl_cv_have_def__SGI_COMPILER_VERSION=yes + curl_cv_def__SGI_COMPILER_VERSION=$tmp_exp + + fi + CPPFLAGS=$OLDCPPFLAGS + + if test "$curl_cv_have_def___GNUC__" = "no" && + (test "$curl_cv_have_def__SGI_COMPILER_VERSION" = "yes" || + test "$curl_cv_have_def__COMPILER_VERSION" = "yes"); then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + compiler_id="SGI_MIPSPRO_C" + flags_dbg_yes="-g" + flags_opt_all="-O -O0 -O1 -O2 -O3 -Ofast" + flags_opt_yes="-O2" + flags_opt_off="-O0" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler is SGI MIPS C" >&5 +printf %s "checking if compiler is SGI MIPS C... " >&6; } + + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + if test -z "$SED"; then + as_fn_error $? "SED not set. Cannot continue without SED being set." "$LINENO" 5 + fi + if test -z "$GREP"; then + as_fn_error $? "GREP not set. Cannot continue without GREP being set." "$LINENO" 5 + fi + + tmp_exp="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __GNUC__ +CURL_DEF_TOKEN __GNUC__ +#endif + + +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[ ][ ]*//' 2>/dev/null | \ + "$SED" 's/["][ ]*["]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "__GNUC__"; then + tmp_exp="" + fi + +fi +rm -f conftest.err conftest.i conftest.$ac_ext + if test -z "$tmp_exp"; then + curl_cv_have_def___GNUC__=no + + else + curl_cv_have_def___GNUC__=yes + curl_cv_def___GNUC__=$tmp_exp + + fi + CPPFLAGS=$OLDCPPFLAGS + + + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + if test -z "$SED"; then + as_fn_error $? "SED not set. Cannot continue without SED being set." "$LINENO" 5 + fi + if test -z "$GREP"; then + as_fn_error $? "GREP not set. Cannot continue without GREP being set." "$LINENO" 5 + fi + + tmp_exp="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __sgi +CURL_DEF_TOKEN __sgi +#endif + + +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[ ][ ]*//' 2>/dev/null | \ + "$SED" 's/["][ ]*["]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "__sgi"; then + tmp_exp="" + fi + +fi +rm -f conftest.err conftest.i conftest.$ac_ext + if test -z "$tmp_exp"; then + curl_cv_have_def___sgi=no + + else + curl_cv_have_def___sgi=yes + curl_cv_def___sgi=$tmp_exp + + fi + CPPFLAGS=$OLDCPPFLAGS + + if test "$curl_cv_have_def___GNUC__" = "no" && + test "$curl_cv_have_def___sgi" = "yes" && + test "$compiler_id" = "unknown"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + compiler_id="SGI_MIPS_C" + flags_dbg_yes="-g" + flags_opt_all="-O -O0 -O1 -O2 -O3 -Ofast" + flags_opt_yes="-O2" + flags_opt_off="-O0" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + + ;; + esac + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler is SunPro C" >&5 +printf %s "checking if compiler is SunPro C... " >&6; } + + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + if test -z "$SED"; then + as_fn_error $? "SED not set. Cannot continue without SED being set." "$LINENO" 5 + fi + if test -z "$GREP"; then + as_fn_error $? "GREP not set. Cannot continue without GREP being set." "$LINENO" 5 + fi + + tmp_exp="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __SUNPRO_C +CURL_DEF_TOKEN __SUNPRO_C +#endif + + +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[ ][ ]*//' 2>/dev/null | \ + "$SED" 's/["][ ]*["]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "__SUNPRO_C"; then + tmp_exp="" + fi + +fi +rm -f conftest.err conftest.i conftest.$ac_ext + if test -z "$tmp_exp"; then + curl_cv_have_def___SUNPRO_C=no + + else + curl_cv_have_def___SUNPRO_C=yes + curl_cv_def___SUNPRO_C=$tmp_exp + + fi + CPPFLAGS=$OLDCPPFLAGS + + if test "$curl_cv_have_def___SUNPRO_C" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + compiler_id="SUNPRO_C" + flags_dbg_yes="-g" + flags_opt_all="-O -xO -xO1 -xO2 -xO3 -xO4 -xO5" + flags_opt_yes="-xO2" + flags_opt_off="" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler is Tiny C" >&5 +printf %s "checking if compiler is Tiny C... " >&6; } + + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + if test -z "$SED"; then + as_fn_error $? "SED not set. Cannot continue without SED being set." "$LINENO" 5 + fi + if test -z "$GREP"; then + as_fn_error $? "GREP not set. Cannot continue without GREP being set." "$LINENO" 5 + fi + + tmp_exp="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __TINYC__ +CURL_DEF_TOKEN __TINYC__ +#endif + + +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[ ][ ]*//' 2>/dev/null | \ + "$SED" 's/["][ ]*["]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "__TINYC__"; then + tmp_exp="" + fi + +fi +rm -f conftest.err conftest.i conftest.$ac_ext + if test -z "$tmp_exp"; then + curl_cv_have_def___TINYC__=no + + else + curl_cv_have_def___TINYC__=yes + curl_cv_def___TINYC__=$tmp_exp + + fi + CPPFLAGS=$OLDCPPFLAGS + + if test "$curl_cv_have_def___TINYC__" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + compiler_id="TINY_C" + flags_dbg_yes="-g" + flags_opt_all="" + flags_opt_yes="" + flags_opt_off="" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + + # + if test "$compiler_id" = "unknown"; then + cat <<_EOF 1>&2 +*** +*** Warning: This configure script does not have information about the +*** compiler you are using, relative to the flags required to enable or +*** disable generation of debug info, optimization options or warnings. +*** +*** Whatever settings are present in CFLAGS will be used for this run. +*** +*** If you wish to help the curl project to better support your compiler +*** you can report this and the required info on the libcurl development +*** mailing list: https://lists.haxx.selistinfo/curl-library/ +*** +_EOF + fi + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether build target is a native Windows one" >&5 +printf %s "checking whether build target is a native Windows one... " >&6; } +if test ${curl_cv_native_windows+y} +then : + printf %s "(cached) " >&6 +else $as_nop + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + +#ifdef _WIN32 + int dummy=1; +#else + Not a native Windows build target. +#endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + curl_cv_native_windows="yes" + +else $as_nop + + curl_cv_native_windows="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $curl_cv_native_windows" >&5 +printf "%s\n" "$curl_cv_native_windows" >&6; } + if test "x$curl_cv_native_windows" = xyes; then + DOING_NATIVE_WINDOWS_TRUE= + DOING_NATIVE_WINDOWS_FALSE='#' +else + DOING_NATIVE_WINDOWS_TRUE='#' + DOING_NATIVE_WINDOWS_FALSE= +fi + + + +squeeze() { + _sqz_result="" + eval _sqz_input=\$$1 + for _sqz_token in $_sqz_input; do + if test -z "$_sqz_result"; then + _sqz_result="$_sqz_token" + else + _sqz_result="$_sqz_result $_sqz_token" + fi + done + eval $1=\$_sqz_result + return 0 +} + + + # + if test "$compiler_id" != "unknown"; then + # + tmp_save_CPPFLAGS="$CPPFLAGS" + tmp_save_CFLAGS="$CFLAGS" + tmp_CPPFLAGS="" + tmp_CFLAGS="" + # + case "$compiler_id" in + # + CLANG) + # + tmp_CFLAGS="$tmp_CFLAGS -Qunused-arguments" + ;; + # + DEC_C) + # + tmp_CFLAGS="$tmp_CFLAGS -std1" + tmp_CFLAGS="$tmp_CFLAGS -noansi_alias" + tmp_CFLAGS="$tmp_CFLAGS -warnprotos" + tmp_CFLAGS="$tmp_CFLAGS -msg_fatal toofewargs,toomanyargs" + ;; + # + GNU_C) + # + if test "$compiler_num" -ge "295"; then + tmp_CFLAGS="$tmp_CFLAGS -Werror-implicit-function-declaration" + fi + ;; + # + HP_UX_C) + # + tmp_CFLAGS="$tmp_CFLAGS -z" + tmp_CFLAGS="$tmp_CFLAGS +W 4227,4255" + ;; + # + IBM_C) + # + tmp_CPPFLAGS="$tmp_CPPFLAGS -qthreaded" + tmp_CPPFLAGS="$tmp_CPPFLAGS -qnoansialias" + tmp_CPPFLAGS="$tmp_CPPFLAGS -qhalt=e" + ;; + # + INTEL_UNIX_C) + # + tmp_CFLAGS="$tmp_CFLAGS -std=gnu89" + tmp_CPPFLAGS="$tmp_CPPFLAGS -diag-error 140,147,165,266" + tmp_CPPFLAGS="$tmp_CPPFLAGS -diag-disable 279,981,1025,1469,2259" + ;; + # + INTEL_WINDOWS_C) + # + tmp_CFLAGS="$tmp_CFLAGS" + ;; + # + SGI_MIPS_C) + # + tmp_CFLAGS="$tmp_CFLAGS" + ;; + # + SGI_MIPSPRO_C) + # + tmp_CFLAGS="$tmp_CFLAGS" + ;; + # + SUNPRO_C) + # + tmp_CFLAGS="$tmp_CFLAGS" + ;; + # + TINY_C) + # + tmp_CFLAGS="$tmp_CFLAGS" + ;; + # + esac + # + squeeze tmp_CPPFLAGS + squeeze tmp_CFLAGS + # + if test ! -z "$tmp_CFLAGS" || test ! -z "$tmp_CPPFLAGS"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler accepts some basic options" >&5 +printf %s "checking if compiler accepts some basic options... " >&6; } + CPPFLAGS="$tmp_save_CPPFLAGS $tmp_CPPFLAGS" + CFLAGS="$tmp_save_CFLAGS $tmp_CFLAGS" + squeeze CPPFLAGS + squeeze CFLAGS + + tmp_compiler_works="unknown" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + + int i = 1; + return i; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + tmp_compiler_works="yes" + +else $as_nop + + tmp_compiler_works="no" + echo " " >&6 + sed 's/^/cc-fail: /' conftest.err >&6 + echo " " >&6 + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + if test "$tmp_compiler_works" = "yes"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + + int i = 1; + return i; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + tmp_compiler_works="yes" + +else $as_nop + + tmp_compiler_works="no" + echo " " >&6 + sed 's/^/link-fail: /' conftest.err >&6 + echo " " >&6 + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + fi + if test "x$cross_compiling" != "xyes" && + test "$tmp_compiler_works" = "yes"; then + + case $host_os in + darwin*) + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +# ifdef __STDC__ +# include +# endif + +int main (void) +{ + + int i = 0; + exit(i); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + tmp_compiler_works="yes" + +else $as_nop + tmp_compiler_works="no" + echo " " >&6 + echo "run-fail: test program exited with status $ac_status" >&6 + echo " " >&6 + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + ;; + *) + oldcc=$CC + old=$LD_LIBRARY_PATH + CC="sh ./run-compiler" + LD_LIBRARY_PATH=$CURL_LIBRARY_PATH:$old + export LD_LIBRARY_PATH + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +# ifdef __STDC__ +# include +# endif + +int main (void) +{ + + int i = 0; + exit(i); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + tmp_compiler_works="yes" + +else $as_nop + tmp_compiler_works="no" + echo " " >&6 + echo "run-fail: test program exited with status $ac_status" >&6 + echo " " >&6 + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LD_LIBRARY_PATH=$old # restore + CC=$oldcc + ;; + esac + + fi + if test "$tmp_compiler_works" = "yes"; then + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: compiler options added: $tmp_CFLAGS $tmp_CPPFLAGS" >&5 +printf "%s\n" "$as_me: compiler options added: $tmp_CFLAGS $tmp_CPPFLAGS" >&6;} + + else + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: compiler options rejected: $tmp_CFLAGS $tmp_CPPFLAGS" >&5 +printf "%s\n" "$as_me: WARNING: compiler options rejected: $tmp_CFLAGS $tmp_CPPFLAGS" >&2;} + CPPFLAGS="$tmp_save_CPPFLAGS" + CFLAGS="$tmp_save_CFLAGS" + + fi + + fi + # + fi + + + # + if test "$compiler_id" != "unknown"; then + # + tmp_save_CFLAGS="$CFLAGS" + tmp_save_CPPFLAGS="$CPPFLAGS" + # + tmp_options="" + tmp_CFLAGS="$CFLAGS" + tmp_CPPFLAGS="$CPPFLAGS" + # + if test "$want_debug" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler accepts debug enabling options" >&5 +printf %s "checking if compiler accepts debug enabling options... " >&6; } + tmp_options="$flags_dbg_yes" + fi + # + if test "$flags_prefer_cppflags" = "yes"; then + CPPFLAGS="$tmp_CPPFLAGS $tmp_options" + CFLAGS="$tmp_CFLAGS" + else + CPPFLAGS="$tmp_CPPFLAGS" + CFLAGS="$tmp_CFLAGS $tmp_options" + fi + squeeze CPPFLAGS + squeeze CFLAGS + fi + + + # + if test "$compiler_id" != "unknown"; then + # + tmp_save_CFLAGS="$CFLAGS" + tmp_save_CPPFLAGS="$CPPFLAGS" + # + tmp_options="" + tmp_CFLAGS="$CFLAGS" + tmp_CPPFLAGS="$CPPFLAGS" + honor_optimize_option="yes" + # + # + if test "$want_optimize" = "assume_no" || + test "$want_optimize" = "assume_yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler optimizer assumed setting might be used" >&5 +printf %s "checking if compiler optimizer assumed setting might be used... " >&6; } + + + ac_var_match_word="no" + for word1 in $tmp_CFLAGS; do + for word2 in $flags_opt_all; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "yes"; then + + honor_optimize_option="no" + + + fi + + + + ac_var_match_word="no" + for word1 in $tmp_CPPFLAGS; do + for word2 in $flags_opt_all; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "yes"; then + + honor_optimize_option="no" + + + fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $honor_optimize_option" >&5 +printf "%s\n" "$honor_optimize_option" >&6; } + if test "$honor_optimize_option" = "yes"; then + if test "$want_optimize" = "assume_yes"; then + want_optimize="yes" + fi + if test "$want_optimize" = "assume_no"; then + want_optimize="no" + fi + fi + fi + # + if test "$honor_optimize_option" = "yes"; then + + ac_var_stripped="" + for word1 in $tmp_CFLAGS; do + ac_var_strip_word="no" + for word2 in $flags_opt_all; do + if test "$word1" = "$word2"; then + ac_var_strip_word="yes" + fi + done + if test "$ac_var_strip_word" = "no"; then + ac_var_stripped="$ac_var_stripped $word1" + fi + done + tmp_CFLAGS="$ac_var_stripped" + squeeze tmp_CFLAGS + + + ac_var_stripped="" + for word1 in $tmp_CPPFLAGS; do + ac_var_strip_word="no" + for word2 in $flags_opt_all; do + if test "$word1" = "$word2"; then + ac_var_strip_word="yes" + fi + done + if test "$ac_var_strip_word" = "no"; then + ac_var_stripped="$ac_var_stripped $word1" + fi + done + tmp_CPPFLAGS="$ac_var_stripped" + squeeze tmp_CPPFLAGS + + if test "$want_optimize" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler accepts optimizer enabling options" >&5 +printf %s "checking if compiler accepts optimizer enabling options... " >&6; } + tmp_options="$flags_opt_yes" + fi + if test "$want_optimize" = "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler accepts optimizer disabling options" >&5 +printf %s "checking if compiler accepts optimizer disabling options... " >&6; } + tmp_options="$flags_opt_off" + fi + if test "$flags_prefer_cppflags" = "yes"; then + CPPFLAGS="$tmp_CPPFLAGS $tmp_options" + CFLAGS="$tmp_CFLAGS" + else + CPPFLAGS="$tmp_CPPFLAGS" + CFLAGS="$tmp_CFLAGS $tmp_options" + fi + squeeze CPPFLAGS + squeeze CFLAGS + + tmp_compiler_works="unknown" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + + int i = 1; + return i; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + tmp_compiler_works="yes" + +else $as_nop + + tmp_compiler_works="no" + echo " " >&6 + sed 's/^/cc-fail: /' conftest.err >&6 + echo " " >&6 + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + if test "$tmp_compiler_works" = "yes"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + + int i = 1; + return i; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + tmp_compiler_works="yes" + +else $as_nop + + tmp_compiler_works="no" + echo " " >&6 + sed 's/^/link-fail: /' conftest.err >&6 + echo " " >&6 + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + fi + if test "x$cross_compiling" != "xyes" && + test "$tmp_compiler_works" = "yes"; then + + case $host_os in + darwin*) + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +# ifdef __STDC__ +# include +# endif + +int main (void) +{ + + int i = 0; + exit(i); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + tmp_compiler_works="yes" + +else $as_nop + tmp_compiler_works="no" + echo " " >&6 + echo "run-fail: test program exited with status $ac_status" >&6 + echo " " >&6 + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + ;; + *) + oldcc=$CC + old=$LD_LIBRARY_PATH + CC="sh ./run-compiler" + LD_LIBRARY_PATH=$CURL_LIBRARY_PATH:$old + export LD_LIBRARY_PATH + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +# ifdef __STDC__ +# include +# endif + +int main (void) +{ + + int i = 0; + exit(i); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + tmp_compiler_works="yes" + +else $as_nop + tmp_compiler_works="no" + echo " " >&6 + echo "run-fail: test program exited with status $ac_status" >&6 + echo " " >&6 + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LD_LIBRARY_PATH=$old # restore + CC=$oldcc + ;; + esac + + fi + if test "$tmp_compiler_works" = "yes"; then + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: compiler options added: $tmp_options" >&5 +printf "%s\n" "$as_me: compiler options added: $tmp_options" >&6;} + + else + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: compiler options rejected: $tmp_options" >&5 +printf "%s\n" "$as_me: WARNING: compiler options rejected: $tmp_options" >&2;} + CPPFLAGS="$tmp_save_CPPFLAGS" + CFLAGS="$tmp_save_CFLAGS" + + fi + + fi + # + fi + + + # + if test "$compiler_id" != "unknown"; then + # + tmp_save_CPPFLAGS="$CPPFLAGS" + tmp_save_CFLAGS="$CFLAGS" + tmp_CPPFLAGS="" + tmp_CFLAGS="" + # + case "$compiler_id" in + # + CLANG) + # + if test "$want_warnings" = "yes"; then + tmp_CFLAGS="$tmp_CFLAGS -pedantic" + + ac_var_added_warnings="" + for warning in all extra; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in pointer-arith write-strings; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in shadow; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in inline nested-externs; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in missing-declarations; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in missing-prototypes; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + tmp_CFLAGS="$tmp_CFLAGS -Wno-long-long" + + ac_var_added_warnings="" + for warning in float-equal; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in sign-compare; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + tmp_CFLAGS="$tmp_CFLAGS -Wno-multichar" + + ac_var_added_warnings="" + for warning in undef; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + tmp_CFLAGS="$tmp_CFLAGS -Wno-format-nonliteral" + + ac_var_added_warnings="" + for warning in endif-labels strict-prototypes; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in declaration-after-statement; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in cast-align; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + tmp_CFLAGS="$tmp_CFLAGS -Wno-system-headers" + + ac_var_added_warnings="" + for warning in shorten-64-to-32; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + # + if test "$compiler_num" -ge "101"; then + + ac_var_added_warnings="" + for warning in unused; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + # + if test "$compiler_num" -ge "207"; then + + ac_var_added_warnings="" + for warning in address; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in attributes; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in bad-function-cast; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in conversion; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in div-by-zero format-security; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in empty-body; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in missing-field-initializers; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in missing-noreturn; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in old-style-definition; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in redundant-decls; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + # CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [switch-enum]) # Not used because this basically disallows default case + + ac_var_added_warnings="" + for warning in type-limits; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + # CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [unused-macros]) # Not practical + + ac_var_added_warnings="" + for warning in unreachable-code unused-parameter; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + # + if test "$compiler_num" -ge "208"; then + + ac_var_added_warnings="" + for warning in ignored-qualifiers; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in vla; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + # + if test "$compiler_num" -ge "209"; then + + ac_var_added_warnings="" + for warning in sign-conversion; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + tmp_CFLAGS="$tmp_CFLAGS -Wno-error=sign-conversion" # FIXME + + ac_var_added_warnings="" + for warning in shift-sign-overflow; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + # CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [padded]) # Not used because we cannot change public structs + fi + # + if test "$compiler_num" -ge "300"; then + + ac_var_added_warnings="" + for warning in language-extension-token; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + tmp_CFLAGS="$tmp_CFLAGS -Wformat=2" + fi + # + if test "$compiler_num" -ge "302"; then + + ac_var_added_warnings="" + for warning in enum-conversion; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in sometimes-uninitialized; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + case $host_os in + cygwin* | mingw*) + ;; + *) + + ac_var_added_warnings="" + for warning in missing-variable-declarations; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + ;; + esac + fi + # + if test "$compiler_num" -ge "304"; then + + ac_var_added_warnings="" + for warning in header-guard; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in unused-const-variable; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + # + if test "$compiler_num" -ge "305"; then + + ac_var_added_warnings="" + for warning in pragmas; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in unreachable-code-break; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + # + if test "$compiler_num" -ge "306"; then + + ac_var_added_warnings="" + for warning in double-promotion; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + # + if test "$compiler_num" -ge "309"; then + + ac_var_added_warnings="" + for warning in comma; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + # avoid the varargs warning, fixed in 4.0 + # https://bugs.llvm.org/show_bug.cgi?id=29140 + if test "$compiler_num" -lt "400"; then + tmp_CFLAGS="$tmp_CFLAGS -Wno-varargs" + fi + fi + if test "$compiler_num" -ge "700"; then + + ac_var_added_warnings="" + for warning in assign-enum; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in extra-semi-stmt; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + if test "$compiler_num" -ge "1000"; then + tmp_CFLAGS="$tmp_CFLAGS -Wimplicit-fallthrough" # we have silencing markup for clang 10.0 and above only + fi + fi + tmp_CFLAGS="$tmp_CFLAGS -Wno-pointer-bool-conversion" + ;; + # + DEC_C) + # + if test "$want_warnings" = "yes"; then + tmp_CFLAGS="$tmp_CFLAGS -msg_enable level3" + fi + ;; + # + GNU_C) + # + if test "$want_warnings" = "yes"; then + # + if test "x$cross_compiling" != "xyes" || + test "$compiler_num" -ge "300"; then + tmp_CFLAGS="$tmp_CFLAGS -pedantic" + fi + # + + ac_var_added_warnings="" + for warning in all; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + tmp_CFLAGS="$tmp_CFLAGS -W" + # + if test "$compiler_num" -ge "104"; then + + ac_var_added_warnings="" + for warning in pointer-arith write-strings; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + if test "x$cross_compiling" != "xyes" || + test "$compiler_num" -ge "300"; then + + ac_var_added_warnings="" + for warning in unused shadow; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + fi + # + if test "$compiler_num" -ge "207"; then + + ac_var_added_warnings="" + for warning in inline nested-externs; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + if test "x$cross_compiling" != "xyes" || + test "$compiler_num" -ge "300"; then + + ac_var_added_warnings="" + for warning in missing-declarations; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in missing-prototypes; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + fi + # + if test "$compiler_num" -ge "295"; then + tmp_CFLAGS="$tmp_CFLAGS -Wno-long-long" + + ac_var_added_warnings="" + for warning in bad-function-cast; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + # + if test "$compiler_num" -ge "296"; then + + ac_var_added_warnings="" + for warning in float-equal; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + tmp_CFLAGS="$tmp_CFLAGS -Wno-multichar" + + ac_var_added_warnings="" + for warning in sign-compare; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in undef; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + # + if test "$compiler_num" -ge "297"; then + tmp_CFLAGS="$tmp_CFLAGS -Wno-format-nonliteral" + fi + # + if test "$compiler_num" -ge "300"; then + tmp_CFLAGS="$tmp_CFLAGS" + fi + # + if test "$compiler_num" -ge "303"; then + + ac_var_added_warnings="" + for warning in endif-labels strict-prototypes; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + # + if test "$compiler_num" -ge "304"; then + + ac_var_added_warnings="" + for warning in declaration-after-statement; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in old-style-definition; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + # + if test "$compiler_num" -ge "400"; then + tmp_CFLAGS="$tmp_CFLAGS -Wstrict-aliasing=3" + fi + # + if test "$compiler_num" -ge "401"; then + + ac_var_added_warnings="" + for warning in attributes; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in div-by-zero format-security; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in missing-field-initializers; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + case $host in + *-*-msys*) + ;; + *) + + ac_var_added_warnings="" + for warning in missing-noreturn; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + # Seen to clash with libtool-generated stub code + ;; + esac + + ac_var_added_warnings="" + for warning in unreachable-code unused-parameter; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + # CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [padded]) # Not used because we cannot change public structs + + ac_var_added_warnings="" + for warning in pragmas; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in redundant-decls; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + # CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [switch-enum]) # Not used because this basically disallows default case + # CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [unused-macros]) # Not practical + fi + # + if test "$compiler_num" -ge "402"; then + + ac_var_added_warnings="" + for warning in cast-align; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + # + if test "$compiler_num" -ge "403"; then + + ac_var_added_warnings="" + for warning in address; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in type-limits old-style-declaration; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in missing-parameter-type empty-body; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in clobbered ignored-qualifiers; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in conversion trampolines; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in sign-conversion; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + tmp_CFLAGS="$tmp_CFLAGS -Wno-error=sign-conversion" # FIXME + + ac_var_added_warnings="" + for warning in vla; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + tmp_CFLAGS="$tmp_CFLAGS -ftree-vrp" + fi + # + if test "$compiler_num" -ge "405"; then + if test "$curl_cv_native_windows" = "yes"; then + tmp_CFLAGS="$tmp_CFLAGS -Wno-pedantic-ms-format" + fi + fi + # + if test "$compiler_num" -ge "406"; then + + ac_var_added_warnings="" + for warning in double-promotion; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + # + if test "$compiler_num" -ge "408"; then + tmp_CFLAGS="$tmp_CFLAGS -Wformat=2" + fi + # + if test "$compiler_num" -ge "500"; then + tmp_CFLAGS="$tmp_CFLAGS -Warray-bounds=2" + fi + # + if test "$compiler_num" -ge "600"; then + + ac_var_added_warnings="" + for warning in shift-negative-value; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + tmp_CFLAGS="$tmp_CFLAGS -Wshift-overflow=2" + + ac_var_added_warnings="" + for warning in null-dereference; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + tmp_CFLAGS="$tmp_CFLAGS -fdelete-null-pointer-checks" + + ac_var_added_warnings="" + for warning in duplicated-cond; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in unused-const-variable; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + # + if test "$compiler_num" -ge "700"; then + + ac_var_added_warnings="" + for warning in duplicated-branches; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in restrict; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in alloc-zero; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + tmp_CFLAGS="$tmp_CFLAGS -Wformat-overflow=2" + tmp_CFLAGS="$tmp_CFLAGS -Wformat-truncation=2" + tmp_CFLAGS="$tmp_CFLAGS -Wimplicit-fallthrough" + fi + # + if test "$compiler_num" -ge "1000"; then + + ac_var_added_warnings="" + for warning in arith-conversion; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in enum-conversion; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + # + fi + # + if test "$compiler_num" -ge "300"; then + tmp_CFLAGS="$tmp_CFLAGS -Wno-system-headers" + else + if test "x$cross_compiling" = "xyes"; then + if test "$compiler_num" -ge "104"; then + tmp_CFLAGS="$tmp_CFLAGS -Wno-unused -Wno-shadow" + fi + if test "$compiler_num" -ge "207"; then + tmp_CFLAGS="$tmp_CFLAGS -Wno-missing-declarations" + tmp_CFLAGS="$tmp_CFLAGS -Wno-missing-prototypes" + fi + fi + fi + ;; + # + HP_UX_C) + # + if test "$want_warnings" = "yes"; then + tmp_CFLAGS="$tmp_CFLAGS +w1" + fi + ;; + # + IBM_C) + # + tmp_CFLAGS="$tmp_CFLAGS" + ;; + # + INTEL_UNIX_C) + # + if test "$want_warnings" = "yes"; then + if test "$compiler_num" -gt "600"; then + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wall -w2" + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wcheck" + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wcomment" + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wdeprecated" + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wmissing-prototypes" + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wp64" + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wpointer-arith" + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wreturn-type" + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wshadow" + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wuninitialized" + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wunused-function" + fi + fi + tmp_CFLAGS="$tmp_CFLAGS -fno-omit-frame-pointer" + tmp_CFLAGS="$tmp_CFLAGS -fno-strict-aliasing" + tmp_CFLAGS="$tmp_CFLAGS -fp-model precise" + ;; + # + INTEL_WINDOWS_C) + # + tmp_CFLAGS="$tmp_CFLAGS" + ;; + # + SGI_MIPS_C) + # + if test "$want_warnings" = "yes"; then + tmp_CFLAGS="$tmp_CFLAGS -fullwarn" + fi + ;; + # + SGI_MIPSPRO_C) + # + if test "$want_warnings" = "yes"; then + tmp_CFLAGS="$tmp_CFLAGS -fullwarn" + tmp_CFLAGS="$tmp_CFLAGS -woff 1209" + fi + ;; + # + SUNPRO_C) + # + if test "$want_warnings" = "yes"; then + tmp_CFLAGS="$tmp_CFLAGS -v" + fi + ;; + # + TINY_C) + # + if test "$want_warnings" = "yes"; then + + ac_var_added_warnings="" + for warning in all; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in write-strings; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + + ac_var_added_warnings="" + for warning in unsupported; do + + ac_var_match_word="no" + for word1 in $CFLAGS; do + for word2 in -Wno-$warning -W$warning; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done + + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + tmp_CFLAGS="$tmp_CFLAGS $ac_var_added_warnings" + squeeze tmp_CFLAGS + + fi + ;; + # + esac + # + squeeze tmp_CPPFLAGS + squeeze tmp_CFLAGS + # + if test ! -z "$tmp_CFLAGS" || test ! -z "$tmp_CPPFLAGS"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler accepts strict warning options" >&5 +printf %s "checking if compiler accepts strict warning options... " >&6; } + CPPFLAGS="$tmp_save_CPPFLAGS $tmp_CPPFLAGS" + CFLAGS="$tmp_save_CFLAGS $tmp_CFLAGS" + squeeze CPPFLAGS + squeeze CFLAGS + + tmp_compiler_works="unknown" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + + int i = 1; + return i; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + tmp_compiler_works="yes" + +else $as_nop + + tmp_compiler_works="no" + echo " " >&6 + sed 's/^/cc-fail: /' conftest.err >&6 + echo " " >&6 + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + if test "$tmp_compiler_works" = "yes"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + + int i = 1; + return i; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + tmp_compiler_works="yes" + +else $as_nop + + tmp_compiler_works="no" + echo " " >&6 + sed 's/^/link-fail: /' conftest.err >&6 + echo " " >&6 + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + fi + if test "x$cross_compiling" != "xyes" && + test "$tmp_compiler_works" = "yes"; then + + case $host_os in + darwin*) + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +# ifdef __STDC__ +# include +# endif + +int main (void) +{ + + int i = 0; + exit(i); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + tmp_compiler_works="yes" + +else $as_nop + tmp_compiler_works="no" + echo " " >&6 + echo "run-fail: test program exited with status $ac_status" >&6 + echo " " >&6 + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + ;; + *) + oldcc=$CC + old=$LD_LIBRARY_PATH + CC="sh ./run-compiler" + LD_LIBRARY_PATH=$CURL_LIBRARY_PATH:$old + export LD_LIBRARY_PATH + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +# ifdef __STDC__ +# include +# endif + +int main (void) +{ + + int i = 0; + exit(i); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + tmp_compiler_works="yes" + +else $as_nop + tmp_compiler_works="no" + echo " " >&6 + echo "run-fail: test program exited with status $ac_status" >&6 + echo " " >&6 + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LD_LIBRARY_PATH=$old # restore + CC=$oldcc + ;; + esac + + fi + if test "$tmp_compiler_works" = "yes"; then + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: compiler options added: $tmp_CFLAGS $tmp_CPPFLAGS" >&5 +printf "%s\n" "$as_me: compiler options added: $tmp_CFLAGS $tmp_CPPFLAGS" >&6;} + + else + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: compiler options rejected: $tmp_CFLAGS $tmp_CPPFLAGS" >&5 +printf "%s\n" "$as_me: WARNING: compiler options rejected: $tmp_CFLAGS $tmp_CPPFLAGS" >&2;} + CPPFLAGS="$tmp_save_CPPFLAGS" + CFLAGS="$tmp_save_CFLAGS" + + fi + + fi + # + fi + + +if test "$compiler_id" = "INTEL_UNIX_C"; then + # + if test "$compiler_num" -ge "1000"; then + CFLAGS="$CFLAGS -shared-intel" + elif test "$compiler_num" -ge "900"; then + CFLAGS="$CFLAGS -i-dynamic" + fi + # +fi + +CURL_CFLAG_EXTRAS="" +if test X"$want_werror" = Xyes; then + CURL_CFLAG_EXTRAS="-Werror" + if test "$compiler_id" = "GNU_C"; then + if test "$compiler_num" -ge "500"; then + CURL_CFLAG_EXTRAS="$CURL_CFLAG_EXTRAS -pedantic-errors" + fi + fi +fi + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler halts on compilation errors" >&5 +printf %s "checking if compiler halts on compilation errors... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + + force compilation error + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + as_fn_error $? "compiler does not halt on compilation errors." "$LINENO" 5 + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler halts on negative sized arrays" >&5 +printf %s "checking if compiler halts on negative sized arrays... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + typedef char bad_t[sizeof(char) == sizeof(int) ? -1 : -1 ]; + +int main (void) +{ + + bad_t dummy; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + as_fn_error $? "compiler does not halt on negative sized arrays." "$LINENO" 5 + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler halts on function prototype mismatch" >&5 +printf %s "checking if compiler halts on function prototype mismatch... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +# include + int rand(int n); + int rand(int n) + { + if(n) + return ++n; + else + return n; + } + +int main (void) +{ + + int i[2]={0,0}; + int j = rand(i[0]); + if(j) + return j; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + as_fn_error $? "compiler does not halt on function prototype mismatch." "$LINENO" 5 + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler supports hiding library internal symbols" >&5 +printf %s "checking if compiler supports hiding library internal symbols... " >&6; } + supports_symbol_hiding="no" + symbol_hiding_CFLAGS="" + symbol_hiding_EXTERN="" + tmp_CFLAGS="" + tmp_EXTERN="" + case "$compiler_id" in + CLANG) + tmp_EXTERN="__attribute__ ((__visibility__ (\"default\")))" + tmp_CFLAGS="-fvisibility=hidden" + supports_symbol_hiding="yes" + ;; + GNU_C) + if test "$compiler_num" -ge "304"; then + if $CC --help --verbose 2>/dev/null | grep fvisibility= >/dev/null ; then + tmp_EXTERN="__attribute__ ((__visibility__ (\"default\")))" + tmp_CFLAGS="-fvisibility=hidden" + supports_symbol_hiding="yes" + fi + fi + ;; + INTEL_UNIX_C) + if test "$compiler_num" -ge "900"; then + if $CC --help --verbose 2>&1 | grep fvisibility= > /dev/null ; then + tmp_save_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS -fvisibility=hidden" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +# include + +int main (void) +{ + + printf("icc fvisibility bug test"); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + tmp_EXTERN="__attribute__ ((__visibility__ (\"default\")))" + tmp_CFLAGS="-fvisibility=hidden" + supports_symbol_hiding="yes" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + CFLAGS="$tmp_save_CFLAGS" + fi + fi + ;; + SUNPRO_C) + if $CC 2>&1 | grep flags >/dev/null && $CC -flags | grep xldscope= >/dev/null ; then + tmp_EXTERN="__global" + tmp_CFLAGS="-xldscope=hidden" + supports_symbol_hiding="yes" + fi + ;; + esac + if test "$supports_symbol_hiding" = "yes"; then + tmp_save_CFLAGS="$CFLAGS" + CFLAGS="$tmp_save_CFLAGS $tmp_CFLAGS" + squeeze CFLAGS + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $tmp_EXTERN char *dummy(char *buff); + char *dummy(char *buff) + { + if(buff) + return ++buff; + else + return buff; + } + +int main (void) +{ + + char b[16]; + char *r = dummy(&b[0]); + if(r) + return (int)*r; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + supports_symbol_hiding="yes" + if test -f conftest.err; then + grep 'visibility' conftest.err >/dev/null + if test "$?" -eq "0"; then + supports_symbol_hiding="no" + fi + fi + +else $as_nop + + supports_symbol_hiding="no" + echo " " >&6 + sed 's/^/cc-src: /' conftest.$ac_ext >&6 + sed 's/^/cc-err: /' conftest.err >&6 + echo " " >&6 + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + CFLAGS="$tmp_save_CFLAGS" + fi + if test "$supports_symbol_hiding" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + symbol_hiding_CFLAGS="$tmp_CFLAGS" + symbol_hiding_EXTERN="$tmp_EXTERN" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + + + + supports_curldebug="unknown" + if test "$want_curldebug" = "yes"; then + if test "x$enable_shared" != "xno" && + test "x$enable_shared" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: unknown enable_shared setting." >&5 +printf "%s\n" "$as_me: WARNING: unknown enable_shared setting." >&2;} + supports_curldebug="no" + fi + if test "x$enable_static" != "xno" && + test "x$enable_static" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: unknown enable_static setting." >&5 +printf "%s\n" "$as_me: WARNING: unknown enable_static setting." >&2;} + supports_curldebug="no" + fi + if test "$supports_curldebug" != "no"; then + if test "$enable_shared" = "yes" && + test "x$xc_lt_shlib_use_no_undefined" = 'xyes'; then + supports_curldebug="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: shared library does not support undefined symbols." >&5 +printf "%s\n" "$as_me: WARNING: shared library does not support undefined symbols." >&2;} + fi + fi + fi + # + if test "$want_curldebug" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if curl debug memory tracking can be enabled" >&5 +printf %s "checking if curl debug memory tracking can be enabled... " >&6; } + test "$supports_curldebug" = "no" || supports_curldebug="yes" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $supports_curldebug" >&5 +printf "%s\n" "$supports_curldebug" >&6; } + if test "$supports_curldebug" = "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: cannot enable curl debug memory tracking." >&5 +printf "%s\n" "$as_me: WARNING: cannot enable curl debug memory tracking." >&2;} + want_curldebug="no" + fi + fi + + if test x$want_curldebug = xyes; then + CURLDEBUG_TRUE= + CURLDEBUG_FALSE='#' +else + CURLDEBUG_TRUE='#' + CURLDEBUG_FALSE= +fi + + +supports_unittests=yes +# cross-compilation of unit tests static library/programs fails when +# libcurl shared library is built. This might be due to a libtool or +# automake issue. In this case we disable unit tests. +if test "x$cross_compiling" != "xno" && + test "x$enable_shared" != "xno"; then + supports_unittests=no +fi + +# IRIX 6.5.24 gcc 3.3 autobuilds fail unittests library compilation due to +# a problem related with OpenSSL headers and library versions not matching. +# Disable unit tests while time to further investigate this is found. +case $host in + mips-sgi-irix6.5) + if test "$compiler_id" = "GNU_C"; then + supports_unittests=no + fi + ;; +esac + +# All AIX autobuilds fails unit tests linking against unittests library +# due to unittests library being built with no symbols or members. Libtool ? +# Disable unit tests while time to further investigate this is found. +case $host_os in + aix*) + supports_unittests=no + ;; +esac + +if test "x$want_debug" = "xyes" && + test "x$supports_unittests" = "xyes"; then + want_unittests=yes +else + want_unittests=no +fi + if test x$want_unittests = xyes; then + BUILD_UNITTESTS_TRUE= + BUILD_UNITTESTS_FALSE='#' +else + BUILD_UNITTESTS_TRUE='#' + BUILD_UNITTESTS_FALSE= +fi + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether build target supports WIN32 file API" >&5 +printf %s "checking whether build target supports WIN32 file API... " >&6; } + curl_win32_file_api="no" + if test "$curl_cv_native_windows" = "yes"; then + if test x"$enable_largefile" != "xno"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + +#if !defined(_WIN32_WCE) && (defined(__MINGW32__) || defined(_MSC_VER)) + int dummy=1; +#else + WIN32 large file API not supported. +#endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + curl_win32_file_api="win32_large_files" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + if test "$curl_win32_file_api" = "no"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + +#if defined(_WIN32_WCE) || defined(__MINGW32__) || defined(_MSC_VER) + int dummy=1; +#else + WIN32 small file API not supported. +#endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + curl_win32_file_api="win32_small_files" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + fi + case "$curl_win32_file_api" in + win32_large_files) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes (large file enabled)" >&5 +printf "%s\n" "yes (large file enabled)" >&6; } + +printf "%s\n" "#define USE_WIN32_LARGE_FILES 1" >>confdefs.h + + USE_WIN32_LARGE_FILES=1 + + ;; + win32_small_files) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes (large file disabled)" >&5 +printf "%s\n" "yes (large file disabled)" >&6; } + +printf "%s\n" "#define USE_WIN32_SMALL_FILES 1" >>confdefs.h + + USE_WIN32_SMALL_FILES=1 + + ;; + *) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + esac + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether build target supports WIN32 crypto API" >&5 +printf %s "checking whether build target supports WIN32 crypto API... " >&6; } + curl_win32_crypto_api="no" + if test "$curl_cv_native_windows" = "yes"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#undef inline +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#include + +int main (void) +{ + + HCRYPTPROV hCryptProv; + if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { + CryptReleaseContext(hCryptProv, 0); + } + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + curl_win32_crypto_api="yes" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + case "$curl_win32_crypto_api" in + yes) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define USE_WIN32_CRYPTO 1" >>confdefs.h + + USE_WIN32_CRYPTO=1 + + ;; + *) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + esac + + + + + tst_cflags="no" + case $host_os in + darwin*) + tst_cflags="yes" + ;; + esac + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for good-to-use Darwin CFLAGS" >&5 +printf %s "checking for good-to-use Darwin CFLAGS... " >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tst_cflags" >&5 +printf "%s\n" "$tst_cflags" >&6; }; + + if test "$tst_cflags" = "yes"; then + old_CFLAGS=$CFLAGS + CFLAGS="$CFLAGS -Werror=partial-availability" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Werror=partial-availability" >&5 +printf %s "checking whether $CC accepts -Werror=partial-availability... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + CFLAGS=$old_CFLAGS +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to link macOS CoreFoundation, CoreServices, and SystemConfiguration frameworks" >&5 +printf %s "checking whether to link macOS CoreFoundation, CoreServices, and SystemConfiguration frameworks... " >&6; } +case $host_os in + darwin*) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#include + +int main (void) +{ + +#if TARGET_OS_MAC && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) + return 0; +#else +#error Not macOS +#endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + build_for_macos="yes" + +else $as_nop + + build_for_macos="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + if test "x$build_for_macos" != xno; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + LDFLAGS="$LDFLAGS -framework CoreFoundation -framework CoreServices -framework SystemConfiguration" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + ;; + *) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +esac + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking to see if the compiler supports __builtin_available()" >&5 +printf %s "checking to see if the compiler supports __builtin_available()... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#include + +int main (void) +{ + + if (__builtin_available(macOS 10.8, iOS 5.0, *)) {} + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_BUILTIN_AVAILABLE 1" >>confdefs.h + + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + + + if test "$curl_cv_native_windows" = "yes" && test -n "${RC}"; then + HAVE_WINDRES_TRUE= + HAVE_WINDRES_FALSE='#' +else + HAVE_WINDRES_TRUE='#' + HAVE_WINDRES_FALSE= +fi + + +if test "$curl_cv_native_windows" = "yes"; then + if test -z "$HAVE_WINDRES_TRUE"; then : + else + as_fn_error $? "windres not found in PATH. Windows builds require windres. Cannot continue." "$LINENO" 5 +fi +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support http" >&5 +printf %s "checking whether to support http... " >&6; } +# Check whether --enable-http was given. +if test ${enable_http+y} +then : + enableval=$enable_http; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_HTTP 1" >>confdefs.h + + disable_http="yes" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: disable HTTP disables FTP over proxy and RTSP" >&5 +printf "%s\n" "$as_me: WARNING: disable HTTP disables FTP over proxy and RTSP" >&2;} + CURL_DISABLE_HTTP=1 + + +printf "%s\n" "#define CURL_DISABLE_RTSP 1" >>confdefs.h + + CURL_DISABLE_RTSP=1 + + +printf "%s\n" "#define CURL_DISABLE_ALTSVC 1" >>confdefs.h + + +printf "%s\n" "#define CURL_DISABLE_HSTS 1" >>confdefs.h + + curl_h1_msg="no (--enable-http, --with-hyper)" + curl_altsvc_msg="no"; + curl_hsts_msg="no (--enable-hsts)"; + enable_altsvc="no" + hsts="no" + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support ftp" >&5 +printf %s "checking whether to support ftp... " >&6; } +# Check whether --enable-ftp was given. +if test ${enable_ftp+y} +then : + enableval=$enable_ftp; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_FTP 1" >>confdefs.h + + CURL_DISABLE_FTP=1 + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support file" >&5 +printf %s "checking whether to support file... " >&6; } +# Check whether --enable-file was given. +if test ${enable_file+y} +then : + enableval=$enable_file; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_FILE 1" >>confdefs.h + + CURL_DISABLE_FILE=1 + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support ldap" >&5 +printf %s "checking whether to support ldap... " >&6; } +# Check whether --enable-ldap was given. +if test ${enable_ldap+y} +then : + enableval=$enable_ldap; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_LDAP 1" >>confdefs.h + + CURL_DISABLE_LDAP=1 + + ;; + yes) + ldap_askedfor="yes" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + *) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support ldaps" >&5 +printf %s "checking whether to support ldaps... " >&6; } +# Check whether --enable-ldaps was given. +if test ${enable_ldaps+y} +then : + enableval=$enable_ldaps; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_LDAPS 1" >>confdefs.h + + CURL_DISABLE_LDAPS=1 + + ;; + *) if test "x$CURL_DISABLE_LDAP" = "x1" ; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: LDAP needs to be enabled to support LDAPS" >&5 +printf "%s\n" "LDAP needs to be enabled to support LDAPS" >&6; } + +printf "%s\n" "#define CURL_DISABLE_LDAPS 1" >>confdefs.h + + CURL_DISABLE_LDAPS=1 + + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_LDAP_SSL 1" >>confdefs.h + + HAVE_LDAP_SSL=1 + + fi + ;; + esac +else $as_nop + + if test "x$CURL_DISABLE_LDAP" = "x1" ; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_LDAPS 1" >>confdefs.h + + CURL_DISABLE_LDAPS=1 + + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_LDAP_SSL 1" >>confdefs.h + + HAVE_LDAP_SSL=1 + + fi + +fi + + + +OPT_HYPER="no" + + +# Check whether --with-hyper was given. +if test ${with_hyper+y} +then : + withval=$with_hyper; OPT_HYPER=$withval +fi + +case "$OPT_HYPER" in + no) + want_hyper="no" + ;; + yes) + want_hyper="default" + want_hyper_path="" + ;; + *) + want_hyper="yes" + want_hyper_path="$withval" + ;; +esac + +if test X"$want_hyper" != Xno; then + if test "x$disable_http" = "xyes"; then + as_fn_error $? "--with-hyper is not compatible with --disable-http" "$LINENO" 5 + fi + + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for hyper options with pkg-config" >&5 +printf %s "checking for hyper options with pkg-config... " >&6; } + itexists=` + if test -n "$want_hyper_path"; then + PKG_CONFIG_LIBDIR="$want_hyper_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists hyper >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + LIB_HYPER=` + if test -n "$want_hyper_path"; then + PKG_CONFIG_LIBDIR="$want_hyper_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-l hyper` + CPP_HYPER=` + if test -n "$want_hyper_path"; then + PKG_CONFIG_LIBDIR="$want_hyper_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --cflags-only-I hyper` + LD_HYPER=` + if test -n "$want_hyper_path"; then + PKG_CONFIG_LIBDIR="$want_hyper_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-L hyper` + else + LIB_HYPER="-lhyper -ldl -lpthread -lm" + if test X"$want_hyper" != Xdefault; then + CPP_HYPER=-I"$want_hyper_path/capi/include" + LD_HYPER="-L$want_hyper_path/target/release -L$want_hyper_path/target/debug" + fi + fi + if test -n "$LIB_HYPER"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -l is $LIB_HYPER" >&5 +printf "%s\n" "$as_me: -l is $LIB_HYPER" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -I is $CPP_HYPER" >&5 +printf "%s\n" "$as_me: -I is $CPP_HYPER" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -L is $LD_HYPER" >&5 +printf "%s\n" "$as_me: -L is $LD_HYPER" >&6;} + + LDFLAGS="$LDFLAGS $LD_HYPER" + CPPFLAGS="$CPPFLAGS $CPP_HYPER" + LIBS="$LIB_HYPER $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_HYPER=`echo $LD_HYPER | $SED -e 's/^-L//' -e 's/ -L/:/g'` + fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for hyper_io_new in -lhyper" >&5 +printf %s "checking for hyper_io_new in -lhyper... " >&6; } +if test ${ac_cv_lib_hyper_hyper_io_new+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lhyper $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char hyper_io_new (); +int main (void) +{ +return hyper_io_new (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_hyper_hyper_io_new=yes +else $as_nop + ac_cv_lib_hyper_hyper_io_new=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_hyper_hyper_io_new" >&5 +printf "%s\n" "$ac_cv_lib_hyper_hyper_io_new" >&6; } +if test "x$ac_cv_lib_hyper_hyper_io_new" = xyes +then : + + for ac_header in hyper.h +do : + ac_fn_c_check_header_compile "$LINENO" "hyper.h" "ac_cv_header_hyper_h" "$ac_includes_default" +if test "x$ac_cv_header_hyper_h" = xyes +then : + printf "%s\n" "#define HAVE_HYPER_H 1" >>confdefs.h + experimental="$experimental Hyper" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Hyper support is experimental" >&5 +printf "%s\n" "$as_me: Hyper support is experimental" >&6;} + curl_h1_msg="enabled (Hyper)" + HYPER_ENABLED=1 + +printf "%s\n" "#define USE_HYPER 1" >>confdefs.h + + USE_HYPER=1 + + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_HYPER" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $DIR_HYPER to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $DIR_HYPER to CURL_LIBRARY_PATH" >&6;} +fi + +done + +else $as_nop + for d in `echo $DIR_HYPER | $SED -e 's/:/ /'`; do + if test -f "$d/libhyper.a"; then + as_fn_error $? "hyper was found in $d but was probably built with wrong flags. See docs/HYPER.md." "$LINENO" 5 + fi + done + as_fn_error $? "--with-hyper but hyper was not found. See docs/HYPER.md." "$LINENO" 5 + +fi + + fi +fi + +if test X"$want_hyper" != Xno; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Disable RTSP support with hyper" >&5 +printf "%s\n" "$as_me: Disable RTSP support with hyper" >&6;} + +printf "%s\n" "#define CURL_DISABLE_RTSP 1" >>confdefs.h + + CURL_DISABLE_RTSP=1 + +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support rtsp" >&5 +printf %s "checking whether to support rtsp... " >&6; } + # Check whether --enable-rtsp was given. +if test ${enable_rtsp+y} +then : + enableval=$enable_rtsp; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_RTSP 1" >>confdefs.h + + CURL_DISABLE_RTSP=1 + + ;; + *) + if test x$CURL_DISABLE_HTTP = x1 ; then + as_fn_error $? "HTTP support needs to be enabled in order to enable RTSP support!" "$LINENO" 5 + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + curl_rtsp_msg="enabled" + fi + ;; + esac +else $as_nop + if test "x$CURL_DISABLE_HTTP" != "x1"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + curl_rtsp_msg="enabled" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + +fi + +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support proxies" >&5 +printf %s "checking whether to support proxies... " >&6; } +# Check whether --enable-proxy was given. +if test ${enable_proxy+y} +then : + enableval=$enable_proxy; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_PROXY 1" >>confdefs.h + + CURL_DISABLE_PROXY=1 + + https_proxy="no" + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support dict" >&5 +printf %s "checking whether to support dict... " >&6; } +# Check whether --enable-dict was given. +if test ${enable_dict+y} +then : + enableval=$enable_dict; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_DICT 1" >>confdefs.h + + CURL_DISABLE_DICT=1 + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support telnet" >&5 +printf %s "checking whether to support telnet... " >&6; } +# Check whether --enable-telnet was given. +if test ${enable_telnet+y} +then : + enableval=$enable_telnet; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_TELNET 1" >>confdefs.h + + CURL_DISABLE_TELNET=1 + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support tftp" >&5 +printf %s "checking whether to support tftp... " >&6; } +# Check whether --enable-tftp was given. +if test ${enable_tftp+y} +then : + enableval=$enable_tftp; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_TFTP 1" >>confdefs.h + + CURL_DISABLE_TFTP=1 + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support pop3" >&5 +printf %s "checking whether to support pop3... " >&6; } +# Check whether --enable-pop3 was given. +if test ${enable_pop3+y} +then : + enableval=$enable_pop3; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_POP3 1" >>confdefs.h + + CURL_DISABLE_POP3=1 + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support imap" >&5 +printf %s "checking whether to support imap... " >&6; } +# Check whether --enable-imap was given. +if test ${enable_imap+y} +then : + enableval=$enable_imap; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_IMAP 1" >>confdefs.h + + CURL_DISABLE_IMAP=1 + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support smb" >&5 +printf %s "checking whether to support smb... " >&6; } +# Check whether --enable-smb was given. +if test ${enable_smb+y} +then : + enableval=$enable_smb; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_SMB 1" >>confdefs.h + + CURL_DISABLE_SMB=1 + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support smtp" >&5 +printf %s "checking whether to support smtp... " >&6; } +# Check whether --enable-smtp was given. +if test ${enable_smtp+y} +then : + enableval=$enable_smtp; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_SMTP 1" >>confdefs.h + + CURL_DISABLE_SMTP=1 + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support gopher" >&5 +printf %s "checking whether to support gopher... " >&6; } +# Check whether --enable-gopher was given. +if test ${enable_gopher+y} +then : + enableval=$enable_gopher; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_GOPHER 1" >>confdefs.h + + CURL_DISABLE_GOPHER=1 + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support mqtt" >&5 +printf %s "checking whether to support mqtt... " >&6; } +# Check whether --enable-mqtt was given. +if test ${enable_mqtt+y} +then : + enableval=$enable_mqtt; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_MQTT 1" >>confdefs.h + + CURL_DISABLE_MQTT=1 + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to provide built-in manual" >&5 +printf %s "checking whether to provide built-in manual... " >&6; } +# Check whether --enable-manual was given. +if test ${enable_manual+y} +then : + enableval=$enable_manual; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + USE_MANUAL="1" + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + USE_MANUAL="1" + +fi + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to build documentation" >&5 +printf %s "checking whether to build documentation... " >&6; } +# Check whether --enable-docs was given. +if test ${enable_docs+y} +then : + enableval=$enable_docs; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + BUILD_DOCS=0 + USE_MANUAL=0 + curl_docs_msg="no" + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + BUILD_DOCS=1 + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + BUILD_DOCS=1 + +fi + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable generation of C code" >&5 +printf %s "checking whether to enable generation of C code... " >&6; } +# Check whether --enable-libcurl_option was given. +if test ${enable_libcurl_option+y} +then : + enableval=$enable_libcurl_option; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_LIBCURL_OPTION 1" >>confdefs.h + + curl_libcurl_msg="no" + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to use libgcc" >&5 +printf %s "checking whether to use libgcc... " >&6; } +# Check whether --enable-libgcc was given. +if test ${enable_libgcc+y} +then : + enableval=$enable_libgcc; case "$enableval" in + yes) + LIBS="-lgcc $LIBS" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if X/Open network library is required" >&5 +printf %s "checking if X/Open network library is required... " >&6; } + tst_lib_xnet_required="no" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +int main (void) +{ +#if defined(__hpux) && defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE >= 600) + return 0; +#elif defined(__hpux) && defined(_XOPEN_SOURCE_EXTENDED) + return 0; +#else + force compilation error +#endif +} + + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + tst_lib_xnet_required="yes" + LIBS="-lxnet $LIBS" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tst_lib_xnet_required" >&5 +printf "%s\n" "$tst_lib_xnet_required" >&6; } + + +ac_fn_c_check_func "$LINENO" "gethostbyname" "ac_cv_func_gethostbyname" +if test "x$ac_cv_func_gethostbyname" = xyes +then : + HAVE_GETHOSTBYNAME="1" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for gethostbyname in -lnsl" >&5 +printf %s "checking for gethostbyname in -lnsl... " >&6; } +if test ${ac_cv_lib_nsl_gethostbyname+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lnsl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char gethostbyname (); +int main (void) +{ +return gethostbyname (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_nsl_gethostbyname=yes +else $as_nop + ac_cv_lib_nsl_gethostbyname=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_nsl_gethostbyname" >&5 +printf "%s\n" "$ac_cv_lib_nsl_gethostbyname" >&6; } +if test "x$ac_cv_lib_nsl_gethostbyname" = xyes +then : + HAVE_GETHOSTBYNAME="1" + LIBS="-lnsl $LIBS" + +fi + + +fi + + +if test "$HAVE_GETHOSTBYNAME" != "1" +then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for gethostbyname in -lsocket" >&5 +printf %s "checking for gethostbyname in -lsocket... " >&6; } +if test ${ac_cv_lib_socket_gethostbyname+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lsocket $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char gethostbyname (); +int main (void) +{ +return gethostbyname (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_socket_gethostbyname=yes +else $as_nop + ac_cv_lib_socket_gethostbyname=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_socket_gethostbyname" >&5 +printf "%s\n" "$ac_cv_lib_socket_gethostbyname" >&6; } +if test "x$ac_cv_lib_socket_gethostbyname" = xyes +then : + HAVE_GETHOSTBYNAME="1" + LIBS="-lsocket $LIBS" + +fi + +fi + +if test "$HAVE_GETHOSTBYNAME" != "1" +then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for gethostbyname in -lwatt" >&5 +printf %s "checking for gethostbyname in -lwatt... " >&6; } +if test ${ac_cv_lib_watt_gethostbyname+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lwatt $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char gethostbyname (); +int main (void) +{ +return gethostbyname (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_watt_gethostbyname=yes +else $as_nop + ac_cv_lib_watt_gethostbyname=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_watt_gethostbyname" >&5 +printf "%s\n" "$ac_cv_lib_watt_gethostbyname" >&6; } +if test "x$ac_cv_lib_watt_gethostbyname" = xyes +then : + HAVE_GETHOSTBYNAME="1" + CPPFLAGS="-I/dev/env/WATT_ROOT/inc" + LDFLAGS="-L/dev/env/WATT_ROOT/lib" + LIBS="-lwatt $LIBS" + +fi + +fi + +if test "$HAVE_GETHOSTBYNAME" != "1" +then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for gethostbyname with both nsl and socket libs" >&5 +printf %s "checking for gethostbyname with both nsl and socket libs... " >&6; } + my_ac_save_LIBS=$LIBS + LIBS="-lnsl -lsocket $LIBS" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + + gethostbyname(); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + HAVE_GETHOSTBYNAME="1" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + LIBS=$my_ac_save_LIBS + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +fi + +if test "$HAVE_GETHOSTBYNAME" != "1" +then + if test "$curl_cv_native_windows" = "yes"; then + winsock_LIB="-lws2_32" + if test ! -z "$winsock_LIB"; then + my_ac_save_LIBS=$LIBS + LIBS="$winsock_LIB $LIBS" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for gethostbyname in $winsock_LIB" >&5 +printf %s "checking for gethostbyname in $winsock_LIB... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#endif + +int main (void) +{ + + gethostbyname("localhost"); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + HAVE_GETHOSTBYNAME="1" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + winsock_LIB="" + LIBS=$my_ac_save_LIBS + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + fi + fi +fi + +if test "$HAVE_GETHOSTBYNAME" != "1" +then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for gethostbyname for Minix 3" >&5 +printf %s "checking for gethostbyname for Minix 3... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +/* Older Minix versions may need here instead */ +#include + +int main (void) +{ + + gethostbyname("localhost"); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + HAVE_GETHOSTBYNAME="1" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +fi + +if test "$HAVE_GETHOSTBYNAME" != "1" +then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for gethostbyname for eCos" >&5 +printf %s "checking for gethostbyname for eCos... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#include +#include + +int main (void) +{ + + gethostbyname("localhost"); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + HAVE_GETHOSTBYNAME="1" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +fi + +if test "$HAVE_GETHOSTBYNAME" != "1" -o "${with_amissl+set}" = set +then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for gethostbyname for AmigaOS bsdsocket.library" >&5 +printf %s "checking for gethostbyname for AmigaOS bsdsocket.library... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + #define __USE_INLINE__ + #include + #ifdef __amigaos4__ + struct SocketIFace *ISocket = NULL; + #else + struct Library *SocketBase = NULL; + #endif + +int main (void) +{ + + gethostbyname("localhost"); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + HAVE_GETHOSTBYNAME="1" + HAVE_PROTO_BSDSOCKET_H="1" + +printf "%s\n" "#define HAVE_PROTO_BSDSOCKET_H 1" >>confdefs.h + + HAVE_PROTO_BSDSOCKET_H=1 + + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +fi + +if test "$HAVE_GETHOSTBYNAME" != "1" +then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for gethostbyname in -lnetwork" >&5 +printf %s "checking for gethostbyname in -lnetwork... " >&6; } +if test ${ac_cv_lib_network_gethostbyname+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lnetwork $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char gethostbyname (); +int main (void) +{ +return gethostbyname (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_network_gethostbyname=yes +else $as_nop + ac_cv_lib_network_gethostbyname=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_network_gethostbyname" >&5 +printf "%s\n" "$ac_cv_lib_network_gethostbyname" >&6; } +if test "x$ac_cv_lib_network_gethostbyname" = xyes +then : + HAVE_GETHOSTBYNAME="1" + LIBS="-lnetwork $LIBS" + +fi + +fi + +if test "$HAVE_GETHOSTBYNAME" != "1"; then + as_fn_error $? "couldn't find libraries for gethostbyname()" "$LINENO" 5 +fi + + +curl_includes_winsock2="\ +/* includes start */ +#ifdef _WIN32 +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +#endif +/* includes end */" + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether build target is a native Windows one" >&5 +printf %s "checking whether build target is a native Windows one... " >&6; } +if test ${curl_cv_native_windows+y} +then : + printf %s "(cached) " >&6 +else $as_nop + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + +#ifdef _WIN32 + int dummy=1; +#else + Not a native Windows build target. +#endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + curl_cv_native_windows="yes" + +else $as_nop + + curl_cv_native_windows="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $curl_cv_native_windows" >&5 +printf "%s\n" "$curl_cv_native_windows" >&6; } + if test "x$curl_cv_native_windows" = xyes; then + DOING_NATIVE_WINDOWS_TRUE= + DOING_NATIVE_WINDOWS_FALSE='#' +else + DOING_NATIVE_WINDOWS_TRUE='#' + DOING_NATIVE_WINDOWS_FALSE= +fi + + + + +curl_includes_bsdsocket="\ +/* includes start */ +#if defined(HAVE_PROTO_BSDSOCKET_H) +# define __NO_NET_API +# define __USE_INLINE__ +# include +# ifdef HAVE_SYS_IOCTL_H +# include +# endif +# ifdef __amigaos4__ +struct SocketIFace *ISocket = NULL; +# else +struct Library *SocketBase = NULL; +# endif +# define select(a,b,c,d,e) WaitSelect(a,b,c,d,e,0) +#endif +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "proto/bsdsocket.h" "ac_cv_header_proto_bsdsocket_h" "$curl_includes_bsdsocket +" +if test "x$ac_cv_header_proto_bsdsocket_h" = xyes +then : + printf "%s\n" "#define HAVE_PROTO_BSDSOCKET_H 1" >>confdefs.h + +fi + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for connect in libraries" >&5 +printf %s "checking for connect in libraries... " >&6; } + tst_connect_save_LIBS="$LIBS" + tst_connect_need_LIBS="unknown" + for tst_lib in '' '-lsocket' ; do + if test "$tst_connect_need_LIBS" = "unknown"; then + LIBS="$tst_lib $tst_connect_save_LIBS" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + $curl_includes_bsdsocket + #if !defined(_WIN32) && !defined(HAVE_PROTO_BSDSOCKET_H) + int connect(int, void*, int); + #endif + +int main (void) +{ + + if(0 != connect(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + tst_connect_need_LIBS="$tst_lib" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + fi + done + LIBS="$tst_connect_save_LIBS" + # + case X-"$tst_connect_need_LIBS" in + X-unknown) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: cannot find connect" >&5 +printf "%s\n" "cannot find connect" >&6; } + as_fn_error $? "cannot find connect function in libraries." "$LINENO" 5 + ;; + X-) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + *) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tst_connect_need_LIBS" >&5 +printf "%s\n" "$tst_connect_need_LIBS" >&6; } + LIBS="$tst_connect_need_LIBS $tst_connect_save_LIBS" + ;; + esac + + +CURL_NETWORK_LIBS=$LIBS + + + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/time.h" "ac_cv_header_sys_time_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_time_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TIME_H 1" >>confdefs.h + +fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for monotonic clock_gettime" >&5 +printf %s "checking for monotonic clock_gettime... " >&6; } + # + if test "x$dontwant_rt" = "xno" ; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include + +int main (void) +{ + + struct timespec ts; + (void)clock_gettime(CLOCK_MONOTONIC, &ts); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + curl_func_clock_gettime="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_func_clock_gettime="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + + + # + if test "$curl_func_clock_gettime" = "yes"; then + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for clock_gettime in libraries" >&5 +printf %s "checking for clock_gettime in libraries... " >&6; } + # + curl_cv_save_LIBS="$LIBS" + curl_cv_gclk_LIBS="unknown" + # + for x_xlibs in '' '-lrt' '-lposix4' ; do + if test "$curl_cv_gclk_LIBS" = "unknown"; then + if test -z "$x_xlibs"; then + LIBS="$curl_cv_save_LIBS" + else + LIBS="$x_xlibs $curl_cv_save_LIBS" + fi + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include + +int main (void) +{ + + struct timespec ts; + (void)clock_gettime(CLOCK_MONOTONIC, &ts); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + curl_cv_gclk_LIBS="$x_xlibs" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + fi + done + # + LIBS="$curl_cv_save_LIBS" + # + case X-"$curl_cv_gclk_LIBS" in + X-unknown) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: cannot find clock_gettime" >&5 +printf "%s\n" "cannot find clock_gettime" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: HAVE_CLOCK_GETTIME_MONOTONIC will not be defined" >&5 +printf "%s\n" "$as_me: WARNING: HAVE_CLOCK_GETTIME_MONOTONIC will not be defined" >&2;} + curl_func_clock_gettime="no" + ;; + X-) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no additional lib required" >&5 +printf "%s\n" "no additional lib required" >&6; } + curl_func_clock_gettime="yes" + ;; + *) + if test -z "$curl_cv_save_LIBS"; then + LIBS="$curl_cv_gclk_LIBS" + else + LIBS="$curl_cv_gclk_LIBS $curl_cv_save_LIBS" + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $curl_cv_gclk_LIBS" >&5 +printf "%s\n" "$curl_cv_gclk_LIBS" >&6; } + curl_func_clock_gettime="yes" + ;; + esac + # + if test "x$cross_compiling" != "xyes" && + test "$curl_func_clock_gettime" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if monotonic clock_gettime works" >&5 +printf %s "checking if monotonic clock_gettime works... " >&6; } + + case $host_os in + darwin*) + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#include +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include + +int main (void) +{ + + struct timespec ts; + if (0 == clock_gettime(CLOCK_MONOTONIC, &ts)) + exit(0); + else + exit(1); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: HAVE_CLOCK_GETTIME_MONOTONIC will not be defined" >&5 +printf "%s\n" "$as_me: WARNING: HAVE_CLOCK_GETTIME_MONOTONIC will not be defined" >&2;} + curl_func_clock_gettime="no" + LIBS="$curl_cv_save_LIBS" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + ;; + *) + oldcc=$CC + old=$LD_LIBRARY_PATH + CC="sh ./run-compiler" + LD_LIBRARY_PATH=$CURL_LIBRARY_PATH:$old + export LD_LIBRARY_PATH + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#include +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include + +int main (void) +{ + + struct timespec ts; + if (0 == clock_gettime(CLOCK_MONOTONIC, &ts)) + exit(0); + else + exit(1); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: HAVE_CLOCK_GETTIME_MONOTONIC will not be defined" >&5 +printf "%s\n" "$as_me: WARNING: HAVE_CLOCK_GETTIME_MONOTONIC will not be defined" >&2;} + curl_func_clock_gettime="no" + LIBS="$curl_cv_save_LIBS" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LD_LIBRARY_PATH=$old # restore + CC=$oldcc + ;; + esac + + fi + # + case "$curl_func_clock_gettime" in + yes) + +printf "%s\n" "#define HAVE_CLOCK_GETTIME_MONOTONIC 1" >>confdefs.h + + ;; + esac + # + fi + # + + + + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/time.h" "ac_cv_header_sys_time_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_time_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TIME_H 1" >>confdefs.h + +fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for raw monotonic clock_gettime" >&5 +printf %s "checking for raw monotonic clock_gettime... " >&6; } + # + if test "x$dontwant_rt" = "xno" ; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include + +int main (void) +{ + + struct timespec ts; + (void)clock_gettime(CLOCK_MONOTONIC_RAW, &ts); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_CLOCK_GETTIME_MONOTONIC_RAW 1" >>confdefs.h + + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + + +CURL_NETWORK_AND_TIME_LIBS=$LIBS + + + +clean_CPPFLAGS=$CPPFLAGS +clean_LDFLAGS=$LDFLAGS +clean_LIBS=$LIBS +ZLIB_LIBS="" + +# Check whether --with-zlib was given. +if test ${with_zlib+y} +then : + withval=$with_zlib; OPT_ZLIB="$withval" +fi + + +if test "$OPT_ZLIB" = "no" ; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: zlib disabled" >&5 +printf "%s\n" "$as_me: WARNING: zlib disabled" >&2;} +else + if test "$OPT_ZLIB" = "yes" ; then + OPT_ZLIB="" + fi + + if test -z "$OPT_ZLIB" ; then + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for zlib options with pkg-config" >&5 +printf %s "checking for zlib options with pkg-config... " >&6; } + itexists=` + if test -n ""; then + PKG_CONFIG_LIBDIR="" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists zlib >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + ZLIB_LIBS="`$PKGCONFIG --libs-only-l zlib`" + if test -n "$ZLIB_LIBS"; then + LDFLAGS="$LDFLAGS `$PKGCONFIG --libs-only-L zlib`" + else + ZLIB_LIBS="`$PKGCONFIG --libs zlib`" + fi + LIBS="$ZLIB_LIBS $LIBS" + CPPFLAGS="$CPPFLAGS `$PKGCONFIG --cflags zlib`" + OPT_ZLIB="" + HAVE_LIBZ="1" + fi + + if test -z "$HAVE_LIBZ"; then + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for inflateEnd in -lz" >&5 +printf %s "checking for inflateEnd in -lz... " >&6; } +if test ${ac_cv_lib_z_inflateEnd+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lz $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char inflateEnd (); +int main (void) +{ +return inflateEnd (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_z_inflateEnd=yes +else $as_nop + ac_cv_lib_z_inflateEnd=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_z_inflateEnd" >&5 +printf "%s\n" "$ac_cv_lib_z_inflateEnd" >&6; } +if test "x$ac_cv_lib_z_inflateEnd" = xyes +then : + HAVE_LIBZ="1" + ZLIB_LIBS="-lz" + LIBS="$ZLIB_LIBS $LIBS" +else $as_nop + OPT_ZLIB="/usr/local" +fi + + fi + fi + + if test -n "$OPT_ZLIB"; then + CPPFLAGS="$CPPFLAGS -I$OPT_ZLIB/include" + LDFLAGS="$LDFLAGS -L$OPT_ZLIB/lib$libsuff" + fi + + ac_fn_c_check_header_compile "$LINENO" "zlib.h" "ac_cv_header_zlib_h" "$ac_includes_default" +if test "x$ac_cv_header_zlib_h" = xyes +then : + + HAVE_ZLIB_H="1" + if test "$HAVE_LIBZ" != "1"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for gzread in -lz" >&5 +printf %s "checking for gzread in -lz... " >&6; } +if test ${ac_cv_lib_z_gzread+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lz $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char gzread (); +int main (void) +{ +return gzread (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_z_gzread=yes +else $as_nop + ac_cv_lib_z_gzread=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_z_gzread" >&5 +printf "%s\n" "$ac_cv_lib_z_gzread" >&6; } +if test "x$ac_cv_lib_z_gzread" = xyes +then : + + HAVE_LIBZ="1" + ZLIB_LIBS="-lz" + LIBS="$ZLIB_LIBS $LIBS" + +else $as_nop + CPPFLAGS=$clean_CPPFLAGS + LDFLAGS=$clean_LDFLAGS +fi + + fi + +else $as_nop + + CPPFLAGS=$clean_CPPFLAGS + LDFLAGS=$clean_LDFLAGS + +fi + + + if test "$HAVE_LIBZ" = "1" && test "$HAVE_ZLIB_H" != "1" + then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: configure found only the libz lib, not the header file!" >&5 +printf "%s\n" "$as_me: WARNING: configure found only the libz lib, not the header file!" >&2;} + HAVE_LIBZ="" + CPPFLAGS=$clean_CPPFLAGS + LDFLAGS=$clean_LDFLAGS + LIBS=$clean_LIBS + ZLIB_LIBS="" + elif test "$HAVE_LIBZ" != "1" && test "$HAVE_ZLIB_H" = "1" + then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: configure found only the libz header file, not the lib!" >&5 +printf "%s\n" "$as_me: WARNING: configure found only the libz header file, not the lib!" >&2;} + CPPFLAGS=$clean_CPPFLAGS + LDFLAGS=$clean_LDFLAGS + LIBS=$clean_LIBS + ZLIB_LIBS="" + elif test "$HAVE_LIBZ" = "1" && test "$HAVE_ZLIB_H" = "1" + then + + +printf "%s\n" "#define HAVE_LIBZ 1" >>confdefs.h + + LIBS="$ZLIB_LIBS $clean_LIBS" + + AMFIXLIB="1" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: found both libz and libz.h header" >&5 +printf "%s\n" "$as_me: found both libz and libz.h header" >&6;} + curl_zlib_msg="enabled" + fi +fi + + if test x"$AMFIXLIB" = x1; then + HAVE_LIBZ_TRUE= + HAVE_LIBZ_FALSE='#' +else + HAVE_LIBZ_TRUE='#' + HAVE_LIBZ_FALSE= +fi + + + + + +OPT_BROTLI=off + +# Check whether --with-brotli was given. +if test ${with_brotli+y} +then : + withval=$with_brotli; OPT_BROTLI=$withval +fi + + +if test X"$OPT_BROTLI" != Xno; then + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_BROTLI" in + yes) + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libbrotlidec options with pkg-config" >&5 +printf %s "checking for libbrotlidec options with pkg-config... " >&6; } + itexists=` + if test -n ""; then + PKG_CONFIG_LIBDIR="" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists libbrotlidec >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + LIB_BROTLI=`$PKGCONFIG --libs-only-l libbrotlidec` + LD_BROTLI=`$PKGCONFIG --libs-only-L libbrotlidec` + CPP_BROTLI=`$PKGCONFIG --cflags-only-I libbrotlidec` + version=`$PKGCONFIG --modversion libbrotlidec` + DIR_BROTLI=`echo $LD_BROTLI | $SED -e 's/^-L//'` + fi + + ;; + off) + ;; + *) + PREFIX_BROTLI=$OPT_BROTLI + ;; + esac + + if test -n "$PREFIX_BROTLI"; then + LIB_BROTLI="-lbrotlidec" + LD_BROTLI=-L${PREFIX_BROTLI}/lib$libsuff + CPP_BROTLI=-I${PREFIX_BROTLI}/include + DIR_BROTLI=${PREFIX_BROTLI}/lib$libsuff + fi + + LDFLAGS="$LDFLAGS $LD_BROTLI" + CPPFLAGS="$CPPFLAGS $CPP_BROTLI" + LIBS="$LIB_BROTLI $LIBS" + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for BrotliDecoderDecompress in -lbrotlidec" >&5 +printf %s "checking for BrotliDecoderDecompress in -lbrotlidec... " >&6; } +if test ${ac_cv_lib_brotlidec_BrotliDecoderDecompress+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lbrotlidec $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char BrotliDecoderDecompress (); +int main (void) +{ +return BrotliDecoderDecompress (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_brotlidec_BrotliDecoderDecompress=yes +else $as_nop + ac_cv_lib_brotlidec_BrotliDecoderDecompress=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_brotlidec_BrotliDecoderDecompress" >&5 +printf "%s\n" "$ac_cv_lib_brotlidec_BrotliDecoderDecompress" >&6; } +if test "x$ac_cv_lib_brotlidec_BrotliDecoderDecompress" = xyes +then : + printf "%s\n" "#define HAVE_LIBBROTLIDEC 1" >>confdefs.h + + LIBS="-lbrotlidec $LIBS" + +fi + + + for ac_header in brotli/decode.h +do : + ac_fn_c_check_header_compile "$LINENO" "brotli/decode.h" "ac_cv_header_brotli_decode_h" "$ac_includes_default" +if test "x$ac_cv_header_brotli_decode_h" = xyes +then : + printf "%s\n" "#define HAVE_BROTLI_DECODE_H 1" >>confdefs.h + curl_brotli_msg="enabled (libbrotlidec)" + HAVE_BROTLI=1 + +printf "%s\n" "#define HAVE_BROTLI 1" >>confdefs.h + + HAVE_BROTLI=1 + + +fi + +done + + if test X"$OPT_BROTLI" != Xoff && + test "$HAVE_BROTLI" != "1"; then + as_fn_error $? "BROTLI libs and/or directories were not found where specified!" "$LINENO" 5 + fi + + if test "$HAVE_BROTLI" = "1"; then + if test -n "$DIR_BROTLI"; then + + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_BROTLI" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $DIR_BROTLI to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $DIR_BROTLI to CURL_LIBRARY_PATH" >&6;} + fi + fi + else + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + fi +fi + + +OPT_ZSTD=off + +# Check whether --with-zstd was given. +if test ${with_zstd+y} +then : + withval=$with_zstd; OPT_ZSTD=$withval +fi + + +if test X"$OPT_ZSTD" != Xno; then + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_ZSTD" in + yes) + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libzstd options with pkg-config" >&5 +printf %s "checking for libzstd options with pkg-config... " >&6; } + itexists=` + if test -n ""; then + PKG_CONFIG_LIBDIR="" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists libzstd >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + LIB_ZSTD=`$PKGCONFIG --libs-only-l libzstd` + LD_ZSTD=`$PKGCONFIG --libs-only-L libzstd` + CPP_ZSTD=`$PKGCONFIG --cflags-only-I libzstd` + version=`$PKGCONFIG --modversion libzstd` + DIR_ZSTD=`echo $LD_ZSTD | $SED -e 's/-L//'` + fi + + ;; + off) + ;; + *) + PREFIX_ZSTD=$OPT_ZSTD + ;; + esac + + if test -n "$PREFIX_ZSTD"; then + LIB_ZSTD="-lzstd" + LD_ZSTD=-L${PREFIX_ZSTD}/lib$libsuff + CPP_ZSTD=-I${PREFIX_ZSTD}/include + DIR_ZSTD=${PREFIX_ZSTD}/lib$libsuff + fi + + LDFLAGS="$LDFLAGS $LD_ZSTD" + CPPFLAGS="$CPPFLAGS $CPP_ZSTD" + LIBS="$LIB_ZSTD $LIBS" + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ZSTD_createDStream in -lzstd" >&5 +printf %s "checking for ZSTD_createDStream in -lzstd... " >&6; } +if test ${ac_cv_lib_zstd_ZSTD_createDStream+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lzstd $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char ZSTD_createDStream (); +int main (void) +{ +return ZSTD_createDStream (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_zstd_ZSTD_createDStream=yes +else $as_nop + ac_cv_lib_zstd_ZSTD_createDStream=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_zstd_ZSTD_createDStream" >&5 +printf "%s\n" "$ac_cv_lib_zstd_ZSTD_createDStream" >&6; } +if test "x$ac_cv_lib_zstd_ZSTD_createDStream" = xyes +then : + printf "%s\n" "#define HAVE_LIBZSTD 1" >>confdefs.h + + LIBS="-lzstd $LIBS" + +fi + + + for ac_header in zstd.h +do : + ac_fn_c_check_header_compile "$LINENO" "zstd.h" "ac_cv_header_zstd_h" "$ac_includes_default" +if test "x$ac_cv_header_zstd_h" = xyes +then : + printf "%s\n" "#define HAVE_ZSTD_H 1" >>confdefs.h + curl_zstd_msg="enabled (libzstd)" + HAVE_ZSTD=1 + +printf "%s\n" "#define HAVE_ZSTD 1" >>confdefs.h + + HAVE_ZSTD=1 + + +fi + +done + + if test X"$OPT_ZSTD" != Xoff && + test "$HAVE_ZSTD" != "1"; then + as_fn_error $? "libzstd was not found where specified!" "$LINENO" 5 + fi + + if test "$HAVE_ZSTD" = "1"; then + if test -n "$DIR_ZSTD"; then + + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_ZSTD" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $DIR_ZSTD to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $DIR_ZSTD to CURL_LIBRARY_PATH" >&6;} + fi + fi + else + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + fi +fi + + +LDAPLIBNAME="" + +# Check whether --with-ldap-lib was given. +if test ${with_ldap_lib+y} +then : + withval=$with_ldap_lib; LDAPLIBNAME="$withval" +fi + + +LBERLIBNAME="" + +# Check whether --with-lber-lib was given. +if test ${with_lber_lib+y} +then : + withval=$with_lber_lib; LBERLIBNAME="$withval" +fi + + +if test x$CURL_DISABLE_LDAP != x1 ; then + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for lber.h" >&5 +printf %s "checking for lber.h... " >&6; } +if test ${curl_cv_header_lber_h+y} +then : + printf %s "(cached) " >&6 +else $as_nop + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#endif +#ifndef NULL +#define NULL (void *)0 +#endif +#include + +int main (void) +{ + + BerValue *bvp = NULL; + BerElement *bep = ber_init(bvp); + ber_free(bep, 1); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + curl_cv_header_lber_h="yes" + +else $as_nop + + curl_cv_header_lber_h="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $curl_cv_header_lber_h" >&5 +printf "%s\n" "$curl_cv_header_lber_h" >&6; } + if test "$curl_cv_header_lber_h" = "yes"; then + +printf "%s\n" "#define HAVE_LBER_H 1" >>confdefs.h + + # + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#endif +#ifndef NULL +#define NULL (void *)0 +#endif +#ifndef LDAP_DEPRECATED +#define LDAP_DEPRECATED 1 +#endif +#include + +int main (void) +{ + + BerValue *bvp = NULL; + BerElement *bep = ber_init(bvp); + ber_free(bep, 1); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + curl_cv_need_header_lber_h="no" + +else $as_nop + + curl_cv_need_header_lber_h="yes" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + # + case "$curl_cv_need_header_lber_h" in + yes) + +printf "%s\n" "#define NEED_LBER_H 1" >>confdefs.h + + ;; + esac + fi + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ldap.h" >&5 +printf %s "checking for ldap.h... " >&6; } +if test ${curl_cv_header_ldap_h+y} +then : + printf %s "(cached) " >&6 +else $as_nop + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#endif +#ifndef LDAP_DEPRECATED +#define LDAP_DEPRECATED 1 +#endif +#ifdef NEED_LBER_H +#include +#endif +#include + +int main (void) +{ + + LDAP *ldp = ldap_init("0.0.0.0", LDAP_PORT); + int res = ldap_unbind(ldp); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + curl_cv_header_ldap_h="yes" + +else $as_nop + + curl_cv_header_ldap_h="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $curl_cv_header_ldap_h" >&5 +printf "%s\n" "$curl_cv_header_ldap_h" >&6; } + case "$curl_cv_header_ldap_h" in + yes) + +printf "%s\n" "#define HAVE_LDAP_H 1" >>confdefs.h + + ;; + esac + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ldap_ssl.h" >&5 +printf %s "checking for ldap_ssl.h... " >&6; } +if test ${curl_cv_header_ldap_ssl_h+y} +then : + printf %s "(cached) " >&6 +else $as_nop + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#endif +#ifndef LDAP_DEPRECATED +#define LDAP_DEPRECATED 1 +#endif +#ifdef NEED_LBER_H +#include +#endif +#ifdef HAVE_LDAP_H +#include +#endif +#include + +int main (void) +{ + + LDAP *ldp = ldapssl_init("0.0.0.0", LDAPS_PORT, 1); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + curl_cv_header_ldap_ssl_h="yes" + +else $as_nop + + curl_cv_header_ldap_ssl_h="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $curl_cv_header_ldap_ssl_h" >&5 +printf "%s\n" "$curl_cv_header_ldap_ssl_h" >&6; } + case "$curl_cv_header_ldap_ssl_h" in + yes) + +printf "%s\n" "#define HAVE_LDAP_SSL_H 1" >>confdefs.h + + ;; + esac + + + if test -z "$LDAPLIBNAME" ; then + if test "$curl_cv_native_windows" = "yes"; then + LDAPLIBNAME="wldap32" + LBERLIBNAME="no" + fi + fi + + if test "$LDAPLIBNAME" ; then + as_ac_Lib=`printf "%s\n" "ac_cv_lib_"$LDAPLIBNAME"""_ldap_init" | $as_tr_sh` +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ldap_init in -l\"$LDAPLIBNAME\"" >&5 +printf %s "checking for ldap_init in -l\"$LDAPLIBNAME\"... " >&6; } +if eval test \${$as_ac_Lib+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-l"$LDAPLIBNAME" $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char ldap_init (); +int main (void) +{ +return ldap_init (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + eval "$as_ac_Lib=yes" +else $as_nop + eval "$as_ac_Lib=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +eval ac_res=\$$as_ac_Lib + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +printf "%s\n" "$ac_res" >&6; } +if eval test \"x\$"$as_ac_Lib"\" = x"yes" +then : + cat >>confdefs.h <<_ACEOF +#define `printf "%s\n" "HAVE_LIB"$LDAPLIBNAME"" | $as_tr_cpp` 1 +_ACEOF + + LIBS="-l"$LDAPLIBNAME" $LIBS" + +else $as_nop + + if test -n "$ldap_askedfor"; then + as_fn_error $? "couldn't detect the LDAP libraries" "$LINENO" 5 + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: \"$LDAPLIBNAME\" is not an LDAP library: LDAP disabled" >&5 +printf "%s\n" "$as_me: WARNING: \"$LDAPLIBNAME\" is not an LDAP library: LDAP disabled" >&2;} + +printf "%s\n" "#define CURL_DISABLE_LDAP 1" >>confdefs.h + + CURL_DISABLE_LDAP=1 + + +printf "%s\n" "#define CURL_DISABLE_LDAPS 1" >>confdefs.h + + CURL_DISABLE_LDAPS=1 + +fi + + else + + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for LDAP libraries" >&5 +printf %s "checking for LDAP libraries... " >&6; } + # + u_libs="" + # + + # + curl_cv_save_LIBS="$LIBS" + curl_cv_ldap_LIBS="unknown" + # + for x_nlibs in '' "$u_libs" \ + '-lldap' \ + '-lldap -llber' \ + '-llber -lldap' \ + '-lldapssl -lldapx -lldapsdk' \ + '-lldapsdk -lldapx -lldapssl' \ + '-lldap -llber -lssl -lcrypto' ; do + + if test "$curl_cv_ldap_LIBS" = "unknown"; then + if test -z "$x_nlibs"; then + LIBS="$curl_cv_save_LIBS" + else + LIBS="$x_nlibs $curl_cv_save_LIBS" + fi + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#endif +#ifndef NULL +#define NULL (void *)0 +#endif +#ifndef LDAP_DEPRECATED +#define LDAP_DEPRECATED 1 +#endif +#ifdef NEED_LBER_H +#include +#endif +#ifdef HAVE_LDAP_H +#include +#endif + +int main (void) +{ + + BerValue *bvp = NULL; + BerElement *bep = ber_init(bvp); + LDAP *ldp = ldap_init("0.0.0.0", LDAP_PORT); + int res = ldap_unbind(ldp); + ber_free(bep, 1); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + curl_cv_ldap_LIBS="$x_nlibs" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + fi + done + # + LIBS="$curl_cv_save_LIBS" + # + case X-"$curl_cv_ldap_LIBS" in + X-unknown) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: cannot find LDAP libraries" >&5 +printf "%s\n" "cannot find LDAP libraries" >&6; } + ;; + X-) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no additional lib required" >&5 +printf "%s\n" "no additional lib required" >&6; } + ;; + *) + if test -z "$curl_cv_save_LIBS"; then + LIBS="$curl_cv_ldap_LIBS" + else + LIBS="$curl_cv_ldap_LIBS $curl_cv_save_LIBS" + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $curl_cv_ldap_LIBS" >&5 +printf "%s\n" "$curl_cv_ldap_LIBS" >&6; } + ;; + esac + # + + case X-"$curl_cv_ldap_LIBS" in + X-unknown) + if test -n "$ldap_askedfor"; then + as_fn_error $? "couldn't detect the LDAP libraries" "$LINENO" 5 + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: Cannot find libraries for LDAP support: LDAP disabled" >&5 +printf "%s\n" "$as_me: WARNING: Cannot find libraries for LDAP support: LDAP disabled" >&2;} + +printf "%s\n" "#define CURL_DISABLE_LDAP 1" >>confdefs.h + + CURL_DISABLE_LDAP=1 + + +printf "%s\n" "#define CURL_DISABLE_LDAPS 1" >>confdefs.h + + CURL_DISABLE_LDAPS=1 + + ;; + esac + fi +fi + +if test x$CURL_DISABLE_LDAP != x1 ; then + + if test "$LBERLIBNAME" ; then + if test "$LBERLIBNAME" != "no" ; then + as_ac_Lib=`printf "%s\n" "ac_cv_lib_"$LBERLIBNAME"""_ber_free" | $as_tr_sh` +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ber_free in -l\"$LBERLIBNAME\"" >&5 +printf %s "checking for ber_free in -l\"$LBERLIBNAME\"... " >&6; } +if eval test \${$as_ac_Lib+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-l"$LBERLIBNAME" $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char ber_free (); +int main (void) +{ +return ber_free (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + eval "$as_ac_Lib=yes" +else $as_nop + eval "$as_ac_Lib=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +eval ac_res=\$$as_ac_Lib + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +printf "%s\n" "$ac_res" >&6; } +if eval test \"x\$"$as_ac_Lib"\" = x"yes" +then : + cat >>confdefs.h <<_ACEOF +#define `printf "%s\n" "HAVE_LIB"$LBERLIBNAME"" | $as_tr_cpp` 1 +_ACEOF + + LIBS="-l"$LBERLIBNAME" $LIBS" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: \"$LBERLIBNAME\" is not an LBER library: LDAP disabled" >&5 +printf "%s\n" "$as_me: WARNING: \"$LBERLIBNAME\" is not an LBER library: LDAP disabled" >&2;} + +printf "%s\n" "#define CURL_DISABLE_LDAP 1" >>confdefs.h + + CURL_DISABLE_LDAP=1 + + +printf "%s\n" "#define CURL_DISABLE_LDAPS 1" >>confdefs.h + + CURL_DISABLE_LDAPS=1 + +fi + + fi + fi +fi + +if test x$CURL_DISABLE_LDAP != x1 ; then + ac_fn_c_check_func "$LINENO" "ldap_url_parse" "ac_cv_func_ldap_url_parse" +if test "x$ac_cv_func_ldap_url_parse" = xyes +then : + printf "%s\n" "#define HAVE_LDAP_URL_PARSE 1" >>confdefs.h + +fi +ac_fn_c_check_func "$LINENO" "ldap_init_fd" "ac_cv_func_ldap_init_fd" +if test "x$ac_cv_func_ldap_init_fd" = xyes +then : + printf "%s\n" "#define HAVE_LDAP_INIT_FD 1" >>confdefs.h + +fi + + + if test "$LDAPLIBNAME" = "wldap32"; then + curl_ldap_msg="enabled (winldap)" + +printf "%s\n" "#define USE_WIN32_LDAP 1" >>confdefs.h + + else + if test "x$ac_cv_func_ldap_init_fd" = "xyes"; then + curl_ldap_msg="enabled (OpenLDAP)" + +printf "%s\n" "#define USE_OPENLDAP 1" >>confdefs.h + + USE_OPENLDAP=1 + + else + curl_ldap_msg="enabled (ancient OpenLDAP)" + fi + fi +fi + +if test x$CURL_DISABLE_LDAPS != x1 ; then + curl_ldaps_msg="enabled" +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable IPv6" >&5 +printf %s "checking whether to enable IPv6... " >&6; } +# Check whether --enable-ipv6 was given. +if test ${enable_ipv6+y} +then : + enableval=$enable_ipv6; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ipv6=no + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ipv6=yes + ;; + esac +else $as_nop + if test "$cross_compiling" = yes +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ipv6=yes + +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* are AF_INET6 and sockaddr_in6 available? */ +#include +#ifdef _WIN32 +#include +#include +#else +#include +#include +#if defined (__TANDEM) +# include +#endif +#endif + +int main(void) +{ + struct sockaddr_in6 s; + (void)s; + return socket(AF_INET6, SOCK_STREAM, 0) < 0; +} + + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ipv6=yes +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ipv6=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi + + +if test "$ipv6" = yes; then + curl_ipv6_msg="enabled" + +printf "%s\n" "#define USE_IPV6 1" >>confdefs.h + + IPV6_ENABLED=1 + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if struct sockaddr_in6 has sin6_scope_id member" >&5 +printf %s "checking if struct sockaddr_in6 has sin6_scope_id member... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef _WIN32 +#include +#include +#else +#include +#if defined (__TANDEM) +# include +#endif +#endif + +int main (void) +{ + + struct sockaddr_in6 s; + s.sin6_scope_id = 0; + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1" >>confdefs.h + + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if argv can be written to" >&5 +printf %s "checking if argv can be written to... " >&6; } + + case $host_os in + darwin*) + if test "$cross_compiling" = yes +then : + curl_cv_writable_argv=cross + +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main(int argc, char **argv) +{ +#ifdef _WIN32 + /* on Windows, writing to the argv does not hide the argument in + process lists so it can just be skipped */ + (void)argc; + (void)argv; + return 1; +#else + (void)argc; + argv[0][0] = ' '; + return (argv[0][0] == ' ')?0:1; +#endif +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + curl_cv_writable_argv=yes + +else $as_nop + curl_cv_writable_argv=no + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + ;; + *) + oldcc=$CC + old=$LD_LIBRARY_PATH + CC="sh ./run-compiler" + LD_LIBRARY_PATH=$CURL_LIBRARY_PATH:$old + export LD_LIBRARY_PATH + if test "$cross_compiling" = yes +then : + curl_cv_writable_argv=cross + +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main(int argc, char **argv) +{ +#ifdef _WIN32 + /* on Windows, writing to the argv does not hide the argument in + process lists so it can just be skipped */ + (void)argc; + (void)argv; + return 1; +#else + (void)argc; + argv[0][0] = ' '; + return (argv[0][0] == ' ')?0:1; +#endif +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + curl_cv_writable_argv=yes + +else $as_nop + curl_cv_writable_argv=no + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LD_LIBRARY_PATH=$old # restore + CC=$oldcc + ;; + esac + +case $curl_cv_writable_argv in +yes) + +printf "%s\n" "#define HAVE_WRITABLE_ARGV 1" >>confdefs.h + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; +no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; +*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: the previous check could not be made default was used" >&5 +printf "%s\n" "$as_me: WARNING: the previous check could not be made default was used" >&2;} + ;; +esac + + + +GSSAPI_ROOT="/usr" + +# Check whether --with-gssapi-includes was given. +if test ${with_gssapi_includes+y} +then : + withval=$with_gssapi_includes; GSSAPI_INCS="-I$withval" + want_gss="yes" + +fi + + + +# Check whether --with-gssapi-libs was given. +if test ${with_gssapi_libs+y} +then : + withval=$with_gssapi_libs; GSSAPI_LIB_DIR="-L$withval" + want_gss="yes" + +fi + + + +# Check whether --with-gssapi was given. +if test ${with_gssapi+y} +then : + withval=$with_gssapi; + GSSAPI_ROOT="$withval" + if test x"$GSSAPI_ROOT" != xno; then + want_gss="yes" + if test x"$GSSAPI_ROOT" = xyes; then + GSSAPI_ROOT="/usr" + fi + fi + +fi + + +: ${KRB5CONFIG:="$GSSAPI_ROOT/bin/krb5-config"} + +save_CPPFLAGS="$CPPFLAGS" +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if GSS-API support is requested" >&5 +printf %s "checking if GSS-API support is requested... " >&6; } +if test x"$want_gss" = xyes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + + if test $GSSAPI_ROOT != "/usr"; then + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for mit-krb5-gssapi options with pkg-config" >&5 +printf %s "checking for mit-krb5-gssapi options with pkg-config... " >&6; } + itexists=` + if test -n "$GSSAPI_ROOT/lib/pkgconfig"; then + PKG_CONFIG_LIBDIR="$GSSAPI_ROOT/lib/pkgconfig" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists mit-krb5-gssapi >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + else + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for mit-krb5-gssapi options with pkg-config" >&5 +printf %s "checking for mit-krb5-gssapi options with pkg-config... " >&6; } + itexists=` + if test -n ""; then + PKG_CONFIG_LIBDIR="" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists mit-krb5-gssapi >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + fi + if test -z "$GSSAPI_INCS"; then + if test -n "$host_alias" -a -f "$GSSAPI_ROOT/bin/$host_alias-krb5-config"; then + GSSAPI_INCS=`$GSSAPI_ROOT/bin/$host_alias-krb5-config --cflags gssapi` + elif test "$PKGCONFIG" != "no" ; then + GSSAPI_INCS=`$PKGCONFIG --cflags mit-krb5-gssapi` + elif test -f "$KRB5CONFIG"; then + GSSAPI_INCS=`$KRB5CONFIG --cflags gssapi` + elif test "$GSSAPI_ROOT" != "yes"; then + GSSAPI_INCS="-I$GSSAPI_ROOT/include" + fi + fi + + CPPFLAGS="$CPPFLAGS $GSSAPI_INCS" + + ac_fn_c_check_header_compile "$LINENO" "gss.h" "ac_cv_header_gss_h" "$ac_includes_default" +if test "x$ac_cv_header_gss_h" = xyes +then : + + +printf "%s\n" "#define HAVE_GSSGNU 1" >>confdefs.h + + gnu_gss=yes + +else $as_nop + + for ac_header in gssapi/gssapi.h +do : + ac_fn_c_check_header_compile "$LINENO" "gssapi/gssapi.h" "ac_cv_header_gssapi_gssapi_h" "$ac_includes_default" +if test "x$ac_cv_header_gssapi_gssapi_h" = xyes +then : + printf "%s\n" "#define HAVE_GSSAPI_GSSAPI_H 1" >>confdefs.h + +else $as_nop + not_mit=1 +fi + +done + for ac_header in gssapi/gssapi_generic.h gssapi/gssapi_krb5.h +do : + as_ac_Header=`printf "%s\n" "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" " +$ac_includes_default +#ifdef HAVE_GSSAPI_GSSAPI_H +#include +#endif + +" +if eval test \"x\$"$as_ac_Header"\" = x"yes" +then : + cat >>confdefs.h <<_ACEOF +#define `printf "%s\n" "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +else $as_nop + not_mit=1 +fi + +done + if test "x$not_mit" = "x1"; then + ac_fn_c_check_header_compile "$LINENO" "gssapi.h" "ac_cv_header_gssapi_h" "$ac_includes_default" +if test "x$ac_cv_header_gssapi_h" = xyes +then : + +else $as_nop + + want_gss=no + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: disabling GSS-API support since no header files were found" >&5 +printf "%s\n" "$as_me: WARNING: disabling GSS-API support since no header files were found" >&2;} + + +fi + + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if GSS-API headers declare GSS_C_NT_HOSTBASED_SERVICE" >&5 +printf %s "checking if GSS-API headers declare GSS_C_NT_HOSTBASED_SERVICE... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#include +#include +#include + +int main (void) +{ + + gss_import_name( + (OM_uint32 *)0, + (gss_buffer_t)0, + GSS_C_NT_HOSTBASED_SERVICE, + (gss_name_t *)0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define HAVE_OLD_GSSMIT 1" >>confdefs.h + + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + + +fi + +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi +if test x"$want_gss" = xyes; then + +printf "%s\n" "#define HAVE_GSSAPI 1" >>confdefs.h + + HAVE_GSSAPI=1 + curl_gss_msg="enabled (MIT Kerberos/Heimdal)" + + if test -n "$gnu_gss"; then + curl_gss_msg="enabled (GNU GSS)" + LDFLAGS="$LDFLAGS $GSSAPI_LIB_DIR" + LIBS="-lgss $LIBS" + elif test -z "$GSSAPI_LIB_DIR"; then + case $host in + *-*-darwin*) + LIBS="-lgssapi_krb5 -lresolv $LIBS" + ;; + *) + if test $GSSAPI_ROOT != "/usr"; then + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for mit-krb5-gssapi options with pkg-config" >&5 +printf %s "checking for mit-krb5-gssapi options with pkg-config... " >&6; } + itexists=` + if test -n "$GSSAPI_ROOT/lib/pkgconfig"; then + PKG_CONFIG_LIBDIR="$GSSAPI_ROOT/lib/pkgconfig" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists mit-krb5-gssapi >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + else + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for mit-krb5-gssapi options with pkg-config" >&5 +printf %s "checking for mit-krb5-gssapi options with pkg-config... " >&6; } + itexists=` + if test -n ""; then + PKG_CONFIG_LIBDIR="" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists mit-krb5-gssapi >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + fi + if test -n "$host_alias" -a -f "$GSSAPI_ROOT/bin/$host_alias-krb5-config"; then + gss_libs=`$GSSAPI_ROOT/bin/$host_alias-krb5-config --libs gssapi` + LIBS="$gss_libs $LIBS" + elif test "$PKGCONFIG" != "no" ; then + gss_libs=`$PKGCONFIG --libs mit-krb5-gssapi` + LIBS="$gss_libs $LIBS" + elif test -f "$KRB5CONFIG"; then + gss_libs=`$KRB5CONFIG --libs gssapi` + LIBS="$gss_libs $LIBS" + else + case $host in + *-hp-hpux*) + gss_libname="gss" + ;; + *) + gss_libname="gssapi" + ;; + esac + + if test "$GSSAPI_ROOT" != "yes"; then + LDFLAGS="$LDFLAGS -L$GSSAPI_ROOT/lib$libsuff" + LIBS="-l$gss_libname $LIBS" + else + LIBS="-l$gss_libname $LIBS" + fi + fi + ;; + esac + else + LDFLAGS="$LDFLAGS $GSSAPI_LIB_DIR" + case $host in + *-hp-hpux*) + LIBS="-lgss $LIBS" + ;; + *) + LIBS="-lgssapi $LIBS" + ;; + esac + fi +else + CPPFLAGS="$save_CPPFLAGS" +fi + +if test x"$want_gss" = xyes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if we can link against GSS-API library" >&5 +printf %s "checking if we can link against GSS-API library... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define gss_init_sec_context innocuous_gss_init_sec_context +#ifdef __STDC__ +# include +#else +# include +#endif +#undef gss_init_sec_context +#ifdef __cplusplus +extern "C" +#endif +char gss_init_sec_context (); +#if defined __stub_gss_init_sec_context || defined __stub___gss_init_sec_context +choke me +#endif + +int main (void) +{ +return gss_init_sec_context (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + as_fn_error $? "--with-gssapi was specified, but a GSS-API library was not found." "$LINENO" 5 + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +fi + +build_libstubgss=no +if test x"$want_gss" = "xyes"; then + build_libstubgss=yes +fi + + if test "x$build_libstubgss" = "xyes"; then + BUILD_STUB_GSS_TRUE= + BUILD_STUB_GSS_FALSE='#' +else + BUILD_STUB_GSS_TRUE='#' + BUILD_STUB_GSS_FALSE= +fi + + + +DEFAULT_SSL_BACKEND=no +VALID_DEFAULT_SSL_BACKEND= + +# Check whether --with-default-ssl-backend was given. +if test ${with_default_ssl_backend+y} +then : + withval=$with_default_ssl_backend; DEFAULT_SSL_BACKEND=$withval +fi + +case "$DEFAULT_SSL_BACKEND" in + no) + ;; + default|yes) + as_fn_error $? "The name of the default SSL backend is required." "$LINENO" 5 + ;; + *) + + VALID_DEFAULT_SSL_BACKEND=no + ;; +esac + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable Windows native SSL/TLS" >&5 +printf %s "checking whether to enable Windows native SSL/TLS... " >&6; } +if test "x$OPT_SCHANNEL" != xno; then + ssl_msg= + if test "x$OPT_SCHANNEL" != "xno" && + test "x$curl_cv_native_windows" = "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define USE_SCHANNEL 1" >>confdefs.h + + USE_SCHANNEL=1 + + ssl_msg="Schannel" + test schannel != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + SCHANNEL_ENABLED=1 + # --with-schannel implies --enable-sspi + +printf "%s\n" "#define USE_WINDOWS_SSPI 1" >>confdefs.h + + USE_WINDOWS_SSPI=1 + + curl_sspi_msg="enabled" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable Secure Transport" >&5 +printf %s "checking whether to enable Secure Transport... " >&6; } +if test "x$OPT_SECURETRANSPORT" != xno; then + if test "x$OPT_SECURETRANSPORT" != "xno" && + (test "x$cross_compiling" != "xno" || test -d "/System/Library/Frameworks/Security.framework"); then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define USE_SECTRANSP 1" >>confdefs.h + + USE_SECTRANSP=1 + + ssl_msg="Secure Transport" + test secure-transport != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + SECURETRANSPORT_ENABLED=1 + LDFLAGS="$LDFLAGS -framework CoreFoundation -framework CoreServices -framework Security" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable Amiga native SSL/TLS (AmiSSL v5)" >&5 +printf %s "checking whether to enable Amiga native SSL/TLS (AmiSSL v5)... " >&6; } +if test "$HAVE_PROTO_BSDSOCKET_H" = "1"; then + if test "x$OPT_AMISSL" != xno; then + ssl_msg= + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + #include + #include + +int main (void) +{ + + #if defined(AMISSL_CURRENT_VERSION) && defined(AMISSL_V3xx) && \ + (OPENSSL_VERSION_NUMBER >= 0x30000000L) && \ + defined(PROTO_AMISSL_H) + return 0; + #else + #error not AmiSSL v5 / OpenSSL 3 + #endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ssl_msg="AmiSSL" + test amissl != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + AMISSL_ENABLED=1 + OPENSSL_ENABLED=1 + # Use AmiSSL's built-in ca bundle + check_for_ca_bundle=1 + with_ca_fallback=yes + LIBS="-lamisslstubs -lamisslauto $LIBS" + +printf "%s\n" "#define USE_AMISSL 1" >>confdefs.h + + +printf "%s\n" "#define USE_OPENSSL 1" >>confdefs.h + + +printf "%s\n" "#define HAVE_OPENSSL3 1" >>confdefs.h + + ac_fn_c_check_header_compile "$LINENO" "openssl/x509.h" "ac_cv_header_openssl_x509_h" "$ac_includes_default" +if test "x$ac_cv_header_openssl_x509_h" = xyes +then : + printf "%s\n" "#define HAVE_OPENSSL_X509_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "openssl/rsa.h" "ac_cv_header_openssl_rsa_h" "$ac_includes_default" +if test "x$ac_cv_header_openssl_rsa_h" = xyes +then : + printf "%s\n" "#define HAVE_OPENSSL_RSA_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "openssl/crypto.h" "ac_cv_header_openssl_crypto_h" "$ac_includes_default" +if test "x$ac_cv_header_openssl_crypto_h" = xyes +then : + printf "%s\n" "#define HAVE_OPENSSL_CRYPTO_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "openssl/pem.h" "ac_cv_header_openssl_pem_h" "$ac_includes_default" +if test "x$ac_cv_header_openssl_pem_h" = xyes +then : + printf "%s\n" "#define HAVE_OPENSSL_PEM_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "openssl/ssl.h" "ac_cv_header_openssl_ssl_h" "$ac_includes_default" +if test "x$ac_cv_header_openssl_ssl_h" = xyes +then : + printf "%s\n" "#define HAVE_OPENSSL_SSL_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "openssl/err.h" "ac_cv_header_openssl_err_h" "$ac_includes_default" +if test "x$ac_cv_header_openssl_err_h" = xyes +then : + printf "%s\n" "#define HAVE_OPENSSL_ERR_H 1" >>confdefs.h + +fi + + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + +if test "x$OPT_OPENSSL" != xno; then + ssl_msg= + + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case $host in + *-*-msys* | *-*-mingw*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for gdi32" >&5 +printf %s "checking for gdi32... " >&6; } + my_ac_save_LIBS=$LIBS + LIBS="-lgdi32 $LIBS" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + #include + #include + +int main (void) +{ + + GdiFlush(); + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } +else $as_nop + LIBS=$my_ac_save_LIBS + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + ;; + esac + + case "$OPT_OPENSSL" in + yes) + PKGTEST="yes" + PREFIX_OPENSSL= + ;; + *) + PKGTEST="no" + PREFIX_OPENSSL=$OPT_OPENSSL + + OPENSSL_PCDIR="$OPT_OPENSSL/lib/pkgconfig" + if test -f "$OPENSSL_PCDIR/openssl.pc"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: PKG_CONFIG_LIBDIR will be set to \"$OPENSSL_PCDIR\"" >&5 +printf "%s\n" "$as_me: PKG_CONFIG_LIBDIR will be set to \"$OPENSSL_PCDIR\"" >&6;} + PKGTEST="yes" + fi + + if test "$PKGTEST" != "yes"; then + # try lib64 instead + OPENSSL_PCDIR="$OPT_OPENSSL/lib64/pkgconfig" + if test -f "$OPENSSL_PCDIR/openssl.pc"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: PKG_CONFIG_LIBDIR will be set to \"$OPENSSL_PCDIR\"" >&5 +printf "%s\n" "$as_me: PKG_CONFIG_LIBDIR will be set to \"$OPENSSL_PCDIR\"" >&6;} + PKGTEST="yes" + fi + fi + + if test "$PKGTEST" != "yes"; then + if test ! -f "$PREFIX_OPENSSL/include/openssl/ssl.h"; then + as_fn_error $? "$PREFIX_OPENSSL is a bad --with-openssl prefix!" "$LINENO" 5 + fi + fi + + LIB_OPENSSL="$PREFIX_OPENSSL/lib$libsuff" + if test "$PREFIX_OPENSSL" != "/usr" ; then + SSL_LDFLAGS="-L$LIB_OPENSSL" + SSL_CPPFLAGS="-I$PREFIX_OPENSSL/include" + fi + ;; + esac + + if test "$PKGTEST" = "yes"; then + + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for openssl options with pkg-config" >&5 +printf %s "checking for openssl options with pkg-config... " >&6; } + itexists=` + if test -n "$OPENSSL_PCDIR"; then + PKG_CONFIG_LIBDIR="$OPENSSL_PCDIR" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists openssl >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + SSL_LIBS=` + if test -n "$OPENSSL_PCDIR"; then + PKG_CONFIG_LIBDIR="$OPENSSL_PCDIR" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --libs-only-l --libs-only-other openssl 2>/dev/null` + + SSL_LDFLAGS=` + if test -n "$OPENSSL_PCDIR"; then + PKG_CONFIG_LIBDIR="$OPENSSL_PCDIR" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --libs-only-L openssl 2>/dev/null` + + SSL_CPPFLAGS=` + if test -n "$OPENSSL_PCDIR"; then + PKG_CONFIG_LIBDIR="$OPENSSL_PCDIR" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --cflags-only-I openssl 2>/dev/null` + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: pkg-config: SSL_LIBS: \"$SSL_LIBS\"" >&5 +printf "%s\n" "$as_me: pkg-config: SSL_LIBS: \"$SSL_LIBS\"" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: pkg-config: SSL_LDFLAGS: \"$SSL_LDFLAGS\"" >&5 +printf "%s\n" "$as_me: pkg-config: SSL_LDFLAGS: \"$SSL_LDFLAGS\"" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: pkg-config: SSL_CPPFLAGS: \"$SSL_CPPFLAGS\"" >&5 +printf "%s\n" "$as_me: pkg-config: SSL_CPPFLAGS: \"$SSL_CPPFLAGS\"" >&6;} + + LIB_OPENSSL=`echo $SSL_LDFLAGS | sed -e 's/^-L//'` + + LIBS="$SSL_LIBS $LIBS" + fi + fi + + CPPFLAGS="$CPPFLAGS $SSL_CPPFLAGS" + LDFLAGS="$LDFLAGS $SSL_LDFLAGS" + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for HMAC_Update in -lcrypto" >&5 +printf %s "checking for HMAC_Update in -lcrypto... " >&6; } +if test ${ac_cv_lib_crypto_HMAC_Update+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lcrypto $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char HMAC_Update (); +int main (void) +{ +return HMAC_Update (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_crypto_HMAC_Update=yes +else $as_nop + ac_cv_lib_crypto_HMAC_Update=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_crypto_HMAC_Update" >&5 +printf "%s\n" "$ac_cv_lib_crypto_HMAC_Update" >&6; } +if test "x$ac_cv_lib_crypto_HMAC_Update" = xyes +then : + + HAVECRYPTO="yes" + LIBS="-lcrypto $LIBS" + +else $as_nop + + if test -n "$LIB_OPENSSL" ; then + LDFLAGS="$CLEANLDFLAGS -L$LIB_OPENSSL" + fi + if test "$PKGCONFIG" = "no" -a -n "$PREFIX_OPENSSL" ; then + # only set this if pkg-config wasn't used + CPPFLAGS="$CLEANCPPFLAGS -I$PREFIX_OPENSSL/include" + fi + # Linking previously failed, try extra paths from --with-openssl or + # pkg-config. Use a different function name to avoid reusing the earlier + # cached result. + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for HMAC_Init_ex in -lcrypto" >&5 +printf %s "checking for HMAC_Init_ex in -lcrypto... " >&6; } +if test ${ac_cv_lib_crypto_HMAC_Init_ex+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lcrypto $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char HMAC_Init_ex (); +int main (void) +{ +return HMAC_Init_ex (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_crypto_HMAC_Init_ex=yes +else $as_nop + ac_cv_lib_crypto_HMAC_Init_ex=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_crypto_HMAC_Init_ex" >&5 +printf "%s\n" "$ac_cv_lib_crypto_HMAC_Init_ex" >&6; } +if test "x$ac_cv_lib_crypto_HMAC_Init_ex" = xyes +then : + + HAVECRYPTO="yes" + LIBS="-lcrypto $LIBS" +else $as_nop + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking OpenSSL linking with -ldl" >&5 +printf %s "checking OpenSSL linking with -ldl... " >&6; } + LIBS="-lcrypto $CLEANLIBS -ldl" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + #include + +int main (void) +{ + + ERR_clear_error(); + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + HAVECRYPTO="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking OpenSSL linking with -ldl and -lpthread" >&5 +printf %s "checking OpenSSL linking with -ldl and -lpthread... " >&6; } + LIBS="-lcrypto $CLEANLIBS -ldl -lpthread" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + #include + +int main (void) +{ + + ERR_clear_error(); + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + HAVECRYPTO="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + LDFLAGS="$CLEANLDFLAGS" + CPPFLAGS="$CLEANCPPFLAGS" + LIBS="$CLEANLIBS" + + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + + +fi + + +fi + + + if test X"$HAVECRYPTO" = X"yes"; then + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for SSL_connect in -lssl" >&5 +printf %s "checking for SSL_connect in -lssl... " >&6; } +if test ${ac_cv_lib_ssl_SSL_connect+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lssl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char SSL_connect (); +int main (void) +{ +return SSL_connect (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_ssl_SSL_connect=yes +else $as_nop + ac_cv_lib_ssl_SSL_connect=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ssl_SSL_connect" >&5 +printf "%s\n" "$ac_cv_lib_ssl_SSL_connect" >&6; } +if test "x$ac_cv_lib_ssl_SSL_connect" = xyes +then : + printf "%s\n" "#define HAVE_LIBSSL 1" >>confdefs.h + + LIBS="-lssl $LIBS" + +fi + + + if test "$ac_cv_lib_ssl_SSL_connect" != yes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ssl with RSAglue/rsaref libs in use" >&5 +printf %s "checking for ssl with RSAglue/rsaref libs in use... " >&6; }; + OLIBS=$LIBS + LIBS="-lRSAglue -lrsaref $LIBS" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for SSL_connect in -lssl" >&5 +printf %s "checking for SSL_connect in -lssl... " >&6; } +if test ${ac_cv_lib_ssl_SSL_connect+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lssl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char SSL_connect (); +int main (void) +{ +return SSL_connect (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_ssl_SSL_connect=yes +else $as_nop + ac_cv_lib_ssl_SSL_connect=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ssl_SSL_connect" >&5 +printf "%s\n" "$ac_cv_lib_ssl_SSL_connect" >&6; } +if test "x$ac_cv_lib_ssl_SSL_connect" = xyes +then : + printf "%s\n" "#define HAVE_LIBSSL 1" >>confdefs.h + + LIBS="-lssl $LIBS" + +fi + + if test "$ac_cv_lib_ssl_SSL_connect" != yes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + LIBS=$OLIBS + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + fi + + else + + for ac_header in openssl/x509.h openssl/rsa.h openssl/crypto.h openssl/pem.h openssl/ssl.h openssl/err.h +do : + as_ac_Header=`printf "%s\n" "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes" +then : + cat >>confdefs.h <<_ACEOF +#define `printf "%s\n" "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + ssl_msg="OpenSSL" + test openssl != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + OPENSSL_ENABLED=1 + +printf "%s\n" "#define USE_OPENSSL 1" >>confdefs.h + +fi + +done + + if test $ac_cv_header_openssl_x509_h = no; then + ac_fn_c_check_header_compile "$LINENO" "x509.h" "ac_cv_header_x509_h" "$ac_includes_default" +if test "x$ac_cv_header_x509_h" = xyes +then : + printf "%s\n" "#define HAVE_X509_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "rsa.h" "ac_cv_header_rsa_h" "$ac_includes_default" +if test "x$ac_cv_header_rsa_h" = xyes +then : + printf "%s\n" "#define HAVE_RSA_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "crypto.h" "ac_cv_header_crypto_h" "$ac_includes_default" +if test "x$ac_cv_header_crypto_h" = xyes +then : + printf "%s\n" "#define HAVE_CRYPTO_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "pem.h" "ac_cv_header_pem_h" "$ac_includes_default" +if test "x$ac_cv_header_pem_h" = xyes +then : + printf "%s\n" "#define HAVE_PEM_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "ssl.h" "ac_cv_header_ssl_h" "$ac_includes_default" +if test "x$ac_cv_header_ssl_h" = xyes +then : + printf "%s\n" "#define HAVE_SSL_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "err.h" "ac_cv_header_err_h" "$ac_includes_default" +if test "x$ac_cv_header_err_h" = xyes +then : + printf "%s\n" "#define HAVE_ERR_H 1" >>confdefs.h + +fi + + + if test $ac_cv_header_x509_h = yes && + test $ac_cv_header_crypto_h = yes && + test $ac_cv_header_ssl_h = yes; then + ssl_msg="OpenSSL" + OPENSSL_ENABLED=1 + fi + fi + fi + + if test X"$OPENSSL_ENABLED" != X"1"; then + LIBS="$CLEANLIBS" + fi + + if test X"$OPT_OPENSSL" != Xoff && + test "$OPENSSL_ENABLED" != "1"; then + as_fn_error $? "OpenSSL libs and/or directories were not found where specified!" "$LINENO" 5 + fi + fi + + if test X"$OPENSSL_ENABLED" = X"1"; then + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for BoringSSL" >&5 +printf %s "checking for BoringSSL... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + #include + +int main (void) +{ + + #ifndef OPENSSL_IS_BORINGSSL + #error not boringssl + #endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ssl_msg="BoringSSL" + OPENSSL_IS_BORINGSSL=1 + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for AWS-LC" >&5 +printf %s "checking for AWS-LC... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + #include + +int main (void) +{ + + #ifndef OPENSSL_IS_AWSLC + #error not AWS-LC + #endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ssl_msg="AWS-LC" + OPENSSL_IS_BORINGSSL=1 + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libressl" >&5 +printf %s "checking for libressl... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#include + +int main (void) +{ + + int dummy = LIBRESSL_VERSION_NUMBER; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_LIBRESSL 1" >>confdefs.h + + ssl_msg="libressl" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for OpenSSL >= v3" >&5 +printf %s "checking for OpenSSL >= v3... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#include + +int main (void) +{ + + #if (OPENSSL_VERSION_NUMBER >= 0x30000000L) + return 0; + #else + #error older than 3 + #endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_OPENSSL3 1" >>confdefs.h + + ssl_msg="OpenSSL v3+" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + + + for ac_func in SSL_set_quic_use_legacy_codepoint +do : + ac_fn_c_check_func "$LINENO" "SSL_set_quic_use_legacy_codepoint" "ac_cv_func_SSL_set_quic_use_legacy_codepoint" +if test "x$ac_cv_func_SSL_set_quic_use_legacy_codepoint" = xyes +then : + printf "%s\n" "#define HAVE_SSL_SET_QUIC_USE_LEGACY_CODEPOINT 1" >>confdefs.h + QUIC_ENABLED=yes +fi + +done + if test "$QUIC_ENABLED" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: OpenSSL fork speaks QUIC API" >&5 +printf "%s\n" "$as_me: OpenSSL fork speaks QUIC API" >&6;} + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: OpenSSL version does not speak QUIC API" >&5 +printf "%s\n" "$as_me: OpenSSL version does not speak QUIC API" >&6;} + fi + + if test "$OPENSSL_ENABLED" = "1"; then + if test -n "$LIB_OPENSSL"; then + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$LIB_OPENSSL" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $LIB_OPENSSL to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $LIB_OPENSSL to CURL_LIBRARY_PATH" >&6;} + fi + fi + check_for_ca_bundle=1 + fi + + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" +fi + +if test X"$OPT_OPENSSL" != Xno && + test "$OPENSSL_ENABLED" != "1"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: OPT_OPENSSL: $OPT_OPENSSL" >&5 +printf "%s\n" "$as_me: OPT_OPENSSL: $OPT_OPENSSL" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: OPENSSL_ENABLED: $OPENSSL_ENABLED" >&5 +printf "%s\n" "$as_me: OPENSSL_ENABLED: $OPENSSL_ENABLED" >&6;} + as_fn_error $? "--with-openssl was given but OpenSSL could not be detected" "$LINENO" 5 +fi + + +if test X"$OPENSSL_ENABLED" = X"1"; then + +# Check whether --with-random was given. +if test ${with_random+y} +then : + withval=$with_random; RANDOM_FILE="$withval" +else $as_nop + + if test x$cross_compiling != xyes; then + as_ac_File=`printf "%s\n" "ac_cv_file_"/dev/urandom"" | $as_tr_sh` +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for \"/dev/urandom\"" >&5 +printf %s "checking for \"/dev/urandom\"... " >&6; } +if eval test \${$as_ac_File+y} +then : + printf %s "(cached) " >&6 +else $as_nop + test "$cross_compiling" = yes && + as_fn_error $? "cannot check for file existence when cross compiling" "$LINENO" 5 +if test -r ""/dev/urandom""; then + eval "$as_ac_File=yes" +else + eval "$as_ac_File=no" +fi +fi +eval ac_res=\$$as_ac_File + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +printf "%s\n" "$ac_res" >&6; } +if eval test \"x\$"$as_ac_File"\" = x"yes" +then : + RANDOM_FILE="/dev/urandom" +fi + + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: skipped the /dev/urandom detection when cross-compiling" >&5 +printf "%s\n" "$as_me: WARNING: skipped the /dev/urandom detection when cross-compiling" >&2;} + fi + + +fi + + if test -n "$RANDOM_FILE" && test X"$RANDOM_FILE" != Xno ; then + + +printf "%s\n" "#define RANDOM_FILE \"$RANDOM_FILE\"" >>confdefs.h + + fi +fi + +if test "$OPENSSL_ENABLED" = "1"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for SRP support in OpenSSL" >&5 +printf %s "checking for SRP support in OpenSSL... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#include + +int main (void) +{ + + SSL_CTX_set_srp_username(NULL, ""); + SSL_CTX_set_srp_password(NULL, ""); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_OPENSSL_SRP 1" >>confdefs.h + + HAVE_OPENSSL_SRP=1 + + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +fi + +if test X"$OPENSSL_ENABLED" = X"1"; then +# Check whether --enable-openssl-auto-load-config was given. +if test ${enable_openssl_auto_load_config+y} +then : + enableval=$enable_openssl_auto_load_config; if test X"$enableval" = X"no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: automatic loading of OpenSSL configuration disabled" >&5 +printf "%s\n" "$as_me: automatic loading of OpenSSL configuration disabled" >&6;} + +printf "%s\n" "#define CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG 1" >>confdefs.h + + fi + +fi + +fi + +if test "$OPENSSL_ENABLED" = "1"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for QUIC support in OpenSSL" >&5 +printf %s "checking for QUIC support in OpenSSL... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#include + +int main (void) +{ + + OSSL_QUIC_client_method(); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_OPENSSL_QUIC 1" >>confdefs.h + + HAVE_OPENSSL_QUIC=1 + + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +fi + + +if test "x$OPT_GNUTLS" != xno; then + ssl_msg= + + if test X"$OPT_GNUTLS" != Xno; then + + addld="" + addlib="" + gtlslib="" + version="" + addcflags="" + + if test "x$OPT_GNUTLS" = "xyes"; then + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for gnutls options with pkg-config" >&5 +printf %s "checking for gnutls options with pkg-config... " >&6; } + itexists=` + if test -n ""; then + PKG_CONFIG_LIBDIR="" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists gnutls >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + addlib=`$PKGCONFIG --libs-only-l gnutls` + addld=`$PKGCONFIG --libs-only-L gnutls` + addcflags=`$PKGCONFIG --cflags-only-I gnutls` + version=`$PKGCONFIG --modversion gnutls` + gtlslib=`echo $addld | $SED -e 's/^-L//'` + else + check=`libgnutls-config --version 2>/dev/null` + if test -n "$check"; then + addlib=`libgnutls-config --libs` + addcflags=`libgnutls-config --cflags` + version=`libgnutls-config --version` + gtlslib=`libgnutls-config --prefix`/lib$libsuff + fi + fi + else + cfg=$OPT_GNUTLS/bin/libgnutls-config + check=`$cfg --version 2>/dev/null` + if test -n "$check"; then + addlib=`$cfg --libs` + addcflags=`$cfg --cflags` + version=`$cfg --version` + gtlslib=`$cfg --prefix`/lib$libsuff + else + addlib=-lgnutls + addld=-L$OPT_GNUTLS/lib$libsuff + addcflags=-I$OPT_GNUTLS/include + version="" # we just don't know + gtlslib=$OPT_GNUTLS/lib$libsuff + fi + fi + + if test -z "$version"; then + version="unknown" + fi + + if test -n "$addlib"; then + + CLEANLIBS="$LIBS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLDFLAGS="$LDFLAGS" + + LIBS="$addlib $LIBS" + LDFLAGS="$LDFLAGS $addld" + if test "$addcflags" != "-I/usr/include"; then + CPPFLAGS="$CPPFLAGS $addcflags" + fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for gnutls_x509_crt_get_dn2 in -lgnutls" >&5 +printf %s "checking for gnutls_x509_crt_get_dn2 in -lgnutls... " >&6; } +if test ${ac_cv_lib_gnutls_gnutls_x509_crt_get_dn2+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lgnutls $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char gnutls_x509_crt_get_dn2 (); +int main (void) +{ +return gnutls_x509_crt_get_dn2 (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_gnutls_gnutls_x509_crt_get_dn2=yes +else $as_nop + ac_cv_lib_gnutls_gnutls_x509_crt_get_dn2=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gnutls_gnutls_x509_crt_get_dn2" >&5 +printf "%s\n" "$ac_cv_lib_gnutls_gnutls_x509_crt_get_dn2" >&6; } +if test "x$ac_cv_lib_gnutls_gnutls_x509_crt_get_dn2" = xyes +then : + + +printf "%s\n" "#define USE_GNUTLS 1" >>confdefs.h + + USE_GNUTLS=1 + + GNUTLS_ENABLED=1 + USE_GNUTLS="yes" + ssl_msg="GnuTLS" + QUIC_ENABLED=yes + test gnutls != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + +else $as_nop + + LIBS="$CLEANLIBS" + CPPFLAGS="$CLEANCPPFLAGS" + +fi + + + if test "x$USE_GNUTLS" = "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: detected GnuTLS version $version" >&5 +printf "%s\n" "$as_me: detected GnuTLS version $version" >&6;} + check_for_ca_bundle=1 + if test -n "$gtlslib"; then + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$gtlslib" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $gtlslib to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $gtlslib to CURL_LIBRARY_PATH" >&6;} + fi + fi + fi + + fi + + fi + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" +fi + + +if test "$GNUTLS_ENABLED" = "1"; then + USE_GNUTLS_NETTLE= + # First check if we can detect either crypto library via transitive linking + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for nettle_MD5Init in -lgnutls" >&5 +printf %s "checking for nettle_MD5Init in -lgnutls... " >&6; } +if test ${ac_cv_lib_gnutls_nettle_MD5Init+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lgnutls $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char nettle_MD5Init (); +int main (void) +{ +return nettle_MD5Init (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_gnutls_nettle_MD5Init=yes +else $as_nop + ac_cv_lib_gnutls_nettle_MD5Init=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gnutls_nettle_MD5Init" >&5 +printf "%s\n" "$ac_cv_lib_gnutls_nettle_MD5Init" >&6; } +if test "x$ac_cv_lib_gnutls_nettle_MD5Init" = xyes +then : + USE_GNUTLS_NETTLE=1 +fi + + + # If not, try linking directly to both of them to see if they are available + if test "$USE_GNUTLS_NETTLE" = ""; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for nettle_MD5Init in -lnettle" >&5 +printf %s "checking for nettle_MD5Init in -lnettle... " >&6; } +if test ${ac_cv_lib_nettle_nettle_MD5Init+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lnettle $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char nettle_MD5Init (); +int main (void) +{ +return nettle_MD5Init (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_nettle_nettle_MD5Init=yes +else $as_nop + ac_cv_lib_nettle_nettle_MD5Init=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_nettle_nettle_MD5Init" >&5 +printf "%s\n" "$ac_cv_lib_nettle_nettle_MD5Init" >&6; } +if test "x$ac_cv_lib_nettle_nettle_MD5Init" = xyes +then : + USE_GNUTLS_NETTLE=1 +fi + + fi + if test "$USE_GNUTLS_NETTLE" = ""; then + as_fn_error $? "GnuTLS found, but nettle was not found" "$LINENO" 5 + fi + LIBS="-lnettle $LIBS" +fi + +if test "$GNUTLS_ENABLED" = "1"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for gnutls_srp_verifier in -lgnutls" >&5 +printf %s "checking for gnutls_srp_verifier in -lgnutls... " >&6; } +if test ${ac_cv_lib_gnutls_gnutls_srp_verifier+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lgnutls $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char gnutls_srp_verifier (); +int main (void) +{ +return gnutls_srp_verifier (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_gnutls_gnutls_srp_verifier=yes +else $as_nop + ac_cv_lib_gnutls_gnutls_srp_verifier=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gnutls_gnutls_srp_verifier" >&5 +printf "%s\n" "$ac_cv_lib_gnutls_gnutls_srp_verifier" >&6; } +if test "x$ac_cv_lib_gnutls_gnutls_srp_verifier" = xyes +then : + + +printf "%s\n" "#define HAVE_GNUTLS_SRP 1" >>confdefs.h + + HAVE_GNUTLS_SRP=1 + + +fi + +fi + + + + +if test "x$OPT_MBEDTLS" != xno; then + _cppflags=$CPPFLAGS + _ldflags=$LDFLAGS + ssl_msg= + + if test X"$OPT_MBEDTLS" != Xno; then + + if test "$OPT_MBEDTLS" = "yes"; then + OPT_MBEDTLS="" + fi + + if test -z "$OPT_MBEDTLS" ; then + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for mbedtls_havege_init in -lmbedtls" >&5 +printf %s "checking for mbedtls_havege_init in -lmbedtls... " >&6; } +if test ${ac_cv_lib_mbedtls_mbedtls_havege_init+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lmbedtls -lmbedx509 -lmbedcrypto $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char mbedtls_havege_init (); +int main (void) +{ +return mbedtls_havege_init (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_mbedtls_mbedtls_havege_init=yes +else $as_nop + ac_cv_lib_mbedtls_mbedtls_havege_init=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_mbedtls_mbedtls_havege_init" >&5 +printf "%s\n" "$ac_cv_lib_mbedtls_mbedtls_havege_init" >&6; } +if test "x$ac_cv_lib_mbedtls_mbedtls_havege_init" = xyes +then : + + +printf "%s\n" "#define USE_MBEDTLS 1" >>confdefs.h + + USE_MBEDTLS=1 + + MBEDTLS_ENABLED=1 + USE_MBEDTLS="yes" + ssl_msg="mbedTLS" + test mbedtls != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + +fi + + fi + + addld="" + addlib="" + addcflags="" + mbedtlslib="" + + if test "x$USE_MBEDTLS" != "xyes"; then + addld=-L$OPT_MBEDTLS/lib$libsuff + addcflags=-I$OPT_MBEDTLS/include + mbedtlslib=$OPT_MBEDTLS/lib$libsuff + + LDFLAGS="$LDFLAGS $addld" + if test "$addcflags" != "-I/usr/include"; then + CPPFLAGS="$CPPFLAGS $addcflags" + fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for mbedtls_ssl_init in -lmbedtls" >&5 +printf %s "checking for mbedtls_ssl_init in -lmbedtls... " >&6; } +if test ${ac_cv_lib_mbedtls_mbedtls_ssl_init+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lmbedtls -lmbedx509 -lmbedcrypto $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char mbedtls_ssl_init (); +int main (void) +{ +return mbedtls_ssl_init (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_mbedtls_mbedtls_ssl_init=yes +else $as_nop + ac_cv_lib_mbedtls_mbedtls_ssl_init=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_mbedtls_mbedtls_ssl_init" >&5 +printf "%s\n" "$ac_cv_lib_mbedtls_mbedtls_ssl_init" >&6; } +if test "x$ac_cv_lib_mbedtls_mbedtls_ssl_init" = xyes +then : + + +printf "%s\n" "#define USE_MBEDTLS 1" >>confdefs.h + + USE_MBEDTLS=1 + + MBEDTLS_ENABLED=1 + USE_MBEDTLS="yes" + ssl_msg="mbedTLS" + test mbedtls != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + +else $as_nop + + CPPFLAGS=$_cppflags + LDFLAGS=$_ldflags + +fi + + fi + + if test "x$USE_MBEDTLS" = "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: detected mbedTLS" >&5 +printf "%s\n" "$as_me: detected mbedTLS" >&6;} + check_for_ca_bundle=1 + + LIBS="-lmbedtls -lmbedx509 -lmbedcrypto $LIBS" + + if test -n "$mbedtlslib"; then + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$mbedtlslib" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $mbedtlslib to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $mbedtlslib to CURL_LIBRARY_PATH" >&6;} + fi + fi + fi + + fi + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" +fi + + + + +case "$OPT_WOLFSSL" in + yes|no) + wolfpkg="" + ;; + *) + wolfpkg="$withval/lib/pkgconfig" + ;; +esac + +if test "x$OPT_WOLFSSL" != xno; then + _cppflags=$CPPFLAGS + _ldflags=$LDFLAGS + + ssl_msg= + + if test X"$OPT_WOLFSSL" != Xno; then + + if test "$OPT_WOLFSSL" = "yes"; then + OPT_WOLFSSL="" + fi + + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for wolfssl options with pkg-config" >&5 +printf %s "checking for wolfssl options with pkg-config... " >&6; } + itexists=` + if test -n "$wolfpkg"; then + PKG_CONFIG_LIBDIR="$wolfpkg" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists wolfssl >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Check dir $wolfpkg" >&5 +printf "%s\n" "$as_me: Check dir $wolfpkg" >&6;} + + addld="" + addlib="" + addcflags="" + if test "$PKGCONFIG" != "no" ; then + addlib=` + if test -n "$wolfpkg"; then + PKG_CONFIG_LIBDIR="$wolfpkg" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-l wolfssl` + addld=` + if test -n "$wolfpkg"; then + PKG_CONFIG_LIBDIR="$wolfpkg" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-L wolfssl` + addcflags=` + if test -n "$wolfpkg"; then + PKG_CONFIG_LIBDIR="$wolfpkg" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --cflags-only-I wolfssl` + version=` + if test -n "$wolfpkg"; then + PKG_CONFIG_LIBDIR="$wolfpkg" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --modversion wolfssl` + wolfssllibpath=`echo $addld | $SED -e 's/^-L//'` + else + addlib=-lwolfssl + if test -n "$OPT_WOLFSSL"; then + addld=-L$OPT_WOLFSSL/lib$libsuff + addcflags=-I$OPT_WOLFSSL/include + wolfssllibpath=$OPT_WOLFSSL/lib$libsuff + fi + fi + + if test "x$USE_WOLFSSL" != "xyes"; then + + LDFLAGS="$LDFLAGS $addld" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Add $addld to LDFLAGS" >&5 +printf "%s\n" "$as_me: Add $addld to LDFLAGS" >&6;} + if test "$addcflags" != "-I/usr/include"; then + CPPFLAGS="$CPPFLAGS $addcflags" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Add $addcflags to CPPFLAGS" >&5 +printf "%s\n" "$as_me: Add $addcflags to CPPFLAGS" >&6;} + fi + + my_ac_save_LIBS="$LIBS" + LIBS="$addlib $LIBS" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Add $addlib to LIBS" >&5 +printf "%s\n" "$as_me: Add $addlib to LIBS" >&6;} + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for wolfSSL_Init in -lwolfssl" >&5 +printf %s "checking for wolfSSL_Init in -lwolfssl... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +/* These aren't needed for detection and confuse WolfSSL. + They are set up properly later if it is detected. */ +#undef SIZEOF_LONG +#undef SIZEOF_LONG_LONG +#include +#include + +int main (void) +{ + + return wolfSSL_Init(); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define USE_WOLFSSL 1" >>confdefs.h + + USE_WOLFSSL=1 + + WOLFSSL_ENABLED=1 + USE_WOLFSSL="yes" + ssl_msg="WolfSSL" + QUIC_ENABLED=yes + test wolfssl != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + CPPFLAGS=$_cppflags + LDFLAGS=$_ldflags + wolfssllibpath="" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + LIBS="$my_ac_save_LIBS" + fi + + if test "x$USE_WOLFSSL" = "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: detected wolfSSL" >&5 +printf "%s\n" "$as_me: detected wolfSSL" >&6;} + check_for_ca_bundle=1 + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking size of long long" >&5 +printf %s "checking size of long long... " >&6; } + r=0 + for typesize in 8 4 2 16 1; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include + + +int main (void) +{ +switch(0) { + case 0: + case (sizeof(long long) == $typesize):; + } + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + r=$typesize +else $as_nop + + r=0 +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + if test $r -gt 0; then + break; + fi + done + if test $r -eq 0; then + as_fn_error $? "Failed to find size of long long" "$LINENO" 5 + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $r" >&5 +printf "%s\n" "$r" >&6; } + tname=$(echo "ac_cv_sizeof_long long" | tr A-Z a-z | tr " " "_") + eval "$tname=$r" + + +printf "%s\n" "#define SIZEOF_LONG_LONG $r" >>confdefs.h + + + + + LIBS="$addlib -lm $LIBS" + + ac_fn_c_check_func "$LINENO" "wolfSSL_get_peer_certificate" "ac_cv_func_wolfSSL_get_peer_certificate" +if test "x$ac_cv_func_wolfSSL_get_peer_certificate" = xyes +then : + printf "%s\n" "#define HAVE_WOLFSSL_GET_PEER_CERTIFICATE 1" >>confdefs.h + +fi +ac_fn_c_check_func "$LINENO" "wolfSSL_UseALPN" "ac_cv_func_wolfSSL_UseALPN" +if test "x$ac_cv_func_wolfSSL_UseALPN" = xyes +then : + printf "%s\n" "#define HAVE_WOLFSSL_USEALPN 1" >>confdefs.h + +fi + + + ac_fn_c_check_func "$LINENO" "wolfSSL_DES_ecb_encrypt" "ac_cv_func_wolfSSL_DES_ecb_encrypt" +if test "x$ac_cv_func_wolfSSL_DES_ecb_encrypt" = xyes +then : + + +printf "%s\n" "#define HAVE_WOLFSSL_DES_ECB_ENCRYPT 1" >>confdefs.h + + WOLFSSL_NTLM=1 + + +fi + + + ac_fn_c_check_func "$LINENO" "wolfSSL_BIO_set_shutdown" "ac_cv_func_wolfSSL_BIO_set_shutdown" +if test "x$ac_cv_func_wolfSSL_BIO_set_shutdown" = xyes +then : + + +printf "%s\n" "#define HAVE_WOLFSSL_FULL_BIO 1" >>confdefs.h + + WOLFSSL_FULL_BIO=1 + + +fi + + + if test -n "$wolfssllibpath"; then + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$wolfssllibpath" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $wolfssllibpath to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $wolfssllibpath to CURL_LIBRARY_PATH" >&6;} + fi + fi + else + as_fn_error $? "--with-wolfssl but wolfSSL was not found or doesn't work" "$LINENO" 5 + fi + + fi + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" +fi + + + + +if test "x$OPT_BEARSSL" != xno; then + _cppflags=$CPPFLAGS + _ldflags=$LDFLAGS + ssl_msg= + + if test X"$OPT_BEARSSL" != Xno; then + + if test "$OPT_BEARSSL" = "yes"; then + OPT_BEARSSL="" + fi + + if test -z "$OPT_BEARSSL" ; then + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for br_ssl_client_init_full in -lbearssl" >&5 +printf %s "checking for br_ssl_client_init_full in -lbearssl... " >&6; } +if test ${ac_cv_lib_bearssl_br_ssl_client_init_full+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lbearssl -lbearssl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char br_ssl_client_init_full (); +int main (void) +{ +return br_ssl_client_init_full (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_bearssl_br_ssl_client_init_full=yes +else $as_nop + ac_cv_lib_bearssl_br_ssl_client_init_full=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bearssl_br_ssl_client_init_full" >&5 +printf "%s\n" "$ac_cv_lib_bearssl_br_ssl_client_init_full" >&6; } +if test "x$ac_cv_lib_bearssl_br_ssl_client_init_full" = xyes +then : + + +printf "%s\n" "#define USE_BEARSSL 1" >>confdefs.h + + USE_BEARSSL=1 + + BEARSSL_ENABLED=1 + USE_BEARSSL="yes" + ssl_msg="BearSSL" + test bearssl != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + +fi + + fi + + addld="" + addlib="" + addcflags="" + bearssllib="" + + if test "x$USE_BEARSSL" != "xyes"; then + addld=-L$OPT_BEARSSL/lib$libsuff + addcflags=-I$OPT_BEARSSL/include + bearssllib=$OPT_BEARSSL/lib$libsuff + + LDFLAGS="$LDFLAGS $addld" + if test "$addcflags" != "-I/usr/include"; then + CPPFLAGS="$CPPFLAGS $addcflags" + fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for br_ssl_client_init_full in -lbearssl" >&5 +printf %s "checking for br_ssl_client_init_full in -lbearssl... " >&6; } +if test ${ac_cv_lib_bearssl_br_ssl_client_init_full+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lbearssl -lbearssl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char br_ssl_client_init_full (); +int main (void) +{ +return br_ssl_client_init_full (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_bearssl_br_ssl_client_init_full=yes +else $as_nop + ac_cv_lib_bearssl_br_ssl_client_init_full=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bearssl_br_ssl_client_init_full" >&5 +printf "%s\n" "$ac_cv_lib_bearssl_br_ssl_client_init_full" >&6; } +if test "x$ac_cv_lib_bearssl_br_ssl_client_init_full" = xyes +then : + + +printf "%s\n" "#define USE_BEARSSL 1" >>confdefs.h + + USE_BEARSSL=1 + + BEARSSL_ENABLED=1 + USE_BEARSSL="yes" + ssl_msg="BearSSL" + test bearssl != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + +else $as_nop + + CPPFLAGS=$_cppflags + LDFLAGS=$_ldflags + +fi + + fi + + if test "x$USE_BEARSSL" = "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: detected BearSSL" >&5 +printf "%s\n" "$as_me: detected BearSSL" >&6;} + check_for_ca_bundle=1 + + LIBS="-lbearssl $LIBS" + + if test -n "$bearssllib"; then + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$bearssllib" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $bearssllib to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $bearssllib to CURL_LIBRARY_PATH" >&6;} + fi + fi + fi + + fi + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" +fi + + + +if test "x$OPT_RUSTLS" != xno; then + ssl_msg= + + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + + case $host_os in + darwin*) + LDFLAGS="$LDFLAGS -framework Security" + ;; + *) + ;; + esac + ## NEW CODE + + + case "$OPT_RUSTLS" in + yes) + PKGTEST="yes" + PREFIX_RUSTLS= + ;; + *) + PKGTEST="no" + PREFIX_RUSTLS=$OPT_RUSTLS + + + RUSTLS_PCDIR="$PREFIX_RUSTLS/lib/pkgconfig" + if test -f "$RUSTLS_PCDIR/rustls.pc"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: PKG_CONFIG_LIBDIR will be set to \"$RUSTLS_PCDIR\"" >&5 +printf "%s\n" "$as_me: PKG_CONFIG_LIBDIR will be set to \"$RUSTLS_PCDIR\"" >&6;} + PKGTEST="yes" + fi + + if test "$PKGTEST" != "yes"; then + # try lib64 instead + RUSTLS_PCDIR="$PREFIX_RUSTLS/lib64/pkgconfig" + if test -f "$RUSTLS_PCDIR/rustls.pc"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: PKG_CONFIG_LIBDIR will be set to \"$RUSTLS_PCDIR\"" >&5 +printf "%s\n" "$as_me: PKG_CONFIG_LIBDIR will be set to \"$RUSTLS_PCDIR\"" >&6;} + PKGTEST="yes" + fi + fi + + if test "$PKGTEST" != "yes"; then + + addld=-L$PREFIX_RUSTLS/lib$libsuff + addcflags=-I$PREFIX_RUSTLS/include + + LDFLAGS="$LDFLAGS $addld" + if test "$addcflags" != "-I/usr/include"; then + CPPFLAGS="$CPPFLAGS $addcflags" + fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for rustls_connection_read in -lrustls" >&5 +printf %s "checking for rustls_connection_read in -lrustls... " >&6; } +if test ${ac_cv_lib_rustls_rustls_connection_read+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lrustls -lpthread -ldl -lm $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char rustls_connection_read (); +int main (void) +{ +return rustls_connection_read (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_rustls_rustls_connection_read=yes +else $as_nop + ac_cv_lib_rustls_rustls_connection_read=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_rustls_rustls_connection_read" >&5 +printf "%s\n" "$ac_cv_lib_rustls_rustls_connection_read" >&6; } +if test "x$ac_cv_lib_rustls_rustls_connection_read" = xyes +then : + + +printf "%s\n" "#define USE_RUSTLS 1" >>confdefs.h + + USE_RUSTLS=1 + + RUSTLS_ENABLED=1 + USE_RUSTLS="yes" + ssl_msg="rustls" + test rustls != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + +else $as_nop + as_fn_error $? "--with-rustls was specified but could not find rustls." "$LINENO" 5 +fi + + + LIB_RUSTLS="$PREFIX_RUSTLS/lib$libsuff" + if test "$PREFIX_RUSTLS" != "/usr" ; then + SSL_LDFLAGS="-L$LIB_RUSTLS" + SSL_CPPFLAGS="-I$PREFIX_RUSTLS/include" + fi + fi + ;; + esac + + if test "$PKGTEST" = "yes"; then + + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for rustls options with pkg-config" >&5 +printf %s "checking for rustls options with pkg-config... " >&6; } + itexists=` + if test -n "$RUSTLS_PCDIR"; then + PKG_CONFIG_LIBDIR="$RUSTLS_PCDIR" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists rustls >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + SSL_LIBS=` + if test -n "$RUSTLS_PCDIR"; then + PKG_CONFIG_LIBDIR="$RUSTLS_PCDIR" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --libs-only-l --libs-only-other rustls 2>/dev/null` + + SSL_LDFLAGS=` + if test -n "$RUSTLS_PCDIR"; then + PKG_CONFIG_LIBDIR="$RUSTLS_PCDIR" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --libs-only-L rustls 2>/dev/null` + + SSL_CPPFLAGS=` + if test -n "$RUSTLS_PCDIR"; then + PKG_CONFIG_LIBDIR="$RUSTLS_PCDIR" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --cflags-only-I rustls 2>/dev/null` + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: pkg-config: SSL_LIBS: \"$SSL_LIBS\"" >&5 +printf "%s\n" "$as_me: pkg-config: SSL_LIBS: \"$SSL_LIBS\"" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: pkg-config: SSL_LDFLAGS: \"$SSL_LDFLAGS\"" >&5 +printf "%s\n" "$as_me: pkg-config: SSL_LDFLAGS: \"$SSL_LDFLAGS\"" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: pkg-config: SSL_CPPFLAGS: \"$SSL_CPPFLAGS\"" >&5 +printf "%s\n" "$as_me: pkg-config: SSL_CPPFLAGS: \"$SSL_CPPFLAGS\"" >&6;} + + LIB_RUSTLS=`echo $SSL_LDFLAGS | sed -e 's/^-L//'` + + LIBS="$SSL_LIBS $LIBS" + ssl_msg="rustls" + +printf "%s\n" "#define USE_RUSTLS 1" >>confdefs.h + + USE_RUSTLS=1 + + USE_RUSTLS="yes" + RUSTLS_ENABLED=1 + test rustls != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + else + as_fn_error $? "pkg-config: Could not find rustls" "$LINENO" 5 + fi + + else + LIBS="-lrustls -lpthread -ldl -lm $LIBS" + fi + + CPPFLAGS="$CLEAN_CPPFLAGS $SSL_CPPFLAGS" + LDFLAGS="$CLAN_LDFLAGS $SSL_LDFLAGS" + + if test "x$USE_RUSTLS" = "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: detected rustls" >&5 +printf "%s\n" "$as_me: detected rustls" >&6;} + check_for_ca_bundle=1 + + if test -n "$LIB_RUSTLS"; then + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$LIB_RUSTLS" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $LIB_RUSTLS to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $LIB_RUSTLS to CURL_LIBRARY_PATH" >&6;} + fi + fi + fi + + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" + + if test X"$OPT_RUSTLS" != Xno && + test "$RUSTLS_ENABLED" != "1"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: OPT_RUSTLS: $OPT_RUSTLS" >&5 +printf "%s\n" "$as_me: OPT_RUSTLS: $OPT_RUSTLS" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: RUSTLS_ENABLED: $RUSTLS_ENABLED" >&5 +printf "%s\n" "$as_me: RUSTLS_ENABLED: $RUSTLS_ENABLED" >&6;} + as_fn_error $? "--with-rustls was given but Rustls could not be detected" "$LINENO" 5 + fi +fi + + +if test "x$USE_WIN32_CRYPTO" = "x1" -o "x$USE_SCHANNEL" = "x1"; then + LIBS="-ladvapi32 -lcrypt32 $LIBS" +fi + +if test "x$curl_cv_native_windows" = "xyes"; then + LIBS="-lbcrypt $LIBS" +fi + +case "x$SSL_DISABLED$OPENSSL_ENABLED$GNUTLS_ENABLED$MBEDTLS_ENABLED$WOLFSSL_ENABLED$SCHANNEL_ENABLED$SECURETRANSPORT_ENABLED$BEARSSL_ENABLED$RUSTLS_ENABLED" +in +x) + as_fn_error $? "TLS not detected, you will not be able to use HTTPS, FTPS, NTLM and more. +Use --with-openssl, --with-gnutls, --with-wolfssl, --with-mbedtls, --with-schannel, --with-secure-transport, --with-amissl, --with-bearssl or --with-rustls to address this." "$LINENO" 5 + ;; +x1) + # one SSL backend is enabled + + SSL_ENABLED="1" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: built with one SSL backend" >&5 +printf "%s\n" "$as_me: built with one SSL backend" >&6;} + ;; +xD) + # explicitly built without TLS + ;; +xD*) + as_fn_error $? "--without-ssl has been set together with an explicit option to use an ssl library +(e.g. --with-openssl, --with-gnutls, --with-wolfssl, --with-mbedtls, --with-schannel, --with-secure-transport, --with-amissl, --with-bearssl, --with-rustls). +Since these are conflicting parameters, verify which is the desired one and drop the other." "$LINENO" 5 + ;; +*) + # more than one SSL backend is enabled + + SSL_ENABLED="1" + + CURL_WITH_MULTI_SSL="1" + +printf "%s\n" "#define CURL_WITH_MULTI_SSL 1" >>confdefs.h + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: built with multiple SSL backends" >&5 +printf "%s\n" "$as_me: built with multiple SSL backends" >&6;} + ;; +esac + +if test -n "$ssl_backends"; then + curl_ssl_msg="enabled ($ssl_backends)" +fi + +if test no = "$VALID_DEFAULT_SSL_BACKEND" +then + if test -n "$SSL_ENABLED" + then + as_fn_error $? "Default SSL backend $DEFAULT_SSL_BACKEND not enabled!" "$LINENO" 5 + else + as_fn_error $? "Default SSL backend requires SSL!" "$LINENO" 5 + fi +elif test yes = "$VALID_DEFAULT_SSL_BACKEND" +then + +printf "%s\n" "#define CURL_DEFAULT_SSL_BACKEND \"$DEFAULT_SSL_BACKEND\"" >>confdefs.h + +fi + + +if test -n "$check_for_ca_bundle"; then + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking default CA cert bundle/path" >&5 +printf %s "checking default CA cert bundle/path... " >&6; } + + +# Check whether --with-ca-bundle was given. +if test ${with_ca_bundle+y} +then : + withval=$with_ca_bundle; + want_ca="$withval" + if test "x$want_ca" = "xyes"; then + as_fn_error $? "--with-ca-bundle=FILE requires a path to the CA bundle" "$LINENO" 5 + fi + +else $as_nop + want_ca="unset" +fi + + +# Check whether --with-ca-path was given. +if test ${with_ca_path+y} +then : + withval=$with_ca_path; + want_capath="$withval" + if test "x$want_capath" = "xyes"; then + as_fn_error $? "--with-ca-path=DIRECTORY requires a path to the CA path directory" "$LINENO" 5 + fi + +else $as_nop + want_capath="unset" +fi + + + ca_warning=" (warning: certs not found)" + capath_warning=" (warning: certs not found)" + check_capath="" + + if test "x$want_ca" != "xno" -a "x$want_ca" != "xunset" -a \ + "x$want_capath" != "xno" -a "x$want_capath" != "xunset"; then + ca="$want_ca" + capath="$want_capath" + elif test "x$want_ca" != "xno" -a "x$want_ca" != "xunset"; then + ca="$want_ca" + capath="no" + elif test "x$want_capath" != "xno" -a "x$want_capath" != "xunset"; then + if test "x$OPENSSL_ENABLED" != "x1" -a \ + "x$GNUTLS_ENABLED" != "x1" -a \ + "x$MBEDTLS_ENABLED" != "x1" -a \ + "x$WOLFSSL_ENABLED" != "x1"; then + as_fn_error $? "--with-ca-path only works with OpenSSL, GnuTLS, mbedTLS or wolfSSL" "$LINENO" 5 + fi + capath="$want_capath" + ca="no" + else + ca="no" + capath="no" + if test "x$cross_compiling" != "xyes"; then + if test "x$want_ca" = "xunset"; then + if test "x$prefix" != xNONE; then + cac="${prefix}/share/curl/curl-ca-bundle.crt" + else + cac="$ac_default_prefix/share/curl/curl-ca-bundle.crt" + fi + + for a in /etc/ssl/certs/ca-certificates.crt \ + /etc/pki/tls/certs/ca-bundle.crt \ + /usr/share/ssl/certs/ca-bundle.crt \ + /usr/local/share/certs/ca-root-nss.crt \ + /etc/ssl/cert.pem \ + "$cac"; do + if test -f "$a"; then + ca="$a" + break + fi + done + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: want $want_capath ca $ca" >&5 +printf "%s\n" "$as_me: want $want_capath ca $ca" >&6;} + if test "x$want_capath" = "xunset"; then + if test "x$OPENSSL_ENABLED" = "x1" -o \ + "x$GNUTLS_ENABLED" = "x1" -o \ + "x$MBEDTLS_ENABLED" = "x1" -o \ + "x$WOLFSSL_ENABLED" = "x1"; then + check_capath="/etc/ssl/certs" + fi + fi + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: skipped the ca-cert path detection when cross-compiling" >&5 +printf "%s\n" "$as_me: WARNING: skipped the ca-cert path detection when cross-compiling" >&2;} + fi + fi + + if test "x$ca" = "xno" || test -f "$ca"; then + ca_warning="" + fi + + if test "x$capath" != "xno"; then + check_capath="$capath" + fi + + if test ! -z "$check_capath"; then + for a in "$check_capath"; do + if test -d "$a" && ls "$a"/[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f].0 >/dev/null 2>/dev/null; then + if test "x$capath" = "xno"; then + capath="$a" + fi + capath_warning="" + break + fi + done + fi + + if test "x$capath" = "xno"; then + capath_warning="" + fi + + if test "x$ca" != "xno"; then + CURL_CA_BUNDLE='"'$ca'"' + +printf "%s\n" "#define CURL_CA_BUNDLE \"$ca\"" >>confdefs.h + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ca" >&5 +printf "%s\n" "$ca" >&6; } + fi + if test "x$capath" != "xno"; then + CURL_CA_PATH="\"$capath\"" + +printf "%s\n" "#define CURL_CA_PATH \"$capath\"" >>confdefs.h + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $capath (capath)" >&5 +printf "%s\n" "$capath (capath)" >&6; } + fi + if test "x$ca" = "xno" && test "x$capath" = "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to use builtin CA store of SSL library" >&5 +printf %s "checking whether to use builtin CA store of SSL library... " >&6; } + +# Check whether --with-ca-fallback was given. +if test ${with_ca_fallback+y} +then : + withval=$with_ca_fallback; + if test "x$with_ca_fallback" != "xyes" -a "x$with_ca_fallback" != "xno"; then + as_fn_error $? "--with-ca-fallback only allows yes or no as parameter" "$LINENO" 5 + fi + +else $as_nop + with_ca_fallback="no" +fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $with_ca_fallback" >&5 +printf "%s\n" "$with_ca_fallback" >&6; } + if test "x$with_ca_fallback" = "xyes"; then + if test "x$OPENSSL_ENABLED" != "x1" -a "x$GNUTLS_ENABLED" != "x1"; then + as_fn_error $? "--with-ca-fallback only works with OpenSSL or GnuTLS" "$LINENO" 5 + fi + +printf "%s\n" "#define CURL_CA_FALLBACK 1" >>confdefs.h + + fi + +fi + + +OPT_LIBPSL=off + +# Check whether --with-libpsl was given. +if test ${with_libpsl+y} +then : + withval=$with_libpsl; OPT_LIBPSL=$withval +fi + + +if test X"$OPT_LIBPSL" != Xno; then + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_LIBPSL" in + yes) + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libpsl options with pkg-config" >&5 +printf %s "checking for libpsl options with pkg-config... " >&6; } + itexists=` + if test -n ""; then + PKG_CONFIG_LIBDIR="" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists libpsl >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + LIB_PSL=`$PKGCONFIG --libs-only-l libpsl` + LD_PSL=`$PKGCONFIG --libs-only-L libpsl` + CPP_PSL=`$PKGCONFIG --cflags-only-I libpsl` + else + LIB_PSL="-lpsl" + fi + + ;; + off) + LIB_PSL="-lpsl" + ;; + *) + LIB_PSL="-lpsl" + PREFIX_PSL=$OPT_LIBPSL + ;; + esac + + if test -n "$PREFIX_PSL"; then + LD_PSL=-L${PREFIX_PSL}/lib$libsuff + CPP_PSL=-I${PREFIX_PSL}/include + fi + + LDFLAGS="$LDFLAGS $LD_PSL" + CPPFLAGS="$CPPFLAGS $CPP_PSL" + LIBS="$LIB_PSL $LIBS" + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for psl_builtin in -lpsl" >&5 +printf %s "checking for psl_builtin in -lpsl... " >&6; } +if test ${ac_cv_lib_psl_psl_builtin+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lpsl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char psl_builtin (); +int main (void) +{ +return psl_builtin (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_psl_psl_builtin=yes +else $as_nop + ac_cv_lib_psl_psl_builtin=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_psl_psl_builtin" >&5 +printf "%s\n" "$ac_cv_lib_psl_psl_builtin" >&6; } +if test "x$ac_cv_lib_psl_psl_builtin" = xyes +then : + + for ac_header in libpsl.h +do : + ac_fn_c_check_header_compile "$LINENO" "libpsl.h" "ac_cv_header_libpsl_h" "$ac_includes_default" +if test "x$ac_cv_header_libpsl_h" = xyes +then : + printf "%s\n" "#define HAVE_LIBPSL_H 1" >>confdefs.h + curl_psl_msg="enabled" + LIBPSL_ENABLED=1 + +printf "%s\n" "#define USE_LIBPSL 1" >>confdefs.h + + USE_LIBPSL=1 + + +fi + +done + +else $as_nop + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + +fi + + + if test X"$OPT_LIBPSL" != Xoff && + test "$LIBPSL_ENABLED" != "1"; then + as_fn_error $? "libpsl libs and/or directories were not found where specified!" "$LINENO" 5 + fi +fi + if test "$curl_psl_msg" = "enabled"; then + USE_LIBPSL_TRUE= + USE_LIBPSL_FALSE='#' +else + USE_LIBPSL_TRUE='#' + USE_LIBPSL_FALSE= +fi + + + + + +# Check whether --with-libgsasl was given. +if test ${with_libgsasl+y} +then : + withval=$with_libgsasl; with_libgsasl=$withval +else $as_nop + with_libgsasl=yes +fi + +if test $with_libgsasl != "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for library containing gsasl_init" >&5 +printf %s "checking for library containing gsasl_init... " >&6; } +if test ${ac_cv_search_gsasl_init+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char gsasl_init (); +int main (void) +{ +return gsasl_init (); + ; + return 0; +} +_ACEOF +for ac_lib in '' gsasl +do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO" +then : + ac_cv_search_gsasl_init=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext + if test ${ac_cv_search_gsasl_init+y} +then : + break +fi +done +if test ${ac_cv_search_gsasl_init+y} +then : + +else $as_nop + ac_cv_search_gsasl_init=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_gsasl_init" >&5 +printf "%s\n" "$ac_cv_search_gsasl_init" >&6; } +ac_res=$ac_cv_search_gsasl_init +if test "$ac_res" != no +then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + curl_gsasl_msg="enabled"; + +printf "%s\n" "#define USE_GSASL 1" >>confdefs.h + + +else $as_nop + curl_gsasl_msg="no (libgsasl not found)"; + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: libgsasl was not found" >&5 +printf "%s\n" "$as_me: WARNING: libgsasl was not found" >&2;} + + +fi + +fi + if test "$curl_gsasl_msg" = "enabled"; then + USE_GSASL_TRUE= + USE_GSASL_FALSE='#' +else + USE_GSASL_TRUE='#' + USE_GSASL_FALSE= +fi + + + +# Check whether --with-libmetalink was given. +if test ${with_libmetalink+y} +then : + withval=$with_libmetalink; as_fn_error $? "--with-libmetalink and --without-libmetalink no longer work!" "$LINENO" 5 +fi + + + +OPT_LIBSSH2=off + +# Check whether --with-libssh2 was given. +if test ${with_libssh2+y} +then : + withval=$with_libssh2; OPT_LIBSSH2=$withval +else $as_nop + OPT_LIBSSH2=no +fi + + + +OPT_LIBSSH=off + +# Check whether --with-libssh was given. +if test ${with_libssh+y} +then : + withval=$with_libssh; OPT_LIBSSH=$withval +else $as_nop + OPT_LIBSSH=no +fi + + +OPT_WOLFSSH=off + +# Check whether --with-wolfssh was given. +if test ${with_wolfssh+y} +then : + withval=$with_wolfssh; OPT_WOLFSSH=$withval +else $as_nop + OPT_WOLFSSH=no +fi + + +if test X"$OPT_LIBSSH2" != Xno; then + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_LIBSSH2" in + yes) + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libssh2 options with pkg-config" >&5 +printf %s "checking for libssh2 options with pkg-config... " >&6; } + itexists=` + if test -n ""; then + PKG_CONFIG_LIBDIR="" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists libssh2 >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + LIB_SSH2=`$PKGCONFIG --libs-only-l libssh2` + LD_SSH2=`$PKGCONFIG --libs-only-L libssh2` + CPP_SSH2=`$PKGCONFIG --cflags-only-I libssh2` + version=`$PKGCONFIG --modversion libssh2` + DIR_SSH2=`echo $LD_SSH2 | $SED -e 's/^-L//'` + fi + + ;; + off) + ;; + *) + PREFIX_SSH2=$OPT_LIBSSH2 + ;; + esac + + if test -n "$PREFIX_SSH2"; then + LIB_SSH2="-lssh2" + LD_SSH2=-L${PREFIX_SSH2}/lib$libsuff + CPP_SSH2=-I${PREFIX_SSH2}/include + DIR_SSH2=${PREFIX_SSH2}/lib$libsuff + fi + + LDFLAGS="$LDFLAGS $LD_SSH2" + CPPFLAGS="$CPPFLAGS $CPP_SSH2" + LIBS="$LIB_SSH2 $LIBS" + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libssh2_session_block_directions in -lssh2" >&5 +printf %s "checking for libssh2_session_block_directions in -lssh2... " >&6; } +if test ${ac_cv_lib_ssh2_libssh2_session_block_directions+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lssh2 $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char libssh2_session_block_directions (); +int main (void) +{ +return libssh2_session_block_directions (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_ssh2_libssh2_session_block_directions=yes +else $as_nop + ac_cv_lib_ssh2_libssh2_session_block_directions=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ssh2_libssh2_session_block_directions" >&5 +printf "%s\n" "$ac_cv_lib_ssh2_libssh2_session_block_directions" >&6; } +if test "x$ac_cv_lib_ssh2_libssh2_session_block_directions" = xyes +then : + printf "%s\n" "#define HAVE_LIBSSH2 1" >>confdefs.h + + LIBS="-lssh2 $LIBS" + +fi + + + ac_fn_c_check_header_compile "$LINENO" "libssh2.h" "ac_cv_header_libssh2_h" "$ac_includes_default" +if test "x$ac_cv_header_libssh2_h" = xyes +then : + curl_ssh_msg="enabled (libSSH2)" + LIBSSH2_ENABLED=1 + +printf "%s\n" "#define USE_LIBSSH2 1" >>confdefs.h + + USE_LIBSSH2=1 + + +fi + + + if test X"$OPT_LIBSSH2" != Xoff && + test "$LIBSSH2_ENABLED" != "1"; then + as_fn_error $? "libSSH2 libs and/or directories were not found where specified!" "$LINENO" 5 + fi + + if test "$LIBSSH2_ENABLED" = "1"; then + if test -n "$DIR_SSH2"; then + + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_SSH2" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $DIR_SSH2 to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $DIR_SSH2 to CURL_LIBRARY_PATH" >&6;} + fi + fi + else + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + fi +elif test X"$OPT_LIBSSH" != Xno; then + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_LIBSSH" in + yes) + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libssh options with pkg-config" >&5 +printf %s "checking for libssh options with pkg-config... " >&6; } + itexists=` + if test -n ""; then + PKG_CONFIG_LIBDIR="" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists libssh >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + LIB_SSH=`$PKGCONFIG --libs-only-l libssh` + LD_SSH=`$PKGCONFIG --libs-only-L libssh` + CPP_SSH=`$PKGCONFIG --cflags-only-I libssh` + version=`$PKGCONFIG --modversion libssh` + DIR_SSH=`echo $LD_SSH | $SED -e 's/^-L//'` + fi + + ;; + off) + ;; + *) + PREFIX_SSH=$OPT_LIBSSH + ;; + esac + + if test -n "$PREFIX_SSH"; then + LIB_SSH="-lssh" + LD_SSH=-L${PREFIX_SSH}/lib$libsuff + CPP_SSH=-I${PREFIX_SSH}/include + DIR_SSH=${PREFIX_SSH}/lib$libsuff + fi + + LDFLAGS="$LDFLAGS $LD_SSH" + CPPFLAGS="$CPPFLAGS $CPP_SSH" + LIBS="$LIB_SSH $LIBS" + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ssh_new in -lssh" >&5 +printf %s "checking for ssh_new in -lssh... " >&6; } +if test ${ac_cv_lib_ssh_ssh_new+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lssh $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char ssh_new (); +int main (void) +{ +return ssh_new (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_ssh_ssh_new=yes +else $as_nop + ac_cv_lib_ssh_ssh_new=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ssh_ssh_new" >&5 +printf "%s\n" "$ac_cv_lib_ssh_ssh_new" >&6; } +if test "x$ac_cv_lib_ssh_ssh_new" = xyes +then : + printf "%s\n" "#define HAVE_LIBSSH 1" >>confdefs.h + + LIBS="-lssh $LIBS" + +fi + + + ac_fn_c_check_header_compile "$LINENO" "libssh/libssh.h" "ac_cv_header_libssh_libssh_h" "$ac_includes_default" +if test "x$ac_cv_header_libssh_libssh_h" = xyes +then : + curl_ssh_msg="enabled (libSSH)" + LIBSSH_ENABLED=1 + +printf "%s\n" "#define USE_LIBSSH 1" >>confdefs.h + + USE_LIBSSH=1 + + +fi + + + if test X"$OPT_LIBSSH" != Xoff && + test "$LIBSSH_ENABLED" != "1"; then + as_fn_error $? "libSSH libs and/or directories were not found where specified!" "$LINENO" 5 + fi + + if test "$LIBSSH_ENABLED" = "1"; then + if test -n "$DIR_SSH"; then + + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_SSH" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $DIR_SSH to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $DIR_SSH to CURL_LIBRARY_PATH" >&6;} + fi + fi + else + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + fi +elif test X"$OPT_WOLFSSH" != Xno; then + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + + if test "$OPT_WOLFSSH" != yes; then + WOLFCONFIG="$OPT_WOLFSSH/bin/wolfssh-config" + LDFLAGS="$LDFLAGS `$WOLFCONFIG --libs`" + CPPFLAGS="$CPPFLAGS `$WOLFCONFIG --cflags`" + fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for wolfSSH_Init in -lwolfssh" >&5 +printf %s "checking for wolfSSH_Init in -lwolfssh... " >&6; } +if test ${ac_cv_lib_wolfssh_wolfSSH_Init+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lwolfssh $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char wolfSSH_Init (); +int main (void) +{ +return wolfSSH_Init (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_wolfssh_wolfSSH_Init=yes +else $as_nop + ac_cv_lib_wolfssh_wolfSSH_Init=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_wolfssh_wolfSSH_Init" >&5 +printf "%s\n" "$ac_cv_lib_wolfssh_wolfSSH_Init" >&6; } +if test "x$ac_cv_lib_wolfssh_wolfSSH_Init" = xyes +then : + printf "%s\n" "#define HAVE_LIBWOLFSSH 1" >>confdefs.h + + LIBS="-lwolfssh $LIBS" + +fi + + + for ac_header in wolfssh/ssh.h +do : + ac_fn_c_check_header_compile "$LINENO" "wolfssh/ssh.h" "ac_cv_header_wolfssh_ssh_h" "$ac_includes_default" +if test "x$ac_cv_header_wolfssh_ssh_h" = xyes +then : + printf "%s\n" "#define HAVE_WOLFSSH_SSH_H 1" >>confdefs.h + curl_ssh_msg="enabled (wolfSSH)" + WOLFSSH_ENABLED=1 + +printf "%s\n" "#define USE_WOLFSSH 1" >>confdefs.h + + USE_WOLFSSH=1 + + +fi + +done + +fi + + +OPT_LIBRTMP=off + +# Check whether --with-librtmp was given. +if test ${with_librtmp+y} +then : + withval=$with_librtmp; OPT_LIBRTMP=$withval +fi + + +if test X"$OPT_LIBRTMP" != Xno; then + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_LIBRTMP" in + yes) + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for librtmp options with pkg-config" >&5 +printf %s "checking for librtmp options with pkg-config... " >&6; } + itexists=` + if test -n ""; then + PKG_CONFIG_LIBDIR="" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists librtmp >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + LIB_RTMP=`$PKGCONFIG --libs-only-l librtmp` + LD_RTMP=`$PKGCONFIG --libs-only-L librtmp` + CPP_RTMP=`$PKGCONFIG --cflags-only-I librtmp` + version=`$PKGCONFIG --modversion librtmp` + DIR_RTMP=`echo $LD_RTMP | $SED -e 's/^-L//'` + else + as_fn_error $? "--librtmp was specified but could not find librtmp pkgconfig file." "$LINENO" 5 + fi + + ;; + off) + LIB_RTMP="-lrtmp" + ;; + *) + LIB_RTMP="-lrtmp" + PREFIX_RTMP=$OPT_LIBRTMP + ;; + esac + + if test -n "$PREFIX_RTMP"; then + LD_RTMP=-L${PREFIX_RTMP}/lib$libsuff + CPP_RTMP=-I${PREFIX_RTMP}/include + DIR_RTMP=${PREFIX_RTMP}/lib$libsuff + fi + + LDFLAGS="$LDFLAGS $LD_RTMP" + CPPFLAGS="$CPPFLAGS $CPP_RTMP" + LIBS="$LIB_RTMP $LIBS" + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for RTMP_Init in -lrtmp" >&5 +printf %s "checking for RTMP_Init in -lrtmp... " >&6; } +if test ${ac_cv_lib_rtmp_RTMP_Init+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lrtmp $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char RTMP_Init (); +int main (void) +{ +return RTMP_Init (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_rtmp_RTMP_Init=yes +else $as_nop + ac_cv_lib_rtmp_RTMP_Init=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_rtmp_RTMP_Init" >&5 +printf "%s\n" "$ac_cv_lib_rtmp_RTMP_Init" >&6; } +if test "x$ac_cv_lib_rtmp_RTMP_Init" = xyes +then : + + for ac_header in librtmp/rtmp.h +do : + ac_fn_c_check_header_compile "$LINENO" "librtmp/rtmp.h" "ac_cv_header_librtmp_rtmp_h" "$ac_includes_default" +if test "x$ac_cv_header_librtmp_rtmp_h" = xyes +then : + printf "%s\n" "#define HAVE_LIBRTMP_RTMP_H 1" >>confdefs.h + curl_rtmp_msg="enabled (librtmp)" + LIBRTMP_ENABLED=1 + +printf "%s\n" "#define USE_LIBRTMP 1" >>confdefs.h + + USE_LIBRTMP=1 + + +fi + +done + +else $as_nop + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + +fi + + + if test X"$OPT_LIBRTMP" != Xoff && + test "$LIBRTMP_ENABLED" != "1"; then + as_fn_error $? "librtmp libs and/or directories were not found where specified!" "$LINENO" 5 + fi + +fi + + +versioned_symbols_flavour= +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether versioned symbols are wanted" >&5 +printf %s "checking whether versioned symbols are wanted... " >&6; } +# Check whether --enable-versioned-symbols was given. +if test ${enable_versioned_symbols+y} +then : + enableval=$enable_versioned_symbols; case "$enableval" in + yes) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if libraries can be versioned" >&5 +printf %s "checking if libraries can be versioned... " >&6; } + GLD=`$LD --help < /dev/null 2>/dev/null | grep version-script` + if test -z "$GLD"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: You need an ld version supporting the --version-script option" >&5 +printf "%s\n" "$as_me: WARNING: You need an ld version supporting the --version-script option" >&2;} + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + if test "x$CURL_WITH_MULTI_SSL" = "x1"; then + versioned_symbols_flavour="MULTISSL_" + elif test "x$OPENSSL_ENABLED" = "x1"; then + versioned_symbols_flavour="OPENSSL_" + elif test "x$GNUTLS_ENABLED" = "x1"; then + versioned_symbols_flavour="GNUTLS_" + elif test "x$WOLFSSL_ENABLED" = "x1"; then + versioned_symbols_flavour="WOLFSSL_" + elif test "x$SCHANNEL_ENABLED" = "x1"; then + versioned_symbols_flavour="SCHANNEL_" + elif test "x$SECURETRANSPORT_ENABLED" = "x1"; then + versioned_symbols_flavour="SECURE_TRANSPORT_" + else + versioned_symbols_flavour="" + fi + versioned_symbols="yes" + fi + ;; + + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + esac + +else $as_nop + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + + +fi + + +CURL_LT_SHLIB_VERSIONED_FLAVOUR="$versioned_symbols_flavour" + + if test "x$versioned_symbols" = 'xyes'; then + CURL_LT_SHLIB_USE_VERSIONED_SYMBOLS_TRUE= + CURL_LT_SHLIB_USE_VERSIONED_SYMBOLS_FALSE='#' +else + CURL_LT_SHLIB_USE_VERSIONED_SYMBOLS_TRUE='#' + CURL_LT_SHLIB_USE_VERSIONED_SYMBOLS_FALSE= +fi + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable Windows native IDN (Windows native builds only)" >&5 +printf %s "checking whether to enable Windows native IDN (Windows native builds only)... " >&6; } +OPT_WINIDN="default" + +# Check whether --with-winidn was given. +if test ${with_winidn+y} +then : + withval=$with_winidn; OPT_WINIDN=$withval +fi + +case "$OPT_WINIDN" in + no|default) + want_winidn="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + yes) + want_winidn="yes" + want_winidn_path="default" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + *) + want_winidn="yes" + want_winidn_path="$withval" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes ($withval)" >&5 +printf "%s\n" "yes ($withval)" >&6; } + ;; +esac + +if test "$want_winidn" = "yes"; then + clean_CFLAGS="$CFLAGS" + clean_CPPFLAGS="$CPPFLAGS" + clean_LDFLAGS="$LDFLAGS" + clean_LIBS="$LIBS" + WINIDN_LIBS="-lnormaliz" + WINIDN_CPPFLAGS="" + # + if test "$want_winidn_path" != "default"; then + WINIDN_LDFLAGS="-L$want_winidn_path/lib$libsuff" + WINIDN_CPPFLAGS="-I$want_winidn_path/include" + WINIDN_DIR="$want_winidn_path/lib$libsuff" + fi + # + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + #include + +int main (void) +{ + + #if (WINVER < 0x600) && (_WIN32_WINNT < 0x600) + #error + #endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + +else $as_nop + + CFLAGS=`echo $CFLAGS | $SED -e 's/-DWINVER=[^ ]*//g'` + CFLAGS=`echo $CFLAGS | $SED -e 's/-D_WIN32_WINNT=[^ ]*//g'` + CPPFLAGS=`echo $CPPFLAGS | $SED -e 's/-DWINVER=[^ ]*//g'` + CPPFLAGS=`echo $CPPFLAGS | $SED -e 's/-D_WIN32_WINNT=[^ ]*//g'` + WINIDN_CPPFLAGS="$WINIDN_CPPFLAGS -DWINVER=0x0600" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + # + CPPFLAGS="$CPPFLAGS $WINIDN_CPPFLAGS" + LDFLAGS="$LDFLAGS $WINIDN_LDFLAGS" + LIBS="$WINIDN_LIBS $LIBS" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if IdnToUnicode can be linked" >&5 +printf %s "checking if IdnToUnicode can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + #include + +int main (void) +{ + + IdnToUnicode(0, NULL, 0, NULL, 0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_winidn="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_winidn="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_winidn" = "yes"; then + +printf "%s\n" "#define USE_WIN32_IDN 1" >>confdefs.h + + IDN_ENABLED=1 + + curl_idn_msg="enabled (Windows-native)" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: Cannot find libraries for IDN support: IDN disabled" >&5 +printf "%s\n" "$as_me: WARNING: Cannot find libraries for IDN support: IDN disabled" >&2;} + CFLAGS="$clean_CFLAGS" + CPPFLAGS="$clean_CPPFLAGS" + LDFLAGS="$clean_LDFLAGS" + LIBS="$clean_LIBS" + fi +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to build with libidn2" >&5 +printf %s "checking whether to build with libidn2... " >&6; } +OPT_IDN="default" + +# Check whether --with-libidn2 was given. +if test ${with_libidn2+y} +then : + withval=$with_libidn2; OPT_IDN=$withval +fi + +if test "x$tst_links_winidn" = "xyes"; then + want_idn="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no (using winidn instead)" >&5 +printf "%s\n" "no (using winidn instead)" >&6; } +else + case "$OPT_IDN" in + no) + want_idn="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + default) + want_idn="yes" + want_idn_path="default" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: (assumed) yes" >&5 +printf "%s\n" "(assumed) yes" >&6; } + ;; + yes) + want_idn="yes" + want_idn_path="default" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + *) + want_idn="yes" + want_idn_path="$withval" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes ($withval)" >&5 +printf "%s\n" "yes ($withval)" >&6; } + ;; + esac +fi + +if test "$want_idn" = "yes"; then + clean_CPPFLAGS="$CPPFLAGS" + clean_LDFLAGS="$LDFLAGS" + clean_LIBS="$LIBS" + PKGCONFIG="no" + # + if test "$want_idn_path" != "default"; then + IDN_PCDIR="$want_idn_path/lib$libsuff/pkgconfig" + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libidn2 options with pkg-config" >&5 +printf %s "checking for libidn2 options with pkg-config... " >&6; } + itexists=` + if test -n "$IDN_PCDIR"; then + PKG_CONFIG_LIBDIR="$IDN_PCDIR" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists libidn2 >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + if test "$PKGCONFIG" != "no"; then + IDN_LIBS=` + if test -n "$IDN_PCDIR"; then + PKG_CONFIG_LIBDIR="$IDN_PCDIR" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --libs-only-l libidn2 2>/dev/null` + IDN_LDFLAGS=` + if test -n "$IDN_PCDIR"; then + PKG_CONFIG_LIBDIR="$IDN_PCDIR" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --libs-only-L libidn2 2>/dev/null` + IDN_CPPFLAGS=` + if test -n "$IDN_PCDIR"; then + PKG_CONFIG_LIBDIR="$IDN_PCDIR" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --cflags-only-I libidn2 2>/dev/null` + IDN_DIR=`echo $IDN_LDFLAGS | $SED -e 's/^-L//'` + else + IDN_LIBS="-lidn2" + IDN_LDFLAGS="-L$want_idn_path/lib$libsuff" + IDN_CPPFLAGS="-I$want_idn_path/include" + IDN_DIR="$want_idn_path/lib$libsuff" + fi + else + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libidn2 options with pkg-config" >&5 +printf %s "checking for libidn2 options with pkg-config... " >&6; } + itexists=` + if test -n ""; then + PKG_CONFIG_LIBDIR="" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists libidn2 >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + if test "$PKGCONFIG" != "no"; then + IDN_LIBS=`$PKGCONFIG --libs-only-l libidn2 2>/dev/null` + IDN_LDFLAGS=`$PKGCONFIG --libs-only-L libidn2 2>/dev/null` + IDN_CPPFLAGS=`$PKGCONFIG --cflags-only-I libidn2 2>/dev/null` + IDN_DIR=`echo $IDN_LDFLAGS | $SED -e 's/^-L//'` + else + IDN_LIBS="-lidn2" + fi + fi + # + if test "$PKGCONFIG" != "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: pkg-config: IDN_LIBS: \"$IDN_LIBS\"" >&5 +printf "%s\n" "$as_me: pkg-config: IDN_LIBS: \"$IDN_LIBS\"" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: pkg-config: IDN_LDFLAGS: \"$IDN_LDFLAGS\"" >&5 +printf "%s\n" "$as_me: pkg-config: IDN_LDFLAGS: \"$IDN_LDFLAGS\"" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: pkg-config: IDN_CPPFLAGS: \"$IDN_CPPFLAGS\"" >&5 +printf "%s\n" "$as_me: pkg-config: IDN_CPPFLAGS: \"$IDN_CPPFLAGS\"" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: pkg-config: IDN_DIR: \"$IDN_DIR\"" >&5 +printf "%s\n" "$as_me: pkg-config: IDN_DIR: \"$IDN_DIR\"" >&6;} + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: IDN_LIBS: \"$IDN_LIBS\"" >&5 +printf "%s\n" "$as_me: IDN_LIBS: \"$IDN_LIBS\"" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: IDN_LDFLAGS: \"$IDN_LDFLAGS\"" >&5 +printf "%s\n" "$as_me: IDN_LDFLAGS: \"$IDN_LDFLAGS\"" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: IDN_CPPFLAGS: \"$IDN_CPPFLAGS\"" >&5 +printf "%s\n" "$as_me: IDN_CPPFLAGS: \"$IDN_CPPFLAGS\"" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: IDN_DIR: \"$IDN_DIR\"" >&5 +printf "%s\n" "$as_me: IDN_DIR: \"$IDN_DIR\"" >&6;} + fi + # + CPPFLAGS="$CPPFLAGS $IDN_CPPFLAGS" + LDFLAGS="$LDFLAGS $IDN_LDFLAGS" + LIBS="$IDN_LIBS $LIBS" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if idn2_lookup_ul can be linked" >&5 +printf %s "checking if idn2_lookup_ul can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define idn2_lookup_ul innocuous_idn2_lookup_ul +#ifdef __STDC__ +# include +#else +# include +#endif +#undef idn2_lookup_ul +#ifdef __cplusplus +extern "C" +#endif +char idn2_lookup_ul (); +#if defined __stub_idn2_lookup_ul || defined __stub___idn2_lookup_ul +choke me +#endif + +int main (void) +{ +return idn2_lookup_ul (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_libidn="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_libidn="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + ac_fn_c_check_header_compile "$LINENO" "idn2.h" "ac_cv_header_idn2_h" "$ac_includes_default" +if test "x$ac_cv_header_idn2_h" = xyes +then : + printf "%s\n" "#define HAVE_IDN2_H 1" >>confdefs.h + +fi + + + if test "$tst_links_libidn" = "yes"; then + +printf "%s\n" "#define HAVE_LIBIDN2 1" >>confdefs.h + + + IDN_ENABLED=1 + + curl_idn_msg="enabled (libidn2)" + if test -n "$IDN_DIR" -a "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$IDN_DIR" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $IDN_DIR to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $IDN_DIR to CURL_LIBRARY_PATH" >&6;} + fi + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: Cannot find libraries for IDN support: IDN disabled" >&5 +printf "%s\n" "$as_me: WARNING: Cannot find libraries for IDN support: IDN disabled" >&2;} + CPPFLAGS="$clean_CPPFLAGS" + LDFLAGS="$clean_LDFLAGS" + LIBS="$clean_LIBS" + fi +fi + + +OPT_H2="yes" + +if test "x$disable_http" = "xyes" -o X"$want_hyper" != Xno; then + # without HTTP or with Hyper, nghttp2 is no use + OPT_H2="no" +fi + + +# Check whether --with-nghttp2 was given. +if test ${with_nghttp2+y} +then : + withval=$with_nghttp2; OPT_H2=$withval +fi + +case "$OPT_H2" in + no) + want_nghttp2="no" + ;; + yes) + want_nghttp2="default" + want_nghttp2_path="" + want_nghttp2_pkg_config_path="" + ;; + *) + want_nghttp2="yes" + want_nghttp2_path="$withval" + want_nghttp2_pkg_config_path="$withval/lib/pkgconfig" + ;; +esac + +if test X"$want_nghttp2" != Xno; then + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libnghttp2 options with pkg-config" >&5 +printf %s "checking for libnghttp2 options with pkg-config... " >&6; } + itexists=` + if test -n "$want_nghttp2_pkg_config_path"; then + PKG_CONFIG_LIBDIR="$want_nghttp2_pkg_config_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists libnghttp2 >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + LIB_H2=` + if test -n "$want_nghttp2_pkg_config_path"; then + PKG_CONFIG_LIBDIR="$want_nghttp2_pkg_config_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-l libnghttp2` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -l is $LIB_H2" >&5 +printf "%s\n" "$as_me: -l is $LIB_H2" >&6;} + + CPP_H2=` + if test -n "$want_nghttp2_pkg_config_path"; then + PKG_CONFIG_LIBDIR="$want_nghttp2_pkg_config_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --cflags-only-I libnghttp2` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -I is $CPP_H2" >&5 +printf "%s\n" "$as_me: -I is $CPP_H2" >&6;} + + LD_H2=` + if test -n "$want_nghttp2_pkg_config_path"; then + PKG_CONFIG_LIBDIR="$want_nghttp2_pkg_config_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-L libnghttp2` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -L is $LD_H2" >&5 +printf "%s\n" "$as_me: -L is $LD_H2" >&6;} + + DIR_H2=`echo $LD_H2 | $SED -e 's/^-L//'` + elif test x"$want_nghttp2_path" != x; then + LIB_H2="-lnghttp2" + LD_H2=-L${want_nghttp2_path}/lib$libsuff + CPP_H2=-I${want_nghttp2_path}/include + DIR_H2=${want_nghttp2_path}/lib$libsuff + elif test X"$want_nghttp2" != Xdefault; then + as_fn_error $? "--with-nghttp2 was specified but could not find libnghttp2 pkg-config file." "$LINENO" 5 + else + LIB_H2="-lnghttp2" + fi + + LDFLAGS="$LDFLAGS $LD_H2" + CPPFLAGS="$CPPFLAGS $CPP_H2" + LIBS="$LIB_H2 $LIBS" + + # use nghttp2_session_get_stream_local_window_size to require nghttp2 + # >= 1.15.0 + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for nghttp2_session_get_stream_local_window_size in -lnghttp2" >&5 +printf %s "checking for nghttp2_session_get_stream_local_window_size in -lnghttp2... " >&6; } +if test ${ac_cv_lib_nghttp2_nghttp2_session_get_stream_local_window_size+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lnghttp2 $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char nghttp2_session_get_stream_local_window_size (); +int main (void) +{ +return nghttp2_session_get_stream_local_window_size (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_nghttp2_nghttp2_session_get_stream_local_window_size=yes +else $as_nop + ac_cv_lib_nghttp2_nghttp2_session_get_stream_local_window_size=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_nghttp2_nghttp2_session_get_stream_local_window_size" >&5 +printf "%s\n" "$ac_cv_lib_nghttp2_nghttp2_session_get_stream_local_window_size" >&6; } +if test "x$ac_cv_lib_nghttp2_nghttp2_session_get_stream_local_window_size" = xyes +then : + + for ac_header in nghttp2/nghttp2.h +do : + ac_fn_c_check_header_compile "$LINENO" "nghttp2/nghttp2.h" "ac_cv_header_nghttp2_nghttp2_h" "$ac_includes_default" +if test "x$ac_cv_header_nghttp2_nghttp2_h" = xyes +then : + printf "%s\n" "#define HAVE_NGHTTP2_NGHTTP2_H 1" >>confdefs.h + curl_h2_msg="enabled (nghttp2)" + NGHTTP2_ENABLED=1 + +printf "%s\n" "#define USE_NGHTTP2 1" >>confdefs.h + + USE_NGHTTP2=1 + + +fi + +done + + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_H2" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $DIR_H2 to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $DIR_H2 to CURL_LIBRARY_PATH" >&6;} + +else $as_nop + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + +fi + +fi + + +OPT_TCP2="no" + +if test "x$disable_http" = "xyes"; then + # without HTTP, ngtcp2 is no use + OPT_TCP2="no" +fi + + +# Check whether --with-ngtcp2 was given. +if test ${with_ngtcp2+y} +then : + withval=$with_ngtcp2; OPT_TCP2=$withval +fi + +case "$OPT_TCP2" in + no) + want_tcp2="no" + ;; + yes) + want_tcp2="default" + want_tcp2_path="" + ;; + *) + want_tcp2="yes" + want_tcp2_path="$withval/lib/pkgconfig" + ;; +esac + +curl_tcp2_msg="no (--with-ngtcp2)" +if test X"$want_tcp2" != Xno; then + + if test "$QUIC_ENABLED" != "yes"; then + as_fn_error $? "the detected TLS library does not support QUIC, making --with-ngtcp2 a no-no" "$LINENO" 5 + fi + + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libngtcp2 options with pkg-config" >&5 +printf %s "checking for libngtcp2 options with pkg-config... " >&6; } + itexists=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists libngtcp2 >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + LIB_TCP2=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-l libngtcp2` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -l is $LIB_TCP2" >&5 +printf "%s\n" "$as_me: -l is $LIB_TCP2" >&6;} + + CPP_TCP2=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --cflags-only-I libngtcp2` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -I is $CPP_TCP2" >&5 +printf "%s\n" "$as_me: -I is $CPP_TCP2" >&6;} + + LD_TCP2=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-L libngtcp2` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -L is $LD_TCP2" >&5 +printf "%s\n" "$as_me: -L is $LD_TCP2" >&6;} + + LDFLAGS="$LDFLAGS $LD_TCP2" + CPPFLAGS="$CPPFLAGS $CPP_TCP2" + LIBS="$LIB_TCP2 $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_TCP2=`echo $LD_TCP2 | $SED -e 's/^-L//'` + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ngtcp2_conn_client_new_versioned in -lngtcp2" >&5 +printf %s "checking for ngtcp2_conn_client_new_versioned in -lngtcp2... " >&6; } +if test ${ac_cv_lib_ngtcp2_ngtcp2_conn_client_new_versioned+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lngtcp2 $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char ngtcp2_conn_client_new_versioned (); +int main (void) +{ +return ngtcp2_conn_client_new_versioned (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_ngtcp2_ngtcp2_conn_client_new_versioned=yes +else $as_nop + ac_cv_lib_ngtcp2_ngtcp2_conn_client_new_versioned=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ngtcp2_ngtcp2_conn_client_new_versioned" >&5 +printf "%s\n" "$ac_cv_lib_ngtcp2_ngtcp2_conn_client_new_versioned" >&6; } +if test "x$ac_cv_lib_ngtcp2_ngtcp2_conn_client_new_versioned" = xyes +then : + + for ac_header in ngtcp2/ngtcp2.h +do : + ac_fn_c_check_header_compile "$LINENO" "ngtcp2/ngtcp2.h" "ac_cv_header_ngtcp2_ngtcp2_h" "$ac_includes_default" +if test "x$ac_cv_header_ngtcp2_ngtcp2_h" = xyes +then : + printf "%s\n" "#define HAVE_NGTCP2_NGTCP2_H 1" >>confdefs.h + NGTCP2_ENABLED=1 + +printf "%s\n" "#define USE_NGTCP2 1" >>confdefs.h + + USE_NGTCP2=1 + + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_TCP2" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $DIR_TCP2 to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $DIR_TCP2 to CURL_LIBRARY_PATH" >&6;} + +fi + +done + +else $as_nop + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + +fi + + + else + if test X"$want_tcp2" != Xdefault; then + as_fn_error $? "--with-ngtcp2 was specified but could not find ngtcp2 pkg-config file." "$LINENO" 5 + fi + fi + +fi + +if test "x$NGTCP2_ENABLED" = "x1" -a "x$OPENSSL_ENABLED" = "x1" -a "x$OPENSSL_IS_BORINGSSL" != "x1"; then + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libngtcp2_crypto_quictls options with pkg-config" >&5 +printf %s "checking for libngtcp2_crypto_quictls options with pkg-config... " >&6; } + itexists=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists libngtcp2_crypto_quictls >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + LIB_NGTCP2_CRYPTO_QUICTLS=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-l libngtcp2_crypto_quictls` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -l is $LIB_NGTCP2_CRYPTO_QUICTLS" >&5 +printf "%s\n" "$as_me: -l is $LIB_NGTCP2_CRYPTO_QUICTLS" >&6;} + + CPP_NGTCP2_CRYPTO_QUICTLS=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --cflags-only-I libngtcp2_crypto_quictls` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -I is $CPP_NGTCP2_CRYPTO_QUICTLS" >&5 +printf "%s\n" "$as_me: -I is $CPP_NGTCP2_CRYPTO_QUICTLS" >&6;} + + LD_NGTCP2_CRYPTO_QUICTLS=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-L libngtcp2_crypto_quictls` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -L is $LD_NGTCP2_CRYPTO_QUICTLS" >&5 +printf "%s\n" "$as_me: -L is $LD_NGTCP2_CRYPTO_QUICTLS" >&6;} + + LDFLAGS="$LDFLAGS $LD_NGTCP2_CRYPTO_QUICTLS" + CPPFLAGS="$CPPFLAGS $CPP_NGTCP2_CRYPTO_QUICTLS" + LIBS="$LIB_NGTCP2_CRYPTO_QUICTLS $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_NGTCP2_CRYPTO_QUICTLS=`echo $LD_NGTCP2_CRYPTO_QUICTLS | $SED -e 's/^-L//'` + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ngtcp2_crypto_recv_client_initial_cb in -lngtcp2_crypto_quictls" >&5 +printf %s "checking for ngtcp2_crypto_recv_client_initial_cb in -lngtcp2_crypto_quictls... " >&6; } +if test ${ac_cv_lib_ngtcp2_crypto_quictls_ngtcp2_crypto_recv_client_initial_cb+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lngtcp2_crypto_quictls $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char ngtcp2_crypto_recv_client_initial_cb (); +int main (void) +{ +return ngtcp2_crypto_recv_client_initial_cb (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_ngtcp2_crypto_quictls_ngtcp2_crypto_recv_client_initial_cb=yes +else $as_nop + ac_cv_lib_ngtcp2_crypto_quictls_ngtcp2_crypto_recv_client_initial_cb=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ngtcp2_crypto_quictls_ngtcp2_crypto_recv_client_initial_cb" >&5 +printf "%s\n" "$ac_cv_lib_ngtcp2_crypto_quictls_ngtcp2_crypto_recv_client_initial_cb" >&6; } +if test "x$ac_cv_lib_ngtcp2_crypto_quictls_ngtcp2_crypto_recv_client_initial_cb" = xyes +then : + + for ac_header in ngtcp2/ngtcp2_crypto.h +do : + ac_fn_c_check_header_compile "$LINENO" "ngtcp2/ngtcp2_crypto.h" "ac_cv_header_ngtcp2_ngtcp2_crypto_h" "$ac_includes_default" +if test "x$ac_cv_header_ngtcp2_ngtcp2_crypto_h" = xyes +then : + printf "%s\n" "#define HAVE_NGTCP2_NGTCP2_CRYPTO_H 1" >>confdefs.h + NGTCP2_ENABLED=1 + +printf "%s\n" "#define USE_NGTCP2_CRYPTO_QUICTLS 1" >>confdefs.h + + USE_NGTCP2_CRYPTO_QUICTLS=1 + + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_NGTCP2_CRYPTO_QUICTLS" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $DIR_NGTCP2_CRYPTO_QUICTLS to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $DIR_NGTCP2_CRYPTO_QUICTLS to CURL_LIBRARY_PATH" >&6;} + +fi + +done + +else $as_nop + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + +fi + + + else + if test X"$want_tcp2" != Xdefault; then + as_fn_error $? "--with-ngtcp2 was specified but could not find ngtcp2_crypto_quictls pkg-config file." "$LINENO" 5 + fi + fi +fi + +if test "x$NGTCP2_ENABLED" = "x1" -a "x$OPENSSL_ENABLED" = "x1" -a "x$OPENSSL_IS_BORINGSSL" = "x1"; then + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libngtcp2_crypto_boringssl options with pkg-config" >&5 +printf %s "checking for libngtcp2_crypto_boringssl options with pkg-config... " >&6; } + itexists=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists libngtcp2_crypto_boringssl >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + LIB_NGTCP2_CRYPTO_BORINGSSL=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-l libngtcp2_crypto_boringssl` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -l is $LIB_NGTCP2_CRYPTO_BORINGSSL" >&5 +printf "%s\n" "$as_me: -l is $LIB_NGTCP2_CRYPTO_BORINGSSL" >&6;} + + CPP_NGTCP2_CRYPTO_BORINGSSL=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --cflags-only-I libngtcp2_crypto_boringssl` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -I is $CPP_NGTCP2_CRYPTO_BORINGSSL" >&5 +printf "%s\n" "$as_me: -I is $CPP_NGTCP2_CRYPTO_BORINGSSL" >&6;} + + LD_NGTCP2_CRYPTO_BORINGSSL=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-L libngtcp2_crypto_boringssl` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -L is $LD_NGTCP2_CRYPTO_BORINGSSL" >&5 +printf "%s\n" "$as_me: -L is $LD_NGTCP2_CRYPTO_BORINGSSL" >&6;} + + LDFLAGS="$LDFLAGS $LD_NGTCP2_CRYPTO_BORINGSSL" + CPPFLAGS="$CPPFLAGS $CPP_NGTCP2_CRYPTO_BORINGSSL" + LIBS="$LIB_NGTCP2_CRYPTO_BORINGSSL $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_NGTCP2_CRYPTO_BORINGSSL=`echo $LD_NGTCP2_CRYPTO_BORINGSSL | $SED -e 's/^-L//'` + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ngtcp2_crypto_recv_client_initial_cb in -lngtcp2_crypto_boringssl" >&5 +printf %s "checking for ngtcp2_crypto_recv_client_initial_cb in -lngtcp2_crypto_boringssl... " >&6; } +if test ${ac_cv_lib_ngtcp2_crypto_boringssl_ngtcp2_crypto_recv_client_initial_cb+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lngtcp2_crypto_boringssl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char ngtcp2_crypto_recv_client_initial_cb (); +int main (void) +{ +return ngtcp2_crypto_recv_client_initial_cb (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_ngtcp2_crypto_boringssl_ngtcp2_crypto_recv_client_initial_cb=yes +else $as_nop + ac_cv_lib_ngtcp2_crypto_boringssl_ngtcp2_crypto_recv_client_initial_cb=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ngtcp2_crypto_boringssl_ngtcp2_crypto_recv_client_initial_cb" >&5 +printf "%s\n" "$ac_cv_lib_ngtcp2_crypto_boringssl_ngtcp2_crypto_recv_client_initial_cb" >&6; } +if test "x$ac_cv_lib_ngtcp2_crypto_boringssl_ngtcp2_crypto_recv_client_initial_cb" = xyes +then : + + for ac_header in ngtcp2/ngtcp2_crypto.h +do : + ac_fn_c_check_header_compile "$LINENO" "ngtcp2/ngtcp2_crypto.h" "ac_cv_header_ngtcp2_ngtcp2_crypto_h" "$ac_includes_default" +if test "x$ac_cv_header_ngtcp2_ngtcp2_crypto_h" = xyes +then : + printf "%s\n" "#define HAVE_NGTCP2_NGTCP2_CRYPTO_H 1" >>confdefs.h + NGTCP2_ENABLED=1 + +printf "%s\n" "#define USE_NGTCP2_CRYPTO_BORINGSSL 1" >>confdefs.h + + USE_NGTCP2_CRYPTO_BORINGSSL=1 + + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_NGTCP2_CRYPTO_BORINGSSL" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $DIR_NGTCP2_CRYPTO_BORINGSSL to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $DIR_NGTCP2_CRYPTO_BORINGSSL to CURL_LIBRARY_PATH" >&6;} + +fi + +done + +else $as_nop + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + +fi + + + else + if test X"$want_tcp2" != Xdefault; then + as_fn_error $? "--with-ngtcp2 was specified but could not find ngtcp2_crypto_boringssl pkg-config file." "$LINENO" 5 + fi + fi +fi + +if test "x$NGTCP2_ENABLED" = "x1" -a "x$GNUTLS_ENABLED" = "x1"; then + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libngtcp2_crypto_gnutls options with pkg-config" >&5 +printf %s "checking for libngtcp2_crypto_gnutls options with pkg-config... " >&6; } + itexists=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists libngtcp2_crypto_gnutls >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + LIB_NGTCP2_CRYPTO_GNUTLS=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-l libngtcp2_crypto_gnutls` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -l is $LIB_NGTCP2_CRYPTO_GNUTLS" >&5 +printf "%s\n" "$as_me: -l is $LIB_NGTCP2_CRYPTO_GNUTLS" >&6;} + + CPP_NGTCP2_CRYPTO_GNUTLS=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --cflags-only-I libngtcp2_crypto_gnutls` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -I is $CPP_NGTCP2_CRYPTO_GNUTLS" >&5 +printf "%s\n" "$as_me: -I is $CPP_NGTCP2_CRYPTO_GNUTLS" >&6;} + + LD_NGTCP2_CRYPTO_GNUTLS=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-L libngtcp2_crypto_gnutls` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -L is $LD_NGTCP2_CRYPTO_GNUTLS" >&5 +printf "%s\n" "$as_me: -L is $LD_NGTCP2_CRYPTO_GNUTLS" >&6;} + + LDFLAGS="$LDFLAGS $LD_NGTCP2_CRYPTO_GNUTLS" + CPPFLAGS="$CPPFLAGS $CPP_NGTCP2_CRYPTO_GNUTLS" + LIBS="$LIB_NGTCP2_CRYPTO_GNUTLS $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_NGTCP2_CRYPTO_GNUTLS=`echo $LD_NGTCP2_CRYPTO_GNUTLS | $SED -e 's/^-L//'` + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ngtcp2_crypto_recv_client_initial_cb in -lngtcp2_crypto_gnutls" >&5 +printf %s "checking for ngtcp2_crypto_recv_client_initial_cb in -lngtcp2_crypto_gnutls... " >&6; } +if test ${ac_cv_lib_ngtcp2_crypto_gnutls_ngtcp2_crypto_recv_client_initial_cb+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lngtcp2_crypto_gnutls $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char ngtcp2_crypto_recv_client_initial_cb (); +int main (void) +{ +return ngtcp2_crypto_recv_client_initial_cb (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_ngtcp2_crypto_gnutls_ngtcp2_crypto_recv_client_initial_cb=yes +else $as_nop + ac_cv_lib_ngtcp2_crypto_gnutls_ngtcp2_crypto_recv_client_initial_cb=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ngtcp2_crypto_gnutls_ngtcp2_crypto_recv_client_initial_cb" >&5 +printf "%s\n" "$ac_cv_lib_ngtcp2_crypto_gnutls_ngtcp2_crypto_recv_client_initial_cb" >&6; } +if test "x$ac_cv_lib_ngtcp2_crypto_gnutls_ngtcp2_crypto_recv_client_initial_cb" = xyes +then : + + for ac_header in ngtcp2/ngtcp2_crypto.h +do : + ac_fn_c_check_header_compile "$LINENO" "ngtcp2/ngtcp2_crypto.h" "ac_cv_header_ngtcp2_ngtcp2_crypto_h" "$ac_includes_default" +if test "x$ac_cv_header_ngtcp2_ngtcp2_crypto_h" = xyes +then : + printf "%s\n" "#define HAVE_NGTCP2_NGTCP2_CRYPTO_H 1" >>confdefs.h + NGTCP2_ENABLED=1 + +printf "%s\n" "#define USE_NGTCP2_CRYPTO_GNUTLS 1" >>confdefs.h + + USE_NGTCP2_CRYPTO_GNUTLS=1 + + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_NGTCP2_CRYPTO_GNUTLS" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $DIR_NGTCP2_CRYPTO_GNUTLS to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $DIR_NGTCP2_CRYPTO_GNUTLS to CURL_LIBRARY_PATH" >&6;} + +fi + +done + +else $as_nop + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + +fi + + + else + if test X"$want_tcp2" != Xdefault; then + as_fn_error $? "--with-ngtcp2 was specified but could not find ngtcp2_crypto_gnutls pkg-config file." "$LINENO" 5 + fi + fi +fi + +if test "x$NGTCP2_ENABLED" = "x1" -a "x$WOLFSSL_ENABLED" = "x1"; then + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libngtcp2_crypto_wolfssl options with pkg-config" >&5 +printf %s "checking for libngtcp2_crypto_wolfssl options with pkg-config... " >&6; } + itexists=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists libngtcp2_crypto_wolfssl >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + LIB_NGTCP2_CRYPTO_WOLFSSL=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-l libngtcp2_crypto_wolfssl` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -l is $LIB_NGTCP2_CRYPTO_WOLFSSL" >&5 +printf "%s\n" "$as_me: -l is $LIB_NGTCP2_CRYPTO_WOLFSSL" >&6;} + + CPP_NGTCP2_CRYPTO_WOLFSSL=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --cflags-only-I libngtcp2_crypto_wolfssl` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -I is $CPP_NGTCP2_CRYPTO_WOLFSSL" >&5 +printf "%s\n" "$as_me: -I is $CPP_NGTCP2_CRYPTO_WOLFSSL" >&6;} + + LD_NGTCP2_CRYPTO_WOLFSSL=` + if test -n "$want_tcp2_path"; then + PKG_CONFIG_LIBDIR="$want_tcp2_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-L libngtcp2_crypto_wolfssl` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -L is $LD_NGTCP2_CRYPTO_WOLFSSL" >&5 +printf "%s\n" "$as_me: -L is $LD_NGTCP2_CRYPTO_WOLFSSL" >&6;} + + LDFLAGS="$LDFLAGS $LD_NGTCP2_CRYPTO_WOLFSSL" + CPPFLAGS="$CPPFLAGS $CPP_NGTCP2_CRYPTO_WOLFSSL" + LIBS="$LIB_NGTCP2_CRYPTO_WOLFSSL $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_NGTCP2_CRYPTO_WOLFSSL=`echo $LD_NGTCP2_CRYPTO_WOLFSSL | $SED -e 's/^-L//'` + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ngtcp2_crypto_recv_client_initial_cb in -lngtcp2_crypto_wolfssl" >&5 +printf %s "checking for ngtcp2_crypto_recv_client_initial_cb in -lngtcp2_crypto_wolfssl... " >&6; } +if test ${ac_cv_lib_ngtcp2_crypto_wolfssl_ngtcp2_crypto_recv_client_initial_cb+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lngtcp2_crypto_wolfssl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char ngtcp2_crypto_recv_client_initial_cb (); +int main (void) +{ +return ngtcp2_crypto_recv_client_initial_cb (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_ngtcp2_crypto_wolfssl_ngtcp2_crypto_recv_client_initial_cb=yes +else $as_nop + ac_cv_lib_ngtcp2_crypto_wolfssl_ngtcp2_crypto_recv_client_initial_cb=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ngtcp2_crypto_wolfssl_ngtcp2_crypto_recv_client_initial_cb" >&5 +printf "%s\n" "$ac_cv_lib_ngtcp2_crypto_wolfssl_ngtcp2_crypto_recv_client_initial_cb" >&6; } +if test "x$ac_cv_lib_ngtcp2_crypto_wolfssl_ngtcp2_crypto_recv_client_initial_cb" = xyes +then : + + for ac_header in ngtcp2/ngtcp2_crypto.h +do : + ac_fn_c_check_header_compile "$LINENO" "ngtcp2/ngtcp2_crypto.h" "ac_cv_header_ngtcp2_ngtcp2_crypto_h" "$ac_includes_default" +if test "x$ac_cv_header_ngtcp2_ngtcp2_crypto_h" = xyes +then : + printf "%s\n" "#define HAVE_NGTCP2_NGTCP2_CRYPTO_H 1" >>confdefs.h + NGTCP2_ENABLED=1 + +printf "%s\n" "#define USE_NGTCP2_CRYPTO_WOLFSSL 1" >>confdefs.h + + USE_NGTCP2_CRYPTO_WOLFSSL=1 + + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_NGTCP2_CRYPTO_WOLFSSL" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $DIR_NGTCP2_CRYPTO_WOLFSSL to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $DIR_NGTCP2_CRYPTO_WOLFSSL to CURL_LIBRARY_PATH" >&6;} + +fi + +done + +else $as_nop + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + +fi + + + else + if test X"$want_tcp2" != Xdefault; then + as_fn_error $? "--with-ngtcp2 was specified but could not find ngtcp2_crypto_wolfssl pkg-config file." "$LINENO" 5 + fi + fi +fi + + +OPT_OPENSSL_QUIC="no" + +if test "x$disable_http" = "xyes" -o "x$OPENSSL_ENABLED" != "x1"; then + # without HTTP or without openssl, no use + OPT_OPENSSL_QUIC="no" +fi + + +# Check whether --with-openssl-quic was given. +if test ${with_openssl_quic+y} +then : + withval=$with_openssl_quic; OPT_OPENSSL_QUIC=$withval +fi + +case "$OPT_OPENSSL_QUIC" in + no) + want_openssl_quic="no" + ;; + yes) + want_openssl_quic="yes" + ;; +esac + +curl_openssl_quic_msg="no (--with-openssl-quic)" +if test "x$want_openssl_quic" = "xyes"; then + + if test "$NGTCP2_ENABLED" = 1; then + as_fn_error $? "--with-openssl-quic and --with-ngtcp2 are mutually exclusive" "$LINENO" 5 + fi + if test "$HAVE_OPENSSL_QUIC" != 1; then + as_fn_error $? "--with-openssl-quic requires quic support in OpenSSL" "$LINENO" 5 + fi + +printf "%s\n" "#define USE_OPENSSL_QUIC 1" >>confdefs.h + + USE_OPENSSL_QUIC=1 + +fi + + +OPT_NGHTTP3="yes" + +if test "x$USE_NGTCP2" != "x1" -a "x$USE_OPENSSL_QUIC" != "x1"; then + # without ngtcp2 or openssl quic, nghttp3 is of no use for us + OPT_NGHTTP3="no" + want_nghttp3="no" +fi + + +# Check whether --with-nghttp3 was given. +if test ${with_nghttp3+y} +then : + withval=$with_nghttp3; OPT_NGHTTP3=$withval +fi + +case "$OPT_NGHTTP3" in + no) + want_nghttp3="no" + ;; + yes) + want_nghttp3="default" + want_nghttp3_path="" + ;; + *) + want_nghttp3="yes" + want_nghttp3_path="$withval/lib/pkgconfig" + ;; +esac + +curl_http3_msg="no (--with-nghttp3)" +if test X"$want_nghttp3" != Xno; then + + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libnghttp3 options with pkg-config" >&5 +printf %s "checking for libnghttp3 options with pkg-config... " >&6; } + itexists=` + if test -n "$want_nghttp3_path"; then + PKG_CONFIG_LIBDIR="$want_nghttp3_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists libnghttp3 >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + LIB_NGHTTP3=` + if test -n "$want_nghttp3_path"; then + PKG_CONFIG_LIBDIR="$want_nghttp3_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-l libnghttp3` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -l is $LIB_NGHTTP3" >&5 +printf "%s\n" "$as_me: -l is $LIB_NGHTTP3" >&6;} + + CPP_NGHTTP3=` + if test -n "$want_nghttp3_path"; then + PKG_CONFIG_LIBDIR="$want_nghttp3_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --cflags-only-I libnghttp3` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -I is $CPP_NGHTTP3" >&5 +printf "%s\n" "$as_me: -I is $CPP_NGHTTP3" >&6;} + + LD_NGHTTP3=` + if test -n "$want_nghttp3_path"; then + PKG_CONFIG_LIBDIR="$want_nghttp3_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-L libnghttp3` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -L is $LD_NGHTTP3" >&5 +printf "%s\n" "$as_me: -L is $LD_NGHTTP3" >&6;} + + LDFLAGS="$LDFLAGS $LD_NGHTTP3" + CPPFLAGS="$CPPFLAGS $CPP_NGHTTP3" + LIBS="$LIB_NGHTTP3 $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_NGHTTP3=`echo $LD_NGHTTP3 | $SED -e 's/^-L//'` + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for nghttp3_conn_client_new_versioned in -lnghttp3" >&5 +printf %s "checking for nghttp3_conn_client_new_versioned in -lnghttp3... " >&6; } +if test ${ac_cv_lib_nghttp3_nghttp3_conn_client_new_versioned+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lnghttp3 $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char nghttp3_conn_client_new_versioned (); +int main (void) +{ +return nghttp3_conn_client_new_versioned (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_nghttp3_nghttp3_conn_client_new_versioned=yes +else $as_nop + ac_cv_lib_nghttp3_nghttp3_conn_client_new_versioned=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_nghttp3_nghttp3_conn_client_new_versioned" >&5 +printf "%s\n" "$ac_cv_lib_nghttp3_nghttp3_conn_client_new_versioned" >&6; } +if test "x$ac_cv_lib_nghttp3_nghttp3_conn_client_new_versioned" = xyes +then : + + for ac_header in nghttp3/nghttp3.h +do : + ac_fn_c_check_header_compile "$LINENO" "nghttp3/nghttp3.h" "ac_cv_header_nghttp3_nghttp3_h" "$ac_includes_default" +if test "x$ac_cv_header_nghttp3_nghttp3_h" = xyes +then : + printf "%s\n" "#define HAVE_NGHTTP3_NGHTTP3_H 1" >>confdefs.h + +printf "%s\n" "#define USE_NGHTTP3 1" >>confdefs.h + + USE_NGHTTP3=1 + + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_NGHTTP3" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $DIR_NGHTTP3 to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $DIR_NGHTTP3 to CURL_LIBRARY_PATH" >&6;} + +fi + +done + +else $as_nop + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + +fi + + + else + if test X"$want_nghttp3" != Xdefault; then + as_fn_error $? "--with-nghttp3 was specified but could not find nghttp3 pkg-config file." "$LINENO" 5 + fi + fi + +fi + + +if test "x$NGTCP2_ENABLED" = "x1" -a "x$USE_NGHTTP3" = "x1"; then + +printf "%s\n" "#define USE_NGTCP2_H3 1" >>confdefs.h + + USE_NGTCP2_H3=1 + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: HTTP3 support is experimental" >&5 +printf "%s\n" "$as_me: HTTP3 support is experimental" >&6;} + curl_h3_msg="enabled (ngtcp2 + nghttp3)" +fi + + +if test "x$USE_OPENSSL_QUIC" = "x1" -a "x$USE_NGHTTP3" = "x1"; then + experimental="$experimental HTTP3" + +printf "%s\n" "#define USE_OPENSSL_H3 1" >>confdefs.h + + USE_OPENSSL_H3=1 + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: HTTP3 support is experimental" >&5 +printf "%s\n" "$as_me: HTTP3 support is experimental" >&6;} + curl_h3_msg="enabled (openssl + nghttp3)" +fi + + +OPT_QUICHE="no" + +if test "x$disable_http" = "xyes" -o "x$USE_NGTCP" = "x1"; then + # without HTTP or with ngtcp2, quiche is no use + OPT_QUICHE="no" +fi + + +# Check whether --with-quiche was given. +if test ${with_quiche+y} +then : + withval=$with_quiche; OPT_QUICHE=$withval +fi + +case "$OPT_QUICHE" in + no) + want_quiche="no" + ;; + yes) + want_quiche="default" + want_quiche_path="" + ;; + *) + want_quiche="yes" + want_quiche_path="$withval" + ;; +esac + +if test X"$want_quiche" != Xno; then + + if test "$QUIC_ENABLED" != "yes"; then + as_fn_error $? "the detected TLS library does not support QUIC, making --with-quiche a no-no" "$LINENO" 5 + fi + + if test "$NGHTTP3_ENABLED" = 1; then + as_fn_error $? "--with-quiche and --with-ngtcp2 are mutually exclusive" "$LINENO" 5 + fi + + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for quiche options with pkg-config" >&5 +printf %s "checking for quiche options with pkg-config... " >&6; } + itexists=` + if test -n "$want_quiche_path"; then + PKG_CONFIG_LIBDIR="$want_quiche_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists quiche >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + + if test "$PKGCONFIG" != "no" ; then + LIB_QUICHE=` + if test -n "$want_quiche_path"; then + PKG_CONFIG_LIBDIR="$want_quiche_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-l quiche` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -l is $LIB_QUICHE" >&5 +printf "%s\n" "$as_me: -l is $LIB_QUICHE" >&6;} + + CPP_QUICHE=` + if test -n "$want_quiche_path"; then + PKG_CONFIG_LIBDIR="$want_quiche_path" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --cflags-only-I quiche` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -I is $CPP_QUICHE" >&5 +printf "%s\n" "$as_me: -I is $CPP_QUICHE" >&6;} + + LD_QUICHE=` + if test -n "$want_quiche_path"; then + PKG_CONFIG_LIBDIR="$want_quiche_path" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-L quiche` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: -L is $LD_QUICHE" >&5 +printf "%s\n" "$as_me: -L is $LD_QUICHE" >&6;} + + LDFLAGS="$LDFLAGS $LD_QUICHE" + CPPFLAGS="$CPPFLAGS $CPP_QUICHE" + LIBS="$LIB_QUICHE $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_QUICHE=`echo $LD_QUICHE | $SED -e 's/^-L//'` + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for quiche_conn_send_ack_eliciting in -lquiche" >&5 +printf %s "checking for quiche_conn_send_ack_eliciting in -lquiche... " >&6; } +if test ${ac_cv_lib_quiche_quiche_conn_send_ack_eliciting+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lquiche $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char quiche_conn_send_ack_eliciting (); +int main (void) +{ +return quiche_conn_send_ack_eliciting (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_quiche_quiche_conn_send_ack_eliciting=yes +else $as_nop + ac_cv_lib_quiche_quiche_conn_send_ack_eliciting=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_quiche_quiche_conn_send_ack_eliciting" >&5 +printf "%s\n" "$ac_cv_lib_quiche_quiche_conn_send_ack_eliciting" >&6; } +if test "x$ac_cv_lib_quiche_quiche_conn_send_ack_eliciting" = xyes +then : + + for ac_header in quiche.h +do : + ac_fn_c_check_header_compile "$LINENO" "quiche.h" "ac_cv_header_quiche_h" " +$ac_includes_default +#include + + +" +if test "x$ac_cv_header_quiche_h" = xyes +then : + printf "%s\n" "#define HAVE_QUICHE_H 1" >>confdefs.h + experimental="$experimental HTTP3" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: HTTP3 support is experimental" >&5 +printf "%s\n" "$as_me: HTTP3 support is experimental" >&6;} + curl_h3_msg="enabled (quiche)" + QUICHE_ENABLED=1 + +printf "%s\n" "#define USE_QUICHE 1" >>confdefs.h + + USE_QUICHE=1 + + ac_fn_c_check_func "$LINENO" "quiche_conn_set_qlog_fd" "ac_cv_func_quiche_conn_set_qlog_fd" +if test "x$ac_cv_func_quiche_conn_set_qlog_fd" = xyes +then : + printf "%s\n" "#define HAVE_QUICHE_CONN_SET_QLOG_FD 1" >>confdefs.h + +fi + + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_QUICHE" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $DIR_QUICHE to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $DIR_QUICHE to CURL_LIBRARY_PATH" >&6;} +fi + +done + +else $as_nop + as_fn_error $? "couldn't use quiche" "$LINENO" 5 + +fi + + else + if test X"$want_quiche" != Xdefault; then + as_fn_error $? "--with-quiche was specified but could not find quiche pkg-config file." "$LINENO" 5 + fi + fi +fi + + +OPT_MSH3="no" + +if test "x$disable_http" = "xyes" -o "x$USE_NGTCP" = "x1"; then + # without HTTP or with ngtcp2, msh3 is no use + OPT_MSH3="no" +fi + + +# Check whether --with-msh3 was given. +if test ${with_msh3+y} +then : + withval=$with_msh3; OPT_MSH3=$withval +fi + +case "$OPT_MSH3" in + no) + want_msh3="no" + ;; + yes) + want_msh3="default" + want_msh3_path="" + ;; + *) + want_msh3="yes" + want_msh3_path="$withval" + ;; +esac + +if test X"$want_msh3" != Xno; then + + if test "$curl_cv_native_windows" != "yes"; then + if test "$QUIC_ENABLED" != "yes"; then + as_fn_error $? "the detected TLS library does not support QUIC, making --with-msh3 a no-no" "$LINENO" 5 + fi + if test "$OPENSSL_ENABLED" != "1"; then + as_fn_error $? "msh3 requires OpenSSL" "$LINENO" 5 + fi + fi + + if test "$NGHTTP3_ENABLED" = 1; then + as_fn_error $? "--with-msh3 and --with-ngtcp2 are mutually exclusive" "$LINENO" 5 + fi + if test "$QUICHE_ENABLED" = 1; then + as_fn_error $? "--with-msh3 and --with-quiche are mutually exclusive" "$LINENO" 5 + fi + + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + if test -n "$want_msh3_path"; then + LD_MSH3="-L$want_msh3_path/lib" + CPP_MSH3="-I$want_msh3_path/include" + DIR_MSH3="$want_msh3_path/lib" + LDFLAGS="$LDFLAGS $LD_MSH3" + CPPFLAGS="$CPPFLAGS $CPP_MSH3" + fi + LIBS="-lmsh3 $LIBS" + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for MsH3ApiOpen in -lmsh3" >&5 +printf %s "checking for MsH3ApiOpen in -lmsh3... " >&6; } +if test ${ac_cv_lib_msh3_MsH3ApiOpen+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lmsh3 $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char MsH3ApiOpen (); +int main (void) +{ +return MsH3ApiOpen (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_msh3_MsH3ApiOpen=yes +else $as_nop + ac_cv_lib_msh3_MsH3ApiOpen=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_msh3_MsH3ApiOpen" >&5 +printf "%s\n" "$ac_cv_lib_msh3_MsH3ApiOpen" >&6; } +if test "x$ac_cv_lib_msh3_MsH3ApiOpen" = xyes +then : + + for ac_header in msh3.h +do : + ac_fn_c_check_header_compile "$LINENO" "msh3.h" "ac_cv_header_msh3_h" "$ac_includes_default" +if test "x$ac_cv_header_msh3_h" = xyes +then : + printf "%s\n" "#define HAVE_MSH3_H 1" >>confdefs.h + curl_h3_msg="enabled (msh3)" + MSH3_ENABLED=1 + +printf "%s\n" "#define USE_MSH3 1" >>confdefs.h + + USE_MSH3=1 + + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_MSH3" + export CURL_LIBRARY_PATH + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Added $DIR_MSH3 to CURL_LIBRARY_PATH" >&5 +printf "%s\n" "$as_me: Added $DIR_MSH3 to CURL_LIBRARY_PATH" >&6;} +else $as_nop + experimental="$experimental HTTP3" + +fi + +done + +else $as_nop + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + +fi + +fi + + +OPT_ZSH_FPATH=default + +# Check whether --with-zsh-functions-dir was given. +if test ${with_zsh_functions_dir+y} +then : + withval=$with_zsh_functions_dir; OPT_ZSH_FPATH=$withval +fi + +case "$OPT_ZSH_FPATH" in + default|no) + ;; + yes) + ZSH_FUNCTIONS_DIR="$datarootdir/zsh/site-functions" + + ;; + *) + ZSH_FUNCTIONS_DIR="$withval" + + ;; +esac + if test x"$ZSH_FUNCTIONS_DIR" != x; then + USE_ZSH_COMPLETION_TRUE= + USE_ZSH_COMPLETION_FALSE='#' +else + USE_ZSH_COMPLETION_TRUE='#' + USE_ZSH_COMPLETION_FALSE= +fi + + + +OPT_FISH_FPATH=default + +# Check whether --with-fish-functions-dir was given. +if test ${with_fish_functions_dir+y} +then : + withval=$with_fish_functions_dir; OPT_FISH_FPATH=$withval +fi + +case "$OPT_FISH_FPATH" in + default|no) + ;; + yes) + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for fish options with pkg-config" >&5 +printf %s "checking for fish options with pkg-config... " >&6; } + itexists=` + if test -n ""; then + PKG_CONFIG_LIBDIR="" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists fish >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + if test "$PKGCONFIG" != "no" ; then + FISH_FUNCTIONS_DIR="$($PKGCONFIG --variable completionsdir fish)" + else + FISH_FUNCTIONS_DIR="$datarootdir/fish/vendor_completions.d" + fi + + ;; + *) + FISH_FUNCTIONS_DIR="$withval" + + ;; +esac + if test x"$FISH_FUNCTIONS_DIR" != x; then + USE_FISH_COMPLETION_TRUE= + USE_FISH_COMPLETION_FALSE='#' +else + USE_FISH_COMPLETION_TRUE='#' + USE_FISH_COMPLETION_FALSE= +fi + + +ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/time.h" "ac_cv_header_sys_time_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_sys_time_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TIME_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/select.h" "ac_cv_header_sys_select_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_sys_select_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_SELECT_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/socket.h" "ac_cv_header_sys_socket_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_sys_socket_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_SOCKET_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/ioctl.h" "ac_cv_header_sys_ioctl_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_sys_ioctl_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_IOCTL_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "unistd.h" "ac_cv_header_unistd_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_unistd_h" = xyes +then : + printf "%s\n" "#define HAVE_UNISTD_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_stdlib_h" = xyes +then : + printf "%s\n" "#define HAVE_STDLIB_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "arpa/inet.h" "ac_cv_header_arpa_inet_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_arpa_inet_h" = xyes +then : + printf "%s\n" "#define HAVE_ARPA_INET_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "net/if.h" "ac_cv_header_net_if_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_net_if_h" = xyes +then : + printf "%s\n" "#define HAVE_NET_IF_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "netinet/in.h" "ac_cv_header_netinet_in_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_netinet_in_h" = xyes +then : + printf "%s\n" "#define HAVE_NETINET_IN_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "netinet/in6.h" "ac_cv_header_netinet_in6_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_netinet_in6_h" = xyes +then : + printf "%s\n" "#define HAVE_NETINET_IN6_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/un.h" "ac_cv_header_sys_un_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_sys_un_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_UN_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "linux/tcp.h" "ac_cv_header_linux_tcp_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_linux_tcp_h" = xyes +then : + printf "%s\n" "#define HAVE_LINUX_TCP_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "netinet/tcp.h" "ac_cv_header_netinet_tcp_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_netinet_tcp_h" = xyes +then : + printf "%s\n" "#define HAVE_NETINET_TCP_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "netinet/udp.h" "ac_cv_header_netinet_udp_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_netinet_udp_h" = xyes +then : + printf "%s\n" "#define HAVE_NETINET_UDP_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "netdb.h" "ac_cv_header_netdb_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_netdb_h" = xyes +then : + printf "%s\n" "#define HAVE_NETDB_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/sockio.h" "ac_cv_header_sys_sockio_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_sys_sockio_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_SOCKIO_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/stat.h" "ac_cv_header_sys_stat_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_sys_stat_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_STAT_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/param.h" "ac_cv_header_sys_param_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_sys_param_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_PARAM_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "termios.h" "ac_cv_header_termios_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_termios_h" = xyes +then : + printf "%s\n" "#define HAVE_TERMIOS_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "termio.h" "ac_cv_header_termio_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_termio_h" = xyes +then : + printf "%s\n" "#define HAVE_TERMIO_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "fcntl.h" "ac_cv_header_fcntl_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_fcntl_h" = xyes +then : + printf "%s\n" "#define HAVE_FCNTL_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "io.h" "ac_cv_header_io_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_io_h" = xyes +then : + printf "%s\n" "#define HAVE_IO_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "pwd.h" "ac_cv_header_pwd_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_pwd_h" = xyes +then : + printf "%s\n" "#define HAVE_PWD_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "utime.h" "ac_cv_header_utime_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_utime_h" = xyes +then : + printf "%s\n" "#define HAVE_UTIME_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/utime.h" "ac_cv_header_sys_utime_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_sys_utime_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_UTIME_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/poll.h" "ac_cv_header_sys_poll_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_sys_poll_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_POLL_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "poll.h" "ac_cv_header_poll_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_poll_h" = xyes +then : + printf "%s\n" "#define HAVE_POLL_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "socket.h" "ac_cv_header_socket_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_socket_h" = xyes +then : + printf "%s\n" "#define HAVE_SOCKET_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/resource.h" "ac_cv_header_sys_resource_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_sys_resource_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_RESOURCE_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "libgen.h" "ac_cv_header_libgen_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_libgen_h" = xyes +then : + printf "%s\n" "#define HAVE_LIBGEN_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "locale.h" "ac_cv_header_locale_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_locale_h" = xyes +then : + printf "%s\n" "#define HAVE_LOCALE_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "stdbool.h" "ac_cv_header_stdbool_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_stdbool_h" = xyes +then : + printf "%s\n" "#define HAVE_STDBOOL_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/filio.h" "ac_cv_header_sys_filio_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_sys_filio_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_FILIO_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/wait.h" "ac_cv_header_sys_wait_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_sys_wait_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_WAIT_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "setjmp.h" "ac_cv_header_setjmp_h" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif + + +" +if test "x$ac_cv_header_setjmp_h" = xyes +then : + printf "%s\n" "#define HAVE_SETJMP_H 1" >>confdefs.h + +fi + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5 +printf %s "checking for an ANSI C-conforming const... " >&6; } +if test ${ac_cv_c_const+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main (void) +{ + +#ifndef __cplusplus + /* Ultrix mips cc rejects this sort of thing. */ + typedef int charset[2]; + const charset cs = { 0, 0 }; + /* SunOS 4.1.1 cc rejects this. */ + char const *const *pcpcc; + char **ppc; + /* NEC SVR4.0.2 mips cc rejects this. */ + struct point {int x, y;}; + static struct point const zero = {0,0}; + /* IBM XL C 1.02.0.0 rejects this. + It does not let you subtract one const X* pointer from another in + an arm of an if-expression whose if-part is not a constant + expression */ + const char *g = "string"; + pcpcc = &g + (g ? g-g : 0); + /* HPUX 7.0 cc rejects these. */ + ++pcpcc; + ppc = (char**) pcpcc; + pcpcc = (char const *const *) ppc; + { /* SCO 3.2v4 cc rejects this sort of thing. */ + char tx; + char *t = &tx; + char const *s = 0 ? (char *) 0 : (char const *) 0; + + *t++ = 0; + if (s) return 0; + } + { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ + int x[] = {25, 17}; + const int *foo = &x[0]; + ++foo; + } + { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ + typedef const int *iptr; + iptr p = 0; + ++p; + } + { /* IBM XL C 1.02.0.0 rejects this sort of thing, saying + "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ + struct s { int j; const int *ap[3]; } bx; + struct s *b = &bx; b->j = 5; + } + { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ + const int foo = 10; + if (!foo) return 0; + } + return !cs[0] && !zero.x; +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_c_const=yes +else $as_nop + ac_cv_c_const=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5 +printf "%s\n" "$ac_cv_c_const" >&6; } +if test $ac_cv_c_const = no; then + +printf "%s\n" "#define const /**/" >>confdefs.h + +fi + +ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default" +if test "x$ac_cv_type_size_t" = xyes +then : + +else $as_nop + +printf "%s\n" "#define size_t unsigned int" >>confdefs.h + +fi + + + + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/time.h" "ac_cv_header_sys_time_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_time_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TIME_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/socket.h" "ac_cv_header_sys_socket_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_socket_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_SOCKET_H 1" >>confdefs.h + +fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for struct timeval" >&5 +printf %s "checking for struct timeval... " >&6; } +if test ${curl_cv_struct_timeval+y} +then : + printf %s "(cached) " >&6 +else $as_nop + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#endif +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +#ifdef HAVE_SYS_SOCKET_H +#include +#endif + +int main (void) +{ + + struct timeval ts; + ts.tv_sec = 0; + ts.tv_usec = 0; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + curl_cv_struct_timeval="yes" + +else $as_nop + + curl_cv_struct_timeval="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $curl_cv_struct_timeval" >&5 +printf "%s\n" "$curl_cv_struct_timeval" >&6; } + case "$curl_cv_struct_timeval" in + yes) + +printf "%s\n" "#define HAVE_STRUCT_TIMEVAL 1" >>confdefs.h + + ;; + esac + + + + if test "x$cross_compiling" != xyes; then + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking run-time libs availability" >&5 +printf %s "checking run-time libs availability... " >&6; } + + case $host_os in + darwin*) + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main() +{ + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: fine" >&5 +printf "%s\n" "fine" >&6; } +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: failed" >&5 +printf "%s\n" "failed" >&6; } + as_fn_error $? "one or more libs available at link-time are not available run-time. Libs used at link-time: $LIBS" "$LINENO" 5 + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + ;; + *) + oldcc=$CC + old=$LD_LIBRARY_PATH + CC="sh ./run-compiler" + LD_LIBRARY_PATH=$CURL_LIBRARY_PATH:$old + export LD_LIBRARY_PATH + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main() +{ + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: fine" >&5 +printf "%s\n" "fine" >&6; } +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: failed" >&5 +printf "%s\n" "failed" >&6; } + as_fn_error $? "one or more libs available at link-time are not available run-time. Libs used at link-time: $LIBS" "$LINENO" 5 + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LD_LIBRARY_PATH=$old # restore + CC=$oldcc + ;; + esac + + + fi + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking size of size_t" >&5 +printf %s "checking size of size_t... " >&6; } + r=0 + for typesize in 8 4 2 16 1; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include + + +int main (void) +{ +switch(0) { + case 0: + case (sizeof(size_t) == $typesize):; + } + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + r=$typesize +else $as_nop + + r=0 +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + if test $r -gt 0; then + break; + fi + done + if test $r -eq 0; then + as_fn_error $? "Failed to find size of size_t" "$LINENO" 5 + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $r" >&5 +printf "%s\n" "$r" >&6; } + tname=$(echo "ac_cv_sizeof_size_t" | tr A-Z a-z | tr " " "_") + eval "$tname=$r" + + +printf "%s\n" "#define SIZEOF_SIZE_T $r" >>confdefs.h + + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking size of long" >&5 +printf %s "checking size of long... " >&6; } + r=0 + for typesize in 8 4 2 16 1; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include + + +int main (void) +{ +switch(0) { + case 0: + case (sizeof(long) == $typesize):; + } + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + r=$typesize +else $as_nop + + r=0 +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + if test $r -gt 0; then + break; + fi + done + if test $r -eq 0; then + as_fn_error $? "Failed to find size of long" "$LINENO" 5 + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $r" >&5 +printf "%s\n" "$r" >&6; } + tname=$(echo "ac_cv_sizeof_long" | tr A-Z a-z | tr " " "_") + eval "$tname=$r" + + +printf "%s\n" "#define SIZEOF_LONG $r" >>confdefs.h + + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking size of int" >&5 +printf %s "checking size of int... " >&6; } + r=0 + for typesize in 8 4 2 16 1; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include + + +int main (void) +{ +switch(0) { + case 0: + case (sizeof(int) == $typesize):; + } + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + r=$typesize +else $as_nop + + r=0 +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + if test $r -gt 0; then + break; + fi + done + if test $r -eq 0; then + as_fn_error $? "Failed to find size of int" "$LINENO" 5 + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $r" >&5 +printf "%s\n" "$r" >&6; } + tname=$(echo "ac_cv_sizeof_int" | tr A-Z a-z | tr " " "_") + eval "$tname=$r" + + +printf "%s\n" "#define SIZEOF_INT $r" >>confdefs.h + + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking size of time_t" >&5 +printf %s "checking size of time_t... " >&6; } + r=0 + for typesize in 8 4 2 16 1; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include + + +int main (void) +{ +switch(0) { + case 0: + case (sizeof(time_t) == $typesize):; + } + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + r=$typesize +else $as_nop + + r=0 +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + if test $r -gt 0; then + break; + fi + done + if test $r -eq 0; then + as_fn_error $? "Failed to find size of time_t" "$LINENO" 5 + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $r" >&5 +printf "%s\n" "$r" >&6; } + tname=$(echo "ac_cv_sizeof_time_t" | tr A-Z a-z | tr " " "_") + eval "$tname=$r" + + +printf "%s\n" "#define SIZEOF_TIME_T $r" >>confdefs.h + + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking size of off_t" >&5 +printf %s "checking size of off_t... " >&6; } + r=0 + for typesize in 8 4 2 16 1; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include + + +int main (void) +{ +switch(0) { + case 0: + case (sizeof(off_t) == $typesize):; + } + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + r=$typesize +else $as_nop + + r=0 +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + if test $r -gt 0; then + break; + fi + done + if test $r -eq 0; then + as_fn_error $? "Failed to find size of off_t" "$LINENO" 5 + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $r" >&5 +printf "%s\n" "$r" >&6; } + tname=$(echo "ac_cv_sizeof_off_t" | tr A-Z a-z | tr " " "_") + eval "$tname=$r" + + +printf "%s\n" "#define SIZEOF_OFF_T $r" >>confdefs.h + + + + +o=$CPPFLAGS +CPPFLAGS="-I$srcdir/include $CPPFLAGS" + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking size of curl_off_t" >&5 +printf %s "checking size of curl_off_t... " >&6; } + r=0 + for typesize in 8 4 2 16 1; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include + +#include + + +int main (void) +{ +switch(0) { + case 0: + case (sizeof(curl_off_t) == $typesize):; + } + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + r=$typesize +else $as_nop + + r=0 +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + if test $r -gt 0; then + break; + fi + done + if test $r -eq 0; then + as_fn_error $? "Failed to find size of curl_off_t" "$LINENO" 5 + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $r" >&5 +printf "%s\n" "$r" >&6; } + tname=$(echo "ac_cv_sizeof_curl_off_t" | tr A-Z a-z | tr " " "_") + eval "$tname=$r" + + +printf "%s\n" "#define SIZEOF_CURL_OFF_T $r" >>confdefs.h + + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking size of curl_socket_t" >&5 +printf %s "checking size of curl_socket_t... " >&6; } + r=0 + for typesize in 8 4 2 16 1; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include + +#include + + +int main (void) +{ +switch(0) { + case 0: + case (sizeof(curl_socket_t) == $typesize):; + } + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + r=$typesize +else $as_nop + + r=0 +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + if test $r -gt 0; then + break; + fi + done + if test $r -eq 0; then + as_fn_error $? "Failed to find size of curl_socket_t" "$LINENO" 5 + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $r" >&5 +printf "%s\n" "$r" >&6; } + tname=$(echo "ac_cv_sizeof_curl_socket_t" | tr A-Z a-z | tr " " "_") + eval "$tname=$r" + + +printf "%s\n" "#define SIZEOF_CURL_SOCKET_T $r" >>confdefs.h + + + +CPPFLAGS=$o + +ac_fn_c_check_type "$LINENO" "long long" "ac_cv_type_long_long" "$ac_includes_default" +if test "x$ac_cv_type_long_long" = xyes +then : + +printf "%s\n" "#define HAVE_LONGLONG 1" >>confdefs.h + + longlong="yes" + +fi + + +if test ${ac_cv_sizeof_curl_off_t} -lt 8; then + as_fn_error $? "64 bit curl_off_t is required" "$LINENO" 5 +fi + +# check for ssize_t +ac_fn_c_check_type "$LINENO" "ssize_t" "ac_cv_type_ssize_t" "$ac_includes_default" +if test "x$ac_cv_type_ssize_t" = xyes +then : + +else $as_nop + +printf "%s\n" "#define ssize_t int" >>confdefs.h + +fi + + +# check for bool type +ac_fn_c_check_type "$LINENO" "bool" "ac_cv_type_bool" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_STDBOOL_H +#include +#endif + +" +if test "x$ac_cv_type_bool" = xyes +then : + + +printf "%s\n" "#define HAVE_BOOL_T 1" >>confdefs.h + + +fi + + +# check for sa_family_t +ac_fn_c_check_type "$LINENO" "sa_family_t" "ac_cv_type_sa_family_t" " +#ifdef HAVE_SYS_SOCKET_H +#include +#endif + +" +if test "x$ac_cv_type_sa_family_t" = xyes +then : + +printf "%s\n" "#define CURL_SA_FAMILY_T sa_family_t" >>confdefs.h + +else $as_nop + + # The windows name? + ac_fn_c_check_type "$LINENO" "ADDRESS_FAMILY" "ac_cv_type_ADDRESS_FAMILY" " +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif + +" +if test "x$ac_cv_type_ADDRESS_FAMILY" = xyes +then : + +printf "%s\n" "#define CURL_SA_FAMILY_T ADDRESS_FAMILY" >>confdefs.h + +else $as_nop + +printf "%s\n" "#define CURL_SA_FAMILY_T unsigned short" >>confdefs.h + +fi + + +fi + + +# check for suseconds_t +ac_fn_c_check_type "$LINENO" "suseconds_t" "ac_cv_type_suseconds_t" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif + +" +if test "x$ac_cv_type_suseconds_t" = xyes +then : + + +printf "%s\n" "#define HAVE_SUSECONDS_T 1" >>confdefs.h + + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if time_t is unsigned" >&5 +printf %s "checking if time_t is unsigned... " >&6; } + + case $host_os in + darwin*) + if test "$cross_compiling" = yes +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + #include + #include + int main(void) { + time_t t = -1; + return (t < 0); + } + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_TIME_T_UNSIGNED 1" >>confdefs.h + + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + ;; + *) + oldcc=$CC + old=$LD_LIBRARY_PATH + CC="sh ./run-compiler" + LD_LIBRARY_PATH=$CURL_LIBRARY_PATH:$old + export LD_LIBRARY_PATH + if test "$cross_compiling" = yes +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + #include + #include + int main(void) { + time_t t = -1; + return (t < 0); + } + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_TIME_T_UNSIGNED 1" >>confdefs.h + + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LD_LIBRARY_PATH=$old # restore + CC=$oldcc + ;; + esac + + + + ac_fn_c_check_type "$LINENO" "in_addr_t" "ac_cv_type_in_addr_t" " +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#endif + +" +if test "x$ac_cv_type_in_addr_t" = xyes +then : + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for in_addr_t equivalent" >&5 +printf %s "checking for in_addr_t equivalent... " >&6; } +if test ${curl_cv_in_addr_t_equiv+y} +then : + printf %s "(cached) " >&6 +else $as_nop + + curl_cv_in_addr_t_equiv="unknown" + for t in "unsigned long" int size_t unsigned long; do + if test "$curl_cv_in_addr_t_equiv" = "unknown"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#endif + +int main (void) +{ + + $t data = inet_addr ("1.2.3.4"); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + curl_cv_in_addr_t_equiv="$t" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + fi + done + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $curl_cv_in_addr_t_equiv" >&5 +printf "%s\n" "$curl_cv_in_addr_t_equiv" >&6; } + case "$curl_cv_in_addr_t_equiv" in + unknown) + as_fn_error $? "Cannot find a type to use in place of in_addr_t" "$LINENO" 5 + ;; + *) + +printf "%s\n" "#define in_addr_t $curl_cv_in_addr_t_equiv" >>confdefs.h + + ;; + esac + +fi + + + + + ac_fn_c_check_type "$LINENO" "struct sockaddr_storage" "ac_cv_type_struct_sockaddr_storage" " +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#endif + +" +if test "x$ac_cv_type_struct_sockaddr_storage" = xyes +then : + +printf "%s\n" "#define HAVE_STRUCT_SOCKADDR_STORAGE 1" >>confdefs.h + +fi + + + + + ac_fn_c_check_header_compile "$LINENO" "sys/select.h" "ac_cv_header_sys_select_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_select_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_SELECT_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/socket.h" "ac_cv_header_sys_socket_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_socket_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_SOCKET_H 1" >>confdefs.h + +fi + + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for select" >&5 +printf %s "checking for select... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#endif +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +#ifndef _WIN32 +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +$curl_includes_bsdsocket +#endif + +int main (void) +{ + + select(0, 0, 0, 0, 0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + curl_cv_select="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_select="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$curl_cv_select" = "yes"; then + +printf "%s\n" "#define HAVE_SELECT 1" >>confdefs.h + + curl_cv_func_select="yes" + fi + + + + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/socket.h" "ac_cv_header_sys_socket_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_socket_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_SOCKET_H 1" >>confdefs.h + +fi + + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for recv" >&5 +printf %s "checking for recv... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +$curl_includes_bsdsocket +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#endif + +int main (void) +{ + + recv(0, 0, 0, 0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + curl_cv_recv="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_recv="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$curl_cv_recv" = "yes"; then + +printf "%s\n" "#define HAVE_RECV 1" >>confdefs.h + + curl_cv_func_recv="yes" + else + as_fn_error $? "Unable to link function recv" "$LINENO" 5 + fi + + + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/socket.h" "ac_cv_header_sys_socket_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_socket_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_SOCKET_H 1" >>confdefs.h + +fi + + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for send" >&5 +printf %s "checking for send... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +$curl_includes_bsdsocket +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#endif + +int main (void) +{ + + send(0, 0, 0, 0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + curl_cv_send="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_send="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$curl_cv_send" = "yes"; then + +printf "%s\n" "#define HAVE_SEND 1" >>confdefs.h + + curl_cv_func_send="yes" + else + as_fn_error $? "Unable to link function send" "$LINENO" 5 + fi + + + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/socket.h" "ac_cv_header_sys_socket_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_socket_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_SOCKET_H 1" >>confdefs.h + +fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for MSG_NOSIGNAL" >&5 +printf %s "checking for MSG_NOSIGNAL... " >&6; } +if test ${curl_cv_msg_nosignal+y} +then : + printf %s "(cached) " >&6 +else $as_nop + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#undef inline +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#endif + +int main (void) +{ + + int flag=MSG_NOSIGNAL; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + curl_cv_msg_nosignal="yes" + +else $as_nop + + curl_cv_msg_nosignal="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $curl_cv_msg_nosignal" >&5 +printf "%s\n" "$curl_cv_msg_nosignal" >&6; } + case "$curl_cv_msg_nosignal" in + yes) + +printf "%s\n" "#define HAVE_MSG_NOSIGNAL 1" >>confdefs.h + + ;; + esac + + + +curl_includes_unistd="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$curl_includes_unistd +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "unistd.h" "ac_cv_header_unistd_h" "$curl_includes_unistd +" +if test "x$ac_cv_header_unistd_h" = xyes +then : + printf "%s\n" "#define HAVE_UNISTD_H 1" >>confdefs.h + +fi + + + + # + tst_links_alarm="unknown" + tst_proto_alarm="unknown" + tst_compi_alarm="unknown" + tst_allow_alarm="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if alarm can be linked" >&5 +printf %s "checking if alarm can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define alarm innocuous_alarm +#ifdef __STDC__ +# include +#else +# include +#endif +#undef alarm +#ifdef __cplusplus +extern "C" +#endif +char alarm (); +#if defined __stub_alarm || defined __stub___alarm +choke me +#endif + +int main (void) +{ +return alarm (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_alarm="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_alarm="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_alarm" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if alarm is prototyped" >&5 +printf %s "checking if alarm is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_unistd + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "alarm" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_alarm="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_alarm="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_alarm" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if alarm is compilable" >&5 +printf %s "checking if alarm is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_unistd + +int main (void) +{ + + if(0 != alarm(0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_alarm="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_alarm="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_alarm" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if alarm usage allowed" >&5 +printf %s "checking if alarm usage allowed... " >&6; } + if test "x$curl_disallow_alarm" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_alarm="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_alarm="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if alarm might be used" >&5 +printf %s "checking if alarm might be used... " >&6; } + if test "$tst_links_alarm" = "yes" && + test "$tst_proto_alarm" = "yes" && + test "$tst_compi_alarm" = "yes" && + test "$tst_allow_alarm" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_ALARM 1" >>confdefs.h + + curl_cv_func_alarm="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_alarm="no" + fi + + +curl_includes_string="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#include +#ifdef HAVE_STRINGS_H +# include +#endif +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$curl_includes_string +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "strings.h" "ac_cv_header_strings_h" "$curl_includes_string +" +if test "x$ac_cv_header_strings_h" = xyes +then : + printf "%s\n" "#define HAVE_STRINGS_H 1" >>confdefs.h + +fi + + + +curl_includes_libgen="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_LIBGEN_H +# include +#endif +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$curl_includes_libgen +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "libgen.h" "ac_cv_header_libgen_h" "$curl_includes_libgen +" +if test "x$ac_cv_header_libgen_h" = xyes +then : + printf "%s\n" "#define HAVE_LIBGEN_H 1" >>confdefs.h + +fi + + + + # + tst_links_basename="unknown" + tst_proto_basename="unknown" + tst_compi_basename="unknown" + tst_allow_basename="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if basename can be linked" >&5 +printf %s "checking if basename can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define basename innocuous_basename +#ifdef __STDC__ +# include +#else +# include +#endif +#undef basename +#ifdef __cplusplus +extern "C" +#endif +char basename (); +#if defined __stub_basename || defined __stub___basename +choke me +#endif + +int main (void) +{ +return basename (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_basename="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_basename="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_basename" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if basename is prototyped" >&5 +printf %s "checking if basename is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_string + $curl_includes_libgen + $curl_includes_unistd + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "basename" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_basename="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_basename="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_basename" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if basename is compilable" >&5 +printf %s "checking if basename is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_string + $curl_includes_libgen + $curl_includes_unistd + +int main (void) +{ + + if(0 != basename(0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_basename="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_basename="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_basename" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if basename usage allowed" >&5 +printf %s "checking if basename usage allowed... " >&6; } + if test "x$curl_disallow_basename" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_basename="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_basename="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if basename might be used" >&5 +printf %s "checking if basename might be used... " >&6; } + if test "$tst_links_basename" = "yes" && + test "$tst_proto_basename" = "yes" && + test "$tst_compi_basename" = "yes" && + test "$tst_allow_basename" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_BASENAME 1" >>confdefs.h + + curl_cv_func_basename="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_basename="no" + fi + + +curl_includes_socket="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SOCKET_H +# include +#endif +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$curl_includes_socket +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "socket.h" "ac_cv_header_socket_h" "$curl_includes_socket +" +if test "x$ac_cv_header_socket_h" = xyes +then : + printf "%s\n" "#define HAVE_SOCKET_H 1" >>confdefs.h + +fi + + + + # + tst_links_closesocket="unknown" + tst_proto_closesocket="unknown" + tst_compi_closesocket="unknown" + tst_allow_closesocket="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if closesocket can be linked" >&5 +printf %s "checking if closesocket can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + $curl_includes_socket + +int main (void) +{ + + if(0 != closesocket(0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_closesocket="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_closesocket="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_closesocket" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if closesocket is prototyped" >&5 +printf %s "checking if closesocket is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_winsock2 + $curl_includes_socket + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "closesocket" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_closesocket="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_closesocket="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_closesocket" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if closesocket is compilable" >&5 +printf %s "checking if closesocket is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + $curl_includes_socket + +int main (void) +{ + + if(0 != closesocket(0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_closesocket="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_closesocket="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_closesocket" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if closesocket usage allowed" >&5 +printf %s "checking if closesocket usage allowed... " >&6; } + if test "x$curl_disallow_closesocket" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_closesocket="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_closesocket="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if closesocket might be used" >&5 +printf %s "checking if closesocket might be used... " >&6; } + if test "$tst_links_closesocket" = "yes" && + test "$tst_proto_closesocket" = "yes" && + test "$tst_compi_closesocket" = "yes" && + test "$tst_allow_closesocket" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_CLOSESOCKET 1" >>confdefs.h + + curl_cv_func_closesocket="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_closesocket="no" + fi + + +curl_includes_sys_socket="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_SOCKET_H +# include +#endif +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$curl_includes_sys_socket +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/socket.h" "ac_cv_header_sys_socket_h" "$curl_includes_sys_socket +" +if test "x$ac_cv_header_sys_socket_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_SOCKET_H 1" >>confdefs.h + +fi + + + + # + tst_links_closesocket_camel="unknown" + tst_proto_closesocket_camel="unknown" + tst_compi_closesocket_camel="unknown" + tst_allow_closesocket_camel="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if CloseSocket can be linked" >&5 +printf %s "checking if CloseSocket can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_bsdsocket + $curl_includes_sys_socket + +int main (void) +{ + + if(0 != CloseSocket(0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_closesocket_camel="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_closesocket_camel="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_closesocket_camel" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if CloseSocket is prototyped" >&5 +printf %s "checking if CloseSocket is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_bsdsocket + $curl_includes_sys_socket + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "CloseSocket" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_closesocket_camel="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_closesocket_camel="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_closesocket_camel" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if CloseSocket is compilable" >&5 +printf %s "checking if CloseSocket is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_bsdsocket + $curl_includes_sys_socket + +int main (void) +{ + + if(0 != CloseSocket(0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_closesocket_camel="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_closesocket_camel="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_closesocket_camel" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if CloseSocket usage allowed" >&5 +printf %s "checking if CloseSocket usage allowed... " >&6; } + if test "x$curl_disallow_closesocket_camel" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_closesocket_camel="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_closesocket_camel="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if CloseSocket might be used" >&5 +printf %s "checking if CloseSocket might be used... " >&6; } + if test "$tst_links_closesocket_camel" = "yes" && + test "$tst_proto_closesocket_camel" = "yes" && + test "$tst_compi_closesocket_camel" = "yes" && + test "$tst_allow_closesocket_camel" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_CLOSESOCKET_CAMEL 1" >>confdefs.h + + curl_cv_func_closesocket_camel="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_closesocket_camel="no" + fi + + +curl_includes_fcntl="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif +#ifdef HAVE_FCNTL_H +# include +#endif +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$curl_includes_fcntl +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "unistd.h" "ac_cv_header_unistd_h" "$curl_includes_fcntl +" +if test "x$ac_cv_header_unistd_h" = xyes +then : + printf "%s\n" "#define HAVE_UNISTD_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "fcntl.h" "ac_cv_header_fcntl_h" "$curl_includes_fcntl +" +if test "x$ac_cv_header_fcntl_h" = xyes +then : + printf "%s\n" "#define HAVE_FCNTL_H 1" >>confdefs.h + +fi + + + + # + tst_links_fcntl="unknown" + tst_proto_fcntl="unknown" + tst_compi_fcntl="unknown" + tst_allow_fcntl="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if fcntl can be linked" >&5 +printf %s "checking if fcntl can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define fcntl innocuous_fcntl +#ifdef __STDC__ +# include +#else +# include +#endif +#undef fcntl +#ifdef __cplusplus +extern "C" +#endif +char fcntl (); +#if defined __stub_fcntl || defined __stub___fcntl +choke me +#endif + +int main (void) +{ +return fcntl (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_fcntl="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_fcntl="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_fcntl" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if fcntl is prototyped" >&5 +printf %s "checking if fcntl is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_fcntl + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "fcntl" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_fcntl="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_fcntl="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_fcntl" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if fcntl is compilable" >&5 +printf %s "checking if fcntl is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_fcntl + +int main (void) +{ + + if(0 != fcntl(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_fcntl="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_fcntl="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_fcntl" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if fcntl usage allowed" >&5 +printf %s "checking if fcntl usage allowed... " >&6; } + if test "x$curl_disallow_fcntl" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_fcntl="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_fcntl="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if fcntl might be used" >&5 +printf %s "checking if fcntl might be used... " >&6; } + if test "$tst_links_fcntl" = "yes" && + test "$tst_proto_fcntl" = "yes" && + test "$tst_compi_fcntl" = "yes" && + test "$tst_allow_fcntl" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_FCNTL 1" >>confdefs.h + + curl_cv_func_fcntl="yes" + + # + tst_compi_fcntl_o_nonblock="unknown" + tst_allow_fcntl_o_nonblock="unknown" + # + case $host_os in + sunos4* | aix3*) + curl_disallow_fcntl_o_nonblock="yes" + ;; + esac + # + if test "$curl_cv_func_fcntl" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if fcntl O_NONBLOCK is compilable" >&5 +printf %s "checking if fcntl O_NONBLOCK is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_fcntl + +int main (void) +{ + + int flags = 0; + if(0 != fcntl(0, F_SETFL, flags | O_NONBLOCK)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_fcntl_o_nonblock="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_fcntl_o_nonblock="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_fcntl_o_nonblock" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if fcntl O_NONBLOCK usage allowed" >&5 +printf %s "checking if fcntl O_NONBLOCK usage allowed... " >&6; } + if test "x$curl_disallow_fcntl_o_nonblock" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_fcntl_o_nonblock="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_fcntl_o_nonblock="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if fcntl O_NONBLOCK might be used" >&5 +printf %s "checking if fcntl O_NONBLOCK might be used... " >&6; } + if test "$tst_compi_fcntl_o_nonblock" = "yes" && + test "$tst_allow_fcntl_o_nonblock" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_FCNTL_O_NONBLOCK 1" >>confdefs.h + + curl_cv_func_fcntl_o_nonblock="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_fcntl_o_nonblock="no" + fi + + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_fcntl="no" + fi + + +curl_includes_ws2tcpip="\ +/* includes start */ +#ifdef _WIN32 +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +# include +#endif +/* includes end */" + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether build target is a native Windows one" >&5 +printf %s "checking whether build target is a native Windows one... " >&6; } +if test ${curl_cv_native_windows+y} +then : + printf %s "(cached) " >&6 +else $as_nop + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + +#ifdef _WIN32 + int dummy=1; +#else + Not a native Windows build target. +#endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + curl_cv_native_windows="yes" + +else $as_nop + + curl_cv_native_windows="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $curl_cv_native_windows" >&5 +printf "%s\n" "$curl_cv_native_windows" >&6; } + if test "x$curl_cv_native_windows" = xyes; then + DOING_NATIVE_WINDOWS_TRUE= + DOING_NATIVE_WINDOWS_FALSE='#' +else + DOING_NATIVE_WINDOWS_TRUE='#' + DOING_NATIVE_WINDOWS_FALSE= +fi + + + + +curl_includes_netdb="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_NETDB_H +# include +#endif +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$curl_includes_netdb +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "netdb.h" "ac_cv_header_netdb_h" "$curl_includes_netdb +" +if test "x$ac_cv_header_netdb_h" = xyes +then : + printf "%s\n" "#define HAVE_NETDB_H 1" >>confdefs.h + +fi + + + + # + tst_links_freeaddrinfo="unknown" + tst_proto_freeaddrinfo="unknown" + tst_compi_freeaddrinfo="unknown" + tst_allow_freeaddrinfo="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if freeaddrinfo can be linked" >&5 +printf %s "checking if freeaddrinfo can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_ws2tcpip + $curl_includes_sys_socket + $curl_includes_netdb + +int main (void) +{ + + freeaddrinfo(0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_freeaddrinfo="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_freeaddrinfo="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_freeaddrinfo" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if freeaddrinfo is prototyped" >&5 +printf %s "checking if freeaddrinfo is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_ws2tcpip + $curl_includes_sys_socket + $curl_includes_netdb + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "freeaddrinfo" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_freeaddrinfo="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_freeaddrinfo="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_freeaddrinfo" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if freeaddrinfo is compilable" >&5 +printf %s "checking if freeaddrinfo is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_ws2tcpip + $curl_includes_sys_socket + $curl_includes_netdb + +int main (void) +{ + + freeaddrinfo(0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_freeaddrinfo="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_freeaddrinfo="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_freeaddrinfo" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if freeaddrinfo usage allowed" >&5 +printf %s "checking if freeaddrinfo usage allowed... " >&6; } + if test "x$curl_disallow_freeaddrinfo" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_freeaddrinfo="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_freeaddrinfo="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if freeaddrinfo might be used" >&5 +printf %s "checking if freeaddrinfo might be used... " >&6; } + if test "$tst_links_freeaddrinfo" = "yes" && + test "$tst_proto_freeaddrinfo" = "yes" && + test "$tst_compi_freeaddrinfo" = "yes" && + test "$tst_allow_freeaddrinfo" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_FREEADDRINFO 1" >>confdefs.h + + curl_cv_func_freeaddrinfo="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_freeaddrinfo="no" + fi + + +curl_includes_sys_xattr="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_XATTR_H +# include +#endif +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$curl_includes_sys_xattr +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/xattr.h" "ac_cv_header_sys_xattr_h" "$curl_includes_sys_xattr +" +if test "x$ac_cv_header_sys_xattr_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_XATTR_H 1" >>confdefs.h + +fi + + + + # + tst_links_fsetxattr="unknown" + tst_proto_fsetxattr="unknown" + tst_compi_fsetxattr="unknown" + tst_allow_fsetxattr="unknown" + tst_nargs_fsetxattr="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if fsetxattr can be linked" >&5 +printf %s "checking if fsetxattr can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define fsetxattr innocuous_fsetxattr +#ifdef __STDC__ +# include +#else +# include +#endif +#undef fsetxattr +#ifdef __cplusplus +extern "C" +#endif +char fsetxattr (); +#if defined __stub_fsetxattr || defined __stub___fsetxattr +choke me +#endif + +int main (void) +{ +return fsetxattr (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_fsetxattr="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_fsetxattr="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_fsetxattr" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if fsetxattr is prototyped" >&5 +printf %s "checking if fsetxattr is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_sys_xattr + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "fsetxattr" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_fsetxattr="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_fsetxattr="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_fsetxattr" = "yes"; then + if test "$tst_nargs_fsetxattr" = "unknown"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if fsetxattr takes 5 args." >&5 +printf %s "checking if fsetxattr takes 5 args.... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_sys_xattr + +int main (void) +{ + + if(0 != fsetxattr(0, 0, 0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_fsetxattr="yes" + tst_nargs_fsetxattr="5" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_fsetxattr="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + if test "$tst_nargs_fsetxattr" = "unknown"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if fsetxattr takes 6 args." >&5 +printf %s "checking if fsetxattr takes 6 args.... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_sys_xattr + +int main (void) +{ + + if(0 != fsetxattr(0, 0, 0, 0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_fsetxattr="yes" + tst_nargs_fsetxattr="6" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_fsetxattr="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if fsetxattr is compilable" >&5 +printf %s "checking if fsetxattr is compilable... " >&6; } + if test "$tst_compi_fsetxattr" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + fi + # + if test "$tst_compi_fsetxattr" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if fsetxattr usage allowed" >&5 +printf %s "checking if fsetxattr usage allowed... " >&6; } + if test "x$curl_disallow_fsetxattr" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_fsetxattr="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_fsetxattr="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if fsetxattr might be used" >&5 +printf %s "checking if fsetxattr might be used... " >&6; } + if test "$tst_links_fsetxattr" = "yes" && + test "$tst_proto_fsetxattr" = "yes" && + test "$tst_compi_fsetxattr" = "yes" && + test "$tst_allow_fsetxattr" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_FSETXATTR 1" >>confdefs.h + + # + if test "$tst_nargs_fsetxattr" -eq "5"; then + +printf "%s\n" "#define HAVE_FSETXATTR_5 1" >>confdefs.h + + elif test "$tst_nargs_fsetxattr" -eq "6"; then + +printf "%s\n" "#define HAVE_FSETXATTR_6 1" >>confdefs.h + + fi + # + curl_cv_func_fsetxattr="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_fsetxattr="no" + fi + + + # + tst_links_ftruncate="unknown" + tst_proto_ftruncate="unknown" + tst_compi_ftruncate="unknown" + tst_allow_ftruncate="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ftruncate can be linked" >&5 +printf %s "checking if ftruncate can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define ftruncate innocuous_ftruncate +#ifdef __STDC__ +# include +#else +# include +#endif +#undef ftruncate +#ifdef __cplusplus +extern "C" +#endif +char ftruncate (); +#if defined __stub_ftruncate || defined __stub___ftruncate +choke me +#endif + +int main (void) +{ +return ftruncate (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_ftruncate="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_ftruncate="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_ftruncate" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ftruncate is prototyped" >&5 +printf %s "checking if ftruncate is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_unistd + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "ftruncate" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_ftruncate="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_ftruncate="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_ftruncate" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ftruncate is compilable" >&5 +printf %s "checking if ftruncate is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_unistd + +int main (void) +{ + + if(0 != ftruncate(0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_ftruncate="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_ftruncate="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_ftruncate" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ftruncate usage allowed" >&5 +printf %s "checking if ftruncate usage allowed... " >&6; } + if test "x$curl_disallow_ftruncate" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_ftruncate="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_ftruncate="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ftruncate might be used" >&5 +printf %s "checking if ftruncate might be used... " >&6; } + if test "$tst_links_ftruncate" = "yes" && + test "$tst_proto_ftruncate" = "yes" && + test "$tst_compi_ftruncate" = "yes" && + test "$tst_allow_ftruncate" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_FTRUNCATE 1" >>confdefs.h + + curl_cv_func_ftruncate="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_ftruncate="no" + fi + + +curl_includes_stdlib="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#include +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$curl_includes_stdlib +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi + + + + # + tst_links_getaddrinfo="unknown" + tst_proto_getaddrinfo="unknown" + tst_compi_getaddrinfo="unknown" + tst_works_getaddrinfo="unknown" + tst_allow_getaddrinfo="unknown" + tst_tsafe_getaddrinfo="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getaddrinfo can be linked" >&5 +printf %s "checking if getaddrinfo can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_ws2tcpip + $curl_includes_sys_socket + $curl_includes_netdb + +int main (void) +{ + + if(0 != getaddrinfo(0, 0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_getaddrinfo="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_getaddrinfo="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_getaddrinfo" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getaddrinfo is prototyped" >&5 +printf %s "checking if getaddrinfo is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_ws2tcpip + $curl_includes_sys_socket + $curl_includes_netdb + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "getaddrinfo" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_getaddrinfo="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_getaddrinfo="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_getaddrinfo" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getaddrinfo is compilable" >&5 +printf %s "checking if getaddrinfo is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_ws2tcpip + $curl_includes_sys_socket + $curl_includes_netdb + +int main (void) +{ + + if(0 != getaddrinfo(0, 0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_getaddrinfo="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_getaddrinfo="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "x$cross_compiling" != "xyes" && + test "$tst_compi_getaddrinfo" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getaddrinfo seems to work" >&5 +printf %s "checking if getaddrinfo seems to work... " >&6; } + + case $host_os in + darwin*) + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_ws2tcpip + $curl_includes_stdlib + $curl_includes_string + $curl_includes_sys_socket + $curl_includes_netdb + +int main (void) +{ + + struct addrinfo hints; + struct addrinfo *ai = 0; + int error; + + #ifdef _WIN32 + WSADATA wsa; + if(WSAStartup(MAKEWORD(2, 2), &wsa)) + exit(2); + #endif + + memset(&hints, 0, sizeof(hints)); + hints.ai_flags = AI_NUMERICHOST; + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + error = getaddrinfo("127.0.0.1", 0, &hints, &ai); + if(error || !ai) + exit(1); /* fail */ + else + exit(0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_works_getaddrinfo="yes" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_works_getaddrinfo="no" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + ;; + *) + oldcc=$CC + old=$LD_LIBRARY_PATH + CC="sh ./run-compiler" + LD_LIBRARY_PATH=$CURL_LIBRARY_PATH:$old + export LD_LIBRARY_PATH + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_ws2tcpip + $curl_includes_stdlib + $curl_includes_string + $curl_includes_sys_socket + $curl_includes_netdb + +int main (void) +{ + + struct addrinfo hints; + struct addrinfo *ai = 0; + int error; + + #ifdef _WIN32 + WSADATA wsa; + if(WSAStartup(MAKEWORD(2, 2), &wsa)) + exit(2); + #endif + + memset(&hints, 0, sizeof(hints)); + hints.ai_flags = AI_NUMERICHOST; + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + error = getaddrinfo("127.0.0.1", 0, &hints, &ai); + if(error || !ai) + exit(1); /* fail */ + else + exit(0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_works_getaddrinfo="yes" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_works_getaddrinfo="no" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LD_LIBRARY_PATH=$old # restore + CC=$oldcc + ;; + esac + + fi + # + if test "$tst_compi_getaddrinfo" = "yes" && + test "$tst_works_getaddrinfo" != "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getaddrinfo usage allowed" >&5 +printf %s "checking if getaddrinfo usage allowed... " >&6; } + if test "x$curl_disallow_getaddrinfo" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_getaddrinfo="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_getaddrinfo="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getaddrinfo might be used" >&5 +printf %s "checking if getaddrinfo might be used... " >&6; } + if test "$tst_links_getaddrinfo" = "yes" && + test "$tst_proto_getaddrinfo" = "yes" && + test "$tst_compi_getaddrinfo" = "yes" && + test "$tst_allow_getaddrinfo" = "yes" && + test "$tst_works_getaddrinfo" != "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_GETADDRINFO 1" >>confdefs.h + + curl_cv_func_getaddrinfo="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_getaddrinfo="no" + curl_cv_func_getaddrinfo_threadsafe="no" + fi + # + if test "$curl_cv_func_getaddrinfo" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getaddrinfo is threadsafe" >&5 +printf %s "checking if getaddrinfo is threadsafe... " >&6; } + case $host_os in + aix[1234].* | aix5.[01].*) + tst_tsafe_getaddrinfo="no" + ;; + aix*) + tst_tsafe_getaddrinfo="yes" + ;; + darwin[12345].*) + tst_tsafe_getaddrinfo="no" + ;; + darwin*) + tst_tsafe_getaddrinfo="yes" + ;; + freebsd[1234].* | freebsd5.[1234]*) + tst_tsafe_getaddrinfo="no" + ;; + freebsd*) + tst_tsafe_getaddrinfo="yes" + ;; + hpux[123456789].* | hpux10.* | hpux11.0* | hpux11.10*) + tst_tsafe_getaddrinfo="no" + ;; + hpux*) + tst_tsafe_getaddrinfo="yes" + ;; + midnightbsd*) + tst_tsafe_getaddrinfo="yes" + ;; + netbsd[123].*) + tst_tsafe_getaddrinfo="no" + ;; + netbsd*) + tst_tsafe_getaddrinfo="yes" + ;; + *bsd*) + tst_tsafe_getaddrinfo="no" + ;; + solaris2*) + tst_tsafe_getaddrinfo="yes" + ;; + esac + if test "$tst_tsafe_getaddrinfo" = "unknown" && + test "$curl_cv_native_windows" = "yes"; then + tst_tsafe_getaddrinfo="yes" + fi + if test "$tst_tsafe_getaddrinfo" = "unknown"; then + + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_sys_socket + $curl_includes_netdb + +int main (void) +{ +#ifdef h_errno + return 0; +#else + force compilation error +#endif +} + + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + tst_symbol_defined="yes" + +else $as_nop + + tst_symbol_defined="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + if test "$tst_symbol_defined" = "yes"; then + curl_cv_have_def_h_errno=yes + + else + curl_cv_have_def_h_errno=no + + fi + + if test "$curl_cv_have_def_h_errno" = "yes"; then + tst_h_errno_macro="yes" + else + tst_h_errno_macro="no" + fi + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_sys_socket + $curl_includes_netdb + +int main (void) +{ + + h_errno = 2; + if(0 != h_errno) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + tst_h_errno_modifiable_lvalue="yes" + +else $as_nop + + tst_h_errno_modifiable_lvalue="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + +#if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200809L) + return 0; +#elif defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE >= 700) + return 0; +#else + force compilation error +#endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + tst_h_errno_sbs_issue_7="yes" + +else $as_nop + + tst_h_errno_sbs_issue_7="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + if test "$tst_h_errno_macro" = "no" && + test "$tst_h_errno_modifiable_lvalue" = "no" && + test "$tst_h_errno_sbs_issue_7" = "no"; then + tst_tsafe_getaddrinfo="no" + else + tst_tsafe_getaddrinfo="yes" + fi + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tst_tsafe_getaddrinfo" >&5 +printf "%s\n" "$tst_tsafe_getaddrinfo" >&6; } + if test "$tst_tsafe_getaddrinfo" = "yes"; then + +printf "%s\n" "#define HAVE_GETADDRINFO_THREADSAFE 1" >>confdefs.h + + curl_cv_func_getaddrinfo_threadsafe="yes" + else + curl_cv_func_getaddrinfo_threadsafe="no" + fi + fi + + + # + tst_links_gethostbyname="unknown" + tst_proto_gethostbyname="unknown" + tst_compi_gethostbyname="unknown" + tst_allow_gethostbyname="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostbyname can be linked" >&5 +printf %s "checking if gethostbyname can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_netdb + +int main (void) +{ + + if(0 != gethostbyname(0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_gethostbyname="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_gethostbyname="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_gethostbyname" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostbyname is prototyped" >&5 +printf %s "checking if gethostbyname is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_netdb + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "gethostbyname" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_gethostbyname="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_gethostbyname="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_gethostbyname" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostbyname is compilable" >&5 +printf %s "checking if gethostbyname is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_netdb + +int main (void) +{ + + if(0 != gethostbyname(0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_gethostbyname="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_gethostbyname="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_gethostbyname" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostbyname usage allowed" >&5 +printf %s "checking if gethostbyname usage allowed... " >&6; } + if test "x$curl_disallow_gethostbyname" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_gethostbyname="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_gethostbyname="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostbyname might be used" >&5 +printf %s "checking if gethostbyname might be used... " >&6; } + if test "$tst_links_gethostbyname" = "yes" && + test "$tst_proto_gethostbyname" = "yes" && + test "$tst_compi_gethostbyname" = "yes" && + test "$tst_allow_gethostbyname" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_GETHOSTBYNAME 1" >>confdefs.h + + curl_cv_func_gethostbyname="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_gethostbyname="no" + fi + + + # + tst_links_gethostbyname_r="unknown" + tst_proto_gethostbyname_r="unknown" + tst_compi_gethostbyname_r="unknown" + tst_allow_gethostbyname_r="unknown" + tst_nargs_gethostbyname_r="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostbyname_r can be linked" >&5 +printf %s "checking if gethostbyname_r can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define gethostbyname_r innocuous_gethostbyname_r +#ifdef __STDC__ +# include +#else +# include +#endif +#undef gethostbyname_r +#ifdef __cplusplus +extern "C" +#endif +char gethostbyname_r (); +#if defined __stub_gethostbyname_r || defined __stub___gethostbyname_r +choke me +#endif + +int main (void) +{ +return gethostbyname_r (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_gethostbyname_r="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_gethostbyname_r="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_gethostbyname_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostbyname_r is prototyped" >&5 +printf %s "checking if gethostbyname_r is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_netdb + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "gethostbyname_r" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_gethostbyname_r="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_gethostbyname_r="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_gethostbyname_r" = "yes"; then + if test "$tst_nargs_gethostbyname_r" = "unknown"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostbyname_r takes 3 args." >&5 +printf %s "checking if gethostbyname_r takes 3 args.... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_netdb + $curl_includes_bsdsocket + +int main (void) +{ + + if(0 != gethostbyname_r(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_gethostbyname_r="yes" + tst_nargs_gethostbyname_r="3" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_gethostbyname_r="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + if test "$tst_nargs_gethostbyname_r" = "unknown"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostbyname_r takes 5 args." >&5 +printf %s "checking if gethostbyname_r takes 5 args.... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_netdb + $curl_includes_bsdsocket + +int main (void) +{ + + if(0 != gethostbyname_r(0, 0, 0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_gethostbyname_r="yes" + tst_nargs_gethostbyname_r="5" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_gethostbyname_r="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + if test "$tst_nargs_gethostbyname_r" = "unknown"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostbyname_r takes 6 args." >&5 +printf %s "checking if gethostbyname_r takes 6 args.... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_netdb + $curl_includes_bsdsocket + +int main (void) +{ + + if(0 != gethostbyname_r(0, 0, 0, 0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_gethostbyname_r="yes" + tst_nargs_gethostbyname_r="6" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_gethostbyname_r="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostbyname_r is compilable" >&5 +printf %s "checking if gethostbyname_r is compilable... " >&6; } + if test "$tst_compi_gethostbyname_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + fi + # + if test "$tst_compi_gethostbyname_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostbyname_r usage allowed" >&5 +printf %s "checking if gethostbyname_r usage allowed... " >&6; } + if test "x$curl_disallow_gethostbyname_r" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_gethostbyname_r="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_gethostbyname_r="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostbyname_r might be used" >&5 +printf %s "checking if gethostbyname_r might be used... " >&6; } + if test "$tst_links_gethostbyname_r" = "yes" && + test "$tst_proto_gethostbyname_r" = "yes" && + test "$tst_compi_gethostbyname_r" = "yes" && + test "$tst_allow_gethostbyname_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h + + # + if test "$tst_nargs_gethostbyname_r" -eq "3"; then + +printf "%s\n" "#define HAVE_GETHOSTBYNAME_R_3 1" >>confdefs.h + + elif test "$tst_nargs_gethostbyname_r" -eq "5"; then + +printf "%s\n" "#define HAVE_GETHOSTBYNAME_R_5 1" >>confdefs.h + + elif test "$tst_nargs_gethostbyname_r" -eq "6"; then + +printf "%s\n" "#define HAVE_GETHOSTBYNAME_R_6 1" >>confdefs.h + + fi + # + curl_cv_func_gethostbyname_r="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_gethostbyname_r="no" + fi + + +curl_preprocess_callconv="\ +/* preprocess start */ +#ifdef _WIN32 +# define FUNCALLCONV __stdcall +#else +# define FUNCALLCONV +#endif +/* preprocess end */" + + + # + tst_links_gethostname="unknown" + tst_proto_gethostname="unknown" + tst_compi_gethostname="unknown" + tst_allow_gethostname="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostname can be linked" >&5 +printf %s "checking if gethostname can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + $curl_includes_unistd + $curl_includes_bsdsocket + +int main (void) +{ + + if(0 != gethostname(0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_gethostname="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_gethostname="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_gethostname" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostname is prototyped" >&5 +printf %s "checking if gethostname is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_winsock2 + $curl_includes_unistd + $curl_includes_bsdsocket + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "gethostname" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_gethostname="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_gethostname="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_gethostname" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostname is compilable" >&5 +printf %s "checking if gethostname is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + $curl_includes_unistd + $curl_includes_bsdsocket + +int main (void) +{ + + if(0 != gethostname(0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_gethostname="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_gethostname="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_gethostname" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for gethostname arg 2 data type" >&5 +printf %s "checking for gethostname arg 2 data type... " >&6; } + tst_gethostname_type_arg2="unknown" + for tst_arg1 in 'char *' 'unsigned char *' 'void *'; do + for tst_arg2 in 'int' 'unsigned int' 'size_t'; do + if test "$tst_gethostname_type_arg2" = "unknown"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + $curl_includes_unistd + $curl_includes_bsdsocket + $curl_preprocess_callconv + extern int FUNCALLCONV gethostname($tst_arg1, $tst_arg2); + +int main (void) +{ + + if(0 != gethostname(0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + tst_gethostname_type_arg2="$tst_arg2" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + done + done + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tst_gethostname_type_arg2" >&5 +printf "%s\n" "$tst_gethostname_type_arg2" >&6; } + if test "$tst_gethostname_type_arg2" != "unknown"; then + +printf "%s\n" "#define GETHOSTNAME_TYPE_ARG2 $tst_gethostname_type_arg2" >>confdefs.h + + fi + fi + # + if test "$tst_compi_gethostname" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostname usage allowed" >&5 +printf %s "checking if gethostname usage allowed... " >&6; } + if test "x$curl_disallow_gethostname" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_gethostname="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_gethostname="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gethostname might be used" >&5 +printf %s "checking if gethostname might be used... " >&6; } + if test "$tst_links_gethostname" = "yes" && + test "$tst_proto_gethostname" = "yes" && + test "$tst_compi_gethostname" = "yes" && + test "$tst_allow_gethostname" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_GETHOSTNAME 1" >>confdefs.h + + curl_cv_func_gethostname="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_gethostname="no" + fi + + + # + tst_links_getpeername="unknown" + tst_proto_getpeername="unknown" + tst_compi_getpeername="unknown" + tst_allow_getpeername="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getpeername can be linked" >&5 +printf %s "checking if getpeername can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + +int main (void) +{ + + if(0 != getpeername(0, (void *)0, (void *)0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_getpeername="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_getpeername="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_getpeername" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getpeername is prototyped" >&5 +printf %s "checking if getpeername is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "getpeername" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_getpeername="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_getpeername="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_getpeername" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getpeername is compilable" >&5 +printf %s "checking if getpeername is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + +int main (void) +{ + + if(0 != getpeername(0, (void *)0, (void *)0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_getpeername="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_getpeername="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_getpeername" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getpeername usage allowed" >&5 +printf %s "checking if getpeername usage allowed... " >&6; } + if test "x$curl_disallow_getpeername" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_getpeername="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_getpeername="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getpeername might be used" >&5 +printf %s "checking if getpeername might be used... " >&6; } + if test "$tst_links_getpeername" = "yes" && + test "$tst_proto_getpeername" = "yes" && + test "$tst_compi_getpeername" = "yes" && + test "$tst_allow_getpeername" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_GETPEERNAME 1" >>confdefs.h + + curl_cv_func_getpeername="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_getpeername="no" + fi + + + # + tst_links_getsockname="unknown" + tst_proto_getsockname="unknown" + tst_compi_getsockname="unknown" + tst_allow_getsockname="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getsockname can be linked" >&5 +printf %s "checking if getsockname can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + +int main (void) +{ + + if(0 != getsockname(0, (void *)0, (void *)0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_getsockname="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_getsockname="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_getsockname" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getsockname is prototyped" >&5 +printf %s "checking if getsockname is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "getsockname" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_getsockname="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_getsockname="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_getsockname" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getsockname is compilable" >&5 +printf %s "checking if getsockname is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + +int main (void) +{ + + if(0 != getsockname(0, (void *)0, (void *)0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_getsockname="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_getsockname="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_getsockname" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getsockname usage allowed" >&5 +printf %s "checking if getsockname usage allowed... " >&6; } + if test "x$curl_disallow_getsockname" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_getsockname="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_getsockname="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getsockname might be used" >&5 +printf %s "checking if getsockname might be used... " >&6; } + if test "$tst_links_getsockname" = "yes" && + test "$tst_proto_getsockname" = "yes" && + test "$tst_compi_getsockname" = "yes" && + test "$tst_allow_getsockname" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_GETSOCKNAME 1" >>confdefs.h + + curl_cv_func_getsockname="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_getsockname="no" + fi + + +curl_includes_netif="\ +/* includes start */ +#ifdef HAVE_NET_IF_H +# include +#endif +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "net/if.h" "ac_cv_header_net_if_h" "$curl_includes_netif +" +if test "x$ac_cv_header_net_if_h" = xyes +then : + printf "%s\n" "#define HAVE_NET_IF_H 1" >>confdefs.h + +fi + + + + # + tst_links_if_nametoindex="unknown" + tst_proto_if_nametoindex="unknown" + tst_compi_if_nametoindex="unknown" + tst_allow_if_nametoindex="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if if_nametoindex can be linked" >&5 +printf %s "checking if if_nametoindex can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + $curl_includes_bsdsocket + #include + +int main (void) +{ + + if(0 != if_nametoindex("")) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_if_nametoindex="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_if_nametoindex="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_if_nametoindex" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if if_nametoindex is prototyped" >&5 +printf %s "checking if if_nametoindex is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_winsock2 + $curl_includes_netif + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "if_nametoindex" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_if_nametoindex="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_if_nametoindex="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_if_nametoindex" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if if_nametoindex is compilable" >&5 +printf %s "checking if if_nametoindex is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + $curl_includes_netif + +int main (void) +{ + + if(0 != if_nametoindex("")) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_if_nametoindex="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_if_nametoindex="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_if_nametoindex" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if if_nametoindex usage allowed" >&5 +printf %s "checking if if_nametoindex usage allowed... " >&6; } + if test "x$curl_disallow_if_nametoindex" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_if_nametoindex="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_if_nametoindex="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if if_nametoindex might be used" >&5 +printf %s "checking if if_nametoindex might be used... " >&6; } + if test "$tst_links_if_nametoindex" = "yes" && + test "$tst_proto_if_nametoindex" = "yes" && + test "$tst_compi_if_nametoindex" = "yes" && + test "$tst_allow_if_nametoindex" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_IF_NAMETOINDEX 1" >>confdefs.h + + curl_cv_func_if_nametoindex="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_if_nametoindex="no" + fi + + +curl_includes_ifaddrs="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_SOCKET_H +# include +#endif +#ifdef HAVE_NETINET_IN_H +# include +#endif +#ifdef HAVE_IFADDRS_H +# include +#endif +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$curl_includes_ifaddrs +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/socket.h" "ac_cv_header_sys_socket_h" "$curl_includes_ifaddrs +" +if test "x$ac_cv_header_sys_socket_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_SOCKET_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "netinet/in.h" "ac_cv_header_netinet_in_h" "$curl_includes_ifaddrs +" +if test "x$ac_cv_header_netinet_in_h" = xyes +then : + printf "%s\n" "#define HAVE_NETINET_IN_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "ifaddrs.h" "ac_cv_header_ifaddrs_h" "$curl_includes_ifaddrs +" +if test "x$ac_cv_header_ifaddrs_h" = xyes +then : + printf "%s\n" "#define HAVE_IFADDRS_H 1" >>confdefs.h + +fi + + + + # + tst_links_getifaddrs="unknown" + tst_proto_getifaddrs="unknown" + tst_compi_getifaddrs="unknown" + tst_works_getifaddrs="unknown" + tst_allow_getifaddrs="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getifaddrs can be linked" >&5 +printf %s "checking if getifaddrs can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define getifaddrs innocuous_getifaddrs +#ifdef __STDC__ +# include +#else +# include +#endif +#undef getifaddrs +#ifdef __cplusplus +extern "C" +#endif +char getifaddrs (); +#if defined __stub_getifaddrs || defined __stub___getifaddrs +choke me +#endif + +int main (void) +{ +return getifaddrs (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_getifaddrs="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_getifaddrs="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_getifaddrs" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getifaddrs is prototyped" >&5 +printf %s "checking if getifaddrs is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_ifaddrs + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "getifaddrs" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_getifaddrs="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_getifaddrs="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_getifaddrs" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getifaddrs is compilable" >&5 +printf %s "checking if getifaddrs is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_ifaddrs + +int main (void) +{ + + if(0 != getifaddrs(0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_getifaddrs="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_getifaddrs="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "x$cross_compiling" != "xyes" && + test "$tst_compi_getifaddrs" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getifaddrs seems to work" >&5 +printf %s "checking if getifaddrs seems to work... " >&6; } + + case $host_os in + darwin*) + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stdlib + $curl_includes_ifaddrs + +int main (void) +{ + + struct ifaddrs *ifa = 0; + int error; + + error = getifaddrs(&ifa); + if(error || !ifa) + exit(1); /* fail */ + else + exit(0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_works_getifaddrs="yes" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_works_getifaddrs="no" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + ;; + *) + oldcc=$CC + old=$LD_LIBRARY_PATH + CC="sh ./run-compiler" + LD_LIBRARY_PATH=$CURL_LIBRARY_PATH:$old + export LD_LIBRARY_PATH + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stdlib + $curl_includes_ifaddrs + +int main (void) +{ + + struct ifaddrs *ifa = 0; + int error; + + error = getifaddrs(&ifa); + if(error || !ifa) + exit(1); /* fail */ + else + exit(0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_works_getifaddrs="yes" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_works_getifaddrs="no" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LD_LIBRARY_PATH=$old # restore + CC=$oldcc + ;; + esac + + fi + # + if test "$tst_compi_getifaddrs" = "yes" && + test "$tst_works_getifaddrs" != "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getifaddrs usage allowed" >&5 +printf %s "checking if getifaddrs usage allowed... " >&6; } + if test "x$curl_disallow_getifaddrs" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_getifaddrs="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_getifaddrs="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if getifaddrs might be used" >&5 +printf %s "checking if getifaddrs might be used... " >&6; } + if test "$tst_links_getifaddrs" = "yes" && + test "$tst_proto_getifaddrs" = "yes" && + test "$tst_compi_getifaddrs" = "yes" && + test "$tst_allow_getifaddrs" = "yes" && + test "$tst_works_getifaddrs" != "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_GETIFADDRS 1" >>confdefs.h + + curl_cv_func_getifaddrs="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_getifaddrs="no" + fi + + +curl_includes_time="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_TIME_H +# include +#endif +#include +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$curl_includes_time +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/time.h" "ac_cv_header_sys_time_h" "$curl_includes_time +" +if test "x$ac_cv_header_sys_time_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TIME_H 1" >>confdefs.h + +fi + + + + # + tst_links_gmtime_r="unknown" + tst_proto_gmtime_r="unknown" + tst_compi_gmtime_r="unknown" + tst_works_gmtime_r="unknown" + tst_allow_gmtime_r="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gmtime_r can be linked" >&5 +printf %s "checking if gmtime_r can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define gmtime_r innocuous_gmtime_r +#ifdef __STDC__ +# include +#else +# include +#endif +#undef gmtime_r +#ifdef __cplusplus +extern "C" +#endif +char gmtime_r (); +#if defined __stub_gmtime_r || defined __stub___gmtime_r +choke me +#endif + +int main (void) +{ +return gmtime_r (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_gmtime_r="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_gmtime_r="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_gmtime_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gmtime_r is prototyped" >&5 +printf %s "checking if gmtime_r is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_time + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "gmtime_r" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_gmtime_r="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_gmtime_r="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_gmtime_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gmtime_r is compilable" >&5 +printf %s "checking if gmtime_r is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_time + +int main (void) +{ + + if(0 != gmtime_r(0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_gmtime_r="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_gmtime_r="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "x$cross_compiling" != "xyes" && + test "$tst_compi_gmtime_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gmtime_r seems to work" >&5 +printf %s "checking if gmtime_r seems to work... " >&6; } + + case $host_os in + darwin*) + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stdlib + $curl_includes_time + +int main (void) +{ + + time_t local = 1170352587; + struct tm *gmt = 0; + struct tm result; + gmt = gmtime_r(&local, &result); + if(gmt) + exit(0); + else + exit(1); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_works_gmtime_r="yes" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_works_gmtime_r="no" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + ;; + *) + oldcc=$CC + old=$LD_LIBRARY_PATH + CC="sh ./run-compiler" + LD_LIBRARY_PATH=$CURL_LIBRARY_PATH:$old + export LD_LIBRARY_PATH + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stdlib + $curl_includes_time + +int main (void) +{ + + time_t local = 1170352587; + struct tm *gmt = 0; + struct tm result; + gmt = gmtime_r(&local, &result); + if(gmt) + exit(0); + else + exit(1); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_works_gmtime_r="yes" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_works_gmtime_r="no" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LD_LIBRARY_PATH=$old # restore + CC=$oldcc + ;; + esac + + fi + # + if test "$tst_compi_gmtime_r" = "yes" && + test "$tst_works_gmtime_r" != "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gmtime_r usage allowed" >&5 +printf %s "checking if gmtime_r usage allowed... " >&6; } + if test "x$curl_disallow_gmtime_r" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_gmtime_r="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_gmtime_r="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if gmtime_r might be used" >&5 +printf %s "checking if gmtime_r might be used... " >&6; } + if test "$tst_links_gmtime_r" = "yes" && + test "$tst_proto_gmtime_r" = "yes" && + test "$tst_compi_gmtime_r" = "yes" && + test "$tst_allow_gmtime_r" = "yes" && + test "$tst_works_gmtime_r" != "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_GMTIME_R 1" >>confdefs.h + + curl_cv_func_gmtime_r="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_gmtime_r="no" + fi + + +curl_includes_arpa_inet="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_SOCKET_H +# include +#endif +#ifdef HAVE_NETINET_IN_H +# include +#endif +#ifdef HAVE_ARPA_INET_H +# include +#endif +#ifdef _WIN32 +#include +#include +#endif +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$curl_includes_arpa_inet +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/socket.h" "ac_cv_header_sys_socket_h" "$curl_includes_arpa_inet +" +if test "x$ac_cv_header_sys_socket_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_SOCKET_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "netinet/in.h" "ac_cv_header_netinet_in_h" "$curl_includes_arpa_inet +" +if test "x$ac_cv_header_netinet_in_h" = xyes +then : + printf "%s\n" "#define HAVE_NETINET_IN_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "arpa/inet.h" "ac_cv_header_arpa_inet_h" "$curl_includes_arpa_inet +" +if test "x$ac_cv_header_arpa_inet_h" = xyes +then : + printf "%s\n" "#define HAVE_ARPA_INET_H 1" >>confdefs.h + +fi + + + + # + tst_links_inet_ntop="unknown" + tst_proto_inet_ntop="unknown" + tst_compi_inet_ntop="unknown" + tst_works_inet_ntop="unknown" + tst_allow_inet_ntop="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if inet_ntop can be linked" >&5 +printf %s "checking if inet_ntop can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define inet_ntop innocuous_inet_ntop +#ifdef __STDC__ +# include +#else +# include +#endif +#undef inet_ntop +#ifdef __cplusplus +extern "C" +#endif +char inet_ntop (); +#if defined __stub_inet_ntop || defined __stub___inet_ntop +choke me +#endif + +int main (void) +{ +return inet_ntop (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_inet_ntop="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_inet_ntop="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_inet_ntop" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if inet_ntop is prototyped" >&5 +printf %s "checking if inet_ntop is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_arpa_inet + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "inet_ntop" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_inet_ntop="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_inet_ntop="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_inet_ntop" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if inet_ntop is compilable" >&5 +printf %s "checking if inet_ntop is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_arpa_inet + +int main (void) +{ + + if(0 != inet_ntop(0, 0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_inet_ntop="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_inet_ntop="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "x$cross_compiling" != "xyes" && + test "$tst_compi_inet_ntop" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if inet_ntop seems to work" >&5 +printf %s "checking if inet_ntop seems to work... " >&6; } + + case $host_os in + darwin*) + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stdlib + $curl_includes_arpa_inet + $curl_includes_string + +int main (void) +{ + + char ipv6res[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")]; + char ipv4res[sizeof "255.255.255.255"]; + unsigned char ipv6a[26]; + unsigned char ipv4a[5]; + char *ipv6ptr = 0; + char *ipv4ptr = 0; + /* - */ + ipv4res[0] = '\0'; + ipv4a[0] = 0xc0; + ipv4a[1] = 0xa8; + ipv4a[2] = 0x64; + ipv4a[3] = 0x01; + ipv4a[4] = 0x01; + /* - */ + ipv4ptr = inet_ntop(AF_INET, ipv4a, ipv4res, sizeof(ipv4res)); + if(!ipv4ptr) + exit(1); /* fail */ + if(ipv4ptr != ipv4res) + exit(1); /* fail */ + if(!ipv4ptr[0]) + exit(1); /* fail */ + if(memcmp(ipv4res, "192.168.100.1", 13) != 0) + exit(1); /* fail */ + /* - */ + ipv6res[0] = '\0'; + memset(ipv6a, 0, sizeof(ipv6a)); + ipv6a[0] = 0xfe; + ipv6a[1] = 0x80; + ipv6a[8] = 0x02; + ipv6a[9] = 0x14; + ipv6a[10] = 0x4f; + ipv6a[11] = 0xff; + ipv6a[12] = 0xfe; + ipv6a[13] = 0x0b; + ipv6a[14] = 0x76; + ipv6a[15] = 0xc8; + ipv6a[25] = 0x01; + /* - */ + ipv6ptr = inet_ntop(AF_INET6, ipv6a, ipv6res, sizeof(ipv6res)); + if(!ipv6ptr) + exit(1); /* fail */ + if(ipv6ptr != ipv6res) + exit(1); /* fail */ + if(!ipv6ptr[0]) + exit(1); /* fail */ + if(memcmp(ipv6res, "fe80::214:4fff:fe0b:76c8", 24) != 0) + exit(1); /* fail */ + /* - */ + exit(0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_works_inet_ntop="yes" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_works_inet_ntop="no" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + ;; + *) + oldcc=$CC + old=$LD_LIBRARY_PATH + CC="sh ./run-compiler" + LD_LIBRARY_PATH=$CURL_LIBRARY_PATH:$old + export LD_LIBRARY_PATH + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stdlib + $curl_includes_arpa_inet + $curl_includes_string + +int main (void) +{ + + char ipv6res[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")]; + char ipv4res[sizeof "255.255.255.255"]; + unsigned char ipv6a[26]; + unsigned char ipv4a[5]; + char *ipv6ptr = 0; + char *ipv4ptr = 0; + /* - */ + ipv4res[0] = '\0'; + ipv4a[0] = 0xc0; + ipv4a[1] = 0xa8; + ipv4a[2] = 0x64; + ipv4a[3] = 0x01; + ipv4a[4] = 0x01; + /* - */ + ipv4ptr = inet_ntop(AF_INET, ipv4a, ipv4res, sizeof(ipv4res)); + if(!ipv4ptr) + exit(1); /* fail */ + if(ipv4ptr != ipv4res) + exit(1); /* fail */ + if(!ipv4ptr[0]) + exit(1); /* fail */ + if(memcmp(ipv4res, "192.168.100.1", 13) != 0) + exit(1); /* fail */ + /* - */ + ipv6res[0] = '\0'; + memset(ipv6a, 0, sizeof(ipv6a)); + ipv6a[0] = 0xfe; + ipv6a[1] = 0x80; + ipv6a[8] = 0x02; + ipv6a[9] = 0x14; + ipv6a[10] = 0x4f; + ipv6a[11] = 0xff; + ipv6a[12] = 0xfe; + ipv6a[13] = 0x0b; + ipv6a[14] = 0x76; + ipv6a[15] = 0xc8; + ipv6a[25] = 0x01; + /* - */ + ipv6ptr = inet_ntop(AF_INET6, ipv6a, ipv6res, sizeof(ipv6res)); + if(!ipv6ptr) + exit(1); /* fail */ + if(ipv6ptr != ipv6res) + exit(1); /* fail */ + if(!ipv6ptr[0]) + exit(1); /* fail */ + if(memcmp(ipv6res, "fe80::214:4fff:fe0b:76c8", 24) != 0) + exit(1); /* fail */ + /* - */ + exit(0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_works_inet_ntop="yes" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_works_inet_ntop="no" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LD_LIBRARY_PATH=$old # restore + CC=$oldcc + ;; + esac + + fi + # + if test "$tst_compi_inet_ntop" = "yes" && + test "$tst_works_inet_ntop" != "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if inet_ntop usage allowed" >&5 +printf %s "checking if inet_ntop usage allowed... " >&6; } + if test "x$curl_disallow_inet_ntop" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_inet_ntop="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_inet_ntop="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if inet_ntop might be used" >&5 +printf %s "checking if inet_ntop might be used... " >&6; } + if test "$tst_links_inet_ntop" = "yes" && + test "$tst_proto_inet_ntop" = "yes" && + test "$tst_compi_inet_ntop" = "yes" && + test "$tst_allow_inet_ntop" = "yes" && + test "$tst_works_inet_ntop" != "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_INET_NTOP 1" >>confdefs.h + + curl_cv_func_inet_ntop="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_inet_ntop="no" + fi + + + # + tst_links_inet_pton="unknown" + tst_proto_inet_pton="unknown" + tst_compi_inet_pton="unknown" + tst_works_inet_pton="unknown" + tst_allow_inet_pton="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if inet_pton can be linked" >&5 +printf %s "checking if inet_pton can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define inet_pton innocuous_inet_pton +#ifdef __STDC__ +# include +#else +# include +#endif +#undef inet_pton +#ifdef __cplusplus +extern "C" +#endif +char inet_pton (); +#if defined __stub_inet_pton || defined __stub___inet_pton +choke me +#endif + +int main (void) +{ +return inet_pton (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_inet_pton="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_inet_pton="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_inet_pton" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if inet_pton is prototyped" >&5 +printf %s "checking if inet_pton is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_arpa_inet + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "inet_pton" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_inet_pton="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_inet_pton="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_inet_pton" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if inet_pton is compilable" >&5 +printf %s "checking if inet_pton is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_arpa_inet + +int main (void) +{ + + if(0 != inet_pton(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_inet_pton="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_inet_pton="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "x$cross_compiling" != "xyes" && + test "$tst_compi_inet_pton" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if inet_pton seems to work" >&5 +printf %s "checking if inet_pton seems to work... " >&6; } + + case $host_os in + darwin*) + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stdlib + $curl_includes_arpa_inet + $curl_includes_string + +int main (void) +{ + + unsigned char ipv6a[16+1]; + unsigned char ipv4a[4+1]; + const char *ipv6src = "fe80::214:4fff:fe0b:76c8"; + const char *ipv4src = "192.168.100.1"; + /* - */ + memset(ipv4a, 1, sizeof(ipv4a)); + if(1 != inet_pton(AF_INET, ipv4src, ipv4a)) + exit(1); /* fail */ + /* - */ + if( (ipv4a[0] != 0xc0) || + (ipv4a[1] != 0xa8) || + (ipv4a[2] != 0x64) || + (ipv4a[3] != 0x01) || + (ipv4a[4] != 0x01) ) + exit(1); /* fail */ + /* - */ + memset(ipv6a, 1, sizeof(ipv6a)); + if(1 != inet_pton(AF_INET6, ipv6src, ipv6a)) + exit(1); /* fail */ + /* - */ + if( (ipv6a[0] != 0xfe) || + (ipv6a[1] != 0x80) || + (ipv6a[8] != 0x02) || + (ipv6a[9] != 0x14) || + (ipv6a[10] != 0x4f) || + (ipv6a[11] != 0xff) || + (ipv6a[12] != 0xfe) || + (ipv6a[13] != 0x0b) || + (ipv6a[14] != 0x76) || + (ipv6a[15] != 0xc8) || + (ipv6a[16] != 0x01) ) + exit(1); /* fail */ + /* - */ + if( (ipv6a[2] != 0x0) || + (ipv6a[3] != 0x0) || + (ipv6a[4] != 0x0) || + (ipv6a[5] != 0x0) || + (ipv6a[6] != 0x0) || + (ipv6a[7] != 0x0) ) + exit(1); /* fail */ + /* - */ + exit(0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_works_inet_pton="yes" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_works_inet_pton="no" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + ;; + *) + oldcc=$CC + old=$LD_LIBRARY_PATH + CC="sh ./run-compiler" + LD_LIBRARY_PATH=$CURL_LIBRARY_PATH:$old + export LD_LIBRARY_PATH + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stdlib + $curl_includes_arpa_inet + $curl_includes_string + +int main (void) +{ + + unsigned char ipv6a[16+1]; + unsigned char ipv4a[4+1]; + const char *ipv6src = "fe80::214:4fff:fe0b:76c8"; + const char *ipv4src = "192.168.100.1"; + /* - */ + memset(ipv4a, 1, sizeof(ipv4a)); + if(1 != inet_pton(AF_INET, ipv4src, ipv4a)) + exit(1); /* fail */ + /* - */ + if( (ipv4a[0] != 0xc0) || + (ipv4a[1] != 0xa8) || + (ipv4a[2] != 0x64) || + (ipv4a[3] != 0x01) || + (ipv4a[4] != 0x01) ) + exit(1); /* fail */ + /* - */ + memset(ipv6a, 1, sizeof(ipv6a)); + if(1 != inet_pton(AF_INET6, ipv6src, ipv6a)) + exit(1); /* fail */ + /* - */ + if( (ipv6a[0] != 0xfe) || + (ipv6a[1] != 0x80) || + (ipv6a[8] != 0x02) || + (ipv6a[9] != 0x14) || + (ipv6a[10] != 0x4f) || + (ipv6a[11] != 0xff) || + (ipv6a[12] != 0xfe) || + (ipv6a[13] != 0x0b) || + (ipv6a[14] != 0x76) || + (ipv6a[15] != 0xc8) || + (ipv6a[16] != 0x01) ) + exit(1); /* fail */ + /* - */ + if( (ipv6a[2] != 0x0) || + (ipv6a[3] != 0x0) || + (ipv6a[4] != 0x0) || + (ipv6a[5] != 0x0) || + (ipv6a[6] != 0x0) || + (ipv6a[7] != 0x0) ) + exit(1); /* fail */ + /* - */ + exit(0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_works_inet_pton="yes" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_works_inet_pton="no" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LD_LIBRARY_PATH=$old # restore + CC=$oldcc + ;; + esac + + fi + # + if test "$tst_compi_inet_pton" = "yes" && + test "$tst_works_inet_pton" != "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if inet_pton usage allowed" >&5 +printf %s "checking if inet_pton usage allowed... " >&6; } + if test "x$curl_disallow_inet_pton" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_inet_pton="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_inet_pton="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if inet_pton might be used" >&5 +printf %s "checking if inet_pton might be used... " >&6; } + if test "$tst_links_inet_pton" = "yes" && + test "$tst_proto_inet_pton" = "yes" && + test "$tst_compi_inet_pton" = "yes" && + test "$tst_allow_inet_pton" = "yes" && + test "$tst_works_inet_pton" != "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_INET_PTON 1" >>confdefs.h + + curl_cv_func_inet_pton="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_inet_pton="no" + fi + + +curl_includes_stropts="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif +#ifdef HAVE_SYS_SOCKET_H +# include +#endif +#ifdef HAVE_SYS_IOCTL_H +# include +#endif +#ifdef HAVE_STROPTS_H +# include +#endif +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$curl_includes_stropts +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "unistd.h" "ac_cv_header_unistd_h" "$curl_includes_stropts +" +if test "x$ac_cv_header_unistd_h" = xyes +then : + printf "%s\n" "#define HAVE_UNISTD_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/socket.h" "ac_cv_header_sys_socket_h" "$curl_includes_stropts +" +if test "x$ac_cv_header_sys_socket_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_SOCKET_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/ioctl.h" "ac_cv_header_sys_ioctl_h" "$curl_includes_stropts +" +if test "x$ac_cv_header_sys_ioctl_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_IOCTL_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "stropts.h" "ac_cv_header_stropts_h" "$curl_includes_stropts +" +if test "x$ac_cv_header_stropts_h" = xyes +then : + printf "%s\n" "#define HAVE_STROPTS_H 1" >>confdefs.h + +fi + + + + # + tst_links_ioctl="unknown" + tst_proto_ioctl="unknown" + tst_compi_ioctl="unknown" + tst_allow_ioctl="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctl can be linked" >&5 +printf %s "checking if ioctl can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define ioctl innocuous_ioctl +#ifdef __STDC__ +# include +#else +# include +#endif +#undef ioctl +#ifdef __cplusplus +extern "C" +#endif +char ioctl (); +#if defined __stub_ioctl || defined __stub___ioctl +choke me +#endif + +int main (void) +{ +return ioctl (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_ioctl="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_ioctl="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_ioctl" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctl is prototyped" >&5 +printf %s "checking if ioctl is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_stropts + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "ioctl" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_ioctl="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_ioctl="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_ioctl" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctl is compilable" >&5 +printf %s "checking if ioctl is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stropts + +int main (void) +{ + + if(0 != ioctl(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_ioctl="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_ioctl="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_ioctl" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctl usage allowed" >&5 +printf %s "checking if ioctl usage allowed... " >&6; } + if test "x$curl_disallow_ioctl" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_ioctl="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_ioctl="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctl might be used" >&5 +printf %s "checking if ioctl might be used... " >&6; } + if test "$tst_links_ioctl" = "yes" && + test "$tst_proto_ioctl" = "yes" && + test "$tst_compi_ioctl" = "yes" && + test "$tst_allow_ioctl" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_IOCTL 1" >>confdefs.h + + curl_cv_func_ioctl="yes" + + # + tst_compi_ioctl_fionbio="unknown" + tst_allow_ioctl_fionbio="unknown" + # + if test "$curl_cv_func_ioctl" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctl FIONBIO is compilable" >&5 +printf %s "checking if ioctl FIONBIO is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stropts + +int main (void) +{ + + int flags = 0; + if(0 != ioctl(0, FIONBIO, &flags)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_ioctl_fionbio="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_ioctl_fionbio="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_ioctl_fionbio" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctl FIONBIO usage allowed" >&5 +printf %s "checking if ioctl FIONBIO usage allowed... " >&6; } + if test "x$curl_disallow_ioctl_fionbio" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_ioctl_fionbio="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_ioctl_fionbio="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctl FIONBIO might be used" >&5 +printf %s "checking if ioctl FIONBIO might be used... " >&6; } + if test "$tst_compi_ioctl_fionbio" = "yes" && + test "$tst_allow_ioctl_fionbio" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_IOCTL_FIONBIO 1" >>confdefs.h + + curl_cv_func_ioctl_fionbio="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_ioctl_fionbio="no" + fi + + + # + tst_compi_ioctl_siocgifaddr="unknown" + tst_allow_ioctl_siocgifaddr="unknown" + # + if test "$curl_cv_func_ioctl" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctl SIOCGIFADDR is compilable" >&5 +printf %s "checking if ioctl SIOCGIFADDR is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stropts + #include + +int main (void) +{ + + struct ifreq ifr; + if(0 != ioctl(0, SIOCGIFADDR, &ifr)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_ioctl_siocgifaddr="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_ioctl_siocgifaddr="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_ioctl_siocgifaddr" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctl SIOCGIFADDR usage allowed" >&5 +printf %s "checking if ioctl SIOCGIFADDR usage allowed... " >&6; } + if test "x$curl_disallow_ioctl_siocgifaddr" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_ioctl_siocgifaddr="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_ioctl_siocgifaddr="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctl SIOCGIFADDR might be used" >&5 +printf %s "checking if ioctl SIOCGIFADDR might be used... " >&6; } + if test "$tst_compi_ioctl_siocgifaddr" = "yes" && + test "$tst_allow_ioctl_siocgifaddr" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_IOCTL_SIOCGIFADDR 1" >>confdefs.h + + curl_cv_func_ioctl_siocgifaddr="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_ioctl_siocgifaddr="no" + fi + + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_ioctl="no" + fi + + + # + tst_links_ioctlsocket="unknown" + tst_proto_ioctlsocket="unknown" + tst_compi_ioctlsocket="unknown" + tst_allow_ioctlsocket="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctlsocket can be linked" >&5 +printf %s "checking if ioctlsocket can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + +int main (void) +{ + + if(0 != ioctlsocket(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_ioctlsocket="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_ioctlsocket="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_ioctlsocket" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctlsocket is prototyped" >&5 +printf %s "checking if ioctlsocket is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_winsock2 + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "ioctlsocket" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_ioctlsocket="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_ioctlsocket="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_ioctlsocket" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctlsocket is compilable" >&5 +printf %s "checking if ioctlsocket is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + +int main (void) +{ + + if(0 != ioctlsocket(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_ioctlsocket="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_ioctlsocket="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_ioctlsocket" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctlsocket usage allowed" >&5 +printf %s "checking if ioctlsocket usage allowed... " >&6; } + if test "x$curl_disallow_ioctlsocket" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_ioctlsocket="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_ioctlsocket="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctlsocket might be used" >&5 +printf %s "checking if ioctlsocket might be used... " >&6; } + if test "$tst_links_ioctlsocket" = "yes" && + test "$tst_proto_ioctlsocket" = "yes" && + test "$tst_compi_ioctlsocket" = "yes" && + test "$tst_allow_ioctlsocket" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_IOCTLSOCKET 1" >>confdefs.h + + curl_cv_func_ioctlsocket="yes" + + # + tst_compi_ioctlsocket_fionbio="unknown" + tst_allow_ioctlsocket_fionbio="unknown" + # + if test "$curl_cv_func_ioctlsocket" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctlsocket FIONBIO is compilable" >&5 +printf %s "checking if ioctlsocket FIONBIO is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + +int main (void) +{ + + unsigned long flags = 0; + if(0 != ioctlsocket(0, FIONBIO, &flags)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_ioctlsocket_fionbio="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_ioctlsocket_fionbio="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_ioctlsocket_fionbio" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctlsocket FIONBIO usage allowed" >&5 +printf %s "checking if ioctlsocket FIONBIO usage allowed... " >&6; } + if test "x$curl_disallow_ioctlsocket_fionbio" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_ioctlsocket_fionbio="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_ioctlsocket_fionbio="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ioctlsocket FIONBIO might be used" >&5 +printf %s "checking if ioctlsocket FIONBIO might be used... " >&6; } + if test "$tst_compi_ioctlsocket_fionbio" = "yes" && + test "$tst_allow_ioctlsocket_fionbio" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_IOCTLSOCKET_FIONBIO 1" >>confdefs.h + + curl_cv_func_ioctlsocket_fionbio="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_ioctlsocket_fionbio="no" + fi + + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_ioctlsocket="no" + fi + + + # + tst_links_ioctlsocket_camel="unknown" + tst_proto_ioctlsocket_camel="unknown" + tst_compi_ioctlsocket_camel="unknown" + tst_allow_ioctlsocket_camel="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if IoctlSocket can be linked" >&5 +printf %s "checking if IoctlSocket can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_bsdsocket + +int main (void) +{ + + IoctlSocket(0, 0, 0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_ioctlsocket_camel="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_ioctlsocket_camel="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_ioctlsocket_camel" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if IoctlSocket is prototyped" >&5 +printf %s "checking if IoctlSocket is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_bsdsocket + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "IoctlSocket" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_ioctlsocket_camel="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_ioctlsocket_camel="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_ioctlsocket_camel" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if IoctlSocket is compilable" >&5 +printf %s "checking if IoctlSocket is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_bsdsocket + +int main (void) +{ + + if(0 != IoctlSocket(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_ioctlsocket_camel="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_ioctlsocket_camel="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_ioctlsocket_camel" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if IoctlSocket usage allowed" >&5 +printf %s "checking if IoctlSocket usage allowed... " >&6; } + if test "x$curl_disallow_ioctlsocket_camel" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_ioctlsocket_camel="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_ioctlsocket_camel="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if IoctlSocket might be used" >&5 +printf %s "checking if IoctlSocket might be used... " >&6; } + if test "$tst_links_ioctlsocket_camel" = "yes" && + test "$tst_proto_ioctlsocket_camel" = "yes" && + test "$tst_compi_ioctlsocket_camel" = "yes" && + test "$tst_allow_ioctlsocket_camel" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_IOCTLSOCKET_CAMEL 1" >>confdefs.h + + curl_cv_func_ioctlsocket_camel="yes" + + # + tst_compi_ioctlsocket_camel_fionbio="unknown" + tst_allow_ioctlsocket_camel_fionbio="unknown" + # + if test "$curl_cv_func_ioctlsocket_camel" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if IoctlSocket FIONBIO is compilable" >&5 +printf %s "checking if IoctlSocket FIONBIO is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_bsdsocket + +int main (void) +{ + + long flags = 0; + if(0 != IoctlSocket(0, FIONBIO, &flags)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_ioctlsocket_camel_fionbio="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_ioctlsocket_camel_fionbio="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_ioctlsocket_camel_fionbio" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if IoctlSocket FIONBIO usage allowed" >&5 +printf %s "checking if IoctlSocket FIONBIO usage allowed... " >&6; } + if test "x$curl_disallow_ioctlsocket_camel_fionbio" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_ioctlsocket_camel_fionbio="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_ioctlsocket_camel_fionbio="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if IoctlSocket FIONBIO might be used" >&5 +printf %s "checking if IoctlSocket FIONBIO might be used... " >&6; } + if test "$tst_compi_ioctlsocket_camel_fionbio" = "yes" && + test "$tst_allow_ioctlsocket_camel_fionbio" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_IOCTLSOCKET_CAMEL_FIONBIO 1" >>confdefs.h + + curl_cv_func_ioctlsocket_camel_fionbio="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_ioctlsocket_camel_fionbio="no" + fi + + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_ioctlsocket_camel="no" + fi + + + # + tst_links_memrchr="unknown" + tst_macro_memrchr="unknown" + tst_proto_memrchr="unknown" + tst_compi_memrchr="unknown" + tst_allow_memrchr="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if memrchr can be linked" >&5 +printf %s "checking if memrchr can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define memrchr innocuous_memrchr +#ifdef __STDC__ +# include +#else +# include +#endif +#undef memrchr +#ifdef __cplusplus +extern "C" +#endif +char memrchr (); +#if defined __stub_memrchr || defined __stub___memrchr +choke me +#endif + +int main (void) +{ +return memrchr (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_memrchr="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_memrchr="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_memrchr" = "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if memrchr seems a macro" >&5 +printf %s "checking if memrchr seems a macro... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_string + +int main (void) +{ + + if(0 != memrchr(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_macro_memrchr="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_macro_memrchr="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + fi + # + if test "$tst_links_memrchr" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if memrchr is prototyped" >&5 +printf %s "checking if memrchr is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_string + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memrchr" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_memrchr="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_memrchr="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_memrchr" = "yes" || + test "$tst_macro_memrchr" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if memrchr is compilable" >&5 +printf %s "checking if memrchr is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_string + +int main (void) +{ + + if(0 != memrchr(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_memrchr="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_memrchr="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_memrchr" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if memrchr usage allowed" >&5 +printf %s "checking if memrchr usage allowed... " >&6; } + if test "x$curl_disallow_memrchr" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_memrchr="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_memrchr="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if memrchr might be used" >&5 +printf %s "checking if memrchr might be used... " >&6; } + if (test "$tst_proto_memrchr" = "yes" || + test "$tst_macro_memrchr" = "yes") && + test "$tst_compi_memrchr" = "yes" && + test "$tst_allow_memrchr" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_MEMRCHR 1" >>confdefs.h + + curl_cv_func_memrchr="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_memrchr="no" + fi + + +curl_includes_poll="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_POLL_H +# include +#endif +#ifdef HAVE_SYS_POLL_H +# include +#endif +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$curl_includes_poll +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "poll.h" "ac_cv_header_poll_h" "$curl_includes_poll +" +if test "x$ac_cv_header_poll_h" = xyes +then : + printf "%s\n" "#define HAVE_POLL_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/poll.h" "ac_cv_header_sys_poll_h" "$curl_includes_poll +" +if test "x$ac_cv_header_sys_poll_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_POLL_H 1" >>confdefs.h + +fi + + + + # + tst_links_poll="unknown" + tst_proto_poll="unknown" + tst_compi_poll="unknown" + tst_works_poll="unknown" + tst_allow_poll="unknown" + # + case $host_os in + darwin*|interix*) + curl_disallow_poll="yes" + tst_compi_poll="no" + ;; + esac + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if poll can be linked" >&5 +printf %s "checking if poll can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_poll + +int main (void) +{ + + if(0 != poll(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_poll="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_poll="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_poll" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if poll is prototyped" >&5 +printf %s "checking if poll is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_poll + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "poll" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_poll="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_poll="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_poll" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if poll is compilable" >&5 +printf %s "checking if poll is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_poll + +int main (void) +{ + + if(0 != poll(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_poll="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_poll="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "x$cross_compiling" != "xyes" && + test "$tst_compi_poll" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if poll seems to work" >&5 +printf %s "checking if poll seems to work... " >&6; } + + case $host_os in + darwin*) + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stdlib + $curl_includes_poll + $curl_includes_time + +int main (void) +{ + + /* detect the original poll() breakage */ + if(0 != poll(0, 0, 10)) + exit(1); /* fail */ + else { + /* detect the 10.12 poll() breakage */ + struct timeval before, after; + int rc; + size_t us; + + gettimeofday(&before, NULL); + rc = poll(NULL, 0, 500); + gettimeofday(&after, NULL); + + us = (after.tv_sec - before.tv_sec) * 1000000 + + (after.tv_usec - before.tv_usec); + + if(us < 400000) + exit(1); + } + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_works_poll="yes" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_works_poll="no" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + ;; + *) + oldcc=$CC + old=$LD_LIBRARY_PATH + CC="sh ./run-compiler" + LD_LIBRARY_PATH=$CURL_LIBRARY_PATH:$old + export LD_LIBRARY_PATH + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stdlib + $curl_includes_poll + $curl_includes_time + +int main (void) +{ + + /* detect the original poll() breakage */ + if(0 != poll(0, 0, 10)) + exit(1); /* fail */ + else { + /* detect the 10.12 poll() breakage */ + struct timeval before, after; + int rc; + size_t us; + + gettimeofday(&before, NULL); + rc = poll(NULL, 0, 500); + gettimeofday(&after, NULL); + + us = (after.tv_sec - before.tv_sec) * 1000000 + + (after.tv_usec - before.tv_usec); + + if(us < 400000) + exit(1); + } + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_works_poll="yes" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_works_poll="no" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LD_LIBRARY_PATH=$old # restore + CC=$oldcc + ;; + esac + + fi + # + if test "$tst_compi_poll" = "yes" && + test "$tst_works_poll" != "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if poll usage allowed" >&5 +printf %s "checking if poll usage allowed... " >&6; } + if test "x$curl_disallow_poll" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_poll="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_poll="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if poll might be used" >&5 +printf %s "checking if poll might be used... " >&6; } + if test "$tst_links_poll" = "yes" && + test "$tst_proto_poll" = "yes" && + test "$tst_compi_poll" = "yes" && + test "$tst_allow_poll" = "yes" && + test "$tst_works_poll" != "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_POLL_FINE 1" >>confdefs.h + + curl_cv_func_poll="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_poll="no" + fi + + +curl_includes_signal="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#include +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$curl_includes_signal +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi + + + + # + tst_links_sigaction="unknown" + tst_proto_sigaction="unknown" + tst_compi_sigaction="unknown" + tst_allow_sigaction="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if sigaction can be linked" >&5 +printf %s "checking if sigaction can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define sigaction innocuous_sigaction +#ifdef __STDC__ +# include +#else +# include +#endif +#undef sigaction +#ifdef __cplusplus +extern "C" +#endif +char sigaction (); +#if defined __stub_sigaction || defined __stub___sigaction +choke me +#endif + +int main (void) +{ +return sigaction (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_sigaction="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_sigaction="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_sigaction" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if sigaction is prototyped" >&5 +printf %s "checking if sigaction is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_signal + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "sigaction" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_sigaction="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_sigaction="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_sigaction" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if sigaction is compilable" >&5 +printf %s "checking if sigaction is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_signal + +int main (void) +{ + + if(0 != sigaction(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_sigaction="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_sigaction="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_sigaction" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if sigaction usage allowed" >&5 +printf %s "checking if sigaction usage allowed... " >&6; } + if test "x$curl_disallow_sigaction" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_sigaction="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_sigaction="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if sigaction might be used" >&5 +printf %s "checking if sigaction might be used... " >&6; } + if test "$tst_links_sigaction" = "yes" && + test "$tst_proto_sigaction" = "yes" && + test "$tst_compi_sigaction" = "yes" && + test "$tst_allow_sigaction" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_SIGACTION 1" >>confdefs.h + + curl_cv_func_sigaction="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_sigaction="no" + fi + + + # + tst_links_siginterrupt="unknown" + tst_proto_siginterrupt="unknown" + tst_compi_siginterrupt="unknown" + tst_allow_siginterrupt="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if siginterrupt can be linked" >&5 +printf %s "checking if siginterrupt can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define siginterrupt innocuous_siginterrupt +#ifdef __STDC__ +# include +#else +# include +#endif +#undef siginterrupt +#ifdef __cplusplus +extern "C" +#endif +char siginterrupt (); +#if defined __stub_siginterrupt || defined __stub___siginterrupt +choke me +#endif + +int main (void) +{ +return siginterrupt (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_siginterrupt="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_siginterrupt="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_siginterrupt" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if siginterrupt is prototyped" >&5 +printf %s "checking if siginterrupt is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_signal + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "siginterrupt" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_siginterrupt="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_siginterrupt="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_siginterrupt" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if siginterrupt is compilable" >&5 +printf %s "checking if siginterrupt is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_signal + +int main (void) +{ + + if(0 != siginterrupt(0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_siginterrupt="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_siginterrupt="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_siginterrupt" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if siginterrupt usage allowed" >&5 +printf %s "checking if siginterrupt usage allowed... " >&6; } + if test "x$curl_disallow_siginterrupt" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_siginterrupt="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_siginterrupt="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if siginterrupt might be used" >&5 +printf %s "checking if siginterrupt might be used... " >&6; } + if test "$tst_links_siginterrupt" = "yes" && + test "$tst_proto_siginterrupt" = "yes" && + test "$tst_compi_siginterrupt" = "yes" && + test "$tst_allow_siginterrupt" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_SIGINTERRUPT 1" >>confdefs.h + + curl_cv_func_siginterrupt="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_siginterrupt="no" + fi + + + # + tst_links_signal="unknown" + tst_proto_signal="unknown" + tst_compi_signal="unknown" + tst_allow_signal="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if signal can be linked" >&5 +printf %s "checking if signal can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define signal innocuous_signal +#ifdef __STDC__ +# include +#else +# include +#endif +#undef signal +#ifdef __cplusplus +extern "C" +#endif +char signal (); +#if defined __stub_signal || defined __stub___signal +choke me +#endif + +int main (void) +{ +return signal (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_signal="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_signal="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_signal" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if signal is prototyped" >&5 +printf %s "checking if signal is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_signal + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "signal" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_signal="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_signal="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_signal" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if signal is compilable" >&5 +printf %s "checking if signal is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_signal + +int main (void) +{ + + if(0 != signal(0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_signal="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_signal="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_signal" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if signal usage allowed" >&5 +printf %s "checking if signal usage allowed... " >&6; } + if test "x$curl_disallow_signal" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_signal="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_signal="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if signal might be used" >&5 +printf %s "checking if signal might be used... " >&6; } + if test "$tst_links_signal" = "yes" && + test "$tst_proto_signal" = "yes" && + test "$tst_compi_signal" = "yes" && + test "$tst_allow_signal" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_SIGNAL 1" >>confdefs.h + + curl_cv_func_signal="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_signal="no" + fi + + +curl_includes_setjmp="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#include +/* includes end */" + ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$curl_includes_setjmp +" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi + + + + # + tst_links_sigsetjmp="unknown" + tst_macro_sigsetjmp="unknown" + tst_proto_sigsetjmp="unknown" + tst_compi_sigsetjmp="unknown" + tst_allow_sigsetjmp="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if sigsetjmp can be linked" >&5 +printf %s "checking if sigsetjmp can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define sigsetjmp innocuous_sigsetjmp +#ifdef __STDC__ +# include +#else +# include +#endif +#undef sigsetjmp +#ifdef __cplusplus +extern "C" +#endif +char sigsetjmp (); +#if defined __stub_sigsetjmp || defined __stub___sigsetjmp +choke me +#endif + +int main (void) +{ +return sigsetjmp (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_sigsetjmp="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_sigsetjmp="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_sigsetjmp" = "no"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if sigsetjmp seems a macro" >&5 +printf %s "checking if sigsetjmp seems a macro... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_setjmp + +int main (void) +{ + + sigjmp_buf env; + if(0 != sigsetjmp(env, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_macro_sigsetjmp="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_macro_sigsetjmp="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + fi + # + if test "$tst_links_sigsetjmp" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if sigsetjmp is prototyped" >&5 +printf %s "checking if sigsetjmp is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_setjmp + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "sigsetjmp" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_sigsetjmp="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_sigsetjmp="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_sigsetjmp" = "yes" || + test "$tst_macro_sigsetjmp" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if sigsetjmp is compilable" >&5 +printf %s "checking if sigsetjmp is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_setjmp + +int main (void) +{ + + sigjmp_buf env; + if(0 != sigsetjmp(env, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_sigsetjmp="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_sigsetjmp="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_sigsetjmp" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if sigsetjmp usage allowed" >&5 +printf %s "checking if sigsetjmp usage allowed... " >&6; } + if test "x$curl_disallow_sigsetjmp" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_sigsetjmp="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_sigsetjmp="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if sigsetjmp might be used" >&5 +printf %s "checking if sigsetjmp might be used... " >&6; } + if (test "$tst_proto_sigsetjmp" = "yes" || + test "$tst_macro_sigsetjmp" = "yes") && + test "$tst_compi_sigsetjmp" = "yes" && + test "$tst_allow_sigsetjmp" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_SIGSETJMP 1" >>confdefs.h + + curl_cv_func_sigsetjmp="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_sigsetjmp="no" + fi + + + # + tst_links_socket="unknown" + tst_proto_socket="unknown" + tst_compi_socket="unknown" + tst_allow_socket="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if socket can be linked" >&5 +printf %s "checking if socket can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + $curl_includes_socket + +int main (void) +{ + + if(0 != socket(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_socket="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_socket="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_socket" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if socket is prototyped" >&5 +printf %s "checking if socket is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + $curl_includes_socket + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "socket" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_socket="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_socket="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_socket" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if socket is compilable" >&5 +printf %s "checking if socket is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + $curl_includes_socket + +int main (void) +{ + + if(0 != socket(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_socket="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_socket="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_socket" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if socket usage allowed" >&5 +printf %s "checking if socket usage allowed... " >&6; } + if test "x$curl_disallow_socket" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_socket="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_socket="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if socket might be used" >&5 +printf %s "checking if socket might be used... " >&6; } + if test "$tst_links_socket" = "yes" && + test "$tst_proto_socket" = "yes" && + test "$tst_compi_socket" = "yes" && + test "$tst_allow_socket" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_SOCKET 1" >>confdefs.h + + curl_cv_func_socket="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_socket="no" + fi + + + # + tst_links_socketpair="unknown" + tst_proto_socketpair="unknown" + tst_compi_socketpair="unknown" + tst_allow_socketpair="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if socketpair can be linked" >&5 +printf %s "checking if socketpair can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define socketpair innocuous_socketpair +#ifdef __STDC__ +# include +#else +# include +#endif +#undef socketpair +#ifdef __cplusplus +extern "C" +#endif +char socketpair (); +#if defined __stub_socketpair || defined __stub___socketpair +choke me +#endif + +int main (void) +{ +return socketpair (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_socketpair="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_socketpair="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_socketpair" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if socketpair is prototyped" >&5 +printf %s "checking if socketpair is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_sys_socket + $curl_includes_socket + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "socketpair" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_socketpair="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_socketpair="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_socketpair" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if socketpair is compilable" >&5 +printf %s "checking if socketpair is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_sys_socket + $curl_includes_socket + +int main (void) +{ + + int sv[2]; + if(0 != socketpair(0, 0, 0, sv)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_socketpair="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_socketpair="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_socketpair" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if socketpair usage allowed" >&5 +printf %s "checking if socketpair usage allowed... " >&6; } + if test "x$curl_disallow_socketpair" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_socketpair="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_socketpair="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if socketpair might be used" >&5 +printf %s "checking if socketpair might be used... " >&6; } + if test "$tst_links_socketpair" = "yes" && + test "$tst_proto_socketpair" = "yes" && + test "$tst_compi_socketpair" = "yes" && + test "$tst_allow_socketpair" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_SOCKETPAIR 1" >>confdefs.h + + curl_cv_func_socketpair="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_socketpair="no" + fi + + + # + tst_links_strcasecmp="unknown" + tst_proto_strcasecmp="unknown" + tst_compi_strcasecmp="unknown" + tst_allow_strcasecmp="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strcasecmp can be linked" >&5 +printf %s "checking if strcasecmp can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define strcasecmp innocuous_strcasecmp +#ifdef __STDC__ +# include +#else +# include +#endif +#undef strcasecmp +#ifdef __cplusplus +extern "C" +#endif +char strcasecmp (); +#if defined __stub_strcasecmp || defined __stub___strcasecmp +choke me +#endif + +int main (void) +{ +return strcasecmp (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_strcasecmp="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_strcasecmp="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_strcasecmp" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strcasecmp is prototyped" >&5 +printf %s "checking if strcasecmp is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_string + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "strcasecmp" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_strcasecmp="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_strcasecmp="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_strcasecmp" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strcasecmp is compilable" >&5 +printf %s "checking if strcasecmp is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_string + +int main (void) +{ + + if(0 != strcasecmp(0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_strcasecmp="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_strcasecmp="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_strcasecmp" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strcasecmp usage allowed" >&5 +printf %s "checking if strcasecmp usage allowed... " >&6; } + if test "x$curl_disallow_strcasecmp" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_strcasecmp="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_strcasecmp="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strcasecmp might be used" >&5 +printf %s "checking if strcasecmp might be used... " >&6; } + if test "$tst_links_strcasecmp" = "yes" && + test "$tst_proto_strcasecmp" = "yes" && + test "$tst_compi_strcasecmp" = "yes" && + test "$tst_allow_strcasecmp" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_STRCASECMP 1" >>confdefs.h + + curl_cv_func_strcasecmp="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_strcasecmp="no" + fi + + + # + tst_links_strcmpi="unknown" + tst_proto_strcmpi="unknown" + tst_compi_strcmpi="unknown" + tst_allow_strcmpi="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strcmpi can be linked" >&5 +printf %s "checking if strcmpi can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define strcmpi innocuous_strcmpi +#ifdef __STDC__ +# include +#else +# include +#endif +#undef strcmpi +#ifdef __cplusplus +extern "C" +#endif +char strcmpi (); +#if defined __stub_strcmpi || defined __stub___strcmpi +choke me +#endif + +int main (void) +{ +return strcmpi (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_strcmpi="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_strcmpi="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_strcmpi" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strcmpi is prototyped" >&5 +printf %s "checking if strcmpi is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_string + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "strcmpi" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_strcmpi="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_strcmpi="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_strcmpi" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strcmpi is compilable" >&5 +printf %s "checking if strcmpi is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_string + +int main (void) +{ + + if(0 != strcmpi(0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_strcmpi="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_strcmpi="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_strcmpi" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strcmpi usage allowed" >&5 +printf %s "checking if strcmpi usage allowed... " >&6; } + if test "x$curl_disallow_strcmpi" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_strcmpi="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_strcmpi="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strcmpi might be used" >&5 +printf %s "checking if strcmpi might be used... " >&6; } + if test "$tst_links_strcmpi" = "yes" && + test "$tst_proto_strcmpi" = "yes" && + test "$tst_compi_strcmpi" = "yes" && + test "$tst_allow_strcmpi" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_STRCMPI 1" >>confdefs.h + + curl_cv_func_strcmpi="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_strcmpi="no" + fi + + + # + tst_links_strdup="unknown" + tst_proto_strdup="unknown" + tst_compi_strdup="unknown" + tst_allow_strdup="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strdup can be linked" >&5 +printf %s "checking if strdup can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define strdup innocuous_strdup +#ifdef __STDC__ +# include +#else +# include +#endif +#undef strdup +#ifdef __cplusplus +extern "C" +#endif +char strdup (); +#if defined __stub_strdup || defined __stub___strdup +choke me +#endif + +int main (void) +{ +return strdup (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_strdup="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_strdup="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_strdup" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strdup is prototyped" >&5 +printf %s "checking if strdup is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_string + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "strdup" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_strdup="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_strdup="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_strdup" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strdup is compilable" >&5 +printf %s "checking if strdup is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_string + +int main (void) +{ + + if(0 != strdup(0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_strdup="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_strdup="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_strdup" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strdup usage allowed" >&5 +printf %s "checking if strdup usage allowed... " >&6; } + if test "x$curl_disallow_strdup" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_strdup="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_strdup="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strdup might be used" >&5 +printf %s "checking if strdup might be used... " >&6; } + if test "$tst_links_strdup" = "yes" && + test "$tst_proto_strdup" = "yes" && + test "$tst_compi_strdup" = "yes" && + test "$tst_allow_strdup" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_STRDUP 1" >>confdefs.h + + curl_cv_func_strdup="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_strdup="no" + fi + + + # + tst_links_strerror_r="unknown" + tst_proto_strerror_r="unknown" + tst_compi_strerror_r="unknown" + tst_glibc_strerror_r="unknown" + tst_posix_strerror_r="unknown" + tst_allow_strerror_r="unknown" + tst_works_glibc_strerror_r="unknown" + tst_works_posix_strerror_r="unknown" + tst_glibc_strerror_r_type_arg3="unknown" + tst_posix_strerror_r_type_arg3="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strerror_r can be linked" >&5 +printf %s "checking if strerror_r can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define strerror_r innocuous_strerror_r +#ifdef __STDC__ +# include +#else +# include +#endif +#undef strerror_r +#ifdef __cplusplus +extern "C" +#endif +char strerror_r (); +#if defined __stub_strerror_r || defined __stub___strerror_r +choke me +#endif + +int main (void) +{ +return strerror_r (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_strerror_r="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_strerror_r="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_strerror_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strerror_r is prototyped" >&5 +printf %s "checking if strerror_r is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_string + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "strerror_r" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_strerror_r="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_strerror_r="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_strerror_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strerror_r is compilable" >&5 +printf %s "checking if strerror_r is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_string + +int main (void) +{ + + if(0 != strerror_r(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_strerror_r="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_strerror_r="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_strerror_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strerror_r is glibc like" >&5 +printf %s "checking if strerror_r is glibc like... " >&6; } + tst_glibc_strerror_r_type_arg3="unknown" + for arg3 in 'size_t' 'int' 'unsigned int'; do + if test "$tst_glibc_strerror_r_type_arg3" = "unknown"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_string + char *strerror_r(int errnum, char *workbuf, $arg3 bufsize); + +int main (void) +{ + + if(0 != strerror_r(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + tst_glibc_strerror_r_type_arg3="$arg3" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + done + case "$tst_glibc_strerror_r_type_arg3" in + unknown) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_glibc_strerror_r="no" + ;; + *) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_glibc_strerror_r="yes" + ;; + esac + fi + # + if test "x$cross_compiling" != "xyes" && + test "$tst_glibc_strerror_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strerror_r seems to work" >&5 +printf %s "checking if strerror_r seems to work... " >&6; } + + case $host_os in + darwin*) + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stdlib + $curl_includes_string +# include + +int main (void) +{ + + char buffer[1024]; + char *string = 0; + buffer[0] = '\0'; + string = strerror_r(EACCES, buffer, sizeof(buffer)); + if(!string) + exit(1); /* fail */ + if(!string[0]) + exit(1); /* fail */ + else + exit(0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_works_glibc_strerror_r="yes" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_works_glibc_strerror_r="no" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + ;; + *) + oldcc=$CC + old=$LD_LIBRARY_PATH + CC="sh ./run-compiler" + LD_LIBRARY_PATH=$CURL_LIBRARY_PATH:$old + export LD_LIBRARY_PATH + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stdlib + $curl_includes_string +# include + +int main (void) +{ + + char buffer[1024]; + char *string = 0; + buffer[0] = '\0'; + string = strerror_r(EACCES, buffer, sizeof(buffer)); + if(!string) + exit(1); /* fail */ + if(!string[0]) + exit(1); /* fail */ + else + exit(0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_works_glibc_strerror_r="yes" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_works_glibc_strerror_r="no" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LD_LIBRARY_PATH=$old # restore + CC=$oldcc + ;; + esac + + fi + # + if test "$tst_compi_strerror_r" = "yes" && + test "$tst_works_glibc_strerror_r" != "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strerror_r is POSIX like" >&5 +printf %s "checking if strerror_r is POSIX like... " >&6; } + tst_posix_strerror_r_type_arg3="unknown" + for arg3 in 'size_t' 'int' 'unsigned int'; do + if test "$tst_posix_strerror_r_type_arg3" = "unknown"; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_string + int strerror_r(int errnum, char *resultbuf, $arg3 bufsize); + +int main (void) +{ + + if(0 != strerror_r(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + tst_posix_strerror_r_type_arg3="$arg3" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + done + case "$tst_posix_strerror_r_type_arg3" in + unknown) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_posix_strerror_r="no" + ;; + *) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_posix_strerror_r="yes" + ;; + esac + fi + # + if test "x$cross_compiling" != "xyes" && + test "$tst_posix_strerror_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strerror_r seems to work" >&5 +printf %s "checking if strerror_r seems to work... " >&6; } + + case $host_os in + darwin*) + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stdlib + $curl_includes_string +# include + +int main (void) +{ + + char buffer[1024]; + int error = 1; + buffer[0] = '\0'; + error = strerror_r(EACCES, buffer, sizeof(buffer)); + if(error) + exit(1); /* fail */ + if(buffer[0] == '\0') + exit(1); /* fail */ + else + exit(0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_works_posix_strerror_r="yes" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_works_posix_strerror_r="no" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + ;; + *) + oldcc=$CC + old=$LD_LIBRARY_PATH + CC="sh ./run-compiler" + LD_LIBRARY_PATH=$CURL_LIBRARY_PATH:$old + export LD_LIBRARY_PATH + if test "$cross_compiling" = yes +then : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stdlib + $curl_includes_string +# include + +int main (void) +{ + + char buffer[1024]; + int error = 1; + buffer[0] = '\0'; + error = strerror_r(EACCES, buffer, sizeof(buffer)); + if(error) + exit(1); /* fail */ + if(buffer[0] == '\0') + exit(1); /* fail */ + else + exit(0); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_works_posix_strerror_r="yes" + +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_works_posix_strerror_r="no" + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LD_LIBRARY_PATH=$old # restore + CC=$oldcc + ;; + esac + + fi + # + if test "$tst_works_glibc_strerror_r" = "yes"; then + tst_posix_strerror_r="no" + fi + if test "$tst_works_posix_strerror_r" = "yes"; then + tst_glibc_strerror_r="no" + fi + if test "$tst_glibc_strerror_r" = "yes" && + test "$tst_works_glibc_strerror_r" != "no" && + test "$tst_posix_strerror_r" != "yes"; then + tst_allow_strerror_r="check" + fi + if test "$tst_posix_strerror_r" = "yes" && + test "$tst_works_posix_strerror_r" != "no" && + test "$tst_glibc_strerror_r" != "yes"; then + tst_allow_strerror_r="check" + fi + if test "$tst_allow_strerror_r" = "check"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strerror_r usage allowed" >&5 +printf %s "checking if strerror_r usage allowed... " >&6; } + if test "x$curl_disallow_strerror_r" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_strerror_r="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_strerror_r="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strerror_r might be used" >&5 +printf %s "checking if strerror_r might be used... " >&6; } + if test "$tst_links_strerror_r" = "yes" && + test "$tst_proto_strerror_r" = "yes" && + test "$tst_compi_strerror_r" = "yes" && + test "$tst_allow_strerror_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + if test "$tst_glibc_strerror_r" = "yes"; then + +printf "%s\n" "#define HAVE_STRERROR_R 1" >>confdefs.h + + +printf "%s\n" "#define HAVE_GLIBC_STRERROR_R 1" >>confdefs.h + + fi + if test "$tst_posix_strerror_r" = "yes"; then + +printf "%s\n" "#define HAVE_STRERROR_R 1" >>confdefs.h + + +printf "%s\n" "#define HAVE_POSIX_STRERROR_R 1" >>confdefs.h + + fi + curl_cv_func_strerror_r="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_strerror_r="no" + fi + # + if test "$tst_compi_strerror_r" = "yes" && + test "$tst_allow_strerror_r" = "unknown"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: cannot determine strerror_r() style: edit lib/curl_config.h manually." >&5 +printf "%s\n" "$as_me: WARNING: cannot determine strerror_r() style: edit lib/curl_config.h manually." >&2;} + fi + # + + + # + tst_links_stricmp="unknown" + tst_proto_stricmp="unknown" + tst_compi_stricmp="unknown" + tst_allow_stricmp="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if stricmp can be linked" >&5 +printf %s "checking if stricmp can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define stricmp innocuous_stricmp +#ifdef __STDC__ +# include +#else +# include +#endif +#undef stricmp +#ifdef __cplusplus +extern "C" +#endif +char stricmp (); +#if defined __stub_stricmp || defined __stub___stricmp +choke me +#endif + +int main (void) +{ +return stricmp (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_stricmp="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_stricmp="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_stricmp" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if stricmp is prototyped" >&5 +printf %s "checking if stricmp is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_string + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "stricmp" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_stricmp="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_stricmp="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_stricmp" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if stricmp is compilable" >&5 +printf %s "checking if stricmp is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_string + +int main (void) +{ + + if(0 != stricmp(0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_stricmp="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_stricmp="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_stricmp" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if stricmp usage allowed" >&5 +printf %s "checking if stricmp usage allowed... " >&6; } + if test "x$curl_disallow_stricmp" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_stricmp="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_stricmp="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if stricmp might be used" >&5 +printf %s "checking if stricmp might be used... " >&6; } + if test "$tst_links_stricmp" = "yes" && + test "$tst_proto_stricmp" = "yes" && + test "$tst_compi_stricmp" = "yes" && + test "$tst_allow_stricmp" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_STRICMP 1" >>confdefs.h + + curl_cv_func_stricmp="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_stricmp="no" + fi + + + # + tst_links_strtok_r="unknown" + tst_proto_strtok_r="unknown" + tst_compi_strtok_r="unknown" + tst_allow_strtok_r="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strtok_r can be linked" >&5 +printf %s "checking if strtok_r can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define strtok_r innocuous_strtok_r +#ifdef __STDC__ +# include +#else +# include +#endif +#undef strtok_r +#ifdef __cplusplus +extern "C" +#endif +char strtok_r (); +#if defined __stub_strtok_r || defined __stub___strtok_r +choke me +#endif + +int main (void) +{ +return strtok_r (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_strtok_r="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_strtok_r="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_strtok_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strtok_r is prototyped" >&5 +printf %s "checking if strtok_r is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_string + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "strtok_r" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_strtok_r="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_strtok_r="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_strtok_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strtok_r is compilable" >&5 +printf %s "checking if strtok_r is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_string + +int main (void) +{ + + if(0 != strtok_r(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_strtok_r="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_strtok_r="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_strtok_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strtok_r usage allowed" >&5 +printf %s "checking if strtok_r usage allowed... " >&6; } + if test "x$curl_disallow_strtok_r" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_strtok_r="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_strtok_r="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strtok_r might be used" >&5 +printf %s "checking if strtok_r might be used... " >&6; } + if test "$tst_links_strtok_r" = "yes" && + test "$tst_proto_strtok_r" = "yes" && + test "$tst_compi_strtok_r" = "yes" && + test "$tst_allow_strtok_r" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_STRTOK_R 1" >>confdefs.h + + curl_cv_func_strtok_r="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_strtok_r="no" + fi + + + # + tst_links_strtoll="unknown" + tst_proto_strtoll="unknown" + tst_compi_strtoll="unknown" + tst_allow_strtoll="unknown" + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strtoll can be linked" >&5 +printf %s "checking if strtoll can be linked... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#define strtoll innocuous_strtoll +#ifdef __STDC__ +# include +#else +# include +#endif +#undef strtoll +#ifdef __cplusplus +extern "C" +#endif +char strtoll (); +#if defined __stub_strtoll || defined __stub___strtoll +choke me +#endif + +int main (void) +{ +return strtoll (); + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_links_strtoll="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_links_strtoll="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + # + if test "$tst_links_strtoll" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strtoll is prototyped" >&5 +printf %s "checking if strtoll is prototyped... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + $curl_includes_stdlib + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "strtoll" >/dev/null 2>&1 +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_proto_strtoll="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_proto_strtoll="no" + +fi +rm -rf conftest* + + fi + # + if test "$tst_proto_strtoll" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strtoll is compilable" >&5 +printf %s "checking if strtoll is compilable... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + $curl_includes_stdlib + +int main (void) +{ + + if(0 != strtoll(0, 0, 0)) + return 1; + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_compi_strtoll="yes" + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_compi_strtoll="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + fi + # + if test "$tst_compi_strtoll" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strtoll usage allowed" >&5 +printf %s "checking if strtoll usage allowed... " >&6; } + if test "x$curl_disallow_strtoll" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tst_allow_strtoll="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + tst_allow_strtoll="no" + fi + fi + # + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if strtoll might be used" >&5 +printf %s "checking if strtoll might be used... " >&6; } + if test "$tst_links_strtoll" = "yes" && + test "$tst_proto_strtoll" = "yes" && + test "$tst_compi_strtoll" = "yes" && + test "$tst_allow_strtoll" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define HAVE_STRTOLL 1" >>confdefs.h + + curl_cv_func_strtoll="yes" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_cv_func_strtoll="no" + fi + + +case $host in + *msdosdjgpp) + ac_cv_func_pipe=no + skipcheck_pipe=yes + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: skip check for pipe on msdosdjgpp" >&5 +printf "%s\n" "$as_me: skip check for pipe on msdosdjgpp" >&6;} + ;; +esac + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC options needed to detect all undeclared functions" >&5 +printf %s "checking for $CC options needed to detect all undeclared functions... " >&6; } +if test ${ac_cv_c_undeclared_builtin_options+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_save_CFLAGS=$CFLAGS + ac_cv_c_undeclared_builtin_options='cannot detect' + for ac_arg in '' -fno-builtin; do + CFLAGS="$ac_save_CFLAGS $ac_arg" + # This test program should *not* compile successfully. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int main (void) +{ +(void) strchr; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + +else $as_nop + # This test program should compile successfully. + # No library function is consistently available on + # freestanding implementations, so test against a dummy + # declaration. Include always-available headers on the + # off chance that they somehow elicit warnings. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include +extern void ac_decl (int, char *); + +int main (void) +{ +(void) ac_decl (0, (char *) 0); + (void) ac_decl; + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + if test x"$ac_arg" = x +then : + ac_cv_c_undeclared_builtin_options='none needed' +else $as_nop + ac_cv_c_undeclared_builtin_options=$ac_arg +fi + break +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + done + CFLAGS=$ac_save_CFLAGS + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_undeclared_builtin_options" >&5 +printf "%s\n" "$ac_cv_c_undeclared_builtin_options" >&6; } + case $ac_cv_c_undeclared_builtin_options in #( + 'cannot detect') : + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot make $CC report undeclared builtins +See \`config.log' for more details" "$LINENO" 5; } ;; #( + 'none needed') : + ac_c_undeclared_builtin_options='' ;; #( + *) : + ac_c_undeclared_builtin_options=$ac_cv_c_undeclared_builtin_options ;; +esac + +ac_fn_check_decl "$LINENO" "getpwuid_r" "ac_cv_have_decl_getpwuid_r" "#include + #include +" "$ac_c_undeclared_builtin_options" "CFLAGS" +if test "x$ac_cv_have_decl_getpwuid_r" = xyes +then : + ac_have_decl=1 +else $as_nop + ac_have_decl=0 +fi +printf "%s\n" "#define HAVE_DECL_GETPWUID_R $ac_have_decl" >>confdefs.h +if test $ac_have_decl = 1 +then : + +else $as_nop + +printf "%s\n" "#define HAVE_DECL_GETPWUID_R_MISSING 1" >>confdefs.h + +fi + + + + for ac_func in _fseeki64 arc4random fnmatch fseeko geteuid getpass_r getppid getpwuid getpwuid_r getrlimit gettimeofday if_nametoindex mach_absolute_time pipe sched_yield sendmsg setlocale setmode setrlimit snprintf utime utimes +do : + as_ac_var=`printf "%s\n" "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes" +then : + cat >>confdefs.h <<_ACEOF +#define `printf "%s\n" "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + + +else $as_nop + + func="$ac_func" + eval skipcheck=\$skipcheck_$func + if test "x$skipcheck" != "xyes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking deeper for $func" >&5 +printf %s "checking deeper for $func... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + +int main (void) +{ + + $func (); + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + eval "ac_cv_func_$func=yes" + +cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$func" | sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/' | sed 's/^A-Z0-9_/_/g'` 1 +_ACEOF + + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: but still no" >&5 +printf "%s\n" "but still no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + fi + +fi + +done + +ac_fn_check_decl "$LINENO" "fseeko" "ac_cv_have_decl_fseeko" "#include +" "$ac_c_undeclared_builtin_options" "CFLAGS" +if test "x$ac_cv_have_decl_fseeko" = xyes +then : + +printf "%s\n" "#define HAVE_DECL_FSEEKO 1" >>confdefs.h + +fi + + + # + tst_method="unknown" + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to set a socket into non-blocking mode" >&5 +printf %s "checking how to set a socket into non-blocking mode... " >&6; } + if test "x$curl_cv_func_fcntl_o_nonblock" = "xyes"; then + tst_method="fcntl O_NONBLOCK" + elif test "x$curl_cv_func_ioctl_fionbio" = "xyes"; then + tst_method="ioctl FIONBIO" + elif test "x$curl_cv_func_ioctlsocket_fionbio" = "xyes"; then + tst_method="ioctlsocket FIONBIO" + elif test "x$curl_cv_func_ioctlsocket_camel_fionbio" = "xyes"; then + tst_method="IoctlSocket FIONBIO" + elif test "x$curl_cv_func_setsockopt_so_nonblock" = "xyes"; then + tst_method="setsockopt SO_NONBLOCK" + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tst_method" >&5 +printf "%s\n" "$tst_method" >&6; } + if test "$tst_method" = "unknown"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: cannot determine non-blocking socket method." >&5 +printf "%s\n" "$as_me: WARNING: cannot determine non-blocking socket method." >&2;} + fi + + +if test "x$BUILD_DOCS" != "x0" -o "x$USE_MANUAL" != "x0"; then + # Extract the first word of "perl", so it can be a program name with args. +set dummy perl; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PERL+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PERL in + [\\/]* | ?:[\\/]*) + ac_cv_path_PERL="$PERL" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/local/bin/perl:/usr/bin/:/usr/local/bin " +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PERL="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PERL=$ac_cv_path_PERL +if test -n "$PERL"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PERL" >&5 +printf "%s\n" "$PERL" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + + + if test -z "$PERL"; then + as_fn_error $? "perl was not found, needed for docs and manual" "$LINENO" 5 + fi +fi + + if test x"$BUILD_DOCS" = x1; then + BUILD_DOCS_TRUE= + BUILD_DOCS_FALSE='#' +else + BUILD_DOCS_TRUE='#' + BUILD_DOCS_FALSE= +fi + + + +if test "$USE_MANUAL" = "1"; then + +printf "%s\n" "#define USE_MANUAL 1" >>confdefs.h + + curl_manual_msg="enabled" +fi + + if test x"$USE_MANUAL" = x1; then + USE_MANUAL_TRUE= + USE_MANUAL_FALSE='#' +else + USE_MANUAL_TRUE='#' + USE_MANUAL_FALSE= +fi + + + + # + if test "$want_ares" = "yes"; then + clean_CPPFLAGS="$CPPFLAGS" + clean_LDFLAGS="$LDFLAGS" + clean_LIBS="$LIBS" + configure_runpath=`pwd` + if test -n "$want_ares_path"; then + ARES_PCDIR="$want_ares_path/lib/pkgconfig" + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libcares options with pkg-config" >&5 +printf %s "checking for libcares options with pkg-config... " >&6; } + itexists=` + if test -n "$ARES_PCDIR"; then + PKG_CONFIG_LIBDIR="$ARES_PCDIR" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists libcares >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + if test "$PKGCONFIG" != "no" ; then + ares_LIBS=` + if test -n "$ARES_PCDIR"; then + PKG_CONFIG_LIBDIR="$ARES_PCDIR" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-l libcares` + ares_LDFLAGS=` + if test -n "$ARES_PCDIR"; then + PKG_CONFIG_LIBDIR="$ARES_PCDIR" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --libs-only-L libcares` + ares_CPPFLAGS=` + if test -n "$ARES_PCDIR"; then + PKG_CONFIG_LIBDIR="$ARES_PCDIR" + export PKG_CONFIG_LIBDIR + fi + + $PKGCONFIG --cflags-only-I libcares` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: pkg-config: ares LIBS: \"$ares_LIBS\"" >&5 +printf "%s\n" "$as_me: pkg-config: ares LIBS: \"$ares_LIBS\"" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: pkg-config: ares LDFLAGS: \"$ares_LDFLAGS\"" >&5 +printf "%s\n" "$as_me: pkg-config: ares LDFLAGS: \"$ares_LDFLAGS\"" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: pkg-config: ares CPPFLAGS: \"$ares_CPPFLAGS\"" >&5 +printf "%s\n" "$as_me: pkg-config: ares CPPFLAGS: \"$ares_CPPFLAGS\"" >&6;} + else + ares_CPPFLAGS="-I$want_ares_path/include" + ares_LDFLAGS="-L$want_ares_path/lib" + ares_LIBS="-lcares" + fi + else + + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKGCONFIG="$PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKGCONFIG=$ac_cv_path_PKGCONFIG +if test -n "$PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKGCONFIG" >&5 +printf "%s\n" "$PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKGCONFIG"; then + ac_pt_PKGCONFIG=$PKGCONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_ac_pt_PKGCONFIG+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $ac_pt_PKGCONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKGCONFIG="$ac_pt_PKGCONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$PATH:/usr/bin:/usr/local/bin" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKGCONFIG="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKGCONFIG=$ac_cv_path_ac_pt_PKGCONFIG +if test -n "$ac_pt_PKGCONFIG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKGCONFIG" >&5 +printf "%s\n" "$ac_pt_PKGCONFIG" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_pt_PKGCONFIG" = x; then + PKGCONFIG="no" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKGCONFIG=$ac_pt_PKGCONFIG + fi +else + PKGCONFIG="$ac_cv_path_PKGCONFIG" +fi + + fi + + if test "x$PKGCONFIG" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libcares options with pkg-config" >&5 +printf %s "checking for libcares options with pkg-config... " >&6; } + itexists=` + if test -n ""; then + PKG_CONFIG_LIBDIR="" + export PKG_CONFIG_LIBDIR + fi + $PKGCONFIG --exists libcares >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + PKGCONFIG="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found" >&5 +printf "%s\n" "found" >&6; } + fi + fi + + if test "$PKGCONFIG" != "no" ; then + ares_LIBS=`$PKGCONFIG --libs-only-l libcares` + ares_LDFLAGS=`$PKGCONFIG --libs-only-L libcares` + ares_CPPFLAGS=`$PKGCONFIG --cflags-only-I libcares` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: pkg-config: ares_LIBS: \"$ares_LIBS\"" >&5 +printf "%s\n" "$as_me: pkg-config: ares_LIBS: \"$ares_LIBS\"" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: pkg-config: ares_LDFLAGS: \"$ares_LDFLAGS\"" >&5 +printf "%s\n" "$as_me: pkg-config: ares_LDFLAGS: \"$ares_LDFLAGS\"" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: pkg-config: ares_CPPFLAGS: \"$ares_CPPFLAGS\"" >&5 +printf "%s\n" "$as_me: pkg-config: ares_CPPFLAGS: \"$ares_CPPFLAGS\"" >&6;} + else + ares_CPPFLAGS="" + ares_LDFLAGS="" + ares_LIBS="-lcares" + fi + fi + # + CPPFLAGS="$clean_CPPFLAGS $ares_CPPFLAGS" + LDFLAGS="$clean_LDFLAGS $ares_LDFLAGS" + LIBS="$ares_LIBS $clean_LIBS" + # + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking that c-ares is good and recent enough" >&5 +printf %s "checking that c-ares is good and recent enough... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#include + /* set of dummy functions in case c-ares was built with debug */ + void curl_dofree() { } + void curl_sclose() { } + void curl_domalloc() { } + void curl_docalloc() { } + void curl_socket() { } + +int main (void) +{ + + ares_channel channel; + ares_cancel(channel); /* added in 1.2.0 */ + ares_process_fd(channel, 0, 0); /* added in 1.4.0 */ + ares_dup(&channel, channel); /* added in 1.6.0 */ + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + as_fn_error $? "c-ares library defective or too old" "$LINENO" 5 + CPPFLAGS="$clean_CPPFLAGS" + LDFLAGS="$clean_LDFLAGS" + LIBS="$clean_LIBS" + # prevent usage + want_ares="no" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + + if test "$want_ares" = "yes"; then + +printf "%s\n" "#define USE_ARES 1" >>confdefs.h + + +printf "%s\n" "#define CARES_NO_DEPRECATED 1" >>confdefs.h + + USE_ARES=1 + + curl_res_msg="c-ares" + fi + fi + + +if test "x$curl_cv_native_windows" != "xyes" && + test "x$enable_shared" = "xyes"; then + build_libhostname=yes +else + build_libhostname=no +fi + if test x$build_libhostname = xyes; then + BUILD_LIBHOSTNAME_TRUE= + BUILD_LIBHOSTNAME_FALSE='#' +else + BUILD_LIBHOSTNAME_TRUE='#' + BUILD_LIBHOSTNAME_FALSE= +fi + + +if test "x$want_ares" != xyes; then + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable the threaded resolver" >&5 +printf %s "checking whether to enable the threaded resolver... " >&6; } + OPT_THRES="default" + # Check whether --enable-threaded_resolver was given. +if test ${enable_threaded_resolver+y} +then : + enableval=$enable_threaded_resolver; OPT_THRES=$enableval +fi + + case "$OPT_THRES" in + no) + want_thres="no" + ;; + *) + want_thres="yes" + ;; + esac + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $want_thres" >&5 +printf "%s\n" "$want_thres" >&6; } + +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to use POSIX threads for threaded resolver" >&5 +printf %s "checking whether to use POSIX threads for threaded resolver... " >&6; } +# Check whether --enable-pthreads was given. +if test ${enable_pthreads+y} +then : + enableval=$enable_pthreads; case "$enableval" in + no) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + want_pthreads=no + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + want_pthreads=yes + ;; + esac +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: auto" >&5 +printf "%s\n" "auto" >&6; } + want_pthreads=auto + + +fi + + +if test "$want_pthreads" != "no"; then + if test "$want_pthreads" = "yes" && test "$dontwant_rt" = "yes"; then + as_fn_error $? "options --enable-pthreads and --disable-rt are mutually exclusive" "$LINENO" 5 + fi + if test "$dontwant_rt" != "no"; then + if test "$want_pthreads" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: --enable-pthreads Ignored since librt is disabled." >&5 +printf "%s\n" "$as_me: WARNING: --enable-pthreads Ignored since librt is disabled." >&2;} + fi + want_pthreads=no + fi +fi + +if test "$want_pthreads" != "no" && test "$want_thres" != "yes"; then + want_pthreads=no +fi + +if test "$want_pthreads" != "no"; then + ac_fn_c_check_header_compile "$LINENO" "pthread.h" "ac_cv_header_pthread_h" "$ac_includes_default" +if test "x$ac_cv_header_pthread_h" = xyes +then : + +printf "%s\n" "#define HAVE_PTHREAD_H 1" >>confdefs.h + + save_CFLAGS="$CFLAGS" + save_LIBS="$LIBS" + + LIBS= + ac_fn_c_check_func "$LINENO" "pthread_create" "ac_cv_func_pthread_create" +if test "x$ac_cv_func_pthread_create" = xyes +then : + USE_THREADS_POSIX=1 +fi + + LIBS="$save_LIBS" + + case $host in + *-hp-hpux*) + USE_THREADS_POSIX="" + ;; + *) + ;; + esac + + if test "$USE_THREADS_POSIX" != "1" + then + # assign PTHREAD for pkg-config use + PTHREAD=" -pthread" + + case $host in + *-ibm-aix*) + COMPILER_VERSION=`"$CC" -qversion 2>/dev/null` + if test x"$COMPILER_VERSION" = "x"; then + CFLAGS="$CFLAGS -pthread" + else + CFLAGS="$CFLAGS -qthreaded" + fi + ;; + powerpc-*amigaos*) + PTHREAD=" -lpthread" + ;; + *) + CFLAGS="$CFLAGS -pthread" + ;; + esac + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthread" >&5 +printf %s "checking for pthread_create in -lpthread... " >&6; } +if test ${ac_cv_lib_pthread_pthread_create+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_check_lib_save_LIBS=$LIBS +LIBS="-lpthread $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + +#ifdef __cplusplus +extern "C" +#endif +char pthread_create (); +int main (void) +{ +return pthread_create (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + ac_cv_lib_pthread_pthread_create=yes +else $as_nop + ac_cv_lib_pthread_pthread_create=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread_pthread_create" >&5 +printf "%s\n" "$ac_cv_lib_pthread_pthread_create" >&6; } +if test "x$ac_cv_lib_pthread_pthread_create" = xyes +then : + USE_THREADS_POSIX=1 +else $as_nop + CFLAGS="$save_CFLAGS" +fi + + fi + + if test "x$USE_THREADS_POSIX" = "x1" + then + +printf "%s\n" "#define USE_THREADS_POSIX 1" >>confdefs.h + + curl_res_msg="POSIX threaded" + fi + +fi + +fi + +if test "$want_thres" = "yes" && test "x$USE_THREADS_POSIX" != "x1"; then + if test "$want_pthreads" = "yes"; then + as_fn_error $? "--enable-pthreads but pthreads was not found" "$LINENO" 5 + fi + if test "$curl_cv_native_windows" = "yes"; then + USE_THREADS_WIN32=1 + +printf "%s\n" "#define USE_THREADS_WIN32 1" >>confdefs.h + + curl_res_msg="Win32 threaded" + else + as_fn_error $? "Threaded resolver enabled but no thread library found" "$LINENO" 5 + fi +fi + +ac_fn_c_check_header_compile "$LINENO" "dirent.h" "ac_cv_header_dirent_h" "$ac_includes_default" +if test "x$ac_cv_header_dirent_h" = xyes +then : + +printf "%s\n" "#define HAVE_DIRENT_H 1" >>confdefs.h + + ac_fn_c_check_func "$LINENO" "opendir" "ac_cv_func_opendir" +if test "x$ac_cv_func_opendir" = xyes +then : + +printf "%s\n" "#define HAVE_OPENDIR 1" >>confdefs.h + +fi + + + +fi + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking convert -I options to -isystem" >&5 +printf %s "checking convert -I options to -isystem... " >&6; } + if test "$compiler_id" = "GNU_C" || + test "$compiler_id" = "CLANG"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + tmp_has_include="no" + tmp_chg_FLAGS="$CFLAGS" + for word1 in $tmp_chg_FLAGS; do + case "$word1" in + -I*) + tmp_has_include="yes" + ;; + esac + done + if test "$tmp_has_include" = "yes"; then + tmp_chg_FLAGS=`echo "$tmp_chg_FLAGS" | "$SED" 's/^-I/ -isystem /g'` + tmp_chg_FLAGS=`echo "$tmp_chg_FLAGS" | "$SED" 's/ -I/ -isystem /g'` + CFLAGS="$tmp_chg_FLAGS" + squeeze CFLAGS + fi + tmp_has_include="no" + tmp_chg_FLAGS="$CPPFLAGS" + for word1 in $tmp_chg_FLAGS; do + case "$word1" in + -I*) + tmp_has_include="yes" + ;; + esac + done + if test "$tmp_has_include" = "yes"; then + tmp_chg_FLAGS=`echo "$tmp_chg_FLAGS" | "$SED" 's/^-I/ -isystem /g'` + tmp_chg_FLAGS=`echo "$tmp_chg_FLAGS" | "$SED" 's/ -I/ -isystem /g'` + CPPFLAGS="$tmp_chg_FLAGS" + squeeze CPPFLAGS + fi + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable verbose strings" >&5 +printf %s "checking whether to enable verbose strings... " >&6; } +# Check whether --enable-verbose was given. +if test ${enable_verbose+y} +then : + enableval=$enable_verbose; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_VERBOSE_STRINGS 1" >>confdefs.h + + curl_verbose_msg="no" + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable SSPI support (Windows native builds only)" >&5 +printf %s "checking whether to enable SSPI support (Windows native builds only)... " >&6; } +# Check whether --enable-sspi was given. +if test ${enable_sspi+y} +then : + enableval=$enable_sspi; case "$enableval" in + yes) + if test "$curl_cv_native_windows" = "yes"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +printf "%s\n" "#define USE_WINDOWS_SSPI 1" >>confdefs.h + + USE_WINDOWS_SSPI=1 + + curl_sspi_msg="enabled" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: --enable-sspi Ignored. Only supported on native Windows builds." >&5 +printf "%s\n" "$as_me: WARNING: --enable-sspi Ignored. Only supported on native Windows builds." >&2;} + fi + ;; + *) + if test "x$SCHANNEL_ENABLED" = "x1"; then + # --with-schannel implies --enable-sspi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + ;; + esac +else $as_nop + if test "x$SCHANNEL_ENABLED" = "x1"; then + # --with-schannel implies --enable-sspi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable basic authentication method" >&5 +printf %s "checking whether to enable basic authentication method... " >&6; } +# Check whether --enable-basic-auth was given. +if test ${enable_basic_auth+y} +then : + enableval=$enable_basic_auth; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_BASIC_AUTH 1" >>confdefs.h + + CURL_DISABLE_BASIC_AUTH=1 + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable bearer authentication method" >&5 +printf %s "checking whether to enable bearer authentication method... " >&6; } +# Check whether --enable-bearer-auth was given. +if test ${enable_bearer_auth+y} +then : + enableval=$enable_bearer_auth; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_BEARER_AUTH 1" >>confdefs.h + + CURL_DISABLE_BEARER_AUTH=1 + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable digest authentication method" >&5 +printf %s "checking whether to enable digest authentication method... " >&6; } +# Check whether --enable-digest-auth was given. +if test ${enable_digest_auth+y} +then : + enableval=$enable_digest_auth; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_DIGEST_AUTH 1" >>confdefs.h + + CURL_DISABLE_DIGEST_AUTH=1 + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable kerberos authentication method" >&5 +printf %s "checking whether to enable kerberos authentication method... " >&6; } +# Check whether --enable-kerberos-auth was given. +if test ${enable_kerberos_auth+y} +then : + enableval=$enable_kerberos_auth; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_KERBEROS_AUTH 1" >>confdefs.h + + CURL_DISABLE_KERBEROS_AUTH=1 + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable negotiate authentication method" >&5 +printf %s "checking whether to enable negotiate authentication method... " >&6; } +# Check whether --enable-negotiate-auth was given. +if test ${enable_negotiate_auth+y} +then : + enableval=$enable_negotiate_auth; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_NEGOTIATE_AUTH 1" >>confdefs.h + + CURL_DISABLE_NEGOTIATE_AUTH=1 + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable aws sig methods" >&5 +printf %s "checking whether to enable aws sig methods... " >&6; } +# Check whether --enable-aws was given. +if test ${enable_aws+y} +then : + enableval=$enable_aws; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_AWS 1" >>confdefs.h + + CURL_DISABLE_AWS=1 + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support NTLM" >&5 +printf %s "checking whether to support NTLM... " >&6; } +# Check whether --enable-ntlm was given. +if test ${enable_ntlm+y} +then : + enableval=$enable_ntlm; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_NTLM 1" >>confdefs.h + + CURL_DISABLE_NTLM=1 + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable TLS-SRP authentication" >&5 +printf %s "checking whether to enable TLS-SRP authentication... " >&6; } +# Check whether --enable-tls-srp was given. +if test ${enable_tls_srp+y} +then : + enableval=$enable_tls_srp; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + want_tls_srp=no + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + want_tls_srp=yes + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + want_tls_srp=yes + +fi + + +if test "$want_tls_srp" = "yes" && ( test "x$HAVE_GNUTLS_SRP" = "x1" || test "x$HAVE_OPENSSL_SRP" = "x1") ; then + +printf "%s\n" "#define USE_TLS_SRP 1" >>confdefs.h + + USE_TLS_SRP=1 + curl_tls_srp_msg="enabled" +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to enable Unix domain sockets" >&5 +printf %s "checking whether to enable Unix domain sockets... " >&6; } +# Check whether --enable-unix-sockets was given. +if test ${enable_unix_sockets+y} +then : + enableval=$enable_unix_sockets; case "$enableval" in + no) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + want_unix_sockets=no + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + want_unix_sockets=yes + ;; + esac +else $as_nop + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: auto" >&5 +printf "%s\n" "auto" >&6; } + want_unix_sockets=auto + + +fi + +if test "x$want_unix_sockets" != "xno"; then + if test "x$curl_cv_native_windows" = "xyes"; then + USE_UNIX_SOCKETS=1 + +printf "%s\n" "#define USE_UNIX_SOCKETS 1" >>confdefs.h + + curl_unix_sockets_msg="enabled" + else + ac_fn_c_check_member "$LINENO" "struct sockaddr_un" "sun_path" "ac_cv_member_struct_sockaddr_un_sun_path" " + #include + +" +if test "x$ac_cv_member_struct_sockaddr_un_sun_path" = xyes +then : + + +printf "%s\n" "#define USE_UNIX_SOCKETS 1" >>confdefs.h + + USE_UNIX_SOCKETS=1 + + curl_unix_sockets_msg="enabled" + +else $as_nop + + if test "x$want_unix_sockets" = "xyes"; then + as_fn_error $? "--enable-unix-sockets is not available on this platform!" "$LINENO" 5 + fi + +fi + + fi +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support cookies" >&5 +printf %s "checking whether to support cookies... " >&6; } +# Check whether --enable-cookies was given. +if test ${enable_cookies+y} +then : + enableval=$enable_cookies; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_COOKIES 1" >>confdefs.h + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support socketpair" >&5 +printf %s "checking whether to support socketpair... " >&6; } +# Check whether --enable-socketpair was given. +if test ${enable_socketpair+y} +then : + enableval=$enable_socketpair; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_SOCKETPAIR 1" >>confdefs.h + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support HTTP authentication" >&5 +printf %s "checking whether to support HTTP authentication... " >&6; } +# Check whether --enable-http-auth was given. +if test ${enable_http_auth+y} +then : + enableval=$enable_http_auth; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_HTTP_AUTH 1" >>confdefs.h + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support DoH" >&5 +printf %s "checking whether to support DoH... " >&6; } +# Check whether --enable-doh was given. +if test ${enable_doh+y} +then : + enableval=$enable_doh; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_DOH 1" >>confdefs.h + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support the MIME API" >&5 +printf %s "checking whether to support the MIME API... " >&6; } +# Check whether --enable-mime was given. +if test ${enable_mime+y} +then : + enableval=$enable_mime; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_MIME 1" >>confdefs.h + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support binding connections locally" >&5 +printf %s "checking whether to support binding connections locally... " >&6; } +# Check whether --enable-bindlocal was given. +if test ${enable_bindlocal+y} +then : + enableval=$enable_bindlocal; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_BINDLOCAL 1" >>confdefs.h + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support the form API" >&5 +printf %s "checking whether to support the form API... " >&6; } +# Check whether --enable-form-api was given. +if test ${enable_form_api+y} +then : + enableval=$enable_form_api; case "$enableval" in + no) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_FORM_API 1" >>confdefs.h + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + test "$enable_mime" = no && + as_fn_error $? "MIME support needs to be enabled in order to enable form API support" "$LINENO" 5 + ;; + esac +else $as_nop + + if test "$enable_mime" = no; then + enable_form_api=no + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_FORM_API 1" >>confdefs.h + + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + fi + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support date parsing" >&5 +printf %s "checking whether to support date parsing... " >&6; } +# Check whether --enable-dateparse was given. +if test ${enable_dateparse+y} +then : + enableval=$enable_dateparse; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_PARSEDATE 1" >>confdefs.h + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support netrc parsing" >&5 +printf %s "checking whether to support netrc parsing... " >&6; } +# Check whether --enable-netrc was given. +if test ${enable_netrc+y} +then : + enableval=$enable_netrc; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_NETRC 1" >>confdefs.h + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support progress-meter" >&5 +printf %s "checking whether to support progress-meter... " >&6; } +# Check whether --enable-progress-meter was given. +if test ${enable_progress_meter+y} +then : + enableval=$enable_progress_meter; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_PROGRESS_METER 1" >>confdefs.h + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support DNS shuffling" >&5 +printf %s "checking whether to support DNS shuffling... " >&6; } +# Check whether --enable-dnsshuffle was given. +if test ${enable_dnsshuffle+y} +then : + enableval=$enable_dnsshuffle; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_SHUFFLE_DNS 1" >>confdefs.h + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support curl_easy_option*" >&5 +printf %s "checking whether to support curl_easy_option*... " >&6; } +# Check whether --enable-get-easy-options was given. +if test ${enable_get_easy_options+y} +then : + enableval=$enable_get_easy_options; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_GETOPTIONS 1" >>confdefs.h + + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support alt-svc" >&5 +printf %s "checking whether to support alt-svc... " >&6; } +# Check whether --enable-alt-svc was given. +if test ${enable_alt_svc+y} +then : + enableval=$enable_alt_svc; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +printf "%s\n" "#define CURL_DISABLE_ALTSVC 1" >>confdefs.h + + curl_altsvc_msg="no"; + enable_altsvc="no" + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support headers-api" >&5 +printf %s "checking whether to support headers-api... " >&6; } +# Check whether --enable-headers-api was given. +if test ${enable_headers_api+y} +then : + enableval=$enable_headers_api; case "$enableval" in + no) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + curl_headers_msg="no (--enable-headers-api)" + +printf "%s\n" "#define CURL_DISABLE_HEADERS_API 1" >>confdefs.h + + ;; + *) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + +fi + + +if test -n "$SSL_ENABLED"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support HSTS" >&5 +printf %s "checking whether to support HSTS... " >&6; } + # Check whether --enable-hsts was given. +if test ${enable_hsts+y} +then : + enableval=$enable_hsts; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + hsts="no" + ;; + *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $hsts" >&5 +printf "%s\n" "$hsts" >&6; } + +fi + +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: disables HSTS due to lack of SSL" >&5 +printf "%s\n" "$as_me: disables HSTS due to lack of SSL" >&6;} + hsts="no" +fi + +if test "x$hsts" != "xyes"; then + curl_hsts_msg="no (--enable-hsts)"; + +printf "%s\n" "#define CURL_DISABLE_HSTS 1" >>confdefs.h + +fi + + +if test "x$want_httpsrr" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: HTTPSRR support is available" >&5 +printf "%s\n" "HTTPSRR support is available" >&6; } + +printf "%s\n" "#define USE_HTTPSRR 1" >>confdefs.h + + experimental="$experimental HTTPSRR" +fi + +if test "x$want_ech" != "xno"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether ECH support is available" >&5 +printf %s "checking whether ECH support is available... " >&6; } + + ECH_ENABLED=0 + ECH_SUPPORT='' + + if test "x$OPENSSL_ENABLED" = "x1"; then + + for ac_func in SSL_ech_set1_echconfig +do : + ac_fn_c_check_func "$LINENO" "SSL_ech_set1_echconfig" "ac_cv_func_SSL_ech_set1_echconfig" +if test "x$ac_cv_func_SSL_ech_set1_echconfig" = xyes +then : + printf "%s\n" "#define HAVE_SSL_ECH_SET1_ECHCONFIG 1" >>confdefs.h + ECH_SUPPORT="ECH support available via OpenSSL with SSL_ech_set1_echconfig" + ECH_ENABLED=1 +fi + +done + fi + if test "x$OPENSSL_ENABLED" = "x1"; then + + for ac_func in SSL_set1_ech_config_list +do : + ac_fn_c_check_func "$LINENO" "SSL_set1_ech_config_list" "ac_cv_func_SSL_set1_ech_config_list" +if test "x$ac_cv_func_SSL_set1_ech_config_list" = xyes +then : + printf "%s\n" "#define HAVE_SSL_SET1_ECH_CONFIG_LIST 1" >>confdefs.h + ECH_SUPPORT="ECH support available via boringssl with SSL_set1_ech_config_list" + ECH_ENABLED=1 +fi + +done + fi + if test "x$WOLFSSL_ENABLED" = "x1"; then + + for ac_func in wolfSSL_CTX_GenerateEchConfig +do : + ac_fn_c_check_func "$LINENO" "wolfSSL_CTX_GenerateEchConfig" "ac_cv_func_wolfSSL_CTX_GenerateEchConfig" +if test "x$ac_cv_func_wolfSSL_CTX_GenerateEchConfig" = xyes +then : + printf "%s\n" "#define HAVE_WOLFSSL_CTX_GENERATEECHCONFIG 1" >>confdefs.h + ECH_SUPPORT="ECH support available via WolfSSL with wolfSSL_CTX_GenerateEchConfig" + ECH_ENABLED=1 +fi + +done + fi + + if test "x$ECH_ENABLED" = "x1"; then + +printf "%s\n" "#define USE_HTTPSRR 1" >>confdefs.h + + +printf "%s\n" "#define USE_ECH 1" >>confdefs.h + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ECH_SUPPORT" >&5 +printf "%s\n" "$ECH_SUPPORT" >&6; } + experimental="$experimental ECH" + else + as_fn_error $? "--enable-ech ignored: No ECH support found" "$LINENO" 5 + fi +fi + +if test "x$OPENSSL_ENABLED" = "x1"; then + ac_fn_c_check_func "$LINENO" "SSL_set0_wbio" "ac_cv_func_SSL_set0_wbio" +if test "x$ac_cv_func_SSL_set0_wbio" = xyes +then : + printf "%s\n" "#define HAVE_SSL_SET0_WBIO 1" >>confdefs.h + +fi + +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to support WebSockets" >&5 +printf %s "checking whether to support WebSockets... " >&6; } +# Check whether --enable-websockets was given. +if test ${enable_websockets+y} +then : + enableval=$enable_websockets; case "$enableval" in + no) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + ;; + *) + if test ${ac_cv_sizeof_curl_off_t} -gt 4; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + curl_ws_msg="enabled" + +printf "%s\n" "#define USE_WEBSOCKETS 1" >>confdefs.h + + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS WS" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS WSS" + fi + experimental="$experimental Websockets" + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: Websockets disabled due to lack of >32 bit curl_off_t" >&5 +printf "%s\n" "$as_me: WARNING: Websockets disabled due to lack of >32 bit curl_off_t" >&2;} + fi + ;; + esac +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + +fi + + + + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether hiding of library internal symbols will actually happen" >&5 +printf %s "checking whether hiding of library internal symbols will actually happen... " >&6; } + CFLAG_CURL_SYMBOL_HIDING="" + doing_symbol_hiding="no" + if test "$want_symbol_hiding" = "yes" && + test "$supports_symbol_hiding" = "yes"; then + doing_symbol_hiding="yes" + CFLAG_CURL_SYMBOL_HIDING="$symbol_hiding_CFLAGS" + +printf "%s\n" "#define CURL_EXTERN_SYMBOL $symbol_hiding_EXTERN" >>confdefs.h + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + if test x$doing_symbol_hiding = xyes; then + DOING_CURL_SYMBOL_HIDING_TRUE= + DOING_CURL_SYMBOL_HIDING_FALSE='#' +else + DOING_CURL_SYMBOL_HIDING_TRUE='#' + DOING_CURL_SYMBOL_HIDING_FALSE= +fi + + + + +LIBCURL_LIBS="$LIBS$PTHREAD" + + + + + +BLANK_AT_MAKETIME= + + + if test x$cross_compiling = xyes; then + CROSSCOMPILING_TRUE= + CROSSCOMPILING_FALSE='#' +else + CROSSCOMPILING_TRUE='#' + CROSSCOMPILING_FALSE= +fi + + +ENABLE_SHARED="$enable_shared" + + +ENABLE_STATIC="$enable_static" + + +if test "x$enable_shared" = "xno"; then + LIBCURL_NO_SHARED=$LIBCURL_LIBS +else + LIBCURL_NO_SHARED= +fi + + +rm $compilersh + + +if test "x$OPENSSL_ENABLED" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES SSL" +elif test -n "$SSL_ENABLED"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES SSL" +fi +if test "x$IPV6_ENABLED" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES IPv6" +fi +if test "x$USE_UNIX_SOCKETS" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES UnixSockets" +fi +if test "x$HAVE_LIBZ" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES libz" +fi +if test "x$HAVE_BROTLI" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES brotli" +fi +if test "x$HAVE_ZSTD" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES zstd" +fi +if test "x$USE_ARES" = "x1" -o "x$USE_THREADS_POSIX" = "x1" \ + -o "x$USE_THREADS_WIN32" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES AsynchDNS" +fi +if test "x$IDN_ENABLED" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES IDN" +fi +if test "x$USE_WINDOWS_SSPI" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES SSPI" +fi + +if test "x$HAVE_GSSAPI" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES GSS-API" +fi + +if test "x$curl_psl_msg" = "xenabled"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES PSL" +fi + +if test "x$curl_gsasl_msg" = "xenabled"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES GSASL" +fi + +if test "x$enable_altsvc" = "xyes"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES alt-svc" +fi +if test "x$hsts" = "xyes"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES HSTS" +fi + +if test "x$CURL_DISABLE_NEGOTIATE_AUTH" != "x1" -a \ + \( "x$HAVE_GSSAPI" = "x1" -o "x$USE_WINDOWS_SSPI" = "x1" \); then + SUPPORT_FEATURES="$SUPPORT_FEATURES SPNEGO" +fi + +if test "x$CURL_DISABLE_KERBEROS_AUTH" != "x1" -a \ + \( "x$HAVE_GSSAPI" = "x1" -o "x$USE_WINDOWS_SSPI" = "x1" \); then + SUPPORT_FEATURES="$SUPPORT_FEATURES Kerberos" +fi + +use_curl_ntlm_core=no + +if test "x$CURL_DISABLE_NTLM" != "x1"; then + if test "x$OPENSSL_ENABLED" = "x1" -o "x$MBEDTLS_ENABLED" = "x1" \ + -o "x$GNUTLS_ENABLED" = "x1" \ + -o "x$SECURETRANSPORT_ENABLED" = "x1" \ + -o "x$USE_WIN32_CRYPTO" = "x1" \ + -o "x$WOLFSSL_NTLM" = "x1"; then + use_curl_ntlm_core=yes + fi + + if test "x$use_curl_ntlm_core" = "xyes" \ + -o "x$USE_WINDOWS_SSPI" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES NTLM" + fi +fi + +if test "x$USE_TLS_SRP" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES TLS-SRP" +fi + +if test "x$USE_NGHTTP2" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES HTTP2" +fi + +if test "x$USE_NGTCP2_H3" = "x1" -o "x$USE_QUICHE" = "x1" \ + -o "x$USE_OPENSSL_H3" = "x1" -o "x$USE_MSH3" = "x1"; then + if test "x$CURL_WITH_MULTI_SSL" = "x1"; then + as_fn_error $? "MultiSSL cannot be enabled with HTTP/3 and vice versa" "$LINENO" 5 + fi + SUPPORT_FEATURES="$SUPPORT_FEATURES HTTP3" +fi + +if test "x$CURL_WITH_MULTI_SSL" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES MultiSSL" +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if this build supports HTTPS-proxy" >&5 +printf %s "checking if this build supports HTTPS-proxy... " >&6; } +if test "x$CURL_DISABLE_HTTP" != "x1"; then + if test "x$https_proxy" != "xno"; then + if test "x$OPENSSL_ENABLED" = "x1" \ + -o "x$GNUTLS_ENABLED" = "x1" \ + -o "x$SECURETRANSPORT_ENABLED" = "x1" \ + -o "x$RUSTLS_ENABLED" = "x1" \ + -o "x$BEARSSL_ENABLED" = "x1" \ + -o "x$SCHANNEL_ENABLED" = "x1" \ + -o "x$GNUTLS_ENABLED" = "x1" \ + -o "x$MBEDTLS_ENABLED" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES HTTPS-proxy" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + elif test "x$WOLFSSL_ENABLED" = "x1" -a "x$WOLFSSL_FULL_BIO" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES HTTPS-proxy" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + fi +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + +if test ${ac_cv_sizeof_curl_off_t} -gt 4; then + if test ${ac_cv_sizeof_off_t} -gt 4 -o \ + "$curl_win32_file_api" = "win32_large_files"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES Largefile" + fi +fi + +if test "$tst_atomic" = "yes"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES threadsafe" +elif test "x$USE_THREADS_POSIX" = "x1" -a \ + "x$ac_cv_header_pthread_h" = "xyes"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES threadsafe" +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + + #include + +int main (void) +{ + + #if (WINVER < 0x600) && (_WIN32_WINNT < 0x600) + #error + #endif + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + + SUPPORT_FEATURES="$SUPPORT_FEATURES threadsafe" + +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +SUPPORT_FEATURES=`echo $SUPPORT_FEATURES | tr ' ' '\012' | sort | tr '\012' ' '` + + +if test "x$CURL_DISABLE_HTTP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS HTTP IPFS IPNS" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS HTTPS" + fi +fi +if test "x$CURL_DISABLE_FTP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS FTP" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS FTPS" + fi +fi +if test "x$CURL_DISABLE_FILE" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS FILE" +fi +if test "x$CURL_DISABLE_TELNET" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS TELNET" +fi +if test "x$CURL_DISABLE_LDAP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS LDAP" + if test "x$CURL_DISABLE_LDAPS" != "x1"; then + if (test "x$USE_OPENLDAP" = "x1" && test "x$SSL_ENABLED" = "x1") || + (test "x$USE_OPENLDAP" != "x1" && test "x$HAVE_LDAP_SSL" = "x1"); then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS LDAPS" + fi + fi +fi +if test "x$CURL_DISABLE_DICT" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS DICT" +fi +if test "x$CURL_DISABLE_TFTP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS TFTP" +fi +if test "x$CURL_DISABLE_GOPHER" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS GOPHER" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS GOPHERS" + fi +fi +if test "x$CURL_DISABLE_MQTT" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS MQTT" +fi +if test "x$CURL_DISABLE_POP3" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS POP3" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS POP3S" + fi +fi +if test "x$CURL_DISABLE_IMAP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS IMAP" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS IMAPS" + fi +fi +if test "x$CURL_DISABLE_SMB" != "x1" \ + -a "x$use_curl_ntlm_core" = "xyes"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SMB" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SMBS" + fi +fi +if test "x$CURL_DISABLE_SMTP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SMTP" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SMTPS" + fi +fi +if test "x$USE_LIBSSH2" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SCP" + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SFTP" +fi +if test "x$USE_LIBSSH" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SCP" + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SFTP" +fi +if test "x$USE_WOLFSSH" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SFTP" +fi +if test "x$CURL_DISABLE_RTSP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS RTSP" +fi +if test "x$USE_LIBRTMP" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS RTMP" +fi + +SUPPORT_PROTOCOLS=`echo $SUPPORT_PROTOCOLS | tr ' ' '\012' | sort | tr '\012' ' '` + + + + +squeeze CFLAGS +squeeze CPPFLAGS +squeeze DEFS +squeeze LDFLAGS +squeeze LIBS + +squeeze LIBCURL_LIBS +squeeze CURL_NETWORK_LIBS +squeeze CURL_NETWORK_AND_TIME_LIBS + +squeeze SUPPORT_FEATURES +squeeze SUPPORT_PROTOCOLS + + + + xc_bad_var_libs=no + for xc_word in $LIBS; do + case "$xc_word" in + -l* | --library=*) + : + ;; + *) + xc_bad_var_libs=yes + ;; + esac + done + if test $xc_bad_var_libs = yes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: using LIBS: $LIBS" >&5 +printf "%s\n" "$as_me: using LIBS: $LIBS" >&6;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: LIBS note: LIBS should only be used to specify libraries (-lname)." >&5 +printf "%s\n" "$as_me: LIBS note: LIBS should only be used to specify libraries (-lname)." >&6;} + fi + + + xc_bad_var_ldflags=no + for xc_word in $LDFLAGS; do + case "$xc_word" in + -D*) + xc_bad_var_ldflags=yes + ;; + -U*) + xc_bad_var_ldflags=yes + ;; + -I*) + xc_bad_var_ldflags=yes + ;; + -l* | --library=*) + xc_bad_var_ldflags=yes + ;; + esac + done + if test $xc_bad_var_ldflags = yes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: using LDFLAGS: $LDFLAGS" >&5 +printf "%s\n" "$as_me: using LDFLAGS: $LDFLAGS" >&6;} + xc_bad_var_msg="LDFLAGS note: LDFLAGS should only be used to specify linker flags, not" + for xc_word in $LDFLAGS; do + case "$xc_word" in + -D*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg macro definitions. Use CPPFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg macro definitions. Use CPPFLAGS for: $xc_word" >&6;} + ;; + -U*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg macro suppressions. Use CPPFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg macro suppressions. Use CPPFLAGS for: $xc_word" >&6;} + ;; + -I*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg include directories. Use CPPFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg include directories. Use CPPFLAGS for: $xc_word" >&6;} + ;; + -l* | --library=*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg libraries. Use LIBS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg libraries. Use LIBS for: $xc_word" >&6;} + ;; + esac + done + fi + + + xc_bad_var_cppflags=no + for xc_word in $CPPFLAGS; do + case "$xc_word" in + -rpath*) + xc_bad_var_cppflags=yes + ;; + -L* | --library-path=*) + xc_bad_var_cppflags=yes + ;; + -l* | --library=*) + xc_bad_var_cppflags=yes + ;; + esac + done + if test $xc_bad_var_cppflags = yes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: using CPPFLAGS: $CPPFLAGS" >&5 +printf "%s\n" "$as_me: using CPPFLAGS: $CPPFLAGS" >&6;} + xc_bad_var_msg="CPPFLAGS note: CPPFLAGS should only be used to specify C preprocessor flags, not" + for xc_word in $CPPFLAGS; do + case "$xc_word" in + -rpath*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg library runtime directories. Use LDFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg library runtime directories. Use LDFLAGS for: $xc_word" >&6;} + ;; + -L* | --library-path=*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg library directories. Use LDFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg library directories. Use LDFLAGS for: $xc_word" >&6;} + ;; + -l* | --library=*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg libraries. Use LIBS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg libraries. Use LIBS for: $xc_word" >&6;} + ;; + esac + done + fi + + + xc_bad_var_cflags=no + for xc_word in $CFLAGS; do + case "$xc_word" in + -D*) + xc_bad_var_cflags=yes + ;; + -U*) + xc_bad_var_cflags=yes + ;; + -I*) + xc_bad_var_cflags=yes + ;; + -rpath*) + xc_bad_var_cflags=yes + ;; + -L* | --library-path=*) + xc_bad_var_cflags=yes + ;; + -l* | --library=*) + xc_bad_var_cflags=yes + ;; + esac + done + if test $xc_bad_var_cflags = yes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: using CFLAGS: $CFLAGS" >&5 +printf "%s\n" "$as_me: using CFLAGS: $CFLAGS" >&6;} + xc_bad_var_msg="CFLAGS note: CFLAGS should only be used to specify C compiler flags, not" + for xc_word in $CFLAGS; do + case "$xc_word" in + -D*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg macro definitions. Use CPPFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg macro definitions. Use CPPFLAGS for: $xc_word" >&6;} + ;; + -U*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg macro suppressions. Use CPPFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg macro suppressions. Use CPPFLAGS for: $xc_word" >&6;} + ;; + -I*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg include directories. Use CPPFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg include directories. Use CPPFLAGS for: $xc_word" >&6;} + ;; + -rpath*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg library runtime directories. Use LDFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg library runtime directories. Use LDFLAGS for: $xc_word" >&6;} + ;; + -L* | --library-path=*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg library directories. Use LDFLAGS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg library directories. Use LDFLAGS for: $xc_word" >&6;} + ;; + -l* | --library=*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $xc_bad_var_msg libraries. Use LIBS for: $xc_word" >&5 +printf "%s\n" "$as_me: $xc_bad_var_msg libraries. Use LIBS for: $xc_word" >&6;} + ;; + esac + done + fi + + if test $xc_bad_var_libs = yes || + test $xc_bad_var_cflags = yes || + test $xc_bad_var_ldflags = yes || + test $xc_bad_var_cppflags = yes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: Continuing even with errors mentioned immediately above this line." >&5 +printf "%s\n" "$as_me: WARNING: Continuing even with errors mentioned immediately above this line." >&2;} + fi + + +SSL_BACKENDS=${ssl_backends} + + +if test "x$want_curldebug_assumed" = "xyes" && + test "x$want_curldebug" = "xyes" && test "x$USE_ARES" = "x1"; then + ac_configure_args="$ac_configure_args --enable-curldebug" +fi + +ac_config_files="$ac_config_files Makefile docs/Makefile docs/examples/Makefile docs/libcurl/Makefile docs/libcurl/opts/Makefile docs/cmdline-opts/Makefile include/Makefile include/curl/Makefile src/Makefile lib/Makefile scripts/Makefile lib/libcurl.vers tests/Makefile tests/config tests/certs/Makefile tests/certs/scripts/Makefile tests/data/Makefile tests/server/Makefile tests/libtest/Makefile tests/unit/Makefile tests/http/config.ini tests/http/Makefile tests/http/clients/Makefile packages/Makefile packages/vms/Makefile curl-config libcurl.pc" + +cat >confcache <<\_ACEOF +# This file is a shell script that caches the results of configure +# tests run on this system so they can be shared between configure +# scripts and configure runs, see configure's option --config-cache. +# It is not useful on other systems. If it contains results you don't +# want to keep, you may remove or edit it. +# +# config.status only pays attention to the cache file if you give it +# the --recheck option to rerun configure. +# +# `ac_cv_env_foo' variables (set or unset) will be overridden when +# loading this file, other *unset* `ac_cv_foo' will be assigned the +# following values. + +_ACEOF + +# The following way of writing the cache mishandles newlines in values, +# but we know of no workaround that is simple, portable, and efficient. +# So, we kill variables containing newlines. +# Ultrix sh set writes to stderr and can't be redirected directly, +# and sets the high bit in the cache file unless we assign to the vars. +( + for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +printf "%s\n" "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + + (set) 2>&1 | + case $as_nl`(ac_space=' '; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + # `set' does not quote correctly, so add quotes: double-quote + # substitution turns \\\\ into \\, and sed turns \\ into \. + sed -n \ + "s/'/'\\\\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" + ;; #( + *) + # `set' quotes correctly as required by POSIX, so do not add quotes. + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) | + sed ' + /^ac_cv_env_/b end + t clear + :clear + s/^\([^=]*\)=\(.*[{}].*\)$/test ${\1+y} || &/ + t end + s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ + :end' >>confcache +if diff "$cache_file" confcache >/dev/null 2>&1; then :; else + if test -w "$cache_file"; then + if test "x$cache_file" != "x/dev/null"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 +printf "%s\n" "$as_me: updating cache $cache_file" >&6;} + if test ! -f "$cache_file" || test -h "$cache_file"; then + cat confcache >"$cache_file" + else + case $cache_file in #( + */* | ?:*) + mv -f confcache "$cache_file"$$ && + mv -f "$cache_file"$$ "$cache_file" ;; #( + *) + mv -f confcache "$cache_file" ;; + esac + fi + fi + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 +printf "%s\n" "$as_me: not updating unwritable cache $cache_file" >&6;} + fi +fi +rm -f confcache + +test "x$prefix" = xNONE && prefix=$ac_default_prefix +# Let make expand exec_prefix. +test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' + +DEFS=-DHAVE_CONFIG_H + +ac_libobjs= +ac_ltlibobjs= +U= +for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue + # 1. Remove the extension, and $U if already installed. + ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' + ac_i=`printf "%s\n" "$ac_i" | sed "$ac_script"` + # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR + # will be set to the directory where LIBOBJS objects are built. + as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" + as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' +done +LIBOBJS=$ac_libobjs + +LTLIBOBJS=$ac_ltlibobjs + + +if test -z "${MAINTAINER_MODE_TRUE}" && test -z "${MAINTAINER_MODE_FALSE}"; then + as_fn_error $? "conditional \"MAINTAINER_MODE\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking that generated files are newer than configure" >&5 +printf %s "checking that generated files are newer than configure... " >&6; } + if test -n "$am_sleep_pid"; then + # Hide warnings about reused PIDs. + wait $am_sleep_pid 2>/dev/null + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: done" >&5 +printf "%s\n" "done" >&6; } +if test -z "${AMDEP_TRUE}" && test -z "${AMDEP_FALSE}"; then + as_fn_error $? "conditional \"AMDEP\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then + as_fn_error $? "conditional \"am__fastdepCC\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi + if test -n "$EXEEXT"; then + am__EXEEXT_TRUE= + am__EXEEXT_FALSE='#' +else + am__EXEEXT_TRUE='#' + am__EXEEXT_FALSE= +fi + +if test -z "${CURL_LT_SHLIB_USE_VERSION_INFO_TRUE}" && test -z "${CURL_LT_SHLIB_USE_VERSION_INFO_FALSE}"; then + as_fn_error $? "conditional \"CURL_LT_SHLIB_USE_VERSION_INFO\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${CURL_LT_SHLIB_USE_NO_UNDEFINED_TRUE}" && test -z "${CURL_LT_SHLIB_USE_NO_UNDEFINED_FALSE}"; then + as_fn_error $? "conditional \"CURL_LT_SHLIB_USE_NO_UNDEFINED\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${CURL_LT_SHLIB_USE_MIMPURE_TEXT_TRUE}" && test -z "${CURL_LT_SHLIB_USE_MIMPURE_TEXT_FALSE}"; then + as_fn_error $? "conditional \"CURL_LT_SHLIB_USE_MIMPURE_TEXT\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${USE_CPPFLAG_CURL_STATICLIB_TRUE}" && test -z "${USE_CPPFLAG_CURL_STATICLIB_FALSE}"; then + as_fn_error $? "conditional \"USE_CPPFLAG_CURL_STATICLIB\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${USE_EXPLICIT_LIB_DEPS_TRUE}" && test -z "${USE_EXPLICIT_LIB_DEPS_FALSE}"; then + as_fn_error $? "conditional \"USE_EXPLICIT_LIB_DEPS\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${DOING_NATIVE_WINDOWS_TRUE}" && test -z "${DOING_NATIVE_WINDOWS_FALSE}"; then + as_fn_error $? "conditional \"DOING_NATIVE_WINDOWS\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${CURLDEBUG_TRUE}" && test -z "${CURLDEBUG_FALSE}"; then + as_fn_error $? "conditional \"CURLDEBUG\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${BUILD_UNITTESTS_TRUE}" && test -z "${BUILD_UNITTESTS_FALSE}"; then + as_fn_error $? "conditional \"BUILD_UNITTESTS\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${HAVE_WINDRES_TRUE}" && test -z "${HAVE_WINDRES_FALSE}"; then + as_fn_error $? "conditional \"HAVE_WINDRES\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${DOING_NATIVE_WINDOWS_TRUE}" && test -z "${DOING_NATIVE_WINDOWS_FALSE}"; then + as_fn_error $? "conditional \"DOING_NATIVE_WINDOWS\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${HAVE_LIBZ_TRUE}" && test -z "${HAVE_LIBZ_FALSE}"; then + as_fn_error $? "conditional \"HAVE_LIBZ\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${BUILD_STUB_GSS_TRUE}" && test -z "${BUILD_STUB_GSS_FALSE}"; then + as_fn_error $? "conditional \"BUILD_STUB_GSS\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${USE_LIBPSL_TRUE}" && test -z "${USE_LIBPSL_FALSE}"; then + as_fn_error $? "conditional \"USE_LIBPSL\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${USE_GSASL_TRUE}" && test -z "${USE_GSASL_FALSE}"; then + as_fn_error $? "conditional \"USE_GSASL\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${CURL_LT_SHLIB_USE_VERSIONED_SYMBOLS_TRUE}" && test -z "${CURL_LT_SHLIB_USE_VERSIONED_SYMBOLS_FALSE}"; then + as_fn_error $? "conditional \"CURL_LT_SHLIB_USE_VERSIONED_SYMBOLS\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${USE_ZSH_COMPLETION_TRUE}" && test -z "${USE_ZSH_COMPLETION_FALSE}"; then + as_fn_error $? "conditional \"USE_ZSH_COMPLETION\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${USE_FISH_COMPLETION_TRUE}" && test -z "${USE_FISH_COMPLETION_FALSE}"; then + as_fn_error $? "conditional \"USE_FISH_COMPLETION\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${DOING_NATIVE_WINDOWS_TRUE}" && test -z "${DOING_NATIVE_WINDOWS_FALSE}"; then + as_fn_error $? "conditional \"DOING_NATIVE_WINDOWS\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${BUILD_DOCS_TRUE}" && test -z "${BUILD_DOCS_FALSE}"; then + as_fn_error $? "conditional \"BUILD_DOCS\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${USE_MANUAL_TRUE}" && test -z "${USE_MANUAL_FALSE}"; then + as_fn_error $? "conditional \"USE_MANUAL\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${BUILD_LIBHOSTNAME_TRUE}" && test -z "${BUILD_LIBHOSTNAME_FALSE}"; then + as_fn_error $? "conditional \"BUILD_LIBHOSTNAME\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${DOING_CURL_SYMBOL_HIDING_TRUE}" && test -z "${DOING_CURL_SYMBOL_HIDING_FALSE}"; then + as_fn_error $? "conditional \"DOING_CURL_SYMBOL_HIDING\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${CROSSCOMPILING_TRUE}" && test -z "${CROSSCOMPILING_FALSE}"; then + as_fn_error $? "conditional \"CROSSCOMPILING\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi + +: "${CONFIG_STATUS=./config.status}" +ac_write_fail=0 +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files $CONFIG_STATUS" +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 +printf "%s\n" "$as_me: creating $CONFIG_STATUS" >&6;} +as_write_fail=0 +cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 +#! $SHELL +# Generated by $as_me. +# Run this file to recreate the current configuration. +# Compiler output produced by configure, useful for debugging +# configure, is in config.log if it exists. + +debug=false +ac_cs_recheck=false +ac_cs_silent=false + +SHELL=\${CONFIG_SHELL-$SHELL} +export SHELL +_ASEOF +cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +as_nop=: +if test ${ZSH_VERSION+y} && (emulate sh) >/dev/null 2>&1 +then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else $as_nop + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + + +# Reset variables that may have inherited troublesome values from +# the environment. + +# IFS needs to be set, to space, tab, and newline, in precisely that order. +# (If _AS_PATH_WALK were called with IFS unset, it would have the +# side effect of setting IFS to empty, thus disabling word splitting.) +# Quoting is to prevent editors from complaining about space-tab. +as_nl=' +' +export as_nl +IFS=" "" $as_nl" + +PS1='$ ' +PS2='> ' +PS4='+ ' + +# Ensure predictable behavior from utilities with locale-dependent output. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# We cannot yet rely on "unset" to work, but we need these variables +# to be unset--not just set to an empty or harmless value--now, to +# avoid bugs in old shells (e.g. pre-3.0 UWIN ksh). This construct +# also avoids known problems related to "unset" and subshell syntax +# in other old shells (e.g. bash 2.01 and pdksh 5.2.14). +for as_var in BASH_ENV ENV MAIL MAILPATH CDPATH +do eval test \${$as_var+y} \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done + +# Ensure that fds 0, 1, and 2 are open. +if (exec 3>&0) 2>/dev/null; then :; else exec 0&1) 2>/dev/null; then :; else exec 1>/dev/null; fi +if (exec 3>&2) ; then :; else exec 2>/dev/null; fi + + + +# Find who we are. Look in the path if we contain no directory separator. +as_myself= +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + test -r "$as_dir$0" && as_myself=$as_dir$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + printf "%s\n" "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + + + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + printf "%s\n" "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + + + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset + +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null +then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else $as_nop + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null +then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else $as_nop + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +printf "%s\n" X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + + +# Determine whether it's possible to make 'echo' print without a newline. +# These variables are no longer used directly by Autoconf, but are AC_SUBSTed +# for compatibility with existing Makefiles. +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +# For backward compatibility with old third-party macros, we provide +# the shell variables $as_echo and $as_echo_n. New code should use +# AS_ECHO(["message"]) and AS_ECHO_N(["message"]), respectively. +as_echo='printf %s\n' +as_echo_n='printf %s' + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -pR'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -pR' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -pR' + fi +else + as_ln_s='cp -pR' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`printf "%s\n" "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +printf "%s\n" X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + + +# as_fn_executable_p FILE +# ----------------------- +# Test if FILE is an executable regular file. +as_fn_executable_p () +{ + test -f "$1" && test -x "$1" +} # as_fn_executable_p +as_test_x='test -x' +as_executable_p=as_fn_executable_p + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +exec 6>&1 +## ----------------------------------- ## +## Main body of $CONFIG_STATUS script. ## +## ----------------------------------- ## +_ASEOF +test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# Save the log message, to keep $0 and so on meaningful, and to +# report actual input values of CONFIG_FILES etc. instead of their +# values after options handling. +ac_log=" +This file was extended by curl $as_me -, which was +generated by GNU Autoconf 2.71. Invocation command line was + + CONFIG_FILES = $CONFIG_FILES + CONFIG_HEADERS = $CONFIG_HEADERS + CONFIG_LINKS = $CONFIG_LINKS + CONFIG_COMMANDS = $CONFIG_COMMANDS + $ $0 $@ + +on `(hostname || uname -n) 2>/dev/null | sed 1q` +" + +_ACEOF + +case $ac_config_files in *" +"*) set x $ac_config_files; shift; ac_config_files=$*;; +esac + +case $ac_config_headers in *" +"*) set x $ac_config_headers; shift; ac_config_headers=$*;; +esac + + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +# Files that config.status was made for. +config_files="$ac_config_files" +config_headers="$ac_config_headers" +config_commands="$ac_config_commands" + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +ac_cs_usage="\ +\`$as_me' instantiates files and other configuration actions +from templates according to the current configuration. Unless the files +and actions are specified as TAGs, all are instantiated by default. + +Usage: $0 [OPTION]... [TAG]... + + -h, --help print this help, then exit + -V, --version print version number and configuration settings, then exit + --config print configuration, then exit + -q, --quiet, --silent + do not print progress messages + -d, --debug don't remove temporary files + --recheck update $as_me by reconfiguring in the same conditions + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + --header=FILE[:TEMPLATE] + instantiate the configuration header FILE + +Configuration files: +$config_files + +Configuration headers: +$config_headers + +Configuration commands: +$config_commands + +Report bugs to ." + +_ACEOF +ac_cs_config=`printf "%s\n" "$ac_configure_args" | sed "$ac_safe_unquote"` +ac_cs_config_escaped=`printf "%s\n" "$ac_cs_config" | sed "s/^ //; s/'/'\\\\\\\\''/g"` +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_cs_config='$ac_cs_config_escaped' +ac_cs_version="\\ +curl config.status - +configured by $0, generated by GNU Autoconf 2.71, + with options \\"\$ac_cs_config\\" + +Copyright (C) 2021 Free Software Foundation, Inc. +This config.status script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it." + +ac_pwd='$ac_pwd' +srcdir='$srcdir' +INSTALL='$INSTALL' +MKDIR_P='$MKDIR_P' +AWK='$AWK' +test -n "\$AWK" || AWK=awk +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# The default lists apply if the user does not specify any file. +ac_need_defaults=: +while test $# != 0 +do + case $1 in + --*=?*) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` + ac_shift=: + ;; + --*=) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg= + ac_shift=: + ;; + *) + ac_option=$1 + ac_optarg=$2 + ac_shift=shift + ;; + esac + + case $ac_option in + # Handling of the options. + -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) + ac_cs_recheck=: ;; + --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) + printf "%s\n" "$ac_cs_version"; exit ;; + --config | --confi | --conf | --con | --co | --c ) + printf "%s\n" "$ac_cs_config"; exit ;; + --debug | --debu | --deb | --de | --d | -d ) + debug=: ;; + --file | --fil | --fi | --f ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`printf "%s\n" "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + '') as_fn_error $? "missing file argument" ;; + esac + as_fn_append CONFIG_FILES " '$ac_optarg'" + ac_need_defaults=false;; + --header | --heade | --head | --hea ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`printf "%s\n" "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + as_fn_append CONFIG_HEADERS " '$ac_optarg'" + ac_need_defaults=false;; + --he | --h) + # Conflict between --help and --header + as_fn_error $? "ambiguous option: \`$1' +Try \`$0 --help' for more information.";; + --help | --hel | -h ) + printf "%s\n" "$ac_cs_usage"; exit ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil | --si | --s) + ac_cs_silent=: ;; + + # This is an error. + -*) as_fn_error $? "unrecognized option: \`$1' +Try \`$0 --help' for more information." ;; + + *) as_fn_append ac_config_targets " $1" + ac_need_defaults=false ;; + + esac + shift +done + +ac_configure_extra_args= + +if $ac_cs_silent; then + exec 6>/dev/null + ac_configure_extra_args="$ac_configure_extra_args --silent" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +if \$ac_cs_recheck; then + set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + shift + \printf "%s\n" "running CONFIG_SHELL=$SHELL \$*" >&6 + CONFIG_SHELL='$SHELL' + export CONFIG_SHELL + exec "\$@" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +exec 5>>config.log +{ + echo + sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX +## Running $as_me. ## +_ASBOX + printf "%s\n" "$ac_log" +} >&5 + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +# +# INIT-COMMANDS +# +AMDEP_TRUE="$AMDEP_TRUE" MAKE="${MAKE-make}" + + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +sed_quote_subst='$sed_quote_subst' +double_quote_subst='$double_quote_subst' +delay_variable_subst='$delay_variable_subst' +macro_version='`$ECHO "$macro_version" | $SED "$delay_single_quote_subst"`' +macro_revision='`$ECHO "$macro_revision" | $SED "$delay_single_quote_subst"`' +AS='`$ECHO "$AS" | $SED "$delay_single_quote_subst"`' +DLLTOOL='`$ECHO "$DLLTOOL" | $SED "$delay_single_quote_subst"`' +OBJDUMP='`$ECHO "$OBJDUMP" | $SED "$delay_single_quote_subst"`' +enable_shared='`$ECHO "$enable_shared" | $SED "$delay_single_quote_subst"`' +enable_static='`$ECHO "$enable_static" | $SED "$delay_single_quote_subst"`' +pic_mode='`$ECHO "$pic_mode" | $SED "$delay_single_quote_subst"`' +enable_fast_install='`$ECHO "$enable_fast_install" | $SED "$delay_single_quote_subst"`' +shared_archive_member_spec='`$ECHO "$shared_archive_member_spec" | $SED "$delay_single_quote_subst"`' +SHELL='`$ECHO "$SHELL" | $SED "$delay_single_quote_subst"`' +ECHO='`$ECHO "$ECHO" | $SED "$delay_single_quote_subst"`' +PATH_SEPARATOR='`$ECHO "$PATH_SEPARATOR" | $SED "$delay_single_quote_subst"`' +host_alias='`$ECHO "$host_alias" | $SED "$delay_single_quote_subst"`' +host='`$ECHO "$host" | $SED "$delay_single_quote_subst"`' +host_os='`$ECHO "$host_os" | $SED "$delay_single_quote_subst"`' +build_alias='`$ECHO "$build_alias" | $SED "$delay_single_quote_subst"`' +build='`$ECHO "$build" | $SED "$delay_single_quote_subst"`' +build_os='`$ECHO "$build_os" | $SED "$delay_single_quote_subst"`' +SED='`$ECHO "$SED" | $SED "$delay_single_quote_subst"`' +Xsed='`$ECHO "$Xsed" | $SED "$delay_single_quote_subst"`' +GREP='`$ECHO "$GREP" | $SED "$delay_single_quote_subst"`' +EGREP='`$ECHO "$EGREP" | $SED "$delay_single_quote_subst"`' +FGREP='`$ECHO "$FGREP" | $SED "$delay_single_quote_subst"`' +LD='`$ECHO "$LD" | $SED "$delay_single_quote_subst"`' +NM='`$ECHO "$NM" | $SED "$delay_single_quote_subst"`' +LN_S='`$ECHO "$LN_S" | $SED "$delay_single_quote_subst"`' +max_cmd_len='`$ECHO "$max_cmd_len" | $SED "$delay_single_quote_subst"`' +ac_objext='`$ECHO "$ac_objext" | $SED "$delay_single_quote_subst"`' +exeext='`$ECHO "$exeext" | $SED "$delay_single_quote_subst"`' +lt_unset='`$ECHO "$lt_unset" | $SED "$delay_single_quote_subst"`' +lt_SP2NL='`$ECHO "$lt_SP2NL" | $SED "$delay_single_quote_subst"`' +lt_NL2SP='`$ECHO "$lt_NL2SP" | $SED "$delay_single_quote_subst"`' +lt_cv_to_host_file_cmd='`$ECHO "$lt_cv_to_host_file_cmd" | $SED "$delay_single_quote_subst"`' +lt_cv_to_tool_file_cmd='`$ECHO "$lt_cv_to_tool_file_cmd" | $SED "$delay_single_quote_subst"`' +reload_flag='`$ECHO "$reload_flag" | $SED "$delay_single_quote_subst"`' +reload_cmds='`$ECHO "$reload_cmds" | $SED "$delay_single_quote_subst"`' +FILECMD='`$ECHO "$FILECMD" | $SED "$delay_single_quote_subst"`' +deplibs_check_method='`$ECHO "$deplibs_check_method" | $SED "$delay_single_quote_subst"`' +file_magic_cmd='`$ECHO "$file_magic_cmd" | $SED "$delay_single_quote_subst"`' +file_magic_glob='`$ECHO "$file_magic_glob" | $SED "$delay_single_quote_subst"`' +want_nocaseglob='`$ECHO "$want_nocaseglob" | $SED "$delay_single_quote_subst"`' +sharedlib_from_linklib_cmd='`$ECHO "$sharedlib_from_linklib_cmd" | $SED "$delay_single_quote_subst"`' +AR='`$ECHO "$AR" | $SED "$delay_single_quote_subst"`' +lt_ar_flags='`$ECHO "$lt_ar_flags" | $SED "$delay_single_quote_subst"`' +AR_FLAGS='`$ECHO "$AR_FLAGS" | $SED "$delay_single_quote_subst"`' +archiver_list_spec='`$ECHO "$archiver_list_spec" | $SED "$delay_single_quote_subst"`' +STRIP='`$ECHO "$STRIP" | $SED "$delay_single_quote_subst"`' +RANLIB='`$ECHO "$RANLIB" | $SED "$delay_single_quote_subst"`' +old_postinstall_cmds='`$ECHO "$old_postinstall_cmds" | $SED "$delay_single_quote_subst"`' +old_postuninstall_cmds='`$ECHO "$old_postuninstall_cmds" | $SED "$delay_single_quote_subst"`' +old_archive_cmds='`$ECHO "$old_archive_cmds" | $SED "$delay_single_quote_subst"`' +lock_old_archive_extraction='`$ECHO "$lock_old_archive_extraction" | $SED "$delay_single_quote_subst"`' +CC='`$ECHO "$CC" | $SED "$delay_single_quote_subst"`' +CFLAGS='`$ECHO "$CFLAGS" | $SED "$delay_single_quote_subst"`' +compiler='`$ECHO "$compiler" | $SED "$delay_single_quote_subst"`' +GCC='`$ECHO "$GCC" | $SED "$delay_single_quote_subst"`' +lt_cv_sys_global_symbol_pipe='`$ECHO "$lt_cv_sys_global_symbol_pipe" | $SED "$delay_single_quote_subst"`' +lt_cv_sys_global_symbol_to_cdecl='`$ECHO "$lt_cv_sys_global_symbol_to_cdecl" | $SED "$delay_single_quote_subst"`' +lt_cv_sys_global_symbol_to_import='`$ECHO "$lt_cv_sys_global_symbol_to_import" | $SED "$delay_single_quote_subst"`' +lt_cv_sys_global_symbol_to_c_name_address='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address" | $SED "$delay_single_quote_subst"`' +lt_cv_sys_global_symbol_to_c_name_address_lib_prefix='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address_lib_prefix" | $SED "$delay_single_quote_subst"`' +lt_cv_nm_interface='`$ECHO "$lt_cv_nm_interface" | $SED "$delay_single_quote_subst"`' +nm_file_list_spec='`$ECHO "$nm_file_list_spec" | $SED "$delay_single_quote_subst"`' +lt_sysroot='`$ECHO "$lt_sysroot" | $SED "$delay_single_quote_subst"`' +lt_cv_truncate_bin='`$ECHO "$lt_cv_truncate_bin" | $SED "$delay_single_quote_subst"`' +objdir='`$ECHO "$objdir" | $SED "$delay_single_quote_subst"`' +MAGIC_CMD='`$ECHO "$MAGIC_CMD" | $SED "$delay_single_quote_subst"`' +lt_prog_compiler_no_builtin_flag='`$ECHO "$lt_prog_compiler_no_builtin_flag" | $SED "$delay_single_quote_subst"`' +lt_prog_compiler_pic='`$ECHO "$lt_prog_compiler_pic" | $SED "$delay_single_quote_subst"`' +lt_prog_compiler_wl='`$ECHO "$lt_prog_compiler_wl" | $SED "$delay_single_quote_subst"`' +lt_prog_compiler_static='`$ECHO "$lt_prog_compiler_static" | $SED "$delay_single_quote_subst"`' +lt_cv_prog_compiler_c_o='`$ECHO "$lt_cv_prog_compiler_c_o" | $SED "$delay_single_quote_subst"`' +need_locks='`$ECHO "$need_locks" | $SED "$delay_single_quote_subst"`' +MANIFEST_TOOL='`$ECHO "$MANIFEST_TOOL" | $SED "$delay_single_quote_subst"`' +DSYMUTIL='`$ECHO "$DSYMUTIL" | $SED "$delay_single_quote_subst"`' +NMEDIT='`$ECHO "$NMEDIT" | $SED "$delay_single_quote_subst"`' +LIPO='`$ECHO "$LIPO" | $SED "$delay_single_quote_subst"`' +OTOOL='`$ECHO "$OTOOL" | $SED "$delay_single_quote_subst"`' +OTOOL64='`$ECHO "$OTOOL64" | $SED "$delay_single_quote_subst"`' +libext='`$ECHO "$libext" | $SED "$delay_single_quote_subst"`' +shrext_cmds='`$ECHO "$shrext_cmds" | $SED "$delay_single_quote_subst"`' +extract_expsyms_cmds='`$ECHO "$extract_expsyms_cmds" | $SED "$delay_single_quote_subst"`' +archive_cmds_need_lc='`$ECHO "$archive_cmds_need_lc" | $SED "$delay_single_quote_subst"`' +enable_shared_with_static_runtimes='`$ECHO "$enable_shared_with_static_runtimes" | $SED "$delay_single_quote_subst"`' +export_dynamic_flag_spec='`$ECHO "$export_dynamic_flag_spec" | $SED "$delay_single_quote_subst"`' +whole_archive_flag_spec='`$ECHO "$whole_archive_flag_spec" | $SED "$delay_single_quote_subst"`' +compiler_needs_object='`$ECHO "$compiler_needs_object" | $SED "$delay_single_quote_subst"`' +old_archive_from_new_cmds='`$ECHO "$old_archive_from_new_cmds" | $SED "$delay_single_quote_subst"`' +old_archive_from_expsyms_cmds='`$ECHO "$old_archive_from_expsyms_cmds" | $SED "$delay_single_quote_subst"`' +archive_cmds='`$ECHO "$archive_cmds" | $SED "$delay_single_quote_subst"`' +archive_expsym_cmds='`$ECHO "$archive_expsym_cmds" | $SED "$delay_single_quote_subst"`' +module_cmds='`$ECHO "$module_cmds" | $SED "$delay_single_quote_subst"`' +module_expsym_cmds='`$ECHO "$module_expsym_cmds" | $SED "$delay_single_quote_subst"`' +with_gnu_ld='`$ECHO "$with_gnu_ld" | $SED "$delay_single_quote_subst"`' +allow_undefined_flag='`$ECHO "$allow_undefined_flag" | $SED "$delay_single_quote_subst"`' +no_undefined_flag='`$ECHO "$no_undefined_flag" | $SED "$delay_single_quote_subst"`' +hardcode_libdir_flag_spec='`$ECHO "$hardcode_libdir_flag_spec" | $SED "$delay_single_quote_subst"`' +hardcode_libdir_separator='`$ECHO "$hardcode_libdir_separator" | $SED "$delay_single_quote_subst"`' +hardcode_direct='`$ECHO "$hardcode_direct" | $SED "$delay_single_quote_subst"`' +hardcode_direct_absolute='`$ECHO "$hardcode_direct_absolute" | $SED "$delay_single_quote_subst"`' +hardcode_minus_L='`$ECHO "$hardcode_minus_L" | $SED "$delay_single_quote_subst"`' +hardcode_shlibpath_var='`$ECHO "$hardcode_shlibpath_var" | $SED "$delay_single_quote_subst"`' +hardcode_automatic='`$ECHO "$hardcode_automatic" | $SED "$delay_single_quote_subst"`' +inherit_rpath='`$ECHO "$inherit_rpath" | $SED "$delay_single_quote_subst"`' +link_all_deplibs='`$ECHO "$link_all_deplibs" | $SED "$delay_single_quote_subst"`' +always_export_symbols='`$ECHO "$always_export_symbols" | $SED "$delay_single_quote_subst"`' +export_symbols_cmds='`$ECHO "$export_symbols_cmds" | $SED "$delay_single_quote_subst"`' +exclude_expsyms='`$ECHO "$exclude_expsyms" | $SED "$delay_single_quote_subst"`' +include_expsyms='`$ECHO "$include_expsyms" | $SED "$delay_single_quote_subst"`' +prelink_cmds='`$ECHO "$prelink_cmds" | $SED "$delay_single_quote_subst"`' +postlink_cmds='`$ECHO "$postlink_cmds" | $SED "$delay_single_quote_subst"`' +file_list_spec='`$ECHO "$file_list_spec" | $SED "$delay_single_quote_subst"`' +variables_saved_for_relink='`$ECHO "$variables_saved_for_relink" | $SED "$delay_single_quote_subst"`' +need_lib_prefix='`$ECHO "$need_lib_prefix" | $SED "$delay_single_quote_subst"`' +need_version='`$ECHO "$need_version" | $SED "$delay_single_quote_subst"`' +version_type='`$ECHO "$version_type" | $SED "$delay_single_quote_subst"`' +runpath_var='`$ECHO "$runpath_var" | $SED "$delay_single_quote_subst"`' +shlibpath_var='`$ECHO "$shlibpath_var" | $SED "$delay_single_quote_subst"`' +shlibpath_overrides_runpath='`$ECHO "$shlibpath_overrides_runpath" | $SED "$delay_single_quote_subst"`' +libname_spec='`$ECHO "$libname_spec" | $SED "$delay_single_quote_subst"`' +library_names_spec='`$ECHO "$library_names_spec" | $SED "$delay_single_quote_subst"`' +soname_spec='`$ECHO "$soname_spec" | $SED "$delay_single_quote_subst"`' +install_override_mode='`$ECHO "$install_override_mode" | $SED "$delay_single_quote_subst"`' +postinstall_cmds='`$ECHO "$postinstall_cmds" | $SED "$delay_single_quote_subst"`' +postuninstall_cmds='`$ECHO "$postuninstall_cmds" | $SED "$delay_single_quote_subst"`' +finish_cmds='`$ECHO "$finish_cmds" | $SED "$delay_single_quote_subst"`' +finish_eval='`$ECHO "$finish_eval" | $SED "$delay_single_quote_subst"`' +hardcode_into_libs='`$ECHO "$hardcode_into_libs" | $SED "$delay_single_quote_subst"`' +sys_lib_search_path_spec='`$ECHO "$sys_lib_search_path_spec" | $SED "$delay_single_quote_subst"`' +configure_time_dlsearch_path='`$ECHO "$configure_time_dlsearch_path" | $SED "$delay_single_quote_subst"`' +configure_time_lt_sys_library_path='`$ECHO "$configure_time_lt_sys_library_path" | $SED "$delay_single_quote_subst"`' +hardcode_action='`$ECHO "$hardcode_action" | $SED "$delay_single_quote_subst"`' +enable_dlopen='`$ECHO "$enable_dlopen" | $SED "$delay_single_quote_subst"`' +enable_dlopen_self='`$ECHO "$enable_dlopen_self" | $SED "$delay_single_quote_subst"`' +enable_dlopen_self_static='`$ECHO "$enable_dlopen_self_static" | $SED "$delay_single_quote_subst"`' +old_striplib='`$ECHO "$old_striplib" | $SED "$delay_single_quote_subst"`' +striplib='`$ECHO "$striplib" | $SED "$delay_single_quote_subst"`' +LD_RC='`$ECHO "$LD_RC" | $SED "$delay_single_quote_subst"`' +reload_flag_RC='`$ECHO "$reload_flag_RC" | $SED "$delay_single_quote_subst"`' +reload_cmds_RC='`$ECHO "$reload_cmds_RC" | $SED "$delay_single_quote_subst"`' +old_archive_cmds_RC='`$ECHO "$old_archive_cmds_RC" | $SED "$delay_single_quote_subst"`' +compiler_RC='`$ECHO "$compiler_RC" | $SED "$delay_single_quote_subst"`' +GCC_RC='`$ECHO "$GCC_RC" | $SED "$delay_single_quote_subst"`' +lt_prog_compiler_no_builtin_flag_RC='`$ECHO "$lt_prog_compiler_no_builtin_flag_RC" | $SED "$delay_single_quote_subst"`' +lt_prog_compiler_pic_RC='`$ECHO "$lt_prog_compiler_pic_RC" | $SED "$delay_single_quote_subst"`' +lt_prog_compiler_wl_RC='`$ECHO "$lt_prog_compiler_wl_RC" | $SED "$delay_single_quote_subst"`' +lt_prog_compiler_static_RC='`$ECHO "$lt_prog_compiler_static_RC" | $SED "$delay_single_quote_subst"`' +lt_cv_prog_compiler_c_o_RC='`$ECHO "$lt_cv_prog_compiler_c_o_RC" | $SED "$delay_single_quote_subst"`' +archive_cmds_need_lc_RC='`$ECHO "$archive_cmds_need_lc_RC" | $SED "$delay_single_quote_subst"`' +enable_shared_with_static_runtimes_RC='`$ECHO "$enable_shared_with_static_runtimes_RC" | $SED "$delay_single_quote_subst"`' +export_dynamic_flag_spec_RC='`$ECHO "$export_dynamic_flag_spec_RC" | $SED "$delay_single_quote_subst"`' +whole_archive_flag_spec_RC='`$ECHO "$whole_archive_flag_spec_RC" | $SED "$delay_single_quote_subst"`' +compiler_needs_object_RC='`$ECHO "$compiler_needs_object_RC" | $SED "$delay_single_quote_subst"`' +old_archive_from_new_cmds_RC='`$ECHO "$old_archive_from_new_cmds_RC" | $SED "$delay_single_quote_subst"`' +old_archive_from_expsyms_cmds_RC='`$ECHO "$old_archive_from_expsyms_cmds_RC" | $SED "$delay_single_quote_subst"`' +archive_cmds_RC='`$ECHO "$archive_cmds_RC" | $SED "$delay_single_quote_subst"`' +archive_expsym_cmds_RC='`$ECHO "$archive_expsym_cmds_RC" | $SED "$delay_single_quote_subst"`' +module_cmds_RC='`$ECHO "$module_cmds_RC" | $SED "$delay_single_quote_subst"`' +module_expsym_cmds_RC='`$ECHO "$module_expsym_cmds_RC" | $SED "$delay_single_quote_subst"`' +with_gnu_ld_RC='`$ECHO "$with_gnu_ld_RC" | $SED "$delay_single_quote_subst"`' +allow_undefined_flag_RC='`$ECHO "$allow_undefined_flag_RC" | $SED "$delay_single_quote_subst"`' +no_undefined_flag_RC='`$ECHO "$no_undefined_flag_RC" | $SED "$delay_single_quote_subst"`' +hardcode_libdir_flag_spec_RC='`$ECHO "$hardcode_libdir_flag_spec_RC" | $SED "$delay_single_quote_subst"`' +hardcode_libdir_separator_RC='`$ECHO "$hardcode_libdir_separator_RC" | $SED "$delay_single_quote_subst"`' +hardcode_direct_RC='`$ECHO "$hardcode_direct_RC" | $SED "$delay_single_quote_subst"`' +hardcode_direct_absolute_RC='`$ECHO "$hardcode_direct_absolute_RC" | $SED "$delay_single_quote_subst"`' +hardcode_minus_L_RC='`$ECHO "$hardcode_minus_L_RC" | $SED "$delay_single_quote_subst"`' +hardcode_shlibpath_var_RC='`$ECHO "$hardcode_shlibpath_var_RC" | $SED "$delay_single_quote_subst"`' +hardcode_automatic_RC='`$ECHO "$hardcode_automatic_RC" | $SED "$delay_single_quote_subst"`' +inherit_rpath_RC='`$ECHO "$inherit_rpath_RC" | $SED "$delay_single_quote_subst"`' +link_all_deplibs_RC='`$ECHO "$link_all_deplibs_RC" | $SED "$delay_single_quote_subst"`' +always_export_symbols_RC='`$ECHO "$always_export_symbols_RC" | $SED "$delay_single_quote_subst"`' +export_symbols_cmds_RC='`$ECHO "$export_symbols_cmds_RC" | $SED "$delay_single_quote_subst"`' +exclude_expsyms_RC='`$ECHO "$exclude_expsyms_RC" | $SED "$delay_single_quote_subst"`' +include_expsyms_RC='`$ECHO "$include_expsyms_RC" | $SED "$delay_single_quote_subst"`' +prelink_cmds_RC='`$ECHO "$prelink_cmds_RC" | $SED "$delay_single_quote_subst"`' +postlink_cmds_RC='`$ECHO "$postlink_cmds_RC" | $SED "$delay_single_quote_subst"`' +file_list_spec_RC='`$ECHO "$file_list_spec_RC" | $SED "$delay_single_quote_subst"`' +hardcode_action_RC='`$ECHO "$hardcode_action_RC" | $SED "$delay_single_quote_subst"`' + +LTCC='$LTCC' +LTCFLAGS='$LTCFLAGS' +compiler='$compiler_DEFAULT' + +# A function that is used when there is no print builtin or printf. +func_fallback_echo () +{ + eval 'cat <<_LTECHO_EOF +\$1 +_LTECHO_EOF' +} + +# Quote evaled strings. +for var in AS \ +DLLTOOL \ +OBJDUMP \ +SHELL \ +ECHO \ +PATH_SEPARATOR \ +SED \ +GREP \ +EGREP \ +FGREP \ +LD \ +NM \ +LN_S \ +lt_SP2NL \ +lt_NL2SP \ +reload_flag \ +FILECMD \ +deplibs_check_method \ +file_magic_cmd \ +file_magic_glob \ +want_nocaseglob \ +sharedlib_from_linklib_cmd \ +AR \ +archiver_list_spec \ +STRIP \ +RANLIB \ +CC \ +CFLAGS \ +compiler \ +lt_cv_sys_global_symbol_pipe \ +lt_cv_sys_global_symbol_to_cdecl \ +lt_cv_sys_global_symbol_to_import \ +lt_cv_sys_global_symbol_to_c_name_address \ +lt_cv_sys_global_symbol_to_c_name_address_lib_prefix \ +lt_cv_nm_interface \ +nm_file_list_spec \ +lt_cv_truncate_bin \ +lt_prog_compiler_no_builtin_flag \ +lt_prog_compiler_pic \ +lt_prog_compiler_wl \ +lt_prog_compiler_static \ +lt_cv_prog_compiler_c_o \ +need_locks \ +MANIFEST_TOOL \ +DSYMUTIL \ +NMEDIT \ +LIPO \ +OTOOL \ +OTOOL64 \ +shrext_cmds \ +export_dynamic_flag_spec \ +whole_archive_flag_spec \ +compiler_needs_object \ +with_gnu_ld \ +allow_undefined_flag \ +no_undefined_flag \ +hardcode_libdir_flag_spec \ +hardcode_libdir_separator \ +exclude_expsyms \ +include_expsyms \ +file_list_spec \ +variables_saved_for_relink \ +libname_spec \ +library_names_spec \ +soname_spec \ +install_override_mode \ +finish_eval \ +old_striplib \ +striplib \ +LD_RC \ +reload_flag_RC \ +compiler_RC \ +lt_prog_compiler_no_builtin_flag_RC \ +lt_prog_compiler_pic_RC \ +lt_prog_compiler_wl_RC \ +lt_prog_compiler_static_RC \ +lt_cv_prog_compiler_c_o_RC \ +export_dynamic_flag_spec_RC \ +whole_archive_flag_spec_RC \ +compiler_needs_object_RC \ +with_gnu_ld_RC \ +allow_undefined_flag_RC \ +no_undefined_flag_RC \ +hardcode_libdir_flag_spec_RC \ +hardcode_libdir_separator_RC \ +exclude_expsyms_RC \ +include_expsyms_RC \ +file_list_spec_RC; do + case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in + *[\\\\\\\`\\"\\\$]*) + eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ## exclude from sc_prohibit_nested_quotes + ;; + *) + eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" + ;; + esac +done + +# Double-quote double-evaled strings. +for var in reload_cmds \ +old_postinstall_cmds \ +old_postuninstall_cmds \ +old_archive_cmds \ +extract_expsyms_cmds \ +old_archive_from_new_cmds \ +old_archive_from_expsyms_cmds \ +archive_cmds \ +archive_expsym_cmds \ +module_cmds \ +module_expsym_cmds \ +export_symbols_cmds \ +prelink_cmds \ +postlink_cmds \ +postinstall_cmds \ +postuninstall_cmds \ +finish_cmds \ +sys_lib_search_path_spec \ +configure_time_dlsearch_path \ +configure_time_lt_sys_library_path \ +reload_cmds_RC \ +old_archive_cmds_RC \ +old_archive_from_new_cmds_RC \ +old_archive_from_expsyms_cmds_RC \ +archive_cmds_RC \ +archive_expsym_cmds_RC \ +module_cmds_RC \ +module_expsym_cmds_RC \ +export_symbols_cmds_RC \ +prelink_cmds_RC \ +postlink_cmds_RC; do + case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in + *[\\\\\\\`\\"\\\$]*) + eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ## exclude from sc_prohibit_nested_quotes + ;; + *) + eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" + ;; + esac +done + +ac_aux_dir='$ac_aux_dir' + +# See if we are running on zsh, and set the options that allow our +# commands through without removal of \ escapes INIT. +if test -n "\${ZSH_VERSION+set}"; then + setopt NO_GLOB_SUBST +fi + + + PACKAGE='$PACKAGE' + VERSION='$VERSION' + RM='$RM' + ofile='$ofile' + + + + + + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + +# Handling of arguments. +for ac_config_target in $ac_config_targets +do + case $ac_config_target in + "lib/curl_config.h") CONFIG_HEADERS="$CONFIG_HEADERS lib/curl_config.h" ;; + "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;; + "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;; + "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; + "docs/Makefile") CONFIG_FILES="$CONFIG_FILES docs/Makefile" ;; + "docs/examples/Makefile") CONFIG_FILES="$CONFIG_FILES docs/examples/Makefile" ;; + "docs/libcurl/Makefile") CONFIG_FILES="$CONFIG_FILES docs/libcurl/Makefile" ;; + "docs/libcurl/opts/Makefile") CONFIG_FILES="$CONFIG_FILES docs/libcurl/opts/Makefile" ;; + "docs/cmdline-opts/Makefile") CONFIG_FILES="$CONFIG_FILES docs/cmdline-opts/Makefile" ;; + "include/Makefile") CONFIG_FILES="$CONFIG_FILES include/Makefile" ;; + "include/curl/Makefile") CONFIG_FILES="$CONFIG_FILES include/curl/Makefile" ;; + "src/Makefile") CONFIG_FILES="$CONFIG_FILES src/Makefile" ;; + "lib/Makefile") CONFIG_FILES="$CONFIG_FILES lib/Makefile" ;; + "scripts/Makefile") CONFIG_FILES="$CONFIG_FILES scripts/Makefile" ;; + "lib/libcurl.vers") CONFIG_FILES="$CONFIG_FILES lib/libcurl.vers" ;; + "tests/Makefile") CONFIG_FILES="$CONFIG_FILES tests/Makefile" ;; + "tests/config") CONFIG_FILES="$CONFIG_FILES tests/config" ;; + "tests/certs/Makefile") CONFIG_FILES="$CONFIG_FILES tests/certs/Makefile" ;; + "tests/certs/scripts/Makefile") CONFIG_FILES="$CONFIG_FILES tests/certs/scripts/Makefile" ;; + "tests/data/Makefile") CONFIG_FILES="$CONFIG_FILES tests/data/Makefile" ;; + "tests/server/Makefile") CONFIG_FILES="$CONFIG_FILES tests/server/Makefile" ;; + "tests/libtest/Makefile") CONFIG_FILES="$CONFIG_FILES tests/libtest/Makefile" ;; + "tests/unit/Makefile") CONFIG_FILES="$CONFIG_FILES tests/unit/Makefile" ;; + "tests/http/config.ini") CONFIG_FILES="$CONFIG_FILES tests/http/config.ini" ;; + "tests/http/Makefile") CONFIG_FILES="$CONFIG_FILES tests/http/Makefile" ;; + "tests/http/clients/Makefile") CONFIG_FILES="$CONFIG_FILES tests/http/clients/Makefile" ;; + "packages/Makefile") CONFIG_FILES="$CONFIG_FILES packages/Makefile" ;; + "packages/vms/Makefile") CONFIG_FILES="$CONFIG_FILES packages/vms/Makefile" ;; + "curl-config") CONFIG_FILES="$CONFIG_FILES curl-config" ;; + "libcurl.pc") CONFIG_FILES="$CONFIG_FILES libcurl.pc" ;; + + *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; + esac +done + + +# If the user did not use the arguments to specify the items to instantiate, +# then the envvar interface is used. Set only those that are not. +# We use the long form for the default assignment because of an extremely +# bizarre bug on SunOS 4.1.3. +if $ac_need_defaults; then + test ${CONFIG_FILES+y} || CONFIG_FILES=$config_files + test ${CONFIG_HEADERS+y} || CONFIG_HEADERS=$config_headers + test ${CONFIG_COMMANDS+y} || CONFIG_COMMANDS=$config_commands +fi + +# Have a temporary directory for convenience. Make it in the build tree +# simply because there is no reason against having it here, and in addition, +# creating and moving files from /tmp can sometimes cause problems. +# Hook for its removal unless debugging. +# Note that there is a small window in which the directory will not be cleaned: +# after its creation but before its name has been assigned to `$tmp'. +$debug || +{ + tmp= ac_tmp= + trap 'exit_status=$? + : "${ac_tmp:=$tmp}" + { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status +' 0 + trap 'as_fn_exit 1' 1 2 13 15 +} +# Create a (secure) tmp directory for tmp files. + +{ + tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && + test -d "$tmp" +} || +{ + tmp=./conf$$-$RANDOM + (umask 077 && mkdir "$tmp") +} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 +ac_tmp=$tmp + +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. +if test -n "$CONFIG_FILES"; then + + +ac_cr=`echo X | tr X '\015'` +# On cygwin, bash can eat \r inside `` if the user requested igncr. +# But we know of no other shell where ac_cr would be empty at this +# point, so we can use a bashism as a fallback. +if test "x$ac_cr" = x; then + eval ac_cr=\$\'\\r\' +fi +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\\r' +else + ac_cs_awk_cr=$ac_cr +fi + +echo 'BEGIN {' >"$ac_tmp/subs1.awk" && +_ACEOF + + +{ + echo "cat >conf$$subs.awk <<_ACEOF" && + echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && + echo "_ACEOF" +} >conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 +ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` +ac_delim='%!_!# ' +for ac_last_try in false false false false false :; do + . ./conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + + ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` + if test $ac_delim_n = $ac_delim_num; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done +rm -f conf$$subs.sh + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && +_ACEOF +sed -n ' +h +s/^/S["/; s/!.*/"]=/ +p +g +s/^[^!]*!// +:repl +t repl +s/'"$ac_delim"'$// +t delim +:nl +h +s/\(.\{148\}\)..*/\1/ +t more1 +s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ +p +n +b repl +:more1 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t nl +:delim +h +s/\(.\{148\}\)..*/\1/ +t more2 +s/["\\]/\\&/g; s/^/"/; s/$/"/ +p +b +:more2 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t delim +' >$CONFIG_STATUS || ac_write_fail=1 +rm -f conf$$subs.awk +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACAWK +cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + + print line +} + +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ + || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 +_ACEOF + +# VPATH may cause trouble with some makes, so we remove sole $(srcdir), +# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and +# trailing colons and then remove the whole line if VPATH becomes empty +# (actually we leave an empty line to preserve line numbers). +if test "x$srcdir" = x.; then + ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ +h +s/// +s/^/:/ +s/[ ]*$/:/ +s/:\$(srcdir):/:/g +s/:\${srcdir}:/:/g +s/:@srcdir@:/:/g +s/^:*// +s/:*$// +x +s/\(=[ ]*\).*/\1/ +G +s/\n// +s/^[^=]*=[ ]*$// +}' +fi + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +fi # test -n "$CONFIG_FILES" + +# Set up the scripts for CONFIG_HEADERS section. +# No need to generate them if there are no CONFIG_HEADERS. +# This happens for instance with `./config.status Makefile'. +if test -n "$CONFIG_HEADERS"; then +cat >"$ac_tmp/defines.awk" <<\_ACAWK || +BEGIN { +_ACEOF + +# Transform confdefs.h into an awk script `defines.awk', embedded as +# here-document in config.status, that substitutes the proper values into +# config.h.in to produce config.h. + +# Create a delimiter string that does not exist in confdefs.h, to ease +# handling of long lines. +ac_delim='%!_!# ' +for ac_last_try in false false :; do + ac_tt=`sed -n "/$ac_delim/p" confdefs.h` + if test -z "$ac_tt"; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done + +# For the awk script, D is an array of macro values keyed by name, +# likewise P contains macro parameters if any. Preserve backslash +# newline sequences. + +ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* +sed -n ' +s/.\{148\}/&'"$ac_delim"'/g +t rset +:rset +s/^[ ]*#[ ]*define[ ][ ]*/ / +t def +d +:def +s/\\$// +t bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3"/p +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p +d +:bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3\\\\\\n"\\/p +t cont +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p +t cont +d +:cont +n +s/.\{148\}/&'"$ac_delim"'/g +t clear +:clear +s/\\$// +t bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/"/p +d +:bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p +b cont +' >$CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + for (key in D) D_is_set[key] = 1 + FS = "" +} +/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { + line = \$ 0 + split(line, arg, " ") + if (arg[1] == "#") { + defundef = arg[2] + mac1 = arg[3] + } else { + defundef = substr(arg[1], 2) + mac1 = arg[2] + } + split(mac1, mac2, "(") #) + macro = mac2[1] + prefix = substr(line, 1, index(line, defundef) - 1) + if (D_is_set[macro]) { + # Preserve the white space surrounding the "#". + print prefix "define", macro P[macro] D[macro] + next + } else { + # Replace #undef with comments. This is necessary, for example, + # in the case of _POSIX_SOURCE, which is predefined and required + # on some systems where configure will not decide to define it. + if (defundef == "undef") { + print "/*", prefix defundef, macro, "*/" + next + } + } +} +{ print } +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 +fi # test -n "$CONFIG_HEADERS" + + +eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS :C $CONFIG_COMMANDS" +shift +for ac_tag +do + case $ac_tag in + :[FHLC]) ac_mode=$ac_tag; continue;; + esac + case $ac_mode$ac_tag in + :[FHL]*:*);; + :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; + :[FH]-) ac_tag=-:-;; + :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; + esac + ac_save_IFS=$IFS + IFS=: + set x $ac_tag + IFS=$ac_save_IFS + shift + ac_file=$1 + shift + + case $ac_mode in + :L) ac_source=$1;; + :[FH]) + ac_file_inputs= + for ac_f + do + case $ac_f in + -) ac_f="$ac_tmp/stdin";; + *) # Look for the file first in the build tree, then in the source tree + # (if the path is not absolute). The absolute path cannot be DOS-style, + # because $ac_f cannot contain `:'. + test -f "$ac_f" || + case $ac_f in + [\\/$]*) false;; + *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; + esac || + as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; + esac + case $ac_f in *\'*) ac_f=`printf "%s\n" "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + as_fn_append ac_file_inputs " '$ac_f'" + done + + # Let's still pretend it is `configure' which instantiates (i.e., don't + # use $as_me), people would be surprised to read: + # /* config.h. Generated by config.status. */ + configure_input='Generated from '` + printf "%s\n" "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' + if test x"$ac_file" != x-; then + configure_input="$ac_file. $configure_input" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 +printf "%s\n" "$as_me: creating $ac_file" >&6;} + fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`printf "%s\n" "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac + + case $ac_tag in + *:-:* | *:-) cat >"$ac_tmp/stdin" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; + esac + ;; + esac + + ac_dir=`$as_dirname -- "$ac_file" || +$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$ac_file" : 'X\(//\)[^/]' \| \ + X"$ac_file" : 'X\(//\)$' \| \ + X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || +printf "%s\n" X"$ac_file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + as_dir="$ac_dir"; as_fn_mkdir_p + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`printf "%s\n" "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`printf "%s\n" "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + + case $ac_mode in + :F) + # + # CONFIG_FILE + # + + case $INSTALL in + [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; + *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; + esac + ac_MKDIR_P=$MKDIR_P + case $MKDIR_P in + [\\/$]* | ?:[\\/]* ) ;; + */*) ac_MKDIR_P=$ac_top_build_prefix$MKDIR_P ;; + esac +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# If the template does not know about datarootdir, expand it. +# FIXME: This hack should be removed a few years after 2.60. +ac_datarootdir_hack=; ac_datarootdir_seen= +ac_sed_dataroot=' +/datarootdir/ { + p + q +} +/@datadir@/p +/@docdir@/p +/@infodir@/p +/@localedir@/p +/@mandir@/p' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in +*datarootdir*) ac_datarootdir_seen=yes;; +*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +printf "%s\n" "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + ac_datarootdir_hack=' + s&@datadir@&$datadir&g + s&@docdir@&$docdir&g + s&@infodir@&$infodir&g + s&@localedir@&$localedir&g + s&@mandir@&$mandir&g + s&\\\${datarootdir}&$datarootdir&g' ;; +esac +_ACEOF + +# Neutralize VPATH when `$srcdir' = `.'. +# Shell code in configure.ac might set extrasub. +# FIXME: do we really want to maintain this feature? +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_sed_extra="$ac_vpsub +$extrasub +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +:t +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b +s|@configure_input@|$ac_sed_conf_input|;t t +s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t +s&@srcdir@&$ac_srcdir&;t t +s&@abs_srcdir@&$ac_abs_srcdir&;t t +s&@top_srcdir@&$ac_top_srcdir&;t t +s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t +s&@builddir@&$ac_builddir&;t t +s&@abs_builddir@&$ac_abs_builddir&;t t +s&@abs_top_builddir@&$ac_abs_top_builddir&;t t +s&@INSTALL@&$ac_INSTALL&;t t +s&@MKDIR_P@&$ac_MKDIR_P&;t t +$ac_datarootdir_hack +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ + >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + +test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && + { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && + { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ + "$ac_tmp/out"`; test -z "$ac_out"; } && + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&5 +printf "%s\n" "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&2;} + + rm -f "$ac_tmp/stdin" + case $ac_file in + -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; + *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; + esac \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + ;; + :H) + # + # CONFIG_HEADER + # + if test x"$ac_file" != x-; then + { + printf "%s\n" "/* $configure_input */" >&1 \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" + } >"$ac_tmp/config.h" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 +printf "%s\n" "$as_me: $ac_file is unchanged" >&6;} + else + rm -f "$ac_file" + mv "$ac_tmp/config.h" "$ac_file" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + fi + else + printf "%s\n" "/* $configure_input */" >&1 \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ + || as_fn_error $? "could not create -" "$LINENO" 5 + fi +# Compute "$ac_file"'s index in $config_headers. +_am_arg="$ac_file" +_am_stamp_count=1 +for _am_header in $config_headers :; do + case $_am_header in + $_am_arg | $_am_arg:* ) + break ;; + * ) + _am_stamp_count=`expr $_am_stamp_count + 1` ;; + esac +done +echo "timestamp for $_am_arg" >`$as_dirname -- "$_am_arg" || +$as_expr X"$_am_arg" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$_am_arg" : 'X\(//\)[^/]' \| \ + X"$_am_arg" : 'X\(//\)$' \| \ + X"$_am_arg" : 'X\(/\)' \| . 2>/dev/null || +printf "%s\n" X"$_am_arg" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'`/stamp-h$_am_stamp_count + ;; + + :C) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: executing $ac_file commands" >&5 +printf "%s\n" "$as_me: executing $ac_file commands" >&6;} + ;; + esac + + + case $ac_file$ac_mode in + "depfiles":C) test x"$AMDEP_TRUE" != x"" || { + # Older Autoconf quotes --file arguments for eval, but not when files + # are listed without --file. Let's play safe and only enable the eval + # if we detect the quoting. + # TODO: see whether this extra hack can be removed once we start + # requiring Autoconf 2.70 or later. + case $CONFIG_FILES in #( + *\'*) : + eval set x "$CONFIG_FILES" ;; #( + *) : + set x $CONFIG_FILES ;; #( + *) : + ;; +esac + shift + # Used to flag and report bootstrapping failures. + am_rc=0 + for am_mf + do + # Strip MF so we end up with the name of the file. + am_mf=`printf "%s\n" "$am_mf" | sed -e 's/:.*$//'` + # Check whether this is an Automake generated Makefile which includes + # dependency-tracking related rules and includes. + # Grep'ing the whole file directly is not great: AIX grep has a line + # limit of 2048, but all sed's we know have understand at least 4000. + sed -n 's,^am--depfiles:.*,X,p' "$am_mf" | grep X >/dev/null 2>&1 \ + || continue + am_dirpart=`$as_dirname -- "$am_mf" || +$as_expr X"$am_mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$am_mf" : 'X\(//\)[^/]' \| \ + X"$am_mf" : 'X\(//\)$' \| \ + X"$am_mf" : 'X\(/\)' \| . 2>/dev/null || +printf "%s\n" X"$am_mf" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + am_filepart=`$as_basename -- "$am_mf" || +$as_expr X/"$am_mf" : '.*/\([^/][^/]*\)/*$' \| \ + X"$am_mf" : 'X\(//\)$' \| \ + X"$am_mf" : 'X\(/\)' \| . 2>/dev/null || +printf "%s\n" X/"$am_mf" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + { echo "$as_me:$LINENO: cd "$am_dirpart" \ + && sed -e '/# am--include-marker/d' "$am_filepart" \ + | $MAKE -f - am--depfiles" >&5 + (cd "$am_dirpart" \ + && sed -e '/# am--include-marker/d' "$am_filepart" \ + | $MAKE -f - am--depfiles) >&5 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } || am_rc=$? + done + if test $am_rc -ne 0; then + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "Something went wrong bootstrapping makefile fragments + for automatic dependency tracking. If GNU make was not used, consider + re-running the configure script with MAKE=\"gmake\" (or whatever is + necessary). You can also try re-running configure with the + '--disable-dependency-tracking' option to at least be able to build + the package (albeit without support for automatic dependency tracking). +See \`config.log' for more details" "$LINENO" 5; } + fi + { am_dirpart=; unset am_dirpart;} + { am_filepart=; unset am_filepart;} + { am_mf=; unset am_mf;} + { am_rc=; unset am_rc;} + rm -f conftest-deps.mk +} + ;; + "libtool":C) + + # See if we are running on zsh, and set the options that allow our + # commands through without removal of \ escapes. + if test -n "${ZSH_VERSION+set}"; then + setopt NO_GLOB_SUBST + fi + + cfgfile=${ofile}T + trap "$RM \"$cfgfile\"; exit 1" 1 2 15 + $RM "$cfgfile" + + cat <<_LT_EOF >> "$cfgfile" +#! $SHELL +# Generated automatically by $as_me ($PACKAGE) $VERSION +# NOTE: Changes made to this file will be lost: look at ltmain.sh. + +# Provide generalized library-building support services. +# Written by Gordon Matzigkeit, 1996 + +# Copyright (C) 2014 Free Software Foundation, Inc. +# This is free software; see the source for copying conditions. There is NO +# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +# GNU Libtool is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of of the License, or +# (at your option) any later version. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program or library that is built +# using GNU Libtool, you may include this file under the same +# distribution terms that you use for the rest of that program. +# +# GNU Libtool is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + + +# The names of the tagged configurations supported by this script. +available_tags='RC ' + +# Configured defaults for sys_lib_dlsearch_path munging. +: \${LT_SYS_LIBRARY_PATH="$configure_time_lt_sys_library_path"} + +# ### BEGIN LIBTOOL CONFIG + +# Which release of libtool.m4 was used? +macro_version=$macro_version +macro_revision=$macro_revision + +# Assembler program. +AS=$lt_AS + +# DLL creation program. +DLLTOOL=$lt_DLLTOOL + +# Object dumper program. +OBJDUMP=$lt_OBJDUMP + +# Whether or not to build shared libraries. +build_libtool_libs=$enable_shared + +# Whether or not to build static libraries. +build_old_libs=$enable_static + +# What type of objects to build. +pic_mode=$pic_mode + +# Whether or not to optimize for fast installation. +fast_install=$enable_fast_install + +# Shared archive member basename,for filename based shared library versioning on AIX. +shared_archive_member_spec=$shared_archive_member_spec + +# Shell to use when invoking shell scripts. +SHELL=$lt_SHELL + +# An echo program that protects backslashes. +ECHO=$lt_ECHO + +# The PATH separator for the build system. +PATH_SEPARATOR=$lt_PATH_SEPARATOR + +# The host system. +host_alias=$host_alias +host=$host +host_os=$host_os + +# The build system. +build_alias=$build_alias +build=$build +build_os=$build_os + +# A sed program that does not truncate output. +SED=$lt_SED + +# Sed that helps us avoid accidentally triggering echo(1) options like -n. +Xsed="\$SED -e 1s/^X//" + +# A grep program that handles long lines. +GREP=$lt_GREP + +# An ERE matcher. +EGREP=$lt_EGREP + +# A literal string matcher. +FGREP=$lt_FGREP + +# A BSD- or MS-compatible name lister. +NM=$lt_NM + +# Whether we need soft or hard links. +LN_S=$lt_LN_S + +# What is the maximum length of a command? +max_cmd_len=$max_cmd_len + +# Object file suffix (normally "o"). +objext=$ac_objext + +# Executable file suffix (normally ""). +exeext=$exeext + +# whether the shell understands "unset". +lt_unset=$lt_unset + +# turn spaces into newlines. +SP2NL=$lt_lt_SP2NL + +# turn newlines into spaces. +NL2SP=$lt_lt_NL2SP + +# convert \$build file names to \$host format. +to_host_file_cmd=$lt_cv_to_host_file_cmd + +# convert \$build files to toolchain format. +to_tool_file_cmd=$lt_cv_to_tool_file_cmd + +# A file(cmd) program that detects file types. +FILECMD=$lt_FILECMD + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method=$lt_deplibs_check_method + +# Command to use when deplibs_check_method = "file_magic". +file_magic_cmd=$lt_file_magic_cmd + +# How to find potential files when deplibs_check_method = "file_magic". +file_magic_glob=$lt_file_magic_glob + +# Find potential files using nocaseglob when deplibs_check_method = "file_magic". +want_nocaseglob=$lt_want_nocaseglob + +# Command to associate shared and link libraries. +sharedlib_from_linklib_cmd=$lt_sharedlib_from_linklib_cmd + +# The archiver. +AR=$lt_AR + +# Flags to create an archive (by configure). +lt_ar_flags=$lt_ar_flags + +# Flags to create an archive. +AR_FLAGS=\${ARFLAGS-"\$lt_ar_flags"} + +# How to feed a file listing to the archiver. +archiver_list_spec=$lt_archiver_list_spec + +# A symbol stripping program. +STRIP=$lt_STRIP + +# Commands used to install an old-style archive. +RANLIB=$lt_RANLIB +old_postinstall_cmds=$lt_old_postinstall_cmds +old_postuninstall_cmds=$lt_old_postuninstall_cmds + +# Whether to use a lock for old archive extraction. +lock_old_archive_extraction=$lock_old_archive_extraction + +# A C compiler. +LTCC=$lt_CC + +# LTCC compiler flags. +LTCFLAGS=$lt_CFLAGS + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe + +# Transform the output of nm in a proper C declaration. +global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl + +# Transform the output of nm into a list of symbols to manually relocate. +global_symbol_to_import=$lt_lt_cv_sys_global_symbol_to_import + +# Transform the output of nm in a C name address pair. +global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address + +# Transform the output of nm in a C name address pair when lib prefix is needed. +global_symbol_to_c_name_address_lib_prefix=$lt_lt_cv_sys_global_symbol_to_c_name_address_lib_prefix + +# The name lister interface. +nm_interface=$lt_lt_cv_nm_interface + +# Specify filename containing input files for \$NM. +nm_file_list_spec=$lt_nm_file_list_spec + +# The root where to search for dependent libraries,and where our libraries should be installed. +lt_sysroot=$lt_sysroot + +# Command to truncate a binary pipe. +lt_truncate_bin=$lt_lt_cv_truncate_bin + +# The name of the directory that contains temporary libtool files. +objdir=$objdir + +# Used to examine libraries when file_magic_cmd begins with "file". +MAGIC_CMD=$MAGIC_CMD + +# Must we lock files when doing compilation? +need_locks=$lt_need_locks + +# Manifest tool. +MANIFEST_TOOL=$lt_MANIFEST_TOOL + +# Tool to manipulate archived DWARF debug symbol files on Mac OS X. +DSYMUTIL=$lt_DSYMUTIL + +# Tool to change global to local symbols on Mac OS X. +NMEDIT=$lt_NMEDIT + +# Tool to manipulate fat objects and archives on Mac OS X. +LIPO=$lt_LIPO + +# ldd/readelf like tool for Mach-O binaries on Mac OS X. +OTOOL=$lt_OTOOL + +# ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4. +OTOOL64=$lt_OTOOL64 + +# Old archive suffix (normally "a"). +libext=$libext + +# Shared library suffix (normally ".so"). +shrext_cmds=$lt_shrext_cmds + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds=$lt_extract_expsyms_cmds + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at link time. +variables_saved_for_relink=$lt_variables_saved_for_relink + +# Do we need the "lib" prefix for modules? +need_lib_prefix=$need_lib_prefix + +# Do we need a version for libraries? +need_version=$need_version + +# Library versioning type. +version_type=$version_type + +# Shared library runtime path variable. +runpath_var=$runpath_var + +# Shared library path variable. +shlibpath_var=$shlibpath_var + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=$shlibpath_overrides_runpath + +# Format of library name prefix. +libname_spec=$lt_libname_spec + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME +library_names_spec=$lt_library_names_spec + +# The coded name of the library, if different from the real name. +soname_spec=$lt_soname_spec + +# Permission mode override for installation of shared libraries. +install_override_mode=$lt_install_override_mode + +# Command to use after installation of a shared archive. +postinstall_cmds=$lt_postinstall_cmds + +# Command to use after uninstallation of a shared archive. +postuninstall_cmds=$lt_postuninstall_cmds + +# Commands used to finish a libtool library installation in a directory. +finish_cmds=$lt_finish_cmds + +# As "finish_cmds", except a single script fragment to be evaled but +# not shown. +finish_eval=$lt_finish_eval + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=$hardcode_into_libs + +# Compile-time system search path for libraries. +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec + +# Detected run-time system search path for libraries. +sys_lib_dlsearch_path_spec=$lt_configure_time_dlsearch_path + +# Explicit LT_SYS_LIBRARY_PATH set during ./configure time. +configure_time_lt_sys_library_path=$lt_configure_time_lt_sys_library_path + +# Whether dlopen is supported. +dlopen_support=$enable_dlopen + +# Whether dlopen of programs is supported. +dlopen_self=$enable_dlopen_self + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=$enable_dlopen_self_static + +# Commands to strip libraries. +old_striplib=$lt_old_striplib +striplib=$lt_striplib + + +# The linker used to build libraries. +LD=$lt_LD + +# How to create reloadable object files. +reload_flag=$lt_reload_flag +reload_cmds=$lt_reload_cmds + +# Commands used to build an old-style archive. +old_archive_cmds=$lt_old_archive_cmds + +# A language specific compiler. +CC=$lt_compiler + +# Is the compiler the GNU compiler? +with_gcc=$GCC + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag + +# Additional compiler flags for building library objects. +pic_flag=$lt_lt_prog_compiler_pic + +# How to pass a linker flag through the compiler. +wl=$lt_lt_prog_compiler_wl + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_lt_prog_compiler_static + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_lt_cv_prog_compiler_c_o + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$archive_cmds_need_lc + +# Whether or not to disallow shared libs when runtime libs are static. +allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_export_dynamic_flag_spec + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_whole_archive_flag_spec + +# Whether the compiler copes with passing no objects directly. +compiler_needs_object=$lt_compiler_needs_object + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_old_archive_from_new_cmds + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds + +# Commands used to build a shared archive. +archive_cmds=$lt_archive_cmds +archive_expsym_cmds=$lt_archive_expsym_cmds + +# Commands used to build a loadable module if different from building +# a shared archive. +module_cmds=$lt_module_cmds +module_expsym_cmds=$lt_module_expsym_cmds + +# Whether we are building with GNU ld or not. +with_gnu_ld=$lt_with_gnu_ld + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_allow_undefined_flag + +# Flag that enforces no undefined symbols. +no_undefined_flag=$lt_no_undefined_flag + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist +hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec + +# Whether we need a single "-rpath" flag with a separated argument. +hardcode_libdir_separator=$lt_hardcode_libdir_separator + +# Set to "yes" if using DIR/libNAME\$shared_ext during linking hardcodes +# DIR into the resulting binary. +hardcode_direct=$hardcode_direct + +# Set to "yes" if using DIR/libNAME\$shared_ext during linking hardcodes +# DIR into the resulting binary and the resulting library dependency is +# "absolute",i.e impossible to change by setting \$shlibpath_var if the +# library is relocated. +hardcode_direct_absolute=$hardcode_direct_absolute + +# Set to "yes" if using the -LDIR flag during linking hardcodes DIR +# into the resulting binary. +hardcode_minus_L=$hardcode_minus_L + +# Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR +# into the resulting binary. +hardcode_shlibpath_var=$hardcode_shlibpath_var + +# Set to "yes" if building a shared library automatically hardcodes DIR +# into the library and all subsequent libraries and executables linked +# against it. +hardcode_automatic=$hardcode_automatic + +# Set to yes if linker adds runtime paths of dependent libraries +# to runtime path list. +inherit_rpath=$inherit_rpath + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$link_all_deplibs + +# Set to "yes" if exported symbols are required. +always_export_symbols=$always_export_symbols + +# The commands to list exported symbols. +export_symbols_cmds=$lt_export_symbols_cmds + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_exclude_expsyms + +# Symbols that must always be exported. +include_expsyms=$lt_include_expsyms + +# Commands necessary for linking programs (against libraries) with templates. +prelink_cmds=$lt_prelink_cmds + +# Commands necessary for finishing linking programs. +postlink_cmds=$lt_postlink_cmds + +# Specify filename containing input files. +file_list_spec=$lt_file_list_spec + +# How to hardcode a shared library path into an executable. +hardcode_action=$hardcode_action + +# ### END LIBTOOL CONFIG + +_LT_EOF + + cat <<'_LT_EOF' >> "$cfgfile" + +# ### BEGIN FUNCTIONS SHARED WITH CONFIGURE + +# func_munge_path_list VARIABLE PATH +# ----------------------------------- +# VARIABLE is name of variable containing _space_ separated list of +# directories to be munged by the contents of PATH, which is string +# having a format: +# "DIR[:DIR]:" +# string "DIR[ DIR]" will be prepended to VARIABLE +# ":DIR[:DIR]" +# string "DIR[ DIR]" will be appended to VARIABLE +# "DIRP[:DIRP]::[DIRA:]DIRA" +# string "DIRP[ DIRP]" will be prepended to VARIABLE and string +# "DIRA[ DIRA]" will be appended to VARIABLE +# "DIR[:DIR]" +# VARIABLE will be replaced by "DIR[ DIR]" +func_munge_path_list () +{ + case x$2 in + x) + ;; + *:) + eval $1=\"`$ECHO $2 | $SED 's/:/ /g'` \$$1\" + ;; + x:*) + eval $1=\"\$$1 `$ECHO $2 | $SED 's/:/ /g'`\" + ;; + *::*) + eval $1=\"\$$1\ `$ECHO $2 | $SED -e 's/.*:://' -e 's/:/ /g'`\" + eval $1=\"`$ECHO $2 | $SED -e 's/::.*//' -e 's/:/ /g'`\ \$$1\" + ;; + *) + eval $1=\"`$ECHO $2 | $SED 's/:/ /g'`\" + ;; + esac +} + + +# Calculate cc_basename. Skip known compiler wrappers and cross-prefix. +func_cc_basename () +{ + for cc_temp in $*""; do + case $cc_temp in + compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; + distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; + \-*) ;; + *) break;; + esac + done + func_cc_basename_result=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` +} + + +# ### END FUNCTIONS SHARED WITH CONFIGURE + +_LT_EOF + + case $host_os in + aix3*) + cat <<\_LT_EOF >> "$cfgfile" +# AIX sometimes has problems with the GCC collect2 program. For some +# reason, if we set the COLLECT_NAMES environment variable, the problems +# vanish in a puff of smoke. +if test set != "${COLLECT_NAMES+set}"; then + COLLECT_NAMES= + export COLLECT_NAMES +fi +_LT_EOF + ;; + esac + + + +ltmain=$ac_aux_dir/ltmain.sh + + + # We use sed instead of cat because bash on DJGPP gets confused if + # if finds mixed CR/LF and LF-only lines. Since sed operates in + # text mode, it properly converts lines to CR/LF. This bash problem + # is reportedly fixed, but why not run on old versions too? + $SED '$q' "$ltmain" >> "$cfgfile" \ + || (rm -f "$cfgfile"; exit 1) + + mv -f "$cfgfile" "$ofile" || + (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") + chmod +x "$ofile" + + + cat <<_LT_EOF >> "$ofile" + +# ### BEGIN LIBTOOL TAG CONFIG: RC + +# The linker used to build libraries. +LD=$lt_LD_RC + +# How to create reloadable object files. +reload_flag=$lt_reload_flag_RC +reload_cmds=$lt_reload_cmds_RC + +# Commands used to build an old-style archive. +old_archive_cmds=$lt_old_archive_cmds_RC + +# A language specific compiler. +CC=$lt_compiler_RC + +# Is the compiler the GNU compiler? +with_gcc=$GCC_RC + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_RC + +# Additional compiler flags for building library objects. +pic_flag=$lt_lt_prog_compiler_pic_RC + +# How to pass a linker flag through the compiler. +wl=$lt_lt_prog_compiler_wl_RC + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_lt_prog_compiler_static_RC + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_lt_cv_prog_compiler_c_o_RC + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$archive_cmds_need_lc_RC + +# Whether or not to disallow shared libs when runtime libs are static. +allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_RC + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_RC + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_whole_archive_flag_spec_RC + +# Whether the compiler copes with passing no objects directly. +compiler_needs_object=$lt_compiler_needs_object_RC + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_RC + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_RC + +# Commands used to build a shared archive. +archive_cmds=$lt_archive_cmds_RC +archive_expsym_cmds=$lt_archive_expsym_cmds_RC + +# Commands used to build a loadable module if different from building +# a shared archive. +module_cmds=$lt_module_cmds_RC +module_expsym_cmds=$lt_module_expsym_cmds_RC + +# Whether we are building with GNU ld or not. +with_gnu_ld=$lt_with_gnu_ld_RC + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_allow_undefined_flag_RC + +# Flag that enforces no undefined symbols. +no_undefined_flag=$lt_no_undefined_flag_RC + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist +hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_RC + +# Whether we need a single "-rpath" flag with a separated argument. +hardcode_libdir_separator=$lt_hardcode_libdir_separator_RC + +# Set to "yes" if using DIR/libNAME\$shared_ext during linking hardcodes +# DIR into the resulting binary. +hardcode_direct=$hardcode_direct_RC + +# Set to "yes" if using DIR/libNAME\$shared_ext during linking hardcodes +# DIR into the resulting binary and the resulting library dependency is +# "absolute",i.e impossible to change by setting \$shlibpath_var if the +# library is relocated. +hardcode_direct_absolute=$hardcode_direct_absolute_RC + +# Set to "yes" if using the -LDIR flag during linking hardcodes DIR +# into the resulting binary. +hardcode_minus_L=$hardcode_minus_L_RC + +# Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR +# into the resulting binary. +hardcode_shlibpath_var=$hardcode_shlibpath_var_RC + +# Set to "yes" if building a shared library automatically hardcodes DIR +# into the library and all subsequent libraries and executables linked +# against it. +hardcode_automatic=$hardcode_automatic_RC + +# Set to yes if linker adds runtime paths of dependent libraries +# to runtime path list. +inherit_rpath=$inherit_rpath_RC + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$link_all_deplibs_RC + +# Set to "yes" if exported symbols are required. +always_export_symbols=$always_export_symbols_RC + +# The commands to list exported symbols. +export_symbols_cmds=$lt_export_symbols_cmds_RC + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_exclude_expsyms_RC + +# Symbols that must always be exported. +include_expsyms=$lt_include_expsyms_RC + +# Commands necessary for linking programs (against libraries) with templates. +prelink_cmds=$lt_prelink_cmds_RC + +# Commands necessary for finishing linking programs. +postlink_cmds=$lt_postlink_cmds_RC + +# Specify filename containing input files. +file_list_spec=$lt_file_list_spec_RC + +# How to hardcode a shared library path into an executable. +hardcode_action=$hardcode_action_RC + +# ### END LIBTOOL TAG CONFIG: RC +_LT_EOF + + ;; + + esac +done # for ac_tag + + +as_fn_exit 0 +_ACEOF +ac_clean_files=$ac_clean_files_save + +test $ac_write_fail = 0 || + as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 + + +# configure is writing to config.log, and then calls config.status. +# config.status does its own redirection, appending to config.log. +# Unfortunately, on DOS this fails, as config.log is still kept open +# by configure, so config.status won't be able to write to it; its +# output is simply discarded. So we exec the FD to /dev/null, +# effectively closing config.log, so it can be properly (re)opened and +# appended to by config.status. When coming back to configure, we +# need to make the FD available again. +if test "$no_create" != yes; then + ac_cs_success=: + ac_config_status_args= + test "$silent" = yes && + ac_config_status_args="$ac_config_status_args --quiet" + exec 5>/dev/null + $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false + exec 5>>config.log + # Use ||, not &&, to avoid exiting from the if with $? = 1, which + # would make configure fail if this is the last instruction. + $ac_cs_success || as_fn_exit 1 +fi +if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 +printf "%s\n" "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} +fi + + + + tmp_cpp=`eval echo "$ac_cpp" 2>/dev/null` + if test -z "$tmp_cpp"; then + tmp_cpp='cpp' + fi + cat >./tests/configurehelp.pm <<_EOF +# This is a generated file. Do not edit. + +package configurehelp; + +use strict; +use warnings; +use Exporter; + +use vars qw( + @ISA + @EXPORT_OK + \$Cpreprocessor + ); + +@ISA = qw(Exporter); + +@EXPORT_OK = qw( + \$Cpreprocessor + ); + +\$Cpreprocessor = '$tmp_cpp'; + +1; +_EOF + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: Configured to build curl/libcurl: + + Host setup: ${host} + Install prefix: ${prefix} + Compiler: ${CC} + CFLAGS: ${CFLAGS} + CPPFLAGS: ${CPPFLAGS} + LDFLAGS: ${LDFLAGS} + LIBS: ${LIBS} + + curl version: ${CURLVERSION} + SSL: ${curl_ssl_msg} + SSH: ${curl_ssh_msg} + zlib: ${curl_zlib_msg} + brotli: ${curl_brotli_msg} + zstd: ${curl_zstd_msg} + GSS-API: ${curl_gss_msg} + GSASL: ${curl_gsasl_msg} + TLS-SRP: ${curl_tls_srp_msg} + resolver: ${curl_res_msg} + IPv6: ${curl_ipv6_msg} + Unix sockets: ${curl_unix_sockets_msg} + IDN: ${curl_idn_msg} + Build docs: ${curl_docs_msg} + Build libcurl: Shared=${enable_shared}, Static=${enable_static} + Built-in manual: ${curl_manual_msg} + --libcurl option: ${curl_libcurl_msg} + Verbose errors: ${curl_verbose_msg} + Code coverage: ${curl_coverage_msg} + SSPI: ${curl_sspi_msg} + ca cert bundle: ${ca}${ca_warning} + ca cert path: ${capath}${capath_warning} + ca fallback: ${with_ca_fallback} + LDAP: ${curl_ldap_msg} + LDAPS: ${curl_ldaps_msg} + RTSP: ${curl_rtsp_msg} + RTMP: ${curl_rtmp_msg} + PSL: ${curl_psl_msg} + Alt-svc: ${curl_altsvc_msg} + Headers API: ${curl_headers_msg} + HSTS: ${curl_hsts_msg} + HTTP1: ${curl_h1_msg} + HTTP2: ${curl_h2_msg} + HTTP3: ${curl_h3_msg} + ECH: ${curl_ech_msg} + WebSockets: ${curl_ws_msg} + Protocols: ${SUPPORT_PROTOCOLS} + Features: ${SUPPORT_FEATURES} +" >&5 +printf "%s\n" "$as_me: Configured to build curl/libcurl: + + Host setup: ${host} + Install prefix: ${prefix} + Compiler: ${CC} + CFLAGS: ${CFLAGS} + CPPFLAGS: ${CPPFLAGS} + LDFLAGS: ${LDFLAGS} + LIBS: ${LIBS} + + curl version: ${CURLVERSION} + SSL: ${curl_ssl_msg} + SSH: ${curl_ssh_msg} + zlib: ${curl_zlib_msg} + brotli: ${curl_brotli_msg} + zstd: ${curl_zstd_msg} + GSS-API: ${curl_gss_msg} + GSASL: ${curl_gsasl_msg} + TLS-SRP: ${curl_tls_srp_msg} + resolver: ${curl_res_msg} + IPv6: ${curl_ipv6_msg} + Unix sockets: ${curl_unix_sockets_msg} + IDN: ${curl_idn_msg} + Build docs: ${curl_docs_msg} + Build libcurl: Shared=${enable_shared}, Static=${enable_static} + Built-in manual: ${curl_manual_msg} + --libcurl option: ${curl_libcurl_msg} + Verbose errors: ${curl_verbose_msg} + Code coverage: ${curl_coverage_msg} + SSPI: ${curl_sspi_msg} + ca cert bundle: ${ca}${ca_warning} + ca cert path: ${capath}${capath_warning} + ca fallback: ${with_ca_fallback} + LDAP: ${curl_ldap_msg} + LDAPS: ${curl_ldaps_msg} + RTSP: ${curl_rtsp_msg} + RTMP: ${curl_rtmp_msg} + PSL: ${curl_psl_msg} + Alt-svc: ${curl_altsvc_msg} + Headers API: ${curl_headers_msg} + HSTS: ${curl_hsts_msg} + HTTP1: ${curl_h1_msg} + HTTP2: ${curl_h2_msg} + HTTP3: ${curl_h3_msg} + ECH: ${curl_ech_msg} + WebSockets: ${curl_ws_msg} + Protocols: ${SUPPORT_PROTOCOLS} + Features: ${SUPPORT_FEATURES} +" >&6;} + +non13=`echo "$TLSCHOICE" | grep -Ei 'bearssl|secure-transport|mbedtls'`; +if test -n "$non13"; then + cat >&2 << _EOF + WARNING: A selected TLS library ($TLSCHOICE) does not support TLS 1.3! +_EOF +fi + +if test -n "$experimental"; then + cat >&2 << _EOF + WARNING: $experimental enabled but marked EXPERIMENTAL. Use with caution! +_EOF +fi + diff --git a/third_party/curl/configure.ac b/third_party/curl/configure.ac new file mode 100644 index 0000000..a4ea9f7 --- /dev/null +++ b/third_party/curl/configure.ac @@ -0,0 +1,5051 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** +dnl Process this file with autoconf to produce a configure script. + +AC_PREREQ(2.59) + +dnl We don't know the version number "statically" so we use a dash here +AC_INIT([curl], [-], [a suitable curl mailing list: https://curl.se/mail/]) + +XC_OVR_ZZ50 +XC_OVR_ZZ60 +CURL_OVERRIDE_AUTOCONF + +dnl configure script copyright +AC_COPYRIGHT([Copyright (C) Daniel Stenberg, +This configure script may be copied, distributed and modified under the +terms of the curl license; see COPYING for more details]) + +AC_CONFIG_SRCDIR([lib/urldata.h]) +AC_CONFIG_HEADERS(lib/curl_config.h) +AC_CONFIG_MACRO_DIR([m4]) +AM_MAINTAINER_MODE +m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])]) + +CURL_CHECK_OPTION_DEBUG +CURL_CHECK_OPTION_OPTIMIZE +CURL_CHECK_OPTION_WARNINGS +CURL_CHECK_OPTION_WERROR +CURL_CHECK_OPTION_CURLDEBUG +CURL_CHECK_OPTION_SYMBOL_HIDING +CURL_CHECK_OPTION_ARES +CURL_CHECK_OPTION_RT +CURL_CHECK_OPTION_HTTPSRR +CURL_CHECK_OPTION_ECH + +XC_CHECK_PATH_SEPARATOR + +# +# save the configure arguments +# +CONFIGURE_OPTIONS="\"$ac_configure_args\"" +AC_SUBST(CONFIGURE_OPTIONS) + +dnl SED is mandatory for configure process and libtool. +dnl Set it now, allowing it to be changed later. +if test -z "$SED"; then + dnl allow it to be overridden + AC_PATH_PROG([SED], [sed], [not_found], + [$PATH:/usr/bin:/usr/local/bin]) + if test -z "$SED" || test "$SED" = "not_found"; then + AC_MSG_ERROR([sed not found in PATH. Cannot continue without sed.]) + fi +fi +AC_SUBST([SED]) + +dnl GREP is mandatory for configure process and libtool. +dnl Set it now, allowing it to be changed later. +if test -z "$GREP"; then + dnl allow it to be overridden + AC_PATH_PROG([GREP], [grep], [not_found], + [$PATH:/usr/bin:/usr/local/bin]) + if test -z "$GREP" || test "$GREP" = "not_found"; then + AC_MSG_ERROR([grep not found in PATH. Cannot continue without grep.]) + fi +fi +AC_SUBST([GREP]) + +dnl 'grep -E' is mandatory for configure process and libtool. +dnl Set it now, allowing it to be changed later. +if test -z "$EGREP"; then + dnl allow it to be overridden + AC_MSG_CHECKING([that grep -E works]) + if echo a | ($GREP -E '(a|b)') >/dev/null 2>&1; then + EGREP="$GREP -E" + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + AC_PATH_PROG([EGREP], [egrep], [not_found], + [$PATH:/usr/bin:/usr/local/bin]) + fi +fi +if test -z "$EGREP" || test "$EGREP" = "not_found"; then + AC_MSG_ERROR([grep -E is not working and egrep is not found in PATH. Cannot continue.]) +fi +AC_SUBST([EGREP]) + +dnl AR is mandatory for configure process and libtool. +dnl This is target dependent, so check it as a tool. +if test -z "$AR"; then + dnl allow it to be overridden + AC_PATH_TOOL([AR], [ar], [not_found], + [$PATH:/usr/bin:/usr/local/bin]) + if test -z "$AR" || test "$AR" = "not_found"; then + AC_MSG_ERROR([ar not found in PATH. Cannot continue without ar.]) + fi +fi +AC_SUBST([AR]) + +AC_SUBST(libext) + +dnl figure out the libcurl version +CURLVERSION=`$SED -ne 's/^#define LIBCURL_VERSION "\(.*\)".*/\1/p' ${srcdir}/include/curl/curlver.h` +XC_CHECK_PROG_CC +CURL_ATOMIC + +dnl for --enable-code-coverage +CURL_COVERAGE + +XC_AUTOMAKE +AC_MSG_CHECKING([curl version]) +AC_MSG_RESULT($CURLVERSION) + +AC_SUBST(CURLVERSION) + +dnl +dnl we extract the numerical version for curl-config only +VERSIONNUM=`$SED -ne 's/^#define LIBCURL_VERSION_NUM 0x\([0-9A-Fa-f]*\).*/\1/p' ${srcdir}/include/curl/curlver.h` +AC_SUBST(VERSIONNUM) + +dnl Solaris pkgadd support definitions +PKGADD_PKG="HAXXcurl" +PKGADD_NAME="curl - a client that groks URLs" +PKGADD_VENDOR="curl.se" +AC_SUBST(PKGADD_PKG) +AC_SUBST(PKGADD_NAME) +AC_SUBST(PKGADD_VENDOR) + +dnl +dnl initialize all the info variables + curl_ssl_msg="no (--with-{openssl,gnutls,mbedtls,wolfssl,schannel,secure-transport,amissl,bearssl,rustls} )" + curl_ssh_msg="no (--with-{libssh,libssh2})" + curl_zlib_msg="no (--with-zlib)" + curl_brotli_msg="no (--with-brotli)" + curl_zstd_msg="no (--with-zstd)" + curl_gss_msg="no (--with-gssapi)" + curl_gsasl_msg="no (--with-gsasl)" +curl_tls_srp_msg="no (--enable-tls-srp)" + curl_res_msg="default (--enable-ares / --enable-threaded-resolver)" + curl_ipv6_msg="no (--enable-ipv6)" +curl_unix_sockets_msg="no (--enable-unix-sockets)" + curl_idn_msg="no (--with-{libidn2,winidn})" + curl_docs_msg="enabled (--disable-docs)" + curl_manual_msg="no (--enable-manual)" +curl_libcurl_msg="enabled (--disable-libcurl-option)" +curl_verbose_msg="enabled (--disable-verbose)" + curl_sspi_msg="no (--enable-sspi)" + curl_ldap_msg="no (--enable-ldap / --with-ldap-lib / --with-lber-lib)" + curl_ldaps_msg="no (--enable-ldaps)" + curl_rtsp_msg="no (--enable-rtsp)" + curl_rtmp_msg="no (--with-librtmp)" + curl_psl_msg="no (--with-libpsl)" + curl_altsvc_msg="enabled (--disable-alt-svc)" +curl_headers_msg="enabled (--disable-headers-api)" + curl_hsts_msg="enabled (--disable-hsts)" + curl_ws_msg="no (--enable-websockets)" + ssl_backends= + curl_h1_msg="enabled (internal)" + curl_h2_msg="no (--with-nghttp2)" + curl_h3_msg="no (--with-ngtcp2 --with-nghttp3, --with-quiche, --with-openssl-quic, --with-msh3)" + +enable_altsvc="yes" +hsts="yes" + +dnl +dnl Save some initial values the user might have provided +dnl +INITIAL_LDFLAGS=$LDFLAGS +INITIAL_LIBS=$LIBS + +dnl +dnl Generates a shell script to run the compiler with LD_LIBRARY_PATH set to +dnl the value used right now. This lets CURL_RUN_IFELSE set LD_LIBRARY_PATH to +dnl something different but only have that affect the execution of the results +dnl of the compile, not change the libraries for the compiler itself. +dnl +compilersh="run-compiler" +CURL_SAVED_CC="$CC" +export CURL_SAVED_CC +CURL_SAVED_LD_LIBRARY_PATH="$LD_LIBRARY_PATH" +export CURL_SAVED_LD_LIBRARY_PATH +cat <<\EOF > "$compilersh" +CC="$CURL_SAVED_CC" +export CC +LD_LIBRARY_PATH="$CURL_SAVED_LD_LIBRARY_PATH" +export LD_LIBRARY_PATH +exec $CC "$@" +EOF + +dnl ********************************************************************** +dnl See which TLS backend(s) that are requested. Just do all the +dnl TLS AC_ARG_WITH() invokes here and do the checks later +dnl ********************************************************************** +OPT_SCHANNEL=no +AC_ARG_WITH(schannel,dnl +AS_HELP_STRING([--with-schannel],[enable Windows native SSL/TLS]), + OPT_SCHANNEL=$withval + TLSCHOICE="schannel") + +OPT_SECURETRANSPORT=no +AC_ARG_WITH(secure-transport,dnl +AS_HELP_STRING([--with-secure-transport],[enable Apple OS native SSL/TLS]),[ + OPT_SECURETRANSPORT=$withval + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }Secure-Transport" +]) + +OPT_AMISSL=no +AC_ARG_WITH(amissl,dnl +AS_HELP_STRING([--with-amissl],[enable Amiga native SSL/TLS (AmiSSL)]),[ + OPT_AMISSL=$withval + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }AmiSSL" +]) + +OPT_OPENSSL=no +dnl Default to no CA bundle +ca="no" +AC_ARG_WITH(ssl,dnl +AS_HELP_STRING([--with-ssl=PATH],[old version of --with-openssl]) +AS_HELP_STRING([--without-ssl], [build without any TLS library]),[ + OPT_SSL=$withval + OPT_OPENSSL=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }OpenSSL" + else + SSL_DISABLED="D" + fi +]) + +AC_ARG_WITH(openssl,dnl +AS_HELP_STRING([--with-openssl=PATH],[Where to look for OpenSSL, PATH points to the SSL installation (default: /usr/local/ssl); when possible, set the PKG_CONFIG_PATH environment variable instead of using this option]),[ + OPT_OPENSSL=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }OpenSSL" + fi +]) + +OPT_GNUTLS=no +AC_ARG_WITH(gnutls,dnl +AS_HELP_STRING([--with-gnutls=PATH],[where to look for GnuTLS, PATH points to the installation root]),[ + OPT_GNUTLS=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }GnuTLS" + fi +]) + +OPT_MBEDTLS=no +AC_ARG_WITH(mbedtls,dnl +AS_HELP_STRING([--with-mbedtls=PATH],[where to look for mbedTLS, PATH points to the installation root]),[ + OPT_MBEDTLS=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }mbedTLS" + fi +]) + +OPT_WOLFSSL=no +AC_ARG_WITH(wolfssl,dnl +AS_HELP_STRING([--with-wolfssl=PATH],[where to look for WolfSSL, PATH points to the installation root (default: system lib default)]),[ + OPT_WOLFSSL=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }wolfSSL" + fi +]) + +OPT_BEARSSL=no +AC_ARG_WITH(bearssl,dnl +AS_HELP_STRING([--with-bearssl=PATH],[where to look for BearSSL, PATH points to the installation root]),[ + OPT_BEARSSL=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }BearSSL" + fi +]) + +OPT_RUSTLS=no +AC_ARG_WITH(rustls,dnl +AS_HELP_STRING([--with-rustls=PATH],[where to look for rustls, PATH points to the installation root]),[ + OPT_RUSTLS=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }rustls" + experimental="$experimental rustls" + fi +]) + +TEST_NGHTTPX=nghttpx +AC_ARG_WITH(test-nghttpx,dnl +AS_HELP_STRING([--with-test-nghttpx=PATH],[where to find nghttpx for testing]), + TEST_NGHTTPX=$withval + if test X"$OPT_TEST_NGHTTPX" = "Xno" ; then + TEST_NGHTTPX="" + fi +) +AC_SUBST(TEST_NGHTTPX) + +CADDY=/usr/bin/caddy +AC_ARG_WITH(test-caddy,dnl +AS_HELP_STRING([--with-test-caddy=PATH],[where to find caddy for testing]), + CADDY=$withval + if test X"$OPT_CADDY" = "Xno" ; then + CADDY="" + fi +) +AC_SUBST(CADDY) + +VSFTPD=/usr/sbin/vsftpd +AC_ARG_WITH(test-vsftpd,dnl +AS_HELP_STRING([--with-test-vsftpd=PATH],[where to find vsftpd for testing]), + VSFTPD=$withval + if test X"$OPT_VSFTPD" = "Xno" ; then + VSFTPD="" + fi +) +AC_SUBST(VSFTPD) + +dnl we'd like a httpd+apachectl as test server +dnl +HTTPD_ENABLED="maybe" +AC_ARG_WITH(test-httpd, [AS_HELP_STRING([--with-test-httpd=PATH], + [where to find httpd/apache2 for testing])], + [request_httpd=$withval], [request_httpd=check]) +if test x"$request_httpd" = "xcheck" -o x"$request_httpd" = "xyes"; then + if test -x "/usr/sbin/apache2" -a -x "/usr/sbin/apache2ctl"; then + # common location on distros (debian/ubuntu) + HTTPD="/usr/sbin/apache2" + APACHECTL="/usr/sbin/apache2ctl" + AC_PATH_PROG([APXS], [apxs]) + if test "x$APXS" = "x"; then + AC_MSG_NOTICE([apache2-dev not installed, httpd tests disabled]) + HTTPD_ENABLED="no" + fi + else + AC_PATH_PROG([HTTPD], [httpd]) + if test "x$HTTPD" = "x"; then + AC_PATH_PROG([HTTPD], [apache2]) + fi + AC_PATH_PROG([APACHECTL], [apachectl]) + AC_PATH_PROG([APXS], [apxs]) + if test "x$HTTPD" = "x" -o "x$APACHECTL" = "x"; then + AC_MSG_NOTICE([httpd/apache2 not in PATH, http tests disabled]) + HTTPD_ENABLED="no" + fi + if test "x$APXS" = "x"; then + AC_MSG_NOTICE([apxs not in PATH, http tests disabled]) + HTTPD_ENABLED="no" + fi + fi +elif test x"$request_httpd" != "xno"; then + HTTPD="${request_httpd}/bin/httpd" + APACHECTL="${request_httpd}/bin/apachectl" + APXS="${request_httpd}/bin/apxs" + if test ! -x "${HTTPD}"; then + AC_MSG_NOTICE([httpd not found as ${HTTPD}, http tests disabled]) + HTTPD_ENABLED="no" + elif test ! -x "${APACHECTL}"; then + AC_MSG_NOTICE([apachectl not found as ${APACHECTL}, http tests disabled]) + HTTPD_ENABLED="no" + elif test ! -x "${APXS}"; then + AC_MSG_NOTICE([apxs not found as ${APXS}, http tests disabled]) + HTTPD_ENABLED="no" + else + AC_MSG_NOTICE([using HTTPD=$HTTPD for tests]) + fi +fi +if test x"$HTTPD_ENABLED" = "xno"; then + HTTPD="" + APACHECTL="" + APXS="" +fi +AC_SUBST(HTTPD) +AC_SUBST(APACHECTL) +AC_SUBST(APXS) + +dnl the nghttpx we might use in httpd testing +if test "x$TEST_NGHTTPX" != "x" -a "x$TEST_NGHTTPX" != "xnghttpx"; then + HTTPD_NGHTTPX="$TEST_NGHTTPX" +else + AC_PATH_PROG([HTTPD_NGHTTPX], [nghttpx], [], + [$PATH:/usr/bin:/usr/local/bin]) +fi +AC_SUBST(HTTPD_NGHTTPX) + +dnl the Caddy server we might use in testing +if test "x$TEST_CADDY" != "x"; then + CADDY="$TEST_CADDY" +else + AC_PATH_PROG([CADDY], [caddy]) +fi +AC_SUBST(CADDY) + +dnl If no TLS choice has been made, check if it was explicitly disabled or +dnl error out to force the user to decide. +if test -z "$TLSCHOICE"; then + if test "x$OPT_SSL" != "xno"; then + AC_MSG_ERROR([select TLS backend(s) or disable TLS with --without-ssl. + +Select from these: + + --with-amissl + --with-bearssl + --with-gnutls + --with-mbedtls + --with-openssl (also works for BoringSSL and libressl) + --with-rustls + --with-schannel + --with-secure-transport + --with-wolfssl +]) + fi +fi + +AC_ARG_WITH(darwinssl,, + AC_MSG_ERROR([--with-darwin-ssl and --without-darwin-ssl no longer work!])) + +dnl +dnl Detect the canonical host and target build environment +dnl + +AC_CANONICAL_HOST +dnl Get system canonical name +AC_DEFINE_UNQUOTED(OS, "${host}", [cpu-machine-OS]) + +# Silence warning: ar: 'u' modifier ignored since 'D' is the default +AC_SUBST(AR_FLAGS, [cr]) + +dnl This defines _ALL_SOURCE for AIX +CURL_CHECK_AIX_ALL_SOURCE + +dnl Our configure and build reentrant settings +CURL_CONFIGURE_THREAD_SAFE +CURL_CONFIGURE_REENTRANT + +dnl check for how to do large files +AC_SYS_LARGEFILE + +XC_LIBTOOL + +LT_LANG([Windows Resource]) + +# +# Automake conditionals based on libtool related checks +# + +AM_CONDITIONAL([CURL_LT_SHLIB_USE_VERSION_INFO], + [test "x$xc_lt_shlib_use_version_info" = 'xyes']) +AM_CONDITIONAL([CURL_LT_SHLIB_USE_NO_UNDEFINED], + [test "x$xc_lt_shlib_use_no_undefined" = 'xyes']) +AM_CONDITIONAL([CURL_LT_SHLIB_USE_MIMPURE_TEXT], + [test "x$xc_lt_shlib_use_mimpure_text" = 'xyes']) + +# +# Due to libtool and automake machinery limitations of not allowing +# specifying separate CPPFLAGS or CFLAGS when compiling objects for +# inclusion of these in shared or static libraries, we are forced to +# build using separate configure runs for shared and static libraries +# on systems where different CPPFLAGS or CFLAGS are mandatory in order +# to compile objects for each kind of library. Notice that relying on +# the '-DPIC' CFLAG that libtool provides is not valid given that the +# user might for example choose to build static libraries with PIC. +# + +# +# Make our Makefile.am files use the staticlib CPPFLAG only when strictly +# targeting a static library and not building its shared counterpart. +# + +AM_CONDITIONAL([USE_CPPFLAG_CURL_STATICLIB], + [test "x$xc_lt_build_static_only" = 'xyes']) + +# +# Make staticlib CPPFLAG variable and its definition visible in output +# files unconditionally, providing an empty definition unless strictly +# targeting a static library and not building its shared counterpart. +# + +CPPFLAG_CURL_STATICLIB= +if test "x$xc_lt_build_static_only" = 'xyes'; then + CPPFLAG_CURL_STATICLIB='-DCURL_STATICLIB' +fi +AC_SUBST([CPPFLAG_CURL_STATICLIB]) + + +# Determine whether all dependent libraries must be specified when linking +if test "X$enable_shared" = "Xyes" -a "X$link_all_deplibs" = "Xno" +then + REQUIRE_LIB_DEPS=no +else + REQUIRE_LIB_DEPS=yes +fi +AC_SUBST(REQUIRE_LIB_DEPS) +AM_CONDITIONAL(USE_EXPLICIT_LIB_DEPS, test x$REQUIRE_LIB_DEPS = xyes) + +dnl ********************************************************************** +dnl platform/compiler/architecture specific checks/flags +dnl ********************************************************************** + +CURL_CHECK_COMPILER +CURL_CHECK_NATIVE_WINDOWS +CURL_SET_COMPILER_BASIC_OPTS +CURL_SET_COMPILER_DEBUG_OPTS +CURL_SET_COMPILER_OPTIMIZE_OPTS +CURL_SET_COMPILER_WARNING_OPTS + +if test "$compiler_id" = "INTEL_UNIX_C"; then + # + if test "$compiler_num" -ge "1000"; then + dnl icc 10.X or later + CFLAGS="$CFLAGS -shared-intel" + elif test "$compiler_num" -ge "900"; then + dnl icc 9.X specific + CFLAGS="$CFLAGS -i-dynamic" + fi + # +fi + +CURL_CFLAG_EXTRAS="" +if test X"$want_werror" = Xyes; then + CURL_CFLAG_EXTRAS="-Werror" + if test "$compiler_id" = "GNU_C"; then + dnl enable -pedantic-errors for GCC 5 and later, + dnl as before that it was the same as -Werror=pedantic + if test "$compiler_num" -ge "500"; then + CURL_CFLAG_EXTRAS="$CURL_CFLAG_EXTRAS -pedantic-errors" + fi + fi +fi +AC_SUBST(CURL_CFLAG_EXTRAS) + +CURL_CHECK_COMPILER_HALT_ON_ERROR +CURL_CHECK_COMPILER_ARRAY_SIZE_NEGATIVE +CURL_CHECK_COMPILER_PROTOTYPE_MISMATCH +CURL_CHECK_COMPILER_SYMBOL_HIDING + +CURL_CHECK_CURLDEBUG +AM_CONDITIONAL(CURLDEBUG, test x$want_curldebug = xyes) + +supports_unittests=yes +# cross-compilation of unit tests static library/programs fails when +# libcurl shared library is built. This might be due to a libtool or +# automake issue. In this case we disable unit tests. +if test "x$cross_compiling" != "xno" && + test "x$enable_shared" != "xno"; then + supports_unittests=no +fi + +# IRIX 6.5.24 gcc 3.3 autobuilds fail unittests library compilation due to +# a problem related with OpenSSL headers and library versions not matching. +# Disable unit tests while time to further investigate this is found. +case $host in + mips-sgi-irix6.5) + if test "$compiler_id" = "GNU_C"; then + supports_unittests=no + fi + ;; +esac + +# All AIX autobuilds fails unit tests linking against unittests library +# due to unittests library being built with no symbols or members. Libtool ? +# Disable unit tests while time to further investigate this is found. +case $host_os in + aix*) + supports_unittests=no + ;; +esac + +dnl Build unit tests when option --enable-debug is given. +if test "x$want_debug" = "xyes" && + test "x$supports_unittests" = "xyes"; then + want_unittests=yes +else + want_unittests=no +fi +AM_CONDITIONAL(BUILD_UNITTESTS, test x$want_unittests = xyes) + +dnl ********************************************************************** +dnl Compilation based checks should not be done before this point. +dnl ********************************************************************** + +CURL_CHECK_WIN32_LARGEFILE +CURL_CHECK_WIN32_CRYPTO + +CURL_DARWIN_CFLAGS +CURL_DARWIN_SYSTEMCONFIGURATION +CURL_SUPPORTS_BUILTIN_AVAILABLE + +AM_CONDITIONAL([HAVE_WINDRES], + [test "$curl_cv_native_windows" = "yes" && test -n "${RC}"]) + +if test "$curl_cv_native_windows" = "yes"; then + AM_COND_IF([HAVE_WINDRES],, + [AC_MSG_ERROR([windres not found in PATH. Windows builds require windres. Cannot continue.])]) +fi + +dnl ************************************************************ +dnl switch off particular protocols +dnl +AC_MSG_CHECKING([whether to support http]) +AC_ARG_ENABLE(http, +AS_HELP_STRING([--enable-http],[Enable HTTP support]) +AS_HELP_STRING([--disable-http],[Disable HTTP support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_HTTP, 1, [to disable HTTP]) + disable_http="yes" + AC_MSG_WARN([disable HTTP disables FTP over proxy and RTSP]) + AC_SUBST(CURL_DISABLE_HTTP, [1]) + AC_DEFINE(CURL_DISABLE_RTSP, 1, [to disable RTSP]) + AC_SUBST(CURL_DISABLE_RTSP, [1]) + dnl toggle off alt-svc too when HTTP is disabled + AC_DEFINE(CURL_DISABLE_ALTSVC, 1, [disable alt-svc]) + AC_DEFINE(CURL_DISABLE_HSTS, 1, [disable HSTS]) + curl_h1_msg="no (--enable-http, --with-hyper)" + curl_altsvc_msg="no"; + curl_hsts_msg="no (--enable-hsts)"; + enable_altsvc="no" + hsts="no" + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) +AC_MSG_CHECKING([whether to support ftp]) +AC_ARG_ENABLE(ftp, +AS_HELP_STRING([--enable-ftp],[Enable FTP support]) +AS_HELP_STRING([--disable-ftp],[Disable FTP support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_FTP, 1, [to disable FTP]) + AC_SUBST(CURL_DISABLE_FTP, [1]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) +AC_MSG_CHECKING([whether to support file]) +AC_ARG_ENABLE(file, +AS_HELP_STRING([--enable-file],[Enable FILE support]) +AS_HELP_STRING([--disable-file],[Disable FILE support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_FILE, 1, [to disable FILE]) + AC_SUBST(CURL_DISABLE_FILE, [1]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) +AC_MSG_CHECKING([whether to support ldap]) +AC_ARG_ENABLE(ldap, +AS_HELP_STRING([--enable-ldap],[Enable LDAP support]) +AS_HELP_STRING([--disable-ldap],[Disable LDAP support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_LDAP, 1, [to disable LDAP]) + AC_SUBST(CURL_DISABLE_LDAP, [1]) + ;; + yes) + ldap_askedfor="yes" + AC_MSG_RESULT(yes) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ],[ + AC_MSG_RESULT(yes) ] +) +AC_MSG_CHECKING([whether to support ldaps]) +AC_ARG_ENABLE(ldaps, +AS_HELP_STRING([--enable-ldaps],[Enable LDAPS support]) +AS_HELP_STRING([--disable-ldaps],[Disable LDAPS support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_LDAPS, 1, [to disable LDAPS]) + AC_SUBST(CURL_DISABLE_LDAPS, [1]) + ;; + *) if test "x$CURL_DISABLE_LDAP" = "x1" ; then + AC_MSG_RESULT(LDAP needs to be enabled to support LDAPS) + AC_DEFINE(CURL_DISABLE_LDAPS, 1, [to disable LDAPS]) + AC_SUBST(CURL_DISABLE_LDAPS, [1]) + else + AC_MSG_RESULT(yes) + AC_DEFINE(HAVE_LDAP_SSL, 1, [Use LDAPS implementation]) + AC_SUBST(HAVE_LDAP_SSL, [1]) + fi + ;; + esac ],[ + if test "x$CURL_DISABLE_LDAP" = "x1" ; then + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_LDAPS, 1, [to disable LDAPS]) + AC_SUBST(CURL_DISABLE_LDAPS, [1]) + else + AC_MSG_RESULT(yes) + AC_DEFINE(HAVE_LDAP_SSL, 1, [Use LDAPS implementation]) + AC_SUBST(HAVE_LDAP_SSL, [1]) + fi ] +) + +dnl ********************************************************************** +dnl Check for Hyper +dnl ********************************************************************** + +OPT_HYPER="no" + +AC_ARG_WITH(hyper, +AS_HELP_STRING([--with-hyper=PATH],[Enable hyper usage]) +AS_HELP_STRING([--without-hyper],[Disable hyper usage]), + [OPT_HYPER=$withval]) +case "$OPT_HYPER" in + no) + dnl --without-hyper option used + want_hyper="no" + ;; + yes) + dnl --with-hyper option used without path + want_hyper="default" + want_hyper_path="" + ;; + *) + dnl --with-hyper option used with path + want_hyper="yes" + want_hyper_path="$withval" + ;; +esac + +if test X"$want_hyper" != Xno; then + if test "x$disable_http" = "xyes"; then + AC_MSG_ERROR([--with-hyper is not compatible with --disable-http]) + fi + + dnl backup the pre-hyper variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(hyper, $want_hyper_path) + + if test "$PKGCONFIG" != "no" ; then + LIB_HYPER=`CURL_EXPORT_PCDIR([$want_hyper_path]) + $PKGCONFIG --libs-only-l hyper` + CPP_HYPER=`CURL_EXPORT_PCDIR([$want_hyper_path]) dnl + $PKGCONFIG --cflags-only-I hyper` + LD_HYPER=`CURL_EXPORT_PCDIR([$want_hyper_path]) + $PKGCONFIG --libs-only-L hyper` + else + dnl no hyper pkg-config found + LIB_HYPER="-lhyper -ldl -lpthread -lm" + if test X"$want_hyper" != Xdefault; then + CPP_HYPER=-I"$want_hyper_path/capi/include" + LD_HYPER="-L$want_hyper_path/target/release -L$want_hyper_path/target/debug" + fi + fi + if test -n "$LIB_HYPER"; then + AC_MSG_NOTICE([-l is $LIB_HYPER]) + AC_MSG_NOTICE([-I is $CPP_HYPER]) + AC_MSG_NOTICE([-L is $LD_HYPER]) + + LDFLAGS="$LDFLAGS $LD_HYPER" + CPPFLAGS="$CPPFLAGS $CPP_HYPER" + LIBS="$LIB_HYPER $LIBS" + + if test "x$cross_compiling" != "xyes"; then + dnl remove -L, separate with colon if more than one + DIR_HYPER=`echo $LD_HYPER | $SED -e 's/^-L//' -e 's/ -L/:/g'` + fi + + AC_CHECK_LIB(hyper, hyper_io_new, + [ + AC_CHECK_HEADERS(hyper.h, + experimental="$experimental Hyper" + AC_MSG_NOTICE([Hyper support is experimental]) + curl_h1_msg="enabled (Hyper)" + HYPER_ENABLED=1 + AC_DEFINE(USE_HYPER, 1, [if hyper is in use]) + AC_SUBST(USE_HYPER, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_HYPER" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_HYPER to CURL_LIBRARY_PATH]), + ) + ], + for d in `echo $DIR_HYPER | $SED -e 's/:/ /'`; do + if test -f "$d/libhyper.a"; then + AC_MSG_ERROR([hyper was found in $d but was probably built with wrong flags. See docs/HYPER.md.]) + fi + done + AC_MSG_ERROR([--with-hyper but hyper was not found. See docs/HYPER.md.]) + ) + fi +fi + +if test X"$want_hyper" != Xno; then + AC_MSG_NOTICE([Disable RTSP support with hyper]) + AC_DEFINE(CURL_DISABLE_RTSP, 1, [to disable RTSP]) + AC_SUBST(CURL_DISABLE_RTSP, [1]) +else + AC_MSG_CHECKING([whether to support rtsp]) + AC_ARG_ENABLE(rtsp, +AS_HELP_STRING([--enable-rtsp],[Enable RTSP support]) +AS_HELP_STRING([--disable-rtsp],[Disable RTSP support]), + [ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_RTSP, 1, [to disable RTSP]) + AC_SUBST(CURL_DISABLE_RTSP, [1]) + ;; + *) + if test x$CURL_DISABLE_HTTP = x1 ; then + AC_MSG_ERROR(HTTP support needs to be enabled in order to enable RTSP support!) + else + AC_MSG_RESULT(yes) + curl_rtsp_msg="enabled" + fi + ;; + esac ], + if test "x$CURL_DISABLE_HTTP" != "x1"; then + AC_MSG_RESULT(yes) + curl_rtsp_msg="enabled" + else + AC_MSG_RESULT(no) + fi + ) +fi + +AC_MSG_CHECKING([whether to support proxies]) +AC_ARG_ENABLE(proxy, +AS_HELP_STRING([--enable-proxy],[Enable proxy support]) +AS_HELP_STRING([--disable-proxy],[Disable proxy support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_PROXY, 1, [to disable proxies]) + AC_SUBST(CURL_DISABLE_PROXY, [1]) + https_proxy="no" + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +AC_MSG_CHECKING([whether to support dict]) +AC_ARG_ENABLE(dict, +AS_HELP_STRING([--enable-dict],[Enable DICT support]) +AS_HELP_STRING([--disable-dict],[Disable DICT support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_DICT, 1, [to disable DICT]) + AC_SUBST(CURL_DISABLE_DICT, [1]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) +AC_MSG_CHECKING([whether to support telnet]) +AC_ARG_ENABLE(telnet, +AS_HELP_STRING([--enable-telnet],[Enable TELNET support]) +AS_HELP_STRING([--disable-telnet],[Disable TELNET support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_TELNET, 1, [to disable TELNET]) + AC_SUBST(CURL_DISABLE_TELNET, [1]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) +AC_MSG_CHECKING([whether to support tftp]) +AC_ARG_ENABLE(tftp, +AS_HELP_STRING([--enable-tftp],[Enable TFTP support]) +AS_HELP_STRING([--disable-tftp],[Disable TFTP support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_TFTP, 1, [to disable TFTP]) + AC_SUBST(CURL_DISABLE_TFTP, [1]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +AC_MSG_CHECKING([whether to support pop3]) +AC_ARG_ENABLE(pop3, +AS_HELP_STRING([--enable-pop3],[Enable POP3 support]) +AS_HELP_STRING([--disable-pop3],[Disable POP3 support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_POP3, 1, [to disable POP3]) + AC_SUBST(CURL_DISABLE_POP3, [1]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + + +AC_MSG_CHECKING([whether to support imap]) +AC_ARG_ENABLE(imap, +AS_HELP_STRING([--enable-imap],[Enable IMAP support]) +AS_HELP_STRING([--disable-imap],[Disable IMAP support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_IMAP, 1, [to disable IMAP]) + AC_SUBST(CURL_DISABLE_IMAP, [1]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + + +AC_MSG_CHECKING([whether to support smb]) +AC_ARG_ENABLE(smb, +AS_HELP_STRING([--enable-smb],[Enable SMB/CIFS support]) +AS_HELP_STRING([--disable-smb],[Disable SMB/CIFS support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_SMB, 1, [to disable SMB/CIFS]) + AC_SUBST(CURL_DISABLE_SMB, [1]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +AC_MSG_CHECKING([whether to support smtp]) +AC_ARG_ENABLE(smtp, +AS_HELP_STRING([--enable-smtp],[Enable SMTP support]) +AS_HELP_STRING([--disable-smtp],[Disable SMTP support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_SMTP, 1, [to disable SMTP]) + AC_SUBST(CURL_DISABLE_SMTP, [1]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +AC_MSG_CHECKING([whether to support gopher]) +AC_ARG_ENABLE(gopher, +AS_HELP_STRING([--enable-gopher],[Enable Gopher support]) +AS_HELP_STRING([--disable-gopher],[Disable Gopher support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_GOPHER, 1, [to disable Gopher]) + AC_SUBST(CURL_DISABLE_GOPHER, [1]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +AC_MSG_CHECKING([whether to support mqtt]) +AC_ARG_ENABLE(mqtt, +AS_HELP_STRING([--enable-mqtt],[Enable MQTT support]) +AS_HELP_STRING([--disable-mqtt],[Disable MQTT support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_MQTT, 1, [to disable MQTT]) + AC_SUBST(CURL_DISABLE_MQTT, [1]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(no) +) + +dnl ********************************************************************** +dnl Check for built-in manual +dnl ********************************************************************** + +AC_MSG_CHECKING([whether to provide built-in manual]) +AC_ARG_ENABLE(manual, +AS_HELP_STRING([--enable-manual],[Enable built-in manual]) +AS_HELP_STRING([--disable-manual],[Disable built-in manual]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + ;; + *) AC_MSG_RESULT(yes) + USE_MANUAL="1" + ;; + esac ], + AC_MSG_RESULT(yes) + USE_MANUAL="1" +) +dnl The actual use of the USE_MANUAL variable is done much later in this +dnl script to allow other actions to disable it as well. + +dnl ********************************************************************** +dnl Check whether to build documentation +dnl ********************************************************************** + +AC_MSG_CHECKING([whether to build documentation]) +AC_ARG_ENABLE(docs, +AS_HELP_STRING([--enable-docs],[Enable documentation]) +AS_HELP_STRING([--disable-docs],[Disable documentation]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + BUILD_DOCS=0 + dnl disable manual too because it needs built documentation + USE_MANUAL=0 + curl_docs_msg="no" + ;; + *) AC_MSG_RESULT(yes) + BUILD_DOCS=1 + ;; + esac ], + AC_MSG_RESULT(yes) + BUILD_DOCS=1 +) + + +dnl ************************************************************ +dnl disable C code generation support +dnl +AC_MSG_CHECKING([whether to enable generation of C code]) +AC_ARG_ENABLE(libcurl_option, +AS_HELP_STRING([--enable-libcurl-option],[Enable --libcurl C code generation support]) +AS_HELP_STRING([--disable-libcurl-option],[Disable --libcurl C code generation support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_LIBCURL_OPTION, 1, [to disable --libcurl C code generation option]) + curl_libcurl_msg="no" + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ********************************************************************** +dnl Checks for libraries. +dnl ********************************************************************** + +AC_MSG_CHECKING([whether to use libgcc]) +AC_ARG_ENABLE(libgcc, +AS_HELP_STRING([--enable-libgcc],[use libgcc when linking]), +[ case "$enableval" in + yes) + LIBS="-lgcc $LIBS" + AC_MSG_RESULT(yes) + ;; + *) AC_MSG_RESULT(no) + ;; + esac ], + AC_MSG_RESULT(no) +) + +CURL_CHECK_LIB_XNET + +dnl gethostbyname without lib or in the nsl lib? +AC_CHECK_FUNC(gethostbyname, + [HAVE_GETHOSTBYNAME="1" + ], + [ AC_CHECK_LIB(nsl, gethostbyname, + [HAVE_GETHOSTBYNAME="1" + LIBS="-lnsl $LIBS" + ]) + ]) + +if test "$HAVE_GETHOSTBYNAME" != "1" +then + dnl gethostbyname in the socket lib? + AC_CHECK_LIB(socket, gethostbyname, + [HAVE_GETHOSTBYNAME="1" + LIBS="-lsocket $LIBS" + ]) +fi + +if test "$HAVE_GETHOSTBYNAME" != "1" +then + dnl gethostbyname in the watt lib? + AC_CHECK_LIB(watt, gethostbyname, + [HAVE_GETHOSTBYNAME="1" + CPPFLAGS="-I/dev/env/WATT_ROOT/inc" + LDFLAGS="-L/dev/env/WATT_ROOT/lib" + LIBS="-lwatt $LIBS" + ]) +fi + +dnl At least one system has been identified to require BOTH nsl and socket +dnl libs at the same time to link properly. +if test "$HAVE_GETHOSTBYNAME" != "1" +then + AC_MSG_CHECKING([for gethostbyname with both nsl and socket libs]) + my_ac_save_LIBS=$LIBS + LIBS="-lnsl -lsocket $LIBS" + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + ]],[[ + gethostbyname(); + ]]) + ],[ + AC_MSG_RESULT([yes]) + HAVE_GETHOSTBYNAME="1" + ],[ + AC_MSG_RESULT([no]) + LIBS=$my_ac_save_LIBS + ]) +fi + +if test "$HAVE_GETHOSTBYNAME" != "1" +then + dnl This is for winsock systems + if test "$curl_cv_native_windows" = "yes"; then + winsock_LIB="-lws2_32" + if test ! -z "$winsock_LIB"; then + my_ac_save_LIBS=$LIBS + LIBS="$winsock_LIB $LIBS" + AC_MSG_CHECKING([for gethostbyname in $winsock_LIB]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#endif + ]],[[ + gethostbyname("localhost"); + ]]) + ],[ + AC_MSG_RESULT([yes]) + HAVE_GETHOSTBYNAME="1" + ],[ + AC_MSG_RESULT([no]) + winsock_LIB="" + LIBS=$my_ac_save_LIBS + ]) + fi + fi +fi + +if test "$HAVE_GETHOSTBYNAME" != "1" +then + dnl This is for Minix 3.1 + AC_MSG_CHECKING([for gethostbyname for Minix 3]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ +/* Older Minix versions may need here instead */ +#include + ]],[[ + gethostbyname("localhost"); + ]]) + ],[ + AC_MSG_RESULT([yes]) + HAVE_GETHOSTBYNAME="1" + ],[ + AC_MSG_RESULT([no]) + ]) +fi + +if test "$HAVE_GETHOSTBYNAME" != "1" +then + dnl This is for eCos with a stubbed DNS implementation + AC_MSG_CHECKING([for gethostbyname for eCos]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ +#include +#include + ]],[[ + gethostbyname("localhost"); + ]]) + ],[ + AC_MSG_RESULT([yes]) + HAVE_GETHOSTBYNAME="1" + ],[ + AC_MSG_RESULT([no]) + ]) +fi + +if test "$HAVE_GETHOSTBYNAME" != "1" -o "${with_amissl+set}" = set +then + dnl This is for AmigaOS with bsdsocket.library - needs testing before -lnet + AC_MSG_CHECKING([for gethostbyname for AmigaOS bsdsocket.library]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + #define __USE_INLINE__ + #include + #ifdef __amigaos4__ + struct SocketIFace *ISocket = NULL; + #else + struct Library *SocketBase = NULL; + #endif + ]],[[ + gethostbyname("localhost"); + ]]) + ],[ + AC_MSG_RESULT([yes]) + HAVE_GETHOSTBYNAME="1" + HAVE_PROTO_BSDSOCKET_H="1" + AC_DEFINE(HAVE_PROTO_BSDSOCKET_H, 1, [if Amiga bsdsocket.library is in use]) + AC_SUBST(HAVE_PROTO_BSDSOCKET_H, [1]) + ],[ + AC_MSG_RESULT([no]) + ]) +fi + +if test "$HAVE_GETHOSTBYNAME" != "1" +then + dnl gethostbyname in the network lib - for Haiku OS + AC_CHECK_LIB(network, gethostbyname, + [HAVE_GETHOSTBYNAME="1" + LIBS="-lnetwork $LIBS" + ]) +fi + +if test "$HAVE_GETHOSTBYNAME" != "1"; then + AC_MSG_ERROR([couldn't find libraries for gethostbyname()]) +fi + +CURL_CHECK_LIBS_CONNECT + +CURL_NETWORK_LIBS=$LIBS + +dnl ********************************************************************** +dnl In case that function clock_gettime with monotonic timer is available, +dnl check for additional required libraries. +dnl ********************************************************************** +CURL_CHECK_LIBS_CLOCK_GETTIME_MONOTONIC + +dnl Check for even better option +CURL_CHECK_FUNC_CLOCK_GETTIME_MONOTONIC_RAW + +dnl ********************************************************************** +dnl The preceding library checks are all potentially useful for test +dnl servers and libtest cases which require networking and clock_gettime +dnl support. Save the list of required libraries at this point for use +dnl while linking those test servers and programs. +dnl ********************************************************************** +CURL_NETWORK_AND_TIME_LIBS=$LIBS + +dnl ********************************************************************** +dnl Check for the presence of ZLIB libraries and headers +dnl ********************************************************************** + +dnl Check for & handle argument to --with-zlib. + +clean_CPPFLAGS=$CPPFLAGS +clean_LDFLAGS=$LDFLAGS +clean_LIBS=$LIBS +ZLIB_LIBS="" +AC_ARG_WITH(zlib, +AS_HELP_STRING([--with-zlib=PATH],[search for zlib in PATH]) +AS_HELP_STRING([--without-zlib],[disable use of zlib]), + [OPT_ZLIB="$withval"]) + +if test "$OPT_ZLIB" = "no" ; then + AC_MSG_WARN([zlib disabled]) +else + if test "$OPT_ZLIB" = "yes" ; then + OPT_ZLIB="" + fi + + if test -z "$OPT_ZLIB" ; then + CURL_CHECK_PKGCONFIG(zlib) + + if test "$PKGCONFIG" != "no" ; then + ZLIB_LIBS="`$PKGCONFIG --libs-only-l zlib`" + if test -n "$ZLIB_LIBS"; then + LDFLAGS="$LDFLAGS `$PKGCONFIG --libs-only-L zlib`" + else + ZLIB_LIBS="`$PKGCONFIG --libs zlib`" + fi + LIBS="$ZLIB_LIBS $LIBS" + CPPFLAGS="$CPPFLAGS `$PKGCONFIG --cflags zlib`" + OPT_ZLIB="" + HAVE_LIBZ="1" + fi + + if test -z "$HAVE_LIBZ"; then + + dnl Check for the lib without setting any new path, since many + dnl people have it in the default path + + AC_CHECK_LIB(z, inflateEnd, + dnl libz found, set the variable + [HAVE_LIBZ="1" + ZLIB_LIBS="-lz" + LIBS="$ZLIB_LIBS $LIBS"], + dnl if no lib found, try /usr/local + [OPT_ZLIB="/usr/local"]) + fi + fi + + dnl Add a nonempty path to the compiler flags + if test -n "$OPT_ZLIB"; then + CPPFLAGS="$CPPFLAGS -I$OPT_ZLIB/include" + LDFLAGS="$LDFLAGS -L$OPT_ZLIB/lib$libsuff" + fi + + AC_CHECK_HEADER(zlib.h, + [ + dnl zlib.h was found + HAVE_ZLIB_H="1" + dnl if the lib wasn't found already, try again with the new paths + if test "$HAVE_LIBZ" != "1"; then + AC_CHECK_LIB(z, gzread, + [ + dnl the lib was found! + HAVE_LIBZ="1" + ZLIB_LIBS="-lz" + LIBS="$ZLIB_LIBS $LIBS" + ], + [ CPPFLAGS=$clean_CPPFLAGS + LDFLAGS=$clean_LDFLAGS]) + fi + ], + [ + dnl zlib.h was not found, restore the flags + CPPFLAGS=$clean_CPPFLAGS + LDFLAGS=$clean_LDFLAGS] + ) + + if test "$HAVE_LIBZ" = "1" && test "$HAVE_ZLIB_H" != "1" + then + AC_MSG_WARN([configure found only the libz lib, not the header file!]) + HAVE_LIBZ="" + CPPFLAGS=$clean_CPPFLAGS + LDFLAGS=$clean_LDFLAGS + LIBS=$clean_LIBS + ZLIB_LIBS="" + elif test "$HAVE_LIBZ" != "1" && test "$HAVE_ZLIB_H" = "1" + then + AC_MSG_WARN([configure found only the libz header file, not the lib!]) + CPPFLAGS=$clean_CPPFLAGS + LDFLAGS=$clean_LDFLAGS + LIBS=$clean_LIBS + ZLIB_LIBS="" + elif test "$HAVE_LIBZ" = "1" && test "$HAVE_ZLIB_H" = "1" + then + dnl both header and lib were found! + AC_SUBST(HAVE_LIBZ) + AC_DEFINE(HAVE_LIBZ, 1, [if zlib is available]) + LIBS="$ZLIB_LIBS $clean_LIBS" + + dnl replace 'HAVE_LIBZ' in the automake makefile.ams + AMFIXLIB="1" + AC_MSG_NOTICE([found both libz and libz.h header]) + curl_zlib_msg="enabled" + fi +fi + +dnl set variable for use in automakefile(s) +AM_CONDITIONAL(HAVE_LIBZ, test x"$AMFIXLIB" = x1) +AC_SUBST(ZLIB_LIBS) + +dnl ********************************************************************** +dnl Check for the presence of BROTLI decoder libraries and headers +dnl ********************************************************************** + +dnl Brotli project home page: https://github.com/google/brotli + +dnl Default to compiler & linker defaults for BROTLI files & libraries. +OPT_BROTLI=off +AC_ARG_WITH(brotli,dnl +AS_HELP_STRING([--with-brotli=PATH],[Where to look for brotli, PATH points to the BROTLI installation; when possible, set the PKG_CONFIG_PATH environment variable instead of using this option]) +AS_HELP_STRING([--without-brotli], [disable BROTLI]), + OPT_BROTLI=$withval) + +if test X"$OPT_BROTLI" != Xno; then + dnl backup the pre-brotli variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_BROTLI" in + yes) + dnl --with-brotli (without path) used + CURL_CHECK_PKGCONFIG(libbrotlidec) + + if test "$PKGCONFIG" != "no" ; then + LIB_BROTLI=`$PKGCONFIG --libs-only-l libbrotlidec` + LD_BROTLI=`$PKGCONFIG --libs-only-L libbrotlidec` + CPP_BROTLI=`$PKGCONFIG --cflags-only-I libbrotlidec` + version=`$PKGCONFIG --modversion libbrotlidec` + DIR_BROTLI=`echo $LD_BROTLI | $SED -e 's/^-L//'` + fi + + ;; + off) + dnl no --with-brotli option given, just check default places + ;; + *) + dnl use the given --with-brotli spot + PREFIX_BROTLI=$OPT_BROTLI + ;; + esac + + dnl if given with a prefix, we set -L and -I based on that + if test -n "$PREFIX_BROTLI"; then + LIB_BROTLI="-lbrotlidec" + LD_BROTLI=-L${PREFIX_BROTLI}/lib$libsuff + CPP_BROTLI=-I${PREFIX_BROTLI}/include + DIR_BROTLI=${PREFIX_BROTLI}/lib$libsuff + fi + + LDFLAGS="$LDFLAGS $LD_BROTLI" + CPPFLAGS="$CPPFLAGS $CPP_BROTLI" + LIBS="$LIB_BROTLI $LIBS" + + AC_CHECK_LIB(brotlidec, BrotliDecoderDecompress) + + AC_CHECK_HEADERS(brotli/decode.h, + curl_brotli_msg="enabled (libbrotlidec)" + HAVE_BROTLI=1 + AC_DEFINE(HAVE_BROTLI, 1, [if BROTLI is in use]) + AC_SUBST(HAVE_BROTLI, [1]) + ) + + if test X"$OPT_BROTLI" != Xoff && + test "$HAVE_BROTLI" != "1"; then + AC_MSG_ERROR([BROTLI libs and/or directories were not found where specified!]) + fi + + if test "$HAVE_BROTLI" = "1"; then + if test -n "$DIR_BROTLI"; then + dnl when the brotli shared libs were found in a path that the run-time + dnl linker doesn't search through, we need to add it to CURL_LIBRARY_PATH + dnl to prevent further configure tests to fail due to this + + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_BROTLI" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_BROTLI to CURL_LIBRARY_PATH]) + fi + fi + else + dnl no brotli, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + fi +fi + +dnl ********************************************************************** +dnl Check for libzstd +dnl ********************************************************************** + +dnl Default to compiler & linker defaults for libzstd +OPT_ZSTD=off +AC_ARG_WITH(zstd,dnl +AS_HELP_STRING([--with-zstd=PATH],[Where to look for libzstd, PATH points to the libzstd installation; when possible, set the PKG_CONFIG_PATH environment variable instead of using this option]) +AS_HELP_STRING([--without-zstd], [disable libzstd]), + OPT_ZSTD=$withval) + +if test X"$OPT_ZSTD" != Xno; then + dnl backup the pre-zstd variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_ZSTD" in + yes) + dnl --with-zstd (without path) used + CURL_CHECK_PKGCONFIG(libzstd) + + if test "$PKGCONFIG" != "no" ; then + LIB_ZSTD=`$PKGCONFIG --libs-only-l libzstd` + LD_ZSTD=`$PKGCONFIG --libs-only-L libzstd` + CPP_ZSTD=`$PKGCONFIG --cflags-only-I libzstd` + version=`$PKGCONFIG --modversion libzstd` + DIR_ZSTD=`echo $LD_ZSTD | $SED -e 's/-L//'` + fi + + ;; + off) + dnl no --with-zstd option given, just check default places + ;; + *) + dnl use the given --with-zstd spot + PREFIX_ZSTD=$OPT_ZSTD + ;; + esac + + dnl if given with a prefix, we set -L and -I based on that + if test -n "$PREFIX_ZSTD"; then + LIB_ZSTD="-lzstd" + LD_ZSTD=-L${PREFIX_ZSTD}/lib$libsuff + CPP_ZSTD=-I${PREFIX_ZSTD}/include + DIR_ZSTD=${PREFIX_ZSTD}/lib$libsuff + fi + + LDFLAGS="$LDFLAGS $LD_ZSTD" + CPPFLAGS="$CPPFLAGS $CPP_ZSTD" + LIBS="$LIB_ZSTD $LIBS" + + AC_CHECK_LIB(zstd, ZSTD_createDStream) + + AC_CHECK_HEADERS(zstd.h, + curl_zstd_msg="enabled (libzstd)" + HAVE_ZSTD=1 + AC_DEFINE(HAVE_ZSTD, 1, [if libzstd is in use]) + AC_SUBST(HAVE_ZSTD, [1]) + ) + + if test X"$OPT_ZSTD" != Xoff && + test "$HAVE_ZSTD" != "1"; then + AC_MSG_ERROR([libzstd was not found where specified!]) + fi + + if test "$HAVE_ZSTD" = "1"; then + if test -n "$DIR_ZSTD"; then + dnl when the zstd shared lib were found in a path that the run-time + dnl linker doesn't search through, we need to add it to + dnl CURL_LIBRARY_PATH to prevent further configure tests to fail due to + dnl this + + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_ZSTD" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_ZSTD to CURL_LIBRARY_PATH]) + fi + fi + else + dnl no zstd, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + fi +fi + +dnl ********************************************************************** +dnl Check for LDAP +dnl ********************************************************************** + +LDAPLIBNAME="" +AC_ARG_WITH(ldap-lib, +AS_HELP_STRING([--with-ldap-lib=libname],[Specify name of ldap lib file]), + [LDAPLIBNAME="$withval"]) + +LBERLIBNAME="" +AC_ARG_WITH(lber-lib, +AS_HELP_STRING([--with-lber-lib=libname],[Specify name of lber lib file]), + [LBERLIBNAME="$withval"]) + +if test x$CURL_DISABLE_LDAP != x1 ; then + + CURL_CHECK_HEADER_LBER + CURL_CHECK_HEADER_LDAP + CURL_CHECK_HEADER_LDAP_SSL + + if test -z "$LDAPLIBNAME" ; then + if test "$curl_cv_native_windows" = "yes"; then + dnl Windows uses a single and unique LDAP library name + LDAPLIBNAME="wldap32" + LBERLIBNAME="no" + fi + fi + + if test "$LDAPLIBNAME" ; then + AC_CHECK_LIB("$LDAPLIBNAME", ldap_init,, [ + if test -n "$ldap_askedfor"; then + AC_MSG_ERROR([couldn't detect the LDAP libraries]) + fi + AC_MSG_WARN(["$LDAPLIBNAME" is not an LDAP library: LDAP disabled]) + AC_DEFINE(CURL_DISABLE_LDAP, 1, [to disable LDAP]) + AC_SUBST(CURL_DISABLE_LDAP, [1]) + AC_DEFINE(CURL_DISABLE_LDAPS, 1, [to disable LDAPS]) + AC_SUBST(CURL_DISABLE_LDAPS, [1])]) + else + dnl Try to find the right ldap libraries for this system + CURL_CHECK_LIBS_LDAP + case X-"$curl_cv_ldap_LIBS" in + X-unknown) + if test -n "$ldap_askedfor"; then + AC_MSG_ERROR([couldn't detect the LDAP libraries]) + fi + AC_MSG_WARN([Cannot find libraries for LDAP support: LDAP disabled]) + AC_DEFINE(CURL_DISABLE_LDAP, 1, [to disable LDAP]) + AC_SUBST(CURL_DISABLE_LDAP, [1]) + AC_DEFINE(CURL_DISABLE_LDAPS, 1, [to disable LDAPS]) + AC_SUBST(CURL_DISABLE_LDAPS, [1]) + ;; + esac + fi +fi + +if test x$CURL_DISABLE_LDAP != x1 ; then + + if test "$LBERLIBNAME" ; then + dnl If name is "no" then don't define this library at all + dnl (it's only needed if libldap.so's dependencies are broken). + if test "$LBERLIBNAME" != "no" ; then + AC_CHECK_LIB("$LBERLIBNAME", ber_free,, [ + AC_MSG_WARN(["$LBERLIBNAME" is not an LBER library: LDAP disabled]) + AC_DEFINE(CURL_DISABLE_LDAP, 1, [to disable LDAP]) + AC_SUBST(CURL_DISABLE_LDAP, [1]) + AC_DEFINE(CURL_DISABLE_LDAPS, 1, [to disable LDAPS]) + AC_SUBST(CURL_DISABLE_LDAPS, [1])]) + fi + fi +fi + +if test x$CURL_DISABLE_LDAP != x1 ; then + AC_CHECK_FUNCS([ldap_url_parse \ + ldap_init_fd]) + + if test "$LDAPLIBNAME" = "wldap32"; then + curl_ldap_msg="enabled (winldap)" + AC_DEFINE(USE_WIN32_LDAP, 1, [Use Windows LDAP implementation]) + else + if test "x$ac_cv_func_ldap_init_fd" = "xyes"; then + curl_ldap_msg="enabled (OpenLDAP)" + AC_DEFINE(USE_OPENLDAP, 1, [Use OpenLDAP-specific code]) + AC_SUBST(USE_OPENLDAP, [1]) + else + curl_ldap_msg="enabled (ancient OpenLDAP)" + fi + fi +fi + +if test x$CURL_DISABLE_LDAPS != x1 ; then + curl_ldaps_msg="enabled" +fi + +dnl ********************************************************************** +dnl Checks for IPv6 +dnl ********************************************************************** + +AC_MSG_CHECKING([whether to enable IPv6]) +AC_ARG_ENABLE(ipv6, +AS_HELP_STRING([--enable-ipv6],[Enable IPv6 (with IPv4) support]) +AS_HELP_STRING([--disable-ipv6],[Disable IPv6 support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + ipv6=no + ;; + *) AC_MSG_RESULT(yes) + ipv6=yes + ;; + esac ], + + AC_RUN_IFELSE([AC_LANG_SOURCE([[ +/* are AF_INET6 and sockaddr_in6 available? */ +#include +#ifdef _WIN32 +#include +#include +#else +#include +#include +#if defined (__TANDEM) +# include +#endif +#endif + +int main(void) +{ + struct sockaddr_in6 s; + (void)s; + return socket(AF_INET6, SOCK_STREAM, 0) < 0; +} +]]) +], + AC_MSG_RESULT(yes) + ipv6=yes, + AC_MSG_RESULT(no) + ipv6=no, + AC_MSG_RESULT(yes) + ipv6=yes +)) + +if test "$ipv6" = yes; then + curl_ipv6_msg="enabled" + AC_DEFINE(USE_IPV6, 1, [Define if you want to enable IPv6 support]) + IPV6_ENABLED=1 + AC_SUBST(IPV6_ENABLED) + + AC_MSG_CHECKING([if struct sockaddr_in6 has sin6_scope_id member]) + AC_COMPILE_IFELSE([ AC_LANG_PROGRAM([[ +#include +#ifdef _WIN32 +#include +#include +#else +#include +#if defined (__TANDEM) +# include +#endif +#endif +]], [[ + struct sockaddr_in6 s; + s.sin6_scope_id = 0; +]])], [ + AC_MSG_RESULT([yes]) + AC_DEFINE(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID, 1, [Define to 1 if struct sockaddr_in6 has the sin6_scope_id member]) + ], [ + AC_MSG_RESULT([no]) + ]) +fi + +dnl ********************************************************************** +dnl Check if the operating system allows programs to write to their own argv[] +dnl ********************************************************************** + +AC_MSG_CHECKING([if argv can be written to]) +CURL_RUN_IFELSE([[ +int main(int argc, char **argv) +{ +#ifdef _WIN32 + /* on Windows, writing to the argv does not hide the argument in + process lists so it can just be skipped */ + (void)argc; + (void)argv; + return 1; +#else + (void)argc; + argv[0][0] = ' '; + return (argv[0][0] == ' ')?0:1; +#endif +} +]],[ + curl_cv_writable_argv=yes +],[ + curl_cv_writable_argv=no +],[ + curl_cv_writable_argv=cross +]) +case $curl_cv_writable_argv in +yes) + AC_DEFINE(HAVE_WRITABLE_ARGV, 1, [Define this symbol if your OS supports changing the contents of argv]) + AC_MSG_RESULT(yes) + ;; +no) + AC_MSG_RESULT(no) + ;; +*) + AC_MSG_RESULT(no) + AC_MSG_WARN([the previous check could not be made default was used]) + ;; +esac + +dnl ********************************************************************** +dnl Check for GSS-API libraries +dnl ********************************************************************** + +dnl check for GSS-API stuff in the /usr as default + +GSSAPI_ROOT="/usr" +AC_ARG_WITH(gssapi-includes, + AS_HELP_STRING([--with-gssapi-includes=DIR], + [Specify location of GSS-API headers]), + [ GSSAPI_INCS="-I$withval" + want_gss="yes" ] +) + +AC_ARG_WITH(gssapi-libs, + AS_HELP_STRING([--with-gssapi-libs=DIR], + [Specify location of GSS-API libs]), + [ GSSAPI_LIB_DIR="-L$withval" + want_gss="yes" ] +) + +AC_ARG_WITH(gssapi, + AS_HELP_STRING([--with-gssapi=DIR], + [Where to look for GSS-API]), [ + GSSAPI_ROOT="$withval" + if test x"$GSSAPI_ROOT" != xno; then + want_gss="yes" + if test x"$GSSAPI_ROOT" = xyes; then + dnl if yes, then use default root + GSSAPI_ROOT="/usr" + fi + fi +]) + +: ${KRB5CONFIG:="$GSSAPI_ROOT/bin/krb5-config"} + +save_CPPFLAGS="$CPPFLAGS" +AC_MSG_CHECKING([if GSS-API support is requested]) +if test x"$want_gss" = xyes; then + AC_MSG_RESULT(yes) + + if test $GSSAPI_ROOT != "/usr"; then + CURL_CHECK_PKGCONFIG(mit-krb5-gssapi, $GSSAPI_ROOT/lib/pkgconfig) + else + CURL_CHECK_PKGCONFIG(mit-krb5-gssapi) + fi + if test -z "$GSSAPI_INCS"; then + if test -n "$host_alias" -a -f "$GSSAPI_ROOT/bin/$host_alias-krb5-config"; then + GSSAPI_INCS=`$GSSAPI_ROOT/bin/$host_alias-krb5-config --cflags gssapi` + elif test "$PKGCONFIG" != "no" ; then + GSSAPI_INCS=`$PKGCONFIG --cflags mit-krb5-gssapi` + elif test -f "$KRB5CONFIG"; then + GSSAPI_INCS=`$KRB5CONFIG --cflags gssapi` + elif test "$GSSAPI_ROOT" != "yes"; then + GSSAPI_INCS="-I$GSSAPI_ROOT/include" + fi + fi + + CPPFLAGS="$CPPFLAGS $GSSAPI_INCS" + + AC_CHECK_HEADER(gss.h, + [ + dnl found in the given dirs + AC_DEFINE(HAVE_GSSGNU, 1, [if you have GNU GSS]) + gnu_gss=yes + ], + [ + dnl not found, check Heimdal or MIT + AC_CHECK_HEADERS([gssapi/gssapi.h], [], [not_mit=1]) + AC_CHECK_HEADERS( + [gssapi/gssapi_generic.h gssapi/gssapi_krb5.h], + [], + [not_mit=1], + [ +AC_INCLUDES_DEFAULT +#ifdef HAVE_GSSAPI_GSSAPI_H +#include +#endif + ]) + if test "x$not_mit" = "x1"; then + dnl MIT not found, check for Heimdal + AC_CHECK_HEADER(gssapi.h, + [], + [ + dnl no header found, disabling GSS + want_gss=no + AC_MSG_WARN(disabling GSS-API support since no header files were found) + ] + ) + else + dnl MIT found + dnl check if we have a really old MIT Kerberos version (<= 1.2) + AC_MSG_CHECKING([if GSS-API headers declare GSS_C_NT_HOSTBASED_SERVICE]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#include +#include +#include + ]],[[ + gss_import_name( + (OM_uint32 *)0, + (gss_buffer_t)0, + GSS_C_NT_HOSTBASED_SERVICE, + (gss_name_t *)0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + ],[ + AC_MSG_RESULT([no]) + AC_DEFINE(HAVE_OLD_GSSMIT, 1, + [if you have an old MIT Kerberos version, lacking GSS_C_NT_HOSTBASED_SERVICE]) + ]) + fi + ] + ) +else + AC_MSG_RESULT(no) +fi +if test x"$want_gss" = xyes; then + AC_DEFINE(HAVE_GSSAPI, 1, [if you have GSS-API libraries]) + HAVE_GSSAPI=1 + curl_gss_msg="enabled (MIT Kerberos/Heimdal)" + + if test -n "$gnu_gss"; then + curl_gss_msg="enabled (GNU GSS)" + LDFLAGS="$LDFLAGS $GSSAPI_LIB_DIR" + LIBS="-lgss $LIBS" + elif test -z "$GSSAPI_LIB_DIR"; then + case $host in + *-*-darwin*) + LIBS="-lgssapi_krb5 -lresolv $LIBS" + ;; + *) + if test $GSSAPI_ROOT != "/usr"; then + CURL_CHECK_PKGCONFIG(mit-krb5-gssapi, $GSSAPI_ROOT/lib/pkgconfig) + else + CURL_CHECK_PKGCONFIG(mit-krb5-gssapi) + fi + if test -n "$host_alias" -a -f "$GSSAPI_ROOT/bin/$host_alias-krb5-config"; then + dnl krb5-config doesn't have --libs-only-L or similar, put everything + dnl into LIBS + gss_libs=`$GSSAPI_ROOT/bin/$host_alias-krb5-config --libs gssapi` + LIBS="$gss_libs $LIBS" + elif test "$PKGCONFIG" != "no" ; then + gss_libs=`$PKGCONFIG --libs mit-krb5-gssapi` + LIBS="$gss_libs $LIBS" + elif test -f "$KRB5CONFIG"; then + dnl krb5-config doesn't have --libs-only-L or similar, put everything + dnl into LIBS + gss_libs=`$KRB5CONFIG --libs gssapi` + LIBS="$gss_libs $LIBS" + else + case $host in + *-hp-hpux*) + gss_libname="gss" + ;; + *) + gss_libname="gssapi" + ;; + esac + + if test "$GSSAPI_ROOT" != "yes"; then + LDFLAGS="$LDFLAGS -L$GSSAPI_ROOT/lib$libsuff" + LIBS="-l$gss_libname $LIBS" + else + LIBS="-l$gss_libname $LIBS" + fi + fi + ;; + esac + else + LDFLAGS="$LDFLAGS $GSSAPI_LIB_DIR" + case $host in + *-hp-hpux*) + LIBS="-lgss $LIBS" + ;; + *) + LIBS="-lgssapi $LIBS" + ;; + esac + fi +else + CPPFLAGS="$save_CPPFLAGS" +fi + +if test x"$want_gss" = xyes; then + AC_MSG_CHECKING([if we can link against GSS-API library]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([gss_init_sec_context]) + ],[ + AC_MSG_RESULT([yes]) + ],[ + AC_MSG_RESULT([no]) + AC_MSG_ERROR([--with-gssapi was specified, but a GSS-API library was not found.]) + ]) +fi + +build_libstubgss=no +if test x"$want_gss" = "xyes"; then + build_libstubgss=yes +fi + +AM_CONDITIONAL(BUILD_STUB_GSS, test "x$build_libstubgss" = "xyes") + +dnl ------------------------------------------------------------- +dnl parse --with-default-ssl-backend so it can be validated below +dnl ------------------------------------------------------------- + +DEFAULT_SSL_BACKEND=no +VALID_DEFAULT_SSL_BACKEND= +AC_ARG_WITH(default-ssl-backend, +AS_HELP_STRING([--with-default-ssl-backend=NAME],[Use NAME as default SSL backend]) +AS_HELP_STRING([--without-default-ssl-backend],[Use implicit default SSL backend]), + [DEFAULT_SSL_BACKEND=$withval]) +case "$DEFAULT_SSL_BACKEND" in + no) + dnl --without-default-ssl-backend option used + ;; + default|yes) + dnl --with-default-ssl-backend option used without name + AC_MSG_ERROR([The name of the default SSL backend is required.]) + ;; + *) + dnl --with-default-ssl-backend option used with name + AC_SUBST(DEFAULT_SSL_BACKEND) + dnl needs to be validated below + VALID_DEFAULT_SSL_BACKEND=no + ;; +esac + +CURL_WITH_SCHANNEL +CURL_WITH_SECURETRANSPORT +CURL_WITH_AMISSL +CURL_WITH_OPENSSL +CURL_WITH_GNUTLS +CURL_WITH_MBEDTLS +CURL_WITH_WOLFSSL +CURL_WITH_BEARSSL +CURL_WITH_RUSTLS + +dnl link required libraries for USE_WIN32_CRYPTO or USE_SCHANNEL +if test "x$USE_WIN32_CRYPTO" = "x1" -o "x$USE_SCHANNEL" = "x1"; then + LIBS="-ladvapi32 -lcrypt32 $LIBS" +fi + +dnl link bcrypt for BCryptGenRandom() (used when building for Vista or newer) +if test "x$curl_cv_native_windows" = "xyes"; then + LIBS="-lbcrypt $LIBS" +fi + +case "x$SSL_DISABLED$OPENSSL_ENABLED$GNUTLS_ENABLED$MBEDTLS_ENABLED$WOLFSSL_ENABLED$SCHANNEL_ENABLED$SECURETRANSPORT_ENABLED$BEARSSL_ENABLED$RUSTLS_ENABLED" +in +x) + AC_MSG_ERROR([TLS not detected, you will not be able to use HTTPS, FTPS, NTLM and more. +Use --with-openssl, --with-gnutls, --with-wolfssl, --with-mbedtls, --with-schannel, --with-secure-transport, --with-amissl, --with-bearssl or --with-rustls to address this.]) + ;; +x1) + # one SSL backend is enabled + AC_SUBST(SSL_ENABLED) + SSL_ENABLED="1" + AC_MSG_NOTICE([built with one SSL backend]) + ;; +xD) + # explicitly built without TLS + ;; +xD*) + AC_MSG_ERROR([--without-ssl has been set together with an explicit option to use an ssl library +(e.g. --with-openssl, --with-gnutls, --with-wolfssl, --with-mbedtls, --with-schannel, --with-secure-transport, --with-amissl, --with-bearssl, --with-rustls). +Since these are conflicting parameters, verify which is the desired one and drop the other.]) + ;; +*) + # more than one SSL backend is enabled + AC_SUBST(SSL_ENABLED) + SSL_ENABLED="1" + AC_SUBST(CURL_WITH_MULTI_SSL) + CURL_WITH_MULTI_SSL="1" + AC_DEFINE(CURL_WITH_MULTI_SSL, 1, [built with multiple SSL backends]) + AC_MSG_NOTICE([built with multiple SSL backends]) + ;; +esac + +if test -n "$ssl_backends"; then + curl_ssl_msg="enabled ($ssl_backends)" +fi + +if test no = "$VALID_DEFAULT_SSL_BACKEND" +then + if test -n "$SSL_ENABLED" + then + AC_MSG_ERROR([Default SSL backend $DEFAULT_SSL_BACKEND not enabled!]) + else + AC_MSG_ERROR([Default SSL backend requires SSL!]) + fi +elif test yes = "$VALID_DEFAULT_SSL_BACKEND" +then + AC_DEFINE_UNQUOTED([CURL_DEFAULT_SSL_BACKEND], ["$DEFAULT_SSL_BACKEND"], [Default SSL backend]) +fi + +dnl ********************************************************************** +dnl Check for the CA bundle +dnl ********************************************************************** + +if test -n "$check_for_ca_bundle"; then + CURL_CHECK_CA_BUNDLE +fi + +dnl ********************************************************************** +dnl Check for libpsl +dnl ********************************************************************** + +dnl Default to compiler & linker defaults for LIBPSL files & libraries. +OPT_LIBPSL=off +AC_ARG_WITH(libpsl,dnl +AS_HELP_STRING([--with-libpsl=PATH],[Where to look for libpsl, PATH points to the LIBPSL installation; when possible, set the PKG_CONFIG_PATH environment variable instead of using this option]) +AS_HELP_STRING([--without-libpsl], [disable LIBPSL]), + OPT_LIBPSL=$withval) + +if test X"$OPT_LIBPSL" != Xno; then + dnl backup the pre-libpsl variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_LIBPSL" in + yes) + dnl --with-libpsl (without path) used + CURL_CHECK_PKGCONFIG(libpsl) + + if test "$PKGCONFIG" != "no" ; then + LIB_PSL=`$PKGCONFIG --libs-only-l libpsl` + LD_PSL=`$PKGCONFIG --libs-only-L libpsl` + CPP_PSL=`$PKGCONFIG --cflags-only-I libpsl` + else + dnl no libpsl pkg-config found + LIB_PSL="-lpsl" + fi + + ;; + off) + dnl no --with-libpsl option given, just check default places + LIB_PSL="-lpsl" + ;; + *) + dnl use the given --with-libpsl spot + LIB_PSL="-lpsl" + PREFIX_PSL=$OPT_LIBPSL + ;; + esac + + dnl if given with a prefix, we set -L and -I based on that + if test -n "$PREFIX_PSL"; then + LD_PSL=-L${PREFIX_PSL}/lib$libsuff + CPP_PSL=-I${PREFIX_PSL}/include + fi + + LDFLAGS="$LDFLAGS $LD_PSL" + CPPFLAGS="$CPPFLAGS $CPP_PSL" + LIBS="$LIB_PSL $LIBS" + + AC_CHECK_LIB(psl, psl_builtin, + [ + AC_CHECK_HEADERS(libpsl.h, + curl_psl_msg="enabled" + LIBPSL_ENABLED=1 + AC_DEFINE(USE_LIBPSL, 1, [if libpsl is in use]) + AC_SUBST(USE_LIBPSL, [1]) + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + if test X"$OPT_LIBPSL" != Xoff && + test "$LIBPSL_ENABLED" != "1"; then + AC_MSG_ERROR([libpsl libs and/or directories were not found where specified!]) + fi +fi +AM_CONDITIONAL([USE_LIBPSL], [test "$curl_psl_msg" = "enabled"]) + + +dnl ********************************************************************** +dnl Check for libgsasl +dnl ********************************************************************** + +AC_ARG_WITH(libgsasl, + AS_HELP_STRING([--without-libgsasl], + [disable libgsasl support for SCRAM]), + with_libgsasl=$withval, + with_libgsasl=yes) +if test $with_libgsasl != "no"; then + AC_SEARCH_LIBS(gsasl_init, gsasl, + [curl_gsasl_msg="enabled"; + AC_DEFINE([USE_GSASL], [1], [GSASL support enabled]) + ], + [curl_gsasl_msg="no (libgsasl not found)"; + AC_MSG_WARN([libgsasl was not found]) + ] + ) +fi +AM_CONDITIONAL([USE_GSASL], [test "$curl_gsasl_msg" = "enabled"]) + +AC_ARG_WITH(libmetalink,, + AC_MSG_ERROR([--with-libmetalink and --without-libmetalink no longer work!])) + +dnl ********************************************************************** +dnl Check for the presence of LIBSSH2 libraries and headers +dnl ********************************************************************** + +dnl Default to compiler & linker defaults for LIBSSH2 files & libraries. +OPT_LIBSSH2=off +AC_ARG_WITH(libssh2,dnl +AS_HELP_STRING([--with-libssh2=PATH],[Where to look for libssh2, PATH points to the libssh2 installation; when possible, set the PKG_CONFIG_PATH environment variable instead of using this option]) +AS_HELP_STRING([--with-libssh2], [enable libssh2]), + OPT_LIBSSH2=$withval, OPT_LIBSSH2=no) + + +OPT_LIBSSH=off +AC_ARG_WITH(libssh,dnl +AS_HELP_STRING([--with-libssh=PATH],[Where to look for libssh, PATH points to the libssh installation; when possible, set the PKG_CONFIG_PATH environment variable instead of using this option]) +AS_HELP_STRING([--with-libssh], [enable libssh]), + OPT_LIBSSH=$withval, OPT_LIBSSH=no) + +OPT_WOLFSSH=off +AC_ARG_WITH(wolfssh,dnl +AS_HELP_STRING([--with-wolfssh=PATH],[Where to look for wolfssh, PATH points to the wolfSSH installation; when possible, set the PKG_CONFIG_PATH environment variable instead of using this option]) +AS_HELP_STRING([--with-wolfssh], [enable wolfssh]), + OPT_WOLFSSH=$withval, OPT_WOLFSSH=no) + +if test X"$OPT_LIBSSH2" != Xno; then + dnl backup the pre-libssh2 variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_LIBSSH2" in + yes) + dnl --with-libssh2 (without path) used + CURL_CHECK_PKGCONFIG(libssh2) + + if test "$PKGCONFIG" != "no" ; then + LIB_SSH2=`$PKGCONFIG --libs-only-l libssh2` + LD_SSH2=`$PKGCONFIG --libs-only-L libssh2` + CPP_SSH2=`$PKGCONFIG --cflags-only-I libssh2` + version=`$PKGCONFIG --modversion libssh2` + DIR_SSH2=`echo $LD_SSH2 | $SED -e 's/^-L//'` + fi + + ;; + off) + dnl no --with-libssh2 option given, just check default places + ;; + *) + dnl use the given --with-libssh2 spot + PREFIX_SSH2=$OPT_LIBSSH2 + ;; + esac + + dnl if given with a prefix, we set -L and -I based on that + if test -n "$PREFIX_SSH2"; then + LIB_SSH2="-lssh2" + LD_SSH2=-L${PREFIX_SSH2}/lib$libsuff + CPP_SSH2=-I${PREFIX_SSH2}/include + DIR_SSH2=${PREFIX_SSH2}/lib$libsuff + fi + + LDFLAGS="$LDFLAGS $LD_SSH2" + CPPFLAGS="$CPPFLAGS $CPP_SSH2" + LIBS="$LIB_SSH2 $LIBS" + + dnl check for function added in libssh2 version 1.0 + AC_CHECK_LIB(ssh2, libssh2_session_block_directions) + + AC_CHECK_HEADER(libssh2.h, + curl_ssh_msg="enabled (libSSH2)" + LIBSSH2_ENABLED=1 + AC_DEFINE(USE_LIBSSH2, 1, [if libSSH2 is in use]) + AC_SUBST(USE_LIBSSH2, [1]) + ) + + if test X"$OPT_LIBSSH2" != Xoff && + test "$LIBSSH2_ENABLED" != "1"; then + AC_MSG_ERROR([libSSH2 libs and/or directories were not found where specified!]) + fi + + if test "$LIBSSH2_ENABLED" = "1"; then + if test -n "$DIR_SSH2"; then + dnl when the libssh2 shared libs were found in a path that the run-time + dnl linker doesn't search through, we need to add it to CURL_LIBRARY_PATH + dnl to prevent further configure tests to fail due to this + + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_SSH2" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_SSH2 to CURL_LIBRARY_PATH]) + fi + fi + else + dnl no libssh2, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + fi +elif test X"$OPT_LIBSSH" != Xno; then + dnl backup the pre-libssh variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_LIBSSH" in + yes) + dnl --with-libssh (without path) used + CURL_CHECK_PKGCONFIG(libssh) + + if test "$PKGCONFIG" != "no" ; then + LIB_SSH=`$PKGCONFIG --libs-only-l libssh` + LD_SSH=`$PKGCONFIG --libs-only-L libssh` + CPP_SSH=`$PKGCONFIG --cflags-only-I libssh` + version=`$PKGCONFIG --modversion libssh` + DIR_SSH=`echo $LD_SSH | $SED -e 's/^-L//'` + fi + + ;; + off) + dnl no --with-libssh option given, just check default places + ;; + *) + dnl use the given --with-libssh spot + PREFIX_SSH=$OPT_LIBSSH + ;; + esac + + dnl if given with a prefix, we set -L and -I based on that + if test -n "$PREFIX_SSH"; then + LIB_SSH="-lssh" + LD_SSH=-L${PREFIX_SSH}/lib$libsuff + CPP_SSH=-I${PREFIX_SSH}/include + DIR_SSH=${PREFIX_SSH}/lib$libsuff + fi + + LDFLAGS="$LDFLAGS $LD_SSH" + CPPFLAGS="$CPPFLAGS $CPP_SSH" + LIBS="$LIB_SSH $LIBS" + + AC_CHECK_LIB(ssh, ssh_new) + + AC_CHECK_HEADER(libssh/libssh.h, + curl_ssh_msg="enabled (libSSH)" + LIBSSH_ENABLED=1 + AC_DEFINE(USE_LIBSSH, 1, [if libSSH is in use]) + AC_SUBST(USE_LIBSSH, [1]) + ) + + if test X"$OPT_LIBSSH" != Xoff && + test "$LIBSSH_ENABLED" != "1"; then + AC_MSG_ERROR([libSSH libs and/or directories were not found where specified!]) + fi + + if test "$LIBSSH_ENABLED" = "1"; then + if test -n "$DIR_SSH"; then + dnl when the libssh shared libs were found in a path that the run-time + dnl linker doesn't search through, we need to add it to CURL_LIBRARY_PATH + dnl to prevent further configure tests to fail due to this + + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_SSH" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_SSH to CURL_LIBRARY_PATH]) + fi + fi + else + dnl no libssh, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + fi +elif test X"$OPT_WOLFSSH" != Xno; then + dnl backup the pre-wolfssh variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + + if test "$OPT_WOLFSSH" != yes; then + WOLFCONFIG="$OPT_WOLFSSH/bin/wolfssh-config" + LDFLAGS="$LDFLAGS `$WOLFCONFIG --libs`" + CPPFLAGS="$CPPFLAGS `$WOLFCONFIG --cflags`" + fi + + AC_CHECK_LIB(wolfssh, wolfSSH_Init) + + AC_CHECK_HEADERS(wolfssh/ssh.h, + curl_ssh_msg="enabled (wolfSSH)" + WOLFSSH_ENABLED=1 + AC_DEFINE(USE_WOLFSSH, 1, [if wolfSSH is in use]) + AC_SUBST(USE_WOLFSSH, [1]) + ) + +fi + +dnl ********************************************************************** +dnl Check for the presence of LIBRTMP libraries and headers +dnl ********************************************************************** + +dnl Default to compiler & linker defaults for LIBRTMP files & libraries. +OPT_LIBRTMP=off +AC_ARG_WITH(librtmp,dnl +AS_HELP_STRING([--with-librtmp=PATH],[Where to look for librtmp, PATH points to the LIBRTMP installation; when possible, set the PKG_CONFIG_PATH environment variable instead of using this option]) +AS_HELP_STRING([--without-librtmp], [disable LIBRTMP]), + OPT_LIBRTMP=$withval) + +if test X"$OPT_LIBRTMP" != Xno; then + dnl backup the pre-librtmp variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_LIBRTMP" in + yes) + dnl --with-librtmp (without path) used + CURL_CHECK_PKGCONFIG(librtmp) + + if test "$PKGCONFIG" != "no" ; then + LIB_RTMP=`$PKGCONFIG --libs-only-l librtmp` + LD_RTMP=`$PKGCONFIG --libs-only-L librtmp` + CPP_RTMP=`$PKGCONFIG --cflags-only-I librtmp` + version=`$PKGCONFIG --modversion librtmp` + DIR_RTMP=`echo $LD_RTMP | $SED -e 's/^-L//'` + else + dnl To avoid link errors, we do not allow --librtmp without + dnl a pkgconfig file + AC_MSG_ERROR([--librtmp was specified but could not find librtmp pkgconfig file.]) + fi + + ;; + off) + dnl no --with-librtmp option given, just check default places + LIB_RTMP="-lrtmp" + ;; + *) + dnl use the given --with-librtmp spot + LIB_RTMP="-lrtmp" + PREFIX_RTMP=$OPT_LIBRTMP + ;; + esac + + dnl if given with a prefix, we set -L and -I based on that + if test -n "$PREFIX_RTMP"; then + LD_RTMP=-L${PREFIX_RTMP}/lib$libsuff + CPP_RTMP=-I${PREFIX_RTMP}/include + DIR_RTMP=${PREFIX_RTMP}/lib$libsuff + fi + + LDFLAGS="$LDFLAGS $LD_RTMP" + CPPFLAGS="$CPPFLAGS $CPP_RTMP" + LIBS="$LIB_RTMP $LIBS" + + AC_CHECK_LIB(rtmp, RTMP_Init, + [ + AC_CHECK_HEADERS(librtmp/rtmp.h, + curl_rtmp_msg="enabled (librtmp)" + LIBRTMP_ENABLED=1 + AC_DEFINE(USE_LIBRTMP, 1, [if librtmp is in use]) + AC_SUBST(USE_LIBRTMP, [1]) + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + if test X"$OPT_LIBRTMP" != Xoff && + test "$LIBRTMP_ENABLED" != "1"; then + AC_MSG_ERROR([librtmp libs and/or directories were not found where specified!]) + fi + +fi + +dnl ********************************************************************** +dnl Check for linker switch for versioned symbols +dnl ********************************************************************** + +versioned_symbols_flavour= +AC_MSG_CHECKING([whether versioned symbols are wanted]) +AC_ARG_ENABLE(versioned-symbols, +AS_HELP_STRING([--enable-versioned-symbols], [Enable versioned symbols in shared library]) +AS_HELP_STRING([--disable-versioned-symbols], [Disable versioned symbols in shared library]), +[ case "$enableval" in + yes) AC_MSG_RESULT(yes) + AC_MSG_CHECKING([if libraries can be versioned]) + GLD=`$LD --help < /dev/null 2>/dev/null | grep version-script` + if test -z "$GLD"; then + AC_MSG_RESULT(no) + AC_MSG_WARN([You need an ld version supporting the --version-script option]) + else + AC_MSG_RESULT(yes) + if test "x$CURL_WITH_MULTI_SSL" = "x1"; then + versioned_symbols_flavour="MULTISSL_" + elif test "x$OPENSSL_ENABLED" = "x1"; then + versioned_symbols_flavour="OPENSSL_" + elif test "x$GNUTLS_ENABLED" = "x1"; then + versioned_symbols_flavour="GNUTLS_" + elif test "x$WOLFSSL_ENABLED" = "x1"; then + versioned_symbols_flavour="WOLFSSL_" + elif test "x$SCHANNEL_ENABLED" = "x1"; then + versioned_symbols_flavour="SCHANNEL_" + elif test "x$SECURETRANSPORT_ENABLED" = "x1"; then + versioned_symbols_flavour="SECURE_TRANSPORT_" + else + versioned_symbols_flavour="" + fi + versioned_symbols="yes" + fi + ;; + + *) AC_MSG_RESULT(no) + ;; + esac +], [ +AC_MSG_RESULT(no) +] +) + +AC_SUBST([CURL_LT_SHLIB_VERSIONED_FLAVOUR], + ["$versioned_symbols_flavour"]) +AM_CONDITIONAL([CURL_LT_SHLIB_USE_VERSIONED_SYMBOLS], + [test "x$versioned_symbols" = 'xyes']) + +dnl ------------------------------------------------- +dnl check winidn option before other IDN libraries +dnl ------------------------------------------------- + +AC_MSG_CHECKING([whether to enable Windows native IDN (Windows native builds only)]) +OPT_WINIDN="default" +AC_ARG_WITH(winidn, +AS_HELP_STRING([--with-winidn=PATH],[enable Windows native IDN]) +AS_HELP_STRING([--without-winidn], [disable Windows native IDN]), + OPT_WINIDN=$withval) +case "$OPT_WINIDN" in + no|default) + dnl --without-winidn option used or configure option not specified + want_winidn="no" + AC_MSG_RESULT([no]) + ;; + yes) + dnl --with-winidn option used without path + want_winidn="yes" + want_winidn_path="default" + AC_MSG_RESULT([yes]) + ;; + *) + dnl --with-winidn option used with path + want_winidn="yes" + want_winidn_path="$withval" + AC_MSG_RESULT([yes ($withval)]) + ;; +esac + +if test "$want_winidn" = "yes"; then + dnl winidn library support has been requested + clean_CFLAGS="$CFLAGS" + clean_CPPFLAGS="$CPPFLAGS" + clean_LDFLAGS="$LDFLAGS" + clean_LIBS="$LIBS" + WINIDN_LIBS="-lnormaliz" + WINIDN_CPPFLAGS="" + # + if test "$want_winidn_path" != "default"; then + dnl path has been specified + dnl pkg-config not available or provides no info + WINIDN_LDFLAGS="-L$want_winidn_path/lib$libsuff" + WINIDN_CPPFLAGS="-I$want_winidn_path/include" + WINIDN_DIR="$want_winidn_path/lib$libsuff" + fi + # + dnl WinIDN requires a minimum supported OS version of at least Vista (0x0600) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + #include + ]],[[ + #if (WINVER < 0x600) && (_WIN32_WINNT < 0x600) + #error + #endif + ]]) + ],[ + ],[ + CFLAGS=`echo $CFLAGS | $SED -e 's/-DWINVER=[[^ ]]*//g'` + CFLAGS=`echo $CFLAGS | $SED -e 's/-D_WIN32_WINNT=[[^ ]]*//g'` + CPPFLAGS=`echo $CPPFLAGS | $SED -e 's/-DWINVER=[[^ ]]*//g'` + CPPFLAGS=`echo $CPPFLAGS | $SED -e 's/-D_WIN32_WINNT=[[^ ]]*//g'` + WINIDN_CPPFLAGS="$WINIDN_CPPFLAGS -DWINVER=0x0600" + ]) + # + CPPFLAGS="$CPPFLAGS $WINIDN_CPPFLAGS" + LDFLAGS="$LDFLAGS $WINIDN_LDFLAGS" + LIBS="$WINIDN_LIBS $LIBS" + # + AC_MSG_CHECKING([if IdnToUnicode can be linked]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + #include + ]],[[ + IdnToUnicode(0, NULL, 0, NULL, 0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_winidn="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_winidn="no" + ]) + # + if test "$tst_links_winidn" = "yes"; then + AC_DEFINE(USE_WIN32_IDN, 1, [Define to 1 if you have the `normaliz' (WinIDN) library (-lnormaliz).]) + AC_SUBST([IDN_ENABLED], [1]) + curl_idn_msg="enabled (Windows-native)" + else + AC_MSG_WARN([Cannot find libraries for IDN support: IDN disabled]) + CFLAGS="$clean_CFLAGS" + CPPFLAGS="$clean_CPPFLAGS" + LDFLAGS="$clean_LDFLAGS" + LIBS="$clean_LIBS" + fi +fi + +dnl ********************************************************************** +dnl Check for the presence of IDN libraries and headers +dnl ********************************************************************** + +AC_MSG_CHECKING([whether to build with libidn2]) +OPT_IDN="default" +AC_ARG_WITH(libidn2, +AS_HELP_STRING([--with-libidn2=PATH],[Enable libidn2 usage]) +AS_HELP_STRING([--without-libidn2],[Disable libidn2 usage]), + [OPT_IDN=$withval]) +if test "x$tst_links_winidn" = "xyes"; then + want_idn="no" + AC_MSG_RESULT([no (using winidn instead)]) +else + case "$OPT_IDN" in + no) + dnl --without-libidn2 option used + want_idn="no" + AC_MSG_RESULT([no]) + ;; + default) + dnl configure option not specified + want_idn="yes" + want_idn_path="default" + AC_MSG_RESULT([(assumed) yes]) + ;; + yes) + dnl --with-libidn2 option used without path + want_idn="yes" + want_idn_path="default" + AC_MSG_RESULT([yes]) + ;; + *) + dnl --with-libidn2 option used with path + want_idn="yes" + want_idn_path="$withval" + AC_MSG_RESULT([yes ($withval)]) + ;; + esac +fi + +if test "$want_idn" = "yes"; then + dnl idn library support has been requested + clean_CPPFLAGS="$CPPFLAGS" + clean_LDFLAGS="$LDFLAGS" + clean_LIBS="$LIBS" + PKGCONFIG="no" + # + if test "$want_idn_path" != "default"; then + dnl path has been specified + IDN_PCDIR="$want_idn_path/lib$libsuff/pkgconfig" + CURL_CHECK_PKGCONFIG(libidn2, [$IDN_PCDIR]) + if test "$PKGCONFIG" != "no"; then + IDN_LIBS=`CURL_EXPORT_PCDIR([$IDN_PCDIR]) dnl + $PKGCONFIG --libs-only-l libidn2 2>/dev/null` + IDN_LDFLAGS=`CURL_EXPORT_PCDIR([$IDN_PCDIR]) dnl + $PKGCONFIG --libs-only-L libidn2 2>/dev/null` + IDN_CPPFLAGS=`CURL_EXPORT_PCDIR([$IDN_PCDIR]) dnl + $PKGCONFIG --cflags-only-I libidn2 2>/dev/null` + IDN_DIR=`echo $IDN_LDFLAGS | $SED -e 's/^-L//'` + else + dnl pkg-config not available or provides no info + IDN_LIBS="-lidn2" + IDN_LDFLAGS="-L$want_idn_path/lib$libsuff" + IDN_CPPFLAGS="-I$want_idn_path/include" + IDN_DIR="$want_idn_path/lib$libsuff" + fi + else + dnl path not specified + CURL_CHECK_PKGCONFIG(libidn2) + if test "$PKGCONFIG" != "no"; then + IDN_LIBS=`$PKGCONFIG --libs-only-l libidn2 2>/dev/null` + IDN_LDFLAGS=`$PKGCONFIG --libs-only-L libidn2 2>/dev/null` + IDN_CPPFLAGS=`$PKGCONFIG --cflags-only-I libidn2 2>/dev/null` + IDN_DIR=`echo $IDN_LDFLAGS | $SED -e 's/^-L//'` + else + dnl pkg-config not available or provides no info + IDN_LIBS="-lidn2" + fi + fi + # + if test "$PKGCONFIG" != "no"; then + AC_MSG_NOTICE([pkg-config: IDN_LIBS: "$IDN_LIBS"]) + AC_MSG_NOTICE([pkg-config: IDN_LDFLAGS: "$IDN_LDFLAGS"]) + AC_MSG_NOTICE([pkg-config: IDN_CPPFLAGS: "$IDN_CPPFLAGS"]) + AC_MSG_NOTICE([pkg-config: IDN_DIR: "$IDN_DIR"]) + else + AC_MSG_NOTICE([IDN_LIBS: "$IDN_LIBS"]) + AC_MSG_NOTICE([IDN_LDFLAGS: "$IDN_LDFLAGS"]) + AC_MSG_NOTICE([IDN_CPPFLAGS: "$IDN_CPPFLAGS"]) + AC_MSG_NOTICE([IDN_DIR: "$IDN_DIR"]) + fi + # + CPPFLAGS="$CPPFLAGS $IDN_CPPFLAGS" + LDFLAGS="$LDFLAGS $IDN_LDFLAGS" + LIBS="$IDN_LIBS $LIBS" + # + AC_MSG_CHECKING([if idn2_lookup_ul can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([idn2_lookup_ul]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_libidn="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_libidn="no" + ]) + # + AC_CHECK_HEADERS( idn2.h ) + + if test "$tst_links_libidn" = "yes"; then + AC_DEFINE(HAVE_LIBIDN2, 1, [Define to 1 if you have the `idn2' library (-lidn2).]) + dnl different versions of libidn have different setups of these: + + AC_SUBST([IDN_ENABLED], [1]) + curl_idn_msg="enabled (libidn2)" + if test -n "$IDN_DIR" -a "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$IDN_DIR" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $IDN_DIR to CURL_LIBRARY_PATH]) + fi + else + AC_MSG_WARN([Cannot find libraries for IDN support: IDN disabled]) + CPPFLAGS="$clean_CPPFLAGS" + LDFLAGS="$clean_LDFLAGS" + LIBS="$clean_LIBS" + fi +fi + +dnl ********************************************************************** +dnl Check for nghttp2 +dnl ********************************************************************** + +OPT_H2="yes" + +if test "x$disable_http" = "xyes" -o X"$want_hyper" != Xno; then + # without HTTP or with Hyper, nghttp2 is no use + OPT_H2="no" +fi + +AC_ARG_WITH(nghttp2, +AS_HELP_STRING([--with-nghttp2=PATH],[Enable nghttp2 usage]) +AS_HELP_STRING([--without-nghttp2],[Disable nghttp2 usage]), + [OPT_H2=$withval]) +case "$OPT_H2" in + no) + dnl --without-nghttp2 option used + want_nghttp2="no" + ;; + yes) + dnl --with-nghttp2 option used without path + want_nghttp2="default" + want_nghttp2_path="" + want_nghttp2_pkg_config_path="" + ;; + *) + dnl --with-nghttp2 option used with path + want_nghttp2="yes" + want_nghttp2_path="$withval" + want_nghttp2_pkg_config_path="$withval/lib/pkgconfig" + ;; +esac + +if test X"$want_nghttp2" != Xno; then + dnl backup the pre-nghttp2 variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(libnghttp2, $want_nghttp2_pkg_config_path) + + if test "$PKGCONFIG" != "no" ; then + LIB_H2=`CURL_EXPORT_PCDIR([$want_nghttp2_pkg_config_path]) + $PKGCONFIG --libs-only-l libnghttp2` + AC_MSG_NOTICE([-l is $LIB_H2]) + + CPP_H2=`CURL_EXPORT_PCDIR([$want_nghttp2_pkg_config_path]) dnl + $PKGCONFIG --cflags-only-I libnghttp2` + AC_MSG_NOTICE([-I is $CPP_H2]) + + LD_H2=`CURL_EXPORT_PCDIR([$want_nghttp2_pkg_config_path]) + $PKGCONFIG --libs-only-L libnghttp2` + AC_MSG_NOTICE([-L is $LD_H2]) + + DIR_H2=`echo $LD_H2 | $SED -e 's/^-L//'` + elif test x"$want_nghttp2_path" != x; then + LIB_H2="-lnghttp2" + LD_H2=-L${want_nghttp2_path}/lib$libsuff + CPP_H2=-I${want_nghttp2_path}/include + DIR_H2=${want_nghttp2_path}/lib$libsuff + elif test X"$want_nghttp2" != Xdefault; then + dnl no nghttp2 pkg-config found and no custom directory specified, + dnl deal with it + AC_MSG_ERROR([--with-nghttp2 was specified but could not find libnghttp2 pkg-config file.]) + else + LIB_H2="-lnghttp2" + fi + + LDFLAGS="$LDFLAGS $LD_H2" + CPPFLAGS="$CPPFLAGS $CPP_H2" + LIBS="$LIB_H2 $LIBS" + + # use nghttp2_session_get_stream_local_window_size to require nghttp2 + # >= 1.15.0 + AC_CHECK_LIB(nghttp2, nghttp2_session_get_stream_local_window_size, + [ + AC_CHECK_HEADERS(nghttp2/nghttp2.h, + curl_h2_msg="enabled (nghttp2)" + NGHTTP2_ENABLED=1 + AC_DEFINE(USE_NGHTTP2, 1, [if nghttp2 is in use]) + AC_SUBST(USE_NGHTTP2, [1]) + ) + + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_H2" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_H2 to CURL_LIBRARY_PATH]) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) +fi + +dnl ********************************************************************** +dnl Check for ngtcp2 (QUIC) +dnl ********************************************************************** + +OPT_TCP2="no" + +if test "x$disable_http" = "xyes"; then + # without HTTP, ngtcp2 is no use + OPT_TCP2="no" +fi + +AC_ARG_WITH(ngtcp2, +AS_HELP_STRING([--with-ngtcp2=PATH],[Enable ngtcp2 usage]) +AS_HELP_STRING([--without-ngtcp2],[Disable ngtcp2 usage]), + [OPT_TCP2=$withval]) +case "$OPT_TCP2" in + no) + dnl --without-ngtcp2 option used + want_tcp2="no" + ;; + yes) + dnl --with-ngtcp2 option used without path + want_tcp2="default" + want_tcp2_path="" + ;; + *) + dnl --with-ngtcp2 option used with path + want_tcp2="yes" + want_tcp2_path="$withval/lib/pkgconfig" + ;; +esac + +curl_tcp2_msg="no (--with-ngtcp2)" +if test X"$want_tcp2" != Xno; then + + if test "$QUIC_ENABLED" != "yes"; then + AC_MSG_ERROR([the detected TLS library does not support QUIC, making --with-ngtcp2 a no-no]) + fi + + dnl backup the pre-ngtcp2 variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(libngtcp2, $want_tcp2_path) + + if test "$PKGCONFIG" != "no" ; then + LIB_TCP2=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-l libngtcp2` + AC_MSG_NOTICE([-l is $LIB_TCP2]) + + CPP_TCP2=`CURL_EXPORT_PCDIR([$want_tcp2_path]) dnl + $PKGCONFIG --cflags-only-I libngtcp2` + AC_MSG_NOTICE([-I is $CPP_TCP2]) + + LD_TCP2=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-L libngtcp2` + AC_MSG_NOTICE([-L is $LD_TCP2]) + + LDFLAGS="$LDFLAGS $LD_TCP2" + CPPFLAGS="$CPPFLAGS $CPP_TCP2" + LIBS="$LIB_TCP2 $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_TCP2=`echo $LD_TCP2 | $SED -e 's/^-L//'` + fi + AC_CHECK_LIB(ngtcp2, ngtcp2_conn_client_new_versioned, + [ + AC_CHECK_HEADERS(ngtcp2/ngtcp2.h, + NGTCP2_ENABLED=1 + AC_DEFINE(USE_NGTCP2, 1, [if ngtcp2 is in use]) + AC_SUBST(USE_NGTCP2, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_TCP2" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_TCP2 to CURL_LIBRARY_PATH]) + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + else + dnl no ngtcp2 pkg-config found, deal with it + if test X"$want_tcp2" != Xdefault; then + dnl To avoid link errors, we do not allow --with-ngtcp2 without + dnl a pkgconfig file + AC_MSG_ERROR([--with-ngtcp2 was specified but could not find ngtcp2 pkg-config file.]) + fi + fi + +fi + +if test "x$NGTCP2_ENABLED" = "x1" -a "x$OPENSSL_ENABLED" = "x1" -a "x$OPENSSL_IS_BORINGSSL" != "x1"; then + dnl backup the pre-ngtcp2_crypto_quictls variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(libngtcp2_crypto_quictls, $want_tcp2_path) + + if test "$PKGCONFIG" != "no" ; then + LIB_NGTCP2_CRYPTO_QUICTLS=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-l libngtcp2_crypto_quictls` + AC_MSG_NOTICE([-l is $LIB_NGTCP2_CRYPTO_QUICTLS]) + + CPP_NGTCP2_CRYPTO_QUICTLS=`CURL_EXPORT_PCDIR([$want_tcp2_path]) dnl + $PKGCONFIG --cflags-only-I libngtcp2_crypto_quictls` + AC_MSG_NOTICE([-I is $CPP_NGTCP2_CRYPTO_QUICTLS]) + + LD_NGTCP2_CRYPTO_QUICTLS=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-L libngtcp2_crypto_quictls` + AC_MSG_NOTICE([-L is $LD_NGTCP2_CRYPTO_QUICTLS]) + + LDFLAGS="$LDFLAGS $LD_NGTCP2_CRYPTO_QUICTLS" + CPPFLAGS="$CPPFLAGS $CPP_NGTCP2_CRYPTO_QUICTLS" + LIBS="$LIB_NGTCP2_CRYPTO_QUICTLS $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_NGTCP2_CRYPTO_QUICTLS=`echo $LD_NGTCP2_CRYPTO_QUICTLS | $SED -e 's/^-L//'` + fi + AC_CHECK_LIB(ngtcp2_crypto_quictls, ngtcp2_crypto_recv_client_initial_cb, + [ + AC_CHECK_HEADERS(ngtcp2/ngtcp2_crypto.h, + NGTCP2_ENABLED=1 + AC_DEFINE(USE_NGTCP2_CRYPTO_QUICTLS, 1, [if ngtcp2_crypto_quictls is in use]) + AC_SUBST(USE_NGTCP2_CRYPTO_QUICTLS, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_NGTCP2_CRYPTO_QUICTLS" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_NGTCP2_CRYPTO_QUICTLS to CURL_LIBRARY_PATH]) + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + else + dnl no ngtcp2_crypto_quictls pkg-config found, deal with it + if test X"$want_tcp2" != Xdefault; then + dnl To avoid link errors, we do not allow --with-ngtcp2 without + dnl a pkgconfig file + AC_MSG_ERROR([--with-ngtcp2 was specified but could not find ngtcp2_crypto_quictls pkg-config file.]) + fi + fi +fi + +if test "x$NGTCP2_ENABLED" = "x1" -a "x$OPENSSL_ENABLED" = "x1" -a "x$OPENSSL_IS_BORINGSSL" = "x1"; then + dnl backup the pre-ngtcp2_crypto_boringssl variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(libngtcp2_crypto_boringssl, $want_tcp2_path) + + if test "$PKGCONFIG" != "no" ; then + LIB_NGTCP2_CRYPTO_BORINGSSL=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-l libngtcp2_crypto_boringssl` + AC_MSG_NOTICE([-l is $LIB_NGTCP2_CRYPTO_BORINGSSL]) + + CPP_NGTCP2_CRYPTO_BORINGSSL=`CURL_EXPORT_PCDIR([$want_tcp2_path]) dnl + $PKGCONFIG --cflags-only-I libngtcp2_crypto_boringssl` + AC_MSG_NOTICE([-I is $CPP_NGTCP2_CRYPTO_BORINGSSL]) + + LD_NGTCP2_CRYPTO_BORINGSSL=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-L libngtcp2_crypto_boringssl` + AC_MSG_NOTICE([-L is $LD_NGTCP2_CRYPTO_BORINGSSL]) + + LDFLAGS="$LDFLAGS $LD_NGTCP2_CRYPTO_BORINGSSL" + CPPFLAGS="$CPPFLAGS $CPP_NGTCP2_CRYPTO_BORINGSSL" + LIBS="$LIB_NGTCP2_CRYPTO_BORINGSSL $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_NGTCP2_CRYPTO_BORINGSSL=`echo $LD_NGTCP2_CRYPTO_BORINGSSL | $SED -e 's/^-L//'` + fi + AC_CHECK_LIB(ngtcp2_crypto_boringssl, ngtcp2_crypto_recv_client_initial_cb, + [ + AC_CHECK_HEADERS(ngtcp2/ngtcp2_crypto.h, + NGTCP2_ENABLED=1 + AC_DEFINE(USE_NGTCP2_CRYPTO_BORINGSSL, 1, [if ngtcp2_crypto_boringssl is in use]) + AC_SUBST(USE_NGTCP2_CRYPTO_BORINGSSL, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_NGTCP2_CRYPTO_BORINGSSL" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_NGTCP2_CRYPTO_BORINGSSL to CURL_LIBRARY_PATH]) + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + else + dnl no ngtcp2_crypto_boringssl pkg-config found, deal with it + if test X"$want_tcp2" != Xdefault; then + dnl To avoid link errors, we do not allow --with-ngtcp2 without + dnl a pkgconfig file + AC_MSG_ERROR([--with-ngtcp2 was specified but could not find ngtcp2_crypto_boringssl pkg-config file.]) + fi + fi +fi + +if test "x$NGTCP2_ENABLED" = "x1" -a "x$GNUTLS_ENABLED" = "x1"; then + dnl backup the pre-ngtcp2_crypto_gnutls variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(libngtcp2_crypto_gnutls, $want_tcp2_path) + + if test "$PKGCONFIG" != "no" ; then + LIB_NGTCP2_CRYPTO_GNUTLS=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-l libngtcp2_crypto_gnutls` + AC_MSG_NOTICE([-l is $LIB_NGTCP2_CRYPTO_GNUTLS]) + + CPP_NGTCP2_CRYPTO_GNUTLS=`CURL_EXPORT_PCDIR([$want_tcp2_path]) dnl + $PKGCONFIG --cflags-only-I libngtcp2_crypto_gnutls` + AC_MSG_NOTICE([-I is $CPP_NGTCP2_CRYPTO_GNUTLS]) + + LD_NGTCP2_CRYPTO_GNUTLS=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-L libngtcp2_crypto_gnutls` + AC_MSG_NOTICE([-L is $LD_NGTCP2_CRYPTO_GNUTLS]) + + LDFLAGS="$LDFLAGS $LD_NGTCP2_CRYPTO_GNUTLS" + CPPFLAGS="$CPPFLAGS $CPP_NGTCP2_CRYPTO_GNUTLS" + LIBS="$LIB_NGTCP2_CRYPTO_GNUTLS $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_NGTCP2_CRYPTO_GNUTLS=`echo $LD_NGTCP2_CRYPTO_GNUTLS | $SED -e 's/^-L//'` + fi + AC_CHECK_LIB(ngtcp2_crypto_gnutls, ngtcp2_crypto_recv_client_initial_cb, + [ + AC_CHECK_HEADERS(ngtcp2/ngtcp2_crypto.h, + NGTCP2_ENABLED=1 + AC_DEFINE(USE_NGTCP2_CRYPTO_GNUTLS, 1, [if ngtcp2_crypto_gnutls is in use]) + AC_SUBST(USE_NGTCP2_CRYPTO_GNUTLS, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_NGTCP2_CRYPTO_GNUTLS" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_NGTCP2_CRYPTO_GNUTLS to CURL_LIBRARY_PATH]) + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + else + dnl no ngtcp2_crypto_gnutls pkg-config found, deal with it + if test X"$want_tcp2" != Xdefault; then + dnl To avoid link errors, we do not allow --with-ngtcp2 without + dnl a pkgconfig file + AC_MSG_ERROR([--with-ngtcp2 was specified but could not find ngtcp2_crypto_gnutls pkg-config file.]) + fi + fi +fi + +if test "x$NGTCP2_ENABLED" = "x1" -a "x$WOLFSSL_ENABLED" = "x1"; then + dnl backup the pre-ngtcp2_crypto_wolfssl variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(libngtcp2_crypto_wolfssl, $want_tcp2_path) + + if test "$PKGCONFIG" != "no" ; then + LIB_NGTCP2_CRYPTO_WOLFSSL=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-l libngtcp2_crypto_wolfssl` + AC_MSG_NOTICE([-l is $LIB_NGTCP2_CRYPTO_WOLFSSL]) + + CPP_NGTCP2_CRYPTO_WOLFSSL=`CURL_EXPORT_PCDIR([$want_tcp2_path]) dnl + $PKGCONFIG --cflags-only-I libngtcp2_crypto_wolfssl` + AC_MSG_NOTICE([-I is $CPP_NGTCP2_CRYPTO_WOLFSSL]) + + LD_NGTCP2_CRYPTO_WOLFSSL=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-L libngtcp2_crypto_wolfssl` + AC_MSG_NOTICE([-L is $LD_NGTCP2_CRYPTO_WOLFSSL]) + + LDFLAGS="$LDFLAGS $LD_NGTCP2_CRYPTO_WOLFSSL" + CPPFLAGS="$CPPFLAGS $CPP_NGTCP2_CRYPTO_WOLFSSL" + LIBS="$LIB_NGTCP2_CRYPTO_WOLFSSL $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_NGTCP2_CRYPTO_WOLFSSL=`echo $LD_NGTCP2_CRYPTO_WOLFSSL | $SED -e 's/^-L//'` + fi + AC_CHECK_LIB(ngtcp2_crypto_wolfssl, ngtcp2_crypto_recv_client_initial_cb, + [ + AC_CHECK_HEADERS(ngtcp2/ngtcp2_crypto.h, + NGTCP2_ENABLED=1 + AC_DEFINE(USE_NGTCP2_CRYPTO_WOLFSSL, 1, [if ngtcp2_crypto_wolfssl is in use]) + AC_SUBST(USE_NGTCP2_CRYPTO_WOLFSSL, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_NGTCP2_CRYPTO_WOLFSSL" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_NGTCP2_CRYPTO_WOLFSSL to CURL_LIBRARY_PATH]) + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + else + dnl no ngtcp2_crypto_wolfssl pkg-config found, deal with it + if test X"$want_tcp2" != Xdefault; then + dnl To avoid link errors, we do not allow --with-ngtcp2 without + dnl a pkgconfig file + AC_MSG_ERROR([--with-ngtcp2 was specified but could not find ngtcp2_crypto_wolfssl pkg-config file.]) + fi + fi +fi + +dnl ********************************************************************** +dnl Check for OpenSSL QUIC +dnl ********************************************************************** + +OPT_OPENSSL_QUIC="no" + +if test "x$disable_http" = "xyes" -o "x$OPENSSL_ENABLED" != "x1"; then + # without HTTP or without openssl, no use + OPT_OPENSSL_QUIC="no" +fi + +AC_ARG_WITH(openssl-quic, +AS_HELP_STRING([--with-openssl-quic],[Enable OpenSSL QUIC usage]) +AS_HELP_STRING([--without-openssl-quic],[Disable OpenSSL QUIC usage]), + [OPT_OPENSSL_QUIC=$withval]) +case "$OPT_OPENSSL_QUIC" in + no) + dnl --without-openssl-quic option used + want_openssl_quic="no" + ;; + yes) + dnl --with-openssl-quic option used + want_openssl_quic="yes" + ;; +esac + +curl_openssl_quic_msg="no (--with-openssl-quic)" +if test "x$want_openssl_quic" = "xyes"; then + + if test "$NGTCP2_ENABLED" = 1; then + AC_MSG_ERROR([--with-openssl-quic and --with-ngtcp2 are mutually exclusive]) + fi + if test "$HAVE_OPENSSL_QUIC" != 1; then + AC_MSG_ERROR([--with-openssl-quic requires quic support in OpenSSL]) + fi + AC_DEFINE(USE_OPENSSL_QUIC, 1, [if openssl QUIC is in use]) + AC_SUBST(USE_OPENSSL_QUIC, [1]) +fi + +dnl ********************************************************************** +dnl Check for nghttp3 (HTTP/3 with ngtcp2) +dnl ********************************************************************** + +OPT_NGHTTP3="yes" + +if test "x$USE_NGTCP2" != "x1" -a "x$USE_OPENSSL_QUIC" != "x1"; then + # without ngtcp2 or openssl quic, nghttp3 is of no use for us + OPT_NGHTTP3="no" + want_nghttp3="no" +fi + +AC_ARG_WITH(nghttp3, +AS_HELP_STRING([--with-nghttp3=PATH],[Enable nghttp3 usage]) +AS_HELP_STRING([--without-nghttp3],[Disable nghttp3 usage]), + [OPT_NGHTTP3=$withval]) +case "$OPT_NGHTTP3" in + no) + dnl --without-nghttp3 option used + want_nghttp3="no" + ;; + yes) + dnl --with-nghttp3 option used without path + want_nghttp3="default" + want_nghttp3_path="" + ;; + *) + dnl --with-nghttp3 option used with path + want_nghttp3="yes" + want_nghttp3_path="$withval/lib/pkgconfig" + ;; +esac + +curl_http3_msg="no (--with-nghttp3)" +if test X"$want_nghttp3" != Xno; then + + dnl backup the pre-nghttp3 variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(libnghttp3, $want_nghttp3_path) + + if test "$PKGCONFIG" != "no" ; then + LIB_NGHTTP3=`CURL_EXPORT_PCDIR([$want_nghttp3_path]) + $PKGCONFIG --libs-only-l libnghttp3` + AC_MSG_NOTICE([-l is $LIB_NGHTTP3]) + + CPP_NGHTTP3=`CURL_EXPORT_PCDIR([$want_nghttp3_path]) dnl + $PKGCONFIG --cflags-only-I libnghttp3` + AC_MSG_NOTICE([-I is $CPP_NGHTTP3]) + + LD_NGHTTP3=`CURL_EXPORT_PCDIR([$want_nghttp3_path]) + $PKGCONFIG --libs-only-L libnghttp3` + AC_MSG_NOTICE([-L is $LD_NGHTTP3]) + + LDFLAGS="$LDFLAGS $LD_NGHTTP3" + CPPFLAGS="$CPPFLAGS $CPP_NGHTTP3" + LIBS="$LIB_NGHTTP3 $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_NGHTTP3=`echo $LD_NGHTTP3 | $SED -e 's/^-L//'` + fi + AC_CHECK_LIB(nghttp3, nghttp3_conn_client_new_versioned, + [ + AC_CHECK_HEADERS(nghttp3/nghttp3.h, + AC_DEFINE(USE_NGHTTP3, 1, [if nghttp3 is in use]) + AC_SUBST(USE_NGHTTP3, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_NGHTTP3" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_NGHTTP3 to CURL_LIBRARY_PATH]) + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + else + dnl no nghttp3 pkg-config found, deal with it + if test X"$want_nghttp3" != Xdefault; then + dnl To avoid link errors, we do not allow --with-nghttp3 without + dnl a pkgconfig file + AC_MSG_ERROR([--with-nghttp3 was specified but could not find nghttp3 pkg-config file.]) + fi + fi + +fi + +dnl ********************************************************************** +dnl Check for ngtcp2 and nghttp3 (HTTP/3 with ngtcp2 + nghttp3) +dnl ********************************************************************** + +if test "x$NGTCP2_ENABLED" = "x1" -a "x$USE_NGHTTP3" = "x1"; then + AC_DEFINE(USE_NGTCP2_H3, 1, [if ngtcp2 + nghttp3 is in use]) + AC_SUBST(USE_NGTCP2_H3, [1]) + AC_MSG_NOTICE([HTTP3 support is experimental]) + curl_h3_msg="enabled (ngtcp2 + nghttp3)" +fi + +dnl ********************************************************************** +dnl Check for OpenSSL and nghttp3 (HTTP/3 with nghttp3 using OpenSSL QUIC) +dnl ********************************************************************** + +if test "x$USE_OPENSSL_QUIC" = "x1" -a "x$USE_NGHTTP3" = "x1"; then + experimental="$experimental HTTP3" + AC_DEFINE(USE_OPENSSL_H3, 1, [if openssl quic + nghttp3 is in use]) + AC_SUBST(USE_OPENSSL_H3, [1]) + AC_MSG_NOTICE([HTTP3 support is experimental]) + curl_h3_msg="enabled (openssl + nghttp3)" +fi + +dnl ********************************************************************** +dnl Check for quiche (QUIC) +dnl ********************************************************************** + +OPT_QUICHE="no" + +if test "x$disable_http" = "xyes" -o "x$USE_NGTCP" = "x1"; then + # without HTTP or with ngtcp2, quiche is no use + OPT_QUICHE="no" +fi + +AC_ARG_WITH(quiche, +AS_HELP_STRING([--with-quiche=PATH],[Enable quiche usage]) +AS_HELP_STRING([--without-quiche],[Disable quiche usage]), + [OPT_QUICHE=$withval]) +case "$OPT_QUICHE" in + no) + dnl --without-quiche option used + want_quiche="no" + ;; + yes) + dnl --with-quiche option used without path + want_quiche="default" + want_quiche_path="" + ;; + *) + dnl --with-quiche option used with path + want_quiche="yes" + want_quiche_path="$withval" + ;; +esac + +if test X"$want_quiche" != Xno; then + + if test "$QUIC_ENABLED" != "yes"; then + AC_MSG_ERROR([the detected TLS library does not support QUIC, making --with-quiche a no-no]) + fi + + if test "$NGHTTP3_ENABLED" = 1; then + AC_MSG_ERROR([--with-quiche and --with-ngtcp2 are mutually exclusive]) + fi + + dnl backup the pre-quiche variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(quiche, $want_quiche_path) + + if test "$PKGCONFIG" != "no" ; then + LIB_QUICHE=`CURL_EXPORT_PCDIR([$want_quiche_path]) + $PKGCONFIG --libs-only-l quiche` + AC_MSG_NOTICE([-l is $LIB_QUICHE]) + + CPP_QUICHE=`CURL_EXPORT_PCDIR([$want_quiche_path]) dnl + $PKGCONFIG --cflags-only-I quiche` + AC_MSG_NOTICE([-I is $CPP_QUICHE]) + + LD_QUICHE=`CURL_EXPORT_PCDIR([$want_quiche_path]) + $PKGCONFIG --libs-only-L quiche` + AC_MSG_NOTICE([-L is $LD_QUICHE]) + + LDFLAGS="$LDFLAGS $LD_QUICHE" + CPPFLAGS="$CPPFLAGS $CPP_QUICHE" + LIBS="$LIB_QUICHE $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_QUICHE=`echo $LD_QUICHE | $SED -e 's/^-L//'` + fi + AC_CHECK_LIB(quiche, quiche_conn_send_ack_eliciting, + [ + AC_CHECK_HEADERS(quiche.h, + experimental="$experimental HTTP3" + AC_MSG_NOTICE([HTTP3 support is experimental]) + curl_h3_msg="enabled (quiche)" + QUICHE_ENABLED=1 + AC_DEFINE(USE_QUICHE, 1, [if quiche is in use]) + AC_SUBST(USE_QUICHE, [1]) + AC_CHECK_FUNCS([quiche_conn_set_qlog_fd]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_QUICHE" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_QUICHE to CURL_LIBRARY_PATH]), + [], + [ +AC_INCLUDES_DEFAULT +#include + ] + ) + ], + dnl not found, revert back to clean variables + AC_MSG_ERROR([couldn't use quiche]) + ) + else + dnl no quiche pkg-config found, deal with it + if test X"$want_quiche" != Xdefault; then + dnl To avoid link errors, we do not allow --with-quiche without + dnl a pkgconfig file + AC_MSG_ERROR([--with-quiche was specified but could not find quiche pkg-config file.]) + fi + fi +fi + +dnl ********************************************************************** +dnl Check for msh3 (QUIC) +dnl ********************************************************************** + +OPT_MSH3="no" + +if test "x$disable_http" = "xyes" -o "x$USE_NGTCP" = "x1"; then + # without HTTP or with ngtcp2, msh3 is no use + OPT_MSH3="no" +fi + +AC_ARG_WITH(msh3, +AS_HELP_STRING([--with-msh3=PATH],[Enable msh3 usage]) +AS_HELP_STRING([--without-msh3],[Disable msh3 usage]), + [OPT_MSH3=$withval]) +case "$OPT_MSH3" in + no) + dnl --without-msh3 option used + want_msh3="no" + ;; + yes) + dnl --with-msh3 option used without path + want_msh3="default" + want_msh3_path="" + ;; + *) + dnl --with-msh3 option used with path + want_msh3="yes" + want_msh3_path="$withval" + ;; +esac + +if test X"$want_msh3" != Xno; then + + dnl msh3 on non-Windows needs an OpenSSL with the QUIC API + if test "$curl_cv_native_windows" != "yes"; then + if test "$QUIC_ENABLED" != "yes"; then + AC_MSG_ERROR([the detected TLS library does not support QUIC, making --with-msh3 a no-no]) + fi + if test "$OPENSSL_ENABLED" != "1"; then + AC_MSG_ERROR([msh3 requires OpenSSL]) + fi + fi + + if test "$NGHTTP3_ENABLED" = 1; then + AC_MSG_ERROR([--with-msh3 and --with-ngtcp2 are mutually exclusive]) + fi + if test "$QUICHE_ENABLED" = 1; then + AC_MSG_ERROR([--with-msh3 and --with-quiche are mutually exclusive]) + fi + + dnl backup the pre-msh3 variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + if test -n "$want_msh3_path"; then + LD_MSH3="-L$want_msh3_path/lib" + CPP_MSH3="-I$want_msh3_path/include" + DIR_MSH3="$want_msh3_path/lib" + LDFLAGS="$LDFLAGS $LD_MSH3" + CPPFLAGS="$CPPFLAGS $CPP_MSH3" + fi + LIBS="-lmsh3 $LIBS" + + AC_CHECK_LIB(msh3, MsH3ApiOpen, + [ + AC_CHECK_HEADERS(msh3.h, + curl_h3_msg="enabled (msh3)" + MSH3_ENABLED=1 + AC_DEFINE(USE_MSH3, 1, [if msh3 is in use]) + AC_SUBST(USE_MSH3, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_MSH3" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_MSH3 to CURL_LIBRARY_PATH]), + experimental="$experimental HTTP3" + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) +fi + +dnl ********************************************************************** +dnl Check for zsh completion path +dnl ********************************************************************** + +OPT_ZSH_FPATH=default +AC_ARG_WITH(zsh-functions-dir, +AS_HELP_STRING([--with-zsh-functions-dir=PATH],[Install zsh completions to PATH]) +AS_HELP_STRING([--without-zsh-functions-dir],[Do not install zsh completions]), + [OPT_ZSH_FPATH=$withval]) +case "$OPT_ZSH_FPATH" in + default|no) + dnl --without-zsh-functions-dir option used + ;; + yes) + dnl --with-zsh-functions-dir option used without path + ZSH_FUNCTIONS_DIR="$datarootdir/zsh/site-functions" + AC_SUBST(ZSH_FUNCTIONS_DIR) + ;; + *) + dnl --with-zsh-functions-dir option used with path + ZSH_FUNCTIONS_DIR="$withval" + AC_SUBST(ZSH_FUNCTIONS_DIR) + ;; +esac +AM_CONDITIONAL(USE_ZSH_COMPLETION, test x"$ZSH_FUNCTIONS_DIR" != x) + +dnl ********************************************************************** +dnl Check for fish completion path +dnl ********************************************************************** + +OPT_FISH_FPATH=default +AC_ARG_WITH(fish-functions-dir, +AS_HELP_STRING([--with-fish-functions-dir=PATH],[Install fish completions to PATH]) +AS_HELP_STRING([--without-fish-functions-dir],[Do not install fish completions]), + [OPT_FISH_FPATH=$withval]) +case "$OPT_FISH_FPATH" in + default|no) + dnl --without-fish-functions-dir option used + ;; + yes) + dnl --with-fish-functions-dir option used without path + CURL_CHECK_PKGCONFIG(fish) + if test "$PKGCONFIG" != "no" ; then + FISH_FUNCTIONS_DIR="$($PKGCONFIG --variable completionsdir fish)" + else + FISH_FUNCTIONS_DIR="$datarootdir/fish/vendor_completions.d" + fi + AC_SUBST(FISH_FUNCTIONS_DIR) + ;; + *) + dnl --with-fish-functions-dir option used with path + FISH_FUNCTIONS_DIR="$withval" + AC_SUBST(FISH_FUNCTIONS_DIR) + ;; +esac +AM_CONDITIONAL(USE_FISH_COMPLETION, test x"$FISH_FUNCTIONS_DIR" != x) + +dnl Now check for the very most basic headers. Then we can use these +dnl ones as default-headers when checking for the rest! +AC_CHECK_HEADERS( + sys/types.h \ + sys/time.h \ + sys/select.h \ + sys/socket.h \ + sys/ioctl.h \ + unistd.h \ + stdlib.h \ + arpa/inet.h \ + net/if.h \ + netinet/in.h \ + netinet/in6.h \ + sys/un.h \ + linux/tcp.h \ + netinet/tcp.h \ + netinet/udp.h \ + netdb.h \ + sys/sockio.h \ + sys/stat.h \ + sys/param.h \ + termios.h \ + termio.h \ + fcntl.h \ + io.h \ + pwd.h \ + utime.h \ + sys/utime.h \ + sys/poll.h \ + poll.h \ + socket.h \ + sys/resource.h \ + libgen.h \ + locale.h \ + stdbool.h \ + sys/filio.h \ + sys/wait.h \ + setjmp.h, +dnl to do if not found +[], +dnl to do if found +[], +dnl default includes +[ +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif +] +) + + +dnl Checks for typedefs, structures, and compiler characteristics. +AC_C_CONST +AC_TYPE_SIZE_T + +CURL_CHECK_STRUCT_TIMEVAL +CURL_VERIFY_RUNTIMELIBS + +CURL_SIZEOF(size_t) +CURL_SIZEOF(long) +CURL_SIZEOF(int) +CURL_SIZEOF(time_t) +CURL_SIZEOF(off_t) + +o=$CPPFLAGS +CPPFLAGS="-I$srcdir/include $CPPFLAGS" +CURL_SIZEOF(curl_off_t, [ +#include +]) +CURL_SIZEOF(curl_socket_t, [ +#include +]) +CPPFLAGS=$o + +AC_CHECK_TYPE(long long, + [AC_DEFINE(HAVE_LONGLONG, 1, + [Define to 1 if the compiler supports the 'long long' data type.])] + longlong="yes" +) + +if test ${ac_cv_sizeof_curl_off_t} -lt 8; then + AC_MSG_ERROR([64 bit curl_off_t is required]) +fi + +# check for ssize_t +AC_CHECK_TYPE(ssize_t, , + AC_DEFINE(ssize_t, int, [the signed version of size_t])) + +# check for bool type +AC_CHECK_TYPE([bool],[ + AC_DEFINE(HAVE_BOOL_T, 1, + [Define to 1 if bool is an available type.]) +], ,[ +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_STDBOOL_H +#include +#endif +]) + +# check for sa_family_t +AC_CHECK_TYPE(sa_family_t, + AC_DEFINE(CURL_SA_FAMILY_T, sa_family_t, [IP address type in sockaddr]), + [ + # The windows name? + AC_CHECK_TYPE(ADDRESS_FAMILY, + AC_DEFINE(CURL_SA_FAMILY_T, ADDRESS_FAMILY, [IP address type in sockaddr]), + AC_DEFINE(CURL_SA_FAMILY_T, unsigned short, [IP address type in sockaddr]), + [ +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif + ]) + ], +[ +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +]) + +# check for suseconds_t +AC_CHECK_TYPE([suseconds_t],[ + AC_DEFINE(HAVE_SUSECONDS_T, 1, + [Define to 1 if suseconds_t is an available type.]) +], ,[ +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +]) + +AC_MSG_CHECKING([if time_t is unsigned]) +CURL_RUN_IFELSE( + [ + #include + #include + int main(void) { + time_t t = -1; + return (t < 0); + } + ],[ + AC_MSG_RESULT([yes]) + AC_DEFINE(HAVE_TIME_T_UNSIGNED, 1, [Define this if time_t is unsigned]) +],[ + AC_MSG_RESULT([no]) +],[ + dnl cross-compiling, most systems are unsigned + AC_MSG_RESULT([no]) +]) + +TYPE_IN_ADDR_T + +TYPE_SOCKADDR_STORAGE + +CURL_CHECK_FUNC_SELECT + +CURL_CHECK_FUNC_RECV +CURL_CHECK_FUNC_SEND +CURL_CHECK_MSG_NOSIGNAL + +CURL_CHECK_FUNC_ALARM +CURL_CHECK_FUNC_BASENAME +CURL_CHECK_FUNC_CLOSESOCKET +CURL_CHECK_FUNC_CLOSESOCKET_CAMEL +CURL_CHECK_FUNC_FCNTL +CURL_CHECK_FUNC_FREEADDRINFO +CURL_CHECK_FUNC_FSETXATTR +CURL_CHECK_FUNC_FTRUNCATE +CURL_CHECK_FUNC_GETADDRINFO +CURL_CHECK_FUNC_GETHOSTBYNAME +CURL_CHECK_FUNC_GETHOSTBYNAME_R +CURL_CHECK_FUNC_GETHOSTNAME +CURL_CHECK_FUNC_GETPEERNAME +CURL_CHECK_FUNC_GETSOCKNAME +CURL_CHECK_FUNC_IF_NAMETOINDEX +CURL_CHECK_FUNC_GETIFADDRS +CURL_CHECK_FUNC_GMTIME_R +CURL_CHECK_FUNC_INET_NTOP +CURL_CHECK_FUNC_INET_PTON +CURL_CHECK_FUNC_IOCTL +CURL_CHECK_FUNC_IOCTLSOCKET +CURL_CHECK_FUNC_IOCTLSOCKET_CAMEL +CURL_CHECK_FUNC_MEMRCHR +CURL_CHECK_FUNC_POLL +CURL_CHECK_FUNC_SIGACTION +CURL_CHECK_FUNC_SIGINTERRUPT +CURL_CHECK_FUNC_SIGNAL +CURL_CHECK_FUNC_SIGSETJMP +CURL_CHECK_FUNC_SOCKET +CURL_CHECK_FUNC_SOCKETPAIR +CURL_CHECK_FUNC_STRCASECMP +CURL_CHECK_FUNC_STRCMPI +CURL_CHECK_FUNC_STRDUP +CURL_CHECK_FUNC_STRERROR_R +CURL_CHECK_FUNC_STRICMP +CURL_CHECK_FUNC_STRTOK_R +CURL_CHECK_FUNC_STRTOLL + +case $host in + *msdosdjgpp) + ac_cv_func_pipe=no + skipcheck_pipe=yes + AC_MSG_NOTICE([skip check for pipe on msdosdjgpp]) + ;; +esac + +AC_CHECK_DECLS([getpwuid_r], [], [AC_DEFINE(HAVE_DECL_GETPWUID_R_MISSING, 1, "Set if getpwuid_r() declaration is missing")], + [[#include + #include ]]) + +AC_CHECK_FUNCS([\ + _fseeki64 \ + arc4random \ + fnmatch \ + fseeko \ + geteuid \ + getpass_r \ + getppid \ + getpwuid \ + getpwuid_r \ + getrlimit \ + gettimeofday \ + if_nametoindex \ + mach_absolute_time \ + pipe \ + sched_yield \ + sendmsg \ + setlocale \ + setmode \ + setrlimit \ + snprintf \ + utime \ + utimes \ +],[ +],[ + func="$ac_func" + eval skipcheck=\$skipcheck_$func + if test "x$skipcheck" != "xyes"; then + AC_MSG_CHECKING([deeper for $func]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + ]],[[ + $func (); + ]]) + ],[ + AC_MSG_RESULT([yes]) + eval "ac_cv_func_$func=yes" + AC_DEFINE_UNQUOTED(XC_SH_TR_CPP([HAVE_$func]), [1], + [Define to 1 if you have the $func function.]) + ],[ + AC_MSG_RESULT([but still no]) + ]) + fi +]) + +dnl On Android, the only way to know if fseeko can be used is to see if it is +dnl declared or not (for this API level), as the symbol always exists in the +dnl lib. +AC_CHECK_DECL([fseeko], + [AC_DEFINE([HAVE_DECL_FSEEKO], [1], + [Define to 1 if you have the fseeko declaration])], + [], + [[#include ]]) + +CURL_CHECK_NONBLOCKING_SOCKET + +if test "x$BUILD_DOCS" != "x0" -o "x$USE_MANUAL" != "x0"; then + AC_PATH_PROG( PERL, perl, , + $PATH:/usr/local/bin/perl:/usr/bin/:/usr/local/bin ) + AC_SUBST(PERL) + + if test -z "$PERL"; then + AC_MSG_ERROR([perl was not found, needed for docs and manual]) + fi +fi + +dnl set variable for use in automakefile(s) +AM_CONDITIONAL(BUILD_DOCS, test x"$BUILD_DOCS" = x1) + +dnl ************************************************************************* +dnl If the manual variable still is set, then we go with providing a built-in +dnl manual + +if test "$USE_MANUAL" = "1"; then + AC_DEFINE(USE_MANUAL, 1, [If you want to build curl with the built-in manual]) + curl_manual_msg="enabled" +fi + +dnl set variable for use in automakefile(s) +AM_CONDITIONAL(USE_MANUAL, test x"$USE_MANUAL" = x1) + +CURL_CHECK_LIB_ARES + +if test "x$curl_cv_native_windows" != "xyes" && + test "x$enable_shared" = "xyes"; then + build_libhostname=yes +else + build_libhostname=no +fi +AM_CONDITIONAL(BUILD_LIBHOSTNAME, test x$build_libhostname = xyes) + +if test "x$want_ares" != xyes; then + CURL_CHECK_OPTION_THREADED_RESOLVER +fi + +dnl ************************************************************ +dnl disable POSIX threads +dnl +AC_MSG_CHECKING([whether to use POSIX threads for threaded resolver]) +AC_ARG_ENABLE(pthreads, +AS_HELP_STRING([--enable-pthreads], + [Enable POSIX threads (default for threaded resolver)]) +AS_HELP_STRING([--disable-pthreads],[Disable POSIX threads]), +[ case "$enableval" in + no) AC_MSG_RESULT(no) + want_pthreads=no + ;; + *) AC_MSG_RESULT(yes) + want_pthreads=yes + ;; + esac ], [ + AC_MSG_RESULT(auto) + want_pthreads=auto + ] +) + +dnl turn off pthreads if rt is disabled +if test "$want_pthreads" != "no"; then + if test "$want_pthreads" = "yes" && test "$dontwant_rt" = "yes"; then + AC_MSG_ERROR([options --enable-pthreads and --disable-rt are mutually exclusive]) + fi + if test "$dontwant_rt" != "no"; then + dnl if --enable-pthreads was explicit then warn it's being ignored + if test "$want_pthreads" = "yes"; then + AC_MSG_WARN([--enable-pthreads Ignored since librt is disabled.]) + fi + want_pthreads=no + fi +fi + +dnl turn off pthreads if no threaded resolver +if test "$want_pthreads" != "no" && test "$want_thres" != "yes"; then + want_pthreads=no +fi + +dnl detect pthreads +if test "$want_pthreads" != "no"; then + AC_CHECK_HEADER(pthread.h, + [ AC_DEFINE(HAVE_PTHREAD_H, 1, [if you have ]) + save_CFLAGS="$CFLAGS" + dnl When statically linking against boringssl, -lpthread is added to LIBS. + dnl Make sure to that this does not pass the check below, we really want + dnl -pthread in CFLAGS as recommended for GCC. This also ensures that + dnl lib1541 and lib1565 tests are built with these options. Otherwise + dnl they fail the build since tests/libtest/Makefile.am clears LIBS. + save_LIBS="$LIBS" + + LIBS= + dnl Check for libc variants without a separate pthread lib like bionic + AC_CHECK_FUNC(pthread_create, [USE_THREADS_POSIX=1] ) + LIBS="$save_LIBS" + + dnl on HPUX, life is more complicated... + case $host in + *-hp-hpux*) + dnl it doesn't actually work without -lpthread + USE_THREADS_POSIX="" + ;; + *) + ;; + esac + + dnl if it wasn't found without lib, search for it in pthread lib + if test "$USE_THREADS_POSIX" != "1" + then + # assign PTHREAD for pkg-config use + PTHREAD=" -pthread" + + case $host in + *-ibm-aix*) + dnl Check if compiler is xlC + COMPILER_VERSION=`"$CC" -qversion 2>/dev/null` + if test x"$COMPILER_VERSION" = "x"; then + CFLAGS="$CFLAGS -pthread" + else + CFLAGS="$CFLAGS -qthreaded" + fi + ;; + powerpc-*amigaos*) + dnl No -pthread option, but link with -lpthread + PTHREAD=" -lpthread" + ;; + *) + CFLAGS="$CFLAGS -pthread" + ;; + esac + AC_CHECK_LIB(pthread, pthread_create, + [USE_THREADS_POSIX=1], + [ CFLAGS="$save_CFLAGS"]) + fi + + if test "x$USE_THREADS_POSIX" = "x1" + then + AC_DEFINE(USE_THREADS_POSIX, 1, [if you want POSIX threaded DNS lookup]) + curl_res_msg="POSIX threaded" + fi + ]) +fi + +dnl threaded resolver check +if test "$want_thres" = "yes" && test "x$USE_THREADS_POSIX" != "x1"; then + if test "$want_pthreads" = "yes"; then + AC_MSG_ERROR([--enable-pthreads but pthreads was not found]) + fi + dnl If native Windows fallback on Win32 threads since no POSIX threads + if test "$curl_cv_native_windows" = "yes"; then + USE_THREADS_WIN32=1 + AC_DEFINE(USE_THREADS_WIN32, 1, [if you want Win32 threaded DNS lookup]) + curl_res_msg="Win32 threaded" + else + AC_MSG_ERROR([Threaded resolver enabled but no thread library found]) + fi +fi + +AC_CHECK_HEADER(dirent.h, + [ AC_DEFINE(HAVE_DIRENT_H, 1, [if you have ]) + AC_CHECK_FUNC(opendir, AC_DEFINE(HAVE_OPENDIR, 1, [if you have opendir]) ) + ] +) + +CURL_CONVERT_INCLUDE_TO_ISYSTEM + +dnl ************************************************************ +dnl disable verbose text strings +dnl +AC_MSG_CHECKING([whether to enable verbose strings]) +AC_ARG_ENABLE(verbose, +AS_HELP_STRING([--enable-verbose],[Enable verbose strings]) +AS_HELP_STRING([--disable-verbose],[Disable verbose strings]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_VERBOSE_STRINGS, 1, [to disable verbose strings]) + curl_verbose_msg="no" + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl enable SSPI support +dnl +AC_MSG_CHECKING([whether to enable SSPI support (Windows native builds only)]) +AC_ARG_ENABLE(sspi, +AS_HELP_STRING([--enable-sspi],[Enable SSPI]) +AS_HELP_STRING([--disable-sspi],[Disable SSPI]), +[ case "$enableval" in + yes) + if test "$curl_cv_native_windows" = "yes"; then + AC_MSG_RESULT(yes) + AC_DEFINE(USE_WINDOWS_SSPI, 1, [to enable SSPI support]) + AC_SUBST(USE_WINDOWS_SSPI, [1]) + curl_sspi_msg="enabled" + else + AC_MSG_RESULT(no) + AC_MSG_WARN([--enable-sspi Ignored. Only supported on native Windows builds.]) + fi + ;; + *) + if test "x$SCHANNEL_ENABLED" = "x1"; then + # --with-schannel implies --enable-sspi + AC_MSG_RESULT(yes) + else + AC_MSG_RESULT(no) + fi + ;; + esac ], + if test "x$SCHANNEL_ENABLED" = "x1"; then + # --with-schannel implies --enable-sspi + AC_MSG_RESULT(yes) + else + AC_MSG_RESULT(no) + fi +) + +dnl ************************************************************ +dnl disable basic authentication +dnl +AC_MSG_CHECKING([whether to enable basic authentication method]) +AC_ARG_ENABLE(basic-auth, +AS_HELP_STRING([--enable-basic-auth],[Enable basic authentication (default)]) +AS_HELP_STRING([--disable-basic-auth],[Disable basic authentication]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_BASIC_AUTH, 1, [to disable basic authentication]) + CURL_DISABLE_BASIC_AUTH=1 + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable bearer authentication +dnl +AC_MSG_CHECKING([whether to enable bearer authentication method]) +AC_ARG_ENABLE(bearer-auth, +AS_HELP_STRING([--enable-bearer-auth],[Enable bearer authentication (default)]) +AS_HELP_STRING([--disable-bearer-auth],[Disable bearer authentication]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_BEARER_AUTH, 1, [to disable bearer authentication]) + CURL_DISABLE_BEARER_AUTH=1 + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable digest authentication +dnl +AC_MSG_CHECKING([whether to enable digest authentication method]) +AC_ARG_ENABLE(digest-auth, +AS_HELP_STRING([--enable-digest-auth],[Enable digest authentication (default)]) +AS_HELP_STRING([--disable-digest-auth],[Disable digest authentication]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_DIGEST_AUTH, 1, [to disable digest authentication]) + CURL_DISABLE_DIGEST_AUTH=1 + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable kerberos authentication +dnl +AC_MSG_CHECKING([whether to enable kerberos authentication method]) +AC_ARG_ENABLE(kerberos-auth, +AS_HELP_STRING([--enable-kerberos-auth],[Enable kerberos authentication (default)]) +AS_HELP_STRING([--disable-kerberos-auth],[Disable kerberos authentication]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_KERBEROS_AUTH, 1, [to disable kerberos authentication]) + CURL_DISABLE_KERBEROS_AUTH=1 + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable negotiate authentication +dnl +AC_MSG_CHECKING([whether to enable negotiate authentication method]) +AC_ARG_ENABLE(negotiate-auth, +AS_HELP_STRING([--enable-negotiate-auth],[Enable negotiate authentication (default)]) +AS_HELP_STRING([--disable-negotiate-auth],[Disable negotiate authentication]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_NEGOTIATE_AUTH, 1, [to disable negotiate authentication]) + CURL_DISABLE_NEGOTIATE_AUTH=1 + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + + +dnl ************************************************************ +dnl disable aws +dnl +AC_MSG_CHECKING([whether to enable aws sig methods]) +AC_ARG_ENABLE(aws, +AS_HELP_STRING([--enable-aws],[Enable AWS sig support (default)]) +AS_HELP_STRING([--disable-aws],[Disable AWS sig support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_AWS, 1, [to disable AWS sig support]) + CURL_DISABLE_AWS=1 + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable NTLM support +dnl +AC_MSG_CHECKING([whether to support NTLM]) +AC_ARG_ENABLE(ntlm, +AS_HELP_STRING([--enable-ntlm],[Enable NTLM support]) +AS_HELP_STRING([--disable-ntlm],[Disable NTLM support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_NTLM, 1, [to disable NTLM support]) + CURL_DISABLE_NTLM=1 + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable TLS-SRP authentication +dnl +AC_MSG_CHECKING([whether to enable TLS-SRP authentication]) +AC_ARG_ENABLE(tls-srp, +AS_HELP_STRING([--enable-tls-srp],[Enable TLS-SRP authentication]) +AS_HELP_STRING([--disable-tls-srp],[Disable TLS-SRP authentication]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + want_tls_srp=no + ;; + *) AC_MSG_RESULT(yes) + want_tls_srp=yes + ;; + esac ], + AC_MSG_RESULT(yes) + want_tls_srp=yes +) + +if test "$want_tls_srp" = "yes" && ( test "x$HAVE_GNUTLS_SRP" = "x1" || test "x$HAVE_OPENSSL_SRP" = "x1") ; then + AC_DEFINE(USE_TLS_SRP, 1, [Use TLS-SRP authentication]) + USE_TLS_SRP=1 + curl_tls_srp_msg="enabled" +fi + +dnl ************************************************************ +dnl disable Unix domain sockets support +dnl +AC_MSG_CHECKING([whether to enable Unix domain sockets]) +AC_ARG_ENABLE(unix-sockets, +AS_HELP_STRING([--enable-unix-sockets],[Enable Unix domain sockets]) +AS_HELP_STRING([--disable-unix-sockets],[Disable Unix domain sockets]), +[ case "$enableval" in + no) AC_MSG_RESULT(no) + want_unix_sockets=no + ;; + *) AC_MSG_RESULT(yes) + want_unix_sockets=yes + ;; + esac ], [ + AC_MSG_RESULT(auto) + want_unix_sockets=auto + ] +) +if test "x$want_unix_sockets" != "xno"; then + if test "x$curl_cv_native_windows" = "xyes"; then + USE_UNIX_SOCKETS=1 + AC_DEFINE(USE_UNIX_SOCKETS, 1, [Use Unix domain sockets]) + curl_unix_sockets_msg="enabled" + else + AC_CHECK_MEMBER([struct sockaddr_un.sun_path], [ + AC_DEFINE(USE_UNIX_SOCKETS, 1, [Use Unix domain sockets]) + AC_SUBST(USE_UNIX_SOCKETS, [1]) + curl_unix_sockets_msg="enabled" + ], [ + if test "x$want_unix_sockets" = "xyes"; then + AC_MSG_ERROR([--enable-unix-sockets is not available on this platform!]) + fi + ], [ + #include + ]) + fi +fi + +dnl ************************************************************ +dnl disable cookies support +dnl +AC_MSG_CHECKING([whether to support cookies]) +AC_ARG_ENABLE(cookies, +AS_HELP_STRING([--enable-cookies],[Enable cookies support]) +AS_HELP_STRING([--disable-cookies],[Disable cookies support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_COOKIES, 1, [to disable cookies support]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable socketpair +dnl +AC_MSG_CHECKING([whether to support socketpair]) +AC_ARG_ENABLE(socketpair, +AS_HELP_STRING([--enable-socketpair],[Enable socketpair support]) +AS_HELP_STRING([--disable-socketpair],[Disable socketpair support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_SOCKETPAIR, 1, [to disable socketpair support]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable HTTP authentication support +dnl +AC_MSG_CHECKING([whether to support HTTP authentication]) +AC_ARG_ENABLE(http-auth, +AS_HELP_STRING([--enable-http-auth],[Enable HTTP authentication support]) +AS_HELP_STRING([--disable-http-auth],[Disable HTTP authentication support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_HTTP_AUTH, 1, [disable HTTP authentication]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable DoH support +dnl +AC_MSG_CHECKING([whether to support DoH]) +AC_ARG_ENABLE(doh, +AS_HELP_STRING([--enable-doh],[Enable DoH support]) +AS_HELP_STRING([--disable-doh],[Disable DoH support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_DOH, 1, [disable DoH]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable mime API support +dnl +AC_MSG_CHECKING([whether to support the MIME API]) +AC_ARG_ENABLE(mime, +AS_HELP_STRING([--enable-mime],[Enable mime API support]) +AS_HELP_STRING([--disable-mime],[Disable mime API support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_MIME, 1, [disable mime API]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable bindlocal +dnl +AC_MSG_CHECKING([whether to support binding connections locally]) +AC_ARG_ENABLE(bindlocal, +AS_HELP_STRING([--enable-bindlocal],[Enable local binding support]) +AS_HELP_STRING([--disable-bindlocal],[Disable local binding support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_BINDLOCAL, 1, [disable local binding support]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable form API support +dnl +AC_MSG_CHECKING([whether to support the form API]) +AC_ARG_ENABLE(form-api, +AS_HELP_STRING([--enable-form-api],[Enable form API support]) +AS_HELP_STRING([--disable-form-api],[Disable form API support]), +[ case "$enableval" in + no) AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_FORM_API, 1, [disable form API]) + ;; + *) AC_MSG_RESULT(yes) + test "$enable_mime" = no && + AC_MSG_ERROR(MIME support needs to be enabled in order to enable form API support) + ;; + esac ], +[ + if test "$enable_mime" = no; then + enable_form_api=no + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_FORM_API, 1, [disable form API]) + else + AC_MSG_RESULT(yes) + fi ] +) + +dnl ************************************************************ +dnl disable date parsing +dnl +AC_MSG_CHECKING([whether to support date parsing]) +AC_ARG_ENABLE(dateparse, +AS_HELP_STRING([--enable-dateparse],[Enable date parsing]) +AS_HELP_STRING([--disable-dateparse],[Disable date parsing]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_PARSEDATE, 1, [disable date parsing]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable netrc +dnl +AC_MSG_CHECKING([whether to support netrc parsing]) +AC_ARG_ENABLE(netrc, +AS_HELP_STRING([--enable-netrc],[Enable netrc parsing]) +AS_HELP_STRING([--disable-netrc],[Disable netrc parsing]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_NETRC, 1, [disable netrc parsing]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable progress-meter +dnl +AC_MSG_CHECKING([whether to support progress-meter]) +AC_ARG_ENABLE(progress-meter, +AS_HELP_STRING([--enable-progress-meter],[Enable progress-meter]) +AS_HELP_STRING([--disable-progress-meter],[Disable progress-meter]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_PROGRESS_METER, 1, [disable progress-meter]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable shuffle DNS support +dnl +AC_MSG_CHECKING([whether to support DNS shuffling]) +AC_ARG_ENABLE(dnsshuffle, +AS_HELP_STRING([--enable-dnsshuffle],[Enable DNS shuffling]) +AS_HELP_STRING([--disable-dnsshuffle],[Disable DNS shuffling]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_SHUFFLE_DNS, 1, [disable DNS shuffling]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable the curl_easy_options API +dnl +AC_MSG_CHECKING([whether to support curl_easy_option*]) +AC_ARG_ENABLE(get-easy-options, +AS_HELP_STRING([--enable-get-easy-options],[Enable curl_easy_options]) +AS_HELP_STRING([--disable-get-easy-options],[Disable curl_easy_options]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_GETOPTIONS, 1, [to disable curl_easy_options]) + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl switch on/off alt-svc +dnl +AC_MSG_CHECKING([whether to support alt-svc]) +AC_ARG_ENABLE(alt-svc, +AS_HELP_STRING([--enable-alt-svc],[Enable alt-svc support]) +AS_HELP_STRING([--disable-alt-svc],[Disable alt-svc support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_ALTSVC, 1, [disable alt-svc]) + curl_altsvc_msg="no"; + enable_altsvc="no" + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl switch on/off headers-api +dnl +AC_MSG_CHECKING([whether to support headers-api]) +AC_ARG_ENABLE(headers-api, +AS_HELP_STRING([--enable-headers-api],[Enable headers-api support]) +AS_HELP_STRING([--disable-headers-api],[Disable headers-api support]), +[ case "$enableval" in + no) AC_MSG_RESULT(no) + curl_headers_msg="no (--enable-headers-api)" + AC_DEFINE(CURL_DISABLE_HEADERS_API, 1, [disable headers-api]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl only check for HSTS if there's SSL present +if test -n "$SSL_ENABLED"; then + dnl ************************************************************ + dnl switch on/off hsts + dnl + AC_MSG_CHECKING([whether to support HSTS]) + AC_ARG_ENABLE(hsts, +AS_HELP_STRING([--enable-hsts],[Enable HSTS support]) +AS_HELP_STRING([--disable-hsts],[Disable HSTS support]), + [ case "$enableval" in + no) + AC_MSG_RESULT(no) + hsts="no" + ;; + *) AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT($hsts) + ) +else + AC_MSG_NOTICE([disables HSTS due to lack of SSL]) + hsts="no" +fi + +if test "x$hsts" != "xyes"; then + curl_hsts_msg="no (--enable-hsts)"; + AC_DEFINE(CURL_DISABLE_HSTS, 1, [disable alt-svc]) +fi + + +dnl ************************************************************* +dnl check whether HTTPSRR support if desired +dnl +if test "x$want_httpsrr" != "xno"; then + AC_MSG_RESULT([HTTPSRR support is available]) + AC_DEFINE(USE_HTTPSRR, 1, [enable HTTPS RR support]) + experimental="$experimental HTTPSRR" +fi + +dnl ************************************************************* +dnl check whether ECH support, if desired, is actually available +dnl +if test "x$want_ech" != "xno"; then + AC_MSG_CHECKING([whether ECH support is available]) + + dnl assume NOT and look for sufficient condition + ECH_ENABLED=0 + ECH_SUPPORT='' + + dnl check for OpenSSL + if test "x$OPENSSL_ENABLED" = "x1"; then + AC_CHECK_FUNCS(SSL_ech_set1_echconfig, + ECH_SUPPORT="ECH support available via OpenSSL with SSL_ech_set1_echconfig" + ECH_ENABLED=1) + fi + dnl check for boringssl equivalent + if test "x$OPENSSL_ENABLED" = "x1"; then + AC_CHECK_FUNCS(SSL_set1_ech_config_list, + ECH_SUPPORT="ECH support available via boringssl with SSL_set1_ech_config_list" + ECH_ENABLED=1) + fi + if test "x$WOLFSSL_ENABLED" = "x1"; then + AC_CHECK_FUNCS(wolfSSL_CTX_GenerateEchConfig, + ECH_SUPPORT="ECH support available via WolfSSL with wolfSSL_CTX_GenerateEchConfig" + ECH_ENABLED=1) + fi + + dnl now deal with whatever we found + if test "x$ECH_ENABLED" = "x1"; then + dnl force pre-requisites for ECH + AC_DEFINE(USE_HTTPSRR, 1, [force HTTPS RR support for ECH]) + AC_DEFINE(USE_ECH, 1, [if ECH support is available]) + AC_MSG_RESULT($ECH_SUPPORT) + experimental="$experimental ECH" + else + AC_MSG_ERROR([--enable-ech ignored: No ECH support found]) + fi +fi + +dnl ************************************************************* +dnl check whether OpenSSL (lookalikes) have SSL_set0_wbio +dnl +if test "x$OPENSSL_ENABLED" = "x1"; then + AC_CHECK_FUNCS([SSL_set0_wbio]) +fi + +dnl ************************************************************* +dnl WebSockets +dnl +AC_MSG_CHECKING([whether to support WebSockets]) +AC_ARG_ENABLE(websockets, +AS_HELP_STRING([--enable-websockets],[Enable WebSockets support]) +AS_HELP_STRING([--disable-websockets],[Disable WebSockets support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + ;; + *) + if test ${ac_cv_sizeof_curl_off_t} -gt 4; then + AC_MSG_RESULT(yes) + curl_ws_msg="enabled" + AC_DEFINE_UNQUOTED(USE_WEBSOCKETS, [1], [enable websockets support]) + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS WS" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS WSS" + fi + experimental="$experimental Websockets" + else + dnl websockets requires >32 bit curl_off_t + AC_MSG_RESULT(no) + AC_MSG_WARN([Websockets disabled due to lack of >32 bit curl_off_t]) + fi + ;; + esac ], + AC_MSG_RESULT(no) +) + + +dnl ************************************************************ +dnl hiding of library internal symbols +dnl +CURL_CONFIGURE_SYMBOL_HIDING + +dnl +dnl All the library dependencies put into $LIB apply to libcurl only. +dnl +LIBCURL_LIBS="$LIBS$PTHREAD" + +AC_SUBST(LIBCURL_LIBS) +AC_SUBST(CURL_NETWORK_LIBS) +AC_SUBST(CURL_NETWORK_AND_TIME_LIBS) + +dnl BLANK_AT_MAKETIME may be used in our Makefile.am files to blank +dnl LIBS variable used in generated makefile at makefile processing +dnl time. Doing this functionally prevents LIBS from being used for +dnl all link targets in given makefile. +BLANK_AT_MAKETIME= +AC_SUBST(BLANK_AT_MAKETIME) + +AM_CONDITIONAL(CROSSCOMPILING, test x$cross_compiling = xyes) + +dnl yes or no +ENABLE_SHARED="$enable_shared" +AC_SUBST(ENABLE_SHARED) + +dnl to let curl-config output the static libraries correctly +ENABLE_STATIC="$enable_static" +AC_SUBST(ENABLE_STATIC) + +dnl merge the pkg-config Libs.private field into Libs when static-only +if test "x$enable_shared" = "xno"; then + LIBCURL_NO_SHARED=$LIBCURL_LIBS +else + LIBCURL_NO_SHARED= +fi +AC_SUBST(LIBCURL_NO_SHARED) + +rm $compilersh + +dnl +dnl For keeping supported features and protocols also in pkg-config file +dnl since it is more cross-compile friendly than curl-config +dnl + +if test "x$OPENSSL_ENABLED" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES SSL" +elif test -n "$SSL_ENABLED"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES SSL" +fi +if test "x$IPV6_ENABLED" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES IPv6" +fi +if test "x$USE_UNIX_SOCKETS" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES UnixSockets" +fi +if test "x$HAVE_LIBZ" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES libz" +fi +if test "x$HAVE_BROTLI" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES brotli" +fi +if test "x$HAVE_ZSTD" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES zstd" +fi +if test "x$USE_ARES" = "x1" -o "x$USE_THREADS_POSIX" = "x1" \ + -o "x$USE_THREADS_WIN32" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES AsynchDNS" +fi +if test "x$IDN_ENABLED" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES IDN" +fi +if test "x$USE_WINDOWS_SSPI" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES SSPI" +fi + +if test "x$HAVE_GSSAPI" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES GSS-API" +fi + +if test "x$curl_psl_msg" = "xenabled"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES PSL" +fi + +if test "x$curl_gsasl_msg" = "xenabled"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES GSASL" +fi + +if test "x$enable_altsvc" = "xyes"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES alt-svc" +fi +if test "x$hsts" = "xyes"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES HSTS" +fi + +if test "x$CURL_DISABLE_NEGOTIATE_AUTH" != "x1" -a \ + \( "x$HAVE_GSSAPI" = "x1" -o "x$USE_WINDOWS_SSPI" = "x1" \); then + SUPPORT_FEATURES="$SUPPORT_FEATURES SPNEGO" +fi + +if test "x$CURL_DISABLE_KERBEROS_AUTH" != "x1" -a \ + \( "x$HAVE_GSSAPI" = "x1" -o "x$USE_WINDOWS_SSPI" = "x1" \); then + SUPPORT_FEATURES="$SUPPORT_FEATURES Kerberos" +fi + +use_curl_ntlm_core=no + +if test "x$CURL_DISABLE_NTLM" != "x1"; then + if test "x$OPENSSL_ENABLED" = "x1" -o "x$MBEDTLS_ENABLED" = "x1" \ + -o "x$GNUTLS_ENABLED" = "x1" \ + -o "x$SECURETRANSPORT_ENABLED" = "x1" \ + -o "x$USE_WIN32_CRYPTO" = "x1" \ + -o "x$WOLFSSL_NTLM" = "x1"; then + use_curl_ntlm_core=yes + fi + + if test "x$use_curl_ntlm_core" = "xyes" \ + -o "x$USE_WINDOWS_SSPI" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES NTLM" + fi +fi + +if test "x$USE_TLS_SRP" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES TLS-SRP" +fi + +if test "x$USE_NGHTTP2" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES HTTP2" +fi + +if test "x$USE_NGTCP2_H3" = "x1" -o "x$USE_QUICHE" = "x1" \ + -o "x$USE_OPENSSL_H3" = "x1" -o "x$USE_MSH3" = "x1"; then + if test "x$CURL_WITH_MULTI_SSL" = "x1"; then + AC_MSG_ERROR([MultiSSL cannot be enabled with HTTP/3 and vice versa]) + fi + SUPPORT_FEATURES="$SUPPORT_FEATURES HTTP3" +fi + +if test "x$CURL_WITH_MULTI_SSL" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES MultiSSL" +fi + +AC_MSG_CHECKING([if this build supports HTTPS-proxy]) +dnl if not explicitly turned off, HTTPS-proxy comes with some TLS backends +if test "x$CURL_DISABLE_HTTP" != "x1"; then + if test "x$https_proxy" != "xno"; then + if test "x$OPENSSL_ENABLED" = "x1" \ + -o "x$GNUTLS_ENABLED" = "x1" \ + -o "x$SECURETRANSPORT_ENABLED" = "x1" \ + -o "x$RUSTLS_ENABLED" = "x1" \ + -o "x$BEARSSL_ENABLED" = "x1" \ + -o "x$SCHANNEL_ENABLED" = "x1" \ + -o "x$GNUTLS_ENABLED" = "x1" \ + -o "x$MBEDTLS_ENABLED" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES HTTPS-proxy" + AC_MSG_RESULT([yes]) + elif test "x$WOLFSSL_ENABLED" = "x1" -a "x$WOLFSSL_FULL_BIO" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES HTTPS-proxy" + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + fi + else + AC_MSG_RESULT([no]) + fi +else + AC_MSG_RESULT([no]) +fi + +if test ${ac_cv_sizeof_curl_off_t} -gt 4; then + if test ${ac_cv_sizeof_off_t} -gt 4 -o \ + "$curl_win32_file_api" = "win32_large_files"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES Largefile" + fi +fi + +if test "$tst_atomic" = "yes"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES threadsafe" +elif test "x$USE_THREADS_POSIX" = "x1" -a \ + "x$ac_cv_header_pthread_h" = "xyes"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES threadsafe" +else + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + #include + ]],[[ + #if (WINVER < 0x600) && (_WIN32_WINNT < 0x600) + #error + #endif + ]]) + ],[ + SUPPORT_FEATURES="$SUPPORT_FEATURES threadsafe" + ],[ + ]) +fi + +dnl replace spaces with newlines +dnl sort the lines +dnl replace the newlines back to spaces +SUPPORT_FEATURES=`echo $SUPPORT_FEATURES | tr ' ' '\012' | sort | tr '\012' ' '` +AC_SUBST(SUPPORT_FEATURES) + +dnl For supported protocols in pkg-config file +if test "x$CURL_DISABLE_HTTP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS HTTP IPFS IPNS" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS HTTPS" + fi +fi +if test "x$CURL_DISABLE_FTP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS FTP" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS FTPS" + fi +fi +if test "x$CURL_DISABLE_FILE" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS FILE" +fi +if test "x$CURL_DISABLE_TELNET" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS TELNET" +fi +if test "x$CURL_DISABLE_LDAP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS LDAP" + if test "x$CURL_DISABLE_LDAPS" != "x1"; then + if (test "x$USE_OPENLDAP" = "x1" && test "x$SSL_ENABLED" = "x1") || + (test "x$USE_OPENLDAP" != "x1" && test "x$HAVE_LDAP_SSL" = "x1"); then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS LDAPS" + fi + fi +fi +if test "x$CURL_DISABLE_DICT" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS DICT" +fi +if test "x$CURL_DISABLE_TFTP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS TFTP" +fi +if test "x$CURL_DISABLE_GOPHER" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS GOPHER" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS GOPHERS" + fi +fi +if test "x$CURL_DISABLE_MQTT" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS MQTT" +fi +if test "x$CURL_DISABLE_POP3" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS POP3" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS POP3S" + fi +fi +if test "x$CURL_DISABLE_IMAP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS IMAP" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS IMAPS" + fi +fi +if test "x$CURL_DISABLE_SMB" != "x1" \ + -a "x$use_curl_ntlm_core" = "xyes"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SMB" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SMBS" + fi +fi +if test "x$CURL_DISABLE_SMTP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SMTP" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SMTPS" + fi +fi +if test "x$USE_LIBSSH2" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SCP" + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SFTP" +fi +if test "x$USE_LIBSSH" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SCP" + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SFTP" +fi +if test "x$USE_WOLFSSH" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SFTP" +fi +if test "x$CURL_DISABLE_RTSP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS RTSP" +fi +if test "x$USE_LIBRTMP" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS RTMP" +fi + +dnl replace spaces with newlines +dnl sort the lines +dnl replace the newlines back to spaces +SUPPORT_PROTOCOLS=`echo $SUPPORT_PROTOCOLS | tr ' ' '\012' | sort | tr '\012' ' '` + +AC_SUBST(SUPPORT_PROTOCOLS) + +dnl squeeze whitespace out of some variables + +squeeze CFLAGS +squeeze CPPFLAGS +squeeze DEFS +squeeze LDFLAGS +squeeze LIBS + +squeeze LIBCURL_LIBS +squeeze CURL_NETWORK_LIBS +squeeze CURL_NETWORK_AND_TIME_LIBS + +squeeze SUPPORT_FEATURES +squeeze SUPPORT_PROTOCOLS + +XC_CHECK_BUILD_FLAGS + +SSL_BACKENDS=${ssl_backends} +AC_SUBST(SSL_BACKENDS) + +if test "x$want_curldebug_assumed" = "xyes" && + test "x$want_curldebug" = "xyes" && test "x$USE_ARES" = "x1"; then + ac_configure_args="$ac_configure_args --enable-curldebug" +fi + +AC_CONFIG_FILES([Makefile \ + docs/Makefile \ + docs/examples/Makefile \ + docs/libcurl/Makefile \ + docs/libcurl/opts/Makefile \ + docs/cmdline-opts/Makefile \ + include/Makefile \ + include/curl/Makefile \ + src/Makefile \ + lib/Makefile \ + scripts/Makefile \ + lib/libcurl.vers \ + tests/Makefile \ + tests/config \ + tests/certs/Makefile \ + tests/certs/scripts/Makefile \ + tests/data/Makefile \ + tests/server/Makefile \ + tests/libtest/Makefile \ + tests/unit/Makefile \ + tests/http/config.ini \ + tests/http/Makefile \ + tests/http/clients/Makefile \ + packages/Makefile \ + packages/vms/Makefile \ + curl-config \ + libcurl.pc +]) +AC_OUTPUT + +CURL_GENERATE_CONFIGUREHELP_PM + +AC_MSG_NOTICE([Configured to build curl/libcurl: + + Host setup: ${host} + Install prefix: ${prefix} + Compiler: ${CC} + CFLAGS: ${CFLAGS} + CPPFLAGS: ${CPPFLAGS} + LDFLAGS: ${LDFLAGS} + LIBS: ${LIBS} + + curl version: ${CURLVERSION} + SSL: ${curl_ssl_msg} + SSH: ${curl_ssh_msg} + zlib: ${curl_zlib_msg} + brotli: ${curl_brotli_msg} + zstd: ${curl_zstd_msg} + GSS-API: ${curl_gss_msg} + GSASL: ${curl_gsasl_msg} + TLS-SRP: ${curl_tls_srp_msg} + resolver: ${curl_res_msg} + IPv6: ${curl_ipv6_msg} + Unix sockets: ${curl_unix_sockets_msg} + IDN: ${curl_idn_msg} + Build docs: ${curl_docs_msg} + Build libcurl: Shared=${enable_shared}, Static=${enable_static} + Built-in manual: ${curl_manual_msg} + --libcurl option: ${curl_libcurl_msg} + Verbose errors: ${curl_verbose_msg} + Code coverage: ${curl_coverage_msg} + SSPI: ${curl_sspi_msg} + ca cert bundle: ${ca}${ca_warning} + ca cert path: ${capath}${capath_warning} + ca fallback: ${with_ca_fallback} + LDAP: ${curl_ldap_msg} + LDAPS: ${curl_ldaps_msg} + RTSP: ${curl_rtsp_msg} + RTMP: ${curl_rtmp_msg} + PSL: ${curl_psl_msg} + Alt-svc: ${curl_altsvc_msg} + Headers API: ${curl_headers_msg} + HSTS: ${curl_hsts_msg} + HTTP1: ${curl_h1_msg} + HTTP2: ${curl_h2_msg} + HTTP3: ${curl_h3_msg} + ECH: ${curl_ech_msg} + WebSockets: ${curl_ws_msg} + Protocols: ${SUPPORT_PROTOCOLS} + Features: ${SUPPORT_FEATURES} +]) + +non13=`echo "$TLSCHOICE" | grep -Ei 'bearssl|secure-transport|mbedtls'`; +if test -n "$non13"; then + cat >&2 << _EOF + WARNING: A selected TLS library ($TLSCHOICE) does not support TLS 1.3! +_EOF +fi + +if test -n "$experimental"; then + cat >&2 << _EOF + WARNING: $experimental enabled but marked EXPERIMENTAL. Use with caution! +_EOF +fi diff --git a/third_party/curl/curl-config.in b/third_party/curl/curl-config.in new file mode 100644 index 0000000..085bb1e --- /dev/null +++ b/third_party/curl/curl-config.in @@ -0,0 +1,193 @@ +#!/bin/sh +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +prefix="@prefix@" +# Used in @libdir@ +# shellcheck disable=SC2034 +exec_prefix=@exec_prefix@ +# shellcheck disable=SC2034 +includedir=@includedir@ +cppflag_curl_staticlib=@CPPFLAG_CURL_STATICLIB@ + +usage() +{ + cat <&2 + exit 1 + fi + ;; + + --configure) + echo @CONFIGURE_OPTIONS@ + ;; + + *) + echo "unknown option: $1" + usage 1 + ;; + esac + shift +done + +exit 0 diff --git a/third_party/curl/depcomp b/third_party/curl/depcomp new file mode 100755 index 0000000..715e343 --- /dev/null +++ b/third_party/curl/depcomp @@ -0,0 +1,791 @@ +#! /bin/sh +# depcomp - compile a program generating dependencies as side-effects + +scriptversion=2018-03-07.03; # UTC + +# Copyright (C) 1999-2021 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# Originally written by Alexandre Oliva . + +case $1 in + '') + echo "$0: No command. Try '$0 --help' for more information." 1>&2 + exit 1; + ;; + -h | --h*) + cat <<\EOF +Usage: depcomp [--help] [--version] PROGRAM [ARGS] + +Run PROGRAMS ARGS to compile a file, generating dependencies +as side-effects. + +Environment variables: + depmode Dependency tracking mode. + source Source file read by 'PROGRAMS ARGS'. + object Object file output by 'PROGRAMS ARGS'. + DEPDIR directory where to store dependencies. + depfile Dependency file to output. + tmpdepfile Temporary file to use when outputting dependencies. + libtool Whether libtool is used (yes/no). + +Report bugs to . +EOF + exit $? + ;; + -v | --v*) + echo "depcomp $scriptversion" + exit $? + ;; +esac + +# Get the directory component of the given path, and save it in the +# global variables '$dir'. Note that this directory component will +# be either empty or ending with a '/' character. This is deliberate. +set_dir_from () +{ + case $1 in + */*) dir=`echo "$1" | sed -e 's|/[^/]*$|/|'`;; + *) dir=;; + esac +} + +# Get the suffix-stripped basename of the given path, and save it the +# global variable '$base'. +set_base_from () +{ + base=`echo "$1" | sed -e 's|^.*/||' -e 's/\.[^.]*$//'` +} + +# If no dependency file was actually created by the compiler invocation, +# we still have to create a dummy depfile, to avoid errors with the +# Makefile "include basename.Plo" scheme. +make_dummy_depfile () +{ + echo "#dummy" > "$depfile" +} + +# Factor out some common post-processing of the generated depfile. +# Requires the auxiliary global variable '$tmpdepfile' to be set. +aix_post_process_depfile () +{ + # If the compiler actually managed to produce a dependency file, + # post-process it. + if test -f "$tmpdepfile"; then + # Each line is of the form 'foo.o: dependency.h'. + # Do two passes, one to just change these to + # $object: dependency.h + # and one to simply output + # dependency.h: + # which is needed to avoid the deleted-header problem. + { sed -e "s,^.*\.[$lower]*:,$object:," < "$tmpdepfile" + sed -e "s,^.*\.[$lower]*:[$tab ]*,," -e 's,$,:,' < "$tmpdepfile" + } > "$depfile" + rm -f "$tmpdepfile" + else + make_dummy_depfile + fi +} + +# A tabulation character. +tab=' ' +# A newline character. +nl=' +' +# Character ranges might be problematic outside the C locale. +# These definitions help. +upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ +lower=abcdefghijklmnopqrstuvwxyz +digits=0123456789 +alpha=${upper}${lower} + +if test -z "$depmode" || test -z "$source" || test -z "$object"; then + echo "depcomp: Variables source, object and depmode must be set" 1>&2 + exit 1 +fi + +# Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po. +depfile=${depfile-`echo "$object" | + sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`} +tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`} + +rm -f "$tmpdepfile" + +# Avoid interferences from the environment. +gccflag= dashmflag= + +# Some modes work just like other modes, but use different flags. We +# parameterize here, but still list the modes in the big case below, +# to make depend.m4 easier to write. Note that we *cannot* use a case +# here, because this file can only contain one case statement. +if test "$depmode" = hp; then + # HP compiler uses -M and no extra arg. + gccflag=-M + depmode=gcc +fi + +if test "$depmode" = dashXmstdout; then + # This is just like dashmstdout with a different argument. + dashmflag=-xM + depmode=dashmstdout +fi + +cygpath_u="cygpath -u -f -" +if test "$depmode" = msvcmsys; then + # This is just like msvisualcpp but w/o cygpath translation. + # Just convert the backslash-escaped backslashes to single forward + # slashes to satisfy depend.m4 + cygpath_u='sed s,\\\\,/,g' + depmode=msvisualcpp +fi + +if test "$depmode" = msvc7msys; then + # This is just like msvc7 but w/o cygpath translation. + # Just convert the backslash-escaped backslashes to single forward + # slashes to satisfy depend.m4 + cygpath_u='sed s,\\\\,/,g' + depmode=msvc7 +fi + +if test "$depmode" = xlc; then + # IBM C/C++ Compilers xlc/xlC can output gcc-like dependency information. + gccflag=-qmakedep=gcc,-MF + depmode=gcc +fi + +case "$depmode" in +gcc3) +## gcc 3 implements dependency tracking that does exactly what +## we want. Yay! Note: for some reason libtool 1.4 doesn't like +## it if -MD -MP comes after the -MF stuff. Hmm. +## Unfortunately, FreeBSD c89 acceptance of flags depends upon +## the command line argument order; so add the flags where they +## appear in depend2.am. Note that the slowdown incurred here +## affects only configure: in makefiles, %FASTDEP% shortcuts this. + for arg + do + case $arg in + -c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;; + *) set fnord "$@" "$arg" ;; + esac + shift # fnord + shift # $arg + done + "$@" + stat=$? + if test $stat -ne 0; then + rm -f "$tmpdepfile" + exit $stat + fi + mv "$tmpdepfile" "$depfile" + ;; + +gcc) +## Note that this doesn't just cater to obsosete pre-3.x GCC compilers. +## but also to in-use compilers like IMB xlc/xlC and the HP C compiler. +## (see the conditional assignment to $gccflag above). +## There are various ways to get dependency output from gcc. Here's +## why we pick this rather obscure method: +## - Don't want to use -MD because we'd like the dependencies to end +## up in a subdir. Having to rename by hand is ugly. +## (We might end up doing this anyway to support other compilers.) +## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like +## -MM, not -M (despite what the docs say). Also, it might not be +## supported by the other compilers which use the 'gcc' depmode. +## - Using -M directly means running the compiler twice (even worse +## than renaming). + if test -z "$gccflag"; then + gccflag=-MD, + fi + "$@" -Wp,"$gccflag$tmpdepfile" + stat=$? + if test $stat -ne 0; then + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + echo "$object : \\" > "$depfile" + # The second -e expression handles DOS-style file names with drive + # letters. + sed -e 's/^[^:]*: / /' \ + -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile" +## This next piece of magic avoids the "deleted header file" problem. +## The problem is that when a header file which appears in a .P file +## is deleted, the dependency causes make to die (because there is +## typically no way to rebuild the header). We avoid this by adding +## dummy dependencies for each header file. Too bad gcc doesn't do +## this for us directly. +## Some versions of gcc put a space before the ':'. On the theory +## that the space means something, we add a space to the output as +## well. hp depmode also adds that space, but also prefixes the VPATH +## to the object. Take care to not repeat it in the output. +## Some versions of the HPUX 10.20 sed can't process this invocation +## correctly. Breaking it into two sed invocations is a workaround. + tr ' ' "$nl" < "$tmpdepfile" \ + | sed -e 's/^\\$//' -e '/^$/d' -e "s|.*$object$||" -e '/:$/d' \ + | sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +hp) + # This case exists only to let depend.m4 do its work. It works by + # looking at the text of this script. This case will never be run, + # since it is checked for above. + exit 1 + ;; + +sgi) + if test "$libtool" = yes; then + "$@" "-Wp,-MDupdate,$tmpdepfile" + else + "$@" -MDupdate "$tmpdepfile" + fi + stat=$? + if test $stat -ne 0; then + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + + if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files + echo "$object : \\" > "$depfile" + # Clip off the initial element (the dependent). Don't try to be + # clever and replace this with sed code, as IRIX sed won't handle + # lines with more than a fixed number of characters (4096 in + # IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines; + # the IRIX cc adds comments like '#:fec' to the end of the + # dependency line. + tr ' ' "$nl" < "$tmpdepfile" \ + | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' \ + | tr "$nl" ' ' >> "$depfile" + echo >> "$depfile" + # The second pass generates a dummy entry for each header file. + tr ' ' "$nl" < "$tmpdepfile" \ + | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \ + >> "$depfile" + else + make_dummy_depfile + fi + rm -f "$tmpdepfile" + ;; + +xlc) + # This case exists only to let depend.m4 do its work. It works by + # looking at the text of this script. This case will never be run, + # since it is checked for above. + exit 1 + ;; + +aix) + # The C for AIX Compiler uses -M and outputs the dependencies + # in a .u file. In older versions, this file always lives in the + # current directory. Also, the AIX compiler puts '$object:' at the + # start of each line; $object doesn't have directory information. + # Version 6 uses the directory in both cases. + set_dir_from "$object" + set_base_from "$object" + if test "$libtool" = yes; then + tmpdepfile1=$dir$base.u + tmpdepfile2=$base.u + tmpdepfile3=$dir.libs/$base.u + "$@" -Wc,-M + else + tmpdepfile1=$dir$base.u + tmpdepfile2=$dir$base.u + tmpdepfile3=$dir$base.u + "$@" -M + fi + stat=$? + if test $stat -ne 0; then + rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" + exit $stat + fi + + for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" + do + test -f "$tmpdepfile" && break + done + aix_post_process_depfile + ;; + +tcc) + # tcc (Tiny C Compiler) understand '-MD -MF file' since version 0.9.26 + # FIXME: That version still under development at the moment of writing. + # Make that this statement remains true also for stable, released + # versions. + # It will wrap lines (doesn't matter whether long or short) with a + # trailing '\', as in: + # + # foo.o : \ + # foo.c \ + # foo.h \ + # + # It will put a trailing '\' even on the last line, and will use leading + # spaces rather than leading tabs (at least since its commit 0394caf7 + # "Emit spaces for -MD"). + "$@" -MD -MF "$tmpdepfile" + stat=$? + if test $stat -ne 0; then + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + # Each non-empty line is of the form 'foo.o : \' or ' dep.h \'. + # We have to change lines of the first kind to '$object: \'. + sed -e "s|.*:|$object :|" < "$tmpdepfile" > "$depfile" + # And for each line of the second kind, we have to emit a 'dep.h:' + # dummy dependency, to avoid the deleted-header problem. + sed -n -e 's|^ *\(.*\) *\\$|\1:|p' < "$tmpdepfile" >> "$depfile" + rm -f "$tmpdepfile" + ;; + +## The order of this option in the case statement is important, since the +## shell code in configure will try each of these formats in the order +## listed in this file. A plain '-MD' option would be understood by many +## compilers, so we must ensure this comes after the gcc and icc options. +pgcc) + # Portland's C compiler understands '-MD'. + # Will always output deps to 'file.d' where file is the root name of the + # source file under compilation, even if file resides in a subdirectory. + # The object file name does not affect the name of the '.d' file. + # pgcc 10.2 will output + # foo.o: sub/foo.c sub/foo.h + # and will wrap long lines using '\' : + # foo.o: sub/foo.c ... \ + # sub/foo.h ... \ + # ... + set_dir_from "$object" + # Use the source, not the object, to determine the base name, since + # that's sadly what pgcc will do too. + set_base_from "$source" + tmpdepfile=$base.d + + # For projects that build the same source file twice into different object + # files, the pgcc approach of using the *source* file root name can cause + # problems in parallel builds. Use a locking strategy to avoid stomping on + # the same $tmpdepfile. + lockdir=$base.d-lock + trap " + echo '$0: caught signal, cleaning up...' >&2 + rmdir '$lockdir' + exit 1 + " 1 2 13 15 + numtries=100 + i=$numtries + while test $i -gt 0; do + # mkdir is a portable test-and-set. + if mkdir "$lockdir" 2>/dev/null; then + # This process acquired the lock. + "$@" -MD + stat=$? + # Release the lock. + rmdir "$lockdir" + break + else + # If the lock is being held by a different process, wait + # until the winning process is done or we timeout. + while test -d "$lockdir" && test $i -gt 0; do + sleep 1 + i=`expr $i - 1` + done + fi + i=`expr $i - 1` + done + trap - 1 2 13 15 + if test $i -le 0; then + echo "$0: failed to acquire lock after $numtries attempts" >&2 + echo "$0: check lockdir '$lockdir'" >&2 + exit 1 + fi + + if test $stat -ne 0; then + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + # Each line is of the form `foo.o: dependent.h', + # or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'. + # Do two passes, one to just change these to + # `$object: dependent.h' and one to simply `dependent.h:'. + sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile" + # Some versions of the HPUX 10.20 sed can't process this invocation + # correctly. Breaking it into two sed invocations is a workaround. + sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" \ + | sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +hp2) + # The "hp" stanza above does not work with aCC (C++) and HP's ia64 + # compilers, which have integrated preprocessors. The correct option + # to use with these is +Maked; it writes dependencies to a file named + # 'foo.d', which lands next to the object file, wherever that + # happens to be. + # Much of this is similar to the tru64 case; see comments there. + set_dir_from "$object" + set_base_from "$object" + if test "$libtool" = yes; then + tmpdepfile1=$dir$base.d + tmpdepfile2=$dir.libs/$base.d + "$@" -Wc,+Maked + else + tmpdepfile1=$dir$base.d + tmpdepfile2=$dir$base.d + "$@" +Maked + fi + stat=$? + if test $stat -ne 0; then + rm -f "$tmpdepfile1" "$tmpdepfile2" + exit $stat + fi + + for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" + do + test -f "$tmpdepfile" && break + done + if test -f "$tmpdepfile"; then + sed -e "s,^.*\.[$lower]*:,$object:," "$tmpdepfile" > "$depfile" + # Add 'dependent.h:' lines. + sed -ne '2,${ + s/^ *// + s/ \\*$// + s/$/:/ + p + }' "$tmpdepfile" >> "$depfile" + else + make_dummy_depfile + fi + rm -f "$tmpdepfile" "$tmpdepfile2" + ;; + +tru64) + # The Tru64 compiler uses -MD to generate dependencies as a side + # effect. 'cc -MD -o foo.o ...' puts the dependencies into 'foo.o.d'. + # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put + # dependencies in 'foo.d' instead, so we check for that too. + # Subdirectories are respected. + set_dir_from "$object" + set_base_from "$object" + + if test "$libtool" = yes; then + # Libtool generates 2 separate objects for the 2 libraries. These + # two compilations output dependencies in $dir.libs/$base.o.d and + # in $dir$base.o.d. We have to check for both files, because + # one of the two compilations can be disabled. We should prefer + # $dir$base.o.d over $dir.libs/$base.o.d because the latter is + # automatically cleaned when .libs/ is deleted, while ignoring + # the former would cause a distcleancheck panic. + tmpdepfile1=$dir$base.o.d # libtool 1.5 + tmpdepfile2=$dir.libs/$base.o.d # Likewise. + tmpdepfile3=$dir.libs/$base.d # Compaq CCC V6.2-504 + "$@" -Wc,-MD + else + tmpdepfile1=$dir$base.d + tmpdepfile2=$dir$base.d + tmpdepfile3=$dir$base.d + "$@" -MD + fi + + stat=$? + if test $stat -ne 0; then + rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" + exit $stat + fi + + for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" + do + test -f "$tmpdepfile" && break + done + # Same post-processing that is required for AIX mode. + aix_post_process_depfile + ;; + +msvc7) + if test "$libtool" = yes; then + showIncludes=-Wc,-showIncludes + else + showIncludes=-showIncludes + fi + "$@" $showIncludes > "$tmpdepfile" + stat=$? + grep -v '^Note: including file: ' "$tmpdepfile" + if test $stat -ne 0; then + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + echo "$object : \\" > "$depfile" + # The first sed program below extracts the file names and escapes + # backslashes for cygpath. The second sed program outputs the file + # name when reading, but also accumulates all include files in the + # hold buffer in order to output them again at the end. This only + # works with sed implementations that can handle large buffers. + sed < "$tmpdepfile" -n ' +/^Note: including file: *\(.*\)/ { + s//\1/ + s/\\/\\\\/g + p +}' | $cygpath_u | sort -u | sed -n ' +s/ /\\ /g +s/\(.*\)/'"$tab"'\1 \\/p +s/.\(.*\) \\/\1:/ +H +$ { + s/.*/'"$tab"'/ + G + p +}' >> "$depfile" + echo >> "$depfile" # make sure the fragment doesn't end with a backslash + rm -f "$tmpdepfile" + ;; + +msvc7msys) + # This case exists only to let depend.m4 do its work. It works by + # looking at the text of this script. This case will never be run, + # since it is checked for above. + exit 1 + ;; + +#nosideeffect) + # This comment above is used by automake to tell side-effect + # dependency tracking mechanisms from slower ones. + +dashmstdout) + # Important note: in order to support this mode, a compiler *must* + # always write the preprocessed file to stdout, regardless of -o. + "$@" || exit $? + + # Remove the call to Libtool. + if test "$libtool" = yes; then + while test "X$1" != 'X--mode=compile'; do + shift + done + shift + fi + + # Remove '-o $object'. + IFS=" " + for arg + do + case $arg in + -o) + shift + ;; + $object) + shift + ;; + *) + set fnord "$@" "$arg" + shift # fnord + shift # $arg + ;; + esac + done + + test -z "$dashmflag" && dashmflag=-M + # Require at least two characters before searching for ':' + # in the target name. This is to cope with DOS-style filenames: + # a dependency such as 'c:/foo/bar' could be seen as target 'c' otherwise. + "$@" $dashmflag | + sed "s|^[$tab ]*[^:$tab ][^:][^:]*:[$tab ]*|$object: |" > "$tmpdepfile" + rm -f "$depfile" + cat < "$tmpdepfile" > "$depfile" + # Some versions of the HPUX 10.20 sed can't process this sed invocation + # correctly. Breaking it into two sed invocations is a workaround. + tr ' ' "$nl" < "$tmpdepfile" \ + | sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \ + | sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +dashXmstdout) + # This case only exists to satisfy depend.m4. It is never actually + # run, as this mode is specially recognized in the preamble. + exit 1 + ;; + +makedepend) + "$@" || exit $? + # Remove any Libtool call + if test "$libtool" = yes; then + while test "X$1" != 'X--mode=compile'; do + shift + done + shift + fi + # X makedepend + shift + cleared=no eat=no + for arg + do + case $cleared in + no) + set ""; shift + cleared=yes ;; + esac + if test $eat = yes; then + eat=no + continue + fi + case "$arg" in + -D*|-I*) + set fnord "$@" "$arg"; shift ;; + # Strip any option that makedepend may not understand. Remove + # the object too, otherwise makedepend will parse it as a source file. + -arch) + eat=yes ;; + -*|$object) + ;; + *) + set fnord "$@" "$arg"; shift ;; + esac + done + obj_suffix=`echo "$object" | sed 's/^.*\././'` + touch "$tmpdepfile" + ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@" + rm -f "$depfile" + # makedepend may prepend the VPATH from the source file name to the object. + # No need to regex-escape $object, excess matching of '.' is harmless. + sed "s|^.*\($object *:\)|\1|" "$tmpdepfile" > "$depfile" + # Some versions of the HPUX 10.20 sed can't process the last invocation + # correctly. Breaking it into two sed invocations is a workaround. + sed '1,2d' "$tmpdepfile" \ + | tr ' ' "$nl" \ + | sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \ + | sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" "$tmpdepfile".bak + ;; + +cpp) + # Important note: in order to support this mode, a compiler *must* + # always write the preprocessed file to stdout. + "$@" || exit $? + + # Remove the call to Libtool. + if test "$libtool" = yes; then + while test "X$1" != 'X--mode=compile'; do + shift + done + shift + fi + + # Remove '-o $object'. + IFS=" " + for arg + do + case $arg in + -o) + shift + ;; + $object) + shift + ;; + *) + set fnord "$@" "$arg" + shift # fnord + shift # $arg + ;; + esac + done + + "$@" -E \ + | sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ + -e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ + | sed '$ s: \\$::' > "$tmpdepfile" + rm -f "$depfile" + echo "$object : \\" > "$depfile" + cat < "$tmpdepfile" >> "$depfile" + sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +msvisualcpp) + # Important note: in order to support this mode, a compiler *must* + # always write the preprocessed file to stdout. + "$@" || exit $? + + # Remove the call to Libtool. + if test "$libtool" = yes; then + while test "X$1" != 'X--mode=compile'; do + shift + done + shift + fi + + IFS=" " + for arg + do + case "$arg" in + -o) + shift + ;; + $object) + shift + ;; + "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI") + set fnord "$@" + shift + shift + ;; + *) + set fnord "$@" "$arg" + shift + shift + ;; + esac + done + "$@" -E 2>/dev/null | + sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile" + rm -f "$depfile" + echo "$object : \\" > "$depfile" + sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::'"$tab"'\1 \\:p' >> "$depfile" + echo "$tab" >> "$depfile" + sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +msvcmsys) + # This case exists only to let depend.m4 do its work. It works by + # looking at the text of this script. This case will never be run, + # since it is checked for above. + exit 1 + ;; + +none) + exec "$@" + ;; + +*) + echo "Unknown depmode $depmode" 1>&2 + exit 1 + ;; +esac + +exit 0 + +# Local Variables: +# mode: shell-script +# sh-indentation: 2 +# eval: (add-hook 'before-save-hook 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-time-zone: "UTC0" +# time-stamp-end: "; # UTC" +# End: diff --git a/third_party/curl/include/Makefile.am b/third_party/curl/include/Makefile.am new file mode 100644 index 0000000..d65bfea --- /dev/null +++ b/third_party/curl/include/Makefile.am @@ -0,0 +1,28 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +SUBDIRS = curl + +EXTRA_DIST = README.md + +AUTOMAKE_OPTIONS = foreign no-dependencies diff --git a/third_party/curl/include/Makefile.in b/third_party/curl/include/Makefile.in new file mode 100644 index 0000000..f3a7a7d --- /dev/null +++ b/third_party/curl/include/Makefile.in @@ -0,0 +1,774 @@ +# Makefile.in generated by automake 1.16.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994-2021 Free Software Foundation, Inc. + +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ +VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = include +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4/curl-amissl.m4 \ + $(top_srcdir)/m4/curl-bearssl.m4 \ + $(top_srcdir)/m4/curl-compilers.m4 \ + $(top_srcdir)/m4/curl-confopts.m4 \ + $(top_srcdir)/m4/curl-functions.m4 \ + $(top_srcdir)/m4/curl-gnutls.m4 \ + $(top_srcdir)/m4/curl-mbedtls.m4 \ + $(top_srcdir)/m4/curl-openssl.m4 \ + $(top_srcdir)/m4/curl-override.m4 \ + $(top_srcdir)/m4/curl-reentrant.m4 \ + $(top_srcdir)/m4/curl-rustls.m4 \ + $(top_srcdir)/m4/curl-schannel.m4 \ + $(top_srcdir)/m4/curl-sectransp.m4 \ + $(top_srcdir)/m4/curl-sysconfig.m4 \ + $(top_srcdir)/m4/curl-wolfssl.m4 $(top_srcdir)/m4/libtool.m4 \ + $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ + $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ + $(top_srcdir)/m4/xc-am-iface.m4 \ + $(top_srcdir)/m4/xc-cc-check.m4 \ + $(top_srcdir)/m4/xc-lt-iface.m4 \ + $(top_srcdir)/m4/xc-translit.m4 \ + $(top_srcdir)/m4/xc-val-flgs.m4 \ + $(top_srcdir)/m4/zz40-xc-ovr.m4 \ + $(top_srcdir)/m4/zz50-xc-ovr.m4 \ + $(top_srcdir)/m4/zz60-xc-ovr.m4 $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/lib/curl_config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +depcomp = +am__maybe_remake_depfiles = +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ + ctags-recursive dvi-recursive html-recursive info-recursive \ + install-data-recursive install-dvi-recursive \ + install-exec-recursive install-html-recursive \ + install-info-recursive install-pdf-recursive \ + install-ps-recursive install-recursive installcheck-recursive \ + installdirs-recursive pdf-recursive ps-recursive \ + tags-recursive uninstall-recursive +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +am__recursive_targets = \ + $(RECURSIVE_TARGETS) \ + $(RECURSIVE_CLEAN_TARGETS) \ + $(am__extra_recursive_targets) +AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ + distdir distdir-am +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` +DIST_SUBDIRS = $(SUBDIRS) +am__DIST_COMMON = $(srcdir)/Makefile.in README.md +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +APACHECTL = @APACHECTL@ +APXS = @APXS@ +AR = @AR@ +AR_FLAGS = @AR_FLAGS@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +BLANK_AT_MAKETIME = @BLANK_AT_MAKETIME@ +CADDY = @CADDY@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CFLAG_CURL_SYMBOL_HIDING = @CFLAG_CURL_SYMBOL_HIDING@ +CONFIGURE_OPTIONS = @CONFIGURE_OPTIONS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CPPFLAG_CURL_STATICLIB = @CPPFLAG_CURL_STATICLIB@ +CSCOPE = @CSCOPE@ +CTAGS = @CTAGS@ +CURLVERSION = @CURLVERSION@ +CURL_CA_BUNDLE = @CURL_CA_BUNDLE@ +CURL_CFLAG_EXTRAS = @CURL_CFLAG_EXTRAS@ +CURL_DISABLE_DICT = @CURL_DISABLE_DICT@ +CURL_DISABLE_FILE = @CURL_DISABLE_FILE@ +CURL_DISABLE_FTP = @CURL_DISABLE_FTP@ +CURL_DISABLE_GOPHER = @CURL_DISABLE_GOPHER@ +CURL_DISABLE_HTTP = @CURL_DISABLE_HTTP@ +CURL_DISABLE_IMAP = @CURL_DISABLE_IMAP@ +CURL_DISABLE_LDAP = @CURL_DISABLE_LDAP@ +CURL_DISABLE_LDAPS = @CURL_DISABLE_LDAPS@ +CURL_DISABLE_MQTT = @CURL_DISABLE_MQTT@ +CURL_DISABLE_POP3 = @CURL_DISABLE_POP3@ +CURL_DISABLE_PROXY = @CURL_DISABLE_PROXY@ +CURL_DISABLE_RTSP = @CURL_DISABLE_RTSP@ +CURL_DISABLE_SMB = @CURL_DISABLE_SMB@ +CURL_DISABLE_SMTP = @CURL_DISABLE_SMTP@ +CURL_DISABLE_TELNET = @CURL_DISABLE_TELNET@ +CURL_DISABLE_TFTP = @CURL_DISABLE_TFTP@ +CURL_LT_SHLIB_VERSIONED_FLAVOUR = @CURL_LT_SHLIB_VERSIONED_FLAVOUR@ +CURL_NETWORK_AND_TIME_LIBS = @CURL_NETWORK_AND_TIME_LIBS@ +CURL_NETWORK_LIBS = @CURL_NETWORK_LIBS@ +CURL_WITH_MULTI_SSL = @CURL_WITH_MULTI_SSL@ +CYGPATH_W = @CYGPATH_W@ +DEFAULT_SSL_BACKEND = @DEFAULT_SSL_BACKEND@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +ENABLE_SHARED = @ENABLE_SHARED@ +ENABLE_STATIC = @ENABLE_STATIC@ +ETAGS = @ETAGS@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +FILECMD = @FILECMD@ +FISH_FUNCTIONS_DIR = @FISH_FUNCTIONS_DIR@ +GCOV = @GCOV@ +GREP = @GREP@ +HAVE_BROTLI = @HAVE_BROTLI@ +HAVE_GNUTLS_SRP = @HAVE_GNUTLS_SRP@ +HAVE_LDAP_SSL = @HAVE_LDAP_SSL@ +HAVE_LIBZ = @HAVE_LIBZ@ +HAVE_OPENSSL_QUIC = @HAVE_OPENSSL_QUIC@ +HAVE_OPENSSL_SRP = @HAVE_OPENSSL_SRP@ +HAVE_PROTO_BSDSOCKET_H = @HAVE_PROTO_BSDSOCKET_H@ +HAVE_ZSTD = @HAVE_ZSTD@ +HTTPD = @HTTPD@ +HTTPD_NGHTTPX = @HTTPD_NGHTTPX@ +IDN_ENABLED = @IDN_ENABLED@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +IPV6_ENABLED = @IPV6_ENABLED@ +LCOV = @LCOV@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBCURL_LIBS = @LIBCURL_LIBS@ +LIBCURL_NO_SHARED = @LIBCURL_NO_SHARED@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ +MAINT = @MAINT@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PERL = @PERL@ +PKGADD_NAME = @PKGADD_NAME@ +PKGADD_PKG = @PKGADD_PKG@ +PKGADD_VENDOR = @PKGADD_VENDOR@ +PKGCONFIG = @PKGCONFIG@ +RANDOM_FILE = @RANDOM_FILE@ +RANLIB = @RANLIB@ +RC = @RC@ +REQUIRE_LIB_DEPS = @REQUIRE_LIB_DEPS@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SSL_BACKENDS = @SSL_BACKENDS@ +SSL_ENABLED = @SSL_ENABLED@ +SSL_LIBS = @SSL_LIBS@ +STRIP = @STRIP@ +SUPPORT_FEATURES = @SUPPORT_FEATURES@ +SUPPORT_PROTOCOLS = @SUPPORT_PROTOCOLS@ +TEST_NGHTTPX = @TEST_NGHTTPX@ +USE_ARES = @USE_ARES@ +USE_BEARSSL = @USE_BEARSSL@ +USE_GNUTLS = @USE_GNUTLS@ +USE_HYPER = @USE_HYPER@ +USE_LIBPSL = @USE_LIBPSL@ +USE_LIBRTMP = @USE_LIBRTMP@ +USE_LIBSSH = @USE_LIBSSH@ +USE_LIBSSH2 = @USE_LIBSSH2@ +USE_MBEDTLS = @USE_MBEDTLS@ +USE_MSH3 = @USE_MSH3@ +USE_NGHTTP2 = @USE_NGHTTP2@ +USE_NGHTTP3 = @USE_NGHTTP3@ +USE_NGTCP2 = @USE_NGTCP2@ +USE_NGTCP2_CRYPTO_BORINGSSL = @USE_NGTCP2_CRYPTO_BORINGSSL@ +USE_NGTCP2_CRYPTO_GNUTLS = @USE_NGTCP2_CRYPTO_GNUTLS@ +USE_NGTCP2_CRYPTO_QUICTLS = @USE_NGTCP2_CRYPTO_QUICTLS@ +USE_NGTCP2_CRYPTO_WOLFSSL = @USE_NGTCP2_CRYPTO_WOLFSSL@ +USE_NGTCP2_H3 = @USE_NGTCP2_H3@ +USE_OPENLDAP = @USE_OPENLDAP@ +USE_OPENSSL_H3 = @USE_OPENSSL_H3@ +USE_OPENSSL_QUIC = @USE_OPENSSL_QUIC@ +USE_QUICHE = @USE_QUICHE@ +USE_RUSTLS = @USE_RUSTLS@ +USE_SCHANNEL = @USE_SCHANNEL@ +USE_SECTRANSP = @USE_SECTRANSP@ +USE_UNIX_SOCKETS = @USE_UNIX_SOCKETS@ +USE_WIN32_CRYPTO = @USE_WIN32_CRYPTO@ +USE_WIN32_LARGE_FILES = @USE_WIN32_LARGE_FILES@ +USE_WIN32_SMALL_FILES = @USE_WIN32_SMALL_FILES@ +USE_WINDOWS_SSPI = @USE_WINDOWS_SSPI@ +USE_WOLFSSH = @USE_WOLFSSH@ +USE_WOLFSSL = @USE_WOLFSSL@ +VERSION = @VERSION@ +VERSIONNUM = @VERSIONNUM@ +VSFTPD = @VSFTPD@ +ZLIB_LIBS = @ZLIB_LIBS@ +ZSH_FUNCTIONS_DIR = @ZSH_FUNCTIONS_DIR@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +libext = @libext@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +runstatedir = @runstatedir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ + +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +SUBDIRS = curl +EXTRA_DIST = README.md +AUTOMAKE_OPTIONS = foreign no-dependencies +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign include/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign include/Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +# This directory's subdirectories are mostly independent; you can cd +# into them and run 'make' without going through this Makefile. +# To change the values of 'make' variables: instead of editing Makefiles, +# (1) if the variable is set in 'config.status', edit 'config.status' +# (which will cause the Makefiles to be regenerated when you run 'make'); +# (2) otherwise, pass the desired values on the 'make' command line. +$(am__recursive_targets): + @fail=; \ + if $(am__make_keepgoing); then \ + failcom='fail=yes'; \ + else \ + failcom='exit 1'; \ + fi; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-recursive +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: ctags-recursive + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-recursive + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags +distdir: $(BUILT_SOURCES) + $(MAKE) $(AM_MAKEFLAGS) distdir-am + +distdir-am: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + $(am__make_dryrun) \ + || test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ + distdir) \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-recursive +all-am: Makefile +installdirs: installdirs-recursive +installdirs-am: +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: + +install-dvi: install-dvi-recursive + +install-dvi-am: + +install-exec-am: + +install-html: install-html-recursive + +install-html-am: + +install-info: install-info-recursive + +install-info-am: + +install-man: + +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: + +.MAKE: $(am__recursive_targets) install-am install-strip + +.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ + check-am clean clean-generic clean-libtool cscopelist-am ctags \ + ctags-am distclean distclean-generic distclean-libtool \ + distclean-tags distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + installdirs-am maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \ + ps ps-am tags tags-am uninstall uninstall-am + +.PRECIOUS: Makefile + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/third_party/curl/include/README.md b/third_party/curl/include/README.md new file mode 100644 index 0000000..c965932 --- /dev/null +++ b/third_party/curl/include/README.md @@ -0,0 +1,20 @@ + + +# include + +Public include files for libcurl, external users. + +They're all placed in the curl subdirectory here for better fit in any kind of +environment. You must include files from here using... + + #include + +... style and point the compiler's include path to the directory holding the +curl subdirectory. It makes it more likely to survive future modifications. + +The public curl include files can be shared freely between different platforms +and different architectures. diff --git a/third_party/curl/include/curl/Makefile.am b/third_party/curl/include/curl/Makefile.am new file mode 100644 index 0000000..a655aff --- /dev/null +++ b/third_party/curl/include/curl/Makefile.am @@ -0,0 +1,41 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +pkginclude_HEADERS = \ + curl.h curlver.h easy.h mprintf.h stdcheaders.h multi.h \ + typecheck-gcc.h system.h urlapi.h options.h header.h websockets.h + +pkgincludedir= $(includedir)/curl + +CHECKSRC = $(CS_$(V)) +CS_0 = @echo " RUN " $@; +CS_1 = +CS_ = $(CS_0) + +checksrc: + $(CHECKSRC)@PERL@ $(top_srcdir)/scripts/checksrc.pl -D$(top_srcdir)/include/curl $(pkginclude_HEADERS) + +if CURLDEBUG +# for debug builds, we scan the sources on all regular make invokes +all-local: checksrc +endif diff --git a/third_party/curl/include/curl/Makefile.in b/third_party/curl/include/curl/Makefile.in new file mode 100644 index 0000000..878c1a3 --- /dev/null +++ b/third_party/curl/include/curl/Makefile.in @@ -0,0 +1,725 @@ +# Makefile.in generated by automake 1.16.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994-2021 Free Software Foundation, Inc. + +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = include/curl +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4/curl-amissl.m4 \ + $(top_srcdir)/m4/curl-bearssl.m4 \ + $(top_srcdir)/m4/curl-compilers.m4 \ + $(top_srcdir)/m4/curl-confopts.m4 \ + $(top_srcdir)/m4/curl-functions.m4 \ + $(top_srcdir)/m4/curl-gnutls.m4 \ + $(top_srcdir)/m4/curl-mbedtls.m4 \ + $(top_srcdir)/m4/curl-openssl.m4 \ + $(top_srcdir)/m4/curl-override.m4 \ + $(top_srcdir)/m4/curl-reentrant.m4 \ + $(top_srcdir)/m4/curl-rustls.m4 \ + $(top_srcdir)/m4/curl-schannel.m4 \ + $(top_srcdir)/m4/curl-sectransp.m4 \ + $(top_srcdir)/m4/curl-sysconfig.m4 \ + $(top_srcdir)/m4/curl-wolfssl.m4 $(top_srcdir)/m4/libtool.m4 \ + $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ + $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ + $(top_srcdir)/m4/xc-am-iface.m4 \ + $(top_srcdir)/m4/xc-cc-check.m4 \ + $(top_srcdir)/m4/xc-lt-iface.m4 \ + $(top_srcdir)/m4/xc-translit.m4 \ + $(top_srcdir)/m4/xc-val-flgs.m4 \ + $(top_srcdir)/m4/zz40-xc-ovr.m4 \ + $(top_srcdir)/m4/zz50-xc-ovr.m4 \ + $(top_srcdir)/m4/zz60-xc-ovr.m4 $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(pkginclude_HEADERS) \ + $(am__DIST_COMMON) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/lib/curl_config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +SOURCES = +DIST_SOURCES = +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(pkgincludedir)" +HEADERS = $(pkginclude_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` +am__DIST_COMMON = $(srcdir)/Makefile.in +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +pkgincludedir = $(includedir)/curl +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +APACHECTL = @APACHECTL@ +APXS = @APXS@ +AR = @AR@ +AR_FLAGS = @AR_FLAGS@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +BLANK_AT_MAKETIME = @BLANK_AT_MAKETIME@ +CADDY = @CADDY@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CFLAG_CURL_SYMBOL_HIDING = @CFLAG_CURL_SYMBOL_HIDING@ +CONFIGURE_OPTIONS = @CONFIGURE_OPTIONS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CPPFLAG_CURL_STATICLIB = @CPPFLAG_CURL_STATICLIB@ +CSCOPE = @CSCOPE@ +CTAGS = @CTAGS@ +CURLVERSION = @CURLVERSION@ +CURL_CA_BUNDLE = @CURL_CA_BUNDLE@ +CURL_CFLAG_EXTRAS = @CURL_CFLAG_EXTRAS@ +CURL_DISABLE_DICT = @CURL_DISABLE_DICT@ +CURL_DISABLE_FILE = @CURL_DISABLE_FILE@ +CURL_DISABLE_FTP = @CURL_DISABLE_FTP@ +CURL_DISABLE_GOPHER = @CURL_DISABLE_GOPHER@ +CURL_DISABLE_HTTP = @CURL_DISABLE_HTTP@ +CURL_DISABLE_IMAP = @CURL_DISABLE_IMAP@ +CURL_DISABLE_LDAP = @CURL_DISABLE_LDAP@ +CURL_DISABLE_LDAPS = @CURL_DISABLE_LDAPS@ +CURL_DISABLE_MQTT = @CURL_DISABLE_MQTT@ +CURL_DISABLE_POP3 = @CURL_DISABLE_POP3@ +CURL_DISABLE_PROXY = @CURL_DISABLE_PROXY@ +CURL_DISABLE_RTSP = @CURL_DISABLE_RTSP@ +CURL_DISABLE_SMB = @CURL_DISABLE_SMB@ +CURL_DISABLE_SMTP = @CURL_DISABLE_SMTP@ +CURL_DISABLE_TELNET = @CURL_DISABLE_TELNET@ +CURL_DISABLE_TFTP = @CURL_DISABLE_TFTP@ +CURL_LT_SHLIB_VERSIONED_FLAVOUR = @CURL_LT_SHLIB_VERSIONED_FLAVOUR@ +CURL_NETWORK_AND_TIME_LIBS = @CURL_NETWORK_AND_TIME_LIBS@ +CURL_NETWORK_LIBS = @CURL_NETWORK_LIBS@ +CURL_WITH_MULTI_SSL = @CURL_WITH_MULTI_SSL@ +CYGPATH_W = @CYGPATH_W@ +DEFAULT_SSL_BACKEND = @DEFAULT_SSL_BACKEND@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +ENABLE_SHARED = @ENABLE_SHARED@ +ENABLE_STATIC = @ENABLE_STATIC@ +ETAGS = @ETAGS@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +FILECMD = @FILECMD@ +FISH_FUNCTIONS_DIR = @FISH_FUNCTIONS_DIR@ +GCOV = @GCOV@ +GREP = @GREP@ +HAVE_BROTLI = @HAVE_BROTLI@ +HAVE_GNUTLS_SRP = @HAVE_GNUTLS_SRP@ +HAVE_LDAP_SSL = @HAVE_LDAP_SSL@ +HAVE_LIBZ = @HAVE_LIBZ@ +HAVE_OPENSSL_QUIC = @HAVE_OPENSSL_QUIC@ +HAVE_OPENSSL_SRP = @HAVE_OPENSSL_SRP@ +HAVE_PROTO_BSDSOCKET_H = @HAVE_PROTO_BSDSOCKET_H@ +HAVE_ZSTD = @HAVE_ZSTD@ +HTTPD = @HTTPD@ +HTTPD_NGHTTPX = @HTTPD_NGHTTPX@ +IDN_ENABLED = @IDN_ENABLED@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +IPV6_ENABLED = @IPV6_ENABLED@ +LCOV = @LCOV@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBCURL_LIBS = @LIBCURL_LIBS@ +LIBCURL_NO_SHARED = @LIBCURL_NO_SHARED@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ +MAINT = @MAINT@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PERL = @PERL@ +PKGADD_NAME = @PKGADD_NAME@ +PKGADD_PKG = @PKGADD_PKG@ +PKGADD_VENDOR = @PKGADD_VENDOR@ +PKGCONFIG = @PKGCONFIG@ +RANDOM_FILE = @RANDOM_FILE@ +RANLIB = @RANLIB@ +RC = @RC@ +REQUIRE_LIB_DEPS = @REQUIRE_LIB_DEPS@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SSL_BACKENDS = @SSL_BACKENDS@ +SSL_ENABLED = @SSL_ENABLED@ +SSL_LIBS = @SSL_LIBS@ +STRIP = @STRIP@ +SUPPORT_FEATURES = @SUPPORT_FEATURES@ +SUPPORT_PROTOCOLS = @SUPPORT_PROTOCOLS@ +TEST_NGHTTPX = @TEST_NGHTTPX@ +USE_ARES = @USE_ARES@ +USE_BEARSSL = @USE_BEARSSL@ +USE_GNUTLS = @USE_GNUTLS@ +USE_HYPER = @USE_HYPER@ +USE_LIBPSL = @USE_LIBPSL@ +USE_LIBRTMP = @USE_LIBRTMP@ +USE_LIBSSH = @USE_LIBSSH@ +USE_LIBSSH2 = @USE_LIBSSH2@ +USE_MBEDTLS = @USE_MBEDTLS@ +USE_MSH3 = @USE_MSH3@ +USE_NGHTTP2 = @USE_NGHTTP2@ +USE_NGHTTP3 = @USE_NGHTTP3@ +USE_NGTCP2 = @USE_NGTCP2@ +USE_NGTCP2_CRYPTO_BORINGSSL = @USE_NGTCP2_CRYPTO_BORINGSSL@ +USE_NGTCP2_CRYPTO_GNUTLS = @USE_NGTCP2_CRYPTO_GNUTLS@ +USE_NGTCP2_CRYPTO_QUICTLS = @USE_NGTCP2_CRYPTO_QUICTLS@ +USE_NGTCP2_CRYPTO_WOLFSSL = @USE_NGTCP2_CRYPTO_WOLFSSL@ +USE_NGTCP2_H3 = @USE_NGTCP2_H3@ +USE_OPENLDAP = @USE_OPENLDAP@ +USE_OPENSSL_H3 = @USE_OPENSSL_H3@ +USE_OPENSSL_QUIC = @USE_OPENSSL_QUIC@ +USE_QUICHE = @USE_QUICHE@ +USE_RUSTLS = @USE_RUSTLS@ +USE_SCHANNEL = @USE_SCHANNEL@ +USE_SECTRANSP = @USE_SECTRANSP@ +USE_UNIX_SOCKETS = @USE_UNIX_SOCKETS@ +USE_WIN32_CRYPTO = @USE_WIN32_CRYPTO@ +USE_WIN32_LARGE_FILES = @USE_WIN32_LARGE_FILES@ +USE_WIN32_SMALL_FILES = @USE_WIN32_SMALL_FILES@ +USE_WINDOWS_SSPI = @USE_WINDOWS_SSPI@ +USE_WOLFSSH = @USE_WOLFSSH@ +USE_WOLFSSL = @USE_WOLFSSL@ +VERSION = @VERSION@ +VERSIONNUM = @VERSIONNUM@ +VSFTPD = @VSFTPD@ +ZLIB_LIBS = @ZLIB_LIBS@ +ZSH_FUNCTIONS_DIR = @ZSH_FUNCTIONS_DIR@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +libext = @libext@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +runstatedir = @runstatedir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ + +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +pkginclude_HEADERS = \ + curl.h curlver.h easy.h mprintf.h stdcheaders.h multi.h \ + typecheck-gcc.h system.h urlapi.h options.h header.h websockets.h + +CHECKSRC = $(CS_$(V)) +CS_0 = @echo " RUN " $@; +CS_1 = +CS_ = $(CS_0) +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu include/curl/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --gnu include/curl/Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-pkgincludeHEADERS: $(pkginclude_HEADERS) + @$(NORMAL_INSTALL) + @list='$(pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(pkgincludedir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(pkgincludedir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(pkgincludedir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(pkgincludedir)" || exit $$?; \ + done + +uninstall-pkgincludeHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(pkgincludedir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ + here=`pwd`; \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags +distdir: $(BUILT_SOURCES) + $(MAKE) $(AM_MAKEFLAGS) distdir-am + +distdir-am: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +@CURLDEBUG_FALSE@all-local: +all-am: Makefile $(HEADERS) all-local +installdirs: + for dir in "$(DESTDIR)$(pkgincludedir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-pkgincludeHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-pkgincludeHEADERS + +.MAKE: install-am install-strip + +.PHONY: CTAGS GTAGS TAGS all all-am all-local check check-am clean \ + clean-generic clean-libtool cscopelist-am ctags ctags-am \ + distclean distclean-generic distclean-libtool distclean-tags \ + distdir dvi dvi-am html html-am info info-am install \ + install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-pkgincludeHEADERS \ + install-ps install-ps-am install-strip installcheck \ + installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ + uninstall-am uninstall-pkgincludeHEADERS + +.PRECIOUS: Makefile + + +checksrc: + $(CHECKSRC)@PERL@ $(top_srcdir)/scripts/checksrc.pl -D$(top_srcdir)/include/curl $(pkginclude_HEADERS) + +# for debug builds, we scan the sources on all regular make invokes +@CURLDEBUG_TRUE@all-local: checksrc + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/third_party/curl/include/curl/curl.h b/third_party/curl/include/curl/curl.h new file mode 100644 index 0000000..91e11f6 --- /dev/null +++ b/third_party/curl/include/curl/curl.h @@ -0,0 +1,3247 @@ +#ifndef CURLINC_CURL_H +#define CURLINC_CURL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * If you have libcurl problems, all docs and details are found here: + * https://curl.se/libcurl/ + */ + +#ifdef CURL_NO_OLDIES +#define CURL_STRICTER +#endif + +/* Compile-time deprecation macros. */ +#if defined(__GNUC__) && \ + ((__GNUC__ > 12) || ((__GNUC__ == 12) && (__GNUC_MINOR__ >= 1 ))) && \ + !defined(__INTEL_COMPILER) && \ + !defined(CURL_DISABLE_DEPRECATION) && !defined(BUILDING_LIBCURL) +#define CURL_DEPRECATED(version, message) \ + __attribute__((deprecated("since " # version ". " message))) +#define CURL_IGNORE_DEPRECATION(statements) \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") \ + statements \ + _Pragma("GCC diagnostic pop") +#else +#define CURL_DEPRECATED(version, message) +#define CURL_IGNORE_DEPRECATION(statements) statements +#endif + +#include "curlver.h" /* libcurl version defines */ +#include "system.h" /* determine things run-time */ + +#include +#include + +#if defined(__FreeBSD__) || defined(__MidnightBSD__) +/* Needed for __FreeBSD_version or __MidnightBSD_version symbol definition */ +#include +#endif + +/* The include stuff here below is mainly for time_t! */ +#include +#include + +#if defined(_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 +#include +#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(__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(__sun__) || defined(__serenity__) || defined(__vxworks__) +#include +#endif + +#if !defined(_WIN32) && !defined(_WIN32_WCE) +#include +#endif + +#if !defined(_WIN32) +#include +#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(_WIN32) || \ + (__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(_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 CURL_DEPRECATED(8.3.0, "") = 3, + CURLSSLBACKEND_OBSOLETE4 = 4, /* Was QSOSSL. */ + CURLSSLBACKEND_GSKIT CURL_DEPRECATED(8.3.0, "") = 5, + CURLSSLBACKEND_POLARSSL CURL_DEPRECATED(7.69.0, "") = 6, + CURLSSLBACKEND_WOLFSSL = 7, + CURLSSLBACKEND_SCHANNEL = 8, + CURLSSLBACKEND_SECURETRANSPORT = 9, + CURLSSLBACKEND_AXTLS CURL_DEPRECATED(7.61.0, "") = 10, + CURLSSLBACKEND_MBEDTLS = 11, + CURLSSLBACKEND_MESALINK CURL_DEPRECATED(7.82.0, "") = 12, + CURLSSLBACKEND_BEARSSL = 13, + CURLSSLBACKEND_RUSTLS = 14 +} curl_sslbackend; + +/* aliases for library clones and renames */ +#define CURLSSLBACKEND_AWSLC CURLSSLBACKEND_OPENSSL +#define CURLSSLBACKEND_BORINGSSL CURLSSLBACKEND_OPENSSL +#define CURLSSLBACKEND_LIBRESSL 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 (10*1024*1024) +#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 + +/* This is a magic return code for the write callback that, when returned, + will signal an error from the callback. */ +#define CURL_WRITEFUNC_ERROR 0xFFFFFFFF + +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; + + /* These are libcurl private struct fields. Previously used by libcurl, so + they must never be interfered with. */ + 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 */ + 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_OBSOLETE62, /* 62 - NOT IN USE since 7.82.0 */ + 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_OBSOLETE75, /* 75 - NOT IN USE since 7.82.0 */ + CURLE_OBSOLETE76, /* 76 - NOT IN USE since 7.82.0 */ + 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 */ + CURLE_UNRECOVERABLE_POLL, /* 99 - poll/select returned fatal error */ + CURLE_TOO_LARGE, /* 100 - a value/data met its maximum */ + CURLE_ECH_REQUIRED, /* 101 - ECH tried but failed */ + 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 reused in 7.38.0 */ +#define CURLE_OBSOLETE16 CURLE_HTTP2 + +/* Previously obsolete error codes reused 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 +#define CURLE_LDAP_INVALID_URL CURLE_OBSOLETE62 +#define CURLE_CONV_REQD CURLE_OBSOLETE76 +#define CURLE_CONV_FAILED CURLE_OBSOLETE75 + +/* 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, /* HTTPS but stick to HTTP/1 added in 7.52.0 */ + CURLPROXY_HTTPS2 = 3, /* HTTPS and attempt HTTP/2 added in 8.2.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) +#ifndef CURL_NO_OLDIES + /* functionality removed since 8.8.0 */ +#define CURLAUTH_NTLM_WB (((unsigned long)1)<<5) +#endif +#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. + Causes a CURLE_PEER_FAILED_VERIFICATION error but 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 with */ + /* CURLOPT_SSH_KEYDATA */ + +typedef int + (*curl_sshhostkeycallback) (void *clientp,/* custom pointer passed */ + /* with CURLOPT_SSH_HOSTKEYDATA */ + int keytype, /* CURLKHTYPE */ + const char *key, /* hostkey to check */ + size_t keylen); /* length of the key */ + /* return CURLE_OK to accept */ + /* or something else to refuse */ + + +/* 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) + +/* The CURLPROTO_ defines below are for the **deprecated** CURLOPT_*PROTOCOLS + options. Do not use. */ +#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 +#define CURLOPTDEPRECATED(na,t,nu,v,m) na CURL_DEPRECATED(v,m) = 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 CURLOPT_READDATA 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 */ + CURLOPTDEPRECATED(CURLOPT_HTTPPOST, CURLOPTTYPE_OBJECTPOINT, 24, + 7.56.0, "Use CURLOPT_MIMEPOST"), + + /* 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 */ + CURLOPTDEPRECATED(CURLOPT_PUT, CURLOPTTYPE_LONG, 54, + 7.12.1, "Use CURLOPT_UPLOAD"), + + /* 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. */ + CURLOPTDEPRECATED(CURLOPT_PROGRESSFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 56, + 7.32.0, "Use CURLOPT_XFERINFOFUNCTION"), + + /* 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 an 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 reused + 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. */ + CURLOPTDEPRECATED(CURLOPT_RANDOM_FILE, CURLOPTTYPE_STRINGPOINT, 76, + 7.84.0, "Serves no purpose anymore"), + + /* Set to the Entropy Gathering Daemon socket pathname */ + CURLOPTDEPRECATED(CURLOPT_EGDSOCKET, CURLOPTTYPE_STRINGPOINT, 77, + 7.84.0, "Serves no purpose anymore"), + + /* 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! */ + CURLOPTDEPRECATED(CURLOPT_DNS_USE_GLOBAL_CACHE, CURLOPTTYPE_LONG, 91, + 7.11.1, "Use CURLOPT_SHARE"), + + /* 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), + + /* 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 server to acknowledge commands in a timely + manner. For FTP, SMTP, IMAP and POP3. */ + CURLOPT(CURLOPT_SERVER_RESPONSE_TIMEOUT, CURLOPTTYPE_LONG, 112), + + /* 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), + + CURLOPTDEPRECATED(CURLOPT_IOCTLFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 130, + 7.18.0, "Use CURLOPT_SEEKFUNCTION"), + CURLOPTDEPRECATED(CURLOPT_IOCTLDATA, CURLOPTTYPE_CBPOINT, 131, + 7.18.0, "Use CURLOPT_SEEKDATA"), + + /* 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) */ + CURLOPTDEPRECATED(CURLOPT_CONV_FROM_NETWORK_FUNCTION, + CURLOPTTYPE_FUNCTIONPOINT, 142, + 7.82.0, "Serves no purpose anymore"), + + /* Function that will be called to convert to the + network encoding (instead of using the iconv calls in libcurl) */ + CURLOPTDEPRECATED(CURLOPT_CONV_TO_NETWORK_FUNCTION, + CURLOPTTYPE_FUNCTIONPOINT, 143, + 7.82.0, "Serves no purpose anymore"), + + /* 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 */ + CURLOPTDEPRECATED(CURLOPT_CONV_FROM_UTF8_FUNCTION, + CURLOPTTYPE_FUNCTIONPOINT, 144, + 7.82.0, "Serves no purpose anymore"), + + /* 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 reuse 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=) 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! */ + CURLOPTDEPRECATED(CURLOPT_SOCKS5_GSSAPI_SERVICE, + CURLOPTTYPE_STRINGPOINT, 179, + 7.49.0, "Use CURLOPT_PROXY_SERVICE_NAME"), + + /* 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. */ + CURLOPTDEPRECATED(CURLOPT_PROTOCOLS, CURLOPTTYPE_LONG, 181, + 7.85.0, "Use CURLOPT_PROTOCOLS_STR"), + + /* 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. */ + CURLOPTDEPRECATED(CURLOPT_REDIR_PROTOCOLS, CURLOPTTYPE_LONG, 182, + 7.85.0, "Use CURLOPT_REDIR_PROTOCOLS_STR"), + + /* 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. + * Only supported by the c-ares DNS backend */ + 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) */ + CURLOPTDEPRECATED(CURLOPT_SSL_ENABLE_NPN, CURLOPTTYPE_LONG, 225, + 7.86.0, "Has no function"), + + /* 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 an 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 authorization identity */ + CURLOPT(CURLOPT_SASL_AUTHZID, CURLOPTTYPE_STRINGPOINT, 289), + + /* allow RCPT TO command to fail for some recipients */ + CURLOPT(CURLOPT_MAIL_RCPT_ALLOWFAILS, 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), + + /* set the SSH host key callback, must point to a curl_sshkeycallback + function */ + CURLOPT(CURLOPT_SSH_HOSTKEYFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 316), + + /* set the SSH host key callback custom pointer */ + CURLOPT(CURLOPT_SSH_HOSTKEYDATA, CURLOPTTYPE_CBPOINT, 317), + + /* specify which 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 + all built-in protocols. */ + CURLOPT(CURLOPT_PROTOCOLS_STR, CURLOPTTYPE_STRINGPOINT, 318), + + /* specify which protocols that libcurl is allowed to follow directs to */ + CURLOPT(CURLOPT_REDIR_PROTOCOLS_STR, CURLOPTTYPE_STRINGPOINT, 319), + + /* websockets options */ + CURLOPT(CURLOPT_WS_OPTIONS, CURLOPTTYPE_LONG, 320), + + /* CA cache timeout */ + CURLOPT(CURLOPT_CA_CACHE_TIMEOUT, CURLOPTTYPE_LONG, 321), + + /* Can leak things, gonna exit() soon */ + CURLOPT(CURLOPT_QUICK_EXIT, CURLOPTTYPE_LONG, 322), + + /* set a specific client IP for HAProxy PROXY protocol header? */ + CURLOPT(CURLOPT_HAPROXY_CLIENT_IP, CURLOPTTYPE_STRINGPOINT, 323), + + /* millisecond version */ + CURLOPT(CURLOPT_SERVER_RESPONSE_TIMEOUT_MS, CURLOPTTYPE_LONG, 324), + + /* set ECH configuration */ + CURLOPT(CURLOPT_ECH, CURLOPTTYPE_STRINGPOINT, 325), + + 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 + +/* */ +#define CURLOPT_FTP_RESPONSE_TIMEOUT CURLOPT_SERVER_RESPONSE_TIMEOUT + +/* Added in 8.2.0 */ +#define CURLOPT_MAIL_RCPT_ALLLOWFAILS CURLOPT_MAIL_RCPT_ALLOWFAILS + +#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 */ + + /* Convenient "aliases" */ +#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, /* Use HTTP/3, fallback to HTTP/2 or HTTP/1 if + needed. For HTTPS only. For HTTP, this option + makes libcurl return error. */ + CURL_HTTP_VERSION_3ONLY = 31, /* Use HTTP/3 without fallback. For HTTPS + only. For HTTP, this makes libcurl + return error. */ + + 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 +}; + +#define CURL_SSLVERSION_DEFAULT 0 +#define CURL_SSLVERSION_TLSv1 1 /* TLS 1.x */ +#define CURL_SSLVERSION_SSLv2 2 +#define CURL_SSLVERSION_SSLv3 3 +#define CURL_SSLVERSION_TLSv1_0 4 +#define CURL_SSLVERSION_TLSv1_1 5 +#define CURL_SSLVERSION_TLSv1_2 6 +#define CURL_SSLVERSION_TLSv1_3 7 + +#define CURL_SSLVERSION_LAST 8 /* never use, keep last */ + +#define CURL_SSLVERSION_MAX_NONE 0 +#define CURL_SSLVERSION_MAX_DEFAULT (CURL_SSLVERSION_TLSv1 << 16) +#define CURL_SSLVERSION_MAX_TLSv1_0 (CURL_SSLVERSION_TLSv1_0 << 16) +#define CURL_SSLVERSION_MAX_TLSv1_1 (CURL_SSLVERSION_TLSv1_1 << 16) +#define CURL_SSLVERSION_MAX_TLSv1_2 (CURL_SSLVERSION_TLSv1_2 << 16) +#define CURL_SSLVERSION_MAX_TLSv1_3 (CURL_SSLVERSION_TLSv1_3 << 16) + + /* never use, keep last */ +#define 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 { + /********* the first one is unused ************/ + CURLFORM_NOTHING CURL_DEPRECATED(7.56.0, ""), + CURLFORM_COPYNAME CURL_DEPRECATED(7.56.0, "Use curl_mime_name()"), + CURLFORM_PTRNAME CURL_DEPRECATED(7.56.0, "Use curl_mime_name()"), + CURLFORM_NAMELENGTH CURL_DEPRECATED(7.56.0, ""), + CURLFORM_COPYCONTENTS CURL_DEPRECATED(7.56.0, "Use curl_mime_data()"), + CURLFORM_PTRCONTENTS CURL_DEPRECATED(7.56.0, "Use curl_mime_data()"), + CURLFORM_CONTENTSLENGTH CURL_DEPRECATED(7.56.0, "Use curl_mime_data()"), + CURLFORM_FILECONTENT CURL_DEPRECATED(7.56.0, "Use curl_mime_data_cb()"), + CURLFORM_ARRAY CURL_DEPRECATED(7.56.0, ""), + CURLFORM_OBSOLETE, + CURLFORM_FILE CURL_DEPRECATED(7.56.0, "Use curl_mime_filedata()"), + + CURLFORM_BUFFER CURL_DEPRECATED(7.56.0, "Use curl_mime_filename()"), + CURLFORM_BUFFERPTR CURL_DEPRECATED(7.56.0, "Use curl_mime_data()"), + CURLFORM_BUFFERLENGTH CURL_DEPRECATED(7.56.0, "Use curl_mime_data()"), + + CURLFORM_CONTENTTYPE CURL_DEPRECATED(7.56.0, "Use curl_mime_type()"), + CURLFORM_CONTENTHEADER CURL_DEPRECATED(7.56.0, "Use curl_mime_headers()"), + CURLFORM_FILENAME CURL_DEPRECATED(7.56.0, "Use curl_mime_filename()"), + CURLFORM_END, + CURLFORM_OBSOLETE2, + + CURLFORM_STREAM CURL_DEPRECATED(7.56.0, "Use curl_mime_data_cb()"), + CURLFORM_CONTENTLEN /* added in 7.46.0, provide a curl_off_t length */ + CURL_DEPRECATED(7.56.0, "Use curl_mime_data()"), + + 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 CURL_DEPRECATED(7.56.0, ""), /* 1st, no error */ + + CURL_FORMADD_MEMORY CURL_DEPRECATED(7.56.0, ""), + CURL_FORMADD_OPTION_TWICE CURL_DEPRECATED(7.56.0, ""), + CURL_FORMADD_NULL CURL_DEPRECATED(7.56.0, ""), + CURL_FORMADD_UNKNOWN_OPTION CURL_DEPRECATED(7.56.0, ""), + CURL_FORMADD_INCOMPLETE CURL_DEPRECATED(7.56.0, ""), + CURL_FORMADD_ILLEGAL_ARRAY CURL_DEPRECATED(7.56.0, ""), + /* libcurl was built with form api disabled */ + CURL_FORMADD_DISABLED CURL_DEPRECATED(7.56.0, ""), + + 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_DEPRECATED(7.56.0, "Use curl_mime_init()") +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_DEPRECATED(7.56.0, "") +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_DEPRECATED(7.56.0, "Use curl_mime_free()") +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 thread-safe if CURL_VERSION_THREADSAFE is set in the + * curl_version_info_data.features flag (fetch by curl_version_info()). + + */ +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); + +/* + * NAME curl_global_trace() + * + * DESCRIPTION + * + * curl_global_trace() can be invoked at application start to + * configure which components in curl should participate in tracing. + + * This function is thread-safe if CURL_VERSION_THREADSAFE is set in the + * curl_version_info_data.features flag (fetch by curl_version_info()). + + */ +CURL_EXTERN CURLcode curl_global_trace(const char *config); + +/* 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 *list, + const char *data); + +/* + * NAME curl_slist_free_all() + * + * DESCRIPTION + * + * free a previously built curl_slist. + */ +CURL_EXTERN void curl_slist_free_all(struct curl_slist *list); + +/* + * 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, for SSL backends that support it. 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 for a + certificate in the format "name:content". + eg "Subject:foo", "Issuer:bar", etc. */ +}; + +/* 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 CURL_DEPRECATED(7.55.0, "Use CURLINFO_SIZE_UPLOAD_T") + = CURLINFO_DOUBLE + 7, + CURLINFO_SIZE_UPLOAD_T = CURLINFO_OFF_T + 7, + CURLINFO_SIZE_DOWNLOAD + CURL_DEPRECATED(7.55.0, "Use CURLINFO_SIZE_DOWNLOAD_T") + = CURLINFO_DOUBLE + 8, + CURLINFO_SIZE_DOWNLOAD_T = CURLINFO_OFF_T + 8, + CURLINFO_SPEED_DOWNLOAD + CURL_DEPRECATED(7.55.0, "Use CURLINFO_SPEED_DOWNLOAD_T") + = CURLINFO_DOUBLE + 9, + CURLINFO_SPEED_DOWNLOAD_T = CURLINFO_OFF_T + 9, + CURLINFO_SPEED_UPLOAD + CURL_DEPRECATED(7.55.0, "Use CURLINFO_SPEED_UPLOAD_T") + = 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 + CURL_DEPRECATED(7.55.0, + "Use CURLINFO_CONTENT_LENGTH_DOWNLOAD_T") + = CURLINFO_DOUBLE + 15, + CURLINFO_CONTENT_LENGTH_DOWNLOAD_T = CURLINFO_OFF_T + 15, + CURLINFO_CONTENT_LENGTH_UPLOAD + CURL_DEPRECATED(7.55.0, + "Use CURLINFO_CONTENT_LENGTH_UPLOAD_T") + = 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 CURL_DEPRECATED(7.45.0, "Use CURLINFO_ACTIVESOCKET") + = 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 CURL_DEPRECATED(7.48.0, "Use CURLINFO_TLS_SSL_PTR") + = 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 CURL_DEPRECATED(7.85.0, "Use CURLINFO_SCHEME") + = 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_CAINFO = CURLINFO_STRING + 61, + CURLINFO_CAPATH = CURLINFO_STRING + 62, + CURLINFO_XFER_ID = CURLINFO_OFF_T + 63, + CURLINFO_CONN_ID = CURLINFO_OFF_T + 64, + CURLINFO_QUEUE_TIME_T = CURLINFO_OFF_T + 65, + CURLINFO_USED_PROXY = CURLINFO_LONG + 66, + CURLINFO_LASTONE = 66 +} 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 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_HSTS, + 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 *share, CURLSHoption option, + ...); +CURL_EXTERN CURLSHcode curl_share_cleanup(CURLSH *share); + +/**************************************************************************** + * Structures for querying information about the curl library at runtime. + */ + +typedef enum { + CURLVERSION_FIRST, /* 7.10 */ + CURLVERSION_SECOND, /* 7.11.1 */ + CURLVERSION_THIRD, /* 7.12.0 */ + CURLVERSION_FOURTH, /* 7.16.1 */ + CURLVERSION_FIFTH, /* 7.57.0 */ + CURLVERSION_SIXTH, /* 7.66.0 */ + CURLVERSION_SEVENTH, /* 7.70.0 */ + CURLVERSION_EIGHTH, /* 7.72.0 */ + CURLVERSION_NINTH, /* 7.75.0 */ + CURLVERSION_TENTH, /* 7.77.0 */ + CURLVERSION_ELEVENTH, /* 7.87.0 */ + CURLVERSION_TWELFTH, /* 8.8.0 */ + 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_TWELFTH + +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. */ + + /* These fields were added in CURLVERSION_ELEVENTH */ + /* feature_names is terminated by an entry with a NULL feature name */ + const char * const *feature_names; + + /* These fields were added in CURLVERSION_TWELFTH */ + const char *rtmp_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 */ +#define CURL_VERSION_THREADSAFE (1<<30) /* libcurl API is thread-safe */ + +/* + * 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 +} /* end of extern "C" */ +#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" +#include "header.h" +#include "websockets.h" +#include "mprintf.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 && !CURL_DISABLE_TYPECHECK */ + +#endif /* CURLINC_CURL_H */ diff --git a/third_party/curl/include/curl/curlver.h b/third_party/curl/include/curl/curlver.h new file mode 100644 index 0000000..b68e3ee --- /dev/null +++ b/third_party/curl/include/curl/curlver.h @@ -0,0 +1,79 @@ +#ifndef CURLINC_CURLVER_H +#define CURLINC_CURLVER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* 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 "Daniel Stenberg, ." + +/* This is the version number of the libcurl package from which this header + file origins: */ +#define LIBCURL_VERSION "8.8.0" + +/* The numeric version number is also available "in parts" by using these + defines: */ +#define LIBCURL_VERSION_MAJOR 8 +#define LIBCURL_VERSION_MINOR 8 +#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 0x080800 + +/* + * 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 "2024-05-22" + +#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/third_party/curl/include/curl/easy.h b/third_party/curl/include/curl/easy.h new file mode 100644 index 0000000..1285101 --- /dev/null +++ b/third_party/curl/include/curl/easy.h @@ -0,0 +1,125 @@ +#ifndef CURLINC_EASY_H +#define CURLINC_EASY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#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 pointing to the specific type of the used option + * which is documented in each man page of the option. 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 +} /* end of extern "C" */ +#endif + +#endif diff --git a/third_party/curl/include/curl/header.h b/third_party/curl/include/curl/header.h new file mode 100644 index 0000000..8df11e1 --- /dev/null +++ b/third_party/curl/include/curl/header.h @@ -0,0 +1,74 @@ +#ifndef CURLINC_HEADER_H +#define CURLINC_HEADER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifdef __cplusplus +extern "C" { +#endif + +struct curl_header { + char *name; /* this might not use the same case */ + char *value; + size_t amount; /* number of headers using this name */ + size_t index; /* ... of this instance, 0 or higher */ + unsigned int origin; /* see bits below */ + void *anchor; /* handle privately used by libcurl */ +}; + +/* 'origin' bits */ +#define CURLH_HEADER (1<<0) /* plain server header */ +#define CURLH_TRAILER (1<<1) /* trailers */ +#define CURLH_CONNECT (1<<2) /* CONNECT headers */ +#define CURLH_1XX (1<<3) /* 1xx headers */ +#define CURLH_PSEUDO (1<<4) /* pseudo headers */ + +typedef enum { + CURLHE_OK, + CURLHE_BADINDEX, /* header exists but not with this index */ + CURLHE_MISSING, /* no such header exists */ + CURLHE_NOHEADERS, /* no headers at all exist (yet) */ + CURLHE_NOREQUEST, /* no request with this number was used */ + CURLHE_OUT_OF_MEMORY, /* out of memory while processing */ + CURLHE_BAD_ARGUMENT, /* a function argument was not okay */ + CURLHE_NOT_BUILT_IN /* if API was disabled in the build */ +} CURLHcode; + +CURL_EXTERN CURLHcode curl_easy_header(CURL *easy, + const char *name, + size_t index, + unsigned int origin, + int request, + struct curl_header **hout); + +CURL_EXTERN struct curl_header *curl_easy_nextheader(CURL *easy, + unsigned int origin, + int request, + struct curl_header *prev); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif /* CURLINC_HEADER_H */ diff --git a/third_party/curl/include/curl/mprintf.h b/third_party/curl/include/curl/mprintf.h new file mode 100644 index 0000000..4f70454 --- /dev/null +++ b/third_party/curl/include/curl/mprintf.h @@ -0,0 +1,78 @@ +#ifndef CURLINC_MPRINTF_H +#define CURLINC_MPRINTF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include +#include /* needed for FILE */ +#include "curl.h" /* for CURL_EXTERN */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if (defined(__GNUC__) || defined(__clang__)) && \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(CURL_NO_FMT_CHECKS) +#if defined(__MINGW32__) && !defined(__clang__) +#define CURL_TEMP_PRINTF(fmt, arg) \ + __attribute__((format(gnu_printf, fmt, arg))) +#else +#define CURL_TEMP_PRINTF(fmt, arg) \ + __attribute__((format(printf, fmt, arg))) +#endif +#else +#define CURL_TEMP_PRINTF(fmt, arg) +#endif + +CURL_EXTERN int curl_mprintf(const char *format, ...) + CURL_TEMP_PRINTF(1, 2); +CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...) + CURL_TEMP_PRINTF(2, 3); +CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...) + CURL_TEMP_PRINTF(2, 3); +CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength, + const char *format, ...) + CURL_TEMP_PRINTF(3, 4); +CURL_EXTERN int curl_mvprintf(const char *format, va_list args) + CURL_TEMP_PRINTF(1, 0); +CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args) + CURL_TEMP_PRINTF(2, 0); +CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args) + CURL_TEMP_PRINTF(2, 0); +CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength, + const char *format, va_list args) + CURL_TEMP_PRINTF(3, 0); +CURL_EXTERN char *curl_maprintf(const char *format, ...) + CURL_TEMP_PRINTF(1, 2); +CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args) + CURL_TEMP_PRINTF(1, 0); + +#undef CURL_TEMP_PRINTF + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif /* CURLINC_MPRINTF_H */ diff --git a/third_party/curl/include/curl/multi.h b/third_party/curl/include/curl/multi.h new file mode 100644 index 0000000..62162f9 --- /dev/null +++ b/third_party/curl/include/curl/multi.h @@ -0,0 +1,475 @@ +#ifndef CURLINC_MULTI_H +#define CURLINC_MULTI_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + 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 + * 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_UNRECOVERABLE_POLL, + 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; +}; + +/* + * Name: curl_multi_init() + * + * Desc: initialize 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_DEPRECATED(7.19.5, "Use curl_multi_socket_action()") + 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_DEPRECATED(7.19.5, "Use curl_multi_socket_action()") + 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_multi_get_handles() + * + * Desc: Returns an allocated array holding all handles currently added to + * the multi handle. Marks the final entry with a NULL pointer. If + * there is no easy handle added to the multi handle, this function + * returns an array with the first entry as a NULL pointer. + * + * Returns: NULL on failure, otherwise a CURL **array pointer + */ +CURL_EXTERN CURL **curl_multi_get_handles(CURLM *multi_handle); + +/* + * 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); + +/* + * Name: curl_multi_waitfds() + * + * Desc: Ask curl for fds for polling. The app can use these to poll on. + * We want curl_multi_perform() called as soon as one of them are + * ready. Passing zero size allows to get just a number of fds. + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_waitfds(CURLM *multi, struct curl_waitfd *ufds, + unsigned int size, + unsigned int *fd_count); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif diff --git a/third_party/curl/include/curl/options.h b/third_party/curl/include/curl/options.h new file mode 100644 index 0000000..1ed76a9 --- /dev/null +++ b/third_party/curl/include/curl/options.h @@ -0,0 +1,70 @@ +#ifndef CURLINC_OPTIONS_H +#define CURLINC_OPTIONS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#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 null-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/third_party/curl/include/curl/stdcheaders.h b/third_party/curl/include/curl/stdcheaders.h new file mode 100644 index 0000000..7451aa3 --- /dev/null +++ b/third_party/curl/include/curl/stdcheaders.h @@ -0,0 +1,35 @@ +#ifndef CURLINC_STDCHEADERS_H +#define CURLINC_STDCHEADERS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include + +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/third_party/curl/include/curl/system.h b/third_party/curl/include/curl/system.h new file mode 100644 index 0000000..81a1b81 --- /dev/null +++ b/third_party/curl/include/curl/system.h @@ -0,0 +1,496 @@ +#ifndef CURLINC_SYSTEM_H +#define CURLINC_SYSTEM_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * 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(__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(__MCST__) /* MCST eLbrus Compiler Collection */ +# 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(macintosh) +# include +# if TYPE_LONGLONG +# 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 unsigned int + +#elif defined(__TANDEM) +# if ! defined(__LP64) + /* Required for 32-bit NonStop builds only. */ +# 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 +# endif + +#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__) +# include +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T PRId64 +# define CURL_FORMAT_CURL_OFF_TU PRIu64 +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# define CURL_PULL_SYS_TYPES_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__) +# 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(__MVS__) +# 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 + +#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 + +#elif defined(__hpux) /* HP aCC 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 >= 1800) +# include +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T PRId64 +# define CURL_FORMAT_CURL_OFF_TU PRIu64 +# define CURL_SUFFIX_CURL_OFF_T i64 +# define CURL_SUFFIX_CURL_OFF_TU ui64 +# elif (_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 */ +#define CURL_PULL_SYS_POLL_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 +#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 +#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 +#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/third_party/curl/include/curl/typecheck-gcc.h b/third_party/curl/include/curl/typecheck-gcc.h new file mode 100644 index 0000000..873a49e --- /dev/null +++ b/third_party/curl/include/curl/typecheck-gcc.h @@ -0,0 +1,718 @@ +#ifndef CURLINC_TYPECHECK_GCC_H +#define CURLINC_TYPECHECK_GCC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* 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__({ \ + CURLoption _curl_opt = (option); \ + if(__builtin_constant_p(_curl_opt)) { \ + CURL_IGNORE_DEPRECATION( \ + 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__({ \ + CURLINFO _curl_info = (info); \ + if(__builtin_constant_p(_curl_info)) { \ + CURL_IGNORE_DEPRECATION( \ + 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_ECH || \ + (option) == CURLOPT_EGDSOCKET || \ + (option) == CURLOPT_FTP_ACCOUNT || \ + (option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \ + (option) == CURLOPT_FTPPORT || \ + (option) == CURLOPT_HSTS || \ + (option) == CURLOPT_HAPROXY_CLIENT_IP || \ + (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_PROTOCOLS_STR || \ + (option) == CURLOPT_PROXY || \ + (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_SSL_CIPHER_LIST || \ + (option) == CURLOPT_PROXY_SSLCERT || \ + (option) == CURLOPT_PROXY_SSLCERTTYPE || \ + (option) == CURLOPT_PROXY_SSLKEY || \ + (option) == CURLOPT_PROXY_SSLKEYTYPE || \ + (option) == CURLOPT_PROXY_TLS13_CIPHERS || \ + (option) == CURLOPT_PROXY_TLSAUTH_PASSWORD || \ + (option) == CURLOPT_PROXY_TLSAUTH_TYPE || \ + (option) == CURLOPT_PROXY_TLSAUTH_USERNAME || \ + (option) == CURLOPT_PROXYPASSWORD || \ + (option) == CURLOPT_PROXYUSERNAME || \ + (option) == CURLOPT_PROXYUSERPWD || \ + (option) == CURLOPT_RANDOM_FILE || \ + (option) == CURLOPT_RANGE || \ + (option) == CURLOPT_REDIR_PROTOCOLS_STR || \ + (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 || \ + (option) == CURLOPT_SSH_HOSTKEYDATA || \ + 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/third_party/curl/include/curl/urlapi.h b/third_party/curl/include/curl/urlapi.h new file mode 100644 index 0000000..19388c3 --- /dev/null +++ b/third_party/curl/include/curl/urlapi.h @@ -0,0 +1,154 @@ +#ifndef CURLINC_URLAPI_H +#define CURLINC_URLAPI_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#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_LACKS_IDN, /* 30 */ + CURLUE_TOO_LARGE, /* 31 */ + 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 */ +#define CURLU_PUNYCODE (1<<12) /* get the host name in punycode */ +#define CURLU_PUNY2IDN (1<<13) /* punycode => IDN conversion */ +#define CURLU_GET_EMPTY (1<<14) /* allow empty queries and fragments + when extracting the URL or the + components */ + +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(const 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(const 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/third_party/curl/include/curl/websockets.h b/third_party/curl/include/curl/websockets.h new file mode 100644 index 0000000..6ef6a2b --- /dev/null +++ b/third_party/curl/include/curl/websockets.h @@ -0,0 +1,84 @@ +#ifndef CURLINC_WEBSOCKETS_H +#define CURLINC_WEBSOCKETS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifdef __cplusplus +extern "C" { +#endif + +struct curl_ws_frame { + int age; /* zero */ + int flags; /* See the CURLWS_* defines */ + curl_off_t offset; /* the offset of this data into the frame */ + curl_off_t bytesleft; /* number of pending bytes left of the payload */ + size_t len; /* size of the current data chunk */ +}; + +/* flag bits */ +#define CURLWS_TEXT (1<<0) +#define CURLWS_BINARY (1<<1) +#define CURLWS_CONT (1<<2) +#define CURLWS_CLOSE (1<<3) +#define CURLWS_PING (1<<4) +#define CURLWS_OFFSET (1<<5) + +/* + * NAME curl_ws_recv() + * + * DESCRIPTION + * + * Receives data from the websocket connection. Use after successful + * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. + */ +CURL_EXTERN CURLcode curl_ws_recv(CURL *curl, void *buffer, size_t buflen, + size_t *recv, + const struct curl_ws_frame **metap); + +/* flags for curl_ws_send() */ +#define CURLWS_PONG (1<<6) + +/* + * NAME curl_ws_send() + * + * DESCRIPTION + * + * Sends data over the websocket connection. Use after successful + * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. + */ +CURL_EXTERN CURLcode curl_ws_send(CURL *curl, const void *buffer, + size_t buflen, size_t *sent, + curl_off_t fragsize, + unsigned int flags); + +/* bits for the CURLOPT_WS_OPTIONS bitmask: */ +#define CURLWS_RAW_MODE (1<<0) + +CURL_EXTERN const struct curl_ws_frame *curl_ws_meta(CURL *curl); + +#ifdef __cplusplus +} +#endif + +#endif /* CURLINC_WEBSOCKETS_H */ diff --git a/third_party/curl/install-sh b/third_party/curl/install-sh new file mode 100755 index 0000000..ec298b5 --- /dev/null +++ b/third_party/curl/install-sh @@ -0,0 +1,541 @@ +#!/bin/sh +# install - install a program, script, or datafile + +scriptversion=2020-11-14.01; # UTC + +# This originates from X11R5 (mit/util/scripts/install.sh), which was +# later released in X11R6 (xc/config/util/install.sh) with the +# following copyright and license. +# +# Copyright (C) 1994 X Consortium +# +# 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 +# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN +# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- +# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# +# Except as contained in this notice, the name of the X Consortium shall not +# be used in advertising or otherwise to promote the sale, use or other deal- +# ings in this Software without prior written authorization from the X Consor- +# tium. +# +# +# FSF changes to this file are in the public domain. +# +# Calling this script install-sh is preferred over install.sh, to prevent +# 'make' implicit rules from creating a file called install from it +# when there is no Makefile. +# +# This script is compatible with the BSD install script, but was written +# from scratch. + +tab=' ' +nl=' +' +IFS=" $tab$nl" + +# Set DOITPROG to "echo" to test this script. + +doit=${DOITPROG-} +doit_exec=${doit:-exec} + +# Put in absolute file names if you don't have them in your path; +# or use environment vars. + +chgrpprog=${CHGRPPROG-chgrp} +chmodprog=${CHMODPROG-chmod} +chownprog=${CHOWNPROG-chown} +cmpprog=${CMPPROG-cmp} +cpprog=${CPPROG-cp} +mkdirprog=${MKDIRPROG-mkdir} +mvprog=${MVPROG-mv} +rmprog=${RMPROG-rm} +stripprog=${STRIPPROG-strip} + +posix_mkdir= + +# Desired mode of installed file. +mode=0755 + +# Create dirs (including intermediate dirs) using mode 755. +# This is like GNU 'install' as of coreutils 8.32 (2020). +mkdir_umask=22 + +backupsuffix= +chgrpcmd= +chmodcmd=$chmodprog +chowncmd= +mvcmd=$mvprog +rmcmd="$rmprog -f" +stripcmd= + +src= +dst= +dir_arg= +dst_arg= + +copy_on_change=false +is_target_a_directory=possibly + +usage="\ +Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE + or: $0 [OPTION]... SRCFILES... DIRECTORY + or: $0 [OPTION]... -t DIRECTORY SRCFILES... + or: $0 [OPTION]... -d DIRECTORIES... + +In the 1st form, copy SRCFILE to DSTFILE. +In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. +In the 4th, create DIRECTORIES. + +Options: + --help display this help and exit. + --version display version info and exit. + + -c (ignored) + -C install only if different (preserve data modification time) + -d create directories instead of installing files. + -g GROUP $chgrpprog installed files to GROUP. + -m MODE $chmodprog installed files to MODE. + -o USER $chownprog installed files to USER. + -p pass -p to $cpprog. + -s $stripprog installed files. + -S SUFFIX attempt to back up existing files, with suffix SUFFIX. + -t DIRECTORY install into DIRECTORY. + -T report an error if DSTFILE is a directory. + +Environment variables override the default commands: + CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG + RMPROG STRIPPROG + +By default, rm is invoked with -f; when overridden with RMPROG, +it's up to you to specify -f if you want it. + +If -S is not specified, no backups are attempted. + +Email bug reports to bug-automake@gnu.org. +Automake home page: https://www.gnu.org/software/automake/ +" + +while test $# -ne 0; do + case $1 in + -c) ;; + + -C) copy_on_change=true;; + + -d) dir_arg=true;; + + -g) chgrpcmd="$chgrpprog $2" + shift;; + + --help) echo "$usage"; exit $?;; + + -m) mode=$2 + case $mode in + *' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*) + echo "$0: invalid mode: $mode" >&2 + exit 1;; + esac + shift;; + + -o) chowncmd="$chownprog $2" + shift;; + + -p) cpprog="$cpprog -p";; + + -s) stripcmd=$stripprog;; + + -S) backupsuffix="$2" + shift;; + + -t) + is_target_a_directory=always + dst_arg=$2 + # Protect names problematic for 'test' and other utilities. + case $dst_arg in + -* | [=\(\)!]) dst_arg=./$dst_arg;; + esac + shift;; + + -T) is_target_a_directory=never;; + + --version) echo "$0 $scriptversion"; exit $?;; + + --) shift + break;; + + -*) echo "$0: invalid option: $1" >&2 + exit 1;; + + *) break;; + esac + shift +done + +# We allow the use of options -d and -T together, by making -d +# take the precedence; this is for compatibility with GNU install. + +if test -n "$dir_arg"; then + if test -n "$dst_arg"; then + echo "$0: target directory not allowed when installing a directory." >&2 + exit 1 + fi +fi + +if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then + # When -d is used, all remaining arguments are directories to create. + # When -t is used, the destination is already specified. + # Otherwise, the last argument is the destination. Remove it from $@. + for arg + do + if test -n "$dst_arg"; then + # $@ is not empty: it contains at least $arg. + set fnord "$@" "$dst_arg" + shift # fnord + fi + shift # arg + dst_arg=$arg + # Protect names problematic for 'test' and other utilities. + case $dst_arg in + -* | [=\(\)!]) dst_arg=./$dst_arg;; + esac + done +fi + +if test $# -eq 0; then + if test -z "$dir_arg"; then + echo "$0: no input file specified." >&2 + exit 1 + fi + # It's OK to call 'install-sh -d' without argument. + # This can happen when creating conditional directories. + exit 0 +fi + +if test -z "$dir_arg"; then + if test $# -gt 1 || test "$is_target_a_directory" = always; then + if test ! -d "$dst_arg"; then + echo "$0: $dst_arg: Is not a directory." >&2 + exit 1 + fi + fi +fi + +if test -z "$dir_arg"; then + do_exit='(exit $ret); exit $ret' + trap "ret=129; $do_exit" 1 + trap "ret=130; $do_exit" 2 + trap "ret=141; $do_exit" 13 + trap "ret=143; $do_exit" 15 + + # Set umask so as not to create temps with too-generous modes. + # However, 'strip' requires both read and write access to temps. + case $mode in + # Optimize common cases. + *644) cp_umask=133;; + *755) cp_umask=22;; + + *[0-7]) + if test -z "$stripcmd"; then + u_plus_rw= + else + u_plus_rw='% 200' + fi + cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; + *) + if test -z "$stripcmd"; then + u_plus_rw= + else + u_plus_rw=,u+rw + fi + cp_umask=$mode$u_plus_rw;; + esac +fi + +for src +do + # Protect names problematic for 'test' and other utilities. + case $src in + -* | [=\(\)!]) src=./$src;; + esac + + if test -n "$dir_arg"; then + dst=$src + dstdir=$dst + test -d "$dstdir" + dstdir_status=$? + # Don't chown directories that already exist. + if test $dstdir_status = 0; then + chowncmd="" + fi + else + + # Waiting for this to be detected by the "$cpprog $src $dsttmp" command + # might cause directories to be created, which would be especially bad + # if $src (and thus $dsttmp) contains '*'. + if test ! -f "$src" && test ! -d "$src"; then + echo "$0: $src does not exist." >&2 + exit 1 + fi + + if test -z "$dst_arg"; then + echo "$0: no destination specified." >&2 + exit 1 + fi + dst=$dst_arg + + # If destination is a directory, append the input filename. + if test -d "$dst"; then + if test "$is_target_a_directory" = never; then + echo "$0: $dst_arg: Is a directory" >&2 + exit 1 + fi + dstdir=$dst + dstbase=`basename "$src"` + case $dst in + */) dst=$dst$dstbase;; + *) dst=$dst/$dstbase;; + esac + dstdir_status=0 + else + dstdir=`dirname "$dst"` + test -d "$dstdir" + dstdir_status=$? + fi + fi + + case $dstdir in + */) dstdirslash=$dstdir;; + *) dstdirslash=$dstdir/;; + esac + + obsolete_mkdir_used=false + + if test $dstdir_status != 0; then + case $posix_mkdir in + '') + # With -d, create the new directory with the user-specified mode. + # Otherwise, rely on $mkdir_umask. + if test -n "$dir_arg"; then + mkdir_mode=-m$mode + else + mkdir_mode= + fi + + posix_mkdir=false + # The $RANDOM variable is not portable (e.g., dash). Use it + # here however when possible just to lower collision chance. + tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ + + trap ' + ret=$? + rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" 2>/dev/null + exit $ret + ' 0 + + # Because "mkdir -p" follows existing symlinks and we likely work + # directly in world-writeable /tmp, make sure that the '$tmpdir' + # directory is successfully created first before we actually test + # 'mkdir -p'. + if (umask $mkdir_umask && + $mkdirprog $mkdir_mode "$tmpdir" && + exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1 + then + if test -z "$dir_arg" || { + # Check for POSIX incompatibilities with -m. + # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or + # other-writable bit of parent directory when it shouldn't. + # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. + test_tmpdir="$tmpdir/a" + ls_ld_tmpdir=`ls -ld "$test_tmpdir"` + case $ls_ld_tmpdir in + d????-?r-*) different_mode=700;; + d????-?--*) different_mode=755;; + *) false;; + esac && + $mkdirprog -m$different_mode -p -- "$test_tmpdir" && { + ls_ld_tmpdir_1=`ls -ld "$test_tmpdir"` + test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" + } + } + then posix_mkdir=: + fi + rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" + else + # Remove any dirs left behind by ancient mkdir implementations. + rmdir ./$mkdir_mode ./-p ./-- "$tmpdir" 2>/dev/null + fi + trap '' 0;; + esac + + if + $posix_mkdir && ( + umask $mkdir_umask && + $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" + ) + then : + else + + # mkdir does not conform to POSIX, + # or it failed possibly due to a race condition. Create the + # directory the slow way, step by step, checking for races as we go. + + case $dstdir in + /*) prefix='/';; + [-=\(\)!]*) prefix='./';; + *) prefix='';; + esac + + oIFS=$IFS + IFS=/ + set -f + set fnord $dstdir + shift + set +f + IFS=$oIFS + + prefixes= + + for d + do + test X"$d" = X && continue + + prefix=$prefix$d + if test -d "$prefix"; then + prefixes= + else + if $posix_mkdir; then + (umask $mkdir_umask && + $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break + # Don't fail if two instances are running concurrently. + test -d "$prefix" || exit 1 + else + case $prefix in + *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; + *) qprefix=$prefix;; + esac + prefixes="$prefixes '$qprefix'" + fi + fi + prefix=$prefix/ + done + + if test -n "$prefixes"; then + # Don't fail if two instances are running concurrently. + (umask $mkdir_umask && + eval "\$doit_exec \$mkdirprog $prefixes") || + test -d "$dstdir" || exit 1 + obsolete_mkdir_used=true + fi + fi + fi + + if test -n "$dir_arg"; then + { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && + { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && + { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || + test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 + else + + # Make a couple of temp file names in the proper directory. + dsttmp=${dstdirslash}_inst.$$_ + rmtmp=${dstdirslash}_rm.$$_ + + # Trap to clean up those temp files at exit. + trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 + + # Copy the file name to the temp name. + (umask $cp_umask && + { test -z "$stripcmd" || { + # Create $dsttmp read-write so that cp doesn't create it read-only, + # which would cause strip to fail. + if test -z "$doit"; then + : >"$dsttmp" # No need to fork-exec 'touch'. + else + $doit touch "$dsttmp" + fi + } + } && + $doit_exec $cpprog "$src" "$dsttmp") && + + # and set any options; do chmod last to preserve setuid bits. + # + # If any of these fail, we abort the whole thing. If we want to + # ignore errors from any of these, just make sure not to ignore + # errors from the above "$doit $cpprog $src $dsttmp" command. + # + { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } && + { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } && + { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } && + { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && + + # If -C, don't bother to copy if it wouldn't change the file. + if $copy_on_change && + old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` && + new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` && + set -f && + set X $old && old=:$2:$4:$5:$6 && + set X $new && new=:$2:$4:$5:$6 && + set +f && + test "$old" = "$new" && + $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1 + then + rm -f "$dsttmp" + else + # If $backupsuffix is set, and the file being installed + # already exists, attempt a backup. Don't worry if it fails, + # e.g., if mv doesn't support -f. + if test -n "$backupsuffix" && test -f "$dst"; then + $doit $mvcmd -f "$dst" "$dst$backupsuffix" 2>/dev/null + fi + + # Rename the file to the real destination. + $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null || + + # The rename failed, perhaps because mv can't rename something else + # to itself, or perhaps because mv is so ancient that it does not + # support -f. + { + # Now remove or move aside any old file at destination location. + # We try this two ways since rm can't unlink itself on some + # systems and the destination file might be busy for other + # reasons. In this case, the final cleanup might fail but the new + # file should still install successfully. + { + test ! -f "$dst" || + $doit $rmcmd "$dst" 2>/dev/null || + { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null && + { $doit $rmcmd "$rmtmp" 2>/dev/null; :; } + } || + { echo "$0: cannot unlink or rename $dst" >&2 + (exit 1); exit 1 + } + } && + + # Now rename the file to the real destination. + $doit $mvcmd "$dsttmp" "$dst" + } + fi || exit 1 + + trap '' 0 + fi +done + +# Local variables: +# eval: (add-hook 'before-save-hook 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-time-zone: "UTC0" +# time-stamp-end: "; # UTC" +# End: diff --git a/third_party/curl/lib/.checksrc b/third_party/curl/lib/.checksrc new file mode 100644 index 0000000..16133a4 --- /dev/null +++ b/third_party/curl/lib/.checksrc @@ -0,0 +1 @@ +enable STRERROR diff --git a/third_party/curl/lib/CMakeLists.txt b/third_party/curl/lib/CMakeLists.txt new file mode 100644 index 0000000..e80df5f --- /dev/null +++ b/third_party/curl/lib/CMakeLists.txt @@ -0,0 +1,251 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +set(LIB_NAME libcurl) +set(LIBCURL_OUTPUT_NAME libcurl CACHE STRING "Basename of the curl library") +add_definitions(-DBUILDING_LIBCURL) + +configure_file(curl_config.h.cmake + ${CMAKE_CURRENT_BINARY_DIR}/curl_config.h) + +transform_makefile_inc("Makefile.inc" "${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake") +include(${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake) + +# DllMain is added later for DLL builds only. +list(REMOVE_ITEM CSOURCES dllmain.c) + +list(APPEND HHEADERS ${CMAKE_CURRENT_BINARY_DIR}/curl_config.h) + +# The rest of the build + +include_directories(${CMAKE_CURRENT_BINARY_DIR}/../include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/..) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../include) +include_directories(${CMAKE_CURRENT_BINARY_DIR}/..) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) +include_directories(${CMAKE_CURRENT_BINARY_DIR}) +if(USE_ARES) + include_directories(${CARES_INCLUDE_DIR}) +endif() + +if(BUILD_TESTING) + add_library( + curlu # special libcurlu library just for unittests + STATIC + EXCLUDE_FROM_ALL + ${HHEADERS} ${CSOURCES} + ) + target_compile_definitions(curlu PUBLIC UNITTESTS CURL_STATICLIB) + target_link_libraries(curlu PRIVATE ${CURL_LIBS}) +endif() + +if(ENABLE_CURLDEBUG) + # We must compile these sources separately to avoid memdebug.h redefinitions + # applying to them. + set_source_files_properties(memdebug.c curl_multibyte.c PROPERTIES SKIP_UNITY_BUILD_INCLUSION ON) +endif() + +transform_makefile_inc("Makefile.soname" "${CMAKE_CURRENT_BINARY_DIR}/Makefile.soname.cmake") +include(${CMAKE_CURRENT_BINARY_DIR}/Makefile.soname.cmake) + +if(CMAKE_SYSTEM_NAME STREQUAL "AIX" OR + CMAKE_SYSTEM_NAME STREQUAL "Linux" OR + CMAKE_SYSTEM_NAME STREQUAL "Darwin" OR + CMAKE_SYSTEM_NAME STREQUAL "SunOS" OR + CMAKE_SYSTEM_NAME STREQUAL "GNU/kFreeBSD" OR + + # FreeBSD comes with the a.out and elf flavours + # but a.out was supported up to version 3.x and + # elf from 3.x. I cannot imagine someone running + # CMake on those ancient systems + CMAKE_SYSTEM_NAME STREQUAL "FreeBSD" OR + + CMAKE_SYSTEM_NAME STREQUAL "Haiku") + + math(EXPR CMAKESONAME "${VERSIONCHANGE} - ${VERSIONDEL}") + set(CMAKEVERSION "${CMAKESONAME}.${VERSIONDEL}.${VERSIONADD}") +else() + unset(CMAKESONAME) +endif() + +## Library definition + +# Add "_imp" as a suffix before the extension to avoid conflicting with +# the statically linked "libcurl.lib" (typically with MSVC) +if(WIN32 AND + NOT IMPORT_LIB_SUFFIX AND + CMAKE_STATIC_LIBRARY_SUFFIX STREQUAL CMAKE_IMPORT_LIBRARY_SUFFIX) + set(IMPORT_LIB_SUFFIX "_imp") +endif() + +# Whether to do a single compilation pass for libcurl sources and reuse these +# objects to generate both static and shared target. +if(NOT DEFINED SHARE_LIB_OBJECT) + # Enable it by default on platforms where PIC is the default for both shared + # and static and there is a way to tell the linker which libcurl symbols it + # should export (vs. marking these symbols exportable at compile-time). + if(WIN32) + set(SHARE_LIB_OBJECT ON) + else() + # On other platforms, make it an option disabled by default + set(SHARE_LIB_OBJECT OFF) + endif() +endif() + +if(SHARE_LIB_OBJECT) + set(LIB_OBJECT "libcurl_object") + add_library(${LIB_OBJECT} OBJECT ${HHEADERS} ${CSOURCES}) + if(WIN32) + # Define CURL_STATICLIB always, to disable __declspec(dllexport) for + # exported libcurl symbols. We handle exports via libcurl.def instead. + # Except with symbol hiding disabled or debug mode enabled, when we export + # _all_ symbols from libcurl DLL, without using libcurl.def. + set_property(TARGET ${LIB_OBJECT} APPEND + PROPERTY COMPILE_DEFINITIONS "CURL_STATICLIB") + endif() + target_link_libraries(${LIB_OBJECT} PRIVATE ${CURL_LIBS}) + set_target_properties(${LIB_OBJECT} PROPERTIES + POSITION_INDEPENDENT_CODE ON) + if(HIDES_CURL_PRIVATE_SYMBOLS) + set_property(TARGET ${LIB_OBJECT} APPEND PROPERTY COMPILE_FLAGS "${CURL_CFLAG_SYMBOLS_HIDE}") + set_property(TARGET ${LIB_OBJECT} APPEND PROPERTY COMPILE_DEFINITIONS "CURL_HIDDEN_SYMBOLS") + endif() + if(CURL_HAS_LTO) + set_target_properties(${LIB_OBJECT} PROPERTIES + INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE + INTERPROCEDURAL_OPTIMIZATION_RELWITHDEBINFO TRUE) + endif() + + target_include_directories(${LIB_OBJECT} INTERFACE + $ + $) + + set(LIB_SOURCE $) +else() + set(LIB_SOURCE ${HHEADERS} ${CSOURCES}) +endif() + +# we want it to be called libcurl on all platforms +if(BUILD_STATIC_LIBS) + list(APPEND libcurl_export ${LIB_STATIC}) + add_library(${LIB_STATIC} STATIC ${LIB_SOURCE}) + add_library(${PROJECT_NAME}::${LIB_STATIC} ALIAS ${LIB_STATIC}) + if(WIN32) + set_property(TARGET ${LIB_OBJECT} APPEND + PROPERTY COMPILE_DEFINITIONS "CURL_STATICLIB") + endif() + target_link_libraries(${LIB_STATIC} PRIVATE ${CURL_LIBS}) + # Remove the "lib" prefix since the library is already named "libcurl". + set_target_properties(${LIB_STATIC} PROPERTIES + PREFIX "" OUTPUT_NAME "${LIBCURL_OUTPUT_NAME}" + SUFFIX "${STATIC_LIB_SUFFIX}${CMAKE_STATIC_LIBRARY_SUFFIX}" + INTERFACE_COMPILE_DEFINITIONS "CURL_STATICLIB") + if(HIDES_CURL_PRIVATE_SYMBOLS) + set_property(TARGET ${LIB_STATIC} APPEND PROPERTY COMPILE_FLAGS "${CURL_CFLAG_SYMBOLS_HIDE}") + set_property(TARGET ${LIB_STATIC} APPEND PROPERTY COMPILE_DEFINITIONS "CURL_HIDDEN_SYMBOLS") + endif() + if(CURL_HAS_LTO) + set_target_properties(${LIB_STATIC} PROPERTIES + INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE + INTERPROCEDURAL_OPTIMIZATION_RELWITHDEBINFO TRUE) + endif() + if(CMAKEVERSION AND CMAKESONAME) + set_target_properties(${LIB_STATIC} PROPERTIES + VERSION ${CMAKEVERSION} SOVERSION ${CMAKESONAME}) + endif() + + target_include_directories(${LIB_STATIC} INTERFACE + $ + $) +endif() + +if(BUILD_SHARED_LIBS) + list(APPEND libcurl_export ${LIB_SHARED}) + add_library(${LIB_SHARED} SHARED ${LIB_SOURCE}) + add_library(${PROJECT_NAME}::${LIB_SHARED} ALIAS ${LIB_SHARED}) + if(WIN32 OR CYGWIN) + if(CYGWIN) + # For cygwin always compile dllmain.c as a separate unit since it + # includes windows.h, which shouldn't be included in other units. + set_source_files_properties(dllmain.c PROPERTIES + SKIP_UNITY_BUILD_INCLUSION ON) + endif() + set_property(TARGET ${LIB_SHARED} APPEND PROPERTY SOURCES dllmain.c) + endif() + if(WIN32) + set_property(TARGET ${LIB_SHARED} APPEND PROPERTY SOURCES libcurl.rc) + if(HIDES_CURL_PRIVATE_SYMBOLS) + set_property(TARGET ${LIB_SHARED} APPEND PROPERTY SOURCES "${CURL_SOURCE_DIR}/libcurl.def") + endif() + endif() + target_link_libraries(${LIB_SHARED} PRIVATE ${CURL_LIBS}) + # Remove the "lib" prefix since the library is already named "libcurl". + set_target_properties(${LIB_SHARED} PROPERTIES + PREFIX "" OUTPUT_NAME "${LIBCURL_OUTPUT_NAME}" + IMPORT_PREFIX "" IMPORT_SUFFIX "${IMPORT_LIB_SUFFIX}${CMAKE_IMPORT_LIBRARY_SUFFIX}" + POSITION_INDEPENDENT_CODE ON) + if(HIDES_CURL_PRIVATE_SYMBOLS) + set_property(TARGET ${LIB_SHARED} APPEND PROPERTY COMPILE_FLAGS "${CURL_CFLAG_SYMBOLS_HIDE}") + set_property(TARGET ${LIB_SHARED} APPEND PROPERTY COMPILE_DEFINITIONS "CURL_HIDDEN_SYMBOLS") + endif() + if(CURL_HAS_LTO) + set_target_properties(${LIB_SHARED} PROPERTIES + INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE + INTERPROCEDURAL_OPTIMIZATION_RELWITHDEBINFO TRUE) + endif() + if(CMAKEVERSION AND CMAKESONAME) + set_target_properties(${LIB_SHARED} PROPERTIES + VERSION ${CMAKEVERSION} SOVERSION ${CMAKESONAME}) + endif() + + target_include_directories(${LIB_SHARED} INTERFACE + $ + $) +endif() + +add_library(${LIB_NAME} ALIAS ${LIB_SELECTED}) +add_library(${PROJECT_NAME}::${LIB_NAME} ALIAS ${LIB_SELECTED}) + +if(CURL_ENABLE_EXPORT_TARGET) + if(BUILD_STATIC_LIBS) + install(TARGETS ${LIB_STATIC} + EXPORT ${TARGETS_EXPORT_NAME} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ) + endif() + if(BUILD_SHARED_LIBS) + install(TARGETS ${LIB_SHARED} + EXPORT ${TARGETS_EXPORT_NAME} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ) + endif() + + export(TARGETS ${libcurl_export} + FILE ${PROJECT_BINARY_DIR}/libcurl-target.cmake + NAMESPACE ${PROJECT_NAME}:: + ) +endif() diff --git a/third_party/curl/lib/Makefile.am b/third_party/curl/lib/Makefile.am new file mode 100644 index 0000000..96afc59 --- /dev/null +++ b/third_party/curl/lib/Makefile.am @@ -0,0 +1,148 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +AUTOMAKE_OPTIONS = foreign nostdinc + +CMAKE_DIST = CMakeLists.txt curl_config.h.cmake + +EXTRA_DIST = Makefile.mk config-win32.h config-win32ce.h config-plan9.h \ + config-riscos.h config-mac.h curl_config.h.in config-dos.h libcurl.rc \ + config-amigaos.h config-win32ce.h config-os400.h setup-os400.h \ + $(CMAKE_DIST) setup-win32.h .checksrc Makefile.soname + +lib_LTLIBRARIES = libcurl.la + +if BUILD_UNITTESTS +noinst_LTLIBRARIES = libcurlu.la +else +noinst_LTLIBRARIES = +endif + +# This might hold -Werror +CFLAGS += @CURL_CFLAG_EXTRAS@ + +# Specify our include paths here, and do it relative to $(top_srcdir) and +# $(top_builddir), to ensure that these paths which belong to the library +# being currently built and tested are searched before the library which +# might possibly already be installed in the system. +# +# $(top_srcdir)/include is for libcurl's external include files +# $(top_builddir)/lib is for libcurl's generated lib/curl_config.h file +# $(top_srcdir)/lib for libcurl's lib/curl_setup.h and other "private" files + +AM_CPPFLAGS = -I$(top_srcdir)/include \ + -I$(top_builddir)/lib \ + -I$(top_srcdir)/lib + +# Prevent LIBS from being used for all link targets +LIBS = $(BLANK_AT_MAKETIME) + +include Makefile.soname + +AM_CPPFLAGS += -DBUILDING_LIBCURL +AM_LDFLAGS = +AM_CFLAGS = + +# Makefile.inc provides the CSOURCES and HHEADERS defines +include Makefile.inc + +libcurl_la_SOURCES = $(CSOURCES) $(HHEADERS) +libcurlu_la_SOURCES = $(CSOURCES) $(HHEADERS) + +libcurl_la_CPPFLAGS_EXTRA = +libcurl_la_LDFLAGS_EXTRA = +libcurl_la_CFLAGS_EXTRA = + +if CURL_LT_SHLIB_USE_VERSION_INFO +libcurl_la_LDFLAGS_EXTRA += $(VERSIONINFO) +endif + +if CURL_LT_SHLIB_USE_NO_UNDEFINED +libcurl_la_LDFLAGS_EXTRA += -no-undefined +endif + +if CURL_LT_SHLIB_USE_MIMPURE_TEXT +libcurl_la_LDFLAGS_EXTRA += -mimpure-text +endif + +if CURL_LT_SHLIB_USE_VERSIONED_SYMBOLS +libcurl_la_LDFLAGS_EXTRA += -Wl,--version-script=libcurl.vers +else +# if symbol-hiding is enabled, hide them! +if DOING_CURL_SYMBOL_HIDING +libcurl_la_LDFLAGS_EXTRA += -export-symbols-regex '^curl_.*' +endif +endif + +if USE_CPPFLAG_CURL_STATICLIB +libcurl_la_CPPFLAGS_EXTRA += -DCURL_STATICLIB +else +if HAVE_WINDRES +libcurl_la_SOURCES += $(LIB_RCFILES) +$(LIB_RCFILES): $(top_srcdir)/include/curl/curlver.h +endif +endif + +if DOING_CURL_SYMBOL_HIDING +libcurl_la_CPPFLAGS_EXTRA += -DCURL_HIDDEN_SYMBOLS +libcurl_la_CFLAGS_EXTRA += $(CFLAG_CURL_SYMBOL_HIDING) +endif + +libcurl_la_CPPFLAGS = $(AM_CPPFLAGS) $(libcurl_la_CPPFLAGS_EXTRA) +libcurl_la_LDFLAGS = $(AM_LDFLAGS) $(libcurl_la_LDFLAGS_EXTRA) $(CURL_LDFLAGS_LIB) $(LIBCURL_LIBS) +libcurl_la_CFLAGS = $(AM_CFLAGS) $(libcurl_la_CFLAGS_EXTRA) + +libcurlu_la_CPPFLAGS = $(AM_CPPFLAGS) -DCURL_STATICLIB -DUNITTESTS +libcurlu_la_LDFLAGS = $(AM_LDFLAGS) -static $(LIBCURL_LIBS) +libcurlu_la_CFLAGS = $(AM_CFLAGS) + +CHECKSRC = $(CS_$(V)) +CS_0 = @echo " RUN " $@; +CS_1 = +CS_ = $(CS_0) + +checksrc: + $(CHECKSRC)(@PERL@ $(top_srcdir)/scripts/checksrc.pl -D$(srcdir) \ + -W$(srcdir)/curl_config.h $(srcdir)/*.[ch] $(srcdir)/vauth/*.[ch] \ + $(srcdir)/vtls/*.[ch] $(srcdir)/vquic/*.[ch] $(srcdir)/vssh/*.[ch]) + +if CURLDEBUG +# for debug builds, we scan the sources on all regular make invokes +all-local: checksrc +endif + +# disable the tests that are mostly causing false positives +TIDYFLAGS=-checks=-clang-analyzer-security.insecureAPI.strcpy,-clang-analyzer-optin.performance.Padding,-clang-analyzer-valist.Uninitialized,-clang-analyzer-core.NonNullParamChecker,-clang-analyzer-core.NullDereference -quiet + +TIDY:=clang-tidy + +tidy: + $(TIDY) $(CSOURCES) $(TIDYFLAGS) -- $(AM_CPPFLAGS) $(CPPFLAGS) -DHAVE_CONFIG_H + +optiontable: + perl optiontable.pl < $(top_srcdir)/include/curl/curl.h > easyoptions.c + +if HAVE_WINDRES +.rc.lo: + $(LIBTOOL) --tag=RC --mode=compile $(RC) -I$(top_srcdir)/include $(RCFLAGS) -i $< -o $@ +endif diff --git a/third_party/curl/lib/Makefile.in b/third_party/curl/lib/Makefile.in new file mode 100644 index 0000000..f2127d9 --- /dev/null +++ b/third_party/curl/lib/Makefile.in @@ -0,0 +1,5523 @@ +# Makefile.in generated by automake 1.16.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994-2021 Free Software Foundation, Inc. + +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +@CURL_LT_SHLIB_USE_VERSION_INFO_TRUE@am__append_1 = $(VERSIONINFO) +@CURL_LT_SHLIB_USE_NO_UNDEFINED_TRUE@am__append_2 = -no-undefined +@CURL_LT_SHLIB_USE_MIMPURE_TEXT_TRUE@am__append_3 = -mimpure-text +@CURL_LT_SHLIB_USE_VERSIONED_SYMBOLS_TRUE@am__append_4 = -Wl,--version-script=libcurl.vers +# if symbol-hiding is enabled, hide them! +@CURL_LT_SHLIB_USE_VERSIONED_SYMBOLS_FALSE@@DOING_CURL_SYMBOL_HIDING_TRUE@am__append_5 = -export-symbols-regex '^curl_.*' +@USE_CPPFLAG_CURL_STATICLIB_TRUE@am__append_6 = -DCURL_STATICLIB +@HAVE_WINDRES_TRUE@@USE_CPPFLAG_CURL_STATICLIB_FALSE@am__append_7 = $(LIB_RCFILES) +@DOING_CURL_SYMBOL_HIDING_TRUE@am__append_8 = -DCURL_HIDDEN_SYMBOLS +@DOING_CURL_SYMBOL_HIDING_TRUE@am__append_9 = $(CFLAG_CURL_SYMBOL_HIDING) +subdir = lib +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4/curl-amissl.m4 \ + $(top_srcdir)/m4/curl-bearssl.m4 \ + $(top_srcdir)/m4/curl-compilers.m4 \ + $(top_srcdir)/m4/curl-confopts.m4 \ + $(top_srcdir)/m4/curl-functions.m4 \ + $(top_srcdir)/m4/curl-gnutls.m4 \ + $(top_srcdir)/m4/curl-mbedtls.m4 \ + $(top_srcdir)/m4/curl-openssl.m4 \ + $(top_srcdir)/m4/curl-override.m4 \ + $(top_srcdir)/m4/curl-reentrant.m4 \ + $(top_srcdir)/m4/curl-rustls.m4 \ + $(top_srcdir)/m4/curl-schannel.m4 \ + $(top_srcdir)/m4/curl-sectransp.m4 \ + $(top_srcdir)/m4/curl-sysconfig.m4 \ + $(top_srcdir)/m4/curl-wolfssl.m4 $(top_srcdir)/m4/libtool.m4 \ + $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ + $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ + $(top_srcdir)/m4/xc-am-iface.m4 \ + $(top_srcdir)/m4/xc-cc-check.m4 \ + $(top_srcdir)/m4/xc-lt-iface.m4 \ + $(top_srcdir)/m4/xc-translit.m4 \ + $(top_srcdir)/m4/xc-val-flgs.m4 \ + $(top_srcdir)/m4/zz40-xc-ovr.m4 \ + $(top_srcdir)/m4/zz50-xc-ovr.m4 \ + $(top_srcdir)/m4/zz60-xc-ovr.m4 $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = curl_config.h +CONFIG_CLEAN_FILES = libcurl.vers +CONFIG_CLEAN_VPATH_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(libdir)" +LTLIBRARIES = $(lib_LTLIBRARIES) $(noinst_LTLIBRARIES) +libcurl_la_LIBADD = +am__libcurl_la_SOURCES_DIST = altsvc.c amigaos.c asyn-ares.c \ + asyn-thread.c base64.c bufq.c bufref.c c-hyper.c cf-h1-proxy.c \ + cf-h2-proxy.c cf-haproxy.c cf-https-connect.c cf-socket.c \ + cfilters.c conncache.c connect.c content_encoding.c cookie.c \ + curl_addrinfo.c curl_des.c curl_endian.c curl_fnmatch.c \ + curl_get_line.c curl_gethostname.c curl_gssapi.c \ + curl_memrchr.c curl_multibyte.c curl_ntlm_core.c curl_path.c \ + curl_range.c curl_rtmp.c curl_sasl.c curl_sha512_256.c \ + curl_sspi.c curl_threads.c curl_trc.c cw-out.c dict.c \ + dllmain.c doh.c dynbuf.c dynhds.c easy.c easygetopt.c \ + easyoptions.c escape.c file.c fileinfo.c fopen.c formdata.c \ + ftp.c ftplistparser.c getenv.c getinfo.c gopher.c hash.c \ + headers.c hmac.c hostasyn.c hostip.c hostip4.c hostip6.c \ + hostsyn.c hsts.c http.c http1.c http2.c http_aws_sigv4.c \ + http_chunks.c http_digest.c http_negotiate.c http_ntlm.c \ + http_proxy.c idn.c if2ip.c imap.c inet_ntop.c inet_pton.c \ + krb5.c ldap.c llist.c macos.c md4.c md5.c memdebug.c mime.c \ + mprintf.c mqtt.c multi.c netrc.c nonblock.c noproxy.c \ + openldap.c parsedate.c pingpong.c pop3.c progress.c psl.c \ + rand.c rename.c request.c rtsp.c select.c sendf.c setopt.c \ + sha256.c share.c slist.c smb.c smtp.c socketpair.c socks.c \ + socks_gssapi.c socks_sspi.c speedcheck.c splay.c strcase.c \ + strdup.c strerror.c strtok.c strtoofft.c system_win32.c \ + telnet.c tftp.c timediff.c timeval.c transfer.c url.c urlapi.c \ + version.c version_win32.c warnless.c ws.c vauth/cleartext.c \ + vauth/cram.c vauth/digest.c vauth/digest_sspi.c vauth/gsasl.c \ + vauth/krb5_gssapi.c vauth/krb5_sspi.c vauth/ntlm.c \ + vauth/ntlm_sspi.c vauth/oauth2.c vauth/spnego_gssapi.c \ + vauth/spnego_sspi.c vauth/vauth.c vtls/bearssl.c \ + vtls/cipher_suite.c vtls/gtls.c vtls/hostcheck.c vtls/keylog.c \ + vtls/mbedtls.c vtls/mbedtls_threadlock.c vtls/openssl.c \ + vtls/rustls.c vtls/schannel.c vtls/schannel_verify.c \ + vtls/sectransp.c vtls/vtls.c vtls/wolfssl.c vtls/x509asn1.c \ + vquic/curl_msh3.c vquic/curl_ngtcp2.c vquic/curl_osslq.c \ + vquic/curl_quiche.c vquic/vquic.c vquic/vquic-tls.c \ + vssh/libssh.c vssh/libssh2.c vssh/wolfssh.c altsvc.h amigaos.h \ + arpa_telnet.h asyn.h bufq.h bufref.h c-hyper.h cf-h1-proxy.h \ + cf-h2-proxy.h cf-haproxy.h cf-https-connect.h cf-socket.h \ + cfilters.h conncache.h connect.h content_encoding.h cookie.h \ + curl_addrinfo.h curl_base64.h curl_ctype.h curl_des.h \ + curl_endian.h curl_fnmatch.h curl_get_line.h \ + curl_gethostname.h curl_gssapi.h curl_hmac.h curl_krb5.h \ + curl_ldap.h curl_md4.h curl_md5.h curl_memory.h curl_memrchr.h \ + curl_multibyte.h curl_ntlm_core.h curl_path.h curl_printf.h \ + curl_range.h curl_rtmp.h curl_sasl.h curl_setup.h \ + curl_setup_once.h curl_sha256.h curl_sha512_256.h curl_sspi.h \ + curl_threads.h curl_trc.h curlx.h cw-out.h dict.h doh.h \ + dynbuf.h dynhds.h easy_lock.h easyif.h easyoptions.h escape.h \ + file.h fileinfo.h fopen.h formdata.h ftp.h ftplistparser.h \ + functypes.h getinfo.h gopher.h hash.h headers.h hostip.h \ + hsts.h http.h http1.h http2.h http_aws_sigv4.h http_chunks.h \ + http_digest.h http_negotiate.h http_ntlm.h http_proxy.h idn.h \ + if2ip.h imap.h inet_ntop.h inet_pton.h llist.h macos.h \ + memdebug.h mime.h mqtt.h multihandle.h multiif.h netrc.h \ + nonblock.h noproxy.h parsedate.h pingpong.h pop3.h progress.h \ + psl.h rand.h rename.h request.h rtsp.h select.h sendf.h \ + setopt.h setup-vms.h share.h sigpipe.h slist.h smb.h smtp.h \ + sockaddr.h socketpair.h socks.h speedcheck.h splay.h strcase.h \ + strdup.h strerror.h strtok.h strtoofft.h system_win32.h \ + telnet.h tftp.h timediff.h timeval.h transfer.h url.h \ + urlapi-int.h urldata.h version_win32.h warnless.h ws.h \ + vauth/digest.h vauth/ntlm.h vauth/vauth.h vtls/bearssl.h \ + vtls/cipher_suite.h vtls/gtls.h vtls/hostcheck.h vtls/keylog.h \ + vtls/mbedtls.h vtls/mbedtls_threadlock.h vtls/openssl.h \ + vtls/rustls.h vtls/schannel.h vtls/schannel_int.h \ + vtls/sectransp.h vtls/vtls.h vtls/vtls_int.h vtls/wolfssl.h \ + vtls/x509asn1.h vquic/curl_msh3.h vquic/curl_ngtcp2.h \ + vquic/curl_osslq.h vquic/curl_quiche.h vquic/vquic.h \ + vquic/vquic_int.h vquic/vquic-tls.h vssh/ssh.h libcurl.rc +am__objects_1 = libcurl_la-altsvc.lo libcurl_la-amigaos.lo \ + libcurl_la-asyn-ares.lo libcurl_la-asyn-thread.lo \ + libcurl_la-base64.lo libcurl_la-bufq.lo libcurl_la-bufref.lo \ + libcurl_la-c-hyper.lo libcurl_la-cf-h1-proxy.lo \ + libcurl_la-cf-h2-proxy.lo libcurl_la-cf-haproxy.lo \ + libcurl_la-cf-https-connect.lo libcurl_la-cf-socket.lo \ + libcurl_la-cfilters.lo libcurl_la-conncache.lo \ + libcurl_la-connect.lo libcurl_la-content_encoding.lo \ + libcurl_la-cookie.lo libcurl_la-curl_addrinfo.lo \ + libcurl_la-curl_des.lo libcurl_la-curl_endian.lo \ + libcurl_la-curl_fnmatch.lo libcurl_la-curl_get_line.lo \ + libcurl_la-curl_gethostname.lo libcurl_la-curl_gssapi.lo \ + libcurl_la-curl_memrchr.lo libcurl_la-curl_multibyte.lo \ + libcurl_la-curl_ntlm_core.lo libcurl_la-curl_path.lo \ + libcurl_la-curl_range.lo libcurl_la-curl_rtmp.lo \ + libcurl_la-curl_sasl.lo libcurl_la-curl_sha512_256.lo \ + libcurl_la-curl_sspi.lo libcurl_la-curl_threads.lo \ + libcurl_la-curl_trc.lo libcurl_la-cw-out.lo libcurl_la-dict.lo \ + libcurl_la-dllmain.lo libcurl_la-doh.lo libcurl_la-dynbuf.lo \ + libcurl_la-dynhds.lo libcurl_la-easy.lo \ + libcurl_la-easygetopt.lo libcurl_la-easyoptions.lo \ + libcurl_la-escape.lo libcurl_la-file.lo libcurl_la-fileinfo.lo \ + libcurl_la-fopen.lo libcurl_la-formdata.lo libcurl_la-ftp.lo \ + libcurl_la-ftplistparser.lo libcurl_la-getenv.lo \ + libcurl_la-getinfo.lo libcurl_la-gopher.lo libcurl_la-hash.lo \ + libcurl_la-headers.lo libcurl_la-hmac.lo \ + libcurl_la-hostasyn.lo libcurl_la-hostip.lo \ + libcurl_la-hostip4.lo libcurl_la-hostip6.lo \ + libcurl_la-hostsyn.lo libcurl_la-hsts.lo libcurl_la-http.lo \ + libcurl_la-http1.lo libcurl_la-http2.lo \ + libcurl_la-http_aws_sigv4.lo libcurl_la-http_chunks.lo \ + libcurl_la-http_digest.lo libcurl_la-http_negotiate.lo \ + libcurl_la-http_ntlm.lo libcurl_la-http_proxy.lo \ + libcurl_la-idn.lo libcurl_la-if2ip.lo libcurl_la-imap.lo \ + libcurl_la-inet_ntop.lo libcurl_la-inet_pton.lo \ + libcurl_la-krb5.lo libcurl_la-ldap.lo libcurl_la-llist.lo \ + libcurl_la-macos.lo libcurl_la-md4.lo libcurl_la-md5.lo \ + libcurl_la-memdebug.lo libcurl_la-mime.lo \ + libcurl_la-mprintf.lo libcurl_la-mqtt.lo libcurl_la-multi.lo \ + libcurl_la-netrc.lo libcurl_la-nonblock.lo \ + libcurl_la-noproxy.lo libcurl_la-openldap.lo \ + libcurl_la-parsedate.lo libcurl_la-pingpong.lo \ + libcurl_la-pop3.lo libcurl_la-progress.lo libcurl_la-psl.lo \ + libcurl_la-rand.lo libcurl_la-rename.lo libcurl_la-request.lo \ + libcurl_la-rtsp.lo libcurl_la-select.lo libcurl_la-sendf.lo \ + libcurl_la-setopt.lo libcurl_la-sha256.lo libcurl_la-share.lo \ + libcurl_la-slist.lo libcurl_la-smb.lo libcurl_la-smtp.lo \ + libcurl_la-socketpair.lo libcurl_la-socks.lo \ + libcurl_la-socks_gssapi.lo libcurl_la-socks_sspi.lo \ + libcurl_la-speedcheck.lo libcurl_la-splay.lo \ + libcurl_la-strcase.lo libcurl_la-strdup.lo \ + libcurl_la-strerror.lo libcurl_la-strtok.lo \ + libcurl_la-strtoofft.lo libcurl_la-system_win32.lo \ + libcurl_la-telnet.lo libcurl_la-tftp.lo libcurl_la-timediff.lo \ + libcurl_la-timeval.lo libcurl_la-transfer.lo libcurl_la-url.lo \ + libcurl_la-urlapi.lo libcurl_la-version.lo \ + libcurl_la-version_win32.lo libcurl_la-warnless.lo \ + libcurl_la-ws.lo +am__dirstamp = $(am__leading_dot)dirstamp +am__objects_2 = vauth/libcurl_la-cleartext.lo vauth/libcurl_la-cram.lo \ + vauth/libcurl_la-digest.lo vauth/libcurl_la-digest_sspi.lo \ + vauth/libcurl_la-gsasl.lo vauth/libcurl_la-krb5_gssapi.lo \ + vauth/libcurl_la-krb5_sspi.lo vauth/libcurl_la-ntlm.lo \ + vauth/libcurl_la-ntlm_sspi.lo vauth/libcurl_la-oauth2.lo \ + vauth/libcurl_la-spnego_gssapi.lo \ + vauth/libcurl_la-spnego_sspi.lo vauth/libcurl_la-vauth.lo +am__objects_3 = vtls/libcurl_la-bearssl.lo \ + vtls/libcurl_la-cipher_suite.lo vtls/libcurl_la-gtls.lo \ + vtls/libcurl_la-hostcheck.lo vtls/libcurl_la-keylog.lo \ + vtls/libcurl_la-mbedtls.lo \ + vtls/libcurl_la-mbedtls_threadlock.lo \ + vtls/libcurl_la-openssl.lo vtls/libcurl_la-rustls.lo \ + vtls/libcurl_la-schannel.lo vtls/libcurl_la-schannel_verify.lo \ + vtls/libcurl_la-sectransp.lo vtls/libcurl_la-vtls.lo \ + vtls/libcurl_la-wolfssl.lo vtls/libcurl_la-x509asn1.lo +am__objects_4 = vquic/libcurl_la-curl_msh3.lo \ + vquic/libcurl_la-curl_ngtcp2.lo vquic/libcurl_la-curl_osslq.lo \ + vquic/libcurl_la-curl_quiche.lo vquic/libcurl_la-vquic.lo \ + vquic/libcurl_la-vquic-tls.lo +am__objects_5 = vssh/libcurl_la-libssh.lo vssh/libcurl_la-libssh2.lo \ + vssh/libcurl_la-wolfssh.lo +am__objects_6 = $(am__objects_1) $(am__objects_2) $(am__objects_3) \ + $(am__objects_4) $(am__objects_5) +am__objects_7 = +am__objects_8 = $(am__objects_7) $(am__objects_7) $(am__objects_7) \ + $(am__objects_7) $(am__objects_7) +am__objects_9 = libcurl.lo +@HAVE_WINDRES_TRUE@@USE_CPPFLAG_CURL_STATICLIB_FALSE@am__objects_10 = $(am__objects_9) +am_libcurl_la_OBJECTS = $(am__objects_6) $(am__objects_8) \ + $(am__objects_10) +libcurl_la_OBJECTS = $(am_libcurl_la_OBJECTS) +AM_V_lt = $(am__v_lt_@AM_V@) +am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) +am__v_lt_0 = --silent +am__v_lt_1 = +libcurl_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(libcurl_la_CFLAGS) \ + $(CFLAGS) $(libcurl_la_LDFLAGS) $(LDFLAGS) -o $@ +libcurlu_la_LIBADD = +am__objects_11 = libcurlu_la-altsvc.lo libcurlu_la-amigaos.lo \ + libcurlu_la-asyn-ares.lo libcurlu_la-asyn-thread.lo \ + libcurlu_la-base64.lo libcurlu_la-bufq.lo \ + libcurlu_la-bufref.lo libcurlu_la-c-hyper.lo \ + libcurlu_la-cf-h1-proxy.lo libcurlu_la-cf-h2-proxy.lo \ + libcurlu_la-cf-haproxy.lo libcurlu_la-cf-https-connect.lo \ + libcurlu_la-cf-socket.lo libcurlu_la-cfilters.lo \ + libcurlu_la-conncache.lo libcurlu_la-connect.lo \ + libcurlu_la-content_encoding.lo libcurlu_la-cookie.lo \ + libcurlu_la-curl_addrinfo.lo libcurlu_la-curl_des.lo \ + libcurlu_la-curl_endian.lo libcurlu_la-curl_fnmatch.lo \ + libcurlu_la-curl_get_line.lo libcurlu_la-curl_gethostname.lo \ + libcurlu_la-curl_gssapi.lo libcurlu_la-curl_memrchr.lo \ + libcurlu_la-curl_multibyte.lo libcurlu_la-curl_ntlm_core.lo \ + libcurlu_la-curl_path.lo libcurlu_la-curl_range.lo \ + libcurlu_la-curl_rtmp.lo libcurlu_la-curl_sasl.lo \ + libcurlu_la-curl_sha512_256.lo libcurlu_la-curl_sspi.lo \ + libcurlu_la-curl_threads.lo libcurlu_la-curl_trc.lo \ + libcurlu_la-cw-out.lo libcurlu_la-dict.lo \ + libcurlu_la-dllmain.lo libcurlu_la-doh.lo \ + libcurlu_la-dynbuf.lo libcurlu_la-dynhds.lo \ + libcurlu_la-easy.lo libcurlu_la-easygetopt.lo \ + libcurlu_la-easyoptions.lo libcurlu_la-escape.lo \ + libcurlu_la-file.lo libcurlu_la-fileinfo.lo \ + libcurlu_la-fopen.lo libcurlu_la-formdata.lo \ + libcurlu_la-ftp.lo libcurlu_la-ftplistparser.lo \ + libcurlu_la-getenv.lo libcurlu_la-getinfo.lo \ + libcurlu_la-gopher.lo libcurlu_la-hash.lo \ + libcurlu_la-headers.lo libcurlu_la-hmac.lo \ + libcurlu_la-hostasyn.lo libcurlu_la-hostip.lo \ + libcurlu_la-hostip4.lo libcurlu_la-hostip6.lo \ + libcurlu_la-hostsyn.lo libcurlu_la-hsts.lo libcurlu_la-http.lo \ + libcurlu_la-http1.lo libcurlu_la-http2.lo \ + libcurlu_la-http_aws_sigv4.lo libcurlu_la-http_chunks.lo \ + libcurlu_la-http_digest.lo libcurlu_la-http_negotiate.lo \ + libcurlu_la-http_ntlm.lo libcurlu_la-http_proxy.lo \ + libcurlu_la-idn.lo libcurlu_la-if2ip.lo libcurlu_la-imap.lo \ + libcurlu_la-inet_ntop.lo libcurlu_la-inet_pton.lo \ + libcurlu_la-krb5.lo libcurlu_la-ldap.lo libcurlu_la-llist.lo \ + libcurlu_la-macos.lo libcurlu_la-md4.lo libcurlu_la-md5.lo \ + libcurlu_la-memdebug.lo libcurlu_la-mime.lo \ + libcurlu_la-mprintf.lo libcurlu_la-mqtt.lo \ + libcurlu_la-multi.lo libcurlu_la-netrc.lo \ + libcurlu_la-nonblock.lo libcurlu_la-noproxy.lo \ + libcurlu_la-openldap.lo libcurlu_la-parsedate.lo \ + libcurlu_la-pingpong.lo libcurlu_la-pop3.lo \ + libcurlu_la-progress.lo libcurlu_la-psl.lo libcurlu_la-rand.lo \ + libcurlu_la-rename.lo libcurlu_la-request.lo \ + libcurlu_la-rtsp.lo libcurlu_la-select.lo libcurlu_la-sendf.lo \ + libcurlu_la-setopt.lo libcurlu_la-sha256.lo \ + libcurlu_la-share.lo libcurlu_la-slist.lo libcurlu_la-smb.lo \ + libcurlu_la-smtp.lo libcurlu_la-socketpair.lo \ + libcurlu_la-socks.lo libcurlu_la-socks_gssapi.lo \ + libcurlu_la-socks_sspi.lo libcurlu_la-speedcheck.lo \ + libcurlu_la-splay.lo libcurlu_la-strcase.lo \ + libcurlu_la-strdup.lo libcurlu_la-strerror.lo \ + libcurlu_la-strtok.lo libcurlu_la-strtoofft.lo \ + libcurlu_la-system_win32.lo libcurlu_la-telnet.lo \ + libcurlu_la-tftp.lo libcurlu_la-timediff.lo \ + libcurlu_la-timeval.lo libcurlu_la-transfer.lo \ + libcurlu_la-url.lo libcurlu_la-urlapi.lo \ + libcurlu_la-version.lo libcurlu_la-version_win32.lo \ + libcurlu_la-warnless.lo libcurlu_la-ws.lo +am__objects_12 = vauth/libcurlu_la-cleartext.lo \ + vauth/libcurlu_la-cram.lo vauth/libcurlu_la-digest.lo \ + vauth/libcurlu_la-digest_sspi.lo vauth/libcurlu_la-gsasl.lo \ + vauth/libcurlu_la-krb5_gssapi.lo \ + vauth/libcurlu_la-krb5_sspi.lo vauth/libcurlu_la-ntlm.lo \ + vauth/libcurlu_la-ntlm_sspi.lo vauth/libcurlu_la-oauth2.lo \ + vauth/libcurlu_la-spnego_gssapi.lo \ + vauth/libcurlu_la-spnego_sspi.lo vauth/libcurlu_la-vauth.lo +am__objects_13 = vtls/libcurlu_la-bearssl.lo \ + vtls/libcurlu_la-cipher_suite.lo vtls/libcurlu_la-gtls.lo \ + vtls/libcurlu_la-hostcheck.lo vtls/libcurlu_la-keylog.lo \ + vtls/libcurlu_la-mbedtls.lo \ + vtls/libcurlu_la-mbedtls_threadlock.lo \ + vtls/libcurlu_la-openssl.lo vtls/libcurlu_la-rustls.lo \ + vtls/libcurlu_la-schannel.lo \ + vtls/libcurlu_la-schannel_verify.lo \ + vtls/libcurlu_la-sectransp.lo vtls/libcurlu_la-vtls.lo \ + vtls/libcurlu_la-wolfssl.lo vtls/libcurlu_la-x509asn1.lo +am__objects_14 = vquic/libcurlu_la-curl_msh3.lo \ + vquic/libcurlu_la-curl_ngtcp2.lo \ + vquic/libcurlu_la-curl_osslq.lo \ + vquic/libcurlu_la-curl_quiche.lo vquic/libcurlu_la-vquic.lo \ + vquic/libcurlu_la-vquic-tls.lo +am__objects_15 = vssh/libcurlu_la-libssh.lo \ + vssh/libcurlu_la-libssh2.lo vssh/libcurlu_la-wolfssh.lo +am__objects_16 = $(am__objects_11) $(am__objects_12) $(am__objects_13) \ + $(am__objects_14) $(am__objects_15) +am_libcurlu_la_OBJECTS = $(am__objects_16) $(am__objects_8) +libcurlu_la_OBJECTS = $(am_libcurlu_la_OBJECTS) +libcurlu_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(libcurlu_la_CFLAGS) \ + $(CFLAGS) $(libcurlu_la_LDFLAGS) $(LDFLAGS) -o $@ +@BUILD_UNITTESTS_TRUE@am_libcurlu_la_rpath = +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = +depcomp = $(SHELL) $(top_srcdir)/depcomp +am__maybe_remake_depfiles = depfiles +am__depfiles_remade = ./$(DEPDIR)/libcurl_la-altsvc.Plo \ + ./$(DEPDIR)/libcurl_la-amigaos.Plo \ + ./$(DEPDIR)/libcurl_la-asyn-ares.Plo \ + ./$(DEPDIR)/libcurl_la-asyn-thread.Plo \ + ./$(DEPDIR)/libcurl_la-base64.Plo \ + ./$(DEPDIR)/libcurl_la-bufq.Plo \ + ./$(DEPDIR)/libcurl_la-bufref.Plo \ + ./$(DEPDIR)/libcurl_la-c-hyper.Plo \ + ./$(DEPDIR)/libcurl_la-cf-h1-proxy.Plo \ + ./$(DEPDIR)/libcurl_la-cf-h2-proxy.Plo \ + ./$(DEPDIR)/libcurl_la-cf-haproxy.Plo \ + ./$(DEPDIR)/libcurl_la-cf-https-connect.Plo \ + ./$(DEPDIR)/libcurl_la-cf-socket.Plo \ + ./$(DEPDIR)/libcurl_la-cfilters.Plo \ + ./$(DEPDIR)/libcurl_la-conncache.Plo \ + ./$(DEPDIR)/libcurl_la-connect.Plo \ + ./$(DEPDIR)/libcurl_la-content_encoding.Plo \ + ./$(DEPDIR)/libcurl_la-cookie.Plo \ + ./$(DEPDIR)/libcurl_la-curl_addrinfo.Plo \ + ./$(DEPDIR)/libcurl_la-curl_des.Plo \ + ./$(DEPDIR)/libcurl_la-curl_endian.Plo \ + ./$(DEPDIR)/libcurl_la-curl_fnmatch.Plo \ + ./$(DEPDIR)/libcurl_la-curl_get_line.Plo \ + ./$(DEPDIR)/libcurl_la-curl_gethostname.Plo \ + ./$(DEPDIR)/libcurl_la-curl_gssapi.Plo \ + ./$(DEPDIR)/libcurl_la-curl_memrchr.Plo \ + ./$(DEPDIR)/libcurl_la-curl_multibyte.Plo \ + ./$(DEPDIR)/libcurl_la-curl_ntlm_core.Plo \ + ./$(DEPDIR)/libcurl_la-curl_path.Plo \ + ./$(DEPDIR)/libcurl_la-curl_range.Plo \ + ./$(DEPDIR)/libcurl_la-curl_rtmp.Plo \ + ./$(DEPDIR)/libcurl_la-curl_sasl.Plo \ + ./$(DEPDIR)/libcurl_la-curl_sha512_256.Plo \ + ./$(DEPDIR)/libcurl_la-curl_sspi.Plo \ + ./$(DEPDIR)/libcurl_la-curl_threads.Plo \ + ./$(DEPDIR)/libcurl_la-curl_trc.Plo \ + ./$(DEPDIR)/libcurl_la-cw-out.Plo \ + ./$(DEPDIR)/libcurl_la-dict.Plo \ + ./$(DEPDIR)/libcurl_la-dllmain.Plo \ + ./$(DEPDIR)/libcurl_la-doh.Plo \ + ./$(DEPDIR)/libcurl_la-dynbuf.Plo \ + ./$(DEPDIR)/libcurl_la-dynhds.Plo \ + ./$(DEPDIR)/libcurl_la-easy.Plo \ + ./$(DEPDIR)/libcurl_la-easygetopt.Plo \ + ./$(DEPDIR)/libcurl_la-easyoptions.Plo \ + ./$(DEPDIR)/libcurl_la-escape.Plo \ + ./$(DEPDIR)/libcurl_la-file.Plo \ + ./$(DEPDIR)/libcurl_la-fileinfo.Plo \ + ./$(DEPDIR)/libcurl_la-fopen.Plo \ + ./$(DEPDIR)/libcurl_la-formdata.Plo \ + ./$(DEPDIR)/libcurl_la-ftp.Plo \ + ./$(DEPDIR)/libcurl_la-ftplistparser.Plo \ + ./$(DEPDIR)/libcurl_la-getenv.Plo \ + ./$(DEPDIR)/libcurl_la-getinfo.Plo \ + ./$(DEPDIR)/libcurl_la-gopher.Plo \ + ./$(DEPDIR)/libcurl_la-hash.Plo \ + ./$(DEPDIR)/libcurl_la-headers.Plo \ + ./$(DEPDIR)/libcurl_la-hmac.Plo \ + ./$(DEPDIR)/libcurl_la-hostasyn.Plo \ + ./$(DEPDIR)/libcurl_la-hostip.Plo \ + ./$(DEPDIR)/libcurl_la-hostip4.Plo \ + ./$(DEPDIR)/libcurl_la-hostip6.Plo \ + ./$(DEPDIR)/libcurl_la-hostsyn.Plo \ + ./$(DEPDIR)/libcurl_la-hsts.Plo \ + ./$(DEPDIR)/libcurl_la-http.Plo \ + ./$(DEPDIR)/libcurl_la-http1.Plo \ + ./$(DEPDIR)/libcurl_la-http2.Plo \ + ./$(DEPDIR)/libcurl_la-http_aws_sigv4.Plo \ + ./$(DEPDIR)/libcurl_la-http_chunks.Plo \ + ./$(DEPDIR)/libcurl_la-http_digest.Plo \ + ./$(DEPDIR)/libcurl_la-http_negotiate.Plo \ + ./$(DEPDIR)/libcurl_la-http_ntlm.Plo \ + ./$(DEPDIR)/libcurl_la-http_proxy.Plo \ + ./$(DEPDIR)/libcurl_la-idn.Plo \ + ./$(DEPDIR)/libcurl_la-if2ip.Plo \ + ./$(DEPDIR)/libcurl_la-imap.Plo \ + ./$(DEPDIR)/libcurl_la-inet_ntop.Plo \ + ./$(DEPDIR)/libcurl_la-inet_pton.Plo \ + ./$(DEPDIR)/libcurl_la-krb5.Plo \ + ./$(DEPDIR)/libcurl_la-ldap.Plo \ + ./$(DEPDIR)/libcurl_la-llist.Plo \ + ./$(DEPDIR)/libcurl_la-macos.Plo \ + ./$(DEPDIR)/libcurl_la-md4.Plo ./$(DEPDIR)/libcurl_la-md5.Plo \ + ./$(DEPDIR)/libcurl_la-memdebug.Plo \ + ./$(DEPDIR)/libcurl_la-mime.Plo \ + ./$(DEPDIR)/libcurl_la-mprintf.Plo \ + ./$(DEPDIR)/libcurl_la-mqtt.Plo \ + ./$(DEPDIR)/libcurl_la-multi.Plo \ + ./$(DEPDIR)/libcurl_la-netrc.Plo \ + ./$(DEPDIR)/libcurl_la-nonblock.Plo \ + ./$(DEPDIR)/libcurl_la-noproxy.Plo \ + ./$(DEPDIR)/libcurl_la-openldap.Plo \ + ./$(DEPDIR)/libcurl_la-parsedate.Plo \ + ./$(DEPDIR)/libcurl_la-pingpong.Plo \ + ./$(DEPDIR)/libcurl_la-pop3.Plo \ + ./$(DEPDIR)/libcurl_la-progress.Plo \ + ./$(DEPDIR)/libcurl_la-psl.Plo ./$(DEPDIR)/libcurl_la-rand.Plo \ + ./$(DEPDIR)/libcurl_la-rename.Plo \ + ./$(DEPDIR)/libcurl_la-request.Plo \ + ./$(DEPDIR)/libcurl_la-rtsp.Plo \ + ./$(DEPDIR)/libcurl_la-select.Plo \ + ./$(DEPDIR)/libcurl_la-sendf.Plo \ + ./$(DEPDIR)/libcurl_la-setopt.Plo \ + ./$(DEPDIR)/libcurl_la-sha256.Plo \ + ./$(DEPDIR)/libcurl_la-share.Plo \ + ./$(DEPDIR)/libcurl_la-slist.Plo \ + ./$(DEPDIR)/libcurl_la-smb.Plo ./$(DEPDIR)/libcurl_la-smtp.Plo \ + ./$(DEPDIR)/libcurl_la-socketpair.Plo \ + ./$(DEPDIR)/libcurl_la-socks.Plo \ + ./$(DEPDIR)/libcurl_la-socks_gssapi.Plo \ + ./$(DEPDIR)/libcurl_la-socks_sspi.Plo \ + ./$(DEPDIR)/libcurl_la-speedcheck.Plo \ + ./$(DEPDIR)/libcurl_la-splay.Plo \ + ./$(DEPDIR)/libcurl_la-strcase.Plo \ + ./$(DEPDIR)/libcurl_la-strdup.Plo \ + ./$(DEPDIR)/libcurl_la-strerror.Plo \ + ./$(DEPDIR)/libcurl_la-strtok.Plo \ + ./$(DEPDIR)/libcurl_la-strtoofft.Plo \ + ./$(DEPDIR)/libcurl_la-system_win32.Plo \ + ./$(DEPDIR)/libcurl_la-telnet.Plo \ + ./$(DEPDIR)/libcurl_la-tftp.Plo \ + ./$(DEPDIR)/libcurl_la-timediff.Plo \ + ./$(DEPDIR)/libcurl_la-timeval.Plo \ + ./$(DEPDIR)/libcurl_la-transfer.Plo \ + ./$(DEPDIR)/libcurl_la-url.Plo \ + ./$(DEPDIR)/libcurl_la-urlapi.Plo \ + ./$(DEPDIR)/libcurl_la-version.Plo \ + ./$(DEPDIR)/libcurl_la-version_win32.Plo \ + ./$(DEPDIR)/libcurl_la-warnless.Plo \ + ./$(DEPDIR)/libcurl_la-ws.Plo \ + ./$(DEPDIR)/libcurlu_la-altsvc.Plo \ + ./$(DEPDIR)/libcurlu_la-amigaos.Plo \ + ./$(DEPDIR)/libcurlu_la-asyn-ares.Plo \ + ./$(DEPDIR)/libcurlu_la-asyn-thread.Plo \ + ./$(DEPDIR)/libcurlu_la-base64.Plo \ + ./$(DEPDIR)/libcurlu_la-bufq.Plo \ + ./$(DEPDIR)/libcurlu_la-bufref.Plo \ + ./$(DEPDIR)/libcurlu_la-c-hyper.Plo \ + ./$(DEPDIR)/libcurlu_la-cf-h1-proxy.Plo \ + ./$(DEPDIR)/libcurlu_la-cf-h2-proxy.Plo \ + ./$(DEPDIR)/libcurlu_la-cf-haproxy.Plo \ + ./$(DEPDIR)/libcurlu_la-cf-https-connect.Plo \ + ./$(DEPDIR)/libcurlu_la-cf-socket.Plo \ + ./$(DEPDIR)/libcurlu_la-cfilters.Plo \ + ./$(DEPDIR)/libcurlu_la-conncache.Plo \ + ./$(DEPDIR)/libcurlu_la-connect.Plo \ + ./$(DEPDIR)/libcurlu_la-content_encoding.Plo \ + ./$(DEPDIR)/libcurlu_la-cookie.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_addrinfo.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_des.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_endian.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_fnmatch.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_get_line.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_gethostname.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_gssapi.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_memrchr.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_multibyte.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_ntlm_core.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_path.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_range.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_rtmp.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_sasl.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_sha512_256.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_sspi.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_threads.Plo \ + ./$(DEPDIR)/libcurlu_la-curl_trc.Plo \ + ./$(DEPDIR)/libcurlu_la-cw-out.Plo \ + ./$(DEPDIR)/libcurlu_la-dict.Plo \ + ./$(DEPDIR)/libcurlu_la-dllmain.Plo \ + ./$(DEPDIR)/libcurlu_la-doh.Plo \ + ./$(DEPDIR)/libcurlu_la-dynbuf.Plo \ + ./$(DEPDIR)/libcurlu_la-dynhds.Plo \ + ./$(DEPDIR)/libcurlu_la-easy.Plo \ + ./$(DEPDIR)/libcurlu_la-easygetopt.Plo \ + ./$(DEPDIR)/libcurlu_la-easyoptions.Plo \ + ./$(DEPDIR)/libcurlu_la-escape.Plo \ + ./$(DEPDIR)/libcurlu_la-file.Plo \ + ./$(DEPDIR)/libcurlu_la-fileinfo.Plo \ + ./$(DEPDIR)/libcurlu_la-fopen.Plo \ + ./$(DEPDIR)/libcurlu_la-formdata.Plo \ + ./$(DEPDIR)/libcurlu_la-ftp.Plo \ + ./$(DEPDIR)/libcurlu_la-ftplistparser.Plo \ + ./$(DEPDIR)/libcurlu_la-getenv.Plo \ + ./$(DEPDIR)/libcurlu_la-getinfo.Plo \ + ./$(DEPDIR)/libcurlu_la-gopher.Plo \ + ./$(DEPDIR)/libcurlu_la-hash.Plo \ + ./$(DEPDIR)/libcurlu_la-headers.Plo \ + ./$(DEPDIR)/libcurlu_la-hmac.Plo \ + ./$(DEPDIR)/libcurlu_la-hostasyn.Plo \ + ./$(DEPDIR)/libcurlu_la-hostip.Plo \ + ./$(DEPDIR)/libcurlu_la-hostip4.Plo \ + ./$(DEPDIR)/libcurlu_la-hostip6.Plo \ + ./$(DEPDIR)/libcurlu_la-hostsyn.Plo \ + ./$(DEPDIR)/libcurlu_la-hsts.Plo \ + ./$(DEPDIR)/libcurlu_la-http.Plo \ + ./$(DEPDIR)/libcurlu_la-http1.Plo \ + ./$(DEPDIR)/libcurlu_la-http2.Plo \ + ./$(DEPDIR)/libcurlu_la-http_aws_sigv4.Plo \ + ./$(DEPDIR)/libcurlu_la-http_chunks.Plo \ + ./$(DEPDIR)/libcurlu_la-http_digest.Plo \ + ./$(DEPDIR)/libcurlu_la-http_negotiate.Plo \ + ./$(DEPDIR)/libcurlu_la-http_ntlm.Plo \ + ./$(DEPDIR)/libcurlu_la-http_proxy.Plo \ + ./$(DEPDIR)/libcurlu_la-idn.Plo \ + ./$(DEPDIR)/libcurlu_la-if2ip.Plo \ + ./$(DEPDIR)/libcurlu_la-imap.Plo \ + ./$(DEPDIR)/libcurlu_la-inet_ntop.Plo \ + ./$(DEPDIR)/libcurlu_la-inet_pton.Plo \ + ./$(DEPDIR)/libcurlu_la-krb5.Plo \ + ./$(DEPDIR)/libcurlu_la-ldap.Plo \ + ./$(DEPDIR)/libcurlu_la-llist.Plo \ + ./$(DEPDIR)/libcurlu_la-macos.Plo \ + ./$(DEPDIR)/libcurlu_la-md4.Plo \ + ./$(DEPDIR)/libcurlu_la-md5.Plo \ + ./$(DEPDIR)/libcurlu_la-memdebug.Plo \ + ./$(DEPDIR)/libcurlu_la-mime.Plo \ + ./$(DEPDIR)/libcurlu_la-mprintf.Plo \ + ./$(DEPDIR)/libcurlu_la-mqtt.Plo \ + ./$(DEPDIR)/libcurlu_la-multi.Plo \ + ./$(DEPDIR)/libcurlu_la-netrc.Plo \ + ./$(DEPDIR)/libcurlu_la-nonblock.Plo \ + ./$(DEPDIR)/libcurlu_la-noproxy.Plo \ + ./$(DEPDIR)/libcurlu_la-openldap.Plo \ + ./$(DEPDIR)/libcurlu_la-parsedate.Plo \ + ./$(DEPDIR)/libcurlu_la-pingpong.Plo \ + ./$(DEPDIR)/libcurlu_la-pop3.Plo \ + ./$(DEPDIR)/libcurlu_la-progress.Plo \ + ./$(DEPDIR)/libcurlu_la-psl.Plo \ + ./$(DEPDIR)/libcurlu_la-rand.Plo \ + ./$(DEPDIR)/libcurlu_la-rename.Plo \ + ./$(DEPDIR)/libcurlu_la-request.Plo \ + ./$(DEPDIR)/libcurlu_la-rtsp.Plo \ + ./$(DEPDIR)/libcurlu_la-select.Plo \ + ./$(DEPDIR)/libcurlu_la-sendf.Plo \ + ./$(DEPDIR)/libcurlu_la-setopt.Plo \ + ./$(DEPDIR)/libcurlu_la-sha256.Plo \ + ./$(DEPDIR)/libcurlu_la-share.Plo \ + ./$(DEPDIR)/libcurlu_la-slist.Plo \ + ./$(DEPDIR)/libcurlu_la-smb.Plo \ + ./$(DEPDIR)/libcurlu_la-smtp.Plo \ + ./$(DEPDIR)/libcurlu_la-socketpair.Plo \ + ./$(DEPDIR)/libcurlu_la-socks.Plo \ + ./$(DEPDIR)/libcurlu_la-socks_gssapi.Plo \ + ./$(DEPDIR)/libcurlu_la-socks_sspi.Plo \ + ./$(DEPDIR)/libcurlu_la-speedcheck.Plo \ + ./$(DEPDIR)/libcurlu_la-splay.Plo \ + ./$(DEPDIR)/libcurlu_la-strcase.Plo \ + ./$(DEPDIR)/libcurlu_la-strdup.Plo \ + ./$(DEPDIR)/libcurlu_la-strerror.Plo \ + ./$(DEPDIR)/libcurlu_la-strtok.Plo \ + ./$(DEPDIR)/libcurlu_la-strtoofft.Plo \ + ./$(DEPDIR)/libcurlu_la-system_win32.Plo \ + ./$(DEPDIR)/libcurlu_la-telnet.Plo \ + ./$(DEPDIR)/libcurlu_la-tftp.Plo \ + ./$(DEPDIR)/libcurlu_la-timediff.Plo \ + ./$(DEPDIR)/libcurlu_la-timeval.Plo \ + ./$(DEPDIR)/libcurlu_la-transfer.Plo \ + ./$(DEPDIR)/libcurlu_la-url.Plo \ + ./$(DEPDIR)/libcurlu_la-urlapi.Plo \ + ./$(DEPDIR)/libcurlu_la-version.Plo \ + ./$(DEPDIR)/libcurlu_la-version_win32.Plo \ + ./$(DEPDIR)/libcurlu_la-warnless.Plo \ + ./$(DEPDIR)/libcurlu_la-ws.Plo \ + vauth/$(DEPDIR)/libcurl_la-cleartext.Plo \ + vauth/$(DEPDIR)/libcurl_la-cram.Plo \ + vauth/$(DEPDIR)/libcurl_la-digest.Plo \ + vauth/$(DEPDIR)/libcurl_la-digest_sspi.Plo \ + vauth/$(DEPDIR)/libcurl_la-gsasl.Plo \ + vauth/$(DEPDIR)/libcurl_la-krb5_gssapi.Plo \ + vauth/$(DEPDIR)/libcurl_la-krb5_sspi.Plo \ + vauth/$(DEPDIR)/libcurl_la-ntlm.Plo \ + vauth/$(DEPDIR)/libcurl_la-ntlm_sspi.Plo \ + vauth/$(DEPDIR)/libcurl_la-oauth2.Plo \ + vauth/$(DEPDIR)/libcurl_la-spnego_gssapi.Plo \ + vauth/$(DEPDIR)/libcurl_la-spnego_sspi.Plo \ + vauth/$(DEPDIR)/libcurl_la-vauth.Plo \ + vauth/$(DEPDIR)/libcurlu_la-cleartext.Plo \ + vauth/$(DEPDIR)/libcurlu_la-cram.Plo \ + vauth/$(DEPDIR)/libcurlu_la-digest.Plo \ + vauth/$(DEPDIR)/libcurlu_la-digest_sspi.Plo \ + vauth/$(DEPDIR)/libcurlu_la-gsasl.Plo \ + vauth/$(DEPDIR)/libcurlu_la-krb5_gssapi.Plo \ + vauth/$(DEPDIR)/libcurlu_la-krb5_sspi.Plo \ + vauth/$(DEPDIR)/libcurlu_la-ntlm.Plo \ + vauth/$(DEPDIR)/libcurlu_la-ntlm_sspi.Plo \ + vauth/$(DEPDIR)/libcurlu_la-oauth2.Plo \ + vauth/$(DEPDIR)/libcurlu_la-spnego_gssapi.Plo \ + vauth/$(DEPDIR)/libcurlu_la-spnego_sspi.Plo \ + vauth/$(DEPDIR)/libcurlu_la-vauth.Plo \ + vquic/$(DEPDIR)/libcurl_la-curl_msh3.Plo \ + vquic/$(DEPDIR)/libcurl_la-curl_ngtcp2.Plo \ + vquic/$(DEPDIR)/libcurl_la-curl_osslq.Plo \ + vquic/$(DEPDIR)/libcurl_la-curl_quiche.Plo \ + vquic/$(DEPDIR)/libcurl_la-vquic-tls.Plo \ + vquic/$(DEPDIR)/libcurl_la-vquic.Plo \ + vquic/$(DEPDIR)/libcurlu_la-curl_msh3.Plo \ + vquic/$(DEPDIR)/libcurlu_la-curl_ngtcp2.Plo \ + vquic/$(DEPDIR)/libcurlu_la-curl_osslq.Plo \ + vquic/$(DEPDIR)/libcurlu_la-curl_quiche.Plo \ + vquic/$(DEPDIR)/libcurlu_la-vquic-tls.Plo \ + vquic/$(DEPDIR)/libcurlu_la-vquic.Plo \ + vssh/$(DEPDIR)/libcurl_la-libssh.Plo \ + vssh/$(DEPDIR)/libcurl_la-libssh2.Plo \ + vssh/$(DEPDIR)/libcurl_la-wolfssh.Plo \ + vssh/$(DEPDIR)/libcurlu_la-libssh.Plo \ + vssh/$(DEPDIR)/libcurlu_la-libssh2.Plo \ + vssh/$(DEPDIR)/libcurlu_la-wolfssh.Plo \ + vtls/$(DEPDIR)/libcurl_la-bearssl.Plo \ + vtls/$(DEPDIR)/libcurl_la-cipher_suite.Plo \ + vtls/$(DEPDIR)/libcurl_la-gtls.Plo \ + vtls/$(DEPDIR)/libcurl_la-hostcheck.Plo \ + vtls/$(DEPDIR)/libcurl_la-keylog.Plo \ + vtls/$(DEPDIR)/libcurl_la-mbedtls.Plo \ + vtls/$(DEPDIR)/libcurl_la-mbedtls_threadlock.Plo \ + vtls/$(DEPDIR)/libcurl_la-openssl.Plo \ + vtls/$(DEPDIR)/libcurl_la-rustls.Plo \ + vtls/$(DEPDIR)/libcurl_la-schannel.Plo \ + vtls/$(DEPDIR)/libcurl_la-schannel_verify.Plo \ + vtls/$(DEPDIR)/libcurl_la-sectransp.Plo \ + vtls/$(DEPDIR)/libcurl_la-vtls.Plo \ + vtls/$(DEPDIR)/libcurl_la-wolfssl.Plo \ + vtls/$(DEPDIR)/libcurl_la-x509asn1.Plo \ + vtls/$(DEPDIR)/libcurlu_la-bearssl.Plo \ + vtls/$(DEPDIR)/libcurlu_la-cipher_suite.Plo \ + vtls/$(DEPDIR)/libcurlu_la-gtls.Plo \ + vtls/$(DEPDIR)/libcurlu_la-hostcheck.Plo \ + vtls/$(DEPDIR)/libcurlu_la-keylog.Plo \ + vtls/$(DEPDIR)/libcurlu_la-mbedtls.Plo \ + vtls/$(DEPDIR)/libcurlu_la-mbedtls_threadlock.Plo \ + vtls/$(DEPDIR)/libcurlu_la-openssl.Plo \ + vtls/$(DEPDIR)/libcurlu_la-rustls.Plo \ + vtls/$(DEPDIR)/libcurlu_la-schannel.Plo \ + vtls/$(DEPDIR)/libcurlu_la-schannel_verify.Plo \ + vtls/$(DEPDIR)/libcurlu_la-sectransp.Plo \ + vtls/$(DEPDIR)/libcurlu_la-vtls.Plo \ + vtls/$(DEPDIR)/libcurlu_la-wolfssl.Plo \ + vtls/$(DEPDIR)/libcurlu_la-x509asn1.Plo +am__mv = mv -f +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ + $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ + $(AM_CFLAGS) $(CFLAGS) +AM_V_CC = $(am__v_CC_@AM_V@) +am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) +am__v_CC_0 = @echo " CC " $@; +am__v_CC_1 = +CCLD = $(CC) +LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(AM_LDFLAGS) $(LDFLAGS) -o $@ +AM_V_CCLD = $(am__v_CCLD_@AM_V@) +am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) +am__v_CCLD_0 = @echo " CCLD " $@; +am__v_CCLD_1 = +SOURCES = $(libcurl_la_SOURCES) $(libcurlu_la_SOURCES) +DIST_SOURCES = $(am__libcurl_la_SOURCES_DIST) $(libcurlu_la_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) \ + curl_config.h.in +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` +am__DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.inc \ + $(srcdir)/Makefile.soname $(srcdir)/curl_config.h.in \ + $(srcdir)/libcurl.vers.in $(top_srcdir)/depcomp +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +APACHECTL = @APACHECTL@ +APXS = @APXS@ +AR = @AR@ +AR_FLAGS = @AR_FLAGS@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +BLANK_AT_MAKETIME = @BLANK_AT_MAKETIME@ +CADDY = @CADDY@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ + +# This might hold -Werror +CFLAGS = @CFLAGS@ @CURL_CFLAG_EXTRAS@ +CFLAG_CURL_SYMBOL_HIDING = @CFLAG_CURL_SYMBOL_HIDING@ +CONFIGURE_OPTIONS = @CONFIGURE_OPTIONS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CPPFLAG_CURL_STATICLIB = @CPPFLAG_CURL_STATICLIB@ +CSCOPE = @CSCOPE@ +CTAGS = @CTAGS@ +CURLVERSION = @CURLVERSION@ +CURL_CA_BUNDLE = @CURL_CA_BUNDLE@ +CURL_CFLAG_EXTRAS = @CURL_CFLAG_EXTRAS@ +CURL_DISABLE_DICT = @CURL_DISABLE_DICT@ +CURL_DISABLE_FILE = @CURL_DISABLE_FILE@ +CURL_DISABLE_FTP = @CURL_DISABLE_FTP@ +CURL_DISABLE_GOPHER = @CURL_DISABLE_GOPHER@ +CURL_DISABLE_HTTP = @CURL_DISABLE_HTTP@ +CURL_DISABLE_IMAP = @CURL_DISABLE_IMAP@ +CURL_DISABLE_LDAP = @CURL_DISABLE_LDAP@ +CURL_DISABLE_LDAPS = @CURL_DISABLE_LDAPS@ +CURL_DISABLE_MQTT = @CURL_DISABLE_MQTT@ +CURL_DISABLE_POP3 = @CURL_DISABLE_POP3@ +CURL_DISABLE_PROXY = @CURL_DISABLE_PROXY@ +CURL_DISABLE_RTSP = @CURL_DISABLE_RTSP@ +CURL_DISABLE_SMB = @CURL_DISABLE_SMB@ +CURL_DISABLE_SMTP = @CURL_DISABLE_SMTP@ +CURL_DISABLE_TELNET = @CURL_DISABLE_TELNET@ +CURL_DISABLE_TFTP = @CURL_DISABLE_TFTP@ +CURL_LT_SHLIB_VERSIONED_FLAVOUR = @CURL_LT_SHLIB_VERSIONED_FLAVOUR@ +CURL_NETWORK_AND_TIME_LIBS = @CURL_NETWORK_AND_TIME_LIBS@ +CURL_NETWORK_LIBS = @CURL_NETWORK_LIBS@ +CURL_WITH_MULTI_SSL = @CURL_WITH_MULTI_SSL@ +CYGPATH_W = @CYGPATH_W@ +DEFAULT_SSL_BACKEND = @DEFAULT_SSL_BACKEND@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +ENABLE_SHARED = @ENABLE_SHARED@ +ENABLE_STATIC = @ENABLE_STATIC@ +ETAGS = @ETAGS@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +FILECMD = @FILECMD@ +FISH_FUNCTIONS_DIR = @FISH_FUNCTIONS_DIR@ +GCOV = @GCOV@ +GREP = @GREP@ +HAVE_BROTLI = @HAVE_BROTLI@ +HAVE_GNUTLS_SRP = @HAVE_GNUTLS_SRP@ +HAVE_LDAP_SSL = @HAVE_LDAP_SSL@ +HAVE_LIBZ = @HAVE_LIBZ@ +HAVE_OPENSSL_QUIC = @HAVE_OPENSSL_QUIC@ +HAVE_OPENSSL_SRP = @HAVE_OPENSSL_SRP@ +HAVE_PROTO_BSDSOCKET_H = @HAVE_PROTO_BSDSOCKET_H@ +HAVE_ZSTD = @HAVE_ZSTD@ +HTTPD = @HTTPD@ +HTTPD_NGHTTPX = @HTTPD_NGHTTPX@ +IDN_ENABLED = @IDN_ENABLED@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +IPV6_ENABLED = @IPV6_ENABLED@ +LCOV = @LCOV@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBCURL_LIBS = @LIBCURL_LIBS@ +LIBCURL_NO_SHARED = @LIBCURL_NO_SHARED@ +LIBOBJS = @LIBOBJS@ + +# Prevent LIBS from being used for all link targets +LIBS = $(BLANK_AT_MAKETIME) +LIBTOOL = @LIBTOOL@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ +MAINT = @MAINT@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PERL = @PERL@ +PKGADD_NAME = @PKGADD_NAME@ +PKGADD_PKG = @PKGADD_PKG@ +PKGADD_VENDOR = @PKGADD_VENDOR@ +PKGCONFIG = @PKGCONFIG@ +RANDOM_FILE = @RANDOM_FILE@ +RANLIB = @RANLIB@ +RC = @RC@ +REQUIRE_LIB_DEPS = @REQUIRE_LIB_DEPS@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SSL_BACKENDS = @SSL_BACKENDS@ +SSL_ENABLED = @SSL_ENABLED@ +SSL_LIBS = @SSL_LIBS@ +STRIP = @STRIP@ +SUPPORT_FEATURES = @SUPPORT_FEATURES@ +SUPPORT_PROTOCOLS = @SUPPORT_PROTOCOLS@ +TEST_NGHTTPX = @TEST_NGHTTPX@ +USE_ARES = @USE_ARES@ +USE_BEARSSL = @USE_BEARSSL@ +USE_GNUTLS = @USE_GNUTLS@ +USE_HYPER = @USE_HYPER@ +USE_LIBPSL = @USE_LIBPSL@ +USE_LIBRTMP = @USE_LIBRTMP@ +USE_LIBSSH = @USE_LIBSSH@ +USE_LIBSSH2 = @USE_LIBSSH2@ +USE_MBEDTLS = @USE_MBEDTLS@ +USE_MSH3 = @USE_MSH3@ +USE_NGHTTP2 = @USE_NGHTTP2@ +USE_NGHTTP3 = @USE_NGHTTP3@ +USE_NGTCP2 = @USE_NGTCP2@ +USE_NGTCP2_CRYPTO_BORINGSSL = @USE_NGTCP2_CRYPTO_BORINGSSL@ +USE_NGTCP2_CRYPTO_GNUTLS = @USE_NGTCP2_CRYPTO_GNUTLS@ +USE_NGTCP2_CRYPTO_QUICTLS = @USE_NGTCP2_CRYPTO_QUICTLS@ +USE_NGTCP2_CRYPTO_WOLFSSL = @USE_NGTCP2_CRYPTO_WOLFSSL@ +USE_NGTCP2_H3 = @USE_NGTCP2_H3@ +USE_OPENLDAP = @USE_OPENLDAP@ +USE_OPENSSL_H3 = @USE_OPENSSL_H3@ +USE_OPENSSL_QUIC = @USE_OPENSSL_QUIC@ +USE_QUICHE = @USE_QUICHE@ +USE_RUSTLS = @USE_RUSTLS@ +USE_SCHANNEL = @USE_SCHANNEL@ +USE_SECTRANSP = @USE_SECTRANSP@ +USE_UNIX_SOCKETS = @USE_UNIX_SOCKETS@ +USE_WIN32_CRYPTO = @USE_WIN32_CRYPTO@ +USE_WIN32_LARGE_FILES = @USE_WIN32_LARGE_FILES@ +USE_WIN32_SMALL_FILES = @USE_WIN32_SMALL_FILES@ +USE_WINDOWS_SSPI = @USE_WINDOWS_SSPI@ +USE_WOLFSSH = @USE_WOLFSSH@ +USE_WOLFSSL = @USE_WOLFSSL@ +VERSION = @VERSION@ +VERSIONNUM = @VERSIONNUM@ +VSFTPD = @VSFTPD@ +ZLIB_LIBS = @ZLIB_LIBS@ +ZSH_FUNCTIONS_DIR = @ZSH_FUNCTIONS_DIR@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +libext = @libext@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +runstatedir = @runstatedir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ + +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +AUTOMAKE_OPTIONS = foreign nostdinc +CMAKE_DIST = CMakeLists.txt curl_config.h.cmake +EXTRA_DIST = Makefile.mk config-win32.h config-win32ce.h config-plan9.h \ + config-riscos.h config-mac.h curl_config.h.in config-dos.h libcurl.rc \ + config-amigaos.h config-win32ce.h config-os400.h setup-os400.h \ + $(CMAKE_DIST) setup-win32.h .checksrc Makefile.soname + +lib_LTLIBRARIES = libcurl.la +@BUILD_UNITTESTS_FALSE@noinst_LTLIBRARIES = +@BUILD_UNITTESTS_TRUE@noinst_LTLIBRARIES = libcurlu.la + +# Specify our include paths here, and do it relative to $(top_srcdir) and +# $(top_builddir), to ensure that these paths which belong to the library +# being currently built and tested are searched before the library which +# might possibly already be installed in the system. +# +# $(top_srcdir)/include is for libcurl's external include files +# $(top_builddir)/lib is for libcurl's generated lib/curl_config.h file +# $(top_srcdir)/lib for libcurl's lib/curl_setup.h and other "private" files +AM_CPPFLAGS = -I$(top_srcdir)/include -I$(top_builddir)/lib \ + -I$(top_srcdir)/lib -DBUILDING_LIBCURL +VERSIONCHANGE = 12 +VERSIONADD = 0 +VERSIONDEL = 8 + +# libtool version: +VERSIONINFO = -version-info $(VERSIONCHANGE):$(VERSIONADD):$(VERSIONDEL) +AM_LDFLAGS = +AM_CFLAGS = +LIB_VAUTH_CFILES = \ + vauth/cleartext.c \ + vauth/cram.c \ + vauth/digest.c \ + vauth/digest_sspi.c \ + vauth/gsasl.c \ + vauth/krb5_gssapi.c \ + vauth/krb5_sspi.c \ + vauth/ntlm.c \ + vauth/ntlm_sspi.c \ + vauth/oauth2.c \ + vauth/spnego_gssapi.c \ + vauth/spnego_sspi.c \ + vauth/vauth.c + +LIB_VAUTH_HFILES = \ + vauth/digest.h \ + vauth/ntlm.h \ + vauth/vauth.h + +LIB_VTLS_CFILES = \ + vtls/bearssl.c \ + vtls/cipher_suite.c \ + vtls/gtls.c \ + vtls/hostcheck.c \ + vtls/keylog.c \ + vtls/mbedtls.c \ + vtls/mbedtls_threadlock.c \ + vtls/openssl.c \ + vtls/rustls.c \ + vtls/schannel.c \ + vtls/schannel_verify.c \ + vtls/sectransp.c \ + vtls/vtls.c \ + vtls/wolfssl.c \ + vtls/x509asn1.c + +LIB_VTLS_HFILES = \ + vtls/bearssl.h \ + vtls/cipher_suite.h \ + vtls/gtls.h \ + vtls/hostcheck.h \ + vtls/keylog.h \ + vtls/mbedtls.h \ + vtls/mbedtls_threadlock.h \ + vtls/openssl.h \ + vtls/rustls.h \ + vtls/schannel.h \ + vtls/schannel_int.h \ + vtls/sectransp.h \ + vtls/vtls.h \ + vtls/vtls_int.h \ + vtls/wolfssl.h \ + vtls/x509asn1.h + +LIB_VQUIC_CFILES = \ + vquic/curl_msh3.c \ + vquic/curl_ngtcp2.c \ + vquic/curl_osslq.c \ + vquic/curl_quiche.c \ + vquic/vquic.c \ + vquic/vquic-tls.c + +LIB_VQUIC_HFILES = \ + vquic/curl_msh3.h \ + vquic/curl_ngtcp2.h \ + vquic/curl_osslq.h \ + vquic/curl_quiche.h \ + vquic/vquic.h \ + vquic/vquic_int.h \ + vquic/vquic-tls.h + +LIB_VSSH_CFILES = \ + vssh/libssh.c \ + vssh/libssh2.c \ + vssh/wolfssh.c + +LIB_VSSH_HFILES = \ + vssh/ssh.h + +LIB_CFILES = \ + altsvc.c \ + amigaos.c \ + asyn-ares.c \ + asyn-thread.c \ + base64.c \ + bufq.c \ + bufref.c \ + c-hyper.c \ + cf-h1-proxy.c \ + cf-h2-proxy.c \ + cf-haproxy.c \ + cf-https-connect.c \ + cf-socket.c \ + cfilters.c \ + conncache.c \ + connect.c \ + content_encoding.c \ + cookie.c \ + curl_addrinfo.c \ + curl_des.c \ + curl_endian.c \ + curl_fnmatch.c \ + curl_get_line.c \ + curl_gethostname.c \ + curl_gssapi.c \ + curl_memrchr.c \ + curl_multibyte.c \ + curl_ntlm_core.c \ + curl_path.c \ + curl_range.c \ + curl_rtmp.c \ + curl_sasl.c \ + curl_sha512_256.c \ + curl_sspi.c \ + curl_threads.c \ + curl_trc.c \ + cw-out.c \ + dict.c \ + dllmain.c \ + doh.c \ + dynbuf.c \ + dynhds.c \ + easy.c \ + easygetopt.c \ + easyoptions.c \ + escape.c \ + file.c \ + fileinfo.c \ + fopen.c \ + formdata.c \ + ftp.c \ + ftplistparser.c \ + getenv.c \ + getinfo.c \ + gopher.c \ + hash.c \ + headers.c \ + hmac.c \ + hostasyn.c \ + hostip.c \ + hostip4.c \ + hostip6.c \ + hostsyn.c \ + hsts.c \ + http.c \ + http1.c \ + http2.c \ + http_aws_sigv4.c \ + http_chunks.c \ + http_digest.c \ + http_negotiate.c \ + http_ntlm.c \ + http_proxy.c \ + idn.c \ + if2ip.c \ + imap.c \ + inet_ntop.c \ + inet_pton.c \ + krb5.c \ + ldap.c \ + llist.c \ + macos.c \ + md4.c \ + md5.c \ + memdebug.c \ + mime.c \ + mprintf.c \ + mqtt.c \ + multi.c \ + netrc.c \ + nonblock.c \ + noproxy.c \ + openldap.c \ + parsedate.c \ + pingpong.c \ + pop3.c \ + progress.c \ + psl.c \ + rand.c \ + rename.c \ + request.c \ + rtsp.c \ + select.c \ + sendf.c \ + setopt.c \ + sha256.c \ + share.c \ + slist.c \ + smb.c \ + smtp.c \ + socketpair.c \ + socks.c \ + socks_gssapi.c \ + socks_sspi.c \ + speedcheck.c \ + splay.c \ + strcase.c \ + strdup.c \ + strerror.c \ + strtok.c \ + strtoofft.c \ + system_win32.c \ + telnet.c \ + tftp.c \ + timediff.c \ + timeval.c \ + transfer.c \ + url.c \ + urlapi.c \ + version.c \ + version_win32.c \ + warnless.c \ + ws.c + +LIB_HFILES = \ + altsvc.h \ + amigaos.h \ + arpa_telnet.h \ + asyn.h \ + bufq.h \ + bufref.h \ + c-hyper.h \ + cf-h1-proxy.h \ + cf-h2-proxy.h \ + cf-haproxy.h \ + cf-https-connect.h \ + cf-socket.h \ + cfilters.h \ + conncache.h \ + connect.h \ + content_encoding.h \ + cookie.h \ + curl_addrinfo.h \ + curl_base64.h \ + curl_ctype.h \ + curl_des.h \ + curl_endian.h \ + curl_fnmatch.h \ + curl_get_line.h \ + curl_gethostname.h \ + curl_gssapi.h \ + curl_hmac.h \ + curl_krb5.h \ + curl_ldap.h \ + curl_md4.h \ + curl_md5.h \ + curl_memory.h \ + curl_memrchr.h \ + curl_multibyte.h \ + curl_ntlm_core.h \ + curl_path.h \ + curl_printf.h \ + curl_range.h \ + curl_rtmp.h \ + curl_sasl.h \ + curl_setup.h \ + curl_setup_once.h \ + curl_sha256.h \ + curl_sha512_256.h \ + curl_sspi.h \ + curl_threads.h \ + curl_trc.h \ + curlx.h \ + cw-out.h \ + dict.h \ + doh.h \ + dynbuf.h \ + dynhds.h \ + easy_lock.h \ + easyif.h \ + easyoptions.h \ + escape.h \ + file.h \ + fileinfo.h \ + fopen.h \ + formdata.h \ + ftp.h \ + ftplistparser.h \ + functypes.h \ + getinfo.h \ + gopher.h \ + hash.h \ + headers.h \ + hostip.h \ + hsts.h \ + http.h \ + http1.h \ + http2.h \ + http_aws_sigv4.h \ + http_chunks.h \ + http_digest.h \ + http_negotiate.h \ + http_ntlm.h \ + http_proxy.h \ + idn.h \ + if2ip.h \ + imap.h \ + inet_ntop.h \ + inet_pton.h \ + llist.h \ + macos.h \ + memdebug.h \ + mime.h \ + mqtt.h \ + multihandle.h \ + multiif.h \ + netrc.h \ + nonblock.h \ + noproxy.h \ + parsedate.h \ + pingpong.h \ + pop3.h \ + progress.h \ + psl.h \ + rand.h \ + rename.h \ + request.h \ + rtsp.h \ + select.h \ + sendf.h \ + setopt.h \ + setup-vms.h \ + share.h \ + sigpipe.h \ + slist.h \ + smb.h \ + smtp.h \ + sockaddr.h \ + socketpair.h \ + socks.h \ + speedcheck.h \ + splay.h \ + strcase.h \ + strdup.h \ + strerror.h \ + strtok.h \ + strtoofft.h \ + system_win32.h \ + telnet.h \ + tftp.h \ + timediff.h \ + timeval.h \ + transfer.h \ + url.h \ + urlapi-int.h \ + urldata.h \ + version_win32.h \ + warnless.h \ + ws.h + +LIB_RCFILES = libcurl.rc +CSOURCES = $(LIB_CFILES) $(LIB_VAUTH_CFILES) $(LIB_VTLS_CFILES) \ + $(LIB_VQUIC_CFILES) $(LIB_VSSH_CFILES) + +HHEADERS = $(LIB_HFILES) $(LIB_VAUTH_HFILES) $(LIB_VTLS_HFILES) \ + $(LIB_VQUIC_HFILES) $(LIB_VSSH_HFILES) + + +# Makefile.inc provides the CSOURCES and HHEADERS defines +libcurl_la_SOURCES = $(CSOURCES) $(HHEADERS) $(am__append_7) +libcurlu_la_SOURCES = $(CSOURCES) $(HHEADERS) +libcurl_la_CPPFLAGS_EXTRA = $(am__append_6) $(am__append_8) +libcurl_la_LDFLAGS_EXTRA = $(am__append_1) $(am__append_2) \ + $(am__append_3) $(am__append_4) $(am__append_5) +libcurl_la_CFLAGS_EXTRA = $(am__append_9) +libcurl_la_CPPFLAGS = $(AM_CPPFLAGS) $(libcurl_la_CPPFLAGS_EXTRA) +libcurl_la_LDFLAGS = $(AM_LDFLAGS) $(libcurl_la_LDFLAGS_EXTRA) $(CURL_LDFLAGS_LIB) $(LIBCURL_LIBS) +libcurl_la_CFLAGS = $(AM_CFLAGS) $(libcurl_la_CFLAGS_EXTRA) +libcurlu_la_CPPFLAGS = $(AM_CPPFLAGS) -DCURL_STATICLIB -DUNITTESTS +libcurlu_la_LDFLAGS = $(AM_LDFLAGS) -static $(LIBCURL_LIBS) +libcurlu_la_CFLAGS = $(AM_CFLAGS) +CHECKSRC = $(CS_$(V)) +CS_0 = @echo " RUN " $@; +CS_1 = +CS_ = $(CS_0) + +# disable the tests that are mostly causing false positives +TIDYFLAGS = -checks=-clang-analyzer-security.insecureAPI.strcpy,-clang-analyzer-optin.performance.Padding,-clang-analyzer-valist.Uninitialized,-clang-analyzer-core.NonNullParamChecker,-clang-analyzer-core.NullDereference -quiet +TIDY := clang-tidy +all: curl_config.h + $(MAKE) $(AM_MAKEFLAGS) all-am + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj .rc +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(srcdir)/Makefile.soname $(srcdir)/Makefile.inc $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign lib/Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ + esac; +$(srcdir)/Makefile.soname $(srcdir)/Makefile.inc $(am__empty): + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +curl_config.h: stamp-h1 + @test -f $@ || rm -f stamp-h1 + @test -f $@ || $(MAKE) $(AM_MAKEFLAGS) stamp-h1 + +stamp-h1: $(srcdir)/curl_config.h.in $(top_builddir)/config.status + @rm -f stamp-h1 + cd $(top_builddir) && $(SHELL) ./config.status lib/curl_config.h +$(srcdir)/curl_config.h.in: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + ($(am__cd) $(top_srcdir) && $(AUTOHEADER)) + rm -f stamp-h1 + touch $@ + +distclean-hdr: + -rm -f curl_config.h stamp-h1 +libcurl.vers: $(top_builddir)/config.status $(srcdir)/libcurl.vers.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ + +install-libLTLIBRARIES: $(lib_LTLIBRARIES) + @$(NORMAL_INSTALL) + @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ + list2=; for p in $$list; do \ + if test -f $$p; then \ + list2="$$list2 $$p"; \ + else :; fi; \ + done; \ + test -z "$$list2" || { \ + echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ + } + +uninstall-libLTLIBRARIES: + @$(NORMAL_UNINSTALL) + @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ + for p in $$list; do \ + $(am__strip_dir) \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ + done + +clean-libLTLIBRARIES: + -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) + @list='$(lib_LTLIBRARIES)'; \ + locs=`for p in $$list; do echo $$p; done | \ + sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ + sort -u`; \ + test -z "$$locs" || { \ + echo rm -f $${locs}; \ + rm -f $${locs}; \ + } + +clean-noinstLTLIBRARIES: + -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) + @list='$(noinst_LTLIBRARIES)'; \ + locs=`for p in $$list; do echo $$p; done | \ + sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ + sort -u`; \ + test -z "$$locs" || { \ + echo rm -f $${locs}; \ + rm -f $${locs}; \ + } +vauth/$(am__dirstamp): + @$(MKDIR_P) vauth + @: > vauth/$(am__dirstamp) +vauth/$(DEPDIR)/$(am__dirstamp): + @$(MKDIR_P) vauth/$(DEPDIR) + @: > vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurl_la-cleartext.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurl_la-cram.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurl_la-digest.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurl_la-digest_sspi.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurl_la-gsasl.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurl_la-krb5_gssapi.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurl_la-krb5_sspi.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurl_la-ntlm.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurl_la-ntlm_sspi.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurl_la-oauth2.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurl_la-spnego_gssapi.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurl_la-spnego_sspi.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurl_la-vauth.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vtls/$(am__dirstamp): + @$(MKDIR_P) vtls + @: > vtls/$(am__dirstamp) +vtls/$(DEPDIR)/$(am__dirstamp): + @$(MKDIR_P) vtls/$(DEPDIR) + @: > vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurl_la-bearssl.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurl_la-cipher_suite.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurl_la-gtls.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurl_la-hostcheck.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurl_la-keylog.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurl_la-mbedtls.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurl_la-mbedtls_threadlock.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurl_la-openssl.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurl_la-rustls.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurl_la-schannel.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurl_la-schannel_verify.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurl_la-sectransp.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurl_la-vtls.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurl_la-wolfssl.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurl_la-x509asn1.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vquic/$(am__dirstamp): + @$(MKDIR_P) vquic + @: > vquic/$(am__dirstamp) +vquic/$(DEPDIR)/$(am__dirstamp): + @$(MKDIR_P) vquic/$(DEPDIR) + @: > vquic/$(DEPDIR)/$(am__dirstamp) +vquic/libcurl_la-curl_msh3.lo: vquic/$(am__dirstamp) \ + vquic/$(DEPDIR)/$(am__dirstamp) +vquic/libcurl_la-curl_ngtcp2.lo: vquic/$(am__dirstamp) \ + vquic/$(DEPDIR)/$(am__dirstamp) +vquic/libcurl_la-curl_osslq.lo: vquic/$(am__dirstamp) \ + vquic/$(DEPDIR)/$(am__dirstamp) +vquic/libcurl_la-curl_quiche.lo: vquic/$(am__dirstamp) \ + vquic/$(DEPDIR)/$(am__dirstamp) +vquic/libcurl_la-vquic.lo: vquic/$(am__dirstamp) \ + vquic/$(DEPDIR)/$(am__dirstamp) +vquic/libcurl_la-vquic-tls.lo: vquic/$(am__dirstamp) \ + vquic/$(DEPDIR)/$(am__dirstamp) +vssh/$(am__dirstamp): + @$(MKDIR_P) vssh + @: > vssh/$(am__dirstamp) +vssh/$(DEPDIR)/$(am__dirstamp): + @$(MKDIR_P) vssh/$(DEPDIR) + @: > vssh/$(DEPDIR)/$(am__dirstamp) +vssh/libcurl_la-libssh.lo: vssh/$(am__dirstamp) \ + vssh/$(DEPDIR)/$(am__dirstamp) +vssh/libcurl_la-libssh2.lo: vssh/$(am__dirstamp) \ + vssh/$(DEPDIR)/$(am__dirstamp) +vssh/libcurl_la-wolfssh.lo: vssh/$(am__dirstamp) \ + vssh/$(DEPDIR)/$(am__dirstamp) + +libcurl.la: $(libcurl_la_OBJECTS) $(libcurl_la_DEPENDENCIES) $(EXTRA_libcurl_la_DEPENDENCIES) + $(AM_V_CCLD)$(libcurl_la_LINK) -rpath $(libdir) $(libcurl_la_OBJECTS) $(libcurl_la_LIBADD) $(LIBS) +vauth/libcurlu_la-cleartext.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurlu_la-cram.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurlu_la-digest.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurlu_la-digest_sspi.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurlu_la-gsasl.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurlu_la-krb5_gssapi.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurlu_la-krb5_sspi.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurlu_la-ntlm.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurlu_la-ntlm_sspi.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurlu_la-oauth2.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurlu_la-spnego_gssapi.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurlu_la-spnego_sspi.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vauth/libcurlu_la-vauth.lo: vauth/$(am__dirstamp) \ + vauth/$(DEPDIR)/$(am__dirstamp) +vtls/libcurlu_la-bearssl.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurlu_la-cipher_suite.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurlu_la-gtls.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurlu_la-hostcheck.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurlu_la-keylog.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurlu_la-mbedtls.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurlu_la-mbedtls_threadlock.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurlu_la-openssl.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurlu_la-rustls.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurlu_la-schannel.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurlu_la-schannel_verify.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurlu_la-sectransp.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurlu_la-vtls.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurlu_la-wolfssl.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vtls/libcurlu_la-x509asn1.lo: vtls/$(am__dirstamp) \ + vtls/$(DEPDIR)/$(am__dirstamp) +vquic/libcurlu_la-curl_msh3.lo: vquic/$(am__dirstamp) \ + vquic/$(DEPDIR)/$(am__dirstamp) +vquic/libcurlu_la-curl_ngtcp2.lo: vquic/$(am__dirstamp) \ + vquic/$(DEPDIR)/$(am__dirstamp) +vquic/libcurlu_la-curl_osslq.lo: vquic/$(am__dirstamp) \ + vquic/$(DEPDIR)/$(am__dirstamp) +vquic/libcurlu_la-curl_quiche.lo: vquic/$(am__dirstamp) \ + vquic/$(DEPDIR)/$(am__dirstamp) +vquic/libcurlu_la-vquic.lo: vquic/$(am__dirstamp) \ + vquic/$(DEPDIR)/$(am__dirstamp) +vquic/libcurlu_la-vquic-tls.lo: vquic/$(am__dirstamp) \ + vquic/$(DEPDIR)/$(am__dirstamp) +vssh/libcurlu_la-libssh.lo: vssh/$(am__dirstamp) \ + vssh/$(DEPDIR)/$(am__dirstamp) +vssh/libcurlu_la-libssh2.lo: vssh/$(am__dirstamp) \ + vssh/$(DEPDIR)/$(am__dirstamp) +vssh/libcurlu_la-wolfssh.lo: vssh/$(am__dirstamp) \ + vssh/$(DEPDIR)/$(am__dirstamp) + +libcurlu.la: $(libcurlu_la_OBJECTS) $(libcurlu_la_DEPENDENCIES) $(EXTRA_libcurlu_la_DEPENDENCIES) + $(AM_V_CCLD)$(libcurlu_la_LINK) $(am_libcurlu_la_rpath) $(libcurlu_la_OBJECTS) $(libcurlu_la_LIBADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + -rm -f vauth/*.$(OBJEXT) + -rm -f vauth/*.lo + -rm -f vquic/*.$(OBJEXT) + -rm -f vquic/*.lo + -rm -f vssh/*.$(OBJEXT) + -rm -f vssh/*.lo + -rm -f vtls/*.$(OBJEXT) + -rm -f vtls/*.lo + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-altsvc.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-amigaos.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-asyn-ares.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-asyn-thread.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-base64.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-bufq.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-bufref.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-c-hyper.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-cf-h1-proxy.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-cf-h2-proxy.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-cf-haproxy.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-cf-https-connect.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-cf-socket.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-cfilters.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-conncache.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-connect.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-content_encoding.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-cookie.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_addrinfo.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_des.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_endian.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_fnmatch.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_get_line.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_gethostname.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_gssapi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_memrchr.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_multibyte.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_ntlm_core.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_path.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_range.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_rtmp.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_sasl.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_sha512_256.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_sspi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_threads.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-curl_trc.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-cw-out.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-dict.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-dllmain.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-doh.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-dynbuf.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-dynhds.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-easy.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-easygetopt.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-easyoptions.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-escape.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-file.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-fileinfo.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-fopen.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-formdata.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-ftp.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-ftplistparser.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-getenv.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-getinfo.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-gopher.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-hash.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-headers.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-hmac.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-hostasyn.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-hostip.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-hostip4.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-hostip6.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-hostsyn.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-hsts.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-http.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-http1.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-http2.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-http_aws_sigv4.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-http_chunks.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-http_digest.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-http_negotiate.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-http_ntlm.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-http_proxy.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-idn.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-if2ip.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-imap.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-inet_ntop.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-inet_pton.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-krb5.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-ldap.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-llist.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-macos.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-md4.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-md5.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-memdebug.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-mime.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-mprintf.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-mqtt.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-multi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-netrc.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-nonblock.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-noproxy.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-openldap.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-parsedate.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-pingpong.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-pop3.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-progress.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-psl.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-rand.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-rename.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-request.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-rtsp.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-select.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-sendf.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-setopt.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-sha256.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-share.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-slist.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-smb.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-smtp.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-socketpair.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-socks.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-socks_gssapi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-socks_sspi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-speedcheck.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-splay.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-strcase.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-strdup.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-strerror.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-strtok.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-strtoofft.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-system_win32.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-telnet.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-tftp.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-timediff.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-timeval.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-transfer.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-url.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-urlapi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-version.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-version_win32.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-warnless.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurl_la-ws.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-altsvc.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-amigaos.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-asyn-ares.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-asyn-thread.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-base64.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-bufq.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-bufref.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-c-hyper.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-cf-h1-proxy.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-cf-h2-proxy.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-cf-haproxy.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-cf-https-connect.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-cf-socket.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-cfilters.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-conncache.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-connect.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-content_encoding.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-cookie.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_addrinfo.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_des.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_endian.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_fnmatch.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_get_line.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_gethostname.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_gssapi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_memrchr.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_multibyte.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_ntlm_core.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_path.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_range.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_rtmp.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_sasl.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_sha512_256.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_sspi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_threads.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-curl_trc.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-cw-out.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-dict.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-dllmain.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-doh.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-dynbuf.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-dynhds.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-easy.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-easygetopt.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-easyoptions.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-escape.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-file.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-fileinfo.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-fopen.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-formdata.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-ftp.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-ftplistparser.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-getenv.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-getinfo.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-gopher.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-hash.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-headers.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-hmac.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-hostasyn.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-hostip.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-hostip4.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-hostip6.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-hostsyn.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-hsts.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-http.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-http1.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-http2.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-http_aws_sigv4.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-http_chunks.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-http_digest.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-http_negotiate.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-http_ntlm.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-http_proxy.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-idn.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-if2ip.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-imap.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-inet_ntop.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-inet_pton.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-krb5.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-ldap.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-llist.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-macos.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-md4.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-md5.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-memdebug.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-mime.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-mprintf.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-mqtt.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-multi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-netrc.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-nonblock.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-noproxy.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-openldap.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-parsedate.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-pingpong.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-pop3.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-progress.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-psl.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-rand.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-rename.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-request.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-rtsp.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-select.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-sendf.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-setopt.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-sha256.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-share.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-slist.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-smb.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-smtp.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-socketpair.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-socks.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-socks_gssapi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-socks_sspi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-speedcheck.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-splay.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-strcase.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-strdup.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-strerror.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-strtok.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-strtoofft.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-system_win32.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-telnet.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-tftp.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-timediff.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-timeval.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-transfer.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-url.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-urlapi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-version.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-version_win32.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-warnless.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcurlu_la-ws.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurl_la-cleartext.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurl_la-cram.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurl_la-digest.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurl_la-digest_sspi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurl_la-gsasl.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurl_la-krb5_gssapi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurl_la-krb5_sspi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurl_la-ntlm.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurl_la-ntlm_sspi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurl_la-oauth2.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurl_la-spnego_gssapi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurl_la-spnego_sspi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurl_la-vauth.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurlu_la-cleartext.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurlu_la-cram.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurlu_la-digest.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurlu_la-digest_sspi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurlu_la-gsasl.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurlu_la-krb5_gssapi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurlu_la-krb5_sspi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurlu_la-ntlm.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurlu_la-ntlm_sspi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurlu_la-oauth2.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurlu_la-spnego_gssapi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurlu_la-spnego_sspi.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vauth/$(DEPDIR)/libcurlu_la-vauth.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vquic/$(DEPDIR)/libcurl_la-curl_msh3.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vquic/$(DEPDIR)/libcurl_la-curl_ngtcp2.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vquic/$(DEPDIR)/libcurl_la-curl_osslq.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vquic/$(DEPDIR)/libcurl_la-curl_quiche.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vquic/$(DEPDIR)/libcurl_la-vquic-tls.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vquic/$(DEPDIR)/libcurl_la-vquic.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vquic/$(DEPDIR)/libcurlu_la-curl_msh3.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vquic/$(DEPDIR)/libcurlu_la-curl_ngtcp2.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vquic/$(DEPDIR)/libcurlu_la-curl_osslq.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vquic/$(DEPDIR)/libcurlu_la-curl_quiche.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vquic/$(DEPDIR)/libcurlu_la-vquic-tls.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vquic/$(DEPDIR)/libcurlu_la-vquic.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vssh/$(DEPDIR)/libcurl_la-libssh.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vssh/$(DEPDIR)/libcurl_la-libssh2.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vssh/$(DEPDIR)/libcurl_la-wolfssh.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vssh/$(DEPDIR)/libcurlu_la-libssh.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vssh/$(DEPDIR)/libcurlu_la-libssh2.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vssh/$(DEPDIR)/libcurlu_la-wolfssh.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurl_la-bearssl.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurl_la-cipher_suite.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurl_la-gtls.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurl_la-hostcheck.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurl_la-keylog.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurl_la-mbedtls.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurl_la-mbedtls_threadlock.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurl_la-openssl.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurl_la-rustls.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurl_la-schannel.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurl_la-schannel_verify.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurl_la-sectransp.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurl_la-vtls.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurl_la-wolfssl.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurl_la-x509asn1.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurlu_la-bearssl.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurlu_la-cipher_suite.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurlu_la-gtls.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurlu_la-hostcheck.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurlu_la-keylog.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurlu_la-mbedtls.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurlu_la-mbedtls_threadlock.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurlu_la-openssl.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurlu_la-rustls.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurlu_la-schannel.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurlu_la-schannel_verify.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurlu_la-sectransp.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurlu_la-vtls.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurlu_la-wolfssl.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@vtls/$(DEPDIR)/libcurlu_la-x509asn1.Plo@am__quote@ # am--include-marker + +$(am__depfiles_remade): + @$(MKDIR_P) $(@D) + @echo '# dummy' >$@-t && $(am__mv) $@-t $@ + +am--depfiles: $(am__depfiles_remade) + +.c.o: +@am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ +@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ +@am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< + +.c.obj: +@am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ +@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ +@am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` + +.c.lo: +@am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ +@am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ +@am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< + +libcurl_la-altsvc.lo: altsvc.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-altsvc.lo -MD -MP -MF $(DEPDIR)/libcurl_la-altsvc.Tpo -c -o libcurl_la-altsvc.lo `test -f 'altsvc.c' || echo '$(srcdir)/'`altsvc.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-altsvc.Tpo $(DEPDIR)/libcurl_la-altsvc.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='altsvc.c' object='libcurl_la-altsvc.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-altsvc.lo `test -f 'altsvc.c' || echo '$(srcdir)/'`altsvc.c + +libcurl_la-amigaos.lo: amigaos.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-amigaos.lo -MD -MP -MF $(DEPDIR)/libcurl_la-amigaos.Tpo -c -o libcurl_la-amigaos.lo `test -f 'amigaos.c' || echo '$(srcdir)/'`amigaos.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-amigaos.Tpo $(DEPDIR)/libcurl_la-amigaos.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='amigaos.c' object='libcurl_la-amigaos.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-amigaos.lo `test -f 'amigaos.c' || echo '$(srcdir)/'`amigaos.c + +libcurl_la-asyn-ares.lo: asyn-ares.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-asyn-ares.lo -MD -MP -MF $(DEPDIR)/libcurl_la-asyn-ares.Tpo -c -o libcurl_la-asyn-ares.lo `test -f 'asyn-ares.c' || echo '$(srcdir)/'`asyn-ares.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-asyn-ares.Tpo $(DEPDIR)/libcurl_la-asyn-ares.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='asyn-ares.c' object='libcurl_la-asyn-ares.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-asyn-ares.lo `test -f 'asyn-ares.c' || echo '$(srcdir)/'`asyn-ares.c + +libcurl_la-asyn-thread.lo: asyn-thread.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-asyn-thread.lo -MD -MP -MF $(DEPDIR)/libcurl_la-asyn-thread.Tpo -c -o libcurl_la-asyn-thread.lo `test -f 'asyn-thread.c' || echo '$(srcdir)/'`asyn-thread.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-asyn-thread.Tpo $(DEPDIR)/libcurl_la-asyn-thread.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='asyn-thread.c' object='libcurl_la-asyn-thread.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-asyn-thread.lo `test -f 'asyn-thread.c' || echo '$(srcdir)/'`asyn-thread.c + +libcurl_la-base64.lo: base64.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-base64.lo -MD -MP -MF $(DEPDIR)/libcurl_la-base64.Tpo -c -o libcurl_la-base64.lo `test -f 'base64.c' || echo '$(srcdir)/'`base64.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-base64.Tpo $(DEPDIR)/libcurl_la-base64.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='base64.c' object='libcurl_la-base64.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-base64.lo `test -f 'base64.c' || echo '$(srcdir)/'`base64.c + +libcurl_la-bufq.lo: bufq.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-bufq.lo -MD -MP -MF $(DEPDIR)/libcurl_la-bufq.Tpo -c -o libcurl_la-bufq.lo `test -f 'bufq.c' || echo '$(srcdir)/'`bufq.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-bufq.Tpo $(DEPDIR)/libcurl_la-bufq.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='bufq.c' object='libcurl_la-bufq.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-bufq.lo `test -f 'bufq.c' || echo '$(srcdir)/'`bufq.c + +libcurl_la-bufref.lo: bufref.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-bufref.lo -MD -MP -MF $(DEPDIR)/libcurl_la-bufref.Tpo -c -o libcurl_la-bufref.lo `test -f 'bufref.c' || echo '$(srcdir)/'`bufref.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-bufref.Tpo $(DEPDIR)/libcurl_la-bufref.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='bufref.c' object='libcurl_la-bufref.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-bufref.lo `test -f 'bufref.c' || echo '$(srcdir)/'`bufref.c + +libcurl_la-c-hyper.lo: c-hyper.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-c-hyper.lo -MD -MP -MF $(DEPDIR)/libcurl_la-c-hyper.Tpo -c -o libcurl_la-c-hyper.lo `test -f 'c-hyper.c' || echo '$(srcdir)/'`c-hyper.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-c-hyper.Tpo $(DEPDIR)/libcurl_la-c-hyper.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='c-hyper.c' object='libcurl_la-c-hyper.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-c-hyper.lo `test -f 'c-hyper.c' || echo '$(srcdir)/'`c-hyper.c + +libcurl_la-cf-h1-proxy.lo: cf-h1-proxy.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-cf-h1-proxy.lo -MD -MP -MF $(DEPDIR)/libcurl_la-cf-h1-proxy.Tpo -c -o libcurl_la-cf-h1-proxy.lo `test -f 'cf-h1-proxy.c' || echo '$(srcdir)/'`cf-h1-proxy.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-cf-h1-proxy.Tpo $(DEPDIR)/libcurl_la-cf-h1-proxy.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cf-h1-proxy.c' object='libcurl_la-cf-h1-proxy.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-cf-h1-proxy.lo `test -f 'cf-h1-proxy.c' || echo '$(srcdir)/'`cf-h1-proxy.c + +libcurl_la-cf-h2-proxy.lo: cf-h2-proxy.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-cf-h2-proxy.lo -MD -MP -MF $(DEPDIR)/libcurl_la-cf-h2-proxy.Tpo -c -o libcurl_la-cf-h2-proxy.lo `test -f 'cf-h2-proxy.c' || echo '$(srcdir)/'`cf-h2-proxy.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-cf-h2-proxy.Tpo $(DEPDIR)/libcurl_la-cf-h2-proxy.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cf-h2-proxy.c' object='libcurl_la-cf-h2-proxy.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-cf-h2-proxy.lo `test -f 'cf-h2-proxy.c' || echo '$(srcdir)/'`cf-h2-proxy.c + +libcurl_la-cf-haproxy.lo: cf-haproxy.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-cf-haproxy.lo -MD -MP -MF $(DEPDIR)/libcurl_la-cf-haproxy.Tpo -c -o libcurl_la-cf-haproxy.lo `test -f 'cf-haproxy.c' || echo '$(srcdir)/'`cf-haproxy.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-cf-haproxy.Tpo $(DEPDIR)/libcurl_la-cf-haproxy.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cf-haproxy.c' object='libcurl_la-cf-haproxy.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-cf-haproxy.lo `test -f 'cf-haproxy.c' || echo '$(srcdir)/'`cf-haproxy.c + +libcurl_la-cf-https-connect.lo: cf-https-connect.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-cf-https-connect.lo -MD -MP -MF $(DEPDIR)/libcurl_la-cf-https-connect.Tpo -c -o libcurl_la-cf-https-connect.lo `test -f 'cf-https-connect.c' || echo '$(srcdir)/'`cf-https-connect.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-cf-https-connect.Tpo $(DEPDIR)/libcurl_la-cf-https-connect.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cf-https-connect.c' object='libcurl_la-cf-https-connect.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-cf-https-connect.lo `test -f 'cf-https-connect.c' || echo '$(srcdir)/'`cf-https-connect.c + +libcurl_la-cf-socket.lo: cf-socket.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-cf-socket.lo -MD -MP -MF $(DEPDIR)/libcurl_la-cf-socket.Tpo -c -o libcurl_la-cf-socket.lo `test -f 'cf-socket.c' || echo '$(srcdir)/'`cf-socket.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-cf-socket.Tpo $(DEPDIR)/libcurl_la-cf-socket.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cf-socket.c' object='libcurl_la-cf-socket.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-cf-socket.lo `test -f 'cf-socket.c' || echo '$(srcdir)/'`cf-socket.c + +libcurl_la-cfilters.lo: cfilters.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-cfilters.lo -MD -MP -MF $(DEPDIR)/libcurl_la-cfilters.Tpo -c -o libcurl_la-cfilters.lo `test -f 'cfilters.c' || echo '$(srcdir)/'`cfilters.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-cfilters.Tpo $(DEPDIR)/libcurl_la-cfilters.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cfilters.c' object='libcurl_la-cfilters.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-cfilters.lo `test -f 'cfilters.c' || echo '$(srcdir)/'`cfilters.c + +libcurl_la-conncache.lo: conncache.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-conncache.lo -MD -MP -MF $(DEPDIR)/libcurl_la-conncache.Tpo -c -o libcurl_la-conncache.lo `test -f 'conncache.c' || echo '$(srcdir)/'`conncache.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-conncache.Tpo $(DEPDIR)/libcurl_la-conncache.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='conncache.c' object='libcurl_la-conncache.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-conncache.lo `test -f 'conncache.c' || echo '$(srcdir)/'`conncache.c + +libcurl_la-connect.lo: connect.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-connect.lo -MD -MP -MF $(DEPDIR)/libcurl_la-connect.Tpo -c -o libcurl_la-connect.lo `test -f 'connect.c' || echo '$(srcdir)/'`connect.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-connect.Tpo $(DEPDIR)/libcurl_la-connect.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='connect.c' object='libcurl_la-connect.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-connect.lo `test -f 'connect.c' || echo '$(srcdir)/'`connect.c + +libcurl_la-content_encoding.lo: content_encoding.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-content_encoding.lo -MD -MP -MF $(DEPDIR)/libcurl_la-content_encoding.Tpo -c -o libcurl_la-content_encoding.lo `test -f 'content_encoding.c' || echo '$(srcdir)/'`content_encoding.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-content_encoding.Tpo $(DEPDIR)/libcurl_la-content_encoding.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='content_encoding.c' object='libcurl_la-content_encoding.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-content_encoding.lo `test -f 'content_encoding.c' || echo '$(srcdir)/'`content_encoding.c + +libcurl_la-cookie.lo: cookie.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-cookie.lo -MD -MP -MF $(DEPDIR)/libcurl_la-cookie.Tpo -c -o libcurl_la-cookie.lo `test -f 'cookie.c' || echo '$(srcdir)/'`cookie.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-cookie.Tpo $(DEPDIR)/libcurl_la-cookie.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cookie.c' object='libcurl_la-cookie.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-cookie.lo `test -f 'cookie.c' || echo '$(srcdir)/'`cookie.c + +libcurl_la-curl_addrinfo.lo: curl_addrinfo.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_addrinfo.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_addrinfo.Tpo -c -o libcurl_la-curl_addrinfo.lo `test -f 'curl_addrinfo.c' || echo '$(srcdir)/'`curl_addrinfo.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_addrinfo.Tpo $(DEPDIR)/libcurl_la-curl_addrinfo.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_addrinfo.c' object='libcurl_la-curl_addrinfo.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_addrinfo.lo `test -f 'curl_addrinfo.c' || echo '$(srcdir)/'`curl_addrinfo.c + +libcurl_la-curl_des.lo: curl_des.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_des.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_des.Tpo -c -o libcurl_la-curl_des.lo `test -f 'curl_des.c' || echo '$(srcdir)/'`curl_des.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_des.Tpo $(DEPDIR)/libcurl_la-curl_des.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_des.c' object='libcurl_la-curl_des.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_des.lo `test -f 'curl_des.c' || echo '$(srcdir)/'`curl_des.c + +libcurl_la-curl_endian.lo: curl_endian.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_endian.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_endian.Tpo -c -o libcurl_la-curl_endian.lo `test -f 'curl_endian.c' || echo '$(srcdir)/'`curl_endian.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_endian.Tpo $(DEPDIR)/libcurl_la-curl_endian.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_endian.c' object='libcurl_la-curl_endian.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_endian.lo `test -f 'curl_endian.c' || echo '$(srcdir)/'`curl_endian.c + +libcurl_la-curl_fnmatch.lo: curl_fnmatch.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_fnmatch.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_fnmatch.Tpo -c -o libcurl_la-curl_fnmatch.lo `test -f 'curl_fnmatch.c' || echo '$(srcdir)/'`curl_fnmatch.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_fnmatch.Tpo $(DEPDIR)/libcurl_la-curl_fnmatch.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_fnmatch.c' object='libcurl_la-curl_fnmatch.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_fnmatch.lo `test -f 'curl_fnmatch.c' || echo '$(srcdir)/'`curl_fnmatch.c + +libcurl_la-curl_get_line.lo: curl_get_line.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_get_line.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_get_line.Tpo -c -o libcurl_la-curl_get_line.lo `test -f 'curl_get_line.c' || echo '$(srcdir)/'`curl_get_line.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_get_line.Tpo $(DEPDIR)/libcurl_la-curl_get_line.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_get_line.c' object='libcurl_la-curl_get_line.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_get_line.lo `test -f 'curl_get_line.c' || echo '$(srcdir)/'`curl_get_line.c + +libcurl_la-curl_gethostname.lo: curl_gethostname.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_gethostname.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_gethostname.Tpo -c -o libcurl_la-curl_gethostname.lo `test -f 'curl_gethostname.c' || echo '$(srcdir)/'`curl_gethostname.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_gethostname.Tpo $(DEPDIR)/libcurl_la-curl_gethostname.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_gethostname.c' object='libcurl_la-curl_gethostname.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_gethostname.lo `test -f 'curl_gethostname.c' || echo '$(srcdir)/'`curl_gethostname.c + +libcurl_la-curl_gssapi.lo: curl_gssapi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_gssapi.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_gssapi.Tpo -c -o libcurl_la-curl_gssapi.lo `test -f 'curl_gssapi.c' || echo '$(srcdir)/'`curl_gssapi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_gssapi.Tpo $(DEPDIR)/libcurl_la-curl_gssapi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_gssapi.c' object='libcurl_la-curl_gssapi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_gssapi.lo `test -f 'curl_gssapi.c' || echo '$(srcdir)/'`curl_gssapi.c + +libcurl_la-curl_memrchr.lo: curl_memrchr.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_memrchr.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_memrchr.Tpo -c -o libcurl_la-curl_memrchr.lo `test -f 'curl_memrchr.c' || echo '$(srcdir)/'`curl_memrchr.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_memrchr.Tpo $(DEPDIR)/libcurl_la-curl_memrchr.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_memrchr.c' object='libcurl_la-curl_memrchr.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_memrchr.lo `test -f 'curl_memrchr.c' || echo '$(srcdir)/'`curl_memrchr.c + +libcurl_la-curl_multibyte.lo: curl_multibyte.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_multibyte.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_multibyte.Tpo -c -o libcurl_la-curl_multibyte.lo `test -f 'curl_multibyte.c' || echo '$(srcdir)/'`curl_multibyte.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_multibyte.Tpo $(DEPDIR)/libcurl_la-curl_multibyte.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_multibyte.c' object='libcurl_la-curl_multibyte.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_multibyte.lo `test -f 'curl_multibyte.c' || echo '$(srcdir)/'`curl_multibyte.c + +libcurl_la-curl_ntlm_core.lo: curl_ntlm_core.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_ntlm_core.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_ntlm_core.Tpo -c -o libcurl_la-curl_ntlm_core.lo `test -f 'curl_ntlm_core.c' || echo '$(srcdir)/'`curl_ntlm_core.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_ntlm_core.Tpo $(DEPDIR)/libcurl_la-curl_ntlm_core.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_ntlm_core.c' object='libcurl_la-curl_ntlm_core.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_ntlm_core.lo `test -f 'curl_ntlm_core.c' || echo '$(srcdir)/'`curl_ntlm_core.c + +libcurl_la-curl_path.lo: curl_path.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_path.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_path.Tpo -c -o libcurl_la-curl_path.lo `test -f 'curl_path.c' || echo '$(srcdir)/'`curl_path.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_path.Tpo $(DEPDIR)/libcurl_la-curl_path.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_path.c' object='libcurl_la-curl_path.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_path.lo `test -f 'curl_path.c' || echo '$(srcdir)/'`curl_path.c + +libcurl_la-curl_range.lo: curl_range.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_range.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_range.Tpo -c -o libcurl_la-curl_range.lo `test -f 'curl_range.c' || echo '$(srcdir)/'`curl_range.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_range.Tpo $(DEPDIR)/libcurl_la-curl_range.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_range.c' object='libcurl_la-curl_range.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_range.lo `test -f 'curl_range.c' || echo '$(srcdir)/'`curl_range.c + +libcurl_la-curl_rtmp.lo: curl_rtmp.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_rtmp.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_rtmp.Tpo -c -o libcurl_la-curl_rtmp.lo `test -f 'curl_rtmp.c' || echo '$(srcdir)/'`curl_rtmp.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_rtmp.Tpo $(DEPDIR)/libcurl_la-curl_rtmp.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_rtmp.c' object='libcurl_la-curl_rtmp.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_rtmp.lo `test -f 'curl_rtmp.c' || echo '$(srcdir)/'`curl_rtmp.c + +libcurl_la-curl_sasl.lo: curl_sasl.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_sasl.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_sasl.Tpo -c -o libcurl_la-curl_sasl.lo `test -f 'curl_sasl.c' || echo '$(srcdir)/'`curl_sasl.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_sasl.Tpo $(DEPDIR)/libcurl_la-curl_sasl.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_sasl.c' object='libcurl_la-curl_sasl.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_sasl.lo `test -f 'curl_sasl.c' || echo '$(srcdir)/'`curl_sasl.c + +libcurl_la-curl_sha512_256.lo: curl_sha512_256.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_sha512_256.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_sha512_256.Tpo -c -o libcurl_la-curl_sha512_256.lo `test -f 'curl_sha512_256.c' || echo '$(srcdir)/'`curl_sha512_256.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_sha512_256.Tpo $(DEPDIR)/libcurl_la-curl_sha512_256.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_sha512_256.c' object='libcurl_la-curl_sha512_256.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_sha512_256.lo `test -f 'curl_sha512_256.c' || echo '$(srcdir)/'`curl_sha512_256.c + +libcurl_la-curl_sspi.lo: curl_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_sspi.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_sspi.Tpo -c -o libcurl_la-curl_sspi.lo `test -f 'curl_sspi.c' || echo '$(srcdir)/'`curl_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_sspi.Tpo $(DEPDIR)/libcurl_la-curl_sspi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_sspi.c' object='libcurl_la-curl_sspi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_sspi.lo `test -f 'curl_sspi.c' || echo '$(srcdir)/'`curl_sspi.c + +libcurl_la-curl_threads.lo: curl_threads.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_threads.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_threads.Tpo -c -o libcurl_la-curl_threads.lo `test -f 'curl_threads.c' || echo '$(srcdir)/'`curl_threads.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_threads.Tpo $(DEPDIR)/libcurl_la-curl_threads.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_threads.c' object='libcurl_la-curl_threads.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_threads.lo `test -f 'curl_threads.c' || echo '$(srcdir)/'`curl_threads.c + +libcurl_la-curl_trc.lo: curl_trc.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-curl_trc.lo -MD -MP -MF $(DEPDIR)/libcurl_la-curl_trc.Tpo -c -o libcurl_la-curl_trc.lo `test -f 'curl_trc.c' || echo '$(srcdir)/'`curl_trc.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-curl_trc.Tpo $(DEPDIR)/libcurl_la-curl_trc.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_trc.c' object='libcurl_la-curl_trc.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-curl_trc.lo `test -f 'curl_trc.c' || echo '$(srcdir)/'`curl_trc.c + +libcurl_la-cw-out.lo: cw-out.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-cw-out.lo -MD -MP -MF $(DEPDIR)/libcurl_la-cw-out.Tpo -c -o libcurl_la-cw-out.lo `test -f 'cw-out.c' || echo '$(srcdir)/'`cw-out.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-cw-out.Tpo $(DEPDIR)/libcurl_la-cw-out.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cw-out.c' object='libcurl_la-cw-out.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-cw-out.lo `test -f 'cw-out.c' || echo '$(srcdir)/'`cw-out.c + +libcurl_la-dict.lo: dict.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-dict.lo -MD -MP -MF $(DEPDIR)/libcurl_la-dict.Tpo -c -o libcurl_la-dict.lo `test -f 'dict.c' || echo '$(srcdir)/'`dict.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-dict.Tpo $(DEPDIR)/libcurl_la-dict.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='dict.c' object='libcurl_la-dict.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-dict.lo `test -f 'dict.c' || echo '$(srcdir)/'`dict.c + +libcurl_la-dllmain.lo: dllmain.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-dllmain.lo -MD -MP -MF $(DEPDIR)/libcurl_la-dllmain.Tpo -c -o libcurl_la-dllmain.lo `test -f 'dllmain.c' || echo '$(srcdir)/'`dllmain.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-dllmain.Tpo $(DEPDIR)/libcurl_la-dllmain.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='dllmain.c' object='libcurl_la-dllmain.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-dllmain.lo `test -f 'dllmain.c' || echo '$(srcdir)/'`dllmain.c + +libcurl_la-doh.lo: doh.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-doh.lo -MD -MP -MF $(DEPDIR)/libcurl_la-doh.Tpo -c -o libcurl_la-doh.lo `test -f 'doh.c' || echo '$(srcdir)/'`doh.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-doh.Tpo $(DEPDIR)/libcurl_la-doh.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='doh.c' object='libcurl_la-doh.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-doh.lo `test -f 'doh.c' || echo '$(srcdir)/'`doh.c + +libcurl_la-dynbuf.lo: dynbuf.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-dynbuf.lo -MD -MP -MF $(DEPDIR)/libcurl_la-dynbuf.Tpo -c -o libcurl_la-dynbuf.lo `test -f 'dynbuf.c' || echo '$(srcdir)/'`dynbuf.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-dynbuf.Tpo $(DEPDIR)/libcurl_la-dynbuf.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='dynbuf.c' object='libcurl_la-dynbuf.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-dynbuf.lo `test -f 'dynbuf.c' || echo '$(srcdir)/'`dynbuf.c + +libcurl_la-dynhds.lo: dynhds.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-dynhds.lo -MD -MP -MF $(DEPDIR)/libcurl_la-dynhds.Tpo -c -o libcurl_la-dynhds.lo `test -f 'dynhds.c' || echo '$(srcdir)/'`dynhds.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-dynhds.Tpo $(DEPDIR)/libcurl_la-dynhds.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='dynhds.c' object='libcurl_la-dynhds.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-dynhds.lo `test -f 'dynhds.c' || echo '$(srcdir)/'`dynhds.c + +libcurl_la-easy.lo: easy.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-easy.lo -MD -MP -MF $(DEPDIR)/libcurl_la-easy.Tpo -c -o libcurl_la-easy.lo `test -f 'easy.c' || echo '$(srcdir)/'`easy.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-easy.Tpo $(DEPDIR)/libcurl_la-easy.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='easy.c' object='libcurl_la-easy.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-easy.lo `test -f 'easy.c' || echo '$(srcdir)/'`easy.c + +libcurl_la-easygetopt.lo: easygetopt.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-easygetopt.lo -MD -MP -MF $(DEPDIR)/libcurl_la-easygetopt.Tpo -c -o libcurl_la-easygetopt.lo `test -f 'easygetopt.c' || echo '$(srcdir)/'`easygetopt.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-easygetopt.Tpo $(DEPDIR)/libcurl_la-easygetopt.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='easygetopt.c' object='libcurl_la-easygetopt.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-easygetopt.lo `test -f 'easygetopt.c' || echo '$(srcdir)/'`easygetopt.c + +libcurl_la-easyoptions.lo: easyoptions.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-easyoptions.lo -MD -MP -MF $(DEPDIR)/libcurl_la-easyoptions.Tpo -c -o libcurl_la-easyoptions.lo `test -f 'easyoptions.c' || echo '$(srcdir)/'`easyoptions.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-easyoptions.Tpo $(DEPDIR)/libcurl_la-easyoptions.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='easyoptions.c' object='libcurl_la-easyoptions.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-easyoptions.lo `test -f 'easyoptions.c' || echo '$(srcdir)/'`easyoptions.c + +libcurl_la-escape.lo: escape.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-escape.lo -MD -MP -MF $(DEPDIR)/libcurl_la-escape.Tpo -c -o libcurl_la-escape.lo `test -f 'escape.c' || echo '$(srcdir)/'`escape.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-escape.Tpo $(DEPDIR)/libcurl_la-escape.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='escape.c' object='libcurl_la-escape.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-escape.lo `test -f 'escape.c' || echo '$(srcdir)/'`escape.c + +libcurl_la-file.lo: file.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-file.lo -MD -MP -MF $(DEPDIR)/libcurl_la-file.Tpo -c -o libcurl_la-file.lo `test -f 'file.c' || echo '$(srcdir)/'`file.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-file.Tpo $(DEPDIR)/libcurl_la-file.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='file.c' object='libcurl_la-file.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-file.lo `test -f 'file.c' || echo '$(srcdir)/'`file.c + +libcurl_la-fileinfo.lo: fileinfo.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-fileinfo.lo -MD -MP -MF $(DEPDIR)/libcurl_la-fileinfo.Tpo -c -o libcurl_la-fileinfo.lo `test -f 'fileinfo.c' || echo '$(srcdir)/'`fileinfo.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-fileinfo.Tpo $(DEPDIR)/libcurl_la-fileinfo.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='fileinfo.c' object='libcurl_la-fileinfo.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-fileinfo.lo `test -f 'fileinfo.c' || echo '$(srcdir)/'`fileinfo.c + +libcurl_la-fopen.lo: fopen.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-fopen.lo -MD -MP -MF $(DEPDIR)/libcurl_la-fopen.Tpo -c -o libcurl_la-fopen.lo `test -f 'fopen.c' || echo '$(srcdir)/'`fopen.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-fopen.Tpo $(DEPDIR)/libcurl_la-fopen.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='fopen.c' object='libcurl_la-fopen.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-fopen.lo `test -f 'fopen.c' || echo '$(srcdir)/'`fopen.c + +libcurl_la-formdata.lo: formdata.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-formdata.lo -MD -MP -MF $(DEPDIR)/libcurl_la-formdata.Tpo -c -o libcurl_la-formdata.lo `test -f 'formdata.c' || echo '$(srcdir)/'`formdata.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-formdata.Tpo $(DEPDIR)/libcurl_la-formdata.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='formdata.c' object='libcurl_la-formdata.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-formdata.lo `test -f 'formdata.c' || echo '$(srcdir)/'`formdata.c + +libcurl_la-ftp.lo: ftp.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-ftp.lo -MD -MP -MF $(DEPDIR)/libcurl_la-ftp.Tpo -c -o libcurl_la-ftp.lo `test -f 'ftp.c' || echo '$(srcdir)/'`ftp.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-ftp.Tpo $(DEPDIR)/libcurl_la-ftp.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='ftp.c' object='libcurl_la-ftp.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-ftp.lo `test -f 'ftp.c' || echo '$(srcdir)/'`ftp.c + +libcurl_la-ftplistparser.lo: ftplistparser.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-ftplistparser.lo -MD -MP -MF $(DEPDIR)/libcurl_la-ftplistparser.Tpo -c -o libcurl_la-ftplistparser.lo `test -f 'ftplistparser.c' || echo '$(srcdir)/'`ftplistparser.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-ftplistparser.Tpo $(DEPDIR)/libcurl_la-ftplistparser.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='ftplistparser.c' object='libcurl_la-ftplistparser.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-ftplistparser.lo `test -f 'ftplistparser.c' || echo '$(srcdir)/'`ftplistparser.c + +libcurl_la-getenv.lo: getenv.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-getenv.lo -MD -MP -MF $(DEPDIR)/libcurl_la-getenv.Tpo -c -o libcurl_la-getenv.lo `test -f 'getenv.c' || echo '$(srcdir)/'`getenv.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-getenv.Tpo $(DEPDIR)/libcurl_la-getenv.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='getenv.c' object='libcurl_la-getenv.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-getenv.lo `test -f 'getenv.c' || echo '$(srcdir)/'`getenv.c + +libcurl_la-getinfo.lo: getinfo.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-getinfo.lo -MD -MP -MF $(DEPDIR)/libcurl_la-getinfo.Tpo -c -o libcurl_la-getinfo.lo `test -f 'getinfo.c' || echo '$(srcdir)/'`getinfo.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-getinfo.Tpo $(DEPDIR)/libcurl_la-getinfo.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='getinfo.c' object='libcurl_la-getinfo.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-getinfo.lo `test -f 'getinfo.c' || echo '$(srcdir)/'`getinfo.c + +libcurl_la-gopher.lo: gopher.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-gopher.lo -MD -MP -MF $(DEPDIR)/libcurl_la-gopher.Tpo -c -o libcurl_la-gopher.lo `test -f 'gopher.c' || echo '$(srcdir)/'`gopher.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-gopher.Tpo $(DEPDIR)/libcurl_la-gopher.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='gopher.c' object='libcurl_la-gopher.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-gopher.lo `test -f 'gopher.c' || echo '$(srcdir)/'`gopher.c + +libcurl_la-hash.lo: hash.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-hash.lo -MD -MP -MF $(DEPDIR)/libcurl_la-hash.Tpo -c -o libcurl_la-hash.lo `test -f 'hash.c' || echo '$(srcdir)/'`hash.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-hash.Tpo $(DEPDIR)/libcurl_la-hash.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='hash.c' object='libcurl_la-hash.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-hash.lo `test -f 'hash.c' || echo '$(srcdir)/'`hash.c + +libcurl_la-headers.lo: headers.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-headers.lo -MD -MP -MF $(DEPDIR)/libcurl_la-headers.Tpo -c -o libcurl_la-headers.lo `test -f 'headers.c' || echo '$(srcdir)/'`headers.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-headers.Tpo $(DEPDIR)/libcurl_la-headers.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='headers.c' object='libcurl_la-headers.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-headers.lo `test -f 'headers.c' || echo '$(srcdir)/'`headers.c + +libcurl_la-hmac.lo: hmac.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-hmac.lo -MD -MP -MF $(DEPDIR)/libcurl_la-hmac.Tpo -c -o libcurl_la-hmac.lo `test -f 'hmac.c' || echo '$(srcdir)/'`hmac.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-hmac.Tpo $(DEPDIR)/libcurl_la-hmac.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='hmac.c' object='libcurl_la-hmac.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-hmac.lo `test -f 'hmac.c' || echo '$(srcdir)/'`hmac.c + +libcurl_la-hostasyn.lo: hostasyn.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-hostasyn.lo -MD -MP -MF $(DEPDIR)/libcurl_la-hostasyn.Tpo -c -o libcurl_la-hostasyn.lo `test -f 'hostasyn.c' || echo '$(srcdir)/'`hostasyn.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-hostasyn.Tpo $(DEPDIR)/libcurl_la-hostasyn.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='hostasyn.c' object='libcurl_la-hostasyn.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-hostasyn.lo `test -f 'hostasyn.c' || echo '$(srcdir)/'`hostasyn.c + +libcurl_la-hostip.lo: hostip.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-hostip.lo -MD -MP -MF $(DEPDIR)/libcurl_la-hostip.Tpo -c -o libcurl_la-hostip.lo `test -f 'hostip.c' || echo '$(srcdir)/'`hostip.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-hostip.Tpo $(DEPDIR)/libcurl_la-hostip.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='hostip.c' object='libcurl_la-hostip.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-hostip.lo `test -f 'hostip.c' || echo '$(srcdir)/'`hostip.c + +libcurl_la-hostip4.lo: hostip4.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-hostip4.lo -MD -MP -MF $(DEPDIR)/libcurl_la-hostip4.Tpo -c -o libcurl_la-hostip4.lo `test -f 'hostip4.c' || echo '$(srcdir)/'`hostip4.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-hostip4.Tpo $(DEPDIR)/libcurl_la-hostip4.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='hostip4.c' object='libcurl_la-hostip4.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-hostip4.lo `test -f 'hostip4.c' || echo '$(srcdir)/'`hostip4.c + +libcurl_la-hostip6.lo: hostip6.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-hostip6.lo -MD -MP -MF $(DEPDIR)/libcurl_la-hostip6.Tpo -c -o libcurl_la-hostip6.lo `test -f 'hostip6.c' || echo '$(srcdir)/'`hostip6.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-hostip6.Tpo $(DEPDIR)/libcurl_la-hostip6.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='hostip6.c' object='libcurl_la-hostip6.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-hostip6.lo `test -f 'hostip6.c' || echo '$(srcdir)/'`hostip6.c + +libcurl_la-hostsyn.lo: hostsyn.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-hostsyn.lo -MD -MP -MF $(DEPDIR)/libcurl_la-hostsyn.Tpo -c -o libcurl_la-hostsyn.lo `test -f 'hostsyn.c' || echo '$(srcdir)/'`hostsyn.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-hostsyn.Tpo $(DEPDIR)/libcurl_la-hostsyn.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='hostsyn.c' object='libcurl_la-hostsyn.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-hostsyn.lo `test -f 'hostsyn.c' || echo '$(srcdir)/'`hostsyn.c + +libcurl_la-hsts.lo: hsts.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-hsts.lo -MD -MP -MF $(DEPDIR)/libcurl_la-hsts.Tpo -c -o libcurl_la-hsts.lo `test -f 'hsts.c' || echo '$(srcdir)/'`hsts.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-hsts.Tpo $(DEPDIR)/libcurl_la-hsts.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='hsts.c' object='libcurl_la-hsts.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-hsts.lo `test -f 'hsts.c' || echo '$(srcdir)/'`hsts.c + +libcurl_la-http.lo: http.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-http.lo -MD -MP -MF $(DEPDIR)/libcurl_la-http.Tpo -c -o libcurl_la-http.lo `test -f 'http.c' || echo '$(srcdir)/'`http.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-http.Tpo $(DEPDIR)/libcurl_la-http.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http.c' object='libcurl_la-http.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-http.lo `test -f 'http.c' || echo '$(srcdir)/'`http.c + +libcurl_la-http1.lo: http1.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-http1.lo -MD -MP -MF $(DEPDIR)/libcurl_la-http1.Tpo -c -o libcurl_la-http1.lo `test -f 'http1.c' || echo '$(srcdir)/'`http1.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-http1.Tpo $(DEPDIR)/libcurl_la-http1.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http1.c' object='libcurl_la-http1.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-http1.lo `test -f 'http1.c' || echo '$(srcdir)/'`http1.c + +libcurl_la-http2.lo: http2.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-http2.lo -MD -MP -MF $(DEPDIR)/libcurl_la-http2.Tpo -c -o libcurl_la-http2.lo `test -f 'http2.c' || echo '$(srcdir)/'`http2.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-http2.Tpo $(DEPDIR)/libcurl_la-http2.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http2.c' object='libcurl_la-http2.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-http2.lo `test -f 'http2.c' || echo '$(srcdir)/'`http2.c + +libcurl_la-http_aws_sigv4.lo: http_aws_sigv4.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-http_aws_sigv4.lo -MD -MP -MF $(DEPDIR)/libcurl_la-http_aws_sigv4.Tpo -c -o libcurl_la-http_aws_sigv4.lo `test -f 'http_aws_sigv4.c' || echo '$(srcdir)/'`http_aws_sigv4.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-http_aws_sigv4.Tpo $(DEPDIR)/libcurl_la-http_aws_sigv4.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http_aws_sigv4.c' object='libcurl_la-http_aws_sigv4.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-http_aws_sigv4.lo `test -f 'http_aws_sigv4.c' || echo '$(srcdir)/'`http_aws_sigv4.c + +libcurl_la-http_chunks.lo: http_chunks.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-http_chunks.lo -MD -MP -MF $(DEPDIR)/libcurl_la-http_chunks.Tpo -c -o libcurl_la-http_chunks.lo `test -f 'http_chunks.c' || echo '$(srcdir)/'`http_chunks.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-http_chunks.Tpo $(DEPDIR)/libcurl_la-http_chunks.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http_chunks.c' object='libcurl_la-http_chunks.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-http_chunks.lo `test -f 'http_chunks.c' || echo '$(srcdir)/'`http_chunks.c + +libcurl_la-http_digest.lo: http_digest.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-http_digest.lo -MD -MP -MF $(DEPDIR)/libcurl_la-http_digest.Tpo -c -o libcurl_la-http_digest.lo `test -f 'http_digest.c' || echo '$(srcdir)/'`http_digest.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-http_digest.Tpo $(DEPDIR)/libcurl_la-http_digest.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http_digest.c' object='libcurl_la-http_digest.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-http_digest.lo `test -f 'http_digest.c' || echo '$(srcdir)/'`http_digest.c + +libcurl_la-http_negotiate.lo: http_negotiate.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-http_negotiate.lo -MD -MP -MF $(DEPDIR)/libcurl_la-http_negotiate.Tpo -c -o libcurl_la-http_negotiate.lo `test -f 'http_negotiate.c' || echo '$(srcdir)/'`http_negotiate.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-http_negotiate.Tpo $(DEPDIR)/libcurl_la-http_negotiate.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http_negotiate.c' object='libcurl_la-http_negotiate.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-http_negotiate.lo `test -f 'http_negotiate.c' || echo '$(srcdir)/'`http_negotiate.c + +libcurl_la-http_ntlm.lo: http_ntlm.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-http_ntlm.lo -MD -MP -MF $(DEPDIR)/libcurl_la-http_ntlm.Tpo -c -o libcurl_la-http_ntlm.lo `test -f 'http_ntlm.c' || echo '$(srcdir)/'`http_ntlm.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-http_ntlm.Tpo $(DEPDIR)/libcurl_la-http_ntlm.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http_ntlm.c' object='libcurl_la-http_ntlm.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-http_ntlm.lo `test -f 'http_ntlm.c' || echo '$(srcdir)/'`http_ntlm.c + +libcurl_la-http_proxy.lo: http_proxy.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-http_proxy.lo -MD -MP -MF $(DEPDIR)/libcurl_la-http_proxy.Tpo -c -o libcurl_la-http_proxy.lo `test -f 'http_proxy.c' || echo '$(srcdir)/'`http_proxy.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-http_proxy.Tpo $(DEPDIR)/libcurl_la-http_proxy.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http_proxy.c' object='libcurl_la-http_proxy.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-http_proxy.lo `test -f 'http_proxy.c' || echo '$(srcdir)/'`http_proxy.c + +libcurl_la-idn.lo: idn.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-idn.lo -MD -MP -MF $(DEPDIR)/libcurl_la-idn.Tpo -c -o libcurl_la-idn.lo `test -f 'idn.c' || echo '$(srcdir)/'`idn.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-idn.Tpo $(DEPDIR)/libcurl_la-idn.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='idn.c' object='libcurl_la-idn.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-idn.lo `test -f 'idn.c' || echo '$(srcdir)/'`idn.c + +libcurl_la-if2ip.lo: if2ip.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-if2ip.lo -MD -MP -MF $(DEPDIR)/libcurl_la-if2ip.Tpo -c -o libcurl_la-if2ip.lo `test -f 'if2ip.c' || echo '$(srcdir)/'`if2ip.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-if2ip.Tpo $(DEPDIR)/libcurl_la-if2ip.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='if2ip.c' object='libcurl_la-if2ip.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-if2ip.lo `test -f 'if2ip.c' || echo '$(srcdir)/'`if2ip.c + +libcurl_la-imap.lo: imap.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-imap.lo -MD -MP -MF $(DEPDIR)/libcurl_la-imap.Tpo -c -o libcurl_la-imap.lo `test -f 'imap.c' || echo '$(srcdir)/'`imap.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-imap.Tpo $(DEPDIR)/libcurl_la-imap.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='imap.c' object='libcurl_la-imap.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-imap.lo `test -f 'imap.c' || echo '$(srcdir)/'`imap.c + +libcurl_la-inet_ntop.lo: inet_ntop.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-inet_ntop.lo -MD -MP -MF $(DEPDIR)/libcurl_la-inet_ntop.Tpo -c -o libcurl_la-inet_ntop.lo `test -f 'inet_ntop.c' || echo '$(srcdir)/'`inet_ntop.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-inet_ntop.Tpo $(DEPDIR)/libcurl_la-inet_ntop.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='inet_ntop.c' object='libcurl_la-inet_ntop.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-inet_ntop.lo `test -f 'inet_ntop.c' || echo '$(srcdir)/'`inet_ntop.c + +libcurl_la-inet_pton.lo: inet_pton.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-inet_pton.lo -MD -MP -MF $(DEPDIR)/libcurl_la-inet_pton.Tpo -c -o libcurl_la-inet_pton.lo `test -f 'inet_pton.c' || echo '$(srcdir)/'`inet_pton.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-inet_pton.Tpo $(DEPDIR)/libcurl_la-inet_pton.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='inet_pton.c' object='libcurl_la-inet_pton.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-inet_pton.lo `test -f 'inet_pton.c' || echo '$(srcdir)/'`inet_pton.c + +libcurl_la-krb5.lo: krb5.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-krb5.lo -MD -MP -MF $(DEPDIR)/libcurl_la-krb5.Tpo -c -o libcurl_la-krb5.lo `test -f 'krb5.c' || echo '$(srcdir)/'`krb5.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-krb5.Tpo $(DEPDIR)/libcurl_la-krb5.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='krb5.c' object='libcurl_la-krb5.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-krb5.lo `test -f 'krb5.c' || echo '$(srcdir)/'`krb5.c + +libcurl_la-ldap.lo: ldap.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-ldap.lo -MD -MP -MF $(DEPDIR)/libcurl_la-ldap.Tpo -c -o libcurl_la-ldap.lo `test -f 'ldap.c' || echo '$(srcdir)/'`ldap.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-ldap.Tpo $(DEPDIR)/libcurl_la-ldap.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='ldap.c' object='libcurl_la-ldap.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-ldap.lo `test -f 'ldap.c' || echo '$(srcdir)/'`ldap.c + +libcurl_la-llist.lo: llist.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-llist.lo -MD -MP -MF $(DEPDIR)/libcurl_la-llist.Tpo -c -o libcurl_la-llist.lo `test -f 'llist.c' || echo '$(srcdir)/'`llist.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-llist.Tpo $(DEPDIR)/libcurl_la-llist.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='llist.c' object='libcurl_la-llist.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-llist.lo `test -f 'llist.c' || echo '$(srcdir)/'`llist.c + +libcurl_la-macos.lo: macos.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-macos.lo -MD -MP -MF $(DEPDIR)/libcurl_la-macos.Tpo -c -o libcurl_la-macos.lo `test -f 'macos.c' || echo '$(srcdir)/'`macos.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-macos.Tpo $(DEPDIR)/libcurl_la-macos.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='macos.c' object='libcurl_la-macos.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-macos.lo `test -f 'macos.c' || echo '$(srcdir)/'`macos.c + +libcurl_la-md4.lo: md4.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-md4.lo -MD -MP -MF $(DEPDIR)/libcurl_la-md4.Tpo -c -o libcurl_la-md4.lo `test -f 'md4.c' || echo '$(srcdir)/'`md4.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-md4.Tpo $(DEPDIR)/libcurl_la-md4.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='md4.c' object='libcurl_la-md4.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-md4.lo `test -f 'md4.c' || echo '$(srcdir)/'`md4.c + +libcurl_la-md5.lo: md5.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-md5.lo -MD -MP -MF $(DEPDIR)/libcurl_la-md5.Tpo -c -o libcurl_la-md5.lo `test -f 'md5.c' || echo '$(srcdir)/'`md5.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-md5.Tpo $(DEPDIR)/libcurl_la-md5.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='md5.c' object='libcurl_la-md5.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-md5.lo `test -f 'md5.c' || echo '$(srcdir)/'`md5.c + +libcurl_la-memdebug.lo: memdebug.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-memdebug.lo -MD -MP -MF $(DEPDIR)/libcurl_la-memdebug.Tpo -c -o libcurl_la-memdebug.lo `test -f 'memdebug.c' || echo '$(srcdir)/'`memdebug.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-memdebug.Tpo $(DEPDIR)/libcurl_la-memdebug.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='memdebug.c' object='libcurl_la-memdebug.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-memdebug.lo `test -f 'memdebug.c' || echo '$(srcdir)/'`memdebug.c + +libcurl_la-mime.lo: mime.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-mime.lo -MD -MP -MF $(DEPDIR)/libcurl_la-mime.Tpo -c -o libcurl_la-mime.lo `test -f 'mime.c' || echo '$(srcdir)/'`mime.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-mime.Tpo $(DEPDIR)/libcurl_la-mime.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mime.c' object='libcurl_la-mime.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-mime.lo `test -f 'mime.c' || echo '$(srcdir)/'`mime.c + +libcurl_la-mprintf.lo: mprintf.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-mprintf.lo -MD -MP -MF $(DEPDIR)/libcurl_la-mprintf.Tpo -c -o libcurl_la-mprintf.lo `test -f 'mprintf.c' || echo '$(srcdir)/'`mprintf.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-mprintf.Tpo $(DEPDIR)/libcurl_la-mprintf.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mprintf.c' object='libcurl_la-mprintf.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-mprintf.lo `test -f 'mprintf.c' || echo '$(srcdir)/'`mprintf.c + +libcurl_la-mqtt.lo: mqtt.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-mqtt.lo -MD -MP -MF $(DEPDIR)/libcurl_la-mqtt.Tpo -c -o libcurl_la-mqtt.lo `test -f 'mqtt.c' || echo '$(srcdir)/'`mqtt.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-mqtt.Tpo $(DEPDIR)/libcurl_la-mqtt.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mqtt.c' object='libcurl_la-mqtt.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-mqtt.lo `test -f 'mqtt.c' || echo '$(srcdir)/'`mqtt.c + +libcurl_la-multi.lo: multi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-multi.lo -MD -MP -MF $(DEPDIR)/libcurl_la-multi.Tpo -c -o libcurl_la-multi.lo `test -f 'multi.c' || echo '$(srcdir)/'`multi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-multi.Tpo $(DEPDIR)/libcurl_la-multi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='multi.c' object='libcurl_la-multi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-multi.lo `test -f 'multi.c' || echo '$(srcdir)/'`multi.c + +libcurl_la-netrc.lo: netrc.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-netrc.lo -MD -MP -MF $(DEPDIR)/libcurl_la-netrc.Tpo -c -o libcurl_la-netrc.lo `test -f 'netrc.c' || echo '$(srcdir)/'`netrc.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-netrc.Tpo $(DEPDIR)/libcurl_la-netrc.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='netrc.c' object='libcurl_la-netrc.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-netrc.lo `test -f 'netrc.c' || echo '$(srcdir)/'`netrc.c + +libcurl_la-nonblock.lo: nonblock.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-nonblock.lo -MD -MP -MF $(DEPDIR)/libcurl_la-nonblock.Tpo -c -o libcurl_la-nonblock.lo `test -f 'nonblock.c' || echo '$(srcdir)/'`nonblock.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-nonblock.Tpo $(DEPDIR)/libcurl_la-nonblock.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='nonblock.c' object='libcurl_la-nonblock.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-nonblock.lo `test -f 'nonblock.c' || echo '$(srcdir)/'`nonblock.c + +libcurl_la-noproxy.lo: noproxy.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-noproxy.lo -MD -MP -MF $(DEPDIR)/libcurl_la-noproxy.Tpo -c -o libcurl_la-noproxy.lo `test -f 'noproxy.c' || echo '$(srcdir)/'`noproxy.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-noproxy.Tpo $(DEPDIR)/libcurl_la-noproxy.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='noproxy.c' object='libcurl_la-noproxy.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-noproxy.lo `test -f 'noproxy.c' || echo '$(srcdir)/'`noproxy.c + +libcurl_la-openldap.lo: openldap.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-openldap.lo -MD -MP -MF $(DEPDIR)/libcurl_la-openldap.Tpo -c -o libcurl_la-openldap.lo `test -f 'openldap.c' || echo '$(srcdir)/'`openldap.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-openldap.Tpo $(DEPDIR)/libcurl_la-openldap.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='openldap.c' object='libcurl_la-openldap.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-openldap.lo `test -f 'openldap.c' || echo '$(srcdir)/'`openldap.c + +libcurl_la-parsedate.lo: parsedate.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-parsedate.lo -MD -MP -MF $(DEPDIR)/libcurl_la-parsedate.Tpo -c -o libcurl_la-parsedate.lo `test -f 'parsedate.c' || echo '$(srcdir)/'`parsedate.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-parsedate.Tpo $(DEPDIR)/libcurl_la-parsedate.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='parsedate.c' object='libcurl_la-parsedate.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-parsedate.lo `test -f 'parsedate.c' || echo '$(srcdir)/'`parsedate.c + +libcurl_la-pingpong.lo: pingpong.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-pingpong.lo -MD -MP -MF $(DEPDIR)/libcurl_la-pingpong.Tpo -c -o libcurl_la-pingpong.lo `test -f 'pingpong.c' || echo '$(srcdir)/'`pingpong.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-pingpong.Tpo $(DEPDIR)/libcurl_la-pingpong.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='pingpong.c' object='libcurl_la-pingpong.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-pingpong.lo `test -f 'pingpong.c' || echo '$(srcdir)/'`pingpong.c + +libcurl_la-pop3.lo: pop3.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-pop3.lo -MD -MP -MF $(DEPDIR)/libcurl_la-pop3.Tpo -c -o libcurl_la-pop3.lo `test -f 'pop3.c' || echo '$(srcdir)/'`pop3.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-pop3.Tpo $(DEPDIR)/libcurl_la-pop3.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='pop3.c' object='libcurl_la-pop3.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-pop3.lo `test -f 'pop3.c' || echo '$(srcdir)/'`pop3.c + +libcurl_la-progress.lo: progress.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-progress.lo -MD -MP -MF $(DEPDIR)/libcurl_la-progress.Tpo -c -o libcurl_la-progress.lo `test -f 'progress.c' || echo '$(srcdir)/'`progress.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-progress.Tpo $(DEPDIR)/libcurl_la-progress.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='progress.c' object='libcurl_la-progress.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-progress.lo `test -f 'progress.c' || echo '$(srcdir)/'`progress.c + +libcurl_la-psl.lo: psl.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-psl.lo -MD -MP -MF $(DEPDIR)/libcurl_la-psl.Tpo -c -o libcurl_la-psl.lo `test -f 'psl.c' || echo '$(srcdir)/'`psl.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-psl.Tpo $(DEPDIR)/libcurl_la-psl.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='psl.c' object='libcurl_la-psl.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-psl.lo `test -f 'psl.c' || echo '$(srcdir)/'`psl.c + +libcurl_la-rand.lo: rand.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-rand.lo -MD -MP -MF $(DEPDIR)/libcurl_la-rand.Tpo -c -o libcurl_la-rand.lo `test -f 'rand.c' || echo '$(srcdir)/'`rand.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-rand.Tpo $(DEPDIR)/libcurl_la-rand.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='rand.c' object='libcurl_la-rand.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-rand.lo `test -f 'rand.c' || echo '$(srcdir)/'`rand.c + +libcurl_la-rename.lo: rename.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-rename.lo -MD -MP -MF $(DEPDIR)/libcurl_la-rename.Tpo -c -o libcurl_la-rename.lo `test -f 'rename.c' || echo '$(srcdir)/'`rename.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-rename.Tpo $(DEPDIR)/libcurl_la-rename.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='rename.c' object='libcurl_la-rename.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-rename.lo `test -f 'rename.c' || echo '$(srcdir)/'`rename.c + +libcurl_la-request.lo: request.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-request.lo -MD -MP -MF $(DEPDIR)/libcurl_la-request.Tpo -c -o libcurl_la-request.lo `test -f 'request.c' || echo '$(srcdir)/'`request.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-request.Tpo $(DEPDIR)/libcurl_la-request.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='request.c' object='libcurl_la-request.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-request.lo `test -f 'request.c' || echo '$(srcdir)/'`request.c + +libcurl_la-rtsp.lo: rtsp.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-rtsp.lo -MD -MP -MF $(DEPDIR)/libcurl_la-rtsp.Tpo -c -o libcurl_la-rtsp.lo `test -f 'rtsp.c' || echo '$(srcdir)/'`rtsp.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-rtsp.Tpo $(DEPDIR)/libcurl_la-rtsp.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='rtsp.c' object='libcurl_la-rtsp.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-rtsp.lo `test -f 'rtsp.c' || echo '$(srcdir)/'`rtsp.c + +libcurl_la-select.lo: select.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-select.lo -MD -MP -MF $(DEPDIR)/libcurl_la-select.Tpo -c -o libcurl_la-select.lo `test -f 'select.c' || echo '$(srcdir)/'`select.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-select.Tpo $(DEPDIR)/libcurl_la-select.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='select.c' object='libcurl_la-select.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-select.lo `test -f 'select.c' || echo '$(srcdir)/'`select.c + +libcurl_la-sendf.lo: sendf.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-sendf.lo -MD -MP -MF $(DEPDIR)/libcurl_la-sendf.Tpo -c -o libcurl_la-sendf.lo `test -f 'sendf.c' || echo '$(srcdir)/'`sendf.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-sendf.Tpo $(DEPDIR)/libcurl_la-sendf.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sendf.c' object='libcurl_la-sendf.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-sendf.lo `test -f 'sendf.c' || echo '$(srcdir)/'`sendf.c + +libcurl_la-setopt.lo: setopt.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-setopt.lo -MD -MP -MF $(DEPDIR)/libcurl_la-setopt.Tpo -c -o libcurl_la-setopt.lo `test -f 'setopt.c' || echo '$(srcdir)/'`setopt.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-setopt.Tpo $(DEPDIR)/libcurl_la-setopt.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='setopt.c' object='libcurl_la-setopt.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-setopt.lo `test -f 'setopt.c' || echo '$(srcdir)/'`setopt.c + +libcurl_la-sha256.lo: sha256.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-sha256.lo -MD -MP -MF $(DEPDIR)/libcurl_la-sha256.Tpo -c -o libcurl_la-sha256.lo `test -f 'sha256.c' || echo '$(srcdir)/'`sha256.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-sha256.Tpo $(DEPDIR)/libcurl_la-sha256.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha256.c' object='libcurl_la-sha256.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-sha256.lo `test -f 'sha256.c' || echo '$(srcdir)/'`sha256.c + +libcurl_la-share.lo: share.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-share.lo -MD -MP -MF $(DEPDIR)/libcurl_la-share.Tpo -c -o libcurl_la-share.lo `test -f 'share.c' || echo '$(srcdir)/'`share.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-share.Tpo $(DEPDIR)/libcurl_la-share.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='share.c' object='libcurl_la-share.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-share.lo `test -f 'share.c' || echo '$(srcdir)/'`share.c + +libcurl_la-slist.lo: slist.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-slist.lo -MD -MP -MF $(DEPDIR)/libcurl_la-slist.Tpo -c -o libcurl_la-slist.lo `test -f 'slist.c' || echo '$(srcdir)/'`slist.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-slist.Tpo $(DEPDIR)/libcurl_la-slist.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='slist.c' object='libcurl_la-slist.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-slist.lo `test -f 'slist.c' || echo '$(srcdir)/'`slist.c + +libcurl_la-smb.lo: smb.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-smb.lo -MD -MP -MF $(DEPDIR)/libcurl_la-smb.Tpo -c -o libcurl_la-smb.lo `test -f 'smb.c' || echo '$(srcdir)/'`smb.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-smb.Tpo $(DEPDIR)/libcurl_la-smb.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='smb.c' object='libcurl_la-smb.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-smb.lo `test -f 'smb.c' || echo '$(srcdir)/'`smb.c + +libcurl_la-smtp.lo: smtp.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-smtp.lo -MD -MP -MF $(DEPDIR)/libcurl_la-smtp.Tpo -c -o libcurl_la-smtp.lo `test -f 'smtp.c' || echo '$(srcdir)/'`smtp.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-smtp.Tpo $(DEPDIR)/libcurl_la-smtp.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='smtp.c' object='libcurl_la-smtp.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-smtp.lo `test -f 'smtp.c' || echo '$(srcdir)/'`smtp.c + +libcurl_la-socketpair.lo: socketpair.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-socketpair.lo -MD -MP -MF $(DEPDIR)/libcurl_la-socketpair.Tpo -c -o libcurl_la-socketpair.lo `test -f 'socketpair.c' || echo '$(srcdir)/'`socketpair.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-socketpair.Tpo $(DEPDIR)/libcurl_la-socketpair.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='socketpair.c' object='libcurl_la-socketpair.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-socketpair.lo `test -f 'socketpair.c' || echo '$(srcdir)/'`socketpair.c + +libcurl_la-socks.lo: socks.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-socks.lo -MD -MP -MF $(DEPDIR)/libcurl_la-socks.Tpo -c -o libcurl_la-socks.lo `test -f 'socks.c' || echo '$(srcdir)/'`socks.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-socks.Tpo $(DEPDIR)/libcurl_la-socks.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='socks.c' object='libcurl_la-socks.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-socks.lo `test -f 'socks.c' || echo '$(srcdir)/'`socks.c + +libcurl_la-socks_gssapi.lo: socks_gssapi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-socks_gssapi.lo -MD -MP -MF $(DEPDIR)/libcurl_la-socks_gssapi.Tpo -c -o libcurl_la-socks_gssapi.lo `test -f 'socks_gssapi.c' || echo '$(srcdir)/'`socks_gssapi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-socks_gssapi.Tpo $(DEPDIR)/libcurl_la-socks_gssapi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='socks_gssapi.c' object='libcurl_la-socks_gssapi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-socks_gssapi.lo `test -f 'socks_gssapi.c' || echo '$(srcdir)/'`socks_gssapi.c + +libcurl_la-socks_sspi.lo: socks_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-socks_sspi.lo -MD -MP -MF $(DEPDIR)/libcurl_la-socks_sspi.Tpo -c -o libcurl_la-socks_sspi.lo `test -f 'socks_sspi.c' || echo '$(srcdir)/'`socks_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-socks_sspi.Tpo $(DEPDIR)/libcurl_la-socks_sspi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='socks_sspi.c' object='libcurl_la-socks_sspi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-socks_sspi.lo `test -f 'socks_sspi.c' || echo '$(srcdir)/'`socks_sspi.c + +libcurl_la-speedcheck.lo: speedcheck.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-speedcheck.lo -MD -MP -MF $(DEPDIR)/libcurl_la-speedcheck.Tpo -c -o libcurl_la-speedcheck.lo `test -f 'speedcheck.c' || echo '$(srcdir)/'`speedcheck.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-speedcheck.Tpo $(DEPDIR)/libcurl_la-speedcheck.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='speedcheck.c' object='libcurl_la-speedcheck.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-speedcheck.lo `test -f 'speedcheck.c' || echo '$(srcdir)/'`speedcheck.c + +libcurl_la-splay.lo: splay.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-splay.lo -MD -MP -MF $(DEPDIR)/libcurl_la-splay.Tpo -c -o libcurl_la-splay.lo `test -f 'splay.c' || echo '$(srcdir)/'`splay.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-splay.Tpo $(DEPDIR)/libcurl_la-splay.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='splay.c' object='libcurl_la-splay.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-splay.lo `test -f 'splay.c' || echo '$(srcdir)/'`splay.c + +libcurl_la-strcase.lo: strcase.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-strcase.lo -MD -MP -MF $(DEPDIR)/libcurl_la-strcase.Tpo -c -o libcurl_la-strcase.lo `test -f 'strcase.c' || echo '$(srcdir)/'`strcase.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-strcase.Tpo $(DEPDIR)/libcurl_la-strcase.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='strcase.c' object='libcurl_la-strcase.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-strcase.lo `test -f 'strcase.c' || echo '$(srcdir)/'`strcase.c + +libcurl_la-strdup.lo: strdup.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-strdup.lo -MD -MP -MF $(DEPDIR)/libcurl_la-strdup.Tpo -c -o libcurl_la-strdup.lo `test -f 'strdup.c' || echo '$(srcdir)/'`strdup.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-strdup.Tpo $(DEPDIR)/libcurl_la-strdup.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='strdup.c' object='libcurl_la-strdup.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-strdup.lo `test -f 'strdup.c' || echo '$(srcdir)/'`strdup.c + +libcurl_la-strerror.lo: strerror.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-strerror.lo -MD -MP -MF $(DEPDIR)/libcurl_la-strerror.Tpo -c -o libcurl_la-strerror.lo `test -f 'strerror.c' || echo '$(srcdir)/'`strerror.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-strerror.Tpo $(DEPDIR)/libcurl_la-strerror.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='strerror.c' object='libcurl_la-strerror.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-strerror.lo `test -f 'strerror.c' || echo '$(srcdir)/'`strerror.c + +libcurl_la-strtok.lo: strtok.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-strtok.lo -MD -MP -MF $(DEPDIR)/libcurl_la-strtok.Tpo -c -o libcurl_la-strtok.lo `test -f 'strtok.c' || echo '$(srcdir)/'`strtok.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-strtok.Tpo $(DEPDIR)/libcurl_la-strtok.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='strtok.c' object='libcurl_la-strtok.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-strtok.lo `test -f 'strtok.c' || echo '$(srcdir)/'`strtok.c + +libcurl_la-strtoofft.lo: strtoofft.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-strtoofft.lo -MD -MP -MF $(DEPDIR)/libcurl_la-strtoofft.Tpo -c -o libcurl_la-strtoofft.lo `test -f 'strtoofft.c' || echo '$(srcdir)/'`strtoofft.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-strtoofft.Tpo $(DEPDIR)/libcurl_la-strtoofft.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='strtoofft.c' object='libcurl_la-strtoofft.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-strtoofft.lo `test -f 'strtoofft.c' || echo '$(srcdir)/'`strtoofft.c + +libcurl_la-system_win32.lo: system_win32.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-system_win32.lo -MD -MP -MF $(DEPDIR)/libcurl_la-system_win32.Tpo -c -o libcurl_la-system_win32.lo `test -f 'system_win32.c' || echo '$(srcdir)/'`system_win32.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-system_win32.Tpo $(DEPDIR)/libcurl_la-system_win32.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='system_win32.c' object='libcurl_la-system_win32.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-system_win32.lo `test -f 'system_win32.c' || echo '$(srcdir)/'`system_win32.c + +libcurl_la-telnet.lo: telnet.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-telnet.lo -MD -MP -MF $(DEPDIR)/libcurl_la-telnet.Tpo -c -o libcurl_la-telnet.lo `test -f 'telnet.c' || echo '$(srcdir)/'`telnet.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-telnet.Tpo $(DEPDIR)/libcurl_la-telnet.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='telnet.c' object='libcurl_la-telnet.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-telnet.lo `test -f 'telnet.c' || echo '$(srcdir)/'`telnet.c + +libcurl_la-tftp.lo: tftp.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-tftp.lo -MD -MP -MF $(DEPDIR)/libcurl_la-tftp.Tpo -c -o libcurl_la-tftp.lo `test -f 'tftp.c' || echo '$(srcdir)/'`tftp.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-tftp.Tpo $(DEPDIR)/libcurl_la-tftp.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='tftp.c' object='libcurl_la-tftp.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-tftp.lo `test -f 'tftp.c' || echo '$(srcdir)/'`tftp.c + +libcurl_la-timediff.lo: timediff.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-timediff.lo -MD -MP -MF $(DEPDIR)/libcurl_la-timediff.Tpo -c -o libcurl_la-timediff.lo `test -f 'timediff.c' || echo '$(srcdir)/'`timediff.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-timediff.Tpo $(DEPDIR)/libcurl_la-timediff.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='timediff.c' object='libcurl_la-timediff.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-timediff.lo `test -f 'timediff.c' || echo '$(srcdir)/'`timediff.c + +libcurl_la-timeval.lo: timeval.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-timeval.lo -MD -MP -MF $(DEPDIR)/libcurl_la-timeval.Tpo -c -o libcurl_la-timeval.lo `test -f 'timeval.c' || echo '$(srcdir)/'`timeval.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-timeval.Tpo $(DEPDIR)/libcurl_la-timeval.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='timeval.c' object='libcurl_la-timeval.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-timeval.lo `test -f 'timeval.c' || echo '$(srcdir)/'`timeval.c + +libcurl_la-transfer.lo: transfer.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-transfer.lo -MD -MP -MF $(DEPDIR)/libcurl_la-transfer.Tpo -c -o libcurl_la-transfer.lo `test -f 'transfer.c' || echo '$(srcdir)/'`transfer.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-transfer.Tpo $(DEPDIR)/libcurl_la-transfer.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='transfer.c' object='libcurl_la-transfer.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-transfer.lo `test -f 'transfer.c' || echo '$(srcdir)/'`transfer.c + +libcurl_la-url.lo: url.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-url.lo -MD -MP -MF $(DEPDIR)/libcurl_la-url.Tpo -c -o libcurl_la-url.lo `test -f 'url.c' || echo '$(srcdir)/'`url.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-url.Tpo $(DEPDIR)/libcurl_la-url.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='url.c' object='libcurl_la-url.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-url.lo `test -f 'url.c' || echo '$(srcdir)/'`url.c + +libcurl_la-urlapi.lo: urlapi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-urlapi.lo -MD -MP -MF $(DEPDIR)/libcurl_la-urlapi.Tpo -c -o libcurl_la-urlapi.lo `test -f 'urlapi.c' || echo '$(srcdir)/'`urlapi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-urlapi.Tpo $(DEPDIR)/libcurl_la-urlapi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='urlapi.c' object='libcurl_la-urlapi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-urlapi.lo `test -f 'urlapi.c' || echo '$(srcdir)/'`urlapi.c + +libcurl_la-version.lo: version.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-version.lo -MD -MP -MF $(DEPDIR)/libcurl_la-version.Tpo -c -o libcurl_la-version.lo `test -f 'version.c' || echo '$(srcdir)/'`version.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-version.Tpo $(DEPDIR)/libcurl_la-version.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='version.c' object='libcurl_la-version.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-version.lo `test -f 'version.c' || echo '$(srcdir)/'`version.c + +libcurl_la-version_win32.lo: version_win32.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-version_win32.lo -MD -MP -MF $(DEPDIR)/libcurl_la-version_win32.Tpo -c -o libcurl_la-version_win32.lo `test -f 'version_win32.c' || echo '$(srcdir)/'`version_win32.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-version_win32.Tpo $(DEPDIR)/libcurl_la-version_win32.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='version_win32.c' object='libcurl_la-version_win32.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-version_win32.lo `test -f 'version_win32.c' || echo '$(srcdir)/'`version_win32.c + +libcurl_la-warnless.lo: warnless.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-warnless.lo -MD -MP -MF $(DEPDIR)/libcurl_la-warnless.Tpo -c -o libcurl_la-warnless.lo `test -f 'warnless.c' || echo '$(srcdir)/'`warnless.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-warnless.Tpo $(DEPDIR)/libcurl_la-warnless.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='warnless.c' object='libcurl_la-warnless.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-warnless.lo `test -f 'warnless.c' || echo '$(srcdir)/'`warnless.c + +libcurl_la-ws.lo: ws.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT libcurl_la-ws.lo -MD -MP -MF $(DEPDIR)/libcurl_la-ws.Tpo -c -o libcurl_la-ws.lo `test -f 'ws.c' || echo '$(srcdir)/'`ws.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurl_la-ws.Tpo $(DEPDIR)/libcurl_la-ws.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='ws.c' object='libcurl_la-ws.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o libcurl_la-ws.lo `test -f 'ws.c' || echo '$(srcdir)/'`ws.c + +vauth/libcurl_la-cleartext.lo: vauth/cleartext.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vauth/libcurl_la-cleartext.lo -MD -MP -MF vauth/$(DEPDIR)/libcurl_la-cleartext.Tpo -c -o vauth/libcurl_la-cleartext.lo `test -f 'vauth/cleartext.c' || echo '$(srcdir)/'`vauth/cleartext.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurl_la-cleartext.Tpo vauth/$(DEPDIR)/libcurl_la-cleartext.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/cleartext.c' object='vauth/libcurl_la-cleartext.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurl_la-cleartext.lo `test -f 'vauth/cleartext.c' || echo '$(srcdir)/'`vauth/cleartext.c + +vauth/libcurl_la-cram.lo: vauth/cram.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vauth/libcurl_la-cram.lo -MD -MP -MF vauth/$(DEPDIR)/libcurl_la-cram.Tpo -c -o vauth/libcurl_la-cram.lo `test -f 'vauth/cram.c' || echo '$(srcdir)/'`vauth/cram.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurl_la-cram.Tpo vauth/$(DEPDIR)/libcurl_la-cram.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/cram.c' object='vauth/libcurl_la-cram.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurl_la-cram.lo `test -f 'vauth/cram.c' || echo '$(srcdir)/'`vauth/cram.c + +vauth/libcurl_la-digest.lo: vauth/digest.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vauth/libcurl_la-digest.lo -MD -MP -MF vauth/$(DEPDIR)/libcurl_la-digest.Tpo -c -o vauth/libcurl_la-digest.lo `test -f 'vauth/digest.c' || echo '$(srcdir)/'`vauth/digest.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurl_la-digest.Tpo vauth/$(DEPDIR)/libcurl_la-digest.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/digest.c' object='vauth/libcurl_la-digest.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurl_la-digest.lo `test -f 'vauth/digest.c' || echo '$(srcdir)/'`vauth/digest.c + +vauth/libcurl_la-digest_sspi.lo: vauth/digest_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vauth/libcurl_la-digest_sspi.lo -MD -MP -MF vauth/$(DEPDIR)/libcurl_la-digest_sspi.Tpo -c -o vauth/libcurl_la-digest_sspi.lo `test -f 'vauth/digest_sspi.c' || echo '$(srcdir)/'`vauth/digest_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurl_la-digest_sspi.Tpo vauth/$(DEPDIR)/libcurl_la-digest_sspi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/digest_sspi.c' object='vauth/libcurl_la-digest_sspi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurl_la-digest_sspi.lo `test -f 'vauth/digest_sspi.c' || echo '$(srcdir)/'`vauth/digest_sspi.c + +vauth/libcurl_la-gsasl.lo: vauth/gsasl.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vauth/libcurl_la-gsasl.lo -MD -MP -MF vauth/$(DEPDIR)/libcurl_la-gsasl.Tpo -c -o vauth/libcurl_la-gsasl.lo `test -f 'vauth/gsasl.c' || echo '$(srcdir)/'`vauth/gsasl.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurl_la-gsasl.Tpo vauth/$(DEPDIR)/libcurl_la-gsasl.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/gsasl.c' object='vauth/libcurl_la-gsasl.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurl_la-gsasl.lo `test -f 'vauth/gsasl.c' || echo '$(srcdir)/'`vauth/gsasl.c + +vauth/libcurl_la-krb5_gssapi.lo: vauth/krb5_gssapi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vauth/libcurl_la-krb5_gssapi.lo -MD -MP -MF vauth/$(DEPDIR)/libcurl_la-krb5_gssapi.Tpo -c -o vauth/libcurl_la-krb5_gssapi.lo `test -f 'vauth/krb5_gssapi.c' || echo '$(srcdir)/'`vauth/krb5_gssapi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurl_la-krb5_gssapi.Tpo vauth/$(DEPDIR)/libcurl_la-krb5_gssapi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/krb5_gssapi.c' object='vauth/libcurl_la-krb5_gssapi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurl_la-krb5_gssapi.lo `test -f 'vauth/krb5_gssapi.c' || echo '$(srcdir)/'`vauth/krb5_gssapi.c + +vauth/libcurl_la-krb5_sspi.lo: vauth/krb5_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vauth/libcurl_la-krb5_sspi.lo -MD -MP -MF vauth/$(DEPDIR)/libcurl_la-krb5_sspi.Tpo -c -o vauth/libcurl_la-krb5_sspi.lo `test -f 'vauth/krb5_sspi.c' || echo '$(srcdir)/'`vauth/krb5_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurl_la-krb5_sspi.Tpo vauth/$(DEPDIR)/libcurl_la-krb5_sspi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/krb5_sspi.c' object='vauth/libcurl_la-krb5_sspi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurl_la-krb5_sspi.lo `test -f 'vauth/krb5_sspi.c' || echo '$(srcdir)/'`vauth/krb5_sspi.c + +vauth/libcurl_la-ntlm.lo: vauth/ntlm.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vauth/libcurl_la-ntlm.lo -MD -MP -MF vauth/$(DEPDIR)/libcurl_la-ntlm.Tpo -c -o vauth/libcurl_la-ntlm.lo `test -f 'vauth/ntlm.c' || echo '$(srcdir)/'`vauth/ntlm.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurl_la-ntlm.Tpo vauth/$(DEPDIR)/libcurl_la-ntlm.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/ntlm.c' object='vauth/libcurl_la-ntlm.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurl_la-ntlm.lo `test -f 'vauth/ntlm.c' || echo '$(srcdir)/'`vauth/ntlm.c + +vauth/libcurl_la-ntlm_sspi.lo: vauth/ntlm_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vauth/libcurl_la-ntlm_sspi.lo -MD -MP -MF vauth/$(DEPDIR)/libcurl_la-ntlm_sspi.Tpo -c -o vauth/libcurl_la-ntlm_sspi.lo `test -f 'vauth/ntlm_sspi.c' || echo '$(srcdir)/'`vauth/ntlm_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurl_la-ntlm_sspi.Tpo vauth/$(DEPDIR)/libcurl_la-ntlm_sspi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/ntlm_sspi.c' object='vauth/libcurl_la-ntlm_sspi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurl_la-ntlm_sspi.lo `test -f 'vauth/ntlm_sspi.c' || echo '$(srcdir)/'`vauth/ntlm_sspi.c + +vauth/libcurl_la-oauth2.lo: vauth/oauth2.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vauth/libcurl_la-oauth2.lo -MD -MP -MF vauth/$(DEPDIR)/libcurl_la-oauth2.Tpo -c -o vauth/libcurl_la-oauth2.lo `test -f 'vauth/oauth2.c' || echo '$(srcdir)/'`vauth/oauth2.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurl_la-oauth2.Tpo vauth/$(DEPDIR)/libcurl_la-oauth2.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/oauth2.c' object='vauth/libcurl_la-oauth2.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurl_la-oauth2.lo `test -f 'vauth/oauth2.c' || echo '$(srcdir)/'`vauth/oauth2.c + +vauth/libcurl_la-spnego_gssapi.lo: vauth/spnego_gssapi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vauth/libcurl_la-spnego_gssapi.lo -MD -MP -MF vauth/$(DEPDIR)/libcurl_la-spnego_gssapi.Tpo -c -o vauth/libcurl_la-spnego_gssapi.lo `test -f 'vauth/spnego_gssapi.c' || echo '$(srcdir)/'`vauth/spnego_gssapi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurl_la-spnego_gssapi.Tpo vauth/$(DEPDIR)/libcurl_la-spnego_gssapi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/spnego_gssapi.c' object='vauth/libcurl_la-spnego_gssapi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurl_la-spnego_gssapi.lo `test -f 'vauth/spnego_gssapi.c' || echo '$(srcdir)/'`vauth/spnego_gssapi.c + +vauth/libcurl_la-spnego_sspi.lo: vauth/spnego_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vauth/libcurl_la-spnego_sspi.lo -MD -MP -MF vauth/$(DEPDIR)/libcurl_la-spnego_sspi.Tpo -c -o vauth/libcurl_la-spnego_sspi.lo `test -f 'vauth/spnego_sspi.c' || echo '$(srcdir)/'`vauth/spnego_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurl_la-spnego_sspi.Tpo vauth/$(DEPDIR)/libcurl_la-spnego_sspi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/spnego_sspi.c' object='vauth/libcurl_la-spnego_sspi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurl_la-spnego_sspi.lo `test -f 'vauth/spnego_sspi.c' || echo '$(srcdir)/'`vauth/spnego_sspi.c + +vauth/libcurl_la-vauth.lo: vauth/vauth.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vauth/libcurl_la-vauth.lo -MD -MP -MF vauth/$(DEPDIR)/libcurl_la-vauth.Tpo -c -o vauth/libcurl_la-vauth.lo `test -f 'vauth/vauth.c' || echo '$(srcdir)/'`vauth/vauth.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurl_la-vauth.Tpo vauth/$(DEPDIR)/libcurl_la-vauth.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/vauth.c' object='vauth/libcurl_la-vauth.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurl_la-vauth.lo `test -f 'vauth/vauth.c' || echo '$(srcdir)/'`vauth/vauth.c + +vtls/libcurl_la-bearssl.lo: vtls/bearssl.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vtls/libcurl_la-bearssl.lo -MD -MP -MF vtls/$(DEPDIR)/libcurl_la-bearssl.Tpo -c -o vtls/libcurl_la-bearssl.lo `test -f 'vtls/bearssl.c' || echo '$(srcdir)/'`vtls/bearssl.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurl_la-bearssl.Tpo vtls/$(DEPDIR)/libcurl_la-bearssl.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/bearssl.c' object='vtls/libcurl_la-bearssl.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurl_la-bearssl.lo `test -f 'vtls/bearssl.c' || echo '$(srcdir)/'`vtls/bearssl.c + +vtls/libcurl_la-cipher_suite.lo: vtls/cipher_suite.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vtls/libcurl_la-cipher_suite.lo -MD -MP -MF vtls/$(DEPDIR)/libcurl_la-cipher_suite.Tpo -c -o vtls/libcurl_la-cipher_suite.lo `test -f 'vtls/cipher_suite.c' || echo '$(srcdir)/'`vtls/cipher_suite.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurl_la-cipher_suite.Tpo vtls/$(DEPDIR)/libcurl_la-cipher_suite.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/cipher_suite.c' object='vtls/libcurl_la-cipher_suite.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurl_la-cipher_suite.lo `test -f 'vtls/cipher_suite.c' || echo '$(srcdir)/'`vtls/cipher_suite.c + +vtls/libcurl_la-gtls.lo: vtls/gtls.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vtls/libcurl_la-gtls.lo -MD -MP -MF vtls/$(DEPDIR)/libcurl_la-gtls.Tpo -c -o vtls/libcurl_la-gtls.lo `test -f 'vtls/gtls.c' || echo '$(srcdir)/'`vtls/gtls.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurl_la-gtls.Tpo vtls/$(DEPDIR)/libcurl_la-gtls.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/gtls.c' object='vtls/libcurl_la-gtls.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurl_la-gtls.lo `test -f 'vtls/gtls.c' || echo '$(srcdir)/'`vtls/gtls.c + +vtls/libcurl_la-hostcheck.lo: vtls/hostcheck.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vtls/libcurl_la-hostcheck.lo -MD -MP -MF vtls/$(DEPDIR)/libcurl_la-hostcheck.Tpo -c -o vtls/libcurl_la-hostcheck.lo `test -f 'vtls/hostcheck.c' || echo '$(srcdir)/'`vtls/hostcheck.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurl_la-hostcheck.Tpo vtls/$(DEPDIR)/libcurl_la-hostcheck.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/hostcheck.c' object='vtls/libcurl_la-hostcheck.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurl_la-hostcheck.lo `test -f 'vtls/hostcheck.c' || echo '$(srcdir)/'`vtls/hostcheck.c + +vtls/libcurl_la-keylog.lo: vtls/keylog.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vtls/libcurl_la-keylog.lo -MD -MP -MF vtls/$(DEPDIR)/libcurl_la-keylog.Tpo -c -o vtls/libcurl_la-keylog.lo `test -f 'vtls/keylog.c' || echo '$(srcdir)/'`vtls/keylog.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurl_la-keylog.Tpo vtls/$(DEPDIR)/libcurl_la-keylog.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/keylog.c' object='vtls/libcurl_la-keylog.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurl_la-keylog.lo `test -f 'vtls/keylog.c' || echo '$(srcdir)/'`vtls/keylog.c + +vtls/libcurl_la-mbedtls.lo: vtls/mbedtls.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vtls/libcurl_la-mbedtls.lo -MD -MP -MF vtls/$(DEPDIR)/libcurl_la-mbedtls.Tpo -c -o vtls/libcurl_la-mbedtls.lo `test -f 'vtls/mbedtls.c' || echo '$(srcdir)/'`vtls/mbedtls.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurl_la-mbedtls.Tpo vtls/$(DEPDIR)/libcurl_la-mbedtls.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/mbedtls.c' object='vtls/libcurl_la-mbedtls.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurl_la-mbedtls.lo `test -f 'vtls/mbedtls.c' || echo '$(srcdir)/'`vtls/mbedtls.c + +vtls/libcurl_la-mbedtls_threadlock.lo: vtls/mbedtls_threadlock.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vtls/libcurl_la-mbedtls_threadlock.lo -MD -MP -MF vtls/$(DEPDIR)/libcurl_la-mbedtls_threadlock.Tpo -c -o vtls/libcurl_la-mbedtls_threadlock.lo `test -f 'vtls/mbedtls_threadlock.c' || echo '$(srcdir)/'`vtls/mbedtls_threadlock.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurl_la-mbedtls_threadlock.Tpo vtls/$(DEPDIR)/libcurl_la-mbedtls_threadlock.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/mbedtls_threadlock.c' object='vtls/libcurl_la-mbedtls_threadlock.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurl_la-mbedtls_threadlock.lo `test -f 'vtls/mbedtls_threadlock.c' || echo '$(srcdir)/'`vtls/mbedtls_threadlock.c + +vtls/libcurl_la-openssl.lo: vtls/openssl.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vtls/libcurl_la-openssl.lo -MD -MP -MF vtls/$(DEPDIR)/libcurl_la-openssl.Tpo -c -o vtls/libcurl_la-openssl.lo `test -f 'vtls/openssl.c' || echo '$(srcdir)/'`vtls/openssl.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurl_la-openssl.Tpo vtls/$(DEPDIR)/libcurl_la-openssl.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/openssl.c' object='vtls/libcurl_la-openssl.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurl_la-openssl.lo `test -f 'vtls/openssl.c' || echo '$(srcdir)/'`vtls/openssl.c + +vtls/libcurl_la-rustls.lo: vtls/rustls.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vtls/libcurl_la-rustls.lo -MD -MP -MF vtls/$(DEPDIR)/libcurl_la-rustls.Tpo -c -o vtls/libcurl_la-rustls.lo `test -f 'vtls/rustls.c' || echo '$(srcdir)/'`vtls/rustls.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurl_la-rustls.Tpo vtls/$(DEPDIR)/libcurl_la-rustls.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/rustls.c' object='vtls/libcurl_la-rustls.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurl_la-rustls.lo `test -f 'vtls/rustls.c' || echo '$(srcdir)/'`vtls/rustls.c + +vtls/libcurl_la-schannel.lo: vtls/schannel.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vtls/libcurl_la-schannel.lo -MD -MP -MF vtls/$(DEPDIR)/libcurl_la-schannel.Tpo -c -o vtls/libcurl_la-schannel.lo `test -f 'vtls/schannel.c' || echo '$(srcdir)/'`vtls/schannel.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurl_la-schannel.Tpo vtls/$(DEPDIR)/libcurl_la-schannel.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/schannel.c' object='vtls/libcurl_la-schannel.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurl_la-schannel.lo `test -f 'vtls/schannel.c' || echo '$(srcdir)/'`vtls/schannel.c + +vtls/libcurl_la-schannel_verify.lo: vtls/schannel_verify.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vtls/libcurl_la-schannel_verify.lo -MD -MP -MF vtls/$(DEPDIR)/libcurl_la-schannel_verify.Tpo -c -o vtls/libcurl_la-schannel_verify.lo `test -f 'vtls/schannel_verify.c' || echo '$(srcdir)/'`vtls/schannel_verify.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurl_la-schannel_verify.Tpo vtls/$(DEPDIR)/libcurl_la-schannel_verify.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/schannel_verify.c' object='vtls/libcurl_la-schannel_verify.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurl_la-schannel_verify.lo `test -f 'vtls/schannel_verify.c' || echo '$(srcdir)/'`vtls/schannel_verify.c + +vtls/libcurl_la-sectransp.lo: vtls/sectransp.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vtls/libcurl_la-sectransp.lo -MD -MP -MF vtls/$(DEPDIR)/libcurl_la-sectransp.Tpo -c -o vtls/libcurl_la-sectransp.lo `test -f 'vtls/sectransp.c' || echo '$(srcdir)/'`vtls/sectransp.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurl_la-sectransp.Tpo vtls/$(DEPDIR)/libcurl_la-sectransp.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/sectransp.c' object='vtls/libcurl_la-sectransp.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurl_la-sectransp.lo `test -f 'vtls/sectransp.c' || echo '$(srcdir)/'`vtls/sectransp.c + +vtls/libcurl_la-vtls.lo: vtls/vtls.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vtls/libcurl_la-vtls.lo -MD -MP -MF vtls/$(DEPDIR)/libcurl_la-vtls.Tpo -c -o vtls/libcurl_la-vtls.lo `test -f 'vtls/vtls.c' || echo '$(srcdir)/'`vtls/vtls.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurl_la-vtls.Tpo vtls/$(DEPDIR)/libcurl_la-vtls.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/vtls.c' object='vtls/libcurl_la-vtls.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurl_la-vtls.lo `test -f 'vtls/vtls.c' || echo '$(srcdir)/'`vtls/vtls.c + +vtls/libcurl_la-wolfssl.lo: vtls/wolfssl.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vtls/libcurl_la-wolfssl.lo -MD -MP -MF vtls/$(DEPDIR)/libcurl_la-wolfssl.Tpo -c -o vtls/libcurl_la-wolfssl.lo `test -f 'vtls/wolfssl.c' || echo '$(srcdir)/'`vtls/wolfssl.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurl_la-wolfssl.Tpo vtls/$(DEPDIR)/libcurl_la-wolfssl.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/wolfssl.c' object='vtls/libcurl_la-wolfssl.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurl_la-wolfssl.lo `test -f 'vtls/wolfssl.c' || echo '$(srcdir)/'`vtls/wolfssl.c + +vtls/libcurl_la-x509asn1.lo: vtls/x509asn1.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vtls/libcurl_la-x509asn1.lo -MD -MP -MF vtls/$(DEPDIR)/libcurl_la-x509asn1.Tpo -c -o vtls/libcurl_la-x509asn1.lo `test -f 'vtls/x509asn1.c' || echo '$(srcdir)/'`vtls/x509asn1.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurl_la-x509asn1.Tpo vtls/$(DEPDIR)/libcurl_la-x509asn1.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/x509asn1.c' object='vtls/libcurl_la-x509asn1.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurl_la-x509asn1.lo `test -f 'vtls/x509asn1.c' || echo '$(srcdir)/'`vtls/x509asn1.c + +vquic/libcurl_la-curl_msh3.lo: vquic/curl_msh3.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vquic/libcurl_la-curl_msh3.lo -MD -MP -MF vquic/$(DEPDIR)/libcurl_la-curl_msh3.Tpo -c -o vquic/libcurl_la-curl_msh3.lo `test -f 'vquic/curl_msh3.c' || echo '$(srcdir)/'`vquic/curl_msh3.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vquic/$(DEPDIR)/libcurl_la-curl_msh3.Tpo vquic/$(DEPDIR)/libcurl_la-curl_msh3.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vquic/curl_msh3.c' object='vquic/libcurl_la-curl_msh3.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vquic/libcurl_la-curl_msh3.lo `test -f 'vquic/curl_msh3.c' || echo '$(srcdir)/'`vquic/curl_msh3.c + +vquic/libcurl_la-curl_ngtcp2.lo: vquic/curl_ngtcp2.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vquic/libcurl_la-curl_ngtcp2.lo -MD -MP -MF vquic/$(DEPDIR)/libcurl_la-curl_ngtcp2.Tpo -c -o vquic/libcurl_la-curl_ngtcp2.lo `test -f 'vquic/curl_ngtcp2.c' || echo '$(srcdir)/'`vquic/curl_ngtcp2.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vquic/$(DEPDIR)/libcurl_la-curl_ngtcp2.Tpo vquic/$(DEPDIR)/libcurl_la-curl_ngtcp2.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vquic/curl_ngtcp2.c' object='vquic/libcurl_la-curl_ngtcp2.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vquic/libcurl_la-curl_ngtcp2.lo `test -f 'vquic/curl_ngtcp2.c' || echo '$(srcdir)/'`vquic/curl_ngtcp2.c + +vquic/libcurl_la-curl_osslq.lo: vquic/curl_osslq.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vquic/libcurl_la-curl_osslq.lo -MD -MP -MF vquic/$(DEPDIR)/libcurl_la-curl_osslq.Tpo -c -o vquic/libcurl_la-curl_osslq.lo `test -f 'vquic/curl_osslq.c' || echo '$(srcdir)/'`vquic/curl_osslq.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vquic/$(DEPDIR)/libcurl_la-curl_osslq.Tpo vquic/$(DEPDIR)/libcurl_la-curl_osslq.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vquic/curl_osslq.c' object='vquic/libcurl_la-curl_osslq.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vquic/libcurl_la-curl_osslq.lo `test -f 'vquic/curl_osslq.c' || echo '$(srcdir)/'`vquic/curl_osslq.c + +vquic/libcurl_la-curl_quiche.lo: vquic/curl_quiche.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vquic/libcurl_la-curl_quiche.lo -MD -MP -MF vquic/$(DEPDIR)/libcurl_la-curl_quiche.Tpo -c -o vquic/libcurl_la-curl_quiche.lo `test -f 'vquic/curl_quiche.c' || echo '$(srcdir)/'`vquic/curl_quiche.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vquic/$(DEPDIR)/libcurl_la-curl_quiche.Tpo vquic/$(DEPDIR)/libcurl_la-curl_quiche.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vquic/curl_quiche.c' object='vquic/libcurl_la-curl_quiche.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vquic/libcurl_la-curl_quiche.lo `test -f 'vquic/curl_quiche.c' || echo '$(srcdir)/'`vquic/curl_quiche.c + +vquic/libcurl_la-vquic.lo: vquic/vquic.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vquic/libcurl_la-vquic.lo -MD -MP -MF vquic/$(DEPDIR)/libcurl_la-vquic.Tpo -c -o vquic/libcurl_la-vquic.lo `test -f 'vquic/vquic.c' || echo '$(srcdir)/'`vquic/vquic.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vquic/$(DEPDIR)/libcurl_la-vquic.Tpo vquic/$(DEPDIR)/libcurl_la-vquic.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vquic/vquic.c' object='vquic/libcurl_la-vquic.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vquic/libcurl_la-vquic.lo `test -f 'vquic/vquic.c' || echo '$(srcdir)/'`vquic/vquic.c + +vquic/libcurl_la-vquic-tls.lo: vquic/vquic-tls.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vquic/libcurl_la-vquic-tls.lo -MD -MP -MF vquic/$(DEPDIR)/libcurl_la-vquic-tls.Tpo -c -o vquic/libcurl_la-vquic-tls.lo `test -f 'vquic/vquic-tls.c' || echo '$(srcdir)/'`vquic/vquic-tls.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vquic/$(DEPDIR)/libcurl_la-vquic-tls.Tpo vquic/$(DEPDIR)/libcurl_la-vquic-tls.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vquic/vquic-tls.c' object='vquic/libcurl_la-vquic-tls.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vquic/libcurl_la-vquic-tls.lo `test -f 'vquic/vquic-tls.c' || echo '$(srcdir)/'`vquic/vquic-tls.c + +vssh/libcurl_la-libssh.lo: vssh/libssh.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vssh/libcurl_la-libssh.lo -MD -MP -MF vssh/$(DEPDIR)/libcurl_la-libssh.Tpo -c -o vssh/libcurl_la-libssh.lo `test -f 'vssh/libssh.c' || echo '$(srcdir)/'`vssh/libssh.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vssh/$(DEPDIR)/libcurl_la-libssh.Tpo vssh/$(DEPDIR)/libcurl_la-libssh.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vssh/libssh.c' object='vssh/libcurl_la-libssh.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vssh/libcurl_la-libssh.lo `test -f 'vssh/libssh.c' || echo '$(srcdir)/'`vssh/libssh.c + +vssh/libcurl_la-libssh2.lo: vssh/libssh2.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vssh/libcurl_la-libssh2.lo -MD -MP -MF vssh/$(DEPDIR)/libcurl_la-libssh2.Tpo -c -o vssh/libcurl_la-libssh2.lo `test -f 'vssh/libssh2.c' || echo '$(srcdir)/'`vssh/libssh2.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vssh/$(DEPDIR)/libcurl_la-libssh2.Tpo vssh/$(DEPDIR)/libcurl_la-libssh2.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vssh/libssh2.c' object='vssh/libcurl_la-libssh2.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vssh/libcurl_la-libssh2.lo `test -f 'vssh/libssh2.c' || echo '$(srcdir)/'`vssh/libssh2.c + +vssh/libcurl_la-wolfssh.lo: vssh/wolfssh.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -MT vssh/libcurl_la-wolfssh.lo -MD -MP -MF vssh/$(DEPDIR)/libcurl_la-wolfssh.Tpo -c -o vssh/libcurl_la-wolfssh.lo `test -f 'vssh/wolfssh.c' || echo '$(srcdir)/'`vssh/wolfssh.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vssh/$(DEPDIR)/libcurl_la-wolfssh.Tpo vssh/$(DEPDIR)/libcurl_la-wolfssh.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vssh/wolfssh.c' object='vssh/libcurl_la-wolfssh.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurl_la_CPPFLAGS) $(CPPFLAGS) $(libcurl_la_CFLAGS) $(CFLAGS) -c -o vssh/libcurl_la-wolfssh.lo `test -f 'vssh/wolfssh.c' || echo '$(srcdir)/'`vssh/wolfssh.c + +libcurlu_la-altsvc.lo: altsvc.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-altsvc.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-altsvc.Tpo -c -o libcurlu_la-altsvc.lo `test -f 'altsvc.c' || echo '$(srcdir)/'`altsvc.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-altsvc.Tpo $(DEPDIR)/libcurlu_la-altsvc.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='altsvc.c' object='libcurlu_la-altsvc.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-altsvc.lo `test -f 'altsvc.c' || echo '$(srcdir)/'`altsvc.c + +libcurlu_la-amigaos.lo: amigaos.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-amigaos.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-amigaos.Tpo -c -o libcurlu_la-amigaos.lo `test -f 'amigaos.c' || echo '$(srcdir)/'`amigaos.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-amigaos.Tpo $(DEPDIR)/libcurlu_la-amigaos.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='amigaos.c' object='libcurlu_la-amigaos.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-amigaos.lo `test -f 'amigaos.c' || echo '$(srcdir)/'`amigaos.c + +libcurlu_la-asyn-ares.lo: asyn-ares.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-asyn-ares.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-asyn-ares.Tpo -c -o libcurlu_la-asyn-ares.lo `test -f 'asyn-ares.c' || echo '$(srcdir)/'`asyn-ares.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-asyn-ares.Tpo $(DEPDIR)/libcurlu_la-asyn-ares.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='asyn-ares.c' object='libcurlu_la-asyn-ares.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-asyn-ares.lo `test -f 'asyn-ares.c' || echo '$(srcdir)/'`asyn-ares.c + +libcurlu_la-asyn-thread.lo: asyn-thread.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-asyn-thread.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-asyn-thread.Tpo -c -o libcurlu_la-asyn-thread.lo `test -f 'asyn-thread.c' || echo '$(srcdir)/'`asyn-thread.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-asyn-thread.Tpo $(DEPDIR)/libcurlu_la-asyn-thread.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='asyn-thread.c' object='libcurlu_la-asyn-thread.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-asyn-thread.lo `test -f 'asyn-thread.c' || echo '$(srcdir)/'`asyn-thread.c + +libcurlu_la-base64.lo: base64.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-base64.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-base64.Tpo -c -o libcurlu_la-base64.lo `test -f 'base64.c' || echo '$(srcdir)/'`base64.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-base64.Tpo $(DEPDIR)/libcurlu_la-base64.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='base64.c' object='libcurlu_la-base64.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-base64.lo `test -f 'base64.c' || echo '$(srcdir)/'`base64.c + +libcurlu_la-bufq.lo: bufq.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-bufq.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-bufq.Tpo -c -o libcurlu_la-bufq.lo `test -f 'bufq.c' || echo '$(srcdir)/'`bufq.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-bufq.Tpo $(DEPDIR)/libcurlu_la-bufq.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='bufq.c' object='libcurlu_la-bufq.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-bufq.lo `test -f 'bufq.c' || echo '$(srcdir)/'`bufq.c + +libcurlu_la-bufref.lo: bufref.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-bufref.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-bufref.Tpo -c -o libcurlu_la-bufref.lo `test -f 'bufref.c' || echo '$(srcdir)/'`bufref.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-bufref.Tpo $(DEPDIR)/libcurlu_la-bufref.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='bufref.c' object='libcurlu_la-bufref.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-bufref.lo `test -f 'bufref.c' || echo '$(srcdir)/'`bufref.c + +libcurlu_la-c-hyper.lo: c-hyper.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-c-hyper.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-c-hyper.Tpo -c -o libcurlu_la-c-hyper.lo `test -f 'c-hyper.c' || echo '$(srcdir)/'`c-hyper.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-c-hyper.Tpo $(DEPDIR)/libcurlu_la-c-hyper.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='c-hyper.c' object='libcurlu_la-c-hyper.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-c-hyper.lo `test -f 'c-hyper.c' || echo '$(srcdir)/'`c-hyper.c + +libcurlu_la-cf-h1-proxy.lo: cf-h1-proxy.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-cf-h1-proxy.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-cf-h1-proxy.Tpo -c -o libcurlu_la-cf-h1-proxy.lo `test -f 'cf-h1-proxy.c' || echo '$(srcdir)/'`cf-h1-proxy.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-cf-h1-proxy.Tpo $(DEPDIR)/libcurlu_la-cf-h1-proxy.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cf-h1-proxy.c' object='libcurlu_la-cf-h1-proxy.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-cf-h1-proxy.lo `test -f 'cf-h1-proxy.c' || echo '$(srcdir)/'`cf-h1-proxy.c + +libcurlu_la-cf-h2-proxy.lo: cf-h2-proxy.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-cf-h2-proxy.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-cf-h2-proxy.Tpo -c -o libcurlu_la-cf-h2-proxy.lo `test -f 'cf-h2-proxy.c' || echo '$(srcdir)/'`cf-h2-proxy.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-cf-h2-proxy.Tpo $(DEPDIR)/libcurlu_la-cf-h2-proxy.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cf-h2-proxy.c' object='libcurlu_la-cf-h2-proxy.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-cf-h2-proxy.lo `test -f 'cf-h2-proxy.c' || echo '$(srcdir)/'`cf-h2-proxy.c + +libcurlu_la-cf-haproxy.lo: cf-haproxy.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-cf-haproxy.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-cf-haproxy.Tpo -c -o libcurlu_la-cf-haproxy.lo `test -f 'cf-haproxy.c' || echo '$(srcdir)/'`cf-haproxy.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-cf-haproxy.Tpo $(DEPDIR)/libcurlu_la-cf-haproxy.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cf-haproxy.c' object='libcurlu_la-cf-haproxy.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-cf-haproxy.lo `test -f 'cf-haproxy.c' || echo '$(srcdir)/'`cf-haproxy.c + +libcurlu_la-cf-https-connect.lo: cf-https-connect.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-cf-https-connect.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-cf-https-connect.Tpo -c -o libcurlu_la-cf-https-connect.lo `test -f 'cf-https-connect.c' || echo '$(srcdir)/'`cf-https-connect.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-cf-https-connect.Tpo $(DEPDIR)/libcurlu_la-cf-https-connect.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cf-https-connect.c' object='libcurlu_la-cf-https-connect.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-cf-https-connect.lo `test -f 'cf-https-connect.c' || echo '$(srcdir)/'`cf-https-connect.c + +libcurlu_la-cf-socket.lo: cf-socket.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-cf-socket.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-cf-socket.Tpo -c -o libcurlu_la-cf-socket.lo `test -f 'cf-socket.c' || echo '$(srcdir)/'`cf-socket.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-cf-socket.Tpo $(DEPDIR)/libcurlu_la-cf-socket.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cf-socket.c' object='libcurlu_la-cf-socket.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-cf-socket.lo `test -f 'cf-socket.c' || echo '$(srcdir)/'`cf-socket.c + +libcurlu_la-cfilters.lo: cfilters.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-cfilters.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-cfilters.Tpo -c -o libcurlu_la-cfilters.lo `test -f 'cfilters.c' || echo '$(srcdir)/'`cfilters.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-cfilters.Tpo $(DEPDIR)/libcurlu_la-cfilters.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cfilters.c' object='libcurlu_la-cfilters.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-cfilters.lo `test -f 'cfilters.c' || echo '$(srcdir)/'`cfilters.c + +libcurlu_la-conncache.lo: conncache.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-conncache.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-conncache.Tpo -c -o libcurlu_la-conncache.lo `test -f 'conncache.c' || echo '$(srcdir)/'`conncache.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-conncache.Tpo $(DEPDIR)/libcurlu_la-conncache.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='conncache.c' object='libcurlu_la-conncache.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-conncache.lo `test -f 'conncache.c' || echo '$(srcdir)/'`conncache.c + +libcurlu_la-connect.lo: connect.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-connect.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-connect.Tpo -c -o libcurlu_la-connect.lo `test -f 'connect.c' || echo '$(srcdir)/'`connect.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-connect.Tpo $(DEPDIR)/libcurlu_la-connect.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='connect.c' object='libcurlu_la-connect.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-connect.lo `test -f 'connect.c' || echo '$(srcdir)/'`connect.c + +libcurlu_la-content_encoding.lo: content_encoding.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-content_encoding.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-content_encoding.Tpo -c -o libcurlu_la-content_encoding.lo `test -f 'content_encoding.c' || echo '$(srcdir)/'`content_encoding.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-content_encoding.Tpo $(DEPDIR)/libcurlu_la-content_encoding.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='content_encoding.c' object='libcurlu_la-content_encoding.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-content_encoding.lo `test -f 'content_encoding.c' || echo '$(srcdir)/'`content_encoding.c + +libcurlu_la-cookie.lo: cookie.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-cookie.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-cookie.Tpo -c -o libcurlu_la-cookie.lo `test -f 'cookie.c' || echo '$(srcdir)/'`cookie.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-cookie.Tpo $(DEPDIR)/libcurlu_la-cookie.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cookie.c' object='libcurlu_la-cookie.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-cookie.lo `test -f 'cookie.c' || echo '$(srcdir)/'`cookie.c + +libcurlu_la-curl_addrinfo.lo: curl_addrinfo.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_addrinfo.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_addrinfo.Tpo -c -o libcurlu_la-curl_addrinfo.lo `test -f 'curl_addrinfo.c' || echo '$(srcdir)/'`curl_addrinfo.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_addrinfo.Tpo $(DEPDIR)/libcurlu_la-curl_addrinfo.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_addrinfo.c' object='libcurlu_la-curl_addrinfo.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_addrinfo.lo `test -f 'curl_addrinfo.c' || echo '$(srcdir)/'`curl_addrinfo.c + +libcurlu_la-curl_des.lo: curl_des.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_des.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_des.Tpo -c -o libcurlu_la-curl_des.lo `test -f 'curl_des.c' || echo '$(srcdir)/'`curl_des.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_des.Tpo $(DEPDIR)/libcurlu_la-curl_des.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_des.c' object='libcurlu_la-curl_des.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_des.lo `test -f 'curl_des.c' || echo '$(srcdir)/'`curl_des.c + +libcurlu_la-curl_endian.lo: curl_endian.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_endian.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_endian.Tpo -c -o libcurlu_la-curl_endian.lo `test -f 'curl_endian.c' || echo '$(srcdir)/'`curl_endian.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_endian.Tpo $(DEPDIR)/libcurlu_la-curl_endian.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_endian.c' object='libcurlu_la-curl_endian.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_endian.lo `test -f 'curl_endian.c' || echo '$(srcdir)/'`curl_endian.c + +libcurlu_la-curl_fnmatch.lo: curl_fnmatch.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_fnmatch.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_fnmatch.Tpo -c -o libcurlu_la-curl_fnmatch.lo `test -f 'curl_fnmatch.c' || echo '$(srcdir)/'`curl_fnmatch.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_fnmatch.Tpo $(DEPDIR)/libcurlu_la-curl_fnmatch.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_fnmatch.c' object='libcurlu_la-curl_fnmatch.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_fnmatch.lo `test -f 'curl_fnmatch.c' || echo '$(srcdir)/'`curl_fnmatch.c + +libcurlu_la-curl_get_line.lo: curl_get_line.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_get_line.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_get_line.Tpo -c -o libcurlu_la-curl_get_line.lo `test -f 'curl_get_line.c' || echo '$(srcdir)/'`curl_get_line.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_get_line.Tpo $(DEPDIR)/libcurlu_la-curl_get_line.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_get_line.c' object='libcurlu_la-curl_get_line.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_get_line.lo `test -f 'curl_get_line.c' || echo '$(srcdir)/'`curl_get_line.c + +libcurlu_la-curl_gethostname.lo: curl_gethostname.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_gethostname.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_gethostname.Tpo -c -o libcurlu_la-curl_gethostname.lo `test -f 'curl_gethostname.c' || echo '$(srcdir)/'`curl_gethostname.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_gethostname.Tpo $(DEPDIR)/libcurlu_la-curl_gethostname.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_gethostname.c' object='libcurlu_la-curl_gethostname.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_gethostname.lo `test -f 'curl_gethostname.c' || echo '$(srcdir)/'`curl_gethostname.c + +libcurlu_la-curl_gssapi.lo: curl_gssapi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_gssapi.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_gssapi.Tpo -c -o libcurlu_la-curl_gssapi.lo `test -f 'curl_gssapi.c' || echo '$(srcdir)/'`curl_gssapi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_gssapi.Tpo $(DEPDIR)/libcurlu_la-curl_gssapi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_gssapi.c' object='libcurlu_la-curl_gssapi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_gssapi.lo `test -f 'curl_gssapi.c' || echo '$(srcdir)/'`curl_gssapi.c + +libcurlu_la-curl_memrchr.lo: curl_memrchr.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_memrchr.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_memrchr.Tpo -c -o libcurlu_la-curl_memrchr.lo `test -f 'curl_memrchr.c' || echo '$(srcdir)/'`curl_memrchr.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_memrchr.Tpo $(DEPDIR)/libcurlu_la-curl_memrchr.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_memrchr.c' object='libcurlu_la-curl_memrchr.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_memrchr.lo `test -f 'curl_memrchr.c' || echo '$(srcdir)/'`curl_memrchr.c + +libcurlu_la-curl_multibyte.lo: curl_multibyte.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_multibyte.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_multibyte.Tpo -c -o libcurlu_la-curl_multibyte.lo `test -f 'curl_multibyte.c' || echo '$(srcdir)/'`curl_multibyte.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_multibyte.Tpo $(DEPDIR)/libcurlu_la-curl_multibyte.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_multibyte.c' object='libcurlu_la-curl_multibyte.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_multibyte.lo `test -f 'curl_multibyte.c' || echo '$(srcdir)/'`curl_multibyte.c + +libcurlu_la-curl_ntlm_core.lo: curl_ntlm_core.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_ntlm_core.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_ntlm_core.Tpo -c -o libcurlu_la-curl_ntlm_core.lo `test -f 'curl_ntlm_core.c' || echo '$(srcdir)/'`curl_ntlm_core.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_ntlm_core.Tpo $(DEPDIR)/libcurlu_la-curl_ntlm_core.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_ntlm_core.c' object='libcurlu_la-curl_ntlm_core.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_ntlm_core.lo `test -f 'curl_ntlm_core.c' || echo '$(srcdir)/'`curl_ntlm_core.c + +libcurlu_la-curl_path.lo: curl_path.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_path.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_path.Tpo -c -o libcurlu_la-curl_path.lo `test -f 'curl_path.c' || echo '$(srcdir)/'`curl_path.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_path.Tpo $(DEPDIR)/libcurlu_la-curl_path.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_path.c' object='libcurlu_la-curl_path.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_path.lo `test -f 'curl_path.c' || echo '$(srcdir)/'`curl_path.c + +libcurlu_la-curl_range.lo: curl_range.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_range.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_range.Tpo -c -o libcurlu_la-curl_range.lo `test -f 'curl_range.c' || echo '$(srcdir)/'`curl_range.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_range.Tpo $(DEPDIR)/libcurlu_la-curl_range.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_range.c' object='libcurlu_la-curl_range.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_range.lo `test -f 'curl_range.c' || echo '$(srcdir)/'`curl_range.c + +libcurlu_la-curl_rtmp.lo: curl_rtmp.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_rtmp.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_rtmp.Tpo -c -o libcurlu_la-curl_rtmp.lo `test -f 'curl_rtmp.c' || echo '$(srcdir)/'`curl_rtmp.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_rtmp.Tpo $(DEPDIR)/libcurlu_la-curl_rtmp.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_rtmp.c' object='libcurlu_la-curl_rtmp.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_rtmp.lo `test -f 'curl_rtmp.c' || echo '$(srcdir)/'`curl_rtmp.c + +libcurlu_la-curl_sasl.lo: curl_sasl.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_sasl.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_sasl.Tpo -c -o libcurlu_la-curl_sasl.lo `test -f 'curl_sasl.c' || echo '$(srcdir)/'`curl_sasl.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_sasl.Tpo $(DEPDIR)/libcurlu_la-curl_sasl.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_sasl.c' object='libcurlu_la-curl_sasl.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_sasl.lo `test -f 'curl_sasl.c' || echo '$(srcdir)/'`curl_sasl.c + +libcurlu_la-curl_sha512_256.lo: curl_sha512_256.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_sha512_256.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_sha512_256.Tpo -c -o libcurlu_la-curl_sha512_256.lo `test -f 'curl_sha512_256.c' || echo '$(srcdir)/'`curl_sha512_256.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_sha512_256.Tpo $(DEPDIR)/libcurlu_la-curl_sha512_256.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_sha512_256.c' object='libcurlu_la-curl_sha512_256.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_sha512_256.lo `test -f 'curl_sha512_256.c' || echo '$(srcdir)/'`curl_sha512_256.c + +libcurlu_la-curl_sspi.lo: curl_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_sspi.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_sspi.Tpo -c -o libcurlu_la-curl_sspi.lo `test -f 'curl_sspi.c' || echo '$(srcdir)/'`curl_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_sspi.Tpo $(DEPDIR)/libcurlu_la-curl_sspi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_sspi.c' object='libcurlu_la-curl_sspi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_sspi.lo `test -f 'curl_sspi.c' || echo '$(srcdir)/'`curl_sspi.c + +libcurlu_la-curl_threads.lo: curl_threads.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_threads.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_threads.Tpo -c -o libcurlu_la-curl_threads.lo `test -f 'curl_threads.c' || echo '$(srcdir)/'`curl_threads.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_threads.Tpo $(DEPDIR)/libcurlu_la-curl_threads.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_threads.c' object='libcurlu_la-curl_threads.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_threads.lo `test -f 'curl_threads.c' || echo '$(srcdir)/'`curl_threads.c + +libcurlu_la-curl_trc.lo: curl_trc.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-curl_trc.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-curl_trc.Tpo -c -o libcurlu_la-curl_trc.lo `test -f 'curl_trc.c' || echo '$(srcdir)/'`curl_trc.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-curl_trc.Tpo $(DEPDIR)/libcurlu_la-curl_trc.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='curl_trc.c' object='libcurlu_la-curl_trc.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-curl_trc.lo `test -f 'curl_trc.c' || echo '$(srcdir)/'`curl_trc.c + +libcurlu_la-cw-out.lo: cw-out.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-cw-out.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-cw-out.Tpo -c -o libcurlu_la-cw-out.lo `test -f 'cw-out.c' || echo '$(srcdir)/'`cw-out.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-cw-out.Tpo $(DEPDIR)/libcurlu_la-cw-out.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cw-out.c' object='libcurlu_la-cw-out.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-cw-out.lo `test -f 'cw-out.c' || echo '$(srcdir)/'`cw-out.c + +libcurlu_la-dict.lo: dict.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-dict.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-dict.Tpo -c -o libcurlu_la-dict.lo `test -f 'dict.c' || echo '$(srcdir)/'`dict.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-dict.Tpo $(DEPDIR)/libcurlu_la-dict.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='dict.c' object='libcurlu_la-dict.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-dict.lo `test -f 'dict.c' || echo '$(srcdir)/'`dict.c + +libcurlu_la-dllmain.lo: dllmain.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-dllmain.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-dllmain.Tpo -c -o libcurlu_la-dllmain.lo `test -f 'dllmain.c' || echo '$(srcdir)/'`dllmain.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-dllmain.Tpo $(DEPDIR)/libcurlu_la-dllmain.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='dllmain.c' object='libcurlu_la-dllmain.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-dllmain.lo `test -f 'dllmain.c' || echo '$(srcdir)/'`dllmain.c + +libcurlu_la-doh.lo: doh.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-doh.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-doh.Tpo -c -o libcurlu_la-doh.lo `test -f 'doh.c' || echo '$(srcdir)/'`doh.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-doh.Tpo $(DEPDIR)/libcurlu_la-doh.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='doh.c' object='libcurlu_la-doh.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-doh.lo `test -f 'doh.c' || echo '$(srcdir)/'`doh.c + +libcurlu_la-dynbuf.lo: dynbuf.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-dynbuf.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-dynbuf.Tpo -c -o libcurlu_la-dynbuf.lo `test -f 'dynbuf.c' || echo '$(srcdir)/'`dynbuf.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-dynbuf.Tpo $(DEPDIR)/libcurlu_la-dynbuf.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='dynbuf.c' object='libcurlu_la-dynbuf.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-dynbuf.lo `test -f 'dynbuf.c' || echo '$(srcdir)/'`dynbuf.c + +libcurlu_la-dynhds.lo: dynhds.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-dynhds.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-dynhds.Tpo -c -o libcurlu_la-dynhds.lo `test -f 'dynhds.c' || echo '$(srcdir)/'`dynhds.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-dynhds.Tpo $(DEPDIR)/libcurlu_la-dynhds.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='dynhds.c' object='libcurlu_la-dynhds.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-dynhds.lo `test -f 'dynhds.c' || echo '$(srcdir)/'`dynhds.c + +libcurlu_la-easy.lo: easy.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-easy.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-easy.Tpo -c -o libcurlu_la-easy.lo `test -f 'easy.c' || echo '$(srcdir)/'`easy.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-easy.Tpo $(DEPDIR)/libcurlu_la-easy.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='easy.c' object='libcurlu_la-easy.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-easy.lo `test -f 'easy.c' || echo '$(srcdir)/'`easy.c + +libcurlu_la-easygetopt.lo: easygetopt.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-easygetopt.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-easygetopt.Tpo -c -o libcurlu_la-easygetopt.lo `test -f 'easygetopt.c' || echo '$(srcdir)/'`easygetopt.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-easygetopt.Tpo $(DEPDIR)/libcurlu_la-easygetopt.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='easygetopt.c' object='libcurlu_la-easygetopt.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-easygetopt.lo `test -f 'easygetopt.c' || echo '$(srcdir)/'`easygetopt.c + +libcurlu_la-easyoptions.lo: easyoptions.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-easyoptions.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-easyoptions.Tpo -c -o libcurlu_la-easyoptions.lo `test -f 'easyoptions.c' || echo '$(srcdir)/'`easyoptions.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-easyoptions.Tpo $(DEPDIR)/libcurlu_la-easyoptions.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='easyoptions.c' object='libcurlu_la-easyoptions.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-easyoptions.lo `test -f 'easyoptions.c' || echo '$(srcdir)/'`easyoptions.c + +libcurlu_la-escape.lo: escape.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-escape.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-escape.Tpo -c -o libcurlu_la-escape.lo `test -f 'escape.c' || echo '$(srcdir)/'`escape.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-escape.Tpo $(DEPDIR)/libcurlu_la-escape.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='escape.c' object='libcurlu_la-escape.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-escape.lo `test -f 'escape.c' || echo '$(srcdir)/'`escape.c + +libcurlu_la-file.lo: file.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-file.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-file.Tpo -c -o libcurlu_la-file.lo `test -f 'file.c' || echo '$(srcdir)/'`file.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-file.Tpo $(DEPDIR)/libcurlu_la-file.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='file.c' object='libcurlu_la-file.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-file.lo `test -f 'file.c' || echo '$(srcdir)/'`file.c + +libcurlu_la-fileinfo.lo: fileinfo.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-fileinfo.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-fileinfo.Tpo -c -o libcurlu_la-fileinfo.lo `test -f 'fileinfo.c' || echo '$(srcdir)/'`fileinfo.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-fileinfo.Tpo $(DEPDIR)/libcurlu_la-fileinfo.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='fileinfo.c' object='libcurlu_la-fileinfo.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-fileinfo.lo `test -f 'fileinfo.c' || echo '$(srcdir)/'`fileinfo.c + +libcurlu_la-fopen.lo: fopen.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-fopen.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-fopen.Tpo -c -o libcurlu_la-fopen.lo `test -f 'fopen.c' || echo '$(srcdir)/'`fopen.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-fopen.Tpo $(DEPDIR)/libcurlu_la-fopen.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='fopen.c' object='libcurlu_la-fopen.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-fopen.lo `test -f 'fopen.c' || echo '$(srcdir)/'`fopen.c + +libcurlu_la-formdata.lo: formdata.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-formdata.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-formdata.Tpo -c -o libcurlu_la-formdata.lo `test -f 'formdata.c' || echo '$(srcdir)/'`formdata.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-formdata.Tpo $(DEPDIR)/libcurlu_la-formdata.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='formdata.c' object='libcurlu_la-formdata.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-formdata.lo `test -f 'formdata.c' || echo '$(srcdir)/'`formdata.c + +libcurlu_la-ftp.lo: ftp.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-ftp.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-ftp.Tpo -c -o libcurlu_la-ftp.lo `test -f 'ftp.c' || echo '$(srcdir)/'`ftp.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-ftp.Tpo $(DEPDIR)/libcurlu_la-ftp.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='ftp.c' object='libcurlu_la-ftp.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-ftp.lo `test -f 'ftp.c' || echo '$(srcdir)/'`ftp.c + +libcurlu_la-ftplistparser.lo: ftplistparser.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-ftplistparser.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-ftplistparser.Tpo -c -o libcurlu_la-ftplistparser.lo `test -f 'ftplistparser.c' || echo '$(srcdir)/'`ftplistparser.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-ftplistparser.Tpo $(DEPDIR)/libcurlu_la-ftplistparser.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='ftplistparser.c' object='libcurlu_la-ftplistparser.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-ftplistparser.lo `test -f 'ftplistparser.c' || echo '$(srcdir)/'`ftplistparser.c + +libcurlu_la-getenv.lo: getenv.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-getenv.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-getenv.Tpo -c -o libcurlu_la-getenv.lo `test -f 'getenv.c' || echo '$(srcdir)/'`getenv.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-getenv.Tpo $(DEPDIR)/libcurlu_la-getenv.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='getenv.c' object='libcurlu_la-getenv.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-getenv.lo `test -f 'getenv.c' || echo '$(srcdir)/'`getenv.c + +libcurlu_la-getinfo.lo: getinfo.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-getinfo.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-getinfo.Tpo -c -o libcurlu_la-getinfo.lo `test -f 'getinfo.c' || echo '$(srcdir)/'`getinfo.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-getinfo.Tpo $(DEPDIR)/libcurlu_la-getinfo.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='getinfo.c' object='libcurlu_la-getinfo.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-getinfo.lo `test -f 'getinfo.c' || echo '$(srcdir)/'`getinfo.c + +libcurlu_la-gopher.lo: gopher.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-gopher.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-gopher.Tpo -c -o libcurlu_la-gopher.lo `test -f 'gopher.c' || echo '$(srcdir)/'`gopher.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-gopher.Tpo $(DEPDIR)/libcurlu_la-gopher.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='gopher.c' object='libcurlu_la-gopher.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-gopher.lo `test -f 'gopher.c' || echo '$(srcdir)/'`gopher.c + +libcurlu_la-hash.lo: hash.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-hash.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-hash.Tpo -c -o libcurlu_la-hash.lo `test -f 'hash.c' || echo '$(srcdir)/'`hash.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-hash.Tpo $(DEPDIR)/libcurlu_la-hash.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='hash.c' object='libcurlu_la-hash.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-hash.lo `test -f 'hash.c' || echo '$(srcdir)/'`hash.c + +libcurlu_la-headers.lo: headers.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-headers.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-headers.Tpo -c -o libcurlu_la-headers.lo `test -f 'headers.c' || echo '$(srcdir)/'`headers.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-headers.Tpo $(DEPDIR)/libcurlu_la-headers.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='headers.c' object='libcurlu_la-headers.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-headers.lo `test -f 'headers.c' || echo '$(srcdir)/'`headers.c + +libcurlu_la-hmac.lo: hmac.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-hmac.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-hmac.Tpo -c -o libcurlu_la-hmac.lo `test -f 'hmac.c' || echo '$(srcdir)/'`hmac.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-hmac.Tpo $(DEPDIR)/libcurlu_la-hmac.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='hmac.c' object='libcurlu_la-hmac.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-hmac.lo `test -f 'hmac.c' || echo '$(srcdir)/'`hmac.c + +libcurlu_la-hostasyn.lo: hostasyn.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-hostasyn.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-hostasyn.Tpo -c -o libcurlu_la-hostasyn.lo `test -f 'hostasyn.c' || echo '$(srcdir)/'`hostasyn.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-hostasyn.Tpo $(DEPDIR)/libcurlu_la-hostasyn.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='hostasyn.c' object='libcurlu_la-hostasyn.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-hostasyn.lo `test -f 'hostasyn.c' || echo '$(srcdir)/'`hostasyn.c + +libcurlu_la-hostip.lo: hostip.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-hostip.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-hostip.Tpo -c -o libcurlu_la-hostip.lo `test -f 'hostip.c' || echo '$(srcdir)/'`hostip.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-hostip.Tpo $(DEPDIR)/libcurlu_la-hostip.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='hostip.c' object='libcurlu_la-hostip.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-hostip.lo `test -f 'hostip.c' || echo '$(srcdir)/'`hostip.c + +libcurlu_la-hostip4.lo: hostip4.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-hostip4.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-hostip4.Tpo -c -o libcurlu_la-hostip4.lo `test -f 'hostip4.c' || echo '$(srcdir)/'`hostip4.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-hostip4.Tpo $(DEPDIR)/libcurlu_la-hostip4.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='hostip4.c' object='libcurlu_la-hostip4.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-hostip4.lo `test -f 'hostip4.c' || echo '$(srcdir)/'`hostip4.c + +libcurlu_la-hostip6.lo: hostip6.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-hostip6.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-hostip6.Tpo -c -o libcurlu_la-hostip6.lo `test -f 'hostip6.c' || echo '$(srcdir)/'`hostip6.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-hostip6.Tpo $(DEPDIR)/libcurlu_la-hostip6.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='hostip6.c' object='libcurlu_la-hostip6.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-hostip6.lo `test -f 'hostip6.c' || echo '$(srcdir)/'`hostip6.c + +libcurlu_la-hostsyn.lo: hostsyn.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-hostsyn.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-hostsyn.Tpo -c -o libcurlu_la-hostsyn.lo `test -f 'hostsyn.c' || echo '$(srcdir)/'`hostsyn.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-hostsyn.Tpo $(DEPDIR)/libcurlu_la-hostsyn.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='hostsyn.c' object='libcurlu_la-hostsyn.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-hostsyn.lo `test -f 'hostsyn.c' || echo '$(srcdir)/'`hostsyn.c + +libcurlu_la-hsts.lo: hsts.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-hsts.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-hsts.Tpo -c -o libcurlu_la-hsts.lo `test -f 'hsts.c' || echo '$(srcdir)/'`hsts.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-hsts.Tpo $(DEPDIR)/libcurlu_la-hsts.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='hsts.c' object='libcurlu_la-hsts.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-hsts.lo `test -f 'hsts.c' || echo '$(srcdir)/'`hsts.c + +libcurlu_la-http.lo: http.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-http.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-http.Tpo -c -o libcurlu_la-http.lo `test -f 'http.c' || echo '$(srcdir)/'`http.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-http.Tpo $(DEPDIR)/libcurlu_la-http.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http.c' object='libcurlu_la-http.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-http.lo `test -f 'http.c' || echo '$(srcdir)/'`http.c + +libcurlu_la-http1.lo: http1.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-http1.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-http1.Tpo -c -o libcurlu_la-http1.lo `test -f 'http1.c' || echo '$(srcdir)/'`http1.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-http1.Tpo $(DEPDIR)/libcurlu_la-http1.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http1.c' object='libcurlu_la-http1.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-http1.lo `test -f 'http1.c' || echo '$(srcdir)/'`http1.c + +libcurlu_la-http2.lo: http2.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-http2.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-http2.Tpo -c -o libcurlu_la-http2.lo `test -f 'http2.c' || echo '$(srcdir)/'`http2.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-http2.Tpo $(DEPDIR)/libcurlu_la-http2.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http2.c' object='libcurlu_la-http2.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-http2.lo `test -f 'http2.c' || echo '$(srcdir)/'`http2.c + +libcurlu_la-http_aws_sigv4.lo: http_aws_sigv4.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-http_aws_sigv4.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-http_aws_sigv4.Tpo -c -o libcurlu_la-http_aws_sigv4.lo `test -f 'http_aws_sigv4.c' || echo '$(srcdir)/'`http_aws_sigv4.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-http_aws_sigv4.Tpo $(DEPDIR)/libcurlu_la-http_aws_sigv4.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http_aws_sigv4.c' object='libcurlu_la-http_aws_sigv4.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-http_aws_sigv4.lo `test -f 'http_aws_sigv4.c' || echo '$(srcdir)/'`http_aws_sigv4.c + +libcurlu_la-http_chunks.lo: http_chunks.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-http_chunks.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-http_chunks.Tpo -c -o libcurlu_la-http_chunks.lo `test -f 'http_chunks.c' || echo '$(srcdir)/'`http_chunks.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-http_chunks.Tpo $(DEPDIR)/libcurlu_la-http_chunks.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http_chunks.c' object='libcurlu_la-http_chunks.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-http_chunks.lo `test -f 'http_chunks.c' || echo '$(srcdir)/'`http_chunks.c + +libcurlu_la-http_digest.lo: http_digest.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-http_digest.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-http_digest.Tpo -c -o libcurlu_la-http_digest.lo `test -f 'http_digest.c' || echo '$(srcdir)/'`http_digest.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-http_digest.Tpo $(DEPDIR)/libcurlu_la-http_digest.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http_digest.c' object='libcurlu_la-http_digest.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-http_digest.lo `test -f 'http_digest.c' || echo '$(srcdir)/'`http_digest.c + +libcurlu_la-http_negotiate.lo: http_negotiate.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-http_negotiate.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-http_negotiate.Tpo -c -o libcurlu_la-http_negotiate.lo `test -f 'http_negotiate.c' || echo '$(srcdir)/'`http_negotiate.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-http_negotiate.Tpo $(DEPDIR)/libcurlu_la-http_negotiate.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http_negotiate.c' object='libcurlu_la-http_negotiate.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-http_negotiate.lo `test -f 'http_negotiate.c' || echo '$(srcdir)/'`http_negotiate.c + +libcurlu_la-http_ntlm.lo: http_ntlm.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-http_ntlm.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-http_ntlm.Tpo -c -o libcurlu_la-http_ntlm.lo `test -f 'http_ntlm.c' || echo '$(srcdir)/'`http_ntlm.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-http_ntlm.Tpo $(DEPDIR)/libcurlu_la-http_ntlm.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http_ntlm.c' object='libcurlu_la-http_ntlm.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-http_ntlm.lo `test -f 'http_ntlm.c' || echo '$(srcdir)/'`http_ntlm.c + +libcurlu_la-http_proxy.lo: http_proxy.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-http_proxy.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-http_proxy.Tpo -c -o libcurlu_la-http_proxy.lo `test -f 'http_proxy.c' || echo '$(srcdir)/'`http_proxy.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-http_proxy.Tpo $(DEPDIR)/libcurlu_la-http_proxy.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='http_proxy.c' object='libcurlu_la-http_proxy.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-http_proxy.lo `test -f 'http_proxy.c' || echo '$(srcdir)/'`http_proxy.c + +libcurlu_la-idn.lo: idn.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-idn.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-idn.Tpo -c -o libcurlu_la-idn.lo `test -f 'idn.c' || echo '$(srcdir)/'`idn.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-idn.Tpo $(DEPDIR)/libcurlu_la-idn.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='idn.c' object='libcurlu_la-idn.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-idn.lo `test -f 'idn.c' || echo '$(srcdir)/'`idn.c + +libcurlu_la-if2ip.lo: if2ip.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-if2ip.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-if2ip.Tpo -c -o libcurlu_la-if2ip.lo `test -f 'if2ip.c' || echo '$(srcdir)/'`if2ip.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-if2ip.Tpo $(DEPDIR)/libcurlu_la-if2ip.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='if2ip.c' object='libcurlu_la-if2ip.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-if2ip.lo `test -f 'if2ip.c' || echo '$(srcdir)/'`if2ip.c + +libcurlu_la-imap.lo: imap.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-imap.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-imap.Tpo -c -o libcurlu_la-imap.lo `test -f 'imap.c' || echo '$(srcdir)/'`imap.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-imap.Tpo $(DEPDIR)/libcurlu_la-imap.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='imap.c' object='libcurlu_la-imap.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-imap.lo `test -f 'imap.c' || echo '$(srcdir)/'`imap.c + +libcurlu_la-inet_ntop.lo: inet_ntop.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-inet_ntop.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-inet_ntop.Tpo -c -o libcurlu_la-inet_ntop.lo `test -f 'inet_ntop.c' || echo '$(srcdir)/'`inet_ntop.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-inet_ntop.Tpo $(DEPDIR)/libcurlu_la-inet_ntop.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='inet_ntop.c' object='libcurlu_la-inet_ntop.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-inet_ntop.lo `test -f 'inet_ntop.c' || echo '$(srcdir)/'`inet_ntop.c + +libcurlu_la-inet_pton.lo: inet_pton.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-inet_pton.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-inet_pton.Tpo -c -o libcurlu_la-inet_pton.lo `test -f 'inet_pton.c' || echo '$(srcdir)/'`inet_pton.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-inet_pton.Tpo $(DEPDIR)/libcurlu_la-inet_pton.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='inet_pton.c' object='libcurlu_la-inet_pton.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-inet_pton.lo `test -f 'inet_pton.c' || echo '$(srcdir)/'`inet_pton.c + +libcurlu_la-krb5.lo: krb5.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-krb5.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-krb5.Tpo -c -o libcurlu_la-krb5.lo `test -f 'krb5.c' || echo '$(srcdir)/'`krb5.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-krb5.Tpo $(DEPDIR)/libcurlu_la-krb5.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='krb5.c' object='libcurlu_la-krb5.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-krb5.lo `test -f 'krb5.c' || echo '$(srcdir)/'`krb5.c + +libcurlu_la-ldap.lo: ldap.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-ldap.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-ldap.Tpo -c -o libcurlu_la-ldap.lo `test -f 'ldap.c' || echo '$(srcdir)/'`ldap.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-ldap.Tpo $(DEPDIR)/libcurlu_la-ldap.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='ldap.c' object='libcurlu_la-ldap.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-ldap.lo `test -f 'ldap.c' || echo '$(srcdir)/'`ldap.c + +libcurlu_la-llist.lo: llist.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-llist.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-llist.Tpo -c -o libcurlu_la-llist.lo `test -f 'llist.c' || echo '$(srcdir)/'`llist.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-llist.Tpo $(DEPDIR)/libcurlu_la-llist.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='llist.c' object='libcurlu_la-llist.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-llist.lo `test -f 'llist.c' || echo '$(srcdir)/'`llist.c + +libcurlu_la-macos.lo: macos.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-macos.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-macos.Tpo -c -o libcurlu_la-macos.lo `test -f 'macos.c' || echo '$(srcdir)/'`macos.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-macos.Tpo $(DEPDIR)/libcurlu_la-macos.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='macos.c' object='libcurlu_la-macos.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-macos.lo `test -f 'macos.c' || echo '$(srcdir)/'`macos.c + +libcurlu_la-md4.lo: md4.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-md4.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-md4.Tpo -c -o libcurlu_la-md4.lo `test -f 'md4.c' || echo '$(srcdir)/'`md4.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-md4.Tpo $(DEPDIR)/libcurlu_la-md4.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='md4.c' object='libcurlu_la-md4.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-md4.lo `test -f 'md4.c' || echo '$(srcdir)/'`md4.c + +libcurlu_la-md5.lo: md5.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-md5.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-md5.Tpo -c -o libcurlu_la-md5.lo `test -f 'md5.c' || echo '$(srcdir)/'`md5.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-md5.Tpo $(DEPDIR)/libcurlu_la-md5.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='md5.c' object='libcurlu_la-md5.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-md5.lo `test -f 'md5.c' || echo '$(srcdir)/'`md5.c + +libcurlu_la-memdebug.lo: memdebug.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-memdebug.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-memdebug.Tpo -c -o libcurlu_la-memdebug.lo `test -f 'memdebug.c' || echo '$(srcdir)/'`memdebug.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-memdebug.Tpo $(DEPDIR)/libcurlu_la-memdebug.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='memdebug.c' object='libcurlu_la-memdebug.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-memdebug.lo `test -f 'memdebug.c' || echo '$(srcdir)/'`memdebug.c + +libcurlu_la-mime.lo: mime.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-mime.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-mime.Tpo -c -o libcurlu_la-mime.lo `test -f 'mime.c' || echo '$(srcdir)/'`mime.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-mime.Tpo $(DEPDIR)/libcurlu_la-mime.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mime.c' object='libcurlu_la-mime.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-mime.lo `test -f 'mime.c' || echo '$(srcdir)/'`mime.c + +libcurlu_la-mprintf.lo: mprintf.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-mprintf.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-mprintf.Tpo -c -o libcurlu_la-mprintf.lo `test -f 'mprintf.c' || echo '$(srcdir)/'`mprintf.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-mprintf.Tpo $(DEPDIR)/libcurlu_la-mprintf.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mprintf.c' object='libcurlu_la-mprintf.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-mprintf.lo `test -f 'mprintf.c' || echo '$(srcdir)/'`mprintf.c + +libcurlu_la-mqtt.lo: mqtt.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-mqtt.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-mqtt.Tpo -c -o libcurlu_la-mqtt.lo `test -f 'mqtt.c' || echo '$(srcdir)/'`mqtt.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-mqtt.Tpo $(DEPDIR)/libcurlu_la-mqtt.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mqtt.c' object='libcurlu_la-mqtt.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-mqtt.lo `test -f 'mqtt.c' || echo '$(srcdir)/'`mqtt.c + +libcurlu_la-multi.lo: multi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-multi.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-multi.Tpo -c -o libcurlu_la-multi.lo `test -f 'multi.c' || echo '$(srcdir)/'`multi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-multi.Tpo $(DEPDIR)/libcurlu_la-multi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='multi.c' object='libcurlu_la-multi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-multi.lo `test -f 'multi.c' || echo '$(srcdir)/'`multi.c + +libcurlu_la-netrc.lo: netrc.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-netrc.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-netrc.Tpo -c -o libcurlu_la-netrc.lo `test -f 'netrc.c' || echo '$(srcdir)/'`netrc.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-netrc.Tpo $(DEPDIR)/libcurlu_la-netrc.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='netrc.c' object='libcurlu_la-netrc.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-netrc.lo `test -f 'netrc.c' || echo '$(srcdir)/'`netrc.c + +libcurlu_la-nonblock.lo: nonblock.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-nonblock.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-nonblock.Tpo -c -o libcurlu_la-nonblock.lo `test -f 'nonblock.c' || echo '$(srcdir)/'`nonblock.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-nonblock.Tpo $(DEPDIR)/libcurlu_la-nonblock.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='nonblock.c' object='libcurlu_la-nonblock.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-nonblock.lo `test -f 'nonblock.c' || echo '$(srcdir)/'`nonblock.c + +libcurlu_la-noproxy.lo: noproxy.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-noproxy.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-noproxy.Tpo -c -o libcurlu_la-noproxy.lo `test -f 'noproxy.c' || echo '$(srcdir)/'`noproxy.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-noproxy.Tpo $(DEPDIR)/libcurlu_la-noproxy.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='noproxy.c' object='libcurlu_la-noproxy.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-noproxy.lo `test -f 'noproxy.c' || echo '$(srcdir)/'`noproxy.c + +libcurlu_la-openldap.lo: openldap.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-openldap.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-openldap.Tpo -c -o libcurlu_la-openldap.lo `test -f 'openldap.c' || echo '$(srcdir)/'`openldap.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-openldap.Tpo $(DEPDIR)/libcurlu_la-openldap.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='openldap.c' object='libcurlu_la-openldap.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-openldap.lo `test -f 'openldap.c' || echo '$(srcdir)/'`openldap.c + +libcurlu_la-parsedate.lo: parsedate.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-parsedate.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-parsedate.Tpo -c -o libcurlu_la-parsedate.lo `test -f 'parsedate.c' || echo '$(srcdir)/'`parsedate.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-parsedate.Tpo $(DEPDIR)/libcurlu_la-parsedate.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='parsedate.c' object='libcurlu_la-parsedate.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-parsedate.lo `test -f 'parsedate.c' || echo '$(srcdir)/'`parsedate.c + +libcurlu_la-pingpong.lo: pingpong.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-pingpong.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-pingpong.Tpo -c -o libcurlu_la-pingpong.lo `test -f 'pingpong.c' || echo '$(srcdir)/'`pingpong.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-pingpong.Tpo $(DEPDIR)/libcurlu_la-pingpong.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='pingpong.c' object='libcurlu_la-pingpong.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-pingpong.lo `test -f 'pingpong.c' || echo '$(srcdir)/'`pingpong.c + +libcurlu_la-pop3.lo: pop3.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-pop3.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-pop3.Tpo -c -o libcurlu_la-pop3.lo `test -f 'pop3.c' || echo '$(srcdir)/'`pop3.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-pop3.Tpo $(DEPDIR)/libcurlu_la-pop3.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='pop3.c' object='libcurlu_la-pop3.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-pop3.lo `test -f 'pop3.c' || echo '$(srcdir)/'`pop3.c + +libcurlu_la-progress.lo: progress.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-progress.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-progress.Tpo -c -o libcurlu_la-progress.lo `test -f 'progress.c' || echo '$(srcdir)/'`progress.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-progress.Tpo $(DEPDIR)/libcurlu_la-progress.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='progress.c' object='libcurlu_la-progress.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-progress.lo `test -f 'progress.c' || echo '$(srcdir)/'`progress.c + +libcurlu_la-psl.lo: psl.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-psl.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-psl.Tpo -c -o libcurlu_la-psl.lo `test -f 'psl.c' || echo '$(srcdir)/'`psl.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-psl.Tpo $(DEPDIR)/libcurlu_la-psl.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='psl.c' object='libcurlu_la-psl.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-psl.lo `test -f 'psl.c' || echo '$(srcdir)/'`psl.c + +libcurlu_la-rand.lo: rand.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-rand.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-rand.Tpo -c -o libcurlu_la-rand.lo `test -f 'rand.c' || echo '$(srcdir)/'`rand.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-rand.Tpo $(DEPDIR)/libcurlu_la-rand.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='rand.c' object='libcurlu_la-rand.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-rand.lo `test -f 'rand.c' || echo '$(srcdir)/'`rand.c + +libcurlu_la-rename.lo: rename.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-rename.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-rename.Tpo -c -o libcurlu_la-rename.lo `test -f 'rename.c' || echo '$(srcdir)/'`rename.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-rename.Tpo $(DEPDIR)/libcurlu_la-rename.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='rename.c' object='libcurlu_la-rename.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-rename.lo `test -f 'rename.c' || echo '$(srcdir)/'`rename.c + +libcurlu_la-request.lo: request.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-request.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-request.Tpo -c -o libcurlu_la-request.lo `test -f 'request.c' || echo '$(srcdir)/'`request.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-request.Tpo $(DEPDIR)/libcurlu_la-request.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='request.c' object='libcurlu_la-request.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-request.lo `test -f 'request.c' || echo '$(srcdir)/'`request.c + +libcurlu_la-rtsp.lo: rtsp.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-rtsp.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-rtsp.Tpo -c -o libcurlu_la-rtsp.lo `test -f 'rtsp.c' || echo '$(srcdir)/'`rtsp.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-rtsp.Tpo $(DEPDIR)/libcurlu_la-rtsp.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='rtsp.c' object='libcurlu_la-rtsp.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-rtsp.lo `test -f 'rtsp.c' || echo '$(srcdir)/'`rtsp.c + +libcurlu_la-select.lo: select.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-select.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-select.Tpo -c -o libcurlu_la-select.lo `test -f 'select.c' || echo '$(srcdir)/'`select.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-select.Tpo $(DEPDIR)/libcurlu_la-select.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='select.c' object='libcurlu_la-select.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-select.lo `test -f 'select.c' || echo '$(srcdir)/'`select.c + +libcurlu_la-sendf.lo: sendf.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-sendf.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-sendf.Tpo -c -o libcurlu_la-sendf.lo `test -f 'sendf.c' || echo '$(srcdir)/'`sendf.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-sendf.Tpo $(DEPDIR)/libcurlu_la-sendf.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sendf.c' object='libcurlu_la-sendf.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-sendf.lo `test -f 'sendf.c' || echo '$(srcdir)/'`sendf.c + +libcurlu_la-setopt.lo: setopt.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-setopt.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-setopt.Tpo -c -o libcurlu_la-setopt.lo `test -f 'setopt.c' || echo '$(srcdir)/'`setopt.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-setopt.Tpo $(DEPDIR)/libcurlu_la-setopt.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='setopt.c' object='libcurlu_la-setopt.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-setopt.lo `test -f 'setopt.c' || echo '$(srcdir)/'`setopt.c + +libcurlu_la-sha256.lo: sha256.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-sha256.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-sha256.Tpo -c -o libcurlu_la-sha256.lo `test -f 'sha256.c' || echo '$(srcdir)/'`sha256.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-sha256.Tpo $(DEPDIR)/libcurlu_la-sha256.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha256.c' object='libcurlu_la-sha256.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-sha256.lo `test -f 'sha256.c' || echo '$(srcdir)/'`sha256.c + +libcurlu_la-share.lo: share.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-share.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-share.Tpo -c -o libcurlu_la-share.lo `test -f 'share.c' || echo '$(srcdir)/'`share.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-share.Tpo $(DEPDIR)/libcurlu_la-share.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='share.c' object='libcurlu_la-share.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-share.lo `test -f 'share.c' || echo '$(srcdir)/'`share.c + +libcurlu_la-slist.lo: slist.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-slist.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-slist.Tpo -c -o libcurlu_la-slist.lo `test -f 'slist.c' || echo '$(srcdir)/'`slist.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-slist.Tpo $(DEPDIR)/libcurlu_la-slist.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='slist.c' object='libcurlu_la-slist.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-slist.lo `test -f 'slist.c' || echo '$(srcdir)/'`slist.c + +libcurlu_la-smb.lo: smb.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-smb.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-smb.Tpo -c -o libcurlu_la-smb.lo `test -f 'smb.c' || echo '$(srcdir)/'`smb.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-smb.Tpo $(DEPDIR)/libcurlu_la-smb.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='smb.c' object='libcurlu_la-smb.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-smb.lo `test -f 'smb.c' || echo '$(srcdir)/'`smb.c + +libcurlu_la-smtp.lo: smtp.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-smtp.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-smtp.Tpo -c -o libcurlu_la-smtp.lo `test -f 'smtp.c' || echo '$(srcdir)/'`smtp.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-smtp.Tpo $(DEPDIR)/libcurlu_la-smtp.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='smtp.c' object='libcurlu_la-smtp.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-smtp.lo `test -f 'smtp.c' || echo '$(srcdir)/'`smtp.c + +libcurlu_la-socketpair.lo: socketpair.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-socketpair.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-socketpair.Tpo -c -o libcurlu_la-socketpair.lo `test -f 'socketpair.c' || echo '$(srcdir)/'`socketpair.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-socketpair.Tpo $(DEPDIR)/libcurlu_la-socketpair.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='socketpair.c' object='libcurlu_la-socketpair.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-socketpair.lo `test -f 'socketpair.c' || echo '$(srcdir)/'`socketpair.c + +libcurlu_la-socks.lo: socks.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-socks.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-socks.Tpo -c -o libcurlu_la-socks.lo `test -f 'socks.c' || echo '$(srcdir)/'`socks.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-socks.Tpo $(DEPDIR)/libcurlu_la-socks.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='socks.c' object='libcurlu_la-socks.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-socks.lo `test -f 'socks.c' || echo '$(srcdir)/'`socks.c + +libcurlu_la-socks_gssapi.lo: socks_gssapi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-socks_gssapi.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-socks_gssapi.Tpo -c -o libcurlu_la-socks_gssapi.lo `test -f 'socks_gssapi.c' || echo '$(srcdir)/'`socks_gssapi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-socks_gssapi.Tpo $(DEPDIR)/libcurlu_la-socks_gssapi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='socks_gssapi.c' object='libcurlu_la-socks_gssapi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-socks_gssapi.lo `test -f 'socks_gssapi.c' || echo '$(srcdir)/'`socks_gssapi.c + +libcurlu_la-socks_sspi.lo: socks_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-socks_sspi.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-socks_sspi.Tpo -c -o libcurlu_la-socks_sspi.lo `test -f 'socks_sspi.c' || echo '$(srcdir)/'`socks_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-socks_sspi.Tpo $(DEPDIR)/libcurlu_la-socks_sspi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='socks_sspi.c' object='libcurlu_la-socks_sspi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-socks_sspi.lo `test -f 'socks_sspi.c' || echo '$(srcdir)/'`socks_sspi.c + +libcurlu_la-speedcheck.lo: speedcheck.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-speedcheck.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-speedcheck.Tpo -c -o libcurlu_la-speedcheck.lo `test -f 'speedcheck.c' || echo '$(srcdir)/'`speedcheck.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-speedcheck.Tpo $(DEPDIR)/libcurlu_la-speedcheck.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='speedcheck.c' object='libcurlu_la-speedcheck.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-speedcheck.lo `test -f 'speedcheck.c' || echo '$(srcdir)/'`speedcheck.c + +libcurlu_la-splay.lo: splay.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-splay.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-splay.Tpo -c -o libcurlu_la-splay.lo `test -f 'splay.c' || echo '$(srcdir)/'`splay.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-splay.Tpo $(DEPDIR)/libcurlu_la-splay.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='splay.c' object='libcurlu_la-splay.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-splay.lo `test -f 'splay.c' || echo '$(srcdir)/'`splay.c + +libcurlu_la-strcase.lo: strcase.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-strcase.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-strcase.Tpo -c -o libcurlu_la-strcase.lo `test -f 'strcase.c' || echo '$(srcdir)/'`strcase.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-strcase.Tpo $(DEPDIR)/libcurlu_la-strcase.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='strcase.c' object='libcurlu_la-strcase.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-strcase.lo `test -f 'strcase.c' || echo '$(srcdir)/'`strcase.c + +libcurlu_la-strdup.lo: strdup.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-strdup.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-strdup.Tpo -c -o libcurlu_la-strdup.lo `test -f 'strdup.c' || echo '$(srcdir)/'`strdup.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-strdup.Tpo $(DEPDIR)/libcurlu_la-strdup.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='strdup.c' object='libcurlu_la-strdup.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-strdup.lo `test -f 'strdup.c' || echo '$(srcdir)/'`strdup.c + +libcurlu_la-strerror.lo: strerror.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-strerror.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-strerror.Tpo -c -o libcurlu_la-strerror.lo `test -f 'strerror.c' || echo '$(srcdir)/'`strerror.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-strerror.Tpo $(DEPDIR)/libcurlu_la-strerror.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='strerror.c' object='libcurlu_la-strerror.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-strerror.lo `test -f 'strerror.c' || echo '$(srcdir)/'`strerror.c + +libcurlu_la-strtok.lo: strtok.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-strtok.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-strtok.Tpo -c -o libcurlu_la-strtok.lo `test -f 'strtok.c' || echo '$(srcdir)/'`strtok.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-strtok.Tpo $(DEPDIR)/libcurlu_la-strtok.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='strtok.c' object='libcurlu_la-strtok.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-strtok.lo `test -f 'strtok.c' || echo '$(srcdir)/'`strtok.c + +libcurlu_la-strtoofft.lo: strtoofft.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-strtoofft.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-strtoofft.Tpo -c -o libcurlu_la-strtoofft.lo `test -f 'strtoofft.c' || echo '$(srcdir)/'`strtoofft.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-strtoofft.Tpo $(DEPDIR)/libcurlu_la-strtoofft.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='strtoofft.c' object='libcurlu_la-strtoofft.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-strtoofft.lo `test -f 'strtoofft.c' || echo '$(srcdir)/'`strtoofft.c + +libcurlu_la-system_win32.lo: system_win32.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-system_win32.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-system_win32.Tpo -c -o libcurlu_la-system_win32.lo `test -f 'system_win32.c' || echo '$(srcdir)/'`system_win32.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-system_win32.Tpo $(DEPDIR)/libcurlu_la-system_win32.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='system_win32.c' object='libcurlu_la-system_win32.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-system_win32.lo `test -f 'system_win32.c' || echo '$(srcdir)/'`system_win32.c + +libcurlu_la-telnet.lo: telnet.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-telnet.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-telnet.Tpo -c -o libcurlu_la-telnet.lo `test -f 'telnet.c' || echo '$(srcdir)/'`telnet.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-telnet.Tpo $(DEPDIR)/libcurlu_la-telnet.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='telnet.c' object='libcurlu_la-telnet.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-telnet.lo `test -f 'telnet.c' || echo '$(srcdir)/'`telnet.c + +libcurlu_la-tftp.lo: tftp.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-tftp.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-tftp.Tpo -c -o libcurlu_la-tftp.lo `test -f 'tftp.c' || echo '$(srcdir)/'`tftp.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-tftp.Tpo $(DEPDIR)/libcurlu_la-tftp.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='tftp.c' object='libcurlu_la-tftp.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-tftp.lo `test -f 'tftp.c' || echo '$(srcdir)/'`tftp.c + +libcurlu_la-timediff.lo: timediff.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-timediff.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-timediff.Tpo -c -o libcurlu_la-timediff.lo `test -f 'timediff.c' || echo '$(srcdir)/'`timediff.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-timediff.Tpo $(DEPDIR)/libcurlu_la-timediff.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='timediff.c' object='libcurlu_la-timediff.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-timediff.lo `test -f 'timediff.c' || echo '$(srcdir)/'`timediff.c + +libcurlu_la-timeval.lo: timeval.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-timeval.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-timeval.Tpo -c -o libcurlu_la-timeval.lo `test -f 'timeval.c' || echo '$(srcdir)/'`timeval.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-timeval.Tpo $(DEPDIR)/libcurlu_la-timeval.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='timeval.c' object='libcurlu_la-timeval.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-timeval.lo `test -f 'timeval.c' || echo '$(srcdir)/'`timeval.c + +libcurlu_la-transfer.lo: transfer.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-transfer.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-transfer.Tpo -c -o libcurlu_la-transfer.lo `test -f 'transfer.c' || echo '$(srcdir)/'`transfer.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-transfer.Tpo $(DEPDIR)/libcurlu_la-transfer.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='transfer.c' object='libcurlu_la-transfer.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-transfer.lo `test -f 'transfer.c' || echo '$(srcdir)/'`transfer.c + +libcurlu_la-url.lo: url.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-url.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-url.Tpo -c -o libcurlu_la-url.lo `test -f 'url.c' || echo '$(srcdir)/'`url.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-url.Tpo $(DEPDIR)/libcurlu_la-url.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='url.c' object='libcurlu_la-url.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-url.lo `test -f 'url.c' || echo '$(srcdir)/'`url.c + +libcurlu_la-urlapi.lo: urlapi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-urlapi.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-urlapi.Tpo -c -o libcurlu_la-urlapi.lo `test -f 'urlapi.c' || echo '$(srcdir)/'`urlapi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-urlapi.Tpo $(DEPDIR)/libcurlu_la-urlapi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='urlapi.c' object='libcurlu_la-urlapi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-urlapi.lo `test -f 'urlapi.c' || echo '$(srcdir)/'`urlapi.c + +libcurlu_la-version.lo: version.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-version.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-version.Tpo -c -o libcurlu_la-version.lo `test -f 'version.c' || echo '$(srcdir)/'`version.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-version.Tpo $(DEPDIR)/libcurlu_la-version.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='version.c' object='libcurlu_la-version.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-version.lo `test -f 'version.c' || echo '$(srcdir)/'`version.c + +libcurlu_la-version_win32.lo: version_win32.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-version_win32.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-version_win32.Tpo -c -o libcurlu_la-version_win32.lo `test -f 'version_win32.c' || echo '$(srcdir)/'`version_win32.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-version_win32.Tpo $(DEPDIR)/libcurlu_la-version_win32.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='version_win32.c' object='libcurlu_la-version_win32.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-version_win32.lo `test -f 'version_win32.c' || echo '$(srcdir)/'`version_win32.c + +libcurlu_la-warnless.lo: warnless.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-warnless.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-warnless.Tpo -c -o libcurlu_la-warnless.lo `test -f 'warnless.c' || echo '$(srcdir)/'`warnless.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-warnless.Tpo $(DEPDIR)/libcurlu_la-warnless.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='warnless.c' object='libcurlu_la-warnless.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-warnless.lo `test -f 'warnless.c' || echo '$(srcdir)/'`warnless.c + +libcurlu_la-ws.lo: ws.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT libcurlu_la-ws.lo -MD -MP -MF $(DEPDIR)/libcurlu_la-ws.Tpo -c -o libcurlu_la-ws.lo `test -f 'ws.c' || echo '$(srcdir)/'`ws.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libcurlu_la-ws.Tpo $(DEPDIR)/libcurlu_la-ws.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='ws.c' object='libcurlu_la-ws.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o libcurlu_la-ws.lo `test -f 'ws.c' || echo '$(srcdir)/'`ws.c + +vauth/libcurlu_la-cleartext.lo: vauth/cleartext.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vauth/libcurlu_la-cleartext.lo -MD -MP -MF vauth/$(DEPDIR)/libcurlu_la-cleartext.Tpo -c -o vauth/libcurlu_la-cleartext.lo `test -f 'vauth/cleartext.c' || echo '$(srcdir)/'`vauth/cleartext.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurlu_la-cleartext.Tpo vauth/$(DEPDIR)/libcurlu_la-cleartext.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/cleartext.c' object='vauth/libcurlu_la-cleartext.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurlu_la-cleartext.lo `test -f 'vauth/cleartext.c' || echo '$(srcdir)/'`vauth/cleartext.c + +vauth/libcurlu_la-cram.lo: vauth/cram.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vauth/libcurlu_la-cram.lo -MD -MP -MF vauth/$(DEPDIR)/libcurlu_la-cram.Tpo -c -o vauth/libcurlu_la-cram.lo `test -f 'vauth/cram.c' || echo '$(srcdir)/'`vauth/cram.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurlu_la-cram.Tpo vauth/$(DEPDIR)/libcurlu_la-cram.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/cram.c' object='vauth/libcurlu_la-cram.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurlu_la-cram.lo `test -f 'vauth/cram.c' || echo '$(srcdir)/'`vauth/cram.c + +vauth/libcurlu_la-digest.lo: vauth/digest.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vauth/libcurlu_la-digest.lo -MD -MP -MF vauth/$(DEPDIR)/libcurlu_la-digest.Tpo -c -o vauth/libcurlu_la-digest.lo `test -f 'vauth/digest.c' || echo '$(srcdir)/'`vauth/digest.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurlu_la-digest.Tpo vauth/$(DEPDIR)/libcurlu_la-digest.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/digest.c' object='vauth/libcurlu_la-digest.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurlu_la-digest.lo `test -f 'vauth/digest.c' || echo '$(srcdir)/'`vauth/digest.c + +vauth/libcurlu_la-digest_sspi.lo: vauth/digest_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vauth/libcurlu_la-digest_sspi.lo -MD -MP -MF vauth/$(DEPDIR)/libcurlu_la-digest_sspi.Tpo -c -o vauth/libcurlu_la-digest_sspi.lo `test -f 'vauth/digest_sspi.c' || echo '$(srcdir)/'`vauth/digest_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurlu_la-digest_sspi.Tpo vauth/$(DEPDIR)/libcurlu_la-digest_sspi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/digest_sspi.c' object='vauth/libcurlu_la-digest_sspi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurlu_la-digest_sspi.lo `test -f 'vauth/digest_sspi.c' || echo '$(srcdir)/'`vauth/digest_sspi.c + +vauth/libcurlu_la-gsasl.lo: vauth/gsasl.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vauth/libcurlu_la-gsasl.lo -MD -MP -MF vauth/$(DEPDIR)/libcurlu_la-gsasl.Tpo -c -o vauth/libcurlu_la-gsasl.lo `test -f 'vauth/gsasl.c' || echo '$(srcdir)/'`vauth/gsasl.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurlu_la-gsasl.Tpo vauth/$(DEPDIR)/libcurlu_la-gsasl.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/gsasl.c' object='vauth/libcurlu_la-gsasl.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurlu_la-gsasl.lo `test -f 'vauth/gsasl.c' || echo '$(srcdir)/'`vauth/gsasl.c + +vauth/libcurlu_la-krb5_gssapi.lo: vauth/krb5_gssapi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vauth/libcurlu_la-krb5_gssapi.lo -MD -MP -MF vauth/$(DEPDIR)/libcurlu_la-krb5_gssapi.Tpo -c -o vauth/libcurlu_la-krb5_gssapi.lo `test -f 'vauth/krb5_gssapi.c' || echo '$(srcdir)/'`vauth/krb5_gssapi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurlu_la-krb5_gssapi.Tpo vauth/$(DEPDIR)/libcurlu_la-krb5_gssapi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/krb5_gssapi.c' object='vauth/libcurlu_la-krb5_gssapi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurlu_la-krb5_gssapi.lo `test -f 'vauth/krb5_gssapi.c' || echo '$(srcdir)/'`vauth/krb5_gssapi.c + +vauth/libcurlu_la-krb5_sspi.lo: vauth/krb5_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vauth/libcurlu_la-krb5_sspi.lo -MD -MP -MF vauth/$(DEPDIR)/libcurlu_la-krb5_sspi.Tpo -c -o vauth/libcurlu_la-krb5_sspi.lo `test -f 'vauth/krb5_sspi.c' || echo '$(srcdir)/'`vauth/krb5_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurlu_la-krb5_sspi.Tpo vauth/$(DEPDIR)/libcurlu_la-krb5_sspi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/krb5_sspi.c' object='vauth/libcurlu_la-krb5_sspi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurlu_la-krb5_sspi.lo `test -f 'vauth/krb5_sspi.c' || echo '$(srcdir)/'`vauth/krb5_sspi.c + +vauth/libcurlu_la-ntlm.lo: vauth/ntlm.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vauth/libcurlu_la-ntlm.lo -MD -MP -MF vauth/$(DEPDIR)/libcurlu_la-ntlm.Tpo -c -o vauth/libcurlu_la-ntlm.lo `test -f 'vauth/ntlm.c' || echo '$(srcdir)/'`vauth/ntlm.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurlu_la-ntlm.Tpo vauth/$(DEPDIR)/libcurlu_la-ntlm.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/ntlm.c' object='vauth/libcurlu_la-ntlm.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurlu_la-ntlm.lo `test -f 'vauth/ntlm.c' || echo '$(srcdir)/'`vauth/ntlm.c + +vauth/libcurlu_la-ntlm_sspi.lo: vauth/ntlm_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vauth/libcurlu_la-ntlm_sspi.lo -MD -MP -MF vauth/$(DEPDIR)/libcurlu_la-ntlm_sspi.Tpo -c -o vauth/libcurlu_la-ntlm_sspi.lo `test -f 'vauth/ntlm_sspi.c' || echo '$(srcdir)/'`vauth/ntlm_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurlu_la-ntlm_sspi.Tpo vauth/$(DEPDIR)/libcurlu_la-ntlm_sspi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/ntlm_sspi.c' object='vauth/libcurlu_la-ntlm_sspi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurlu_la-ntlm_sspi.lo `test -f 'vauth/ntlm_sspi.c' || echo '$(srcdir)/'`vauth/ntlm_sspi.c + +vauth/libcurlu_la-oauth2.lo: vauth/oauth2.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vauth/libcurlu_la-oauth2.lo -MD -MP -MF vauth/$(DEPDIR)/libcurlu_la-oauth2.Tpo -c -o vauth/libcurlu_la-oauth2.lo `test -f 'vauth/oauth2.c' || echo '$(srcdir)/'`vauth/oauth2.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurlu_la-oauth2.Tpo vauth/$(DEPDIR)/libcurlu_la-oauth2.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/oauth2.c' object='vauth/libcurlu_la-oauth2.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurlu_la-oauth2.lo `test -f 'vauth/oauth2.c' || echo '$(srcdir)/'`vauth/oauth2.c + +vauth/libcurlu_la-spnego_gssapi.lo: vauth/spnego_gssapi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vauth/libcurlu_la-spnego_gssapi.lo -MD -MP -MF vauth/$(DEPDIR)/libcurlu_la-spnego_gssapi.Tpo -c -o vauth/libcurlu_la-spnego_gssapi.lo `test -f 'vauth/spnego_gssapi.c' || echo '$(srcdir)/'`vauth/spnego_gssapi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurlu_la-spnego_gssapi.Tpo vauth/$(DEPDIR)/libcurlu_la-spnego_gssapi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/spnego_gssapi.c' object='vauth/libcurlu_la-spnego_gssapi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurlu_la-spnego_gssapi.lo `test -f 'vauth/spnego_gssapi.c' || echo '$(srcdir)/'`vauth/spnego_gssapi.c + +vauth/libcurlu_la-spnego_sspi.lo: vauth/spnego_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vauth/libcurlu_la-spnego_sspi.lo -MD -MP -MF vauth/$(DEPDIR)/libcurlu_la-spnego_sspi.Tpo -c -o vauth/libcurlu_la-spnego_sspi.lo `test -f 'vauth/spnego_sspi.c' || echo '$(srcdir)/'`vauth/spnego_sspi.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurlu_la-spnego_sspi.Tpo vauth/$(DEPDIR)/libcurlu_la-spnego_sspi.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/spnego_sspi.c' object='vauth/libcurlu_la-spnego_sspi.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurlu_la-spnego_sspi.lo `test -f 'vauth/spnego_sspi.c' || echo '$(srcdir)/'`vauth/spnego_sspi.c + +vauth/libcurlu_la-vauth.lo: vauth/vauth.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vauth/libcurlu_la-vauth.lo -MD -MP -MF vauth/$(DEPDIR)/libcurlu_la-vauth.Tpo -c -o vauth/libcurlu_la-vauth.lo `test -f 'vauth/vauth.c' || echo '$(srcdir)/'`vauth/vauth.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vauth/$(DEPDIR)/libcurlu_la-vauth.Tpo vauth/$(DEPDIR)/libcurlu_la-vauth.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vauth/vauth.c' object='vauth/libcurlu_la-vauth.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vauth/libcurlu_la-vauth.lo `test -f 'vauth/vauth.c' || echo '$(srcdir)/'`vauth/vauth.c + +vtls/libcurlu_la-bearssl.lo: vtls/bearssl.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vtls/libcurlu_la-bearssl.lo -MD -MP -MF vtls/$(DEPDIR)/libcurlu_la-bearssl.Tpo -c -o vtls/libcurlu_la-bearssl.lo `test -f 'vtls/bearssl.c' || echo '$(srcdir)/'`vtls/bearssl.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurlu_la-bearssl.Tpo vtls/$(DEPDIR)/libcurlu_la-bearssl.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/bearssl.c' object='vtls/libcurlu_la-bearssl.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurlu_la-bearssl.lo `test -f 'vtls/bearssl.c' || echo '$(srcdir)/'`vtls/bearssl.c + +vtls/libcurlu_la-cipher_suite.lo: vtls/cipher_suite.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vtls/libcurlu_la-cipher_suite.lo -MD -MP -MF vtls/$(DEPDIR)/libcurlu_la-cipher_suite.Tpo -c -o vtls/libcurlu_la-cipher_suite.lo `test -f 'vtls/cipher_suite.c' || echo '$(srcdir)/'`vtls/cipher_suite.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurlu_la-cipher_suite.Tpo vtls/$(DEPDIR)/libcurlu_la-cipher_suite.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/cipher_suite.c' object='vtls/libcurlu_la-cipher_suite.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurlu_la-cipher_suite.lo `test -f 'vtls/cipher_suite.c' || echo '$(srcdir)/'`vtls/cipher_suite.c + +vtls/libcurlu_la-gtls.lo: vtls/gtls.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vtls/libcurlu_la-gtls.lo -MD -MP -MF vtls/$(DEPDIR)/libcurlu_la-gtls.Tpo -c -o vtls/libcurlu_la-gtls.lo `test -f 'vtls/gtls.c' || echo '$(srcdir)/'`vtls/gtls.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurlu_la-gtls.Tpo vtls/$(DEPDIR)/libcurlu_la-gtls.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/gtls.c' object='vtls/libcurlu_la-gtls.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurlu_la-gtls.lo `test -f 'vtls/gtls.c' || echo '$(srcdir)/'`vtls/gtls.c + +vtls/libcurlu_la-hostcheck.lo: vtls/hostcheck.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vtls/libcurlu_la-hostcheck.lo -MD -MP -MF vtls/$(DEPDIR)/libcurlu_la-hostcheck.Tpo -c -o vtls/libcurlu_la-hostcheck.lo `test -f 'vtls/hostcheck.c' || echo '$(srcdir)/'`vtls/hostcheck.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurlu_la-hostcheck.Tpo vtls/$(DEPDIR)/libcurlu_la-hostcheck.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/hostcheck.c' object='vtls/libcurlu_la-hostcheck.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurlu_la-hostcheck.lo `test -f 'vtls/hostcheck.c' || echo '$(srcdir)/'`vtls/hostcheck.c + +vtls/libcurlu_la-keylog.lo: vtls/keylog.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vtls/libcurlu_la-keylog.lo -MD -MP -MF vtls/$(DEPDIR)/libcurlu_la-keylog.Tpo -c -o vtls/libcurlu_la-keylog.lo `test -f 'vtls/keylog.c' || echo '$(srcdir)/'`vtls/keylog.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurlu_la-keylog.Tpo vtls/$(DEPDIR)/libcurlu_la-keylog.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/keylog.c' object='vtls/libcurlu_la-keylog.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurlu_la-keylog.lo `test -f 'vtls/keylog.c' || echo '$(srcdir)/'`vtls/keylog.c + +vtls/libcurlu_la-mbedtls.lo: vtls/mbedtls.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vtls/libcurlu_la-mbedtls.lo -MD -MP -MF vtls/$(DEPDIR)/libcurlu_la-mbedtls.Tpo -c -o vtls/libcurlu_la-mbedtls.lo `test -f 'vtls/mbedtls.c' || echo '$(srcdir)/'`vtls/mbedtls.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurlu_la-mbedtls.Tpo vtls/$(DEPDIR)/libcurlu_la-mbedtls.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/mbedtls.c' object='vtls/libcurlu_la-mbedtls.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurlu_la-mbedtls.lo `test -f 'vtls/mbedtls.c' || echo '$(srcdir)/'`vtls/mbedtls.c + +vtls/libcurlu_la-mbedtls_threadlock.lo: vtls/mbedtls_threadlock.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vtls/libcurlu_la-mbedtls_threadlock.lo -MD -MP -MF vtls/$(DEPDIR)/libcurlu_la-mbedtls_threadlock.Tpo -c -o vtls/libcurlu_la-mbedtls_threadlock.lo `test -f 'vtls/mbedtls_threadlock.c' || echo '$(srcdir)/'`vtls/mbedtls_threadlock.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurlu_la-mbedtls_threadlock.Tpo vtls/$(DEPDIR)/libcurlu_la-mbedtls_threadlock.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/mbedtls_threadlock.c' object='vtls/libcurlu_la-mbedtls_threadlock.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurlu_la-mbedtls_threadlock.lo `test -f 'vtls/mbedtls_threadlock.c' || echo '$(srcdir)/'`vtls/mbedtls_threadlock.c + +vtls/libcurlu_la-openssl.lo: vtls/openssl.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vtls/libcurlu_la-openssl.lo -MD -MP -MF vtls/$(DEPDIR)/libcurlu_la-openssl.Tpo -c -o vtls/libcurlu_la-openssl.lo `test -f 'vtls/openssl.c' || echo '$(srcdir)/'`vtls/openssl.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurlu_la-openssl.Tpo vtls/$(DEPDIR)/libcurlu_la-openssl.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/openssl.c' object='vtls/libcurlu_la-openssl.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurlu_la-openssl.lo `test -f 'vtls/openssl.c' || echo '$(srcdir)/'`vtls/openssl.c + +vtls/libcurlu_la-rustls.lo: vtls/rustls.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vtls/libcurlu_la-rustls.lo -MD -MP -MF vtls/$(DEPDIR)/libcurlu_la-rustls.Tpo -c -o vtls/libcurlu_la-rustls.lo `test -f 'vtls/rustls.c' || echo '$(srcdir)/'`vtls/rustls.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurlu_la-rustls.Tpo vtls/$(DEPDIR)/libcurlu_la-rustls.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/rustls.c' object='vtls/libcurlu_la-rustls.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurlu_la-rustls.lo `test -f 'vtls/rustls.c' || echo '$(srcdir)/'`vtls/rustls.c + +vtls/libcurlu_la-schannel.lo: vtls/schannel.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vtls/libcurlu_la-schannel.lo -MD -MP -MF vtls/$(DEPDIR)/libcurlu_la-schannel.Tpo -c -o vtls/libcurlu_la-schannel.lo `test -f 'vtls/schannel.c' || echo '$(srcdir)/'`vtls/schannel.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurlu_la-schannel.Tpo vtls/$(DEPDIR)/libcurlu_la-schannel.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/schannel.c' object='vtls/libcurlu_la-schannel.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurlu_la-schannel.lo `test -f 'vtls/schannel.c' || echo '$(srcdir)/'`vtls/schannel.c + +vtls/libcurlu_la-schannel_verify.lo: vtls/schannel_verify.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vtls/libcurlu_la-schannel_verify.lo -MD -MP -MF vtls/$(DEPDIR)/libcurlu_la-schannel_verify.Tpo -c -o vtls/libcurlu_la-schannel_verify.lo `test -f 'vtls/schannel_verify.c' || echo '$(srcdir)/'`vtls/schannel_verify.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurlu_la-schannel_verify.Tpo vtls/$(DEPDIR)/libcurlu_la-schannel_verify.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/schannel_verify.c' object='vtls/libcurlu_la-schannel_verify.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurlu_la-schannel_verify.lo `test -f 'vtls/schannel_verify.c' || echo '$(srcdir)/'`vtls/schannel_verify.c + +vtls/libcurlu_la-sectransp.lo: vtls/sectransp.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vtls/libcurlu_la-sectransp.lo -MD -MP -MF vtls/$(DEPDIR)/libcurlu_la-sectransp.Tpo -c -o vtls/libcurlu_la-sectransp.lo `test -f 'vtls/sectransp.c' || echo '$(srcdir)/'`vtls/sectransp.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurlu_la-sectransp.Tpo vtls/$(DEPDIR)/libcurlu_la-sectransp.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/sectransp.c' object='vtls/libcurlu_la-sectransp.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurlu_la-sectransp.lo `test -f 'vtls/sectransp.c' || echo '$(srcdir)/'`vtls/sectransp.c + +vtls/libcurlu_la-vtls.lo: vtls/vtls.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vtls/libcurlu_la-vtls.lo -MD -MP -MF vtls/$(DEPDIR)/libcurlu_la-vtls.Tpo -c -o vtls/libcurlu_la-vtls.lo `test -f 'vtls/vtls.c' || echo '$(srcdir)/'`vtls/vtls.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurlu_la-vtls.Tpo vtls/$(DEPDIR)/libcurlu_la-vtls.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/vtls.c' object='vtls/libcurlu_la-vtls.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurlu_la-vtls.lo `test -f 'vtls/vtls.c' || echo '$(srcdir)/'`vtls/vtls.c + +vtls/libcurlu_la-wolfssl.lo: vtls/wolfssl.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vtls/libcurlu_la-wolfssl.lo -MD -MP -MF vtls/$(DEPDIR)/libcurlu_la-wolfssl.Tpo -c -o vtls/libcurlu_la-wolfssl.lo `test -f 'vtls/wolfssl.c' || echo '$(srcdir)/'`vtls/wolfssl.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurlu_la-wolfssl.Tpo vtls/$(DEPDIR)/libcurlu_la-wolfssl.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/wolfssl.c' object='vtls/libcurlu_la-wolfssl.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurlu_la-wolfssl.lo `test -f 'vtls/wolfssl.c' || echo '$(srcdir)/'`vtls/wolfssl.c + +vtls/libcurlu_la-x509asn1.lo: vtls/x509asn1.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vtls/libcurlu_la-x509asn1.lo -MD -MP -MF vtls/$(DEPDIR)/libcurlu_la-x509asn1.Tpo -c -o vtls/libcurlu_la-x509asn1.lo `test -f 'vtls/x509asn1.c' || echo '$(srcdir)/'`vtls/x509asn1.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vtls/$(DEPDIR)/libcurlu_la-x509asn1.Tpo vtls/$(DEPDIR)/libcurlu_la-x509asn1.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vtls/x509asn1.c' object='vtls/libcurlu_la-x509asn1.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vtls/libcurlu_la-x509asn1.lo `test -f 'vtls/x509asn1.c' || echo '$(srcdir)/'`vtls/x509asn1.c + +vquic/libcurlu_la-curl_msh3.lo: vquic/curl_msh3.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vquic/libcurlu_la-curl_msh3.lo -MD -MP -MF vquic/$(DEPDIR)/libcurlu_la-curl_msh3.Tpo -c -o vquic/libcurlu_la-curl_msh3.lo `test -f 'vquic/curl_msh3.c' || echo '$(srcdir)/'`vquic/curl_msh3.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vquic/$(DEPDIR)/libcurlu_la-curl_msh3.Tpo vquic/$(DEPDIR)/libcurlu_la-curl_msh3.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vquic/curl_msh3.c' object='vquic/libcurlu_la-curl_msh3.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vquic/libcurlu_la-curl_msh3.lo `test -f 'vquic/curl_msh3.c' || echo '$(srcdir)/'`vquic/curl_msh3.c + +vquic/libcurlu_la-curl_ngtcp2.lo: vquic/curl_ngtcp2.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vquic/libcurlu_la-curl_ngtcp2.lo -MD -MP -MF vquic/$(DEPDIR)/libcurlu_la-curl_ngtcp2.Tpo -c -o vquic/libcurlu_la-curl_ngtcp2.lo `test -f 'vquic/curl_ngtcp2.c' || echo '$(srcdir)/'`vquic/curl_ngtcp2.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vquic/$(DEPDIR)/libcurlu_la-curl_ngtcp2.Tpo vquic/$(DEPDIR)/libcurlu_la-curl_ngtcp2.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vquic/curl_ngtcp2.c' object='vquic/libcurlu_la-curl_ngtcp2.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vquic/libcurlu_la-curl_ngtcp2.lo `test -f 'vquic/curl_ngtcp2.c' || echo '$(srcdir)/'`vquic/curl_ngtcp2.c + +vquic/libcurlu_la-curl_osslq.lo: vquic/curl_osslq.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vquic/libcurlu_la-curl_osslq.lo -MD -MP -MF vquic/$(DEPDIR)/libcurlu_la-curl_osslq.Tpo -c -o vquic/libcurlu_la-curl_osslq.lo `test -f 'vquic/curl_osslq.c' || echo '$(srcdir)/'`vquic/curl_osslq.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vquic/$(DEPDIR)/libcurlu_la-curl_osslq.Tpo vquic/$(DEPDIR)/libcurlu_la-curl_osslq.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vquic/curl_osslq.c' object='vquic/libcurlu_la-curl_osslq.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vquic/libcurlu_la-curl_osslq.lo `test -f 'vquic/curl_osslq.c' || echo '$(srcdir)/'`vquic/curl_osslq.c + +vquic/libcurlu_la-curl_quiche.lo: vquic/curl_quiche.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vquic/libcurlu_la-curl_quiche.lo -MD -MP -MF vquic/$(DEPDIR)/libcurlu_la-curl_quiche.Tpo -c -o vquic/libcurlu_la-curl_quiche.lo `test -f 'vquic/curl_quiche.c' || echo '$(srcdir)/'`vquic/curl_quiche.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vquic/$(DEPDIR)/libcurlu_la-curl_quiche.Tpo vquic/$(DEPDIR)/libcurlu_la-curl_quiche.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vquic/curl_quiche.c' object='vquic/libcurlu_la-curl_quiche.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vquic/libcurlu_la-curl_quiche.lo `test -f 'vquic/curl_quiche.c' || echo '$(srcdir)/'`vquic/curl_quiche.c + +vquic/libcurlu_la-vquic.lo: vquic/vquic.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vquic/libcurlu_la-vquic.lo -MD -MP -MF vquic/$(DEPDIR)/libcurlu_la-vquic.Tpo -c -o vquic/libcurlu_la-vquic.lo `test -f 'vquic/vquic.c' || echo '$(srcdir)/'`vquic/vquic.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vquic/$(DEPDIR)/libcurlu_la-vquic.Tpo vquic/$(DEPDIR)/libcurlu_la-vquic.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vquic/vquic.c' object='vquic/libcurlu_la-vquic.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vquic/libcurlu_la-vquic.lo `test -f 'vquic/vquic.c' || echo '$(srcdir)/'`vquic/vquic.c + +vquic/libcurlu_la-vquic-tls.lo: vquic/vquic-tls.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vquic/libcurlu_la-vquic-tls.lo -MD -MP -MF vquic/$(DEPDIR)/libcurlu_la-vquic-tls.Tpo -c -o vquic/libcurlu_la-vquic-tls.lo `test -f 'vquic/vquic-tls.c' || echo '$(srcdir)/'`vquic/vquic-tls.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vquic/$(DEPDIR)/libcurlu_la-vquic-tls.Tpo vquic/$(DEPDIR)/libcurlu_la-vquic-tls.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vquic/vquic-tls.c' object='vquic/libcurlu_la-vquic-tls.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vquic/libcurlu_la-vquic-tls.lo `test -f 'vquic/vquic-tls.c' || echo '$(srcdir)/'`vquic/vquic-tls.c + +vssh/libcurlu_la-libssh.lo: vssh/libssh.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vssh/libcurlu_la-libssh.lo -MD -MP -MF vssh/$(DEPDIR)/libcurlu_la-libssh.Tpo -c -o vssh/libcurlu_la-libssh.lo `test -f 'vssh/libssh.c' || echo '$(srcdir)/'`vssh/libssh.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vssh/$(DEPDIR)/libcurlu_la-libssh.Tpo vssh/$(DEPDIR)/libcurlu_la-libssh.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vssh/libssh.c' object='vssh/libcurlu_la-libssh.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vssh/libcurlu_la-libssh.lo `test -f 'vssh/libssh.c' || echo '$(srcdir)/'`vssh/libssh.c + +vssh/libcurlu_la-libssh2.lo: vssh/libssh2.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vssh/libcurlu_la-libssh2.lo -MD -MP -MF vssh/$(DEPDIR)/libcurlu_la-libssh2.Tpo -c -o vssh/libcurlu_la-libssh2.lo `test -f 'vssh/libssh2.c' || echo '$(srcdir)/'`vssh/libssh2.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vssh/$(DEPDIR)/libcurlu_la-libssh2.Tpo vssh/$(DEPDIR)/libcurlu_la-libssh2.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vssh/libssh2.c' object='vssh/libcurlu_la-libssh2.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vssh/libcurlu_la-libssh2.lo `test -f 'vssh/libssh2.c' || echo '$(srcdir)/'`vssh/libssh2.c + +vssh/libcurlu_la-wolfssh.lo: vssh/wolfssh.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -MT vssh/libcurlu_la-wolfssh.lo -MD -MP -MF vssh/$(DEPDIR)/libcurlu_la-wolfssh.Tpo -c -o vssh/libcurlu_la-wolfssh.lo `test -f 'vssh/wolfssh.c' || echo '$(srcdir)/'`vssh/wolfssh.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) vssh/$(DEPDIR)/libcurlu_la-wolfssh.Tpo vssh/$(DEPDIR)/libcurlu_la-wolfssh.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='vssh/wolfssh.c' object='vssh/libcurlu_la-wolfssh.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcurlu_la_CPPFLAGS) $(CPPFLAGS) $(libcurlu_la_CFLAGS) $(CFLAGS) -c -o vssh/libcurlu_la-wolfssh.lo `test -f 'vssh/wolfssh.c' || echo '$(srcdir)/'`vssh/wolfssh.c + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + -rm -rf vauth/.libs vauth/_libs + -rm -rf vquic/.libs vquic/_libs + -rm -rf vssh/.libs vssh/_libs + -rm -rf vtls/.libs vtls/_libs + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ + here=`pwd`; \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags +distdir: $(BUILT_SOURCES) + $(MAKE) $(AM_MAKEFLAGS) distdir-am + +distdir-am: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +@CURLDEBUG_FALSE@all-local: +all-am: Makefile $(LTLIBRARIES) curl_config.h all-local +installdirs: + for dir in "$(DESTDIR)$(libdir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + -rm -f vauth/$(DEPDIR)/$(am__dirstamp) + -rm -f vauth/$(am__dirstamp) + -rm -f vquic/$(DEPDIR)/$(am__dirstamp) + -rm -f vquic/$(am__dirstamp) + -rm -f vssh/$(DEPDIR)/$(am__dirstamp) + -rm -f vssh/$(am__dirstamp) + -rm -f vtls/$(DEPDIR)/$(am__dirstamp) + -rm -f vtls/$(am__dirstamp) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ + clean-noinstLTLIBRARIES mostlyclean-am + +distclean: distclean-am + -rm -f ./$(DEPDIR)/libcurl_la-altsvc.Plo + -rm -f ./$(DEPDIR)/libcurl_la-amigaos.Plo + -rm -f ./$(DEPDIR)/libcurl_la-asyn-ares.Plo + -rm -f ./$(DEPDIR)/libcurl_la-asyn-thread.Plo + -rm -f ./$(DEPDIR)/libcurl_la-base64.Plo + -rm -f ./$(DEPDIR)/libcurl_la-bufq.Plo + -rm -f ./$(DEPDIR)/libcurl_la-bufref.Plo + -rm -f ./$(DEPDIR)/libcurl_la-c-hyper.Plo + -rm -f ./$(DEPDIR)/libcurl_la-cf-h1-proxy.Plo + -rm -f ./$(DEPDIR)/libcurl_la-cf-h2-proxy.Plo + -rm -f ./$(DEPDIR)/libcurl_la-cf-haproxy.Plo + -rm -f ./$(DEPDIR)/libcurl_la-cf-https-connect.Plo + -rm -f ./$(DEPDIR)/libcurl_la-cf-socket.Plo + -rm -f ./$(DEPDIR)/libcurl_la-cfilters.Plo + -rm -f ./$(DEPDIR)/libcurl_la-conncache.Plo + -rm -f ./$(DEPDIR)/libcurl_la-connect.Plo + -rm -f ./$(DEPDIR)/libcurl_la-content_encoding.Plo + -rm -f ./$(DEPDIR)/libcurl_la-cookie.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_addrinfo.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_des.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_endian.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_fnmatch.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_get_line.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_gethostname.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_gssapi.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_memrchr.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_multibyte.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_ntlm_core.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_path.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_range.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_rtmp.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_sasl.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_sha512_256.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_sspi.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_threads.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_trc.Plo + -rm -f ./$(DEPDIR)/libcurl_la-cw-out.Plo + -rm -f ./$(DEPDIR)/libcurl_la-dict.Plo + -rm -f ./$(DEPDIR)/libcurl_la-dllmain.Plo + -rm -f ./$(DEPDIR)/libcurl_la-doh.Plo + -rm -f ./$(DEPDIR)/libcurl_la-dynbuf.Plo + -rm -f ./$(DEPDIR)/libcurl_la-dynhds.Plo + -rm -f ./$(DEPDIR)/libcurl_la-easy.Plo + -rm -f ./$(DEPDIR)/libcurl_la-easygetopt.Plo + -rm -f ./$(DEPDIR)/libcurl_la-easyoptions.Plo + -rm -f ./$(DEPDIR)/libcurl_la-escape.Plo + -rm -f ./$(DEPDIR)/libcurl_la-file.Plo + -rm -f ./$(DEPDIR)/libcurl_la-fileinfo.Plo + -rm -f ./$(DEPDIR)/libcurl_la-fopen.Plo + -rm -f ./$(DEPDIR)/libcurl_la-formdata.Plo + -rm -f ./$(DEPDIR)/libcurl_la-ftp.Plo + -rm -f ./$(DEPDIR)/libcurl_la-ftplistparser.Plo + -rm -f ./$(DEPDIR)/libcurl_la-getenv.Plo + -rm -f ./$(DEPDIR)/libcurl_la-getinfo.Plo + -rm -f ./$(DEPDIR)/libcurl_la-gopher.Plo + -rm -f ./$(DEPDIR)/libcurl_la-hash.Plo + -rm -f ./$(DEPDIR)/libcurl_la-headers.Plo + -rm -f ./$(DEPDIR)/libcurl_la-hmac.Plo + -rm -f ./$(DEPDIR)/libcurl_la-hostasyn.Plo + -rm -f ./$(DEPDIR)/libcurl_la-hostip.Plo + -rm -f ./$(DEPDIR)/libcurl_la-hostip4.Plo + -rm -f ./$(DEPDIR)/libcurl_la-hostip6.Plo + -rm -f ./$(DEPDIR)/libcurl_la-hostsyn.Plo + -rm -f ./$(DEPDIR)/libcurl_la-hsts.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http1.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http2.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http_aws_sigv4.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http_chunks.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http_digest.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http_negotiate.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http_ntlm.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http_proxy.Plo + -rm -f ./$(DEPDIR)/libcurl_la-idn.Plo + -rm -f ./$(DEPDIR)/libcurl_la-if2ip.Plo + -rm -f ./$(DEPDIR)/libcurl_la-imap.Plo + -rm -f ./$(DEPDIR)/libcurl_la-inet_ntop.Plo + -rm -f ./$(DEPDIR)/libcurl_la-inet_pton.Plo + -rm -f ./$(DEPDIR)/libcurl_la-krb5.Plo + -rm -f ./$(DEPDIR)/libcurl_la-ldap.Plo + -rm -f ./$(DEPDIR)/libcurl_la-llist.Plo + -rm -f ./$(DEPDIR)/libcurl_la-macos.Plo + -rm -f ./$(DEPDIR)/libcurl_la-md4.Plo + -rm -f ./$(DEPDIR)/libcurl_la-md5.Plo + -rm -f ./$(DEPDIR)/libcurl_la-memdebug.Plo + -rm -f ./$(DEPDIR)/libcurl_la-mime.Plo + -rm -f ./$(DEPDIR)/libcurl_la-mprintf.Plo + -rm -f ./$(DEPDIR)/libcurl_la-mqtt.Plo + -rm -f ./$(DEPDIR)/libcurl_la-multi.Plo + -rm -f ./$(DEPDIR)/libcurl_la-netrc.Plo + -rm -f ./$(DEPDIR)/libcurl_la-nonblock.Plo + -rm -f ./$(DEPDIR)/libcurl_la-noproxy.Plo + -rm -f ./$(DEPDIR)/libcurl_la-openldap.Plo + -rm -f ./$(DEPDIR)/libcurl_la-parsedate.Plo + -rm -f ./$(DEPDIR)/libcurl_la-pingpong.Plo + -rm -f ./$(DEPDIR)/libcurl_la-pop3.Plo + -rm -f ./$(DEPDIR)/libcurl_la-progress.Plo + -rm -f ./$(DEPDIR)/libcurl_la-psl.Plo + -rm -f ./$(DEPDIR)/libcurl_la-rand.Plo + -rm -f ./$(DEPDIR)/libcurl_la-rename.Plo + -rm -f ./$(DEPDIR)/libcurl_la-request.Plo + -rm -f ./$(DEPDIR)/libcurl_la-rtsp.Plo + -rm -f ./$(DEPDIR)/libcurl_la-select.Plo + -rm -f ./$(DEPDIR)/libcurl_la-sendf.Plo + -rm -f ./$(DEPDIR)/libcurl_la-setopt.Plo + -rm -f ./$(DEPDIR)/libcurl_la-sha256.Plo + -rm -f ./$(DEPDIR)/libcurl_la-share.Plo + -rm -f ./$(DEPDIR)/libcurl_la-slist.Plo + -rm -f ./$(DEPDIR)/libcurl_la-smb.Plo + -rm -f ./$(DEPDIR)/libcurl_la-smtp.Plo + -rm -f ./$(DEPDIR)/libcurl_la-socketpair.Plo + -rm -f ./$(DEPDIR)/libcurl_la-socks.Plo + -rm -f ./$(DEPDIR)/libcurl_la-socks_gssapi.Plo + -rm -f ./$(DEPDIR)/libcurl_la-socks_sspi.Plo + -rm -f ./$(DEPDIR)/libcurl_la-speedcheck.Plo + -rm -f ./$(DEPDIR)/libcurl_la-splay.Plo + -rm -f ./$(DEPDIR)/libcurl_la-strcase.Plo + -rm -f ./$(DEPDIR)/libcurl_la-strdup.Plo + -rm -f ./$(DEPDIR)/libcurl_la-strerror.Plo + -rm -f ./$(DEPDIR)/libcurl_la-strtok.Plo + -rm -f ./$(DEPDIR)/libcurl_la-strtoofft.Plo + -rm -f ./$(DEPDIR)/libcurl_la-system_win32.Plo + -rm -f ./$(DEPDIR)/libcurl_la-telnet.Plo + -rm -f ./$(DEPDIR)/libcurl_la-tftp.Plo + -rm -f ./$(DEPDIR)/libcurl_la-timediff.Plo + -rm -f ./$(DEPDIR)/libcurl_la-timeval.Plo + -rm -f ./$(DEPDIR)/libcurl_la-transfer.Plo + -rm -f ./$(DEPDIR)/libcurl_la-url.Plo + -rm -f ./$(DEPDIR)/libcurl_la-urlapi.Plo + -rm -f ./$(DEPDIR)/libcurl_la-version.Plo + -rm -f ./$(DEPDIR)/libcurl_la-version_win32.Plo + -rm -f ./$(DEPDIR)/libcurl_la-warnless.Plo + -rm -f ./$(DEPDIR)/libcurl_la-ws.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-altsvc.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-amigaos.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-asyn-ares.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-asyn-thread.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-base64.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-bufq.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-bufref.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-c-hyper.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-cf-h1-proxy.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-cf-h2-proxy.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-cf-haproxy.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-cf-https-connect.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-cf-socket.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-cfilters.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-conncache.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-connect.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-content_encoding.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-cookie.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_addrinfo.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_des.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_endian.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_fnmatch.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_get_line.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_gethostname.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_gssapi.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_memrchr.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_multibyte.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_ntlm_core.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_path.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_range.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_rtmp.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_sasl.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_sha512_256.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_sspi.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_threads.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_trc.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-cw-out.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-dict.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-dllmain.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-doh.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-dynbuf.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-dynhds.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-easy.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-easygetopt.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-easyoptions.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-escape.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-file.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-fileinfo.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-fopen.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-formdata.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-ftp.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-ftplistparser.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-getenv.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-getinfo.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-gopher.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-hash.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-headers.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-hmac.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-hostasyn.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-hostip.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-hostip4.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-hostip6.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-hostsyn.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-hsts.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http1.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http2.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http_aws_sigv4.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http_chunks.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http_digest.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http_negotiate.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http_ntlm.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http_proxy.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-idn.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-if2ip.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-imap.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-inet_ntop.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-inet_pton.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-krb5.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-ldap.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-llist.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-macos.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-md4.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-md5.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-memdebug.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-mime.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-mprintf.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-mqtt.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-multi.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-netrc.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-nonblock.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-noproxy.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-openldap.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-parsedate.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-pingpong.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-pop3.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-progress.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-psl.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-rand.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-rename.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-request.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-rtsp.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-select.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-sendf.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-setopt.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-sha256.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-share.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-slist.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-smb.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-smtp.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-socketpair.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-socks.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-socks_gssapi.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-socks_sspi.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-speedcheck.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-splay.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-strcase.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-strdup.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-strerror.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-strtok.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-strtoofft.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-system_win32.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-telnet.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-tftp.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-timediff.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-timeval.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-transfer.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-url.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-urlapi.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-version.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-version_win32.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-warnless.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-ws.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-cleartext.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-cram.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-digest.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-digest_sspi.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-gsasl.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-krb5_gssapi.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-krb5_sspi.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-ntlm.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-ntlm_sspi.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-oauth2.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-spnego_gssapi.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-spnego_sspi.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-vauth.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-cleartext.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-cram.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-digest.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-digest_sspi.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-gsasl.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-krb5_gssapi.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-krb5_sspi.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-ntlm.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-ntlm_sspi.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-oauth2.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-spnego_gssapi.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-spnego_sspi.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-vauth.Plo + -rm -f vquic/$(DEPDIR)/libcurl_la-curl_msh3.Plo + -rm -f vquic/$(DEPDIR)/libcurl_la-curl_ngtcp2.Plo + -rm -f vquic/$(DEPDIR)/libcurl_la-curl_osslq.Plo + -rm -f vquic/$(DEPDIR)/libcurl_la-curl_quiche.Plo + -rm -f vquic/$(DEPDIR)/libcurl_la-vquic-tls.Plo + -rm -f vquic/$(DEPDIR)/libcurl_la-vquic.Plo + -rm -f vquic/$(DEPDIR)/libcurlu_la-curl_msh3.Plo + -rm -f vquic/$(DEPDIR)/libcurlu_la-curl_ngtcp2.Plo + -rm -f vquic/$(DEPDIR)/libcurlu_la-curl_osslq.Plo + -rm -f vquic/$(DEPDIR)/libcurlu_la-curl_quiche.Plo + -rm -f vquic/$(DEPDIR)/libcurlu_la-vquic-tls.Plo + -rm -f vquic/$(DEPDIR)/libcurlu_la-vquic.Plo + -rm -f vssh/$(DEPDIR)/libcurl_la-libssh.Plo + -rm -f vssh/$(DEPDIR)/libcurl_la-libssh2.Plo + -rm -f vssh/$(DEPDIR)/libcurl_la-wolfssh.Plo + -rm -f vssh/$(DEPDIR)/libcurlu_la-libssh.Plo + -rm -f vssh/$(DEPDIR)/libcurlu_la-libssh2.Plo + -rm -f vssh/$(DEPDIR)/libcurlu_la-wolfssh.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-bearssl.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-cipher_suite.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-gtls.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-hostcheck.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-keylog.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-mbedtls.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-mbedtls_threadlock.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-openssl.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-rustls.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-schannel.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-schannel_verify.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-sectransp.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-vtls.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-wolfssl.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-x509asn1.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-bearssl.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-cipher_suite.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-gtls.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-hostcheck.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-keylog.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-mbedtls.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-mbedtls_threadlock.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-openssl.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-rustls.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-schannel.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-schannel_verify.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-sectransp.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-vtls.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-wolfssl.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-x509asn1.Plo + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-hdr distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: install-libLTLIBRARIES + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f ./$(DEPDIR)/libcurl_la-altsvc.Plo + -rm -f ./$(DEPDIR)/libcurl_la-amigaos.Plo + -rm -f ./$(DEPDIR)/libcurl_la-asyn-ares.Plo + -rm -f ./$(DEPDIR)/libcurl_la-asyn-thread.Plo + -rm -f ./$(DEPDIR)/libcurl_la-base64.Plo + -rm -f ./$(DEPDIR)/libcurl_la-bufq.Plo + -rm -f ./$(DEPDIR)/libcurl_la-bufref.Plo + -rm -f ./$(DEPDIR)/libcurl_la-c-hyper.Plo + -rm -f ./$(DEPDIR)/libcurl_la-cf-h1-proxy.Plo + -rm -f ./$(DEPDIR)/libcurl_la-cf-h2-proxy.Plo + -rm -f ./$(DEPDIR)/libcurl_la-cf-haproxy.Plo + -rm -f ./$(DEPDIR)/libcurl_la-cf-https-connect.Plo + -rm -f ./$(DEPDIR)/libcurl_la-cf-socket.Plo + -rm -f ./$(DEPDIR)/libcurl_la-cfilters.Plo + -rm -f ./$(DEPDIR)/libcurl_la-conncache.Plo + -rm -f ./$(DEPDIR)/libcurl_la-connect.Plo + -rm -f ./$(DEPDIR)/libcurl_la-content_encoding.Plo + -rm -f ./$(DEPDIR)/libcurl_la-cookie.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_addrinfo.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_des.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_endian.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_fnmatch.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_get_line.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_gethostname.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_gssapi.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_memrchr.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_multibyte.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_ntlm_core.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_path.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_range.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_rtmp.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_sasl.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_sha512_256.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_sspi.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_threads.Plo + -rm -f ./$(DEPDIR)/libcurl_la-curl_trc.Plo + -rm -f ./$(DEPDIR)/libcurl_la-cw-out.Plo + -rm -f ./$(DEPDIR)/libcurl_la-dict.Plo + -rm -f ./$(DEPDIR)/libcurl_la-dllmain.Plo + -rm -f ./$(DEPDIR)/libcurl_la-doh.Plo + -rm -f ./$(DEPDIR)/libcurl_la-dynbuf.Plo + -rm -f ./$(DEPDIR)/libcurl_la-dynhds.Plo + -rm -f ./$(DEPDIR)/libcurl_la-easy.Plo + -rm -f ./$(DEPDIR)/libcurl_la-easygetopt.Plo + -rm -f ./$(DEPDIR)/libcurl_la-easyoptions.Plo + -rm -f ./$(DEPDIR)/libcurl_la-escape.Plo + -rm -f ./$(DEPDIR)/libcurl_la-file.Plo + -rm -f ./$(DEPDIR)/libcurl_la-fileinfo.Plo + -rm -f ./$(DEPDIR)/libcurl_la-fopen.Plo + -rm -f ./$(DEPDIR)/libcurl_la-formdata.Plo + -rm -f ./$(DEPDIR)/libcurl_la-ftp.Plo + -rm -f ./$(DEPDIR)/libcurl_la-ftplistparser.Plo + -rm -f ./$(DEPDIR)/libcurl_la-getenv.Plo + -rm -f ./$(DEPDIR)/libcurl_la-getinfo.Plo + -rm -f ./$(DEPDIR)/libcurl_la-gopher.Plo + -rm -f ./$(DEPDIR)/libcurl_la-hash.Plo + -rm -f ./$(DEPDIR)/libcurl_la-headers.Plo + -rm -f ./$(DEPDIR)/libcurl_la-hmac.Plo + -rm -f ./$(DEPDIR)/libcurl_la-hostasyn.Plo + -rm -f ./$(DEPDIR)/libcurl_la-hostip.Plo + -rm -f ./$(DEPDIR)/libcurl_la-hostip4.Plo + -rm -f ./$(DEPDIR)/libcurl_la-hostip6.Plo + -rm -f ./$(DEPDIR)/libcurl_la-hostsyn.Plo + -rm -f ./$(DEPDIR)/libcurl_la-hsts.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http1.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http2.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http_aws_sigv4.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http_chunks.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http_digest.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http_negotiate.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http_ntlm.Plo + -rm -f ./$(DEPDIR)/libcurl_la-http_proxy.Plo + -rm -f ./$(DEPDIR)/libcurl_la-idn.Plo + -rm -f ./$(DEPDIR)/libcurl_la-if2ip.Plo + -rm -f ./$(DEPDIR)/libcurl_la-imap.Plo + -rm -f ./$(DEPDIR)/libcurl_la-inet_ntop.Plo + -rm -f ./$(DEPDIR)/libcurl_la-inet_pton.Plo + -rm -f ./$(DEPDIR)/libcurl_la-krb5.Plo + -rm -f ./$(DEPDIR)/libcurl_la-ldap.Plo + -rm -f ./$(DEPDIR)/libcurl_la-llist.Plo + -rm -f ./$(DEPDIR)/libcurl_la-macos.Plo + -rm -f ./$(DEPDIR)/libcurl_la-md4.Plo + -rm -f ./$(DEPDIR)/libcurl_la-md5.Plo + -rm -f ./$(DEPDIR)/libcurl_la-memdebug.Plo + -rm -f ./$(DEPDIR)/libcurl_la-mime.Plo + -rm -f ./$(DEPDIR)/libcurl_la-mprintf.Plo + -rm -f ./$(DEPDIR)/libcurl_la-mqtt.Plo + -rm -f ./$(DEPDIR)/libcurl_la-multi.Plo + -rm -f ./$(DEPDIR)/libcurl_la-netrc.Plo + -rm -f ./$(DEPDIR)/libcurl_la-nonblock.Plo + -rm -f ./$(DEPDIR)/libcurl_la-noproxy.Plo + -rm -f ./$(DEPDIR)/libcurl_la-openldap.Plo + -rm -f ./$(DEPDIR)/libcurl_la-parsedate.Plo + -rm -f ./$(DEPDIR)/libcurl_la-pingpong.Plo + -rm -f ./$(DEPDIR)/libcurl_la-pop3.Plo + -rm -f ./$(DEPDIR)/libcurl_la-progress.Plo + -rm -f ./$(DEPDIR)/libcurl_la-psl.Plo + -rm -f ./$(DEPDIR)/libcurl_la-rand.Plo + -rm -f ./$(DEPDIR)/libcurl_la-rename.Plo + -rm -f ./$(DEPDIR)/libcurl_la-request.Plo + -rm -f ./$(DEPDIR)/libcurl_la-rtsp.Plo + -rm -f ./$(DEPDIR)/libcurl_la-select.Plo + -rm -f ./$(DEPDIR)/libcurl_la-sendf.Plo + -rm -f ./$(DEPDIR)/libcurl_la-setopt.Plo + -rm -f ./$(DEPDIR)/libcurl_la-sha256.Plo + -rm -f ./$(DEPDIR)/libcurl_la-share.Plo + -rm -f ./$(DEPDIR)/libcurl_la-slist.Plo + -rm -f ./$(DEPDIR)/libcurl_la-smb.Plo + -rm -f ./$(DEPDIR)/libcurl_la-smtp.Plo + -rm -f ./$(DEPDIR)/libcurl_la-socketpair.Plo + -rm -f ./$(DEPDIR)/libcurl_la-socks.Plo + -rm -f ./$(DEPDIR)/libcurl_la-socks_gssapi.Plo + -rm -f ./$(DEPDIR)/libcurl_la-socks_sspi.Plo + -rm -f ./$(DEPDIR)/libcurl_la-speedcheck.Plo + -rm -f ./$(DEPDIR)/libcurl_la-splay.Plo + -rm -f ./$(DEPDIR)/libcurl_la-strcase.Plo + -rm -f ./$(DEPDIR)/libcurl_la-strdup.Plo + -rm -f ./$(DEPDIR)/libcurl_la-strerror.Plo + -rm -f ./$(DEPDIR)/libcurl_la-strtok.Plo + -rm -f ./$(DEPDIR)/libcurl_la-strtoofft.Plo + -rm -f ./$(DEPDIR)/libcurl_la-system_win32.Plo + -rm -f ./$(DEPDIR)/libcurl_la-telnet.Plo + -rm -f ./$(DEPDIR)/libcurl_la-tftp.Plo + -rm -f ./$(DEPDIR)/libcurl_la-timediff.Plo + -rm -f ./$(DEPDIR)/libcurl_la-timeval.Plo + -rm -f ./$(DEPDIR)/libcurl_la-transfer.Plo + -rm -f ./$(DEPDIR)/libcurl_la-url.Plo + -rm -f ./$(DEPDIR)/libcurl_la-urlapi.Plo + -rm -f ./$(DEPDIR)/libcurl_la-version.Plo + -rm -f ./$(DEPDIR)/libcurl_la-version_win32.Plo + -rm -f ./$(DEPDIR)/libcurl_la-warnless.Plo + -rm -f ./$(DEPDIR)/libcurl_la-ws.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-altsvc.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-amigaos.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-asyn-ares.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-asyn-thread.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-base64.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-bufq.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-bufref.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-c-hyper.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-cf-h1-proxy.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-cf-h2-proxy.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-cf-haproxy.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-cf-https-connect.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-cf-socket.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-cfilters.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-conncache.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-connect.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-content_encoding.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-cookie.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_addrinfo.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_des.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_endian.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_fnmatch.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_get_line.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_gethostname.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_gssapi.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_memrchr.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_multibyte.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_ntlm_core.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_path.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_range.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_rtmp.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_sasl.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_sha512_256.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_sspi.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_threads.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-curl_trc.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-cw-out.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-dict.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-dllmain.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-doh.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-dynbuf.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-dynhds.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-easy.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-easygetopt.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-easyoptions.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-escape.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-file.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-fileinfo.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-fopen.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-formdata.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-ftp.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-ftplistparser.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-getenv.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-getinfo.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-gopher.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-hash.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-headers.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-hmac.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-hostasyn.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-hostip.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-hostip4.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-hostip6.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-hostsyn.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-hsts.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http1.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http2.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http_aws_sigv4.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http_chunks.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http_digest.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http_negotiate.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http_ntlm.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-http_proxy.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-idn.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-if2ip.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-imap.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-inet_ntop.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-inet_pton.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-krb5.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-ldap.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-llist.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-macos.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-md4.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-md5.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-memdebug.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-mime.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-mprintf.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-mqtt.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-multi.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-netrc.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-nonblock.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-noproxy.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-openldap.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-parsedate.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-pingpong.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-pop3.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-progress.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-psl.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-rand.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-rename.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-request.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-rtsp.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-select.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-sendf.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-setopt.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-sha256.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-share.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-slist.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-smb.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-smtp.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-socketpair.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-socks.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-socks_gssapi.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-socks_sspi.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-speedcheck.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-splay.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-strcase.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-strdup.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-strerror.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-strtok.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-strtoofft.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-system_win32.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-telnet.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-tftp.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-timediff.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-timeval.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-transfer.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-url.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-urlapi.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-version.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-version_win32.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-warnless.Plo + -rm -f ./$(DEPDIR)/libcurlu_la-ws.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-cleartext.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-cram.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-digest.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-digest_sspi.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-gsasl.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-krb5_gssapi.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-krb5_sspi.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-ntlm.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-ntlm_sspi.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-oauth2.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-spnego_gssapi.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-spnego_sspi.Plo + -rm -f vauth/$(DEPDIR)/libcurl_la-vauth.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-cleartext.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-cram.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-digest.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-digest_sspi.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-gsasl.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-krb5_gssapi.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-krb5_sspi.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-ntlm.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-ntlm_sspi.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-oauth2.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-spnego_gssapi.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-spnego_sspi.Plo + -rm -f vauth/$(DEPDIR)/libcurlu_la-vauth.Plo + -rm -f vquic/$(DEPDIR)/libcurl_la-curl_msh3.Plo + -rm -f vquic/$(DEPDIR)/libcurl_la-curl_ngtcp2.Plo + -rm -f vquic/$(DEPDIR)/libcurl_la-curl_osslq.Plo + -rm -f vquic/$(DEPDIR)/libcurl_la-curl_quiche.Plo + -rm -f vquic/$(DEPDIR)/libcurl_la-vquic-tls.Plo + -rm -f vquic/$(DEPDIR)/libcurl_la-vquic.Plo + -rm -f vquic/$(DEPDIR)/libcurlu_la-curl_msh3.Plo + -rm -f vquic/$(DEPDIR)/libcurlu_la-curl_ngtcp2.Plo + -rm -f vquic/$(DEPDIR)/libcurlu_la-curl_osslq.Plo + -rm -f vquic/$(DEPDIR)/libcurlu_la-curl_quiche.Plo + -rm -f vquic/$(DEPDIR)/libcurlu_la-vquic-tls.Plo + -rm -f vquic/$(DEPDIR)/libcurlu_la-vquic.Plo + -rm -f vssh/$(DEPDIR)/libcurl_la-libssh.Plo + -rm -f vssh/$(DEPDIR)/libcurl_la-libssh2.Plo + -rm -f vssh/$(DEPDIR)/libcurl_la-wolfssh.Plo + -rm -f vssh/$(DEPDIR)/libcurlu_la-libssh.Plo + -rm -f vssh/$(DEPDIR)/libcurlu_la-libssh2.Plo + -rm -f vssh/$(DEPDIR)/libcurlu_la-wolfssh.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-bearssl.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-cipher_suite.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-gtls.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-hostcheck.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-keylog.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-mbedtls.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-mbedtls_threadlock.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-openssl.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-rustls.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-schannel.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-schannel_verify.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-sectransp.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-vtls.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-wolfssl.Plo + -rm -f vtls/$(DEPDIR)/libcurl_la-x509asn1.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-bearssl.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-cipher_suite.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-gtls.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-hostcheck.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-keylog.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-mbedtls.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-mbedtls_threadlock.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-openssl.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-rustls.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-schannel.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-schannel_verify.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-sectransp.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-vtls.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-wolfssl.Plo + -rm -f vtls/$(DEPDIR)/libcurlu_la-x509asn1.Plo + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-libLTLIBRARIES + +.MAKE: all install-am install-strip + +.PHONY: CTAGS GTAGS TAGS all all-am all-local am--depfiles check \ + check-am clean clean-generic clean-libLTLIBRARIES \ + clean-libtool clean-noinstLTLIBRARIES cscopelist-am ctags \ + ctags-am distclean distclean-compile distclean-generic \ + distclean-hdr distclean-libtool distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-libLTLIBRARIES \ + install-man install-pdf install-pdf-am install-ps \ + install-ps-am install-strip installcheck installcheck-am \ + installdirs maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ + uninstall-am uninstall-libLTLIBRARIES + +.PRECIOUS: Makefile + +# This flag accepts an argument of the form current[:revision[:age]]. So, +# passing -version-info 3:12:1 sets current to 3, revision to 12, and age to +# 1. +# +# Here's the simplified rule guide on how to change -version-info: +# (current version is C:R:A) +# +# 1. if there are only source changes, use C:R+1:A +# 2. if interfaces were added use C+1:0:A+1 +# 3. if interfaces were removed, then use C+1:0:0 +# +# For the full guide on libcurl ABI rules, see docs/libcurl/ABI +@HAVE_WINDRES_TRUE@@USE_CPPFLAG_CURL_STATICLIB_FALSE@$(LIB_RCFILES): $(top_srcdir)/include/curl/curlver.h + +checksrc: + $(CHECKSRC)(@PERL@ $(top_srcdir)/scripts/checksrc.pl -D$(srcdir) \ + -W$(srcdir)/curl_config.h $(srcdir)/*.[ch] $(srcdir)/vauth/*.[ch] \ + $(srcdir)/vtls/*.[ch] $(srcdir)/vquic/*.[ch] $(srcdir)/vssh/*.[ch]) + +# for debug builds, we scan the sources on all regular make invokes +@CURLDEBUG_TRUE@all-local: checksrc + +tidy: + $(TIDY) $(CSOURCES) $(TIDYFLAGS) -- $(AM_CPPFLAGS) $(CPPFLAGS) -DHAVE_CONFIG_H + +optiontable: + perl optiontable.pl < $(top_srcdir)/include/curl/curl.h > easyoptions.c + +@HAVE_WINDRES_TRUE@.rc.lo: +@HAVE_WINDRES_TRUE@ $(LIBTOOL) --tag=RC --mode=compile $(RC) -I$(top_srcdir)/include $(RCFLAGS) -i $< -o $@ + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/third_party/curl/lib/Makefile.inc b/third_party/curl/lib/Makefile.inc new file mode 100644 index 0000000..66680f3 --- /dev/null +++ b/third_party/curl/lib/Makefile.inc @@ -0,0 +1,381 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +LIB_VAUTH_CFILES = \ + vauth/cleartext.c \ + vauth/cram.c \ + vauth/digest.c \ + vauth/digest_sspi.c \ + vauth/gsasl.c \ + vauth/krb5_gssapi.c \ + vauth/krb5_sspi.c \ + vauth/ntlm.c \ + vauth/ntlm_sspi.c \ + vauth/oauth2.c \ + vauth/spnego_gssapi.c \ + vauth/spnego_sspi.c \ + vauth/vauth.c + +LIB_VAUTH_HFILES = \ + vauth/digest.h \ + vauth/ntlm.h \ + vauth/vauth.h + +LIB_VTLS_CFILES = \ + vtls/bearssl.c \ + vtls/cipher_suite.c \ + vtls/gtls.c \ + vtls/hostcheck.c \ + vtls/keylog.c \ + vtls/mbedtls.c \ + vtls/mbedtls_threadlock.c \ + vtls/openssl.c \ + vtls/rustls.c \ + vtls/schannel.c \ + vtls/schannel_verify.c \ + vtls/sectransp.c \ + vtls/vtls.c \ + vtls/wolfssl.c \ + vtls/x509asn1.c + +LIB_VTLS_HFILES = \ + vtls/bearssl.h \ + vtls/cipher_suite.h \ + vtls/gtls.h \ + vtls/hostcheck.h \ + vtls/keylog.h \ + vtls/mbedtls.h \ + vtls/mbedtls_threadlock.h \ + vtls/openssl.h \ + vtls/rustls.h \ + vtls/schannel.h \ + vtls/schannel_int.h \ + vtls/sectransp.h \ + vtls/vtls.h \ + vtls/vtls_int.h \ + vtls/wolfssl.h \ + vtls/x509asn1.h + +LIB_VQUIC_CFILES = \ + vquic/curl_msh3.c \ + vquic/curl_ngtcp2.c \ + vquic/curl_osslq.c \ + vquic/curl_quiche.c \ + vquic/vquic.c \ + vquic/vquic-tls.c + +LIB_VQUIC_HFILES = \ + vquic/curl_msh3.h \ + vquic/curl_ngtcp2.h \ + vquic/curl_osslq.h \ + vquic/curl_quiche.h \ + vquic/vquic.h \ + vquic/vquic_int.h \ + vquic/vquic-tls.h + +LIB_VSSH_CFILES = \ + vssh/libssh.c \ + vssh/libssh2.c \ + vssh/wolfssh.c + +LIB_VSSH_HFILES = \ + vssh/ssh.h + +LIB_CFILES = \ + altsvc.c \ + amigaos.c \ + asyn-ares.c \ + asyn-thread.c \ + base64.c \ + bufq.c \ + bufref.c \ + c-hyper.c \ + cf-h1-proxy.c \ + cf-h2-proxy.c \ + cf-haproxy.c \ + cf-https-connect.c \ + cf-socket.c \ + cfilters.c \ + conncache.c \ + connect.c \ + content_encoding.c \ + cookie.c \ + curl_addrinfo.c \ + curl_des.c \ + curl_endian.c \ + curl_fnmatch.c \ + curl_get_line.c \ + curl_gethostname.c \ + curl_gssapi.c \ + curl_memrchr.c \ + curl_multibyte.c \ + curl_ntlm_core.c \ + curl_path.c \ + curl_range.c \ + curl_rtmp.c \ + curl_sasl.c \ + curl_sha512_256.c \ + curl_sspi.c \ + curl_threads.c \ + curl_trc.c \ + cw-out.c \ + dict.c \ + dllmain.c \ + doh.c \ + dynbuf.c \ + dynhds.c \ + easy.c \ + easygetopt.c \ + easyoptions.c \ + escape.c \ + file.c \ + fileinfo.c \ + fopen.c \ + formdata.c \ + ftp.c \ + ftplistparser.c \ + getenv.c \ + getinfo.c \ + gopher.c \ + hash.c \ + headers.c \ + hmac.c \ + hostasyn.c \ + hostip.c \ + hostip4.c \ + hostip6.c \ + hostsyn.c \ + hsts.c \ + http.c \ + http1.c \ + http2.c \ + http_aws_sigv4.c \ + http_chunks.c \ + http_digest.c \ + http_negotiate.c \ + http_ntlm.c \ + http_proxy.c \ + idn.c \ + if2ip.c \ + imap.c \ + inet_ntop.c \ + inet_pton.c \ + krb5.c \ + ldap.c \ + llist.c \ + macos.c \ + md4.c \ + md5.c \ + memdebug.c \ + mime.c \ + mprintf.c \ + mqtt.c \ + multi.c \ + netrc.c \ + nonblock.c \ + noproxy.c \ + openldap.c \ + parsedate.c \ + pingpong.c \ + pop3.c \ + progress.c \ + psl.c \ + rand.c \ + rename.c \ + request.c \ + rtsp.c \ + select.c \ + sendf.c \ + setopt.c \ + sha256.c \ + share.c \ + slist.c \ + smb.c \ + smtp.c \ + socketpair.c \ + socks.c \ + socks_gssapi.c \ + socks_sspi.c \ + speedcheck.c \ + splay.c \ + strcase.c \ + strdup.c \ + strerror.c \ + strtok.c \ + strtoofft.c \ + system_win32.c \ + telnet.c \ + tftp.c \ + timediff.c \ + timeval.c \ + transfer.c \ + url.c \ + urlapi.c \ + version.c \ + version_win32.c \ + warnless.c \ + ws.c + +LIB_HFILES = \ + altsvc.h \ + amigaos.h \ + arpa_telnet.h \ + asyn.h \ + bufq.h \ + bufref.h \ + c-hyper.h \ + cf-h1-proxy.h \ + cf-h2-proxy.h \ + cf-haproxy.h \ + cf-https-connect.h \ + cf-socket.h \ + cfilters.h \ + conncache.h \ + connect.h \ + content_encoding.h \ + cookie.h \ + curl_addrinfo.h \ + curl_base64.h \ + curl_ctype.h \ + curl_des.h \ + curl_endian.h \ + curl_fnmatch.h \ + curl_get_line.h \ + curl_gethostname.h \ + curl_gssapi.h \ + curl_hmac.h \ + curl_krb5.h \ + curl_ldap.h \ + curl_md4.h \ + curl_md5.h \ + curl_memory.h \ + curl_memrchr.h \ + curl_multibyte.h \ + curl_ntlm_core.h \ + curl_path.h \ + curl_printf.h \ + curl_range.h \ + curl_rtmp.h \ + curl_sasl.h \ + curl_setup.h \ + curl_setup_once.h \ + curl_sha256.h \ + curl_sha512_256.h \ + curl_sspi.h \ + curl_threads.h \ + curl_trc.h \ + curlx.h \ + cw-out.h \ + dict.h \ + doh.h \ + dynbuf.h \ + dynhds.h \ + easy_lock.h \ + easyif.h \ + easyoptions.h \ + escape.h \ + file.h \ + fileinfo.h \ + fopen.h \ + formdata.h \ + ftp.h \ + ftplistparser.h \ + functypes.h \ + getinfo.h \ + gopher.h \ + hash.h \ + headers.h \ + hostip.h \ + hsts.h \ + http.h \ + http1.h \ + http2.h \ + http_aws_sigv4.h \ + http_chunks.h \ + http_digest.h \ + http_negotiate.h \ + http_ntlm.h \ + http_proxy.h \ + idn.h \ + if2ip.h \ + imap.h \ + inet_ntop.h \ + inet_pton.h \ + llist.h \ + macos.h \ + memdebug.h \ + mime.h \ + mqtt.h \ + multihandle.h \ + multiif.h \ + netrc.h \ + nonblock.h \ + noproxy.h \ + parsedate.h \ + pingpong.h \ + pop3.h \ + progress.h \ + psl.h \ + rand.h \ + rename.h \ + request.h \ + rtsp.h \ + select.h \ + sendf.h \ + setopt.h \ + setup-vms.h \ + share.h \ + sigpipe.h \ + slist.h \ + smb.h \ + smtp.h \ + sockaddr.h \ + socketpair.h \ + socks.h \ + speedcheck.h \ + splay.h \ + strcase.h \ + strdup.h \ + strerror.h \ + strtok.h \ + strtoofft.h \ + system_win32.h \ + telnet.h \ + tftp.h \ + timediff.h \ + timeval.h \ + transfer.h \ + url.h \ + urlapi-int.h \ + urldata.h \ + version_win32.h \ + warnless.h \ + ws.h + +LIB_RCFILES = libcurl.rc + +CSOURCES = $(LIB_CFILES) $(LIB_VAUTH_CFILES) $(LIB_VTLS_CFILES) \ + $(LIB_VQUIC_CFILES) $(LIB_VSSH_CFILES) +HHEADERS = $(LIB_HFILES) $(LIB_VAUTH_HFILES) $(LIB_VTLS_HFILES) \ + $(LIB_VQUIC_HFILES) $(LIB_VSSH_HFILES) diff --git a/third_party/curl/lib/Makefile.mk b/third_party/curl/lib/Makefile.mk new file mode 100644 index 0000000..bb6873c --- /dev/null +++ b/third_party/curl/lib/Makefile.mk @@ -0,0 +1,334 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +# Makefile to build curl parts with GCC-like toolchains and optional features. +# +# Usage: make -f Makefile.mk CFG=-feat1[-feat2][-feat3][...] +# Example: make -f Makefile.mk CFG=-zlib-ssl-libssh2-ipv6 +# +# Look for ' ?=' to find all accepted customization variables. + +# This script is reused by 'src' and 'docs/examples' Makefile.mk scripts. + +ifndef PROOT + PROOT := .. + LOCAL := 1 +endif + +### Common + +CFLAGS ?= +CPPFLAGS ?= +LDFLAGS ?= +LIBS ?= + +CROSSPREFIX ?= + +ifeq ($(CC),cc) + CC := gcc +endif +CC := $(CROSSPREFIX)$(CC) +AR := $(CROSSPREFIX)$(AR) + +TRIPLET ?= $(shell $(CC) -dumpmachine) + +BIN_EXT := + +ifneq ($(findstring msdos,$(TRIPLET)),) + # Cross-tools: https://github.com/andrewwutw/build-djgpp + MSDOS := 1 + BIN_EXT := .exe +else ifneq ($(findstring amigaos,$(TRIPLET)),) + # Cross-tools: https://github.com/bebbo/amiga-gcc + AMIGA := 1 +endif + +CPPFLAGS += -I. -I$(PROOT)/include + +### Deprecated settings. For compatibility. + +ifdef WATT_ROOT + WATT_PATH := $(realpath $(WATT_ROOT)) +endif + +### Optional features + +ifneq ($(findstring -debug,$(CFG)),) + CFLAGS += -g + CPPFLAGS += -DDEBUGBUILD +else + CPPFLAGS += -DNDEBUG +endif +ifneq ($(findstring -trackmem,$(CFG)),) + CPPFLAGS += -DCURLDEBUG +endif +ifneq ($(findstring -map,$(CFG)),) + MAP := 1 +endif + +# CPPFLAGS below are only necessary when building libcurl via 'lib' (see +# comments below about exceptions). Always include them anyway to match +# behavior of other build systems. + +ifneq ($(findstring -sync,$(CFG)),) + CPPFLAGS += -DUSE_SYNC_DNS +else ifneq ($(findstring -ares,$(CFG)),) + LIBCARES_PATH ?= $(PROOT)/../c-ares + CPPFLAGS += -DUSE_ARES + CPPFLAGS += -I"$(LIBCARES_PATH)/include" + LDFLAGS += -L"$(LIBCARES_PATH)/lib" + LIBS += -lcares +endif + +ifneq ($(findstring -rtmp,$(CFG)),) + LIBRTMP_PATH ?= $(PROOT)/../librtmp + CPPFLAGS += -DUSE_LIBRTMP + CPPFLAGS += -I"$(LIBRTMP_PATH)" + LDFLAGS += -L"$(LIBRTMP_PATH)/librtmp" + LIBS += -lrtmp + ZLIB := 1 +endif + +ifneq ($(findstring -ssh2,$(CFG)),) + LIBSSH2_PATH ?= $(PROOT)/../libssh2 + CPPFLAGS += -DUSE_LIBSSH2 + CPPFLAGS += -I"$(LIBSSH2_PATH)/include" + LDFLAGS += -L"$(LIBSSH2_PATH)/lib" + LIBS += -lssh2 +else ifneq ($(findstring -libssh,$(CFG)),) + LIBSSH_PATH ?= $(PROOT)/../libssh + CPPFLAGS += -DUSE_LIBSSH + CPPFLAGS += -I"$(LIBSSH_PATH)/include" + LDFLAGS += -L"$(LIBSSH_PATH)/lib" + LIBS += -lssh +else ifneq ($(findstring -wolfssh,$(CFG)),) + WOLFSSH_PATH ?= $(PROOT)/../wolfssh + CPPFLAGS += -DUSE_WOLFSSH + CPPFLAGS += -I"$(WOLFSSH_PATH)/include" + LDFLAGS += -L"$(WOLFSSH_PATH)/lib" + LIBS += -lwolfssh +endif + +ifneq ($(findstring -ssl,$(CFG)),) + OPENSSL_PATH ?= $(PROOT)/../openssl + CPPFLAGS += -DUSE_OPENSSL + CPPFLAGS += -DCURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG + OPENSSL_INCLUDE ?= $(OPENSSL_PATH)/include + OPENSSL_LIBPATH ?= $(OPENSSL_PATH)/lib + CPPFLAGS += -I"$(OPENSSL_INCLUDE)" + LDFLAGS += -L"$(OPENSSL_LIBPATH)" + OPENSSL_LIBS ?= -lssl -lcrypto + LIBS += $(OPENSSL_LIBS) + + ifneq ($(findstring -srp,$(CFG)),) + ifneq ($(wildcard $(OPENSSL_INCLUDE)/openssl/srp.h),) + # OpenSSL 1.0.1 and later. + CPPFLAGS += -DHAVE_OPENSSL_SRP -DUSE_TLS_SRP + endif + endif + SSLLIBS += 1 +endif +ifneq ($(findstring -wolfssl,$(CFG)),) + WOLFSSL_PATH ?= $(PROOT)/../wolfssl + CPPFLAGS += -DUSE_WOLFSSL + CPPFLAGS += -DSIZEOF_LONG_LONG=8 + CPPFLAGS += -I"$(WOLFSSL_PATH)/include" + LDFLAGS += -L"$(WOLFSSL_PATH)/lib" + LIBS += -lwolfssl + SSLLIBS += 1 +endif +ifneq ($(findstring -mbedtls,$(CFG)),) + MBEDTLS_PATH ?= $(PROOT)/../mbedtls + CPPFLAGS += -DUSE_MBEDTLS + CPPFLAGS += -I"$(MBEDTLS_PATH)/include" + LDFLAGS += -L"$(MBEDTLS_PATH)/lib" + LIBS += -lmbedtls -lmbedx509 -lmbedcrypto + SSLLIBS += 1 +endif + +ifneq ($(findstring -nghttp2,$(CFG)),) + NGHTTP2_PATH ?= $(PROOT)/../nghttp2 + CPPFLAGS += -DUSE_NGHTTP2 + CPPFLAGS += -I"$(NGHTTP2_PATH)/include" + LDFLAGS += -L"$(NGHTTP2_PATH)/lib" + LIBS += -lnghttp2 +endif + +ifeq ($(findstring -nghttp3,$(CFG))$(findstring -ngtcp2,$(CFG)),-nghttp3-ngtcp2) + NGHTTP3_PATH ?= $(PROOT)/../nghttp3 + CPPFLAGS += -DUSE_NGHTTP3 + CPPFLAGS += -I"$(NGHTTP3_PATH)/include" + LDFLAGS += -L"$(NGHTTP3_PATH)/lib" + LIBS += -lnghttp3 + + NGTCP2_PATH ?= $(PROOT)/../ngtcp2 + CPPFLAGS += -DUSE_NGTCP2 + CPPFLAGS += -I"$(NGTCP2_PATH)/include" + LDFLAGS += -L"$(NGTCP2_PATH)/lib" + + NGTCP2_LIBS ?= + ifeq ($(NGTCP2_LIBS),) + ifneq ($(findstring -ssl,$(CFG)),) + ifneq ($(wildcard $(OPENSSL_INCLUDE)/openssl/aead.h),) + NGTCP2_LIBS := -lngtcp2_crypto_boringssl + else # including libressl + NGTCP2_LIBS := -lngtcp2_crypto_quictls + endif + else ifneq ($(findstring -wolfssl,$(CFG)),) + NGTCP2_LIBS := -lngtcp2_crypto_wolfssl + endif + endif + + LIBS += -lngtcp2 $(NGTCP2_LIBS) +endif + +ifneq ($(findstring -zlib,$(CFG))$(ZLIB),) + ZLIB_PATH ?= $(PROOT)/../zlib + # These CPPFLAGS are also required when compiling the curl tool via 'src'. + CPPFLAGS += -DHAVE_LIBZ + CPPFLAGS += -I"$(ZLIB_PATH)/include" + LDFLAGS += -L"$(ZLIB_PATH)/lib" + ZLIB_LIBS ?= -lz + LIBS += $(ZLIB_LIBS) + ZLIB := 1 +endif +ifneq ($(findstring -zstd,$(CFG)),) + ZSTD_PATH ?= $(PROOT)/../zstd + CPPFLAGS += -DHAVE_ZSTD + CPPFLAGS += -I"$(ZSTD_PATH)/include" + LDFLAGS += -L"$(ZSTD_PATH)/lib" + ZSTD_LIBS ?= -lzstd + LIBS += $(ZSTD_LIBS) +endif +ifneq ($(findstring -brotli,$(CFG)),) + BROTLI_PATH ?= $(PROOT)/../brotli + CPPFLAGS += -DHAVE_BROTLI + CPPFLAGS += -I"$(BROTLI_PATH)/include" + LDFLAGS += -L"$(BROTLI_PATH)/lib" + BROTLI_LIBS ?= -lbrotlidec -lbrotlicommon + LIBS += $(BROTLI_LIBS) +endif +ifneq ($(findstring -gsasl,$(CFG)),) + LIBGSASL_PATH ?= $(PROOT)/../gsasl + CPPFLAGS += -DUSE_GSASL + CPPFLAGS += -I"$(LIBGSASL_PATH)/include" + LDFLAGS += -L"$(LIBGSASL_PATH)/lib" + LIBS += -lgsasl +endif + +ifneq ($(findstring -idn2,$(CFG)),) + LIBIDN2_PATH ?= $(PROOT)/../libidn2 + CPPFLAGS += -DUSE_LIBIDN2 + CPPFLAGS += -I"$(LIBIDN2_PATH)/include" + LDFLAGS += -L"$(LIBIDN2_PATH)/lib" + LIBS += -lidn2 + +ifneq ($(findstring -psl,$(CFG)),) + LIBPSL_PATH ?= $(PROOT)/../libpsl + CPPFLAGS += -DUSE_LIBPSL + CPPFLAGS += -I"$(LIBPSL_PATH)/include" + LDFLAGS += -L"$(LIBPSL_PATH)/lib" + LIBS += -lpsl +endif +endif + +ifneq ($(findstring -ipv6,$(CFG)),) + CPPFLAGS += -DUSE_IPV6 +endif + +ifneq ($(findstring -watt,$(CFG))$(MSDOS),) + WATT_PATH ?= $(PROOT)/../watt + CPPFLAGS += -I"$(WATT_PATH)/inc" + LDFLAGS += -L"$(WATT_PATH)/lib" + LIBS += -lwatt +endif + +ifneq ($(findstring 11,$(subst $(subst ,, ),,$(SSLLIBS))),) + CPPFLAGS += -DCURL_WITH_MULTI_SSL +endif + +### Common rules + +OBJ_DIR := $(TRIPLET) + +ifneq ($(findstring /sh,$(SHELL)),) +DEL = rm -f $1 +COPY = -cp -afv $1 $2 +MKDIR = mkdir -p $1 +RMDIR = rm -fr $1 +WHICH = $(SHELL) -c "command -v $1" +else +DEL = -del 2>NUL /q /f $(subst /,\,$1) +COPY = -copy 2>NUL /y $(subst /,\,$1) $(subst /,\,$2) +MKDIR = -md 2>NUL $(subst /,\,$1) +RMDIR = -rd 2>NUL /q /s $(subst /,\,$1) +WHICH = where $1 +endif + +all: $(TARGETS) + +$(OBJ_DIR): + -$(call MKDIR, $(OBJ_DIR)) + +$(OBJ_DIR)/%.o: %.c + $(CC) -W -Wall $(CFLAGS) $(CPPFLAGS) -c $< -o $@ + +clean: + @$(call DEL, $(TOCLEAN)) + @$(RMDIR) $(OBJ_DIR) + +distclean vclean: clean + @$(call DEL, $(TARGETS) $(TOVCLEAN)) + +### Local + +ifdef LOCAL + +CPPFLAGS += -DBUILDING_LIBCURL + +### Sources and targets + +# Provides CSOURCES, HHEADERS +include Makefile.inc + +vpath %.c vauth vquic vssh vtls + +libcurl_a_LIBRARY := libcurl.a + +TARGETS := $(libcurl_a_LIBRARY) + +libcurl_a_OBJECTS := $(patsubst %.c,$(OBJ_DIR)/%.o,$(notdir $(strip $(CSOURCES)))) +libcurl_a_DEPENDENCIES := $(strip $(CSOURCES) $(HHEADERS)) + +TOCLEAN := +TOVCLEAN := + +### Rules + +$(libcurl_a_LIBRARY): $(libcurl_a_OBJECTS) $(libcurl_a_DEPENDENCIES) + @$(call DEL, $@) + $(AR) rcs $@ $(libcurl_a_OBJECTS) + +all: $(OBJ_DIR) $(TARGETS) +endif diff --git a/third_party/curl/lib/Makefile.soname b/third_party/curl/lib/Makefile.soname new file mode 100644 index 0000000..02e003a --- /dev/null +++ b/third_party/curl/lib/Makefile.soname @@ -0,0 +1,42 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +VERSIONCHANGE=12 +VERSIONADD=0 +VERSIONDEL=8 + +# libtool version: +VERSIONINFO=-version-info $(VERSIONCHANGE):$(VERSIONADD):$(VERSIONDEL) +# This flag accepts an argument of the form current[:revision[:age]]. So, +# passing -version-info 3:12:1 sets current to 3, revision to 12, and age to +# 1. +# +# Here's the simplified rule guide on how to change -version-info: +# (current version is C:R:A) +# +# 1. if there are only source changes, use C:R+1:A +# 2. if interfaces were added use C+1:0:A+1 +# 3. if interfaces were removed, then use C+1:0:0 +# +# For the full guide on libcurl ABI rules, see docs/libcurl/ABI diff --git a/third_party/curl/lib/altsvc.c b/third_party/curl/lib/altsvc.c new file mode 100644 index 0000000..b72a596 --- /dev/null +++ b/third_party/curl/lib/altsvc.c @@ -0,0 +1,708 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * The Alt-Svc: header is defined in RFC 7838: + * https://datatracker.ietf.org/doc/html/rfc7838 + */ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_ALTSVC) +#include +#include "urldata.h" +#include "altsvc.h" +#include "curl_get_line.h" +#include "strcase.h" +#include "parsedate.h" +#include "sendf.h" +#include "warnless.h" +#include "fopen.h" +#include "rename.h" +#include "strdup.h" +#include "inet_pton.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#define MAX_ALTSVC_LINE 4095 +#define MAX_ALTSVC_DATELENSTR "64" +#define MAX_ALTSVC_DATELEN 64 +#define MAX_ALTSVC_HOSTLENSTR "512" +#define MAX_ALTSVC_HOSTLEN 512 +#define MAX_ALTSVC_ALPNLENSTR "10" +#define MAX_ALTSVC_ALPNLEN 10 + +#define H3VERSION "h3" + +static enum alpnid alpn2alpnid(char *name) +{ + if(strcasecompare(name, "h1")) + return ALPN_h1; + if(strcasecompare(name, "h2")) + return ALPN_h2; + if(strcasecompare(name, H3VERSION)) + return ALPN_h3; + return ALPN_none; /* unknown, probably rubbish input */ +} + +/* Given the ALPN ID, return the name */ +const char *Curl_alpnid2str(enum alpnid id) +{ + switch(id) { + case ALPN_h1: + return "h1"; + case ALPN_h2: + return "h2"; + case ALPN_h3: + return H3VERSION; + default: + return ""; /* bad */ + } +} + + +static void altsvc_free(struct altsvc *as) +{ + free(as->src.host); + free(as->dst.host); + free(as); +} + +static struct altsvc *altsvc_createid(const char *srchost, + const char *dsthost, + enum alpnid srcalpnid, + enum alpnid dstalpnid, + unsigned int srcport, + unsigned int dstport) +{ + struct altsvc *as = calloc(1, sizeof(struct altsvc)); + size_t hlen; + size_t dlen; + if(!as) + return NULL; + hlen = strlen(srchost); + dlen = strlen(dsthost); + DEBUGASSERT(hlen); + DEBUGASSERT(dlen); + if(!hlen || !dlen) { + /* bad input */ + free(as); + return NULL; + } + if((hlen > 2) && srchost[0] == '[') { + /* IPv6 address, strip off brackets */ + srchost++; + hlen -= 2; + } + else if(srchost[hlen - 1] == '.') + /* strip off trailing dot */ + hlen--; + if((dlen > 2) && dsthost[0] == '[') { + /* IPv6 address, strip off brackets */ + dsthost++; + dlen -= 2; + } + + as->src.host = Curl_memdup0(srchost, hlen); + if(!as->src.host) + goto error; + + as->dst.host = Curl_memdup0(dsthost, dlen); + if(!as->dst.host) + goto error; + + as->src.alpnid = srcalpnid; + as->dst.alpnid = dstalpnid; + as->src.port = curlx_ultous(srcport); + as->dst.port = curlx_ultous(dstport); + + return as; +error: + altsvc_free(as); + return NULL; +} + +static struct altsvc *altsvc_create(char *srchost, + char *dsthost, + char *srcalpn, + char *dstalpn, + unsigned int srcport, + unsigned int dstport) +{ + enum alpnid dstalpnid = alpn2alpnid(dstalpn); + enum alpnid srcalpnid = alpn2alpnid(srcalpn); + if(!srcalpnid || !dstalpnid) + return NULL; + return altsvc_createid(srchost, dsthost, srcalpnid, dstalpnid, + srcport, dstport); +} + +/* only returns SERIOUS errors */ +static CURLcode altsvc_add(struct altsvcinfo *asi, char *line) +{ + /* Example line: + h2 example.com 443 h3 shiny.example.com 8443 "20191231 10:00:00" 1 + */ + char srchost[MAX_ALTSVC_HOSTLEN + 1]; + char dsthost[MAX_ALTSVC_HOSTLEN + 1]; + char srcalpn[MAX_ALTSVC_ALPNLEN + 1]; + char dstalpn[MAX_ALTSVC_ALPNLEN + 1]; + char date[MAX_ALTSVC_DATELEN + 1]; + unsigned int srcport; + unsigned int dstport; + unsigned int prio; + unsigned int persist; + int rc; + + rc = sscanf(line, + "%" MAX_ALTSVC_ALPNLENSTR "s %" MAX_ALTSVC_HOSTLENSTR "s %u " + "%" MAX_ALTSVC_ALPNLENSTR "s %" MAX_ALTSVC_HOSTLENSTR "s %u " + "\"%" MAX_ALTSVC_DATELENSTR "[^\"]\" %u %u", + srcalpn, srchost, &srcport, + dstalpn, dsthost, &dstport, + date, &persist, &prio); + if(9 == rc) { + struct altsvc *as; + time_t expires = Curl_getdate_capped(date); + as = altsvc_create(srchost, dsthost, srcalpn, dstalpn, srcport, dstport); + if(as) { + as->expires = expires; + as->prio = prio; + as->persist = persist ? 1 : 0; + Curl_llist_append(&asi->list, as, &as->node); + } + } + + return CURLE_OK; +} + +/* + * Load alt-svc entries from the given file. The text based line-oriented file + * format is documented here: https://curl.se/docs/alt-svc.html + * + * This function only returns error on major problems that prevent alt-svc + * handling to work completely. It will ignore individual syntactical errors + * etc. + */ +static CURLcode altsvc_load(struct altsvcinfo *asi, const char *file) +{ + CURLcode result = CURLE_OK; + FILE *fp; + + /* we need a private copy of the file name so that the altsvc cache file + name survives an easy handle reset */ + free(asi->filename); + asi->filename = strdup(file); + if(!asi->filename) + return CURLE_OUT_OF_MEMORY; + + fp = fopen(file, FOPEN_READTEXT); + if(fp) { + struct dynbuf buf; + Curl_dyn_init(&buf, MAX_ALTSVC_LINE); + while(Curl_get_line(&buf, fp)) { + char *lineptr = Curl_dyn_ptr(&buf); + while(*lineptr && ISBLANK(*lineptr)) + lineptr++; + if(*lineptr == '#') + /* skip commented lines */ + continue; + + altsvc_add(asi, lineptr); + } + Curl_dyn_free(&buf); /* free the line buffer */ + fclose(fp); + } + return result; +} + +/* + * Write this single altsvc entry to a single output line + */ + +static CURLcode altsvc_out(struct altsvc *as, FILE *fp) +{ + struct tm stamp; + const char *dst6_pre = ""; + const char *dst6_post = ""; + const char *src6_pre = ""; + const char *src6_post = ""; + CURLcode result = Curl_gmtime(as->expires, &stamp); + if(result) + return result; +#ifdef USE_IPV6 + else { + char ipv6_unused[16]; + if(1 == Curl_inet_pton(AF_INET6, as->dst.host, ipv6_unused)) { + dst6_pre = "["; + dst6_post = "]"; + } + if(1 == Curl_inet_pton(AF_INET6, as->src.host, ipv6_unused)) { + src6_pre = "["; + src6_post = "]"; + } + } +#endif + fprintf(fp, + "%s %s%s%s %u " + "%s %s%s%s %u " + "\"%d%02d%02d " + "%02d:%02d:%02d\" " + "%u %d\n", + Curl_alpnid2str(as->src.alpnid), + src6_pre, as->src.host, src6_post, + as->src.port, + + Curl_alpnid2str(as->dst.alpnid), + dst6_pre, as->dst.host, dst6_post, + as->dst.port, + + stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday, + stamp.tm_hour, stamp.tm_min, stamp.tm_sec, + as->persist, as->prio); + return CURLE_OK; +} + +/* ---- library-wide functions below ---- */ + +/* + * Curl_altsvc_init() creates a new altsvc cache. + * It returns the new instance or NULL if something goes wrong. + */ +struct altsvcinfo *Curl_altsvc_init(void) +{ + struct altsvcinfo *asi = calloc(1, sizeof(struct altsvcinfo)); + if(!asi) + return NULL; + Curl_llist_init(&asi->list, NULL); + + /* set default behavior */ + asi->flags = CURLALTSVC_H1 +#ifdef USE_HTTP2 + | CURLALTSVC_H2 +#endif +#ifdef USE_HTTP3 + | CURLALTSVC_H3 +#endif + ; + return asi; +} + +/* + * Curl_altsvc_load() loads alt-svc from file. + */ +CURLcode Curl_altsvc_load(struct altsvcinfo *asi, const char *file) +{ + CURLcode result; + DEBUGASSERT(asi); + result = altsvc_load(asi, file); + return result; +} + +/* + * Curl_altsvc_ctrl() passes on the external bitmask. + */ +CURLcode Curl_altsvc_ctrl(struct altsvcinfo *asi, const long ctrl) +{ + DEBUGASSERT(asi); + asi->flags = ctrl; + return CURLE_OK; +} + +/* + * Curl_altsvc_cleanup() frees an altsvc cache instance and all associated + * resources. + */ +void Curl_altsvc_cleanup(struct altsvcinfo **altsvcp) +{ + struct Curl_llist_element *e; + struct Curl_llist_element *n; + if(*altsvcp) { + struct altsvcinfo *altsvc = *altsvcp; + for(e = altsvc->list.head; e; e = n) { + struct altsvc *as = e->ptr; + n = e->next; + altsvc_free(as); + } + free(altsvc->filename); + free(altsvc); + *altsvcp = NULL; /* clear the pointer */ + } +} + +/* + * Curl_altsvc_save() writes the altsvc cache to a file. + */ +CURLcode Curl_altsvc_save(struct Curl_easy *data, + struct altsvcinfo *altsvc, const char *file) +{ + struct Curl_llist_element *e; + struct Curl_llist_element *n; + CURLcode result = CURLE_OK; + FILE *out; + char *tempstore = NULL; + + if(!altsvc) + /* no cache activated */ + return CURLE_OK; + + /* if not new name is given, use the one we stored from the load */ + if(!file && altsvc->filename) + file = altsvc->filename; + + if((altsvc->flags & CURLALTSVC_READONLYFILE) || !file || !file[0]) + /* marked as read-only, no file or zero length file name */ + return CURLE_OK; + + result = Curl_fopen(data, file, &out, &tempstore); + if(!result) { + fputs("# Your alt-svc cache. https://curl.se/docs/alt-svc.html\n" + "# This file was generated by libcurl! Edit at your own risk.\n", + out); + for(e = altsvc->list.head; e; e = n) { + struct altsvc *as = e->ptr; + n = e->next; + result = altsvc_out(as, out); + if(result) + break; + } + fclose(out); + if(!result && tempstore && Curl_rename(tempstore, file)) + result = CURLE_WRITE_ERROR; + + if(result && tempstore) + unlink(tempstore); + } + free(tempstore); + return result; +} + +static CURLcode getalnum(const char **ptr, char *alpnbuf, size_t buflen) +{ + size_t len; + const char *protop; + const char *p = *ptr; + while(*p && ISBLANK(*p)) + p++; + protop = p; + while(*p && !ISBLANK(*p) && (*p != ';') && (*p != '=')) + p++; + len = p - protop; + *ptr = p; + + if(!len || (len >= buflen)) + return CURLE_BAD_FUNCTION_ARGUMENT; + memcpy(alpnbuf, protop, len); + alpnbuf[len] = 0; + return CURLE_OK; +} + +/* hostcompare() returns true if 'host' matches 'check'. The first host + * argument may have a trailing dot present that will be ignored. + */ +static bool hostcompare(const char *host, const char *check) +{ + size_t hlen = strlen(host); + size_t clen = strlen(check); + + if(hlen && (host[hlen - 1] == '.')) + hlen--; + if(hlen != clen) + /* they can't match if they have different lengths */ + return FALSE; + return strncasecompare(host, check, hlen); +} + +/* altsvc_flush() removes all alternatives for this source origin from the + list */ +static void altsvc_flush(struct altsvcinfo *asi, enum alpnid srcalpnid, + const char *srchost, unsigned short srcport) +{ + struct Curl_llist_element *e; + struct Curl_llist_element *n; + for(e = asi->list.head; e; e = n) { + struct altsvc *as = e->ptr; + n = e->next; + if((srcalpnid == as->src.alpnid) && + (srcport == as->src.port) && + hostcompare(srchost, as->src.host)) { + Curl_llist_remove(&asi->list, e, NULL); + altsvc_free(as); + } + } +} + +#ifdef DEBUGBUILD +/* to play well with debug builds, we can *set* a fixed time this will + return */ +static time_t altsvc_debugtime(void *unused) +{ + char *timestr = getenv("CURL_TIME"); + (void)unused; + if(timestr) { + unsigned long val = strtol(timestr, NULL, 10); + return (time_t)val; + } + return time(NULL); +} +#undef time +#define time(x) altsvc_debugtime(x) +#endif + +#define ISNEWLINE(x) (((x) == '\n') || (x) == '\r') + +/* + * Curl_altsvc_parse() takes an incoming alt-svc response header and stores + * the data correctly in the cache. + * + * 'value' points to the header *value*. That's contents to the right of the + * header name. + * + * Currently this function rejects invalid data without returning an error. + * Invalid host name, port number will result in the specific alternative + * being rejected. Unknown protocols are skipped. + */ +CURLcode Curl_altsvc_parse(struct Curl_easy *data, + struct altsvcinfo *asi, const char *value, + enum alpnid srcalpnid, const char *srchost, + unsigned short srcport) +{ + const char *p = value; + size_t len; + char namebuf[MAX_ALTSVC_HOSTLEN] = ""; + char alpnbuf[MAX_ALTSVC_ALPNLEN] = ""; + struct altsvc *as; + unsigned short dstport = srcport; /* the same by default */ + CURLcode result = getalnum(&p, alpnbuf, sizeof(alpnbuf)); + size_t entries = 0; +#ifdef CURL_DISABLE_VERBOSE_STRINGS + (void)data; +#endif + if(result) { + infof(data, "Excessive alt-svc header, ignoring."); + return CURLE_OK; + } + + DEBUGASSERT(asi); + + /* "clear" is a magic keyword */ + if(strcasecompare(alpnbuf, "clear")) { + /* Flush cached alternatives for this source origin */ + altsvc_flush(asi, srcalpnid, srchost, srcport); + return CURLE_OK; + } + + do { + if(*p == '=') { + /* [protocol]="[host][:port]" */ + enum alpnid dstalpnid = alpn2alpnid(alpnbuf); /* the same by default */ + p++; + if(*p == '\"') { + const char *dsthost = ""; + const char *value_ptr; + char option[32]; + unsigned long num; + char *end_ptr; + bool quoted = FALSE; + time_t maxage = 24 * 3600; /* default is 24 hours */ + bool persist = FALSE; + bool valid = TRUE; + p++; + if(*p != ':') { + /* host name starts here */ + const char *hostp = p; + if(*p == '[') { + /* pass all valid IPv6 letters - does not handle zone id */ + len = strspn(++p, "0123456789abcdefABCDEF:."); + if(p[len] != ']') + /* invalid host syntax, bail out */ + break; + /* we store the IPv6 numerical address *with* brackets */ + len += 2; + p = &p[len-1]; + } + else { + while(*p && (ISALNUM(*p) || (*p == '.') || (*p == '-'))) + p++; + len = p - hostp; + } + if(!len || (len >= MAX_ALTSVC_HOSTLEN)) { + infof(data, "Excessive alt-svc host name, ignoring."); + valid = FALSE; + } + else { + memcpy(namebuf, hostp, len); + namebuf[len] = 0; + dsthost = namebuf; + } + } + else { + /* no destination name, use source host */ + dsthost = srchost; + } + if(*p == ':') { + unsigned long port = 0; + p++; + if(ISDIGIT(*p)) + /* a port number */ + port = strtoul(p, &end_ptr, 10); + else + end_ptr = (char *)p; /* not left uninitialized */ + if(!port || port > USHRT_MAX || end_ptr == p || *end_ptr != '\"') { + infof(data, "Unknown alt-svc port number, ignoring."); + valid = FALSE; + } + else { + dstport = curlx_ultous(port); + p = end_ptr; + } + } + if(*p++ != '\"') + break; + /* Handle the optional 'ma' and 'persist' flags. Unknown flags + are skipped. */ + for(;;) { + while(ISBLANK(*p)) + p++; + if(*p != ';') + break; + p++; /* pass the semicolon */ + if(!*p || ISNEWLINE(*p)) + break; + result = getalnum(&p, option, sizeof(option)); + if(result) { + /* skip option if name is too long */ + option[0] = '\0'; + } + while(*p && ISBLANK(*p)) + p++; + if(*p != '=') + return CURLE_OK; + p++; + while(*p && ISBLANK(*p)) + p++; + if(!*p) + return CURLE_OK; + if(*p == '\"') { + /* quoted value */ + p++; + quoted = TRUE; + } + value_ptr = p; + if(quoted) { + while(*p && *p != '\"') + p++; + if(!*p++) + return CURLE_OK; + } + else { + while(*p && !ISBLANK(*p) && *p!= ';' && *p != ',') + p++; + } + num = strtoul(value_ptr, &end_ptr, 10); + if((end_ptr != value_ptr) && (num < ULONG_MAX)) { + if(strcasecompare("ma", option)) + maxage = num; + else if(strcasecompare("persist", option) && (num == 1)) + persist = TRUE; + } + } + if(dstalpnid && valid) { + if(!entries++) + /* Flush cached alternatives for this source origin, if any - when + this is the first entry of the line. */ + altsvc_flush(asi, srcalpnid, srchost, srcport); + + as = altsvc_createid(srchost, dsthost, + srcalpnid, dstalpnid, + srcport, dstport); + if(as) { + /* The expires time also needs to take the Age: value (if any) into + account. [See RFC 7838 section 3.1] */ + as->expires = maxage + time(NULL); + as->persist = persist; + Curl_llist_append(&asi->list, as, &as->node); + infof(data, "Added alt-svc: %s:%d over %s", dsthost, dstport, + Curl_alpnid2str(dstalpnid)); + } + } + } + else + break; + /* after the double quote there can be a comma if there's another + string or a semicolon if no more */ + if(*p == ',') { + /* comma means another alternative is presented */ + p++; + result = getalnum(&p, alpnbuf, sizeof(alpnbuf)); + if(result) + break; + } + } + else + break; + } while(*p && (*p != ';') && (*p != '\n') && (*p != '\r')); + + return CURLE_OK; +} + +/* + * Return TRUE on a match + */ +bool Curl_altsvc_lookup(struct altsvcinfo *asi, + enum alpnid srcalpnid, const char *srchost, + int srcport, + struct altsvc **dstentry, + const int versions) /* one or more bits */ +{ + struct Curl_llist_element *e; + struct Curl_llist_element *n; + time_t now = time(NULL); + DEBUGASSERT(asi); + DEBUGASSERT(srchost); + DEBUGASSERT(dstentry); + + for(e = asi->list.head; e; e = n) { + struct altsvc *as = e->ptr; + n = e->next; + if(as->expires < now) { + /* an expired entry, remove */ + Curl_llist_remove(&asi->list, e, NULL); + altsvc_free(as); + continue; + } + if((as->src.alpnid == srcalpnid) && + hostcompare(srchost, as->src.host) && + (as->src.port == srcport) && + (versions & as->dst.alpnid)) { + /* match */ + *dstentry = as; + return TRUE; + } + } + return FALSE; +} + +#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_ALTSVC */ diff --git a/third_party/curl/lib/altsvc.h b/third_party/curl/lib/altsvc.h new file mode 100644 index 0000000..7fea143 --- /dev/null +++ b/third_party/curl/lib/altsvc.h @@ -0,0 +1,81 @@ +#ifndef HEADER_CURL_ALTSVC_H +#define HEADER_CURL_ALTSVC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_ALTSVC) +#include +#include "llist.h" + +enum alpnid { + ALPN_none = 0, + ALPN_h1 = CURLALTSVC_H1, + ALPN_h2 = CURLALTSVC_H2, + ALPN_h3 = CURLALTSVC_H3 +}; + +struct althost { + char *host; + unsigned short port; + enum alpnid alpnid; +}; + +struct altsvc { + struct althost src; + struct althost dst; + time_t expires; + bool persist; + int prio; + struct Curl_llist_element node; +}; + +struct altsvcinfo { + char *filename; + struct Curl_llist list; /* list of entries */ + long flags; /* the publicly set bitmask */ +}; + +const char *Curl_alpnid2str(enum alpnid id); +struct altsvcinfo *Curl_altsvc_init(void); +CURLcode Curl_altsvc_load(struct altsvcinfo *asi, const char *file); +CURLcode Curl_altsvc_save(struct Curl_easy *data, + struct altsvcinfo *asi, const char *file); +CURLcode Curl_altsvc_ctrl(struct altsvcinfo *asi, const long ctrl); +void Curl_altsvc_cleanup(struct altsvcinfo **altsvc); +CURLcode Curl_altsvc_parse(struct Curl_easy *data, + struct altsvcinfo *altsvc, const char *value, + enum alpnid srcalpn, const char *srchost, + unsigned short srcport); +bool Curl_altsvc_lookup(struct altsvcinfo *asi, + enum alpnid srcalpnid, const char *srchost, + int srcport, + struct altsvc **dstentry, + const int versions); /* CURLALTSVC_H* bits */ +#else +/* disabled */ +#define Curl_altsvc_save(a,b,c) +#define Curl_altsvc_cleanup(x) +#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_ALTSVC */ +#endif /* HEADER_CURL_ALTSVC_H */ diff --git a/third_party/curl/lib/amigaos.c b/third_party/curl/lib/amigaos.c new file mode 100644 index 0000000..139309b --- /dev/null +++ b/third_party/curl/lib/amigaos.c @@ -0,0 +1,247 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef __AMIGA__ + +#include + +#include "hostip.h" +#include "amigaos.h" + +#ifdef HAVE_PROTO_BSDSOCKET_H +# if defined(__amigaos4__) +# include +# elif !defined(USE_AMISSL) +# include +# endif +# ifdef __libnix__ +# include +# endif +#endif + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +#ifdef HAVE_PROTO_BSDSOCKET_H + +#ifdef __amigaos4__ +/* + * AmigaOS 4.x specific code + */ + +/* + * hostip4.c - Curl_ipv4_resolve_r() replacement code + * + * Logic that needs to be considered are the following build cases: + * - newlib networking + * - clib2 networking + * - direct bsdsocket.library networking (usually AmiSSL builds) + * Each with the threaded resolver enabled or not. + * + * With the threaded resolver enabled, try to use gethostbyname_r() where + * available, otherwise (re)open bsdsocket.library and fallback to + * gethostbyname(). + */ + +#include + +static struct SocketIFace *__CurlISocket = NULL; +static uint32 SocketFeatures = 0; + +#define HAVE_BSDSOCKET_GETHOSTBYNAME_R 0x01 +#define HAVE_BSDSOCKET_GETADDRINFO 0x02 + +CURLcode Curl_amiga_init(void) +{ + struct SocketIFace *ISocket; + struct Library *base = OpenLibrary("bsdsocket.library", 4); + + if(base) { + ISocket = (struct SocketIFace *)GetInterface(base, "main", 1, NULL); + if(ISocket) { + ULONG enabled = 0; + + SocketBaseTags(SBTM_SETVAL(SBTC_CAN_SHARE_LIBRARY_BASES), TRUE, + SBTM_GETREF(SBTC_HAVE_GETHOSTADDR_R_API), (ULONG)&enabled, + TAG_DONE); + + if(enabled) { + SocketFeatures |= HAVE_BSDSOCKET_GETHOSTBYNAME_R; + } + + __CurlISocket = ISocket; + + atexit(Curl_amiga_cleanup); + + return CURLE_OK; + } + CloseLibrary(base); + } + + return CURLE_FAILED_INIT; +} + +void Curl_amiga_cleanup(void) +{ + if(__CurlISocket) { + struct Library *base = __CurlISocket->Data.LibBase; + DropInterface((struct Interface *)__CurlISocket); + CloseLibrary(base); + __CurlISocket = NULL; + } +} + +#ifdef CURLRES_AMIGA +/* + * Because we need to handle the different cases in hostip4.c at run-time, + * not at compile-time, based on what was detected in Curl_amiga_init(), + * we replace it completely with our own as to not complicate the baseline + * code. Assumes malloc/calloc/free are thread safe because Curl_he2ai() + * allocates memory also. + */ + +struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname, + int port) +{ + struct Curl_addrinfo *ai = NULL; + struct hostent *h; + struct SocketIFace *ISocket = __CurlISocket; + + if(SocketFeatures & HAVE_BSDSOCKET_GETHOSTBYNAME_R) { + LONG h_errnop = 0; + struct hostent *buf; + + buf = calloc(1, CURL_HOSTENT_SIZE); + if(buf) { + h = gethostbyname_r((STRPTR)hostname, buf, + (char *)buf + sizeof(struct hostent), + CURL_HOSTENT_SIZE - sizeof(struct hostent), + &h_errnop); + if(h) { + ai = Curl_he2ai(h, port); + } + free(buf); + } + } + else { + #ifdef CURLRES_THREADED + /* gethostbyname() is not thread safe, so we need to reopen bsdsocket + * on the thread's context + */ + struct Library *base = OpenLibrary("bsdsocket.library", 4); + if(base) { + ISocket = (struct SocketIFace *)GetInterface(base, "main", 1, NULL); + if(ISocket) { + h = gethostbyname((STRPTR)hostname); + if(h) { + ai = Curl_he2ai(h, port); + } + DropInterface((struct Interface *)ISocket); + } + CloseLibrary(base); + } + #else + /* not using threaded resolver - safe to use this as-is */ + h = gethostbyname(hostname); + if(h) { + ai = Curl_he2ai(h, port); + } + #endif + } + + return ai; +} +#endif /* CURLRES_AMIGA */ + +#ifdef USE_AMISSL +#include +int Curl_amiga_select(int nfds, fd_set *readfds, fd_set *writefds, + fd_set *errorfds, struct timeval *timeout) +{ + int r = WaitSelect(nfds, readfds, writefds, errorfds, timeout, 0); + /* Ensure Ctrl-C signal is actioned */ + if((r == -1) && (SOCKERRNO == EINTR)) + raise(SIGINT); + return r; +} +#endif /* USE_AMISSL */ + +#elif !defined(USE_AMISSL) /* __amigaos4__ */ +/* + * Amiga OS3 specific code + */ + +struct Library *SocketBase = NULL; +extern int errno, h_errno; + +#ifdef __libnix__ +void __request(const char *msg); +#else +# define __request(msg) Printf(msg "\n\a") +#endif + +void Curl_amiga_cleanup(void) +{ + if(SocketBase) { + CloseLibrary(SocketBase); + SocketBase = NULL; + } +} + +CURLcode Curl_amiga_init(void) +{ + if(!SocketBase) + SocketBase = OpenLibrary("bsdsocket.library", 4); + + if(!SocketBase) { + __request("No TCP/IP Stack running!"); + return CURLE_FAILED_INIT; + } + + if(SocketBaseTags(SBTM_SETVAL(SBTC_ERRNOPTR(sizeof(errno))), (ULONG) &errno, + SBTM_SETVAL(SBTC_LOGTAGPTR), (ULONG) "curl", + TAG_DONE)) { + __request("SocketBaseTags ERROR"); + return CURLE_FAILED_INIT; + } + +#ifndef __libnix__ + atexit(Curl_amiga_cleanup); +#endif + + return CURLE_OK; +} + +#ifdef __libnix__ +ADD2EXIT(Curl_amiga_cleanup, -50); +#endif + +#endif /* !USE_AMISSL */ + +#endif /* HAVE_PROTO_BSDSOCKET_H */ + +#endif /* __AMIGA__ */ diff --git a/third_party/curl/lib/amigaos.h b/third_party/curl/lib/amigaos.h new file mode 100644 index 0000000..c99d963 --- /dev/null +++ b/third_party/curl/lib/amigaos.h @@ -0,0 +1,41 @@ +#ifndef HEADER_CURL_AMIGAOS_H +#define HEADER_CURL_AMIGAOS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(__AMIGA__) && defined(HAVE_PROTO_BSDSOCKET_H) && \ + (!defined(USE_AMISSL) || defined(__amigaos4__)) + +CURLcode Curl_amiga_init(void); +void Curl_amiga_cleanup(void); + +#else + +#define Curl_amiga_init() CURLE_OK +#define Curl_amiga_cleanup() Curl_nop_stmt + +#endif + +#endif /* HEADER_CURL_AMIGAOS_H */ diff --git a/third_party/curl/lib/arpa_telnet.h b/third_party/curl/lib/arpa_telnet.h new file mode 100644 index 0000000..228b446 --- /dev/null +++ b/third_party/curl/lib/arpa_telnet.h @@ -0,0 +1,117 @@ +#ifndef HEADER_CURL_ARPA_TELNET_H +#define HEADER_CURL_ARPA_TELNET_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifndef CURL_DISABLE_TELNET +/* + * Telnet option defines. Add more here if in need. + */ +#define CURL_TELOPT_BINARY 0 /* binary 8bit data */ +#define CURL_TELOPT_ECHO 1 /* just echo! */ +#define CURL_TELOPT_SGA 3 /* Suppress Go Ahead */ +#define CURL_TELOPT_EXOPL 255 /* EXtended OPtions List */ +#define CURL_TELOPT_TTYPE 24 /* Terminal TYPE */ +#define CURL_TELOPT_NAWS 31 /* Negotiate About Window Size */ +#define CURL_TELOPT_XDISPLOC 35 /* X DISPlay LOCation */ + +#define CURL_TELOPT_NEW_ENVIRON 39 /* NEW ENVIRONment variables */ +#define CURL_NEW_ENV_VAR 0 +#define CURL_NEW_ENV_VALUE 1 + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +/* + * The telnet options represented as strings + */ +static const char * const telnetoptions[]= +{ + "BINARY", "ECHO", "RCP", "SUPPRESS GO AHEAD", + "NAME", "STATUS", "TIMING MARK", "RCTE", + "NAOL", "NAOP", "NAOCRD", "NAOHTS", + "NAOHTD", "NAOFFD", "NAOVTS", "NAOVTD", + "NAOLFD", "EXTEND ASCII", "LOGOUT", "BYTE MACRO", + "DE TERMINAL", "SUPDUP", "SUPDUP OUTPUT", "SEND LOCATION", + "TERM TYPE", "END OF RECORD", "TACACS UID", "OUTPUT MARKING", + "TTYLOC", "3270 REGIME", "X3 PAD", "NAWS", + "TERM SPEED", "LFLOW", "LINEMODE", "XDISPLOC", + "OLD-ENVIRON", "AUTHENTICATION", "ENCRYPT", "NEW-ENVIRON" +}; +#define CURL_TELOPT(x) telnetoptions[x] +#else +#define CURL_TELOPT(x) "" +#endif + +#define CURL_TELOPT_MAXIMUM CURL_TELOPT_NEW_ENVIRON + +#define CURL_TELOPT_OK(x) ((x) <= CURL_TELOPT_MAXIMUM) + +#define CURL_NTELOPTS 40 + +/* + * First some defines + */ +#define CURL_xEOF 236 /* End Of File */ +#define CURL_SE 240 /* Sub negotiation End */ +#define CURL_NOP 241 /* No OPeration */ +#define CURL_DM 242 /* Data Mark */ +#define CURL_GA 249 /* Go Ahead, reverse the line */ +#define CURL_SB 250 /* SuBnegotiation */ +#define CURL_WILL 251 /* Our side WILL use this option */ +#define CURL_WONT 252 /* Our side WON'T use this option */ +#define CURL_DO 253 /* DO use this option! */ +#define CURL_DONT 254 /* DON'T use this option! */ +#define CURL_IAC 255 /* Interpret As Command */ + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +/* + * Then those numbers represented as strings: + */ +static const char * const telnetcmds[]= +{ + "EOF", "SUSP", "ABORT", "EOR", "SE", + "NOP", "DMARK", "BRK", "IP", "AO", + "AYT", "EC", "EL", "GA", "SB", + "WILL", "WONT", "DO", "DONT", "IAC" +}; +#endif + +#define CURL_TELCMD_MINIMUM CURL_xEOF /* the first one */ +#define CURL_TELCMD_MAXIMUM CURL_IAC /* surprise, 255 is the last one! ;-) */ + +#define CURL_TELQUAL_IS 0 +#define CURL_TELQUAL_SEND 1 +#define CURL_TELQUAL_INFO 2 +#define CURL_TELQUAL_NAME 3 + +#define CURL_TELCMD_OK(x) ( ((unsigned int)(x) >= CURL_TELCMD_MINIMUM) && \ + ((unsigned int)(x) <= CURL_TELCMD_MAXIMUM) ) + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +#define CURL_TELCMD(x) telnetcmds[(x)-CURL_TELCMD_MINIMUM] +#else +#define CURL_TELCMD(x) "" +#endif + +#endif /* CURL_DISABLE_TELNET */ + +#endif /* HEADER_CURL_ARPA_TELNET_H */ diff --git a/third_party/curl/lib/asyn-ares.c b/third_party/curl/lib/asyn-ares.c new file mode 100644 index 0000000..8fed617 --- /dev/null +++ b/third_party/curl/lib/asyn-ares.c @@ -0,0 +1,958 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +/*********************************************************************** + * Only for ares-enabled builds + * And only for functions that fulfill the asynch resolver backend API + * as defined in asyn.h, nothing else belongs in this file! + **********************************************************************/ + +#ifdef CURLRES_ARES + +#include +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef __VMS +#include +#include +#endif + +#include "urldata.h" +#include "sendf.h" +#include "hostip.h" +#include "hash.h" +#include "share.h" +#include "url.h" +#include "multiif.h" +#include "inet_pton.h" +#include "connect.h" +#include "select.h" +#include "progress.h" +#include "timediff.h" + +#if defined(CURL_STATICLIB) && !defined(CARES_STATICLIB) && \ + defined(_WIN32) +# define CARES_STATICLIB +#endif +#include +#include /* really old c-ares didn't include this by + itself */ + +#if ARES_VERSION >= 0x010500 +/* c-ares 1.5.0 or later, the callback proto is modified */ +#define HAVE_CARES_CALLBACK_TIMEOUTS 1 +#endif + +#if ARES_VERSION >= 0x010601 +/* IPv6 supported since 1.6.1 */ +#define HAVE_CARES_IPV6 1 +#endif + +#if ARES_VERSION >= 0x010704 +#define HAVE_CARES_SERVERS_CSV 1 +#define HAVE_CARES_LOCAL_DEV 1 +#define HAVE_CARES_SET_LOCAL 1 +#endif + +#if ARES_VERSION >= 0x010b00 +#define HAVE_CARES_PORTS_CSV 1 +#endif + +#if ARES_VERSION >= 0x011000 +/* 1.16.0 or later has ares_getaddrinfo */ +#define HAVE_CARES_GETADDRINFO 1 +#endif + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +struct thread_data { + int num_pending; /* number of outstanding c-ares requests */ + struct Curl_addrinfo *temp_ai; /* intermediary result while fetching c-ares + parts */ + int last_status; +#ifndef HAVE_CARES_GETADDRINFO + struct curltime happy_eyeballs_dns_time; /* when this timer started, or 0 */ +#endif + char hostname[1]; +}; + +/* How long we are willing to wait for additional parallel responses after + obtaining a "definitive" one. For old c-ares without getaddrinfo. + + This is intended to equal the c-ares default timeout. cURL always uses that + default value. Unfortunately, c-ares doesn't expose its default timeout in + its API, but it is officially documented as 5 seconds. + + See query_completed_cb() for an explanation of how this is used. + */ +#define HAPPY_EYEBALLS_DNS_TIMEOUT 5000 + +#define CARES_TIMEOUT_PER_ATTEMPT 2000 + +static int ares_ver = 0; + +/* + * Curl_resolver_global_init() - the generic low-level asynchronous name + * resolve API. Called from curl_global_init() to initialize global resolver + * environment. Initializes ares library. + */ +int Curl_resolver_global_init(void) +{ +#ifdef CARES_HAVE_ARES_LIBRARY_INIT + if(ares_library_init(ARES_LIB_INIT_ALL)) { + return CURLE_FAILED_INIT; + } +#endif + ares_version(&ares_ver); + return CURLE_OK; +} + +/* + * Curl_resolver_global_cleanup() + * + * Called from curl_global_cleanup() to destroy global resolver environment. + * Deinitializes ares library. + */ +void Curl_resolver_global_cleanup(void) +{ +#ifdef CARES_HAVE_ARES_LIBRARY_CLEANUP + ares_library_cleanup(); +#endif +} + + +static void sock_state_cb(void *data, ares_socket_t socket_fd, + int readable, int writable) +{ + struct Curl_easy *easy = data; + if(!readable && !writable) { + DEBUGASSERT(easy); + Curl_multi_closed(easy, socket_fd); + } +} + +/* + * Curl_resolver_init() + * + * Called from curl_easy_init() -> Curl_open() to initialize resolver + * URL-state specific environment ('resolver' member of the UrlState + * structure). Fills the passed pointer by the initialized ares_channel. + */ +CURLcode Curl_resolver_init(struct Curl_easy *easy, void **resolver) +{ + int status; + struct ares_options options; + int optmask = ARES_OPT_SOCK_STATE_CB; + options.sock_state_cb = sock_state_cb; + options.sock_state_cb_data = easy; + + /* + if c ares < 1.20.0: curl set timeout to CARES_TIMEOUT_PER_ATTEMPT (2s) + + if c-ares >= 1.20.0 it already has the timeout to 2s, curl does not need + to set the timeout value; + + if c-ares >= 1.24.0, user can set the timeout via /etc/resolv.conf to + overwrite c-ares' timeout. + */ + DEBUGASSERT(ares_ver); + if(ares_ver < 0x011400) { + options.timeout = CARES_TIMEOUT_PER_ATTEMPT; + optmask |= ARES_OPT_TIMEOUTMS; + } + + status = ares_init_options((ares_channel*)resolver, &options, optmask); + if(status != ARES_SUCCESS) { + if(status == ARES_ENOMEM) + return CURLE_OUT_OF_MEMORY; + else + return CURLE_FAILED_INIT; + } + return CURLE_OK; + /* make sure that all other returns from this function should destroy the + ares channel before returning error! */ +} + +/* + * Curl_resolver_cleanup() + * + * Called from curl_easy_cleanup() -> Curl_close() to cleanup resolver + * URL-state specific environment ('resolver' member of the UrlState + * structure). Destroys the ares channel. + */ +void Curl_resolver_cleanup(void *resolver) +{ + ares_destroy((ares_channel)resolver); +} + +/* + * Curl_resolver_duphandle() + * + * Called from curl_easy_duphandle() to duplicate resolver URL-state specific + * environment ('resolver' member of the UrlState structure). Duplicates the + * 'from' ares channel and passes the resulting channel to the 'to' pointer. + */ +CURLcode Curl_resolver_duphandle(struct Curl_easy *easy, void **to, void *from) +{ + (void)from; + /* + * it would be better to call ares_dup instead, but right now + * it is not possible to set 'sock_state_cb_data' outside of + * ares_init_options + */ + return Curl_resolver_init(easy, to); +} + +static void destroy_async_data(struct Curl_async *async); + +/* + * Cancel all possibly still on-going resolves for this connection. + */ +void Curl_resolver_cancel(struct Curl_easy *data) +{ + DEBUGASSERT(data); + if(data->state.async.resolver) + ares_cancel((ares_channel)data->state.async.resolver); + destroy_async_data(&data->state.async); +} + +/* + * We're equivalent to Curl_resolver_cancel() for the c-ares resolver. We + * never block. + */ +void Curl_resolver_kill(struct Curl_easy *data) +{ + /* We don't need to check the resolver state because we can be called safely + at any time and we always do the same thing. */ + Curl_resolver_cancel(data); +} + +/* + * destroy_async_data() cleans up async resolver data. + */ +static void destroy_async_data(struct Curl_async *async) +{ + if(async->tdata) { + struct thread_data *res = async->tdata; + if(res) { + if(res->temp_ai) { + Curl_freeaddrinfo(res->temp_ai); + res->temp_ai = NULL; + } + free(res); + } + async->tdata = NULL; + } +} + +/* + * Curl_resolver_getsock() is called when someone from the outside world + * (using curl_multi_fdset()) wants to get our fd_set setup and we're talking + * with ares. The caller must make sure that this function is only called when + * we have a working ares channel. + * + * Returns: sockets-in-use-bitmap + */ + +int Curl_resolver_getsock(struct Curl_easy *data, + curl_socket_t *socks) +{ + struct timeval maxtime; + struct timeval timebuf; + struct timeval *timeout; + long milli; + int max = ares_getsock((ares_channel)data->state.async.resolver, + (ares_socket_t *)socks, MAX_SOCKSPEREASYHANDLE); + + maxtime.tv_sec = CURL_TIMEOUT_RESOLVE; + maxtime.tv_usec = 0; + + timeout = ares_timeout((ares_channel)data->state.async.resolver, &maxtime, + &timebuf); + milli = (long)curlx_tvtoms(timeout); + if(milli == 0) + milli += 10; + Curl_expire(data, milli, EXPIRE_ASYNC_NAME); + + return max; +} + +/* + * waitperform() + * + * 1) Ask ares what sockets it currently plays with, then + * 2) wait for the timeout period to check for action on ares' sockets. + * 3) tell ares to act on all the sockets marked as "with action" + * + * return number of sockets it worked on, or -1 on error + */ + +static int waitperform(struct Curl_easy *data, timediff_t timeout_ms) +{ + int nfds; + int bitmask; + ares_socket_t socks[ARES_GETSOCK_MAXNUM]; + struct pollfd pfd[ARES_GETSOCK_MAXNUM]; + int i; + int num = 0; + + bitmask = ares_getsock((ares_channel)data->state.async.resolver, socks, + ARES_GETSOCK_MAXNUM); + + for(i = 0; i < ARES_GETSOCK_MAXNUM; i++) { + pfd[i].events = 0; + pfd[i].revents = 0; + if(ARES_GETSOCK_READABLE(bitmask, i)) { + pfd[i].fd = socks[i]; + pfd[i].events |= POLLRDNORM|POLLIN; + } + if(ARES_GETSOCK_WRITABLE(bitmask, i)) { + pfd[i].fd = socks[i]; + pfd[i].events |= POLLWRNORM|POLLOUT; + } + if(pfd[i].events) + num++; + else + break; + } + + if(num) { + nfds = Curl_poll(pfd, num, timeout_ms); + if(nfds < 0) + return -1; + } + else + nfds = 0; + + if(!nfds) + /* Call ares_process() unconditionally here, even if we simply timed out + above, as otherwise the ares name resolve won't timeout! */ + ares_process_fd((ares_channel)data->state.async.resolver, ARES_SOCKET_BAD, + ARES_SOCKET_BAD); + else { + /* move through the descriptors and ask for processing on them */ + for(i = 0; i < num; i++) + ares_process_fd((ares_channel)data->state.async.resolver, + (pfd[i].revents & (POLLRDNORM|POLLIN))? + pfd[i].fd:ARES_SOCKET_BAD, + (pfd[i].revents & (POLLWRNORM|POLLOUT))? + pfd[i].fd:ARES_SOCKET_BAD); + } + return nfds; +} + +/* + * Curl_resolver_is_resolved() is called repeatedly to check if a previous + * name resolve request has completed. It should also make sure to time-out if + * the operation seems to take too long. + * + * Returns normal CURLcode errors. + */ +CURLcode Curl_resolver_is_resolved(struct Curl_easy *data, + struct Curl_dns_entry **dns) +{ + struct thread_data *res = data->state.async.tdata; + CURLcode result = CURLE_OK; + + DEBUGASSERT(dns); + *dns = NULL; + + if(waitperform(data, 0) < 0) + return CURLE_UNRECOVERABLE_POLL; + +#ifndef HAVE_CARES_GETADDRINFO + /* Now that we've checked for any last minute results above, see if there are + any responses still pending when the EXPIRE_HAPPY_EYEBALLS_DNS timer + expires. */ + if(res + && res->num_pending + /* This is only set to non-zero if the timer was started. */ + && (res->happy_eyeballs_dns_time.tv_sec + || res->happy_eyeballs_dns_time.tv_usec) + && (Curl_timediff(Curl_now(), res->happy_eyeballs_dns_time) + >= HAPPY_EYEBALLS_DNS_TIMEOUT)) { + /* Remember that the EXPIRE_HAPPY_EYEBALLS_DNS timer is no longer + running. */ + memset( + &res->happy_eyeballs_dns_time, 0, sizeof(res->happy_eyeballs_dns_time)); + + /* Cancel the raw c-ares request, which will fire query_completed_cb() with + ARES_ECANCELLED synchronously for all pending responses. This will + leave us with res->num_pending == 0, which is perfect for the next + block. */ + ares_cancel((ares_channel)data->state.async.resolver); + DEBUGASSERT(res->num_pending == 0); + } +#endif + + if(res && !res->num_pending) { + (void)Curl_addrinfo_callback(data, res->last_status, res->temp_ai); + /* temp_ai ownership is moved to the connection, so we need not free-up + them */ + res->temp_ai = NULL; + + if(!data->state.async.dns) + result = Curl_resolver_error(data); + else + *dns = data->state.async.dns; + + destroy_async_data(&data->state.async); + } + + return result; +} + +/* + * Curl_resolver_wait_resolv() + * + * Waits for a resolve to finish. This function should be avoided since using + * this risk getting the multi interface to "hang". + * + * 'entry' MUST be non-NULL. + * + * Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved, + * CURLE_OPERATION_TIMEDOUT if a time-out occurred, or other errors. + */ +CURLcode Curl_resolver_wait_resolv(struct Curl_easy *data, + struct Curl_dns_entry **entry) +{ + CURLcode result = CURLE_OK; + timediff_t timeout; + struct curltime now = Curl_now(); + + DEBUGASSERT(entry); + *entry = NULL; /* clear on entry */ + + timeout = Curl_timeleft(data, &now, TRUE); + if(timeout < 0) { + /* already expired! */ + connclose(data->conn, "Timed out before name resolve started"); + return CURLE_OPERATION_TIMEDOUT; + } + if(!timeout) + timeout = CURL_TIMEOUT_RESOLVE * 1000; /* default name resolve timeout */ + + /* Wait for the name resolve query to complete. */ + while(!result) { + struct timeval *tvp, tv, store; + int itimeout; + timediff_t timeout_ms; + +#if TIMEDIFF_T_MAX > INT_MAX + itimeout = (timeout > INT_MAX) ? INT_MAX : (int)timeout; +#else + itimeout = (int)timeout; +#endif + + store.tv_sec = itimeout/1000; + store.tv_usec = (itimeout%1000)*1000; + + tvp = ares_timeout((ares_channel)data->state.async.resolver, &store, &tv); + + /* use the timeout period ares returned to us above if less than one + second is left, otherwise just use 1000ms to make sure the progress + callback gets called frequent enough */ + if(!tvp->tv_sec) + timeout_ms = (timediff_t)(tvp->tv_usec/1000); + else + timeout_ms = 1000; + + if(waitperform(data, timeout_ms) < 0) + return CURLE_UNRECOVERABLE_POLL; + result = Curl_resolver_is_resolved(data, entry); + + if(result || data->state.async.done) + break; + + if(Curl_pgrsUpdate(data)) + result = CURLE_ABORTED_BY_CALLBACK; + else { + struct curltime now2 = Curl_now(); + timediff_t timediff = Curl_timediff(now2, now); /* spent time */ + if(timediff <= 0) + timeout -= 1; /* always deduct at least 1 */ + else if(timediff > timeout) + timeout = -1; + else + timeout -= timediff; + now = now2; /* for next loop */ + } + if(timeout < 0) + result = CURLE_OPERATION_TIMEDOUT; + } + if(result) + /* failure, so we cancel the ares operation */ + ares_cancel((ares_channel)data->state.async.resolver); + + /* Operation complete, if the lookup was successful we now have the entry + in the cache. */ + if(entry) + *entry = data->state.async.dns; + + if(result) + /* close the connection, since we can't return failure here without + cleaning up this connection properly. */ + connclose(data->conn, "c-ares resolve failed"); + + return result; +} + +#ifndef HAVE_CARES_GETADDRINFO + +/* Connects results to the list */ +static void compound_results(struct thread_data *res, + struct Curl_addrinfo *ai) +{ + if(!ai) + return; + +#ifdef USE_IPV6 /* CURLRES_IPV6 */ + if(res->temp_ai && res->temp_ai->ai_family == PF_INET6) { + /* We have results already, put the new IPv6 entries at the head of the + list. */ + struct Curl_addrinfo *temp_ai_tail = res->temp_ai; + + while(temp_ai_tail->ai_next) + temp_ai_tail = temp_ai_tail->ai_next; + + temp_ai_tail->ai_next = ai; + } + else +#endif /* CURLRES_IPV6 */ + { + /* Add the new results to the list of old results. */ + struct Curl_addrinfo *ai_tail = ai; + while(ai_tail->ai_next) + ai_tail = ai_tail->ai_next; + + ai_tail->ai_next = res->temp_ai; + res->temp_ai = ai; + } +} + +/* + * ares_query_completed_cb() is the callback that ares will call when + * the host query initiated by ares_gethostbyname() from Curl_getaddrinfo(), + * when using ares, is completed either successfully or with failure. + */ +static void query_completed_cb(void *arg, /* (struct connectdata *) */ + int status, +#ifdef HAVE_CARES_CALLBACK_TIMEOUTS + int timeouts, +#endif + struct hostent *hostent) +{ + struct Curl_easy *data = (struct Curl_easy *)arg; + struct thread_data *res; + +#ifdef HAVE_CARES_CALLBACK_TIMEOUTS + (void)timeouts; /* ignored */ +#endif + + if(ARES_EDESTRUCTION == status) + /* when this ares handle is getting destroyed, the 'arg' pointer may not + be valid so only defer it when we know the 'status' says its fine! */ + return; + + res = data->state.async.tdata; + if(res) { + res->num_pending--; + + if(CURL_ASYNC_SUCCESS == status) { + struct Curl_addrinfo *ai = Curl_he2ai(hostent, data->state.async.port); + if(ai) { + compound_results(res, ai); + } + } + /* A successful result overwrites any previous error */ + if(res->last_status != ARES_SUCCESS) + res->last_status = status; + + /* If there are responses still pending, we presume they must be the + complementary IPv4 or IPv6 lookups that we started in parallel in + Curl_resolver_getaddrinfo() (for Happy Eyeballs). If we've got a + "definitive" response from one of a set of parallel queries, we need to + think about how long we're willing to wait for more responses. */ + if(res->num_pending + /* Only these c-ares status values count as "definitive" for these + purposes. For example, ARES_ENODATA is what we expect when there is + no IPv6 entry for a domain name, and that's not a reason to get more + aggressive in our timeouts for the other response. Other errors are + either a result of bad input (which should affect all parallel + requests), local or network conditions, non-definitive server + responses, or us cancelling the request. */ + && (status == ARES_SUCCESS || status == ARES_ENOTFOUND)) { + /* Right now, there can only be up to two parallel queries, so don't + bother handling any other cases. */ + DEBUGASSERT(res->num_pending == 1); + + /* It's possible that one of these parallel queries could succeed + quickly, but the other could always fail or timeout (when we're + talking to a pool of DNS servers that can only successfully resolve + IPv4 address, for example). + + It's also possible that the other request could always just take + longer because it needs more time or only the second DNS server can + fulfill it successfully. But, to align with the philosophy of Happy + Eyeballs, we don't want to wait _too_ long or users will think + requests are slow when IPv6 lookups don't actually work (but IPv4 ones + do). + + So, now that we have a usable answer (some IPv4 addresses, some IPv6 + addresses, or "no such domain"), we start a timeout for the remaining + pending responses. Even though it is typical that this resolved + request came back quickly, that needn't be the case. It might be that + this completing request didn't get a result from the first DNS server + or even the first round of the whole DNS server pool. So it could + already be quite some time after we issued the DNS queries in the + first place. Without modifying c-ares, we can't know exactly where in + its retry cycle we are. We could guess based on how much time has + gone by, but it doesn't really matter. Happy Eyeballs tells us that, + given usable information in hand, we simply don't want to wait "too + much longer" after we get a result. + + We simply wait an additional amount of time equal to the default + c-ares query timeout. That is enough time for a typical parallel + response to arrive without being "too long". Even on a network + where one of the two types of queries is failing or timing out + constantly, this will usually mean we wait a total of the default + c-ares timeout (5 seconds) plus the round trip time for the successful + request, which seems bearable. The downside is that c-ares might race + with us to issue one more retry just before we give up, but it seems + better to "waste" that request instead of trying to guess the perfect + timeout to prevent it. After all, we don't even know where in the + c-ares retry cycle each request is. + */ + res->happy_eyeballs_dns_time = Curl_now(); + Curl_expire(data, HAPPY_EYEBALLS_DNS_TIMEOUT, + EXPIRE_HAPPY_EYEBALLS_DNS); + } + } +} +#else +/* c-ares 1.16.0 or later */ + +/* + * ares2addr() converts an address list provided by c-ares to an internal + * libcurl compatible list + */ +static struct Curl_addrinfo *ares2addr(struct ares_addrinfo_node *node) +{ + /* traverse the ares_addrinfo_node list */ + struct ares_addrinfo_node *ai; + struct Curl_addrinfo *cafirst = NULL; + struct Curl_addrinfo *calast = NULL; + int error = 0; + + for(ai = node; ai != NULL; ai = ai->ai_next) { + size_t ss_size; + struct Curl_addrinfo *ca; + /* ignore elements with unsupported address family, */ + /* settle family-specific sockaddr structure size. */ + if(ai->ai_family == AF_INET) + ss_size = sizeof(struct sockaddr_in); +#ifdef USE_IPV6 + else if(ai->ai_family == AF_INET6) + ss_size = sizeof(struct sockaddr_in6); +#endif + else + continue; + + /* ignore elements without required address info */ + if(!ai->ai_addr || !(ai->ai_addrlen > 0)) + continue; + + /* ignore elements with bogus address size */ + if((size_t)ai->ai_addrlen < ss_size) + continue; + + ca = malloc(sizeof(struct Curl_addrinfo) + ss_size); + if(!ca) { + error = EAI_MEMORY; + break; + } + + /* copy each structure member individually, member ordering, */ + /* size, or padding might be different for each platform. */ + + ca->ai_flags = ai->ai_flags; + ca->ai_family = ai->ai_family; + ca->ai_socktype = ai->ai_socktype; + ca->ai_protocol = ai->ai_protocol; + ca->ai_addrlen = (curl_socklen_t)ss_size; + ca->ai_addr = NULL; + ca->ai_canonname = NULL; + ca->ai_next = NULL; + + ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo)); + memcpy(ca->ai_addr, ai->ai_addr, ss_size); + + /* if the return list is empty, this becomes the first element */ + if(!cafirst) + cafirst = ca; + + /* add this element last in the return list */ + if(calast) + calast->ai_next = ca; + calast = ca; + } + + /* if we failed, destroy the Curl_addrinfo list */ + if(error) { + Curl_freeaddrinfo(cafirst); + cafirst = NULL; + } + + return cafirst; +} + +static void addrinfo_cb(void *arg, int status, int timeouts, + struct ares_addrinfo *result) +{ + struct Curl_easy *data = (struct Curl_easy *)arg; + struct thread_data *res = data->state.async.tdata; + (void)timeouts; + if(ARES_SUCCESS == status) { + res->temp_ai = ares2addr(result->nodes); + res->last_status = CURL_ASYNC_SUCCESS; + ares_freeaddrinfo(result); + } + res->num_pending--; +} + +#endif +/* + * Curl_resolver_getaddrinfo() - when using ares + * + * Returns name information about the given hostname and port number. If + * successful, the 'hostent' is returned and the fourth argument will point to + * memory we need to free after use. That memory *MUST* be freed with + * Curl_freeaddrinfo(), nothing else. + */ +struct Curl_addrinfo *Curl_resolver_getaddrinfo(struct Curl_easy *data, + const char *hostname, + int port, + int *waitp) +{ + struct thread_data *res = NULL; + size_t namelen = strlen(hostname); + *waitp = 0; /* default to synchronous response */ + + res = calloc(1, sizeof(struct thread_data) + namelen); + if(res) { + strcpy(res->hostname, hostname); + data->state.async.hostname = res->hostname; + data->state.async.port = port; + data->state.async.done = FALSE; /* not done */ + data->state.async.status = 0; /* clear */ + data->state.async.dns = NULL; /* clear */ + data->state.async.tdata = res; + + /* initial status - failed */ + res->last_status = ARES_ENOTFOUND; + +#ifdef HAVE_CARES_GETADDRINFO + { + struct ares_addrinfo_hints hints; + char service[12]; + int pf = PF_INET; + memset(&hints, 0, sizeof(hints)); +#ifdef CURLRES_IPV6 + if((data->conn->ip_version != CURL_IPRESOLVE_V4) && + Curl_ipv6works(data)) { + /* The stack seems to be IPv6-enabled */ + if(data->conn->ip_version == CURL_IPRESOLVE_V6) + pf = PF_INET6; + else + pf = PF_UNSPEC; + } +#endif /* CURLRES_IPV6 */ + hints.ai_family = pf; + hints.ai_socktype = (data->conn->transport == TRNSPRT_TCP)? + SOCK_STREAM : SOCK_DGRAM; + /* Since the service is a numerical one, set the hint flags + * accordingly to save a call to getservbyname in inside C-Ares + */ + hints.ai_flags = ARES_AI_NUMERICSERV; + msnprintf(service, sizeof(service), "%d", port); + res->num_pending = 1; + ares_getaddrinfo((ares_channel)data->state.async.resolver, hostname, + service, &hints, addrinfo_cb, data); + } +#else + +#ifdef HAVE_CARES_IPV6 + if((data->conn->ip_version != CURL_IPRESOLVE_V4) && Curl_ipv6works(data)) { + /* The stack seems to be IPv6-enabled */ + res->num_pending = 2; + + /* areschannel is already setup in the Curl_open() function */ + ares_gethostbyname((ares_channel)data->state.async.resolver, hostname, + PF_INET, query_completed_cb, data); + ares_gethostbyname((ares_channel)data->state.async.resolver, hostname, + PF_INET6, query_completed_cb, data); + } + else +#endif + { + res->num_pending = 1; + + /* areschannel is already setup in the Curl_open() function */ + ares_gethostbyname((ares_channel)data->state.async.resolver, + hostname, PF_INET, + query_completed_cb, data); + } +#endif + *waitp = 1; /* expect asynchronous response */ + } + return NULL; /* no struct yet */ +} + +CURLcode Curl_set_dns_servers(struct Curl_easy *data, + char *servers) +{ + CURLcode result = CURLE_NOT_BUILT_IN; + int ares_result; + + /* If server is NULL or empty, this would purge all DNS servers + * from ares library, which will cause any and all queries to fail. + * So, just return OK if none are configured and don't actually make + * any changes to c-ares. This lets c-ares use its defaults, which + * it gets from the OS (for instance from /etc/resolv.conf on Linux). + */ + if(!(servers && servers[0])) + return CURLE_OK; + +#ifdef HAVE_CARES_SERVERS_CSV +#ifdef HAVE_CARES_PORTS_CSV + ares_result = ares_set_servers_ports_csv(data->state.async.resolver, + servers); +#else + ares_result = ares_set_servers_csv(data->state.async.resolver, servers); +#endif + switch(ares_result) { + case ARES_SUCCESS: + result = CURLE_OK; + break; + case ARES_ENOMEM: + result = CURLE_OUT_OF_MEMORY; + break; + case ARES_ENOTINITIALIZED: + case ARES_ENODATA: + case ARES_EBADSTR: + default: + DEBUGF(infof(data, "bad servers set")); + result = CURLE_BAD_FUNCTION_ARGUMENT; + break; + } +#else /* too old c-ares version! */ + (void)data; + (void)(ares_result); +#endif + return result; +} + +CURLcode Curl_set_dns_interface(struct Curl_easy *data, + const char *interf) +{ +#ifdef HAVE_CARES_LOCAL_DEV + if(!interf) + interf = ""; + + ares_set_local_dev((ares_channel)data->state.async.resolver, interf); + + return CURLE_OK; +#else /* c-ares version too old! */ + (void)data; + (void)interf; + return CURLE_NOT_BUILT_IN; +#endif +} + +CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data, + const char *local_ip4) +{ +#ifdef HAVE_CARES_SET_LOCAL + struct in_addr a4; + + if((!local_ip4) || (local_ip4[0] == 0)) { + a4.s_addr = 0; /* disabled: do not bind to a specific address */ + } + else { + if(Curl_inet_pton(AF_INET, local_ip4, &a4) != 1) { + DEBUGF(infof(data, "bad DNS IPv4 address")); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + } + + ares_set_local_ip4((ares_channel)data->state.async.resolver, + ntohl(a4.s_addr)); + + return CURLE_OK; +#else /* c-ares version too old! */ + (void)data; + (void)local_ip4; + return CURLE_NOT_BUILT_IN; +#endif +} + +CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data, + const char *local_ip6) +{ +#if defined(HAVE_CARES_SET_LOCAL) && defined(USE_IPV6) + unsigned char a6[INET6_ADDRSTRLEN]; + + if((!local_ip6) || (local_ip6[0] == 0)) { + /* disabled: do not bind to a specific address */ + memset(a6, 0, sizeof(a6)); + } + else { + if(Curl_inet_pton(AF_INET6, local_ip6, a6) != 1) { + DEBUGF(infof(data, "bad DNS IPv6 address")); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + } + + ares_set_local_ip6((ares_channel)data->state.async.resolver, a6); + + return CURLE_OK; +#else /* c-ares version too old! */ + (void)data; + (void)local_ip6; + return CURLE_NOT_BUILT_IN; +#endif +} +#endif /* CURLRES_ARES */ diff --git a/third_party/curl/lib/asyn-thread.c b/third_party/curl/lib/asyn-thread.c new file mode 100644 index 0000000..1760d6c --- /dev/null +++ b/third_party/curl/lib/asyn-thread.c @@ -0,0 +1,998 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "socketpair.h" + +/*********************************************************************** + * Only for threaded name resolves builds + **********************************************************************/ +#ifdef CURLRES_THREADED + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef __VMS +#include +#include +#endif + +#if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) +# include +#endif + +#ifdef HAVE_GETADDRINFO +# define RESOLVER_ENOMEM EAI_MEMORY +#else +# define RESOLVER_ENOMEM ENOMEM +#endif + +#include "system_win32.h" +#include "urldata.h" +#include "sendf.h" +#include "hostip.h" +#include "hash.h" +#include "share.h" +#include "url.h" +#include "multiif.h" +#include "inet_ntop.h" +#include "curl_threads.h" +#include "connect.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +struct resdata { + struct curltime start; +}; + +/* + * Curl_resolver_global_init() + * Called from curl_global_init() to initialize global resolver environment. + * Does nothing here. + */ +int Curl_resolver_global_init(void) +{ + return CURLE_OK; +} + +/* + * Curl_resolver_global_cleanup() + * Called from curl_global_cleanup() to destroy global resolver environment. + * Does nothing here. + */ +void Curl_resolver_global_cleanup(void) +{ +} + +/* + * Curl_resolver_init() + * Called from curl_easy_init() -> Curl_open() to initialize resolver + * URL-state specific environment ('resolver' member of the UrlState + * structure). + */ +CURLcode Curl_resolver_init(struct Curl_easy *easy, void **resolver) +{ + (void)easy; + *resolver = calloc(1, sizeof(struct resdata)); + if(!*resolver) + return CURLE_OUT_OF_MEMORY; + return CURLE_OK; +} + +/* + * Curl_resolver_cleanup() + * Called from curl_easy_cleanup() -> Curl_close() to cleanup resolver + * URL-state specific environment ('resolver' member of the UrlState + * structure). + */ +void Curl_resolver_cleanup(void *resolver) +{ + free(resolver); +} + +/* + * Curl_resolver_duphandle() + * Called from curl_easy_duphandle() to duplicate resolver URL state-specific + * environment ('resolver' member of the UrlState structure). + */ +CURLcode Curl_resolver_duphandle(struct Curl_easy *easy, void **to, void *from) +{ + (void)from; + return Curl_resolver_init(easy, to); +} + +static void destroy_async_data(struct Curl_async *); + +/* + * Cancel all possibly still on-going resolves for this connection. + */ +void Curl_resolver_cancel(struct Curl_easy *data) +{ + destroy_async_data(&data->state.async); +} + +/* This function is used to init a threaded resolve */ +static bool init_resolve_thread(struct Curl_easy *data, + const char *hostname, int port, + const struct addrinfo *hints); + +#ifdef _WIN32 +/* Thread sync data used by GetAddrInfoExW for win8+ */ +struct thread_sync_data_w8 +{ + OVERLAPPED overlapped; + ADDRINFOEXW_ *res; + HANDLE cancel_ev; + ADDRINFOEXW_ hints; +}; +#endif + +/* Data for synchronization between resolver thread and its parent */ +struct thread_sync_data { +#ifdef _WIN32 + struct thread_sync_data_w8 w8; +#endif + curl_mutex_t *mtx; + int done; + int port; + char *hostname; /* hostname to resolve, Curl_async.hostname + duplicate */ +#ifndef CURL_DISABLE_SOCKETPAIR + struct Curl_easy *data; + curl_socket_t sock_pair[2]; /* socket pair */ +#endif + int sock_error; + struct Curl_addrinfo *res; +#ifdef HAVE_GETADDRINFO + struct addrinfo hints; +#endif + struct thread_data *td; /* for thread-self cleanup */ +}; + +struct thread_data { +#ifdef _WIN32 + HANDLE complete_ev; +#endif + curl_thread_t thread_hnd; + unsigned int poll_interval; + timediff_t interval_end; + struct thread_sync_data tsd; +}; + +static struct thread_sync_data *conn_thread_sync_data(struct Curl_easy *data) +{ + return &(data->state.async.tdata->tsd); +} + +/* Destroy resolver thread synchronization data */ +static +void destroy_thread_sync_data(struct thread_sync_data *tsd) +{ + if(tsd->mtx) { + Curl_mutex_destroy(tsd->mtx); + free(tsd->mtx); + } + + free(tsd->hostname); + + if(tsd->res) + Curl_freeaddrinfo(tsd->res); + +#ifndef CURL_DISABLE_SOCKETPAIR + /* + * close one end of the socket pair (may be done in resolver thread); + * the other end (for reading) is always closed in the parent thread. + */ + if(tsd->sock_pair[1] != CURL_SOCKET_BAD) { + wakeup_close(tsd->sock_pair[1]); + } +#endif + memset(tsd, 0, sizeof(*tsd)); +} + +/* Initialize resolver thread synchronization data */ +static +int init_thread_sync_data(struct thread_data *td, + const char *hostname, + int port, + const struct addrinfo *hints) +{ + struct thread_sync_data *tsd = &td->tsd; + + memset(tsd, 0, sizeof(*tsd)); + + tsd->td = td; + tsd->port = port; + /* Treat the request as done until the thread actually starts so any early + * cleanup gets done properly. + */ + tsd->done = 1; +#ifdef HAVE_GETADDRINFO + DEBUGASSERT(hints); + tsd->hints = *hints; +#else + (void) hints; +#endif + + tsd->mtx = malloc(sizeof(curl_mutex_t)); + if(!tsd->mtx) + goto err_exit; + + Curl_mutex_init(tsd->mtx); + +#ifndef CURL_DISABLE_SOCKETPAIR + /* create socket pair or pipe */ + if(wakeup_create(&tsd->sock_pair[0]) < 0) { + tsd->sock_pair[0] = CURL_SOCKET_BAD; + tsd->sock_pair[1] = CURL_SOCKET_BAD; + goto err_exit; + } +#endif + tsd->sock_error = CURL_ASYNC_SUCCESS; + + /* Copying hostname string because original can be destroyed by parent + * thread during gethostbyname execution. + */ + tsd->hostname = strdup(hostname); + if(!tsd->hostname) + goto err_exit; + + return 1; + +err_exit: +#ifndef CURL_DISABLE_SOCKETPAIR + if(tsd->sock_pair[0] != CURL_SOCKET_BAD) { + wakeup_close(tsd->sock_pair[0]); + tsd->sock_pair[0] = CURL_SOCKET_BAD; + } +#endif + destroy_thread_sync_data(tsd); + return 0; +} + +static CURLcode getaddrinfo_complete(struct Curl_easy *data) +{ + struct thread_sync_data *tsd = conn_thread_sync_data(data); + CURLcode result; + + result = Curl_addrinfo_callback(data, tsd->sock_error, tsd->res); + /* The tsd->res structure has been copied to async.dns and perhaps the DNS + cache. Set our copy to NULL so destroy_thread_sync_data doesn't free it. + */ + tsd->res = NULL; + + return result; +} + +#ifdef _WIN32 +static VOID WINAPI +query_complete(DWORD err, DWORD bytes, LPWSAOVERLAPPED overlapped) +{ + size_t ss_size; + const ADDRINFOEXW_ *ai; + struct Curl_addrinfo *ca; + struct Curl_addrinfo *cafirst = NULL; + struct Curl_addrinfo *calast = NULL; +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcast-align" +#endif + struct thread_sync_data *tsd = + CONTAINING_RECORD(overlapped, struct thread_sync_data, w8.overlapped); +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + struct thread_data *td = tsd->td; + const ADDRINFOEXW_ *res = tsd->w8.res; + int error = (int)err; + (void)bytes; + + if(error == ERROR_SUCCESS) { + /* traverse the addrinfo list */ + + for(ai = res; ai != NULL; ai = ai->ai_next) { + size_t namelen = ai->ai_canonname ? wcslen(ai->ai_canonname) + 1 : 0; + /* ignore elements with unsupported address family, */ + /* settle family-specific sockaddr structure size. */ + if(ai->ai_family == AF_INET) + ss_size = sizeof(struct sockaddr_in); +#ifdef USE_IPV6 + else if(ai->ai_family == AF_INET6) + ss_size = sizeof(struct sockaddr_in6); +#endif + else + continue; + + /* ignore elements without required address info */ + if(!ai->ai_addr || !(ai->ai_addrlen > 0)) + continue; + + /* ignore elements with bogus address size */ + if((size_t)ai->ai_addrlen < ss_size) + continue; + + ca = malloc(sizeof(struct Curl_addrinfo) + ss_size + namelen); + if(!ca) { + error = EAI_MEMORY; + break; + } + + /* copy each structure member individually, member ordering, */ + /* size, or padding might be different for each platform. */ + ca->ai_flags = ai->ai_flags; + ca->ai_family = ai->ai_family; + ca->ai_socktype = ai->ai_socktype; + ca->ai_protocol = ai->ai_protocol; + ca->ai_addrlen = (curl_socklen_t)ss_size; + ca->ai_addr = NULL; + ca->ai_canonname = NULL; + ca->ai_next = NULL; + + ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo)); + memcpy(ca->ai_addr, ai->ai_addr, ss_size); + + if(namelen) { + size_t i; + ca->ai_canonname = (void *)((char *)ca->ai_addr + ss_size); + for(i = 0; i < namelen; ++i) /* convert wide string to ascii */ + ca->ai_canonname[i] = (char)ai->ai_canonname[i]; + ca->ai_canonname[namelen] = '\0'; + } + + /* if the return list is empty, this becomes the first element */ + if(!cafirst) + cafirst = ca; + + /* add this element last in the return list */ + if(calast) + calast->ai_next = ca; + calast = ca; + } + + /* if we failed, also destroy the Curl_addrinfo list */ + if(error) { + Curl_freeaddrinfo(cafirst); + cafirst = NULL; + } + else if(!cafirst) { +#ifdef EAI_NONAME + /* rfc3493 conformant */ + error = EAI_NONAME; +#else + /* rfc3493 obsoleted */ + error = EAI_NODATA; +#endif +#ifdef USE_WINSOCK + SET_SOCKERRNO(error); +#endif + } + tsd->res = cafirst; + } + + if(tsd->w8.res) { + Curl_FreeAddrInfoExW(tsd->w8.res); + tsd->w8.res = NULL; + } + + if(error) { + tsd->sock_error = SOCKERRNO?SOCKERRNO:error; + if(tsd->sock_error == 0) + tsd->sock_error = RESOLVER_ENOMEM; + } + else { + Curl_addrinfo_set_port(tsd->res, tsd->port); + } + + Curl_mutex_acquire(tsd->mtx); + if(tsd->done) { + /* too late, gotta clean up the mess */ + Curl_mutex_release(tsd->mtx); + destroy_thread_sync_data(tsd); + free(td); + } + else { +#ifndef CURL_DISABLE_SOCKETPAIR + char buf[1]; + if(tsd->sock_pair[1] != CURL_SOCKET_BAD) { + /* DNS has been resolved, signal client task */ + buf[0] = 1; + if(swrite(tsd->sock_pair[1], buf, sizeof(buf)) < 0) { + /* update sock_erro to errno */ + tsd->sock_error = SOCKERRNO; + } + } +#endif + tsd->done = 1; + Curl_mutex_release(tsd->mtx); + if(td->complete_ev) + SetEvent(td->complete_ev); /* Notify caller that the query completed */ + } +} +#endif + +#ifdef HAVE_GETADDRINFO + +/* + * getaddrinfo_thread() resolves a name and then exits. + * + * For builds without ARES, but with USE_IPV6, create a resolver thread + * and wait on it. + */ +static unsigned int CURL_STDCALL getaddrinfo_thread(void *arg) +{ + struct thread_sync_data *tsd = (struct thread_sync_data *)arg; + struct thread_data *td = tsd->td; + char service[12]; + int rc; +#ifndef CURL_DISABLE_SOCKETPAIR + char buf[1]; +#endif + + msnprintf(service, sizeof(service), "%d", tsd->port); + + rc = Curl_getaddrinfo_ex(tsd->hostname, service, &tsd->hints, &tsd->res); + + if(rc) { + tsd->sock_error = SOCKERRNO?SOCKERRNO:rc; + if(tsd->sock_error == 0) + tsd->sock_error = RESOLVER_ENOMEM; + } + else { + Curl_addrinfo_set_port(tsd->res, tsd->port); + } + + Curl_mutex_acquire(tsd->mtx); + if(tsd->done) { + /* too late, gotta clean up the mess */ + Curl_mutex_release(tsd->mtx); + destroy_thread_sync_data(tsd); + free(td); + } + else { +#ifndef CURL_DISABLE_SOCKETPAIR + if(tsd->sock_pair[1] != CURL_SOCKET_BAD) { + /* DNS has been resolved, signal client task */ + buf[0] = 1; + if(wakeup_write(tsd->sock_pair[1], buf, sizeof(buf)) < 0) { + /* update sock_erro to errno */ + tsd->sock_error = SOCKERRNO; + } + } +#endif + tsd->done = 1; + Curl_mutex_release(tsd->mtx); + } + + return 0; +} + +#else /* HAVE_GETADDRINFO */ + +/* + * gethostbyname_thread() resolves a name and then exits. + */ +static unsigned int CURL_STDCALL gethostbyname_thread(void *arg) +{ + struct thread_sync_data *tsd = (struct thread_sync_data *)arg; + struct thread_data *td = tsd->td; + + tsd->res = Curl_ipv4_resolve_r(tsd->hostname, tsd->port); + + if(!tsd->res) { + tsd->sock_error = SOCKERRNO; + if(tsd->sock_error == 0) + tsd->sock_error = RESOLVER_ENOMEM; + } + + Curl_mutex_acquire(tsd->mtx); + if(tsd->done) { + /* too late, gotta clean up the mess */ + Curl_mutex_release(tsd->mtx); + destroy_thread_sync_data(tsd); + free(td); + } + else { + tsd->done = 1; + Curl_mutex_release(tsd->mtx); + } + + return 0; +} + +#endif /* HAVE_GETADDRINFO */ + +/* + * destroy_async_data() cleans up async resolver data and thread handle. + */ +static void destroy_async_data(struct Curl_async *async) +{ + if(async->tdata) { + struct thread_data *td = async->tdata; + int done; +#ifndef CURL_DISABLE_SOCKETPAIR + curl_socket_t sock_rd = td->tsd.sock_pair[0]; + struct Curl_easy *data = td->tsd.data; +#endif + + /* + * if the thread is still blocking in the resolve syscall, detach it and + * let the thread do the cleanup... + */ + Curl_mutex_acquire(td->tsd.mtx); + done = td->tsd.done; + td->tsd.done = 1; + Curl_mutex_release(td->tsd.mtx); + + if(!done) { +#ifdef _WIN32 + if(td->complete_ev) { + CloseHandle(td->complete_ev); + td->complete_ev = NULL; + } +#endif + if(td->thread_hnd != curl_thread_t_null) { + Curl_thread_destroy(td->thread_hnd); + td->thread_hnd = curl_thread_t_null; + } + } + else { +#ifdef _WIN32 + if(td->complete_ev) { + Curl_GetAddrInfoExCancel(&td->tsd.w8.cancel_ev); + WaitForSingleObject(td->complete_ev, INFINITE); + CloseHandle(td->complete_ev); + td->complete_ev = NULL; + } +#endif + if(td->thread_hnd != curl_thread_t_null) + Curl_thread_join(&td->thread_hnd); + + destroy_thread_sync_data(&td->tsd); + + free(async->tdata); + } +#ifndef CURL_DISABLE_SOCKETPAIR + /* + * ensure CURLMOPT_SOCKETFUNCTION fires CURL_POLL_REMOVE + * before the FD is invalidated to avoid EBADF on EPOLL_CTL_DEL + */ + Curl_multi_closed(data, sock_rd); + wakeup_close(sock_rd); +#endif + } + async->tdata = NULL; + + free(async->hostname); + async->hostname = NULL; +} + +/* + * init_resolve_thread() starts a new thread that performs the actual + * resolve. This function returns before the resolve is done. + * + * Returns FALSE in case of failure, otherwise TRUE. + */ +static bool init_resolve_thread(struct Curl_easy *data, + const char *hostname, int port, + const struct addrinfo *hints) +{ + struct thread_data *td = calloc(1, sizeof(struct thread_data)); + int err = ENOMEM; + struct Curl_async *asp = &data->state.async; + + data->state.async.tdata = td; + if(!td) + goto errno_exit; + + asp->port = port; + asp->done = FALSE; + asp->status = 0; + asp->dns = NULL; + td->thread_hnd = curl_thread_t_null; +#ifdef _WIN32 + td->complete_ev = NULL; +#endif + + if(!init_thread_sync_data(td, hostname, port, hints)) { + asp->tdata = NULL; + free(td); + goto errno_exit; + } + + free(asp->hostname); + asp->hostname = strdup(hostname); + if(!asp->hostname) + goto err_exit; + + /* The thread will set this to 1 when complete. */ + td->tsd.done = 0; + +#ifdef _WIN32 + if(Curl_isWindows8OrGreater && Curl_FreeAddrInfoExW && + Curl_GetAddrInfoExCancel && Curl_GetAddrInfoExW) { +#define MAX_NAME_LEN 256 /* max domain name is 253 chars */ +#define MAX_PORT_LEN 8 + WCHAR namebuf[MAX_NAME_LEN]; + WCHAR portbuf[MAX_PORT_LEN]; + /* calculate required length */ + int w_len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, hostname, + -1, NULL, 0); + if((w_len > 0) && (w_len < MAX_NAME_LEN)) { + /* do utf8 conversion */ + w_len = MultiByteToWideChar(CP_UTF8, 0, hostname, -1, namebuf, w_len); + if((w_len > 0) && (w_len < MAX_NAME_LEN)) { + swprintf(portbuf, MAX_PORT_LEN, L"%d", port); + td->tsd.w8.hints.ai_family = hints->ai_family; + td->tsd.w8.hints.ai_socktype = hints->ai_socktype; + td->complete_ev = CreateEvent(NULL, TRUE, FALSE, NULL); + if(!td->complete_ev) { + /* failed to start, mark it as done here for proper cleanup. */ + td->tsd.done = 1; + goto err_exit; + } + err = Curl_GetAddrInfoExW(namebuf, portbuf, NS_DNS, + NULL, &td->tsd.w8.hints, &td->tsd.w8.res, + NULL, &td->tsd.w8.overlapped, + &query_complete, &td->tsd.w8.cancel_ev); + if(err != WSA_IO_PENDING) + query_complete(err, 0, &td->tsd.w8.overlapped); + return TRUE; + } + } + } +#endif + +#ifdef HAVE_GETADDRINFO + td->thread_hnd = Curl_thread_create(getaddrinfo_thread, &td->tsd); +#else + td->thread_hnd = Curl_thread_create(gethostbyname_thread, &td->tsd); +#endif + + if(td->thread_hnd == curl_thread_t_null) { + /* The thread never started, so mark it as done here for proper cleanup. */ + td->tsd.done = 1; + err = errno; + goto err_exit; + } + + return TRUE; + +err_exit: + destroy_async_data(asp); + +errno_exit: + errno = err; + return FALSE; +} + +/* + * 'entry' may be NULL and then no data is returned + */ +static CURLcode thread_wait_resolv(struct Curl_easy *data, + struct Curl_dns_entry **entry, + bool report) +{ + struct thread_data *td; + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + td = data->state.async.tdata; + DEBUGASSERT(td); +#ifdef _WIN32 + DEBUGASSERT(td->complete_ev || td->thread_hnd != curl_thread_t_null); +#else + DEBUGASSERT(td->thread_hnd != curl_thread_t_null); +#endif + + /* wait for the thread to resolve the name */ +#ifdef _WIN32 + if(td->complete_ev) { + WaitForSingleObject(td->complete_ev, INFINITE); + CloseHandle(td->complete_ev); + td->complete_ev = NULL; + if(entry) + result = getaddrinfo_complete(data); + } + else +#endif + if(Curl_thread_join(&td->thread_hnd)) { + if(entry) + result = getaddrinfo_complete(data); + } + else + DEBUGASSERT(0); + + data->state.async.done = TRUE; + + if(entry) + *entry = data->state.async.dns; + + if(!data->state.async.dns && report) + /* a name was not resolved, report error */ + result = Curl_resolver_error(data); + + destroy_async_data(&data->state.async); + + if(!data->state.async.dns && report) + connclose(data->conn, "asynch resolve failed"); + + return result; +} + + +/* + * Until we gain a way to signal the resolver threads to stop early, we must + * simply wait for them and ignore their results. + */ +void Curl_resolver_kill(struct Curl_easy *data) +{ + struct thread_data *td = data->state.async.tdata; + + /* If we're still resolving, we must wait for the threads to fully clean up, + unfortunately. Otherwise, we can simply cancel to clean up any resolver + data. */ +#ifdef _WIN32 + if(td && td->complete_ev) { + Curl_GetAddrInfoExCancel(&td->tsd.w8.cancel_ev); + (void)thread_wait_resolv(data, NULL, FALSE); + } + else +#endif + if(td && td->thread_hnd != curl_thread_t_null + && (data->set.quick_exit != 1L)) + (void)thread_wait_resolv(data, NULL, FALSE); + else + Curl_resolver_cancel(data); +} + +/* + * Curl_resolver_wait_resolv() + * + * Waits for a resolve to finish. This function should be avoided since using + * this risk getting the multi interface to "hang". + * + * If 'entry' is non-NULL, make it point to the resolved dns entry + * + * Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved, + * CURLE_OPERATION_TIMEDOUT if a time-out occurred, or other errors. + * + * This is the version for resolves-in-a-thread. + */ +CURLcode Curl_resolver_wait_resolv(struct Curl_easy *data, + struct Curl_dns_entry **entry) +{ + return thread_wait_resolv(data, entry, TRUE); +} + +/* + * Curl_resolver_is_resolved() is called repeatedly to check if a previous + * name resolve request has completed. It should also make sure to time-out if + * the operation seems to take too long. + */ +CURLcode Curl_resolver_is_resolved(struct Curl_easy *data, + struct Curl_dns_entry **entry) +{ + struct thread_data *td = data->state.async.tdata; + int done = 0; + + DEBUGASSERT(entry); + *entry = NULL; + + if(!td) { + DEBUGASSERT(td); + return CURLE_COULDNT_RESOLVE_HOST; + } + + Curl_mutex_acquire(td->tsd.mtx); + done = td->tsd.done; + Curl_mutex_release(td->tsd.mtx); + + if(done) { + getaddrinfo_complete(data); + + if(!data->state.async.dns) { + CURLcode result = Curl_resolver_error(data); + destroy_async_data(&data->state.async); + return result; + } + destroy_async_data(&data->state.async); + *entry = data->state.async.dns; + } + else { + /* poll for name lookup done with exponential backoff up to 250ms */ + /* should be fine even if this converts to 32 bit */ + timediff_t elapsed = Curl_timediff(Curl_now(), + data->progress.t_startsingle); + if(elapsed < 0) + elapsed = 0; + + if(td->poll_interval == 0) + /* Start at 1ms poll interval */ + td->poll_interval = 1; + else if(elapsed >= td->interval_end) + /* Back-off exponentially if last interval expired */ + td->poll_interval *= 2; + + if(td->poll_interval > 250) + td->poll_interval = 250; + + td->interval_end = elapsed + td->poll_interval; + Curl_expire(data, td->poll_interval, EXPIRE_ASYNC_NAME); + } + + return CURLE_OK; +} + +int Curl_resolver_getsock(struct Curl_easy *data, curl_socket_t *socks) +{ + int ret_val = 0; + timediff_t milli; + timediff_t ms; + struct resdata *reslv = (struct resdata *)data->state.async.resolver; +#ifndef CURL_DISABLE_SOCKETPAIR + struct thread_data *td = data->state.async.tdata; +#else + (void)socks; +#endif + +#ifndef CURL_DISABLE_SOCKETPAIR + if(td) { + /* return read fd to client for polling the DNS resolution status */ + socks[0] = td->tsd.sock_pair[0]; + td->tsd.data = data; + ret_val = GETSOCK_READSOCK(0); + } + else { +#endif + ms = Curl_timediff(Curl_now(), reslv->start); + if(ms < 3) + milli = 0; + else if(ms <= 50) + milli = ms/3; + else if(ms <= 250) + milli = 50; + else + milli = 200; + Curl_expire(data, milli, EXPIRE_ASYNC_NAME); +#ifndef CURL_DISABLE_SOCKETPAIR + } +#endif + + + return ret_val; +} + +#ifndef HAVE_GETADDRINFO +/* + * Curl_getaddrinfo() - for platforms without getaddrinfo + */ +struct Curl_addrinfo *Curl_resolver_getaddrinfo(struct Curl_easy *data, + const char *hostname, + int port, + int *waitp) +{ + struct resdata *reslv = (struct resdata *)data->state.async.resolver; + + *waitp = 0; /* default to synchronous response */ + + reslv->start = Curl_now(); + + /* fire up a new resolver thread! */ + if(init_resolve_thread(data, hostname, port, NULL)) { + *waitp = 1; /* expect asynchronous response */ + return NULL; + } + + failf(data, "getaddrinfo() thread failed"); + + return NULL; +} + +#else /* !HAVE_GETADDRINFO */ + +/* + * Curl_resolver_getaddrinfo() - for getaddrinfo + */ +struct Curl_addrinfo *Curl_resolver_getaddrinfo(struct Curl_easy *data, + const char *hostname, + int port, + int *waitp) +{ + struct addrinfo hints; + int pf = PF_INET; + struct resdata *reslv = (struct resdata *)data->state.async.resolver; + + *waitp = 0; /* default to synchronous response */ + +#ifdef CURLRES_IPV6 + if((data->conn->ip_version != CURL_IPRESOLVE_V4) && Curl_ipv6works(data)) { + /* The stack seems to be IPv6-enabled */ + if(data->conn->ip_version == CURL_IPRESOLVE_V6) + pf = PF_INET6; + else + pf = PF_UNSPEC; + } +#endif /* CURLRES_IPV6 */ + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = pf; + hints.ai_socktype = (data->conn->transport == TRNSPRT_TCP)? + SOCK_STREAM : SOCK_DGRAM; + + reslv->start = Curl_now(); + /* fire up a new resolver thread! */ + if(init_resolve_thread(data, hostname, port, &hints)) { + *waitp = 1; /* expect asynchronous response */ + return NULL; + } + + failf(data, "getaddrinfo() thread failed to start"); + return NULL; + +} + +#endif /* !HAVE_GETADDRINFO */ + +CURLcode Curl_set_dns_servers(struct Curl_easy *data, + char *servers) +{ + (void)data; + (void)servers; + return CURLE_NOT_BUILT_IN; + +} + +CURLcode Curl_set_dns_interface(struct Curl_easy *data, + const char *interf) +{ + (void)data; + (void)interf; + return CURLE_NOT_BUILT_IN; +} + +CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data, + const char *local_ip4) +{ + (void)data; + (void)local_ip4; + return CURLE_NOT_BUILT_IN; +} + +CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data, + const char *local_ip6) +{ + (void)data; + (void)local_ip6; + return CURLE_NOT_BUILT_IN; +} + +#endif /* CURLRES_THREADED */ diff --git a/third_party/curl/lib/asyn.h b/third_party/curl/lib/asyn.h new file mode 100644 index 0000000..7e207c4 --- /dev/null +++ b/third_party/curl/lib/asyn.h @@ -0,0 +1,184 @@ +#ifndef HEADER_CURL_ASYN_H +#define HEADER_CURL_ASYN_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "curl_addrinfo.h" + +struct addrinfo; +struct hostent; +struct Curl_easy; +struct connectdata; +struct Curl_dns_entry; + +/* + * This header defines all functions in the internal asynch resolver interface. + * All asynch resolvers need to provide these functions. + * asyn-ares.c and asyn-thread.c are the current implementations of asynch + * resolver backends. + */ + +/* + * Curl_resolver_global_init() + * + * Called from curl_global_init() to initialize global resolver environment. + * Returning anything else than CURLE_OK fails curl_global_init(). + */ +int Curl_resolver_global_init(void); + +/* + * Curl_resolver_global_cleanup() + * Called from curl_global_cleanup() to destroy global resolver environment. + */ +void Curl_resolver_global_cleanup(void); + +/* + * Curl_resolver_init() + * Called from curl_easy_init() -> Curl_open() to initialize resolver + * URL-state specific environment ('resolver' member of the UrlState + * structure). Should fill the passed pointer by the initialized handler. + * Returning anything else than CURLE_OK fails curl_easy_init() with the + * correspondent code. + */ +CURLcode Curl_resolver_init(struct Curl_easy *easy, void **resolver); + +/* + * Curl_resolver_cleanup() + * Called from curl_easy_cleanup() -> Curl_close() to cleanup resolver + * URL-state specific environment ('resolver' member of the UrlState + * structure). Should destroy the handler and free all resources connected to + * it. + */ +void Curl_resolver_cleanup(void *resolver); + +/* + * Curl_resolver_duphandle() + * Called from curl_easy_duphandle() to duplicate resolver URL-state specific + * environment ('resolver' member of the UrlState structure). Should + * duplicate the 'from' handle and pass the resulting handle to the 'to' + * pointer. Returning anything else than CURLE_OK causes failed + * curl_easy_duphandle() call. + */ +CURLcode Curl_resolver_duphandle(struct Curl_easy *easy, void **to, + void *from); + +/* + * Curl_resolver_cancel(). + * + * It is called from inside other functions to cancel currently performing + * resolver request. Should also free any temporary resources allocated to + * perform a request. This never waits for resolver threads to complete. + * + * It is safe to call this when conn is in any state. + */ +void Curl_resolver_cancel(struct Curl_easy *data); + +/* + * Curl_resolver_kill(). + * + * This acts like Curl_resolver_cancel() except it will block until any threads + * associated with the resolver are complete. This never blocks for resolvers + * that do not use threads. This is intended to be the "last chance" function + * that cleans up an in-progress resolver completely (before its owner is about + * to die). + * + * It is safe to call this when conn is in any state. + */ +void Curl_resolver_kill(struct Curl_easy *data); + +/* Curl_resolver_getsock() + * + * This function is called from the multi_getsock() function. 'sock' is a + * pointer to an array to hold the file descriptors, with 'numsock' being the + * size of that array (in number of entries). This function is supposed to + * return bitmask indicating what file descriptors (referring to array indexes + * in the 'sock' array) to wait for, read/write. + */ +int Curl_resolver_getsock(struct Curl_easy *data, curl_socket_t *sock); + +/* + * Curl_resolver_is_resolved() + * + * Called repeatedly to check if a previous name resolve request has + * completed. It should also make sure to time-out if the operation seems to + * take too long. + * + * Returns normal CURLcode errors. + */ +CURLcode Curl_resolver_is_resolved(struct Curl_easy *data, + struct Curl_dns_entry **dns); + +/* + * Curl_resolver_wait_resolv() + * + * Waits for a resolve to finish. This function should be avoided since using + * this risk getting the multi interface to "hang". + * + * If 'entry' is non-NULL, make it point to the resolved dns entry + * + * Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved, + * CURLE_OPERATION_TIMEDOUT if a time-out occurred, or other errors. + */ +CURLcode Curl_resolver_wait_resolv(struct Curl_easy *data, + struct Curl_dns_entry **dnsentry); + +/* + * Curl_resolver_getaddrinfo() - when using this resolver + * + * Returns name information about the given hostname and port number. If + * successful, the 'hostent' is returned and the fourth argument will point to + * memory we need to free after use. That memory *MUST* be freed with + * Curl_freeaddrinfo(), nothing else. + * + * Each resolver backend must of course make sure to return data in the + * correct format to comply with this. + */ +struct Curl_addrinfo *Curl_resolver_getaddrinfo(struct Curl_easy *data, + const char *hostname, + int port, + int *waitp); + +#ifndef CURLRES_ASYNCH +/* convert these functions if an asynch resolver isn't used */ +#define Curl_resolver_cancel(x) Curl_nop_stmt +#define Curl_resolver_kill(x) Curl_nop_stmt +#define Curl_resolver_is_resolved(x,y) CURLE_COULDNT_RESOLVE_HOST +#define Curl_resolver_wait_resolv(x,y) CURLE_COULDNT_RESOLVE_HOST +#define Curl_resolver_duphandle(x,y,z) CURLE_OK +#define Curl_resolver_init(x,y) CURLE_OK +#define Curl_resolver_global_init() CURLE_OK +#define Curl_resolver_global_cleanup() Curl_nop_stmt +#define Curl_resolver_cleanup(x) Curl_nop_stmt +#endif + +#ifdef CURLRES_ASYNCH +#define Curl_resolver_asynch() 1 +#else +#define Curl_resolver_asynch() 0 +#endif + + +/********** end of generic resolver interface functions *****************/ +#endif /* HEADER_CURL_ASYN_H */ diff --git a/third_party/curl/lib/base64.c b/third_party/curl/lib/base64.c new file mode 100644 index 0000000..8373115 --- /dev/null +++ b/third_party/curl/lib/base64.c @@ -0,0 +1,293 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* Base64 encoding/decoding */ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP_AUTH) || defined(USE_SSH) || \ + !defined(CURL_DISABLE_LDAP) || \ + !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_POP3) || \ + !defined(CURL_DISABLE_IMAP) || \ + !defined(CURL_DISABLE_DIGEST_AUTH) || \ + !defined(CURL_DISABLE_DOH) || defined(USE_SSL) || defined(BUILDING_CURL) +#include "curl/curl.h" +#include "warnless.h" +#include "curl_base64.h" + +/* The last 2 #include files should be in this order */ +#ifdef BUILDING_LIBCURL +#include "curl_memory.h" +#endif +#include "memdebug.h" + +/* ---- Base64 Encoding/Decoding Table --- */ +/* Padding character string starts at offset 64. */ +static const char base64encdec[]= + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +/* The Base 64 encoding with a URL and filename safe alphabet, RFC 4648 + section 5 */ +static const char base64url[]= + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + +static const unsigned char decodetable[] = +{ 62, 255, 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, + 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, 255, 26, 27, 28, + 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51 }; +/* + * Curl_base64_decode() + * + * Given a base64 NUL-terminated string at src, decode it and return a + * pointer in *outptr to a newly allocated memory area holding decoded + * data. Size of decoded data is returned in variable pointed by outlen. + * + * Returns CURLE_OK on success, otherwise specific error code. Function + * output shall not be considered valid unless CURLE_OK is returned. + * + * When decoded data length is 0, returns NULL in *outptr. + * + * @unittest: 1302 + */ +CURLcode Curl_base64_decode(const char *src, + unsigned char **outptr, size_t *outlen) +{ + size_t srclen = 0; + size_t padding = 0; + size_t i; + size_t numQuantums; + size_t fullQuantums; + size_t rawlen = 0; + unsigned char *pos; + unsigned char *newstr; + unsigned char lookup[256]; + + *outptr = NULL; + *outlen = 0; + srclen = strlen(src); + + /* Check the length of the input string is valid */ + if(!srclen || srclen % 4) + return CURLE_BAD_CONTENT_ENCODING; + + /* srclen is at least 4 here */ + while(src[srclen - 1 - padding] == '=') { + /* count padding characters */ + padding++; + /* A maximum of two = padding characters is allowed */ + if(padding > 2) + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Calculate the number of quantums */ + numQuantums = srclen / 4; + fullQuantums = numQuantums - (padding ? 1 : 0); + + /* Calculate the size of the decoded string */ + rawlen = (numQuantums * 3) - padding; + + /* Allocate our buffer including room for a null-terminator */ + newstr = malloc(rawlen + 1); + if(!newstr) + return CURLE_OUT_OF_MEMORY; + + pos = newstr; + + memset(lookup, 0xff, sizeof(lookup)); + memcpy(&lookup['+'], decodetable, sizeof(decodetable)); + /* replaces + { + unsigned char c; + const unsigned char *p = (const unsigned char *)base64encdec; + for(c = 0; *p; c++, p++) + lookup[*p] = c; + } + */ + + /* Decode the complete quantums first */ + for(i = 0; i < fullQuantums; i++) { + unsigned char val; + unsigned int x = 0; + int j; + + for(j = 0; j < 4; j++) { + val = lookup[(unsigned char)*src++]; + if(val == 0xff) /* bad symbol */ + goto bad; + x = (x << 6) | val; + } + pos[2] = x & 0xff; + pos[1] = (x >> 8) & 0xff; + pos[0] = (x >> 16) & 0xff; + pos += 3; + } + if(padding) { + /* this means either 8 or 16 bits output */ + unsigned char val; + unsigned int x = 0; + int j; + size_t padc = 0; + for(j = 0; j < 4; j++) { + if(*src == '=') { + x <<= 6; + src++; + if(++padc > padding) + /* this is a badly placed '=' symbol! */ + goto bad; + } + else { + val = lookup[(unsigned char)*src++]; + if(val == 0xff) /* bad symbol */ + goto bad; + x = (x << 6) | val; + } + } + if(padding == 1) + pos[1] = (x >> 8) & 0xff; + pos[0] = (x >> 16) & 0xff; + pos += 3 - padding; + } + + /* Zero terminate */ + *pos = '\0'; + + /* Return the decoded data */ + *outptr = newstr; + *outlen = rawlen; + + return CURLE_OK; +bad: + free(newstr); + return CURLE_BAD_CONTENT_ENCODING; +} + +static CURLcode base64_encode(const char *table64, + const char *inputbuff, size_t insize, + char **outptr, size_t *outlen) +{ + char *output; + char *base64data; + const unsigned char *in = (unsigned char *)inputbuff; + const char *padstr = &table64[64]; /* Point to padding string. */ + + *outptr = NULL; + *outlen = 0; + + if(!insize) + insize = strlen(inputbuff); + +#if SIZEOF_SIZE_T == 4 + if(insize > UINT_MAX/4) + return CURLE_OUT_OF_MEMORY; +#endif + + base64data = output = malloc((insize + 2) / 3 * 4 + 1); + if(!output) + return CURLE_OUT_OF_MEMORY; + + while(insize >= 3) { + *output++ = table64[ in[0] >> 2 ]; + *output++ = table64[ ((in[0] & 0x03) << 4) | (in[1] >> 4) ]; + *output++ = table64[ ((in[1] & 0x0F) << 2) | ((in[2] & 0xC0) >> 6) ]; + *output++ = table64[ in[2] & 0x3F ]; + insize -= 3; + in += 3; + } + if(insize) { + /* this is only one or two bytes now */ + *output++ = table64[ in[0] >> 2 ]; + if(insize == 1) { + *output++ = table64[ ((in[0] & 0x03) << 4) ]; + if(*padstr) { + *output++ = *padstr; + *output++ = *padstr; + } + } + else { + /* insize == 2 */ + *output++ = table64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xF0) >> 4) ]; + *output++ = table64[ ((in[1] & 0x0F) << 2) ]; + if(*padstr) + *output++ = *padstr; + } + } + + /* Zero terminate */ + *output = '\0'; + + /* Return the pointer to the new data (allocated memory) */ + *outptr = base64data; + + /* Return the length of the new data */ + *outlen = (size_t)(output - base64data); + + return CURLE_OK; +} + +/* + * Curl_base64_encode() + * + * Given a pointer to an input buffer and an input size, encode it and + * return a pointer in *outptr to a newly allocated memory area holding + * encoded data. Size of encoded data is returned in variable pointed by + * outlen. + * + * Input length of 0 indicates input buffer holds a NUL-terminated string. + * + * Returns CURLE_OK on success, otherwise specific error code. Function + * output shall not be considered valid unless CURLE_OK is returned. + * + * @unittest: 1302 + */ +CURLcode Curl_base64_encode(const char *inputbuff, size_t insize, + char **outptr, size_t *outlen) +{ + return base64_encode(base64encdec, inputbuff, insize, outptr, outlen); +} + +/* + * Curl_base64url_encode() + * + * Given a pointer to an input buffer and an input size, encode it and + * return a pointer in *outptr to a newly allocated memory area holding + * encoded data. Size of encoded data is returned in variable pointed by + * outlen. + * + * Input length of 0 indicates input buffer holds a NUL-terminated string. + * + * Returns CURLE_OK on success, otherwise specific error code. Function + * output shall not be considered valid unless CURLE_OK is returned. + * + * @unittest: 1302 + */ +CURLcode Curl_base64url_encode(const char *inputbuff, size_t insize, + char **outptr, size_t *outlen) +{ + return base64_encode(base64url, inputbuff, insize, outptr, outlen); +} + +#endif /* no users so disabled */ diff --git a/third_party/curl/lib/bufq.c b/third_party/curl/lib/bufq.c new file mode 100644 index 0000000..c324551 --- /dev/null +++ b/third_party/curl/lib/bufq.c @@ -0,0 +1,677 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "bufq.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +static bool chunk_is_empty(const struct buf_chunk *chunk) +{ + return chunk->r_offset >= chunk->w_offset; +} + +static bool chunk_is_full(const struct buf_chunk *chunk) +{ + return chunk->w_offset >= chunk->dlen; +} + +static size_t chunk_len(const struct buf_chunk *chunk) +{ + return chunk->w_offset - chunk->r_offset; +} + +static size_t chunk_space(const struct buf_chunk *chunk) +{ + return chunk->dlen - chunk->w_offset; +} + +static void chunk_reset(struct buf_chunk *chunk) +{ + chunk->next = NULL; + chunk->r_offset = chunk->w_offset = 0; +} + +static size_t chunk_append(struct buf_chunk *chunk, + const unsigned char *buf, size_t len) +{ + unsigned char *p = &chunk->x.data[chunk->w_offset]; + size_t n = chunk->dlen - chunk->w_offset; + DEBUGASSERT(chunk->dlen >= chunk->w_offset); + if(n) { + n = CURLMIN(n, len); + memcpy(p, buf, n); + chunk->w_offset += n; + } + return n; +} + +static size_t chunk_read(struct buf_chunk *chunk, + unsigned char *buf, size_t len) +{ + unsigned char *p = &chunk->x.data[chunk->r_offset]; + size_t n = chunk->w_offset - chunk->r_offset; + DEBUGASSERT(chunk->w_offset >= chunk->r_offset); + if(!n) { + return 0; + } + else if(n <= len) { + memcpy(buf, p, n); + chunk->r_offset = chunk->w_offset = 0; + return n; + } + else { + memcpy(buf, p, len); + chunk->r_offset += len; + return len; + } +} + +static ssize_t chunk_slurpn(struct buf_chunk *chunk, size_t max_len, + Curl_bufq_reader *reader, + void *reader_ctx, CURLcode *err) +{ + unsigned char *p = &chunk->x.data[chunk->w_offset]; + size_t n = chunk->dlen - chunk->w_offset; /* free amount */ + ssize_t nread; + + DEBUGASSERT(chunk->dlen >= chunk->w_offset); + if(!n) { + *err = CURLE_AGAIN; + return -1; + } + if(max_len && n > max_len) + n = max_len; + nread = reader(reader_ctx, p, n, err); + if(nread > 0) { + DEBUGASSERT((size_t)nread <= n); + chunk->w_offset += nread; + } + return nread; +} + +static void chunk_peek(const struct buf_chunk *chunk, + const unsigned char **pbuf, size_t *plen) +{ + DEBUGASSERT(chunk->w_offset >= chunk->r_offset); + *pbuf = &chunk->x.data[chunk->r_offset]; + *plen = chunk->w_offset - chunk->r_offset; +} + +static void chunk_peek_at(const struct buf_chunk *chunk, size_t offset, + const unsigned char **pbuf, size_t *plen) +{ + offset += chunk->r_offset; + DEBUGASSERT(chunk->w_offset >= offset); + *pbuf = &chunk->x.data[offset]; + *plen = chunk->w_offset - offset; +} + +static size_t chunk_skip(struct buf_chunk *chunk, size_t amount) +{ + size_t n = chunk->w_offset - chunk->r_offset; + DEBUGASSERT(chunk->w_offset >= chunk->r_offset); + if(n) { + n = CURLMIN(n, amount); + chunk->r_offset += n; + if(chunk->r_offset == chunk->w_offset) + chunk->r_offset = chunk->w_offset = 0; + } + return n; +} + +static void chunk_list_free(struct buf_chunk **anchor) +{ + struct buf_chunk *chunk; + while(*anchor) { + chunk = *anchor; + *anchor = chunk->next; + free(chunk); + } +} + + + +void Curl_bufcp_init(struct bufc_pool *pool, + size_t chunk_size, size_t spare_max) +{ + DEBUGASSERT(chunk_size > 0); + DEBUGASSERT(spare_max > 0); + memset(pool, 0, sizeof(*pool)); + pool->chunk_size = chunk_size; + pool->spare_max = spare_max; +} + +static CURLcode bufcp_take(struct bufc_pool *pool, + struct buf_chunk **pchunk) +{ + struct buf_chunk *chunk = NULL; + + if(pool->spare) { + chunk = pool->spare; + pool->spare = chunk->next; + --pool->spare_count; + chunk_reset(chunk); + *pchunk = chunk; + return CURLE_OK; + } + + chunk = calloc(1, sizeof(*chunk) + pool->chunk_size); + if(!chunk) { + *pchunk = NULL; + return CURLE_OUT_OF_MEMORY; + } + chunk->dlen = pool->chunk_size; + *pchunk = chunk; + return CURLE_OK; +} + +static void bufcp_put(struct bufc_pool *pool, + struct buf_chunk *chunk) +{ + if(pool->spare_count >= pool->spare_max) { + free(chunk); + } + else { + chunk_reset(chunk); + chunk->next = pool->spare; + pool->spare = chunk; + ++pool->spare_count; + } +} + +void Curl_bufcp_free(struct bufc_pool *pool) +{ + chunk_list_free(&pool->spare); + pool->spare_count = 0; +} + +static void bufq_init(struct bufq *q, struct bufc_pool *pool, + size_t chunk_size, size_t max_chunks, int opts) +{ + DEBUGASSERT(chunk_size > 0); + DEBUGASSERT(max_chunks > 0); + memset(q, 0, sizeof(*q)); + q->chunk_size = chunk_size; + q->max_chunks = max_chunks; + q->pool = pool; + q->opts = opts; +} + +void Curl_bufq_init2(struct bufq *q, size_t chunk_size, size_t max_chunks, + int opts) +{ + bufq_init(q, NULL, chunk_size, max_chunks, opts); +} + +void Curl_bufq_init(struct bufq *q, size_t chunk_size, size_t max_chunks) +{ + bufq_init(q, NULL, chunk_size, max_chunks, BUFQ_OPT_NONE); +} + +void Curl_bufq_initp(struct bufq *q, struct bufc_pool *pool, + size_t max_chunks, int opts) +{ + bufq_init(q, pool, pool->chunk_size, max_chunks, opts); +} + +void Curl_bufq_free(struct bufq *q) +{ + chunk_list_free(&q->head); + chunk_list_free(&q->spare); + q->tail = NULL; + q->chunk_count = 0; +} + +void Curl_bufq_reset(struct bufq *q) +{ + struct buf_chunk *chunk; + while(q->head) { + chunk = q->head; + q->head = chunk->next; + chunk->next = q->spare; + q->spare = chunk; + } + q->tail = NULL; +} + +size_t Curl_bufq_len(const struct bufq *q) +{ + const struct buf_chunk *chunk = q->head; + size_t len = 0; + while(chunk) { + len += chunk_len(chunk); + chunk = chunk->next; + } + return len; +} + +size_t Curl_bufq_space(const struct bufq *q) +{ + size_t space = 0; + if(q->tail) + space += chunk_space(q->tail); + if(q->spare) { + struct buf_chunk *chunk = q->spare; + while(chunk) { + space += chunk->dlen; + chunk = chunk->next; + } + } + if(q->chunk_count < q->max_chunks) { + space += (q->max_chunks - q->chunk_count) * q->chunk_size; + } + return space; +} + +bool Curl_bufq_is_empty(const struct bufq *q) +{ + return !q->head || chunk_is_empty(q->head); +} + +bool Curl_bufq_is_full(const struct bufq *q) +{ + if(!q->tail || q->spare) + return FALSE; + if(q->chunk_count < q->max_chunks) + return FALSE; + if(q->chunk_count > q->max_chunks) + return TRUE; + /* we have no spares and cannot make more, is the tail full? */ + return chunk_is_full(q->tail); +} + +static struct buf_chunk *get_spare(struct bufq *q) +{ + struct buf_chunk *chunk = NULL; + + if(q->spare) { + chunk = q->spare; + q->spare = chunk->next; + chunk_reset(chunk); + return chunk; + } + + if(q->chunk_count >= q->max_chunks && (!(q->opts & BUFQ_OPT_SOFT_LIMIT))) + return NULL; + + if(q->pool) { + if(bufcp_take(q->pool, &chunk)) + return NULL; + ++q->chunk_count; + return chunk; + } + else { + chunk = calloc(1, sizeof(*chunk) + q->chunk_size); + if(!chunk) + return NULL; + chunk->dlen = q->chunk_size; + ++q->chunk_count; + return chunk; + } +} + +static void prune_head(struct bufq *q) +{ + struct buf_chunk *chunk; + + while(q->head && chunk_is_empty(q->head)) { + chunk = q->head; + q->head = chunk->next; + if(q->tail == chunk) + q->tail = q->head; + if(q->pool) { + bufcp_put(q->pool, chunk); + --q->chunk_count; + } + else if((q->chunk_count > q->max_chunks) || + (q->opts & BUFQ_OPT_NO_SPARES)) { + /* SOFT_LIMIT allowed us more than max. free spares until + * we are at max again. Or free them if we are configured + * to not use spares. */ + free(chunk); + --q->chunk_count; + } + else { + chunk->next = q->spare; + q->spare = chunk; + } + } +} + +static struct buf_chunk *get_non_full_tail(struct bufq *q) +{ + struct buf_chunk *chunk; + + if(q->tail && !chunk_is_full(q->tail)) + return q->tail; + chunk = get_spare(q); + if(chunk) { + /* new tail, and possibly new head */ + if(q->tail) { + q->tail->next = chunk; + q->tail = chunk; + } + else { + DEBUGASSERT(!q->head); + q->head = q->tail = chunk; + } + } + return chunk; +} + +ssize_t Curl_bufq_write(struct bufq *q, + const unsigned char *buf, size_t len, + CURLcode *err) +{ + struct buf_chunk *tail; + ssize_t nwritten = 0; + size_t n; + + DEBUGASSERT(q->max_chunks > 0); + while(len) { + tail = get_non_full_tail(q); + if(!tail) { + if((q->chunk_count < q->max_chunks) || (q->opts & BUFQ_OPT_SOFT_LIMIT)) { + *err = CURLE_OUT_OF_MEMORY; + return -1; + } + break; + } + n = chunk_append(tail, buf, len); + if(!n) + break; + nwritten += n; + buf += n; + len -= n; + } + if(nwritten == 0 && len) { + *err = CURLE_AGAIN; + return -1; + } + *err = CURLE_OK; + return nwritten; +} + +CURLcode Curl_bufq_cwrite(struct bufq *q, + const char *buf, size_t len, + size_t *pnwritten) +{ + ssize_t n; + CURLcode result; + n = Curl_bufq_write(q, (const unsigned char *)buf, len, &result); + *pnwritten = (n < 0)? 0 : (size_t)n; + return result; +} + +ssize_t Curl_bufq_read(struct bufq *q, unsigned char *buf, size_t len, + CURLcode *err) +{ + ssize_t nread = 0; + size_t n; + + *err = CURLE_OK; + while(len && q->head) { + n = chunk_read(q->head, buf, len); + if(n) { + nread += n; + buf += n; + len -= n; + } + prune_head(q); + } + if(nread == 0) { + *err = CURLE_AGAIN; + return -1; + } + return nread; +} + +CURLcode Curl_bufq_cread(struct bufq *q, char *buf, size_t len, + size_t *pnread) +{ + ssize_t n; + CURLcode result; + n = Curl_bufq_read(q, (unsigned char *)buf, len, &result); + *pnread = (n < 0)? 0 : (size_t)n; + return result; +} + +bool Curl_bufq_peek(struct bufq *q, + const unsigned char **pbuf, size_t *plen) +{ + if(q->head && chunk_is_empty(q->head)) { + prune_head(q); + } + if(q->head && !chunk_is_empty(q->head)) { + chunk_peek(q->head, pbuf, plen); + return TRUE; + } + *pbuf = NULL; + *plen = 0; + return FALSE; +} + +bool Curl_bufq_peek_at(struct bufq *q, size_t offset, + const unsigned char **pbuf, size_t *plen) +{ + struct buf_chunk *c = q->head; + size_t clen; + + while(c) { + clen = chunk_len(c); + if(!clen) + break; + if(offset >= clen) { + offset -= clen; + c = c->next; + continue; + } + chunk_peek_at(c, offset, pbuf, plen); + return TRUE; + } + *pbuf = NULL; + *plen = 0; + return FALSE; +} + +void Curl_bufq_skip(struct bufq *q, size_t amount) +{ + size_t n; + + while(amount && q->head) { + n = chunk_skip(q->head, amount); + amount -= n; + prune_head(q); + } +} + +ssize_t Curl_bufq_pass(struct bufq *q, Curl_bufq_writer *writer, + void *writer_ctx, CURLcode *err) +{ + const unsigned char *buf; + size_t blen; + ssize_t nwritten = 0; + + while(Curl_bufq_peek(q, &buf, &blen)) { + ssize_t chunk_written; + + chunk_written = writer(writer_ctx, buf, blen, err); + if(chunk_written < 0) { + if(!nwritten || *err != CURLE_AGAIN) { + /* blocked on first write or real error, fail */ + nwritten = -1; + } + break; + } + if(!chunk_written) { + if(!nwritten) { + /* treat as blocked */ + *err = CURLE_AGAIN; + nwritten = -1; + } + break; + } + Curl_bufq_skip(q, (size_t)chunk_written); + nwritten += chunk_written; + } + return nwritten; +} + +ssize_t Curl_bufq_write_pass(struct bufq *q, + const unsigned char *buf, size_t len, + Curl_bufq_writer *writer, void *writer_ctx, + CURLcode *err) +{ + ssize_t nwritten = 0, n; + + *err = CURLE_OK; + while(len) { + if(Curl_bufq_is_full(q)) { + /* try to make room in case we are full */ + n = Curl_bufq_pass(q, writer, writer_ctx, err); + if(n < 0) { + if(*err != CURLE_AGAIN) { + /* real error, fail */ + return -1; + } + /* would block, bufq is full, give up */ + break; + } + } + + /* Add whatever is remaining now to bufq */ + n = Curl_bufq_write(q, buf, len, err); + if(n < 0) { + if(*err != CURLE_AGAIN) { + /* real error, fail */ + return -1; + } + /* no room in bufq */ + break; + } + /* edge case of writer returning 0 (and len is >0) + * break or we might enter an infinite loop here */ + if(n == 0) + break; + + /* Maybe only part of `data` has been added, continue to loop */ + buf += (size_t)n; + len -= (size_t)n; + nwritten += (size_t)n; + } + + if(!nwritten && len) { + *err = CURLE_AGAIN; + return -1; + } + *err = CURLE_OK; + return nwritten; +} + +ssize_t Curl_bufq_sipn(struct bufq *q, size_t max_len, + Curl_bufq_reader *reader, void *reader_ctx, + CURLcode *err) +{ + struct buf_chunk *tail = NULL; + ssize_t nread; + + *err = CURLE_AGAIN; + tail = get_non_full_tail(q); + if(!tail) { + if(q->chunk_count < q->max_chunks) { + *err = CURLE_OUT_OF_MEMORY; + return -1; + } + /* full, blocked */ + *err = CURLE_AGAIN; + return -1; + } + + nread = chunk_slurpn(tail, max_len, reader, reader_ctx, err); + if(nread < 0) { + return -1; + } + else if(nread == 0) { + /* eof */ + *err = CURLE_OK; + } + return nread; +} + +/** + * Read up to `max_len` bytes and append it to the end of the buffer queue. + * if `max_len` is 0, no limit is imposed and the call behaves exactly + * the same as `Curl_bufq_slurp()`. + * Returns the total amount of buf read (may be 0) or -1 on other + * reader errors. + * Note that even in case of a -1 chunks may have been read and + * the buffer queue will have different length than before. + */ +static ssize_t bufq_slurpn(struct bufq *q, size_t max_len, + Curl_bufq_reader *reader, void *reader_ctx, + CURLcode *err) +{ + ssize_t nread = 0, n; + + *err = CURLE_AGAIN; + while(1) { + + n = Curl_bufq_sipn(q, max_len, reader, reader_ctx, err); + if(n < 0) { + if(!nread || *err != CURLE_AGAIN) { + /* blocked on first read or real error, fail */ + nread = -1; + } + else + *err = CURLE_OK; + break; + } + else if(n == 0) { + /* eof */ + *err = CURLE_OK; + break; + } + nread += (size_t)n; + if(max_len) { + DEBUGASSERT((size_t)n <= max_len); + max_len -= (size_t)n; + if(!max_len) + break; + } + /* give up slurping when we get less bytes than we asked for */ + if(q->tail && !chunk_is_full(q->tail)) + break; + } + return nread; +} + +ssize_t Curl_bufq_slurp(struct bufq *q, Curl_bufq_reader *reader, + void *reader_ctx, CURLcode *err) +{ + return bufq_slurpn(q, 0, reader, reader_ctx, err); +} diff --git a/third_party/curl/lib/bufq.h b/third_party/curl/lib/bufq.h new file mode 100644 index 0000000..87ffa45 --- /dev/null +++ b/third_party/curl/lib/bufq.h @@ -0,0 +1,272 @@ +#ifndef HEADER_CURL_BUFQ_H +#define HEADER_CURL_BUFQ_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include + +/** + * A chunk of bytes for reading and writing. + * The size is fixed a creation with read and write offset + * for where unread content is. + */ +struct buf_chunk { + struct buf_chunk *next; /* to keep it in a list */ + size_t dlen; /* the amount of allocated x.data[] */ + size_t r_offset; /* first unread bytes */ + size_t w_offset; /* one after last written byte */ + union { + unsigned char data[1]; /* the buffer for `dlen` bytes */ + void *dummy; /* alignment */ + } x; +}; + +/** + * A pool for providing/keeping a number of chunks of the same size + * + * The same pool can be shared by many `bufq` instances. However, a pool + * is not thread safe. All bufqs using it are supposed to operate in the + * same thread. + */ +struct bufc_pool { + struct buf_chunk *spare; /* list of available spare chunks */ + size_t chunk_size; /* the size of chunks in this pool */ + size_t spare_count; /* current number of spare chunks in list */ + size_t spare_max; /* max number of spares to keep */ +}; + +void Curl_bufcp_init(struct bufc_pool *pool, + size_t chunk_size, size_t spare_max); + +void Curl_bufcp_free(struct bufc_pool *pool); + +/** + * A queue of byte chunks for reading and writing. + * Reading is done from `head`, writing is done to `tail`. + * + * `bufq`s can be empty or full or neither. Its `len` is the number + * of bytes that can be read. For an empty bufq, `len` will be 0. + * + * By default, a bufq can hold up to `max_chunks * chunk_size` number + * of bytes. When `max_chunks` are used (in the `head` list) and the + * `tail` chunk is full, the bufq will report that it is full. + * + * On a full bufq, `len` may be less than the maximum number of bytes, + * e.g. when the head chunk is partially read. `len` may also become + * larger than the max when option `BUFQ_OPT_SOFT_LIMIT` is used. + * + * By default, writing to a full bufq will return (-1, CURLE_AGAIN). Same + * as reading from an empty bufq. + * With `BUFQ_OPT_SOFT_LIMIT` set, a bufq will allow writing becond this + * limit and use more than `max_chunks`. However it will report that it + * is full nevertheless. This is provided for situation where writes + * preferably never fail (except for memory exhaustion). + * + * By default and without a pool, a bufq will keep chunks that read + * empty in its `spare` list. Option `BUFQ_OPT_NO_SPARES` will + * disable that and free chunks once they become empty. + * + * When providing a pool to a bufq, all chunk creation and spare handling + * will be delegated to that pool. + */ +struct bufq { + struct buf_chunk *head; /* chunk with bytes to read from */ + struct buf_chunk *tail; /* chunk to write to */ + struct buf_chunk *spare; /* list of free chunks, unless `pool` */ + struct bufc_pool *pool; /* optional pool for free chunks */ + size_t chunk_count; /* current number of chunks in `head+spare` */ + size_t max_chunks; /* max `head` chunks to use */ + size_t chunk_size; /* size of chunks to manage */ + int opts; /* options for handling queue, see below */ +}; + +/** + * Default behaviour: chunk limit is "hard", meaning attempts to write + * more bytes than can be hold in `max_chunks` is refused and will return + * -1, CURLE_AGAIN. */ +#define BUFQ_OPT_NONE (0) +/** + * Make `max_chunks` a "soft" limit. A bufq will report that it is "full" + * when `max_chunks` are used, but allows writing beyond this limit. + */ +#define BUFQ_OPT_SOFT_LIMIT (1 << 0) +/** + * Do not keep spare chunks. + */ +#define BUFQ_OPT_NO_SPARES (1 << 1) + +/** + * Initialize a buffer queue that can hold up to `max_chunks` buffers + * each of size `chunk_size`. The bufq will not allow writing of + * more bytes than can be held in `max_chunks`. + */ +void Curl_bufq_init(struct bufq *q, size_t chunk_size, size_t max_chunks); + +/** + * Initialize a buffer queue that can hold up to `max_chunks` buffers + * each of size `chunk_size` with the given options. See `BUFQ_OPT_*`. + */ +void Curl_bufq_init2(struct bufq *q, size_t chunk_size, + size_t max_chunks, int opts); + +void Curl_bufq_initp(struct bufq *q, struct bufc_pool *pool, + size_t max_chunks, int opts); + +/** + * Reset the buffer queue to be empty. Will keep any allocated buffer + * chunks around. + */ +void Curl_bufq_reset(struct bufq *q); + +/** + * Free all resources held by the buffer queue. + */ +void Curl_bufq_free(struct bufq *q); + +/** + * Return the total amount of data in the queue. + */ +size_t Curl_bufq_len(const struct bufq *q); + +/** + * Return the total amount of free space in the queue. + * The returned length is the number of bytes that can + * be expected to be written successfully to the bufq, + * providing no memory allocations fail. + */ +size_t Curl_bufq_space(const struct bufq *q); + +/** + * Returns TRUE iff there is no data in the buffer queue. + */ +bool Curl_bufq_is_empty(const struct bufq *q); + +/** + * Returns TRUE iff there is no space left in the buffer queue. + */ +bool Curl_bufq_is_full(const struct bufq *q); + +/** + * Write buf to the end of the buffer queue. The buf is copied + * and the amount of copied bytes is returned. + * A return code of -1 indicates an error, setting `err` to the + * cause. An err of CURLE_AGAIN is returned if the buffer queue is full. + */ +ssize_t Curl_bufq_write(struct bufq *q, + const unsigned char *buf, size_t len, + CURLcode *err); + +CURLcode Curl_bufq_cwrite(struct bufq *q, + const char *buf, size_t len, + size_t *pnwritten); + +/** + * Read buf from the start of the buffer queue. The buf is copied + * and the amount of copied bytes is returned. + * A return code of -1 indicates an error, setting `err` to the + * cause. An err of CURLE_AGAIN is returned if the buffer queue is empty. + */ +ssize_t Curl_bufq_read(struct bufq *q, unsigned char *buf, size_t len, + CURLcode *err); + +CURLcode Curl_bufq_cread(struct bufq *q, char *buf, size_t len, + size_t *pnread); + +/** + * Peek at the head chunk in the buffer queue. Returns a pointer to + * the chunk buf (at the current offset) and its length. Does not + * modify the buffer queue. + * Returns TRUE iff bytes are available. Sets `pbuf` to NULL and `plen` + * to 0 when no bytes are available. + * Repeated calls return the same information until the buffer queue + * is modified, see `Curl_bufq_skip()`` + */ +bool Curl_bufq_peek(struct bufq *q, + const unsigned char **pbuf, size_t *plen); + +bool Curl_bufq_peek_at(struct bufq *q, size_t offset, + const unsigned char **pbuf, size_t *plen); + +/** + * Tell the buffer queue to discard `amount` buf bytes at the head + * of the queue. Skipping more buf than is currently buffered will + * just empty the queue. + */ +void Curl_bufq_skip(struct bufq *q, size_t amount); + +typedef ssize_t Curl_bufq_writer(void *writer_ctx, + const unsigned char *buf, size_t len, + CURLcode *err); +/** + * Passes the chunks in the buffer queue to the writer and returns + * the amount of buf written. A writer may return -1 and CURLE_AGAIN + * to indicate blocking at which point the queue will stop and return + * the amount of buf passed so far. + * -1 is returned on any other errors reported by the writer. + * Note that in case of a -1 chunks may have been written and + * the buffer queue will have different length than before. + */ +ssize_t Curl_bufq_pass(struct bufq *q, Curl_bufq_writer *writer, + void *writer_ctx, CURLcode *err); + +typedef ssize_t Curl_bufq_reader(void *reader_ctx, + unsigned char *buf, size_t len, + CURLcode *err); + +/** + * Read date and append it to the end of the buffer queue until the + * reader returns blocking or the queue is full. A reader returns + * -1 and CURLE_AGAIN to indicate blocking. + * Returns the total amount of buf read (may be 0) or -1 on other + * reader errors. + * Note that in case of a -1 chunks may have been read and + * the buffer queue will have different length than before. + */ +ssize_t Curl_bufq_slurp(struct bufq *q, Curl_bufq_reader *reader, + void *reader_ctx, CURLcode *err); + +/** + * Read *once* up to `max_len` bytes and append it to the buffer. + * if `max_len` is 0, no limit is imposed besides the chunk space. + * Returns the total amount of buf read (may be 0) or -1 on other + * reader errors. + */ +ssize_t Curl_bufq_sipn(struct bufq *q, size_t max_len, + Curl_bufq_reader *reader, void *reader_ctx, + CURLcode *err); + +/** + * Write buf to the end of the buffer queue. + * Will write bufq content or passed `buf` directly using the `writer` + * callback when it sees fit. 'buf' might get passed directly + * on or is placed into the buffer, depending on `len` and current + * amount buffered, chunk size, etc. + */ +ssize_t Curl_bufq_write_pass(struct bufq *q, + const unsigned char *buf, size_t len, + Curl_bufq_writer *writer, void *writer_ctx, + CURLcode *err); + +#endif /* HEADER_CURL_BUFQ_H */ diff --git a/third_party/curl/lib/bufref.c b/third_party/curl/lib/bufref.c new file mode 100644 index 0000000..f0a0e2a --- /dev/null +++ b/third_party/curl/lib/bufref.c @@ -0,0 +1,127 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "urldata.h" +#include "bufref.h" +#include "strdup.h" + +#include "curl_memory.h" +#include "memdebug.h" + +#define SIGNATURE 0x5c48e9b2 /* Random pattern. */ + +/* + * Init a bufref struct. + */ +void Curl_bufref_init(struct bufref *br) +{ + DEBUGASSERT(br); + br->dtor = NULL; + br->ptr = NULL; + br->len = 0; + +#ifdef DEBUGBUILD + br->signature = SIGNATURE; +#endif +} + +/* + * Free the buffer and re-init the necessary fields. It doesn't touch the + * 'signature' field and thus this buffer reference can be reused. + */ + +void Curl_bufref_free(struct bufref *br) +{ + DEBUGASSERT(br); + DEBUGASSERT(br->signature == SIGNATURE); + DEBUGASSERT(br->ptr || !br->len); + + if(br->ptr && br->dtor) + br->dtor((void *) br->ptr); + + br->dtor = NULL; + br->ptr = NULL; + br->len = 0; +} + +/* + * Set the buffer reference to new values. The previously referenced buffer + * is released before assignment. + */ +void Curl_bufref_set(struct bufref *br, const void *ptr, size_t len, + void (*dtor)(void *)) +{ + DEBUGASSERT(ptr || !len); + DEBUGASSERT(len <= CURL_MAX_INPUT_LENGTH); + + Curl_bufref_free(br); + br->ptr = (const unsigned char *) ptr; + br->len = len; + br->dtor = dtor; +} + +/* + * Get a pointer to the referenced buffer. + */ +const unsigned char *Curl_bufref_ptr(const struct bufref *br) +{ + DEBUGASSERT(br); + DEBUGASSERT(br->signature == SIGNATURE); + DEBUGASSERT(br->ptr || !br->len); + + return br->ptr; +} + +/* + * Get the length of the referenced buffer data. + */ +size_t Curl_bufref_len(const struct bufref *br) +{ + DEBUGASSERT(br); + DEBUGASSERT(br->signature == SIGNATURE); + DEBUGASSERT(br->ptr || !br->len); + + return br->len; +} + +CURLcode Curl_bufref_memdup(struct bufref *br, const void *ptr, size_t len) +{ + unsigned char *cpy = NULL; + + DEBUGASSERT(br); + DEBUGASSERT(br->signature == SIGNATURE); + DEBUGASSERT(br->ptr || !br->len); + DEBUGASSERT(ptr || !len); + DEBUGASSERT(len <= CURL_MAX_INPUT_LENGTH); + + if(ptr) { + cpy = Curl_memdup0(ptr, len); + if(!cpy) + return CURLE_OUT_OF_MEMORY; + } + + Curl_bufref_set(br, cpy, len, curl_free); + return CURLE_OK; +} diff --git a/third_party/curl/lib/bufref.h b/third_party/curl/lib/bufref.h new file mode 100644 index 0000000..dd424f1 --- /dev/null +++ b/third_party/curl/lib/bufref.h @@ -0,0 +1,48 @@ +#ifndef HEADER_CURL_BUFREF_H +#define HEADER_CURL_BUFREF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Generic buffer reference. + */ +struct bufref { + void (*dtor)(void *); /* Associated destructor. */ + const unsigned char *ptr; /* Referenced data buffer. */ + size_t len; /* The data size in bytes. */ +#ifdef DEBUGBUILD + int signature; /* Detect API use mistakes. */ +#endif +}; + + +void Curl_bufref_init(struct bufref *br); +void Curl_bufref_set(struct bufref *br, const void *ptr, size_t len, + void (*dtor)(void *)); +const unsigned char *Curl_bufref_ptr(const struct bufref *br); +size_t Curl_bufref_len(const struct bufref *br); +CURLcode Curl_bufref_memdup(struct bufref *br, const void *ptr, size_t len); +void Curl_bufref_free(struct bufref *br); + +#endif diff --git a/third_party/curl/lib/c-hyper.c b/third_party/curl/lib/c-hyper.c new file mode 100644 index 0000000..0593d97 --- /dev/null +++ b/third_party/curl/lib/c-hyper.c @@ -0,0 +1,1228 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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.haxx.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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* Curl's integration with Hyper. This replaces certain functions in http.c, + * based on configuration #defines. This implementation supports HTTP/1.1 but + * not HTTP/2. + */ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_HYPER) + +#ifdef HAVE_NETINET_IN_H +#include +#endif + +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NET_IF_H +#include +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif + +#ifdef HAVE_SYS_PARAM_H +#include +#endif + +#include +#include "urldata.h" +#include "cfilters.h" +#include "sendf.h" +#include "headers.h" +#include "transfer.h" +#include "multiif.h" +#include "progress.h" +#include "content_encoding.h" +#include "ws.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +static CURLcode cr_hyper_add(struct Curl_easy *data); + +typedef enum { + USERDATA_NOT_SET = 0, /* for tasks with no userdata set; must be zero */ + USERDATA_RESP_BODY +} userdata_t; + +size_t Curl_hyper_recv(void *userp, hyper_context *ctx, + uint8_t *buf, size_t buflen) +{ + struct hyp_io_ctx *io_ctx = userp; + struct Curl_easy *data = io_ctx->data; + struct connectdata *conn = data->conn; + CURLcode result; + ssize_t nread; + DEBUGASSERT(conn); + (void)ctx; + + DEBUGF(infof(data, "Curl_hyper_recv(%zu)", buflen)); + result = Curl_conn_recv(data, io_ctx->sockindex, + (char *)buf, buflen, &nread); + if(result == CURLE_AGAIN) { + /* would block, register interest */ + DEBUGF(infof(data, "Curl_hyper_recv(%zu) -> EAGAIN", buflen)); + if(data->hyp.read_waker) + hyper_waker_free(data->hyp.read_waker); + data->hyp.read_waker = hyper_context_waker(ctx); + if(!data->hyp.read_waker) { + failf(data, "Couldn't make the read hyper_context_waker"); + return HYPER_IO_ERROR; + } + return HYPER_IO_PENDING; + } + else if(result) { + failf(data, "Curl_read failed"); + return HYPER_IO_ERROR; + } + DEBUGF(infof(data, "Curl_hyper_recv(%zu) -> %zd", buflen, nread)); + return (size_t)nread; +} + +size_t Curl_hyper_send(void *userp, hyper_context *ctx, + const uint8_t *buf, size_t buflen) +{ + struct hyp_io_ctx *io_ctx = userp; + struct Curl_easy *data = io_ctx->data; + CURLcode result; + size_t nwrote; + + DEBUGF(infof(data, "Curl_hyper_send(%zu)", buflen)); + result = Curl_conn_send(data, io_ctx->sockindex, + (void *)buf, buflen, &nwrote); + if(result == CURLE_AGAIN) { + DEBUGF(infof(data, "Curl_hyper_send(%zu) -> EAGAIN", buflen)); + /* would block, register interest */ + if(data->hyp.write_waker) + hyper_waker_free(data->hyp.write_waker); + data->hyp.write_waker = hyper_context_waker(ctx); + if(!data->hyp.write_waker) { + failf(data, "Couldn't make the write hyper_context_waker"); + return HYPER_IO_ERROR; + } + return HYPER_IO_PENDING; + } + else if(result) { + failf(data, "Curl_write failed"); + return HYPER_IO_ERROR; + } + DEBUGF(infof(data, "Curl_hyper_send(%zu) -> %zd", buflen, nwrote)); + return (size_t)nwrote; +} + +static int hyper_each_header(void *userdata, + const uint8_t *name, + size_t name_len, + const uint8_t *value, + size_t value_len) +{ + struct Curl_easy *data = (struct Curl_easy *)userdata; + size_t len; + char *headp; + CURLcode result; + int writetype; + + if(name_len + value_len + 2 > CURL_MAX_HTTP_HEADER) { + failf(data, "Too long response header"); + data->state.hresult = CURLE_TOO_LARGE; + return HYPER_ITER_BREAK; + } + + Curl_dyn_reset(&data->state.headerb); + if(name_len) { + if(Curl_dyn_addf(&data->state.headerb, "%.*s: %.*s\r\n", + (int) name_len, name, (int) value_len, value)) + return HYPER_ITER_BREAK; + } + else { + if(Curl_dyn_addn(&data->state.headerb, STRCONST("\r\n"))) + return HYPER_ITER_BREAK; + } + len = Curl_dyn_len(&data->state.headerb); + headp = Curl_dyn_ptr(&data->state.headerb); + + result = Curl_http_header(data, headp, len); + if(result) { + data->state.hresult = result; + return HYPER_ITER_BREAK; + } + + Curl_debug(data, CURLINFO_HEADER_IN, headp, len); + + writetype = CLIENTWRITE_HEADER; + if(data->state.hconnect) + writetype |= CLIENTWRITE_CONNECT; + if(data->req.httpcode/100 == 1) + writetype |= CLIENTWRITE_1XX; + result = Curl_client_write(data, writetype, headp, len); + if(result) { + data->state.hresult = CURLE_ABORTED_BY_CALLBACK; + return HYPER_ITER_BREAK; + } + + result = Curl_bump_headersize(data, len, FALSE); + if(result) { + data->state.hresult = result; + return HYPER_ITER_BREAK; + } + return HYPER_ITER_CONTINUE; +} + +static int hyper_body_chunk(void *userdata, const hyper_buf *chunk) +{ + char *buf = (char *)hyper_buf_bytes(chunk); + size_t len = hyper_buf_len(chunk); + struct Curl_easy *data = (struct Curl_easy *)userdata; + struct SingleRequest *k = &data->req; + CURLcode result = CURLE_OK; + + if(0 == k->bodywrites) { +#if defined(USE_NTLM) + struct connectdata *conn = data->conn; + if(conn->bits.close && + (((data->req.httpcode == 401) && + (conn->http_ntlm_state == NTLMSTATE_TYPE2)) || + ((data->req.httpcode == 407) && + (conn->proxy_ntlm_state == NTLMSTATE_TYPE2)))) { + infof(data, "Connection closed while negotiating NTLM"); + data->state.authproblem = TRUE; + Curl_safefree(data->req.newurl); + } +#endif + if(Curl_http_exp100_is_selected(data)) { + if(data->req.httpcode < 400) { + Curl_http_exp100_got100(data); + if(data->hyp.send_body_waker) { + hyper_waker_wake(data->hyp.send_body_waker); + data->hyp.send_body_waker = NULL; + } + } + else { /* >= 4xx */ + Curl_req_abort_sending(data); + } + } + if(data->state.hconnect && (data->req.httpcode/100 != 2) && + data->state.authproxy.done) { + data->req.done = TRUE; + result = CURLE_OK; + } + else + result = Curl_http_firstwrite(data); + if(result || data->req.done) { + infof(data, "Return early from hyper_body_chunk"); + data->state.hresult = result; + return HYPER_ITER_BREAK; + } + } + result = Curl_client_write(data, CLIENTWRITE_BODY, buf, len); + + if(result) { + data->state.hresult = result; + return HYPER_ITER_BREAK; + } + + return HYPER_ITER_CONTINUE; +} + +/* + * Hyper does not consider the status line, the first line in an HTTP/1 + * response, to be a header. The libcurl API does. This function sends the + * status line in the header callback. */ +static CURLcode status_line(struct Curl_easy *data, + struct connectdata *conn, + uint16_t http_status, + int http_version, + const uint8_t *reason, size_t rlen) +{ + CURLcode result; + size_t len; + const char *vstr; + int writetype; + vstr = http_version == HYPER_HTTP_VERSION_1_1 ? "1.1" : + (http_version == HYPER_HTTP_VERSION_2 ? "2" : "1.0"); + + /* We need to set 'httpcodeq' for functions that check the response code in + a single place. */ + data->req.httpcode = http_status; + data->req.httpversion = http_version == HYPER_HTTP_VERSION_1_1? 11 : + (http_version == HYPER_HTTP_VERSION_2 ? 20 : 10); + if(data->state.hconnect) + /* CONNECT */ + data->info.httpproxycode = http_status; + else { + conn->httpversion = (unsigned char)data->req.httpversion; + if(http_version == HYPER_HTTP_VERSION_1_0) + data->state.httpwant = CURL_HTTP_VERSION_1_0; + + result = Curl_http_statusline(data, conn); + if(result) + return result; + } + + Curl_dyn_reset(&data->state.headerb); + + result = Curl_dyn_addf(&data->state.headerb, "HTTP/%s %03d %.*s\r\n", + vstr, + (int)http_status, + (int)rlen, reason); + if(result) + return result; + len = Curl_dyn_len(&data->state.headerb); + Curl_debug(data, CURLINFO_HEADER_IN, Curl_dyn_ptr(&data->state.headerb), + len); + + writetype = CLIENTWRITE_HEADER|CLIENTWRITE_STATUS; + if(data->state.hconnect) + writetype |= CLIENTWRITE_CONNECT; + result = Curl_client_write(data, writetype, + Curl_dyn_ptr(&data->state.headerb), len); + if(result) + return result; + + result = Curl_bump_headersize(data, len, FALSE); + return result; +} + +/* + * Hyper does not pass on the last empty response header. The libcurl API + * does. This function sends an empty header in the header callback. + */ +static CURLcode empty_header(struct Curl_easy *data) +{ + CURLcode result = Curl_http_size(data); + if(!result) { + result = hyper_each_header(data, NULL, 0, NULL, 0) ? + CURLE_WRITE_ERROR : CURLE_OK; + if(result) + failf(data, "hyperstream: couldn't pass blank header"); + /* Hyper does chunked decoding itself. If it was added during + * response header processing, remove it again. */ + Curl_cwriter_remove_by_name(data, "chunked"); + } + return result; +} + +CURLcode Curl_hyper_stream(struct Curl_easy *data, + struct connectdata *conn, + int *didwhat, + int select_res) +{ + hyper_response *resp = NULL; + uint16_t http_status; + int http_version; + hyper_headers *headers = NULL; + hyper_body *resp_body = NULL; + struct hyptransfer *h = &data->hyp; + hyper_task *task; + hyper_task *foreach; + const uint8_t *reasonp; + size_t reason_len; + CURLcode result = CURLE_OK; + struct SingleRequest *k = &data->req; + (void)conn; + + if(data->hyp.send_body_waker) { + hyper_waker_wake(data->hyp.send_body_waker); + data->hyp.send_body_waker = NULL; + } + + if(select_res & CURL_CSELECT_IN) { + if(h->read_waker) + hyper_waker_wake(h->read_waker); + h->read_waker = NULL; + } + if(select_res & CURL_CSELECT_OUT) { + if(h->write_waker) + hyper_waker_wake(h->write_waker); + h->write_waker = NULL; + } + + do { + hyper_task_return_type t; + task = hyper_executor_poll(h->exec); + if(!task) { + *didwhat = KEEP_RECV; + break; + } + t = hyper_task_type(task); + if(t == HYPER_TASK_ERROR) { + hyper_error *hypererr = hyper_task_value(task); + hyper_task_free(task); + if(data->state.hresult) { + /* override Hyper's view, might not even be an error */ + result = data->state.hresult; + infof(data, "hyperstream is done (by early callback)"); + } + else { + uint8_t errbuf[256]; + size_t errlen = hyper_error_print(hypererr, errbuf, sizeof(errbuf)); + hyper_code code = hyper_error_code(hypererr); + failf(data, "Hyper: [%d] %.*s", (int)code, (int)errlen, errbuf); + switch(code) { + case HYPERE_ABORTED_BY_CALLBACK: + result = CURLE_OK; + break; + case HYPERE_UNEXPECTED_EOF: + if(!data->req.bytecount) + result = CURLE_GOT_NOTHING; + else + result = CURLE_RECV_ERROR; + break; + case HYPERE_INVALID_PEER_MESSAGE: + /* bump headerbytecount to avoid the count remaining at zero and + appearing to not having read anything from the peer at all */ + data->req.headerbytecount++; + result = CURLE_UNSUPPORTED_PROTOCOL; /* maybe */ + break; + default: + result = CURLE_RECV_ERROR; + break; + } + } + data->req.done = TRUE; + hyper_error_free(hypererr); + break; + } + else if(t == HYPER_TASK_EMPTY) { + void *userdata = hyper_task_userdata(task); + hyper_task_free(task); + if((userdata_t)userdata == USERDATA_RESP_BODY) { + /* end of transfer */ + data->req.done = TRUE; + infof(data, "hyperstream is done"); + if(!k->bodywrites) { + /* hyper doesn't always call the body write callback */ + result = Curl_http_firstwrite(data); + } + break; + } + else { + /* A background task for hyper; ignore */ + continue; + } + } + + DEBUGASSERT(HYPER_TASK_RESPONSE); + + resp = hyper_task_value(task); + hyper_task_free(task); + + *didwhat = KEEP_RECV; + if(!resp) { + failf(data, "hyperstream: couldn't get response"); + return CURLE_RECV_ERROR; + } + + http_status = hyper_response_status(resp); + http_version = hyper_response_version(resp); + reasonp = hyper_response_reason_phrase(resp); + reason_len = hyper_response_reason_phrase_len(resp); + + if(http_status == 417 && Curl_http_exp100_is_selected(data)) { + infof(data, "Got 417 while waiting for a 100"); + data->state.disableexpect = TRUE; + data->req.newurl = strdup(data->state.url); + Curl_req_abort_sending(data); + } + + result = status_line(data, conn, + http_status, http_version, reasonp, reason_len); + if(result) + break; + + headers = hyper_response_headers(resp); + if(!headers) { + failf(data, "hyperstream: couldn't get response headers"); + result = CURLE_RECV_ERROR; + break; + } + + /* the headers are already received */ + hyper_headers_foreach(headers, hyper_each_header, data); + if(data->state.hresult) { + result = data->state.hresult; + break; + } + + result = empty_header(data); + if(result) + break; + + k->deductheadercount = + (100 <= http_status && 199 >= http_status)?k->headerbytecount:0; +#ifdef USE_WEBSOCKETS + if(k->upgr101 == UPGR101_WS) { + if(http_status == 101) { + /* verify the response */ + result = Curl_ws_accept(data, NULL, 0); + if(result) + return result; + } + else { + failf(data, "Expected 101, got %u", k->httpcode); + result = CURLE_HTTP_RETURNED_ERROR; + break; + } + } +#endif + + /* Curl_http_auth_act() checks what authentication methods that are + * available and decides which one (if any) to use. It will set 'newurl' + * if an auth method was picked. */ + result = Curl_http_auth_act(data); + if(result) + break; + + resp_body = hyper_response_body(resp); + if(!resp_body) { + failf(data, "hyperstream: couldn't get response body"); + result = CURLE_RECV_ERROR; + break; + } + foreach = hyper_body_foreach(resp_body, hyper_body_chunk, data); + if(!foreach) { + failf(data, "hyperstream: body foreach failed"); + result = CURLE_OUT_OF_MEMORY; + break; + } + hyper_task_set_userdata(foreach, (void *)USERDATA_RESP_BODY); + if(HYPERE_OK != hyper_executor_push(h->exec, foreach)) { + failf(data, "Couldn't hyper_executor_push the body-foreach"); + result = CURLE_OUT_OF_MEMORY; + break; + } + + hyper_response_free(resp); + resp = NULL; + } while(1); + if(resp) + hyper_response_free(resp); + return result; +} + +static CURLcode debug_request(struct Curl_easy *data, + const char *method, + const char *path) +{ + char *req = aprintf("%s %s HTTP/1.1\r\n", method, path); + if(!req) + return CURLE_OUT_OF_MEMORY; + Curl_debug(data, CURLINFO_HEADER_OUT, req, strlen(req)); + free(req); + return CURLE_OK; +} + +/* + * Given a full header line "name: value" (optional CRLF in the input, should + * be in the output), add to Hyper and send to the debug callback. + * + * Supports multiple headers. + */ + +CURLcode Curl_hyper_header(struct Curl_easy *data, hyper_headers *headers, + const char *line) +{ + const char *p; + const char *n; + size_t nlen; + const char *v; + size_t vlen; + bool newline = TRUE; + int numh = 0; + + if(!line) + return CURLE_OK; + n = line; + do { + size_t linelen = 0; + + p = strchr(n, ':'); + if(!p) + /* this is fine if we already added at least one header */ + return numh ? CURLE_OK : CURLE_BAD_FUNCTION_ARGUMENT; + nlen = p - n; + p++; /* move past the colon */ + while(*p == ' ') + p++; + v = p; + p = strchr(v, '\r'); + if(!p) { + p = strchr(v, '\n'); + if(p) + linelen = 1; /* LF only */ + else { + p = strchr(v, '\0'); + newline = FALSE; /* no newline */ + } + } + else + linelen = 2; /* CRLF ending */ + linelen += (p - n); + vlen = p - v; + + if(HYPERE_OK != hyper_headers_add(headers, (uint8_t *)n, nlen, + (uint8_t *)v, vlen)) { + failf(data, "hyper refused to add header '%s'", line); + return CURLE_OUT_OF_MEMORY; + } + if(data->set.verbose) { + char *ptr = NULL; + if(!newline) { + ptr = aprintf("%.*s\r\n", (int)linelen, line); + if(!ptr) + return CURLE_OUT_OF_MEMORY; + Curl_debug(data, CURLINFO_HEADER_OUT, ptr, linelen + 2); + free(ptr); + } + else + Curl_debug(data, CURLINFO_HEADER_OUT, (char *)n, linelen); + } + numh++; + n += linelen; + } while(newline); + return CURLE_OK; +} + +static CURLcode request_target(struct Curl_easy *data, + struct connectdata *conn, + const char *method, + hyper_request *req) +{ + CURLcode result; + struct dynbuf r; + + Curl_dyn_init(&r, DYN_HTTP_REQUEST); + + result = Curl_http_target(data, conn, &r); + if(result) + return result; + + if(hyper_request_set_uri(req, (uint8_t *)Curl_dyn_uptr(&r), + Curl_dyn_len(&r))) { + failf(data, "error setting uri to hyper"); + result = CURLE_OUT_OF_MEMORY; + } + else + result = debug_request(data, method, Curl_dyn_ptr(&r)); + + Curl_dyn_free(&r); + + return result; +} + +static int uploadstreamed(void *userdata, hyper_context *ctx, + hyper_buf **chunk) +{ + size_t fillcount; + struct Curl_easy *data = (struct Curl_easy *)userdata; + CURLcode result; + char *xfer_ulbuf; + size_t xfer_ulblen; + bool eos; + int rc = HYPER_POLL_ERROR; + (void)ctx; + + result = Curl_multi_xfer_ulbuf_borrow(data, &xfer_ulbuf, &xfer_ulblen); + if(result) + goto out; + + result = Curl_client_read(data, xfer_ulbuf, xfer_ulblen, &fillcount, &eos); + if(result) + goto out; + + if(fillcount) { + hyper_buf *copy = hyper_buf_copy((uint8_t *)xfer_ulbuf, fillcount); + if(copy) + *chunk = copy; + else { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + /* increasing the writebytecount here is a little premature but we + don't know exactly when the body is sent */ + data->req.writebytecount += fillcount; + Curl_pgrsSetUploadCounter(data, data->req.writebytecount); + rc = HYPER_POLL_READY; + } + else if(eos) { + *chunk = NULL; + rc = HYPER_POLL_READY; + } + else { + /* paused, save a waker */ + if(data->hyp.send_body_waker) + hyper_waker_free(data->hyp.send_body_waker); + data->hyp.send_body_waker = hyper_context_waker(ctx); + rc = HYPER_POLL_PENDING; + } + +out: + Curl_multi_xfer_ulbuf_release(data, xfer_ulbuf); + data->state.hresult = result; + return rc; +} + +/* + * finalize_request() sets up last headers and optional body settings + */ +static CURLcode finalize_request(struct Curl_easy *data, + hyper_headers *headers, + hyper_request *hyperreq, + Curl_HttpReq httpreq) +{ + CURLcode result = CURLE_OK; + struct dynbuf req; + if((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) + Curl_pgrsSetUploadSize(data, 0); /* no request body */ + else { + hyper_body *body; + Curl_dyn_init(&req, DYN_HTTP_REQUEST); + result = Curl_http_req_complete(data, &req, httpreq); + if(result) + return result; + + /* if the "complete" above did produce more than the closing line, + parse the added headers */ + if(Curl_dyn_len(&req) != 2 || strcmp(Curl_dyn_ptr(&req), "\r\n")) { + result = Curl_hyper_header(data, headers, Curl_dyn_ptr(&req)); + if(result) + return result; + } + + Curl_dyn_free(&req); + + body = hyper_body_new(); + hyper_body_set_userdata(body, data); + hyper_body_set_data_func(body, uploadstreamed); + + if(HYPERE_OK != hyper_request_set_body(hyperreq, body)) { + /* fail */ + result = CURLE_OUT_OF_MEMORY; + } + } + + return cr_hyper_add(data); +} + +static CURLcode cookies(struct Curl_easy *data, + struct connectdata *conn, + hyper_headers *headers) +{ + struct dynbuf req; + CURLcode result; + Curl_dyn_init(&req, DYN_HTTP_REQUEST); + + result = Curl_http_cookies(data, conn, &req); + if(!result) + result = Curl_hyper_header(data, headers, Curl_dyn_ptr(&req)); + Curl_dyn_free(&req); + return result; +} + +/* called on 1xx responses */ +static void http1xx_cb(void *arg, struct hyper_response *resp) +{ + struct Curl_easy *data = (struct Curl_easy *)arg; + hyper_headers *headers = NULL; + CURLcode result = CURLE_OK; + uint16_t http_status; + int http_version; + const uint8_t *reasonp; + size_t reason_len; + + infof(data, "Got HTTP 1xx informational"); + + http_status = hyper_response_status(resp); + http_version = hyper_response_version(resp); + reasonp = hyper_response_reason_phrase(resp); + reason_len = hyper_response_reason_phrase_len(resp); + + result = status_line(data, data->conn, + http_status, http_version, reasonp, reason_len); + if(!result) { + headers = hyper_response_headers(resp); + if(!headers) { + failf(data, "hyperstream: couldn't get 1xx response headers"); + result = CURLE_RECV_ERROR; + } + } + data->state.hresult = result; + + if(!result) { + /* the headers are already received */ + hyper_headers_foreach(headers, hyper_each_header, data); + /* this callback also sets data->state.hresult on error */ + + if(empty_header(data)) + result = CURLE_OUT_OF_MEMORY; + } + + if(data->state.hresult) + infof(data, "ERROR in 1xx, bail out"); +} + +/* + * Curl_http() gets called from the generic multi_do() function when an HTTP + * request is to be performed. This creates and sends a properly constructed + * HTTP request. + */ +CURLcode Curl_http(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct hyptransfer *h = &data->hyp; + hyper_io *io = NULL; + hyper_clientconn_options *options = NULL; + hyper_task *task = NULL; /* for the handshake */ + hyper_task *sendtask = NULL; /* for the send */ + hyper_clientconn *client = NULL; + hyper_request *req = NULL; + hyper_headers *headers = NULL; + hyper_task *handshake = NULL; + CURLcode result; + const char *p_accept; /* Accept: string */ + const char *method; + Curl_HttpReq httpreq; + const char *te = NULL; /* transfer-encoding */ + hyper_code rc; + + /* Always consider the DO phase done after this function call, even if there + may be parts of the request that is not yet sent, since we can deal with + the rest of the request in the PERFORM phase. */ + *done = TRUE; + result = Curl_client_start(data); + if(result) + return result; + + /* Add collecting of headers written to client. For a new connection, + * we might have done that already, but reuse + * or multiplex needs it here as well. */ + result = Curl_headers_init(data); + if(result) + return result; + + infof(data, "Time for the Hyper dance"); + memset(h, 0, sizeof(struct hyptransfer)); + + result = Curl_http_host(data, conn); + if(result) + return result; + + Curl_http_method(data, conn, &method, &httpreq); + + DEBUGASSERT(data->req.bytecount == 0); + + /* setup the authentication headers */ + { + char *pq = NULL; + if(data->state.up.query) { + pq = aprintf("%s?%s", data->state.up.path, data->state.up.query); + if(!pq) + return CURLE_OUT_OF_MEMORY; + } + result = Curl_http_output_auth(data, conn, method, httpreq, + (pq ? pq : data->state.up.path), FALSE); + free(pq); + if(result) + return result; + } + + result = Curl_http_req_set_reader(data, httpreq, &te); + if(result) + goto error; + + result = Curl_http_range(data, httpreq); + if(result) + return result; + + result = Curl_http_useragent(data); + if(result) + return result; + + io = hyper_io_new(); + if(!io) { + failf(data, "Couldn't create hyper IO"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + /* tell Hyper how to read/write network data */ + h->io_ctx.data = data; + h->io_ctx.sockindex = FIRSTSOCKET; + hyper_io_set_userdata(io, &h->io_ctx); + hyper_io_set_read(io, Curl_hyper_recv); + hyper_io_set_write(io, Curl_hyper_send); + + /* create an executor to poll futures */ + if(!h->exec) { + h->exec = hyper_executor_new(); + if(!h->exec) { + failf(data, "Couldn't create hyper executor"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + } + + options = hyper_clientconn_options_new(); + if(!options) { + failf(data, "Couldn't create hyper client options"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + if(conn->alpn == CURL_HTTP_VERSION_2) { + failf(data, "ALPN protocol h2 not supported with Hyper"); + result = CURLE_UNSUPPORTED_PROTOCOL; + goto error; + } + hyper_clientconn_options_set_preserve_header_case(options, 1); + hyper_clientconn_options_set_preserve_header_order(options, 1); + hyper_clientconn_options_http1_allow_multiline_headers(options, 1); + + hyper_clientconn_options_exec(options, h->exec); + + /* "Both the `io` and the `options` are consumed in this function call" */ + handshake = hyper_clientconn_handshake(io, options); + if(!handshake) { + failf(data, "Couldn't create hyper client handshake"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + io = NULL; + options = NULL; + + if(HYPERE_OK != hyper_executor_push(h->exec, handshake)) { + failf(data, "Couldn't hyper_executor_push the handshake"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + handshake = NULL; /* ownership passed on */ + + task = hyper_executor_poll(h->exec); + if(!task) { + failf(data, "Couldn't hyper_executor_poll the handshake"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + client = hyper_task_value(task); + hyper_task_free(task); + + req = hyper_request_new(); + if(!req) { + failf(data, "Couldn't hyper_request_new"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + if(!Curl_use_http_1_1plus(data, conn)) { + if(HYPERE_OK != hyper_request_set_version(req, + HYPER_HTTP_VERSION_1_0)) { + failf(data, "error setting HTTP version"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + } + + if(hyper_request_set_method(req, (uint8_t *)method, strlen(method))) { + failf(data, "error setting method"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + result = request_target(data, conn, method, req); + if(result) + goto error; + + headers = hyper_request_headers(req); + if(!headers) { + failf(data, "hyper_request_headers"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + rc = hyper_request_on_informational(req, http1xx_cb, data); + if(rc) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + if(data->state.aptr.host) { + result = Curl_hyper_header(data, headers, data->state.aptr.host); + if(result) + goto error; + } + +#ifndef CURL_DISABLE_PROXY + if(data->state.aptr.proxyuserpwd) { + result = Curl_hyper_header(data, headers, data->state.aptr.proxyuserpwd); + if(result) + goto error; + } +#endif + + if(data->state.aptr.userpwd) { + result = Curl_hyper_header(data, headers, data->state.aptr.userpwd); + if(result) + goto error; + } + + if((data->state.use_range && data->state.aptr.rangeline)) { + result = Curl_hyper_header(data, headers, data->state.aptr.rangeline); + if(result) + goto error; + } + + if(data->set.str[STRING_USERAGENT] && + *data->set.str[STRING_USERAGENT] && + data->state.aptr.uagent) { + result = Curl_hyper_header(data, headers, data->state.aptr.uagent); + if(result) + goto error; + } + + p_accept = Curl_checkheaders(data, + STRCONST("Accept"))?NULL:"Accept: */*\r\n"; + if(p_accept) { + result = Curl_hyper_header(data, headers, p_accept); + if(result) + goto error; + } + if(te) { + result = Curl_hyper_header(data, headers, te); + if(result) + goto error; + } + +#ifndef CURL_DISABLE_ALTSVC + if(conn->bits.altused && !Curl_checkheaders(data, STRCONST("Alt-Used"))) { + char *altused = aprintf("Alt-Used: %s:%d\r\n", + conn->conn_to_host.name, conn->conn_to_port); + if(!altused) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + result = Curl_hyper_header(data, headers, altused); + if(result) + goto error; + free(altused); + } +#endif + +#ifndef CURL_DISABLE_PROXY + if(conn->bits.httpproxy && !conn->bits.tunnel_proxy && + !Curl_checkheaders(data, STRCONST("Proxy-Connection")) && + !Curl_checkProxyheaders(data, conn, STRCONST("Proxy-Connection"))) { + result = Curl_hyper_header(data, headers, "Proxy-Connection: Keep-Alive"); + if(result) + goto error; + } +#endif + + Curl_safefree(data->state.aptr.ref); + if(data->state.referer && !Curl_checkheaders(data, STRCONST("Referer"))) { + data->state.aptr.ref = aprintf("Referer: %s\r\n", data->state.referer); + if(!data->state.aptr.ref) + result = CURLE_OUT_OF_MEMORY; + else + result = Curl_hyper_header(data, headers, data->state.aptr.ref); + if(result) + goto error; + } + +#ifdef HAVE_LIBZ + /* we only consider transfer-encoding magic if libz support is built-in */ + result = Curl_transferencode(data); + if(result) + goto error; + result = Curl_hyper_header(data, headers, data->state.aptr.te); + if(result) + goto error; +#endif + + if(!Curl_checkheaders(data, STRCONST("Accept-Encoding")) && + data->set.str[STRING_ENCODING]) { + Curl_safefree(data->state.aptr.accept_encoding); + data->state.aptr.accept_encoding = + aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]); + if(!data->state.aptr.accept_encoding) + result = CURLE_OUT_OF_MEMORY; + else + result = Curl_hyper_header(data, headers, + data->state.aptr.accept_encoding); + if(result) + goto error; + } + else + Curl_safefree(data->state.aptr.accept_encoding); + + result = cookies(data, conn, headers); + if(result) + goto error; + + if(!result && conn->handler->protocol&(CURLPROTO_WS|CURLPROTO_WSS)) + result = Curl_ws_request(data, headers); + + result = Curl_add_timecondition(data, headers); + if(result) + goto error; + + result = Curl_add_custom_headers(data, FALSE, headers); + if(result) + goto error; + + result = finalize_request(data, headers, req, httpreq); + if(result) + goto error; + + Curl_debug(data, CURLINFO_HEADER_OUT, (char *)"\r\n", 2); + + if(data->req.upload_chunky && data->req.authneg) { + data->req.upload_chunky = TRUE; + } + else { + data->req.upload_chunky = FALSE; + } + sendtask = hyper_clientconn_send(client, req); + if(!sendtask) { + failf(data, "hyper_clientconn_send"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + req = NULL; + + if(HYPERE_OK != hyper_executor_push(h->exec, sendtask)) { + failf(data, "Couldn't hyper_executor_push the send"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + sendtask = NULL; /* ownership passed on */ + + hyper_clientconn_free(client); + client = NULL; + + if((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) { + /* HTTP GET/HEAD download */ + Curl_pgrsSetUploadSize(data, 0); /* nothing */ + } + + Curl_xfer_setup(data, FIRSTSOCKET, -1, TRUE, FIRSTSOCKET); + conn->datastream = Curl_hyper_stream; + + /* clear userpwd and proxyuserpwd to avoid reusing old credentials + * from reused connections */ + Curl_safefree(data->state.aptr.userpwd); +#ifndef CURL_DISABLE_PROXY + Curl_safefree(data->state.aptr.proxyuserpwd); +#endif + return CURLE_OK; +error: + DEBUGASSERT(result); + if(io) + hyper_io_free(io); + + if(options) + hyper_clientconn_options_free(options); + + if(handshake) + hyper_task_free(handshake); + + if(client) + hyper_clientconn_free(client); + + if(req) + hyper_request_free(req); + + return result; +} + +void Curl_hyper_done(struct Curl_easy *data) +{ + struct hyptransfer *h = &data->hyp; + if(h->exec) { + hyper_executor_free(h->exec); + h->exec = NULL; + } + if(h->read_waker) { + hyper_waker_free(h->read_waker); + h->read_waker = NULL; + } + if(h->write_waker) { + hyper_waker_free(h->write_waker); + h->write_waker = NULL; + } + if(h->send_body_waker) { + hyper_waker_free(h->send_body_waker); + h->send_body_waker = NULL; + } +} + +static CURLcode cr_hyper_unpause(struct Curl_easy *data, + struct Curl_creader *reader) +{ + (void)reader; + if(data->hyp.send_body_waker) { + hyper_waker_wake(data->hyp.send_body_waker); + data->hyp.send_body_waker = NULL; + } + return CURLE_OK; +} + +/* Hyper client reader, handling unpausing */ +static const struct Curl_crtype cr_hyper_protocol = { + "cr-hyper", + Curl_creader_def_init, + Curl_creader_def_read, + Curl_creader_def_close, + Curl_creader_def_needs_rewind, + Curl_creader_def_total_length, + Curl_creader_def_resume_from, + Curl_creader_def_rewind, + cr_hyper_unpause, + Curl_creader_def_done, + sizeof(struct Curl_creader) +}; + +static CURLcode cr_hyper_add(struct Curl_easy *data) +{ + struct Curl_creader *reader = NULL; + CURLcode result; + + result = Curl_creader_create(&reader, data, &cr_hyper_protocol, + CURL_CR_PROTOCOL); + if(!result) + result = Curl_creader_add(data, reader); + + if(result && reader) + Curl_creader_free(data, reader); + return result; +} + +#endif /* !defined(CURL_DISABLE_HTTP) && defined(USE_HYPER) */ diff --git a/third_party/curl/lib/c-hyper.h b/third_party/curl/lib/c-hyper.h new file mode 100644 index 0000000..89dd53b --- /dev/null +++ b/third_party/curl/lib/c-hyper.h @@ -0,0 +1,63 @@ +#ifndef HEADER_CURL_HYPER_H +#define HEADER_CURL_HYPER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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.haxx.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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_HYPER) + +#include + +struct hyp_io_ctx { + struct Curl_easy *data; + int sockindex; +}; + +/* per-transfer data for the Hyper backend */ +struct hyptransfer { + hyper_waker *write_waker; + hyper_waker *read_waker; + const hyper_executor *exec; + hyper_waker *send_body_waker; + struct hyp_io_ctx io_ctx; +}; + +size_t Curl_hyper_recv(void *userp, hyper_context *ctx, + uint8_t *buf, size_t buflen); +size_t Curl_hyper_send(void *userp, hyper_context *ctx, + const uint8_t *buf, size_t buflen); +CURLcode Curl_hyper_stream(struct Curl_easy *data, + struct connectdata *conn, + int *didwhat, + int select_res); + +CURLcode Curl_hyper_header(struct Curl_easy *data, hyper_headers *headers, + const char *line); +void Curl_hyper_done(struct Curl_easy *); + +#else +#define Curl_hyper_done(x) + +#endif /* !defined(CURL_DISABLE_HTTP) && defined(USE_HYPER) */ +#endif /* HEADER_CURL_HYPER_H */ diff --git a/third_party/curl/lib/cf-h1-proxy.c b/third_party/curl/lib/cf-h1-proxy.c new file mode 100644 index 0000000..093c33b --- /dev/null +++ b/third_party/curl/lib/cf-h1-proxy.c @@ -0,0 +1,1104 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP) + +#include +#ifdef USE_HYPER +#include +#endif +#include "urldata.h" +#include "dynbuf.h" +#include "sendf.h" +#include "http.h" +#include "http1.h" +#include "http_proxy.h" +#include "url.h" +#include "select.h" +#include "progress.h" +#include "cfilters.h" +#include "cf-h1-proxy.h" +#include "connect.h" +#include "curl_trc.h" +#include "curlx.h" +#include "vtls/vtls.h" +#include "transfer.h" +#include "multiif.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +typedef enum { + H1_TUNNEL_INIT, /* init/default/no tunnel state */ + H1_TUNNEL_CONNECT, /* CONNECT request is being send */ + H1_TUNNEL_RECEIVE, /* CONNECT answer is being received */ + H1_TUNNEL_RESPONSE, /* CONNECT response received completely */ + H1_TUNNEL_ESTABLISHED, + H1_TUNNEL_FAILED +} h1_tunnel_state; + +/* struct for HTTP CONNECT tunneling */ +struct h1_tunnel_state { + struct HTTP CONNECT; + struct dynbuf rcvbuf; + struct dynbuf request_data; + size_t nsent; + size_t headerlines; + struct Curl_chunker ch; + enum keeponval { + KEEPON_DONE, + KEEPON_CONNECT, + KEEPON_IGNORE + } keepon; + curl_off_t cl; /* size of content to read and ignore */ + h1_tunnel_state tunnel_state; + BIT(chunked_encoding); + BIT(close_connection); +}; + + +static bool tunnel_is_established(struct h1_tunnel_state *ts) +{ + return ts && (ts->tunnel_state == H1_TUNNEL_ESTABLISHED); +} + +static bool tunnel_is_failed(struct h1_tunnel_state *ts) +{ + return ts && (ts->tunnel_state == H1_TUNNEL_FAILED); +} + +static CURLcode tunnel_reinit(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts) +{ + (void)data; + (void)cf; + DEBUGASSERT(ts); + Curl_dyn_reset(&ts->rcvbuf); + Curl_dyn_reset(&ts->request_data); + ts->tunnel_state = H1_TUNNEL_INIT; + ts->keepon = KEEPON_CONNECT; + ts->cl = 0; + ts->close_connection = FALSE; + return CURLE_OK; +} + +static CURLcode tunnel_init(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state **pts) +{ + struct h1_tunnel_state *ts; + + if(cf->conn->handler->flags & PROTOPT_NOTCPPROXY) { + failf(data, "%s cannot be done over CONNECT", cf->conn->handler->scheme); + return CURLE_UNSUPPORTED_PROTOCOL; + } + + ts = calloc(1, sizeof(*ts)); + if(!ts) + return CURLE_OUT_OF_MEMORY; + + infof(data, "allocate connect buffer"); + + Curl_dyn_init(&ts->rcvbuf, DYN_PROXY_CONNECT_HEADERS); + Curl_dyn_init(&ts->request_data, DYN_HTTP_REQUEST); + Curl_httpchunk_init(data, &ts->ch, TRUE); + + *pts = ts; + connkeep(cf->conn, "HTTP proxy CONNECT"); + return tunnel_reinit(cf, data, ts); +} + +static void h1_tunnel_go_state(struct Curl_cfilter *cf, + struct h1_tunnel_state *ts, + h1_tunnel_state new_state, + struct Curl_easy *data) +{ + if(ts->tunnel_state == new_state) + return; + /* entering this one */ + switch(new_state) { + case H1_TUNNEL_INIT: + CURL_TRC_CF(data, cf, "new tunnel state 'init'"); + tunnel_reinit(cf, data, ts); + break; + + case H1_TUNNEL_CONNECT: + CURL_TRC_CF(data, cf, "new tunnel state 'connect'"); + ts->tunnel_state = H1_TUNNEL_CONNECT; + ts->keepon = KEEPON_CONNECT; + Curl_dyn_reset(&ts->rcvbuf); + break; + + case H1_TUNNEL_RECEIVE: + CURL_TRC_CF(data, cf, "new tunnel state 'receive'"); + ts->tunnel_state = H1_TUNNEL_RECEIVE; + break; + + case H1_TUNNEL_RESPONSE: + CURL_TRC_CF(data, cf, "new tunnel state 'response'"); + ts->tunnel_state = H1_TUNNEL_RESPONSE; + break; + + case H1_TUNNEL_ESTABLISHED: + CURL_TRC_CF(data, cf, "new tunnel state 'established'"); + infof(data, "CONNECT phase completed"); + data->state.authproxy.done = TRUE; + data->state.authproxy.multipass = FALSE; + FALLTHROUGH(); + case H1_TUNNEL_FAILED: + if(new_state == H1_TUNNEL_FAILED) + CURL_TRC_CF(data, cf, "new tunnel state 'failed'"); + ts->tunnel_state = new_state; + Curl_dyn_reset(&ts->rcvbuf); + Curl_dyn_reset(&ts->request_data); + /* restore the protocol pointer */ + data->info.httpcode = 0; /* clear it as it might've been used for the + proxy */ + /* If a proxy-authorization header was used for the proxy, then we should + make sure that it isn't accidentally used for the document request + after we've connected. So let's free and clear it here. */ + Curl_safefree(data->state.aptr.proxyuserpwd); +#ifdef USE_HYPER + data->state.hconnect = FALSE; +#endif + break; + } +} + +static void tunnel_free(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + if(cf) { + struct h1_tunnel_state *ts = cf->ctx; + if(ts) { + h1_tunnel_go_state(cf, ts, H1_TUNNEL_FAILED, data); + Curl_dyn_free(&ts->rcvbuf); + Curl_dyn_free(&ts->request_data); + Curl_httpchunk_free(data, &ts->ch); + free(ts); + cf->ctx = NULL; + } + } +} + +static bool tunnel_want_send(struct h1_tunnel_state *ts) +{ + return (ts->tunnel_state == H1_TUNNEL_CONNECT); +} + +#ifndef USE_HYPER +static CURLcode start_CONNECT(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts) +{ + struct httpreq *req = NULL; + int http_minor; + CURLcode result; + + /* This only happens if we've looped here due to authentication + reasons, and we don't really use the newly cloned URL here + then. Just free() it. */ + Curl_safefree(data->req.newurl); + + result = Curl_http_proxy_create_CONNECT(&req, cf, data, 1); + if(result) + goto out; + + infof(data, "Establish HTTP proxy tunnel to %s", req->authority); + + Curl_dyn_reset(&ts->request_data); + ts->nsent = 0; + ts->headerlines = 0; + http_minor = (cf->conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0) ? 0 : 1; + + result = Curl_h1_req_write_head(req, http_minor, &ts->request_data); + if(!result) + result = Curl_creader_set_null(data); + +out: + if(result) + failf(data, "Failed sending CONNECT to proxy"); + if(req) + Curl_http_req_free(req); + return result; +} + +static CURLcode send_CONNECT(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts, + bool *done) +{ + char *buf = Curl_dyn_ptr(&ts->request_data); + size_t request_len = Curl_dyn_len(&ts->request_data); + size_t blen = request_len; + CURLcode result = CURLE_OK; + ssize_t nwritten; + + if(blen <= ts->nsent) + goto out; /* we are done */ + + blen -= ts->nsent; + buf += ts->nsent; + + nwritten = cf->next->cft->do_send(cf->next, data, buf, blen, &result); + if(nwritten < 0) { + if(result == CURLE_AGAIN) { + result = CURLE_OK; + } + goto out; + } + + DEBUGASSERT(blen >= (size_t)nwritten); + ts->nsent += (size_t)nwritten; + Curl_debug(data, CURLINFO_HEADER_OUT, buf, (size_t)nwritten); + +out: + if(result) + failf(data, "Failed sending CONNECT to proxy"); + *done = (!result && (ts->nsent >= request_len)); + return result; +} + +static CURLcode on_resp_header(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts, + const char *header) +{ + CURLcode result = CURLE_OK; + struct SingleRequest *k = &data->req; + (void)cf; + + if((checkprefix("WWW-Authenticate:", header) && + (401 == k->httpcode)) || + (checkprefix("Proxy-authenticate:", header) && + (407 == k->httpcode))) { + + bool proxy = (k->httpcode == 407) ? TRUE : FALSE; + char *auth = Curl_copy_header_value(header); + if(!auth) + return CURLE_OUT_OF_MEMORY; + + CURL_TRC_CF(data, cf, "CONNECT: fwd auth header '%s'", header); + result = Curl_http_input_auth(data, proxy, auth); + + free(auth); + + if(result) + return result; + } + else if(checkprefix("Content-Length:", header)) { + if(k->httpcode/100 == 2) { + /* A client MUST ignore any Content-Length or Transfer-Encoding + header fields received in a successful response to CONNECT. + "Successful" described as: 2xx (Successful). RFC 7231 4.3.6 */ + infof(data, "Ignoring Content-Length in CONNECT %03d response", + k->httpcode); + } + else { + (void)curlx_strtoofft(header + strlen("Content-Length:"), + NULL, 10, &ts->cl); + } + } + else if(Curl_compareheader(header, + STRCONST("Connection:"), STRCONST("close"))) + ts->close_connection = TRUE; + else if(checkprefix("Transfer-Encoding:", header)) { + if(k->httpcode/100 == 2) { + /* A client MUST ignore any Content-Length or Transfer-Encoding + header fields received in a successful response to CONNECT. + "Successful" described as: 2xx (Successful). RFC 7231 4.3.6 */ + infof(data, "Ignoring Transfer-Encoding in " + "CONNECT %03d response", k->httpcode); + } + else if(Curl_compareheader(header, + STRCONST("Transfer-Encoding:"), + STRCONST("chunked"))) { + infof(data, "CONNECT responded chunked"); + ts->chunked_encoding = TRUE; + /* reset our chunky engine */ + Curl_httpchunk_reset(data, &ts->ch, TRUE); + } + } + else if(Curl_compareheader(header, + STRCONST("Proxy-Connection:"), + STRCONST("close"))) + ts->close_connection = TRUE; + else if(!strncmp(header, "HTTP/1.", 7) && + ((header[7] == '0') || (header[7] == '1')) && + (header[8] == ' ') && + ISDIGIT(header[9]) && ISDIGIT(header[10]) && ISDIGIT(header[11]) && + !ISDIGIT(header[12])) { + /* store the HTTP code from the proxy */ + data->info.httpproxycode = k->httpcode = (header[9] - '0') * 100 + + (header[10] - '0') * 10 + (header[11] - '0'); + } + return result; +} + +static CURLcode recv_CONNECT_resp(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts, + bool *done) +{ + CURLcode result = CURLE_OK; + struct SingleRequest *k = &data->req; + char *linep; + size_t line_len; + int error, writetype; + +#define SELECT_OK 0 +#define SELECT_ERROR 1 + + error = SELECT_OK; + *done = FALSE; + + if(!Curl_conn_data_pending(data, cf->sockindex)) + return CURLE_OK; + + while(ts->keepon) { + ssize_t nread; + char byte; + + /* Read one byte at a time to avoid a race condition. Wait at most one + second before looping to ensure continuous pgrsUpdates. */ + result = Curl_conn_recv(data, cf->sockindex, &byte, 1, &nread); + if(result == CURLE_AGAIN) + /* socket buffer drained, return */ + return CURLE_OK; + + if(Curl_pgrsUpdate(data)) + return CURLE_ABORTED_BY_CALLBACK; + + if(result) { + ts->keepon = KEEPON_DONE; + break; + } + + if(nread <= 0) { + if(data->set.proxyauth && data->state.authproxy.avail && + data->state.aptr.proxyuserpwd) { + /* proxy auth was requested and there was proxy auth available, + then deem this as "mere" proxy disconnect */ + ts->close_connection = TRUE; + infof(data, "Proxy CONNECT connection closed"); + } + else { + error = SELECT_ERROR; + failf(data, "Proxy CONNECT aborted"); + } + ts->keepon = KEEPON_DONE; + break; + } + + if(ts->keepon == KEEPON_IGNORE) { + /* This means we are currently ignoring a response-body */ + + if(ts->cl) { + /* A Content-Length based body: simply count down the counter + and make sure to break out of the loop when we're done! */ + ts->cl--; + if(ts->cl <= 0) { + ts->keepon = KEEPON_DONE; + break; + } + } + else if(ts->chunked_encoding) { + /* chunked-encoded body, so we need to do the chunked dance + properly to know when the end of the body is reached */ + size_t consumed = 0; + + /* now parse the chunked piece of data so that we can + properly tell when the stream ends */ + result = Curl_httpchunk_read(data, &ts->ch, &byte, 1, &consumed); + if(result) + return result; + if(Curl_httpchunk_is_done(data, &ts->ch)) { + /* we're done reading chunks! */ + infof(data, "chunk reading DONE"); + ts->keepon = KEEPON_DONE; + } + } + continue; + } + + if(Curl_dyn_addn(&ts->rcvbuf, &byte, 1)) { + failf(data, "CONNECT response too large"); + return CURLE_RECV_ERROR; + } + + /* if this is not the end of a header line then continue */ + if(byte != 0x0a) + continue; + + ts->headerlines++; + linep = Curl_dyn_ptr(&ts->rcvbuf); + line_len = Curl_dyn_len(&ts->rcvbuf); /* amount of bytes in this line */ + + /* output debug if that is requested */ + Curl_debug(data, CURLINFO_HEADER_IN, linep, line_len); + + /* send the header to the callback */ + writetype = CLIENTWRITE_HEADER | CLIENTWRITE_CONNECT | + (ts->headerlines == 1 ? CLIENTWRITE_STATUS : 0); + result = Curl_client_write(data, writetype, linep, line_len); + if(result) + return result; + + result = Curl_bump_headersize(data, line_len, TRUE); + if(result) + return result; + + /* Newlines are CRLF, so the CR is ignored as the line isn't + really terminated until the LF comes. Treat a following CR + as end-of-headers as well.*/ + + if(('\r' == linep[0]) || + ('\n' == linep[0])) { + /* end of response-headers from the proxy */ + + if((407 == k->httpcode) && !data->state.authproblem) { + /* If we get a 407 response code with content length + when we have no auth problem, we must ignore the + whole response-body */ + ts->keepon = KEEPON_IGNORE; + + if(ts->cl) { + infof(data, "Ignore %" CURL_FORMAT_CURL_OFF_T + " bytes of response-body", ts->cl); + } + else if(ts->chunked_encoding) { + infof(data, "Ignore chunked response-body"); + } + else { + /* without content-length or chunked encoding, we + can't keep the connection alive since the close is + the end signal so we bail out at once instead */ + CURL_TRC_CF(data, cf, "CONNECT: no content-length or chunked"); + ts->keepon = KEEPON_DONE; + } + } + else { + ts->keepon = KEEPON_DONE; + } + + DEBUGASSERT(ts->keepon == KEEPON_IGNORE + || ts->keepon == KEEPON_DONE); + continue; + } + + result = on_resp_header(cf, data, ts, linep); + if(result) + return result; + + Curl_dyn_reset(&ts->rcvbuf); + } /* while there's buffer left and loop is requested */ + + if(error) + result = CURLE_RECV_ERROR; + *done = (ts->keepon == KEEPON_DONE); + if(!result && *done && data->info.httpproxycode/100 != 2) { + /* Deal with the possibly already received authenticate + headers. 'newurl' is set to a new URL if we must loop. */ + result = Curl_http_auth_act(data); + } + return result; +} + +#else /* USE_HYPER */ + +static CURLcode CONNECT_host(struct Curl_cfilter *cf, + struct Curl_easy *data, + char **pauthority, + char **phost_header) +{ + const char *hostname; + int port; + bool ipv6_ip; + CURLcode result; + char *authority; /* for CONNECT, the destination host + port */ + char *host_header = NULL; /* Host: authority */ + + result = Curl_http_proxy_get_destination(cf, &hostname, &port, &ipv6_ip); + if(result) + return result; + + authority = aprintf("%s%s%s:%d", ipv6_ip?"[":"", hostname, ipv6_ip?"]":"", + port); + if(!authority) + return CURLE_OUT_OF_MEMORY; + + /* If user is not overriding the Host header later */ + if(!Curl_checkProxyheaders(data, cf->conn, STRCONST("Host"))) { + host_header = aprintf("Host: %s\r\n", authority); + if(!host_header) { + free(authority); + return CURLE_OUT_OF_MEMORY; + } + } + *pauthority = authority; + *phost_header = host_header; + return CURLE_OK; +} + +/* The Hyper version of CONNECT */ +static CURLcode start_CONNECT(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts) +{ + struct connectdata *conn = cf->conn; + struct hyptransfer *h = &data->hyp; + curl_socket_t tunnelsocket = Curl_conn_cf_get_socket(cf, data); + hyper_io *io = NULL; + hyper_request *req = NULL; + hyper_headers *headers = NULL; + hyper_clientconn_options *options = NULL; + hyper_task *handshake = NULL; + hyper_task *task = NULL; /* for the handshake */ + hyper_clientconn *client = NULL; + hyper_task *sendtask = NULL; /* for the send */ + char *authority = NULL; /* for CONNECT */ + char *host_header = NULL; /* Host: */ + CURLcode result = CURLE_OUT_OF_MEMORY; + (void)ts; + + io = hyper_io_new(); + if(!io) { + failf(data, "Couldn't create hyper IO"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + /* tell Hyper how to read/write network data */ + h->io_ctx.data = data; + h->io_ctx.sockindex = cf->sockindex; + hyper_io_set_userdata(io, &h->io_ctx); + hyper_io_set_read(io, Curl_hyper_recv); + hyper_io_set_write(io, Curl_hyper_send); + conn->sockfd = tunnelsocket; + + data->state.hconnect = TRUE; + + /* create an executor to poll futures */ + if(!h->exec) { + h->exec = hyper_executor_new(); + if(!h->exec) { + failf(data, "Couldn't create hyper executor"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + } + + options = hyper_clientconn_options_new(); + if(!options) { + failf(data, "Couldn't create hyper client options"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + hyper_clientconn_options_set_preserve_header_case(options, 1); + hyper_clientconn_options_set_preserve_header_order(options, 1); + + hyper_clientconn_options_exec(options, h->exec); + + /* "Both the `io` and the `options` are consumed in this function + call" */ + handshake = hyper_clientconn_handshake(io, options); + if(!handshake) { + failf(data, "Couldn't create hyper client handshake"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + io = NULL; + options = NULL; + + if(HYPERE_OK != hyper_executor_push(h->exec, handshake)) { + failf(data, "Couldn't hyper_executor_push the handshake"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + handshake = NULL; /* ownership passed on */ + + task = hyper_executor_poll(h->exec); + if(!task) { + failf(data, "Couldn't hyper_executor_poll the handshake"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + client = hyper_task_value(task); + hyper_task_free(task); + + req = hyper_request_new(); + if(!req) { + failf(data, "Couldn't hyper_request_new"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + if(hyper_request_set_method(req, (uint8_t *)"CONNECT", + strlen("CONNECT"))) { + failf(data, "error setting method"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + /* This only happens if we've looped here due to authentication + reasons, and we don't really use the newly cloned URL here + then. Just free() it. */ + Curl_safefree(data->req.newurl); + + result = CONNECT_host(cf, data, &authority, &host_header); + if(result) + goto error; + + infof(data, "Establish HTTP proxy tunnel to %s", authority); + + if(hyper_request_set_uri(req, (uint8_t *)authority, + strlen(authority))) { + failf(data, "error setting path"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + if(data->set.verbose) { + char *se = aprintf("CONNECT %s HTTP/1.1\r\n", authority); + if(!se) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + Curl_debug(data, CURLINFO_HEADER_OUT, se, strlen(se)); + free(se); + } + /* Setup the proxy-authorization header, if any */ + result = Curl_http_output_auth(data, conn, "CONNECT", HTTPREQ_GET, + authority, TRUE); + if(result) + goto error; + Curl_safefree(authority); + + /* default is 1.1 */ + if((conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0) && + (HYPERE_OK != hyper_request_set_version(req, + HYPER_HTTP_VERSION_1_0))) { + failf(data, "error setting HTTP version"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + headers = hyper_request_headers(req); + if(!headers) { + failf(data, "hyper_request_headers"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + if(host_header) { + result = Curl_hyper_header(data, headers, host_header); + if(result) + goto error; + Curl_safefree(host_header); + } + + if(data->state.aptr.proxyuserpwd) { + result = Curl_hyper_header(data, headers, + data->state.aptr.proxyuserpwd); + if(result) + goto error; + } + + if(!Curl_checkProxyheaders(data, conn, STRCONST("User-Agent")) && + data->set.str[STRING_USERAGENT] && *data->set.str[STRING_USERAGENT]) { + struct dynbuf ua; + Curl_dyn_init(&ua, DYN_HTTP_REQUEST); + result = Curl_dyn_addf(&ua, "User-Agent: %s\r\n", + data->set.str[STRING_USERAGENT]); + if(result) + goto error; + result = Curl_hyper_header(data, headers, Curl_dyn_ptr(&ua)); + if(result) + goto error; + Curl_dyn_free(&ua); + } + + if(!Curl_checkProxyheaders(data, conn, STRCONST("Proxy-Connection"))) { + result = Curl_hyper_header(data, headers, + "Proxy-Connection: Keep-Alive"); + if(result) + goto error; + } + + result = Curl_add_custom_headers(data, TRUE, headers); + if(result) + goto error; + + result = Curl_creader_set_null(data); + if(result) + goto error; + + sendtask = hyper_clientconn_send(client, req); + if(!sendtask) { + failf(data, "hyper_clientconn_send"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + req = NULL; + + if(HYPERE_OK != hyper_executor_push(h->exec, sendtask)) { + failf(data, "Couldn't hyper_executor_push the send"); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + sendtask = NULL; /* ownership passed on */ + + hyper_clientconn_free(client); + client = NULL; + +error: + free(host_header); + free(authority); + if(io) + hyper_io_free(io); + if(options) + hyper_clientconn_options_free(options); + if(handshake) + hyper_task_free(handshake); + if(client) + hyper_clientconn_free(client); + if(req) + hyper_request_free(req); + + return result; +} + +static CURLcode send_CONNECT(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts, + bool *done) +{ + struct hyptransfer *h = &data->hyp; + struct connectdata *conn = cf->conn; + hyper_task *task = NULL; + hyper_error *hypererr = NULL; + CURLcode result = CURLE_OK; + + (void)ts; + (void)conn; + do { + task = hyper_executor_poll(h->exec); + if(task) { + bool error = hyper_task_type(task) == HYPER_TASK_ERROR; + if(error) + hypererr = hyper_task_value(task); + hyper_task_free(task); + if(error) { + /* this could probably use a better error code? */ + result = CURLE_OUT_OF_MEMORY; + goto error; + } + } + } while(task); +error: + *done = (result == CURLE_OK); + if(hypererr) { + uint8_t errbuf[256]; + size_t errlen = hyper_error_print(hypererr, errbuf, sizeof(errbuf)); + failf(data, "Hyper: %.*s", (int)errlen, errbuf); + hyper_error_free(hypererr); + } + return result; +} + +static CURLcode recv_CONNECT_resp(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts, + bool *done) +{ + struct hyptransfer *h = &data->hyp; + CURLcode result; + int didwhat; + + (void)ts; + result = Curl_hyper_stream(data, cf->conn, &didwhat, + CURL_CSELECT_IN | CURL_CSELECT_OUT); + *done = data->req.done; + if(result || !*done) + return result; + if(h->exec) { + hyper_executor_free(h->exec); + h->exec = NULL; + } + if(h->read_waker) { + hyper_waker_free(h->read_waker); + h->read_waker = NULL; + } + if(h->write_waker) { + hyper_waker_free(h->write_waker); + h->write_waker = NULL; + } + return result; +} + +#endif /* USE_HYPER */ + +static CURLcode H1_CONNECT(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts) +{ + struct connectdata *conn = cf->conn; + CURLcode result; + bool done; + + if(tunnel_is_established(ts)) + return CURLE_OK; + if(tunnel_is_failed(ts)) + return CURLE_RECV_ERROR; /* Need a cfilter close and new bootstrap */ + + do { + timediff_t check; + + check = Curl_timeleft(data, NULL, TRUE); + if(check <= 0) { + failf(data, "Proxy CONNECT aborted due to timeout"); + result = CURLE_OPERATION_TIMEDOUT; + goto out; + } + + switch(ts->tunnel_state) { + case H1_TUNNEL_INIT: + /* Prepare the CONNECT request and make a first attempt to send. */ + CURL_TRC_CF(data, cf, "CONNECT start"); + result = start_CONNECT(cf, data, ts); + if(result) + goto out; + h1_tunnel_go_state(cf, ts, H1_TUNNEL_CONNECT, data); + FALLTHROUGH(); + + case H1_TUNNEL_CONNECT: + /* see that the request is completely sent */ + CURL_TRC_CF(data, cf, "CONNECT send"); + result = send_CONNECT(cf, data, ts, &done); + if(result || !done) + goto out; + h1_tunnel_go_state(cf, ts, H1_TUNNEL_RECEIVE, data); + FALLTHROUGH(); + + case H1_TUNNEL_RECEIVE: + /* read what is there */ + CURL_TRC_CF(data, cf, "CONNECT receive"); + result = recv_CONNECT_resp(cf, data, ts, &done); + if(Curl_pgrsUpdate(data)) { + result = CURLE_ABORTED_BY_CALLBACK; + goto out; + } + /* error or not complete yet. return for more multi-multi */ + if(result || !done) + goto out; + /* got it */ + h1_tunnel_go_state(cf, ts, H1_TUNNEL_RESPONSE, data); + FALLTHROUGH(); + + case H1_TUNNEL_RESPONSE: + CURL_TRC_CF(data, cf, "CONNECT response"); + if(data->req.newurl) { + /* not the "final" response, we need to do a follow up request. + * If the other side indicated a connection close, or if someone + * else told us to close this connection, do so now. + */ + Curl_req_soft_reset(&data->req, data); + if(ts->close_connection || conn->bits.close) { + /* Close this filter and the sub-chain, re-connect the + * sub-chain and continue. Closing this filter will + * reset our tunnel state. To avoid recursion, we return + * and expect to be called again. + */ + CURL_TRC_CF(data, cf, "CONNECT need to close+open"); + infof(data, "Connect me again please"); + Curl_conn_cf_close(cf, data); + connkeep(conn, "HTTP proxy CONNECT"); + result = Curl_conn_cf_connect(cf->next, data, FALSE, &done); + goto out; + } + else { + /* staying on this connection, reset state */ + h1_tunnel_go_state(cf, ts, H1_TUNNEL_INIT, data); + } + } + break; + + default: + break; + } + + } while(data->req.newurl); + + DEBUGASSERT(ts->tunnel_state == H1_TUNNEL_RESPONSE); + if(data->info.httpproxycode/100 != 2) { + /* a non-2xx response and we have no next url to try. */ + Curl_safefree(data->req.newurl); + /* failure, close this connection to avoid reuse */ + streamclose(conn, "proxy CONNECT failure"); + h1_tunnel_go_state(cf, ts, H1_TUNNEL_FAILED, data); + failf(data, "CONNECT tunnel failed, response %d", data->req.httpcode); + return CURLE_RECV_ERROR; + } + /* 2xx response, SUCCESS! */ + h1_tunnel_go_state(cf, ts, H1_TUNNEL_ESTABLISHED, data); + infof(data, "CONNECT tunnel established, response %d", + data->info.httpproxycode); + result = CURLE_OK; + +out: + if(result) + h1_tunnel_go_state(cf, ts, H1_TUNNEL_FAILED, data); + return result; +} + +static CURLcode cf_h1_proxy_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + CURLcode result; + struct h1_tunnel_state *ts = cf->ctx; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + CURL_TRC_CF(data, cf, "connect"); + result = cf->next->cft->do_connect(cf->next, data, blocking, done); + if(result || !*done) + return result; + + *done = FALSE; + if(!ts) { + result = tunnel_init(cf, data, &ts); + if(result) + return result; + cf->ctx = ts; + } + + /* TODO: can we do blocking? */ + /* We want "seamless" operations through HTTP proxy tunnel */ + + result = H1_CONNECT(cf, data, ts); + if(result) + goto out; + Curl_safefree(data->state.aptr.proxyuserpwd); + +out: + *done = (result == CURLE_OK) && tunnel_is_established(cf->ctx); + if(*done) { + cf->connected = TRUE; + /* The real request will follow the CONNECT, reset request partially */ + Curl_req_soft_reset(&data->req, data); + Curl_client_reset(data); + Curl_pgrsSetUploadCounter(data, 0); + Curl_pgrsSetDownloadCounter(data, 0); + + tunnel_free(cf, data); + } + return result; +} + +static void cf_h1_proxy_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct h1_tunnel_state *ts = cf->ctx; + + if(!cf->connected) { + /* If we are not connected, but the filter "below" is + * and not waiting on something, we are tunneling. */ + curl_socket_t sock = Curl_conn_cf_get_socket(cf, data); + if(ts) { + /* when we've sent a CONNECT to a proxy, we should rather either + wait for the socket to become readable to be able to get the + response headers or if we're still sending the request, wait + for write. */ + if(tunnel_want_send(ts)) + Curl_pollset_set_out_only(data, ps, sock); + else + Curl_pollset_set_in_only(data, ps, sock); + } + else + Curl_pollset_set_out_only(data, ps, sock); + } +} + +static void cf_h1_proxy_destroy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURL_TRC_CF(data, cf, "destroy"); + tunnel_free(cf, data); +} + +static void cf_h1_proxy_close(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURL_TRC_CF(data, cf, "close"); + if(cf) { + cf->connected = FALSE; + if(cf->ctx) { + h1_tunnel_go_state(cf, cf->ctx, H1_TUNNEL_INIT, data); + } + if(cf->next) + cf->next->cft->do_close(cf->next, data); + } +} + + +struct Curl_cftype Curl_cft_h1_proxy = { + "H1-PROXY", + CF_TYPE_IP_CONNECT|CF_TYPE_PROXY, + 0, + cf_h1_proxy_destroy, + cf_h1_proxy_connect, + cf_h1_proxy_close, + Curl_cf_http_proxy_get_host, + cf_h1_proxy_adjust_pollset, + Curl_cf_def_data_pending, + Curl_cf_def_send, + Curl_cf_def_recv, + Curl_cf_def_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + Curl_cf_def_query, +}; + +CURLcode Curl_cf_h1_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data) +{ + struct Curl_cfilter *cf; + CURLcode result; + + (void)data; + result = Curl_cf_create(&cf, &Curl_cft_h1_proxy, NULL); + if(!result) + Curl_conn_cf_insert_after(cf_at, cf); + return result; +} + +#endif /* !CURL_DISABLE_PROXY && ! CURL_DISABLE_HTTP */ diff --git a/third_party/curl/lib/cf-h1-proxy.h b/third_party/curl/lib/cf-h1-proxy.h new file mode 100644 index 0000000..ac5bed0 --- /dev/null +++ b/third_party/curl/lib/cf-h1-proxy.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_H1_PROXY_H +#define HEADER_CURL_H1_PROXY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP) + +CURLcode Curl_cf_h1_proxy_insert_after(struct Curl_cfilter *cf, + struct Curl_easy *data); + +extern struct Curl_cftype Curl_cft_h1_proxy; + + +#endif /* !CURL_DISABLE_PROXY && !CURL_DISABLE_HTTP */ + +#endif /* HEADER_CURL_H1_PROXY_H */ diff --git a/third_party/curl/lib/cf-h2-proxy.c b/third_party/curl/lib/cf-h2-proxy.c new file mode 100644 index 0000000..0bff15f --- /dev/null +++ b/third_party/curl/lib/cf-h2-proxy.c @@ -0,0 +1,1576 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_NGHTTP2) && !defined(CURL_DISABLE_PROXY) + +#include +#include "urldata.h" +#include "cfilters.h" +#include "connect.h" +#include "curl_trc.h" +#include "bufq.h" +#include "dynbuf.h" +#include "dynhds.h" +#include "http1.h" +#include "http2.h" +#include "http_proxy.h" +#include "multiif.h" +#include "sendf.h" +#include "cf-h2-proxy.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#define PROXY_H2_CHUNK_SIZE (16*1024) + +#define PROXY_HTTP2_HUGE_WINDOW_SIZE (100 * 1024 * 1024) +#define H2_TUNNEL_WINDOW_SIZE (10 * 1024 * 1024) + +#define PROXY_H2_NW_RECV_CHUNKS (H2_TUNNEL_WINDOW_SIZE / PROXY_H2_CHUNK_SIZE) +#define PROXY_H2_NW_SEND_CHUNKS 1 + +#define H2_TUNNEL_RECV_CHUNKS (H2_TUNNEL_WINDOW_SIZE / PROXY_H2_CHUNK_SIZE) +#define H2_TUNNEL_SEND_CHUNKS ((128 * 1024) / PROXY_H2_CHUNK_SIZE) + + +typedef enum { + H2_TUNNEL_INIT, /* init/default/no tunnel state */ + H2_TUNNEL_CONNECT, /* CONNECT request is being send */ + H2_TUNNEL_RESPONSE, /* CONNECT response received completely */ + H2_TUNNEL_ESTABLISHED, + H2_TUNNEL_FAILED +} h2_tunnel_state; + +struct tunnel_stream { + struct http_resp *resp; + struct bufq recvbuf; + struct bufq sendbuf; + char *authority; + int32_t stream_id; + uint32_t error; + size_t upload_blocked_len; + h2_tunnel_state state; + BIT(has_final_response); + BIT(closed); + BIT(reset); +}; + +static CURLcode tunnel_stream_init(struct Curl_cfilter *cf, + struct tunnel_stream *ts) +{ + const char *hostname; + int port; + bool ipv6_ip; + CURLcode result; + + ts->state = H2_TUNNEL_INIT; + ts->stream_id = -1; + Curl_bufq_init2(&ts->recvbuf, PROXY_H2_CHUNK_SIZE, H2_TUNNEL_RECV_CHUNKS, + BUFQ_OPT_SOFT_LIMIT); + Curl_bufq_init(&ts->sendbuf, PROXY_H2_CHUNK_SIZE, H2_TUNNEL_SEND_CHUNKS); + + result = Curl_http_proxy_get_destination(cf, &hostname, &port, &ipv6_ip); + if(result) + return result; + + ts->authority = /* host:port with IPv6 support */ + aprintf("%s%s%s:%d", ipv6_ip?"[":"", hostname, ipv6_ip?"]":"", port); + if(!ts->authority) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +static void tunnel_stream_clear(struct tunnel_stream *ts) +{ + Curl_http_resp_free(ts->resp); + Curl_bufq_free(&ts->recvbuf); + Curl_bufq_free(&ts->sendbuf); + Curl_safefree(ts->authority); + memset(ts, 0, sizeof(*ts)); + ts->state = H2_TUNNEL_INIT; +} + +static void h2_tunnel_go_state(struct Curl_cfilter *cf, + struct tunnel_stream *ts, + h2_tunnel_state new_state, + struct Curl_easy *data) +{ + (void)cf; + + if(ts->state == new_state) + return; + /* leaving this one */ + switch(ts->state) { + case H2_TUNNEL_CONNECT: + data->req.ignorebody = FALSE; + break; + default: + break; + } + /* entering this one */ + switch(new_state) { + case H2_TUNNEL_INIT: + CURL_TRC_CF(data, cf, "[%d] new tunnel state 'init'", ts->stream_id); + tunnel_stream_clear(ts); + break; + + case H2_TUNNEL_CONNECT: + CURL_TRC_CF(data, cf, "[%d] new tunnel state 'connect'", ts->stream_id); + ts->state = H2_TUNNEL_CONNECT; + break; + + case H2_TUNNEL_RESPONSE: + CURL_TRC_CF(data, cf, "[%d] new tunnel state 'response'", ts->stream_id); + ts->state = H2_TUNNEL_RESPONSE; + break; + + case H2_TUNNEL_ESTABLISHED: + CURL_TRC_CF(data, cf, "[%d] new tunnel state 'established'", + ts->stream_id); + infof(data, "CONNECT phase completed"); + data->state.authproxy.done = TRUE; + data->state.authproxy.multipass = FALSE; + FALLTHROUGH(); + case H2_TUNNEL_FAILED: + if(new_state == H2_TUNNEL_FAILED) + CURL_TRC_CF(data, cf, "[%d] new tunnel state 'failed'", ts->stream_id); + ts->state = new_state; + /* If a proxy-authorization header was used for the proxy, then we should + make sure that it isn't accidentally used for the document request + after we've connected. So let's free and clear it here. */ + Curl_safefree(data->state.aptr.proxyuserpwd); + break; + } +} + +struct cf_h2_proxy_ctx { + nghttp2_session *h2; + /* The easy handle used in the current filter call, cleared at return */ + struct cf_call_data call_data; + + struct bufq inbufq; /* network receive buffer */ + struct bufq outbufq; /* network send buffer */ + + struct tunnel_stream tunnel; /* our tunnel CONNECT stream */ + int32_t goaway_error; + int32_t last_stream_id; + BIT(conn_closed); + BIT(goaway); + BIT(nw_out_blocked); +}; + +/* How to access `call_data` from a cf_h2 filter */ +#undef CF_CTX_CALL_DATA +#define CF_CTX_CALL_DATA(cf) \ + ((struct cf_h2_proxy_ctx *)(cf)->ctx)->call_data + +static void cf_h2_proxy_ctx_clear(struct cf_h2_proxy_ctx *ctx) +{ + struct cf_call_data save = ctx->call_data; + + if(ctx->h2) { + nghttp2_session_del(ctx->h2); + } + Curl_bufq_free(&ctx->inbufq); + Curl_bufq_free(&ctx->outbufq); + tunnel_stream_clear(&ctx->tunnel); + memset(ctx, 0, sizeof(*ctx)); + ctx->call_data = save; +} + +static void cf_h2_proxy_ctx_free(struct cf_h2_proxy_ctx *ctx) +{ + if(ctx) { + cf_h2_proxy_ctx_clear(ctx); + free(ctx); + } +} + +static void drain_tunnel(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct tunnel_stream *tunnel) +{ + unsigned char bits; + + (void)cf; + bits = CURL_CSELECT_IN; + if(!tunnel->closed && !tunnel->reset && tunnel->upload_blocked_len) + bits |= CURL_CSELECT_OUT; + if(data->state.select_bits != bits) { + CURL_TRC_CF(data, cf, "[%d] DRAIN select_bits=%x", + tunnel->stream_id, bits); + data->state.select_bits = bits; + Curl_expire(data, 0, EXPIRE_RUN_NOW); + } +} + +static ssize_t proxy_nw_in_reader(void *reader_ctx, + unsigned char *buf, size_t buflen, + CURLcode *err) +{ + struct Curl_cfilter *cf = reader_ctx; + ssize_t nread; + + if(cf) { + struct Curl_easy *data = CF_DATA_CURRENT(cf); + nread = Curl_conn_cf_recv(cf->next, data, (char *)buf, buflen, err); + CURL_TRC_CF(data, cf, "[0] nw_in_reader(len=%zu) -> %zd, %d", + buflen, nread, *err); + } + else { + nread = 0; + } + return nread; +} + +static ssize_t proxy_h2_nw_out_writer(void *writer_ctx, + const unsigned char *buf, size_t buflen, + CURLcode *err) +{ + struct Curl_cfilter *cf = writer_ctx; + ssize_t nwritten; + + if(cf) { + struct Curl_easy *data = CF_DATA_CURRENT(cf); + nwritten = Curl_conn_cf_send(cf->next, data, (const char *)buf, buflen, + err); + CURL_TRC_CF(data, cf, "[0] nw_out_writer(len=%zu) -> %zd, %d", + buflen, nwritten, *err); + } + else { + nwritten = 0; + } + return nwritten; +} + +static int proxy_h2_client_new(struct Curl_cfilter *cf, + nghttp2_session_callbacks *cbs) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + nghttp2_option *o; + + int rc = nghttp2_option_new(&o); + if(rc) + return rc; + /* We handle window updates ourself to enforce buffer limits */ + nghttp2_option_set_no_auto_window_update(o, 1); +#if NGHTTP2_VERSION_NUM >= 0x013200 + /* with 1.50.0 */ + /* turn off RFC 9113 leading and trailing white spaces validation against + HTTP field value. */ + nghttp2_option_set_no_rfc9113_leading_and_trailing_ws_validation(o, 1); +#endif + rc = nghttp2_session_client_new2(&ctx->h2, cbs, cf, o); + nghttp2_option_del(o); + return rc; +} + +static ssize_t on_session_send(nghttp2_session *h2, + const uint8_t *buf, size_t blen, + int flags, void *userp); +static int proxy_h2_on_frame_recv(nghttp2_session *session, + const nghttp2_frame *frame, + void *userp); +#ifndef CURL_DISABLE_VERBOSE_STRINGS +static int proxy_h2_on_frame_send(nghttp2_session *session, + const nghttp2_frame *frame, + void *userp); +#endif +static int proxy_h2_on_stream_close(nghttp2_session *session, + int32_t stream_id, + uint32_t error_code, void *userp); +static int proxy_h2_on_header(nghttp2_session *session, + const nghttp2_frame *frame, + const uint8_t *name, size_t namelen, + const uint8_t *value, size_t valuelen, + uint8_t flags, + void *userp); +static int tunnel_recv_callback(nghttp2_session *session, uint8_t flags, + int32_t stream_id, + const uint8_t *mem, size_t len, void *userp); + +/* + * Initialize the cfilter context + */ +static CURLcode cf_h2_proxy_ctx_init(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OUT_OF_MEMORY; + nghttp2_session_callbacks *cbs = NULL; + int rc; + + DEBUGASSERT(!ctx->h2); + memset(&ctx->tunnel, 0, sizeof(ctx->tunnel)); + + Curl_bufq_init(&ctx->inbufq, PROXY_H2_CHUNK_SIZE, PROXY_H2_NW_RECV_CHUNKS); + Curl_bufq_init(&ctx->outbufq, PROXY_H2_CHUNK_SIZE, PROXY_H2_NW_SEND_CHUNKS); + + if(tunnel_stream_init(cf, &ctx->tunnel)) + goto out; + + rc = nghttp2_session_callbacks_new(&cbs); + if(rc) { + failf(data, "Couldn't initialize nghttp2 callbacks"); + goto out; + } + + nghttp2_session_callbacks_set_send_callback(cbs, on_session_send); + nghttp2_session_callbacks_set_on_frame_recv_callback( + cbs, proxy_h2_on_frame_recv); +#ifndef CURL_DISABLE_VERBOSE_STRINGS + nghttp2_session_callbacks_set_on_frame_send_callback(cbs, + proxy_h2_on_frame_send); +#endif + nghttp2_session_callbacks_set_on_data_chunk_recv_callback( + cbs, tunnel_recv_callback); + nghttp2_session_callbacks_set_on_stream_close_callback( + cbs, proxy_h2_on_stream_close); + nghttp2_session_callbacks_set_on_header_callback(cbs, proxy_h2_on_header); + + /* The nghttp2 session is not yet setup, do it */ + rc = proxy_h2_client_new(cf, cbs); + if(rc) { + failf(data, "Couldn't initialize nghttp2"); + goto out; + } + + { + nghttp2_settings_entry iv[3]; + + iv[0].settings_id = NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS; + iv[0].value = Curl_multi_max_concurrent_streams(data->multi); + iv[1].settings_id = NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; + iv[1].value = H2_TUNNEL_WINDOW_SIZE; + iv[2].settings_id = NGHTTP2_SETTINGS_ENABLE_PUSH; + iv[2].value = 0; + rc = nghttp2_submit_settings(ctx->h2, NGHTTP2_FLAG_NONE, iv, 3); + if(rc) { + failf(data, "nghttp2_submit_settings() failed: %s(%d)", + nghttp2_strerror(rc), rc); + result = CURLE_HTTP2; + goto out; + } + } + + rc = nghttp2_session_set_local_window_size(ctx->h2, NGHTTP2_FLAG_NONE, 0, + PROXY_HTTP2_HUGE_WINDOW_SIZE); + if(rc) { + failf(data, "nghttp2_session_set_local_window_size() failed: %s(%d)", + nghttp2_strerror(rc), rc); + result = CURLE_HTTP2; + goto out; + } + + + /* all set, traffic will be send on connect */ + result = CURLE_OK; + +out: + if(cbs) + nghttp2_session_callbacks_del(cbs); + CURL_TRC_CF(data, cf, "[0] init proxy ctx -> %d", result); + return result; +} + +static int proxy_h2_should_close_session(struct cf_h2_proxy_ctx *ctx) +{ + return !nghttp2_session_want_read(ctx->h2) && + !nghttp2_session_want_write(ctx->h2); +} + +static CURLcode proxy_h2_nw_out_flush(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + ssize_t nwritten; + CURLcode result; + + (void)data; + if(Curl_bufq_is_empty(&ctx->outbufq)) + return CURLE_OK; + + nwritten = Curl_bufq_pass(&ctx->outbufq, proxy_h2_nw_out_writer, cf, + &result); + if(nwritten < 0) { + if(result == CURLE_AGAIN) { + CURL_TRC_CF(data, cf, "[0] flush nw send buffer(%zu) -> EAGAIN", + Curl_bufq_len(&ctx->outbufq)); + ctx->nw_out_blocked = 1; + } + return result; + } + CURL_TRC_CF(data, cf, "[0] nw send buffer flushed"); + return Curl_bufq_is_empty(&ctx->outbufq)? CURLE_OK: CURLE_AGAIN; +} + +/* + * Processes pending input left in network input buffer. + * This function returns 0 if it succeeds, or -1 and error code will + * be assigned to *err. + */ +static int proxy_h2_process_pending_input(struct Curl_cfilter *cf, + struct Curl_easy *data, + CURLcode *err) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + const unsigned char *buf; + size_t blen; + ssize_t rv; + + while(Curl_bufq_peek(&ctx->inbufq, &buf, &blen)) { + + rv = nghttp2_session_mem_recv(ctx->h2, (const uint8_t *)buf, blen); + CURL_TRC_CF(data, cf, "[0] %zu bytes to nghttp2 -> %zd", blen, rv); + if(rv < 0) { + failf(data, + "process_pending_input: nghttp2_session_mem_recv() returned " + "%zd:%s", rv, nghttp2_strerror((int)rv)); + *err = CURLE_RECV_ERROR; + return -1; + } + Curl_bufq_skip(&ctx->inbufq, (size_t)rv); + if(Curl_bufq_is_empty(&ctx->inbufq)) { + CURL_TRC_CF(data, cf, "[0] all data in connection buffer processed"); + break; + } + else { + CURL_TRC_CF(data, cf, "[0] process_pending_input: %zu bytes left " + "in connection buffer", Curl_bufq_len(&ctx->inbufq)); + } + } + + return 0; +} + +static CURLcode proxy_h2_progress_ingress(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + ssize_t nread; + + /* Process network input buffer fist */ + if(!Curl_bufq_is_empty(&ctx->inbufq)) { + CURL_TRC_CF(data, cf, "[0] process %zu bytes in connection buffer", + Curl_bufq_len(&ctx->inbufq)); + if(proxy_h2_process_pending_input(cf, data, &result) < 0) + return result; + } + + /* Receive data from the "lower" filters, e.g. network until + * it is time to stop or we have enough data for this stream */ + while(!ctx->conn_closed && /* not closed the connection */ + !ctx->tunnel.closed && /* nor the tunnel */ + Curl_bufq_is_empty(&ctx->inbufq) && /* and we consumed our input */ + !Curl_bufq_is_full(&ctx->tunnel.recvbuf)) { + + nread = Curl_bufq_slurp(&ctx->inbufq, proxy_nw_in_reader, cf, &result); + CURL_TRC_CF(data, cf, "[0] read %zu bytes nw data -> %zd, %d", + Curl_bufq_len(&ctx->inbufq), nread, result); + if(nread < 0) { + if(result != CURLE_AGAIN) { + failf(data, "Failed receiving HTTP2 data"); + return result; + } + break; + } + else if(nread == 0) { + ctx->conn_closed = TRUE; + break; + } + + if(proxy_h2_process_pending_input(cf, data, &result)) + return result; + } + + if(ctx->conn_closed && Curl_bufq_is_empty(&ctx->inbufq)) { + connclose(cf->conn, "GOAWAY received"); + } + + return CURLE_OK; +} + +static CURLcode proxy_h2_progress_egress(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + int rv = 0; + + ctx->nw_out_blocked = 0; + while(!rv && !ctx->nw_out_blocked && nghttp2_session_want_write(ctx->h2)) + rv = nghttp2_session_send(ctx->h2); + + if(nghttp2_is_fatal(rv)) { + CURL_TRC_CF(data, cf, "[0] nghttp2_session_send error (%s)%d", + nghttp2_strerror(rv), rv); + return CURLE_SEND_ERROR; + } + return proxy_h2_nw_out_flush(cf, data); +} + +static ssize_t on_session_send(nghttp2_session *h2, + const uint8_t *buf, size_t blen, int flags, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_proxy_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + ssize_t nwritten; + CURLcode result = CURLE_OK; + + (void)h2; + (void)flags; + DEBUGASSERT(data); + + nwritten = Curl_bufq_write_pass(&ctx->outbufq, buf, blen, + proxy_h2_nw_out_writer, cf, &result); + if(nwritten < 0) { + if(result == CURLE_AGAIN) { + return NGHTTP2_ERR_WOULDBLOCK; + } + failf(data, "Failed sending HTTP2 data"); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + + if(!nwritten) + return NGHTTP2_ERR_WOULDBLOCK; + + return nwritten; +} + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +static int proxy_h2_fr_print(const nghttp2_frame *frame, + char *buffer, size_t blen) +{ + switch(frame->hd.type) { + case NGHTTP2_DATA: { + return msnprintf(buffer, blen, + "FRAME[DATA, len=%d, eos=%d, padlen=%d]", + (int)frame->hd.length, + !!(frame->hd.flags & NGHTTP2_FLAG_END_STREAM), + (int)frame->data.padlen); + } + case NGHTTP2_HEADERS: { + return msnprintf(buffer, blen, + "FRAME[HEADERS, len=%d, hend=%d, eos=%d]", + (int)frame->hd.length, + !!(frame->hd.flags & NGHTTP2_FLAG_END_HEADERS), + !!(frame->hd.flags & NGHTTP2_FLAG_END_STREAM)); + } + case NGHTTP2_PRIORITY: { + return msnprintf(buffer, blen, + "FRAME[PRIORITY, len=%d, flags=%d]", + (int)frame->hd.length, frame->hd.flags); + } + case NGHTTP2_RST_STREAM: { + return msnprintf(buffer, blen, + "FRAME[RST_STREAM, len=%d, flags=%d, error=%u]", + (int)frame->hd.length, frame->hd.flags, + frame->rst_stream.error_code); + } + case NGHTTP2_SETTINGS: { + if(frame->hd.flags & NGHTTP2_FLAG_ACK) { + return msnprintf(buffer, blen, "FRAME[SETTINGS, ack=1]"); + } + return msnprintf(buffer, blen, + "FRAME[SETTINGS, len=%d]", (int)frame->hd.length); + } + case NGHTTP2_PUSH_PROMISE: { + return msnprintf(buffer, blen, + "FRAME[PUSH_PROMISE, len=%d, hend=%d]", + (int)frame->hd.length, + !!(frame->hd.flags & NGHTTP2_FLAG_END_HEADERS)); + } + case NGHTTP2_PING: { + return msnprintf(buffer, blen, + "FRAME[PING, len=%d, ack=%d]", + (int)frame->hd.length, + frame->hd.flags&NGHTTP2_FLAG_ACK); + } + case NGHTTP2_GOAWAY: { + char scratch[128]; + size_t s_len = sizeof(scratch)/sizeof(scratch[0]); + size_t len = (frame->goaway.opaque_data_len < s_len)? + frame->goaway.opaque_data_len : s_len-1; + if(len) + memcpy(scratch, frame->goaway.opaque_data, len); + scratch[len] = '\0'; + return msnprintf(buffer, blen, "FRAME[GOAWAY, error=%d, reason='%s', " + "last_stream=%d]", frame->goaway.error_code, + scratch, frame->goaway.last_stream_id); + } + case NGHTTP2_WINDOW_UPDATE: { + return msnprintf(buffer, blen, + "FRAME[WINDOW_UPDATE, incr=%d]", + frame->window_update.window_size_increment); + } + default: + return msnprintf(buffer, blen, "FRAME[%d, len=%d, flags=%d]", + frame->hd.type, (int)frame->hd.length, + frame->hd.flags); + } +} + +static int proxy_h2_on_frame_send(nghttp2_session *session, + const nghttp2_frame *frame, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + + (void)session; + DEBUGASSERT(data); + if(data && Curl_trc_cf_is_verbose(cf, data)) { + char buffer[256]; + int len; + len = proxy_h2_fr_print(frame, buffer, sizeof(buffer)-1); + buffer[len] = 0; + CURL_TRC_CF(data, cf, "[%d] -> %s", frame->hd.stream_id, buffer); + } + return 0; +} +#endif /* !CURL_DISABLE_VERBOSE_STRINGS */ + +static int proxy_h2_on_frame_recv(nghttp2_session *session, + const nghttp2_frame *frame, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_proxy_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + int32_t stream_id = frame->hd.stream_id; + + (void)session; + DEBUGASSERT(data); +#ifndef CURL_DISABLE_VERBOSE_STRINGS + if(Curl_trc_cf_is_verbose(cf, data)) { + char buffer[256]; + int len; + len = proxy_h2_fr_print(frame, buffer, sizeof(buffer)-1); + buffer[len] = 0; + CURL_TRC_CF(data, cf, "[%d] <- %s",frame->hd.stream_id, buffer); + } +#endif /* !CURL_DISABLE_VERBOSE_STRINGS */ + + if(!stream_id) { + /* stream ID zero is for connection-oriented stuff */ + DEBUGASSERT(data); + switch(frame->hd.type) { + case NGHTTP2_SETTINGS: + /* Since the initial stream window is 64K, a request might be on HOLD, + * due to exhaustion. The (initial) SETTINGS may announce a much larger + * window and *assume* that we treat this like a WINDOW_UPDATE. Some + * servers send an explicit WINDOW_UPDATE, but not all seem to do that. + * To be safe, we UNHOLD a stream in order not to stall. */ + if(CURL_WANT_SEND(data)) { + drain_tunnel(cf, data, &ctx->tunnel); + } + break; + case NGHTTP2_GOAWAY: + ctx->goaway = TRUE; + break; + default: + break; + } + return 0; + } + + if(stream_id != ctx->tunnel.stream_id) { + CURL_TRC_CF(data, cf, "[%d] rcvd FRAME not for tunnel", stream_id); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + + switch(frame->hd.type) { + case NGHTTP2_HEADERS: + /* nghttp2 guarantees that :status is received, and we store it to + stream->status_code. Fuzzing has proven this can still be reached + without status code having been set. */ + if(!ctx->tunnel.resp) + return NGHTTP2_ERR_CALLBACK_FAILURE; + /* Only final status code signals the end of header */ + CURL_TRC_CF(data, cf, "[%d] got http status: %d", + stream_id, ctx->tunnel.resp->status); + if(!ctx->tunnel.has_final_response) { + if(ctx->tunnel.resp->status / 100 != 1) { + ctx->tunnel.has_final_response = TRUE; + } + } + break; + case NGHTTP2_WINDOW_UPDATE: + if(CURL_WANT_SEND(data)) { + drain_tunnel(cf, data, &ctx->tunnel); + } + break; + default: + break; + } + return 0; +} + +static int proxy_h2_on_header(nghttp2_session *session, + const nghttp2_frame *frame, + const uint8_t *name, size_t namelen, + const uint8_t *value, size_t valuelen, + uint8_t flags, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_proxy_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + int32_t stream_id = frame->hd.stream_id; + CURLcode result; + + (void)flags; + (void)data; + (void)session; + DEBUGASSERT(stream_id); /* should never be a zero stream ID here */ + if(stream_id != ctx->tunnel.stream_id) { + CURL_TRC_CF(data, cf, "[%d] header for non-tunnel stream: " + "%.*s: %.*s", stream_id, + (int)namelen, name, (int)valuelen, value); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + + if(frame->hd.type == NGHTTP2_PUSH_PROMISE) + return NGHTTP2_ERR_CALLBACK_FAILURE; + + if(ctx->tunnel.has_final_response) { + /* we do not do anything with trailers for tunnel streams */ + return 0; + } + + if(namelen == sizeof(HTTP_PSEUDO_STATUS) - 1 && + memcmp(HTTP_PSEUDO_STATUS, name, namelen) == 0) { + int http_status; + struct http_resp *resp; + + /* status: always comes first, we might get more than one response, + * link the previous ones for keepers */ + result = Curl_http_decode_status(&http_status, + (const char *)value, valuelen); + if(result) + return NGHTTP2_ERR_CALLBACK_FAILURE; + result = Curl_http_resp_make(&resp, http_status, NULL); + if(result) + return NGHTTP2_ERR_CALLBACK_FAILURE; + resp->prev = ctx->tunnel.resp; + ctx->tunnel.resp = resp; + CURL_TRC_CF(data, cf, "[%d] status: HTTP/2 %03d", + stream_id, ctx->tunnel.resp->status); + return 0; + } + + if(!ctx->tunnel.resp) + return NGHTTP2_ERR_CALLBACK_FAILURE; + + result = Curl_dynhds_add(&ctx->tunnel.resp->headers, + (const char *)name, namelen, + (const char *)value, valuelen); + if(result) + return NGHTTP2_ERR_CALLBACK_FAILURE; + + CURL_TRC_CF(data, cf, "[%d] header: %.*s: %.*s", + stream_id, (int)namelen, name, (int)valuelen, value); + + return 0; /* 0 is successful */ +} + +static ssize_t tunnel_send_callback(nghttp2_session *session, + int32_t stream_id, + uint8_t *buf, size_t length, + uint32_t *data_flags, + nghttp2_data_source *source, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_proxy_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + struct tunnel_stream *ts; + CURLcode result; + ssize_t nread; + + (void)source; + (void)data; + (void)ctx; + + if(!stream_id) + return NGHTTP2_ERR_INVALID_ARGUMENT; + + ts = nghttp2_session_get_stream_user_data(session, stream_id); + if(!ts) + return NGHTTP2_ERR_CALLBACK_FAILURE; + DEBUGASSERT(ts == &ctx->tunnel); + + nread = Curl_bufq_read(&ts->sendbuf, buf, length, &result); + if(nread < 0) { + if(result != CURLE_AGAIN) + return NGHTTP2_ERR_CALLBACK_FAILURE; + return NGHTTP2_ERR_DEFERRED; + } + if(ts->closed && Curl_bufq_is_empty(&ts->sendbuf)) + *data_flags = NGHTTP2_DATA_FLAG_EOF; + + CURL_TRC_CF(data, cf, "[%d] tunnel_send_callback -> %zd", + ts->stream_id, nread); + return nread; +} + +static int tunnel_recv_callback(nghttp2_session *session, uint8_t flags, + int32_t stream_id, + const uint8_t *mem, size_t len, void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_proxy_ctx *ctx = cf->ctx; + ssize_t nwritten; + CURLcode result; + + (void)flags; + (void)session; + DEBUGASSERT(stream_id); /* should never be a zero stream ID here */ + + if(stream_id != ctx->tunnel.stream_id) + return NGHTTP2_ERR_CALLBACK_FAILURE; + + nwritten = Curl_bufq_write(&ctx->tunnel.recvbuf, mem, len, &result); + if(nwritten < 0) { + if(result != CURLE_AGAIN) + return NGHTTP2_ERR_CALLBACK_FAILURE; + nwritten = 0; + } + DEBUGASSERT((size_t)nwritten == len); + return 0; +} + +static int proxy_h2_on_stream_close(nghttp2_session *session, + int32_t stream_id, + uint32_t error_code, void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_proxy_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + + (void)session; + (void)data; + + if(stream_id != ctx->tunnel.stream_id) + return 0; + + CURL_TRC_CF(data, cf, "[%d] proxy_h2_on_stream_close, %s (err %d)", + stream_id, nghttp2_http2_strerror(error_code), error_code); + ctx->tunnel.closed = TRUE; + ctx->tunnel.error = error_code; + + return 0; +} + +static CURLcode proxy_h2_submit(int32_t *pstream_id, + struct Curl_cfilter *cf, + struct Curl_easy *data, + nghttp2_session *h2, + struct httpreq *req, + const nghttp2_priority_spec *pri_spec, + void *stream_user_data, + nghttp2_data_source_read_callback read_callback, + void *read_ctx) +{ + struct dynhds h2_headers; + nghttp2_nv *nva = NULL; + int32_t stream_id = -1; + size_t nheader; + CURLcode result; + + (void)cf; + Curl_dynhds_init(&h2_headers, 0, DYN_HTTP_REQUEST); + result = Curl_http_req_to_h2(&h2_headers, req, data); + if(result) + goto out; + + nva = Curl_dynhds_to_nva(&h2_headers, &nheader); + if(!nva) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + if(read_callback) { + nghttp2_data_provider data_prd; + + data_prd.read_callback = read_callback; + data_prd.source.ptr = read_ctx; + stream_id = nghttp2_submit_request(h2, pri_spec, nva, nheader, + &data_prd, stream_user_data); + } + else { + stream_id = nghttp2_submit_request(h2, pri_spec, nva, nheader, + NULL, stream_user_data); + } + + if(stream_id < 0) { + failf(data, "nghttp2_session_upgrade2() failed: %s(%d)", + nghttp2_strerror(stream_id), stream_id); + result = CURLE_SEND_ERROR; + goto out; + } + result = CURLE_OK; + +out: + free(nva); + Curl_dynhds_free(&h2_headers); + *pstream_id = stream_id; + return result; +} + +static CURLcode submit_CONNECT(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct tunnel_stream *ts) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + CURLcode result; + struct httpreq *req = NULL; + + result = Curl_http_proxy_create_CONNECT(&req, cf, data, 2); + if(result) + goto out; + result = Curl_creader_set_null(data); + if(result) + goto out; + + infof(data, "Establish HTTP/2 proxy tunnel to %s", req->authority); + + result = proxy_h2_submit(&ts->stream_id, cf, data, ctx->h2, req, + NULL, ts, tunnel_send_callback, cf); + if(result) { + CURL_TRC_CF(data, cf, "[%d] send, nghttp2_submit_request error: %s", + ts->stream_id, nghttp2_strerror(ts->stream_id)); + } + +out: + if(req) + Curl_http_req_free(req); + if(result) + failf(data, "Failed sending CONNECT to proxy"); + return result; +} + +static CURLcode inspect_response(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct tunnel_stream *ts) +{ + CURLcode result = CURLE_OK; + struct dynhds_entry *auth_reply = NULL; + (void)cf; + + DEBUGASSERT(ts->resp); + if(ts->resp->status/100 == 2) { + infof(data, "CONNECT tunnel established, response %d", ts->resp->status); + h2_tunnel_go_state(cf, ts, H2_TUNNEL_ESTABLISHED, data); + return CURLE_OK; + } + + if(ts->resp->status == 401) { + auth_reply = Curl_dynhds_cget(&ts->resp->headers, "WWW-Authenticate"); + } + else if(ts->resp->status == 407) { + auth_reply = Curl_dynhds_cget(&ts->resp->headers, "Proxy-Authenticate"); + } + + if(auth_reply) { + CURL_TRC_CF(data, cf, "[0] CONNECT: fwd auth header '%s'", + auth_reply->value); + result = Curl_http_input_auth(data, ts->resp->status == 407, + auth_reply->value); + if(result) + return result; + if(data->req.newurl) { + /* Indicator that we should try again */ + Curl_safefree(data->req.newurl); + h2_tunnel_go_state(cf, ts, H2_TUNNEL_INIT, data); + return CURLE_OK; + } + } + + /* Seems to have failed */ + return CURLE_RECV_ERROR; +} + +static CURLcode H2_CONNECT(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct tunnel_stream *ts) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + DEBUGASSERT(ts); + DEBUGASSERT(ts->authority); + do { + switch(ts->state) { + case H2_TUNNEL_INIT: + /* Prepare the CONNECT request and make a first attempt to send. */ + CURL_TRC_CF(data, cf, "[0] CONNECT start for %s", ts->authority); + result = submit_CONNECT(cf, data, ts); + if(result) + goto out; + h2_tunnel_go_state(cf, ts, H2_TUNNEL_CONNECT, data); + FALLTHROUGH(); + + case H2_TUNNEL_CONNECT: + /* see that the request is completely sent */ + result = proxy_h2_progress_ingress(cf, data); + if(!result) + result = proxy_h2_progress_egress(cf, data); + if(result && result != CURLE_AGAIN) { + h2_tunnel_go_state(cf, ts, H2_TUNNEL_FAILED, data); + break; + } + + if(ts->has_final_response) { + h2_tunnel_go_state(cf, ts, H2_TUNNEL_RESPONSE, data); + } + else { + result = CURLE_OK; + goto out; + } + FALLTHROUGH(); + + case H2_TUNNEL_RESPONSE: + DEBUGASSERT(ts->has_final_response); + result = inspect_response(cf, data, ts); + if(result) + goto out; + break; + + case H2_TUNNEL_ESTABLISHED: + return CURLE_OK; + + case H2_TUNNEL_FAILED: + return CURLE_RECV_ERROR; + + default: + break; + } + + } while(ts->state == H2_TUNNEL_INIT); + +out: + if(result || ctx->tunnel.closed) + h2_tunnel_go_state(cf, ts, H2_TUNNEL_FAILED, data); + return result; +} + +static CURLcode cf_h2_proxy_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + struct cf_call_data save; + timediff_t check; + struct tunnel_stream *ts = &ctx->tunnel; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + /* Connect the lower filters first */ + if(!cf->next->connected) { + result = Curl_conn_cf_connect(cf->next, data, blocking, done); + if(result || !*done) + return result; + } + + *done = FALSE; + + CF_DATA_SAVE(save, cf, data); + if(!ctx->h2) { + result = cf_h2_proxy_ctx_init(cf, data); + if(result) + goto out; + } + DEBUGASSERT(ts->authority); + + check = Curl_timeleft(data, NULL, TRUE); + if(check <= 0) { + failf(data, "Proxy CONNECT aborted due to timeout"); + result = CURLE_OPERATION_TIMEDOUT; + goto out; + } + + /* for the secondary socket (FTP), use the "connect to host" + * but ignore the "connect to port" (use the secondary port) + */ + result = H2_CONNECT(cf, data, ts); + +out: + *done = (result == CURLE_OK) && (ts->state == H2_TUNNEL_ESTABLISHED); + if(*done) { + cf->connected = TRUE; + /* The real request will follow the CONNECT, reset request partially */ + Curl_req_soft_reset(&data->req, data); + Curl_client_reset(data); + } + CF_DATA_RESTORE(cf, save); + return result; +} + +static void cf_h2_proxy_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + + if(ctx) { + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + cf_h2_proxy_ctx_clear(ctx); + CF_DATA_RESTORE(cf, save); + } + if(cf->next) + cf->next->cft->do_close(cf->next, data); +} + +static void cf_h2_proxy_destroy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + + (void)data; + if(ctx) { + cf_h2_proxy_ctx_free(ctx); + cf->ctx = NULL; + } +} + +static bool cf_h2_proxy_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + if((ctx && !Curl_bufq_is_empty(&ctx->inbufq)) || + (ctx && ctx->tunnel.state == H2_TUNNEL_ESTABLISHED && + !Curl_bufq_is_empty(&ctx->tunnel.recvbuf))) + return TRUE; + return cf->next? cf->next->cft->has_data_pending(cf->next, data) : FALSE; +} + +static void cf_h2_proxy_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + curl_socket_t sock = Curl_conn_cf_get_socket(cf, data); + bool want_recv, want_send; + + Curl_pollset_check(data, ps, sock, &want_recv, &want_send); + if(ctx->h2 && (want_recv || want_send)) { + struct cf_call_data save; + bool c_exhaust, s_exhaust; + + CF_DATA_SAVE(save, cf, data); + c_exhaust = !nghttp2_session_get_remote_window_size(ctx->h2); + s_exhaust = ctx->tunnel.stream_id >= 0 && + !nghttp2_session_get_stream_remote_window_size( + ctx->h2, ctx->tunnel.stream_id); + want_recv = (want_recv || c_exhaust || s_exhaust); + want_send = (!s_exhaust && want_send) || + (!c_exhaust && nghttp2_session_want_write(ctx->h2)); + + Curl_pollset_set(data, ps, sock, want_recv, want_send); + CF_DATA_RESTORE(cf, save); + } +} + +static ssize_t h2_handle_tunnel_close(struct Curl_cfilter *cf, + struct Curl_easy *data, + CURLcode *err) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + ssize_t rv = 0; + + if(ctx->tunnel.error == NGHTTP2_REFUSED_STREAM) { + CURL_TRC_CF(data, cf, "[%d] REFUSED_STREAM, try again on a new " + "connection", ctx->tunnel.stream_id); + connclose(cf->conn, "REFUSED_STREAM"); /* don't use this anymore */ + *err = CURLE_RECV_ERROR; /* trigger Curl_retry_request() later */ + return -1; + } + else if(ctx->tunnel.error != NGHTTP2_NO_ERROR) { + failf(data, "HTTP/2 stream %u was not closed cleanly: %s (err %u)", + ctx->tunnel.stream_id, nghttp2_http2_strerror(ctx->tunnel.error), + ctx->tunnel.error); + *err = CURLE_HTTP2_STREAM; + return -1; + } + else if(ctx->tunnel.reset) { + failf(data, "HTTP/2 stream %u was reset", ctx->tunnel.stream_id); + *err = CURLE_RECV_ERROR; + return -1; + } + + *err = CURLE_OK; + rv = 0; + CURL_TRC_CF(data, cf, "[%d] handle_tunnel_close -> %zd, %d", + ctx->tunnel.stream_id, rv, *err); + return rv; +} + +static ssize_t tunnel_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, CURLcode *err) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + ssize_t nread = -1; + + *err = CURLE_AGAIN; + if(!Curl_bufq_is_empty(&ctx->tunnel.recvbuf)) { + nread = Curl_bufq_read(&ctx->tunnel.recvbuf, + (unsigned char *)buf, len, err); + if(nread < 0) + goto out; + DEBUGASSERT(nread > 0); + } + + if(nread < 0) { + if(ctx->tunnel.closed) { + nread = h2_handle_tunnel_close(cf, data, err); + } + else if(ctx->tunnel.reset || + (ctx->conn_closed && Curl_bufq_is_empty(&ctx->inbufq)) || + (ctx->goaway && ctx->last_stream_id < ctx->tunnel.stream_id)) { + *err = CURLE_RECV_ERROR; + nread = -1; + } + } + else if(nread == 0) { + *err = CURLE_AGAIN; + nread = -1; + } + +out: + CURL_TRC_CF(data, cf, "[%d] tunnel_recv(len=%zu) -> %zd, %d", + ctx->tunnel.stream_id, len, nread, *err); + return nread; +} + +static ssize_t cf_h2_proxy_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, + char *buf, size_t len, CURLcode *err) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + ssize_t nread = -1; + struct cf_call_data save; + CURLcode result; + + if(ctx->tunnel.state != H2_TUNNEL_ESTABLISHED) { + *err = CURLE_RECV_ERROR; + return -1; + } + CF_DATA_SAVE(save, cf, data); + + if(Curl_bufq_is_empty(&ctx->tunnel.recvbuf)) { + *err = proxy_h2_progress_ingress(cf, data); + if(*err) + goto out; + } + + nread = tunnel_recv(cf, data, buf, len, err); + + if(nread > 0) { + CURL_TRC_CF(data, cf, "[%d] increase window by %zd", + ctx->tunnel.stream_id, nread); + nghttp2_session_consume(ctx->h2, ctx->tunnel.stream_id, (size_t)nread); + } + + result = proxy_h2_progress_egress(cf, data); + if(result == CURLE_AGAIN) { + /* pending data to send, need to be called again. Ideally, we'd + * monitor the socket for POLLOUT, but we might not be in SENDING + * transfer state any longer and are unable to make this happen. + */ + CURL_TRC_CF(data, cf, "[%d] egress blocked, DRAIN", + ctx->tunnel.stream_id); + drain_tunnel(cf, data, &ctx->tunnel); + } + else if(result) { + *err = result; + nread = -1; + } + +out: + if(!Curl_bufq_is_empty(&ctx->tunnel.recvbuf) && + (nread >= 0 || *err == CURLE_AGAIN)) { + /* data pending and no fatal error to report. Need to trigger + * draining to avoid stalling when no socket events happen. */ + drain_tunnel(cf, data, &ctx->tunnel); + } + CURL_TRC_CF(data, cf, "[%d] cf_recv(len=%zu) -> %zd %d", + ctx->tunnel.stream_id, len, nread, *err); + CF_DATA_RESTORE(cf, save); + return nread; +} + +static ssize_t cf_h2_proxy_send(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *buf, size_t len, CURLcode *err) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + struct cf_call_data save; + int rv; + ssize_t nwritten; + CURLcode result; + int blocked = 0; + + if(ctx->tunnel.state != H2_TUNNEL_ESTABLISHED) { + *err = CURLE_SEND_ERROR; + return -1; + } + CF_DATA_SAVE(save, cf, data); + + if(ctx->tunnel.closed) { + nwritten = -1; + *err = CURLE_SEND_ERROR; + goto out; + } + else if(ctx->tunnel.upload_blocked_len) { + /* the data in `buf` has already been submitted or added to the + * buffers, but have been EAGAINed on the last invocation. */ + DEBUGASSERT(len >= ctx->tunnel.upload_blocked_len); + if(len < ctx->tunnel.upload_blocked_len) { + /* Did we get called again with a smaller `len`? This should not + * happen. We are not prepared to handle that. */ + failf(data, "HTTP/2 proxy, send again with decreased length"); + *err = CURLE_HTTP2; + nwritten = -1; + goto out; + } + nwritten = (ssize_t)ctx->tunnel.upload_blocked_len; + ctx->tunnel.upload_blocked_len = 0; + *err = CURLE_OK; + } + else { + nwritten = Curl_bufq_write(&ctx->tunnel.sendbuf, buf, len, err); + if(nwritten < 0) { + if(*err != CURLE_AGAIN) + goto out; + nwritten = 0; + } + } + + if(!Curl_bufq_is_empty(&ctx->tunnel.sendbuf)) { + /* req body data is buffered, resume the potentially suspended stream */ + rv = nghttp2_session_resume_data(ctx->h2, ctx->tunnel.stream_id); + if(nghttp2_is_fatal(rv)) { + *err = CURLE_SEND_ERROR; + nwritten = -1; + goto out; + } + } + + result = proxy_h2_progress_ingress(cf, data); + if(result) { + *err = result; + nwritten = -1; + goto out; + } + + /* Call the nghttp2 send loop and flush to write ALL buffered data, + * headers and/or request body completely out to the network */ + result = proxy_h2_progress_egress(cf, data); + if(result == CURLE_AGAIN) { + blocked = 1; + } + else if(result) { + *err = result; + nwritten = -1; + goto out; + } + else if(!Curl_bufq_is_empty(&ctx->tunnel.sendbuf)) { + /* although we wrote everything that nghttp2 wants to send now, + * there is data left in our stream send buffer unwritten. This may + * be due to the stream's HTTP/2 flow window being exhausted. */ + blocked = 1; + } + + if(blocked) { + /* Unable to send all data, due to connection blocked or H2 window + * exhaustion. Data is left in our stream buffer, or nghttp2's internal + * frame buffer or our network out buffer. */ + size_t rwin = nghttp2_session_get_stream_remote_window_size( + ctx->h2, ctx->tunnel.stream_id); + if(rwin == 0) { + /* H2 flow window exhaustion. + * FIXME: there is no way to HOLD all transfers that use this + * proxy connection AND to UNHOLD all of them again when the + * window increases. + * We *could* iterate over all data on this conn maybe? */ + CURL_TRC_CF(data, cf, "[%d] remote flow " + "window is exhausted", ctx->tunnel.stream_id); + } + + /* Whatever the cause, we need to return CURL_EAGAIN for this call. + * We have unwritten state that needs us being invoked again and EAGAIN + * is the only way to ensure that. */ + ctx->tunnel.upload_blocked_len = nwritten; + CURL_TRC_CF(data, cf, "[%d] cf_send(len=%zu) BLOCK: win %u/%zu " + "blocked_len=%zu", + ctx->tunnel.stream_id, len, + nghttp2_session_get_remote_window_size(ctx->h2), rwin, + nwritten); + drain_tunnel(cf, data, &ctx->tunnel); + *err = CURLE_AGAIN; + nwritten = -1; + goto out; + } + else if(proxy_h2_should_close_session(ctx)) { + /* nghttp2 thinks this session is done. If the stream has not been + * closed, this is an error state for out transfer */ + if(ctx->tunnel.closed) { + *err = CURLE_SEND_ERROR; + nwritten = -1; + } + else { + CURL_TRC_CF(data, cf, "[0] send: nothing to do in this session"); + *err = CURLE_HTTP2; + nwritten = -1; + } + } + +out: + if(!Curl_bufq_is_empty(&ctx->tunnel.recvbuf) && + (nwritten >= 0 || *err == CURLE_AGAIN)) { + /* data pending and no fatal error to report. Need to trigger + * draining to avoid stalling when no socket events happen. */ + drain_tunnel(cf, data, &ctx->tunnel); + } + CURL_TRC_CF(data, cf, "[%d] cf_send(len=%zu) -> %zd, %d, " + "h2 windows %d-%d (stream-conn), buffers %zu-%zu (stream-conn)", + ctx->tunnel.stream_id, len, nwritten, *err, + nghttp2_session_get_stream_remote_window_size( + ctx->h2, ctx->tunnel.stream_id), + nghttp2_session_get_remote_window_size(ctx->h2), + Curl_bufq_len(&ctx->tunnel.sendbuf), + Curl_bufq_len(&ctx->outbufq)); + CF_DATA_RESTORE(cf, save); + return nwritten; +} + +static bool proxy_h2_connisalive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + bool alive = TRUE; + + *input_pending = FALSE; + if(!cf->next || !cf->next->cft->is_alive(cf->next, data, input_pending)) + return FALSE; + + if(*input_pending) { + /* This happens before we've sent off a request and the connection is + not in use by any other transfer, there shouldn't be any data here, + only "protocol frames" */ + CURLcode result; + ssize_t nread = -1; + + *input_pending = FALSE; + nread = Curl_bufq_slurp(&ctx->inbufq, proxy_nw_in_reader, cf, &result); + if(nread != -1) { + if(proxy_h2_process_pending_input(cf, data, &result) < 0) + /* immediate error, considered dead */ + alive = FALSE; + else { + alive = !proxy_h2_should_close_session(ctx); + } + } + else if(result != CURLE_AGAIN) { + /* the read failed so let's say this is dead anyway */ + alive = FALSE; + } + } + + return alive; +} + +static bool cf_h2_proxy_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + CURLcode result; + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + result = (ctx && ctx->h2 && proxy_h2_connisalive(cf, data, input_pending)); + CURL_TRC_CF(data, cf, "[0] conn alive -> %d, input_pending=%d", + result, *input_pending); + CF_DATA_RESTORE(cf, save); + return result; +} + +struct Curl_cftype Curl_cft_h2_proxy = { + "H2-PROXY", + CF_TYPE_IP_CONNECT|CF_TYPE_PROXY, + CURL_LOG_LVL_NONE, + cf_h2_proxy_destroy, + cf_h2_proxy_connect, + cf_h2_proxy_close, + Curl_cf_http_proxy_get_host, + cf_h2_proxy_adjust_pollset, + cf_h2_proxy_data_pending, + cf_h2_proxy_send, + cf_h2_proxy_recv, + Curl_cf_def_cntrl, + cf_h2_proxy_is_alive, + Curl_cf_def_conn_keep_alive, + Curl_cf_def_query, +}; + +CURLcode Curl_cf_h2_proxy_insert_after(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct Curl_cfilter *cf_h2_proxy = NULL; + struct cf_h2_proxy_ctx *ctx; + CURLcode result = CURLE_OUT_OF_MEMORY; + + (void)data; + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) + goto out; + + result = Curl_cf_create(&cf_h2_proxy, &Curl_cft_h2_proxy, ctx); + if(result) + goto out; + + Curl_conn_cf_insert_after(cf, cf_h2_proxy); + result = CURLE_OK; + +out: + if(result) + cf_h2_proxy_ctx_free(ctx); + return result; +} + +#endif /* defined(USE_NGHTTP2) && !defined(CURL_DISABLE_PROXY) */ diff --git a/third_party/curl/lib/cf-h2-proxy.h b/third_party/curl/lib/cf-h2-proxy.h new file mode 100644 index 0000000..c01bf62 --- /dev/null +++ b/third_party/curl/lib/cf-h2-proxy.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_H2_PROXY_H +#define HEADER_CURL_H2_PROXY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_NGHTTP2) && !defined(CURL_DISABLE_PROXY) + +CURLcode Curl_cf_h2_proxy_insert_after(struct Curl_cfilter *cf, + struct Curl_easy *data); + +extern struct Curl_cftype Curl_cft_h2_proxy; + + +#endif /* defined(USE_NGHTTP2) && !defined(CURL_DISABLE_PROXY) */ + +#endif /* HEADER_CURL_H2_PROXY_H */ diff --git a/third_party/curl/lib/cf-haproxy.c b/third_party/curl/lib/cf-haproxy.c new file mode 100644 index 0000000..2abc4d7 --- /dev/null +++ b/third_party/curl/lib/cf-haproxy.c @@ -0,0 +1,250 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_PROXY) + +#include +#include "urldata.h" +#include "cfilters.h" +#include "cf-haproxy.h" +#include "curl_trc.h" +#include "multiif.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +typedef enum { + HAPROXY_INIT, /* init/default/no tunnel state */ + HAPROXY_SEND, /* data_out being sent */ + HAPROXY_DONE /* all work done */ +} haproxy_state; + +struct cf_haproxy_ctx { + int state; + struct dynbuf data_out; +}; + +static void cf_haproxy_ctx_reset(struct cf_haproxy_ctx *ctx) +{ + DEBUGASSERT(ctx); + ctx->state = HAPROXY_INIT; + Curl_dyn_reset(&ctx->data_out); +} + +static void cf_haproxy_ctx_free(struct cf_haproxy_ctx *ctx) +{ + if(ctx) { + Curl_dyn_free(&ctx->data_out); + free(ctx); + } +} + +static CURLcode cf_haproxy_date_out_set(struct Curl_cfilter*cf, + struct Curl_easy *data) +{ + struct cf_haproxy_ctx *ctx = cf->ctx; + CURLcode result; + const char *tcp_version; + const char *client_ip; + + DEBUGASSERT(ctx); + DEBUGASSERT(ctx->state == HAPROXY_INIT); +#ifdef USE_UNIX_SOCKETS + if(cf->conn->unix_domain_socket) + /* the buffer is large enough to hold this! */ + result = Curl_dyn_addn(&ctx->data_out, STRCONST("PROXY UNKNOWN\r\n")); + else { +#endif /* USE_UNIX_SOCKETS */ + /* Emit the correct prefix for IPv6 */ + tcp_version = cf->conn->bits.ipv6 ? "TCP6" : "TCP4"; + if(data->set.str[STRING_HAPROXY_CLIENT_IP]) + client_ip = data->set.str[STRING_HAPROXY_CLIENT_IP]; + else + client_ip = data->info.primary.local_ip; + + result = Curl_dyn_addf(&ctx->data_out, "PROXY %s %s %s %i %i\r\n", + tcp_version, + client_ip, + data->info.primary.remote_ip, + data->info.primary.local_port, + data->info.primary.remote_port); + +#ifdef USE_UNIX_SOCKETS + } +#endif /* USE_UNIX_SOCKETS */ + return result; +} + +static CURLcode cf_haproxy_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + struct cf_haproxy_ctx *ctx = cf->ctx; + CURLcode result; + size_t len; + + DEBUGASSERT(ctx); + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + result = cf->next->cft->do_connect(cf->next, data, blocking, done); + if(result || !*done) + return result; + + switch(ctx->state) { + case HAPROXY_INIT: + result = cf_haproxy_date_out_set(cf, data); + if(result) + goto out; + ctx->state = HAPROXY_SEND; + FALLTHROUGH(); + case HAPROXY_SEND: + len = Curl_dyn_len(&ctx->data_out); + if(len > 0) { + size_t written; + result = Curl_conn_send(data, cf->sockindex, + Curl_dyn_ptr(&ctx->data_out), + len, &written); + if(result == CURLE_AGAIN) { + result = CURLE_OK; + written = 0; + } + else if(result) + goto out; + Curl_dyn_tail(&ctx->data_out, len - written); + if(Curl_dyn_len(&ctx->data_out) > 0) { + result = CURLE_OK; + goto out; + } + } + ctx->state = HAPROXY_DONE; + FALLTHROUGH(); + default: + Curl_dyn_free(&ctx->data_out); + break; + } + +out: + *done = (!result) && (ctx->state == HAPROXY_DONE); + cf->connected = *done; + return result; +} + +static void cf_haproxy_destroy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + (void)data; + CURL_TRC_CF(data, cf, "destroy"); + cf_haproxy_ctx_free(cf->ctx); +} + +static void cf_haproxy_close(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURL_TRC_CF(data, cf, "close"); + cf->connected = FALSE; + cf_haproxy_ctx_reset(cf->ctx); + if(cf->next) + cf->next->cft->do_close(cf->next, data); +} + +static void cf_haproxy_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + if(cf->next->connected && !cf->connected) { + /* If we are not connected, but the filter "below" is + * and not waiting on something, we are sending. */ + Curl_pollset_set_out_only(data, ps, Curl_conn_cf_get_socket(cf, data)); + } +} + +struct Curl_cftype Curl_cft_haproxy = { + "HAPROXY", + CF_TYPE_PROXY, + 0, + cf_haproxy_destroy, + cf_haproxy_connect, + cf_haproxy_close, + Curl_cf_def_get_host, + cf_haproxy_adjust_pollset, + Curl_cf_def_data_pending, + Curl_cf_def_send, + Curl_cf_def_recv, + Curl_cf_def_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + Curl_cf_def_query, +}; + +static CURLcode cf_haproxy_create(struct Curl_cfilter **pcf, + struct Curl_easy *data) +{ + struct Curl_cfilter *cf = NULL; + struct cf_haproxy_ctx *ctx; + CURLcode result; + + (void)data; + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + ctx->state = HAPROXY_INIT; + Curl_dyn_init(&ctx->data_out, DYN_HAXPROXY); + + result = Curl_cf_create(&cf, &Curl_cft_haproxy, ctx); + if(result) + goto out; + ctx = NULL; + +out: + cf_haproxy_ctx_free(ctx); + *pcf = result? NULL : cf; + return result; +} + +CURLcode Curl_cf_haproxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data) +{ + struct Curl_cfilter *cf; + CURLcode result; + + result = cf_haproxy_create(&cf, data); + if(result) + goto out; + Curl_conn_cf_insert_after(cf_at, cf); + +out: + return result; +} + +#endif /* !CURL_DISABLE_PROXY */ diff --git a/third_party/curl/lib/cf-haproxy.h b/third_party/curl/lib/cf-haproxy.h new file mode 100644 index 0000000..d02c323 --- /dev/null +++ b/third_party/curl/lib/cf-haproxy.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_CF_HAPROXY_H +#define HEADER_CURL_CF_HAPROXY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "urldata.h" + +#if !defined(CURL_DISABLE_PROXY) + +CURLcode Curl_cf_haproxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data); + +extern struct Curl_cftype Curl_cft_haproxy; + +#endif /* !CURL_DISABLE_PROXY */ + +#endif /* HEADER_CURL_CF_HAPROXY_H */ diff --git a/third_party/curl/lib/cf-https-connect.c b/third_party/curl/lib/cf-https-connect.c new file mode 100644 index 0000000..50ac8d4 --- /dev/null +++ b/third_party/curl/lib/cf-https-connect.c @@ -0,0 +1,531 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(USE_HYPER) + +#include "urldata.h" +#include +#include "curl_trc.h" +#include "cfilters.h" +#include "connect.h" +#include "multiif.h" +#include "cf-https-connect.h" +#include "http2.h" +#include "vquic/vquic.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +typedef enum { + CF_HC_INIT, + CF_HC_CONNECT, + CF_HC_SUCCESS, + CF_HC_FAILURE +} cf_hc_state; + +struct cf_hc_baller { + const char *name; + struct Curl_cfilter *cf; + CURLcode result; + struct curltime started; + int reply_ms; + bool enabled; +}; + +static void cf_hc_baller_reset(struct cf_hc_baller *b, + struct Curl_easy *data) +{ + if(b->cf) { + Curl_conn_cf_close(b->cf, data); + Curl_conn_cf_discard_chain(&b->cf, data); + b->cf = NULL; + } + b->result = CURLE_OK; + b->reply_ms = -1; +} + +static bool cf_hc_baller_is_active(struct cf_hc_baller *b) +{ + return b->enabled && b->cf && !b->result; +} + +static bool cf_hc_baller_has_started(struct cf_hc_baller *b) +{ + return !!b->cf; +} + +static int cf_hc_baller_reply_ms(struct cf_hc_baller *b, + struct Curl_easy *data) +{ + if(b->reply_ms < 0) + b->cf->cft->query(b->cf, data, CF_QUERY_CONNECT_REPLY_MS, + &b->reply_ms, NULL); + return b->reply_ms; +} + +static bool cf_hc_baller_data_pending(struct cf_hc_baller *b, + const struct Curl_easy *data) +{ + return b->cf && !b->result && b->cf->cft->has_data_pending(b->cf, data); +} + +struct cf_hc_ctx { + cf_hc_state state; + const struct Curl_dns_entry *remotehost; + struct curltime started; /* when connect started */ + CURLcode result; /* overall result */ + struct cf_hc_baller h3_baller; + struct cf_hc_baller h21_baller; + unsigned int soft_eyeballs_timeout_ms; + unsigned int hard_eyeballs_timeout_ms; +}; + +static void cf_hc_baller_init(struct cf_hc_baller *b, + struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *name, + int transport) +{ + struct cf_hc_ctx *ctx = cf->ctx; + struct Curl_cfilter *save = cf->next; + + b->name = name; + cf->next = NULL; + b->started = Curl_now(); + b->result = Curl_cf_setup_insert_after(cf, data, ctx->remotehost, + transport, CURL_CF_SSL_ENABLE); + b->cf = cf->next; + cf->next = save; +} + +static CURLcode cf_hc_baller_connect(struct cf_hc_baller *b, + struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct Curl_cfilter *save = cf->next; + + cf->next = b->cf; + b->result = Curl_conn_cf_connect(cf->next, data, FALSE, done); + b->cf = cf->next; /* it might mutate */ + cf->next = save; + return b->result; +} + +static void cf_hc_reset(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_hc_ctx *ctx = cf->ctx; + + if(ctx) { + cf_hc_baller_reset(&ctx->h3_baller, data); + cf_hc_baller_reset(&ctx->h21_baller, data); + ctx->state = CF_HC_INIT; + ctx->result = CURLE_OK; + ctx->hard_eyeballs_timeout_ms = data->set.happy_eyeballs_timeout; + ctx->soft_eyeballs_timeout_ms = data->set.happy_eyeballs_timeout / 2; + } +} + +static CURLcode baller_connected(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_hc_baller *winner) +{ + struct cf_hc_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + DEBUGASSERT(winner->cf); + if(winner != &ctx->h3_baller) + cf_hc_baller_reset(&ctx->h3_baller, data); + if(winner != &ctx->h21_baller) + cf_hc_baller_reset(&ctx->h21_baller, data); + + CURL_TRC_CF(data, cf, "connect+handshake %s: %dms, 1st data: %dms", + winner->name, (int)Curl_timediff(Curl_now(), winner->started), + cf_hc_baller_reply_ms(winner, data)); + cf->next = winner->cf; + winner->cf = NULL; + + switch(cf->conn->alpn) { + case CURL_HTTP_VERSION_3: + infof(data, "using HTTP/3"); + break; + case CURL_HTTP_VERSION_2: +#ifdef USE_NGHTTP2 + /* Using nghttp2, we add the filter "below" us, so when the conn + * closes, we tear it down for a fresh reconnect */ + result = Curl_http2_switch_at(cf, data); + if(result) { + ctx->state = CF_HC_FAILURE; + ctx->result = result; + return result; + } +#endif + infof(data, "using HTTP/2"); + break; + default: + infof(data, "using HTTP/1.x"); + break; + } + ctx->state = CF_HC_SUCCESS; + cf->connected = TRUE; + Curl_conn_cf_cntrl(cf->next, data, TRUE, + CF_CTRL_CONN_INFO_UPDATE, 0, NULL); + return result; +} + + +static bool time_to_start_h21(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct curltime now) +{ + struct cf_hc_ctx *ctx = cf->ctx; + timediff_t elapsed_ms; + + if(!ctx->h21_baller.enabled || cf_hc_baller_has_started(&ctx->h21_baller)) + return FALSE; + + if(!ctx->h3_baller.enabled || !cf_hc_baller_is_active(&ctx->h3_baller)) + return TRUE; + + elapsed_ms = Curl_timediff(now, ctx->started); + if(elapsed_ms >= ctx->hard_eyeballs_timeout_ms) { + CURL_TRC_CF(data, cf, "hard timeout of %dms reached, starting h21", + ctx->hard_eyeballs_timeout_ms); + return TRUE; + } + + if(elapsed_ms >= ctx->soft_eyeballs_timeout_ms) { + if(cf_hc_baller_reply_ms(&ctx->h3_baller, data) < 0) { + CURL_TRC_CF(data, cf, "soft timeout of %dms reached, h3 has not " + "seen any data, starting h21", + ctx->soft_eyeballs_timeout_ms); + return TRUE; + } + /* set the effective hard timeout again */ + Curl_expire(data, ctx->hard_eyeballs_timeout_ms - elapsed_ms, + EXPIRE_ALPN_EYEBALLS); + } + return FALSE; +} + +static CURLcode cf_hc_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + struct cf_hc_ctx *ctx = cf->ctx; + struct curltime now; + CURLcode result = CURLE_OK; + + (void)blocking; + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + *done = FALSE; + now = Curl_now(); + switch(ctx->state) { + case CF_HC_INIT: + DEBUGASSERT(!ctx->h3_baller.cf); + DEBUGASSERT(!ctx->h21_baller.cf); + DEBUGASSERT(!cf->next); + CURL_TRC_CF(data, cf, "connect, init"); + ctx->started = now; + if(ctx->h3_baller.enabled) { + cf_hc_baller_init(&ctx->h3_baller, cf, data, "h3", TRNSPRT_QUIC); + if(ctx->h21_baller.enabled) + Curl_expire(data, ctx->soft_eyeballs_timeout_ms, EXPIRE_ALPN_EYEBALLS); + } + else if(ctx->h21_baller.enabled) + cf_hc_baller_init(&ctx->h21_baller, cf, data, "h21", + cf->conn->transport); + ctx->state = CF_HC_CONNECT; + FALLTHROUGH(); + + case CF_HC_CONNECT: + if(cf_hc_baller_is_active(&ctx->h3_baller)) { + result = cf_hc_baller_connect(&ctx->h3_baller, cf, data, done); + if(!result && *done) { + result = baller_connected(cf, data, &ctx->h3_baller); + goto out; + } + } + + if(time_to_start_h21(cf, data, now)) { + cf_hc_baller_init(&ctx->h21_baller, cf, data, "h21", + cf->conn->transport); + } + + if(cf_hc_baller_is_active(&ctx->h21_baller)) { + CURL_TRC_CF(data, cf, "connect, check h21"); + result = cf_hc_baller_connect(&ctx->h21_baller, cf, data, done); + if(!result && *done) { + result = baller_connected(cf, data, &ctx->h21_baller); + goto out; + } + } + + if((!ctx->h3_baller.enabled || ctx->h3_baller.result) && + (!ctx->h21_baller.enabled || ctx->h21_baller.result)) { + /* both failed or disabled. we give up */ + CURL_TRC_CF(data, cf, "connect, all failed"); + result = ctx->result = ctx->h3_baller.enabled? + ctx->h3_baller.result : ctx->h21_baller.result; + ctx->state = CF_HC_FAILURE; + goto out; + } + result = CURLE_OK; + *done = FALSE; + break; + + case CF_HC_FAILURE: + result = ctx->result; + cf->connected = FALSE; + *done = FALSE; + break; + + case CF_HC_SUCCESS: + result = CURLE_OK; + cf->connected = TRUE; + *done = TRUE; + break; + } + +out: + CURL_TRC_CF(data, cf, "connect -> %d, done=%d", result, *done); + return result; +} + +static void cf_hc_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + if(!cf->connected) { + struct cf_hc_ctx *ctx = cf->ctx; + struct cf_hc_baller *ballers[2]; + size_t i; + + ballers[0] = &ctx->h3_baller; + ballers[1] = &ctx->h21_baller; + for(i = 0; i < sizeof(ballers)/sizeof(ballers[0]); i++) { + struct cf_hc_baller *b = ballers[i]; + if(!cf_hc_baller_is_active(b)) + continue; + Curl_conn_cf_adjust_pollset(b->cf, data, ps); + } + CURL_TRC_CF(data, cf, "adjust_pollset -> %d socks", ps->num); + } +} + +static bool cf_hc_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct cf_hc_ctx *ctx = cf->ctx; + + if(cf->connected) + return cf->next->cft->has_data_pending(cf->next, data); + + CURL_TRC_CF((struct Curl_easy *)data, cf, "data_pending"); + return cf_hc_baller_data_pending(&ctx->h3_baller, data) + || cf_hc_baller_data_pending(&ctx->h21_baller, data); +} + +static struct curltime cf_get_max_baller_time(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query) +{ + struct cf_hc_ctx *ctx = cf->ctx; + struct Curl_cfilter *cfb; + struct curltime t, tmax; + + memset(&tmax, 0, sizeof(tmax)); + memset(&t, 0, sizeof(t)); + cfb = ctx->h21_baller.enabled? ctx->h21_baller.cf : NULL; + if(cfb && !cfb->cft->query(cfb, data, query, NULL, &t)) { + if((t.tv_sec || t.tv_usec) && Curl_timediff_us(t, tmax) > 0) + tmax = t; + } + memset(&t, 0, sizeof(t)); + cfb = ctx->h3_baller.enabled? ctx->h3_baller.cf : NULL; + if(cfb && !cfb->cft->query(cfb, data, query, NULL, &t)) { + if((t.tv_sec || t.tv_usec) && Curl_timediff_us(t, tmax) > 0) + tmax = t; + } + return tmax; +} + +static CURLcode cf_hc_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + if(!cf->connected) { + switch(query) { + case CF_QUERY_TIMER_CONNECT: { + struct curltime *when = pres2; + *when = cf_get_max_baller_time(cf, data, CF_QUERY_TIMER_CONNECT); + return CURLE_OK; + } + case CF_QUERY_TIMER_APPCONNECT: { + struct curltime *when = pres2; + *when = cf_get_max_baller_time(cf, data, CF_QUERY_TIMER_APPCONNECT); + return CURLE_OK; + } + default: + break; + } + } + return cf->next? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +static void cf_hc_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + CURL_TRC_CF(data, cf, "close"); + cf_hc_reset(cf, data); + cf->connected = FALSE; + + if(cf->next) { + cf->next->cft->do_close(cf->next, data); + Curl_conn_cf_discard_chain(&cf->next, data); + } +} + +static void cf_hc_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_hc_ctx *ctx = cf->ctx; + + (void)data; + CURL_TRC_CF(data, cf, "destroy"); + cf_hc_reset(cf, data); + Curl_safefree(ctx); +} + +struct Curl_cftype Curl_cft_http_connect = { + "HTTPS-CONNECT", + 0, + CURL_LOG_LVL_NONE, + cf_hc_destroy, + cf_hc_connect, + cf_hc_close, + Curl_cf_def_get_host, + cf_hc_adjust_pollset, + cf_hc_data_pending, + Curl_cf_def_send, + Curl_cf_def_recv, + Curl_cf_def_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_hc_query, +}; + +static CURLcode cf_hc_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + const struct Curl_dns_entry *remotehost, + bool try_h3, bool try_h21) +{ + struct Curl_cfilter *cf = NULL; + struct cf_hc_ctx *ctx; + CURLcode result = CURLE_OK; + + (void)data; + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + ctx->remotehost = remotehost; + ctx->h3_baller.enabled = try_h3; + ctx->h21_baller.enabled = try_h21; + + result = Curl_cf_create(&cf, &Curl_cft_http_connect, ctx); + if(result) + goto out; + ctx = NULL; + cf_hc_reset(cf, data); + +out: + *pcf = result? NULL : cf; + free(ctx); + return result; +} + +static CURLcode cf_http_connect_add(struct Curl_easy *data, + struct connectdata *conn, + int sockindex, + const struct Curl_dns_entry *remotehost, + bool try_h3, bool try_h21) +{ + struct Curl_cfilter *cf; + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + result = cf_hc_create(&cf, data, remotehost, try_h3, try_h21); + if(result) + goto out; + Curl_conn_cf_add(data, conn, sockindex, cf); +out: + return result; +} + +CURLcode Curl_cf_https_setup(struct Curl_easy *data, + struct connectdata *conn, + int sockindex, + const struct Curl_dns_entry *remotehost) +{ + bool try_h3 = FALSE, try_h21 = TRUE; /* defaults, for now */ + CURLcode result = CURLE_OK; + + (void)sockindex; + (void)remotehost; + + if(!conn->bits.tls_enable_alpn) + goto out; + + if(data->state.httpwant == CURL_HTTP_VERSION_3ONLY) { + result = Curl_conn_may_http3(data, conn); + if(result) /* can't do it */ + goto out; + try_h3 = TRUE; + try_h21 = FALSE; + } + else if(data->state.httpwant >= CURL_HTTP_VERSION_3) { + /* We assume that silently not even trying H3 is ok here */ + /* TODO: should we fail instead? */ + try_h3 = (Curl_conn_may_http3(data, conn) == CURLE_OK); + try_h21 = TRUE; + } + + result = cf_http_connect_add(data, conn, sockindex, remotehost, + try_h3, try_h21); +out: + return result; +} + +#endif /* !defined(CURL_DISABLE_HTTP) && !defined(USE_HYPER) */ diff --git a/third_party/curl/lib/cf-https-connect.h b/third_party/curl/lib/cf-https-connect.h new file mode 100644 index 0000000..6a39527 --- /dev/null +++ b/third_party/curl/lib/cf-https-connect.h @@ -0,0 +1,58 @@ +#ifndef HEADER_CURL_CF_HTTP_H +#define HEADER_CURL_CF_HTTP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(USE_HYPER) + +struct Curl_cfilter; +struct Curl_easy; +struct connectdata; +struct Curl_cftype; +struct Curl_dns_entry; + +extern struct Curl_cftype Curl_cft_http_connect; + +CURLcode Curl_cf_http_connect_add(struct Curl_easy *data, + struct connectdata *conn, + int sockindex, + const struct Curl_dns_entry *remotehost, + bool try_h3, bool try_h21); + +CURLcode +Curl_cf_http_connect_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + const struct Curl_dns_entry *remotehost, + bool try_h3, bool try_h21); + + +CURLcode Curl_cf_https_setup(struct Curl_easy *data, + struct connectdata *conn, + int sockindex, + const struct Curl_dns_entry *remotehost); + + +#endif /* !defined(CURL_DISABLE_HTTP) && !defined(USE_HYPER) */ +#endif /* HEADER_CURL_CF_HTTP_H */ diff --git a/third_party/curl/lib/cf-socket.c b/third_party/curl/lib/cf-socket.c new file mode 100644 index 0000000..3e87889 --- /dev/null +++ b/third_party/curl/lib/cf-socket.c @@ -0,0 +1,1963 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include /* may need it */ +#endif +#ifdef HAVE_SYS_UN_H +#include /* for sockaddr_un */ +#endif +#ifdef HAVE_LINUX_TCP_H +#include +#elif defined(HAVE_NETINET_TCP_H) +#include +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_FCNTL_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif + +#ifdef __VMS +#include +#include +#endif + +#include "urldata.h" +#include "bufq.h" +#include "sendf.h" +#include "if2ip.h" +#include "strerror.h" +#include "cfilters.h" +#include "cf-socket.h" +#include "connect.h" +#include "select.h" +#include "url.h" /* for Curl_safefree() */ +#include "multiif.h" +#include "sockaddr.h" /* required for Curl_sockaddr_storage */ +#include "inet_ntop.h" +#include "inet_pton.h" +#include "progress.h" +#include "warnless.h" +#include "conncache.h" +#include "multihandle.h" +#include "rand.h" +#include "share.h" +#include "version_win32.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +#if defined(USE_IPV6) && defined(IPV6_V6ONLY) && defined(_WIN32) +/* It makes support for IPv4-mapped IPv6 addresses. + * Linux kernel, NetBSD, FreeBSD and Darwin: default is off; + * Windows Vista and later: default is on; + * DragonFly BSD: acts like off, and dummy setting; + * OpenBSD and earlier Windows: unsupported. + * Linux: controlled by /proc/sys/net/ipv6/bindv6only. + */ +static void set_ipv6_v6only(curl_socket_t sockfd, int on) +{ + (void)setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&on, sizeof(on)); +} +#else +#define set_ipv6_v6only(x,y) +#endif + +static void tcpnodelay(struct Curl_easy *data, curl_socket_t sockfd) +{ +#if defined(TCP_NODELAY) + curl_socklen_t onoff = (curl_socklen_t) 1; + int level = IPPROTO_TCP; + char buffer[STRERROR_LEN]; + + if(setsockopt(sockfd, level, TCP_NODELAY, (void *)&onoff, + sizeof(onoff)) < 0) + infof(data, "Could not set TCP_NODELAY: %s", + Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); +#else + (void)data; + (void)sockfd; +#endif +} + +#ifdef SO_NOSIGPIPE +/* The preferred method on Mac OS X (10.2 and later) to prevent SIGPIPEs when + sending data to a dead peer (instead of relying on the 4th argument to send + being MSG_NOSIGNAL). Possibly also existing and in use on other BSD + systems? */ +static void nosigpipe(struct Curl_easy *data, + curl_socket_t sockfd) +{ + int onoff = 1; + (void)data; + if(setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&onoff, + sizeof(onoff)) < 0) { +#if !defined(CURL_DISABLE_VERBOSE_STRINGS) + char buffer[STRERROR_LEN]; + infof(data, "Could not set SO_NOSIGPIPE: %s", + Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); +#endif + } +} +#else +#define nosigpipe(x,y) Curl_nop_stmt +#endif + +#if defined(__DragonFly__) || defined(USE_WINSOCK) +/* DragonFlyBSD and Windows use millisecond units */ +#define KEEPALIVE_FACTOR(x) (x *= 1000) +#else +#define KEEPALIVE_FACTOR(x) +#endif + +#if defined(USE_WINSOCK) && !defined(SIO_KEEPALIVE_VALS) +#define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4) + +struct tcp_keepalive { + u_long onoff; + u_long keepalivetime; + u_long keepaliveinterval; +}; +#endif + +static void +tcpkeepalive(struct Curl_easy *data, + curl_socket_t sockfd) +{ + int optval = data->set.tcp_keepalive?1:0; + + /* only set IDLE and INTVL if setting KEEPALIVE is successful */ + if(setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, + (void *)&optval, sizeof(optval)) < 0) { + infof(data, "Failed to set SO_KEEPALIVE on fd " + "%" CURL_FORMAT_SOCKET_T ": errno %d", + sockfd, SOCKERRNO); + } + else { +#if defined(SIO_KEEPALIVE_VALS) + struct tcp_keepalive vals; + DWORD dummy; + vals.onoff = 1; + optval = curlx_sltosi(data->set.tcp_keepidle); + KEEPALIVE_FACTOR(optval); + vals.keepalivetime = optval; + optval = curlx_sltosi(data->set.tcp_keepintvl); + KEEPALIVE_FACTOR(optval); + vals.keepaliveinterval = optval; + if(WSAIoctl(sockfd, SIO_KEEPALIVE_VALS, (LPVOID) &vals, sizeof(vals), + NULL, 0, &dummy, NULL, NULL) != 0) { + infof(data, "Failed to set SIO_KEEPALIVE_VALS on fd " + "%" CURL_FORMAT_SOCKET_T ": errno %d", + sockfd, SOCKERRNO); + } +#else +#ifdef TCP_KEEPIDLE + optval = curlx_sltosi(data->set.tcp_keepidle); + KEEPALIVE_FACTOR(optval); + if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, + (void *)&optval, sizeof(optval)) < 0) { + infof(data, "Failed to set TCP_KEEPIDLE on fd " + "%" CURL_FORMAT_SOCKET_T ": errno %d", + sockfd, SOCKERRNO); + } +#elif defined(TCP_KEEPALIVE) + /* Mac OS X style */ + optval = curlx_sltosi(data->set.tcp_keepidle); + KEEPALIVE_FACTOR(optval); + if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE, + (void *)&optval, sizeof(optval)) < 0) { + infof(data, "Failed to set TCP_KEEPALIVE on fd " + "%" CURL_FORMAT_SOCKET_T ": errno %d", + sockfd, SOCKERRNO); + } +#endif +#ifdef TCP_KEEPINTVL + optval = curlx_sltosi(data->set.tcp_keepintvl); + KEEPALIVE_FACTOR(optval); + if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, + (void *)&optval, sizeof(optval)) < 0) { + infof(data, "Failed to set TCP_KEEPINTVL on fd " + "%" CURL_FORMAT_SOCKET_T ": errno %d", + sockfd, SOCKERRNO); + } +#endif +#endif + } +} + +/** + * Assign the address `ai` to the Curl_sockaddr_ex `dest` and + * set the transport used. + */ +void Curl_sock_assign_addr(struct Curl_sockaddr_ex *dest, + const struct Curl_addrinfo *ai, + int transport) +{ + /* + * The Curl_sockaddr_ex structure is basically libcurl's external API + * curl_sockaddr structure with enough space available to directly hold + * any protocol-specific address structures. The variable declared here + * will be used to pass / receive data to/from the fopensocket callback + * if this has been set, before that, it is initialized from parameters. + */ + dest->family = ai->ai_family; + switch(transport) { + case TRNSPRT_TCP: + dest->socktype = SOCK_STREAM; + dest->protocol = IPPROTO_TCP; + break; + case TRNSPRT_UNIX: + dest->socktype = SOCK_STREAM; + dest->protocol = IPPROTO_IP; + break; + default: /* UDP and QUIC */ + dest->socktype = SOCK_DGRAM; + dest->protocol = IPPROTO_UDP; + break; + } + dest->addrlen = ai->ai_addrlen; + + if(dest->addrlen > sizeof(struct Curl_sockaddr_storage)) + dest->addrlen = sizeof(struct Curl_sockaddr_storage); + memcpy(&dest->sa_addr, ai->ai_addr, dest->addrlen); +} + +static CURLcode socket_open(struct Curl_easy *data, + struct Curl_sockaddr_ex *addr, + curl_socket_t *sockfd) +{ + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + if(data->set.fopensocket) { + /* + * If the opensocket callback is set, all the destination address + * information is passed to the callback. Depending on this information the + * callback may opt to abort the connection, this is indicated returning + * CURL_SOCKET_BAD; otherwise it will return a not-connected socket. When + * the callback returns a valid socket the destination address information + * might have been changed and this 'new' address will actually be used + * here to connect. + */ + Curl_set_in_callback(data, true); + *sockfd = data->set.fopensocket(data->set.opensocket_client, + CURLSOCKTYPE_IPCXN, + (struct curl_sockaddr *)addr); + Curl_set_in_callback(data, false); + } + else { + /* opensocket callback not set, so simply create the socket now */ + *sockfd = socket(addr->family, addr->socktype, addr->protocol); + } + + if(*sockfd == CURL_SOCKET_BAD) + /* no socket, no connection */ + return CURLE_COULDNT_CONNECT; + +#if defined(USE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID) + if(data->conn->scope_id && (addr->family == AF_INET6)) { + struct sockaddr_in6 * const sa6 = (void *)&addr->sa_addr; + sa6->sin6_scope_id = data->conn->scope_id; + } +#endif + return CURLE_OK; +} + +/* + * Create a socket based on info from 'conn' and 'ai'. + * + * 'addr' should be a pointer to the correct struct to get data back, or NULL. + * 'sockfd' must be a pointer to a socket descriptor. + * + * If the open socket callback is set, used that! + * + */ +CURLcode Curl_socket_open(struct Curl_easy *data, + const struct Curl_addrinfo *ai, + struct Curl_sockaddr_ex *addr, + int transport, + curl_socket_t *sockfd) +{ + struct Curl_sockaddr_ex dummy; + + if(!addr) + /* if the caller doesn't want info back, use a local temp copy */ + addr = &dummy; + + Curl_sock_assign_addr(addr, ai, transport); + return socket_open(data, addr, sockfd); +} + +static int socket_close(struct Curl_easy *data, struct connectdata *conn, + int use_callback, curl_socket_t sock) +{ + if(use_callback && conn && conn->fclosesocket) { + int rc; + Curl_multi_closed(data, sock); + Curl_set_in_callback(data, true); + rc = conn->fclosesocket(conn->closesocket_client, sock); + Curl_set_in_callback(data, false); + return rc; + } + + if(conn) + /* tell the multi-socket code about this */ + Curl_multi_closed(data, sock); + + sclose(sock); + + return 0; +} + +/* + * Close a socket. + * + * 'conn' can be NULL, beware! + */ +int Curl_socket_close(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t sock) +{ + return socket_close(data, conn, FALSE, sock); +} + +#ifdef USE_WINSOCK +/* When you run a program that uses the Windows Sockets API, you may + experience slow performance when you copy data to a TCP server. + + https://support.microsoft.com/kb/823764 + + Work-around: Make the Socket Send Buffer Size Larger Than the Program Send + Buffer Size + + The problem described in this knowledge-base is applied only to pre-Vista + Windows. Following function trying to detect OS version and skips + SO_SNDBUF adjustment for Windows Vista and above. +*/ +#define DETECT_OS_NONE 0 +#define DETECT_OS_PREVISTA 1 +#define DETECT_OS_VISTA_OR_LATER 2 + +void Curl_sndbufset(curl_socket_t sockfd) +{ + int val = CURL_MAX_WRITE_SIZE + 32; + int curval = 0; + int curlen = sizeof(curval); + + static int detectOsState = DETECT_OS_NONE; + + if(detectOsState == DETECT_OS_NONE) { + if(curlx_verify_windows_version(6, 0, 0, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) + detectOsState = DETECT_OS_VISTA_OR_LATER; + else + detectOsState = DETECT_OS_PREVISTA; + } + + if(detectOsState == DETECT_OS_VISTA_OR_LATER) + return; + + if(getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (char *)&curval, &curlen) == 0) + if(curval > val) + return; + + setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&val, sizeof(val)); +} +#endif + +#ifndef CURL_DISABLE_BINDLOCAL +static CURLcode bindlocal(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t sockfd, int af, unsigned int scope) +{ + struct Curl_sockaddr_storage sa; + struct sockaddr *sock = (struct sockaddr *)&sa; /* bind to this address */ + curl_socklen_t sizeof_sa = 0; /* size of the data sock points to */ + struct sockaddr_in *si4 = (struct sockaddr_in *)&sa; +#ifdef USE_IPV6 + struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)&sa; +#endif + + struct Curl_dns_entry *h = NULL; + unsigned short port = data->set.localport; /* use this port number, 0 for + "random" */ + /* how many port numbers to try to bind to, increasing one at a time */ + int portnum = data->set.localportrange; + const char *dev = data->set.str[STRING_DEVICE]; + int error; +#ifdef IP_BIND_ADDRESS_NO_PORT + int on = 1; +#endif +#ifndef USE_IPV6 + (void)scope; +#endif + + /************************************************************* + * Select device to bind socket to + *************************************************************/ + if(!dev && !port) + /* no local kind of binding was requested */ + return CURLE_OK; + + memset(&sa, 0, sizeof(struct Curl_sockaddr_storage)); + + if(dev && (strlen(dev)<255) ) { + char myhost[256] = ""; + int done = 0; /* -1 for error, 1 for address found */ + bool is_interface = FALSE; + bool is_host = FALSE; + static const char *if_prefix = "if!"; + static const char *host_prefix = "host!"; + + if(strncmp(if_prefix, dev, strlen(if_prefix)) == 0) { + dev += strlen(if_prefix); + is_interface = TRUE; + } + else if(strncmp(host_prefix, dev, strlen(host_prefix)) == 0) { + dev += strlen(host_prefix); + is_host = TRUE; + } + + /* interface */ + if(!is_host) { +#ifdef SO_BINDTODEVICE + /* + * This binds the local socket to a particular interface. This will + * force even requests to other local interfaces to go out the external + * interface. Only bind to the interface when specified as interface, + * not just as a hostname or ip address. + * + * The interface might be a VRF, eg: vrf-blue, which means it cannot be + * converted to an IP address and would fail Curl_if2ip. Simply try to + * use it straight away. + */ + if(setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE, + dev, (curl_socklen_t)strlen(dev) + 1) == 0) { + /* This is often "errno 1, error: Operation not permitted" if you're + * not running as root or another suitable privileged user. If it + * succeeds it means the parameter was a valid interface and not an IP + * address. Return immediately. + */ + infof(data, "socket successfully bound to interface '%s'", dev); + return CURLE_OK; + } +#endif + + switch(Curl_if2ip(af, +#ifdef USE_IPV6 + scope, conn->scope_id, +#endif + dev, myhost, sizeof(myhost))) { + case IF2IP_NOT_FOUND: + if(is_interface) { + /* Do not fall back to treating it as a host name */ + failf(data, "Couldn't bind to interface '%s'", dev); + return CURLE_INTERFACE_FAILED; + } + break; + case IF2IP_AF_NOT_SUPPORTED: + /* Signal the caller to try another address family if available */ + return CURLE_UNSUPPORTED_PROTOCOL; + case IF2IP_FOUND: + is_interface = TRUE; + /* + * We now have the numerical IP address in the 'myhost' buffer + */ + infof(data, "Local Interface %s is ip %s using address family %i", + dev, myhost, af); + done = 1; + break; + } + } + if(!is_interface) { + /* + * This was not an interface, resolve the name as a host name + * or IP number + * + * Temporarily force name resolution to use only the address type + * of the connection. The resolve functions should really be changed + * to take a type parameter instead. + */ + unsigned char ipver = conn->ip_version; + int rc; + + if(af == AF_INET) + conn->ip_version = CURL_IPRESOLVE_V4; +#ifdef USE_IPV6 + else if(af == AF_INET6) + conn->ip_version = CURL_IPRESOLVE_V6; +#endif + + rc = Curl_resolv(data, dev, 80, FALSE, &h); + if(rc == CURLRESOLV_PENDING) + (void)Curl_resolver_wait_resolv(data, &h); + conn->ip_version = ipver; + + if(h) { + /* convert the resolved address, sizeof myhost >= INET_ADDRSTRLEN */ + Curl_printable_address(h->addr, myhost, sizeof(myhost)); + infof(data, "Name '%s' family %i resolved to '%s' family %i", + dev, af, myhost, h->addr->ai_family); + Curl_resolv_unlock(data, h); + if(af != h->addr->ai_family) { + /* bad IP version combo, signal the caller to try another address + family if available */ + return CURLE_UNSUPPORTED_PROTOCOL; + } + done = 1; + } + else { + /* + * provided dev was no interface (or interfaces are not supported + * e.g. solaris) no ip address and no domain we fail here + */ + done = -1; + } + } + + if(done > 0) { +#ifdef USE_IPV6 + /* IPv6 address */ + if(af == AF_INET6) { +#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID + char *scope_ptr = strchr(myhost, '%'); + if(scope_ptr) + *(scope_ptr++) = '\0'; +#endif + if(Curl_inet_pton(AF_INET6, myhost, &si6->sin6_addr) > 0) { + si6->sin6_family = AF_INET6; + si6->sin6_port = htons(port); +#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID + if(scope_ptr) { + /* The "myhost" string either comes from Curl_if2ip or from + Curl_printable_address. The latter returns only numeric scope + IDs and the former returns none at all. So the scope ID, if + present, is known to be numeric */ + unsigned long scope_id = strtoul(scope_ptr, NULL, 10); + if(scope_id > UINT_MAX) + return CURLE_UNSUPPORTED_PROTOCOL; + + si6->sin6_scope_id = (unsigned int)scope_id; + } +#endif + } + sizeof_sa = sizeof(struct sockaddr_in6); + } + else +#endif + /* IPv4 address */ + if((af == AF_INET) && + (Curl_inet_pton(AF_INET, myhost, &si4->sin_addr) > 0)) { + si4->sin_family = AF_INET; + si4->sin_port = htons(port); + sizeof_sa = sizeof(struct sockaddr_in); + } + } + + if(done < 1) { + /* errorbuf is set false so failf will overwrite any message already in + the error buffer, so the user receives this error message instead of a + generic resolve error. */ + data->state.errorbuf = FALSE; + failf(data, "Couldn't bind to '%s'", dev); + return CURLE_INTERFACE_FAILED; + } + } + else { + /* no device was given, prepare sa to match af's needs */ +#ifdef USE_IPV6 + if(af == AF_INET6) { + si6->sin6_family = AF_INET6; + si6->sin6_port = htons(port); + sizeof_sa = sizeof(struct sockaddr_in6); + } + else +#endif + if(af == AF_INET) { + si4->sin_family = AF_INET; + si4->sin_port = htons(port); + sizeof_sa = sizeof(struct sockaddr_in); + } + } +#ifdef IP_BIND_ADDRESS_NO_PORT + (void)setsockopt(sockfd, SOL_IP, IP_BIND_ADDRESS_NO_PORT, &on, sizeof(on)); +#endif + for(;;) { + if(bind(sockfd, sock, sizeof_sa) >= 0) { + /* we succeeded to bind */ + infof(data, "Local port: %hu", port); + conn->bits.bound = TRUE; + return CURLE_OK; + } + + if(--portnum > 0) { + port++; /* try next port */ + if(port == 0) + break; + infof(data, "Bind to local port %d failed, trying next", port - 1); + /* We reuse/clobber the port variable here below */ + if(sock->sa_family == AF_INET) + si4->sin_port = ntohs(port); +#ifdef USE_IPV6 + else + si6->sin6_port = ntohs(port); +#endif + } + else + break; + } + { + char buffer[STRERROR_LEN]; + data->state.os_errno = error = SOCKERRNO; + failf(data, "bind failed with errno %d: %s", + error, Curl_strerror(error, buffer, sizeof(buffer))); + } + + return CURLE_INTERFACE_FAILED; +} +#endif + +/* + * verifyconnect() returns TRUE if the connect really has happened. + */ +static bool verifyconnect(curl_socket_t sockfd, int *error) +{ + bool rc = TRUE; +#ifdef SO_ERROR + int err = 0; + curl_socklen_t errSize = sizeof(err); + +#ifdef _WIN32 + /* + * In October 2003 we effectively nullified this function on Windows due to + * problems with it using all CPU in multi-threaded cases. + * + * In May 2004, we bring it back to offer more info back on connect failures. + * Gisle Vanem could reproduce the former problems with this function, but + * could avoid them by adding this SleepEx() call below: + * + * "I don't have Rational Quantify, but the hint from his post was + * ntdll::NtRemoveIoCompletion(). So I'd assume the SleepEx (or maybe + * just Sleep(0) would be enough?) would release whatever + * mutex/critical-section the ntdll call is waiting on. + * + * Someone got to verify this on Win-NT 4.0, 2000." + */ + +#ifdef _WIN32_WCE + Sleep(0); +#else + SleepEx(0, FALSE); +#endif + +#endif + + if(0 != getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&err, &errSize)) + err = SOCKERRNO; +#ifdef _WIN32_WCE + /* Old WinCE versions don't support SO_ERROR */ + if(WSAENOPROTOOPT == err) { + SET_SOCKERRNO(0); + err = 0; + } +#endif +#if defined(EBADIOCTL) && defined(__minix) + /* Minix 3.1.x doesn't support getsockopt on UDP sockets */ + if(EBADIOCTL == err) { + SET_SOCKERRNO(0); + err = 0; + } +#endif + if((0 == err) || (EISCONN == err)) + /* we are connected, awesome! */ + rc = TRUE; + else + /* This wasn't a successful connect */ + rc = FALSE; + if(error) + *error = err; +#else + (void)sockfd; + if(error) + *error = SOCKERRNO; +#endif + return rc; +} + +/** + * Determine the curl code for a socket connect() == -1 with errno. + */ +static CURLcode socket_connect_result(struct Curl_easy *data, + const char *ipaddress, int error) +{ + switch(error) { + case EINPROGRESS: + case EWOULDBLOCK: +#if defined(EAGAIN) +#if (EAGAIN) != (EWOULDBLOCK) + /* On some platforms EAGAIN and EWOULDBLOCK are the + * same value, and on others they are different, hence + * the odd #if + */ + case EAGAIN: +#endif +#endif + return CURLE_OK; + + default: + /* unknown error, fallthrough and try another address! */ +#ifdef CURL_DISABLE_VERBOSE_STRINGS + (void)ipaddress; +#else + { + char buffer[STRERROR_LEN]; + infof(data, "Immediate connect fail for %s: %s", + ipaddress, Curl_strerror(error, buffer, sizeof(buffer))); + } +#endif + data->state.os_errno = error; + /* connect failed */ + return CURLE_COULDNT_CONNECT; + } +} + +/* We have a recv buffer to enhance reads with len < NW_SMALL_READS. + * This happens often on TLS connections where the TLS implementation + * tries to read the head of a TLS record, determine the length of the + * full record and then make a subsequent read for that. + * On large reads, we will not fill the buffer to avoid the double copy. */ +#define NW_RECV_CHUNK_SIZE (64 * 1024) +#define NW_RECV_CHUNKS 1 +#define NW_SMALL_READS (1024) + +struct cf_socket_ctx { + int transport; + struct Curl_sockaddr_ex addr; /* address to connect to */ + curl_socket_t sock; /* current attempt socket */ + struct bufq recvbuf; /* used when `buffer_recv` is set */ + struct ip_quadruple ip; /* The IP quadruple 2x(addr+port) */ + struct curltime started_at; /* when socket was created */ + struct curltime connected_at; /* when socket connected/got first byte */ + struct curltime first_byte_at; /* when first byte was recvd */ + int error; /* errno of last failure or 0 */ +#ifdef DEBUGBUILD + int wblock_percent; /* percent of writes doing EAGAIN */ + int wpartial_percent; /* percent of bytes written in send */ + int rblock_percent; /* percent of reads doing EAGAIN */ + size_t recv_max; /* max enforced read size */ +#endif + BIT(got_first_byte); /* if first byte was received */ + BIT(accepted); /* socket was accepted, not connected */ + BIT(sock_connected); /* socket is "connected", e.g. in UDP */ + BIT(active); + BIT(buffer_recv); +}; + +static void cf_socket_ctx_init(struct cf_socket_ctx *ctx, + const struct Curl_addrinfo *ai, + int transport) +{ + memset(ctx, 0, sizeof(*ctx)); + ctx->sock = CURL_SOCKET_BAD; + ctx->transport = transport; + Curl_sock_assign_addr(&ctx->addr, ai, transport); + Curl_bufq_init(&ctx->recvbuf, NW_RECV_CHUNK_SIZE, NW_RECV_CHUNKS); +#ifdef DEBUGBUILD + { + char *p = getenv("CURL_DBG_SOCK_WBLOCK"); + if(p) { + long l = strtol(p, NULL, 10); + if(l >= 0 && l <= 100) + ctx->wblock_percent = (int)l; + } + p = getenv("CURL_DBG_SOCK_WPARTIAL"); + if(p) { + long l = strtol(p, NULL, 10); + if(l >= 0 && l <= 100) + ctx->wpartial_percent = (int)l; + } + p = getenv("CURL_DBG_SOCK_RBLOCK"); + if(p) { + long l = strtol(p, NULL, 10); + if(l >= 0 && l <= 100) + ctx->rblock_percent = (int)l; + } + p = getenv("CURL_DBG_SOCK_RMAX"); + if(p) { + long l = strtol(p, NULL, 10); + if(l >= 0) + ctx->recv_max = (size_t)l; + } + } +#endif +} + +struct reader_ctx { + struct Curl_cfilter *cf; + struct Curl_easy *data; +}; + +static ssize_t nw_in_read(void *reader_ctx, + unsigned char *buf, size_t len, + CURLcode *err) +{ + struct reader_ctx *rctx = reader_ctx; + struct cf_socket_ctx *ctx = rctx->cf->ctx; + ssize_t nread; + + *err = CURLE_OK; + nread = sread(ctx->sock, buf, len); + + if(-1 == nread) { + int sockerr = SOCKERRNO; + + if( +#ifdef WSAEWOULDBLOCK + /* This is how Windows does it */ + (WSAEWOULDBLOCK == sockerr) +#else + /* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned + due to its inability to send off data without blocking. We therefore + treat both error codes the same here */ + (EWOULDBLOCK == sockerr) || (EAGAIN == sockerr) || (EINTR == sockerr) +#endif + ) { + /* this is just a case of EWOULDBLOCK */ + *err = CURLE_AGAIN; + nread = -1; + } + else { + char buffer[STRERROR_LEN]; + + failf(rctx->data, "Recv failure: %s", + Curl_strerror(sockerr, buffer, sizeof(buffer))); + rctx->data->state.os_errno = sockerr; + *err = CURLE_RECV_ERROR; + nread = -1; + } + } + CURL_TRC_CF(rctx->data, rctx->cf, "nw_in_read(len=%zu, fd=%" + CURL_FORMAT_SOCKET_T ") -> %d, err=%d", + len, ctx->sock, (int)nread, *err); + return nread; +} + +static void cf_socket_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; + + if(ctx && CURL_SOCKET_BAD != ctx->sock) { + CURL_TRC_CF(data, cf, "cf_socket_close(%" CURL_FORMAT_SOCKET_T + ")", ctx->sock); + if(ctx->sock == cf->conn->sock[cf->sockindex]) + cf->conn->sock[cf->sockindex] = CURL_SOCKET_BAD; + socket_close(data, cf->conn, !ctx->accepted, ctx->sock); + ctx->sock = CURL_SOCKET_BAD; + if(ctx->active && cf->sockindex == FIRSTSOCKET) + cf->conn->remote_addr = NULL; + Curl_bufq_reset(&ctx->recvbuf); + ctx->active = FALSE; + ctx->buffer_recv = FALSE; + memset(&ctx->started_at, 0, sizeof(ctx->started_at)); + memset(&ctx->connected_at, 0, sizeof(ctx->connected_at)); + } + + cf->connected = FALSE; +} + +static void cf_socket_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; + + cf_socket_close(cf, data); + CURL_TRC_CF(data, cf, "destroy"); + Curl_bufq_free(&ctx->recvbuf); + free(ctx); + cf->ctx = NULL; +} + +static CURLcode set_local_ip(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; + +#ifdef HAVE_GETSOCKNAME + if((ctx->sock != CURL_SOCKET_BAD) && + !(data->conn->handler->protocol & CURLPROTO_TFTP)) { + /* TFTP does not connect, so it cannot get the IP like this */ + + char buffer[STRERROR_LEN]; + struct Curl_sockaddr_storage ssloc; + curl_socklen_t slen = sizeof(struct Curl_sockaddr_storage); + + memset(&ssloc, 0, sizeof(ssloc)); + if(getsockname(ctx->sock, (struct sockaddr*) &ssloc, &slen)) { + int error = SOCKERRNO; + failf(data, "getsockname() failed with errno %d: %s", + error, Curl_strerror(error, buffer, sizeof(buffer))); + return CURLE_FAILED_INIT; + } + if(!Curl_addr2string((struct sockaddr*)&ssloc, slen, + ctx->ip.local_ip, &ctx->ip.local_port)) { + failf(data, "ssloc inet_ntop() failed with errno %d: %s", + errno, Curl_strerror(errno, buffer, sizeof(buffer))); + return CURLE_FAILED_INIT; + } + } +#else + (void)data; + ctx->ip.local_ip[0] = 0; + ctx->ip.local_port = -1; +#endif + return CURLE_OK; +} + +static CURLcode set_remote_ip(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; + + /* store remote address and port used in this connection attempt */ + if(!Curl_addr2string(&ctx->addr.sa_addr, ctx->addr.addrlen, + ctx->ip.remote_ip, &ctx->ip.remote_port)) { + char buffer[STRERROR_LEN]; + + ctx->error = errno; + /* malformed address or bug in inet_ntop, try next address */ + failf(data, "sa_addr inet_ntop() failed with errno %d: %s", + errno, Curl_strerror(errno, buffer, sizeof(buffer))); + return CURLE_FAILED_INIT; + } + return CURLE_OK; +} + +static CURLcode cf_socket_open(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; + int error = 0; + bool isconnected = FALSE; + CURLcode result = CURLE_COULDNT_CONNECT; + bool is_tcp; + + (void)data; + DEBUGASSERT(ctx->sock == CURL_SOCKET_BAD); + ctx->started_at = Curl_now(); + result = socket_open(data, &ctx->addr, &ctx->sock); + if(result) + goto out; + + result = set_remote_ip(cf, data); + if(result) + goto out; + +#ifdef USE_IPV6 + if(ctx->addr.family == AF_INET6) { + set_ipv6_v6only(ctx->sock, 0); + infof(data, " Trying [%s]:%d...", ctx->ip.remote_ip, ctx->ip.remote_port); + } + else +#endif + infof(data, " Trying %s:%d...", ctx->ip.remote_ip, ctx->ip.remote_port); + +#ifdef USE_IPV6 + is_tcp = (ctx->addr.family == AF_INET + || ctx->addr.family == AF_INET6) && + ctx->addr.socktype == SOCK_STREAM; +#else + is_tcp = (ctx->addr.family == AF_INET) && + ctx->addr.socktype == SOCK_STREAM; +#endif + if(is_tcp && data->set.tcp_nodelay) + tcpnodelay(data, ctx->sock); + + nosigpipe(data, ctx->sock); + + Curl_sndbufset(ctx->sock); + + if(is_tcp && data->set.tcp_keepalive) + tcpkeepalive(data, ctx->sock); + + if(data->set.fsockopt) { + /* activate callback for setting socket options */ + Curl_set_in_callback(data, true); + error = data->set.fsockopt(data->set.sockopt_client, + ctx->sock, + CURLSOCKTYPE_IPCXN); + Curl_set_in_callback(data, false); + + if(error == CURL_SOCKOPT_ALREADY_CONNECTED) + isconnected = TRUE; + else if(error) { + result = CURLE_ABORTED_BY_CALLBACK; + goto out; + } + } + +#ifndef CURL_DISABLE_BINDLOCAL + /* possibly bind the local end to an IP, interface or port */ + if(ctx->addr.family == AF_INET +#ifdef USE_IPV6 + || ctx->addr.family == AF_INET6 +#endif + ) { + result = bindlocal(data, cf->conn, ctx->sock, ctx->addr.family, + Curl_ipv6_scope(&ctx->addr.sa_addr)); + if(result) { + if(result == CURLE_UNSUPPORTED_PROTOCOL) { + /* The address family is not supported on this interface. + We can continue trying addresses */ + result = CURLE_COULDNT_CONNECT; + } + goto out; + } + } +#endif + + /* set socket non-blocking */ + (void)curlx_nonblock(ctx->sock, TRUE); + ctx->sock_connected = (ctx->addr.socktype != SOCK_DGRAM); +out: + if(result) { + if(ctx->sock != CURL_SOCKET_BAD) { + socket_close(data, cf->conn, TRUE, ctx->sock); + ctx->sock = CURL_SOCKET_BAD; + } + } + else if(isconnected) { + set_local_ip(cf, data); + ctx->connected_at = Curl_now(); + cf->connected = TRUE; + } + CURL_TRC_CF(data, cf, "cf_socket_open() -> %d, fd=%" CURL_FORMAT_SOCKET_T, + result, ctx->sock); + return result; +} + +static int do_connect(struct Curl_cfilter *cf, struct Curl_easy *data, + bool is_tcp_fastopen) +{ + struct cf_socket_ctx *ctx = cf->ctx; +#ifdef TCP_FASTOPEN_CONNECT + int optval = 1; +#endif + int rc = -1; + + (void)data; + if(is_tcp_fastopen) { +#if defined(CONNECT_DATA_IDEMPOTENT) /* Darwin */ +# if defined(HAVE_BUILTIN_AVAILABLE) + /* while connectx function is available since macOS 10.11 / iOS 9, + it did not have the interface declared correctly until + Xcode 9 / macOS SDK 10.13 */ + if(__builtin_available(macOS 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *)) { + sa_endpoints_t endpoints; + endpoints.sae_srcif = 0; + endpoints.sae_srcaddr = NULL; + endpoints.sae_srcaddrlen = 0; + endpoints.sae_dstaddr = &ctx->addr.sa_addr; + endpoints.sae_dstaddrlen = ctx->addr.addrlen; + + rc = connectx(ctx->sock, &endpoints, SAE_ASSOCID_ANY, + CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT, + NULL, 0, NULL, NULL); + } + else { + rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen); + } +# else + rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen); +# endif /* HAVE_BUILTIN_AVAILABLE */ +#elif defined(TCP_FASTOPEN_CONNECT) /* Linux >= 4.11 */ + if(setsockopt(ctx->sock, IPPROTO_TCP, TCP_FASTOPEN_CONNECT, + (void *)&optval, sizeof(optval)) < 0) + infof(data, "Failed to enable TCP Fast Open on fd %" + CURL_FORMAT_SOCKET_T, ctx->sock); + + rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen); +#elif defined(MSG_FASTOPEN) /* old Linux */ + if(cf->conn->given->flags & PROTOPT_SSL) + rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen); + else + rc = 0; /* Do nothing */ +#endif + } + else { + rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen); + } + return rc; +} + +static CURLcode cf_tcp_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + struct cf_socket_ctx *ctx = cf->ctx; + CURLcode result = CURLE_COULDNT_CONNECT; + int rc = 0; + + (void)data; + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + /* TODO: need to support blocking connect? */ + if(blocking) + return CURLE_UNSUPPORTED_PROTOCOL; + + *done = FALSE; /* a very negative world view is best */ + if(ctx->sock == CURL_SOCKET_BAD) { + int error; + + result = cf_socket_open(cf, data); + if(result) + goto out; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + /* Connect TCP socket */ + rc = do_connect(cf, data, cf->conn->bits.tcp_fastopen); + error = SOCKERRNO; + set_local_ip(cf, data); + CURL_TRC_CF(data, cf, "local address %s port %d...", + ctx->ip.local_ip, ctx->ip.local_port); + if(-1 == rc) { + result = socket_connect_result(data, ctx->ip.remote_ip, error); + goto out; + } + } + +#ifdef mpeix + /* Call this function once now, and ignore the results. We do this to + "clear" the error state on the socket so that we can later read it + reliably. This is reported necessary on the MPE/iX operating + system. */ + (void)verifyconnect(ctx->sock, NULL); +#endif + /* check socket for connect */ + rc = SOCKET_WRITABLE(ctx->sock, 0); + + if(rc == 0) { /* no connection yet */ + CURL_TRC_CF(data, cf, "not connected yet"); + return CURLE_OK; + } + else if(rc == CURL_CSELECT_OUT || cf->conn->bits.tcp_fastopen) { + if(verifyconnect(ctx->sock, &ctx->error)) { + /* we are connected with TCP, awesome! */ + ctx->connected_at = Curl_now(); + set_local_ip(cf, data); + *done = TRUE; + cf->connected = TRUE; + CURL_TRC_CF(data, cf, "connected"); + return CURLE_OK; + } + } + else if(rc & CURL_CSELECT_ERR) { + (void)verifyconnect(ctx->sock, &ctx->error); + result = CURLE_COULDNT_CONNECT; + } + +out: + if(result) { + if(ctx->error) { + set_local_ip(cf, data); + data->state.os_errno = ctx->error; + SET_SOCKERRNO(ctx->error); +#ifndef CURL_DISABLE_VERBOSE_STRINGS + { + char buffer[STRERROR_LEN]; + infof(data, "connect to %s port %u from %s port %d failed: %s", + ctx->ip.remote_ip, ctx->ip.remote_port, + ctx->ip.local_ip, ctx->ip.local_port, + Curl_strerror(ctx->error, buffer, sizeof(buffer))); + } +#endif + } + if(ctx->sock != CURL_SOCKET_BAD) { + socket_close(data, cf->conn, TRUE, ctx->sock); + ctx->sock = CURL_SOCKET_BAD; + } + *done = FALSE; + } + return result; +} + +static void cf_socket_get_host(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char **phost, + const char **pdisplay_host, + int *pport) +{ + struct cf_socket_ctx *ctx = cf->ctx; + (void)data; + *phost = cf->conn->host.name; + *pdisplay_host = cf->conn->host.dispname; + *pport = ctx->ip.remote_port; +} + +static void cf_socket_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_socket_ctx *ctx = cf->ctx; + + if(ctx->sock != CURL_SOCKET_BAD) { + if(!cf->connected) { + Curl_pollset_set_out_only(data, ps, ctx->sock); + CURL_TRC_CF(data, cf, "adjust_pollset, !connected, POLLOUT fd=%" + CURL_FORMAT_SOCKET_T, ctx->sock); + } + else if(!ctx->active) { + Curl_pollset_add_in(data, ps, ctx->sock); + CURL_TRC_CF(data, cf, "adjust_pollset, !active, POLLIN fd=%" + CURL_FORMAT_SOCKET_T, ctx->sock); + } + } +} + +static bool cf_socket_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; + int readable; + + (void)data; + if(!Curl_bufq_is_empty(&ctx->recvbuf)) + return TRUE; + + readable = SOCKET_READABLE(ctx->sock, 0); + return (readable > 0 && (readable & CURL_CSELECT_IN)); +} + +static ssize_t cf_socket_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *buf, size_t len, CURLcode *err) +{ + struct cf_socket_ctx *ctx = cf->ctx; + curl_socket_t fdsave; + ssize_t nwritten; + size_t orig_len = len; + + *err = CURLE_OK; + fdsave = cf->conn->sock[cf->sockindex]; + cf->conn->sock[cf->sockindex] = ctx->sock; + +#ifdef DEBUGBUILD + /* simulate network blocking/partial writes */ + if(ctx->wblock_percent > 0) { + unsigned char c = 0; + Curl_rand(data, &c, 1); + if(c >= ((100-ctx->wblock_percent)*256/100)) { + CURL_TRC_CF(data, cf, "send(len=%zu) SIMULATE EWOULDBLOCK", orig_len); + *err = CURLE_AGAIN; + nwritten = -1; + cf->conn->sock[cf->sockindex] = fdsave; + return nwritten; + } + } + if(cf->cft != &Curl_cft_udp && ctx->wpartial_percent > 0 && len > 8) { + len = len * ctx->wpartial_percent / 100; + if(!len) + len = 1; + CURL_TRC_CF(data, cf, "send(len=%zu) SIMULATE partial write of %zu bytes", + orig_len, len); + } +#endif + +#if defined(MSG_FASTOPEN) && !defined(TCP_FASTOPEN_CONNECT) /* Linux */ + if(cf->conn->bits.tcp_fastopen) { + nwritten = sendto(ctx->sock, buf, len, MSG_FASTOPEN, + &cf->conn->remote_addr->sa_addr, + cf->conn->remote_addr->addrlen); + cf->conn->bits.tcp_fastopen = FALSE; + } + else +#endif + nwritten = swrite(ctx->sock, buf, len); + + if(-1 == nwritten) { + int sockerr = SOCKERRNO; + + if( +#ifdef WSAEWOULDBLOCK + /* This is how Windows does it */ + (WSAEWOULDBLOCK == sockerr) +#else + /* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned + due to its inability to send off data without blocking. We therefore + treat both error codes the same here */ + (EWOULDBLOCK == sockerr) || (EAGAIN == sockerr) || (EINTR == sockerr) || + (EINPROGRESS == sockerr) +#endif + ) { + /* this is just a case of EWOULDBLOCK */ + *err = CURLE_AGAIN; + } + else { + char buffer[STRERROR_LEN]; + failf(data, "Send failure: %s", + Curl_strerror(sockerr, buffer, sizeof(buffer))); + data->state.os_errno = sockerr; + *err = CURLE_SEND_ERROR; + } + } + + CURL_TRC_CF(data, cf, "send(len=%zu) -> %d, err=%d", + orig_len, (int)nwritten, *err); + cf->conn->sock[cf->sockindex] = fdsave; + return nwritten; +} + +static ssize_t cf_socket_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, CURLcode *err) +{ + struct cf_socket_ctx *ctx = cf->ctx; + curl_socket_t fdsave; + ssize_t nread; + + *err = CURLE_OK; + + fdsave = cf->conn->sock[cf->sockindex]; + cf->conn->sock[cf->sockindex] = ctx->sock; + +#ifdef DEBUGBUILD + /* simulate network blocking/partial reads */ + if(cf->cft != &Curl_cft_udp && ctx->rblock_percent > 0) { + unsigned char c = 0; + Curl_rand(data, &c, 1); + if(c >= ((100-ctx->rblock_percent)*256/100)) { + CURL_TRC_CF(data, cf, "recv(len=%zu) SIMULATE EWOULDBLOCK", len); + *err = CURLE_AGAIN; + nread = -1; + cf->conn->sock[cf->sockindex] = fdsave; + return nread; + } + } + if(cf->cft != &Curl_cft_udp && ctx->recv_max && ctx->recv_max < len) { + size_t orig_len = len; + len = ctx->recv_max; + CURL_TRC_CF(data, cf, "recv(len=%zu) SIMULATE max read of %zu bytes", + orig_len, len); + } +#endif + + if(ctx->buffer_recv && !Curl_bufq_is_empty(&ctx->recvbuf)) { + CURL_TRC_CF(data, cf, "recv from buffer"); + nread = Curl_bufq_read(&ctx->recvbuf, (unsigned char *)buf, len, err); + } + else { + struct reader_ctx rctx; + + rctx.cf = cf; + rctx.data = data; + + /* "small" reads may trigger filling our buffer, "large" reads + * are probably not worth the additional copy */ + if(ctx->buffer_recv && len < NW_SMALL_READS) { + ssize_t nwritten; + nwritten = Curl_bufq_slurp(&ctx->recvbuf, nw_in_read, &rctx, err); + if(nwritten < 0 && !Curl_bufq_is_empty(&ctx->recvbuf)) { + /* we have a partial read with an error. need to deliver + * what we got, return the error later. */ + CURL_TRC_CF(data, cf, "partial read: empty buffer first"); + nread = Curl_bufq_read(&ctx->recvbuf, (unsigned char *)buf, len, err); + } + else if(nwritten < 0) { + nread = -1; + goto out; + } + else if(nwritten == 0) { + /* eof */ + *err = CURLE_OK; + nread = 0; + } + else { + CURL_TRC_CF(data, cf, "buffered %zd additional bytes", nwritten); + nread = Curl_bufq_read(&ctx->recvbuf, (unsigned char *)buf, len, err); + } + } + else { + nread = nw_in_read(&rctx, (unsigned char *)buf, len, err); + } + } + +out: + CURL_TRC_CF(data, cf, "recv(len=%zu) -> %d, err=%d", len, (int)nread, + *err); + if(nread > 0 && !ctx->got_first_byte) { + ctx->first_byte_at = Curl_now(); + ctx->got_first_byte = TRUE; + } + cf->conn->sock[cf->sockindex] = fdsave; + return nread; +} + +static void cf_socket_active(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; + + /* use this socket from now on */ + cf->conn->sock[cf->sockindex] = ctx->sock; + set_local_ip(cf, data); + if(cf->sockindex == SECONDARYSOCKET) + cf->conn->secondary = ctx->ip; + else + cf->conn->primary = ctx->ip; + /* the first socket info gets some specials */ + if(cf->sockindex == FIRSTSOCKET) { + cf->conn->remote_addr = &ctx->addr; + #ifdef USE_IPV6 + cf->conn->bits.ipv6 = (ctx->addr.family == AF_INET6)? TRUE : FALSE; + #endif + Curl_persistconninfo(data, cf->conn, &ctx->ip); + /* buffering is currently disabled by default because we have stalls + * in parallel transfers where not all buffered data is consumed and no + * socket events happen. + */ + ctx->buffer_recv = FALSE; + } + ctx->active = TRUE; +} + +static CURLcode cf_socket_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + struct cf_socket_ctx *ctx = cf->ctx; + + (void)arg1; + (void)arg2; + switch(event) { + case CF_CTRL_CONN_INFO_UPDATE: + cf_socket_active(cf, data); + break; + case CF_CTRL_DATA_SETUP: + Curl_persistconninfo(data, cf->conn, &ctx->ip); + break; + case CF_CTRL_FORGET_SOCKET: + ctx->sock = CURL_SOCKET_BAD; + break; + } + return CURLE_OK; +} + +static bool cf_socket_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending) +{ + struct cf_socket_ctx *ctx = cf->ctx; + struct pollfd pfd[1]; + int r; + + *input_pending = FALSE; + (void)data; + if(!ctx || ctx->sock == CURL_SOCKET_BAD) + return FALSE; + + /* Check with 0 timeout if there are any events pending on the socket */ + pfd[0].fd = ctx->sock; + pfd[0].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI; + pfd[0].revents = 0; + + r = Curl_poll(pfd, 1, 0); + if(r < 0) { + CURL_TRC_CF(data, cf, "is_alive: poll error, assume dead"); + return FALSE; + } + else if(r == 0) { + CURL_TRC_CF(data, cf, "is_alive: poll timeout, assume alive"); + return TRUE; + } + else if(pfd[0].revents & (POLLERR|POLLHUP|POLLPRI|POLLNVAL)) { + CURL_TRC_CF(data, cf, "is_alive: err/hup/etc events, assume dead"); + return FALSE; + } + + CURL_TRC_CF(data, cf, "is_alive: valid events, looks alive"); + *input_pending = TRUE; + return TRUE; +} + +static CURLcode cf_socket_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_socket_ctx *ctx = cf->ctx; + + switch(query) { + case CF_QUERY_SOCKET: + DEBUGASSERT(pres2); + *((curl_socket_t *)pres2) = ctx->sock; + return CURLE_OK; + case CF_QUERY_CONNECT_REPLY_MS: + if(ctx->got_first_byte) { + timediff_t ms = Curl_timediff(ctx->first_byte_at, ctx->started_at); + *pres1 = (ms < INT_MAX)? (int)ms : INT_MAX; + } + else + *pres1 = -1; + return CURLE_OK; + case CF_QUERY_TIMER_CONNECT: { + struct curltime *when = pres2; + switch(ctx->transport) { + case TRNSPRT_UDP: + case TRNSPRT_QUIC: + /* Since UDP connected sockets work different from TCP, we use the + * time of the first byte from the peer as the "connect" time. */ + if(ctx->got_first_byte) { + *when = ctx->first_byte_at; + break; + } + FALLTHROUGH(); + default: + *when = ctx->connected_at; + break; + } + return CURLE_OK; + } + default: + break; + } + return cf->next? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +struct Curl_cftype Curl_cft_tcp = { + "TCP", + CF_TYPE_IP_CONNECT, + CURL_LOG_LVL_NONE, + cf_socket_destroy, + cf_tcp_connect, + cf_socket_close, + cf_socket_get_host, + cf_socket_adjust_pollset, + cf_socket_data_pending, + cf_socket_send, + cf_socket_recv, + cf_socket_cntrl, + cf_socket_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_socket_query, +}; + +CURLcode Curl_cf_tcp_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai, + int transport) +{ + struct cf_socket_ctx *ctx = NULL; + struct Curl_cfilter *cf = NULL; + CURLcode result; + + (void)data; + (void)conn; + DEBUGASSERT(transport == TRNSPRT_TCP); + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + cf_socket_ctx_init(ctx, ai, transport); + + result = Curl_cf_create(&cf, &Curl_cft_tcp, ctx); + +out: + *pcf = (!result)? cf : NULL; + if(result) { + Curl_safefree(cf); + Curl_safefree(ctx); + } + + return result; +} + +static CURLcode cf_udp_setup_quic(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; + int rc; + + /* QUIC needs a connected socket, nonblocking */ + DEBUGASSERT(ctx->sock != CURL_SOCKET_BAD); + +#if defined(__APPLE__) && defined(USE_OPENSSL_QUIC) + (void)rc; + /* On macOS OpenSSL QUIC fails on connected sockets. + * see: */ +#else + rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen); + if(-1 == rc) { + return socket_connect_result(data, ctx->ip.remote_ip, SOCKERRNO); + } + ctx->sock_connected = TRUE; +#endif + set_local_ip(cf, data); + CURL_TRC_CF(data, cf, "%s socket %" CURL_FORMAT_SOCKET_T + " connected: [%s:%d] -> [%s:%d]", + (ctx->transport == TRNSPRT_QUIC)? "QUIC" : "UDP", + ctx->sock, ctx->ip.local_ip, ctx->ip.local_port, + ctx->ip.remote_ip, ctx->ip.remote_port); + + (void)curlx_nonblock(ctx->sock, TRUE); + switch(ctx->addr.family) { +#if defined(__linux__) && defined(IP_MTU_DISCOVER) + case AF_INET: { + int val = IP_PMTUDISC_DO; + (void)setsockopt(ctx->sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, + sizeof(val)); + break; + } +#endif +#if defined(__linux__) && defined(IPV6_MTU_DISCOVER) + case AF_INET6: { + int val = IPV6_PMTUDISC_DO; + (void)setsockopt(ctx->sock, IPPROTO_IPV6, IPV6_MTU_DISCOVER, &val, + sizeof(val)); + break; + } +#endif + } + return CURLE_OK; +} + +static CURLcode cf_udp_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + struct cf_socket_ctx *ctx = cf->ctx; + CURLcode result = CURLE_COULDNT_CONNECT; + + (void)blocking; + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + *done = FALSE; + if(ctx->sock == CURL_SOCKET_BAD) { + result = cf_socket_open(cf, data); + if(result) { + CURL_TRC_CF(data, cf, "cf_udp_connect(), open failed -> %d", result); + goto out; + } + + if(ctx->transport == TRNSPRT_QUIC) { + result = cf_udp_setup_quic(cf, data); + if(result) + goto out; + CURL_TRC_CF(data, cf, "cf_udp_connect(), opened socket=%" + CURL_FORMAT_SOCKET_T " (%s:%d)", + ctx->sock, ctx->ip.local_ip, ctx->ip.local_port); + } + else { + CURL_TRC_CF(data, cf, "cf_udp_connect(), opened socket=%" + CURL_FORMAT_SOCKET_T " (unconnected)", ctx->sock); + } + *done = TRUE; + cf->connected = TRUE; + } +out: + return result; +} + +struct Curl_cftype Curl_cft_udp = { + "UDP", + CF_TYPE_IP_CONNECT, + CURL_LOG_LVL_NONE, + cf_socket_destroy, + cf_udp_connect, + cf_socket_close, + cf_socket_get_host, + cf_socket_adjust_pollset, + cf_socket_data_pending, + cf_socket_send, + cf_socket_recv, + cf_socket_cntrl, + cf_socket_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_socket_query, +}; + +CURLcode Curl_cf_udp_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai, + int transport) +{ + struct cf_socket_ctx *ctx = NULL; + struct Curl_cfilter *cf = NULL; + CURLcode result; + + (void)data; + (void)conn; + DEBUGASSERT(transport == TRNSPRT_UDP || transport == TRNSPRT_QUIC); + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + cf_socket_ctx_init(ctx, ai, transport); + + result = Curl_cf_create(&cf, &Curl_cft_udp, ctx); + +out: + *pcf = (!result)? cf : NULL; + if(result) { + Curl_safefree(cf); + Curl_safefree(ctx); + } + + return result; +} + +/* this is the TCP filter which can also handle this case */ +struct Curl_cftype Curl_cft_unix = { + "UNIX", + CF_TYPE_IP_CONNECT, + CURL_LOG_LVL_NONE, + cf_socket_destroy, + cf_tcp_connect, + cf_socket_close, + cf_socket_get_host, + cf_socket_adjust_pollset, + cf_socket_data_pending, + cf_socket_send, + cf_socket_recv, + cf_socket_cntrl, + cf_socket_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_socket_query, +}; + +CURLcode Curl_cf_unix_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai, + int transport) +{ + struct cf_socket_ctx *ctx = NULL; + struct Curl_cfilter *cf = NULL; + CURLcode result; + + (void)data; + (void)conn; + DEBUGASSERT(transport == TRNSPRT_UNIX); + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + cf_socket_ctx_init(ctx, ai, transport); + + result = Curl_cf_create(&cf, &Curl_cft_unix, ctx); + +out: + *pcf = (!result)? cf : NULL; + if(result) { + Curl_safefree(cf); + Curl_safefree(ctx); + } + + return result; +} + +static CURLcode cf_tcp_accept_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + /* we start accepted, if we ever close, we cannot go on */ + (void)data; + (void)blocking; + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + return CURLE_FAILED_INIT; +} + +struct Curl_cftype Curl_cft_tcp_accept = { + "TCP-ACCEPT", + CF_TYPE_IP_CONNECT, + CURL_LOG_LVL_NONE, + cf_socket_destroy, + cf_tcp_accept_connect, + cf_socket_close, + cf_socket_get_host, /* TODO: not accurate */ + cf_socket_adjust_pollset, + cf_socket_data_pending, + cf_socket_send, + cf_socket_recv, + cf_socket_cntrl, + cf_socket_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_socket_query, +}; + +CURLcode Curl_conn_tcp_listen_set(struct Curl_easy *data, + struct connectdata *conn, + int sockindex, curl_socket_t *s) +{ + CURLcode result; + struct Curl_cfilter *cf = NULL; + struct cf_socket_ctx *ctx = NULL; + + /* replace any existing */ + Curl_conn_cf_discard_all(data, conn, sockindex); + DEBUGASSERT(conn->sock[sockindex] == CURL_SOCKET_BAD); + + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + ctx->transport = conn->transport; + ctx->sock = *s; + ctx->accepted = FALSE; + result = Curl_cf_create(&cf, &Curl_cft_tcp_accept, ctx); + if(result) + goto out; + Curl_conn_cf_add(data, conn, sockindex, cf); + + conn->sock[sockindex] = ctx->sock; + set_local_ip(cf, data); + ctx->active = TRUE; + ctx->connected_at = Curl_now(); + cf->connected = TRUE; + CURL_TRC_CF(data, cf, "Curl_conn_tcp_listen_set(%" + CURL_FORMAT_SOCKET_T ")", ctx->sock); + +out: + if(result) { + Curl_safefree(cf); + Curl_safefree(ctx); + } + return result; +} + +static void set_accepted_remote_ip(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; +#ifdef HAVE_GETPEERNAME + char buffer[STRERROR_LEN]; + struct Curl_sockaddr_storage ssrem; + curl_socklen_t plen; + + ctx->ip.remote_ip[0] = 0; + ctx->ip.remote_port = 0; + plen = sizeof(ssrem); + memset(&ssrem, 0, plen); + if(getpeername(ctx->sock, (struct sockaddr*) &ssrem, &plen)) { + int error = SOCKERRNO; + failf(data, "getpeername() failed with errno %d: %s", + error, Curl_strerror(error, buffer, sizeof(buffer))); + return; + } + if(!Curl_addr2string((struct sockaddr*)&ssrem, plen, + ctx->ip.remote_ip, &ctx->ip.remote_port)) { + failf(data, "ssrem inet_ntop() failed with errno %d: %s", + errno, Curl_strerror(errno, buffer, sizeof(buffer))); + return; + } +#else + ctx->ip.remote_ip[0] = 0; + ctx->ip.remote_port = 0; + (void)data; +#endif +} + +CURLcode Curl_conn_tcp_accepted_set(struct Curl_easy *data, + struct connectdata *conn, + int sockindex, curl_socket_t *s) +{ + struct Curl_cfilter *cf = NULL; + struct cf_socket_ctx *ctx = NULL; + + cf = conn->cfilter[sockindex]; + if(!cf || cf->cft != &Curl_cft_tcp_accept) + return CURLE_FAILED_INIT; + + ctx = cf->ctx; + /* discard the listen socket */ + socket_close(data, conn, TRUE, ctx->sock); + ctx->sock = *s; + conn->sock[sockindex] = ctx->sock; + set_accepted_remote_ip(cf, data); + set_local_ip(cf, data); + ctx->active = TRUE; + ctx->accepted = TRUE; + ctx->connected_at = Curl_now(); + cf->connected = TRUE; + CURL_TRC_CF(data, cf, "accepted_set(sock=%" CURL_FORMAT_SOCKET_T + ", remote=%s port=%d)", + ctx->sock, ctx->ip.remote_ip, ctx->ip.remote_port); + + return CURLE_OK; +} + +/** + * Return TRUE iff `cf` is a socket filter. + */ +static bool cf_is_socket(struct Curl_cfilter *cf) +{ + return cf && (cf->cft == &Curl_cft_tcp || + cf->cft == &Curl_cft_udp || + cf->cft == &Curl_cft_unix || + cf->cft == &Curl_cft_tcp_accept); +} + +CURLcode Curl_cf_socket_peek(struct Curl_cfilter *cf, + struct Curl_easy *data, + curl_socket_t *psock, + const struct Curl_sockaddr_ex **paddr, + struct ip_quadruple *pip) +{ + (void)data; + if(cf_is_socket(cf) && cf->ctx) { + struct cf_socket_ctx *ctx = cf->ctx; + + if(psock) + *psock = ctx->sock; + if(paddr) + *paddr = &ctx->addr; + if(pip) + *pip = ctx->ip; + return CURLE_OK; + } + return CURLE_FAILED_INIT; +} diff --git a/third_party/curl/lib/cf-socket.h b/third_party/curl/lib/cf-socket.h new file mode 100644 index 0000000..058af50 --- /dev/null +++ b/third_party/curl/lib/cf-socket.h @@ -0,0 +1,171 @@ +#ifndef HEADER_CURL_CF_SOCKET_H +#define HEADER_CURL_CF_SOCKET_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "nonblock.h" /* for curlx_nonblock(), formerly Curl_nonblock() */ +#include "sockaddr.h" + +struct Curl_addrinfo; +struct Curl_cfilter; +struct Curl_easy; +struct connectdata; +struct Curl_sockaddr_ex; +struct ip_quadruple; + +/* + * The Curl_sockaddr_ex structure is basically libcurl's external API + * curl_sockaddr structure with enough space available to directly hold any + * protocol-specific address structures. The variable declared here will be + * used to pass / receive data to/from the fopensocket callback if this has + * been set, before that, it is initialized from parameters. + */ +struct Curl_sockaddr_ex { + int family; + int socktype; + int protocol; + unsigned int addrlen; + union { + struct sockaddr addr; + struct Curl_sockaddr_storage buff; + } _sa_ex_u; +}; +#define sa_addr _sa_ex_u.addr + + +/* + * Create a socket based on info from 'conn' and 'ai'. + * + * Fill in 'addr' and 'sockfd' accordingly if OK is returned. If the open + * socket callback is set, used that! + * + */ +CURLcode Curl_socket_open(struct Curl_easy *data, + const struct Curl_addrinfo *ai, + struct Curl_sockaddr_ex *addr, + int transport, + curl_socket_t *sockfd); + +int Curl_socket_close(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t sock); + +#ifdef USE_WINSOCK +/* When you run a program that uses the Windows Sockets API, you may + experience slow performance when you copy data to a TCP server. + + https://support.microsoft.com/kb/823764 + + Work-around: Make the Socket Send Buffer Size Larger Than the Program Send + Buffer Size + +*/ +void Curl_sndbufset(curl_socket_t sockfd); +#else +#define Curl_sndbufset(y) Curl_nop_stmt +#endif + +/** + * Assign the address `ai` to the Curl_sockaddr_ex `dest` and + * set the transport used. + */ +void Curl_sock_assign_addr(struct Curl_sockaddr_ex *dest, + const struct Curl_addrinfo *ai, + int transport); + +/** + * Creates a cfilter that opens a TCP socket to the given address + * when calling its `connect` implementation. + * The filter will not touch any connection/data flags and can be + * used in happy eyeballing. Once selected for use, its `_active()` + * method needs to be called. + */ +CURLcode Curl_cf_tcp_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai, + int transport); + +/** + * Creates a cfilter that opens a UDP socket to the given address + * when calling its `connect` implementation. + * The filter will not touch any connection/data flags and can be + * used in happy eyeballing. Once selected for use, its `_active()` + * method needs to be called. + */ +CURLcode Curl_cf_udp_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai, + int transport); + +/** + * Creates a cfilter that opens a UNIX socket to the given address + * when calling its `connect` implementation. + * The filter will not touch any connection/data flags and can be + * used in happy eyeballing. Once selected for use, its `_active()` + * method needs to be called. + */ +CURLcode Curl_cf_unix_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai, + int transport); + +/** + * Creates a cfilter that keeps a listening socket. + */ +CURLcode Curl_conn_tcp_listen_set(struct Curl_easy *data, + struct connectdata *conn, + int sockindex, + curl_socket_t *s); + +/** + * Replace the listen socket with the accept()ed one. + */ +CURLcode Curl_conn_tcp_accepted_set(struct Curl_easy *data, + struct connectdata *conn, + int sockindex, + curl_socket_t *s); + +/** + * Peek at the socket and remote ip/port the socket filter is using. + * The filter owns all returned values. + * @param psock pointer to hold socket descriptor or NULL + * @param paddr pointer to hold addr reference or NULL + * @param pip pointer to get IP quadruple or NULL + * Returns error if the filter is of invalid type. + */ +CURLcode Curl_cf_socket_peek(struct Curl_cfilter *cf, + struct Curl_easy *data, + curl_socket_t *psock, + const struct Curl_sockaddr_ex **paddr, + struct ip_quadruple *pip); + +extern struct Curl_cftype Curl_cft_tcp; +extern struct Curl_cftype Curl_cft_udp; +extern struct Curl_cftype Curl_cft_unix; +extern struct Curl_cftype Curl_cft_tcp_accept; + +#endif /* HEADER_CURL_CF_SOCKET_H */ diff --git a/third_party/curl/lib/cfilters.c b/third_party/curl/lib/cfilters.c new file mode 100644 index 0000000..a327fa1 --- /dev/null +++ b/third_party/curl/lib/cfilters.c @@ -0,0 +1,861 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "urldata.h" +#include "strerror.h" +#include "cfilters.h" +#include "connect.h" +#include "url.h" /* for Curl_safefree() */ +#include "sendf.h" +#include "sockaddr.h" /* required for Curl_sockaddr_storage */ +#include "multiif.h" +#include "progress.h" +#include "select.h" +#include "warnless.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#ifndef ARRAYSIZE +#define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) +#endif + +#ifdef DEBUGBUILD +/* used by unit2600.c */ +void Curl_cf_def_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + cf->connected = FALSE; + if(cf->next) + cf->next->cft->do_close(cf->next, data); +} +#endif + +static void conn_report_connect_stats(struct Curl_easy *data, + struct connectdata *conn); + +void Curl_cf_def_get_host(struct Curl_cfilter *cf, struct Curl_easy *data, + const char **phost, const char **pdisplay_host, + int *pport) +{ + if(cf->next) + cf->next->cft->get_host(cf->next, data, phost, pdisplay_host, pport); + else { + *phost = cf->conn->host.name; + *pdisplay_host = cf->conn->host.dispname; + *pport = cf->conn->primary.remote_port; + } +} + +void Curl_cf_def_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + /* NOP */ + (void)cf; + (void)data; + (void)ps; +} + +bool Curl_cf_def_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + return cf->next? + cf->next->cft->has_data_pending(cf->next, data) : FALSE; +} + +ssize_t Curl_cf_def_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *buf, size_t len, CURLcode *err) +{ + return cf->next? + cf->next->cft->do_send(cf->next, data, buf, len, err) : + CURLE_RECV_ERROR; +} + +ssize_t Curl_cf_def_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, CURLcode *err) +{ + return cf->next? + cf->next->cft->do_recv(cf->next, data, buf, len, err) : + CURLE_SEND_ERROR; +} + +bool Curl_cf_def_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending) +{ + return cf->next? + cf->next->cft->is_alive(cf->next, data, input_pending) : + FALSE; /* pessimistic in absence of data */ +} + +CURLcode Curl_cf_def_conn_keep_alive(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + return cf->next? + cf->next->cft->keep_alive(cf->next, data) : + CURLE_OK; +} + +CURLcode Curl_cf_def_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + return cf->next? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +void Curl_conn_cf_discard_chain(struct Curl_cfilter **pcf, + struct Curl_easy *data) +{ + struct Curl_cfilter *cfn, *cf = *pcf; + + if(cf) { + *pcf = NULL; + while(cf) { + cfn = cf->next; + /* prevent destroying filter to mess with its sub-chain, since + * we have the reference now and will call destroy on it. + */ + cf->next = NULL; + cf->cft->destroy(cf, data); + free(cf); + cf = cfn; + } + } +} + +void Curl_conn_cf_discard_all(struct Curl_easy *data, + struct connectdata *conn, int index) +{ + Curl_conn_cf_discard_chain(&conn->cfilter[index], data); +} + +void Curl_conn_close(struct Curl_easy *data, int index) +{ + struct Curl_cfilter *cf; + + DEBUGASSERT(data->conn); + /* it is valid to call that without filters being present */ + cf = data->conn->cfilter[index]; + if(cf) { + cf->cft->do_close(cf, data); + } +} + +ssize_t Curl_cf_recv(struct Curl_easy *data, int num, char *buf, + size_t len, CURLcode *code) +{ + struct Curl_cfilter *cf; + + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + *code = CURLE_OK; + cf = data->conn->cfilter[num]; + while(cf && !cf->connected) { + cf = cf->next; + } + if(cf) { + ssize_t nread = cf->cft->do_recv(cf, data, buf, len, code); + DEBUGASSERT(nread >= 0 || *code); + DEBUGASSERT(nread < 0 || !*code); + return nread; + } + failf(data, "recv: no filter connected"); + *code = CURLE_FAILED_INIT; + return -1; +} + +ssize_t Curl_cf_send(struct Curl_easy *data, int num, + const void *mem, size_t len, CURLcode *code) +{ + struct Curl_cfilter *cf; + + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + *code = CURLE_OK; + cf = data->conn->cfilter[num]; + while(cf && !cf->connected) { + cf = cf->next; + } + if(cf) { + ssize_t nwritten = cf->cft->do_send(cf, data, mem, len, code); + DEBUGASSERT(nwritten >= 0 || *code); + DEBUGASSERT(nwritten < 0 || !*code || !len); + return nwritten; + } + failf(data, "send: no filter connected"); + DEBUGASSERT(0); + *code = CURLE_FAILED_INIT; + return -1; +} + +CURLcode Curl_cf_create(struct Curl_cfilter **pcf, + const struct Curl_cftype *cft, + void *ctx) +{ + struct Curl_cfilter *cf; + CURLcode result = CURLE_OUT_OF_MEMORY; + + DEBUGASSERT(cft); + cf = calloc(1, sizeof(*cf)); + if(!cf) + goto out; + + cf->cft = cft; + cf->ctx = ctx; + result = CURLE_OK; +out: + *pcf = cf; + return result; +} + +void Curl_conn_cf_add(struct Curl_easy *data, + struct connectdata *conn, + int index, + struct Curl_cfilter *cf) +{ + (void)data; + DEBUGASSERT(conn); + DEBUGASSERT(!cf->conn); + DEBUGASSERT(!cf->next); + + cf->next = conn->cfilter[index]; + cf->conn = conn; + cf->sockindex = index; + conn->cfilter[index] = cf; + CURL_TRC_CF(data, cf, "added"); +} + +void Curl_conn_cf_insert_after(struct Curl_cfilter *cf_at, + struct Curl_cfilter *cf_new) +{ + struct Curl_cfilter *tail, **pnext; + + DEBUGASSERT(cf_at); + DEBUGASSERT(cf_new); + DEBUGASSERT(!cf_new->conn); + + tail = cf_at->next; + cf_at->next = cf_new; + do { + cf_new->conn = cf_at->conn; + cf_new->sockindex = cf_at->sockindex; + pnext = &cf_new->next; + cf_new = cf_new->next; + } while(cf_new); + *pnext = tail; +} + +bool Curl_conn_cf_discard_sub(struct Curl_cfilter *cf, + struct Curl_cfilter *discard, + struct Curl_easy *data, + bool destroy_always) +{ + struct Curl_cfilter **pprev = &cf->next; + bool found = FALSE; + + /* remove from sub-chain and destroy */ + DEBUGASSERT(cf); + while(*pprev) { + if(*pprev == cf) { + *pprev = discard->next; + discard->next = NULL; + found = TRUE; + break; + } + pprev = &((*pprev)->next); + } + if(found || destroy_always) { + discard->next = NULL; + discard->cft->destroy(discard, data); + free(discard); + } + return found; +} + +CURLcode Curl_conn_cf_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + if(cf) + return cf->cft->do_connect(cf, data, blocking, done); + return CURLE_FAILED_INIT; +} + +void Curl_conn_cf_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + if(cf) + cf->cft->do_close(cf, data); +} + +ssize_t Curl_conn_cf_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *buf, size_t len, CURLcode *err) +{ + if(cf) + return cf->cft->do_send(cf, data, buf, len, err); + *err = CURLE_SEND_ERROR; + return -1; +} + +ssize_t Curl_conn_cf_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, CURLcode *err) +{ + if(cf) + return cf->cft->do_recv(cf, data, buf, len, err); + *err = CURLE_RECV_ERROR; + return -1; +} + +CURLcode Curl_conn_connect(struct Curl_easy *data, + int sockindex, + bool blocking, + bool *done) +{ + struct Curl_cfilter *cf; + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + + cf = data->conn->cfilter[sockindex]; + DEBUGASSERT(cf); + if(!cf) + return CURLE_FAILED_INIT; + + *done = cf->connected; + if(!*done) { + result = cf->cft->do_connect(cf, data, blocking, done); + if(!result && *done) { + Curl_conn_ev_update_info(data, data->conn); + conn_report_connect_stats(data, data->conn); + data->conn->keepalive = Curl_now(); + } + else if(result) { + conn_report_connect_stats(data, data->conn); + } + } + + return result; +} + +bool Curl_conn_is_connected(struct connectdata *conn, int sockindex) +{ + struct Curl_cfilter *cf; + + cf = conn->cfilter[sockindex]; + return cf && cf->connected; +} + +bool Curl_conn_is_ip_connected(struct Curl_easy *data, int sockindex) +{ + struct Curl_cfilter *cf; + + cf = data->conn->cfilter[sockindex]; + while(cf) { + if(cf->connected) + return TRUE; + if(cf->cft->flags & CF_TYPE_IP_CONNECT) + return FALSE; + cf = cf->next; + } + return FALSE; +} + +bool Curl_conn_cf_is_ssl(struct Curl_cfilter *cf) +{ + for(; cf; cf = cf->next) { + if(cf->cft->flags & CF_TYPE_SSL) + return TRUE; + if(cf->cft->flags & CF_TYPE_IP_CONNECT) + return FALSE; + } + return FALSE; +} + +bool Curl_conn_is_ssl(struct connectdata *conn, int sockindex) +{ + return conn? Curl_conn_cf_is_ssl(conn->cfilter[sockindex]) : FALSE; +} + +bool Curl_conn_is_multiplex(struct connectdata *conn, int sockindex) +{ + struct Curl_cfilter *cf = conn? conn->cfilter[sockindex] : NULL; + + for(; cf; cf = cf->next) { + if(cf->cft->flags & CF_TYPE_MULTIPLEX) + return TRUE; + if(cf->cft->flags & CF_TYPE_IP_CONNECT + || cf->cft->flags & CF_TYPE_SSL) + return FALSE; + } + return FALSE; +} + +bool Curl_conn_data_pending(struct Curl_easy *data, int sockindex) +{ + struct Curl_cfilter *cf; + + (void)data; + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + + cf = data->conn->cfilter[sockindex]; + while(cf && !cf->connected) { + cf = cf->next; + } + if(cf) { + return cf->cft->has_data_pending(cf, data); + } + return FALSE; +} + +void Curl_conn_cf_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + /* Get the lowest not-connected filter, if there are any */ + while(cf && !cf->connected && cf->next && !cf->next->connected) + cf = cf->next; + /* From there on, give all filters a chance to adjust the pollset. + * Lower filters are called later, so they may override */ + while(cf) { + cf->cft->adjust_pollset(cf, data, ps); + cf = cf->next; + } +} + +void Curl_conn_adjust_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + int i; + + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + for(i = 0; i < 2; ++i) { + Curl_conn_cf_adjust_pollset(data->conn->cfilter[i], data, ps); + } +} + +void Curl_conn_get_host(struct Curl_easy *data, int sockindex, + const char **phost, const char **pdisplay_host, + int *pport) +{ + struct Curl_cfilter *cf; + + DEBUGASSERT(data->conn); + cf = data->conn->cfilter[sockindex]; + if(cf) { + cf->cft->get_host(cf, data, phost, pdisplay_host, pport); + } + else { + /* Some filter ask during shutdown for this, mainly for debugging + * purposes. We hand out the defaults, however this is not always + * accurate, as the connection might be tunneled, etc. But all that + * state is already gone here. */ + *phost = data->conn->host.name; + *pdisplay_host = data->conn->host.dispname; + *pport = data->conn->remote_port; + } +} + +CURLcode Curl_cf_def_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + (void)cf; + (void)data; + (void)event; + (void)arg1; + (void)arg2; + return CURLE_OK; +} + +CURLcode Curl_conn_cf_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool ignore_result, + int event, int arg1, void *arg2) +{ + CURLcode result = CURLE_OK; + + for(; cf; cf = cf->next) { + if(Curl_cf_def_cntrl == cf->cft->cntrl) + continue; + result = cf->cft->cntrl(cf, data, event, arg1, arg2); + if(!ignore_result && result) + break; + } + return result; +} + +curl_socket_t Curl_conn_cf_get_socket(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + curl_socket_t sock; + if(cf && !cf->cft->query(cf, data, CF_QUERY_SOCKET, NULL, &sock)) + return sock; + return CURL_SOCKET_BAD; +} + +curl_socket_t Curl_conn_get_socket(struct Curl_easy *data, int sockindex) +{ + struct Curl_cfilter *cf; + + cf = data->conn? data->conn->cfilter[sockindex] : NULL; + /* if the top filter has not connected, ask it (and its sub-filters) + * for the socket. Otherwise conn->sock[sockindex] should have it. + */ + if(cf && !cf->connected) + return Curl_conn_cf_get_socket(cf, data); + return data->conn? data->conn->sock[sockindex] : CURL_SOCKET_BAD; +} + +void Curl_conn_forget_socket(struct Curl_easy *data, int sockindex) +{ + if(data->conn) { + struct Curl_cfilter *cf = data->conn->cfilter[sockindex]; + if(cf) + (void)Curl_conn_cf_cntrl(cf, data, TRUE, + CF_CTRL_FORGET_SOCKET, 0, NULL); + fake_sclose(data->conn->sock[sockindex]); + data->conn->sock[sockindex] = CURL_SOCKET_BAD; + } +} + +static CURLcode cf_cntrl_all(struct connectdata *conn, + struct Curl_easy *data, + bool ignore_result, + int event, int arg1, void *arg2) +{ + CURLcode result = CURLE_OK; + size_t i; + + for(i = 0; i < ARRAYSIZE(conn->cfilter); ++i) { + result = Curl_conn_cf_cntrl(conn->cfilter[i], data, ignore_result, + event, arg1, arg2); + if(!ignore_result && result) + break; + } + return result; +} + +void Curl_conn_ev_data_attach(struct connectdata *conn, + struct Curl_easy *data) +{ + cf_cntrl_all(conn, data, TRUE, CF_CTRL_DATA_ATTACH, 0, NULL); +} + +void Curl_conn_ev_data_detach(struct connectdata *conn, + struct Curl_easy *data) +{ + cf_cntrl_all(conn, data, TRUE, CF_CTRL_DATA_DETACH, 0, NULL); +} + +CURLcode Curl_conn_ev_data_setup(struct Curl_easy *data) +{ + return cf_cntrl_all(data->conn, data, FALSE, + CF_CTRL_DATA_SETUP, 0, NULL); +} + +CURLcode Curl_conn_ev_data_idle(struct Curl_easy *data) +{ + return cf_cntrl_all(data->conn, data, FALSE, + CF_CTRL_DATA_IDLE, 0, NULL); +} + +/** + * Notify connection filters that the transfer represented by `data` + * is done with sending data (e.g. has uploaded everything). + */ +void Curl_conn_ev_data_done_send(struct Curl_easy *data) +{ + cf_cntrl_all(data->conn, data, TRUE, CF_CTRL_DATA_DONE_SEND, 0, NULL); +} + +/** + * Notify connection filters that the transfer represented by `data` + * is finished - eventually premature, e.g. before being complete. + */ +void Curl_conn_ev_data_done(struct Curl_easy *data, bool premature) +{ + cf_cntrl_all(data->conn, data, TRUE, CF_CTRL_DATA_DONE, premature, NULL); +} + +CURLcode Curl_conn_ev_data_pause(struct Curl_easy *data, bool do_pause) +{ + return cf_cntrl_all(data->conn, data, FALSE, + CF_CTRL_DATA_PAUSE, do_pause, NULL); +} + +void Curl_conn_ev_update_info(struct Curl_easy *data, + struct connectdata *conn) +{ + cf_cntrl_all(conn, data, TRUE, CF_CTRL_CONN_INFO_UPDATE, 0, NULL); +} + +/** + * Update connection statistics + */ +static void conn_report_connect_stats(struct Curl_easy *data, + struct connectdata *conn) +{ + struct Curl_cfilter *cf = conn->cfilter[FIRSTSOCKET]; + if(cf) { + struct curltime connected; + struct curltime appconnected; + + memset(&connected, 0, sizeof(connected)); + cf->cft->query(cf, data, CF_QUERY_TIMER_CONNECT, NULL, &connected); + if(connected.tv_sec || connected.tv_usec) + Curl_pgrsTimeWas(data, TIMER_CONNECT, connected); + + memset(&appconnected, 0, sizeof(appconnected)); + cf->cft->query(cf, data, CF_QUERY_TIMER_APPCONNECT, NULL, &appconnected); + if(appconnected.tv_sec || appconnected.tv_usec) + Curl_pgrsTimeWas(data, TIMER_APPCONNECT, appconnected); + } +} + +bool Curl_conn_is_alive(struct Curl_easy *data, struct connectdata *conn, + bool *input_pending) +{ + struct Curl_cfilter *cf = conn->cfilter[FIRSTSOCKET]; + return cf && !cf->conn->bits.close && + cf->cft->is_alive(cf, data, input_pending); +} + +CURLcode Curl_conn_keep_alive(struct Curl_easy *data, + struct connectdata *conn, + int sockindex) +{ + struct Curl_cfilter *cf = conn->cfilter[sockindex]; + return cf? cf->cft->keep_alive(cf, data) : CURLE_OK; +} + +size_t Curl_conn_get_max_concurrent(struct Curl_easy *data, + struct connectdata *conn, + int sockindex) +{ + CURLcode result; + int n = 0; + + struct Curl_cfilter *cf = conn->cfilter[sockindex]; + result = cf? cf->cft->query(cf, data, CF_QUERY_MAX_CONCURRENT, + &n, NULL) : CURLE_UNKNOWN_OPTION; + return (result || n <= 0)? 1 : (size_t)n; +} + +int Curl_conn_get_stream_error(struct Curl_easy *data, + struct connectdata *conn, + int sockindex) +{ + CURLcode result; + int n = 0; + + struct Curl_cfilter *cf = conn->cfilter[sockindex]; + result = cf? cf->cft->query(cf, data, CF_QUERY_STREAM_ERROR, + &n, NULL) : CURLE_UNKNOWN_OPTION; + return (result || n < 0)? 0 : n; +} + +int Curl_conn_sockindex(struct Curl_easy *data, curl_socket_t sockfd) +{ + if(data && data->conn && + sockfd != CURL_SOCKET_BAD && sockfd == data->conn->sock[SECONDARYSOCKET]) + return SECONDARYSOCKET; + return FIRSTSOCKET; +} + +CURLcode Curl_conn_recv(struct Curl_easy *data, int sockindex, + char *buf, size_t blen, ssize_t *n) +{ + CURLcode result = CURLE_OK; + ssize_t nread; + + DEBUGASSERT(data->conn); + nread = data->conn->recv[sockindex](data, sockindex, buf, blen, &result); + DEBUGASSERT(nread >= 0 || result); + DEBUGASSERT(nread < 0 || !result); + *n = (nread >= 0)? (size_t)nread : 0; + return result; +} + +CURLcode Curl_conn_send(struct Curl_easy *data, int sockindex, + const void *buf, size_t blen, + size_t *pnwritten) +{ + ssize_t nwritten; + CURLcode result = CURLE_OK; + struct connectdata *conn; + + DEBUGASSERT(sockindex >= 0 && sockindex < 2); + DEBUGASSERT(pnwritten); + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + conn = data->conn; +#ifdef CURLDEBUG + { + /* Allow debug builds to override this logic to force short sends + */ + char *p = getenv("CURL_SMALLSENDS"); + if(p) { + size_t altsize = (size_t)strtoul(p, NULL, 10); + if(altsize) + blen = CURLMIN(blen, altsize); + } + } +#endif + nwritten = conn->send[sockindex](data, sockindex, buf, blen, &result); + DEBUGASSERT((nwritten >= 0) || result); + *pnwritten = (nwritten < 0)? 0 : (size_t)nwritten; + return result; +} + +void Curl_pollset_reset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + size_t i; + (void)data; + memset(ps, 0, sizeof(*ps)); + for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) + ps->sockets[i] = CURL_SOCKET_BAD; +} + +/** + * + */ +void Curl_pollset_change(struct Curl_easy *data, + struct easy_pollset *ps, curl_socket_t sock, + int add_flags, int remove_flags) +{ + unsigned int i; + + (void)data; + DEBUGASSERT(VALID_SOCK(sock)); + if(!VALID_SOCK(sock)) + return; + + DEBUGASSERT(add_flags <= (CURL_POLL_IN|CURL_POLL_OUT)); + DEBUGASSERT(remove_flags <= (CURL_POLL_IN|CURL_POLL_OUT)); + DEBUGASSERT((add_flags&remove_flags) == 0); /* no overlap */ + for(i = 0; i < ps->num; ++i) { + if(ps->sockets[i] == sock) { + ps->actions[i] &= (unsigned char)(~remove_flags); + ps->actions[i] |= (unsigned char)add_flags; + /* all gone? remove socket */ + if(!ps->actions[i]) { + if((i + 1) < ps->num) { + memmove(&ps->sockets[i], &ps->sockets[i + 1], + (ps->num - (i + 1)) * sizeof(ps->sockets[0])); + memmove(&ps->actions[i], &ps->actions[i + 1], + (ps->num - (i + 1)) * sizeof(ps->actions[0])); + } + --ps->num; + } + return; + } + } + /* not present */ + if(add_flags) { + /* Having more SOCKETS per easy handle than what is defined + * is a programming error. This indicates that we need + * to raise this limit, making easy_pollset larger. + * Since we use this in tight loops, we do not want to make + * the pollset dynamic unnecessarily. + * The current maximum in practise is HTTP/3 eyeballing where + * we have up to 4 sockets involved in connection setup. + */ + DEBUGASSERT(i < MAX_SOCKSPEREASYHANDLE); + if(i < MAX_SOCKSPEREASYHANDLE) { + ps->sockets[i] = sock; + ps->actions[i] = (unsigned char)add_flags; + ps->num = i + 1; + } + } +} + +void Curl_pollset_set(struct Curl_easy *data, + struct easy_pollset *ps, curl_socket_t sock, + bool do_in, bool do_out) +{ + Curl_pollset_change(data, ps, sock, + (do_in?CURL_POLL_IN:0)|(do_out?CURL_POLL_OUT:0), + (!do_in?CURL_POLL_IN:0)|(!do_out?CURL_POLL_OUT:0)); +} + +static void ps_add(struct Curl_easy *data, struct easy_pollset *ps, + int bitmap, curl_socket_t *socks) +{ + if(bitmap) { + int i; + for(i = 0; i < MAX_SOCKSPEREASYHANDLE; ++i) { + if(!(bitmap & GETSOCK_MASK_RW(i)) || !VALID_SOCK((socks[i]))) { + break; + } + if(bitmap & GETSOCK_READSOCK(i)) { + if(bitmap & GETSOCK_WRITESOCK(i)) + Curl_pollset_add_inout(data, ps, socks[i]); + else + /* is READ, since we checked MASK_RW above */ + Curl_pollset_add_in(data, ps, socks[i]); + } + else + Curl_pollset_add_out(data, ps, socks[i]); + } + } +} + +void Curl_pollset_add_socks(struct Curl_easy *data, + struct easy_pollset *ps, + int (*get_socks_cb)(struct Curl_easy *data, + curl_socket_t *socks)) +{ + curl_socket_t socks[MAX_SOCKSPEREASYHANDLE]; + int bitmap; + + bitmap = get_socks_cb(data, socks); + ps_add(data, ps, bitmap, socks); +} + +void Curl_pollset_check(struct Curl_easy *data, + struct easy_pollset *ps, curl_socket_t sock, + bool *pwant_read, bool *pwant_write) +{ + unsigned int i; + + (void)data; + DEBUGASSERT(VALID_SOCK(sock)); + for(i = 0; i < ps->num; ++i) { + if(ps->sockets[i] == sock) { + *pwant_read = !!(ps->actions[i] & CURL_POLL_IN); + *pwant_write = !!(ps->actions[i] & CURL_POLL_OUT); + return; + } + } + *pwant_read = *pwant_write = FALSE; +} diff --git a/third_party/curl/lib/cfilters.h b/third_party/curl/lib/cfilters.h new file mode 100644 index 0000000..dcfc1b7 --- /dev/null +++ b/third_party/curl/lib/cfilters.h @@ -0,0 +1,644 @@ +#ifndef HEADER_CURL_CFILTERS_H +#define HEADER_CURL_CFILTERS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + + +struct Curl_cfilter; +struct Curl_easy; +struct Curl_dns_entry; +struct connectdata; + +/* Callback to destroy resources held by this filter instance. + * Implementations MUST NOT chain calls to cf->next. + */ +typedef void Curl_cft_destroy_this(struct Curl_cfilter *cf, + struct Curl_easy *data); + +typedef void Curl_cft_close(struct Curl_cfilter *cf, + struct Curl_easy *data); + +typedef CURLcode Curl_cft_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done); + +/* Return the hostname and port the connection goes to. + * This may change with the connection state of filters when tunneling + * is involved. + * @param cf the filter to ask + * @param data the easy handle currently active + * @param phost on return, points to the relevant, real hostname. + * this is owned by the connection. + * @param pdisplay_host on return, points to the printable hostname. + * this is owned by the connection. + * @param pport on return, contains the port number + */ +typedef void Curl_cft_get_host(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char **phost, + const char **pdisplay_host, + int *pport); + +struct easy_pollset; + +/* Passing in an easy_pollset for monitoring of sockets, let + * filters add or remove sockets actions (CURL_POLL_OUT, CURL_POLL_IN). + * This may add a socket or, in case no actions remain, remove + * a socket from the set. + * + * Filter implementations need to call filters "below" *after* they have + * made their adjustments. This allows lower filters to override "upper" + * actions. If a "lower" filter is unable to write, it needs to be able + * to disallow POLL_OUT. + * + * A filter without own restrictions/preferences should not modify + * the pollset. Filters, whose filter "below" is not connected, should + * also do no adjustments. + * + * Examples: a TLS handshake, while ongoing, might remove POLL_IN + * when it needs to write, or vice versa. A HTTP/2 filter might remove + * POLL_OUT when a stream window is exhausted and a WINDOW_UPDATE needs + * to be received first and add instead POLL_IN. + * + * @param cf the filter to ask + * @param data the easy handle the pollset is about + * @param ps the pollset (inout) for the easy handle + */ +typedef void Curl_cft_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps); + +typedef bool Curl_cft_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data); + +typedef ssize_t Curl_cft_send(struct Curl_cfilter *cf, + struct Curl_easy *data, /* transfer */ + const void *buf, /* data to write */ + size_t len, /* amount to write */ + CURLcode *err); /* error to return */ + +typedef ssize_t Curl_cft_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, /* transfer */ + char *buf, /* store data here */ + size_t len, /* amount to read */ + CURLcode *err); /* error to return */ + +typedef bool Curl_cft_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending); + +typedef CURLcode Curl_cft_conn_keep_alive(struct Curl_cfilter *cf, + struct Curl_easy *data); + +/** + * Events/controls for connection filters, their arguments and + * return code handling. Filter callbacks are invoked "top down". + * Return code handling: + * "first fail" meaning that the first filter returning != CURLE_OK, will + * abort further event distribution and determine the result. + * "ignored" meaning return values are ignored and the event is distributed + * to all filters in the chain. Overall result is always CURLE_OK. + */ +/* data event arg1 arg2 return */ +#define CF_CTRL_DATA_ATTACH 1 /* 0 NULL ignored */ +#define CF_CTRL_DATA_DETACH 2 /* 0 NULL ignored */ +#define CF_CTRL_DATA_SETUP 4 /* 0 NULL first fail */ +#define CF_CTRL_DATA_IDLE 5 /* 0 NULL first fail */ +#define CF_CTRL_DATA_PAUSE 6 /* on/off NULL first fail */ +#define CF_CTRL_DATA_DONE 7 /* premature NULL ignored */ +#define CF_CTRL_DATA_DONE_SEND 8 /* 0 NULL ignored */ +/* update conn info at connection and data */ +#define CF_CTRL_CONN_INFO_UPDATE (256+0) /* 0 NULL ignored */ +#define CF_CTRL_FORGET_SOCKET (256+1) /* 0 NULL ignored */ + +/** + * Handle event/control for the filter. + * Implementations MUST NOT chain calls to cf->next. + */ +typedef CURLcode Curl_cft_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2); + + +/** + * Queries to ask via a `Curl_cft_query *query` method on a cfilter chain. + * - MAX_CONCURRENT: the maximum number of parallel transfers the filter + * chain expects to handle at the same time. + * default: 1 if no filter overrides. + * - CONNECT_REPLY_MS: milliseconds until the first indication of a server + * response was received on a connect. For TCP, this + * reflects the time until the socket connected. On UDP + * this gives the time the first bytes from the server + * were received. + * -1 if not determined yet. + * - CF_QUERY_SOCKET: the socket used by the filter chain + */ +/* query res1 res2 */ +#define CF_QUERY_MAX_CONCURRENT 1 /* number - */ +#define CF_QUERY_CONNECT_REPLY_MS 2 /* number - */ +#define CF_QUERY_SOCKET 3 /* - curl_socket_t */ +#define CF_QUERY_TIMER_CONNECT 4 /* - struct curltime */ +#define CF_QUERY_TIMER_APPCONNECT 5 /* - struct curltime */ +#define CF_QUERY_STREAM_ERROR 6 /* error code - */ + +/** + * Query the cfilter for properties. Filters ignorant of a query will + * pass it "down" the filter chain. + */ +typedef CURLcode Curl_cft_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2); + +/** + * Type flags for connection filters. A filter can have none, one or + * many of those. Use to evaluate state/capabilities of a filter chain. + * + * CF_TYPE_IP_CONNECT: provides an IP connection or sth equivalent, like + * a CONNECT tunnel, a UNIX domain socket, a QUIC + * connection, etc. + * CF_TYPE_SSL: provide SSL/TLS + * CF_TYPE_MULTIPLEX: provides multiplexing of easy handles + * CF_TYPE_PROXY provides proxying + */ +#define CF_TYPE_IP_CONNECT (1 << 0) +#define CF_TYPE_SSL (1 << 1) +#define CF_TYPE_MULTIPLEX (1 << 2) +#define CF_TYPE_PROXY (1 << 3) + +/* A connection filter type, e.g. specific implementation. */ +struct Curl_cftype { + const char *name; /* name of the filter type */ + int flags; /* flags of filter type */ + int log_level; /* log level for such filters */ + Curl_cft_destroy_this *destroy; /* destroy resources of this cf */ + Curl_cft_connect *do_connect; /* establish connection */ + Curl_cft_close *do_close; /* close conn */ + Curl_cft_get_host *get_host; /* host filter talks to */ + Curl_cft_adjust_pollset *adjust_pollset; /* adjust transfer poll set */ + Curl_cft_data_pending *has_data_pending;/* conn has data pending */ + Curl_cft_send *do_send; /* send data */ + Curl_cft_recv *do_recv; /* receive data */ + Curl_cft_cntrl *cntrl; /* events/control */ + Curl_cft_conn_is_alive *is_alive; /* FALSE if conn is dead, Jim! */ + Curl_cft_conn_keep_alive *keep_alive; /* try to keep it alive */ + Curl_cft_query *query; /* query filter chain */ +}; + +/* A connection filter instance, e.g. registered at a connection */ +struct Curl_cfilter { + const struct Curl_cftype *cft; /* the type providing implementation */ + struct Curl_cfilter *next; /* next filter in chain */ + void *ctx; /* filter type specific settings */ + struct connectdata *conn; /* the connection this filter belongs to */ + int sockindex; /* the index the filter is installed at */ + BIT(connected); /* != 0 iff this filter is connected */ +}; + +/* Default implementations for the type functions, implementing nop. */ +void Curl_cf_def_destroy_this(struct Curl_cfilter *cf, + struct Curl_easy *data); + +/* Default implementations for the type functions, implementing pass-through + * the filter chain. */ +void Curl_cf_def_get_host(struct Curl_cfilter *cf, struct Curl_easy *data, + const char **phost, const char **pdisplay_host, + int *pport); +void Curl_cf_def_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps); +bool Curl_cf_def_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data); +ssize_t Curl_cf_def_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *buf, size_t len, CURLcode *err); +ssize_t Curl_cf_def_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, CURLcode *err); +CURLcode Curl_cf_def_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2); +bool Curl_cf_def_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending); +CURLcode Curl_cf_def_conn_keep_alive(struct Curl_cfilter *cf, + struct Curl_easy *data); +CURLcode Curl_cf_def_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2); + +/** + * Create a new filter instance, unattached to the filter chain. + * Use Curl_conn_cf_add() to add it to the chain. + * @param pcf on success holds the created instance + * @param cft the filter type + * @param ctx the type specific context to use + */ +CURLcode Curl_cf_create(struct Curl_cfilter **pcf, + const struct Curl_cftype *cft, + void *ctx); + +/** + * Add a filter instance to the `sockindex` filter chain at connection + * `conn`. The filter must not already be attached. It is inserted at + * the start of the chain (top). + */ +void Curl_conn_cf_add(struct Curl_easy *data, + struct connectdata *conn, + int sockindex, + struct Curl_cfilter *cf); + +/** + * Insert a filter (chain) after `cf_at`. + * `cf_new` must not already be attached. + */ +void Curl_conn_cf_insert_after(struct Curl_cfilter *cf_at, + struct Curl_cfilter *cf_new); + +/** + * Discard, e.g. remove and destroy `discard` iff + * it still is in the filter chain below `cf`. If `discard` + * is no longer found beneath `cf` return FALSE. + * if `destroy_always` is TRUE, will call `discard`s destroy + * function and free it even if not found in the subchain. + */ +bool Curl_conn_cf_discard_sub(struct Curl_cfilter *cf, + struct Curl_cfilter *discard, + struct Curl_easy *data, + bool destroy_always); + +/** + * Discard all cfilters starting with `*pcf` and clearing it afterwards. + */ +void Curl_conn_cf_discard_chain(struct Curl_cfilter **pcf, + struct Curl_easy *data); + +/** + * Remove and destroy all filters at chain `sockindex` on connection `conn`. + */ +void Curl_conn_cf_discard_all(struct Curl_easy *data, + struct connectdata *conn, + int sockindex); + + +CURLcode Curl_conn_cf_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done); +void Curl_conn_cf_close(struct Curl_cfilter *cf, struct Curl_easy *data); +ssize_t Curl_conn_cf_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *buf, size_t len, CURLcode *err); +ssize_t Curl_conn_cf_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, CURLcode *err); +CURLcode Curl_conn_cf_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool ignore_result, + int event, int arg1, void *arg2); + +/** + * Determine if the connection filter chain is using SSL to the remote host + * (or will be once connected). + */ +bool Curl_conn_cf_is_ssl(struct Curl_cfilter *cf); + +/** + * Get the socket used by the filter chain starting at `cf`. + * Returns CURL_SOCKET_BAD if not available. + */ +curl_socket_t Curl_conn_cf_get_socket(struct Curl_cfilter *cf, + struct Curl_easy *data); + + +#define CURL_CF_SSL_DEFAULT -1 +#define CURL_CF_SSL_DISABLE 0 +#define CURL_CF_SSL_ENABLE 1 + +/** + * Bring the filter chain at `sockindex` for connection `data->conn` into + * connected state. Which will set `*done` to TRUE. + * This can be called on an already connected chain with no side effects. + * When not `blocking`, calls may return without error and `*done != TRUE`, + * while the individual filters negotiated the connection. + */ +CURLcode Curl_conn_connect(struct Curl_easy *data, int sockindex, + bool blocking, bool *done); + +/** + * Check if the filter chain at `sockindex` for connection `conn` is + * completely connected. + */ +bool Curl_conn_is_connected(struct connectdata *conn, int sockindex); + +/** + * Determine if we have reached the remote host on IP level, e.g. + * have a TCP connection. This turns TRUE before a possible SSL + * handshake has been started/done. + */ +bool Curl_conn_is_ip_connected(struct Curl_easy *data, int sockindex); + +/** + * Determine if the connection is using SSL to the remote host + * (or will be once connected). This will return FALSE, if SSL + * is only used in proxying and not for the tunnel itself. + */ +bool Curl_conn_is_ssl(struct connectdata *conn, int sockindex); + +/** + * Connection provides multiplexing of easy handles at `socketindex`. + */ +bool Curl_conn_is_multiplex(struct connectdata *conn, int sockindex); + +/** + * Close the filter chain at `sockindex` for connection `data->conn`. + * Filters remain in place and may be connected again afterwards. + */ +void Curl_conn_close(struct Curl_easy *data, int sockindex); + +/** + * Return if data is pending in some connection filter at chain + * `sockindex` for connection `data->conn`. + */ +bool Curl_conn_data_pending(struct Curl_easy *data, + int sockindex); + +/** + * Return the socket used on data's connection for the index. + * Returns CURL_SOCKET_BAD if not available. + */ +curl_socket_t Curl_conn_get_socket(struct Curl_easy *data, int sockindex); + +/** + * Tell filters to forget about the socket at sockindex. + */ +void Curl_conn_forget_socket(struct Curl_easy *data, int sockindex); + +/** + * Adjust the pollset for the filter chain startgin at `cf`. + */ +void Curl_conn_cf_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps); + +/** + * Adjust pollset from filters installed at transfer's connection. + */ +void Curl_conn_adjust_pollset(struct Curl_easy *data, + struct easy_pollset *ps); + +/** + * Receive data through the filter chain at `sockindex` for connection + * `data->conn`. Copy at most `len` bytes into `buf`. Return the + * actual number of bytes copied or a negative value on error. + * The error code is placed into `*code`. + */ +ssize_t Curl_cf_recv(struct Curl_easy *data, int sockindex, char *buf, + size_t len, CURLcode *code); + +/** + * Send `len` bytes of data from `buf` through the filter chain `sockindex` + * at connection `data->conn`. Return the actual number of bytes written + * or a negative value on error. + * The error code is placed into `*code`. + */ +ssize_t Curl_cf_send(struct Curl_easy *data, int sockindex, + const void *buf, size_t len, CURLcode *code); + +/** + * The easy handle `data` is being attached to `conn`. This does + * not mean that data will actually do a transfer. Attachment is + * also used for temporary actions on the connection. + */ +void Curl_conn_ev_data_attach(struct connectdata *conn, + struct Curl_easy *data); + +/** + * The easy handle `data` is being detached (no longer served) + * by connection `conn`. All filters are informed to release any resources + * related to `data`. + * Note: there may be several `data` attached to a connection at the same + * time. + */ +void Curl_conn_ev_data_detach(struct connectdata *conn, + struct Curl_easy *data); + +/** + * Notify connection filters that they need to setup data for + * a transfer. + */ +CURLcode Curl_conn_ev_data_setup(struct Curl_easy *data); + +/** + * Notify connection filters that now would be a good time to + * perform any idle, e.g. time related, actions. + */ +CURLcode Curl_conn_ev_data_idle(struct Curl_easy *data); + +/** + * Notify connection filters that the transfer represented by `data` + * is done with sending data (e.g. has uploaded everything). + */ +void Curl_conn_ev_data_done_send(struct Curl_easy *data); + +/** + * Notify connection filters that the transfer represented by `data` + * is finished - eventually premature, e.g. before being complete. + */ +void Curl_conn_ev_data_done(struct Curl_easy *data, bool premature); + +/** + * Notify connection filters that the transfer of data is paused/unpaused. + */ +CURLcode Curl_conn_ev_data_pause(struct Curl_easy *data, bool do_pause); + +/** + * Inform connection filters to update their info in `conn`. + */ +void Curl_conn_ev_update_info(struct Curl_easy *data, + struct connectdata *conn); + +/** + * Check if FIRSTSOCKET's cfilter chain deems connection alive. + */ +bool Curl_conn_is_alive(struct Curl_easy *data, struct connectdata *conn, + bool *input_pending); + +/** + * Try to upkeep the connection filters at sockindex. + */ +CURLcode Curl_conn_keep_alive(struct Curl_easy *data, + struct connectdata *conn, + int sockindex); + +void Curl_cf_def_close(struct Curl_cfilter *cf, struct Curl_easy *data); +void Curl_conn_get_host(struct Curl_easy *data, int sockindex, + const char **phost, const char **pdisplay_host, + int *pport); + +/** + * Get the maximum number of parallel transfers the connection + * expects to be able to handle at `sockindex`. + */ +size_t Curl_conn_get_max_concurrent(struct Curl_easy *data, + struct connectdata *conn, + int sockindex); + +/** + * Get the underlying error code for a transfer stream or 0 if not known. + */ +int Curl_conn_get_stream_error(struct Curl_easy *data, + struct connectdata *conn, + int sockindex); + +/** + * Get the index of the given socket in the connection's sockets. + * Useful in calling `Curl_conn_send()/Curl_conn_recv()` with the + * correct socket index. + */ +int Curl_conn_sockindex(struct Curl_easy *data, curl_socket_t sockfd); + +/* + * Receive data on the connection, using FIRSTSOCKET/SECONDARYSOCKET. + * Will return CURLE_AGAIN iff blocked on receiving. + */ +CURLcode Curl_conn_recv(struct Curl_easy *data, int sockindex, + char *buf, size_t buffersize, + ssize_t *pnread); + +/* + * Send data on the connection, using FIRSTSOCKET/SECONDARYSOCKET. + * Will return CURLE_AGAIN iff blocked on sending. + */ +CURLcode Curl_conn_send(struct Curl_easy *data, int sockindex, + const void *buf, size_t blen, + size_t *pnwritten); + + +void Curl_pollset_reset(struct Curl_easy *data, + struct easy_pollset *ps); + +/* Change the poll flags (CURL_POLL_IN/CURL_POLL_OUT) to the poll set for + * socket `sock`. If the socket is not already part of the poll set, it + * will be added. + * If the socket is present and all poll flags are cleared, it will be removed. + */ +void Curl_pollset_change(struct Curl_easy *data, + struct easy_pollset *ps, curl_socket_t sock, + int add_flags, int remove_flags); + +void Curl_pollset_set(struct Curl_easy *data, + struct easy_pollset *ps, curl_socket_t sock, + bool do_in, bool do_out); + +#define Curl_pollset_add_in(data, ps, sock) \ + Curl_pollset_change((data), (ps), (sock), CURL_POLL_IN, 0) +#define Curl_pollset_add_out(data, ps, sock) \ + Curl_pollset_change((data), (ps), (sock), CURL_POLL_OUT, 0) +#define Curl_pollset_add_inout(data, ps, sock) \ + Curl_pollset_change((data), (ps), (sock), \ + CURL_POLL_IN|CURL_POLL_OUT, 0) +#define Curl_pollset_set_in_only(data, ps, sock) \ + Curl_pollset_change((data), (ps), (sock), \ + CURL_POLL_IN, CURL_POLL_OUT) +#define Curl_pollset_set_out_only(data, ps, sock) \ + Curl_pollset_change((data), (ps), (sock), \ + CURL_POLL_OUT, CURL_POLL_IN) + +void Curl_pollset_add_socks(struct Curl_easy *data, + struct easy_pollset *ps, + int (*get_socks_cb)(struct Curl_easy *data, + curl_socket_t *socks)); + +/** + * Check if the pollset, as is, wants to read and/or write regarding + * the given socket. + */ +void Curl_pollset_check(struct Curl_easy *data, + struct easy_pollset *ps, curl_socket_t sock, + bool *pwant_read, bool *pwant_write); + +/** + * Types and macros used to keep the current easy handle in filter calls, + * allowing for nested invocations. See #10336. + * + * `cf_call_data` is intended to be a member of the cfilter's `ctx` type. + * A filter defines the macro `CF_CTX_CALL_DATA` to give access to that. + * + * With all values 0, the default, this indicates that there is no cfilter + * call with `data` ongoing. + * Macro `CF_DATA_SAVE` preserves the current `cf_call_data` in a local + * variable and sets the `data` given, incrementing the `depth` counter. + * + * Macro `CF_DATA_RESTORE` restores the old values from the local variable, + * while checking that `depth` values are as expected (debug build), catching + * cases where a "lower" RESTORE was not called. + * + * Finally, macro `CF_DATA_CURRENT` gives the easy handle of the current + * invocation. + */ +struct cf_call_data { + struct Curl_easy *data; +#ifdef DEBUGBUILD + int depth; +#endif +}; + +/** + * define to access the `struct cf_call_data for a cfilter. Normally + * a member in the cfilter's `ctx`. + * + * #define CF_CTX_CALL_DATA(cf) -> struct cf_call_data instance +*/ + +#ifdef DEBUGBUILD + +#define CF_DATA_SAVE(save, cf, data) \ + do { \ + (save) = CF_CTX_CALL_DATA(cf); \ + DEBUGASSERT((save).data == NULL || (save).depth > 0); \ + CF_CTX_CALL_DATA(cf).depth++; \ + CF_CTX_CALL_DATA(cf).data = (struct Curl_easy *)data; \ + } while(0) + +#define CF_DATA_RESTORE(cf, save) \ + do { \ + DEBUGASSERT(CF_CTX_CALL_DATA(cf).depth == (save).depth + 1); \ + DEBUGASSERT((save).data == NULL || (save).depth > 0); \ + CF_CTX_CALL_DATA(cf) = (save); \ + } while(0) + +#else /* DEBUGBUILD */ + +#define CF_DATA_SAVE(save, cf, data) \ + do { \ + (save) = CF_CTX_CALL_DATA(cf); \ + CF_CTX_CALL_DATA(cf).data = (struct Curl_easy *)data; \ + } while(0) + +#define CF_DATA_RESTORE(cf, save) \ + do { \ + CF_CTX_CALL_DATA(cf) = (save); \ + } while(0) + +#endif /* !DEBUGBUILD */ + +#define CF_DATA_CURRENT(cf) \ + ((cf)? (CF_CTX_CALL_DATA(cf).data) : NULL) + +#endif /* HEADER_CURL_CFILTERS_H */ diff --git a/third_party/curl/lib/config-amigaos.h b/third_party/curl/lib/config-amigaos.h new file mode 100644 index 0000000..d168b44 --- /dev/null +++ b/third_party/curl/lib/config-amigaos.h @@ -0,0 +1,129 @@ +#ifndef HEADER_CURL_CONFIG_AMIGAOS_H +#define HEADER_CURL_CONFIG_AMIGAOS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* ================================================================ */ +/* Hand crafted config file for AmigaOS */ +/* ================================================================ */ + +#ifdef __AMIGA__ /* Any AmigaOS flavour */ + +#define HAVE_ARPA_INET_H 1 +#define HAVE_CLOSESOCKET_CAMEL 1 +#define HAVE_IOCTLSOCKET_CAMEL 1 +#define HAVE_IOCTLSOCKET_CAMEL_FIONBIO 1 +#define HAVE_LONGLONG 1 +#define HAVE_NETDB_H 1 +#define HAVE_NETINET_IN_H 1 +#define HAVE_NET_IF_H 1 +#define HAVE_PWD_H 1 +#define HAVE_SELECT 1 +#define HAVE_SIGNAL 1 +#define HAVE_SOCKET 1 +#define HAVE_STRCASECMP 1 +#define HAVE_STRDUP 1 +#define HAVE_STRICMP 1 +#define HAVE_STRINGS_H 1 +#define HAVE_STRUCT_TIMEVAL 1 +#define HAVE_SYS_PARAM_H 1 +#define HAVE_SYS_SOCKET_H 1 +#define HAVE_SYS_SOCKIO_H 1 +#define HAVE_SYS_STAT_H 1 +#define HAVE_SYS_TIME_H 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_UNISTD_H 1 +#define HAVE_UTIME 1 +#define HAVE_UTIME_H 1 +#define HAVE_WRITABLE_ARGV 1 +#define HAVE_SYS_IOCTL_H 1 + +#define NEED_MALLOC_H 1 + +#define SIZEOF_INT 4 +#define SIZEOF_SIZE_T 4 + +#ifndef SIZEOF_CURL_OFF_T +#define SIZEOF_CURL_OFF_T 8 +#endif + +#define USE_MANUAL 1 +#define CURL_DISABLE_LDAP 1 + +#ifndef OS +#define OS "AmigaOS" +#endif + +#define PACKAGE "curl" +#define PACKAGE_BUGREPORT "a suitable mailing list: https://curl.se/mail/" +#define PACKAGE_NAME "curl" +#define PACKAGE_STRING "curl -" +#define PACKAGE_TARNAME "curl" +#define PACKAGE_VERSION "-" + +#if defined(USE_AMISSL) +#define CURL_CA_PATH "AmiSSL:Certs" +#elif defined(__MORPHOS__) +#define CURL_CA_BUNDLE "MOSSYS:Data/SSL/curl-ca-bundle.crt" +#else +#define CURL_CA_BUNDLE "s:curl-ca-bundle.crt" +#endif + +#define STDC_HEADERS 1 + +#define in_addr_t int + +#ifndef F_OK +# define F_OK 0 +#endif + +#ifndef O_RDONLY +# define O_RDONLY 0x0000 +#endif + +#ifndef LONG_MAX +# define LONG_MAX 0x7fffffffL +#endif + +#ifndef LONG_MIN +# define LONG_MIN (-0x7fffffffL-1) +#endif + +#define HAVE_RECV 1 +#define RECV_TYPE_ARG1 long +#define RECV_TYPE_ARG2 char * +#define RECV_TYPE_ARG3 long +#define RECV_TYPE_ARG4 long +#define RECV_TYPE_RETV long + +#define HAVE_SEND 1 +#define SEND_TYPE_ARG1 int +#define SEND_QUAL_ARG2 const +#define SEND_TYPE_ARG2 char * +#define SEND_TYPE_ARG3 int +#define SEND_TYPE_ARG4 int +#define SEND_TYPE_RETV int + +#endif /* __AMIGA__ */ +#endif /* HEADER_CURL_CONFIG_AMIGAOS_H */ diff --git a/third_party/curl/lib/config-dos.h b/third_party/curl/lib/config-dos.h new file mode 100644 index 0000000..c6fbba7 --- /dev/null +++ b/third_party/curl/lib/config-dos.h @@ -0,0 +1,138 @@ +#ifndef HEADER_CURL_CONFIG_DOS_H +#define HEADER_CURL_CONFIG_DOS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + + +/* ================================================================ */ +/* lib/config-dos.h - Hand crafted config file for DOS */ +/* ================================================================ */ + +#ifndef OS +#if defined(DJGPP) + #define OS "MSDOS/djgpp" +#elif defined(__HIGHC__) + #define OS "MSDOS/HighC" +#else + #define OS "MSDOS/?" +#endif +#endif + +#define PACKAGE "curl" + +#define USE_MANUAL 1 + +#define HAVE_ARPA_INET_H 1 +#define HAVE_FCNTL_H 1 +#define HAVE_FREEADDRINFO 1 +#define HAVE_GETADDRINFO 1 +#define HAVE_GETTIMEOFDAY 1 +#define HAVE_IO_H 1 +#define HAVE_IOCTL_FIONBIO 1 +#define HAVE_IOCTLSOCKET 1 +#define HAVE_IOCTLSOCKET_FIONBIO 1 +#define HAVE_LOCALE_H 1 +#define HAVE_LONGLONG 1 +#define HAVE_NETDB_H 1 +#define HAVE_NETINET_IN_H 1 +#define HAVE_NETINET_TCP_H 1 +#define HAVE_NET_IF_H 1 +#define HAVE_RECV 1 +#define HAVE_SELECT 1 +#define HAVE_SEND 1 +#define HAVE_SETLOCALE 1 +#define HAVE_SETMODE 1 +#define HAVE_SIGNAL 1 +#define HAVE_SOCKET 1 +#define HAVE_STRDUP 1 +#define HAVE_STRICMP 1 +#define HAVE_STRTOLL 1 +#define HAVE_STRUCT_TIMEVAL 1 +#define HAVE_SYS_IOCTL_H 1 +#define HAVE_SYS_SOCKET_H 1 +#define HAVE_SYS_STAT_H 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_UNISTD_H 1 + +#define NEED_MALLOC_H 1 + +#define SIZEOF_INT 4 +#define SIZEOF_LONG 4 +#define SIZEOF_SIZE_T 4 +#define SIZEOF_CURL_OFF_T 8 +#define STDC_HEADERS 1 + +/* Qualifiers for send() and recv() */ + +#define SEND_TYPE_ARG1 int +#define SEND_QUAL_ARG2 const +#define SEND_TYPE_ARG2 void * +#define SEND_TYPE_ARG3 int +#define SEND_TYPE_ARG4 int +#define SEND_TYPE_RETV int + +#define RECV_TYPE_ARG1 int +#define RECV_TYPE_ARG2 void * +#define RECV_TYPE_ARG3 int +#define RECV_TYPE_ARG4 int +#define RECV_TYPE_RETV int + +#define BSD + +/* CURLDEBUG definition enables memory tracking */ +/* #define CURLDEBUG */ + +/* to disable LDAP */ +#define CURL_DISABLE_LDAP 1 + +#define in_addr_t u_long + +#if defined(__HIGHC__) || \ + (defined(__GNUC__) && (__GNUC__ < 4)) + #define ssize_t int +#endif + +/* Target HAVE_x section */ + +#if defined(DJGPP) + #define HAVE_BASENAME 1 + #define HAVE_STRCASECMP 1 + #define HAVE_SIGACTION 1 + #define HAVE_SIGSETJMP 1 + #define HAVE_SYS_TIME_H 1 + #define HAVE_TERMIOS_H 1 + +#elif defined(__HIGHC__) + #define HAVE_SYS_TIME_H 1 + #define strerror(e) strerror_s_((e)) +#endif + +#ifdef MSDOS /* Watt-32 */ + #define HAVE_CLOSE_S 1 +#endif + +#undef word +#undef byte + +#endif /* HEADER_CURL_CONFIG_DOS_H */ diff --git a/third_party/curl/lib/config-mac.h b/third_party/curl/lib/config-mac.h new file mode 100644 index 0000000..c29888f --- /dev/null +++ b/third_party/curl/lib/config-mac.h @@ -0,0 +1,103 @@ +#ifndef HEADER_CURL_CONFIG_MAC_H +#define HEADER_CURL_CONFIG_MAC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* =================================================================== */ +/* Hand crafted config file for Mac OS 9 */ +/* =================================================================== */ +/* On Mac OS X you must run configure to generate curl_config.h file */ +/* =================================================================== */ + +#ifndef OS +#define OS "mac" +#endif + +#include +#if TYPE_LONGLONG +#define HAVE_LONGLONG 1 +#endif + +/* Define if you want the built-in manual */ +#define USE_MANUAL 1 + +#define HAVE_NETINET_IN_H 1 +#define HAVE_SYS_SOCKET_H 1 +#define HAVE_NETDB_H 1 +#define HAVE_ARPA_INET_H 1 +#define HAVE_UNISTD_H 1 +#define HAVE_NET_IF_H 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_GETTIMEOFDAY 1 +#define HAVE_FCNTL_H 1 +#define HAVE_SYS_STAT_H 1 +#define HAVE_UTIME_H 1 +#define HAVE_SYS_TIME_H 1 +#define HAVE_SYS_UTIME_H 1 +#define HAVE_SYS_IOCTL_H 1 +#define HAVE_ALARM 1 +#define HAVE_FTRUNCATE 1 +#define HAVE_UTIME 1 +#define HAVE_SELECT 1 +#define HAVE_SOCKET 1 +#define HAVE_STRUCT_TIMEVAL 1 + +#define HAVE_SIGACTION 1 + +#ifdef MACOS_SSL_SUPPORT +# define USE_OPENSSL 1 +#endif + +#define CURL_DISABLE_LDAP 1 + +#define HAVE_IOCTL_FIONBIO 1 + +#define SIZEOF_INT 4 +#define SIZEOF_LONG 4 +#define SIZEOF_SIZE_T 4 +#ifdef HAVE_LONGLONG +#define SIZEOF_CURL_OFF_T 8 +#else +#define SIZEOF_CURL_OFF_T 4 +#endif + +#define HAVE_RECV 1 +#define RECV_TYPE_ARG1 int +#define RECV_TYPE_ARG2 void * +#define RECV_TYPE_ARG3 size_t +#define RECV_TYPE_ARG4 int +#define RECV_TYPE_RETV ssize_t + +#define HAVE_SEND 1 +#define SEND_TYPE_ARG1 int +#define SEND_QUAL_ARG2 const +#define SEND_TYPE_ARG2 void * +#define SEND_TYPE_ARG3 size_t +#define SEND_TYPE_ARG4 int +#define SEND_TYPE_RETV ssize_t + +#define HAVE_EXTRA_STRICMP_H 1 +#define HAVE_EXTRA_STRDUP_H 1 + +#endif /* HEADER_CURL_CONFIG_MAC_H */ diff --git a/third_party/curl/lib/config-os400.h b/third_party/curl/lib/config-os400.h new file mode 100644 index 0000000..018e90a --- /dev/null +++ b/third_party/curl/lib/config-os400.h @@ -0,0 +1,334 @@ +#ifndef HEADER_CURL_CONFIG_OS400_H +#define HEADER_CURL_CONFIG_OS400_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* ================================================================ */ +/* Hand crafted config file for OS/400 */ +/* ================================================================ */ + +#pragma enum(int) + +#undef PACKAGE + +/* Version number of this archive. */ +#undef VERSION + +/* Define cpu-machine-OS */ +#ifndef OS +#define OS "OS/400" +#endif + +/* OS400 supports a 3-argument ASCII version of gethostbyaddr_r(), but its + * prototype is incompatible with the "standard" one (1st argument is not + * const). However, getaddrinfo() is supported (ASCII version defined as + * a local wrapper in setup-os400.h) in a threadsafe way: we can then + * configure getaddrinfo() as such and get rid of gethostbyname_r() without + * loss of threadsafeness. */ +#undef HAVE_GETHOSTBYNAME_R +#undef HAVE_GETHOSTBYNAME_R_3 +#undef HAVE_GETHOSTBYNAME_R_5 +#undef HAVE_GETHOSTBYNAME_R_6 +#define HAVE_GETADDRINFO +#define HAVE_GETADDRINFO_THREADSAFE + +/* Define if you need the _REENTRANT define for some functions */ +#undef NEED_REENTRANT + +/* Define if you want to enable IPv6 support */ +#define USE_IPV6 + +/* Define if struct sockaddr_in6 has the sin6_scope_id member */ +#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 + +/* Define this to 'int' if ssize_t is not an available typedefed type */ +#undef ssize_t + +/* Define this as a suitable file to read random data from */ +#undef RANDOM_FILE + +/* Define to 1 if you have the alarm function. */ +#define HAVE_ALARM 1 + +/* Define if you have the header file. */ +#define HAVE_ARPA_INET_H + +/* Define if you have the `closesocket' function. */ +#undef HAVE_CLOSESOCKET + +/* Define if you have the header file. */ +#define HAVE_FCNTL_H + +/* Define if you have the `geteuid' function. */ +#define HAVE_GETEUID + +/* Define if you have the `gethostname' function. */ +#define HAVE_GETHOSTNAME + +/* Define if you have the `getpass_r' function. */ +#undef HAVE_GETPASS_R + +/* Define to 1 if you have the getpeername function. */ +#define HAVE_GETPEERNAME 1 + +/* Define if you have the `getpwuid' function. */ +#define HAVE_GETPWUID + +/* Define to 1 if you have the getsockname function. */ +#define HAVE_GETSOCKNAME 1 + +/* Define if you have the `gettimeofday' function. */ +#define HAVE_GETTIMEOFDAY + +/* Define if you have the `timeval' struct. */ +#define HAVE_STRUCT_TIMEVAL + +/* Define if you have the header file. */ +#undef HAVE_IO_H + +/* Define if you have the `socket' library (-lsocket). */ +#undef HAVE_LIBSOCKET + +/* Define if you have GSS API. */ +#define HAVE_GSSAPI + +/* Define if you have the GNU gssapi libraries */ +#undef HAVE_GSSGNU + +/* Define if you need the malloc.h header file even with stdlib.h */ +/* #define NEED_MALLOC_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_NETDB_H + +/* Define if you have the header file. */ +#define HAVE_NETINET_IN_H + +/* Define if you have the header file. */ +#define HAVE_NET_IF_H + +/* Define if you have the header file. */ +#define HAVE_PWD_H + +/* Define if you have the `select' function. */ +#define HAVE_SELECT + +/* Define if you have the `sigaction' function. */ +#define HAVE_SIGACTION + +/* Define if you have the `signal' function. */ +#undef HAVE_SIGNAL + +/* Define if you have the `socket' function. */ +#define HAVE_SOCKET + + +/* The following define is needed on OS400 to enable strcmpi(), stricmp() and + strdup(). */ +#define __cplusplus__strings__ + +/* Define if you have the `strcasecmp' function. */ +#undef HAVE_STRCASECMP + +/* Define if you have the `strcmpi' function. */ +#define HAVE_STRCMPI + +/* Define if you have the `stricmp' function. */ +#define HAVE_STRICMP + +/* Define if you have the `strdup' function. */ +#define HAVE_STRDUP + +/* Define if you have the header file. */ +#define HAVE_STRINGS_H + +/* Define if you have the header file. */ +#undef HAVE_STROPTS_H + +/* Define if you have the `strtok_r' function. */ +#define HAVE_STRTOK_R + +/* Define if you have the `strtoll' function. */ +#undef HAVE_STRTOLL /* Allows ASCII compile on V5R1. */ + +/* Define if you have the header file. */ +#define HAVE_SYS_PARAM_H + +/* Define if you have the header file. */ +#undef HAVE_SYS_SELECT_H + +/* Define if you have the header file. */ +#define HAVE_SYS_SOCKET_H + +/* Define if you have the header file. */ +#undef HAVE_SYS_SOCKIO_H + +/* Define if you have the header file. */ +#define HAVE_SYS_STAT_H + +/* Define if you have the header file. */ +#define HAVE_SYS_TIME_H + +/* Define if you have the header file. */ +#define HAVE_SYS_TYPES_H + +/* Define if you have the header file. */ +#define HAVE_SYS_UN_H + +/* Define if you have the header file. */ +#define HAVE_SYS_IOCTL_H + +/* Define if you have the header file. */ +#undef HAVE_TERMIOS_H + +/* Define if you have the header file. */ +#undef HAVE_TERMIO_H + +/* Define if you have the header file. */ +#define HAVE_UNISTD_H + +/* Name of package */ +#undef PACKAGE + +/* The size of `int', as computed by sizeof. */ +#define SIZEOF_INT 4 + +/* Define if the compiler supports the 'long long' data type. */ +#define HAVE_LONGLONG + +/* The size of a `long long', as computed by sizeof. */ +#define SIZEOF_LONG_LONG 8 + +/* The size of `long', as computed by sizeof. */ +#define SIZEOF_LONG 4 + +/* The size of `size_t', as computed by sizeof. */ +#define SIZEOF_SIZE_T 4 + +/* The size of `curl_off_t', as computed by sizeof. */ +#define SIZEOF_CURL_OFF_T 8 + +/* Define this if you have struct sockaddr_storage */ +#define HAVE_STRUCT_SOCKADDR_STORAGE + +/* Define if you have the ANSI C header files. */ +#define STDC_HEADERS + +/* Define to enable HTTP3 support (experimental, requires NGTCP2, QUICHE or + MSH3) */ +#undef USE_HTTP3 + +/* Version number of package */ +#undef VERSION + +/* Number of bits in a file offset, on hosts where this is settable. */ +#undef _FILE_OFFSET_BITS + +/* Define for large files, on AIX-style hosts. */ +#define _LARGE_FILES + +/* Define to empty if `const' does not conform to ANSI C. */ +#undef const + +/* type to use in place of in_addr_t if not defined */ +#define in_addr_t unsigned long + +/* Define to `unsigned' if does not define. */ +#undef size_t + +/* Define if you have a working ioctl FIONBIO function. */ +#define HAVE_IOCTL_FIONBIO + +/* Define if you have a working ioctl SIOCGIFADDR function. */ +#define HAVE_IOCTL_SIOCGIFADDR + +/* To disable LDAP */ +#undef CURL_DISABLE_LDAP + +/* Definition to make a library symbol externally visible. */ +#define CURL_EXTERN_SYMBOL + +/* Define if you have the ldap_url_parse procedure. */ +/* #define HAVE_LDAP_URL_PARSE */ /* Disabled because of an IBM bug. */ + +/* Define if you have the recv function. */ +#define HAVE_RECV + +/* Define to the type of arg 1 for recv. */ +#define RECV_TYPE_ARG1 int + +/* Define to the type of arg 2 for recv. */ +#define RECV_TYPE_ARG2 char * + +/* Define to the type of arg 3 for recv. */ +#define RECV_TYPE_ARG3 int + +/* Define to the type of arg 4 for recv. */ +#define RECV_TYPE_ARG4 int + +/* Define to the function return type for recv. */ +#define RECV_TYPE_RETV int + +/* Define if you have the send function. */ +#define HAVE_SEND + +/* Define to the type of arg 1 for send. */ +#define SEND_TYPE_ARG1 int + +/* Define to the type qualifier of arg 2 for send. */ +#define SEND_QUAL_ARG2 + +/* Define to the type of arg 2 for send. */ +#define SEND_TYPE_ARG2 char * + +/* Define to the type of arg 3 for send. */ +#define SEND_TYPE_ARG3 int + +/* Define to the type of arg 4 for send. */ +#define SEND_TYPE_ARG4 int + +/* Define to the function return type for send. */ +#define SEND_TYPE_RETV int + +/* Define to use the OS/400 crypto library. */ +#define USE_OS400CRYPTO + +/* Define to use Unix sockets. */ +#define USE_UNIX_SOCKETS + +/* Use the system keyring as the default CA bundle. */ +#define CURL_CA_BUNDLE "/QIBM/UserData/ICSS/Cert/Server/DEFAULT.KDB" + +/* ---------------------------------------------------------------- */ +/* ADDITIONAL DEFINITIONS */ +/* ---------------------------------------------------------------- */ + +/* The following must be defined BEFORE system header files inclusion. */ + +#define __ptr128 /* No teraspace. */ +#define qadrt_use_fputc_inline /* Generate fputc() wrapper inline. */ +#define qadrt_use_fread_inline /* Generate fread() wrapper inline. */ +#define qadrt_use_fwrite_inline /* Generate fwrite() wrapper inline. */ + +#endif /* HEADER_CURL_CONFIG_OS400_H */ diff --git a/third_party/curl/lib/config-plan9.h b/third_party/curl/lib/config-plan9.h new file mode 100644 index 0000000..6f3a15a --- /dev/null +++ b/third_party/curl/lib/config-plan9.h @@ -0,0 +1,147 @@ +#ifndef HEADER_CURL_CONFIG_PLAN9_H +#define HEADER_CURL_CONFIG_PLAN9_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#define BUILDING_LIBCURL 1 +#define CURL_CA_BUNDLE "/sys/lib/tls/ca.pem" +#define CURL_CA_PATH "/sys/lib/tls" +#define CURL_STATICLIB 1 +#define USE_IPV6 1 +#define CURL_DISABLE_LDAP 1 + +#define NEED_REENTRANT 1 +#ifndef OS +#define OS "plan9" +#endif +#define PACKAGE "curl" +#define PACKAGE_NAME "curl" +#define PACKAGE_BUGREPORT "a suitable mailing list: https://curl.se/mail/" +#define PACKAGE_STRING "curl -" +#define PACKAGE_TARNAME "curl" +#define PACKAGE_VERSION "-" +#define RANDOM_FILE "/dev/random" +#define VERSION "0.0.0" /* TODO */ + +#define STDC_HEADERS 1 + +#ifdef _BITS64 +#error not implement +#else +#define SIZEOF_INT 4 +#define SIZEOF_LONG 4 +#define SIZEOF_OFF_T 8 +#define SIZEOF_CURL_OFF_T 4 /* curl_off_t = timediff_t = int */ +#define SIZEOF_SIZE_T 4 +#define SIZEOF_TIME_T 4 +#endif + +#define HAVE_RECV 1 +#define RECV_TYPE_ARG1 int +#define RECV_TYPE_ARG2 void * +#define RECV_TYPE_ARG3 int +#define RECV_TYPE_ARG4 int +#define RECV_TYPE_RETV int + +#define HAVE_SELECT 1 + +#define HAVE_SEND 1 +#define SEND_TYPE_ARG1 int +#define SEND_TYPE_ARG2 void * +#define SEND_QUAL_ARG2 +#define SEND_TYPE_ARG3 int +#define SEND_TYPE_ARG4 int +#define SEND_TYPE_RETV int + +#define HAVE_ALARM 1 +#define HAVE_ARPA_INET_H 1 +#define HAVE_BASENAME 1 +#define HAVE_BOOL_T 1 +#define HAVE_FCNTL 1 +#define HAVE_FCNTL_H 1 +#define HAVE_FREEADDRINFO 1 +#define HAVE_FTRUNCATE 1 +#define HAVE_GETADDRINFO 1 +#define HAVE_GETEUID 1 +#define HAVE_GETHOSTNAME 1 +#define HAVE_GETPPID 1 +#define HAVE_GETPWUID 1 +#define HAVE_GETTIMEOFDAY 1 +#define HAVE_GMTIME_R 1 +#define HAVE_INET_NTOP 1 +#define HAVE_INET_PTON 1 +#define HAVE_LIBGEN_H 1 +#define HAVE_LIBZ 1 +#define HAVE_LOCALE_H 1 +#define HAVE_LONGLONG 1 +#define HAVE_NETDB_H 1 +#define HAVE_NETINET_IN_H 1 +#define HAVE_NETINET_TCP_H 1 +#define HAVE_PWD_H 1 +#define HAVE_SYS_SELECT_H 1 + +#define USE_OPENSSL 1 + +#define HAVE_PIPE 1 +#define HAVE_POLL_FINE 1 +#define HAVE_POLL_H 1 +#define HAVE_PTHREAD_H 1 +#define HAVE_SETLOCALE 1 + +#define HAVE_SIGACTION 1 +#define HAVE_SIGNAL 1 +#define HAVE_SIGSETJMP 1 +#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 +#define HAVE_SOCKET 1 +#define HAVE_SSL_GET_SHUTDOWN 1 +#define HAVE_STDBOOL_H 1 +#define HAVE_STRCASECMP 1 +#define HAVE_STRDUP 1 +#define HAVE_STRTOK_R 1 +#define HAVE_STRTOLL 1 +#define HAVE_STRUCT_TIMEVAL 1 +#define HAVE_SYS_IOCTL_H 1 +#define HAVE_SYS_PARAM_H 1 +#define HAVE_SYS_RESOURCE_H 1 +#define HAVE_SYS_SOCKET_H 1 +#define HAVE_SYS_STAT_H 1 +#define HAVE_SYS_TIME_H 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_SYS_UN_H 1 +#define HAVE_TERMIOS_H 1 +#define HAVE_UNISTD_H 1 +#define HAVE_UTIME 1 +#define HAVE_UTIME_H 1 + +#define HAVE_POSIX_STRERROR_R 1 +#define HAVE_STRERROR_R 1 +#define USE_MANUAL 1 + +#define __attribute__(x) + +#ifndef __cplusplus +#undef inline +#endif + +#endif /* HEADER_CURL_CONFIG_PLAN9_H */ diff --git a/third_party/curl/lib/config-riscos.h b/third_party/curl/lib/config-riscos.h new file mode 100644 index 0000000..eb1d26e --- /dev/null +++ b/third_party/curl/lib/config-riscos.h @@ -0,0 +1,277 @@ +#ifndef HEADER_CURL_CONFIG_RISCOS_H +#define HEADER_CURL_CONFIG_RISCOS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* ================================================================ */ +/* Hand crafted config file for RISC OS */ +/* ================================================================ */ + +/* Name of this package! */ +#undef PACKAGE + +/* Version number of this archive. */ +#undef VERSION + +/* Define cpu-machine-OS */ +#ifndef OS +#define OS "ARM-RISC OS" +#endif + +/* Define if you want the built-in manual */ +#define USE_MANUAL + +/* Define if you have the gethostbyname_r() function with 3 arguments */ +#undef HAVE_GETHOSTBYNAME_R_3 + +/* Define if you have the gethostbyname_r() function with 5 arguments */ +#undef HAVE_GETHOSTBYNAME_R_5 + +/* Define if you have the gethostbyname_r() function with 6 arguments */ +#undef HAVE_GETHOSTBYNAME_R_6 + +/* Define if you need the _REENTRANT define for some functions */ +#undef NEED_REENTRANT + +/* Define if you want to enable IPv6 support */ +#undef USE_IPV6 + +/* Define if struct sockaddr_in6 has the sin6_scope_id member */ +#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 + +/* Define this to 'int' if ssize_t is not an available typedefed type */ +#undef ssize_t + +/* Define this as a suitable file to read random data from */ +#undef RANDOM_FILE + +/* Define if you have the alarm function. */ +#define HAVE_ALARM + +/* Define if you have the header file. */ +#define HAVE_ARPA_INET_H + +/* Define if you have the `closesocket' function. */ +#undef HAVE_CLOSESOCKET + +/* Define if you have the header file. */ +#define HAVE_FCNTL_H + +/* Define if you have the `ftruncate' function. */ +#define HAVE_FTRUNCATE + +/* Define if getaddrinfo exists and works */ +#define HAVE_GETADDRINFO + +/* Define if you have the `geteuid' function. */ +#undef HAVE_GETEUID + +/* Define if you have the `gethostbyname_r' function. */ +#undef HAVE_GETHOSTBYNAME_R + +/* Define if you have the `gethostname' function. */ +#define HAVE_GETHOSTNAME + +/* Define if you have the `getpass_r' function. */ +#undef HAVE_GETPASS_R + +/* Define if you have the `getpwuid' function. */ +#undef HAVE_GETPWUID + +/* Define if you have the `gettimeofday' function. */ +#define HAVE_GETTIMEOFDAY + +/* Define if you have the `timeval' struct. */ +#define HAVE_STRUCT_TIMEVAL + +/* Define if you have the header file. */ +#undef HAVE_IO_H + +/* Define if you have the `socket' library (-lsocket). */ +#undef HAVE_LIBSOCKET + +/* Define if you need the malloc.h header file even with stdlib.h */ +/* #define NEED_MALLOC_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_NETDB_H + +/* Define if you have the header file. */ +#define HAVE_NETINET_IN_H + +/* Define if you have the header file. */ +#define HAVE_NET_IF_H + +/* Define if you have the header file. */ +#undef HAVE_PWD_H + +/* Define if you have the `select' function. */ +#define HAVE_SELECT + +/* Define if you have the `sigaction' function. */ +#undef HAVE_SIGACTION + +/* Define if you have the `signal' function. */ +#define HAVE_SIGNAL + +/* Define if you have the `socket' function. */ +#define HAVE_SOCKET + +/* Define if you have the `strcasecmp' function. */ +#undef HAVE_STRCASECMP + +/* Define if you have the `strcmpi' function. */ +#undef HAVE_STRCMPI + +/* Define if you have the `strdup' function. */ +#define HAVE_STRDUP + +/* Define if you have the `stricmp' function. */ +#define HAVE_STRICMP + +/* Define if you have the header file. */ +#undef HAVE_STRINGS_H + +/* Define if you have the `strtok_r' function. */ +#undef HAVE_STRTOK_R + +/* Define if you have the `strtoll' function. */ +#undef HAVE_STRTOLL + +/* Define if you have the header file. */ +#undef HAVE_SYS_PARAM_H + +/* Define if you have the header file. */ +#undef HAVE_SYS_SELECT_H + +/* Define if you have the header file. */ +#define HAVE_SYS_SOCKET_H + +/* Define if you have the header file. */ +#undef HAVE_SYS_SOCKIO_H + +/* Define if you have the header file. */ +#undef HAVE_SYS_STAT_H + +/* Define if you have the header file. */ +#define HAVE_SYS_TIME_H + +/* Define if you have the header file. */ +#define HAVE_SYS_TYPES_H + +/* Define if you have the header file. */ +#define HAVE_TERMIOS_H + +/* Define if you have the header file. */ +#undef HAVE_TERMIO_H + +/* Define if you have the header file. */ +#define HAVE_UNISTD_H + +/* Name of package */ +#undef PACKAGE + +/* The size of `int', as computed by sizeof. */ +#define SIZEOF_INT 4 + +/* The size of `long long', as computed by sizeof. */ +#undef SIZEOF_LONG_LONG + +/* The size of `size_t', as computed by sizeof. */ +#define SIZEOF_SIZE_T 4 + +/* Define if you have the ANSI C header files. */ +#undef STDC_HEADERS + +/* Version number of package */ +#undef VERSION + +/* Define if on AIX 3. + System headers sometimes define this. + We just want to avoid a redefinition error message. */ +#ifndef _ALL_SOURCE +# undef _ALL_SOURCE +#endif + +/* Number of bits in a file offset, on hosts where this is settable. */ +#undef _FILE_OFFSET_BITS + +/* Define for large files, on AIX-style hosts. */ +#undef _LARGE_FILES + +/* Define to empty if `const' does not conform to ANSI C. */ +#undef const + +/* Define to `unsigned' if does not define. */ +#undef size_t + +/* Define to `int' if does not define. */ +#undef ssize_t + +/* Define if you have a working ioctl FIONBIO function. */ +#define HAVE_IOCTL_FIONBIO + +/* to disable LDAP */ +#define CURL_DISABLE_LDAP + +/* Define if you have the recv function. */ +#define HAVE_RECV 1 + +/* Define to the type of arg 1 for recv. */ +#define RECV_TYPE_ARG1 int + +/* Define to the type of arg 2 for recv. */ +#define RECV_TYPE_ARG2 void * + +/* Define to the type of arg 3 for recv. */ +#define RECV_TYPE_ARG3 size_t + +/* Define to the type of arg 4 for recv. */ +#define RECV_TYPE_ARG4 int + +/* Define to the function return type for recv. */ +#define RECV_TYPE_RETV ssize_t + +/* Define if you have the send function. */ +#define HAVE_SEND 1 + +/* Define to the type of arg 1 for send. */ +#define SEND_TYPE_ARG1 int + +/* Define to the type qualifier of arg 2 for send. */ +#define SEND_QUAL_ARG2 const + +/* Define to the type of arg 2 for send. */ +#define SEND_TYPE_ARG2 void * + +/* Define to the type of arg 3 for send. */ +#define SEND_TYPE_ARG3 size_t + +/* Define to the type of arg 4 for send. */ +#define SEND_TYPE_ARG4 int + +/* Define to the function return type for send. */ +#define SEND_TYPE_RETV ssize_t + +#endif /* HEADER_CURL_CONFIG_RISCOS_H */ diff --git a/third_party/curl/lib/config-win32.h b/third_party/curl/lib/config-win32.h new file mode 100644 index 0000000..d134193 --- /dev/null +++ b/third_party/curl/lib/config-win32.h @@ -0,0 +1,512 @@ +#ifndef HEADER_CURL_CONFIG_WIN32_H +#define HEADER_CURL_CONFIG_WIN32_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* ================================================================ */ +/* Hand crafted config file for Windows */ +/* ================================================================ */ + +/* ---------------------------------------------------------------- */ +/* HEADER FILES */ +/* ---------------------------------------------------------------- */ + +/* Define if you have the header file. */ +/* #define HAVE_ARPA_INET_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_FCNTL_H 1 + +/* Define if you have the header file. */ +#define HAVE_IO_H 1 + +/* Define if you have the header file. */ +#define HAVE_LOCALE_H 1 + +/* Define if you need header even with header file. */ +#define NEED_MALLOC_H 1 + +/* Define if you have the header file. */ +/* #define HAVE_NETDB_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_NETINET_IN_H 1 */ + +/* Define to 1 if you have the header file. */ +#if (defined(_MSC_VER) && (_MSC_VER >= 1800)) || defined(__MINGW32__) +#define HAVE_STDBOOL_H 1 +#endif + +/* Define if you have the header file. */ +#if defined(__MINGW32__) +#define HAVE_SYS_PARAM_H 1 +#endif + +/* Define if you have the header file. */ +/* #define HAVE_SYS_SELECT_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_SYS_SOCKET_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_SYS_SOCKIO_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define if you have the header file. */ +#if defined(__MINGW32__) +#define HAVE_SYS_TIME_H 1 +#endif + +/* Define if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define if you have the header file. */ +#define HAVE_SYS_UTIME_H 1 + +/* Define if you have the header file. */ +/* #define HAVE_TERMIO_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_TERMIOS_H 1 */ + +/* Define if you have the header file. */ +#if defined(__MINGW32__) +#define HAVE_UNISTD_H 1 +#endif + +/* Define to 1 if you have the header file. */ +#if defined(__MINGW32__) +#define HAVE_LIBGEN_H 1 +#endif + +/* ---------------------------------------------------------------- */ +/* OTHER HEADER INFO */ +/* ---------------------------------------------------------------- */ + +/* Define if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define to 1 if bool is an available type. */ +#if (defined(_MSC_VER) && (_MSC_VER >= 1800)) || defined(__MINGW32__) +#define HAVE_BOOL_T 1 +#endif + +/* ---------------------------------------------------------------- */ +/* FUNCTIONS */ +/* ---------------------------------------------------------------- */ + +/* Define if you have the closesocket function. */ +#define HAVE_CLOSESOCKET 1 + +/* Define if you have the ftruncate function. */ +#if defined(__MINGW32__) +#define HAVE_FTRUNCATE 1 +#endif + +/* Define to 1 if you have the `getpeername' function. */ +#define HAVE_GETPEERNAME 1 + +/* Define to 1 if you have the getsockname function. */ +#define HAVE_GETSOCKNAME 1 + +/* Define if you have the gethostname function. */ +#define HAVE_GETHOSTNAME 1 + +/* Define if you have the gettimeofday function. */ +#if defined(__MINGW32__) +#define HAVE_GETTIMEOFDAY 1 +#endif + +/* Define if you have the ioctlsocket function. */ +#define HAVE_IOCTLSOCKET 1 + +/* Define if you have a working ioctlsocket FIONBIO function. */ +#define HAVE_IOCTLSOCKET_FIONBIO 1 + +/* Define if you have the select function. */ +#define HAVE_SELECT 1 + +/* Define if you have the setlocale function. */ +#define HAVE_SETLOCALE 1 + +/* Define if you have the setmode function. */ +#define HAVE_SETMODE 1 + +/* Define if you have the socket function. */ +#define HAVE_SOCKET 1 + +/* Define if you have the strcasecmp function. */ +#if defined(__MINGW32__) +#define HAVE_STRCASECMP 1 +#endif + +/* Define if you have the strdup function. */ +#define HAVE_STRDUP 1 + +/* Define if you have the stricmp function. */ +#define HAVE_STRICMP 1 + +/* Define if you have the strtoll function. */ +#if (defined(_MSC_VER) && (_MSC_VER >= 1800)) || defined(__MINGW32__) +#define HAVE_STRTOLL 1 +#endif + +/* Define if you have the utime function. */ +#define HAVE_UTIME 1 + +/* Define if you have the recv function. */ +#define HAVE_RECV 1 + +/* Define to the type of arg 1 for recv. */ +#define RECV_TYPE_ARG1 SOCKET + +/* Define to the type of arg 2 for recv. */ +#define RECV_TYPE_ARG2 char * + +/* Define to the type of arg 3 for recv. */ +#define RECV_TYPE_ARG3 int + +/* Define to the type of arg 4 for recv. */ +#define RECV_TYPE_ARG4 int + +/* Define to the function return type for recv. */ +#define RECV_TYPE_RETV int + +/* Define if you have the send function. */ +#define HAVE_SEND 1 + +/* Define to the type of arg 1 for send. */ +#define SEND_TYPE_ARG1 SOCKET + +/* Define to the type qualifier of arg 2 for send. */ +#define SEND_QUAL_ARG2 const + +/* Define to the type of arg 2 for send. */ +#define SEND_TYPE_ARG2 char * + +/* Define to the type of arg 3 for send. */ +#define SEND_TYPE_ARG3 int + +/* Define to the type of arg 4 for send. */ +#define SEND_TYPE_ARG4 int + +/* Define to the function return type for send. */ +#define SEND_TYPE_RETV int + +/* Define to 1 if you have the snprintf function. */ +#if (defined(_MSC_VER) && (_MSC_VER >= 1900)) || defined(__MINGW32__) +#define HAVE_SNPRINTF 1 +#endif + +#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x600 /* Vista */ +/* Define to 1 if you have a IPv6 capable working inet_ntop function. */ +#define HAVE_INET_NTOP 1 +/* Define to 1 if you have a IPv6 capable working inet_pton function. */ +#define HAVE_INET_PTON 1 +#endif + +/* Define to 1 if you have the `basename' function. */ +#if defined(__MINGW32__) +#define HAVE_BASENAME 1 +#endif + +/* Define to 1 if you have the strtok_r function. */ +#if defined(__MINGW32__) +#define HAVE_STRTOK_R 1 +#endif + +/* Define to 1 if you have the signal function. */ +#define HAVE_SIGNAL 1 + +/* ---------------------------------------------------------------- */ +/* TYPEDEF REPLACEMENTS */ +/* ---------------------------------------------------------------- */ + +/* Define if in_addr_t is not an available 'typedefed' type. */ +#define in_addr_t unsigned long + +/* Define if ssize_t is not an available 'typedefed' type. */ +#ifndef _SSIZE_T_DEFINED +# if defined(__MINGW32__) +# elif defined(_WIN64) +# define _SSIZE_T_DEFINED +# define ssize_t __int64 +# else +# define _SSIZE_T_DEFINED +# define ssize_t int +# endif +#endif + +/* ---------------------------------------------------------------- */ +/* TYPE SIZES */ +/* ---------------------------------------------------------------- */ + +/* Define to the size of `int', as computed by sizeof. */ +#define SIZEOF_INT 4 + +/* Define to the size of `long long', as computed by sizeof. */ +/* #define SIZEOF_LONG_LONG 8 */ + +/* Define to the size of `long', as computed by sizeof. */ +#define SIZEOF_LONG 4 + +/* Define to the size of `size_t', as computed by sizeof. */ +#if defined(_WIN64) +# define SIZEOF_SIZE_T 8 +#else +# define SIZEOF_SIZE_T 4 +#endif + +/* Define to the size of `curl_off_t', as computed by sizeof. */ +#define SIZEOF_CURL_OFF_T 8 + +/* ---------------------------------------------------------------- */ +/* COMPILER SPECIFIC */ +/* ---------------------------------------------------------------- */ + +/* Define to nothing if compiler does not support 'const' qualifier. */ +/* #define const */ + +/* Define to nothing if compiler does not support 'volatile' qualifier. */ +/* #define volatile */ + +/* Windows should not have HAVE_GMTIME_R defined */ +/* #undef HAVE_GMTIME_R */ + +/* Define if the compiler supports the 'long long' data type. */ +#if (defined(_MSC_VER) && (_MSC_VER >= 1310)) || defined(__MINGW32__) +#define HAVE_LONGLONG 1 +#endif + +/* Define to avoid VS2005 complaining about portable C functions. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1400) +#define _CRT_SECURE_NO_DEPRECATE 1 +#define _CRT_NONSTDC_NO_DEPRECATE 1 +#endif + +/* mingw-w64 and visual studio >= 2005 (MSVCR80) + all default to 64-bit time_t unless _USE_32BIT_TIME_T is defined */ +#if (defined(_MSC_VER) && (_MSC_VER >= 1400)) || defined(__MINGW32__) +# ifndef _USE_32BIT_TIME_T +# define SIZEOF_TIME_T 8 +# else +# define SIZEOF_TIME_T 4 +# endif +#endif + +/* Define some minimum and default build targets for Visual Studio */ +#if defined(_MSC_VER) + /* Officially, Microsoft's Windows SDK versions 6.X does not support Windows + 2000 as a supported build target. VS2008 default installations provides + an embedded Windows SDK v6.0A along with the claim that Windows 2000 is a + valid build target for VS2008. Popular belief is that binaries built with + VS2008 using Windows SDK versions v6.X and Windows 2000 as a build target + are functional. */ +# define VS2008_MIN_TARGET 0x0500 + + /* The minimum build target for VS2012 is Vista unless Update 1 is installed + and the v110_xp toolset is chosen. */ +# if defined(_USING_V110_SDK71_) +# define VS2012_MIN_TARGET 0x0501 +# else +# define VS2012_MIN_TARGET 0x0600 +# endif + + /* VS2008 default build target is Windows Vista. We override default target + to be Windows XP. */ +# define VS2008_DEF_TARGET 0x0501 + + /* VS2012 default build target is Windows Vista unless Update 1 is installed + and the v110_xp toolset is chosen. */ +# if defined(_USING_V110_SDK71_) +# define VS2012_DEF_TARGET 0x0501 +# else +# define VS2012_DEF_TARGET 0x0600 +# endif +#endif + +/* VS2008 default target settings and minimum build target check. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1500) && (_MSC_VER <= 1600) +# ifndef _WIN32_WINNT +# define _WIN32_WINNT VS2008_DEF_TARGET +# endif +# ifndef WINVER +# define WINVER VS2008_DEF_TARGET +# endif +# if (_WIN32_WINNT < VS2008_MIN_TARGET) || (WINVER < VS2008_MIN_TARGET) +# error VS2008 does not support Windows build targets prior to Windows 2000 +# endif +#endif + +/* VS2012 default target settings and minimum build target check. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1700) +# ifndef _WIN32_WINNT +# define _WIN32_WINNT VS2012_DEF_TARGET +# endif +# ifndef WINVER +# define WINVER VS2012_DEF_TARGET +# endif +# if (_WIN32_WINNT < VS2012_MIN_TARGET) || (WINVER < VS2012_MIN_TARGET) +# if defined(_USING_V110_SDK71_) +# error VS2012 does not support Windows build targets prior to Windows XP +# else +# error VS2012 does not support Windows build targets prior to Windows \ +Vista +# endif +# endif +#endif + +/* Windows XP is required for freeaddrinfo, getaddrinfo */ +#define HAVE_FREEADDRINFO 1 +#define HAVE_GETADDRINFO 1 +#define HAVE_GETADDRINFO_THREADSAFE 1 + +/* ---------------------------------------------------------------- */ +/* STRUCT RELATED */ +/* ---------------------------------------------------------------- */ + +/* Define if you have struct sockaddr_storage. */ +#define HAVE_STRUCT_SOCKADDR_STORAGE 1 + +/* Define if you have struct timeval. */ +#define HAVE_STRUCT_TIMEVAL 1 + +/* Define if struct sockaddr_in6 has the sin6_scope_id member. */ +#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 + +/* ---------------------------------------------------------------- */ +/* LARGE FILE SUPPORT */ +/* ---------------------------------------------------------------- */ + +#if defined(_MSC_VER) && !defined(_WIN32_WCE) +# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64) +# define USE_WIN32_LARGE_FILES +# else +# define USE_WIN32_SMALL_FILES +# endif +#endif + +#if defined(__MINGW32__) && !defined(USE_WIN32_LARGE_FILES) +# define USE_WIN32_LARGE_FILES +#endif + +#if !defined(USE_WIN32_LARGE_FILES) && !defined(USE_WIN32_SMALL_FILES) +# define USE_WIN32_SMALL_FILES +#endif + +/* Number of bits in a file offset, on hosts where this is settable. */ +#if defined(USE_WIN32_LARGE_FILES) && defined(__MINGW32__) +# ifndef _FILE_OFFSET_BITS +# define _FILE_OFFSET_BITS 64 +# endif +#endif + +#ifdef USE_WIN32_LARGE_FILES +#define HAVE__FSEEKI64 +#endif + +/* Define to the size of `off_t', as computed by sizeof. */ +#if defined(__MINGW32__) && \ + defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64) +# define SIZEOF_OFF_T 8 +#else +# define SIZEOF_OFF_T 4 +#endif + +/* ---------------------------------------------------------------- */ +/* DNS RESOLVER SPECIALTY */ +/* ---------------------------------------------------------------- */ + +/* + * Undefine both USE_ARES and USE_THREADS_WIN32 for synchronous DNS. + */ + +/* Define to enable c-ares asynchronous DNS lookups. */ +/* #define USE_ARES 1 */ + +/* Default define to enable threaded asynchronous DNS lookups. */ +#if !defined(USE_SYNC_DNS) && !defined(USE_ARES) && \ + !defined(USE_THREADS_WIN32) +# define USE_THREADS_WIN32 1 +#endif + +#if defined(USE_ARES) && defined(USE_THREADS_WIN32) +# error "Only one DNS lookup specialty may be defined at most" +#endif + +/* ---------------------------------------------------------------- */ +/* LDAP SUPPORT */ +/* ---------------------------------------------------------------- */ + +#if defined(CURL_HAS_NOVELL_LDAPSDK) +#undef USE_WIN32_LDAP +#define HAVE_LDAP_SSL_H 1 +#define HAVE_LDAP_URL_PARSE 1 +#elif defined(CURL_HAS_OPENLDAP_LDAPSDK) +#undef USE_WIN32_LDAP +#define HAVE_LDAP_URL_PARSE 1 +#else +#undef HAVE_LDAP_URL_PARSE +#define HAVE_LDAP_SSL 1 +#define USE_WIN32_LDAP 1 +#endif + +/* Define to use the Windows crypto library. */ +#if !defined(CURL_WINDOWS_APP) +#define USE_WIN32_CRYPTO +#endif + +/* Define to use Unix sockets. */ +#define USE_UNIX_SOCKETS + +/* ---------------------------------------------------------------- */ +/* ADDITIONAL DEFINITIONS */ +/* ---------------------------------------------------------------- */ + +/* Define cpu-machine-OS */ +#ifndef OS +#if defined(_M_IX86) || defined(__i386__) /* x86 (MSVC or gcc) */ +#define OS "i386-pc-win32" +#elif defined(_M_X64) || defined(__x86_64__) /* x86_64 (MSVC >=2005 or gcc) */ +#define OS "x86_64-pc-win32" +#elif defined(_M_IA64) || defined(__ia64__) /* Itanium */ +#define OS "ia64-pc-win32" +#elif defined(_M_ARM_NT) || defined(__arm__) /* ARMv7-Thumb2 (Windows RT) */ +#define OS "thumbv7a-pc-win32" +#elif defined(_M_ARM64) || defined(__aarch64__) /* ARM64 (Windows 10) */ +#define OS "aarch64-pc-win32" +#else +#define OS "unknown-pc-win32" +#endif +#endif + +/* Name of package */ +#define PACKAGE "curl" + +/* If you want to build curl with the built-in manual */ +#define USE_MANUAL 1 + +#endif /* HEADER_CURL_CONFIG_WIN32_H */ diff --git a/third_party/curl/lib/config-win32ce.h b/third_party/curl/lib/config-win32ce.h new file mode 100644 index 0000000..ae3ca29 --- /dev/null +++ b/third_party/curl/lib/config-win32ce.h @@ -0,0 +1,303 @@ +#ifndef HEADER_CURL_CONFIG_WIN32CE_H +#define HEADER_CURL_CONFIG_WIN32CE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* ================================================================ */ +/* lib/config-win32ce.h - Hand crafted config file for windows ce */ +/* ================================================================ */ + +/* ---------------------------------------------------------------- */ +/* HEADER FILES */ +/* ---------------------------------------------------------------- */ + +/* Define if you have the header file. */ +/* #define HAVE_ARPA_INET_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_FCNTL_H 1 + +/* Define if you have the header file. */ +#define HAVE_IO_H 1 + +/* Define if you need the malloc.h header file even with stdlib.h */ +#define NEED_MALLOC_H 1 + +/* Define if you have the header file. */ +/* #define HAVE_NETDB_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_NETINET_IN_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_SYS_PARAM_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_SYS_SELECT_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_SYS_SOCKET_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_SYS_SOCKIO_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define if you have the header file */ +/* #define HAVE_SYS_TIME_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_SYS_TYPES_H 1 */ + +/* Define if you have the header file */ +#define HAVE_SYS_UTIME_H 1 + +/* Define if you have the header file. */ +/* #define HAVE_TERMIO_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_TERMIOS_H 1 */ + +/* Define if you have the header file. */ +#if defined(__MINGW32__) +#define HAVE_UNISTD_H 1 +#endif + +/* ---------------------------------------------------------------- */ +/* OTHER HEADER INFO */ +/* ---------------------------------------------------------------- */ + +/* Define if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* ---------------------------------------------------------------- */ +/* FUNCTIONS */ +/* ---------------------------------------------------------------- */ + +/* Define if you have the closesocket function. */ +#define HAVE_CLOSESOCKET 1 + +/* Define if you have the gethostname function. */ +#define HAVE_GETHOSTNAME 1 + +/* Define if you have the gettimeofday function. */ +/* #define HAVE_GETTIMEOFDAY 1 */ + +/* Define if you have the ioctlsocket function. */ +#define HAVE_IOCTLSOCKET 1 + +/* Define if you have a working ioctlsocket FIONBIO function. */ +#define HAVE_IOCTLSOCKET_FIONBIO 1 + +/* Define if you have the select function. */ +#define HAVE_SELECT 1 + +/* Define if you have the socket function. */ +#define HAVE_SOCKET 1 + +/* Define if you have the strcasecmp function. */ +/* #define HAVE_STRCASECMP 1 */ + +/* Define if you have the strdup function. */ +/* #define HAVE_STRDUP 1 */ + +/* Define if you have the stricmp function. */ +/* #define HAVE_STRICMP 1 */ + +/* Define if you have the strtoll function. */ +#if defined(__MINGW32__) +#define HAVE_STRTOLL 1 +#endif + +/* Define if you have the utime function */ +#define HAVE_UTIME 1 + +/* Define if you have the recv function. */ +#define HAVE_RECV 1 + +/* Define to the type of arg 1 for recv. */ +#define RECV_TYPE_ARG1 SOCKET + +/* Define to the type of arg 2 for recv. */ +#define RECV_TYPE_ARG2 char * + +/* Define to the type of arg 3 for recv. */ +#define RECV_TYPE_ARG3 int + +/* Define to the type of arg 4 for recv. */ +#define RECV_TYPE_ARG4 int + +/* Define to the function return type for recv. */ +#define RECV_TYPE_RETV int + +/* Define if you have the send function. */ +#define HAVE_SEND 1 + +/* Define to the type of arg 1 for send. */ +#define SEND_TYPE_ARG1 SOCKET + +/* Define to the type qualifier of arg 2 for send. */ +#define SEND_QUAL_ARG2 const + +/* Define to the type of arg 2 for send. */ +#define SEND_TYPE_ARG2 char * + +/* Define to the type of arg 3 for send. */ +#define SEND_TYPE_ARG3 int + +/* Define to the type of arg 4 for send. */ +#define SEND_TYPE_ARG4 int + +/* Define to the function return type for send. */ +#define SEND_TYPE_RETV int + +/* ---------------------------------------------------------------- */ +/* TYPEDEF REPLACEMENTS */ +/* ---------------------------------------------------------------- */ + +/* Define this if in_addr_t is not an available 'typedefed' type */ +#define in_addr_t unsigned long + +/* Define ssize_t if it is not an available 'typedefed' type */ +#if defined(_WIN64) +#define ssize_t __int64 +#else +#define ssize_t int +#endif + +/* ---------------------------------------------------------------- */ +/* TYPE SIZES */ +/* ---------------------------------------------------------------- */ + +/* The size of `int', as computed by sizeof. */ +#define SIZEOF_INT 4 + +/* The size of `long long', as computed by sizeof. */ +/* #define SIZEOF_LONG_LONG 8 */ + +/* Define to the size of `long', as computed by sizeof. */ +#define SIZEOF_LONG 4 + +/* The size of `size_t', as computed by sizeof. */ +#if defined(_WIN64) +# define SIZEOF_SIZE_T 8 +#else +# define SIZEOF_SIZE_T 4 +#endif + +/* ---------------------------------------------------------------- */ +/* STRUCT RELATED */ +/* ---------------------------------------------------------------- */ + +/* Define this if you have struct sockaddr_storage */ +/* #define HAVE_STRUCT_SOCKADDR_STORAGE 1 */ + +/* Define this if you have struct timeval */ +#define HAVE_STRUCT_TIMEVAL 1 + +/* Define this if struct sockaddr_in6 has the sin6_scope_id member */ +#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 + +/* ---------------------------------------------------------------- */ +/* COMPILER SPECIFIC */ +/* ---------------------------------------------------------------- */ + +/* Undef keyword 'const' if it does not work. */ +/* #undef const */ + +/* Define to avoid VS2005 complaining about portable C functions */ +#if defined(_MSC_VER) && (_MSC_VER >= 1400) +#define _CRT_SECURE_NO_DEPRECATE 1 +#define _CRT_NONSTDC_NO_DEPRECATE 1 +#endif + +/* VS2005 and later default size for time_t is 64-bit, unless */ +/* _USE_32BIT_TIME_T has been defined to get a 32-bit time_t. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1400) +# ifndef _USE_32BIT_TIME_T +# define SIZEOF_TIME_T 8 +# else +# define SIZEOF_TIME_T 4 +# endif +#endif + +/* ---------------------------------------------------------------- */ +/* LARGE FILE SUPPORT */ +/* ---------------------------------------------------------------- */ + +#if defined(_MSC_VER) && !defined(_WIN32_WCE) +# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64) +# define USE_WIN32_LARGE_FILES +# else +# define USE_WIN32_SMALL_FILES +# endif +#endif + +#if !defined(USE_WIN32_LARGE_FILES) && !defined(USE_WIN32_SMALL_FILES) +# define USE_WIN32_SMALL_FILES +#endif + +/* ---------------------------------------------------------------- */ +/* LDAP SUPPORT */ +/* ---------------------------------------------------------------- */ + +#define USE_WIN32_LDAP 1 +#undef HAVE_LDAP_URL_PARSE + +/* ---------------------------------------------------------------- */ +/* ADDITIONAL DEFINITIONS */ +/* ---------------------------------------------------------------- */ + +/* Define cpu-machine-OS */ +#ifndef OS +#define OS "i386-pc-win32ce" +#endif + +/* Name of package */ +#define PACKAGE "curl" + +/* ---------------------------------------------------------------- */ +/* WinCE */ +/* ---------------------------------------------------------------- */ + +#ifndef UNICODE +# define UNICODE +#endif + +#ifndef _UNICODE +# define _UNICODE +#endif + +#define CURL_DISABLE_FILE 1 +#define CURL_DISABLE_TELNET 1 +#define CURL_DISABLE_LDAP 1 + +#define ENOSPC 1 +#define ENOMEM 2 +#define EAGAIN 3 + +extern int stat(const char *path, struct stat *buffer); + +#endif /* HEADER_CURL_CONFIG_WIN32CE_H */ diff --git a/third_party/curl/lib/conncache.c b/third_party/curl/lib/conncache.c new file mode 100644 index 0000000..2b5ee4f --- /dev/null +++ b/third_party/curl/lib/conncache.c @@ -0,0 +1,581 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Linus Nielsen Feltzing, + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "urldata.h" +#include "url.h" +#include "progress.h" +#include "multiif.h" +#include "sendf.h" +#include "conncache.h" +#include "share.h" +#include "sigpipe.h" +#include "connect.h" +#include "strcase.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#define HASHKEY_SIZE 128 + +static CURLcode bundle_create(struct connectbundle **bundlep) +{ + DEBUGASSERT(*bundlep == NULL); + *bundlep = malloc(sizeof(struct connectbundle)); + if(!*bundlep) + return CURLE_OUT_OF_MEMORY; + + (*bundlep)->num_connections = 0; + (*bundlep)->multiuse = BUNDLE_UNKNOWN; + + Curl_llist_init(&(*bundlep)->conn_list, NULL); + return CURLE_OK; +} + +static void bundle_destroy(struct connectbundle *bundle) +{ + free(bundle); +} + +/* Add a connection to a bundle */ +static void bundle_add_conn(struct connectbundle *bundle, + struct connectdata *conn) +{ + Curl_llist_append(&bundle->conn_list, conn, &conn->bundle_node); + conn->bundle = bundle; + bundle->num_connections++; +} + +/* Remove a connection from a bundle */ +static int bundle_remove_conn(struct connectbundle *bundle, + struct connectdata *conn) +{ + struct Curl_llist_element *curr; + + curr = bundle->conn_list.head; + while(curr) { + if(curr->ptr == conn) { + Curl_llist_remove(&bundle->conn_list, curr, NULL); + bundle->num_connections--; + conn->bundle = NULL; + return 1; /* we removed a handle */ + } + curr = curr->next; + } + DEBUGASSERT(0); + return 0; +} + +static void free_bundle_hash_entry(void *freethis) +{ + struct connectbundle *b = (struct connectbundle *) freethis; + + bundle_destroy(b); +} + +int Curl_conncache_init(struct conncache *connc, size_t size) +{ + /* allocate a new easy handle to use when closing cached connections */ + connc->closure_handle = curl_easy_init(); + if(!connc->closure_handle) + return 1; /* bad */ + connc->closure_handle->state.internal = true; + + Curl_hash_init(&connc->hash, size, Curl_hash_str, + Curl_str_key_compare, free_bundle_hash_entry); + connc->closure_handle->state.conn_cache = connc; + + return 0; /* good */ +} + +void Curl_conncache_destroy(struct conncache *connc) +{ + if(connc) + Curl_hash_destroy(&connc->hash); +} + +/* creates a key to find a bundle for this connection */ +static void hashkey(struct connectdata *conn, char *buf, size_t len) +{ + const char *hostname; + long port = conn->remote_port; + DEBUGASSERT(len >= HASHKEY_SIZE); +#ifndef CURL_DISABLE_PROXY + if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) { + hostname = conn->http_proxy.host.name; + port = conn->primary.remote_port; + } + else +#endif + if(conn->bits.conn_to_host) + hostname = conn->conn_to_host.name; + else + hostname = conn->host.name; + + /* put the numbers first so that the hostname gets cut off if too long */ +#ifdef USE_IPV6 + msnprintf(buf, len, "%u/%ld/%s", conn->scope_id, port, hostname); +#else + msnprintf(buf, len, "%ld/%s", port, hostname); +#endif + Curl_strntolower(buf, buf, len); +} + +/* Returns number of connections currently held in the connection cache. + Locks/unlocks the cache itself! +*/ +size_t Curl_conncache_size(struct Curl_easy *data) +{ + size_t num; + CONNCACHE_LOCK(data); + num = data->state.conn_cache->num_conn; + CONNCACHE_UNLOCK(data); + return num; +} + +/* Look up the bundle with all the connections to the same host this + connectdata struct is setup to use. + + **NOTE**: When it returns, it holds the connection cache lock! */ +struct connectbundle * +Curl_conncache_find_bundle(struct Curl_easy *data, + struct connectdata *conn, + struct conncache *connc) +{ + struct connectbundle *bundle = NULL; + CONNCACHE_LOCK(data); + if(connc) { + char key[HASHKEY_SIZE]; + hashkey(conn, key, sizeof(key)); + bundle = Curl_hash_pick(&connc->hash, key, strlen(key)); + } + + return bundle; +} + +static void *conncache_add_bundle(struct conncache *connc, + char *key, + struct connectbundle *bundle) +{ + return Curl_hash_add(&connc->hash, key, strlen(key), bundle); +} + +static void conncache_remove_bundle(struct conncache *connc, + struct connectbundle *bundle) +{ + struct Curl_hash_iterator iter; + struct Curl_hash_element *he; + + if(!connc) + return; + + Curl_hash_start_iterate(&connc->hash, &iter); + + he = Curl_hash_next_element(&iter); + while(he) { + if(he->ptr == bundle) { + /* The bundle is destroyed by the hash destructor function, + free_bundle_hash_entry() */ + Curl_hash_delete(&connc->hash, he->key, he->key_len); + return; + } + + he = Curl_hash_next_element(&iter); + } +} + +CURLcode Curl_conncache_add_conn(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct connectbundle *bundle = NULL; + struct connectdata *conn = data->conn; + struct conncache *connc = data->state.conn_cache; + DEBUGASSERT(conn); + + /* *find_bundle() locks the connection cache */ + bundle = Curl_conncache_find_bundle(data, conn, data->state.conn_cache); + if(!bundle) { + char key[HASHKEY_SIZE]; + + result = bundle_create(&bundle); + if(result) { + goto unlock; + } + + hashkey(conn, key, sizeof(key)); + + if(!conncache_add_bundle(data->state.conn_cache, key, bundle)) { + bundle_destroy(bundle); + result = CURLE_OUT_OF_MEMORY; + goto unlock; + } + } + + bundle_add_conn(bundle, conn); + conn->connection_id = connc->next_connection_id++; + connc->num_conn++; + + DEBUGF(infof(data, "Added connection %" CURL_FORMAT_CURL_OFF_T ". " + "The cache now contains %zu members", + conn->connection_id, connc->num_conn)); + +unlock: + CONNCACHE_UNLOCK(data); + + return result; +} + +/* + * Removes the connectdata object from the connection cache, but the transfer + * still owns this connection. + * + * Pass TRUE/FALSE in the 'lock' argument depending on if the parent function + * already holds the lock or not. + */ +void Curl_conncache_remove_conn(struct Curl_easy *data, + struct connectdata *conn, bool lock) +{ + struct connectbundle *bundle = conn->bundle; + struct conncache *connc = data->state.conn_cache; + + /* The bundle pointer can be NULL, since this function can be called + due to a failed connection attempt, before being added to a bundle */ + if(bundle) { + if(lock) { + CONNCACHE_LOCK(data); + } + bundle_remove_conn(bundle, conn); + if(bundle->num_connections == 0) + conncache_remove_bundle(connc, bundle); + conn->bundle = NULL; /* removed from it */ + if(connc) { + connc->num_conn--; + DEBUGF(infof(data, "The cache now contains %zu members", + connc->num_conn)); + } + if(lock) { + CONNCACHE_UNLOCK(data); + } + } +} + +/* This function iterates the entire connection cache and calls the function + func() with the connection pointer as the first argument and the supplied + 'param' argument as the other. + + The conncache lock is still held when the callback is called. It needs it, + so that it can safely continue traversing the lists once the callback + returns. + + Returns 1 if the loop was aborted due to the callback's return code. + + Return 0 from func() to continue the loop, return 1 to abort it. + */ +bool Curl_conncache_foreach(struct Curl_easy *data, + struct conncache *connc, + void *param, + int (*func)(struct Curl_easy *data, + struct connectdata *conn, void *param)) +{ + struct Curl_hash_iterator iter; + struct Curl_llist_element *curr; + struct Curl_hash_element *he; + + if(!connc) + return FALSE; + + CONNCACHE_LOCK(data); + Curl_hash_start_iterate(&connc->hash, &iter); + + he = Curl_hash_next_element(&iter); + while(he) { + struct connectbundle *bundle; + + bundle = he->ptr; + he = Curl_hash_next_element(&iter); + + curr = bundle->conn_list.head; + while(curr) { + /* Yes, we need to update curr before calling func(), because func() + might decide to remove the connection */ + struct connectdata *conn = curr->ptr; + curr = curr->next; + + if(1 == func(data, conn, param)) { + CONNCACHE_UNLOCK(data); + return TRUE; + } + } + } + CONNCACHE_UNLOCK(data); + return FALSE; +} + +/* Return the first connection found in the cache. Used when closing all + connections. + + NOTE: no locking is done here as this is presumably only done when cleaning + up a cache! +*/ +static struct connectdata * +conncache_find_first_connection(struct conncache *connc) +{ + struct Curl_hash_iterator iter; + struct Curl_hash_element *he; + struct connectbundle *bundle; + + Curl_hash_start_iterate(&connc->hash, &iter); + + he = Curl_hash_next_element(&iter); + while(he) { + struct Curl_llist_element *curr; + bundle = he->ptr; + + curr = bundle->conn_list.head; + if(curr) { + return curr->ptr; + } + + he = Curl_hash_next_element(&iter); + } + + return NULL; +} + +/* + * Give ownership of a connection back to the connection cache. Might + * disconnect the oldest existing in there to make space. + * + * Return TRUE if stored, FALSE if closed. + */ +bool Curl_conncache_return_conn(struct Curl_easy *data, + struct connectdata *conn) +{ + unsigned int maxconnects = !data->multi->maxconnects ? + data->multi->num_easy * 4: data->multi->maxconnects; + struct connectdata *conn_candidate = NULL; + + conn->lastused = Curl_now(); /* it was used up until now */ + if(maxconnects && Curl_conncache_size(data) > maxconnects) { + infof(data, "Connection cache is full, closing the oldest one"); + + conn_candidate = Curl_conncache_extract_oldest(data); + if(conn_candidate) { + /* Use the closure handle for this disconnect so that anything that + happens during the disconnect is not stored and associated with the + 'data' handle which already just finished a transfer and it is + important that details from this (unrelated) disconnect does not + taint meta-data in the data handle. */ + struct conncache *connc = data->state.conn_cache; + Curl_disconnect(connc->closure_handle, conn_candidate, + /* dead_connection */ FALSE); + } + } + + return (conn_candidate == conn) ? FALSE : TRUE; + +} + +/* + * This function finds the connection in the connection bundle that has been + * unused for the longest time. + * + * Does not lock the connection cache! + * + * Returns the pointer to the oldest idle connection, or NULL if none was + * found. + */ +struct connectdata * +Curl_conncache_extract_bundle(struct Curl_easy *data, + struct connectbundle *bundle) +{ + struct Curl_llist_element *curr; + timediff_t highscore = -1; + timediff_t score; + struct curltime now; + struct connectdata *conn_candidate = NULL; + struct connectdata *conn; + + (void)data; + + now = Curl_now(); + + curr = bundle->conn_list.head; + while(curr) { + conn = curr->ptr; + + if(!CONN_INUSE(conn)) { + /* Set higher score for the age passed since the connection was used */ + score = Curl_timediff(now, conn->lastused); + + if(score > highscore) { + highscore = score; + conn_candidate = conn; + } + } + curr = curr->next; + } + if(conn_candidate) { + /* remove it to prevent another thread from nicking it */ + bundle_remove_conn(bundle, conn_candidate); + data->state.conn_cache->num_conn--; + DEBUGF(infof(data, "The cache now contains %zu members", + data->state.conn_cache->num_conn)); + } + + return conn_candidate; +} + +/* + * This function finds the connection in the connection cache that has been + * unused for the longest time and extracts that from the bundle. + * + * Returns the pointer to the connection, or NULL if none was found. + */ +struct connectdata * +Curl_conncache_extract_oldest(struct Curl_easy *data) +{ + struct conncache *connc = data->state.conn_cache; + struct Curl_hash_iterator iter; + struct Curl_llist_element *curr; + struct Curl_hash_element *he; + timediff_t highscore =- 1; + timediff_t score; + struct curltime now; + struct connectdata *conn_candidate = NULL; + struct connectbundle *bundle; + struct connectbundle *bundle_candidate = NULL; + + now = Curl_now(); + + CONNCACHE_LOCK(data); + Curl_hash_start_iterate(&connc->hash, &iter); + + he = Curl_hash_next_element(&iter); + while(he) { + struct connectdata *conn; + + bundle = he->ptr; + + curr = bundle->conn_list.head; + while(curr) { + conn = curr->ptr; + + if(!CONN_INUSE(conn) && !conn->bits.close && + !conn->connect_only) { + /* Set higher score for the age passed since the connection was used */ + score = Curl_timediff(now, conn->lastused); + + if(score > highscore) { + highscore = score; + conn_candidate = conn; + bundle_candidate = bundle; + } + } + curr = curr->next; + } + + he = Curl_hash_next_element(&iter); + } + if(conn_candidate) { + /* remove it to prevent another thread from nicking it */ + bundle_remove_conn(bundle_candidate, conn_candidate); + connc->num_conn--; + DEBUGF(infof(data, "The cache now contains %zu members", + connc->num_conn)); + } + CONNCACHE_UNLOCK(data); + + return conn_candidate; +} + +void Curl_conncache_close_all_connections(struct conncache *connc) +{ + struct connectdata *conn; + SIGPIPE_VARIABLE(pipe_st); + if(!connc->closure_handle) + return; + + conn = conncache_find_first_connection(connc); + while(conn) { + sigpipe_ignore(connc->closure_handle, &pipe_st); + /* This will remove the connection from the cache */ + connclose(conn, "kill all"); + Curl_conncache_remove_conn(connc->closure_handle, conn, TRUE); + Curl_disconnect(connc->closure_handle, conn, FALSE); + sigpipe_restore(&pipe_st); + + conn = conncache_find_first_connection(connc); + } + + sigpipe_ignore(connc->closure_handle, &pipe_st); + + Curl_hostcache_clean(connc->closure_handle, + connc->closure_handle->dns.hostcache); + Curl_close(&connc->closure_handle); + sigpipe_restore(&pipe_st); +} + +#if 0 +/* Useful for debugging the connection cache */ +void Curl_conncache_print(struct conncache *connc) +{ + struct Curl_hash_iterator iter; + struct Curl_llist_element *curr; + struct Curl_hash_element *he; + + if(!connc) + return; + + fprintf(stderr, "=Bundle cache=\n"); + + Curl_hash_start_iterate(connc->hash, &iter); + + he = Curl_hash_next_element(&iter); + while(he) { + struct connectbundle *bundle; + struct connectdata *conn; + + bundle = he->ptr; + + fprintf(stderr, "%s -", he->key); + curr = bundle->conn_list->head; + while(curr) { + conn = curr->ptr; + + fprintf(stderr, " [%p %d]", (void *)conn, conn->inuse); + curr = curr->next; + } + fprintf(stderr, "\n"); + + he = Curl_hash_next_element(&iter); + } +} +#endif diff --git a/third_party/curl/lib/conncache.h b/third_party/curl/lib/conncache.h new file mode 100644 index 0000000..e685123 --- /dev/null +++ b/third_party/curl/lib/conncache.h @@ -0,0 +1,122 @@ +#ifndef HEADER_CURL_CONNCACHE_H +#define HEADER_CURL_CONNCACHE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (C) Linus Nielsen Feltzing, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * All accesses to struct fields and changing of data in the connection cache + * and connectbundles must be done with the conncache LOCKED. The cache might + * be shared. + */ + +#include +#include "timeval.h" + +struct connectdata; + +struct conncache { + struct Curl_hash hash; + size_t num_conn; + curl_off_t next_connection_id; + curl_off_t next_easy_id; + struct curltime last_cleanup; + /* handle used for closing cached connections */ + struct Curl_easy *closure_handle; +}; + +#define BUNDLE_NO_MULTIUSE -1 +#define BUNDLE_UNKNOWN 0 /* initial value */ +#define BUNDLE_MULTIPLEX 2 + +#ifdef CURLDEBUG +/* the debug versions of these macros make extra certain that the lock is + never doubly locked or unlocked */ +#define CONNCACHE_LOCK(x) \ + do { \ + if((x)->share) { \ + Curl_share_lock((x), CURL_LOCK_DATA_CONNECT, \ + CURL_LOCK_ACCESS_SINGLE); \ + DEBUGASSERT(!(x)->state.conncache_lock); \ + (x)->state.conncache_lock = TRUE; \ + } \ + } while(0) + +#define CONNCACHE_UNLOCK(x) \ + do { \ + if((x)->share) { \ + DEBUGASSERT((x)->state.conncache_lock); \ + (x)->state.conncache_lock = FALSE; \ + Curl_share_unlock((x), CURL_LOCK_DATA_CONNECT); \ + } \ + } while(0) +#else +#define CONNCACHE_LOCK(x) if((x)->share) \ + Curl_share_lock((x), CURL_LOCK_DATA_CONNECT, CURL_LOCK_ACCESS_SINGLE) +#define CONNCACHE_UNLOCK(x) if((x)->share) \ + Curl_share_unlock((x), CURL_LOCK_DATA_CONNECT) +#endif + +struct connectbundle { + int multiuse; /* supports multi-use */ + size_t num_connections; /* Number of connections in the bundle */ + struct Curl_llist conn_list; /* The connectdata members of the bundle */ +}; + +/* returns 1 on error, 0 is fine */ +int Curl_conncache_init(struct conncache *, size_t size); +void Curl_conncache_destroy(struct conncache *connc); + +/* return the correct bundle, to a host or a proxy */ +struct connectbundle *Curl_conncache_find_bundle(struct Curl_easy *data, + struct connectdata *conn, + struct conncache *connc); +/* returns number of connections currently held in the connection cache */ +size_t Curl_conncache_size(struct Curl_easy *data); + +bool Curl_conncache_return_conn(struct Curl_easy *data, + struct connectdata *conn); +CURLcode Curl_conncache_add_conn(struct Curl_easy *data) WARN_UNUSED_RESULT; +void Curl_conncache_remove_conn(struct Curl_easy *data, + struct connectdata *conn, + bool lock); +bool Curl_conncache_foreach(struct Curl_easy *data, + struct conncache *connc, + void *param, + int (*func)(struct Curl_easy *data, + struct connectdata *conn, + void *param)); + +struct connectdata * +Curl_conncache_find_first_connection(struct conncache *connc); + +struct connectdata * +Curl_conncache_extract_bundle(struct Curl_easy *data, + struct connectbundle *bundle); +struct connectdata * +Curl_conncache_extract_oldest(struct Curl_easy *data); +void Curl_conncache_close_all_connections(struct conncache *connc); +void Curl_conncache_print(struct conncache *connc); + +#endif /* HEADER_CURL_CONNCACHE_H */ diff --git a/third_party/curl/lib/connect.c b/third_party/curl/lib/connect.c new file mode 100644 index 0000000..bf85e64 --- /dev/null +++ b/third_party/curl/lib/connect.c @@ -0,0 +1,1446 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include /* may need it */ +#endif +#ifdef HAVE_SYS_UN_H +#include /* for sockaddr_un */ +#endif +#ifdef HAVE_LINUX_TCP_H +#include +#elif defined(HAVE_NETINET_TCP_H) +#include +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_FCNTL_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif + +#ifdef __VMS +#include +#include +#endif + +#include "urldata.h" +#include "sendf.h" +#include "if2ip.h" +#include "strerror.h" +#include "cfilters.h" +#include "connect.h" +#include "cf-haproxy.h" +#include "cf-https-connect.h" +#include "cf-socket.h" +#include "select.h" +#include "url.h" /* for Curl_safefree() */ +#include "multiif.h" +#include "sockaddr.h" /* required for Curl_sockaddr_storage */ +#include "inet_ntop.h" +#include "inet_pton.h" +#include "vtls/vtls.h" /* for vtsl cfilters */ +#include "progress.h" +#include "warnless.h" +#include "conncache.h" +#include "multihandle.h" +#include "share.h" +#include "version_win32.h" +#include "vquic/vquic.h" /* for quic cfilters */ +#include "http_proxy.h" +#include "socks.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#ifndef ARRAYSIZE +#define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) +#endif + +/* + * Curl_timeleft() returns the amount of milliseconds left allowed for the + * transfer/connection. If the value is 0, there's no timeout (ie there's + * infinite time left). If the value is negative, the timeout time has already + * elapsed. + * @param data the transfer to check on + * @param nowp timestamp to use for calculation, NULL to use Curl_now() + * @param duringconnect TRUE iff connect timeout is also taken into account. + * @unittest: 1303 + */ +timediff_t Curl_timeleft(struct Curl_easy *data, + struct curltime *nowp, + bool duringconnect) +{ + timediff_t timeleft_ms = 0; + timediff_t ctimeleft_ms = 0; + struct curltime now; + + /* The duration of a connect and the total transfer are calculated from two + different time-stamps. It can end up with the total timeout being reached + before the connect timeout expires and we must acknowledge whichever + timeout that is reached first. The total timeout is set per entire + operation, while the connect timeout is set per connect. */ + if(data->set.timeout <= 0 && !duringconnect) + return 0; /* no timeout in place or checked, return "no limit" */ + + if(!nowp) { + now = Curl_now(); + nowp = &now; + } + + if(data->set.timeout > 0) { + timeleft_ms = data->set.timeout - + Curl_timediff(*nowp, data->progress.t_startop); + if(!timeleft_ms) + timeleft_ms = -1; /* 0 is "no limit", fake 1 ms expiry */ + if(!duringconnect) + return timeleft_ms; /* no connect check, this is it */ + } + + if(duringconnect) { + timediff_t ctimeout_ms = (data->set.connecttimeout > 0) ? + data->set.connecttimeout : DEFAULT_CONNECT_TIMEOUT; + ctimeleft_ms = ctimeout_ms - + Curl_timediff(*nowp, data->progress.t_startsingle); + if(!ctimeleft_ms) + ctimeleft_ms = -1; /* 0 is "no limit", fake 1 ms expiry */ + if(!timeleft_ms) + return ctimeleft_ms; /* no general timeout, this is it */ + } + /* return minimal time left or max amount already expired */ + return (ctimeleft_ms < timeleft_ms)? ctimeleft_ms : timeleft_ms; +} + +/* Copies connection info into the transfer handle to make it available when + the transfer handle is no longer associated with the connection. */ +void Curl_persistconninfo(struct Curl_easy *data, struct connectdata *conn, + struct ip_quadruple *ip) +{ + if(ip) + data->info.primary = *ip; + else { + memset(&data->info.primary, 0, sizeof(data->info.primary)); + data->info.primary.remote_port = -1; + data->info.primary.local_port = -1; + } + data->info.conn_scheme = conn->handler->scheme; + /* conn_protocol can only provide "old" protocols */ + data->info.conn_protocol = (conn->handler->protocol) & CURLPROTO_MASK; + data->info.conn_remote_port = conn->remote_port; + data->info.used_proxy = +#ifdef CURL_DISABLE_PROXY + 0 +#else + conn->bits.proxy +#endif + ; +} + +static const struct Curl_addrinfo * +addr_first_match(const struct Curl_addrinfo *addr, int family) +{ + while(addr) { + if(addr->ai_family == family) + return addr; + addr = addr->ai_next; + } + return NULL; +} + +static const struct Curl_addrinfo * +addr_next_match(const struct Curl_addrinfo *addr, int family) +{ + while(addr && addr->ai_next) { + addr = addr->ai_next; + if(addr->ai_family == family) + return addr; + } + return NULL; +} + +/* retrieves ip address and port from a sockaddr structure. + note it calls Curl_inet_ntop which sets errno on fail, not SOCKERRNO. */ +bool Curl_addr2string(struct sockaddr *sa, curl_socklen_t salen, + char *addr, int *port) +{ + struct sockaddr_in *si = NULL; +#ifdef USE_IPV6 + struct sockaddr_in6 *si6 = NULL; +#endif +#if (defined(HAVE_SYS_UN_H) || defined(WIN32_SOCKADDR_UN)) && defined(AF_UNIX) + struct sockaddr_un *su = NULL; +#else + (void)salen; +#endif + + switch(sa->sa_family) { + case AF_INET: + si = (struct sockaddr_in *)(void *) sa; + if(Curl_inet_ntop(sa->sa_family, &si->sin_addr, + addr, MAX_IPADR_LEN)) { + unsigned short us_port = ntohs(si->sin_port); + *port = us_port; + return TRUE; + } + break; +#ifdef USE_IPV6 + case AF_INET6: + si6 = (struct sockaddr_in6 *)(void *) sa; + if(Curl_inet_ntop(sa->sa_family, &si6->sin6_addr, + addr, MAX_IPADR_LEN)) { + unsigned short us_port = ntohs(si6->sin6_port); + *port = us_port; + return TRUE; + } + break; +#endif +#if (defined(HAVE_SYS_UN_H) || defined(WIN32_SOCKADDR_UN)) && defined(AF_UNIX) + case AF_UNIX: + if(salen > (curl_socklen_t)sizeof(CURL_SA_FAMILY_T)) { + su = (struct sockaddr_un*)sa; + msnprintf(addr, MAX_IPADR_LEN, "%s", su->sun_path); + } + else + addr[0] = 0; /* socket with no name */ + *port = 0; + return TRUE; +#endif + default: + break; + } + + addr[0] = '\0'; + *port = 0; + errno = EAFNOSUPPORT; + return FALSE; +} + +struct connfind { + curl_off_t id_tofind; + struct connectdata *found; +}; + +static int conn_is_conn(struct Curl_easy *data, + struct connectdata *conn, void *param) +{ + struct connfind *f = (struct connfind *)param; + (void)data; + if(conn->connection_id == f->id_tofind) { + f->found = conn; + return 1; + } + return 0; +} + +/* + * Used to extract socket and connectdata struct for the most recent + * transfer on the given Curl_easy. + * + * The returned socket will be CURL_SOCKET_BAD in case of failure! + */ +curl_socket_t Curl_getconnectinfo(struct Curl_easy *data, + struct connectdata **connp) +{ + DEBUGASSERT(data); + + /* this works for an easy handle: + * - that has been used for curl_easy_perform() + * - that is associated with a multi handle, and whose connection + * was detached with CURLOPT_CONNECT_ONLY + */ + if((data->state.lastconnect_id != -1) && (data->multi_easy || data->multi)) { + struct connectdata *c; + struct connfind find; + find.id_tofind = data->state.lastconnect_id; + find.found = NULL; + + Curl_conncache_foreach(data, + data->share && (data->share->specifier + & (1<< CURL_LOCK_DATA_CONNECT))? + &data->share->conn_cache: + data->multi_easy? + &data->multi_easy->conn_cache: + &data->multi->conn_cache, &find, conn_is_conn); + + if(!find.found) { + data->state.lastconnect_id = -1; + return CURL_SOCKET_BAD; + } + + c = find.found; + if(connp) + /* only store this if the caller cares for it */ + *connp = c; + return c->sock[FIRSTSOCKET]; + } + return CURL_SOCKET_BAD; +} + +/* + * Curl_conncontrol() marks streams or connection for closure. + */ +void Curl_conncontrol(struct connectdata *conn, + int ctrl /* see defines in header */ +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + , const char *reason +#endif + ) +{ + /* close if a connection, or a stream that isn't multiplexed. */ + /* This function will be called both before and after this connection is + associated with a transfer. */ + bool closeit, is_multiplex; + DEBUGASSERT(conn); +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + (void)reason; /* useful for debugging */ +#endif + is_multiplex = Curl_conn_is_multiplex(conn, FIRSTSOCKET); + closeit = (ctrl == CONNCTRL_CONNECTION) || + ((ctrl == CONNCTRL_STREAM) && !is_multiplex); + if((ctrl == CONNCTRL_STREAM) && is_multiplex) + ; /* stream signal on multiplex conn never affects close state */ + else if((bit)closeit != conn->bits.close) { + conn->bits.close = closeit; /* the only place in the source code that + should assign this bit */ + } +} + +/** + * job walking the matching addr infos, creating a sub-cfilter with the + * provided method `cf_create` and running setup/connect on it. + */ +struct eyeballer { + const char *name; + const struct Curl_addrinfo *first; /* complete address list, not owned */ + const struct Curl_addrinfo *addr; /* List of addresses to try, not owned */ + int ai_family; /* matching address family only */ + cf_ip_connect_create *cf_create; /* for creating cf */ + struct Curl_cfilter *cf; /* current sub-cfilter connecting */ + struct eyeballer *primary; /* eyeballer this one is backup for */ + timediff_t delay_ms; /* delay until start */ + struct curltime started; /* start of current attempt */ + timediff_t timeoutms; /* timeout for current attempt */ + expire_id timeout_id; /* ID for Curl_expire() */ + CURLcode result; + int error; + BIT(rewinded); /* if we rewinded the addr list */ + BIT(has_started); /* attempts have started */ + BIT(is_done); /* out of addresses/time */ + BIT(connected); /* cf has connected */ + BIT(inconclusive); /* connect was not a hard failure, we + * might talk to a restarting server */ +}; + + +typedef enum { + SCFST_INIT, + SCFST_WAITING, + SCFST_DONE +} cf_connect_state; + +struct cf_he_ctx { + int transport; + cf_ip_connect_create *cf_create; + const struct Curl_dns_entry *remotehost; + cf_connect_state state; + struct eyeballer *baller[2]; + struct eyeballer *winner; + struct curltime started; +}; + +/* when there are more than one IP address left to use, this macro returns how + much of the given timeout to spend on *this* attempt */ +#define TIMEOUT_LARGE 600 +#define USETIME(ms) ((ms > TIMEOUT_LARGE) ? (ms / 2) : ms) + +static CURLcode eyeballer_new(struct eyeballer **pballer, + cf_ip_connect_create *cf_create, + const struct Curl_addrinfo *addr, + int ai_family, + struct eyeballer *primary, + timediff_t delay_ms, + timediff_t timeout_ms, + expire_id timeout_id) +{ + struct eyeballer *baller; + + *pballer = NULL; + baller = calloc(1, sizeof(*baller)); + if(!baller) + return CURLE_OUT_OF_MEMORY; + + baller->name = ((ai_family == AF_INET)? "ipv4" : ( +#ifdef USE_IPV6 + (ai_family == AF_INET6)? "ipv6" : +#endif + "ip")); + baller->cf_create = cf_create; + baller->first = baller->addr = addr; + baller->ai_family = ai_family; + baller->primary = primary; + baller->delay_ms = delay_ms; + baller->timeoutms = addr_next_match(baller->addr, baller->ai_family)? + USETIME(timeout_ms) : timeout_ms; + baller->timeout_id = timeout_id; + baller->result = CURLE_COULDNT_CONNECT; + + *pballer = baller; + return CURLE_OK; +} + +static void baller_close(struct eyeballer *baller, + struct Curl_easy *data) +{ + if(baller && baller->cf) { + Curl_conn_cf_discard_chain(&baller->cf, data); + } +} + +static void baller_free(struct eyeballer *baller, + struct Curl_easy *data) +{ + if(baller) { + baller_close(baller, data); + free(baller); + } +} + +static void baller_rewind(struct eyeballer *baller) +{ + baller->rewinded = TRUE; + baller->addr = baller->first; + baller->inconclusive = FALSE; +} + +static void baller_next_addr(struct eyeballer *baller) +{ + baller->addr = addr_next_match(baller->addr, baller->ai_family); +} + +/* + * Initiate a connect attempt walk. + * + * Note that even on connect fail it returns CURLE_OK, but with 'sock' set to + * CURL_SOCKET_BAD. Other errors will however return proper errors. + */ +static void baller_initiate(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct eyeballer *baller) +{ + struct cf_he_ctx *ctx = cf->ctx; + struct Curl_cfilter *cf_prev = baller->cf; + struct Curl_cfilter *wcf; + CURLcode result; + + + /* Don't close a previous cfilter yet to ensure that the next IP's + socket gets a different file descriptor, which can prevent bugs when + the curl_multi_socket_action interface is used with certain select() + replacements such as kqueue. */ + result = baller->cf_create(&baller->cf, data, cf->conn, baller->addr, + ctx->transport); + if(result) + goto out; + + /* the new filter might have sub-filters */ + for(wcf = baller->cf; wcf; wcf = wcf->next) { + wcf->conn = cf->conn; + wcf->sockindex = cf->sockindex; + } + + if(addr_next_match(baller->addr, baller->ai_family)) { + Curl_expire(data, baller->timeoutms, baller->timeout_id); + } + +out: + if(result) { + CURL_TRC_CF(data, cf, "%s failed", baller->name); + baller_close(baller, data); + } + if(cf_prev) + Curl_conn_cf_discard_chain(&cf_prev, data); + baller->result = result; +} + +/** + * Start a connection attempt on the current baller address. + * Will return CURLE_OK on the first address where a socket + * could be created and the non-blocking connect started. + * Returns error when all remaining addresses have been tried. + */ +static CURLcode baller_start(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct eyeballer *baller, + timediff_t timeoutms) +{ + baller->error = 0; + baller->connected = FALSE; + baller->has_started = TRUE; + + while(baller->addr) { + baller->started = Curl_now(); + baller->timeoutms = addr_next_match(baller->addr, baller->ai_family) ? + USETIME(timeoutms) : timeoutms; + baller_initiate(cf, data, baller); + if(!baller->result) + break; + baller_next_addr(baller); + } + if(!baller->addr) { + baller->is_done = TRUE; + } + return baller->result; +} + + +/* Used within the multi interface. Try next IP address, returns error if no + more address exists or error */ +static CURLcode baller_start_next(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct eyeballer *baller, + timediff_t timeoutms) +{ + if(cf->sockindex == FIRSTSOCKET) { + baller_next_addr(baller); + /* If we get inconclusive answers from the server(s), we make + * a second iteration over the address list */ + if(!baller->addr && baller->inconclusive && !baller->rewinded) + baller_rewind(baller); + baller_start(cf, data, baller, timeoutms); + } + else { + baller->error = 0; + baller->connected = FALSE; + baller->has_started = TRUE; + baller->is_done = TRUE; + baller->result = CURLE_COULDNT_CONNECT; + } + return baller->result; +} + +static CURLcode baller_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct eyeballer *baller, + struct curltime *now, + bool *connected) +{ + (void)cf; + *connected = baller->connected; + if(!baller->result && !*connected) { + /* evaluate again */ + baller->result = Curl_conn_cf_connect(baller->cf, data, 0, connected); + + if(!baller->result) { + if(*connected) { + baller->connected = TRUE; + baller->is_done = TRUE; + } + else if(Curl_timediff(*now, baller->started) >= baller->timeoutms) { + infof(data, "%s connect timeout after %" CURL_FORMAT_TIMEDIFF_T + "ms, move on!", baller->name, baller->timeoutms); +#if defined(ETIMEDOUT) + baller->error = ETIMEDOUT; +#endif + baller->result = CURLE_OPERATION_TIMEDOUT; + } + } + else if(baller->result == CURLE_WEIRD_SERVER_REPLY) + baller->inconclusive = TRUE; + } + return baller->result; +} + +/* + * is_connected() checks if the socket has connected. + */ +static CURLcode is_connected(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *connected) +{ + struct cf_he_ctx *ctx = cf->ctx; + struct connectdata *conn = cf->conn; + CURLcode result; + struct curltime now; + size_t i; + int ongoing, not_started; + const char *hostname; + + /* Check if any of the conn->tempsock we use for establishing connections + * succeeded and, if so, close any ongoing other ones. + * Transfer the successful conn->tempsock to conn->sock[sockindex] + * and set conn->tempsock to CURL_SOCKET_BAD. + * If transport is QUIC, we need to shutdown the ongoing 'other' + * cot ballers in a QUIC appropriate way. */ +evaluate: + *connected = FALSE; /* a very negative world view is best */ + now = Curl_now(); + ongoing = not_started = 0; + for(i = 0; i < ARRAYSIZE(ctx->baller); i++) { + struct eyeballer *baller = ctx->baller[i]; + + if(!baller || baller->is_done) + continue; + + if(!baller->has_started) { + ++not_started; + continue; + } + baller->result = baller_connect(cf, data, baller, &now, connected); + CURL_TRC_CF(data, cf, "%s connect -> %d, connected=%d", + baller->name, baller->result, *connected); + + if(!baller->result) { + if(*connected) { + /* connected, declare the winner */ + ctx->winner = baller; + ctx->baller[i] = NULL; + break; + } + else { /* still waiting */ + ++ongoing; + } + } + else if(!baller->is_done) { + /* The baller failed to connect, start its next attempt */ + if(baller->error) { + data->state.os_errno = baller->error; + SET_SOCKERRNO(baller->error); + } + baller_start_next(cf, data, baller, Curl_timeleft(data, &now, TRUE)); + if(baller->is_done) { + CURL_TRC_CF(data, cf, "%s done", baller->name); + } + else { + /* next attempt was started */ + CURL_TRC_CF(data, cf, "%s trying next", baller->name); + ++ongoing; + Curl_expire(data, 0, EXPIRE_RUN_NOW); + } + } + } + + if(ctx->winner) { + *connected = TRUE; + return CURLE_OK; + } + + /* Nothing connected, check the time before we might + * start new ballers or return ok. */ + if((ongoing || not_started) && Curl_timeleft(data, &now, TRUE) < 0) { + failf(data, "Connection timeout after %" CURL_FORMAT_CURL_OFF_T " ms", + Curl_timediff(now, data->progress.t_startsingle)); + return CURLE_OPERATION_TIMEDOUT; + } + + /* Check if we have any waiting ballers to start now. */ + if(not_started > 0) { + int added = 0; + + for(i = 0; i < ARRAYSIZE(ctx->baller); i++) { + struct eyeballer *baller = ctx->baller[i]; + + if(!baller || baller->has_started) + continue; + /* We start its primary baller has failed to connect or if + * its start delay_ms have expired */ + if((baller->primary && baller->primary->is_done) || + Curl_timediff(now, ctx->started) >= baller->delay_ms) { + baller_start(cf, data, baller, Curl_timeleft(data, &now, TRUE)); + if(baller->is_done) { + CURL_TRC_CF(data, cf, "%s done", baller->name); + } + else { + CURL_TRC_CF(data, cf, "%s starting (timeout=%" + CURL_FORMAT_TIMEDIFF_T "ms)", + baller->name, baller->timeoutms); + ++ongoing; + ++added; + } + } + } + if(added > 0) + goto evaluate; + } + + if(ongoing > 0) { + /* We are still trying, return for more waiting */ + *connected = FALSE; + return CURLE_OK; + } + + /* all ballers have failed to connect. */ + CURL_TRC_CF(data, cf, "all eyeballers failed"); + result = CURLE_COULDNT_CONNECT; + for(i = 0; i < ARRAYSIZE(ctx->baller); i++) { + struct eyeballer *baller = ctx->baller[i]; + if(!baller) + continue; + CURL_TRC_CF(data, cf, "%s assess started=%d, result=%d", + baller->name, baller->has_started, baller->result); + if(baller->has_started && baller->result) { + result = baller->result; + break; + } + } + +#ifndef CURL_DISABLE_PROXY + if(conn->bits.socksproxy) + hostname = conn->socks_proxy.host.name; + else if(conn->bits.httpproxy) + hostname = conn->http_proxy.host.name; + else +#endif + if(conn->bits.conn_to_host) + hostname = conn->conn_to_host.name; + else + hostname = conn->host.name; + + failf(data, "Failed to connect to %s port %u after " + "%" CURL_FORMAT_TIMEDIFF_T " ms: %s", + hostname, conn->primary.remote_port, + Curl_timediff(now, data->progress.t_startsingle), + curl_easy_strerror(result)); + +#ifdef WSAETIMEDOUT + if(WSAETIMEDOUT == data->state.os_errno) + result = CURLE_OPERATION_TIMEDOUT; +#elif defined(ETIMEDOUT) + if(ETIMEDOUT == data->state.os_errno) + result = CURLE_OPERATION_TIMEDOUT; +#endif + + return result; +} + +/* + * Connect to the given host with timeout, proxy or remote doesn't matter. + * There might be more than one IP address to try out. + */ +static CURLcode start_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + const struct Curl_dns_entry *remotehost) +{ + struct cf_he_ctx *ctx = cf->ctx; + struct connectdata *conn = cf->conn; + CURLcode result = CURLE_COULDNT_CONNECT; + int ai_family0, ai_family1; + timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE); + const struct Curl_addrinfo *addr0, *addr1; + + if(timeout_ms < 0) { + /* a precaution, no need to continue if time already is up */ + failf(data, "Connection time-out"); + return CURLE_OPERATION_TIMEDOUT; + } + + ctx->started = Curl_now(); + + /* remotehost->addr is the list of addresses from the resolver, each + * with an address family. The list has at least one entry, possibly + * many more. + * We try at most 2 at a time, until we either get a connection or + * run out of addresses to try. Since likelihood of success is tied + * to the address family (e.g. IPV6 might not work at all ), we want + * the 2 connect attempt ballers to try different families, if possible. + * + */ + if(conn->ip_version == CURL_IPRESOLVE_WHATEVER) { + /* any IP version is allowed */ + ai_family0 = remotehost->addr? + remotehost->addr->ai_family : 0; +#ifdef USE_IPV6 + ai_family1 = ai_family0 == AF_INET6 ? + AF_INET : AF_INET6; +#else + ai_family1 = AF_UNSPEC; +#endif + } + else { + /* only one IP version is allowed */ + ai_family0 = (conn->ip_version == CURL_IPRESOLVE_V4) ? + AF_INET : +#ifdef USE_IPV6 + AF_INET6; +#else + AF_UNSPEC; +#endif + ai_family1 = AF_UNSPEC; + } + + /* Get the first address in the list that matches the family, + * this might give NULL, if we do not have any matches. */ + addr0 = addr_first_match(remotehost->addr, ai_family0); + addr1 = addr_first_match(remotehost->addr, ai_family1); + if(!addr0 && addr1) { + /* switch around, so a single baller always uses addr0 */ + addr0 = addr1; + ai_family0 = ai_family1; + addr1 = NULL; + } + + /* We found no address that matches our criteria, we cannot connect */ + if(!addr0) { + return CURLE_COULDNT_CONNECT; + } + + memset(ctx->baller, 0, sizeof(ctx->baller)); + result = eyeballer_new(&ctx->baller[0], ctx->cf_create, addr0, ai_family0, + NULL, 0, /* no primary/delay, start now */ + timeout_ms, EXPIRE_DNS_PER_NAME); + if(result) + return result; + CURL_TRC_CF(data, cf, "created %s (timeout %" + CURL_FORMAT_TIMEDIFF_T "ms)", + ctx->baller[0]->name, ctx->baller[0]->timeoutms); + if(addr1) { + /* second one gets a delayed start */ + result = eyeballer_new(&ctx->baller[1], ctx->cf_create, addr1, ai_family1, + ctx->baller[0], /* wait on that to fail */ + /* or start this delayed */ + data->set.happy_eyeballs_timeout, + timeout_ms, EXPIRE_DNS_PER_NAME2); + if(result) + return result; + CURL_TRC_CF(data, cf, "created %s (timeout %" + CURL_FORMAT_TIMEDIFF_T "ms)", + ctx->baller[1]->name, ctx->baller[1]->timeoutms); + Curl_expire(data, data->set.happy_eyeballs_timeout, + EXPIRE_HAPPY_EYEBALLS); + } + + return CURLE_OK; +} + +static void cf_he_ctx_clear(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_he_ctx *ctx = cf->ctx; + size_t i; + + DEBUGASSERT(ctx); + DEBUGASSERT(data); + for(i = 0; i < ARRAYSIZE(ctx->baller); i++) { + baller_free(ctx->baller[i], data); + ctx->baller[i] = NULL; + } + baller_free(ctx->winner, data); + ctx->winner = NULL; +} + +static void cf_he_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_he_ctx *ctx = cf->ctx; + size_t i; + + if(!cf->connected) { + for(i = 0; i < ARRAYSIZE(ctx->baller); i++) { + struct eyeballer *baller = ctx->baller[i]; + if(!baller || !baller->cf) + continue; + Curl_conn_cf_adjust_pollset(baller->cf, data, ps); + } + CURL_TRC_CF(data, cf, "adjust_pollset -> %d socks", ps->num); + } +} + +static CURLcode cf_he_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + struct cf_he_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + (void)blocking; /* TODO: do we want to support this? */ + DEBUGASSERT(ctx); + *done = FALSE; + + switch(ctx->state) { + case SCFST_INIT: + DEBUGASSERT(CURL_SOCKET_BAD == Curl_conn_cf_get_socket(cf, data)); + DEBUGASSERT(!cf->connected); + result = start_connect(cf, data, ctx->remotehost); + if(result) + return result; + ctx->state = SCFST_WAITING; + FALLTHROUGH(); + case SCFST_WAITING: + result = is_connected(cf, data, done); + if(!result && *done) { + DEBUGASSERT(ctx->winner); + DEBUGASSERT(ctx->winner->cf); + DEBUGASSERT(ctx->winner->cf->connected); + /* we have a winner. Install and activate it. + * close/free all others. */ + ctx->state = SCFST_DONE; + cf->connected = TRUE; + cf->next = ctx->winner->cf; + ctx->winner->cf = NULL; + cf_he_ctx_clear(cf, data); + Curl_conn_cf_cntrl(cf->next, data, TRUE, + CF_CTRL_CONN_INFO_UPDATE, 0, NULL); + + if(cf->conn->handler->protocol & PROTO_FAMILY_SSH) + Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */ + Curl_verboseconnect(data, cf->conn, cf->sockindex); + data->info.numconnects++; /* to track the # of connections made */ + } + break; + case SCFST_DONE: + *done = TRUE; + break; + } + return result; +} + +static void cf_he_close(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_he_ctx *ctx = cf->ctx; + + CURL_TRC_CF(data, cf, "close"); + cf_he_ctx_clear(cf, data); + cf->connected = FALSE; + ctx->state = SCFST_INIT; + + if(cf->next) { + cf->next->cft->do_close(cf->next, data); + Curl_conn_cf_discard_chain(&cf->next, data); + } +} + +static bool cf_he_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct cf_he_ctx *ctx = cf->ctx; + size_t i; + + if(cf->connected) + return cf->next->cft->has_data_pending(cf->next, data); + + for(i = 0; i < ARRAYSIZE(ctx->baller); i++) { + struct eyeballer *baller = ctx->baller[i]; + if(!baller || !baller->cf) + continue; + if(baller->cf->cft->has_data_pending(baller->cf, data)) + return TRUE; + } + return FALSE; +} + +static struct curltime get_max_baller_time(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query) +{ + struct cf_he_ctx *ctx = cf->ctx; + struct curltime t, tmax; + size_t i; + + memset(&tmax, 0, sizeof(tmax)); + for(i = 0; i < ARRAYSIZE(ctx->baller); i++) { + struct eyeballer *baller = ctx->baller[i]; + + memset(&t, 0, sizeof(t)); + if(baller && baller->cf && + !baller->cf->cft->query(baller->cf, data, query, NULL, &t)) { + if((t.tv_sec || t.tv_usec) && Curl_timediff_us(t, tmax) > 0) + tmax = t; + } + } + return tmax; +} + +static CURLcode cf_he_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_he_ctx *ctx = cf->ctx; + + if(!cf->connected) { + switch(query) { + case CF_QUERY_CONNECT_REPLY_MS: { + int reply_ms = -1; + size_t i; + + for(i = 0; i < ARRAYSIZE(ctx->baller); i++) { + struct eyeballer *baller = ctx->baller[i]; + int breply_ms; + + if(baller && baller->cf && + !baller->cf->cft->query(baller->cf, data, query, + &breply_ms, NULL)) { + if(breply_ms >= 0 && (reply_ms < 0 || breply_ms < reply_ms)) + reply_ms = breply_ms; + } + } + *pres1 = reply_ms; + CURL_TRC_CF(data, cf, "query connect reply: %dms", *pres1); + return CURLE_OK; + } + case CF_QUERY_TIMER_CONNECT: { + struct curltime *when = pres2; + *when = get_max_baller_time(cf, data, CF_QUERY_TIMER_CONNECT); + return CURLE_OK; + } + case CF_QUERY_TIMER_APPCONNECT: { + struct curltime *when = pres2; + *when = get_max_baller_time(cf, data, CF_QUERY_TIMER_APPCONNECT); + return CURLE_OK; + } + default: + break; + } + } + + return cf->next? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +static void cf_he_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_he_ctx *ctx = cf->ctx; + + CURL_TRC_CF(data, cf, "destroy"); + if(ctx) { + cf_he_ctx_clear(cf, data); + } + /* release any resources held in state */ + Curl_safefree(ctx); +} + +struct Curl_cftype Curl_cft_happy_eyeballs = { + "HAPPY-EYEBALLS", + 0, + CURL_LOG_LVL_NONE, + cf_he_destroy, + cf_he_connect, + cf_he_close, + Curl_cf_def_get_host, + cf_he_adjust_pollset, + cf_he_data_pending, + Curl_cf_def_send, + Curl_cf_def_recv, + Curl_cf_def_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_he_query, +}; + +/** + * Create a happy eyeball connection filter that uses the, once resolved, + * address information to connect on ip families based on connection + * configuration. + * @param pcf output, the created cfilter + * @param data easy handle used in creation + * @param conn connection the filter is created for + * @param cf_create method to create the sub-filters performing the + * actual connects. + */ +static CURLcode +cf_happy_eyeballs_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + cf_ip_connect_create *cf_create, + const struct Curl_dns_entry *remotehost, + int transport) +{ + struct cf_he_ctx *ctx = NULL; + CURLcode result; + + (void)data; + (void)conn; + *pcf = NULL; + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + ctx->transport = transport; + ctx->cf_create = cf_create; + ctx->remotehost = remotehost; + + result = Curl_cf_create(pcf, &Curl_cft_happy_eyeballs, ctx); + +out: + if(result) { + Curl_safefree(*pcf); + Curl_safefree(ctx); + } + return result; +} + +struct transport_provider { + int transport; + cf_ip_connect_create *cf_create; +}; + +static +#ifndef DEBUGBUILD +const +#endif +struct transport_provider transport_providers[] = { + { TRNSPRT_TCP, Curl_cf_tcp_create }, +#ifdef USE_HTTP3 + { TRNSPRT_QUIC, Curl_cf_quic_create }, +#endif +#ifndef CURL_DISABLE_TFTP + { TRNSPRT_UDP, Curl_cf_udp_create }, +#endif +#ifdef USE_UNIX_SOCKETS + { TRNSPRT_UNIX, Curl_cf_unix_create }, +#endif +}; + +static cf_ip_connect_create *get_cf_create(int transport) +{ + size_t i; + for(i = 0; i < ARRAYSIZE(transport_providers); ++i) { + if(transport == transport_providers[i].transport) + return transport_providers[i].cf_create; + } + return NULL; +} + +static CURLcode cf_he_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + const struct Curl_dns_entry *remotehost, + int transport) +{ + cf_ip_connect_create *cf_create; + struct Curl_cfilter *cf; + CURLcode result; + + /* Need to be first */ + DEBUGASSERT(cf_at); + cf_create = get_cf_create(transport); + if(!cf_create) { + CURL_TRC_CF(data, cf_at, "unsupported transport type %d", transport); + return CURLE_UNSUPPORTED_PROTOCOL; + } + result = cf_happy_eyeballs_create(&cf, data, cf_at->conn, + cf_create, remotehost, + transport); + if(result) + return result; + + Curl_conn_cf_insert_after(cf_at, cf); + return CURLE_OK; +} + +typedef enum { + CF_SETUP_INIT, + CF_SETUP_CNNCT_EYEBALLS, + CF_SETUP_CNNCT_SOCKS, + CF_SETUP_CNNCT_HTTP_PROXY, + CF_SETUP_CNNCT_HAPROXY, + CF_SETUP_CNNCT_SSL, + CF_SETUP_DONE +} cf_setup_state; + +struct cf_setup_ctx { + cf_setup_state state; + const struct Curl_dns_entry *remotehost; + int ssl_mode; + int transport; +}; + +static CURLcode cf_setup_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + struct cf_setup_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + /* connect current sub-chain */ +connect_sub_chain: + if(cf->next && !cf->next->connected) { + result = Curl_conn_cf_connect(cf->next, data, blocking, done); + if(result || !*done) + return result; + } + + if(ctx->state < CF_SETUP_CNNCT_EYEBALLS) { + result = cf_he_insert_after(cf, data, ctx->remotehost, ctx->transport); + if(result) + return result; + ctx->state = CF_SETUP_CNNCT_EYEBALLS; + if(!cf->next || !cf->next->connected) + goto connect_sub_chain; + } + + /* sub-chain connected, do we need to add more? */ +#ifndef CURL_DISABLE_PROXY + if(ctx->state < CF_SETUP_CNNCT_SOCKS && cf->conn->bits.socksproxy) { + result = Curl_cf_socks_proxy_insert_after(cf, data); + if(result) + return result; + ctx->state = CF_SETUP_CNNCT_SOCKS; + if(!cf->next || !cf->next->connected) + goto connect_sub_chain; + } + + if(ctx->state < CF_SETUP_CNNCT_HTTP_PROXY && cf->conn->bits.httpproxy) { +#ifdef USE_SSL + if(IS_HTTPS_PROXY(cf->conn->http_proxy.proxytype) + && !Curl_conn_is_ssl(cf->conn, cf->sockindex)) { + result = Curl_cf_ssl_proxy_insert_after(cf, data); + if(result) + return result; + } +#endif /* USE_SSL */ + +#if !defined(CURL_DISABLE_HTTP) + if(cf->conn->bits.tunnel_proxy) { + result = Curl_cf_http_proxy_insert_after(cf, data); + if(result) + return result; + } +#endif /* !CURL_DISABLE_HTTP */ + ctx->state = CF_SETUP_CNNCT_HTTP_PROXY; + if(!cf->next || !cf->next->connected) + goto connect_sub_chain; + } +#endif /* !CURL_DISABLE_PROXY */ + + if(ctx->state < CF_SETUP_CNNCT_HAPROXY) { +#if !defined(CURL_DISABLE_PROXY) + if(data->set.haproxyprotocol) { + if(Curl_conn_is_ssl(cf->conn, cf->sockindex)) { + failf(data, "haproxy protocol not support with SSL " + "encryption in place (QUIC?)"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + result = Curl_cf_haproxy_insert_after(cf, data); + if(result) + return result; + } +#endif /* !CURL_DISABLE_PROXY */ + ctx->state = CF_SETUP_CNNCT_HAPROXY; + if(!cf->next || !cf->next->connected) + goto connect_sub_chain; + } + + if(ctx->state < CF_SETUP_CNNCT_SSL) { +#ifdef USE_SSL + if((ctx->ssl_mode == CURL_CF_SSL_ENABLE + || (ctx->ssl_mode != CURL_CF_SSL_DISABLE + && cf->conn->handler->flags & PROTOPT_SSL)) /* we want SSL */ + && !Curl_conn_is_ssl(cf->conn, cf->sockindex)) { /* it is missing */ + result = Curl_cf_ssl_insert_after(cf, data); + if(result) + return result; + } +#endif /* USE_SSL */ + ctx->state = CF_SETUP_CNNCT_SSL; + if(!cf->next || !cf->next->connected) + goto connect_sub_chain; + } + + ctx->state = CF_SETUP_DONE; + cf->connected = TRUE; + *done = TRUE; + return CURLE_OK; +} + +static void cf_setup_close(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_setup_ctx *ctx = cf->ctx; + + CURL_TRC_CF(data, cf, "close"); + cf->connected = FALSE; + ctx->state = CF_SETUP_INIT; + + if(cf->next) { + cf->next->cft->do_close(cf->next, data); + Curl_conn_cf_discard_chain(&cf->next, data); + } +} + +static void cf_setup_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_setup_ctx *ctx = cf->ctx; + + (void)data; + CURL_TRC_CF(data, cf, "destroy"); + Curl_safefree(ctx); +} + + +struct Curl_cftype Curl_cft_setup = { + "SETUP", + 0, + CURL_LOG_LVL_NONE, + cf_setup_destroy, + cf_setup_connect, + cf_setup_close, + Curl_cf_def_get_host, + Curl_cf_def_adjust_pollset, + Curl_cf_def_data_pending, + Curl_cf_def_send, + Curl_cf_def_recv, + Curl_cf_def_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + Curl_cf_def_query, +}; + +static CURLcode cf_setup_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + const struct Curl_dns_entry *remotehost, + int transport, + int ssl_mode) +{ + struct Curl_cfilter *cf = NULL; + struct cf_setup_ctx *ctx; + CURLcode result = CURLE_OK; + + (void)data; + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + ctx->state = CF_SETUP_INIT; + ctx->remotehost = remotehost; + ctx->ssl_mode = ssl_mode; + ctx->transport = transport; + + result = Curl_cf_create(&cf, &Curl_cft_setup, ctx); + if(result) + goto out; + ctx = NULL; + +out: + *pcf = result? NULL : cf; + free(ctx); + return result; +} + +static CURLcode cf_setup_add(struct Curl_easy *data, + struct connectdata *conn, + int sockindex, + const struct Curl_dns_entry *remotehost, + int transport, + int ssl_mode) +{ + struct Curl_cfilter *cf; + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + result = cf_setup_create(&cf, data, remotehost, transport, ssl_mode); + if(result) + goto out; + Curl_conn_cf_add(data, conn, sockindex, cf); +out: + return result; +} + +#ifdef DEBUGBUILD +/* used by unit2600.c */ +void Curl_debug_set_transport_provider(int transport, + cf_ip_connect_create *cf_create) +{ + size_t i; + for(i = 0; i < ARRAYSIZE(transport_providers); ++i) { + if(transport == transport_providers[i].transport) { + transport_providers[i].cf_create = cf_create; + return; + } + } +} +#endif /* DEBUGBUILD */ + +CURLcode Curl_cf_setup_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + const struct Curl_dns_entry *remotehost, + int transport, + int ssl_mode) +{ + struct Curl_cfilter *cf; + CURLcode result; + + DEBUGASSERT(data); + result = cf_setup_create(&cf, data, remotehost, transport, ssl_mode); + if(result) + goto out; + Curl_conn_cf_insert_after(cf_at, cf); +out: + return result; +} + +CURLcode Curl_conn_setup(struct Curl_easy *data, + struct connectdata *conn, + int sockindex, + const struct Curl_dns_entry *remotehost, + int ssl_mode) +{ + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + DEBUGASSERT(conn->handler); + +#if !defined(CURL_DISABLE_HTTP) && !defined(USE_HYPER) + if(!conn->cfilter[sockindex] && + conn->handler->protocol == CURLPROTO_HTTPS) { + DEBUGASSERT(ssl_mode != CURL_CF_SSL_DISABLE); + result = Curl_cf_https_setup(data, conn, sockindex, remotehost); + if(result) + goto out; + } +#endif /* !defined(CURL_DISABLE_HTTP) && !defined(USE_HYPER) */ + + /* Still no cfilter set, apply default. */ + if(!conn->cfilter[sockindex]) { + result = cf_setup_add(data, conn, sockindex, remotehost, + conn->transport, ssl_mode); + if(result) + goto out; + } + + DEBUGASSERT(conn->cfilter[sockindex]); +out: + return result; +} diff --git a/third_party/curl/lib/connect.h b/third_party/curl/lib/connect.h new file mode 100644 index 0000000..00efe6f --- /dev/null +++ b/third_party/curl/lib/connect.h @@ -0,0 +1,133 @@ +#ifndef HEADER_CURL_CONNECT_H +#define HEADER_CURL_CONNECT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "nonblock.h" /* for curlx_nonblock(), formerly Curl_nonblock() */ +#include "sockaddr.h" +#include "timeval.h" + +struct Curl_dns_entry; +struct ip_quadruple; + +/* generic function that returns how much time there's left to run, according + to the timeouts set */ +timediff_t Curl_timeleft(struct Curl_easy *data, + struct curltime *nowp, + bool duringconnect); + +#define DEFAULT_CONNECT_TIMEOUT 300000 /* milliseconds == five minutes */ + +/* + * Used to extract socket and connectdata struct for the most recent + * transfer on the given Curl_easy. + * + * The returned socket will be CURL_SOCKET_BAD in case of failure! + */ +curl_socket_t Curl_getconnectinfo(struct Curl_easy *data, + struct connectdata **connp); + +bool Curl_addr2string(struct sockaddr *sa, curl_socklen_t salen, + char *addr, int *port); + +void Curl_persistconninfo(struct Curl_easy *data, struct connectdata *conn, + struct ip_quadruple *ip); + +/* + * Curl_conncontrol() marks the end of a connection/stream. The 'closeit' + * argument specifies if it is the end of a connection or a stream. + * + * For stream-based protocols (such as HTTP/2), a stream close will not cause + * a connection close. Other protocols will close the connection for both + * cases. + * + * It sets the bit.close bit to TRUE (with an explanation for debug builds), + * when the connection will close. + */ + +#define CONNCTRL_KEEP 0 /* undo a marked closure */ +#define CONNCTRL_CONNECTION 1 +#define CONNCTRL_STREAM 2 + +void Curl_conncontrol(struct connectdata *conn, + int closeit +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + , const char *reason +#endif + ); + +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) +#define streamclose(x,y) Curl_conncontrol(x, CONNCTRL_STREAM, y) +#define connclose(x,y) Curl_conncontrol(x, CONNCTRL_CONNECTION, y) +#define connkeep(x,y) Curl_conncontrol(x, CONNCTRL_KEEP, y) +#else /* if !DEBUGBUILD || CURL_DISABLE_VERBOSE_STRINGS */ +#define streamclose(x,y) Curl_conncontrol(x, CONNCTRL_STREAM) +#define connclose(x,y) Curl_conncontrol(x, CONNCTRL_CONNECTION) +#define connkeep(x,y) Curl_conncontrol(x, CONNCTRL_KEEP) +#endif + +/** + * Create a cfilter for making an "ip" connection to the + * given address, using parameters from `conn`. The "ip" connection + * can be a TCP socket, a UDP socket or even a QUIC connection. + * + * It MUST use only the supplied `ai` for its connection attempt. + * + * Such a filter may be used in "happy eyeball" scenarios, and its + * `connect` implementation needs to support non-blocking. Once connected, + * it MAY be installed in the connection filter chain to serve transfers. + */ +typedef CURLcode cf_ip_connect_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai, + int transport); + +CURLcode Curl_cf_setup_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + const struct Curl_dns_entry *remotehost, + int transport, + int ssl_mode); + +/** + * Setup the cfilters at `sockindex` in connection `conn`. + * If no filter chain is installed yet, inspects the configuration + * in `data` and `conn? to install a suitable filter chain. + */ +CURLcode Curl_conn_setup(struct Curl_easy *data, + struct connectdata *conn, + int sockindex, + const struct Curl_dns_entry *remotehost, + int ssl_mode); + +extern struct Curl_cftype Curl_cft_happy_eyeballs; +extern struct Curl_cftype Curl_cft_setup; + +#ifdef DEBUGBUILD +void Curl_debug_set_transport_provider(int transport, + cf_ip_connect_create *cf_create); +#endif + +#endif /* HEADER_CURL_CONNECT_H */ diff --git a/third_party/curl/lib/content_encoding.c b/third_party/curl/lib/content_encoding.c new file mode 100644 index 0000000..d34d3a1 --- /dev/null +++ b/third_party/curl/lib/content_encoding.c @@ -0,0 +1,1079 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "urldata.h" +#include +#include + +#ifdef HAVE_LIBZ +#include +#endif + +#ifdef HAVE_BROTLI +#if defined(__GNUC__) +/* Ignore -Wvla warnings in brotli headers */ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wvla" +#endif +#include +#if defined(__GNUC__) +#pragma GCC diagnostic pop +#endif +#endif + +#ifdef HAVE_ZSTD +#include +#endif + +#include "sendf.h" +#include "http.h" +#include "content_encoding.h" +#include "strdup.h" +#include "strcase.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#define CONTENT_ENCODING_DEFAULT "identity" + +#ifndef CURL_DISABLE_HTTP + +/* allow no more than 5 "chained" compression steps */ +#define MAX_ENCODE_STACK 5 + +#define DSIZ CURL_MAX_WRITE_SIZE /* buffer size for decompressed data */ + + +#ifdef HAVE_LIBZ + +/* Comment this out if zlib is always going to be at least ver. 1.2.0.4 + (doing so will reduce code size slightly). */ +#define OLD_ZLIB_SUPPORT 1 + +#define GZIP_MAGIC_0 0x1f +#define GZIP_MAGIC_1 0x8b + +/* gzip flag byte */ +#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ +#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */ +#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ +#define ORIG_NAME 0x08 /* bit 3 set: original file name present */ +#define COMMENT 0x10 /* bit 4 set: file comment present */ +#define RESERVED 0xE0 /* bits 5..7: reserved */ + +typedef enum { + ZLIB_UNINIT, /* uninitialized */ + ZLIB_INIT, /* initialized */ + ZLIB_INFLATING, /* inflating started. */ + ZLIB_EXTERNAL_TRAILER, /* reading external trailer */ + ZLIB_GZIP_HEADER, /* reading gzip header */ + ZLIB_GZIP_INFLATING, /* inflating gzip stream */ + ZLIB_INIT_GZIP /* initialized in transparent gzip mode */ +} zlibInitState; + +/* Deflate and gzip writer. */ +struct zlib_writer { + struct Curl_cwriter super; + zlibInitState zlib_init; /* zlib init state */ + uInt trailerlen; /* Remaining trailer byte count. */ + z_stream z; /* State structure for zlib. */ +}; + + +static voidpf +zalloc_cb(voidpf opaque, unsigned int items, unsigned int size) +{ + (void) opaque; + /* not a typo, keep it calloc() */ + return (voidpf) calloc(items, size); +} + +static void +zfree_cb(voidpf opaque, voidpf ptr) +{ + (void) opaque; + free(ptr); +} + +static CURLcode +process_zlib_error(struct Curl_easy *data, z_stream *z) +{ + if(z->msg) + failf(data, "Error while processing content unencoding: %s", + z->msg); + else + failf(data, "Error while processing content unencoding: " + "Unknown failure within decompression software."); + + return CURLE_BAD_CONTENT_ENCODING; +} + +static CURLcode +exit_zlib(struct Curl_easy *data, + z_stream *z, zlibInitState *zlib_init, CURLcode result) +{ + if(*zlib_init == ZLIB_GZIP_HEADER) + Curl_safefree(z->next_in); + + if(*zlib_init != ZLIB_UNINIT) { + if(inflateEnd(z) != Z_OK && result == CURLE_OK) + result = process_zlib_error(data, z); + *zlib_init = ZLIB_UNINIT; + } + + return result; +} + +static CURLcode process_trailer(struct Curl_easy *data, + struct zlib_writer *zp) +{ + z_stream *z = &zp->z; + CURLcode result = CURLE_OK; + uInt len = z->avail_in < zp->trailerlen? z->avail_in: zp->trailerlen; + + /* Consume expected trailer bytes. Terminate stream if exhausted. + Issue an error if unexpected bytes follow. */ + + zp->trailerlen -= len; + z->avail_in -= len; + z->next_in += len; + if(z->avail_in) + result = CURLE_WRITE_ERROR; + if(result || !zp->trailerlen) + result = exit_zlib(data, z, &zp->zlib_init, result); + else { + /* Only occurs for gzip with zlib < 1.2.0.4 or raw deflate. */ + zp->zlib_init = ZLIB_EXTERNAL_TRAILER; + } + return result; +} + +static CURLcode inflate_stream(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + zlibInitState started) +{ + struct zlib_writer *zp = (struct zlib_writer *) writer; + z_stream *z = &zp->z; /* zlib state structure */ + uInt nread = z->avail_in; + Bytef *orig_in = z->next_in; + bool done = FALSE; + CURLcode result = CURLE_OK; /* Curl_client_write status */ + char *decomp; /* Put the decompressed data here. */ + + /* Check state. */ + if(zp->zlib_init != ZLIB_INIT && + zp->zlib_init != ZLIB_INFLATING && + zp->zlib_init != ZLIB_INIT_GZIP && + zp->zlib_init != ZLIB_GZIP_INFLATING) + return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR); + + /* Dynamically allocate a buffer for decompression because it's uncommonly + large to hold on the stack */ + decomp = malloc(DSIZ); + if(!decomp) + return exit_zlib(data, z, &zp->zlib_init, CURLE_OUT_OF_MEMORY); + + /* because the buffer size is fixed, iteratively decompress and transfer to + the client via next_write function. */ + while(!done) { + int status; /* zlib status */ + done = TRUE; + + /* (re)set buffer for decompressed output for every iteration */ + z->next_out = (Bytef *) decomp; + z->avail_out = DSIZ; + +#ifdef Z_BLOCK + /* Z_BLOCK is only available in zlib ver. >= 1.2.0.5 */ + status = inflate(z, Z_BLOCK); +#else + /* fallback for zlib ver. < 1.2.0.5 */ + status = inflate(z, Z_SYNC_FLUSH); +#endif + + /* Flush output data if some. */ + if(z->avail_out != DSIZ) { + if(status == Z_OK || status == Z_STREAM_END) { + zp->zlib_init = started; /* Data started. */ + result = Curl_cwriter_write(data, writer->next, type, decomp, + DSIZ - z->avail_out); + if(result) { + exit_zlib(data, z, &zp->zlib_init, result); + break; + } + } + } + + /* Dispatch by inflate() status. */ + switch(status) { + case Z_OK: + /* Always loop: there may be unflushed latched data in zlib state. */ + done = FALSE; + break; + case Z_BUF_ERROR: + /* No more data to flush: just exit loop. */ + break; + case Z_STREAM_END: + result = process_trailer(data, zp); + break; + case Z_DATA_ERROR: + /* some servers seem to not generate zlib headers, so this is an attempt + to fix and continue anyway */ + if(zp->zlib_init == ZLIB_INIT) { + /* Do not use inflateReset2(): only available since zlib 1.2.3.4. */ + (void) inflateEnd(z); /* don't care about the return code */ + if(inflateInit2(z, -MAX_WBITS) == Z_OK) { + z->next_in = orig_in; + z->avail_in = nread; + zp->zlib_init = ZLIB_INFLATING; + zp->trailerlen = 4; /* Tolerate up to 4 unknown trailer bytes. */ + done = FALSE; + break; + } + zp->zlib_init = ZLIB_UNINIT; /* inflateEnd() already called. */ + } + result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z)); + break; + default: + result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z)); + break; + } + } + free(decomp); + + /* We're about to leave this call so the `nread' data bytes won't be seen + again. If we are in a state that would wrongly allow restart in raw mode + at the next call, assume output has already started. */ + if(nread && zp->zlib_init == ZLIB_INIT) + zp->zlib_init = started; /* Cannot restart anymore. */ + + return result; +} + + +/* Deflate handler. */ +static CURLcode deflate_do_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct zlib_writer *zp = (struct zlib_writer *) writer; + z_stream *z = &zp->z; /* zlib state structure */ + + /* Initialize zlib */ + z->zalloc = (alloc_func) zalloc_cb; + z->zfree = (free_func) zfree_cb; + + if(inflateInit(z) != Z_OK) + return process_zlib_error(data, z); + zp->zlib_init = ZLIB_INIT; + return CURLE_OK; +} + +static CURLcode deflate_do_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + struct zlib_writer *zp = (struct zlib_writer *) writer; + z_stream *z = &zp->z; /* zlib state structure */ + + if(!(type & CLIENTWRITE_BODY) || !nbytes) + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); + + /* Set the compressed input when this function is called */ + z->next_in = (Bytef *) buf; + z->avail_in = (uInt) nbytes; + + if(zp->zlib_init == ZLIB_EXTERNAL_TRAILER) + return process_trailer(data, zp); + + /* Now uncompress the data */ + return inflate_stream(data, writer, type, ZLIB_INFLATING); +} + +static void deflate_do_close(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct zlib_writer *zp = (struct zlib_writer *) writer; + z_stream *z = &zp->z; /* zlib state structure */ + + exit_zlib(data, z, &zp->zlib_init, CURLE_OK); +} + +static const struct Curl_cwtype deflate_encoding = { + "deflate", + NULL, + deflate_do_init, + deflate_do_write, + deflate_do_close, + sizeof(struct zlib_writer) +}; + + +/* Gzip handler. */ +static CURLcode gzip_do_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct zlib_writer *zp = (struct zlib_writer *) writer; + z_stream *z = &zp->z; /* zlib state structure */ + + /* Initialize zlib */ + z->zalloc = (alloc_func) zalloc_cb; + z->zfree = (free_func) zfree_cb; + + if(strcmp(zlibVersion(), "1.2.0.4") >= 0) { + /* zlib ver. >= 1.2.0.4 supports transparent gzip decompressing */ + if(inflateInit2(z, MAX_WBITS + 32) != Z_OK) { + return process_zlib_error(data, z); + } + zp->zlib_init = ZLIB_INIT_GZIP; /* Transparent gzip decompress state */ + } + else { + /* we must parse the gzip header and trailer ourselves */ + if(inflateInit2(z, -MAX_WBITS) != Z_OK) { + return process_zlib_error(data, z); + } + zp->trailerlen = 8; /* A CRC-32 and a 32-bit input size (RFC 1952, 2.2) */ + zp->zlib_init = ZLIB_INIT; /* Initial call state */ + } + + return CURLE_OK; +} + +#ifdef OLD_ZLIB_SUPPORT +/* Skip over the gzip header */ +typedef enum { + GZIP_OK, + GZIP_BAD, + GZIP_UNDERFLOW +} gzip_status; + +static gzip_status check_gzip_header(unsigned char const *data, ssize_t len, + ssize_t *headerlen) +{ + int method, flags; + const ssize_t totallen = len; + + /* The shortest header is 10 bytes */ + if(len < 10) + return GZIP_UNDERFLOW; + + if((data[0] != GZIP_MAGIC_0) || (data[1] != GZIP_MAGIC_1)) + return GZIP_BAD; + + method = data[2]; + flags = data[3]; + + if(method != Z_DEFLATED || (flags & RESERVED) != 0) { + /* Can't handle this compression method or unknown flag */ + return GZIP_BAD; + } + + /* Skip over time, xflags, OS code and all previous bytes */ + len -= 10; + data += 10; + + if(flags & EXTRA_FIELD) { + ssize_t extra_len; + + if(len < 2) + return GZIP_UNDERFLOW; + + extra_len = (data[1] << 8) | data[0]; + + if(len < (extra_len + 2)) + return GZIP_UNDERFLOW; + + len -= (extra_len + 2); + data += (extra_len + 2); + } + + if(flags & ORIG_NAME) { + /* Skip over NUL-terminated file name */ + while(len && *data) { + --len; + ++data; + } + if(!len || *data) + return GZIP_UNDERFLOW; + + /* Skip over the NUL */ + --len; + ++data; + } + + if(flags & COMMENT) { + /* Skip over NUL-terminated comment */ + while(len && *data) { + --len; + ++data; + } + if(!len || *data) + return GZIP_UNDERFLOW; + + /* Skip over the NUL */ + --len; + } + + if(flags & HEAD_CRC) { + if(len < 2) + return GZIP_UNDERFLOW; + + len -= 2; + } + + *headerlen = totallen - len; + return GZIP_OK; +} +#endif + +static CURLcode gzip_do_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + struct zlib_writer *zp = (struct zlib_writer *) writer; + z_stream *z = &zp->z; /* zlib state structure */ + + if(!(type & CLIENTWRITE_BODY) || !nbytes) + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); + + if(zp->zlib_init == ZLIB_INIT_GZIP) { + /* Let zlib handle the gzip decompression entirely */ + z->next_in = (Bytef *) buf; + z->avail_in = (uInt) nbytes; + /* Now uncompress the data */ + return inflate_stream(data, writer, type, ZLIB_INIT_GZIP); + } + +#ifndef OLD_ZLIB_SUPPORT + /* Support for old zlib versions is compiled away and we are running with + an old version, so return an error. */ + return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR); + +#else + /* This next mess is to get around the potential case where there isn't + * enough data passed in to skip over the gzip header. If that happens, we + * malloc a block and copy what we have then wait for the next call. If + * there still isn't enough (this is definitely a worst-case scenario), we + * make the block bigger, copy the next part in and keep waiting. + * + * This is only required with zlib versions < 1.2.0.4 as newer versions + * can handle the gzip header themselves. + */ + + switch(zp->zlib_init) { + /* Skip over gzip header? */ + case ZLIB_INIT: + { + /* Initial call state */ + ssize_t hlen; + + switch(check_gzip_header((unsigned char *) buf, nbytes, &hlen)) { + case GZIP_OK: + z->next_in = (Bytef *) buf + hlen; + z->avail_in = (uInt) (nbytes - hlen); + zp->zlib_init = ZLIB_GZIP_INFLATING; /* Inflating stream state */ + break; + + case GZIP_UNDERFLOW: + /* We need more data so we can find the end of the gzip header. It's + * possible that the memory block we malloc here will never be freed if + * the transfer abruptly aborts after this point. Since it's unlikely + * that circumstances will be right for this code path to be followed in + * the first place, and it's even more unlikely for a transfer to fail + * immediately afterwards, it should seldom be a problem. + */ + z->avail_in = (uInt) nbytes; + z->next_in = malloc(z->avail_in); + if(!z->next_in) { + return exit_zlib(data, z, &zp->zlib_init, CURLE_OUT_OF_MEMORY); + } + memcpy(z->next_in, buf, z->avail_in); + zp->zlib_init = ZLIB_GZIP_HEADER; /* Need more gzip header data state */ + /* We don't have any data to inflate yet */ + return CURLE_OK; + + case GZIP_BAD: + default: + return exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z)); + } + + } + break; + + case ZLIB_GZIP_HEADER: + { + /* Need more gzip header data state */ + ssize_t hlen; + z->avail_in += (uInt) nbytes; + z->next_in = Curl_saferealloc(z->next_in, z->avail_in); + if(!z->next_in) { + return exit_zlib(data, z, &zp->zlib_init, CURLE_OUT_OF_MEMORY); + } + /* Append the new block of data to the previous one */ + memcpy(z->next_in + z->avail_in - nbytes, buf, nbytes); + + switch(check_gzip_header(z->next_in, z->avail_in, &hlen)) { + case GZIP_OK: + /* This is the zlib stream data */ + free(z->next_in); + /* Don't point into the malloced block since we just freed it */ + z->next_in = (Bytef *) buf + hlen + nbytes - z->avail_in; + z->avail_in = (uInt) (z->avail_in - hlen); + zp->zlib_init = ZLIB_GZIP_INFLATING; /* Inflating stream state */ + break; + + case GZIP_UNDERFLOW: + /* We still don't have any data to inflate! */ + return CURLE_OK; + + case GZIP_BAD: + default: + return exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z)); + } + + } + break; + + case ZLIB_EXTERNAL_TRAILER: + z->next_in = (Bytef *) buf; + z->avail_in = (uInt) nbytes; + return process_trailer(data, zp); + + case ZLIB_GZIP_INFLATING: + default: + /* Inflating stream state */ + z->next_in = (Bytef *) buf; + z->avail_in = (uInt) nbytes; + break; + } + + if(z->avail_in == 0) { + /* We don't have any data to inflate; wait until next time */ + return CURLE_OK; + } + + /* We've parsed the header, now uncompress the data */ + return inflate_stream(data, writer, type, ZLIB_GZIP_INFLATING); +#endif +} + +static void gzip_do_close(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct zlib_writer *zp = (struct zlib_writer *) writer; + z_stream *z = &zp->z; /* zlib state structure */ + + exit_zlib(data, z, &zp->zlib_init, CURLE_OK); +} + +static const struct Curl_cwtype gzip_encoding = { + "gzip", + "x-gzip", + gzip_do_init, + gzip_do_write, + gzip_do_close, + sizeof(struct zlib_writer) +}; + +#endif /* HAVE_LIBZ */ + + +#ifdef HAVE_BROTLI +/* Brotli writer. */ +struct brotli_writer { + struct Curl_cwriter super; + BrotliDecoderState *br; /* State structure for brotli. */ +}; + +static CURLcode brotli_map_error(BrotliDecoderErrorCode be) +{ + switch(be) { + case BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: + case BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: + case BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: + case BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: + case BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: + case BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: + case BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: + case BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: + case BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: + case BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: + case BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: + case BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: + case BROTLI_DECODER_ERROR_FORMAT_PADDING_1: + case BROTLI_DECODER_ERROR_FORMAT_PADDING_2: +#ifdef BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY + case BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY: +#endif +#ifdef BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET + case BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: +#endif + case BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: + return CURLE_BAD_CONTENT_ENCODING; + case BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: + case BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: + case BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: + case BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: + case BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: + case BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: + return CURLE_OUT_OF_MEMORY; + default: + break; + } + return CURLE_WRITE_ERROR; +} + +static CURLcode brotli_do_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct brotli_writer *bp = (struct brotli_writer *) writer; + (void) data; + + bp->br = BrotliDecoderCreateInstance(NULL, NULL, NULL); + return bp->br? CURLE_OK: CURLE_OUT_OF_MEMORY; +} + +static CURLcode brotli_do_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + struct brotli_writer *bp = (struct brotli_writer *) writer; + const uint8_t *src = (const uint8_t *) buf; + char *decomp; + uint8_t *dst; + size_t dstleft; + CURLcode result = CURLE_OK; + BrotliDecoderResult r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT; + + if(!(type & CLIENTWRITE_BODY) || !nbytes) + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); + + if(!bp->br) + return CURLE_WRITE_ERROR; /* Stream already ended. */ + + decomp = malloc(DSIZ); + if(!decomp) + return CURLE_OUT_OF_MEMORY; + + while((nbytes || r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) && + result == CURLE_OK) { + dst = (uint8_t *) decomp; + dstleft = DSIZ; + r = BrotliDecoderDecompressStream(bp->br, + &nbytes, &src, &dstleft, &dst, NULL); + result = Curl_cwriter_write(data, writer->next, type, + decomp, DSIZ - dstleft); + if(result) + break; + switch(r) { + case BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: + case BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: + break; + case BROTLI_DECODER_RESULT_SUCCESS: + BrotliDecoderDestroyInstance(bp->br); + bp->br = NULL; + if(nbytes) + result = CURLE_WRITE_ERROR; + break; + default: + result = brotli_map_error(BrotliDecoderGetErrorCode(bp->br)); + break; + } + } + free(decomp); + return result; +} + +static void brotli_do_close(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct brotli_writer *bp = (struct brotli_writer *) writer; + + (void) data; + + if(bp->br) { + BrotliDecoderDestroyInstance(bp->br); + bp->br = NULL; + } +} + +static const struct Curl_cwtype brotli_encoding = { + "br", + NULL, + brotli_do_init, + brotli_do_write, + brotli_do_close, + sizeof(struct brotli_writer) +}; +#endif + + +#ifdef HAVE_ZSTD +/* Zstd writer. */ +struct zstd_writer { + struct Curl_cwriter super; + ZSTD_DStream *zds; /* State structure for zstd. */ + void *decomp; +}; + +static CURLcode zstd_do_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct zstd_writer *zp = (struct zstd_writer *) writer; + + (void)data; + + zp->zds = ZSTD_createDStream(); + zp->decomp = NULL; + return zp->zds ? CURLE_OK : CURLE_OUT_OF_MEMORY; +} + +static CURLcode zstd_do_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + CURLcode result = CURLE_OK; + struct zstd_writer *zp = (struct zstd_writer *) writer; + ZSTD_inBuffer in; + ZSTD_outBuffer out; + size_t errorCode; + + if(!(type & CLIENTWRITE_BODY) || !nbytes) + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); + + if(!zp->decomp) { + zp->decomp = malloc(DSIZ); + if(!zp->decomp) + return CURLE_OUT_OF_MEMORY; + } + in.pos = 0; + in.src = buf; + in.size = nbytes; + + for(;;) { + out.pos = 0; + out.dst = zp->decomp; + out.size = DSIZ; + + errorCode = ZSTD_decompressStream(zp->zds, &out, &in); + if(ZSTD_isError(errorCode)) { + return CURLE_BAD_CONTENT_ENCODING; + } + if(out.pos > 0) { + result = Curl_cwriter_write(data, writer->next, type, + zp->decomp, out.pos); + if(result) + break; + } + if((in.pos == nbytes) && (out.pos < out.size)) + break; + } + + return result; +} + +static void zstd_do_close(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct zstd_writer *zp = (struct zstd_writer *) writer; + + (void)data; + + if(zp->decomp) { + free(zp->decomp); + zp->decomp = NULL; + } + if(zp->zds) { + ZSTD_freeDStream(zp->zds); + zp->zds = NULL; + } +} + +static const struct Curl_cwtype zstd_encoding = { + "zstd", + NULL, + zstd_do_init, + zstd_do_write, + zstd_do_close, + sizeof(struct zstd_writer) +}; +#endif + + +/* Identity handler. */ +static const struct Curl_cwtype identity_encoding = { + "identity", + "none", + Curl_cwriter_def_init, + Curl_cwriter_def_write, + Curl_cwriter_def_close, + sizeof(struct Curl_cwriter) +}; + + +/* supported general content decoders. */ +static const struct Curl_cwtype * const general_unencoders[] = { + &identity_encoding, +#ifdef HAVE_LIBZ + &deflate_encoding, + &gzip_encoding, +#endif +#ifdef HAVE_BROTLI + &brotli_encoding, +#endif +#ifdef HAVE_ZSTD + &zstd_encoding, +#endif + NULL +}; + +/* supported content decoders only for transfer encodings */ +static const struct Curl_cwtype * const transfer_unencoders[] = { +#ifndef CURL_DISABLE_HTTP + &Curl_httpchunk_unencoder, +#endif + NULL +}; + +/* Provide a list of comma-separated names of supported encodings. +*/ +void Curl_all_content_encodings(char *buf, size_t blen) +{ + size_t len = 0; + const struct Curl_cwtype * const *cep; + const struct Curl_cwtype *ce; + + DEBUGASSERT(buf); + DEBUGASSERT(blen); + buf[0] = 0; + + for(cep = general_unencoders; *cep; cep++) { + ce = *cep; + if(!strcasecompare(ce->name, CONTENT_ENCODING_DEFAULT)) + len += strlen(ce->name) + 2; + } + + if(!len) { + if(blen >= sizeof(CONTENT_ENCODING_DEFAULT)) + strcpy(buf, CONTENT_ENCODING_DEFAULT); + } + else if(blen > len) { + char *p = buf; + for(cep = general_unencoders; *cep; cep++) { + ce = *cep; + if(!strcasecompare(ce->name, CONTENT_ENCODING_DEFAULT)) { + strcpy(p, ce->name); + p += strlen(p); + *p++ = ','; + *p++ = ' '; + } + } + p[-2] = '\0'; + } +} + +/* Deferred error dummy writer. */ +static CURLcode error_do_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + (void)data; + (void)writer; + return CURLE_OK; +} + +static CURLcode error_do_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + char all[256]; + (void)Curl_all_content_encodings(all, sizeof(all)); + + (void) writer; + (void) buf; + (void) nbytes; + + if(!(type & CLIENTWRITE_BODY) || !nbytes) + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); + + failf(data, "Unrecognized content encoding type. " + "libcurl understands %s content encodings.", all); + return CURLE_BAD_CONTENT_ENCODING; +} + +static void error_do_close(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + (void) data; + (void) writer; +} + +static const struct Curl_cwtype error_writer = { + "ce-error", + NULL, + error_do_init, + error_do_write, + error_do_close, + sizeof(struct Curl_cwriter) +}; + +/* Find the content encoding by name. */ +static const struct Curl_cwtype *find_unencode_writer(const char *name, + size_t len, + Curl_cwriter_phase phase) +{ + const struct Curl_cwtype * const *cep; + + if(phase == CURL_CW_TRANSFER_DECODE) { + for(cep = transfer_unencoders; *cep; cep++) { + const struct Curl_cwtype *ce = *cep; + if((strncasecompare(name, ce->name, len) && !ce->name[len]) || + (ce->alias && strncasecompare(name, ce->alias, len) + && !ce->alias[len])) + return ce; + } + } + /* look among the general decoders */ + for(cep = general_unencoders; *cep; cep++) { + const struct Curl_cwtype *ce = *cep; + if((strncasecompare(name, ce->name, len) && !ce->name[len]) || + (ce->alias && strncasecompare(name, ce->alias, len) && !ce->alias[len])) + return ce; + } + return NULL; +} + +/* Set-up the unencoding stack from the Content-Encoding header value. + * See RFC 7231 section 3.1.2.2. */ +CURLcode Curl_build_unencoding_stack(struct Curl_easy *data, + const char *enclist, int is_transfer) +{ + Curl_cwriter_phase phase = is_transfer? + CURL_CW_TRANSFER_DECODE:CURL_CW_CONTENT_DECODE; + CURLcode result; + + do { + const char *name; + size_t namelen; + bool is_chunked = FALSE; + + /* Parse a single encoding name. */ + while(ISBLANK(*enclist) || *enclist == ',') + enclist++; + + name = enclist; + + for(namelen = 0; *enclist && *enclist != ','; enclist++) + if(!ISSPACE(*enclist)) + namelen = enclist - name + 1; + + if(namelen) { + const struct Curl_cwtype *cwt; + struct Curl_cwriter *writer; + + is_chunked = (is_transfer && (namelen == 7) && + strncasecompare(name, "chunked", 7)); + /* if we skip the decoding in this phase, do not look further. + * Exception is "chunked" transfer-encoding which always must happen */ + if((is_transfer && !data->set.http_transfer_encoding && !is_chunked) || + (!is_transfer && data->set.http_ce_skip)) { + /* not requested, ignore */ + return CURLE_OK; + } + + if(Curl_cwriter_count(data, phase) + 1 >= MAX_ENCODE_STACK) { + failf(data, "Reject response due to more than %u content encodings", + MAX_ENCODE_STACK); + return CURLE_BAD_CONTENT_ENCODING; + } + + cwt = find_unencode_writer(name, namelen, phase); + if(cwt && is_chunked && Curl_cwriter_get_by_type(data, cwt)) { + /* A 'chunked' transfer encoding has already been added. + * Ignore duplicates. See #13451. + * Also RFC 9112, ch. 6.1: + * "A sender MUST NOT apply the chunked transfer coding more than + * once to a message body." + */ + return CURLE_OK; + } + + if(is_transfer && !is_chunked && + Curl_cwriter_get_by_name(data, "chunked")) { + /* RFC 9112, ch. 6.1: + * "If any transfer coding other than chunked is applied to a + * response's content, the sender MUST either apply chunked as the + * final transfer coding or terminate the message by closing the + * connection." + * "chunked" must be the last added to be the first in its phase, + * reject this. + */ + failf(data, "Reject response due to 'chunked' not being the last " + "Transfer-Encoding"); + return CURLE_BAD_CONTENT_ENCODING; + } + + if(!cwt) + cwt = &error_writer; /* Defer error at use. */ + + result = Curl_cwriter_create(&writer, data, cwt, phase); + if(result) + return result; + + result = Curl_cwriter_add(data, writer); + if(result) { + Curl_cwriter_free(data, writer); + return result; + } + } + } while(*enclist); + + return CURLE_OK; +} + +#else +/* Stubs for builds without HTTP. */ +CURLcode Curl_build_unencoding_stack(struct Curl_easy *data, + const char *enclist, int is_transfer) +{ + (void) data; + (void) enclist; + (void) is_transfer; + return CURLE_NOT_BUILT_IN; +} + +void Curl_all_content_encodings(char *buf, size_t blen) +{ + DEBUGASSERT(buf); + DEBUGASSERT(blen); + if(blen < sizeof(CONTENT_ENCODING_DEFAULT)) + buf[0] = 0; + else + strcpy(buf, CONTENT_ENCODING_DEFAULT); +} + + +#endif /* CURL_DISABLE_HTTP */ diff --git a/third_party/curl/lib/content_encoding.h b/third_party/curl/lib/content_encoding.h new file mode 100644 index 0000000..1addf23 --- /dev/null +++ b/third_party/curl/lib/content_encoding.h @@ -0,0 +1,34 @@ +#ifndef HEADER_CURL_CONTENT_ENCODING_H +#define HEADER_CURL_CONTENT_ENCODING_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +struct Curl_cwriter; + +void Curl_all_content_encodings(char *buf, size_t blen); + +CURLcode Curl_build_unencoding_stack(struct Curl_easy *data, + const char *enclist, int is_transfer); +#endif /* HEADER_CURL_CONTENT_ENCODING_H */ diff --git a/third_party/curl/lib/cookie.c b/third_party/curl/lib/cookie.c new file mode 100644 index 0000000..837caaa --- /dev/null +++ b/third_party/curl/lib/cookie.c @@ -0,0 +1,1771 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/*** + + +RECEIVING COOKIE INFORMATION +============================ + +struct CookieInfo *Curl_cookie_init(struct Curl_easy *data, + const char *file, struct CookieInfo *inc, bool newsession); + + Inits a cookie struct to store data in a local file. This is always + called before any cookies are set. + +struct Cookie *Curl_cookie_add(struct Curl_easy *data, + struct CookieInfo *c, bool httpheader, bool noexpire, + char *lineptr, const char *domain, const char *path, + bool secure); + + The 'lineptr' parameter is a full "Set-cookie:" line as + received from a server. + + The function need to replace previously stored lines that this new + line supersedes. + + It may remove lines that are expired. + + It should return an indication of success/error. + + +SENDING COOKIE INFORMATION +========================== + +struct Cookies *Curl_cookie_getlist(struct CookieInfo *cookie, + char *host, char *path, bool secure); + + For a given host and path, return a linked list of cookies that + the client should send to the server if used now. The secure + boolean informs the cookie if a secure connection is achieved or + not. + + It shall only return cookies that haven't expired. + + +Example set of cookies: + + Set-cookie: PRODUCTINFO=webxpress; domain=.fidelity.com; path=/; secure + Set-cookie: PERSONALIZE=none;expires=Monday, 13-Jun-1988 03:04:55 GMT; + domain=.fidelity.com; path=/ftgw; secure + Set-cookie: FidHist=none;expires=Monday, 13-Jun-1988 03:04:55 GMT; + domain=.fidelity.com; path=/; secure + Set-cookie: FidOrder=none;expires=Monday, 13-Jun-1988 03:04:55 GMT; + domain=.fidelity.com; path=/; secure + Set-cookie: DisPend=none;expires=Monday, 13-Jun-1988 03:04:55 GMT; + domain=.fidelity.com; path=/; secure + Set-cookie: FidDis=none;expires=Monday, 13-Jun-1988 03:04:55 GMT; + domain=.fidelity.com; path=/; secure + Set-cookie: + Session_Key@6791a9e0-901a-11d0-a1c8-9b012c88aa77=none;expires=Monday, + 13-Jun-1988 03:04:55 GMT; domain=.fidelity.com; path=/; secure +****/ + + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) + +#include "urldata.h" +#include "cookie.h" +#include "psl.h" +#include "strtok.h" +#include "sendf.h" +#include "slist.h" +#include "share.h" +#include "strtoofft.h" +#include "strcase.h" +#include "curl_get_line.h" +#include "curl_memrchr.h" +#include "parsedate.h" +#include "rename.h" +#include "fopen.h" +#include "strdup.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +static void strstore(char **str, const char *newstr, size_t len); + +static void freecookie(struct Cookie *co) +{ + free(co->domain); + free(co->path); + free(co->spath); + free(co->name); + free(co->value); + free(co); +} + +static bool cookie_tailmatch(const char *cookie_domain, + size_t cookie_domain_len, + const char *hostname) +{ + size_t hostname_len = strlen(hostname); + + if(hostname_len < cookie_domain_len) + return FALSE; + + if(!strncasecompare(cookie_domain, + hostname + hostname_len-cookie_domain_len, + cookie_domain_len)) + return FALSE; + + /* + * A lead char of cookie_domain is not '.'. + * RFC6265 4.1.2.3. The Domain Attribute says: + * For example, if the value of the Domain attribute is + * "example.com", the user agent will include the cookie in the Cookie + * header when making HTTP requests to example.com, www.example.com, and + * www.corp.example.com. + */ + if(hostname_len == cookie_domain_len) + return TRUE; + if('.' == *(hostname + hostname_len - cookie_domain_len - 1)) + return TRUE; + return FALSE; +} + +/* + * matching cookie path and url path + * RFC6265 5.1.4 Paths and Path-Match + */ +static bool pathmatch(const char *cookie_path, const char *request_uri) +{ + size_t cookie_path_len; + size_t uri_path_len; + char *uri_path = NULL; + char *pos; + bool ret = FALSE; + + /* cookie_path must not have last '/' separator. ex: /sample */ + cookie_path_len = strlen(cookie_path); + if(1 == cookie_path_len) { + /* cookie_path must be '/' */ + return TRUE; + } + + uri_path = strdup(request_uri); + if(!uri_path) + return FALSE; + pos = strchr(uri_path, '?'); + if(pos) + *pos = 0x0; + + /* #-fragments are already cut off! */ + if(0 == strlen(uri_path) || uri_path[0] != '/') { + strstore(&uri_path, "/", 1); + if(!uri_path) + return FALSE; + } + + /* + * here, RFC6265 5.1.4 says + * 4. Output the characters of the uri-path from the first character up + * to, but not including, the right-most %x2F ("/"). + * but URL path /hoge?fuga=xxx means /hoge/index.cgi?fuga=xxx in some site + * without redirect. + * Ignore this algorithm because /hoge is uri path for this case + * (uri path is not /). + */ + + uri_path_len = strlen(uri_path); + + if(uri_path_len < cookie_path_len) { + ret = FALSE; + goto pathmatched; + } + + /* not using checkprefix() because matching should be case-sensitive */ + if(strncmp(cookie_path, uri_path, cookie_path_len)) { + ret = FALSE; + goto pathmatched; + } + + /* The cookie-path and the uri-path are identical. */ + if(cookie_path_len == uri_path_len) { + ret = TRUE; + goto pathmatched; + } + + /* here, cookie_path_len < uri_path_len */ + if(uri_path[cookie_path_len] == '/') { + ret = TRUE; + goto pathmatched; + } + + ret = FALSE; + +pathmatched: + free(uri_path); + return ret; +} + +/* + * Return the top-level domain, for optimal hashing. + */ +static const char *get_top_domain(const char * const domain, size_t *outlen) +{ + size_t len = 0; + const char *first = NULL, *last; + + if(domain) { + len = strlen(domain); + last = memrchr(domain, '.', len); + if(last) { + first = memrchr(domain, '.', (last - domain)); + if(first) + len -= (++first - domain); + } + } + + if(outlen) + *outlen = len; + + return first? first: domain; +} + +/* Avoid C1001, an "internal error" with MSVC14 */ +#if defined(_MSC_VER) && (_MSC_VER == 1900) +#pragma optimize("", off) +#endif + +/* + * A case-insensitive hash for the cookie domains. + */ +static size_t cookie_hash_domain(const char *domain, const size_t len) +{ + const char *end = domain + len; + size_t h = 5381; + + while(domain < end) { + h += h << 5; + h ^= Curl_raw_toupper(*domain++); + } + + return (h % COOKIE_HASH_SIZE); +} + +#if defined(_MSC_VER) && (_MSC_VER == 1900) +#pragma optimize("", on) +#endif + +/* + * Hash this domain. + */ +static size_t cookiehash(const char * const domain) +{ + const char *top; + size_t len; + + if(!domain || Curl_host_is_ipnum(domain)) + return 0; + + top = get_top_domain(domain, &len); + return cookie_hash_domain(top, len); +} + +/* + * cookie path sanitize + */ +static char *sanitize_cookie_path(const char *cookie_path) +{ + size_t len; + char *new_path = strdup(cookie_path); + if(!new_path) + return NULL; + + /* some stupid site sends path attribute with '"'. */ + len = strlen(new_path); + if(new_path[0] == '\"') { + memmove(new_path, new_path + 1, len); + len--; + } + if(len && (new_path[len - 1] == '\"')) { + new_path[--len] = 0x0; + } + + /* RFC6265 5.2.4 The Path Attribute */ + if(new_path[0] != '/') { + /* Let cookie-path be the default-path. */ + strstore(&new_path, "/", 1); + return new_path; + } + + /* convert /hoge/ to /hoge */ + if(len && new_path[len - 1] == '/') { + new_path[len - 1] = 0x0; + } + + return new_path; +} + +/* + * Load cookies from all given cookie files (CURLOPT_COOKIEFILE). + * + * NOTE: OOM or cookie parsing failures are ignored. + */ +void Curl_cookie_loadfiles(struct Curl_easy *data) +{ + struct curl_slist *list = data->state.cookielist; + if(list) { + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + while(list) { + struct CookieInfo *newcookies = + Curl_cookie_init(data, list->data, data->cookies, + data->set.cookiesession); + if(!newcookies) + /* + * Failure may be due to OOM or a bad cookie; both are ignored + * but only the first should be + */ + infof(data, "ignoring failed cookie_init for %s", list->data); + else + data->cookies = newcookies; + list = list->next; + } + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); + } +} + +/* + * strstore + * + * A thin wrapper around strdup which ensures that any memory allocated at + * *str will be freed before the string allocated by strdup is stored there. + * The intended usecase is repeated assignments to the same variable during + * parsing in a last-wins scenario. The caller is responsible for checking + * for OOM errors. + */ +static void strstore(char **str, const char *newstr, size_t len) +{ + DEBUGASSERT(newstr); + DEBUGASSERT(str); + free(*str); + *str = Curl_memdup0(newstr, len); +} + +/* + * remove_expired + * + * Remove expired cookies from the hash by inspecting the expires timestamp on + * each cookie in the hash, freeing and deleting any where the timestamp is in + * the past. If the cookiejar has recorded the next timestamp at which one or + * more cookies expire, then processing will exit early in case this timestamp + * is in the future. + */ +static void remove_expired(struct CookieInfo *cookies) +{ + struct Cookie *co, *nx; + curl_off_t now = (curl_off_t)time(NULL); + unsigned int i; + + /* + * If the earliest expiration timestamp in the jar is in the future we can + * skip scanning the whole jar and instead exit early as there won't be any + * cookies to evict. If we need to evict however, reset the next_expiration + * counter in order to track the next one. In case the recorded first + * expiration is the max offset, then perform the safe fallback of checking + * all cookies. + */ + if(now < cookies->next_expiration && + cookies->next_expiration != CURL_OFF_T_MAX) + return; + else + cookies->next_expiration = CURL_OFF_T_MAX; + + for(i = 0; i < COOKIE_HASH_SIZE; i++) { + struct Cookie *pv = NULL; + co = cookies->cookies[i]; + while(co) { + nx = co->next; + if(co->expires && co->expires < now) { + if(!pv) { + cookies->cookies[i] = co->next; + } + else { + pv->next = co->next; + } + cookies->numcookies--; + freecookie(co); + } + else { + /* + * If this cookie has an expiration timestamp earlier than what we've + * seen so far then record it for the next round of expirations. + */ + if(co->expires && co->expires < cookies->next_expiration) + cookies->next_expiration = co->expires; + pv = co; + } + co = nx; + } + } +} + +#ifndef USE_LIBPSL +/* Make sure domain contains a dot or is localhost. */ +static bool bad_domain(const char *domain, size_t len) +{ + if((len == 9) && strncasecompare(domain, "localhost", 9)) + return FALSE; + else { + /* there must be a dot present, but that dot must not be a trailing dot */ + char *dot = memchr(domain, '.', len); + if(dot) { + size_t i = dot - domain; + if((len - i) > 1) + /* the dot is not the last byte */ + return FALSE; + } + } + return TRUE; +} +#endif + +/* + RFC 6265 section 4.1.1 says a server should accept this range: + + cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + + But Firefox and Chrome as of June 2022 accept space, comma and double-quotes + fine. The prime reason for filtering out control bytes is that some HTTP + servers return 400 for requests that contain such. +*/ +static int invalid_octets(const char *p) +{ + /* Reject all bytes \x01 - \x1f (*except* \x09, TAB) + \x7f */ + static const char badoctets[] = { + "\x01\x02\x03\x04\x05\x06\x07\x08\x0a" + "\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14" + "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x7f" + }; + size_t len; + /* scan for all the octets that are *not* in cookie-octet */ + len = strcspn(p, badoctets); + return (p[len] != '\0'); +} + +/* + * Curl_cookie_add + * + * Add a single cookie line to the cookie keeping object. Be aware that + * sometimes we get an IP-only host name, and that might also be a numerical + * IPv6 address. + * + * Returns NULL on out of memory or invalid cookie. This is suboptimal, + * as they should be treated separately. + */ +struct Cookie * +Curl_cookie_add(struct Curl_easy *data, + struct CookieInfo *c, + bool httpheader, /* TRUE if HTTP header-style line */ + bool noexpire, /* if TRUE, skip remove_expired() */ + const char *lineptr, /* first character of the line */ + const char *domain, /* default domain */ + const char *path, /* full path used when this cookie is set, + used to get default path for the cookie + unless set */ + bool secure) /* TRUE if connection is over secure origin */ +{ + struct Cookie *clist; + struct Cookie *co; + struct Cookie *lastc = NULL; + struct Cookie *replace_co = NULL; + struct Cookie *replace_clist = NULL; + time_t now = time(NULL); + bool replace_old = FALSE; + bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */ + size_t myhash; + + DEBUGASSERT(data); + DEBUGASSERT(MAX_SET_COOKIE_AMOUNT <= 255); /* counter is an unsigned char */ + if(data->req.setcookies >= MAX_SET_COOKIE_AMOUNT) + return NULL; + + /* First, alloc and init a new struct for it */ + co = calloc(1, sizeof(struct Cookie)); + if(!co) + return NULL; /* bail out if we're this low on memory */ + + if(httpheader) { + /* This line was read off an HTTP-header */ + const char *ptr; + + size_t linelength = strlen(lineptr); + if(linelength > MAX_COOKIE_LINE) { + /* discard overly long lines at once */ + free(co); + return NULL; + } + + ptr = lineptr; + do { + size_t vlen; + size_t nlen; + + while(*ptr && ISBLANK(*ptr)) + ptr++; + + /* we have a = pair or a stand-alone word here */ + nlen = strcspn(ptr, ";\t\r\n="); + if(nlen) { + bool done = FALSE; + bool sep = FALSE; + const char *namep = ptr; + const char *valuep; + + ptr += nlen; + + /* trim trailing spaces and tabs after name */ + while(nlen && ISBLANK(namep[nlen - 1])) + nlen--; + + if(*ptr == '=') { + vlen = strcspn(++ptr, ";\r\n"); + valuep = ptr; + sep = TRUE; + ptr = &valuep[vlen]; + + /* Strip off trailing whitespace from the value */ + while(vlen && ISBLANK(valuep[vlen-1])) + vlen--; + + /* Skip leading whitespace from the value */ + while(vlen && ISBLANK(*valuep)) { + valuep++; + vlen--; + } + + /* Reject cookies with a TAB inside the value */ + if(memchr(valuep, '\t', vlen)) { + freecookie(co); + infof(data, "cookie contains TAB, dropping"); + return NULL; + } + } + else { + valuep = NULL; + vlen = 0; + } + + /* + * Check for too long individual name or contents, or too long + * combination of name + contents. Chrome and Firefox support 4095 or + * 4096 bytes combo + */ + if(nlen >= (MAX_NAME-1) || vlen >= (MAX_NAME-1) || + ((nlen + vlen) > MAX_NAME)) { + freecookie(co); + infof(data, "oversized cookie dropped, name/val %zu + %zu bytes", + nlen, vlen); + return NULL; + } + + /* + * Check if we have a reserved prefix set before anything else, as we + * otherwise have to test for the prefix in both the cookie name and + * "the rest". Prefixes must start with '__' and end with a '-', so + * only test for names where that can possibly be true. + */ + if(nlen >= 7 && namep[0] == '_' && namep[1] == '_') { + if(strncasecompare("__Secure-", namep, 9)) + co->prefix |= COOKIE_PREFIX__SECURE; + else if(strncasecompare("__Host-", namep, 7)) + co->prefix |= COOKIE_PREFIX__HOST; + } + + /* + * Use strstore() below to properly deal with received cookie + * headers that have the same string property set more than once, + * and then we use the last one. + */ + + if(!co->name) { + /* The very first name/value pair is the actual cookie name */ + if(!sep) { + /* Bad name/value pair. */ + badcookie = TRUE; + break; + } + strstore(&co->name, namep, nlen); + strstore(&co->value, valuep, vlen); + done = TRUE; + if(!co->name || !co->value) { + badcookie = TRUE; + break; + } + if(invalid_octets(co->value) || invalid_octets(co->name)) { + infof(data, "invalid octets in name/value, cookie dropped"); + badcookie = TRUE; + break; + } + } + else if(!vlen) { + /* + * this was a "=" with no content, and we must allow + * 'secure' and 'httponly' specified this weirdly + */ + done = TRUE; + /* + * secure cookies are only allowed to be set when the connection is + * using a secure protocol, or when the cookie is being set by + * reading from file + */ + if((nlen == 6) && strncasecompare("secure", namep, 6)) { + if(secure || !c->running) { + co->secure = TRUE; + } + else { + badcookie = TRUE; + break; + } + } + else if((nlen == 8) && strncasecompare("httponly", namep, 8)) + co->httponly = TRUE; + else if(sep) + /* there was a '=' so we're not done parsing this field */ + done = FALSE; + } + if(done) + ; + else if((nlen == 4) && strncasecompare("path", namep, 4)) { + strstore(&co->path, valuep, vlen); + if(!co->path) { + badcookie = TRUE; /* out of memory bad */ + break; + } + free(co->spath); /* if this is set again */ + co->spath = sanitize_cookie_path(co->path); + if(!co->spath) { + badcookie = TRUE; /* out of memory bad */ + break; + } + } + else if((nlen == 6) && + strncasecompare("domain", namep, 6) && vlen) { + bool is_ip; + + /* + * Now, we make sure that our host is within the given domain, or + * the given domain is not valid and thus cannot be set. + */ + + if('.' == valuep[0]) { + valuep++; /* ignore preceding dot */ + vlen--; + } + +#ifndef USE_LIBPSL + /* + * Without PSL we don't know when the incoming cookie is set on a + * TLD or otherwise "protected" suffix. To reduce risk, we require a + * dot OR the exact host name being "localhost". + */ + if(bad_domain(valuep, vlen)) + domain = ":"; +#endif + + is_ip = Curl_host_is_ipnum(domain ? domain : valuep); + + if(!domain + || (is_ip && !strncmp(valuep, domain, vlen) && + (vlen == strlen(domain))) + || (!is_ip && cookie_tailmatch(valuep, vlen, domain))) { + strstore(&co->domain, valuep, vlen); + if(!co->domain) { + badcookie = TRUE; + break; + } + if(!is_ip) + co->tailmatch = TRUE; /* we always do that if the domain name was + given */ + } + else { + /* + * We did not get a tailmatch and then the attempted set domain is + * not a domain to which the current host belongs. Mark as bad. + */ + badcookie = TRUE; + infof(data, "skipped cookie with bad tailmatch domain: %s", + valuep); + } + } + else if((nlen == 7) && strncasecompare("version", namep, 7)) { + /* just ignore */ + } + else if((nlen == 7) && strncasecompare("max-age", namep, 7)) { + /* + * Defined in RFC2109: + * + * Optional. The Max-Age attribute defines the lifetime of the + * cookie, in seconds. The delta-seconds value is a decimal non- + * negative integer. After delta-seconds seconds elapse, the + * client should discard the cookie. A value of zero means the + * cookie should be discarded immediately. + */ + CURLofft offt; + const char *maxage = valuep; + offt = curlx_strtoofft((*maxage == '\"')? + &maxage[1]:&maxage[0], NULL, 10, + &co->expires); + switch(offt) { + case CURL_OFFT_FLOW: + /* overflow, used max value */ + co->expires = CURL_OFF_T_MAX; + break; + case CURL_OFFT_INVAL: + /* negative or otherwise bad, expire */ + co->expires = 1; + break; + case CURL_OFFT_OK: + if(!co->expires) + /* already expired */ + co->expires = 1; + else if(CURL_OFF_T_MAX - now < co->expires) + /* would overflow */ + co->expires = CURL_OFF_T_MAX; + else + co->expires += now; + break; + } + } + else if((nlen == 7) && strncasecompare("expires", namep, 7)) { + char date[128]; + if(!co->expires && (vlen < sizeof(date))) { + /* copy the date so that it can be null terminated */ + memcpy(date, valuep, vlen); + date[vlen] = 0; + /* + * Let max-age have priority. + * + * If the date cannot get parsed for whatever reason, the cookie + * will be treated as a session cookie + */ + co->expires = Curl_getdate_capped(date); + + /* + * Session cookies have expires set to 0 so if we get that back + * from the date parser let's add a second to make it a + * non-session cookie + */ + if(co->expires == 0) + co->expires = 1; + else if(co->expires < 0) + co->expires = 0; + } + } + + /* + * Else, this is the second (or more) name we don't know about! + */ + } + else { + /* this is an "illegal" = pair */ + } + + while(*ptr && ISBLANK(*ptr)) + ptr++; + if(*ptr == ';') + ptr++; + else + break; + } while(1); + + if(!badcookie && !co->domain) { + if(domain) { + /* no domain was given in the header line, set the default */ + co->domain = strdup(domain); + if(!co->domain) + badcookie = TRUE; + } + } + + if(!badcookie && !co->path && path) { + /* + * No path was given in the header line, set the default. Note that the + * passed-in path to this function MAY have a '?' and following part that + * MUST NOT be stored as part of the path. + */ + char *queryp = strchr(path, '?'); + + /* + * queryp is where the interesting part of the path ends, so now we + * want to the find the last + */ + char *endslash; + if(!queryp) + endslash = strrchr(path, '/'); + else + endslash = memrchr(path, '/', (queryp - path)); + if(endslash) { + size_t pathlen = (endslash-path + 1); /* include end slash */ + co->path = Curl_memdup0(path, pathlen); + if(co->path) { + co->spath = sanitize_cookie_path(co->path); + if(!co->spath) + badcookie = TRUE; /* out of memory bad */ + } + else + badcookie = TRUE; + } + } + + /* + * If we didn't get a cookie name, or a bad one, the this is an illegal + * line so bail out. + */ + if(badcookie || !co->name) { + freecookie(co); + return NULL; + } + data->req.setcookies++; + } + else { + /* + * This line is NOT an HTTP header style line, we do offer support for + * reading the odd netscape cookies-file format here + */ + char *ptr; + char *firstptr; + char *tok_buf = NULL; + int fields; + + /* + * IE introduced HTTP-only cookies to prevent XSS attacks. Cookies marked + * with httpOnly after the domain name are not accessible from javascripts, + * but since curl does not operate at javascript level, we include them + * anyway. In Firefox's cookie files, these lines are preceded with + * #HttpOnly_ and then everything is as usual, so we skip 10 characters of + * the line.. + */ + if(strncmp(lineptr, "#HttpOnly_", 10) == 0) { + lineptr += 10; + co->httponly = TRUE; + } + + if(lineptr[0]=='#') { + /* don't even try the comments */ + free(co); + return NULL; + } + /* strip off the possible end-of-line characters */ + ptr = strchr(lineptr, '\r'); + if(ptr) + *ptr = 0; /* clear it */ + ptr = strchr(lineptr, '\n'); + if(ptr) + *ptr = 0; /* clear it */ + + firstptr = strtok_r((char *)lineptr, "\t", &tok_buf); /* tokenize on TAB */ + + /* + * Now loop through the fields and init the struct we already have + * allocated + */ + fields = 0; + for(ptr = firstptr; ptr && !badcookie; + ptr = strtok_r(NULL, "\t", &tok_buf), fields++) { + switch(fields) { + case 0: + if(ptr[0]=='.') /* skip preceding dots */ + ptr++; + co->domain = strdup(ptr); + if(!co->domain) + badcookie = TRUE; + break; + case 1: + /* + * flag: A TRUE/FALSE value indicating if all machines within a given + * domain can access the variable. Set TRUE when the cookie says + * .domain.com and to false when the domain is complete www.domain.com + */ + co->tailmatch = strcasecompare(ptr, "TRUE")?TRUE:FALSE; + break; + case 2: + /* The file format allows the path field to remain not filled in */ + if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) { + /* only if the path doesn't look like a boolean option! */ + co->path = strdup(ptr); + if(!co->path) + badcookie = TRUE; + else { + co->spath = sanitize_cookie_path(co->path); + if(!co->spath) { + badcookie = TRUE; /* out of memory bad */ + } + } + break; + } + /* this doesn't look like a path, make one up! */ + co->path = strdup("/"); + if(!co->path) + badcookie = TRUE; + co->spath = strdup("/"); + if(!co->spath) + badcookie = TRUE; + fields++; /* add a field and fall down to secure */ + FALLTHROUGH(); + case 3: + co->secure = FALSE; + if(strcasecompare(ptr, "TRUE")) { + if(secure || c->running) + co->secure = TRUE; + else + badcookie = TRUE; + } + break; + case 4: + if(curlx_strtoofft(ptr, NULL, 10, &co->expires)) + badcookie = TRUE; + break; + case 5: + co->name = strdup(ptr); + if(!co->name) + badcookie = TRUE; + else { + /* For Netscape file format cookies we check prefix on the name */ + if(strncasecompare("__Secure-", co->name, 9)) + co->prefix |= COOKIE_PREFIX__SECURE; + else if(strncasecompare("__Host-", co->name, 7)) + co->prefix |= COOKIE_PREFIX__HOST; + } + break; + case 6: + co->value = strdup(ptr); + if(!co->value) + badcookie = TRUE; + break; + } + } + if(6 == fields) { + /* we got a cookie with blank contents, fix it */ + co->value = strdup(""); + if(!co->value) + badcookie = TRUE; + else + fields++; + } + + if(!badcookie && (7 != fields)) + /* we did not find the sufficient number of fields */ + badcookie = TRUE; + + if(badcookie) { + freecookie(co); + return NULL; + } + + } + + if(co->prefix & COOKIE_PREFIX__SECURE) { + /* The __Secure- prefix only requires that the cookie be set secure */ + if(!co->secure) { + freecookie(co); + return NULL; + } + } + if(co->prefix & COOKIE_PREFIX__HOST) { + /* + * The __Host- prefix requires the cookie to be secure, have a "/" path + * and not have a domain set. + */ + if(co->secure && co->path && strcmp(co->path, "/") == 0 && !co->tailmatch) + ; + else { + freecookie(co); + return NULL; + } + } + + if(!c->running && /* read from a file */ + c->newsession && /* clean session cookies */ + !co->expires) { /* this is a session cookie since it doesn't expire! */ + freecookie(co); + return NULL; + } + + co->livecookie = c->running; + co->creationtime = ++c->lastct; + + /* + * Now we have parsed the incoming line, we must now check if this supersedes + * an already existing cookie, which it may if the previous have the same + * domain and path as this. + */ + + /* at first, remove expired cookies */ + if(!noexpire) + remove_expired(c); + +#ifdef USE_LIBPSL + /* + * Check if the domain is a Public Suffix and if yes, ignore the cookie. We + * must also check that the data handle isn't NULL since the psl code will + * dereference it. + */ + if(data && (domain && co->domain && !Curl_host_is_ipnum(co->domain))) { + bool acceptable = FALSE; + char lcase[256]; + char lcookie[256]; + size_t dlen = strlen(domain); + size_t clen = strlen(co->domain); + if((dlen < sizeof(lcase)) && (clen < sizeof(lcookie))) { + const psl_ctx_t *psl = Curl_psl_use(data); + if(psl) { + /* the PSL check requires lowercase domain name and pattern */ + Curl_strntolower(lcase, domain, dlen + 1); + Curl_strntolower(lcookie, co->domain, clen + 1); + acceptable = psl_is_cookie_domain_acceptable(psl, lcase, lcookie); + Curl_psl_release(data); + } + else + infof(data, "libpsl problem, rejecting cookie for satety"); + } + + if(!acceptable) { + infof(data, "cookie '%s' dropped, domain '%s' must not " + "set cookies for '%s'", co->name, domain, co->domain); + freecookie(co); + return NULL; + } + } +#endif + + /* A non-secure cookie may not overlay an existing secure cookie. */ + myhash = cookiehash(co->domain); + clist = c->cookies[myhash]; + while(clist) { + if(strcasecompare(clist->name, co->name)) { + /* the names are identical */ + bool matching_domains = FALSE; + + if(clist->domain && co->domain) { + if(strcasecompare(clist->domain, co->domain)) + /* The domains are identical */ + matching_domains = TRUE; + } + else if(!clist->domain && !co->domain) + matching_domains = TRUE; + + if(matching_domains && /* the domains were identical */ + clist->spath && co->spath && /* both have paths */ + clist->secure && !co->secure && !secure) { + size_t cllen; + const char *sep; + + /* + * A non-secure cookie may not overlay an existing secure cookie. + * For an existing cookie "a" with path "/login", refuse a new + * cookie "a" with for example path "/login/en", while the path + * "/loginhelper" is ok. + */ + + sep = strchr(clist->spath + 1, '/'); + + if(sep) + cllen = sep - clist->spath; + else + cllen = strlen(clist->spath); + + if(strncasecompare(clist->spath, co->spath, cllen)) { + infof(data, "cookie '%s' for domain '%s' dropped, would " + "overlay an existing cookie", co->name, co->domain); + freecookie(co); + return NULL; + } + } + } + + if(!replace_co && strcasecompare(clist->name, co->name)) { + /* the names are identical */ + + if(clist->domain && co->domain) { + if(strcasecompare(clist->domain, co->domain) && + (clist->tailmatch == co->tailmatch)) + /* The domains are identical */ + replace_old = TRUE; + } + else if(!clist->domain && !co->domain) + replace_old = TRUE; + + if(replace_old) { + /* the domains were identical */ + + if(clist->spath && co->spath && + !strcasecompare(clist->spath, co->spath)) + replace_old = FALSE; + else if(!clist->spath != !co->spath) + replace_old = FALSE; + } + + if(replace_old && !co->livecookie && clist->livecookie) { + /* + * Both cookies matched fine, except that the already present cookie is + * "live", which means it was set from a header, while the new one was + * read from a file and thus isn't "live". "live" cookies are preferred + * so the new cookie is freed. + */ + freecookie(co); + return NULL; + } + if(replace_old) { + replace_co = co; + replace_clist = clist; + } + } + lastc = clist; + clist = clist->next; + } + if(replace_co) { + co = replace_co; + clist = replace_clist; + co->next = clist->next; /* get the next-pointer first */ + + /* when replacing, creationtime is kept from old */ + co->creationtime = clist->creationtime; + + /* then free all the old pointers */ + free(clist->name); + free(clist->value); + free(clist->domain); + free(clist->path); + free(clist->spath); + + *clist = *co; /* then store all the new data */ + + free(co); /* free the newly allocated memory */ + co = clist; + } + + if(c->running) + /* Only show this when NOT reading the cookies from a file */ + infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, " + "expire %" CURL_FORMAT_CURL_OFF_T, + replace_old?"Replaced":"Added", co->name, co->value, + co->domain, co->path, co->expires); + + if(!replace_old) { + /* then make the last item point on this new one */ + if(lastc) + lastc->next = co; + else + c->cookies[myhash] = co; + c->numcookies++; /* one more cookie in the jar */ + } + + /* + * Now that we've added a new cookie to the jar, update the expiration + * tracker in case it is the next one to expire. + */ + if(co->expires && (co->expires < c->next_expiration)) + c->next_expiration = co->expires; + + return co; +} + + +/* + * Curl_cookie_init() + * + * Inits a cookie struct to read data from a local file. This is always + * called before any cookies are set. File may be NULL in which case only the + * struct is initialized. Is file is "-" then STDIN is read. + * + * If 'newsession' is TRUE, discard all "session cookies" on read from file. + * + * Note that 'data' might be called as NULL pointer. If data is NULL, 'file' + * will be ignored. + * + * Returns NULL on out of memory. Invalid cookies are ignored. + */ +struct CookieInfo *Curl_cookie_init(struct Curl_easy *data, + const char *file, + struct CookieInfo *inc, + bool newsession) +{ + struct CookieInfo *c; + FILE *handle = NULL; + + if(!inc) { + /* we didn't get a struct, create one */ + c = calloc(1, sizeof(struct CookieInfo)); + if(!c) + return NULL; /* failed to get memory */ + /* + * Initialize the next_expiration time to signal that we don't have enough + * information yet. + */ + c->next_expiration = CURL_OFF_T_MAX; + } + else { + /* we got an already existing one, use that */ + c = inc; + } + c->newsession = newsession; /* new session? */ + + if(data) { + FILE *fp = NULL; + if(file && *file) { + if(!strcmp(file, "-")) + fp = stdin; + else { + fp = fopen(file, "rb"); + if(!fp) + infof(data, "WARNING: failed to open cookie file \"%s\"", file); + else + handle = fp; + } + } + + c->running = FALSE; /* this is not running, this is init */ + if(fp) { + struct dynbuf buf; + Curl_dyn_init(&buf, MAX_COOKIE_LINE); + while(Curl_get_line(&buf, fp)) { + char *lineptr = Curl_dyn_ptr(&buf); + bool headerline = FALSE; + if(checkprefix("Set-Cookie:", lineptr)) { + /* This is a cookie line, get it! */ + lineptr += 11; + headerline = TRUE; + while(*lineptr && ISBLANK(*lineptr)) + lineptr++; + } + + Curl_cookie_add(data, c, headerline, TRUE, lineptr, NULL, NULL, TRUE); + } + Curl_dyn_free(&buf); /* free the line buffer */ + + /* + * Remove expired cookies from the hash. We must make sure to run this + * after reading the file, and not on every cookie. + */ + remove_expired(c); + + if(handle) + fclose(handle); + } + data->state.cookie_engine = TRUE; + } + c->running = TRUE; /* now, we're running */ + + return c; +} + +/* + * cookie_sort + * + * Helper function to sort cookies such that the longest path gets before the + * shorter path. Path, domain and name lengths are considered in that order, + * with the creationtime as the tiebreaker. The creationtime is guaranteed to + * be unique per cookie, so we know we will get an ordering at that point. + */ +static int cookie_sort(const void *p1, const void *p2) +{ + struct Cookie *c1 = *(struct Cookie **)p1; + struct Cookie *c2 = *(struct Cookie **)p2; + size_t l1, l2; + + /* 1 - compare cookie path lengths */ + l1 = c1->path ? strlen(c1->path) : 0; + l2 = c2->path ? strlen(c2->path) : 0; + + if(l1 != l2) + return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */ + + /* 2 - compare cookie domain lengths */ + l1 = c1->domain ? strlen(c1->domain) : 0; + l2 = c2->domain ? strlen(c2->domain) : 0; + + if(l1 != l2) + return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */ + + /* 3 - compare cookie name lengths */ + l1 = c1->name ? strlen(c1->name) : 0; + l2 = c2->name ? strlen(c2->name) : 0; + + if(l1 != l2) + return (l2 > l1) ? 1 : -1; + + /* 4 - compare cookie creation time */ + return (c2->creationtime > c1->creationtime) ? 1 : -1; +} + +/* + * cookie_sort_ct + * + * Helper function to sort cookies according to creation time. + */ +static int cookie_sort_ct(const void *p1, const void *p2) +{ + struct Cookie *c1 = *(struct Cookie **)p1; + struct Cookie *c2 = *(struct Cookie **)p2; + + return (c2->creationtime > c1->creationtime) ? 1 : -1; +} + +#define CLONE(field) \ + do { \ + if(src->field) { \ + d->field = strdup(src->field); \ + if(!d->field) \ + goto fail; \ + } \ + } while(0) + +static struct Cookie *dup_cookie(struct Cookie *src) +{ + struct Cookie *d = calloc(1, sizeof(struct Cookie)); + if(d) { + CLONE(domain); + CLONE(path); + CLONE(spath); + CLONE(name); + CLONE(value); + d->expires = src->expires; + d->tailmatch = src->tailmatch; + d->secure = src->secure; + d->livecookie = src->livecookie; + d->httponly = src->httponly; + d->creationtime = src->creationtime; + } + return d; + +fail: + freecookie(d); + return NULL; +} + +/* + * Curl_cookie_getlist + * + * For a given host and path, return a linked list of cookies that the client + * should send to the server if used now. The secure boolean informs the cookie + * if a secure connection is achieved or not. + * + * It shall only return cookies that haven't expired. + */ +struct Cookie *Curl_cookie_getlist(struct Curl_easy *data, + struct CookieInfo *c, + const char *host, const char *path, + bool secure) +{ + struct Cookie *newco; + struct Cookie *co; + struct Cookie *mainco = NULL; + size_t matches = 0; + bool is_ip; + const size_t myhash = cookiehash(host); + + if(!c || !c->cookies[myhash]) + return NULL; /* no cookie struct or no cookies in the struct */ + + /* at first, remove expired cookies */ + remove_expired(c); + + /* check if host is an IP(v4|v6) address */ + is_ip = Curl_host_is_ipnum(host); + + co = c->cookies[myhash]; + + while(co) { + /* if the cookie requires we're secure we must only continue if we are! */ + if(co->secure?secure:TRUE) { + + /* now check if the domain is correct */ + if(!co->domain || + (co->tailmatch && !is_ip && + cookie_tailmatch(co->domain, strlen(co->domain), host)) || + ((!co->tailmatch || is_ip) && strcasecompare(host, co->domain)) ) { + /* + * the right part of the host matches the domain stuff in the + * cookie data + */ + + /* + * now check the left part of the path with the cookies path + * requirement + */ + if(!co->spath || pathmatch(co->spath, path) ) { + + /* + * and now, we know this is a match and we should create an + * entry for the return-linked-list + */ + + newco = dup_cookie(co); + if(newco) { + /* then modify our next */ + newco->next = mainco; + + /* point the main to us */ + mainco = newco; + + matches++; + if(matches >= MAX_COOKIE_SEND_AMOUNT) { + infof(data, "Included max number of cookies (%zu) in request!", + matches); + break; + } + } + else + goto fail; + } + } + } + co = co->next; + } + + if(matches) { + /* + * Now we need to make sure that if there is a name appearing more than + * once, the longest specified path version comes first. To make this + * the swiftest way, we just sort them all based on path length. + */ + struct Cookie **array; + size_t i; + + /* alloc an array and store all cookie pointers */ + array = malloc(sizeof(struct Cookie *) * matches); + if(!array) + goto fail; + + co = mainco; + + for(i = 0; co; co = co->next) + array[i++] = co; + + /* now sort the cookie pointers in path length order */ + qsort(array, matches, sizeof(struct Cookie *), cookie_sort); + + /* remake the linked list order according to the new order */ + + mainco = array[0]; /* start here */ + for(i = 0; inext = array[i + 1]; + array[matches-1]->next = NULL; /* terminate the list */ + + free(array); /* remove the temporary data again */ + } + + return mainco; /* return the new list */ + +fail: + /* failure, clear up the allocated chain and return NULL */ + Curl_cookie_freelist(mainco); + return NULL; +} + +/* + * Curl_cookie_clearall + * + * Clear all existing cookies and reset the counter. + */ +void Curl_cookie_clearall(struct CookieInfo *cookies) +{ + if(cookies) { + unsigned int i; + for(i = 0; i < COOKIE_HASH_SIZE; i++) { + Curl_cookie_freelist(cookies->cookies[i]); + cookies->cookies[i] = NULL; + } + cookies->numcookies = 0; + } +} + +/* + * Curl_cookie_freelist + * + * Free a list of cookies previously returned by Curl_cookie_getlist(); + */ +void Curl_cookie_freelist(struct Cookie *co) +{ + struct Cookie *next; + while(co) { + next = co->next; + freecookie(co); + co = next; + } +} + +/* + * Curl_cookie_clearsess + * + * Free all session cookies in the cookies list. + */ +void Curl_cookie_clearsess(struct CookieInfo *cookies) +{ + struct Cookie *first, *curr, *next, *prev = NULL; + unsigned int i; + + if(!cookies) + return; + + for(i = 0; i < COOKIE_HASH_SIZE; i++) { + if(!cookies->cookies[i]) + continue; + + first = curr = prev = cookies->cookies[i]; + + for(; curr; curr = next) { + next = curr->next; + if(!curr->expires) { + if(first == curr) + first = next; + + if(prev == curr) + prev = next; + else + prev->next = next; + + freecookie(curr); + cookies->numcookies--; + } + else + prev = curr; + } + + cookies->cookies[i] = first; + } +} + +/* + * Curl_cookie_cleanup() + * + * Free a "cookie object" previous created with Curl_cookie_init(). + */ +void Curl_cookie_cleanup(struct CookieInfo *c) +{ + if(c) { + unsigned int i; + for(i = 0; i < COOKIE_HASH_SIZE; i++) + Curl_cookie_freelist(c->cookies[i]); + free(c); /* free the base struct as well */ + } +} + +/* + * get_netscape_format() + * + * Formats a string for Netscape output file, w/o a newline at the end. + * Function returns a char * to a formatted line. The caller is responsible + * for freeing the returned pointer. + */ +static char *get_netscape_format(const struct Cookie *co) +{ + return aprintf( + "%s" /* httponly preamble */ + "%s%s\t" /* domain */ + "%s\t" /* tailmatch */ + "%s\t" /* path */ + "%s\t" /* secure */ + "%" CURL_FORMAT_CURL_OFF_T "\t" /* expires */ + "%s\t" /* name */ + "%s", /* value */ + co->httponly?"#HttpOnly_":"", + /* + * Make sure all domains are prefixed with a dot if they allow + * tailmatching. This is Mozilla-style. + */ + (co->tailmatch && co->domain && co->domain[0] != '.')? ".":"", + co->domain?co->domain:"unknown", + co->tailmatch?"TRUE":"FALSE", + co->path?co->path:"/", + co->secure?"TRUE":"FALSE", + co->expires, + co->name, + co->value?co->value:""); +} + +/* + * cookie_output() + * + * Writes all internally known cookies to the specified file. Specify + * "-" as file name to write to stdout. + * + * The function returns non-zero on write failure. + */ +static CURLcode cookie_output(struct Curl_easy *data, + struct CookieInfo *c, const char *filename) +{ + struct Cookie *co; + FILE *out = NULL; + bool use_stdout = FALSE; + char *tempstore = NULL; + CURLcode error = CURLE_OK; + + if(!c) + /* no cookie engine alive */ + return CURLE_OK; + + /* at first, remove expired cookies */ + remove_expired(c); + + if(!strcmp("-", filename)) { + /* use stdout */ + out = stdout; + use_stdout = TRUE; + } + else { + error = Curl_fopen(data, filename, &out, &tempstore); + if(error) + goto error; + } + + fputs("# Netscape HTTP Cookie File\n" + "# https://curl.se/docs/http-cookies.html\n" + "# This file was generated by libcurl! Edit at your own risk.\n\n", + out); + + if(c->numcookies) { + unsigned int i; + size_t nvalid = 0; + struct Cookie **array; + + array = calloc(1, sizeof(struct Cookie *) * c->numcookies); + if(!array) { + error = CURLE_OUT_OF_MEMORY; + goto error; + } + + /* only sort the cookies with a domain property */ + for(i = 0; i < COOKIE_HASH_SIZE; i++) { + for(co = c->cookies[i]; co; co = co->next) { + if(!co->domain) + continue; + array[nvalid++] = co; + } + } + + qsort(array, nvalid, sizeof(struct Cookie *), cookie_sort_ct); + + for(i = 0; i < nvalid; i++) { + char *format_ptr = get_netscape_format(array[i]); + if(!format_ptr) { + free(array); + error = CURLE_OUT_OF_MEMORY; + goto error; + } + fprintf(out, "%s\n", format_ptr); + free(format_ptr); + } + + free(array); + } + + if(!use_stdout) { + fclose(out); + out = NULL; + if(tempstore && Curl_rename(tempstore, filename)) { + unlink(tempstore); + error = CURLE_WRITE_ERROR; + goto error; + } + } + + /* + * If we reach here we have successfully written a cookie file so there is + * no need to inspect the error, any error case should have jumped into the + * error block below. + */ + free(tempstore); + return CURLE_OK; + +error: + if(out && !use_stdout) + fclose(out); + free(tempstore); + return error; +} + +static struct curl_slist *cookie_list(struct Curl_easy *data) +{ + struct curl_slist *list = NULL; + struct curl_slist *beg; + struct Cookie *c; + char *line; + unsigned int i; + + if(!data->cookies || (data->cookies->numcookies == 0)) + return NULL; + + for(i = 0; i < COOKIE_HASH_SIZE; i++) { + for(c = data->cookies->cookies[i]; c; c = c->next) { + if(!c->domain) + continue; + line = get_netscape_format(c); + if(!line) { + curl_slist_free_all(list); + return NULL; + } + beg = Curl_slist_append_nodup(list, line); + if(!beg) { + free(line); + curl_slist_free_all(list); + return NULL; + } + list = beg; + } + } + + return list; +} + +struct curl_slist *Curl_cookie_list(struct Curl_easy *data) +{ + struct curl_slist *list; + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + list = cookie_list(data); + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); + return list; +} + +void Curl_flush_cookies(struct Curl_easy *data, bool cleanup) +{ + CURLcode res; + + if(data->set.str[STRING_COOKIEJAR]) { + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + + /* if we have a destination file for all the cookies to get dumped to */ + res = cookie_output(data, data->cookies, data->set.str[STRING_COOKIEJAR]); + if(res) + infof(data, "WARNING: failed to save cookies in %s: %s", + data->set.str[STRING_COOKIEJAR], curl_easy_strerror(res)); + } + else { + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + } + + if(cleanup && (!data->share || (data->cookies != data->share->cookies))) { + Curl_cookie_cleanup(data->cookies); + data->cookies = NULL; + } + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); +} + +#endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */ diff --git a/third_party/curl/lib/cookie.h b/third_party/curl/lib/cookie.h new file mode 100644 index 0000000..012dd89 --- /dev/null +++ b/third_party/curl/lib/cookie.h @@ -0,0 +1,138 @@ +#ifndef HEADER_CURL_COOKIE_H +#define HEADER_CURL_COOKIE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include + +struct Cookie { + struct Cookie *next; /* next in the chain */ + char *name; /* = value */ + char *value; /* name = */ + char *path; /* path = which is in Set-Cookie: */ + char *spath; /* sanitized cookie path */ + char *domain; /* domain = */ + curl_off_t expires; /* expires = */ + bool tailmatch; /* whether we do tail-matching of the domain name */ + bool secure; /* whether the 'secure' keyword was used */ + bool livecookie; /* updated from a server, not a stored file */ + bool httponly; /* true if the httponly directive is present */ + int creationtime; /* time when the cookie was written */ + unsigned char prefix; /* bitmap fields indicating which prefix are set */ +}; + +/* + * Available cookie prefixes, as defined in + * draft-ietf-httpbis-rfc6265bis-02 + */ +#define COOKIE_PREFIX__SECURE (1<<0) +#define COOKIE_PREFIX__HOST (1<<1) + +#define COOKIE_HASH_SIZE 63 + +struct CookieInfo { + /* linked list of cookies we know of */ + struct Cookie *cookies[COOKIE_HASH_SIZE]; + curl_off_t next_expiration; /* the next time at which expiration happens */ + int numcookies; /* number of cookies in the "jar" */ + int lastct; /* last creation-time used in the jar */ + bool running; /* state info, for cookie adding information */ + bool newsession; /* new session, discard session cookies on load */ +}; + +/* The maximum sizes we accept for cookies. RFC 6265 section 6.1 says + "general-use user agents SHOULD provide each of the following minimum + capabilities": + + - At least 4096 bytes per cookie (as measured by the sum of the length of + the cookie's name, value, and attributes). + In the 6265bis draft document section 5.4 it is phrased even stronger: "If + the sum of the lengths of the name string and the value string is more than + 4096 octets, abort these steps and ignore the set-cookie-string entirely." +*/ + +/** Limits for INCOMING cookies **/ + +/* The longest we allow a line to be when reading a cookie from a HTTP header + or from a cookie jar */ +#define MAX_COOKIE_LINE 5000 + +/* Maximum length of an incoming cookie name or content we deal with. Longer + cookies are ignored. */ +#define MAX_NAME 4096 + +/* Maximum number of Set-Cookie: lines accepted in a single response. If more + such header lines are received, they are ignored. This value must be less + than 256 since an unsigned char is used to count. */ +#define MAX_SET_COOKIE_AMOUNT 50 + +/** Limits for OUTGOING cookies **/ + +/* Maximum size for an outgoing cookie line libcurl will use in an http + request. This is the default maximum length used in some versions of Apache + httpd. */ +#define MAX_COOKIE_HEADER_LEN 8190 + +/* Maximum number of cookies libcurl will send in a single request, even if + there might be more cookies that match. One reason to cap the number is to + keep the maximum HTTP request within the maximum allowed size. */ +#define MAX_COOKIE_SEND_AMOUNT 150 + +struct Curl_easy; +/* + * Add a cookie to the internal list of cookies. The domain and path arguments + * are only used if the header boolean is TRUE. + */ + +struct Cookie *Curl_cookie_add(struct Curl_easy *data, + struct CookieInfo *c, bool header, + bool noexpiry, const char *lineptr, + const char *domain, const char *path, + bool secure); + +struct Cookie *Curl_cookie_getlist(struct Curl_easy *data, + struct CookieInfo *c, const char *host, + const char *path, bool secure); +void Curl_cookie_freelist(struct Cookie *cookies); +void Curl_cookie_clearall(struct CookieInfo *cookies); +void Curl_cookie_clearsess(struct CookieInfo *cookies); + +#if defined(CURL_DISABLE_HTTP) || defined(CURL_DISABLE_COOKIES) +#define Curl_cookie_list(x) NULL +#define Curl_cookie_loadfiles(x) Curl_nop_stmt +#define Curl_cookie_init(x,y,z,w) NULL +#define Curl_cookie_cleanup(x) Curl_nop_stmt +#define Curl_flush_cookies(x,y) Curl_nop_stmt +#else +void Curl_flush_cookies(struct Curl_easy *data, bool cleanup); +void Curl_cookie_cleanup(struct CookieInfo *c); +struct CookieInfo *Curl_cookie_init(struct Curl_easy *data, + const char *file, struct CookieInfo *inc, + bool newsession); +struct curl_slist *Curl_cookie_list(struct Curl_easy *data); +void Curl_cookie_loadfiles(struct Curl_easy *data); +#endif + +#endif /* HEADER_CURL_COOKIE_H */ diff --git a/third_party/curl/lib/curl_addrinfo.c b/third_party/curl/lib/curl_addrinfo.c new file mode 100644 index 0000000..c32f24d --- /dev/null +++ b/third_party/curl/lib/curl_addrinfo.c @@ -0,0 +1,592 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#ifdef HAVE_NETINET_IN_H +# include +#endif +#ifdef HAVE_NETINET_IN6_H +# include +#endif +#ifdef HAVE_NETDB_H +# include +#endif +#ifdef HAVE_ARPA_INET_H +# include +#endif +#ifdef HAVE_SYS_UN_H +# include +#endif + +#ifdef __VMS +# include +# include +#endif + +#include + +#include "curl_addrinfo.h" +#include "inet_pton.h" +#include "warnless.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_freeaddrinfo() + * + * This is used to free a linked list of Curl_addrinfo structs along + * with all its associated allocated storage. This function should be + * called once for each successful call to Curl_getaddrinfo_ex() or to + * any function call which actually allocates a Curl_addrinfo struct. + */ + +#if defined(__INTEL_COMPILER) && (__INTEL_COMPILER == 910) && \ + defined(__OPTIMIZE__) && defined(__unix__) && defined(__i386__) + /* workaround icc 9.1 optimizer issue */ +# define vqualifier volatile +#else +# define vqualifier +#endif + +void +Curl_freeaddrinfo(struct Curl_addrinfo *cahead) +{ + struct Curl_addrinfo *vqualifier canext; + struct Curl_addrinfo *ca; + + for(ca = cahead; ca; ca = canext) { + canext = ca->ai_next; + free(ca); + } +} + + +#ifdef HAVE_GETADDRINFO +/* + * Curl_getaddrinfo_ex() + * + * This is a wrapper function around system's getaddrinfo(), with + * the only difference that instead of returning a linked list of + * addrinfo structs this one returns a linked list of Curl_addrinfo + * ones. The memory allocated by this function *MUST* be free'd with + * Curl_freeaddrinfo(). For each successful call to this function + * there must be an associated call later to Curl_freeaddrinfo(). + * + * There should be no single call to system's getaddrinfo() in the + * whole library, any such call should be 'routed' through this one. + */ + +int +Curl_getaddrinfo_ex(const char *nodename, + const char *servname, + const struct addrinfo *hints, + struct Curl_addrinfo **result) +{ + const struct addrinfo *ai; + struct addrinfo *aihead; + struct Curl_addrinfo *cafirst = NULL; + struct Curl_addrinfo *calast = NULL; + struct Curl_addrinfo *ca; + size_t ss_size; + int error; + + *result = NULL; /* assume failure */ + + error = getaddrinfo(nodename, servname, hints, &aihead); + if(error) + return error; + + /* traverse the addrinfo list */ + + for(ai = aihead; ai != NULL; ai = ai->ai_next) { + size_t namelen = ai->ai_canonname ? strlen(ai->ai_canonname) + 1 : 0; + /* ignore elements with unsupported address family, */ + /* settle family-specific sockaddr structure size. */ + if(ai->ai_family == AF_INET) + ss_size = sizeof(struct sockaddr_in); +#ifdef USE_IPV6 + else if(ai->ai_family == AF_INET6) + ss_size = sizeof(struct sockaddr_in6); +#endif + else + continue; + + /* ignore elements without required address info */ + if(!ai->ai_addr || !(ai->ai_addrlen > 0)) + continue; + + /* ignore elements with bogus address size */ + if((size_t)ai->ai_addrlen < ss_size) + continue; + + ca = malloc(sizeof(struct Curl_addrinfo) + ss_size + namelen); + if(!ca) { + error = EAI_MEMORY; + break; + } + + /* copy each structure member individually, member ordering, */ + /* size, or padding might be different for each platform. */ + + ca->ai_flags = ai->ai_flags; + ca->ai_family = ai->ai_family; + ca->ai_socktype = ai->ai_socktype; + ca->ai_protocol = ai->ai_protocol; + ca->ai_addrlen = (curl_socklen_t)ss_size; + ca->ai_addr = NULL; + ca->ai_canonname = NULL; + ca->ai_next = NULL; + + ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo)); + memcpy(ca->ai_addr, ai->ai_addr, ss_size); + + if(namelen) { + ca->ai_canonname = (void *)((char *)ca->ai_addr + ss_size); + memcpy(ca->ai_canonname, ai->ai_canonname, namelen); + } + + /* if the return list is empty, this becomes the first element */ + if(!cafirst) + cafirst = ca; + + /* add this element last in the return list */ + if(calast) + calast->ai_next = ca; + calast = ca; + + } + + /* destroy the addrinfo list */ + if(aihead) + freeaddrinfo(aihead); + + /* if we failed, also destroy the Curl_addrinfo list */ + if(error) { + Curl_freeaddrinfo(cafirst); + cafirst = NULL; + } + else if(!cafirst) { +#ifdef EAI_NONAME + /* rfc3493 conformant */ + error = EAI_NONAME; +#else + /* rfc3493 obsoleted */ + error = EAI_NODATA; +#endif +#ifdef USE_WINSOCK + SET_SOCKERRNO(error); +#endif + } + + *result = cafirst; + + /* This is not a CURLcode */ + return error; +} +#endif /* HAVE_GETADDRINFO */ + + +/* + * Curl_he2ai() + * + * This function returns a pointer to the first element of a newly allocated + * Curl_addrinfo struct linked list filled with the data of a given hostent. + * Curl_addrinfo is meant to work like the addrinfo struct does for a IPv6 + * stack, but usable also for IPv4, all hosts and environments. + * + * The memory allocated by this function *MUST* be free'd later on calling + * Curl_freeaddrinfo(). For each successful call to this function there + * must be an associated call later to Curl_freeaddrinfo(). + * + * Curl_addrinfo defined in "lib/curl_addrinfo.h" + * + * struct Curl_addrinfo { + * int ai_flags; + * int ai_family; + * int ai_socktype; + * int ai_protocol; + * curl_socklen_t ai_addrlen; * Follow rfc3493 struct addrinfo * + * char *ai_canonname; + * struct sockaddr *ai_addr; + * struct Curl_addrinfo *ai_next; + * }; + * + * hostent defined in + * + * struct hostent { + * char *h_name; + * char **h_aliases; + * int h_addrtype; + * int h_length; + * char **h_addr_list; + * }; + * + * for backward compatibility: + * + * #define h_addr h_addr_list[0] + */ + +struct Curl_addrinfo * +Curl_he2ai(const struct hostent *he, int port) +{ + struct Curl_addrinfo *ai; + struct Curl_addrinfo *prevai = NULL; + struct Curl_addrinfo *firstai = NULL; + struct sockaddr_in *addr; +#ifdef USE_IPV6 + struct sockaddr_in6 *addr6; +#endif + CURLcode result = CURLE_OK; + int i; + char *curr; + + if(!he) + /* no input == no output! */ + return NULL; + + DEBUGASSERT((he->h_name != NULL) && (he->h_addr_list != NULL)); + + for(i = 0; (curr = he->h_addr_list[i]) != NULL; i++) { + size_t ss_size; + size_t namelen = strlen(he->h_name) + 1; /* include null-terminator */ +#ifdef USE_IPV6 + if(he->h_addrtype == AF_INET6) + ss_size = sizeof(struct sockaddr_in6); + else +#endif + ss_size = sizeof(struct sockaddr_in); + + /* allocate memory to hold the struct, the address and the name */ + ai = calloc(1, sizeof(struct Curl_addrinfo) + ss_size + namelen); + if(!ai) { + result = CURLE_OUT_OF_MEMORY; + break; + } + /* put the address after the struct */ + ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo)); + /* then put the name after the address */ + ai->ai_canonname = (char *)ai->ai_addr + ss_size; + memcpy(ai->ai_canonname, he->h_name, namelen); + + if(!firstai) + /* store the pointer we want to return from this function */ + firstai = ai; + + if(prevai) + /* make the previous entry point to this */ + prevai->ai_next = ai; + + ai->ai_family = he->h_addrtype; + + /* we return all names as STREAM, so when using this address for TFTP + the type must be ignored and conn->socktype be used instead! */ + ai->ai_socktype = SOCK_STREAM; + + ai->ai_addrlen = (curl_socklen_t)ss_size; + + /* leave the rest of the struct filled with zero */ + + switch(ai->ai_family) { + case AF_INET: + addr = (void *)ai->ai_addr; /* storage area for this info */ + + memcpy(&addr->sin_addr, curr, sizeof(struct in_addr)); + addr->sin_family = (CURL_SA_FAMILY_T)(he->h_addrtype); + addr->sin_port = htons((unsigned short)port); + break; + +#ifdef USE_IPV6 + case AF_INET6: + addr6 = (void *)ai->ai_addr; /* storage area for this info */ + + memcpy(&addr6->sin6_addr, curr, sizeof(struct in6_addr)); + addr6->sin6_family = (CURL_SA_FAMILY_T)(he->h_addrtype); + addr6->sin6_port = htons((unsigned short)port); + break; +#endif + } + + prevai = ai; + } + + if(result) { + Curl_freeaddrinfo(firstai); + firstai = NULL; + } + + return firstai; +} + + +struct namebuff { + struct hostent hostentry; + union { + struct in_addr ina4; +#ifdef USE_IPV6 + struct in6_addr ina6; +#endif + } addrentry; + char *h_addr_list[2]; +}; + + +/* + * Curl_ip2addr() + * + * This function takes an internet address, in binary form, as input parameter + * along with its address family and the string version of the address, and it + * returns a Curl_addrinfo chain filled in correctly with information for the + * given address/host + */ + +struct Curl_addrinfo * +Curl_ip2addr(int af, const void *inaddr, const char *hostname, int port) +{ + struct Curl_addrinfo *ai; + +#if defined(__VMS) && \ + defined(__INITIAL_POINTER_SIZE) && (__INITIAL_POINTER_SIZE == 64) +#pragma pointer_size save +#pragma pointer_size short +#pragma message disable PTRMISMATCH +#endif + + struct hostent *h; + struct namebuff *buf; + char *addrentry; + char *hoststr; + size_t addrsize; + + DEBUGASSERT(inaddr && hostname); + + buf = malloc(sizeof(struct namebuff)); + if(!buf) + return NULL; + + hoststr = strdup(hostname); + if(!hoststr) { + free(buf); + return NULL; + } + + switch(af) { + case AF_INET: + addrsize = sizeof(struct in_addr); + addrentry = (void *)&buf->addrentry.ina4; + memcpy(addrentry, inaddr, sizeof(struct in_addr)); + break; +#ifdef USE_IPV6 + case AF_INET6: + addrsize = sizeof(struct in6_addr); + addrentry = (void *)&buf->addrentry.ina6; + memcpy(addrentry, inaddr, sizeof(struct in6_addr)); + break; +#endif + default: + free(hoststr); + free(buf); + return NULL; + } + + h = &buf->hostentry; + h->h_name = hoststr; + h->h_aliases = NULL; + h->h_addrtype = (short)af; + h->h_length = (short)addrsize; + h->h_addr_list = &buf->h_addr_list[0]; + h->h_addr_list[0] = addrentry; + h->h_addr_list[1] = NULL; /* terminate list of entries */ + +#if defined(__VMS) && \ + defined(__INITIAL_POINTER_SIZE) && (__INITIAL_POINTER_SIZE == 64) +#pragma pointer_size restore +#pragma message enable PTRMISMATCH +#endif + + ai = Curl_he2ai(h, port); + + free(hoststr); + free(buf); + + return ai; +} + +/* + * Given an IPv4 or IPv6 dotted string address, this converts it to a proper + * allocated Curl_addrinfo struct and returns it. + */ +struct Curl_addrinfo *Curl_str2addr(char *address, int port) +{ + struct in_addr in; + if(Curl_inet_pton(AF_INET, address, &in) > 0) + /* This is a dotted IP address 123.123.123.123-style */ + return Curl_ip2addr(AF_INET, &in, address, port); +#ifdef USE_IPV6 + { + struct in6_addr in6; + if(Curl_inet_pton(AF_INET6, address, &in6) > 0) + /* This is a dotted IPv6 address ::1-style */ + return Curl_ip2addr(AF_INET6, &in6, address, port); + } +#endif + return NULL; /* bad input format */ +} + +#ifdef USE_UNIX_SOCKETS +/** + * Given a path to a Unix domain socket, return a newly allocated Curl_addrinfo + * struct initialized with this path. + * Set '*longpath' to TRUE if the error is a too long path. + */ +struct Curl_addrinfo *Curl_unix2addr(const char *path, bool *longpath, + bool abstract) +{ + struct Curl_addrinfo *ai; + struct sockaddr_un *sa_un; + size_t path_len; + + *longpath = FALSE; + + ai = calloc(1, sizeof(struct Curl_addrinfo) + sizeof(struct sockaddr_un)); + if(!ai) + return NULL; + ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo)); + + sa_un = (void *) ai->ai_addr; + sa_un->sun_family = AF_UNIX; + + /* sun_path must be able to store the NUL-terminated path */ + path_len = strlen(path) + 1; + if(path_len > sizeof(sa_un->sun_path)) { + free(ai); + *longpath = TRUE; + return NULL; + } + + ai->ai_family = AF_UNIX; + ai->ai_socktype = SOCK_STREAM; /* assume reliable transport for HTTP */ + ai->ai_addrlen = (curl_socklen_t) + ((offsetof(struct sockaddr_un, sun_path) + path_len) & 0x7FFFFFFF); + + /* Abstract Unix domain socket have NULL prefix instead of suffix */ + if(abstract) + memcpy(sa_un->sun_path + 1, path, path_len - 1); + else + memcpy(sa_un->sun_path, path, path_len); /* copy NUL byte */ + + return ai; +} +#endif + +#if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) && \ + defined(HAVE_FREEADDRINFO) +/* + * curl_dbg_freeaddrinfo() + * + * This is strictly for memory tracing and are using the same style as the + * family otherwise present in memdebug.c. I put these ones here since they + * require a bunch of structs I didn't want to include in memdebug.c + */ + +void +curl_dbg_freeaddrinfo(struct addrinfo *freethis, + int line, const char *source) +{ + curl_dbg_log("ADDR %s:%d freeaddrinfo(%p)\n", + source, line, (void *)freethis); +#ifdef USE_LWIPSOCK + lwip_freeaddrinfo(freethis); +#else + (freeaddrinfo)(freethis); +#endif +} +#endif /* defined(CURLDEBUG) && defined(HAVE_FREEADDRINFO) */ + + +#if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) +/* + * curl_dbg_getaddrinfo() + * + * This is strictly for memory tracing and are using the same style as the + * family otherwise present in memdebug.c. I put these ones here since they + * require a bunch of structs I didn't want to include in memdebug.c + */ + +int +curl_dbg_getaddrinfo(const char *hostname, + const char *service, + const struct addrinfo *hints, + struct addrinfo **result, + int line, const char *source) +{ +#ifdef USE_LWIPSOCK + int res = lwip_getaddrinfo(hostname, service, hints, result); +#else + int res = (getaddrinfo)(hostname, service, hints, result); +#endif + if(0 == res) + /* success */ + curl_dbg_log("ADDR %s:%d getaddrinfo() = %p\n", + source, line, (void *)*result); + else + curl_dbg_log("ADDR %s:%d getaddrinfo() failed\n", + source, line); + return res; +} +#endif /* defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) */ + +#if defined(HAVE_GETADDRINFO) && defined(USE_RESOLVE_ON_IPS) +/* + * Work-arounds the sin6_port is always zero bug on iOS 9.3.2 and Mac OS X + * 10.11.5. + */ +void Curl_addrinfo_set_port(struct Curl_addrinfo *addrinfo, int port) +{ + struct Curl_addrinfo *ca; + struct sockaddr_in *addr; +#ifdef USE_IPV6 + struct sockaddr_in6 *addr6; +#endif + for(ca = addrinfo; ca != NULL; ca = ca->ai_next) { + switch(ca->ai_family) { + case AF_INET: + addr = (void *)ca->ai_addr; /* storage area for this info */ + addr->sin_port = htons((unsigned short)port); + break; + +#ifdef USE_IPV6 + case AF_INET6: + addr6 = (void *)ca->ai_addr; /* storage area for this info */ + addr6->sin6_port = htons((unsigned short)port); + break; +#endif + } + } +} +#endif diff --git a/third_party/curl/lib/curl_addrinfo.h b/third_party/curl/lib/curl_addrinfo.h new file mode 100644 index 0000000..c757c49 --- /dev/null +++ b/third_party/curl/lib/curl_addrinfo.h @@ -0,0 +1,108 @@ +#ifndef HEADER_CURL_ADDRINFO_H +#define HEADER_CURL_ADDRINFO_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +# include +#endif +#ifdef HAVE_NETDB_H +# include +#endif +#ifdef HAVE_ARPA_INET_H +# include +#endif + +#ifdef __VMS +# include +# include +# include +#endif + +/* + * Curl_addrinfo is our internal struct definition that we use to allow + * consistent internal handling of this data. We use this even when the + * system provides an addrinfo structure definition. And we use this for + * all sorts of IPv4 and IPV6 builds. + */ + +struct Curl_addrinfo { + int ai_flags; + int ai_family; + int ai_socktype; + int ai_protocol; + curl_socklen_t ai_addrlen; /* Follow rfc3493 struct addrinfo */ + char *ai_canonname; + struct sockaddr *ai_addr; + struct Curl_addrinfo *ai_next; +}; + +void +Curl_freeaddrinfo(struct Curl_addrinfo *cahead); + +#ifdef HAVE_GETADDRINFO +int +Curl_getaddrinfo_ex(const char *nodename, + const char *servname, + const struct addrinfo *hints, + struct Curl_addrinfo **result); +#endif + +struct Curl_addrinfo * +Curl_he2ai(const struct hostent *he, int port); + +struct Curl_addrinfo * +Curl_ip2addr(int af, const void *inaddr, const char *hostname, int port); + +struct Curl_addrinfo *Curl_str2addr(char *dotted, int port); + +#ifdef USE_UNIX_SOCKETS +struct Curl_addrinfo *Curl_unix2addr(const char *path, bool *longpath, + bool abstract); +#endif + +#if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) && \ + defined(HAVE_FREEADDRINFO) +void +curl_dbg_freeaddrinfo(struct addrinfo *freethis, int line, const char *source); +#endif + +#if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) +int +curl_dbg_getaddrinfo(const char *hostname, const char *service, + const struct addrinfo *hints, struct addrinfo **result, + int line, const char *source); +#endif + +#ifdef HAVE_GETADDRINFO +#ifdef USE_RESOLVE_ON_IPS +void Curl_addrinfo_set_port(struct Curl_addrinfo *addrinfo, int port); +#else +#define Curl_addrinfo_set_port(x,y) +#endif +#endif + +#endif /* HEADER_CURL_ADDRINFO_H */ diff --git a/third_party/curl/lib/curl_base64.h b/third_party/curl/lib/curl_base64.h new file mode 100644 index 0000000..7f7cd1d --- /dev/null +++ b/third_party/curl/lib/curl_base64.h @@ -0,0 +1,41 @@ +#ifndef HEADER_CURL_BASE64_H +#define HEADER_CURL_BASE64_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifndef BUILDING_LIBCURL +/* this renames functions so that the tool code can use the same code + without getting symbol collisions */ +#define Curl_base64_encode(a,b,c,d) curlx_base64_encode(a,b,c,d) +#define Curl_base64url_encode(a,b,c,d) curlx_base64url_encode(a,b,c,d) +#define Curl_base64_decode(a,b,c) curlx_base64_decode(a,b,c) +#endif + +CURLcode Curl_base64_encode(const char *inputbuff, size_t insize, + char **outptr, size_t *outlen); +CURLcode Curl_base64url_encode(const char *inputbuff, size_t insize, + char **outptr, size_t *outlen); +CURLcode Curl_base64_decode(const char *src, + unsigned char **outptr, size_t *outlen); +#endif /* HEADER_CURL_BASE64_H */ diff --git a/third_party/curl/lib/curl_config.h.cmake b/third_party/curl/lib/curl_config.h.cmake new file mode 100644 index 0000000..3a46c64 --- /dev/null +++ b/third_party/curl/lib/curl_config.h.cmake @@ -0,0 +1,810 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* lib/curl_config.h.in. Generated somehow by cmake. */ + +/* Location of default ca bundle */ +#cmakedefine CURL_CA_BUNDLE "${CURL_CA_BUNDLE}" + +/* define "1" to use built-in ca store of TLS backend */ +#cmakedefine CURL_CA_FALLBACK 1 + +/* Location of default ca path */ +#cmakedefine CURL_CA_PATH "${CURL_CA_PATH}" + +/* Default SSL backend */ +#cmakedefine CURL_DEFAULT_SSL_BACKEND "${CURL_DEFAULT_SSL_BACKEND}" + +/* disables alt-svc */ +#cmakedefine CURL_DISABLE_ALTSVC 1 + +/* disables cookies support */ +#cmakedefine CURL_DISABLE_COOKIES 1 + +/* disables Basic authentication */ +#cmakedefine CURL_DISABLE_BASIC_AUTH 1 + +/* disables Bearer authentication */ +#cmakedefine CURL_DISABLE_BEARER_AUTH 1 + +/* disables Digest authentication */ +#cmakedefine CURL_DISABLE_DIGEST_AUTH 1 + +/* disables Kerberos authentication */ +#cmakedefine CURL_DISABLE_KERBEROS_AUTH 1 + +/* disables negotiate authentication */ +#cmakedefine CURL_DISABLE_NEGOTIATE_AUTH 1 + +/* disables AWS-SIG4 */ +#cmakedefine CURL_DISABLE_AWS 1 + +/* disables DICT */ +#cmakedefine CURL_DISABLE_DICT 1 + +/* disables DNS-over-HTTPS */ +#cmakedefine CURL_DISABLE_DOH 1 + +/* disables FILE */ +#cmakedefine CURL_DISABLE_FILE 1 + +/* disables form api */ +#cmakedefine CURL_DISABLE_FORM_API 1 + +/* disables FTP */ +#cmakedefine CURL_DISABLE_FTP 1 + +/* disables curl_easy_options API for existing options to curl_easy_setopt */ +#cmakedefine CURL_DISABLE_GETOPTIONS 1 + +/* disables GOPHER */ +#cmakedefine CURL_DISABLE_GOPHER 1 + +/* disables headers-api support */ +#cmakedefine CURL_DISABLE_HEADERS_API 1 + +/* disables HSTS support */ +#cmakedefine CURL_DISABLE_HSTS 1 + +/* disables HTTP */ +#cmakedefine CURL_DISABLE_HTTP 1 + +/* disables IMAP */ +#cmakedefine CURL_DISABLE_IMAP 1 + +/* disables LDAP */ +#cmakedefine CURL_DISABLE_LDAP 1 + +/* disables LDAPS */ +#cmakedefine CURL_DISABLE_LDAPS 1 + +/* disables --libcurl option from the curl tool */ +#cmakedefine CURL_DISABLE_LIBCURL_OPTION 1 + +/* disables MIME support */ +#cmakedefine CURL_DISABLE_MIME 1 + +/* disables local binding support */ +#cmakedefine CURL_DISABLE_BINDLOCAL 1 + +/* disables MQTT */ +#cmakedefine CURL_DISABLE_MQTT 1 + +/* disables netrc parser */ +#cmakedefine CURL_DISABLE_NETRC 1 + +/* disables NTLM support */ +#cmakedefine CURL_DISABLE_NTLM 1 + +/* disables date parsing */ +#cmakedefine CURL_DISABLE_PARSEDATE 1 + +/* disables POP3 */ +#cmakedefine CURL_DISABLE_POP3 1 + +/* disables built-in progress meter */ +#cmakedefine CURL_DISABLE_PROGRESS_METER 1 + +/* disables proxies */ +#cmakedefine CURL_DISABLE_PROXY 1 + +/* disables RTSP */ +#cmakedefine CURL_DISABLE_RTSP 1 + +/* disables SMB */ +#cmakedefine CURL_DISABLE_SMB 1 + +/* disables SMTP */ +#cmakedefine CURL_DISABLE_SMTP 1 + +/* disables use of socketpair for curl_multi_poll */ +#cmakedefine CURL_DISABLE_SOCKETPAIR 1 + +/* disables TELNET */ +#cmakedefine CURL_DISABLE_TELNET 1 + +/* disables TFTP */ +#cmakedefine CURL_DISABLE_TFTP 1 + +/* disables verbose strings */ +#cmakedefine CURL_DISABLE_VERBOSE_STRINGS 1 + +/* to make a symbol visible */ +#cmakedefine CURL_EXTERN_SYMBOL ${CURL_EXTERN_SYMBOL} +/* Ensure using CURL_EXTERN_SYMBOL is possible */ +#ifndef CURL_EXTERN_SYMBOL +#define CURL_EXTERN_SYMBOL +#endif + +/* Allow SMB to work on Windows */ +#cmakedefine USE_WIN32_CRYPTO 1 + +/* Use Windows LDAP implementation */ +#cmakedefine USE_WIN32_LDAP 1 + +/* Define if you want to enable IPv6 support */ +#cmakedefine USE_IPV6 1 + +/* Define to 1 if you have the alarm function. */ +#cmakedefine HAVE_ALARM 1 + +/* Define to 1 if you have the arc4random function. */ +#cmakedefine HAVE_ARC4RANDOM 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_ARPA_INET_H 1 + +/* Define to 1 if you have _Atomic support. */ +#cmakedefine HAVE_ATOMIC 1 + +/* Define to 1 if you have the `fnmatch' function. */ +#cmakedefine HAVE_FNMATCH 1 + +/* Define to 1 if you have the `basename' function. */ +#cmakedefine HAVE_BASENAME 1 + +/* Define to 1 if bool is an available type. */ +#cmakedefine HAVE_BOOL_T 1 + +/* Define to 1 if you have the __builtin_available function. */ +#cmakedefine HAVE_BUILTIN_AVAILABLE 1 + +/* Define to 1 if you have the clock_gettime function and monotonic timer. */ +#cmakedefine HAVE_CLOCK_GETTIME_MONOTONIC 1 + +/* Define to 1 if you have the clock_gettime function and raw monotonic timer. + */ +#cmakedefine HAVE_CLOCK_GETTIME_MONOTONIC_RAW 1 + +/* Define to 1 if you have the `closesocket' function. */ +#cmakedefine HAVE_CLOSESOCKET 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_DIRENT_H 1 + +/* Define to 1 if you have the `opendir' function. */ +#cmakedefine HAVE_OPENDIR 1 + +/* Define to 1 if you have the fcntl function. */ +#cmakedefine HAVE_FCNTL 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_FCNTL_H 1 + +/* Define to 1 if you have a working fcntl O_NONBLOCK function. */ +#cmakedefine HAVE_FCNTL_O_NONBLOCK 1 + +/* Define to 1 if you have the freeaddrinfo function. */ +#cmakedefine HAVE_FREEADDRINFO 1 + +/* Define to 1 if you have the fseeko function. */ +#cmakedefine HAVE_FSEEKO 1 + +/* Define to 1 if you have the fseeko declaration. */ +#cmakedefine HAVE_DECL_FSEEKO 1 + +/* Define to 1 if you have the _fseeki64 function. */ +#cmakedefine HAVE__FSEEKI64 1 + +/* Define to 1 if you have the ftruncate function. */ +#cmakedefine HAVE_FTRUNCATE 1 + +/* Define to 1 if you have a working getaddrinfo function. */ +#cmakedefine HAVE_GETADDRINFO 1 + +/* Define to 1 if the getaddrinfo function is threadsafe. */ +#cmakedefine HAVE_GETADDRINFO_THREADSAFE 1 + +/* Define to 1 if you have the `geteuid' function. */ +#cmakedefine HAVE_GETEUID 1 + +/* Define to 1 if you have the `getppid' function. */ +#cmakedefine HAVE_GETPPID 1 + +/* Define to 1 if you have the gethostbyname_r function. */ +#cmakedefine HAVE_GETHOSTBYNAME_R 1 + +/* gethostbyname_r() takes 3 args */ +#cmakedefine HAVE_GETHOSTBYNAME_R_3 1 + +/* gethostbyname_r() takes 5 args */ +#cmakedefine HAVE_GETHOSTBYNAME_R_5 1 + +/* gethostbyname_r() takes 6 args */ +#cmakedefine HAVE_GETHOSTBYNAME_R_6 1 + +/* Define to 1 if you have the gethostname function. */ +#cmakedefine HAVE_GETHOSTNAME 1 + +/* Define to 1 if you have a working getifaddrs function. */ +#cmakedefine HAVE_GETIFADDRS 1 + +/* Define to 1 if you have the `getpass_r' function. */ +#cmakedefine HAVE_GETPASS_R 1 + +/* Define to 1 if you have the `getpeername' function. */ +#cmakedefine HAVE_GETPEERNAME 1 + +/* Define to 1 if you have the `getsockname' function. */ +#cmakedefine HAVE_GETSOCKNAME 1 + +/* Define to 1 if you have the `if_nametoindex' function. */ +#cmakedefine HAVE_IF_NAMETOINDEX 1 + +/* Define to 1 if you have the `getpwuid' function. */ +#cmakedefine HAVE_GETPWUID 1 + +/* Define to 1 if you have the `getpwuid_r' function. */ +#cmakedefine HAVE_GETPWUID_R 1 + +/* Define to 1 if you have the `getrlimit' function. */ +#cmakedefine HAVE_GETRLIMIT 1 + +/* Define to 1 if you have the `gettimeofday' function. */ +#cmakedefine HAVE_GETTIMEOFDAY 1 + +/* Define to 1 if you have a working glibc-style strerror_r function. */ +#cmakedefine HAVE_GLIBC_STRERROR_R 1 + +/* Define to 1 if you have a working gmtime_r function. */ +#cmakedefine HAVE_GMTIME_R 1 + +/* if you have the gssapi libraries */ +#cmakedefine HAVE_GSSAPI 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_GSSAPI_GSSAPI_GENERIC_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_GSSAPI_GSSAPI_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_GSSAPI_GSSAPI_KRB5_H 1 + +/* if you have the GNU gssapi libraries */ +#cmakedefine HAVE_GSSGNU 1 + +/* Define to 1 if you have the `idna_strerror' function. */ +#cmakedefine HAVE_IDNA_STRERROR 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_IFADDRS_H 1 + +/* Define to 1 if you have a IPv6 capable working inet_ntop function. */ +#cmakedefine HAVE_INET_NTOP 1 + +/* Define to 1 if you have a IPv6 capable working inet_pton function. */ +#cmakedefine HAVE_INET_PTON 1 + +/* Define to 1 if symbol `sa_family_t' exists */ +#cmakedefine HAVE_SA_FAMILY_T 1 + +/* Define to 1 if symbol `ADDRESS_FAMILY' exists */ +#cmakedefine HAVE_ADDRESS_FAMILY 1 + +/* Define to 1 if you have the ioctlsocket function. */ +#cmakedefine HAVE_IOCTLSOCKET 1 + +/* Define to 1 if you have the IoctlSocket camel case function. */ +#cmakedefine HAVE_IOCTLSOCKET_CAMEL 1 + +/* Define to 1 if you have a working IoctlSocket camel case FIONBIO function. + */ +#cmakedefine HAVE_IOCTLSOCKET_CAMEL_FIONBIO 1 + +/* Define to 1 if you have a working ioctlsocket FIONBIO function. */ +#cmakedefine HAVE_IOCTLSOCKET_FIONBIO 1 + +/* Define to 1 if you have a working ioctl FIONBIO function. */ +#cmakedefine HAVE_IOCTL_FIONBIO 1 + +/* Define to 1 if you have a working ioctl SIOCGIFADDR function. */ +#cmakedefine HAVE_IOCTL_SIOCGIFADDR 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_IO_H 1 + +/* Define to 1 if you have the lber.h header file. */ +#cmakedefine HAVE_LBER_H 1 + +/* Define to 1 if you have the ldap.h header file. */ +#cmakedefine HAVE_LDAP_H 1 + +/* Use LDAPS implementation */ +#cmakedefine HAVE_LDAP_SSL 1 + +/* Define to 1 if you have the ldap_ssl.h header file. */ +#cmakedefine HAVE_LDAP_SSL_H 1 + +/* Define to 1 if you have the `ldap_url_parse' function. */ +#cmakedefine HAVE_LDAP_URL_PARSE 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_LIBGEN_H 1 + +/* Define to 1 if you have the `idn2' library (-lidn2). */ +#cmakedefine HAVE_LIBIDN2 1 + +/* Define to 1 if you have the idn2.h header file. */ +#cmakedefine HAVE_IDN2_H 1 + +/* Define to 1 if you have the `socket' library (-lsocket). */ +#cmakedefine HAVE_LIBSOCKET 1 + +/* Define to 1 if you have the `ssh2' library (-lssh2). */ +#cmakedefine HAVE_LIBSSH2 1 + +/* if zlib is available */ +#cmakedefine HAVE_LIBZ 1 + +/* if brotli is available */ +#cmakedefine HAVE_BROTLI 1 + +/* if zstd is available */ +#cmakedefine HAVE_ZSTD 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_LOCALE_H 1 + +/* Define to 1 if the compiler supports the 'long long' data type. */ +#cmakedefine HAVE_LONGLONG 1 + +/* Define to 1 if you have the 'suseconds_t' data type. */ +#cmakedefine HAVE_SUSECONDS_T 1 + +/* Define to 1 if you have the MSG_NOSIGNAL flag. */ +#cmakedefine HAVE_MSG_NOSIGNAL 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_NETDB_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_NETINET_IN_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_NETINET_TCP_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_NETINET_UDP_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_LINUX_TCP_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_NET_IF_H 1 + +/* if you have an old MIT gssapi library, lacking GSS_C_NT_HOSTBASED_SERVICE */ +#cmakedefine HAVE_OLD_GSSMIT 1 + +/* Define to 1 if you have the `pipe' function. */ +#cmakedefine HAVE_PIPE 1 + +/* If you have a fine poll */ +#cmakedefine HAVE_POLL_FINE 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_POLL_H 1 + +/* Define to 1 if you have a working POSIX-style strerror_r function. */ +#cmakedefine HAVE_POSIX_STRERROR_R 1 + +/* Define to 1 if you have the header file */ +#cmakedefine HAVE_PTHREAD_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_PWD_H 1 + +/* Define to 1 if OpenSSL has the `SSL_set0_wbio` function. */ +#cmakedefine HAVE_SSL_SET0_WBIO 1 + +/* Define to 1 if you have the recv function. */ +#cmakedefine HAVE_RECV 1 + +/* Define to 1 if you have the select function. */ +#cmakedefine HAVE_SELECT 1 + +/* Define to 1 if you have the sched_yield function. */ +#cmakedefine HAVE_SCHED_YIELD 1 + +/* Define to 1 if you have the send function. */ +#cmakedefine HAVE_SEND 1 + +/* Define to 1 if you have the sendmsg function. */ +#cmakedefine HAVE_SENDMSG 1 + +/* Define to 1 if you have the 'fsetxattr' function. */ +#cmakedefine HAVE_FSETXATTR 1 + +/* fsetxattr() takes 5 args */ +#cmakedefine HAVE_FSETXATTR_5 1 + +/* fsetxattr() takes 6 args */ +#cmakedefine HAVE_FSETXATTR_6 1 + +/* Define to 1 if you have the `setlocale' function. */ +#cmakedefine HAVE_SETLOCALE 1 + +/* Define to 1 if you have the `setmode' function. */ +#cmakedefine HAVE_SETMODE 1 + +/* Define to 1 if you have the `setrlimit' function. */ +#cmakedefine HAVE_SETRLIMIT 1 + +/* Define to 1 if you have a working setsockopt SO_NONBLOCK function. */ +#cmakedefine HAVE_SETSOCKOPT_SO_NONBLOCK 1 + +/* Define to 1 if you have the sigaction function. */ +#cmakedefine HAVE_SIGACTION 1 + +/* Define to 1 if you have the siginterrupt function. */ +#cmakedefine HAVE_SIGINTERRUPT 1 + +/* Define to 1 if you have the signal function. */ +#cmakedefine HAVE_SIGNAL 1 + +/* Define to 1 if you have the sigsetjmp function or macro. */ +#cmakedefine HAVE_SIGSETJMP 1 + +/* Define to 1 if you have the `snprintf' function. */ +#cmakedefine HAVE_SNPRINTF 1 + +/* Define to 1 if struct sockaddr_in6 has the sin6_scope_id member */ +#cmakedefine HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 + +/* Define to 1 if you have the `socket' function. */ +#cmakedefine HAVE_SOCKET 1 + +/* Define to 1 if you have the socketpair function. */ +#cmakedefine HAVE_SOCKETPAIR 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STDATOMIC_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STDBOOL_H 1 + +/* Define to 1 if you have the strcasecmp function. */ +#cmakedefine HAVE_STRCASECMP 1 + +/* Define to 1 if you have the strcmpi function. */ +#cmakedefine HAVE_STRCMPI 1 + +/* Define to 1 if you have the strdup function. */ +#cmakedefine HAVE_STRDUP 1 + +/* Define to 1 if you have the strerror_r function. */ +#cmakedefine HAVE_STRERROR_R 1 + +/* Define to 1 if you have the stricmp function. */ +#cmakedefine HAVE_STRICMP 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STROPTS_H 1 + +/* Define to 1 if you have the strtok_r function. */ +#cmakedefine HAVE_STRTOK_R 1 + +/* Define to 1 if you have the strtoll function. */ +#cmakedefine HAVE_STRTOLL 1 + +/* Define to 1 if you have the memrchr function. */ +#cmakedefine HAVE_MEMRCHR 1 + +/* if struct sockaddr_storage is defined */ +#cmakedefine HAVE_STRUCT_SOCKADDR_STORAGE 1 + +/* Define to 1 if you have the timeval struct. */ +#cmakedefine HAVE_STRUCT_TIMEVAL 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_FILIO_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_WAIT_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_IOCTL_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_PARAM_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_POLL_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_RESOURCE_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_SELECT_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_SOCKET_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_SOCKIO_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_TIME_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_UN_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_UTIME_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_TERMIOS_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_TERMIO_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_UNISTD_H 1 + +/* Define to 1 if you have the `utime' function. */ +#cmakedefine HAVE_UTIME 1 + +/* Define to 1 if you have the `utimes' function. */ +#cmakedefine HAVE_UTIMES 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_UTIME_H 1 + +/* Define this symbol if your OS supports changing the contents of argv */ +#cmakedefine HAVE_WRITABLE_ARGV 1 + +/* Define to 1 if you need the lber.h header file even with ldap.h */ +#cmakedefine NEED_LBER_H 1 + +/* Define to 1 if you need the malloc.h header file even with stdlib.h */ +#cmakedefine NEED_MALLOC_H 1 + +/* Define to 1 if _REENTRANT preprocessor symbol must be defined. */ +#cmakedefine NEED_REENTRANT 1 + +/* cpu-machine-OS */ +#cmakedefine OS ${OS} + +/* Name of package */ +#cmakedefine PACKAGE ${PACKAGE} + +/* Define to the address where bug reports for this package should be sent. */ +#cmakedefine PACKAGE_BUGREPORT ${PACKAGE_BUGREPORT} + +/* Define to the full name of this package. */ +#cmakedefine PACKAGE_NAME ${PACKAGE_NAME} + +/* Define to the full name and version of this package. */ +#cmakedefine PACKAGE_STRING ${PACKAGE_STRING} + +/* Define to the one symbol short name of this package. */ +#cmakedefine PACKAGE_TARNAME ${PACKAGE_TARNAME} + +/* Define to the version of this package. */ +#cmakedefine PACKAGE_VERSION ${PACKAGE_VERSION} + +/* a suitable file to read random data from */ +#cmakedefine RANDOM_FILE "${RANDOM_FILE}" + +/* + Note: SIZEOF_* variables are fetched with CMake through check_type_size(). + As per CMake documentation on CheckTypeSize, C preprocessor code is + generated by CMake into SIZEOF_*_CODE. This is what we use in the + following statements. + + Reference: https://cmake.org/cmake/help/latest/module/CheckTypeSize.html +*/ + +/* The size of `int', as computed by sizeof. */ +${SIZEOF_INT_CODE} + +/* The size of `long', as computed by sizeof. */ +${SIZEOF_LONG_CODE} + +/* The size of `long long', as computed by sizeof. */ +${SIZEOF_LONG_LONG_CODE} + +/* The size of `off_t', as computed by sizeof. */ +${SIZEOF_OFF_T_CODE} + +/* The size of `curl_off_t', as computed by sizeof. */ +${SIZEOF_CURL_OFF_T_CODE} + +/* The size of `curl_socket_t', as computed by sizeof. */ +${SIZEOF_CURL_SOCKET_T_CODE} + +/* The size of `size_t', as computed by sizeof. */ +${SIZEOF_SIZE_T_CODE} + +/* The size of `time_t', as computed by sizeof. */ +${SIZEOF_TIME_T_CODE} + +/* Define to 1 if you have the ANSI C header files. */ +#cmakedefine STDC_HEADERS 1 + +/* Define if you want to enable c-ares support */ +#cmakedefine USE_ARES 1 + +/* Define if you want to enable POSIX threaded DNS lookup */ +#cmakedefine USE_THREADS_POSIX 1 + +/* Define if you want to enable WIN32 threaded DNS lookup */ +#cmakedefine USE_THREADS_WIN32 1 + +/* if GnuTLS is enabled */ +#cmakedefine USE_GNUTLS 1 + +/* if Secure Transport is enabled */ +#cmakedefine USE_SECTRANSP 1 + +/* if mbedTLS is enabled */ +#cmakedefine USE_MBEDTLS 1 + +/* if BearSSL is enabled */ +#cmakedefine USE_BEARSSL 1 + +/* if WolfSSL is enabled */ +#cmakedefine USE_WOLFSSL 1 + +/* if libSSH is in use */ +#cmakedefine USE_LIBSSH 1 + +/* if libSSH2 is in use */ +#cmakedefine USE_LIBSSH2 1 + +/* if libPSL is in use */ +#cmakedefine USE_LIBPSL 1 + +/* if you want to use OpenLDAP code instead of legacy ldap implementation */ +#cmakedefine USE_OPENLDAP 1 + +/* if OpenSSL is in use */ +#cmakedefine USE_OPENSSL 1 + +/* if librtmp/rtmpdump is in use */ +#cmakedefine USE_LIBRTMP 1 + +/* Define to 1 if you don't want the OpenSSL configuration to be loaded + automatically */ +#cmakedefine CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG 1 + +/* to enable NGHTTP2 */ +#cmakedefine USE_NGHTTP2 1 + +/* to enable NGTCP2 */ +#cmakedefine USE_NGTCP2 1 + +/* to enable NGHTTP3 */ +#cmakedefine USE_NGHTTP3 1 + +/* to enable quiche */ +#cmakedefine USE_QUICHE 1 + +/* to enable openssl + nghttp3 */ +#cmakedefine USE_OPENSSL_QUIC 1 + +/* Define to 1 if you have the quiche_conn_set_qlog_fd function. */ +#cmakedefine HAVE_QUICHE_CONN_SET_QLOG_FD 1 + +/* to enable msh3 */ +#cmakedefine USE_MSH3 1 + +/* if Unix domain sockets are enabled */ +#cmakedefine USE_UNIX_SOCKETS 1 + +/* Define to 1 if you are building a Windows target with large file support. */ +#cmakedefine USE_WIN32_LARGE_FILES 1 + +/* to enable SSPI support */ +#cmakedefine USE_WINDOWS_SSPI 1 + +/* to enable Windows SSL */ +#cmakedefine USE_SCHANNEL 1 + +/* enable multiple SSL backends */ +#cmakedefine CURL_WITH_MULTI_SSL 1 + +/* Version number of package */ +#cmakedefine VERSION ${VERSION} + +/* Define to 1 if OS is AIX. */ +#ifndef _ALL_SOURCE +# undef _ALL_SOURCE +#endif + +/* Number of bits in a file offset, on hosts where this is settable. */ +#cmakedefine _FILE_OFFSET_BITS ${_FILE_OFFSET_BITS} + +/* Define for large files, on AIX-style hosts. */ +#cmakedefine _LARGE_FILES ${_LARGE_FILES} + +/* define this if you need it to compile thread-safe code */ +#cmakedefine _THREAD_SAFE ${_THREAD_SAFE} + +/* Define to empty if `const' does not conform to ANSI C. */ +#cmakedefine const ${const} + +/* Type to use in place of in_addr_t when system does not provide it. */ +#cmakedefine in_addr_t ${in_addr_t} + +/* Define to `unsigned int' if does not define. */ +#cmakedefine size_t ${size_t} + +/* the signed version of size_t */ +#cmakedefine ssize_t ${ssize_t} + +/* Define to 1 if you have the mach_absolute_time function. */ +#cmakedefine HAVE_MACH_ABSOLUTE_TIME 1 + +/* to enable Windows IDN */ +#cmakedefine USE_WIN32_IDN 1 + +/* to enable Apple IDN */ +#cmakedefine USE_APPLE_IDN 1 + +/* Define to 1 to enable websocket support. */ +#cmakedefine USE_WEBSOCKETS 1 + +/* Define to 1 if OpenSSL has the SSL_CTX_set_srp_username function. */ +#cmakedefine HAVE_OPENSSL_SRP 1 + +/* Define to 1 if GnuTLS has the gnutls_srp_verifier function. */ +#cmakedefine HAVE_GNUTLS_SRP 1 + +/* Define to 1 to enable TLS-SRP support. */ +#cmakedefine USE_TLS_SRP 1 + +/* Define to 1 to query for HTTPSRR when using DoH */ +#cmakedefine USE_HTTPSRR 1 + +/* if ECH support is available */ +#cmakedefine USE_ECH 1 diff --git a/third_party/curl/lib/curl_config.h.in b/third_party/curl/lib/curl_config.h.in new file mode 100644 index 0000000..50e0759 --- /dev/null +++ b/third_party/curl/lib/curl_config.h.in @@ -0,0 +1,1001 @@ +/* lib/curl_config.h.in. Generated from configure.ac by autoheader. */ + +/* Ignore c-ares deprecation warnings */ +#undef CARES_NO_DEPRECATED + +/* to enable curl debug memory tracking */ +#undef CURLDEBUG + +/* Location of default ca bundle */ +#undef CURL_CA_BUNDLE + +/* define "1" to use built in CA store of SSL library */ +#undef CURL_CA_FALLBACK + +/* Location of default ca path */ +#undef CURL_CA_PATH + +/* Default SSL backend */ +#undef CURL_DEFAULT_SSL_BACKEND + +/* disable alt-svc */ +#undef CURL_DISABLE_ALTSVC + +/* to disable AWS sig support */ +#undef CURL_DISABLE_AWS + +/* to disable basic authentication */ +#undef CURL_DISABLE_BASIC_AUTH + +/* to disable bearer authentication */ +#undef CURL_DISABLE_BEARER_AUTH + +/* disable local binding support */ +#undef CURL_DISABLE_BINDLOCAL + +/* to disable cookies support */ +#undef CURL_DISABLE_COOKIES + +/* to disable DICT */ +#undef CURL_DISABLE_DICT + +/* to disable digest authentication */ +#undef CURL_DISABLE_DIGEST_AUTH + +/* disable DoH */ +#undef CURL_DISABLE_DOH + +/* to disable FILE */ +#undef CURL_DISABLE_FILE + +/* disable form API */ +#undef CURL_DISABLE_FORM_API + +/* to disable FTP */ +#undef CURL_DISABLE_FTP + +/* to disable curl_easy_options */ +#undef CURL_DISABLE_GETOPTIONS + +/* to disable Gopher */ +#undef CURL_DISABLE_GOPHER + +/* disable headers-api */ +#undef CURL_DISABLE_HEADERS_API + +/* disable alt-svc */ +#undef CURL_DISABLE_HSTS + +/* to disable HTTP */ +#undef CURL_DISABLE_HTTP + +/* disable HTTP authentication */ +#undef CURL_DISABLE_HTTP_AUTH + +/* to disable IMAP */ +#undef CURL_DISABLE_IMAP + +/* to disable kerberos authentication */ +#undef CURL_DISABLE_KERBEROS_AUTH + +/* to disable LDAP */ +#undef CURL_DISABLE_LDAP + +/* to disable LDAPS */ +#undef CURL_DISABLE_LDAPS + +/* to disable --libcurl C code generation option */ +#undef CURL_DISABLE_LIBCURL_OPTION + +/* disable mime API */ +#undef CURL_DISABLE_MIME + +/* to disable MQTT */ +#undef CURL_DISABLE_MQTT + +/* to disable negotiate authentication */ +#undef CURL_DISABLE_NEGOTIATE_AUTH + +/* disable netrc parsing */ +#undef CURL_DISABLE_NETRC + +/* to disable NTLM support */ +#undef CURL_DISABLE_NTLM + +/* if the OpenSSL configuration won't be loaded automatically */ +#undef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG + +/* disable date parsing */ +#undef CURL_DISABLE_PARSEDATE + +/* to disable POP3 */ +#undef CURL_DISABLE_POP3 + +/* disable progress-meter */ +#undef CURL_DISABLE_PROGRESS_METER + +/* to disable proxies */ +#undef CURL_DISABLE_PROXY + +/* to disable RTSP */ +#undef CURL_DISABLE_RTSP + +/* disable DNS shuffling */ +#undef CURL_DISABLE_SHUFFLE_DNS + +/* to disable SMB/CIFS */ +#undef CURL_DISABLE_SMB + +/* to disable SMTP */ +#undef CURL_DISABLE_SMTP + +/* to disable socketpair support */ +#undef CURL_DISABLE_SOCKETPAIR + +/* to disable TELNET */ +#undef CURL_DISABLE_TELNET + +/* to disable TFTP */ +#undef CURL_DISABLE_TFTP + +/* to disable verbose strings */ +#undef CURL_DISABLE_VERBOSE_STRINGS + +/* Definition to make a library symbol externally visible. */ +#undef CURL_EXTERN_SYMBOL + +/* IP address type in sockaddr */ +#undef CURL_SA_FAMILY_T + +/* built with multiple SSL backends */ +#undef CURL_WITH_MULTI_SSL + +/* enable debug build options */ +#undef DEBUGBUILD + +/* Define to the type of arg 2 for gethostname. */ +#undef GETHOSTNAME_TYPE_ARG2 + +/* Define to 1 if you have the alarm function. */ +#undef HAVE_ALARM + +/* Define to 1 if you have the `arc4random' function. */ +#undef HAVE_ARC4RANDOM + +/* Define to 1 if you have the header file. */ +#undef HAVE_ARPA_INET_H + +/* Define to 1 if you have _Atomic support. */ +#undef HAVE_ATOMIC + +/* Define to 1 if you have the basename function. */ +#undef HAVE_BASENAME + +/* Define to 1 if bool is an available type. */ +#undef HAVE_BOOL_T + +/* if BROTLI is in use */ +#undef HAVE_BROTLI + +/* Define to 1 if you have the header file. */ +#undef HAVE_BROTLI_DECODE_H + +/* Define to 1 if you have the __builtin_available function. */ +#undef HAVE_BUILTIN_AVAILABLE + +/* Define to 1 if you have the clock_gettime function and monotonic timer. */ +#undef HAVE_CLOCK_GETTIME_MONOTONIC + +/* Define to 1 if you have the clock_gettime function and raw monotonic timer. + */ +#undef HAVE_CLOCK_GETTIME_MONOTONIC_RAW + +/* Define to 1 if you have the closesocket function. */ +#undef HAVE_CLOSESOCKET + +/* Define to 1 if you have the CloseSocket camel case function. */ +#undef HAVE_CLOSESOCKET_CAMEL + +/* Define to 1 if you have the header file. */ +#undef HAVE_CRYPTO_H + +/* Define to 1 if you have the fseeko declaration */ +#undef HAVE_DECL_FSEEKO + +/* Define to 1 if you have the declaration of `getpwuid_r', and to 0 if you + don't. */ +#undef HAVE_DECL_GETPWUID_R + +/* "Set if getpwuid_r() declaration is missing" */ +#undef HAVE_DECL_GETPWUID_R_MISSING + +/* if you have */ +#undef HAVE_DIRENT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_DLFCN_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_ERR_H + +/* Define to 1 if you have the fcntl function. */ +#undef HAVE_FCNTL + +/* Define to 1 if you have the header file. */ +#undef HAVE_FCNTL_H + +/* Define to 1 if you have a working fcntl O_NONBLOCK function. */ +#undef HAVE_FCNTL_O_NONBLOCK + +/* Define to 1 if you have the `fnmatch' function. */ +#undef HAVE_FNMATCH + +/* Define to 1 if you have the freeaddrinfo function. */ +#undef HAVE_FREEADDRINFO + +/* Define to 1 if you have the `fseeko' function. */ +#undef HAVE_FSEEKO + +/* Define to 1 if you have the fsetxattr function. */ +#undef HAVE_FSETXATTR + +/* fsetxattr() takes 5 args */ +#undef HAVE_FSETXATTR_5 + +/* fsetxattr() takes 6 args */ +#undef HAVE_FSETXATTR_6 + +/* Define to 1 if you have the ftruncate function. */ +#undef HAVE_FTRUNCATE + +/* Define to 1 if you have a working getaddrinfo function. */ +#undef HAVE_GETADDRINFO + +/* Define to 1 if the getaddrinfo function is threadsafe. */ +#undef HAVE_GETADDRINFO_THREADSAFE + +/* Define to 1 if you have the `geteuid' function. */ +#undef HAVE_GETEUID + +/* Define to 1 if you have the gethostbyname function. */ +#undef HAVE_GETHOSTBYNAME + +/* Define to 1 if you have the gethostbyname_r function. */ +#undef HAVE_GETHOSTBYNAME_R + +/* gethostbyname_r() takes 3 args */ +#undef HAVE_GETHOSTBYNAME_R_3 + +/* gethostbyname_r() takes 5 args */ +#undef HAVE_GETHOSTBYNAME_R_5 + +/* gethostbyname_r() takes 6 args */ +#undef HAVE_GETHOSTBYNAME_R_6 + +/* Define to 1 if you have the gethostname function. */ +#undef HAVE_GETHOSTNAME + +/* Define to 1 if you have a working getifaddrs function. */ +#undef HAVE_GETIFADDRS + +/* Define to 1 if you have the `getpass_r' function. */ +#undef HAVE_GETPASS_R + +/* Define to 1 if you have the getpeername function. */ +#undef HAVE_GETPEERNAME + +/* Define to 1 if you have the `getppid' function. */ +#undef HAVE_GETPPID + +/* Define to 1 if you have the `getpwuid' function. */ +#undef HAVE_GETPWUID + +/* Define to 1 if you have the `getpwuid_r' function. */ +#undef HAVE_GETPWUID_R + +/* Define to 1 if you have the `getrlimit' function. */ +#undef HAVE_GETRLIMIT + +/* Define to 1 if you have the getsockname function. */ +#undef HAVE_GETSOCKNAME + +/* Define to 1 if you have the `gettimeofday' function. */ +#undef HAVE_GETTIMEOFDAY + +/* Define to 1 if you have a working glibc-style strerror_r function. */ +#undef HAVE_GLIBC_STRERROR_R + +/* Define to 1 if you have a working gmtime_r function. */ +#undef HAVE_GMTIME_R + +/* if you have the function gnutls_srp_verifier */ +#undef HAVE_GNUTLS_SRP + +/* if you have GSS-API libraries */ +#undef HAVE_GSSAPI + +/* Define to 1 if you have the header file. */ +#undef HAVE_GSSAPI_GSSAPI_GENERIC_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_GSSAPI_GSSAPI_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_GSSAPI_GSSAPI_KRB5_H + +/* if you have GNU GSS */ +#undef HAVE_GSSGNU + +/* Define to 1 if you have the header file. */ +#undef HAVE_HYPER_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_IDN2_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_IFADDRS_H + +/* Define to 1 if you have the `if_nametoindex' function. */ +#undef HAVE_IF_NAMETOINDEX + +/* Define to 1 if you have a IPv6 capable working inet_ntop function. */ +#undef HAVE_INET_NTOP + +/* Define to 1 if you have a IPv6 capable working inet_pton function. */ +#undef HAVE_INET_PTON + +/* Define to 1 if you have the header file. */ +#undef HAVE_INTTYPES_H + +/* Define to 1 if you have the ioctl function. */ +#undef HAVE_IOCTL + +/* Define to 1 if you have the ioctlsocket function. */ +#undef HAVE_IOCTLSOCKET + +/* Define to 1 if you have the IoctlSocket camel case function. */ +#undef HAVE_IOCTLSOCKET_CAMEL + +/* Define to 1 if you have a working IoctlSocket camel case FIONBIO function. + */ +#undef HAVE_IOCTLSOCKET_CAMEL_FIONBIO + +/* Define to 1 if you have a working ioctlsocket FIONBIO function. */ +#undef HAVE_IOCTLSOCKET_FIONBIO + +/* Define to 1 if you have a working ioctl FIONBIO function. */ +#undef HAVE_IOCTL_FIONBIO + +/* Define to 1 if you have a working ioctl SIOCGIFADDR function. */ +#undef HAVE_IOCTL_SIOCGIFADDR + +/* Define to 1 if you have the header file. */ +#undef HAVE_IO_H + +/* Define to 1 if you have the lber.h header file. */ +#undef HAVE_LBER_H + +/* Define to 1 if you have the ldap.h header file. */ +#undef HAVE_LDAP_H + +/* Define to 1 if you have the `ldap_init_fd' function. */ +#undef HAVE_LDAP_INIT_FD + +/* Use LDAPS implementation */ +#undef HAVE_LDAP_SSL + +/* Define to 1 if you have the ldap_ssl.h header file. */ +#undef HAVE_LDAP_SSL_H + +/* Define to 1 if you have the `ldap_url_parse' function. */ +#undef HAVE_LDAP_URL_PARSE + +/* Define to 1 if you have the `brotlidec' library (-lbrotlidec). */ +#undef HAVE_LIBBROTLIDEC + +/* Define to 1 if you have the header file. */ +#undef HAVE_LIBGEN_H + +/* Define to 1 if you have the `idn2' library (-lidn2). */ +#undef HAVE_LIBIDN2 + +/* Define to 1 if you have the header file. */ +#undef HAVE_LIBPSL_H + +/* Define to 1 if using libressl. */ +#undef HAVE_LIBRESSL + +/* Define to 1 if you have the header file. */ +#undef HAVE_LIBRTMP_RTMP_H + +/* Define to 1 if you have the `ssh' library (-lssh). */ +#undef HAVE_LIBSSH + +/* Define to 1 if you have the `ssh2' library (-lssh2). */ +#undef HAVE_LIBSSH2 + +/* Define to 1 if you have the `ssl' library (-lssl). */ +#undef HAVE_LIBSSL + +/* Define to 1 if you have the `wolfssh' library (-lwolfssh). */ +#undef HAVE_LIBWOLFSSH + +/* if zlib is available */ +#undef HAVE_LIBZ + +/* Define to 1 if you have the `zstd' library (-lzstd). */ +#undef HAVE_LIBZSTD + +/* Define to 1 if you have the header file. */ +#undef HAVE_LINUX_TCP_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_LOCALE_H + +/* Define to 1 if the compiler supports the 'long long' data type. */ +#undef HAVE_LONGLONG + +/* Define to 1 if you have the `mach_absolute_time' function. */ +#undef HAVE_MACH_ABSOLUTE_TIME + +/* Define to 1 if you have the memrchr function or macro. */ +#undef HAVE_MEMRCHR + +/* Define to 1 if you have the MSG_NOSIGNAL flag. */ +#undef HAVE_MSG_NOSIGNAL + +/* Define to 1 if you have the header file. */ +#undef HAVE_MSH3_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NETDB_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NETINET_IN6_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NETINET_IN_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NETINET_TCP_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NETINET_UDP_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NET_IF_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NGHTTP2_NGHTTP2_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NGHTTP3_NGHTTP3_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NGTCP2_NGTCP2_CRYPTO_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NGTCP2_NGTCP2_H + +/* if you have an old MIT Kerberos version, lacking GSS_C_NT_HOSTBASED_SERVICE + */ +#undef HAVE_OLD_GSSMIT + +/* if you have opendir */ +#undef HAVE_OPENDIR + +/* Define to 1 if using OpenSSL 3 or later. */ +#undef HAVE_OPENSSL3 + +/* Define to 1 if you have the header file. */ +#undef HAVE_OPENSSL_CRYPTO_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_OPENSSL_ERR_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_OPENSSL_PEM_H + +/* if you have the functions OSSL_QUIC_client_method */ +#undef HAVE_OPENSSL_QUIC + +/* Define to 1 if you have the header file. */ +#undef HAVE_OPENSSL_RSA_H + +/* if you have the functions SSL_CTX_set_srp_username and + SSL_CTX_set_srp_password */ +#undef HAVE_OPENSSL_SRP + +/* Define to 1 if you have the header file. */ +#undef HAVE_OPENSSL_SSL_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_OPENSSL_X509_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_PEM_H + +/* Define to 1 if you have the `pipe' function. */ +#undef HAVE_PIPE + +/* If you have a fine poll */ +#undef HAVE_POLL_FINE + +/* Define to 1 if you have the header file. */ +#undef HAVE_POLL_H + +/* Define to 1 if you have a working POSIX-style strerror_r function. */ +#undef HAVE_POSIX_STRERROR_R + +/* Define to 1 if you have the header file. */ +#undef HAVE_PROTO_BSDSOCKET_H + +/* if you have */ +#undef HAVE_PTHREAD_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_PWD_H + +/* Define to 1 if you have the `quiche_conn_set_qlog_fd' function. */ +#undef HAVE_QUICHE_CONN_SET_QLOG_FD + +/* Define to 1 if you have the header file. */ +#undef HAVE_QUICHE_H + +/* Define to 1 if you have the recv function. */ +#undef HAVE_RECV + +/* Define to 1 if you have the header file. */ +#undef HAVE_RSA_H + +/* Define to 1 if you have the `sched_yield' function. */ +#undef HAVE_SCHED_YIELD + +/* Define to 1 if you have the select function. */ +#undef HAVE_SELECT + +/* Define to 1 if you have the send function. */ +#undef HAVE_SEND + +/* Define to 1 if you have the `sendmsg' function. */ +#undef HAVE_SENDMSG + +/* Define to 1 if you have the header file. */ +#undef HAVE_SETJMP_H + +/* Define to 1 if you have the `setlocale' function. */ +#undef HAVE_SETLOCALE + +/* Define to 1 if you have the `setmode' function. */ +#undef HAVE_SETMODE + +/* Define to 1 if you have the `setrlimit' function. */ +#undef HAVE_SETRLIMIT + +/* Define to 1 if you have the sigaction function. */ +#undef HAVE_SIGACTION + +/* Define to 1 if you have the siginterrupt function. */ +#undef HAVE_SIGINTERRUPT + +/* Define to 1 if you have the signal function. */ +#undef HAVE_SIGNAL + +/* Define to 1 if you have the sigsetjmp function or macro. */ +#undef HAVE_SIGSETJMP + +/* Define to 1 if you have the `snprintf' function. */ +#undef HAVE_SNPRINTF + +/* Define to 1 if struct sockaddr_in6 has the sin6_scope_id member */ +#undef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID + +/* Define to 1 if you have the socket function. */ +#undef HAVE_SOCKET + +/* Define to 1 if you have the socketpair function. */ +#undef HAVE_SOCKETPAIR + +/* Define to 1 if you have the header file. */ +#undef HAVE_SOCKET_H + +/* Define to 1 if you have the `SSL_ech_set1_echconfig' function. */ +#undef HAVE_SSL_ECH_SET1_ECHCONFIG + +/* Define to 1 if you have the header file. */ +#undef HAVE_SSL_H + +/* Define to 1 if you have the `SSL_set0_wbio' function. */ +#undef HAVE_SSL_SET0_WBIO + +/* Define to 1 if you have the `SSL_set1_ech_config_list' function. */ +#undef HAVE_SSL_SET1_ECH_CONFIG_LIST + +/* Define to 1 if you have the `SSL_set_quic_use_legacy_codepoint' function. + */ +#undef HAVE_SSL_SET_QUIC_USE_LEGACY_CODEPOINT + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDATOMIC_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDBOOL_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDINT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDIO_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDLIB_H + +/* Define to 1 if you have the strcasecmp function. */ +#undef HAVE_STRCASECMP + +/* Define to 1 if you have the strcmpi function. */ +#undef HAVE_STRCMPI + +/* Define to 1 if you have the strdup function. */ +#undef HAVE_STRDUP + +/* Define to 1 if you have the strerror_r function. */ +#undef HAVE_STRERROR_R + +/* Define to 1 if you have the stricmp function. */ +#undef HAVE_STRICMP + +/* Define to 1 if you have the header file. */ +#undef HAVE_STRINGS_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STRING_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STROPTS_H + +/* Define to 1 if you have the strtok_r function. */ +#undef HAVE_STRTOK_R + +/* Define to 1 if you have the strtoll function. */ +#undef HAVE_STRTOLL + +/* if struct sockaddr_storage is defined */ +#undef HAVE_STRUCT_SOCKADDR_STORAGE + +/* Define to 1 if you have the timeval struct. */ +#undef HAVE_STRUCT_TIMEVAL + +/* Define to 1 if suseconds_t is an available type. */ +#undef HAVE_SUSECONDS_T + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_FILIO_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_IOCTL_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_PARAM_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_POLL_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_RESOURCE_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_SELECT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_SOCKET_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_SOCKIO_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_STAT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_TIME_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_TYPES_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_UN_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_UTIME_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_WAIT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_XATTR_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_TERMIOS_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_TERMIO_H + +/* Define this if time_t is unsigned */ +#undef HAVE_TIME_T_UNSIGNED + +/* Define to 1 if you have the header file. */ +#undef HAVE_UNISTD_H + +/* Define to 1 if you have the `utime' function. */ +#undef HAVE_UTIME + +/* Define to 1 if you have the `utimes' function. */ +#undef HAVE_UTIMES + +/* Define to 1 if you have the header file. */ +#undef HAVE_UTIME_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_WOLFSSH_SSH_H + +/* Define to 1 if you have the `wolfSSL_CTX_GenerateEchConfig' function. */ +#undef HAVE_WOLFSSL_CTX_GENERATEECHCONFIG + +/* if you have wolfSSL_DES_ecb_encrypt */ +#undef HAVE_WOLFSSL_DES_ECB_ENCRYPT + +/* if you have wolfSSL_BIO_set_shutdown */ +#undef HAVE_WOLFSSL_FULL_BIO + +/* Define to 1 if you have the `wolfSSL_get_peer_certificate' function. */ +#undef HAVE_WOLFSSL_GET_PEER_CERTIFICATE + +/* Define to 1 if you have the `wolfSSL_UseALPN' function. */ +#undef HAVE_WOLFSSL_USEALPN + +/* Define this symbol if your OS supports changing the contents of argv */ +#undef HAVE_WRITABLE_ARGV + +/* Define to 1 if you have the header file. */ +#undef HAVE_X509_H + +/* if libzstd is in use */ +#undef HAVE_ZSTD + +/* Define to 1 if you have the header file. */ +#undef HAVE_ZSTD_H + +/* Define to 1 if you have the `_fseeki64' function. */ +#undef HAVE__FSEEKI64 + +/* Define to the sub-directory where libtool stores uninstalled libraries. */ +#undef LT_OBJDIR + +/* Define to 1 if you need the lber.h header file even with ldap.h */ +#undef NEED_LBER_H + +/* Define to 1 if _REENTRANT preprocessor symbol must be defined. */ +#undef NEED_REENTRANT + +/* Define to 1 if _THREAD_SAFE preprocessor symbol must be defined. */ +#undef NEED_THREAD_SAFE + +/* cpu-machine-OS */ +#undef OS + +/* Name of package */ +#undef PACKAGE + +/* Define to the address where bug reports for this package should be sent. */ +#undef PACKAGE_BUGREPORT + +/* Define to the full name of this package. */ +#undef PACKAGE_NAME + +/* Define to the full name and version of this package. */ +#undef PACKAGE_STRING + +/* Define to the one symbol short name of this package. */ +#undef PACKAGE_TARNAME + +/* Define to the home page for this package. */ +#undef PACKAGE_URL + +/* Define to the version of this package. */ +#undef PACKAGE_VERSION + +/* a suitable file to read random data from */ +#undef RANDOM_FILE + +/* Size of curl_off_t in number of bytes */ +#undef SIZEOF_CURL_OFF_T + +/* Size of curl_socket_t in number of bytes */ +#undef SIZEOF_CURL_SOCKET_T + +/* Size of int in number of bytes */ +#undef SIZEOF_INT + +/* Size of long in number of bytes */ +#undef SIZEOF_LONG + +/* Size of long long in number of bytes */ +#undef SIZEOF_LONG_LONG + +/* Size of off_t in number of bytes */ +#undef SIZEOF_OFF_T + +/* Size of size_t in number of bytes */ +#undef SIZEOF_SIZE_T + +/* Size of time_t in number of bytes */ +#undef SIZEOF_TIME_T + +/* Define to 1 if all of the C90 standard headers exist (not just the ones + required in a freestanding environment). This macro is provided for + backward compatibility; new code need not use it. */ +#undef STDC_HEADERS + +/* if AmiSSL is in use */ +#undef USE_AMISSL + +/* Define to enable c-ares support */ +#undef USE_ARES + +/* if BearSSL is enabled */ +#undef USE_BEARSSL + +/* if ECH support is available */ +#undef USE_ECH + +/* if GnuTLS is enabled */ +#undef USE_GNUTLS + +/* GSASL support enabled */ +#undef USE_GSASL + +/* force HTTPS RR support for ECH */ +#undef USE_HTTPSRR + +/* if hyper is in use */ +#undef USE_HYPER + +/* Define if you want to enable IPv6 support */ +#undef USE_IPV6 + +/* if libpsl is in use */ +#undef USE_LIBPSL + +/* if librtmp is in use */ +#undef USE_LIBRTMP + +/* if libSSH is in use */ +#undef USE_LIBSSH + +/* if libSSH2 is in use */ +#undef USE_LIBSSH2 + +/* If you want to build curl with the built-in manual */ +#undef USE_MANUAL + +/* if mbedTLS is enabled */ +#undef USE_MBEDTLS + +/* if msh3 is in use */ +#undef USE_MSH3 + +/* if nghttp2 is in use */ +#undef USE_NGHTTP2 + +/* if nghttp3 is in use */ +#undef USE_NGHTTP3 + +/* if ngtcp2 is in use */ +#undef USE_NGTCP2 + +/* if ngtcp2_crypto_boringssl is in use */ +#undef USE_NGTCP2_CRYPTO_BORINGSSL + +/* if ngtcp2_crypto_gnutls is in use */ +#undef USE_NGTCP2_CRYPTO_GNUTLS + +/* if ngtcp2_crypto_quictls is in use */ +#undef USE_NGTCP2_CRYPTO_QUICTLS + +/* if ngtcp2_crypto_wolfssl is in use */ +#undef USE_NGTCP2_CRYPTO_WOLFSSL + +/* if ngtcp2 + nghttp3 is in use */ +#undef USE_NGTCP2_H3 + +/* Use OpenLDAP-specific code */ +#undef USE_OPENLDAP + +/* if OpenSSL is in use */ +#undef USE_OPENSSL + +/* if openssl quic + nghttp3 is in use */ +#undef USE_OPENSSL_H3 + +/* if openssl QUIC is in use */ +#undef USE_OPENSSL_QUIC + +/* if quiche is in use */ +#undef USE_QUICHE + +/* if rustls is enabled */ +#undef USE_RUSTLS + +/* to enable Windows native SSL/TLS support */ +#undef USE_SCHANNEL + +/* enable Secure Transport */ +#undef USE_SECTRANSP + +/* if you want POSIX threaded DNS lookup */ +#undef USE_THREADS_POSIX + +/* if you want Win32 threaded DNS lookup */ +#undef USE_THREADS_WIN32 + +/* Use TLS-SRP authentication */ +#undef USE_TLS_SRP + +/* Use Unix domain sockets */ +#undef USE_UNIX_SOCKETS + +/* enable websockets support */ +#undef USE_WEBSOCKETS + +/* Define to 1 if you are building a Windows target with crypto API support. + */ +#undef USE_WIN32_CRYPTO + +/* Define to 1 if you have the `normaliz' (WinIDN) library (-lnormaliz). */ +#undef USE_WIN32_IDN + +/* Define to 1 if you are building a Windows target with large file support. + */ +#undef USE_WIN32_LARGE_FILES + +/* Use Windows LDAP implementation */ +#undef USE_WIN32_LDAP + +/* Define to 1 if you are building a Windows target without large file + support. */ +#undef USE_WIN32_SMALL_FILES + +/* to enable SSPI support */ +#undef USE_WINDOWS_SSPI + +/* if wolfSSH is in use */ +#undef USE_WOLFSSH + +/* if wolfSSL is enabled */ +#undef USE_WOLFSSL + +/* Version number of package */ +#undef VERSION + +/* Define to 1 if OS is AIX. */ +#ifndef _ALL_SOURCE +# undef _ALL_SOURCE +#endif + +/* Number of bits in a file offset, on hosts where this is settable. */ +#undef _FILE_OFFSET_BITS + +/* Define for large files, on AIX-style hosts. */ +#undef _LARGE_FILES + +/* Define to empty if `const' does not conform to ANSI C. */ +#undef const + +/* Type to use in place of in_addr_t when system does not provide it. */ +#undef in_addr_t + +/* Define to `unsigned int' if does not define. */ +#undef size_t + +/* the signed version of size_t */ +#undef ssize_t diff --git a/third_party/curl/lib/curl_ctype.h b/third_party/curl/lib/curl_ctype.h new file mode 100644 index 0000000..7f0d0cc --- /dev/null +++ b/third_party/curl/lib/curl_ctype.h @@ -0,0 +1,51 @@ +#ifndef HEADER_CURL_CTYPE_H +#define HEADER_CURL_CTYPE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#define ISLOWHEXALHA(x) (((x) >= 'a') && ((x) <= 'f')) +#define ISUPHEXALHA(x) (((x) >= 'A') && ((x) <= 'F')) + +#define ISLOWCNTRL(x) ((unsigned char)(x) <= 0x1f) +#define IS7F(x) ((x) == 0x7f) + +#define ISLOWPRINT(x) (((x) >= 9) && ((x) <= 0x0d)) + +#define ISPRINT(x) (ISLOWPRINT(x) || (((x) >= ' ') && ((x) <= 0x7e))) +#define ISGRAPH(x) (ISLOWPRINT(x) || (((x) > ' ') && ((x) <= 0x7e))) +#define ISCNTRL(x) (ISLOWCNTRL(x) || IS7F(x)) +#define ISALPHA(x) (ISLOWER(x) || ISUPPER(x)) +#define ISXDIGIT(x) (ISDIGIT(x) || ISLOWHEXALHA(x) || ISUPHEXALHA(x)) +#define ISALNUM(x) (ISDIGIT(x) || ISLOWER(x) || ISUPPER(x)) +#define ISUPPER(x) (((x) >= 'A') && ((x) <= 'Z')) +#define ISLOWER(x) (((x) >= 'a') && ((x) <= 'z')) +#define ISDIGIT(x) (((x) >= '0') && ((x) <= '9')) +#define ISBLANK(x) (((x) == ' ') || ((x) == '\t')) +#define ISSPACE(x) (ISBLANK(x) || (((x) >= 0xa) && ((x) <= 0x0d))) +#define ISURLPUNTCS(x) (((x) == '-') || ((x) == '.') || ((x) == '_') || \ + ((x) == '~')) +#define ISUNRESERVED(x) (ISALNUM(x) || ISURLPUNTCS(x)) + + +#endif /* HEADER_CURL_CTYPE_H */ diff --git a/third_party/curl/lib/curl_des.c b/third_party/curl/lib/curl_des.c new file mode 100644 index 0000000..f8d2b2c --- /dev/null +++ b/third_party/curl/lib/curl_des.c @@ -0,0 +1,69 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, . + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_CURL_NTLM_CORE) && !defined(USE_WOLFSSL) && \ + (defined(USE_GNUTLS) || \ + defined(USE_SECTRANSP) || \ + defined(USE_OS400CRYPTO) || \ + defined(USE_WIN32_CRYPTO)) + +#include "curl_des.h" + +/* + * Curl_des_set_odd_parity() + * + * This is used to apply odd parity to the given byte array. It is typically + * used by when a cryptography engine doesn't have its own version. + * + * The function is a port of the Java based oddParity() function over at: + * + * https://davenport.sourceforge.net/ntlm.html + * + * Parameters: + * + * bytes [in/out] - The data whose parity bits are to be adjusted for + * odd parity. + * len [out] - The length of the data. + */ +void Curl_des_set_odd_parity(unsigned char *bytes, size_t len) +{ + size_t i; + + for(i = 0; i < len; i++) { + unsigned char b = bytes[i]; + + bool needs_parity = (((b >> 7) ^ (b >> 6) ^ (b >> 5) ^ + (b >> 4) ^ (b >> 3) ^ (b >> 2) ^ + (b >> 1)) & 0x01) == 0; + + if(needs_parity) + bytes[i] |= 0x01; + else + bytes[i] &= 0xfe; + } +} + +#endif diff --git a/third_party/curl/lib/curl_des.h b/third_party/curl/lib/curl_des.h new file mode 100644 index 0000000..66525ab --- /dev/null +++ b/third_party/curl/lib/curl_des.h @@ -0,0 +1,40 @@ +#ifndef HEADER_CURL_DES_H +#define HEADER_CURL_DES_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, . + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_CURL_NTLM_CORE) && !defined(USE_WOLFSSL) && \ + (defined(USE_GNUTLS) || \ + defined(USE_SECTRANSP) || \ + defined(USE_OS400CRYPTO) || \ + defined(USE_WIN32_CRYPTO)) + +/* Applies odd parity to the given byte array */ +void Curl_des_set_odd_parity(unsigned char *bytes, size_t length); + +#endif + +#endif /* HEADER_CURL_DES_H */ diff --git a/third_party/curl/lib/curl_endian.c b/third_party/curl/lib/curl_endian.c new file mode 100644 index 0000000..11c662a --- /dev/null +++ b/third_party/curl/lib/curl_endian.c @@ -0,0 +1,84 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "curl_endian.h" + +/* + * Curl_read16_le() + * + * This function converts a 16-bit integer from the little endian format, as + * used in the incoming package to whatever endian format we're using + * natively. + * + * Parameters: + * + * buf [in] - A pointer to a 2 byte buffer. + * + * Returns the integer. + */ +unsigned short Curl_read16_le(const unsigned char *buf) +{ + return (unsigned short)(((unsigned short)buf[0]) | + ((unsigned short)buf[1] << 8)); +} + +/* + * Curl_read32_le() + * + * This function converts a 32-bit integer from the little endian format, as + * used in the incoming package to whatever endian format we're using + * natively. + * + * Parameters: + * + * buf [in] - A pointer to a 4 byte buffer. + * + * Returns the integer. + */ +unsigned int Curl_read32_le(const unsigned char *buf) +{ + return ((unsigned int)buf[0]) | ((unsigned int)buf[1] << 8) | + ((unsigned int)buf[2] << 16) | ((unsigned int)buf[3] << 24); +} + +/* + * Curl_read16_be() + * + * This function converts a 16-bit integer from the big endian format, as + * used in the incoming package to whatever endian format we're using + * natively. + * + * Parameters: + * + * buf [in] - A pointer to a 2 byte buffer. + * + * Returns the integer. + */ +unsigned short Curl_read16_be(const unsigned char *buf) +{ + return (unsigned short)(((unsigned short)buf[0] << 8) | + ((unsigned short)buf[1])); +} diff --git a/third_party/curl/lib/curl_endian.h b/third_party/curl/lib/curl_endian.h new file mode 100644 index 0000000..fa28321 --- /dev/null +++ b/third_party/curl/lib/curl_endian.h @@ -0,0 +1,36 @@ +#ifndef HEADER_CURL_ENDIAN_H +#define HEADER_CURL_ENDIAN_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* Converts a 16-bit integer from little endian */ +unsigned short Curl_read16_le(const unsigned char *buf); + +/* Converts a 32-bit integer from little endian */ +unsigned int Curl_read32_le(const unsigned char *buf); + +/* Converts a 16-bit integer from big endian */ +unsigned short Curl_read16_be(const unsigned char *buf); + +#endif /* HEADER_CURL_ENDIAN_H */ diff --git a/third_party/curl/lib/curl_fnmatch.c b/third_party/curl/lib/curl_fnmatch.c new file mode 100644 index 0000000..5f9ca4f --- /dev/null +++ b/third_party/curl/lib/curl_fnmatch.c @@ -0,0 +1,390 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#ifndef CURL_DISABLE_FTP +#include + +#include "curl_fnmatch.h" +#include "curl_memory.h" + +/* The last #include file should be: */ +#include "memdebug.h" + +#ifndef HAVE_FNMATCH + +#define CURLFNM_CHARSET_LEN (sizeof(char) * 256) +#define CURLFNM_CHSET_SIZE (CURLFNM_CHARSET_LEN + 15) + +#define CURLFNM_NEGATE CURLFNM_CHARSET_LEN + +#define CURLFNM_ALNUM (CURLFNM_CHARSET_LEN + 1) +#define CURLFNM_DIGIT (CURLFNM_CHARSET_LEN + 2) +#define CURLFNM_XDIGIT (CURLFNM_CHARSET_LEN + 3) +#define CURLFNM_ALPHA (CURLFNM_CHARSET_LEN + 4) +#define CURLFNM_PRINT (CURLFNM_CHARSET_LEN + 5) +#define CURLFNM_BLANK (CURLFNM_CHARSET_LEN + 6) +#define CURLFNM_LOWER (CURLFNM_CHARSET_LEN + 7) +#define CURLFNM_GRAPH (CURLFNM_CHARSET_LEN + 8) +#define CURLFNM_SPACE (CURLFNM_CHARSET_LEN + 9) +#define CURLFNM_UPPER (CURLFNM_CHARSET_LEN + 10) + +typedef enum { + CURLFNM_SCHS_DEFAULT = 0, + CURLFNM_SCHS_RIGHTBR, + CURLFNM_SCHS_RIGHTBRLEFTBR +} setcharset_state; + +typedef enum { + CURLFNM_PKW_INIT = 0, + CURLFNM_PKW_DDOT +} parsekey_state; + +typedef enum { + CCLASS_OTHER = 0, + CCLASS_DIGIT, + CCLASS_UPPER, + CCLASS_LOWER +} char_class; + +#define SETCHARSET_OK 1 +#define SETCHARSET_FAIL 0 + +static int parsekeyword(unsigned char **pattern, unsigned char *charset) +{ + parsekey_state state = CURLFNM_PKW_INIT; +#define KEYLEN 10 + char keyword[KEYLEN] = { 0 }; + int i; + unsigned char *p = *pattern; + bool found = FALSE; + for(i = 0; !found; i++) { + char c = *p++; + if(i >= KEYLEN) + return SETCHARSET_FAIL; + switch(state) { + case CURLFNM_PKW_INIT: + if(ISLOWER(c)) + keyword[i] = c; + else if(c == ':') + state = CURLFNM_PKW_DDOT; + else + return SETCHARSET_FAIL; + break; + case CURLFNM_PKW_DDOT: + if(c == ']') + found = TRUE; + else + return SETCHARSET_FAIL; + } + } +#undef KEYLEN + + *pattern = p; /* move caller's pattern pointer */ + if(strcmp(keyword, "digit") == 0) + charset[CURLFNM_DIGIT] = 1; + else if(strcmp(keyword, "alnum") == 0) + charset[CURLFNM_ALNUM] = 1; + else if(strcmp(keyword, "alpha") == 0) + charset[CURLFNM_ALPHA] = 1; + else if(strcmp(keyword, "xdigit") == 0) + charset[CURLFNM_XDIGIT] = 1; + else if(strcmp(keyword, "print") == 0) + charset[CURLFNM_PRINT] = 1; + else if(strcmp(keyword, "graph") == 0) + charset[CURLFNM_GRAPH] = 1; + else if(strcmp(keyword, "space") == 0) + charset[CURLFNM_SPACE] = 1; + else if(strcmp(keyword, "blank") == 0) + charset[CURLFNM_BLANK] = 1; + else if(strcmp(keyword, "upper") == 0) + charset[CURLFNM_UPPER] = 1; + else if(strcmp(keyword, "lower") == 0) + charset[CURLFNM_LOWER] = 1; + else + return SETCHARSET_FAIL; + return SETCHARSET_OK; +} + +/* Return the character class. */ +static char_class charclass(unsigned char c) +{ + if(ISUPPER(c)) + return CCLASS_UPPER; + if(ISLOWER(c)) + return CCLASS_LOWER; + if(ISDIGIT(c)) + return CCLASS_DIGIT; + return CCLASS_OTHER; +} + +/* Include a character or a range in set. */ +static void setcharorrange(unsigned char **pp, unsigned char *charset) +{ + unsigned char *p = (*pp)++; + unsigned char c = *p++; + + charset[c] = 1; + if(ISALNUM(c) && *p++ == '-') { + char_class cc = charclass(c); + unsigned char endrange = *p++; + + if(endrange == '\\') + endrange = *p++; + if(endrange >= c && charclass(endrange) == cc) { + while(c++ != endrange) + if(charclass(c) == cc) /* Chars in class may be not consecutive. */ + charset[c] = 1; + *pp = p; + } + } +} + +/* returns 1 (true) if pattern is OK, 0 if is bad ("p" is pattern pointer) */ +static int setcharset(unsigned char **p, unsigned char *charset) +{ + setcharset_state state = CURLFNM_SCHS_DEFAULT; + bool something_found = FALSE; + unsigned char c; + + memset(charset, 0, CURLFNM_CHSET_SIZE); + for(;;) { + c = **p; + if(!c) + return SETCHARSET_FAIL; + + switch(state) { + case CURLFNM_SCHS_DEFAULT: + if(c == ']') { + if(something_found) + return SETCHARSET_OK; + something_found = TRUE; + state = CURLFNM_SCHS_RIGHTBR; + charset[c] = 1; + (*p)++; + } + else if(c == '[') { + unsigned char *pp = *p + 1; + + if(*pp++ == ':' && parsekeyword(&pp, charset)) + *p = pp; + else { + charset[c] = 1; + (*p)++; + } + something_found = TRUE; + } + else if(c == '^' || c == '!') { + if(!something_found) { + if(charset[CURLFNM_NEGATE]) { + charset[c] = 1; + something_found = TRUE; + } + else + charset[CURLFNM_NEGATE] = 1; /* negate charset */ + } + else + charset[c] = 1; + (*p)++; + } + else if(c == '\\') { + c = *(++(*p)); + if(c) + setcharorrange(p, charset); + else + charset['\\'] = 1; + something_found = TRUE; + } + else { + setcharorrange(p, charset); + something_found = TRUE; + } + break; + case CURLFNM_SCHS_RIGHTBR: + if(c == '[') { + state = CURLFNM_SCHS_RIGHTBRLEFTBR; + charset[c] = 1; + (*p)++; + } + else if(c == ']') { + return SETCHARSET_OK; + } + else if(ISPRINT(c)) { + charset[c] = 1; + (*p)++; + state = CURLFNM_SCHS_DEFAULT; + } + else + /* used 'goto fail' instead of 'return SETCHARSET_FAIL' to avoid a + * nonsense warning 'statement not reached' at end of the fnc when + * compiling on Solaris */ + goto fail; + break; + case CURLFNM_SCHS_RIGHTBRLEFTBR: + if(c == ']') + return SETCHARSET_OK; + state = CURLFNM_SCHS_DEFAULT; + charset[c] = 1; + (*p)++; + break; + } + } +fail: + return SETCHARSET_FAIL; +} + +static int loop(const unsigned char *pattern, const unsigned char *string, + int maxstars) +{ + unsigned char *p = (unsigned char *)pattern; + unsigned char *s = (unsigned char *)string; + unsigned char charset[CURLFNM_CHSET_SIZE] = { 0 }; + + for(;;) { + unsigned char *pp; + + switch(*p) { + case '*': + if(!maxstars) + return CURL_FNMATCH_NOMATCH; + /* Regroup consecutive stars and question marks. This can be done because + '*?*?*' can be expressed as '??*'. */ + for(;;) { + if(*++p == '\0') + return CURL_FNMATCH_MATCH; + if(*p == '?') { + if(!*s++) + return CURL_FNMATCH_NOMATCH; + } + else if(*p != '*') + break; + } + /* Skip string characters until we find a match with pattern suffix. */ + for(maxstars--; *s; s++) { + if(loop(p, s, maxstars) == CURL_FNMATCH_MATCH) + return CURL_FNMATCH_MATCH; + } + return CURL_FNMATCH_NOMATCH; + case '?': + if(!*s) + return CURL_FNMATCH_NOMATCH; + s++; + p++; + break; + case '\0': + return *s? CURL_FNMATCH_NOMATCH: CURL_FNMATCH_MATCH; + case '\\': + if(p[1]) + p++; + if(*s++ != *p++) + return CURL_FNMATCH_NOMATCH; + break; + case '[': + pp = p + 1; /* Copy in case of syntax error in set. */ + if(setcharset(&pp, charset)) { + int found = FALSE; + if(!*s) + return CURL_FNMATCH_NOMATCH; + if(charset[(unsigned int)*s]) + found = TRUE; + else if(charset[CURLFNM_ALNUM]) + found = ISALNUM(*s); + else if(charset[CURLFNM_ALPHA]) + found = ISALPHA(*s); + else if(charset[CURLFNM_DIGIT]) + found = ISDIGIT(*s); + else if(charset[CURLFNM_XDIGIT]) + found = ISXDIGIT(*s); + else if(charset[CURLFNM_PRINT]) + found = ISPRINT(*s); + else if(charset[CURLFNM_SPACE]) + found = ISSPACE(*s); + else if(charset[CURLFNM_UPPER]) + found = ISUPPER(*s); + else if(charset[CURLFNM_LOWER]) + found = ISLOWER(*s); + else if(charset[CURLFNM_BLANK]) + found = ISBLANK(*s); + else if(charset[CURLFNM_GRAPH]) + found = ISGRAPH(*s); + + if(charset[CURLFNM_NEGATE]) + found = !found; + + if(!found) + return CURL_FNMATCH_NOMATCH; + p = pp + 1; + s++; + break; + } + /* Syntax error in set; mismatch! */ + return CURL_FNMATCH_NOMATCH; + + default: + if(*p++ != *s++) + return CURL_FNMATCH_NOMATCH; + break; + } + } +} + +/* + * @unittest: 1307 + */ +int Curl_fnmatch(void *ptr, const char *pattern, const char *string) +{ + (void)ptr; /* the argument is specified by the curl_fnmatch_callback + prototype, but not used by Curl_fnmatch() */ + if(!pattern || !string) { + return CURL_FNMATCH_FAIL; + } + return loop((unsigned char *)pattern, (unsigned char *)string, 2); +} +#else +#include +/* + * @unittest: 1307 + */ +int Curl_fnmatch(void *ptr, const char *pattern, const char *string) +{ + (void)ptr; /* the argument is specified by the curl_fnmatch_callback + prototype, but not used by Curl_fnmatch() */ + if(!pattern || !string) { + return CURL_FNMATCH_FAIL; + } + + switch(fnmatch(pattern, string, 0)) { + case 0: + return CURL_FNMATCH_MATCH; + case FNM_NOMATCH: + return CURL_FNMATCH_NOMATCH; + default: + return CURL_FNMATCH_FAIL; + } + /* not reached */ +} + +#endif + +#endif /* if FTP is disabled */ diff --git a/third_party/curl/lib/curl_fnmatch.h b/third_party/curl/lib/curl_fnmatch.h new file mode 100644 index 0000000..595646f --- /dev/null +++ b/third_party/curl/lib/curl_fnmatch.h @@ -0,0 +1,46 @@ +#ifndef HEADER_CURL_FNMATCH_H +#define HEADER_CURL_FNMATCH_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#define CURL_FNMATCH_MATCH 0 +#define CURL_FNMATCH_NOMATCH 1 +#define CURL_FNMATCH_FAIL 2 + +/* default pattern matching function + * ================================= + * Implemented with recursive backtracking, if you want to use Curl_fnmatch, + * please note that there is not implemented UTF/UNICODE support. + * + * Implemented features: + * '?' notation, does not match UTF characters + * '*' can also work with UTF string + * [a-zA-Z0-9] enumeration support + * + * keywords: alnum, digit, xdigit, alpha, print, blank, lower, graph, space + * and upper (use as "[[:alnum:]]") + */ +int Curl_fnmatch(void *ptr, const char *pattern, const char *string); + +#endif /* HEADER_CURL_FNMATCH_H */ diff --git a/third_party/curl/lib/curl_get_line.c b/third_party/curl/lib/curl_get_line.c new file mode 100644 index 0000000..1002073 --- /dev/null +++ b/third_party/curl/lib/curl_get_line.c @@ -0,0 +1,77 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_COOKIES) || !defined(CURL_DISABLE_ALTSVC) || \ + !defined(CURL_DISABLE_HSTS) || !defined(CURL_DISABLE_NETRC) + +#include "curl_get_line.h" +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + +/* + * Curl_get_line() makes sure to only return complete whole lines that end + * newlines. + */ +int Curl_get_line(struct dynbuf *buf, FILE *input) +{ + CURLcode result; + char buffer[128]; + Curl_dyn_reset(buf); + while(1) { + char *b = fgets(buffer, sizeof(buffer), input); + + if(b) { + size_t rlen = strlen(b); + + if(!rlen) + break; + + result = Curl_dyn_addn(buf, b, rlen); + if(result) + /* too long line or out of memory */ + return 0; /* error */ + + else if(b[rlen-1] == '\n') + /* end of the line */ + return 1; /* all good */ + + else if(feof(input)) { + /* append a newline */ + result = Curl_dyn_addn(buf, "\n", 1); + if(result) + /* too long line or out of memory */ + return 0; /* error */ + return 1; /* all good */ + } + } + else + break; + } + return 0; +} + +#endif /* if not disabled */ diff --git a/third_party/curl/lib/curl_get_line.h b/third_party/curl/lib/curl_get_line.h new file mode 100644 index 0000000..7907cde --- /dev/null +++ b/third_party/curl/lib/curl_get_line.h @@ -0,0 +1,32 @@ +#ifndef HEADER_CURL_GET_LINE_H +#define HEADER_CURL_GET_LINE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "dynbuf.h" + +/* Curl_get_line() returns complete lines that end with a newline. */ +int Curl_get_line(struct dynbuf *buf, FILE *input); + +#endif /* HEADER_CURL_GET_LINE_H */ diff --git a/third_party/curl/lib/curl_gethostname.c b/third_party/curl/lib/curl_gethostname.c new file mode 100644 index 0000000..bd9b220 --- /dev/null +++ b/third_party/curl/lib/curl_gethostname.c @@ -0,0 +1,102 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "curl_gethostname.h" + +/* + * Curl_gethostname() is a wrapper around gethostname() which allows + * overriding the host name that the function would normally return. + * This capability is used by the test suite to verify exact matching + * of NTLM authentication, which exercises libcurl's MD4 and DES code + * as well as by the SMTP module when a hostname is not provided. + * + * For libcurl debug enabled builds host name overriding takes place + * when environment variable CURL_GETHOSTNAME is set, using the value + * held by the variable to override returned host name. + * + * Note: The function always returns the un-qualified hostname rather + * than being provider dependent. + * + * For libcurl shared library release builds the test suite preloads + * another shared library named libhostname using the LD_PRELOAD + * mechanism which intercepts, and might override, the gethostname() + * function call. In this case a given platform must support the + * LD_PRELOAD mechanism and additionally have environment variable + * CURL_GETHOSTNAME set in order to override the returned host name. + * + * For libcurl static library release builds no overriding takes place. + */ + +int Curl_gethostname(char * const name, GETHOSTNAME_TYPE_ARG2 namelen) +{ +#ifndef HAVE_GETHOSTNAME + + /* Allow compilation and return failure when unavailable */ + (void) name; + (void) namelen; + return -1; + +#else + int err; + char *dot; + +#ifdef DEBUGBUILD + + /* Override host name when environment variable CURL_GETHOSTNAME is set */ + const char *force_hostname = getenv("CURL_GETHOSTNAME"); + if(force_hostname) { + strncpy(name, force_hostname, namelen - 1); + err = 0; + } + else { + name[0] = '\0'; + err = gethostname(name, namelen); + } + +#else /* DEBUGBUILD */ + + /* The call to system's gethostname() might get intercepted by the + libhostname library when libcurl is built as a non-debug shared + library when running the test suite. */ + name[0] = '\0'; + err = gethostname(name, namelen); + +#endif + + name[namelen - 1] = '\0'; + + if(err) + return err; + + /* Truncate domain, leave only machine name */ + dot = strchr(name, '.'); + if(dot) + *dot = '\0'; + + return 0; +#endif + +} diff --git a/third_party/curl/lib/curl_gethostname.h b/third_party/curl/lib/curl_gethostname.h new file mode 100644 index 0000000..9281d9c --- /dev/null +++ b/third_party/curl/lib/curl_gethostname.h @@ -0,0 +1,33 @@ +#ifndef HEADER_CURL_GETHOSTNAME_H +#define HEADER_CURL_GETHOSTNAME_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* Hostname buffer size */ +#define HOSTNAME_MAX 1024 + +/* This returns the local machine's un-qualified hostname */ +int Curl_gethostname(char * const name, GETHOSTNAME_TYPE_ARG2 namelen); + +#endif /* HEADER_CURL_GETHOSTNAME_H */ diff --git a/third_party/curl/lib/curl_gssapi.c b/third_party/curl/lib/curl_gssapi.c new file mode 100644 index 0000000..c6fe125 --- /dev/null +++ b/third_party/curl/lib/curl_gssapi.c @@ -0,0 +1,152 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_GSSAPI + +#include "curl_gssapi.h" +#include "sendf.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if defined(__GNUC__) +#define CURL_ALIGN8 __attribute__ ((aligned(8))) +#else +#define CURL_ALIGN8 +#endif + +gss_OID_desc Curl_spnego_mech_oid CURL_ALIGN8 = { + 6, (char *)"\x2b\x06\x01\x05\x05\x02" +}; +gss_OID_desc Curl_krb5_mech_oid CURL_ALIGN8 = { + 9, (char *)"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02" +}; + +OM_uint32 Curl_gss_init_sec_context( + struct Curl_easy *data, + OM_uint32 *minor_status, + gss_ctx_id_t *context, + gss_name_t target_name, + gss_OID mech_type, + gss_channel_bindings_t input_chan_bindings, + gss_buffer_t input_token, + gss_buffer_t output_token, + const bool mutual_auth, + OM_uint32 *ret_flags) +{ + OM_uint32 req_flags = GSS_C_REPLAY_FLAG; + + if(mutual_auth) + req_flags |= GSS_C_MUTUAL_FLAG; + + if(data->set.gssapi_delegation & CURLGSSAPI_DELEGATION_POLICY_FLAG) { +#ifdef GSS_C_DELEG_POLICY_FLAG + req_flags |= GSS_C_DELEG_POLICY_FLAG; +#else + infof(data, "WARNING: support for CURLGSSAPI_DELEGATION_POLICY_FLAG not " + "compiled in"); +#endif + } + + if(data->set.gssapi_delegation & CURLGSSAPI_DELEGATION_FLAG) + req_flags |= GSS_C_DELEG_FLAG; + + return gss_init_sec_context(minor_status, + GSS_C_NO_CREDENTIAL, /* cred_handle */ + context, + target_name, + mech_type, + req_flags, + 0, /* time_req */ + input_chan_bindings, + input_token, + NULL, /* actual_mech_type */ + output_token, + ret_flags, + NULL /* time_rec */); +} + +#define GSS_LOG_BUFFER_LEN 1024 +static size_t display_gss_error(OM_uint32 status, int type, + char *buf, size_t len) { + OM_uint32 maj_stat; + OM_uint32 min_stat; + OM_uint32 msg_ctx = 0; + gss_buffer_desc status_string = GSS_C_EMPTY_BUFFER; + + do { + maj_stat = gss_display_status(&min_stat, + status, + type, + GSS_C_NO_OID, + &msg_ctx, + &status_string); + if(maj_stat == GSS_S_COMPLETE && status_string.length > 0) { + if(GSS_LOG_BUFFER_LEN > len + status_string.length + 3) { + len += msnprintf(buf + len, GSS_LOG_BUFFER_LEN - len, + "%.*s. ", (int)status_string.length, + (char *)status_string.value); + } + } + gss_release_buffer(&min_stat, &status_string); + } while(!GSS_ERROR(maj_stat) && msg_ctx); + + return len; +} + +/* + * Curl_gss_log_error() + * + * This is used to log a GSS-API error status. + * + * Parameters: + * + * data [in] - The session handle. + * prefix [in] - The prefix of the log message. + * major [in] - The major status code. + * minor [in] - The minor status code. + */ +void Curl_gss_log_error(struct Curl_easy *data, const char *prefix, + OM_uint32 major, OM_uint32 minor) +{ + char buf[GSS_LOG_BUFFER_LEN]; + size_t len = 0; + + if(major != GSS_S_FAILURE) + len = display_gss_error(major, GSS_C_GSS_CODE, buf, len); + + display_gss_error(minor, GSS_C_MECH_CODE, buf, len); + + infof(data, "%s%s", prefix, buf); +#ifdef CURL_DISABLE_VERBOSE_STRINGS + (void)data; + (void)prefix; +#endif +} + +#endif /* HAVE_GSSAPI */ diff --git a/third_party/curl/lib/curl_gssapi.h b/third_party/curl/lib/curl_gssapi.h new file mode 100644 index 0000000..7b9a534 --- /dev/null +++ b/third_party/curl/lib/curl_gssapi.h @@ -0,0 +1,63 @@ +#ifndef HEADER_CURL_GSSAPI_H +#define HEADER_CURL_GSSAPI_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "urldata.h" + +#ifdef HAVE_GSSAPI +extern gss_OID_desc Curl_spnego_mech_oid; +extern gss_OID_desc Curl_krb5_mech_oid; + +/* Common method for using GSS-API */ +OM_uint32 Curl_gss_init_sec_context( + struct Curl_easy *data, + OM_uint32 *minor_status, + gss_ctx_id_t *context, + gss_name_t target_name, + gss_OID mech_type, + gss_channel_bindings_t input_chan_bindings, + gss_buffer_t input_token, + gss_buffer_t output_token, + const bool mutual_auth, + OM_uint32 *ret_flags); + +/* Helper to log a GSS-API error status */ +void Curl_gss_log_error(struct Curl_easy *data, const char *prefix, + OM_uint32 major, OM_uint32 minor); + +/* Provide some definitions missing in old headers */ +#ifdef HAVE_OLD_GSSMIT +#define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name +#define NCOMPAT 1 +#endif + +/* Define our privacy and integrity protection values */ +#define GSSAUTH_P_NONE 1 +#define GSSAUTH_P_INTEGRITY 2 +#define GSSAUTH_P_PRIVACY 4 + +#endif /* HAVE_GSSAPI */ +#endif /* HEADER_CURL_GSSAPI_H */ diff --git a/third_party/curl/lib/curl_hmac.h b/third_party/curl/lib/curl_hmac.h new file mode 100644 index 0000000..7a5387a --- /dev/null +++ b/third_party/curl/lib/curl_hmac.h @@ -0,0 +1,78 @@ +#ifndef HEADER_CURL_HMAC_H +#define HEADER_CURL_HMAC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#if (defined(USE_CURL_NTLM_CORE) && !defined(USE_WINDOWS_SSPI)) \ + || !defined(CURL_DISABLE_AWS) || !defined(CURL_DISABLE_DIGEST_AUTH) \ + || defined(USE_LIBSSH2) + +#include + +#define HMAC_MD5_LENGTH 16 + +typedef CURLcode (* HMAC_hinit_func)(void *context); +typedef void (* HMAC_hupdate_func)(void *context, + const unsigned char *data, + unsigned int len); +typedef void (* HMAC_hfinal_func)(unsigned char *result, void *context); + + +/* Per-hash function HMAC parameters. */ +struct HMAC_params { + HMAC_hinit_func + hmac_hinit; /* Initialize context procedure. */ + HMAC_hupdate_func hmac_hupdate; /* Update context with data. */ + HMAC_hfinal_func hmac_hfinal; /* Get final result procedure. */ + unsigned int hmac_ctxtsize; /* Context structure size. */ + unsigned int hmac_maxkeylen; /* Maximum key length (bytes). */ + unsigned int hmac_resultlen; /* Result length (bytes). */ +}; + + +/* HMAC computation context. */ +struct HMAC_context { + const struct HMAC_params *hmac_hash; /* Hash function definition. */ + void *hmac_hashctxt1; /* Hash function context 1. */ + void *hmac_hashctxt2; /* Hash function context 2. */ +}; + + +/* Prototypes. */ +struct HMAC_context *Curl_HMAC_init(const struct HMAC_params *hashparams, + const unsigned char *key, + unsigned int keylen); +int Curl_HMAC_update(struct HMAC_context *context, + const unsigned char *data, + unsigned int len); +int Curl_HMAC_final(struct HMAC_context *context, unsigned char *result); + +CURLcode Curl_hmacit(const struct HMAC_params *hashparams, + const unsigned char *key, const size_t keylen, + const unsigned char *data, const size_t datalen, + unsigned char *output); + +#endif + +#endif /* HEADER_CURL_HMAC_H */ diff --git a/third_party/curl/lib/curl_krb5.h b/third_party/curl/lib/curl_krb5.h new file mode 100644 index 0000000..ccf6b96 --- /dev/null +++ b/third_party/curl/lib/curl_krb5.h @@ -0,0 +1,52 @@ +#ifndef HEADER_CURL_KRB5_H +#define HEADER_CURL_KRB5_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +struct Curl_sec_client_mech { + const char *name; + size_t size; + int (*init)(void *); + int (*auth)(void *, struct Curl_easy *data, struct connectdata *); + void (*end)(void *); + int (*check_prot)(void *, int); + int (*encode)(void *, const void *, int, int, void **); + int (*decode)(void *, void *, int, int, struct connectdata *); +}; + +#define AUTH_OK 0 +#define AUTH_CONTINUE 1 +#define AUTH_ERROR 2 + +#ifdef HAVE_GSSAPI +int Curl_sec_read_msg(struct Curl_easy *data, struct connectdata *conn, char *, + enum protection_level); +void Curl_sec_end(struct connectdata *); +CURLcode Curl_sec_login(struct Curl_easy *, struct connectdata *); +int Curl_sec_request_prot(struct connectdata *conn, const char *level); +#else +#define Curl_sec_end(x) +#endif + +#endif /* HEADER_CURL_KRB5_H */ diff --git a/third_party/curl/lib/curl_ldap.h b/third_party/curl/lib/curl_ldap.h new file mode 100644 index 0000000..8a1d807 --- /dev/null +++ b/third_party/curl/lib/curl_ldap.h @@ -0,0 +1,36 @@ +#ifndef HEADER_CURL_LDAP_H +#define HEADER_CURL_LDAP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifndef CURL_DISABLE_LDAP +extern const struct Curl_handler Curl_handler_ldap; + +#if !defined(CURL_DISABLE_LDAPS) && \ + ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \ + (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL))) +extern const struct Curl_handler Curl_handler_ldaps; +#endif + +#endif +#endif /* HEADER_CURL_LDAP_H */ diff --git a/third_party/curl/lib/curl_md4.h b/third_party/curl/lib/curl_md4.h new file mode 100644 index 0000000..4706e49 --- /dev/null +++ b/third_party/curl/lib/curl_md4.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_MD4_H +#define HEADER_CURL_MD4_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include + +#if defined(USE_CURL_NTLM_CORE) + +#define MD4_DIGEST_LENGTH 16 + +CURLcode Curl_md4it(unsigned char *output, const unsigned char *input, + const size_t len); + +#endif /* defined(USE_CURL_NTLM_CORE) */ + +#endif /* HEADER_CURL_MD4_H */ diff --git a/third_party/curl/lib/curl_md5.h b/third_party/curl/lib/curl_md5.h new file mode 100644 index 0000000..61671c3 --- /dev/null +++ b/third_party/curl/lib/curl_md5.h @@ -0,0 +1,67 @@ +#ifndef HEADER_CURL_MD5_H +#define HEADER_CURL_MD5_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#if (defined(USE_CURL_NTLM_CORE) && !defined(USE_WINDOWS_SSPI)) \ + || !defined(CURL_DISABLE_DIGEST_AUTH) + +#include "curl_hmac.h" + +#define MD5_DIGEST_LEN 16 + +typedef CURLcode (* Curl_MD5_init_func)(void *context); +typedef void (* Curl_MD5_update_func)(void *context, + const unsigned char *data, + unsigned int len); +typedef void (* Curl_MD5_final_func)(unsigned char *result, void *context); + +struct MD5_params { + Curl_MD5_init_func md5_init_func; /* Initialize context procedure */ + Curl_MD5_update_func md5_update_func; /* Update context with data */ + Curl_MD5_final_func md5_final_func; /* Get final result procedure */ + unsigned int md5_ctxtsize; /* Context structure size */ + unsigned int md5_resultlen; /* Result length (bytes) */ +}; + +struct MD5_context { + const struct MD5_params *md5_hash; /* Hash function definition */ + void *md5_hashctx; /* Hash function context */ +}; + +extern const struct MD5_params Curl_DIGEST_MD5[1]; +extern const struct HMAC_params Curl_HMAC_MD5[1]; + +CURLcode Curl_md5it(unsigned char *output, const unsigned char *input, + const size_t len); + +struct MD5_context *Curl_MD5_init(const struct MD5_params *md5params); +CURLcode Curl_MD5_update(struct MD5_context *context, + const unsigned char *data, + unsigned int len); +CURLcode Curl_MD5_final(struct MD5_context *context, unsigned char *result); + +#endif + +#endif /* HEADER_CURL_MD5_H */ diff --git a/third_party/curl/lib/curl_memory.h b/third_party/curl/lib/curl_memory.h new file mode 100644 index 0000000..714ad71 --- /dev/null +++ b/third_party/curl/lib/curl_memory.h @@ -0,0 +1,178 @@ +#ifndef HEADER_CURL_MEMORY_H +#define HEADER_CURL_MEMORY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Nasty internal details ahead... + * + * File curl_memory.h must be included by _all_ *.c source files + * that use memory related functions strdup, malloc, calloc, realloc + * or free, and given source file is used to build libcurl library. + * It should be included immediately before memdebug.h as the last files + * included to avoid undesired interaction with other memory function + * headers in dependent libraries. + * + * There is nearly no exception to above rule. All libcurl source + * files in 'lib' subdirectory as well as those living deep inside + * 'packages' subdirectories and linked together in order to build + * libcurl library shall follow it. + * + * File lib/strdup.c is an exception, given that it provides a strdup + * clone implementation while using malloc. Extra care needed inside + * this one. + * + * The need for curl_memory.h inclusion is due to libcurl's feature + * of allowing library user to provide memory replacement functions, + * memory callbacks, at runtime with curl_global_init_mem() + * + * Any *.c source file used to build libcurl library that does not + * include curl_memory.h and uses any memory function of the five + * mentioned above will compile without any indication, but it will + * trigger weird memory related issues at runtime. + * + */ + +#ifdef HEADER_CURL_MEMDEBUG_H +/* cleanup after memdebug.h */ + +#ifdef MEMDEBUG_NODEFINES +#ifdef CURLDEBUG + +#undef strdup +#undef malloc +#undef calloc +#undef realloc +#undef free +#undef send +#undef recv + +#ifdef _WIN32 +# ifdef UNICODE +# undef wcsdup +# undef _wcsdup +# undef _tcsdup +# else +# undef _tcsdup +# endif +#endif + +#undef socket +#undef accept +#ifdef HAVE_SOCKETPAIR +#undef socketpair +#endif + +#ifdef HAVE_GETADDRINFO +#if defined(getaddrinfo) && defined(__osf__) +#undef ogetaddrinfo +#else +#undef getaddrinfo +#endif +#endif /* HAVE_GETADDRINFO */ + +#ifdef HAVE_FREEADDRINFO +#undef freeaddrinfo +#endif /* HAVE_FREEADDRINFO */ + +/* sclose is probably already defined, redefine it! */ +#undef sclose +#undef fopen +#undef fdopen +#undef fclose + +#endif /* MEMDEBUG_NODEFINES */ +#endif /* CURLDEBUG */ + +#undef HEADER_CURL_MEMDEBUG_H +#endif /* HEADER_CURL_MEMDEBUG_H */ + +/* +** Following section applies even when CURLDEBUG is not defined. +*/ + +#undef fake_sclose + +#ifndef CURL_DID_MEMORY_FUNC_TYPEDEFS /* only if not already done */ +/* + * The following memory function replacement typedef's are COPIED from + * curl/curl.h and MUST match the originals. We copy them to avoid having to + * include curl/curl.h here. We avoid that include since it includes stdio.h + * and other headers that may get messed up with defines done here. + */ +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 + +extern curl_malloc_callback Curl_cmalloc; +extern curl_free_callback Curl_cfree; +extern curl_realloc_callback Curl_crealloc; +extern curl_strdup_callback Curl_cstrdup; +extern curl_calloc_callback Curl_ccalloc; +#if defined(_WIN32) && defined(UNICODE) +extern curl_wcsdup_callback Curl_cwcsdup; +#endif + +#ifndef CURLDEBUG + +/* + * libcurl's 'memory tracking' system defines strdup, malloc, calloc, + * realloc and free, along with others, in memdebug.h in a different + * way although still using memory callbacks forward declared above. + * When using the 'memory tracking' system (CURLDEBUG defined) we do + * not define here the five memory functions given that definitions + * from memdebug.h are the ones that shall be used. + */ + +#undef strdup +#define strdup(ptr) Curl_cstrdup(ptr) +#undef malloc +#define malloc(size) Curl_cmalloc(size) +#undef calloc +#define calloc(nbelem,size) Curl_ccalloc(nbelem, size) +#undef realloc +#define realloc(ptr,size) Curl_crealloc(ptr, size) +#undef free +#define free(ptr) Curl_cfree(ptr) + +#ifdef _WIN32 +# ifdef UNICODE +# undef wcsdup +# define wcsdup(ptr) Curl_cwcsdup(ptr) +# undef _wcsdup +# define _wcsdup(ptr) Curl_cwcsdup(ptr) +# undef _tcsdup +# define _tcsdup(ptr) Curl_cwcsdup(ptr) +# else +# undef _tcsdup +# define _tcsdup(ptr) Curl_cstrdup(ptr) +# endif +#endif + +#endif /* CURLDEBUG */ +#endif /* HEADER_CURL_MEMORY_H */ diff --git a/third_party/curl/lib/curl_memrchr.c b/third_party/curl/lib/curl_memrchr.c new file mode 100644 index 0000000..3f3dc6d --- /dev/null +++ b/third_party/curl/lib/curl_memrchr.c @@ -0,0 +1,64 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "curl_memrchr.h" +#include "curl_memory.h" + +/* The last #include file should be: */ +#include "memdebug.h" + +#ifndef HAVE_MEMRCHR + +/* + * Curl_memrchr() + * + * Our memrchr() function clone for systems which lack this function. The + * memrchr() function is like the memchr() function, except that it searches + * backwards from the end of the n bytes pointed to by s instead of forward + * from the beginning. + */ + +void * +Curl_memrchr(const void *s, int c, size_t n) +{ + if(n > 0) { + const unsigned char *p = s; + const unsigned char *q = s; + + p += n - 1; + + while(p >= q) { + if(*p == (unsigned char)c) + return (void *)p; + p--; + } + } + return NULL; +} + +#endif /* HAVE_MEMRCHR */ diff --git a/third_party/curl/lib/curl_memrchr.h b/third_party/curl/lib/curl_memrchr.h new file mode 100644 index 0000000..45bb38c --- /dev/null +++ b/third_party/curl/lib/curl_memrchr.h @@ -0,0 +1,44 @@ +#ifndef HEADER_CURL_MEMRCHR_H +#define HEADER_CURL_MEMRCHR_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_MEMRCHR + +#include +#ifdef HAVE_STRINGS_H +# include +#endif + +#else /* HAVE_MEMRCHR */ + +void *Curl_memrchr(const void *s, int c, size_t n); + +#define memrchr(x,y,z) Curl_memrchr((x),(y),(z)) + +#endif /* HAVE_MEMRCHR */ + +#endif /* HEADER_CURL_MEMRCHR_H */ diff --git a/third_party/curl/lib/curl_multibyte.c b/third_party/curl/lib/curl_multibyte.c new file mode 100644 index 0000000..86ac74f --- /dev/null +++ b/third_party/curl/lib/curl_multibyte.c @@ -0,0 +1,162 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * This file is 'mem-include-scan' clean, which means memdebug.h and + * curl_memory.h are purposely not included in this file. See test 1132. + * + * The functions in this file are curlx functions which are not tracked by the + * curl memory tracker memdebug. + */ + +#include "curl_setup.h" + +#if defined(_WIN32) + +#include "curl_multibyte.h" + +/* + * MultiByte conversions using Windows kernel32 library. + */ + +wchar_t *curlx_convert_UTF8_to_wchar(const char *str_utf8) +{ + wchar_t *str_w = NULL; + + if(str_utf8) { + int str_w_len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, + str_utf8, -1, NULL, 0); + if(str_w_len > 0) { + str_w = malloc(str_w_len * sizeof(wchar_t)); + if(str_w) { + if(MultiByteToWideChar(CP_UTF8, 0, str_utf8, -1, str_w, + str_w_len) == 0) { + free(str_w); + return NULL; + } + } + } + } + + return str_w; +} + +char *curlx_convert_wchar_to_UTF8(const wchar_t *str_w) +{ + char *str_utf8 = NULL; + + if(str_w) { + int bytes = WideCharToMultiByte(CP_UTF8, 0, str_w, -1, + NULL, 0, NULL, NULL); + if(bytes > 0) { + str_utf8 = malloc(bytes); + if(str_utf8) { + if(WideCharToMultiByte(CP_UTF8, 0, str_w, -1, str_utf8, bytes, + NULL, NULL) == 0) { + free(str_utf8); + return NULL; + } + } + } + } + + return str_utf8; +} + +#endif /* _WIN32 */ + +#if defined(USE_WIN32_LARGE_FILES) || defined(USE_WIN32_SMALL_FILES) + +int curlx_win32_open(const char *filename, int oflag, ...) +{ + int pmode = 0; + +#ifdef _UNICODE + int result = -1; + wchar_t *filename_w = curlx_convert_UTF8_to_wchar(filename); +#endif + + va_list param; + va_start(param, oflag); + if(oflag & O_CREAT) + pmode = va_arg(param, int); + va_end(param); + +#ifdef _UNICODE + if(filename_w) { + result = _wopen(filename_w, oflag, pmode); + curlx_unicodefree(filename_w); + } + else + errno = EINVAL; + return result; +#else + return (_open)(filename, oflag, pmode); +#endif +} + +FILE *curlx_win32_fopen(const char *filename, const char *mode) +{ +#ifdef _UNICODE + FILE *result = NULL; + wchar_t *filename_w = curlx_convert_UTF8_to_wchar(filename); + wchar_t *mode_w = curlx_convert_UTF8_to_wchar(mode); + if(filename_w && mode_w) + result = _wfopen(filename_w, mode_w); + else + errno = EINVAL; + curlx_unicodefree(filename_w); + curlx_unicodefree(mode_w); + return result; +#else + return (fopen)(filename, mode); +#endif +} + +int curlx_win32_stat(const char *path, struct_stat *buffer) +{ +#ifdef _UNICODE + int result = -1; + wchar_t *path_w = curlx_convert_UTF8_to_wchar(path); + if(path_w) { +#if defined(USE_WIN32_SMALL_FILES) + result = _wstat(path_w, buffer); +#else + result = _wstati64(path_w, buffer); +#endif + curlx_unicodefree(path_w); + } + else + errno = EINVAL; + return result; +#else +#if defined(USE_WIN32_SMALL_FILES) + return _stat(path, buffer); +#else + return _stati64(path, buffer); +#endif +#endif +} + +#endif /* USE_WIN32_LARGE_FILES || USE_WIN32_SMALL_FILES */ diff --git a/third_party/curl/lib/curl_multibyte.h b/third_party/curl/lib/curl_multibyte.h new file mode 100644 index 0000000..8b9ac71 --- /dev/null +++ b/third_party/curl/lib/curl_multibyte.h @@ -0,0 +1,91 @@ +#ifndef HEADER_CURL_MULTIBYTE_H +#define HEADER_CURL_MULTIBYTE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(_WIN32) + + /* + * MultiByte conversions using Windows kernel32 library. + */ + +wchar_t *curlx_convert_UTF8_to_wchar(const char *str_utf8); +char *curlx_convert_wchar_to_UTF8(const wchar_t *str_w); +#endif /* _WIN32 */ + +/* + * Macros curlx_convert_UTF8_to_tchar(), curlx_convert_tchar_to_UTF8() + * and curlx_unicodefree() main purpose is to minimize the number of + * preprocessor conditional directives needed by code using these + * to differentiate UNICODE from non-UNICODE builds. + * + * In the case of a non-UNICODE build the tchar strings are char strings that + * are duplicated via strdup and remain in whatever the passed in encoding is, + * which is assumed to be UTF-8 but may be other encoding. Therefore the + * significance of the conversion functions is primarily for UNICODE builds. + * + * Allocated memory should be free'd with curlx_unicodefree(). + * + * Note: Because these are curlx functions their memory usage is not tracked + * by the curl memory tracker memdebug. You'll notice that curlx function-like + * macros call free and strdup in parentheses, eg (strdup)(ptr), and that's to + * ensure that the curl memdebug override macros do not replace them. + */ + +#if defined(UNICODE) && defined(_WIN32) + +#define curlx_convert_UTF8_to_tchar(ptr) curlx_convert_UTF8_to_wchar((ptr)) +#define curlx_convert_tchar_to_UTF8(ptr) curlx_convert_wchar_to_UTF8((ptr)) + +typedef union { + unsigned short *tchar_ptr; + const unsigned short *const_tchar_ptr; + unsigned short *tbyte_ptr; + const unsigned short *const_tbyte_ptr; +} xcharp_u; + +#else + +#define curlx_convert_UTF8_to_tchar(ptr) (strdup)(ptr) +#define curlx_convert_tchar_to_UTF8(ptr) (strdup)(ptr) + +typedef union { + char *tchar_ptr; + const char *const_tchar_ptr; + unsigned char *tbyte_ptr; + const unsigned char *const_tbyte_ptr; +} xcharp_u; + +#endif /* UNICODE && _WIN32 */ + +#define curlx_unicodefree(ptr) \ + do { \ + if(ptr) { \ + (free)(ptr); \ + (ptr) = NULL; \ + } \ + } while(0) + +#endif /* HEADER_CURL_MULTIBYTE_H */ diff --git a/third_party/curl/lib/curl_ntlm_core.c b/third_party/curl/lib/curl_ntlm_core.c new file mode 100644 index 0000000..6f6d75c --- /dev/null +++ b/third_party/curl/lib/curl_ntlm_core.c @@ -0,0 +1,669 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_CURL_NTLM_CORE) + +/* + * NTLM details: + * + * https://davenport.sourceforge.net/ntlm.html + * https://www.innovation.ch/java/ntlm.html + */ + +/* Please keep the SSL backend-specific #if branches in this order: + + 1. USE_OPENSSL + 2. USE_WOLFSSL + 3. USE_GNUTLS + 4. - + 5. USE_MBEDTLS + 6. USE_SECTRANSP + 7. USE_OS400CRYPTO + 8. USE_WIN32_CRYPTO + + This ensures that: + - the same SSL branch gets activated throughout this source + file even if multiple backends are enabled at the same time. + - OpenSSL has higher priority than Windows Crypt, due + to issues with the latter supporting NTLM2Session responses + in NTLM type-3 messages. + */ + +#if defined(USE_OPENSSL) + #include + #if !defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_DEPRECATED_3_0) + #define USE_OPENSSL_DES + #endif +#endif + +#if defined(USE_OPENSSL_DES) || defined(USE_WOLFSSL) + +#if defined(USE_OPENSSL) +# include +# include +# include +# include +#else +# include +# include +# include +# include +# include +#endif + +# if (defined(OPENSSL_VERSION_NUMBER) && \ + (OPENSSL_VERSION_NUMBER < 0x00907001L)) && !defined(USE_WOLFSSL) +# define DES_key_schedule des_key_schedule +# define DES_cblock des_cblock +# define DES_set_odd_parity des_set_odd_parity +# define DES_set_key des_set_key +# define DES_ecb_encrypt des_ecb_encrypt +# define DESKEY(x) x +# define DESKEYARG(x) x +# elif defined(OPENSSL_IS_AWSLC) +# define DES_set_key_unchecked (void)DES_set_key +# define DESKEYARG(x) *x +# define DESKEY(x) &x +# else +# define DESKEYARG(x) *x +# define DESKEY(x) &x +# endif + +#elif defined(USE_GNUTLS) + +# include + +#elif defined(USE_MBEDTLS) + +# include + +#elif defined(USE_SECTRANSP) + +# include +# include + +#elif defined(USE_OS400CRYPTO) +# include "cipher.mih" /* mih/cipher */ +#elif defined(USE_WIN32_CRYPTO) +# include +#else +# error "Can't compile NTLM support without a crypto library with DES." +# define CURL_NTLM_NOT_SUPPORTED +#endif + +#include "urldata.h" +#include "strcase.h" +#include "curl_ntlm_core.h" +#include "curl_md5.h" +#include "curl_hmac.h" +#include "warnless.h" +#include "curl_endian.h" +#include "curl_des.h" +#include "curl_md4.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#define NTLMv2_BLOB_SIGNATURE "\x01\x01\x00\x00" +#define NTLMv2_BLOB_LEN (44 -16 + ntlm->target_info_len + 4) + +#if !defined(CURL_NTLM_NOT_SUPPORTED) +/* +* Turns a 56-bit key into being 64-bit wide. +*/ +static void extend_key_56_to_64(const unsigned char *key_56, char *key) +{ + key[0] = key_56[0]; + key[1] = (unsigned char)(((key_56[0] << 7) & 0xFF) | (key_56[1] >> 1)); + key[2] = (unsigned char)(((key_56[1] << 6) & 0xFF) | (key_56[2] >> 2)); + key[3] = (unsigned char)(((key_56[2] << 5) & 0xFF) | (key_56[3] >> 3)); + key[4] = (unsigned char)(((key_56[3] << 4) & 0xFF) | (key_56[4] >> 4)); + key[5] = (unsigned char)(((key_56[4] << 3) & 0xFF) | (key_56[5] >> 5)); + key[6] = (unsigned char)(((key_56[5] << 2) & 0xFF) | (key_56[6] >> 6)); + key[7] = (unsigned char) ((key_56[6] << 1) & 0xFF); +} +#endif + +#if defined(USE_OPENSSL_DES) || defined(USE_WOLFSSL) +/* + * Turns a 56 bit key into the 64 bit, odd parity key and sets the key. The + * key schedule ks is also set. + */ +static void setup_des_key(const unsigned char *key_56, + DES_key_schedule DESKEYARG(ks)) +{ + DES_cblock key; + + /* Expand the 56-bit key to 64-bits */ + extend_key_56_to_64(key_56, (char *) &key); + + /* Set the key parity to odd */ + DES_set_odd_parity(&key); + + /* Set the key */ + DES_set_key_unchecked(&key, ks); +} + +#elif defined(USE_GNUTLS) + +static void setup_des_key(const unsigned char *key_56, + struct des_ctx *des) +{ + char key[8]; + + /* Expand the 56-bit key to 64-bits */ + extend_key_56_to_64(key_56, key); + + /* Set the key parity to odd */ + Curl_des_set_odd_parity((unsigned char *) key, sizeof(key)); + + /* Set the key */ + des_set_key(des, (const uint8_t *) key); +} + +#elif defined(USE_MBEDTLS) + +static bool encrypt_des(const unsigned char *in, unsigned char *out, + const unsigned char *key_56) +{ + mbedtls_des_context ctx; + char key[8]; + + /* Expand the 56-bit key to 64-bits */ + extend_key_56_to_64(key_56, key); + + /* Set the key parity to odd */ + mbedtls_des_key_set_parity((unsigned char *) key); + + /* Perform the encryption */ + mbedtls_des_init(&ctx); + mbedtls_des_setkey_enc(&ctx, (unsigned char *) key); + return mbedtls_des_crypt_ecb(&ctx, in, out) == 0; +} + +#elif defined(USE_SECTRANSP) + +static bool encrypt_des(const unsigned char *in, unsigned char *out, + const unsigned char *key_56) +{ + char key[8]; + size_t out_len; + CCCryptorStatus err; + + /* Expand the 56-bit key to 64-bits */ + extend_key_56_to_64(key_56, key); + + /* Set the key parity to odd */ + Curl_des_set_odd_parity((unsigned char *) key, sizeof(key)); + + /* Perform the encryption */ + err = CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionECBMode, key, + kCCKeySizeDES, NULL, in, 8 /* inbuflen */, out, + 8 /* outbuflen */, &out_len); + + return err == kCCSuccess; +} + +#elif defined(USE_OS400CRYPTO) + +static bool encrypt_des(const unsigned char *in, unsigned char *out, + const unsigned char *key_56) +{ + char key[8]; + _CIPHER_Control_T ctl; + + /* Setup the cipher control structure */ + ctl.Func_ID = ENCRYPT_ONLY; + ctl.Data_Len = sizeof(key); + + /* Expand the 56-bit key to 64-bits */ + extend_key_56_to_64(key_56, ctl.Crypto_Key); + + /* Set the key parity to odd */ + Curl_des_set_odd_parity((unsigned char *) ctl.Crypto_Key, ctl.Data_Len); + + /* Perform the encryption */ + _CIPHER((_SPCPTR *) &out, &ctl, (_SPCPTR *) &in); + + return TRUE; +} + +#elif defined(USE_WIN32_CRYPTO) + +static bool encrypt_des(const unsigned char *in, unsigned char *out, + const unsigned char *key_56) +{ + HCRYPTPROV hprov; + HCRYPTKEY hkey; + struct { + BLOBHEADER hdr; + unsigned int len; + char key[8]; + } blob; + DWORD len = 8; + + /* Acquire the crypto provider */ + if(!CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + return FALSE; + + /* Setup the key blob structure */ + memset(&blob, 0, sizeof(blob)); + blob.hdr.bType = PLAINTEXTKEYBLOB; + blob.hdr.bVersion = 2; + blob.hdr.aiKeyAlg = CALG_DES; + blob.len = sizeof(blob.key); + + /* Expand the 56-bit key to 64-bits */ + extend_key_56_to_64(key_56, blob.key); + + /* Set the key parity to odd */ + Curl_des_set_odd_parity((unsigned char *) blob.key, sizeof(blob.key)); + + /* Import the key */ + if(!CryptImportKey(hprov, (BYTE *) &blob, sizeof(blob), 0, 0, &hkey)) { + CryptReleaseContext(hprov, 0); + + return FALSE; + } + + memcpy(out, in, 8); + + /* Perform the encryption */ + CryptEncrypt(hkey, 0, FALSE, 0, out, &len, len); + + CryptDestroyKey(hkey); + CryptReleaseContext(hprov, 0); + + return TRUE; +} + +#endif /* defined(USE_WIN32_CRYPTO) */ + + /* + * takes a 21 byte array and treats it as 3 56-bit DES keys. The + * 8 byte plaintext is encrypted with each key and the resulting 24 + * bytes are stored in the results array. + */ +void Curl_ntlm_core_lm_resp(const unsigned char *keys, + const unsigned char *plaintext, + unsigned char *results) +{ +#if defined(USE_OPENSSL_DES) || defined(USE_WOLFSSL) + DES_key_schedule ks; + + setup_des_key(keys, DESKEY(ks)); + DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) results, + DESKEY(ks), DES_ENCRYPT); + + setup_des_key(keys + 7, DESKEY(ks)); + DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) (results + 8), + DESKEY(ks), DES_ENCRYPT); + + setup_des_key(keys + 14, DESKEY(ks)); + DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) (results + 16), + DESKEY(ks), DES_ENCRYPT); +#elif defined(USE_GNUTLS) + struct des_ctx des; + setup_des_key(keys, &des); + des_encrypt(&des, 8, results, plaintext); + setup_des_key(keys + 7, &des); + des_encrypt(&des, 8, results + 8, plaintext); + setup_des_key(keys + 14, &des); + des_encrypt(&des, 8, results + 16, plaintext); +#elif defined(USE_MBEDTLS) || defined(USE_SECTRANSP) \ + || defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO) + encrypt_des(plaintext, results, keys); + encrypt_des(plaintext, results + 8, keys + 7); + encrypt_des(plaintext, results + 16, keys + 14); +#else + (void)keys; + (void)plaintext; + (void)results; +#endif +} + +/* + * Set up lanmanager hashed password + */ +CURLcode Curl_ntlm_core_mk_lm_hash(const char *password, + unsigned char *lmbuffer /* 21 bytes */) +{ + unsigned char pw[14]; +#if !defined(CURL_NTLM_NOT_SUPPORTED) + static const unsigned char magic[] = { + 0x4B, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25 /* i.e. KGS!@#$% */ + }; +#endif + size_t len = CURLMIN(strlen(password), 14); + + Curl_strntoupper((char *)pw, password, len); + memset(&pw[len], 0, 14 - len); + + { + /* Create LanManager hashed password. */ + +#if defined(USE_OPENSSL_DES) || defined(USE_WOLFSSL) + DES_key_schedule ks; + + setup_des_key(pw, DESKEY(ks)); + DES_ecb_encrypt((DES_cblock *)magic, (DES_cblock *)lmbuffer, + DESKEY(ks), DES_ENCRYPT); + + setup_des_key(pw + 7, DESKEY(ks)); + DES_ecb_encrypt((DES_cblock *)magic, (DES_cblock *)(lmbuffer + 8), + DESKEY(ks), DES_ENCRYPT); +#elif defined(USE_GNUTLS) + struct des_ctx des; + setup_des_key(pw, &des); + des_encrypt(&des, 8, lmbuffer, magic); + setup_des_key(pw + 7, &des); + des_encrypt(&des, 8, lmbuffer + 8, magic); +#elif defined(USE_MBEDTLS) || defined(USE_SECTRANSP) \ + || defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO) + encrypt_des(magic, lmbuffer, pw); + encrypt_des(magic, lmbuffer + 8, pw + 7); +#endif + + memset(lmbuffer + 16, 0, 21 - 16); + } + + return CURLE_OK; +} + +static void ascii_to_unicode_le(unsigned char *dest, const char *src, + size_t srclen) +{ + size_t i; + for(i = 0; i < srclen; i++) { + dest[2 * i] = (unsigned char)src[i]; + dest[2 * i + 1] = '\0'; + } +} + +#if !defined(USE_WINDOWS_SSPI) + +static void ascii_uppercase_to_unicode_le(unsigned char *dest, + const char *src, size_t srclen) +{ + size_t i; + for(i = 0; i < srclen; i++) { + dest[2 * i] = (unsigned char)(Curl_raw_toupper(src[i])); + dest[2 * i + 1] = '\0'; + } +} + +#endif /* !USE_WINDOWS_SSPI */ + +/* + * Set up nt hashed passwords + * @unittest: 1600 + */ +CURLcode Curl_ntlm_core_mk_nt_hash(const char *password, + unsigned char *ntbuffer /* 21 bytes */) +{ + size_t len = strlen(password); + unsigned char *pw; + CURLcode result; + if(len > SIZE_T_MAX/2) /* avoid integer overflow */ + return CURLE_OUT_OF_MEMORY; + pw = len ? malloc(len * 2) : (unsigned char *)strdup(""); + if(!pw) + return CURLE_OUT_OF_MEMORY; + + ascii_to_unicode_le(pw, password, len); + + /* Create NT hashed password. */ + result = Curl_md4it(ntbuffer, pw, 2 * len); + if(!result) + memset(ntbuffer + 16, 0, 21 - 16); + + free(pw); + + return result; +} + +#if !defined(USE_WINDOWS_SSPI) + +/* Timestamp in tenths of a microsecond since January 1, 1601 00:00:00 UTC. */ +struct ms_filetime { + unsigned int dwLowDateTime; + unsigned int dwHighDateTime; +}; + +/* Convert a time_t to an MS FILETIME (MS-DTYP section 2.3.3). */ +static void time2filetime(struct ms_filetime *ft, time_t t) +{ +#if SIZEOF_TIME_T > 4 + t = (t + CURL_OFF_T_C(11644473600)) * 10000000; + ft->dwLowDateTime = (unsigned int) (t & 0xFFFFFFFF); + ft->dwHighDateTime = (unsigned int) (t >> 32); +#else + unsigned int r, s; + unsigned int i; + + ft->dwLowDateTime = t & 0xFFFFFFFF; + ft->dwHighDateTime = 0; + +# ifndef HAVE_TIME_T_UNSIGNED + /* Extend sign if needed. */ + if(ft->dwLowDateTime & 0x80000000) + ft->dwHighDateTime = ~0; +# endif + + /* Bias seconds to Jan 1, 1601. + 134774 days = 11644473600 seconds = 0x2B6109100 */ + r = ft->dwLowDateTime; + ft->dwLowDateTime = (ft->dwLowDateTime + 0xB6109100U) & 0xFFFFFFFF; + ft->dwHighDateTime += ft->dwLowDateTime < r? 0x03: 0x02; + + /* Convert to tenths of microseconds. */ + ft->dwHighDateTime *= 10000000; + i = 32; + do { + i -= 8; + s = ((ft->dwLowDateTime >> i) & 0xFF) * (10000000 - 1); + r = (s << i) & 0xFFFFFFFF; + s >>= 1; /* Split shift to avoid width overflow. */ + s >>= 31 - i; + ft->dwLowDateTime = (ft->dwLowDateTime + r) & 0xFFFFFFFF; + if(ft->dwLowDateTime < r) + s++; + ft->dwHighDateTime += s; + } while(i); + ft->dwHighDateTime &= 0xFFFFFFFF; +#endif +} + +/* This creates the NTLMv2 hash by using NTLM hash as the key and Unicode + * (uppercase UserName + Domain) as the data + */ +CURLcode Curl_ntlm_core_mk_ntlmv2_hash(const char *user, size_t userlen, + const char *domain, size_t domlen, + unsigned char *ntlmhash, + unsigned char *ntlmv2hash) +{ + /* Unicode representation */ + size_t identity_len; + unsigned char *identity; + CURLcode result = CURLE_OK; + + if((userlen > CURL_MAX_INPUT_LENGTH) || (domlen > CURL_MAX_INPUT_LENGTH)) + return CURLE_OUT_OF_MEMORY; + + identity_len = (userlen + domlen) * 2; + identity = malloc(identity_len + 1); + + if(!identity) + return CURLE_OUT_OF_MEMORY; + + ascii_uppercase_to_unicode_le(identity, user, userlen); + ascii_to_unicode_le(identity + (userlen << 1), domain, domlen); + + result = Curl_hmacit(Curl_HMAC_MD5, ntlmhash, 16, identity, identity_len, + ntlmv2hash); + free(identity); + + return result; +} + +/* + * Curl_ntlm_core_mk_ntlmv2_resp() + * + * This creates the NTLMv2 response as set in the ntlm type-3 message. + * + * Parameters: + * + * ntlmv2hash [in] - The ntlmv2 hash (16 bytes) + * challenge_client [in] - The client nonce (8 bytes) + * ntlm [in] - The ntlm data struct being used to read TargetInfo + and Server challenge received in the type-2 message + * ntresp [out] - The address where a pointer to newly allocated + * memory holding the NTLMv2 response. + * ntresp_len [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_ntlm_core_mk_ntlmv2_resp(unsigned char *ntlmv2hash, + unsigned char *challenge_client, + struct ntlmdata *ntlm, + unsigned char **ntresp, + unsigned int *ntresp_len) +{ +/* NTLMv2 response structure : +------------------------------------------------------------------------------ +0 HMAC MD5 16 bytes +------BLOB-------------------------------------------------------------------- +16 Signature 0x01010000 +20 Reserved long (0x00000000) +24 Timestamp LE, 64-bit signed value representing the number of + tenths of a microsecond since January 1, 1601. +32 Client Nonce 8 bytes +40 Unknown 4 bytes +44 Target Info N bytes (from the type-2 message) +44+N Unknown 4 bytes +------------------------------------------------------------------------------ +*/ + + unsigned int len = 0; + unsigned char *ptr = NULL; + unsigned char hmac_output[HMAC_MD5_LENGTH]; + struct ms_filetime tw; + + CURLcode result = CURLE_OK; + + /* Calculate the timestamp */ +#ifdef DEBUGBUILD + char *force_timestamp = getenv("CURL_FORCETIME"); + if(force_timestamp) + time2filetime(&tw, (time_t) 0); + else +#endif + time2filetime(&tw, time(NULL)); + + /* Calculate the response len */ + len = HMAC_MD5_LENGTH + NTLMv2_BLOB_LEN; + + /* Allocate the response */ + ptr = calloc(1, len); + if(!ptr) + return CURLE_OUT_OF_MEMORY; + + /* Create the BLOB structure */ + msnprintf((char *)ptr + HMAC_MD5_LENGTH, NTLMv2_BLOB_LEN, + "%c%c%c%c" /* NTLMv2_BLOB_SIGNATURE */ + "%c%c%c%c" /* Reserved = 0 */ + "%c%c%c%c%c%c%c%c", /* Timestamp */ + NTLMv2_BLOB_SIGNATURE[0], NTLMv2_BLOB_SIGNATURE[1], + NTLMv2_BLOB_SIGNATURE[2], NTLMv2_BLOB_SIGNATURE[3], + 0, 0, 0, 0, + LONGQUARTET(tw.dwLowDateTime), LONGQUARTET(tw.dwHighDateTime)); + + memcpy(ptr + 32, challenge_client, 8); + if(ntlm->target_info_len) + memcpy(ptr + 44, ntlm->target_info, ntlm->target_info_len); + + /* Concatenate the Type 2 challenge with the BLOB and do HMAC MD5 */ + memcpy(ptr + 8, &ntlm->nonce[0], 8); + result = Curl_hmacit(Curl_HMAC_MD5, ntlmv2hash, HMAC_MD5_LENGTH, ptr + 8, + NTLMv2_BLOB_LEN + 8, hmac_output); + if(result) { + free(ptr); + return result; + } + + /* Concatenate the HMAC MD5 output with the BLOB */ + memcpy(ptr, hmac_output, HMAC_MD5_LENGTH); + + /* Return the response */ + *ntresp = ptr; + *ntresp_len = len; + + return result; +} + +/* + * Curl_ntlm_core_mk_lmv2_resp() + * + * This creates the LMv2 response as used in the ntlm type-3 message. + * + * Parameters: + * + * ntlmv2hash [in] - The ntlmv2 hash (16 bytes) + * challenge_client [in] - The client nonce (8 bytes) + * challenge_client [in] - The server challenge (8 bytes) + * lmresp [out] - The LMv2 response (24 bytes) + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_ntlm_core_mk_lmv2_resp(unsigned char *ntlmv2hash, + unsigned char *challenge_client, + unsigned char *challenge_server, + unsigned char *lmresp) +{ + unsigned char data[16]; + unsigned char hmac_output[16]; + CURLcode result = CURLE_OK; + + memcpy(&data[0], challenge_server, 8); + memcpy(&data[8], challenge_client, 8); + + result = Curl_hmacit(Curl_HMAC_MD5, ntlmv2hash, 16, &data[0], 16, + hmac_output); + if(result) + return result; + + /* Concatenate the HMAC MD5 output with the client nonce */ + memcpy(lmresp, hmac_output, 16); + memcpy(lmresp + 16, challenge_client, 8); + + return result; +} + +#endif /* !USE_WINDOWS_SSPI */ + +#endif /* USE_CURL_NTLM_CORE */ diff --git a/third_party/curl/lib/curl_ntlm_core.h b/third_party/curl/lib/curl_ntlm_core.h new file mode 100644 index 0000000..0c62ee0 --- /dev/null +++ b/third_party/curl/lib/curl_ntlm_core.h @@ -0,0 +1,79 @@ +#ifndef HEADER_CURL_NTLM_CORE_H +#define HEADER_CURL_NTLM_CORE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_CURL_NTLM_CORE) + +#if defined(USE_OPENSSL) +# include +#elif defined(USE_WOLFSSL) +# include +# include +#endif + +/* Helpers to generate function byte arguments in little endian order */ +#define SHORTPAIR(x) ((int)((x) & 0xff)), ((int)(((x) >> 8) & 0xff)) +#define LONGQUARTET(x) ((int)((x) & 0xff)), ((int)(((x) >> 8) & 0xff)), \ + ((int)(((x) >> 16) & 0xff)), ((int)(((x) >> 24) & 0xff)) + +void Curl_ntlm_core_lm_resp(const unsigned char *keys, + const unsigned char *plaintext, + unsigned char *results); + +CURLcode Curl_ntlm_core_mk_lm_hash(const char *password, + unsigned char *lmbuffer /* 21 bytes */); + +CURLcode Curl_ntlm_core_mk_nt_hash(const char *password, + unsigned char *ntbuffer /* 21 bytes */); + +#if !defined(USE_WINDOWS_SSPI) + +CURLcode Curl_hmac_md5(const unsigned char *key, unsigned int keylen, + const unsigned char *data, unsigned int datalen, + unsigned char *output); + +CURLcode Curl_ntlm_core_mk_ntlmv2_hash(const char *user, size_t userlen, + const char *domain, size_t domlen, + unsigned char *ntlmhash, + unsigned char *ntlmv2hash); + +CURLcode Curl_ntlm_core_mk_ntlmv2_resp(unsigned char *ntlmv2hash, + unsigned char *challenge_client, + struct ntlmdata *ntlm, + unsigned char **ntresp, + unsigned int *ntresp_len); + +CURLcode Curl_ntlm_core_mk_lmv2_resp(unsigned char *ntlmv2hash, + unsigned char *challenge_client, + unsigned char *challenge_server, + unsigned char *lmresp); + +#endif /* !USE_WINDOWS_SSPI */ + +#endif /* USE_CURL_NTLM_CORE */ + +#endif /* HEADER_CURL_NTLM_CORE_H */ diff --git a/third_party/curl/lib/curl_path.c b/third_party/curl/lib/curl_path.c new file mode 100644 index 0000000..144f880 --- /dev/null +++ b/third_party/curl/lib/curl_path.c @@ -0,0 +1,203 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl AND ISC + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_SSH) + +#include +#include "curl_memory.h" +#include "curl_path.h" +#include "escape.h" +#include "memdebug.h" + +#define MAX_SSHPATH_LEN 100000 /* arbitrary */ + +/* figure out the path to work with in this particular request */ +CURLcode Curl_getworkingpath(struct Curl_easy *data, + char *homedir, /* when SFTP is used */ + char **path) /* returns the allocated + real path to work with */ +{ + char *working_path; + size_t working_path_len; + struct dynbuf npath; + CURLcode result = + Curl_urldecode(data->state.up.path, 0, &working_path, + &working_path_len, REJECT_ZERO); + if(result) + return result; + + /* new path to switch to in case we need to */ + Curl_dyn_init(&npath, MAX_SSHPATH_LEN); + + /* Check for /~/, indicating relative to the user's home directory */ + if((data->conn->handler->protocol & CURLPROTO_SCP) && + (working_path_len > 3) && (!memcmp(working_path, "/~/", 3))) { + /* It is referenced to the home directory, so strip the leading '/~/' */ + if(Curl_dyn_addn(&npath, &working_path[3], working_path_len - 3)) { + free(working_path); + return CURLE_OUT_OF_MEMORY; + } + } + else if((data->conn->handler->protocol & CURLPROTO_SFTP) && + (!strcmp("/~", working_path) || + ((working_path_len > 2) && !memcmp(working_path, "/~/", 3)))) { + if(Curl_dyn_add(&npath, homedir)) { + free(working_path); + return CURLE_OUT_OF_MEMORY; + } + if(working_path_len > 2) { + size_t len; + const char *p; + int copyfrom = 3; + /* Copy a separating '/' if homedir does not end with one */ + len = Curl_dyn_len(&npath); + p = Curl_dyn_ptr(&npath); + if(len && (p[len-1] != '/')) + copyfrom = 2; + + if(Curl_dyn_addn(&npath, + &working_path[copyfrom], working_path_len - copyfrom)) { + free(working_path); + return CURLE_OUT_OF_MEMORY; + } + } + } + + if(Curl_dyn_len(&npath)) { + free(working_path); + + /* store the pointer for the caller to receive */ + *path = Curl_dyn_ptr(&npath); + } + else + *path = working_path; + + return CURLE_OK; +} + +/* The original get_pathname() function came from OpenSSH sftp.c version + 4.6p1. */ +/* + * Copyright (c) 2001-2004 Damien Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#define MAX_PATHLENGTH 65535 /* arbitrary long */ + +CURLcode Curl_get_pathname(const char **cpp, char **path, const char *homedir) +{ + const char *cp = *cpp, *end; + char quot; + unsigned int i; + static const char WHITESPACE[] = " \t\r\n"; + struct dynbuf out; + CURLcode result; + + DEBUGASSERT(homedir); + *path = NULL; + *cpp = NULL; + if(!*cp || !homedir) + return CURLE_QUOTE_ERROR; + + Curl_dyn_init(&out, MAX_PATHLENGTH); + + /* Ignore leading whitespace */ + cp += strspn(cp, WHITESPACE); + + /* Check for quoted filenames */ + if(*cp == '\"' || *cp == '\'') { + quot = *cp++; + + /* Search for terminating quote, unescape some chars */ + for(i = 0; i <= strlen(cp); i++) { + if(cp[i] == quot) { /* Found quote */ + i++; + break; + } + if(cp[i] == '\0') { /* End of string */ + goto fail; + } + if(cp[i] == '\\') { /* Escaped characters */ + i++; + if(cp[i] != '\'' && cp[i] != '\"' && + cp[i] != '\\') { + goto fail; + } + } + result = Curl_dyn_addn(&out, &cp[i], 1); + if(result) + return result; + } + + if(!Curl_dyn_len(&out)) + goto fail; + + /* return pointer to second parameter if it exists */ + *cpp = &cp[i] + strspn(&cp[i], WHITESPACE); + } + else { + /* Read to end of filename - either to whitespace or terminator */ + end = strpbrk(cp, WHITESPACE); + if(!end) + end = strchr(cp, '\0'); + + /* return pointer to second parameter if it exists */ + *cpp = end + strspn(end, WHITESPACE); + + /* Handling for relative path - prepend home directory */ + if(cp[0] == '/' && cp[1] == '~' && cp[2] == '/') { + result = Curl_dyn_add(&out, homedir); + if(!result) + result = Curl_dyn_addn(&out, "/", 1); + if(result) + return result; + cp += 3; + } + /* Copy path name up until first "whitespace" */ + result = Curl_dyn_addn(&out, cp, (end - cp)); + if(result) + return result; + } + *path = Curl_dyn_ptr(&out); + return CURLE_OK; + +fail: + Curl_dyn_free(&out); + return CURLE_QUOTE_ERROR; +} + +#endif /* if SSH is used */ diff --git a/third_party/curl/lib/curl_path.h b/third_party/curl/lib/curl_path.h new file mode 100644 index 0000000..6fdb2fd --- /dev/null +++ b/third_party/curl/lib/curl_path.h @@ -0,0 +1,49 @@ +#ifndef HEADER_CURL_PATH_H +#define HEADER_CURL_PATH_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include +#include "urldata.h" + +#ifdef _WIN32 +# undef PATH_MAX +# define PATH_MAX MAX_PATH +# ifndef R_OK +# define R_OK 4 +# endif +#endif + +#ifndef PATH_MAX +#define PATH_MAX 1024 /* just an extra precaution since there are systems that + have their definition hidden well */ +#endif + +CURLcode Curl_getworkingpath(struct Curl_easy *data, + char *homedir, + char **path); + +CURLcode Curl_get_pathname(const char **cpp, char **path, const char *homedir); +#endif /* HEADER_CURL_PATH_H */ diff --git a/third_party/curl/lib/curl_printf.h b/third_party/curl/lib/curl_printf.h new file mode 100644 index 0000000..c2457d2 --- /dev/null +++ b/third_party/curl/lib/curl_printf.h @@ -0,0 +1,55 @@ +#ifndef HEADER_CURL_PRINTF_H +#define HEADER_CURL_PRINTF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * This header should be included by ALL code in libcurl that uses any + * *rintf() functions. + */ + +#include + +#define MERR_OK 0 +#define MERR_MEM 1 +#define MERR_TOO_LARGE 2 + +# undef printf +# undef fprintf +# undef msnprintf +# undef vprintf +# undef vfprintf +# undef vsnprintf +# undef mvsnprintf +# undef aprintf +# undef vaprintf +# define printf curl_mprintf +# define fprintf curl_mfprintf +# define msnprintf curl_msnprintf +# define vprintf curl_mvprintf +# define vfprintf curl_mvfprintf +# define mvsnprintf curl_mvsnprintf +# define aprintf curl_maprintf +# define vaprintf curl_mvaprintf +#endif /* HEADER_CURL_PRINTF_H */ diff --git a/third_party/curl/lib/curl_range.c b/third_party/curl/lib/curl_range.c new file mode 100644 index 0000000..d499953 --- /dev/null +++ b/third_party/curl/lib/curl_range.c @@ -0,0 +1,96 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include +#include "curl_range.h" +#include "sendf.h" +#include "strtoofft.h" + +/* Only include this function if one or more of FTP, FILE are enabled. */ +#if !defined(CURL_DISABLE_FTP) || !defined(CURL_DISABLE_FILE) + + /* + Check if this is a range download, and if so, set the internal variables + properly. + */ +CURLcode Curl_range(struct Curl_easy *data) +{ + curl_off_t from, to; + char *ptr; + char *ptr2; + + if(data->state.use_range && data->state.range) { + CURLofft from_t; + CURLofft to_t; + from_t = curlx_strtoofft(data->state.range, &ptr, 10, &from); + if(from_t == CURL_OFFT_FLOW) + return CURLE_RANGE_ERROR; + while(*ptr && (ISBLANK(*ptr) || (*ptr == '-'))) + ptr++; + to_t = curlx_strtoofft(ptr, &ptr2, 10, &to); + if(to_t == CURL_OFFT_FLOW) + return CURLE_RANGE_ERROR; + if((to_t == CURL_OFFT_INVAL) && !from_t) { + /* X - */ + data->state.resume_from = from; + DEBUGF(infof(data, "RANGE %" CURL_FORMAT_CURL_OFF_T " to end of file", + from)); + } + else if((from_t == CURL_OFFT_INVAL) && !to_t) { + /* -Y */ + data->req.maxdownload = to; + data->state.resume_from = -to; + DEBUGF(infof(data, "RANGE the last %" CURL_FORMAT_CURL_OFF_T " bytes", + to)); + } + else { + /* X-Y */ + curl_off_t totalsize; + + /* Ensure the range is sensible - to should follow from. */ + if(from > to) + return CURLE_RANGE_ERROR; + + totalsize = to - from; + if(totalsize == CURL_OFF_T_MAX) + return CURLE_RANGE_ERROR; + + data->req.maxdownload = totalsize + 1; /* include last byte */ + data->state.resume_from = from; + DEBUGF(infof(data, "RANGE from %" CURL_FORMAT_CURL_OFF_T + " getting %" CURL_FORMAT_CURL_OFF_T " bytes", + from, data->req.maxdownload)); + } + DEBUGF(infof(data, "range-download from %" CURL_FORMAT_CURL_OFF_T + " to %" CURL_FORMAT_CURL_OFF_T ", totally %" + CURL_FORMAT_CURL_OFF_T " bytes", + from, to, data->req.maxdownload)); + } + else + data->req.maxdownload = -1; + return CURLE_OK; +} + +#endif diff --git a/third_party/curl/lib/curl_range.h b/third_party/curl/lib/curl_range.h new file mode 100644 index 0000000..77679e2 --- /dev/null +++ b/third_party/curl/lib/curl_range.h @@ -0,0 +1,31 @@ +#ifndef HEADER_CURL_RANGE_H +#define HEADER_CURL_RANGE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "urldata.h" + +CURLcode Curl_range(struct Curl_easy *data); +#endif /* HEADER_CURL_RANGE_H */ diff --git a/third_party/curl/lib/curl_rtmp.c b/third_party/curl/lib/curl_rtmp.c new file mode 100644 index 0000000..76eff78 --- /dev/null +++ b/third_party/curl/lib/curl_rtmp.c @@ -0,0 +1,362 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (C) Howard Chu, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_LIBRTMP + +#include "curl_rtmp.h" +#include "urldata.h" +#include "nonblock.h" /* for curlx_nonblock */ +#include "progress.h" /* for Curl_pgrsSetUploadSize */ +#include "transfer.h" +#include "warnless.h" +#include +#include + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if defined(_WIN32) && !defined(USE_LWIPSOCK) +#define setsockopt(a,b,c,d,e) (setsockopt)(a,b,c,(const char *)d,(int)e) +#define SET_RCVTIMEO(tv,s) int tv = s*1000 +#elif defined(LWIP_SO_SNDRCVTIMEO_NONSTANDARD) +#define SET_RCVTIMEO(tv,s) int tv = s*1000 +#else +#define SET_RCVTIMEO(tv,s) struct timeval tv = {s,0} +#endif + +#define DEF_BUFTIME (2*60*60*1000) /* 2 hours */ + +static CURLcode rtmp_setup_connection(struct Curl_easy *data, + struct connectdata *conn); +static CURLcode rtmp_do(struct Curl_easy *data, bool *done); +static CURLcode rtmp_done(struct Curl_easy *data, CURLcode, bool premature); +static CURLcode rtmp_connect(struct Curl_easy *data, bool *done); +static CURLcode rtmp_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead); + +static Curl_recv rtmp_recv; +static Curl_send rtmp_send; + +/* + * RTMP protocol handler.h, based on https://rtmpdump.mplayerhq.hu + */ + +const struct Curl_handler Curl_handler_rtmp = { + "rtmp", /* scheme */ + rtmp_setup_connection, /* setup_connection */ + rtmp_do, /* do_it */ + rtmp_done, /* done */ + ZERO_NULL, /* do_more */ + rtmp_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + rtmp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_RTMP, /* defport */ + CURLPROTO_RTMP, /* protocol */ + CURLPROTO_RTMP, /* family */ + PROTOPT_NONE /* flags */ +}; + +const struct Curl_handler Curl_handler_rtmpt = { + "rtmpt", /* scheme */ + rtmp_setup_connection, /* setup_connection */ + rtmp_do, /* do_it */ + rtmp_done, /* done */ + ZERO_NULL, /* do_more */ + rtmp_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + rtmp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_RTMPT, /* defport */ + CURLPROTO_RTMPT, /* protocol */ + CURLPROTO_RTMPT, /* family */ + PROTOPT_NONE /* flags */ +}; + +const struct Curl_handler Curl_handler_rtmpe = { + "rtmpe", /* scheme */ + rtmp_setup_connection, /* setup_connection */ + rtmp_do, /* do_it */ + rtmp_done, /* done */ + ZERO_NULL, /* do_more */ + rtmp_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + rtmp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_RTMP, /* defport */ + CURLPROTO_RTMPE, /* protocol */ + CURLPROTO_RTMPE, /* family */ + PROTOPT_NONE /* flags */ +}; + +const struct Curl_handler Curl_handler_rtmpte = { + "rtmpte", /* scheme */ + rtmp_setup_connection, /* setup_connection */ + rtmp_do, /* do_it */ + rtmp_done, /* done */ + ZERO_NULL, /* do_more */ + rtmp_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + rtmp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_RTMPT, /* defport */ + CURLPROTO_RTMPTE, /* protocol */ + CURLPROTO_RTMPTE, /* family */ + PROTOPT_NONE /* flags */ +}; + +const struct Curl_handler Curl_handler_rtmps = { + "rtmps", /* scheme */ + rtmp_setup_connection, /* setup_connection */ + rtmp_do, /* do_it */ + rtmp_done, /* done */ + ZERO_NULL, /* do_more */ + rtmp_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + rtmp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_RTMPS, /* defport */ + CURLPROTO_RTMPS, /* protocol */ + CURLPROTO_RTMP, /* family */ + PROTOPT_NONE /* flags */ +}; + +const struct Curl_handler Curl_handler_rtmpts = { + "rtmpts", /* scheme */ + rtmp_setup_connection, /* setup_connection */ + rtmp_do, /* do_it */ + rtmp_done, /* done */ + ZERO_NULL, /* do_more */ + rtmp_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + rtmp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_RTMPS, /* defport */ + CURLPROTO_RTMPTS, /* protocol */ + CURLPROTO_RTMPT, /* family */ + PROTOPT_NONE /* flags */ +}; + +static CURLcode rtmp_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + RTMP *r = RTMP_Alloc(); + if(!r) + return CURLE_OUT_OF_MEMORY; + + RTMP_Init(r); + RTMP_SetBufferMS(r, DEF_BUFTIME); + if(!RTMP_SetupURL(r, data->state.url)) { + RTMP_Free(r); + return CURLE_URL_MALFORMAT; + } + conn->proto.rtmp = r; + return CURLE_OK; +} + +static CURLcode rtmp_connect(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + RTMP *r = conn->proto.rtmp; + SET_RCVTIMEO(tv, 10); + + r->m_sb.sb_socket = (int)conn->sock[FIRSTSOCKET]; + + /* We have to know if it's a write before we send the + * connect request packet + */ + if(data->state.upload) + r->Link.protocol |= RTMP_FEATURE_WRITE; + + /* For plain streams, use the buffer toggle trick to keep data flowing */ + if(!(r->Link.lFlags & RTMP_LF_LIVE) && + !(r->Link.protocol & RTMP_FEATURE_HTTP)) + r->Link.lFlags |= RTMP_LF_BUFX; + + (void)curlx_nonblock(r->m_sb.sb_socket, FALSE); + setsockopt(r->m_sb.sb_socket, SOL_SOCKET, SO_RCVTIMEO, + (char *)&tv, sizeof(tv)); + + if(!RTMP_Connect1(r, NULL)) + return CURLE_FAILED_INIT; + + /* Clients must send a periodic BytesReceived report to the server */ + r->m_bSendCounter = true; + + *done = TRUE; + conn->recv[FIRSTSOCKET] = rtmp_recv; + conn->send[FIRSTSOCKET] = rtmp_send; + return CURLE_OK; +} + +static CURLcode rtmp_do(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + RTMP *r = conn->proto.rtmp; + + if(!RTMP_ConnectStream(r, 0)) + return CURLE_FAILED_INIT; + + if(data->state.upload) { + Curl_pgrsSetUploadSize(data, data->state.infilesize); + Curl_xfer_setup(data, -1, -1, FALSE, FIRSTSOCKET); + } + else + Curl_xfer_setup(data, FIRSTSOCKET, -1, FALSE, -1); + *done = TRUE; + return CURLE_OK; +} + +static CURLcode rtmp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + (void)data; /* unused */ + (void)status; /* unused */ + (void)premature; /* unused */ + + return CURLE_OK; +} + +static CURLcode rtmp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + RTMP *r = conn->proto.rtmp; + (void)data; + (void)dead_connection; + if(r) { + conn->proto.rtmp = NULL; + RTMP_Close(r); + RTMP_Free(r); + } + return CURLE_OK; +} + +static ssize_t rtmp_recv(struct Curl_easy *data, int sockindex, char *buf, + size_t len, CURLcode *err) +{ + struct connectdata *conn = data->conn; + RTMP *r = conn->proto.rtmp; + ssize_t nread; + + (void)sockindex; /* unused */ + + nread = RTMP_Read(r, buf, curlx_uztosi(len)); + if(nread < 0) { + if(r->m_read.status == RTMP_READ_COMPLETE || + r->m_read.status == RTMP_READ_EOF) { + data->req.size = data->req.bytecount; + nread = 0; + } + else + *err = CURLE_RECV_ERROR; + } + return nread; +} + +static ssize_t rtmp_send(struct Curl_easy *data, int sockindex, + const void *buf, size_t len, CURLcode *err) +{ + struct connectdata *conn = data->conn; + RTMP *r = conn->proto.rtmp; + ssize_t num; + + (void)sockindex; /* unused */ + + num = RTMP_Write(r, (char *)buf, curlx_uztosi(len)); + if(num < 0) + *err = CURLE_SEND_ERROR; + + return num; +} + +void Curl_rtmp_version(char *version, size_t len) +{ + char suff[2]; + if(RTMP_LIB_VERSION & 0xff) { + suff[0] = (RTMP_LIB_VERSION & 0xff) + 'a' - 1; + suff[1] = '\0'; + } + else + suff[0] = '\0'; + + msnprintf(version, len, "librtmp/%d.%d%s", + RTMP_LIB_VERSION >> 16, (RTMP_LIB_VERSION >> 8) & 0xff, + suff); +} + +#endif /* USE_LIBRTMP */ diff --git a/third_party/curl/lib/curl_rtmp.h b/third_party/curl/lib/curl_rtmp.h new file mode 100644 index 0000000..339d3a4 --- /dev/null +++ b/third_party/curl/lib/curl_rtmp.h @@ -0,0 +1,37 @@ +#ifndef HEADER_CURL_RTMP_H +#define HEADER_CURL_RTMP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Howard Chu, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifdef USE_LIBRTMP +extern const struct Curl_handler Curl_handler_rtmp; +extern const struct Curl_handler Curl_handler_rtmpt; +extern const struct Curl_handler Curl_handler_rtmpe; +extern const struct Curl_handler Curl_handler_rtmpte; +extern const struct Curl_handler Curl_handler_rtmps; +extern const struct Curl_handler Curl_handler_rtmpts; + +void Curl_rtmp_version(char *version, size_t len); +#endif + +#endif /* HEADER_CURL_RTMP_H */ diff --git a/third_party/curl/lib/curl_sasl.c b/third_party/curl/lib/curl_sasl.c new file mode 100644 index 0000000..ba8911b --- /dev/null +++ b/third_party/curl/lib/curl_sasl.c @@ -0,0 +1,760 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * RFC2195 CRAM-MD5 authentication + * RFC2617 Basic and Digest Access Authentication + * RFC2831 DIGEST-MD5 authentication + * RFC4422 Simple Authentication and Security Layer (SASL) + * RFC4616 PLAIN authentication + * RFC5802 SCRAM-SHA-1 authentication + * RFC7677 SCRAM-SHA-256 authentication + * RFC6749 OAuth 2.0 Authorization Framework + * RFC7628 A Set of SASL Mechanisms for OAuth + * Draft LOGIN SASL Mechanism + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_POP3) || \ + (!defined(CURL_DISABLE_LDAP) && defined(USE_OPENLDAP)) + +#include +#include "urldata.h" + +#include "curl_base64.h" +#include "curl_md5.h" +#include "vauth/vauth.h" +#include "cfilters.h" +#include "vtls/vtls.h" +#include "curl_hmac.h" +#include "curl_sasl.h" +#include "warnless.h" +#include "strtok.h" +#include "sendf.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* Supported mechanisms */ +static const struct { + const char *name; /* Name */ + size_t len; /* Name length */ + unsigned short bit; /* Flag bit */ +} mechtable[] = { + { "LOGIN", 5, SASL_MECH_LOGIN }, + { "PLAIN", 5, SASL_MECH_PLAIN }, + { "CRAM-MD5", 8, SASL_MECH_CRAM_MD5 }, + { "DIGEST-MD5", 10, SASL_MECH_DIGEST_MD5 }, + { "GSSAPI", 6, SASL_MECH_GSSAPI }, + { "EXTERNAL", 8, SASL_MECH_EXTERNAL }, + { "NTLM", 4, SASL_MECH_NTLM }, + { "XOAUTH2", 7, SASL_MECH_XOAUTH2 }, + { "OAUTHBEARER", 11, SASL_MECH_OAUTHBEARER }, + { "SCRAM-SHA-1", 11, SASL_MECH_SCRAM_SHA_1 }, + { "SCRAM-SHA-256",13, SASL_MECH_SCRAM_SHA_256 }, + { ZERO_NULL, 0, 0 } +}; + +/* + * Curl_sasl_cleanup() + * + * This is used to cleanup any libraries or curl modules used by the sasl + * functions. + * + * Parameters: + * + * conn [in] - The connection data. + * authused [in] - The authentication mechanism used. + */ +void Curl_sasl_cleanup(struct connectdata *conn, unsigned short authused) +{ + (void)conn; + (void)authused; + +#if defined(USE_KERBEROS5) + /* Cleanup the gssapi structure */ + if(authused == SASL_MECH_GSSAPI) { + Curl_auth_cleanup_gssapi(&conn->krb5); + } +#endif + +#if defined(USE_GSASL) + /* Cleanup the GSASL structure */ + if(authused & (SASL_MECH_SCRAM_SHA_1 | SASL_MECH_SCRAM_SHA_256)) { + Curl_auth_gsasl_cleanup(&conn->gsasl); + } +#endif + +#if defined(USE_NTLM) + /* Cleanup the NTLM structure */ + if(authused == SASL_MECH_NTLM) { + Curl_auth_cleanup_ntlm(&conn->ntlm); + } +#endif +} + +/* + * Curl_sasl_decode_mech() + * + * Convert a SASL mechanism name into a token. + * + * Parameters: + * + * ptr [in] - The mechanism string. + * maxlen [in] - Maximum mechanism string length. + * len [out] - If not NULL, effective name length. + * + * Returns the SASL mechanism token or 0 if no match. + */ +unsigned short Curl_sasl_decode_mech(const char *ptr, size_t maxlen, + size_t *len) +{ + unsigned int i; + char c; + + for(i = 0; mechtable[i].name; i++) { + if(maxlen >= mechtable[i].len && + !memcmp(ptr, mechtable[i].name, mechtable[i].len)) { + if(len) + *len = mechtable[i].len; + + if(maxlen == mechtable[i].len) + return mechtable[i].bit; + + c = ptr[mechtable[i].len]; + if(!ISUPPER(c) && !ISDIGIT(c) && c != '-' && c != '_') + return mechtable[i].bit; + } + } + + return 0; +} + +/* + * Curl_sasl_parse_url_auth_option() + * + * Parse the URL login options. + */ +CURLcode Curl_sasl_parse_url_auth_option(struct SASL *sasl, + const char *value, size_t len) +{ + CURLcode result = CURLE_OK; + size_t mechlen; + + if(!len) + return CURLE_URL_MALFORMAT; + + if(sasl->resetprefs) { + sasl->resetprefs = FALSE; + sasl->prefmech = SASL_AUTH_NONE; + } + + if(!strncmp(value, "*", len)) + sasl->prefmech = SASL_AUTH_DEFAULT; + else { + unsigned short mechbit = Curl_sasl_decode_mech(value, len, &mechlen); + if(mechbit && mechlen == len) + sasl->prefmech |= mechbit; + else + result = CURLE_URL_MALFORMAT; + } + + return result; +} + +/* + * Curl_sasl_init() + * + * Initializes the SASL structure. + */ +void Curl_sasl_init(struct SASL *sasl, struct Curl_easy *data, + const struct SASLproto *params) +{ + unsigned long auth = data->set.httpauth; + + sasl->params = params; /* Set protocol dependent parameters */ + sasl->state = SASL_STOP; /* Not yet running */ + sasl->curmech = NULL; /* No mechanism yet. */ + sasl->authmechs = SASL_AUTH_NONE; /* No known authentication mechanism yet */ + sasl->prefmech = params->defmechs; /* Default preferred mechanisms */ + sasl->authused = SASL_AUTH_NONE; /* The authentication mechanism used */ + sasl->resetprefs = TRUE; /* Reset prefmech upon AUTH parsing. */ + sasl->mutual_auth = FALSE; /* No mutual authentication (GSSAPI only) */ + sasl->force_ir = FALSE; /* Respect external option */ + + if(auth != CURLAUTH_BASIC) { + unsigned short mechs = SASL_AUTH_NONE; + + /* If some usable http authentication options have been set, determine + new defaults from them. */ + if(auth & CURLAUTH_BASIC) + mechs |= SASL_MECH_PLAIN | SASL_MECH_LOGIN; + if(auth & CURLAUTH_DIGEST) + mechs |= SASL_MECH_DIGEST_MD5; + if(auth & CURLAUTH_NTLM) + mechs |= SASL_MECH_NTLM; + if(auth & CURLAUTH_BEARER) + mechs |= SASL_MECH_OAUTHBEARER | SASL_MECH_XOAUTH2; + if(auth & CURLAUTH_GSSAPI) + mechs |= SASL_MECH_GSSAPI; + + if(mechs != SASL_AUTH_NONE) + sasl->prefmech = mechs; + } +} + +/* + * sasl_state() + * + * This is the ONLY way to change SASL state! + */ +static void sasl_state(struct SASL *sasl, struct Curl_easy *data, + saslstate newstate) +{ +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + /* for debug purposes */ + static const char * const names[]={ + "STOP", + "PLAIN", + "LOGIN", + "LOGIN_PASSWD", + "EXTERNAL", + "CRAMMD5", + "DIGESTMD5", + "DIGESTMD5_RESP", + "NTLM", + "NTLM_TYPE2MSG", + "GSSAPI", + "GSSAPI_TOKEN", + "GSSAPI_NO_DATA", + "OAUTH2", + "OAUTH2_RESP", + "GSASL", + "CANCEL", + "FINAL", + /* LAST */ + }; + + if(sasl->state != newstate) + infof(data, "SASL %p state change from %s to %s", + (void *)sasl, names[sasl->state], names[newstate]); +#else + (void) data; +#endif + + sasl->state = newstate; +} + +#if defined(USE_NTLM) || defined(USE_GSASL) || defined(USE_KERBEROS5) || \ + !defined(CURL_DISABLE_DIGEST_AUTH) +/* Get the SASL server message and convert it to binary. */ +static CURLcode get_server_message(struct SASL *sasl, struct Curl_easy *data, + struct bufref *out) +{ + CURLcode result = CURLE_OK; + + result = sasl->params->getmessage(data, out); + if(!result && (sasl->params->flags & SASL_FLAG_BASE64)) { + unsigned char *msg; + size_t msglen; + const char *serverdata = (const char *) Curl_bufref_ptr(out); + + if(!*serverdata || *serverdata == '=') + Curl_bufref_set(out, NULL, 0, NULL); + else { + result = Curl_base64_decode(serverdata, &msg, &msglen); + if(!result) + Curl_bufref_set(out, msg, msglen, curl_free); + } + } + return result; +} +#endif + +/* Encode the outgoing SASL message. */ +static CURLcode build_message(struct SASL *sasl, struct bufref *msg) +{ + CURLcode result = CURLE_OK; + + if(sasl->params->flags & SASL_FLAG_BASE64) { + if(!Curl_bufref_ptr(msg)) /* Empty message. */ + Curl_bufref_set(msg, "", 0, NULL); + else if(!Curl_bufref_len(msg)) /* Explicit empty response. */ + Curl_bufref_set(msg, "=", 1, NULL); + else { + char *base64; + size_t base64len; + + result = Curl_base64_encode((const char *) Curl_bufref_ptr(msg), + Curl_bufref_len(msg), &base64, &base64len); + if(!result) + Curl_bufref_set(msg, base64, base64len, curl_free); + } + } + + return result; +} + +/* + * Curl_sasl_can_authenticate() + * + * Check if we have enough auth data and capabilities to authenticate. + */ +bool Curl_sasl_can_authenticate(struct SASL *sasl, struct Curl_easy *data) +{ + /* Have credentials been provided? */ + if(data->state.aptr.user) + return TRUE; + + /* EXTERNAL can authenticate without a user name and/or password */ + if(sasl->authmechs & sasl->prefmech & SASL_MECH_EXTERNAL) + return TRUE; + + return FALSE; +} + +/* + * Curl_sasl_start() + * + * Calculate the required login details for SASL authentication. + */ +CURLcode Curl_sasl_start(struct SASL *sasl, struct Curl_easy *data, + bool force_ir, saslprogress *progress) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + unsigned short enabledmechs; + const char *mech = NULL; + struct bufref resp; + saslstate state1 = SASL_STOP; + saslstate state2 = SASL_FINAL; + const char *hostname, *disp_hostname; + int port; +#if defined(USE_KERBEROS5) || defined(USE_NTLM) + const char *service = data->set.str[STRING_SERVICE_NAME] ? + data->set.str[STRING_SERVICE_NAME] : + sasl->params->service; +#endif + const char *oauth_bearer = data->set.str[STRING_BEARER]; + struct bufref nullmsg; + + Curl_conn_get_host(data, FIRSTSOCKET, &hostname, &disp_hostname, &port); + Curl_bufref_init(&nullmsg); + Curl_bufref_init(&resp); + sasl->force_ir = force_ir; /* Latch for future use */ + sasl->authused = 0; /* No mechanism used yet */ + enabledmechs = sasl->authmechs & sasl->prefmech; + *progress = SASL_IDLE; + + /* Calculate the supported authentication mechanism, by decreasing order of + security, as well as the initial response where appropriate */ + if((enabledmechs & SASL_MECH_EXTERNAL) && !conn->passwd[0]) { + mech = SASL_MECH_STRING_EXTERNAL; + state1 = SASL_EXTERNAL; + sasl->authused = SASL_MECH_EXTERNAL; + + if(force_ir || data->set.sasl_ir) + Curl_auth_create_external_message(conn->user, &resp); + } + else if(data->state.aptr.user) { +#if defined(USE_KERBEROS5) + if((enabledmechs & SASL_MECH_GSSAPI) && Curl_auth_is_gssapi_supported() && + Curl_auth_user_contains_domain(conn->user)) { + sasl->mutual_auth = FALSE; + mech = SASL_MECH_STRING_GSSAPI; + state1 = SASL_GSSAPI; + state2 = SASL_GSSAPI_TOKEN; + sasl->authused = SASL_MECH_GSSAPI; + + if(force_ir || data->set.sasl_ir) + result = Curl_auth_create_gssapi_user_message(data, conn->user, + conn->passwd, + service, + conn->host.name, + sasl->mutual_auth, + NULL, &conn->krb5, + &resp); + } + else +#endif +#ifdef USE_GSASL + if((enabledmechs & SASL_MECH_SCRAM_SHA_256) && + Curl_auth_gsasl_is_supported(data, SASL_MECH_STRING_SCRAM_SHA_256, + &conn->gsasl)) { + mech = SASL_MECH_STRING_SCRAM_SHA_256; + sasl->authused = SASL_MECH_SCRAM_SHA_256; + state1 = SASL_GSASL; + state2 = SASL_GSASL; + + result = Curl_auth_gsasl_start(data, conn->user, + conn->passwd, &conn->gsasl); + if(result == CURLE_OK && (force_ir || data->set.sasl_ir)) + result = Curl_auth_gsasl_token(data, &nullmsg, &conn->gsasl, &resp); + } + else if((enabledmechs & SASL_MECH_SCRAM_SHA_1) && + Curl_auth_gsasl_is_supported(data, SASL_MECH_STRING_SCRAM_SHA_1, + &conn->gsasl)) { + mech = SASL_MECH_STRING_SCRAM_SHA_1; + sasl->authused = SASL_MECH_SCRAM_SHA_1; + state1 = SASL_GSASL; + state2 = SASL_GSASL; + + result = Curl_auth_gsasl_start(data, conn->user, + conn->passwd, &conn->gsasl); + if(result == CURLE_OK && (force_ir || data->set.sasl_ir)) + result = Curl_auth_gsasl_token(data, &nullmsg, &conn->gsasl, &resp); + } + else +#endif +#ifndef CURL_DISABLE_DIGEST_AUTH + if((enabledmechs & SASL_MECH_DIGEST_MD5) && + Curl_auth_is_digest_supported()) { + mech = SASL_MECH_STRING_DIGEST_MD5; + state1 = SASL_DIGESTMD5; + sasl->authused = SASL_MECH_DIGEST_MD5; + } + else if(enabledmechs & SASL_MECH_CRAM_MD5) { + mech = SASL_MECH_STRING_CRAM_MD5; + state1 = SASL_CRAMMD5; + sasl->authused = SASL_MECH_CRAM_MD5; + } + else +#endif +#ifdef USE_NTLM + if((enabledmechs & SASL_MECH_NTLM) && Curl_auth_is_ntlm_supported()) { + mech = SASL_MECH_STRING_NTLM; + state1 = SASL_NTLM; + state2 = SASL_NTLM_TYPE2MSG; + sasl->authused = SASL_MECH_NTLM; + + if(force_ir || data->set.sasl_ir) + result = Curl_auth_create_ntlm_type1_message(data, + conn->user, conn->passwd, + service, + hostname, + &conn->ntlm, &resp); + } + else +#endif + if((enabledmechs & SASL_MECH_OAUTHBEARER) && oauth_bearer) { + mech = SASL_MECH_STRING_OAUTHBEARER; + state1 = SASL_OAUTH2; + state2 = SASL_OAUTH2_RESP; + sasl->authused = SASL_MECH_OAUTHBEARER; + + if(force_ir || data->set.sasl_ir) + result = Curl_auth_create_oauth_bearer_message(conn->user, + hostname, + port, + oauth_bearer, + &resp); + } + else if((enabledmechs & SASL_MECH_XOAUTH2) && oauth_bearer) { + mech = SASL_MECH_STRING_XOAUTH2; + state1 = SASL_OAUTH2; + sasl->authused = SASL_MECH_XOAUTH2; + + if(force_ir || data->set.sasl_ir) + result = Curl_auth_create_xoauth_bearer_message(conn->user, + oauth_bearer, + &resp); + } + else if(enabledmechs & SASL_MECH_PLAIN) { + mech = SASL_MECH_STRING_PLAIN; + state1 = SASL_PLAIN; + sasl->authused = SASL_MECH_PLAIN; + + if(force_ir || data->set.sasl_ir) + result = Curl_auth_create_plain_message(conn->sasl_authzid, + conn->user, conn->passwd, + &resp); + } + else if(enabledmechs & SASL_MECH_LOGIN) { + mech = SASL_MECH_STRING_LOGIN; + state1 = SASL_LOGIN; + state2 = SASL_LOGIN_PASSWD; + sasl->authused = SASL_MECH_LOGIN; + + if(force_ir || data->set.sasl_ir) + Curl_auth_create_login_message(conn->user, &resp); + } + } + + if(!result && mech) { + sasl->curmech = mech; + if(Curl_bufref_ptr(&resp)) + result = build_message(sasl, &resp); + + if(sasl->params->maxirlen && + strlen(mech) + Curl_bufref_len(&resp) > sasl->params->maxirlen) + Curl_bufref_free(&resp); + + if(!result) + result = sasl->params->sendauth(data, mech, &resp); + + if(!result) { + *progress = SASL_INPROGRESS; + sasl_state(sasl, data, Curl_bufref_ptr(&resp) ? state2 : state1); + } + } + + Curl_bufref_free(&resp); + return result; +} + +/* + * Curl_sasl_continue() + * + * Continue the authentication. + */ +CURLcode Curl_sasl_continue(struct SASL *sasl, struct Curl_easy *data, + int code, saslprogress *progress) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + saslstate newstate = SASL_FINAL; + struct bufref resp; + const char *hostname, *disp_hostname; + int port; +#if defined(USE_KERBEROS5) || defined(USE_NTLM) \ + || !defined(CURL_DISABLE_DIGEST_AUTH) + const char *service = data->set.str[STRING_SERVICE_NAME] ? + data->set.str[STRING_SERVICE_NAME] : + sasl->params->service; +#endif + const char *oauth_bearer = data->set.str[STRING_BEARER]; + struct bufref serverdata; + + Curl_conn_get_host(data, FIRSTSOCKET, &hostname, &disp_hostname, &port); + Curl_bufref_init(&serverdata); + Curl_bufref_init(&resp); + *progress = SASL_INPROGRESS; + + if(sasl->state == SASL_FINAL) { + if(code != sasl->params->finalcode) + result = CURLE_LOGIN_DENIED; + *progress = SASL_DONE; + sasl_state(sasl, data, SASL_STOP); + return result; + } + + if(sasl->state != SASL_CANCEL && sasl->state != SASL_OAUTH2_RESP && + code != sasl->params->contcode) { + *progress = SASL_DONE; + sasl_state(sasl, data, SASL_STOP); + return CURLE_LOGIN_DENIED; + } + + switch(sasl->state) { + case SASL_STOP: + *progress = SASL_DONE; + return result; + case SASL_PLAIN: + result = Curl_auth_create_plain_message(conn->sasl_authzid, + conn->user, conn->passwd, &resp); + break; + case SASL_LOGIN: + Curl_auth_create_login_message(conn->user, &resp); + newstate = SASL_LOGIN_PASSWD; + break; + case SASL_LOGIN_PASSWD: + Curl_auth_create_login_message(conn->passwd, &resp); + break; + case SASL_EXTERNAL: + Curl_auth_create_external_message(conn->user, &resp); + break; +#ifdef USE_GSASL + case SASL_GSASL: + result = get_server_message(sasl, data, &serverdata); + if(!result) + result = Curl_auth_gsasl_token(data, &serverdata, &conn->gsasl, &resp); + if(!result && Curl_bufref_len(&resp) > 0) + newstate = SASL_GSASL; + break; +#endif +#ifndef CURL_DISABLE_DIGEST_AUTH + case SASL_CRAMMD5: + result = get_server_message(sasl, data, &serverdata); + if(!result) + result = Curl_auth_create_cram_md5_message(&serverdata, conn->user, + conn->passwd, &resp); + break; + case SASL_DIGESTMD5: + result = get_server_message(sasl, data, &serverdata); + if(!result) + result = Curl_auth_create_digest_md5_message(data, &serverdata, + conn->user, conn->passwd, + service, &resp); + if(!result && (sasl->params->flags & SASL_FLAG_BASE64)) + newstate = SASL_DIGESTMD5_RESP; + break; + case SASL_DIGESTMD5_RESP: + /* Keep response NULL to output an empty line. */ + break; +#endif + +#ifdef USE_NTLM + case SASL_NTLM: + /* Create the type-1 message */ + result = Curl_auth_create_ntlm_type1_message(data, + conn->user, conn->passwd, + service, hostname, + &conn->ntlm, &resp); + newstate = SASL_NTLM_TYPE2MSG; + break; + case SASL_NTLM_TYPE2MSG: + /* Decode the type-2 message */ + result = get_server_message(sasl, data, &serverdata); + if(!result) + result = Curl_auth_decode_ntlm_type2_message(data, &serverdata, + &conn->ntlm); + if(!result) + result = Curl_auth_create_ntlm_type3_message(data, conn->user, + conn->passwd, &conn->ntlm, + &resp); + break; +#endif + +#if defined(USE_KERBEROS5) + case SASL_GSSAPI: + result = Curl_auth_create_gssapi_user_message(data, conn->user, + conn->passwd, + service, + conn->host.name, + sasl->mutual_auth, NULL, + &conn->krb5, + &resp); + newstate = SASL_GSSAPI_TOKEN; + break; + case SASL_GSSAPI_TOKEN: + result = get_server_message(sasl, data, &serverdata); + if(!result) { + if(sasl->mutual_auth) { + /* Decode the user token challenge and create the optional response + message */ + result = Curl_auth_create_gssapi_user_message(data, NULL, NULL, + NULL, NULL, + sasl->mutual_auth, + &serverdata, + &conn->krb5, + &resp); + newstate = SASL_GSSAPI_NO_DATA; + } + else + /* Decode the security challenge and create the response message */ + result = Curl_auth_create_gssapi_security_message(data, + conn->sasl_authzid, + &serverdata, + &conn->krb5, + &resp); + } + break; + case SASL_GSSAPI_NO_DATA: + /* Decode the security challenge and create the response message */ + result = get_server_message(sasl, data, &serverdata); + if(!result) + result = Curl_auth_create_gssapi_security_message(data, + conn->sasl_authzid, + &serverdata, + &conn->krb5, + &resp); + break; +#endif + + case SASL_OAUTH2: + /* Create the authorization message */ + if(sasl->authused == SASL_MECH_OAUTHBEARER) { + result = Curl_auth_create_oauth_bearer_message(conn->user, + hostname, + port, + oauth_bearer, + &resp); + + /* Failures maybe sent by the server as continuations for OAUTHBEARER */ + newstate = SASL_OAUTH2_RESP; + } + else + result = Curl_auth_create_xoauth_bearer_message(conn->user, + oauth_bearer, + &resp); + break; + + case SASL_OAUTH2_RESP: + /* The continuation is optional so check the response code */ + if(code == sasl->params->finalcode) { + /* Final response was received so we are done */ + *progress = SASL_DONE; + sasl_state(sasl, data, SASL_STOP); + return result; + } + else if(code == sasl->params->contcode) { + /* Acknowledge the continuation by sending a 0x01 response. */ + Curl_bufref_set(&resp, "\x01", 1, NULL); + break; + } + else { + *progress = SASL_DONE; + sasl_state(sasl, data, SASL_STOP); + return CURLE_LOGIN_DENIED; + } + + case SASL_CANCEL: + /* Remove the offending mechanism from the supported list */ + sasl->authmechs ^= sasl->authused; + + /* Start an alternative SASL authentication */ + return Curl_sasl_start(sasl, data, sasl->force_ir, progress); + default: + failf(data, "Unsupported SASL authentication mechanism"); + result = CURLE_UNSUPPORTED_PROTOCOL; /* Should not happen */ + break; + } + + Curl_bufref_free(&serverdata); + + switch(result) { + case CURLE_BAD_CONTENT_ENCODING: + /* Cancel dialog */ + result = sasl->params->cancelauth(data, sasl->curmech); + newstate = SASL_CANCEL; + break; + case CURLE_OK: + result = build_message(sasl, &resp); + if(!result) + result = sasl->params->contauth(data, sasl->curmech, &resp); + break; + default: + newstate = SASL_STOP; /* Stop on error */ + *progress = SASL_DONE; + break; + } + + Curl_bufref_free(&resp); + + sasl_state(sasl, data, newstate); + + return result; +} +#endif /* protocols are enabled that use SASL */ diff --git a/third_party/curl/lib/curl_sasl.h b/third_party/curl/lib/curl_sasl.h new file mode 100644 index 0000000..e94e643 --- /dev/null +++ b/third_party/curl/lib/curl_sasl.h @@ -0,0 +1,165 @@ +#ifndef HEADER_CURL_SASL_H +#define HEADER_CURL_SASL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include + +#include "bufref.h" + +struct Curl_easy; +struct connectdata; + +/* Authentication mechanism flags */ +#define SASL_MECH_LOGIN (1 << 0) +#define SASL_MECH_PLAIN (1 << 1) +#define SASL_MECH_CRAM_MD5 (1 << 2) +#define SASL_MECH_DIGEST_MD5 (1 << 3) +#define SASL_MECH_GSSAPI (1 << 4) +#define SASL_MECH_EXTERNAL (1 << 5) +#define SASL_MECH_NTLM (1 << 6) +#define SASL_MECH_XOAUTH2 (1 << 7) +#define SASL_MECH_OAUTHBEARER (1 << 8) +#define SASL_MECH_SCRAM_SHA_1 (1 << 9) +#define SASL_MECH_SCRAM_SHA_256 (1 << 10) + +/* Authentication mechanism values */ +#define SASL_AUTH_NONE 0 +#define SASL_AUTH_ANY 0xffff +#define SASL_AUTH_DEFAULT (SASL_AUTH_ANY & ~SASL_MECH_EXTERNAL) + +/* Authentication mechanism strings */ +#define SASL_MECH_STRING_LOGIN "LOGIN" +#define SASL_MECH_STRING_PLAIN "PLAIN" +#define SASL_MECH_STRING_CRAM_MD5 "CRAM-MD5" +#define SASL_MECH_STRING_DIGEST_MD5 "DIGEST-MD5" +#define SASL_MECH_STRING_GSSAPI "GSSAPI" +#define SASL_MECH_STRING_EXTERNAL "EXTERNAL" +#define SASL_MECH_STRING_NTLM "NTLM" +#define SASL_MECH_STRING_XOAUTH2 "XOAUTH2" +#define SASL_MECH_STRING_OAUTHBEARER "OAUTHBEARER" +#define SASL_MECH_STRING_SCRAM_SHA_1 "SCRAM-SHA-1" +#define SASL_MECH_STRING_SCRAM_SHA_256 "SCRAM-SHA-256" + +/* SASL flags */ +#define SASL_FLAG_BASE64 0x0001 /* Messages are base64-encoded */ + +/* SASL machine states */ +typedef enum { + SASL_STOP, + SASL_PLAIN, + SASL_LOGIN, + SASL_LOGIN_PASSWD, + SASL_EXTERNAL, + SASL_CRAMMD5, + SASL_DIGESTMD5, + SASL_DIGESTMD5_RESP, + SASL_NTLM, + SASL_NTLM_TYPE2MSG, + SASL_GSSAPI, + SASL_GSSAPI_TOKEN, + SASL_GSSAPI_NO_DATA, + SASL_OAUTH2, + SASL_OAUTH2_RESP, + SASL_GSASL, + SASL_CANCEL, + SASL_FINAL +} saslstate; + +/* Progress indicator */ +typedef enum { + SASL_IDLE, + SASL_INPROGRESS, + SASL_DONE +} saslprogress; + +/* Protocol dependent SASL parameters */ +struct SASLproto { + const char *service; /* The service name */ + CURLcode (*sendauth)(struct Curl_easy *data, const char *mech, + const struct bufref *ir); + /* Send authentication command */ + CURLcode (*contauth)(struct Curl_easy *data, const char *mech, + const struct bufref *contauth); + /* Send authentication continuation */ + CURLcode (*cancelauth)(struct Curl_easy *data, const char *mech); + /* Cancel authentication. */ + CURLcode (*getmessage)(struct Curl_easy *data, struct bufref *out); + /* Get SASL response message */ + size_t maxirlen; /* Maximum initial response + mechanism length, + or zero if no max. This is normally the max + command length - other characters count. + This has to be zero for non-base64 protocols. */ + int contcode; /* Code to receive when continuation is expected */ + int finalcode; /* Code to receive upon authentication success */ + unsigned short defmechs; /* Mechanisms enabled by default */ + unsigned short flags; /* Configuration flags. */ +}; + +/* Per-connection parameters */ +struct SASL { + const struct SASLproto *params; /* Protocol dependent parameters */ + saslstate state; /* Current machine state */ + const char *curmech; /* Current mechanism id. */ + unsigned short authmechs; /* Accepted authentication mechanisms */ + unsigned short prefmech; /* Preferred authentication mechanism */ + unsigned short authused; /* Auth mechanism used for the connection */ + BIT(resetprefs); /* For URL auth option parsing. */ + BIT(mutual_auth); /* Mutual authentication enabled (GSSAPI only) */ + BIT(force_ir); /* Protocol always supports initial response */ +}; + +/* This is used to test whether the line starts with the given mechanism */ +#define sasl_mech_equal(line, wordlen, mech) \ + (wordlen == (sizeof(mech) - 1) / sizeof(char) && \ + !memcmp(line, mech, wordlen)) + +/* This is used to cleanup any libraries or curl modules used by the sasl + functions */ +void Curl_sasl_cleanup(struct connectdata *conn, unsigned short authused); + +/* Convert a mechanism name to a token */ +unsigned short Curl_sasl_decode_mech(const char *ptr, + size_t maxlen, size_t *len); + +/* Parse the URL login options */ +CURLcode Curl_sasl_parse_url_auth_option(struct SASL *sasl, + const char *value, size_t len); + +/* Initializes an SASL structure */ +void Curl_sasl_init(struct SASL *sasl, struct Curl_easy *data, + const struct SASLproto *params); + +/* Check if we have enough auth data and capabilities to authenticate */ +bool Curl_sasl_can_authenticate(struct SASL *sasl, struct Curl_easy *data); + +/* Calculate the required login details for SASL authentication */ +CURLcode Curl_sasl_start(struct SASL *sasl, struct Curl_easy *data, + bool force_ir, saslprogress *progress); + +/* Continue an SASL authentication */ +CURLcode Curl_sasl_continue(struct SASL *sasl, struct Curl_easy *data, + int code, saslprogress *progress); + +#endif /* HEADER_CURL_SASL_H */ diff --git a/third_party/curl/lib/curl_setup.h b/third_party/curl/lib/curl_setup.h new file mode 100644 index 0000000..6c05b87 --- /dev/null +++ b/third_party/curl/lib/curl_setup.h @@ -0,0 +1,921 @@ +#ifndef HEADER_CURL_SETUP_H +#define HEADER_CURL_SETUP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#if defined(BUILDING_LIBCURL) && !defined(CURL_NO_OLDIES) +#define CURL_NO_OLDIES +#endif + +/* FIXME: Delete this once the warnings have been fixed. */ +#if !defined(CURL_WARN_SIGN_CONVERSION) +#ifdef __GNUC__ +#pragma GCC diagnostic ignored "-Wsign-conversion" +#endif +#endif + +/* Set default _WIN32_WINNT */ +#ifdef __MINGW32__ +#include <_mingw.h> +#endif + +/* + * Disable Visual Studio warnings: + * 4127 "conditional expression is constant" + */ +#ifdef _MSC_VER +#pragma warning(disable:4127) +#endif + +#ifdef _WIN32 +/* + * Don't include unneeded stuff in Windows headers to avoid compiler + * warnings and macro clashes. + * Make sure to define this macro before including any Windows headers. + */ +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# ifndef NOGDI +# define NOGDI +# endif +/* Detect Windows App environment which has a restricted access + * to the Win32 APIs. */ +# if (defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0602)) || \ + defined(WINAPI_FAMILY) +# include +# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \ + !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +# define CURL_WINDOWS_APP +# endif +# endif +#endif + +/* Compatibility */ +#if defined(ENABLE_IPV6) +# define USE_IPV6 1 +#endif + +/* + * Include configuration script results or hand-crafted + * configuration file for platforms which lack config tool. + */ + +#ifdef HAVE_CONFIG_H + +#include "curl_config.h" + +#else /* HAVE_CONFIG_H */ + +#ifdef _WIN32_WCE +# include "config-win32ce.h" +#else +# ifdef _WIN32 +# include "config-win32.h" +# endif +#endif + +#ifdef macintosh +# include "config-mac.h" +#endif + +#ifdef __riscos__ +# include "config-riscos.h" +#endif + +#ifdef __AMIGA__ +# include "config-amigaos.h" +#endif + +#ifdef __OS400__ +# include "config-os400.h" +#endif + +#ifdef __PLAN9__ +# include "config-plan9.h" +#endif + +#ifdef MSDOS +# include "config-dos.h" +#endif + +#endif /* HAVE_CONFIG_H */ + +/* ================================================================ */ +/* Definition of preprocessor macros/symbols which modify compiler */ +/* behavior or generated code characteristics must be done here, */ +/* as appropriate, before any system header file is included. It is */ +/* also possible to have them defined in the config file included */ +/* before this point. As a result of all this we frown inclusion of */ +/* system header files in our config files, avoid this at any cost. */ +/* ================================================================ */ + +/* + * AIX 4.3 and newer needs _THREAD_SAFE defined to build + * proper reentrant code. Others may also need it. + */ + +#ifdef NEED_THREAD_SAFE +# ifndef _THREAD_SAFE +# define _THREAD_SAFE +# endif +#endif + +/* + * Tru64 needs _REENTRANT set for a few function prototypes and + * things to appear in the system header files. Unixware needs it + * to build proper reentrant code. Others may also need it. + */ + +#ifdef NEED_REENTRANT +# ifndef _REENTRANT +# define _REENTRANT +# endif +#endif + +/* Solaris needs this to get a POSIX-conformant getpwuid_r */ +#if defined(sun) || defined(__sun) +# ifndef _POSIX_PTHREAD_SEMANTICS +# define _POSIX_PTHREAD_SEMANTICS 1 +# endif +#endif + +/* ================================================================ */ +/* If you need to include a system header file for your platform, */ +/* please, do it beyond the point further indicated in this file. */ +/* ================================================================ */ + +/* + * Disable other protocols when http is the only one desired. + */ + +#ifdef HTTP_ONLY +# ifndef CURL_DISABLE_DICT +# define CURL_DISABLE_DICT +# endif +# ifndef CURL_DISABLE_FILE +# define CURL_DISABLE_FILE +# endif +# ifndef CURL_DISABLE_FTP +# define CURL_DISABLE_FTP +# endif +# ifndef CURL_DISABLE_GOPHER +# define CURL_DISABLE_GOPHER +# endif +# ifndef CURL_DISABLE_IMAP +# define CURL_DISABLE_IMAP +# endif +# ifndef CURL_DISABLE_LDAP +# define CURL_DISABLE_LDAP +# endif +# ifndef CURL_DISABLE_LDAPS +# define CURL_DISABLE_LDAPS +# endif +# ifndef CURL_DISABLE_MQTT +# define CURL_DISABLE_MQTT +# endif +# ifndef CURL_DISABLE_POP3 +# define CURL_DISABLE_POP3 +# endif +# ifndef CURL_DISABLE_RTSP +# define CURL_DISABLE_RTSP +# endif +# ifndef CURL_DISABLE_SMB +# define CURL_DISABLE_SMB +# endif +# ifndef CURL_DISABLE_SMTP +# define CURL_DISABLE_SMTP +# endif +# ifndef CURL_DISABLE_TELNET +# define CURL_DISABLE_TELNET +# endif +# ifndef CURL_DISABLE_TFTP +# define CURL_DISABLE_TFTP +# endif +#endif + +/* + * When http is disabled rtsp is not supported. + */ + +#if defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_RTSP) +# define CURL_DISABLE_RTSP +#endif + +/* + * When HTTP is disabled, disable HTTP-only features + */ + +#if defined(CURL_DISABLE_HTTP) +# define CURL_DISABLE_ALTSVC 1 +# define CURL_DISABLE_COOKIES 1 +# define CURL_DISABLE_BASIC_AUTH 1 +# define CURL_DISABLE_BEARER_AUTH 1 +# define CURL_DISABLE_AWS 1 +# define CURL_DISABLE_DOH 1 +# define CURL_DISABLE_FORM_API 1 +# define CURL_DISABLE_HEADERS_API 1 +# define CURL_DISABLE_HSTS 1 +# define CURL_DISABLE_HTTP_AUTH 1 +#endif + +/* ================================================================ */ +/* No system header file shall be included in this file before this */ +/* point. */ +/* ================================================================ */ + +/* + * OS/400 setup file includes some system headers. + */ + +#ifdef __OS400__ +# include "setup-os400.h" +#endif + +/* + * VMS setup file includes some system headers. + */ + +#ifdef __VMS +# include "setup-vms.h" +#endif + +/* + * Windows setup file includes some system headers. + */ + +#ifdef _WIN32 +# include "setup-win32.h" +#endif + +#include + +/* Helper macro to expand and concatenate two macros. + * Direct macros concatenation does not work because macros + * are not expanded before direct concatenation. + */ +#define CURL_CONC_MACROS_(A,B) A ## B +#define CURL_CONC_MACROS(A,B) CURL_CONC_MACROS_(A,B) + +/* curl uses its own printf() function internally. It understands the GNU + * format. Use this format, so that is matches the GNU format attribute we + * use with the mingw compiler, allowing it to verify them at compile-time. + */ +#ifdef __MINGW32__ +# undef CURL_FORMAT_CURL_OFF_T +# undef CURL_FORMAT_CURL_OFF_TU +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +#endif + +/* based on logic in "curl/mprintf.h" */ + +#if (defined(__GNUC__) || defined(__clang__) || \ + defined(__IAR_SYSTEMS_ICC__)) && \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(CURL_NO_FMT_CHECKS) +#if defined(__MINGW32__) && !defined(__clang__) +#define CURL_PRINTF(fmt, arg) \ + __attribute__((format(gnu_printf, fmt, arg))) +#else +#define CURL_PRINTF(fmt, arg) \ + __attribute__((format(__printf__, fmt, arg))) +#endif +#else +#define CURL_PRINTF(fmt, arg) +#endif + +/* + * Use getaddrinfo to resolve the IPv4 address literal. If the current network + * interface doesn't support IPv4, but supports IPv6, NAT64, and DNS64, + * performing this task will result in a synthesized IPv6 address. + */ +#if defined(__APPLE__) && !defined(USE_ARES) +#include +#define USE_RESOLVE_ON_IPS 1 +# if TARGET_OS_MAC && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && \ + defined(USE_IPV6) +# define CURL_MACOS_CALL_COPYPROXIES 1 +# endif +#endif + +#ifdef USE_LWIPSOCK +# include +# include +# include +#endif + +#ifdef HAVE_EXTRA_STRICMP_H +# include +#endif + +#ifdef HAVE_EXTRA_STRDUP_H +# include +#endif + +#ifdef __AMIGA__ +# ifdef __amigaos4__ +# define __USE_INLINE__ + /* use our own resolver which uses runtime feature detection */ +# define CURLRES_AMIGA + /* getaddrinfo() currently crashes bsdsocket.library, so disable */ +# undef HAVE_GETADDRINFO +# if !(defined(__NEWLIB__) || \ + (defined(__CLIB2__) && defined(__THREAD_SAFE))) + /* disable threaded resolver with clib2 - requires newlib or clib-ts */ +# undef USE_THREADS_POSIX +# endif +# endif +# include +# include +# include +# include +# include +# if defined(HAVE_PROTO_BSDSOCKET_H) && \ + (!defined(__amigaos4__) || defined(USE_AMISSL)) + /* use bsdsocket.library directly, instead of libc networking functions */ +# define _SYS_MBUF_H /* m_len define clashes with curl */ +# include +# ifdef __amigaos4__ + int Curl_amiga_select(int nfds, fd_set *readfds, fd_set *writefds, + fd_set *errorfds, struct timeval *timeout); +# define select(a,b,c,d,e) Curl_amiga_select(a,b,c,d,e) +# else +# define select(a,b,c,d,e) WaitSelect(a,b,c,d,e,0) +# endif + /* must not use libc's fcntl() on bsdsocket.library sockfds! */ +# undef HAVE_FCNTL +# undef HAVE_FCNTL_O_NONBLOCK +# else + /* use libc networking and hence close() and fnctl() */ +# undef HAVE_CLOSESOCKET_CAMEL +# undef HAVE_IOCTLSOCKET_CAMEL +# endif +/* + * In clib2 arpa/inet.h warns that some prototypes may clash + * with bsdsocket.library. This avoids the definition of those. + */ +# define __NO_NET_API +#endif + +#include +#include + +#ifdef __TANDEM /* for ns*-tandem-nsk systems */ +# if ! defined __LP64 +# include /* FLOSS is only used for 32-bit builds. */ +# endif +#endif + +#ifndef STDC_HEADERS /* no standard C headers! */ +#include +#endif + +/* + * Large file (>2Gb) support using WIN32 functions. + */ + +#ifdef USE_WIN32_LARGE_FILES +# include +# include +# include +# undef lseek +# define lseek(fdes,offset,whence) _lseeki64(fdes, offset, whence) +# undef fstat +# define fstat(fdes,stp) _fstati64(fdes, stp) +# undef stat +# define stat(fname,stp) curlx_win32_stat(fname, stp) +# define struct_stat struct _stati64 +# define LSEEK_ERROR (__int64)-1 +# define open curlx_win32_open +# define fopen(fname,mode) curlx_win32_fopen(fname, mode) + int curlx_win32_open(const char *filename, int oflag, ...); + int curlx_win32_stat(const char *path, struct_stat *buffer); + FILE *curlx_win32_fopen(const char *filename, const char *mode); +#endif + +/* + * Small file (<2Gb) support using WIN32 functions. + */ + +#ifdef USE_WIN32_SMALL_FILES +# include +# include +# include +# ifndef _WIN32_WCE +# undef lseek +# define lseek(fdes,offset,whence) _lseek(fdes, (long)offset, whence) +# define fstat(fdes,stp) _fstat(fdes, stp) +# define stat(fname,stp) curlx_win32_stat(fname, stp) +# define struct_stat struct _stat +# define open curlx_win32_open +# define fopen(fname,mode) curlx_win32_fopen(fname, mode) + int curlx_win32_stat(const char *path, struct_stat *buffer); + int curlx_win32_open(const char *filename, int oflag, ...); + FILE *curlx_win32_fopen(const char *filename, const char *mode); +# endif +# define LSEEK_ERROR (long)-1 +#endif + +#ifndef struct_stat +# define struct_stat struct stat +#endif + +#ifndef LSEEK_ERROR +# define LSEEK_ERROR (off_t)-1 +#endif + +#ifndef SIZEOF_TIME_T +/* assume default size of time_t to be 32 bit */ +#define SIZEOF_TIME_T 4 +#endif + +#ifndef SIZEOF_CURL_SOCKET_T +/* configure and cmake check and set the define */ +# ifdef _WIN64 +# define SIZEOF_CURL_SOCKET_T 8 +# else +/* default guess */ +# define SIZEOF_CURL_SOCKET_T 4 +# endif +#endif + +#if SIZEOF_CURL_SOCKET_T < 8 +# define CURL_FORMAT_SOCKET_T "d" +#elif defined(__MINGW32__) +# define CURL_FORMAT_SOCKET_T "zd" +#else +# define CURL_FORMAT_SOCKET_T "qd" +#endif + +/* + * Default sizeof(off_t) in case it hasn't been defined in config file. + */ + +#ifndef SIZEOF_OFF_T +# if defined(__VMS) && !defined(__VAX) +# if defined(_LARGEFILE) +# define SIZEOF_OFF_T 8 +# endif +# elif defined(__OS400__) && defined(__ILEC400__) +# if defined(_LARGE_FILES) +# define SIZEOF_OFF_T 8 +# endif +# elif defined(__MVS__) && defined(__IBMC__) +# if defined(_LP64) || defined(_LARGE_FILES) +# define SIZEOF_OFF_T 8 +# endif +# elif defined(__370__) && defined(__IBMC__) +# if defined(_LP64) || defined(_LARGE_FILES) +# define SIZEOF_OFF_T 8 +# endif +# endif +# ifndef SIZEOF_OFF_T +# define SIZEOF_OFF_T 4 +# endif +#endif + +#if (SIZEOF_CURL_OFF_T < 8) +#error "too small curl_off_t" +#else + /* assume SIZEOF_CURL_OFF_T == 8 */ +# define CURL_OFF_T_MAX CURL_OFF_T_C(0x7FFFFFFFFFFFFFFF) +#endif +#define CURL_OFF_T_MIN (-CURL_OFF_T_MAX - CURL_OFF_T_C(1)) + +#if (SIZEOF_CURL_OFF_T != 8) +# error "curl_off_t must be exactly 64 bits" +#else + typedef unsigned CURL_TYPEOF_CURL_OFF_T curl_uint64_t; + typedef CURL_TYPEOF_CURL_OFF_T curl_int64_t; +# ifndef CURL_SUFFIX_CURL_OFF_TU +# error "CURL_SUFFIX_CURL_OFF_TU must be defined" +# endif +# define CURL_UINT64_SUFFIX CURL_SUFFIX_CURL_OFF_TU +# define CURL_UINT64_C(val) CURL_CONC_MACROS(val,CURL_UINT64_SUFFIX) +# define CURL_PRId64 CURL_FORMAT_CURL_OFF_T +# define CURL_PRIu64 CURL_FORMAT_CURL_OFF_TU +#endif + +#if (SIZEOF_TIME_T == 4) +# ifdef HAVE_TIME_T_UNSIGNED +# define TIME_T_MAX UINT_MAX +# define TIME_T_MIN 0 +# else +# define TIME_T_MAX INT_MAX +# define TIME_T_MIN INT_MIN +# endif +#else +# ifdef HAVE_TIME_T_UNSIGNED +# define TIME_T_MAX 0xFFFFFFFFFFFFFFFF +# define TIME_T_MIN 0 +# else +# define TIME_T_MAX 0x7FFFFFFFFFFFFFFF +# define TIME_T_MIN (-TIME_T_MAX - 1) +# endif +#endif + +#ifndef SIZE_T_MAX +/* some limits.h headers have this defined, some don't */ +#if defined(SIZEOF_SIZE_T) && (SIZEOF_SIZE_T > 4) +#define SIZE_T_MAX 18446744073709551615U +#else +#define SIZE_T_MAX 4294967295U +#endif +#endif + +#ifndef SSIZE_T_MAX +/* some limits.h headers have this defined, some don't */ +#if defined(SIZEOF_SIZE_T) && (SIZEOF_SIZE_T > 4) +#define SSIZE_T_MAX 9223372036854775807 +#else +#define SSIZE_T_MAX 2147483647 +#endif +#endif + +/* + * Arg 2 type for gethostname in case it hasn't been defined in config file. + */ + +#ifndef GETHOSTNAME_TYPE_ARG2 +# ifdef USE_WINSOCK +# define GETHOSTNAME_TYPE_ARG2 int +# else +# define GETHOSTNAME_TYPE_ARG2 size_t +# endif +#endif + +/* Below we define some functions. They should + + 4. set the SIGALRM signal timeout + 5. set dir/file naming defines + */ + +#ifdef _WIN32 + +# define DIR_CHAR "\\" + +#else /* _WIN32 */ + +# ifdef MSDOS /* Watt-32 */ + +# include +# define select(n,r,w,x,t) select_s(n,r,w,x,t) +# define ioctl(x,y,z) ioctlsocket(x,y,(char *)(z)) +# include +# ifdef word +# undef word +# endif +# ifdef byte +# undef byte +# endif + +# endif /* MSDOS */ + +# ifdef __minix + /* Minix 3 versions up to at least 3.1.3 are missing these prototypes */ + extern char *strtok_r(char *s, const char *delim, char **last); + extern struct tm *gmtime_r(const time_t * const timep, struct tm *tmp); +# endif + +# define DIR_CHAR "/" + +#endif /* _WIN32 */ + +/* ---------------------------------------------------------------- */ +/* resolver specialty compile-time defines */ +/* CURLRES_* defines to use in the host*.c sources */ +/* ---------------------------------------------------------------- */ + +/* + * MSVC threads support requires a multi-threaded runtime library. + * _beginthreadex() is not available in single-threaded ones. + */ + +#if defined(_MSC_VER) && !defined(_MT) +# undef USE_THREADS_POSIX +# undef USE_THREADS_WIN32 +#endif + +/* + * Mutually exclusive CURLRES_* definitions. + */ + +#if defined(USE_IPV6) && defined(HAVE_GETADDRINFO) +# define CURLRES_IPV6 +#elif defined(USE_IPV6) && (defined(_WIN32) || defined(__CYGWIN__)) +/* assume on Windows that IPv6 without getaddrinfo is a broken build */ +# error "Unexpected build: IPv6 is enabled but getaddrinfo was not found." +#else +# define CURLRES_IPV4 +#endif + +#ifdef USE_ARES +# define CURLRES_ASYNCH +# define CURLRES_ARES +/* now undef the stock libc functions just to avoid them being used */ +# undef HAVE_GETADDRINFO +# undef HAVE_FREEADDRINFO +#elif defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32) +# define CURLRES_ASYNCH +# define CURLRES_THREADED +#else +# define CURLRES_SYNCH +#endif + +/* ---------------------------------------------------------------- */ + +#if defined(HAVE_LIBIDN2) && defined(HAVE_IDN2_H) && \ + !defined(USE_WIN32_IDN) && !defined(USE_APPLE_IDN) +/* The lib and header are present */ +#define USE_LIBIDN2 +#endif + +#if defined(USE_LIBIDN2) && (defined(USE_WIN32_IDN) || defined(USE_APPLE_IDN)) +#error "libidn2 cannot be enabled with WinIDN or AppleIDN, choose one." +#endif + +#define LIBIDN_REQUIRED_VERSION "0.4.1" + +#if defined(USE_GNUTLS) || defined(USE_OPENSSL) || defined(USE_MBEDTLS) || \ + defined(USE_WOLFSSL) || defined(USE_SCHANNEL) || defined(USE_SECTRANSP) || \ + defined(USE_BEARSSL) || defined(USE_RUSTLS) +#define USE_SSL /* SSL support has been enabled */ +#endif + +/* Single point where USE_SPNEGO definition might be defined */ +#if !defined(CURL_DISABLE_NEGOTIATE_AUTH) && \ + (defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)) +#define USE_SPNEGO +#endif + +/* Single point where USE_KERBEROS5 definition might be defined */ +#if !defined(CURL_DISABLE_KERBEROS_AUTH) && \ + (defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)) +#define USE_KERBEROS5 +#endif + +/* Single point where USE_NTLM definition might be defined */ +#if !defined(CURL_DISABLE_NTLM) +# if defined(USE_OPENSSL) || defined(USE_MBEDTLS) || \ + defined(USE_GNUTLS) || defined(USE_SECTRANSP) || \ + defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO) || \ + (defined(USE_WOLFSSL) && defined(HAVE_WOLFSSL_DES_ECB_ENCRYPT)) +# define USE_CURL_NTLM_CORE +# endif +# if defined(USE_CURL_NTLM_CORE) || defined(USE_WINDOWS_SSPI) +# define USE_NTLM +# endif +#endif + +#ifdef CURL_WANTS_CA_BUNDLE_ENV +#error "No longer supported. Set CURLOPT_CAINFO at runtime instead." +#endif + +#if defined(USE_LIBSSH2) || defined(USE_LIBSSH) || defined(USE_WOLFSSH) +#define USE_SSH +#endif + +/* + * Provide a mechanism to silence picky compilers, such as gcc 4.6+. + * Parameters should of course normally not be unused, but for example when + * we have multiple implementations of the same interface it may happen. + */ + +#if defined(__GNUC__) && ((__GNUC__ >= 3) || \ + ((__GNUC__ == 2) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ >= 7))) +# define UNUSED_PARAM __attribute__((__unused__)) +# define WARN_UNUSED_RESULT __attribute__((warn_unused_result)) +#elif defined(__IAR_SYSTEMS_ICC__) +# define UNUSED_PARAM __attribute__((__unused__)) +# if (__VER__ >= 9040001) +# define WARN_UNUSED_RESULT __attribute__((warn_unused_result)) +# else +# define WARN_UNUSED_RESULT +# endif +#else +# define UNUSED_PARAM /* NOTHING */ +# define WARN_UNUSED_RESULT +#endif + +/* noreturn attribute */ + +#if !defined(CURL_NORETURN) +#if (defined(__GNUC__) && (__GNUC__ >= 3)) || defined(__clang__) || \ + defined(__IAR_SYSTEMS_ICC__) +# define CURL_NORETURN __attribute__((__noreturn__)) +#elif defined(_MSC_VER) && (_MSC_VER >= 1200) +# define CURL_NORETURN __declspec(noreturn) +#else +# define CURL_NORETURN +#endif +#endif + +/* fallthrough attribute */ + +#if !defined(FALLTHROUGH) +#if (defined(__GNUC__) && __GNUC__ >= 7) || \ + (defined(__clang__) && __clang_major__ >= 10) +# define FALLTHROUGH() __attribute__((fallthrough)) +#else +# define FALLTHROUGH() do {} while (0) +#endif +#endif + +/* + * Include macros and defines that should only be processed once. + */ + +#ifndef HEADER_CURL_SETUP_ONCE_H +#include "curl_setup_once.h" +#endif + +/* + * Definition of our NOP statement Object-like macro + */ + +#ifndef Curl_nop_stmt +# define Curl_nop_stmt do { } while(0) +#endif + +/* + * Ensure that Winsock and lwIP TCP/IP stacks are not mixed. + */ + +#if defined(__LWIP_OPT_H__) || defined(LWIP_HDR_OPT_H) +# if defined(SOCKET) || defined(USE_WINSOCK) +# error "WinSock and lwIP TCP/IP stack definitions shall not coexist!" +# endif +#endif + +/* + * shutdown() flags for systems that don't define them + */ + +#ifndef SHUT_RD +#define SHUT_RD 0x00 +#endif + +#ifndef SHUT_WR +#define SHUT_WR 0x01 +#endif + +#ifndef SHUT_RDWR +#define SHUT_RDWR 0x02 +#endif + +/* Define S_ISREG if not defined by system headers, e.g. MSVC */ +#if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG) +#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) +#endif + +/* Define S_ISDIR if not defined by system headers, e.g. MSVC */ +#if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR) +#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) +#endif + +/* In Windows the default file mode is text but an application can override it. +Therefore we specify it explicitly. https://github.com/curl/curl/pull/258 +*/ +#if defined(_WIN32) || defined(MSDOS) +#define FOPEN_READTEXT "rt" +#define FOPEN_WRITETEXT "wt" +#define FOPEN_APPENDTEXT "at" +#elif defined(__CYGWIN__) +/* Cygwin has specific behavior we need to address when WIN32 is not defined. +https://cygwin.com/cygwin-ug-net/using-textbinary.html +For write we want our output to have line endings of LF and be compatible with +other Cygwin utilities. For read we want to handle input that may have line +endings either CRLF or LF so 't' is appropriate. +*/ +#define FOPEN_READTEXT "rt" +#define FOPEN_WRITETEXT "w" +#define FOPEN_APPENDTEXT "a" +#else +#define FOPEN_READTEXT "r" +#define FOPEN_WRITETEXT "w" +#define FOPEN_APPENDTEXT "a" +#endif + +/* for systems that don't detect this in configure */ +#ifndef CURL_SA_FAMILY_T +# if defined(HAVE_SA_FAMILY_T) +# define CURL_SA_FAMILY_T sa_family_t +# elif defined(HAVE_ADDRESS_FAMILY) +# define CURL_SA_FAMILY_T ADDRESS_FAMILY +# else +/* use a sensible default */ +# define CURL_SA_FAMILY_T unsigned short +# endif +#endif + +/* Some convenience macros to get the larger/smaller value out of two given. + We prefix with CURL to prevent name collisions. */ +#define CURLMAX(x,y) ((x)>(y)?(x):(y)) +#define CURLMIN(x,y) ((x)<(y)?(x):(y)) + +/* A convenience macro to provide both the string literal and the length of + the string literal in one go, useful for functions that take "string,len" + as their argument */ +#define STRCONST(x) x,sizeof(x)-1 + +/* Some versions of the Android SDK is missing the declaration */ +#if defined(HAVE_GETPWUID_R) && defined(HAVE_DECL_GETPWUID_R_MISSING) +struct passwd; +int getpwuid_r(uid_t uid, struct passwd *pwd, char *buf, + size_t buflen, struct passwd **result); +#endif + +#ifdef DEBUGBUILD +#define UNITTEST +#else +#define UNITTEST static +#endif + +/* Hyper supports HTTP2 also, but Curl's integration with Hyper does not */ +#if defined(USE_NGHTTP2) +#define USE_HTTP2 +#endif + +#if (defined(USE_NGTCP2) && defined(USE_NGHTTP3)) || \ + (defined(USE_OPENSSL_QUIC) && defined(USE_NGHTTP3)) || \ + defined(USE_QUICHE) || defined(USE_MSH3) + +#ifdef CURL_WITH_MULTI_SSL +#error "Multi-SSL combined with QUIC is not supported" +#endif + +#define USE_HTTP3 +#endif + +/* Certain Windows implementations are not aligned with what curl expects, + so always use the local one on this platform. E.g. the mingw-w64 + implementation can return wrong results for non-ASCII inputs. */ +#if defined(HAVE_BASENAME) && defined(_WIN32) +#undef HAVE_BASENAME +#endif + +#if defined(USE_UNIX_SOCKETS) && defined(_WIN32) +# if !defined(UNIX_PATH_MAX) + /* Replicating logic present in afunix.h + (distributed with newer Windows 10 SDK versions only) */ +# define UNIX_PATH_MAX 108 + /* !checksrc! disable TYPEDEFSTRUCT 1 */ + typedef struct sockaddr_un { + ADDRESS_FAMILY sun_family; + char sun_path[UNIX_PATH_MAX]; + } SOCKADDR_UN, *PSOCKADDR_UN; +# define WIN32_SOCKADDR_UN +# endif +#endif + +/* OpenSSLv3 marks DES, MD5 and ENGINE functions deprecated but we have no + replacements (yet) so tell the compiler to not warn for them. */ +#ifdef USE_OPENSSL +#define OPENSSL_SUPPRESS_DEPRECATED +#endif + +#if defined(inline) + /* 'inline' is defined as macro and assumed to be correct */ + /* No need for 'inline' replacement */ +#elif defined(__cplusplus) + /* The code is compiled with C++ compiler. + C++ always supports 'inline'. */ + /* No need for 'inline' replacement */ +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901 + /* C99 (and later) supports 'inline' keyword */ + /* No need for 'inline' replacement */ +#elif defined(__GNUC__) && __GNUC__ >= 3 + /* GCC supports '__inline__' as an extension */ +# define inline __inline__ +#elif defined(_MSC_VER) && _MSC_VER >= 1400 + /* MSC supports '__inline' from VS 2005 (or even earlier) */ +# define inline __inline +#else + /* Probably 'inline' is not supported by compiler. + Define to the empty string to be on the safe side. */ +# define inline /* empty */ +#endif + +#endif /* HEADER_CURL_SETUP_H */ diff --git a/third_party/curl/lib/curl_setup_once.h b/third_party/curl/lib/curl_setup_once.h new file mode 100644 index 0000000..40c7bcb --- /dev/null +++ b/third_party/curl/lib/curl_setup_once.h @@ -0,0 +1,414 @@ +#ifndef HEADER_CURL_SETUP_ONCE_H +#define HEADER_CURL_SETUP_ONCE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + + +/* + * Inclusion of common header files. + */ + +#include +#include +#include +#include +#include +#include + +#ifdef HAVE_SYS_TYPES_H +#include +#endif + +#ifdef NEED_MALLOC_H +#include +#endif + +#ifdef NEED_MEMORY_H +#include +#endif + +#ifdef HAVE_SYS_STAT_H +#include +#endif + +#ifdef HAVE_SYS_TIME_H +#include +#endif + +#ifdef _WIN32 +#include +#include +#endif + +#if defined(HAVE_STDBOOL_H) && defined(HAVE_BOOL_T) +#include +#endif + +#ifdef HAVE_UNISTD_H +#include +#endif + +#ifdef USE_WOLFSSL +#include +#endif + +#ifdef USE_SCHANNEL +/* Must set this before is included directly or indirectly by + another Windows header. */ +# define SCHANNEL_USE_BLACKLISTS 1 +#endif + +#ifdef __hpux +# if !defined(_XOPEN_SOURCE_EXTENDED) || defined(_KERNEL) +# ifdef _APP32_64BIT_OFF_T +# define OLD_APP32_64BIT_OFF_T _APP32_64BIT_OFF_T +# undef _APP32_64BIT_OFF_T +# else +# undef OLD_APP32_64BIT_OFF_T +# endif +# endif +#endif + +#ifdef HAVE_SYS_SOCKET_H +#include +#endif + +#include "functypes.h" + +#ifdef __hpux +# if !defined(_XOPEN_SOURCE_EXTENDED) || defined(_KERNEL) +# ifdef OLD_APP32_64BIT_OFF_T +# define _APP32_64BIT_OFF_T OLD_APP32_64BIT_OFF_T +# undef OLD_APP32_64BIT_OFF_T +# endif +# endif +#endif + +/* + * Definition of timeval struct for platforms that don't have it. + */ + +#ifndef HAVE_STRUCT_TIMEVAL +struct timeval { + long tv_sec; + long tv_usec; +}; +#endif + + +/* + * If we have the MSG_NOSIGNAL define, make sure we use + * it as the fourth argument of function send() + */ + +#ifdef HAVE_MSG_NOSIGNAL +#define SEND_4TH_ARG MSG_NOSIGNAL +#else +#define SEND_4TH_ARG 0 +#endif + + +#if defined(__minix) +/* Minix doesn't support recv on TCP sockets */ +#define sread(x,y,z) (ssize_t)read((RECV_TYPE_ARG1)(x), \ + (RECV_TYPE_ARG2)(y), \ + (RECV_TYPE_ARG3)(z)) + +#elif defined(HAVE_RECV) +/* + * The definitions for the return type and arguments types + * of functions recv() and send() belong and come from the + * configuration file. Do not define them in any other place. + * + * HAVE_RECV is defined if you have a function named recv() + * which is used to read incoming data from sockets. If your + * function has another name then don't define HAVE_RECV. + * + * If HAVE_RECV is defined then RECV_TYPE_ARG1, RECV_TYPE_ARG2, + * RECV_TYPE_ARG3, RECV_TYPE_ARG4 and RECV_TYPE_RETV must also + * be defined. + * + * HAVE_SEND is defined if you have a function named send() + * which is used to write outgoing data on a connected socket. + * If yours has another name then don't define HAVE_SEND. + * + * If HAVE_SEND is defined then SEND_TYPE_ARG1, SEND_QUAL_ARG2, + * SEND_TYPE_ARG2, SEND_TYPE_ARG3, SEND_TYPE_ARG4 and + * SEND_TYPE_RETV must also be defined. + */ + +#define sread(x,y,z) (ssize_t)recv((RECV_TYPE_ARG1)(x), \ + (RECV_TYPE_ARG2)(y), \ + (RECV_TYPE_ARG3)(z), \ + (RECV_TYPE_ARG4)(0)) +#else /* HAVE_RECV */ +#ifndef sread +#error "Missing definition of macro sread!" +#endif +#endif /* HAVE_RECV */ + + +#if defined(__minix) +/* Minix doesn't support send on TCP sockets */ +#define swrite(x,y,z) (ssize_t)write((SEND_TYPE_ARG1)(x), \ + (SEND_TYPE_ARG2)(y), \ + (SEND_TYPE_ARG3)(z)) + +#elif defined(HAVE_SEND) +#define swrite(x,y,z) (ssize_t)send((SEND_TYPE_ARG1)(x), \ + (SEND_QUAL_ARG2 SEND_TYPE_ARG2)(y), \ + (SEND_TYPE_ARG3)(z), \ + (SEND_TYPE_ARG4)(SEND_4TH_ARG)) +#else /* HAVE_SEND */ +#ifndef swrite +#error "Missing definition of macro swrite!" +#endif +#endif /* HAVE_SEND */ + + +/* + * Function-like macro definition used to close a socket. + */ + +#if defined(HAVE_CLOSESOCKET) +# define sclose(x) closesocket((x)) +#elif defined(HAVE_CLOSESOCKET_CAMEL) +# define sclose(x) CloseSocket((x)) +#elif defined(HAVE_CLOSE_S) +# define sclose(x) close_s((x)) +#elif defined(USE_LWIPSOCK) +# define sclose(x) lwip_close((x)) +#else +# define sclose(x) close((x)) +#endif + +/* + * Stack-independent version of fcntl() on sockets: + */ +#if defined(USE_LWIPSOCK) +# define sfcntl lwip_fcntl +#else +# define sfcntl fcntl +#endif + +/* + * 'bool' stuff compatible with HP-UX headers. + */ + +#if defined(__hpux) && !defined(HAVE_BOOL_T) + typedef int bool; +# define false 0 +# define true 1 +# define HAVE_BOOL_T +#endif + + +/* + * 'bool' exists on platforms with , i.e. C99 platforms. + * On non-C99 platforms there's no bool, so define an enum for that. + * On C99 platforms 'false' and 'true' also exist. Enum uses a + * global namespace though, so use bool_false and bool_true. + */ + +#ifndef HAVE_BOOL_T + typedef enum { + bool_false = 0, + bool_true = 1 + } bool; + +/* + * Use a define to let 'true' and 'false' use those enums. There + * are currently no use of true and false in libcurl proper, but + * there are some in the examples. This will cater for any later + * code happening to use true and false. + */ +# define false bool_false +# define true bool_true +# define HAVE_BOOL_T +#endif + +/* the type we use for storing a single boolean bit */ +#ifdef _MSC_VER +typedef bool bit; +#define BIT(x) bool x +#else +typedef unsigned int bit; +#define BIT(x) bit x:1 +#endif + +/* + * Redefine TRUE and FALSE too, to catch current use. With this + * change, 'bool found = 1' will give a warning on MIPSPro, but + * 'bool found = TRUE' will not. Change tested on IRIX/MIPSPro, + * AIX 5.1/Xlc, Tru64 5.1/cc, w/make test too. + */ + +#ifndef TRUE +#define TRUE true +#endif +#ifndef FALSE +#define FALSE false +#endif + +#include "curl_ctype.h" + + +/* + * Macro used to include code only in debug builds. + */ + +#ifdef DEBUGBUILD +#define DEBUGF(x) x +#else +#define DEBUGF(x) do { } while(0) +#endif + + +/* + * Macro used to include assertion code only in debug builds. + */ + +#undef DEBUGASSERT +#if defined(DEBUGBUILD) +#define DEBUGASSERT(x) assert(x) +#else +#define DEBUGASSERT(x) do { } while(0) +#endif + + +/* + * Macro SOCKERRNO / SET_SOCKERRNO() returns / sets the *socket-related* errno + * (or equivalent) on this platform to hide platform details to code using it. + */ + +#ifdef USE_WINSOCK +#define SOCKERRNO ((int)WSAGetLastError()) +#define SET_SOCKERRNO(x) (WSASetLastError((int)(x))) +#else +#define SOCKERRNO (errno) +#define SET_SOCKERRNO(x) (errno = (x)) +#endif + + +/* + * Portable error number symbolic names defined to Winsock error codes. + */ + +#ifdef USE_WINSOCK +#undef EBADF /* override definition in errno.h */ +#define EBADF WSAEBADF +#undef EINTR /* override definition in errno.h */ +#define EINTR WSAEINTR +#undef EINVAL /* override definition in errno.h */ +#define EINVAL WSAEINVAL +#undef EWOULDBLOCK /* override definition in errno.h */ +#define EWOULDBLOCK WSAEWOULDBLOCK +#undef EINPROGRESS /* override definition in errno.h */ +#define EINPROGRESS WSAEINPROGRESS +#undef EALREADY /* override definition in errno.h */ +#define EALREADY WSAEALREADY +#undef ENOTSOCK /* override definition in errno.h */ +#define ENOTSOCK WSAENOTSOCK +#undef EDESTADDRREQ /* override definition in errno.h */ +#define EDESTADDRREQ WSAEDESTADDRREQ +#undef EMSGSIZE /* override definition in errno.h */ +#define EMSGSIZE WSAEMSGSIZE +#undef EPROTOTYPE /* override definition in errno.h */ +#define EPROTOTYPE WSAEPROTOTYPE +#undef ENOPROTOOPT /* override definition in errno.h */ +#define ENOPROTOOPT WSAENOPROTOOPT +#undef EPROTONOSUPPORT /* override definition in errno.h */ +#define EPROTONOSUPPORT WSAEPROTONOSUPPORT +#define ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT +#undef EOPNOTSUPP /* override definition in errno.h */ +#define EOPNOTSUPP WSAEOPNOTSUPP +#define EPFNOSUPPORT WSAEPFNOSUPPORT +#undef EAFNOSUPPORT /* override definition in errno.h */ +#define EAFNOSUPPORT WSAEAFNOSUPPORT +#undef EADDRINUSE /* override definition in errno.h */ +#define EADDRINUSE WSAEADDRINUSE +#undef EADDRNOTAVAIL /* override definition in errno.h */ +#define EADDRNOTAVAIL WSAEADDRNOTAVAIL +#undef ENETDOWN /* override definition in errno.h */ +#define ENETDOWN WSAENETDOWN +#undef ENETUNREACH /* override definition in errno.h */ +#define ENETUNREACH WSAENETUNREACH +#undef ENETRESET /* override definition in errno.h */ +#define ENETRESET WSAENETRESET +#undef ECONNABORTED /* override definition in errno.h */ +#define ECONNABORTED WSAECONNABORTED +#undef ECONNRESET /* override definition in errno.h */ +#define ECONNRESET WSAECONNRESET +#undef ENOBUFS /* override definition in errno.h */ +#define ENOBUFS WSAENOBUFS +#undef EISCONN /* override definition in errno.h */ +#define EISCONN WSAEISCONN +#undef ENOTCONN /* override definition in errno.h */ +#define ENOTCONN WSAENOTCONN +#define ESHUTDOWN WSAESHUTDOWN +#define ETOOMANYREFS WSAETOOMANYREFS +#undef ETIMEDOUT /* override definition in errno.h */ +#define ETIMEDOUT WSAETIMEDOUT +#undef ECONNREFUSED /* override definition in errno.h */ +#define ECONNREFUSED WSAECONNREFUSED +#undef ELOOP /* override definition in errno.h */ +#define ELOOP WSAELOOP +#ifndef ENAMETOOLONG /* possible previous definition in errno.h */ +#define ENAMETOOLONG WSAENAMETOOLONG +#endif +#define EHOSTDOWN WSAEHOSTDOWN +#undef EHOSTUNREACH /* override definition in errno.h */ +#define EHOSTUNREACH WSAEHOSTUNREACH +#ifndef ENOTEMPTY /* possible previous definition in errno.h */ +#define ENOTEMPTY WSAENOTEMPTY +#endif +#define EPROCLIM WSAEPROCLIM +#define EUSERS WSAEUSERS +#define EDQUOT WSAEDQUOT +#define ESTALE WSAESTALE +#define EREMOTE WSAEREMOTE +#endif + +/* + * Macro argv_item_t hides platform details to code using it. + */ + +#ifdef __VMS +#define argv_item_t __char_ptr32 +#elif defined(_UNICODE) +#define argv_item_t wchar_t * +#else +#define argv_item_t char * +#endif + + +/* + * We use this ZERO_NULL to avoid picky compiler warnings, + * when assigning a NULL pointer to a function pointer var. + */ + +#define ZERO_NULL 0 + + +#endif /* HEADER_CURL_SETUP_ONCE_H */ diff --git a/third_party/curl/lib/curl_sha256.h b/third_party/curl/lib/curl_sha256.h new file mode 100644 index 0000000..d99f958 --- /dev/null +++ b/third_party/curl/lib/curl_sha256.h @@ -0,0 +1,50 @@ +#ifndef HEADER_CURL_SHA256_H +#define HEADER_CURL_SHA256_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Florin Petriuc, + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#if !defined(CURL_DISABLE_AWS) || !defined(CURL_DISABLE_DIGEST_AUTH) \ + || defined(USE_LIBSSH2) + +#include +#include "curl_hmac.h" + +extern const struct HMAC_params Curl_HMAC_SHA256[1]; + +#ifdef USE_WOLFSSL +/* SHA256_DIGEST_LENGTH is an enum value in wolfSSL. Need to import it from + * sha.h */ +#include +#include +#else +#define SHA256_DIGEST_LENGTH 32 +#endif + +CURLcode Curl_sha256it(unsigned char *outbuffer, const unsigned char *input, + const size_t len); + +#endif + +#endif /* HEADER_CURL_SHA256_H */ diff --git a/third_party/curl/lib/curl_sha512_256.c b/third_party/curl/lib/curl_sha512_256.c new file mode 100644 index 0000000..5f2e995 --- /dev/null +++ b/third_party/curl/lib/curl_sha512_256.c @@ -0,0 +1,850 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Evgeny Grin (Karlson2k), . + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_DIGEST_AUTH) && !defined(CURL_DISABLE_SHA512_256) + +#include "curl_sha512_256.h" +#include "warnless.h" + +/* The recommended order of the TLS backends: + * * OpenSSL + * * GnuTLS + * * wolfSSL + * * Schannel SSPI + * * SecureTransport (Darwin) + * * mbedTLS + * * BearSSL + * * rustls + * Skip the backend if it does not support the required algorithm */ + +#if defined(USE_OPENSSL) +# include +# if (!defined(LIBRESSL_VERSION_NUMBER) && \ + defined(OPENSSL_VERSION_NUMBER) && \ + (OPENSSL_VERSION_NUMBER >= 0x10101000L)) || \ + (defined(LIBRESSL_VERSION_NUMBER) && \ + (LIBRESSL_VERSION_NUMBER >= 0x3080000fL)) +# include +# if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA512) +# include +# define USE_OPENSSL_SHA512_256 1 +# define HAS_SHA512_256_IMPLEMENTATION 1 +# ifdef __NetBSD__ +/* Some NetBSD versions has a bug in SHA-512/256. + * See https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=58039 + * The problematic versions: + * - NetBSD before 9.4 + * - NetBSD 9 all development versions (9.99.x) + * - NetBSD 10 development versions (10.99.x) before 10.99.11 + * The bug was fixed in NetBSD 9.4 release, NetBSD 10.0 release, + * NetBSD 10.99.11 development. + * It is safe to apply the workaround even if the bug is not present, as + * the workaround just reduces performance slightly. */ +# include +# if __NetBSD_Version__ < 904000000 || \ + (__NetBSD_Version__ >= 999000000 && \ + __NetBSD_Version__ < 1000000000) || \ + (__NetBSD_Version__ >= 1099000000 && \ + __NetBSD_Version__ < 1099001100) +# define NEED_NETBSD_SHA512_256_WORKAROUND 1 +# include +# endif +# endif +# endif +# endif +#endif /* USE_OPENSSL */ + + +#if !defined(HAS_SHA512_256_IMPLEMENTATION) && defined(USE_GNUTLS) +# include +# if defined(SHA512_256_DIGEST_SIZE) +# define USE_GNUTLS_SHA512_256 1 +# define HAS_SHA512_256_IMPLEMENTATION 1 +# endif +#endif /* ! HAS_SHA512_256_IMPLEMENTATION && USE_GNUTLS */ + +#if defined(USE_OPENSSL_SHA512_256) + +/* OpenSSL does not provide macros for SHA-512/256 sizes */ + +/** + * Size of the SHA-512/256 single processing block in bytes. + */ +#define SHA512_256_BLOCK_SIZE 128 + +/** + * Size of the SHA-512/256 resulting digest in bytes. + * This is the final digest size, not intermediate hash. + */ +#define SHA512_256_DIGEST_SIZE SHA512_256_DIGEST_LENGTH + +/** + * Context type used for SHA-512/256 calculations + */ +typedef EVP_MD_CTX *Curl_sha512_256_ctx; + +/** + * Initialise structure for SHA-512/256 calculation. + * + * @param context the calculation context + * @return CURLE_OK if succeed, + * error code otherwise + */ +static CURLcode +Curl_sha512_256_init(void *context) +{ + Curl_sha512_256_ctx *const ctx = (Curl_sha512_256_ctx *)context; + + *ctx = EVP_MD_CTX_create(); + if(!*ctx) + return CURLE_OUT_OF_MEMORY; + + if(EVP_DigestInit_ex(*ctx, EVP_sha512_256(), NULL)) { + /* Check whether the header and this file use the same numbers */ + DEBUGASSERT(EVP_MD_CTX_size(*ctx) == SHA512_256_DIGEST_SIZE); + /* Check whether the block size is correct */ + DEBUGASSERT(EVP_MD_CTX_block_size(*ctx) == SHA512_256_BLOCK_SIZE); + + return CURLE_OK; /* Success */ + } + + /* Cleanup */ + EVP_MD_CTX_destroy(*ctx); + return CURLE_FAILED_INIT; +} + + +/** + * Process portion of bytes. + * + * @param context the calculation context + * @param data bytes to add to hash + * @return CURLE_OK if succeed, + * error code otherwise + */ +static CURLcode +Curl_sha512_256_update(void *context, + const unsigned char *data, + size_t length) +{ + Curl_sha512_256_ctx *const ctx = (Curl_sha512_256_ctx *)context; + + if(!EVP_DigestUpdate(*ctx, data, length)) + return CURLE_SSL_CIPHER; + + return CURLE_OK; +} + + +/** + * Finalise SHA-512/256 calculation, return digest. + * + * @param context the calculation context + * @param[out] digest set to the hash, must be #SHA512_256_DIGEST_SIZE bytes + * @return CURLE_OK if succeed, + * error code otherwise + */ +static CURLcode +Curl_sha512_256_finish(unsigned char *digest, + void *context) +{ + CURLcode ret; + Curl_sha512_256_ctx *const ctx = (Curl_sha512_256_ctx *)context; + +#ifdef NEED_NETBSD_SHA512_256_WORKAROUND + /* Use a larger buffer to work around a bug in NetBSD: + https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=58039 */ + unsigned char tmp_digest[SHA512_256_DIGEST_SIZE * 2]; + ret = EVP_DigestFinal_ex(*ctx, + tmp_digest, NULL) ? CURLE_OK : CURLE_SSL_CIPHER; + if(ret == CURLE_OK) + memcpy(digest, tmp_digest, SHA512_256_DIGEST_SIZE); + explicit_memset(tmp_digest, 0, sizeof(tmp_digest)); +#else /* ! NEED_NETBSD_SHA512_256_WORKAROUND */ + ret = EVP_DigestFinal_ex(*ctx, digest, NULL) ? CURLE_OK : CURLE_SSL_CIPHER; +#endif /* ! NEED_NETBSD_SHA512_256_WORKAROUND */ + + EVP_MD_CTX_destroy(*ctx); + *ctx = NULL; + + return ret; +} + +#elif defined(USE_GNUTLS_SHA512_256) + +/** + * Context type used for SHA-512/256 calculations + */ +typedef struct sha512_256_ctx Curl_sha512_256_ctx; + +/** + * Initialise structure for SHA-512/256 calculation. + * + * @param context the calculation context + * @return always CURLE_OK + */ +static CURLcode +Curl_sha512_256_init(void *context) +{ + Curl_sha512_256_ctx *const ctx = (Curl_sha512_256_ctx *)context; + + /* Check whether the header and this file use the same numbers */ + DEBUGASSERT(SHA512_256_DIGEST_LENGTH == SHA512_256_DIGEST_SIZE); + + sha512_256_init(ctx); + + return CURLE_OK; +} + + +/** + * Process portion of bytes. + * + * @param context the calculation context + * @param data bytes to add to hash + * @param length number of bytes in @a data + * @return always CURLE_OK + */ +static CURLcode +Curl_sha512_256_update(void *context, + const unsigned char *data, + size_t length) +{ + Curl_sha512_256_ctx *const ctx = (Curl_sha512_256_ctx *)context; + + DEBUGASSERT((data != NULL) || (length == 0)); + + sha512_256_update(ctx, length, (const uint8_t *)data); + + return CURLE_OK; +} + + +/** + * Finalise SHA-512/256 calculation, return digest. + * + * @param context the calculation context + * @param[out] digest set to the hash, must be #SHA512_256_DIGEST_SIZE bytes + * @return always CURLE_OK + */ +static CURLcode +Curl_sha512_256_finish(unsigned char *digest, + void *context) +{ + Curl_sha512_256_ctx *const ctx = (Curl_sha512_256_ctx *)context; + + sha512_256_digest(ctx, (size_t)SHA512_256_DIGEST_SIZE, (uint8_t *)digest); + + return CURLE_OK; +} + +#else /* No system or TLS backend SHA-512/256 implementation available */ + +/* Use local implementation */ +#define HAS_SHA512_256_IMPLEMENTATION 1 + +/* ** This implementation of SHA-512/256 hash calculation was originally ** * + * ** written by Evgeny Grin (Karlson2k) for GNU libmicrohttpd. ** * + * ** The author ported the code to libcurl. The ported code is provided ** * + * ** under curl license. ** * + * ** This is a minimal version with minimal optimisations. Performance ** * + * ** can be significantly improved. Big-endian store and load macros ** * + * ** are obvious targets for optimisation. ** */ + +#ifdef __GNUC__ +# if defined(__has_attribute) && defined(__STDC_VERSION__) +# if __has_attribute(always_inline) && __STDC_VERSION__ >= 199901 +# define MHDX_INLINE inline __attribute__((always_inline)) +# endif +# endif +#endif + +#if !defined(MHDX_INLINE) && \ + defined(_MSC_VER) && !defined(__GNUC__) && !defined(__clang__) +# if _MSC_VER >= 1400 +# define MHDX_INLINE __forceinline +# endif +#endif + +#if !defined(MHDX_INLINE) + /* Assume that 'inline' keyword works or the + * macro was already defined correctly. */ +# define MHDX_INLINE inline +#endif + +/* Bits manipulation macros and functions. + Can be moved to other headers to reuse. */ + +#define MHDX_GET_64BIT_BE(ptr) \ + ( ((curl_uint64_t)(((const unsigned char*)(ptr))[0]) << 56) | \ + ((curl_uint64_t)(((const unsigned char*)(ptr))[1]) << 48) | \ + ((curl_uint64_t)(((const unsigned char*)(ptr))[2]) << 40) | \ + ((curl_uint64_t)(((const unsigned char*)(ptr))[3]) << 32) | \ + ((curl_uint64_t)(((const unsigned char*)(ptr))[4]) << 24) | \ + ((curl_uint64_t)(((const unsigned char*)(ptr))[5]) << 16) | \ + ((curl_uint64_t)(((const unsigned char*)(ptr))[6]) << 8) | \ + (curl_uint64_t)(((const unsigned char*)(ptr))[7]) ) + +#define MHDX_PUT_64BIT_BE(ptr,val) do { \ + ((unsigned char*)(ptr))[7]=(unsigned char)((curl_uint64_t)(val)); \ + ((unsigned char*)(ptr))[6]=(unsigned char)(((curl_uint64_t)(val)) >> 8); \ + ((unsigned char*)(ptr))[5]=(unsigned char)(((curl_uint64_t)(val)) >> 16); \ + ((unsigned char*)(ptr))[4]=(unsigned char)(((curl_uint64_t)(val)) >> 24); \ + ((unsigned char*)(ptr))[3]=(unsigned char)(((curl_uint64_t)(val)) >> 32); \ + ((unsigned char*)(ptr))[2]=(unsigned char)(((curl_uint64_t)(val)) >> 40); \ + ((unsigned char*)(ptr))[1]=(unsigned char)(((curl_uint64_t)(val)) >> 48); \ + ((unsigned char*)(ptr))[0]=(unsigned char)(((curl_uint64_t)(val)) >> 56); \ + } while(0) + +/* Defined as a function. The macro version may duplicate the binary code + * size as each argument is used twice, so if any calculation is used + * as an argument, the calculation could be done twice. */ +static MHDX_INLINE curl_uint64_t +MHDx_rotr64(curl_uint64_t value, unsigned int bits) +{ + bits %= 64; + if(0 == bits) + return value; + /* Defined in a form which modern compiler could optimise. */ + return (value >> bits) | (value << (64 - bits)); +} + +/* SHA-512/256 specific data */ + +/** + * Number of bits in a single SHA-512/256 word. + */ +#define SHA512_256_WORD_SIZE_BITS 64 + +/** + * Number of bytes in a single SHA-512/256 word. + */ +#define SHA512_256_BYTES_IN_WORD (SHA512_256_WORD_SIZE_BITS / 8) + +/** + * Hash is kept internally as 8 64-bit words. + * This is the intermediate hash size, used during computing the final digest. + */ +#define SHA512_256_HASH_SIZE_WORDS 8 + +/** + * Size of the SHA-512/256 resulting digest in words. + * This is the final digest size, not intermediate hash. + */ +#define SHA512_256_DIGEST_SIZE_WORDS (SHA512_256_HASH_SIZE_WORDS / 2) + +/** + * Size of the SHA-512/256 resulting digest in bytes + * This is the final digest size, not intermediate hash. + */ +#define SHA512_256_DIGEST_SIZE \ + (SHA512_256_DIGEST_SIZE_WORDS * SHA512_256_BYTES_IN_WORD) + +/** + * Size of the SHA-512/256 single processing block in bits. + */ +#define SHA512_256_BLOCK_SIZE_BITS 1024 + +/** + * Size of the SHA-512/256 single processing block in bytes. + */ +#define SHA512_256_BLOCK_SIZE (SHA512_256_BLOCK_SIZE_BITS / 8) + +/** + * Size of the SHA-512/256 single processing block in words. + */ +#define SHA512_256_BLOCK_SIZE_WORDS \ + (SHA512_256_BLOCK_SIZE_BITS / SHA512_256_WORD_SIZE_BITS) + +/** + * SHA-512/256 calculation context + */ +struct mhdx_sha512_256ctx +{ + /** + * Intermediate hash value. The variable is properly aligned. Smart + * compilers may automatically use fast load/store instruction for big + * endian data on little endian machine. + */ + curl_uint64_t H[SHA512_256_HASH_SIZE_WORDS]; + /** + * SHA-512/256 input data buffer. The buffer is properly aligned. Smart + * compilers may automatically use fast load/store instruction for big + * endian data on little endian machine. + */ + curl_uint64_t buffer[SHA512_256_BLOCK_SIZE_WORDS]; + /** + * The number of bytes, lower part + */ + curl_uint64_t count; + /** + * The number of bits, high part. Unlike lower part, this counts the number + * of bits, not bytes. + */ + curl_uint64_t count_bits_hi; +}; + +/** + * Context type used for SHA-512/256 calculations + */ +typedef struct mhdx_sha512_256ctx Curl_sha512_256_ctx; + + +/** + * Initialise structure for SHA-512/256 calculation. + * + * @param context the calculation context + * @return always CURLE_OK + */ +static CURLcode +MHDx_sha512_256_init(void *context) +{ + struct mhdx_sha512_256ctx *const ctx = (struct mhdx_sha512_256ctx *) context; + + /* Check whether the header and this file use the same numbers */ + DEBUGASSERT(SHA512_256_DIGEST_LENGTH == SHA512_256_DIGEST_SIZE); + + DEBUGASSERT(sizeof(curl_uint64_t) == 8); + + /* Initial hash values, see FIPS PUB 180-4 section 5.3.6.2 */ + /* Values generated by "IV Generation Function" as described in + * section 5.3.6 */ + ctx->H[0] = CURL_UINT64_C(0x22312194FC2BF72C); + ctx->H[1] = CURL_UINT64_C(0x9F555FA3C84C64C2); + ctx->H[2] = CURL_UINT64_C(0x2393B86B6F53B151); + ctx->H[3] = CURL_UINT64_C(0x963877195940EABD); + ctx->H[4] = CURL_UINT64_C(0x96283EE2A88EFFE3); + ctx->H[5] = CURL_UINT64_C(0xBE5E1E2553863992); + ctx->H[6] = CURL_UINT64_C(0x2B0199FC2C85B8AA); + ctx->H[7] = CURL_UINT64_C(0x0EB72DDC81C52CA2); + + /* Initialise number of bytes and high part of number of bits. */ + ctx->count = CURL_UINT64_C(0); + ctx->count_bits_hi = CURL_UINT64_C(0); + + return CURLE_OK; +} + + +/** + * Base of the SHA-512/256 transformation. + * Gets a full 128 bytes block of data and updates hash values; + * @param H hash values + * @param data the data buffer with #SHA512_256_BLOCK_SIZE bytes block + */ +static void +MHDx_sha512_256_transform(curl_uint64_t H[SHA512_256_HASH_SIZE_WORDS], + const void *data) +{ + /* Working variables, + see FIPS PUB 180-4 section 6.7, 6.4. */ + curl_uint64_t a = H[0]; + curl_uint64_t b = H[1]; + curl_uint64_t c = H[2]; + curl_uint64_t d = H[3]; + curl_uint64_t e = H[4]; + curl_uint64_t f = H[5]; + curl_uint64_t g = H[6]; + curl_uint64_t h = H[7]; + + /* Data buffer, used as a cyclic buffer. + See FIPS PUB 180-4 section 5.2.2, 6.7, 6.4. */ + curl_uint64_t W[16]; + + /* 'Ch' and 'Maj' macro functions are defined with widely-used optimisation. + See FIPS PUB 180-4 formulae 4.8, 4.9. */ +#define Ch(x,y,z) ( (z) ^ ((x) & ((y) ^ (z))) ) +#define Maj(x,y,z) ( ((x) & (y)) ^ ((z) & ((x) ^ (y))) ) + + /* Four 'Sigma' macro functions. + See FIPS PUB 180-4 formulae 4.10, 4.11, 4.12, 4.13. */ +#define SIG0(x) \ + ( MHDx_rotr64((x), 28) ^ MHDx_rotr64((x), 34) ^ MHDx_rotr64((x), 39) ) +#define SIG1(x) \ + ( MHDx_rotr64((x), 14) ^ MHDx_rotr64((x), 18) ^ MHDx_rotr64((x), 41) ) +#define sig0(x) \ + ( MHDx_rotr64((x), 1) ^ MHDx_rotr64((x), 8) ^ ((x) >> 7) ) +#define sig1(x) \ + ( MHDx_rotr64((x), 19) ^ MHDx_rotr64((x), 61) ^ ((x) >> 6) ) + + if(1) { + unsigned int t; + /* K constants array. + See FIPS PUB 180-4 section 4.2.3 for K values. */ + static const curl_uint64_t K[80] = { + CURL_UINT64_C(0x428a2f98d728ae22), CURL_UINT64_C(0x7137449123ef65cd), + CURL_UINT64_C(0xb5c0fbcfec4d3b2f), CURL_UINT64_C(0xe9b5dba58189dbbc), + CURL_UINT64_C(0x3956c25bf348b538), CURL_UINT64_C(0x59f111f1b605d019), + CURL_UINT64_C(0x923f82a4af194f9b), CURL_UINT64_C(0xab1c5ed5da6d8118), + CURL_UINT64_C(0xd807aa98a3030242), CURL_UINT64_C(0x12835b0145706fbe), + CURL_UINT64_C(0x243185be4ee4b28c), CURL_UINT64_C(0x550c7dc3d5ffb4e2), + CURL_UINT64_C(0x72be5d74f27b896f), CURL_UINT64_C(0x80deb1fe3b1696b1), + CURL_UINT64_C(0x9bdc06a725c71235), CURL_UINT64_C(0xc19bf174cf692694), + CURL_UINT64_C(0xe49b69c19ef14ad2), CURL_UINT64_C(0xefbe4786384f25e3), + CURL_UINT64_C(0x0fc19dc68b8cd5b5), CURL_UINT64_C(0x240ca1cc77ac9c65), + CURL_UINT64_C(0x2de92c6f592b0275), CURL_UINT64_C(0x4a7484aa6ea6e483), + CURL_UINT64_C(0x5cb0a9dcbd41fbd4), CURL_UINT64_C(0x76f988da831153b5), + CURL_UINT64_C(0x983e5152ee66dfab), CURL_UINT64_C(0xa831c66d2db43210), + CURL_UINT64_C(0xb00327c898fb213f), CURL_UINT64_C(0xbf597fc7beef0ee4), + CURL_UINT64_C(0xc6e00bf33da88fc2), CURL_UINT64_C(0xd5a79147930aa725), + CURL_UINT64_C(0x06ca6351e003826f), CURL_UINT64_C(0x142929670a0e6e70), + CURL_UINT64_C(0x27b70a8546d22ffc), CURL_UINT64_C(0x2e1b21385c26c926), + CURL_UINT64_C(0x4d2c6dfc5ac42aed), CURL_UINT64_C(0x53380d139d95b3df), + CURL_UINT64_C(0x650a73548baf63de), CURL_UINT64_C(0x766a0abb3c77b2a8), + CURL_UINT64_C(0x81c2c92e47edaee6), CURL_UINT64_C(0x92722c851482353b), + CURL_UINT64_C(0xa2bfe8a14cf10364), CURL_UINT64_C(0xa81a664bbc423001), + CURL_UINT64_C(0xc24b8b70d0f89791), CURL_UINT64_C(0xc76c51a30654be30), + CURL_UINT64_C(0xd192e819d6ef5218), CURL_UINT64_C(0xd69906245565a910), + CURL_UINT64_C(0xf40e35855771202a), CURL_UINT64_C(0x106aa07032bbd1b8), + CURL_UINT64_C(0x19a4c116b8d2d0c8), CURL_UINT64_C(0x1e376c085141ab53), + CURL_UINT64_C(0x2748774cdf8eeb99), CURL_UINT64_C(0x34b0bcb5e19b48a8), + CURL_UINT64_C(0x391c0cb3c5c95a63), CURL_UINT64_C(0x4ed8aa4ae3418acb), + CURL_UINT64_C(0x5b9cca4f7763e373), CURL_UINT64_C(0x682e6ff3d6b2b8a3), + CURL_UINT64_C(0x748f82ee5defb2fc), CURL_UINT64_C(0x78a5636f43172f60), + CURL_UINT64_C(0x84c87814a1f0ab72), CURL_UINT64_C(0x8cc702081a6439ec), + CURL_UINT64_C(0x90befffa23631e28), CURL_UINT64_C(0xa4506cebde82bde9), + CURL_UINT64_C(0xbef9a3f7b2c67915), CURL_UINT64_C(0xc67178f2e372532b), + CURL_UINT64_C(0xca273eceea26619c), CURL_UINT64_C(0xd186b8c721c0c207), + CURL_UINT64_C(0xeada7dd6cde0eb1e), CURL_UINT64_C(0xf57d4f7fee6ed178), + CURL_UINT64_C(0x06f067aa72176fba), CURL_UINT64_C(0x0a637dc5a2c898a6), + CURL_UINT64_C(0x113f9804bef90dae), CURL_UINT64_C(0x1b710b35131c471b), + CURL_UINT64_C(0x28db77f523047d84), CURL_UINT64_C(0x32caab7b40c72493), + CURL_UINT64_C(0x3c9ebe0a15c9bebc), CURL_UINT64_C(0x431d67c49c100d4c), + CURL_UINT64_C(0x4cc5d4becb3e42b6), CURL_UINT64_C(0x597f299cfc657e2a), + CURL_UINT64_C(0x5fcb6fab3ad6faec), CURL_UINT64_C(0x6c44198c4a475817) + }; + + /* One step of SHA-512/256 computation, + see FIPS PUB 180-4 section 6.4.2 step 3. + * Note: this macro updates working variables in-place, without rotation. + * Note: the first (vH += SIG1(vE) + Ch(vE,vF,vG) + kt + wt) equals T1 in + FIPS PUB 180-4 section 6.4.2 step 3. + the second (vH += SIG0(vA) + Maj(vE,vF,vC) equals T1 + T2 in + FIPS PUB 180-4 section 6.4.2 step 3. + * Note: 'wt' must be used exactly one time in this macro as macro for + 'wt' calculation may change other data as well every time when + used. */ +#define SHA2STEP64(vA,vB,vC,vD,vE,vF,vG,vH,kt,wt) do { \ + (vD) += ((vH) += SIG1 ((vE)) + Ch ((vE),(vF),(vG)) + (kt) + (wt)); \ + (vH) += SIG0 ((vA)) + Maj ((vA),(vB),(vC)); } while (0) + + /* One step of SHA-512/256 computation with working variables rotation, + see FIPS PUB 180-4 section 6.4.2 step 3. This macro version reassigns + all working variables on each step. */ +#define SHA2STEP64RV(vA,vB,vC,vD,vE,vF,vG,vH,kt,wt) do { \ + curl_uint64_t tmp_h_ = (vH); \ + SHA2STEP64((vA),(vB),(vC),(vD),(vE),(vF),(vG),tmp_h_,(kt),(wt)); \ + (vH) = (vG); \ + (vG) = (vF); \ + (vF) = (vE); \ + (vE) = (vD); \ + (vD) = (vC); \ + (vC) = (vB); \ + (vB) = (vA); \ + (vA) = tmp_h_; } while(0) + + /* Get value of W(t) from input data buffer for 0 <= t <= 15, + See FIPS PUB 180-4 section 6.2. + Input data must be read in big-endian bytes order, + see FIPS PUB 180-4 section 3.1.2. */ +#define SHA512_GET_W_FROM_DATA(buf,t) \ + MHDX_GET_64BIT_BE( \ + ((const unsigned char*) (buf)) + (t) * SHA512_256_BYTES_IN_WORD) + + /* During first 16 steps, before making any calculation on each step, the + W element is read from the input data buffer as a big-endian value and + stored in the array of W elements. */ + for(t = 0; t < 16; ++t) { + SHA2STEP64RV(a, b, c, d, e, f, g, h, K[t], \ + W[t] = SHA512_GET_W_FROM_DATA(data, t)); + } + + /* 'W' generation and assignment for 16 <= t <= 79. + See FIPS PUB 180-4 section 6.4.2. + As only the last 16 'W' are used in calculations, it is possible to + use 16 elements array of W as a cyclic buffer. + Note: ((t-16) & 15) have same value as (t & 15) */ +#define Wgen(w,t) \ + (curl_uint64_t)( (w)[(t - 16) & 15] + sig1((w)[((t) - 2) & 15]) \ + + (w)[((t) - 7) & 15] + sig0((w)[((t) - 15) & 15]) ) + + /* During the last 64 steps, before making any calculation on each step, + current W element is generated from other W elements of the cyclic + buffer and the generated value is stored back in the cyclic buffer. */ + for(t = 16; t < 80; ++t) { + SHA2STEP64RV(a, b, c, d, e, f, g, h, K[t], \ + W[t & 15] = Wgen(W, t)); + } + } + + /* Compute and store the intermediate hash. + See FIPS PUB 180-4 section 6.4.2 step 4. */ + H[0] += a; + H[1] += b; + H[2] += c; + H[3] += d; + H[4] += e; + H[5] += f; + H[6] += g; + H[7] += h; +} + + +/** + * Process portion of bytes. + * + * @param context the calculation context + * @param data bytes to add to hash + * @param length number of bytes in @a data + * @return always CURLE_OK + */ +static CURLcode +MHDx_sha512_256_update(void *context, + const unsigned char *data, + size_t length) +{ + unsigned int bytes_have; /**< Number of bytes in the context buffer */ + struct mhdx_sha512_256ctx *const ctx = (struct mhdx_sha512_256ctx *)context; + /* the void pointer here is required to mute Intel compiler warning */ + void *const ctx_buf = ctx->buffer; + + DEBUGASSERT((data != NULL) || (length == 0)); + + if(0 == length) + return CURLE_OK; /* Shortcut, do nothing */ + + /* Note: (count & (SHA512_256_BLOCK_SIZE-1)) + equals (count % SHA512_256_BLOCK_SIZE) for this block size. */ + bytes_have = (unsigned int) (ctx->count & (SHA512_256_BLOCK_SIZE - 1)); + ctx->count += length; + if(length > ctx->count) + ctx->count_bits_hi += 1U << 3; /* Value wrap */ + ctx->count_bits_hi += ctx->count >> 61; + ctx->count &= CURL_UINT64_C(0x1FFFFFFFFFFFFFFF); + + if(0 != bytes_have) { + unsigned int bytes_left = SHA512_256_BLOCK_SIZE - bytes_have; + if(length >= bytes_left) { + /* Combine new data with data in the buffer and process the full + block. */ + memcpy(((unsigned char *) ctx_buf) + bytes_have, + data, + bytes_left); + data += bytes_left; + length -= bytes_left; + MHDx_sha512_256_transform(ctx->H, ctx->buffer); + bytes_have = 0; + } + } + + while(SHA512_256_BLOCK_SIZE <= length) { + /* Process any full blocks of new data directly, + without copying to the buffer. */ + MHDx_sha512_256_transform(ctx->H, data); + data += SHA512_256_BLOCK_SIZE; + length -= SHA512_256_BLOCK_SIZE; + } + + if(0 != length) { + /* Copy incomplete block of new data (if any) + to the buffer. */ + memcpy(((unsigned char *) ctx_buf) + bytes_have, data, length); + } + + return CURLE_OK; +} + + + +/** + * Size of "length" insertion in bits. + * See FIPS PUB 180-4 section 5.1.2. + */ +#define SHA512_256_SIZE_OF_LEN_ADD_BITS 128 + +/** + * Size of "length" insertion in bytes. + */ +#define SHA512_256_SIZE_OF_LEN_ADD (SHA512_256_SIZE_OF_LEN_ADD_BITS / 8) + +/** + * Finalise SHA-512/256 calculation, return digest. + * + * @param context the calculation context + * @param[out] digest set to the hash, must be #SHA512_256_DIGEST_SIZE bytes + * @return always CURLE_OK + */ +static CURLcode +MHDx_sha512_256_finish(unsigned char *digest, + void *context) +{ + struct mhdx_sha512_256ctx *const ctx = (struct mhdx_sha512_256ctx *)context; + curl_uint64_t num_bits; /**< Number of processed bits */ + unsigned int bytes_have; /**< Number of bytes in the context buffer */ + /* the void pointer here is required to mute Intel compiler warning */ + void *const ctx_buf = ctx->buffer; + + /* Memorise the number of processed bits. + The padding and other data added here during the postprocessing must + not change the amount of hashed data. */ + num_bits = ctx->count << 3; + + /* Note: (count & (SHA512_256_BLOCK_SIZE-1)) + equals (count % SHA512_256_BLOCK_SIZE) for this block size. */ + bytes_have = (unsigned int) (ctx->count & (SHA512_256_BLOCK_SIZE - 1)); + + /* Input data must be padded with a single bit "1", then with zeros and + the finally the length of data in bits must be added as the final bytes + of the last block. + See FIPS PUB 180-4 section 5.1.2. */ + + /* Data is always processed in form of bytes (not by individual bits), + therefore position of the first padding bit in byte is always + predefined (0x80). */ + /* Buffer always have space at least for one byte (as full buffers are + processed when formed). */ + ((unsigned char *) ctx_buf)[bytes_have++] = 0x80U; + + if(SHA512_256_BLOCK_SIZE - bytes_have < SHA512_256_SIZE_OF_LEN_ADD) { + /* No space in the current block to put the total length of message. + Pad the current block with zeros and process it. */ + if(bytes_have < SHA512_256_BLOCK_SIZE) + memset(((unsigned char *) ctx_buf) + bytes_have, 0, + SHA512_256_BLOCK_SIZE - bytes_have); + /* Process the full block. */ + MHDx_sha512_256_transform(ctx->H, ctx->buffer); + /* Start the new block. */ + bytes_have = 0; + } + + /* Pad the rest of the buffer with zeros. */ + memset(((unsigned char *) ctx_buf) + bytes_have, 0, + SHA512_256_BLOCK_SIZE - SHA512_256_SIZE_OF_LEN_ADD - bytes_have); + /* Put high part of number of bits in processed message and then lower + part of number of bits as big-endian values. + See FIPS PUB 180-4 section 5.1.2. */ + /* Note: the target location is predefined and buffer is always aligned */ + MHDX_PUT_64BIT_BE(((unsigned char *) ctx_buf) \ + + SHA512_256_BLOCK_SIZE \ + - SHA512_256_SIZE_OF_LEN_ADD, \ + ctx->count_bits_hi); + MHDX_PUT_64BIT_BE(((unsigned char *) ctx_buf) \ + + SHA512_256_BLOCK_SIZE \ + - SHA512_256_SIZE_OF_LEN_ADD \ + + SHA512_256_BYTES_IN_WORD, \ + num_bits); + /* Process the full final block. */ + MHDx_sha512_256_transform(ctx->H, ctx->buffer); + + /* Put in BE mode the leftmost part of the hash as the final digest. + See FIPS PUB 180-4 section 6.7. */ + + MHDX_PUT_64BIT_BE((digest + 0 * SHA512_256_BYTES_IN_WORD), ctx->H[0]); + MHDX_PUT_64BIT_BE((digest + 1 * SHA512_256_BYTES_IN_WORD), ctx->H[1]); + MHDX_PUT_64BIT_BE((digest + 2 * SHA512_256_BYTES_IN_WORD), ctx->H[2]); + MHDX_PUT_64BIT_BE((digest + 3 * SHA512_256_BYTES_IN_WORD), ctx->H[3]); + + /* Erase potentially sensitive data. */ + memset(ctx, 0, sizeof(struct mhdx_sha512_256ctx)); + + return CURLE_OK; +} + +/* Map to the local implementation */ +#define Curl_sha512_256_init MHDx_sha512_256_init +#define Curl_sha512_256_update MHDx_sha512_256_update +#define Curl_sha512_256_finish MHDx_sha512_256_finish + +#endif /* Local SHA-512/256 code */ + + +/** + * Compute SHA-512/256 hash for the given data in one function call + * @param[out] output the pointer to put the hash + * @param[in] input the pointer to the data to process + * @param input_size the size of the data pointed by @a input + * @return always #CURLE_OK + */ +CURLcode +Curl_sha512_256it(unsigned char *output, const unsigned char *input, + size_t input_size) +{ + Curl_sha512_256_ctx ctx; + CURLcode res; + + res = Curl_sha512_256_init(&ctx); + if(res != CURLE_OK) + return res; + + res = Curl_sha512_256_update(&ctx, (const void *) input, input_size); + + if(res != CURLE_OK) { + (void) Curl_sha512_256_finish(output, &ctx); + return res; + } + + return Curl_sha512_256_finish(output, &ctx); +} + +/* Wrapper function, takes 'unsigned int' as length type, returns void */ +static void +Curl_sha512_256_update_i(void *context, + const unsigned char *data, + unsigned int length) +{ + /* Hypothetically the function may fail, but assume it does not */ + (void) Curl_sha512_256_update(context, data, length); +} + +/* Wrapper function, returns void */ +static void +Curl_sha512_256_finish_v(unsigned char *result, + void *context) +{ + /* Hypothetically the function may fail, but assume it does not */ + (void) Curl_sha512_256_finish(result, context); +} + +/* Wrapper function, takes 'unsigned int' as length type, returns void */ + +const struct HMAC_params Curl_HMAC_SHA512_256[] = { + { + /* Initialize context procedure. */ + Curl_sha512_256_init, + /* Update context with data. */ + Curl_sha512_256_update_i, + /* Get final result procedure. */ + Curl_sha512_256_finish_v, + /* Context structure size. */ + sizeof(Curl_sha512_256_ctx), + /* Maximum key length (bytes). */ + SHA512_256_BLOCK_SIZE, + /* Result length (bytes). */ + SHA512_256_DIGEST_SIZE + } +}; + +#endif /* !CURL_DISABLE_DIGEST_AUTH && !CURL_DISABLE_SHA512_256 */ diff --git a/third_party/curl/lib/curl_sha512_256.h b/third_party/curl/lib/curl_sha512_256.h new file mode 100644 index 0000000..30a9f14 --- /dev/null +++ b/third_party/curl/lib/curl_sha512_256.h @@ -0,0 +1,44 @@ +#ifndef HEADER_CURL_SHA512_256_H +#define HEADER_CURL_SHA512_256_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Evgeny Grin (Karlson2k), . + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#if !defined(CURL_DISABLE_DIGEST_AUTH) && !defined(CURL_DISABLE_SHA512_256) + +#include +#include "curl_hmac.h" + +#define CURL_HAVE_SHA512_256 + +extern const struct HMAC_params Curl_HMAC_SHA512_256[1]; + +#define SHA512_256_DIGEST_LENGTH 32 + +CURLcode +Curl_sha512_256it(unsigned char *output, const unsigned char *input, + size_t input_size); + +#endif /* !CURL_DISABLE_DIGEST_AUTH && !CURL_DISABLE_SHA512_256 */ + +#endif /* HEADER_CURL_SHA256_H */ diff --git a/third_party/curl/lib/curl_sspi.c b/third_party/curl/lib/curl_sspi.c new file mode 100644 index 0000000..eb21e7e --- /dev/null +++ b/third_party/curl/lib/curl_sspi.c @@ -0,0 +1,239 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_WINDOWS_SSPI + +#include +#include "curl_sspi.h" +#include "curl_multibyte.h" +#include "system_win32.h" +#include "version_win32.h" +#include "warnless.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* We use our own typedef here since some headers might lack these */ +typedef PSecurityFunctionTable (APIENTRY *INITSECURITYINTERFACE_FN)(VOID); + +/* See definition of SECURITY_ENTRYPOINT in sspi.h */ +#ifdef UNICODE +# ifdef _WIN32_WCE +# define SECURITYENTRYPOINT L"InitSecurityInterfaceW" +# else +# define SECURITYENTRYPOINT "InitSecurityInterfaceW" +# endif +#else +# define SECURITYENTRYPOINT "InitSecurityInterfaceA" +#endif + +/* Handle of security.dll or secur32.dll, depending on Windows version */ +HMODULE s_hSecDll = NULL; + +/* Pointer to SSPI dispatch table */ +PSecurityFunctionTable s_pSecFn = NULL; + +/* + * Curl_sspi_global_init() + * + * This is used to load the Security Service Provider Interface (SSPI) + * dynamic link library portably across all Windows versions, without + * the need to directly link libcurl, nor the application using it, at + * build time. + * + * Once this function has been executed, Windows SSPI functions can be + * called through the Security Service Provider Interface dispatch table. + * + * Parameters: + * + * None. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_sspi_global_init(void) +{ + INITSECURITYINTERFACE_FN pInitSecurityInterface; + + /* If security interface is not yet initialized try to do this */ + if(!s_hSecDll) { + /* Security Service Provider Interface (SSPI) functions are located in + * security.dll on WinNT 4.0 and in secur32.dll on Win9x. Win2K and XP + * have both these DLLs (security.dll forwards calls to secur32.dll) */ + + /* Load SSPI dll into the address space of the calling process */ + if(curlx_verify_windows_version(4, 0, 0, PLATFORM_WINNT, VERSION_EQUAL)) + s_hSecDll = Curl_load_library(TEXT("security.dll")); + else + s_hSecDll = Curl_load_library(TEXT("secur32.dll")); + if(!s_hSecDll) + return CURLE_FAILED_INIT; + + /* Get address of the InitSecurityInterfaceA function from the SSPI dll */ + pInitSecurityInterface = + CURLX_FUNCTION_CAST(INITSECURITYINTERFACE_FN, + (GetProcAddress(s_hSecDll, SECURITYENTRYPOINT))); + if(!pInitSecurityInterface) + return CURLE_FAILED_INIT; + + /* Get pointer to Security Service Provider Interface dispatch table */ + s_pSecFn = pInitSecurityInterface(); + if(!s_pSecFn) + return CURLE_FAILED_INIT; + } + + return CURLE_OK; +} + +/* + * Curl_sspi_global_cleanup() + * + * This deinitializes the Security Service Provider Interface from libcurl. + * + * Parameters: + * + * None. + */ +void Curl_sspi_global_cleanup(void) +{ + if(s_hSecDll) { + FreeLibrary(s_hSecDll); + s_hSecDll = NULL; + s_pSecFn = NULL; + } +} + +/* + * Curl_create_sspi_identity() + * + * This is used to populate a SSPI identity structure based on the supplied + * username and password. + * + * Parameters: + * + * userp [in] - The user name in the format User or Domain\User. + * passwdp [in] - The user's password. + * identity [in/out] - The identity structure. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_create_sspi_identity(const char *userp, const char *passwdp, + SEC_WINNT_AUTH_IDENTITY *identity) +{ + xcharp_u useranddomain; + xcharp_u user, dup_user; + xcharp_u domain, dup_domain; + xcharp_u passwd, dup_passwd; + size_t domlen = 0; + + domain.const_tchar_ptr = TEXT(""); + + /* Initialize the identity */ + memset(identity, 0, sizeof(*identity)); + + useranddomain.tchar_ptr = curlx_convert_UTF8_to_tchar((char *)userp); + if(!useranddomain.tchar_ptr) + return CURLE_OUT_OF_MEMORY; + + user.const_tchar_ptr = _tcschr(useranddomain.const_tchar_ptr, TEXT('\\')); + if(!user.const_tchar_ptr) + user.const_tchar_ptr = _tcschr(useranddomain.const_tchar_ptr, TEXT('/')); + + if(user.tchar_ptr) { + domain.tchar_ptr = useranddomain.tchar_ptr; + domlen = user.tchar_ptr - useranddomain.tchar_ptr; + user.tchar_ptr++; + } + else { + user.tchar_ptr = useranddomain.tchar_ptr; + domain.const_tchar_ptr = TEXT(""); + domlen = 0; + } + + /* Setup the identity's user and length */ + dup_user.tchar_ptr = _tcsdup(user.tchar_ptr); + if(!dup_user.tchar_ptr) { + curlx_unicodefree(useranddomain.tchar_ptr); + return CURLE_OUT_OF_MEMORY; + } + identity->User = dup_user.tbyte_ptr; + identity->UserLength = curlx_uztoul(_tcslen(dup_user.tchar_ptr)); + dup_user.tchar_ptr = NULL; + + /* Setup the identity's domain and length */ + dup_domain.tchar_ptr = malloc(sizeof(TCHAR) * (domlen + 1)); + if(!dup_domain.tchar_ptr) { + curlx_unicodefree(useranddomain.tchar_ptr); + return CURLE_OUT_OF_MEMORY; + } + _tcsncpy(dup_domain.tchar_ptr, domain.tchar_ptr, domlen); + *(dup_domain.tchar_ptr + domlen) = TEXT('\0'); + identity->Domain = dup_domain.tbyte_ptr; + identity->DomainLength = curlx_uztoul(domlen); + dup_domain.tchar_ptr = NULL; + + curlx_unicodefree(useranddomain.tchar_ptr); + + /* Setup the identity's password and length */ + passwd.tchar_ptr = curlx_convert_UTF8_to_tchar((char *)passwdp); + if(!passwd.tchar_ptr) + return CURLE_OUT_OF_MEMORY; + dup_passwd.tchar_ptr = _tcsdup(passwd.tchar_ptr); + if(!dup_passwd.tchar_ptr) { + curlx_unicodefree(passwd.tchar_ptr); + return CURLE_OUT_OF_MEMORY; + } + identity->Password = dup_passwd.tbyte_ptr; + identity->PasswordLength = curlx_uztoul(_tcslen(dup_passwd.tchar_ptr)); + dup_passwd.tchar_ptr = NULL; + + curlx_unicodefree(passwd.tchar_ptr); + + /* Setup the identity's flags */ + identity->Flags = SECFLAG_WINNT_AUTH_IDENTITY; + + return CURLE_OK; +} + +/* + * Curl_sspi_free_identity() + * + * This is used to free the contents of a SSPI identifier structure. + * + * Parameters: + * + * identity [in/out] - The identity structure. + */ +void Curl_sspi_free_identity(SEC_WINNT_AUTH_IDENTITY *identity) +{ + if(identity) { + Curl_safefree(identity->User); + Curl_safefree(identity->Password); + Curl_safefree(identity->Domain); + } +} + +#endif /* USE_WINDOWS_SSPI */ diff --git a/third_party/curl/lib/curl_sspi.h b/third_party/curl/lib/curl_sspi.h new file mode 100644 index 0000000..b26c391 --- /dev/null +++ b/third_party/curl/lib/curl_sspi.h @@ -0,0 +1,123 @@ +#ifndef HEADER_CURL_SSPI_H +#define HEADER_CURL_SSPI_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_WINDOWS_SSPI + +#include + +/* + * When including the following three headers, it is mandatory to define either + * SECURITY_WIN32 or SECURITY_KERNEL, indicating who is compiling the code. + */ + +#undef SECURITY_WIN32 +#undef SECURITY_KERNEL +#define SECURITY_WIN32 1 +#include +#include +#include + +CURLcode Curl_sspi_global_init(void); +void Curl_sspi_global_cleanup(void); + +/* This is used to populate the domain in a SSPI identity structure */ +CURLcode Curl_override_sspi_http_realm(const char *chlg, + SEC_WINNT_AUTH_IDENTITY *identity); + +/* This is used to generate an SSPI identity structure */ +CURLcode Curl_create_sspi_identity(const char *userp, const char *passwdp, + SEC_WINNT_AUTH_IDENTITY *identity); + +/* This is used to free an SSPI identity structure */ +void Curl_sspi_free_identity(SEC_WINNT_AUTH_IDENTITY *identity); + +/* Forward-declaration of global variables defined in curl_sspi.c */ +extern HMODULE s_hSecDll; +extern PSecurityFunctionTable s_pSecFn; + +/* Provide some definitions missing in old headers */ +#define SP_NAME_DIGEST "WDigest" +#define SP_NAME_NTLM "NTLM" +#define SP_NAME_NEGOTIATE "Negotiate" +#define SP_NAME_KERBEROS "Kerberos" + +#ifndef ISC_REQ_USE_HTTP_STYLE +#define ISC_REQ_USE_HTTP_STYLE 0x01000000 +#endif + +#ifndef SEC_E_INVALID_PARAMETER +# define SEC_E_INVALID_PARAMETER ((HRESULT)0x8009035DL) +#endif +#ifndef SEC_E_DELEGATION_POLICY +# define SEC_E_DELEGATION_POLICY ((HRESULT)0x8009035EL) +#endif +#ifndef SEC_E_POLICY_NLTM_ONLY +# define SEC_E_POLICY_NLTM_ONLY ((HRESULT)0x8009035FL) +#endif + +#ifndef SEC_I_SIGNATURE_NEEDED +# define SEC_I_SIGNATURE_NEEDED ((HRESULT)0x0009035CL) +#endif + +#ifndef CRYPT_E_REVOKED +# define CRYPT_E_REVOKED ((HRESULT)0x80092010L) +#endif + +#ifndef CRYPT_E_NO_REVOCATION_DLL +# define CRYPT_E_NO_REVOCATION_DLL ((HRESULT)0x80092011L) +#endif + +#ifndef CRYPT_E_NO_REVOCATION_CHECK +# define CRYPT_E_NO_REVOCATION_CHECK ((HRESULT)0x80092012L) +#endif + +#ifndef CRYPT_E_REVOCATION_OFFLINE +# define CRYPT_E_REVOCATION_OFFLINE ((HRESULT)0x80092013L) +#endif + +#ifndef CRYPT_E_NOT_IN_REVOCATION_DATABASE +# define CRYPT_E_NOT_IN_REVOCATION_DATABASE ((HRESULT)0x80092014L) +#endif + +#ifdef UNICODE +# define SECFLAG_WINNT_AUTH_IDENTITY \ + (unsigned long)SEC_WINNT_AUTH_IDENTITY_UNICODE +#else +# define SECFLAG_WINNT_AUTH_IDENTITY \ + (unsigned long)SEC_WINNT_AUTH_IDENTITY_ANSI +#endif + +/* + * Definitions required from ntsecapi.h are directly provided below this point + * to avoid including ntsecapi.h due to a conflict with OpenSSL's safestack.h + */ +#define KERB_WRAP_NO_ENCRYPT 0x80000001 + +#endif /* USE_WINDOWS_SSPI */ + +#endif /* HEADER_CURL_SSPI_H */ diff --git a/third_party/curl/lib/curl_threads.c b/third_party/curl/lib/curl_threads.c new file mode 100644 index 0000000..93fa2da --- /dev/null +++ b/third_party/curl/lib/curl_threads.c @@ -0,0 +1,154 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#if defined(USE_THREADS_POSIX) +# ifdef HAVE_PTHREAD_H +# include +# endif +#elif defined(USE_THREADS_WIN32) +# include +#endif + +#include "curl_threads.h" +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + +#if defined(USE_THREADS_POSIX) + +struct Curl_actual_call { + unsigned int (*func)(void *); + void *arg; +}; + +static void *curl_thread_create_thunk(void *arg) +{ + struct Curl_actual_call *ac = arg; + unsigned int (*func)(void *) = ac->func; + void *real_arg = ac->arg; + + free(ac); + + (*func)(real_arg); + + return 0; +} + +curl_thread_t Curl_thread_create(unsigned int (*func) (void *), void *arg) +{ + curl_thread_t t = malloc(sizeof(pthread_t)); + struct Curl_actual_call *ac = malloc(sizeof(struct Curl_actual_call)); + if(!(ac && t)) + goto err; + + ac->func = func; + ac->arg = arg; + + if(pthread_create(t, NULL, curl_thread_create_thunk, ac) != 0) + goto err; + + return t; + +err: + free(t); + free(ac); + return curl_thread_t_null; +} + +void Curl_thread_destroy(curl_thread_t hnd) +{ + if(hnd != curl_thread_t_null) { + pthread_detach(*hnd); + free(hnd); + } +} + +int Curl_thread_join(curl_thread_t *hnd) +{ + int ret = (pthread_join(**hnd, NULL) == 0); + + free(*hnd); + *hnd = curl_thread_t_null; + + return ret; +} + +#elif defined(USE_THREADS_WIN32) + +/* !checksrc! disable SPACEBEFOREPAREN 1 */ +curl_thread_t Curl_thread_create(unsigned int (CURL_STDCALL *func) (void *), + void *arg) +{ +#ifdef _WIN32_WCE + typedef HANDLE curl_win_thread_handle_t; +#else + typedef uintptr_t curl_win_thread_handle_t; +#endif + curl_thread_t t; + curl_win_thread_handle_t thread_handle; +#ifdef _WIN32_WCE + thread_handle = CreateThread(NULL, 0, func, arg, 0, NULL); +#else + thread_handle = _beginthreadex(NULL, 0, func, arg, 0, NULL); +#endif + t = (curl_thread_t)thread_handle; + if((t == 0) || (t == LongToHandle(-1L))) { +#ifdef _WIN32_WCE + DWORD gle = GetLastError(); + errno = ((gle == ERROR_ACCESS_DENIED || + gle == ERROR_NOT_ENOUGH_MEMORY) ? + EACCES : EINVAL); +#endif + return curl_thread_t_null; + } + return t; +} + +void Curl_thread_destroy(curl_thread_t hnd) +{ + if(hnd != curl_thread_t_null) + CloseHandle(hnd); +} + +int Curl_thread_join(curl_thread_t *hnd) +{ +#if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_VISTA) || \ + (_WIN32_WINNT < _WIN32_WINNT_VISTA) + int ret = (WaitForSingleObject(*hnd, INFINITE) == WAIT_OBJECT_0); +#else + int ret = (WaitForSingleObjectEx(*hnd, INFINITE, FALSE) == WAIT_OBJECT_0); +#endif + + Curl_thread_destroy(*hnd); + + *hnd = curl_thread_t_null; + + return ret; +} + +#endif /* USE_THREADS_* */ diff --git a/third_party/curl/lib/curl_threads.h b/third_party/curl/lib/curl_threads.h new file mode 100644 index 0000000..27a478d --- /dev/null +++ b/third_party/curl/lib/curl_threads.h @@ -0,0 +1,65 @@ +#ifndef HEADER_CURL_THREADS_H +#define HEADER_CURL_THREADS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_THREADS_POSIX) +# define CURL_STDCALL +# define curl_mutex_t pthread_mutex_t +# define curl_thread_t pthread_t * +# define curl_thread_t_null (pthread_t *)0 +# define Curl_mutex_init(m) pthread_mutex_init(m, NULL) +# define Curl_mutex_acquire(m) pthread_mutex_lock(m) +# define Curl_mutex_release(m) pthread_mutex_unlock(m) +# define Curl_mutex_destroy(m) pthread_mutex_destroy(m) +#elif defined(USE_THREADS_WIN32) +# define CURL_STDCALL __stdcall +# define curl_mutex_t CRITICAL_SECTION +# define curl_thread_t HANDLE +# define curl_thread_t_null (HANDLE)0 +# if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_VISTA) || \ + (_WIN32_WINNT < _WIN32_WINNT_VISTA) +# define Curl_mutex_init(m) InitializeCriticalSection(m) +# else +# define Curl_mutex_init(m) InitializeCriticalSectionEx(m, 0, 1) +# endif +# define Curl_mutex_acquire(m) EnterCriticalSection(m) +# define Curl_mutex_release(m) LeaveCriticalSection(m) +# define Curl_mutex_destroy(m) DeleteCriticalSection(m) +#endif + +#if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32) + +/* !checksrc! disable SPACEBEFOREPAREN 1 */ +curl_thread_t Curl_thread_create(unsigned int (CURL_STDCALL *func) (void *), + void *arg); + +void Curl_thread_destroy(curl_thread_t hnd); + +int Curl_thread_join(curl_thread_t *hnd); + +#endif /* USE_THREADS_POSIX || USE_THREADS_WIN32 */ + +#endif /* HEADER_CURL_THREADS_H */ diff --git a/third_party/curl/lib/curl_trc.c b/third_party/curl/lib/curl_trc.c new file mode 100644 index 0000000..f017e21 --- /dev/null +++ b/third_party/curl/lib/curl_trc.c @@ -0,0 +1,331 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "curl_trc.h" +#include "urldata.h" +#include "easyif.h" +#include "cfilters.h" +#include "timeval.h" +#include "multiif.h" +#include "strcase.h" + +#include "cf-socket.h" +#include "connect.h" +#include "doh.h" +#include "http2.h" +#include "http_proxy.h" +#include "cf-h1-proxy.h" +#include "cf-h2-proxy.h" +#include "cf-haproxy.h" +#include "cf-https-connect.h" +#include "socks.h" +#include "strtok.h" +#include "vtls/vtls.h" +#include "vquic/vquic.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +void Curl_debug(struct Curl_easy *data, curl_infotype type, + char *ptr, size_t size) +{ + if(data->set.verbose) { + static const char s_infotype[CURLINFO_END][3] = { + "* ", "< ", "> ", "{ ", "} ", "{ ", "} " }; + if(data->set.fdebug) { + bool inCallback = Curl_is_in_callback(data); + Curl_set_in_callback(data, true); + (void)(*data->set.fdebug)(data, type, ptr, size, data->set.debugdata); + Curl_set_in_callback(data, inCallback); + } + else { + switch(type) { + case CURLINFO_TEXT: + case CURLINFO_HEADER_OUT: + case CURLINFO_HEADER_IN: + fwrite(s_infotype[type], 2, 1, data->set.err); + fwrite(ptr, size, 1, data->set.err); + break; + default: /* nada */ + break; + } + } + } +} + + +/* Curl_failf() is for messages stating why we failed. + * The message SHALL NOT include any LF or CR. + */ +void Curl_failf(struct Curl_easy *data, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(data->set.verbose || data->set.errorbuffer) { + va_list ap; + int len; + char error[CURL_ERROR_SIZE + 2]; + va_start(ap, fmt); + len = mvsnprintf(error, CURL_ERROR_SIZE, fmt, ap); + + if(data->set.errorbuffer && !data->state.errorbuf) { + strcpy(data->set.errorbuffer, error); + data->state.errorbuf = TRUE; /* wrote error string */ + } + error[len++] = '\n'; + error[len] = '\0'; + Curl_debug(data, CURLINFO_TEXT, error, len); + va_end(ap); + } +} + +#if !defined(CURL_DISABLE_VERBOSE_STRINGS) + +/* Curl_infof() is for info message along the way */ +#define MAXINFO 2048 + +static void trc_infof(struct Curl_easy *data, struct curl_trc_feat *feat, + const char * const fmt, va_list ap) CURL_PRINTF(3, 0); + +static void trc_infof(struct Curl_easy *data, struct curl_trc_feat *feat, + const char * const fmt, va_list ap) +{ + int len = 0; + char buffer[MAXINFO + 2]; + if(feat) + len = msnprintf(buffer, MAXINFO, "[%s] ", feat->name); + len += mvsnprintf(buffer + len, MAXINFO - len, fmt, ap); + buffer[len++] = '\n'; + buffer[len] = '\0'; + Curl_debug(data, CURLINFO_TEXT, buffer, len); +} + +void Curl_infof(struct Curl_easy *data, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(Curl_trc_is_verbose(data)) { + va_list ap; + va_start(ap, fmt); + trc_infof(data, data->state.feat, fmt, ap); + va_end(ap); + } +} + +void Curl_trc_cf_infof(struct Curl_easy *data, struct Curl_cfilter *cf, + const char *fmt, ...) +{ + DEBUGASSERT(cf); + if(Curl_trc_cf_is_verbose(cf, data)) { + va_list ap; + int len = 0; + char buffer[MAXINFO + 2]; + if(data->state.feat) + len += msnprintf(buffer + len, MAXINFO - len, "[%s] ", + data->state.feat->name); + if(cf->sockindex) + len += msnprintf(buffer + len, MAXINFO - len, "[%s-%d] ", + cf->cft->name, cf->sockindex); + else + len += msnprintf(buffer + len, MAXINFO - len, "[%s] ", cf->cft->name); + va_start(ap, fmt); + len += mvsnprintf(buffer + len, MAXINFO - len, fmt, ap); + va_end(ap); + buffer[len++] = '\n'; + buffer[len] = '\0'; + Curl_debug(data, CURLINFO_TEXT, buffer, len); + } +} + +struct curl_trc_feat Curl_trc_feat_read = { + "READ", + CURL_LOG_LVL_NONE, +}; +struct curl_trc_feat Curl_trc_feat_write = { + "WRITE", + CURL_LOG_LVL_NONE, +}; + +void Curl_trc_read(struct Curl_easy *data, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_read)) { + va_list ap; + va_start(ap, fmt); + trc_infof(data, &Curl_trc_feat_read, fmt, ap); + va_end(ap); + } +} + +void Curl_trc_write(struct Curl_easy *data, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_write)) { + va_list ap; + va_start(ap, fmt); + trc_infof(data, &Curl_trc_feat_write, fmt, ap); + va_end(ap); + } +} + +#ifndef CURL_DISABLE_FTP +struct curl_trc_feat Curl_trc_feat_ftp = { + "FTP", + CURL_LOG_LVL_NONE, +}; + +void Curl_trc_ftp(struct Curl_easy *data, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_ftp)) { + va_list ap; + va_start(ap, fmt); + trc_infof(data, &Curl_trc_feat_ftp, fmt, ap); + va_end(ap); + } +} +#endif /* !CURL_DISABLE_FTP */ + +static struct curl_trc_feat *trc_feats[] = { + &Curl_trc_feat_read, + &Curl_trc_feat_write, +#ifndef CURL_DISABLE_FTP + &Curl_trc_feat_ftp, +#endif +#ifndef CURL_DISABLE_DOH + &Curl_doh_trc, +#endif + NULL, +}; + +static struct Curl_cftype *cf_types[] = { + &Curl_cft_tcp, + &Curl_cft_udp, + &Curl_cft_unix, + &Curl_cft_tcp_accept, + &Curl_cft_happy_eyeballs, + &Curl_cft_setup, +#ifdef USE_NGHTTP2 + &Curl_cft_nghttp2, +#endif +#ifdef USE_SSL + &Curl_cft_ssl, +#ifndef CURL_DISABLE_PROXY + &Curl_cft_ssl_proxy, +#endif +#endif +#if !defined(CURL_DISABLE_PROXY) +#if !defined(CURL_DISABLE_HTTP) + &Curl_cft_h1_proxy, +#ifdef USE_NGHTTP2 + &Curl_cft_h2_proxy, +#endif + &Curl_cft_http_proxy, +#endif /* !CURL_DISABLE_HTTP */ + &Curl_cft_haproxy, + &Curl_cft_socks_proxy, +#endif /* !CURL_DISABLE_PROXY */ +#ifdef USE_HTTP3 + &Curl_cft_http3, +#endif +#if !defined(CURL_DISABLE_HTTP) && !defined(USE_HYPER) + &Curl_cft_http_connect, +#endif + NULL, +}; + +CURLcode Curl_trc_opt(const char *config) +{ + char *token, *tok_buf, *tmp; + size_t i; + int lvl; + + tmp = strdup(config); + if(!tmp) + return CURLE_OUT_OF_MEMORY; + + token = strtok_r(tmp, ", ", &tok_buf); + while(token) { + switch(*token) { + case '-': + lvl = CURL_LOG_LVL_NONE; + ++token; + break; + case '+': + lvl = CURL_LOG_LVL_INFO; + ++token; + break; + default: + lvl = CURL_LOG_LVL_INFO; + break; + } + for(i = 0; cf_types[i]; ++i) { + if(strcasecompare(token, "all")) { + cf_types[i]->log_level = lvl; + } + else if(strcasecompare(token, cf_types[i]->name)) { + cf_types[i]->log_level = lvl; + break; + } + } + for(i = 0; trc_feats[i]; ++i) { + if(strcasecompare(token, "all")) { + trc_feats[i]->log_level = lvl; + } + else if(strcasecompare(token, trc_feats[i]->name)) { + trc_feats[i]->log_level = lvl; + break; + } + } + token = strtok_r(NULL, ", ", &tok_buf); + } + free(tmp); + return CURLE_OK; +} + +CURLcode Curl_trc_init(void) +{ +#ifdef DEBUGBUILD + /* WIP: we use the auto-init from an env var only in DEBUG builds for + * convenience. */ + const char *config = getenv("CURL_DEBUG"); + if(config) { + return Curl_trc_opt(config); + } +#endif /* DEBUGBUILD */ + return CURLE_OK; +} +#else /* defined(CURL_DISABLE_VERBOSE_STRINGS) */ + +CURLcode Curl_trc_init(void) +{ + return CURLE_OK; +} + +#endif /* !defined(CURL_DISABLE_VERBOSE_STRINGS) */ diff --git a/third_party/curl/lib/curl_trc.h b/third_party/curl/lib/curl_trc.h new file mode 100644 index 0000000..3d38018 --- /dev/null +++ b/third_party/curl/lib/curl_trc.h @@ -0,0 +1,200 @@ +#ifndef HEADER_CURL_TRC_H +#define HEADER_CURL_TRC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +struct Curl_easy; +struct Curl_cfilter; + +/** + * Init logging, return != 0 on failure. + */ +CURLcode Curl_trc_init(void); + +/** + * Configure tracing. May be called several times during global + * initialization. Later calls may not take effect. + * + * Configuration format supported: + * - comma-separated list of component names to enable logging on. + * E.g. 'http/2,ssl'. Unknown names are ignored. Names are compared + * case-insensitive. + * - component 'all' applies to all known log components + * - prefixing a component with '+' or '-' will en-/disable logging for + * that component + * Example: 'all,-ssl' would enable logging for all components but the + * SSL filters. + * + * @param config configuration string + */ +CURLcode Curl_trc_opt(const char *config); + +/* the function used to output verbose information */ +void Curl_debug(struct Curl_easy *data, curl_infotype type, + char *ptr, size_t size); + +/** + * Output a failure message on registered callbacks for transfer. + */ +void Curl_failf(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); + +#define failf Curl_failf + +#define CURL_LOG_LVL_NONE 0 +#define CURL_LOG_LVL_INFO 1 + + +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L +#define CURL_HAVE_C99 +#endif + +#ifdef CURL_HAVE_C99 +#define infof(data, ...) \ + do { if(Curl_trc_is_verbose(data)) \ + Curl_infof(data, __VA_ARGS__); } while(0) +#define CURL_TRC_CF(data, cf, ...) \ + do { if(Curl_trc_cf_is_verbose(cf, data)) \ + Curl_trc_cf_infof(data, cf, __VA_ARGS__); } while(0) +#define CURL_TRC_WRITE(data, ...) \ + do { if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_write)) \ + Curl_trc_write(data, __VA_ARGS__); } while(0) +#define CURL_TRC_READ(data, ...) \ + do { if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_read)) \ + Curl_trc_read(data, __VA_ARGS__); } while(0) + +#ifndef CURL_DISABLE_FTP +#define CURL_TRC_FTP(data, ...) \ + do { if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_ftp)) \ + Curl_trc_ftp(data, __VA_ARGS__); } while(0) +#endif /* !CURL_DISABLE_FTP */ + +#else /* CURL_HAVE_C99 */ + +#define infof Curl_infof +#define CURL_TRC_CF Curl_trc_cf_infof +#define CURL_TRC_WRITE Curl_trc_write +#define CURL_TRC_READ Curl_trc_read + +#ifndef CURL_DISABLE_FTP +#define CURL_TRC_FTP Curl_trc_ftp +#endif + +#endif /* !CURL_HAVE_C99 */ + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +/* informational messages enabled */ + +struct curl_trc_feat { + const char *name; + int log_level; +}; +extern struct curl_trc_feat Curl_trc_feat_read; +extern struct curl_trc_feat Curl_trc_feat_write; + +#define Curl_trc_is_verbose(data) \ + ((data) && (data)->set.verbose && \ + (!(data)->state.feat || \ + ((data)->state.feat->log_level >= CURL_LOG_LVL_INFO))) +#define Curl_trc_cf_is_verbose(cf, data) \ + (Curl_trc_is_verbose(data) && \ + (cf) && (cf)->cft->log_level >= CURL_LOG_LVL_INFO) +#define Curl_trc_ft_is_verbose(data, ft) \ + (Curl_trc_is_verbose(data) && \ + (ft)->log_level >= CURL_LOG_LVL_INFO) + +/** + * Output an informational message when transfer's verbose logging is enabled. + */ +void Curl_infof(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); + +/** + * Output an informational message when both transfer's verbose logging + * and connection filters verbose logging are enabled. + */ +void Curl_trc_cf_infof(struct Curl_easy *data, struct Curl_cfilter *cf, + const char *fmt, ...) CURL_PRINTF(3, 4); +void Curl_trc_ft_infof(struct Curl_easy *data, struct curl_trc_feat *ft, + const char *fmt, ...) CURL_PRINTF(3, 4); +void Curl_trc_write(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); +void Curl_trc_read(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); + +#ifndef CURL_DISABLE_FTP +extern struct curl_trc_feat Curl_trc_feat_ftp; +void Curl_trc_ftp(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); +#endif + + +#else /* defined(CURL_DISABLE_VERBOSE_STRINGS) */ +/* All informational messages are not compiled in for size savings */ + +#define Curl_trc_is_verbose(d) (FALSE) +#define Curl_trc_cf_is_verbose(x,y) (FALSE) +#define Curl_trc_ft_is_verbose(x,y) (FALSE) + +static void Curl_infof(struct Curl_easy *data, const char *fmt, ...) +{ + (void)data; (void)fmt; +} + +static void Curl_trc_cf_infof(struct Curl_easy *data, + struct Curl_cfilter *cf, + const char *fmt, ...) +{ + (void)data; (void)cf; (void)fmt; +} + +struct curl_trc_feat; + +static void Curl_trc_ft_infof(struct Curl_easy *data, + struct curl_trc_feat *ft, + const char *fmt, ...) +{ + (void)data; (void)ft; (void)fmt; +} + +static void Curl_trc_write(struct Curl_easy *data, const char *fmt, ...) +{ + (void)data; (void)fmt; +} + +static void Curl_trc_read(struct Curl_easy *data, const char *fmt, ...) +{ + (void)data; (void)fmt; +} + +#ifndef CURL_DISABLE_FTP +static void Curl_trc_ftp(struct Curl_easy *data, const char *fmt, ...) +{ + (void)data; (void)fmt; +} +#endif + +#endif /* !defined(CURL_DISABLE_VERBOSE_STRINGS) */ + +#endif /* HEADER_CURL_TRC_H */ diff --git a/third_party/curl/lib/curlx.h b/third_party/curl/lib/curlx.h new file mode 100644 index 0000000..54e4279 --- /dev/null +++ b/third_party/curl/lib/curlx.h @@ -0,0 +1,117 @@ +#ifndef HEADER_CURL_CURLX_H +#define HEADER_CURL_CURLX_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Defines protos and includes all header files that provide the curlx_* + * functions. The curlx_* functions are not part of the libcurl API, but are + * stand-alone functions whose sources can be built and linked by apps if need + * be. + */ + +#include +/* this is still a public header file that provides the curl_mprintf() + functions while they still are offered publicly. They will be made library- + private one day */ + +#include "strcase.h" +/* "strcase.h" provides the strcasecompare protos */ + +#include "strtoofft.h" +/* "strtoofft.h" provides this function: curlx_strtoofft(), returns a + curl_off_t number from a given string. +*/ + +#include "nonblock.h" +/* "nonblock.h" provides curlx_nonblock() */ + +#include "warnless.h" +/* "warnless.h" provides functions: + + curlx_ultous() + curlx_ultouc() + curlx_uztosi() +*/ + +#include "curl_multibyte.h" +/* "curl_multibyte.h" provides these functions and macros: + + curlx_convert_UTF8_to_wchar() + curlx_convert_wchar_to_UTF8() + curlx_convert_UTF8_to_tchar() + curlx_convert_tchar_to_UTF8() + curlx_unicodefree() +*/ + +#include "version_win32.h" +/* "version_win32.h" provides curlx_verify_windows_version() */ + +/* Now setup curlx_ * names for the functions that are to become curlx_ and + be removed from a future libcurl official API: + curlx_getenv + curlx_mprintf (and its variations) + curlx_strcasecompare + curlx_strncasecompare + +*/ + +#define curlx_mvsnprintf curl_mvsnprintf +#define curlx_msnprintf curl_msnprintf +#define curlx_maprintf curl_maprintf +#define curlx_mvaprintf curl_mvaprintf +#define curlx_msprintf curl_msprintf +#define curlx_mprintf curl_mprintf +#define curlx_mfprintf curl_mfprintf +#define curlx_mvsprintf curl_mvsprintf +#define curlx_mvprintf curl_mvprintf +#define curlx_mvfprintf curl_mvfprintf + +#ifdef ENABLE_CURLX_PRINTF +/* If this define is set, we define all "standard" printf() functions to use + the curlx_* version instead. It makes the source code transparent and + easier to understand/patch. Undefine them first. */ +# undef printf +# undef fprintf +# undef sprintf +# undef msnprintf +# undef vprintf +# undef vfprintf +# undef vsprintf +# undef mvsnprintf +# undef aprintf +# undef vaprintf + +# define printf curlx_mprintf +# define fprintf curlx_mfprintf +# define sprintf curlx_msprintf +# define msnprintf curlx_msnprintf +# define vprintf curlx_mvprintf +# define vfprintf curlx_mvfprintf +# define mvsnprintf curlx_mvsnprintf +# define aprintf curlx_maprintf +# define vaprintf curlx_mvaprintf +#endif /* ENABLE_CURLX_PRINTF */ + +#endif /* HEADER_CURL_CURLX_H */ diff --git a/third_party/curl/lib/cw-out.c b/third_party/curl/lib/cw-out.c new file mode 100644 index 0000000..4e56c6a --- /dev/null +++ b/third_party/curl/lib/cw-out.c @@ -0,0 +1,474 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "urldata.h" +#include "cfilters.h" +#include "headers.h" +#include "multiif.h" +#include "sendf.h" +#include "cw-out.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +/** + * OVERALL DESIGN of this client writer + * + * The 'cw-out' writer is supposed to be the last writer in a transfer's + * stack. It is always added when that stack is initialized. Its purpose + * is to pass BODY and HEADER bytes to the client-installed callback + * functions. + * + * These callback may return `CURL_WRITEFUNC_PAUSE` to indicate that the + * data had not been written and the whole transfer should stop receiving + * new data. Or at least, stop calling the functions. When the transfer + * is "unpaused" by the client, the previous data shall be passed as + * if nothing happened. + * + * The `cw-out` writer therefore manages buffers for bytes that could + * not be written. Data that was already in flight from the server also + * needs buffering on paused transfer when it arrives. + * + * In addition, the writer allows buffering of "small" body writes, + * so client functions are called less often. That is only enabled on a + * number of conditions. + * + * HEADER and BODY data may arrive in any order. For paused transfers, + * a list of `struct cw_out_buf` is kept for `cw_out_type` types. The + * list may be: [BODY]->[HEADER]->[BODY]->[HEADER].... + * When unpausing, this list is "played back" to the client callbacks. + * + * The amount of bytes being buffered is limited by `DYN_PAUSE_BUFFER` + * and when that is exceeded `CURLE_TOO_LARGE` is returned as error. + */ +typedef enum { + CW_OUT_NONE, + CW_OUT_BODY, + CW_OUT_HDS +} cw_out_type; + +struct cw_out_buf { + struct cw_out_buf *next; + struct dynbuf b; + cw_out_type type; +}; + +static struct cw_out_buf *cw_out_buf_create(cw_out_type otype) +{ + struct cw_out_buf *cwbuf = calloc(1, sizeof(*cwbuf)); + if(cwbuf) { + cwbuf->type = otype; + Curl_dyn_init(&cwbuf->b, DYN_PAUSE_BUFFER); + } + return cwbuf; +} + +static void cw_out_buf_free(struct cw_out_buf *cwbuf) +{ + if(cwbuf) { + Curl_dyn_free(&cwbuf->b); + free(cwbuf); + } +} + +struct cw_out_ctx { + struct Curl_cwriter super; + struct cw_out_buf *buf; + BIT(paused); + BIT(errored); +}; + +static CURLcode cw_out_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes); +static void cw_out_close(struct Curl_easy *data, struct Curl_cwriter *writer); +static CURLcode cw_out_init(struct Curl_easy *data, + struct Curl_cwriter *writer); + +struct Curl_cwtype Curl_cwt_out = { + "cw-out", + NULL, + cw_out_init, + cw_out_write, + cw_out_close, + sizeof(struct cw_out_ctx) +}; + +static CURLcode cw_out_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct cw_out_ctx *ctx = writer->ctx; + (void)data; + ctx->buf = NULL; + return CURLE_OK; +} + +static void cw_out_bufs_free(struct cw_out_ctx *ctx) +{ + while(ctx->buf) { + struct cw_out_buf *next = ctx->buf->next; + cw_out_buf_free(ctx->buf); + ctx->buf = next; + } +} + +static size_t cw_out_bufs_len(struct cw_out_ctx *ctx) +{ + struct cw_out_buf *cwbuf = ctx->buf; + size_t len = 0; + while(cwbuf) { + len += Curl_dyn_len(&cwbuf->b); + cwbuf = cwbuf->next; + } + return len; +} + +static void cw_out_close(struct Curl_easy *data, struct Curl_cwriter *writer) +{ + struct cw_out_ctx *ctx = writer->ctx; + + (void)data; + cw_out_bufs_free(ctx); +} + +/** + * Return the current curl_write_callback and user_data for the buf type + */ +static void cw_get_writefunc(struct Curl_easy *data, cw_out_type otype, + curl_write_callback *pwcb, void **pwcb_data, + size_t *pmax_write, size_t *pmin_write) +{ + switch(otype) { + case CW_OUT_BODY: + *pwcb = data->set.fwrite_func; + *pwcb_data = data->set.out; + *pmax_write = CURL_MAX_WRITE_SIZE; + /* if we ever want buffering of BODY output, we can set `min_write` + * the preferred size. The default should always be to pass data + * to the client as it comes without delay */ + *pmin_write = 0; + break; + case CW_OUT_HDS: + *pwcb = data->set.fwrite_header? data->set.fwrite_header : + (data->set.writeheader? data->set.fwrite_func : NULL); + *pwcb_data = data->set.writeheader; + *pmax_write = 0; /* do not chunk-write headers, write them as they are */ + *pmin_write = 0; + break; + default: + *pwcb = NULL; + *pwcb_data = NULL; + *pmax_write = CURL_MAX_WRITE_SIZE; + *pmin_write = 0; + } +} + +static CURLcode cw_out_ptr_flush(struct cw_out_ctx *ctx, + struct Curl_easy *data, + cw_out_type otype, + bool flush_all, + const char *buf, size_t blen, + size_t *pconsumed) +{ + curl_write_callback wcb; + void *wcb_data; + size_t max_write, min_write; + size_t wlen, nwritten; + + /* If we errored once, we do not invoke the client callback again */ + if(ctx->errored) + return CURLE_WRITE_ERROR; + + /* write callbacks may get NULLed by the client between calls. */ + cw_get_writefunc(data, otype, &wcb, &wcb_data, &max_write, &min_write); + if(!wcb) { + *pconsumed = blen; + return CURLE_OK; + } + + *pconsumed = 0; + while(blen && !ctx->paused) { + if(!flush_all && blen < min_write) + break; + wlen = max_write? CURLMIN(blen, max_write) : blen; + Curl_set_in_callback(data, TRUE); + nwritten = wcb((char *)buf, 1, wlen, wcb_data); + Curl_set_in_callback(data, FALSE); + CURL_TRC_WRITE(data, "cw_out, wrote %zu %s bytes -> %zu", + wlen, (otype == CW_OUT_BODY)? "body" : "header", + nwritten); + if(CURL_WRITEFUNC_PAUSE == nwritten) { + if(data->conn && data->conn->handler->flags & PROTOPT_NONETWORK) { + /* Protocols that work without network cannot be paused. This is + actually only FILE:// just now, and it can't pause since the + transfer isn't done using the "normal" procedure. */ + failf(data, "Write callback asked for PAUSE when not supported"); + return CURLE_WRITE_ERROR; + } + /* mark the connection as RECV paused */ + data->req.keepon |= KEEP_RECV_PAUSE; + ctx->paused = TRUE; + CURL_TRC_WRITE(data, "cw_out, PAUSE requested by client"); + break; + } + else if(CURL_WRITEFUNC_ERROR == nwritten) { + failf(data, "client returned ERROR on write of %zu bytes", wlen); + return CURLE_WRITE_ERROR; + } + else if(nwritten != wlen) { + failf(data, "Failure writing output to destination, " + "passed %zu returned %zd", wlen, nwritten); + return CURLE_WRITE_ERROR; + } + *pconsumed += nwritten; + blen -= nwritten; + buf += nwritten; + } + return CURLE_OK; +} + +static CURLcode cw_out_buf_flush(struct cw_out_ctx *ctx, + struct Curl_easy *data, + struct cw_out_buf *cwbuf, + bool flush_all) +{ + CURLcode result = CURLE_OK; + + if(Curl_dyn_len(&cwbuf->b)) { + size_t consumed; + + result = cw_out_ptr_flush(ctx, data, cwbuf->type, flush_all, + Curl_dyn_ptr(&cwbuf->b), + Curl_dyn_len(&cwbuf->b), + &consumed); + if(result) + return result; + + if(consumed) { + if(consumed == Curl_dyn_len(&cwbuf->b)) { + Curl_dyn_free(&cwbuf->b); + } + else { + DEBUGASSERT(consumed < Curl_dyn_len(&cwbuf->b)); + result = Curl_dyn_tail(&cwbuf->b, Curl_dyn_len(&cwbuf->b) - consumed); + if(result) + return result; + } + } + } + return result; +} + +static CURLcode cw_out_flush_chain(struct cw_out_ctx *ctx, + struct Curl_easy *data, + struct cw_out_buf **pcwbuf, + bool flush_all) +{ + struct cw_out_buf *cwbuf = *pcwbuf; + CURLcode result; + + if(!cwbuf) + return CURLE_OK; + if(ctx->paused) + return CURLE_OK; + + /* write the end of the chain until it blocks or gets empty */ + while(cwbuf->next) { + struct cw_out_buf **plast = &cwbuf->next; + while((*plast)->next) + plast = &(*plast)->next; + result = cw_out_flush_chain(ctx, data, plast, flush_all); + if(result) + return result; + if(*plast) { + /* could not write last, paused again? */ + DEBUGASSERT(ctx->paused); + return CURLE_OK; + } + } + + result = cw_out_buf_flush(ctx, data, cwbuf, flush_all); + if(result) + return result; + if(!Curl_dyn_len(&cwbuf->b)) { + cw_out_buf_free(cwbuf); + *pcwbuf = NULL; + } + return CURLE_OK; +} + +static CURLcode cw_out_append(struct cw_out_ctx *ctx, + cw_out_type otype, + const char *buf, size_t blen) +{ + if(cw_out_bufs_len(ctx) + blen > DYN_PAUSE_BUFFER) + return CURLE_TOO_LARGE; + + /* if we do not have a buffer, or it is of another type, make a new one. + * And for CW_OUT_HDS always make a new one, so we "replay" headers + * exactly as they came in */ + if(!ctx->buf || (ctx->buf->type != otype) || (otype == CW_OUT_HDS)) { + struct cw_out_buf *cwbuf = cw_out_buf_create(otype); + if(!cwbuf) + return CURLE_OUT_OF_MEMORY; + cwbuf->next = ctx->buf; + ctx->buf = cwbuf; + } + DEBUGASSERT(ctx->buf && (ctx->buf->type == otype)); + return Curl_dyn_addn(&ctx->buf->b, buf, blen); +} + +static CURLcode cw_out_do_write(struct cw_out_ctx *ctx, + struct Curl_easy *data, + cw_out_type otype, + bool flush_all, + const char *buf, size_t blen) +{ + CURLcode result = CURLE_OK; + + /* if we have buffered data and it is a different type than what + * we are writing now, try to flush all */ + if(ctx->buf && ctx->buf->type != otype) { + result = cw_out_flush_chain(ctx, data, &ctx->buf, TRUE); + if(result) + goto out; + } + + if(ctx->buf) { + /* still have buffered data, append and flush */ + result = cw_out_append(ctx, otype, buf, blen); + if(result) + return result; + result = cw_out_flush_chain(ctx, data, &ctx->buf, flush_all); + if(result) + goto out; + } + else { + /* nothing buffered, try direct write */ + size_t consumed; + result = cw_out_ptr_flush(ctx, data, otype, flush_all, + buf, blen, &consumed); + if(result) + return result; + if(consumed < blen) { + /* did not write all, append the rest */ + result = cw_out_append(ctx, otype, buf + consumed, blen - consumed); + if(result) + goto out; + } + } + +out: + if(result) { + /* We do not want to invoked client callbacks a second time after + * encountering an error. See issue #13337 */ + ctx->errored = TRUE; + cw_out_bufs_free(ctx); + } + return result; +} + +static CURLcode cw_out_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t blen) +{ + struct cw_out_ctx *ctx = writer->ctx; + CURLcode result; + bool flush_all; + + flush_all = (type & CLIENTWRITE_EOS)? TRUE:FALSE; + if((type & CLIENTWRITE_BODY) || + ((type & CLIENTWRITE_HEADER) && data->set.include_header)) { + result = cw_out_do_write(ctx, data, CW_OUT_BODY, flush_all, buf, blen); + if(result) + return result; + } + + if(type & (CLIENTWRITE_HEADER|CLIENTWRITE_INFO)) { + result = cw_out_do_write(ctx, data, CW_OUT_HDS, flush_all, buf, blen); + if(result) + return result; + } + + return CURLE_OK; +} + +bool Curl_cw_out_is_paused(struct Curl_easy *data) +{ + struct Curl_cwriter *cw_out; + struct cw_out_ctx *ctx; + + cw_out = Curl_cwriter_get_by_type(data, &Curl_cwt_out); + if(!cw_out) + return FALSE; + + ctx = (struct cw_out_ctx *)cw_out; + CURL_TRC_WRITE(data, "cw-out is%spaused", ctx->paused? "" : " not"); + return ctx->paused; +} + +static CURLcode cw_out_flush(struct Curl_easy *data, + bool unpause, bool flush_all) +{ + struct Curl_cwriter *cw_out; + CURLcode result = CURLE_OK; + + cw_out = Curl_cwriter_get_by_type(data, &Curl_cwt_out); + if(cw_out) { + struct cw_out_ctx *ctx = (struct cw_out_ctx *)cw_out; + if(ctx->errored) + return CURLE_WRITE_ERROR; + if(unpause && ctx->paused) + ctx->paused = FALSE; + if(ctx->paused) + return CURLE_OK; /* not doing it */ + + result = cw_out_flush_chain(ctx, data, &ctx->buf, flush_all); + if(result) { + ctx->errored = TRUE; + cw_out_bufs_free(ctx); + return result; + } + } + return result; +} + +CURLcode Curl_cw_out_unpause(struct Curl_easy *data) +{ + CURL_TRC_WRITE(data, "cw-out unpause"); + return cw_out_flush(data, TRUE, FALSE); +} + +CURLcode Curl_cw_out_done(struct Curl_easy *data) +{ + CURL_TRC_WRITE(data, "cw-out done"); + return cw_out_flush(data, FALSE, TRUE); +} diff --git a/third_party/curl/lib/cw-out.h b/third_party/curl/lib/cw-out.h new file mode 100644 index 0000000..ca4c2e4 --- /dev/null +++ b/third_party/curl/lib/cw-out.h @@ -0,0 +1,53 @@ +#ifndef HEADER_CURL_CW_OUT_H +#define HEADER_CURL_CW_OUT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "sendf.h" + +/** + * The client writer type "cw-out" that does the actual writing to + * the client callbacks. Intended to be the last installed in the + * client writer stack of a transfer. + */ +extern struct Curl_cwtype Curl_cwt_out; + +/** + * Return TRUE iff 'cw-out' client write has paused data. + */ +bool Curl_cw_out_is_paused(struct Curl_easy *data); + +/** + * Flush any buffered date to the client, chunk collation still applies. + */ +CURLcode Curl_cw_out_unpause(struct Curl_easy *data); + +/** + * Mark EndOfStream reached and flush ALL data to the client. + */ +CURLcode Curl_cw_out_done(struct Curl_easy *data); + +#endif /* HEADER_CURL_CW_OUT_H */ diff --git a/third_party/curl/lib/dict.c b/third_party/curl/lib/dict.c new file mode 100644 index 0000000..a26a28b --- /dev/null +++ b/third_party/curl/lib/dict.c @@ -0,0 +1,321 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_DICT + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NET_IF_H +#include +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif + +#ifdef HAVE_SYS_PARAM_H +#include +#endif + +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif + +#include "urldata.h" +#include +#include "transfer.h" +#include "sendf.h" +#include "escape.h" +#include "progress.h" +#include "dict.h" +#include "curl_printf.h" +#include "strcase.h" +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + +/* + * Forward declarations. + */ + +static CURLcode dict_do(struct Curl_easy *data, bool *done); + +/* + * DICT protocol handler. + */ + +const struct Curl_handler Curl_handler_dict = { + "dict", /* scheme */ + ZERO_NULL, /* setup_connection */ + dict_do, /* do_it */ + ZERO_NULL, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_DICT, /* defport */ + CURLPROTO_DICT, /* protocol */ + CURLPROTO_DICT, /* family */ + PROTOPT_NONE | PROTOPT_NOURLQUERY /* flags */ +}; + +#define DYN_DICT_WORD 10000 +static char *unescape_word(const char *input) +{ + struct dynbuf out; + const char *ptr; + CURLcode result = CURLE_OK; + Curl_dyn_init(&out, DYN_DICT_WORD); + + /* According to RFC2229 section 2.2, these letters need to be escaped with + \[letter] */ + for(ptr = input; *ptr; ptr++) { + char ch = *ptr; + if((ch <= 32) || (ch == 127) || + (ch == '\'') || (ch == '\"') || (ch == '\\')) + result = Curl_dyn_addn(&out, "\\", 1); + if(!result) + result = Curl_dyn_addn(&out, ptr, 1); + if(result) + return NULL; + } + return Curl_dyn_ptr(&out); +} + +/* sendf() sends formatted data to the server */ +static CURLcode sendf(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); + +static CURLcode sendf(struct Curl_easy *data, const char *fmt, ...) +{ + size_t bytes_written; + size_t write_len; + CURLcode result = CURLE_OK; + char *s; + char *sptr; + va_list ap; + va_start(ap, fmt); + s = vaprintf(fmt, ap); /* returns an allocated string */ + va_end(ap); + if(!s) + return CURLE_OUT_OF_MEMORY; /* failure */ + + bytes_written = 0; + write_len = strlen(s); + sptr = s; + + for(;;) { + /* Write the buffer to the socket */ + result = Curl_xfer_send(data, sptr, write_len, &bytes_written); + + if(result) + break; + + Curl_debug(data, CURLINFO_DATA_OUT, sptr, (size_t)bytes_written); + + if((size_t)bytes_written != write_len) { + /* if not all was written at once, we must advance the pointer, decrease + the size left and try again! */ + write_len -= bytes_written; + sptr += bytes_written; + } + else + break; + } + + free(s); /* free the output string */ + + return result; +} + +static CURLcode dict_do(struct Curl_easy *data, bool *done) +{ + char *word; + char *eword = NULL; + char *ppath; + char *database = NULL; + char *strategy = NULL; + char *nthdef = NULL; /* This is not part of the protocol, but required + by RFC 2229 */ + CURLcode result; + + char *path; + + *done = TRUE; /* unconditionally */ + + /* url-decode path before further evaluation */ + result = Curl_urldecode(data->state.up.path, 0, &path, NULL, REJECT_CTRL); + if(result) + return result; + + if(strncasecompare(path, DICT_MATCH, sizeof(DICT_MATCH)-1) || + strncasecompare(path, DICT_MATCH2, sizeof(DICT_MATCH2)-1) || + strncasecompare(path, DICT_MATCH3, sizeof(DICT_MATCH3)-1)) { + + word = strchr(path, ':'); + if(word) { + word++; + database = strchr(word, ':'); + if(database) { + *database++ = (char)0; + strategy = strchr(database, ':'); + if(strategy) { + *strategy++ = (char)0; + nthdef = strchr(strategy, ':'); + if(nthdef) { + *nthdef = (char)0; + } + } + } + } + + if(!word || (*word == (char)0)) { + infof(data, "lookup word is missing"); + word = (char *)"default"; + } + if(!database || (*database == (char)0)) { + database = (char *)"!"; + } + if(!strategy || (*strategy == (char)0)) { + strategy = (char *)"."; + } + + eword = unescape_word(word); + if(!eword) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + result = sendf(data, + "CLIENT " LIBCURL_NAME " " LIBCURL_VERSION "\r\n" + "MATCH " + "%s " /* database */ + "%s " /* strategy */ + "%s\r\n" /* word */ + "QUIT\r\n", + database, + strategy, + eword); + + if(result) { + failf(data, "Failed sending DICT request"); + goto error; + } + Curl_xfer_setup(data, FIRSTSOCKET, -1, FALSE, -1); /* no upload */ + } + else if(strncasecompare(path, DICT_DEFINE, sizeof(DICT_DEFINE)-1) || + strncasecompare(path, DICT_DEFINE2, sizeof(DICT_DEFINE2)-1) || + strncasecompare(path, DICT_DEFINE3, sizeof(DICT_DEFINE3)-1)) { + + word = strchr(path, ':'); + if(word) { + word++; + database = strchr(word, ':'); + if(database) { + *database++ = (char)0; + nthdef = strchr(database, ':'); + if(nthdef) { + *nthdef = (char)0; + } + } + } + + if(!word || (*word == (char)0)) { + infof(data, "lookup word is missing"); + word = (char *)"default"; + } + if(!database || (*database == (char)0)) { + database = (char *)"!"; + } + + eword = unescape_word(word); + if(!eword) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + result = sendf(data, + "CLIENT " LIBCURL_NAME " " LIBCURL_VERSION "\r\n" + "DEFINE " + "%s " /* database */ + "%s\r\n" /* word */ + "QUIT\r\n", + database, + eword); + + if(result) { + failf(data, "Failed sending DICT request"); + goto error; + } + Curl_xfer_setup(data, FIRSTSOCKET, -1, FALSE, -1); + } + else { + + ppath = strchr(path, '/'); + if(ppath) { + int i; + + ppath++; + for(i = 0; ppath[i]; i++) { + if(ppath[i] == ':') + ppath[i] = ' '; + } + result = sendf(data, + "CLIENT " LIBCURL_NAME " " LIBCURL_VERSION "\r\n" + "%s\r\n" + "QUIT\r\n", ppath); + if(result) { + failf(data, "Failed sending DICT request"); + goto error; + } + + Curl_xfer_setup(data, FIRSTSOCKET, -1, FALSE, -1); + } + } + +error: + free(eword); + free(path); + return result; +} +#endif /* CURL_DISABLE_DICT */ diff --git a/third_party/curl/lib/dict.h b/third_party/curl/lib/dict.h new file mode 100644 index 0000000..ba9a927 --- /dev/null +++ b/third_party/curl/lib/dict.h @@ -0,0 +1,31 @@ +#ifndef HEADER_CURL_DICT_H +#define HEADER_CURL_DICT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifndef CURL_DISABLE_DICT +extern const struct Curl_handler Curl_handler_dict; +#endif + +#endif /* HEADER_CURL_DICT_H */ diff --git a/third_party/curl/lib/dllmain.c b/third_party/curl/lib/dllmain.c new file mode 100644 index 0000000..41e97b3 --- /dev/null +++ b/third_party/curl/lib/dllmain.c @@ -0,0 +1,81 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_OPENSSL +#include +#endif + +/* The fourth-to-last include */ +#ifdef __CYGWIN__ +#define WIN32_LEAN_AND_MEAN +#include +#ifdef _WIN32 +#undef _WIN32 +#endif +#endif + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* DllMain() must only be defined for Windows and Cygwin DLL builds. */ +#if (defined(_WIN32) || defined(__CYGWIN__)) && !defined(CURL_STATICLIB) + +#if defined(USE_OPENSSL) && \ + !defined(OPENSSL_IS_AWSLC) && \ + !defined(OPENSSL_IS_BORINGSSL) && \ + !defined(LIBRESSL_VERSION_NUMBER) && \ + (OPENSSL_VERSION_NUMBER >= 0x10100000L) +#define PREVENT_OPENSSL_MEMLEAK +#endif + +#ifdef PREVENT_OPENSSL_MEMLEAK +BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved); +BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) +{ + (void)hinstDLL; + (void)lpvReserved; + + switch(fdwReason) { + case DLL_PROCESS_ATTACH: + break; + case DLL_PROCESS_DETACH: + break; + case DLL_THREAD_ATTACH: + break; + case DLL_THREAD_DETACH: + /* Call OPENSSL_thread_stop to prevent a memory leak in case OpenSSL is + linked statically. + https://github.com/curl/curl/issues/12327#issuecomment-1826405944 */ + OPENSSL_thread_stop(); + break; + } + return TRUE; +} +#endif /* OpenSSL */ + +#endif /* DLL build */ diff --git a/third_party/curl/lib/doh.c b/third_party/curl/lib/doh.c new file mode 100644 index 0000000..03317ae --- /dev/null +++ b/third_party/curl/lib/doh.c @@ -0,0 +1,1403 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_DOH + +#include "urldata.h" +#include "curl_addrinfo.h" +#include "doh.h" + +#include "sendf.h" +#include "multiif.h" +#include "url.h" +#include "share.h" +#include "curl_base64.h" +#include "connect.h" +#include "strdup.h" +#include "dynbuf.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" +#include "escape.h" + +#define DNS_CLASS_IN 0x01 + +/* local_print_buf truncates if the hex string will be more than this */ +#define LOCAL_PB_HEXMAX 400 + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +static const char * const errors[]={ + "", + "Bad label", + "Out of range", + "Label loop", + "Too small", + "Out of memory", + "RDATA length", + "Malformat", + "Bad RCODE", + "Unexpected TYPE", + "Unexpected CLASS", + "No content", + "Bad ID", + "Name too long" +}; + +static const char *doh_strerror(DOHcode code) +{ + if((code >= DOH_OK) && (code <= DOH_DNS_NAME_TOO_LONG)) + return errors[code]; + return "bad error code"; +} + +struct curl_trc_feat Curl_doh_trc = { + "DoH", + CURL_LOG_LVL_NONE, +}; +#endif /* !CURL_DISABLE_VERBOSE_STRINGS */ + +/* @unittest 1655 + */ +UNITTEST DOHcode doh_encode(const char *host, + DNStype dnstype, + unsigned char *dnsp, /* buffer */ + size_t len, /* buffer size */ + size_t *olen) /* output length */ +{ + const size_t hostlen = strlen(host); + unsigned char *orig = dnsp; + const char *hostp = host; + + /* The expected output length is 16 bytes more than the length of + * the QNAME-encoding of the host name. + * + * A valid DNS name may not contain a zero-length label, except at + * the end. For this reason, a name beginning with a dot, or + * containing a sequence of two or more consecutive dots, is invalid + * and cannot be encoded as a QNAME. + * + * If the host name ends with a trailing dot, the corresponding + * QNAME-encoding is one byte longer than the host name. If (as is + * also valid) the hostname is shortened by the omission of the + * trailing dot, then its QNAME-encoding will be two bytes longer + * than the host name. + * + * Each [ label, dot ] pair is encoded as [ length, label ], + * preserving overall length. A final [ label ] without a dot is + * also encoded as [ length, label ], increasing overall length + * by one. The encoding is completed by appending a zero byte, + * representing the zero-length root label, again increasing + * the overall length by one. + */ + + size_t expected_len; + DEBUGASSERT(hostlen); + expected_len = 12 + 1 + hostlen + 4; + if(host[hostlen-1]!='.') + expected_len++; + + if(expected_len > (256 + 16)) /* RFCs 1034, 1035 */ + return DOH_DNS_NAME_TOO_LONG; + + if(len < expected_len) + return DOH_TOO_SMALL_BUFFER; + + *dnsp++ = 0; /* 16 bit id */ + *dnsp++ = 0; + *dnsp++ = 0x01; /* |QR| Opcode |AA|TC|RD| Set the RD bit */ + *dnsp++ = '\0'; /* |RA| Z | RCODE | */ + *dnsp++ = '\0'; + *dnsp++ = 1; /* QDCOUNT (number of entries in the question section) */ + *dnsp++ = '\0'; + *dnsp++ = '\0'; /* ANCOUNT */ + *dnsp++ = '\0'; + *dnsp++ = '\0'; /* NSCOUNT */ + *dnsp++ = '\0'; + *dnsp++ = '\0'; /* ARCOUNT */ + + /* encode each label and store it in the QNAME */ + while(*hostp) { + size_t labellen; + char *dot = strchr(hostp, '.'); + if(dot) + labellen = dot - hostp; + else + labellen = strlen(hostp); + if((labellen > 63) || (!labellen)) { + /* label is too long or too short, error out */ + *olen = 0; + return DOH_DNS_BAD_LABEL; + } + /* label is non-empty, process it */ + *dnsp++ = (unsigned char)labellen; + memcpy(dnsp, hostp, labellen); + dnsp += labellen; + hostp += labellen; + /* advance past dot, but only if there is one */ + if(dot) + hostp++; + } /* next label */ + + *dnsp++ = 0; /* append zero-length label for root */ + + /* There are assigned TYPE codes beyond 255: use range [1..65535] */ + *dnsp++ = (unsigned char)(255 & (dnstype>>8)); /* upper 8 bit TYPE */ + *dnsp++ = (unsigned char)(255 & dnstype); /* lower 8 bit TYPE */ + + *dnsp++ = '\0'; /* upper 8 bit CLASS */ + *dnsp++ = DNS_CLASS_IN; /* IN - "the Internet" */ + + *olen = dnsp - orig; + + /* verify that our estimation of length is valid, since + * this has led to buffer overflows in this function */ + DEBUGASSERT(*olen == expected_len); + return DOH_OK; +} + +static size_t +doh_write_cb(const void *contents, size_t size, size_t nmemb, void *userp) +{ + size_t realsize = size * nmemb; + struct dynbuf *mem = (struct dynbuf *)userp; + + if(Curl_dyn_addn(mem, contents, realsize)) + return 0; + + return realsize; +} + +#if defined(USE_HTTPSRR) && defined(CURLDEBUG) +static void local_print_buf(struct Curl_easy *data, + const char *prefix, + unsigned char *buf, size_t len) +{ + unsigned char hexstr[LOCAL_PB_HEXMAX]; + size_t hlen = LOCAL_PB_HEXMAX; + bool truncated = false; + + if(len > (LOCAL_PB_HEXMAX / 2)) + truncated = true; + Curl_hexencode(buf, len, hexstr, hlen); + if(!truncated) + infof(data, "%s: len=%d, val=%s", prefix, (int)len, hexstr); + else + infof(data, "%s: len=%d (truncated)val=%s", prefix, (int)len, hexstr); + return; +} +#endif + +/* called from multi.c when this DoH transfer is complete */ +static int doh_done(struct Curl_easy *doh, CURLcode result) +{ + struct Curl_easy *data = doh->set.dohfor; + struct dohdata *dohp = data->req.doh; + /* so one of the DoH request done for the 'data' transfer is now complete! */ + dohp->pending--; + infof(doh, "a DoH request is completed, %u to go", dohp->pending); + if(result) + infof(doh, "DoH request %s", curl_easy_strerror(result)); + + if(!dohp->pending) { + /* DoH completed */ + curl_slist_free_all(dohp->headers); + dohp->headers = NULL; + Curl_expire(data, 0, EXPIRE_RUN_NOW); + } + return 0; +} + +#define ERROR_CHECK_SETOPT(x,y) \ +do { \ + result = curl_easy_setopt(doh, x, y); \ + if(result && \ + result != CURLE_NOT_BUILT_IN && \ + result != CURLE_UNKNOWN_OPTION) \ + goto error; \ +} while(0) + +static CURLcode dohprobe(struct Curl_easy *data, + struct dnsprobe *p, DNStype dnstype, + const char *host, + const char *url, CURLM *multi, + struct curl_slist *headers) +{ + struct Curl_easy *doh = NULL; + CURLcode result = CURLE_OK; + timediff_t timeout_ms; + DOHcode d = doh_encode(host, dnstype, p->dohbuffer, sizeof(p->dohbuffer), + &p->dohlen); + if(d) { + failf(data, "Failed to encode DoH packet [%d]", d); + return CURLE_OUT_OF_MEMORY; + } + + p->dnstype = dnstype; + Curl_dyn_init(&p->serverdoh, DYN_DOH_RESPONSE); + + timeout_ms = Curl_timeleft(data, NULL, TRUE); + if(timeout_ms <= 0) { + result = CURLE_OPERATION_TIMEDOUT; + goto error; + } + /* Curl_open() is the internal version of curl_easy_init() */ + result = Curl_open(&doh); + if(!result) { + /* pass in the struct pointer via a local variable to please coverity and + the gcc typecheck helpers */ + struct dynbuf *resp = &p->serverdoh; + doh->state.internal = true; +#ifndef CURL_DISABLE_VERBOSE_STRINGS + doh->state.feat = &Curl_doh_trc; +#endif + ERROR_CHECK_SETOPT(CURLOPT_URL, url); + ERROR_CHECK_SETOPT(CURLOPT_DEFAULT_PROTOCOL, "https"); + ERROR_CHECK_SETOPT(CURLOPT_WRITEFUNCTION, doh_write_cb); + ERROR_CHECK_SETOPT(CURLOPT_WRITEDATA, resp); + ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDS, p->dohbuffer); + ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDSIZE, (long)p->dohlen); + ERROR_CHECK_SETOPT(CURLOPT_HTTPHEADER, headers); +#ifdef USE_HTTP2 + ERROR_CHECK_SETOPT(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS); + ERROR_CHECK_SETOPT(CURLOPT_PIPEWAIT, 1L); +#endif +#ifndef CURLDEBUG + /* enforce HTTPS if not debug */ + ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTPS); +#else + /* in debug mode, also allow http */ + ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTP|CURLPROTO_HTTPS); +#endif + ERROR_CHECK_SETOPT(CURLOPT_TIMEOUT_MS, (long)timeout_ms); + ERROR_CHECK_SETOPT(CURLOPT_SHARE, data->share); + if(data->set.err && data->set.err != stderr) + ERROR_CHECK_SETOPT(CURLOPT_STDERR, data->set.err); + if(Curl_trc_ft_is_verbose(data, &Curl_doh_trc)) + ERROR_CHECK_SETOPT(CURLOPT_VERBOSE, 1L); + if(data->set.no_signal) + ERROR_CHECK_SETOPT(CURLOPT_NOSIGNAL, 1L); + + ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYHOST, + data->set.doh_verifyhost ? 2L : 0L); + ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYPEER, + data->set.doh_verifypeer ? 1L : 0L); + ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYSTATUS, + data->set.doh_verifystatus ? 1L : 0L); + + /* Inherit *some* SSL options from the user's transfer. This is a + best-guess as to which options are needed for compatibility. #3661 + + Note DoH does not inherit the user's proxy server so proxy SSL settings + have no effect and are not inherited. If that changes then two new + options should be added to check doh proxy insecure separately, + CURLOPT_DOH_PROXY_SSL_VERIFYHOST and CURLOPT_DOH_PROXY_SSL_VERIFYPEER. + */ + if(data->set.ssl.falsestart) + ERROR_CHECK_SETOPT(CURLOPT_SSL_FALSESTART, 1L); + if(data->set.str[STRING_SSL_CAFILE]) { + ERROR_CHECK_SETOPT(CURLOPT_CAINFO, + data->set.str[STRING_SSL_CAFILE]); + } + if(data->set.blobs[BLOB_CAINFO]) { + ERROR_CHECK_SETOPT(CURLOPT_CAINFO_BLOB, + data->set.blobs[BLOB_CAINFO]); + } + if(data->set.str[STRING_SSL_CAPATH]) { + ERROR_CHECK_SETOPT(CURLOPT_CAPATH, + data->set.str[STRING_SSL_CAPATH]); + } + if(data->set.str[STRING_SSL_CRLFILE]) { + ERROR_CHECK_SETOPT(CURLOPT_CRLFILE, + data->set.str[STRING_SSL_CRLFILE]); + } + if(data->set.ssl.certinfo) + ERROR_CHECK_SETOPT(CURLOPT_CERTINFO, 1L); + if(data->set.ssl.fsslctx) + ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_FUNCTION, data->set.ssl.fsslctx); + if(data->set.ssl.fsslctxp) + ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_DATA, data->set.ssl.fsslctxp); + if(data->set.fdebug) + ERROR_CHECK_SETOPT(CURLOPT_DEBUGFUNCTION, data->set.fdebug); + if(data->set.debugdata) + ERROR_CHECK_SETOPT(CURLOPT_DEBUGDATA, data->set.debugdata); + if(data->set.str[STRING_SSL_EC_CURVES]) { + ERROR_CHECK_SETOPT(CURLOPT_SSL_EC_CURVES, + data->set.str[STRING_SSL_EC_CURVES]); + } + + { + long mask = + (data->set.ssl.enable_beast ? + CURLSSLOPT_ALLOW_BEAST : 0) | + (data->set.ssl.no_revoke ? + CURLSSLOPT_NO_REVOKE : 0) | + (data->set.ssl.no_partialchain ? + CURLSSLOPT_NO_PARTIALCHAIN : 0) | + (data->set.ssl.revoke_best_effort ? + CURLSSLOPT_REVOKE_BEST_EFFORT : 0) | + (data->set.ssl.native_ca_store ? + CURLSSLOPT_NATIVE_CA : 0) | + (data->set.ssl.auto_client_cert ? + CURLSSLOPT_AUTO_CLIENT_CERT : 0); + + (void)curl_easy_setopt(doh, CURLOPT_SSL_OPTIONS, mask); + } + + doh->set.fmultidone = doh_done; + doh->set.dohfor = data; /* identify for which transfer this is done */ + p->easy = doh; + + /* DoH handles must not inherit private_data. The handles may be passed to + the user via callbacks and the user will be able to identify them as + internal handles because private data is not set. The user can then set + private_data via CURLOPT_PRIVATE if they so choose. */ + DEBUGASSERT(!doh->set.private_data); + + if(curl_multi_add_handle(multi, doh)) + goto error; + } + else + goto error; + return CURLE_OK; + +error: + Curl_close(&doh); + return result; +} + +/* + * Curl_doh() resolves a name using DoH. It resolves a name and returns a + * 'Curl_addrinfo *' with the address information. + */ + +struct Curl_addrinfo *Curl_doh(struct Curl_easy *data, + const char *hostname, + int port, + int *waitp) +{ + CURLcode result = CURLE_OK; + int slot; + struct dohdata *dohp; + struct connectdata *conn = data->conn; +#ifdef USE_HTTPSRR + /* for now, this is only used when ECH is enabled */ +# ifdef USE_ECH + char *qname = NULL; +# endif +#endif + *waitp = FALSE; + (void)hostname; + (void)port; + + DEBUGASSERT(!data->req.doh); + DEBUGASSERT(conn); + + /* start clean, consider allocating this struct on demand */ + dohp = data->req.doh = calloc(1, sizeof(struct dohdata)); + if(!dohp) + return NULL; + + conn->bits.doh = TRUE; + dohp->host = hostname; + dohp->port = port; + dohp->headers = + curl_slist_append(NULL, + "Content-Type: application/dns-message"); + if(!dohp->headers) + goto error; + + /* create IPv4 DoH request */ + result = dohprobe(data, &dohp->probe[DOH_PROBE_SLOT_IPADDR_V4], + DNS_TYPE_A, hostname, data->set.str[STRING_DOH], + data->multi, dohp->headers); + if(result) + goto error; + dohp->pending++; + +#ifdef USE_IPV6 + if((conn->ip_version != CURL_IPRESOLVE_V4) && Curl_ipv6works(data)) { + /* create IPv6 DoH request */ + result = dohprobe(data, &dohp->probe[DOH_PROBE_SLOT_IPADDR_V6], + DNS_TYPE_AAAA, hostname, data->set.str[STRING_DOH], + data->multi, dohp->headers); + if(result) + goto error; + dohp->pending++; + } +#endif + +#ifdef USE_HTTPSRR + /* + * TODO: Figure out the conditions under which we want to make + * a request for an HTTPS RR when we are not doing ECH. For now, + * making this request breaks a bunch of DoH tests, e.g. test2100, + * where the additional request doesn't match the pre-cooked data + * files, so there's a bit of work attached to making the request + * in a non-ECH use-case. For the present, we'll only make the + * request when ECH is enabled in the build and is being used for + * the curl operation. + */ +# ifdef USE_ECH + if(data->set.tls_ech & CURLECH_ENABLE + || data->set.tls_ech & CURLECH_HARD) { + if(port == 443) + qname = strdup(hostname); + else + qname = aprintf("_%d._https.%s", port, hostname); + if(!qname) + goto error; + result = dohprobe(data, &dohp->probe[DOH_PROBE_SLOT_HTTPS], + DNS_TYPE_HTTPS, qname, data->set.str[STRING_DOH], + data->multi, dohp->headers); + free(qname); + if(result) + goto error; + dohp->pending++; + } +# endif +#endif + *waitp = TRUE; /* this never returns synchronously */ + return NULL; + +error: + curl_slist_free_all(dohp->headers); + data->req.doh->headers = NULL; + for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) { + (void)curl_multi_remove_handle(data->multi, dohp->probe[slot].easy); + Curl_close(&dohp->probe[slot].easy); + } + Curl_safefree(data->req.doh); + return NULL; +} + +static DOHcode skipqname(const unsigned char *doh, size_t dohlen, + unsigned int *indexp) +{ + unsigned char length; + do { + if(dohlen < (*indexp + 1)) + return DOH_DNS_OUT_OF_RANGE; + length = doh[*indexp]; + if((length & 0xc0) == 0xc0) { + /* name pointer, advance over it and be done */ + if(dohlen < (*indexp + 2)) + return DOH_DNS_OUT_OF_RANGE; + *indexp += 2; + break; + } + if(length & 0xc0) + return DOH_DNS_BAD_LABEL; + if(dohlen < (*indexp + 1 + length)) + return DOH_DNS_OUT_OF_RANGE; + *indexp += (unsigned int)(1 + length); + } while(length); + return DOH_OK; +} + +static unsigned short get16bit(const unsigned char *doh, int index) +{ + return (unsigned short)((doh[index] << 8) | doh[index + 1]); +} + +static unsigned int get32bit(const unsigned char *doh, int index) +{ + /* make clang and gcc optimize this to bswap by incrementing + the pointer first. */ + doh += index; + + /* avoid undefined behavior by casting to unsigned before shifting + 24 bits, possibly into the sign bit. codegen is same, but + ub sanitizer won't be upset */ + return ((unsigned)doh[0] << 24) | ((unsigned)doh[1] << 16) | + ((unsigned)doh[2] << 8) | doh[3]; +} + +static DOHcode store_a(const unsigned char *doh, int index, struct dohentry *d) +{ + /* silently ignore addresses over the limit */ + if(d->numaddr < DOH_MAX_ADDR) { + struct dohaddr *a = &d->addr[d->numaddr]; + a->type = DNS_TYPE_A; + memcpy(&a->ip.v4, &doh[index], 4); + d->numaddr++; + } + return DOH_OK; +} + +static DOHcode store_aaaa(const unsigned char *doh, + int index, + struct dohentry *d) +{ + /* silently ignore addresses over the limit */ + if(d->numaddr < DOH_MAX_ADDR) { + struct dohaddr *a = &d->addr[d->numaddr]; + a->type = DNS_TYPE_AAAA; + memcpy(&a->ip.v6, &doh[index], 16); + d->numaddr++; + } + return DOH_OK; +} + +#ifdef USE_HTTPSRR +static DOHcode store_https(const unsigned char *doh, + int index, + struct dohentry *d, + uint16_t len) +{ + /* silently ignore RRs over the limit */ + if(d->numhttps_rrs < DOH_MAX_HTTPS) { + struct dohhttps_rr *h = &d->https_rrs[d->numhttps_rrs]; + h->val = Curl_memdup(&doh[index], len); + if(!h->val) + return DOH_OUT_OF_MEM; + h->len = len; + d->numhttps_rrs++; + } + return DOH_OK; +} +#endif + +static DOHcode store_cname(const unsigned char *doh, + size_t dohlen, + unsigned int index, + struct dohentry *d) +{ + struct dynbuf *c; + unsigned int loop = 128; /* a valid DNS name can never loop this much */ + unsigned char length; + + if(d->numcname == DOH_MAX_CNAME) + return DOH_OK; /* skip! */ + + c = &d->cname[d->numcname++]; + do { + if(index >= dohlen) + return DOH_DNS_OUT_OF_RANGE; + length = doh[index]; + if((length & 0xc0) == 0xc0) { + int newpos; + /* name pointer, get the new offset (14 bits) */ + if((index + 1) >= dohlen) + return DOH_DNS_OUT_OF_RANGE; + + /* move to the new index */ + newpos = (length & 0x3f) << 8 | doh[index + 1]; + index = newpos; + continue; + } + else if(length & 0xc0) + return DOH_DNS_BAD_LABEL; /* bad input */ + else + index++; + + if(length) { + if(Curl_dyn_len(c)) { + if(Curl_dyn_addn(c, STRCONST("."))) + return DOH_OUT_OF_MEM; + } + if((index + length) > dohlen) + return DOH_DNS_BAD_LABEL; + + if(Curl_dyn_addn(c, &doh[index], length)) + return DOH_OUT_OF_MEM; + index += length; + } + } while(length && --loop); + + if(!loop) + return DOH_DNS_LABEL_LOOP; + return DOH_OK; +} + +static DOHcode rdata(const unsigned char *doh, + size_t dohlen, + unsigned short rdlength, + unsigned short type, + int index, + struct dohentry *d) +{ + /* RDATA + - A (TYPE 1): 4 bytes + - AAAA (TYPE 28): 16 bytes + - NS (TYPE 2): N bytes + - HTTPS (TYPE 65): N bytes */ + DOHcode rc; + + switch(type) { + case DNS_TYPE_A: + if(rdlength != 4) + return DOH_DNS_RDATA_LEN; + rc = store_a(doh, index, d); + if(rc) + return rc; + break; + case DNS_TYPE_AAAA: + if(rdlength != 16) + return DOH_DNS_RDATA_LEN; + rc = store_aaaa(doh, index, d); + if(rc) + return rc; + break; +#ifdef USE_HTTPSRR + case DNS_TYPE_HTTPS: + rc = store_https(doh, index, d, rdlength); + if(rc) + return rc; + break; +#endif + case DNS_TYPE_CNAME: + rc = store_cname(doh, dohlen, index, d); + if(rc) + return rc; + break; + case DNS_TYPE_DNAME: + /* explicit for clarity; just skip; rely on synthesized CNAME */ + break; + default: + /* unsupported type, just skip it */ + break; + } + return DOH_OK; +} + +UNITTEST void de_init(struct dohentry *de) +{ + int i; + memset(de, 0, sizeof(*de)); + de->ttl = INT_MAX; + for(i = 0; i < DOH_MAX_CNAME; i++) + Curl_dyn_init(&de->cname[i], DYN_DOH_CNAME); +} + + +UNITTEST DOHcode doh_decode(const unsigned char *doh, + size_t dohlen, + DNStype dnstype, + struct dohentry *d) +{ + unsigned char rcode; + unsigned short qdcount; + unsigned short ancount; + unsigned short type = 0; + unsigned short rdlength; + unsigned short nscount; + unsigned short arcount; + unsigned int index = 12; + DOHcode rc; + + if(dohlen < 12) + return DOH_TOO_SMALL_BUFFER; /* too small */ + if(!doh || doh[0] || doh[1]) + return DOH_DNS_BAD_ID; /* bad ID */ + rcode = doh[3] & 0x0f; + if(rcode) + return DOH_DNS_BAD_RCODE; /* bad rcode */ + + qdcount = get16bit(doh, 4); + while(qdcount) { + rc = skipqname(doh, dohlen, &index); + if(rc) + return rc; /* bad qname */ + if(dohlen < (index + 4)) + return DOH_DNS_OUT_OF_RANGE; + index += 4; /* skip question's type and class */ + qdcount--; + } + + ancount = get16bit(doh, 6); + while(ancount) { + unsigned short class; + unsigned int ttl; + + rc = skipqname(doh, dohlen, &index); + if(rc) + return rc; /* bad qname */ + + if(dohlen < (index + 2)) + return DOH_DNS_OUT_OF_RANGE; + + type = get16bit(doh, index); + if((type != DNS_TYPE_CNAME) /* may be synthesized from DNAME */ + && (type != DNS_TYPE_DNAME) /* if present, accept and ignore */ + && (type != dnstype)) + /* Not the same type as was asked for nor CNAME nor DNAME */ + return DOH_DNS_UNEXPECTED_TYPE; + index += 2; + + if(dohlen < (index + 2)) + return DOH_DNS_OUT_OF_RANGE; + class = get16bit(doh, index); + if(DNS_CLASS_IN != class) + return DOH_DNS_UNEXPECTED_CLASS; /* unsupported */ + index += 2; + + if(dohlen < (index + 4)) + return DOH_DNS_OUT_OF_RANGE; + + ttl = get32bit(doh, index); + if(ttl < d->ttl) + d->ttl = ttl; + index += 4; + + if(dohlen < (index + 2)) + return DOH_DNS_OUT_OF_RANGE; + + rdlength = get16bit(doh, index); + index += 2; + if(dohlen < (index + rdlength)) + return DOH_DNS_OUT_OF_RANGE; + + rc = rdata(doh, dohlen, rdlength, type, index, d); + if(rc) + return rc; /* bad rdata */ + index += rdlength; + ancount--; + } + + nscount = get16bit(doh, 8); + while(nscount) { + rc = skipqname(doh, dohlen, &index); + if(rc) + return rc; /* bad qname */ + + if(dohlen < (index + 8)) + return DOH_DNS_OUT_OF_RANGE; + + index += 2 + 2 + 4; /* type, class and ttl */ + + if(dohlen < (index + 2)) + return DOH_DNS_OUT_OF_RANGE; + + rdlength = get16bit(doh, index); + index += 2; + if(dohlen < (index + rdlength)) + return DOH_DNS_OUT_OF_RANGE; + index += rdlength; + nscount--; + } + + arcount = get16bit(doh, 10); + while(arcount) { + rc = skipqname(doh, dohlen, &index); + if(rc) + return rc; /* bad qname */ + + if(dohlen < (index + 8)) + return DOH_DNS_OUT_OF_RANGE; + + index += 2 + 2 + 4; /* type, class and ttl */ + + if(dohlen < (index + 2)) + return DOH_DNS_OUT_OF_RANGE; + + rdlength = get16bit(doh, index); + index += 2; + if(dohlen < (index + rdlength)) + return DOH_DNS_OUT_OF_RANGE; + index += rdlength; + arcount--; + } + + if(index != dohlen) + return DOH_DNS_MALFORMAT; /* something is wrong */ + +#ifdef USE_HTTTPS + if((type != DNS_TYPE_NS) && !d->numcname && !d->numaddr && !d->numhttps_rrs) +#else + if((type != DNS_TYPE_NS) && !d->numcname && !d->numaddr) +#endif + /* nothing stored! */ + return DOH_NO_CONTENT; + + return DOH_OK; /* ok */ +} + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +static void showdoh(struct Curl_easy *data, + const struct dohentry *d) +{ + int i; + infof(data, "[DoH] TTL: %u seconds", d->ttl); + for(i = 0; i < d->numaddr; i++) { + const struct dohaddr *a = &d->addr[i]; + if(a->type == DNS_TYPE_A) { + infof(data, "[DoH] A: %u.%u.%u.%u", + a->ip.v4[0], a->ip.v4[1], + a->ip.v4[2], a->ip.v4[3]); + } + else if(a->type == DNS_TYPE_AAAA) { + int j; + char buffer[128]; + char *ptr; + size_t len; + len = msnprintf(buffer, 128, "[DoH] AAAA: "); + ptr = &buffer[len]; + len = sizeof(buffer) - len; + for(j = 0; j < 16; j += 2) { + size_t l; + msnprintf(ptr, len, "%s%02x%02x", j?":":"", d->addr[i].ip.v6[j], + d->addr[i].ip.v6[j + 1]); + l = strlen(ptr); + len -= l; + ptr += l; + } + infof(data, "%s", buffer); + } + } +#ifdef USE_HTTPSRR + for(i = 0; i < d->numhttps_rrs; i++) { +# ifdef CURLDEBUG + local_print_buf(data, "DoH HTTPS", + d->https_rrs[i].val, d->https_rrs[i].len); +# else + infof(data, "DoH HTTPS RR: length %d", d->https_rrs[i].len); +# endif + } +#endif + for(i = 0; i < d->numcname; i++) { + infof(data, "CNAME: %s", Curl_dyn_ptr(&d->cname[i])); + } +} +#else +#define showdoh(x,y) +#endif + +/* + * doh2ai() + * + * This function returns a pointer to the first element of a newly allocated + * Curl_addrinfo struct linked list filled with the data from a set of DoH + * lookups. Curl_addrinfo is meant to work like the addrinfo struct does for + * a IPv6 stack, but usable also for IPv4, all hosts and environments. + * + * The memory allocated by this function *MUST* be free'd later on calling + * Curl_freeaddrinfo(). For each successful call to this function there + * must be an associated call later to Curl_freeaddrinfo(). + */ + +static CURLcode doh2ai(const struct dohentry *de, const char *hostname, + int port, struct Curl_addrinfo **aip) +{ + struct Curl_addrinfo *ai; + struct Curl_addrinfo *prevai = NULL; + struct Curl_addrinfo *firstai = NULL; + struct sockaddr_in *addr; +#ifdef USE_IPV6 + struct sockaddr_in6 *addr6; +#endif + CURLcode result = CURLE_OK; + int i; + size_t hostlen = strlen(hostname) + 1; /* include null-terminator */ + + DEBUGASSERT(de); + + if(!de->numaddr) + return CURLE_COULDNT_RESOLVE_HOST; + + for(i = 0; i < de->numaddr; i++) { + size_t ss_size; + CURL_SA_FAMILY_T addrtype; + if(de->addr[i].type == DNS_TYPE_AAAA) { +#ifndef USE_IPV6 + /* we can't handle IPv6 addresses */ + continue; +#else + ss_size = sizeof(struct sockaddr_in6); + addrtype = AF_INET6; +#endif + } + else { + ss_size = sizeof(struct sockaddr_in); + addrtype = AF_INET; + } + + ai = calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen); + if(!ai) { + result = CURLE_OUT_OF_MEMORY; + break; + } + ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo)); + ai->ai_canonname = (void *)((char *)ai->ai_addr + ss_size); + memcpy(ai->ai_canonname, hostname, hostlen); + + if(!firstai) + /* store the pointer we want to return from this function */ + firstai = ai; + + if(prevai) + /* make the previous entry point to this */ + prevai->ai_next = ai; + + ai->ai_family = addrtype; + + /* we return all names as STREAM, so when using this address for TFTP + the type must be ignored and conn->socktype be used instead! */ + ai->ai_socktype = SOCK_STREAM; + + ai->ai_addrlen = (curl_socklen_t)ss_size; + + /* leave the rest of the struct filled with zero */ + + switch(ai->ai_family) { + case AF_INET: + addr = (void *)ai->ai_addr; /* storage area for this info */ + DEBUGASSERT(sizeof(struct in_addr) == sizeof(de->addr[i].ip.v4)); + memcpy(&addr->sin_addr, &de->addr[i].ip.v4, sizeof(struct in_addr)); + addr->sin_family = addrtype; + addr->sin_port = htons((unsigned short)port); + break; + +#ifdef USE_IPV6 + case AF_INET6: + addr6 = (void *)ai->ai_addr; /* storage area for this info */ + DEBUGASSERT(sizeof(struct in6_addr) == sizeof(de->addr[i].ip.v6)); + memcpy(&addr6->sin6_addr, &de->addr[i].ip.v6, sizeof(struct in6_addr)); + addr6->sin6_family = addrtype; + addr6->sin6_port = htons((unsigned short)port); + break; +#endif + } + + prevai = ai; + } + + if(result) { + Curl_freeaddrinfo(firstai); + firstai = NULL; + } + *aip = firstai; + + return result; +} + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +static const char *type2name(DNStype dnstype) +{ + switch(dnstype) { + case DNS_TYPE_A: + return "A"; + case DNS_TYPE_AAAA: + return "AAAA"; +#ifdef USE_HTTPSRR + case DNS_TYPE_HTTPS: + return "HTTPS"; +#endif + default: + return "unknown"; + } +} +#endif + +UNITTEST void de_cleanup(struct dohentry *d) +{ + int i = 0; + for(i = 0; i < d->numcname; i++) { + Curl_dyn_free(&d->cname[i]); + } +#ifdef USE_HTTPSRR + for(i = 0; i < d->numhttps_rrs; i++) + free(d->https_rrs[i].val); +#endif +} + +#ifdef USE_HTTPSRR + +/* + * @brief decode the DNS name in a binary RRData + * @param buf points to the buffer (in/out) + * @param remaining points to the remaining buffer length (in/out) + * @param dnsname returns the string form name on success + * @return is 1 for success, error otherwise + * + * The encoding here is defined in + * https://tools.ietf.org/html/rfc1035#section-3.1 + * + * The input buffer pointer will be modified so it points to + * just after the end of the DNS name encoding on output. (And + * that's why it's an "unsigned char **" :-) + */ +static CURLcode local_decode_rdata_name(unsigned char **buf, size_t *remaining, + char **dnsname) +{ + unsigned char *cp = NULL; + int rem = 0; + unsigned char clen = 0; /* chunk len */ + struct dynbuf thename; + + DEBUGASSERT(buf && remaining && dnsname); + if(!buf || !remaining || !dnsname) + return CURLE_OUT_OF_MEMORY; + rem = (int)*remaining; + if(rem <= 0) { + Curl_dyn_free(&thename); + return CURLE_OUT_OF_MEMORY; + } + Curl_dyn_init(&thename, CURL_MAXLEN_host_name); + cp = *buf; + clen = *cp++; + if(clen == 0) { + /* special case - return "." as name */ + if(Curl_dyn_addn(&thename, ".", 1)) + return CURLE_OUT_OF_MEMORY; + } + while(clen) { + if(clen >= rem) { + Curl_dyn_free(&thename); + return CURLE_OUT_OF_MEMORY; + } + if(Curl_dyn_addn(&thename, cp, clen) || + Curl_dyn_addn(&thename, ".", 1)) + return CURLE_TOO_LARGE; + + cp += clen; + rem -= (clen + 1); + if(rem <= 0) { + Curl_dyn_free(&thename); + return CURLE_OUT_OF_MEMORY; + } + clen = *cp++; + } + *buf = cp; + *remaining = rem - 1; + *dnsname = Curl_dyn_ptr(&thename); + return CURLE_OK; +} + +static CURLcode local_decode_rdata_alpn(unsigned char *rrval, size_t len, + char **alpns) +{ + /* + * spec here is as per draft-ietf-dnsop-svcb-https, section-7.1.1 + * encoding is catenated list of strings each preceded by a one + * octet length + * output is comma-sep list of the strings + * implementations may or may not handle quoting of comma within + * string values, so we might see a comma within the wire format + * version of a string, in which case we'll precede that by a + * backslash - same goes for a backslash character, and of course + * we need to use two backslashes in strings when we mean one;-) + */ + int remaining = (int) len; + char *oval; + size_t i; + unsigned char *cp = rrval; + struct dynbuf dval; + + if(!alpns) + return CURLE_OUT_OF_MEMORY; + Curl_dyn_init(&dval, DYN_DOH_RESPONSE); + remaining = (int)len; + cp = rrval; + while(remaining > 0) { + size_t tlen = (size_t) *cp++; + + /* if not 1st time, add comma */ + if(remaining != (int)len && Curl_dyn_addn(&dval, ",", 1)) + goto err; + remaining--; + if(tlen > (size_t)remaining) + goto err; + /* add escape char if needed, clunky but easier to read */ + for(i = 0; i != tlen; i++) { + if('\\' == *cp || ',' == *cp) { + if(Curl_dyn_addn(&dval, "\\", 1)) + goto err; + } + if(Curl_dyn_addn(&dval, cp++, 1)) + goto err; + } + remaining -= (int)tlen; + } + /* this string is always null terminated */ + oval = Curl_dyn_ptr(&dval); + if(!oval) + goto err; + *alpns = oval; + return CURLE_OK; +err: + Curl_dyn_free(&dval); + return CURLE_BAD_CONTENT_ENCODING; +} + +#ifdef CURLDEBUG +static CURLcode test_alpn_escapes(void) +{ + /* we'll use an example from draft-ietf-dnsop-svcb, figure 10 */ + static unsigned char example[] = { + 0x08, /* length 8 */ + 0x66, 0x5c, 0x6f, 0x6f, 0x2c, 0x62, 0x61, 0x72, /* value "f\\oo,bar" */ + 0x02, /* length 2 */ + 0x68, 0x32 /* value "h2" */ + }; + size_t example_len = sizeof(example); + char *aval = NULL; + static const char *expected = "f\\\\oo\\,bar,h2"; + + if(local_decode_rdata_alpn(example, example_len, &aval) != CURLE_OK) + return CURLE_BAD_CONTENT_ENCODING; + if(strlen(aval) != strlen(expected)) + return CURLE_BAD_CONTENT_ENCODING; + if(memcmp(aval, expected, strlen(aval))) + return CURLE_BAD_CONTENT_ENCODING; + return CURLE_OK; +} +#endif + +static CURLcode Curl_doh_decode_httpsrr(unsigned char *rrval, size_t len, + struct Curl_https_rrinfo **hrr) +{ + size_t remaining = len; + unsigned char *cp = rrval; + uint16_t pcode = 0, plen = 0; + struct Curl_https_rrinfo *lhrr = NULL; + char *dnsname = NULL; + +#ifdef CURLDEBUG + /* a few tests of escaping, shouldn't be here but ok for now */ + if(test_alpn_escapes() != CURLE_OK) + return CURLE_OUT_OF_MEMORY; +#endif + lhrr = calloc(1, sizeof(struct Curl_https_rrinfo)); + if(!lhrr) + return CURLE_OUT_OF_MEMORY; + lhrr->val = Curl_memdup(rrval, len); + if(!lhrr->val) + goto err; + lhrr->len = len; + if(remaining <= 2) + goto err; + lhrr->priority = (uint16_t)((cp[0] << 8) + cp[1]); + cp += 2; + remaining -= (uint16_t)2; + if(local_decode_rdata_name(&cp, &remaining, &dnsname) != CURLE_OK) + goto err; + lhrr->target = dnsname; + while(remaining >= 4) { + pcode = (uint16_t)((*cp << 8) + (*(cp + 1))); + cp += 2; + plen = (uint16_t)((*cp << 8) + (*(cp + 1))); + cp += 2; + remaining -= 4; + if(pcode == HTTPS_RR_CODE_ALPN) { + if(local_decode_rdata_alpn(cp, plen, &lhrr->alpns) != CURLE_OK) + goto err; + } + if(pcode == HTTPS_RR_CODE_NO_DEF_ALPN) + lhrr->no_def_alpn = TRUE; + else if(pcode == HTTPS_RR_CODE_IPV4) { + lhrr->ipv4hints = Curl_memdup(cp, plen); + if(!lhrr->ipv4hints) + goto err; + lhrr->ipv4hints_len = (size_t)plen; + } + else if(pcode == HTTPS_RR_CODE_ECH) { + lhrr->echconfiglist = Curl_memdup(cp, plen); + if(!lhrr->echconfiglist) + goto err; + lhrr->echconfiglist_len = (size_t)plen; + } + else if(pcode == HTTPS_RR_CODE_IPV6) { + lhrr->ipv6hints = Curl_memdup(cp, plen); + if(!lhrr->ipv6hints) + goto err; + lhrr->ipv6hints_len = (size_t)plen; + } + if(plen > 0 && plen <= remaining) { + cp += plen; + remaining -= plen; + } + } + DEBUGASSERT(!remaining); + *hrr = lhrr; + return CURLE_OK; +err: + if(lhrr) { + free(lhrr->target); + free(lhrr->echconfiglist); + free(lhrr->val); + free(lhrr); + } + return CURLE_OUT_OF_MEMORY; +} + +# ifdef CURLDEBUG +static void local_print_httpsrr(struct Curl_easy *data, + struct Curl_https_rrinfo *hrr) +{ + DEBUGASSERT(hrr); + infof(data, "HTTPS RR: priority %d, target: %s", + hrr->priority, hrr->target); + if(hrr->alpns) + infof(data, "HTTPS RR: alpns %s", hrr->alpns); + else + infof(data, "HTTPS RR: no alpns"); + if(hrr->no_def_alpn) + infof(data, "HTTPS RR: no_def_alpn set"); + else + infof(data, "HTTPS RR: no_def_alpn not set"); + if(hrr->ipv4hints) { + local_print_buf(data, "HTTPS RR: ipv4hints", + hrr->ipv4hints, hrr->ipv4hints_len); + } + else + infof(data, "HTTPS RR: no ipv4hints"); + if(hrr->echconfiglist) { + local_print_buf(data, "HTTPS RR: ECHConfigList", + hrr->echconfiglist, hrr->echconfiglist_len); + } + else + infof(data, "HTTPS RR: no ECHConfigList"); + if(hrr->ipv6hints) { + local_print_buf(data, "HTTPS RR: ipv6hint", + hrr->ipv6hints, hrr->ipv6hints_len); + } + else + infof(data, "HTTPS RR: no ipv6hints"); + return; +} +# endif +#endif + +CURLcode Curl_doh_is_resolved(struct Curl_easy *data, + struct Curl_dns_entry **dnsp) +{ + CURLcode result; + struct dohdata *dohp = data->req.doh; + *dnsp = NULL; /* defaults to no response */ + if(!dohp) + return CURLE_OUT_OF_MEMORY; + + if(!dohp->probe[DOH_PROBE_SLOT_IPADDR_V4].easy && + !dohp->probe[DOH_PROBE_SLOT_IPADDR_V6].easy) { + failf(data, "Could not DoH-resolve: %s", data->state.async.hostname); + return CONN_IS_PROXIED(data->conn)?CURLE_COULDNT_RESOLVE_PROXY: + CURLE_COULDNT_RESOLVE_HOST; + } + else if(!dohp->pending) { +#ifndef USE_HTTPSRR + DOHcode rc[DOH_PROBE_SLOTS] = { + DOH_OK, DOH_OK + }; +#else + DOHcode rc[DOH_PROBE_SLOTS] = { + DOH_OK, DOH_OK, DOH_OK + }; +#endif + struct dohentry de; + int slot; + /* remove DoH handles from multi handle and close them */ + for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) { + curl_multi_remove_handle(data->multi, dohp->probe[slot].easy); + Curl_close(&dohp->probe[slot].easy); + } + /* parse the responses, create the struct and return it! */ + de_init(&de); + for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) { + struct dnsprobe *p = &dohp->probe[slot]; + if(!p->dnstype) + continue; + rc[slot] = doh_decode(Curl_dyn_uptr(&p->serverdoh), + Curl_dyn_len(&p->serverdoh), + p->dnstype, + &de); + Curl_dyn_free(&p->serverdoh); +#ifndef CURL_DISABLE_VERBOSE_STRINGS + if(rc[slot]) { + infof(data, "DoH: %s type %s for %s", doh_strerror(rc[slot]), + type2name(p->dnstype), dohp->host); + } +#endif + } /* next slot */ + + result = CURLE_COULDNT_RESOLVE_HOST; /* until we know better */ + if(!rc[DOH_PROBE_SLOT_IPADDR_V4] || !rc[DOH_PROBE_SLOT_IPADDR_V6]) { + /* we have an address, of one kind or other */ + struct Curl_dns_entry *dns; + struct Curl_addrinfo *ai; + + + if(Curl_trc_ft_is_verbose(data, &Curl_doh_trc)) { + infof(data, "[DoH] Host name: %s", dohp->host); + showdoh(data, &de); + } + + result = doh2ai(&de, dohp->host, dohp->port, &ai); + if(result) { + de_cleanup(&de); + return result; + } + + if(data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + /* we got a response, store it in the cache */ + dns = Curl_cache_addr(data, ai, dohp->host, 0, dohp->port); + + if(data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); + + if(!dns) { + /* returned failure, bail out nicely */ + Curl_freeaddrinfo(ai); + } + else { + data->state.async.dns = dns; + *dnsp = dns; + result = CURLE_OK; /* address resolution OK */ + } + } /* address processing done */ + + /* Now process any build-specific attributes retrieved from DNS */ +#ifdef USE_HTTPSRR + if(de.numhttps_rrs > 0 && result == CURLE_OK && *dnsp) { + struct Curl_https_rrinfo *hrr = NULL; + result = Curl_doh_decode_httpsrr(de.https_rrs->val, de.https_rrs->len, + &hrr); + if(result) { + infof(data, "Failed to decode HTTPS RR"); + return result; + } + infof(data, "Some HTTPS RR to process"); +# ifdef CURLDEBUG + local_print_httpsrr(data, hrr); +# endif + (*dnsp)->hinfo = hrr; + } +#endif + + /* All done */ + de_cleanup(&de); + Curl_safefree(data->req.doh); + return result; + + } /* !dohp->pending */ + + /* else wait for pending DoH transactions to complete */ + return CURLE_OK; +} + +#endif /* CURL_DISABLE_DOH */ diff --git a/third_party/curl/lib/doh.h b/third_party/curl/lib/doh.h new file mode 100644 index 0000000..bb881ec --- /dev/null +++ b/third_party/curl/lib/doh.h @@ -0,0 +1,165 @@ +#ifndef HEADER_CURL_DOH_H +#define HEADER_CURL_DOH_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "urldata.h" +#include "curl_addrinfo.h" +#ifdef USE_HTTPSRR +# include +#endif + +#ifndef CURL_DISABLE_DOH + +typedef enum { + DOH_OK, + DOH_DNS_BAD_LABEL, /* 1 */ + DOH_DNS_OUT_OF_RANGE, /* 2 */ + DOH_DNS_LABEL_LOOP, /* 3 */ + DOH_TOO_SMALL_BUFFER, /* 4 */ + DOH_OUT_OF_MEM, /* 5 */ + DOH_DNS_RDATA_LEN, /* 6 */ + DOH_DNS_MALFORMAT, /* 7 */ + DOH_DNS_BAD_RCODE, /* 8 - no such name */ + DOH_DNS_UNEXPECTED_TYPE, /* 9 */ + DOH_DNS_UNEXPECTED_CLASS, /* 10 */ + DOH_NO_CONTENT, /* 11 */ + DOH_DNS_BAD_ID, /* 12 */ + DOH_DNS_NAME_TOO_LONG /* 13 */ +} DOHcode; + +typedef enum { + DNS_TYPE_A = 1, + DNS_TYPE_NS = 2, + DNS_TYPE_CNAME = 5, + DNS_TYPE_AAAA = 28, + DNS_TYPE_DNAME = 39, /* RFC6672 */ + DNS_TYPE_HTTPS = 65 +} DNStype; + +/* one of these for each DoH request */ +struct dnsprobe { + CURL *easy; + DNStype dnstype; + unsigned char dohbuffer[512]; + size_t dohlen; + struct dynbuf serverdoh; +}; + +struct dohdata { + struct curl_slist *headers; + struct dnsprobe probe[DOH_PROBE_SLOTS]; + unsigned int pending; /* still outstanding requests */ + int port; + const char *host; +}; + +/* + * Curl_doh() resolve a name using DoH (DNS-over-HTTPS). It resolves a name + * and returns a 'Curl_addrinfo *' with the address information. + */ + +struct Curl_addrinfo *Curl_doh(struct Curl_easy *data, + const char *hostname, + int port, + int *waitp); + +CURLcode Curl_doh_is_resolved(struct Curl_easy *data, + struct Curl_dns_entry **dns); + +#define DOH_MAX_ADDR 24 +#define DOH_MAX_CNAME 4 +#define DOH_MAX_HTTPS 4 + +struct dohaddr { + int type; + union { + unsigned char v4[4]; /* network byte order */ + unsigned char v6[16]; + } ip; +}; + +#ifdef USE_HTTPSRR + +/* + * These are the code points for DNS wire format SvcParams as + * per draft-ietf-dnsop-svcb-https + * Not all are supported now, and even those that are may need + * more work in future to fully support the spec. + */ +#define HTTPS_RR_CODE_ALPN 0x01 +#define HTTPS_RR_CODE_NO_DEF_ALPN 0x02 +#define HTTPS_RR_CODE_PORT 0x03 +#define HTTPS_RR_CODE_IPV4 0x04 +#define HTTPS_RR_CODE_ECH 0x05 +#define HTTPS_RR_CODE_IPV6 0x06 + +/* + * These may need escaping when found within an alpn string + * value. + */ +#define COMMA_CHAR ',' +#define BACKSLASH_CHAR '\\' + +struct dohhttps_rr { + uint16_t len; /* raw encoded length */ + unsigned char *val; /* raw encoded octets */ +}; +#endif + +struct dohentry { + struct dynbuf cname[DOH_MAX_CNAME]; + struct dohaddr addr[DOH_MAX_ADDR]; + int numaddr; + unsigned int ttl; + int numcname; +#ifdef USE_HTTPSRR + struct dohhttps_rr https_rrs[DOH_MAX_HTTPS]; + int numhttps_rrs; +#endif +}; + + +#ifdef DEBUGBUILD +DOHcode doh_encode(const char *host, + DNStype dnstype, + unsigned char *dnsp, /* buffer */ + size_t len, /* buffer size */ + size_t *olen); /* output length */ +DOHcode doh_decode(const unsigned char *doh, + size_t dohlen, + DNStype dnstype, + struct dohentry *d); +void de_init(struct dohentry *d); +void de_cleanup(struct dohentry *d); +#endif + +extern struct curl_trc_feat Curl_doh_trc; + +#else /* if DoH is disabled */ +#define Curl_doh(a,b,c,d) NULL +#define Curl_doh_is_resolved(x,y) CURLE_COULDNT_RESOLVE_HOST +#endif + +#endif /* HEADER_CURL_DOH_H */ diff --git a/third_party/curl/lib/dynbuf.c b/third_party/curl/lib/dynbuf.c new file mode 100644 index 0000000..3b62eaf --- /dev/null +++ b/third_party/curl/lib/dynbuf.c @@ -0,0 +1,282 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "dynbuf.h" +#include "curl_printf.h" +#ifdef BUILDING_LIBCURL +#include "curl_memory.h" +#endif +#include "memdebug.h" + +#define MIN_FIRST_ALLOC 32 + +#define DYNINIT 0xbee51da /* random pattern */ + +/* + * Init a dynbuf struct. + */ +void Curl_dyn_init(struct dynbuf *s, size_t toobig) +{ + DEBUGASSERT(s); + DEBUGASSERT(toobig); + s->bufr = NULL; + s->leng = 0; + s->allc = 0; + s->toobig = toobig; +#ifdef DEBUGBUILD + s->init = DYNINIT; +#endif +} + +/* + * free the buffer and re-init the necessary fields. It doesn't touch the + * 'init' field and thus this buffer can be reused to add data to again. + */ +void Curl_dyn_free(struct dynbuf *s) +{ + DEBUGASSERT(s); + Curl_safefree(s->bufr); + s->leng = s->allc = 0; +} + +/* + * Store/append an chunk of memory to the dynbuf. + */ +static CURLcode dyn_nappend(struct dynbuf *s, + const unsigned char *mem, size_t len) +{ + size_t indx = s->leng; + size_t a = s->allc; + size_t fit = len + indx + 1; /* new string + old string + zero byte */ + + /* try to detect if there's rubbish in the struct */ + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(s->toobig); + DEBUGASSERT(indx < s->toobig); + DEBUGASSERT(!s->leng || s->bufr); + DEBUGASSERT(a <= s->toobig); + DEBUGASSERT(!len || mem); + + if(fit > s->toobig) { + Curl_dyn_free(s); + return CURLE_TOO_LARGE; + } + else if(!a) { + DEBUGASSERT(!indx); + /* first invoke */ + if(MIN_FIRST_ALLOC > s->toobig) + a = s->toobig; + else if(fit < MIN_FIRST_ALLOC) + a = MIN_FIRST_ALLOC; + else + a = fit; + } + else { + while(a < fit) + a *= 2; + if(a > s->toobig) + /* no point in allocating a larger buffer than this is allowed to use */ + a = s->toobig; + } + + if(a != s->allc) { + /* this logic is not using Curl_saferealloc() to make the tool not have to + include that as well when it uses this code */ + void *p = realloc(s->bufr, a); + if(!p) { + Curl_dyn_free(s); + return CURLE_OUT_OF_MEMORY; + } + s->bufr = p; + s->allc = a; + } + + if(len) + memcpy(&s->bufr[indx], mem, len); + s->leng = indx + len; + s->bufr[s->leng] = 0; + return CURLE_OK; +} + +/* + * Clears the string, keeps the allocation. This can also be called on a + * buffer that already was freed. + */ +void Curl_dyn_reset(struct dynbuf *s) +{ + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + if(s->leng) + s->bufr[0] = 0; + s->leng = 0; +} + +/* + * Specify the size of the tail to keep (number of bytes from the end of the + * buffer). The rest will be dropped. + */ +CURLcode Curl_dyn_tail(struct dynbuf *s, size_t trail) +{ + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + if(trail > s->leng) + return CURLE_BAD_FUNCTION_ARGUMENT; + else if(trail == s->leng) + return CURLE_OK; + else if(!trail) { + Curl_dyn_reset(s); + } + else { + memmove(&s->bufr[0], &s->bufr[s->leng - trail], trail); + s->leng = trail; + s->bufr[s->leng] = 0; + } + return CURLE_OK; + +} + +/* + * Appends a buffer with length. + */ +CURLcode Curl_dyn_addn(struct dynbuf *s, const void *mem, size_t len) +{ + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + return dyn_nappend(s, mem, len); +} + +/* + * Append a null-terminated string at the end. + */ +CURLcode Curl_dyn_add(struct dynbuf *s, const char *str) +{ + size_t n; + DEBUGASSERT(str); + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + n = strlen(str); + return dyn_nappend(s, (unsigned char *)str, n); +} + +/* + * Append a string vprintf()-style + */ +CURLcode Curl_dyn_vaddf(struct dynbuf *s, const char *fmt, va_list ap) +{ +#ifdef BUILDING_LIBCURL + int rc; + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + DEBUGASSERT(fmt); + rc = Curl_dyn_vprintf(s, fmt, ap); + + if(!rc) + return CURLE_OK; + else if(rc == MERR_TOO_LARGE) + return CURLE_TOO_LARGE; + return CURLE_OUT_OF_MEMORY; +#else + char *str; + str = vaprintf(fmt, ap); /* this allocs a new string to append */ + + if(str) { + CURLcode result = dyn_nappend(s, (unsigned char *)str, strlen(str)); + free(str); + return result; + } + /* If we failed, we cleanup the whole buffer and return error */ + Curl_dyn_free(s); + return CURLE_OUT_OF_MEMORY; +#endif +} + +/* + * Append a string printf()-style + */ +CURLcode Curl_dyn_addf(struct dynbuf *s, const char *fmt, ...) +{ + CURLcode result; + va_list ap; + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + va_start(ap, fmt); + result = Curl_dyn_vaddf(s, fmt, ap); + va_end(ap); + return result; +} + +/* + * Returns a pointer to the buffer. + */ +char *Curl_dyn_ptr(const struct dynbuf *s) +{ + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + return s->bufr; +} + +/* + * Returns an unsigned pointer to the buffer. + */ +unsigned char *Curl_dyn_uptr(const struct dynbuf *s) +{ + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + return (unsigned char *)s->bufr; +} + +/* + * Returns the length of the buffer. + */ +size_t Curl_dyn_len(const struct dynbuf *s) +{ + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + return s->leng; +} + +/* + * Set a new (smaller) length. + */ +CURLcode Curl_dyn_setlen(struct dynbuf *s, size_t set) +{ + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + if(set > s->leng) + return CURLE_BAD_FUNCTION_ARGUMENT; + s->leng = set; + s->bufr[s->leng] = 0; + return CURLE_OK; +} diff --git a/third_party/curl/lib/dynbuf.h b/third_party/curl/lib/dynbuf.h new file mode 100644 index 0000000..7dbaab8 --- /dev/null +++ b/third_party/curl/lib/dynbuf.h @@ -0,0 +1,93 @@ +#ifndef HEADER_CURL_DYNBUF_H +#define HEADER_CURL_DYNBUF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include + +#ifndef BUILDING_LIBCURL +/* this renames the functions so that the tool code can use the same code + without getting symbol collisions */ +#define Curl_dyn_init(a,b) curlx_dyn_init(a,b) +#define Curl_dyn_add(a,b) curlx_dyn_add(a,b) +#define Curl_dyn_addn(a,b,c) curlx_dyn_addn(a,b,c) +#define Curl_dyn_addf curlx_dyn_addf +#define Curl_dyn_vaddf curlx_dyn_vaddf +#define Curl_dyn_free(a) curlx_dyn_free(a) +#define Curl_dyn_ptr(a) curlx_dyn_ptr(a) +#define Curl_dyn_uptr(a) curlx_dyn_uptr(a) +#define Curl_dyn_len(a) curlx_dyn_len(a) +#define Curl_dyn_reset(a) curlx_dyn_reset(a) +#define Curl_dyn_tail(a,b) curlx_dyn_tail(a,b) +#define Curl_dyn_setlen(a,b) curlx_dyn_setlen(a,b) +#define curlx_dynbuf dynbuf /* for the struct name */ +#endif + +struct dynbuf { + char *bufr; /* point to a null-terminated allocated buffer */ + size_t leng; /* number of bytes *EXCLUDING* the null-terminator */ + size_t allc; /* size of the current allocation */ + size_t toobig; /* size limit for the buffer */ +#ifdef DEBUGBUILD + int init; /* detect API usage mistakes */ +#endif +}; + +void Curl_dyn_init(struct dynbuf *s, size_t toobig); +void Curl_dyn_free(struct dynbuf *s); +CURLcode Curl_dyn_addn(struct dynbuf *s, const void *mem, size_t len) + WARN_UNUSED_RESULT; +CURLcode Curl_dyn_add(struct dynbuf *s, const char *str) + WARN_UNUSED_RESULT; +CURLcode Curl_dyn_addf(struct dynbuf *s, const char *fmt, ...) + WARN_UNUSED_RESULT CURL_PRINTF(2, 3); +CURLcode Curl_dyn_vaddf(struct dynbuf *s, const char *fmt, va_list ap) + WARN_UNUSED_RESULT CURL_PRINTF(2, 0); +void Curl_dyn_reset(struct dynbuf *s); +CURLcode Curl_dyn_tail(struct dynbuf *s, size_t trail); +CURLcode Curl_dyn_setlen(struct dynbuf *s, size_t set); +char *Curl_dyn_ptr(const struct dynbuf *s); +unsigned char *Curl_dyn_uptr(const struct dynbuf *s); +size_t Curl_dyn_len(const struct dynbuf *s); + +/* returns 0 on success, -1 on error */ +/* The implementation of this function exists in mprintf.c */ +int Curl_dyn_vprintf(struct dynbuf *dyn, const char *format, va_list ap_save); + +/* Dynamic buffer max sizes */ +#define DYN_DOH_RESPONSE 3000 +#define DYN_DOH_CNAME 256 +#define DYN_PAUSE_BUFFER (64 * 1024 * 1024) +#define DYN_HAXPROXY 2048 +#define DYN_HTTP_REQUEST (1024*1024) +#define DYN_APRINTF 8000000 +#define DYN_RTSP_REQ_HEADER (64*1024) +#define DYN_TRAILERS (64*1024) +#define DYN_PROXY_CONNECT_HEADERS 16384 +#define DYN_QLOG_NAME 1024 +#define DYN_H1_TRAILER 4096 +#define DYN_PINGPPONG_CMD (64*1024) +#define DYN_IMAP_CMD (64*1024) +#define DYN_MQTT_RECV (64*1024) +#endif diff --git a/third_party/curl/lib/dynhds.c b/third_party/curl/lib/dynhds.c new file mode 100644 index 0000000..d754895 --- /dev/null +++ b/third_party/curl/lib/dynhds.c @@ -0,0 +1,396 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "dynhds.h" +#include "strcase.h" + +/* The last 3 #include files should be in this order */ +#ifdef USE_NGHTTP2 +#include +#include +#endif /* USE_NGHTTP2 */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +static struct dynhds_entry * +entry_new(const char *name, size_t namelen, + const char *value, size_t valuelen, int opts) +{ + struct dynhds_entry *e; + char *p; + + DEBUGASSERT(name); + DEBUGASSERT(value); + e = calloc(1, sizeof(*e) + namelen + valuelen + 2); + if(!e) + return NULL; + e->name = p = ((char *)e) + sizeof(*e); + memcpy(p, name, namelen); + e->namelen = namelen; + e->value = p += namelen + 1; /* leave a \0 at the end of name */ + memcpy(p, value, valuelen); + e->valuelen = valuelen; + if(opts & DYNHDS_OPT_LOWERCASE) + Curl_strntolower(e->name, e->name, e->namelen); + return e; +} + +static struct dynhds_entry * +entry_append(struct dynhds_entry *e, + const char *value, size_t valuelen) +{ + struct dynhds_entry *e2; + size_t valuelen2 = e->valuelen + 1 + valuelen; + char *p; + + DEBUGASSERT(value); + e2 = calloc(1, sizeof(*e) + e->namelen + valuelen2 + 2); + if(!e2) + return NULL; + e2->name = p = ((char *)e2) + sizeof(*e2); + memcpy(p, e->name, e->namelen); + e2->namelen = e->namelen; + e2->value = p += e->namelen + 1; /* leave a \0 at the end of name */ + memcpy(p, e->value, e->valuelen); + p += e->valuelen; + p[0] = ' '; + memcpy(p + 1, value, valuelen); + e2->valuelen = valuelen2; + return e2; +} + +static void entry_free(struct dynhds_entry *e) +{ + free(e); +} + +void Curl_dynhds_init(struct dynhds *dynhds, size_t max_entries, + size_t max_strs_size) +{ + DEBUGASSERT(dynhds); + DEBUGASSERT(max_strs_size); + dynhds->hds = NULL; + dynhds->hds_len = dynhds->hds_allc = dynhds->strs_len = 0; + dynhds->max_entries = max_entries; + dynhds->max_strs_size = max_strs_size; + dynhds->opts = 0; +} + +void Curl_dynhds_free(struct dynhds *dynhds) +{ + DEBUGASSERT(dynhds); + if(dynhds->hds && dynhds->hds_len) { + size_t i; + DEBUGASSERT(dynhds->hds); + for(i = 0; i < dynhds->hds_len; ++i) { + entry_free(dynhds->hds[i]); + } + } + Curl_safefree(dynhds->hds); + dynhds->hds_len = dynhds->hds_allc = dynhds->strs_len = 0; +} + +void Curl_dynhds_reset(struct dynhds *dynhds) +{ + DEBUGASSERT(dynhds); + if(dynhds->hds_len) { + size_t i; + DEBUGASSERT(dynhds->hds); + for(i = 0; i < dynhds->hds_len; ++i) { + entry_free(dynhds->hds[i]); + dynhds->hds[i] = NULL; + } + } + dynhds->hds_len = dynhds->strs_len = 0; +} + +size_t Curl_dynhds_count(struct dynhds *dynhds) +{ + return dynhds->hds_len; +} + +void Curl_dynhds_set_opts(struct dynhds *dynhds, int opts) +{ + dynhds->opts = opts; +} + +struct dynhds_entry *Curl_dynhds_getn(struct dynhds *dynhds, size_t n) +{ + DEBUGASSERT(dynhds); + return (n < dynhds->hds_len)? dynhds->hds[n] : NULL; +} + +struct dynhds_entry *Curl_dynhds_get(struct dynhds *dynhds, const char *name, + size_t namelen) +{ + size_t i; + for(i = 0; i < dynhds->hds_len; ++i) { + if(dynhds->hds[i]->namelen == namelen && + strncasecompare(dynhds->hds[i]->name, name, namelen)) { + return dynhds->hds[i]; + } + } + return NULL; +} + +struct dynhds_entry *Curl_dynhds_cget(struct dynhds *dynhds, const char *name) +{ + return Curl_dynhds_get(dynhds, name, strlen(name)); +} + +CURLcode Curl_dynhds_add(struct dynhds *dynhds, + const char *name, size_t namelen, + const char *value, size_t valuelen) +{ + struct dynhds_entry *entry = NULL; + CURLcode result = CURLE_OUT_OF_MEMORY; + + DEBUGASSERT(dynhds); + if(dynhds->max_entries && dynhds->hds_len >= dynhds->max_entries) + return CURLE_OUT_OF_MEMORY; + if(dynhds->strs_len + namelen + valuelen > dynhds->max_strs_size) + return CURLE_OUT_OF_MEMORY; + +entry = entry_new(name, namelen, value, valuelen, dynhds->opts); + if(!entry) + goto out; + + if(dynhds->hds_len + 1 >= dynhds->hds_allc) { + size_t nallc = dynhds->hds_len + 16; + struct dynhds_entry **nhds; + + if(dynhds->max_entries && nallc > dynhds->max_entries) + nallc = dynhds->max_entries; + + nhds = calloc(nallc, sizeof(struct dynhds_entry *)); + if(!nhds) + goto out; + if(dynhds->hds) { + memcpy(nhds, dynhds->hds, + dynhds->hds_len * sizeof(struct dynhds_entry *)); + Curl_safefree(dynhds->hds); + } + dynhds->hds = nhds; + dynhds->hds_allc = nallc; + } + dynhds->hds[dynhds->hds_len++] = entry; + entry = NULL; + dynhds->strs_len += namelen + valuelen; + result = CURLE_OK; + +out: + if(entry) + entry_free(entry); + return result; +} + +CURLcode Curl_dynhds_cadd(struct dynhds *dynhds, + const char *name, const char *value) +{ + return Curl_dynhds_add(dynhds, name, strlen(name), value, strlen(value)); +} + +CURLcode Curl_dynhds_h1_add_line(struct dynhds *dynhds, + const char *line, size_t line_len) +{ + const char *p; + const char *name; + size_t namelen; + const char *value; + size_t valuelen, i; + + if(!line || !line_len) + return CURLE_OK; + + if((line[0] == ' ') || (line[0] == '\t')) { + struct dynhds_entry *e, *e2; + /* header continuation, yikes! */ + if(!dynhds->hds_len) + return CURLE_BAD_FUNCTION_ARGUMENT; + + while(line_len && ISBLANK(line[0])) { + ++line; + --line_len; + } + if(!line_len) + return CURLE_BAD_FUNCTION_ARGUMENT; + e = dynhds->hds[dynhds->hds_len-1]; + e2 = entry_append(e, line, line_len); + if(!e2) + return CURLE_OUT_OF_MEMORY; + dynhds->hds[dynhds->hds_len-1] = e2; + entry_free(e); + return CURLE_OK; + } + else { + p = memchr(line, ':', line_len); + if(!p) + return CURLE_BAD_FUNCTION_ARGUMENT; + name = line; + namelen = p - line; + p++; /* move past the colon */ + for(i = namelen + 1; i < line_len; ++i, ++p) { + if(!ISBLANK(*p)) + break; + } + value = p; + valuelen = line_len - i; + + p = memchr(value, '\r', valuelen); + if(!p) + p = memchr(value, '\n', valuelen); + if(p) + valuelen = (size_t)(p - value); + + return Curl_dynhds_add(dynhds, name, namelen, value, valuelen); + } +} + +CURLcode Curl_dynhds_h1_cadd_line(struct dynhds *dynhds, const char *line) +{ + return Curl_dynhds_h1_add_line(dynhds, line, line? strlen(line) : 0); +} + +#ifdef DEBUGBUILD +/* used by unit2602.c */ + +bool Curl_dynhds_contains(struct dynhds *dynhds, + const char *name, size_t namelen) +{ + return !!Curl_dynhds_get(dynhds, name, namelen); +} + +bool Curl_dynhds_ccontains(struct dynhds *dynhds, const char *name) +{ + return Curl_dynhds_contains(dynhds, name, strlen(name)); +} + +size_t Curl_dynhds_count_name(struct dynhds *dynhds, + const char *name, size_t namelen) +{ + size_t n = 0; + if(dynhds->hds_len) { + size_t i; + for(i = 0; i < dynhds->hds_len; ++i) { + if((namelen == dynhds->hds[i]->namelen) && + strncasecompare(name, dynhds->hds[i]->name, namelen)) + ++n; + } + } + return n; +} + +size_t Curl_dynhds_ccount_name(struct dynhds *dynhds, const char *name) +{ + return Curl_dynhds_count_name(dynhds, name, strlen(name)); +} + +CURLcode Curl_dynhds_set(struct dynhds *dynhds, + const char *name, size_t namelen, + const char *value, size_t valuelen) +{ + Curl_dynhds_remove(dynhds, name, namelen); + return Curl_dynhds_add(dynhds, name, namelen, value, valuelen); +} + +size_t Curl_dynhds_remove(struct dynhds *dynhds, + const char *name, size_t namelen) +{ + size_t n = 0; + if(dynhds->hds_len) { + size_t i, len; + for(i = 0; i < dynhds->hds_len; ++i) { + if((namelen == dynhds->hds[i]->namelen) && + strncasecompare(name, dynhds->hds[i]->name, namelen)) { + ++n; + --dynhds->hds_len; + dynhds->strs_len -= (dynhds->hds[i]->namelen + + dynhds->hds[i]->valuelen); + entry_free(dynhds->hds[i]); + len = dynhds->hds_len - i; /* remaining entries */ + if(len) { + memmove(&dynhds->hds[i], &dynhds->hds[i + 1], + len * sizeof(dynhds->hds[i])); + } + --i; /* do this index again */ + } + } + } + return n; +} + +size_t Curl_dynhds_cremove(struct dynhds *dynhds, const char *name) +{ + return Curl_dynhds_remove(dynhds, name, strlen(name)); +} + +#endif + +CURLcode Curl_dynhds_h1_dprint(struct dynhds *dynhds, struct dynbuf *dbuf) +{ + CURLcode result = CURLE_OK; + size_t i; + + if(!dynhds->hds_len) + return result; + + for(i = 0; i < dynhds->hds_len; ++i) { + result = Curl_dyn_addf(dbuf, "%.*s: %.*s\r\n", + (int)dynhds->hds[i]->namelen, dynhds->hds[i]->name, + (int)dynhds->hds[i]->valuelen, dynhds->hds[i]->value); + if(result) + break; + } + + return result; +} + +#ifdef USE_NGHTTP2 + +nghttp2_nv *Curl_dynhds_to_nva(struct dynhds *dynhds, size_t *pcount) +{ + nghttp2_nv *nva = calloc(1, sizeof(nghttp2_nv) * dynhds->hds_len); + size_t i; + + *pcount = 0; + if(!nva) + return NULL; + + for(i = 0; i < dynhds->hds_len; ++i) { + struct dynhds_entry *e = dynhds->hds[i]; + DEBUGASSERT(e); + nva[i].name = (unsigned char *)e->name; + nva[i].namelen = e->namelen; + nva[i].value = (unsigned char *)e->value; + nva[i].valuelen = e->valuelen; + nva[i].flags = NGHTTP2_NV_FLAG_NONE; + } + *pcount = dynhds->hds_len; + return nva; +} + +#endif /* USE_NGHTTP2 */ diff --git a/third_party/curl/lib/dynhds.h b/third_party/curl/lib/dynhds.h new file mode 100644 index 0000000..3b53600 --- /dev/null +++ b/third_party/curl/lib/dynhds.h @@ -0,0 +1,183 @@ +#ifndef HEADER_CURL_DYNHDS_H +#define HEADER_CURL_DYNHDS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include +#include "dynbuf.h" + +struct dynbuf; + +/** + * A single header entry. + * `name` and `value` are non-NULL and always NUL terminated. + */ +struct dynhds_entry { + char *name; + char *value; + size_t namelen; + size_t valuelen; +}; + +struct dynhds { + struct dynhds_entry **hds; + size_t hds_len; /* number of entries in hds */ + size_t hds_allc; /* size of hds allocation */ + size_t max_entries; /* size limit number of entries */ + size_t strs_len; /* length of all strings */ + size_t max_strs_size; /* max length of all strings */ + int opts; +}; + +#define DYNHDS_OPT_NONE (0) +#define DYNHDS_OPT_LOWERCASE (1 << 0) + +/** + * Init for use on first time or after a reset. + * Allow `max_entries` headers to be added, 0 for unlimited. + * Allow size of all name and values added to not exceed `max_strs_size`` + */ +void Curl_dynhds_init(struct dynhds *dynhds, size_t max_entries, + size_t max_strs_size); +/** + * Frees all data held in `dynhds`, but not the struct itself. + */ +void Curl_dynhds_free(struct dynhds *dynhds); + +/** + * Reset `dyndns` to the initial init state. May keep allocations + * around. + */ +void Curl_dynhds_reset(struct dynhds *dynhds); + +/** + * Return the number of header entries. + */ +size_t Curl_dynhds_count(struct dynhds *dynhds); + +/** + * Set the options to use, replacing any existing ones. + * This will not have an effect on already existing headers. + */ +void Curl_dynhds_set_opts(struct dynhds *dynhds, int opts); + +/** + * Return the n-th header entry or NULL if it does not exist. + */ +struct dynhds_entry *Curl_dynhds_getn(struct dynhds *dynhds, size_t n); + +/** + * Return the 1st header entry of the name or NULL if none exists. + */ +struct dynhds_entry *Curl_dynhds_get(struct dynhds *dynhds, + const char *name, size_t namelen); +struct dynhds_entry *Curl_dynhds_cget(struct dynhds *dynhds, const char *name); + +/** + * Return TRUE iff one or more headers with the given name exist. + */ +bool Curl_dynhds_contains(struct dynhds *dynhds, + const char *name, size_t namelen); +bool Curl_dynhds_ccontains(struct dynhds *dynhds, const char *name); + +/** + * Return how often the given name appears in `dynhds`. + * Names are case-insensitive. + */ +size_t Curl_dynhds_count_name(struct dynhds *dynhds, + const char *name, size_t namelen); + +/** + * Return how often the given 0-terminated name appears in `dynhds`. + * Names are case-insensitive. + */ +size_t Curl_dynhds_ccount_name(struct dynhds *dynhds, const char *name); + +/** + * Add a header, name + value, to `dynhds` at the end. Does *not* + * check for duplicate names. + */ +CURLcode Curl_dynhds_add(struct dynhds *dynhds, + const char *name, size_t namelen, + const char *value, size_t valuelen); + +/** + * Add a header, c-string name + value, to `dynhds` at the end. + */ +CURLcode Curl_dynhds_cadd(struct dynhds *dynhds, + const char *name, const char *value); + +/** + * Remove all entries with the given name. + * Returns number of entries removed. + */ +size_t Curl_dynhds_remove(struct dynhds *dynhds, + const char *name, size_t namelen); +size_t Curl_dynhds_cremove(struct dynhds *dynhds, const char *name); + + +/** + * Set the give header name and value, replacing any entries with + * the same name. The header is added at the end of all (remaining) + * entries. + */ +CURLcode Curl_dynhds_set(struct dynhds *dynhds, + const char *name, size_t namelen, + const char *value, size_t valuelen); + +CURLcode Curl_dynhds_cset(struct dynhds *dynhds, + const char *name, const char *value); + +/** + * Add a single header from a HTTP/1.1 formatted line at the end. Line + * may contain a delimiting \r\n or just \n. Any characters after + * that will be ignored. + */ +CURLcode Curl_dynhds_h1_cadd_line(struct dynhds *dynhds, const char *line); + +/** + * Add a single header from a HTTP/1.1 formatted line at the end. Line + * may contain a delimiting \r\n or just \n. Any characters after + * that will be ignored. + */ +CURLcode Curl_dynhds_h1_add_line(struct dynhds *dynhds, + const char *line, size_t line_len); + +/** + * Add the headers to the given `dynbuf` in HTTP/1.1 format with + * cr+lf line endings. Will NOT output a last empty line. + */ +CURLcode Curl_dynhds_h1_dprint(struct dynhds *dynhds, struct dynbuf *dbuf); + +#ifdef USE_NGHTTP2 + +#include +#include + +nghttp2_nv *Curl_dynhds_to_nva(struct dynhds *dynhds, size_t *pcount); + +#endif /* USE_NGHTTP2 */ + +#endif /* HEADER_CURL_DYNHDS_H */ diff --git a/third_party/curl/lib/easy.c b/third_party/curl/lib/easy.c new file mode 100644 index 0000000..a04dbed --- /dev/null +++ b/third_party/curl/lib/easy.c @@ -0,0 +1,1343 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NET_IF_H +#include +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif + +#ifdef HAVE_SYS_PARAM_H +#include +#endif + +#include "urldata.h" +#include +#include "transfer.h" +#include "vtls/vtls.h" +#include "url.h" +#include "getinfo.h" +#include "hostip.h" +#include "share.h" +#include "strdup.h" +#include "progress.h" +#include "easyif.h" +#include "multiif.h" +#include "select.h" +#include "cfilters.h" +#include "sendf.h" /* for failf function prototype */ +#include "connect.h" /* for Curl_getconnectinfo */ +#include "slist.h" +#include "mime.h" +#include "amigaos.h" +#include "macos.h" +#include "warnless.h" +#include "sigpipe.h" +#include "vssh/ssh.h" +#include "setopt.h" +#include "http_digest.h" +#include "system_win32.h" +#include "http2.h" +#include "dynbuf.h" +#include "altsvc.h" +#include "hsts.h" + +#include "easy_lock.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* true globals -- for curl_global_init() and curl_global_cleanup() */ +static unsigned int initialized; +static long easy_init_flags; + +#ifdef GLOBAL_INIT_IS_THREADSAFE + +static curl_simple_lock s_lock = CURL_SIMPLE_LOCK_INIT; +#define global_init_lock() curl_simple_lock_lock(&s_lock) +#define global_init_unlock() curl_simple_lock_unlock(&s_lock) + +#else + +#define global_init_lock() +#define global_init_unlock() + +#endif + +/* + * strdup (and other memory functions) is redefined in complicated + * ways, but at this point it must be defined as the system-supplied strdup + * so the callback pointer is initialized correctly. + */ +#if defined(_WIN32_WCE) +#define system_strdup _strdup +#elif !defined(HAVE_STRDUP) +#define system_strdup Curl_strdup +#else +#define system_strdup strdup +#endif + +#if defined(_MSC_VER) && defined(_DLL) +# pragma warning(disable:4232) /* MSVC extension, dllimport identity */ +#endif + +/* + * If a memory-using function (like curl_getenv) is used before + * curl_global_init() is called, we need to have these pointers set already. + */ +curl_malloc_callback Curl_cmalloc = (curl_malloc_callback)malloc; +curl_free_callback Curl_cfree = (curl_free_callback)free; +curl_realloc_callback Curl_crealloc = (curl_realloc_callback)realloc; +curl_strdup_callback Curl_cstrdup = (curl_strdup_callback)system_strdup; +curl_calloc_callback Curl_ccalloc = (curl_calloc_callback)calloc; +#if defined(_WIN32) && defined(UNICODE) +curl_wcsdup_callback Curl_cwcsdup = Curl_wcsdup; +#endif + +#if defined(_MSC_VER) && defined(_DLL) +# pragma warning(default:4232) /* MSVC extension, dllimport identity */ +#endif + +#ifdef DEBUGBUILD +static char *leakpointer; +#endif + +/** + * curl_global_init() globally initializes curl given a bitwise set of the + * different features of what to initialize. + */ +static CURLcode global_init(long flags, bool memoryfuncs) +{ + if(initialized++) + return CURLE_OK; + + if(memoryfuncs) { + /* Setup the default memory functions here (again) */ + Curl_cmalloc = (curl_malloc_callback)malloc; + Curl_cfree = (curl_free_callback)free; + Curl_crealloc = (curl_realloc_callback)realloc; + Curl_cstrdup = (curl_strdup_callback)system_strdup; + Curl_ccalloc = (curl_calloc_callback)calloc; +#if defined(_WIN32) && defined(UNICODE) + Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup; +#endif + } + + if(Curl_trc_init()) { + DEBUGF(fprintf(stderr, "Error: Curl_trc_init failed\n")); + goto fail; + } + + if(!Curl_ssl_init()) { + DEBUGF(fprintf(stderr, "Error: Curl_ssl_init failed\n")); + goto fail; + } + + if(Curl_win32_init(flags)) { + DEBUGF(fprintf(stderr, "Error: win32_init failed\n")); + goto fail; + } + + if(Curl_amiga_init()) { + DEBUGF(fprintf(stderr, "Error: Curl_amiga_init failed\n")); + goto fail; + } + + if(Curl_macos_init()) { + DEBUGF(fprintf(stderr, "Error: Curl_macos_init failed\n")); + goto fail; + } + + if(Curl_resolver_global_init()) { + DEBUGF(fprintf(stderr, "Error: resolver_global_init failed\n")); + goto fail; + } + + if(Curl_ssh_init()) { + DEBUGF(fprintf(stderr, "Error: Curl_ssh_init failed\n")); + goto fail; + } + + easy_init_flags = flags; + +#ifdef DEBUGBUILD + if(getenv("CURL_GLOBAL_INIT")) + /* alloc data that will leak if *cleanup() is not called! */ + leakpointer = malloc(1); +#endif + + return CURLE_OK; + +fail: + initialized--; /* undo the increase */ + return CURLE_FAILED_INIT; +} + + +/** + * curl_global_init() globally initializes curl given a bitwise set of the + * different features of what to initialize. + */ +CURLcode curl_global_init(long flags) +{ + CURLcode result; + global_init_lock(); + + result = global_init(flags, TRUE); + + global_init_unlock(); + + return result; +} + +/* + * curl_global_init_mem() globally initializes curl and also registers the + * user provided callback routines. + */ +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) +{ + CURLcode result; + + /* Invalid input, return immediately */ + if(!m || !f || !r || !s || !c) + return CURLE_FAILED_INIT; + + global_init_lock(); + + if(initialized) { + /* Already initialized, don't do it again, but bump the variable anyway to + work like curl_global_init() and require the same amount of cleanup + calls. */ + initialized++; + global_init_unlock(); + return CURLE_OK; + } + + /* set memory functions before global_init() in case it wants memory + functions */ + Curl_cmalloc = m; + Curl_cfree = f; + Curl_cstrdup = s; + Curl_crealloc = r; + Curl_ccalloc = c; + + /* Call the actual init function, but without setting */ + result = global_init(flags, FALSE); + + global_init_unlock(); + + return result; +} + +/** + * curl_global_cleanup() globally cleanups curl, uses the value of + * "easy_init_flags" to determine what needs to be cleaned up and what doesn't. + */ +void curl_global_cleanup(void) +{ + global_init_lock(); + + if(!initialized) { + global_init_unlock(); + return; + } + + if(--initialized) { + global_init_unlock(); + return; + } + + Curl_ssl_cleanup(); + Curl_resolver_global_cleanup(); + +#ifdef _WIN32 + Curl_win32_cleanup(easy_init_flags); +#endif + + Curl_amiga_cleanup(); + + Curl_ssh_cleanup(); + +#ifdef DEBUGBUILD + free(leakpointer); +#endif + + easy_init_flags = 0; + + global_init_unlock(); +} + +/** + * curl_global_trace() globally initializes curl logging. + */ +CURLcode curl_global_trace(const char *config) +{ +#ifndef CURL_DISABLE_VERBOSE_STRINGS + CURLcode result; + global_init_lock(); + + result = Curl_trc_opt(config); + + global_init_unlock(); + + return result; +#else + (void)config; + return CURLE_OK; +#endif +} + +/* + * curl_global_sslset() globally initializes the SSL backend to use. + */ +CURLsslset curl_global_sslset(curl_sslbackend id, const char *name, + const curl_ssl_backend ***avail) +{ + CURLsslset rc; + + global_init_lock(); + + rc = Curl_init_sslset_nolock(id, name, avail); + + global_init_unlock(); + + return rc; +} + +/* + * curl_easy_init() is the external interface to alloc, setup and init an + * easy handle that is returned. If anything goes wrong, NULL is returned. + */ +struct Curl_easy *curl_easy_init(void) +{ + CURLcode result; + struct Curl_easy *data; + + /* Make sure we inited the global SSL stuff */ + global_init_lock(); + + if(!initialized) { + result = global_init(CURL_GLOBAL_DEFAULT, TRUE); + if(result) { + /* something in the global init failed, return nothing */ + DEBUGF(fprintf(stderr, "Error: curl_global_init failed\n")); + global_init_unlock(); + return NULL; + } + } + global_init_unlock(); + + /* We use curl_open() with undefined URL so far */ + result = Curl_open(&data); + if(result) { + DEBUGF(fprintf(stderr, "Error: Curl_open failed\n")); + return NULL; + } + + return data; +} + +#ifdef CURLDEBUG + +struct socketmonitor { + struct socketmonitor *next; /* the next node in the list or NULL */ + struct pollfd socket; /* socket info of what to monitor */ +}; + +struct events { + long ms; /* timeout, run the timeout function when reached */ + bool msbump; /* set TRUE when timeout is set by callback */ + int num_sockets; /* number of nodes in the monitor list */ + struct socketmonitor *list; /* list of sockets to monitor */ + int running_handles; /* store the returned number */ +}; + +/* events_timer + * + * Callback that gets called with a new value when the timeout should be + * updated. + */ + +static int events_timer(struct Curl_multi *multi, /* multi handle */ + long timeout_ms, /* see above */ + void *userp) /* private callback pointer */ +{ + struct events *ev = userp; + (void)multi; + if(timeout_ms == -1) + /* timeout removed */ + timeout_ms = 0; + else if(timeout_ms == 0) + /* timeout is already reached! */ + timeout_ms = 1; /* trigger asap */ + + ev->ms = timeout_ms; + ev->msbump = TRUE; + return 0; +} + + +/* poll2cselect + * + * convert from poll() bit definitions to libcurl's CURL_CSELECT_* ones + */ +static int poll2cselect(int pollmask) +{ + int omask = 0; + if(pollmask & POLLIN) + omask |= CURL_CSELECT_IN; + if(pollmask & POLLOUT) + omask |= CURL_CSELECT_OUT; + if(pollmask & POLLERR) + omask |= CURL_CSELECT_ERR; + return omask; +} + + +/* socketcb2poll + * + * convert from libcurl' CURL_POLL_* bit definitions to poll()'s + */ +static short socketcb2poll(int pollmask) +{ + short omask = 0; + if(pollmask & CURL_POLL_IN) + omask |= POLLIN; + if(pollmask & CURL_POLL_OUT) + omask |= POLLOUT; + return omask; +} + +/* events_socket + * + * Callback that gets called with information about socket activity to + * monitor. + */ +static int events_socket(struct Curl_easy *easy, /* easy handle */ + curl_socket_t s, /* socket */ + int what, /* see above */ + void *userp, /* private callback + pointer */ + void *socketp) /* private socket + pointer */ +{ + struct events *ev = userp; + struct socketmonitor *m; + struct socketmonitor *prev = NULL; + +#if defined(CURL_DISABLE_VERBOSE_STRINGS) + (void) easy; +#endif + (void)socketp; + + m = ev->list; + while(m) { + if(m->socket.fd == s) { + + if(what == CURL_POLL_REMOVE) { + struct socketmonitor *nxt = m->next; + /* remove this node from the list of monitored sockets */ + if(prev) + prev->next = nxt; + else + ev->list = nxt; + free(m); + m = nxt; + infof(easy, "socket cb: socket %" CURL_FORMAT_SOCKET_T + " REMOVED", s); + } + else { + /* The socket 's' is already being monitored, update the activity + mask. Convert from libcurl bitmask to the poll one. */ + m->socket.events = socketcb2poll(what); + infof(easy, "socket cb: socket %" CURL_FORMAT_SOCKET_T + " UPDATED as %s%s", s, + (what&CURL_POLL_IN)?"IN":"", + (what&CURL_POLL_OUT)?"OUT":""); + } + break; + } + prev = m; + m = m->next; /* move to next node */ + } + if(!m) { + if(what == CURL_POLL_REMOVE) { + /* this happens a bit too often, libcurl fix perhaps? */ + /* fprintf(stderr, + "%s: socket %d asked to be REMOVED but not present!\n", + __func__, s); */ + } + else { + m = malloc(sizeof(struct socketmonitor)); + if(m) { + m->next = ev->list; + m->socket.fd = s; + m->socket.events = socketcb2poll(what); + m->socket.revents = 0; + ev->list = m; + infof(easy, "socket cb: socket %" CURL_FORMAT_SOCKET_T + " ADDED as %s%s", s, + (what&CURL_POLL_IN)?"IN":"", + (what&CURL_POLL_OUT)?"OUT":""); + } + else + return CURLE_OUT_OF_MEMORY; + } + } + + return 0; +} + + +/* + * events_setup() + * + * Do the multi handle setups that only event-based transfers need. + */ +static void events_setup(struct Curl_multi *multi, struct events *ev) +{ + /* timer callback */ + curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, events_timer); + curl_multi_setopt(multi, CURLMOPT_TIMERDATA, ev); + + /* socket callback */ + curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, events_socket); + curl_multi_setopt(multi, CURLMOPT_SOCKETDATA, ev); +} + + +/* wait_or_timeout() + * + * waits for activity on any of the given sockets, or the timeout to trigger. + */ + +static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev) +{ + bool done = FALSE; + CURLMcode mcode = CURLM_OK; + CURLcode result = CURLE_OK; + + while(!done) { + CURLMsg *msg; + struct socketmonitor *m; + struct pollfd *f; + struct pollfd fds[4]; + int numfds = 0; + int pollrc; + int i; + struct curltime before; + struct curltime after; + + /* populate the fds[] array */ + for(m = ev->list, f = &fds[0]; m; m = m->next) { + f->fd = m->socket.fd; + f->events = m->socket.events; + f->revents = 0; + /* fprintf(stderr, "poll() %d check socket %d\n", numfds, f->fd); */ + f++; + numfds++; + } + + /* get the time stamp to use to figure out how long poll takes */ + before = Curl_now(); + + /* wait for activity or timeout */ + pollrc = Curl_poll(fds, numfds, ev->ms); + if(pollrc < 0) + return CURLE_UNRECOVERABLE_POLL; + + after = Curl_now(); + + ev->msbump = FALSE; /* reset here */ + + if(!pollrc) { + /* timeout! */ + ev->ms = 0; + /* fprintf(stderr, "call curl_multi_socket_action(TIMEOUT)\n"); */ + mcode = curl_multi_socket_action(multi, CURL_SOCKET_TIMEOUT, 0, + &ev->running_handles); + } + else { + /* here pollrc is > 0 */ + + /* loop over the monitored sockets to see which ones had activity */ + for(i = 0; i< numfds; i++) { + if(fds[i].revents) { + /* socket activity, tell libcurl */ + int act = poll2cselect(fds[i].revents); /* convert */ + infof(multi->easyp, + "call curl_multi_socket_action(socket " + "%" CURL_FORMAT_SOCKET_T ")", fds[i].fd); + mcode = curl_multi_socket_action(multi, fds[i].fd, act, + &ev->running_handles); + } + } + + if(!ev->msbump) { + /* If nothing updated the timeout, we decrease it by the spent time. + * If it was updated, it has the new timeout time stored already. + */ + timediff_t timediff = Curl_timediff(after, before); + if(timediff > 0) { + if(timediff > ev->ms) + ev->ms = 0; + else + ev->ms -= (long)timediff; + } + } + } + + if(mcode) + return CURLE_URL_MALFORMAT; + + /* we don't really care about the "msgs_in_queue" value returned in the + second argument */ + msg = curl_multi_info_read(multi, &pollrc); + if(msg) { + result = msg->data.result; + done = TRUE; + } + } + + return result; +} + + +/* easy_events() + * + * Runs a transfer in a blocking manner using the events-based API + */ +static CURLcode easy_events(struct Curl_multi *multi) +{ + /* this struct is made static to allow it to be used after this function + returns and curl_multi_remove_handle() is called */ + static struct events evs = {2, FALSE, 0, NULL, 0}; + + /* if running event-based, do some further multi inits */ + events_setup(multi, &evs); + + return wait_or_timeout(multi, &evs); +} +#else /* CURLDEBUG */ +/* when not built with debug, this function doesn't exist */ +#define easy_events(x) CURLE_NOT_BUILT_IN +#endif + +static CURLcode easy_transfer(struct Curl_multi *multi) +{ + bool done = FALSE; + CURLMcode mcode = CURLM_OK; + CURLcode result = CURLE_OK; + + while(!done && !mcode) { + int still_running = 0; + + mcode = curl_multi_poll(multi, NULL, 0, 1000, NULL); + + if(!mcode) + mcode = curl_multi_perform(multi, &still_running); + + /* only read 'still_running' if curl_multi_perform() return OK */ + if(!mcode && !still_running) { + int rc; + CURLMsg *msg = curl_multi_info_read(multi, &rc); + if(msg) { + result = msg->data.result; + done = TRUE; + } + } + } + + /* Make sure to return some kind of error if there was a multi problem */ + if(mcode) { + result = (mcode == CURLM_OUT_OF_MEMORY) ? CURLE_OUT_OF_MEMORY : + /* The other multi errors should never happen, so return + something suitably generic */ + CURLE_BAD_FUNCTION_ARGUMENT; + } + + return result; +} + + +/* + * easy_perform() is the external interface that performs a blocking + * transfer as previously setup. + * + * CONCEPT: This function creates a multi handle, adds the easy handle to it, + * runs curl_multi_perform() until the transfer is done, then detaches the + * easy handle, destroys the multi handle and returns the easy handle's return + * code. + * + * REALITY: it can't just create and destroy the multi handle that easily. It + * needs to keep it around since if this easy handle is used again by this + * function, the same multi handle must be reused so that the same pools and + * caches can be used. + * + * DEBUG: if 'events' is set TRUE, this function will use a replacement engine + * instead of curl_multi_perform() and use curl_multi_socket_action(). + */ +static CURLcode easy_perform(struct Curl_easy *data, bool events) +{ + struct Curl_multi *multi; + CURLMcode mcode; + CURLcode result = CURLE_OK; + SIGPIPE_VARIABLE(pipe_st); + + if(!data) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(data->set.errorbuffer) + /* clear this as early as possible */ + data->set.errorbuffer[0] = 0; + + data->state.os_errno = 0; + + if(data->multi) { + failf(data, "easy handle already used in multi handle"); + return CURLE_FAILED_INIT; + } + + if(data->multi_easy) + multi = data->multi_easy; + else { + /* this multi handle will only ever have a single easy handled attached + to it, so make it use minimal hashes */ + multi = Curl_multi_handle(1, 3, 7); + if(!multi) + return CURLE_OUT_OF_MEMORY; + } + + if(multi->in_callback) + return CURLE_RECURSIVE_API_CALL; + + /* Copy the MAXCONNECTS option to the multi handle */ + curl_multi_setopt(multi, CURLMOPT_MAXCONNECTS, (long)data->set.maxconnects); + + data->multi_easy = NULL; /* pretend it does not exist */ + mcode = curl_multi_add_handle(multi, data); + if(mcode) { + curl_multi_cleanup(multi); + if(mcode == CURLM_OUT_OF_MEMORY) + return CURLE_OUT_OF_MEMORY; + return CURLE_FAILED_INIT; + } + + /* assign this after curl_multi_add_handle() */ + data->multi_easy = multi; + + sigpipe_ignore(data, &pipe_st); + + /* run the transfer */ + result = events ? easy_events(multi) : easy_transfer(multi); + + /* ignoring the return code isn't nice, but atm we can't really handle + a failure here, room for future improvement! */ + (void)curl_multi_remove_handle(multi, data); + + sigpipe_restore(&pipe_st); + + /* The multi handle is kept alive, owned by the easy handle */ + return result; +} + + +/* + * curl_easy_perform() is the external interface that performs a blocking + * transfer as previously setup. + */ +CURLcode curl_easy_perform(struct Curl_easy *data) +{ + return easy_perform(data, FALSE); +} + +#ifdef CURLDEBUG +/* + * curl_easy_perform_ev() is the external interface that performs a blocking + * transfer using the event-based API internally. + */ +CURLcode curl_easy_perform_ev(struct Curl_easy *data) +{ + return easy_perform(data, TRUE); +} + +#endif + +/* + * curl_easy_cleanup() is the external interface to cleaning/freeing the given + * easy handle. + */ +void curl_easy_cleanup(struct Curl_easy *data) +{ + if(GOOD_EASY_HANDLE(data)) { + SIGPIPE_VARIABLE(pipe_st); + sigpipe_ignore(data, &pipe_st); + Curl_close(&data); + sigpipe_restore(&pipe_st); + } +} + +/* + * curl_easy_getinfo() is an external interface that allows an app to retrieve + * information from a performed transfer and similar. + */ +#undef curl_easy_getinfo +CURLcode curl_easy_getinfo(struct Curl_easy *data, CURLINFO info, ...) +{ + va_list arg; + void *paramp; + CURLcode result; + + va_start(arg, info); + paramp = va_arg(arg, void *); + + result = Curl_getinfo(data, info, paramp); + + va_end(arg); + return result; +} + +static CURLcode dupset(struct Curl_easy *dst, struct Curl_easy *src) +{ + CURLcode result = CURLE_OK; + enum dupstring i; + enum dupblob j; + + /* Copy src->set into dst->set first, then deal with the strings + afterwards */ + dst->set = src->set; + Curl_mime_initpart(&dst->set.mimepost); + + /* clear all dest string and blob pointers first, in case we error out + mid-function */ + memset(dst->set.str, 0, STRING_LAST * sizeof(char *)); + memset(dst->set.blobs, 0, BLOB_LAST * sizeof(struct curl_blob *)); + + /* duplicate all strings */ + for(i = (enum dupstring)0; i< STRING_LASTZEROTERMINATED; i++) { + result = Curl_setstropt(&dst->set.str[i], src->set.str[i]); + if(result) + return result; + } + + /* duplicate all blobs */ + for(j = (enum dupblob)0; j < BLOB_LAST; j++) { + result = Curl_setblobopt(&dst->set.blobs[j], src->set.blobs[j]); + if(result) + return result; + } + + /* duplicate memory areas pointed to */ + i = STRING_COPYPOSTFIELDS; + if(src->set.str[i]) { + if(src->set.postfieldsize == -1) + dst->set.str[i] = strdup(src->set.str[i]); + else + /* postfieldsize is curl_off_t, Curl_memdup() takes a size_t ... */ + dst->set.str[i] = Curl_memdup(src->set.str[i], + curlx_sotouz(src->set.postfieldsize)); + if(!dst->set.str[i]) + return CURLE_OUT_OF_MEMORY; + /* point to the new copy */ + dst->set.postfields = dst->set.str[i]; + } + + /* Duplicate mime data. */ + result = Curl_mime_duppart(dst, &dst->set.mimepost, &src->set.mimepost); + + if(src->set.resolve) + dst->state.resolve = dst->set.resolve; + + return result; +} + +/* + * curl_easy_duphandle() is an external interface to allow duplication of a + * given input easy handle. The returned handle will be a new working handle + * with all options set exactly as the input source handle. + */ +struct Curl_easy *curl_easy_duphandle(struct Curl_easy *data) +{ + struct Curl_easy *outcurl = calloc(1, sizeof(struct Curl_easy)); + if(!outcurl) + goto fail; + + /* + * We setup a few buffers we need. We should probably make them + * get setup on-demand in the code, as that would probably decrease + * the likeliness of us forgetting to init a buffer here in the future. + */ + outcurl->set.buffer_size = data->set.buffer_size; + + /* copy all userdefined values */ + if(dupset(outcurl, data)) + goto fail; + + Curl_dyn_init(&outcurl->state.headerb, CURL_MAX_HTTP_HEADER); + + /* the connection cache is setup on demand */ + outcurl->state.conn_cache = NULL; + outcurl->state.lastconnect_id = -1; + outcurl->state.recent_conn_id = -1; + outcurl->id = -1; + + outcurl->progress.flags = data->progress.flags; + outcurl->progress.callback = data->progress.callback; + +#ifndef CURL_DISABLE_COOKIES + outcurl->state.cookielist = NULL; + if(data->cookies && data->state.cookie_engine) { + /* If cookies are enabled in the parent handle, we enable them + in the clone as well! */ + outcurl->cookies = Curl_cookie_init(outcurl, NULL, outcurl->cookies, + data->set.cookiesession); + if(!outcurl->cookies) + goto fail; + } + + if(data->state.cookielist) { + outcurl->state.cookielist = Curl_slist_duplicate(data->state.cookielist); + if(!outcurl->state.cookielist) + goto fail; + } +#endif + + if(data->state.url) { + outcurl->state.url = strdup(data->state.url); + if(!outcurl->state.url) + goto fail; + outcurl->state.url_alloc = TRUE; + } + + if(data->state.referer) { + outcurl->state.referer = strdup(data->state.referer); + if(!outcurl->state.referer) + goto fail; + outcurl->state.referer_alloc = TRUE; + } + + /* Reinitialize an SSL engine for the new handle + * note: the engine name has already been copied by dupset */ + if(outcurl->set.str[STRING_SSL_ENGINE]) { + if(Curl_ssl_set_engine(outcurl, outcurl->set.str[STRING_SSL_ENGINE])) + goto fail; + } + +#ifndef CURL_DISABLE_ALTSVC + if(data->asi) { + outcurl->asi = Curl_altsvc_init(); + if(!outcurl->asi) + goto fail; + if(outcurl->set.str[STRING_ALTSVC]) + (void)Curl_altsvc_load(outcurl->asi, outcurl->set.str[STRING_ALTSVC]); + } +#endif +#ifndef CURL_DISABLE_HSTS + if(data->hsts) { + outcurl->hsts = Curl_hsts_init(); + if(!outcurl->hsts) + goto fail; + if(outcurl->set.str[STRING_HSTS]) + (void)Curl_hsts_loadfile(outcurl, + outcurl->hsts, outcurl->set.str[STRING_HSTS]); + (void)Curl_hsts_loadcb(outcurl, outcurl->hsts); + } +#endif + +#ifdef CURLRES_ASYNCH + /* Clone the resolver handle, if present, for the new handle */ + if(Curl_resolver_duphandle(outcurl, + &outcurl->state.async.resolver, + data->state.async.resolver)) + goto fail; +#endif + +#ifdef USE_ARES + { + CURLcode rc; + + rc = Curl_set_dns_servers(outcurl, data->set.str[STRING_DNS_SERVERS]); + if(rc && rc != CURLE_NOT_BUILT_IN) + goto fail; + + rc = Curl_set_dns_interface(outcurl, data->set.str[STRING_DNS_INTERFACE]); + if(rc && rc != CURLE_NOT_BUILT_IN) + goto fail; + + rc = Curl_set_dns_local_ip4(outcurl, data->set.str[STRING_DNS_LOCAL_IP4]); + if(rc && rc != CURLE_NOT_BUILT_IN) + goto fail; + + rc = Curl_set_dns_local_ip6(outcurl, data->set.str[STRING_DNS_LOCAL_IP6]); + if(rc && rc != CURLE_NOT_BUILT_IN) + goto fail; + } +#endif /* USE_ARES */ + + Curl_initinfo(outcurl); + + outcurl->magic = CURLEASY_MAGIC_NUMBER; + + /* we reach this point and thus we are OK */ + + return outcurl; + +fail: + + if(outcurl) { +#ifndef CURL_DISABLE_COOKIES + free(outcurl->cookies); +#endif + Curl_dyn_free(&outcurl->state.headerb); + Curl_altsvc_cleanup(&outcurl->asi); + Curl_hsts_cleanup(&outcurl->hsts); + Curl_freeset(outcurl); + free(outcurl); + } + + return NULL; +} + +/* + * curl_easy_reset() is an external interface that allows an app to re- + * initialize a session handle to the default values. + */ +void curl_easy_reset(struct Curl_easy *data) +{ + Curl_req_hard_reset(&data->req, data); + + /* zero out UserDefined data: */ + Curl_freeset(data); + memset(&data->set, 0, sizeof(struct UserDefined)); + (void)Curl_init_userdefined(data); + + /* zero out Progress data: */ + memset(&data->progress, 0, sizeof(struct Progress)); + + /* zero out PureInfo data: */ + Curl_initinfo(data); + + data->progress.flags |= PGRS_HIDE; + data->state.current_speed = -1; /* init to negative == impossible */ + data->state.retrycount = 0; /* reset the retry counter */ + + /* zero out authentication data: */ + memset(&data->state.authhost, 0, sizeof(struct auth)); + memset(&data->state.authproxy, 0, sizeof(struct auth)); + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_DIGEST_AUTH) + Curl_http_auth_cleanup_digest(data); +#endif +} + +/* + * curl_easy_pause() allows an application to pause or unpause a specific + * transfer and direction. This function sets the full new state for the + * current connection this easy handle operates on. + * + * NOTE: if you have the receiving paused and you call this function to remove + * the pausing, you may get your write callback called at this point. + * + * Action is a bitmask consisting of CURLPAUSE_* bits in curl/curl.h + * + * NOTE: This is one of few API functions that are allowed to be called from + * within a callback. + */ +CURLcode curl_easy_pause(struct Curl_easy *data, int action) +{ + struct SingleRequest *k; + CURLcode result = CURLE_OK; + int oldstate; + int newstate; + bool recursive = FALSE; + bool keep_changed, unpause_read, not_all_paused; + + if(!GOOD_EASY_HANDLE(data) || !data->conn) + /* crazy input, don't continue */ + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(Curl_is_in_callback(data)) + recursive = TRUE; + k = &data->req; + oldstate = k->keepon & (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE); + + /* first switch off both pause bits then set the new pause bits */ + newstate = (k->keepon &~ (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE)) | + ((action & CURLPAUSE_RECV)?KEEP_RECV_PAUSE:0) | + ((action & CURLPAUSE_SEND)?KEEP_SEND_PAUSE:0); + + keep_changed = ((newstate & (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE)) != oldstate); + not_all_paused = (newstate & (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) != + (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE); + unpause_read = ((k->keepon & ~newstate & KEEP_SEND_PAUSE) && + (data->mstate == MSTATE_PERFORMING || + data->mstate == MSTATE_RATELIMITING)); + /* Unpausing writes is detected on the next run in + * transfer.c:Curl_readwrite(). This is because this may result + * in a transfer error if the application's callbacks fail */ + + /* Set the new keepon state, so it takes effect no matter what error + * may happen afterwards. */ + k->keepon = newstate; + + /* If not completely pausing both directions now, run again in any case. */ + if(not_all_paused) { + Curl_expire(data, 0, EXPIRE_RUN_NOW); + /* reset the too-slow time keeper */ + data->state.keeps_speed.tv_sec = 0; + /* Simulate socket events on next run for unpaused directions */ + if(!(newstate & KEEP_SEND_PAUSE)) + data->state.select_bits |= CURL_CSELECT_OUT; + if(!(newstate & KEEP_RECV_PAUSE)) + data->state.select_bits |= CURL_CSELECT_IN; + /* On changes, tell application to update its timers. */ + if(keep_changed && data->multi) { + if(Curl_update_timer(data->multi)) { + result = CURLE_ABORTED_BY_CALLBACK; + goto out; + } + } + } + + if(unpause_read) { + result = Curl_creader_unpause(data); + if(result) + goto out; + } + +out: + if(!result && !data->state.done && keep_changed) + /* This transfer may have been moved in or out of the bundle, update the + corresponding socket callback, if used */ + result = Curl_updatesocket(data); + + if(recursive) + /* this might have called a callback recursively which might have set this + to false again on exit */ + Curl_set_in_callback(data, TRUE); + + return result; +} + + +static CURLcode easy_connection(struct Curl_easy *data, + struct connectdata **connp) +{ + curl_socket_t sfd; + + if(!data) + return CURLE_BAD_FUNCTION_ARGUMENT; + + /* only allow these to be called on handles with CURLOPT_CONNECT_ONLY */ + if(!data->set.connect_only) { + failf(data, "CONNECT_ONLY is required"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + + sfd = Curl_getconnectinfo(data, connp); + + if(sfd == CURL_SOCKET_BAD) { + failf(data, "Failed to get recent socket"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + + return CURLE_OK; +} + +/* + * Receives data from the connected socket. Use after successful + * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. + * Returns CURLE_OK on success, error code on error. + */ +CURLcode curl_easy_recv(struct Curl_easy *data, void *buffer, size_t buflen, + size_t *n) +{ + CURLcode result; + ssize_t n1; + struct connectdata *c; + + if(Curl_is_in_callback(data)) + return CURLE_RECURSIVE_API_CALL; + + result = easy_connection(data, &c); + if(result) + return result; + + if(!data->conn) + /* on first invoke, the transfer has been detached from the connection and + needs to be reattached */ + Curl_attach_connection(data, c); + + *n = 0; + result = Curl_conn_recv(data, FIRSTSOCKET, buffer, buflen, &n1); + + if(result) + return result; + + *n = (size_t)n1; + return CURLE_OK; +} + +#ifdef USE_WEBSOCKETS +CURLcode Curl_connect_only_attach(struct Curl_easy *data) +{ + CURLcode result; + struct connectdata *c = NULL; + + result = easy_connection(data, &c); + if(result) + return result; + + if(!data->conn) + /* on first invoke, the transfer has been detached from the connection and + needs to be reattached */ + Curl_attach_connection(data, c); + + return CURLE_OK; +} +#endif /* USE_WEBSOCKETS */ + +/* + * Sends data over the connected socket. + * + * This is the private internal version of curl_easy_send() + */ +CURLcode Curl_senddata(struct Curl_easy *data, const void *buffer, + size_t buflen, size_t *n) +{ + CURLcode result; + struct connectdata *c = NULL; + SIGPIPE_VARIABLE(pipe_st); + + *n = 0; + result = easy_connection(data, &c); + if(result) + return result; + + if(!data->conn) + /* on first invoke, the transfer has been detached from the connection and + needs to be reattached */ + Curl_attach_connection(data, c); + + sigpipe_ignore(data, &pipe_st); + result = Curl_conn_send(data, FIRSTSOCKET, buffer, buflen, n); + sigpipe_restore(&pipe_st); + + if(result && result != CURLE_AGAIN) + return CURLE_SEND_ERROR; + return result; +} + +/* + * Sends data over the connected socket. Use after successful + * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. + */ +CURLcode curl_easy_send(struct Curl_easy *data, const void *buffer, + size_t buflen, size_t *n) +{ + size_t written = 0; + CURLcode result; + if(Curl_is_in_callback(data)) + return CURLE_RECURSIVE_API_CALL; + + result = Curl_senddata(data, buffer, buflen, &written); + *n = written; + return result; +} + +/* + * Wrapper to call functions in Curl_conncache_foreach() + * + * Returns always 0. + */ +static int conn_upkeep(struct Curl_easy *data, + struct connectdata *conn, + void *param) +{ + struct curltime *now = param; + + if(Curl_timediff(*now, conn->keepalive) <= data->set.upkeep_interval_ms) + return 0; + + /* briefly attach for action */ + Curl_attach_connection(data, conn); + if(conn->handler->connection_check) { + /* Do a protocol-specific keepalive check on the connection. */ + conn->handler->connection_check(data, conn, CONNCHECK_KEEPALIVE); + } + else { + /* Do the generic action on the FIRSTSOCKET filter chain */ + Curl_conn_keep_alive(data, conn, FIRSTSOCKET); + } + Curl_detach_connection(data); + + conn->keepalive = *now; + return 0; /* continue iteration */ +} + +static CURLcode upkeep(struct conncache *conn_cache, void *data) +{ + struct curltime now = Curl_now(); + /* Loop over every connection and make connection alive. */ + Curl_conncache_foreach(data, + conn_cache, + &now, + conn_upkeep); + return CURLE_OK; +} + +/* + * Performs connection upkeep for the given session handle. + */ +CURLcode curl_easy_upkeep(struct Curl_easy *data) +{ + /* Verify that we got an easy handle we can work with. */ + if(!GOOD_EASY_HANDLE(data)) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(data->multi_easy) { + /* Use the common function to keep connections alive. */ + return upkeep(&data->multi_easy->conn_cache, data); + } + else { + /* No connections, so just return success */ + return CURLE_OK; + } +} diff --git a/third_party/curl/lib/easy_lock.h b/third_party/curl/lib/easy_lock.h new file mode 100644 index 0000000..4f6764d --- /dev/null +++ b/third_party/curl/lib/easy_lock.h @@ -0,0 +1,111 @@ +#ifndef HEADER_CURL_EASY_LOCK_H +#define HEADER_CURL_EASY_LOCK_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#define GLOBAL_INIT_IS_THREADSAFE + +#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x600 + +#ifdef __MINGW32__ +#ifndef SRWLOCK_INIT +#define SRWLOCK_INIT NULL +#endif +#endif /* __MINGW32__ */ + +#define curl_simple_lock SRWLOCK +#define CURL_SIMPLE_LOCK_INIT SRWLOCK_INIT + +#define curl_simple_lock_lock(m) AcquireSRWLockExclusive(m) +#define curl_simple_lock_unlock(m) ReleaseSRWLockExclusive(m) + +#elif defined(HAVE_ATOMIC) && defined(HAVE_STDATOMIC_H) +#include +#if defined(HAVE_SCHED_YIELD) +#include +#endif + +#define curl_simple_lock atomic_int +#define CURL_SIMPLE_LOCK_INIT 0 + +/* a clang-thing */ +#ifndef __has_builtin +#define __has_builtin(x) 0 +#endif + +#ifndef __INTEL_COMPILER +/* The Intel compiler tries to look like GCC *and* clang *and* lies in its + __has_builtin() function, so override it. */ + +/* if GCC on i386/x86_64 or if the built-in is present */ +#if ( (defined(__GNUC__) && !defined(__clang__)) && \ + (defined(__i386__) || defined(__x86_64__))) || \ + __has_builtin(__builtin_ia32_pause) +#define HAVE_BUILTIN_IA32_PAUSE +#endif + +#endif + +static inline void curl_simple_lock_lock(curl_simple_lock *lock) +{ + for(;;) { + if(!atomic_exchange_explicit(lock, true, memory_order_acquire)) + break; + /* Reduce cache coherency traffic */ + while(atomic_load_explicit(lock, memory_order_relaxed)) { + /* Reduce load (not mandatory) */ +#ifdef HAVE_BUILTIN_IA32_PAUSE + __builtin_ia32_pause(); +#elif defined(__aarch64__) + __asm__ volatile("yield" ::: "memory"); +#elif defined(HAVE_SCHED_YIELD) + sched_yield(); +#endif + } + } +} + +static inline void curl_simple_lock_unlock(curl_simple_lock *lock) +{ + atomic_store_explicit(lock, false, memory_order_release); +} + +#elif defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) + +#include + +#define curl_simple_lock pthread_mutex_t +#define CURL_SIMPLE_LOCK_INIT PTHREAD_MUTEX_INITIALIZER +#define curl_simple_lock_lock(m) pthread_mutex_lock(m) +#define curl_simple_lock_unlock(m) pthread_mutex_unlock(m) + +#else + +#undef GLOBAL_INIT_IS_THREADSAFE + +#endif + +#endif /* HEADER_CURL_EASY_LOCK_H */ diff --git a/third_party/curl/lib/easygetopt.c b/third_party/curl/lib/easygetopt.c new file mode 100644 index 0000000..a0239a8 --- /dev/null +++ b/third_party/curl/lib/easygetopt.c @@ -0,0 +1,98 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ | | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * ___|___/|_| ______| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "strcase.h" +#include "easyoptions.h" + +#ifndef CURL_DISABLE_GETOPTIONS + +/* Lookups easy options at runtime */ +static struct curl_easyoption *lookup(const char *name, CURLoption id) +{ + DEBUGASSERT(name || id); + DEBUGASSERT(!Curl_easyopts_check()); + if(name || id) { + struct curl_easyoption *o = &Curl_easyopts[0]; + do { + if(name) { + if(strcasecompare(o->name, name)) + return o; + } + else { + if((o->id == id) && !(o->flags & CURLOT_FLAG_ALIAS)) + /* don't match alias options */ + return o; + } + o++; + } while(o->name); + } + return NULL; +} + +const struct curl_easyoption *curl_easy_option_by_name(const char *name) +{ + /* when name is used, the id argument is ignored */ + return lookup(name, CURLOPT_LASTENTRY); +} + +const struct curl_easyoption *curl_easy_option_by_id(CURLoption id) +{ + return lookup(NULL, id); +} + +/* Iterates over available options */ +const struct curl_easyoption * +curl_easy_option_next(const struct curl_easyoption *prev) +{ + if(prev && prev->name) { + prev++; + if(prev->name) + return prev; + } + else if(!prev) + return &Curl_easyopts[0]; + return NULL; +} + +#else +const struct curl_easyoption *curl_easy_option_by_name(const char *name) +{ + (void)name; + return NULL; +} + +const struct curl_easyoption *curl_easy_option_by_id (CURLoption id) +{ + (void)id; + return NULL; +} + +const struct curl_easyoption * +curl_easy_option_next(const struct curl_easyoption *prev) +{ + (void)prev; + return NULL; +} +#endif diff --git a/third_party/curl/lib/easyif.h b/third_party/curl/lib/easyif.h new file mode 100644 index 0000000..6ce3483 --- /dev/null +++ b/third_party/curl/lib/easyif.h @@ -0,0 +1,41 @@ +#ifndef HEADER_CURL_EASYIF_H +#define HEADER_CURL_EASYIF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Prototypes for library-wide functions provided by easy.c + */ +CURLcode Curl_senddata(struct Curl_easy *data, const void *buffer, + size_t buflen, size_t *n); + +#ifdef USE_WEBSOCKETS +CURLcode Curl_connect_only_attach(struct Curl_easy *data); +#endif + +#ifdef CURLDEBUG +CURL_EXTERN CURLcode curl_easy_perform_ev(struct Curl_easy *easy); +#endif + +#endif /* HEADER_CURL_EASYIF_H */ diff --git a/third_party/curl/lib/easyoptions.c b/third_party/curl/lib/easyoptions.c new file mode 100644 index 0000000..c79d136 --- /dev/null +++ b/third_party/curl/lib/easyoptions.c @@ -0,0 +1,381 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* This source code is generated by optiontable.pl - DO NOT EDIT BY HAND */ + +#include "curl_setup.h" +#include "easyoptions.h" + +/* all easy setopt options listed in alphabetical order */ +struct curl_easyoption Curl_easyopts[] = { + {"ABSTRACT_UNIX_SOCKET", CURLOPT_ABSTRACT_UNIX_SOCKET, CURLOT_STRING, 0}, + {"ACCEPTTIMEOUT_MS", CURLOPT_ACCEPTTIMEOUT_MS, CURLOT_LONG, 0}, + {"ACCEPT_ENCODING", CURLOPT_ACCEPT_ENCODING, CURLOT_STRING, 0}, + {"ADDRESS_SCOPE", CURLOPT_ADDRESS_SCOPE, CURLOT_LONG, 0}, + {"ALTSVC", CURLOPT_ALTSVC, CURLOT_STRING, 0}, + {"ALTSVC_CTRL", CURLOPT_ALTSVC_CTRL, CURLOT_LONG, 0}, + {"APPEND", CURLOPT_APPEND, CURLOT_LONG, 0}, + {"AUTOREFERER", CURLOPT_AUTOREFERER, CURLOT_LONG, 0}, + {"AWS_SIGV4", CURLOPT_AWS_SIGV4, CURLOT_STRING, 0}, + {"BUFFERSIZE", CURLOPT_BUFFERSIZE, CURLOT_LONG, 0}, + {"CAINFO", CURLOPT_CAINFO, CURLOT_STRING, 0}, + {"CAINFO_BLOB", CURLOPT_CAINFO_BLOB, CURLOT_BLOB, 0}, + {"CAPATH", CURLOPT_CAPATH, CURLOT_STRING, 0}, + {"CA_CACHE_TIMEOUT", CURLOPT_CA_CACHE_TIMEOUT, CURLOT_LONG, 0}, + {"CERTINFO", CURLOPT_CERTINFO, CURLOT_LONG, 0}, + {"CHUNK_BGN_FUNCTION", CURLOPT_CHUNK_BGN_FUNCTION, CURLOT_FUNCTION, 0}, + {"CHUNK_DATA", CURLOPT_CHUNK_DATA, CURLOT_CBPTR, 0}, + {"CHUNK_END_FUNCTION", CURLOPT_CHUNK_END_FUNCTION, CURLOT_FUNCTION, 0}, + {"CLOSESOCKETDATA", CURLOPT_CLOSESOCKETDATA, CURLOT_CBPTR, 0}, + {"CLOSESOCKETFUNCTION", CURLOPT_CLOSESOCKETFUNCTION, CURLOT_FUNCTION, 0}, + {"CONNECTTIMEOUT", CURLOPT_CONNECTTIMEOUT, CURLOT_LONG, 0}, + {"CONNECTTIMEOUT_MS", CURLOPT_CONNECTTIMEOUT_MS, CURLOT_LONG, 0}, + {"CONNECT_ONLY", CURLOPT_CONNECT_ONLY, CURLOT_LONG, 0}, + {"CONNECT_TO", CURLOPT_CONNECT_TO, CURLOT_SLIST, 0}, + {"CONV_FROM_NETWORK_FUNCTION", CURLOPT_CONV_FROM_NETWORK_FUNCTION, + CURLOT_FUNCTION, 0}, + {"CONV_FROM_UTF8_FUNCTION", CURLOPT_CONV_FROM_UTF8_FUNCTION, + CURLOT_FUNCTION, 0}, + {"CONV_TO_NETWORK_FUNCTION", CURLOPT_CONV_TO_NETWORK_FUNCTION, + CURLOT_FUNCTION, 0}, + {"COOKIE", CURLOPT_COOKIE, CURLOT_STRING, 0}, + {"COOKIEFILE", CURLOPT_COOKIEFILE, CURLOT_STRING, 0}, + {"COOKIEJAR", CURLOPT_COOKIEJAR, CURLOT_STRING, 0}, + {"COOKIELIST", CURLOPT_COOKIELIST, CURLOT_STRING, 0}, + {"COOKIESESSION", CURLOPT_COOKIESESSION, CURLOT_LONG, 0}, + {"COPYPOSTFIELDS", CURLOPT_COPYPOSTFIELDS, CURLOT_OBJECT, 0}, + {"CRLF", CURLOPT_CRLF, CURLOT_LONG, 0}, + {"CRLFILE", CURLOPT_CRLFILE, CURLOT_STRING, 0}, + {"CURLU", CURLOPT_CURLU, CURLOT_OBJECT, 0}, + {"CUSTOMREQUEST", CURLOPT_CUSTOMREQUEST, CURLOT_STRING, 0}, + {"DEBUGDATA", CURLOPT_DEBUGDATA, CURLOT_CBPTR, 0}, + {"DEBUGFUNCTION", CURLOPT_DEBUGFUNCTION, CURLOT_FUNCTION, 0}, + {"DEFAULT_PROTOCOL", CURLOPT_DEFAULT_PROTOCOL, CURLOT_STRING, 0}, + {"DIRLISTONLY", CURLOPT_DIRLISTONLY, CURLOT_LONG, 0}, + {"DISALLOW_USERNAME_IN_URL", CURLOPT_DISALLOW_USERNAME_IN_URL, + CURLOT_LONG, 0}, + {"DNS_CACHE_TIMEOUT", CURLOPT_DNS_CACHE_TIMEOUT, CURLOT_LONG, 0}, + {"DNS_INTERFACE", CURLOPT_DNS_INTERFACE, CURLOT_STRING, 0}, + {"DNS_LOCAL_IP4", CURLOPT_DNS_LOCAL_IP4, CURLOT_STRING, 0}, + {"DNS_LOCAL_IP6", CURLOPT_DNS_LOCAL_IP6, CURLOT_STRING, 0}, + {"DNS_SERVERS", CURLOPT_DNS_SERVERS, CURLOT_STRING, 0}, + {"DNS_SHUFFLE_ADDRESSES", CURLOPT_DNS_SHUFFLE_ADDRESSES, CURLOT_LONG, 0}, + {"DNS_USE_GLOBAL_CACHE", CURLOPT_DNS_USE_GLOBAL_CACHE, CURLOT_LONG, 0}, + {"DOH_SSL_VERIFYHOST", CURLOPT_DOH_SSL_VERIFYHOST, CURLOT_LONG, 0}, + {"DOH_SSL_VERIFYPEER", CURLOPT_DOH_SSL_VERIFYPEER, CURLOT_LONG, 0}, + {"DOH_SSL_VERIFYSTATUS", CURLOPT_DOH_SSL_VERIFYSTATUS, CURLOT_LONG, 0}, + {"DOH_URL", CURLOPT_DOH_URL, CURLOT_STRING, 0}, + {"ECH", CURLOPT_ECH, CURLOT_STRING, 0}, + {"EGDSOCKET", CURLOPT_EGDSOCKET, CURLOT_STRING, 0}, + {"ENCODING", CURLOPT_ACCEPT_ENCODING, CURLOT_STRING, CURLOT_FLAG_ALIAS}, + {"ERRORBUFFER", CURLOPT_ERRORBUFFER, CURLOT_OBJECT, 0}, + {"EXPECT_100_TIMEOUT_MS", CURLOPT_EXPECT_100_TIMEOUT_MS, CURLOT_LONG, 0}, + {"FAILONERROR", CURLOPT_FAILONERROR, CURLOT_LONG, 0}, + {"FILE", CURLOPT_WRITEDATA, CURLOT_CBPTR, CURLOT_FLAG_ALIAS}, + {"FILETIME", CURLOPT_FILETIME, CURLOT_LONG, 0}, + {"FNMATCH_DATA", CURLOPT_FNMATCH_DATA, CURLOT_CBPTR, 0}, + {"FNMATCH_FUNCTION", CURLOPT_FNMATCH_FUNCTION, CURLOT_FUNCTION, 0}, + {"FOLLOWLOCATION", CURLOPT_FOLLOWLOCATION, CURLOT_LONG, 0}, + {"FORBID_REUSE", CURLOPT_FORBID_REUSE, CURLOT_LONG, 0}, + {"FRESH_CONNECT", CURLOPT_FRESH_CONNECT, CURLOT_LONG, 0}, + {"FTPAPPEND", CURLOPT_APPEND, CURLOT_LONG, CURLOT_FLAG_ALIAS}, + {"FTPLISTONLY", CURLOPT_DIRLISTONLY, CURLOT_LONG, CURLOT_FLAG_ALIAS}, + {"FTPPORT", CURLOPT_FTPPORT, CURLOT_STRING, 0}, + {"FTPSSLAUTH", CURLOPT_FTPSSLAUTH, CURLOT_VALUES, 0}, + {"FTP_ACCOUNT", CURLOPT_FTP_ACCOUNT, CURLOT_STRING, 0}, + {"FTP_ALTERNATIVE_TO_USER", CURLOPT_FTP_ALTERNATIVE_TO_USER, + CURLOT_STRING, 0}, + {"FTP_CREATE_MISSING_DIRS", CURLOPT_FTP_CREATE_MISSING_DIRS, + CURLOT_LONG, 0}, + {"FTP_FILEMETHOD", CURLOPT_FTP_FILEMETHOD, CURLOT_VALUES, 0}, + {"FTP_RESPONSE_TIMEOUT", CURLOPT_SERVER_RESPONSE_TIMEOUT, + CURLOT_LONG, CURLOT_FLAG_ALIAS}, + {"FTP_SKIP_PASV_IP", CURLOPT_FTP_SKIP_PASV_IP, CURLOT_LONG, 0}, + {"FTP_SSL", CURLOPT_USE_SSL, CURLOT_VALUES, CURLOT_FLAG_ALIAS}, + {"FTP_SSL_CCC", CURLOPT_FTP_SSL_CCC, CURLOT_LONG, 0}, + {"FTP_USE_EPRT", CURLOPT_FTP_USE_EPRT, CURLOT_LONG, 0}, + {"FTP_USE_EPSV", CURLOPT_FTP_USE_EPSV, CURLOT_LONG, 0}, + {"FTP_USE_PRET", CURLOPT_FTP_USE_PRET, CURLOT_LONG, 0}, + {"GSSAPI_DELEGATION", CURLOPT_GSSAPI_DELEGATION, CURLOT_VALUES, 0}, + {"HAPPY_EYEBALLS_TIMEOUT_MS", CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, + CURLOT_LONG, 0}, + {"HAPROXYPROTOCOL", CURLOPT_HAPROXYPROTOCOL, CURLOT_LONG, 0}, + {"HAPROXY_CLIENT_IP", CURLOPT_HAPROXY_CLIENT_IP, CURLOT_STRING, 0}, + {"HEADER", CURLOPT_HEADER, CURLOT_LONG, 0}, + {"HEADERDATA", CURLOPT_HEADERDATA, CURLOT_CBPTR, 0}, + {"HEADERFUNCTION", CURLOPT_HEADERFUNCTION, CURLOT_FUNCTION, 0}, + {"HEADEROPT", CURLOPT_HEADEROPT, CURLOT_VALUES, 0}, + {"HSTS", CURLOPT_HSTS, CURLOT_STRING, 0}, + {"HSTSREADDATA", CURLOPT_HSTSREADDATA, CURLOT_CBPTR, 0}, + {"HSTSREADFUNCTION", CURLOPT_HSTSREADFUNCTION, CURLOT_FUNCTION, 0}, + {"HSTSWRITEDATA", CURLOPT_HSTSWRITEDATA, CURLOT_CBPTR, 0}, + {"HSTSWRITEFUNCTION", CURLOPT_HSTSWRITEFUNCTION, CURLOT_FUNCTION, 0}, + {"HSTS_CTRL", CURLOPT_HSTS_CTRL, CURLOT_LONG, 0}, + {"HTTP09_ALLOWED", CURLOPT_HTTP09_ALLOWED, CURLOT_LONG, 0}, + {"HTTP200ALIASES", CURLOPT_HTTP200ALIASES, CURLOT_SLIST, 0}, + {"HTTPAUTH", CURLOPT_HTTPAUTH, CURLOT_VALUES, 0}, + {"HTTPGET", CURLOPT_HTTPGET, CURLOT_LONG, 0}, + {"HTTPHEADER", CURLOPT_HTTPHEADER, CURLOT_SLIST, 0}, + {"HTTPPOST", CURLOPT_HTTPPOST, CURLOT_OBJECT, 0}, + {"HTTPPROXYTUNNEL", CURLOPT_HTTPPROXYTUNNEL, CURLOT_LONG, 0}, + {"HTTP_CONTENT_DECODING", CURLOPT_HTTP_CONTENT_DECODING, CURLOT_LONG, 0}, + {"HTTP_TRANSFER_DECODING", CURLOPT_HTTP_TRANSFER_DECODING, CURLOT_LONG, 0}, + {"HTTP_VERSION", CURLOPT_HTTP_VERSION, CURLOT_VALUES, 0}, + {"IGNORE_CONTENT_LENGTH", CURLOPT_IGNORE_CONTENT_LENGTH, CURLOT_LONG, 0}, + {"INFILE", CURLOPT_READDATA, CURLOT_CBPTR, CURLOT_FLAG_ALIAS}, + {"INFILESIZE", CURLOPT_INFILESIZE, CURLOT_LONG, 0}, + {"INFILESIZE_LARGE", CURLOPT_INFILESIZE_LARGE, CURLOT_OFF_T, 0}, + {"INTERFACE", CURLOPT_INTERFACE, CURLOT_STRING, 0}, + {"INTERLEAVEDATA", CURLOPT_INTERLEAVEDATA, CURLOT_CBPTR, 0}, + {"INTERLEAVEFUNCTION", CURLOPT_INTERLEAVEFUNCTION, CURLOT_FUNCTION, 0}, + {"IOCTLDATA", CURLOPT_IOCTLDATA, CURLOT_CBPTR, 0}, + {"IOCTLFUNCTION", CURLOPT_IOCTLFUNCTION, CURLOT_FUNCTION, 0}, + {"IPRESOLVE", CURLOPT_IPRESOLVE, CURLOT_VALUES, 0}, + {"ISSUERCERT", CURLOPT_ISSUERCERT, CURLOT_STRING, 0}, + {"ISSUERCERT_BLOB", CURLOPT_ISSUERCERT_BLOB, CURLOT_BLOB, 0}, + {"KEEP_SENDING_ON_ERROR", CURLOPT_KEEP_SENDING_ON_ERROR, CURLOT_LONG, 0}, + {"KEYPASSWD", CURLOPT_KEYPASSWD, CURLOT_STRING, 0}, + {"KRB4LEVEL", CURLOPT_KRBLEVEL, CURLOT_STRING, CURLOT_FLAG_ALIAS}, + {"KRBLEVEL", CURLOPT_KRBLEVEL, CURLOT_STRING, 0}, + {"LOCALPORT", CURLOPT_LOCALPORT, CURLOT_LONG, 0}, + {"LOCALPORTRANGE", CURLOPT_LOCALPORTRANGE, CURLOT_LONG, 0}, + {"LOGIN_OPTIONS", CURLOPT_LOGIN_OPTIONS, CURLOT_STRING, 0}, + {"LOW_SPEED_LIMIT", CURLOPT_LOW_SPEED_LIMIT, CURLOT_LONG, 0}, + {"LOW_SPEED_TIME", CURLOPT_LOW_SPEED_TIME, CURLOT_LONG, 0}, + {"MAIL_AUTH", CURLOPT_MAIL_AUTH, CURLOT_STRING, 0}, + {"MAIL_FROM", CURLOPT_MAIL_FROM, CURLOT_STRING, 0}, + {"MAIL_RCPT", CURLOPT_MAIL_RCPT, CURLOT_SLIST, 0}, + {"MAIL_RCPT_ALLLOWFAILS", CURLOPT_MAIL_RCPT_ALLOWFAILS, + CURLOT_LONG, CURLOT_FLAG_ALIAS}, + {"MAIL_RCPT_ALLOWFAILS", CURLOPT_MAIL_RCPT_ALLOWFAILS, CURLOT_LONG, 0}, + {"MAXAGE_CONN", CURLOPT_MAXAGE_CONN, CURLOT_LONG, 0}, + {"MAXCONNECTS", CURLOPT_MAXCONNECTS, CURLOT_LONG, 0}, + {"MAXFILESIZE", CURLOPT_MAXFILESIZE, CURLOT_LONG, 0}, + {"MAXFILESIZE_LARGE", CURLOPT_MAXFILESIZE_LARGE, CURLOT_OFF_T, 0}, + {"MAXLIFETIME_CONN", CURLOPT_MAXLIFETIME_CONN, CURLOT_LONG, 0}, + {"MAXREDIRS", CURLOPT_MAXREDIRS, CURLOT_LONG, 0}, + {"MAX_RECV_SPEED_LARGE", CURLOPT_MAX_RECV_SPEED_LARGE, CURLOT_OFF_T, 0}, + {"MAX_SEND_SPEED_LARGE", CURLOPT_MAX_SEND_SPEED_LARGE, CURLOT_OFF_T, 0}, + {"MIMEPOST", CURLOPT_MIMEPOST, CURLOT_OBJECT, 0}, + {"MIME_OPTIONS", CURLOPT_MIME_OPTIONS, CURLOT_LONG, 0}, + {"NETRC", CURLOPT_NETRC, CURLOT_VALUES, 0}, + {"NETRC_FILE", CURLOPT_NETRC_FILE, CURLOT_STRING, 0}, + {"NEW_DIRECTORY_PERMS", CURLOPT_NEW_DIRECTORY_PERMS, CURLOT_LONG, 0}, + {"NEW_FILE_PERMS", CURLOPT_NEW_FILE_PERMS, CURLOT_LONG, 0}, + {"NOBODY", CURLOPT_NOBODY, CURLOT_LONG, 0}, + {"NOPROGRESS", CURLOPT_NOPROGRESS, CURLOT_LONG, 0}, + {"NOPROXY", CURLOPT_NOPROXY, CURLOT_STRING, 0}, + {"NOSIGNAL", CURLOPT_NOSIGNAL, CURLOT_LONG, 0}, + {"OPENSOCKETDATA", CURLOPT_OPENSOCKETDATA, CURLOT_CBPTR, 0}, + {"OPENSOCKETFUNCTION", CURLOPT_OPENSOCKETFUNCTION, CURLOT_FUNCTION, 0}, + {"PASSWORD", CURLOPT_PASSWORD, CURLOT_STRING, 0}, + {"PATH_AS_IS", CURLOPT_PATH_AS_IS, CURLOT_LONG, 0}, + {"PINNEDPUBLICKEY", CURLOPT_PINNEDPUBLICKEY, CURLOT_STRING, 0}, + {"PIPEWAIT", CURLOPT_PIPEWAIT, CURLOT_LONG, 0}, + {"PORT", CURLOPT_PORT, CURLOT_LONG, 0}, + {"POST", CURLOPT_POST, CURLOT_LONG, 0}, + {"POST301", CURLOPT_POSTREDIR, CURLOT_VALUES, CURLOT_FLAG_ALIAS}, + {"POSTFIELDS", CURLOPT_POSTFIELDS, CURLOT_OBJECT, 0}, + {"POSTFIELDSIZE", CURLOPT_POSTFIELDSIZE, CURLOT_LONG, 0}, + {"POSTFIELDSIZE_LARGE", CURLOPT_POSTFIELDSIZE_LARGE, CURLOT_OFF_T, 0}, + {"POSTQUOTE", CURLOPT_POSTQUOTE, CURLOT_SLIST, 0}, + {"POSTREDIR", CURLOPT_POSTREDIR, CURLOT_VALUES, 0}, + {"PREQUOTE", CURLOPT_PREQUOTE, CURLOT_SLIST, 0}, + {"PREREQDATA", CURLOPT_PREREQDATA, CURLOT_CBPTR, 0}, + {"PREREQFUNCTION", CURLOPT_PREREQFUNCTION, CURLOT_FUNCTION, 0}, + {"PRE_PROXY", CURLOPT_PRE_PROXY, CURLOT_STRING, 0}, + {"PRIVATE", CURLOPT_PRIVATE, CURLOT_OBJECT, 0}, + {"PROGRESSDATA", CURLOPT_XFERINFODATA, CURLOT_CBPTR, CURLOT_FLAG_ALIAS}, + {"PROGRESSFUNCTION", CURLOPT_PROGRESSFUNCTION, CURLOT_FUNCTION, 0}, + {"PROTOCOLS", CURLOPT_PROTOCOLS, CURLOT_LONG, 0}, + {"PROTOCOLS_STR", CURLOPT_PROTOCOLS_STR, CURLOT_STRING, 0}, + {"PROXY", CURLOPT_PROXY, CURLOT_STRING, 0}, + {"PROXYAUTH", CURLOPT_PROXYAUTH, CURLOT_VALUES, 0}, + {"PROXYHEADER", CURLOPT_PROXYHEADER, CURLOT_SLIST, 0}, + {"PROXYPASSWORD", CURLOPT_PROXYPASSWORD, CURLOT_STRING, 0}, + {"PROXYPORT", CURLOPT_PROXYPORT, CURLOT_LONG, 0}, + {"PROXYTYPE", CURLOPT_PROXYTYPE, CURLOT_VALUES, 0}, + {"PROXYUSERNAME", CURLOPT_PROXYUSERNAME, CURLOT_STRING, 0}, + {"PROXYUSERPWD", CURLOPT_PROXYUSERPWD, CURLOT_STRING, 0}, + {"PROXY_CAINFO", CURLOPT_PROXY_CAINFO, CURLOT_STRING, 0}, + {"PROXY_CAINFO_BLOB", CURLOPT_PROXY_CAINFO_BLOB, CURLOT_BLOB, 0}, + {"PROXY_CAPATH", CURLOPT_PROXY_CAPATH, CURLOT_STRING, 0}, + {"PROXY_CRLFILE", CURLOPT_PROXY_CRLFILE, CURLOT_STRING, 0}, + {"PROXY_ISSUERCERT", CURLOPT_PROXY_ISSUERCERT, CURLOT_STRING, 0}, + {"PROXY_ISSUERCERT_BLOB", CURLOPT_PROXY_ISSUERCERT_BLOB, CURLOT_BLOB, 0}, + {"PROXY_KEYPASSWD", CURLOPT_PROXY_KEYPASSWD, CURLOT_STRING, 0}, + {"PROXY_PINNEDPUBLICKEY", CURLOPT_PROXY_PINNEDPUBLICKEY, CURLOT_STRING, 0}, + {"PROXY_SERVICE_NAME", CURLOPT_PROXY_SERVICE_NAME, CURLOT_STRING, 0}, + {"PROXY_SSLCERT", CURLOPT_PROXY_SSLCERT, CURLOT_STRING, 0}, + {"PROXY_SSLCERTTYPE", CURLOPT_PROXY_SSLCERTTYPE, CURLOT_STRING, 0}, + {"PROXY_SSLCERT_BLOB", CURLOPT_PROXY_SSLCERT_BLOB, CURLOT_BLOB, 0}, + {"PROXY_SSLKEY", CURLOPT_PROXY_SSLKEY, CURLOT_STRING, 0}, + {"PROXY_SSLKEYTYPE", CURLOPT_PROXY_SSLKEYTYPE, CURLOT_STRING, 0}, + {"PROXY_SSLKEY_BLOB", CURLOPT_PROXY_SSLKEY_BLOB, CURLOT_BLOB, 0}, + {"PROXY_SSLVERSION", CURLOPT_PROXY_SSLVERSION, CURLOT_VALUES, 0}, + {"PROXY_SSL_CIPHER_LIST", CURLOPT_PROXY_SSL_CIPHER_LIST, CURLOT_STRING, 0}, + {"PROXY_SSL_OPTIONS", CURLOPT_PROXY_SSL_OPTIONS, CURLOT_LONG, 0}, + {"PROXY_SSL_VERIFYHOST", CURLOPT_PROXY_SSL_VERIFYHOST, CURLOT_LONG, 0}, + {"PROXY_SSL_VERIFYPEER", CURLOPT_PROXY_SSL_VERIFYPEER, CURLOT_LONG, 0}, + {"PROXY_TLS13_CIPHERS", CURLOPT_PROXY_TLS13_CIPHERS, CURLOT_STRING, 0}, + {"PROXY_TLSAUTH_PASSWORD", CURLOPT_PROXY_TLSAUTH_PASSWORD, + CURLOT_STRING, 0}, + {"PROXY_TLSAUTH_TYPE", CURLOPT_PROXY_TLSAUTH_TYPE, CURLOT_STRING, 0}, + {"PROXY_TLSAUTH_USERNAME", CURLOPT_PROXY_TLSAUTH_USERNAME, + CURLOT_STRING, 0}, + {"PROXY_TRANSFER_MODE", CURLOPT_PROXY_TRANSFER_MODE, CURLOT_LONG, 0}, + {"PUT", CURLOPT_PUT, CURLOT_LONG, 0}, + {"QUICK_EXIT", CURLOPT_QUICK_EXIT, CURLOT_LONG, 0}, + {"QUOTE", CURLOPT_QUOTE, CURLOT_SLIST, 0}, + {"RANDOM_FILE", CURLOPT_RANDOM_FILE, CURLOT_STRING, 0}, + {"RANGE", CURLOPT_RANGE, CURLOT_STRING, 0}, + {"READDATA", CURLOPT_READDATA, CURLOT_CBPTR, 0}, + {"READFUNCTION", CURLOPT_READFUNCTION, CURLOT_FUNCTION, 0}, + {"REDIR_PROTOCOLS", CURLOPT_REDIR_PROTOCOLS, CURLOT_LONG, 0}, + {"REDIR_PROTOCOLS_STR", CURLOPT_REDIR_PROTOCOLS_STR, CURLOT_STRING, 0}, + {"REFERER", CURLOPT_REFERER, CURLOT_STRING, 0}, + {"REQUEST_TARGET", CURLOPT_REQUEST_TARGET, CURLOT_STRING, 0}, + {"RESOLVE", CURLOPT_RESOLVE, CURLOT_SLIST, 0}, + {"RESOLVER_START_DATA", CURLOPT_RESOLVER_START_DATA, CURLOT_CBPTR, 0}, + {"RESOLVER_START_FUNCTION", CURLOPT_RESOLVER_START_FUNCTION, + CURLOT_FUNCTION, 0}, + {"RESUME_FROM", CURLOPT_RESUME_FROM, CURLOT_LONG, 0}, + {"RESUME_FROM_LARGE", CURLOPT_RESUME_FROM_LARGE, CURLOT_OFF_T, 0}, + {"RTSPHEADER", CURLOPT_HTTPHEADER, CURLOT_SLIST, CURLOT_FLAG_ALIAS}, + {"RTSP_CLIENT_CSEQ", CURLOPT_RTSP_CLIENT_CSEQ, CURLOT_LONG, 0}, + {"RTSP_REQUEST", CURLOPT_RTSP_REQUEST, CURLOT_VALUES, 0}, + {"RTSP_SERVER_CSEQ", CURLOPT_RTSP_SERVER_CSEQ, CURLOT_LONG, 0}, + {"RTSP_SESSION_ID", CURLOPT_RTSP_SESSION_ID, CURLOT_STRING, 0}, + {"RTSP_STREAM_URI", CURLOPT_RTSP_STREAM_URI, CURLOT_STRING, 0}, + {"RTSP_TRANSPORT", CURLOPT_RTSP_TRANSPORT, CURLOT_STRING, 0}, + {"SASL_AUTHZID", CURLOPT_SASL_AUTHZID, CURLOT_STRING, 0}, + {"SASL_IR", CURLOPT_SASL_IR, CURLOT_LONG, 0}, + {"SEEKDATA", CURLOPT_SEEKDATA, CURLOT_CBPTR, 0}, + {"SEEKFUNCTION", CURLOPT_SEEKFUNCTION, CURLOT_FUNCTION, 0}, + {"SERVER_RESPONSE_TIMEOUT", CURLOPT_SERVER_RESPONSE_TIMEOUT, + CURLOT_LONG, 0}, + {"SERVER_RESPONSE_TIMEOUT_MS", CURLOPT_SERVER_RESPONSE_TIMEOUT_MS, + CURLOT_LONG, 0}, + {"SERVICE_NAME", CURLOPT_SERVICE_NAME, CURLOT_STRING, 0}, + {"SHARE", CURLOPT_SHARE, CURLOT_OBJECT, 0}, + {"SOCKOPTDATA", CURLOPT_SOCKOPTDATA, CURLOT_CBPTR, 0}, + {"SOCKOPTFUNCTION", CURLOPT_SOCKOPTFUNCTION, CURLOT_FUNCTION, 0}, + {"SOCKS5_AUTH", CURLOPT_SOCKS5_AUTH, CURLOT_LONG, 0}, + {"SOCKS5_GSSAPI_NEC", CURLOPT_SOCKS5_GSSAPI_NEC, CURLOT_LONG, 0}, + {"SOCKS5_GSSAPI_SERVICE", CURLOPT_SOCKS5_GSSAPI_SERVICE, CURLOT_STRING, 0}, + {"SSH_AUTH_TYPES", CURLOPT_SSH_AUTH_TYPES, CURLOT_VALUES, 0}, + {"SSH_COMPRESSION", CURLOPT_SSH_COMPRESSION, CURLOT_LONG, 0}, + {"SSH_HOSTKEYDATA", CURLOPT_SSH_HOSTKEYDATA, CURLOT_CBPTR, 0}, + {"SSH_HOSTKEYFUNCTION", CURLOPT_SSH_HOSTKEYFUNCTION, CURLOT_FUNCTION, 0}, + {"SSH_HOST_PUBLIC_KEY_MD5", CURLOPT_SSH_HOST_PUBLIC_KEY_MD5, + CURLOT_STRING, 0}, + {"SSH_HOST_PUBLIC_KEY_SHA256", CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256, + CURLOT_STRING, 0}, + {"SSH_KEYDATA", CURLOPT_SSH_KEYDATA, CURLOT_CBPTR, 0}, + {"SSH_KEYFUNCTION", CURLOPT_SSH_KEYFUNCTION, CURLOT_FUNCTION, 0}, + {"SSH_KNOWNHOSTS", CURLOPT_SSH_KNOWNHOSTS, CURLOT_STRING, 0}, + {"SSH_PRIVATE_KEYFILE", CURLOPT_SSH_PRIVATE_KEYFILE, CURLOT_STRING, 0}, + {"SSH_PUBLIC_KEYFILE", CURLOPT_SSH_PUBLIC_KEYFILE, CURLOT_STRING, 0}, + {"SSLCERT", CURLOPT_SSLCERT, CURLOT_STRING, 0}, + {"SSLCERTPASSWD", CURLOPT_KEYPASSWD, CURLOT_STRING, CURLOT_FLAG_ALIAS}, + {"SSLCERTTYPE", CURLOPT_SSLCERTTYPE, CURLOT_STRING, 0}, + {"SSLCERT_BLOB", CURLOPT_SSLCERT_BLOB, CURLOT_BLOB, 0}, + {"SSLENGINE", CURLOPT_SSLENGINE, CURLOT_STRING, 0}, + {"SSLENGINE_DEFAULT", CURLOPT_SSLENGINE_DEFAULT, CURLOT_LONG, 0}, + {"SSLKEY", CURLOPT_SSLKEY, CURLOT_STRING, 0}, + {"SSLKEYPASSWD", CURLOPT_KEYPASSWD, CURLOT_STRING, CURLOT_FLAG_ALIAS}, + {"SSLKEYTYPE", CURLOPT_SSLKEYTYPE, CURLOT_STRING, 0}, + {"SSLKEY_BLOB", CURLOPT_SSLKEY_BLOB, CURLOT_BLOB, 0}, + {"SSLVERSION", CURLOPT_SSLVERSION, CURLOT_VALUES, 0}, + {"SSL_CIPHER_LIST", CURLOPT_SSL_CIPHER_LIST, CURLOT_STRING, 0}, + {"SSL_CTX_DATA", CURLOPT_SSL_CTX_DATA, CURLOT_CBPTR, 0}, + {"SSL_CTX_FUNCTION", CURLOPT_SSL_CTX_FUNCTION, CURLOT_FUNCTION, 0}, + {"SSL_EC_CURVES", CURLOPT_SSL_EC_CURVES, CURLOT_STRING, 0}, + {"SSL_ENABLE_ALPN", CURLOPT_SSL_ENABLE_ALPN, CURLOT_LONG, 0}, + {"SSL_ENABLE_NPN", CURLOPT_SSL_ENABLE_NPN, CURLOT_LONG, 0}, + {"SSL_FALSESTART", CURLOPT_SSL_FALSESTART, CURLOT_LONG, 0}, + {"SSL_OPTIONS", CURLOPT_SSL_OPTIONS, CURLOT_VALUES, 0}, + {"SSL_SESSIONID_CACHE", CURLOPT_SSL_SESSIONID_CACHE, CURLOT_LONG, 0}, + {"SSL_VERIFYHOST", CURLOPT_SSL_VERIFYHOST, CURLOT_LONG, 0}, + {"SSL_VERIFYPEER", CURLOPT_SSL_VERIFYPEER, CURLOT_LONG, 0}, + {"SSL_VERIFYSTATUS", CURLOPT_SSL_VERIFYSTATUS, CURLOT_LONG, 0}, + {"STDERR", CURLOPT_STDERR, CURLOT_OBJECT, 0}, + {"STREAM_DEPENDS", CURLOPT_STREAM_DEPENDS, CURLOT_OBJECT, 0}, + {"STREAM_DEPENDS_E", CURLOPT_STREAM_DEPENDS_E, CURLOT_OBJECT, 0}, + {"STREAM_WEIGHT", CURLOPT_STREAM_WEIGHT, CURLOT_LONG, 0}, + {"SUPPRESS_CONNECT_HEADERS", CURLOPT_SUPPRESS_CONNECT_HEADERS, + CURLOT_LONG, 0}, + {"TCP_FASTOPEN", CURLOPT_TCP_FASTOPEN, CURLOT_LONG, 0}, + {"TCP_KEEPALIVE", CURLOPT_TCP_KEEPALIVE, CURLOT_LONG, 0}, + {"TCP_KEEPIDLE", CURLOPT_TCP_KEEPIDLE, CURLOT_LONG, 0}, + {"TCP_KEEPINTVL", CURLOPT_TCP_KEEPINTVL, CURLOT_LONG, 0}, + {"TCP_NODELAY", CURLOPT_TCP_NODELAY, CURLOT_LONG, 0}, + {"TELNETOPTIONS", CURLOPT_TELNETOPTIONS, CURLOT_SLIST, 0}, + {"TFTP_BLKSIZE", CURLOPT_TFTP_BLKSIZE, CURLOT_LONG, 0}, + {"TFTP_NO_OPTIONS", CURLOPT_TFTP_NO_OPTIONS, CURLOT_LONG, 0}, + {"TIMECONDITION", CURLOPT_TIMECONDITION, CURLOT_VALUES, 0}, + {"TIMEOUT", CURLOPT_TIMEOUT, CURLOT_LONG, 0}, + {"TIMEOUT_MS", CURLOPT_TIMEOUT_MS, CURLOT_LONG, 0}, + {"TIMEVALUE", CURLOPT_TIMEVALUE, CURLOT_LONG, 0}, + {"TIMEVALUE_LARGE", CURLOPT_TIMEVALUE_LARGE, CURLOT_OFF_T, 0}, + {"TLS13_CIPHERS", CURLOPT_TLS13_CIPHERS, CURLOT_STRING, 0}, + {"TLSAUTH_PASSWORD", CURLOPT_TLSAUTH_PASSWORD, CURLOT_STRING, 0}, + {"TLSAUTH_TYPE", CURLOPT_TLSAUTH_TYPE, CURLOT_STRING, 0}, + {"TLSAUTH_USERNAME", CURLOPT_TLSAUTH_USERNAME, CURLOT_STRING, 0}, + {"TRAILERDATA", CURLOPT_TRAILERDATA, CURLOT_CBPTR, 0}, + {"TRAILERFUNCTION", CURLOPT_TRAILERFUNCTION, CURLOT_FUNCTION, 0}, + {"TRANSFERTEXT", CURLOPT_TRANSFERTEXT, CURLOT_LONG, 0}, + {"TRANSFER_ENCODING", CURLOPT_TRANSFER_ENCODING, CURLOT_LONG, 0}, + {"UNIX_SOCKET_PATH", CURLOPT_UNIX_SOCKET_PATH, CURLOT_STRING, 0}, + {"UNRESTRICTED_AUTH", CURLOPT_UNRESTRICTED_AUTH, CURLOT_LONG, 0}, + {"UPKEEP_INTERVAL_MS", CURLOPT_UPKEEP_INTERVAL_MS, CURLOT_LONG, 0}, + {"UPLOAD", CURLOPT_UPLOAD, CURLOT_LONG, 0}, + {"UPLOAD_BUFFERSIZE", CURLOPT_UPLOAD_BUFFERSIZE, CURLOT_LONG, 0}, + {"URL", CURLOPT_URL, CURLOT_STRING, 0}, + {"USERAGENT", CURLOPT_USERAGENT, CURLOT_STRING, 0}, + {"USERNAME", CURLOPT_USERNAME, CURLOT_STRING, 0}, + {"USERPWD", CURLOPT_USERPWD, CURLOT_STRING, 0}, + {"USE_SSL", CURLOPT_USE_SSL, CURLOT_VALUES, 0}, + {"VERBOSE", CURLOPT_VERBOSE, CURLOT_LONG, 0}, + {"WILDCARDMATCH", CURLOPT_WILDCARDMATCH, CURLOT_LONG, 0}, + {"WRITEDATA", CURLOPT_WRITEDATA, CURLOT_CBPTR, 0}, + {"WRITEFUNCTION", CURLOPT_WRITEFUNCTION, CURLOT_FUNCTION, 0}, + {"WRITEHEADER", CURLOPT_HEADERDATA, CURLOT_CBPTR, CURLOT_FLAG_ALIAS}, + {"WS_OPTIONS", CURLOPT_WS_OPTIONS, CURLOT_LONG, 0}, + {"XFERINFODATA", CURLOPT_XFERINFODATA, CURLOT_CBPTR, 0}, + {"XFERINFOFUNCTION", CURLOPT_XFERINFOFUNCTION, CURLOT_FUNCTION, 0}, + {"XOAUTH2_BEARER", CURLOPT_XOAUTH2_BEARER, CURLOT_STRING, 0}, + {NULL, CURLOPT_LASTENTRY, CURLOT_LONG, 0} /* end of table */ +}; + +#ifdef DEBUGBUILD +/* + * Curl_easyopts_check() is a debug-only function that returns non-zero + * if this source file is not in sync with the options listed in curl/curl.h + */ +int Curl_easyopts_check(void) +{ + return ((CURLOPT_LASTENTRY%10000) != (325 + 1)); +} +#endif diff --git a/third_party/curl/lib/easyoptions.h b/third_party/curl/lib/easyoptions.h new file mode 100644 index 0000000..24b4cd9 --- /dev/null +++ b/third_party/curl/lib/easyoptions.h @@ -0,0 +1,37 @@ +#ifndef HEADER_CURL_EASYOPTIONS_H +#define HEADER_CURL_EASYOPTIONS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* should probably go into the public header */ + +#include + +/* generated table with all easy options */ +extern struct curl_easyoption Curl_easyopts[]; + +#ifdef DEBUGBUILD +int Curl_easyopts_check(void); +#endif +#endif diff --git a/third_party/curl/lib/escape.c b/third_party/curl/lib/escape.c new file mode 100644 index 0000000..5af00c3 --- /dev/null +++ b/third_party/curl/lib/escape.c @@ -0,0 +1,234 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* Escape and unescape URL encoding in strings. The functions return a new + * allocated string or NULL if an error occurred. */ + +#include "curl_setup.h" + +#include + +#include "urldata.h" +#include "warnless.h" +#include "escape.h" +#include "strdup.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* for ABI-compatibility with previous versions */ +char *curl_escape(const char *string, int inlength) +{ + return curl_easy_escape(NULL, string, inlength); +} + +/* for ABI-compatibility with previous versions */ +char *curl_unescape(const char *string, int length) +{ + return curl_easy_unescape(NULL, string, length, NULL); +} + +/* Escapes for URL the given unescaped string of given length. + * 'data' is ignored since 7.82.0. + */ +char *curl_easy_escape(struct Curl_easy *data, const char *string, + int inlength) +{ + size_t length; + struct dynbuf d; + (void)data; + + if(inlength < 0) + return NULL; + + Curl_dyn_init(&d, CURL_MAX_INPUT_LENGTH * 3); + + length = (inlength?(size_t)inlength:strlen(string)); + if(!length) + return strdup(""); + + while(length--) { + unsigned char in = *string++; /* treat the characters unsigned */ + + if(ISUNRESERVED(in)) { + /* append this */ + if(Curl_dyn_addn(&d, &in, 1)) + return NULL; + } + else { + /* encode it */ + const char hex[] = "0123456789ABCDEF"; + char out[3]={'%'}; + out[1] = hex[in>>4]; + out[2] = hex[in & 0xf]; + if(Curl_dyn_addn(&d, out, 3)) + return NULL; + } + } + + return Curl_dyn_ptr(&d); +} + +static const unsigned char hextable[] = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, /* 0x30 - 0x3f */ + 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x40 - 0x4f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x50 - 0x5f */ + 0, 10, 11, 12, 13, 14, 15 /* 0x60 - 0x66 */ +}; + +/* the input is a single hex digit */ +#define onehex2dec(x) hextable[x - '0'] + +/* + * Curl_urldecode() URL decodes the given string. + * + * Returns a pointer to a malloced string in *ostring with length given in + * *olen. If length == 0, the length is assumed to be strlen(string). + * + * ctrl options: + * - REJECT_NADA: accept everything + * - REJECT_CTRL: rejects control characters (byte codes lower than 32) in + * the data + * - REJECT_ZERO: rejects decoded zero bytes + * + * The values for the enum starts at 2, to make the assert detect legacy + * invokes that used TRUE/FALSE (0 and 1). + */ + +CURLcode Curl_urldecode(const char *string, size_t length, + char **ostring, size_t *olen, + enum urlreject ctrl) +{ + size_t alloc; + char *ns; + + DEBUGASSERT(string); + DEBUGASSERT(ctrl >= REJECT_NADA); /* crash on TRUE/FALSE */ + + alloc = (length?length:strlen(string)); + ns = malloc(alloc + 1); + + if(!ns) + return CURLE_OUT_OF_MEMORY; + + /* store output string */ + *ostring = ns; + + while(alloc) { + unsigned char in = *string; + if(('%' == in) && (alloc > 2) && + ISXDIGIT(string[1]) && ISXDIGIT(string[2])) { + /* this is two hexadecimal digits following a '%' */ + in = (unsigned char)(onehex2dec(string[1]) << 4) | onehex2dec(string[2]); + + string += 3; + alloc -= 3; + } + else { + string++; + alloc--; + } + + if(((ctrl == REJECT_CTRL) && (in < 0x20)) || + ((ctrl == REJECT_ZERO) && (in == 0))) { + Curl_safefree(*ostring); + return CURLE_URL_MALFORMAT; + } + + *ns++ = in; + } + *ns = 0; /* terminate it */ + + if(olen) + /* store output size */ + *olen = ns - *ostring; + + return CURLE_OK; +} + +/* + * Unescapes the given URL escaped string of given length. Returns a + * pointer to a malloced string with length given in *olen. + * If length == 0, the length is assumed to be strlen(string). + * If olen == NULL, no output length is stored. + * 'data' is ignored since 7.82.0. + */ +char *curl_easy_unescape(struct Curl_easy *data, const char *string, + int length, int *olen) +{ + char *str = NULL; + (void)data; + if(length >= 0) { + size_t inputlen = (size_t)length; + size_t outputlen; + CURLcode res = Curl_urldecode(string, inputlen, &str, &outputlen, + REJECT_NADA); + if(res) + return NULL; + + if(olen) { + if(outputlen <= (size_t) INT_MAX) + *olen = curlx_uztosi(outputlen); + else + /* too large to return in an int, fail! */ + Curl_safefree(str); + } + } + return str; +} + +/* For operating systems/environments that use different malloc/free + systems for the app and for this library, we provide a free that uses + the library's memory system */ +void curl_free(void *p) +{ + free(p); +} + +/* + * Curl_hexencode() + * + * Converts binary input to lowercase hex-encoded ASCII output. + * Null-terminated. + */ +void Curl_hexencode(const unsigned char *src, size_t len, /* input length */ + unsigned char *out, size_t olen) /* output buffer size */ +{ + const char *hex = "0123456789abcdef"; + DEBUGASSERT(src && len && (olen >= 3)); + if(src && len && (olen >= 3)) { + while(len-- && (olen >= 3)) { + /* clang-tidy warns on this line without this comment: */ + /* NOLINTNEXTLINE(clang-analyzer-core.UndefinedBinaryOperatorResult) */ + *out++ = hex[(*src & 0xF0)>>4]; + *out++ = hex[*src & 0x0F]; + ++src; + olen -= 2; + } + *out = 0; + } + else if(olen) + *out = 0; +} diff --git a/third_party/curl/lib/escape.h b/third_party/curl/lib/escape.h new file mode 100644 index 0000000..690e417 --- /dev/null +++ b/third_party/curl/lib/escape.h @@ -0,0 +1,44 @@ +#ifndef HEADER_CURL_ESCAPE_H +#define HEADER_CURL_ESCAPE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* Escape and unescape URL encoding in strings. The functions return a new + * allocated string or NULL if an error occurred. */ + +#include "curl_ctype.h" + +enum urlreject { + REJECT_NADA = 2, + REJECT_CTRL, + REJECT_ZERO +}; + +CURLcode Curl_urldecode(const char *string, size_t length, + char **ostring, size_t *olen, + enum urlreject ctrl); + +void Curl_hexencode(const unsigned char *src, size_t len, /* input length */ + unsigned char *out, size_t olen); /* output buffer size */ + +#endif /* HEADER_CURL_ESCAPE_H */ diff --git a/third_party/curl/lib/file.c b/third_party/curl/lib/file.c new file mode 100644 index 0000000..db86022 --- /dev/null +++ b/third_party/curl/lib/file.c @@ -0,0 +1,639 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_FILE + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NET_IF_H +#include +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif + +#ifdef HAVE_SYS_PARAM_H +#include +#endif + +#ifdef HAVE_FCNTL_H +#include +#endif + +#ifdef HAVE_SYS_TYPES_H +#include +#endif + +#ifdef HAVE_DIRENT_H +#include +#endif + +#include "strtoofft.h" +#include "urldata.h" +#include +#include "progress.h" +#include "sendf.h" +#include "escape.h" +#include "file.h" +#include "speedcheck.h" +#include "getinfo.h" +#include "multiif.h" +#include "transfer.h" +#include "url.h" +#include "parsedate.h" /* for the week day and month names */ +#include "warnless.h" +#include "curl_range.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if defined(_WIN32) || defined(MSDOS) || defined(__EMX__) +#define DOS_FILESYSTEM 1 +#elif defined(__amigaos4__) +#define AMIGA_FILESYSTEM 1 +#endif + +#ifdef OPEN_NEEDS_ARG3 +# define open_readonly(p,f) open((p),(f),(0)) +#else +# define open_readonly(p,f) open((p),(f)) +#endif + +/* + * Forward declarations. + */ + +static CURLcode file_do(struct Curl_easy *data, bool *done); +static CURLcode file_done(struct Curl_easy *data, + CURLcode status, bool premature); +static CURLcode file_connect(struct Curl_easy *data, bool *done); +static CURLcode file_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection); +static CURLcode file_setup_connection(struct Curl_easy *data, + struct connectdata *conn); + +/* + * FILE scheme handler. + */ + +const struct Curl_handler Curl_handler_file = { + "file", /* scheme */ + file_setup_connection, /* setup_connection */ + file_do, /* do_it */ + file_done, /* done */ + ZERO_NULL, /* do_more */ + file_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + file_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + 0, /* defport */ + CURLPROTO_FILE, /* protocol */ + CURLPROTO_FILE, /* family */ + PROTOPT_NONETWORK | PROTOPT_NOURLQUERY /* flags */ +}; + + +static CURLcode file_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + (void)conn; + /* allocate the FILE specific struct */ + data->req.p.file = calloc(1, sizeof(struct FILEPROTO)); + if(!data->req.p.file) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +/* + * file_connect() gets called from Curl_protocol_connect() to allow us to + * do protocol-specific actions at connect-time. We emulate a + * connect-then-transfer protocol and "connect" to the file here + */ +static CURLcode file_connect(struct Curl_easy *data, bool *done) +{ + char *real_path; + struct FILEPROTO *file = data->req.p.file; + int fd; +#ifdef DOS_FILESYSTEM + size_t i; + char *actual_path; +#endif + size_t real_path_len; + CURLcode result; + + if(file->path) { + /* already connected. + * the handler->connect_it() is normally only called once, but + * FILE does a special check on setting up the connection which + * calls this explicitly. */ + *done = TRUE; + return CURLE_OK; + } + + result = Curl_urldecode(data->state.up.path, 0, &real_path, + &real_path_len, REJECT_ZERO); + if(result) + return result; + +#ifdef DOS_FILESYSTEM + /* If the first character is a slash, and there's + something that looks like a drive at the beginning of + the path, skip the slash. If we remove the initial + slash in all cases, paths without drive letters end up + relative to the current directory which isn't how + browsers work. + + Some browsers accept | instead of : as the drive letter + separator, so we do too. + + On other platforms, we need the slash to indicate an + absolute pathname. On Windows, absolute paths start + with a drive letter. + */ + actual_path = real_path; + if((actual_path[0] == '/') && + actual_path[1] && + (actual_path[2] == ':' || actual_path[2] == '|')) { + actual_path[2] = ':'; + actual_path++; + real_path_len--; + } + + /* change path separators from '/' to '\\' for DOS, Windows and OS/2 */ + for(i = 0; i < real_path_len; ++i) + if(actual_path[i] == '/') + actual_path[i] = '\\'; + else if(!actual_path[i]) { /* binary zero */ + Curl_safefree(real_path); + return CURLE_URL_MALFORMAT; + } + + fd = open_readonly(actual_path, O_RDONLY|O_BINARY); + file->path = actual_path; +#else + if(memchr(real_path, 0, real_path_len)) { + /* binary zeroes indicate foul play */ + Curl_safefree(real_path); + return CURLE_URL_MALFORMAT; + } + + #ifdef AMIGA_FILESYSTEM + /* + * A leading slash in an AmigaDOS path denotes the parent + * directory, and hence we block this as it is relative. + * Absolute paths start with 'volumename:', so we check for + * this first. Failing that, we treat the path as a real unix + * path, but only if the application was compiled with -lunix. + */ + fd = -1; + file->path = real_path; + + if(real_path[0] == '/') { + extern int __unix_path_semantics; + if(strchr(real_path + 1, ':')) { + /* Amiga absolute path */ + fd = open_readonly(real_path + 1, O_RDONLY); + file->path++; + } + else if(__unix_path_semantics) { + /* -lunix fallback */ + fd = open_readonly(real_path, O_RDONLY); + } + } + #else + fd = open_readonly(real_path, O_RDONLY); + file->path = real_path; + #endif +#endif + Curl_safefree(file->freepath); + file->freepath = real_path; /* free this when done */ + + file->fd = fd; + if(!data->state.upload && (fd == -1)) { + failf(data, "Couldn't open file %s", data->state.up.path); + file_done(data, CURLE_FILE_COULDNT_READ_FILE, FALSE); + return CURLE_FILE_COULDNT_READ_FILE; + } + *done = TRUE; + + return CURLE_OK; +} + +static CURLcode file_done(struct Curl_easy *data, + CURLcode status, bool premature) +{ + struct FILEPROTO *file = data->req.p.file; + (void)status; /* not used */ + (void)premature; /* not used */ + + if(file) { + Curl_safefree(file->freepath); + file->path = NULL; + if(file->fd != -1) + close(file->fd); + file->fd = -1; + } + + return CURLE_OK; +} + +static CURLcode file_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + (void)dead_connection; /* not used */ + (void)conn; + return file_done(data, CURLE_OK, FALSE); +} + +#ifdef DOS_FILESYSTEM +#define DIRSEP '\\' +#else +#define DIRSEP '/' +#endif + +static CURLcode file_upload(struct Curl_easy *data) +{ + struct FILEPROTO *file = data->req.p.file; + const char *dir = strchr(file->path, DIRSEP); + int fd; + int mode; + CURLcode result = CURLE_OK; + char *xfer_ulbuf; + size_t xfer_ulblen; + curl_off_t bytecount = 0; + struct_stat file_stat; + const char *sendbuf; + bool eos = FALSE; + + /* + * Since FILE: doesn't do the full init, we need to provide some extra + * assignments here. + */ + + if(!dir) + return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */ + + if(!dir[1]) + return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */ + +#ifdef O_BINARY +#define MODE_DEFAULT O_WRONLY|O_CREAT|O_BINARY +#else +#define MODE_DEFAULT O_WRONLY|O_CREAT +#endif + + if(data->state.resume_from) + mode = MODE_DEFAULT|O_APPEND; + else + mode = MODE_DEFAULT|O_TRUNC; + + fd = open(file->path, mode, data->set.new_file_perms); + if(fd < 0) { + failf(data, "Can't open %s for writing", file->path); + return CURLE_WRITE_ERROR; + } + + if(-1 != data->state.infilesize) + /* known size of data to "upload" */ + Curl_pgrsSetUploadSize(data, data->state.infilesize); + + /* treat the negative resume offset value as the case of "-" */ + if(data->state.resume_from < 0) { + if(fstat(fd, &file_stat)) { + close(fd); + failf(data, "Can't get the size of %s", file->path); + return CURLE_WRITE_ERROR; + } + data->state.resume_from = (curl_off_t)file_stat.st_size; + } + + result = Curl_multi_xfer_ulbuf_borrow(data, &xfer_ulbuf, &xfer_ulblen); + if(result) + goto out; + + while(!result && !eos) { + size_t nread; + ssize_t nwrite; + size_t readcount; + + result = Curl_client_read(data, xfer_ulbuf, xfer_ulblen, &readcount, &eos); + if(result) + break; + + if(!readcount) + break; + + nread = readcount; + + /* skip bytes before resume point */ + if(data->state.resume_from) { + if((curl_off_t)nread <= data->state.resume_from) { + data->state.resume_from -= nread; + nread = 0; + sendbuf = xfer_ulbuf; + } + else { + sendbuf = xfer_ulbuf + data->state.resume_from; + nread -= (size_t)data->state.resume_from; + data->state.resume_from = 0; + } + } + else + sendbuf = xfer_ulbuf; + + /* write the data to the target */ + nwrite = write(fd, sendbuf, nread); + if((size_t)nwrite != nread) { + result = CURLE_SEND_ERROR; + break; + } + + bytecount += nread; + + Curl_pgrsSetUploadCounter(data, bytecount); + + if(Curl_pgrsUpdate(data)) + result = CURLE_ABORTED_BY_CALLBACK; + else + result = Curl_speedcheck(data, Curl_now()); + } + if(!result && Curl_pgrsUpdate(data)) + result = CURLE_ABORTED_BY_CALLBACK; + +out: + close(fd); + Curl_multi_xfer_ulbuf_release(data, xfer_ulbuf); + + return result; +} + +/* + * file_do() is the protocol-specific function for the do-phase, separated + * from the connect-phase above. Other protocols merely setup the transfer in + * the do-phase, to have it done in the main transfer loop but since some + * platforms we support don't allow select()ing etc on file handles (as + * opposed to sockets) we instead perform the whole do-operation in this + * function. + */ +static CURLcode file_do(struct Curl_easy *data, bool *done) +{ + /* This implementation ignores the host name in conformance with + RFC 1738. Only local files (reachable via the standard file system) + are supported. This means that files on remotely mounted directories + (via NFS, Samba, NT sharing) can be accessed through a file:// URL + */ + CURLcode result = CURLE_OK; + struct_stat statbuf; /* struct_stat instead of struct stat just to allow the + Windows version to have a different struct without + having to redefine the simple word 'stat' */ + curl_off_t expected_size = -1; + bool size_known; + bool fstated = FALSE; + int fd; + struct FILEPROTO *file; + char *xfer_buf; + size_t xfer_blen; + + *done = TRUE; /* unconditionally */ + + if(data->state.upload) + return file_upload(data); + + file = data->req.p.file; + + /* get the fd from the connection phase */ + fd = file->fd; + + /* VMS: This only works reliable for STREAMLF files */ + if(-1 != fstat(fd, &statbuf)) { + if(!S_ISDIR(statbuf.st_mode)) + expected_size = statbuf.st_size; + /* and store the modification time */ + data->info.filetime = statbuf.st_mtime; + fstated = TRUE; + } + + if(fstated && !data->state.range && data->set.timecondition && + !Curl_meets_timecondition(data, data->info.filetime)) + return CURLE_OK; + + if(fstated) { + time_t filetime; + struct tm buffer; + const struct tm *tm = &buffer; + char header[80]; + int headerlen; + char accept_ranges[24]= { "Accept-ranges: bytes\r\n" }; + if(expected_size >= 0) { + headerlen = msnprintf(header, sizeof(header), + "Content-Length: %" CURL_FORMAT_CURL_OFF_T "\r\n", + expected_size); + result = Curl_client_write(data, CLIENTWRITE_HEADER, header, headerlen); + if(result) + return result; + + result = Curl_client_write(data, CLIENTWRITE_HEADER, + accept_ranges, strlen(accept_ranges)); + if(result != CURLE_OK) + return result; + } + + filetime = (time_t)statbuf.st_mtime; + result = Curl_gmtime(filetime, &buffer); + if(result) + return result; + + /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */ + headerlen = msnprintf(header, sizeof(header), + "Last-Modified: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n%s", + Curl_wkday[tm->tm_wday?tm->tm_wday-1:6], + tm->tm_mday, + Curl_month[tm->tm_mon], + tm->tm_year + 1900, + tm->tm_hour, + tm->tm_min, + tm->tm_sec, + data->req.no_body ? "": "\r\n"); + result = Curl_client_write(data, CLIENTWRITE_HEADER, header, headerlen); + if(result) + return result; + /* set the file size to make it available post transfer */ + Curl_pgrsSetDownloadSize(data, expected_size); + if(data->req.no_body) + return result; + } + + /* Check whether file range has been specified */ + result = Curl_range(data); + if(result) + return result; + + /* Adjust the start offset in case we want to get the N last bytes + * of the stream if the filesize could be determined */ + if(data->state.resume_from < 0) { + if(!fstated) { + failf(data, "Can't get the size of file."); + return CURLE_READ_ERROR; + } + data->state.resume_from += (curl_off_t)statbuf.st_size; + } + + if(data->state.resume_from > 0) { + /* We check explicitly if we have a start offset, because + * expected_size may be -1 if we don't know how large the file is, + * in which case we should not adjust it. */ + if(data->state.resume_from <= expected_size) + expected_size -= data->state.resume_from; + else { + failf(data, "failed to resume file:// transfer"); + return CURLE_BAD_DOWNLOAD_RESUME; + } + } + + /* A high water mark has been specified so we obey... */ + if(data->req.maxdownload > 0) + expected_size = data->req.maxdownload; + + if(!fstated || (expected_size <= 0)) + size_known = FALSE; + else + size_known = TRUE; + + /* The following is a shortcut implementation of file reading + this is both more efficient than the former call to download() and + it avoids problems with select() and recv() on file descriptors + in Winsock */ + if(size_known) + Curl_pgrsSetDownloadSize(data, expected_size); + + if(data->state.resume_from) { + if(!S_ISDIR(statbuf.st_mode)) { + if(data->state.resume_from != + lseek(fd, data->state.resume_from, SEEK_SET)) + return CURLE_BAD_DOWNLOAD_RESUME; + } + else { + return CURLE_BAD_DOWNLOAD_RESUME; + } + } + + result = Curl_multi_xfer_buf_borrow(data, &xfer_buf, &xfer_blen); + if(result) + goto out; + + if(!S_ISDIR(statbuf.st_mode)) { + while(!result) { + ssize_t nread; + /* Don't fill a whole buffer if we want less than all data */ + size_t bytestoread; + + if(size_known) { + bytestoread = (expected_size < (curl_off_t)(xfer_blen-1)) ? + curlx_sotouz(expected_size) : (xfer_blen-1); + } + else + bytestoread = xfer_blen-1; + + nread = read(fd, xfer_buf, bytestoread); + + if(nread > 0) + xfer_buf[nread] = 0; + + if(nread <= 0 || (size_known && (expected_size == 0))) + break; + + if(size_known) + expected_size -= nread; + + result = Curl_client_write(data, CLIENTWRITE_BODY, xfer_buf, nread); + if(result) + goto out; + + if(Curl_pgrsUpdate(data)) + result = CURLE_ABORTED_BY_CALLBACK; + else + result = Curl_speedcheck(data, Curl_now()); + if(result) + goto out; + } + } + else { +#ifdef HAVE_OPENDIR + DIR *dir = opendir(file->path); + struct dirent *entry; + + if(!dir) { + result = CURLE_READ_ERROR; + goto out; + } + else { + while((entry = readdir(dir))) { + if(entry->d_name[0] != '.') { + result = Curl_client_write(data, CLIENTWRITE_BODY, + entry->d_name, strlen(entry->d_name)); + if(result) + break; + result = Curl_client_write(data, CLIENTWRITE_BODY, "\n", 1); + if(result) + break; + } + } + closedir(dir); + } +#else + failf(data, "Directory listing not yet implemented on this platform."); + result = CURLE_READ_ERROR; +#endif + } + + if(Curl_pgrsUpdate(data)) + result = CURLE_ABORTED_BY_CALLBACK; + +out: + Curl_multi_xfer_buf_release(data, xfer_buf); + return result; +} + +#endif diff --git a/third_party/curl/lib/file.h b/third_party/curl/lib/file.h new file mode 100644 index 0000000..4565525 --- /dev/null +++ b/third_party/curl/lib/file.h @@ -0,0 +1,42 @@ +#ifndef HEADER_CURL_FILE_H +#define HEADER_CURL_FILE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + + +/**************************************************************************** + * FILE unique setup + ***************************************************************************/ +struct FILEPROTO { + char *path; /* the path we operate on */ + char *freepath; /* pointer to the allocated block we must free, this might + differ from the 'path' pointer */ + int fd; /* open file descriptor to read from! */ +}; + +#ifndef CURL_DISABLE_FILE +extern const struct Curl_handler Curl_handler_file; +#endif + +#endif /* HEADER_CURL_FILE_H */ diff --git a/third_party/curl/lib/fileinfo.c b/third_party/curl/lib/fileinfo.c new file mode 100644 index 0000000..2be3b32 --- /dev/null +++ b/third_party/curl/lib/fileinfo.c @@ -0,0 +1,46 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#ifndef CURL_DISABLE_FTP +#include "strdup.h" +#include "fileinfo.h" +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + +struct fileinfo *Curl_fileinfo_alloc(void) +{ + return calloc(1, sizeof(struct fileinfo)); +} + +void Curl_fileinfo_cleanup(struct fileinfo *finfo) +{ + if(!finfo) + return; + + Curl_dyn_free(&finfo->buf); + free(finfo); +} +#endif diff --git a/third_party/curl/lib/fileinfo.h b/third_party/curl/lib/fileinfo.h new file mode 100644 index 0000000..ce009da --- /dev/null +++ b/third_party/curl/lib/fileinfo.h @@ -0,0 +1,40 @@ +#ifndef HEADER_CURL_FILEINFO_H +#define HEADER_CURL_FILEINFO_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include +#include "llist.h" +#include "dynbuf.h" + +struct fileinfo { + struct curl_fileinfo info; + struct Curl_llist_element list; + struct dynbuf buf; +}; + +struct fileinfo *Curl_fileinfo_alloc(void); +void Curl_fileinfo_cleanup(struct fileinfo *finfo); + +#endif /* HEADER_CURL_FILEINFO_H */ diff --git a/third_party/curl/lib/fopen.c b/third_party/curl/lib/fopen.c new file mode 100644 index 0000000..0bdf2e1 --- /dev/null +++ b/third_party/curl/lib/fopen.c @@ -0,0 +1,158 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_COOKIES) || !defined(CURL_DISABLE_ALTSVC) || \ + !defined(CURL_DISABLE_HSTS) + +#ifdef HAVE_FCNTL_H +#include +#endif + +#include "urldata.h" +#include "rand.h" +#include "fopen.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* + The dirslash() function breaks a null-terminated pathname string into + directory and filename components then returns the directory component up + to, *AND INCLUDING*, a final '/'. If there is no directory in the path, + this instead returns a "" string. + + This function returns a pointer to malloc'ed memory. + + The input path to this function is expected to have a file name part. +*/ + +#ifdef _WIN32 +#define PATHSEP "\\" +#define IS_SEP(x) (((x) == '/') || ((x) == '\\')) +#elif defined(MSDOS) || defined(__EMX__) || defined(OS2) +#define PATHSEP "\\" +#define IS_SEP(x) ((x) == '\\') +#else +#define PATHSEP "/" +#define IS_SEP(x) ((x) == '/') +#endif + +static char *dirslash(const char *path) +{ + size_t n; + struct dynbuf out; + DEBUGASSERT(path); + Curl_dyn_init(&out, CURL_MAX_INPUT_LENGTH); + n = strlen(path); + if(n) { + /* find the rightmost path separator, if any */ + while(n && !IS_SEP(path[n-1])) + --n; + /* skip over all the path separators, if any */ + while(n && IS_SEP(path[n-1])) + --n; + } + if(Curl_dyn_addn(&out, path, n)) + return NULL; + /* if there was a directory, append a single trailing slash */ + if(n && Curl_dyn_addn(&out, PATHSEP, 1)) + return NULL; + return Curl_dyn_ptr(&out); +} + +/* + * Curl_fopen() opens a file for writing with a temp name, to be renamed + * to the final name when completed. If there is an existing file using this + * name at the time of the open, this function will clone the mode from that + * file. if 'tempname' is non-NULL, it needs a rename after the file is + * written. + */ +CURLcode Curl_fopen(struct Curl_easy *data, const char *filename, + FILE **fh, char **tempname) +{ + CURLcode result = CURLE_WRITE_ERROR; + unsigned char randbuf[41]; + char *tempstore = NULL; + struct_stat sb; + int fd = -1; + char *dir = NULL; + *tempname = NULL; + + *fh = fopen(filename, FOPEN_WRITETEXT); + if(!*fh) + goto fail; + if(fstat(fileno(*fh), &sb) == -1 || !S_ISREG(sb.st_mode)) { + return CURLE_OK; + } + fclose(*fh); + *fh = NULL; + + result = Curl_rand_alnum(data, randbuf, sizeof(randbuf)); + if(result) + goto fail; + + dir = dirslash(filename); + if(dir) { + /* The temp file name should not end up too long for the target file + system */ + tempstore = aprintf("%s%s.tmp", dir, randbuf); + free(dir); + } + + if(!tempstore) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + result = CURLE_WRITE_ERROR; +#if (defined(ANDROID) || defined(__ANDROID__)) && \ + (defined(__i386__) || defined(__arm__)) + fd = open(tempstore, O_WRONLY | O_CREAT | O_EXCL, (mode_t)(0600|sb.st_mode)); +#else + fd = open(tempstore, O_WRONLY | O_CREAT | O_EXCL, 0600|sb.st_mode); +#endif + if(fd == -1) + goto fail; + + *fh = fdopen(fd, FOPEN_WRITETEXT); + if(!*fh) + goto fail; + + *tempname = tempstore; + return CURLE_OK; + +fail: + if(fd != -1) { + close(fd); + unlink(tempstore); + } + + free(tempstore); + return result; +} + +#endif /* ! disabled */ diff --git a/third_party/curl/lib/fopen.h b/third_party/curl/lib/fopen.h new file mode 100644 index 0000000..e3a919d --- /dev/null +++ b/third_party/curl/lib/fopen.h @@ -0,0 +1,30 @@ +#ifndef HEADER_CURL_FOPEN_H +#define HEADER_CURL_FOPEN_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +CURLcode Curl_fopen(struct Curl_easy *data, const char *filename, + FILE **fh, char **tempname); + +#endif diff --git a/third_party/curl/lib/formdata.c b/third_party/curl/lib/formdata.c new file mode 100644 index 0000000..d6a1697 --- /dev/null +++ b/third_party/curl/lib/formdata.c @@ -0,0 +1,958 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "formdata.h" +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_FORM_API) + +#if defined(HAVE_LIBGEN_H) && defined(HAVE_BASENAME) +#include +#endif + +#include "urldata.h" /* for struct Curl_easy */ +#include "mime.h" +#include "vtls/vtls.h" +#include "strcase.h" +#include "sendf.h" +#include "strdup.h" +#include "rand.h" +#include "warnless.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +#define HTTPPOST_PTRNAME CURL_HTTPPOST_PTRNAME +#define HTTPPOST_FILENAME CURL_HTTPPOST_FILENAME +#define HTTPPOST_PTRCONTENTS CURL_HTTPPOST_PTRCONTENTS +#define HTTPPOST_READFILE CURL_HTTPPOST_READFILE +#define HTTPPOST_PTRBUFFER CURL_HTTPPOST_PTRBUFFER +#define HTTPPOST_CALLBACK CURL_HTTPPOST_CALLBACK +#define HTTPPOST_BUFFER CURL_HTTPPOST_BUFFER + +/*************************************************************************** + * + * AddHttpPost() + * + * Adds an HttpPost structure to the list, if parent_post is given becomes + * a subpost of parent_post instead of a direct list element. + * + * Returns newly allocated HttpPost on success and NULL if malloc failed. + * + ***************************************************************************/ +static struct curl_httppost * +AddHttpPost(char *name, size_t namelength, + char *value, curl_off_t contentslength, + char *buffer, size_t bufferlength, + char *contenttype, + long flags, + struct curl_slist *contentHeader, + char *showfilename, char *userp, + struct curl_httppost *parent_post, + struct curl_httppost **httppost, + struct curl_httppost **last_post) +{ + struct curl_httppost *post; + if(!namelength && name) + namelength = strlen(name); + if((bufferlength > LONG_MAX) || (namelength > LONG_MAX)) + /* avoid overflow in typecasts below */ + return NULL; + post = calloc(1, sizeof(struct curl_httppost)); + if(post) { + post->name = name; + post->namelength = (long)namelength; + post->contents = value; + post->contentlen = contentslength; + post->buffer = buffer; + post->bufferlength = (long)bufferlength; + post->contenttype = contenttype; + post->contentheader = contentHeader; + post->showfilename = showfilename; + post->userp = userp; + post->flags = flags | CURL_HTTPPOST_LARGE; + } + else + return NULL; + + if(parent_post) { + /* now, point our 'more' to the original 'more' */ + post->more = parent_post->more; + + /* then move the original 'more' to point to ourselves */ + parent_post->more = post; + } + else { + /* make the previous point to this */ + if(*last_post) + (*last_post)->next = post; + else + (*httppost) = post; + + (*last_post) = post; + } + return post; +} + +/*************************************************************************** + * + * AddFormInfo() + * + * Adds a FormInfo structure to the list presented by parent_form_info. + * + * Returns newly allocated FormInfo on success and NULL if malloc failed/ + * parent_form_info is NULL. + * + ***************************************************************************/ +static struct FormInfo *AddFormInfo(char *value, + char *contenttype, + struct FormInfo *parent_form_info) +{ + struct FormInfo *form_info; + form_info = calloc(1, sizeof(struct FormInfo)); + if(!form_info) + return NULL; + if(value) + form_info->value = value; + if(contenttype) + form_info->contenttype = contenttype; + form_info->flags = HTTPPOST_FILENAME; + + if(parent_form_info) { + /* now, point our 'more' to the original 'more' */ + form_info->more = parent_form_info->more; + + /* then move the original 'more' to point to ourselves */ + parent_form_info->more = form_info; + } + + return form_info; +} + +/*************************************************************************** + * + * FormAdd() + * + * Stores a formpost parameter and builds the appropriate linked list. + * + * Has two principal functionalities: using files and byte arrays as + * post parts. Byte arrays are either copied or just the pointer is stored + * (as the user requests) while for files only the filename and not the + * content is stored. + * + * While you may have only one byte array for each name, multiple filenames + * are allowed (and because of this feature CURLFORM_END is needed after + * using CURLFORM_FILE). + * + * Examples: + * + * Simple name/value pair with copied contents: + * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name", + * CURLFORM_COPYCONTENTS, "value", CURLFORM_END); + * + * name/value pair where only the content pointer is remembered: + * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name", + * CURLFORM_PTRCONTENTS, ptr, CURLFORM_CONTENTSLENGTH, 10, CURLFORM_END); + * (if CURLFORM_CONTENTSLENGTH is missing strlen () is used) + * + * storing a filename (CONTENTTYPE is optional!): + * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name", + * CURLFORM_FILE, "filename1", CURLFORM_CONTENTTYPE, "plain/text", + * CURLFORM_END); + * + * storing multiple filenames: + * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name", + * CURLFORM_FILE, "filename1", CURLFORM_FILE, "filename2", CURLFORM_END); + * + * 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 an 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 + * + ***************************************************************************/ + +static +CURLFORMcode FormAdd(struct curl_httppost **httppost, + struct curl_httppost **last_post, + va_list params) +{ + struct FormInfo *first_form, *current_form, *form = NULL; + CURLFORMcode return_value = CURL_FORMADD_OK; + const char *prevtype = NULL; + struct curl_httppost *post = NULL; + CURLformoption option; + struct curl_forms *forms = NULL; + char *array_value = NULL; /* value read from an array */ + + /* This is a state variable, that if TRUE means that we're parsing an + array that we got passed to us. If FALSE we're parsing the input + va_list arguments. */ + bool array_state = FALSE; + + /* + * We need to allocate the first struct to fill in. + */ + first_form = calloc(1, sizeof(struct FormInfo)); + if(!first_form) + return CURL_FORMADD_MEMORY; + + current_form = first_form; + + /* + * Loop through all the options set. Break if we have an error to report. + */ + while(return_value == CURL_FORMADD_OK) { + + /* first see if we have more parts of the array param */ + if(array_state && forms) { + /* get the upcoming option from the given array */ + option = forms->option; + array_value = (char *)forms->value; + + forms++; /* advance this to next entry */ + if(CURLFORM_END == option) { + /* end of array state */ + array_state = FALSE; + continue; + } + } + else { + /* This is not array-state, get next option. This gets an 'int' with + va_arg() because CURLformoption might be a smaller type than int and + might cause compiler warnings and wrong behavior. */ + option = (CURLformoption)va_arg(params, int); + if(CURLFORM_END == option) + break; + } + + switch(option) { + case CURLFORM_ARRAY: + if(array_state) + /* we don't support an array from within an array */ + return_value = CURL_FORMADD_ILLEGAL_ARRAY; + else { + forms = va_arg(params, struct curl_forms *); + if(forms) + array_state = TRUE; + else + return_value = CURL_FORMADD_NULL; + } + break; + + /* + * Set the Name property. + */ + case CURLFORM_PTRNAME: + current_form->flags |= HTTPPOST_PTRNAME; /* fall through */ + + FALLTHROUGH(); + case CURLFORM_COPYNAME: + if(current_form->name) + return_value = CURL_FORMADD_OPTION_TWICE; + else { + char *name = array_state? + array_value:va_arg(params, char *); + if(name) + current_form->name = name; /* store for the moment */ + else + return_value = CURL_FORMADD_NULL; + } + break; + case CURLFORM_NAMELENGTH: + if(current_form->namelength) + return_value = CURL_FORMADD_OPTION_TWICE; + else + current_form->namelength = + array_state?(size_t)array_value:(size_t)va_arg(params, long); + break; + + /* + * Set the contents property. + */ + case CURLFORM_PTRCONTENTS: + current_form->flags |= HTTPPOST_PTRCONTENTS; + FALLTHROUGH(); + case CURLFORM_COPYCONTENTS: + if(current_form->value) + return_value = CURL_FORMADD_OPTION_TWICE; + else { + char *value = + array_state?array_value:va_arg(params, char *); + if(value) + current_form->value = value; /* store for the moment */ + else + return_value = CURL_FORMADD_NULL; + } + break; + case CURLFORM_CONTENTSLENGTH: + current_form->contentslength = + array_state?(size_t)array_value:(size_t)va_arg(params, long); + break; + + case CURLFORM_CONTENTLEN: + current_form->flags |= CURL_HTTPPOST_LARGE; + current_form->contentslength = + array_state?(curl_off_t)(size_t)array_value:va_arg(params, curl_off_t); + break; + + /* Get contents from a given file name */ + case CURLFORM_FILECONTENT: + if(current_form->flags & (HTTPPOST_PTRCONTENTS|HTTPPOST_READFILE)) + return_value = CURL_FORMADD_OPTION_TWICE; + else { + const char *filename = array_state? + array_value:va_arg(params, char *); + if(filename) { + current_form->value = strdup(filename); + if(!current_form->value) + return_value = CURL_FORMADD_MEMORY; + else { + current_form->flags |= HTTPPOST_READFILE; + current_form->value_alloc = TRUE; + } + } + else + return_value = CURL_FORMADD_NULL; + } + break; + + /* We upload a file */ + case CURLFORM_FILE: + { + const char *filename = array_state?array_value: + va_arg(params, char *); + + if(current_form->value) { + if(current_form->flags & HTTPPOST_FILENAME) { + if(filename) { + char *fname = strdup(filename); + if(!fname) + return_value = CURL_FORMADD_MEMORY; + else { + form = AddFormInfo(fname, NULL, current_form); + if(!form) { + free(fname); + return_value = CURL_FORMADD_MEMORY; + } + else { + form->value_alloc = TRUE; + current_form = form; + form = NULL; + } + } + } + else + return_value = CURL_FORMADD_NULL; + } + else + return_value = CURL_FORMADD_OPTION_TWICE; + } + else { + if(filename) { + current_form->value = strdup(filename); + if(!current_form->value) + return_value = CURL_FORMADD_MEMORY; + else { + current_form->flags |= HTTPPOST_FILENAME; + current_form->value_alloc = TRUE; + } + } + else + return_value = CURL_FORMADD_NULL; + } + break; + } + + case CURLFORM_BUFFERPTR: + current_form->flags |= HTTPPOST_PTRBUFFER|HTTPPOST_BUFFER; + if(current_form->buffer) + return_value = CURL_FORMADD_OPTION_TWICE; + else { + char *buffer = + array_state?array_value:va_arg(params, char *); + if(buffer) { + current_form->buffer = buffer; /* store for the moment */ + current_form->value = buffer; /* make it non-NULL to be accepted + as fine */ + } + else + return_value = CURL_FORMADD_NULL; + } + break; + + case CURLFORM_BUFFERLENGTH: + if(current_form->bufferlength) + return_value = CURL_FORMADD_OPTION_TWICE; + else + current_form->bufferlength = + array_state?(size_t)array_value:(size_t)va_arg(params, long); + break; + + case CURLFORM_STREAM: + current_form->flags |= HTTPPOST_CALLBACK; + if(current_form->userp) + return_value = CURL_FORMADD_OPTION_TWICE; + else { + char *userp = + array_state?array_value:va_arg(params, char *); + if(userp) { + current_form->userp = userp; + current_form->value = userp; /* this isn't strictly true but we + derive a value from this later on + and we need this non-NULL to be + accepted as a fine form part */ + } + else + return_value = CURL_FORMADD_NULL; + } + break; + + case CURLFORM_CONTENTTYPE: + { + const char *contenttype = + array_state?array_value:va_arg(params, char *); + if(current_form->contenttype) { + if(current_form->flags & HTTPPOST_FILENAME) { + if(contenttype) { + char *type = strdup(contenttype); + if(!type) + return_value = CURL_FORMADD_MEMORY; + else { + form = AddFormInfo(NULL, type, current_form); + if(!form) { + free(type); + return_value = CURL_FORMADD_MEMORY; + } + else { + form->contenttype_alloc = TRUE; + current_form = form; + form = NULL; + } + } + } + else + return_value = CURL_FORMADD_NULL; + } + else + return_value = CURL_FORMADD_OPTION_TWICE; + } + else { + if(contenttype) { + current_form->contenttype = strdup(contenttype); + if(!current_form->contenttype) + return_value = CURL_FORMADD_MEMORY; + else + current_form->contenttype_alloc = TRUE; + } + else + return_value = CURL_FORMADD_NULL; + } + break; + } + case CURLFORM_CONTENTHEADER: + { + /* this "cast increases required alignment of target type" but + we consider it OK anyway */ + struct curl_slist *list = array_state? + (struct curl_slist *)(void *)array_value: + va_arg(params, struct curl_slist *); + + if(current_form->contentheader) + return_value = CURL_FORMADD_OPTION_TWICE; + else + current_form->contentheader = list; + + break; + } + case CURLFORM_FILENAME: + case CURLFORM_BUFFER: + { + const char *filename = array_state?array_value: + va_arg(params, char *); + if(current_form->showfilename) + return_value = CURL_FORMADD_OPTION_TWICE; + else { + current_form->showfilename = strdup(filename); + if(!current_form->showfilename) + return_value = CURL_FORMADD_MEMORY; + else + current_form->showfilename_alloc = TRUE; + } + break; + } + default: + return_value = CURL_FORMADD_UNKNOWN_OPTION; + break; + } + } + + if(CURL_FORMADD_OK != return_value) { + /* On error, free allocated fields for all nodes of the FormInfo linked + list without deallocating nodes. List nodes are deallocated later on */ + struct FormInfo *ptr; + for(ptr = first_form; ptr != NULL; ptr = ptr->more) { + if(ptr->name_alloc) { + Curl_safefree(ptr->name); + ptr->name_alloc = FALSE; + } + if(ptr->value_alloc) { + Curl_safefree(ptr->value); + ptr->value_alloc = FALSE; + } + if(ptr->contenttype_alloc) { + Curl_safefree(ptr->contenttype); + ptr->contenttype_alloc = FALSE; + } + if(ptr->showfilename_alloc) { + Curl_safefree(ptr->showfilename); + ptr->showfilename_alloc = FALSE; + } + } + } + + if(CURL_FORMADD_OK == return_value) { + /* go through the list, check for completeness and if everything is + * alright add the HttpPost item otherwise set return_value accordingly */ + + post = NULL; + for(form = first_form; + form != NULL; + form = form->more) { + if(((!form->name || !form->value) && !post) || + ( (form->contentslength) && + (form->flags & HTTPPOST_FILENAME) ) || + ( (form->flags & HTTPPOST_FILENAME) && + (form->flags & HTTPPOST_PTRCONTENTS) ) || + + ( (!form->buffer) && + (form->flags & HTTPPOST_BUFFER) && + (form->flags & HTTPPOST_PTRBUFFER) ) || + + ( (form->flags & HTTPPOST_READFILE) && + (form->flags & HTTPPOST_PTRCONTENTS) ) + ) { + return_value = CURL_FORMADD_INCOMPLETE; + break; + } + if(((form->flags & HTTPPOST_FILENAME) || + (form->flags & HTTPPOST_BUFFER)) && + !form->contenttype) { + char *f = (form->flags & HTTPPOST_BUFFER)? + form->showfilename : form->value; + char const *type; + type = Curl_mime_contenttype(f); + if(!type) + type = prevtype; + if(!type) + type = FILE_CONTENTTYPE_DEFAULT; + + /* our contenttype is missing */ + form->contenttype = strdup(type); + if(!form->contenttype) { + return_value = CURL_FORMADD_MEMORY; + break; + } + form->contenttype_alloc = TRUE; + } + if(form->name && form->namelength) { + /* Name should not contain nul bytes. */ + size_t i; + for(i = 0; i < form->namelength; i++) + if(!form->name[i]) { + return_value = CURL_FORMADD_NULL; + break; + } + if(return_value != CURL_FORMADD_OK) + break; + } + if(!(form->flags & HTTPPOST_PTRNAME) && + (form == first_form) ) { + /* Note that there's small risk that form->name is NULL here if the + app passed in a bad combo, so we better check for that first. */ + if(form->name) { + /* copy name (without strdup; possibly not null-terminated) */ + form->name = Curl_memdup0(form->name, form->namelength? + form->namelength: + strlen(form->name)); + } + if(!form->name) { + return_value = CURL_FORMADD_MEMORY; + break; + } + form->name_alloc = TRUE; + } + if(!(form->flags & (HTTPPOST_FILENAME | HTTPPOST_READFILE | + HTTPPOST_PTRCONTENTS | HTTPPOST_PTRBUFFER | + HTTPPOST_CALLBACK)) && form->value) { + /* copy value (without strdup; possibly contains null characters) */ + size_t clen = (size_t) form->contentslength; + if(!clen) + clen = strlen(form->value) + 1; + + form->value = Curl_memdup(form->value, clen); + + if(!form->value) { + return_value = CURL_FORMADD_MEMORY; + break; + } + form->value_alloc = TRUE; + } + post = AddHttpPost(form->name, form->namelength, + form->value, form->contentslength, + form->buffer, form->bufferlength, + form->contenttype, form->flags, + form->contentheader, form->showfilename, + form->userp, + post, httppost, + last_post); + + if(!post) { + return_value = CURL_FORMADD_MEMORY; + break; + } + + if(form->contenttype) + prevtype = form->contenttype; + } + if(CURL_FORMADD_OK != return_value) { + /* On error, free allocated fields for nodes of the FormInfo linked + list which are not already owned by the httppost linked list + without deallocating nodes. List nodes are deallocated later on */ + struct FormInfo *ptr; + for(ptr = form; ptr != NULL; ptr = ptr->more) { + if(ptr->name_alloc) { + Curl_safefree(ptr->name); + ptr->name_alloc = FALSE; + } + if(ptr->value_alloc) { + Curl_safefree(ptr->value); + ptr->value_alloc = FALSE; + } + if(ptr->contenttype_alloc) { + Curl_safefree(ptr->contenttype); + ptr->contenttype_alloc = FALSE; + } + if(ptr->showfilename_alloc) { + Curl_safefree(ptr->showfilename); + ptr->showfilename_alloc = FALSE; + } + } + } + } + + /* Always deallocate FormInfo linked list nodes without touching node + fields given that these have either been deallocated or are owned + now by the httppost linked list */ + while(first_form) { + struct FormInfo *ptr = first_form->more; + free(first_form); + first_form = ptr; + } + + return return_value; +} + +/* + * curl_formadd() is a public API to add a section to the multipart formpost. + * + * @unittest: 1308 + */ + +CURLFORMcode curl_formadd(struct curl_httppost **httppost, + struct curl_httppost **last_post, + ...) +{ + va_list arg; + CURLFORMcode result; + va_start(arg, last_post); + result = FormAdd(httppost, last_post, arg); + va_end(arg); + return result; +} + +/* + * curl_formget() + * Serialize a curl_httppost struct. + * Returns 0 on success. + * + * @unittest: 1308 + */ +int curl_formget(struct curl_httppost *form, void *arg, + curl_formget_callback append) +{ + CURLcode result; + curl_mimepart toppart; + + Curl_mime_initpart(&toppart); /* default form is empty */ + result = Curl_getformdata(NULL, &toppart, form, NULL); + if(!result) + result = Curl_mime_prepare_headers(NULL, &toppart, "multipart/form-data", + NULL, MIMESTRATEGY_FORM); + + while(!result) { + char buffer[8192]; + size_t nread = Curl_mime_read(buffer, 1, sizeof(buffer), &toppart); + + if(!nread) + break; + + if(nread > sizeof(buffer) || append(arg, buffer, nread) != nread) { + result = CURLE_READ_ERROR; + if(nread == CURL_READFUNC_ABORT) + result = CURLE_ABORTED_BY_CALLBACK; + } + } + + Curl_mime_cleanpart(&toppart); + return (int) result; +} + +/* + * curl_formfree() is an external function to free up a whole form post + * chain + */ +void curl_formfree(struct curl_httppost *form) +{ + struct curl_httppost *next; + + if(!form) + /* no form to free, just get out of this */ + return; + + do { + next = form->next; /* the following form line */ + + /* recurse to sub-contents */ + curl_formfree(form->more); + + if(!(form->flags & HTTPPOST_PTRNAME)) + free(form->name); /* free the name */ + if(!(form->flags & + (HTTPPOST_PTRCONTENTS|HTTPPOST_BUFFER|HTTPPOST_CALLBACK)) + ) + free(form->contents); /* free the contents */ + free(form->contenttype); /* free the content type */ + free(form->showfilename); /* free the faked file name */ + free(form); /* free the struct */ + form = next; + } while(form); /* continue */ +} + + +/* Set mime part name, taking care of non null-terminated name string. */ +static CURLcode setname(curl_mimepart *part, const char *name, size_t len) +{ + char *zname; + CURLcode res; + + if(!name || !len) + return curl_mime_name(part, name); + zname = Curl_memdup0(name, len); + if(!zname) + return CURLE_OUT_OF_MEMORY; + res = curl_mime_name(part, zname); + free(zname); + return res; +} + +/* wrap call to fseeko so it matches the calling convention of callback */ +static int fseeko_wrapper(void *stream, curl_off_t offset, int whence) +{ +#if defined(HAVE_FSEEKO) && defined(HAVE_DECL_FSEEKO) + return fseeko(stream, (off_t)offset, whence); +#elif defined(HAVE__FSEEKI64) + return _fseeki64(stream, (__int64)offset, whence); +#else + if(offset > LONG_MAX) + return -1; + return fseek(stream, (long)offset, whence); +#endif +} + +/* + * Curl_getformdata() converts a linked list of "meta data" into a mime + * structure. The input list is in 'post', while the output is stored in + * mime part at '*finalform'. + * + * This function will not do a failf() for the potential memory failures but + * should for all other errors it spots. Just note that this function MAY get + * a NULL pointer in the 'data' argument. + */ + +CURLcode Curl_getformdata(struct Curl_easy *data, + curl_mimepart *finalform, + struct curl_httppost *post, + curl_read_callback fread_func) +{ + CURLcode result = CURLE_OK; + curl_mime *form = NULL; + curl_mimepart *part; + struct curl_httppost *file; + + Curl_mime_cleanpart(finalform); /* default form is empty */ + + if(!post) + return result; /* no input => no output! */ + + form = curl_mime_init(data); + if(!form) + result = CURLE_OUT_OF_MEMORY; + + if(!result) + result = curl_mime_subparts(finalform, form); + + /* Process each top part. */ + for(; !result && post; post = post->next) { + /* If we have more than a file here, create a mime subpart and fill it. */ + curl_mime *multipart = form; + if(post->more) { + part = curl_mime_addpart(form); + if(!part) + result = CURLE_OUT_OF_MEMORY; + if(!result) + result = setname(part, post->name, post->namelength); + if(!result) { + multipart = curl_mime_init(data); + if(!multipart) + result = CURLE_OUT_OF_MEMORY; + } + if(!result) + result = curl_mime_subparts(part, multipart); + } + + /* Generate all the part contents. */ + for(file = post; !result && file; file = file->more) { + /* Create the part. */ + part = curl_mime_addpart(multipart); + if(!part) + result = CURLE_OUT_OF_MEMORY; + + /* Set the headers. */ + if(!result) + result = curl_mime_headers(part, file->contentheader, 0); + + /* Set the content type. */ + if(!result && file->contenttype) + result = curl_mime_type(part, file->contenttype); + + /* Set field name. */ + if(!result && !post->more) + result = setname(part, post->name, post->namelength); + + /* Process contents. */ + if(!result) { + curl_off_t clen = post->contentslength; + + if(post->flags & CURL_HTTPPOST_LARGE) + clen = post->contentlen; + + if(post->flags & (HTTPPOST_FILENAME | HTTPPOST_READFILE)) { + if(!strcmp(file->contents, "-")) { + /* There are a few cases where the code below won't work; in + particular, freopen(stdin) by the caller is not guaranteed + to result as expected. This feature has been kept for backward + compatibility: use of "-" pseudo file name should be avoided. */ + result = curl_mime_data_cb(part, (curl_off_t) -1, + (curl_read_callback) fread, + fseeko_wrapper, + NULL, (void *) stdin); + } + else + result = curl_mime_filedata(part, file->contents); + if(!result && (post->flags & HTTPPOST_READFILE)) + result = curl_mime_filename(part, NULL); + } + else if(post->flags & HTTPPOST_BUFFER) + result = curl_mime_data(part, post->buffer, + post->bufferlength? post->bufferlength: -1); + else if(post->flags & HTTPPOST_CALLBACK) { + /* the contents should be read with the callback and the size is set + with the contentslength */ + if(!clen) + clen = -1; + result = curl_mime_data_cb(part, clen, + fread_func, NULL, NULL, post->userp); + } + else { + size_t uclen; + if(!clen) + uclen = CURL_ZERO_TERMINATED; + else + uclen = (size_t)clen; + result = curl_mime_data(part, post->contents, uclen); + } + } + + /* Set fake file name. */ + if(!result && post->showfilename) + if(post->more || (post->flags & (HTTPPOST_FILENAME | HTTPPOST_BUFFER | + HTTPPOST_CALLBACK))) + result = curl_mime_filename(part, post->showfilename); + } + } + + if(result) + Curl_mime_cleanpart(finalform); + + return result; +} + +#else +/* if disabled */ +CURLFORMcode curl_formadd(struct curl_httppost **httppost, + struct curl_httppost **last_post, + ...) +{ + (void)httppost; + (void)last_post; + return CURL_FORMADD_DISABLED; +} + +int curl_formget(struct curl_httppost *form, void *arg, + curl_formget_callback append) +{ + (void) form; + (void) arg; + (void) append; + return CURL_FORMADD_DISABLED; +} + +void curl_formfree(struct curl_httppost *form) +{ + (void)form; + /* Nothing to do. */ +} + +#endif /* if disabled */ diff --git a/third_party/curl/lib/formdata.h b/third_party/curl/lib/formdata.h new file mode 100644 index 0000000..af46624 --- /dev/null +++ b/third_party/curl/lib/formdata.h @@ -0,0 +1,59 @@ +#ifndef HEADER_CURL_FORMDATA_H +#define HEADER_CURL_FORMDATA_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_FORM_API + +/* used by FormAdd for temporary storage */ +struct FormInfo { + char *name; + size_t namelength; + char *value; + curl_off_t contentslength; + char *contenttype; + long flags; + char *buffer; /* pointer to existing buffer used for file upload */ + size_t bufferlength; + char *showfilename; /* The file name to show. If not set, the actual + file name will be used */ + char *userp; /* pointer for the read callback */ + struct curl_slist *contentheader; + struct FormInfo *more; + bool name_alloc; + bool value_alloc; + bool contenttype_alloc; + bool showfilename_alloc; +}; + +CURLcode Curl_getformdata(struct Curl_easy *data, + curl_mimepart *, + struct curl_httppost *post, + curl_read_callback fread_func); +#endif /* CURL_DISABLE_FORM_API */ + + +#endif /* HEADER_CURL_FORMDATA_H */ diff --git a/third_party/curl/lib/ftp.c b/third_party/curl/lib/ftp.c new file mode 100644 index 0000000..b88d4d7 --- /dev/null +++ b/third_party/curl/lib/ftp.c @@ -0,0 +1,4584 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_FTP + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef __VMS +#include +#include +#endif + +#include +#include "urldata.h" +#include "sendf.h" +#include "if2ip.h" +#include "hostip.h" +#include "progress.h" +#include "transfer.h" +#include "escape.h" +#include "http.h" /* for HTTP proxy tunnel stuff */ +#include "ftp.h" +#include "fileinfo.h" +#include "ftplistparser.h" +#include "curl_range.h" +#include "curl_krb5.h" +#include "strtoofft.h" +#include "strcase.h" +#include "vtls/vtls.h" +#include "cfilters.h" +#include "cf-socket.h" +#include "connect.h" +#include "strerror.h" +#include "inet_ntop.h" +#include "inet_pton.h" +#include "select.h" +#include "parsedate.h" /* for the week day and month names */ +#include "sockaddr.h" /* required for Curl_sockaddr_storage */ +#include "multiif.h" +#include "url.h" +#include "speedcheck.h" +#include "warnless.h" +#include "http_proxy.h" +#include "socks.h" +#include "strdup.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#ifndef NI_MAXHOST +#define NI_MAXHOST 1025 +#endif +#ifndef INET_ADDRSTRLEN +#define INET_ADDRSTRLEN 16 +#endif + +/* macro to check for a three-digit ftp status code at the start of the + given string */ +#define STATUSCODE(line) (ISDIGIT(line[0]) && ISDIGIT(line[1]) && \ + ISDIGIT(line[2])) + +/* macro to check for the last line in an FTP server response */ +#define LASTLINE(line) (STATUSCODE(line) && (' ' == line[3])) + +#ifdef CURL_DISABLE_VERBOSE_STRINGS +#define ftp_pasv_verbose(a,b,c,d) Curl_nop_stmt +#define FTP_CSTATE(c) "" +#define FTP_DSTATE(d) "" +#else /* CURL_DISABLE_VERBOSE_STRINGS */ + /* for tracing purposes */ +static const char * const ftp_state_names[]={ + "STOP", + "WAIT220", + "AUTH", + "USER", + "PASS", + "ACCT", + "PBSZ", + "PROT", + "CCC", + "PWD", + "SYST", + "NAMEFMT", + "QUOTE", + "RETR_PREQUOTE", + "STOR_PREQUOTE", + "POSTQUOTE", + "CWD", + "MKD", + "MDTM", + "TYPE", + "LIST_TYPE", + "RETR_TYPE", + "STOR_TYPE", + "SIZE", + "RETR_SIZE", + "STOR_SIZE", + "REST", + "RETR_REST", + "PORT", + "PRET", + "PASV", + "LIST", + "RETR", + "STOR", + "QUIT" +}; +#define FTP_CSTATE(c) ((c)? ftp_state_names[(c)->proto.ftpc.state] : "???") +#define FTP_DSTATE(d) (((d) && (d)->conn)? \ + ftp_state_names[(d)->conn->proto.ftpc.state] : "???") + +#endif /* !CURL_DISABLE_VERBOSE_STRINGS */ + +/* This is the ONLY way to change FTP state! */ +static void _ftp_state(struct Curl_easy *data, + ftpstate newstate +#ifdef DEBUGBUILD + , int lineno +#endif + ) +{ + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = &conn->proto.ftpc; + +#if defined(CURL_DISABLE_VERBOSE_STRINGS) +#ifdef DEBUGBUILD + (void)lineno; +#endif +#else /* CURL_DISABLE_VERBOSE_STRINGS */ + if(ftpc->state != newstate) +#ifdef DEBUGBUILD + CURL_TRC_FTP(data, "[%s] -> [%s] (line %d)", FTP_DSTATE(data), + ftp_state_names[newstate], lineno); +#else + CURL_TRC_FTP(data, "[%s] -> [%s]", FTP_DSTATE(data), + ftp_state_names[newstate]); +#endif +#endif /* !CURL_DISABLE_VERBOSE_STRINGS */ + + ftpc->state = newstate; +} + + +/* Local API functions */ +#ifndef DEBUGBUILD +#define ftp_state(x,y) _ftp_state(x,y) +#else /* !DEBUGBUILD */ +#define ftp_state(x,y) _ftp_state(x,y,__LINE__) +#endif /* DEBUGBUILD */ + +static CURLcode ftp_sendquote(struct Curl_easy *data, + struct connectdata *conn, + struct curl_slist *quote); +static CURLcode ftp_quit(struct Curl_easy *data, struct connectdata *conn); +static CURLcode ftp_parse_url_path(struct Curl_easy *data); +static CURLcode ftp_regular_transfer(struct Curl_easy *data, bool *done); +#ifndef CURL_DISABLE_VERBOSE_STRINGS +static void ftp_pasv_verbose(struct Curl_easy *data, + struct Curl_addrinfo *ai, + char *newhost, /* ascii version */ + int port); +#endif +static CURLcode ftp_state_prepare_transfer(struct Curl_easy *data); +static CURLcode ftp_state_mdtm(struct Curl_easy *data); +static CURLcode ftp_state_quote(struct Curl_easy *data, + bool init, ftpstate instate); +static CURLcode ftp_nb_type(struct Curl_easy *data, + struct connectdata *conn, + bool ascii, ftpstate newstate); +static int ftp_need_type(struct connectdata *conn, + bool ascii); +static CURLcode ftp_do(struct Curl_easy *data, bool *done); +static CURLcode ftp_done(struct Curl_easy *data, + CURLcode, bool premature); +static CURLcode ftp_connect(struct Curl_easy *data, bool *done); +static CURLcode ftp_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead_connection); +static CURLcode ftp_do_more(struct Curl_easy *data, int *completed); +static CURLcode ftp_multi_statemach(struct Curl_easy *data, bool *done); +static int ftp_getsock(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t *socks); +static int ftp_domore_getsock(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *socks); +static CURLcode ftp_doing(struct Curl_easy *data, + bool *dophase_done); +static CURLcode ftp_setup_connection(struct Curl_easy *data, + struct connectdata *conn); +static CURLcode init_wc_data(struct Curl_easy *data); +static CURLcode wc_statemach(struct Curl_easy *data); +static void wc_data_dtor(void *ptr); +static CURLcode ftp_state_retr(struct Curl_easy *data, curl_off_t filesize); +static CURLcode ftp_readresp(struct Curl_easy *data, + int sockindex, + struct pingpong *pp, + int *ftpcode, + size_t *size); +static CURLcode ftp_dophase_done(struct Curl_easy *data, + bool connected); + +/* + * FTP protocol handler. + */ + +const struct Curl_handler Curl_handler_ftp = { + "ftp", /* scheme */ + ftp_setup_connection, /* setup_connection */ + ftp_do, /* do_it */ + ftp_done, /* done */ + ftp_do_more, /* do_more */ + ftp_connect, /* connect_it */ + ftp_multi_statemach, /* connecting */ + ftp_doing, /* doing */ + ftp_getsock, /* proto_getsock */ + ftp_getsock, /* doing_getsock */ + ftp_domore_getsock, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ftp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_FTP, /* defport */ + CURLPROTO_FTP, /* protocol */ + CURLPROTO_FTP, /* family */ + PROTOPT_DUAL | PROTOPT_CLOSEACTION | PROTOPT_NEEDSPWD | + PROTOPT_NOURLQUERY | PROTOPT_PROXY_AS_HTTP | + PROTOPT_WILDCARD /* flags */ +}; + + +#ifdef USE_SSL +/* + * FTPS protocol handler. + */ + +const struct Curl_handler Curl_handler_ftps = { + "ftps", /* scheme */ + ftp_setup_connection, /* setup_connection */ + ftp_do, /* do_it */ + ftp_done, /* done */ + ftp_do_more, /* do_more */ + ftp_connect, /* connect_it */ + ftp_multi_statemach, /* connecting */ + ftp_doing, /* doing */ + ftp_getsock, /* proto_getsock */ + ftp_getsock, /* doing_getsock */ + ftp_domore_getsock, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ftp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_FTPS, /* defport */ + CURLPROTO_FTPS, /* protocol */ + CURLPROTO_FTP, /* family */ + PROTOPT_SSL | PROTOPT_DUAL | PROTOPT_CLOSEACTION | + PROTOPT_NEEDSPWD | PROTOPT_NOURLQUERY | PROTOPT_WILDCARD /* flags */ +}; +#endif + +static void close_secondarysocket(struct Curl_easy *data, + struct connectdata *conn) +{ + CURL_TRC_FTP(data, "[%s] closing DATA connection", FTP_DSTATE(data)); + Curl_conn_close(data, SECONDARYSOCKET); + Curl_conn_cf_discard_all(data, conn, SECONDARYSOCKET); +} + +/* + * NOTE: back in the old days, we added code in the FTP code that made NOBODY + * requests on files respond with headers passed to the client/stdout that + * looked like HTTP ones. + * + * This approach is not very elegant, it causes confusion and is error-prone. + * It is subject for removal at the next (or at least a future) soname bump. + * Until then you can test the effects of the removal by undefining the + * following define named CURL_FTP_HTTPSTYLE_HEAD. + */ +#define CURL_FTP_HTTPSTYLE_HEAD 1 + +static void freedirs(struct ftp_conn *ftpc) +{ + if(ftpc->dirs) { + int i; + for(i = 0; i < ftpc->dirdepth; i++) { + free(ftpc->dirs[i]); + ftpc->dirs[i] = NULL; + } + free(ftpc->dirs); + ftpc->dirs = NULL; + ftpc->dirdepth = 0; + } + Curl_safefree(ftpc->file); + + /* no longer of any use */ + Curl_safefree(ftpc->newhost); +} + +#ifdef CURL_DO_LINEEND_CONV +/*********************************************************************** + * + * Lineend Conversions + * On ASCII transfers, e.g. directory listings, we might get lines + * ending in '\r\n' and we prefer just '\n'. + * We might also get a lonely '\r' which we convert into a '\n'. + */ +struct ftp_cw_lc_ctx { + struct Curl_cwriter super; + bool newline_pending; +}; + +static CURLcode ftp_cw_lc_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t blen) +{ + static const char nl = '\n'; + struct ftp_cw_lc_ctx *ctx = writer->ctx; + + if(!(type & CLIENTWRITE_BODY) || + data->conn->proto.ftpc.transfertype != 'A') + return Curl_cwriter_write(data, writer->next, type, buf, blen); + + /* ASCII mode BODY data, convert lineends */ + while(blen) { + /* do not pass EOS when writing parts */ + int chunk_type = (type & ~CLIENTWRITE_EOS); + const char *cp; + size_t chunk_len; + CURLcode result; + + if(ctx->newline_pending) { + if(buf[0] != '\n') { + /* previous chunk ended in '\r' and we do not see a '\n' in this one, + * need to write a newline. */ + result = Curl_cwriter_write(data, writer->next, chunk_type, &nl, 1); + if(result) + return result; + } + /* either we just wrote the newline or it is part of the next + * chunk of bytes we write. */ + data->state.crlf_conversions++; + ctx->newline_pending = FALSE; + } + + cp = memchr(buf, '\r', blen); + if(!cp) + break; + + /* write the bytes before the '\r', excluding the '\r' */ + chunk_len = cp - buf; + if(chunk_len) { + result = Curl_cwriter_write(data, writer->next, chunk_type, + buf, chunk_len); + if(result) + return result; + } + /* skip the '\r', we now have a newline pending */ + buf = cp + 1; + blen = blen - chunk_len - 1; + ctx->newline_pending = TRUE; + } + + /* Any remaining data does not contain a '\r' */ + if(blen) { + DEBUGASSERT(!ctx->newline_pending); + return Curl_cwriter_write(data, writer->next, type, buf, blen); + } + else if(type & CLIENTWRITE_EOS) { + /* EndOfStream, if we have a trailing cr, now is the time to write it */ + if(ctx->newline_pending) { + ctx->newline_pending = FALSE; + data->state.crlf_conversions++; + return Curl_cwriter_write(data, writer->next, type, &nl, 1); + } + /* Always pass on the EOS type indicator */ + return Curl_cwriter_write(data, writer->next, type, buf, 0); + } + return CURLE_OK; +} + +static const struct Curl_cwtype ftp_cw_lc = { + "ftp-lineconv", + NULL, + Curl_cwriter_def_init, + ftp_cw_lc_write, + Curl_cwriter_def_close, + sizeof(struct ftp_cw_lc_ctx) +}; + +#endif /* CURL_DO_LINEEND_CONV */ +/*********************************************************************** + * + * AcceptServerConnect() + * + * After connection request is received from the server this function is + * called to accept the connection and close the listening socket + * + */ +static CURLcode AcceptServerConnect(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + curl_socket_t sock = conn->sock[SECONDARYSOCKET]; + curl_socket_t s = CURL_SOCKET_BAD; +#ifdef USE_IPV6 + struct Curl_sockaddr_storage add; +#else + struct sockaddr_in add; +#endif + curl_socklen_t size = (curl_socklen_t) sizeof(add); + CURLcode result; + + if(0 == getsockname(sock, (struct sockaddr *) &add, &size)) { + size = sizeof(add); + + s = accept(sock, (struct sockaddr *) &add, &size); + } + + if(CURL_SOCKET_BAD == s) { + failf(data, "Error accept()ing server connect"); + return CURLE_FTP_PORT_FAILED; + } + infof(data, "Connection accepted from server"); + /* when this happens within the DO state it is important that we mark us as + not needing DO_MORE anymore */ + conn->bits.do_more = FALSE; + + (void)curlx_nonblock(s, TRUE); /* enable non-blocking */ + /* Replace any filter on SECONDARY with one listening on this socket */ + result = Curl_conn_tcp_accepted_set(data, conn, SECONDARYSOCKET, &s); + if(result) { + sclose(s); + return result; + } + + if(data->set.fsockopt) { + int error = 0; + + /* activate callback for setting socket options */ + Curl_set_in_callback(data, true); + error = data->set.fsockopt(data->set.sockopt_client, + s, + CURLSOCKTYPE_ACCEPT); + Curl_set_in_callback(data, false); + + if(error) { + close_secondarysocket(data, conn); + return CURLE_ABORTED_BY_CALLBACK; + } + } + + return CURLE_OK; + +} + +/* + * ftp_timeleft_accept() returns the amount of milliseconds left allowed for + * waiting server to connect. If the value is negative, the timeout time has + * already elapsed. + * + * The start time is stored in progress.t_acceptdata - as set with + * Curl_pgrsTime(..., TIMER_STARTACCEPT); + * + */ +static timediff_t ftp_timeleft_accept(struct Curl_easy *data) +{ + timediff_t timeout_ms = DEFAULT_ACCEPT_TIMEOUT; + timediff_t other; + struct curltime now; + + if(data->set.accepttimeout > 0) + timeout_ms = data->set.accepttimeout; + + now = Curl_now(); + + /* check if the generic timeout possibly is set shorter */ + other = Curl_timeleft(data, &now, FALSE); + if(other && (other < timeout_ms)) + /* note that this also works fine for when other happens to be negative + due to it already having elapsed */ + timeout_ms = other; + else { + /* subtract elapsed time */ + timeout_ms -= Curl_timediff(now, data->progress.t_acceptdata); + if(!timeout_ms) + /* avoid returning 0 as that means no timeout! */ + return -1; + } + + return timeout_ms; +} + + +/*********************************************************************** + * + * ReceivedServerConnect() + * + * After allowing server to connect to us from data port, this function + * checks both data connection for connection establishment and ctrl + * connection for a negative response regarding a failure in connecting + * + */ +static CURLcode ReceivedServerConnect(struct Curl_easy *data, bool *received) +{ + struct connectdata *conn = data->conn; + curl_socket_t ctrl_sock = conn->sock[FIRSTSOCKET]; + curl_socket_t data_sock = conn->sock[SECONDARYSOCKET]; + struct ftp_conn *ftpc = &conn->proto.ftpc; + struct pingpong *pp = &ftpc->pp; + int socketstate = 0; + timediff_t timeout_ms; + ssize_t nread; + int ftpcode; + bool response = FALSE; + + *received = FALSE; + + timeout_ms = ftp_timeleft_accept(data); + infof(data, "Checking for server connect"); + if(timeout_ms < 0) { + /* if a timeout was already reached, bail out */ + failf(data, "Accept timeout occurred while waiting server connect"); + return CURLE_FTP_ACCEPT_TIMEOUT; + } + + /* First check whether there is a cached response from server */ + if(Curl_dyn_len(&pp->recvbuf) && (*Curl_dyn_ptr(&pp->recvbuf) > '3')) { + /* Data connection could not be established, let's return */ + infof(data, "There is negative response in cache while serv connect"); + (void)Curl_GetFTPResponse(data, &nread, &ftpcode); + return CURLE_FTP_ACCEPT_FAILED; + } + + if(pp->overflow) + /* there is pending control data still in the buffer to read */ + response = TRUE; + else + socketstate = Curl_socket_check(ctrl_sock, data_sock, CURL_SOCKET_BAD, 0); + + /* see if the connection request is already here */ + switch(socketstate) { + case -1: /* error */ + /* let's die here */ + failf(data, "Error while waiting for server connect"); + return CURLE_FTP_ACCEPT_FAILED; + case 0: /* Server connect is not received yet */ + break; /* loop */ + default: + if(socketstate & CURL_CSELECT_IN2) { + infof(data, "Ready to accept data connection from server"); + *received = TRUE; + } + else if(socketstate & CURL_CSELECT_IN) + response = TRUE; + break; + } + if(response) { + infof(data, "Ctrl conn has data while waiting for data conn"); + if(pp->overflow > 3) { + char *r = Curl_dyn_ptr(&pp->recvbuf); + + DEBUGASSERT((pp->overflow + pp->nfinal) <= + Curl_dyn_len(&pp->recvbuf)); + /* move over the most recently handled response line */ + r += pp->nfinal; + + if(LASTLINE(r)) { + int status = curlx_sltosi(strtol(r, NULL, 10)); + if(status == 226) { + /* funny timing situation where we get the final message on the + control connection before traffic on the data connection has been + noticed. Leave the 226 in there and use this as a trigger to read + the data socket. */ + infof(data, "Got 226 before data activity"); + *received = TRUE; + return CURLE_OK; + } + } + } + + (void)Curl_GetFTPResponse(data, &nread, &ftpcode); + + infof(data, "FTP code: %03d", ftpcode); + + if(ftpcode/100 > 3) + return CURLE_FTP_ACCEPT_FAILED; + + return CURLE_WEIRD_SERVER_REPLY; + } + + return CURLE_OK; +} + + +/*********************************************************************** + * + * InitiateTransfer() + * + * After connection from server is accepted this function is called to + * setup transfer parameters and initiate the data transfer. + * + */ +static CURLcode InitiateTransfer(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + bool connected; + + CURL_TRC_FTP(data, "InitiateTransfer()"); + if(conn->bits.ftp_use_data_ssl && data->set.ftp_use_port && + !Curl_conn_is_ssl(conn, SECONDARYSOCKET)) { + result = Curl_ssl_cfilter_add(data, conn, SECONDARYSOCKET); + if(result) + return result; + } + result = Curl_conn_connect(data, SECONDARYSOCKET, TRUE, &connected); + if(result || !connected) + return result; + + if(conn->proto.ftpc.state_saved == FTP_STOR) { + /* When we know we're uploading a specified file, we can get the file + size prior to the actual upload. */ + Curl_pgrsSetUploadSize(data, data->state.infilesize); + + /* set the SO_SNDBUF for the secondary socket for those who need it */ + Curl_sndbufset(conn->sock[SECONDARYSOCKET]); + + Curl_xfer_setup(data, -1, -1, FALSE, SECONDARYSOCKET); + } + else { + /* FTP download: */ + Curl_xfer_setup(data, SECONDARYSOCKET, + conn->proto.ftpc.retr_size_saved, FALSE, -1); + } + + conn->proto.ftpc.pp.pending_resp = TRUE; /* expect server response */ + ftp_state(data, FTP_STOP); + + return CURLE_OK; +} + +/*********************************************************************** + * + * AllowServerConnect() + * + * When we've issue the PORT command, we have told the server to connect to + * us. This function checks whether data connection is established if so it is + * accepted. + * + */ +static CURLcode AllowServerConnect(struct Curl_easy *data, bool *connected) +{ + timediff_t timeout_ms; + CURLcode result = CURLE_OK; + + *connected = FALSE; + infof(data, "Preparing for accepting server on data port"); + + /* Save the time we start accepting server connect */ + Curl_pgrsTime(data, TIMER_STARTACCEPT); + + timeout_ms = ftp_timeleft_accept(data); + if(timeout_ms < 0) { + /* if a timeout was already reached, bail out */ + failf(data, "Accept timeout occurred while waiting server connect"); + result = CURLE_FTP_ACCEPT_TIMEOUT; + goto out; + } + + /* see if the connection request is already here */ + result = ReceivedServerConnect(data, connected); + if(result) + goto out; + + if(*connected) { + result = AcceptServerConnect(data); + if(result) + goto out; + + result = InitiateTransfer(data); + if(result) + goto out; + } + else { + /* Add timeout to multi handle and break out of the loop */ + Curl_expire(data, data->set.accepttimeout ? + data->set.accepttimeout: DEFAULT_ACCEPT_TIMEOUT, + EXPIRE_FTP_ACCEPT); + } + +out: + CURL_TRC_FTP(data, "AllowServerConnect() -> %d", result); + return result; +} + +static bool ftp_endofresp(struct Curl_easy *data, struct connectdata *conn, + char *line, size_t len, int *code) +{ + (void)data; + (void)conn; + + if((len > 3) && LASTLINE(line)) { + *code = curlx_sltosi(strtol(line, NULL, 10)); + return TRUE; + } + + return FALSE; +} + +static CURLcode ftp_readresp(struct Curl_easy *data, + int sockindex, + struct pingpong *pp, + int *ftpcode, /* return the ftp-code if done */ + size_t *size) /* size of the response */ +{ + int code; + CURLcode result = Curl_pp_readresp(data, sockindex, pp, &code, size); + +#ifdef HAVE_GSSAPI + { + struct connectdata *conn = data->conn; + char * const buf = Curl_dyn_ptr(&data->conn->proto.ftpc.pp.recvbuf); + + /* handle the security-oriented responses 6xx ***/ + switch(code) { + case 631: + code = Curl_sec_read_msg(data, conn, buf, PROT_SAFE); + break; + case 632: + code = Curl_sec_read_msg(data, conn, buf, PROT_PRIVATE); + break; + case 633: + code = Curl_sec_read_msg(data, conn, buf, PROT_CONFIDENTIAL); + break; + default: + /* normal ftp stuff we pass through! */ + break; + } + } +#endif + + /* store the latest code for later retrieval */ + data->info.httpcode = code; + + if(ftpcode) + *ftpcode = code; + + if(421 == code) { + /* 421 means "Service not available, closing control connection." and FTP + * servers use it to signal that idle session timeout has been exceeded. + * If we ignored the response, it could end up hanging in some cases. + * + * This response code can come at any point so having it treated + * generically is a good idea. + */ + infof(data, "We got a 421 - timeout"); + ftp_state(data, FTP_STOP); + return CURLE_OPERATION_TIMEDOUT; + } + + return result; +} + +/* --- parse FTP server responses --- */ + +/* + * Curl_GetFTPResponse() is a BLOCKING function to read the full response + * from a server after a command. + * + */ + +CURLcode Curl_GetFTPResponse(struct Curl_easy *data, + ssize_t *nreadp, /* return number of bytes read */ + int *ftpcode) /* return the ftp-code */ +{ + /* + * We cannot read just one byte per read() and then go back to select() as + * the OpenSSL read() doesn't grok that properly. + * + * Alas, read as much as possible, split up into lines, use the ending + * line in a response or continue reading. */ + + struct connectdata *conn = data->conn; + curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; + CURLcode result = CURLE_OK; + struct ftp_conn *ftpc = &conn->proto.ftpc; + struct pingpong *pp = &ftpc->pp; + size_t nread; + int cache_skip = 0; + int value_to_be_ignored = 0; + + if(ftpcode) + *ftpcode = 0; /* 0 for errors */ + else + /* make the pointer point to something for the rest of this function */ + ftpcode = &value_to_be_ignored; + + *nreadp = 0; + + while(!*ftpcode && !result) { + /* check and reset timeout value every lap */ + timediff_t timeout = Curl_pp_state_timeout(data, pp, FALSE); + timediff_t interval_ms; + + if(timeout <= 0) { + failf(data, "FTP response timeout"); + return CURLE_OPERATION_TIMEDOUT; /* already too little time */ + } + + interval_ms = 1000; /* use 1 second timeout intervals */ + if(timeout < interval_ms) + interval_ms = timeout; + + /* + * Since this function is blocking, we need to wait here for input on the + * connection and only then we call the response reading function. We do + * timeout at least every second to make the timeout check run. + * + * A caution here is that the ftp_readresp() function has a cache that may + * contain pieces of a response from the previous invoke and we need to + * make sure we don't just wait for input while there is unhandled data in + * that cache. But also, if the cache is there, we call ftp_readresp() and + * the cache wasn't good enough to continue we must not just busy-loop + * around this function. + * + */ + + if(Curl_dyn_len(&pp->recvbuf) && (cache_skip < 2)) { + /* + * There's a cache left since before. We then skipping the wait for + * socket action, unless this is the same cache like the previous round + * as then the cache was deemed not enough to act on and we then need to + * wait for more data anyway. + */ + } + else if(!Curl_conn_data_pending(data, FIRSTSOCKET)) { + switch(SOCKET_READABLE(sockfd, interval_ms)) { + case -1: /* select() error, stop reading */ + failf(data, "FTP response aborted due to select/poll error: %d", + SOCKERRNO); + return CURLE_RECV_ERROR; + + case 0: /* timeout */ + if(Curl_pgrsUpdate(data)) + return CURLE_ABORTED_BY_CALLBACK; + continue; /* just continue in our loop for the timeout duration */ + + default: /* for clarity */ + break; + } + } + result = ftp_readresp(data, FIRSTSOCKET, pp, ftpcode, &nread); + if(result) + break; + + if(!nread && Curl_dyn_len(&pp->recvbuf)) + /* bump cache skip counter as on repeated skips we must wait for more + data */ + cache_skip++; + else + /* when we got data or there is no cache left, we reset the cache skip + counter */ + cache_skip = 0; + + *nreadp += nread; + + } /* while there's buffer left and loop is requested */ + + pp->pending_resp = FALSE; + + return result; +} + +static CURLcode ftp_state_user(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = Curl_pp_sendf(data, + &conn->proto.ftpc.pp, "USER %s", + conn->user?conn->user:""); + if(!result) { + struct ftp_conn *ftpc = &conn->proto.ftpc; + ftpc->ftp_trying_alternative = FALSE; + ftp_state(data, FTP_USER); + } + return result; +} + +static CURLcode ftp_state_pwd(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = Curl_pp_sendf(data, &conn->proto.ftpc.pp, "%s", "PWD"); + if(!result) + ftp_state(data, FTP_PWD); + + return result; +} + +/* For the FTP "protocol connect" and "doing" phases only */ +static int ftp_getsock(struct Curl_easy *data, + struct connectdata *conn, + curl_socket_t *socks) +{ + return Curl_pp_getsock(data, &conn->proto.ftpc.pp, socks); +} + +/* For the FTP "DO_MORE" phase only */ +static int ftp_domore_getsock(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *socks) +{ + struct ftp_conn *ftpc = &conn->proto.ftpc; + (void)data; + + /* When in DO_MORE state, we could be either waiting for us to connect to a + * remote site, or we could wait for that site to connect to us. Or just + * handle ordinary commands. + */ + CURL_TRC_FTP(data, "[%s] ftp_domore_getsock()", FTP_DSTATE(data)); + + if(FTP_STOP == ftpc->state) { + /* if stopped and still in this state, then we're also waiting for a + connect on the secondary connection */ + DEBUGASSERT(conn->sock[SECONDARYSOCKET] != CURL_SOCKET_BAD || + (conn->cfilter[SECONDARYSOCKET] && + !Curl_conn_is_connected(conn, SECONDARYSOCKET))); + socks[0] = conn->sock[FIRSTSOCKET]; + /* An unconnected SECONDARY will add its socket by itself + * via its adjust_pollset() */ + return GETSOCK_READSOCK(0); + } + return Curl_pp_getsock(data, &conn->proto.ftpc.pp, socks); +} + +/* This is called after the FTP_QUOTE state is passed. + + ftp_state_cwd() sends the range of CWD commands to the server to change to + the correct directory. It may also need to send MKD commands to create + missing ones, if that option is enabled. +*/ +static CURLcode ftp_state_cwd(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + struct ftp_conn *ftpc = &conn->proto.ftpc; + + if(ftpc->cwddone) + /* already done and fine */ + result = ftp_state_mdtm(data); + else { + /* FTPFILE_NOCWD with full path: expect ftpc->cwddone! */ + DEBUGASSERT((data->set.ftp_filemethod != FTPFILE_NOCWD) || + !(ftpc->dirdepth && ftpc->dirs[0][0] == '/')); + + ftpc->count2 = 0; /* count2 counts failed CWDs */ + + if(conn->bits.reuse && ftpc->entrypath && + /* no need to go to entrypath when we have an absolute path */ + !(ftpc->dirdepth && ftpc->dirs[0][0] == '/')) { + /* This is a reused connection. Since we change directory to where the + transfer is taking place, we must first get back to the original dir + where we ended up after login: */ + ftpc->cwdcount = 0; /* we count this as the first path, then we add one + for all upcoming ones in the ftp->dirs[] array */ + result = Curl_pp_sendf(data, &ftpc->pp, "CWD %s", ftpc->entrypath); + if(!result) + ftp_state(data, FTP_CWD); + } + else { + if(ftpc->dirdepth) { + ftpc->cwdcount = 1; + /* issue the first CWD, the rest is sent when the CWD responses are + received... */ + result = Curl_pp_sendf(data, &ftpc->pp, "CWD %s", + ftpc->dirs[ftpc->cwdcount -1]); + if(!result) + ftp_state(data, FTP_CWD); + } + else { + /* No CWD necessary */ + result = ftp_state_mdtm(data); + } + } + } + return result; +} + +typedef enum { + EPRT, + PORT, + DONE +} ftpport; + +static CURLcode ftp_state_use_port(struct Curl_easy *data, + ftpport fcmd) /* start with this */ +{ + CURLcode result = CURLE_FTP_PORT_FAILED; + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = &conn->proto.ftpc; + curl_socket_t portsock = CURL_SOCKET_BAD; + char myhost[MAX_IPADR_LEN + 1] = ""; + + struct Curl_sockaddr_storage ss; + struct Curl_addrinfo *res, *ai; + curl_socklen_t sslen; + char hbuf[NI_MAXHOST]; + struct sockaddr *sa = (struct sockaddr *)&ss; + struct sockaddr_in * const sa4 = (void *)sa; +#ifdef USE_IPV6 + struct sockaddr_in6 * const sa6 = (void *)sa; +#endif + static const char mode[][5] = { "EPRT", "PORT" }; + enum resolve_t rc; + int error; + char *host = NULL; + char *string_ftpport = data->set.str[STRING_FTPPORT]; + struct Curl_dns_entry *h = NULL; + unsigned short port_min = 0; + unsigned short port_max = 0; + unsigned short port; + bool possibly_non_local = TRUE; + char buffer[STRERROR_LEN]; + char *addr = NULL; + size_t addrlen = 0; + char ipstr[50]; + + /* Step 1, figure out what is requested, + * accepted format : + * (ipv4|ipv6|domain|interface)?(:port(-range)?)? + */ + + if(data->set.str[STRING_FTPPORT] && + (strlen(data->set.str[STRING_FTPPORT]) > 1)) { + char *ip_end = NULL; + +#ifdef USE_IPV6 + if(*string_ftpport == '[') { + /* [ipv6]:port(-range) */ + char *ip_start = string_ftpport + 1; + ip_end = strchr(ip_start, ']'); + if(ip_end) { + addrlen = ip_end - ip_start; + addr = ip_start; + } + } + else +#endif + if(*string_ftpport == ':') { + /* :port */ + ip_end = string_ftpport; + } + else { + ip_end = strchr(string_ftpport, ':'); + addr = string_ftpport; + if(ip_end) { + /* either ipv6 or (ipv4|domain|interface):port(-range) */ + addrlen = ip_end - string_ftpport; +#ifdef USE_IPV6 + if(Curl_inet_pton(AF_INET6, string_ftpport, &sa6->sin6_addr) == 1) { + /* ipv6 */ + port_min = port_max = 0; + ip_end = NULL; /* this got no port ! */ + } +#endif + } + else + /* ipv4|interface */ + addrlen = strlen(string_ftpport); + } + + /* parse the port */ + if(ip_end) { + char *port_sep = NULL; + char *port_start = strchr(ip_end, ':'); + if(port_start) { + port_min = curlx_ultous(strtoul(port_start + 1, NULL, 10)); + port_sep = strchr(port_start, '-'); + if(port_sep) { + port_max = curlx_ultous(strtoul(port_sep + 1, NULL, 10)); + } + else + port_max = port_min; + } + } + + /* correct errors like: + * :1234-1230 + * :-4711, in this case port_min is (unsigned)-1, + * therefore port_min > port_max for all cases + * but port_max = (unsigned)-1 + */ + if(port_min > port_max) + port_min = port_max = 0; + + if(addrlen) { + DEBUGASSERT(addr); + if(addrlen >= sizeof(ipstr)) + goto out; + memcpy(ipstr, addr, addrlen); + ipstr[addrlen] = 0; + + /* attempt to get the address of the given interface name */ + switch(Curl_if2ip(conn->remote_addr->family, +#ifdef USE_IPV6 + Curl_ipv6_scope(&conn->remote_addr->sa_addr), + conn->scope_id, +#endif + ipstr, hbuf, sizeof(hbuf))) { + case IF2IP_NOT_FOUND: + /* not an interface, use the given string as host name instead */ + host = ipstr; + break; + case IF2IP_AF_NOT_SUPPORTED: + goto out; + case IF2IP_FOUND: + host = hbuf; /* use the hbuf for host name */ + break; + } + } + else + /* there was only a port(-range) given, default the host */ + host = NULL; + } /* data->set.ftpport */ + + if(!host) { + const char *r; + /* not an interface and not a host name, get default by extracting + the IP from the control connection */ + sslen = sizeof(ss); + if(getsockname(conn->sock[FIRSTSOCKET], sa, &sslen)) { + failf(data, "getsockname() failed: %s", + Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + goto out; + } + switch(sa->sa_family) { +#ifdef USE_IPV6 + case AF_INET6: + r = Curl_inet_ntop(sa->sa_family, &sa6->sin6_addr, hbuf, sizeof(hbuf)); + break; +#endif + default: + r = Curl_inet_ntop(sa->sa_family, &sa4->sin_addr, hbuf, sizeof(hbuf)); + break; + } + if(!r) { + goto out; + } + host = hbuf; /* use this host name */ + possibly_non_local = FALSE; /* we know it is local now */ + } + + /* resolv ip/host to ip */ + rc = Curl_resolv(data, host, 0, FALSE, &h); + if(rc == CURLRESOLV_PENDING) + (void)Curl_resolver_wait_resolv(data, &h); + if(h) { + res = h->addr; + /* when we return from this function, we can forget about this entry + to we can unlock it now already */ + Curl_resolv_unlock(data, h); + } /* (h) */ + else + res = NULL; /* failure! */ + + if(!res) { + failf(data, "failed to resolve the address provided to PORT: %s", host); + goto out; + } + + host = NULL; + + /* step 2, create a socket for the requested address */ + error = 0; + for(ai = res; ai; ai = ai->ai_next) { + if(Curl_socket_open(data, ai, NULL, conn->transport, &portsock)) { + error = SOCKERRNO; + continue; + } + break; + } + if(!ai) { + failf(data, "socket failure: %s", + Curl_strerror(error, buffer, sizeof(buffer))); + goto out; + } + CURL_TRC_FTP(data, "[%s] ftp_state_use_port(), opened socket", + FTP_DSTATE(data)); + + /* step 3, bind to a suitable local address */ + + memcpy(sa, ai->ai_addr, ai->ai_addrlen); + sslen = ai->ai_addrlen; + + for(port = port_min; port <= port_max;) { + if(sa->sa_family == AF_INET) + sa4->sin_port = htons(port); +#ifdef USE_IPV6 + else + sa6->sin6_port = htons(port); +#endif + /* Try binding the given address. */ + if(bind(portsock, sa, sslen) ) { + /* It failed. */ + error = SOCKERRNO; + if(possibly_non_local && (error == EADDRNOTAVAIL)) { + /* The requested bind address is not local. Use the address used for + * the control connection instead and restart the port loop + */ + infof(data, "bind(port=%hu) on non-local address failed: %s", port, + Curl_strerror(error, buffer, sizeof(buffer))); + + sslen = sizeof(ss); + if(getsockname(conn->sock[FIRSTSOCKET], sa, &sslen)) { + failf(data, "getsockname() failed: %s", + Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + goto out; + } + port = port_min; + possibly_non_local = FALSE; /* don't try this again */ + continue; + } + if(error != EADDRINUSE && error != EACCES) { + failf(data, "bind(port=%hu) failed: %s", port, + Curl_strerror(error, buffer, sizeof(buffer))); + goto out; + } + } + else + break; + + port++; + } + + /* maybe all ports were in use already */ + if(port > port_max) { + failf(data, "bind() failed, we ran out of ports"); + goto out; + } + + /* get the name again after the bind() so that we can extract the + port number it uses now */ + sslen = sizeof(ss); + if(getsockname(portsock, sa, &sslen)) { + failf(data, "getsockname() failed: %s", + Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + goto out; + } + CURL_TRC_FTP(data, "[%s] ftp_state_use_port(), socket bound to port %d", + FTP_DSTATE(data), port); + + /* step 4, listen on the socket */ + + if(listen(portsock, 1)) { + failf(data, "socket failure: %s", + Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + goto out; + } + CURL_TRC_FTP(data, "[%s] ftp_state_use_port(), listening on %d", + FTP_DSTATE(data), port); + + /* step 5, send the proper FTP command */ + + /* get a plain printable version of the numerical address to work with + below */ + Curl_printable_address(ai, myhost, sizeof(myhost)); + +#ifdef USE_IPV6 + if(!conn->bits.ftp_use_eprt && conn->bits.ipv6) + /* EPRT is disabled but we are connected to a IPv6 host, so we ignore the + request and enable EPRT again! */ + conn->bits.ftp_use_eprt = TRUE; +#endif + + /* Replace any filter on SECONDARY with one listening on this socket */ + result = Curl_conn_tcp_listen_set(data, conn, SECONDARYSOCKET, &portsock); + if(result) + goto out; + portsock = CURL_SOCKET_BAD; /* now held in filter */ + + for(; fcmd != DONE; fcmd++) { + + if(!conn->bits.ftp_use_eprt && (EPRT == fcmd)) + /* if disabled, goto next */ + continue; + + if((PORT == fcmd) && sa->sa_family != AF_INET) + /* PORT is IPv4 only */ + continue; + + switch(sa->sa_family) { + case AF_INET: + port = ntohs(sa4->sin_port); + break; +#ifdef USE_IPV6 + case AF_INET6: + port = ntohs(sa6->sin6_port); + break; +#endif + default: + continue; /* might as well skip this */ + } + + if(EPRT == fcmd) { + /* + * Two fine examples from RFC2428; + * + * EPRT |1|132.235.1.2|6275| + * + * EPRT |2|1080::8:800:200C:417A|5282| + */ + + result = Curl_pp_sendf(data, &ftpc->pp, "%s |%d|%s|%hu|", mode[fcmd], + sa->sa_family == AF_INET?1:2, + myhost, port); + if(result) { + failf(data, "Failure sending EPRT command: %s", + curl_easy_strerror(result)); + goto out; + } + break; + } + if(PORT == fcmd) { + /* large enough for [IP address],[num],[num] */ + char target[sizeof(myhost) + 20]; + char *source = myhost; + char *dest = target; + + /* translate x.x.x.x to x,x,x,x */ + while(source && *source) { + if(*source == '.') + *dest = ','; + else + *dest = *source; + dest++; + source++; + } + *dest = 0; + msnprintf(dest, 20, ",%d,%d", (int)(port>>8), (int)(port&0xff)); + + result = Curl_pp_sendf(data, &ftpc->pp, "%s %s", mode[fcmd], target); + if(result) { + failf(data, "Failure sending PORT command: %s", + curl_easy_strerror(result)); + goto out; + } + break; + } + } + + /* store which command was sent */ + ftpc->count1 = fcmd; + + ftp_state(data, FTP_PORT); + +out: + if(result) { + ftp_state(data, FTP_STOP); + } + if(portsock != CURL_SOCKET_BAD) + Curl_socket_close(data, conn, portsock); + return result; +} + +static CURLcode ftp_state_use_pasv(struct Curl_easy *data, + struct connectdata *conn) +{ + struct ftp_conn *ftpc = &conn->proto.ftpc; + CURLcode result = CURLE_OK; + /* + Here's the executive summary on what to do: + + PASV is RFC959, expect: + 227 Entering Passive Mode (a1,a2,a3,a4,p1,p2) + + LPSV is RFC1639, expect: + 228 Entering Long Passive Mode (4,4,a1,a2,a3,a4,2,p1,p2) + + EPSV is RFC2428, expect: + 229 Entering Extended Passive Mode (|||port|) + + */ + + static const char mode[][5] = { "EPSV", "PASV" }; + int modeoff; + +#ifdef PF_INET6 + if(!conn->bits.ftp_use_epsv && conn->bits.ipv6) + /* EPSV is disabled but we are connected to a IPv6 host, so we ignore the + request and enable EPSV again! */ + conn->bits.ftp_use_epsv = TRUE; +#endif + + modeoff = conn->bits.ftp_use_epsv?0:1; + + result = Curl_pp_sendf(data, &ftpc->pp, "%s", mode[modeoff]); + if(!result) { + ftpc->count1 = modeoff; + ftp_state(data, FTP_PASV); + infof(data, "Connect data stream passively"); + } + return result; +} + +/* + * ftp_state_prepare_transfer() starts PORT, PASV or PRET etc. + * + * REST is the last command in the chain of commands when a "head"-like + * request is made. Thus, if an actual transfer is to be made this is where we + * take off for real. + */ +static CURLcode ftp_state_prepare_transfer(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct FTP *ftp = data->req.p.ftp; + struct connectdata *conn = data->conn; + + if(ftp->transfer != PPTRANSFER_BODY) { + /* doesn't transfer any data */ + + /* still possibly do PRE QUOTE jobs */ + ftp_state(data, FTP_RETR_PREQUOTE); + result = ftp_state_quote(data, TRUE, FTP_RETR_PREQUOTE); + } + else if(data->set.ftp_use_port) { + /* We have chosen to use the PORT (or similar) command */ + result = ftp_state_use_port(data, EPRT); + } + else { + /* We have chosen (this is default) to use the PASV (or similar) command */ + if(data->set.ftp_use_pret) { + /* The user has requested that we send a PRET command + to prepare the server for the upcoming PASV */ + struct ftp_conn *ftpc = &conn->proto.ftpc; + if(!conn->proto.ftpc.file) + result = Curl_pp_sendf(data, &ftpc->pp, "PRET %s", + data->set.str[STRING_CUSTOMREQUEST]? + data->set.str[STRING_CUSTOMREQUEST]: + (data->state.list_only?"NLST":"LIST")); + else if(data->state.upload) + result = Curl_pp_sendf(data, &ftpc->pp, "PRET STOR %s", + conn->proto.ftpc.file); + else + result = Curl_pp_sendf(data, &ftpc->pp, "PRET RETR %s", + conn->proto.ftpc.file); + if(!result) + ftp_state(data, FTP_PRET); + } + else + result = ftp_state_use_pasv(data, conn); + } + return result; +} + +static CURLcode ftp_state_rest(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + struct FTP *ftp = data->req.p.ftp; + struct ftp_conn *ftpc = &conn->proto.ftpc; + + if((ftp->transfer != PPTRANSFER_BODY) && ftpc->file) { + /* if a "head"-like request is being made (on a file) */ + + /* Determine if server can respond to REST command and therefore + whether it supports range */ + result = Curl_pp_sendf(data, &ftpc->pp, "REST %d", 0); + if(!result) + ftp_state(data, FTP_REST); + } + else + result = ftp_state_prepare_transfer(data); + + return result; +} + +static CURLcode ftp_state_size(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + struct FTP *ftp = data->req.p.ftp; + struct ftp_conn *ftpc = &conn->proto.ftpc; + + if((ftp->transfer == PPTRANSFER_INFO) && ftpc->file) { + /* if a "head"-like request is being made (on a file) */ + + /* we know ftpc->file is a valid pointer to a file name */ + result = Curl_pp_sendf(data, &ftpc->pp, "SIZE %s", ftpc->file); + if(!result) + ftp_state(data, FTP_SIZE); + } + else + result = ftp_state_rest(data, conn); + + return result; +} + +static CURLcode ftp_state_list(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct FTP *ftp = data->req.p.ftp; + struct connectdata *conn = data->conn; + + /* If this output is to be machine-parsed, the NLST command might be better + to use, since the LIST command output is not specified or standard in any + way. It has turned out that the NLST list output is not the same on all + servers either... */ + + /* + if FTPFILE_NOCWD was specified, we should add the path + as argument for the LIST / NLST / or custom command. + Whether the server will support this, is uncertain. + + The other ftp_filemethods will CWD into dir/dir/ first and + then just do LIST (in that case: nothing to do here) + */ + char *lstArg = NULL; + char *cmd; + + if((data->set.ftp_filemethod == FTPFILE_NOCWD) && ftp->path) { + /* url-decode before evaluation: e.g. paths starting/ending with %2f */ + const char *slashPos = NULL; + char *rawPath = NULL; + result = Curl_urldecode(ftp->path, 0, &rawPath, NULL, REJECT_CTRL); + if(result) + return result; + + slashPos = strrchr(rawPath, '/'); + if(slashPos) { + /* chop off the file part if format is dir/file otherwise remove + the trailing slash for dir/dir/ except for absolute path / */ + size_t n = slashPos - rawPath; + if(n == 0) + ++n; + + lstArg = rawPath; + lstArg[n] = '\0'; + } + else + free(rawPath); + } + + cmd = aprintf("%s%s%s", + data->set.str[STRING_CUSTOMREQUEST]? + data->set.str[STRING_CUSTOMREQUEST]: + (data->state.list_only?"NLST":"LIST"), + lstArg? " ": "", + lstArg? lstArg: ""); + free(lstArg); + + if(!cmd) + return CURLE_OUT_OF_MEMORY; + + result = Curl_pp_sendf(data, &conn->proto.ftpc.pp, "%s", cmd); + free(cmd); + + if(!result) + ftp_state(data, FTP_LIST); + + return result; +} + +static CURLcode ftp_state_retr_prequote(struct Curl_easy *data) +{ + /* We've sent the TYPE, now we must send the list of prequote strings */ + return ftp_state_quote(data, TRUE, FTP_RETR_PREQUOTE); +} + +static CURLcode ftp_state_stor_prequote(struct Curl_easy *data) +{ + /* We've sent the TYPE, now we must send the list of prequote strings */ + return ftp_state_quote(data, TRUE, FTP_STOR_PREQUOTE); +} + +static CURLcode ftp_state_type(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct FTP *ftp = data->req.p.ftp; + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = &conn->proto.ftpc; + + /* If we have selected NOBODY and HEADER, it means that we only want file + information. Which in FTP can't be much more than the file size and + date. */ + if(data->req.no_body && ftpc->file && + ftp_need_type(conn, data->state.prefer_ascii)) { + /* The SIZE command is _not_ RFC 959 specified, and therefore many servers + may not support it! It is however the only way we have to get a file's + size! */ + + ftp->transfer = PPTRANSFER_INFO; + /* this means no actual transfer will be made */ + + /* Some servers return different sizes for different modes, and thus we + must set the proper type before we check the size */ + result = ftp_nb_type(data, conn, data->state.prefer_ascii, FTP_TYPE); + if(result) + return result; + } + else + result = ftp_state_size(data, conn); + + return result; +} + +/* This is called after the CWD commands have been done in the beginning of + the DO phase */ +static CURLcode ftp_state_mdtm(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = &conn->proto.ftpc; + + /* Requested time of file or time-depended transfer? */ + if((data->set.get_filetime || data->set.timecondition) && ftpc->file) { + + /* we have requested to get the modified-time of the file, this is a white + spot as the MDTM is not mentioned in RFC959 */ + result = Curl_pp_sendf(data, &ftpc->pp, "MDTM %s", ftpc->file); + + if(!result) + ftp_state(data, FTP_MDTM); + } + else + result = ftp_state_type(data); + + return result; +} + + +/* This is called after the TYPE and possible quote commands have been sent */ +static CURLcode ftp_state_ul_setup(struct Curl_easy *data, + bool sizechecked) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct FTP *ftp = data->req.p.ftp; + struct ftp_conn *ftpc = &conn->proto.ftpc; + bool append = data->set.remote_append; + + if((data->state.resume_from && !sizechecked) || + ((data->state.resume_from > 0) && sizechecked)) { + /* we're about to continue the uploading of a file */ + /* 1. get already existing file's size. We use the SIZE command for this + which may not exist in the server! The SIZE command is not in + RFC959. */ + + /* 2. This used to set REST. But since we can do append, we + don't another ftp command. We just skip the source file + offset and then we APPEND the rest on the file instead */ + + /* 3. pass file-size number of bytes in the source file */ + /* 4. lower the infilesize counter */ + /* => transfer as usual */ + int seekerr = CURL_SEEKFUNC_OK; + + if(data->state.resume_from < 0) { + /* Got no given size to start from, figure it out */ + result = Curl_pp_sendf(data, &ftpc->pp, "SIZE %s", ftpc->file); + if(!result) + ftp_state(data, FTP_STOR_SIZE); + return result; + } + + /* enable append */ + append = TRUE; + + /* Let's read off the proper amount of bytes from the input. */ + if(data->set.seek_func) { + Curl_set_in_callback(data, true); + seekerr = data->set.seek_func(data->set.seek_client, + data->state.resume_from, SEEK_SET); + Curl_set_in_callback(data, false); + } + + if(seekerr != CURL_SEEKFUNC_OK) { + curl_off_t passed = 0; + if(seekerr != CURL_SEEKFUNC_CANTSEEK) { + failf(data, "Could not seek stream"); + return CURLE_FTP_COULDNT_USE_REST; + } + /* seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */ + do { + char scratch[4*1024]; + size_t readthisamountnow = + (data->state.resume_from - passed > (curl_off_t)sizeof(scratch)) ? + sizeof(scratch) : + curlx_sotouz(data->state.resume_from - passed); + + size_t actuallyread = + data->state.fread_func(scratch, 1, readthisamountnow, + data->state.in); + + passed += actuallyread; + if((actuallyread == 0) || (actuallyread > readthisamountnow)) { + /* this checks for greater-than only to make sure that the + CURL_READFUNC_ABORT return code still aborts */ + failf(data, "Failed to read data"); + return CURLE_FTP_COULDNT_USE_REST; + } + } while(passed < data->state.resume_from); + } + /* now, decrease the size of the read */ + if(data->state.infilesize>0) { + data->state.infilesize -= data->state.resume_from; + + if(data->state.infilesize <= 0) { + infof(data, "File already completely uploaded"); + + /* no data to transfer */ + Curl_xfer_setup(data, -1, -1, FALSE, -1); + + /* Set ->transfer so that we won't get any error in + * ftp_done() because we didn't transfer anything! */ + ftp->transfer = PPTRANSFER_NONE; + + ftp_state(data, FTP_STOP); + return CURLE_OK; + } + } + /* we've passed, proceed as normal */ + } /* resume_from */ + + result = Curl_pp_sendf(data, &ftpc->pp, append?"APPE %s":"STOR %s", + ftpc->file); + if(!result) + ftp_state(data, FTP_STOR); + + return result; +} + +static CURLcode ftp_state_quote(struct Curl_easy *data, + bool init, + ftpstate instate) +{ + CURLcode result = CURLE_OK; + struct FTP *ftp = data->req.p.ftp; + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = &conn->proto.ftpc; + bool quote = FALSE; + struct curl_slist *item; + + switch(instate) { + case FTP_QUOTE: + default: + item = data->set.quote; + break; + case FTP_RETR_PREQUOTE: + case FTP_STOR_PREQUOTE: + item = data->set.prequote; + break; + case FTP_POSTQUOTE: + item = data->set.postquote; + break; + } + + /* + * This state uses: + * 'count1' to iterate over the commands to send + * 'count2' to store whether to allow commands to fail + */ + + if(init) + ftpc->count1 = 0; + else + ftpc->count1++; + + if(item) { + int i = 0; + + /* Skip count1 items in the linked list */ + while((i< ftpc->count1) && item) { + item = item->next; + i++; + } + if(item) { + char *cmd = item->data; + if(cmd[0] == '*') { + cmd++; + ftpc->count2 = 1; /* the sent command is allowed to fail */ + } + else + ftpc->count2 = 0; /* failure means cancel operation */ + + result = Curl_pp_sendf(data, &ftpc->pp, "%s", cmd); + if(result) + return result; + ftp_state(data, instate); + quote = TRUE; + } + } + + if(!quote) { + /* No more quote to send, continue to ... */ + switch(instate) { + case FTP_QUOTE: + default: + result = ftp_state_cwd(data, conn); + break; + case FTP_RETR_PREQUOTE: + if(ftp->transfer != PPTRANSFER_BODY) + ftp_state(data, FTP_STOP); + else { + if(ftpc->known_filesize != -1) { + Curl_pgrsSetDownloadSize(data, ftpc->known_filesize); + result = ftp_state_retr(data, ftpc->known_filesize); + } + else { + if(data->set.ignorecl || data->state.prefer_ascii) { + /* 'ignorecl' is used to support download of growing files. It + prevents the state machine from requesting the file size from + the server. With an unknown file size the download continues + until the server terminates it, otherwise the client stops if + the received byte count exceeds the reported file size. Set + option CURLOPT_IGNORE_CONTENT_LENGTH to 1 to enable this + behavior. + + In addition: asking for the size for 'TYPE A' transfers is not + constructive since servers don't report the converted size. So + skip it. + */ + result = Curl_pp_sendf(data, &ftpc->pp, "RETR %s", ftpc->file); + if(!result) + ftp_state(data, FTP_RETR); + } + else { + result = Curl_pp_sendf(data, &ftpc->pp, "SIZE %s", ftpc->file); + if(!result) + ftp_state(data, FTP_RETR_SIZE); + } + } + } + break; + case FTP_STOR_PREQUOTE: + result = ftp_state_ul_setup(data, FALSE); + break; + case FTP_POSTQUOTE: + break; + } + } + + return result; +} + +/* called from ftp_state_pasv_resp to switch to PASV in case of EPSV + problems */ +static CURLcode ftp_epsv_disable(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + + if(conn->bits.ipv6 +#ifndef CURL_DISABLE_PROXY + && !(conn->bits.tunnel_proxy || conn->bits.socksproxy) +#endif + ) { + /* We can't disable EPSV when doing IPv6, so this is instead a fail */ + failf(data, "Failed EPSV attempt, exiting"); + return CURLE_WEIRD_SERVER_REPLY; + } + + infof(data, "Failed EPSV attempt. Disabling EPSV"); + /* disable it for next transfer */ + conn->bits.ftp_use_epsv = FALSE; + Curl_conn_close(data, SECONDARYSOCKET); + Curl_conn_cf_discard_all(data, conn, SECONDARYSOCKET); + data->state.errorbuf = FALSE; /* allow error message to get + rewritten */ + result = Curl_pp_sendf(data, &conn->proto.ftpc.pp, "%s", "PASV"); + if(!result) { + conn->proto.ftpc.count1++; + /* remain in/go to the FTP_PASV state */ + ftp_state(data, FTP_PASV); + } + return result; +} + + +static char *control_address(struct connectdata *conn) +{ + /* Returns the control connection IP address. + If a proxy tunnel is used, returns the original host name instead, because + the effective control connection address is the proxy address, + not the ftp host. */ +#ifndef CURL_DISABLE_PROXY + if(conn->bits.tunnel_proxy || conn->bits.socksproxy) + return conn->host.name; +#endif + return conn->primary.remote_ip; +} + +static bool match_pasv_6nums(const char *p, + unsigned int *array) /* 6 numbers */ +{ + int i; + for(i = 0; i < 6; i++) { + unsigned long num; + char *endp; + if(i) { + if(*p != ',') + return FALSE; + p++; + } + if(!ISDIGIT(*p)) + return FALSE; + num = strtoul(p, &endp, 10); + if(num > 255) + return FALSE; + array[i] = (unsigned int)num; + p = endp; + } + return TRUE; +} + +static CURLcode ftp_state_pasv_resp(struct Curl_easy *data, + int ftpcode) +{ + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = &conn->proto.ftpc; + CURLcode result; + struct Curl_dns_entry *addr = NULL; + enum resolve_t rc; + unsigned short connectport; /* the local port connect() should use! */ + struct pingpong *pp = &ftpc->pp; + char *str = + Curl_dyn_ptr(&pp->recvbuf) + 4; /* start on the first letter */ + + /* if we come here again, make sure the former name is cleared */ + Curl_safefree(ftpc->newhost); + + if((ftpc->count1 == 0) && + (ftpcode == 229)) { + /* positive EPSV response */ + char *ptr = strchr(str, '('); + if(ptr) { + char sep; + ptr++; + /* |||12345| */ + sep = ptr[0]; + /* the ISDIGIT() check here is because strtoul() accepts leading minus + etc */ + if((ptr[1] == sep) && (ptr[2] == sep) && ISDIGIT(ptr[3])) { + char *endp; + unsigned long num = strtoul(&ptr[3], &endp, 10); + if(*endp != sep) + ptr = NULL; + else if(num > 0xffff) { + failf(data, "Illegal port number in EPSV reply"); + return CURLE_FTP_WEIRD_PASV_REPLY; + } + if(ptr) { + ftpc->newport = (unsigned short)(num & 0xffff); + ftpc->newhost = strdup(control_address(conn)); + if(!ftpc->newhost) + return CURLE_OUT_OF_MEMORY; + } + } + else + ptr = NULL; + } + if(!ptr) { + failf(data, "Weirdly formatted EPSV reply"); + return CURLE_FTP_WEIRD_PASV_REPLY; + } + } + else if((ftpc->count1 == 1) && + (ftpcode == 227)) { + /* positive PASV response */ + unsigned int ip[6]; + + /* + * Scan for a sequence of six comma-separated numbers and use them as + * IP+port indicators. + * + * Found reply-strings include: + * "227 Entering Passive Mode (127,0,0,1,4,51)" + * "227 Data transfer will passively listen to 127,0,0,1,4,51" + * "227 Entering passive mode. 127,0,0,1,4,51" + */ + while(*str) { + if(match_pasv_6nums(str, ip)) + break; + str++; + } + + if(!*str) { + failf(data, "Couldn't interpret the 227-response"); + return CURLE_FTP_WEIRD_227_FORMAT; + } + + /* we got OK from server */ + if(data->set.ftp_skip_ip) { + /* told to ignore the remotely given IP but instead use the host we used + for the control connection */ + infof(data, "Skip %u.%u.%u.%u for data connection, reuse %s instead", + ip[0], ip[1], ip[2], ip[3], + conn->host.name); + ftpc->newhost = strdup(control_address(conn)); + } + else + ftpc->newhost = aprintf("%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]); + + if(!ftpc->newhost) + return CURLE_OUT_OF_MEMORY; + + ftpc->newport = (unsigned short)(((ip[4]<<8) + ip[5]) & 0xffff); + } + else if(ftpc->count1 == 0) { + /* EPSV failed, move on to PASV */ + return ftp_epsv_disable(data, conn); + } + else { + failf(data, "Bad PASV/EPSV response: %03d", ftpcode); + return CURLE_FTP_WEIRD_PASV_REPLY; + } + +#ifndef CURL_DISABLE_PROXY + if(conn->bits.proxy) { + /* + * This connection uses a proxy and we need to connect to the proxy again + * here. We don't want to rely on a former host lookup that might've + * expired now, instead we remake the lookup here and now! + */ + const char * const host_name = conn->bits.socksproxy ? + conn->socks_proxy.host.name : conn->http_proxy.host.name; + rc = Curl_resolv(data, host_name, conn->primary.remote_port, FALSE, &addr); + if(rc == CURLRESOLV_PENDING) + /* BLOCKING, ignores the return code but 'addr' will be NULL in + case of failure */ + (void)Curl_resolver_wait_resolv(data, &addr); + + /* we connect to the proxy's port */ + connectport = (unsigned short)conn->primary.remote_port; + + if(!addr) { + failf(data, "Can't resolve proxy host %s:%hu", host_name, connectport); + return CURLE_COULDNT_RESOLVE_PROXY; + } + } + else +#endif + { + /* normal, direct, ftp connection */ + DEBUGASSERT(ftpc->newhost); + + /* postponed address resolution in case of tcp fastopen */ + if(conn->bits.tcp_fastopen && !conn->bits.reuse && !ftpc->newhost[0]) { + Curl_conn_ev_update_info(data, conn); + Curl_safefree(ftpc->newhost); + ftpc->newhost = strdup(control_address(conn)); + if(!ftpc->newhost) + return CURLE_OUT_OF_MEMORY; + } + + rc = Curl_resolv(data, ftpc->newhost, ftpc->newport, FALSE, &addr); + if(rc == CURLRESOLV_PENDING) + /* BLOCKING */ + (void)Curl_resolver_wait_resolv(data, &addr); + + connectport = ftpc->newport; /* we connect to the remote port */ + + if(!addr) { + failf(data, "Can't resolve new host %s:%hu", ftpc->newhost, connectport); + return CURLE_FTP_CANT_GET_HOST; + } + } + + result = Curl_conn_setup(data, conn, SECONDARYSOCKET, addr, + conn->bits.ftp_use_data_ssl? + CURL_CF_SSL_ENABLE : CURL_CF_SSL_DISABLE); + + if(result) { + Curl_resolv_unlock(data, addr); /* we're done using this address */ + if(ftpc->count1 == 0 && ftpcode == 229) + return ftp_epsv_disable(data, conn); + + return result; + } + + + /* + * When this is used from the multi interface, this might've returned with + * the 'connected' set to FALSE and thus we are now awaiting a non-blocking + * connect to connect. + */ + + if(data->set.verbose) + /* this just dumps information about this second connection */ + ftp_pasv_verbose(data, addr->addr, ftpc->newhost, connectport); + + Curl_resolv_unlock(data, addr); /* we're done using this address */ + + Curl_safefree(conn->secondaryhostname); + conn->secondary_port = ftpc->newport; + conn->secondaryhostname = strdup(ftpc->newhost); + if(!conn->secondaryhostname) + return CURLE_OUT_OF_MEMORY; + + conn->bits.do_more = TRUE; + ftp_state(data, FTP_STOP); /* this phase is completed */ + + return result; +} + +static CURLcode ftp_state_port_resp(struct Curl_easy *data, + int ftpcode) +{ + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = &conn->proto.ftpc; + ftpport fcmd = (ftpport)ftpc->count1; + CURLcode result = CURLE_OK; + + /* The FTP spec tells a positive response should have code 200. + Be more permissive here to tolerate deviant servers. */ + if(ftpcode / 100 != 2) { + /* the command failed */ + + if(EPRT == fcmd) { + infof(data, "disabling EPRT usage"); + conn->bits.ftp_use_eprt = FALSE; + } + fcmd++; + + if(fcmd == DONE) { + failf(data, "Failed to do PORT"); + result = CURLE_FTP_PORT_FAILED; + } + else + /* try next */ + result = ftp_state_use_port(data, fcmd); + } + else { + infof(data, "Connect data stream actively"); + ftp_state(data, FTP_STOP); /* end of DO phase */ + result = ftp_dophase_done(data, FALSE); + } + + return result; +} + +static int twodigit(const char *p) +{ + return (p[0]-'0') * 10 + (p[1]-'0'); +} + +static bool ftp_213_date(const char *p, int *year, int *month, int *day, + int *hour, int *minute, int *second) +{ + size_t len = strlen(p); + if(len < 14) + return FALSE; + *year = twodigit(&p[0]) * 100 + twodigit(&p[2]); + *month = twodigit(&p[4]); + *day = twodigit(&p[6]); + *hour = twodigit(&p[8]); + *minute = twodigit(&p[10]); + *second = twodigit(&p[12]); + + if((*month > 12) || (*day > 31) || (*hour > 23) || (*minute > 59) || + (*second > 60)) + return FALSE; + return TRUE; +} + +static CURLcode client_write_header(struct Curl_easy *data, + char *buf, size_t blen) +{ + /* Some replies from an FTP server are written to the client + * as CLIENTWRITE_HEADER, formatted as if they came from a + * HTTP conversation. + * In all protocols, CLIENTWRITE_HEADER data is only passed to + * the body write callback when data->set.include_header is set + * via CURLOPT_HEADER. + * For historic reasons, FTP never played this game and expects + * all its HEADERs to do that always. Set that flag during the + * call to Curl_client_write() so it does the right thing. + * + * Notice that we cannot enable this flag for FTP in general, + * as an FTP transfer might involve a HTTP proxy connection and + * headers from CONNECT should not automatically be part of the + * output. */ + CURLcode result; + int save = data->set.include_header; + data->set.include_header = TRUE; + result = Curl_client_write(data, CLIENTWRITE_HEADER, buf, blen); + data->set.include_header = save? TRUE:FALSE; + return result; +} + +static CURLcode ftp_state_mdtm_resp(struct Curl_easy *data, + int ftpcode) +{ + CURLcode result = CURLE_OK; + struct FTP *ftp = data->req.p.ftp; + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = &conn->proto.ftpc; + + switch(ftpcode) { + case 213: + { + /* we got a time. Format should be: "YYYYMMDDHHMMSS[.sss]" where the + last .sss part is optional and means fractions of a second */ + int year, month, day, hour, minute, second; + struct pingpong *pp = &ftpc->pp; + char *resp = Curl_dyn_ptr(&pp->recvbuf) + 4; + if(ftp_213_date(resp, &year, &month, &day, &hour, &minute, &second)) { + /* we have a time, reformat it */ + char timebuf[24]; + msnprintf(timebuf, sizeof(timebuf), + "%04d%02d%02d %02d:%02d:%02d GMT", + year, month, day, hour, minute, second); + /* now, convert this into a time() value: */ + data->info.filetime = Curl_getdate_capped(timebuf); + } + +#ifdef CURL_FTP_HTTPSTYLE_HEAD + /* If we asked for a time of the file and we actually got one as well, + we "emulate" an HTTP-style header in our output. */ + + if(data->req.no_body && + ftpc->file && + data->set.get_filetime && + (data->info.filetime >= 0) ) { + char headerbuf[128]; + int headerbuflen; + time_t filetime = data->info.filetime; + struct tm buffer; + const struct tm *tm = &buffer; + + result = Curl_gmtime(filetime, &buffer); + if(result) + return result; + + /* format: "Tue, 15 Nov 1994 12:45:26" */ + headerbuflen = msnprintf(headerbuf, sizeof(headerbuf), + "Last-Modified: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n", + Curl_wkday[tm->tm_wday?tm->tm_wday-1:6], + tm->tm_mday, + Curl_month[tm->tm_mon], + tm->tm_year + 1900, + tm->tm_hour, + tm->tm_min, + tm->tm_sec); + result = client_write_header(data, headerbuf, headerbuflen); + if(result) + return result; + } /* end of a ridiculous amount of conditionals */ +#endif + } + break; + default: + infof(data, "unsupported MDTM reply format"); + break; + case 550: /* 550 is used for several different problems, e.g. + "No such file or directory" or "Permission denied". + It does not mean that the file does not exist at all. */ + infof(data, "MDTM failed: file does not exist or permission problem," + " continuing"); + break; + } + + if(data->set.timecondition) { + if((data->info.filetime > 0) && (data->set.timevalue > 0)) { + switch(data->set.timecondition) { + case CURL_TIMECOND_IFMODSINCE: + default: + if(data->info.filetime <= data->set.timevalue) { + infof(data, "The requested document is not new enough"); + ftp->transfer = PPTRANSFER_NONE; /* mark to not transfer data */ + data->info.timecond = TRUE; + ftp_state(data, FTP_STOP); + return CURLE_OK; + } + break; + case CURL_TIMECOND_IFUNMODSINCE: + if(data->info.filetime > data->set.timevalue) { + infof(data, "The requested document is not old enough"); + ftp->transfer = PPTRANSFER_NONE; /* mark to not transfer data */ + data->info.timecond = TRUE; + ftp_state(data, FTP_STOP); + return CURLE_OK; + } + break; + } /* switch */ + } + else { + infof(data, "Skipping time comparison"); + } + } + + if(!result) + result = ftp_state_type(data); + + return result; +} + +static CURLcode ftp_state_type_resp(struct Curl_easy *data, + int ftpcode, + ftpstate instate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + if(ftpcode/100 != 2) { + /* "sasserftpd" and "(u)r(x)bot ftpd" both responds with 226 after a + successful 'TYPE I'. While that is not as RFC959 says, it is still a + positive response code and we allow that. */ + failf(data, "Couldn't set desired mode"); + return CURLE_FTP_COULDNT_SET_TYPE; + } + if(ftpcode != 200) + infof(data, "Got a %03d response code instead of the assumed 200", + ftpcode); + + if(instate == FTP_TYPE) + result = ftp_state_size(data, conn); + else if(instate == FTP_LIST_TYPE) + result = ftp_state_list(data); + else if(instate == FTP_RETR_TYPE) + result = ftp_state_retr_prequote(data); + else if(instate == FTP_STOR_TYPE) + result = ftp_state_stor_prequote(data); + + return result; +} + +static CURLcode ftp_state_retr(struct Curl_easy *data, + curl_off_t filesize) +{ + CURLcode result = CURLE_OK; + struct FTP *ftp = data->req.p.ftp; + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = &conn->proto.ftpc; + + CURL_TRC_FTP(data, "[%s] ftp_state_retr()", FTP_DSTATE(data)); + if(data->set.max_filesize && (filesize > data->set.max_filesize)) { + failf(data, "Maximum file size exceeded"); + return CURLE_FILESIZE_EXCEEDED; + } + ftp->downloadsize = filesize; + + if(data->state.resume_from) { + /* We always (attempt to) get the size of downloads, so it is done before + this even when not doing resumes. */ + if(filesize == -1) { + infof(data, "ftp server doesn't support SIZE"); + /* We couldn't get the size and therefore we can't know if there really + is a part of the file left to get, although the server will just + close the connection when we start the connection so it won't cause + us any harm, just not make us exit as nicely. */ + } + else { + /* We got a file size report, so we check that there actually is a + part of the file left to get, or else we go home. */ + if(data->state.resume_from< 0) { + /* We're supposed to download the last abs(from) bytes */ + if(filesize < -data->state.resume_from) { + failf(data, "Offset (%" CURL_FORMAT_CURL_OFF_T + ") was beyond file size (%" CURL_FORMAT_CURL_OFF_T ")", + data->state.resume_from, filesize); + return CURLE_BAD_DOWNLOAD_RESUME; + } + /* convert to size to download */ + ftp->downloadsize = -data->state.resume_from; + /* download from where? */ + data->state.resume_from = filesize - ftp->downloadsize; + } + else { + if(filesize < data->state.resume_from) { + failf(data, "Offset (%" CURL_FORMAT_CURL_OFF_T + ") was beyond file size (%" CURL_FORMAT_CURL_OFF_T ")", + data->state.resume_from, filesize); + return CURLE_BAD_DOWNLOAD_RESUME; + } + /* Now store the number of bytes we are expected to download */ + ftp->downloadsize = filesize-data->state.resume_from; + } + } + + if(ftp->downloadsize == 0) { + /* no data to transfer */ + Curl_xfer_setup(data, -1, -1, FALSE, -1); + infof(data, "File already completely downloaded"); + + /* Set ->transfer so that we won't get any error in ftp_done() + * because we didn't transfer the any file */ + ftp->transfer = PPTRANSFER_NONE; + ftp_state(data, FTP_STOP); + return CURLE_OK; + } + + /* Set resume file transfer offset */ + infof(data, "Instructs server to resume from offset %" + CURL_FORMAT_CURL_OFF_T, data->state.resume_from); + + result = Curl_pp_sendf(data, &ftpc->pp, "REST %" CURL_FORMAT_CURL_OFF_T, + data->state.resume_from); + if(!result) + ftp_state(data, FTP_RETR_REST); + } + else { + /* no resume */ + result = Curl_pp_sendf(data, &ftpc->pp, "RETR %s", ftpc->file); + if(!result) + ftp_state(data, FTP_RETR); + } + + return result; +} + +static CURLcode ftp_state_size_resp(struct Curl_easy *data, + int ftpcode, + ftpstate instate) +{ + CURLcode result = CURLE_OK; + curl_off_t filesize = -1; + char *buf = Curl_dyn_ptr(&data->conn->proto.ftpc.pp.recvbuf); + size_t len = data->conn->proto.ftpc.pp.nfinal; + + /* get the size from the ascii string: */ + if(ftpcode == 213) { + /* To allow servers to prepend "rubbish" in the response string, we scan + for all the digits at the end of the response and parse only those as a + number. */ + char *start = &buf[4]; + char *fdigit = memchr(start, '\r', len); + if(fdigit) { + fdigit--; + if(*fdigit == '\n') + fdigit--; + while(ISDIGIT(fdigit[-1]) && (fdigit > start)) + fdigit--; + } + else + fdigit = start; + /* ignores parsing errors, which will make the size remain unknown */ + (void)curlx_strtoofft(fdigit, NULL, 10, &filesize); + + } + else if(ftpcode == 550) { /* "No such file or directory" */ + /* allow a SIZE failure for (resumed) uploads, when probing what command + to use */ + if(instate != FTP_STOR_SIZE) { + failf(data, "The file does not exist"); + return CURLE_REMOTE_FILE_NOT_FOUND; + } + } + + if(instate == FTP_SIZE) { +#ifdef CURL_FTP_HTTPSTYLE_HEAD + if(-1 != filesize) { + char clbuf[128]; + int clbuflen = msnprintf(clbuf, sizeof(clbuf), + "Content-Length: %" CURL_FORMAT_CURL_OFF_T "\r\n", filesize); + result = client_write_header(data, clbuf, clbuflen); + if(result) + return result; + } +#endif + Curl_pgrsSetDownloadSize(data, filesize); + result = ftp_state_rest(data, data->conn); + } + else if(instate == FTP_RETR_SIZE) { + Curl_pgrsSetDownloadSize(data, filesize); + result = ftp_state_retr(data, filesize); + } + else if(instate == FTP_STOR_SIZE) { + data->state.resume_from = filesize; + result = ftp_state_ul_setup(data, TRUE); + } + + return result; +} + +static CURLcode ftp_state_rest_resp(struct Curl_easy *data, + struct connectdata *conn, + int ftpcode, + ftpstate instate) +{ + CURLcode result = CURLE_OK; + struct ftp_conn *ftpc = &conn->proto.ftpc; + + switch(instate) { + case FTP_REST: + default: +#ifdef CURL_FTP_HTTPSTYLE_HEAD + if(ftpcode == 350) { + char buffer[24]= { "Accept-ranges: bytes\r\n" }; + result = client_write_header(data, buffer, strlen(buffer)); + if(result) + return result; + } +#endif + result = ftp_state_prepare_transfer(data); + break; + + case FTP_RETR_REST: + if(ftpcode != 350) { + failf(data, "Couldn't use REST"); + result = CURLE_FTP_COULDNT_USE_REST; + } + else { + result = Curl_pp_sendf(data, &ftpc->pp, "RETR %s", ftpc->file); + if(!result) + ftp_state(data, FTP_RETR); + } + break; + } + + return result; +} + +static CURLcode ftp_state_stor_resp(struct Curl_easy *data, + int ftpcode, ftpstate instate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + if(ftpcode >= 400) { + failf(data, "Failed FTP upload: %0d", ftpcode); + ftp_state(data, FTP_STOP); + /* oops, we never close the sockets! */ + return CURLE_UPLOAD_FAILED; + } + + conn->proto.ftpc.state_saved = instate; + + /* PORT means we are now awaiting the server to connect to us. */ + if(data->set.ftp_use_port) { + bool connected; + + ftp_state(data, FTP_STOP); /* no longer in STOR state */ + + result = AllowServerConnect(data, &connected); + if(result) + return result; + + if(!connected) { + struct ftp_conn *ftpc = &conn->proto.ftpc; + infof(data, "Data conn was not available immediately"); + ftpc->wait_data_conn = TRUE; + } + + return CURLE_OK; + } + return InitiateTransfer(data); +} + +/* for LIST and RETR responses */ +static CURLcode ftp_state_get_resp(struct Curl_easy *data, + int ftpcode, + ftpstate instate) +{ + CURLcode result = CURLE_OK; + struct FTP *ftp = data->req.p.ftp; + struct connectdata *conn = data->conn; + + if((ftpcode == 150) || (ftpcode == 125)) { + + /* + A; + 150 Opening BINARY mode data connection for /etc/passwd (2241 + bytes). (ok, the file is being transferred) + + B: + 150 Opening ASCII mode data connection for /bin/ls + + C: + 150 ASCII data connection for /bin/ls (137.167.104.91,37445) (0 bytes). + + D: + 150 Opening ASCII mode data connection for [file] (0.0.0.0,0) (545 bytes) + + E: + 125 Data connection already open; Transfer starting. */ + + curl_off_t size = -1; /* default unknown size */ + + + /* + * It appears that there are FTP-servers that return size 0 for files when + * SIZE is used on the file while being in BINARY mode. To work around + * that (stupid) behavior, we attempt to parse the RETR response even if + * the SIZE returned size zero. + * + * Debugging help from Salvatore Sorrentino on February 26, 2003. + */ + + if((instate != FTP_LIST) && + !data->state.prefer_ascii && + !data->set.ignorecl && + (ftp->downloadsize < 1)) { + /* + * It seems directory listings either don't show the size or very + * often uses size 0 anyway. ASCII transfers may very well turn out + * that the transferred amount of data is not the same as this line + * tells, why using this number in those cases only confuses us. + * + * Example D above makes this parsing a little tricky */ + char *bytes; + char *buf = Curl_dyn_ptr(&conn->proto.ftpc.pp.recvbuf); + bytes = strstr(buf, " bytes"); + if(bytes) { + long in = (long)(--bytes-buf); + /* this is a hint there is size information in there! ;-) */ + while(--in) { + /* scan for the left parenthesis and break there */ + if('(' == *bytes) + break; + /* skip only digits */ + if(!ISDIGIT(*bytes)) { + bytes = NULL; + break; + } + /* one more estep backwards */ + bytes--; + } + /* if we have nothing but digits: */ + if(bytes) { + ++bytes; + /* get the number! */ + (void)curlx_strtoofft(bytes, NULL, 10, &size); + } + } + } + else if(ftp->downloadsize > -1) + size = ftp->downloadsize; + + if(size > data->req.maxdownload && data->req.maxdownload > 0) + size = data->req.size = data->req.maxdownload; + else if((instate != FTP_LIST) && (data->state.prefer_ascii)) + size = -1; /* kludge for servers that understate ASCII mode file size */ + + infof(data, "Maxdownload = %" CURL_FORMAT_CURL_OFF_T, + data->req.maxdownload); + + if(instate != FTP_LIST) + infof(data, "Getting file with size: %" CURL_FORMAT_CURL_OFF_T, + size); + + /* FTP download: */ + conn->proto.ftpc.state_saved = instate; + conn->proto.ftpc.retr_size_saved = size; + + if(data->set.ftp_use_port) { + bool connected; + + result = AllowServerConnect(data, &connected); + if(result) + return result; + + if(!connected) { + struct ftp_conn *ftpc = &conn->proto.ftpc; + infof(data, "Data conn was not available immediately"); + ftp_state(data, FTP_STOP); + ftpc->wait_data_conn = TRUE; + } + } + else + return InitiateTransfer(data); + } + else { + if((instate == FTP_LIST) && (ftpcode == 450)) { + /* simply no matching files in the dir listing */ + ftp->transfer = PPTRANSFER_NONE; /* don't download anything */ + ftp_state(data, FTP_STOP); /* this phase is over */ + } + else { + failf(data, "RETR response: %03d", ftpcode); + return instate == FTP_RETR && ftpcode == 550? + CURLE_REMOTE_FILE_NOT_FOUND: + CURLE_FTP_COULDNT_RETR_FILE; + } + } + + return result; +} + +/* after USER, PASS and ACCT */ +static CURLcode ftp_state_loggedin(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + if(conn->bits.ftp_use_control_ssl) { + /* PBSZ = PROTECTION BUFFER SIZE. + + The 'draft-murray-auth-ftp-ssl' (draft 12, page 7) says: + + Specifically, the PROT command MUST be preceded by a PBSZ + command and a PBSZ command MUST be preceded by a successful + security data exchange (the TLS negotiation in this case) + + ... (and on page 8): + + Thus the PBSZ command must still be issued, but must have a + parameter of '0' to indicate that no buffering is taking place + and the data connection should not be encapsulated. + */ + result = Curl_pp_sendf(data, &conn->proto.ftpc.pp, "PBSZ %d", 0); + if(!result) + ftp_state(data, FTP_PBSZ); + } + else { + result = ftp_state_pwd(data, conn); + } + return result; +} + +/* for USER and PASS responses */ +static CURLcode ftp_state_user_resp(struct Curl_easy *data, + int ftpcode) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = &conn->proto.ftpc; + + /* some need password anyway, and others just return 2xx ignored */ + if((ftpcode == 331) && (ftpc->state == FTP_USER)) { + /* 331 Password required for ... + (the server requires to send the user's password too) */ + result = Curl_pp_sendf(data, &ftpc->pp, "PASS %s", + conn->passwd?conn->passwd:""); + if(!result) + ftp_state(data, FTP_PASS); + } + else if(ftpcode/100 == 2) { + /* 230 User ... logged in. + (the user logged in with or without password) */ + result = ftp_state_loggedin(data); + } + else if(ftpcode == 332) { + if(data->set.str[STRING_FTP_ACCOUNT]) { + result = Curl_pp_sendf(data, &ftpc->pp, "ACCT %s", + data->set.str[STRING_FTP_ACCOUNT]); + if(!result) + ftp_state(data, FTP_ACCT); + } + else { + failf(data, "ACCT requested but none available"); + result = CURLE_LOGIN_DENIED; + } + } + else { + /* All other response codes, like: + + 530 User ... access denied + (the server denies to log the specified user) */ + + if(data->set.str[STRING_FTP_ALTERNATIVE_TO_USER] && + !ftpc->ftp_trying_alternative) { + /* Ok, USER failed. Let's try the supplied command. */ + result = + Curl_pp_sendf(data, &ftpc->pp, "%s", + data->set.str[STRING_FTP_ALTERNATIVE_TO_USER]); + if(!result) { + ftpc->ftp_trying_alternative = TRUE; + ftp_state(data, FTP_USER); + } + } + else { + failf(data, "Access denied: %03d", ftpcode); + result = CURLE_LOGIN_DENIED; + } + } + return result; +} + +/* for ACCT response */ +static CURLcode ftp_state_acct_resp(struct Curl_easy *data, + int ftpcode) +{ + CURLcode result = CURLE_OK; + if(ftpcode != 230) { + failf(data, "ACCT rejected by server: %03d", ftpcode); + result = CURLE_FTP_WEIRD_PASS_REPLY; /* FIX */ + } + else + result = ftp_state_loggedin(data); + + return result; +} + + +static CURLcode ftp_statemachine(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result; + int ftpcode; + struct ftp_conn *ftpc = &conn->proto.ftpc; + struct pingpong *pp = &ftpc->pp; + static const char * const ftpauth[] = { "SSL", "TLS" }; + size_t nread = 0; + + if(pp->sendleft) + return Curl_pp_flushsend(data, pp); + + result = ftp_readresp(data, FIRSTSOCKET, pp, &ftpcode, &nread); + if(result) + return result; + + if(ftpcode) { + /* we have now received a full FTP server response */ + switch(ftpc->state) { + case FTP_WAIT220: + if(ftpcode == 230) { + /* 230 User logged in - already! Take as 220 if TLS required. */ + if(data->set.use_ssl <= CURLUSESSL_TRY || + conn->bits.ftp_use_control_ssl) + return ftp_state_user_resp(data, ftpcode); + } + else if(ftpcode != 220) { + failf(data, "Got a %03d ftp-server response when 220 was expected", + ftpcode); + return CURLE_WEIRD_SERVER_REPLY; + } + + /* We have received a 220 response fine, now we proceed. */ +#ifdef HAVE_GSSAPI + if(data->set.krb) { + /* If not anonymous login, try a secure login. Note that this + procedure is still BLOCKING. */ + + Curl_sec_request_prot(conn, "private"); + /* We set private first as default, in case the line below fails to + set a valid level */ + Curl_sec_request_prot(conn, data->set.str[STRING_KRB_LEVEL]); + + if(Curl_sec_login(data, conn)) { + failf(data, "secure login failed"); + return CURLE_WEIRD_SERVER_REPLY; + } + infof(data, "Authentication successful"); + } +#endif + + if(data->set.use_ssl && !conn->bits.ftp_use_control_ssl) { + /* We don't have a SSL/TLS control connection yet, but FTPS is + requested. Try a FTPS connection now */ + + ftpc->count3 = 0; + switch(data->set.ftpsslauth) { + case CURLFTPAUTH_DEFAULT: + case CURLFTPAUTH_SSL: + ftpc->count2 = 1; /* add one to get next */ + ftpc->count1 = 0; + break; + case CURLFTPAUTH_TLS: + ftpc->count2 = -1; /* subtract one to get next */ + ftpc->count1 = 1; + break; + default: + failf(data, "unsupported parameter to CURLOPT_FTPSSLAUTH: %d", + (int)data->set.ftpsslauth); + return CURLE_UNKNOWN_OPTION; /* we don't know what to do */ + } + result = Curl_pp_sendf(data, &ftpc->pp, "AUTH %s", + ftpauth[ftpc->count1]); + if(!result) + ftp_state(data, FTP_AUTH); + } + else + result = ftp_state_user(data, conn); + break; + + case FTP_AUTH: + /* we have gotten the response to a previous AUTH command */ + + if(pp->overflow) + return CURLE_WEIRD_SERVER_REPLY; /* Forbid pipelining in response. */ + + /* RFC2228 (page 5) says: + * + * If the server is willing to accept the named security mechanism, + * and does not require any security data, it must respond with + * reply code 234/334. + */ + + if((ftpcode == 234) || (ftpcode == 334)) { + /* this was BLOCKING, keep it so for now */ + bool done; + if(!Curl_conn_is_ssl(conn, FIRSTSOCKET)) { + result = Curl_ssl_cfilter_add(data, conn, FIRSTSOCKET); + if(result) { + /* we failed and bail out */ + return CURLE_USE_SSL_FAILED; + } + } + result = Curl_conn_connect(data, FIRSTSOCKET, TRUE, &done); + if(!result) { + conn->bits.ftp_use_data_ssl = FALSE; /* clear-text data */ + conn->bits.ftp_use_control_ssl = TRUE; /* SSL on control */ + result = ftp_state_user(data, conn); + } + } + else if(ftpc->count3 < 1) { + ftpc->count3++; + ftpc->count1 += ftpc->count2; /* get next attempt */ + result = Curl_pp_sendf(data, &ftpc->pp, "AUTH %s", + ftpauth[ftpc->count1]); + /* remain in this same state */ + } + else { + if(data->set.use_ssl > CURLUSESSL_TRY) + /* we failed and CURLUSESSL_CONTROL or CURLUSESSL_ALL is set */ + result = CURLE_USE_SSL_FAILED; + else + /* ignore the failure and continue */ + result = ftp_state_user(data, conn); + } + break; + + case FTP_USER: + case FTP_PASS: + result = ftp_state_user_resp(data, ftpcode); + break; + + case FTP_ACCT: + result = ftp_state_acct_resp(data, ftpcode); + break; + + case FTP_PBSZ: + result = + Curl_pp_sendf(data, &ftpc->pp, "PROT %c", + data->set.use_ssl == CURLUSESSL_CONTROL ? 'C' : 'P'); + if(!result) + ftp_state(data, FTP_PROT); + break; + + case FTP_PROT: + if(ftpcode/100 == 2) + /* We have enabled SSL for the data connection! */ + conn->bits.ftp_use_data_ssl = + (data->set.use_ssl != CURLUSESSL_CONTROL) ? TRUE : FALSE; + /* FTP servers typically responds with 500 if they decide to reject + our 'P' request */ + else if(data->set.use_ssl > CURLUSESSL_CONTROL) + /* we failed and bails out */ + return CURLE_USE_SSL_FAILED; + + if(data->set.ftp_ccc) { + /* CCC - Clear Command Channel + */ + result = Curl_pp_sendf(data, &ftpc->pp, "%s", "CCC"); + if(!result) + ftp_state(data, FTP_CCC); + } + else + result = ftp_state_pwd(data, conn); + break; + + case FTP_CCC: + if(ftpcode < 500) { + /* First shut down the SSL layer (note: this call will block) */ + result = Curl_ssl_cfilter_remove(data, FIRSTSOCKET); + + if(result) + failf(data, "Failed to clear the command channel (CCC)"); + } + if(!result) + /* Then continue as normal */ + result = ftp_state_pwd(data, conn); + break; + + case FTP_PWD: + if(ftpcode == 257) { + char *ptr = Curl_dyn_ptr(&pp->recvbuf) + 4; /* start on the first + letter */ + bool entry_extracted = FALSE; + struct dynbuf out; + Curl_dyn_init(&out, 1000); + + /* Reply format is like + 257[rubbish]"" and the + RFC959 says + + The directory name can contain any character; embedded + double-quotes should be escaped by double-quotes (the + "quote-doubling" convention). + */ + + /* scan for the first double-quote for non-standard responses */ + while(*ptr != '\n' && *ptr != '\0' && *ptr != '"') + ptr++; + + if('\"' == *ptr) { + /* it started good */ + for(ptr++; *ptr; ptr++) { + if('\"' == *ptr) { + if('\"' == ptr[1]) { + /* "quote-doubling" */ + result = Curl_dyn_addn(&out, &ptr[1], 1); + ptr++; + } + else { + /* end of path */ + if(Curl_dyn_len(&out)) + entry_extracted = TRUE; + break; /* get out of this loop */ + } + } + else + result = Curl_dyn_addn(&out, ptr, 1); + if(result) + return result; + } + } + if(entry_extracted) { + /* If the path name does not look like an absolute path (i.e.: it + does not start with a '/'), we probably need some server-dependent + adjustments. For example, this is the case when connecting to + an OS400 FTP server: this server supports two name syntaxes, + the default one being incompatible with standard paths. In + addition, this server switches automatically to the regular path + syntax when one is encountered in a command: this results in + having an entrypath in the wrong syntax when later used in CWD. + The method used here is to check the server OS: we do it only + if the path name looks strange to minimize overhead on other + systems. */ + char *dir = Curl_dyn_ptr(&out); + + if(!ftpc->server_os && dir[0] != '/') { + result = Curl_pp_sendf(data, &ftpc->pp, "%s", "SYST"); + if(result) { + free(dir); + return result; + } + Curl_safefree(ftpc->entrypath); + ftpc->entrypath = dir; /* remember this */ + infof(data, "Entry path is '%s'", ftpc->entrypath); + /* also save it where getinfo can access it: */ + data->state.most_recent_ftp_entrypath = ftpc->entrypath; + ftp_state(data, FTP_SYST); + break; + } + + Curl_safefree(ftpc->entrypath); + ftpc->entrypath = dir; /* remember this */ + infof(data, "Entry path is '%s'", ftpc->entrypath); + /* also save it where getinfo can access it: */ + data->state.most_recent_ftp_entrypath = ftpc->entrypath; + } + else { + /* couldn't get the path */ + Curl_dyn_free(&out); + infof(data, "Failed to figure out path"); + } + } + ftp_state(data, FTP_STOP); /* we are done with the CONNECT phase! */ + CURL_TRC_FTP(data, "[%s] protocol connect phase DONE", FTP_DSTATE(data)); + break; + + case FTP_SYST: + if(ftpcode == 215) { + char *ptr = Curl_dyn_ptr(&pp->recvbuf) + 4; /* start on the first + letter */ + char *os; + char *start; + + /* Reply format is like + 215 + */ + while(*ptr == ' ') + ptr++; + for(start = ptr; *ptr && *ptr != ' '; ptr++) + ; + os = Curl_memdup0(start, ptr - start); + if(!os) + return CURLE_OUT_OF_MEMORY; + + /* Check for special servers here. */ + if(strcasecompare(os, "OS/400")) { + /* Force OS400 name format 1. */ + result = Curl_pp_sendf(data, &ftpc->pp, "%s", "SITE NAMEFMT 1"); + if(result) { + free(os); + return result; + } + /* remember target server OS */ + Curl_safefree(ftpc->server_os); + ftpc->server_os = os; + ftp_state(data, FTP_NAMEFMT); + break; + } + /* Nothing special for the target server. */ + /* remember target server OS */ + Curl_safefree(ftpc->server_os); + ftpc->server_os = os; + } + else { + /* Cannot identify server OS. Continue anyway and cross fingers. */ + } + + ftp_state(data, FTP_STOP); /* we are done with the CONNECT phase! */ + CURL_TRC_FTP(data, "[%s] protocol connect phase DONE", FTP_DSTATE(data)); + break; + + case FTP_NAMEFMT: + if(ftpcode == 250) { + /* Name format change successful: reload initial path. */ + ftp_state_pwd(data, conn); + break; + } + + ftp_state(data, FTP_STOP); /* we are done with the CONNECT phase! */ + CURL_TRC_FTP(data, "[%s] protocol connect phase DONE", FTP_DSTATE(data)); + break; + + case FTP_QUOTE: + case FTP_POSTQUOTE: + case FTP_RETR_PREQUOTE: + case FTP_STOR_PREQUOTE: + if((ftpcode >= 400) && !ftpc->count2) { + /* failure response code, and not allowed to fail */ + failf(data, "QUOT command failed with %03d", ftpcode); + result = CURLE_QUOTE_ERROR; + } + else + result = ftp_state_quote(data, FALSE, ftpc->state); + break; + + case FTP_CWD: + if(ftpcode/100 != 2) { + /* failure to CWD there */ + if(data->set.ftp_create_missing_dirs && + ftpc->cwdcount && !ftpc->count2) { + /* try making it */ + ftpc->count2++; /* counter to prevent CWD-MKD loops */ + + /* count3 is set to allow MKD to fail once per dir. In the case when + CWD fails and then MKD fails (due to another session raced it to + create the dir) this then allows for a second try to CWD to it. */ + ftpc->count3 = (data->set.ftp_create_missing_dirs == 2) ? 1 : 0; + + result = Curl_pp_sendf(data, &ftpc->pp, "MKD %s", + ftpc->dirs[ftpc->cwdcount - 1]); + if(!result) + ftp_state(data, FTP_MKD); + } + else { + /* return failure */ + failf(data, "Server denied you to change to the given directory"); + ftpc->cwdfail = TRUE; /* don't remember this path as we failed + to enter it */ + result = CURLE_REMOTE_ACCESS_DENIED; + } + } + else { + /* success */ + ftpc->count2 = 0; + if(++ftpc->cwdcount <= ftpc->dirdepth) + /* send next CWD */ + result = Curl_pp_sendf(data, &ftpc->pp, "CWD %s", + ftpc->dirs[ftpc->cwdcount - 1]); + else + result = ftp_state_mdtm(data); + } + break; + + case FTP_MKD: + if((ftpcode/100 != 2) && !ftpc->count3--) { + /* failure to MKD the dir */ + failf(data, "Failed to MKD dir: %03d", ftpcode); + result = CURLE_REMOTE_ACCESS_DENIED; + } + else { + ftp_state(data, FTP_CWD); + /* send CWD */ + result = Curl_pp_sendf(data, &ftpc->pp, "CWD %s", + ftpc->dirs[ftpc->cwdcount - 1]); + } + break; + + case FTP_MDTM: + result = ftp_state_mdtm_resp(data, ftpcode); + break; + + case FTP_TYPE: + case FTP_LIST_TYPE: + case FTP_RETR_TYPE: + case FTP_STOR_TYPE: + result = ftp_state_type_resp(data, ftpcode, ftpc->state); + break; + + case FTP_SIZE: + case FTP_RETR_SIZE: + case FTP_STOR_SIZE: + result = ftp_state_size_resp(data, ftpcode, ftpc->state); + break; + + case FTP_REST: + case FTP_RETR_REST: + result = ftp_state_rest_resp(data, conn, ftpcode, ftpc->state); + break; + + case FTP_PRET: + if(ftpcode != 200) { + /* there only is this one standard OK return code. */ + failf(data, "PRET command not accepted: %03d", ftpcode); + return CURLE_FTP_PRET_FAILED; + } + result = ftp_state_use_pasv(data, conn); + break; + + case FTP_PASV: + result = ftp_state_pasv_resp(data, ftpcode); + break; + + case FTP_PORT: + result = ftp_state_port_resp(data, ftpcode); + break; + + case FTP_LIST: + case FTP_RETR: + result = ftp_state_get_resp(data, ftpcode, ftpc->state); + break; + + case FTP_STOR: + result = ftp_state_stor_resp(data, ftpcode, ftpc->state); + break; + + case FTP_QUIT: + default: + /* internal error */ + ftp_state(data, FTP_STOP); + break; + } + } /* if(ftpcode) */ + + return result; +} + + +/* called repeatedly until done from multi.c */ +static CURLcode ftp_multi_statemach(struct Curl_easy *data, + bool *done) +{ + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = &conn->proto.ftpc; + CURLcode result = Curl_pp_statemach(data, &ftpc->pp, FALSE, FALSE); + + /* Check for the state outside of the Curl_socket_check() return code checks + since at times we are in fact already in this state when this function + gets called. */ + *done = (ftpc->state == FTP_STOP) ? TRUE : FALSE; + + return result; +} + +static CURLcode ftp_block_statemach(struct Curl_easy *data, + struct connectdata *conn) +{ + struct ftp_conn *ftpc = &conn->proto.ftpc; + struct pingpong *pp = &ftpc->pp; + CURLcode result = CURLE_OK; + + while(ftpc->state != FTP_STOP) { + result = Curl_pp_statemach(data, pp, TRUE, TRUE /* disconnecting */); + if(result) + break; + } + + return result; +} + +/* + * ftp_connect() should do everything that is to be considered a part of + * the connection phase. + * + * The variable 'done' points to will be TRUE if the protocol-layer connect + * phase is done when this function returns, or FALSE if not. + * + */ +static CURLcode ftp_connect(struct Curl_easy *data, + bool *done) /* see description above */ +{ + CURLcode result; + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = &conn->proto.ftpc; + struct pingpong *pp = &ftpc->pp; + + *done = FALSE; /* default to not done yet */ + + /* We always support persistent connections on ftp */ + connkeep(conn, "FTP default"); + + PINGPONG_SETUP(pp, ftp_statemachine, ftp_endofresp); + + if(conn->handler->flags & PROTOPT_SSL) { + /* BLOCKING */ + result = Curl_conn_connect(data, FIRSTSOCKET, TRUE, done); + if(result) + return result; + conn->bits.ftp_use_control_ssl = TRUE; + } + + Curl_pp_init(pp); /* once per transfer */ + + /* When we connect, we start in the state where we await the 220 + response */ + ftp_state(data, FTP_WAIT220); + + result = ftp_multi_statemach(data, done); + + return result; +} + +/*********************************************************************** + * + * ftp_done() + * + * The DONE function. This does what needs to be done after a single DO has + * performed. + * + * Input argument is already checked for validity. + */ +static CURLcode ftp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + struct connectdata *conn = data->conn; + struct FTP *ftp = data->req.p.ftp; + struct ftp_conn *ftpc = &conn->proto.ftpc; + struct pingpong *pp = &ftpc->pp; + ssize_t nread; + int ftpcode; + CURLcode result = CURLE_OK; + char *rawPath = NULL; + size_t pathLen = 0; + + if(!ftp) + return CURLE_OK; + + switch(status) { + case CURLE_BAD_DOWNLOAD_RESUME: + case CURLE_FTP_WEIRD_PASV_REPLY: + case CURLE_FTP_PORT_FAILED: + case CURLE_FTP_ACCEPT_FAILED: + case CURLE_FTP_ACCEPT_TIMEOUT: + case CURLE_FTP_COULDNT_SET_TYPE: + case CURLE_FTP_COULDNT_RETR_FILE: + case CURLE_PARTIAL_FILE: + case CURLE_UPLOAD_FAILED: + case CURLE_REMOTE_ACCESS_DENIED: + case CURLE_FILESIZE_EXCEEDED: + case CURLE_REMOTE_FILE_NOT_FOUND: + case CURLE_WRITE_ERROR: + /* the connection stays alive fine even though this happened */ + case CURLE_OK: /* doesn't affect the control connection's status */ + if(!premature) + break; + + /* until we cope better with prematurely ended requests, let them + * fallback as if in complete failure */ + FALLTHROUGH(); + default: /* by default, an error means the control connection is + wedged and should not be used anymore */ + ftpc->ctl_valid = FALSE; + ftpc->cwdfail = TRUE; /* set this TRUE to prevent us to remember the + current path, as this connection is going */ + connclose(conn, "FTP ended with bad error code"); + result = status; /* use the already set error code */ + break; + } + + if(data->state.wildcardmatch) { + if(data->set.chunk_end && ftpc->file) { + Curl_set_in_callback(data, true); + data->set.chunk_end(data->set.wildcardptr); + Curl_set_in_callback(data, false); + } + ftpc->known_filesize = -1; + } + + if(!result) + /* get the url-decoded "raw" path */ + result = Curl_urldecode(ftp->path, 0, &rawPath, &pathLen, + REJECT_CTRL); + if(result) { + /* We can limp along anyway (and should try to since we may already be in + * the error path) */ + ftpc->ctl_valid = FALSE; /* mark control connection as bad */ + connclose(conn, "FTP: out of memory!"); /* mark for connection closure */ + free(ftpc->prevpath); + ftpc->prevpath = NULL; /* no path remembering */ + } + else { /* remember working directory for connection reuse */ + if((data->set.ftp_filemethod == FTPFILE_NOCWD) && (rawPath[0] == '/')) + free(rawPath); /* full path => no CWDs happened => keep ftpc->prevpath */ + else { + free(ftpc->prevpath); + + if(!ftpc->cwdfail) { + if(data->set.ftp_filemethod == FTPFILE_NOCWD) + pathLen = 0; /* relative path => working directory is FTP home */ + else + pathLen -= ftpc->file?strlen(ftpc->file):0; /* file is url-decoded */ + + rawPath[pathLen] = '\0'; + ftpc->prevpath = rawPath; + } + else { + free(rawPath); + ftpc->prevpath = NULL; /* no path */ + } + } + + if(ftpc->prevpath) + infof(data, "Remembering we are in dir \"%s\"", ftpc->prevpath); + } + + /* free the dir tree and file parts */ + freedirs(ftpc); + + /* shut down the socket to inform the server we're done */ + +#ifdef _WIN32_WCE + shutdown(conn->sock[SECONDARYSOCKET], 2); /* SD_BOTH */ +#endif + + if(conn->sock[SECONDARYSOCKET] != CURL_SOCKET_BAD) { + if(!result && ftpc->dont_check && data->req.maxdownload > 0) { + /* partial download completed */ + result = Curl_pp_sendf(data, pp, "%s", "ABOR"); + if(result) { + failf(data, "Failure sending ABOR command: %s", + curl_easy_strerror(result)); + ftpc->ctl_valid = FALSE; /* mark control connection as bad */ + connclose(conn, "ABOR command failed"); /* connection closure */ + } + } + + close_secondarysocket(data, conn); + } + + if(!result && (ftp->transfer == PPTRANSFER_BODY) && ftpc->ctl_valid && + pp->pending_resp && !premature) { + /* + * Let's see what the server says about the transfer we just performed, + * but lower the timeout as sometimes this connection has died while the + * data has been transferred. This happens when doing through NATs etc that + * abandon old silent connections. + */ + timediff_t old_time = pp->response_time; + + pp->response_time = 60*1000; /* give it only a minute for now */ + pp->response = Curl_now(); /* timeout relative now */ + + result = Curl_GetFTPResponse(data, &nread, &ftpcode); + + pp->response_time = old_time; /* set this back to previous value */ + + if(!nread && (CURLE_OPERATION_TIMEDOUT == result)) { + failf(data, "control connection looks dead"); + ftpc->ctl_valid = FALSE; /* mark control connection as bad */ + connclose(conn, "Timeout or similar in FTP DONE operation"); /* close */ + } + + if(result) { + Curl_safefree(ftp->pathalloc); + return result; + } + + if(ftpc->dont_check && data->req.maxdownload > 0) { + /* we have just sent ABOR and there is no reliable way to check if it was + * successful or not; we have to close the connection now */ + infof(data, "partial download completed, closing connection"); + connclose(conn, "Partial download with no ability to check"); + return result; + } + + if(!ftpc->dont_check) { + /* 226 Transfer complete, 250 Requested file action okay, completed. */ + switch(ftpcode) { + case 226: + case 250: + break; + case 552: + failf(data, "Exceeded storage allocation"); + result = CURLE_REMOTE_DISK_FULL; + break; + default: + failf(data, "server did not report OK, got %d", ftpcode); + result = CURLE_PARTIAL_FILE; + break; + } + } + } + + if(result || premature) + /* the response code from the transfer showed an error already so no + use checking further */ + ; + else if(data->state.upload) { + if((-1 != data->state.infilesize) && + (data->state.infilesize != data->req.writebytecount) && + !data->set.crlf && + (ftp->transfer == PPTRANSFER_BODY)) { + failf(data, "Uploaded unaligned file size (%" CURL_FORMAT_CURL_OFF_T + " out of %" CURL_FORMAT_CURL_OFF_T " bytes)", + data->req.writebytecount, data->state.infilesize); + result = CURLE_PARTIAL_FILE; + } + } + else { + if((-1 != data->req.size) && + (data->req.size != data->req.bytecount) && +#ifdef CURL_DO_LINEEND_CONV + /* Most FTP servers don't adjust their file SIZE response for CRLFs, so + * we'll check to see if the discrepancy can be explained by the number + * of CRLFs we've changed to LFs. + */ + ((data->req.size + data->state.crlf_conversions) != + data->req.bytecount) && +#endif /* CURL_DO_LINEEND_CONV */ + (data->req.maxdownload != data->req.bytecount)) { + failf(data, "Received only partial file: %" CURL_FORMAT_CURL_OFF_T + " bytes", data->req.bytecount); + result = CURLE_PARTIAL_FILE; + } + else if(!ftpc->dont_check && + !data->req.bytecount && + (data->req.size>0)) { + failf(data, "No data was received"); + result = CURLE_FTP_COULDNT_RETR_FILE; + } + } + + /* clear these for next connection */ + ftp->transfer = PPTRANSFER_BODY; + ftpc->dont_check = FALSE; + + /* Send any post-transfer QUOTE strings? */ + if(!status && !result && !premature && data->set.postquote) + result = ftp_sendquote(data, conn, data->set.postquote); + CURL_TRC_FTP(data, "[%s] done, result=%d", FTP_DSTATE(data), result); + Curl_safefree(ftp->pathalloc); + return result; +} + +/*********************************************************************** + * + * ftp_sendquote() + * + * Where a 'quote' means a list of custom commands to send to the server. + * The quote list is passed as an argument. + * + * BLOCKING + */ + +static +CURLcode ftp_sendquote(struct Curl_easy *data, + struct connectdata *conn, struct curl_slist *quote) +{ + struct curl_slist *item; + struct ftp_conn *ftpc = &conn->proto.ftpc; + struct pingpong *pp = &ftpc->pp; + + item = quote; + while(item) { + if(item->data) { + ssize_t nread; + char *cmd = item->data; + bool acceptfail = FALSE; + CURLcode result; + int ftpcode = 0; + + /* if a command starts with an asterisk, which a legal FTP command never + can, the command will be allowed to fail without it causing any + aborts or cancels etc. It will cause libcurl to act as if the command + is successful, whatever the server responds. */ + + if(cmd[0] == '*') { + cmd++; + acceptfail = TRUE; + } + + result = Curl_pp_sendf(data, &ftpc->pp, "%s", cmd); + if(!result) { + pp->response = Curl_now(); /* timeout relative now */ + result = Curl_GetFTPResponse(data, &nread, &ftpcode); + } + if(result) + return result; + + if(!acceptfail && (ftpcode >= 400)) { + failf(data, "QUOT string not accepted: %s", cmd); + return CURLE_QUOTE_ERROR; + } + } + + item = item->next; + } + + return CURLE_OK; +} + +/*********************************************************************** + * + * ftp_need_type() + * + * Returns TRUE if we in the current situation should send TYPE + */ +static int ftp_need_type(struct connectdata *conn, + bool ascii_wanted) +{ + return conn->proto.ftpc.transfertype != (ascii_wanted?'A':'I'); +} + +/*********************************************************************** + * + * ftp_nb_type() + * + * Set TYPE. We only deal with ASCII or BINARY so this function + * sets one of them. + * If the transfer type is not sent, simulate on OK response in newstate + */ +static CURLcode ftp_nb_type(struct Curl_easy *data, + struct connectdata *conn, + bool ascii, ftpstate newstate) +{ + struct ftp_conn *ftpc = &conn->proto.ftpc; + CURLcode result; + char want = (char)(ascii?'A':'I'); + + if(ftpc->transfertype == want) { + ftp_state(data, newstate); + return ftp_state_type_resp(data, 200, newstate); + } + + result = Curl_pp_sendf(data, &ftpc->pp, "TYPE %c", want); + if(!result) { + ftp_state(data, newstate); + + /* keep track of our current transfer type */ + ftpc->transfertype = want; + } + return result; +} + +/*************************************************************************** + * + * ftp_pasv_verbose() + * + * This function only outputs some informationals about this second connection + * when we've issued a PASV command before and thus we have connected to a + * possibly new IP address. + * + */ +#ifndef CURL_DISABLE_VERBOSE_STRINGS +static void +ftp_pasv_verbose(struct Curl_easy *data, + struct Curl_addrinfo *ai, + char *newhost, /* ascii version */ + int port) +{ + char buf[256]; + Curl_printable_address(ai, buf, sizeof(buf)); + infof(data, "Connecting to %s (%s) port %d", newhost, buf, port); +} +#endif + +/* + * ftp_do_more() + * + * This function shall be called when the second FTP (data) connection is + * connected. + * + * 'complete' can return 0 for incomplete, 1 for done and -1 for go back + * (which basically is only for when PASV is being sent to retry a failed + * EPSV). + */ + +static CURLcode ftp_do_more(struct Curl_easy *data, int *completep) +{ + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = &conn->proto.ftpc; + CURLcode result = CURLE_OK; + bool connected = FALSE; + bool complete = FALSE; + + /* the ftp struct is inited in ftp_connect(). If we are connecting to an HTTP + * proxy then the state will not be valid until after that connection is + * complete */ + struct FTP *ftp = NULL; + + /* if the second connection isn't done yet, wait for it to have + * connected to the remote host. When using proxy tunneling, this + * means the tunnel needs to have been establish. However, we + * can not expect the remote host to talk to us in any way yet. + * So, when using ftps: the SSL handshake will not start until we + * tell the remote server that we are there. */ + if(conn->cfilter[SECONDARYSOCKET]) { + result = Curl_conn_connect(data, SECONDARYSOCKET, FALSE, &connected); + if(result || !Curl_conn_is_ip_connected(data, SECONDARYSOCKET)) { + if(result && (ftpc->count1 == 0)) { + *completep = -1; /* go back to DOING please */ + /* this is a EPSV connect failing, try PASV instead */ + return ftp_epsv_disable(data, conn); + } + return result; + } + } + + /* Curl_proxy_connect might have moved the protocol state */ + ftp = data->req.p.ftp; + + if(ftpc->state) { + /* already in a state so skip the initial commands. + They are only done to kickstart the do_more state */ + result = ftp_multi_statemach(data, &complete); + + *completep = (int)complete; + + /* if we got an error or if we don't wait for a data connection return + immediately */ + if(result || !ftpc->wait_data_conn) + return result; + + /* if we reach the end of the FTP state machine here, *complete will be + TRUE but so is ftpc->wait_data_conn, which says we need to wait for the + data connection and therefore we're not actually complete */ + *completep = 0; + } + + if(ftp->transfer <= PPTRANSFER_INFO) { + /* a transfer is about to take place, or if not a file name was given + so we'll do a SIZE on it later and then we need the right TYPE first */ + + if(ftpc->wait_data_conn) { + bool serv_conned; + + result = ReceivedServerConnect(data, &serv_conned); + if(result) + return result; /* Failed to accept data connection */ + + if(serv_conned) { + /* It looks data connection is established */ + result = AcceptServerConnect(data); + ftpc->wait_data_conn = FALSE; + if(!result) + result = InitiateTransfer(data); + + if(result) + return result; + + *completep = 1; /* this state is now complete when the server has + connected back to us */ + } + } + else if(data->state.upload) { + result = ftp_nb_type(data, conn, data->state.prefer_ascii, + FTP_STOR_TYPE); + if(result) + return result; + + result = ftp_multi_statemach(data, &complete); + *completep = (int)complete; + } + else { + /* download */ + ftp->downloadsize = -1; /* unknown as of yet */ + + result = Curl_range(data); + + if(result == CURLE_OK && data->req.maxdownload >= 0) { + /* Don't check for successful transfer */ + ftpc->dont_check = TRUE; + } + + if(result) + ; + else if(data->state.list_only || !ftpc->file) { + /* The specified path ends with a slash, and therefore we think this + is a directory that is requested, use LIST. But before that we + need to set ASCII transfer mode. */ + + /* But only if a body transfer was requested. */ + if(ftp->transfer == PPTRANSFER_BODY) { + result = ftp_nb_type(data, conn, TRUE, FTP_LIST_TYPE); + if(result) + return result; + } + /* otherwise just fall through */ + } + else { + result = ftp_nb_type(data, conn, data->state.prefer_ascii, + FTP_RETR_TYPE); + if(result) + return result; + } + + result = ftp_multi_statemach(data, &complete); + *completep = (int)complete; + } + return result; + } + + /* no data to transfer */ + Curl_xfer_setup(data, -1, -1, FALSE, -1); + + if(!ftpc->wait_data_conn) { + /* no waiting for the data connection so this is now complete */ + *completep = 1; + CURL_TRC_FTP(data, "[%s] DO-MORE phase ends with %d", FTP_DSTATE(data), + (int)result); + } + + return result; +} + + + +/*********************************************************************** + * + * ftp_perform() + * + * This is the actual DO function for FTP. Get a file/directory according to + * the options previously setup. + */ + +static +CURLcode ftp_perform(struct Curl_easy *data, + bool *connected, /* connect status after PASV / PORT */ + bool *dophase_done) +{ + /* this is FTP and no proxy */ + CURLcode result = CURLE_OK; + + CURL_TRC_FTP(data, "[%s] DO phase starts", FTP_DSTATE(data)); + + if(data->req.no_body) { + /* requested no body means no transfer... */ + struct FTP *ftp = data->req.p.ftp; + ftp->transfer = PPTRANSFER_INFO; + } + + *dophase_done = FALSE; /* not done yet */ + + /* start the first command in the DO phase */ + result = ftp_state_quote(data, TRUE, FTP_QUOTE); + if(result) + return result; + + /* run the state-machine */ + result = ftp_multi_statemach(data, dophase_done); + + *connected = Curl_conn_is_connected(data->conn, SECONDARYSOCKET); + + if(*connected) + infof(data, "[FTP] [%s] perform, DATA connection established", + FTP_DSTATE(data)); + else + CURL_TRC_FTP(data, "[%s] perform, awaiting DATA connect", + FTP_DSTATE(data)); + + if(*dophase_done) + CURL_TRC_FTP(data, "[%s] DO phase is complete1", FTP_DSTATE(data)); + + return result; +} + +static void wc_data_dtor(void *ptr) +{ + struct ftp_wc *ftpwc = ptr; + if(ftpwc && ftpwc->parser) + Curl_ftp_parselist_data_free(&ftpwc->parser); + free(ftpwc); +} + +static CURLcode init_wc_data(struct Curl_easy *data) +{ + char *last_slash; + struct FTP *ftp = data->req.p.ftp; + char *path = ftp->path; + struct WildcardData *wildcard = data->wildcard; + CURLcode result = CURLE_OK; + struct ftp_wc *ftpwc = NULL; + + last_slash = strrchr(ftp->path, '/'); + if(last_slash) { + last_slash++; + if(last_slash[0] == '\0') { + wildcard->state = CURLWC_CLEAN; + result = ftp_parse_url_path(data); + return result; + } + wildcard->pattern = strdup(last_slash); + if(!wildcard->pattern) + return CURLE_OUT_OF_MEMORY; + last_slash[0] = '\0'; /* cut file from path */ + } + else { /* there is only 'wildcard pattern' or nothing */ + if(path[0]) { + wildcard->pattern = strdup(path); + if(!wildcard->pattern) + return CURLE_OUT_OF_MEMORY; + path[0] = '\0'; + } + else { /* only list */ + wildcard->state = CURLWC_CLEAN; + result = ftp_parse_url_path(data); + return result; + } + } + + /* program continues only if URL is not ending with slash, allocate needed + resources for wildcard transfer */ + + /* allocate ftp protocol specific wildcard data */ + ftpwc = calloc(1, sizeof(struct ftp_wc)); + if(!ftpwc) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + /* INITIALIZE parselist structure */ + ftpwc->parser = Curl_ftp_parselist_data_alloc(); + if(!ftpwc->parser) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + wildcard->ftpwc = ftpwc; /* put it to the WildcardData tmp pointer */ + wildcard->dtor = wc_data_dtor; + + /* wildcard does not support NOCWD option (assert it?) */ + if(data->set.ftp_filemethod == FTPFILE_NOCWD) + data->set.ftp_filemethod = FTPFILE_MULTICWD; + + /* try to parse ftp url */ + result = ftp_parse_url_path(data); + if(result) { + goto fail; + } + + wildcard->path = strdup(ftp->path); + if(!wildcard->path) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + /* backup old write_function */ + ftpwc->backup.write_function = data->set.fwrite_func; + /* parsing write function */ + data->set.fwrite_func = Curl_ftp_parselist; + /* backup old file descriptor */ + ftpwc->backup.file_descriptor = data->set.out; + /* let the writefunc callback know the transfer */ + data->set.out = data; + + infof(data, "Wildcard - Parsing started"); + return CURLE_OK; + +fail: + if(ftpwc) { + Curl_ftp_parselist_data_free(&ftpwc->parser); + free(ftpwc); + } + Curl_safefree(wildcard->pattern); + wildcard->dtor = ZERO_NULL; + wildcard->ftpwc = NULL; + return result; +} + +static CURLcode wc_statemach(struct Curl_easy *data) +{ + struct WildcardData * const wildcard = data->wildcard; + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + + for(;;) { + switch(wildcard->state) { + case CURLWC_INIT: + result = init_wc_data(data); + if(wildcard->state == CURLWC_CLEAN) + /* only listing! */ + return result; + wildcard->state = result ? CURLWC_ERROR : CURLWC_MATCHING; + return result; + + case CURLWC_MATCHING: { + /* In this state is LIST response successfully parsed, so lets restore + previous WRITEFUNCTION callback and WRITEDATA pointer */ + struct ftp_wc *ftpwc = wildcard->ftpwc; + data->set.fwrite_func = ftpwc->backup.write_function; + data->set.out = ftpwc->backup.file_descriptor; + ftpwc->backup.write_function = ZERO_NULL; + ftpwc->backup.file_descriptor = NULL; + wildcard->state = CURLWC_DOWNLOADING; + + if(Curl_ftp_parselist_geterror(ftpwc->parser)) { + /* error found in LIST parsing */ + wildcard->state = CURLWC_CLEAN; + continue; + } + if(wildcard->filelist.size == 0) { + /* no corresponding file */ + wildcard->state = CURLWC_CLEAN; + return CURLE_REMOTE_FILE_NOT_FOUND; + } + continue; + } + + case CURLWC_DOWNLOADING: { + /* filelist has at least one file, lets get first one */ + struct ftp_conn *ftpc = &conn->proto.ftpc; + struct curl_fileinfo *finfo = wildcard->filelist.head->ptr; + struct FTP *ftp = data->req.p.ftp; + + char *tmp_path = aprintf("%s%s", wildcard->path, finfo->filename); + if(!tmp_path) + return CURLE_OUT_OF_MEMORY; + + /* switch default ftp->path and tmp_path */ + free(ftp->pathalloc); + ftp->pathalloc = ftp->path = tmp_path; + + infof(data, "Wildcard - START of \"%s\"", finfo->filename); + if(data->set.chunk_bgn) { + long userresponse; + Curl_set_in_callback(data, true); + userresponse = data->set.chunk_bgn( + finfo, data->set.wildcardptr, (int)wildcard->filelist.size); + Curl_set_in_callback(data, false); + switch(userresponse) { + case CURL_CHUNK_BGN_FUNC_SKIP: + infof(data, "Wildcard - \"%s\" skipped by user", + finfo->filename); + wildcard->state = CURLWC_SKIP; + continue; + case CURL_CHUNK_BGN_FUNC_FAIL: + return CURLE_CHUNK_FAILED; + } + } + + if(finfo->filetype != CURLFILETYPE_FILE) { + wildcard->state = CURLWC_SKIP; + continue; + } + + if(finfo->flags & CURLFINFOFLAG_KNOWN_SIZE) + ftpc->known_filesize = finfo->size; + + result = ftp_parse_url_path(data); + if(result) + return result; + + /* we don't need the Curl_fileinfo of first file anymore */ + Curl_llist_remove(&wildcard->filelist, wildcard->filelist.head, NULL); + + if(wildcard->filelist.size == 0) { /* remains only one file to down. */ + wildcard->state = CURLWC_CLEAN; + /* after that will be ftp_do called once again and no transfer + will be done because of CURLWC_CLEAN state */ + return CURLE_OK; + } + return result; + } + + case CURLWC_SKIP: { + if(data->set.chunk_end) { + Curl_set_in_callback(data, true); + data->set.chunk_end(data->set.wildcardptr); + Curl_set_in_callback(data, false); + } + Curl_llist_remove(&wildcard->filelist, wildcard->filelist.head, NULL); + wildcard->state = (wildcard->filelist.size == 0) ? + CURLWC_CLEAN : CURLWC_DOWNLOADING; + continue; + } + + case CURLWC_CLEAN: { + struct ftp_wc *ftpwc = wildcard->ftpwc; + result = CURLE_OK; + if(ftpwc) + result = Curl_ftp_parselist_geterror(ftpwc->parser); + + wildcard->state = result ? CURLWC_ERROR : CURLWC_DONE; + return result; + } + + case CURLWC_DONE: + case CURLWC_ERROR: + case CURLWC_CLEAR: + if(wildcard->dtor) { + wildcard->dtor(wildcard->ftpwc); + wildcard->ftpwc = NULL; + } + return result; + } + } + /* UNREACHABLE */ +} + +/*********************************************************************** + * + * ftp_do() + * + * This function is registered as 'curl_do' function. It decodes the path + * parts etc as a wrapper to the actual DO function (ftp_perform). + * + * The input argument is already checked for validity. + */ +static CURLcode ftp_do(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = &conn->proto.ftpc; + + *done = FALSE; /* default to false */ + ftpc->wait_data_conn = FALSE; /* default to no such wait */ + +#ifdef CURL_DO_LINEEND_CONV + { + /* FTP data may need conversion. */ + struct Curl_cwriter *ftp_lc_writer; + + result = Curl_cwriter_create(&ftp_lc_writer, data, &ftp_cw_lc, + CURL_CW_CONTENT_DECODE); + if(result) + return result; + + result = Curl_cwriter_add(data, ftp_lc_writer); + if(result) { + Curl_cwriter_free(data, ftp_lc_writer); + return result; + } + } +#endif /* CURL_DO_LINEEND_CONV */ + + if(data->state.wildcardmatch) { + result = wc_statemach(data); + if(data->wildcard->state == CURLWC_SKIP || + data->wildcard->state == CURLWC_DONE) { + /* do not call ftp_regular_transfer */ + return CURLE_OK; + } + if(result) /* error, loop or skipping the file */ + return result; + } + else { /* no wildcard FSM needed */ + result = ftp_parse_url_path(data); + if(result) + return result; + } + + result = ftp_regular_transfer(data, done); + + return result; +} + +/*********************************************************************** + * + * ftp_quit() + * + * This should be called before calling sclose() on an ftp control connection + * (not data connections). We should then wait for the response from the + * server before returning. The calling code should then try to close the + * connection. + * + */ +static CURLcode ftp_quit(struct Curl_easy *data, struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + + if(conn->proto.ftpc.ctl_valid) { + result = Curl_pp_sendf(data, &conn->proto.ftpc.pp, "%s", "QUIT"); + if(result) { + failf(data, "Failure sending QUIT command: %s", + curl_easy_strerror(result)); + conn->proto.ftpc.ctl_valid = FALSE; /* mark control connection as bad */ + connclose(conn, "QUIT command failed"); /* mark for connection closure */ + ftp_state(data, FTP_STOP); + return result; + } + + ftp_state(data, FTP_QUIT); + + result = ftp_block_statemach(data, conn); + } + + return result; +} + +/*********************************************************************** + * + * ftp_disconnect() + * + * Disconnect from an FTP server. Cleanup protocol-specific per-connection + * resources. BLOCKING. + */ +static CURLcode ftp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + struct ftp_conn *ftpc = &conn->proto.ftpc; + struct pingpong *pp = &ftpc->pp; + + /* We cannot send quit unconditionally. If this connection is stale or + bad in any way, sending quit and waiting around here will make the + disconnect wait in vain and cause more problems than we need to. + + ftp_quit() will check the state of ftp->ctl_valid. If it's ok it + will try to send the QUIT command, otherwise it will just return. + */ + if(dead_connection) + ftpc->ctl_valid = FALSE; + + /* The FTP session may or may not have been allocated/setup at this point! */ + (void)ftp_quit(data, conn); /* ignore errors on the QUIT */ + + if(ftpc->entrypath) { + if(data->state.most_recent_ftp_entrypath == ftpc->entrypath) { + data->state.most_recent_ftp_entrypath = NULL; + } + Curl_safefree(ftpc->entrypath); + } + + freedirs(ftpc); + Curl_safefree(ftpc->account); + Curl_safefree(ftpc->alternative_to_user); + Curl_safefree(ftpc->prevpath); + Curl_safefree(ftpc->server_os); + Curl_pp_disconnect(pp); + Curl_sec_end(conn); + return CURLE_OK; +} + +#ifdef _MSC_VER +/* warning C4706: assignment within conditional expression */ +#pragma warning(disable:4706) +#endif + +/*********************************************************************** + * + * ftp_parse_url_path() + * + * Parse the URL path into separate path components. + * + */ +static +CURLcode ftp_parse_url_path(struct Curl_easy *data) +{ + /* the ftp struct is already inited in ftp_connect() */ + struct FTP *ftp = data->req.p.ftp; + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = &conn->proto.ftpc; + const char *slashPos = NULL; + const char *fileName = NULL; + CURLcode result = CURLE_OK; + char *rawPath = NULL; /* url-decoded "raw" path */ + size_t pathLen = 0; + + ftpc->ctl_valid = FALSE; + ftpc->cwdfail = FALSE; + + /* url-decode ftp path before further evaluation */ + result = Curl_urldecode(ftp->path, 0, &rawPath, &pathLen, REJECT_CTRL); + if(result) { + failf(data, "path contains control characters"); + return result; + } + + switch(data->set.ftp_filemethod) { + case FTPFILE_NOCWD: /* fastest, but less standard-compliant */ + + if((pathLen > 0) && (rawPath[pathLen - 1] != '/')) + fileName = rawPath; /* this is a full file path */ + /* + else: ftpc->file is not used anywhere other than for operations on + a file. In other words, never for directory operations. + So we can safely leave filename as NULL here and use it as a + argument in dir/file decisions. + */ + break; + + case FTPFILE_SINGLECWD: + slashPos = strrchr(rawPath, '/'); + if(slashPos) { + /* get path before last slash, except for / */ + size_t dirlen = slashPos - rawPath; + if(dirlen == 0) + dirlen = 1; + + ftpc->dirs = calloc(1, sizeof(ftpc->dirs[0])); + if(!ftpc->dirs) { + free(rawPath); + return CURLE_OUT_OF_MEMORY; + } + + ftpc->dirs[0] = Curl_memdup0(rawPath, dirlen); + if(!ftpc->dirs[0]) { + free(rawPath); + return CURLE_OUT_OF_MEMORY; + } + + ftpc->dirdepth = 1; /* we consider it to be a single dir */ + fileName = slashPos + 1; /* rest is file name */ + } + else + fileName = rawPath; /* file name only (or empty) */ + break; + + default: /* allow pretty much anything */ + case FTPFILE_MULTICWD: { + /* current position: begin of next path component */ + const char *curPos = rawPath; + + /* number of entries allocated for the 'dirs' array */ + size_t dirAlloc = 0; + const char *str = rawPath; + for(; *str != 0; ++str) + if(*str == '/') + ++dirAlloc; + + if(dirAlloc) { + ftpc->dirs = calloc(dirAlloc, sizeof(ftpc->dirs[0])); + if(!ftpc->dirs) { + free(rawPath); + return CURLE_OUT_OF_MEMORY; + } + + /* parse the URL path into separate path components */ + while((slashPos = strchr(curPos, '/'))) { + size_t compLen = slashPos - curPos; + + /* path starts with a slash: add that as a directory */ + if((compLen == 0) && (ftpc->dirdepth == 0)) + ++compLen; + + /* we skip empty path components, like "x//y" since the FTP command + CWD requires a parameter and a non-existent parameter a) doesn't + work on many servers and b) has no effect on the others. */ + if(compLen > 0) { + char *comp = Curl_memdup0(curPos, compLen); + if(!comp) { + free(rawPath); + return CURLE_OUT_OF_MEMORY; + } + ftpc->dirs[ftpc->dirdepth++] = comp; + } + curPos = slashPos + 1; + } + } + DEBUGASSERT((size_t)ftpc->dirdepth <= dirAlloc); + fileName = curPos; /* the rest is the file name (or empty) */ + } + break; + } /* switch */ + + if(fileName && *fileName) + ftpc->file = strdup(fileName); + else + ftpc->file = NULL; /* instead of point to a zero byte, + we make it a NULL pointer */ + + if(data->state.upload && !ftpc->file && (ftp->transfer == PPTRANSFER_BODY)) { + /* We need a file name when uploading. Return error! */ + failf(data, "Uploading to a URL without a file name"); + free(rawPath); + return CURLE_URL_MALFORMAT; + } + + ftpc->cwddone = FALSE; /* default to not done */ + + if((data->set.ftp_filemethod == FTPFILE_NOCWD) && (rawPath[0] == '/')) + ftpc->cwddone = TRUE; /* skip CWD for absolute paths */ + else { /* newly created FTP connections are already in entry path */ + const char *oldPath = conn->bits.reuse ? ftpc->prevpath : ""; + if(oldPath) { + size_t n = pathLen; + if(data->set.ftp_filemethod == FTPFILE_NOCWD) + n = 0; /* CWD to entry for relative paths */ + else + n -= ftpc->file?strlen(ftpc->file):0; + + if((strlen(oldPath) == n) && !strncmp(rawPath, oldPath, n)) { + infof(data, "Request has same path as previous transfer"); + ftpc->cwddone = TRUE; + } + } + } + + free(rawPath); + return CURLE_OK; +} + +/* call this when the DO phase has completed */ +static CURLcode ftp_dophase_done(struct Curl_easy *data, bool connected) +{ + struct connectdata *conn = data->conn; + struct FTP *ftp = data->req.p.ftp; + struct ftp_conn *ftpc = &conn->proto.ftpc; + + if(connected) { + int completed; + CURLcode result = ftp_do_more(data, &completed); + + if(result) { + close_secondarysocket(data, conn); + return result; + } + } + + if(ftp->transfer != PPTRANSFER_BODY) + /* no data to transfer */ + Curl_xfer_setup(data, -1, -1, FALSE, -1); + else if(!connected) + /* since we didn't connect now, we want do_more to get called */ + conn->bits.do_more = TRUE; + + ftpc->ctl_valid = TRUE; /* seems good */ + + return CURLE_OK; +} + +/* called from multi.c while DOing */ +static CURLcode ftp_doing(struct Curl_easy *data, + bool *dophase_done) +{ + CURLcode result = ftp_multi_statemach(data, dophase_done); + + if(result) + CURL_TRC_FTP(data, "[%s] DO phase failed", FTP_DSTATE(data)); + else if(*dophase_done) { + result = ftp_dophase_done(data, FALSE /* not connected */); + + CURL_TRC_FTP(data, "[%s] DO phase is complete2", FTP_DSTATE(data)); + } + return result; +} + +/*********************************************************************** + * + * ftp_regular_transfer() + * + * The input argument is already checked for validity. + * + * Performs all commands done before a regular transfer between a local and a + * remote host. + * + * ftp->ctl_valid starts out as FALSE, and gets set to TRUE if we reach the + * ftp_done() function without finding any major problem. + */ +static +CURLcode ftp_regular_transfer(struct Curl_easy *data, + bool *dophase_done) +{ + CURLcode result = CURLE_OK; + bool connected = FALSE; + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = &conn->proto.ftpc; + data->req.size = -1; /* make sure this is unknown at this point */ + + Curl_pgrsSetUploadCounter(data, 0); + Curl_pgrsSetDownloadCounter(data, 0); + Curl_pgrsSetUploadSize(data, -1); + Curl_pgrsSetDownloadSize(data, -1); + + ftpc->ctl_valid = TRUE; /* starts good */ + + result = ftp_perform(data, + &connected, /* have we connected after PASV/PORT */ + dophase_done); /* all commands in the DO-phase done? */ + + if(!result) { + + if(!*dophase_done) + /* the DO phase has not completed yet */ + return CURLE_OK; + + result = ftp_dophase_done(data, connected); + + if(result) + return result; + } + else + freedirs(ftpc); + + return result; +} + +static CURLcode ftp_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + char *type; + struct FTP *ftp; + CURLcode result = CURLE_OK; + struct ftp_conn *ftpc = &conn->proto.ftpc; + + ftp = calloc(1, sizeof(struct FTP)); + if(!ftp) + return CURLE_OUT_OF_MEMORY; + + /* clone connection related data that is FTP specific */ + if(data->set.str[STRING_FTP_ACCOUNT]) { + ftpc->account = strdup(data->set.str[STRING_FTP_ACCOUNT]); + if(!ftpc->account) { + free(ftp); + return CURLE_OUT_OF_MEMORY; + } + } + if(data->set.str[STRING_FTP_ALTERNATIVE_TO_USER]) { + ftpc->alternative_to_user = + strdup(data->set.str[STRING_FTP_ALTERNATIVE_TO_USER]); + if(!ftpc->alternative_to_user) { + Curl_safefree(ftpc->account); + free(ftp); + return CURLE_OUT_OF_MEMORY; + } + } + data->req.p.ftp = ftp; + + ftp->path = &data->state.up.path[1]; /* don't include the initial slash */ + + /* FTP URLs support an extension like ";type=" that + * we'll try to get now! */ + type = strstr(ftp->path, ";type="); + + if(!type) + type = strstr(conn->host.rawalloc, ";type="); + + if(type) { + char command; + *type = 0; /* it was in the middle of the hostname */ + command = Curl_raw_toupper(type[6]); + + switch(command) { + case 'A': /* ASCII mode */ + data->state.prefer_ascii = TRUE; + break; + + case 'D': /* directory mode */ + data->state.list_only = TRUE; + break; + + case 'I': /* binary mode */ + default: + /* switch off ASCII */ + data->state.prefer_ascii = FALSE; + break; + } + } + + /* get some initial data into the ftp struct */ + ftp->transfer = PPTRANSFER_BODY; + ftp->downloadsize = 0; + ftpc->known_filesize = -1; /* unknown size for now */ + ftpc->use_ssl = data->set.use_ssl; + ftpc->ccc = data->set.ftp_ccc; + + CURL_TRC_FTP(data, "[%s] setup connection -> %d", FTP_CSTATE(conn), result); + return result; +} + +#endif /* CURL_DISABLE_FTP */ diff --git a/third_party/curl/lib/ftp.h b/third_party/curl/lib/ftp.h new file mode 100644 index 0000000..977fc88 --- /dev/null +++ b/third_party/curl/lib/ftp.h @@ -0,0 +1,167 @@ +#ifndef HEADER_CURL_FTP_H +#define HEADER_CURL_FTP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "pingpong.h" + +#ifndef CURL_DISABLE_FTP +extern const struct Curl_handler Curl_handler_ftp; + +#ifdef USE_SSL +extern const struct Curl_handler Curl_handler_ftps; +#endif + +CURLcode Curl_GetFTPResponse(struct Curl_easy *data, ssize_t *nread, + int *ftpcode); +#endif /* CURL_DISABLE_FTP */ + +/**************************************************************************** + * FTP unique setup + ***************************************************************************/ +enum { + FTP_STOP, /* do nothing state, stops the state machine */ + FTP_WAIT220, /* waiting for the initial 220 response immediately after + a connect */ + FTP_AUTH, + FTP_USER, + FTP_PASS, + FTP_ACCT, + FTP_PBSZ, + FTP_PROT, + FTP_CCC, + FTP_PWD, + FTP_SYST, + FTP_NAMEFMT, + FTP_QUOTE, /* waiting for a response to a command sent in a quote list */ + FTP_RETR_PREQUOTE, + FTP_STOR_PREQUOTE, + FTP_POSTQUOTE, + FTP_CWD, /* change dir */ + FTP_MKD, /* if the dir didn't exist */ + FTP_MDTM, /* to figure out the datestamp */ + FTP_TYPE, /* to set type when doing a head-like request */ + FTP_LIST_TYPE, /* set type when about to do a dir list */ + FTP_RETR_TYPE, /* set type when about to RETR a file */ + FTP_STOR_TYPE, /* set type when about to STOR a file */ + FTP_SIZE, /* get the remote file's size for head-like request */ + FTP_RETR_SIZE, /* get the remote file's size for RETR */ + FTP_STOR_SIZE, /* get the size for STOR */ + FTP_REST, /* when used to check if the server supports it in head-like */ + FTP_RETR_REST, /* when asking for "resume" in for RETR */ + FTP_PORT, /* generic state for PORT, LPRT and EPRT, check count1 */ + FTP_PRET, /* generic state for PRET RETR, PRET STOR and PRET LIST/NLST */ + FTP_PASV, /* generic state for PASV and EPSV, check count1 */ + FTP_LIST, /* generic state for LIST, NLST or a custom list command */ + FTP_RETR, + FTP_STOR, /* generic state for STOR and APPE */ + FTP_QUIT, + FTP_LAST /* never used */ +}; +typedef unsigned char ftpstate; /* use the enum values */ + +struct ftp_parselist_data; /* defined later in ftplistparser.c */ + +struct ftp_wc { + struct ftp_parselist_data *parser; + + struct { + curl_write_callback write_function; + FILE *file_descriptor; + } backup; +}; + +typedef enum { + FTPFILE_MULTICWD = 1, /* as defined by RFC1738 */ + FTPFILE_NOCWD = 2, /* use SIZE / RETR / STOR on the full path */ + FTPFILE_SINGLECWD = 3 /* make one CWD, then SIZE / RETR / STOR on the + file */ +} curl_ftpfile; + +/* This FTP struct is used in the Curl_easy. All FTP data that is + connection-oriented must be in FTP_conn to properly deal with the fact that + perhaps the Curl_easy is changed between the times the connection is + used. */ +struct FTP { + char *path; /* points to the urlpieces struct field */ + char *pathalloc; /* if non-NULL a pointer to an allocated path */ + + /* transfer a file/body or not, done as a typedefed enum just to make + debuggers display the full symbol and not just the numerical value */ + curl_pp_transfer transfer; + curl_off_t downloadsize; +}; + + +/* ftp_conn is used for struct connection-oriented data in the connectdata + struct */ +struct ftp_conn { + struct pingpong pp; + char *account; + char *alternative_to_user; + char *entrypath; /* the PWD reply when we logged on */ + char *file; /* url-decoded file name (or path) */ + char **dirs; /* realloc()ed array for path components */ + char *newhost; + char *prevpath; /* url-decoded conn->path from the previous transfer */ + char transfertype; /* set by ftp_transfertype for use by Curl_client_write()a + and others (A/I or zero) */ + curl_off_t retr_size_saved; /* Size of retrieved file saved */ + char *server_os; /* The target server operating system. */ + curl_off_t known_filesize; /* file size is different from -1, if wildcard + LIST parsing was done and wc_statemach set + it */ + int dirdepth; /* number of entries used in the 'dirs' array */ + int cwdcount; /* number of CWD commands issued */ + int count1; /* general purpose counter for the state machine */ + int count2; /* general purpose counter for the state machine */ + int count3; /* general purpose counter for the state machine */ + /* newhost is the (allocated) IP addr or host name to connect the data + connection to */ + unsigned short newport; + ftpstate state; /* always use ftp.c:state() to change state! */ + ftpstate state_saved; /* transfer type saved to be reloaded after data + connection is established */ + unsigned char use_ssl; /* if AUTH TLS is to be attempted etc, for FTP or + IMAP or POP3 or others! (type: curl_usessl)*/ + unsigned char ccc; /* ccc level for this connection */ + BIT(ftp_trying_alternative); + BIT(dont_check); /* Set to TRUE to prevent the final (post-transfer) + file size and 226/250 status check. It should still + read the line, just ignore the result. */ + BIT(ctl_valid); /* Tells Curl_ftp_quit() whether or not to do anything. If + the connection has timed out or been closed, this + should be FALSE when it gets to Curl_ftp_quit() */ + BIT(cwddone); /* if it has been determined that the proper CWD combo + already has been done */ + BIT(cwdfail); /* set TRUE if a CWD command fails, as then we must prevent + caching the current directory */ + BIT(wait_data_conn); /* this is set TRUE if data connection is waited */ +}; + +#define DEFAULT_ACCEPT_TIMEOUT 60000 /* milliseconds == one minute */ + +#endif /* HEADER_CURL_FTP_H */ diff --git a/third_party/curl/lib/ftplistparser.c b/third_party/curl/lib/ftplistparser.c new file mode 100644 index 0000000..448f3a4 --- /dev/null +++ b/third_party/curl/lib/ftplistparser.c @@ -0,0 +1,1041 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/** + * Now implemented: + * + * 1) Unix version 1 + * drwxr-xr-x 1 user01 ftp 512 Jan 29 23:32 prog + * 2) Unix version 2 + * drwxr-xr-x 1 user01 ftp 512 Jan 29 1997 prog + * 3) Unix version 3 + * drwxr-xr-x 1 1 1 512 Jan 29 23:32 prog + * 4) Unix symlink + * lrwxr-xr-x 1 user01 ftp 512 Jan 29 23:32 prog -> prog2000 + * 5) DOS style + * 01-29-97 11:32PM prog + */ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_FTP + +#include + +#include "urldata.h" +#include "fileinfo.h" +#include "llist.h" +#include "strtoofft.h" +#include "ftp.h" +#include "ftplistparser.h" +#include "curl_fnmatch.h" +#include "curl_memory.h" +#include "multiif.h" +/* The last #include file should be: */ +#include "memdebug.h" + +typedef enum { + PL_UNIX_TOTALSIZE = 0, + PL_UNIX_FILETYPE, + PL_UNIX_PERMISSION, + PL_UNIX_HLINKS, + PL_UNIX_USER, + PL_UNIX_GROUP, + PL_UNIX_SIZE, + PL_UNIX_TIME, + PL_UNIX_FILENAME, + PL_UNIX_SYMLINK +} pl_unix_mainstate; + +typedef union { + enum { + PL_UNIX_TOTALSIZE_INIT = 0, + PL_UNIX_TOTALSIZE_READING + } total_dirsize; + + enum { + PL_UNIX_HLINKS_PRESPACE = 0, + PL_UNIX_HLINKS_NUMBER + } hlinks; + + enum { + PL_UNIX_USER_PRESPACE = 0, + PL_UNIX_USER_PARSING + } user; + + enum { + PL_UNIX_GROUP_PRESPACE = 0, + PL_UNIX_GROUP_NAME + } group; + + enum { + PL_UNIX_SIZE_PRESPACE = 0, + PL_UNIX_SIZE_NUMBER + } size; + + enum { + PL_UNIX_TIME_PREPART1 = 0, + PL_UNIX_TIME_PART1, + PL_UNIX_TIME_PREPART2, + PL_UNIX_TIME_PART2, + PL_UNIX_TIME_PREPART3, + PL_UNIX_TIME_PART3 + } time; + + enum { + PL_UNIX_FILENAME_PRESPACE = 0, + PL_UNIX_FILENAME_NAME, + PL_UNIX_FILENAME_WINDOWSEOL + } filename; + + enum { + PL_UNIX_SYMLINK_PRESPACE = 0, + PL_UNIX_SYMLINK_NAME, + PL_UNIX_SYMLINK_PRETARGET1, + PL_UNIX_SYMLINK_PRETARGET2, + PL_UNIX_SYMLINK_PRETARGET3, + PL_UNIX_SYMLINK_PRETARGET4, + PL_UNIX_SYMLINK_TARGET, + PL_UNIX_SYMLINK_WINDOWSEOL + } symlink; +} pl_unix_substate; + +typedef enum { + PL_WINNT_DATE = 0, + PL_WINNT_TIME, + PL_WINNT_DIRORSIZE, + PL_WINNT_FILENAME +} pl_winNT_mainstate; + +typedef union { + enum { + PL_WINNT_TIME_PRESPACE = 0, + PL_WINNT_TIME_TIME + } time; + enum { + PL_WINNT_DIRORSIZE_PRESPACE = 0, + PL_WINNT_DIRORSIZE_CONTENT + } dirorsize; + enum { + PL_WINNT_FILENAME_PRESPACE = 0, + PL_WINNT_FILENAME_CONTENT, + PL_WINNT_FILENAME_WINEOL + } filename; +} pl_winNT_substate; + +/* This struct is used in wildcard downloading - for parsing LIST response */ +struct ftp_parselist_data { + enum { + OS_TYPE_UNKNOWN = 0, + OS_TYPE_UNIX, + OS_TYPE_WIN_NT + } os_type; + + union { + struct { + pl_unix_mainstate main; + pl_unix_substate sub; + } UNIX; + + struct { + pl_winNT_mainstate main; + pl_winNT_substate sub; + } NT; + } state; + + CURLcode error; + struct fileinfo *file_data; + unsigned int item_length; + size_t item_offset; + struct { + size_t filename; + size_t user; + size_t group; + size_t time; + size_t perm; + size_t symlink_target; + } offsets; +}; + +static void fileinfo_dtor(void *user, void *element) +{ + (void)user; + Curl_fileinfo_cleanup(element); +} + +CURLcode Curl_wildcard_init(struct WildcardData *wc) +{ + Curl_llist_init(&wc->filelist, fileinfo_dtor); + wc->state = CURLWC_INIT; + + return CURLE_OK; +} + +void Curl_wildcard_dtor(struct WildcardData **wcp) +{ + struct WildcardData *wc = *wcp; + if(!wc) + return; + + if(wc->dtor) { + wc->dtor(wc->ftpwc); + wc->dtor = ZERO_NULL; + wc->ftpwc = NULL; + } + DEBUGASSERT(wc->ftpwc == NULL); + + Curl_llist_destroy(&wc->filelist, NULL); + free(wc->path); + wc->path = NULL; + free(wc->pattern); + wc->pattern = NULL; + wc->state = CURLWC_INIT; + free(wc); + *wcp = NULL; +} + +struct ftp_parselist_data *Curl_ftp_parselist_data_alloc(void) +{ + return calloc(1, sizeof(struct ftp_parselist_data)); +} + + +void Curl_ftp_parselist_data_free(struct ftp_parselist_data **parserp) +{ + struct ftp_parselist_data *parser = *parserp; + if(parser) + Curl_fileinfo_cleanup(parser->file_data); + free(parser); + *parserp = NULL; +} + + +CURLcode Curl_ftp_parselist_geterror(struct ftp_parselist_data *pl_data) +{ + return pl_data->error; +} + + +#define FTP_LP_MALFORMATED_PERM 0x01000000 + +static unsigned int ftp_pl_get_permission(const char *str) +{ + unsigned int permissions = 0; + /* USER */ + if(str[0] == 'r') + permissions |= 1 << 8; + else if(str[0] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + if(str[1] == 'w') + permissions |= 1 << 7; + else if(str[1] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + + if(str[2] == 'x') + permissions |= 1 << 6; + else if(str[2] == 's') { + permissions |= 1 << 6; + permissions |= 1 << 11; + } + else if(str[2] == 'S') + permissions |= 1 << 11; + else if(str[2] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + /* GROUP */ + if(str[3] == 'r') + permissions |= 1 << 5; + else if(str[3] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + if(str[4] == 'w') + permissions |= 1 << 4; + else if(str[4] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + if(str[5] == 'x') + permissions |= 1 << 3; + else if(str[5] == 's') { + permissions |= 1 << 3; + permissions |= 1 << 10; + } + else if(str[5] == 'S') + permissions |= 1 << 10; + else if(str[5] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + /* others */ + if(str[6] == 'r') + permissions |= 1 << 2; + else if(str[6] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + if(str[7] == 'w') + permissions |= 1 << 1; + else if(str[7] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + if(str[8] == 'x') + permissions |= 1; + else if(str[8] == 't') { + permissions |= 1; + permissions |= 1 << 9; + } + else if(str[8] == 'T') + permissions |= 1 << 9; + else if(str[8] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + + return permissions; +} + +static CURLcode ftp_pl_insert_finfo(struct Curl_easy *data, + struct fileinfo *infop) +{ + curl_fnmatch_callback compare; + struct WildcardData *wc = data->wildcard; + struct ftp_wc *ftpwc = wc->ftpwc; + struct Curl_llist *llist = &wc->filelist; + struct ftp_parselist_data *parser = ftpwc->parser; + bool add = TRUE; + struct curl_fileinfo *finfo = &infop->info; + + /* set the finfo pointers */ + char *str = Curl_dyn_ptr(&infop->buf); + finfo->filename = str + parser->offsets.filename; + finfo->strings.group = parser->offsets.group ? + str + parser->offsets.group : NULL; + finfo->strings.perm = parser->offsets.perm ? + str + parser->offsets.perm : NULL; + finfo->strings.target = parser->offsets.symlink_target ? + str + parser->offsets.symlink_target : NULL; + finfo->strings.time = str + parser->offsets.time; + finfo->strings.user = parser->offsets.user ? + str + parser->offsets.user : NULL; + + /* get correct fnmatch callback */ + compare = data->set.fnmatch; + if(!compare) + compare = Curl_fnmatch; + + /* filter pattern-corresponding filenames */ + Curl_set_in_callback(data, true); + if(compare(data->set.fnmatch_data, wc->pattern, + finfo->filename) == 0) { + /* discard symlink which is containing multiple " -> " */ + if((finfo->filetype == CURLFILETYPE_SYMLINK) && finfo->strings.target && + (strstr(finfo->strings.target, " -> "))) { + add = FALSE; + } + } + else { + add = FALSE; + } + Curl_set_in_callback(data, false); + + if(add) { + Curl_llist_append(llist, finfo, &infop->list); + } + else { + Curl_fileinfo_cleanup(infop); + } + + ftpwc->parser->file_data = NULL; + return CURLE_OK; +} + +#define MAX_FTPLIST_BUFFER 10000 /* arbitrarily set */ + +size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb, + void *connptr) +{ + size_t bufflen = size*nmemb; + struct Curl_easy *data = (struct Curl_easy *)connptr; + struct ftp_wc *ftpwc = data->wildcard->ftpwc; + struct ftp_parselist_data *parser = ftpwc->parser; + size_t i = 0; + CURLcode result; + size_t retsize = bufflen; + + if(parser->error) { /* error in previous call */ + /* scenario: + * 1. call => OK.. + * 2. call => OUT_OF_MEMORY (or other error) + * 3. (last) call => is skipped RIGHT HERE and the error is handled later + * in wc_statemach() + */ + goto fail; + } + + if(parser->os_type == OS_TYPE_UNKNOWN && bufflen > 0) { + /* considering info about FILE response format */ + parser->os_type = ISDIGIT(buffer[0]) ? OS_TYPE_WIN_NT : OS_TYPE_UNIX; + } + + while(i < bufflen) { /* FSM */ + char *mem; + size_t len; /* number of bytes of data in the dynbuf */ + char c = buffer[i]; + struct fileinfo *infop; + struct curl_fileinfo *finfo; + if(!parser->file_data) { /* tmp file data is not allocated yet */ + parser->file_data = Curl_fileinfo_alloc(); + if(!parser->file_data) { + parser->error = CURLE_OUT_OF_MEMORY; + goto fail; + } + parser->item_offset = 0; + parser->item_length = 0; + Curl_dyn_init(&parser->file_data->buf, MAX_FTPLIST_BUFFER); + } + + infop = parser->file_data; + finfo = &infop->info; + + if(Curl_dyn_addn(&infop->buf, &c, 1)) { + parser->error = CURLE_OUT_OF_MEMORY; + goto fail; + } + len = Curl_dyn_len(&infop->buf); + mem = Curl_dyn_ptr(&infop->buf); + + switch(parser->os_type) { + case OS_TYPE_UNIX: + switch(parser->state.UNIX.main) { + case PL_UNIX_TOTALSIZE: + switch(parser->state.UNIX.sub.total_dirsize) { + case PL_UNIX_TOTALSIZE_INIT: + if(c == 't') { + parser->state.UNIX.sub.total_dirsize = PL_UNIX_TOTALSIZE_READING; + parser->item_length++; + } + else { + parser->state.UNIX.main = PL_UNIX_FILETYPE; + /* start FSM again not considering size of directory */ + Curl_dyn_reset(&infop->buf); + continue; + } + break; + case PL_UNIX_TOTALSIZE_READING: + parser->item_length++; + if(c == '\r') { + parser->item_length--; + Curl_dyn_setlen(&infop->buf, --len); + } + else if(c == '\n') { + mem[parser->item_length - 1] = 0; + if(!strncmp("total ", mem, 6)) { + char *endptr = mem + 6; + /* here we can deal with directory size, pass the leading + whitespace and then the digits */ + while(ISBLANK(*endptr)) + endptr++; + while(ISDIGIT(*endptr)) + endptr++; + if(*endptr) { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + parser->state.UNIX.main = PL_UNIX_FILETYPE; + Curl_dyn_reset(&infop->buf); + } + else { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + } + break; + } + break; + case PL_UNIX_FILETYPE: + switch(c) { + case '-': + finfo->filetype = CURLFILETYPE_FILE; + break; + case 'd': + finfo->filetype = CURLFILETYPE_DIRECTORY; + break; + case 'l': + finfo->filetype = CURLFILETYPE_SYMLINK; + break; + case 'p': + finfo->filetype = CURLFILETYPE_NAMEDPIPE; + break; + case 's': + finfo->filetype = CURLFILETYPE_SOCKET; + break; + case 'c': + finfo->filetype = CURLFILETYPE_DEVICE_CHAR; + break; + case 'b': + finfo->filetype = CURLFILETYPE_DEVICE_BLOCK; + break; + case 'D': + finfo->filetype = CURLFILETYPE_DOOR; + break; + default: + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + parser->state.UNIX.main = PL_UNIX_PERMISSION; + parser->item_length = 0; + parser->item_offset = 1; + break; + case PL_UNIX_PERMISSION: + parser->item_length++; + if(parser->item_length <= 9) { + if(!strchr("rwx-tTsS", c)) { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + } + else if(parser->item_length == 10) { + unsigned int perm; + if(c != ' ') { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + mem[10] = 0; /* terminate permissions */ + perm = ftp_pl_get_permission(mem + parser->item_offset); + if(perm & FTP_LP_MALFORMATED_PERM) { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_PERM; + parser->file_data->info.perm = perm; + parser->offsets.perm = parser->item_offset; + + parser->item_length = 0; + parser->state.UNIX.main = PL_UNIX_HLINKS; + parser->state.UNIX.sub.hlinks = PL_UNIX_HLINKS_PRESPACE; + } + break; + case PL_UNIX_HLINKS: + switch(parser->state.UNIX.sub.hlinks) { + case PL_UNIX_HLINKS_PRESPACE: + if(c != ' ') { + if(ISDIGIT(c)) { + parser->item_offset = len - 1; + parser->item_length = 1; + parser->state.UNIX.sub.hlinks = PL_UNIX_HLINKS_NUMBER; + } + else { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + } + break; + case PL_UNIX_HLINKS_NUMBER: + parser->item_length ++; + if(c == ' ') { + char *p; + long int hlinks; + mem[parser->item_offset + parser->item_length - 1] = 0; + hlinks = strtol(mem + parser->item_offset, &p, 10); + if(p[0] == '\0' && hlinks != LONG_MAX && hlinks != LONG_MIN) { + parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_HLINKCOUNT; + parser->file_data->info.hardlinks = hlinks; + } + parser->item_length = 0; + parser->item_offset = 0; + parser->state.UNIX.main = PL_UNIX_USER; + parser->state.UNIX.sub.user = PL_UNIX_USER_PRESPACE; + } + else if(!ISDIGIT(c)) { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + break; + } + break; + case PL_UNIX_USER: + switch(parser->state.UNIX.sub.user) { + case PL_UNIX_USER_PRESPACE: + if(c != ' ') { + parser->item_offset = len - 1; + parser->item_length = 1; + parser->state.UNIX.sub.user = PL_UNIX_USER_PARSING; + } + break; + case PL_UNIX_USER_PARSING: + parser->item_length++; + if(c == ' ') { + mem[parser->item_offset + parser->item_length - 1] = 0; + parser->offsets.user = parser->item_offset; + parser->state.UNIX.main = PL_UNIX_GROUP; + parser->state.UNIX.sub.group = PL_UNIX_GROUP_PRESPACE; + parser->item_offset = 0; + parser->item_length = 0; + } + break; + } + break; + case PL_UNIX_GROUP: + switch(parser->state.UNIX.sub.group) { + case PL_UNIX_GROUP_PRESPACE: + if(c != ' ') { + parser->item_offset = len - 1; + parser->item_length = 1; + parser->state.UNIX.sub.group = PL_UNIX_GROUP_NAME; + } + break; + case PL_UNIX_GROUP_NAME: + parser->item_length++; + if(c == ' ') { + mem[parser->item_offset + parser->item_length - 1] = 0; + parser->offsets.group = parser->item_offset; + parser->state.UNIX.main = PL_UNIX_SIZE; + parser->state.UNIX.sub.size = PL_UNIX_SIZE_PRESPACE; + parser->item_offset = 0; + parser->item_length = 0; + } + break; + } + break; + case PL_UNIX_SIZE: + switch(parser->state.UNIX.sub.size) { + case PL_UNIX_SIZE_PRESPACE: + if(c != ' ') { + if(ISDIGIT(c)) { + parser->item_offset = len - 1; + parser->item_length = 1; + parser->state.UNIX.sub.size = PL_UNIX_SIZE_NUMBER; + } + else { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + } + break; + case PL_UNIX_SIZE_NUMBER: + parser->item_length++; + if(c == ' ') { + char *p; + curl_off_t fsize; + mem[parser->item_offset + parser->item_length - 1] = 0; + if(!curlx_strtoofft(mem + parser->item_offset, + &p, 10, &fsize)) { + if(p[0] == '\0' && fsize != CURL_OFF_T_MAX && + fsize != CURL_OFF_T_MIN) { + parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_SIZE; + parser->file_data->info.size = fsize; + } + parser->item_length = 0; + parser->item_offset = 0; + parser->state.UNIX.main = PL_UNIX_TIME; + parser->state.UNIX.sub.time = PL_UNIX_TIME_PREPART1; + } + } + else if(!ISDIGIT(c)) { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + break; + } + break; + case PL_UNIX_TIME: + switch(parser->state.UNIX.sub.time) { + case PL_UNIX_TIME_PREPART1: + if(c != ' ') { + if(ISALNUM(c)) { + parser->item_offset = len -1; + parser->item_length = 1; + parser->state.UNIX.sub.time = PL_UNIX_TIME_PART1; + } + else { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + } + break; + case PL_UNIX_TIME_PART1: + parser->item_length++; + if(c == ' ') { + parser->state.UNIX.sub.time = PL_UNIX_TIME_PREPART2; + } + else if(!ISALNUM(c) && c != '.') { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + break; + case PL_UNIX_TIME_PREPART2: + parser->item_length++; + if(c != ' ') { + if(ISALNUM(c)) { + parser->state.UNIX.sub.time = PL_UNIX_TIME_PART2; + } + else { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + } + break; + case PL_UNIX_TIME_PART2: + parser->item_length++; + if(c == ' ') { + parser->state.UNIX.sub.time = PL_UNIX_TIME_PREPART3; + } + else if(!ISALNUM(c) && c != '.') { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + break; + case PL_UNIX_TIME_PREPART3: + parser->item_length++; + if(c != ' ') { + if(ISALNUM(c)) { + parser->state.UNIX.sub.time = PL_UNIX_TIME_PART3; + } + else { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + } + break; + case PL_UNIX_TIME_PART3: + parser->item_length++; + if(c == ' ') { + mem[parser->item_offset + parser->item_length -1] = 0; + parser->offsets.time = parser->item_offset; + /* + if(ftp_pl_gettime(parser, finfo->mem + parser->item_offset)) { + parser->file_data->flags |= CURLFINFOFLAG_KNOWN_TIME; + } + */ + if(finfo->filetype == CURLFILETYPE_SYMLINK) { + parser->state.UNIX.main = PL_UNIX_SYMLINK; + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRESPACE; + } + else { + parser->state.UNIX.main = PL_UNIX_FILENAME; + parser->state.UNIX.sub.filename = PL_UNIX_FILENAME_PRESPACE; + } + } + else if(!ISALNUM(c) && c != '.' && c != ':') { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + break; + } + break; + case PL_UNIX_FILENAME: + switch(parser->state.UNIX.sub.filename) { + case PL_UNIX_FILENAME_PRESPACE: + if(c != ' ') { + parser->item_offset = len - 1; + parser->item_length = 1; + parser->state.UNIX.sub.filename = PL_UNIX_FILENAME_NAME; + } + break; + case PL_UNIX_FILENAME_NAME: + parser->item_length++; + if(c == '\r') { + parser->state.UNIX.sub.filename = PL_UNIX_FILENAME_WINDOWSEOL; + } + else if(c == '\n') { + mem[parser->item_offset + parser->item_length - 1] = 0; + parser->offsets.filename = parser->item_offset; + parser->state.UNIX.main = PL_UNIX_FILETYPE; + result = ftp_pl_insert_finfo(data, infop); + if(result) { + parser->error = result; + goto fail; + } + } + break; + case PL_UNIX_FILENAME_WINDOWSEOL: + if(c == '\n') { + mem[parser->item_offset + parser->item_length - 1] = 0; + parser->offsets.filename = parser->item_offset; + parser->state.UNIX.main = PL_UNIX_FILETYPE; + result = ftp_pl_insert_finfo(data, infop); + if(result) { + parser->error = result; + goto fail; + } + } + else { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + break; + } + break; + case PL_UNIX_SYMLINK: + switch(parser->state.UNIX.sub.symlink) { + case PL_UNIX_SYMLINK_PRESPACE: + if(c != ' ') { + parser->item_offset = len - 1; + parser->item_length = 1; + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME; + } + break; + case PL_UNIX_SYMLINK_NAME: + parser->item_length++; + if(c == ' ') { + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET1; + } + else if(c == '\r' || c == '\n') { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + break; + case PL_UNIX_SYMLINK_PRETARGET1: + parser->item_length++; + if(c == '-') { + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET2; + } + else if(c == '\r' || c == '\n') { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + else { + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME; + } + break; + case PL_UNIX_SYMLINK_PRETARGET2: + parser->item_length++; + if(c == '>') { + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET3; + } + else if(c == '\r' || c == '\n') { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + else { + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME; + } + break; + case PL_UNIX_SYMLINK_PRETARGET3: + parser->item_length++; + if(c == ' ') { + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET4; + /* now place where is symlink following */ + mem[parser->item_offset + parser->item_length - 4] = 0; + parser->offsets.filename = parser->item_offset; + parser->item_length = 0; + parser->item_offset = 0; + } + else if(c == '\r' || c == '\n') { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + else { + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME; + } + break; + case PL_UNIX_SYMLINK_PRETARGET4: + if(c != '\r' && c != '\n') { + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_TARGET; + parser->item_offset = len - 1; + parser->item_length = 1; + } + else { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + break; + case PL_UNIX_SYMLINK_TARGET: + parser->item_length++; + if(c == '\r') { + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_WINDOWSEOL; + } + else if(c == '\n') { + mem[parser->item_offset + parser->item_length - 1] = 0; + parser->offsets.symlink_target = parser->item_offset; + result = ftp_pl_insert_finfo(data, infop); + if(result) { + parser->error = result; + goto fail; + } + parser->state.UNIX.main = PL_UNIX_FILETYPE; + } + break; + case PL_UNIX_SYMLINK_WINDOWSEOL: + if(c == '\n') { + mem[parser->item_offset + parser->item_length - 1] = 0; + parser->offsets.symlink_target = parser->item_offset; + result = ftp_pl_insert_finfo(data, infop); + if(result) { + parser->error = result; + goto fail; + } + parser->state.UNIX.main = PL_UNIX_FILETYPE; + } + else { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + break; + } + break; + } + break; + case OS_TYPE_WIN_NT: + switch(parser->state.NT.main) { + case PL_WINNT_DATE: + parser->item_length++; + if(parser->item_length < 9) { + if(!strchr("0123456789-", c)) { /* only simple control */ + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + } + else if(parser->item_length == 9) { + if(c == ' ') { + parser->state.NT.main = PL_WINNT_TIME; + parser->state.NT.sub.time = PL_WINNT_TIME_PRESPACE; + } + else { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + } + else { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + break; + case PL_WINNT_TIME: + parser->item_length++; + switch(parser->state.NT.sub.time) { + case PL_WINNT_TIME_PRESPACE: + if(!ISBLANK(c)) { + parser->state.NT.sub.time = PL_WINNT_TIME_TIME; + } + break; + case PL_WINNT_TIME_TIME: + if(c == ' ') { + parser->offsets.time = parser->item_offset; + mem[parser->item_offset + parser->item_length -1] = 0; + parser->state.NT.main = PL_WINNT_DIRORSIZE; + parser->state.NT.sub.dirorsize = PL_WINNT_DIRORSIZE_PRESPACE; + parser->item_length = 0; + } + else if(!strchr("APM0123456789:", c)) { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + break; + } + break; + case PL_WINNT_DIRORSIZE: + switch(parser->state.NT.sub.dirorsize) { + case PL_WINNT_DIRORSIZE_PRESPACE: + if(c != ' ') { + parser->item_offset = len - 1; + parser->item_length = 1; + parser->state.NT.sub.dirorsize = PL_WINNT_DIRORSIZE_CONTENT; + } + break; + case PL_WINNT_DIRORSIZE_CONTENT: + parser->item_length ++; + if(c == ' ') { + mem[parser->item_offset + parser->item_length - 1] = 0; + if(strcmp("", mem + parser->item_offset) == 0) { + finfo->filetype = CURLFILETYPE_DIRECTORY; + finfo->size = 0; + } + else { + char *endptr; + if(curlx_strtoofft(mem + + parser->item_offset, + &endptr, 10, &finfo->size)) { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + /* correct file type */ + parser->file_data->info.filetype = CURLFILETYPE_FILE; + } + + parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_SIZE; + parser->item_length = 0; + parser->state.NT.main = PL_WINNT_FILENAME; + parser->state.NT.sub.filename = PL_WINNT_FILENAME_PRESPACE; + } + break; + } + break; + case PL_WINNT_FILENAME: + switch(parser->state.NT.sub.filename) { + case PL_WINNT_FILENAME_PRESPACE: + if(c != ' ') { + parser->item_offset = len -1; + parser->item_length = 1; + parser->state.NT.sub.filename = PL_WINNT_FILENAME_CONTENT; + } + break; + case PL_WINNT_FILENAME_CONTENT: + parser->item_length++; + if(c == '\r') { + parser->state.NT.sub.filename = PL_WINNT_FILENAME_WINEOL; + mem[len - 1] = 0; + } + else if(c == '\n') { + parser->offsets.filename = parser->item_offset; + mem[len - 1] = 0; + result = ftp_pl_insert_finfo(data, infop); + if(result) { + parser->error = result; + goto fail; + } + parser->state.NT.main = PL_WINNT_DATE; + parser->state.NT.sub.filename = PL_WINNT_FILENAME_PRESPACE; + } + break; + case PL_WINNT_FILENAME_WINEOL: + if(c == '\n') { + parser->offsets.filename = parser->item_offset; + result = ftp_pl_insert_finfo(data, infop); + if(result) { + parser->error = result; + goto fail; + } + parser->state.NT.main = PL_WINNT_DATE; + parser->state.NT.sub.filename = PL_WINNT_FILENAME_PRESPACE; + } + else { + parser->error = CURLE_FTP_BAD_FILE_LIST; + goto fail; + } + break; + } + break; + } + break; + default: + retsize = bufflen + 1; + goto fail; + } + + i++; + } + return retsize; + +fail: + + /* Clean up any allocated memory. */ + if(parser->file_data) { + Curl_fileinfo_cleanup(parser->file_data); + parser->file_data = NULL; + } + + return retsize; +} + +#endif /* CURL_DISABLE_FTP */ diff --git a/third_party/curl/lib/ftplistparser.h b/third_party/curl/lib/ftplistparser.h new file mode 100644 index 0000000..5ba1f6a --- /dev/null +++ b/third_party/curl/lib/ftplistparser.h @@ -0,0 +1,77 @@ +#ifndef HEADER_CURL_FTPLISTPARSER_H +#define HEADER_CURL_FTPLISTPARSER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_FTP + +/* WRITEFUNCTION callback for parsing LIST responses */ +size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb, + void *connptr); + +struct ftp_parselist_data; /* defined inside ftplibparser.c */ + +CURLcode Curl_ftp_parselist_geterror(struct ftp_parselist_data *pl_data); + +struct ftp_parselist_data *Curl_ftp_parselist_data_alloc(void); + +void Curl_ftp_parselist_data_free(struct ftp_parselist_data **pl_data); + +/* list of wildcard process states */ +typedef enum { + CURLWC_CLEAR = 0, + CURLWC_INIT = 1, + CURLWC_MATCHING, /* library is trying to get list of addresses for + downloading */ + CURLWC_DOWNLOADING, + CURLWC_CLEAN, /* deallocate resources and reset settings */ + CURLWC_SKIP, /* skip over concrete file */ + CURLWC_ERROR, /* error cases */ + CURLWC_DONE /* if is wildcard->state == CURLWC_DONE wildcard loop + will end */ +} wildcard_states; + +typedef void (*wildcard_dtor)(void *ptr); + +/* struct keeping information about wildcard download process */ +struct WildcardData { + char *path; /* path to the directory, where we trying wildcard-match */ + char *pattern; /* wildcard pattern */ + struct Curl_llist filelist; /* llist with struct Curl_fileinfo */ + struct ftp_wc *ftpwc; /* pointer to FTP wildcard data */ + wildcard_dtor dtor; + unsigned char state; /* wildcard_states */ +}; + +CURLcode Curl_wildcard_init(struct WildcardData *wc); +void Curl_wildcard_dtor(struct WildcardData **wcp); + +struct Curl_easy; + +#else +/* FTP is disabled */ +#define Curl_wildcard_dtor(x) +#endif /* CURL_DISABLE_FTP */ +#endif /* HEADER_CURL_FTPLISTPARSER_H */ diff --git a/third_party/curl/lib/functypes.h b/third_party/curl/lib/functypes.h new file mode 100644 index 0000000..ea66d32 --- /dev/null +++ b/third_party/curl/lib/functypes.h @@ -0,0 +1,115 @@ +#ifndef HEADER_CURL_FUNCTYPES_H +#define HEADER_CURL_FUNCTYPES_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +/* defaults: + + ssize_t recv(int, void *, size_t, int); + ssize_t send(int, const void *, size_t, int); + + If other argument or return types are needed: + + 1. For systems that run configure or cmake, the alternatives are provided + here. + 2. For systems with config-*.h files, define them there. +*/ + +#ifdef _WIN32 +/* int recv(SOCKET, char *, int, int) */ +#define RECV_TYPE_ARG1 SOCKET +#define RECV_TYPE_ARG2 char * +#define RECV_TYPE_ARG3 int +#define RECV_TYPE_RETV int + +/* int send(SOCKET, const char *, int, int); */ +#define SEND_TYPE_ARG1 SOCKET +#define SEND_TYPE_ARG2 char * +#define SEND_TYPE_ARG3 int +#define SEND_TYPE_RETV int + +#elif defined(__AMIGA__) /* Any AmigaOS flavour */ + +/* long recv(long, char *, long, long); */ +#define RECV_TYPE_ARG1 long +#define RECV_TYPE_ARG2 char * +#define RECV_TYPE_ARG3 long +#define RECV_TYPE_ARG4 long +#define RECV_TYPE_RETV long + +/* int send(int, const char *, int, int); */ +#define SEND_TYPE_ARG1 int +#define SEND_TYPE_ARG2 char * +#define SEND_TYPE_ARG3 int +#define SEND_TYPE_RETV int +#endif + + +#ifndef RECV_TYPE_ARG1 +#define RECV_TYPE_ARG1 int +#endif + +#ifndef RECV_TYPE_ARG2 +#define RECV_TYPE_ARG2 void * +#endif + +#ifndef RECV_TYPE_ARG3 +#define RECV_TYPE_ARG3 size_t +#endif + +#ifndef RECV_TYPE_ARG4 +#define RECV_TYPE_ARG4 int +#endif + +#ifndef RECV_TYPE_RETV +#define RECV_TYPE_RETV ssize_t +#endif + +#ifndef SEND_QUAL_ARG2 +#define SEND_QUAL_ARG2 const +#endif + +#ifndef SEND_TYPE_ARG1 +#define SEND_TYPE_ARG1 int +#endif + +#ifndef SEND_TYPE_ARG2 +#define SEND_TYPE_ARG2 void * +#endif + +#ifndef SEND_TYPE_ARG3 +#define SEND_TYPE_ARG3 size_t +#endif + +#ifndef SEND_TYPE_ARG4 +#define SEND_TYPE_ARG4 int +#endif + +#ifndef SEND_TYPE_RETV +#define SEND_TYPE_RETV ssize_t +#endif + +#endif /* HEADER_CURL_FUNCTYPES_H */ diff --git a/third_party/curl/lib/getenv.c b/third_party/curl/lib/getenv.c new file mode 100644 index 0000000..48ee972 --- /dev/null +++ b/third_party/curl/lib/getenv.c @@ -0,0 +1,80 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include +#include "curl_memory.h" + +#include "memdebug.h" + +static char *GetEnv(const char *variable) +{ +#if defined(_WIN32_WCE) || defined(CURL_WINDOWS_APP) || \ + defined(__ORBIS__) || defined(__PROSPERO__) /* PlayStation 4 and 5 */ + (void)variable; + return NULL; +#elif defined(_WIN32) + /* This uses Windows API instead of C runtime getenv() to get the environment + variable since some changes aren't always visible to the latter. #4774 */ + char *buf = NULL; + char *tmp; + DWORD bufsize; + DWORD rc = 1; + const DWORD max = 32768; /* max env var size from MSCRT source */ + + for(;;) { + tmp = realloc(buf, rc); + if(!tmp) { + free(buf); + return NULL; + } + + buf = tmp; + bufsize = rc; + + /* It's possible for rc to be 0 if the variable was found but empty. + Since getenv doesn't make that distinction we ignore it as well. */ + rc = GetEnvironmentVariableA(variable, buf, bufsize); + if(!rc || rc == bufsize || rc > max) { + free(buf); + return NULL; + } + + /* if rc < bufsize then rc is bytes written not including null */ + if(rc < bufsize) + return buf; + + /* else rc is bytes needed, try again */ + } +#else + char *env = getenv(variable); + return (env && env[0])?strdup(env):NULL; +#endif +} + +char *curl_getenv(const char *v) +{ + return GetEnv(v); +} diff --git a/third_party/curl/lib/getinfo.c b/third_party/curl/lib/getinfo.c new file mode 100644 index 0000000..e423f0b --- /dev/null +++ b/third_party/curl/lib/getinfo.c @@ -0,0 +1,640 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "urldata.h" +#include "getinfo.h" + +#include "vtls/vtls.h" +#include "connect.h" /* Curl_getconnectinfo() */ +#include "progress.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Initialize statistical and informational data. + * + * This function is called in curl_easy_reset, curl_easy_duphandle and at the + * beginning of a perform session. It must reset the session-info variables, + * in particular all variables in struct PureInfo. + */ +CURLcode Curl_initinfo(struct Curl_easy *data) +{ + struct Progress *pro = &data->progress; + struct PureInfo *info = &data->info; + + pro->t_nslookup = 0; + pro->t_connect = 0; + pro->t_appconnect = 0; + pro->t_pretransfer = 0; + pro->t_starttransfer = 0; + pro->timespent = 0; + pro->t_redirect = 0; + pro->is_t_startransfer_set = false; + + info->httpcode = 0; + info->httpproxycode = 0; + info->httpversion = 0; + info->filetime = -1; /* -1 is an illegal time and thus means unknown */ + info->timecond = FALSE; + + info->header_size = 0; + info->request_size = 0; + info->proxyauthavail = 0; + info->httpauthavail = 0; + info->numconnects = 0; + + free(info->contenttype); + info->contenttype = NULL; + + free(info->wouldredirect); + info->wouldredirect = NULL; + + info->primary.remote_ip[0] = '\0'; + info->primary.local_ip[0] = '\0'; + info->primary.remote_port = 0; + info->primary.local_port = 0; + info->retry_after = 0; + + info->conn_scheme = 0; + info->conn_protocol = 0; + +#ifdef USE_SSL + Curl_ssl_free_certinfo(data); +#endif + return CURLE_OK; +} + +static CURLcode getinfo_char(struct Curl_easy *data, CURLINFO info, + const char **param_charp) +{ + switch(info) { + case CURLINFO_EFFECTIVE_URL: + *param_charp = data->state.url?data->state.url:(char *)""; + break; + case CURLINFO_EFFECTIVE_METHOD: { + const char *m = data->set.str[STRING_CUSTOMREQUEST]; + if(!m) { + if(data->set.opt_no_body) + m = "HEAD"; +#ifndef CURL_DISABLE_HTTP + else { + switch(data->state.httpreq) { + case HTTPREQ_POST: + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + m = "POST"; + break; + case HTTPREQ_PUT: + m = "PUT"; + break; + default: /* this should never happen */ + case HTTPREQ_GET: + m = "GET"; + break; + case HTTPREQ_HEAD: + m = "HEAD"; + break; + } + } +#endif + } + *param_charp = m; + } + break; + case CURLINFO_CONTENT_TYPE: + *param_charp = data->info.contenttype; + break; + case CURLINFO_PRIVATE: + *param_charp = (char *) data->set.private_data; + break; + case CURLINFO_FTP_ENTRY_PATH: + /* Return the entrypath string from the most recent connection. + This pointer was copied from the connectdata structure by FTP. + The actual string may be free()ed by subsequent libcurl calls so + it must be copied to a safer area before the next libcurl call. + Callers must never free it themselves. */ + *param_charp = data->state.most_recent_ftp_entrypath; + break; + case CURLINFO_REDIRECT_URL: + /* Return the URL this request would have been redirected to if that + option had been enabled! */ + *param_charp = data->info.wouldredirect; + break; + case CURLINFO_REFERER: + /* Return the referrer header for this request, or NULL if unset */ + *param_charp = data->state.referer; + break; + case CURLINFO_PRIMARY_IP: + /* Return the ip address of the most recent (primary) connection */ + *param_charp = data->info.primary.remote_ip; + break; + case CURLINFO_LOCAL_IP: + /* Return the source/local ip address of the most recent (primary) + connection */ + *param_charp = data->info.primary.local_ip; + break; + case CURLINFO_RTSP_SESSION_ID: +#ifndef CURL_DISABLE_RTSP + *param_charp = data->set.str[STRING_RTSP_SESSION_ID]; +#else + *param_charp = NULL; +#endif + break; + case CURLINFO_SCHEME: + *param_charp = data->info.conn_scheme; + break; + case CURLINFO_CAPATH: +#ifdef CURL_CA_PATH + *param_charp = CURL_CA_PATH; +#else + *param_charp = NULL; +#endif + break; + case CURLINFO_CAINFO: +#ifdef CURL_CA_BUNDLE + *param_charp = CURL_CA_BUNDLE; +#else + *param_charp = NULL; +#endif + break; + default: + return CURLE_UNKNOWN_OPTION; + } + + return CURLE_OK; +} + +static CURLcode getinfo_long(struct Curl_easy *data, CURLINFO info, + long *param_longp) +{ + curl_socket_t sockfd; + + union { + unsigned long *to_ulong; + long *to_long; + } lptr; + +#ifdef DEBUGBUILD + char *timestr = getenv("CURL_TIME"); + if(timestr) { + unsigned long val = strtol(timestr, NULL, 10); + switch(info) { + case CURLINFO_LOCAL_PORT: + *param_longp = (long)val; + return CURLE_OK; + default: + break; + } + } + /* use another variable for this to allow different values */ + timestr = getenv("CURL_DEBUG_SIZE"); + if(timestr) { + unsigned long val = strtol(timestr, NULL, 10); + switch(info) { + case CURLINFO_HEADER_SIZE: + case CURLINFO_REQUEST_SIZE: + *param_longp = (long)val; + return CURLE_OK; + default: + break; + } + } +#endif + + switch(info) { + case CURLINFO_RESPONSE_CODE: + *param_longp = data->info.httpcode; + break; + case CURLINFO_HTTP_CONNECTCODE: + *param_longp = data->info.httpproxycode; + break; + case CURLINFO_FILETIME: + if(data->info.filetime > LONG_MAX) + *param_longp = LONG_MAX; + else if(data->info.filetime < LONG_MIN) + *param_longp = LONG_MIN; + else + *param_longp = (long)data->info.filetime; + break; + case CURLINFO_HEADER_SIZE: + *param_longp = (long)data->info.header_size; + break; + case CURLINFO_REQUEST_SIZE: + *param_longp = (long)data->info.request_size; + break; + case CURLINFO_SSL_VERIFYRESULT: + *param_longp = data->set.ssl.certverifyresult; + break; +#ifndef CURL_DISABLE_PROXY + case CURLINFO_PROXY_SSL_VERIFYRESULT: + *param_longp = data->set.proxy_ssl.certverifyresult; + break; +#endif + case CURLINFO_REDIRECT_COUNT: + *param_longp = data->state.followlocation; + break; + case CURLINFO_HTTPAUTH_AVAIL: + lptr.to_long = param_longp; + *lptr.to_ulong = data->info.httpauthavail; + break; + case CURLINFO_PROXYAUTH_AVAIL: + lptr.to_long = param_longp; + *lptr.to_ulong = data->info.proxyauthavail; + break; + case CURLINFO_OS_ERRNO: + *param_longp = data->state.os_errno; + break; + case CURLINFO_NUM_CONNECTS: + *param_longp = data->info.numconnects; + break; + case CURLINFO_LASTSOCKET: + sockfd = Curl_getconnectinfo(data, NULL); + + /* note: this is not a good conversion for systems with 64 bit sockets and + 32 bit longs */ + if(sockfd != CURL_SOCKET_BAD) + *param_longp = (long)sockfd; + else + /* this interface is documented to return -1 in case of badness, which + may not be the same as the CURL_SOCKET_BAD value */ + *param_longp = -1; + break; + case CURLINFO_PRIMARY_PORT: + /* Return the (remote) port of the most recent (primary) connection */ + *param_longp = data->info.primary.remote_port; + break; + case CURLINFO_LOCAL_PORT: + /* Return the local port of the most recent (primary) connection */ + *param_longp = data->info.primary.local_port; + break; + case CURLINFO_PROXY_ERROR: + *param_longp = (long)data->info.pxcode; + break; + case CURLINFO_CONDITION_UNMET: + if(data->info.httpcode == 304) + *param_longp = 1L; + else + /* return if the condition prevented the document to get transferred */ + *param_longp = data->info.timecond ? 1L : 0L; + break; +#ifndef CURL_DISABLE_RTSP + case CURLINFO_RTSP_CLIENT_CSEQ: + *param_longp = data->state.rtsp_next_client_CSeq; + break; + case CURLINFO_RTSP_SERVER_CSEQ: + *param_longp = data->state.rtsp_next_server_CSeq; + break; + case CURLINFO_RTSP_CSEQ_RECV: + *param_longp = data->state.rtsp_CSeq_recv; + break; +#endif + case CURLINFO_HTTP_VERSION: + switch(data->info.httpversion) { + case 10: + *param_longp = CURL_HTTP_VERSION_1_0; + break; + case 11: + *param_longp = CURL_HTTP_VERSION_1_1; + break; + case 20: + *param_longp = CURL_HTTP_VERSION_2_0; + break; + case 30: + *param_longp = CURL_HTTP_VERSION_3; + break; + default: + *param_longp = CURL_HTTP_VERSION_NONE; + break; + } + break; + case CURLINFO_PROTOCOL: + *param_longp = data->info.conn_protocol; + break; + case CURLINFO_USED_PROXY: + *param_longp = +#ifdef CURL_DISABLE_PROXY + 0 +#else + data->info.used_proxy +#endif + ; + break; + default: + return CURLE_UNKNOWN_OPTION; + } + + return CURLE_OK; +} + +#define DOUBLE_SECS(x) (double)(x)/1000000 + +static CURLcode getinfo_offt(struct Curl_easy *data, CURLINFO info, + curl_off_t *param_offt) +{ +#ifdef DEBUGBUILD + char *timestr = getenv("CURL_TIME"); + if(timestr) { + unsigned long val = strtol(timestr, NULL, 10); + switch(info) { + case CURLINFO_TOTAL_TIME_T: + case CURLINFO_NAMELOOKUP_TIME_T: + case CURLINFO_CONNECT_TIME_T: + case CURLINFO_APPCONNECT_TIME_T: + case CURLINFO_PRETRANSFER_TIME_T: + case CURLINFO_STARTTRANSFER_TIME_T: + case CURLINFO_REDIRECT_TIME_T: + case CURLINFO_SPEED_DOWNLOAD_T: + case CURLINFO_SPEED_UPLOAD_T: + *param_offt = (curl_off_t)val; + return CURLE_OK; + default: + break; + } + } +#endif + switch(info) { + case CURLINFO_FILETIME_T: + *param_offt = (curl_off_t)data->info.filetime; + break; + case CURLINFO_SIZE_UPLOAD_T: + *param_offt = data->progress.uploaded; + break; + case CURLINFO_SIZE_DOWNLOAD_T: + *param_offt = data->progress.downloaded; + break; + case CURLINFO_SPEED_DOWNLOAD_T: + *param_offt = data->progress.dlspeed; + break; + case CURLINFO_SPEED_UPLOAD_T: + *param_offt = data->progress.ulspeed; + break; + case CURLINFO_CONTENT_LENGTH_DOWNLOAD_T: + *param_offt = (data->progress.flags & PGRS_DL_SIZE_KNOWN)? + data->progress.size_dl:-1; + break; + case CURLINFO_CONTENT_LENGTH_UPLOAD_T: + *param_offt = (data->progress.flags & PGRS_UL_SIZE_KNOWN)? + data->progress.size_ul:-1; + break; + case CURLINFO_TOTAL_TIME_T: + *param_offt = data->progress.timespent; + break; + case CURLINFO_NAMELOOKUP_TIME_T: + *param_offt = data->progress.t_nslookup; + break; + case CURLINFO_CONNECT_TIME_T: + *param_offt = data->progress.t_connect; + break; + case CURLINFO_APPCONNECT_TIME_T: + *param_offt = data->progress.t_appconnect; + break; + case CURLINFO_PRETRANSFER_TIME_T: + *param_offt = data->progress.t_pretransfer; + break; + case CURLINFO_STARTTRANSFER_TIME_T: + *param_offt = data->progress.t_starttransfer; + break; + case CURLINFO_QUEUE_TIME_T: + *param_offt = data->progress.t_postqueue; + break; + case CURLINFO_REDIRECT_TIME_T: + *param_offt = data->progress.t_redirect; + break; + case CURLINFO_RETRY_AFTER: + *param_offt = data->info.retry_after; + break; + case CURLINFO_XFER_ID: + *param_offt = data->id; + break; + case CURLINFO_CONN_ID: + *param_offt = data->conn? + data->conn->connection_id : data->state.recent_conn_id; + break; + default: + return CURLE_UNKNOWN_OPTION; + } + + return CURLE_OK; +} + +static CURLcode getinfo_double(struct Curl_easy *data, CURLINFO info, + double *param_doublep) +{ +#ifdef DEBUGBUILD + char *timestr = getenv("CURL_TIME"); + if(timestr) { + unsigned long val = strtol(timestr, NULL, 10); + switch(info) { + case CURLINFO_TOTAL_TIME: + case CURLINFO_NAMELOOKUP_TIME: + case CURLINFO_CONNECT_TIME: + case CURLINFO_APPCONNECT_TIME: + case CURLINFO_PRETRANSFER_TIME: + case CURLINFO_STARTTRANSFER_TIME: + case CURLINFO_REDIRECT_TIME: + case CURLINFO_SPEED_DOWNLOAD: + case CURLINFO_SPEED_UPLOAD: + *param_doublep = (double)val; + return CURLE_OK; + default: + break; + } + } +#endif + switch(info) { + case CURLINFO_TOTAL_TIME: + *param_doublep = DOUBLE_SECS(data->progress.timespent); + break; + case CURLINFO_NAMELOOKUP_TIME: + *param_doublep = DOUBLE_SECS(data->progress.t_nslookup); + break; + case CURLINFO_CONNECT_TIME: + *param_doublep = DOUBLE_SECS(data->progress.t_connect); + break; + case CURLINFO_APPCONNECT_TIME: + *param_doublep = DOUBLE_SECS(data->progress.t_appconnect); + break; + case CURLINFO_PRETRANSFER_TIME: + *param_doublep = DOUBLE_SECS(data->progress.t_pretransfer); + break; + case CURLINFO_STARTTRANSFER_TIME: + *param_doublep = DOUBLE_SECS(data->progress.t_starttransfer); + break; + case CURLINFO_SIZE_UPLOAD: + *param_doublep = (double)data->progress.uploaded; + break; + case CURLINFO_SIZE_DOWNLOAD: + *param_doublep = (double)data->progress.downloaded; + break; + case CURLINFO_SPEED_DOWNLOAD: + *param_doublep = (double)data->progress.dlspeed; + break; + case CURLINFO_SPEED_UPLOAD: + *param_doublep = (double)data->progress.ulspeed; + break; + case CURLINFO_CONTENT_LENGTH_DOWNLOAD: + *param_doublep = (data->progress.flags & PGRS_DL_SIZE_KNOWN)? + (double)data->progress.size_dl:-1; + break; + case CURLINFO_CONTENT_LENGTH_UPLOAD: + *param_doublep = (data->progress.flags & PGRS_UL_SIZE_KNOWN)? + (double)data->progress.size_ul:-1; + break; + case CURLINFO_REDIRECT_TIME: + *param_doublep = DOUBLE_SECS(data->progress.t_redirect); + break; + + default: + return CURLE_UNKNOWN_OPTION; + } + + return CURLE_OK; +} + +static CURLcode getinfo_slist(struct Curl_easy *data, CURLINFO info, + struct curl_slist **param_slistp) +{ + union { + struct curl_certinfo *to_certinfo; + struct curl_slist *to_slist; + } ptr; + + switch(info) { + case CURLINFO_SSL_ENGINES: + *param_slistp = Curl_ssl_engines_list(data); + break; + case CURLINFO_COOKIELIST: + *param_slistp = Curl_cookie_list(data); + break; + case CURLINFO_CERTINFO: + /* Return the a pointer to the certinfo struct. Not really an slist + pointer but we can pretend it is here */ + ptr.to_certinfo = &data->info.certs; + *param_slistp = ptr.to_slist; + break; + case CURLINFO_TLS_SESSION: + case CURLINFO_TLS_SSL_PTR: + { + struct curl_tlssessioninfo **tsip = (struct curl_tlssessioninfo **) + param_slistp; + struct curl_tlssessioninfo *tsi = &data->tsi; +#ifdef USE_SSL + struct connectdata *conn = data->conn; +#endif + + *tsip = tsi; + tsi->backend = Curl_ssl_backend(); + tsi->internals = NULL; + +#ifdef USE_SSL + if(conn && tsi->backend != CURLSSLBACKEND_NONE) { + tsi->internals = Curl_ssl_get_internals(data, FIRSTSOCKET, info, 0); + } +#endif + } + break; + default: + return CURLE_UNKNOWN_OPTION; + } + + return CURLE_OK; +} + +static CURLcode getinfo_socket(struct Curl_easy *data, CURLINFO info, + curl_socket_t *param_socketp) +{ + switch(info) { + case CURLINFO_ACTIVESOCKET: + *param_socketp = Curl_getconnectinfo(data, NULL); + break; + default: + return CURLE_UNKNOWN_OPTION; + } + + return CURLE_OK; +} + +CURLcode Curl_getinfo(struct Curl_easy *data, CURLINFO info, ...) +{ + va_list arg; + long *param_longp = NULL; + double *param_doublep = NULL; + curl_off_t *param_offt = NULL; + const char **param_charp = NULL; + struct curl_slist **param_slistp = NULL; + curl_socket_t *param_socketp = NULL; + int type; + CURLcode result = CURLE_UNKNOWN_OPTION; + + if(!data) + return CURLE_BAD_FUNCTION_ARGUMENT; + + va_start(arg, info); + + type = CURLINFO_TYPEMASK & (int)info; + switch(type) { + case CURLINFO_STRING: + param_charp = va_arg(arg, const char **); + if(param_charp) + result = getinfo_char(data, info, param_charp); + break; + case CURLINFO_LONG: + param_longp = va_arg(arg, long *); + if(param_longp) + result = getinfo_long(data, info, param_longp); + break; + case CURLINFO_DOUBLE: + param_doublep = va_arg(arg, double *); + if(param_doublep) + result = getinfo_double(data, info, param_doublep); + break; + case CURLINFO_OFF_T: + param_offt = va_arg(arg, curl_off_t *); + if(param_offt) + result = getinfo_offt(data, info, param_offt); + break; + case CURLINFO_SLIST: + param_slistp = va_arg(arg, struct curl_slist **); + if(param_slistp) + result = getinfo_slist(data, info, param_slistp); + break; + case CURLINFO_SOCKET: + param_socketp = va_arg(arg, curl_socket_t *); + if(param_socketp) + result = getinfo_socket(data, info, param_socketp); + break; + default: + break; + } + + va_end(arg); + + return result; +} diff --git a/third_party/curl/lib/getinfo.h b/third_party/curl/lib/getinfo.h new file mode 100644 index 0000000..56bb440 --- /dev/null +++ b/third_party/curl/lib/getinfo.h @@ -0,0 +1,29 @@ +#ifndef HEADER_CURL_GETINFO_H +#define HEADER_CURL_GETINFO_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +CURLcode Curl_getinfo(struct Curl_easy *data, CURLINFO info, ...); +CURLcode Curl_initinfo(struct Curl_easy *data); + +#endif /* HEADER_CURL_GETINFO_H */ diff --git a/third_party/curl/lib/gopher.c b/third_party/curl/lib/gopher.c new file mode 100644 index 0000000..311bd37 --- /dev/null +++ b/third_party/curl/lib/gopher.c @@ -0,0 +1,244 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_GOPHER + +#include "urldata.h" +#include +#include "transfer.h" +#include "sendf.h" +#include "cfilters.h" +#include "connect.h" +#include "progress.h" +#include "gopher.h" +#include "select.h" +#include "strdup.h" +#include "vtls/vtls.h" +#include "url.h" +#include "escape.h" +#include "warnless.h" +#include "curl_printf.h" +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + +/* + * Forward declarations. + */ + +static CURLcode gopher_do(struct Curl_easy *data, bool *done); +#ifdef USE_SSL +static CURLcode gopher_connect(struct Curl_easy *data, bool *done); +static CURLcode gopher_connecting(struct Curl_easy *data, bool *done); +#endif + +/* + * Gopher protocol handler. + * This is also a nice simple template to build off for simple + * connect-command-download protocols. + */ + +const struct Curl_handler Curl_handler_gopher = { + "gopher", /* scheme */ + ZERO_NULL, /* setup_connection */ + gopher_do, /* do_it */ + ZERO_NULL, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_GOPHER, /* defport */ + CURLPROTO_GOPHER, /* protocol */ + CURLPROTO_GOPHER, /* family */ + PROTOPT_NONE /* flags */ +}; + +#ifdef USE_SSL +const struct Curl_handler Curl_handler_gophers = { + "gophers", /* scheme */ + ZERO_NULL, /* setup_connection */ + gopher_do, /* do_it */ + ZERO_NULL, /* done */ + ZERO_NULL, /* do_more */ + gopher_connect, /* connect_it */ + gopher_connecting, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_GOPHER, /* defport */ + CURLPROTO_GOPHERS, /* protocol */ + CURLPROTO_GOPHER, /* family */ + PROTOPT_SSL /* flags */ +}; + +static CURLcode gopher_connect(struct Curl_easy *data, bool *done) +{ + (void)data; + (void)done; + return CURLE_OK; +} + +static CURLcode gopher_connecting(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + CURLcode result; + + result = Curl_conn_connect(data, FIRSTSOCKET, TRUE, done); + if(result) + connclose(conn, "Failed TLS connection"); + *done = TRUE; + return result; +} +#endif + +static CURLcode gopher_do(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; + char *gopherpath; + char *path = data->state.up.path; + char *query = data->state.up.query; + char *sel = NULL; + char *sel_org = NULL; + timediff_t timeout_ms; + ssize_t k; + size_t amount, len; + int what; + + *done = TRUE; /* unconditionally */ + + /* path is guaranteed non-NULL */ + DEBUGASSERT(path); + + if(query) + gopherpath = aprintf("%s?%s", path, query); + else + gopherpath = strdup(path); + + if(!gopherpath) + return CURLE_OUT_OF_MEMORY; + + /* Create selector. Degenerate cases: / and /1 => convert to "" */ + if(strlen(gopherpath) <= 2) { + sel = (char *)""; + len = strlen(sel); + free(gopherpath); + } + else { + char *newp; + + /* Otherwise, drop / and the first character (i.e., item type) ... */ + newp = gopherpath; + newp += 2; + + /* ... and finally unescape */ + result = Curl_urldecode(newp, 0, &sel, &len, REJECT_ZERO); + free(gopherpath); + if(result) + return result; + sel_org = sel; + } + + k = curlx_uztosz(len); + + for(;;) { + /* Break out of the loop if the selector is empty because OpenSSL and/or + LibreSSL fail with errno 0 if this is the case. */ + if(strlen(sel) < 1) + break; + + result = Curl_xfer_send(data, sel, k, &amount); + if(!result) { /* Which may not have written it all! */ + result = Curl_client_write(data, CLIENTWRITE_HEADER, sel, amount); + if(result) + break; + + k -= amount; + sel += amount; + if(k < 1) + break; /* but it did write it all */ + } + else + break; + + timeout_ms = Curl_timeleft(data, NULL, FALSE); + if(timeout_ms < 0) { + result = CURLE_OPERATION_TIMEDOUT; + break; + } + if(!timeout_ms) + timeout_ms = TIMEDIFF_T_MAX; + + /* Don't busyloop. The entire loop thing is a work-around as it causes a + BLOCKING behavior which is a NO-NO. This function should rather be + split up in a do and a doing piece where the pieces that aren't + possible to send now will be sent in the doing function repeatedly + until the entire request is sent. + */ + what = SOCKET_WRITABLE(sockfd, timeout_ms); + if(what < 0) { + result = CURLE_SEND_ERROR; + break; + } + else if(!what) { + result = CURLE_OPERATION_TIMEDOUT; + break; + } + } + + free(sel_org); + + if(!result) + result = Curl_xfer_send(data, "\r\n", 2, &amount); + if(result) { + failf(data, "Failed sending Gopher request"); + return result; + } + result = Curl_client_write(data, CLIENTWRITE_HEADER, (char *)"\r\n", 2); + if(result) + return result; + + Curl_xfer_setup(data, FIRSTSOCKET, -1, FALSE, -1); + return CURLE_OK; +} +#endif /* CURL_DISABLE_GOPHER */ diff --git a/third_party/curl/lib/gopher.h b/third_party/curl/lib/gopher.h new file mode 100644 index 0000000..9e3365b --- /dev/null +++ b/third_party/curl/lib/gopher.h @@ -0,0 +1,34 @@ +#ifndef HEADER_CURL_GOPHER_H +#define HEADER_CURL_GOPHER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifndef CURL_DISABLE_GOPHER +extern const struct Curl_handler Curl_handler_gopher; +#ifdef USE_SSL +extern const struct Curl_handler Curl_handler_gophers; +#endif +#endif + +#endif /* HEADER_CURL_GOPHER_H */ diff --git a/third_party/curl/lib/hash.c b/third_party/curl/lib/hash.c new file mode 100644 index 0000000..ddbae4d --- /dev/null +++ b/third_party/curl/lib/hash.c @@ -0,0 +1,373 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "hash.h" +#include "llist.h" +#include "curl_memory.h" + +/* The last #include file should be: */ +#include "memdebug.h" + +static void +hash_element_dtor(void *user, void *element) +{ + struct Curl_hash *h = (struct Curl_hash *) user; + struct Curl_hash_element *e = (struct Curl_hash_element *) element; + + if(e->ptr) { + h->dtor(e->ptr); + e->ptr = NULL; + } + + e->key_len = 0; + + free(e); +} + +/* Initializes a hash structure. + * Return 1 on error, 0 is fine. + * + * @unittest: 1602 + * @unittest: 1603 + */ +void +Curl_hash_init(struct Curl_hash *h, + size_t slots, + hash_function hfunc, + comp_function comparator, + Curl_hash_dtor dtor) +{ + DEBUGASSERT(h); + DEBUGASSERT(slots); + DEBUGASSERT(hfunc); + DEBUGASSERT(comparator); + DEBUGASSERT(dtor); + + h->table = NULL; + h->hash_func = hfunc; + h->comp_func = comparator; + h->dtor = dtor; + h->size = 0; + h->slots = slots; +} + +static struct Curl_hash_element * +mk_hash_element(const void *key, size_t key_len, const void *p) +{ + /* allocate the struct plus memory after it to store the key */ + struct Curl_hash_element *he = malloc(sizeof(struct Curl_hash_element) + + key_len); + if(he) { + /* copy the key */ + memcpy(he->key, key, key_len); + he->key_len = key_len; + he->ptr = (void *) p; + } + return he; +} + +#define FETCH_LIST(x,y,z) &x->table[x->hash_func(y, z, x->slots)] + +/* Insert the data in the hash. If there already was a match in the hash, that + * data is replaced. This function also "lazily" allocates the table if + * needed, as it isn't done in the _init function (anymore). + * + * @unittest: 1305 + * @unittest: 1602 + * @unittest: 1603 + */ +void * +Curl_hash_add(struct Curl_hash *h, void *key, size_t key_len, void *p) +{ + struct Curl_hash_element *he; + struct Curl_llist_element *le; + struct Curl_llist *l; + + DEBUGASSERT(h); + DEBUGASSERT(h->slots); + if(!h->table) { + size_t i; + h->table = malloc(h->slots * sizeof(struct Curl_llist)); + if(!h->table) + return NULL; /* OOM */ + for(i = 0; i < h->slots; ++i) + Curl_llist_init(&h->table[i], hash_element_dtor); + } + + l = FETCH_LIST(h, key, key_len); + + for(le = l->head; le; le = le->next) { + he = (struct Curl_hash_element *) le->ptr; + if(h->comp_func(he->key, he->key_len, key, key_len)) { + Curl_llist_remove(l, le, (void *)h); + --h->size; + break; + } + } + + he = mk_hash_element(key, key_len, p); + if(he) { + Curl_llist_append(l, he, &he->list); + ++h->size; + return p; /* return the new entry */ + } + + return NULL; /* failure */ +} + +/* Remove the identified hash entry. + * Returns non-zero on failure. + * + * @unittest: 1603 + */ +int Curl_hash_delete(struct Curl_hash *h, void *key, size_t key_len) +{ + struct Curl_llist_element *le; + struct Curl_llist *l; + + DEBUGASSERT(h); + DEBUGASSERT(h->slots); + if(h->table) { + l = FETCH_LIST(h, key, key_len); + + for(le = l->head; le; le = le->next) { + struct Curl_hash_element *he = le->ptr; + if(h->comp_func(he->key, he->key_len, key, key_len)) { + Curl_llist_remove(l, le, (void *) h); + --h->size; + return 0; + } + } + } + return 1; +} + +/* Retrieves a hash element. + * + * @unittest: 1603 + */ +void * +Curl_hash_pick(struct Curl_hash *h, void *key, size_t key_len) +{ + struct Curl_llist_element *le; + struct Curl_llist *l; + + DEBUGASSERT(h); + if(h->table) { + DEBUGASSERT(h->slots); + l = FETCH_LIST(h, key, key_len); + for(le = l->head; le; le = le->next) { + struct Curl_hash_element *he = le->ptr; + if(h->comp_func(he->key, he->key_len, key, key_len)) { + return he->ptr; + } + } + } + + return NULL; +} + +/* Destroys all the entries in the given hash and resets its attributes, + * prepping the given hash for [static|dynamic] deallocation. + * + * @unittest: 1305 + * @unittest: 1602 + * @unittest: 1603 + */ +void +Curl_hash_destroy(struct Curl_hash *h) +{ + if(h->table) { + size_t i; + for(i = 0; i < h->slots; ++i) { + Curl_llist_destroy(&h->table[i], (void *) h); + } + Curl_safefree(h->table); + } + h->size = 0; + h->slots = 0; +} + +/* Removes all the entries in the given hash. + * + * @unittest: 1602 + */ +void +Curl_hash_clean(struct Curl_hash *h) +{ + Curl_hash_clean_with_criterium(h, NULL, NULL); +} + +/* Cleans all entries that pass the comp function criteria. */ +void +Curl_hash_clean_with_criterium(struct Curl_hash *h, void *user, + int (*comp)(void *, void *)) +{ + struct Curl_llist_element *le; + struct Curl_llist_element *lnext; + struct Curl_llist *list; + size_t i; + + if(!h || !h->table) + return; + + for(i = 0; i < h->slots; ++i) { + list = &h->table[i]; + le = list->head; /* get first list entry */ + while(le) { + struct Curl_hash_element *he = le->ptr; + lnext = le->next; + /* ask the callback function if we shall remove this entry or not */ + if(!comp || comp(user, he->ptr)) { + Curl_llist_remove(list, le, (void *) h); + --h->size; /* one less entry in the hash now */ + } + le = lnext; + } + } +} + +size_t Curl_hash_str(void *key, size_t key_length, size_t slots_num) +{ + const char *key_str = (const char *) key; + const char *end = key_str + key_length; + size_t h = 5381; + + while(key_str < end) { + h += h << 5; + h ^= *key_str++; + } + + return (h % slots_num); +} + +size_t Curl_str_key_compare(void *k1, size_t key1_len, + void *k2, size_t key2_len) +{ + if((key1_len == key2_len) && !memcmp(k1, k2, key1_len)) + return 1; + + return 0; +} + +void Curl_hash_start_iterate(struct Curl_hash *hash, + struct Curl_hash_iterator *iter) +{ + iter->hash = hash; + iter->slot_index = 0; + iter->current_element = NULL; +} + +struct Curl_hash_element * +Curl_hash_next_element(struct Curl_hash_iterator *iter) +{ + struct Curl_hash *h = iter->hash; + + if(!h->table) + return NULL; /* empty hash, nothing to return */ + + /* Get the next element in the current list, if any */ + if(iter->current_element) + iter->current_element = iter->current_element->next; + + /* If we have reached the end of the list, find the next one */ + if(!iter->current_element) { + size_t i; + for(i = iter->slot_index; i < h->slots; i++) { + if(h->table[i].head) { + iter->current_element = h->table[i].head; + iter->slot_index = i + 1; + break; + } + } + } + + if(iter->current_element) { + struct Curl_hash_element *he = iter->current_element->ptr; + return he; + } + return NULL; +} + +#if 0 /* useful function for debugging hashes and their contents */ +void Curl_hash_print(struct Curl_hash *h, + void (*func)(void *)) +{ + struct Curl_hash_iterator iter; + struct Curl_hash_element *he; + size_t last_index = ~0; + + if(!h) + return; + + fprintf(stderr, "=Hash dump=\n"); + + Curl_hash_start_iterate(h, &iter); + + he = Curl_hash_next_element(&iter); + while(he) { + if(iter.slot_index != last_index) { + fprintf(stderr, "index %d:", iter.slot_index); + if(last_index != ~0) { + fprintf(stderr, "\n"); + } + last_index = iter.slot_index; + } + + if(func) + func(he->ptr); + else + fprintf(stderr, " [%p]", (void *)he->ptr); + + he = Curl_hash_next_element(&iter); + } + fprintf(stderr, "\n"); +} +#endif + +void Curl_hash_offt_init(struct Curl_hash *h, + size_t slots, + Curl_hash_dtor dtor) +{ + Curl_hash_init(h, slots, Curl_hash_str, Curl_str_key_compare, dtor); +} + +void *Curl_hash_offt_set(struct Curl_hash *h, curl_off_t id, void *elem) +{ + return Curl_hash_add(h, &id, sizeof(id), elem); +} + +int Curl_hash_offt_remove(struct Curl_hash *h, curl_off_t id) +{ + return Curl_hash_delete(h, &id, sizeof(id)); +} + +void *Curl_hash_offt_get(struct Curl_hash *h, curl_off_t id) +{ + return Curl_hash_pick(h, &id, sizeof(id)); +} diff --git a/third_party/curl/lib/hash.h b/third_party/curl/lib/hash.h new file mode 100644 index 0000000..2bdc247 --- /dev/null +++ b/third_party/curl/lib/hash.h @@ -0,0 +1,108 @@ +#ifndef HEADER_CURL_HASH_H +#define HEADER_CURL_HASH_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "llist.h" + +/* Hash function prototype */ +typedef size_t (*hash_function) (void *key, + size_t key_length, + size_t slots_num); + +/* + Comparator function prototype. Compares two keys. +*/ +typedef size_t (*comp_function) (void *key1, + size_t key1_len, + void *key2, + size_t key2_len); + +typedef void (*Curl_hash_dtor)(void *); + +struct Curl_hash { + struct Curl_llist *table; + + /* Hash function to be used for this hash table */ + hash_function hash_func; + + /* Comparator function to compare keys */ + comp_function comp_func; + Curl_hash_dtor dtor; + size_t slots; + size_t size; +}; + +struct Curl_hash_element { + struct Curl_llist_element list; + void *ptr; + size_t key_len; + char key[1]; /* allocated memory following the struct */ +}; + +struct Curl_hash_iterator { + struct Curl_hash *hash; + size_t slot_index; + struct Curl_llist_element *current_element; +}; + +void Curl_hash_init(struct Curl_hash *h, + size_t slots, + hash_function hfunc, + comp_function comparator, + Curl_hash_dtor dtor); + +void *Curl_hash_add(struct Curl_hash *h, void *key, size_t key_len, void *p); +int Curl_hash_delete(struct Curl_hash *h, void *key, size_t key_len); +void *Curl_hash_pick(struct Curl_hash *, void *key, size_t key_len); +#define Curl_hash_count(h) ((h)->size) +void Curl_hash_destroy(struct Curl_hash *h); +void Curl_hash_clean(struct Curl_hash *h); +void Curl_hash_clean_with_criterium(struct Curl_hash *h, void *user, + int (*comp)(void *, void *)); +size_t Curl_hash_str(void *key, size_t key_length, size_t slots_num); +size_t Curl_str_key_compare(void *k1, size_t key1_len, void *k2, + size_t key2_len); +void Curl_hash_start_iterate(struct Curl_hash *hash, + struct Curl_hash_iterator *iter); +struct Curl_hash_element * +Curl_hash_next_element(struct Curl_hash_iterator *iter); + +void Curl_hash_print(struct Curl_hash *h, + void (*func)(void *)); + +/* Hash for `curl_off_t` as key */ +void Curl_hash_offt_init(struct Curl_hash *h, size_t slots, + Curl_hash_dtor dtor); + +void *Curl_hash_offt_set(struct Curl_hash *h, curl_off_t id, void *elem); +int Curl_hash_offt_remove(struct Curl_hash *h, curl_off_t id); +void *Curl_hash_offt_get(struct Curl_hash *h, curl_off_t id); + + +#endif /* HEADER_CURL_HASH_H */ diff --git a/third_party/curl/lib/headers.c b/third_party/curl/lib/headers.c new file mode 100644 index 0000000..9a5692e --- /dev/null +++ b/third_party/curl/lib/headers.c @@ -0,0 +1,449 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "urldata.h" +#include "strdup.h" +#include "strcase.h" +#include "sendf.h" +#include "headers.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HEADERS_API) + +/* Generate the curl_header struct for the user. This function MUST assign all + struct fields in the output struct. */ +static void copy_header_external(struct Curl_header_store *hs, + size_t index, + size_t amount, + struct Curl_llist_element *e, + struct curl_header *hout) +{ + struct curl_header *h = hout; + h->name = hs->name; + h->value = hs->value; + h->amount = amount; + h->index = index; + /* this will randomly OR a reserved bit for the sole purpose of making it + impossible for applications to do == comparisons, as that would otherwise + be very tempting and then lead to the reserved bits not being reserved + anymore. */ + h->origin = hs->type | (1<<27); + h->anchor = e; +} + +/* public API */ +CURLHcode curl_easy_header(CURL *easy, + const char *name, + size_t nameindex, + unsigned int type, + int request, + struct curl_header **hout) +{ + struct Curl_llist_element *e; + struct Curl_llist_element *e_pick = NULL; + struct Curl_easy *data = easy; + size_t match = 0; + size_t amount = 0; + struct Curl_header_store *hs = NULL; + struct Curl_header_store *pick = NULL; + if(!name || !hout || !data || + (type > (CURLH_HEADER|CURLH_TRAILER|CURLH_CONNECT|CURLH_1XX| + CURLH_PSEUDO)) || !type || (request < -1)) + return CURLHE_BAD_ARGUMENT; + if(!Curl_llist_count(&data->state.httphdrs)) + return CURLHE_NOHEADERS; /* no headers available */ + if(request > data->state.requests) + return CURLHE_NOREQUEST; + if(request == -1) + request = data->state.requests; + + /* we need a first round to count amount of this header */ + for(e = data->state.httphdrs.head; e; e = e->next) { + hs = e->ptr; + if(strcasecompare(hs->name, name) && + (hs->type & type) && + (hs->request == request)) { + amount++; + pick = hs; + e_pick = e; + } + } + if(!amount) + return CURLHE_MISSING; + else if(nameindex >= amount) + return CURLHE_BADINDEX; + + if(nameindex == amount - 1) + /* if the last or only occurrence is what's asked for, then we know it */ + hs = pick; + else { + for(e = data->state.httphdrs.head; e; e = e->next) { + hs = e->ptr; + if(strcasecompare(hs->name, name) && + (hs->type & type) && + (hs->request == request) && + (match++ == nameindex)) { + e_pick = e; + break; + } + } + if(!e) /* this shouldn't happen */ + return CURLHE_MISSING; + } + /* this is the name we want */ + copy_header_external(hs, nameindex, amount, e_pick, + &data->state.headerout[0]); + *hout = &data->state.headerout[0]; + return CURLHE_OK; +} + +/* public API */ +struct curl_header *curl_easy_nextheader(CURL *easy, + unsigned int type, + int request, + struct curl_header *prev) +{ + struct Curl_easy *data = easy; + struct Curl_llist_element *pick; + struct Curl_llist_element *e; + struct Curl_header_store *hs; + size_t amount = 0; + size_t index = 0; + + if(request > data->state.requests) + return NULL; + if(request == -1) + request = data->state.requests; + + if(prev) { + pick = prev->anchor; + if(!pick) + /* something is wrong */ + return NULL; + pick = pick->next; + } + else + pick = data->state.httphdrs.head; + + if(pick) { + /* make sure it is the next header of the desired type */ + do { + hs = pick->ptr; + if((hs->type & type) && (hs->request == request)) + break; + pick = pick->next; + } while(pick); + } + + if(!pick) + /* no more headers available */ + return NULL; + + hs = pick->ptr; + + /* count number of occurrences of this name within the mask and figure out + the index for the currently selected entry */ + for(e = data->state.httphdrs.head; e; e = e->next) { + struct Curl_header_store *check = e->ptr; + if(strcasecompare(hs->name, check->name) && + (check->request == request) && + (check->type & type)) + amount++; + if(e == pick) + index = amount - 1; + } + + copy_header_external(hs, index, amount, pick, + &data->state.headerout[1]); + return &data->state.headerout[1]; +} + +static CURLcode namevalue(char *header, size_t hlen, unsigned int type, + char **name, char **value) +{ + char *end = header + hlen - 1; /* point to the last byte */ + DEBUGASSERT(hlen); + *name = header; + + if(type == CURLH_PSEUDO) { + if(*header != ':') + return CURLE_BAD_FUNCTION_ARGUMENT; + header++; + } + + /* Find the end of the header name */ + while(*header && (*header != ':')) + ++header; + + if(*header) + /* Skip over colon, null it */ + *header++ = 0; + else + return CURLE_BAD_FUNCTION_ARGUMENT; + + /* skip all leading space letters */ + while(*header && ISBLANK(*header)) + header++; + + *value = header; + + /* skip all trailing space letters */ + while((end > header) && ISSPACE(*end)) + *end-- = 0; /* nul terminate */ + return CURLE_OK; +} + +static CURLcode unfold_value(struct Curl_easy *data, const char *value, + size_t vlen) /* length of the incoming header */ +{ + struct Curl_header_store *hs; + struct Curl_header_store *newhs; + size_t olen; /* length of the old value */ + size_t oalloc; /* length of the old name + value + separator */ + size_t offset; + DEBUGASSERT(data->state.prevhead); + hs = data->state.prevhead; + olen = strlen(hs->value); + offset = hs->value - hs->buffer; + oalloc = olen + offset + 1; + + /* skip all trailing space letters */ + while(vlen && ISSPACE(value[vlen - 1])) + vlen--; + + /* save only one leading space */ + while((vlen > 1) && ISBLANK(value[0]) && ISBLANK(value[1])) { + vlen--; + value++; + } + + /* since this header block might move in the realloc below, it needs to + first be unlinked from the list and then re-added again after the + realloc */ + Curl_llist_remove(&data->state.httphdrs, &hs->node, NULL); + + /* new size = struct + new value length + old name+value length */ + newhs = Curl_saferealloc(hs, sizeof(*hs) + vlen + oalloc + 1); + if(!newhs) + return CURLE_OUT_OF_MEMORY; + /* ->name and ->value point into ->buffer (to keep the header allocation + in a single memory block), which now potentially have moved. Adjust + them. */ + newhs->name = newhs->buffer; + newhs->value = &newhs->buffer[offset]; + + /* put the data at the end of the previous data, not the newline */ + memcpy(&newhs->value[olen], value, vlen); + newhs->value[olen + vlen] = 0; /* null-terminate at newline */ + + /* insert this node into the list of headers */ + Curl_llist_append(&data->state.httphdrs, newhs, &newhs->node); + data->state.prevhead = newhs; + return CURLE_OK; +} + + +/* + * Curl_headers_push() gets passed a full HTTP header to store. It gets called + * immediately before the header callback. The header is CRLF terminated. + */ +CURLcode Curl_headers_push(struct Curl_easy *data, const char *header, + unsigned char type) +{ + char *value = NULL; + char *name = NULL; + char *end; + size_t hlen; /* length of the incoming header */ + struct Curl_header_store *hs; + CURLcode result = CURLE_OUT_OF_MEMORY; + + if((header[0] == '\r') || (header[0] == '\n')) + /* ignore the body separator */ + return CURLE_OK; + + end = strchr(header, '\r'); + if(!end) { + end = strchr(header, '\n'); + if(!end) + /* neither CR nor LF as terminator is not a valid header */ + return CURLE_WEIRD_SERVER_REPLY; + } + hlen = end - header; + + if((header[0] == ' ') || (header[0] == '\t')) { + if(data->state.prevhead) + /* line folding, append value to the previous header's value */ + return unfold_value(data, header, hlen); + else { + /* Can't unfold without a previous header. Instead of erroring, just + pass the leading blanks. */ + while(hlen && ISBLANK(*header)) { + header++; + hlen--; + } + if(!hlen) + return CURLE_WEIRD_SERVER_REPLY; + } + } + + hs = calloc(1, sizeof(*hs) + hlen); + if(!hs) + return CURLE_OUT_OF_MEMORY; + memcpy(hs->buffer, header, hlen); + hs->buffer[hlen] = 0; /* nul terminate */ + + result = namevalue(hs->buffer, hlen, type, &name, &value); + if(!result) { + hs->name = name; + hs->value = value; + hs->type = type; + hs->request = data->state.requests; + + /* insert this node into the list of headers */ + Curl_llist_append(&data->state.httphdrs, hs, &hs->node); + data->state.prevhead = hs; + } + else + free(hs); + return result; +} + +/* + * Curl_headers_reset(). Reset the headers subsystem. + */ +static void headers_reset(struct Curl_easy *data) +{ + Curl_llist_init(&data->state.httphdrs, NULL); + data->state.prevhead = NULL; +} + +struct hds_cw_collect_ctx { + struct Curl_cwriter super; +}; + +static CURLcode hds_cw_collect_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t blen) +{ + if((type & CLIENTWRITE_HEADER) && !(type & CLIENTWRITE_STATUS)) { + unsigned char htype = (unsigned char) + (type & CLIENTWRITE_CONNECT ? CURLH_CONNECT : + (type & CLIENTWRITE_1XX ? CURLH_1XX : + (type & CLIENTWRITE_TRAILER ? CURLH_TRAILER : + CURLH_HEADER))); + CURLcode result = Curl_headers_push(data, buf, htype); + CURL_TRC_WRITE(data, "header_collect pushed(type=%x, len=%zu) -> %d", + htype, blen, result); + if(result) + return result; + } + return Curl_cwriter_write(data, writer->next, type, buf, blen); +} + +static const struct Curl_cwtype hds_cw_collect = { + "hds-collect", + NULL, + Curl_cwriter_def_init, + hds_cw_collect_write, + Curl_cwriter_def_close, + sizeof(struct hds_cw_collect_ctx) +}; + +CURLcode Curl_headers_init(struct Curl_easy *data) +{ + struct Curl_cwriter *writer; + CURLcode result; + + if(data->conn && (data->conn->handler->protocol & PROTO_FAMILY_HTTP)) { + /* avoid installing it twice */ + if(Curl_cwriter_get_by_name(data, hds_cw_collect.name)) + return CURLE_OK; + + result = Curl_cwriter_create(&writer, data, &hds_cw_collect, + CURL_CW_PROTOCOL); + if(result) + return result; + + result = Curl_cwriter_add(data, writer); + if(result) { + Curl_cwriter_free(data, writer); + return result; + } + } + return CURLE_OK; +} + +/* + * Curl_headers_cleanup(). Free all stored headers and associated memory. + */ +CURLcode Curl_headers_cleanup(struct Curl_easy *data) +{ + struct Curl_llist_element *e; + struct Curl_llist_element *n; + + for(e = data->state.httphdrs.head; e; e = n) { + struct Curl_header_store *hs = e->ptr; + n = e->next; + free(hs); + } + headers_reset(data); + return CURLE_OK; +} + +#else /* HTTP-disabled builds below */ + +CURLHcode curl_easy_header(CURL *easy, + const char *name, + size_t index, + unsigned int origin, + int request, + struct curl_header **hout) +{ + (void)easy; + (void)name; + (void)index; + (void)origin; + (void)request; + (void)hout; + return CURLHE_NOT_BUILT_IN; +} + +struct curl_header *curl_easy_nextheader(CURL *easy, + unsigned int type, + int request, + struct curl_header *prev) +{ + (void)easy; + (void)type; + (void)request; + (void)prev; + return NULL; +} +#endif diff --git a/third_party/curl/lib/headers.h b/third_party/curl/lib/headers.h new file mode 100644 index 0000000..d981338 --- /dev/null +++ b/third_party/curl/lib/headers.h @@ -0,0 +1,62 @@ +#ifndef HEADER_CURL_HEADER_H +#define HEADER_CURL_HEADER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HEADERS_API) + +struct Curl_header_store { + struct Curl_llist_element node; + char *name; /* points into 'buffer' */ + char *value; /* points into 'buffer */ + int request; /* 0 is the first request, then 1.. 2.. */ + unsigned char type; /* CURLH_* defines */ + char buffer[1]; /* this is the raw header blob */ +}; + +/* + * Initialize header collecting for a transfer. + * Will add a client writer that catches CLIENTWRITE_HEADER writes. + */ +CURLcode Curl_headers_init(struct Curl_easy *data); + +/* + * Curl_headers_push() gets passed a full header to store. + */ +CURLcode Curl_headers_push(struct Curl_easy *data, const char *header, + unsigned char type); + +/* + * Curl_headers_cleanup(). Free all stored headers and associated memory. + */ +CURLcode Curl_headers_cleanup(struct Curl_easy *data); + +#else +#define Curl_headers_init(x) CURLE_OK +#define Curl_headers_push(x,y,z) CURLE_OK +#define Curl_headers_cleanup(x) Curl_nop_stmt +#endif + +#endif /* HEADER_CURL_HEADER_H */ diff --git a/third_party/curl/lib/hmac.c b/third_party/curl/lib/hmac.c new file mode 100644 index 0000000..4019b67 --- /dev/null +++ b/third_party/curl/lib/hmac.c @@ -0,0 +1,173 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * RFC2104 Keyed-Hashing for Message Authentication + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if (defined(USE_CURL_NTLM_CORE) && !defined(USE_WINDOWS_SSPI)) \ + || !defined(CURL_DISABLE_AWS) || !defined(CURL_DISABLE_DIGEST_AUTH) + +#include + +#include "curl_hmac.h" +#include "curl_memory.h" +#include "warnless.h" + +/* The last #include file should be: */ +#include "memdebug.h" + +/* + * Generic HMAC algorithm. + * + * This module computes HMAC digests based on any hash function. Parameters + * and computing procedures are set-up dynamically at HMAC computation context + * initialization. + */ + +static const unsigned char hmac_ipad = 0x36; +static const unsigned char hmac_opad = 0x5C; + + + +struct HMAC_context * +Curl_HMAC_init(const struct HMAC_params *hashparams, + const unsigned char *key, + unsigned int keylen) +{ + size_t i; + struct HMAC_context *ctxt; + unsigned char *hkey; + unsigned char b; + + /* Create HMAC context. */ + i = sizeof(*ctxt) + 2 * hashparams->hmac_ctxtsize + + hashparams->hmac_resultlen; + ctxt = malloc(i); + + if(!ctxt) + return ctxt; + + ctxt->hmac_hash = hashparams; + ctxt->hmac_hashctxt1 = (void *) (ctxt + 1); + ctxt->hmac_hashctxt2 = (void *) ((char *) ctxt->hmac_hashctxt1 + + hashparams->hmac_ctxtsize); + + /* If the key is too long, replace it by its hash digest. */ + if(keylen > hashparams->hmac_maxkeylen) { + (*hashparams->hmac_hinit)(ctxt->hmac_hashctxt1); + (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt1, key, keylen); + hkey = (unsigned char *) ctxt->hmac_hashctxt2 + hashparams->hmac_ctxtsize; + (*hashparams->hmac_hfinal)(hkey, ctxt->hmac_hashctxt1); + key = hkey; + keylen = hashparams->hmac_resultlen; + } + + /* Prime the two hash contexts with the modified key. */ + (*hashparams->hmac_hinit)(ctxt->hmac_hashctxt1); + (*hashparams->hmac_hinit)(ctxt->hmac_hashctxt2); + + for(i = 0; i < keylen; i++) { + b = (unsigned char)(*key ^ hmac_ipad); + (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt1, &b, 1); + b = (unsigned char)(*key++ ^ hmac_opad); + (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt2, &b, 1); + } + + for(; i < hashparams->hmac_maxkeylen; i++) { + (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt1, &hmac_ipad, 1); + (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt2, &hmac_opad, 1); + } + + /* Done, return pointer to HMAC context. */ + return ctxt; +} + +int Curl_HMAC_update(struct HMAC_context *ctxt, + const unsigned char *data, + unsigned int len) +{ + /* Update first hash calculation. */ + (*ctxt->hmac_hash->hmac_hupdate)(ctxt->hmac_hashctxt1, data, len); + return 0; +} + + +int Curl_HMAC_final(struct HMAC_context *ctxt, unsigned char *result) +{ + const struct HMAC_params *hashparams = ctxt->hmac_hash; + + /* Do not get result if called with a null parameter: only release + storage. */ + + if(!result) + result = (unsigned char *) ctxt->hmac_hashctxt2 + + ctxt->hmac_hash->hmac_ctxtsize; + + (*hashparams->hmac_hfinal)(result, ctxt->hmac_hashctxt1); + (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt2, + result, hashparams->hmac_resultlen); + (*hashparams->hmac_hfinal)(result, ctxt->hmac_hashctxt2); + free((char *) ctxt); + return 0; +} + +/* + * Curl_hmacit() + * + * This is used to generate a HMAC hash, for the specified input data, given + * the specified hash function and key. + * + * Parameters: + * + * hashparams [in] - The hash function (Curl_HMAC_MD5). + * key [in] - The key to use. + * keylen [in] - The length of the key. + * data [in] - The data to encrypt. + * datalen [in] - The length of the data. + * output [in/out] - The output buffer. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_hmacit(const struct HMAC_params *hashparams, + const unsigned char *key, const size_t keylen, + const unsigned char *data, const size_t datalen, + unsigned char *output) +{ + struct HMAC_context *ctxt = + Curl_HMAC_init(hashparams, key, curlx_uztoui(keylen)); + + if(!ctxt) + return CURLE_OUT_OF_MEMORY; + + /* Update the digest with the given challenge */ + Curl_HMAC_update(ctxt, data, curlx_uztoui(datalen)); + + /* Finalise the digest */ + Curl_HMAC_final(ctxt, output); + + return CURLE_OK; +} + +#endif /* Using NTLM (without SSPI) or AWS */ diff --git a/third_party/curl/lib/hostasyn.c b/third_party/curl/lib/hostasyn.c new file mode 100644 index 0000000..2f6762c --- /dev/null +++ b/third_party/curl/lib/hostasyn.c @@ -0,0 +1,123 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +/*********************************************************************** + * Only for builds using asynchronous name resolves + **********************************************************************/ +#ifdef CURLRES_ASYNCH + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef __VMS +#include +#include +#endif + +#include "urldata.h" +#include "sendf.h" +#include "hostip.h" +#include "hash.h" +#include "share.h" +#include "url.h" +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + +/* + * Curl_addrinfo_callback() gets called by ares, gethostbyname_thread() + * or getaddrinfo_thread() when we got the name resolved (or not!). + * + * If the status argument is CURL_ASYNC_SUCCESS, this function takes + * ownership of the Curl_addrinfo passed, storing the resolved data + * in the DNS cache. + * + * The storage operation locks and unlocks the DNS cache. + */ +CURLcode Curl_addrinfo_callback(struct Curl_easy *data, + int status, + struct Curl_addrinfo *ai) +{ + struct Curl_dns_entry *dns = NULL; + CURLcode result = CURLE_OK; + + data->state.async.status = status; + + if(CURL_ASYNC_SUCCESS == status) { + if(ai) { + if(data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + dns = Curl_cache_addr(data, ai, + data->state.async.hostname, 0, + data->state.async.port); + if(data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); + + if(!dns) { + /* failed to store, cleanup and return error */ + Curl_freeaddrinfo(ai); + result = CURLE_OUT_OF_MEMORY; + } + } + else { + result = CURLE_OUT_OF_MEMORY; + } + } + + data->state.async.dns = dns; + + /* Set async.done TRUE last in this function since it may be used multi- + threaded and once this is TRUE the other thread may read fields from the + async struct */ + data->state.async.done = TRUE; + + /* IPv4: The input hostent struct will be freed by ares when we return from + this function */ + return result; +} + +/* + * Curl_getaddrinfo() is the generic low-level name resolve API within this + * source file. There are several versions of this function - for different + * name resolve layers (selected at build-time). They all take this same set + * of arguments + */ +struct Curl_addrinfo *Curl_getaddrinfo(struct Curl_easy *data, + const char *hostname, + int port, + int *waitp) +{ + return Curl_resolver_getaddrinfo(data, hostname, port, waitp); +} + +#endif /* CURLRES_ASYNCH */ diff --git a/third_party/curl/lib/hostip.c b/third_party/curl/lib/hostip.c new file mode 100644 index 0000000..93c36e0 --- /dev/null +++ b/third_party/curl/lib/hostip.c @@ -0,0 +1,1481 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef __VMS +#include +#include +#endif + +#include +#include + +#include "urldata.h" +#include "sendf.h" +#include "hostip.h" +#include "hash.h" +#include "rand.h" +#include "share.h" +#include "url.h" +#include "inet_ntop.h" +#include "inet_pton.h" +#include "multiif.h" +#include "doh.h" +#include "warnless.h" +#include "strcase.h" +#include "easy_lock.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if defined(CURLRES_SYNCH) && \ + defined(HAVE_ALARM) && \ + defined(SIGALRM) && \ + defined(HAVE_SIGSETJMP) && \ + defined(GLOBAL_INIT_IS_THREADSAFE) +/* alarm-based timeouts can only be used with all the dependencies satisfied */ +#define USE_ALARM_TIMEOUT +#endif + +#define MAX_HOSTCACHE_LEN (255 + 7) /* max FQDN + colon + port number + zero */ + +#define MAX_DNS_CACHE_SIZE 29999 + +/* + * hostip.c explained + * ================== + * + * The main COMPILE-TIME DEFINES to keep in mind when reading the host*.c + * source file are these: + * + * CURLRES_IPV6 - this host has getaddrinfo() and family, and thus we use + * that. The host may not be able to resolve IPv6, but we don't really have to + * take that into account. Hosts that aren't IPv6-enabled have CURLRES_IPV4 + * defined. + * + * CURLRES_ARES - is defined if libcurl is built to use c-ares for + * asynchronous name resolves. This can be Windows or *nix. + * + * CURLRES_THREADED - is defined if libcurl is built to run under (native) + * Windows, and then the name resolve will be done in a new thread, and the + * supported API will be the same as for ares-builds. + * + * If any of the two previous are defined, CURLRES_ASYNCH is defined too. If + * libcurl is not built to use an asynchronous resolver, CURLRES_SYNCH is + * defined. + * + * The host*.c sources files are split up like this: + * + * hostip.c - method-independent resolver functions and utility functions + * hostasyn.c - functions for asynchronous name resolves + * hostsyn.c - functions for synchronous name resolves + * hostip4.c - IPv4 specific functions + * hostip6.c - IPv6 specific functions + * + * The two asynchronous name resolver backends are implemented in: + * asyn-ares.c - functions for ares-using name resolves + * asyn-thread.c - functions for threaded name resolves + + * The hostip.h is the united header file for all this. It defines the + * CURLRES_* defines based on the config*.h and curl_setup.h defines. + */ + +static void freednsentry(void *freethis); + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +static void show_resolve_info(struct Curl_easy *data, + struct Curl_dns_entry *dns); +#else +#define show_resolve_info(x,y) Curl_nop_stmt +#endif + +/* + * Curl_printable_address() stores a printable version of the 1st address + * given in the 'ai' argument. The result will be stored in the buf that is + * bufsize bytes big. + * + * If the conversion fails, the target buffer is empty. + */ +void Curl_printable_address(const struct Curl_addrinfo *ai, char *buf, + size_t bufsize) +{ + DEBUGASSERT(bufsize); + buf[0] = 0; + + switch(ai->ai_family) { + case AF_INET: { + const struct sockaddr_in *sa4 = (const void *)ai->ai_addr; + const struct in_addr *ipaddr4 = &sa4->sin_addr; + (void)Curl_inet_ntop(ai->ai_family, (const void *)ipaddr4, buf, bufsize); + break; + } +#ifdef USE_IPV6 + case AF_INET6: { + const struct sockaddr_in6 *sa6 = (const void *)ai->ai_addr; + const struct in6_addr *ipaddr6 = &sa6->sin6_addr; + (void)Curl_inet_ntop(ai->ai_family, (const void *)ipaddr6, buf, bufsize); + break; + } +#endif + default: + break; + } +} + +/* + * Create a hostcache id string for the provided host + port, to be used by + * the DNS caching. Without alloc. Return length of the id string. + */ +static size_t +create_hostcache_id(const char *name, + size_t nlen, /* 0 or actual name length */ + int port, char *ptr, size_t buflen) +{ + size_t len = nlen ? nlen : strlen(name); + DEBUGASSERT(buflen >= MAX_HOSTCACHE_LEN); + if(len > (buflen - 7)) + len = buflen - 7; + /* store and lower case the name */ + Curl_strntolower(ptr, name, len); + return msnprintf(&ptr[len], 7, ":%u", port) + len; +} + +struct hostcache_prune_data { + time_t now; + time_t oldest; /* oldest time in cache not pruned. */ + int cache_timeout; +}; + +/* + * This function is set as a callback to be called for every entry in the DNS + * cache when we want to prune old unused entries. + * + * Returning non-zero means remove the entry, return 0 to keep it in the + * cache. + */ +static int +hostcache_timestamp_remove(void *datap, void *hc) +{ + struct hostcache_prune_data *prune = + (struct hostcache_prune_data *) datap; + struct Curl_dns_entry *c = (struct Curl_dns_entry *) hc; + + if(c->timestamp) { + /* age in seconds */ + time_t age = prune->now - c->timestamp; + if(age >= prune->cache_timeout) + return TRUE; + if(age > prune->oldest) + prune->oldest = age; + } + return FALSE; +} + +/* + * Prune the DNS cache. This assumes that a lock has already been taken. + * Returns the 'age' of the oldest still kept entry. + */ +static time_t +hostcache_prune(struct Curl_hash *hostcache, int cache_timeout, + time_t now) +{ + struct hostcache_prune_data user; + + user.cache_timeout = cache_timeout; + user.now = now; + user.oldest = 0; + + Curl_hash_clean_with_criterium(hostcache, + (void *) &user, + hostcache_timestamp_remove); + + return user.oldest; +} + +/* + * Library-wide function for pruning the DNS cache. This function takes and + * returns the appropriate locks. + */ +void Curl_hostcache_prune(struct Curl_easy *data) +{ + time_t now; + /* the timeout may be set -1 (forever) */ + int timeout = data->set.dns_cache_timeout; + + if(!data->dns.hostcache) + /* NULL hostcache means we can't do it */ + return; + + if(data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + now = time(NULL); + + do { + /* Remove outdated and unused entries from the hostcache */ + time_t oldest = hostcache_prune(data->dns.hostcache, timeout, now); + + if(oldest < INT_MAX) + timeout = (int)oldest; /* we know it fits */ + else + timeout = INT_MAX - 1; + + /* if the cache size is still too big, use the oldest age as new + prune limit */ + } while(timeout && (data->dns.hostcache->size > MAX_DNS_CACHE_SIZE)); + + if(data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); +} + +#ifdef USE_ALARM_TIMEOUT +/* Beware this is a global and unique instance. This is used to store the + return address that we can jump back to from inside a signal handler. This + is not thread-safe stuff. */ +static sigjmp_buf curl_jmpenv; +static curl_simple_lock curl_jmpenv_lock; +#endif + +/* lookup address, returns entry if found and not stale */ +static struct Curl_dns_entry *fetch_addr(struct Curl_easy *data, + const char *hostname, + int port) +{ + struct Curl_dns_entry *dns = NULL; + char entry_id[MAX_HOSTCACHE_LEN]; + + /* Create an entry id, based upon the hostname and port */ + size_t entry_len = create_hostcache_id(hostname, 0, port, + entry_id, sizeof(entry_id)); + + /* See if it's already in our dns cache */ + dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1); + + /* No entry found in cache, check if we might have a wildcard entry */ + if(!dns && data->state.wildcard_resolve) { + entry_len = create_hostcache_id("*", 1, port, entry_id, sizeof(entry_id)); + + /* See if it's already in our dns cache */ + dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1); + } + + if(dns && (data->set.dns_cache_timeout != -1)) { + /* See whether the returned entry is stale. Done before we release lock */ + struct hostcache_prune_data user; + + user.now = time(NULL); + user.cache_timeout = data->set.dns_cache_timeout; + user.oldest = 0; + + if(hostcache_timestamp_remove(&user, dns)) { + infof(data, "Hostname in DNS cache was stale, zapped"); + dns = NULL; /* the memory deallocation is being handled by the hash */ + Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1); + } + } + + /* See if the returned entry matches the required resolve mode */ + if(dns && data->conn->ip_version != CURL_IPRESOLVE_WHATEVER) { + int pf = PF_INET; + bool found = false; + struct Curl_addrinfo *addr = dns->addr; + +#ifdef PF_INET6 + if(data->conn->ip_version == CURL_IPRESOLVE_V6) + pf = PF_INET6; +#endif + + while(addr) { + if(addr->ai_family == pf) { + found = true; + break; + } + addr = addr->ai_next; + } + + if(!found) { + infof(data, "Hostname in DNS cache doesn't have needed family, zapped"); + dns = NULL; /* the memory deallocation is being handled by the hash */ + Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1); + } + } + return dns; +} + +/* + * Curl_fetch_addr() fetches a 'Curl_dns_entry' already in the DNS cache. + * + * Curl_resolv() checks initially and multi_runsingle() checks each time + * it discovers the handle in the state WAITRESOLVE whether the hostname + * has already been resolved and the address has already been stored in + * the DNS cache. This short circuits waiting for a lot of pending + * lookups for the same hostname requested by different handles. + * + * Returns the Curl_dns_entry entry pointer or NULL if not in the cache. + * + * The returned data *MUST* be "unlocked" with Curl_resolv_unlock() after + * use, or we'll leak memory! + */ +struct Curl_dns_entry * +Curl_fetch_addr(struct Curl_easy *data, + const char *hostname, + int port) +{ + struct Curl_dns_entry *dns = NULL; + + if(data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + dns = fetch_addr(data, hostname, port); + + if(dns) + dns->inuse++; /* we use it! */ + + if(data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); + + return dns; +} + +#ifndef CURL_DISABLE_SHUFFLE_DNS +/* + * Return # of addresses in a Curl_addrinfo struct + */ +static int num_addresses(const struct Curl_addrinfo *addr) +{ + int i = 0; + while(addr) { + addr = addr->ai_next; + i++; + } + return i; +} + +UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data, + struct Curl_addrinfo **addr); +/* + * Curl_shuffle_addr() shuffles the order of addresses in a 'Curl_addrinfo' + * struct by re-linking its linked list. + * + * The addr argument should be the address of a pointer to the head node of a + * `Curl_addrinfo` list and it will be modified to point to the new head after + * shuffling. + * + * Not declared static only to make it easy to use in a unit test! + * + * @unittest: 1608 + */ +UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data, + struct Curl_addrinfo **addr) +{ + CURLcode result = CURLE_OK; + const int num_addrs = num_addresses(*addr); + + if(num_addrs > 1) { + struct Curl_addrinfo **nodes; + infof(data, "Shuffling %i addresses", num_addrs); + + nodes = malloc(num_addrs*sizeof(*nodes)); + if(nodes) { + int i; + unsigned int *rnd; + const size_t rnd_size = num_addrs * sizeof(*rnd); + + /* build a plain array of Curl_addrinfo pointers */ + nodes[0] = *addr; + for(i = 1; i < num_addrs; i++) { + nodes[i] = nodes[i-1]->ai_next; + } + + rnd = malloc(rnd_size); + if(rnd) { + /* Fisher-Yates shuffle */ + if(Curl_rand(data, (unsigned char *)rnd, rnd_size) == CURLE_OK) { + struct Curl_addrinfo *swap_tmp; + for(i = num_addrs - 1; i > 0; i--) { + swap_tmp = nodes[rnd[i] % (i + 1)]; + nodes[rnd[i] % (i + 1)] = nodes[i]; + nodes[i] = swap_tmp; + } + + /* relink list in the new order */ + for(i = 1; i < num_addrs; i++) { + nodes[i-1]->ai_next = nodes[i]; + } + + nodes[num_addrs-1]->ai_next = NULL; + *addr = nodes[0]; + } + free(rnd); + } + else + result = CURLE_OUT_OF_MEMORY; + free(nodes); + } + else + result = CURLE_OUT_OF_MEMORY; + } + return result; +} +#endif + +/* + * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache. + * + * When calling Curl_resolv() has resulted in a response with a returned + * address, we call this function to store the information in the dns + * cache etc + * + * Returns the Curl_dns_entry entry pointer or NULL if the storage failed. + */ +struct Curl_dns_entry * +Curl_cache_addr(struct Curl_easy *data, + struct Curl_addrinfo *addr, + const char *hostname, + size_t hostlen, /* length or zero */ + int port) +{ + char entry_id[MAX_HOSTCACHE_LEN]; + size_t entry_len; + struct Curl_dns_entry *dns; + struct Curl_dns_entry *dns2; + +#ifndef CURL_DISABLE_SHUFFLE_DNS + /* shuffle addresses if requested */ + if(data->set.dns_shuffle_addresses) { + CURLcode result = Curl_shuffle_addr(data, &addr); + if(result) + return NULL; + } +#endif + if(!hostlen) + hostlen = strlen(hostname); + + /* Create a new cache entry */ + dns = calloc(1, sizeof(struct Curl_dns_entry) + hostlen); + if(!dns) { + return NULL; + } + + /* Create an entry id, based upon the hostname and port */ + entry_len = create_hostcache_id(hostname, hostlen, port, + entry_id, sizeof(entry_id)); + + dns->inuse = 1; /* the cache has the first reference */ + dns->addr = addr; /* this is the address(es) */ + time(&dns->timestamp); + if(dns->timestamp == 0) + dns->timestamp = 1; /* zero indicates permanent CURLOPT_RESOLVE entry */ + dns->hostport = port; + if(hostlen) + memcpy(dns->hostname, hostname, hostlen); + + /* Store the resolved data in our DNS cache. */ + dns2 = Curl_hash_add(data->dns.hostcache, entry_id, entry_len + 1, + (void *)dns); + if(!dns2) { + free(dns); + return NULL; + } + + dns = dns2; + dns->inuse++; /* mark entry as in-use */ + return dns; +} + +#ifdef USE_IPV6 +/* return a static IPv6 ::1 for the name */ +static struct Curl_addrinfo *get_localhost6(int port, const char *name) +{ + struct Curl_addrinfo *ca; + const size_t ss_size = sizeof(struct sockaddr_in6); + const size_t hostlen = strlen(name); + struct sockaddr_in6 sa6; + unsigned char ipv6[16]; + unsigned short port16 = (unsigned short)(port & 0xffff); + ca = calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen + 1); + if(!ca) + return NULL; + + sa6.sin6_family = AF_INET6; + sa6.sin6_port = htons(port16); + sa6.sin6_flowinfo = 0; + sa6.sin6_scope_id = 0; + if(Curl_inet_pton(AF_INET6, "::1", ipv6) < 1) + return NULL; + memcpy(&sa6.sin6_addr, ipv6, sizeof(ipv6)); + + ca->ai_flags = 0; + ca->ai_family = AF_INET6; + ca->ai_socktype = SOCK_STREAM; + ca->ai_protocol = IPPROTO_TCP; + ca->ai_addrlen = (curl_socklen_t)ss_size; + ca->ai_next = NULL; + ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo)); + memcpy(ca->ai_addr, &sa6, ss_size); + ca->ai_canonname = (char *)ca->ai_addr + ss_size; + strcpy(ca->ai_canonname, name); + return ca; +} +#else +#define get_localhost6(x,y) NULL +#endif + +/* return a static IPv4 127.0.0.1 for the given name */ +static struct Curl_addrinfo *get_localhost(int port, const char *name) +{ + struct Curl_addrinfo *ca; + struct Curl_addrinfo *ca6; + const size_t ss_size = sizeof(struct sockaddr_in); + const size_t hostlen = strlen(name); + struct sockaddr_in sa; + unsigned int ipv4; + unsigned short port16 = (unsigned short)(port & 0xffff); + + /* memset to clear the sa.sin_zero field */ + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_port = htons(port16); + if(Curl_inet_pton(AF_INET, "127.0.0.1", (char *)&ipv4) < 1) + return NULL; + memcpy(&sa.sin_addr, &ipv4, sizeof(ipv4)); + + ca = calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen + 1); + if(!ca) + return NULL; + ca->ai_flags = 0; + ca->ai_family = AF_INET; + ca->ai_socktype = SOCK_STREAM; + ca->ai_protocol = IPPROTO_TCP; + ca->ai_addrlen = (curl_socklen_t)ss_size; + ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo)); + memcpy(ca->ai_addr, &sa, ss_size); + ca->ai_canonname = (char *)ca->ai_addr + ss_size; + strcpy(ca->ai_canonname, name); + + ca6 = get_localhost6(port, name); + if(!ca6) + return ca; + ca6->ai_next = ca; + return ca6; +} + +#ifdef USE_IPV6 +/* + * Curl_ipv6works() returns TRUE if IPv6 seems to work. + */ +bool Curl_ipv6works(struct Curl_easy *data) +{ + if(data) { + /* the nature of most system is that IPv6 status doesn't come and go + during a program's lifetime so we only probe the first time and then we + have the info kept for fast reuse */ + DEBUGASSERT(data); + DEBUGASSERT(data->multi); + if(data->multi->ipv6_up == IPV6_UNKNOWN) { + bool works = Curl_ipv6works(NULL); + data->multi->ipv6_up = works ? IPV6_WORKS : IPV6_DEAD; + } + return data->multi->ipv6_up == IPV6_WORKS; + } + else { + int ipv6_works = -1; + /* probe to see if we have a working IPv6 stack */ + curl_socket_t s = socket(PF_INET6, SOCK_DGRAM, 0); + if(s == CURL_SOCKET_BAD) + /* an IPv6 address was requested but we can't get/use one */ + ipv6_works = 0; + else { + ipv6_works = 1; + sclose(s); + } + return (ipv6_works>0)?TRUE:FALSE; + } +} +#endif /* USE_IPV6 */ + +/* + * Curl_host_is_ipnum() returns TRUE if the given string is a numerical IPv4 + * (or IPv6 if supported) address. + */ +bool Curl_host_is_ipnum(const char *hostname) +{ + struct in_addr in; +#ifdef USE_IPV6 + struct in6_addr in6; +#endif + if(Curl_inet_pton(AF_INET, hostname, &in) > 0 +#ifdef USE_IPV6 + || Curl_inet_pton(AF_INET6, hostname, &in6) > 0 +#endif + ) + return TRUE; + return FALSE; +} + + +/* return TRUE if 'part' is a case insensitive tail of 'full' */ +static bool tailmatch(const char *full, const char *part) +{ + size_t plen = strlen(part); + size_t flen = strlen(full); + if(plen > flen) + return FALSE; + return strncasecompare(part, &full[flen - plen], plen); +} + +/* + * Curl_resolv() is the main name resolve function within libcurl. It resolves + * a name and returns a pointer to the entry in the 'entry' argument (if one + * is provided). This function might return immediately if we're using asynch + * resolves. See the return codes. + * + * The cache entry we return will get its 'inuse' counter increased when this + * function is used. You MUST call Curl_resolv_unlock() later (when you're + * done using this struct) to decrease the counter again. + * + * Return codes: + * + * CURLRESOLV_ERROR (-1) = error, no pointer + * CURLRESOLV_RESOLVED (0) = OK, pointer provided + * CURLRESOLV_PENDING (1) = waiting for response, no pointer + */ + +enum resolve_t Curl_resolv(struct Curl_easy *data, + const char *hostname, + int port, + bool allowDOH, + struct Curl_dns_entry **entry) +{ + struct Curl_dns_entry *dns = NULL; + CURLcode result; + enum resolve_t rc = CURLRESOLV_ERROR; /* default to failure */ + struct connectdata *conn = data->conn; + /* We should intentionally error and not resolve .onion TLDs */ + size_t hostname_len = strlen(hostname); + if(hostname_len >= 7 && + (curl_strequal(&hostname[hostname_len - 6], ".onion") || + curl_strequal(&hostname[hostname_len - 7], ".onion."))) { + failf(data, "Not resolving .onion address (RFC 7686)"); + return CURLRESOLV_ERROR; + } + *entry = NULL; +#ifndef CURL_DISABLE_DOH + conn->bits.doh = FALSE; /* default is not */ +#else + (void)allowDOH; +#endif + + if(data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + dns = fetch_addr(data, hostname, port); + + if(dns) { + infof(data, "Hostname %s was found in DNS cache", hostname); + dns->inuse++; /* we use it! */ + rc = CURLRESOLV_RESOLVED; + } + + if(data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); + + if(!dns) { + /* The entry was not in the cache. Resolve it to IP address */ + + struct Curl_addrinfo *addr = NULL; + int respwait = 0; +#if !defined(CURL_DISABLE_DOH) || !defined(USE_RESOLVE_ON_IPS) + struct in_addr in; +#endif +#ifndef CURL_DISABLE_DOH +#ifndef USE_RESOLVE_ON_IPS + const +#endif + bool ipnum = FALSE; +#endif + + /* notify the resolver start callback */ + if(data->set.resolver_start) { + int st; + Curl_set_in_callback(data, true); + st = data->set.resolver_start( +#ifdef USE_CURL_ASYNC + data->state.async.resolver, +#else + NULL, +#endif + NULL, + data->set.resolver_start_client); + Curl_set_in_callback(data, false); + if(st) + return CURLRESOLV_ERROR; + } + +#ifndef USE_RESOLVE_ON_IPS + /* First check if this is an IPv4 address string */ + if(Curl_inet_pton(AF_INET, hostname, &in) > 0) { + /* This is a dotted IP address 123.123.123.123-style */ + addr = Curl_ip2addr(AF_INET, &in, hostname, port); + if(!addr) + return CURLRESOLV_ERROR; + } +#ifdef USE_IPV6 + else { + struct in6_addr in6; + /* check if this is an IPv6 address string */ + if(Curl_inet_pton(AF_INET6, hostname, &in6) > 0) { + /* This is an IPv6 address literal */ + addr = Curl_ip2addr(AF_INET6, &in6, hostname, port); + if(!addr) + return CURLRESOLV_ERROR; + } + } +#endif /* USE_IPV6 */ + +#else /* if USE_RESOLVE_ON_IPS */ +#ifndef CURL_DISABLE_DOH + /* First check if this is an IPv4 address string */ + if(Curl_inet_pton(AF_INET, hostname, &in) > 0) + /* This is a dotted IP address 123.123.123.123-style */ + ipnum = TRUE; +#ifdef USE_IPV6 + else { + struct in6_addr in6; + /* check if this is an IPv6 address string */ + if(Curl_inet_pton(AF_INET6, hostname, &in6) > 0) + /* This is an IPv6 address literal */ + ipnum = TRUE; + } +#endif /* USE_IPV6 */ +#endif /* CURL_DISABLE_DOH */ + +#endif /* !USE_RESOLVE_ON_IPS */ + + if(!addr) { + if(conn->ip_version == CURL_IPRESOLVE_V6 && !Curl_ipv6works(data)) + return CURLRESOLV_ERROR; + + if(strcasecompare(hostname, "localhost") || + tailmatch(hostname, ".localhost")) + addr = get_localhost(port, hostname); +#ifndef CURL_DISABLE_DOH + else if(allowDOH && data->set.doh && !ipnum) + addr = Curl_doh(data, hostname, port, &respwait); +#endif + else { + /* Check what IP specifics the app has requested and if we can provide + * it. If not, bail out. */ + if(!Curl_ipvalid(data, conn)) + return CURLRESOLV_ERROR; + /* If Curl_getaddrinfo() returns NULL, 'respwait' might be set to a + non-zero value indicating that we need to wait for the response to + the resolve call */ + addr = Curl_getaddrinfo(data, hostname, port, &respwait); + } + } + if(!addr) { + if(respwait) { + /* the response to our resolve call will come asynchronously at + a later time, good or bad */ + /* First, check that we haven't received the info by now */ + result = Curl_resolv_check(data, &dns); + if(result) /* error detected */ + return CURLRESOLV_ERROR; + if(dns) + rc = CURLRESOLV_RESOLVED; /* pointer provided */ + else + rc = CURLRESOLV_PENDING; /* no info yet */ + } + } + else { + if(data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + /* we got a response, store it in the cache */ + dns = Curl_cache_addr(data, addr, hostname, 0, port); + + if(data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); + + if(!dns) + /* returned failure, bail out nicely */ + Curl_freeaddrinfo(addr); + else { + rc = CURLRESOLV_RESOLVED; + show_resolve_info(data, dns); + } + } + } + + *entry = dns; + + return rc; +} + +#ifdef USE_ALARM_TIMEOUT +/* + * This signal handler jumps back into the main libcurl code and continues + * execution. This effectively causes the remainder of the application to run + * within a signal handler which is nonportable and could lead to problems. + */ +CURL_NORETURN static +void alarmfunc(int sig) +{ + (void)sig; + siglongjmp(curl_jmpenv, 1); +} +#endif /* USE_ALARM_TIMEOUT */ + +/* + * Curl_resolv_timeout() is the same as Curl_resolv() but specifies a + * timeout. This function might return immediately if we're using asynch + * resolves. See the return codes. + * + * The cache entry we return will get its 'inuse' counter increased when this + * function is used. You MUST call Curl_resolv_unlock() later (when you're + * done using this struct) to decrease the counter again. + * + * If built with a synchronous resolver and use of signals is not + * disabled by the application, then a nonzero timeout will cause a + * timeout after the specified number of milliseconds. Otherwise, timeout + * is ignored. + * + * Return codes: + * + * CURLRESOLV_TIMEDOUT(-2) = warning, time too short or previous alarm expired + * CURLRESOLV_ERROR (-1) = error, no pointer + * CURLRESOLV_RESOLVED (0) = OK, pointer provided + * CURLRESOLV_PENDING (1) = waiting for response, no pointer + */ + +enum resolve_t Curl_resolv_timeout(struct Curl_easy *data, + const char *hostname, + int port, + struct Curl_dns_entry **entry, + timediff_t timeoutms) +{ +#ifdef USE_ALARM_TIMEOUT +#ifdef HAVE_SIGACTION + struct sigaction keep_sigact; /* store the old struct here */ + volatile bool keep_copysig = FALSE; /* whether old sigact has been saved */ + struct sigaction sigact; +#else +#ifdef HAVE_SIGNAL + void (*keep_sigact)(int); /* store the old handler here */ +#endif /* HAVE_SIGNAL */ +#endif /* HAVE_SIGACTION */ + volatile long timeout; + volatile unsigned int prev_alarm = 0; +#endif /* USE_ALARM_TIMEOUT */ + enum resolve_t rc; + + *entry = NULL; + + if(timeoutms < 0) + /* got an already expired timeout */ + return CURLRESOLV_TIMEDOUT; + +#ifdef USE_ALARM_TIMEOUT + if(data->set.no_signal) + /* Ignore the timeout when signals are disabled */ + timeout = 0; + else + timeout = (timeoutms > LONG_MAX) ? LONG_MAX : (long)timeoutms; + + if(!timeout) + /* USE_ALARM_TIMEOUT defined, but no timeout actually requested */ + return Curl_resolv(data, hostname, port, TRUE, entry); + + if(timeout < 1000) { + /* The alarm() function only provides integer second resolution, so if + we want to wait less than one second we must bail out already now. */ + failf(data, + "remaining timeout of %ld too small to resolve via SIGALRM method", + timeout); + return CURLRESOLV_TIMEDOUT; + } + /* This allows us to time-out from the name resolver, as the timeout + will generate a signal and we will siglongjmp() from that here. + This technique has problems (see alarmfunc). + This should be the last thing we do before calling Curl_resolv(), + as otherwise we'd have to worry about variables that get modified + before we invoke Curl_resolv() (and thus use "volatile"). */ + curl_simple_lock_lock(&curl_jmpenv_lock); + + if(sigsetjmp(curl_jmpenv, 1)) { + /* this is coming from a siglongjmp() after an alarm signal */ + failf(data, "name lookup timed out"); + rc = CURLRESOLV_ERROR; + goto clean_up; + } + else { + /************************************************************* + * Set signal handler to catch SIGALRM + * Store the old value to be able to set it back later! + *************************************************************/ +#ifdef HAVE_SIGACTION + sigaction(SIGALRM, NULL, &sigact); + keep_sigact = sigact; + keep_copysig = TRUE; /* yes, we have a copy */ + sigact.sa_handler = alarmfunc; +#ifdef SA_RESTART + /* HPUX doesn't have SA_RESTART but defaults to that behavior! */ + sigact.sa_flags &= ~SA_RESTART; +#endif + /* now set the new struct */ + sigaction(SIGALRM, &sigact, NULL); +#else /* HAVE_SIGACTION */ + /* no sigaction(), revert to the much lamer signal() */ +#ifdef HAVE_SIGNAL + keep_sigact = signal(SIGALRM, alarmfunc); +#endif +#endif /* HAVE_SIGACTION */ + + /* alarm() makes a signal get sent when the timeout fires off, and that + will abort system calls */ + prev_alarm = alarm(curlx_sltoui(timeout/1000L)); + } + +#else +#ifndef CURLRES_ASYNCH + if(timeoutms) + infof(data, "timeout on name lookup is not supported"); +#else + (void)timeoutms; /* timeoutms not used with an async resolver */ +#endif +#endif /* USE_ALARM_TIMEOUT */ + + /* Perform the actual name resolution. This might be interrupted by an + * alarm if it takes too long. + */ + rc = Curl_resolv(data, hostname, port, TRUE, entry); + +#ifdef USE_ALARM_TIMEOUT +clean_up: + + if(!prev_alarm) + /* deactivate a possibly active alarm before uninstalling the handler */ + alarm(0); + +#ifdef HAVE_SIGACTION + if(keep_copysig) { + /* we got a struct as it looked before, now put that one back nice + and clean */ + sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */ + } +#else +#ifdef HAVE_SIGNAL + /* restore the previous SIGALRM handler */ + signal(SIGALRM, keep_sigact); +#endif +#endif /* HAVE_SIGACTION */ + + curl_simple_lock_unlock(&curl_jmpenv_lock); + + /* switch back the alarm() to either zero or to what it was before minus + the time we spent until now! */ + if(prev_alarm) { + /* there was an alarm() set before us, now put it back */ + timediff_t elapsed_secs = Curl_timediff(Curl_now(), + data->conn->created) / 1000; + + /* the alarm period is counted in even number of seconds */ + unsigned long alarm_set = (unsigned long)(prev_alarm - elapsed_secs); + + if(!alarm_set || + ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) { + /* if the alarm time-left reached zero or turned "negative" (counted + with unsigned values), we should fire off a SIGALRM here, but we + won't, and zero would be to switch it off so we never set it to + less than 1! */ + alarm(1); + rc = CURLRESOLV_TIMEDOUT; + failf(data, "Previous alarm fired off"); + } + else + alarm((unsigned int)alarm_set); + } +#endif /* USE_ALARM_TIMEOUT */ + + return rc; +} + +/* + * Curl_resolv_unlock() unlocks the given cached DNS entry. When this has been + * made, the struct may be destroyed due to pruning. It is important that only + * one unlock is made for each Curl_resolv() call. + * + * May be called with 'data' == NULL for global cache. + */ +void Curl_resolv_unlock(struct Curl_easy *data, struct Curl_dns_entry *dns) +{ + if(data && data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + freednsentry(dns); + + if(data && data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); +} + +/* + * File-internal: release cache dns entry reference, free if inuse drops to 0 + */ +static void freednsentry(void *freethis) +{ + struct Curl_dns_entry *dns = (struct Curl_dns_entry *) freethis; + DEBUGASSERT(dns && (dns->inuse>0)); + + dns->inuse--; + if(dns->inuse == 0) { + Curl_freeaddrinfo(dns->addr); +#ifdef USE_HTTPSRR + if(dns->hinfo) { + if(dns->hinfo->target) + free(dns->hinfo->target); + if(dns->hinfo->alpns) + free(dns->hinfo->alpns); + if(dns->hinfo->ipv4hints) + free(dns->hinfo->ipv4hints); + if(dns->hinfo->echconfiglist) + free(dns->hinfo->echconfiglist); + if(dns->hinfo->ipv6hints) + free(dns->hinfo->ipv6hints); + if(dns->hinfo->val) + free(dns->hinfo->val); + free(dns->hinfo); + } +#endif + free(dns); + } +} + +/* + * Curl_init_dnscache() inits a new DNS cache. + */ +void Curl_init_dnscache(struct Curl_hash *hash, size_t size) +{ + Curl_hash_init(hash, size, Curl_hash_str, Curl_str_key_compare, + freednsentry); +} + +/* + * Curl_hostcache_clean() + * + * This _can_ be called with 'data' == NULL but then of course no locking + * can be done! + */ + +void Curl_hostcache_clean(struct Curl_easy *data, + struct Curl_hash *hash) +{ + if(data && data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + Curl_hash_clean(hash); + + if(data && data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); +} + + +CURLcode Curl_loadhostpairs(struct Curl_easy *data) +{ + struct curl_slist *hostp; + char *host_end; + + /* Default is no wildcard found */ + data->state.wildcard_resolve = false; + + for(hostp = data->state.resolve; hostp; hostp = hostp->next) { + char entry_id[MAX_HOSTCACHE_LEN]; + if(!hostp->data) + continue; + if(hostp->data[0] == '-') { + unsigned long num = 0; + size_t entry_len; + size_t hlen = 0; + host_end = strchr(&hostp->data[1], ':'); + + if(host_end) { + hlen = host_end - &hostp->data[1]; + num = strtoul(++host_end, NULL, 10); + if(!hlen || (num > 0xffff)) + host_end = NULL; + } + if(!host_end) { + infof(data, "Bad syntax CURLOPT_RESOLVE removal entry '%s'", + hostp->data); + continue; + } + /* Create an entry id, based upon the hostname and port */ + entry_len = create_hostcache_id(&hostp->data[1], hlen, (int)num, + entry_id, sizeof(entry_id)); + if(data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + /* delete entry, ignore if it didn't exist */ + Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1); + + if(data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); + } + else { + struct Curl_dns_entry *dns; + struct Curl_addrinfo *head = NULL, *tail = NULL; + size_t entry_len; + char address[64]; +#if !defined(CURL_DISABLE_VERBOSE_STRINGS) + char *addresses = NULL; +#endif + char *addr_begin; + char *addr_end; + char *port_ptr; + int port = 0; + char *end_ptr; + bool permanent = TRUE; + unsigned long tmp_port; + bool error = true; + char *host_begin = hostp->data; + size_t hlen = 0; + + if(host_begin[0] == '+') { + host_begin++; + permanent = FALSE; + } + host_end = strchr(host_begin, ':'); + if(!host_end) + goto err; + hlen = host_end - host_begin; + + port_ptr = host_end + 1; + tmp_port = strtoul(port_ptr, &end_ptr, 10); + if(tmp_port > USHRT_MAX || end_ptr == port_ptr || *end_ptr != ':') + goto err; + + port = (int)tmp_port; +#if !defined(CURL_DISABLE_VERBOSE_STRINGS) + addresses = end_ptr + 1; +#endif + + while(*end_ptr) { + size_t alen; + struct Curl_addrinfo *ai; + + addr_begin = end_ptr + 1; + addr_end = strchr(addr_begin, ','); + if(!addr_end) + addr_end = addr_begin + strlen(addr_begin); + end_ptr = addr_end; + + /* allow IP(v6) address within [brackets] */ + if(*addr_begin == '[') { + if(addr_end == addr_begin || *(addr_end - 1) != ']') + goto err; + ++addr_begin; + --addr_end; + } + + alen = addr_end - addr_begin; + if(!alen) + continue; + + if(alen >= sizeof(address)) + goto err; + + memcpy(address, addr_begin, alen); + address[alen] = '\0'; + +#ifndef USE_IPV6 + if(strchr(address, ':')) { + infof(data, "Ignoring resolve address '%s', missing IPv6 support.", + address); + continue; + } +#endif + + ai = Curl_str2addr(address, port); + if(!ai) { + infof(data, "Resolve address '%s' found illegal", address); + goto err; + } + + if(tail) { + tail->ai_next = ai; + tail = tail->ai_next; + } + else { + head = tail = ai; + } + } + + if(!head) + goto err; + + error = false; +err: + if(error) { + failf(data, "Couldn't parse CURLOPT_RESOLVE entry '%s'", + hostp->data); + Curl_freeaddrinfo(head); + return CURLE_SETOPT_OPTION_SYNTAX; + } + + /* Create an entry id, based upon the hostname and port */ + entry_len = create_hostcache_id(host_begin, hlen, port, + entry_id, sizeof(entry_id)); + + if(data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + /* See if it's already in our dns cache */ + dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1); + + if(dns) { + infof(data, "RESOLVE %.*s:%d - old addresses discarded", + (int)hlen, host_begin, port); + /* delete old entry, there are two reasons for this + 1. old entry may have different addresses. + 2. even if entry with correct addresses is already in the cache, + but if it is close to expire, then by the time next http + request is made, it can get expired and pruned because old + entry is not necessarily marked as permanent. + 3. when adding a non-permanent entry, we want it to remove and + replace an existing permanent entry. + 4. when adding a non-permanent entry, we want it to get a "fresh" + timeout that starts _now_. */ + + Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1); + } + + /* put this new host in the cache */ + dns = Curl_cache_addr(data, head, host_begin, hlen, port); + if(dns) { + if(permanent) + dns->timestamp = 0; /* mark as permanent */ + /* release the returned reference; the cache itself will keep the + * entry alive: */ + dns->inuse--; + } + + if(data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); + + if(!dns) { + Curl_freeaddrinfo(head); + return CURLE_OUT_OF_MEMORY; + } +#ifndef CURL_DISABLE_VERBOSE_STRINGS + infof(data, "Added %.*s:%d:%s to DNS cache%s", + (int)hlen, host_begin, port, addresses, + permanent ? "" : " (non-permanent)"); +#endif + + /* Wildcard hostname */ + if((hlen == 1) && (host_begin[0] == '*')) { + infof(data, "RESOLVE *:%d using wildcard", port); + data->state.wildcard_resolve = true; + } + } + } + data->state.resolve = NULL; /* dealt with now */ + + return CURLE_OK; +} + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +static void show_resolve_info(struct Curl_easy *data, + struct Curl_dns_entry *dns) +{ + struct Curl_addrinfo *a; + CURLcode result = CURLE_OK; +#ifdef CURLRES_IPV6 + struct dynbuf out[2]; +#else + struct dynbuf out[1]; +#endif + DEBUGASSERT(data); + DEBUGASSERT(dns); + + if(!data->set.verbose || + /* ignore no name or numerical IP addresses */ + !dns->hostname[0] || Curl_host_is_ipnum(dns->hostname)) + return; + + a = dns->addr; + + infof(data, "Host %s:%d was resolved.", + (dns->hostname[0] ? dns->hostname : "(none)"), dns->hostport); + + Curl_dyn_init(&out[0], 1024); +#ifdef CURLRES_IPV6 + Curl_dyn_init(&out[1], 1024); +#endif + + while(a) { + if( +#ifdef CURLRES_IPV6 + a->ai_family == PF_INET6 || +#endif + a->ai_family == PF_INET) { + char buf[MAX_IPADR_LEN]; + struct dynbuf *d = &out[(a->ai_family != PF_INET)]; + Curl_printable_address(a, buf, sizeof(buf)); + if(Curl_dyn_len(d)) + result = Curl_dyn_addn(d, ", ", 2); + if(!result) + result = Curl_dyn_add(d, buf); + if(result) { + infof(data, "too many IP, can't show"); + goto fail; + } + } + a = a->ai_next; + } + +#ifdef CURLRES_IPV6 + infof(data, "IPv6: %s", + (Curl_dyn_len(&out[1]) ? Curl_dyn_ptr(&out[1]) : "(none)")); +#endif + infof(data, "IPv4: %s", + (Curl_dyn_len(&out[0]) ? Curl_dyn_ptr(&out[0]) : "(none)")); + +fail: + Curl_dyn_free(&out[0]); +#ifdef CURLRES_IPV6 + Curl_dyn_free(&out[1]); +#endif +} +#endif + +CURLcode Curl_resolv_check(struct Curl_easy *data, + struct Curl_dns_entry **dns) +{ + CURLcode result; +#if defined(CURL_DISABLE_DOH) && !defined(CURLRES_ASYNCH) + (void)data; + (void)dns; +#endif +#ifndef CURL_DISABLE_DOH + if(data->conn->bits.doh) { + result = Curl_doh_is_resolved(data, dns); + } + else +#endif + result = Curl_resolver_is_resolved(data, dns); + if(*dns) + show_resolve_info(data, *dns); + return result; +} + +int Curl_resolv_getsock(struct Curl_easy *data, + curl_socket_t *socks) +{ +#ifdef CURLRES_ASYNCH +#ifndef CURL_DISABLE_DOH + if(data->conn->bits.doh) + /* nothing to wait for during DoH resolve, those handles have their own + sockets */ + return GETSOCK_BLANK; +#endif + return Curl_resolver_getsock(data, socks); +#else + (void)data; + (void)socks; + return GETSOCK_BLANK; +#endif +} + +/* Call this function after Curl_connect() has returned async=TRUE and + then a successful name resolve has been received. + + Note: this function disconnects and frees the conn data in case of + resolve failure */ +CURLcode Curl_once_resolved(struct Curl_easy *data, bool *protocol_done) +{ + CURLcode result; + struct connectdata *conn = data->conn; + +#ifdef USE_CURL_ASYNC + if(data->state.async.dns) { + conn->dns_entry = data->state.async.dns; + data->state.async.dns = NULL; + } +#endif + + result = Curl_setup_conn(data, protocol_done); + + if(result) { + Curl_detach_connection(data); + Curl_conncache_remove_conn(data, conn, TRUE); + Curl_disconnect(data, conn, TRUE); + } + return result; +} + +/* + * Curl_resolver_error() calls failf() with the appropriate message after a + * resolve error + */ + +#ifdef USE_CURL_ASYNC +CURLcode Curl_resolver_error(struct Curl_easy *data) +{ + const char *host_or_proxy; + CURLcode result; + +#ifndef CURL_DISABLE_PROXY + struct connectdata *conn = data->conn; + if(conn->bits.httpproxy) { + host_or_proxy = "proxy"; + result = CURLE_COULDNT_RESOLVE_PROXY; + } + else +#endif + { + host_or_proxy = "host"; + result = CURLE_COULDNT_RESOLVE_HOST; + } + + failf(data, "Could not resolve %s: %s", host_or_proxy, + data->state.async.hostname); + + return result; +} +#endif /* USE_CURL_ASYNC */ diff --git a/third_party/curl/lib/hostip.h b/third_party/curl/lib/hostip.h new file mode 100644 index 0000000..bf4e94d --- /dev/null +++ b/third_party/curl/lib/hostip.h @@ -0,0 +1,266 @@ +#ifndef HEADER_CURL_HOSTIP_H +#define HEADER_CURL_HOSTIP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "hash.h" +#include "curl_addrinfo.h" +#include "timeval.h" /* for timediff_t */ +#include "asyn.h" + +#include + +#ifdef USE_HTTPSRR +# include +#endif + +/* Allocate enough memory to hold the full name information structs and + * everything. OSF1 is known to require at least 8872 bytes. The buffer + * required for storing all possible aliases and IP numbers is according to + * Stevens' Unix Network Programming 2nd edition, p. 304: 8192 bytes! + */ +#define CURL_HOSTENT_SIZE 9000 + +#define CURL_TIMEOUT_RESOLVE 300 /* when using asynch methods, we allow this + many seconds for a name resolve */ + +#define CURL_ASYNC_SUCCESS CURLE_OK + +struct addrinfo; +struct hostent; +struct Curl_easy; +struct connectdata; + +/* + * Curl_global_host_cache_init() initializes and sets up a global DNS cache. + * Global DNS cache is general badness. Do not use. This will be removed in + * a future version. Use the share interface instead! + * + * Returns a struct Curl_hash pointer on success, NULL on failure. + */ +struct Curl_hash *Curl_global_host_cache_init(void); + +#ifdef USE_HTTPSRR + +#define CURL_MAXLEN_host_name 253 + +struct Curl_https_rrinfo { + size_t len; /* raw encoded length */ + unsigned char *val; /* raw encoded octets */ + /* + * fields from HTTPS RR, with the mandatory fields + * first (priority, target), then the others in the + * order of the keytag numbers defined at + * https://datatracker.ietf.org/doc/html/rfc9460#section-14.3.2 + */ + uint16_t priority; + char *target; + char *alpns; /* keytag = 1 */ + bool no_def_alpn; /* keytag = 2 */ + /* + * we don't support ports (keytag = 3) as we don't support + * port-switching yet + */ + unsigned char *ipv4hints; /* keytag = 4 */ + size_t ipv4hints_len; + unsigned char *echconfiglist; /* keytag = 5 */ + size_t echconfiglist_len; + unsigned char *ipv6hints; /* keytag = 6 */ + size_t ipv6hints_len; +}; +#endif + +struct Curl_dns_entry { + struct Curl_addrinfo *addr; +#ifdef USE_HTTPSRR + struct Curl_https_rrinfo *hinfo; +#endif + /* timestamp == 0 -- permanent CURLOPT_RESOLVE entry (doesn't time out) */ + time_t timestamp; + /* use-counter, use Curl_resolv_unlock to release reference */ + long inuse; + /* hostname port number that resolved to addr. */ + int hostport; + /* hostname that resolved to addr. may be NULL (unix domain sockets). */ + char hostname[1]; +}; + +bool Curl_host_is_ipnum(const char *hostname); + +/* + * Curl_resolv() returns an entry with the info for the specified host + * and port. + * + * The returned data *MUST* be "unlocked" with Curl_resolv_unlock() after + * use, or we'll leak memory! + */ +/* return codes */ +enum resolve_t { + CURLRESOLV_TIMEDOUT = -2, + CURLRESOLV_ERROR = -1, + CURLRESOLV_RESOLVED = 0, + CURLRESOLV_PENDING = 1 +}; +enum resolve_t Curl_resolv(struct Curl_easy *data, + const char *hostname, + int port, + bool allowDOH, + struct Curl_dns_entry **dnsentry); +enum resolve_t Curl_resolv_timeout(struct Curl_easy *data, + const char *hostname, int port, + struct Curl_dns_entry **dnsentry, + timediff_t timeoutms); + +#ifdef USE_IPV6 +/* + * Curl_ipv6works() returns TRUE if IPv6 seems to work. + */ +bool Curl_ipv6works(struct Curl_easy *data); +#else +#define Curl_ipv6works(x) FALSE +#endif + +/* + * Curl_ipvalid() checks what CURL_IPRESOLVE_* requirements that might've + * been set and returns TRUE if they are OK. + */ +bool Curl_ipvalid(struct Curl_easy *data, struct connectdata *conn); + + +/* + * Curl_getaddrinfo() is the generic low-level name resolve API within this + * source file. There are several versions of this function - for different + * name resolve layers (selected at build-time). They all take this same set + * of arguments + */ +struct Curl_addrinfo *Curl_getaddrinfo(struct Curl_easy *data, + const char *hostname, + int port, + int *waitp); + + +/* unlock a previously resolved dns entry */ +void Curl_resolv_unlock(struct Curl_easy *data, + struct Curl_dns_entry *dns); + +/* init a new dns cache */ +void Curl_init_dnscache(struct Curl_hash *hash, size_t hashsize); + +/* prune old entries from the DNS cache */ +void Curl_hostcache_prune(struct Curl_easy *data); + +/* IPv4 threadsafe resolve function used for synch and asynch builds */ +struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname, int port); + +CURLcode Curl_once_resolved(struct Curl_easy *data, bool *protocol_connect); + +/* + * Curl_addrinfo_callback() is used when we build with any asynch specialty. + * Handles end of async request processing. Inserts ai into hostcache when + * status is CURL_ASYNC_SUCCESS. Twiddles fields in conn to indicate async + * request completed whether successful or failed. + */ +CURLcode Curl_addrinfo_callback(struct Curl_easy *data, + int status, + struct Curl_addrinfo *ai); + +/* + * Curl_printable_address() returns a printable version of the 1st address + * given in the 'ip' argument. The result will be stored in the buf that is + * bufsize bytes big. + */ +void Curl_printable_address(const struct Curl_addrinfo *ip, + char *buf, size_t bufsize); + +/* + * Curl_fetch_addr() fetches a 'Curl_dns_entry' already in the DNS cache. + * + * Returns the Curl_dns_entry entry pointer or NULL if not in the cache. + * + * The returned data *MUST* be "unlocked" with Curl_resolv_unlock() after + * use, or we'll leak memory! + */ +struct Curl_dns_entry * +Curl_fetch_addr(struct Curl_easy *data, + const char *hostname, + int port); + +/* + * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache. + * + * Returns the Curl_dns_entry entry pointer or NULL if the storage failed. + */ +struct Curl_dns_entry * +Curl_cache_addr(struct Curl_easy *data, struct Curl_addrinfo *addr, + const char *hostname, size_t hostlen, int port); + +#ifndef INADDR_NONE +#define CURL_INADDR_NONE (in_addr_t) ~0 +#else +#define CURL_INADDR_NONE INADDR_NONE +#endif + +/* + * Function provided by the resolver backend to set DNS servers to use. + */ +CURLcode Curl_set_dns_servers(struct Curl_easy *data, char *servers); + +/* + * Function provided by the resolver backend to set + * outgoing interface to use for DNS requests + */ +CURLcode Curl_set_dns_interface(struct Curl_easy *data, + const char *interf); + +/* + * Function provided by the resolver backend to set + * local IPv4 address to use as source address for DNS requests + */ +CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data, + const char *local_ip4); + +/* + * Function provided by the resolver backend to set + * local IPv6 address to use as source address for DNS requests + */ +CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data, + const char *local_ip6); + +/* + * Clean off entries from the cache + */ +void Curl_hostcache_clean(struct Curl_easy *data, struct Curl_hash *hash); + +/* + * Populate the cache with specified entries from CURLOPT_RESOLVE. + */ +CURLcode Curl_loadhostpairs(struct Curl_easy *data); +CURLcode Curl_resolv_check(struct Curl_easy *data, + struct Curl_dns_entry **dns); +int Curl_resolv_getsock(struct Curl_easy *data, + curl_socket_t *socks); + +CURLcode Curl_resolver_error(struct Curl_easy *data); +#endif /* HEADER_CURL_HOSTIP_H */ diff --git a/third_party/curl/lib/hostip4.c b/third_party/curl/lib/hostip4.c new file mode 100644 index 0000000..9140180 --- /dev/null +++ b/third_party/curl/lib/hostip4.c @@ -0,0 +1,301 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +/*********************************************************************** + * Only for plain IPv4 builds + **********************************************************************/ +#ifdef CURLRES_IPV4 /* plain IPv4 code coming up */ + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef __VMS +#include +#include +#endif + +#include "urldata.h" +#include "sendf.h" +#include "hostip.h" +#include "hash.h" +#include "share.h" +#include "url.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_ipvalid() checks what CURL_IPRESOLVE_* requirements that might've + * been set and returns TRUE if they are OK. + */ +bool Curl_ipvalid(struct Curl_easy *data, struct connectdata *conn) +{ + (void)data; + if(conn->ip_version == CURL_IPRESOLVE_V6) + /* An IPv6 address was requested and we can't get/use one */ + return FALSE; + + return TRUE; /* OK, proceed */ +} + +#ifdef CURLRES_SYNCH + +/* + * Curl_getaddrinfo() - the IPv4 synchronous version. + * + * The original code to this function was from the Dancer source code, written + * by Bjorn Reese, it has since been patched and modified considerably. + * + * gethostbyname_r() is the thread-safe version of the gethostbyname() + * function. When we build for plain IPv4, we attempt to use this + * function. There are _three_ different gethostbyname_r() versions, and we + * detect which one this platform supports in the configure script and set up + * the HAVE_GETHOSTBYNAME_R_3, HAVE_GETHOSTBYNAME_R_5 or + * HAVE_GETHOSTBYNAME_R_6 defines accordingly. Note that HAVE_GETADDRBYNAME + * has the corresponding rules. This is primarily on *nix. Note that some unix + * flavours have thread-safe versions of the plain gethostbyname() etc. + * + */ +struct Curl_addrinfo *Curl_getaddrinfo(struct Curl_easy *data, + const char *hostname, + int port, + int *waitp) +{ + struct Curl_addrinfo *ai = NULL; + +#ifdef CURL_DISABLE_VERBOSE_STRINGS + (void)data; +#endif + + *waitp = 0; /* synchronous response only */ + + ai = Curl_ipv4_resolve_r(hostname, port); + if(!ai) + infof(data, "Curl_ipv4_resolve_r failed for %s", hostname); + + return ai; +} +#endif /* CURLRES_SYNCH */ +#endif /* CURLRES_IPV4 */ + +#if defined(CURLRES_IPV4) && \ + !defined(CURLRES_ARES) && !defined(CURLRES_AMIGA) + +/* + * Curl_ipv4_resolve_r() - ipv4 threadsafe resolver function. + * + * This is used for both synchronous and asynchronous resolver builds, + * implying that only threadsafe code and function calls may be used. + * + */ +struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname, + int port) +{ +#if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETADDRINFO_THREADSAFE)) && \ + defined(HAVE_GETHOSTBYNAME_R_3) + int res; +#endif + struct Curl_addrinfo *ai = NULL; + struct hostent *h = NULL; + struct hostent *buf = NULL; + +#if defined(HAVE_GETADDRINFO) && defined(HAVE_GETADDRINFO_THREADSAFE) + struct addrinfo hints; + char sbuf[12]; + char *sbufptr = NULL; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = PF_INET; + hints.ai_socktype = SOCK_STREAM; + if(port) { + msnprintf(sbuf, sizeof(sbuf), "%d", port); + sbufptr = sbuf; + } + + (void)Curl_getaddrinfo_ex(hostname, sbufptr, &hints, &ai); + +#elif defined(HAVE_GETHOSTBYNAME_R) + /* + * gethostbyname_r() is the preferred resolve function for many platforms. + * Since there are three different versions of it, the following code is + * somewhat #ifdef-ridden. + */ + int h_errnop; + + buf = calloc(1, CURL_HOSTENT_SIZE); + if(!buf) + return NULL; /* major failure */ + /* + * The clearing of the buffer is a workaround for a gethostbyname_r bug in + * qnx nto and it is also _required_ for some of these functions on some + * platforms. + */ + +#if defined(HAVE_GETHOSTBYNAME_R_5) + /* Solaris, IRIX and more */ + h = gethostbyname_r(hostname, + (struct hostent *)buf, + (char *)buf + sizeof(struct hostent), + CURL_HOSTENT_SIZE - sizeof(struct hostent), + &h_errnop); + + /* If the buffer is too small, it returns NULL and sets errno to + * ERANGE. The errno is thread safe if this is compiled with + * -D_REENTRANT as then the 'errno' variable is a macro defined to get + * used properly for threads. + */ + + if(h) { + ; + } + else +#elif defined(HAVE_GETHOSTBYNAME_R_6) + /* Linux */ + + (void)gethostbyname_r(hostname, + (struct hostent *)buf, + (char *)buf + sizeof(struct hostent), + CURL_HOSTENT_SIZE - sizeof(struct hostent), + &h, /* DIFFERENCE */ + &h_errnop); + /* Redhat 8, using glibc 2.2.93 changed the behavior. Now all of a + * sudden this function returns EAGAIN if the given buffer size is too + * small. Previous versions are known to return ERANGE for the same + * problem. + * + * This wouldn't be such a big problem if older versions wouldn't + * sometimes return EAGAIN on a common failure case. Alas, we can't + * assume that EAGAIN *or* ERANGE means ERANGE for any given version of + * glibc. + * + * For now, we do that and thus we may call the function repeatedly and + * fail for older glibc versions that return EAGAIN, until we run out of + * buffer size (step_size grows beyond CURL_HOSTENT_SIZE). + * + * If anyone has a better fix, please tell us! + * + * ------------------------------------------------------------------- + * + * On October 23rd 2003, Dan C dug up more details on the mysteries of + * gethostbyname_r() in glibc: + * + * In glibc 2.2.5 the interface is different (this has also been + * discovered in glibc 2.1.1-6 as shipped by Redhat 6). What I can't + * explain, is that tests performed on glibc 2.2.4-34 and 2.2.4-32 + * (shipped/upgraded by Redhat 7.2) don't show this behavior! + * + * In this "buggy" version, the return code is -1 on error and 'errno' + * is set to the ERANGE or EAGAIN code. Note that 'errno' is not a + * thread-safe variable. + */ + + if(!h) /* failure */ +#elif defined(HAVE_GETHOSTBYNAME_R_3) + /* AIX, Digital Unix/Tru64, HPUX 10, more? */ + + /* For AIX 4.3 or later, we don't use gethostbyname_r() at all, because of + * the plain fact that it does not return unique full buffers on each + * call, but instead several of the pointers in the hostent structs will + * point to the same actual data! This have the unfortunate down-side that + * our caching system breaks down horribly. Luckily for us though, AIX 4.3 + * and more recent versions have a "completely thread-safe"[*] libc where + * all the data is stored in thread-specific memory areas making calls to + * the plain old gethostbyname() work fine even for multi-threaded + * programs. + * + * This AIX 4.3 or later detection is all made in the configure script. + * + * Troels Walsted Hansen helped us work this out on March 3rd, 2003. + * + * [*] = much later we've found out that it isn't at all "completely + * thread-safe", but at least the gethostbyname() function is. + */ + + if(CURL_HOSTENT_SIZE >= + (sizeof(struct hostent) + sizeof(struct hostent_data))) { + + /* August 22nd, 2000: Albert Chin-A-Young brought an updated version + * that should work! September 20: Richard Prescott worked on the buffer + * size dilemma. + */ + + res = gethostbyname_r(hostname, + (struct hostent *)buf, + (struct hostent_data *)((char *)buf + + sizeof(struct hostent))); + h_errnop = SOCKERRNO; /* we don't deal with this, but set it anyway */ + } + else + res = -1; /* failure, too smallish buffer size */ + + if(!res) { /* success */ + + h = buf; /* result expected in h */ + + /* This is the worst kind of the different gethostbyname_r() interfaces. + * Since we don't know how big buffer this particular lookup required, + * we can't realloc down the huge alloc without doing closer analysis of + * the returned data. Thus, we always use CURL_HOSTENT_SIZE for every + * name lookup. Fixing this would require an extra malloc() and then + * calling Curl_addrinfo_copy() that subsequent realloc()s down the new + * memory area to the actually used amount. + */ + } + else +#endif /* HAVE_...BYNAME_R_5 || HAVE_...BYNAME_R_6 || HAVE_...BYNAME_R_3 */ + { + h = NULL; /* set return code to NULL */ + free(buf); + } +#else /* (HAVE_GETADDRINFO && HAVE_GETADDRINFO_THREADSAFE) || + HAVE_GETHOSTBYNAME_R */ + /* + * Here is code for platforms that don't have a thread safe + * getaddrinfo() nor gethostbyname_r() function or for which + * gethostbyname() is the preferred one. + */ + h = gethostbyname((void *)hostname); +#endif /* (HAVE_GETADDRINFO && HAVE_GETADDRINFO_THREADSAFE) || + HAVE_GETHOSTBYNAME_R */ + + if(h) { + ai = Curl_he2ai(h, port); + + if(buf) /* used a *_r() function */ + free(buf); + } + + return ai; +} +#endif /* defined(CURLRES_IPV4) && !defined(CURLRES_ARES) && + !defined(CURLRES_AMIGA) */ diff --git a/third_party/curl/lib/hostip6.c b/third_party/curl/lib/hostip6.c new file mode 100644 index 0000000..18969a7 --- /dev/null +++ b/third_party/curl/lib/hostip6.c @@ -0,0 +1,157 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +/*********************************************************************** + * Only for IPv6-enabled builds + **********************************************************************/ +#ifdef CURLRES_IPV6 + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef __VMS +#include +#include +#endif + +#include "urldata.h" +#include "sendf.h" +#include "hostip.h" +#include "hash.h" +#include "share.h" +#include "url.h" +#include "inet_pton.h" +#include "connect.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_ipvalid() checks what CURL_IPRESOLVE_* requirements that might've + * been set and returns TRUE if they are OK. + */ +bool Curl_ipvalid(struct Curl_easy *data, struct connectdata *conn) +{ + if(conn->ip_version == CURL_IPRESOLVE_V6) + return Curl_ipv6works(data); + + return TRUE; +} + +#if defined(CURLRES_SYNCH) + +#ifdef DEBUG_ADDRINFO +static void dump_addrinfo(const struct Curl_addrinfo *ai) +{ + printf("dump_addrinfo:\n"); + for(; ai; ai = ai->ai_next) { + char buf[INET6_ADDRSTRLEN]; + printf(" fam %2d, CNAME %s, ", + ai->ai_family, ai->ai_canonname ? ai->ai_canonname : ""); + Curl_printable_address(ai, buf, sizeof(buf)); + printf("%s\n", buf); + } +} +#else +#define dump_addrinfo(x) Curl_nop_stmt +#endif + +/* + * Curl_getaddrinfo() when built IPv6-enabled (non-threading and + * non-ares version). + * + * Returns name information about the given hostname and port number. If + * successful, the 'addrinfo' is returned and the fourth argument will point + * to memory we need to free after use. That memory *MUST* be freed with + * Curl_freeaddrinfo(), nothing else. + */ +struct Curl_addrinfo *Curl_getaddrinfo(struct Curl_easy *data, + const char *hostname, + int port, + int *waitp) +{ + struct addrinfo hints; + struct Curl_addrinfo *res; + int error; + char sbuf[12]; + char *sbufptr = NULL; +#ifndef USE_RESOLVE_ON_IPS + char addrbuf[128]; +#endif + int pf = PF_INET; + + *waitp = 0; /* synchronous response only */ + + if((data->conn->ip_version != CURL_IPRESOLVE_V4) && Curl_ipv6works(data)) + /* The stack seems to be IPv6-enabled */ + pf = PF_UNSPEC; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = pf; + hints.ai_socktype = (data->conn->transport == TRNSPRT_TCP) ? + SOCK_STREAM : SOCK_DGRAM; + +#ifndef USE_RESOLVE_ON_IPS + /* + * The AI_NUMERICHOST must not be set to get synthesized IPv6 address from + * an IPv4 address on iOS and Mac OS X. + */ + if((1 == Curl_inet_pton(AF_INET, hostname, addrbuf)) || + (1 == Curl_inet_pton(AF_INET6, hostname, addrbuf))) { + /* the given address is numerical only, prevent a reverse lookup */ + hints.ai_flags = AI_NUMERICHOST; + } +#endif + + if(port) { + msnprintf(sbuf, sizeof(sbuf), "%d", port); + sbufptr = sbuf; + } + + error = Curl_getaddrinfo_ex(hostname, sbufptr, &hints, &res); + if(error) { + infof(data, "getaddrinfo(3) failed for %s:%d", hostname, port); + return NULL; + } + + if(port) { + Curl_addrinfo_set_port(res, port); + } + + dump_addrinfo(res); + + return res; +} +#endif /* CURLRES_SYNCH */ + +#endif /* CURLRES_IPV6 */ diff --git a/third_party/curl/lib/hostsyn.c b/third_party/curl/lib/hostsyn.c new file mode 100644 index 0000000..ca8b075 --- /dev/null +++ b/third_party/curl/lib/hostsyn.c @@ -0,0 +1,104 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +/*********************************************************************** + * Only for builds using synchronous name resolves + **********************************************************************/ +#ifdef CURLRES_SYNCH + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef __VMS +#include +#include +#endif + +#include "urldata.h" +#include "sendf.h" +#include "hostip.h" +#include "hash.h" +#include "share.h" +#include "url.h" +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + +/* + * Function provided by the resolver backend to set DNS servers to use. + */ +CURLcode Curl_set_dns_servers(struct Curl_easy *data, + char *servers) +{ + (void)data; + (void)servers; + return CURLE_NOT_BUILT_IN; + +} + +/* + * Function provided by the resolver backend to set + * outgoing interface to use for DNS requests + */ +CURLcode Curl_set_dns_interface(struct Curl_easy *data, + const char *interf) +{ + (void)data; + (void)interf; + return CURLE_NOT_BUILT_IN; +} + +/* + * Function provided by the resolver backend to set + * local IPv4 address to use as source address for DNS requests + */ +CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data, + const char *local_ip4) +{ + (void)data; + (void)local_ip4; + return CURLE_NOT_BUILT_IN; +} + +/* + * Function provided by the resolver backend to set + * local IPv6 address to use as source address for DNS requests + */ +CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data, + const char *local_ip6) +{ + (void)data; + (void)local_ip6; + return CURLE_NOT_BUILT_IN; +} + +#endif /* truly sync */ diff --git a/third_party/curl/lib/hsts.c b/third_party/curl/lib/hsts.c new file mode 100644 index 0000000..a5e7676 --- /dev/null +++ b/third_party/curl/lib/hsts.c @@ -0,0 +1,576 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * The Strict-Transport-Security header is defined in RFC 6797: + * https://datatracker.ietf.org/doc/html/rfc6797 + */ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HSTS) +#include +#include "urldata.h" +#include "llist.h" +#include "hsts.h" +#include "curl_get_line.h" +#include "strcase.h" +#include "sendf.h" +#include "strtoofft.h" +#include "parsedate.h" +#include "fopen.h" +#include "rename.h" +#include "share.h" +#include "strdup.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#define MAX_HSTS_LINE 4095 +#define MAX_HSTS_HOSTLEN 256 +#define MAX_HSTS_HOSTLENSTR "256" +#define MAX_HSTS_DATELEN 64 +#define MAX_HSTS_DATELENSTR "64" +#define UNLIMITED "unlimited" + +#ifdef DEBUGBUILD +/* to play well with debug builds, we can *set* a fixed time this will + return */ +time_t deltatime; /* allow for "adjustments" for unit test purposes */ +static time_t hsts_debugtime(void *unused) +{ + char *timestr = getenv("CURL_TIME"); + (void)unused; + if(timestr) { + curl_off_t val; + (void)curlx_strtoofft(timestr, NULL, 10, &val); + + val += (curl_off_t)deltatime; + return (time_t)val; + } + return time(NULL); +} +#undef time +#define time(x) hsts_debugtime(x) +#endif + +struct hsts *Curl_hsts_init(void) +{ + struct hsts *h = calloc(1, sizeof(struct hsts)); + if(h) { + Curl_llist_init(&h->list, NULL); + } + return h; +} + +static void hsts_free(struct stsentry *e) +{ + free((char *)e->host); + free(e); +} + +void Curl_hsts_cleanup(struct hsts **hp) +{ + struct hsts *h = *hp; + if(h) { + struct Curl_llist_element *e; + struct Curl_llist_element *n; + for(e = h->list.head; e; e = n) { + struct stsentry *sts = e->ptr; + n = e->next; + hsts_free(sts); + } + free(h->filename); + free(h); + *hp = NULL; + } +} + +static CURLcode hsts_create(struct hsts *h, + const char *hostname, + bool subdomains, + curl_off_t expires) +{ + size_t hlen; + DEBUGASSERT(h); + DEBUGASSERT(hostname); + + hlen = strlen(hostname); + if(hlen && (hostname[hlen - 1] == '.')) + /* strip off any trailing dot */ + --hlen; + if(hlen) { + char *duphost; + struct stsentry *sts = calloc(1, sizeof(struct stsentry)); + if(!sts) + return CURLE_OUT_OF_MEMORY; + + duphost = Curl_memdup0(hostname, hlen); + if(!duphost) { + free(sts); + return CURLE_OUT_OF_MEMORY; + } + + sts->host = duphost; + sts->expires = expires; + sts->includeSubDomains = subdomains; + Curl_llist_append(&h->list, sts, &sts->node); + } + return CURLE_OK; +} + +CURLcode Curl_hsts_parse(struct hsts *h, const char *hostname, + const char *header) +{ + const char *p = header; + curl_off_t expires = 0; + bool gotma = FALSE; + bool gotinc = FALSE; + bool subdomains = FALSE; + struct stsentry *sts; + time_t now = time(NULL); + + if(Curl_host_is_ipnum(hostname)) + /* "explicit IP address identification of all forms is excluded." + / RFC 6797 */ + return CURLE_OK; + + do { + while(*p && ISBLANK(*p)) + p++; + if(strncasecompare("max-age=", p, 8)) { + bool quoted = FALSE; + CURLofft offt; + char *endp; + + if(gotma) + return CURLE_BAD_FUNCTION_ARGUMENT; + + p += 8; + while(*p && ISBLANK(*p)) + p++; + if(*p == '\"') { + p++; + quoted = TRUE; + } + offt = curlx_strtoofft(p, &endp, 10, &expires); + if(offt == CURL_OFFT_FLOW) + expires = CURL_OFF_T_MAX; + else if(offt) + /* invalid max-age */ + return CURLE_BAD_FUNCTION_ARGUMENT; + p = endp; + if(quoted) { + if(*p != '\"') + return CURLE_BAD_FUNCTION_ARGUMENT; + p++; + } + gotma = TRUE; + } + else if(strncasecompare("includesubdomains", p, 17)) { + if(gotinc) + return CURLE_BAD_FUNCTION_ARGUMENT; + subdomains = TRUE; + p += 17; + gotinc = TRUE; + } + else { + /* unknown directive, do a lame attempt to skip */ + while(*p && (*p != ';')) + p++; + } + + while(*p && ISBLANK(*p)) + p++; + if(*p == ';') + p++; + } while(*p); + + if(!gotma) + /* max-age is mandatory */ + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(!expires) { + /* remove the entry if present verbatim (without subdomain match) */ + sts = Curl_hsts(h, hostname, FALSE); + if(sts) { + Curl_llist_remove(&h->list, &sts->node, NULL); + hsts_free(sts); + } + return CURLE_OK; + } + + if(CURL_OFF_T_MAX - now < expires) + /* would overflow, use maximum value */ + expires = CURL_OFF_T_MAX; + else + expires += now; + + /* check if it already exists */ + sts = Curl_hsts(h, hostname, FALSE); + if(sts) { + /* just update these fields */ + sts->expires = expires; + sts->includeSubDomains = subdomains; + } + else + return hsts_create(h, hostname, subdomains, expires); + + return CURLE_OK; +} + +/* + * Return TRUE if the given host name is currently an HSTS one. + * + * The 'subdomain' argument tells the function if subdomain matching should be + * attempted. + */ +struct stsentry *Curl_hsts(struct hsts *h, const char *hostname, + bool subdomain) +{ + if(h) { + char buffer[MAX_HSTS_HOSTLEN + 1]; + time_t now = time(NULL); + size_t hlen = strlen(hostname); + struct Curl_llist_element *e; + struct Curl_llist_element *n; + + if((hlen > MAX_HSTS_HOSTLEN) || !hlen) + return NULL; + memcpy(buffer, hostname, hlen); + if(hostname[hlen-1] == '.') + /* remove the trailing dot */ + --hlen; + buffer[hlen] = 0; + hostname = buffer; + + for(e = h->list.head; e; e = n) { + struct stsentry *sts = e->ptr; + n = e->next; + if(sts->expires <= now) { + /* remove expired entries */ + Curl_llist_remove(&h->list, &sts->node, NULL); + hsts_free(sts); + continue; + } + if(subdomain && sts->includeSubDomains) { + size_t ntail = strlen(sts->host); + if(ntail < hlen) { + size_t offs = hlen - ntail; + if((hostname[offs-1] == '.') && + strncasecompare(&hostname[offs], sts->host, ntail)) + return sts; + } + } + if(strcasecompare(hostname, sts->host)) + return sts; + } + } + return NULL; /* no match */ +} + +/* + * Send this HSTS entry to the write callback. + */ +static CURLcode hsts_push(struct Curl_easy *data, + struct curl_index *i, + struct stsentry *sts, + bool *stop) +{ + struct curl_hstsentry e; + CURLSTScode sc; + struct tm stamp; + CURLcode result; + + e.name = (char *)sts->host; + e.namelen = strlen(sts->host); + e.includeSubDomains = sts->includeSubDomains; + + if(sts->expires != TIME_T_MAX) { + result = Curl_gmtime((time_t)sts->expires, &stamp); + if(result) + return result; + + msnprintf(e.expire, sizeof(e.expire), "%d%02d%02d %02d:%02d:%02d", + stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday, + stamp.tm_hour, stamp.tm_min, stamp.tm_sec); + } + else + strcpy(e.expire, UNLIMITED); + + sc = data->set.hsts_write(data, &e, i, + data->set.hsts_write_userp); + *stop = (sc != CURLSTS_OK); + return sc == CURLSTS_FAIL ? CURLE_BAD_FUNCTION_ARGUMENT : CURLE_OK; +} + +/* + * Write this single hsts entry to a single output line + */ +static CURLcode hsts_out(struct stsentry *sts, FILE *fp) +{ + struct tm stamp; + if(sts->expires != TIME_T_MAX) { + CURLcode result = Curl_gmtime((time_t)sts->expires, &stamp); + if(result) + return result; + fprintf(fp, "%s%s \"%d%02d%02d %02d:%02d:%02d\"\n", + sts->includeSubDomains ? ".": "", sts->host, + stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday, + stamp.tm_hour, stamp.tm_min, stamp.tm_sec); + } + else + fprintf(fp, "%s%s \"%s\"\n", + sts->includeSubDomains ? ".": "", sts->host, UNLIMITED); + return CURLE_OK; +} + + +/* + * Curl_https_save() writes the HSTS cache to file and callback. + */ +CURLcode Curl_hsts_save(struct Curl_easy *data, struct hsts *h, + const char *file) +{ + struct Curl_llist_element *e; + struct Curl_llist_element *n; + CURLcode result = CURLE_OK; + FILE *out; + char *tempstore = NULL; + + if(!h) + /* no cache activated */ + return CURLE_OK; + + /* if no new name is given, use the one we stored from the load */ + if(!file && h->filename) + file = h->filename; + + if((h->flags & CURLHSTS_READONLYFILE) || !file || !file[0]) + /* marked as read-only, no file or zero length file name */ + goto skipsave; + + result = Curl_fopen(data, file, &out, &tempstore); + if(!result) { + fputs("# Your HSTS cache. https://curl.se/docs/hsts.html\n" + "# This file was generated by libcurl! Edit at your own risk.\n", + out); + for(e = h->list.head; e; e = n) { + struct stsentry *sts = e->ptr; + n = e->next; + result = hsts_out(sts, out); + if(result) + break; + } + fclose(out); + if(!result && tempstore && Curl_rename(tempstore, file)) + result = CURLE_WRITE_ERROR; + + if(result && tempstore) + unlink(tempstore); + } + free(tempstore); +skipsave: + if(data->set.hsts_write) { + /* if there's a write callback */ + struct curl_index i; /* count */ + i.total = h->list.size; + i.index = 0; + for(e = h->list.head; e; e = n) { + struct stsentry *sts = e->ptr; + bool stop; + n = e->next; + result = hsts_push(data, &i, sts, &stop); + if(result || stop) + break; + i.index++; + } + } + return result; +} + +/* only returns SERIOUS errors */ +static CURLcode hsts_add(struct hsts *h, char *line) +{ + /* Example lines: + example.com "20191231 10:00:00" + .example.net "20191231 10:00:00" + */ + char host[MAX_HSTS_HOSTLEN + 1]; + char date[MAX_HSTS_DATELEN + 1]; + int rc; + + rc = sscanf(line, + "%" MAX_HSTS_HOSTLENSTR "s \"%" MAX_HSTS_DATELENSTR "[^\"]\"", + host, date); + if(2 == rc) { + time_t expires = strcmp(date, UNLIMITED) ? Curl_getdate_capped(date) : + TIME_T_MAX; + CURLcode result = CURLE_OK; + char *p = host; + bool subdomain = FALSE; + struct stsentry *e; + if(p[0] == '.') { + p++; + subdomain = TRUE; + } + /* only add it if not already present */ + e = Curl_hsts(h, p, subdomain); + if(!e) + result = hsts_create(h, p, subdomain, expires); + else { + /* the same host name, use the largest expire time */ + if(expires > e->expires) + e->expires = expires; + } + if(result) + return result; + } + + return CURLE_OK; +} + +/* + * Load HSTS data from callback. + * + */ +static CURLcode hsts_pull(struct Curl_easy *data, struct hsts *h) +{ + /* if the HSTS read callback is set, use it */ + if(data->set.hsts_read) { + CURLSTScode sc; + DEBUGASSERT(h); + do { + char buffer[MAX_HSTS_HOSTLEN + 1]; + struct curl_hstsentry e; + e.name = buffer; + e.namelen = sizeof(buffer)-1; + e.includeSubDomains = FALSE; /* default */ + e.expire[0] = 0; + e.name[0] = 0; /* just to make it clean */ + sc = data->set.hsts_read(data, &e, data->set.hsts_read_userp); + if(sc == CURLSTS_OK) { + time_t expires; + CURLcode result; + DEBUGASSERT(e.name[0]); + if(!e.name[0]) + /* bail out if no name was stored */ + return CURLE_BAD_FUNCTION_ARGUMENT; + if(e.expire[0]) + expires = Curl_getdate_capped(e.expire); + else + expires = TIME_T_MAX; /* the end of time */ + result = hsts_create(h, e.name, + /* bitfield to bool conversion: */ + e.includeSubDomains ? TRUE : FALSE, + expires); + if(result) + return result; + } + else if(sc == CURLSTS_FAIL) + return CURLE_ABORTED_BY_CALLBACK; + } while(sc == CURLSTS_OK); + } + return CURLE_OK; +} + +/* + * Load the HSTS cache from the given file. The text based line-oriented file + * format is documented here: https://curl.se/docs/hsts.html + * + * This function only returns error on major problems that prevent hsts + * handling to work completely. It will ignore individual syntactical errors + * etc. + */ +static CURLcode hsts_load(struct hsts *h, const char *file) +{ + CURLcode result = CURLE_OK; + FILE *fp; + + /* we need a private copy of the file name so that the hsts cache file + name survives an easy handle reset */ + free(h->filename); + h->filename = strdup(file); + if(!h->filename) + return CURLE_OUT_OF_MEMORY; + + fp = fopen(file, FOPEN_READTEXT); + if(fp) { + struct dynbuf buf; + Curl_dyn_init(&buf, MAX_HSTS_LINE); + while(Curl_get_line(&buf, fp)) { + char *lineptr = Curl_dyn_ptr(&buf); + while(*lineptr && ISBLANK(*lineptr)) + lineptr++; + /* + * Skip empty or commented lines, since we know the line will have a + * trailing newline from Curl_get_line we can treat length 1 as empty. + */ + if((*lineptr == '#') || strlen(lineptr) <= 1) + continue; + + hsts_add(h, lineptr); + } + Curl_dyn_free(&buf); /* free the line buffer */ + fclose(fp); + } + return result; +} + +/* + * Curl_hsts_loadfile() loads HSTS from file + */ +CURLcode Curl_hsts_loadfile(struct Curl_easy *data, + struct hsts *h, const char *file) +{ + DEBUGASSERT(h); + (void)data; + return hsts_load(h, file); +} + +/* + * Curl_hsts_loadcb() loads HSTS from callback + */ +CURLcode Curl_hsts_loadcb(struct Curl_easy *data, struct hsts *h) +{ + if(h) + return hsts_pull(data, h); + return CURLE_OK; +} + +void Curl_hsts_loadfiles(struct Curl_easy *data) +{ + struct curl_slist *l = data->state.hstslist; + if(l) { + Curl_share_lock(data, CURL_LOCK_DATA_HSTS, CURL_LOCK_ACCESS_SINGLE); + + while(l) { + (void)Curl_hsts_loadfile(data, data->hsts, l->data); + l = l->next; + } + Curl_share_unlock(data, CURL_LOCK_DATA_HSTS); + } +} + +#endif /* CURL_DISABLE_HTTP || CURL_DISABLE_HSTS */ diff --git a/third_party/curl/lib/hsts.h b/third_party/curl/lib/hsts.h new file mode 100644 index 0000000..d3431a5 --- /dev/null +++ b/third_party/curl/lib/hsts.h @@ -0,0 +1,69 @@ +#ifndef HEADER_CURL_HSTS_H +#define HEADER_CURL_HSTS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HSTS) +#include +#include "llist.h" + +#ifdef DEBUGBUILD +extern time_t deltatime; +#endif + +struct stsentry { + struct Curl_llist_element node; + const char *host; + bool includeSubDomains; + curl_off_t expires; /* the timestamp of this entry's expiry */ +}; + +/* The HSTS cache. Needs to be able to tailmatch host names. */ +struct hsts { + struct Curl_llist list; + char *filename; + unsigned int flags; +}; + +struct hsts *Curl_hsts_init(void); +void Curl_hsts_cleanup(struct hsts **hp); +CURLcode Curl_hsts_parse(struct hsts *h, const char *hostname, + const char *sts); +struct stsentry *Curl_hsts(struct hsts *h, const char *hostname, + bool subdomain); +CURLcode Curl_hsts_save(struct Curl_easy *data, struct hsts *h, + const char *file); +CURLcode Curl_hsts_loadfile(struct Curl_easy *data, + struct hsts *h, const char *file); +CURLcode Curl_hsts_loadcb(struct Curl_easy *data, + struct hsts *h); +void Curl_hsts_loadfiles(struct Curl_easy *data); +#else +#define Curl_hsts_cleanup(x) +#define Curl_hsts_loadcb(x,y) CURLE_OK +#define Curl_hsts_save(x,y,z) +#define Curl_hsts_loadfiles(x) +#endif /* CURL_DISABLE_HTTP || CURL_DISABLE_HSTS */ +#endif /* HEADER_CURL_HSTS_H */ diff --git a/third_party/curl/lib/http.c b/third_party/curl/lib/http.c new file mode 100644 index 0000000..2a41f80 --- /dev/null +++ b/third_party/curl/lib/http.c @@ -0,0 +1,4516 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_HTTP + +#ifdef HAVE_NETINET_IN_H +#include +#endif + +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NET_IF_H +#include +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif + +#ifdef HAVE_SYS_PARAM_H +#include +#endif + +#ifdef USE_HYPER +#include +#endif + +#include "urldata.h" +#include +#include "transfer.h" +#include "sendf.h" +#include "formdata.h" +#include "mime.h" +#include "progress.h" +#include "curl_base64.h" +#include "cookie.h" +#include "vauth/vauth.h" +#include "vtls/vtls.h" +#include "vquic/vquic.h" +#include "http_digest.h" +#include "http_ntlm.h" +#include "http_negotiate.h" +#include "http_aws_sigv4.h" +#include "url.h" +#include "share.h" +#include "hostip.h" +#include "dynhds.h" +#include "http.h" +#include "headers.h" +#include "select.h" +#include "parsedate.h" /* for the week day and month names */ +#include "strtoofft.h" +#include "multiif.h" +#include "strcase.h" +#include "content_encoding.h" +#include "http_proxy.h" +#include "warnless.h" +#include "http2.h" +#include "cfilters.h" +#include "connect.h" +#include "strdup.h" +#include "altsvc.h" +#include "hsts.h" +#include "ws.h" +#include "c-hyper.h" +#include "curl_ctype.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Forward declarations. + */ + +static bool http_should_fail(struct Curl_easy *data, int httpcode); +static bool http_exp100_is_waiting(struct Curl_easy *data); +static CURLcode http_exp100_add_reader(struct Curl_easy *data); +static void http_exp100_send_anyway(struct Curl_easy *data); + +/* + * HTTP handler interface. + */ +const struct Curl_handler Curl_handler_http = { + "http", /* scheme */ + Curl_http_setup_conn, /* setup_connection */ + Curl_http, /* do_it */ + Curl_http_done, /* done */ + ZERO_NULL, /* do_more */ + Curl_http_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + Curl_http_getsock_do, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ZERO_NULL, /* disconnect */ + Curl_http_write_resp, /* write_resp */ + Curl_http_write_resp_hd, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_HTTP, /* defport */ + CURLPROTO_HTTP, /* protocol */ + CURLPROTO_HTTP, /* family */ + PROTOPT_CREDSPERREQUEST | /* flags */ + PROTOPT_USERPWDCTRL +}; + +#ifdef USE_SSL +/* + * HTTPS handler interface. + */ +const struct Curl_handler Curl_handler_https = { + "https", /* scheme */ + Curl_http_setup_conn, /* setup_connection */ + Curl_http, /* do_it */ + Curl_http_done, /* done */ + ZERO_NULL, /* do_more */ + Curl_http_connect, /* connect_it */ + NULL, /* connecting */ + ZERO_NULL, /* doing */ + NULL, /* proto_getsock */ + Curl_http_getsock_do, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ZERO_NULL, /* disconnect */ + Curl_http_write_resp, /* write_resp */ + Curl_http_write_resp_hd, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_HTTPS, /* defport */ + CURLPROTO_HTTPS, /* protocol */ + CURLPROTO_HTTP, /* family */ + PROTOPT_SSL | PROTOPT_CREDSPERREQUEST | PROTOPT_ALPN | /* flags */ + PROTOPT_USERPWDCTRL +}; + +#endif + +CURLcode Curl_http_setup_conn(struct Curl_easy *data, + struct connectdata *conn) +{ + /* allocate the HTTP-specific struct for the Curl_easy, only to survive + during this request */ + struct HTTP *http; + DEBUGASSERT(data->req.p.http == NULL); + + http = calloc(1, sizeof(struct HTTP)); + if(!http) + return CURLE_OUT_OF_MEMORY; + + data->req.p.http = http; + connkeep(conn, "HTTP default"); + + if(data->state.httpwant == CURL_HTTP_VERSION_3ONLY) { + CURLcode result = Curl_conn_may_http3(data, conn); + if(result) + return result; + } + + return CURLE_OK; +} + +#ifndef CURL_DISABLE_PROXY +/* + * checkProxyHeaders() checks the linked list of custom proxy headers + * if proxy headers are not available, then it will lookup into http header + * link list + * + * It takes a connectdata struct as input to see if this is a proxy request or + * not, as it then might check a different header list. Provide the header + * prefix without colon! + */ +char *Curl_checkProxyheaders(struct Curl_easy *data, + const struct connectdata *conn, + const char *thisheader, + const size_t thislen) +{ + struct curl_slist *head; + + for(head = (conn->bits.proxy && data->set.sep_headers) ? + data->set.proxyheaders : data->set.headers; + head; head = head->next) { + if(strncasecompare(head->data, thisheader, thislen) && + Curl_headersep(head->data[thislen])) + return head->data; + } + + return NULL; +} +#else +/* disabled */ +#define Curl_checkProxyheaders(x,y,z,a) NULL +#endif + +/* + * Strip off leading and trailing whitespace from the value in the + * given HTTP header line and return a strdupped copy. Returns NULL in + * case of allocation failure. Returns an empty string if the header value + * consists entirely of whitespace. + */ +char *Curl_copy_header_value(const char *header) +{ + const char *start; + const char *end; + size_t len; + + /* Find the end of the header name */ + while(*header && (*header != ':')) + ++header; + + if(*header) + /* Skip over colon */ + ++header; + + /* Find the first non-space letter */ + start = header; + while(*start && ISSPACE(*start)) + start++; + + end = strchr(start, '\r'); + if(!end) + end = strchr(start, '\n'); + if(!end) + end = strchr(start, '\0'); + if(!end) + return NULL; + + /* skip all trailing space letters */ + while((end > start) && ISSPACE(*end)) + end--; + + /* get length of the type */ + len = end - start + 1; + + return Curl_memdup0(start, len); +} + +#ifndef CURL_DISABLE_HTTP_AUTH + +#ifndef CURL_DISABLE_BASIC_AUTH +/* + * http_output_basic() sets up an Authorization: header (or the proxy version) + * for HTTP Basic authentication. + * + * Returns CURLcode. + */ +static CURLcode http_output_basic(struct Curl_easy *data, bool proxy) +{ + size_t size = 0; + char *authorization = NULL; + char **userp; + const char *user; + const char *pwd; + CURLcode result; + char *out; + + /* credentials are unique per transfer for HTTP, do not use the ones for the + connection */ + if(proxy) { +#ifndef CURL_DISABLE_PROXY + userp = &data->state.aptr.proxyuserpwd; + user = data->state.aptr.proxyuser; + pwd = data->state.aptr.proxypasswd; +#else + return CURLE_NOT_BUILT_IN; +#endif + } + else { + userp = &data->state.aptr.userpwd; + user = data->state.aptr.user; + pwd = data->state.aptr.passwd; + } + + out = aprintf("%s:%s", user ? user : "", pwd ? pwd : ""); + if(!out) + return CURLE_OUT_OF_MEMORY; + + result = Curl_base64_encode(out, strlen(out), &authorization, &size); + if(result) + goto fail; + + if(!authorization) { + result = CURLE_REMOTE_ACCESS_DENIED; + goto fail; + } + + free(*userp); + *userp = aprintf("%sAuthorization: Basic %s\r\n", + proxy ? "Proxy-" : "", + authorization); + free(authorization); + if(!*userp) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + +fail: + free(out); + return result; +} + +#endif + +#ifndef CURL_DISABLE_BEARER_AUTH +/* + * http_output_bearer() sets up an Authorization: header + * for HTTP Bearer authentication. + * + * Returns CURLcode. + */ +static CURLcode http_output_bearer(struct Curl_easy *data) +{ + char **userp; + CURLcode result = CURLE_OK; + + userp = &data->state.aptr.userpwd; + free(*userp); + *userp = aprintf("Authorization: Bearer %s\r\n", + data->set.str[STRING_BEARER]); + + if(!*userp) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + +fail: + return result; +} + +#endif + +#endif + +/* pickoneauth() selects the most favourable authentication method from the + * ones available and the ones we want. + * + * return TRUE if one was picked + */ +static bool pickoneauth(struct auth *pick, unsigned long mask) +{ + bool picked; + /* only deal with authentication we want */ + unsigned long avail = pick->avail & pick->want & mask; + picked = TRUE; + + /* The order of these checks is highly relevant, as this will be the order + of preference in case of the existence of multiple accepted types. */ + if(avail & CURLAUTH_NEGOTIATE) + pick->picked = CURLAUTH_NEGOTIATE; +#ifndef CURL_DISABLE_BEARER_AUTH + else if(avail & CURLAUTH_BEARER) + pick->picked = CURLAUTH_BEARER; +#endif +#ifndef CURL_DISABLE_DIGEST_AUTH + else if(avail & CURLAUTH_DIGEST) + pick->picked = CURLAUTH_DIGEST; +#endif + else if(avail & CURLAUTH_NTLM) + pick->picked = CURLAUTH_NTLM; +#ifndef CURL_DISABLE_BASIC_AUTH + else if(avail & CURLAUTH_BASIC) + pick->picked = CURLAUTH_BASIC; +#endif +#ifndef CURL_DISABLE_AWS + else if(avail & CURLAUTH_AWS_SIGV4) + pick->picked = CURLAUTH_AWS_SIGV4; +#endif + else { + pick->picked = CURLAUTH_PICKNONE; /* we select to use nothing */ + picked = FALSE; + } + pick->avail = CURLAUTH_NONE; /* clear it here */ + + return picked; +} + +/* + * http_perhapsrewind() + * + * The current request needs to be done again - maybe due to a follow + * or authentication negotiation. Check if: + * 1) a rewind of the data sent to the server is necessary + * 2) the current transfer should continue or be stopped early + */ +static CURLcode http_perhapsrewind(struct Curl_easy *data, + struct connectdata *conn) +{ + curl_off_t bytessent = data->req.writebytecount; + curl_off_t expectsend = Curl_creader_total_length(data); + curl_off_t upload_remain = (expectsend >= 0)? (expectsend - bytessent) : -1; + bool little_upload_remains = (upload_remain >= 0 && upload_remain < 2000); + bool needs_rewind = Curl_creader_needs_rewind(data); + /* By default, we'd like to abort the transfer when little or + * unknown amount remains. But this may be overridden by authentications + * further below! */ + bool abort_upload = (!data->req.upload_done && !little_upload_remains); + const char *ongoing_auth = NULL; + + /* We need a rewind before uploading client read data again. The + * checks below just influence of the upload is to be continued + * or aborted early. + * This depends on how much remains to be sent and in what state + * the authentication is. Some auth schemes such as NTLM do not work + * for a new connection. */ + if(needs_rewind) { + infof(data, "Need to rewind upload for next request"); + Curl_creader_set_rewind(data, TRUE); + } + + if(conn->bits.close) + /* If we already decided to close this connection, we cannot veto. */ + return CURLE_OK; + + if(abort_upload) { + /* We'd like to abort the upload - but should we? */ +#if defined(USE_NTLM) + if((data->state.authproxy.picked == CURLAUTH_NTLM) || + (data->state.authhost.picked == CURLAUTH_NTLM)) { + ongoing_auth = "NTML"; + if((conn->http_ntlm_state != NTLMSTATE_NONE) || + (conn->proxy_ntlm_state != NTLMSTATE_NONE)) { + /* The NTLM-negotiation has started, keep on sending. + * Need to do further work on same connection */ + abort_upload = FALSE; + } + } +#endif +#if defined(USE_SPNEGO) + /* There is still data left to send */ + if((data->state.authproxy.picked == CURLAUTH_NEGOTIATE) || + (data->state.authhost.picked == CURLAUTH_NEGOTIATE)) { + ongoing_auth = "NEGOTIATE"; + if((conn->http_negotiate_state != GSS_AUTHNONE) || + (conn->proxy_negotiate_state != GSS_AUTHNONE)) { + /* The NEGOTIATE-negotiation has started, keep on sending. + * Need to do further work on same connection */ + abort_upload = FALSE; + } + } +#endif + } + + if(abort_upload) { + if(upload_remain >= 0) + infof(data, "%s%sclose instead of sending %" + CURL_FORMAT_CURL_OFF_T " more bytes", + ongoing_auth? ongoing_auth : "", + ongoing_auth? " send, " : "", + upload_remain); + else + infof(data, "%s%sclose instead of sending unknown amount " + "of more bytes", + ongoing_auth? ongoing_auth : "", + ongoing_auth? " send, " : ""); + /* We decided to abort the ongoing transfer */ + streamclose(conn, "Mid-auth HTTP and much data left to send"); + /* FIXME: questionable manipulation here, can we do this differently? */ + data->req.size = 0; /* don't download any more than 0 bytes */ + } + return CURLE_OK; +} + +/* + * Curl_http_auth_act() gets called when all HTTP headers have been received + * and it checks what authentication methods that are available and decides + * which one (if any) to use. It will set 'newurl' if an auth method was + * picked. + */ + +CURLcode Curl_http_auth_act(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + bool pickhost = FALSE; + bool pickproxy = FALSE; + CURLcode result = CURLE_OK; + unsigned long authmask = ~0ul; + + if(!data->set.str[STRING_BEARER]) + authmask &= (unsigned long)~CURLAUTH_BEARER; + + if(100 <= data->req.httpcode && data->req.httpcode <= 199) + /* this is a transient response code, ignore */ + return CURLE_OK; + + if(data->state.authproblem) + return data->set.http_fail_on_error?CURLE_HTTP_RETURNED_ERROR:CURLE_OK; + + if((data->state.aptr.user || data->set.str[STRING_BEARER]) && + ((data->req.httpcode == 401) || + (data->req.authneg && data->req.httpcode < 300))) { + pickhost = pickoneauth(&data->state.authhost, authmask); + if(!pickhost) + data->state.authproblem = TRUE; + if(data->state.authhost.picked == CURLAUTH_NTLM && + conn->httpversion > 11) { + infof(data, "Forcing HTTP/1.1 for NTLM"); + connclose(conn, "Force HTTP/1.1 connection"); + data->state.httpwant = CURL_HTTP_VERSION_1_1; + } + } +#ifndef CURL_DISABLE_PROXY + if(conn->bits.proxy_user_passwd && + ((data->req.httpcode == 407) || + (data->req.authneg && data->req.httpcode < 300))) { + pickproxy = pickoneauth(&data->state.authproxy, + authmask & ~CURLAUTH_BEARER); + if(!pickproxy) + data->state.authproblem = TRUE; + } +#endif + + if(pickhost || pickproxy) { + result = http_perhapsrewind(data, conn); + if(result) + return result; + + /* In case this is GSS auth, the newurl field is already allocated so + we must make sure to free it before allocating a new one. As figured + out in bug #2284386 */ + Curl_safefree(data->req.newurl); + data->req.newurl = strdup(data->state.url); /* clone URL */ + if(!data->req.newurl) + return CURLE_OUT_OF_MEMORY; + } + else if((data->req.httpcode < 300) && + (!data->state.authhost.done) && + data->req.authneg) { + /* no (known) authentication available, + authentication is not "done" yet and + no authentication seems to be required and + we didn't try HEAD or GET */ + if((data->state.httpreq != HTTPREQ_GET) && + (data->state.httpreq != HTTPREQ_HEAD)) { + data->req.newurl = strdup(data->state.url); /* clone URL */ + if(!data->req.newurl) + return CURLE_OUT_OF_MEMORY; + data->state.authhost.done = TRUE; + } + } + if(http_should_fail(data, data->req.httpcode)) { + failf(data, "The requested URL returned error: %d", + data->req.httpcode); + result = CURLE_HTTP_RETURNED_ERROR; + } + + return result; +} + +#ifndef CURL_DISABLE_HTTP_AUTH +/* + * Output the correct authentication header depending on the auth type + * and whether or not it is to a proxy. + */ +static CURLcode +output_auth_headers(struct Curl_easy *data, + struct connectdata *conn, + struct auth *authstatus, + const char *request, + const char *path, + bool proxy) +{ + const char *auth = NULL; + CURLcode result = CURLE_OK; + (void)conn; + +#ifdef CURL_DISABLE_DIGEST_AUTH + (void)request; + (void)path; +#endif +#ifndef CURL_DISABLE_AWS + if(authstatus->picked == CURLAUTH_AWS_SIGV4) { + auth = "AWS_SIGV4"; + result = Curl_output_aws_sigv4(data, proxy); + if(result) + return result; + } + else +#endif +#ifdef USE_SPNEGO + if(authstatus->picked == CURLAUTH_NEGOTIATE) { + auth = "Negotiate"; + result = Curl_output_negotiate(data, conn, proxy); + if(result) + return result; + } + else +#endif +#ifdef USE_NTLM + if(authstatus->picked == CURLAUTH_NTLM) { + auth = "NTLM"; + result = Curl_output_ntlm(data, proxy); + if(result) + return result; + } + else +#endif +#ifndef CURL_DISABLE_DIGEST_AUTH + if(authstatus->picked == CURLAUTH_DIGEST) { + auth = "Digest"; + result = Curl_output_digest(data, + proxy, + (const unsigned char *)request, + (const unsigned char *)path); + if(result) + return result; + } + else +#endif +#ifndef CURL_DISABLE_BASIC_AUTH + if(authstatus->picked == CURLAUTH_BASIC) { + /* Basic */ + if( +#ifndef CURL_DISABLE_PROXY + (proxy && conn->bits.proxy_user_passwd && + !Curl_checkProxyheaders(data, conn, STRCONST("Proxy-authorization"))) || +#endif + (!proxy && data->state.aptr.user && + !Curl_checkheaders(data, STRCONST("Authorization")))) { + auth = "Basic"; + result = http_output_basic(data, proxy); + if(result) + return result; + } + + /* NOTE: this function should set 'done' TRUE, as the other auth + functions work that way */ + authstatus->done = TRUE; + } +#endif +#ifndef CURL_DISABLE_BEARER_AUTH + if(authstatus->picked == CURLAUTH_BEARER) { + /* Bearer */ + if((!proxy && data->set.str[STRING_BEARER] && + !Curl_checkheaders(data, STRCONST("Authorization")))) { + auth = "Bearer"; + result = http_output_bearer(data); + if(result) + return result; + } + + /* NOTE: this function should set 'done' TRUE, as the other auth + functions work that way */ + authstatus->done = TRUE; + } +#endif + + if(auth) { +#ifndef CURL_DISABLE_PROXY + infof(data, "%s auth using %s with user '%s'", + proxy ? "Proxy" : "Server", auth, + proxy ? (data->state.aptr.proxyuser ? + data->state.aptr.proxyuser : "") : + (data->state.aptr.user ? + data->state.aptr.user : "")); +#else + (void)proxy; + infof(data, "Server auth using %s with user '%s'", + auth, data->state.aptr.user ? + data->state.aptr.user : ""); +#endif + authstatus->multipass = (!authstatus->done) ? TRUE : FALSE; + } + else + authstatus->multipass = FALSE; + + return result; +} + +/** + * Curl_http_output_auth() setups the authentication headers for the + * host/proxy and the correct authentication + * method. data->state.authdone is set to TRUE when authentication is + * done. + * + * @param conn all information about the current connection + * @param request pointer to the request keyword + * @param path pointer to the requested path; should include query part + * @param proxytunnel boolean if this is the request setting up a "proxy + * tunnel" + * + * @returns CURLcode + */ +CURLcode +Curl_http_output_auth(struct Curl_easy *data, + struct connectdata *conn, + const char *request, + Curl_HttpReq httpreq, + const char *path, + bool proxytunnel) /* TRUE if this is the request setting + up the proxy tunnel */ +{ + CURLcode result = CURLE_OK; + struct auth *authhost; + struct auth *authproxy; + + DEBUGASSERT(data); + + authhost = &data->state.authhost; + authproxy = &data->state.authproxy; + + if( +#ifndef CURL_DISABLE_PROXY + (conn->bits.httpproxy && conn->bits.proxy_user_passwd) || +#endif + data->state.aptr.user || +#ifdef USE_SPNEGO + authhost->want & CURLAUTH_NEGOTIATE || + authproxy->want & CURLAUTH_NEGOTIATE || +#endif + data->set.str[STRING_BEARER]) + /* continue please */; + else { + authhost->done = TRUE; + authproxy->done = TRUE; + return CURLE_OK; /* no authentication with no user or password */ + } + + if(authhost->want && !authhost->picked) + /* The app has selected one or more methods, but none has been picked + so far by a server round-trip. Then we set the picked one to the + want one, and if this is one single bit it'll be used instantly. */ + authhost->picked = authhost->want; + + if(authproxy->want && !authproxy->picked) + /* The app has selected one or more methods, but none has been picked so + far by a proxy round-trip. Then we set the picked one to the want one, + and if this is one single bit it'll be used instantly. */ + authproxy->picked = authproxy->want; + +#ifndef CURL_DISABLE_PROXY + /* Send proxy authentication header if needed */ + if(conn->bits.httpproxy && + (conn->bits.tunnel_proxy == (bit)proxytunnel)) { + result = output_auth_headers(data, conn, authproxy, request, path, TRUE); + if(result) + return result; + } + else +#else + (void)proxytunnel; +#endif /* CURL_DISABLE_PROXY */ + /* we have no proxy so let's pretend we're done authenticating + with it */ + authproxy->done = TRUE; + + /* To prevent the user+password to get sent to other than the original host + due to a location-follow */ + if(Curl_auth_allowed_to_host(data) +#ifndef CURL_DISABLE_NETRC + || conn->bits.netrc +#endif + ) + result = output_auth_headers(data, conn, authhost, request, path, FALSE); + else + authhost->done = TRUE; + + if(((authhost->multipass && !authhost->done) || + (authproxy->multipass && !authproxy->done)) && + (httpreq != HTTPREQ_GET) && + (httpreq != HTTPREQ_HEAD)) { + /* Auth is required and we are not authenticated yet. Make a PUT or POST + with content-length zero as a "probe". */ + data->req.authneg = TRUE; + } + else + data->req.authneg = FALSE; + + return result; +} + +#else +/* when disabled */ +CURLcode +Curl_http_output_auth(struct Curl_easy *data, + struct connectdata *conn, + const char *request, + Curl_HttpReq httpreq, + const char *path, + bool proxytunnel) +{ + (void)data; + (void)conn; + (void)request; + (void)httpreq; + (void)path; + (void)proxytunnel; + return CURLE_OK; +} +#endif + +#if defined(USE_SPNEGO) || defined(USE_NTLM) || \ + !defined(CURL_DISABLE_DIGEST_AUTH) || \ + !defined(CURL_DISABLE_BASIC_AUTH) || \ + !defined(CURL_DISABLE_BEARER_AUTH) +static int is_valid_auth_separator(char ch) +{ + return ch == '\0' || ch == ',' || ISSPACE(ch); +} +#endif + +/* + * Curl_http_input_auth() deals with Proxy-Authenticate: and WWW-Authenticate: + * headers. They are dealt with both in the transfer.c main loop and in the + * proxy CONNECT loop. + */ +CURLcode Curl_http_input_auth(struct Curl_easy *data, bool proxy, + const char *auth) /* the first non-space */ +{ + /* + * This resource requires authentication + */ + struct connectdata *conn = data->conn; +#ifdef USE_SPNEGO + curlnegotiate *negstate = proxy ? &conn->proxy_negotiate_state : + &conn->http_negotiate_state; +#endif +#if defined(USE_SPNEGO) || \ + defined(USE_NTLM) || \ + !defined(CURL_DISABLE_DIGEST_AUTH) || \ + !defined(CURL_DISABLE_BASIC_AUTH) || \ + !defined(CURL_DISABLE_BEARER_AUTH) + + unsigned long *availp; + struct auth *authp; + + if(proxy) { + availp = &data->info.proxyauthavail; + authp = &data->state.authproxy; + } + else { + availp = &data->info.httpauthavail; + authp = &data->state.authhost; + } +#else + (void) proxy; +#endif + + (void) conn; /* In case conditionals make it unused. */ + + /* + * Here we check if we want the specific single authentication (using ==) and + * if we do, we initiate usage of it. + * + * If the provided authentication is wanted as one out of several accepted + * types (using &), we OR this authentication type to the authavail + * variable. + * + * Note: + * + * ->picked is first set to the 'want' value (one or more bits) before the + * request is sent, and then it is again set _after_ all response 401/407 + * headers have been received but then only to a single preferred method + * (bit). + */ + + while(*auth) { +#ifdef USE_SPNEGO + if(checkprefix("Negotiate", auth) && is_valid_auth_separator(auth[9])) { + if((authp->avail & CURLAUTH_NEGOTIATE) || + Curl_auth_is_spnego_supported()) { + *availp |= CURLAUTH_NEGOTIATE; + authp->avail |= CURLAUTH_NEGOTIATE; + + if(authp->picked == CURLAUTH_NEGOTIATE) { + CURLcode result = Curl_input_negotiate(data, conn, proxy, auth); + if(!result) { + free(data->req.newurl); + data->req.newurl = strdup(data->state.url); + if(!data->req.newurl) + return CURLE_OUT_OF_MEMORY; + data->state.authproblem = FALSE; + /* we received a GSS auth token and we dealt with it fine */ + *negstate = GSS_AUTHRECV; + } + else + data->state.authproblem = TRUE; + } + } + } + else +#endif +#ifdef USE_NTLM + /* NTLM support requires the SSL crypto libs */ + if(checkprefix("NTLM", auth) && is_valid_auth_separator(auth[4])) { + if((authp->avail & CURLAUTH_NTLM) || + Curl_auth_is_ntlm_supported()) { + *availp |= CURLAUTH_NTLM; + authp->avail |= CURLAUTH_NTLM; + + if(authp->picked == CURLAUTH_NTLM) { + /* NTLM authentication is picked and activated */ + CURLcode result = Curl_input_ntlm(data, proxy, auth); + if(!result) { + data->state.authproblem = FALSE; + } + else { + infof(data, "Authentication problem. Ignoring this."); + data->state.authproblem = TRUE; + } + } + } + } + else +#endif +#ifndef CURL_DISABLE_DIGEST_AUTH + if(checkprefix("Digest", auth) && is_valid_auth_separator(auth[6])) { + if((authp->avail & CURLAUTH_DIGEST) != 0) + infof(data, "Ignoring duplicate digest auth header."); + else if(Curl_auth_is_digest_supported()) { + CURLcode result; + + *availp |= CURLAUTH_DIGEST; + authp->avail |= CURLAUTH_DIGEST; + + /* We call this function on input Digest headers even if Digest + * authentication isn't activated yet, as we need to store the + * incoming data from this header in case we are going to use + * Digest */ + result = Curl_input_digest(data, proxy, auth); + if(result) { + infof(data, "Authentication problem. Ignoring this."); + data->state.authproblem = TRUE; + } + } + } + else +#endif +#ifndef CURL_DISABLE_BASIC_AUTH + if(checkprefix("Basic", auth) && + is_valid_auth_separator(auth[5])) { + *availp |= CURLAUTH_BASIC; + authp->avail |= CURLAUTH_BASIC; + if(authp->picked == CURLAUTH_BASIC) { + /* We asked for Basic authentication but got a 40X back + anyway, which basically means our name+password isn't + valid. */ + authp->avail = CURLAUTH_NONE; + infof(data, "Authentication problem. Ignoring this."); + data->state.authproblem = TRUE; + } + } + else +#endif +#ifndef CURL_DISABLE_BEARER_AUTH + if(checkprefix("Bearer", auth) && + is_valid_auth_separator(auth[6])) { + *availp |= CURLAUTH_BEARER; + authp->avail |= CURLAUTH_BEARER; + if(authp->picked == CURLAUTH_BEARER) { + /* We asked for Bearer authentication but got a 40X back + anyway, which basically means our token isn't valid. */ + authp->avail = CURLAUTH_NONE; + infof(data, "Authentication problem. Ignoring this."); + data->state.authproblem = TRUE; + } + } +#else + { + /* + * Empty block to terminate the if-else chain correctly. + * + * A semicolon would yield the same result here, but can cause a + * compiler warning when -Wextra is enabled. + */ + } +#endif + + /* there may be multiple methods on one line, so keep reading */ + while(*auth && *auth != ',') /* read up to the next comma */ + auth++; + if(*auth == ',') /* if we're on a comma, skip it */ + auth++; + while(*auth && ISSPACE(*auth)) + auth++; + } + + return CURLE_OK; +} + +/** + * http_should_fail() determines whether an HTTP response code has gotten us + * into an error state or not. + * + * @retval FALSE communications should continue + * + * @retval TRUE communications should not continue + */ +static bool http_should_fail(struct Curl_easy *data, int httpcode) +{ + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + + /* + ** If we haven't been asked to fail on error, + ** don't fail. + */ + if(!data->set.http_fail_on_error) + return FALSE; + + /* + ** Any code < 400 is never terminal. + */ + if(httpcode < 400) + return FALSE; + + /* + ** A 416 response to a resume request is presumably because the file is + ** already completely downloaded and thus not actually a fail. + */ + if(data->state.resume_from && data->state.httpreq == HTTPREQ_GET && + httpcode == 416) + return FALSE; + + /* + ** Any code >= 400 that's not 401 or 407 is always + ** a terminal error + */ + if((httpcode != 401) && (httpcode != 407)) + return TRUE; + + /* + ** All we have left to deal with is 401 and 407 + */ + DEBUGASSERT((httpcode == 401) || (httpcode == 407)); + + /* + ** Examine the current authentication state to see if this + ** is an error. The idea is for this function to get + ** called after processing all the headers in a response + ** message. So, if we've been to asked to authenticate a + ** particular stage, and we've done it, we're OK. But, if + ** we're already completely authenticated, it's not OK to + ** get another 401 or 407. + ** + ** It is possible for authentication to go stale such that + ** the client needs to reauthenticate. Once that info is + ** available, use it here. + */ + + /* + ** Either we're not authenticating, or we're supposed to + ** be authenticating something else. This is an error. + */ + if((httpcode == 401) && !data->state.aptr.user) + return TRUE; +#ifndef CURL_DISABLE_PROXY + if((httpcode == 407) && !data->conn->bits.proxy_user_passwd) + return TRUE; +#endif + + return data->state.authproblem; +} + +/* + * Curl_compareheader() + * + * Returns TRUE if 'headerline' contains the 'header' with given 'content'. + * Pass headers WITH the colon. + */ +bool +Curl_compareheader(const char *headerline, /* line to check */ + const char *header, /* header keyword _with_ colon */ + const size_t hlen, /* len of the keyword in bytes */ + const char *content, /* content string to find */ + const size_t clen) /* len of the content in bytes */ +{ + /* RFC2616, section 4.2 says: "Each header field consists of a name followed + * by a colon (":") and the field value. Field names are case-insensitive. + * The field value MAY be preceded by any amount of LWS, though a single SP + * is preferred." */ + + size_t len; + const char *start; + const char *end; + DEBUGASSERT(hlen); + DEBUGASSERT(clen); + DEBUGASSERT(header); + DEBUGASSERT(content); + + if(!strncasecompare(headerline, header, hlen)) + return FALSE; /* doesn't start with header */ + + /* pass the header */ + start = &headerline[hlen]; + + /* pass all whitespace */ + while(*start && ISSPACE(*start)) + start++; + + /* find the end of the header line */ + end = strchr(start, '\r'); /* lines end with CRLF */ + if(!end) { + /* in case there's a non-standard compliant line here */ + end = strchr(start, '\n'); + + if(!end) + /* hm, there's no line ending here, use the zero byte! */ + end = strchr(start, '\0'); + } + + len = end-start; /* length of the content part of the input line */ + + /* find the content string in the rest of the line */ + for(; len >= clen; len--, start++) { + if(strncasecompare(start, content, clen)) + return TRUE; /* match! */ + } + + return FALSE; /* no match */ +} + +/* + * Curl_http_connect() performs HTTP stuff to do at connect-time, called from + * the generic Curl_connect(). + */ +CURLcode Curl_http_connect(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + + /* We default to persistent connections. We set this already in this connect + function to make the reuse checks properly be able to check this bit. */ + connkeep(conn, "HTTP default"); + + return Curl_conn_connect(data, FIRSTSOCKET, FALSE, done); +} + +/* this returns the socket to wait for in the DO and DOING state for the multi + interface and then we're always _sending_ a request and thus we wait for + the single socket to become writable only */ +int Curl_http_getsock_do(struct Curl_easy *data, + struct connectdata *conn, + curl_socket_t *socks) +{ + /* write mode */ + (void)conn; + socks[0] = Curl_conn_get_socket(data, FIRSTSOCKET); + return GETSOCK_WRITESOCK(0); +} + +/* + * Curl_http_done() gets called after a single HTTP request has been + * performed. + */ + +CURLcode Curl_http_done(struct Curl_easy *data, + CURLcode status, bool premature) +{ + struct connectdata *conn = data->conn; + struct HTTP *http = data->req.p.http; + + /* Clear multipass flag. If authentication isn't done yet, then it will get + * a chance to be set back to true when we output the next auth header */ + data->state.authhost.multipass = FALSE; + data->state.authproxy.multipass = FALSE; + + if(!http) + return CURLE_OK; + + Curl_dyn_reset(&data->state.headerb); + Curl_hyper_done(data); + + if(status) + return status; + + if(!premature && /* this check is pointless when DONE is called before the + entire operation is complete */ + !conn->bits.retry && + !data->set.connect_only && + (data->req.bytecount + + data->req.headerbytecount - + data->req.deductheadercount) <= 0) { + /* If this connection isn't simply closed to be retried, AND nothing was + read from the HTTP server (that counts), this can't be right so we + return an error here */ + failf(data, "Empty reply from server"); + /* Mark it as closed to avoid the "left intact" message */ + streamclose(conn, "Empty reply from server"); + return CURLE_GOT_NOTHING; + } + + return CURLE_OK; +} + +/* + * Determine if we should use HTTP 1.1 (OR BETTER) for this request. Reasons + * to avoid it include: + * + * - if the user specifically requested HTTP 1.0 + * - if the server we are connected to only supports 1.0 + * - if any server previously contacted to handle this request only supports + * 1.0. + */ +bool Curl_use_http_1_1plus(const struct Curl_easy *data, + const struct connectdata *conn) +{ + if((data->state.httpversion == 10) || (conn->httpversion == 10)) + return FALSE; + if((data->state.httpwant == CURL_HTTP_VERSION_1_0) && + (conn->httpversion <= 10)) + return FALSE; + return ((data->state.httpwant == CURL_HTTP_VERSION_NONE) || + (data->state.httpwant >= CURL_HTTP_VERSION_1_1)); +} + +#ifndef USE_HYPER +static const char *get_http_string(const struct Curl_easy *data, + const struct connectdata *conn) +{ + if(Curl_conn_is_http3(data, conn, FIRSTSOCKET)) + return "3"; + if(Curl_conn_is_http2(data, conn, FIRSTSOCKET)) + return "2"; + if(Curl_use_http_1_1plus(data, conn)) + return "1.1"; + + return "1.0"; +} +#endif + +enum proxy_use { + HEADER_SERVER, /* direct to server */ + HEADER_PROXY, /* regular request to proxy */ + HEADER_CONNECT /* sending CONNECT to a proxy */ +}; + +static bool hd_name_eq(const char *n1, size_t n1len, + const char *n2, size_t n2len) +{ + if(n1len == n2len) { + return strncasecompare(n1, n2, n1len); + } + return FALSE; +} + +CURLcode Curl_dynhds_add_custom(struct Curl_easy *data, + bool is_connect, + struct dynhds *hds) +{ + struct connectdata *conn = data->conn; + char *ptr; + struct curl_slist *h[2]; + struct curl_slist *headers; + int numlists = 1; /* by default */ + int i; + +#ifndef CURL_DISABLE_PROXY + enum proxy_use proxy; + + if(is_connect) + proxy = HEADER_CONNECT; + else + proxy = conn->bits.httpproxy && !conn->bits.tunnel_proxy? + HEADER_PROXY:HEADER_SERVER; + + switch(proxy) { + case HEADER_SERVER: + h[0] = data->set.headers; + break; + case HEADER_PROXY: + h[0] = data->set.headers; + if(data->set.sep_headers) { + h[1] = data->set.proxyheaders; + numlists++; + } + break; + case HEADER_CONNECT: + if(data->set.sep_headers) + h[0] = data->set.proxyheaders; + else + h[0] = data->set.headers; + break; + } +#else + (void)is_connect; + h[0] = data->set.headers; +#endif + + /* loop through one or two lists */ + for(i = 0; i < numlists; i++) { + for(headers = h[i]; headers; headers = headers->next) { + const char *name, *value; + size_t namelen, valuelen; + + /* There are 2 quirks in place for custom headers: + * 1. setting only 'name:' to suppress a header from being sent + * 2. setting only 'name;' to send an empty (illegal) header + */ + ptr = strchr(headers->data, ':'); + if(ptr) { + name = headers->data; + namelen = ptr - headers->data; + ptr++; /* pass the colon */ + while(*ptr && ISSPACE(*ptr)) + ptr++; + if(*ptr) { + value = ptr; + valuelen = strlen(value); + } + else { + /* quirk #1, suppress this header */ + continue; + } + } + else { + ptr = strchr(headers->data, ';'); + + if(!ptr) { + /* neither : nor ; in provided header value. We seem + * to ignore this silently */ + continue; + } + + name = headers->data; + namelen = ptr - headers->data; + ptr++; /* pass the semicolon */ + while(*ptr && ISSPACE(*ptr)) + ptr++; + if(!*ptr) { + /* quirk #2, send an empty header */ + value = ""; + valuelen = 0; + } + else { + /* this may be used for something else in the future, + * ignore this for now */ + continue; + } + } + + DEBUGASSERT(name && value); + if(data->state.aptr.host && + /* a Host: header was sent already, don't pass on any custom Host: + header as that will produce *two* in the same request! */ + hd_name_eq(name, namelen, STRCONST("Host:"))) + ; + else if(data->state.httpreq == HTTPREQ_POST_FORM && + /* this header (extended by formdata.c) is sent later */ + hd_name_eq(name, namelen, STRCONST("Content-Type:"))) + ; + else if(data->state.httpreq == HTTPREQ_POST_MIME && + /* this header is sent later */ + hd_name_eq(name, namelen, STRCONST("Content-Type:"))) + ; + else if(data->req.authneg && + /* while doing auth neg, don't allow the custom length since + we will force length zero then */ + hd_name_eq(name, namelen, STRCONST("Content-Length:"))) + ; + else if(data->state.aptr.te && + /* when asking for Transfer-Encoding, don't pass on a custom + Connection: */ + hd_name_eq(name, namelen, STRCONST("Connection:"))) + ; + else if((conn->httpversion >= 20) && + hd_name_eq(name, namelen, STRCONST("Transfer-Encoding:"))) + /* HTTP/2 doesn't support chunked requests */ + ; + else if((hd_name_eq(name, namelen, STRCONST("Authorization:")) || + hd_name_eq(name, namelen, STRCONST("Cookie:"))) && + /* be careful of sending this potentially sensitive header to + other hosts */ + !Curl_auth_allowed_to_host(data)) + ; + else { + CURLcode result; + + result = Curl_dynhds_add(hds, name, namelen, value, valuelen); + if(result) + return result; + } + } + } + + return CURLE_OK; +} + +CURLcode Curl_add_custom_headers(struct Curl_easy *data, + bool is_connect, +#ifndef USE_HYPER + struct dynbuf *req +#else + void *req +#endif + ) +{ + struct connectdata *conn = data->conn; + char *ptr; + struct curl_slist *h[2]; + struct curl_slist *headers; + int numlists = 1; /* by default */ + int i; + +#ifndef CURL_DISABLE_PROXY + enum proxy_use proxy; + + if(is_connect) + proxy = HEADER_CONNECT; + else + proxy = conn->bits.httpproxy && !conn->bits.tunnel_proxy? + HEADER_PROXY:HEADER_SERVER; + + switch(proxy) { + case HEADER_SERVER: + h[0] = data->set.headers; + break; + case HEADER_PROXY: + h[0] = data->set.headers; + if(data->set.sep_headers) { + h[1] = data->set.proxyheaders; + numlists++; + } + break; + case HEADER_CONNECT: + if(data->set.sep_headers) + h[0] = data->set.proxyheaders; + else + h[0] = data->set.headers; + break; + } +#else + (void)is_connect; + h[0] = data->set.headers; +#endif + + /* loop through one or two lists */ + for(i = 0; i < numlists; i++) { + headers = h[i]; + + while(headers) { + char *semicolonp = NULL; + ptr = strchr(headers->data, ':'); + if(!ptr) { + char *optr; + /* no colon, semicolon? */ + ptr = strchr(headers->data, ';'); + if(ptr) { + optr = ptr; + ptr++; /* pass the semicolon */ + while(*ptr && ISSPACE(*ptr)) + ptr++; + + if(*ptr) { + /* this may be used for something else in the future */ + optr = NULL; + } + else { + if(*(--ptr) == ';') { + /* copy the source */ + semicolonp = strdup(headers->data); + if(!semicolonp) { +#ifndef USE_HYPER + Curl_dyn_free(req); +#endif + return CURLE_OUT_OF_MEMORY; + } + /* put a colon where the semicolon is */ + semicolonp[ptr - headers->data] = ':'; + /* point at the colon */ + optr = &semicolonp [ptr - headers->data]; + } + } + ptr = optr; + } + } + if(ptr && (ptr != headers->data)) { + /* we require a colon for this to be a true header */ + + ptr++; /* pass the colon */ + while(*ptr && ISSPACE(*ptr)) + ptr++; + + if(*ptr || semicolonp) { + /* only send this if the contents was non-blank or done special */ + CURLcode result = CURLE_OK; + char *compare = semicolonp ? semicolonp : headers->data; + + if(data->state.aptr.host && + /* a Host: header was sent already, don't pass on any custom Host: + header as that will produce *two* in the same request! */ + checkprefix("Host:", compare)) + ; + else if(data->state.httpreq == HTTPREQ_POST_FORM && + /* this header (extended by formdata.c) is sent later */ + checkprefix("Content-Type:", compare)) + ; + else if(data->state.httpreq == HTTPREQ_POST_MIME && + /* this header is sent later */ + checkprefix("Content-Type:", compare)) + ; + else if(data->req.authneg && + /* while doing auth neg, don't allow the custom length since + we will force length zero then */ + checkprefix("Content-Length:", compare)) + ; + else if(data->state.aptr.te && + /* when asking for Transfer-Encoding, don't pass on a custom + Connection: */ + checkprefix("Connection:", compare)) + ; + else if((conn->httpversion >= 20) && + checkprefix("Transfer-Encoding:", compare)) + /* HTTP/2 doesn't support chunked requests */ + ; + else if((checkprefix("Authorization:", compare) || + checkprefix("Cookie:", compare)) && + /* be careful of sending this potentially sensitive header to + other hosts */ + !Curl_auth_allowed_to_host(data)) + ; + else { +#ifdef USE_HYPER + result = Curl_hyper_header(data, req, compare); +#else + result = Curl_dyn_addf(req, "%s\r\n", compare); +#endif + } + if(semicolonp) + free(semicolonp); + if(result) + return result; + } + } + headers = headers->next; + } + } + + return CURLE_OK; +} + +#ifndef CURL_DISABLE_PARSEDATE +CURLcode Curl_add_timecondition(struct Curl_easy *data, +#ifndef USE_HYPER + struct dynbuf *req +#else + void *req +#endif + ) +{ + const struct tm *tm; + struct tm keeptime; + CURLcode result; + char datestr[80]; + const char *condp; + size_t len; + + if(data->set.timecondition == CURL_TIMECOND_NONE) + /* no condition was asked for */ + return CURLE_OK; + + result = Curl_gmtime(data->set.timevalue, &keeptime); + if(result) { + failf(data, "Invalid TIMEVALUE"); + return result; + } + tm = &keeptime; + + switch(data->set.timecondition) { + default: + DEBUGF(infof(data, "invalid time condition")); + return CURLE_BAD_FUNCTION_ARGUMENT; + + case CURL_TIMECOND_IFMODSINCE: + condp = "If-Modified-Since"; + len = 17; + break; + case CURL_TIMECOND_IFUNMODSINCE: + condp = "If-Unmodified-Since"; + len = 19; + break; + case CURL_TIMECOND_LASTMOD: + condp = "Last-Modified"; + len = 13; + break; + } + + if(Curl_checkheaders(data, condp, len)) { + /* A custom header was specified; it will be sent instead. */ + return CURLE_OK; + } + + /* The If-Modified-Since header family should have their times set in + * GMT as RFC2616 defines: "All HTTP date/time stamps MUST be + * represented in Greenwich Mean Time (GMT), without exception. For the + * purposes of HTTP, GMT is exactly equal to UTC (Coordinated Universal + * Time)." (see page 20 of RFC2616). + */ + + /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */ + msnprintf(datestr, sizeof(datestr), + "%s: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n", + condp, + Curl_wkday[tm->tm_wday?tm->tm_wday-1:6], + tm->tm_mday, + Curl_month[tm->tm_mon], + tm->tm_year + 1900, + tm->tm_hour, + tm->tm_min, + tm->tm_sec); + +#ifndef USE_HYPER + result = Curl_dyn_add(req, datestr); +#else + result = Curl_hyper_header(data, req, datestr); +#endif + + return result; +} +#else +/* disabled */ +CURLcode Curl_add_timecondition(struct Curl_easy *data, + struct dynbuf *req) +{ + (void)data; + (void)req; + return CURLE_OK; +} +#endif + +void Curl_http_method(struct Curl_easy *data, struct connectdata *conn, + const char **method, Curl_HttpReq *reqp) +{ + Curl_HttpReq httpreq = (Curl_HttpReq)data->state.httpreq; + const char *request; + if((conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_FTP)) && + data->state.upload) + httpreq = HTTPREQ_PUT; + + /* Now set the 'request' pointer to the proper request string */ + if(data->set.str[STRING_CUSTOMREQUEST]) + request = data->set.str[STRING_CUSTOMREQUEST]; + else { + if(data->req.no_body) + request = "HEAD"; + else { + DEBUGASSERT((httpreq >= HTTPREQ_GET) && (httpreq <= HTTPREQ_HEAD)); + switch(httpreq) { + case HTTPREQ_POST: + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + request = "POST"; + break; + case HTTPREQ_PUT: + request = "PUT"; + break; + default: /* this should never happen */ + case HTTPREQ_GET: + request = "GET"; + break; + case HTTPREQ_HEAD: + request = "HEAD"; + break; + } + } + } + *method = request; + *reqp = httpreq; +} + +CURLcode Curl_http_useragent(struct Curl_easy *data) +{ + /* The User-Agent string might have been allocated in url.c already, because + it might have been used in the proxy connect, but if we have got a header + with the user-agent string specified, we erase the previously made string + here. */ + if(Curl_checkheaders(data, STRCONST("User-Agent"))) { + free(data->state.aptr.uagent); + data->state.aptr.uagent = NULL; + } + return CURLE_OK; +} + + +CURLcode Curl_http_host(struct Curl_easy *data, struct connectdata *conn) +{ + const char *ptr; + struct dynamically_allocated_data *aptr = &data->state.aptr; + if(!data->state.this_is_a_follow) { + /* Free to avoid leaking memory on multiple requests */ + free(data->state.first_host); + + data->state.first_host = strdup(conn->host.name); + if(!data->state.first_host) + return CURLE_OUT_OF_MEMORY; + + data->state.first_remote_port = conn->remote_port; + data->state.first_remote_protocol = conn->handler->protocol; + } + Curl_safefree(aptr->host); + + ptr = Curl_checkheaders(data, STRCONST("Host")); + if(ptr && (!data->state.this_is_a_follow || + strcasecompare(data->state.first_host, conn->host.name))) { +#if !defined(CURL_DISABLE_COOKIES) + /* If we have a given custom Host: header, we extract the host name in + order to possibly use it for cookie reasons later on. We only allow the + custom Host: header if this is NOT a redirect, as setting Host: in the + redirected request is being out on thin ice. Except if the host name + is the same as the first one! */ + char *cookiehost = Curl_copy_header_value(ptr); + if(!cookiehost) + return CURLE_OUT_OF_MEMORY; + if(!*cookiehost) + /* ignore empty data */ + free(cookiehost); + else { + /* If the host begins with '[', we start searching for the port after + the bracket has been closed */ + if(*cookiehost == '[') { + char *closingbracket; + /* since the 'cookiehost' is an allocated memory area that will be + freed later we cannot simply increment the pointer */ + memmove(cookiehost, cookiehost + 1, strlen(cookiehost) - 1); + closingbracket = strchr(cookiehost, ']'); + if(closingbracket) + *closingbracket = 0; + } + else { + int startsearch = 0; + char *colon = strchr(cookiehost + startsearch, ':'); + if(colon) + *colon = 0; /* The host must not include an embedded port number */ + } + Curl_safefree(aptr->cookiehost); + aptr->cookiehost = cookiehost; + } +#endif + + if(!strcasecompare("Host:", ptr)) { + aptr->host = aprintf("Host:%s\r\n", &ptr[5]); + if(!aptr->host) + return CURLE_OUT_OF_MEMORY; + } + } + else { + /* When building Host: headers, we must put the host name within + [brackets] if the host name is a plain IPv6-address. RFC2732-style. */ + const char *host = conn->host.name; + + if(((conn->given->protocol&(CURLPROTO_HTTPS|CURLPROTO_WSS)) && + (conn->remote_port == PORT_HTTPS)) || + ((conn->given->protocol&(CURLPROTO_HTTP|CURLPROTO_WS)) && + (conn->remote_port == PORT_HTTP)) ) + /* if(HTTPS on port 443) OR (HTTP on port 80) then don't include + the port number in the host string */ + aptr->host = aprintf("Host: %s%s%s\r\n", conn->bits.ipv6_ip?"[":"", + host, conn->bits.ipv6_ip?"]":""); + else + aptr->host = aprintf("Host: %s%s%s:%d\r\n", conn->bits.ipv6_ip?"[":"", + host, conn->bits.ipv6_ip?"]":"", + conn->remote_port); + + if(!aptr->host) + /* without Host: we can't make a nice request */ + return CURLE_OUT_OF_MEMORY; + } + return CURLE_OK; +} + +/* + * Append the request-target to the HTTP request + */ +CURLcode Curl_http_target(struct Curl_easy *data, + struct connectdata *conn, + struct dynbuf *r) +{ + CURLcode result = CURLE_OK; + const char *path = data->state.up.path; + const char *query = data->state.up.query; + + if(data->set.str[STRING_TARGET]) { + path = data->set.str[STRING_TARGET]; + query = NULL; + } + +#ifndef CURL_DISABLE_PROXY + if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) { + /* Using a proxy but does not tunnel through it */ + + /* The path sent to the proxy is in fact the entire URL. But if the remote + host is a IDN-name, we must make sure that the request we produce only + uses the encoded host name! */ + + /* and no fragment part */ + CURLUcode uc; + char *url; + CURLU *h = curl_url_dup(data->state.uh); + if(!h) + return CURLE_OUT_OF_MEMORY; + + if(conn->host.dispname != conn->host.name) { + uc = curl_url_set(h, CURLUPART_HOST, conn->host.name, 0); + if(uc) { + curl_url_cleanup(h); + return CURLE_OUT_OF_MEMORY; + } + } + uc = curl_url_set(h, CURLUPART_FRAGMENT, NULL, 0); + if(uc) { + curl_url_cleanup(h); + return CURLE_OUT_OF_MEMORY; + } + + if(strcasecompare("http", data->state.up.scheme)) { + /* when getting HTTP, we don't want the userinfo the URL */ + uc = curl_url_set(h, CURLUPART_USER, NULL, 0); + if(uc) { + curl_url_cleanup(h); + return CURLE_OUT_OF_MEMORY; + } + uc = curl_url_set(h, CURLUPART_PASSWORD, NULL, 0); + if(uc) { + curl_url_cleanup(h); + return CURLE_OUT_OF_MEMORY; + } + } + /* Extract the URL to use in the request. */ + uc = curl_url_get(h, CURLUPART_URL, &url, CURLU_NO_DEFAULT_PORT); + if(uc) { + curl_url_cleanup(h); + return CURLE_OUT_OF_MEMORY; + } + + curl_url_cleanup(h); + + /* target or url */ + result = Curl_dyn_add(r, data->set.str[STRING_TARGET]? + data->set.str[STRING_TARGET]:url); + free(url); + if(result) + return (result); + + if(strcasecompare("ftp", data->state.up.scheme)) { + if(data->set.proxy_transfer_mode) { + /* when doing ftp, append ;type= if not present */ + char *type = strstr(path, ";type="); + if(type && type[6] && type[7] == 0) { + switch(Curl_raw_toupper(type[6])) { + case 'A': + case 'D': + case 'I': + break; + default: + type = NULL; + } + } + if(!type) { + result = Curl_dyn_addf(r, ";type=%c", + data->state.prefer_ascii ? 'a' : 'i'); + if(result) + return result; + } + } + } + } + + else +#else + (void)conn; /* not used in disabled-proxy builds */ +#endif + { + result = Curl_dyn_add(r, path); + if(result) + return result; + if(query) + result = Curl_dyn_addf(r, "?%s", query); + } + + return result; +} + +#if !defined(CURL_DISABLE_MIME) || !defined(CURL_DISABLE_FORM_API) +static CURLcode set_post_reader(struct Curl_easy *data, Curl_HttpReq httpreq) +{ + CURLcode result; + + switch(httpreq) { +#ifndef CURL_DISABLE_MIME + case HTTPREQ_POST_MIME: + data->state.mimepost = &data->set.mimepost; + break; +#endif +#ifndef CURL_DISABLE_FORM_API + case HTTPREQ_POST_FORM: + /* Convert the form structure into a mime structure, then keep + the conversion */ + if(!data->state.formp) { + data->state.formp = calloc(1, sizeof(curl_mimepart)); + if(!data->state.formp) + return CURLE_OUT_OF_MEMORY; + Curl_mime_cleanpart(data->state.formp); + result = Curl_getformdata(data, data->state.formp, data->set.httppost, + data->state.fread_func); + if(result) { + Curl_safefree(data->state.formp); + return result; + } + data->state.mimepost = data->state.formp; + } + break; +#endif + default: + data->state.mimepost = NULL; + break; + } + + switch(httpreq) { + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + /* This is form posting using mime data. */ +#ifndef CURL_DISABLE_MIME + if(data->state.mimepost) { + const char *cthdr = Curl_checkheaders(data, STRCONST("Content-Type")); + + /* Read and seek body only. */ + data->state.mimepost->flags |= MIME_BODY_ONLY; + + /* Prepare the mime structure headers & set content type. */ + + if(cthdr) + for(cthdr += 13; *cthdr == ' '; cthdr++) + ; + else if(data->state.mimepost->kind == MIMEKIND_MULTIPART) + cthdr = "multipart/form-data"; + + curl_mime_headers(data->state.mimepost, data->set.headers, 0); + result = Curl_mime_prepare_headers(data, data->state.mimepost, cthdr, + NULL, MIMESTRATEGY_FORM); + if(result) + return result; + curl_mime_headers(data->state.mimepost, NULL, 0); + result = Curl_creader_set_mime(data, data->state.mimepost); + if(result) + return result; + } + else +#endif + { + result = Curl_creader_set_null(data); + } + data->state.infilesize = Curl_creader_total_length(data); + return result; + + default: + return Curl_creader_set_null(data); + } + /* never reached */ +} +#endif + +static CURLcode set_reader(struct Curl_easy *data, Curl_HttpReq httpreq) +{ + CURLcode result = CURLE_OK; + curl_off_t postsize = data->state.infilesize; + + DEBUGASSERT(data->conn); + + if(data->req.authneg) { + return Curl_creader_set_null(data); + } + + switch(httpreq) { + case HTTPREQ_PUT: /* Let's PUT the data to the server! */ + if(!postsize) + result = Curl_creader_set_null(data); + else + result = Curl_creader_set_fread(data, postsize); + return result; + +#if !defined(CURL_DISABLE_MIME) || !defined(CURL_DISABLE_FORM_API) + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + return set_post_reader(data, httpreq); +#endif + + case HTTPREQ_POST: + /* this is the simple POST, using x-www-form-urlencoded style */ + /* the size of the post body */ + if(!postsize) { + result = Curl_creader_set_null(data); + } + else if(data->set.postfields) { + if(postsize > 0) + result = Curl_creader_set_buf(data, data->set.postfields, + (size_t)postsize); + else + result = Curl_creader_set_null(data); + } + else { + /* we read the bytes from the callback. In case "chunked" encoding + * is forced by the application, we disregard `postsize`. This is + * a backward compatibility decision to earlier versions where + * chunking disregarded this. See issue #13229. */ + bool chunked = FALSE; + char *ptr = Curl_checkheaders(data, STRCONST("Transfer-Encoding")); + if(ptr) { + /* Some kind of TE is requested, check if 'chunked' is chosen */ + chunked = Curl_compareheader(ptr, STRCONST("Transfer-Encoding:"), + STRCONST("chunked")); + } + result = Curl_creader_set_fread(data, chunked? -1 : postsize); + } + return result; + + default: + /* HTTP GET/HEAD download, has no body, needs no Content-Length */ + data->state.infilesize = 0; + return Curl_creader_set_null(data); + } + /* not reached */ +} + +static CURLcode http_resume(struct Curl_easy *data, Curl_HttpReq httpreq) +{ + if((HTTPREQ_POST == httpreq || HTTPREQ_PUT == httpreq) && + data->state.resume_from) { + /********************************************************************** + * Resuming upload in HTTP means that we PUT or POST and that we have + * got a resume_from value set. The resume value has already created + * a Range: header that will be passed along. We need to "fast forward" + * the file the given number of bytes and decrease the assume upload + * file size before we continue this venture in the dark lands of HTTP. + * Resuming mime/form posting at an offset > 0 has no sense and is ignored. + *********************************************************************/ + + if(data->state.resume_from < 0) { + /* + * This is meant to get the size of the present remote-file by itself. + * We don't support this now. Bail out! + */ + data->state.resume_from = 0; + } + + if(data->state.resume_from && !data->req.authneg) { + /* only act on the first request */ + CURLcode result; + result = Curl_creader_resume_from(data, data->state.resume_from); + if(result) { + failf(data, "Unable to resume from offset %" CURL_FORMAT_CURL_OFF_T, + data->state.resume_from); + return result; + } + } + } + return CURLE_OK; +} + +CURLcode Curl_http_req_set_reader(struct Curl_easy *data, + Curl_HttpReq httpreq, + const char **tep) +{ + CURLcode result = CURLE_OK; + const char *ptr; + + result = set_reader(data, httpreq); + if(result) + return result; + + result = http_resume(data, httpreq); + if(result) + return result; + + ptr = Curl_checkheaders(data, STRCONST("Transfer-Encoding")); + if(ptr) { + /* Some kind of TE is requested, check if 'chunked' is chosen */ + data->req.upload_chunky = + Curl_compareheader(ptr, + STRCONST("Transfer-Encoding:"), STRCONST("chunked")); + if(data->req.upload_chunky && + Curl_use_http_1_1plus(data, data->conn) && + (data->conn->httpversion >= 20)) { + infof(data, "suppressing chunked transfer encoding on connection " + "using HTTP version 2 or higher"); + data->req.upload_chunky = FALSE; + } + } + else { + curl_off_t req_clen = Curl_creader_total_length(data); + + if(req_clen < 0) { + /* indeterminate request content length */ + if(Curl_use_http_1_1plus(data, data->conn)) { + /* On HTTP/1.1, enable chunked, on HTTP/2 and later we do not + * need it */ + data->req.upload_chunky = (data->conn->httpversion < 20); + } + else { + failf(data, "Chunky upload is not supported by HTTP 1.0"); + return CURLE_UPLOAD_FAILED; + } + } + else { + /* else, no chunky upload */ + data->req.upload_chunky = FALSE; + } + + if(data->req.upload_chunky) + *tep = "Transfer-Encoding: chunked\r\n"; + } + return result; +} + +static CURLcode addexpect(struct Curl_easy *data, struct dynbuf *r, + bool *announced_exp100) +{ + CURLcode result; + char *ptr; + + *announced_exp100 = FALSE; + /* Avoid Expect: 100-continue if Upgrade: is used */ + if(data->req.upgr101 != UPGR101_INIT) + return CURLE_OK; + + /* For really small puts we don't use Expect: headers at all, and for + the somewhat bigger ones we allow the app to disable it. Just make + sure that the expect100header is always set to the preferred value + here. */ + ptr = Curl_checkheaders(data, STRCONST("Expect")); + if(ptr) { + *announced_exp100 = + Curl_compareheader(ptr, STRCONST("Expect:"), STRCONST("100-continue")); + } + else if(!data->state.disableexpect && + Curl_use_http_1_1plus(data, data->conn) && + (data->conn->httpversion < 20)) { + /* if not doing HTTP 1.0 or version 2, or disabled explicitly, we add an + Expect: 100-continue to the headers which actually speeds up post + operations (as there is one packet coming back from the web server) */ + curl_off_t client_len = Curl_creader_client_length(data); + if(client_len > EXPECT_100_THRESHOLD || client_len < 0) { + result = Curl_dyn_addn(r, STRCONST("Expect: 100-continue\r\n")); + if(result) + return result; + *announced_exp100 = TRUE; + } + } + return CURLE_OK; +} + +CURLcode Curl_http_req_complete(struct Curl_easy *data, + struct dynbuf *r, Curl_HttpReq httpreq) +{ + CURLcode result = CURLE_OK; + curl_off_t req_clen; + bool announced_exp100 = FALSE; + + DEBUGASSERT(data->conn); +#ifndef USE_HYPER + if(data->req.upload_chunky) { + result = Curl_httpchunk_add_reader(data); + if(result) + return result; + } +#endif + + /* Get the request body length that has been set up */ + req_clen = Curl_creader_total_length(data); + switch(httpreq) { + case HTTPREQ_PUT: + case HTTPREQ_POST: +#if !defined(CURL_DISABLE_MIME) || !defined(CURL_DISABLE_FORM_API) + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: +#endif + /* We only set Content-Length and allow a custom Content-Length if + we don't upload data chunked, as RFC2616 forbids us to set both + kinds of headers (Transfer-Encoding: chunked and Content-Length). + We do not override a custom "Content-Length" header, but during + authentication negotiation that header is suppressed. + */ + if(req_clen >= 0 && !data->req.upload_chunky && + (data->req.authneg || + !Curl_checkheaders(data, STRCONST("Content-Length")))) { + /* we allow replacing this header if not during auth negotiation, + although it isn't very wise to actually set your own */ + result = Curl_dyn_addf(r, + "Content-Length: %" CURL_FORMAT_CURL_OFF_T + "\r\n", req_clen); + } + if(result) + goto out; + +#ifndef CURL_DISABLE_MIME + /* Output mime-generated headers. */ + if(data->state.mimepost && + ((httpreq == HTTPREQ_POST_FORM) || (httpreq == HTTPREQ_POST_MIME))) { + struct curl_slist *hdr; + + for(hdr = data->state.mimepost->curlheaders; hdr; hdr = hdr->next) { + result = Curl_dyn_addf(r, "%s\r\n", hdr->data); + if(result) + goto out; + } + } +#endif + if(httpreq == HTTPREQ_POST) { + if(!Curl_checkheaders(data, STRCONST("Content-Type"))) { + result = Curl_dyn_addn(r, STRCONST("Content-Type: application/" + "x-www-form-urlencoded\r\n")); + if(result) + goto out; + } + } + result = addexpect(data, r, &announced_exp100); + if(result) + goto out; + break; + default: + break; + } + + /* end of headers */ + result = Curl_dyn_addn(r, STRCONST("\r\n")); + if(!result) { + Curl_pgrsSetUploadSize(data, req_clen); + if(announced_exp100) + result = http_exp100_add_reader(data); + } + +out: + if(!result) { + /* setup variables for the upcoming transfer */ + Curl_xfer_setup(data, FIRSTSOCKET, -1, TRUE, FIRSTSOCKET); + } + return result; +} + +#if !defined(CURL_DISABLE_COOKIES) + +CURLcode Curl_http_cookies(struct Curl_easy *data, + struct connectdata *conn, + struct dynbuf *r) +{ + CURLcode result = CURLE_OK; + char *addcookies = NULL; + bool linecap = FALSE; + if(data->set.str[STRING_COOKIE] && + !Curl_checkheaders(data, STRCONST("Cookie"))) + addcookies = data->set.str[STRING_COOKIE]; + + if(data->cookies || addcookies) { + struct Cookie *co = NULL; /* no cookies from start */ + int count = 0; + + if(data->cookies && data->state.cookie_engine) { + const char *host = data->state.aptr.cookiehost ? + data->state.aptr.cookiehost : conn->host.name; + const bool secure_context = + conn->handler->protocol&(CURLPROTO_HTTPS|CURLPROTO_WSS) || + strcasecompare("localhost", host) || + !strcmp(host, "127.0.0.1") || + !strcmp(host, "::1") ? TRUE : FALSE; + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + co = Curl_cookie_getlist(data, data->cookies, host, data->state.up.path, + secure_context); + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); + } + if(co) { + struct Cookie *store = co; + size_t clen = 8; /* hold the size of the generated Cookie: header */ + /* now loop through all cookies that matched */ + while(co) { + if(co->value) { + size_t add; + if(!count) { + result = Curl_dyn_addn(r, STRCONST("Cookie: ")); + if(result) + break; + } + add = strlen(co->name) + strlen(co->value) + 1; + if(clen + add >= MAX_COOKIE_HEADER_LEN) { + infof(data, "Restricted outgoing cookies due to header size, " + "'%s' not sent", co->name); + linecap = TRUE; + break; + } + result = Curl_dyn_addf(r, "%s%s=%s", count?"; ":"", + co->name, co->value); + if(result) + break; + clen += add + (count ? 2 : 0); + count++; + } + co = co->next; /* next cookie please */ + } + Curl_cookie_freelist(store); + } + if(addcookies && !result && !linecap) { + if(!count) + result = Curl_dyn_addn(r, STRCONST("Cookie: ")); + if(!result) { + result = Curl_dyn_addf(r, "%s%s", count?"; ":"", addcookies); + count++; + } + } + if(count && !result) + result = Curl_dyn_addn(r, STRCONST("\r\n")); + + if(result) + return result; + } + return result; +} +#endif + +CURLcode Curl_http_range(struct Curl_easy *data, + Curl_HttpReq httpreq) +{ + if(data->state.use_range) { + /* + * A range is selected. We use different headers whether we're downloading + * or uploading and we always let customized headers override our internal + * ones if any such are specified. + */ + if(((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) && + !Curl_checkheaders(data, STRCONST("Range"))) { + /* if a line like this was already allocated, free the previous one */ + free(data->state.aptr.rangeline); + data->state.aptr.rangeline = aprintf("Range: bytes=%s\r\n", + data->state.range); + } + else if((httpreq == HTTPREQ_POST || httpreq == HTTPREQ_PUT) && + !Curl_checkheaders(data, STRCONST("Content-Range"))) { + curl_off_t req_clen = Curl_creader_total_length(data); + /* if a line like this was already allocated, free the previous one */ + free(data->state.aptr.rangeline); + + if(data->set.set_resume_from < 0) { + /* Upload resume was asked for, but we don't know the size of the + remote part so we tell the server (and act accordingly) that we + upload the whole file (again) */ + data->state.aptr.rangeline = + aprintf("Content-Range: bytes 0-%" CURL_FORMAT_CURL_OFF_T + "/%" CURL_FORMAT_CURL_OFF_T "\r\n", + req_clen - 1, req_clen); + + } + else if(data->state.resume_from) { + /* This is because "resume" was selected */ + /* TODO: not sure if we want to send this header during authentication + * negotiation, but test1084 checks for it. In which case we have a + * "null" client reader installed that gives an unexpected length. */ + curl_off_t total_len = data->req.authneg? + data->state.infilesize : + (data->state.resume_from + req_clen); + data->state.aptr.rangeline = + aprintf("Content-Range: bytes %s%" CURL_FORMAT_CURL_OFF_T + "/%" CURL_FORMAT_CURL_OFF_T "\r\n", + data->state.range, total_len-1, total_len); + } + else { + /* Range was selected and then we just pass the incoming range and + append total size */ + data->state.aptr.rangeline = + aprintf("Content-Range: bytes %s/%" CURL_FORMAT_CURL_OFF_T "\r\n", + data->state.range, req_clen); + } + if(!data->state.aptr.rangeline) + return CURLE_OUT_OF_MEMORY; + } + } + return CURLE_OK; +} + +CURLcode Curl_http_firstwrite(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + struct SingleRequest *k = &data->req; + + if(data->req.newurl) { + if(conn->bits.close) { + /* Abort after the headers if "follow Location" is set + and we're set to close anyway. */ + k->keepon &= ~KEEP_RECV; + k->done = TRUE; + return CURLE_OK; + } + /* We have a new url to load, but since we want to be able to reuse this + connection properly, we read the full response in "ignore more" */ + k->ignorebody = TRUE; + infof(data, "Ignoring the response-body"); + } + if(data->state.resume_from && !k->content_range && + (data->state.httpreq == HTTPREQ_GET) && + !k->ignorebody) { + + if(k->size == data->state.resume_from) { + /* The resume point is at the end of file, consider this fine even if it + doesn't allow resume from here. */ + infof(data, "The entire document is already downloaded"); + streamclose(conn, "already downloaded"); + /* Abort download */ + k->keepon &= ~KEEP_RECV; + k->done = TRUE; + return CURLE_OK; + } + + /* we wanted to resume a download, although the server doesn't seem to + * support this and we did this with a GET (if it wasn't a GET we did a + * POST or PUT resume) */ + failf(data, "HTTP server doesn't seem to support " + "byte ranges. Cannot resume."); + return CURLE_RANGE_ERROR; + } + + if(data->set.timecondition && !data->state.range) { + /* A time condition has been set AND no ranges have been requested. This + seems to be what chapter 13.3.4 of RFC 2616 defines to be the correct + action for an HTTP/1.1 client */ + + if(!Curl_meets_timecondition(data, k->timeofdoc)) { + k->done = TRUE; + /* We're simulating an HTTP 304 from server so we return + what should have been returned from the server */ + data->info.httpcode = 304; + infof(data, "Simulate an HTTP 304 response"); + /* we abort the transfer before it is completed == we ruin the + reuse ability. Close the connection */ + streamclose(conn, "Simulated 304 handling"); + return CURLE_OK; + } + } /* we have a time condition */ + + return CURLE_OK; +} + +#ifdef HAVE_LIBZ +CURLcode Curl_transferencode(struct Curl_easy *data) +{ + if(!Curl_checkheaders(data, STRCONST("TE")) && + data->set.http_transfer_encoding) { + /* When we are to insert a TE: header in the request, we must also insert + TE in a Connection: header, so we need to merge the custom provided + Connection: header and prevent the original to get sent. Note that if + the user has inserted his/her own TE: header we don't do this magic + but then assume that the user will handle it all! */ + char *cptr = Curl_checkheaders(data, STRCONST("Connection")); +#define TE_HEADER "TE: gzip\r\n" + + Curl_safefree(data->state.aptr.te); + + if(cptr) { + cptr = Curl_copy_header_value(cptr); + if(!cptr) + return CURLE_OUT_OF_MEMORY; + } + + /* Create the (updated) Connection: header */ + data->state.aptr.te = aprintf("Connection: %s%sTE\r\n" TE_HEADER, + cptr ? cptr : "", (cptr && *cptr) ? ", ":""); + + free(cptr); + if(!data->state.aptr.te) + return CURLE_OUT_OF_MEMORY; + } + return CURLE_OK; +} +#endif + +#ifndef USE_HYPER +/* + * Curl_http() gets called from the generic multi_do() function when an HTTP + * request is to be performed. This creates and sends a properly constructed + * HTTP request. + */ +CURLcode Curl_http(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + Curl_HttpReq httpreq; + const char *te = ""; /* transfer-encoding */ + const char *request; + const char *httpstring; + struct dynbuf req; + char *altused = NULL; + const char *p_accept; /* Accept: string */ + + /* Always consider the DO phase done after this function call, even if there + may be parts of the request that are not yet sent, since we can deal with + the rest of the request in the PERFORM phase. */ + *done = TRUE; + + switch(conn->alpn) { + case CURL_HTTP_VERSION_3: + DEBUGASSERT(Curl_conn_is_http3(data, conn, FIRSTSOCKET)); + break; + case CURL_HTTP_VERSION_2: +#ifndef CURL_DISABLE_PROXY + if(!Curl_conn_is_http2(data, conn, FIRSTSOCKET) && + conn->bits.proxy && !conn->bits.tunnel_proxy + ) { + result = Curl_http2_switch(data, conn, FIRSTSOCKET); + if(result) + goto fail; + } + else +#endif + DEBUGASSERT(Curl_conn_is_http2(data, conn, FIRSTSOCKET)); + break; + case CURL_HTTP_VERSION_1_1: + /* continue with HTTP/1.x when explicitly requested */ + break; + default: + /* Check if user wants to use HTTP/2 with clear TCP */ + if(Curl_http2_may_switch(data, conn, FIRSTSOCKET)) { + DEBUGF(infof(data, "HTTP/2 over clean TCP")); + result = Curl_http2_switch(data, conn, FIRSTSOCKET); + if(result) + goto fail; + } + break; + } + + /* Add collecting of headers written to client. For a new connection, + * we might have done that already, but reuse + * or multiplex needs it here as well. */ + result = Curl_headers_init(data); + if(result) + goto fail; + + result = Curl_http_host(data, conn); + if(result) + goto fail; + + result = Curl_http_useragent(data); + if(result) + goto fail; + + Curl_http_method(data, conn, &request, &httpreq); + + /* setup the authentication headers */ + { + char *pq = NULL; + if(data->state.up.query) { + pq = aprintf("%s?%s", data->state.up.path, data->state.up.query); + if(!pq) + return CURLE_OUT_OF_MEMORY; + } + result = Curl_http_output_auth(data, conn, request, httpreq, + (pq ? pq : data->state.up.path), FALSE); + free(pq); + if(result) + goto fail; + } + + Curl_safefree(data->state.aptr.ref); + if(data->state.referer && !Curl_checkheaders(data, STRCONST("Referer"))) { + data->state.aptr.ref = aprintf("Referer: %s\r\n", data->state.referer); + if(!data->state.aptr.ref) + return CURLE_OUT_OF_MEMORY; + } + + if(!Curl_checkheaders(data, STRCONST("Accept-Encoding")) && + data->set.str[STRING_ENCODING]) { + Curl_safefree(data->state.aptr.accept_encoding); + data->state.aptr.accept_encoding = + aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]); + if(!data->state.aptr.accept_encoding) + return CURLE_OUT_OF_MEMORY; + } + else + Curl_safefree(data->state.aptr.accept_encoding); + +#ifdef HAVE_LIBZ + /* we only consider transfer-encoding magic if libz support is built-in */ + result = Curl_transferencode(data); + if(result) + goto fail; +#endif + + result = Curl_http_req_set_reader(data, httpreq, &te); + if(result) + goto fail; + + p_accept = Curl_checkheaders(data, + STRCONST("Accept"))?NULL:"Accept: */*\r\n"; + + result = Curl_http_range(data, httpreq); + if(result) + goto fail; + + httpstring = get_http_string(data, conn); + + /* initialize a dynamic send-buffer */ + Curl_dyn_init(&req, DYN_HTTP_REQUEST); + + /* make sure the header buffer is reset - if there are leftovers from a + previous transfer */ + Curl_dyn_reset(&data->state.headerb); + + /* add the main request stuff */ + /* GET/HEAD/POST/PUT */ + result = Curl_dyn_addf(&req, "%s ", request); + if(!result) + result = Curl_http_target(data, conn, &req); + if(result) { + Curl_dyn_free(&req); + goto fail; + } + +#ifndef CURL_DISABLE_ALTSVC + if(conn->bits.altused && !Curl_checkheaders(data, STRCONST("Alt-Used"))) { + altused = aprintf("Alt-Used: %s:%d\r\n", + conn->conn_to_host.name, conn->conn_to_port); + if(!altused) { + Curl_dyn_free(&req); + return CURLE_OUT_OF_MEMORY; + } + } +#endif + result = + Curl_dyn_addf(&req, + " HTTP/%s\r\n" /* HTTP version */ + "%s" /* host */ + "%s" /* proxyuserpwd */ + "%s" /* userpwd */ + "%s" /* range */ + "%s" /* user agent */ + "%s" /* accept */ + "%s" /* TE: */ + "%s" /* accept-encoding */ + "%s" /* referer */ + "%s" /* Proxy-Connection */ + "%s" /* transfer-encoding */ + "%s",/* Alt-Used */ + + httpstring, + (data->state.aptr.host?data->state.aptr.host:""), +#ifndef CURL_DISABLE_PROXY + data->state.aptr.proxyuserpwd? + data->state.aptr.proxyuserpwd:"", +#else + "", +#endif + data->state.aptr.userpwd?data->state.aptr.userpwd:"", + (data->state.use_range && data->state.aptr.rangeline)? + data->state.aptr.rangeline:"", + (data->set.str[STRING_USERAGENT] && + *data->set.str[STRING_USERAGENT] && + data->state.aptr.uagent)? + data->state.aptr.uagent:"", + p_accept?p_accept:"", + data->state.aptr.te?data->state.aptr.te:"", + (data->set.str[STRING_ENCODING] && + *data->set.str[STRING_ENCODING] && + data->state.aptr.accept_encoding)? + data->state.aptr.accept_encoding:"", + (data->state.referer && data->state.aptr.ref)? + data->state.aptr.ref:"" /* Referer: */, +#ifndef CURL_DISABLE_PROXY + (conn->bits.httpproxy && + !conn->bits.tunnel_proxy && + !Curl_checkheaders(data, STRCONST("Proxy-Connection")) && + !Curl_checkProxyheaders(data, + conn, + STRCONST("Proxy-Connection")))? + "Proxy-Connection: Keep-Alive\r\n":"", +#else + "", +#endif + te, + altused ? altused : "" + ); + + /* clear userpwd and proxyuserpwd to avoid reusing old credentials + * from reused connections */ + Curl_safefree(data->state.aptr.userpwd); +#ifndef CURL_DISABLE_PROXY + Curl_safefree(data->state.aptr.proxyuserpwd); +#endif + free(altused); + + if(result) { + Curl_dyn_free(&req); + goto fail; + } + + if(!(conn->handler->flags&PROTOPT_SSL) && + conn->httpversion < 20 && + (data->state.httpwant == CURL_HTTP_VERSION_2)) { + /* append HTTP2 upgrade magic stuff to the HTTP request if it isn't done + over SSL */ + result = Curl_http2_request_upgrade(&req, data); + if(result) { + Curl_dyn_free(&req); + return result; + } + } + + result = Curl_http_cookies(data, conn, &req); +#ifdef USE_WEBSOCKETS + if(!result && conn->handler->protocol&(CURLPROTO_WS|CURLPROTO_WSS)) + result = Curl_ws_request(data, &req); +#endif + if(!result) + result = Curl_add_timecondition(data, &req); + if(!result) + result = Curl_add_custom_headers(data, FALSE, &req); + + if(!result) { + /* req_send takes ownership of the 'req' memory on success */ + result = Curl_http_req_complete(data, &req, httpreq); + if(!result) + result = Curl_req_send(data, &req); + } + Curl_dyn_free(&req); + if(result) + goto fail; + + if((conn->httpversion >= 20) && data->req.upload_chunky) + /* upload_chunky was set above to set up the request in a chunky fashion, + but is disabled here again to avoid that the chunked encoded version is + actually used when sending the request body over h2 */ + data->req.upload_chunky = FALSE; +fail: + if(CURLE_TOO_LARGE == result) + failf(data, "HTTP request too large"); + return result; +} + +#endif /* USE_HYPER */ + +typedef enum { + STATUS_UNKNOWN, /* not enough data to tell yet */ + STATUS_DONE, /* a status line was read */ + STATUS_BAD /* not a status line */ +} statusline; + + +/* Check a string for a prefix. Check no more than 'len' bytes */ +static bool checkprefixmax(const char *prefix, const char *buffer, size_t len) +{ + size_t ch = CURLMIN(strlen(prefix), len); + return curl_strnequal(prefix, buffer, ch); +} + +/* + * checkhttpprefix() + * + * Returns TRUE if member of the list matches prefix of string + */ +static statusline +checkhttpprefix(struct Curl_easy *data, + const char *s, size_t len) +{ + struct curl_slist *head = data->set.http200aliases; + statusline rc = STATUS_BAD; + statusline onmatch = len >= 5? STATUS_DONE : STATUS_UNKNOWN; + + while(head) { + if(checkprefixmax(head->data, s, len)) { + rc = onmatch; + break; + } + head = head->next; + } + + if((rc != STATUS_DONE) && (checkprefixmax("HTTP/", s, len))) + rc = onmatch; + + return rc; +} + +#ifndef CURL_DISABLE_RTSP +static statusline +checkrtspprefix(struct Curl_easy *data, + const char *s, size_t len) +{ + statusline result = STATUS_BAD; + statusline onmatch = len >= 5? STATUS_DONE : STATUS_UNKNOWN; + (void)data; /* unused */ + if(checkprefixmax("RTSP/", s, len)) + result = onmatch; + + return result; +} +#endif /* CURL_DISABLE_RTSP */ + +static statusline +checkprotoprefix(struct Curl_easy *data, struct connectdata *conn, + const char *s, size_t len) +{ +#ifndef CURL_DISABLE_RTSP + if(conn->handler->protocol & CURLPROTO_RTSP) + return checkrtspprefix(data, s, len); +#else + (void)conn; +#endif /* CURL_DISABLE_RTSP */ + + return checkhttpprefix(data, s, len); +} + +/* HTTP header has field name `n` (a string constant) */ +#define HD_IS(hd, hdlen, n) \ + (((hdlen) >= (sizeof(n)-1)) && curl_strnequal((n), (hd), (sizeof(n)-1))) + +#define HD_VAL(hd, hdlen, n) \ + ((((hdlen) >= (sizeof(n)-1)) && \ + curl_strnequal((n), (hd), (sizeof(n)-1)))? (hd + (sizeof(n)-1)) : NULL) + +/* HTTP header has field name `n` (a string constant) and contains `v` + * (a string constant) in its value(s) */ +#define HD_IS_AND_SAYS(hd, hdlen, n, v) \ + (HD_IS(hd, hdlen, n) && \ + ((hdlen) > ((sizeof(n)-1) + (sizeof(v)-1))) && \ + Curl_compareheader(hd, STRCONST(n), STRCONST(v))) + +/* + * Curl_http_header() parses a single response header. + */ +CURLcode Curl_http_header(struct Curl_easy *data, + const char *hd, size_t hdlen) +{ + struct connectdata *conn = data->conn; + CURLcode result; + struct SingleRequest *k = &data->req; + const char *v; + + switch(hd[0]) { + case 'a': + case 'A': +#ifndef CURL_DISABLE_ALTSVC + v = (data->asi && + ((data->conn->handler->flags & PROTOPT_SSL) || +#ifdef CURLDEBUG + /* allow debug builds to circumvent the HTTPS restriction */ + getenv("CURL_ALTSVC_HTTP") +#else + 0 +#endif + ))? HD_VAL(hd, hdlen, "Alt-Svc:") : NULL; + if(v) { + /* the ALPN of the current request */ + enum alpnid id = (conn->httpversion == 30)? ALPN_h3 : + (conn->httpversion == 20) ? ALPN_h2 : ALPN_h1; + return Curl_altsvc_parse(data, data->asi, v, id, conn->host.name, + curlx_uitous((unsigned int)conn->remote_port)); + } +#endif + break; + case 'c': + case 'C': + /* Check for Content-Length: header lines to get size */ + v = (!k->http_bodyless && !data->set.ignorecl)? + HD_VAL(hd, hdlen, "Content-Length:") : NULL; + if(v) { + curl_off_t contentlength; + CURLofft offt = curlx_strtoofft(v, NULL, 10, &contentlength); + + if(offt == CURL_OFFT_OK) { + k->size = contentlength; + k->maxdownload = k->size; + } + else if(offt == CURL_OFFT_FLOW) { + /* out of range */ + if(data->set.max_filesize) { + failf(data, "Maximum file size exceeded"); + return CURLE_FILESIZE_EXCEEDED; + } + streamclose(conn, "overflow content-length"); + infof(data, "Overflow Content-Length: value"); + } + else { + /* negative or just rubbish - bad HTTP */ + failf(data, "Invalid Content-Length: value"); + return CURLE_WEIRD_SERVER_REPLY; + } + return CURLE_OK; + } + v = (!k->http_bodyless && data->set.str[STRING_ENCODING])? + HD_VAL(hd, hdlen, "Content-Encoding:") : NULL; + if(v) { + /* + * Process Content-Encoding. Look for the values: identity, + * gzip, deflate, compress, x-gzip and x-compress. x-gzip and + * x-compress are the same as gzip and compress. (Sec 3.5 RFC + * 2616). zlib cannot handle compress. However, errors are + * handled further down when the response body is processed + */ + return Curl_build_unencoding_stack(data, v, FALSE); + } + /* check for Content-Type: header lines to get the MIME-type */ + v = HD_VAL(hd, hdlen, "Content-Type:"); + if(v) { + char *contenttype = Curl_copy_header_value(hd); + if(!contenttype) + return CURLE_OUT_OF_MEMORY; + if(!*contenttype) + /* ignore empty data */ + free(contenttype); + else { + Curl_safefree(data->info.contenttype); + data->info.contenttype = contenttype; + } + return CURLE_OK; + } + if(HD_IS_AND_SAYS(hd, hdlen, "Connection:", "close")) { + /* + * [RFC 2616, section 8.1.2.1] + * "Connection: close" is HTTP/1.1 language and means that + * the connection will close when this request has been + * served. + */ + streamclose(conn, "Connection: close used"); + return CURLE_OK; + } + if((conn->httpversion == 10) && + HD_IS_AND_SAYS(hd, hdlen, "Connection:", "keep-alive")) { + /* + * An HTTP/1.0 reply with the 'Connection: keep-alive' line + * tells us the connection will be kept alive for our + * pleasure. Default action for 1.0 is to close. + * + * [RFC2068, section 19.7.1] */ + connkeep(conn, "Connection keep-alive"); + infof(data, "HTTP/1.0 connection set to keep alive"); + return CURLE_OK; + } + v = !k->http_bodyless? HD_VAL(hd, hdlen, "Content-Range:") : NULL; + if(v) { + /* Content-Range: bytes [num]- + Content-Range: bytes: [num]- + Content-Range: [num]- + Content-Range: [asterisk]/[total] + + The second format was added since Sun's webserver + JavaWebServer/1.1.1 obviously sends the header this way! + The third added since some servers use that! + The fourth means the requested range was unsatisfied. + */ + + const char *ptr = v; + + /* Move forward until first digit or asterisk */ + while(*ptr && !ISDIGIT(*ptr) && *ptr != '*') + ptr++; + + /* if it truly stopped on a digit */ + if(ISDIGIT(*ptr)) { + if(!curlx_strtoofft(ptr, NULL, 10, &k->offset)) { + if(data->state.resume_from == k->offset) + /* we asked for a resume and we got it */ + k->content_range = TRUE; + } + } + else if(k->httpcode < 300) + data->state.resume_from = 0; /* get everything */ + } + break; + case 'l': + case 'L': + v = (!k->http_bodyless && + (data->set.timecondition || data->set.get_filetime))? + HD_VAL(hd, hdlen, "Last-Modified:") : NULL; + if(v) { + k->timeofdoc = Curl_getdate_capped(v); + if(data->set.get_filetime) + data->info.filetime = k->timeofdoc; + return CURLE_OK; + } + if((k->httpcode >= 300 && k->httpcode < 400) && + HD_IS(hd, hdlen, "Location:") && + !data->req.location) { + /* this is the URL that the server advises us to use instead */ + char *location = Curl_copy_header_value(hd); + if(!location) + return CURLE_OUT_OF_MEMORY; + if(!*location) + /* ignore empty data */ + free(location); + else { + data->req.location = location; + + if(data->set.http_follow_location) { + DEBUGASSERT(!data->req.newurl); + data->req.newurl = strdup(data->req.location); /* clone */ + if(!data->req.newurl) + return CURLE_OUT_OF_MEMORY; + + /* some cases of POST and PUT etc needs to rewind the data + stream at this point */ + result = http_perhapsrewind(data, conn); + if(result) + return result; + + /* mark the next request as a followed location: */ + data->state.this_is_a_follow = TRUE; + } + } + } + break; + case 'p': + case 'P': +#ifndef CURL_DISABLE_PROXY + v = HD_VAL(hd, hdlen, "Proxy-Connection:"); + if(v) { + if((conn->httpversion == 10) && conn->bits.httpproxy && + HD_IS_AND_SAYS(hd, hdlen, "Proxy-Connection:", "keep-alive")) { + /* + * When an HTTP/1.0 reply comes when using a proxy, the + * 'Proxy-Connection: keep-alive' line tells us the + * connection will be kept alive for our pleasure. + * Default action for 1.0 is to close. + */ + connkeep(conn, "Proxy-Connection keep-alive"); /* don't close */ + infof(data, "HTTP/1.0 proxy connection set to keep alive"); + } + else if((conn->httpversion == 11) && conn->bits.httpproxy && + HD_IS_AND_SAYS(hd, hdlen, "Proxy-Connection:", "close")) { + /* + * We get an HTTP/1.1 response from a proxy and it says it'll + * close down after this transfer. + */ + connclose(conn, "Proxy-Connection: asked to close after done"); + infof(data, "HTTP/1.1 proxy connection set close"); + } + return CURLE_OK; + } +#endif + if((407 == k->httpcode) && HD_IS(hd, hdlen, "Proxy-authenticate:")) { + char *auth = Curl_copy_header_value(hd); + if(!auth) + return CURLE_OUT_OF_MEMORY; + result = Curl_http_input_auth(data, TRUE, auth); + free(auth); + return result; + } +#ifdef USE_SPNEGO + if(HD_IS(hd, hdlen, "Persistent-Auth:")) { + struct negotiatedata *negdata = &conn->negotiate; + struct auth *authp = &data->state.authhost; + if(authp->picked == CURLAUTH_NEGOTIATE) { + char *persistentauth = Curl_copy_header_value(hd); + if(!persistentauth) + return CURLE_OUT_OF_MEMORY; + negdata->noauthpersist = checkprefix("false", persistentauth)? + TRUE:FALSE; + negdata->havenoauthpersist = TRUE; + infof(data, "Negotiate: noauthpersist -> %d, header part: %s", + negdata->noauthpersist, persistentauth); + free(persistentauth); + } + } +#endif + break; + case 'r': + case 'R': + v = HD_VAL(hd, hdlen, "Retry-After:"); + if(v) { + /* Retry-After = HTTP-date / delay-seconds */ + curl_off_t retry_after = 0; /* zero for unknown or "now" */ + /* Try it as a decimal number, if it works it is not a date */ + (void)curlx_strtoofft(v, NULL, 10, &retry_after); + if(!retry_after) { + time_t date = Curl_getdate_capped(v); + if(-1 != date) + /* convert date to number of seconds into the future */ + retry_after = date - time(NULL); + } + data->info.retry_after = retry_after; /* store it */ + return CURLE_OK; + } + break; + case 's': + case 'S': +#if !defined(CURL_DISABLE_COOKIES) + v = (data->cookies && data->state.cookie_engine)? + HD_VAL(hd, hdlen, "Set-Cookie:") : NULL; + if(v) { + /* If there is a custom-set Host: name, use it here, or else use + * real peer host name. */ + const char *host = data->state.aptr.cookiehost? + data->state.aptr.cookiehost:conn->host.name; + const bool secure_context = + conn->handler->protocol&(CURLPROTO_HTTPS|CURLPROTO_WSS) || + strcasecompare("localhost", host) || + !strcmp(host, "127.0.0.1") || + !strcmp(host, "::1") ? TRUE : FALSE; + + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, + CURL_LOCK_ACCESS_SINGLE); + Curl_cookie_add(data, data->cookies, TRUE, FALSE, v, host, + data->state.up.path, secure_context); + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); + return CURLE_OK; + } +#endif +#ifndef CURL_DISABLE_HSTS + /* If enabled, the header is incoming and this is over HTTPS */ + v = (data->hsts && + ((conn->handler->flags & PROTOPT_SSL) || +#ifdef CURLDEBUG + /* allow debug builds to circumvent the HTTPS restriction */ + getenv("CURL_HSTS_HTTP") +#else + 0 +#endif + ) + )? HD_VAL(hd, hdlen, "Strict-Transport-Security:") : NULL; + if(v) { + CURLcode check = + Curl_hsts_parse(data->hsts, conn->host.name, v); + if(check) + infof(data, "Illegal STS header skipped"); +#ifdef DEBUGBUILD + else + infof(data, "Parsed STS header fine (%zu entries)", + data->hsts->list.size); +#endif + } +#endif + break; + case 't': + case 'T': + /* RFC 9112, ch. 6.1 + * "Transfer-Encoding MAY be sent in a response to a HEAD request or + * in a 304 (Not Modified) response (Section 15.4.5 of [HTTP]) to a + * GET request, neither of which includes a message body, to indicate + * that the origin server would have applied a transfer coding to the + * message body if the request had been an unconditional GET." + * + * Read: in these cases the 'Transfer-Encoding' does not apply + * to any data following the response headers. Do not add any decoders. + */ + v = (!k->http_bodyless && + (data->state.httpreq != HTTPREQ_HEAD) && + (k->httpcode != 304))? + HD_VAL(hd, hdlen, "Transfer-Encoding:") : NULL; + if(v) { + /* One or more encodings. We check for chunked and/or a compression + algorithm. */ + result = Curl_build_unencoding_stack(data, v, TRUE); + if(result) + return result; + if(!k->chunk && data->set.http_transfer_encoding) { + /* if this isn't chunked, only close can signal the end of this + * transfer as Content-Length is said not to be trusted for + * transfer-encoding! */ + connclose(conn, "HTTP/1.1 transfer-encoding without chunks"); + k->ignore_cl = TRUE; + } + return CURLE_OK; + } + break; + case 'w': + case 'W': + if((401 == k->httpcode) && HD_IS(hd, hdlen, "WWW-Authenticate:")) { + char *auth = Curl_copy_header_value(hd); + if(!auth) + return CURLE_OUT_OF_MEMORY; + result = Curl_http_input_auth(data, FALSE, auth); + free(auth); + return result; + } + break; + } + + if(conn->handler->protocol & CURLPROTO_RTSP) { + result = Curl_rtsp_parseheader(data, hd); + if(result) + return result; + } + return CURLE_OK; +} + +/* + * Called after the first HTTP response line (the status line) has been + * received and parsed. + */ +CURLcode Curl_http_statusline(struct Curl_easy *data, + struct connectdata *conn) +{ + struct SingleRequest *k = &data->req; + + switch(k->httpversion) { + case 10: + case 11: +#ifdef USE_HTTP2 + case 20: +#endif +#ifdef USE_HTTP3 + case 30: +#endif + /* no major version switch mid-connection */ + if(conn->httpversion && + (k->httpversion/10 != conn->httpversion/10)) { + failf(data, "Version mismatch (from HTTP/%u to HTTP/%u)", + conn->httpversion/10, k->httpversion/10); + return CURLE_UNSUPPORTED_PROTOCOL; + } + break; + default: + failf(data, "Unsupported HTTP version (%u.%d) in response", + k->httpversion/10, k->httpversion%10); + return CURLE_UNSUPPORTED_PROTOCOL; + } + + data->info.httpcode = k->httpcode; + data->info.httpversion = k->httpversion; + conn->httpversion = (unsigned char)k->httpversion; + + if(!data->state.httpversion || data->state.httpversion > k->httpversion) + /* store the lowest server version we encounter */ + data->state.httpversion = (unsigned char)k->httpversion; + + /* + * This code executes as part of processing the header. As a + * result, it's not totally clear how to interpret the + * response code yet as that depends on what other headers may + * be present. 401 and 407 may be errors, but may be OK + * depending on how authentication is working. Other codes + * are definitely errors, so give up here. + */ + if(data->state.resume_from && data->state.httpreq == HTTPREQ_GET && + k->httpcode == 416) { + /* "Requested Range Not Satisfiable", just proceed and + pretend this is no error */ + k->ignorebody = TRUE; /* Avoid appending error msg to good data. */ + } + + if(k->httpversion == 10) { + /* Default action for HTTP/1.0 must be to close, unless + we get one of those fancy headers that tell us the + server keeps it open for us! */ + infof(data, "HTTP 1.0, assume close after body"); + connclose(conn, "HTTP/1.0 close after body"); + } + else if(k->httpversion == 20 || + (k->upgr101 == UPGR101_H2 && k->httpcode == 101)) { + DEBUGF(infof(data, "HTTP/2 found, allow multiplexing")); + /* HTTP/2 cannot avoid multiplexing since it is a core functionality + of the protocol */ + conn->bundle->multiuse = BUNDLE_MULTIPLEX; + } + + k->http_bodyless = k->httpcode >= 100 && k->httpcode < 200; + switch(k->httpcode) { + case 304: + /* (quote from RFC2616, section 10.3.5): The 304 response + * MUST NOT contain a message-body, and thus is always + * terminated by the first empty line after the header + * fields. */ + if(data->set.timecondition) + data->info.timecond = TRUE; + FALLTHROUGH(); + case 204: + /* (quote from RFC2616, section 10.2.5): The server has + * fulfilled the request but does not need to return an + * entity-body ... The 204 response MUST NOT include a + * message-body, and thus is always terminated by the first + * empty line after the header fields. */ + k->size = 0; + k->maxdownload = 0; + k->http_bodyless = TRUE; + break; + default: + break; + } + return CURLE_OK; +} + +/* Content-Length must be ignored if any Transfer-Encoding is present in the + response. Refer to RFC 7230 section 3.3.3 and RFC2616 section 4.4. This is + figured out here after all headers have been received but before the final + call to the user's header callback, so that a valid content length can be + retrieved by the user in the final call. */ +CURLcode Curl_http_size(struct Curl_easy *data) +{ + struct SingleRequest *k = &data->req; + if(data->req.ignore_cl || k->chunk) { + k->size = k->maxdownload = -1; + } + else if(k->size != -1) { + if(data->set.max_filesize && + k->size > data->set.max_filesize) { + failf(data, "Maximum file size exceeded"); + return CURLE_FILESIZE_EXCEEDED; + } + Curl_pgrsSetDownloadSize(data, k->size); + k->maxdownload = k->size; + } + return CURLE_OK; +} + +static CURLcode verify_header(struct Curl_easy *data, + const char *hd, size_t hdlen) +{ + struct SingleRequest *k = &data->req; + char *ptr = memchr(hd, 0x00, hdlen); + if(ptr) { + /* this is bad, bail out */ + failf(data, "Nul byte in header"); + return CURLE_WEIRD_SERVER_REPLY; + } + if(k->headerline < 2) + /* the first "header" is the status-line and it has no colon */ + return CURLE_OK; + if(((hd[0] == ' ') || (hd[0] == '\t')) && k->headerline > 2) + /* line folding, can't happen on line 2 */ + ; + else { + ptr = memchr(hd, ':', hdlen); + if(!ptr) { + /* this is bad, bail out */ + failf(data, "Header without colon"); + return CURLE_WEIRD_SERVER_REPLY; + } + } + return CURLE_OK; +} + +CURLcode Curl_bump_headersize(struct Curl_easy *data, + size_t delta, + bool connect_only) +{ + size_t bad = 0; + unsigned int max = MAX_HTTP_RESP_HEADER_SIZE; + if(delta < MAX_HTTP_RESP_HEADER_SIZE) { + data->info.header_size += (unsigned int)delta; + data->req.allheadercount += (unsigned int)delta; + if(!connect_only) + data->req.headerbytecount += (unsigned int)delta; + if(data->req.allheadercount > max) + bad = data->req.allheadercount; + else if(data->info.header_size > (max * 20)) { + bad = data->info.header_size; + max *= 20; + } + } + else + bad = data->req.allheadercount + delta; + if(bad) { + failf(data, "Too large response headers: %zu > %u", bad, max); + return CURLE_RECV_ERROR; + } + return CURLE_OK; +} + + +static CURLcode http_on_response(struct Curl_easy *data, + const char *buf, size_t blen, + size_t *pconsumed) +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + struct SingleRequest *k = &data->req; + + (void)buf; /* not used without HTTP2 enabled */ + *pconsumed = 0; + + if(k->upgr101 == UPGR101_RECEIVED) { + /* supposedly upgraded to http2 now */ + if(conn->httpversion != 20) + infof(data, "Lying server, not serving HTTP/2"); + } + if(conn->httpversion < 20) { + conn->bundle->multiuse = BUNDLE_NO_MULTIUSE; + } + + if(k->httpcode < 100) { + failf(data, "Unsupported response code in HTTP response"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + else if(k->httpcode < 200) { + /* "A user agent MAY ignore unexpected 1xx status responses." + * By default, we expect to get more responses after this one. */ + k->header = TRUE; + k->headerline = 0; /* restart the header line counter */ + + switch(k->httpcode) { + case 100: + /* + * We have made an HTTP PUT or POST and this is 1.1-lingo + * that tells us that the server is OK with this and ready + * to receive the data. + */ + Curl_http_exp100_got100(data); + break; + case 101: + /* Switching Protocols only allowed from HTTP/1.1 */ + if(conn->httpversion != 11) { + /* invalid for other HTTP versions */ + failf(data, "unexpected 101 response code"); + return CURLE_WEIRD_SERVER_REPLY; + } + if(k->upgr101 == UPGR101_H2) { + /* Switching to HTTP/2, where we will get more responses */ + infof(data, "Received 101, Switching to HTTP/2"); + k->upgr101 = UPGR101_RECEIVED; + /* We expect more response from HTTP/2 later */ + k->header = TRUE; + k->headerline = 0; /* restart the header line counter */ + /* Any remaining `buf` bytes are already HTTP/2 and passed to + * be processed. */ + result = Curl_http2_upgrade(data, conn, FIRSTSOCKET, buf, blen); + if(result) + return result; + *pconsumed += blen; + } +#ifdef USE_WEBSOCKETS + else if(k->upgr101 == UPGR101_WS) { + /* verify the response. Any passed `buf` bytes are already in + * WebSockets format and taken in by the protocol handler. */ + result = Curl_ws_accept(data, buf, blen); + if(result) + return result; + *pconsumed += blen; /* ws accept handled the data */ + k->header = FALSE; /* we will not get more responses */ + if(data->set.connect_only) + k->keepon &= ~KEEP_RECV; /* read no more content */ + } +#endif + else { + /* We silently accept this as the final response. + * TODO: this looks, uhm, wrong. What are we switching to if we + * did not ask for an Upgrade? Maybe the application provided an + * `Upgrade: xxx` header? */ + k->header = FALSE; + } + break; + default: + /* The server may send us other 1xx responses, like informative + * 103. This have no influence on request processing and we expect + * to receive a final response eventually. */ + break; + } + return result; + } + + /* k->httpcode >= 200, final response */ + k->header = FALSE; + + if(k->upgr101 == UPGR101_H2) { + /* A requested upgrade was denied, poke the multi handle to possibly + allow a pending pipewait to continue */ + Curl_multi_connchanged(data->multi); + } + + if((k->size == -1) && !k->chunk && !conn->bits.close && + (conn->httpversion == 11) && + !(conn->handler->protocol & CURLPROTO_RTSP) && + data->state.httpreq != HTTPREQ_HEAD) { + /* On HTTP 1.1, when connection is not to get closed, but no + Content-Length nor Transfer-Encoding chunked have been + received, according to RFC2616 section 4.4 point 5, we + assume that the server will close the connection to + signal the end of the document. */ + infof(data, "no chunk, no close, no size. Assume close to " + "signal end"); + streamclose(conn, "HTTP: No end-of-message indicator"); + } + + /* At this point we have some idea about the fate of the connection. + If we are closing the connection it may result auth failure. */ +#if defined(USE_NTLM) + if(conn->bits.close && + (((data->req.httpcode == 401) && + (conn->http_ntlm_state == NTLMSTATE_TYPE2)) || + ((data->req.httpcode == 407) && + (conn->proxy_ntlm_state == NTLMSTATE_TYPE2)))) { + infof(data, "Connection closure while negotiating auth (HTTP 1.0?)"); + data->state.authproblem = TRUE; + } +#endif +#if defined(USE_SPNEGO) + if(conn->bits.close && + (((data->req.httpcode == 401) && + (conn->http_negotiate_state == GSS_AUTHRECV)) || + ((data->req.httpcode == 407) && + (conn->proxy_negotiate_state == GSS_AUTHRECV)))) { + infof(data, "Connection closure while negotiating auth (HTTP 1.0?)"); + data->state.authproblem = TRUE; + } + if((conn->http_negotiate_state == GSS_AUTHDONE) && + (data->req.httpcode != 401)) { + conn->http_negotiate_state = GSS_AUTHSUCC; + } + if((conn->proxy_negotiate_state == GSS_AUTHDONE) && + (data->req.httpcode != 407)) { + conn->proxy_negotiate_state = GSS_AUTHSUCC; + } +#endif + +#ifdef USE_WEBSOCKETS + /* All >=200 HTTP status codes are errors when wanting websockets */ + if(data->req.upgr101 == UPGR101_WS) { + failf(data, "Refused WebSockets upgrade: %d", k->httpcode); + return CURLE_HTTP_RETURNED_ERROR; + } +#endif + + /* Check if this response means the transfer errored. */ + if(http_should_fail(data, data->req.httpcode)) { + failf(data, "The requested URL returned error: %d", + k->httpcode); + return CURLE_HTTP_RETURNED_ERROR; + } + + /* Curl_http_auth_act() checks what authentication methods + * that are available and decides which one (if any) to + * use. It will set 'newurl' if an auth method was picked. */ + result = Curl_http_auth_act(data); + if(result) + return result; + + if(k->httpcode >= 300) { + if((!data->req.authneg) && !conn->bits.close && + !Curl_creader_will_rewind(data)) { + /* + * General treatment of errors when about to send data. Including : + * "417 Expectation Failed", while waiting for 100-continue. + * + * The check for close above is done simply because of something + * else has already deemed the connection to get closed then + * something else should've considered the big picture and we + * avoid this check. + * + */ + + switch(data->state.httpreq) { + case HTTPREQ_PUT: + case HTTPREQ_POST: + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + /* We got an error response. If this happened before the whole + * request body has been sent we stop sending and mark the + * connection for closure after we've read the entire response. + */ + if(!Curl_req_done_sending(data)) { + if((k->httpcode == 417) && Curl_http_exp100_is_selected(data)) { + /* 417 Expectation Failed - try again without the Expect + header */ + if(!k->writebytecount && http_exp100_is_waiting(data)) { + infof(data, "Got HTTP failure 417 while waiting for a 100"); + } + else { + infof(data, "Got HTTP failure 417 while sending data"); + streamclose(conn, + "Stop sending data before everything sent"); + result = http_perhapsrewind(data, conn); + if(result) + return result; + } + data->state.disableexpect = TRUE; + DEBUGASSERT(!data->req.newurl); + data->req.newurl = strdup(data->state.url); + Curl_req_abort_sending(data); + } + else if(data->set.http_keep_sending_on_error) { + infof(data, "HTTP error before end of send, keep sending"); + http_exp100_send_anyway(data); + } + else { + infof(data, "HTTP error before end of send, stop sending"); + streamclose(conn, "Stop sending data before everything sent"); + result = Curl_req_abort_sending(data); + if(result) + return result; + } + } + break; + + default: /* default label present to avoid compiler warnings */ + break; + } + } + + if(Curl_creader_will_rewind(data) && !Curl_req_done_sending(data)) { + /* We rewind before next send, continue sending now */ + infof(data, "Keep sending data to get tossed away"); + k->keepon |= KEEP_SEND; + } + + } + + /* This is the last response that we will got for the current request. + * Check on the body size and determine if the response is complete. + */ + result = Curl_http_size(data); + if(result) + return result; + + /* If we requested a "no body", this is a good time to get + * out and return home. + */ + if(data->req.no_body) + k->download_done = TRUE; + + /* If max download size is *zero* (nothing) we already have + nothing and can safely return ok now! But for HTTP/2, we'd + like to call http2_handle_stream_close to properly close a + stream. In order to do this, we keep reading until we + close the stream. */ + if(0 == k->maxdownload + && !Curl_conn_is_http2(data, conn, FIRSTSOCKET) + && !Curl_conn_is_http3(data, conn, FIRSTSOCKET)) + k->download_done = TRUE; + + /* final response without error, prepare to receive the body */ + return Curl_http_firstwrite(data); +} + +static CURLcode http_rw_hd(struct Curl_easy *data, + const char *hd, size_t hdlen, + const char *buf_remain, size_t blen, + size_t *pconsumed) +{ + CURLcode result = CURLE_OK; + struct SingleRequest *k = &data->req; + int writetype; + + *pconsumed = 0; + if((0x0a == *hd) || (0x0d == *hd)) { + /* Empty header line means end of headers! */ + size_t consumed; + + /* now, only output this if the header AND body are requested: + */ + Curl_debug(data, CURLINFO_HEADER_IN, (char *)hd, hdlen); + + writetype = CLIENTWRITE_HEADER | + ((k->httpcode/100 == 1) ? CLIENTWRITE_1XX : 0); + + result = Curl_client_write(data, writetype, hd, hdlen); + if(result) + return result; + + result = Curl_bump_headersize(data, hdlen, FALSE); + if(result) + return result; + + data->req.deductheadercount = + (100 <= k->httpcode && 199 >= k->httpcode)?data->req.headerbytecount:0; + + /* analyze the response to find out what to do. */ + /* Caveat: we clear anything in the header brigade, because a + * response might switch HTTP version which may call use recursively. + * Not nice, but that is currently the way of things. */ + Curl_dyn_reset(&data->state.headerb); + result = http_on_response(data, buf_remain, blen, &consumed); + if(result) + return result; + *pconsumed += consumed; + return CURLE_OK; + } + + /* + * Checks for special headers coming up. + */ + + writetype = CLIENTWRITE_HEADER; + if(!k->headerline++) { + /* This is the first header, it MUST be the error code line + or else we consider this to be the body right away! */ + bool fine_statusline = FALSE; + + k->httpversion = 0; /* Don't know yet */ + if(data->conn->handler->protocol & PROTO_FAMILY_HTTP) { + /* + * https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2 + * + * The response code is always a three-digit number in HTTP as the spec + * says. We allow any three-digit number here, but we cannot make + * guarantees on future behaviors since it isn't within the protocol. + */ + const char *p = hd; + + while(*p && ISBLANK(*p)) + p++; + if(!strncmp(p, "HTTP/", 5)) { + p += 5; + switch(*p) { + case '1': + p++; + if((p[0] == '.') && (p[1] == '0' || p[1] == '1')) { + if(ISBLANK(p[2])) { + k->httpversion = 10 + (p[1] - '0'); + p += 3; + if(ISDIGIT(p[0]) && ISDIGIT(p[1]) && ISDIGIT(p[2])) { + k->httpcode = (p[0] - '0') * 100 + (p[1] - '0') * 10 + + (p[2] - '0'); + p += 3; + if(ISSPACE(*p)) + fine_statusline = TRUE; + } + } + } + if(!fine_statusline) { + failf(data, "Unsupported HTTP/1 subversion in response"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + break; + case '2': + case '3': + if(!ISBLANK(p[1])) + break; + k->httpversion = (*p - '0') * 10; + p += 2; + if(ISDIGIT(p[0]) && ISDIGIT(p[1]) && ISDIGIT(p[2])) { + k->httpcode = (p[0] - '0') * 100 + (p[1] - '0') * 10 + + (p[2] - '0'); + p += 3; + if(!ISSPACE(*p)) + break; + fine_statusline = TRUE; + } + break; + default: /* unsupported */ + failf(data, "Unsupported HTTP version in response"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + } + + if(!fine_statusline) { + /* If user has set option HTTP200ALIASES, + compare header line against list of aliases + */ + statusline check = checkhttpprefix(data, hd, hdlen); + if(check == STATUS_DONE) { + fine_statusline = TRUE; + k->httpcode = 200; + k->httpversion = 10; + } + } + } + else if(data->conn->handler->protocol & CURLPROTO_RTSP) { + const char *p = hd; + while(*p && ISBLANK(*p)) + p++; + if(!strncmp(p, "RTSP/", 5)) { + p += 5; + if(ISDIGIT(*p)) { + p++; + if((p[0] == '.') && ISDIGIT(p[1])) { + if(ISBLANK(p[2])) { + p += 3; + if(ISDIGIT(p[0]) && ISDIGIT(p[1]) && ISDIGIT(p[2])) { + k->httpcode = (p[0] - '0') * 100 + (p[1] - '0') * 10 + + (p[2] - '0'); + p += 3; + if(ISSPACE(*p)) { + fine_statusline = TRUE; + k->httpversion = 11; /* RTSP acts like HTTP 1.1 */ + } + } + } + } + } + if(!fine_statusline) + return CURLE_WEIRD_SERVER_REPLY; + } + } + + if(fine_statusline) { + result = Curl_http_statusline(data, data->conn); + if(result) + return result; + writetype |= CLIENTWRITE_STATUS; + } + else { + k->header = FALSE; /* this is not a header line */ + return CURLE_WEIRD_SERVER_REPLY; + } + } + + result = verify_header(data, hd, hdlen); + if(result) + return result; + + result = Curl_http_header(data, hd, hdlen); + if(result) + return result; + + /* + * Taken in one (more) header. Write it to the client. + */ + Curl_debug(data, CURLINFO_HEADER_IN, (char *)hd, hdlen); + + if(k->httpcode/100 == 1) + writetype |= CLIENTWRITE_1XX; + result = Curl_client_write(data, writetype, hd, hdlen); + if(result) + return result; + + result = Curl_bump_headersize(data, hdlen, FALSE); + if(result) + return result; + + return CURLE_OK; +} + +/* + * Read any HTTP header lines from the server and pass them to the client app. + */ +static CURLcode http_parse_headers(struct Curl_easy *data, + const char *buf, size_t blen, + size_t *pconsumed) +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + struct SingleRequest *k = &data->req; + char *end_ptr; + bool leftover_body = FALSE; + + /* header line within buffer loop */ + *pconsumed = 0; + while(blen && k->header) { + size_t consumed; + + end_ptr = memchr(buf, '\n', blen); + if(!end_ptr) { + /* Not a complete header line within buffer, append the data to + the end of the headerbuff. */ + result = Curl_dyn_addn(&data->state.headerb, buf, blen); + if(result) + return result; + *pconsumed += blen; + + if(!k->headerline) { + /* check if this looks like a protocol header */ + statusline st = + checkprotoprefix(data, conn, + Curl_dyn_ptr(&data->state.headerb), + Curl_dyn_len(&data->state.headerb)); + + if(st == STATUS_BAD) { + /* this is not the beginning of a protocol first header line */ + k->header = FALSE; + streamclose(conn, "bad HTTP: No end-of-message indicator"); + if(conn->httpversion >= 10) { + failf(data, "Invalid status line"); + return CURLE_WEIRD_SERVER_REPLY; + } + if(!data->set.http09_allowed) { + failf(data, "Received HTTP/0.9 when not allowed"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + leftover_body = TRUE; + goto out; + } + } + goto out; /* read more and try again */ + } + + /* decrease the size of the remaining (supposed) header line */ + consumed = (end_ptr - buf) + 1; + result = Curl_dyn_addn(&data->state.headerb, buf, consumed); + if(result) + return result; + blen -= consumed; + buf += consumed; + *pconsumed += consumed; + + /**** + * We now have a FULL header line in 'headerb'. + *****/ + + if(!k->headerline) { + /* the first read header */ + statusline st = checkprotoprefix(data, conn, + Curl_dyn_ptr(&data->state.headerb), + Curl_dyn_len(&data->state.headerb)); + if(st == STATUS_BAD) { + streamclose(conn, "bad HTTP: No end-of-message indicator"); + /* this is not the beginning of a protocol first header line */ + if(conn->httpversion >= 10) { + failf(data, "Invalid status line"); + return CURLE_WEIRD_SERVER_REPLY; + } + if(!data->set.http09_allowed) { + failf(data, "Received HTTP/0.9 when not allowed"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + k->header = FALSE; + leftover_body = TRUE; + goto out; + } + } + + result = http_rw_hd(data, Curl_dyn_ptr(&data->state.headerb), + Curl_dyn_len(&data->state.headerb), + buf, blen, &consumed); + /* We are done with this line. We reset because response + * processing might switch to HTTP/2 and that might call us + * directly again. */ + Curl_dyn_reset(&data->state.headerb); + if(consumed) { + blen -= consumed; + buf += consumed; + *pconsumed += consumed; + } + if(result) + return result; + } + + /* We might have reached the end of the header part here, but + there might be a non-header part left in the end of the read + buffer. */ +out: + if(!k->header && !leftover_body) { + Curl_dyn_free(&data->state.headerb); + } + return CURLE_OK; +} + +CURLcode Curl_http_write_resp_hd(struct Curl_easy *data, + const char *hd, size_t hdlen, + bool is_eos) +{ + CURLcode result; + size_t consumed; + char tmp = 0; + + result = http_rw_hd(data, hd, hdlen, &tmp, 0, &consumed); + if(!result && is_eos) { + result = Curl_client_write(data, (CLIENTWRITE_BODY|CLIENTWRITE_EOS), + &tmp, 0); + } + return result; +} + +/* + * HTTP protocol `write_resp` implementation. Will parse headers + * when not done yet and otherwise return without consuming data. + */ +CURLcode Curl_http_write_resp_hds(struct Curl_easy *data, + const char *buf, size_t blen, + size_t *pconsumed) +{ + if(!data->req.header) { + *pconsumed = 0; + return CURLE_OK; + } + else { + CURLcode result; + + result = http_parse_headers(data, buf, blen, pconsumed); + if(!result && !data->req.header) { + if(!data->req.no_body && Curl_dyn_len(&data->state.headerb)) { + /* leftover from parsing something that turned out not + * to be a header, only happens if we allow for + * HTTP/0.9 like responses */ + result = Curl_client_write(data, CLIENTWRITE_BODY, + Curl_dyn_ptr(&data->state.headerb), + Curl_dyn_len(&data->state.headerb)); + } + Curl_dyn_free(&data->state.headerb); + } + return result; + } +} + +CURLcode Curl_http_write_resp(struct Curl_easy *data, + const char *buf, size_t blen, + bool is_eos) +{ + CURLcode result; + size_t consumed; + int flags; + + result = Curl_http_write_resp_hds(data, buf, blen, &consumed); + if(result || data->req.done) + goto out; + + DEBUGASSERT(consumed <= blen); + blen -= consumed; + buf += consumed; + /* either all was consumed in header parsing, or we have data left + * and are done with headers, e.g. it is BODY data */ + DEBUGASSERT(!blen || !data->req.header); + if(!data->req.header && (blen || is_eos)) { + /* BODY data after header been parsed, write and consume */ + flags = CLIENTWRITE_BODY; + if(is_eos) + flags |= CLIENTWRITE_EOS; + result = Curl_client_write(data, flags, (char *)buf, blen); + } +out: + return result; +} + +/* Decode HTTP status code string. */ +CURLcode Curl_http_decode_status(int *pstatus, const char *s, size_t len) +{ + CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT; + int status = 0; + int i; + + if(len != 3) + goto out; + + for(i = 0; i < 3; ++i) { + char c = s[i]; + + if(c < '0' || c > '9') + goto out; + + status *= 10; + status += c - '0'; + } + result = CURLE_OK; +out: + *pstatus = result? -1 : status; + return result; +} + +CURLcode Curl_http_req_make(struct httpreq **preq, + const char *method, size_t m_len, + const char *scheme, size_t s_len, + const char *authority, size_t a_len, + const char *path, size_t p_len) +{ + struct httpreq *req; + CURLcode result = CURLE_OUT_OF_MEMORY; + + DEBUGASSERT(method); + if(m_len + 1 > sizeof(req->method)) + return CURLE_BAD_FUNCTION_ARGUMENT; + + req = calloc(1, sizeof(*req)); + if(!req) + goto out; + memcpy(req->method, method, m_len); + if(scheme) { + req->scheme = Curl_memdup0(scheme, s_len); + if(!req->scheme) + goto out; + } + if(authority) { + req->authority = Curl_memdup0(authority, a_len); + if(!req->authority) + goto out; + } + if(path) { + req->path = Curl_memdup0(path, p_len); + if(!req->path) + goto out; + } + Curl_dynhds_init(&req->headers, 0, DYN_HTTP_REQUEST); + Curl_dynhds_init(&req->trailers, 0, DYN_HTTP_REQUEST); + result = CURLE_OK; + +out: + if(result && req) + Curl_http_req_free(req); + *preq = result? NULL : req; + return result; +} + +static CURLcode req_assign_url_authority(struct httpreq *req, CURLU *url) +{ + char *user, *pass, *host, *port; + struct dynbuf buf; + CURLUcode uc; + CURLcode result = CURLE_URL_MALFORMAT; + + user = pass = host = port = NULL; + Curl_dyn_init(&buf, DYN_HTTP_REQUEST); + + uc = curl_url_get(url, CURLUPART_HOST, &host, 0); + if(uc && uc != CURLUE_NO_HOST) + goto out; + if(!host) { + req->authority = NULL; + result = CURLE_OK; + goto out; + } + + uc = curl_url_get(url, CURLUPART_PORT, &port, CURLU_NO_DEFAULT_PORT); + if(uc && uc != CURLUE_NO_PORT) + goto out; + uc = curl_url_get(url, CURLUPART_USER, &user, 0); + if(uc && uc != CURLUE_NO_USER) + goto out; + if(user) { + uc = curl_url_get(url, CURLUPART_PASSWORD, &pass, 0); + if(uc && uc != CURLUE_NO_PASSWORD) + goto out; + } + + if(user) { + result = Curl_dyn_add(&buf, user); + if(result) + goto out; + if(pass) { + result = Curl_dyn_addf(&buf, ":%s", pass); + if(result) + goto out; + } + result = Curl_dyn_add(&buf, "@"); + if(result) + goto out; + } + result = Curl_dyn_add(&buf, host); + if(result) + goto out; + if(port) { + result = Curl_dyn_addf(&buf, ":%s", port); + if(result) + goto out; + } + req->authority = strdup(Curl_dyn_ptr(&buf)); + if(!req->authority) + goto out; + result = CURLE_OK; + +out: + free(user); + free(pass); + free(host); + free(port); + Curl_dyn_free(&buf); + return result; +} + +static CURLcode req_assign_url_path(struct httpreq *req, CURLU *url) +{ + char *path, *query; + struct dynbuf buf; + CURLUcode uc; + CURLcode result = CURLE_URL_MALFORMAT; + + path = query = NULL; + Curl_dyn_init(&buf, DYN_HTTP_REQUEST); + + uc = curl_url_get(url, CURLUPART_PATH, &path, CURLU_PATH_AS_IS); + if(uc) + goto out; + uc = curl_url_get(url, CURLUPART_QUERY, &query, 0); + if(uc && uc != CURLUE_NO_QUERY) + goto out; + + if(!path && !query) { + req->path = NULL; + } + else if(path && !query) { + req->path = path; + path = NULL; + } + else { + if(path) { + result = Curl_dyn_add(&buf, path); + if(result) + goto out; + } + if(query) { + result = Curl_dyn_addf(&buf, "?%s", query); + if(result) + goto out; + } + req->path = strdup(Curl_dyn_ptr(&buf)); + if(!req->path) + goto out; + } + result = CURLE_OK; + +out: + free(path); + free(query); + Curl_dyn_free(&buf); + return result; +} + +CURLcode Curl_http_req_make2(struct httpreq **preq, + const char *method, size_t m_len, + CURLU *url, const char *scheme_default) +{ + struct httpreq *req; + CURLcode result = CURLE_OUT_OF_MEMORY; + CURLUcode uc; + + DEBUGASSERT(method); + if(m_len + 1 > sizeof(req->method)) + return CURLE_BAD_FUNCTION_ARGUMENT; + + req = calloc(1, sizeof(*req)); + if(!req) + goto out; + memcpy(req->method, method, m_len); + + uc = curl_url_get(url, CURLUPART_SCHEME, &req->scheme, 0); + if(uc && uc != CURLUE_NO_SCHEME) + goto out; + if(!req->scheme && scheme_default) { + req->scheme = strdup(scheme_default); + if(!req->scheme) + goto out; + } + + result = req_assign_url_authority(req, url); + if(result) + goto out; + result = req_assign_url_path(req, url); + if(result) + goto out; + + Curl_dynhds_init(&req->headers, 0, DYN_HTTP_REQUEST); + Curl_dynhds_init(&req->trailers, 0, DYN_HTTP_REQUEST); + result = CURLE_OK; + +out: + if(result && req) + Curl_http_req_free(req); + *preq = result? NULL : req; + return result; +} + +void Curl_http_req_free(struct httpreq *req) +{ + if(req) { + free(req->scheme); + free(req->authority); + free(req->path); + Curl_dynhds_free(&req->headers); + Curl_dynhds_free(&req->trailers); + free(req); + } +} + +struct name_const { + const char *name; + size_t namelen; +}; + +static struct name_const H2_NON_FIELD[] = { + { STRCONST("Host") }, + { STRCONST("Upgrade") }, + { STRCONST("Connection") }, + { STRCONST("Keep-Alive") }, + { STRCONST("Proxy-Connection") }, + { STRCONST("Transfer-Encoding") }, +}; + +static bool h2_non_field(const char *name, size_t namelen) +{ + size_t i; + for(i = 0; i < sizeof(H2_NON_FIELD)/sizeof(H2_NON_FIELD[0]); ++i) { + if(namelen < H2_NON_FIELD[i].namelen) + return FALSE; + if(namelen == H2_NON_FIELD[i].namelen && + strcasecompare(H2_NON_FIELD[i].name, name)) + return TRUE; + } + return FALSE; +} + +CURLcode Curl_http_req_to_h2(struct dynhds *h2_headers, + struct httpreq *req, struct Curl_easy *data) +{ + const char *scheme = NULL, *authority = NULL; + struct dynhds_entry *e; + size_t i; + CURLcode result; + + DEBUGASSERT(req); + DEBUGASSERT(h2_headers); + + if(req->scheme) { + scheme = req->scheme; + } + else if(strcmp("CONNECT", req->method)) { + scheme = Curl_checkheaders(data, STRCONST(HTTP_PSEUDO_SCHEME)); + if(scheme) { + scheme += sizeof(HTTP_PSEUDO_SCHEME); + while(*scheme && ISBLANK(*scheme)) + scheme++; + infof(data, "set pseudo header %s to %s", HTTP_PSEUDO_SCHEME, scheme); + } + else { + scheme = (data->conn && data->conn->handler->flags & PROTOPT_SSL)? + "https" : "http"; + } + } + + if(req->authority) { + authority = req->authority; + } + else { + e = Curl_dynhds_get(&req->headers, STRCONST("Host")); + if(e) + authority = e->value; + } + + Curl_dynhds_reset(h2_headers); + Curl_dynhds_set_opts(h2_headers, DYNHDS_OPT_LOWERCASE); + result = Curl_dynhds_add(h2_headers, STRCONST(HTTP_PSEUDO_METHOD), + req->method, strlen(req->method)); + if(!result && scheme) { + result = Curl_dynhds_add(h2_headers, STRCONST(HTTP_PSEUDO_SCHEME), + scheme, strlen(scheme)); + } + if(!result && authority) { + result = Curl_dynhds_add(h2_headers, STRCONST(HTTP_PSEUDO_AUTHORITY), + authority, strlen(authority)); + } + if(!result && req->path) { + result = Curl_dynhds_add(h2_headers, STRCONST(HTTP_PSEUDO_PATH), + req->path, strlen(req->path)); + } + for(i = 0; !result && i < Curl_dynhds_count(&req->headers); ++i) { + e = Curl_dynhds_getn(&req->headers, i); + if(!h2_non_field(e->name, e->namelen)) { + result = Curl_dynhds_add(h2_headers, e->name, e->namelen, + e->value, e->valuelen); + } + } + + return result; +} + +CURLcode Curl_http_resp_make(struct http_resp **presp, + int status, + const char *description) +{ + struct http_resp *resp; + CURLcode result = CURLE_OUT_OF_MEMORY; + + resp = calloc(1, sizeof(*resp)); + if(!resp) + goto out; + + resp->status = status; + if(description) { + resp->description = strdup(description); + if(!resp->description) + goto out; + } + Curl_dynhds_init(&resp->headers, 0, DYN_HTTP_REQUEST); + Curl_dynhds_init(&resp->trailers, 0, DYN_HTTP_REQUEST); + result = CURLE_OK; + +out: + if(result && resp) + Curl_http_resp_free(resp); + *presp = result? NULL : resp; + return result; +} + +void Curl_http_resp_free(struct http_resp *resp) +{ + if(resp) { + free(resp->description); + Curl_dynhds_free(&resp->headers); + Curl_dynhds_free(&resp->trailers); + if(resp->prev) + Curl_http_resp_free(resp->prev); + free(resp); + } +} + +struct cr_exp100_ctx { + struct Curl_creader super; + struct curltime start; /* time started waiting */ + enum expect100 state; +}; + +/* Expect: 100-continue client reader, blocking uploads */ + +static void http_exp100_continue(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_exp100_ctx *ctx = reader->ctx; + if(ctx->state > EXP100_SEND_DATA) { + ctx->state = EXP100_SEND_DATA; + data->req.keepon |= KEEP_SEND; + data->req.keepon &= ~KEEP_SEND_TIMED; + Curl_expire_done(data, EXPIRE_100_TIMEOUT); + } +} + +static CURLcode cr_exp100_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *nread, bool *eos) +{ + struct cr_exp100_ctx *ctx = reader->ctx; + timediff_t ms; + + switch(ctx->state) { + case EXP100_SENDING_REQUEST: + /* We are now waiting for a reply from the server or + * a timeout on our side */ + DEBUGF(infof(data, "cr_exp100_read, start AWAITING_CONTINUE")); + ctx->state = EXP100_AWAITING_CONTINUE; + ctx->start = Curl_now(); + Curl_expire(data, data->set.expect_100_timeout, EXPIRE_100_TIMEOUT); + data->req.keepon &= ~KEEP_SEND; + data->req.keepon |= KEEP_SEND_TIMED; + *nread = 0; + *eos = FALSE; + return CURLE_OK; + case EXP100_FAILED: + DEBUGF(infof(data, "cr_exp100_read, expectation failed, error")); + *nread = 0; + *eos = FALSE; + return CURLE_READ_ERROR; + case EXP100_AWAITING_CONTINUE: + ms = Curl_timediff(Curl_now(), ctx->start); + if(ms < data->set.expect_100_timeout) { + DEBUGF(infof(data, "cr_exp100_read, AWAITING_CONTINUE, not expired")); + data->req.keepon &= ~KEEP_SEND; + data->req.keepon |= KEEP_SEND_TIMED; + *nread = 0; + *eos = FALSE; + return CURLE_OK; + } + /* we've waited long enough, continue anyway */ + http_exp100_continue(data, reader); + infof(data, "Done waiting for 100-continue"); + FALLTHROUGH(); + default: + DEBUGF(infof(data, "cr_exp100_read, pass through")); + return Curl_creader_read(data, reader->next, buf, blen, nread, eos); + } +} + +static void cr_exp100_done(struct Curl_easy *data, + struct Curl_creader *reader, int premature) +{ + struct cr_exp100_ctx *ctx = reader->ctx; + ctx->state = premature? EXP100_FAILED : EXP100_SEND_DATA; + data->req.keepon &= ~KEEP_SEND_TIMED; + Curl_expire_done(data, EXPIRE_100_TIMEOUT); +} + +static const struct Curl_crtype cr_exp100 = { + "cr-exp100", + Curl_creader_def_init, + cr_exp100_read, + Curl_creader_def_close, + Curl_creader_def_needs_rewind, + Curl_creader_def_total_length, + Curl_creader_def_resume_from, + Curl_creader_def_rewind, + Curl_creader_def_unpause, + cr_exp100_done, + sizeof(struct cr_exp100_ctx) +}; + +static CURLcode http_exp100_add_reader(struct Curl_easy *data) +{ + struct Curl_creader *reader = NULL; + CURLcode result; + + result = Curl_creader_create(&reader, data, &cr_exp100, + CURL_CR_PROTOCOL); + if(!result) + result = Curl_creader_add(data, reader); + if(!result) { + struct cr_exp100_ctx *ctx = reader->ctx; + ctx->state = EXP100_SENDING_REQUEST; + } + + if(result && reader) + Curl_creader_free(data, reader); + return result; +} + +void Curl_http_exp100_got100(struct Curl_easy *data) +{ + struct Curl_creader *r = Curl_creader_get_by_type(data, &cr_exp100); + if(r) + http_exp100_continue(data, r); +} + +static bool http_exp100_is_waiting(struct Curl_easy *data) +{ + struct Curl_creader *r = Curl_creader_get_by_type(data, &cr_exp100); + if(r) { + struct cr_exp100_ctx *ctx = r->ctx; + return (ctx->state == EXP100_AWAITING_CONTINUE); + } + return FALSE; +} + +static void http_exp100_send_anyway(struct Curl_easy *data) +{ + struct Curl_creader *r = Curl_creader_get_by_type(data, &cr_exp100); + if(r) + http_exp100_continue(data, r); +} + +bool Curl_http_exp100_is_selected(struct Curl_easy *data) +{ + struct Curl_creader *r = Curl_creader_get_by_type(data, &cr_exp100); + return r? TRUE : FALSE; +} + +#endif /* CURL_DISABLE_HTTP */ diff --git a/third_party/curl/lib/http.h b/third_party/curl/lib/http.h new file mode 100644 index 0000000..b0c4f5f --- /dev/null +++ b/third_party/curl/lib/http.h @@ -0,0 +1,301 @@ +#ifndef HEADER_CURL_HTTP_H +#define HEADER_CURL_HTTP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_MSH3) && !defined(_WIN32) +#include +#endif + +#include "bufq.h" +#include "dynhds.h" +#include "ws.h" + +typedef enum { + HTTPREQ_GET, + HTTPREQ_POST, + HTTPREQ_POST_FORM, /* we make a difference internally */ + HTTPREQ_POST_MIME, /* we make a difference internally */ + HTTPREQ_PUT, + HTTPREQ_HEAD +} Curl_HttpReq; + +#ifndef CURL_DISABLE_HTTP + +#if defined(USE_HTTP3) +#include +#endif + +extern const struct Curl_handler Curl_handler_http; + +#ifdef USE_SSL +extern const struct Curl_handler Curl_handler_https; +#endif + +struct dynhds; + +CURLcode Curl_bump_headersize(struct Curl_easy *data, + size_t delta, + bool connect_only); + +/* Header specific functions */ +bool Curl_compareheader(const char *headerline, /* line to check */ + const char *header, /* header keyword _with_ colon */ + const size_t hlen, /* len of the keyword in bytes */ + const char *content, /* content string to find */ + const size_t clen); /* len of the content in bytes */ + +char *Curl_copy_header_value(const char *header); + +char *Curl_checkProxyheaders(struct Curl_easy *data, + const struct connectdata *conn, + const char *thisheader, + const size_t thislen); +struct HTTP; /* see below */ + +CURLcode Curl_add_timecondition(struct Curl_easy *data, +#ifndef USE_HYPER + struct dynbuf *req +#else + void *headers +#endif + ); +CURLcode Curl_add_custom_headers(struct Curl_easy *data, + bool is_connect, +#ifndef USE_HYPER + struct dynbuf *req +#else + void *headers +#endif + ); +CURLcode Curl_dynhds_add_custom(struct Curl_easy *data, + bool is_connect, + struct dynhds *hds); + +void Curl_http_method(struct Curl_easy *data, struct connectdata *conn, + const char **method, Curl_HttpReq *); +CURLcode Curl_http_useragent(struct Curl_easy *data); +CURLcode Curl_http_host(struct Curl_easy *data, struct connectdata *conn); +CURLcode Curl_http_target(struct Curl_easy *data, struct connectdata *conn, + struct dynbuf *req); +CURLcode Curl_http_statusline(struct Curl_easy *data, + struct connectdata *conn); +CURLcode Curl_http_header(struct Curl_easy *data, + const char *hd, size_t hdlen); +CURLcode Curl_transferencode(struct Curl_easy *data); +CURLcode Curl_http_req_set_reader(struct Curl_easy *data, + Curl_HttpReq httpreq, + const char **tep); +CURLcode Curl_http_req_complete(struct Curl_easy *data, + struct dynbuf *r, Curl_HttpReq httpreq); +bool Curl_use_http_1_1plus(const struct Curl_easy *data, + const struct connectdata *conn); +#ifndef CURL_DISABLE_COOKIES +CURLcode Curl_http_cookies(struct Curl_easy *data, + struct connectdata *conn, + struct dynbuf *r); +#else +#define Curl_http_cookies(a,b,c) CURLE_OK +#endif +CURLcode Curl_http_range(struct Curl_easy *data, + Curl_HttpReq httpreq); +CURLcode Curl_http_firstwrite(struct Curl_easy *data); + +/* protocol-specific functions set up to be called by the main engine */ +CURLcode Curl_http_setup_conn(struct Curl_easy *data, + struct connectdata *conn); +CURLcode Curl_http(struct Curl_easy *data, bool *done); +CURLcode Curl_http_done(struct Curl_easy *data, CURLcode, bool premature); +CURLcode Curl_http_connect(struct Curl_easy *data, bool *done); +int Curl_http_getsock_do(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t *socks); +CURLcode Curl_http_write_resp(struct Curl_easy *data, + const char *buf, size_t blen, + bool is_eos); +CURLcode Curl_http_write_resp_hd(struct Curl_easy *data, + const char *hd, size_t hdlen, + bool is_eos); + +/* These functions are in http.c */ +CURLcode Curl_http_input_auth(struct Curl_easy *data, bool proxy, + const char *auth); +CURLcode Curl_http_auth_act(struct Curl_easy *data); + +/* If only the PICKNONE bit is set, there has been a round-trip and we + selected to use no auth at all. Ie, we actively select no auth, as opposed + to not having one selected. The other CURLAUTH_* defines are present in the + public curl/curl.h header. */ +#define CURLAUTH_PICKNONE (1<<30) /* don't use auth */ + +/* MAX_INITIAL_POST_SIZE indicates the number of bytes that will make the POST + data get included in the initial data chunk sent to the server. If the + data is larger than this, it will automatically get split up in multiple + system calls. + + This value used to be fairly big (100K), but we must take into account that + if the server rejects the POST due for authentication reasons, this data + will always be unconditionally sent and thus it may not be larger than can + always be afforded to send twice. + + It must not be greater than 64K to work on VMS. +*/ +#ifndef MAX_INITIAL_POST_SIZE +#define MAX_INITIAL_POST_SIZE (64*1024) +#endif + +/* EXPECT_100_THRESHOLD is the request body size limit for when libcurl will + * automatically add an "Expect: 100-continue" header in HTTP requests. When + * the size is unknown, it will always add it. + * + */ +#ifndef EXPECT_100_THRESHOLD +#define EXPECT_100_THRESHOLD (1024*1024) +#endif + +/* MAX_HTTP_RESP_HEADER_SIZE is the maximum size of all response headers + combined that libcurl allows for a single HTTP response, any HTTP + version. This count includes CONNECT response headers. */ +#define MAX_HTTP_RESP_HEADER_SIZE (300*1024) + +bool Curl_http_exp100_is_selected(struct Curl_easy *data); +void Curl_http_exp100_got100(struct Curl_easy *data); + +#endif /* CURL_DISABLE_HTTP */ + +/**************************************************************************** + * HTTP unique setup + ***************************************************************************/ +struct HTTP { + /* TODO: no longer used, we should remove it from SingleRequest */ + char unused; +}; + +CURLcode Curl_http_size(struct Curl_easy *data); + +CURLcode Curl_http_write_resp_hds(struct Curl_easy *data, + const char *buf, size_t blen, + size_t *pconsumed); + +/** + * Curl_http_output_auth() setups the authentication headers for the + * host/proxy and the correct authentication + * method. data->state.authdone is set to TRUE when authentication is + * done. + * + * @param data all information about the current transfer + * @param conn all information about the current connection + * @param request pointer to the request keyword + * @param httpreq is the request type + * @param path pointer to the requested path + * @param proxytunnel boolean if this is the request setting up a "proxy + * tunnel" + * + * @returns CURLcode + */ +CURLcode +Curl_http_output_auth(struct Curl_easy *data, + struct connectdata *conn, + const char *request, + Curl_HttpReq httpreq, + const char *path, + bool proxytunnel); /* TRUE if this is the request setting + up the proxy tunnel */ + +/* Decode HTTP status code string. */ +CURLcode Curl_http_decode_status(int *pstatus, const char *s, size_t len); + + +/** + * All about a core HTTP request, excluding body and trailers + */ +struct httpreq { + char method[24]; + char *scheme; + char *authority; + char *path; + struct dynhds headers; + struct dynhds trailers; +}; + +/** + * Create a HTTP request struct. + */ +CURLcode Curl_http_req_make(struct httpreq **preq, + const char *method, size_t m_len, + const char *scheme, size_t s_len, + const char *authority, size_t a_len, + const char *path, size_t p_len); + +CURLcode Curl_http_req_make2(struct httpreq **preq, + const char *method, size_t m_len, + CURLU *url, const char *scheme_default); + +void Curl_http_req_free(struct httpreq *req); + +#define HTTP_PSEUDO_METHOD ":method" +#define HTTP_PSEUDO_SCHEME ":scheme" +#define HTTP_PSEUDO_AUTHORITY ":authority" +#define HTTP_PSEUDO_PATH ":path" +#define HTTP_PSEUDO_STATUS ":status" + +/** + * Create the list of HTTP/2 headers which represent the request, + * using HTTP/2 pseudo headers preceding the `req->headers`. + * + * Applies the following transformations: + * - if `authority` is set, any "Host" header is removed. + * - if `authority` is unset and a "Host" header is present, use + * that as `authority` and remove "Host" + * - removes and Connection header fields as defined in rfc9113 ch. 8.2.2 + * - lower-cases the header field names + * + * @param h2_headers will contain the HTTP/2 headers on success + * @param req the request to transform + * @param data the handle to lookup defaults like ' :scheme' from + */ +CURLcode Curl_http_req_to_h2(struct dynhds *h2_headers, + struct httpreq *req, struct Curl_easy *data); + +/** + * All about a core HTTP response, excluding body and trailers + */ +struct http_resp { + int status; + char *description; + struct dynhds headers; + struct dynhds trailers; + struct http_resp *prev; +}; + +/** + * Create a HTTP response struct. + */ +CURLcode Curl_http_resp_make(struct http_resp **presp, + int status, + const char *description); + +void Curl_http_resp_free(struct http_resp *resp); + +#endif /* HEADER_CURL_HTTP_H */ diff --git a/third_party/curl/lib/http1.c b/third_party/curl/lib/http1.c new file mode 100644 index 0000000..182234c --- /dev/null +++ b/third_party/curl/lib/http1.c @@ -0,0 +1,346 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_HTTP + +#include "urldata.h" +#include +#include "http.h" +#include "http1.h" +#include "urlapi-int.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +#define H1_MAX_URL_LEN (8*1024) + +void Curl_h1_req_parse_init(struct h1_req_parser *parser, size_t max_line_len) +{ + memset(parser, 0, sizeof(*parser)); + parser->max_line_len = max_line_len; + Curl_dyn_init(&parser->scratch, max_line_len); +} + +void Curl_h1_req_parse_free(struct h1_req_parser *parser) +{ + if(parser) { + Curl_http_req_free(parser->req); + Curl_dyn_free(&parser->scratch); + parser->req = NULL; + parser->done = FALSE; + } +} + +static CURLcode trim_line(struct h1_req_parser *parser, int options) +{ + DEBUGASSERT(parser->line); + if(parser->line_len) { + if(parser->line[parser->line_len - 1] == '\n') + --parser->line_len; + if(parser->line_len) { + if(parser->line[parser->line_len - 1] == '\r') + --parser->line_len; + else if(options & H1_PARSE_OPT_STRICT) + return CURLE_URL_MALFORMAT; + } + else if(options & H1_PARSE_OPT_STRICT) + return CURLE_URL_MALFORMAT; + } + else if(options & H1_PARSE_OPT_STRICT) + return CURLE_URL_MALFORMAT; + + if(parser->line_len > parser->max_line_len) { + return CURLE_URL_MALFORMAT; + } + return CURLE_OK; +} + +static ssize_t detect_line(struct h1_req_parser *parser, + const char *buf, const size_t buflen, + CURLcode *err) +{ + const char *line_end; + + DEBUGASSERT(!parser->line); + line_end = memchr(buf, '\n', buflen); + if(!line_end) { + *err = CURLE_AGAIN; + return -1; + } + parser->line = buf; + parser->line_len = line_end - buf + 1; + *err = CURLE_OK; + return (ssize_t)parser->line_len; +} + +static ssize_t next_line(struct h1_req_parser *parser, + const char *buf, const size_t buflen, int options, + CURLcode *err) +{ + ssize_t nread = 0; + + if(parser->line) { + parser->line = NULL; + parser->line_len = 0; + Curl_dyn_reset(&parser->scratch); + } + + nread = detect_line(parser, buf, buflen, err); + if(nread >= 0) { + if(Curl_dyn_len(&parser->scratch)) { + /* append detected line to scratch to have the complete line */ + *err = Curl_dyn_addn(&parser->scratch, parser->line, parser->line_len); + if(*err) + return -1; + parser->line = Curl_dyn_ptr(&parser->scratch); + parser->line_len = Curl_dyn_len(&parser->scratch); + } + *err = trim_line(parser, options); + if(*err) + return -1; + } + else if(*err == CURLE_AGAIN) { + /* no line end in `buf`, add it to our scratch */ + *err = Curl_dyn_addn(&parser->scratch, (const unsigned char *)buf, buflen); + nread = (*err)? -1 : (ssize_t)buflen; + } + return nread; +} + +static CURLcode start_req(struct h1_req_parser *parser, + const char *scheme_default, int options) +{ + const char *p, *m, *target, *hv, *scheme, *authority, *path; + size_t m_len, target_len, hv_len, scheme_len, authority_len, path_len; + size_t i; + CURLU *url = NULL; + CURLcode result = CURLE_URL_MALFORMAT; /* Use this as default fail */ + + DEBUGASSERT(!parser->req); + /* line must match: "METHOD TARGET HTTP_VERSION" */ + p = memchr(parser->line, ' ', parser->line_len); + if(!p || p == parser->line) + goto out; + + m = parser->line; + m_len = p - parser->line; + target = p + 1; + target_len = hv_len = 0; + hv = NULL; + + /* URL may contain spaces so scan backwards */ + for(i = parser->line_len; i > m_len; --i) { + if(parser->line[i] == ' ') { + hv = &parser->line[i + 1]; + hv_len = parser->line_len - i; + target_len = (hv - target) - 1; + break; + } + } + /* no SPACE found or empty TARGET or empty HTTP_VERSION */ + if(!target_len || !hv_len) + goto out; + + /* TODO: we do not check HTTP_VERSION for conformity, should + + do that when STRICT option is supplied. */ + (void)hv; + + /* The TARGET can be (rfc 9112, ch. 3.2): + * origin-form: path + optional query + * absolute-form: absolute URI + * authority-form: host+port for CONNECT + * asterisk-form: '*' for OPTIONS + * + * from TARGET, we derive `scheme` `authority` `path` + * origin-form -- -- TARGET + * absolute-form URL* URL* URL* + * authority-form -- TARGET -- + * asterisk-form -- -- TARGET + */ + scheme = authority = path = NULL; + scheme_len = authority_len = path_len = 0; + + if(target_len == 1 && target[0] == '*') { + /* asterisk-form */ + path = target; + path_len = target_len; + } + else if(!strncmp("CONNECT", m, m_len)) { + /* authority-form */ + authority = target; + authority_len = target_len; + } + else if(target[0] == '/') { + /* origin-form */ + path = target; + path_len = target_len; + } + else { + /* origin-form OR absolute-form */ + CURLUcode uc; + char tmp[H1_MAX_URL_LEN]; + + /* default, unless we see an absolute URL */ + path = target; + path_len = target_len; + + /* URL parser wants 0-termination */ + if(target_len >= sizeof(tmp)) + goto out; + memcpy(tmp, target, target_len); + tmp[target_len] = '\0'; + /* See if treating TARGET as an absolute URL makes sense */ + if(Curl_is_absolute_url(tmp, NULL, 0, FALSE)) { + int url_options; + + url = curl_url(); + if(!url) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + url_options = (CURLU_NON_SUPPORT_SCHEME| + CURLU_PATH_AS_IS| + CURLU_NO_DEFAULT_PORT); + if(!(options & H1_PARSE_OPT_STRICT)) + url_options |= CURLU_ALLOW_SPACE; + uc = curl_url_set(url, CURLUPART_URL, tmp, url_options); + if(uc) { + goto out; + } + } + + if(!url && (options & H1_PARSE_OPT_STRICT)) { + /* we should have an absolute URL or have seen `/` earlier */ + goto out; + } + } + + if(url) { + result = Curl_http_req_make2(&parser->req, m, m_len, url, scheme_default); + } + else { + if(!scheme && scheme_default) { + scheme = scheme_default; + scheme_len = strlen(scheme_default); + } + result = Curl_http_req_make(&parser->req, m, m_len, scheme, scheme_len, + authority, authority_len, path, path_len); + } + +out: + curl_url_cleanup(url); + return result; +} + +ssize_t Curl_h1_req_parse_read(struct h1_req_parser *parser, + const char *buf, size_t buflen, + const char *scheme_default, int options, + CURLcode *err) +{ + ssize_t nread = 0, n; + + *err = CURLE_OK; + while(!parser->done) { + n = next_line(parser, buf, buflen, options, err); + if(n < 0) { + if(*err != CURLE_AGAIN) { + nread = -1; + } + *err = CURLE_OK; + goto out; + } + + /* Consume this line */ + nread += (size_t)n; + buf += (size_t)n; + buflen -= (size_t)n; + + if(!parser->line) { + /* consumed bytes, but line not complete */ + if(!buflen) + goto out; + } + else if(!parser->req) { + *err = start_req(parser, scheme_default, options); + if(*err) { + nread = -1; + goto out; + } + } + else if(parser->line_len == 0) { + /* last, empty line, we are finished */ + if(!parser->req) { + *err = CURLE_URL_MALFORMAT; + nread = -1; + goto out; + } + parser->done = TRUE; + Curl_dyn_reset(&parser->scratch); + /* last chance adjustments */ + } + else { + *err = Curl_dynhds_h1_add_line(&parser->req->headers, + parser->line, parser->line_len); + if(*err) { + nread = -1; + goto out; + } + } + } + +out: + return nread; +} + +CURLcode Curl_h1_req_write_head(struct httpreq *req, int http_minor, + struct dynbuf *dbuf) +{ + CURLcode result; + + result = Curl_dyn_addf(dbuf, "%s %s%s%s%s HTTP/1.%d\r\n", + req->method, + req->scheme? req->scheme : "", + req->scheme? "://" : "", + req->authority? req->authority : "", + req->path? req->path : "", + http_minor); + if(result) + goto out; + + result = Curl_dynhds_h1_dprint(&req->headers, dbuf); + if(result) + goto out; + + result = Curl_dyn_addn(dbuf, STRCONST("\r\n")); + +out: + return result; +} + +#endif /* !CURL_DISABLE_HTTP */ diff --git a/third_party/curl/lib/http1.h b/third_party/curl/lib/http1.h new file mode 100644 index 0000000..2de302f --- /dev/null +++ b/third_party/curl/lib/http1.h @@ -0,0 +1,63 @@ +#ifndef HEADER_CURL_HTTP1_H +#define HEADER_CURL_HTTP1_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_HTTP +#include "bufq.h" +#include "http.h" + +#define H1_PARSE_OPT_NONE (0) +#define H1_PARSE_OPT_STRICT (1 << 0) + +#define H1_PARSE_DEFAULT_MAX_LINE_LEN DYN_HTTP_REQUEST + +struct h1_req_parser { + struct httpreq *req; + struct dynbuf scratch; + size_t scratch_skip; + const char *line; + size_t max_line_len; + size_t line_len; + bool done; +}; + +void Curl_h1_req_parse_init(struct h1_req_parser *parser, size_t max_line_len); +void Curl_h1_req_parse_free(struct h1_req_parser *parser); + +ssize_t Curl_h1_req_parse_read(struct h1_req_parser *parser, + const char *buf, size_t buflen, + const char *scheme_default, int options, + CURLcode *err); + +CURLcode Curl_h1_req_dprint(const struct httpreq *req, + struct dynbuf *dbuf); + +CURLcode Curl_h1_req_write_head(struct httpreq *req, int http_minor, + struct dynbuf *dbuf); + +#endif /* !CURL_DISABLE_HTTP */ +#endif /* HEADER_CURL_HTTP1_H */ diff --git a/third_party/curl/lib/http2.c b/third_party/curl/lib/http2.c new file mode 100644 index 0000000..f0f7b56 --- /dev/null +++ b/third_party/curl/lib/http2.c @@ -0,0 +1,2875 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_NGHTTP2 +#include +#include +#include "urldata.h" +#include "bufq.h" +#include "hash.h" +#include "http1.h" +#include "http2.h" +#include "http.h" +#include "sendf.h" +#include "select.h" +#include "curl_base64.h" +#include "strcase.h" +#include "multiif.h" +#include "url.h" +#include "urlapi-int.h" +#include "cfilters.h" +#include "connect.h" +#include "rand.h" +#include "strtoofft.h" +#include "strdup.h" +#include "transfer.h" +#include "dynbuf.h" +#include "headers.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if (NGHTTP2_VERSION_NUM < 0x010c00) +#error too old nghttp2 version, upgrade! +#endif + +#ifdef CURL_DISABLE_VERBOSE_STRINGS +#define nghttp2_session_callbacks_set_error_callback(x,y) +#endif + +#if (NGHTTP2_VERSION_NUM >= 0x010c00) +#define NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE 1 +#endif + + +/* buffer dimensioning: + * use 16K as chunk size, as that fits H2 DATA frames well */ +#define H2_CHUNK_SIZE (16 * 1024) +/* this is how much we want "in flight" for a stream */ +#define H2_STREAM_WINDOW_SIZE (10 * 1024 * 1024) +/* on receiving from TLS, we prep for holding a full stream window */ +#define H2_NW_RECV_CHUNKS (H2_STREAM_WINDOW_SIZE / H2_CHUNK_SIZE) +/* on send into TLS, we just want to accumulate small frames */ +#define H2_NW_SEND_CHUNKS 1 +/* stream recv/send chunks are a result of window / chunk sizes */ +#define H2_STREAM_RECV_CHUNKS (H2_STREAM_WINDOW_SIZE / H2_CHUNK_SIZE) +/* keep smaller stream upload buffer (default h2 window size) to have + * our progress bars and "upload done" reporting closer to reality */ +#define H2_STREAM_SEND_CHUNKS ((64 * 1024) / H2_CHUNK_SIZE) +/* spare chunks we keep for a full window */ +#define H2_STREAM_POOL_SPARES (H2_STREAM_WINDOW_SIZE / H2_CHUNK_SIZE) + +/* We need to accommodate the max number of streams with their window + * sizes on the overall connection. Streams might become PAUSED which + * will block their received QUOTA in the connection window. And if we + * run out of space, the server is blocked from sending us any data. + * See #10988 for an issue with this. */ +#define HTTP2_HUGE_WINDOW_SIZE (100 * H2_STREAM_WINDOW_SIZE) + +#define H2_SETTINGS_IV_LEN 3 +#define H2_BINSETTINGS_LEN 80 + +static int populate_settings(nghttp2_settings_entry *iv, + struct Curl_easy *data) +{ + iv[0].settings_id = NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS; + iv[0].value = Curl_multi_max_concurrent_streams(data->multi); + + iv[1].settings_id = NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; + iv[1].value = H2_STREAM_WINDOW_SIZE; + + iv[2].settings_id = NGHTTP2_SETTINGS_ENABLE_PUSH; + iv[2].value = data->multi->push_cb != NULL; + + return 3; +} + +static ssize_t populate_binsettings(uint8_t *binsettings, + struct Curl_easy *data) +{ + nghttp2_settings_entry iv[H2_SETTINGS_IV_LEN]; + int ivlen; + + ivlen = populate_settings(iv, data); + /* this returns number of bytes it wrote or a negative number on error. */ + return nghttp2_pack_settings_payload(binsettings, H2_BINSETTINGS_LEN, + iv, ivlen); +} + +struct cf_h2_ctx { + nghttp2_session *h2; + /* The easy handle used in the current filter call, cleared at return */ + struct cf_call_data call_data; + + struct bufq inbufq; /* network input */ + struct bufq outbufq; /* network output */ + struct bufc_pool stream_bufcp; /* spares for stream buffers */ + struct dynbuf scratch; /* scratch buffer for temp use */ + + struct Curl_hash streams; /* hash of `data->id` to `h2_stream_ctx` */ + size_t drain_total; /* sum of all stream's UrlState drain */ + uint32_t max_concurrent_streams; + int32_t goaway_error; + int32_t last_stream_id; + BIT(conn_closed); + BIT(goaway); + BIT(enable_push); + BIT(nw_out_blocked); +}; + +/* How to access `call_data` from a cf_h2 filter */ +#undef CF_CTX_CALL_DATA +#define CF_CTX_CALL_DATA(cf) \ + ((struct cf_h2_ctx *)(cf)->ctx)->call_data + +static void cf_h2_ctx_clear(struct cf_h2_ctx *ctx) +{ + struct cf_call_data save = ctx->call_data; + + if(ctx->h2) { + nghttp2_session_del(ctx->h2); + } + Curl_bufq_free(&ctx->inbufq); + Curl_bufq_free(&ctx->outbufq); + Curl_bufcp_free(&ctx->stream_bufcp); + Curl_dyn_free(&ctx->scratch); + Curl_hash_clean(&ctx->streams); + Curl_hash_destroy(&ctx->streams); + memset(ctx, 0, sizeof(*ctx)); + ctx->call_data = save; +} + +static void cf_h2_ctx_free(struct cf_h2_ctx *ctx) +{ + if(ctx) { + cf_h2_ctx_clear(ctx); + free(ctx); + } +} + +static CURLcode h2_progress_egress(struct Curl_cfilter *cf, + struct Curl_easy *data); + +/** + * All about the H2 internals of a stream + */ +struct h2_stream_ctx { + struct bufq recvbuf; /* response buffer */ + struct bufq sendbuf; /* request buffer */ + struct h1_req_parser h1; /* parsing the request */ + struct dynhds resp_trailers; /* response trailer fields */ + size_t resp_hds_len; /* amount of response header bytes in recvbuf */ + size_t upload_blocked_len; + curl_off_t upload_left; /* number of request bytes left to upload */ + curl_off_t nrcvd_data; /* number of DATA bytes received */ + + char **push_headers; /* allocated array */ + size_t push_headers_used; /* number of entries filled in */ + size_t push_headers_alloc; /* number of entries allocated */ + + int status_code; /* HTTP response status code */ + uint32_t error; /* stream error code */ + CURLcode xfer_result; /* Result of writing out response */ + uint32_t local_window_size; /* the local recv window size */ + int32_t id; /* HTTP/2 protocol identifier for stream */ + BIT(resp_hds_complete); /* we have a complete, final response */ + BIT(closed); /* TRUE on stream close */ + BIT(reset); /* TRUE on stream reset */ + BIT(close_handled); /* TRUE if stream closure is handled by libcurl */ + BIT(bodystarted); + BIT(send_closed); /* transfer is done sending, we might have still + buffered data in stream->sendbuf to upload. */ +}; + +#define H2_STREAM_CTX(ctx,data) ((struct h2_stream_ctx *)(\ + data? Curl_hash_offt_get(&(ctx)->streams, (data)->id) : NULL)) + +static struct h2_stream_ctx *h2_stream_ctx_create(struct cf_h2_ctx *ctx) +{ + struct h2_stream_ctx *stream; + + (void)ctx; + stream = calloc(1, sizeof(*stream)); + if(!stream) + return NULL; + + stream->id = -1; + Curl_bufq_initp(&stream->sendbuf, &ctx->stream_bufcp, + H2_STREAM_SEND_CHUNKS, BUFQ_OPT_NONE); + Curl_h1_req_parse_init(&stream->h1, H1_PARSE_DEFAULT_MAX_LINE_LEN); + Curl_dynhds_init(&stream->resp_trailers, 0, DYN_HTTP_REQUEST); + stream->resp_hds_len = 0; + stream->bodystarted = FALSE; + stream->status_code = -1; + stream->closed = FALSE; + stream->close_handled = FALSE; + stream->error = NGHTTP2_NO_ERROR; + stream->local_window_size = H2_STREAM_WINDOW_SIZE; + stream->upload_left = 0; + stream->nrcvd_data = 0; + return stream; +} + +static void free_push_headers(struct h2_stream_ctx *stream) +{ + size_t i; + for(i = 0; ipush_headers_used; i++) + free(stream->push_headers[i]); + Curl_safefree(stream->push_headers); + stream->push_headers_used = 0; +} + +static void h2_stream_ctx_free(struct h2_stream_ctx *stream) +{ + Curl_bufq_free(&stream->sendbuf); + Curl_h1_req_parse_free(&stream->h1); + Curl_dynhds_free(&stream->resp_trailers); + free_push_headers(stream); + free(stream); +} + +static void h2_stream_hash_free(void *stream) +{ + DEBUGASSERT(stream); + h2_stream_ctx_free((struct h2_stream_ctx *)stream); +} + +/* + * Mark this transfer to get "drained". + */ +static void drain_stream(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h2_stream_ctx *stream) +{ + unsigned char bits; + + (void)cf; + bits = CURL_CSELECT_IN; + if(!stream->send_closed && + (stream->upload_left || stream->upload_blocked_len)) + bits |= CURL_CSELECT_OUT; + if(data->state.select_bits != bits) { + CURL_TRC_CF(data, cf, "[%d] DRAIN select_bits=%x", + stream->id, bits); + data->state.select_bits = bits; + Curl_expire(data, 0, EXPIRE_RUN_NOW); + } +} + +static CURLcode http2_data_setup(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h2_stream_ctx **pstream) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream; + + (void)cf; + DEBUGASSERT(data); + if(!data->req.p.http) { + failf(data, "initialization failure, transfer not http initialized"); + return CURLE_FAILED_INIT; + } + stream = H2_STREAM_CTX(ctx, data); + if(stream) { + *pstream = stream; + return CURLE_OK; + } + + stream = h2_stream_ctx_create(ctx); + if(!stream) + return CURLE_OUT_OF_MEMORY; + + if(!Curl_hash_offt_set(&ctx->streams, data->id, stream)) { + h2_stream_ctx_free(stream); + return CURLE_OUT_OF_MEMORY; + } + + *pstream = stream; + return CURLE_OK; +} + +static void http2_data_done(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + + DEBUGASSERT(ctx); + if(!stream) + return; + + if(ctx->h2) { + bool flush_egress = FALSE; + /* returns error if stream not known, which is fine here */ + (void)nghttp2_session_set_stream_user_data(ctx->h2, stream->id, NULL); + + if(!stream->closed && stream->id > 0) { + /* RST_STREAM */ + CURL_TRC_CF(data, cf, "[%d] premature DATA_DONE, RST stream", + stream->id); + stream->closed = TRUE; + stream->reset = TRUE; + stream->send_closed = TRUE; + nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE, + stream->id, NGHTTP2_STREAM_CLOSED); + flush_egress = TRUE; + } + + if(flush_egress) + nghttp2_session_send(ctx->h2); + } + + Curl_hash_offt_remove(&ctx->streams, data->id); +} + +static int h2_client_new(struct Curl_cfilter *cf, + nghttp2_session_callbacks *cbs) +{ + struct cf_h2_ctx *ctx = cf->ctx; + nghttp2_option *o; + + int rc = nghttp2_option_new(&o); + if(rc) + return rc; + /* We handle window updates ourself to enforce buffer limits */ + nghttp2_option_set_no_auto_window_update(o, 1); +#if NGHTTP2_VERSION_NUM >= 0x013200 + /* with 1.50.0 */ + /* turn off RFC 9113 leading and trailing white spaces validation against + HTTP field value. */ + nghttp2_option_set_no_rfc9113_leading_and_trailing_ws_validation(o, 1); +#endif + rc = nghttp2_session_client_new2(&ctx->h2, cbs, cf, o); + nghttp2_option_del(o); + return rc; +} + +static ssize_t nw_in_reader(void *reader_ctx, + unsigned char *buf, size_t buflen, + CURLcode *err) +{ + struct Curl_cfilter *cf = reader_ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + + return Curl_conn_cf_recv(cf->next, data, (char *)buf, buflen, err); +} + +static ssize_t nw_out_writer(void *writer_ctx, + const unsigned char *buf, size_t buflen, + CURLcode *err) +{ + struct Curl_cfilter *cf = writer_ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + + if(data) { + ssize_t nwritten = Curl_conn_cf_send(cf->next, data, + (const char *)buf, buflen, err); + if(nwritten > 0) + CURL_TRC_CF(data, cf, "[0] egress: wrote %zd bytes", nwritten); + return nwritten; + } + return 0; +} + +static ssize_t send_callback(nghttp2_session *h2, + const uint8_t *mem, size_t length, int flags, + void *userp); +static int on_frame_recv(nghttp2_session *session, const nghttp2_frame *frame, + void *userp); +#ifndef CURL_DISABLE_VERBOSE_STRINGS +static int on_frame_send(nghttp2_session *session, const nghttp2_frame *frame, + void *userp); +#endif +static int on_data_chunk_recv(nghttp2_session *session, uint8_t flags, + int32_t stream_id, + const uint8_t *mem, size_t len, void *userp); +static int on_stream_close(nghttp2_session *session, int32_t stream_id, + uint32_t error_code, void *userp); +static int on_begin_headers(nghttp2_session *session, + const nghttp2_frame *frame, void *userp); +static int on_header(nghttp2_session *session, const nghttp2_frame *frame, + const uint8_t *name, size_t namelen, + const uint8_t *value, size_t valuelen, + uint8_t flags, + void *userp); +static int error_callback(nghttp2_session *session, const char *msg, + size_t len, void *userp); + +/* + * Initialize the cfilter context + */ +static CURLcode cf_h2_ctx_init(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool via_h1_upgrade) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream; + CURLcode result = CURLE_OUT_OF_MEMORY; + int rc; + nghttp2_session_callbacks *cbs = NULL; + + DEBUGASSERT(!ctx->h2); + Curl_bufcp_init(&ctx->stream_bufcp, H2_CHUNK_SIZE, H2_STREAM_POOL_SPARES); + Curl_bufq_initp(&ctx->inbufq, &ctx->stream_bufcp, H2_NW_RECV_CHUNKS, 0); + Curl_bufq_initp(&ctx->outbufq, &ctx->stream_bufcp, H2_NW_SEND_CHUNKS, 0); + Curl_dyn_init(&ctx->scratch, CURL_MAX_HTTP_HEADER); + Curl_hash_offt_init(&ctx->streams, 63, h2_stream_hash_free); + ctx->last_stream_id = 2147483647; + + rc = nghttp2_session_callbacks_new(&cbs); + if(rc) { + failf(data, "Couldn't initialize nghttp2 callbacks"); + goto out; + } + + nghttp2_session_callbacks_set_send_callback(cbs, send_callback); + nghttp2_session_callbacks_set_on_frame_recv_callback(cbs, on_frame_recv); +#ifndef CURL_DISABLE_VERBOSE_STRINGS + nghttp2_session_callbacks_set_on_frame_send_callback(cbs, on_frame_send); +#endif + nghttp2_session_callbacks_set_on_data_chunk_recv_callback( + cbs, on_data_chunk_recv); + nghttp2_session_callbacks_set_on_stream_close_callback(cbs, on_stream_close); + nghttp2_session_callbacks_set_on_begin_headers_callback( + cbs, on_begin_headers); + nghttp2_session_callbacks_set_on_header_callback(cbs, on_header); + nghttp2_session_callbacks_set_error_callback(cbs, error_callback); + + /* The nghttp2 session is not yet setup, do it */ + rc = h2_client_new(cf, cbs); + if(rc) { + failf(data, "Couldn't initialize nghttp2"); + goto out; + } + ctx->max_concurrent_streams = DEFAULT_MAX_CONCURRENT_STREAMS; + + if(via_h1_upgrade) { + /* HTTP/1.1 Upgrade issued. H2 Settings have already been submitted + * in the H1 request and we upgrade from there. This stream + * is opened implicitly as #1. */ + uint8_t binsettings[H2_BINSETTINGS_LEN]; + ssize_t binlen; /* length of the binsettings data */ + + binlen = populate_binsettings(binsettings, data); + if(binlen <= 0) { + failf(data, "nghttp2 unexpectedly failed on pack_settings_payload"); + result = CURLE_FAILED_INIT; + goto out; + } + + result = http2_data_setup(cf, data, &stream); + if(result) + goto out; + DEBUGASSERT(stream); + stream->id = 1; + /* queue SETTINGS frame (again) */ + rc = nghttp2_session_upgrade2(ctx->h2, binsettings, binlen, + data->state.httpreq == HTTPREQ_HEAD, + NULL); + if(rc) { + failf(data, "nghttp2_session_upgrade2() failed: %s(%d)", + nghttp2_strerror(rc), rc); + result = CURLE_HTTP2; + goto out; + } + + rc = nghttp2_session_set_stream_user_data(ctx->h2, stream->id, + data); + if(rc) { + infof(data, "http/2: failed to set user_data for stream %u", + stream->id); + DEBUGASSERT(0); + } + CURL_TRC_CF(data, cf, "created session via Upgrade"); + } + else { + nghttp2_settings_entry iv[H2_SETTINGS_IV_LEN]; + int ivlen; + + ivlen = populate_settings(iv, data); + rc = nghttp2_submit_settings(ctx->h2, NGHTTP2_FLAG_NONE, + iv, ivlen); + if(rc) { + failf(data, "nghttp2_submit_settings() failed: %s(%d)", + nghttp2_strerror(rc), rc); + result = CURLE_HTTP2; + goto out; + } + } + + rc = nghttp2_session_set_local_window_size(ctx->h2, NGHTTP2_FLAG_NONE, 0, + HTTP2_HUGE_WINDOW_SIZE); + if(rc) { + failf(data, "nghttp2_session_set_local_window_size() failed: %s(%d)", + nghttp2_strerror(rc), rc); + result = CURLE_HTTP2; + goto out; + } + + /* all set, traffic will be send on connect */ + result = CURLE_OK; + CURL_TRC_CF(data, cf, "[0] created h2 session%s", + via_h1_upgrade? " (via h1 upgrade)" : ""); + +out: + if(cbs) + nghttp2_session_callbacks_del(cbs); + return result; +} + +/* + * Returns nonzero if current HTTP/2 session should be closed. + */ +static int should_close_session(struct cf_h2_ctx *ctx) +{ + return ctx->drain_total == 0 && !nghttp2_session_want_read(ctx->h2) && + !nghttp2_session_want_write(ctx->h2); +} + +/* + * Processes pending input left in network input buffer. + * This function returns 0 if it succeeds, or -1 and error code will + * be assigned to *err. + */ +static int h2_process_pending_input(struct Curl_cfilter *cf, + struct Curl_easy *data, + CURLcode *err) +{ + struct cf_h2_ctx *ctx = cf->ctx; + const unsigned char *buf; + size_t blen; + ssize_t rv; + + while(Curl_bufq_peek(&ctx->inbufq, &buf, &blen)) { + + rv = nghttp2_session_mem_recv(ctx->h2, (const uint8_t *)buf, blen); + if(rv < 0) { + failf(data, + "process_pending_input: nghttp2_session_mem_recv() returned " + "%zd:%s", rv, nghttp2_strerror((int)rv)); + *err = CURLE_RECV_ERROR; + return -1; + } + Curl_bufq_skip(&ctx->inbufq, (size_t)rv); + if(Curl_bufq_is_empty(&ctx->inbufq)) { + break; + } + else { + CURL_TRC_CF(data, cf, "process_pending_input: %zu bytes left " + "in connection buffer", Curl_bufq_len(&ctx->inbufq)); + } + } + + if(nghttp2_session_check_request_allowed(ctx->h2) == 0) { + /* No more requests are allowed in the current session, so + the connection may not be reused. This is set when a + GOAWAY frame has been received or when the limit of stream + identifiers has been reached. */ + connclose(cf->conn, "http/2: No new requests allowed"); + } + + return 0; +} + +/* + * The server may send us data at any point (e.g. PING frames). Therefore, + * we cannot assume that an HTTP/2 socket is dead just because it is readable. + * + * Check the lower filters first and, if successful, peek at the socket + * and distinguish between closed and data. + */ +static bool http2_connisalive(struct Curl_cfilter *cf, struct Curl_easy *data, + bool *input_pending) +{ + struct cf_h2_ctx *ctx = cf->ctx; + bool alive = TRUE; + + *input_pending = FALSE; + if(!cf->next || !cf->next->cft->is_alive(cf->next, data, input_pending)) + return FALSE; + + if(*input_pending) { + /* This happens before we've sent off a request and the connection is + not in use by any other transfer, there shouldn't be any data here, + only "protocol frames" */ + CURLcode result; + ssize_t nread = -1; + + *input_pending = FALSE; + nread = Curl_bufq_slurp(&ctx->inbufq, nw_in_reader, cf, &result); + if(nread != -1) { + CURL_TRC_CF(data, cf, "%zd bytes stray data read before trying " + "h2 connection", nread); + if(h2_process_pending_input(cf, data, &result) < 0) + /* immediate error, considered dead */ + alive = FALSE; + else { + alive = !should_close_session(ctx); + } + } + else if(result != CURLE_AGAIN) { + /* the read failed so let's say this is dead anyway */ + alive = FALSE; + } + } + + return alive; +} + +static CURLcode http2_send_ping(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + int rc; + + rc = nghttp2_submit_ping(ctx->h2, 0, ZERO_NULL); + if(rc) { + failf(data, "nghttp2_submit_ping() failed: %s(%d)", + nghttp2_strerror(rc), rc); + return CURLE_HTTP2; + } + + rc = nghttp2_session_send(ctx->h2); + if(rc) { + failf(data, "nghttp2_session_send() failed: %s(%d)", + nghttp2_strerror(rc), rc); + return CURLE_SEND_ERROR; + } + return CURLE_OK; +} + +/* + * Store nghttp2 version info in this buffer. + */ +void Curl_http2_ver(char *p, size_t len) +{ + nghttp2_info *h2 = nghttp2_version(0); + (void)msnprintf(p, len, "nghttp2/%s", h2->version_str); +} + +static CURLcode nw_out_flush(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + ssize_t nwritten; + CURLcode result; + + (void)data; + if(Curl_bufq_is_empty(&ctx->outbufq)) + return CURLE_OK; + + nwritten = Curl_bufq_pass(&ctx->outbufq, nw_out_writer, cf, &result); + if(nwritten < 0) { + if(result == CURLE_AGAIN) { + CURL_TRC_CF(data, cf, "flush nw send buffer(%zu) -> EAGAIN", + Curl_bufq_len(&ctx->outbufq)); + ctx->nw_out_blocked = 1; + } + return result; + } + return Curl_bufq_is_empty(&ctx->outbufq)? CURLE_OK: CURLE_AGAIN; +} + +/* + * The implementation of nghttp2_send_callback type. Here we write |data| with + * size |length| to the network and return the number of bytes actually + * written. See the documentation of nghttp2_send_callback for the details. + */ +static ssize_t send_callback(nghttp2_session *h2, + const uint8_t *buf, size_t blen, int flags, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + ssize_t nwritten; + CURLcode result = CURLE_OK; + + (void)h2; + (void)flags; + DEBUGASSERT(data); + + nwritten = Curl_bufq_write_pass(&ctx->outbufq, buf, blen, + nw_out_writer, cf, &result); + if(nwritten < 0) { + if(result == CURLE_AGAIN) { + ctx->nw_out_blocked = 1; + return NGHTTP2_ERR_WOULDBLOCK; + } + failf(data, "Failed sending HTTP2 data"); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + + if(!nwritten) { + ctx->nw_out_blocked = 1; + return NGHTTP2_ERR_WOULDBLOCK; + } + return nwritten; +} + + +/* We pass a pointer to this struct in the push callback, but the contents of + the struct are hidden from the user. */ +struct curl_pushheaders { + struct Curl_easy *data; + struct h2_stream_ctx *stream; + const nghttp2_push_promise *frame; +}; + +/* + * push header access function. Only to be used from within the push callback + */ +char *curl_pushheader_bynum(struct curl_pushheaders *h, size_t num) +{ + /* Verify that we got a good easy handle in the push header struct, mostly to + detect rubbish input fast(er). */ + if(!h || !GOOD_EASY_HANDLE(h->data)) + return NULL; + else { + if(h->stream && num < h->stream->push_headers_used) + return h->stream->push_headers[num]; + } + return NULL; +} + +/* + * push header access function. Only to be used from within the push callback + */ +char *curl_pushheader_byname(struct curl_pushheaders *h, const char *header) +{ + struct h2_stream_ctx *stream; + size_t len; + size_t i; + /* Verify that we got a good easy handle in the push header struct, + mostly to detect rubbish input fast(er). Also empty header name + is just a rubbish too. We have to allow ":" at the beginning of + the header, but header == ":" must be rejected. If we have ':' in + the middle of header, it could be matched in middle of the value, + this is because we do prefix match.*/ + if(!h || !GOOD_EASY_HANDLE(h->data) || !header || !header[0] || + !strcmp(header, ":") || strchr(header + 1, ':')) + return NULL; + + stream = h->stream; + if(!stream) + return NULL; + + len = strlen(header); + for(i = 0; ipush_headers_used; i++) { + if(!strncmp(header, stream->push_headers[i], len)) { + /* sub-match, make sure that it is followed by a colon */ + if(stream->push_headers[i][len] != ':') + continue; + return &stream->push_headers[i][len + 1]; + } + } + return NULL; +} + +static struct Curl_easy *h2_duphandle(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct Curl_easy *second = curl_easy_duphandle(data); + if(second) { + /* setup the request struct */ + struct HTTP *http = calloc(1, sizeof(struct HTTP)); + if(!http) { + (void)Curl_close(&second); + } + else { + struct h2_stream_ctx *second_stream; + + second->req.p.http = http; + http2_data_setup(cf, second, &second_stream); + second->state.priority.weight = data->state.priority.weight; + } + } + return second; +} + +static int set_transfer_url(struct Curl_easy *data, + struct curl_pushheaders *hp) +{ + const char *v; + CURLUcode uc; + char *url = NULL; + int rc = 0; + CURLU *u = curl_url(); + + if(!u) + return 5; + + v = curl_pushheader_byname(hp, HTTP_PSEUDO_SCHEME); + if(v) { + uc = curl_url_set(u, CURLUPART_SCHEME, v, 0); + if(uc) { + rc = 1; + goto fail; + } + } + + v = curl_pushheader_byname(hp, HTTP_PSEUDO_AUTHORITY); + if(v) { + uc = Curl_url_set_authority(u, v); + if(uc) { + rc = 2; + goto fail; + } + } + + v = curl_pushheader_byname(hp, HTTP_PSEUDO_PATH); + if(v) { + uc = curl_url_set(u, CURLUPART_PATH, v, 0); + if(uc) { + rc = 3; + goto fail; + } + } + + uc = curl_url_get(u, CURLUPART_URL, &url, 0); + if(uc) + rc = 4; +fail: + curl_url_cleanup(u); + if(rc) + return rc; + + if(data->state.url_alloc) + free(data->state.url); + data->state.url_alloc = TRUE; + data->state.url = url; + return 0; +} + +static void discard_newhandle(struct Curl_cfilter *cf, + struct Curl_easy *newhandle) +{ + if(newhandle->req.p.http) { + http2_data_done(cf, newhandle); + } + (void)Curl_close(&newhandle); +} + +static int push_promise(struct Curl_cfilter *cf, + struct Curl_easy *data, + const nghttp2_push_promise *frame) +{ + struct cf_h2_ctx *ctx = cf->ctx; + int rv; /* one of the CURL_PUSH_* defines */ + + CURL_TRC_CF(data, cf, "[%d] PUSH_PROMISE received", + frame->promised_stream_id); + if(data->multi->push_cb) { + struct h2_stream_ctx *stream; + struct h2_stream_ctx *newstream; + struct curl_pushheaders heads; + CURLMcode rc; + CURLcode result; + /* clone the parent */ + struct Curl_easy *newhandle = h2_duphandle(cf, data); + if(!newhandle) { + infof(data, "failed to duplicate handle"); + rv = CURL_PUSH_DENY; /* FAIL HARD */ + goto fail; + } + + /* ask the application */ + CURL_TRC_CF(data, cf, "Got PUSH_PROMISE, ask application"); + + stream = H2_STREAM_CTX(ctx, data); + if(!stream) { + failf(data, "Internal NULL stream"); + discard_newhandle(cf, newhandle); + rv = CURL_PUSH_DENY; + goto fail; + } + + heads.data = data; + heads.stream = stream; + heads.frame = frame; + + rv = set_transfer_url(newhandle, &heads); + if(rv) { + discard_newhandle(cf, newhandle); + rv = CURL_PUSH_DENY; + goto fail; + } + + result = http2_data_setup(cf, newhandle, &newstream); + if(result) { + failf(data, "error setting up stream: %d", result); + discard_newhandle(cf, newhandle); + rv = CURL_PUSH_DENY; + goto fail; + } + DEBUGASSERT(stream); + + Curl_set_in_callback(data, true); + rv = data->multi->push_cb(data, newhandle, + stream->push_headers_used, &heads, + data->multi->push_userp); + Curl_set_in_callback(data, false); + + /* free the headers again */ + free_push_headers(stream); + + if(rv) { + DEBUGASSERT((rv > CURL_PUSH_OK) && (rv <= CURL_PUSH_ERROROUT)); + /* denied, kill off the new handle again */ + discard_newhandle(cf, newhandle); + goto fail; + } + + newstream->id = frame->promised_stream_id; + newhandle->req.maxdownload = -1; + newhandle->req.size = -1; + + /* approved, add to the multi handle and immediately switch to PERFORM + state with the given connection !*/ + rc = Curl_multi_add_perform(data->multi, newhandle, cf->conn); + if(rc) { + infof(data, "failed to add handle to multi"); + discard_newhandle(cf, newhandle); + rv = CURL_PUSH_DENY; + goto fail; + } + + rv = nghttp2_session_set_stream_user_data(ctx->h2, + newstream->id, + newhandle); + if(rv) { + infof(data, "failed to set user_data for stream %u", + newstream->id); + DEBUGASSERT(0); + rv = CURL_PUSH_DENY; + goto fail; + } + } + else { + CURL_TRC_CF(data, cf, "Got PUSH_PROMISE, ignore it"); + rv = CURL_PUSH_DENY; + } +fail: + return rv; +} + +static void h2_xfer_write_resp_hd(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h2_stream_ctx *stream, + const char *buf, size_t blen, bool eos) +{ + + /* If we already encountered an error, skip further writes */ + if(!stream->xfer_result) { + stream->xfer_result = Curl_xfer_write_resp_hd(data, buf, blen, eos); + if(stream->xfer_result) + CURL_TRC_CF(data, cf, "[%d] error %d writing %zu bytes of headers", + stream->id, stream->xfer_result, blen); + } +} + +static void h2_xfer_write_resp(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h2_stream_ctx *stream, + const char *buf, size_t blen, bool eos) +{ + + /* If we already encountered an error, skip further writes */ + if(!stream->xfer_result) + stream->xfer_result = Curl_xfer_write_resp(data, buf, blen, eos); + /* If the transfer write is errored, we do not want any more data */ + if(stream->xfer_result) { + struct cf_h2_ctx *ctx = cf->ctx; + CURL_TRC_CF(data, cf, "[%d] error %d writing %zu bytes of data, " + "RST-ing stream", + stream->id, stream->xfer_result, blen); + nghttp2_submit_rst_stream(ctx->h2, 0, stream->id, + NGHTTP2_ERR_CALLBACK_FAILURE); + } +} + +static CURLcode on_stream_frame(struct Curl_cfilter *cf, + struct Curl_easy *data, + const nghttp2_frame *frame) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + int32_t stream_id = frame->hd.stream_id; + int rv; + + if(!stream) { + CURL_TRC_CF(data, cf, "[%d] No stream_ctx set", stream_id); + return CURLE_FAILED_INIT; + } + + switch(frame->hd.type) { + case NGHTTP2_DATA: + CURL_TRC_CF(data, cf, "[%d] DATA, window=%d/%d", + stream_id, + nghttp2_session_get_stream_effective_recv_data_length( + ctx->h2, stream->id), + nghttp2_session_get_stream_effective_local_window_size( + ctx->h2, stream->id)); + /* If !body started on this stream, then receiving DATA is illegal. */ + if(!stream->bodystarted) { + rv = nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE, + stream_id, NGHTTP2_PROTOCOL_ERROR); + + if(nghttp2_is_fatal(rv)) { + return CURLE_RECV_ERROR; + } + } + if(frame->hd.flags & NGHTTP2_FLAG_END_STREAM) { + drain_stream(cf, data, stream); + } + break; + case NGHTTP2_HEADERS: + if(stream->bodystarted) { + /* Only valid HEADERS after body started is trailer HEADERS. We + buffer them in on_header callback. */ + break; + } + + /* nghttp2 guarantees that :status is received, and we store it to + stream->status_code. Fuzzing has proven this can still be reached + without status code having been set. */ + if(stream->status_code == -1) + return CURLE_RECV_ERROR; + + /* Only final status code signals the end of header */ + if(stream->status_code / 100 != 1) { + stream->bodystarted = TRUE; + stream->status_code = -1; + } + + h2_xfer_write_resp_hd(cf, data, stream, STRCONST("\r\n"), stream->closed); + + if(stream->status_code / 100 != 1) { + stream->resp_hds_complete = TRUE; + } + drain_stream(cf, data, stream); + break; + case NGHTTP2_PUSH_PROMISE: + rv = push_promise(cf, data, &frame->push_promise); + if(rv) { /* deny! */ + DEBUGASSERT((rv > CURL_PUSH_OK) && (rv <= CURL_PUSH_ERROROUT)); + rv = nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE, + frame->push_promise.promised_stream_id, + NGHTTP2_CANCEL); + if(nghttp2_is_fatal(rv)) + return CURLE_SEND_ERROR; + else if(rv == CURL_PUSH_ERROROUT) { + CURL_TRC_CF(data, cf, "[%d] fail in PUSH_PROMISE received", + stream_id); + return CURLE_RECV_ERROR; + } + } + break; + case NGHTTP2_RST_STREAM: + stream->closed = TRUE; + if(frame->rst_stream.error_code) { + stream->reset = TRUE; + } + stream->send_closed = TRUE; + drain_stream(cf, data, stream); + break; + case NGHTTP2_WINDOW_UPDATE: + if(CURL_WANT_SEND(data)) { + drain_stream(cf, data, stream); + } + break; + default: + break; + } + return CURLE_OK; +} + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +static int fr_print(const nghttp2_frame *frame, char *buffer, size_t blen) +{ + switch(frame->hd.type) { + case NGHTTP2_DATA: { + return msnprintf(buffer, blen, + "FRAME[DATA, len=%d, eos=%d, padlen=%d]", + (int)frame->hd.length, + !!(frame->hd.flags & NGHTTP2_FLAG_END_STREAM), + (int)frame->data.padlen); + } + case NGHTTP2_HEADERS: { + return msnprintf(buffer, blen, + "FRAME[HEADERS, len=%d, hend=%d, eos=%d]", + (int)frame->hd.length, + !!(frame->hd.flags & NGHTTP2_FLAG_END_HEADERS), + !!(frame->hd.flags & NGHTTP2_FLAG_END_STREAM)); + } + case NGHTTP2_PRIORITY: { + return msnprintf(buffer, blen, + "FRAME[PRIORITY, len=%d, flags=%d]", + (int)frame->hd.length, frame->hd.flags); + } + case NGHTTP2_RST_STREAM: { + return msnprintf(buffer, blen, + "FRAME[RST_STREAM, len=%d, flags=%d, error=%u]", + (int)frame->hd.length, frame->hd.flags, + frame->rst_stream.error_code); + } + case NGHTTP2_SETTINGS: { + if(frame->hd.flags & NGHTTP2_FLAG_ACK) { + return msnprintf(buffer, blen, "FRAME[SETTINGS, ack=1]"); + } + return msnprintf(buffer, blen, + "FRAME[SETTINGS, len=%d]", (int)frame->hd.length); + } + case NGHTTP2_PUSH_PROMISE: { + return msnprintf(buffer, blen, + "FRAME[PUSH_PROMISE, len=%d, hend=%d]", + (int)frame->hd.length, + !!(frame->hd.flags & NGHTTP2_FLAG_END_HEADERS)); + } + case NGHTTP2_PING: { + return msnprintf(buffer, blen, + "FRAME[PING, len=%d, ack=%d]", + (int)frame->hd.length, + frame->hd.flags&NGHTTP2_FLAG_ACK); + } + case NGHTTP2_GOAWAY: { + char scratch[128]; + size_t s_len = sizeof(scratch)/sizeof(scratch[0]); + size_t len = (frame->goaway.opaque_data_len < s_len)? + frame->goaway.opaque_data_len : s_len-1; + if(len) + memcpy(scratch, frame->goaway.opaque_data, len); + scratch[len] = '\0'; + return msnprintf(buffer, blen, "FRAME[GOAWAY, error=%d, reason='%s', " + "last_stream=%d]", frame->goaway.error_code, + scratch, frame->goaway.last_stream_id); + } + case NGHTTP2_WINDOW_UPDATE: { + return msnprintf(buffer, blen, + "FRAME[WINDOW_UPDATE, incr=%d]", + frame->window_update.window_size_increment); + } + default: + return msnprintf(buffer, blen, "FRAME[%d, len=%d, flags=%d]", + frame->hd.type, (int)frame->hd.length, + frame->hd.flags); + } +} + +static int on_frame_send(nghttp2_session *session, const nghttp2_frame *frame, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + + (void)session; + DEBUGASSERT(data); + if(data && Curl_trc_cf_is_verbose(cf, data)) { + char buffer[256]; + int len; + len = fr_print(frame, buffer, sizeof(buffer)-1); + buffer[len] = 0; + CURL_TRC_CF(data, cf, "[%d] -> %s", frame->hd.stream_id, buffer); + } + return 0; +} +#endif /* !CURL_DISABLE_VERBOSE_STRINGS */ + +static int on_frame_recv(nghttp2_session *session, const nghttp2_frame *frame, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf), *data_s; + int32_t stream_id = frame->hd.stream_id; + + DEBUGASSERT(data); +#ifndef CURL_DISABLE_VERBOSE_STRINGS + if(Curl_trc_cf_is_verbose(cf, data)) { + char buffer[256]; + int len; + len = fr_print(frame, buffer, sizeof(buffer)-1); + buffer[len] = 0; + CURL_TRC_CF(data, cf, "[%d] <- %s",frame->hd.stream_id, buffer); + } +#endif /* !CURL_DISABLE_VERBOSE_STRINGS */ + + if(!stream_id) { + /* stream ID zero is for connection-oriented stuff */ + DEBUGASSERT(data); + switch(frame->hd.type) { + case NGHTTP2_SETTINGS: { + if(!(frame->hd.flags & NGHTTP2_FLAG_ACK)) { + uint32_t max_conn = ctx->max_concurrent_streams; + ctx->max_concurrent_streams = nghttp2_session_get_remote_settings( + session, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS); + ctx->enable_push = nghttp2_session_get_remote_settings( + session, NGHTTP2_SETTINGS_ENABLE_PUSH) != 0; + CURL_TRC_CF(data, cf, "[0] MAX_CONCURRENT_STREAMS: %d", + ctx->max_concurrent_streams); + CURL_TRC_CF(data, cf, "[0] ENABLE_PUSH: %s", + ctx->enable_push ? "TRUE" : "false"); + if(data && max_conn != ctx->max_concurrent_streams) { + /* only signal change if the value actually changed */ + CURL_TRC_CF(data, cf, "[0] notify MAX_CONCURRENT_STREAMS: %u", + ctx->max_concurrent_streams); + Curl_multi_connchanged(data->multi); + } + /* Since the initial stream window is 64K, a request might be on HOLD, + * due to exhaustion. The (initial) SETTINGS may announce a much larger + * window and *assume* that we treat this like a WINDOW_UPDATE. Some + * servers send an explicit WINDOW_UPDATE, but not all seem to do that. + * To be safe, we UNHOLD a stream in order not to stall. */ + if(CURL_WANT_SEND(data)) { + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + if(stream) + drain_stream(cf, data, stream); + } + } + break; + } + case NGHTTP2_GOAWAY: + ctx->goaway = TRUE; + ctx->goaway_error = frame->goaway.error_code; + ctx->last_stream_id = frame->goaway.last_stream_id; + if(data) { + infof(data, "received GOAWAY, error=%d, last_stream=%u", + ctx->goaway_error, ctx->last_stream_id); + Curl_multi_connchanged(data->multi); + } + break; + default: + break; + } + return 0; + } + + data_s = nghttp2_session_get_stream_user_data(session, stream_id); + if(!data_s) { + CURL_TRC_CF(data, cf, "[%d] No Curl_easy associated", stream_id); + return 0; + } + + return on_stream_frame(cf, data_s, frame)? NGHTTP2_ERR_CALLBACK_FAILURE : 0; +} + +static int on_data_chunk_recv(nghttp2_session *session, uint8_t flags, + int32_t stream_id, + const uint8_t *mem, size_t len, void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream; + struct Curl_easy *data_s; + (void)flags; + + DEBUGASSERT(stream_id); /* should never be a zero stream ID here */ + DEBUGASSERT(CF_DATA_CURRENT(cf)); + + /* get the stream from the hash based on Stream ID */ + data_s = nghttp2_session_get_stream_user_data(session, stream_id); + if(!data_s) { + /* Receiving a Stream ID not in the hash should not happen - unless + we have aborted a transfer artificially and there were more data + in the pipeline. Silently ignore. */ + CURL_TRC_CF(CF_DATA_CURRENT(cf), cf, "[%d] Data for unknown", + stream_id); + /* consumed explicitly as no one will read it */ + nghttp2_session_consume(session, stream_id, len); + return 0; + } + + stream = H2_STREAM_CTX(ctx, data_s); + if(!stream) + return NGHTTP2_ERR_CALLBACK_FAILURE; + + h2_xfer_write_resp(cf, data_s, stream, (char *)mem, len, FALSE); + + nghttp2_session_consume(ctx->h2, stream_id, len); + stream->nrcvd_data += (curl_off_t)len; + + /* if we receive data for another handle, wake that up */ + drain_stream(cf, data_s, stream); + return 0; +} + +static int on_stream_close(nghttp2_session *session, int32_t stream_id, + uint32_t error_code, void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_ctx *ctx = cf->ctx; + struct Curl_easy *data_s, *call_data = CF_DATA_CURRENT(cf); + struct h2_stream_ctx *stream; + int rv; + (void)session; + + DEBUGASSERT(call_data); + /* get the stream from the hash based on Stream ID, stream ID zero is for + connection-oriented stuff */ + data_s = stream_id? + nghttp2_session_get_stream_user_data(session, stream_id) : NULL; + if(!data_s) { + CURL_TRC_CF(call_data, cf, + "[%d] on_stream_close, no easy set on stream", stream_id); + return 0; + } + if(!GOOD_EASY_HANDLE(data_s)) { + /* nghttp2 still has an easy registered for the stream which has + * been freed be libcurl. This points to a code path that does not + * trigger DONE or DETACH events as it must. */ + CURL_TRC_CF(call_data, cf, + "[%d] on_stream_close, not a GOOD easy on stream", stream_id); + (void)nghttp2_session_set_stream_user_data(session, stream_id, 0); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + stream = H2_STREAM_CTX(ctx, data_s); + if(!stream) { + CURL_TRC_CF(data_s, cf, + "[%d] on_stream_close, GOOD easy but no stream", stream_id); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + + stream->closed = TRUE; + stream->error = error_code; + if(stream->error) { + stream->reset = TRUE; + stream->send_closed = TRUE; + } + + if(stream->error) + CURL_TRC_CF(data_s, cf, "[%d] RESET: %s (err %d)", + stream_id, nghttp2_http2_strerror(error_code), error_code); + else + CURL_TRC_CF(data_s, cf, "[%d] CLOSED", stream_id); + drain_stream(cf, data_s, stream); + + /* remove `data_s` from the nghttp2 stream */ + rv = nghttp2_session_set_stream_user_data(session, stream_id, 0); + if(rv) { + infof(data_s, "http/2: failed to clear user_data for stream %u", + stream_id); + DEBUGASSERT(0); + } + return 0; +} + +static int on_begin_headers(nghttp2_session *session, + const nghttp2_frame *frame, void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream; + struct Curl_easy *data_s = NULL; + + (void)cf; + data_s = nghttp2_session_get_stream_user_data(session, frame->hd.stream_id); + if(!data_s) { + return 0; + } + + if(frame->hd.type != NGHTTP2_HEADERS) { + return 0; + } + + stream = H2_STREAM_CTX(ctx, data_s); + if(!stream || !stream->bodystarted) { + return 0; + } + + return 0; +} + +/* frame->hd.type is either NGHTTP2_HEADERS or NGHTTP2_PUSH_PROMISE */ +static int on_header(nghttp2_session *session, const nghttp2_frame *frame, + const uint8_t *name, size_t namelen, + const uint8_t *value, size_t valuelen, + uint8_t flags, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream; + struct Curl_easy *data_s; + int32_t stream_id = frame->hd.stream_id; + CURLcode result; + (void)flags; + + DEBUGASSERT(stream_id); /* should never be a zero stream ID here */ + + /* get the stream from the hash based on Stream ID */ + data_s = nghttp2_session_get_stream_user_data(session, stream_id); + if(!data_s) + /* Receiving a Stream ID not in the hash should not happen, this is an + internal error more than anything else! */ + return NGHTTP2_ERR_CALLBACK_FAILURE; + + stream = H2_STREAM_CTX(ctx, data_s); + if(!stream) { + failf(data_s, "Internal NULL stream"); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + + /* Store received PUSH_PROMISE headers to be used when the subsequent + PUSH_PROMISE callback comes */ + if(frame->hd.type == NGHTTP2_PUSH_PROMISE) { + char *h; + + if(!strcmp(HTTP_PSEUDO_AUTHORITY, (const char *)name)) { + /* pseudo headers are lower case */ + int rc = 0; + char *check = aprintf("%s:%d", cf->conn->host.name, + cf->conn->remote_port); + if(!check) + /* no memory */ + return NGHTTP2_ERR_CALLBACK_FAILURE; + if(!strcasecompare(check, (const char *)value) && + ((cf->conn->remote_port != cf->conn->given->defport) || + !strcasecompare(cf->conn->host.name, (const char *)value))) { + /* This is push is not for the same authority that was asked for in + * the URL. RFC 7540 section 8.2 says: "A client MUST treat a + * PUSH_PROMISE for which the server is not authoritative as a stream + * error of type PROTOCOL_ERROR." + */ + (void)nghttp2_submit_rst_stream(session, NGHTTP2_FLAG_NONE, + stream_id, NGHTTP2_PROTOCOL_ERROR); + rc = NGHTTP2_ERR_CALLBACK_FAILURE; + } + free(check); + if(rc) + return rc; + } + + if(!stream->push_headers) { + stream->push_headers_alloc = 10; + stream->push_headers = malloc(stream->push_headers_alloc * + sizeof(char *)); + if(!stream->push_headers) + return NGHTTP2_ERR_CALLBACK_FAILURE; + stream->push_headers_used = 0; + } + else if(stream->push_headers_used == + stream->push_headers_alloc) { + char **headp; + if(stream->push_headers_alloc > 1000) { + /* this is beyond crazy many headers, bail out */ + failf(data_s, "Too many PUSH_PROMISE headers"); + free_push_headers(stream); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + stream->push_headers_alloc *= 2; + headp = realloc(stream->push_headers, + stream->push_headers_alloc * sizeof(char *)); + if(!headp) { + free_push_headers(stream); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + stream->push_headers = headp; + } + h = aprintf("%s:%s", name, value); + if(h) + stream->push_headers[stream->push_headers_used++] = h; + return 0; + } + + if(stream->bodystarted) { + /* This is a trailer */ + CURL_TRC_CF(data_s, cf, "[%d] trailer: %.*s: %.*s", + stream->id, (int)namelen, name, (int)valuelen, value); + result = Curl_dynhds_add(&stream->resp_trailers, + (const char *)name, namelen, + (const char *)value, valuelen); + if(result) + return NGHTTP2_ERR_CALLBACK_FAILURE; + + return 0; + } + + if(namelen == sizeof(HTTP_PSEUDO_STATUS) - 1 && + memcmp(HTTP_PSEUDO_STATUS, name, namelen) == 0) { + /* nghttp2 guarantees :status is received first and only once. */ + char buffer[32]; + result = Curl_http_decode_status(&stream->status_code, + (const char *)value, valuelen); + if(result) + return NGHTTP2_ERR_CALLBACK_FAILURE; + msnprintf(buffer, sizeof(buffer), HTTP_PSEUDO_STATUS ":%u\r", + stream->status_code); + result = Curl_headers_push(data_s, buffer, CURLH_PSEUDO); + if(result) + return NGHTTP2_ERR_CALLBACK_FAILURE; + Curl_dyn_reset(&ctx->scratch); + result = Curl_dyn_addn(&ctx->scratch, STRCONST("HTTP/2 ")); + if(!result) + result = Curl_dyn_addn(&ctx->scratch, value, valuelen); + if(!result) + result = Curl_dyn_addn(&ctx->scratch, STRCONST(" \r\n")); + if(!result) + h2_xfer_write_resp_hd(cf, data_s, stream, Curl_dyn_ptr(&ctx->scratch), + Curl_dyn_len(&ctx->scratch), FALSE); + if(result) + return NGHTTP2_ERR_CALLBACK_FAILURE; + /* if we receive data for another handle, wake that up */ + if(CF_DATA_CURRENT(cf) != data_s) + Curl_expire(data_s, 0, EXPIRE_RUN_NOW); + + CURL_TRC_CF(data_s, cf, "[%d] status: HTTP/2 %03d", + stream->id, stream->status_code); + return 0; + } + + /* nghttp2 guarantees that namelen > 0, and :status was already + received, and this is not pseudo-header field . */ + /* convert to an HTTP1-style header */ + Curl_dyn_reset(&ctx->scratch); + result = Curl_dyn_addn(&ctx->scratch, (const char *)name, namelen); + if(!result) + result = Curl_dyn_addn(&ctx->scratch, STRCONST(": ")); + if(!result) + result = Curl_dyn_addn(&ctx->scratch, (const char *)value, valuelen); + if(!result) + result = Curl_dyn_addn(&ctx->scratch, STRCONST("\r\n")); + if(!result) + h2_xfer_write_resp_hd(cf, data_s, stream, Curl_dyn_ptr(&ctx->scratch), + Curl_dyn_len(&ctx->scratch), FALSE); + if(result) + return NGHTTP2_ERR_CALLBACK_FAILURE; + /* if we receive data for another handle, wake that up */ + if(CF_DATA_CURRENT(cf) != data_s) + Curl_expire(data_s, 0, EXPIRE_RUN_NOW); + + CURL_TRC_CF(data_s, cf, "[%d] header: %.*s: %.*s", + stream->id, (int)namelen, name, (int)valuelen, value); + + return 0; /* 0 is successful */ +} + +static ssize_t req_body_read_callback(nghttp2_session *session, + int32_t stream_id, + uint8_t *buf, size_t length, + uint32_t *data_flags, + nghttp2_data_source *source, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_ctx *ctx = cf->ctx; + struct Curl_easy *data_s; + struct h2_stream_ctx *stream = NULL; + CURLcode result; + ssize_t nread; + (void)source; + + (void)cf; + if(stream_id) { + /* get the stream from the hash based on Stream ID, stream ID zero is for + connection-oriented stuff */ + data_s = nghttp2_session_get_stream_user_data(session, stream_id); + if(!data_s) + /* Receiving a Stream ID not in the hash should not happen, this is an + internal error more than anything else! */ + return NGHTTP2_ERR_CALLBACK_FAILURE; + + stream = H2_STREAM_CTX(ctx, data_s); + if(!stream) + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + else + return NGHTTP2_ERR_INVALID_ARGUMENT; + + nread = Curl_bufq_read(&stream->sendbuf, buf, length, &result); + if(nread < 0) { + if(result != CURLE_AGAIN) + return NGHTTP2_ERR_CALLBACK_FAILURE; + nread = 0; + } + + if(nread > 0 && stream->upload_left != -1) + stream->upload_left -= nread; + + CURL_TRC_CF(data_s, cf, "[%d] req_body_read(len=%zu) left=%" + CURL_FORMAT_CURL_OFF_T " -> %zd, %d", + stream_id, length, stream->upload_left, nread, result); + + if(stream->upload_left == 0) + *data_flags = NGHTTP2_DATA_FLAG_EOF; + else if(nread == 0) + return NGHTTP2_ERR_DEFERRED; + + return nread; +} + +#if !defined(CURL_DISABLE_VERBOSE_STRINGS) +static int error_callback(nghttp2_session *session, + const char *msg, + size_t len, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + (void)session; + failf(data, "%.*s", (int)len, msg); + return 0; +} +#endif + +/* + * Append headers to ask for an HTTP1.1 to HTTP2 upgrade. + */ +CURLcode Curl_http2_request_upgrade(struct dynbuf *req, + struct Curl_easy *data) +{ + CURLcode result; + char *base64; + size_t blen; + struct SingleRequest *k = &data->req; + uint8_t binsettings[H2_BINSETTINGS_LEN]; + ssize_t binlen; /* length of the binsettings data */ + + binlen = populate_binsettings(binsettings, data); + if(binlen <= 0) { + failf(data, "nghttp2 unexpectedly failed on pack_settings_payload"); + Curl_dyn_free(req); + return CURLE_FAILED_INIT; + } + + result = Curl_base64url_encode((const char *)binsettings, binlen, + &base64, &blen); + if(result) { + Curl_dyn_free(req); + return result; + } + + result = Curl_dyn_addf(req, + "Connection: Upgrade, HTTP2-Settings\r\n" + "Upgrade: %s\r\n" + "HTTP2-Settings: %s\r\n", + NGHTTP2_CLEARTEXT_PROTO_VERSION_ID, base64); + free(base64); + + k->upgr101 = UPGR101_H2; + + return result; +} + +static CURLcode http2_data_done_send(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + + if(!ctx || !ctx->h2 || !stream) + goto out; + + CURL_TRC_CF(data, cf, "[%d] data done send", stream->id); + if(!stream->send_closed) { + stream->send_closed = TRUE; + if(stream->upload_left) { + /* we now know that everything that is buffered is all there is. */ + stream->upload_left = Curl_bufq_len(&stream->sendbuf); + /* resume sending here to trigger the callback to get called again so + that it can signal EOF to nghttp2 */ + (void)nghttp2_session_resume_data(ctx->h2, stream->id); + drain_stream(cf, data, stream); + } + } + +out: + return result; +} + +static ssize_t http2_handle_stream_close(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h2_stream_ctx *stream, + CURLcode *err) +{ + ssize_t rv = 0; + + if(stream->error == NGHTTP2_REFUSED_STREAM) { + CURL_TRC_CF(data, cf, "[%d] REFUSED_STREAM, try again on a new " + "connection", stream->id); + connclose(cf->conn, "REFUSED_STREAM"); /* don't use this anymore */ + data->state.refused_stream = TRUE; + *err = CURLE_RECV_ERROR; /* trigger Curl_retry_request() later */ + return -1; + } + else if(stream->error != NGHTTP2_NO_ERROR) { + if(stream->resp_hds_complete && data->req.no_body) { + CURL_TRC_CF(data, cf, "[%d] error after response headers, but we did " + "not want a body anyway, ignore: %s (err %u)", + stream->id, nghttp2_http2_strerror(stream->error), + stream->error); + stream->close_handled = TRUE; + *err = CURLE_OK; + goto out; + } + failf(data, "HTTP/2 stream %u was not closed cleanly: %s (err %u)", + stream->id, nghttp2_http2_strerror(stream->error), + stream->error); + *err = CURLE_HTTP2_STREAM; + return -1; + } + else if(stream->reset) { + failf(data, "HTTP/2 stream %u was reset", stream->id); + *err = data->req.bytecount? CURLE_PARTIAL_FILE : CURLE_HTTP2; + return -1; + } + + if(!stream->bodystarted) { + failf(data, "HTTP/2 stream %u was closed cleanly, but before getting " + " all response header fields, treated as error", + stream->id); + *err = CURLE_HTTP2_STREAM; + return -1; + } + + if(Curl_dynhds_count(&stream->resp_trailers)) { + struct dynhds_entry *e; + struct dynbuf dbuf; + size_t i; + + *err = CURLE_OK; + Curl_dyn_init(&dbuf, DYN_TRAILERS); + for(i = 0; i < Curl_dynhds_count(&stream->resp_trailers); ++i) { + e = Curl_dynhds_getn(&stream->resp_trailers, i); + if(!e) + break; + Curl_dyn_reset(&dbuf); + *err = Curl_dyn_addf(&dbuf, "%.*s: %.*s\x0d\x0a", + (int)e->namelen, e->name, + (int)e->valuelen, e->value); + if(*err) + break; + Curl_debug(data, CURLINFO_HEADER_IN, Curl_dyn_ptr(&dbuf), + Curl_dyn_len(&dbuf)); + *err = Curl_client_write(data, CLIENTWRITE_HEADER|CLIENTWRITE_TRAILER, + Curl_dyn_ptr(&dbuf), Curl_dyn_len(&dbuf)); + if(*err) + break; + } + Curl_dyn_free(&dbuf); + if(*err) + goto out; + } + + stream->close_handled = TRUE; + *err = CURLE_OK; + rv = 0; + +out: + CURL_TRC_CF(data, cf, "handle_stream_close -> %zd, %d", rv, *err); + return rv; +} + +static int sweight_wanted(const struct Curl_easy *data) +{ + /* 0 weight is not set by user and we take the nghttp2 default one */ + return data->set.priority.weight? + data->set.priority.weight : NGHTTP2_DEFAULT_WEIGHT; +} + +static int sweight_in_effect(const struct Curl_easy *data) +{ + /* 0 weight is not set by user and we take the nghttp2 default one */ + return data->state.priority.weight? + data->state.priority.weight : NGHTTP2_DEFAULT_WEIGHT; +} + +/* + * h2_pri_spec() fills in the pri_spec struct, used by nghttp2 to send weight + * and dependency to the peer. It also stores the updated values in the state + * struct. + */ + +static void h2_pri_spec(struct cf_h2_ctx *ctx, + struct Curl_easy *data, + nghttp2_priority_spec *pri_spec) +{ + struct Curl_data_priority *prio = &data->set.priority; + struct h2_stream_ctx *depstream = H2_STREAM_CTX(ctx, prio->parent); + int32_t depstream_id = depstream? depstream->id:0; + nghttp2_priority_spec_init(pri_spec, depstream_id, + sweight_wanted(data), + data->set.priority.exclusive); + data->state.priority = *prio; +} + +/* + * Check if there's been an update in the priority / + * dependency settings and if so it submits a PRIORITY frame with the updated + * info. + * Flush any out data pending in the network buffer. + */ +static CURLcode h2_progress_egress(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + int rv = 0; + + if(stream && stream->id > 0 && + ((sweight_wanted(data) != sweight_in_effect(data)) || + (data->set.priority.exclusive != data->state.priority.exclusive) || + (data->set.priority.parent != data->state.priority.parent)) ) { + /* send new weight and/or dependency */ + nghttp2_priority_spec pri_spec; + + h2_pri_spec(ctx, data, &pri_spec); + CURL_TRC_CF(data, cf, "[%d] Queuing PRIORITY", stream->id); + DEBUGASSERT(stream->id != -1); + rv = nghttp2_submit_priority(ctx->h2, NGHTTP2_FLAG_NONE, + stream->id, &pri_spec); + if(rv) + goto out; + } + + ctx->nw_out_blocked = 0; + while(!rv && !ctx->nw_out_blocked && nghttp2_session_want_write(ctx->h2)) + rv = nghttp2_session_send(ctx->h2); + +out: + if(nghttp2_is_fatal(rv)) { + CURL_TRC_CF(data, cf, "nghttp2_session_send error (%s)%d", + nghttp2_strerror(rv), rv); + return CURLE_SEND_ERROR; + } + return nw_out_flush(cf, data); +} + +static ssize_t stream_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + struct h2_stream_ctx *stream, + char *buf, size_t len, CURLcode *err) +{ + struct cf_h2_ctx *ctx = cf->ctx; + ssize_t nread = -1; + + (void)buf; + *err = CURLE_AGAIN; + if(stream->xfer_result) { + CURL_TRC_CF(data, cf, "[%d] xfer write failed", stream->id); + *err = stream->xfer_result; + nread = -1; + } + else if(stream->closed) { + CURL_TRC_CF(data, cf, "[%d] returning CLOSE", stream->id); + nread = http2_handle_stream_close(cf, data, stream, err); + } + else if(stream->reset || + (ctx->conn_closed && Curl_bufq_is_empty(&ctx->inbufq)) || + (ctx->goaway && ctx->last_stream_id < stream->id)) { + CURL_TRC_CF(data, cf, "[%d] returning ERR", stream->id); + *err = data->req.bytecount? CURLE_PARTIAL_FILE : CURLE_HTTP2; + nread = -1; + } + + if(nread < 0 && *err != CURLE_AGAIN) + CURL_TRC_CF(data, cf, "[%d] stream_recv(len=%zu) -> %zd, %d", + stream->id, len, nread, *err); + return nread; +} + +static CURLcode h2_progress_ingress(struct Curl_cfilter *cf, + struct Curl_easy *data, + size_t data_max_bytes) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream; + CURLcode result = CURLE_OK; + ssize_t nread; + + /* Process network input buffer fist */ + if(!Curl_bufq_is_empty(&ctx->inbufq)) { + CURL_TRC_CF(data, cf, "Process %zu bytes in connection buffer", + Curl_bufq_len(&ctx->inbufq)); + if(h2_process_pending_input(cf, data, &result) < 0) + return result; + } + + /* Receive data from the "lower" filters, e.g. network until + * it is time to stop due to connection close or us not processing + * all network input */ + while(!ctx->conn_closed && Curl_bufq_is_empty(&ctx->inbufq)) { + stream = H2_STREAM_CTX(ctx, data); + if(stream && (stream->closed || !data_max_bytes)) { + /* We would like to abort here and stop processing, so that + * the transfer loop can handle the data/close here. However, + * this may leave data in underlying buffers that will not + * be consumed. */ + if(!cf->next || !cf->next->cft->has_data_pending(cf->next, data)) + drain_stream(cf, data, stream); + break; + } + + nread = Curl_bufq_sipn(&ctx->inbufq, 0, nw_in_reader, cf, &result); + if(nread < 0) { + if(result != CURLE_AGAIN) { + failf(data, "Failed receiving HTTP2 data: %d(%s)", result, + curl_easy_strerror(result)); + return result; + } + break; + } + else if(nread == 0) { + CURL_TRC_CF(data, cf, "[0] ingress: connection closed"); + ctx->conn_closed = TRUE; + break; + } + else { + CURL_TRC_CF(data, cf, "[0] ingress: read %zd bytes", nread); + data_max_bytes = (data_max_bytes > (size_t)nread)? + (data_max_bytes - (size_t)nread) : 0; + } + + if(h2_process_pending_input(cf, data, &result)) + return result; + } + + if(ctx->conn_closed && Curl_bufq_is_empty(&ctx->inbufq)) { + connclose(cf->conn, "GOAWAY received"); + } + + return CURLE_OK; +} + +static ssize_t cf_h2_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, CURLcode *err) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + ssize_t nread = -1; + CURLcode result; + struct cf_call_data save; + + if(!stream) { + /* Abnormal call sequence: either this transfer has never opened a stream + * (unlikely) or the transfer has been done, cleaned up its resources, but + * a read() is called anyway. It is not clear what the calling sequence + * is for such a case. */ + failf(data, "[%zd-%zd], http/2 recv on a transfer never opened " + "or already cleared", (ssize_t)data->id, + (ssize_t)cf->conn->connection_id); + *err = CURLE_HTTP2; + return -1; + } + + CF_DATA_SAVE(save, cf, data); + + nread = stream_recv(cf, data, stream, buf, len, err); + if(nread < 0 && *err != CURLE_AGAIN) + goto out; + + if(nread < 0) { + *err = h2_progress_ingress(cf, data, len); + if(*err) + goto out; + + nread = stream_recv(cf, data, stream, buf, len, err); + } + + if(nread > 0) { + size_t data_consumed = (size_t)nread; + /* Now that we transferred this to the upper layer, we report + * the actual amount of DATA consumed to the H2 session, so + * that it adjusts stream flow control */ + if(stream->resp_hds_len >= data_consumed) { + stream->resp_hds_len -= data_consumed; /* no DATA */ + } + else { + if(stream->resp_hds_len) { + data_consumed -= stream->resp_hds_len; + stream->resp_hds_len = 0; + } + if(data_consumed) { + nghttp2_session_consume(ctx->h2, stream->id, data_consumed); + } + } + + if(stream->closed) { + CURL_TRC_CF(data, cf, "[%d] DRAIN closed stream", stream->id); + drain_stream(cf, data, stream); + } + } + +out: + result = h2_progress_egress(cf, data); + if(result == CURLE_AGAIN) { + /* pending data to send, need to be called again. Ideally, we'd + * monitor the socket for POLLOUT, but we might not be in SENDING + * transfer state any longer and are unable to make this happen. + */ + drain_stream(cf, data, stream); + } + else if(result) { + *err = result; + nread = -1; + } + CURL_TRC_CF(data, cf, "[%d] cf_recv(len=%zu) -> %zd %d, " + "window=%d/%d, connection %d/%d", + stream->id, len, nread, *err, + nghttp2_session_get_stream_effective_recv_data_length( + ctx->h2, stream->id), + nghttp2_session_get_stream_effective_local_window_size( + ctx->h2, stream->id), + nghttp2_session_get_local_window_size(ctx->h2), + HTTP2_HUGE_WINDOW_SIZE); + + CF_DATA_RESTORE(cf, save); + return nread; +} + +static ssize_t h2_submit(struct h2_stream_ctx **pstream, + struct Curl_cfilter *cf, struct Curl_easy *data, + const void *buf, size_t len, + size_t *phdslen, CURLcode *err) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream = NULL; + struct dynhds h2_headers; + nghttp2_nv *nva = NULL; + const void *body = NULL; + size_t nheader, bodylen, i; + nghttp2_data_provider data_prd; + int32_t stream_id; + nghttp2_priority_spec pri_spec; + ssize_t nwritten; + + *phdslen = 0; + Curl_dynhds_init(&h2_headers, 0, DYN_HTTP_REQUEST); + + *err = http2_data_setup(cf, data, &stream); + if(*err) { + nwritten = -1; + goto out; + } + + nwritten = Curl_h1_req_parse_read(&stream->h1, buf, len, NULL, 0, err); + if(nwritten < 0) + goto out; + *phdslen = (size_t)nwritten; + if(!stream->h1.done) { + /* need more data */ + goto out; + } + DEBUGASSERT(stream->h1.req); + + *err = Curl_http_req_to_h2(&h2_headers, stream->h1.req, data); + if(*err) { + nwritten = -1; + goto out; + } + /* no longer needed */ + Curl_h1_req_parse_free(&stream->h1); + + nva = Curl_dynhds_to_nva(&h2_headers, &nheader); + if(!nva) { + *err = CURLE_OUT_OF_MEMORY; + nwritten = -1; + goto out; + } + + h2_pri_spec(ctx, data, &pri_spec); + if(!nghttp2_session_check_request_allowed(ctx->h2)) + CURL_TRC_CF(data, cf, "send request NOT allowed (via nghttp2)"); + + switch(data->state.httpreq) { + case HTTPREQ_POST: + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + case HTTPREQ_PUT: + if(data->state.infilesize != -1) + stream->upload_left = data->state.infilesize; + else + /* data sending without specifying the data amount up front */ + stream->upload_left = -1; /* unknown */ + + data_prd.read_callback = req_body_read_callback; + data_prd.source.ptr = NULL; + stream_id = nghttp2_submit_request(ctx->h2, &pri_spec, nva, nheader, + &data_prd, data); + break; + default: + stream->upload_left = 0; /* no request body */ + stream_id = nghttp2_submit_request(ctx->h2, &pri_spec, nva, nheader, + NULL, data); + } + + if(stream_id < 0) { + CURL_TRC_CF(data, cf, "send: nghttp2_submit_request error (%s)%u", + nghttp2_strerror(stream_id), stream_id); + *err = CURLE_SEND_ERROR; + nwritten = -1; + goto out; + } + +#define MAX_ACC 60000 /* <64KB to account for some overhead */ + if(Curl_trc_is_verbose(data)) { + size_t acc = 0; + + infof(data, "[HTTP/2] [%d] OPENED stream for %s", + stream_id, data->state.url); + for(i = 0; i < nheader; ++i) { + acc += nva[i].namelen + nva[i].valuelen; + + infof(data, "[HTTP/2] [%d] [%.*s: %.*s]", stream_id, + (int)nva[i].namelen, nva[i].name, + (int)nva[i].valuelen, nva[i].value); + } + + if(acc > MAX_ACC) { + infof(data, "[HTTP/2] Warning: The cumulative length of all " + "headers exceeds %d bytes and that could cause the " + "stream to be rejected.", MAX_ACC); + } + } + + stream->id = stream_id; + stream->local_window_size = H2_STREAM_WINDOW_SIZE; + if(data->set.max_recv_speed) { + /* We are asked to only receive `max_recv_speed` bytes per second. + * Let's limit our stream window size around that, otherwise the server + * will send in large bursts only. We make the window 50% larger to + * allow for data in flight and avoid stalling. */ + curl_off_t n = (((data->set.max_recv_speed - 1) / H2_CHUNK_SIZE) + 1); + n += CURLMAX((n/2), 1); + if(n < (H2_STREAM_WINDOW_SIZE / H2_CHUNK_SIZE) && + n < (UINT_MAX / H2_CHUNK_SIZE)) { + stream->local_window_size = (uint32_t)n * H2_CHUNK_SIZE; + } + } + + body = (const char *)buf + nwritten; + bodylen = len - nwritten; + + if(bodylen) { + /* We have request body to send in DATA frame */ + ssize_t n = Curl_bufq_write(&stream->sendbuf, body, bodylen, err); + if(n < 0) { + *err = CURLE_SEND_ERROR; + nwritten = -1; + goto out; + } + nwritten += n; + } + +out: + CURL_TRC_CF(data, cf, "[%d] submit -> %zd, %d", + stream? stream->id : -1, nwritten, *err); + Curl_safefree(nva); + *pstream = stream; + Curl_dynhds_free(&h2_headers); + return nwritten; +} + +static ssize_t cf_h2_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *buf, size_t len, CURLcode *err) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + struct cf_call_data save; + int rv; + ssize_t nwritten; + size_t hdslen = 0; + CURLcode result; + int blocked = 0, was_blocked = 0; + + CF_DATA_SAVE(save, cf, data); + + if(stream && stream->id != -1) { + if(stream->upload_blocked_len) { + /* the data in `buf` has already been submitted or added to the + * buffers, but have been EAGAINed on the last invocation. */ + /* TODO: this assertion triggers in OSSFuzz runs and it is not + * clear why. Disable for now to let OSSFuzz continue its tests. */ + DEBUGASSERT(len >= stream->upload_blocked_len); + if(len < stream->upload_blocked_len) { + /* Did we get called again with a smaller `len`? This should not + * happen. We are not prepared to handle that. */ + failf(data, "HTTP/2 send again with decreased length (%zd vs %zd)", + len, stream->upload_blocked_len); + *err = CURLE_HTTP2; + nwritten = -1; + goto out; + } + nwritten = (ssize_t)stream->upload_blocked_len; + stream->upload_blocked_len = 0; + was_blocked = 1; + } + else if(stream->closed) { + if(stream->resp_hds_complete) { + /* Server decided to close the stream after having sent us a findl + * response. This is valid if it is not interested in the request + * body. This happens on 30x or 40x responses. + * We silently discard the data sent, since this is not a transport + * error situation. */ + CURL_TRC_CF(data, cf, "[%d] discarding data" + "on closed stream with response", stream->id); + *err = CURLE_OK; + nwritten = (ssize_t)len; + goto out; + } + infof(data, "stream %u closed", stream->id); + *err = CURLE_SEND_ERROR; + nwritten = -1; + goto out; + } + else { + /* If stream_id != -1, we have dispatched request HEADERS and + * optionally request body, and now are going to send or sending + * more request body in DATA frame */ + nwritten = Curl_bufq_write(&stream->sendbuf, buf, len, err); + if(nwritten < 0 && *err != CURLE_AGAIN) + goto out; + } + + if(!Curl_bufq_is_empty(&stream->sendbuf)) { + /* req body data is buffered, resume the potentially suspended stream */ + rv = nghttp2_session_resume_data(ctx->h2, stream->id); + if(nghttp2_is_fatal(rv)) { + *err = CURLE_SEND_ERROR; + nwritten = -1; + goto out; + } + } + } + else { + nwritten = h2_submit(&stream, cf, data, buf, len, &hdslen, err); + if(nwritten < 0) { + goto out; + } + DEBUGASSERT(stream); + DEBUGASSERT(hdslen <= (size_t)nwritten); + } + + /* Call the nghttp2 send loop and flush to write ALL buffered data, + * headers and/or request body completely out to the network */ + result = h2_progress_egress(cf, data); + /* if the stream has been closed in egress handling (nghttp2 does that + * when it does not like the headers, for example */ + if(stream && stream->closed && !was_blocked) { + infof(data, "stream %u closed", stream->id); + *err = CURLE_SEND_ERROR; + nwritten = -1; + goto out; + } + else if(result == CURLE_AGAIN) { + blocked = 1; + } + else if(result) { + *err = result; + nwritten = -1; + goto out; + } + else if(stream && !Curl_bufq_is_empty(&stream->sendbuf)) { + /* although we wrote everything that nghttp2 wants to send now, + * there is data left in our stream send buffer unwritten. This may + * be due to the stream's HTTP/2 flow window being exhausted. */ + blocked = 1; + } + + if(stream && blocked && nwritten > 0) { + /* Unable to send all data, due to connection blocked or H2 window + * exhaustion. Data is left in our stream buffer, or nghttp2's internal + * frame buffer or our network out buffer. */ + size_t rwin = nghttp2_session_get_stream_remote_window_size(ctx->h2, + stream->id); + /* At the start of a stream, we are called with request headers + * and, possibly, parts of the body. Later, only body data. + * If we cannot send pure body data, we EAGAIN. If there had been + * header, we return that *they* have been written and remember the + * block on the data length only. */ + stream->upload_blocked_len = ((size_t)nwritten) - hdslen; + CURL_TRC_CF(data, cf, "[%d] cf_send(len=%zu) BLOCK: win %u/%zu " + "hds_len=%zu blocked_len=%zu", + stream->id, len, + nghttp2_session_get_remote_window_size(ctx->h2), rwin, + hdslen, stream->upload_blocked_len); + if(hdslen) { + *err = CURLE_OK; + nwritten = hdslen; + } + else { + *err = CURLE_AGAIN; + nwritten = -1; + goto out; + } + } + else if(should_close_session(ctx)) { + /* nghttp2 thinks this session is done. If the stream has not been + * closed, this is an error state for out transfer */ + if(stream->closed) { + nwritten = http2_handle_stream_close(cf, data, stream, err); + } + else { + CURL_TRC_CF(data, cf, "send: nothing to do in this session"); + *err = CURLE_HTTP2; + nwritten = -1; + } + } + +out: + if(stream) { + CURL_TRC_CF(data, cf, "[%d] cf_send(len=%zu) -> %zd, %d, " + "upload_left=%" CURL_FORMAT_CURL_OFF_T ", " + "h2 windows %d-%d (stream-conn), " + "buffers %zu-%zu (stream-conn)", + stream->id, len, nwritten, *err, + stream->upload_left, + nghttp2_session_get_stream_remote_window_size( + ctx->h2, stream->id), + nghttp2_session_get_remote_window_size(ctx->h2), + Curl_bufq_len(&stream->sendbuf), + Curl_bufq_len(&ctx->outbufq)); + } + else { + CURL_TRC_CF(data, cf, "cf_send(len=%zu) -> %zd, %d, " + "connection-window=%d, nw_send_buffer(%zu)", + len, nwritten, *err, + nghttp2_session_get_remote_window_size(ctx->h2), + Curl_bufq_len(&ctx->outbufq)); + } + CF_DATA_RESTORE(cf, save); + return nwritten; +} + +static void cf_h2_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_h2_ctx *ctx = cf->ctx; + curl_socket_t sock; + bool want_recv, want_send; + + if(!ctx->h2) + return; + + sock = Curl_conn_cf_get_socket(cf, data); + Curl_pollset_check(data, ps, sock, &want_recv, &want_send); + if(want_recv || want_send) { + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + struct cf_call_data save; + bool c_exhaust, s_exhaust; + + CF_DATA_SAVE(save, cf, data); + c_exhaust = want_send && !nghttp2_session_get_remote_window_size(ctx->h2); + s_exhaust = want_send && stream && stream->id >= 0 && + !nghttp2_session_get_stream_remote_window_size(ctx->h2, + stream->id); + want_recv = (want_recv || c_exhaust || s_exhaust); + want_send = (!s_exhaust && want_send) || + (!c_exhaust && nghttp2_session_want_write(ctx->h2)); + + Curl_pollset_set(data, ps, sock, want_recv, want_send); + CF_DATA_RESTORE(cf, save); + } +} + +static CURLcode cf_h2_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + struct cf_h2_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + struct cf_call_data save; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + /* Connect the lower filters first */ + if(!cf->next->connected) { + result = Curl_conn_cf_connect(cf->next, data, blocking, done); + if(result || !*done) + return result; + } + + *done = FALSE; + + CF_DATA_SAVE(save, cf, data); + if(!ctx->h2) { + result = cf_h2_ctx_init(cf, data, FALSE); + if(result) + goto out; + } + + result = h2_progress_ingress(cf, data, H2_CHUNK_SIZE); + if(result) + goto out; + + /* Send out our SETTINGS and ACKs and such. If that blocks, we + * have it buffered and can count this filter as being connected */ + result = h2_progress_egress(cf, data); + if(result == CURLE_AGAIN) + result = CURLE_OK; + else if(result) + goto out; + + *done = TRUE; + cf->connected = TRUE; + result = CURLE_OK; + +out: + CURL_TRC_CF(data, cf, "cf_connect() -> %d, %d, ", result, *done); + CF_DATA_RESTORE(cf, save); + return result; +} + +static void cf_h2_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + + if(ctx) { + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + cf_h2_ctx_clear(ctx); + CF_DATA_RESTORE(cf, save); + } + if(cf->next) + cf->next->cft->do_close(cf->next, data); +} + +static void cf_h2_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + + (void)data; + if(ctx) { + cf_h2_ctx_free(ctx); + cf->ctx = NULL; + } +} + +static CURLcode http2_data_pause(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool pause) +{ +#ifdef NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + + DEBUGASSERT(data); + if(ctx && ctx->h2 && stream) { + uint32_t window = pause? 0 : stream->local_window_size; + + int rv = nghttp2_session_set_local_window_size(ctx->h2, + NGHTTP2_FLAG_NONE, + stream->id, + window); + if(rv) { + failf(data, "nghttp2_session_set_local_window_size() failed: %s(%d)", + nghttp2_strerror(rv), rv); + return CURLE_HTTP2; + } + + if(!pause) + drain_stream(cf, data, stream); + + /* attempt to send the window update */ + (void)h2_progress_egress(cf, data); + + if(!pause) { + /* Unpausing a h2 transfer, requires it to be run again. The server + * may send new DATA on us increasing the flow window, and it may + * not. We may have already buffered and exhausted the new window + * by operating on things in flight during the handling of other + * transfers. */ + drain_stream(cf, data, stream); + Curl_expire(data, 0, EXPIRE_RUN_NOW); + } + DEBUGF(infof(data, "Set HTTP/2 window size to %u for stream %u", + window, stream->id)); + +#ifdef DEBUGBUILD + { + /* read out the stream local window again */ + uint32_t window2 = + nghttp2_session_get_stream_local_window_size(ctx->h2, + stream->id); + DEBUGF(infof(data, "HTTP/2 window size is now %u for stream %u", + window2, stream->id)); + } +#endif + } +#endif + return CURLE_OK; +} + +static CURLcode cf_h2_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + CURLcode result = CURLE_OK; + struct cf_call_data save; + + (void)arg2; + + CF_DATA_SAVE(save, cf, data); + switch(event) { + case CF_CTRL_DATA_SETUP: + break; + case CF_CTRL_DATA_PAUSE: + result = http2_data_pause(cf, data, (arg1 != 0)); + break; + case CF_CTRL_DATA_DONE_SEND: + result = http2_data_done_send(cf, data); + break; + case CF_CTRL_DATA_DETACH: + http2_data_done(cf, data); + break; + case CF_CTRL_DATA_DONE: + http2_data_done(cf, data); + break; + default: + break; + } + CF_DATA_RESTORE(cf, save); + return result; +} + +static bool cf_h2_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + + if(ctx && (!Curl_bufq_is_empty(&ctx->inbufq) + || (stream && !Curl_bufq_is_empty(&stream->sendbuf)))) + return TRUE; + return cf->next? cf->next->cft->has_data_pending(cf->next, data) : FALSE; +} + +static bool cf_h2_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending) +{ + struct cf_h2_ctx *ctx = cf->ctx; + CURLcode result; + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + result = (ctx && ctx->h2 && http2_connisalive(cf, data, input_pending)); + CURL_TRC_CF(data, cf, "conn alive -> %d, input_pending=%d", + result, *input_pending); + CF_DATA_RESTORE(cf, save); + return result; +} + +static CURLcode cf_h2_keep_alive(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURLcode result; + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + result = http2_send_ping(cf, data); + CF_DATA_RESTORE(cf, save); + return result; +} + +static CURLcode cf_h2_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct cf_call_data save; + size_t effective_max; + + switch(query) { + case CF_QUERY_MAX_CONCURRENT: + DEBUGASSERT(pres1); + + CF_DATA_SAVE(save, cf, data); + if(nghttp2_session_check_request_allowed(ctx->h2) == 0) { + /* the limit is what we have in use right now */ + effective_max = CONN_INUSE(cf->conn); + } + else { + effective_max = ctx->max_concurrent_streams; + } + *pres1 = (effective_max > INT_MAX)? INT_MAX : (int)effective_max; + CF_DATA_RESTORE(cf, save); + return CURLE_OK; + case CF_QUERY_STREAM_ERROR: { + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + *pres1 = stream? (int)stream->error : 0; + return CURLE_OK; + } + default: + break; + } + return cf->next? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +struct Curl_cftype Curl_cft_nghttp2 = { + "HTTP/2", + CF_TYPE_MULTIPLEX, + CURL_LOG_LVL_NONE, + cf_h2_destroy, + cf_h2_connect, + cf_h2_close, + Curl_cf_def_get_host, + cf_h2_adjust_pollset, + cf_h2_data_pending, + cf_h2_send, + cf_h2_recv, + cf_h2_cntrl, + cf_h2_is_alive, + cf_h2_keep_alive, + cf_h2_query, +}; + +static CURLcode http2_cfilter_add(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + int sockindex, + bool via_h1_upgrade) +{ + struct Curl_cfilter *cf = NULL; + struct cf_h2_ctx *ctx; + CURLcode result = CURLE_OUT_OF_MEMORY; + + DEBUGASSERT(data->conn); + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) + goto out; + + result = Curl_cf_create(&cf, &Curl_cft_nghttp2, ctx); + if(result) + goto out; + + ctx = NULL; + Curl_conn_cf_add(data, conn, sockindex, cf); + result = cf_h2_ctx_init(cf, data, via_h1_upgrade); + +out: + if(result) + cf_h2_ctx_free(ctx); + *pcf = result? NULL : cf; + return result; +} + +static CURLcode http2_cfilter_insert_after(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool via_h1_upgrade) +{ + struct Curl_cfilter *cf_h2 = NULL; + struct cf_h2_ctx *ctx; + CURLcode result = CURLE_OUT_OF_MEMORY; + + (void)data; + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) + goto out; + + result = Curl_cf_create(&cf_h2, &Curl_cft_nghttp2, ctx); + if(result) + goto out; + + ctx = NULL; + Curl_conn_cf_insert_after(cf, cf_h2); + result = cf_h2_ctx_init(cf_h2, data, via_h1_upgrade); + +out: + if(result) + cf_h2_ctx_free(ctx); + return result; +} + +static bool Curl_cf_is_http2(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + (void)data; + for(; cf; cf = cf->next) { + if(cf->cft == &Curl_cft_nghttp2) + return TRUE; + if(cf->cft->flags & CF_TYPE_IP_CONNECT) + return FALSE; + } + return FALSE; +} + +bool Curl_conn_is_http2(const struct Curl_easy *data, + const struct connectdata *conn, + int sockindex) +{ + return conn? Curl_cf_is_http2(conn->cfilter[sockindex], data) : FALSE; +} + +bool Curl_http2_may_switch(struct Curl_easy *data, + struct connectdata *conn, + int sockindex) +{ + (void)sockindex; + if(!Curl_conn_is_http2(data, conn, sockindex) && + data->state.httpwant == CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE) { +#ifndef CURL_DISABLE_PROXY + if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) { + /* We don't support HTTP/2 proxies yet. Also it's debatable + whether or not this setting should apply to HTTP/2 proxies. */ + infof(data, "Ignoring HTTP/2 prior knowledge due to proxy"); + return FALSE; + } +#endif + return TRUE; + } + return FALSE; +} + +CURLcode Curl_http2_switch(struct Curl_easy *data, + struct connectdata *conn, int sockindex) +{ + struct Curl_cfilter *cf; + CURLcode result; + + DEBUGASSERT(!Curl_conn_is_http2(data, conn, sockindex)); + DEBUGF(infof(data, "switching to HTTP/2")); + + result = http2_cfilter_add(&cf, data, conn, sockindex, FALSE); + if(result) + return result; + + conn->httpversion = 20; /* we know we're on HTTP/2 now */ + conn->bits.multiplex = TRUE; /* at least potentially multiplexed */ + conn->bundle->multiuse = BUNDLE_MULTIPLEX; + Curl_multi_connchanged(data->multi); + + if(cf->next) { + bool done; + return Curl_conn_cf_connect(cf, data, FALSE, &done); + } + return CURLE_OK; +} + +CURLcode Curl_http2_switch_at(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct Curl_cfilter *cf_h2; + CURLcode result; + + DEBUGASSERT(!Curl_cf_is_http2(cf, data)); + + result = http2_cfilter_insert_after(cf, data, FALSE); + if(result) + return result; + + cf_h2 = cf->next; + cf->conn->httpversion = 20; /* we know we're on HTTP/2 now */ + cf->conn->bits.multiplex = TRUE; /* at least potentially multiplexed */ + cf->conn->bundle->multiuse = BUNDLE_MULTIPLEX; + Curl_multi_connchanged(data->multi); + + if(cf_h2->next) { + bool done; + return Curl_conn_cf_connect(cf_h2, data, FALSE, &done); + } + return CURLE_OK; +} + +CURLcode Curl_http2_upgrade(struct Curl_easy *data, + struct connectdata *conn, int sockindex, + const char *mem, size_t nread) +{ + struct Curl_cfilter *cf; + struct cf_h2_ctx *ctx; + CURLcode result; + + DEBUGASSERT(!Curl_conn_is_http2(data, conn, sockindex)); + DEBUGF(infof(data, "upgrading to HTTP/2")); + DEBUGASSERT(data->req.upgr101 == UPGR101_RECEIVED); + + result = http2_cfilter_add(&cf, data, conn, sockindex, TRUE); + if(result) + return result; + + DEBUGASSERT(cf->cft == &Curl_cft_nghttp2); + ctx = cf->ctx; + + if(nread > 0) { + /* Remaining data from the protocol switch reply is already using + * the switched protocol, ie. HTTP/2. We add that to the network + * inbufq. */ + ssize_t copied; + + copied = Curl_bufq_write(&ctx->inbufq, + (const unsigned char *)mem, nread, &result); + if(copied < 0) { + failf(data, "error on copying HTTP Upgrade response: %d", result); + return CURLE_RECV_ERROR; + } + if((size_t)copied < nread) { + failf(data, "connection buffer size could not take all data " + "from HTTP Upgrade response header: copied=%zd, datalen=%zu", + copied, nread); + return CURLE_HTTP2; + } + infof(data, "Copied HTTP/2 data in stream buffer to connection buffer" + " after upgrade: len=%zu", nread); + } + + conn->httpversion = 20; /* we know we're on HTTP/2 now */ + conn->bits.multiplex = TRUE; /* at least potentially multiplexed */ + conn->bundle->multiuse = BUNDLE_MULTIPLEX; + Curl_multi_connchanged(data->multi); + + if(cf->next) { + bool done; + return Curl_conn_cf_connect(cf, data, FALSE, &done); + } + return CURLE_OK; +} + +/* Only call this function for a transfer that already got an HTTP/2 + CURLE_HTTP2_STREAM error! */ +bool Curl_h2_http_1_1_error(struct Curl_easy *data) +{ + if(Curl_conn_is_http2(data, data->conn, FIRSTSOCKET)) { + int err = Curl_conn_get_stream_error(data, data->conn, FIRSTSOCKET); + return (err == NGHTTP2_HTTP_1_1_REQUIRED); + } + return FALSE; +} + +#else /* !USE_NGHTTP2 */ + +/* Satisfy external references even if http2 is not compiled in. */ +#include + +char *curl_pushheader_bynum(struct curl_pushheaders *h, size_t num) +{ + (void) h; + (void) num; + return NULL; +} + +char *curl_pushheader_byname(struct curl_pushheaders *h, const char *header) +{ + (void) h; + (void) header; + return NULL; +} + +#endif /* USE_NGHTTP2 */ diff --git a/third_party/curl/lib/http2.h b/third_party/curl/lib/http2.h new file mode 100644 index 0000000..80e1834 --- /dev/null +++ b/third_party/curl/lib/http2.h @@ -0,0 +1,77 @@ +#ifndef HEADER_CURL_HTTP2_H +#define HEADER_CURL_HTTP2_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_NGHTTP2 +#include "http.h" + +/* value for MAX_CONCURRENT_STREAMS we use until we get an updated setting + from the peer */ +#define DEFAULT_MAX_CONCURRENT_STREAMS 100 + +/* + * Store nghttp2 version info in this buffer. + */ +void Curl_http2_ver(char *p, size_t len); + +CURLcode Curl_http2_request_upgrade(struct dynbuf *req, + struct Curl_easy *data); + +/* returns true if the HTTP/2 stream error was HTTP_1_1_REQUIRED */ +bool Curl_h2_http_1_1_error(struct Curl_easy *data); + +bool Curl_conn_is_http2(const struct Curl_easy *data, + const struct connectdata *conn, + int sockindex); +bool Curl_http2_may_switch(struct Curl_easy *data, + struct connectdata *conn, + int sockindex); + +CURLcode Curl_http2_switch(struct Curl_easy *data, + struct connectdata *conn, int sockindex); + +CURLcode Curl_http2_switch_at(struct Curl_cfilter *cf, struct Curl_easy *data); + +CURLcode Curl_http2_upgrade(struct Curl_easy *data, + struct connectdata *conn, int sockindex, + const char *ptr, size_t nread); + +extern struct Curl_cftype Curl_cft_nghttp2; + +#else /* USE_NGHTTP2 */ + +#define Curl_cf_is_http2(a,b) FALSE +#define Curl_conn_is_http2(a,b,c) FALSE +#define Curl_http2_may_switch(a,b,c) FALSE + +#define Curl_http2_request_upgrade(x,y) CURLE_UNSUPPORTED_PROTOCOL +#define Curl_http2_switch(a,b,c) CURLE_UNSUPPORTED_PROTOCOL +#define Curl_http2_upgrade(a,b,c,d,e) CURLE_UNSUPPORTED_PROTOCOL +#define Curl_h2_http_1_1_error(x) 0 +#endif + +#endif /* HEADER_CURL_HTTP2_H */ diff --git a/third_party/curl/lib/http_aws_sigv4.c b/third_party/curl/lib/http_aws_sigv4.c new file mode 100644 index 0000000..98cc033 --- /dev/null +++ b/third_party/curl/lib/http_aws_sigv4.c @@ -0,0 +1,814 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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.haxx.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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_AWS) + +#include "urldata.h" +#include "strcase.h" +#include "strdup.h" +#include "http_aws_sigv4.h" +#include "curl_sha256.h" +#include "transfer.h" +#include "parsedate.h" +#include "sendf.h" +#include "escape.h" + +#include + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#include "slist.h" + +#define HMAC_SHA256(k, kl, d, dl, o) \ + do { \ + result = Curl_hmacit(Curl_HMAC_SHA256, \ + (unsigned char *)k, \ + kl, \ + (unsigned char *)d, \ + dl, o); \ + if(result) { \ + goto fail; \ + } \ + } while(0) + +#define TIMESTAMP_SIZE 17 + +/* hex-encoded with trailing null */ +#define SHA256_HEX_LENGTH (2 * SHA256_DIGEST_LENGTH + 1) + +static void sha256_to_hex(char *dst, unsigned char *sha) +{ + Curl_hexencode(sha, SHA256_DIGEST_LENGTH, + (unsigned char *)dst, SHA256_HEX_LENGTH); +} + +static char *find_date_hdr(struct Curl_easy *data, const char *sig_hdr) +{ + char *tmp = Curl_checkheaders(data, sig_hdr, strlen(sig_hdr)); + + if(tmp) + return tmp; + return Curl_checkheaders(data, STRCONST("Date")); +} + +/* remove whitespace, and lowercase all headers */ +static void trim_headers(struct curl_slist *head) +{ + struct curl_slist *l; + for(l = head; l; l = l->next) { + char *value; /* to read from */ + char *store; + size_t colon = strcspn(l->data, ":"); + Curl_strntolower(l->data, l->data, colon); + + value = &l->data[colon]; + if(!*value) + continue; + ++value; + store = value; + + /* skip leading whitespace */ + while(*value && ISBLANK(*value)) + value++; + + while(*value) { + int space = 0; + while(*value && ISBLANK(*value)) { + value++; + space++; + } + if(space) { + /* replace any number of consecutive whitespace with a single space, + unless at the end of the string, then nothing */ + if(*value) + *store++ = ' '; + } + else + *store++ = *value++; + } + *store = 0; /* null terminate */ + } +} + +/* maximum length for the aws sivg4 parts */ +#define MAX_SIGV4_LEN 64 +#define MAX_SIGV4_LEN_TXT "64" + +#define DATE_HDR_KEY_LEN (MAX_SIGV4_LEN + sizeof("X--Date")) + +#define MAX_HOST_LEN 255 +/* FQDN + host: */ +#define FULL_HOST_LEN (MAX_HOST_LEN + sizeof("host:")) + +/* string been x-PROVIDER-date:TIMESTAMP, I need +1 for ':' */ +#define DATE_FULL_HDR_LEN (DATE_HDR_KEY_LEN + TIMESTAMP_SIZE + 1) + +/* timestamp should point to a buffer of at last TIMESTAMP_SIZE bytes */ +static CURLcode make_headers(struct Curl_easy *data, + const char *hostname, + char *timestamp, + char *provider1, + char **date_header, + char *content_sha256_header, + struct dynbuf *canonical_headers, + struct dynbuf *signed_headers) +{ + char date_hdr_key[DATE_HDR_KEY_LEN]; + char date_full_hdr[DATE_FULL_HDR_LEN]; + struct curl_slist *head = NULL; + struct curl_slist *tmp_head = NULL; + CURLcode ret = CURLE_OUT_OF_MEMORY; + struct curl_slist *l; + int again = 1; + + /* provider1 mid */ + Curl_strntolower(provider1, provider1, strlen(provider1)); + provider1[0] = Curl_raw_toupper(provider1[0]); + + msnprintf(date_hdr_key, DATE_HDR_KEY_LEN, "X-%s-Date", provider1); + + /* provider1 lowercase */ + Curl_strntolower(provider1, provider1, 1); /* first byte only */ + msnprintf(date_full_hdr, DATE_FULL_HDR_LEN, + "x-%s-date:%s", provider1, timestamp); + + if(!Curl_checkheaders(data, STRCONST("Host"))) { + char full_host[FULL_HOST_LEN + 1]; + + if(data->state.aptr.host) { + size_t pos; + + if(strlen(data->state.aptr.host) > FULL_HOST_LEN) { + ret = CURLE_URL_MALFORMAT; + goto fail; + } + strcpy(full_host, data->state.aptr.host); + /* remove /r/n as the separator for canonical request must be '\n' */ + pos = strcspn(full_host, "\n\r"); + full_host[pos] = 0; + } + else { + if(strlen(hostname) > MAX_HOST_LEN) { + ret = CURLE_URL_MALFORMAT; + goto fail; + } + msnprintf(full_host, FULL_HOST_LEN, "host:%s", hostname); + } + + head = curl_slist_append(NULL, full_host); + if(!head) + goto fail; + } + + + if(*content_sha256_header) { + tmp_head = curl_slist_append(head, content_sha256_header); + if(!tmp_head) + goto fail; + head = tmp_head; + } + + /* copy user headers to our header list. the logic is based on how http.c + handles user headers. + + user headers in format 'name:' with no value are used to signal that an + internal header of that name should be removed. those user headers are not + added to this list. + + user headers in format 'name;' with no value are used to signal that a + header of that name with no value should be sent. those user headers are + added to this list but in the format that they will be sent, ie the + semi-colon is changed to a colon for format 'name:'. + + user headers with a value of whitespace only, or without a colon or + semi-colon, are not added to this list. + */ + for(l = data->set.headers; l; l = l->next) { + char *dupdata, *ptr; + char *sep = strchr(l->data, ':'); + if(!sep) + sep = strchr(l->data, ';'); + if(!sep || (*sep == ':' && !*(sep + 1))) + continue; + for(ptr = sep + 1; ISSPACE(*ptr); ++ptr) + ; + if(!*ptr && ptr != sep + 1) /* a value of whitespace only */ + continue; + dupdata = strdup(l->data); + if(!dupdata) + goto fail; + dupdata[sep - l->data] = ':'; + tmp_head = Curl_slist_append_nodup(head, dupdata); + if(!tmp_head) { + free(dupdata); + goto fail; + } + head = tmp_head; + } + + trim_headers(head); + + *date_header = find_date_hdr(data, date_hdr_key); + if(!*date_header) { + tmp_head = curl_slist_append(head, date_full_hdr); + if(!tmp_head) + goto fail; + head = tmp_head; + *date_header = curl_maprintf("%s: %s\r\n", date_hdr_key, timestamp); + } + else { + char *value; + char *endp; + value = strchr(*date_header, ':'); + if(!value) { + *date_header = NULL; + goto fail; + } + ++value; + while(ISBLANK(*value)) + ++value; + endp = value; + while(*endp && ISALNUM(*endp)) + ++endp; + /* 16 bytes => "19700101T000000Z" */ + if((endp - value) == TIMESTAMP_SIZE - 1) { + memcpy(timestamp, value, TIMESTAMP_SIZE - 1); + timestamp[TIMESTAMP_SIZE - 1] = 0; + } + else + /* bad timestamp length */ + timestamp[0] = 0; + *date_header = NULL; + } + + /* alpha-sort in a case sensitive manner */ + do { + again = 0; + for(l = head; l; l = l->next) { + struct curl_slist *next = l->next; + + if(next && strcmp(l->data, next->data) > 0) { + char *tmp = l->data; + + l->data = next->data; + next->data = tmp; + again = 1; + } + } + } while(again); + + for(l = head; l; l = l->next) { + char *tmp; + + if(Curl_dyn_add(canonical_headers, l->data)) + goto fail; + if(Curl_dyn_add(canonical_headers, "\n")) + goto fail; + + tmp = strchr(l->data, ':'); + if(tmp) + *tmp = 0; + + if(l != head) { + if(Curl_dyn_add(signed_headers, ";")) + goto fail; + } + if(Curl_dyn_add(signed_headers, l->data)) + goto fail; + } + + ret = CURLE_OK; +fail: + curl_slist_free_all(head); + + return ret; +} + +#define CONTENT_SHA256_KEY_LEN (MAX_SIGV4_LEN + sizeof("X--Content-Sha256")) +/* add 2 for ": " between header name and value */ +#define CONTENT_SHA256_HDR_LEN (CONTENT_SHA256_KEY_LEN + 2 + \ + SHA256_HEX_LENGTH) + +/* try to parse a payload hash from the content-sha256 header */ +static char *parse_content_sha_hdr(struct Curl_easy *data, + const char *provider1, + size_t *value_len) +{ + char key[CONTENT_SHA256_KEY_LEN]; + size_t key_len; + char *value; + size_t len; + + key_len = msnprintf(key, sizeof(key), "x-%s-content-sha256", provider1); + + value = Curl_checkheaders(data, key, key_len); + if(!value) + return NULL; + + value = strchr(value, ':'); + if(!value) + return NULL; + ++value; + + while(*value && ISBLANK(*value)) + ++value; + + len = strlen(value); + while(len > 0 && ISBLANK(value[len-1])) + --len; + + *value_len = len; + return value; +} + +static CURLcode calc_payload_hash(struct Curl_easy *data, + unsigned char *sha_hash, char *sha_hex) +{ + const char *post_data = data->set.postfields; + size_t post_data_len = 0; + CURLcode result; + + if(post_data) { + if(data->set.postfieldsize < 0) + post_data_len = strlen(post_data); + else + post_data_len = (size_t)data->set.postfieldsize; + } + result = Curl_sha256it(sha_hash, (const unsigned char *) post_data, + post_data_len); + if(!result) + sha256_to_hex(sha_hex, sha_hash); + return result; +} + +#define S3_UNSIGNED_PAYLOAD "UNSIGNED-PAYLOAD" + +static CURLcode calc_s3_payload_hash(struct Curl_easy *data, + Curl_HttpReq httpreq, char *provider1, + unsigned char *sha_hash, + char *sha_hex, char *header) +{ + bool empty_method = (httpreq == HTTPREQ_GET || httpreq == HTTPREQ_HEAD); + /* The request method or filesize indicate no request payload */ + bool empty_payload = (empty_method || data->set.filesize == 0); + /* The POST payload is in memory */ + bool post_payload = (httpreq == HTTPREQ_POST && data->set.postfields); + CURLcode ret = CURLE_OUT_OF_MEMORY; + + if(empty_payload || post_payload) { + /* Calculate a real hash when we know the request payload */ + ret = calc_payload_hash(data, sha_hash, sha_hex); + if(ret) + goto fail; + } + else { + /* Fall back to s3's UNSIGNED-PAYLOAD */ + size_t len = sizeof(S3_UNSIGNED_PAYLOAD) - 1; + DEBUGASSERT(len < SHA256_HEX_LENGTH); /* 16 < 65 */ + memcpy(sha_hex, S3_UNSIGNED_PAYLOAD, len); + sha_hex[len] = 0; + } + + /* format the required content-sha256 header */ + msnprintf(header, CONTENT_SHA256_HDR_LEN, + "x-%s-content-sha256: %s", provider1, sha_hex); + + ret = CURLE_OK; +fail: + return ret; +} + +struct pair { + const char *p; + size_t len; +}; + +static int compare_func(const void *a, const void *b) +{ + const struct pair *aa = a; + const struct pair *bb = b; + /* If one element is empty, the other is always sorted higher */ + if(aa->len == 0) + return -1; + if(bb->len == 0) + return 1; + return strncmp(aa->p, bb->p, aa->len < bb->len ? aa->len : bb->len); +} + +#define MAX_QUERYPAIRS 64 + +static CURLcode canon_query(struct Curl_easy *data, + const char *query, struct dynbuf *dq) +{ + CURLcode result = CURLE_OK; + int entry = 0; + int i; + const char *p = query; + struct pair array[MAX_QUERYPAIRS]; + struct pair *ap = &array[0]; + if(!query) + return result; + + /* sort the name=value pairs first */ + do { + char *amp; + entry++; + ap->p = p; + amp = strchr(p, '&'); + if(amp) + ap->len = amp - p; /* excluding the ampersand */ + else { + ap->len = strlen(p); + break; + } + ap++; + p = amp + 1; + } while(entry < MAX_QUERYPAIRS); + if(entry == MAX_QUERYPAIRS) { + /* too many query pairs for us */ + failf(data, "aws-sigv4: too many query pairs in URL"); + return CURLE_URL_MALFORMAT; + } + + qsort(&array[0], entry, sizeof(struct pair), compare_func); + + ap = &array[0]; + for(i = 0; !result && (i < entry); i++, ap++) { + size_t len; + const char *q = ap->p; + bool found_equals = false; + if(!ap->len) + continue; + for(len = ap->len; len && !result; q++, len--) { + if(ISALNUM(*q)) + result = Curl_dyn_addn(dq, q, 1); + else { + switch(*q) { + case '-': + case '.': + case '_': + case '~': + /* allowed as-is */ + result = Curl_dyn_addn(dq, q, 1); + break; + case '=': + /* allowed as-is */ + result = Curl_dyn_addn(dq, q, 1); + found_equals = true; + break; + case '%': + /* uppercase the following if hexadecimal */ + if(ISXDIGIT(q[1]) && ISXDIGIT(q[2])) { + char tmp[3]="%"; + tmp[1] = Curl_raw_toupper(q[1]); + tmp[2] = Curl_raw_toupper(q[2]); + result = Curl_dyn_addn(dq, tmp, 3); + q += 2; + len -= 2; + } + else + /* '%' without a following two-digit hex, encode it */ + result = Curl_dyn_addn(dq, "%25", 3); + break; + default: { + /* URL encode */ + const char hex[] = "0123456789ABCDEF"; + char out[3]={'%'}; + out[1] = hex[((unsigned char)*q)>>4]; + out[2] = hex[*q & 0xf]; + result = Curl_dyn_addn(dq, out, 3); + break; + } + } + } + } + if(!result && !found_equals) { + /* queries without value still need an equals */ + result = Curl_dyn_addn(dq, "=", 1); + } + if(!result && i < entry - 1) { + /* insert ampersands between query pairs */ + result = Curl_dyn_addn(dq, "&", 1); + } + } + return result; +} + + +CURLcode Curl_output_aws_sigv4(struct Curl_easy *data, bool proxy) +{ + CURLcode result = CURLE_OUT_OF_MEMORY; + struct connectdata *conn = data->conn; + size_t len; + const char *arg; + char provider0[MAX_SIGV4_LEN + 1]=""; + char provider1[MAX_SIGV4_LEN + 1]=""; + char region[MAX_SIGV4_LEN + 1]=""; + char service[MAX_SIGV4_LEN + 1]=""; + bool sign_as_s3 = false; + const char *hostname = conn->host.name; + time_t clock; + struct tm tm; + char timestamp[TIMESTAMP_SIZE]; + char date[9]; + struct dynbuf canonical_headers; + struct dynbuf signed_headers; + struct dynbuf canonical_query; + char *date_header = NULL; + Curl_HttpReq httpreq; + const char *method = NULL; + char *payload_hash = NULL; + size_t payload_hash_len = 0; + unsigned char sha_hash[SHA256_DIGEST_LENGTH]; + char sha_hex[SHA256_HEX_LENGTH]; + char content_sha256_hdr[CONTENT_SHA256_HDR_LEN + 2] = ""; /* add \r\n */ + char *canonical_request = NULL; + char *request_type = NULL; + char *credential_scope = NULL; + char *str_to_sign = NULL; + const char *user = data->state.aptr.user ? data->state.aptr.user : ""; + char *secret = NULL; + unsigned char sign0[SHA256_DIGEST_LENGTH] = {0}; + unsigned char sign1[SHA256_DIGEST_LENGTH] = {0}; + char *auth_headers = NULL; + + DEBUGASSERT(!proxy); + (void)proxy; + + if(Curl_checkheaders(data, STRCONST("Authorization"))) { + /* Authorization already present, Bailing out */ + return CURLE_OK; + } + + /* we init those buffers here, so goto fail will free initialized dynbuf */ + Curl_dyn_init(&canonical_headers, CURL_MAX_HTTP_HEADER); + Curl_dyn_init(&canonical_query, CURL_MAX_HTTP_HEADER); + Curl_dyn_init(&signed_headers, CURL_MAX_HTTP_HEADER); + + /* + * Parameters parsing + * Google and Outscale use the same OSC or GOOG, + * but Amazon uses AWS and AMZ for header arguments. + * AWS is the default because most of non-amazon providers + * are still using aws:amz as a prefix. + */ + arg = data->set.str[STRING_AWS_SIGV4] ? + data->set.str[STRING_AWS_SIGV4] : "aws:amz"; + + /* provider1[:provider2[:region[:service]]] + + No string can be longer than N bytes of non-whitespace + */ + (void)sscanf(arg, "%" MAX_SIGV4_LEN_TXT "[^:]" + ":%" MAX_SIGV4_LEN_TXT "[^:]" + ":%" MAX_SIGV4_LEN_TXT "[^:]" + ":%" MAX_SIGV4_LEN_TXT "s", + provider0, provider1, region, service); + if(!provider0[0]) { + failf(data, "first aws-sigv4 provider can't be empty"); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto fail; + } + else if(!provider1[0]) + strcpy(provider1, provider0); + + if(!service[0]) { + char *hostdot = strchr(hostname, '.'); + if(!hostdot) { + failf(data, "aws-sigv4: service missing in parameters and hostname"); + result = CURLE_URL_MALFORMAT; + goto fail; + } + len = hostdot - hostname; + if(len > MAX_SIGV4_LEN) { + failf(data, "aws-sigv4: service too long in hostname"); + result = CURLE_URL_MALFORMAT; + goto fail; + } + memcpy(service, hostname, len); + service[len] = '\0'; + + infof(data, "aws_sigv4: picked service %s from host", service); + + if(!region[0]) { + const char *reg = hostdot + 1; + const char *hostreg = strchr(reg, '.'); + if(!hostreg) { + failf(data, "aws-sigv4: region missing in parameters and hostname"); + result = CURLE_URL_MALFORMAT; + goto fail; + } + len = hostreg - reg; + if(len > MAX_SIGV4_LEN) { + failf(data, "aws-sigv4: region too long in hostname"); + result = CURLE_URL_MALFORMAT; + goto fail; + } + memcpy(region, reg, len); + region[len] = '\0'; + infof(data, "aws_sigv4: picked region %s from host", region); + } + } + + Curl_http_method(data, conn, &method, &httpreq); + + /* AWS S3 requires a x-amz-content-sha256 header, and supports special + * values like UNSIGNED-PAYLOAD */ + sign_as_s3 = (strcasecompare(provider0, "aws") && + strcasecompare(service, "s3")); + + payload_hash = parse_content_sha_hdr(data, provider1, &payload_hash_len); + + if(!payload_hash) { + if(sign_as_s3) + result = calc_s3_payload_hash(data, httpreq, provider1, sha_hash, + sha_hex, content_sha256_hdr); + else + result = calc_payload_hash(data, sha_hash, sha_hex); + if(result) + goto fail; + + payload_hash = sha_hex; + /* may be shorter than SHA256_HEX_LENGTH, like S3_UNSIGNED_PAYLOAD */ + payload_hash_len = strlen(sha_hex); + } + +#ifdef DEBUGBUILD + { + char *force_timestamp = getenv("CURL_FORCETIME"); + if(force_timestamp) + clock = 0; + else + time(&clock); + } +#else + time(&clock); +#endif + result = Curl_gmtime(clock, &tm); + if(result) { + goto fail; + } + if(!strftime(timestamp, sizeof(timestamp), "%Y%m%dT%H%M%SZ", &tm)) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + result = make_headers(data, hostname, timestamp, provider1, + &date_header, content_sha256_hdr, + &canonical_headers, &signed_headers); + if(result) + goto fail; + + if(*content_sha256_hdr) { + /* make_headers() needed this without the \r\n for canonicalization */ + size_t hdrlen = strlen(content_sha256_hdr); + DEBUGASSERT(hdrlen + 3 < sizeof(content_sha256_hdr)); + memcpy(content_sha256_hdr + hdrlen, "\r\n", 3); + } + + memcpy(date, timestamp, sizeof(date)); + date[sizeof(date) - 1] = 0; + + result = canon_query(data, data->state.up.query, &canonical_query); + if(result) + goto fail; + result = CURLE_OUT_OF_MEMORY; + + canonical_request = + curl_maprintf("%s\n" /* HTTPRequestMethod */ + "%s\n" /* CanonicalURI */ + "%s\n" /* CanonicalQueryString */ + "%s\n" /* CanonicalHeaders */ + "%s\n" /* SignedHeaders */ + "%.*s", /* HashedRequestPayload in hex */ + method, + data->state.up.path, + Curl_dyn_ptr(&canonical_query) ? + Curl_dyn_ptr(&canonical_query) : "", + Curl_dyn_ptr(&canonical_headers), + Curl_dyn_ptr(&signed_headers), + (int)payload_hash_len, payload_hash); + if(!canonical_request) + goto fail; + + DEBUGF(infof(data, "Canonical request: %s", canonical_request)); + + /* provider 0 lowercase */ + Curl_strntolower(provider0, provider0, strlen(provider0)); + request_type = curl_maprintf("%s4_request", provider0); + if(!request_type) + goto fail; + + credential_scope = curl_maprintf("%s/%s/%s/%s", + date, region, service, request_type); + if(!credential_scope) + goto fail; + + if(Curl_sha256it(sha_hash, (unsigned char *) canonical_request, + strlen(canonical_request))) + goto fail; + + sha256_to_hex(sha_hex, sha_hash); + + /* provider 0 uppercase */ + Curl_strntoupper(provider0, provider0, strlen(provider0)); + + /* + * Google allows using RSA key instead of HMAC, so this code might change + * in the future. For now we only support HMAC. + */ + str_to_sign = curl_maprintf("%s4-HMAC-SHA256\n" /* Algorithm */ + "%s\n" /* RequestDateTime */ + "%s\n" /* CredentialScope */ + "%s", /* HashedCanonicalRequest in hex */ + provider0, + timestamp, + credential_scope, + sha_hex); + if(!str_to_sign) { + goto fail; + } + + /* provider 0 uppercase */ + secret = curl_maprintf("%s4%s", provider0, + data->state.aptr.passwd ? + data->state.aptr.passwd : ""); + if(!secret) + goto fail; + + HMAC_SHA256(secret, strlen(secret), date, strlen(date), sign0); + HMAC_SHA256(sign0, sizeof(sign0), region, strlen(region), sign1); + HMAC_SHA256(sign1, sizeof(sign1), service, strlen(service), sign0); + HMAC_SHA256(sign0, sizeof(sign0), request_type, strlen(request_type), sign1); + HMAC_SHA256(sign1, sizeof(sign1), str_to_sign, strlen(str_to_sign), sign0); + + sha256_to_hex(sha_hex, sign0); + + /* provider 0 uppercase */ + auth_headers = curl_maprintf("Authorization: %s4-HMAC-SHA256 " + "Credential=%s/%s, " + "SignedHeaders=%s, " + "Signature=%s\r\n" + /* + * date_header is added here, only if it wasn't + * user-specified (using CURLOPT_HTTPHEADER). + * date_header includes \r\n + */ + "%s" + "%s", /* optional sha256 header includes \r\n */ + provider0, + user, + credential_scope, + Curl_dyn_ptr(&signed_headers), + sha_hex, + date_header ? date_header : "", + content_sha256_hdr); + if(!auth_headers) { + goto fail; + } + + Curl_safefree(data->state.aptr.userpwd); + data->state.aptr.userpwd = auth_headers; + data->state.authhost.done = TRUE; + result = CURLE_OK; + +fail: + Curl_dyn_free(&canonical_query); + Curl_dyn_free(&canonical_headers); + Curl_dyn_free(&signed_headers); + free(canonical_request); + free(request_type); + free(credential_scope); + free(str_to_sign); + free(secret); + free(date_header); + return result; +} + +#endif /* !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_AWS) */ diff --git a/third_party/curl/lib/http_aws_sigv4.h b/third_party/curl/lib/http_aws_sigv4.h new file mode 100644 index 0000000..57cc570 --- /dev/null +++ b/third_party/curl/lib/http_aws_sigv4.h @@ -0,0 +1,31 @@ +#ifndef HEADER_CURL_HTTP_AWS_SIGV4_H +#define HEADER_CURL_HTTP_AWS_SIGV4_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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.haxx.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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* this is for creating aws_sigv4 header output */ +CURLcode Curl_output_aws_sigv4(struct Curl_easy *data, bool proxy); + +#endif /* HEADER_CURL_HTTP_AWS_SIGV4_H */ diff --git a/third_party/curl/lib/http_chunks.c b/third_party/curl/lib/http_chunks.c new file mode 100644 index 0000000..48e7e46 --- /dev/null +++ b/third_party/curl/lib/http_chunks.c @@ -0,0 +1,681 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_HTTP + +#include "urldata.h" /* it includes http_chunks.h */ +#include "curl_printf.h" +#include "curl_trc.h" +#include "sendf.h" /* for the client write stuff */ +#include "dynbuf.h" +#include "content_encoding.h" +#include "http.h" +#include "multiif.h" +#include "strtoofft.h" +#include "warnless.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Chunk format (simplified): + * + * [ chunk extension ] CRLF + * CRLF + * + * Highlights from RFC2616 section 3.6 say: + + The chunked encoding modifies the body of a message in order to + transfer it as a series of chunks, each with its own size indicator, + followed by an OPTIONAL trailer containing entity-header fields. This + allows dynamically produced content to be transferred along with the + information necessary for the recipient to verify that it has + received the full message. + + Chunked-Body = *chunk + last-chunk + trailer + CRLF + + chunk = chunk-size [ chunk-extension ] CRLF + chunk-data CRLF + chunk-size = 1*HEX + last-chunk = 1*("0") [ chunk-extension ] CRLF + + chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] ) + chunk-ext-name = token + chunk-ext-val = token | quoted-string + chunk-data = chunk-size(OCTET) + trailer = *(entity-header CRLF) + + The chunk-size field is a string of hex digits indicating the size of + the chunk. The chunked encoding is ended by any chunk whose size is + zero, followed by the trailer, which is terminated by an empty line. + + */ + +void Curl_httpchunk_init(struct Curl_easy *data, struct Curl_chunker *ch, + bool ignore_body) +{ + (void)data; + ch->hexindex = 0; /* start at 0 */ + ch->state = CHUNK_HEX; /* we get hex first! */ + ch->last_code = CHUNKE_OK; + Curl_dyn_init(&ch->trailer, DYN_H1_TRAILER); + ch->ignore_body = ignore_body; +} + +void Curl_httpchunk_reset(struct Curl_easy *data, struct Curl_chunker *ch, + bool ignore_body) +{ + (void)data; + ch->hexindex = 0; /* start at 0 */ + ch->state = CHUNK_HEX; /* we get hex first! */ + ch->last_code = CHUNKE_OK; + Curl_dyn_reset(&ch->trailer); + ch->ignore_body = ignore_body; +} + +void Curl_httpchunk_free(struct Curl_easy *data, struct Curl_chunker *ch) +{ + (void)data; + Curl_dyn_free(&ch->trailer); +} + +bool Curl_httpchunk_is_done(struct Curl_easy *data, struct Curl_chunker *ch) +{ + (void)data; + return ch->state == CHUNK_DONE; +} + +static CURLcode httpchunk_readwrite(struct Curl_easy *data, + struct Curl_chunker *ch, + struct Curl_cwriter *cw_next, + const char *buf, size_t blen, + size_t *pconsumed) +{ + CURLcode result = CURLE_OK; + size_t piece; + + *pconsumed = 0; /* nothing's written yet */ + /* first check terminal states that will not progress anywhere */ + if(ch->state == CHUNK_DONE) + return CURLE_OK; + if(ch->state == CHUNK_FAILED) + return CURLE_RECV_ERROR; + + /* the original data is written to the client, but we go on with the + chunk read process, to properly calculate the content length */ + if(data->set.http_te_skip && !ch->ignore_body) { + if(cw_next) + result = Curl_cwriter_write(data, cw_next, CLIENTWRITE_BODY, buf, blen); + else + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)buf, blen); + if(result) { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_PASSTHRU_ERROR; + return result; + } + } + + while(blen) { + switch(ch->state) { + case CHUNK_HEX: + if(ISXDIGIT(*buf)) { + if(ch->hexindex >= CHUNK_MAXNUM_LEN) { + failf(data, "chunk hex-length longer than %d", CHUNK_MAXNUM_LEN); + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_TOO_LONG_HEX; /* longer than we support */ + return CURLE_RECV_ERROR; + } + ch->hexbuffer[ch->hexindex++] = *buf; + buf++; + blen--; + (*pconsumed)++; + } + else { + if(0 == ch->hexindex) { + /* This is illegal data, we received junk where we expected + a hexadecimal digit. */ + failf(data, "chunk hex-length char not a hex digit: 0x%x", *buf); + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_ILLEGAL_HEX; + return CURLE_RECV_ERROR; + } + + /* blen and buf are unmodified */ + ch->hexbuffer[ch->hexindex] = 0; + if(curlx_strtoofft(ch->hexbuffer, NULL, 16, &ch->datasize)) { + failf(data, "chunk hex-length not valid: '%s'", ch->hexbuffer); + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_ILLEGAL_HEX; + return CURLE_RECV_ERROR; + } + ch->state = CHUNK_LF; /* now wait for the CRLF */ + } + break; + + case CHUNK_LF: + /* waiting for the LF after a chunk size */ + if(*buf == 0x0a) { + /* we're now expecting data to come, unless size was zero! */ + if(0 == ch->datasize) { + ch->state = CHUNK_TRAILER; /* now check for trailers */ + } + else { + ch->state = CHUNK_DATA; + CURL_TRC_WRITE(data, "http_chunked, chunk start of %" + CURL_FORMAT_CURL_OFF_T " bytes", ch->datasize); + } + } + + buf++; + blen--; + (*pconsumed)++; + break; + + case CHUNK_DATA: + /* We expect 'datasize' of data. We have 'blen' right now, it can be + more or less than 'datasize'. Get the smallest piece. + */ + piece = blen; + if(ch->datasize < (curl_off_t)blen) + piece = curlx_sotouz(ch->datasize); + + /* Write the data portion available */ + if(!data->set.http_te_skip && !ch->ignore_body) { + if(cw_next) + result = Curl_cwriter_write(data, cw_next, CLIENTWRITE_BODY, + buf, piece); + else + result = Curl_client_write(data, CLIENTWRITE_BODY, + (char *)buf, piece); + if(result) { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_PASSTHRU_ERROR; + return result; + } + } + + *pconsumed += piece; + ch->datasize -= piece; /* decrease amount left to expect */ + buf += piece; /* move read pointer forward */ + blen -= piece; /* decrease space left in this round */ + CURL_TRC_WRITE(data, "http_chunked, write %zu body bytes, %" + CURL_FORMAT_CURL_OFF_T " bytes in chunk remain", + piece, ch->datasize); + + if(0 == ch->datasize) + /* end of data this round, we now expect a trailing CRLF */ + ch->state = CHUNK_POSTLF; + break; + + case CHUNK_POSTLF: + if(*buf == 0x0a) { + /* The last one before we go back to hex state and start all over. */ + Curl_httpchunk_reset(data, ch, ch->ignore_body); + } + else if(*buf != 0x0d) { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_BAD_CHUNK; + return CURLE_RECV_ERROR; + } + buf++; + blen--; + (*pconsumed)++; + break; + + case CHUNK_TRAILER: + if((*buf == 0x0d) || (*buf == 0x0a)) { + char *tr = Curl_dyn_ptr(&ch->trailer); + /* this is the end of a trailer, but if the trailer was zero bytes + there was no trailer and we move on */ + + if(tr) { + size_t trlen; + result = Curl_dyn_addn(&ch->trailer, (char *)STRCONST("\x0d\x0a")); + if(result) { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_OUT_OF_MEMORY; + return result; + } + tr = Curl_dyn_ptr(&ch->trailer); + trlen = Curl_dyn_len(&ch->trailer); + if(!data->set.http_te_skip) { + if(cw_next) + result = Curl_cwriter_write(data, cw_next, + CLIENTWRITE_HEADER| + CLIENTWRITE_TRAILER, + tr, trlen); + else + result = Curl_client_write(data, + CLIENTWRITE_HEADER| + CLIENTWRITE_TRAILER, + tr, trlen); + if(result) { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_PASSTHRU_ERROR; + return result; + } + } + Curl_dyn_reset(&ch->trailer); + ch->state = CHUNK_TRAILER_CR; + if(*buf == 0x0a) + /* already on the LF */ + break; + } + else { + /* no trailer, we're on the final CRLF pair */ + ch->state = CHUNK_TRAILER_POSTCR; + break; /* don't advance the pointer */ + } + } + else { + result = Curl_dyn_addn(&ch->trailer, buf, 1); + if(result) { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_OUT_OF_MEMORY; + return result; + } + } + buf++; + blen--; + (*pconsumed)++; + break; + + case CHUNK_TRAILER_CR: + if(*buf == 0x0a) { + ch->state = CHUNK_TRAILER_POSTCR; + buf++; + blen--; + (*pconsumed)++; + } + else { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_BAD_CHUNK; + return CURLE_RECV_ERROR; + } + break; + + case CHUNK_TRAILER_POSTCR: + /* We enter this state when a CR should arrive so we expect to + have to first pass a CR before we wait for LF */ + if((*buf != 0x0d) && (*buf != 0x0a)) { + /* not a CR then it must be another header in the trailer */ + ch->state = CHUNK_TRAILER; + break; + } + if(*buf == 0x0d) { + /* skip if CR */ + buf++; + blen--; + (*pconsumed)++; + } + /* now wait for the final LF */ + ch->state = CHUNK_STOP; + break; + + case CHUNK_STOP: + if(*buf == 0x0a) { + blen--; + (*pconsumed)++; + /* Record the length of any data left in the end of the buffer + even if there's no more chunks to read */ + ch->datasize = blen; + ch->state = CHUNK_DONE; + CURL_TRC_WRITE(data, "http_chunk, response complete"); + return CURLE_OK; + } + else { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_BAD_CHUNK; + CURL_TRC_WRITE(data, "http_chunk error, expected 0x0a, seeing 0x%ux", + (unsigned int)*buf); + return CURLE_RECV_ERROR; + } + case CHUNK_DONE: + return CURLE_OK; + + case CHUNK_FAILED: + return CURLE_RECV_ERROR; + } + + } + return CURLE_OK; +} + +static const char *Curl_chunked_strerror(CHUNKcode code) +{ + switch(code) { + default: + return "OK"; + case CHUNKE_TOO_LONG_HEX: + return "Too long hexadecimal number"; + case CHUNKE_ILLEGAL_HEX: + return "Illegal or missing hexadecimal sequence"; + case CHUNKE_BAD_CHUNK: + return "Malformed encoding found"; + case CHUNKE_PASSTHRU_ERROR: + return "Error writing data to client"; + case CHUNKE_BAD_ENCODING: + return "Bad content-encoding found"; + case CHUNKE_OUT_OF_MEMORY: + return "Out of memory"; + } +} + +CURLcode Curl_httpchunk_read(struct Curl_easy *data, + struct Curl_chunker *ch, + char *buf, size_t blen, + size_t *pconsumed) +{ + return httpchunk_readwrite(data, ch, NULL, buf, blen, pconsumed); +} + +struct chunked_writer { + struct Curl_cwriter super; + struct Curl_chunker ch; +}; + +static CURLcode cw_chunked_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct chunked_writer *ctx = writer->ctx; + + data->req.chunk = TRUE; /* chunks coming our way. */ + Curl_httpchunk_init(data, &ctx->ch, FALSE); + return CURLE_OK; +} + +static void cw_chunked_close(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct chunked_writer *ctx = writer->ctx; + Curl_httpchunk_free(data, &ctx->ch); +} + +static CURLcode cw_chunked_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t blen) +{ + struct chunked_writer *ctx = writer->ctx; + CURLcode result; + size_t consumed; + + if(!(type & CLIENTWRITE_BODY)) + return Curl_cwriter_write(data, writer->next, type, buf, blen); + + consumed = 0; + result = httpchunk_readwrite(data, &ctx->ch, writer->next, buf, blen, + &consumed); + + if(result) { + if(CHUNKE_PASSTHRU_ERROR == ctx->ch.last_code) { + failf(data, "Failed reading the chunked-encoded stream"); + } + else { + failf(data, "%s in chunked-encoding", + Curl_chunked_strerror(ctx->ch.last_code)); + } + return result; + } + + blen -= consumed; + if(CHUNK_DONE == ctx->ch.state) { + /* chunks read successfully, download is complete */ + data->req.download_done = TRUE; + if(blen) { + infof(data, "Leftovers after chunking: %zu bytes", blen); + } + } + else if((type & CLIENTWRITE_EOS) && !data->req.no_body) { + failf(data, "transfer closed with outstanding read data remaining"); + return CURLE_PARTIAL_FILE; + } + + return CURLE_OK; +} + +/* HTTP chunked Transfer-Encoding decoder */ +const struct Curl_cwtype Curl_httpchunk_unencoder = { + "chunked", + NULL, + cw_chunked_init, + cw_chunked_write, + cw_chunked_close, + sizeof(struct chunked_writer) +}; + +/* max length of a HTTP chunk that we want to generate */ +#define CURL_CHUNKED_MINLEN (1024) +#define CURL_CHUNKED_MAXLEN (64 * 1024) + +struct chunked_reader { + struct Curl_creader super; + struct bufq chunkbuf; + BIT(read_eos); /* we read an EOS from the next reader */ + BIT(eos); /* we have returned an EOS */ +}; + +static CURLcode cr_chunked_init(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct chunked_reader *ctx = reader->ctx; + (void)data; + Curl_bufq_init2(&ctx->chunkbuf, CURL_CHUNKED_MAXLEN, 2, BUFQ_OPT_SOFT_LIMIT); + return CURLE_OK; +} + +static void cr_chunked_close(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct chunked_reader *ctx = reader->ctx; + (void)data; + Curl_bufq_free(&ctx->chunkbuf); +} + +static CURLcode add_last_chunk(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct chunked_reader *ctx = reader->ctx; + struct curl_slist *trailers = NULL, *tr; + CURLcode result; + size_t n; + int rc; + + if(!data->set.trailer_callback) { + CURL_TRC_READ(data, "http_chunk, added last, empty chunk"); + return Curl_bufq_cwrite(&ctx->chunkbuf, STRCONST("0\r\n\r\n"), &n); + } + + result = Curl_bufq_cwrite(&ctx->chunkbuf, STRCONST("0\r\n"), &n); + if(result) + goto out; + + Curl_set_in_callback(data, true); + rc = data->set.trailer_callback(&trailers, data->set.trailer_data); + Curl_set_in_callback(data, false); + + if(rc != CURL_TRAILERFUNC_OK) { + failf(data, "operation aborted by trailing headers callback"); + result = CURLE_ABORTED_BY_CALLBACK; + goto out; + } + + for(tr = trailers; tr; tr = tr->next) { + /* only add correctly formatted trailers */ + char *ptr = strchr(tr->data, ':'); + if(!ptr || *(ptr + 1) != ' ') { + infof(data, "Malformatted trailing header, skipping trailer"); + continue; + } + + result = Curl_bufq_cwrite(&ctx->chunkbuf, tr->data, + strlen(tr->data), &n); + if(!result) + result = Curl_bufq_cwrite(&ctx->chunkbuf, STRCONST("\r\n"), &n); + if(result) + goto out; + } + + result = Curl_bufq_cwrite(&ctx->chunkbuf, STRCONST("\r\n"), &n); + +out: + curl_slist_free_all(trailers); + CURL_TRC_READ(data, "http_chunk, added last chunk with trailers " + "from client -> %d", result); + return result; +} + +static CURLcode add_chunk(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen) +{ + struct chunked_reader *ctx = reader->ctx; + CURLcode result; + char tmp[CURL_CHUNKED_MINLEN]; + size_t nread; + bool eos; + + DEBUGASSERT(!ctx->read_eos); + blen = CURLMIN(blen, CURL_CHUNKED_MAXLEN); /* respect our buffer pref */ + if(blen < sizeof(tmp)) { + /* small read, make a chunk of decent size */ + buf = tmp; + blen = sizeof(tmp); + } + else { + /* larger read, make a chunk that will fit when read back */ + blen -= (8 + 2 + 2); /* deduct max overhead, 8 hex + 2*crlf */ + } + + result = Curl_creader_read(data, reader->next, buf, blen, &nread, &eos); + if(result) + return result; + if(eos) + ctx->read_eos = TRUE; + + if(nread) { + /* actually got bytes, wrap them into the chunkbuf */ + char hd[11] = ""; + int hdlen; + size_t n; + + hdlen = msnprintf(hd, sizeof(hd), "%zx\r\n", nread); + if(hdlen <= 0) + return CURLE_READ_ERROR; + /* On a soft-limited bufq, we do not need to check that all was written */ + result = Curl_bufq_cwrite(&ctx->chunkbuf, hd, hdlen, &n); + if(!result) + result = Curl_bufq_cwrite(&ctx->chunkbuf, buf, nread, &n); + if(!result) + result = Curl_bufq_cwrite(&ctx->chunkbuf, "\r\n", 2, &n); + CURL_TRC_READ(data, "http_chunk, made chunk of %zu bytes -> %d", + nread, result); + if(result) + return result; + } + + if(ctx->read_eos) + return add_last_chunk(data, reader); + return CURLE_OK; +} + +static CURLcode cr_chunked_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *pnread, bool *peos) +{ + struct chunked_reader *ctx = reader->ctx; + CURLcode result = CURLE_READ_ERROR; + + *pnread = 0; + *peos = ctx->eos; + + if(!ctx->eos) { + if(!ctx->read_eos && Curl_bufq_is_empty(&ctx->chunkbuf)) { + /* Still getting data form the next reader, buffer is empty */ + result = add_chunk(data, reader, buf, blen); + if(result) + return result; + } + + if(!Curl_bufq_is_empty(&ctx->chunkbuf)) { + result = Curl_bufq_cread(&ctx->chunkbuf, buf, blen, pnread); + if(!result && ctx->read_eos && Curl_bufq_is_empty(&ctx->chunkbuf)) { + /* no more data, read all, done. */ + ctx->eos = TRUE; + *peos = TRUE; + } + return result; + } + } + /* We may get here, because we are done or because callbacks paused */ + DEBUGASSERT(ctx->eos || !ctx->read_eos); + return CURLE_OK; +} + +static curl_off_t cr_chunked_total_length(struct Curl_easy *data, + struct Curl_creader *reader) +{ + /* this reader changes length depending on input */ + (void)data; + (void)reader; + return -1; +} + +/* HTTP chunked Transfer-Encoding encoder */ +const struct Curl_crtype Curl_httpchunk_encoder = { + "chunked", + cr_chunked_init, + cr_chunked_read, + cr_chunked_close, + Curl_creader_def_needs_rewind, + cr_chunked_total_length, + Curl_creader_def_resume_from, + Curl_creader_def_rewind, + Curl_creader_def_unpause, + Curl_creader_def_done, + sizeof(struct chunked_reader) +}; + +CURLcode Curl_httpchunk_add_reader(struct Curl_easy *data) +{ + struct Curl_creader *reader = NULL; + CURLcode result; + + result = Curl_creader_create(&reader, data, &Curl_httpchunk_encoder, + CURL_CR_TRANSFER_ENCODE); + if(!result) + result = Curl_creader_add(data, reader); + + if(result && reader) + Curl_creader_free(data, reader); + return result; +} + +#endif /* CURL_DISABLE_HTTP */ diff --git a/third_party/curl/lib/http_chunks.h b/third_party/curl/lib/http_chunks.h new file mode 100644 index 0000000..d3ecc36 --- /dev/null +++ b/third_party/curl/lib/http_chunks.h @@ -0,0 +1,145 @@ +#ifndef HEADER_CURL_HTTP_CHUNKS_H +#define HEADER_CURL_HTTP_CHUNKS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifndef CURL_DISABLE_HTTP + +#include "dynbuf.h" + +struct connectdata; + +/* + * The longest possible hexadecimal number we support in a chunked transfer. + * Neither RFC2616 nor the later HTTP specs define a maximum chunk size. + * For 64 bit curl_off_t we support 16 digits. For 32 bit, 8 digits. + */ +#define CHUNK_MAXNUM_LEN (SIZEOF_CURL_OFF_T * 2) + +typedef enum { + /* await and buffer all hexadecimal digits until we get one that isn't a + hexadecimal digit. When done, we go CHUNK_LF */ + CHUNK_HEX, + + /* wait for LF, ignore all else */ + CHUNK_LF, + + /* We eat the amount of data specified. When done, we move on to the + POST_CR state. */ + CHUNK_DATA, + + /* POSTLF should get a CR and then a LF and nothing else, then move back to + HEX as the CRLF combination marks the end of a chunk. A missing CR is no + big deal. */ + CHUNK_POSTLF, + + /* Used to mark that we're out of the game. NOTE: that there's a 'datasize' + field in the struct that will tell how many bytes that were not passed to + the client in the end of the last buffer! */ + CHUNK_STOP, + + /* At this point optional trailer headers can be found, unless the next line + is CRLF */ + CHUNK_TRAILER, + + /* A trailer CR has been found - next state is CHUNK_TRAILER_POSTCR. + Next char must be a LF */ + CHUNK_TRAILER_CR, + + /* A trailer LF must be found now, otherwise CHUNKE_BAD_CHUNK will be + signalled If this is an empty trailer CHUNKE_STOP will be signalled. + Otherwise the trailer will be broadcasted via Curl_client_write() and the + next state will be CHUNK_TRAILER */ + CHUNK_TRAILER_POSTCR, + + /* Successfully de-chunked everything */ + CHUNK_DONE, + + /* Failed on seeing a bad or not correctly terminated chunk */ + CHUNK_FAILED +} ChunkyState; + +typedef enum { + CHUNKE_OK = 0, + CHUNKE_TOO_LONG_HEX = 1, + CHUNKE_ILLEGAL_HEX, + CHUNKE_BAD_CHUNK, + CHUNKE_BAD_ENCODING, + CHUNKE_OUT_OF_MEMORY, + CHUNKE_PASSTHRU_ERROR /* Curl_httpchunk_read() returns a CURLcode to use */ +} CHUNKcode; + +struct Curl_chunker { + curl_off_t datasize; + ChunkyState state; + CHUNKcode last_code; + struct dynbuf trailer; /* for chunked-encoded trailer */ + unsigned char hexindex; + char hexbuffer[CHUNK_MAXNUM_LEN + 1]; /* +1 for null-terminator */ + BIT(ignore_body); /* never write response body data */ +}; + +/* The following functions are defined in http_chunks.c */ +void Curl_httpchunk_init(struct Curl_easy *data, struct Curl_chunker *ch, + bool ignore_body); +void Curl_httpchunk_free(struct Curl_easy *data, struct Curl_chunker *ch); +void Curl_httpchunk_reset(struct Curl_easy *data, struct Curl_chunker *ch, + bool ignore_body); + +/* + * Read BODY bytes in HTTP/1.1 chunked encoding from `buf` and return + * the amount of bytes consumed. The actual response bytes and trailer + * headers are written out to the client. + * On success, this will consume all bytes up to the end of the response, + * e.g. the last chunk, has been processed. + * @param data the transfer involved + * @param ch the chunker instance keeping state across calls + * @param buf the response data + * @param blen amount of bytes in `buf` + * @param pconsumed on successful return, the number of bytes in `buf` + * consumed + * + * This function always uses ASCII hex values to accommodate non-ASCII hosts. + * For example, 0x0d and 0x0a are used instead of '\r' and '\n'. + */ +CURLcode Curl_httpchunk_read(struct Curl_easy *data, struct Curl_chunker *ch, + char *buf, size_t blen, size_t *pconsumed); + +/** + * @return TRUE iff chunked decoded has finished successfully. + */ +bool Curl_httpchunk_is_done(struct Curl_easy *data, struct Curl_chunker *ch); + +extern const struct Curl_cwtype Curl_httpchunk_unencoder; + +extern const struct Curl_crtype Curl_httpchunk_encoder; + +/** + * Add a transfer-encoding "chunked" reader to the transfers reader stack + */ +CURLcode Curl_httpchunk_add_reader(struct Curl_easy *data); + +#endif /* !CURL_DISABLE_HTTP */ + +#endif /* HEADER_CURL_HTTP_CHUNKS_H */ diff --git a/third_party/curl/lib/http_digest.c b/third_party/curl/lib/http_digest.c new file mode 100644 index 0000000..2db3125 --- /dev/null +++ b/third_party/curl/lib/http_digest.c @@ -0,0 +1,185 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_DIGEST_AUTH) + +#include "urldata.h" +#include "strcase.h" +#include "vauth/vauth.h" +#include "http_digest.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* Test example headers: + +WWW-Authenticate: Digest realm="testrealm", nonce="1053604598" +Proxy-Authenticate: Digest realm="testrealm", nonce="1053604598" + +*/ + +CURLcode Curl_input_digest(struct Curl_easy *data, + bool proxy, + const char *header) /* rest of the *-authenticate: + header */ +{ + /* Point to the correct struct with this */ + struct digestdata *digest; + + if(proxy) { + digest = &data->state.proxydigest; + } + else { + digest = &data->state.digest; + } + + if(!checkprefix("Digest", header) || !ISBLANK(header[6])) + return CURLE_BAD_CONTENT_ENCODING; + + header += strlen("Digest"); + while(*header && ISBLANK(*header)) + header++; + + return Curl_auth_decode_digest_http_message(header, digest); +} + +CURLcode Curl_output_digest(struct Curl_easy *data, + bool proxy, + const unsigned char *request, + const unsigned char *uripath) +{ + CURLcode result; + unsigned char *path = NULL; + char *tmp = NULL; + char *response; + size_t len; + bool have_chlg; + + /* Point to the address of the pointer that holds the string to send to the + server, which is for a plain host or for an HTTP proxy */ + char **allocuserpwd; + + /* Point to the name and password for this */ + const char *userp; + const char *passwdp; + + /* Point to the correct struct with this */ + struct digestdata *digest; + struct auth *authp; + + if(proxy) { +#ifdef CURL_DISABLE_PROXY + return CURLE_NOT_BUILT_IN; +#else + digest = &data->state.proxydigest; + allocuserpwd = &data->state.aptr.proxyuserpwd; + userp = data->state.aptr.proxyuser; + passwdp = data->state.aptr.proxypasswd; + authp = &data->state.authproxy; +#endif + } + else { + digest = &data->state.digest; + allocuserpwd = &data->state.aptr.userpwd; + userp = data->state.aptr.user; + passwdp = data->state.aptr.passwd; + authp = &data->state.authhost; + } + + Curl_safefree(*allocuserpwd); + + /* not set means empty */ + if(!userp) + userp = ""; + + if(!passwdp) + passwdp = ""; + +#if defined(USE_WINDOWS_SSPI) + have_chlg = digest->input_token ? TRUE : FALSE; +#else + have_chlg = digest->nonce ? TRUE : FALSE; +#endif + + if(!have_chlg) { + authp->done = FALSE; + return CURLE_OK; + } + + /* So IE browsers < v7 cut off the URI part at the query part when they + evaluate the MD5 and some (IIS?) servers work with them so we may need to + do the Digest IE-style. Note that the different ways cause different MD5 + sums to get sent. + + Apache servers can be set to do the Digest IE-style automatically using + the BrowserMatch feature: + https://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html#msie + + Further details on Digest implementation differences: + http://www.fngtps.com/2006/09/http-authentication + */ + + if(authp->iestyle) { + tmp = strchr((char *)uripath, '?'); + if(tmp) { + size_t urilen = tmp - (char *)uripath; + /* typecast is fine here since the value is always less than 32 bits */ + path = (unsigned char *) aprintf("%.*s", (int)urilen, uripath); + } + } + if(!tmp) + path = (unsigned char *) strdup((char *) uripath); + + if(!path) + return CURLE_OUT_OF_MEMORY; + + result = Curl_auth_create_digest_http_message(data, userp, passwdp, request, + path, digest, &response, &len); + free(path); + if(result) + return result; + + *allocuserpwd = aprintf("%sAuthorization: Digest %s\r\n", + proxy ? "Proxy-" : "", + response); + free(response); + if(!*allocuserpwd) + return CURLE_OUT_OF_MEMORY; + + authp->done = TRUE; + + return CURLE_OK; +} + +void Curl_http_auth_cleanup_digest(struct Curl_easy *data) +{ + Curl_auth_digest_cleanup(&data->state.digest); + Curl_auth_digest_cleanup(&data->state.proxydigest); +} + +#endif diff --git a/third_party/curl/lib/http_digest.h b/third_party/curl/lib/http_digest.h new file mode 100644 index 0000000..5f79731 --- /dev/null +++ b/third_party/curl/lib/http_digest.h @@ -0,0 +1,44 @@ +#ifndef HEADER_CURL_HTTP_DIGEST_H +#define HEADER_CURL_HTTP_DIGEST_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_DIGEST_AUTH) + +/* this is for digest header input */ +CURLcode Curl_input_digest(struct Curl_easy *data, + bool proxy, const char *header); + +/* this is for creating digest header output */ +CURLcode Curl_output_digest(struct Curl_easy *data, + bool proxy, + const unsigned char *request, + const unsigned char *uripath); + +void Curl_http_auth_cleanup_digest(struct Curl_easy *data); + +#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_DIGEST_AUTH */ + +#endif /* HEADER_CURL_HTTP_DIGEST_H */ diff --git a/third_party/curl/lib/http_negotiate.c b/third_party/curl/lib/http_negotiate.c new file mode 100644 index 0000000..4cbe2df --- /dev/null +++ b/third_party/curl/lib/http_negotiate.c @@ -0,0 +1,239 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO) + +#include "urldata.h" +#include "sendf.h" +#include "http_negotiate.h" +#include "vauth/vauth.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +CURLcode Curl_input_negotiate(struct Curl_easy *data, struct connectdata *conn, + bool proxy, const char *header) +{ + CURLcode result; + size_t len; + + /* Point to the username, password, service and host */ + const char *userp; + const char *passwdp; + const char *service; + const char *host; + + /* Point to the correct struct with this */ + struct negotiatedata *neg_ctx; + curlnegotiate state; + + if(proxy) { +#ifndef CURL_DISABLE_PROXY + userp = conn->http_proxy.user; + passwdp = conn->http_proxy.passwd; + service = data->set.str[STRING_PROXY_SERVICE_NAME] ? + data->set.str[STRING_PROXY_SERVICE_NAME] : "HTTP"; + host = conn->http_proxy.host.name; + neg_ctx = &conn->proxyneg; + state = conn->proxy_negotiate_state; +#else + return CURLE_NOT_BUILT_IN; +#endif + } + else { + userp = conn->user; + passwdp = conn->passwd; + service = data->set.str[STRING_SERVICE_NAME] ? + data->set.str[STRING_SERVICE_NAME] : "HTTP"; + host = conn->host.name; + neg_ctx = &conn->negotiate; + state = conn->http_negotiate_state; + } + + /* Not set means empty */ + if(!userp) + userp = ""; + + if(!passwdp) + passwdp = ""; + + /* Obtain the input token, if any */ + header += strlen("Negotiate"); + while(*header && ISBLANK(*header)) + header++; + + len = strlen(header); + neg_ctx->havenegdata = len != 0; + if(!len) { + if(state == GSS_AUTHSUCC) { + infof(data, "Negotiate auth restarted"); + Curl_http_auth_cleanup_negotiate(conn); + } + else if(state != GSS_AUTHNONE) { + /* The server rejected our authentication and hasn't supplied any more + negotiation mechanisms */ + Curl_http_auth_cleanup_negotiate(conn); + return CURLE_LOGIN_DENIED; + } + } + + /* Supports SSL channel binding for Windows ISS extended protection */ +#if defined(USE_WINDOWS_SSPI) && defined(SECPKG_ATTR_ENDPOINT_BINDINGS) + neg_ctx->sslContext = conn->sslContext; +#endif + + /* Initialize the security context and decode our challenge */ + result = Curl_auth_decode_spnego_message(data, userp, passwdp, service, + host, header, neg_ctx); + + if(result) + Curl_http_auth_cleanup_negotiate(conn); + + return result; +} + +CURLcode Curl_output_negotiate(struct Curl_easy *data, + struct connectdata *conn, bool proxy) +{ + struct negotiatedata *neg_ctx; + struct auth *authp; + curlnegotiate *state; + char *base64 = NULL; + size_t len = 0; + char *userp; + CURLcode result; + + if(proxy) { +#ifndef CURL_DISABLE_PROXY + neg_ctx = &conn->proxyneg; + authp = &data->state.authproxy; + state = &conn->proxy_negotiate_state; +#else + return CURLE_NOT_BUILT_IN; +#endif + } + else { + neg_ctx = &conn->negotiate; + authp = &data->state.authhost; + state = &conn->http_negotiate_state; + } + + authp->done = FALSE; + + if(*state == GSS_AUTHRECV) { + if(neg_ctx->havenegdata) { + neg_ctx->havemultiplerequests = TRUE; + } + } + else if(*state == GSS_AUTHSUCC) { + if(!neg_ctx->havenoauthpersist) { + neg_ctx->noauthpersist = !neg_ctx->havemultiplerequests; + } + } + + if(neg_ctx->noauthpersist || + (*state != GSS_AUTHDONE && *state != GSS_AUTHSUCC)) { + + if(neg_ctx->noauthpersist && *state == GSS_AUTHSUCC) { + infof(data, "Curl_output_negotiate, " + "no persistent authentication: cleanup existing context"); + Curl_http_auth_cleanup_negotiate(conn); + } + if(!neg_ctx->context) { + result = Curl_input_negotiate(data, conn, proxy, "Negotiate"); + if(result == CURLE_AUTH_ERROR) { + /* negotiate auth failed, let's continue unauthenticated to stay + * compatible with the behavior before curl-7_64_0-158-g6c6035532 */ + authp->done = TRUE; + return CURLE_OK; + } + else if(result) + return result; + } + + result = Curl_auth_create_spnego_message(neg_ctx, &base64, &len); + if(result) + return result; + + userp = aprintf("%sAuthorization: Negotiate %s\r\n", proxy ? "Proxy-" : "", + base64); + + if(proxy) { +#ifndef CURL_DISABLE_PROXY + Curl_safefree(data->state.aptr.proxyuserpwd); + data->state.aptr.proxyuserpwd = userp; +#endif + } + else { + Curl_safefree(data->state.aptr.userpwd); + data->state.aptr.userpwd = userp; + } + + free(base64); + + if(!userp) { + return CURLE_OUT_OF_MEMORY; + } + + *state = GSS_AUTHSENT; + #ifdef HAVE_GSSAPI + if(neg_ctx->status == GSS_S_COMPLETE || + neg_ctx->status == GSS_S_CONTINUE_NEEDED) { + *state = GSS_AUTHDONE; + } + #else + #ifdef USE_WINDOWS_SSPI + if(neg_ctx->status == SEC_E_OK || + neg_ctx->status == SEC_I_CONTINUE_NEEDED) { + *state = GSS_AUTHDONE; + } + #endif + #endif + } + + if(*state == GSS_AUTHDONE || *state == GSS_AUTHSUCC) { + /* connection is already authenticated, + * don't send a header in future requests */ + authp->done = TRUE; + } + + neg_ctx->havenegdata = FALSE; + + return CURLE_OK; +} + +void Curl_http_auth_cleanup_negotiate(struct connectdata *conn) +{ + conn->http_negotiate_state = GSS_AUTHNONE; + conn->proxy_negotiate_state = GSS_AUTHNONE; + + Curl_auth_cleanup_spnego(&conn->negotiate); + Curl_auth_cleanup_spnego(&conn->proxyneg); +} + +#endif /* !CURL_DISABLE_HTTP && USE_SPNEGO */ diff --git a/third_party/curl/lib/http_negotiate.h b/third_party/curl/lib/http_negotiate.h new file mode 100644 index 0000000..76d8356 --- /dev/null +++ b/third_party/curl/lib/http_negotiate.h @@ -0,0 +1,43 @@ +#ifndef HEADER_CURL_HTTP_NEGOTIATE_H +#define HEADER_CURL_HTTP_NEGOTIATE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO) + +/* this is for Negotiate header input */ +CURLcode Curl_input_negotiate(struct Curl_easy *data, struct connectdata *conn, + bool proxy, const char *header); + +/* this is for creating Negotiate header output */ +CURLcode Curl_output_negotiate(struct Curl_easy *data, + struct connectdata *conn, bool proxy); + +void Curl_http_auth_cleanup_negotiate(struct connectdata *conn); + +#else /* !CURL_DISABLE_HTTP && USE_SPNEGO */ +#define Curl_http_auth_cleanup_negotiate(x) +#endif + +#endif /* HEADER_CURL_HTTP_NEGOTIATE_H */ diff --git a/third_party/curl/lib/http_ntlm.c b/third_party/curl/lib/http_ntlm.c new file mode 100644 index 0000000..3dccb5c --- /dev/null +++ b/third_party/curl/lib/http_ntlm.c @@ -0,0 +1,270 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) + +/* + * NTLM details: + * + * https://davenport.sourceforge.net/ntlm.html + * https://www.innovation.ch/java/ntlm.html + */ + +#define DEBUG_ME 0 + +#include "urldata.h" +#include "sendf.h" +#include "strcase.h" +#include "http_ntlm.h" +#include "curl_ntlm_core.h" +#include "curl_base64.h" +#include "vauth/vauth.h" +#include "url.h" + +/* SSL backend-specific #if branches in this file must be kept in the order + documented in curl_ntlm_core. */ +#if defined(USE_WINDOWS_SSPI) +#include "curl_sspi.h" +#endif + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if DEBUG_ME +# define DEBUG_OUT(x) x +#else +# define DEBUG_OUT(x) Curl_nop_stmt +#endif + +CURLcode Curl_input_ntlm(struct Curl_easy *data, + bool proxy, /* if proxy or not */ + const char *header) /* rest of the www-authenticate: + header */ +{ + /* point to the correct struct with this */ + struct ntlmdata *ntlm; + curlntlm *state; + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + ntlm = proxy ? &conn->proxyntlm : &conn->ntlm; + state = proxy ? &conn->proxy_ntlm_state : &conn->http_ntlm_state; + + if(checkprefix("NTLM", header)) { + header += strlen("NTLM"); + + while(*header && ISSPACE(*header)) + header++; + + if(*header) { + unsigned char *hdr; + size_t hdrlen; + + result = Curl_base64_decode(header, &hdr, &hdrlen); + if(!result) { + struct bufref hdrbuf; + + Curl_bufref_init(&hdrbuf); + Curl_bufref_set(&hdrbuf, hdr, hdrlen, curl_free); + result = Curl_auth_decode_ntlm_type2_message(data, &hdrbuf, ntlm); + Curl_bufref_free(&hdrbuf); + } + if(result) + return result; + + *state = NTLMSTATE_TYPE2; /* We got a type-2 message */ + } + else { + if(*state == NTLMSTATE_LAST) { + infof(data, "NTLM auth restarted"); + Curl_http_auth_cleanup_ntlm(conn); + } + else if(*state == NTLMSTATE_TYPE3) { + infof(data, "NTLM handshake rejected"); + Curl_http_auth_cleanup_ntlm(conn); + *state = NTLMSTATE_NONE; + return CURLE_REMOTE_ACCESS_DENIED; + } + else if(*state >= NTLMSTATE_TYPE1) { + infof(data, "NTLM handshake failure (internal error)"); + return CURLE_REMOTE_ACCESS_DENIED; + } + + *state = NTLMSTATE_TYPE1; /* We should send away a type-1 */ + } + } + + return result; +} + +/* + * This is for creating ntlm header output + */ +CURLcode Curl_output_ntlm(struct Curl_easy *data, bool proxy) +{ + char *base64 = NULL; + size_t len = 0; + CURLcode result = CURLE_OK; + struct bufref ntlmmsg; + + /* point to the address of the pointer that holds the string to send to the + server, which is for a plain host or for an HTTP proxy */ + char **allocuserpwd; + + /* point to the username, password, service and host */ + const char *userp; + const char *passwdp; + const char *service = NULL; + const char *hostname = NULL; + + /* point to the correct struct with this */ + struct ntlmdata *ntlm; + curlntlm *state; + struct auth *authp; + struct connectdata *conn = data->conn; + + DEBUGASSERT(conn); + DEBUGASSERT(data); + + if(proxy) { +#ifndef CURL_DISABLE_PROXY + allocuserpwd = &data->state.aptr.proxyuserpwd; + userp = data->state.aptr.proxyuser; + passwdp = data->state.aptr.proxypasswd; + service = data->set.str[STRING_PROXY_SERVICE_NAME] ? + data->set.str[STRING_PROXY_SERVICE_NAME] : "HTTP"; + hostname = conn->http_proxy.host.name; + ntlm = &conn->proxyntlm; + state = &conn->proxy_ntlm_state; + authp = &data->state.authproxy; +#else + return CURLE_NOT_BUILT_IN; +#endif + } + else { + allocuserpwd = &data->state.aptr.userpwd; + userp = data->state.aptr.user; + passwdp = data->state.aptr.passwd; + service = data->set.str[STRING_SERVICE_NAME] ? + data->set.str[STRING_SERVICE_NAME] : "HTTP"; + hostname = conn->host.name; + ntlm = &conn->ntlm; + state = &conn->http_ntlm_state; + authp = &data->state.authhost; + } + authp->done = FALSE; + + /* not set means empty */ + if(!userp) + userp = ""; + + if(!passwdp) + passwdp = ""; + +#ifdef USE_WINDOWS_SSPI + if(!s_hSecDll) { + /* not thread safe and leaks - use curl_global_init() to avoid */ + CURLcode err = Curl_sspi_global_init(); + if(!s_hSecDll) + return err; + } +#ifdef SECPKG_ATTR_ENDPOINT_BINDINGS + ntlm->sslContext = conn->sslContext; +#endif +#endif + + Curl_bufref_init(&ntlmmsg); + + /* connection is already authenticated, don't send a header in future + * requests so go directly to NTLMSTATE_LAST */ + if(*state == NTLMSTATE_TYPE3) + *state = NTLMSTATE_LAST; + + switch(*state) { + case NTLMSTATE_TYPE1: + default: /* for the weird cases we (re)start here */ + /* Create a type-1 message */ + result = Curl_auth_create_ntlm_type1_message(data, userp, passwdp, + service, hostname, + ntlm, &ntlmmsg); + if(!result) { + DEBUGASSERT(Curl_bufref_len(&ntlmmsg) != 0); + result = Curl_base64_encode((const char *) Curl_bufref_ptr(&ntlmmsg), + Curl_bufref_len(&ntlmmsg), &base64, &len); + if(!result) { + free(*allocuserpwd); + *allocuserpwd = aprintf("%sAuthorization: NTLM %s\r\n", + proxy ? "Proxy-" : "", + base64); + free(base64); + if(!*allocuserpwd) + result = CURLE_OUT_OF_MEMORY; + } + } + break; + + case NTLMSTATE_TYPE2: + /* We already received the type-2 message, create a type-3 message */ + result = Curl_auth_create_ntlm_type3_message(data, userp, passwdp, + ntlm, &ntlmmsg); + if(!result && Curl_bufref_len(&ntlmmsg)) { + result = Curl_base64_encode((const char *) Curl_bufref_ptr(&ntlmmsg), + Curl_bufref_len(&ntlmmsg), &base64, &len); + if(!result) { + free(*allocuserpwd); + *allocuserpwd = aprintf("%sAuthorization: NTLM %s\r\n", + proxy ? "Proxy-" : "", + base64); + free(base64); + if(!*allocuserpwd) + result = CURLE_OUT_OF_MEMORY; + else { + *state = NTLMSTATE_TYPE3; /* we send a type-3 */ + authp->done = TRUE; + } + } + } + break; + + case NTLMSTATE_LAST: + Curl_safefree(*allocuserpwd); + authp->done = TRUE; + break; + } + Curl_bufref_free(&ntlmmsg); + + return result; +} + +void Curl_http_auth_cleanup_ntlm(struct connectdata *conn) +{ + Curl_auth_cleanup_ntlm(&conn->ntlm); + Curl_auth_cleanup_ntlm(&conn->proxyntlm); +} + +#endif /* !CURL_DISABLE_HTTP && USE_NTLM */ diff --git a/third_party/curl/lib/http_ntlm.h b/third_party/curl/lib/http_ntlm.h new file mode 100644 index 0000000..f37572b --- /dev/null +++ b/third_party/curl/lib/http_ntlm.h @@ -0,0 +1,44 @@ +#ifndef HEADER_CURL_HTTP_NTLM_H +#define HEADER_CURL_HTTP_NTLM_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) + +/* this is for ntlm header input */ +CURLcode Curl_input_ntlm(struct Curl_easy *data, bool proxy, + const char *header); + +/* this is for creating ntlm header output */ +CURLcode Curl_output_ntlm(struct Curl_easy *data, bool proxy); + +void Curl_http_auth_cleanup_ntlm(struct connectdata *conn); + +#else /* !CURL_DISABLE_HTTP && USE_NTLM */ +#define Curl_http_auth_cleanup_ntlm(x) +#endif + +#endif /* HEADER_CURL_HTTP_NTLM_H */ diff --git a/third_party/curl/lib/http_proxy.c b/third_party/curl/lib/http_proxy.c new file mode 100644 index 0000000..7c035d4 --- /dev/null +++ b/third_party/curl/lib/http_proxy.c @@ -0,0 +1,336 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "http_proxy.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_PROXY) + +#include +#ifdef USE_HYPER +#include +#endif +#include "sendf.h" +#include "http.h" +#include "url.h" +#include "select.h" +#include "progress.h" +#include "cfilters.h" +#include "cf-h1-proxy.h" +#include "cf-h2-proxy.h" +#include "connect.h" +#include "curlx.h" +#include "vtls/vtls.h" +#include "transfer.h" +#include "multiif.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +CURLcode Curl_http_proxy_get_destination(struct Curl_cfilter *cf, + const char **phostname, + int *pport, bool *pipv6_ip) +{ + DEBUGASSERT(cf); + DEBUGASSERT(cf->conn); + + if(cf->conn->bits.conn_to_host) + *phostname = cf->conn->conn_to_host.name; + else if(cf->sockindex == SECONDARYSOCKET) + *phostname = cf->conn->secondaryhostname; + else + *phostname = cf->conn->host.name; + + if(cf->sockindex == SECONDARYSOCKET) + *pport = cf->conn->secondary_port; + else if(cf->conn->bits.conn_to_port) + *pport = cf->conn->conn_to_port; + else + *pport = cf->conn->remote_port; + + if(*phostname != cf->conn->host.name) + *pipv6_ip = (strchr(*phostname, ':') != NULL); + else + *pipv6_ip = cf->conn->bits.ipv6_ip; + + return CURLE_OK; +} + +CURLcode Curl_http_proxy_create_CONNECT(struct httpreq **preq, + struct Curl_cfilter *cf, + struct Curl_easy *data, + int http_version_major) +{ + const char *hostname = NULL; + char *authority = NULL; + int port; + bool ipv6_ip; + CURLcode result; + struct httpreq *req = NULL; + + result = Curl_http_proxy_get_destination(cf, &hostname, &port, &ipv6_ip); + if(result) + goto out; + + authority = aprintf("%s%s%s:%d", ipv6_ip?"[":"", hostname, + ipv6_ip?"]":"", port); + if(!authority) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + result = Curl_http_req_make(&req, "CONNECT", sizeof("CONNECT")-1, + NULL, 0, authority, strlen(authority), + NULL, 0); + if(result) + goto out; + + /* Setup the proxy-authorization header, if any */ + result = Curl_http_output_auth(data, cf->conn, req->method, HTTPREQ_GET, + req->authority, TRUE); + if(result) + goto out; + + /* If user is not overriding Host: header, we add for HTTP/1.x */ + if(http_version_major == 1 && + !Curl_checkProxyheaders(data, cf->conn, STRCONST("Host"))) { + result = Curl_dynhds_cadd(&req->headers, "Host", authority); + if(result) + goto out; + } + + if(data->state.aptr.proxyuserpwd) { + result = Curl_dynhds_h1_cadd_line(&req->headers, + data->state.aptr.proxyuserpwd); + if(result) + goto out; + } + + if(!Curl_checkProxyheaders(data, cf->conn, STRCONST("User-Agent")) && + data->set.str[STRING_USERAGENT] && *data->set.str[STRING_USERAGENT]) { + result = Curl_dynhds_cadd(&req->headers, "User-Agent", + data->set.str[STRING_USERAGENT]); + if(result) + goto out; + } + + if(http_version_major == 1 && + !Curl_checkProxyheaders(data, cf->conn, STRCONST("Proxy-Connection"))) { + result = Curl_dynhds_cadd(&req->headers, "Proxy-Connection", "Keep-Alive"); + if(result) + goto out; + } + + result = Curl_dynhds_add_custom(data, TRUE, &req->headers); + +out: + if(result && req) { + Curl_http_req_free(req); + req = NULL; + } + free(authority); + *preq = req; + return result; +} + + +struct cf_proxy_ctx { + /* the protocol specific sub-filter we install during connect */ + struct Curl_cfilter *cf_protocol; +}; + +static CURLcode http_proxy_cf_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + struct cf_proxy_ctx *ctx = cf->ctx; + CURLcode result; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + CURL_TRC_CF(data, cf, "connect"); +connect_sub: + result = cf->next->cft->do_connect(cf->next, data, blocking, done); + if(result || !*done) + return result; + + *done = FALSE; + if(!ctx->cf_protocol) { + struct Curl_cfilter *cf_protocol = NULL; + int alpn = Curl_conn_cf_is_ssl(cf->next)? + cf->conn->proxy_alpn : CURL_HTTP_VERSION_1_1; + + /* First time call after the subchain connected */ + switch(alpn) { + case CURL_HTTP_VERSION_NONE: + case CURL_HTTP_VERSION_1_0: + case CURL_HTTP_VERSION_1_1: + CURL_TRC_CF(data, cf, "installing subfilter for HTTP/1.1"); + infof(data, "CONNECT tunnel: HTTP/1.%d negotiated", + (alpn == CURL_HTTP_VERSION_1_0)? 0 : 1); + result = Curl_cf_h1_proxy_insert_after(cf, data); + if(result) + goto out; + cf_protocol = cf->next; + break; +#ifdef USE_NGHTTP2 + case CURL_HTTP_VERSION_2: + CURL_TRC_CF(data, cf, "installing subfilter for HTTP/2"); + infof(data, "CONNECT tunnel: HTTP/2 negotiated"); + result = Curl_cf_h2_proxy_insert_after(cf, data); + if(result) + goto out; + cf_protocol = cf->next; + break; +#endif + default: + infof(data, "CONNECT tunnel: unsupported ALPN(%d) negotiated", alpn); + result = CURLE_COULDNT_CONNECT; + goto out; + } + + ctx->cf_protocol = cf_protocol; + /* after we installed the filter "below" us, we call connect + * on out sub-chain again. + */ + goto connect_sub; + } + else { + /* subchain connected and we had already installed the protocol filter. + * This means the protocol tunnel is established, we are done. + */ + DEBUGASSERT(ctx->cf_protocol); + result = CURLE_OK; + } + +out: + if(!result) { + cf->connected = TRUE; + *done = TRUE; + } + return result; +} + +void Curl_cf_http_proxy_get_host(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char **phost, + const char **pdisplay_host, + int *pport) +{ + (void)data; + if(!cf->connected) { + *phost = cf->conn->http_proxy.host.name; + *pdisplay_host = cf->conn->http_proxy.host.dispname; + *pport = (int)cf->conn->http_proxy.port; + } + else { + cf->next->cft->get_host(cf->next, data, phost, pdisplay_host, pport); + } +} + +static void http_proxy_cf_destroy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_proxy_ctx *ctx = cf->ctx; + + (void)data; + CURL_TRC_CF(data, cf, "destroy"); + free(ctx); +} + +static void http_proxy_cf_close(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_proxy_ctx *ctx = cf->ctx; + + CURL_TRC_CF(data, cf, "close"); + cf->connected = FALSE; + if(ctx->cf_protocol) { + struct Curl_cfilter *f; + /* if someone already removed it, we assume he also + * took care of destroying it. */ + for(f = cf->next; f; f = f->next) { + if(f == ctx->cf_protocol) { + /* still in our sub-chain */ + Curl_conn_cf_discard_sub(cf, ctx->cf_protocol, data, FALSE); + break; + } + } + ctx->cf_protocol = NULL; + } + if(cf->next) + cf->next->cft->do_close(cf->next, data); +} + + +struct Curl_cftype Curl_cft_http_proxy = { + "HTTP-PROXY", + CF_TYPE_IP_CONNECT|CF_TYPE_PROXY, + 0, + http_proxy_cf_destroy, + http_proxy_cf_connect, + http_proxy_cf_close, + Curl_cf_http_proxy_get_host, + Curl_cf_def_adjust_pollset, + Curl_cf_def_data_pending, + Curl_cf_def_send, + Curl_cf_def_recv, + Curl_cf_def_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + Curl_cf_def_query, +}; + +CURLcode Curl_cf_http_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data) +{ + struct Curl_cfilter *cf; + struct cf_proxy_ctx *ctx = NULL; + CURLcode result; + + (void)data; + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + result = Curl_cf_create(&cf, &Curl_cft_http_proxy, ctx); + if(result) + goto out; + ctx = NULL; + Curl_conn_cf_insert_after(cf_at, cf); + +out: + free(ctx); + return result; +} + +#endif /* ! CURL_DISABLE_HTTP && !CURL_DISABLE_PROXY */ diff --git a/third_party/curl/lib/http_proxy.h b/third_party/curl/lib/http_proxy.h new file mode 100644 index 0000000..2b5f7ae --- /dev/null +++ b/third_party/curl/lib/http_proxy.h @@ -0,0 +1,61 @@ +#ifndef HEADER_CURL_HTTP_PROXY_H +#define HEADER_CURL_HTTP_PROXY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP) + +#include "urldata.h" + +CURLcode Curl_http_proxy_get_destination(struct Curl_cfilter *cf, + const char **phostname, + int *pport, bool *pipv6_ip); + +CURLcode Curl_http_proxy_create_CONNECT(struct httpreq **preq, + struct Curl_cfilter *cf, + struct Curl_easy *data, + int http_version_major); + +/* Default proxy timeout in milliseconds */ +#define PROXY_TIMEOUT (3600*1000) + +void Curl_cf_http_proxy_get_host(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char **phost, + const char **pdisplay_host, + int *pport); + +CURLcode Curl_cf_http_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data); + +extern struct Curl_cftype Curl_cft_http_proxy; + +#endif /* !CURL_DISABLE_PROXY && !CURL_DISABLE_HTTP */ + +#define IS_HTTPS_PROXY(t) (((t) == CURLPROXY_HTTPS) || \ + ((t) == CURLPROXY_HTTPS2)) + +#endif /* HEADER_CURL_HTTP_PROXY_H */ diff --git a/third_party/curl/lib/idn.c b/third_party/curl/lib/idn.c new file mode 100644 index 0000000..c795672 --- /dev/null +++ b/third_party/curl/lib/idn.c @@ -0,0 +1,337 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + + /* + * IDN conversions + */ + +#include "curl_setup.h" +#include "urldata.h" +#include "idn.h" +#include "sendf.h" +#include "curl_multibyte.h" +#include "warnless.h" + +#ifdef USE_LIBIDN2 +#include + +#if defined(_WIN32) && defined(UNICODE) +#define IDN2_LOOKUP(name, host, flags) \ + idn2_lookup_u8((const uint8_t *)name, (uint8_t **)host, flags) +#else +#define IDN2_LOOKUP(name, host, flags) \ + idn2_lookup_ul((const char *)name, (char **)host, flags) +#endif +#endif /* USE_LIBIDN2 */ + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* for macOS and iOS targets */ +#if defined(USE_APPLE_IDN) +#include + +static CURLcode mac_idn_to_ascii(const char *in, char **out) +{ + UErrorCode err = U_ZERO_ERROR; + UIDNA* idna = uidna_openUTS46(UIDNA_CHECK_BIDI, &err); + if(U_FAILURE(err)) { + return CURLE_OUT_OF_MEMORY; + } + else { + UIDNAInfo info = UIDNA_INFO_INITIALIZER; + char buffer[256] = {0}; + (void)uidna_nameToASCII_UTF8(idna, in, -1, buffer, + sizeof(buffer), &info, &err); + uidna_close(idna); + if(U_FAILURE(err)) { + return CURLE_URL_MALFORMAT; + } + else { + *out = strdup(buffer); + if(*out) + return CURLE_OK; + else + return CURLE_OUT_OF_MEMORY; + } + } +} + +static CURLcode mac_ascii_to_idn(const char *in, char **out) +{ + UErrorCode err = U_ZERO_ERROR; + UIDNA* idna = uidna_openUTS46(UIDNA_CHECK_BIDI, &err); + if(U_FAILURE(err)) { + return CURLE_OUT_OF_MEMORY; + } + else { + UIDNAInfo info = UIDNA_INFO_INITIALIZER; + char buffer[256] = {0}; + (void)uidna_nameToUnicodeUTF8(idna, in, -1, buffer, + sizeof(buffer), &info, &err); + uidna_close(idna); + if(U_FAILURE(err)) { + return CURLE_URL_MALFORMAT; + } + else { + *out = strdup(buffer); + if(*out) + return CURLE_OK; + else + return CURLE_OUT_OF_MEMORY; + } + } +} +#endif + +#ifdef USE_WIN32_IDN +/* using Windows kernel32 and normaliz libraries. */ + +#if !defined(_WIN32_WINNT) || _WIN32_WINNT < 0x600 +WINBASEAPI int WINAPI IdnToAscii(DWORD dwFlags, + const WCHAR *lpUnicodeCharStr, + int cchUnicodeChar, + WCHAR *lpASCIICharStr, + int cchASCIIChar); +WINBASEAPI int WINAPI IdnToUnicode(DWORD dwFlags, + const WCHAR *lpASCIICharStr, + int cchASCIIChar, + WCHAR *lpUnicodeCharStr, + int cchUnicodeChar); +#endif + +#define IDN_MAX_LENGTH 255 + +static CURLcode win32_idn_to_ascii(const char *in, char **out) +{ + wchar_t *in_w = curlx_convert_UTF8_to_wchar(in); + *out = NULL; + if(in_w) { + wchar_t punycode[IDN_MAX_LENGTH]; + int chars = IdnToAscii(0, in_w, (int)(wcslen(in_w) + 1), punycode, + IDN_MAX_LENGTH); + curlx_unicodefree(in_w); + if(chars) { + char *mstr = curlx_convert_wchar_to_UTF8(punycode); + if(mstr) { + *out = strdup(mstr); + curlx_unicodefree(mstr); + if(!*out) + return CURLE_OUT_OF_MEMORY; + } + else + return CURLE_OUT_OF_MEMORY; + } + else + return CURLE_URL_MALFORMAT; + } + else + return CURLE_URL_MALFORMAT; + + return CURLE_OK; +} + +static CURLcode win32_ascii_to_idn(const char *in, char **output) +{ + char *out = NULL; + + wchar_t *in_w = curlx_convert_UTF8_to_wchar(in); + if(in_w) { + WCHAR idn[IDN_MAX_LENGTH]; /* stores a UTF-16 string */ + int chars = IdnToUnicode(0, in_w, (int)(wcslen(in_w) + 1), idn, + IDN_MAX_LENGTH); + if(chars) { + /* 'chars' is "the number of characters retrieved" */ + char *mstr = curlx_convert_wchar_to_UTF8(idn); + if(mstr) { + out = strdup(mstr); + curlx_unicodefree(mstr); + if(!out) + return CURLE_OUT_OF_MEMORY; + } + } + else + return CURLE_URL_MALFORMAT; + } + else + return CURLE_URL_MALFORMAT; + *output = out; + return CURLE_OK; +} + +#endif /* USE_WIN32_IDN */ + +/* + * Helpers for IDNA conversions. + */ +bool Curl_is_ASCII_name(const char *hostname) +{ + /* get an UNSIGNED local version of the pointer */ + const unsigned char *ch = (const unsigned char *)hostname; + + if(!hostname) /* bad input, consider it ASCII! */ + return TRUE; + + while(*ch) { + if(*ch++ & 0x80) + return FALSE; + } + return TRUE; +} + +#ifdef USE_IDN +/* + * Curl_idn_decode() returns an allocated IDN decoded string if it was + * possible. NULL on error. + * + * CURLE_URL_MALFORMAT - the host name could not be converted + * CURLE_OUT_OF_MEMORY - memory problem + * + */ +static CURLcode idn_decode(const char *input, char **output) +{ + char *decoded = NULL; + CURLcode result = CURLE_OK; +#ifdef USE_LIBIDN2 + if(idn2_check_version(IDN2_VERSION)) { + int flags = IDN2_NFC_INPUT +#if IDN2_VERSION_NUMBER >= 0x00140000 + /* IDN2_NFC_INPUT: Normalize input string using normalization form C. + IDN2_NONTRANSITIONAL: Perform Unicode TR46 non-transitional + processing. */ + | IDN2_NONTRANSITIONAL +#endif + ; + int rc = IDN2_LOOKUP(input, &decoded, flags); + if(rc != IDN2_OK) + /* fallback to TR46 Transitional mode for better IDNA2003 + compatibility */ + rc = IDN2_LOOKUP(input, &decoded, IDN2_TRANSITIONAL); + if(rc != IDN2_OK) + result = CURLE_URL_MALFORMAT; + } + else + /* a too old libidn2 version */ + result = CURLE_NOT_BUILT_IN; +#elif defined(USE_WIN32_IDN) + result = win32_idn_to_ascii(input, &decoded); +#elif defined(USE_APPLE_IDN) + result = mac_idn_to_ascii(input, &decoded); +#endif + if(!result) + *output = decoded; + return result; +} + +static CURLcode idn_encode(const char *puny, char **output) +{ + char *enc = NULL; +#ifdef USE_LIBIDN2 + int rc = idn2_to_unicode_8z8z(puny, &enc, 0); + if(rc != IDNA_SUCCESS) + return rc == IDNA_MALLOC_ERROR ? CURLE_OUT_OF_MEMORY : CURLE_URL_MALFORMAT; +#elif defined(USE_WIN32_IDN) + CURLcode result = win32_ascii_to_idn(puny, &enc); + if(result) + return result; +#elif defined(USE_APPLE_IDN) + CURLcode result = mac_ascii_to_idn(puny, &enc); + if(result) + return result; +#endif + *output = enc; + return CURLE_OK; +} + +CURLcode Curl_idn_decode(const char *input, char **output) +{ + char *d = NULL; + CURLcode result = idn_decode(input, &d); +#ifdef USE_LIBIDN2 + if(!result) { + char *c = strdup(d); + idn2_free(d); + if(c) + d = c; + else + result = CURLE_OUT_OF_MEMORY; + } +#endif + if(!result) + *output = d; + return result; +} + +CURLcode Curl_idn_encode(const char *puny, char **output) +{ + char *d = NULL; + CURLcode result = idn_encode(puny, &d); +#ifdef USE_LIBIDN2 + if(!result) { + char *c = strdup(d); + idn2_free(d); + if(c) + d = c; + else + result = CURLE_OUT_OF_MEMORY; + } +#endif + if(!result) + *output = d; + return result; +} + +/* + * Frees data allocated by idnconvert_hostname() + */ +void Curl_free_idnconverted_hostname(struct hostname *host) +{ + Curl_safefree(host->encalloc); +} + +#endif /* USE_IDN */ + +/* + * Perform any necessary IDN conversion of hostname + */ +CURLcode Curl_idnconvert_hostname(struct hostname *host) +{ + /* set the name we use to display the host name */ + host->dispname = host->name; + +#ifdef USE_IDN + /* Check name for non-ASCII and convert hostname if we can */ + if(!Curl_is_ASCII_name(host->name)) { + char *decoded; + CURLcode result = Curl_idn_decode(host->name, &decoded); + if(result) + return result; + /* successful */ + host->name = host->encalloc = decoded; + } +#endif + return CURLE_OK; +} diff --git a/third_party/curl/lib/idn.h b/third_party/curl/lib/idn.h new file mode 100644 index 0000000..2bdce89 --- /dev/null +++ b/third_party/curl/lib/idn.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_IDN_H +#define HEADER_CURL_IDN_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +bool Curl_is_ASCII_name(const char *hostname); +CURLcode Curl_idnconvert_hostname(struct hostname *host); +#if defined(USE_LIBIDN2) || defined(USE_WIN32_IDN) || defined(USE_APPLE_IDN) +#define USE_IDN +void Curl_free_idnconverted_hostname(struct hostname *host); +CURLcode Curl_idn_decode(const char *input, char **output); +CURLcode Curl_idn_encode(const char *input, char **output); + +#else +#define Curl_free_idnconverted_hostname(x) +#define Curl_idn_decode(x) NULL +#endif +#endif /* HEADER_CURL_IDN_H */ diff --git a/third_party/curl/lib/if2ip.c b/third_party/curl/lib/if2ip.c new file mode 100644 index 0000000..42e1450 --- /dev/null +++ b/third_party/curl/lib/if2ip.c @@ -0,0 +1,260 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +# include +#endif +#ifdef HAVE_ARPA_INET_H +# include +#endif +#ifdef HAVE_NET_IF_H +# include +#endif +#ifdef HAVE_SYS_IOCTL_H +# include +#endif +#ifdef HAVE_NETDB_H +# include +#endif +#ifdef HAVE_SYS_SOCKIO_H +# include +#endif +#ifdef HAVE_IFADDRS_H +# include +#endif +#ifdef HAVE_STROPTS_H +# include +#endif +#ifdef __VMS +# include +#endif + +#include "inet_ntop.h" +#include "strcase.h" +#include "if2ip.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* ------------------------------------------------------------------ */ + +#ifdef USE_IPV6 +/* Return the scope of the given address. */ +unsigned int Curl_ipv6_scope(const struct sockaddr *sa) +{ + if(sa->sa_family == AF_INET6) { + const struct sockaddr_in6 * sa6 = (const struct sockaddr_in6 *)(void *) sa; + const unsigned char *b = sa6->sin6_addr.s6_addr; + unsigned short w = (unsigned short) ((b[0] << 8) | b[1]); + + if((b[0] & 0xFE) == 0xFC) /* Handle ULAs */ + return IPV6_SCOPE_UNIQUELOCAL; + switch(w & 0xFFC0) { + case 0xFE80: + return IPV6_SCOPE_LINKLOCAL; + case 0xFEC0: + return IPV6_SCOPE_SITELOCAL; + case 0x0000: + w = b[1] | b[2] | b[3] | b[4] | b[5] | b[6] | b[7] | b[8] | b[9] | + b[10] | b[11] | b[12] | b[13] | b[14]; + if(w || b[15] != 0x01) + break; + return IPV6_SCOPE_NODELOCAL; + default: + break; + } + } + return IPV6_SCOPE_GLOBAL; +} +#endif + +#ifndef CURL_DISABLE_BINDLOCAL + +#if defined(HAVE_GETIFADDRS) + +if2ip_result_t Curl_if2ip(int af, +#ifdef USE_IPV6 + unsigned int remote_scope, + unsigned int local_scope_id, +#endif + const char *interf, + char *buf, size_t buf_size) +{ + struct ifaddrs *iface, *head; + if2ip_result_t res = IF2IP_NOT_FOUND; + +#if defined(USE_IPV6) && \ + !defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID) + (void) local_scope_id; +#endif + + if(getifaddrs(&head) >= 0) { + for(iface = head; iface != NULL; iface = iface->ifa_next) { + if(iface->ifa_addr) { + if(iface->ifa_addr->sa_family == af) { + if(strcasecompare(iface->ifa_name, interf)) { + void *addr; + const char *ip; + char scope[12] = ""; + char ipstr[64]; +#ifdef USE_IPV6 + if(af == AF_INET6) { +#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID + unsigned int scopeid = 0; +#endif + unsigned int ifscope = Curl_ipv6_scope(iface->ifa_addr); + + if(ifscope != remote_scope) { + /* We are interested only in interface addresses whose scope + matches the remote address we want to connect to: global + for global, link-local for link-local, etc... */ + if(res == IF2IP_NOT_FOUND) + res = IF2IP_AF_NOT_SUPPORTED; + continue; + } + + addr = + &((struct sockaddr_in6 *)(void *)iface->ifa_addr)->sin6_addr; +#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID + /* Include the scope of this interface as part of the address */ + scopeid = ((struct sockaddr_in6 *)(void *)iface->ifa_addr) + ->sin6_scope_id; + + /* If given, scope id should match. */ + if(local_scope_id && scopeid != local_scope_id) { + if(res == IF2IP_NOT_FOUND) + res = IF2IP_AF_NOT_SUPPORTED; + + continue; + } + + if(scopeid) + msnprintf(scope, sizeof(scope), "%%%u", scopeid); +#endif + } + else +#endif + addr = + &((struct sockaddr_in *)(void *)iface->ifa_addr)->sin_addr; + res = IF2IP_FOUND; + ip = Curl_inet_ntop(af, addr, ipstr, sizeof(ipstr)); + msnprintf(buf, buf_size, "%s%s", ip, scope); + break; + } + } + else if((res == IF2IP_NOT_FOUND) && + strcasecompare(iface->ifa_name, interf)) { + res = IF2IP_AF_NOT_SUPPORTED; + } + } + } + + freeifaddrs(head); + } + + return res; +} + +#elif defined(HAVE_IOCTL_SIOCGIFADDR) + +if2ip_result_t Curl_if2ip(int af, +#ifdef USE_IPV6 + unsigned int remote_scope, + unsigned int local_scope_id, +#endif + const char *interf, + char *buf, size_t buf_size) +{ + struct ifreq req; + struct in_addr in; + struct sockaddr_in *s; + curl_socket_t dummy; + size_t len; + const char *r; + +#ifdef USE_IPV6 + (void)remote_scope; + (void)local_scope_id; +#endif + + if(!interf || (af != AF_INET)) + return IF2IP_NOT_FOUND; + + len = strlen(interf); + if(len >= sizeof(req.ifr_name)) + return IF2IP_NOT_FOUND; + + dummy = socket(AF_INET, SOCK_STREAM, 0); + if(CURL_SOCKET_BAD == dummy) + return IF2IP_NOT_FOUND; + + memset(&req, 0, sizeof(req)); + memcpy(req.ifr_name, interf, len + 1); + req.ifr_addr.sa_family = AF_INET; + + if(ioctl(dummy, SIOCGIFADDR, &req) < 0) { + sclose(dummy); + /* With SIOCGIFADDR, we cannot tell the difference between an interface + that does not exist and an interface that has no address of the + correct family. Assume the interface does not exist */ + return IF2IP_NOT_FOUND; + } + + s = (struct sockaddr_in *)(void *)&req.ifr_addr; + memcpy(&in, &s->sin_addr, sizeof(in)); + r = Curl_inet_ntop(s->sin_family, &in, buf, buf_size); + + sclose(dummy); + if(!r) + return IF2IP_NOT_FOUND; + return IF2IP_FOUND; +} + +#else + +if2ip_result_t Curl_if2ip(int af, +#ifdef USE_IPV6 + unsigned int remote_scope, + unsigned int local_scope_id, +#endif + const char *interf, + char *buf, size_t buf_size) +{ + (void) af; +#ifdef USE_IPV6 + (void) remote_scope; + (void) local_scope_id; +#endif + (void) interf; + (void) buf; + (void) buf_size; + return IF2IP_NOT_FOUND; +} + +#endif + +#endif /* CURL_DISABLE_BINDLOCAL */ diff --git a/third_party/curl/lib/if2ip.h b/third_party/curl/lib/if2ip.h new file mode 100644 index 0000000..f4b2f4c --- /dev/null +++ b/third_party/curl/lib/if2ip.h @@ -0,0 +1,92 @@ +#ifndef HEADER_CURL_IF2IP_H +#define HEADER_CURL_IF2IP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* IPv6 address scopes. */ +#define IPV6_SCOPE_GLOBAL 0 /* Global scope. */ +#define IPV6_SCOPE_LINKLOCAL 1 /* Link-local scope. */ +#define IPV6_SCOPE_SITELOCAL 2 /* Site-local scope (deprecated). */ +#define IPV6_SCOPE_UNIQUELOCAL 3 /* Unique local */ +#define IPV6_SCOPE_NODELOCAL 4 /* Loopback. */ + +#ifdef USE_IPV6 +unsigned int Curl_ipv6_scope(const struct sockaddr *sa); +#else +#define Curl_ipv6_scope(x) 0 +#endif + +typedef enum { + IF2IP_NOT_FOUND = 0, /* Interface not found */ + IF2IP_AF_NOT_SUPPORTED = 1, /* Int. exists but has no address for this af */ + IF2IP_FOUND = 2 /* The address has been stored in "buf" */ +} if2ip_result_t; + +if2ip_result_t Curl_if2ip(int af, +#ifdef USE_IPV6 + unsigned int remote_scope, + unsigned int local_scope_id, +#endif + const char *interf, + char *buf, size_t buf_size); + +#ifdef __INTERIX + +/* Nedelcho Stanev's work-around for SFU 3.0 */ +struct ifreq { +#define IFNAMSIZ 16 +#define IFHWADDRLEN 6 + union { + char ifrn_name[IFNAMSIZ]; /* if name, e.g. "en0" */ + } ifr_ifrn; + + union { + struct sockaddr ifru_addr; + struct sockaddr ifru_broadaddr; + struct sockaddr ifru_netmask; + struct sockaddr ifru_hwaddr; + short ifru_flags; + int ifru_metric; + int ifru_mtu; + } ifr_ifru; +}; + +/* This define was added by Daniel to avoid an extra #ifdef INTERIX in the + C code. */ + +#define ifr_name ifr_ifrn.ifrn_name /* interface name */ +#define ifr_addr ifr_ifru.ifru_addr /* address */ +#define ifr_broadaddr ifr_ifru.ifru_broadaddr /* broadcast address */ +#define ifr_netmask ifr_ifru.ifru_netmask /* interface net mask */ +#define ifr_flags ifr_ifru.ifru_flags /* flags */ +#define ifr_hwaddr ifr_ifru.ifru_hwaddr /* MAC address */ +#define ifr_metric ifr_ifru.ifru_metric /* metric */ +#define ifr_mtu ifr_ifru.ifru_mtu /* mtu */ + +#define SIOCGIFADDR _IOW('s', 102, struct ifreq) /* Get if addr */ + +#endif /* __INTERIX */ + +#endif /* HEADER_CURL_IF2IP_H */ diff --git a/third_party/curl/lib/imap.c b/third_party/curl/lib/imap.c new file mode 100644 index 0000000..f6e98bd --- /dev/null +++ b/third_party/curl/lib/imap.c @@ -0,0 +1,2117 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * RFC2195 CRAM-MD5 authentication + * RFC2595 Using TLS with IMAP, POP3 and ACAP + * RFC2831 DIGEST-MD5 authentication + * RFC3501 IMAPv4 protocol + * RFC4422 Simple Authentication and Security Layer (SASL) + * RFC4616 PLAIN authentication + * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism + * RFC4959 IMAP Extension for SASL Initial Client Response + * RFC5092 IMAP URL Scheme + * RFC6749 OAuth 2.0 Authorization Framework + * RFC8314 Use of TLS for Email Submission and Access + * Draft LOGIN SASL Mechanism + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_IMAP + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef __VMS +#include +#include +#endif + +#include +#include "urldata.h" +#include "sendf.h" +#include "hostip.h" +#include "progress.h" +#include "transfer.h" +#include "escape.h" +#include "http.h" /* for HTTP proxy tunnel stuff */ +#include "socks.h" +#include "imap.h" +#include "mime.h" +#include "strtoofft.h" +#include "strcase.h" +#include "vtls/vtls.h" +#include "cfilters.h" +#include "connect.h" +#include "select.h" +#include "multiif.h" +#include "url.h" +#include "bufref.h" +#include "curl_sasl.h" +#include "warnless.h" +#include "curl_ctype.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* Local API functions */ +static CURLcode imap_regular_transfer(struct Curl_easy *data, bool *done); +static CURLcode imap_do(struct Curl_easy *data, bool *done); +static CURLcode imap_done(struct Curl_easy *data, CURLcode status, + bool premature); +static CURLcode imap_connect(struct Curl_easy *data, bool *done); +static CURLcode imap_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead); +static CURLcode imap_multi_statemach(struct Curl_easy *data, bool *done); +static int imap_getsock(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t *socks); +static CURLcode imap_doing(struct Curl_easy *data, bool *dophase_done); +static CURLcode imap_setup_connection(struct Curl_easy *data, + struct connectdata *conn); +static char *imap_atom(const char *str, bool escape_only); +static CURLcode imap_sendf(struct Curl_easy *data, const char *fmt, ...) + CURL_PRINTF(2, 3); +static CURLcode imap_parse_url_options(struct connectdata *conn); +static CURLcode imap_parse_url_path(struct Curl_easy *data); +static CURLcode imap_parse_custom_request(struct Curl_easy *data); +static CURLcode imap_perform_authenticate(struct Curl_easy *data, + const char *mech, + const struct bufref *initresp); +static CURLcode imap_continue_authenticate(struct Curl_easy *data, + const char *mech, + const struct bufref *resp); +static CURLcode imap_cancel_authenticate(struct Curl_easy *data, + const char *mech); +static CURLcode imap_get_message(struct Curl_easy *data, struct bufref *out); + +/* + * IMAP protocol handler. + */ + +const struct Curl_handler Curl_handler_imap = { + "imap", /* scheme */ + imap_setup_connection, /* setup_connection */ + imap_do, /* do_it */ + imap_done, /* done */ + ZERO_NULL, /* do_more */ + imap_connect, /* connect_it */ + imap_multi_statemach, /* connecting */ + imap_doing, /* doing */ + imap_getsock, /* proto_getsock */ + imap_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + imap_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_IMAP, /* defport */ + CURLPROTO_IMAP, /* protocol */ + CURLPROTO_IMAP, /* family */ + PROTOPT_CLOSEACTION| /* flags */ + PROTOPT_URLOPTIONS +}; + +#ifdef USE_SSL +/* + * IMAPS protocol handler. + */ + +const struct Curl_handler Curl_handler_imaps = { + "imaps", /* scheme */ + imap_setup_connection, /* setup_connection */ + imap_do, /* do_it */ + imap_done, /* done */ + ZERO_NULL, /* do_more */ + imap_connect, /* connect_it */ + imap_multi_statemach, /* connecting */ + imap_doing, /* doing */ + imap_getsock, /* proto_getsock */ + imap_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + imap_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_IMAPS, /* defport */ + CURLPROTO_IMAPS, /* protocol */ + CURLPROTO_IMAP, /* family */ + PROTOPT_CLOSEACTION | PROTOPT_SSL | /* flags */ + PROTOPT_URLOPTIONS +}; +#endif + +#define IMAP_RESP_OK 1 +#define IMAP_RESP_NOT_OK 2 +#define IMAP_RESP_PREAUTH 3 + +/* SASL parameters for the imap protocol */ +static const struct SASLproto saslimap = { + "imap", /* The service name */ + imap_perform_authenticate, /* Send authentication command */ + imap_continue_authenticate, /* Send authentication continuation */ + imap_cancel_authenticate, /* Send authentication cancellation */ + imap_get_message, /* Get SASL response message */ + 0, /* No maximum initial response length */ + '+', /* Code received when continuation is expected */ + IMAP_RESP_OK, /* Code to receive upon authentication success */ + SASL_AUTH_DEFAULT, /* Default mechanisms */ + SASL_FLAG_BASE64 /* Configuration flags */ +}; + + +#ifdef USE_SSL +static void imap_to_imaps(struct connectdata *conn) +{ + /* Change the connection handler */ + conn->handler = &Curl_handler_imaps; + + /* Set the connection's upgraded to TLS flag */ + conn->bits.tls_upgraded = TRUE; +} +#else +#define imap_to_imaps(x) Curl_nop_stmt +#endif + +/*********************************************************************** + * + * imap_matchresp() + * + * Determines whether the untagged response is related to the specified + * command by checking if it is in format "* ..." or + * "* ...". + * + * The "* " marker is assumed to have already been checked by the caller. + */ +static bool imap_matchresp(const char *line, size_t len, const char *cmd) +{ + const char *end = line + len; + size_t cmd_len = strlen(cmd); + + /* Skip the untagged response marker */ + line += 2; + + /* Do we have a number after the marker? */ + if(line < end && ISDIGIT(*line)) { + /* Skip the number */ + do + line++; + while(line < end && ISDIGIT(*line)); + + /* Do we have the space character? */ + if(line == end || *line != ' ') + return FALSE; + + line++; + } + + /* Does the command name match and is it followed by a space character or at + the end of line? */ + if(line + cmd_len <= end && strncasecompare(line, cmd, cmd_len) && + (line[cmd_len] == ' ' || line + cmd_len + 2 == end)) + return TRUE; + + return FALSE; +} + +/*********************************************************************** + * + * imap_endofresp() + * + * Checks whether the given string is a valid tagged, untagged or continuation + * response which can be processed by the response handler. + */ +static bool imap_endofresp(struct Curl_easy *data, struct connectdata *conn, + char *line, size_t len, int *resp) +{ + struct IMAP *imap = data->req.p.imap; + struct imap_conn *imapc = &conn->proto.imapc; + const char *id = imapc->resptag; + size_t id_len = strlen(id); + + /* Do we have a tagged command response? */ + if(len >= id_len + 1 && !memcmp(id, line, id_len) && line[id_len] == ' ') { + line += id_len + 1; + len -= id_len + 1; + + if(len >= 2 && !memcmp(line, "OK", 2)) + *resp = IMAP_RESP_OK; + else if(len >= 7 && !memcmp(line, "PREAUTH", 7)) + *resp = IMAP_RESP_PREAUTH; + else + *resp = IMAP_RESP_NOT_OK; + + return TRUE; + } + + /* Do we have an untagged command response? */ + if(len >= 2 && !memcmp("* ", line, 2)) { + switch(imapc->state) { + /* States which are interested in untagged responses */ + case IMAP_CAPABILITY: + if(!imap_matchresp(line, len, "CAPABILITY")) + return FALSE; + break; + + case IMAP_LIST: + if((!imap->custom && !imap_matchresp(line, len, "LIST")) || + (imap->custom && !imap_matchresp(line, len, imap->custom) && + (!strcasecompare(imap->custom, "STORE") || + !imap_matchresp(line, len, "FETCH")) && + !strcasecompare(imap->custom, "SELECT") && + !strcasecompare(imap->custom, "EXAMINE") && + !strcasecompare(imap->custom, "SEARCH") && + !strcasecompare(imap->custom, "EXPUNGE") && + !strcasecompare(imap->custom, "LSUB") && + !strcasecompare(imap->custom, "UID") && + !strcasecompare(imap->custom, "GETQUOTAROOT") && + !strcasecompare(imap->custom, "NOOP"))) + return FALSE; + break; + + case IMAP_SELECT: + /* SELECT is special in that its untagged responses do not have a + common prefix so accept anything! */ + break; + + case IMAP_FETCH: + if(!imap_matchresp(line, len, "FETCH")) + return FALSE; + break; + + case IMAP_SEARCH: + if(!imap_matchresp(line, len, "SEARCH")) + return FALSE; + break; + + /* Ignore other untagged responses */ + default: + return FALSE; + } + + *resp = '*'; + return TRUE; + } + + /* Do we have a continuation response? This should be a + symbol followed by + a space and optionally some text as per RFC-3501 for the AUTHENTICATE and + APPEND commands and as outlined in Section 4. Examples of RFC-4959 but + some email servers ignore this and only send a single + instead. */ + if(imap && !imap->custom && ((len == 3 && line[0] == '+') || + (len >= 2 && !memcmp("+ ", line, 2)))) { + switch(imapc->state) { + /* States which are interested in continuation responses */ + case IMAP_AUTHENTICATE: + case IMAP_APPEND: + *resp = '+'; + break; + + default: + failf(data, "Unexpected continuation response"); + *resp = -1; + break; + } + + return TRUE; + } + + return FALSE; /* Nothing for us */ +} + +/*********************************************************************** + * + * imap_get_message() + * + * Gets the authentication message from the response buffer. + */ +static CURLcode imap_get_message(struct Curl_easy *data, struct bufref *out) +{ + char *message = Curl_dyn_ptr(&data->conn->proto.imapc.pp.recvbuf); + size_t len = data->conn->proto.imapc.pp.nfinal; + + if(len > 2) { + /* Find the start of the message */ + len -= 2; + for(message += 2; *message == ' ' || *message == '\t'; message++, len--) + ; + + /* Find the end of the message */ + while(len--) + if(message[len] != '\r' && message[len] != '\n' && message[len] != ' ' && + message[len] != '\t') + break; + + /* Terminate the message */ + message[++len] = '\0'; + Curl_bufref_set(out, message, len, NULL); + } + else + /* junk input => zero length output */ + Curl_bufref_set(out, "", 0, NULL); + + return CURLE_OK; +} + +/*********************************************************************** + * + * imap_state() + * + * This is the ONLY way to change IMAP state! + */ +static void imap_state(struct Curl_easy *data, imapstate newstate) +{ + struct imap_conn *imapc = &data->conn->proto.imapc; +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + /* for debug purposes */ + static const char * const names[]={ + "STOP", + "SERVERGREET", + "CAPABILITY", + "STARTTLS", + "UPGRADETLS", + "AUTHENTICATE", + "LOGIN", + "LIST", + "SELECT", + "FETCH", + "FETCH_FINAL", + "APPEND", + "APPEND_FINAL", + "SEARCH", + "LOGOUT", + /* LAST */ + }; + + if(imapc->state != newstate) + infof(data, "IMAP %p state change from %s to %s", + (void *)imapc, names[imapc->state], names[newstate]); +#endif + + imapc->state = newstate; +} + +/*********************************************************************** + * + * imap_perform_capability() + * + * Sends the CAPABILITY command in order to obtain a list of server side + * supported capabilities. + */ +static CURLcode imap_perform_capability(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + struct imap_conn *imapc = &conn->proto.imapc; + imapc->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanisms yet */ + imapc->sasl.authused = SASL_AUTH_NONE; /* Clear the auth. mechanism used */ + imapc->tls_supported = FALSE; /* Clear the TLS capability */ + + /* Send the CAPABILITY command */ + result = imap_sendf(data, "CAPABILITY"); + + if(!result) + imap_state(data, IMAP_CAPABILITY); + + return result; +} + +/*********************************************************************** + * + * imap_perform_starttls() + * + * Sends the STARTTLS command to start the upgrade to TLS. + */ +static CURLcode imap_perform_starttls(struct Curl_easy *data) +{ + /* Send the STARTTLS command */ + CURLcode result = imap_sendf(data, "STARTTLS"); + + if(!result) + imap_state(data, IMAP_STARTTLS); + + return result; +} + +/*********************************************************************** + * + * imap_perform_upgrade_tls() + * + * Performs the upgrade to TLS. + */ +static CURLcode imap_perform_upgrade_tls(struct Curl_easy *data, + struct connectdata *conn) +{ + /* Start the SSL connection */ + struct imap_conn *imapc = &conn->proto.imapc; + CURLcode result; + bool ssldone = FALSE; + + if(!Curl_conn_is_ssl(conn, FIRSTSOCKET)) { + result = Curl_ssl_cfilter_add(data, conn, FIRSTSOCKET); + if(result) + goto out; + } + + result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &ssldone); + if(!result) { + imapc->ssldone = ssldone; + if(imapc->state != IMAP_UPGRADETLS) + imap_state(data, IMAP_UPGRADETLS); + + if(imapc->ssldone) { + imap_to_imaps(conn); + result = imap_perform_capability(data, conn); + } + } +out: + return result; +} + +/*********************************************************************** + * + * imap_perform_login() + * + * Sends a clear text LOGIN command to authenticate with. + */ +static CURLcode imap_perform_login(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + char *user; + char *passwd; + + /* Check we have a username and password to authenticate with and end the + connect phase if we don't */ + if(!data->state.aptr.user) { + imap_state(data, IMAP_STOP); + + return result; + } + + /* Make sure the username and password are in the correct atom format */ + user = imap_atom(conn->user, false); + passwd = imap_atom(conn->passwd, false); + + /* Send the LOGIN command */ + result = imap_sendf(data, "LOGIN %s %s", user ? user : "", + passwd ? passwd : ""); + + free(user); + free(passwd); + + if(!result) + imap_state(data, IMAP_LOGIN); + + return result; +} + +/*********************************************************************** + * + * imap_perform_authenticate() + * + * Sends an AUTHENTICATE command allowing the client to login with the given + * SASL authentication mechanism. + */ +static CURLcode imap_perform_authenticate(struct Curl_easy *data, + const char *mech, + const struct bufref *initresp) +{ + CURLcode result = CURLE_OK; + const char *ir = (const char *) Curl_bufref_ptr(initresp); + + if(ir) { + /* Send the AUTHENTICATE command with the initial response */ + result = imap_sendf(data, "AUTHENTICATE %s %s", mech, ir); + } + else { + /* Send the AUTHENTICATE command */ + result = imap_sendf(data, "AUTHENTICATE %s", mech); + } + + return result; +} + +/*********************************************************************** + * + * imap_continue_authenticate() + * + * Sends SASL continuation data. + */ +static CURLcode imap_continue_authenticate(struct Curl_easy *data, + const char *mech, + const struct bufref *resp) +{ + struct imap_conn *imapc = &data->conn->proto.imapc; + + (void)mech; + + return Curl_pp_sendf(data, &imapc->pp, + "%s", (const char *) Curl_bufref_ptr(resp)); +} + +/*********************************************************************** + * + * imap_cancel_authenticate() + * + * Sends SASL cancellation. + */ +static CURLcode imap_cancel_authenticate(struct Curl_easy *data, + const char *mech) +{ + struct imap_conn *imapc = &data->conn->proto.imapc; + + (void)mech; + + return Curl_pp_sendf(data, &imapc->pp, "*"); +} + +/*********************************************************************** + * + * imap_perform_authentication() + * + * Initiates the authentication sequence, with the appropriate SASL + * authentication mechanism, falling back to clear text should a common + * mechanism not be available between the client and server. + */ +static CURLcode imap_perform_authentication(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + struct imap_conn *imapc = &conn->proto.imapc; + saslprogress progress; + + /* Check if already authenticated OR if there is enough data to authenticate + with and end the connect phase if we don't */ + if(imapc->preauth || + !Curl_sasl_can_authenticate(&imapc->sasl, data)) { + imap_state(data, IMAP_STOP); + return result; + } + + /* Calculate the SASL login details */ + result = Curl_sasl_start(&imapc->sasl, data, imapc->ir_supported, &progress); + + if(!result) { + if(progress == SASL_INPROGRESS) + imap_state(data, IMAP_AUTHENTICATE); + else if(!imapc->login_disabled && (imapc->preftype & IMAP_TYPE_CLEARTEXT)) + /* Perform clear text authentication */ + result = imap_perform_login(data, conn); + else { + /* Other mechanisms not supported */ + infof(data, "No known authentication mechanisms supported"); + result = CURLE_LOGIN_DENIED; + } + } + + return result; +} + +/*********************************************************************** + * + * imap_perform_list() + * + * Sends a LIST command or an alternative custom request. + */ +static CURLcode imap_perform_list(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct IMAP *imap = data->req.p.imap; + + if(imap->custom) + /* Send the custom request */ + result = imap_sendf(data, "%s%s", imap->custom, + imap->custom_params ? imap->custom_params : ""); + else { + /* Make sure the mailbox is in the correct atom format if necessary */ + char *mailbox = imap->mailbox ? imap_atom(imap->mailbox, true) + : strdup(""); + if(!mailbox) + return CURLE_OUT_OF_MEMORY; + + /* Send the LIST command */ + result = imap_sendf(data, "LIST \"%s\" *", mailbox); + + free(mailbox); + } + + if(!result) + imap_state(data, IMAP_LIST); + + return result; +} + +/*********************************************************************** + * + * imap_perform_select() + * + * Sends a SELECT command to ask the server to change the selected mailbox. + */ +static CURLcode imap_perform_select(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct IMAP *imap = data->req.p.imap; + struct imap_conn *imapc = &conn->proto.imapc; + char *mailbox; + + /* Invalidate old information as we are switching mailboxes */ + Curl_safefree(imapc->mailbox); + Curl_safefree(imapc->mailbox_uidvalidity); + + /* Check we have a mailbox */ + if(!imap->mailbox) { + failf(data, "Cannot SELECT without a mailbox."); + return CURLE_URL_MALFORMAT; + } + + /* Make sure the mailbox is in the correct atom format */ + mailbox = imap_atom(imap->mailbox, false); + if(!mailbox) + return CURLE_OUT_OF_MEMORY; + + /* Send the SELECT command */ + result = imap_sendf(data, "SELECT %s", mailbox); + + free(mailbox); + + if(!result) + imap_state(data, IMAP_SELECT); + + return result; +} + +/*********************************************************************** + * + * imap_perform_fetch() + * + * Sends a FETCH command to initiate the download of a message. + */ +static CURLcode imap_perform_fetch(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct IMAP *imap = data->req.p.imap; + /* Check we have a UID */ + if(imap->uid) { + + /* Send the FETCH command */ + if(imap->partial) + result = imap_sendf(data, "UID FETCH %s BODY[%s]<%s>", + imap->uid, imap->section ? imap->section : "", + imap->partial); + else + result = imap_sendf(data, "UID FETCH %s BODY[%s]", + imap->uid, imap->section ? imap->section : ""); + } + else if(imap->mindex) { + /* Send the FETCH command */ + if(imap->partial) + result = imap_sendf(data, "FETCH %s BODY[%s]<%s>", + imap->mindex, imap->section ? imap->section : "", + imap->partial); + else + result = imap_sendf(data, "FETCH %s BODY[%s]", + imap->mindex, imap->section ? imap->section : ""); + } + else { + failf(data, "Cannot FETCH without a UID."); + return CURLE_URL_MALFORMAT; + } + if(!result) + imap_state(data, IMAP_FETCH); + + return result; +} + +/*********************************************************************** + * + * imap_perform_append() + * + * Sends an APPEND command to initiate the upload of a message. + */ +static CURLcode imap_perform_append(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct IMAP *imap = data->req.p.imap; + char *mailbox; + + /* Check we have a mailbox */ + if(!imap->mailbox) { + failf(data, "Cannot APPEND without a mailbox."); + return CURLE_URL_MALFORMAT; + } + +#ifndef CURL_DISABLE_MIME + /* Prepare the mime data if some. */ + if(data->set.mimepost.kind != MIMEKIND_NONE) { + /* Use the whole structure as data. */ + data->set.mimepost.flags &= ~MIME_BODY_ONLY; + + /* Add external headers and mime version. */ + curl_mime_headers(&data->set.mimepost, data->set.headers, 0); + result = Curl_mime_prepare_headers(data, &data->set.mimepost, NULL, + NULL, MIMESTRATEGY_MAIL); + + if(!result) + if(!Curl_checkheaders(data, STRCONST("Mime-Version"))) + result = Curl_mime_add_header(&data->set.mimepost.curlheaders, + "Mime-Version: 1.0"); + + if(!result) + result = Curl_creader_set_mime(data, &data->set.mimepost); + if(result) + return result; + data->state.infilesize = Curl_creader_client_length(data); + } + else +#endif + { + result = Curl_creader_set_fread(data, data->state.infilesize); + if(result) + return result; + } + + /* Check we know the size of the upload */ + if(data->state.infilesize < 0) { + failf(data, "Cannot APPEND with unknown input file size"); + return CURLE_UPLOAD_FAILED; + } + + /* Make sure the mailbox is in the correct atom format */ + mailbox = imap_atom(imap->mailbox, false); + if(!mailbox) + return CURLE_OUT_OF_MEMORY; + + /* Send the APPEND command */ + result = imap_sendf(data, + "APPEND %s (\\Seen) {%" CURL_FORMAT_CURL_OFF_T "}", + mailbox, data->state.infilesize); + + free(mailbox); + + if(!result) + imap_state(data, IMAP_APPEND); + + return result; +} + +/*********************************************************************** + * + * imap_perform_search() + * + * Sends a SEARCH command. + */ +static CURLcode imap_perform_search(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct IMAP *imap = data->req.p.imap; + + /* Check we have a query string */ + if(!imap->query) { + failf(data, "Cannot SEARCH without a query string."); + return CURLE_URL_MALFORMAT; + } + + /* Send the SEARCH command */ + result = imap_sendf(data, "SEARCH %s", imap->query); + + if(!result) + imap_state(data, IMAP_SEARCH); + + return result; +} + +/*********************************************************************** + * + * imap_perform_logout() + * + * Performs the logout action prior to sclose() being called. + */ +static CURLcode imap_perform_logout(struct Curl_easy *data) +{ + /* Send the LOGOUT command */ + CURLcode result = imap_sendf(data, "LOGOUT"); + + if(!result) + imap_state(data, IMAP_LOGOUT); + + return result; +} + +/* For the initial server greeting */ +static CURLcode imap_state_servergreet_resp(struct Curl_easy *data, + int imapcode, + imapstate instate) +{ + struct connectdata *conn = data->conn; + (void)instate; /* no use for this yet */ + + if(imapcode == IMAP_RESP_PREAUTH) { + /* PREAUTH */ + struct imap_conn *imapc = &conn->proto.imapc; + imapc->preauth = TRUE; + infof(data, "PREAUTH connection, already authenticated"); + } + else if(imapcode != IMAP_RESP_OK) { + failf(data, "Got unexpected imap-server response"); + return CURLE_WEIRD_SERVER_REPLY; + } + + return imap_perform_capability(data, conn); +} + +/* For CAPABILITY responses */ +static CURLcode imap_state_capability_resp(struct Curl_easy *data, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct imap_conn *imapc = &conn->proto.imapc; + const char *line = Curl_dyn_ptr(&imapc->pp.recvbuf); + + (void)instate; /* no use for this yet */ + + /* Do we have a untagged response? */ + if(imapcode == '*') { + line += 2; + + /* Loop through the data line */ + for(;;) { + size_t wordlen; + while(*line && + (*line == ' ' || *line == '\t' || + *line == '\r' || *line == '\n')) { + + line++; + } + + if(!*line) + break; + + /* Extract the word */ + for(wordlen = 0; line[wordlen] && line[wordlen] != ' ' && + line[wordlen] != '\t' && line[wordlen] != '\r' && + line[wordlen] != '\n';) + wordlen++; + + /* Does the server support the STARTTLS capability? */ + if(wordlen == 8 && !memcmp(line, "STARTTLS", 8)) + imapc->tls_supported = TRUE; + + /* Has the server explicitly disabled clear text authentication? */ + else if(wordlen == 13 && !memcmp(line, "LOGINDISABLED", 13)) + imapc->login_disabled = TRUE; + + /* Does the server support the SASL-IR capability? */ + else if(wordlen == 7 && !memcmp(line, "SASL-IR", 7)) + imapc->ir_supported = TRUE; + + /* Do we have a SASL based authentication mechanism? */ + else if(wordlen > 5 && !memcmp(line, "AUTH=", 5)) { + size_t llen; + unsigned short mechbit; + + line += 5; + wordlen -= 5; + + /* Test the word for a matching authentication mechanism */ + mechbit = Curl_sasl_decode_mech(line, wordlen, &llen); + if(mechbit && llen == wordlen) + imapc->sasl.authmechs |= mechbit; + } + + line += wordlen; + } + } + else if(data->set.use_ssl && !Curl_conn_is_ssl(conn, FIRSTSOCKET)) { + /* PREAUTH is not compatible with STARTTLS. */ + if(imapcode == IMAP_RESP_OK && imapc->tls_supported && !imapc->preauth) { + /* Switch to TLS connection now */ + result = imap_perform_starttls(data); + } + else if(data->set.use_ssl <= CURLUSESSL_TRY) + result = imap_perform_authentication(data, conn); + else { + failf(data, "STARTTLS not available."); + result = CURLE_USE_SSL_FAILED; + } + } + else + result = imap_perform_authentication(data, conn); + + return result; +} + +/* For STARTTLS responses */ +static CURLcode imap_state_starttls_resp(struct Curl_easy *data, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + (void)instate; /* no use for this yet */ + + /* Pipelining in response is forbidden. */ + if(data->conn->proto.imapc.pp.overflow) + return CURLE_WEIRD_SERVER_REPLY; + + if(imapcode != IMAP_RESP_OK) { + if(data->set.use_ssl != CURLUSESSL_TRY) { + failf(data, "STARTTLS denied"); + result = CURLE_USE_SSL_FAILED; + } + else + result = imap_perform_authentication(data, conn); + } + else + result = imap_perform_upgrade_tls(data, conn); + + return result; +} + +/* For SASL authentication responses */ +static CURLcode imap_state_auth_resp(struct Curl_easy *data, + struct connectdata *conn, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + struct imap_conn *imapc = &conn->proto.imapc; + saslprogress progress; + + (void)instate; /* no use for this yet */ + + result = Curl_sasl_continue(&imapc->sasl, data, imapcode, &progress); + if(!result) + switch(progress) { + case SASL_DONE: + imap_state(data, IMAP_STOP); /* Authenticated */ + break; + case SASL_IDLE: /* No mechanism left after cancellation */ + if((!imapc->login_disabled) && (imapc->preftype & IMAP_TYPE_CLEARTEXT)) + /* Perform clear text authentication */ + result = imap_perform_login(data, conn); + else { + failf(data, "Authentication cancelled"); + result = CURLE_LOGIN_DENIED; + } + break; + default: + break; + } + + return result; +} + +/* For LOGIN responses */ +static CURLcode imap_state_login_resp(struct Curl_easy *data, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + (void)instate; /* no use for this yet */ + + if(imapcode != IMAP_RESP_OK) { + failf(data, "Access denied. %c", imapcode); + result = CURLE_LOGIN_DENIED; + } + else + /* End of connect phase */ + imap_state(data, IMAP_STOP); + + return result; +} + +/* For LIST and SEARCH responses */ +static CURLcode imap_state_listsearch_resp(struct Curl_easy *data, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + char *line = Curl_dyn_ptr(&data->conn->proto.imapc.pp.recvbuf); + size_t len = data->conn->proto.imapc.pp.nfinal; + + (void)instate; /* No use for this yet */ + + if(imapcode == '*') + result = Curl_client_write(data, CLIENTWRITE_BODY, line, len); + else if(imapcode != IMAP_RESP_OK) + result = CURLE_QUOTE_ERROR; + else + /* End of DO phase */ + imap_state(data, IMAP_STOP); + + return result; +} + +/* For SELECT responses */ +static CURLcode imap_state_select_resp(struct Curl_easy *data, int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct IMAP *imap = data->req.p.imap; + struct imap_conn *imapc = &conn->proto.imapc; + const char *line = Curl_dyn_ptr(&data->conn->proto.imapc.pp.recvbuf); + + (void)instate; /* no use for this yet */ + + if(imapcode == '*') { + /* See if this is an UIDVALIDITY response */ + if(checkprefix("OK [UIDVALIDITY ", line + 2)) { + size_t len = 0; + const char *p = &line[2] + strlen("OK [UIDVALIDITY "); + while((len < 20) && p[len] && ISDIGIT(p[len])) + len++; + if(len && (p[len] == ']')) { + struct dynbuf uid; + Curl_dyn_init(&uid, 20); + if(Curl_dyn_addn(&uid, p, len)) + return CURLE_OUT_OF_MEMORY; + Curl_safefree(imapc->mailbox_uidvalidity); + imapc->mailbox_uidvalidity = Curl_dyn_ptr(&uid); + } + } + } + else if(imapcode == IMAP_RESP_OK) { + /* Check if the UIDVALIDITY has been specified and matches */ + if(imap->uidvalidity && imapc->mailbox_uidvalidity && + !strcasecompare(imap->uidvalidity, imapc->mailbox_uidvalidity)) { + failf(data, "Mailbox UIDVALIDITY has changed"); + result = CURLE_REMOTE_FILE_NOT_FOUND; + } + else { + /* Note the currently opened mailbox on this connection */ + DEBUGASSERT(!imapc->mailbox); + imapc->mailbox = strdup(imap->mailbox); + if(!imapc->mailbox) + return CURLE_OUT_OF_MEMORY; + + if(imap->custom) + result = imap_perform_list(data); + else if(imap->query) + result = imap_perform_search(data); + else + result = imap_perform_fetch(data); + } + } + else { + failf(data, "Select failed"); + result = CURLE_LOGIN_DENIED; + } + + return result; +} + +/* For the (first line of the) FETCH responses */ +static CURLcode imap_state_fetch_resp(struct Curl_easy *data, + struct connectdata *conn, int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + struct imap_conn *imapc = &conn->proto.imapc; + struct pingpong *pp = &imapc->pp; + const char *ptr = Curl_dyn_ptr(&data->conn->proto.imapc.pp.recvbuf); + size_t len = data->conn->proto.imapc.pp.nfinal; + bool parsed = FALSE; + curl_off_t size = 0; + + (void)instate; /* no use for this yet */ + + if(imapcode != '*') { + Curl_pgrsSetDownloadSize(data, -1); + imap_state(data, IMAP_STOP); + return CURLE_REMOTE_FILE_NOT_FOUND; + } + + /* Something like this is received "* 1 FETCH (BODY[TEXT] {2021}\r" so parse + the continuation data contained within the curly brackets */ + ptr = memchr(ptr, '{', len); + if(ptr) { + char *endptr; + if(!curlx_strtoofft(ptr + 1, &endptr, 10, &size) && + (endptr - ptr > 1 && *endptr == '}')) + parsed = TRUE; + } + + if(parsed) { + infof(data, "Found %" CURL_FORMAT_CURL_OFF_T " bytes to download", + size); + Curl_pgrsSetDownloadSize(data, size); + + if(pp->overflow) { + /* At this point there is a data in the receive buffer that is body + content, send it as body and then skip it. Do note that there may + even be additional "headers" after the body. */ + size_t chunk = pp->overflow; + + /* keep only the overflow */ + Curl_dyn_tail(&pp->recvbuf, chunk); + pp->nfinal = 0; /* done */ + + if(chunk > (size_t)size) + /* The conversion from curl_off_t to size_t is always fine here */ + chunk = (size_t)size; + + if(!chunk) { + /* no size, we're done with the data */ + imap_state(data, IMAP_STOP); + return CURLE_OK; + } + result = Curl_client_write(data, CLIENTWRITE_BODY, + Curl_dyn_ptr(&pp->recvbuf), chunk); + if(result) + return result; + + infof(data, "Written %zu bytes, %" CURL_FORMAT_CURL_OFF_TU + " bytes are left for transfer", chunk, size - chunk); + + /* Have we used the entire overflow or just part of it?*/ + if(pp->overflow > chunk) { + /* remember the remaining trailing overflow data */ + pp->overflow -= chunk; + Curl_dyn_tail(&pp->recvbuf, pp->overflow); + } + else { + pp->overflow = 0; /* handled */ + /* Free the cache */ + Curl_dyn_reset(&pp->recvbuf); + } + } + + if(data->req.bytecount == size) + /* The entire data is already transferred! */ + Curl_xfer_setup(data, -1, -1, FALSE, -1); + else { + /* IMAP download */ + data->req.maxdownload = size; + /* force a recv/send check of this connection, as the data might've been + read off the socket already */ + data->state.select_bits = CURL_CSELECT_IN; + Curl_xfer_setup(data, FIRSTSOCKET, size, FALSE, -1); + } + } + else { + /* We don't know how to parse this line */ + failf(data, "Failed to parse FETCH response."); + result = CURLE_WEIRD_SERVER_REPLY; + } + + /* End of DO phase */ + imap_state(data, IMAP_STOP); + + return result; +} + +/* For final FETCH responses performed after the download */ +static CURLcode imap_state_fetch_final_resp(struct Curl_easy *data, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + + (void)instate; /* No use for this yet */ + + if(imapcode != IMAP_RESP_OK) + result = CURLE_WEIRD_SERVER_REPLY; + else + /* End of DONE phase */ + imap_state(data, IMAP_STOP); + + return result; +} + +/* For APPEND responses */ +static CURLcode imap_state_append_resp(struct Curl_easy *data, int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + (void)instate; /* No use for this yet */ + + if(imapcode != '+') { + result = CURLE_UPLOAD_FAILED; + } + else { + /* Set the progress upload size */ + Curl_pgrsSetUploadSize(data, data->state.infilesize); + + /* IMAP upload */ + Curl_xfer_setup(data, -1, -1, FALSE, FIRSTSOCKET); + + /* End of DO phase */ + imap_state(data, IMAP_STOP); + } + + return result; +} + +/* For final APPEND responses performed after the upload */ +static CURLcode imap_state_append_final_resp(struct Curl_easy *data, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + + (void)instate; /* No use for this yet */ + + if(imapcode != IMAP_RESP_OK) + result = CURLE_UPLOAD_FAILED; + else + /* End of DONE phase */ + imap_state(data, IMAP_STOP); + + return result; +} + +static CURLcode imap_statemachine(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + int imapcode; + struct imap_conn *imapc = &conn->proto.imapc; + struct pingpong *pp = &imapc->pp; + size_t nread = 0; + (void)data; + + /* Busy upgrading the connection; right now all I/O is SSL/TLS, not IMAP */ + if(imapc->state == IMAP_UPGRADETLS) + return imap_perform_upgrade_tls(data, conn); + + /* Flush any data that needs to be sent */ + if(pp->sendleft) + return Curl_pp_flushsend(data, pp); + + do { + /* Read the response from the server */ + result = Curl_pp_readresp(data, FIRSTSOCKET, pp, &imapcode, &nread); + if(result) + return result; + + /* Was there an error parsing the response line? */ + if(imapcode == -1) + return CURLE_WEIRD_SERVER_REPLY; + + if(!imapcode) + break; + + /* We have now received a full IMAP server response */ + switch(imapc->state) { + case IMAP_SERVERGREET: + result = imap_state_servergreet_resp(data, imapcode, imapc->state); + break; + + case IMAP_CAPABILITY: + result = imap_state_capability_resp(data, imapcode, imapc->state); + break; + + case IMAP_STARTTLS: + result = imap_state_starttls_resp(data, imapcode, imapc->state); + break; + + case IMAP_AUTHENTICATE: + result = imap_state_auth_resp(data, conn, imapcode, imapc->state); + break; + + case IMAP_LOGIN: + result = imap_state_login_resp(data, imapcode, imapc->state); + break; + + case IMAP_LIST: + case IMAP_SEARCH: + result = imap_state_listsearch_resp(data, imapcode, imapc->state); + break; + + case IMAP_SELECT: + result = imap_state_select_resp(data, imapcode, imapc->state); + break; + + case IMAP_FETCH: + result = imap_state_fetch_resp(data, conn, imapcode, imapc->state); + break; + + case IMAP_FETCH_FINAL: + result = imap_state_fetch_final_resp(data, imapcode, imapc->state); + break; + + case IMAP_APPEND: + result = imap_state_append_resp(data, imapcode, imapc->state); + break; + + case IMAP_APPEND_FINAL: + result = imap_state_append_final_resp(data, imapcode, imapc->state); + break; + + case IMAP_LOGOUT: + default: + /* internal error */ + imap_state(data, IMAP_STOP); + break; + } + } while(!result && imapc->state != IMAP_STOP && Curl_pp_moredata(pp)); + + return result; +} + +/* Called repeatedly until done from multi.c */ +static CURLcode imap_multi_statemach(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct imap_conn *imapc = &conn->proto.imapc; + + if((conn->handler->flags & PROTOPT_SSL) && !imapc->ssldone) { + bool ssldone = FALSE; + result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &ssldone); + imapc->ssldone = ssldone; + if(result || !ssldone) + return result; + } + + result = Curl_pp_statemach(data, &imapc->pp, FALSE, FALSE); + *done = (imapc->state == IMAP_STOP) ? TRUE : FALSE; + + return result; +} + +static CURLcode imap_block_statemach(struct Curl_easy *data, + struct connectdata *conn, + bool disconnecting) +{ + CURLcode result = CURLE_OK; + struct imap_conn *imapc = &conn->proto.imapc; + + while(imapc->state != IMAP_STOP && !result) + result = Curl_pp_statemach(data, &imapc->pp, TRUE, disconnecting); + + return result; +} + +/* Allocate and initialize the struct IMAP for the current Curl_easy if + required */ +static CURLcode imap_init(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct IMAP *imap; + + imap = data->req.p.imap = calloc(1, sizeof(struct IMAP)); + if(!imap) + result = CURLE_OUT_OF_MEMORY; + + return result; +} + +/* For the IMAP "protocol connect" and "doing" phases only */ +static int imap_getsock(struct Curl_easy *data, + struct connectdata *conn, + curl_socket_t *socks) +{ + return Curl_pp_getsock(data, &conn->proto.imapc.pp, socks); +} + +/*********************************************************************** + * + * imap_connect() + * + * This function should do everything that is to be considered a part of the + * connection phase. + * + * The variable 'done' points to will be TRUE if the protocol-layer connect + * phase is done when this function returns, or FALSE if not. + */ +static CURLcode imap_connect(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct imap_conn *imapc = &conn->proto.imapc; + struct pingpong *pp = &imapc->pp; + + *done = FALSE; /* default to not done yet */ + + /* We always support persistent connections in IMAP */ + connkeep(conn, "IMAP default"); + + PINGPONG_SETUP(pp, imap_statemachine, imap_endofresp); + + /* Set the default preferred authentication type and mechanism */ + imapc->preftype = IMAP_TYPE_ANY; + Curl_sasl_init(&imapc->sasl, data, &saslimap); + + Curl_dyn_init(&imapc->dyn, DYN_IMAP_CMD); + Curl_pp_init(pp); + + /* Parse the URL options */ + result = imap_parse_url_options(conn); + if(result) + return result; + + /* Start off waiting for the server greeting response */ + imap_state(data, IMAP_SERVERGREET); + + /* Start off with an response id of '*' */ + strcpy(imapc->resptag, "*"); + + result = imap_multi_statemach(data, done); + + return result; +} + +/*********************************************************************** + * + * imap_done() + * + * The DONE function. This does what needs to be done after a single DO has + * performed. + * + * Input argument is already checked for validity. + */ +static CURLcode imap_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct IMAP *imap = data->req.p.imap; + + (void)premature; + + if(!imap) + return CURLE_OK; + + if(status) { + connclose(conn, "IMAP done with bad status"); /* marked for closure */ + result = status; /* use the already set error code */ + } + else if(!data->set.connect_only && !imap->custom && + (imap->uid || imap->mindex || data->state.upload || + IS_MIME_POST(data))) { + /* Handle responses after FETCH or APPEND transfer has finished */ + + if(!data->state.upload && !IS_MIME_POST(data)) + imap_state(data, IMAP_FETCH_FINAL); + else { + /* End the APPEND command first by sending an empty line */ + result = Curl_pp_sendf(data, &conn->proto.imapc.pp, "%s", ""); + if(!result) + imap_state(data, IMAP_APPEND_FINAL); + } + + /* Run the state-machine */ + if(!result) + result = imap_block_statemach(data, conn, FALSE); + } + + /* Cleanup our per-request based variables */ + Curl_safefree(imap->mailbox); + Curl_safefree(imap->uidvalidity); + Curl_safefree(imap->uid); + Curl_safefree(imap->mindex); + Curl_safefree(imap->section); + Curl_safefree(imap->partial); + Curl_safefree(imap->query); + Curl_safefree(imap->custom); + Curl_safefree(imap->custom_params); + + /* Clear the transfer mode for the next request */ + imap->transfer = PPTRANSFER_BODY; + + return result; +} + +/*********************************************************************** + * + * imap_perform() + * + * This is the actual DO function for IMAP. Fetch or append a message, or do + * other things according to the options previously setup. + */ +static CURLcode imap_perform(struct Curl_easy *data, bool *connected, + bool *dophase_done) +{ + /* This is IMAP and no proxy */ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct IMAP *imap = data->req.p.imap; + struct imap_conn *imapc = &conn->proto.imapc; + bool selected = FALSE; + + DEBUGF(infof(data, "DO phase starts")); + + if(data->req.no_body) { + /* Requested no body means no transfer */ + imap->transfer = PPTRANSFER_INFO; + } + + *dophase_done = FALSE; /* not done yet */ + + /* Determine if the requested mailbox (with the same UIDVALIDITY if set) + has already been selected on this connection */ + if(imap->mailbox && imapc->mailbox && + strcasecompare(imap->mailbox, imapc->mailbox) && + (!imap->uidvalidity || !imapc->mailbox_uidvalidity || + strcasecompare(imap->uidvalidity, imapc->mailbox_uidvalidity))) + selected = TRUE; + + /* Start the first command in the DO phase */ + if(data->state.upload || IS_MIME_POST(data)) + /* APPEND can be executed directly */ + result = imap_perform_append(data); + else if(imap->custom && (selected || !imap->mailbox)) + /* Custom command using the same mailbox or no mailbox */ + result = imap_perform_list(data); + else if(!imap->custom && selected && (imap->uid || imap->mindex)) + /* FETCH from the same mailbox */ + result = imap_perform_fetch(data); + else if(!imap->custom && selected && imap->query) + /* SEARCH the current mailbox */ + result = imap_perform_search(data); + else if(imap->mailbox && !selected && + (imap->custom || imap->uid || imap->mindex || imap->query)) + /* SELECT the mailbox */ + result = imap_perform_select(data); + else + /* LIST */ + result = imap_perform_list(data); + + if(result) + return result; + + /* Run the state-machine */ + result = imap_multi_statemach(data, dophase_done); + + *connected = Curl_conn_is_connected(conn, FIRSTSOCKET); + + if(*dophase_done) + DEBUGF(infof(data, "DO phase is complete")); + + return result; +} + +/*********************************************************************** + * + * imap_do() + * + * This function is registered as 'curl_do' function. It decodes the path + * parts etc as a wrapper to the actual DO function (imap_perform). + * + * The input argument is already checked for validity. + */ +static CURLcode imap_do(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + *done = FALSE; /* default to false */ + + /* Parse the URL path */ + result = imap_parse_url_path(data); + if(result) + return result; + + /* Parse the custom request */ + result = imap_parse_custom_request(data); + if(result) + return result; + + result = imap_regular_transfer(data, done); + + return result; +} + +/*********************************************************************** + * + * imap_disconnect() + * + * Disconnect from an IMAP server. Cleanup protocol-specific per-connection + * resources. BLOCKING. + */ +static CURLcode imap_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead_connection) +{ + struct imap_conn *imapc = &conn->proto.imapc; + (void)data; + + /* We cannot send quit unconditionally. If this connection is stale or + bad in any way, sending quit and waiting around here will make the + disconnect wait in vain and cause more problems than we need to. */ + + /* The IMAP session may or may not have been allocated/setup at this + point! */ + if(!dead_connection && conn->bits.protoconnstart) { + if(!imap_perform_logout(data)) + (void)imap_block_statemach(data, conn, TRUE); /* ignore errors */ + } + + /* Disconnect from the server */ + Curl_pp_disconnect(&imapc->pp); + Curl_dyn_free(&imapc->dyn); + + /* Cleanup the SASL module */ + Curl_sasl_cleanup(conn, imapc->sasl.authused); + + /* Cleanup our connection based variables */ + Curl_safefree(imapc->mailbox); + Curl_safefree(imapc->mailbox_uidvalidity); + + return CURLE_OK; +} + +/* Call this when the DO phase has completed */ +static CURLcode imap_dophase_done(struct Curl_easy *data, bool connected) +{ + struct IMAP *imap = data->req.p.imap; + + (void)connected; + + if(imap->transfer != PPTRANSFER_BODY) + /* no data to transfer */ + Curl_xfer_setup(data, -1, -1, FALSE, -1); + + return CURLE_OK; +} + +/* Called from multi.c while DOing */ +static CURLcode imap_doing(struct Curl_easy *data, bool *dophase_done) +{ + CURLcode result = imap_multi_statemach(data, dophase_done); + + if(result) + DEBUGF(infof(data, "DO phase failed")); + else if(*dophase_done) { + result = imap_dophase_done(data, FALSE /* not connected */); + + DEBUGF(infof(data, "DO phase is complete")); + } + + return result; +} + +/*********************************************************************** + * + * imap_regular_transfer() + * + * The input argument is already checked for validity. + * + * Performs all commands done before a regular transfer between a local and a + * remote host. + */ +static CURLcode imap_regular_transfer(struct Curl_easy *data, + bool *dophase_done) +{ + CURLcode result = CURLE_OK; + bool connected = FALSE; + + /* Make sure size is unknown at this point */ + data->req.size = -1; + + /* Set the progress data */ + Curl_pgrsSetUploadCounter(data, 0); + Curl_pgrsSetDownloadCounter(data, 0); + Curl_pgrsSetUploadSize(data, -1); + Curl_pgrsSetDownloadSize(data, -1); + + /* Carry out the perform */ + result = imap_perform(data, &connected, dophase_done); + + /* Perform post DO phase operations if necessary */ + if(!result && *dophase_done) + result = imap_dophase_done(data, connected); + + return result; +} + +static CURLcode imap_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + /* Initialise the IMAP layer */ + CURLcode result = imap_init(data); + if(result) + return result; + + /* Clear the TLS upgraded flag */ + conn->bits.tls_upgraded = FALSE; + + return CURLE_OK; +} + +/*********************************************************************** + * + * imap_sendf() + * + * Sends the formatted string as an IMAP command to the server. + * + * Designed to never block. + */ +static CURLcode imap_sendf(struct Curl_easy *data, const char *fmt, ...) +{ + CURLcode result = CURLE_OK; + struct imap_conn *imapc = &data->conn->proto.imapc; + + DEBUGASSERT(fmt); + + /* Calculate the tag based on the connection ID and command ID */ + msnprintf(imapc->resptag, sizeof(imapc->resptag), "%c%03d", + 'A' + curlx_sltosi((long)(data->conn->connection_id % 26)), + ++imapc->cmdid); + + /* start with a blank buffer */ + Curl_dyn_reset(&imapc->dyn); + + /* append tag + space + fmt */ + result = Curl_dyn_addf(&imapc->dyn, "%s %s", imapc->resptag, fmt); + if(!result) { + va_list ap; + va_start(ap, fmt); +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wformat-nonliteral" +#endif + result = Curl_pp_vsendf(data, &imapc->pp, Curl_dyn_ptr(&imapc->dyn), ap); +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + va_end(ap); + } + return result; +} + +/*********************************************************************** + * + * imap_atom() + * + * Checks the input string for characters that need escaping and returns an + * atom ready for sending to the server. + * + * The returned string needs to be freed. + * + */ +static char *imap_atom(const char *str, bool escape_only) +{ + struct dynbuf line; + size_t nclean; + size_t len; + + if(!str) + return NULL; + + len = strlen(str); + nclean = strcspn(str, "() {%*]\\\""); + if(len == nclean) + /* nothing to escape, return a strdup */ + return strdup(str); + + Curl_dyn_init(&line, 2000); + + if(!escape_only && Curl_dyn_addn(&line, "\"", 1)) + return NULL; + + while(*str) { + if((*str == '\\' || *str == '"') && + Curl_dyn_addn(&line, "\\", 1)) + return NULL; + if(Curl_dyn_addn(&line, str, 1)) + return NULL; + str++; + } + + if(!escape_only && Curl_dyn_addn(&line, "\"", 1)) + return NULL; + + return Curl_dyn_ptr(&line); +} + +/*********************************************************************** + * + * imap_is_bchar() + * + * Portable test of whether the specified char is a "bchar" as defined in the + * grammar of RFC-5092. + */ +static bool imap_is_bchar(char ch) +{ + /* Performing the alnum check with this macro is faster because of ASCII + arithmetic */ + if(ISALNUM(ch)) + return true; + + switch(ch) { + /* bchar */ + case ':': case '@': case '/': + /* bchar -> achar */ + case '&': case '=': + /* bchar -> achar -> uchar -> unreserved (without alphanumeric) */ + case '-': case '.': case '_': case '~': + /* bchar -> achar -> uchar -> sub-delims-sh */ + case '!': case '$': case '\'': case '(': case ')': case '*': + case '+': case ',': + /* bchar -> achar -> uchar -> pct-encoded */ + case '%': /* HEXDIG chars are already included above */ + return true; + + default: + return false; + } +} + +/*********************************************************************** + * + * imap_parse_url_options() + * + * Parse the URL login options. + */ +static CURLcode imap_parse_url_options(struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + struct imap_conn *imapc = &conn->proto.imapc; + const char *ptr = conn->options; + bool prefer_login = false; + + while(!result && ptr && *ptr) { + const char *key = ptr; + const char *value; + + while(*ptr && *ptr != '=') + ptr++; + + value = ptr + 1; + + while(*ptr && *ptr != ';') + ptr++; + + if(strncasecompare(key, "AUTH=+LOGIN", 11)) { + /* User prefers plaintext LOGIN over any SASL, including SASL LOGIN */ + prefer_login = true; + imapc->sasl.prefmech = SASL_AUTH_NONE; + } + else if(strncasecompare(key, "AUTH=", 5)) { + prefer_login = false; + result = Curl_sasl_parse_url_auth_option(&imapc->sasl, + value, ptr - value); + } + else { + prefer_login = false; + result = CURLE_URL_MALFORMAT; + } + + if(*ptr == ';') + ptr++; + } + + if(prefer_login) + imapc->preftype = IMAP_TYPE_CLEARTEXT; + else { + switch(imapc->sasl.prefmech) { + case SASL_AUTH_NONE: + imapc->preftype = IMAP_TYPE_NONE; + break; + case SASL_AUTH_DEFAULT: + imapc->preftype = IMAP_TYPE_ANY; + break; + default: + imapc->preftype = IMAP_TYPE_SASL; + break; + } + } + + return result; +} + +/*********************************************************************** + * + * imap_parse_url_path() + * + * Parse the URL path into separate path components. + * + */ +static CURLcode imap_parse_url_path(struct Curl_easy *data) +{ + /* The imap struct is already initialised in imap_connect() */ + CURLcode result = CURLE_OK; + struct IMAP *imap = data->req.p.imap; + const char *begin = &data->state.up.path[1]; /* skip leading slash */ + const char *ptr = begin; + + /* See how much of the URL is a valid path and decode it */ + while(imap_is_bchar(*ptr)) + ptr++; + + if(ptr != begin) { + /* Remove the trailing slash if present */ + const char *end = ptr; + if(end > begin && end[-1] == '/') + end--; + + result = Curl_urldecode(begin, end - begin, &imap->mailbox, NULL, + REJECT_CTRL); + if(result) + return result; + } + else + imap->mailbox = NULL; + + /* There can be any number of parameters in the form ";NAME=VALUE" */ + while(*ptr == ';') { + char *name; + char *value; + size_t valuelen; + + /* Find the length of the name parameter */ + begin = ++ptr; + while(*ptr && *ptr != '=') + ptr++; + + if(!*ptr) + return CURLE_URL_MALFORMAT; + + /* Decode the name parameter */ + result = Curl_urldecode(begin, ptr - begin, &name, NULL, + REJECT_CTRL); + if(result) + return result; + + /* Find the length of the value parameter */ + begin = ++ptr; + while(imap_is_bchar(*ptr)) + ptr++; + + /* Decode the value parameter */ + result = Curl_urldecode(begin, ptr - begin, &value, &valuelen, + REJECT_CTRL); + if(result) { + free(name); + return result; + } + + DEBUGF(infof(data, "IMAP URL parameter '%s' = '%s'", name, value)); + + /* Process the known hierarchical parameters (UIDVALIDITY, UID, SECTION and + PARTIAL) stripping of the trailing slash character if it is present. + + Note: Unknown parameters trigger a URL_MALFORMAT error. */ + if(strcasecompare(name, "UIDVALIDITY") && !imap->uidvalidity) { + if(valuelen > 0 && value[valuelen - 1] == '/') + value[valuelen - 1] = '\0'; + + imap->uidvalidity = value; + value = NULL; + } + else if(strcasecompare(name, "UID") && !imap->uid) { + if(valuelen > 0 && value[valuelen - 1] == '/') + value[valuelen - 1] = '\0'; + + imap->uid = value; + value = NULL; + } + else if(strcasecompare(name, "MAILINDEX") && !imap->mindex) { + if(valuelen > 0 && value[valuelen - 1] == '/') + value[valuelen - 1] = '\0'; + + imap->mindex = value; + value = NULL; + } + else if(strcasecompare(name, "SECTION") && !imap->section) { + if(valuelen > 0 && value[valuelen - 1] == '/') + value[valuelen - 1] = '\0'; + + imap->section = value; + value = NULL; + } + else if(strcasecompare(name, "PARTIAL") && !imap->partial) { + if(valuelen > 0 && value[valuelen - 1] == '/') + value[valuelen - 1] = '\0'; + + imap->partial = value; + value = NULL; + } + else { + free(name); + free(value); + + return CURLE_URL_MALFORMAT; + } + + free(name); + free(value); + } + + /* Does the URL contain a query parameter? Only valid when we have a mailbox + and no UID as per RFC-5092 */ + if(imap->mailbox && !imap->uid && !imap->mindex) { + /* Get the query parameter, URL decoded */ + (void)curl_url_get(data->state.uh, CURLUPART_QUERY, &imap->query, + CURLU_URLDECODE); + } + + /* Any extra stuff at the end of the URL is an error */ + if(*ptr) + return CURLE_URL_MALFORMAT; + + return CURLE_OK; +} + +/*********************************************************************** + * + * imap_parse_custom_request() + * + * Parse the custom request. + */ +static CURLcode imap_parse_custom_request(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct IMAP *imap = data->req.p.imap; + const char *custom = data->set.str[STRING_CUSTOMREQUEST]; + + if(custom) { + /* URL decode the custom request */ + result = Curl_urldecode(custom, 0, &imap->custom, NULL, REJECT_CTRL); + + /* Extract the parameters if specified */ + if(!result) { + const char *params = imap->custom; + + while(*params && *params != ' ') + params++; + + if(*params) { + imap->custom_params = strdup(params); + imap->custom[params - imap->custom] = '\0'; + + if(!imap->custom_params) + result = CURLE_OUT_OF_MEMORY; + } + } + } + + return result; +} + +#endif /* CURL_DISABLE_IMAP */ diff --git a/third_party/curl/lib/imap.h b/third_party/curl/lib/imap.h new file mode 100644 index 0000000..784ee97 --- /dev/null +++ b/third_party/curl/lib/imap.h @@ -0,0 +1,101 @@ +#ifndef HEADER_CURL_IMAP_H +#define HEADER_CURL_IMAP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "pingpong.h" +#include "curl_sasl.h" + +/**************************************************************************** + * IMAP unique setup + ***************************************************************************/ +typedef enum { + IMAP_STOP, /* do nothing state, stops the state machine */ + IMAP_SERVERGREET, /* waiting for the initial greeting immediately after + a connect */ + IMAP_CAPABILITY, + IMAP_STARTTLS, + IMAP_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS + (multi mode only) */ + IMAP_AUTHENTICATE, + IMAP_LOGIN, + IMAP_LIST, + IMAP_SELECT, + IMAP_FETCH, + IMAP_FETCH_FINAL, + IMAP_APPEND, + IMAP_APPEND_FINAL, + IMAP_SEARCH, + IMAP_LOGOUT, + IMAP_LAST /* never used */ +} imapstate; + +/* This IMAP struct is used in the Curl_easy. All IMAP data that is + connection-oriented must be in imap_conn to properly deal with the fact that + perhaps the Curl_easy is changed between the times the connection is + used. */ +struct IMAP { + curl_pp_transfer transfer; + char *mailbox; /* Mailbox to select */ + char *uidvalidity; /* UIDVALIDITY to check in select */ + char *uid; /* Message UID to fetch */ + char *mindex; /* Index in mail box of mail to fetch */ + char *section; /* Message SECTION to fetch */ + char *partial; /* Message PARTIAL to fetch */ + char *query; /* Query to search for */ + char *custom; /* Custom request */ + char *custom_params; /* Parameters for the custom request */ +}; + +/* imap_conn is used for struct connection-oriented data in the connectdata + struct */ +struct imap_conn { + struct pingpong pp; + struct SASL sasl; /* SASL-related parameters */ + struct dynbuf dyn; /* for the IMAP commands */ + char *mailbox; /* The last selected mailbox */ + char *mailbox_uidvalidity; /* UIDVALIDITY parsed from select response */ + imapstate state; /* Always use imap.c:state() to change state! */ + char resptag[5]; /* Response tag to wait for */ + unsigned char preftype; /* Preferred authentication type */ + unsigned char cmdid; /* Last used command ID */ + BIT(ssldone); /* Is connect() over SSL done? */ + BIT(preauth); /* Is this connection PREAUTH? */ + BIT(tls_supported); /* StartTLS capability supported by server */ + BIT(login_disabled); /* LOGIN command disabled by server */ + BIT(ir_supported); /* Initial response supported by server */ +}; + +extern const struct Curl_handler Curl_handler_imap; +extern const struct Curl_handler Curl_handler_imaps; + +/* Authentication type flags */ +#define IMAP_TYPE_CLEARTEXT (1 << 0) +#define IMAP_TYPE_SASL (1 << 1) + +/* Authentication type values */ +#define IMAP_TYPE_NONE 0 +#define IMAP_TYPE_ANY (IMAP_TYPE_CLEARTEXT|IMAP_TYPE_SASL) + +#endif /* HEADER_CURL_IMAP_H */ diff --git a/third_party/curl/lib/inet_ntop.c b/third_party/curl/lib/inet_ntop.c new file mode 100644 index 0000000..4520b87 --- /dev/null +++ b/third_party/curl/lib/inet_ntop.c @@ -0,0 +1,205 @@ +/* + * Copyright (C) 1996-2022 Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM + * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL + * INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING + * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, + * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION + * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * SPDX-License-Identifier: ISC + */ +/* + * Original code by Paul Vixie. "curlified" by Gisle Vanem. + */ + +#include "curl_setup.h" + +#ifndef HAVE_INET_NTOP + +#ifdef HAVE_SYS_PARAM_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif + +#include "inet_ntop.h" +#include "curl_printf.h" + +#define IN6ADDRSZ 16 +#define INADDRSZ 4 +#define INT16SZ 2 + +/* + * If USE_IPV6 is disabled, we still want to parse IPv6 addresses, so make + * sure we have _some_ value for AF_INET6 without polluting our fake value + * everywhere. + */ +#if !defined(USE_IPV6) && !defined(AF_INET6) +#define AF_INET6 (AF_INET + 1) +#endif + +/* + * Format an IPv4 address, more or less like inet_ntop(). + * + * Returns `dst' (as a const) + * Note: + * - uses no statics + * - takes a unsigned char* not an in_addr as input + */ +static char *inet_ntop4 (const unsigned char *src, char *dst, size_t size) +{ + char tmp[sizeof("255.255.255.255")]; + size_t len; + + DEBUGASSERT(size >= 16); + + tmp[0] = '\0'; + (void)msnprintf(tmp, sizeof(tmp), "%d.%d.%d.%d", + ((int)((unsigned char)src[0])) & 0xff, + ((int)((unsigned char)src[1])) & 0xff, + ((int)((unsigned char)src[2])) & 0xff, + ((int)((unsigned char)src[3])) & 0xff); + + len = strlen(tmp); + if(len == 0 || len >= size) { + errno = ENOSPC; + return (NULL); + } + strcpy(dst, tmp); + return dst; +} + +/* + * Convert IPv6 binary address into presentation (printable) format. + */ +static char *inet_ntop6 (const unsigned char *src, char *dst, size_t size) +{ + /* + * Note that int32_t and int16_t need only be "at least" large enough + * to contain a value of the specified size. On some systems, like + * Crays, there is no such thing as an integer variable with 16 bits. + * Keep this in mind if you think this function should have been coded + * to use pointer overlays. All the world's not a VAX. + */ + char tmp[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")]; + char *tp; + struct { + int base; + int len; + } best, cur; + unsigned int words[IN6ADDRSZ / INT16SZ]; + int i; + + /* Preprocess: + * Copy the input (bytewise) array into a wordwise array. + * Find the longest run of 0x00's in src[] for :: shorthanding. + */ + memset(words, '\0', sizeof(words)); + for(i = 0; i < IN6ADDRSZ; i++) + words[i/2] |= ((unsigned int)src[i] << ((1 - (i % 2)) << 3)); + + best.base = -1; + cur.base = -1; + best.len = 0; + cur.len = 0; + + for(i = 0; i < (IN6ADDRSZ / INT16SZ); i++) { + if(words[i] == 0) { + if(cur.base == -1) { + cur.base = i; cur.len = 1; + } + else + cur.len++; + } + else if(cur.base != -1) { + if(best.base == -1 || cur.len > best.len) + best = cur; + cur.base = -1; + } + } + if((cur.base != -1) && (best.base == -1 || cur.len > best.len)) + best = cur; + if(best.base != -1 && best.len < 2) + best.base = -1; + /* Format the result. */ + tp = tmp; + for(i = 0; i < (IN6ADDRSZ / INT16SZ); i++) { + /* Are we inside the best run of 0x00's? */ + if(best.base != -1 && i >= best.base && i < (best.base + best.len)) { + if(i == best.base) + *tp++ = ':'; + continue; + } + + /* Are we following an initial run of 0x00s or any real hex? + */ + if(i) + *tp++ = ':'; + + /* Is this address an encapsulated IPv4? + */ + if(i == 6 && best.base == 0 && + (best.len == 6 || (best.len == 5 && words[5] == 0xffff))) { + if(!inet_ntop4(src + 12, tp, sizeof(tmp) - (tp - tmp))) { + errno = ENOSPC; + return (NULL); + } + tp += strlen(tp); + break; + } + tp += msnprintf(tp, 5, "%x", words[i]); + } + + /* Was it a trailing run of 0x00's? + */ + if(best.base != -1 && (best.base + best.len) == (IN6ADDRSZ / INT16SZ)) + *tp++ = ':'; + *tp++ = '\0'; + + /* Check for overflow, copy, and we're done. + */ + if((size_t)(tp - tmp) > size) { + errno = ENOSPC; + return (NULL); + } + strcpy(dst, tmp); + return dst; +} + +/* + * Convert a network format address to presentation format. + * + * Returns pointer to presentation format address (`buf'). + * Returns NULL on error and errno set with the specific + * error, EAFNOSUPPORT or ENOSPC. + * + * On Windows we store the error in the thread errno, not + * in the winsock error code. This is to avoid losing the + * actual last winsock error. So when this function returns + * NULL, check errno not SOCKERRNO. + */ +char *Curl_inet_ntop(int af, const void *src, char *buf, size_t size) +{ + switch(af) { + case AF_INET: + return inet_ntop4((const unsigned char *)src, buf, size); + case AF_INET6: + return inet_ntop6((const unsigned char *)src, buf, size); + default: + errno = EAFNOSUPPORT; + return NULL; + } +} +#endif /* HAVE_INET_NTOP */ diff --git a/third_party/curl/lib/inet_ntop.h b/third_party/curl/lib/inet_ntop.h new file mode 100644 index 0000000..7c3ead4 --- /dev/null +++ b/third_party/curl/lib/inet_ntop.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_INET_NTOP_H +#define HEADER_CURL_INET_NTOP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +char *Curl_inet_ntop(int af, const void *addr, char *buf, size_t size); + +#ifdef HAVE_INET_NTOP +#ifdef HAVE_ARPA_INET_H +#include +#endif +#define Curl_inet_ntop(af,addr,buf,size) \ + inet_ntop(af, addr, buf, (curl_socklen_t)size) +#endif + +#endif /* HEADER_CURL_INET_NTOP_H */ diff --git a/third_party/curl/lib/inet_pton.c b/third_party/curl/lib/inet_pton.c new file mode 100644 index 0000000..9cfcec1 --- /dev/null +++ b/third_party/curl/lib/inet_pton.c @@ -0,0 +1,243 @@ +/* This is from the BIND 4.9.4 release, modified to compile by itself */ + +/* Copyright (c) Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS + * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE + * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + * SOFTWARE. + * + * SPDX-License-Identifier: ISC + */ + +#include "curl_setup.h" + +#ifndef HAVE_INET_PTON + +#ifdef HAVE_SYS_PARAM_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif + +#include "inet_pton.h" + +#define IN6ADDRSZ 16 +#define INADDRSZ 4 +#define INT16SZ 2 + +/* + * If USE_IPV6 is disabled, we still want to parse IPv6 addresses, so make + * sure we have _some_ value for AF_INET6 without polluting our fake value + * everywhere. + */ +#if !defined(USE_IPV6) && !defined(AF_INET6) +#define AF_INET6 (AF_INET + 1) +#endif + +/* + * WARNING: Don't even consider trying to compile this on a system where + * sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX. + */ + +static int inet_pton4(const char *src, unsigned char *dst); +static int inet_pton6(const char *src, unsigned char *dst); + +/* int + * inet_pton(af, src, dst) + * convert from presentation format (which usually means ASCII printable) + * to network format (which is usually some kind of binary format). + * return: + * 1 if the address was valid for the specified address family + * 0 if the address wasn't valid (`dst' is untouched in this case) + * -1 if some other error occurred (`dst' is untouched in this case, too) + * notice: + * On Windows we store the error in the thread errno, not + * in the winsock error code. This is to avoid losing the + * actual last winsock error. So when this function returns + * -1, check errno not SOCKERRNO. + * author: + * Paul Vixie, 1996. + */ +int +Curl_inet_pton(int af, const char *src, void *dst) +{ + switch(af) { + case AF_INET: + return (inet_pton4(src, (unsigned char *)dst)); + case AF_INET6: + return (inet_pton6(src, (unsigned char *)dst)); + default: + errno = EAFNOSUPPORT; + return (-1); + } + /* NOTREACHED */ +} + +/* int + * inet_pton4(src, dst) + * like inet_aton() but without all the hexadecimal and shorthand. + * return: + * 1 if `src' is a valid dotted quad, else 0. + * notice: + * does not touch `dst' unless it's returning 1. + * author: + * Paul Vixie, 1996. + */ +static int +inet_pton4(const char *src, unsigned char *dst) +{ + static const char digits[] = "0123456789"; + int saw_digit, octets, ch; + unsigned char tmp[INADDRSZ], *tp; + + saw_digit = 0; + octets = 0; + tp = tmp; + *tp = 0; + while((ch = *src++) != '\0') { + const char *pch; + + pch = strchr(digits, ch); + if(pch) { + unsigned int val = (unsigned int)(*tp * 10) + + (unsigned int)(pch - digits); + + if(saw_digit && *tp == 0) + return (0); + if(val > 255) + return (0); + *tp = (unsigned char)val; + if(!saw_digit) { + if(++octets > 4) + return (0); + saw_digit = 1; + } + } + else if(ch == '.' && saw_digit) { + if(octets == 4) + return (0); + *++tp = 0; + saw_digit = 0; + } + else + return (0); + } + if(octets < 4) + return (0); + memcpy(dst, tmp, INADDRSZ); + return (1); +} + +/* int + * inet_pton6(src, dst) + * convert presentation level address to network order binary form. + * return: + * 1 if `src' is a valid [RFC1884 2.2] address, else 0. + * notice: + * (1) does not touch `dst' unless it's returning 1. + * (2) :: in a full address is silently ignored. + * credit: + * inspired by Mark Andrews. + * author: + * Paul Vixie, 1996. + */ +static int +inet_pton6(const char *src, unsigned char *dst) +{ + static const char xdigits_l[] = "0123456789abcdef", + xdigits_u[] = "0123456789ABCDEF"; + unsigned char tmp[IN6ADDRSZ], *tp, *endp, *colonp; + const char *curtok; + int ch, saw_xdigit; + size_t val; + + memset((tp = tmp), 0, IN6ADDRSZ); + endp = tp + IN6ADDRSZ; + colonp = NULL; + /* Leading :: requires some special handling. */ + if(*src == ':') + if(*++src != ':') + return (0); + curtok = src; + saw_xdigit = 0; + val = 0; + while((ch = *src++) != '\0') { + const char *xdigits; + const char *pch; + + pch = strchr((xdigits = xdigits_l), ch); + if(!pch) + pch = strchr((xdigits = xdigits_u), ch); + if(pch) { + val <<= 4; + val |= (pch - xdigits); + if(++saw_xdigit > 4) + return (0); + continue; + } + if(ch == ':') { + curtok = src; + if(!saw_xdigit) { + if(colonp) + return (0); + colonp = tp; + continue; + } + if(tp + INT16SZ > endp) + return (0); + *tp++ = (unsigned char) ((val >> 8) & 0xff); + *tp++ = (unsigned char) (val & 0xff); + saw_xdigit = 0; + val = 0; + continue; + } + if(ch == '.' && ((tp + INADDRSZ) <= endp) && + inet_pton4(curtok, tp) > 0) { + tp += INADDRSZ; + saw_xdigit = 0; + break; /* '\0' was seen by inet_pton4(). */ + } + return (0); + } + if(saw_xdigit) { + if(tp + INT16SZ > endp) + return (0); + *tp++ = (unsigned char) ((val >> 8) & 0xff); + *tp++ = (unsigned char) (val & 0xff); + } + if(colonp) { + /* + * Since some memmove()'s erroneously fail to handle + * overlapping regions, we'll do the shift by hand. + */ + const ssize_t n = tp - colonp; + ssize_t i; + + if(tp == endp) + return (0); + for(i = 1; i <= n; i++) { + *(endp - i) = *(colonp + n - i); + *(colonp + n - i) = 0; + } + tp = endp; + } + if(tp != endp) + return (0); + memcpy(dst, tmp, IN6ADDRSZ); + return (1); +} + +#endif /* HAVE_INET_PTON */ diff --git a/third_party/curl/lib/inet_pton.h b/third_party/curl/lib/inet_pton.h new file mode 100644 index 0000000..f8562fa --- /dev/null +++ b/third_party/curl/lib/inet_pton.h @@ -0,0 +1,38 @@ +#ifndef HEADER_CURL_INET_PTON_H +#define HEADER_CURL_INET_PTON_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +int Curl_inet_pton(int, const char *, void *); + +#ifdef HAVE_INET_PTON +#ifdef HAVE_ARPA_INET_H +#include +#endif +#define Curl_inet_pton(x,y,z) inet_pton(x,y,z) +#endif + +#endif /* HEADER_CURL_INET_PTON_H */ diff --git a/third_party/curl/lib/krb5.c b/third_party/curl/lib/krb5.c new file mode 100644 index 0000000..d355665 --- /dev/null +++ b/third_party/curl/lib/krb5.c @@ -0,0 +1,922 @@ +/* GSSAPI/krb5 support for FTP - loosely based on old krb4.c + * + * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska Högskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * Copyright (C) Daniel Stenberg + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. */ + +#include "curl_setup.h" + +#if defined(HAVE_GSSAPI) && !defined(CURL_DISABLE_FTP) + +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif + +#include "urldata.h" +#include "cfilters.h" +#include "cf-socket.h" +#include "curl_base64.h" +#include "ftp.h" +#include "curl_gssapi.h" +#include "sendf.h" +#include "transfer.h" +#include "curl_krb5.h" +#include "warnless.h" +#include "strcase.h" +#include "strdup.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +static CURLcode ftpsend(struct Curl_easy *data, struct connectdata *conn, + const char *cmd) +{ + size_t bytes_written; +#define SBUF_SIZE 1024 + char s[SBUF_SIZE]; + size_t write_len; + char *sptr = s; + CURLcode result = CURLE_OK; +#ifdef HAVE_GSSAPI + unsigned char data_sec = conn->data_prot; +#endif + + DEBUGASSERT(cmd); + + write_len = strlen(cmd); + if(!write_len || write_len > (sizeof(s) -3)) + return CURLE_BAD_FUNCTION_ARGUMENT; + + memcpy(&s, cmd, write_len); + strcpy(&s[write_len], "\r\n"); /* append a trailing CRLF */ + write_len += 2; + bytes_written = 0; + + for(;;) { +#ifdef HAVE_GSSAPI + conn->data_prot = PROT_CMD; +#endif + result = Curl_xfer_send(data, sptr, write_len, &bytes_written); +#ifdef HAVE_GSSAPI + DEBUGASSERT(data_sec > PROT_NONE && data_sec < PROT_LAST); + conn->data_prot = data_sec; +#endif + + if(result) + break; + + Curl_debug(data, CURLINFO_HEADER_OUT, sptr, bytes_written); + + if(bytes_written != write_len) { + write_len -= bytes_written; + sptr += bytes_written; + } + else + break; + } + + return result; +} + +static int +krb5_init(void *app_data) +{ + gss_ctx_id_t *context = app_data; + /* Make sure our context is initialized for krb5_end. */ + *context = GSS_C_NO_CONTEXT; + return 0; +} + +static int +krb5_check_prot(void *app_data, int level) +{ + (void)app_data; /* unused */ + if(level == PROT_CONFIDENTIAL) + return -1; + return 0; +} + +static int +krb5_decode(void *app_data, void *buf, int len, + int level UNUSED_PARAM, + struct connectdata *conn UNUSED_PARAM) +{ + gss_ctx_id_t *context = app_data; + OM_uint32 maj, min; + gss_buffer_desc enc, dec; + + (void)level; + (void)conn; + + enc.value = buf; + enc.length = len; + maj = gss_unwrap(&min, *context, &enc, &dec, NULL, NULL); + if(maj != GSS_S_COMPLETE) + return -1; + + memcpy(buf, dec.value, dec.length); + len = curlx_uztosi(dec.length); + gss_release_buffer(&min, &dec); + + return len; +} + +static int +krb5_encode(void *app_data, const void *from, int length, int level, void **to) +{ + gss_ctx_id_t *context = app_data; + gss_buffer_desc dec, enc; + OM_uint32 maj, min; + int state; + int len; + + /* NOTE that the cast is safe, neither of the krb5, gnu gss and heimdal + * libraries modify the input buffer in gss_wrap() + */ + dec.value = (void *)from; + dec.length = length; + maj = gss_wrap(&min, *context, + level == PROT_PRIVATE, + GSS_C_QOP_DEFAULT, + &dec, &state, &enc); + + if(maj != GSS_S_COMPLETE) + return -1; + + /* malloc a new buffer, in case gss_release_buffer doesn't work as + expected */ + *to = malloc(enc.length); + if(!*to) + return -1; + memcpy(*to, enc.value, enc.length); + len = curlx_uztosi(enc.length); + gss_release_buffer(&min, &enc); + return len; +} + +static int +krb5_auth(void *app_data, struct Curl_easy *data, struct connectdata *conn) +{ + int ret = AUTH_OK; + char *p; + const char *host = conn->host.name; + ssize_t nread; + curl_socklen_t l = sizeof(conn->local_addr); + CURLcode result; + const char *service = data->set.str[STRING_SERVICE_NAME] ? + data->set.str[STRING_SERVICE_NAME] : + "ftp"; + const char *srv_host = "host"; + gss_buffer_desc input_buffer, output_buffer, _gssresp, *gssresp; + OM_uint32 maj, min; + gss_name_t gssname; + gss_ctx_id_t *context = app_data; + struct gss_channel_bindings_struct chan; + size_t base64_sz = 0; + struct sockaddr_in *remote_addr = + (struct sockaddr_in *)(void *)&conn->remote_addr->sa_addr; + char *stringp; + + if(getsockname(conn->sock[FIRSTSOCKET], + (struct sockaddr *)&conn->local_addr, &l) < 0) + perror("getsockname()"); + + chan.initiator_addrtype = GSS_C_AF_INET; + chan.initiator_address.length = l - 4; + chan.initiator_address.value = &conn->local_addr.sin_addr.s_addr; + chan.acceptor_addrtype = GSS_C_AF_INET; + chan.acceptor_address.length = l - 4; + chan.acceptor_address.value = &remote_addr->sin_addr.s_addr; + chan.application_data.length = 0; + chan.application_data.value = NULL; + + /* this loop will execute twice (once for service, once for host) */ + for(;;) { + /* this really shouldn't be repeated here, but can't help it */ + if(service == srv_host) { + result = ftpsend(data, conn, "AUTH GSSAPI"); + if(result) + return -2; + + if(Curl_GetFTPResponse(data, &nread, NULL)) + return -1; + else { + struct pingpong *pp = &conn->proto.ftpc.pp; + char *line = Curl_dyn_ptr(&pp->recvbuf); + if(line[0] != '3') + return -1; + } + } + + stringp = aprintf("%s@%s", service, host); + if(!stringp) + return -2; + + input_buffer.value = stringp; + input_buffer.length = strlen(stringp); + maj = gss_import_name(&min, &input_buffer, GSS_C_NT_HOSTBASED_SERVICE, + &gssname); + free(stringp); + if(maj != GSS_S_COMPLETE) { + gss_release_name(&min, &gssname); + if(service == srv_host) { + failf(data, "Error importing service name %s@%s", service, host); + return AUTH_ERROR; + } + service = srv_host; + continue; + } + /* We pass NULL as |output_name_type| to avoid a leak. */ + gss_display_name(&min, gssname, &output_buffer, NULL); + infof(data, "Trying against %s", (char *)output_buffer.value); + gssresp = GSS_C_NO_BUFFER; + *context = GSS_C_NO_CONTEXT; + + do { + /* Release the buffer at each iteration to avoid leaking: the first time + we are releasing the memory from gss_display_name. The last item is + taken care by a final gss_release_buffer. */ + gss_release_buffer(&min, &output_buffer); + ret = AUTH_OK; + maj = Curl_gss_init_sec_context(data, + &min, + context, + gssname, + &Curl_krb5_mech_oid, + &chan, + gssresp, + &output_buffer, + TRUE, + NULL); + + if(gssresp) { + free(_gssresp.value); + gssresp = NULL; + } + + if(GSS_ERROR(maj)) { + infof(data, "Error creating security context"); + ret = AUTH_ERROR; + break; + } + + if(output_buffer.length) { + char *cmd; + + result = Curl_base64_encode((char *)output_buffer.value, + output_buffer.length, &p, &base64_sz); + if(result) { + infof(data, "base64-encoding: %s", curl_easy_strerror(result)); + ret = AUTH_ERROR; + break; + } + + cmd = aprintf("ADAT %s", p); + if(cmd) + result = ftpsend(data, conn, cmd); + else + result = CURLE_OUT_OF_MEMORY; + + free(p); + free(cmd); + + if(result) { + ret = -2; + break; + } + + if(Curl_GetFTPResponse(data, &nread, NULL)) { + ret = -1; + break; + } + else { + struct pingpong *pp = &conn->proto.ftpc.pp; + size_t len = Curl_dyn_len(&pp->recvbuf); + p = Curl_dyn_ptr(&pp->recvbuf); + if((len < 4) || (p[0] != '2' && p[0] != '3')) { + infof(data, "Server didn't accept auth data"); + ret = AUTH_ERROR; + break; + } + } + + _gssresp.value = NULL; /* make sure it is initialized */ + p += 4; /* over '789 ' */ + p = strstr(p, "ADAT="); + if(p) { + result = Curl_base64_decode(p + 5, + (unsigned char **)&_gssresp.value, + &_gssresp.length); + if(result) { + failf(data, "base64-decoding: %s", curl_easy_strerror(result)); + ret = AUTH_CONTINUE; + break; + } + } + + gssresp = &_gssresp; + } + } while(maj == GSS_S_CONTINUE_NEEDED); + + gss_release_name(&min, &gssname); + gss_release_buffer(&min, &output_buffer); + + if(gssresp) + free(_gssresp.value); + + if(ret == AUTH_OK || service == srv_host) + return ret; + + service = srv_host; + } + return ret; +} + +static void krb5_end(void *app_data) +{ + OM_uint32 min; + gss_ctx_id_t *context = app_data; + if(*context != GSS_C_NO_CONTEXT) { + OM_uint32 maj = gss_delete_sec_context(&min, context, GSS_C_NO_BUFFER); + (void)maj; + DEBUGASSERT(maj == GSS_S_COMPLETE); + } +} + +static const struct Curl_sec_client_mech Curl_krb5_client_mech = { + "GSSAPI", + sizeof(gss_ctx_id_t), + krb5_init, + krb5_auth, + krb5_end, + krb5_check_prot, + + krb5_encode, + krb5_decode +}; + +static const struct { + unsigned char level; + const char *name; +} level_names[] = { + { PROT_CLEAR, "clear" }, + { PROT_SAFE, "safe" }, + { PROT_CONFIDENTIAL, "confidential" }, + { PROT_PRIVATE, "private" } +}; + +static unsigned char name_to_level(const char *name) +{ + int i; + for(i = 0; i < (int)sizeof(level_names)/(int)sizeof(level_names[0]); i++) + if(curl_strequal(name, level_names[i].name)) + return level_names[i].level; + return PROT_NONE; +} + +/* Convert a protocol |level| to its char representation. + We take an int to catch programming mistakes. */ +static char level_to_char(int level) +{ + switch(level) { + case PROT_CLEAR: + return 'C'; + case PROT_SAFE: + return 'S'; + case PROT_CONFIDENTIAL: + return 'E'; + case PROT_PRIVATE: + return 'P'; + case PROT_CMD: + default: + /* Those 2 cases should not be reached! */ + break; + } + DEBUGASSERT(0); + /* Default to the most secure alternative. */ + return 'P'; +} + +/* Send an FTP command defined by |message| and the optional arguments. The + function returns the ftp_code. If an error occurs, -1 is returned. */ +static int ftp_send_command(struct Curl_easy *data, const char *message, ...) + CURL_PRINTF(2, 3); + +static int ftp_send_command(struct Curl_easy *data, const char *message, ...) +{ + int ftp_code; + ssize_t nread = 0; + va_list args; + char print_buffer[50]; + + va_start(args, message); + mvsnprintf(print_buffer, sizeof(print_buffer), message, args); + va_end(args); + + if(ftpsend(data, data->conn, print_buffer)) { + ftp_code = -1; + } + else { + if(Curl_GetFTPResponse(data, &nread, &ftp_code)) + ftp_code = -1; + } + + (void)nread; /* Unused */ + return ftp_code; +} + +/* Read |len| from the socket |fd| and store it in |to|. Return a CURLcode + saying whether an error occurred or CURLE_OK if |len| was read. */ +static CURLcode +socket_read(struct Curl_easy *data, int sockindex, void *to, size_t len) +{ + char *to_p = to; + CURLcode result; + ssize_t nread = 0; + + while(len > 0) { + result = Curl_conn_recv(data, sockindex, to_p, len, &nread); + if(nread > 0) { + len -= nread; + to_p += nread; + } + else { + if(result == CURLE_AGAIN) + continue; + return result; + } + } + return CURLE_OK; +} + + +/* Write |len| bytes from the buffer |to| to the socket |fd|. Return a + CURLcode saying whether an error occurred or CURLE_OK if |len| was + written. */ +static CURLcode +socket_write(struct Curl_easy *data, int sockindex, const void *to, + size_t len) +{ + const char *to_p = to; + CURLcode result; + size_t written; + + while(len > 0) { + result = Curl_conn_send(data, sockindex, to_p, len, &written); + if(!result && written > 0) { + len -= written; + to_p += written; + } + else { + if(result == CURLE_AGAIN) + continue; + return result; + } + } + return CURLE_OK; +} + +static CURLcode read_data(struct Curl_easy *data, int sockindex, + struct krb5buffer *buf) +{ + struct connectdata *conn = data->conn; + int len; + CURLcode result; + int nread; + + result = socket_read(data, sockindex, &len, sizeof(len)); + if(result) + return result; + + if(len) { + len = ntohl(len); + if(len > CURL_MAX_INPUT_LENGTH) + return CURLE_TOO_LARGE; + + Curl_dyn_reset(&buf->buf); + } + else + return CURLE_RECV_ERROR; + + do { + char buffer[1024]; + nread = CURLMIN(len, (int)sizeof(buffer)); + result = socket_read(data, sockindex, buffer, nread); + if(result) + return result; + result = Curl_dyn_addn(&buf->buf, buffer, nread); + if(result) + return result; + len -= nread; + } while(len); + /* this decodes the dynbuf *in place* */ + nread = conn->mech->decode(conn->app_data, + Curl_dyn_ptr(&buf->buf), + len, conn->data_prot, conn); + if(nread < 0) + return CURLE_RECV_ERROR; + Curl_dyn_setlen(&buf->buf, nread); + buf->index = 0; + return CURLE_OK; +} + +static size_t +buffer_read(struct krb5buffer *buf, void *data, size_t len) +{ + size_t size = Curl_dyn_len(&buf->buf); + if(size - buf->index < len) + len = size - buf->index; + memcpy(data, Curl_dyn_ptr(&buf->buf) + buf->index, len); + buf->index += len; + return len; +} + +/* Matches Curl_recv signature */ +static ssize_t sec_recv(struct Curl_easy *data, int sockindex, + char *buffer, size_t len, CURLcode *err) +{ + size_t bytes_read; + size_t total_read = 0; + struct connectdata *conn = data->conn; + + *err = CURLE_OK; + + /* Handle clear text response. */ + if(conn->sec_complete == 0 || conn->data_prot == PROT_CLEAR) { + ssize_t nread; + *err = Curl_conn_recv(data, sockindex, buffer, len, &nread); + return nread; + } + + if(conn->in_buffer.eof_flag) { + conn->in_buffer.eof_flag = 0; + return 0; + } + + bytes_read = buffer_read(&conn->in_buffer, buffer, len); + len -= bytes_read; + total_read += bytes_read; + buffer += bytes_read; + + while(len > 0) { + if(read_data(data, sockindex, &conn->in_buffer)) + return -1; + if(Curl_dyn_len(&conn->in_buffer.buf) == 0) { + if(bytes_read > 0) + conn->in_buffer.eof_flag = 1; + return bytes_read; + } + bytes_read = buffer_read(&conn->in_buffer, buffer, len); + len -= bytes_read; + total_read += bytes_read; + buffer += bytes_read; + } + return total_read; +} + +/* Send |length| bytes from |from| to the |fd| socket taking care of encoding + and negotiating with the server. |from| can be NULL. */ +static void do_sec_send(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t fd, const char *from, int length) +{ + int bytes, htonl_bytes; /* 32-bit integers for htonl */ + char *buffer = NULL; + char *cmd_buffer; + size_t cmd_size = 0; + CURLcode error; + enum protection_level prot_level = conn->data_prot; + bool iscmd = (prot_level == PROT_CMD)?TRUE:FALSE; + + DEBUGASSERT(prot_level > PROT_NONE && prot_level < PROT_LAST); + + if(iscmd) { + if(!strncmp(from, "PASS ", 5) || !strncmp(from, "ACCT ", 5)) + prot_level = PROT_PRIVATE; + else + prot_level = conn->command_prot; + } + bytes = conn->mech->encode(conn->app_data, from, length, prot_level, + (void **)&buffer); + if(!buffer || bytes <= 0) + return; /* error */ + + if(iscmd) { + error = Curl_base64_encode(buffer, curlx_sitouz(bytes), + &cmd_buffer, &cmd_size); + if(error) { + free(buffer); + return; /* error */ + } + if(cmd_size > 0) { + static const char *enc = "ENC "; + static const char *mic = "MIC "; + if(prot_level == PROT_PRIVATE) + socket_write(data, fd, enc, 4); + else + socket_write(data, fd, mic, 4); + + socket_write(data, fd, cmd_buffer, cmd_size); + socket_write(data, fd, "\r\n", 2); + infof(data, "Send: %s%s", prot_level == PROT_PRIVATE?enc:mic, + cmd_buffer); + free(cmd_buffer); + } + } + else { + htonl_bytes = htonl(bytes); + socket_write(data, fd, &htonl_bytes, sizeof(htonl_bytes)); + socket_write(data, fd, buffer, curlx_sitouz(bytes)); + } + free(buffer); +} + +static ssize_t sec_write(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t fd, const char *buffer, size_t length) +{ + ssize_t tx = 0, len = conn->buffer_size; + + if(len <= 0) + len = length; + while(length) { + if(length < (size_t)len) + len = length; + + do_sec_send(data, conn, fd, buffer, curlx_sztosi(len)); + length -= len; + buffer += len; + tx += len; + } + return tx; +} + +/* Matches Curl_send signature */ +static ssize_t sec_send(struct Curl_easy *data, int sockindex, + const void *buffer, size_t len, CURLcode *err) +{ + struct connectdata *conn = data->conn; + curl_socket_t fd = conn->sock[sockindex]; + *err = CURLE_OK; + return sec_write(data, conn, fd, buffer, len); +} + +int Curl_sec_read_msg(struct Curl_easy *data, struct connectdata *conn, + char *buffer, enum protection_level level) +{ + /* decoded_len should be size_t or ssize_t but conn->mech->decode returns an + int */ + int decoded_len; + char *buf; + int ret_code = 0; + size_t decoded_sz = 0; + CURLcode error; + + (void) data; + + if(!conn->mech) + /* not initialized, return error */ + return -1; + + DEBUGASSERT(level > PROT_NONE && level < PROT_LAST); + + error = Curl_base64_decode(buffer + 4, (unsigned char **)&buf, &decoded_sz); + if(error || decoded_sz == 0) + return -1; + + if(decoded_sz > (size_t)INT_MAX) { + free(buf); + return -1; + } + decoded_len = curlx_uztosi(decoded_sz); + + decoded_len = conn->mech->decode(conn->app_data, buf, decoded_len, + level, conn); + if(decoded_len <= 0) { + free(buf); + return -1; + } + + { + buf[decoded_len] = '\n'; + Curl_debug(data, CURLINFO_HEADER_IN, buf, decoded_len + 1); + } + + buf[decoded_len] = '\0'; + if(decoded_len <= 3) + /* suspiciously short */ + return 0; + + if(buf[3] != '-') + ret_code = atoi(buf); + + if(buf[decoded_len - 1] == '\n') + buf[decoded_len - 1] = '\0'; + strcpy(buffer, buf); + free(buf); + return ret_code; +} + +static int sec_set_protection_level(struct Curl_easy *data) +{ + int code; + struct connectdata *conn = data->conn; + unsigned char level = conn->request_data_prot; + + DEBUGASSERT(level > PROT_NONE && level < PROT_LAST); + + if(!conn->sec_complete) { + infof(data, "Trying to change the protection level after the" + " completion of the data exchange."); + return -1; + } + + /* Bail out if we try to set up the same level */ + if(conn->data_prot == level) + return 0; + + if(level) { + char *pbsz; + unsigned int buffer_size = 1 << 20; /* 1048576 */ + struct pingpong *pp = &conn->proto.ftpc.pp; + char *line; + + code = ftp_send_command(data, "PBSZ %u", buffer_size); + if(code < 0) + return -1; + + if(code/100 != 2) { + failf(data, "Failed to set the protection's buffer size."); + return -1; + } + conn->buffer_size = buffer_size; + + line = Curl_dyn_ptr(&pp->recvbuf); + pbsz = strstr(line, "PBSZ="); + if(pbsz) { + /* stick to default value if the check fails */ + if(ISDIGIT(pbsz[5])) + buffer_size = atoi(&pbsz[5]); + if(buffer_size < conn->buffer_size) + conn->buffer_size = buffer_size; + } + } + + /* Now try to negotiate the protection level. */ + code = ftp_send_command(data, "PROT %c", level_to_char(level)); + + if(code < 0) + return -1; + + if(code/100 != 2) { + failf(data, "Failed to set the protection level."); + return -1; + } + + conn->data_prot = level; + if(level == PROT_PRIVATE) + conn->command_prot = level; + + return 0; +} + +int +Curl_sec_request_prot(struct connectdata *conn, const char *level) +{ + unsigned char l = name_to_level(level); + if(l == PROT_NONE) + return -1; + DEBUGASSERT(l > PROT_NONE && l < PROT_LAST); + conn->request_data_prot = l; + return 0; +} + +static CURLcode choose_mech(struct Curl_easy *data, struct connectdata *conn) +{ + int ret; + void *tmp_allocation; + const struct Curl_sec_client_mech *mech = &Curl_krb5_client_mech; + + tmp_allocation = realloc(conn->app_data, mech->size); + if(!tmp_allocation) { + failf(data, "Failed realloc of size %zu", mech->size); + mech = NULL; + return CURLE_OUT_OF_MEMORY; + } + conn->app_data = tmp_allocation; + + if(mech->init) { + ret = mech->init(conn->app_data); + if(ret) { + infof(data, "Failed initialization for %s. Skipping it.", + mech->name); + return CURLE_FAILED_INIT; + } + Curl_dyn_init(&conn->in_buffer.buf, CURL_MAX_INPUT_LENGTH); + } + + infof(data, "Trying mechanism %s...", mech->name); + ret = ftp_send_command(data, "AUTH %s", mech->name); + if(ret < 0) + return CURLE_COULDNT_CONNECT; + + if(ret/100 != 3) { + switch(ret) { + case 504: + infof(data, "Mechanism %s is not supported by the server (server " + "returned ftp code: 504).", mech->name); + break; + case 534: + infof(data, "Mechanism %s was rejected by the server (server returned " + "ftp code: 534).", mech->name); + break; + default: + if(ret/100 == 5) { + infof(data, "server does not support the security extensions"); + return CURLE_USE_SSL_FAILED; + } + break; + } + return CURLE_LOGIN_DENIED; + } + + /* Authenticate */ + ret = mech->auth(conn->app_data, data, conn); + + if(ret != AUTH_CONTINUE) { + if(ret != AUTH_OK) { + /* Mechanism has dumped the error to stderr, don't error here. */ + return CURLE_USE_SSL_FAILED; + } + DEBUGASSERT(ret == AUTH_OK); + + conn->mech = mech; + conn->sec_complete = 1; + conn->recv[FIRSTSOCKET] = sec_recv; + conn->send[FIRSTSOCKET] = sec_send; + conn->recv[SECONDARYSOCKET] = sec_recv; + conn->send[SECONDARYSOCKET] = sec_send; + conn->command_prot = PROT_SAFE; + /* Set the requested protection level */ + /* BLOCKING */ + (void)sec_set_protection_level(data); + } + + return CURLE_OK; +} + +CURLcode +Curl_sec_login(struct Curl_easy *data, struct connectdata *conn) +{ + return choose_mech(data, conn); +} + + +void +Curl_sec_end(struct connectdata *conn) +{ + if(conn->mech && conn->mech->end) + conn->mech->end(conn->app_data); + Curl_safefree(conn->app_data); + Curl_dyn_free(&conn->in_buffer.buf); + conn->in_buffer.index = 0; + conn->in_buffer.eof_flag = 0; + conn->sec_complete = 0; + conn->data_prot = PROT_CLEAR; + conn->mech = NULL; +} + +#endif /* HAVE_GSSAPI && !CURL_DISABLE_FTP */ diff --git a/third_party/curl/lib/ldap.c b/third_party/curl/lib/ldap.c new file mode 100644 index 0000000..678b4d5 --- /dev/null +++ b/third_party/curl/lib/ldap.c @@ -0,0 +1,1112 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_LDAP) && !defined(USE_OPENLDAP) + +/* + * Notice that USE_OPENLDAP is only a source code selection switch. When + * libcurl is built with USE_OPENLDAP defined the libcurl source code that + * gets compiled is the code from openldap.c, otherwise the code that gets + * compiled is the code from ldap.c. + * + * When USE_OPENLDAP is defined a recent version of the OpenLDAP library + * might be required for compilation and runtime. In order to use ancient + * OpenLDAP library versions, USE_OPENLDAP shall not be defined. + */ + +/* Wincrypt must be included before anything that could include OpenSSL. */ +#if defined(USE_WIN32_CRYPTO) +#include +/* Undefine wincrypt conflicting symbols for BoringSSL. */ +#undef X509_NAME +#undef X509_EXTENSIONS +#undef PKCS7_ISSUER_AND_SERIAL +#undef PKCS7_SIGNER_INFO +#undef OCSP_REQUEST +#undef OCSP_RESPONSE +#endif + +#ifdef USE_WIN32_LDAP /* Use Windows LDAP implementation. */ +# ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable: 4201) +# endif +# include /* for [P]UNICODE_STRING */ +# ifdef _MSC_VER +# pragma warning(pop) +# endif +# include +# ifndef LDAP_VENDOR_NAME +# error Your Platform SDK is NOT sufficient for LDAP support! \ + Update your Platform SDK, or disable LDAP support! +# else +# include +# endif +#else +# define LDAP_DEPRECATED 1 /* Be sure ldap_init() is defined. */ +# ifdef HAVE_LBER_H +# include +# endif +# include +# if (defined(HAVE_LDAP_SSL) && defined(HAVE_LDAP_SSL_H)) +# include +# endif /* HAVE_LDAP_SSL && HAVE_LDAP_SSL_H */ +#endif + +#include "urldata.h" +#include +#include "sendf.h" +#include "escape.h" +#include "progress.h" +#include "transfer.h" +#include "strcase.h" +#include "strtok.h" +#include "curl_ldap.h" +#include "curl_multibyte.h" +#include "curl_base64.h" +#include "connect.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#ifndef HAVE_LDAP_URL_PARSE + +/* Use our own implementation. */ + +struct ldap_urldesc { + char *lud_host; + int lud_port; +#if defined(USE_WIN32_LDAP) + TCHAR *lud_dn; + TCHAR **lud_attrs; +#else + char *lud_dn; + char **lud_attrs; +#endif + int lud_scope; +#if defined(USE_WIN32_LDAP) + TCHAR *lud_filter; +#else + char *lud_filter; +#endif + char **lud_exts; + size_t lud_attrs_dups; /* how many were dup'ed, this field is not in the + "real" struct so can only be used in code + without HAVE_LDAP_URL_PARSE defined */ +}; + +#undef LDAPURLDesc +#define LDAPURLDesc struct ldap_urldesc + +static int _ldap_url_parse(struct Curl_easy *data, + const struct connectdata *conn, + LDAPURLDesc **ludp); +static void _ldap_free_urldesc(LDAPURLDesc *ludp); + +#undef ldap_free_urldesc +#define ldap_free_urldesc _ldap_free_urldesc +#endif + +#ifdef DEBUG_LDAP + #define LDAP_TRACE(x) do { \ + _ldap_trace("%u: ", __LINE__); \ + _ldap_trace x; \ + } while(0) + + static void _ldap_trace(const char *fmt, ...) CURL_PRINTF(1, 2); +#else + #define LDAP_TRACE(x) Curl_nop_stmt +#endif + +#if defined(USE_WIN32_LDAP) && defined(ldap_err2string) +/* Use ansi error strings in UNICODE builds */ +#undef ldap_err2string +#define ldap_err2string ldap_err2stringA +#endif + +#if defined(USE_WIN32_LDAP) && defined(_MSC_VER) && (_MSC_VER <= 1600) +/* Workaround for warning: + 'type cast' : conversion from 'int' to 'void *' of greater size */ +#undef LDAP_OPT_ON +#undef LDAP_OPT_OFF +#define LDAP_OPT_ON ((void *)(size_t)1) +#define LDAP_OPT_OFF ((void *)(size_t)0) +#endif + +static CURLcode ldap_do(struct Curl_easy *data, bool *done); + +/* + * LDAP protocol handler. + */ + +const struct Curl_handler Curl_handler_ldap = { + "ldap", /* scheme */ + ZERO_NULL, /* setup_connection */ + ldap_do, /* do_it */ + ZERO_NULL, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_LDAP, /* defport */ + CURLPROTO_LDAP, /* protocol */ + CURLPROTO_LDAP, /* family */ + PROTOPT_NONE /* flags */ +}; + +#ifdef HAVE_LDAP_SSL +/* + * LDAPS protocol handler. + */ + +const struct Curl_handler Curl_handler_ldaps = { + "ldaps", /* scheme */ + ZERO_NULL, /* setup_connection */ + ldap_do, /* do_it */ + ZERO_NULL, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_LDAPS, /* defport */ + CURLPROTO_LDAPS, /* protocol */ + CURLPROTO_LDAP, /* family */ + PROTOPT_SSL /* flags */ +}; +#endif + +#if defined(USE_WIN32_LDAP) + +#if defined(USE_WINDOWS_SSPI) +static int ldap_win_bind_auth(LDAP *server, const char *user, + const char *passwd, unsigned long authflags) +{ + ULONG method = 0; + SEC_WINNT_AUTH_IDENTITY cred; + int rc = LDAP_AUTH_METHOD_NOT_SUPPORTED; + + memset(&cred, 0, sizeof(cred)); + +#if defined(USE_SPNEGO) + if(authflags & CURLAUTH_NEGOTIATE) { + method = LDAP_AUTH_NEGOTIATE; + } + else +#endif +#if defined(USE_NTLM) + if(authflags & CURLAUTH_NTLM) { + method = LDAP_AUTH_NTLM; + } + else +#endif +#if !defined(CURL_DISABLE_DIGEST_AUTH) + if(authflags & CURLAUTH_DIGEST) { + method = LDAP_AUTH_DIGEST; + } + else +#endif + { + /* required anyway if one of upper preprocessor definitions enabled */ + } + + if(method && user && passwd) { + rc = Curl_create_sspi_identity(user, passwd, &cred); + if(!rc) { + rc = ldap_bind_s(server, NULL, (TCHAR *)&cred, method); + Curl_sspi_free_identity(&cred); + } + } + else { + /* proceed with current user credentials */ + method = LDAP_AUTH_NEGOTIATE; + rc = ldap_bind_s(server, NULL, NULL, method); + } + return rc; +} +#endif /* #if defined(USE_WINDOWS_SSPI) */ + +static int ldap_win_bind(struct Curl_easy *data, LDAP *server, + const char *user, const char *passwd) +{ + int rc = LDAP_INVALID_CREDENTIALS; + + PTCHAR inuser = NULL; + PTCHAR inpass = NULL; + + if(user && passwd && (data->set.httpauth & CURLAUTH_BASIC)) { + inuser = curlx_convert_UTF8_to_tchar((char *) user); + inpass = curlx_convert_UTF8_to_tchar((char *) passwd); + + rc = ldap_simple_bind_s(server, inuser, inpass); + + curlx_unicodefree(inuser); + curlx_unicodefree(inpass); + } +#if defined(USE_WINDOWS_SSPI) + else { + rc = ldap_win_bind_auth(server, user, passwd, data->set.httpauth); + } +#endif + + return rc; +} +#endif /* #if defined(USE_WIN32_LDAP) */ + +#if defined(USE_WIN32_LDAP) +#define FREE_ON_WINLDAP(x) curlx_unicodefree(x) +#else +#define FREE_ON_WINLDAP(x) +#endif + + +static CURLcode ldap_do(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + int rc = 0; + LDAP *server = NULL; + LDAPURLDesc *ludp = NULL; + LDAPMessage *ldapmsg = NULL; + LDAPMessage *entryIterator; + int num = 0; + struct connectdata *conn = data->conn; + int ldap_proto = LDAP_VERSION3; + int ldap_ssl = 0; + char *val_b64 = NULL; + size_t val_b64_sz = 0; +#ifdef LDAP_OPT_NETWORK_TIMEOUT + struct timeval ldap_timeout = {10, 0}; /* 10 sec connection/search timeout */ +#endif +#if defined(USE_WIN32_LDAP) + TCHAR *host = NULL; +#else + char *host = NULL; +#endif + char *user = NULL; + char *passwd = NULL; + + *done = TRUE; /* unconditionally */ + infof(data, "LDAP local: LDAP Vendor = %s ; LDAP Version = %d", + LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION); + infof(data, "LDAP local: %s", data->state.url); + +#ifdef HAVE_LDAP_URL_PARSE + rc = ldap_url_parse(data->state.url, &ludp); +#else + rc = _ldap_url_parse(data, conn, &ludp); +#endif + if(rc) { + failf(data, "Bad LDAP URL: %s", ldap_err2string(rc)); + result = CURLE_URL_MALFORMAT; + goto quit; + } + + /* Get the URL scheme (either ldap or ldaps) */ + if(conn->given->flags & PROTOPT_SSL) + ldap_ssl = 1; + infof(data, "LDAP local: trying to establish %s connection", + ldap_ssl ? "encrypted" : "cleartext"); + +#if defined(USE_WIN32_LDAP) + host = curlx_convert_UTF8_to_tchar(conn->host.name); + if(!host) { + result = CURLE_OUT_OF_MEMORY; + + goto quit; + } +#else + host = conn->host.name; +#endif + + if(data->state.aptr.user) { + user = conn->user; + passwd = conn->passwd; + } + +#ifdef LDAP_OPT_NETWORK_TIMEOUT + ldap_set_option(NULL, LDAP_OPT_NETWORK_TIMEOUT, &ldap_timeout); +#endif + ldap_set_option(NULL, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); + + if(ldap_ssl) { +#ifdef HAVE_LDAP_SSL +#ifdef USE_WIN32_LDAP + /* Win32 LDAP SDK doesn't support insecure mode without CA! */ + server = ldap_sslinit(host, conn->primary.remote_port, 1); + ldap_set_option(server, LDAP_OPT_SSL, LDAP_OPT_ON); +#else + int ldap_option; + char *ldap_ca = conn->ssl_config.CAfile; +#if defined(CURL_HAS_NOVELL_LDAPSDK) + rc = ldapssl_client_init(NULL, NULL); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ldapssl_client_init %s", ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + if(conn->ssl_config.verifypeer) { + /* Novell SDK supports DER or BASE64 files. */ + int cert_type = LDAPSSL_CERT_FILETYPE_B64; + if((data->set.ssl.cert_type) && + (strcasecompare(data->set.ssl.cert_type, "DER"))) + cert_type = LDAPSSL_CERT_FILETYPE_DER; + if(!ldap_ca) { + failf(data, "LDAP local: ERROR %s CA cert not set", + (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM")); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + infof(data, "LDAP local: using %s CA cert '%s'", + (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"), + ldap_ca); + rc = ldapssl_add_trusted_cert(ldap_ca, cert_type); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ERROR setting %s CA cert: %s", + (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"), + ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + ldap_option = LDAPSSL_VERIFY_SERVER; + } + else + ldap_option = LDAPSSL_VERIFY_NONE; + rc = ldapssl_set_verify_mode(ldap_option); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ERROR setting cert verify mode: %s", + ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + server = ldapssl_init(host, conn->primary.remote_port, 1); + if(!server) { + failf(data, "LDAP local: Cannot connect to %s:%u", + conn->host.dispname, conn->primary.remote_port); + result = CURLE_COULDNT_CONNECT; + goto quit; + } +#elif defined(LDAP_OPT_X_TLS) + if(conn->ssl_config.verifypeer) { + /* OpenLDAP SDK supports BASE64 files. */ + if((data->set.ssl.cert_type) && + (!strcasecompare(data->set.ssl.cert_type, "PEM"))) { + failf(data, "LDAP local: ERROR OpenLDAP only supports PEM cert-type"); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + if(!ldap_ca) { + failf(data, "LDAP local: ERROR PEM CA cert not set"); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + infof(data, "LDAP local: using PEM CA cert: %s", ldap_ca); + rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, ldap_ca); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ERROR setting PEM CA cert: %s", + ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + ldap_option = LDAP_OPT_X_TLS_DEMAND; + } + else + ldap_option = LDAP_OPT_X_TLS_NEVER; + + rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &ldap_option); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ERROR setting cert verify mode: %s", + ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + server = ldap_init(host, conn->primary.remote_port); + if(!server) { + failf(data, "LDAP local: Cannot connect to %s:%u", + conn->host.dispname, conn->primary.remote_port); + result = CURLE_COULDNT_CONNECT; + goto quit; + } + ldap_option = LDAP_OPT_X_TLS_HARD; + rc = ldap_set_option(server, LDAP_OPT_X_TLS, &ldap_option); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ERROR setting SSL/TLS mode: %s", + ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } +/* + rc = ldap_start_tls_s(server, NULL, NULL); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ERROR starting SSL/TLS mode: %s", + ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } +*/ +#else + (void)ldap_option; + (void)ldap_ca; + /* we should probably never come up to here since configure + should check in first place if we can support LDAP SSL/TLS */ + failf(data, "LDAP local: SSL/TLS not supported with this version " + "of the OpenLDAP toolkit\n"); + result = CURLE_SSL_CERTPROBLEM; + goto quit; +#endif +#endif +#endif /* CURL_LDAP_USE_SSL */ + } + else if(data->set.use_ssl > CURLUSESSL_TRY) { + failf(data, "LDAP local: explicit TLS not supported"); + result = CURLE_NOT_BUILT_IN; + goto quit; + } + else { + server = ldap_init(host, conn->primary.remote_port); + if(!server) { + failf(data, "LDAP local: Cannot connect to %s:%u", + conn->host.dispname, conn->primary.remote_port); + result = CURLE_COULDNT_CONNECT; + goto quit; + } + } +#ifdef USE_WIN32_LDAP + ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); + rc = ldap_win_bind(data, server, user, passwd); +#else + rc = ldap_simple_bind_s(server, user, passwd); +#endif + if(!ldap_ssl && rc) { + ldap_proto = LDAP_VERSION2; + ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); +#ifdef USE_WIN32_LDAP + rc = ldap_win_bind(data, server, user, passwd); +#else + rc = ldap_simple_bind_s(server, user, passwd); +#endif + } + if(rc) { +#ifdef USE_WIN32_LDAP + failf(data, "LDAP local: bind via ldap_win_bind %s", + ldap_err2string(rc)); +#else + failf(data, "LDAP local: bind via ldap_simple_bind_s %s", + ldap_err2string(rc)); +#endif + result = CURLE_LDAP_CANNOT_BIND; + goto quit; + } + + Curl_pgrsSetDownloadCounter(data, 0); + rc = ldap_search_s(server, ludp->lud_dn, ludp->lud_scope, + ludp->lud_filter, ludp->lud_attrs, 0, &ldapmsg); + + if(rc && rc != LDAP_SIZELIMIT_EXCEEDED) { + failf(data, "LDAP remote: %s", ldap_err2string(rc)); + result = CURLE_LDAP_SEARCH_FAILED; + goto quit; + } + + num = 0; + for(entryIterator = ldap_first_entry(server, ldapmsg); + entryIterator; + entryIterator = ldap_next_entry(server, entryIterator), num++) { + BerElement *ber = NULL; +#if defined(USE_WIN32_LDAP) + TCHAR *attribute; +#else + char *attribute; +#endif + int i; + + /* Get the DN and write it to the client */ + { + char *name; + size_t name_len; +#if defined(USE_WIN32_LDAP) + TCHAR *dn = ldap_get_dn(server, entryIterator); + name = curlx_convert_tchar_to_UTF8(dn); + if(!name) { + ldap_memfree(dn); + + result = CURLE_OUT_OF_MEMORY; + + goto quit; + } +#else + char *dn = name = ldap_get_dn(server, entryIterator); +#endif + name_len = strlen(name); + + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"DN: ", 4); + if(result) { + FREE_ON_WINLDAP(name); + ldap_memfree(dn); + goto quit; + } + + result = Curl_client_write(data, CLIENTWRITE_BODY, name, name_len); + if(result) { + FREE_ON_WINLDAP(name); + ldap_memfree(dn); + goto quit; + } + + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1); + if(result) { + FREE_ON_WINLDAP(name); + ldap_memfree(dn); + + goto quit; + } + + FREE_ON_WINLDAP(name); + ldap_memfree(dn); + } + + /* Get the attributes and write them to the client */ + for(attribute = ldap_first_attribute(server, entryIterator, &ber); + attribute; + attribute = ldap_next_attribute(server, entryIterator, ber)) { + BerValue **vals; + size_t attr_len; +#if defined(USE_WIN32_LDAP) + char *attr = curlx_convert_tchar_to_UTF8(attribute); + if(!attr) { + if(ber) + ber_free(ber, 0); + + result = CURLE_OUT_OF_MEMORY; + + goto quit; + } +#else + char *attr = attribute; +#endif + attr_len = strlen(attr); + + vals = ldap_get_values_len(server, entryIterator, attribute); + if(vals) { + for(i = 0; (vals[i] != NULL); i++) { + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\t", 1); + if(result) { + ldap_value_free_len(vals); + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + if(ber) + ber_free(ber, 0); + + goto quit; + } + + result = Curl_client_write(data, CLIENTWRITE_BODY, attr, attr_len); + if(result) { + ldap_value_free_len(vals); + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + if(ber) + ber_free(ber, 0); + + goto quit; + } + + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)": ", 2); + if(result) { + ldap_value_free_len(vals); + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + if(ber) + ber_free(ber, 0); + + goto quit; + } + + if((attr_len > 7) && + (strcmp(";binary", attr + (attr_len - 7)) == 0)) { + /* Binary attribute, encode to base64. */ + result = Curl_base64_encode(vals[i]->bv_val, vals[i]->bv_len, + &val_b64, &val_b64_sz); + if(result) { + ldap_value_free_len(vals); + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + if(ber) + ber_free(ber, 0); + + goto quit; + } + + if(val_b64_sz > 0) { + result = Curl_client_write(data, CLIENTWRITE_BODY, val_b64, + val_b64_sz); + free(val_b64); + if(result) { + ldap_value_free_len(vals); + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + if(ber) + ber_free(ber, 0); + + goto quit; + } + } + } + else { + result = Curl_client_write(data, CLIENTWRITE_BODY, vals[i]->bv_val, + vals[i]->bv_len); + if(result) { + ldap_value_free_len(vals); + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + if(ber) + ber_free(ber, 0); + + goto quit; + } + } + + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1); + if(result) { + ldap_value_free_len(vals); + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + if(ber) + ber_free(ber, 0); + + goto quit; + } + } + + /* Free memory used to store values */ + ldap_value_free_len(vals); + } + + /* Free the attribute as we are done with it */ + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1); + if(result) + goto quit; + } + + if(ber) + ber_free(ber, 0); + } + +quit: + if(ldapmsg) { + ldap_msgfree(ldapmsg); + LDAP_TRACE(("Received %d entries\n", num)); + } + if(rc == LDAP_SIZELIMIT_EXCEEDED) + infof(data, "There are more than %d entries", num); + if(ludp) + ldap_free_urldesc(ludp); + if(server) + ldap_unbind_s(server); +#if defined(HAVE_LDAP_SSL) && defined(CURL_HAS_NOVELL_LDAPSDK) + if(ldap_ssl) + ldapssl_client_deinit(); +#endif /* HAVE_LDAP_SSL && CURL_HAS_NOVELL_LDAPSDK */ + + FREE_ON_WINLDAP(host); + + /* no data to transfer */ + Curl_xfer_setup(data, -1, -1, FALSE, -1); + connclose(conn, "LDAP connection always disable reuse"); + + return result; +} + +#ifdef DEBUG_LDAP +static void _ldap_trace(const char *fmt, ...) +{ + static int do_trace = -1; + va_list args; + + if(do_trace == -1) { + const char *env = getenv("CURL_TRACE"); + do_trace = (env && strtol(env, NULL, 10) > 0); + } + if(!do_trace) + return; + + va_start(args, fmt); + vfprintf(stderr, fmt, args); + va_end(args); +} +#endif + +#ifndef HAVE_LDAP_URL_PARSE + +/* + * Return scope-value for a scope-string. + */ +static int str2scope(const char *p) +{ + if(strcasecompare(p, "one")) + return LDAP_SCOPE_ONELEVEL; + if(strcasecompare(p, "onetree")) + return LDAP_SCOPE_ONELEVEL; + if(strcasecompare(p, "base")) + return LDAP_SCOPE_BASE; + if(strcasecompare(p, "sub")) + return LDAP_SCOPE_SUBTREE; + if(strcasecompare(p, "subtree")) + return LDAP_SCOPE_SUBTREE; + return (-1); +} + +/* + * Split 'str' into strings separated by commas. + * Note: out[] points into 'str'. + */ +static bool split_str(char *str, char ***out, size_t *count) +{ + char **res; + char *lasts; + char *s; + size_t i; + size_t items = 1; + + s = strchr(str, ','); + while(s) { + items++; + s = strchr(++s, ','); + } + + res = calloc(items, sizeof(char *)); + if(!res) + return FALSE; + + for(i = 0, s = strtok_r(str, ",", &lasts); s && i < items; + s = strtok_r(NULL, ",", &lasts), i++) + res[i] = s; + + *out = res; + *count = items; + + return TRUE; +} + +/* + * Break apart the pieces of an LDAP URL. + * Syntax: + * ldap://:/???? + * + * already known from 'conn->host.name'. + * already known from 'conn->remote_port'. + * extract the rest from 'data->state.path+1'. All fields are optional. + * e.g. + * ldap://:/??? + * yields ludp->lud_dn = "". + * + * Defined in RFC4516 section 2. + */ +static int _ldap_url_parse2(struct Curl_easy *data, + const struct connectdata *conn, LDAPURLDesc *ludp) +{ + int rc = LDAP_SUCCESS; + char *p; + char *path; + char *q = NULL; + char *query = NULL; + size_t i; + + if(!data || + !data->state.up.path || + data->state.up.path[0] != '/' || + !strncasecompare("LDAP", data->state.up.scheme, 4)) + return LDAP_INVALID_SYNTAX; + + ludp->lud_scope = LDAP_SCOPE_BASE; + ludp->lud_port = conn->remote_port; + ludp->lud_host = conn->host.name; + + /* Duplicate the path */ + p = path = strdup(data->state.up.path + 1); + if(!path) + return LDAP_NO_MEMORY; + + /* Duplicate the query if present */ + if(data->state.up.query) { + q = query = strdup(data->state.up.query); + if(!query) { + free(path); + return LDAP_NO_MEMORY; + } + } + + /* Parse the DN (Distinguished Name) */ + if(*p) { + char *dn = p; + char *unescaped; + CURLcode result; + + LDAP_TRACE(("DN '%s'\n", dn)); + + /* Unescape the DN */ + result = Curl_urldecode(dn, 0, &unescaped, NULL, REJECT_ZERO); + if(result) { + rc = LDAP_NO_MEMORY; + + goto quit; + } + +#if defined(USE_WIN32_LDAP) + /* Convert the unescaped string to a tchar */ + ludp->lud_dn = curlx_convert_UTF8_to_tchar(unescaped); + + /* Free the unescaped string as we are done with it */ + free(unescaped); + + if(!ludp->lud_dn) { + rc = LDAP_NO_MEMORY; + + goto quit; + } +#else + ludp->lud_dn = unescaped; +#endif + } + + p = q; + if(!p) + goto quit; + + /* Parse the attributes. skip "??" */ + q = strchr(p, '?'); + if(q) + *q++ = '\0'; + + if(*p) { + char **attributes; + size_t count = 0; + + /* Split the string into an array of attributes */ + if(!split_str(p, &attributes, &count)) { + rc = LDAP_NO_MEMORY; + + goto quit; + } + + /* Allocate our array (+1 for the NULL entry) */ +#if defined(USE_WIN32_LDAP) + ludp->lud_attrs = calloc(count + 1, sizeof(TCHAR *)); +#else + ludp->lud_attrs = calloc(count + 1, sizeof(char *)); +#endif + if(!ludp->lud_attrs) { + free(attributes); + + rc = LDAP_NO_MEMORY; + + goto quit; + } + + for(i = 0; i < count; i++) { + char *unescaped; + CURLcode result; + + LDAP_TRACE(("attr[%zu] '%s'\n", i, attributes[i])); + + /* Unescape the attribute */ + result = Curl_urldecode(attributes[i], 0, &unescaped, NULL, + REJECT_ZERO); + if(result) { + free(attributes); + + rc = LDAP_NO_MEMORY; + + goto quit; + } + +#if defined(USE_WIN32_LDAP) + /* Convert the unescaped string to a tchar */ + ludp->lud_attrs[i] = curlx_convert_UTF8_to_tchar(unescaped); + + /* Free the unescaped string as we are done with it */ + free(unescaped); + + if(!ludp->lud_attrs[i]) { + free(attributes); + + rc = LDAP_NO_MEMORY; + + goto quit; + } +#else + ludp->lud_attrs[i] = unescaped; +#endif + + ludp->lud_attrs_dups++; + } + + free(attributes); + } + + p = q; + if(!p) + goto quit; + + /* Parse the scope. skip "??" */ + q = strchr(p, '?'); + if(q) + *q++ = '\0'; + + if(*p) { + ludp->lud_scope = str2scope(p); + if(ludp->lud_scope == -1) { + rc = LDAP_INVALID_SYNTAX; + + goto quit; + } + LDAP_TRACE(("scope %d\n", ludp->lud_scope)); + } + + p = q; + if(!p) + goto quit; + + /* Parse the filter */ + q = strchr(p, '?'); + if(q) + *q++ = '\0'; + + if(*p) { + char *filter = p; + char *unescaped; + CURLcode result; + + LDAP_TRACE(("filter '%s'\n", filter)); + + /* Unescape the filter */ + result = Curl_urldecode(filter, 0, &unescaped, NULL, REJECT_ZERO); + if(result) { + rc = LDAP_NO_MEMORY; + + goto quit; + } + +#if defined(USE_WIN32_LDAP) + /* Convert the unescaped string to a tchar */ + ludp->lud_filter = curlx_convert_UTF8_to_tchar(unescaped); + + /* Free the unescaped string as we are done with it */ + free(unescaped); + + if(!ludp->lud_filter) { + rc = LDAP_NO_MEMORY; + + goto quit; + } +#else + ludp->lud_filter = unescaped; +#endif + } + + p = q; + if(p && !*p) { + rc = LDAP_INVALID_SYNTAX; + + goto quit; + } + +quit: + free(path); + free(query); + + return rc; +} + +static int _ldap_url_parse(struct Curl_easy *data, + const struct connectdata *conn, + LDAPURLDesc **ludpp) +{ + LDAPURLDesc *ludp = calloc(1, sizeof(*ludp)); + int rc; + + *ludpp = NULL; + if(!ludp) + return LDAP_NO_MEMORY; + + rc = _ldap_url_parse2(data, conn, ludp); + if(rc != LDAP_SUCCESS) { + _ldap_free_urldesc(ludp); + ludp = NULL; + } + *ludpp = ludp; + return (rc); +} + +static void _ldap_free_urldesc(LDAPURLDesc *ludp) +{ + if(!ludp) + return; + +#if defined(USE_WIN32_LDAP) + curlx_unicodefree(ludp->lud_dn); + curlx_unicodefree(ludp->lud_filter); +#else + free(ludp->lud_dn); + free(ludp->lud_filter); +#endif + + if(ludp->lud_attrs) { + size_t i; + for(i = 0; i < ludp->lud_attrs_dups; i++) { +#if defined(USE_WIN32_LDAP) + curlx_unicodefree(ludp->lud_attrs[i]); +#else + free(ludp->lud_attrs[i]); +#endif + } + free(ludp->lud_attrs); + } + + free(ludp); +} +#endif /* !HAVE_LDAP_URL_PARSE */ +#endif /* !CURL_DISABLE_LDAP && !USE_OPENLDAP */ diff --git a/third_party/curl/lib/libcurl.rc b/third_party/curl/lib/libcurl.rc new file mode 100644 index 0000000..daa2d62 --- /dev/null +++ b/third_party/curl/lib/libcurl.rc @@ -0,0 +1,65 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include +#include "../include/curl/curlver.h" + +LANGUAGE 0, 0 + +#define RC_VERSION LIBCURL_VERSION_MAJOR, LIBCURL_VERSION_MINOR, LIBCURL_VERSION_PATCH, 0 + +VS_VERSION_INFO VERSIONINFO + FILEVERSION RC_VERSION + PRODUCTVERSION RC_VERSION + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#if defined(DEBUGBUILD) || defined(_DEBUG) + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_DLL + FILESUBTYPE 0L + +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "CompanyName", "The curl library, https://curl.se/\0" + VALUE "FileDescription", "libcurl Shared Library\0" + VALUE "FileVersion", LIBCURL_VERSION "\0" + VALUE "InternalName", "libcurl\0" + VALUE "OriginalFilename", "libcurl.dll\0" + VALUE "ProductName", "The curl library\0" + VALUE "ProductVersion", LIBCURL_VERSION "\0" + VALUE "LegalCopyright", "Copyright (C) " LIBCURL_COPYRIGHT "\0" + VALUE "License", "https://curl.se/docs/copyright.html\0" + END + END + + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END diff --git a/third_party/curl/lib/libcurl.vers.in b/third_party/curl/lib/libcurl.vers.in new file mode 100644 index 0000000..ae978a4 --- /dev/null +++ b/third_party/curl/lib/libcurl.vers.in @@ -0,0 +1,13 @@ +HIDDEN +{ + local: + __*; + _rest*; + _save*; +}; + +CURL_@CURL_LT_SHLIB_VERSIONED_FLAVOUR@4 +{ + global: curl_*; + local: *; +}; diff --git a/third_party/curl/lib/llist.c b/third_party/curl/lib/llist.c new file mode 100644 index 0000000..716f0cd --- /dev/null +++ b/third_party/curl/lib/llist.c @@ -0,0 +1,162 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "llist.h" +#include "curl_memory.h" + +/* this must be the last include file */ +#include "memdebug.h" + +/* + * @unittest: 1300 + */ +void +Curl_llist_init(struct Curl_llist *l, Curl_llist_dtor dtor) +{ + l->size = 0; + l->dtor = dtor; + l->head = NULL; + l->tail = NULL; +} + +/* + * Curl_llist_insert_next() + * + * Inserts a new list element after the given one 'e'. If the given existing + * entry is NULL and the list already has elements, the new one will be + * inserted first in the list. + * + * The 'ne' argument should be a pointer into the object to store. + * + * @unittest: 1300 + */ +void +Curl_llist_insert_next(struct Curl_llist *list, struct Curl_llist_element *e, + const void *p, + struct Curl_llist_element *ne) +{ + ne->ptr = (void *) p; + if(list->size == 0) { + list->head = ne; + list->head->prev = NULL; + list->head->next = NULL; + list->tail = ne; + } + else { + /* if 'e' is NULL here, we insert the new element first in the list */ + ne->next = e?e->next:list->head; + ne->prev = e; + if(!e) { + list->head->prev = ne; + list->head = ne; + } + else if(e->next) { + e->next->prev = ne; + } + else { + list->tail = ne; + } + if(e) + e->next = ne; + } + + ++list->size; +} + +/* + * Curl_llist_append() + * + * Adds a new list element to the end of the list. + * + * The 'ne' argument should be a pointer into the object to store. + * + * @unittest: 1300 + */ +void +Curl_llist_append(struct Curl_llist *list, const void *p, + struct Curl_llist_element *ne) +{ + Curl_llist_insert_next(list, list->tail, p, ne); +} + +/* + * @unittest: 1300 + */ +void +Curl_llist_remove(struct Curl_llist *list, struct Curl_llist_element *e, + void *user) +{ + void *ptr; + if(!e || list->size == 0) + return; + + if(e == list->head) { + list->head = e->next; + + if(!list->head) + list->tail = NULL; + else + e->next->prev = NULL; + } + else { + if(e->prev) + e->prev->next = e->next; + + if(!e->next) + list->tail = e->prev; + else + e->next->prev = e->prev; + } + + ptr = e->ptr; + + e->ptr = NULL; + e->prev = NULL; + e->next = NULL; + + --list->size; + + /* call the dtor() last for when it actually frees the 'e' memory itself */ + if(list->dtor) + list->dtor(user, ptr); +} + +void +Curl_llist_destroy(struct Curl_llist *list, void *user) +{ + if(list) { + while(list->size > 0) + Curl_llist_remove(list, list->tail, user); + } +} + +size_t +Curl_llist_count(struct Curl_llist *list) +{ + return list->size; +} diff --git a/third_party/curl/lib/llist.h b/third_party/curl/lib/llist.h new file mode 100644 index 0000000..d75582f --- /dev/null +++ b/third_party/curl/lib/llist.h @@ -0,0 +1,54 @@ +#ifndef HEADER_CURL_LLIST_H +#define HEADER_CURL_LLIST_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include + +typedef void (*Curl_llist_dtor)(void *, void *); + +struct Curl_llist_element { + void *ptr; + struct Curl_llist_element *prev; + struct Curl_llist_element *next; +}; + +struct Curl_llist { + struct Curl_llist_element *head; + struct Curl_llist_element *tail; + Curl_llist_dtor dtor; + size_t size; +}; + +void Curl_llist_init(struct Curl_llist *, Curl_llist_dtor); +void Curl_llist_insert_next(struct Curl_llist *, struct Curl_llist_element *, + const void *, struct Curl_llist_element *node); +void Curl_llist_append(struct Curl_llist *, + const void *, struct Curl_llist_element *node); +void Curl_llist_remove(struct Curl_llist *, struct Curl_llist_element *, + void *); +size_t Curl_llist_count(struct Curl_llist *); +void Curl_llist_destroy(struct Curl_llist *, void *); +#endif /* HEADER_CURL_LLIST_H */ diff --git a/third_party/curl/lib/macos.c b/third_party/curl/lib/macos.c new file mode 100644 index 0000000..9e8e76e --- /dev/null +++ b/third_party/curl/lib/macos.c @@ -0,0 +1,55 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef CURL_MACOS_CALL_COPYPROXIES + +#include + +#include "macos.h" + +#include + +CURLcode Curl_macos_init(void) +{ + { + /* + * The automagic conversion from IPv4 literals to IPv6 literals only + * works if the SCDynamicStoreCopyProxies system function gets called + * first. As Curl currently doesn't support system-wide HTTP proxies, we + * therefore don't use any value this function might return. + * + * This function is only available on macOS and is not needed for + * IPv4-only builds, hence the conditions for defining + * CURL_MACOS_CALL_COPYPROXIES in curl_setup.h. + */ + CFDictionaryRef dict = SCDynamicStoreCopyProxies(NULL); + if(dict) + CFRelease(dict); + } + return CURLE_OK; +} + +#endif diff --git a/third_party/curl/lib/macos.h b/third_party/curl/lib/macos.h new file mode 100644 index 0000000..637860e --- /dev/null +++ b/third_party/curl/lib/macos.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_MACOS_H +#define HEADER_CURL_MACOS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef CURL_MACOS_CALL_COPYPROXIES + +CURLcode Curl_macos_init(void); + +#else + +#define Curl_macos_init() CURLE_OK + +#endif + +#endif /* HEADER_CURL_MACOS_H */ diff --git a/third_party/curl/lib/md4.c b/third_party/curl/lib/md4.c new file mode 100644 index 0000000..db00281 --- /dev/null +++ b/third_party/curl/lib/md4.c @@ -0,0 +1,526 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_CURL_NTLM_CORE) + +#include + +#include "strdup.h" +#include "curl_md4.h" +#include "warnless.h" + +#ifdef USE_OPENSSL +#include +#if (OPENSSL_VERSION_NUMBER >= 0x30000000L) && !defined(USE_AMISSL) +/* OpenSSL 3.0.0 marks the MD4 functions as deprecated */ +#define OPENSSL_NO_MD4 +#endif +#endif /* USE_OPENSSL */ + +#ifdef USE_WOLFSSL +#include +#define VOID_MD4_INIT +#ifdef NO_MD4 +#define WOLFSSL_NO_MD4 +#endif +#endif + +#ifdef USE_MBEDTLS +#include +#if MBEDTLS_VERSION_NUMBER >= 0x03000000 +#include +#else +#include +#endif +#if(MBEDTLS_VERSION_NUMBER >= 0x02070000) && \ + (MBEDTLS_VERSION_NUMBER < 0x03000000) + #define HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS +#endif +#endif /* USE_MBEDTLS */ + +#if defined(USE_GNUTLS) +#include +/* When OpenSSL or wolfSSL is available, we use their MD4 functions. */ +#elif defined(USE_WOLFSSL) && !defined(WOLFSSL_NO_MD4) +#include +#elif defined(USE_OPENSSL) && !defined(OPENSSL_NO_MD4) +#include +#elif (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \ + (__MAC_OS_X_VERSION_MAX_ALLOWED >= 1040) && \ + defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && \ + (__MAC_OS_X_VERSION_MIN_REQUIRED < 101500)) || \ + (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \ + (__IPHONE_OS_VERSION_MAX_ALLOWED >= 20000) && \ + defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && \ + (__IPHONE_OS_VERSION_MIN_REQUIRED < 130000)) +#define AN_APPLE_OS +#include +#elif defined(USE_WIN32_CRYPTO) +#include +#elif(defined(USE_MBEDTLS) && defined(MBEDTLS_MD4_C)) +#include +#endif + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +#if defined(USE_GNUTLS) + +typedef struct md4_ctx MD4_CTX; + +static int MD4_Init(MD4_CTX *ctx) +{ + md4_init(ctx); + return 1; +} + +static void MD4_Update(MD4_CTX *ctx, const void *data, unsigned long size) +{ + md4_update(ctx, size, data); +} + +static void MD4_Final(unsigned char *result, MD4_CTX *ctx) +{ + md4_digest(ctx, MD4_DIGEST_SIZE, result); +} + +#elif defined(USE_WOLFSSL) && !defined(WOLFSSL_NO_MD4) + +#elif defined(USE_OPENSSL) && !defined(OPENSSL_NO_MD4) + +#elif defined(AN_APPLE_OS) +typedef CC_MD4_CTX MD4_CTX; + +static int MD4_Init(MD4_CTX *ctx) +{ + return CC_MD4_Init(ctx); +} + +static void MD4_Update(MD4_CTX *ctx, const void *data, unsigned long size) +{ + (void)CC_MD4_Update(ctx, data, (CC_LONG)size); +} + +static void MD4_Final(unsigned char *result, MD4_CTX *ctx) +{ + (void)CC_MD4_Final(result, ctx); +} + +#elif defined(USE_WIN32_CRYPTO) + +struct md4_ctx { + HCRYPTPROV hCryptProv; + HCRYPTHASH hHash; +}; +typedef struct md4_ctx MD4_CTX; + +static int MD4_Init(MD4_CTX *ctx) +{ + ctx->hCryptProv = 0; + ctx->hHash = 0; + + if(!CryptAcquireContext(&ctx->hCryptProv, NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + return 0; + + if(!CryptCreateHash(ctx->hCryptProv, CALG_MD4, 0, 0, &ctx->hHash)) { + CryptReleaseContext(ctx->hCryptProv, 0); + ctx->hCryptProv = 0; + return 0; + } + + return 1; +} + +static void MD4_Update(MD4_CTX *ctx, const void *data, unsigned long size) +{ + CryptHashData(ctx->hHash, (BYTE *)data, (unsigned int) size, 0); +} + +static void MD4_Final(unsigned char *result, MD4_CTX *ctx) +{ + unsigned long length = 0; + + CryptGetHashParam(ctx->hHash, HP_HASHVAL, NULL, &length, 0); + if(length == MD4_DIGEST_LENGTH) + CryptGetHashParam(ctx->hHash, HP_HASHVAL, result, &length, 0); + + if(ctx->hHash) + CryptDestroyHash(ctx->hHash); + + if(ctx->hCryptProv) + CryptReleaseContext(ctx->hCryptProv, 0); +} + +#elif(defined(USE_MBEDTLS) && defined(MBEDTLS_MD4_C)) + +struct md4_ctx { + void *data; + unsigned long size; +}; +typedef struct md4_ctx MD4_CTX; + +static int MD4_Init(MD4_CTX *ctx) +{ + ctx->data = NULL; + ctx->size = 0; + return 1; +} + +static void MD4_Update(MD4_CTX *ctx, const void *data, unsigned long size) +{ + if(!ctx->data) { + ctx->data = Curl_memdup(data, size); + if(ctx->data) + ctx->size = size; + } +} + +static void MD4_Final(unsigned char *result, MD4_CTX *ctx) +{ + if(ctx->data) { +#if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS) + mbedtls_md4(ctx->data, ctx->size, result); +#else + (void) mbedtls_md4_ret(ctx->data, ctx->size, result); +#endif + + Curl_safefree(ctx->data); + ctx->size = 0; + } +} + +#else +/* When no other crypto library is available, or the crypto library doesn't + * support MD4, we use this code segment this implementation of it + * + * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. + * MD4 Message-Digest Algorithm (RFC 1320). + * + * Homepage: + https://openwall.info/wiki/people/solar/software/public-domain-source-code/md4 + * + * Author: + * Alexander Peslyak, better known as Solar Designer + * + * This software was written by Alexander Peslyak in 2001. No copyright is + * claimed, and the software is hereby placed in the public domain. In case + * this attempt to disclaim copyright and place the software in the public + * domain is deemed null and void, then the software is Copyright (c) 2001 + * Alexander Peslyak and it is hereby released to the general public under the + * following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There's ABSOLUTELY NO WARRANTY, express or implied. + * + * (This is a heavily cut-down "BSD license".) + * + * This differs from Colin Plumb's older public domain implementation in that + * no exactly 32-bit integer data type is required (any 32-bit or wider + * unsigned integer data type will do), there's no compile-time endianness + * configuration, and the function prototypes match OpenSSL's. No code from + * Colin Plumb's implementation has been reused; this comment merely compares + * the properties of the two independent implementations. + * + * The primary goals of this implementation are portability and ease of use. + * It is meant to be fast, but not as fast as possible. Some known + * optimizations are not included to reduce source code size and avoid + * compile-time configuration. + */ + +/* Any 32-bit or wider unsigned integer data type will do */ +typedef unsigned int MD4_u32plus; + +struct md4_ctx { + MD4_u32plus lo, hi; + MD4_u32plus a, b, c, d; + unsigned char buffer[64]; + MD4_u32plus block[16]; +}; +typedef struct md4_ctx MD4_CTX; + +static int MD4_Init(MD4_CTX *ctx); +static void MD4_Update(MD4_CTX *ctx, const void *data, unsigned long size); +static void MD4_Final(unsigned char *result, MD4_CTX *ctx); + +/* + * The basic MD4 functions. + * + * F and G are optimized compared to their RFC 1320 definitions, with the + * optimization for F borrowed from Colin Plumb's MD5 implementation. + */ +#define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) +#define G(x, y, z) (((x) & ((y) | (z))) | ((y) & (z))) +#define H(x, y, z) ((x) ^ (y) ^ (z)) + +/* + * The MD4 transformation for all three rounds. + */ +#define STEP(f, a, b, c, d, x, s) \ + (a) += f((b), (c), (d)) + (x); \ + (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); + +/* + * SET reads 4 input bytes in little-endian byte order and stores them + * in a properly aligned word in host byte order. + * + * The check for little-endian architectures that tolerate unaligned + * memory accesses is just an optimization. Nothing will break if it + * doesn't work. + */ +#if defined(__i386__) || defined(__x86_64__) || defined(__vax__) +#define SET(n) \ + (*(MD4_u32plus *)(void *)&ptr[(n) * 4]) +#define GET(n) \ + SET(n) +#else +#define SET(n) \ + (ctx->block[(n)] = \ + (MD4_u32plus)ptr[(n) * 4] | \ + ((MD4_u32plus)ptr[(n) * 4 + 1] << 8) | \ + ((MD4_u32plus)ptr[(n) * 4 + 2] << 16) | \ + ((MD4_u32plus)ptr[(n) * 4 + 3] << 24)) +#define GET(n) \ + (ctx->block[(n)]) +#endif + +/* + * This processes one or more 64-byte data blocks, but does NOT update + * the bit counters. There are no alignment requirements. + */ +static const void *body(MD4_CTX *ctx, const void *data, unsigned long size) +{ + const unsigned char *ptr; + MD4_u32plus a, b, c, d; + + ptr = (const unsigned char *)data; + + a = ctx->a; + b = ctx->b; + c = ctx->c; + d = ctx->d; + + do { + MD4_u32plus saved_a, saved_b, saved_c, saved_d; + + saved_a = a; + saved_b = b; + saved_c = c; + saved_d = d; + +/* Round 1 */ + STEP(F, a, b, c, d, SET(0), 3) + STEP(F, d, a, b, c, SET(1), 7) + STEP(F, c, d, a, b, SET(2), 11) + STEP(F, b, c, d, a, SET(3), 19) + STEP(F, a, b, c, d, SET(4), 3) + STEP(F, d, a, b, c, SET(5), 7) + STEP(F, c, d, a, b, SET(6), 11) + STEP(F, b, c, d, a, SET(7), 19) + STEP(F, a, b, c, d, SET(8), 3) + STEP(F, d, a, b, c, SET(9), 7) + STEP(F, c, d, a, b, SET(10), 11) + STEP(F, b, c, d, a, SET(11), 19) + STEP(F, a, b, c, d, SET(12), 3) + STEP(F, d, a, b, c, SET(13), 7) + STEP(F, c, d, a, b, SET(14), 11) + STEP(F, b, c, d, a, SET(15), 19) + +/* Round 2 */ + STEP(G, a, b, c, d, GET(0) + 0x5a827999, 3) + STEP(G, d, a, b, c, GET(4) + 0x5a827999, 5) + STEP(G, c, d, a, b, GET(8) + 0x5a827999, 9) + STEP(G, b, c, d, a, GET(12) + 0x5a827999, 13) + STEP(G, a, b, c, d, GET(1) + 0x5a827999, 3) + STEP(G, d, a, b, c, GET(5) + 0x5a827999, 5) + STEP(G, c, d, a, b, GET(9) + 0x5a827999, 9) + STEP(G, b, c, d, a, GET(13) + 0x5a827999, 13) + STEP(G, a, b, c, d, GET(2) + 0x5a827999, 3) + STEP(G, d, a, b, c, GET(6) + 0x5a827999, 5) + STEP(G, c, d, a, b, GET(10) + 0x5a827999, 9) + STEP(G, b, c, d, a, GET(14) + 0x5a827999, 13) + STEP(G, a, b, c, d, GET(3) + 0x5a827999, 3) + STEP(G, d, a, b, c, GET(7) + 0x5a827999, 5) + STEP(G, c, d, a, b, GET(11) + 0x5a827999, 9) + STEP(G, b, c, d, a, GET(15) + 0x5a827999, 13) + +/* Round 3 */ + STEP(H, a, b, c, d, GET(0) + 0x6ed9eba1, 3) + STEP(H, d, a, b, c, GET(8) + 0x6ed9eba1, 9) + STEP(H, c, d, a, b, GET(4) + 0x6ed9eba1, 11) + STEP(H, b, c, d, a, GET(12) + 0x6ed9eba1, 15) + STEP(H, a, b, c, d, GET(2) + 0x6ed9eba1, 3) + STEP(H, d, a, b, c, GET(10) + 0x6ed9eba1, 9) + STEP(H, c, d, a, b, GET(6) + 0x6ed9eba1, 11) + STEP(H, b, c, d, a, GET(14) + 0x6ed9eba1, 15) + STEP(H, a, b, c, d, GET(1) + 0x6ed9eba1, 3) + STEP(H, d, a, b, c, GET(9) + 0x6ed9eba1, 9) + STEP(H, c, d, a, b, GET(5) + 0x6ed9eba1, 11) + STEP(H, b, c, d, a, GET(13) + 0x6ed9eba1, 15) + STEP(H, a, b, c, d, GET(3) + 0x6ed9eba1, 3) + STEP(H, d, a, b, c, GET(11) + 0x6ed9eba1, 9) + STEP(H, c, d, a, b, GET(7) + 0x6ed9eba1, 11) + STEP(H, b, c, d, a, GET(15) + 0x6ed9eba1, 15) + + a += saved_a; + b += saved_b; + c += saved_c; + d += saved_d; + + ptr += 64; + } while(size -= 64); + + ctx->a = a; + ctx->b = b; + ctx->c = c; + ctx->d = d; + + return ptr; +} + +static int MD4_Init(MD4_CTX *ctx) +{ + ctx->a = 0x67452301; + ctx->b = 0xefcdab89; + ctx->c = 0x98badcfe; + ctx->d = 0x10325476; + + ctx->lo = 0; + ctx->hi = 0; + return 1; +} + +static void MD4_Update(MD4_CTX *ctx, const void *data, unsigned long size) +{ + MD4_u32plus saved_lo; + unsigned long used; + + saved_lo = ctx->lo; + ctx->lo = (saved_lo + size) & 0x1fffffff; + if(ctx->lo < saved_lo) + ctx->hi++; + ctx->hi += (MD4_u32plus)size >> 29; + + used = saved_lo & 0x3f; + + if(used) { + unsigned long available = 64 - used; + + if(size < available) { + memcpy(&ctx->buffer[used], data, size); + return; + } + + memcpy(&ctx->buffer[used], data, available); + data = (const unsigned char *)data + available; + size -= available; + body(ctx, ctx->buffer, 64); + } + + if(size >= 64) { + data = body(ctx, data, size & ~(unsigned long)0x3f); + size &= 0x3f; + } + + memcpy(ctx->buffer, data, size); +} + +static void MD4_Final(unsigned char *result, MD4_CTX *ctx) +{ + unsigned long used, available; + + used = ctx->lo & 0x3f; + + ctx->buffer[used++] = 0x80; + + available = 64 - used; + + if(available < 8) { + memset(&ctx->buffer[used], 0, available); + body(ctx, ctx->buffer, 64); + used = 0; + available = 64; + } + + memset(&ctx->buffer[used], 0, available - 8); + + ctx->lo <<= 3; + ctx->buffer[56] = curlx_ultouc((ctx->lo)&0xff); + ctx->buffer[57] = curlx_ultouc((ctx->lo >> 8)&0xff); + ctx->buffer[58] = curlx_ultouc((ctx->lo >> 16)&0xff); + ctx->buffer[59] = curlx_ultouc((ctx->lo >> 24)&0xff); + ctx->buffer[60] = curlx_ultouc((ctx->hi)&0xff); + ctx->buffer[61] = curlx_ultouc((ctx->hi >> 8)&0xff); + ctx->buffer[62] = curlx_ultouc((ctx->hi >> 16)&0xff); + ctx->buffer[63] = curlx_ultouc(ctx->hi >> 24); + + body(ctx, ctx->buffer, 64); + + result[0] = curlx_ultouc((ctx->a)&0xff); + result[1] = curlx_ultouc((ctx->a >> 8)&0xff); + result[2] = curlx_ultouc((ctx->a >> 16)&0xff); + result[3] = curlx_ultouc(ctx->a >> 24); + result[4] = curlx_ultouc((ctx->b)&0xff); + result[5] = curlx_ultouc((ctx->b >> 8)&0xff); + result[6] = curlx_ultouc((ctx->b >> 16)&0xff); + result[7] = curlx_ultouc(ctx->b >> 24); + result[8] = curlx_ultouc((ctx->c)&0xff); + result[9] = curlx_ultouc((ctx->c >> 8)&0xff); + result[10] = curlx_ultouc((ctx->c >> 16)&0xff); + result[11] = curlx_ultouc(ctx->c >> 24); + result[12] = curlx_ultouc((ctx->d)&0xff); + result[13] = curlx_ultouc((ctx->d >> 8)&0xff); + result[14] = curlx_ultouc((ctx->d >> 16)&0xff); + result[15] = curlx_ultouc(ctx->d >> 24); + + memset(ctx, 0, sizeof(*ctx)); +} + +#endif /* CRYPTO LIBS */ + +CURLcode Curl_md4it(unsigned char *output, const unsigned char *input, + const size_t len) +{ + MD4_CTX ctx; + +#ifdef VOID_MD4_INIT + MD4_Init(&ctx); +#else + if(!MD4_Init(&ctx)) + return CURLE_FAILED_INIT; +#endif + + MD4_Update(&ctx, input, curlx_uztoui(len)); + MD4_Final(output, &ctx); + return CURLE_OK; +} + +#endif /* USE_CURL_NTLM_CORE */ diff --git a/third_party/curl/lib/md5.c b/third_party/curl/lib/md5.c new file mode 100644 index 0000000..01415af --- /dev/null +++ b/third_party/curl/lib/md5.c @@ -0,0 +1,656 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if (defined(USE_CURL_NTLM_CORE) && !defined(USE_WINDOWS_SSPI)) \ + || !defined(CURL_DISABLE_DIGEST_AUTH) + +#include +#include + +#include "curl_md5.h" +#include "curl_hmac.h" +#include "warnless.h" + +#ifdef USE_MBEDTLS +#include + +#if(MBEDTLS_VERSION_NUMBER >= 0x02070000) && \ + (MBEDTLS_VERSION_NUMBER < 0x03000000) + #define HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS +#endif +#endif /* USE_MBEDTLS */ + +#ifdef USE_OPENSSL + #include + #if !defined(OPENSSL_NO_MD5) && !defined(OPENSSL_NO_DEPRECATED_3_0) + #define USE_OPENSSL_MD5 + #endif +#endif + +#ifdef USE_WOLFSSL + #include + #ifndef NO_MD5 + #define USE_WOLFSSL_MD5 + #endif +#endif + +#if defined(USE_GNUTLS) +#include +#elif defined(USE_OPENSSL_MD5) +#include +#elif defined(USE_WOLFSSL_MD5) +#include +#elif defined(USE_MBEDTLS) +#include +#elif (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \ + (__MAC_OS_X_VERSION_MAX_ALLOWED >= 1040) && \ + defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && \ + (__MAC_OS_X_VERSION_MIN_REQUIRED < 101500)) || \ + (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \ + (__IPHONE_OS_VERSION_MAX_ALLOWED >= 20000) && \ + defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && \ + (__IPHONE_OS_VERSION_MIN_REQUIRED < 130000)) +#define AN_APPLE_OS +#include +#elif defined(USE_WIN32_CRYPTO) +#include +#endif + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if defined(USE_GNUTLS) + +typedef struct md5_ctx my_md5_ctx; + +static CURLcode my_md5_init(my_md5_ctx *ctx) +{ + md5_init(ctx); + return CURLE_OK; +} + +static void my_md5_update(my_md5_ctx *ctx, + const unsigned char *input, + unsigned int inputLen) +{ + md5_update(ctx, inputLen, input); +} + +static void my_md5_final(unsigned char *digest, my_md5_ctx *ctx) +{ + md5_digest(ctx, 16, digest); +} + +#elif defined(USE_OPENSSL_MD5) || defined(USE_WOLFSSL_MD5) + +typedef MD5_CTX my_md5_ctx; + +static CURLcode my_md5_init(my_md5_ctx *ctx) +{ + if(!MD5_Init(ctx)) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +static void my_md5_update(my_md5_ctx *ctx, + const unsigned char *input, + unsigned int len) +{ + (void)MD5_Update(ctx, input, len); +} + +static void my_md5_final(unsigned char *digest, my_md5_ctx *ctx) +{ + (void)MD5_Final(digest, ctx); +} + +#elif defined(USE_MBEDTLS) + +typedef mbedtls_md5_context my_md5_ctx; + +static CURLcode my_md5_init(my_md5_ctx *ctx) +{ +#if (MBEDTLS_VERSION_NUMBER >= 0x03000000) + if(mbedtls_md5_starts(ctx)) + return CURLE_OUT_OF_MEMORY; +#elif defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS) + if(mbedtls_md5_starts_ret(ctx)) + return CURLE_OUT_OF_MEMORY; +#else + (void)mbedtls_md5_starts(ctx); +#endif + return CURLE_OK; +} + +static void my_md5_update(my_md5_ctx *ctx, + const unsigned char *data, + unsigned int length) +{ +#if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS) + (void) mbedtls_md5_update(ctx, data, length); +#else + (void) mbedtls_md5_update_ret(ctx, data, length); +#endif +} + +static void my_md5_final(unsigned char *digest, my_md5_ctx *ctx) +{ +#if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS) + (void) mbedtls_md5_finish(ctx, digest); +#else + (void) mbedtls_md5_finish_ret(ctx, digest); +#endif +} + +#elif defined(AN_APPLE_OS) + +/* For Apple operating systems: CommonCrypto has the functions we need. + These functions are available on Tiger and later, as well as iOS 2.0 + and later. If you're building for an older cat, well, sorry. + + Declaring the functions as static like this seems to be a bit more + reliable than defining COMMON_DIGEST_FOR_OPENSSL on older cats. */ +# define my_md5_ctx CC_MD5_CTX + +static CURLcode my_md5_init(my_md5_ctx *ctx) +{ + if(!CC_MD5_Init(ctx)) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +static void my_md5_update(my_md5_ctx *ctx, + const unsigned char *input, + unsigned int inputLen) +{ + CC_MD5_Update(ctx, input, inputLen); +} + +static void my_md5_final(unsigned char *digest, my_md5_ctx *ctx) +{ + CC_MD5_Final(digest, ctx); +} + +#elif defined(USE_WIN32_CRYPTO) + +struct md5_ctx { + HCRYPTPROV hCryptProv; + HCRYPTHASH hHash; +}; +typedef struct md5_ctx my_md5_ctx; + +static CURLcode my_md5_init(my_md5_ctx *ctx) +{ + if(!CryptAcquireContext(&ctx->hCryptProv, NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + return CURLE_OUT_OF_MEMORY; + + if(!CryptCreateHash(ctx->hCryptProv, CALG_MD5, 0, 0, &ctx->hHash)) { + CryptReleaseContext(ctx->hCryptProv, 0); + ctx->hCryptProv = 0; + return CURLE_FAILED_INIT; + } + + return CURLE_OK; +} + +static void my_md5_update(my_md5_ctx *ctx, + const unsigned char *input, + unsigned int inputLen) +{ + CryptHashData(ctx->hHash, (unsigned char *)input, inputLen, 0); +} + +static void my_md5_final(unsigned char *digest, my_md5_ctx *ctx) +{ + unsigned long length = 0; + CryptGetHashParam(ctx->hHash, HP_HASHVAL, NULL, &length, 0); + if(length == 16) + CryptGetHashParam(ctx->hHash, HP_HASHVAL, digest, &length, 0); + if(ctx->hHash) + CryptDestroyHash(ctx->hHash); + if(ctx->hCryptProv) + CryptReleaseContext(ctx->hCryptProv, 0); +} + +#else + +/* When no other crypto library is available we use this code segment */ + +/* + * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. + * MD5 Message-Digest Algorithm (RFC 1321). + * + * Homepage: + https://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 + * + * Author: + * Alexander Peslyak, better known as Solar Designer + * + * This software was written by Alexander Peslyak in 2001. No copyright is + * claimed, and the software is hereby placed in the public domain. + * In case this attempt to disclaim copyright and place the software in the + * public domain is deemed null and void, then the software is + * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the + * general public under the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There's ABSOLUTELY NO WARRANTY, express or implied. + * + * (This is a heavily cut-down "BSD license".) + * + * This differs from Colin Plumb's older public domain implementation in that + * no exactly 32-bit integer data type is required (any 32-bit or wider + * unsigned integer data type will do), there's no compile-time endianness + * configuration, and the function prototypes match OpenSSL's. No code from + * Colin Plumb's implementation has been reused; this comment merely compares + * the properties of the two independent implementations. + * + * The primary goals of this implementation are portability and ease of use. + * It is meant to be fast, but not as fast as possible. Some known + * optimizations are not included to reduce source code size and avoid + * compile-time configuration. + */ + +/* Any 32-bit or wider unsigned integer data type will do */ +typedef unsigned int MD5_u32plus; + +struct md5_ctx { + MD5_u32plus lo, hi; + MD5_u32plus a, b, c, d; + unsigned char buffer[64]; + MD5_u32plus block[16]; +}; +typedef struct md5_ctx my_md5_ctx; + +static CURLcode my_md5_init(my_md5_ctx *ctx); +static void my_md5_update(my_md5_ctx *ctx, const void *data, + unsigned long size); +static void my_md5_final(unsigned char *result, my_md5_ctx *ctx); + +/* + * The basic MD5 functions. + * + * F and G are optimized compared to their RFC 1321 definitions for + * architectures that lack an AND-NOT instruction, just like in Colin Plumb's + * implementation. + */ +#define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) +#define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y)))) +#define H(x, y, z) (((x) ^ (y)) ^ (z)) +#define H2(x, y, z) ((x) ^ ((y) ^ (z))) +#define I(x, y, z) ((y) ^ ((x) | ~(z))) + +/* + * The MD5 transformation for all four rounds. + */ +#define STEP(f, a, b, c, d, x, t, s) \ + (a) += f((b), (c), (d)) + (x) + (t); \ + (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \ + (a) += (b); + +/* + * SET reads 4 input bytes in little-endian byte order and stores them + * in a properly aligned word in host byte order. + * + * The check for little-endian architectures that tolerate unaligned + * memory accesses is just an optimization. Nothing will break if it + * doesn't work. + */ +#if defined(__i386__) || defined(__x86_64__) || defined(__vax__) +#define SET(n) \ + (*(MD5_u32plus *)(void *)&ptr[(n) * 4]) +#define GET(n) \ + SET(n) +#else +#define SET(n) \ + (ctx->block[(n)] = \ + (MD5_u32plus)ptr[(n) * 4] | \ + ((MD5_u32plus)ptr[(n) * 4 + 1] << 8) | \ + ((MD5_u32plus)ptr[(n) * 4 + 2] << 16) | \ + ((MD5_u32plus)ptr[(n) * 4 + 3] << 24)) +#define GET(n) \ + (ctx->block[(n)]) +#endif + +/* + * This processes one or more 64-byte data blocks, but does NOT update + * the bit counters. There are no alignment requirements. + */ +static const void *body(my_md5_ctx *ctx, const void *data, unsigned long size) +{ + const unsigned char *ptr; + MD5_u32plus a, b, c, d; + + ptr = (const unsigned char *)data; + + a = ctx->a; + b = ctx->b; + c = ctx->c; + d = ctx->d; + + do { + MD5_u32plus saved_a, saved_b, saved_c, saved_d; + + saved_a = a; + saved_b = b; + saved_c = c; + saved_d = d; + +/* Round 1 */ + STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7) + STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12) + STEP(F, c, d, a, b, SET(2), 0x242070db, 17) + STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22) + STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7) + STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12) + STEP(F, c, d, a, b, SET(6), 0xa8304613, 17) + STEP(F, b, c, d, a, SET(7), 0xfd469501, 22) + STEP(F, a, b, c, d, SET(8), 0x698098d8, 7) + STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12) + STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17) + STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22) + STEP(F, a, b, c, d, SET(12), 0x6b901122, 7) + STEP(F, d, a, b, c, SET(13), 0xfd987193, 12) + STEP(F, c, d, a, b, SET(14), 0xa679438e, 17) + STEP(F, b, c, d, a, SET(15), 0x49b40821, 22) + +/* Round 2 */ + STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5) + STEP(G, d, a, b, c, GET(6), 0xc040b340, 9) + STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14) + STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20) + STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5) + STEP(G, d, a, b, c, GET(10), 0x02441453, 9) + STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14) + STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20) + STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5) + STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9) + STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14) + STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20) + STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5) + STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9) + STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14) + STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20) + +/* Round 3 */ + STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4) + STEP(H2, d, a, b, c, GET(8), 0x8771f681, 11) + STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16) + STEP(H2, b, c, d, a, GET(14), 0xfde5380c, 23) + STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4) + STEP(H2, d, a, b, c, GET(4), 0x4bdecfa9, 11) + STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16) + STEP(H2, b, c, d, a, GET(10), 0xbebfbc70, 23) + STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4) + STEP(H2, d, a, b, c, GET(0), 0xeaa127fa, 11) + STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16) + STEP(H2, b, c, d, a, GET(6), 0x04881d05, 23) + STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4) + STEP(H2, d, a, b, c, GET(12), 0xe6db99e5, 11) + STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16) + STEP(H2, b, c, d, a, GET(2), 0xc4ac5665, 23) + +/* Round 4 */ + STEP(I, a, b, c, d, GET(0), 0xf4292244, 6) + STEP(I, d, a, b, c, GET(7), 0x432aff97, 10) + STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15) + STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21) + STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6) + STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10) + STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15) + STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21) + STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6) + STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10) + STEP(I, c, d, a, b, GET(6), 0xa3014314, 15) + STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21) + STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6) + STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10) + STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15) + STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21) + + a += saved_a; + b += saved_b; + c += saved_c; + d += saved_d; + + ptr += 64; + } while(size -= 64); + + ctx->a = a; + ctx->b = b; + ctx->c = c; + ctx->d = d; + + return ptr; +} + +static CURLcode my_md5_init(my_md5_ctx *ctx) +{ + ctx->a = 0x67452301; + ctx->b = 0xefcdab89; + ctx->c = 0x98badcfe; + ctx->d = 0x10325476; + + ctx->lo = 0; + ctx->hi = 0; + + return CURLE_OK; +} + +static void my_md5_update(my_md5_ctx *ctx, const void *data, + unsigned long size) +{ + MD5_u32plus saved_lo; + unsigned long used; + + saved_lo = ctx->lo; + ctx->lo = (saved_lo + size) & 0x1fffffff; + if(ctx->lo < saved_lo) + ctx->hi++; + ctx->hi += (MD5_u32plus)size >> 29; + + used = saved_lo & 0x3f; + + if(used) { + unsigned long available = 64 - used; + + if(size < available) { + memcpy(&ctx->buffer[used], data, size); + return; + } + + memcpy(&ctx->buffer[used], data, available); + data = (const unsigned char *)data + available; + size -= available; + body(ctx, ctx->buffer, 64); + } + + if(size >= 64) { + data = body(ctx, data, size & ~(unsigned long)0x3f); + size &= 0x3f; + } + + memcpy(ctx->buffer, data, size); +} + +static void my_md5_final(unsigned char *result, my_md5_ctx *ctx) +{ + unsigned long used, available; + + used = ctx->lo & 0x3f; + + ctx->buffer[used++] = 0x80; + + available = 64 - used; + + if(available < 8) { + memset(&ctx->buffer[used], 0, available); + body(ctx, ctx->buffer, 64); + used = 0; + available = 64; + } + + memset(&ctx->buffer[used], 0, available - 8); + + ctx->lo <<= 3; + ctx->buffer[56] = curlx_ultouc((ctx->lo)&0xff); + ctx->buffer[57] = curlx_ultouc((ctx->lo >> 8)&0xff); + ctx->buffer[58] = curlx_ultouc((ctx->lo >> 16)&0xff); + ctx->buffer[59] = curlx_ultouc(ctx->lo >> 24); + ctx->buffer[60] = curlx_ultouc((ctx->hi)&0xff); + ctx->buffer[61] = curlx_ultouc((ctx->hi >> 8)&0xff); + ctx->buffer[62] = curlx_ultouc((ctx->hi >> 16)&0xff); + ctx->buffer[63] = curlx_ultouc(ctx->hi >> 24); + + body(ctx, ctx->buffer, 64); + + result[0] = curlx_ultouc((ctx->a)&0xff); + result[1] = curlx_ultouc((ctx->a >> 8)&0xff); + result[2] = curlx_ultouc((ctx->a >> 16)&0xff); + result[3] = curlx_ultouc(ctx->a >> 24); + result[4] = curlx_ultouc((ctx->b)&0xff); + result[5] = curlx_ultouc((ctx->b >> 8)&0xff); + result[6] = curlx_ultouc((ctx->b >> 16)&0xff); + result[7] = curlx_ultouc(ctx->b >> 24); + result[8] = curlx_ultouc((ctx->c)&0xff); + result[9] = curlx_ultouc((ctx->c >> 8)&0xff); + result[10] = curlx_ultouc((ctx->c >> 16)&0xff); + result[11] = curlx_ultouc(ctx->c >> 24); + result[12] = curlx_ultouc((ctx->d)&0xff); + result[13] = curlx_ultouc((ctx->d >> 8)&0xff); + result[14] = curlx_ultouc((ctx->d >> 16)&0xff); + result[15] = curlx_ultouc(ctx->d >> 24); + + memset(ctx, 0, sizeof(*ctx)); +} + +#endif /* CRYPTO LIBS */ + +const struct HMAC_params Curl_HMAC_MD5[] = { + { + /* Hash initialization function. */ + CURLX_FUNCTION_CAST(HMAC_hinit_func, my_md5_init), + /* Hash update function. */ + CURLX_FUNCTION_CAST(HMAC_hupdate_func, my_md5_update), + /* Hash computation end function. */ + CURLX_FUNCTION_CAST(HMAC_hfinal_func, my_md5_final), + /* Size of hash context structure. */ + sizeof(my_md5_ctx), + /* Maximum key length. */ + 64, + /* Result size. */ + 16 + } +}; + +const struct MD5_params Curl_DIGEST_MD5[] = { + { + /* Digest initialization function */ + CURLX_FUNCTION_CAST(Curl_MD5_init_func, my_md5_init), + /* Digest update function */ + CURLX_FUNCTION_CAST(Curl_MD5_update_func, my_md5_update), + /* Digest computation end function */ + CURLX_FUNCTION_CAST(Curl_MD5_final_func, my_md5_final), + /* Size of digest context struct */ + sizeof(my_md5_ctx), + /* Result size */ + 16 + } +}; + +/* + * @unittest: 1601 + * Returns CURLE_OK on success. + */ +CURLcode Curl_md5it(unsigned char *outbuffer, const unsigned char *input, + const size_t len) +{ + CURLcode result; + my_md5_ctx ctx; + + result = my_md5_init(&ctx); + if(!result) { + my_md5_update(&ctx, input, curlx_uztoui(len)); + my_md5_final(outbuffer, &ctx); + } + return result; +} + +struct MD5_context *Curl_MD5_init(const struct MD5_params *md5params) +{ + struct MD5_context *ctxt; + + /* Create MD5 context */ + ctxt = malloc(sizeof(*ctxt)); + + if(!ctxt) + return ctxt; + + ctxt->md5_hashctx = malloc(md5params->md5_ctxtsize); + + if(!ctxt->md5_hashctx) { + free(ctxt); + return NULL; + } + + ctxt->md5_hash = md5params; + + if((*md5params->md5_init_func)(ctxt->md5_hashctx)) { + free(ctxt->md5_hashctx); + free(ctxt); + return NULL; + } + + return ctxt; +} + +CURLcode Curl_MD5_update(struct MD5_context *context, + const unsigned char *data, + unsigned int len) +{ + (*context->md5_hash->md5_update_func)(context->md5_hashctx, data, len); + + return CURLE_OK; +} + +CURLcode Curl_MD5_final(struct MD5_context *context, unsigned char *result) +{ + (*context->md5_hash->md5_final_func)(result, context->md5_hashctx); + + free(context->md5_hashctx); + free(context); + + return CURLE_OK; +} + +#endif /* Using NTLM (without SSPI) || Digest */ diff --git a/third_party/curl/lib/memdebug.c b/third_party/curl/lib/memdebug.c new file mode 100644 index 0000000..fce933a --- /dev/null +++ b/third_party/curl/lib/memdebug.c @@ -0,0 +1,463 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef CURLDEBUG + +#include + +#include "urldata.h" + +#define MEMDEBUG_NODEFINES /* don't redefine the standard functions */ + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +struct memdebug { + size_t size; + union { + curl_off_t o; + double d; + void *p; + } mem[1]; + /* I'm hoping this is the thing with the strictest alignment + * requirements. That also means we waste some space :-( */ +}; + +/* + * Note that these debug functions are very simple and they are meant to + * remain so. For advanced analysis, record a log file and write perl scripts + * to analyze them! + * + * Don't use these with multithreaded test programs! + */ + +FILE *curl_dbg_logfile = NULL; +static bool registered_cleanup = FALSE; /* atexit registered cleanup */ +static bool memlimit = FALSE; /* enable memory limit */ +static long memsize = 0; /* set number of mallocs allowed */ + +/* LeakSantizier (LSAN) calls _exit() instead of exit() when a leak is detected + on exit so the logfile must be closed explicitly or data could be lost. + Though _exit() does not call atexit handlers such as this, LSAN's call to + _exit() comes after the atexit handlers are called. curl/curl#6620 */ +static void curl_dbg_cleanup(void) +{ + if(curl_dbg_logfile && + curl_dbg_logfile != stderr && + curl_dbg_logfile != stdout) { + fclose(curl_dbg_logfile); + } + curl_dbg_logfile = NULL; +} + +/* this sets the log file name */ +void curl_dbg_memdebug(const char *logname) +{ + if(!curl_dbg_logfile) { + if(logname && *logname) + curl_dbg_logfile = fopen(logname, FOPEN_WRITETEXT); + else + curl_dbg_logfile = stderr; +#ifdef MEMDEBUG_LOG_SYNC + /* Flush the log file after every line so the log isn't lost in a crash */ + if(curl_dbg_logfile) + setbuf(curl_dbg_logfile, (char *)NULL); +#endif + } + if(!registered_cleanup) + registered_cleanup = !atexit(curl_dbg_cleanup); +} + +/* This function sets the number of malloc() calls that should return + successfully! */ +void curl_dbg_memlimit(long limit) +{ + if(!memlimit) { + memlimit = TRUE; + memsize = limit; + } +} + +/* returns TRUE if this isn't allowed! */ +static bool countcheck(const char *func, int line, const char *source) +{ + /* if source is NULL, then the call is made internally and this check + should not be made */ + if(memlimit && source) { + if(!memsize) { + /* log to file */ + curl_dbg_log("LIMIT %s:%d %s reached memlimit\n", + source, line, func); + /* log to stderr also */ + fprintf(stderr, "LIMIT %s:%d %s reached memlimit\n", + source, line, func); + fflush(curl_dbg_logfile); /* because it might crash now */ + errno = ENOMEM; + return TRUE; /* RETURN ERROR! */ + } + else + memsize--; /* countdown */ + + + } + + return FALSE; /* allow this */ +} + +ALLOC_FUNC void *curl_dbg_malloc(size_t wantedsize, + int line, const char *source) +{ + struct memdebug *mem; + size_t size; + + DEBUGASSERT(wantedsize != 0); + + if(countcheck("malloc", line, source)) + return NULL; + + /* alloc at least 64 bytes */ + size = sizeof(struct memdebug) + wantedsize; + + mem = (Curl_cmalloc)(size); + if(mem) { + mem->size = wantedsize; + } + + if(source) + curl_dbg_log("MEM %s:%d malloc(%zu) = %p\n", + source, line, wantedsize, + mem ? (void *)mem->mem : (void *)0); + + return (mem ? mem->mem : NULL); +} + +ALLOC_FUNC void *curl_dbg_calloc(size_t wanted_elements, size_t wanted_size, + int line, const char *source) +{ + struct memdebug *mem; + size_t size, user_size; + + DEBUGASSERT(wanted_elements != 0); + DEBUGASSERT(wanted_size != 0); + + if(countcheck("calloc", line, source)) + return NULL; + + /* alloc at least 64 bytes */ + user_size = wanted_size * wanted_elements; + size = sizeof(struct memdebug) + user_size; + + mem = (Curl_ccalloc)(1, size); + if(mem) + mem->size = user_size; + + if(source) + curl_dbg_log("MEM %s:%d calloc(%zu,%zu) = %p\n", + source, line, wanted_elements, wanted_size, + mem ? (void *)mem->mem : (void *)0); + + return (mem ? mem->mem : NULL); +} + +ALLOC_FUNC char *curl_dbg_strdup(const char *str, + int line, const char *source) +{ + char *mem; + size_t len; + + DEBUGASSERT(str != NULL); + + if(countcheck("strdup", line, source)) + return NULL; + + len = strlen(str) + 1; + + mem = curl_dbg_malloc(len, 0, NULL); /* NULL prevents logging */ + if(mem) + memcpy(mem, str, len); + + if(source) + curl_dbg_log("MEM %s:%d strdup(%p) (%zu) = %p\n", + source, line, (const void *)str, len, (const void *)mem); + + return mem; +} + +#if defined(_WIN32) && defined(UNICODE) +ALLOC_FUNC wchar_t *curl_dbg_wcsdup(const wchar_t *str, + int line, const char *source) +{ + wchar_t *mem; + size_t wsiz, bsiz; + + DEBUGASSERT(str != NULL); + + if(countcheck("wcsdup", line, source)) + return NULL; + + wsiz = wcslen(str) + 1; + bsiz = wsiz * sizeof(wchar_t); + + mem = curl_dbg_malloc(bsiz, 0, NULL); /* NULL prevents logging */ + if(mem) + memcpy(mem, str, bsiz); + + if(source) + curl_dbg_log("MEM %s:%d wcsdup(%p) (%zu) = %p\n", + source, line, (void *)str, bsiz, (void *)mem); + + return mem; +} +#endif + +/* We provide a realloc() that accepts a NULL as pointer, which then + performs a malloc(). In order to work with ares. */ +void *curl_dbg_realloc(void *ptr, size_t wantedsize, + int line, const char *source) +{ + struct memdebug *mem = NULL; + + size_t size = sizeof(struct memdebug) + wantedsize; + + DEBUGASSERT(wantedsize != 0); + + if(countcheck("realloc", line, source)) + return NULL; + +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:1684) + /* 1684: conversion from pointer to same-sized integral type */ +#endif + + if(ptr) + mem = (void *)((char *)ptr - offsetof(struct memdebug, mem)); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif + + mem = (Curl_crealloc)(mem, size); + if(source) + curl_dbg_log("MEM %s:%d realloc(%p, %zu) = %p\n", + source, line, (void *)ptr, wantedsize, + mem ? (void *)mem->mem : (void *)0); + + if(mem) { + mem->size = wantedsize; + return mem->mem; + } + + return NULL; +} + +void curl_dbg_free(void *ptr, int line, const char *source) +{ + if(ptr) { + struct memdebug *mem; + +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:1684) + /* 1684: conversion from pointer to same-sized integral type */ +#endif + + mem = (void *)((char *)ptr - offsetof(struct memdebug, mem)); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif + + /* free for real */ + (Curl_cfree)(mem); + } + + if(source && ptr) + curl_dbg_log("MEM %s:%d free(%p)\n", source, line, (void *)ptr); +} + +curl_socket_t curl_dbg_socket(int domain, int type, int protocol, + int line, const char *source) +{ + curl_socket_t sockfd; + + if(countcheck("socket", line, source)) + return CURL_SOCKET_BAD; + + sockfd = socket(domain, type, protocol); + + if(source && (sockfd != CURL_SOCKET_BAD)) + curl_dbg_log("FD %s:%d socket() = %" CURL_FORMAT_SOCKET_T "\n", + source, line, sockfd); + + return sockfd; +} + +SEND_TYPE_RETV curl_dbg_send(SEND_TYPE_ARG1 sockfd, + SEND_QUAL_ARG2 SEND_TYPE_ARG2 buf, + SEND_TYPE_ARG3 len, SEND_TYPE_ARG4 flags, int line, + const char *source) +{ + SEND_TYPE_RETV rc; + if(countcheck("send", line, source)) + return -1; + rc = send(sockfd, buf, len, flags); + if(source) + curl_dbg_log("SEND %s:%d send(%lu) = %ld\n", + source, line, (unsigned long)len, (long)rc); + return rc; +} + +RECV_TYPE_RETV curl_dbg_recv(RECV_TYPE_ARG1 sockfd, RECV_TYPE_ARG2 buf, + RECV_TYPE_ARG3 len, RECV_TYPE_ARG4 flags, int line, + const char *source) +{ + RECV_TYPE_RETV rc; + if(countcheck("recv", line, source)) + return -1; + rc = recv(sockfd, buf, len, flags); + if(source) + curl_dbg_log("RECV %s:%d recv(%lu) = %ld\n", + source, line, (unsigned long)len, (long)rc); + return rc; +} + +#ifdef HAVE_SOCKETPAIR +int curl_dbg_socketpair(int domain, int type, int protocol, + curl_socket_t socket_vector[2], + int line, const char *source) +{ + int res = socketpair(domain, type, protocol, socket_vector); + + if(source && (0 == res)) + curl_dbg_log("FD %s:%d socketpair() = " + "%" CURL_FORMAT_SOCKET_T " %" CURL_FORMAT_SOCKET_T "\n", + source, line, socket_vector[0], socket_vector[1]); + + return res; +} +#endif + +curl_socket_t curl_dbg_accept(curl_socket_t s, void *saddr, void *saddrlen, + int line, const char *source) +{ + struct sockaddr *addr = (struct sockaddr *)saddr; + curl_socklen_t *addrlen = (curl_socklen_t *)saddrlen; + + curl_socket_t sockfd = accept(s, addr, addrlen); + + if(source && (sockfd != CURL_SOCKET_BAD)) + curl_dbg_log("FD %s:%d accept() = %" CURL_FORMAT_SOCKET_T "\n", + source, line, sockfd); + + return sockfd; +} + +/* separate function to allow libcurl to mark a "faked" close */ +void curl_dbg_mark_sclose(curl_socket_t sockfd, int line, const char *source) +{ + if(source) + curl_dbg_log("FD %s:%d sclose(%" CURL_FORMAT_SOCKET_T ")\n", + source, line, sockfd); +} + +/* this is our own defined way to close sockets on *ALL* platforms */ +int curl_dbg_sclose(curl_socket_t sockfd, int line, const char *source) +{ + int res = sclose(sockfd); + curl_dbg_mark_sclose(sockfd, line, source); + return res; +} + +ALLOC_FUNC FILE *curl_dbg_fopen(const char *file, const char *mode, + int line, const char *source) +{ + FILE *res = fopen(file, mode); + + if(source) + curl_dbg_log("FILE %s:%d fopen(\"%s\",\"%s\") = %p\n", + source, line, file, mode, (void *)res); + + return res; +} + +ALLOC_FUNC FILE *curl_dbg_fdopen(int filedes, const char *mode, + int line, const char *source) +{ + FILE *res = fdopen(filedes, mode); + if(source) + curl_dbg_log("FILE %s:%d fdopen(\"%d\",\"%s\") = %p\n", + source, line, filedes, mode, (void *)res); + return res; +} + +int curl_dbg_fclose(FILE *file, int line, const char *source) +{ + int res; + + DEBUGASSERT(file != NULL); + + if(source) + curl_dbg_log("FILE %s:%d fclose(%p)\n", + source, line, (void *)file); + + res = fclose(file); + + return res; +} + +#define LOGLINE_BUFSIZE 1024 + +/* this does the writing to the memory tracking log file */ +void curl_dbg_log(const char *format, ...) +{ + char *buf; + int nchars; + va_list ap; + + if(!curl_dbg_logfile) + return; + + buf = (Curl_cmalloc)(LOGLINE_BUFSIZE); + if(!buf) + return; + + va_start(ap, format); + nchars = mvsnprintf(buf, LOGLINE_BUFSIZE, format, ap); + va_end(ap); + + if(nchars > LOGLINE_BUFSIZE - 1) + nchars = LOGLINE_BUFSIZE - 1; + + if(nchars > 0) + fwrite(buf, 1, (size_t)nchars, curl_dbg_logfile); + + (Curl_cfree)(buf); +} + +#endif /* CURLDEBUG */ diff --git a/third_party/curl/lib/memdebug.h b/third_party/curl/lib/memdebug.h new file mode 100644 index 0000000..51147cd --- /dev/null +++ b/third_party/curl/lib/memdebug.h @@ -0,0 +1,202 @@ +#ifndef HEADER_CURL_MEMDEBUG_H +#define HEADER_CURL_MEMDEBUG_H +#ifdef CURLDEBUG +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * CAUTION: this header is designed to work when included by the app-side + * as well as the library. Do not mix with library internals! + */ + +#include +#include "functypes.h" + +#if defined(__GNUC__) && __GNUC__ >= 3 +# define ALLOC_FUNC __attribute__((malloc)) +# define ALLOC_SIZE(s) __attribute__((alloc_size(s))) +# define ALLOC_SIZE2(n, s) __attribute__((alloc_size(n, s))) +#elif defined(_MSC_VER) +# define ALLOC_FUNC __declspec(restrict) +# define ALLOC_SIZE(s) +# define ALLOC_SIZE2(n, s) +#else +# define ALLOC_FUNC +# define ALLOC_SIZE(s) +# define ALLOC_SIZE2(n, s) +#endif + +#define CURL_MT_LOGFNAME_BUFSIZE 512 + +extern FILE *curl_dbg_logfile; + +/* memory functions */ +CURL_EXTERN ALLOC_FUNC ALLOC_SIZE(1) void *curl_dbg_malloc(size_t size, + int line, + const char *source); +CURL_EXTERN ALLOC_FUNC ALLOC_SIZE2(1, 2) void *curl_dbg_calloc(size_t elements, + size_t size, int line, const char *source); +CURL_EXTERN ALLOC_SIZE(2) void *curl_dbg_realloc(void *ptr, + size_t size, + int line, + const char *source); +CURL_EXTERN void curl_dbg_free(void *ptr, int line, const char *source); +CURL_EXTERN ALLOC_FUNC char *curl_dbg_strdup(const char *str, int line, + const char *src); +#if defined(_WIN32) && defined(UNICODE) +CURL_EXTERN ALLOC_FUNC wchar_t *curl_dbg_wcsdup(const wchar_t *str, + int line, + const char *source); +#endif + +CURL_EXTERN void curl_dbg_memdebug(const char *logname); +CURL_EXTERN void curl_dbg_memlimit(long limit); +CURL_EXTERN void curl_dbg_log(const char *format, ...) CURL_PRINTF(1, 2); + +/* file descriptor manipulators */ +CURL_EXTERN curl_socket_t curl_dbg_socket(int domain, int type, int protocol, + int line, const char *source); +CURL_EXTERN void curl_dbg_mark_sclose(curl_socket_t sockfd, + int line, const char *source); +CURL_EXTERN int curl_dbg_sclose(curl_socket_t sockfd, + int line, const char *source); +CURL_EXTERN curl_socket_t curl_dbg_accept(curl_socket_t s, void *a, void *alen, + int line, const char *source); +#ifdef HAVE_SOCKETPAIR +CURL_EXTERN int curl_dbg_socketpair(int domain, int type, int protocol, + curl_socket_t socket_vector[2], + int line, const char *source); +#endif + +/* send/receive sockets */ +CURL_EXTERN SEND_TYPE_RETV curl_dbg_send(SEND_TYPE_ARG1 sockfd, + SEND_QUAL_ARG2 SEND_TYPE_ARG2 buf, + SEND_TYPE_ARG3 len, + SEND_TYPE_ARG4 flags, int line, + const char *source); +CURL_EXTERN RECV_TYPE_RETV curl_dbg_recv(RECV_TYPE_ARG1 sockfd, + RECV_TYPE_ARG2 buf, + RECV_TYPE_ARG3 len, + RECV_TYPE_ARG4 flags, int line, + const char *source); + +/* FILE functions */ +CURL_EXTERN ALLOC_FUNC FILE *curl_dbg_fopen(const char *file, const char *mode, + int line, const char *source); +CURL_EXTERN ALLOC_FUNC FILE *curl_dbg_fdopen(int filedes, const char *mode, + int line, const char *source); + +CURL_EXTERN int curl_dbg_fclose(FILE *file, int line, const char *source); + +#ifndef MEMDEBUG_NODEFINES + +/* Set this symbol on the command-line, recompile all lib-sources */ +#undef strdup +#define strdup(ptr) curl_dbg_strdup(ptr, __LINE__, __FILE__) +#define malloc(size) curl_dbg_malloc(size, __LINE__, __FILE__) +#define calloc(nbelem,size) curl_dbg_calloc(nbelem, size, __LINE__, __FILE__) +#define realloc(ptr,size) curl_dbg_realloc(ptr, size, __LINE__, __FILE__) +#define free(ptr) curl_dbg_free(ptr, __LINE__, __FILE__) +#define send(a,b,c,d) curl_dbg_send(a,b,c,d, __LINE__, __FILE__) +#define recv(a,b,c,d) curl_dbg_recv(a,b,c,d, __LINE__, __FILE__) + +#ifdef _WIN32 +# ifdef UNICODE +# undef wcsdup +# define wcsdup(ptr) curl_dbg_wcsdup(ptr, __LINE__, __FILE__) +# undef _wcsdup +# define _wcsdup(ptr) curl_dbg_wcsdup(ptr, __LINE__, __FILE__) +# undef _tcsdup +# define _tcsdup(ptr) curl_dbg_wcsdup(ptr, __LINE__, __FILE__) +# else +# undef _tcsdup +# define _tcsdup(ptr) curl_dbg_strdup(ptr, __LINE__, __FILE__) +# endif +#endif + +#undef socket +#define socket(domain,type,protocol)\ + curl_dbg_socket(domain, type, protocol, __LINE__, __FILE__) +#undef accept /* for those with accept as a macro */ +#define accept(sock,addr,len)\ + curl_dbg_accept(sock, addr, len, __LINE__, __FILE__) +#ifdef HAVE_SOCKETPAIR +#define socketpair(domain,type,protocol,socket_vector)\ + curl_dbg_socketpair(domain, type, protocol, socket_vector, __LINE__, __FILE__) +#endif + +#ifdef HAVE_GETADDRINFO +#if defined(getaddrinfo) && defined(__osf__) +/* OSF/1 and Tru64 have getaddrinfo as a define already, so we cannot define + our macro as for other platforms. Instead, we redefine the new name they + define getaddrinfo to become! */ +#define ogetaddrinfo(host,serv,hint,res) \ + curl_dbg_getaddrinfo(host, serv, hint, res, __LINE__, __FILE__) +#else +#undef getaddrinfo +#define getaddrinfo(host,serv,hint,res) \ + curl_dbg_getaddrinfo(host, serv, hint, res, __LINE__, __FILE__) +#endif +#endif /* HAVE_GETADDRINFO */ + +#ifdef HAVE_FREEADDRINFO +#undef freeaddrinfo +#define freeaddrinfo(data) \ + curl_dbg_freeaddrinfo(data, __LINE__, __FILE__) +#endif /* HAVE_FREEADDRINFO */ + +/* sclose is probably already defined, redefine it! */ +#undef sclose +#define sclose(sockfd) curl_dbg_sclose(sockfd,__LINE__,__FILE__) + +#define fake_sclose(sockfd) curl_dbg_mark_sclose(sockfd,__LINE__,__FILE__) + +#undef fopen +#define fopen(file,mode) curl_dbg_fopen(file,mode,__LINE__,__FILE__) +#undef fdopen +#define fdopen(file,mode) curl_dbg_fdopen(file,mode,__LINE__,__FILE__) +#define fclose(file) curl_dbg_fclose(file,__LINE__,__FILE__) + +#endif /* MEMDEBUG_NODEFINES */ + +#endif /* CURLDEBUG */ + +/* +** Following section applies even when CURLDEBUG is not defined. +*/ + +#ifndef fake_sclose +#define fake_sclose(x) Curl_nop_stmt +#endif + +/* + * Curl_safefree defined as a macro to allow MemoryTracking feature + * to log free() calls at same location where Curl_safefree is used. + * This macro also assigns NULL to given pointer when free'd. + */ + +#define Curl_safefree(ptr) \ + do { free((ptr)); (ptr) = NULL;} while(0) + +#endif /* HEADER_CURL_MEMDEBUG_H */ diff --git a/third_party/curl/lib/mime.c b/third_party/curl/lib/mime.c new file mode 100644 index 0000000..a2356c4 --- /dev/null +++ b/third_party/curl/lib/mime.c @@ -0,0 +1,2238 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "mime.h" +#include "warnless.h" +#include "urldata.h" +#include "sendf.h" +#include "strdup.h" + +#if !defined(CURL_DISABLE_MIME) && (!defined(CURL_DISABLE_HTTP) || \ + !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_IMAP)) + +#if defined(HAVE_LIBGEN_H) && defined(HAVE_BASENAME) +#include +#endif + +#include "rand.h" +#include "slist.h" +#include "strcase.h" +#include "dynbuf.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#ifdef _WIN32 +# ifndef R_OK +# define R_OK 4 +# endif +#endif + + +#define READ_ERROR ((size_t) -1) +#define STOP_FILLING ((size_t) -2) + +static size_t mime_subparts_read(char *buffer, size_t size, size_t nitems, + void *instream, bool *hasread); + +/* Encoders. */ +static size_t encoder_nop_read(char *buffer, size_t size, bool ateof, + curl_mimepart *part); +static curl_off_t encoder_nop_size(curl_mimepart *part); +static size_t encoder_7bit_read(char *buffer, size_t size, bool ateof, + curl_mimepart *part); +static size_t encoder_base64_read(char *buffer, size_t size, bool ateof, + curl_mimepart *part); +static curl_off_t encoder_base64_size(curl_mimepart *part); +static size_t encoder_qp_read(char *buffer, size_t size, bool ateof, + curl_mimepart *part); +static curl_off_t encoder_qp_size(curl_mimepart *part); +static curl_off_t mime_size(curl_mimepart *part); + +static const struct mime_encoder encoders[] = { + {"binary", encoder_nop_read, encoder_nop_size}, + {"8bit", encoder_nop_read, encoder_nop_size}, + {"7bit", encoder_7bit_read, encoder_nop_size}, + {"base64", encoder_base64_read, encoder_base64_size}, + {"quoted-printable", encoder_qp_read, encoder_qp_size}, + {ZERO_NULL, ZERO_NULL, ZERO_NULL} +}; + +/* Base64 encoding table */ +static const char base64enc[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +/* Quoted-printable character class table. + * + * We cannot rely on ctype functions since quoted-printable input data + * is assumed to be ascii-compatible, even on non-ascii platforms. */ +#define QP_OK 1 /* Can be represented by itself. */ +#define QP_SP 2 /* Space or tab. */ +#define QP_CR 3 /* Carriage return. */ +#define QP_LF 4 /* Line-feed. */ +static const unsigned char qp_class[] = { + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 - 07 */ + 0, QP_SP, QP_LF, 0, 0, QP_CR, 0, 0, /* 08 - 0F */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 10 - 17 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 18 - 1F */ + QP_SP, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 20 - 27 */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 28 - 2F */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 30 - 37 */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, 0 , QP_OK, QP_OK, /* 38 - 3F */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 40 - 47 */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 48 - 4F */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 50 - 57 */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 58 - 5F */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 60 - 67 */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 68 - 6F */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 70 - 77 */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, 0, /* 78 - 7F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 8F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 90 - 9F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A0 - AF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0 - BF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0 - CF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0 - DF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0 - EF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */ +}; + + +/* Binary --> hexadecimal ASCII table. */ +static const char aschex[] = + "\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x41\x42\x43\x44\x45\x46"; + + + +#ifndef __VMS +#define filesize(name, stat_data) (stat_data.st_size) +#define fopen_read fopen + +#else + +#include +/* + * get_vms_file_size does what it takes to get the real size of the file + * + * For fixed files, find out the size of the EOF block and adjust. + * + * For all others, have to read the entire file in, discarding the contents. + * Most posted text files will be small, and binary files like zlib archives + * and CD/DVD images should be either a STREAM_LF format or a fixed format. + * + */ +curl_off_t VmsRealFileSize(const char *name, + const struct_stat *stat_buf) +{ + char buffer[8192]; + curl_off_t count; + int ret_stat; + FILE * file; + + file = fopen(name, FOPEN_READTEXT); /* VMS */ + if(!file) + return 0; + + count = 0; + ret_stat = 1; + while(ret_stat > 0) { + ret_stat = fread(buffer, 1, sizeof(buffer), file); + if(ret_stat) + count += ret_stat; + } + fclose(file); + + return count; +} + +/* + * + * VmsSpecialSize checks to see if the stat st_size can be trusted and + * if not to call a routine to get the correct size. + * + */ +static curl_off_t VmsSpecialSize(const char *name, + const struct_stat *stat_buf) +{ + switch(stat_buf->st_fab_rfm) { + case FAB$C_VAR: + case FAB$C_VFC: + return VmsRealFileSize(name, stat_buf); + break; + default: + return stat_buf->st_size; + } +} + +#define filesize(name, stat_data) VmsSpecialSize(name, &stat_data) + +/* + * vmsfopenread + * + * For upload to work as expected on VMS, different optional + * parameters must be added to the fopen command based on + * record format of the file. + * + */ +static FILE * vmsfopenread(const char *file, const char *mode) +{ + struct_stat statbuf; + int result; + + result = stat(file, &statbuf); + + switch(statbuf.st_fab_rfm) { + case FAB$C_VAR: + case FAB$C_VFC: + case FAB$C_STMCR: + return fopen(file, FOPEN_READTEXT); /* VMS */ + break; + default: + return fopen(file, FOPEN_READTEXT, "rfm=stmlf", "ctx=stm"); + } +} + +#define fopen_read vmsfopenread +#endif + + +#ifndef HAVE_BASENAME +/* + (Quote from The Open Group Base Specifications Issue 6 IEEE Std 1003.1, 2004 + Edition) + + The basename() function shall take the pathname pointed to by path and + return a pointer to the final component of the pathname, deleting any + trailing '/' characters. + + If the string pointed to by path consists entirely of the '/' character, + basename() shall return a pointer to the string "/". If the string pointed + to by path is exactly "//", it is implementation-defined whether '/' or "//" + is returned. + + If path is a null pointer or points to an empty string, basename() shall + return a pointer to the string ".". + + The basename() function may modify the string pointed to by path, and may + return a pointer to static storage that may then be overwritten by a + subsequent call to basename(). + + The basename() function need not be reentrant. A function that is not + required to be reentrant is not required to be thread-safe. + +*/ +static char *Curl_basename(char *path) +{ + /* Ignore all the details above for now and make a quick and simple + implementation here */ + char *s1; + char *s2; + + s1 = strrchr(path, '/'); + s2 = strrchr(path, '\\'); + + if(s1 && s2) { + path = (s1 > s2? s1 : s2) + 1; + } + else if(s1) + path = s1 + 1; + else if(s2) + path = s2 + 1; + + return path; +} + +#define basename(x) Curl_basename((x)) +#endif + + +/* Set readback state. */ +static void mimesetstate(struct mime_state *state, + enum mimestate tok, void *ptr) +{ + state->state = tok; + state->ptr = ptr; + state->offset = 0; +} + + +/* Escape header string into allocated memory. */ +static char *escape_string(struct Curl_easy *data, + const char *src, enum mimestrategy strategy) +{ + CURLcode result; + struct dynbuf db; + const char * const *table; + const char * const *p; + /* replace first character by rest of string. */ + static const char * const mimetable[] = { + "\\\\\\", + "\"\\\"", + NULL + }; + /* WHATWG HTML living standard 4.10.21.8 2 specifies: + For field names and filenames for file fields, the result of the + encoding in the previous bullet point must be escaped by replacing + any 0x0A (LF) bytes with the byte sequence `%0A`, 0x0D (CR) with `%0D` + and 0x22 (") with `%22`. + The user agent must not perform any other escapes. */ + static const char * const formtable[] = { + "\"%22", + "\r%0D", + "\n%0A", + NULL + }; + + table = formtable; + /* data can be NULL when this function is called indirectly from + curl_formget(). */ + if(strategy == MIMESTRATEGY_MAIL || (data && (data->set.mime_formescape))) + table = mimetable; + + Curl_dyn_init(&db, CURL_MAX_INPUT_LENGTH); + + for(result = Curl_dyn_addn(&db, STRCONST("")); !result && *src; src++) { + for(p = table; *p && **p != *src; p++) + ; + + if(*p) + result = Curl_dyn_add(&db, *p + 1); + else + result = Curl_dyn_addn(&db, src, 1); + } + + return Curl_dyn_ptr(&db); +} + +/* Check if header matches. */ +static char *match_header(struct curl_slist *hdr, const char *lbl, size_t len) +{ + char *value = NULL; + + if(strncasecompare(hdr->data, lbl, len) && hdr->data[len] == ':') + for(value = hdr->data + len + 1; *value == ' '; value++) + ; + return value; +} + +/* Get a header from an slist. */ +static char *search_header(struct curl_slist *hdrlist, + const char *hdr, size_t len) +{ + char *value = NULL; + + for(; !value && hdrlist; hdrlist = hdrlist->next) + value = match_header(hdrlist, hdr, len); + + return value; +} + +static char *strippath(const char *fullfile) +{ + char *filename; + char *base; + filename = strdup(fullfile); /* duplicate since basename() may ruin the + buffer it works on */ + if(!filename) + return NULL; + base = strdup(basename(filename)); + + free(filename); /* free temporary buffer */ + + return base; /* returns an allocated string or NULL ! */ +} + +/* Initialize data encoder state. */ +static void cleanup_encoder_state(struct mime_encoder_state *p) +{ + p->pos = 0; + p->bufbeg = 0; + p->bufend = 0; +} + + +/* Dummy encoder. This is used for 8bit and binary content encodings. */ +static size_t encoder_nop_read(char *buffer, size_t size, bool ateof, + struct curl_mimepart *part) +{ + struct mime_encoder_state *st = &part->encstate; + size_t insize = st->bufend - st->bufbeg; + + (void) ateof; + + if(!size) + return STOP_FILLING; + + if(size > insize) + size = insize; + + if(size) + memcpy(buffer, st->buf + st->bufbeg, size); + + st->bufbeg += size; + return size; +} + +static curl_off_t encoder_nop_size(curl_mimepart *part) +{ + return part->datasize; +} + + +/* 7bit encoder: the encoder is just a data validity check. */ +static size_t encoder_7bit_read(char *buffer, size_t size, bool ateof, + curl_mimepart *part) +{ + struct mime_encoder_state *st = &part->encstate; + size_t cursize = st->bufend - st->bufbeg; + + (void) ateof; + + if(!size) + return STOP_FILLING; + + if(size > cursize) + size = cursize; + + for(cursize = 0; cursize < size; cursize++) { + *buffer = st->buf[st->bufbeg]; + if(*buffer++ & 0x80) + return cursize? cursize: READ_ERROR; + st->bufbeg++; + } + + return cursize; +} + + +/* Base64 content encoder. */ +static size_t encoder_base64_read(char *buffer, size_t size, bool ateof, + curl_mimepart *part) +{ + struct mime_encoder_state *st = &part->encstate; + size_t cursize = 0; + int i; + char *ptr = buffer; + + while(st->bufbeg < st->bufend) { + /* Line full ? */ + if(st->pos > MAX_ENCODED_LINE_LENGTH - 4) { + /* Yes, we need 2 characters for CRLF. */ + if(size < 2) { + if(!cursize) + return STOP_FILLING; + break; + } + *ptr++ = '\r'; + *ptr++ = '\n'; + st->pos = 0; + cursize += 2; + size -= 2; + } + + /* Be sure there is enough space and input data for a base64 group. */ + if(size < 4) { + if(!cursize) + return STOP_FILLING; + break; + } + if(st->bufend - st->bufbeg < 3) + break; + + /* Encode three bytes as four characters. */ + i = st->buf[st->bufbeg++] & 0xFF; + i = (i << 8) | (st->buf[st->bufbeg++] & 0xFF); + i = (i << 8) | (st->buf[st->bufbeg++] & 0xFF); + *ptr++ = base64enc[(i >> 18) & 0x3F]; + *ptr++ = base64enc[(i >> 12) & 0x3F]; + *ptr++ = base64enc[(i >> 6) & 0x3F]; + *ptr++ = base64enc[i & 0x3F]; + cursize += 4; + st->pos += 4; + size -= 4; + } + + /* If at eof, we have to flush the buffered data. */ + if(ateof) { + if(size < 4) { + if(!cursize) + return STOP_FILLING; + } + else { + /* Buffered data size can only be 0, 1 or 2. */ + ptr[2] = ptr[3] = '='; + i = 0; + + /* If there is buffered data */ + if(st->bufend != st->bufbeg) { + + if(st->bufend - st->bufbeg == 2) + i = (st->buf[st->bufbeg + 1] & 0xFF) << 8; + + i |= (st->buf[st->bufbeg] & 0xFF) << 16; + ptr[0] = base64enc[(i >> 18) & 0x3F]; + ptr[1] = base64enc[(i >> 12) & 0x3F]; + if(++st->bufbeg != st->bufend) { + ptr[2] = base64enc[(i >> 6) & 0x3F]; + st->bufbeg++; + } + cursize += 4; + st->pos += 4; + } + } + } + + return cursize; +} + +static curl_off_t encoder_base64_size(curl_mimepart *part) +{ + curl_off_t size = part->datasize; + + if(size <= 0) + return size; /* Unknown size or no data. */ + + /* Compute base64 character count. */ + size = 4 * (1 + (size - 1) / 3); + + /* Effective character count must include CRLFs. */ + return size + 2 * ((size - 1) / MAX_ENCODED_LINE_LENGTH); +} + + +/* Quoted-printable lookahead. + * + * Check if a CRLF or end of data is in input buffer at current position + n. + * Return -1 if more data needed, 1 if CRLF or end of data, else 0. + */ +static int qp_lookahead_eol(struct mime_encoder_state *st, int ateof, size_t n) +{ + n += st->bufbeg; + if(n >= st->bufend && ateof) + return 1; + if(n + 2 > st->bufend) + return ateof? 0: -1; + if(qp_class[st->buf[n] & 0xFF] == QP_CR && + qp_class[st->buf[n + 1] & 0xFF] == QP_LF) + return 1; + return 0; +} + +/* Quoted-printable encoder. */ +static size_t encoder_qp_read(char *buffer, size_t size, bool ateof, + curl_mimepart *part) +{ + struct mime_encoder_state *st = &part->encstate; + char *ptr = buffer; + size_t cursize = 0; + int softlinebreak; + char buf[4]; + + /* On all platforms, input is supposed to be ASCII compatible: for this + reason, we use hexadecimal ASCII codes in this function rather than + character constants that can be interpreted as non-ascii on some + platforms. Preserve ASCII encoding on output too. */ + while(st->bufbeg < st->bufend) { + size_t len = 1; + size_t consumed = 1; + int i = st->buf[st->bufbeg]; + buf[0] = (char) i; + buf[1] = aschex[(i >> 4) & 0xF]; + buf[2] = aschex[i & 0xF]; + + switch(qp_class[st->buf[st->bufbeg] & 0xFF]) { + case QP_OK: /* Not a special character. */ + break; + case QP_SP: /* Space or tab. */ + /* Spacing must be escaped if followed by CRLF. */ + switch(qp_lookahead_eol(st, ateof, 1)) { + case -1: /* More input data needed. */ + return cursize; + case 0: /* No encoding needed. */ + break; + default: /* CRLF after space or tab. */ + buf[0] = '\x3D'; /* '=' */ + len = 3; + break; + } + break; + case QP_CR: /* Carriage return. */ + /* If followed by a line-feed, output the CRLF pair. + Else escape it. */ + switch(qp_lookahead_eol(st, ateof, 0)) { + case -1: /* Need more data. */ + return cursize; + case 1: /* CRLF found. */ + buf[len++] = '\x0A'; /* Append '\n'. */ + consumed = 2; + break; + default: /* Not followed by LF: escape. */ + buf[0] = '\x3D'; /* '=' */ + len = 3; + break; + } + break; + default: /* Character must be escaped. */ + buf[0] = '\x3D'; /* '=' */ + len = 3; + break; + } + + /* Be sure the encoded character fits within maximum line length. */ + if(buf[len - 1] != '\x0A') { /* '\n' */ + softlinebreak = st->pos + len > MAX_ENCODED_LINE_LENGTH; + if(!softlinebreak && st->pos + len == MAX_ENCODED_LINE_LENGTH) { + /* We may use the current line only if end of data or followed by + a CRLF. */ + switch(qp_lookahead_eol(st, ateof, consumed)) { + case -1: /* Need more data. */ + return cursize; + case 0: /* Not followed by a CRLF. */ + softlinebreak = 1; + break; + } + } + if(softlinebreak) { + strcpy(buf, "\x3D\x0D\x0A"); /* "=\r\n" */ + len = 3; + consumed = 0; + } + } + + /* If the output buffer would overflow, do not store. */ + if(len > size) { + if(!cursize) + return STOP_FILLING; + break; + } + + /* Append to output buffer. */ + memcpy(ptr, buf, len); + cursize += len; + ptr += len; + size -= len; + st->pos += len; + if(buf[len - 1] == '\x0A') /* '\n' */ + st->pos = 0; + st->bufbeg += consumed; + } + + return cursize; +} + +static curl_off_t encoder_qp_size(curl_mimepart *part) +{ + /* Determining the size can only be done by reading the data: unless the + data size is 0, we return it as unknown (-1). */ + return part->datasize? -1: 0; +} + + +/* In-memory data callbacks. */ +/* Argument is a pointer to the mime part. */ +static size_t mime_mem_read(char *buffer, size_t size, size_t nitems, + void *instream) +{ + curl_mimepart *part = (curl_mimepart *) instream; + size_t sz = curlx_sotouz(part->datasize - part->state.offset); + (void) size; /* Always 1.*/ + + if(!nitems) + return STOP_FILLING; + + if(sz > nitems) + sz = nitems; + + if(sz) + memcpy(buffer, part->data + curlx_sotouz(part->state.offset), sz); + + return sz; +} + +static int mime_mem_seek(void *instream, curl_off_t offset, int whence) +{ + curl_mimepart *part = (curl_mimepart *) instream; + + switch(whence) { + case SEEK_CUR: + offset += part->state.offset; + break; + case SEEK_END: + offset += part->datasize; + break; + } + + if(offset < 0 || offset > part->datasize) + return CURL_SEEKFUNC_FAIL; + + part->state.offset = offset; + return CURL_SEEKFUNC_OK; +} + +static void mime_mem_free(void *ptr) +{ + Curl_safefree(((curl_mimepart *) ptr)->data); +} + + +/* Named file callbacks. */ +/* Argument is a pointer to the mime part. */ +static int mime_open_file(curl_mimepart *part) +{ + /* Open a MIMEKIND_FILE part. */ + + if(part->fp) + return 0; + part->fp = fopen_read(part->data, "rb"); + return part->fp? 0: -1; +} + +static size_t mime_file_read(char *buffer, size_t size, size_t nitems, + void *instream) +{ + curl_mimepart *part = (curl_mimepart *) instream; + + if(!nitems) + return STOP_FILLING; + + if(mime_open_file(part)) + return READ_ERROR; + + return fread(buffer, size, nitems, part->fp); +} + +static int mime_file_seek(void *instream, curl_off_t offset, int whence) +{ + curl_mimepart *part = (curl_mimepart *) instream; + + if(whence == SEEK_SET && !offset && !part->fp) + return CURL_SEEKFUNC_OK; /* Not open: implicitly already at BOF. */ + + if(mime_open_file(part)) + return CURL_SEEKFUNC_FAIL; + + return fseek(part->fp, (long) offset, whence)? + CURL_SEEKFUNC_CANTSEEK: CURL_SEEKFUNC_OK; +} + +static void mime_file_free(void *ptr) +{ + curl_mimepart *part = (curl_mimepart *) ptr; + + if(part->fp) { + fclose(part->fp); + part->fp = NULL; + } + Curl_safefree(part->data); +} + + +/* Subparts callbacks. */ +/* Argument is a pointer to the mime structure. */ + +/* Readback a byte string segment. */ +static size_t readback_bytes(struct mime_state *state, + char *buffer, size_t bufsize, + const char *bytes, size_t numbytes, + const char *trail, size_t traillen) +{ + size_t sz; + size_t offset = curlx_sotouz(state->offset); + + if(numbytes > offset) { + sz = numbytes - offset; + bytes += offset; + } + else { + sz = offset - numbytes; + if(sz >= traillen) + return 0; + bytes = trail + sz; + sz = traillen - sz; + } + + if(sz > bufsize) + sz = bufsize; + + memcpy(buffer, bytes, sz); + state->offset += sz; + return sz; +} + +/* Read a non-encoded part content. */ +static size_t read_part_content(curl_mimepart *part, + char *buffer, size_t bufsize, bool *hasread) +{ + size_t sz = 0; + + switch(part->lastreadstatus) { + case 0: + case CURL_READFUNC_ABORT: + case CURL_READFUNC_PAUSE: + case READ_ERROR: + return part->lastreadstatus; + default: + break; + } + + /* If we can determine we are at end of part data, spare a read. */ + if(part->datasize != (curl_off_t) -1 && + part->state.offset >= part->datasize) { + /* sz is already zero. */ + } + else { + switch(part->kind) { + case MIMEKIND_MULTIPART: + /* + * Cannot be processed as other kinds since read function requires + * an additional parameter and is highly recursive. + */ + sz = mime_subparts_read(buffer, 1, bufsize, part->arg, hasread); + break; + case MIMEKIND_FILE: + if(part->fp && feof(part->fp)) + break; /* At EOF. */ + FALLTHROUGH(); + default: + if(part->readfunc) { + if(!(part->flags & MIME_FAST_READ)) { + if(*hasread) + return STOP_FILLING; + *hasread = TRUE; + } + sz = part->readfunc(buffer, 1, bufsize, part->arg); + } + break; + } + } + + switch(sz) { + case STOP_FILLING: + break; + case 0: + case CURL_READFUNC_ABORT: + case CURL_READFUNC_PAUSE: + case READ_ERROR: + part->lastreadstatus = sz; + break; + default: + part->state.offset += sz; + part->lastreadstatus = sz; + break; + } + + return sz; +} + +/* Read and encode part content. */ +static size_t read_encoded_part_content(curl_mimepart *part, char *buffer, + size_t bufsize, bool *hasread) +{ + struct mime_encoder_state *st = &part->encstate; + size_t cursize = 0; + size_t sz; + bool ateof = FALSE; + + for(;;) { + if(st->bufbeg < st->bufend || ateof) { + /* Encode buffered data. */ + sz = part->encoder->encodefunc(buffer, bufsize, ateof, part); + switch(sz) { + case 0: + if(ateof) + return cursize; + break; + case READ_ERROR: + case STOP_FILLING: + return cursize? cursize: sz; + default: + cursize += sz; + buffer += sz; + bufsize -= sz; + continue; + } + } + + /* We need more data in input buffer. */ + if(st->bufbeg) { + size_t len = st->bufend - st->bufbeg; + + if(len) + memmove(st->buf, st->buf + st->bufbeg, len); + st->bufbeg = 0; + st->bufend = len; + } + if(st->bufend >= sizeof(st->buf)) + return cursize? cursize: READ_ERROR; /* Buffer full. */ + sz = read_part_content(part, st->buf + st->bufend, + sizeof(st->buf) - st->bufend, hasread); + switch(sz) { + case 0: + ateof = TRUE; + break; + case CURL_READFUNC_ABORT: + case CURL_READFUNC_PAUSE: + case READ_ERROR: + case STOP_FILLING: + return cursize? cursize: sz; + default: + st->bufend += sz; + break; + } + } + + /* NOTREACHED */ +} + +/* Readback a mime part. */ +static size_t readback_part(curl_mimepart *part, + char *buffer, size_t bufsize, bool *hasread) +{ + size_t cursize = 0; + + /* Readback from part. */ + + while(bufsize) { + size_t sz = 0; + struct curl_slist *hdr = (struct curl_slist *) part->state.ptr; + switch(part->state.state) { + case MIMESTATE_BEGIN: + mimesetstate(&part->state, + (part->flags & MIME_BODY_ONLY)? + MIMESTATE_BODY: MIMESTATE_CURLHEADERS, + part->curlheaders); + break; + case MIMESTATE_USERHEADERS: + if(!hdr) { + mimesetstate(&part->state, MIMESTATE_EOH, NULL); + break; + } + if(match_header(hdr, "Content-Type", 12)) { + mimesetstate(&part->state, MIMESTATE_USERHEADERS, hdr->next); + break; + } + FALLTHROUGH(); + case MIMESTATE_CURLHEADERS: + if(!hdr) + mimesetstate(&part->state, MIMESTATE_USERHEADERS, part->userheaders); + else { + sz = readback_bytes(&part->state, buffer, bufsize, + hdr->data, strlen(hdr->data), STRCONST("\r\n")); + if(!sz) + mimesetstate(&part->state, part->state.state, hdr->next); + } + break; + case MIMESTATE_EOH: + sz = readback_bytes(&part->state, buffer, bufsize, STRCONST("\r\n"), + STRCONST("")); + if(!sz) + mimesetstate(&part->state, MIMESTATE_BODY, NULL); + break; + case MIMESTATE_BODY: + cleanup_encoder_state(&part->encstate); + mimesetstate(&part->state, MIMESTATE_CONTENT, NULL); + break; + case MIMESTATE_CONTENT: + if(part->encoder) + sz = read_encoded_part_content(part, buffer, bufsize, hasread); + else + sz = read_part_content(part, buffer, bufsize, hasread); + switch(sz) { + case 0: + mimesetstate(&part->state, MIMESTATE_END, NULL); + /* Try sparing open file descriptors. */ + if(part->kind == MIMEKIND_FILE && part->fp) { + fclose(part->fp); + part->fp = NULL; + } + FALLTHROUGH(); + case CURL_READFUNC_ABORT: + case CURL_READFUNC_PAUSE: + case READ_ERROR: + case STOP_FILLING: + return cursize? cursize: sz; + } + break; + case MIMESTATE_END: + return cursize; + default: + break; /* Other values not in part state. */ + } + + /* Bump buffer and counters according to read size. */ + cursize += sz; + buffer += sz; + bufsize -= sz; + } + + return cursize; +} + +/* Readback from mime. Warning: not a read callback function. */ +static size_t mime_subparts_read(char *buffer, size_t size, size_t nitems, + void *instream, bool *hasread) +{ + curl_mime *mime = (curl_mime *) instream; + size_t cursize = 0; + (void) size; /* Always 1. */ + + while(nitems) { + size_t sz = 0; + curl_mimepart *part = mime->state.ptr; + switch(mime->state.state) { + case MIMESTATE_BEGIN: + case MIMESTATE_BODY: + mimesetstate(&mime->state, MIMESTATE_BOUNDARY1, mime->firstpart); + /* The first boundary always follows the header termination empty line, + so is always preceded by a CRLF. We can then spare 2 characters + by skipping the leading CRLF in boundary. */ + mime->state.offset += 2; + break; + case MIMESTATE_BOUNDARY1: + sz = readback_bytes(&mime->state, buffer, nitems, STRCONST("\r\n--"), + STRCONST("")); + if(!sz) + mimesetstate(&mime->state, MIMESTATE_BOUNDARY2, part); + break; + case MIMESTATE_BOUNDARY2: + if(part) + sz = readback_bytes(&mime->state, buffer, nitems, mime->boundary, + MIME_BOUNDARY_LEN, STRCONST("\r\n")); + else + sz = readback_bytes(&mime->state, buffer, nitems, mime->boundary, + MIME_BOUNDARY_LEN, STRCONST("--\r\n")); + if(!sz) { + mimesetstate(&mime->state, MIMESTATE_CONTENT, part); + } + break; + case MIMESTATE_CONTENT: + if(!part) { + mimesetstate(&mime->state, MIMESTATE_END, NULL); + break; + } + sz = readback_part(part, buffer, nitems, hasread); + switch(sz) { + case CURL_READFUNC_ABORT: + case CURL_READFUNC_PAUSE: + case READ_ERROR: + case STOP_FILLING: + return cursize? cursize: sz; + case 0: + mimesetstate(&mime->state, MIMESTATE_BOUNDARY1, part->nextpart); + break; + } + break; + case MIMESTATE_END: + return cursize; + default: + break; /* other values not used in mime state. */ + } + + /* Bump buffer and counters according to read size. */ + cursize += sz; + buffer += sz; + nitems -= sz; + } + + return cursize; +} + +static int mime_part_rewind(curl_mimepart *part) +{ + int res = CURL_SEEKFUNC_OK; + enum mimestate targetstate = MIMESTATE_BEGIN; + + if(part->flags & MIME_BODY_ONLY) + targetstate = MIMESTATE_BODY; + cleanup_encoder_state(&part->encstate); + if(part->state.state > targetstate) { + res = CURL_SEEKFUNC_CANTSEEK; + if(part->seekfunc) { + res = part->seekfunc(part->arg, (curl_off_t) 0, SEEK_SET); + switch(res) { + case CURL_SEEKFUNC_OK: + case CURL_SEEKFUNC_FAIL: + case CURL_SEEKFUNC_CANTSEEK: + break; + case -1: /* For fseek() error. */ + res = CURL_SEEKFUNC_CANTSEEK; + break; + default: + res = CURL_SEEKFUNC_FAIL; + break; + } + } + } + + if(res == CURL_SEEKFUNC_OK) + mimesetstate(&part->state, targetstate, NULL); + + part->lastreadstatus = 1; /* Successful read status. */ + return res; +} + +static int mime_subparts_seek(void *instream, curl_off_t offset, int whence) +{ + curl_mime *mime = (curl_mime *) instream; + curl_mimepart *part; + int result = CURL_SEEKFUNC_OK; + + if(whence != SEEK_SET || offset) + return CURL_SEEKFUNC_CANTSEEK; /* Only support full rewind. */ + + if(mime->state.state == MIMESTATE_BEGIN) + return CURL_SEEKFUNC_OK; /* Already rewound. */ + + for(part = mime->firstpart; part; part = part->nextpart) { + int res = mime_part_rewind(part); + if(res != CURL_SEEKFUNC_OK) + result = res; + } + + if(result == CURL_SEEKFUNC_OK) + mimesetstate(&mime->state, MIMESTATE_BEGIN, NULL); + + return result; +} + +/* Release part content. */ +static void cleanup_part_content(curl_mimepart *part) +{ + if(part->freefunc) + part->freefunc(part->arg); + + part->readfunc = NULL; + part->seekfunc = NULL; + part->freefunc = NULL; + part->arg = (void *) part; /* Defaults to part itself. */ + part->data = NULL; + part->fp = NULL; + part->datasize = (curl_off_t) 0; /* No size yet. */ + cleanup_encoder_state(&part->encstate); + part->kind = MIMEKIND_NONE; + part->flags &= ~MIME_FAST_READ; + part->lastreadstatus = 1; /* Successful read status. */ + part->state.state = MIMESTATE_BEGIN; +} + +static void mime_subparts_free(void *ptr) +{ + curl_mime *mime = (curl_mime *) ptr; + + if(mime && mime->parent) { + mime->parent->freefunc = NULL; /* Be sure we won't be called again. */ + cleanup_part_content(mime->parent); /* Avoid dangling pointer in part. */ + } + curl_mime_free(mime); +} + +/* Do not free subparts: unbind them. This is used for the top level only. */ +static void mime_subparts_unbind(void *ptr) +{ + curl_mime *mime = (curl_mime *) ptr; + + if(mime && mime->parent) { + mime->parent->freefunc = NULL; /* Be sure we won't be called again. */ + cleanup_part_content(mime->parent); /* Avoid dangling pointer in part. */ + mime->parent = NULL; + } +} + + +void Curl_mime_cleanpart(curl_mimepart *part) +{ + if(part) { + cleanup_part_content(part); + curl_slist_free_all(part->curlheaders); + if(part->flags & MIME_USERHEADERS_OWNER) + curl_slist_free_all(part->userheaders); + Curl_safefree(part->mimetype); + Curl_safefree(part->name); + Curl_safefree(part->filename); + Curl_mime_initpart(part); + } +} + +/* Recursively delete a mime handle and its parts. */ +void curl_mime_free(curl_mime *mime) +{ + curl_mimepart *part; + + if(mime) { + mime_subparts_unbind(mime); /* Be sure it's not referenced anymore. */ + while(mime->firstpart) { + part = mime->firstpart; + mime->firstpart = part->nextpart; + Curl_mime_cleanpart(part); + free(part); + } + free(mime); + } +} + +CURLcode Curl_mime_duppart(struct Curl_easy *data, + curl_mimepart *dst, const curl_mimepart *src) +{ + curl_mime *mime; + curl_mimepart *d; + const curl_mimepart *s; + CURLcode res = CURLE_OK; + + DEBUGASSERT(dst); + + /* Duplicate content. */ + switch(src->kind) { + case MIMEKIND_NONE: + break; + case MIMEKIND_DATA: + res = curl_mime_data(dst, src->data, (size_t) src->datasize); + break; + case MIMEKIND_FILE: + res = curl_mime_filedata(dst, src->data); + /* Do not abort duplication if file is not readable. */ + if(res == CURLE_READ_ERROR) + res = CURLE_OK; + break; + case MIMEKIND_CALLBACK: + res = curl_mime_data_cb(dst, src->datasize, src->readfunc, + src->seekfunc, src->freefunc, src->arg); + break; + case MIMEKIND_MULTIPART: + /* No one knows about the cloned subparts, thus always attach ownership + to the part. */ + mime = curl_mime_init(data); + res = mime? curl_mime_subparts(dst, mime): CURLE_OUT_OF_MEMORY; + + /* Duplicate subparts. */ + for(s = ((curl_mime *) src->arg)->firstpart; !res && s; s = s->nextpart) { + d = curl_mime_addpart(mime); + res = d? Curl_mime_duppart(data, d, s): CURLE_OUT_OF_MEMORY; + } + break; + default: /* Invalid kind: should not occur. */ + DEBUGF(infof(data, "invalid MIMEKIND* attempt")); + res = CURLE_BAD_FUNCTION_ARGUMENT; /* Internal error? */ + break; + } + + /* Duplicate headers. */ + if(!res && src->userheaders) { + struct curl_slist *hdrs = Curl_slist_duplicate(src->userheaders); + + if(!hdrs) + res = CURLE_OUT_OF_MEMORY; + else { + /* No one but this procedure knows about the new header list, + so always take ownership. */ + res = curl_mime_headers(dst, hdrs, TRUE); + if(res) + curl_slist_free_all(hdrs); + } + } + + if(!res) { + /* Duplicate other fields. */ + dst->encoder = src->encoder; + res = curl_mime_type(dst, src->mimetype); + } + if(!res) + res = curl_mime_name(dst, src->name); + if(!res) + res = curl_mime_filename(dst, src->filename); + + /* If an error occurred, rollback. */ + if(res) + Curl_mime_cleanpart(dst); + + return res; +} + +/* + * Mime build functions. + */ + +/* Create a mime handle. */ +curl_mime *curl_mime_init(struct Curl_easy *easy) +{ + curl_mime *mime; + + mime = (curl_mime *) malloc(sizeof(*mime)); + + if(mime) { + mime->parent = NULL; + mime->firstpart = NULL; + mime->lastpart = NULL; + + memset(mime->boundary, '-', MIME_BOUNDARY_DASHES); + if(Curl_rand_alnum(easy, + (unsigned char *) &mime->boundary[MIME_BOUNDARY_DASHES], + MIME_RAND_BOUNDARY_CHARS + 1)) { + /* failed to get random separator, bail out */ + free(mime); + return NULL; + } + mimesetstate(&mime->state, MIMESTATE_BEGIN, NULL); + } + + return mime; +} + +/* Initialize a mime part. */ +void Curl_mime_initpart(curl_mimepart *part) +{ + memset((char *) part, 0, sizeof(*part)); + part->lastreadstatus = 1; /* Successful read status. */ + mimesetstate(&part->state, MIMESTATE_BEGIN, NULL); +} + +/* Create a mime part and append it to a mime handle's part list. */ +curl_mimepart *curl_mime_addpart(curl_mime *mime) +{ + curl_mimepart *part; + + if(!mime) + return NULL; + + part = (curl_mimepart *) malloc(sizeof(*part)); + + if(part) { + Curl_mime_initpart(part); + part->parent = mime; + + if(mime->lastpart) + mime->lastpart->nextpart = part; + else + mime->firstpart = part; + + mime->lastpart = part; + } + + return part; +} + +/* Set mime part name. */ +CURLcode curl_mime_name(curl_mimepart *part, const char *name) +{ + if(!part) + return CURLE_BAD_FUNCTION_ARGUMENT; + + Curl_safefree(part->name); + + if(name) { + part->name = strdup(name); + if(!part->name) + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} + +/* Set mime part remote file name. */ +CURLcode curl_mime_filename(curl_mimepart *part, const char *filename) +{ + if(!part) + return CURLE_BAD_FUNCTION_ARGUMENT; + + Curl_safefree(part->filename); + + if(filename) { + part->filename = strdup(filename); + if(!part->filename) + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} + +/* Set mime part content from memory data. */ +CURLcode curl_mime_data(curl_mimepart *part, + const char *ptr, size_t datasize) +{ + if(!part) + return CURLE_BAD_FUNCTION_ARGUMENT; + + cleanup_part_content(part); + + if(ptr) { + if(datasize == CURL_ZERO_TERMINATED) + datasize = strlen(ptr); + + part->data = Curl_memdup0(ptr, datasize); + if(!part->data) + return CURLE_OUT_OF_MEMORY; + + part->datasize = datasize; + part->readfunc = mime_mem_read; + part->seekfunc = mime_mem_seek; + part->freefunc = mime_mem_free; + part->flags |= MIME_FAST_READ; + part->kind = MIMEKIND_DATA; + } + + return CURLE_OK; +} + +/* Set mime part content from named local file. */ +CURLcode curl_mime_filedata(curl_mimepart *part, const char *filename) +{ + CURLcode result = CURLE_OK; + + if(!part) + return CURLE_BAD_FUNCTION_ARGUMENT; + + cleanup_part_content(part); + + if(filename) { + char *base; + struct_stat sbuf; + + if(stat(filename, &sbuf)) + result = CURLE_READ_ERROR; + else { + part->data = strdup(filename); + if(!part->data) + result = CURLE_OUT_OF_MEMORY; + else { + part->datasize = -1; + if(S_ISREG(sbuf.st_mode)) { + part->datasize = filesize(filename, sbuf); + part->seekfunc = mime_file_seek; + } + + part->readfunc = mime_file_read; + part->freefunc = mime_file_free; + part->kind = MIMEKIND_FILE; + + /* As a side effect, set the filename to the current file's base name. + It is possible to withdraw this by explicitly calling + curl_mime_filename() with a NULL filename argument after the current + call. */ + base = strippath(filename); + if(!base) + result = CURLE_OUT_OF_MEMORY; + else { + result = curl_mime_filename(part, base); + free(base); + } + } + } + } + return result; +} + +/* Set mime part type. */ +CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype) +{ + if(!part) + return CURLE_BAD_FUNCTION_ARGUMENT; + + Curl_safefree(part->mimetype); + + if(mimetype) { + part->mimetype = strdup(mimetype); + if(!part->mimetype) + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} + +/* Set mime data transfer encoder. */ +CURLcode curl_mime_encoder(curl_mimepart *part, const char *encoding) +{ + CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT; + const struct mime_encoder *mep; + + if(!part) + return result; + + part->encoder = NULL; + + if(!encoding) + return CURLE_OK; /* Removing current encoder. */ + + for(mep = encoders; mep->name; mep++) + if(strcasecompare(encoding, mep->name)) { + part->encoder = mep; + result = CURLE_OK; + } + + return result; +} + +/* Set mime part headers. */ +CURLcode curl_mime_headers(curl_mimepart *part, + struct curl_slist *headers, int take_ownership) +{ + if(!part) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(part->flags & MIME_USERHEADERS_OWNER) { + if(part->userheaders != headers) /* Allow setting twice the same list. */ + curl_slist_free_all(part->userheaders); + part->flags &= ~MIME_USERHEADERS_OWNER; + } + part->userheaders = headers; + if(headers && take_ownership) + part->flags |= MIME_USERHEADERS_OWNER; + return CURLE_OK; +} + +/* Set mime part content from callback. */ +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) +{ + if(!part) + return CURLE_BAD_FUNCTION_ARGUMENT; + + cleanup_part_content(part); + + if(readfunc) { + part->readfunc = readfunc; + part->seekfunc = seekfunc; + part->freefunc = freefunc; + part->arg = arg; + part->datasize = datasize; + part->kind = MIMEKIND_CALLBACK; + } + + return CURLE_OK; +} + +/* Set mime part content from subparts. */ +CURLcode Curl_mime_set_subparts(curl_mimepart *part, + curl_mime *subparts, int take_ownership) +{ + curl_mime *root; + + if(!part) + return CURLE_BAD_FUNCTION_ARGUMENT; + + /* Accept setting twice the same subparts. */ + if(part->kind == MIMEKIND_MULTIPART && part->arg == subparts) + return CURLE_OK; + + cleanup_part_content(part); + + if(subparts) { + /* Should not have been attached already. */ + if(subparts->parent) + return CURLE_BAD_FUNCTION_ARGUMENT; + + /* Should not be the part's root. */ + root = part->parent; + if(root) { + while(root->parent && root->parent->parent) + root = root->parent->parent; + if(subparts == root) { + /* Can't add as a subpart of itself. */ + return CURLE_BAD_FUNCTION_ARGUMENT; + } + } + + subparts->parent = part; + /* Subparts are processed internally: no read callback. */ + part->seekfunc = mime_subparts_seek; + part->freefunc = take_ownership? mime_subparts_free: mime_subparts_unbind; + part->arg = subparts; + part->datasize = -1; + part->kind = MIMEKIND_MULTIPART; + } + + return CURLE_OK; +} + +CURLcode curl_mime_subparts(curl_mimepart *part, curl_mime *subparts) +{ + return Curl_mime_set_subparts(part, subparts, TRUE); +} + + +/* Readback from top mime. */ +/* Argument is the dummy top part. */ +size_t Curl_mime_read(char *buffer, size_t size, size_t nitems, void *instream) +{ + curl_mimepart *part = (curl_mimepart *) instream; + size_t ret; + bool hasread; + + (void) size; /* Always 1. */ + + do { + hasread = FALSE; + ret = readback_part(part, buffer, nitems, &hasread); + /* + * If this is not possible to get some data without calling more than + * one read callback (probably because a content encoder is not able to + * deliver a new bunch for the few data accumulated so far), force another + * read until we get enough data or a special exit code. + */ + } while(ret == STOP_FILLING); + + return ret; +} + +/* Rewind mime stream. */ +static CURLcode mime_rewind(curl_mimepart *part) +{ + return mime_part_rewind(part) == CURL_SEEKFUNC_OK? + CURLE_OK: CURLE_SEND_FAIL_REWIND; +} + +/* Compute header list size. */ +static size_t slist_size(struct curl_slist *s, + size_t overhead, const char *skip, size_t skiplen) +{ + size_t size = 0; + + for(; s; s = s->next) + if(!skip || !match_header(s, skip, skiplen)) + size += strlen(s->data) + overhead; + return size; +} + +/* Get/compute multipart size. */ +static curl_off_t multipart_size(curl_mime *mime) +{ + curl_off_t size; + curl_off_t boundarysize; + curl_mimepart *part; + + if(!mime) + return 0; /* Not present -> empty. */ + + boundarysize = 4 + MIME_BOUNDARY_LEN + 2; + size = boundarysize; /* Final boundary - CRLF after headers. */ + + for(part = mime->firstpart; part; part = part->nextpart) { + curl_off_t sz = mime_size(part); + + if(sz < 0) + size = sz; + + if(size >= 0) + size += boundarysize + sz; + } + + return size; +} + +/* Get/compute mime size. */ +static curl_off_t mime_size(curl_mimepart *part) +{ + curl_off_t size; + + if(part->kind == MIMEKIND_MULTIPART) + part->datasize = multipart_size(part->arg); + + size = part->datasize; + + if(part->encoder) + size = part->encoder->sizefunc(part); + + if(size >= 0 && !(part->flags & MIME_BODY_ONLY)) { + /* Compute total part size. */ + size += slist_size(part->curlheaders, 2, NULL, 0); + size += slist_size(part->userheaders, 2, STRCONST("Content-Type")); + size += 2; /* CRLF after headers. */ + } + return size; +} + +/* Add a header. */ +/* VARARGS2 */ +CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...) +{ + struct curl_slist *hdr = NULL; + char *s = NULL; + va_list ap; + + va_start(ap, fmt); + s = curl_mvaprintf(fmt, ap); + va_end(ap); + + if(s) { + hdr = Curl_slist_append_nodup(*slp, s); + if(hdr) + *slp = hdr; + else + free(s); + } + + return hdr? CURLE_OK: CURLE_OUT_OF_MEMORY; +} + +/* Add a content type header. */ +static CURLcode add_content_type(struct curl_slist **slp, + const char *type, const char *boundary) +{ + return Curl_mime_add_header(slp, "Content-Type: %s%s%s", type, + boundary? "; boundary=": "", + boundary? boundary: ""); +} + +const char *Curl_mime_contenttype(const char *filename) +{ + /* + * If no content type was specified, we scan through a few well-known + * extensions and pick the first we match! + */ + struct ContentType { + const char *extension; + const char *type; + }; + static const struct ContentType ctts[] = { + {".gif", "image/gif"}, + {".jpg", "image/jpeg"}, + {".jpeg", "image/jpeg"}, + {".png", "image/png"}, + {".svg", "image/svg+xml"}, + {".txt", "text/plain"}, + {".htm", "text/html"}, + {".html", "text/html"}, + {".pdf", "application/pdf"}, + {".xml", "application/xml"} + }; + + if(filename) { + size_t len1 = strlen(filename); + const char *nameend = filename + len1; + unsigned int i; + + for(i = 0; i < sizeof(ctts) / sizeof(ctts[0]); i++) { + size_t len2 = strlen(ctts[i].extension); + + if(len1 >= len2 && strcasecompare(nameend - len2, ctts[i].extension)) + return ctts[i].type; + } + } + return NULL; +} + +static bool content_type_match(const char *contenttype, + const char *target, size_t len) +{ + if(contenttype && strncasecompare(contenttype, target, len)) + switch(contenttype[len]) { + case '\0': + case '\t': + case '\r': + case '\n': + case ' ': + case ';': + return TRUE; + } + return FALSE; +} + +CURLcode Curl_mime_prepare_headers(struct Curl_easy *data, + curl_mimepart *part, + const char *contenttype, + const char *disposition, + enum mimestrategy strategy) +{ + curl_mime *mime = NULL; + const char *boundary = NULL; + char *customct; + const char *cte = NULL; + CURLcode ret = CURLE_OK; + + /* Get rid of previously prepared headers. */ + curl_slist_free_all(part->curlheaders); + part->curlheaders = NULL; + + /* Be sure we won't access old headers later. */ + if(part->state.state == MIMESTATE_CURLHEADERS) + mimesetstate(&part->state, MIMESTATE_CURLHEADERS, NULL); + + /* Check if content type is specified. */ + customct = part->mimetype; + if(!customct) + customct = search_header(part->userheaders, STRCONST("Content-Type")); + if(customct) + contenttype = customct; + + /* If content type is not specified, try to determine it. */ + if(!contenttype) { + switch(part->kind) { + case MIMEKIND_MULTIPART: + contenttype = MULTIPART_CONTENTTYPE_DEFAULT; + break; + case MIMEKIND_FILE: + contenttype = Curl_mime_contenttype(part->filename); + if(!contenttype) + contenttype = Curl_mime_contenttype(part->data); + if(!contenttype && part->filename) + contenttype = FILE_CONTENTTYPE_DEFAULT; + break; + default: + contenttype = Curl_mime_contenttype(part->filename); + break; + } + } + + if(part->kind == MIMEKIND_MULTIPART) { + mime = (curl_mime *) part->arg; + if(mime) + boundary = mime->boundary; + } + else if(contenttype && !customct && + content_type_match(contenttype, STRCONST("text/plain"))) + if(strategy == MIMESTRATEGY_MAIL || !part->filename) + contenttype = NULL; + + /* Issue content-disposition header only if not already set by caller. */ + if(!search_header(part->userheaders, STRCONST("Content-Disposition"))) { + if(!disposition) + if(part->filename || part->name || + (contenttype && !strncasecompare(contenttype, "multipart/", 10))) + disposition = DISPOSITION_DEFAULT; + if(disposition && curl_strequal(disposition, "attachment") && + !part->name && !part->filename) + disposition = NULL; + if(disposition) { + char *name = NULL; + char *filename = NULL; + + if(part->name) { + name = escape_string(data, part->name, strategy); + if(!name) + ret = CURLE_OUT_OF_MEMORY; + } + if(!ret && part->filename) { + filename = escape_string(data, part->filename, strategy); + if(!filename) + ret = CURLE_OUT_OF_MEMORY; + } + if(!ret) + ret = Curl_mime_add_header(&part->curlheaders, + "Content-Disposition: %s%s%s%s%s%s%s", + disposition, + name? "; name=\"": "", + name? name: "", + name? "\"": "", + filename? "; filename=\"": "", + filename? filename: "", + filename? "\"": ""); + Curl_safefree(name); + Curl_safefree(filename); + if(ret) + return ret; + } + } + + /* Issue Content-Type header. */ + if(contenttype) { + ret = add_content_type(&part->curlheaders, contenttype, boundary); + if(ret) + return ret; + } + + /* Content-Transfer-Encoding header. */ + if(!search_header(part->userheaders, + STRCONST("Content-Transfer-Encoding"))) { + if(part->encoder) + cte = part->encoder->name; + else if(contenttype && strategy == MIMESTRATEGY_MAIL && + part->kind != MIMEKIND_MULTIPART) + cte = "8bit"; + if(cte) { + ret = Curl_mime_add_header(&part->curlheaders, + "Content-Transfer-Encoding: %s", cte); + if(ret) + return ret; + } + } + + /* If we were reading curl-generated headers, restart with new ones (this + should not occur). */ + if(part->state.state == MIMESTATE_CURLHEADERS) + mimesetstate(&part->state, MIMESTATE_CURLHEADERS, part->curlheaders); + + /* Process subparts. */ + if(part->kind == MIMEKIND_MULTIPART && mime) { + curl_mimepart *subpart; + + disposition = NULL; + if(content_type_match(contenttype, STRCONST("multipart/form-data"))) + disposition = "form-data"; + for(subpart = mime->firstpart; subpart; subpart = subpart->nextpart) { + ret = Curl_mime_prepare_headers(data, subpart, NULL, + disposition, strategy); + if(ret) + return ret; + } + } + return ret; +} + +/* Recursively reset paused status in the given part. */ +static void mime_unpause(curl_mimepart *part) +{ + if(part) { + if(part->lastreadstatus == CURL_READFUNC_PAUSE) + part->lastreadstatus = 1; /* Successful read status. */ + if(part->kind == MIMEKIND_MULTIPART) { + curl_mime *mime = (curl_mime *) part->arg; + + if(mime) { + curl_mimepart *subpart; + + for(subpart = mime->firstpart; subpart; subpart = subpart->nextpart) + mime_unpause(subpart); + } + } + } +} + +struct cr_mime_ctx { + struct Curl_creader super; + curl_mimepart *part; + curl_off_t total_len; + curl_off_t read_len; + CURLcode error_result; + BIT(seen_eos); + BIT(errored); +}; + +static CURLcode cr_mime_init(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_mime_ctx *ctx = reader->ctx; + (void)data; + ctx->total_len = -1; + ctx->read_len = 0; + return CURLE_OK; +} + +/* Real client reader to installed client callbacks. */ +static CURLcode cr_mime_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *pnread, bool *peos) +{ + struct cr_mime_ctx *ctx = reader->ctx; + size_t nread; + + /* Once we have errored, we will return the same error forever */ + if(ctx->errored) { + *pnread = 0; + *peos = FALSE; + return ctx->error_result; + } + if(ctx->seen_eos) { + *pnread = 0; + *peos = TRUE; + return CURLE_OK; + } + /* respect length limitations */ + if(ctx->total_len >= 0) { + curl_off_t remain = ctx->total_len - ctx->read_len; + if(remain <= 0) + blen = 0; + else if(remain < (curl_off_t)blen) + blen = (size_t)remain; + } + nread = 0; + if(blen) { + nread = Curl_mime_read(buf, 1, blen, ctx->part); + } + + switch(nread) { + case 0: + if((ctx->total_len >= 0) && (ctx->read_len < ctx->total_len)) { + failf(data, "client mime read EOF fail, " + "only %"CURL_FORMAT_CURL_OFF_T"/%"CURL_FORMAT_CURL_OFF_T + " of needed bytes read", ctx->read_len, ctx->total_len); + return CURLE_READ_ERROR; + } + *pnread = 0; + *peos = TRUE; + ctx->seen_eos = TRUE; + break; + + case CURL_READFUNC_ABORT: + failf(data, "operation aborted by callback"); + *pnread = 0; + *peos = FALSE; + ctx->errored = TRUE; + ctx->error_result = CURLE_ABORTED_BY_CALLBACK; + return CURLE_ABORTED_BY_CALLBACK; + + case CURL_READFUNC_PAUSE: + /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */ + data->req.keepon |= KEEP_SEND_PAUSE; /* mark socket send as paused */ + *pnread = 0; + *peos = FALSE; + break; /* nothing was read */ + + default: + if(nread > blen) { + /* the read function returned a too large value */ + failf(data, "read function returned funny value"); + *pnread = 0; + *peos = FALSE; + ctx->errored = TRUE; + ctx->error_result = CURLE_READ_ERROR; + return CURLE_READ_ERROR; + } + ctx->read_len += nread; + if(ctx->total_len >= 0) + ctx->seen_eos = (ctx->read_len >= ctx->total_len); + *pnread = nread; + *peos = ctx->seen_eos; + break; + } + DEBUGF(infof(data, "cr_mime_read(len=%zu, total=%"CURL_FORMAT_CURL_OFF_T + ", read=%"CURL_FORMAT_CURL_OFF_T") -> %d, %zu, %d", + blen, ctx->total_len, ctx->read_len, CURLE_OK, *pnread, *peos)); + return CURLE_OK; +} + +static bool cr_mime_needs_rewind(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_mime_ctx *ctx = reader->ctx; + (void)data; + return ctx->read_len > 0; +} + +static curl_off_t cr_mime_total_length(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_mime_ctx *ctx = reader->ctx; + (void)data; + return ctx->total_len; +} + +static CURLcode cr_mime_resume_from(struct Curl_easy *data, + struct Curl_creader *reader, + curl_off_t offset) +{ + struct cr_mime_ctx *ctx = reader->ctx; + + if(offset > 0) { + curl_off_t passed = 0; + + do { + char scratch[4*1024]; + size_t readthisamountnow = + (offset - passed > (curl_off_t)sizeof(scratch)) ? + sizeof(scratch) : + curlx_sotouz(offset - passed); + size_t nread; + + nread = Curl_mime_read(scratch, 1, readthisamountnow, ctx->part); + passed += (curl_off_t)nread; + if((nread == 0) || (nread > readthisamountnow)) { + /* this checks for greater-than only to make sure that the + CURL_READFUNC_ABORT return code still aborts */ + failf(data, "Could only read %" CURL_FORMAT_CURL_OFF_T + " bytes from the mime post", passed); + return CURLE_READ_ERROR; + } + } while(passed < offset); + + /* now, decrease the size of the read */ + if(ctx->total_len > 0) { + ctx->total_len -= offset; + + if(ctx->total_len <= 0) { + failf(data, "Mime post already completely uploaded"); + return CURLE_PARTIAL_FILE; + } + } + /* we've passed, proceed as normal */ + } + return CURLE_OK; +} + +static CURLcode cr_mime_rewind(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_mime_ctx *ctx = reader->ctx; + CURLcode result = mime_rewind(ctx->part); + if(result) + failf(data, "Cannot rewind mime/post data"); + return result; +} + +static CURLcode cr_mime_unpause(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_mime_ctx *ctx = reader->ctx; + (void)data; + mime_unpause(ctx->part); + return CURLE_OK; +} + +static const struct Curl_crtype cr_mime = { + "cr-mime", + cr_mime_init, + cr_mime_read, + Curl_creader_def_close, + cr_mime_needs_rewind, + cr_mime_total_length, + cr_mime_resume_from, + cr_mime_rewind, + cr_mime_unpause, + Curl_creader_def_done, + sizeof(struct cr_mime_ctx) +}; + +CURLcode Curl_creader_set_mime(struct Curl_easy *data, curl_mimepart *part) +{ + struct Curl_creader *r; + struct cr_mime_ctx *ctx; + CURLcode result; + + result = Curl_creader_create(&r, data, &cr_mime, CURL_CR_CLIENT); + if(result) + return result; + ctx = r->ctx; + ctx->part = part; + /* Make sure we will read the entire mime structure. */ + result = mime_rewind(ctx->part); + if(result) { + Curl_creader_free(data, r); + return result; + } + ctx->total_len = mime_size(ctx->part); + + return Curl_creader_set(data, r); +} + +#else /* !CURL_DISABLE_MIME && (!CURL_DISABLE_HTTP || + !CURL_DISABLE_SMTP || !CURL_DISABLE_IMAP) */ + +/* Mime not compiled in: define stubs for externally-referenced functions. */ +curl_mime *curl_mime_init(CURL *easy) +{ + (void) easy; + return NULL; +} + +void curl_mime_free(curl_mime *mime) +{ + (void) mime; +} + +curl_mimepart *curl_mime_addpart(curl_mime *mime) +{ + (void) mime; + return NULL; +} + +CURLcode curl_mime_name(curl_mimepart *part, const char *name) +{ + (void) part; + (void) name; + return CURLE_NOT_BUILT_IN; +} + +CURLcode curl_mime_filename(curl_mimepart *part, const char *filename) +{ + (void) part; + (void) filename; + return CURLE_NOT_BUILT_IN; +} + +CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype) +{ + (void) part; + (void) mimetype; + return CURLE_NOT_BUILT_IN; +} + +CURLcode curl_mime_encoder(curl_mimepart *part, const char *encoding) +{ + (void) part; + (void) encoding; + return CURLE_NOT_BUILT_IN; +} + +CURLcode curl_mime_data(curl_mimepart *part, + const char *data, size_t datasize) +{ + (void) part; + (void) data; + (void) datasize; + return CURLE_NOT_BUILT_IN; +} + +CURLcode curl_mime_filedata(curl_mimepart *part, const char *filename) +{ + (void) part; + (void) filename; + return CURLE_NOT_BUILT_IN; +} + +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) +{ + (void) part; + (void) datasize; + (void) readfunc; + (void) seekfunc; + (void) freefunc; + (void) arg; + return CURLE_NOT_BUILT_IN; +} + +CURLcode curl_mime_subparts(curl_mimepart *part, curl_mime *subparts) +{ + (void) part; + (void) subparts; + return CURLE_NOT_BUILT_IN; +} + +CURLcode curl_mime_headers(curl_mimepart *part, + struct curl_slist *headers, int take_ownership) +{ + (void) part; + (void) headers; + (void) take_ownership; + return CURLE_NOT_BUILT_IN; +} + +CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...) +{ + (void)slp; + (void)fmt; + return CURLE_NOT_BUILT_IN; +} + +#endif /* if disabled */ diff --git a/third_party/curl/lib/mime.h b/third_party/curl/lib/mime.h new file mode 100644 index 0000000..954b3cc --- /dev/null +++ b/third_party/curl/lib/mime.h @@ -0,0 +1,176 @@ +#ifndef HEADER_CURL_MIME_H +#define HEADER_CURL_MIME_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#define MIME_BOUNDARY_DASHES 24 /* leading boundary dashes */ +#define MIME_RAND_BOUNDARY_CHARS 22 /* Nb. of random boundary chars. */ +#define MAX_ENCODED_LINE_LENGTH 76 /* Maximum encoded line length. */ +#define ENCODING_BUFFER_SIZE 256 /* Encoding temp buffers size. */ + +/* Part flags. */ +#define MIME_USERHEADERS_OWNER (1 << 0) +#define MIME_BODY_ONLY (1 << 1) +#define MIME_FAST_READ (1 << 2) + +#define FILE_CONTENTTYPE_DEFAULT "application/octet-stream" +#define MULTIPART_CONTENTTYPE_DEFAULT "multipart/mixed" +#define DISPOSITION_DEFAULT "attachment" + +/* Part source kinds. */ +enum mimekind { + MIMEKIND_NONE = 0, /* Part not set. */ + MIMEKIND_DATA, /* Allocated mime data. */ + MIMEKIND_FILE, /* Data from file. */ + MIMEKIND_CALLBACK, /* Data from `read' callback. */ + MIMEKIND_MULTIPART, /* Data is a mime subpart. */ + MIMEKIND_LAST +}; + +/* Readback state tokens. */ +enum mimestate { + MIMESTATE_BEGIN, /* Readback has not yet started. */ + MIMESTATE_CURLHEADERS, /* In curl-generated headers. */ + MIMESTATE_USERHEADERS, /* In caller's supplied headers. */ + MIMESTATE_EOH, /* End of headers. */ + MIMESTATE_BODY, /* Placeholder. */ + MIMESTATE_BOUNDARY1, /* In boundary prefix. */ + MIMESTATE_BOUNDARY2, /* In boundary. */ + MIMESTATE_CONTENT, /* In content. */ + MIMESTATE_END, /* End of part reached. */ + MIMESTATE_LAST +}; + +/* Mime headers strategies. */ +enum mimestrategy { + MIMESTRATEGY_MAIL, /* Mime mail. */ + MIMESTRATEGY_FORM, /* HTTP post form. */ + MIMESTRATEGY_LAST +}; + +/* Content transfer encoder. */ +struct mime_encoder { + const char * name; /* Encoding name. */ + size_t (*encodefunc)(char *buffer, size_t size, bool ateof, + curl_mimepart *part); /* Encoded read. */ + curl_off_t (*sizefunc)(curl_mimepart *part); /* Encoded size. */ +}; + +/* Content transfer encoder state. */ +struct mime_encoder_state { + size_t pos; /* Position on output line. */ + size_t bufbeg; /* Next data index in input buffer. */ + size_t bufend; /* First unused byte index in input buffer. */ + char buf[ENCODING_BUFFER_SIZE]; /* Input buffer. */ +}; + +/* Mime readback state. */ +struct mime_state { + enum mimestate state; /* Current state token. */ + void *ptr; /* State-dependent pointer. */ + curl_off_t offset; /* State-dependent offset. */ +}; + +/* Boundary string length. */ +#define MIME_BOUNDARY_LEN (MIME_BOUNDARY_DASHES + MIME_RAND_BOUNDARY_CHARS) + +/* A mime multipart. */ +struct curl_mime { + curl_mimepart *parent; /* Parent part. */ + curl_mimepart *firstpart; /* First part. */ + curl_mimepart *lastpart; /* Last part. */ + char boundary[MIME_BOUNDARY_LEN + 1]; /* The part boundary. */ + struct mime_state state; /* Current readback state. */ +}; + +/* A mime part. */ +struct curl_mimepart { + curl_mime *parent; /* Parent mime structure. */ + curl_mimepart *nextpart; /* Forward linked list. */ + enum mimekind kind; /* The part kind. */ + unsigned int flags; /* Flags. */ + char *data; /* Memory data or file name. */ + curl_read_callback readfunc; /* Read function. */ + curl_seek_callback seekfunc; /* Seek function. */ + curl_free_callback freefunc; /* Argument free function. */ + void *arg; /* Argument to callback functions. */ + FILE *fp; /* File pointer. */ + struct curl_slist *curlheaders; /* Part headers. */ + struct curl_slist *userheaders; /* Part headers. */ + char *mimetype; /* Part mime type. */ + char *filename; /* Remote file name. */ + char *name; /* Data name. */ + curl_off_t datasize; /* Expected data size. */ + struct mime_state state; /* Current readback state. */ + const struct mime_encoder *encoder; /* Content data encoder. */ + struct mime_encoder_state encstate; /* Data encoder state. */ + size_t lastreadstatus; /* Last read callback returned status. */ +}; + +CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...) + CURL_PRINTF(2, 3); + +#if !defined(CURL_DISABLE_MIME) && (!defined(CURL_DISABLE_HTTP) || \ + !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_IMAP)) + +/* Prototypes. */ +void Curl_mime_initpart(struct curl_mimepart *part); +void Curl_mime_cleanpart(struct curl_mimepart *part); +CURLcode Curl_mime_duppart(struct Curl_easy *data, + struct curl_mimepart *dst, + const curl_mimepart *src); +CURLcode Curl_mime_set_subparts(struct curl_mimepart *part, + struct curl_mime *subparts, + int take_ownership); +CURLcode Curl_mime_prepare_headers(struct Curl_easy *data, + struct curl_mimepart *part, + const char *contenttype, + const char *disposition, + enum mimestrategy strategy); +size_t Curl_mime_read(char *buffer, size_t size, size_t nitems, + void *instream); +const char *Curl_mime_contenttype(const char *filename); + +/** + * Install a client reader as upload source that reads the given + * mime part. + */ +CURLcode Curl_creader_set_mime(struct Curl_easy *data, curl_mimepart *part); + +#else +/* if disabled */ +#define Curl_mime_initpart(x) +#define Curl_mime_cleanpart(x) +#define Curl_mime_duppart(x,y,z) CURLE_OK /* Nothing to duplicate. Succeed */ +#define Curl_mime_set_subparts(a,b,c) CURLE_NOT_BUILT_IN +#define Curl_mime_prepare_headers(a,b,c,d,e) CURLE_NOT_BUILT_IN +#define Curl_mime_read NULL +#define Curl_creader_set_mime(x,y) ((void)x, CURLE_NOT_BUILT_IN) +#endif + + +#endif /* HEADER_CURL_MIME_H */ diff --git a/third_party/curl/lib/mprintf.c b/third_party/curl/lib/mprintf.c new file mode 100644 index 0000000..1829abc --- /dev/null +++ b/third_party/curl/lib/mprintf.c @@ -0,0 +1,1204 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + */ + +#include "curl_setup.h" +#include "dynbuf.h" +#include "curl_printf.h" +#include + +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + +/* + * If SIZEOF_SIZE_T has not been defined, default to the size of long. + */ + +#ifdef HAVE_LONGLONG +# define LONG_LONG_TYPE long long +# define HAVE_LONG_LONG_TYPE +#else +# if defined(_MSC_VER) && (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64) +# define LONG_LONG_TYPE __int64 +# define HAVE_LONG_LONG_TYPE +# else +# undef LONG_LONG_TYPE +# undef HAVE_LONG_LONG_TYPE +# endif +#endif + +/* + * Max integer data types that mprintf.c is capable + */ + +#ifdef HAVE_LONG_LONG_TYPE +# define mp_intmax_t LONG_LONG_TYPE +# define mp_uintmax_t unsigned LONG_LONG_TYPE +#else +# define mp_intmax_t long +# define mp_uintmax_t unsigned long +#endif + +#define BUFFSIZE 326 /* buffer for long-to-str and float-to-str calcs, should + fit negative DBL_MAX (317 letters) */ +#define MAX_PARAMETERS 128 /* number of input arguments */ +#define MAX_SEGMENTS 128 /* number of output segments */ + +#ifdef __AMIGA__ +# undef FORMAT_INT +#endif + +/* Lower-case digits. */ +static const char lower_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; + +/* Upper-case digits. */ +static const char upper_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +#define OUTCHAR(x) \ + do { \ + if(!stream((unsigned char)x, userp)) \ + done++; \ + else \ + return done; /* return on failure */ \ + } while(0) + +/* Data type to read from the arglist */ +typedef enum { + FORMAT_STRING, + FORMAT_PTR, + FORMAT_INTPTR, + FORMAT_INT, + FORMAT_LONG, + FORMAT_LONGLONG, + FORMAT_INTU, + FORMAT_LONGU, + FORMAT_LONGLONGU, + FORMAT_DOUBLE, + FORMAT_LONGDOUBLE, + FORMAT_WIDTH, + FORMAT_PRECISION +} FormatType; + +/* conversion and display flags */ +enum { + FLAGS_SPACE = 1<<0, + FLAGS_SHOWSIGN = 1<<1, + FLAGS_LEFT = 1<<2, + FLAGS_ALT = 1<<3, + FLAGS_SHORT = 1<<4, + FLAGS_LONG = 1<<5, + FLAGS_LONGLONG = 1<<6, + FLAGS_LONGDOUBLE = 1<<7, + FLAGS_PAD_NIL = 1<<8, + FLAGS_UNSIGNED = 1<<9, + FLAGS_OCTAL = 1<<10, + FLAGS_HEX = 1<<11, + FLAGS_UPPER = 1<<12, + FLAGS_WIDTH = 1<<13, /* '*' or '*$' used */ + FLAGS_WIDTHPARAM = 1<<14, /* width PARAMETER was specified */ + FLAGS_PREC = 1<<15, /* precision was specified */ + FLAGS_PRECPARAM = 1<<16, /* precision PARAMETER was specified */ + FLAGS_CHAR = 1<<17, /* %c story */ + FLAGS_FLOATE = 1<<18, /* %e or %E */ + FLAGS_FLOATG = 1<<19, /* %g or %G */ + FLAGS_SUBSTR = 1<<20 /* no input, only substring */ +}; + +enum { + DOLLAR_UNKNOWN, + DOLLAR_NOPE, + DOLLAR_USE +}; + +/* + * Describes an input va_arg type and hold its value. + */ +struct va_input { + FormatType type; /* FormatType */ + union { + char *str; + void *ptr; + mp_intmax_t nums; /* signed */ + mp_uintmax_t numu; /* unsigned */ + double dnum; + } val; +}; + +/* + * Describes an output segment. + */ +struct outsegment { + int width; /* width OR width parameter number */ + int precision; /* precision OR precision parameter number */ + unsigned int flags; + unsigned int input; /* input argument array index */ + char *start; /* format string start to output */ + size_t outlen; /* number of bytes from the format string to output */ +}; + +struct nsprintf { + char *buffer; + size_t length; + size_t max; +}; + +struct asprintf { + struct dynbuf *b; + char merr; +}; + +/* the provided input number is 1-based but this returns the number 0-based. + + returns -1 if no valid number was provided. +*/ +static int dollarstring(char *input, char **end) +{ + if(ISDIGIT(*input)) { + int number = 0; + do { + if(number < MAX_PARAMETERS) { + number *= 10; + number += *input - '0'; + } + input++; + } while(ISDIGIT(*input)); + + if(number && (number <= MAX_PARAMETERS) && ('$' == *input)) { + *end = ++input; + return number - 1; + } + } + return -1; +} + +/* + * Parse the format string. + * + * Create two arrays. One describes the inputs, one describes the outputs. + * + * Returns zero on success. + */ + +#define PFMT_OK 0 +#define PFMT_DOLLAR 1 /* bad dollar for main param */ +#define PFMT_DOLLARWIDTH 2 /* bad dollar use for width */ +#define PFMT_DOLLARPREC 3 /* bad dollar use for precision */ +#define PFMT_MANYARGS 4 /* too many input arguments used */ +#define PFMT_PREC 5 /* precision overflow */ +#define PFMT_PRECMIX 6 /* bad mix of precision specifiers */ +#define PFMT_WIDTH 7 /* width overflow */ +#define PFMT_INPUTGAP 8 /* gap in arguments */ +#define PFMT_WIDTHARG 9 /* attempted to use same arg twice, for width */ +#define PFMT_PRECARG 10 /* attempted to use same arg twice, for prec */ +#define PFMT_MANYSEGS 11 /* maxed out output segments */ + +static int parsefmt(const char *format, + struct outsegment *out, + struct va_input *in, + int *opieces, + int *ipieces, va_list arglist) +{ + char *fmt = (char *)format; + int param_num = 0; + int param; + int width; + int precision; + unsigned int flags; + FormatType type; + int max_param = -1; + int i; + int ocount = 0; + unsigned char usedinput[MAX_PARAMETERS/8]; + size_t outlen = 0; + struct outsegment *optr; + int use_dollar = DOLLAR_UNKNOWN; + char *start = fmt; + + /* clear, set a bit for each used input */ + memset(usedinput, 0, sizeof(usedinput)); + + while(*fmt) { + if(*fmt == '%') { + struct va_input *iptr; + bool loopit = TRUE; + fmt++; + outlen = (size_t)(fmt - start - 1); + if(*fmt == '%') { + /* this means a %% that should be output only as %. Create an output + segment. */ + if(outlen) { + optr = &out[ocount++]; + if(ocount > MAX_SEGMENTS) + return PFMT_MANYSEGS; + optr->input = 0; + optr->flags = FLAGS_SUBSTR; + optr->start = start; + optr->outlen = outlen; + } + start = fmt; + fmt++; + continue; /* while */ + } + + flags = 0; + width = precision = 0; + + if(use_dollar != DOLLAR_NOPE) { + param = dollarstring(fmt, &fmt); + if(param < 0) { + if(use_dollar == DOLLAR_USE) + /* illegal combo */ + return PFMT_DOLLAR; + + /* we got no positional, just get the next arg */ + param = -1; + use_dollar = DOLLAR_NOPE; + } + else + use_dollar = DOLLAR_USE; + } + else + param = -1; + + /* Handle the flags */ + while(loopit) { + switch(*fmt++) { + case ' ': + flags |= FLAGS_SPACE; + break; + case '+': + flags |= FLAGS_SHOWSIGN; + break; + case '-': + flags |= FLAGS_LEFT; + flags &= ~(unsigned int)FLAGS_PAD_NIL; + break; + case '#': + flags |= FLAGS_ALT; + break; + case '.': + if('*' == *fmt) { + /* The precision is picked from a specified parameter */ + flags |= FLAGS_PRECPARAM; + fmt++; + + if(use_dollar == DOLLAR_USE) { + precision = dollarstring(fmt, &fmt); + if(precision < 0) + /* illegal combo */ + return PFMT_DOLLARPREC; + } + else + /* get it from the next argument */ + precision = -1; + } + else { + bool is_neg = FALSE; + flags |= FLAGS_PREC; + precision = 0; + if('-' == *fmt) { + is_neg = TRUE; + fmt++; + } + while(ISDIGIT(*fmt)) { + if(precision > INT_MAX/10) + return PFMT_PREC; + precision *= 10; + precision += *fmt - '0'; + fmt++; + } + if(is_neg) + precision = -precision; + } + if((flags & (FLAGS_PREC | FLAGS_PRECPARAM)) == + (FLAGS_PREC | FLAGS_PRECPARAM)) + /* it is not permitted to use both kinds of precision for the same + argument */ + return PFMT_PRECMIX; + break; + case 'h': + flags |= FLAGS_SHORT; + break; +#if defined(_WIN32) || defined(_WIN32_WCE) + case 'I': + /* Non-ANSI integer extensions I32 I64 */ + if((fmt[0] == '3') && (fmt[1] == '2')) { + flags |= FLAGS_LONG; + fmt += 2; + } + else if((fmt[0] == '6') && (fmt[1] == '4')) { + flags |= FLAGS_LONGLONG; + fmt += 2; + } + else { +#if (SIZEOF_CURL_OFF_T > SIZEOF_LONG) + flags |= FLAGS_LONGLONG; +#else + flags |= FLAGS_LONG; +#endif + } + break; +#endif /* _WIN32 || _WIN32_WCE */ + case 'l': + if(flags & FLAGS_LONG) + flags |= FLAGS_LONGLONG; + else + flags |= FLAGS_LONG; + break; + case 'L': + flags |= FLAGS_LONGDOUBLE; + break; + case 'q': + flags |= FLAGS_LONGLONG; + break; + case 'z': + /* the code below generates a warning if -Wunreachable-code is + used */ +#if (SIZEOF_SIZE_T > SIZEOF_LONG) + flags |= FLAGS_LONGLONG; +#else + flags |= FLAGS_LONG; +#endif + break; + case 'O': +#if (SIZEOF_CURL_OFF_T > SIZEOF_LONG) + flags |= FLAGS_LONGLONG; +#else + flags |= FLAGS_LONG; +#endif + break; + case '0': + if(!(flags & FLAGS_LEFT)) + flags |= FLAGS_PAD_NIL; + FALLTHROUGH(); + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + flags |= FLAGS_WIDTH; + width = 0; + fmt--; + do { + if(width > INT_MAX/10) + return PFMT_WIDTH; + width *= 10; + width += *fmt - '0'; + fmt++; + } while(ISDIGIT(*fmt)); + break; + case '*': /* read width from argument list */ + flags |= FLAGS_WIDTHPARAM; + if(use_dollar == DOLLAR_USE) { + width = dollarstring(fmt, &fmt); + if(width < 0) + /* illegal combo */ + return PFMT_DOLLARWIDTH; + } + else + /* pick from the next argument */ + width = -1; + break; + default: + loopit = FALSE; + fmt--; + break; + } /* switch */ + } /* while */ + + switch(*fmt) { + case 'S': + flags |= FLAGS_ALT; + FALLTHROUGH(); + case 's': + type = FORMAT_STRING; + break; + case 'n': + type = FORMAT_INTPTR; + break; + case 'p': + type = FORMAT_PTR; + break; + case 'd': + case 'i': + if(flags & FLAGS_LONGLONG) + type = FORMAT_LONGLONG; + else if(flags & FLAGS_LONG) + type = FORMAT_LONG; + else + type = FORMAT_INT; + break; + case 'u': + if(flags & FLAGS_LONGLONG) + type = FORMAT_LONGLONGU; + else if(flags & FLAGS_LONG) + type = FORMAT_LONGU; + else + type = FORMAT_INTU; + flags |= FLAGS_UNSIGNED; + break; + case 'o': + type = FORMAT_INT; + flags |= FLAGS_OCTAL; + break; + case 'x': + type = FORMAT_INTU; + flags |= FLAGS_HEX|FLAGS_UNSIGNED; + break; + case 'X': + type = FORMAT_INTU; + flags |= FLAGS_HEX|FLAGS_UPPER|FLAGS_UNSIGNED; + break; + case 'c': + type = FORMAT_INT; + flags |= FLAGS_CHAR; + break; + case 'f': + type = FORMAT_DOUBLE; + break; + case 'e': + type = FORMAT_DOUBLE; + flags |= FLAGS_FLOATE; + break; + case 'E': + type = FORMAT_DOUBLE; + flags |= FLAGS_FLOATE|FLAGS_UPPER; + break; + case 'g': + type = FORMAT_DOUBLE; + flags |= FLAGS_FLOATG; + break; + case 'G': + type = FORMAT_DOUBLE; + flags |= FLAGS_FLOATG|FLAGS_UPPER; + break; + default: + /* invalid instruction, disregard and continue */ + continue; + } /* switch */ + + if(flags & FLAGS_WIDTHPARAM) { + if(width < 0) + width = param_num++; + else { + /* if this identifies a parameter already used, this + is illegal */ + if(usedinput[width/8] & (1 << (width&7))) + return PFMT_WIDTHARG; + } + if(width >= MAX_PARAMETERS) + return PFMT_MANYARGS; + if(width >= max_param) + max_param = width; + + in[width].type = FORMAT_WIDTH; + /* mark as used */ + usedinput[width/8] |= (unsigned char)(1 << (width&7)); + } + + if(flags & FLAGS_PRECPARAM) { + if(precision < 0) + precision = param_num++; + else { + /* if this identifies a parameter already used, this + is illegal */ + if(usedinput[precision/8] & (1 << (precision&7))) + return PFMT_PRECARG; + } + if(precision >= MAX_PARAMETERS) + return PFMT_MANYARGS; + if(precision >= max_param) + max_param = precision; + + in[precision].type = FORMAT_PRECISION; + usedinput[precision/8] |= (unsigned char)(1 << (precision&7)); + } + + /* Handle the specifier */ + if(param < 0) + param = param_num++; + if(param >= MAX_PARAMETERS) + return PFMT_MANYARGS; + if(param >= max_param) + max_param = param; + + iptr = &in[param]; + iptr->type = type; + + /* mark this input as used */ + usedinput[param/8] |= (unsigned char)(1 << (param&7)); + + fmt++; + optr = &out[ocount++]; + if(ocount > MAX_SEGMENTS) + return PFMT_MANYSEGS; + optr->input = (unsigned int)param; + optr->flags = flags; + optr->width = width; + optr->precision = precision; + optr->start = start; + optr->outlen = outlen; + start = fmt; + } + else + fmt++; + } + + /* is there a trailing piece */ + outlen = (size_t)(fmt - start); + if(outlen) { + optr = &out[ocount++]; + if(ocount > MAX_SEGMENTS) + return PFMT_MANYSEGS; + optr->input = 0; + optr->flags = FLAGS_SUBSTR; + optr->start = start; + optr->outlen = outlen; + } + + /* Read the arg list parameters into our data list */ + for(i = 0; i < max_param + 1; i++) { + struct va_input *iptr = &in[i]; + if(!(usedinput[i/8] & (1 << (i&7)))) + /* bad input */ + return PFMT_INPUTGAP; + + /* based on the type, read the correct argument */ + switch(iptr->type) { + case FORMAT_STRING: + iptr->val.str = va_arg(arglist, char *); + break; + + case FORMAT_INTPTR: + case FORMAT_PTR: + iptr->val.ptr = va_arg(arglist, void *); + break; + + case FORMAT_LONGLONGU: + iptr->val.numu = (mp_uintmax_t)va_arg(arglist, mp_uintmax_t); + break; + + case FORMAT_LONGLONG: + iptr->val.nums = (mp_intmax_t)va_arg(arglist, mp_intmax_t); + break; + + case FORMAT_LONGU: + iptr->val.numu = (mp_uintmax_t)va_arg(arglist, unsigned long); + break; + + case FORMAT_LONG: + iptr->val.nums = (mp_intmax_t)va_arg(arglist, long); + break; + + case FORMAT_INTU: + iptr->val.numu = (mp_uintmax_t)va_arg(arglist, unsigned int); + break; + + case FORMAT_INT: + case FORMAT_WIDTH: + case FORMAT_PRECISION: + iptr->val.nums = (mp_intmax_t)va_arg(arglist, int); + break; + + case FORMAT_DOUBLE: + iptr->val.dnum = va_arg(arglist, double); + break; + + default: + DEBUGASSERT(NULL); /* unexpected */ + break; + } + } + *ipieces = max_param + 1; + *opieces = ocount; + + return PFMT_OK; +} + +/* + * formatf() - the general printf function. + * + * It calls parsefmt() to parse the format string. It populates two arrays; + * one that describes the input arguments and one that describes a number of + * output segments. + * + * On success, the input array describes the type of all arguments and their + * values. + * + * The function then iterates over the output segments and outputs them one + * by one until done. Using the appropriate input arguments (if any). + * + * All output is sent to the 'stream()' callback, one byte at a time. + */ + +static int formatf( + void *userp, /* untouched by format(), just sent to the stream() function in + the second argument */ + /* function pointer called for each output character */ + int (*stream)(unsigned char, void *), + const char *format, /* %-formatted string */ + va_list ap_save) /* list of parameters */ +{ + static const char nilstr[] = "(nil)"; + const char *digits = lower_digits; /* Base-36 digits for numbers. */ + int done = 0; /* number of characters written */ + int i; + int ocount = 0; /* number of output segments */ + int icount = 0; /* number of input arguments */ + + struct outsegment output[MAX_SEGMENTS]; + struct va_input input[MAX_PARAMETERS]; + char work[BUFFSIZE]; + + /* 'workend' points to the final buffer byte position, but with an extra + byte as margin to avoid the (false?) warning Coverity gives us + otherwise */ + char *workend = &work[sizeof(work) - 2]; + + /* Parse the format string */ + if(parsefmt(format, output, input, &ocount, &icount, ap_save)) + return 0; + + for(i = 0; i < ocount; i++) { + struct outsegment *optr = &output[i]; + struct va_input *iptr; + bool is_alt; /* Format spec modifiers. */ + int width; /* Width of a field. */ + int prec; /* Precision of a field. */ + bool is_neg; /* Decimal integer is negative. */ + unsigned long base; /* Base of a number to be written. */ + mp_uintmax_t num; /* Integral values to be written. */ + mp_intmax_t signed_num; /* Used to convert negative in positive. */ + char *w; + size_t outlen = optr->outlen; + unsigned int flags = optr->flags; + + if(outlen) { + char *str = optr->start; + for(; outlen && *str; outlen--) + OUTCHAR(*str++); + if(optr->flags & FLAGS_SUBSTR) + /* this is just a substring */ + continue; + } + + /* pick up the specified width */ + if(flags & FLAGS_WIDTHPARAM) { + width = (int)input[optr->width].val.nums; + if(width < 0) { + /* "A negative field width is taken as a '-' flag followed by a + positive field width." */ + if(width == INT_MIN) + width = INT_MAX; + else + width = -width; + flags |= FLAGS_LEFT; + flags &= ~(unsigned int)FLAGS_PAD_NIL; + } + } + else + width = optr->width; + + /* pick up the specified precision */ + if(flags & FLAGS_PRECPARAM) { + prec = (int)input[optr->precision].val.nums; + if(prec < 0) + /* "A negative precision is taken as if the precision were + omitted." */ + prec = -1; + } + else if(flags & FLAGS_PREC) + prec = optr->precision; + else + prec = -1; + + is_alt = (flags & FLAGS_ALT) ? 1 : 0; + iptr = &input[optr->input]; + + switch(iptr->type) { + case FORMAT_INTU: + case FORMAT_LONGU: + case FORMAT_LONGLONGU: + flags |= FLAGS_UNSIGNED; + FALLTHROUGH(); + case FORMAT_INT: + case FORMAT_LONG: + case FORMAT_LONGLONG: + num = iptr->val.numu; + if(flags & FLAGS_CHAR) { + /* Character. */ + if(!(flags & FLAGS_LEFT)) + while(--width > 0) + OUTCHAR(' '); + OUTCHAR((char) num); + if(flags & FLAGS_LEFT) + while(--width > 0) + OUTCHAR(' '); + break; + } + if(flags & FLAGS_OCTAL) { + /* Octal unsigned integer */ + base = 8; + is_neg = FALSE; + } + else if(flags & FLAGS_HEX) { + /* Hexadecimal unsigned integer */ + digits = (flags & FLAGS_UPPER)? upper_digits : lower_digits; + base = 16; + is_neg = FALSE; + } + else if(flags & FLAGS_UNSIGNED) { + /* Decimal unsigned integer */ + base = 10; + is_neg = FALSE; + } + else { + /* Decimal integer. */ + base = 10; + + is_neg = (iptr->val.nums < (mp_intmax_t)0); + if(is_neg) { + /* signed_num might fail to hold absolute negative minimum by 1 */ + signed_num = iptr->val.nums + (mp_intmax_t)1; + signed_num = -signed_num; + num = (mp_uintmax_t)signed_num; + num += (mp_uintmax_t)1; + } + } +number: + /* Supply a default precision if none was given. */ + if(prec == -1) + prec = 1; + + /* Put the number in WORK. */ + w = workend; + switch(base) { + case 10: + while(num > 0) { + *w-- = (char)('0' + (num % 10)); + num /= 10; + } + break; + default: + while(num > 0) { + *w-- = digits[num % base]; + num /= base; + } + break; + } + width -= (int)(workend - w); + prec -= (int)(workend - w); + + if(is_alt && base == 8 && prec <= 0) { + *w-- = '0'; + --width; + } + + if(prec > 0) { + width -= prec; + while(prec-- > 0 && w >= work) + *w-- = '0'; + } + + if(is_alt && base == 16) + width -= 2; + + if(is_neg || (flags & FLAGS_SHOWSIGN) || (flags & FLAGS_SPACE)) + --width; + + if(!(flags & FLAGS_LEFT) && !(flags & FLAGS_PAD_NIL)) + while(width-- > 0) + OUTCHAR(' '); + + if(is_neg) + OUTCHAR('-'); + else if(flags & FLAGS_SHOWSIGN) + OUTCHAR('+'); + else if(flags & FLAGS_SPACE) + OUTCHAR(' '); + + if(is_alt && base == 16) { + OUTCHAR('0'); + if(flags & FLAGS_UPPER) + OUTCHAR('X'); + else + OUTCHAR('x'); + } + + if(!(flags & FLAGS_LEFT) && (flags & FLAGS_PAD_NIL)) + while(width-- > 0) + OUTCHAR('0'); + + /* Write the number. */ + while(++w <= workend) { + OUTCHAR(*w); + } + + if(flags & FLAGS_LEFT) + while(width-- > 0) + OUTCHAR(' '); + break; + + case FORMAT_STRING: { + const char *str; + size_t len; + + str = (char *)iptr->val.str; + if(!str) { + /* Write null string if there's space. */ + if(prec == -1 || prec >= (int) sizeof(nilstr) - 1) { + str = nilstr; + len = sizeof(nilstr) - 1; + /* Disable quotes around (nil) */ + flags &= ~(unsigned int)FLAGS_ALT; + } + else { + str = ""; + len = 0; + } + } + else if(prec != -1) + len = (size_t)prec; + else if(*str == '\0') + len = 0; + else + len = strlen(str); + + width -= (len > INT_MAX) ? INT_MAX : (int)len; + + if(flags & FLAGS_ALT) + OUTCHAR('"'); + + if(!(flags & FLAGS_LEFT)) + while(width-- > 0) + OUTCHAR(' '); + + for(; len && *str; len--) + OUTCHAR(*str++); + if(flags & FLAGS_LEFT) + while(width-- > 0) + OUTCHAR(' '); + + if(flags & FLAGS_ALT) + OUTCHAR('"'); + break; + } + + case FORMAT_PTR: + /* Generic pointer. */ + if(iptr->val.ptr) { + /* If the pointer is not NULL, write it as a %#x spec. */ + base = 16; + digits = (flags & FLAGS_UPPER)? upper_digits : lower_digits; + is_alt = TRUE; + num = (size_t) iptr->val.ptr; + is_neg = FALSE; + goto number; + } + else { + /* Write "(nil)" for a nil pointer. */ + const char *point; + + width -= (int)(sizeof(nilstr) - 1); + if(flags & FLAGS_LEFT) + while(width-- > 0) + OUTCHAR(' '); + for(point = nilstr; *point != '\0'; ++point) + OUTCHAR(*point); + if(!(flags & FLAGS_LEFT)) + while(width-- > 0) + OUTCHAR(' '); + } + break; + + case FORMAT_DOUBLE: { + char formatbuf[32]="%"; + char *fptr = &formatbuf[1]; + size_t left = sizeof(formatbuf)-strlen(formatbuf); + int len; + + if(flags & FLAGS_WIDTH) + width = optr->width; + + if(flags & FLAGS_PREC) + prec = optr->precision; + + if(flags & FLAGS_LEFT) + *fptr++ = '-'; + if(flags & FLAGS_SHOWSIGN) + *fptr++ = '+'; + if(flags & FLAGS_SPACE) + *fptr++ = ' '; + if(flags & FLAGS_ALT) + *fptr++ = '#'; + + *fptr = 0; + + if(width >= 0) { + size_t dlen; + if(width >= (int)sizeof(work)) + width = sizeof(work)-1; + /* RECURSIVE USAGE */ + dlen = (size_t)curl_msnprintf(fptr, left, "%d", width); + fptr += dlen; + left -= dlen; + } + if(prec >= 0) { + /* for each digit in the integer part, we can have one less + precision */ + size_t maxprec = sizeof(work) - 2; + double val = iptr->val.dnum; + if(width > 0 && prec <= width) + maxprec -= (size_t)width; + while(val >= 10.0) { + val /= 10; + maxprec--; + } + + if(prec > (int)maxprec) + prec = (int)maxprec-1; + if(prec < 0) + prec = 0; + /* RECURSIVE USAGE */ + len = curl_msnprintf(fptr, left, ".%d", prec); + fptr += len; + } + if(flags & FLAGS_LONG) + *fptr++ = 'l'; + + if(flags & FLAGS_FLOATE) + *fptr++ = (char)((flags & FLAGS_UPPER) ? 'E':'e'); + else if(flags & FLAGS_FLOATG) + *fptr++ = (char)((flags & FLAGS_UPPER) ? 'G' : 'g'); + else + *fptr++ = 'f'; + + *fptr = 0; /* and a final null-termination */ + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wformat-nonliteral" +#endif + /* NOTE NOTE NOTE!! Not all sprintf implementations return number of + output characters */ +#ifdef HAVE_SNPRINTF + (snprintf)(work, sizeof(work), formatbuf, iptr->val.dnum); +#else + (sprintf)(work, formatbuf, iptr->val.dnum); +#endif +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + DEBUGASSERT(strlen(work) <= sizeof(work)); + for(fptr = work; *fptr; fptr++) + OUTCHAR(*fptr); + break; + } + + case FORMAT_INTPTR: + /* Answer the count of characters written. */ +#ifdef HAVE_LONG_LONG_TYPE + if(flags & FLAGS_LONGLONG) + *(LONG_LONG_TYPE *) iptr->val.ptr = (LONG_LONG_TYPE)done; + else +#endif + if(flags & FLAGS_LONG) + *(long *) iptr->val.ptr = (long)done; + else if(!(flags & FLAGS_SHORT)) + *(int *) iptr->val.ptr = (int)done; + else + *(short *) iptr->val.ptr = (short)done; + break; + + default: + break; + } + } + return done; +} + +/* fputc() look-alike */ +static int addbyter(unsigned char outc, void *f) +{ + struct nsprintf *infop = f; + if(infop->length < infop->max) { + /* only do this if we haven't reached max length yet */ + *infop->buffer++ = (char)outc; /* store */ + infop->length++; /* we are now one byte larger */ + return 0; /* fputc() returns like this on success */ + } + return 1; +} + +int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format, + va_list ap_save) +{ + int retcode; + struct nsprintf info; + + info.buffer = buffer; + info.length = 0; + info.max = maxlength; + + retcode = formatf(&info, addbyter, format, ap_save); + if(info.max) { + /* we terminate this with a zero byte */ + if(info.max == info.length) { + /* we're at maximum, scrap the last letter */ + info.buffer[-1] = 0; + DEBUGASSERT(retcode); + retcode--; /* don't count the nul byte */ + } + else + info.buffer[0] = 0; + } + return retcode; +} + +int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...) +{ + int retcode; + va_list ap_save; /* argument pointer */ + va_start(ap_save, format); + retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save); + va_end(ap_save); + return retcode; +} + +/* fputc() look-alike */ +static int alloc_addbyter(unsigned char outc, void *f) +{ + struct asprintf *infop = f; + CURLcode result = Curl_dyn_addn(infop->b, &outc, 1); + if(result) { + infop->merr = result == CURLE_TOO_LARGE ? MERR_TOO_LARGE : MERR_MEM; + return 1 ; /* fail */ + } + return 0; +} + +/* appends the formatted string, returns MERR error code */ +int Curl_dyn_vprintf(struct dynbuf *dyn, const char *format, va_list ap_save) +{ + struct asprintf info; + info.b = dyn; + info.merr = MERR_OK; + + (void)formatf(&info, alloc_addbyter, format, ap_save); + if(info.merr) { + Curl_dyn_free(info.b); + return info.merr; + } + return 0; +} + +char *curl_mvaprintf(const char *format, va_list ap_save) +{ + struct asprintf info; + struct dynbuf dyn; + info.b = &dyn; + Curl_dyn_init(info.b, DYN_APRINTF); + info.merr = MERR_OK; + + (void)formatf(&info, alloc_addbyter, format, ap_save); + if(info.merr) { + Curl_dyn_free(info.b); + return NULL; + } + if(Curl_dyn_len(info.b)) + return Curl_dyn_ptr(info.b); + return strdup(""); +} + +char *curl_maprintf(const char *format, ...) +{ + va_list ap_save; + char *s; + va_start(ap_save, format); + s = curl_mvaprintf(format, ap_save); + va_end(ap_save); + return s; +} + +static int storebuffer(unsigned char outc, void *f) +{ + char **buffer = f; + **buffer = (char)outc; + (*buffer)++; + return 0; +} + +int curl_msprintf(char *buffer, const char *format, ...) +{ + va_list ap_save; /* argument pointer */ + int retcode; + va_start(ap_save, format); + retcode = formatf(&buffer, storebuffer, format, ap_save); + va_end(ap_save); + *buffer = 0; /* we terminate this with a zero byte */ + return retcode; +} + +static int fputc_wrapper(unsigned char outc, void *f) +{ + int out = outc; + FILE *s = f; + int rc = fputc(out, s); + return rc == EOF; +} + +int curl_mprintf(const char *format, ...) +{ + int retcode; + va_list ap_save; /* argument pointer */ + va_start(ap_save, format); + + retcode = formatf(stdout, fputc_wrapper, format, ap_save); + va_end(ap_save); + return retcode; +} + +int curl_mfprintf(FILE *whereto, const char *format, ...) +{ + int retcode; + va_list ap_save; /* argument pointer */ + va_start(ap_save, format); + retcode = formatf(whereto, fputc_wrapper, format, ap_save); + va_end(ap_save); + return retcode; +} + +int curl_mvsprintf(char *buffer, const char *format, va_list ap_save) +{ + int retcode = formatf(&buffer, storebuffer, format, ap_save); + *buffer = 0; /* we terminate this with a zero byte */ + return retcode; +} + +int curl_mvprintf(const char *format, va_list ap_save) +{ + return formatf(stdout, fputc_wrapper, format, ap_save); +} + +int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save) +{ + return formatf(whereto, fputc_wrapper, format, ap_save); +} diff --git a/third_party/curl/lib/mqtt.c b/third_party/curl/lib/mqtt.c new file mode 100644 index 0000000..4ca24eb --- /dev/null +++ b/third_party/curl/lib/mqtt.c @@ -0,0 +1,842 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (C) Björn Stenberg, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_MQTT + +#include "urldata.h" +#include +#include "transfer.h" +#include "sendf.h" +#include "progress.h" +#include "mqtt.h" +#include "select.h" +#include "strdup.h" +#include "url.h" +#include "escape.h" +#include "warnless.h" +#include "curl_printf.h" +#include "curl_memory.h" +#include "multiif.h" +#include "rand.h" + +/* The last #include file should be: */ +#include "memdebug.h" + +#define MQTT_MSG_CONNECT 0x10 +#define MQTT_MSG_CONNACK 0x20 +#define MQTT_MSG_PUBLISH 0x30 +#define MQTT_MSG_SUBSCRIBE 0x82 +#define MQTT_MSG_SUBACK 0x90 +#define MQTT_MSG_DISCONNECT 0xe0 + +#define MQTT_CONNACK_LEN 2 +#define MQTT_SUBACK_LEN 3 +#define MQTT_CLIENTID_LEN 12 /* "curl0123abcd" */ + +/* + * Forward declarations. + */ + +static CURLcode mqtt_do(struct Curl_easy *data, bool *done); +static CURLcode mqtt_done(struct Curl_easy *data, + CURLcode status, bool premature); +static CURLcode mqtt_doing(struct Curl_easy *data, bool *done); +static int mqtt_getsock(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t *sock); +static CURLcode mqtt_setup_conn(struct Curl_easy *data, + struct connectdata *conn); + +/* + * MQTT protocol handler. + */ + +const struct Curl_handler Curl_handler_mqtt = { + "mqtt", /* scheme */ + mqtt_setup_conn, /* setup_connection */ + mqtt_do, /* do_it */ + mqtt_done, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + mqtt_doing, /* doing */ + ZERO_NULL, /* proto_getsock */ + mqtt_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_MQTT, /* defport */ + CURLPROTO_MQTT, /* protocol */ + CURLPROTO_MQTT, /* family */ + PROTOPT_NONE /* flags */ +}; + +static CURLcode mqtt_setup_conn(struct Curl_easy *data, + struct connectdata *conn) +{ + /* allocate the HTTP-specific struct for the Curl_easy, only to survive + during this request */ + struct MQTT *mq; + (void)conn; + DEBUGASSERT(data->req.p.mqtt == NULL); + + mq = calloc(1, sizeof(struct MQTT)); + if(!mq) + return CURLE_OUT_OF_MEMORY; + Curl_dyn_init(&mq->recvbuf, DYN_MQTT_RECV); + data->req.p.mqtt = mq; + return CURLE_OK; +} + +static CURLcode mqtt_send(struct Curl_easy *data, + char *buf, size_t len) +{ + CURLcode result = CURLE_OK; + struct MQTT *mq = data->req.p.mqtt; + size_t n; + result = Curl_xfer_send(data, buf, len, &n); + if(result) + return result; + Curl_debug(data, CURLINFO_HEADER_OUT, buf, (size_t)n); + if(len != n) { + size_t nsend = len - n; + char *sendleftovers = Curl_memdup(&buf[n], nsend); + if(!sendleftovers) + return CURLE_OUT_OF_MEMORY; + mq->sendleftovers = sendleftovers; + mq->nsend = nsend; + } + else { + mq->sendleftovers = NULL; + mq->nsend = 0; + } + return result; +} + +/* Generic function called by the multi interface to figure out what socket(s) + to wait for and for what actions during the DOING and PROTOCONNECT + states */ +static int mqtt_getsock(struct Curl_easy *data, + struct connectdata *conn, + curl_socket_t *sock) +{ + (void)data; + sock[0] = conn->sock[FIRSTSOCKET]; + return GETSOCK_READSOCK(FIRSTSOCKET); +} + +static int mqtt_encode_len(char *buf, size_t len) +{ + unsigned char encoded; + int i; + + for(i = 0; (len > 0) && (i<4); i++) { + encoded = len % 0x80; + len /= 0x80; + if(len) + encoded |= 0x80; + buf[i] = encoded; + } + + return i; +} + +/* add the passwd to the CONNECT packet */ +static int add_passwd(const char *passwd, const size_t plen, + char *pkt, const size_t start, int remain_pos) +{ + /* magic number that need to be set properly */ + const size_t conn_flags_pos = remain_pos + 8; + if(plen > 0xffff) + return 1; + + /* set password flag */ + pkt[conn_flags_pos] |= 0x40; + + /* length of password provided */ + pkt[start] = (char)((plen >> 8) & 0xFF); + pkt[start + 1] = (char)(plen & 0xFF); + memcpy(&pkt[start + 2], passwd, plen); + return 0; +} + +/* add user to the CONNECT packet */ +static int add_user(const char *username, const size_t ulen, + unsigned char *pkt, const size_t start, int remain_pos) +{ + /* magic number that need to be set properly */ + const size_t conn_flags_pos = remain_pos + 8; + if(ulen > 0xffff) + return 1; + + /* set username flag */ + pkt[conn_flags_pos] |= 0x80; + /* length of username provided */ + pkt[start] = (unsigned char)((ulen >> 8) & 0xFF); + pkt[start + 1] = (unsigned char)(ulen & 0xFF); + memcpy(&pkt[start + 2], username, ulen); + return 0; +} + +/* add client ID to the CONNECT packet */ +static int add_client_id(const char *client_id, const size_t client_id_len, + char *pkt, const size_t start) +{ + if(client_id_len != MQTT_CLIENTID_LEN) + return 1; + pkt[start] = 0x00; + pkt[start + 1] = MQTT_CLIENTID_LEN; + memcpy(&pkt[start + 2], client_id, MQTT_CLIENTID_LEN); + return 0; +} + +/* Set initial values of CONNECT packet */ +static int init_connpack(char *packet, char *remain, int remain_pos) +{ + /* Fixed header starts */ + /* packet type */ + packet[0] = MQTT_MSG_CONNECT; + /* remaining length field */ + memcpy(&packet[1], remain, remain_pos); + /* Fixed header ends */ + + /* Variable header starts */ + /* protocol length */ + packet[remain_pos + 1] = 0x00; + packet[remain_pos + 2] = 0x04; + /* protocol name */ + packet[remain_pos + 3] = 'M'; + packet[remain_pos + 4] = 'Q'; + packet[remain_pos + 5] = 'T'; + packet[remain_pos + 6] = 'T'; + /* protocol level */ + packet[remain_pos + 7] = 0x04; + /* CONNECT flag: CleanSession */ + packet[remain_pos + 8] = 0x02; + /* keep-alive 0 = disabled */ + packet[remain_pos + 9] = 0x00; + packet[remain_pos + 10] = 0x3c; + /* end of variable header */ + return remain_pos + 10; +} + +static CURLcode mqtt_connect(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + int pos = 0; + int rc = 0; + /* remain length */ + int remain_pos = 0; + char remain[4] = {0}; + size_t packetlen = 0; + size_t payloadlen = 0; + size_t start_user = 0; + size_t start_pwd = 0; + char client_id[MQTT_CLIENTID_LEN + 1] = "curl"; + const size_t clen = strlen("curl"); + char *packet = NULL; + + /* extracting username from request */ + const char *username = data->state.aptr.user ? + data->state.aptr.user : ""; + const size_t ulen = strlen(username); + /* extracting password from request */ + const char *passwd = data->state.aptr.passwd ? + data->state.aptr.passwd : ""; + const size_t plen = strlen(passwd); + + payloadlen = ulen + plen + MQTT_CLIENTID_LEN + 2; + /* The plus 2 are for the MSB and LSB describing the length of the string to + * be added on the payload. Refer to spec 1.5.2 and 1.5.4 */ + if(ulen) + payloadlen += 2; + if(plen) + payloadlen += 2; + + /* getting how much occupy the remain length */ + remain_pos = mqtt_encode_len(remain, payloadlen + 10); + + /* 10 length of variable header and 1 the first byte of the fixed header */ + packetlen = payloadlen + 10 + remain_pos + 1; + + /* allocating packet */ + if(packetlen > 268435455) + return CURLE_WEIRD_SERVER_REPLY; + packet = malloc(packetlen); + if(!packet) + return CURLE_OUT_OF_MEMORY; + memset(packet, 0, packetlen); + + /* set initial values for the CONNECT packet */ + pos = init_connpack(packet, remain, remain_pos); + + result = Curl_rand_alnum(data, (unsigned char *)&client_id[clen], + MQTT_CLIENTID_LEN - clen + 1); + /* add client id */ + rc = add_client_id(client_id, strlen(client_id), packet, pos + 1); + if(rc) { + failf(data, "Client ID length mismatched: [%zu]", strlen(client_id)); + result = CURLE_WEIRD_SERVER_REPLY; + goto end; + } + infof(data, "Using client id '%s'", client_id); + + /* position where starts the user payload */ + start_user = pos + 3 + MQTT_CLIENTID_LEN; + /* position where starts the password payload */ + start_pwd = start_user + ulen; + /* if user name was provided, add it to the packet */ + if(ulen) { + start_pwd += 2; + + rc = add_user(username, ulen, + (unsigned char *)packet, start_user, remain_pos); + if(rc) { + failf(data, "Username is too large: [%zu]", ulen); + result = CURLE_WEIRD_SERVER_REPLY; + goto end; + } + } + + /* if passwd was provided, add it to the packet */ + if(plen) { + rc = add_passwd(passwd, plen, packet, start_pwd, remain_pos); + if(rc) { + failf(data, "Password is too large: [%zu]", plen); + result = CURLE_WEIRD_SERVER_REPLY; + goto end; + } + } + + if(!result) + result = mqtt_send(data, packet, packetlen); + +end: + if(packet) + free(packet); + Curl_safefree(data->state.aptr.user); + Curl_safefree(data->state.aptr.passwd); + return result; +} + +static CURLcode mqtt_disconnect(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct MQTT *mq = data->req.p.mqtt; + result = mqtt_send(data, (char *)"\xe0\x00", 2); + Curl_safefree(mq->sendleftovers); + Curl_dyn_free(&mq->recvbuf); + return result; +} + +static CURLcode mqtt_recv_atleast(struct Curl_easy *data, size_t nbytes) +{ + struct MQTT *mq = data->req.p.mqtt; + size_t rlen = Curl_dyn_len(&mq->recvbuf); + CURLcode result; + + if(rlen < nbytes) { + unsigned char readbuf[1024]; + ssize_t nread; + + DEBUGASSERT(nbytes - rlen < sizeof(readbuf)); + result = Curl_xfer_recv(data, (char *)readbuf, nbytes - rlen, &nread); + if(result) + return result; + DEBUGASSERT(nread >= 0); + if(Curl_dyn_addn(&mq->recvbuf, readbuf, (size_t)nread)) + return CURLE_OUT_OF_MEMORY; + rlen = Curl_dyn_len(&mq->recvbuf); + } + return (rlen >= nbytes)? CURLE_OK : CURLE_AGAIN; +} + +static void mqtt_recv_consume(struct Curl_easy *data, size_t nbytes) +{ + struct MQTT *mq = data->req.p.mqtt; + size_t rlen = Curl_dyn_len(&mq->recvbuf); + if(rlen <= nbytes) + Curl_dyn_reset(&mq->recvbuf); + else + Curl_dyn_tail(&mq->recvbuf, rlen - nbytes); +} + +static CURLcode mqtt_verify_connack(struct Curl_easy *data) +{ + struct MQTT *mq = data->req.p.mqtt; + CURLcode result; + char *ptr; + + result = mqtt_recv_atleast(data, MQTT_CONNACK_LEN); + if(result) + goto fail; + + /* verify CONNACK */ + DEBUGASSERT(Curl_dyn_len(&mq->recvbuf) >= MQTT_CONNACK_LEN); + ptr = Curl_dyn_ptr(&mq->recvbuf); + Curl_debug(data, CURLINFO_HEADER_IN, ptr, MQTT_CONNACK_LEN); + + if(ptr[0] != 0x00 || ptr[1] != 0x00) { + failf(data, "Expected %02x%02x but got %02x%02x", + 0x00, 0x00, ptr[0], ptr[1]); + Curl_dyn_reset(&mq->recvbuf); + result = CURLE_WEIRD_SERVER_REPLY; + goto fail; + } + mqtt_recv_consume(data, MQTT_CONNACK_LEN); +fail: + return result; +} + +static CURLcode mqtt_get_topic(struct Curl_easy *data, + char **topic, size_t *topiclen) +{ + char *path = data->state.up.path; + CURLcode result = CURLE_URL_MALFORMAT; + if(strlen(path) > 1) { + result = Curl_urldecode(path + 1, 0, topic, topiclen, REJECT_NADA); + if(!result && (*topiclen > 0xffff)) { + failf(data, "Too long MQTT topic"); + result = CURLE_URL_MALFORMAT; + } + } + else + failf(data, "No MQTT topic found. Forgot to URL encode it?"); + + return result; +} + +static CURLcode mqtt_subscribe(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + char *topic = NULL; + size_t topiclen; + unsigned char *packet = NULL; + size_t packetlen; + char encodedsize[4]; + size_t n; + struct connectdata *conn = data->conn; + + result = mqtt_get_topic(data, &topic, &topiclen); + if(result) + goto fail; + + conn->proto.mqtt.packetid++; + + packetlen = topiclen + 5; /* packetid + topic (has a two byte length field) + + 2 bytes topic length + QoS byte */ + n = mqtt_encode_len((char *)encodedsize, packetlen); + packetlen += n + 1; /* add one for the control packet type byte */ + + packet = malloc(packetlen); + if(!packet) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + packet[0] = MQTT_MSG_SUBSCRIBE; + memcpy(&packet[1], encodedsize, n); + packet[1 + n] = (conn->proto.mqtt.packetid >> 8) & 0xff; + packet[2 + n] = conn->proto.mqtt.packetid & 0xff; + packet[3 + n] = (topiclen >> 8) & 0xff; + packet[4 + n ] = topiclen & 0xff; + memcpy(&packet[5 + n], topic, topiclen); + packet[5 + n + topiclen] = 0; /* QoS zero */ + + result = mqtt_send(data, (char *)packet, packetlen); + +fail: + free(topic); + free(packet); + return result; +} + +/* + * Called when the first byte was already read. + */ +static CURLcode mqtt_verify_suback(struct Curl_easy *data) +{ + struct MQTT *mq = data->req.p.mqtt; + struct connectdata *conn = data->conn; + struct mqtt_conn *mqtt = &conn->proto.mqtt; + CURLcode result; + char *ptr; + + result = mqtt_recv_atleast(data, MQTT_SUBACK_LEN); + if(result) + goto fail; + + /* verify SUBACK */ + DEBUGASSERT(Curl_dyn_len(&mq->recvbuf) >= MQTT_SUBACK_LEN); + ptr = Curl_dyn_ptr(&mq->recvbuf); + Curl_debug(data, CURLINFO_HEADER_IN, ptr, MQTT_SUBACK_LEN); + + if(((unsigned char)ptr[0]) != ((mqtt->packetid >> 8) & 0xff) || + ((unsigned char)ptr[1]) != (mqtt->packetid & 0xff) || + ptr[2] != 0x00) { + Curl_dyn_reset(&mq->recvbuf); + result = CURLE_WEIRD_SERVER_REPLY; + goto fail; + } + mqtt_recv_consume(data, MQTT_SUBACK_LEN); +fail: + return result; +} + +static CURLcode mqtt_publish(struct Curl_easy *data) +{ + CURLcode result; + char *payload = data->set.postfields; + size_t payloadlen; + char *topic = NULL; + size_t topiclen; + unsigned char *pkt = NULL; + size_t i = 0; + size_t remaininglength; + size_t encodelen; + char encodedbytes[4]; + curl_off_t postfieldsize = data->set.postfieldsize; + + if(!payload) { + DEBUGF(infof(data, "mqtt_publish without payload, return bad arg")); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + if(postfieldsize < 0) + payloadlen = strlen(payload); + else + payloadlen = (size_t)postfieldsize; + + result = mqtt_get_topic(data, &topic, &topiclen); + if(result) + goto fail; + + remaininglength = payloadlen + 2 + topiclen; + encodelen = mqtt_encode_len(encodedbytes, remaininglength); + + /* add the control byte and the encoded remaining length */ + pkt = malloc(remaininglength + 1 + encodelen); + if(!pkt) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + /* assemble packet */ + pkt[i++] = MQTT_MSG_PUBLISH; + memcpy(&pkt[i], encodedbytes, encodelen); + i += encodelen; + pkt[i++] = (topiclen >> 8) & 0xff; + pkt[i++] = (topiclen & 0xff); + memcpy(&pkt[i], topic, topiclen); + i += topiclen; + memcpy(&pkt[i], payload, payloadlen); + i += payloadlen; + result = mqtt_send(data, (char *)pkt, i); + +fail: + free(pkt); + free(topic); + return result; +} + +static size_t mqtt_decode_len(unsigned char *buf, + size_t buflen, size_t *lenbytes) +{ + size_t len = 0; + size_t mult = 1; + size_t i; + unsigned char encoded = 128; + + for(i = 0; (i < buflen) && (encoded & 128); i++) { + encoded = buf[i]; + len += (encoded & 127) * mult; + mult *= 128; + } + + if(lenbytes) + *lenbytes = i; + + return len; +} + +#ifdef CURLDEBUG +static const char *statenames[]={ + "MQTT_FIRST", + "MQTT_REMAINING_LENGTH", + "MQTT_CONNACK", + "MQTT_SUBACK", + "MQTT_SUBACK_COMING", + "MQTT_PUBWAIT", + "MQTT_PUB_REMAIN", + + "NOT A STATE" +}; +#endif + +/* The only way to change state */ +static void mqstate(struct Curl_easy *data, + enum mqttstate state, + enum mqttstate nextstate) /* used if state == FIRST */ +{ + struct connectdata *conn = data->conn; + struct mqtt_conn *mqtt = &conn->proto.mqtt; +#ifdef CURLDEBUG + infof(data, "%s (from %s) (next is %s)", + statenames[state], + statenames[mqtt->state], + (state == MQTT_FIRST)? statenames[nextstate] : ""); +#endif + mqtt->state = state; + if(state == MQTT_FIRST) + mqtt->nextstate = nextstate; +} + + +static CURLcode mqtt_read_publish(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + ssize_t nread; + size_t remlen; + struct mqtt_conn *mqtt = &conn->proto.mqtt; + struct MQTT *mq = data->req.p.mqtt; + unsigned char packet; + + switch(mqtt->state) { +MQTT_SUBACK_COMING: + case MQTT_SUBACK_COMING: + result = mqtt_verify_suback(data); + if(result) + break; + + mqstate(data, MQTT_FIRST, MQTT_PUBWAIT); + break; + + case MQTT_SUBACK: + case MQTT_PUBWAIT: + /* we are expecting PUBLISH or SUBACK */ + packet = mq->firstbyte & 0xf0; + if(packet == MQTT_MSG_PUBLISH) + mqstate(data, MQTT_PUB_REMAIN, MQTT_NOSTATE); + else if(packet == MQTT_MSG_SUBACK) { + mqstate(data, MQTT_SUBACK_COMING, MQTT_NOSTATE); + goto MQTT_SUBACK_COMING; + } + else if(packet == MQTT_MSG_DISCONNECT) { + infof(data, "Got DISCONNECT"); + *done = TRUE; + goto end; + } + else { + result = CURLE_WEIRD_SERVER_REPLY; + goto end; + } + + /* -- switched state -- */ + remlen = mq->remaining_length; + infof(data, "Remaining length: %zu bytes", remlen); + if(data->set.max_filesize && + (curl_off_t)remlen > data->set.max_filesize) { + failf(data, "Maximum file size exceeded"); + result = CURLE_FILESIZE_EXCEEDED; + goto end; + } + Curl_pgrsSetDownloadSize(data, remlen); + data->req.bytecount = 0; + data->req.size = remlen; + mq->npacket = remlen; /* get this many bytes */ + FALLTHROUGH(); + case MQTT_PUB_REMAIN: { + /* read rest of packet, but no more. Cap to buffer size */ + char buffer[4*1024]; + size_t rest = mq->npacket; + if(rest > sizeof(buffer)) + rest = sizeof(buffer); + result = Curl_xfer_recv(data, buffer, rest, &nread); + if(result) { + if(CURLE_AGAIN == result) { + infof(data, "EEEE AAAAGAIN"); + } + goto end; + } + if(!nread) { + infof(data, "server disconnected"); + result = CURLE_PARTIAL_FILE; + goto end; + } + + /* if QoS is set, message contains packet id */ + result = Curl_client_write(data, CLIENTWRITE_BODY, buffer, nread); + if(result) + goto end; + + mq->npacket -= nread; + if(!mq->npacket) + /* no more PUBLISH payload, back to subscribe wait state */ + mqstate(data, MQTT_FIRST, MQTT_PUBWAIT); + break; + } + default: + DEBUGASSERT(NULL); /* illegal state */ + result = CURLE_WEIRD_SERVER_REPLY; + goto end; + } +end: + return result; +} + +static CURLcode mqtt_do(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + *done = FALSE; /* unconditionally */ + + result = mqtt_connect(data); + if(result) { + failf(data, "Error %d sending MQTT CONNECT request", result); + return result; + } + mqstate(data, MQTT_FIRST, MQTT_CONNACK); + return CURLE_OK; +} + +static CURLcode mqtt_done(struct Curl_easy *data, + CURLcode status, bool premature) +{ + struct MQTT *mq = data->req.p.mqtt; + (void)status; + (void)premature; + Curl_safefree(mq->sendleftovers); + Curl_dyn_free(&mq->recvbuf); + return CURLE_OK; +} + +static CURLcode mqtt_doing(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct mqtt_conn *mqtt = &conn->proto.mqtt; + struct MQTT *mq = data->req.p.mqtt; + ssize_t nread; + unsigned char byte; + + *done = FALSE; + + if(mq->nsend) { + /* send the remainder of an outgoing packet */ + char *ptr = mq->sendleftovers; + result = mqtt_send(data, mq->sendleftovers, mq->nsend); + free(ptr); + if(result) + return result; + } + + infof(data, "mqtt_doing: state [%d]", (int) mqtt->state); + switch(mqtt->state) { + case MQTT_FIRST: + /* Read the initial byte only */ + result = Curl_xfer_recv(data, (char *)&mq->firstbyte, 1, &nread); + if(result) + break; + else if(!nread) { + failf(data, "Connection disconnected"); + *done = TRUE; + result = CURLE_RECV_ERROR; + break; + } + Curl_debug(data, CURLINFO_HEADER_IN, (char *)&mq->firstbyte, 1); + /* remember the first byte */ + mq->npacket = 0; + mqstate(data, MQTT_REMAINING_LENGTH, MQTT_NOSTATE); + FALLTHROUGH(); + case MQTT_REMAINING_LENGTH: + do { + result = Curl_xfer_recv(data, (char *)&byte, 1, &nread); + if(result || !nread) + break; + Curl_debug(data, CURLINFO_HEADER_IN, (char *)&byte, 1); + mq->pkt_hd[mq->npacket++] = byte; + } while((byte & 0x80) && (mq->npacket < 4)); + if(!result && nread && (byte & 0x80)) + /* MQTT supports up to 127 * 128^0 + 127 * 128^1 + 127 * 128^2 + + 127 * 128^3 bytes. server tried to send more */ + result = CURLE_WEIRD_SERVER_REPLY; + if(result) + break; + mq->remaining_length = mqtt_decode_len(mq->pkt_hd, mq->npacket, NULL); + mq->npacket = 0; + if(mq->remaining_length) { + mqstate(data, mqtt->nextstate, MQTT_NOSTATE); + break; + } + mqstate(data, MQTT_FIRST, MQTT_FIRST); + + if(mq->firstbyte == MQTT_MSG_DISCONNECT) { + infof(data, "Got DISCONNECT"); + *done = TRUE; + } + break; + case MQTT_CONNACK: + result = mqtt_verify_connack(data); + if(result) + break; + + if(data->state.httpreq == HTTPREQ_POST) { + result = mqtt_publish(data); + if(!result) { + result = mqtt_disconnect(data); + *done = TRUE; + } + mqtt->nextstate = MQTT_FIRST; + } + else { + result = mqtt_subscribe(data); + if(!result) { + mqstate(data, MQTT_FIRST, MQTT_SUBACK); + } + } + break; + + case MQTT_SUBACK: + case MQTT_PUBWAIT: + case MQTT_PUB_REMAIN: + result = mqtt_read_publish(data, done); + break; + + default: + failf(data, "State not handled yet"); + *done = TRUE; + break; + } + + if(result == CURLE_AGAIN) + result = CURLE_OK; + return result; +} + +#endif /* CURL_DISABLE_MQTT */ diff --git a/third_party/curl/lib/mqtt.h b/third_party/curl/lib/mqtt.h new file mode 100644 index 0000000..99ab12a --- /dev/null +++ b/third_party/curl/lib/mqtt.h @@ -0,0 +1,63 @@ +#ifndef HEADER_CURL_MQTT_H +#define HEADER_CURL_MQTT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Björn Stenberg, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifndef CURL_DISABLE_MQTT +extern const struct Curl_handler Curl_handler_mqtt; +#endif + +enum mqttstate { + MQTT_FIRST, /* 0 */ + MQTT_REMAINING_LENGTH, /* 1 */ + MQTT_CONNACK, /* 2 */ + MQTT_SUBACK, /* 3 */ + MQTT_SUBACK_COMING, /* 4 - the SUBACK remainder */ + MQTT_PUBWAIT, /* 5 - wait for publish */ + MQTT_PUB_REMAIN, /* 6 - wait for the remainder of the publish */ + + MQTT_NOSTATE /* 7 - never used an actual state */ +}; + +struct mqtt_conn { + enum mqttstate state; + enum mqttstate nextstate; /* switch to this after remaining length is + done */ + unsigned int packetid; +}; + +/* protocol-specific transfer-related data */ +struct MQTT { + char *sendleftovers; + size_t nsend; /* size of sendleftovers */ + + /* when receiving */ + size_t npacket; /* byte counter */ + unsigned char firstbyte; + size_t remaining_length; + struct dynbuf recvbuf; + unsigned char pkt_hd[4]; /* for decoding the arriving packet length */ +}; + +#endif /* HEADER_CURL_MQTT_H */ diff --git a/third_party/curl/lib/multi.c b/third_party/curl/lib/multi.c new file mode 100644 index 0000000..6bbdfe2 --- /dev/null +++ b/third_party/curl/lib/multi.c @@ -0,0 +1,3937 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "urldata.h" +#include "transfer.h" +#include "url.h" +#include "cfilters.h" +#include "connect.h" +#include "progress.h" +#include "easyif.h" +#include "share.h" +#include "psl.h" +#include "multiif.h" +#include "sendf.h" +#include "timeval.h" +#include "http.h" +#include "select.h" +#include "warnless.h" +#include "speedcheck.h" +#include "conncache.h" +#include "multihandle.h" +#include "sigpipe.h" +#include "vtls/vtls.h" +#include "http_proxy.h" +#include "http2.h" +#include "socketpair.h" +#include "socks.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* + CURL_SOCKET_HASH_TABLE_SIZE should be a prime number. Increasing it from 97 + to 911 takes on a 32-bit machine 4 x 804 = 3211 more bytes. Still, every + CURL handle takes 45-50 K memory, therefore this 3K are not significant. +*/ +#ifndef CURL_SOCKET_HASH_TABLE_SIZE +#define CURL_SOCKET_HASH_TABLE_SIZE 911 +#endif + +#ifndef CURL_CONNECTION_HASH_SIZE +#define CURL_CONNECTION_HASH_SIZE 97 +#endif + +#ifndef CURL_DNS_HASH_SIZE +#define CURL_DNS_HASH_SIZE 71 +#endif + +#define CURL_MULTI_HANDLE 0x000bab1e + +#ifdef DEBUGBUILD +/* On a debug build, we want to fail hard on multi handles that + * are not NULL, but no longer have the MAGIC touch. This gives + * us early warning on things only discovered by valgrind otherwise. */ +#define GOOD_MULTI_HANDLE(x) \ + (((x) && (x)->magic == CURL_MULTI_HANDLE)? TRUE: \ + (DEBUGASSERT(!(x)), FALSE)) +#else +#define GOOD_MULTI_HANDLE(x) \ + ((x) && (x)->magic == CURL_MULTI_HANDLE) +#endif + +static void move_pending_to_connect(struct Curl_multi *multi, + struct Curl_easy *data); +static CURLMcode singlesocket(struct Curl_multi *multi, + struct Curl_easy *data); +static CURLMcode add_next_timeout(struct curltime now, + struct Curl_multi *multi, + struct Curl_easy *d); +static CURLMcode multi_timeout(struct Curl_multi *multi, + long *timeout_ms); +static void process_pending_handles(struct Curl_multi *multi); +static void multi_xfer_bufs_free(struct Curl_multi *multi); + +#ifdef DEBUGBUILD +static const char * const multi_statename[]={ + "INIT", + "PENDING", + "SETUP", + "CONNECT", + "RESOLVING", + "CONNECTING", + "TUNNELING", + "PROTOCONNECT", + "PROTOCONNECTING", + "DO", + "DOING", + "DOING_MORE", + "DID", + "PERFORMING", + "RATELIMITING", + "DONE", + "COMPLETED", + "MSGSENT", +}; +#endif + +/* function pointer called once when switching TO a state */ +typedef void (*init_multistate_func)(struct Curl_easy *data); + +/* called in DID state, before PERFORMING state */ +static void before_perform(struct Curl_easy *data) +{ + data->req.chunk = FALSE; + Curl_pgrsTime(data, TIMER_PRETRANSFER); +} + +static void init_completed(struct Curl_easy *data) +{ + /* this is a completed transfer */ + + /* Important: reset the conn pointer so that we don't point to memory + that could be freed anytime */ + Curl_detach_connection(data); + Curl_expire_clear(data); /* stop all timers */ +} + +/* always use this function to change state, to make debugging easier */ +static void mstate(struct Curl_easy *data, CURLMstate state +#ifdef DEBUGBUILD + , int lineno +#endif +) +{ + CURLMstate oldstate = data->mstate; + static const init_multistate_func finit[MSTATE_LAST] = { + NULL, /* INIT */ + NULL, /* PENDING */ + NULL, /* SETUP */ + Curl_init_CONNECT, /* CONNECT */ + NULL, /* RESOLVING */ + NULL, /* CONNECTING */ + NULL, /* TUNNELING */ + NULL, /* PROTOCONNECT */ + NULL, /* PROTOCONNECTING */ + NULL, /* DO */ + NULL, /* DOING */ + NULL, /* DOING_MORE */ + before_perform, /* DID */ + NULL, /* PERFORMING */ + NULL, /* RATELIMITING */ + NULL, /* DONE */ + init_completed, /* COMPLETED */ + NULL /* MSGSENT */ + }; + +#if defined(DEBUGBUILD) && defined(CURL_DISABLE_VERBOSE_STRINGS) + (void) lineno; +#endif + + if(oldstate == state) + /* don't bother when the new state is the same as the old state */ + return; + + data->mstate = state; + +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + if(data->mstate >= MSTATE_PENDING && + data->mstate < MSTATE_COMPLETED) { + infof(data, + "STATE: %s => %s handle %p; line %d", + multi_statename[oldstate], multi_statename[data->mstate], + (void *)data, lineno); + } +#endif + + if(state == MSTATE_COMPLETED) { + /* changing to COMPLETED means there's one less easy handle 'alive' */ + DEBUGASSERT(data->multi->num_alive > 0); + data->multi->num_alive--; + if(!data->multi->num_alive) { + /* free the transfer buffer when we have no more active transfers */ + multi_xfer_bufs_free(data->multi); + } + } + + /* if this state has an init-function, run it */ + if(finit[state]) + finit[state](data); +} + +#ifndef DEBUGBUILD +#define multistate(x,y) mstate(x,y) +#else +#define multistate(x,y) mstate(x,y, __LINE__) +#endif + +/* + * We add one of these structs to the sockhash for each socket + */ + +struct Curl_sh_entry { + struct Curl_hash transfers; /* hash of transfers using this socket */ + unsigned int action; /* what combined action READ/WRITE this socket waits + for */ + unsigned int users; /* number of transfers using this */ + void *socketp; /* settable by users with curl_multi_assign() */ + unsigned int readers; /* this many transfers want to read */ + unsigned int writers; /* this many transfers want to write */ +}; + +/* look up a given socket in the socket hash, skip invalid sockets */ +static struct Curl_sh_entry *sh_getentry(struct Curl_hash *sh, + curl_socket_t s) +{ + if(s != CURL_SOCKET_BAD) { + /* only look for proper sockets */ + return Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t)); + } + return NULL; +} + +#define TRHASH_SIZE 13 +static size_t trhash(void *key, size_t key_length, size_t slots_num) +{ + size_t keyval = (size_t)*(struct Curl_easy **)key; + (void) key_length; + + return (keyval % slots_num); +} + +static size_t trhash_compare(void *k1, size_t k1_len, void *k2, size_t k2_len) +{ + (void)k1_len; + (void)k2_len; + + return *(struct Curl_easy **)k1 == *(struct Curl_easy **)k2; +} + +static void trhash_dtor(void *nada) +{ + (void)nada; +} + +/* + * The sockhash has its own separate subhash in each entry that need to be + * safely destroyed first. + */ +static void sockhash_destroy(struct Curl_hash *h) +{ + struct Curl_hash_iterator iter; + struct Curl_hash_element *he; + + DEBUGASSERT(h); + Curl_hash_start_iterate(h, &iter); + he = Curl_hash_next_element(&iter); + while(he) { + struct Curl_sh_entry *sh = (struct Curl_sh_entry *)he->ptr; + Curl_hash_destroy(&sh->transfers); + he = Curl_hash_next_element(&iter); + } + Curl_hash_destroy(h); +} + + +/* make sure this socket is present in the hash for this handle */ +static struct Curl_sh_entry *sh_addentry(struct Curl_hash *sh, + curl_socket_t s) +{ + struct Curl_sh_entry *there = sh_getentry(sh, s); + struct Curl_sh_entry *check; + + if(there) { + /* it is present, return fine */ + return there; + } + + /* not present, add it */ + check = calloc(1, sizeof(struct Curl_sh_entry)); + if(!check) + return NULL; /* major failure */ + + Curl_hash_init(&check->transfers, TRHASH_SIZE, trhash, trhash_compare, + trhash_dtor); + + /* make/add new hash entry */ + if(!Curl_hash_add(sh, (char *)&s, sizeof(curl_socket_t), check)) { + Curl_hash_destroy(&check->transfers); + free(check); + return NULL; /* major failure */ + } + + return check; /* things are good in sockhash land */ +} + + +/* delete the given socket + handle from the hash */ +static void sh_delentry(struct Curl_sh_entry *entry, + struct Curl_hash *sh, curl_socket_t s) +{ + Curl_hash_destroy(&entry->transfers); + + /* We remove the hash entry. This will end up in a call to + sh_freeentry(). */ + Curl_hash_delete(sh, (char *)&s, sizeof(curl_socket_t)); +} + +/* + * free a sockhash entry + */ +static void sh_freeentry(void *freethis) +{ + struct Curl_sh_entry *p = (struct Curl_sh_entry *) freethis; + + free(p); +} + +static size_t fd_key_compare(void *k1, size_t k1_len, void *k2, size_t k2_len) +{ + (void) k1_len; (void) k2_len; + + return (*((curl_socket_t *) k1)) == (*((curl_socket_t *) k2)); +} + +static size_t hash_fd(void *key, size_t key_length, size_t slots_num) +{ + curl_socket_t fd = *((curl_socket_t *) key); + (void) key_length; + + return (fd % slots_num); +} + +/* + * sh_init() creates a new socket hash and returns the handle for it. + * + * Quote from README.multi_socket: + * + * "Some tests at 7000 and 9000 connections showed that the socket hash lookup + * is somewhat of a bottle neck. Its current implementation may be a bit too + * limiting. It simply has a fixed-size array, and on each entry in the array + * it has a linked list with entries. So the hash only checks which list to + * scan through. The code I had used so for used a list with merely 7 slots + * (as that is what the DNS hash uses) but with 7000 connections that would + * make an average of 1000 nodes in each list to run through. I upped that to + * 97 slots (I believe a prime is suitable) and noticed a significant speed + * increase. I need to reconsider the hash implementation or use a rather + * large default value like this. At 9000 connections I was still below 10us + * per call." + * + */ +static void sh_init(struct Curl_hash *hash, size_t hashsize) +{ + Curl_hash_init(hash, hashsize, hash_fd, fd_key_compare, + sh_freeentry); +} + +/* + * multi_addmsg() + * + * Called when a transfer is completed. Adds the given msg pointer to + * the list kept in the multi handle. + */ +static void multi_addmsg(struct Curl_multi *multi, struct Curl_message *msg) +{ + Curl_llist_append(&multi->msglist, msg, &msg->list); +} + +struct Curl_multi *Curl_multi_handle(size_t hashsize, /* socket hash */ + size_t chashsize, /* connection hash */ + size_t dnssize) /* dns hash */ +{ + struct Curl_multi *multi = calloc(1, sizeof(struct Curl_multi)); + + if(!multi) + return NULL; + + multi->magic = CURL_MULTI_HANDLE; + + Curl_init_dnscache(&multi->hostcache, dnssize); + + sh_init(&multi->sockhash, hashsize); + + if(Curl_conncache_init(&multi->conn_cache, chashsize)) + goto error; + + Curl_llist_init(&multi->msglist, NULL); + Curl_llist_init(&multi->pending, NULL); + Curl_llist_init(&multi->msgsent, NULL); + + multi->multiplexing = TRUE; + multi->max_concurrent_streams = 100; + +#ifdef USE_WINSOCK + multi->wsa_event = WSACreateEvent(); + if(multi->wsa_event == WSA_INVALID_EVENT) + goto error; +#else +#ifdef ENABLE_WAKEUP + if(wakeup_create(multi->wakeup_pair) < 0) { + multi->wakeup_pair[0] = CURL_SOCKET_BAD; + multi->wakeup_pair[1] = CURL_SOCKET_BAD; + } + else if(curlx_nonblock(multi->wakeup_pair[0], TRUE) < 0 || + curlx_nonblock(multi->wakeup_pair[1], TRUE) < 0) { + wakeup_close(multi->wakeup_pair[0]); + wakeup_close(multi->wakeup_pair[1]); + multi->wakeup_pair[0] = CURL_SOCKET_BAD; + multi->wakeup_pair[1] = CURL_SOCKET_BAD; + } +#endif +#endif + + return multi; + +error: + + sockhash_destroy(&multi->sockhash); + Curl_hash_destroy(&multi->hostcache); + Curl_conncache_destroy(&multi->conn_cache); + free(multi); + return NULL; +} + +struct Curl_multi *curl_multi_init(void) +{ + return Curl_multi_handle(CURL_SOCKET_HASH_TABLE_SIZE, + CURL_CONNECTION_HASH_SIZE, + CURL_DNS_HASH_SIZE); +} + +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) +static void multi_warn_debug(struct Curl_multi *multi, struct Curl_easy *data) +{ + if(!multi->warned) { + infof(data, "!!! WARNING !!!"); + infof(data, "This is a debug build of libcurl, " + "do not use in production."); + multi->warned = true; + } +} +#else +#define multi_warn_debug(x,y) Curl_nop_stmt +#endif + +/* returns TRUE if the easy handle is supposed to be present in the main link + list */ +static bool in_main_list(struct Curl_easy *data) +{ + return ((data->mstate != MSTATE_PENDING) && + (data->mstate != MSTATE_MSGSENT)); +} + +static void link_easy(struct Curl_multi *multi, + struct Curl_easy *data) +{ + /* We add the new easy entry last in the list. */ + data->next = NULL; /* end of the line */ + if(multi->easyp) { + struct Curl_easy *last = multi->easylp; + last->next = data; + data->prev = last; + multi->easylp = data; /* the new last node */ + } + else { + /* first node, make prev NULL! */ + data->prev = NULL; + multi->easylp = multi->easyp = data; /* both first and last */ + } +} + +/* unlink the given easy handle from the linked list of easy handles */ +static void unlink_easy(struct Curl_multi *multi, + struct Curl_easy *data) +{ + /* make the previous node point to our next */ + if(data->prev) + data->prev->next = data->next; + else + multi->easyp = data->next; /* point to first node */ + + /* make our next point to our previous node */ + if(data->next) + data->next->prev = data->prev; + else + multi->easylp = data->prev; /* point to last node */ + + data->prev = data->next = NULL; +} + + +CURLMcode curl_multi_add_handle(struct Curl_multi *multi, + struct Curl_easy *data) +{ + CURLMcode rc; + /* First, make some basic checks that the CURLM handle is a good handle */ + if(!GOOD_MULTI_HANDLE(multi)) + return CURLM_BAD_HANDLE; + + /* Verify that we got a somewhat good easy handle too */ + if(!GOOD_EASY_HANDLE(data)) + return CURLM_BAD_EASY_HANDLE; + + /* Prevent users from adding same easy handle more than once and prevent + adding to more than one multi stack */ + if(data->multi) + return CURLM_ADDED_ALREADY; + + if(multi->in_callback) + return CURLM_RECURSIVE_API_CALL; + + if(multi->dead) { + /* a "dead" handle cannot get added transfers while any existing easy + handles are still alive - but if there are none alive anymore, it is + fine to start over and unmark the "deadness" of this handle */ + if(multi->num_alive) + return CURLM_ABORTED_BY_CALLBACK; + multi->dead = FALSE; + } + + if(data->multi_easy) { + /* if this easy handle was previously used for curl_easy_perform(), there + is a private multi handle here that we can kill */ + curl_multi_cleanup(data->multi_easy); + data->multi_easy = NULL; + } + + /* Initialize timeout list for this handle */ + Curl_llist_init(&data->state.timeoutlist, NULL); + + /* + * No failure allowed in this function beyond this point. And no + * modification of easy nor multi handle allowed before this except for + * potential multi's connection cache growing which won't be undone in this + * function no matter what. + */ + if(data->set.errorbuffer) + data->set.errorbuffer[0] = 0; + + data->state.os_errno = 0; + + /* make the Curl_easy refer back to this multi handle - before Curl_expire() + is called. */ + data->multi = multi; + + /* Set the timeout for this handle to expire really soon so that it will + be taken care of even when this handle is added in the midst of operation + when only the curl_multi_socket() API is used. During that flow, only + sockets that time-out or have actions will be dealt with. Since this + handle has no action yet, we make sure it times out to get things to + happen. */ + Curl_expire(data, 0, EXPIRE_RUN_NOW); + + /* A somewhat crude work-around for a little glitch in Curl_update_timer() + that happens if the lastcall time is set to the same time when the handle + is removed as when the next handle is added, as then the check in + Curl_update_timer() that prevents calling the application multiple times + with the same timer info will not trigger and then the new handle's + timeout will not be notified to the app. + + The work-around is thus simply to clear the 'lastcall' variable to force + Curl_update_timer() to always trigger a callback to the app when a new + easy handle is added */ + memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall)); + + rc = Curl_update_timer(multi); + if(rc) + return rc; + + /* set the easy handle */ + multistate(data, MSTATE_INIT); + + /* for multi interface connections, we share DNS cache automatically if the + easy handle's one is currently not set. */ + if(!data->dns.hostcache || + (data->dns.hostcachetype == HCACHE_NONE)) { + data->dns.hostcache = &multi->hostcache; + data->dns.hostcachetype = HCACHE_MULTI; + } + + /* Point to the shared or multi handle connection cache */ + if(data->share && (data->share->specifier & (1<< CURL_LOCK_DATA_CONNECT))) + data->state.conn_cache = &data->share->conn_cache; + else + data->state.conn_cache = &multi->conn_cache; + data->state.lastconnect_id = -1; + +#ifdef USE_LIBPSL + /* Do the same for PSL. */ + if(data->share && (data->share->specifier & (1 << CURL_LOCK_DATA_PSL))) + data->psl = &data->share->psl; + else + data->psl = &multi->psl; +#endif + + link_easy(multi, data); + + /* increase the node-counter */ + multi->num_easy++; + + /* increase the alive-counter */ + multi->num_alive++; + + CONNCACHE_LOCK(data); + /* The closure handle only ever has default timeouts set. To improve the + state somewhat we clone the timeouts from each added handle so that the + closure handle always has the same timeouts as the most recently added + easy handle. */ + data->state.conn_cache->closure_handle->set.timeout = data->set.timeout; + data->state.conn_cache->closure_handle->set.server_response_timeout = + data->set.server_response_timeout; + data->state.conn_cache->closure_handle->set.no_signal = + data->set.no_signal; + data->id = data->state.conn_cache->next_easy_id++; + if(data->state.conn_cache->next_easy_id <= 0) + data->state.conn_cache->next_easy_id = 0; + CONNCACHE_UNLOCK(data); + + multi_warn_debug(multi, data); + + return CURLM_OK; +} + +#if 0 +/* Debug-function, used like this: + * + * Curl_hash_print(&multi->sockhash, debug_print_sock_hash); + * + * Enable the hash print function first by editing hash.c + */ +static void debug_print_sock_hash(void *p) +{ + struct Curl_sh_entry *sh = (struct Curl_sh_entry *)p; + + fprintf(stderr, " [readers %u][writers %u]", + sh->readers, sh->writers); +} +#endif + +static CURLcode multi_done(struct Curl_easy *data, + CURLcode status, /* an error if this is called + after an error was detected */ + bool premature) +{ + CURLcode result, r2; + struct connectdata *conn = data->conn; + +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + DEBUGF(infof(data, "multi_done[%s]: status: %d prem: %d done: %d", + multi_statename[data->mstate], + (int)status, (int)premature, data->state.done)); +#else + DEBUGF(infof(data, "multi_done: status: %d prem: %d done: %d", + (int)status, (int)premature, data->state.done)); +#endif + + if(data->state.done) + /* Stop if multi_done() has already been called */ + return CURLE_OK; + + /* Stop the resolver and free its own resources (but not dns_entry yet). */ + Curl_resolver_kill(data); + + /* Cleanup possible redirect junk */ + Curl_safefree(data->req.newurl); + Curl_safefree(data->req.location); + + switch(status) { + case CURLE_ABORTED_BY_CALLBACK: + case CURLE_READ_ERROR: + case CURLE_WRITE_ERROR: + /* When we're aborted due to a callback return code it basically have to + be counted as premature as there is trouble ahead if we don't. We have + many callbacks and protocols work differently, we could potentially do + this more fine-grained in the future. */ + premature = TRUE; + FALLTHROUGH(); + default: + break; + } + + /* this calls the protocol-specific function pointer previously set */ + if(conn->handler->done) + result = conn->handler->done(data, status, premature); + else + result = status; + + if(CURLE_ABORTED_BY_CALLBACK != result) { + /* avoid this if we already aborted by callback to avoid this calling + another callback */ + int rc = Curl_pgrsDone(data); + if(!result && rc) + result = CURLE_ABORTED_BY_CALLBACK; + } + + /* Make sure that transfer client writes are really done now. */ + r2 = Curl_xfer_write_done(data, premature); + if(r2 && !result) + result = r2; + + /* Inform connection filters that this transfer is done */ + Curl_conn_ev_data_done(data, premature); + + process_pending_handles(data->multi); /* connection / multiplex */ + + if(!result) + result = Curl_req_done(&data->req, data, premature); + + CONNCACHE_LOCK(data); + Curl_detach_connection(data); + if(CONN_INUSE(conn)) { + /* Stop if still used. */ + CONNCACHE_UNLOCK(data); + DEBUGF(infof(data, "Connection still in use %zu, " + "no more multi_done now!", + conn->easyq.size)); + return CURLE_OK; + } + + data->state.done = TRUE; /* called just now! */ + + if(conn->dns_entry) { + Curl_resolv_unlock(data, conn->dns_entry); /* done with this */ + conn->dns_entry = NULL; + } + Curl_hostcache_prune(data); + + /* if data->set.reuse_forbid is TRUE, it means the libcurl client has + forced us to close this connection. This is ignored for requests taking + place in a NTLM/NEGOTIATE authentication handshake + + if conn->bits.close is TRUE, it means that the connection should be + closed in spite of all our efforts to be nice, due to protocol + restrictions in our or the server's end + + if premature is TRUE, it means this connection was said to be DONE before + the entire request operation is complete and thus we can't know in what + state it is for reusing, so we're forced to close it. In a perfect world + we can add code that keep track of if we really must close it here or not, + but currently we have no such detail knowledge. + */ + + data->state.recent_conn_id = conn->connection_id; + if((data->set.reuse_forbid +#if defined(USE_NTLM) + && !(conn->http_ntlm_state == NTLMSTATE_TYPE2 || + conn->proxy_ntlm_state == NTLMSTATE_TYPE2) +#endif +#if defined(USE_SPNEGO) + && !(conn->http_negotiate_state == GSS_AUTHRECV || + conn->proxy_negotiate_state == GSS_AUTHRECV) +#endif + ) || conn->bits.close + || (premature && !Curl_conn_is_multiplex(conn, FIRSTSOCKET))) { + DEBUGF(infof(data, "multi_done, not reusing connection=%" + CURL_FORMAT_CURL_OFF_T ", forbid=%d" + ", close=%d, premature=%d, conn_multiplex=%d", + conn->connection_id, + data->set.reuse_forbid, conn->bits.close, premature, + Curl_conn_is_multiplex(conn, FIRSTSOCKET))); + connclose(conn, "disconnecting"); + Curl_conncache_remove_conn(data, conn, FALSE); + CONNCACHE_UNLOCK(data); + Curl_disconnect(data, conn, premature); + } + else { + char buffer[256]; + const char *host = +#ifndef CURL_DISABLE_PROXY + conn->bits.socksproxy ? + conn->socks_proxy.host.dispname : + conn->bits.httpproxy ? conn->http_proxy.host.dispname : +#endif + conn->bits.conn_to_host ? conn->conn_to_host.dispname : + conn->host.dispname; + /* create string before returning the connection */ + curl_off_t connection_id = conn->connection_id; + msnprintf(buffer, sizeof(buffer), + "Connection #%" CURL_FORMAT_CURL_OFF_T " to host %s left intact", + connection_id, host); + /* the connection is no longer in use by this transfer */ + CONNCACHE_UNLOCK(data); + if(Curl_conncache_return_conn(data, conn)) { + /* remember the most recently used connection */ + data->state.lastconnect_id = connection_id; + data->state.recent_conn_id = connection_id; + infof(data, "%s", buffer); + } + else + data->state.lastconnect_id = -1; + } + + return result; +} + +static int close_connect_only(struct Curl_easy *data, + struct connectdata *conn, void *param) +{ + (void)param; + if(data->state.lastconnect_id != conn->connection_id) + return 0; + + if(!conn->connect_only) + return 1; + + connclose(conn, "Removing connect-only easy handle"); + + return 1; +} + +CURLMcode curl_multi_remove_handle(struct Curl_multi *multi, + struct Curl_easy *data) +{ + struct Curl_easy *easy = data; + bool premature; + struct Curl_llist_element *e; + CURLMcode rc; + + /* First, make some basic checks that the CURLM handle is a good handle */ + if(!GOOD_MULTI_HANDLE(multi)) + return CURLM_BAD_HANDLE; + + /* Verify that we got a somewhat good easy handle too */ + if(!GOOD_EASY_HANDLE(data)) + return CURLM_BAD_EASY_HANDLE; + + /* Prevent users from trying to remove same easy handle more than once */ + if(!data->multi) + return CURLM_OK; /* it is already removed so let's say it is fine! */ + + /* Prevent users from trying to remove an easy handle from the wrong multi */ + if(data->multi != multi) + return CURLM_BAD_EASY_HANDLE; + + if(multi->in_callback) + return CURLM_RECURSIVE_API_CALL; + + premature = (data->mstate < MSTATE_COMPLETED) ? TRUE : FALSE; + + /* If the 'state' is not INIT or COMPLETED, we might need to do something + nice to put the easy_handle in a good known state when this returns. */ + if(premature) { + /* this handle is "alive" so we need to count down the total number of + alive connections when this is removed */ + multi->num_alive--; + } + + if(data->conn && + data->mstate > MSTATE_DO && + data->mstate < MSTATE_COMPLETED) { + /* Set connection owner so that the DONE function closes it. We can + safely do this here since connection is killed. */ + streamclose(data->conn, "Removed with partial response"); + } + + if(data->conn) { + /* multi_done() clears the association between the easy handle and the + connection. + + Note that this ignores the return code simply because there's + nothing really useful to do with it anyway! */ + (void)multi_done(data, data->result, premature); + } + + /* The timer must be shut down before data->multi is set to NULL, else the + timenode will remain in the splay tree after curl_easy_cleanup is + called. Do it after multi_done() in case that sets another time! */ + Curl_expire_clear(data); + + if(data->connect_queue.ptr) { + /* the handle is in the pending or msgsent lists, so go ahead and remove + it */ + if(data->mstate == MSTATE_PENDING) + Curl_llist_remove(&multi->pending, &data->connect_queue, NULL); + else + Curl_llist_remove(&multi->msgsent, &data->connect_queue, NULL); + } + if(in_main_list(data)) + unlink_easy(multi, data); + + if(data->dns.hostcachetype == HCACHE_MULTI) { + /* stop using the multi handle's DNS cache, *after* the possible + multi_done() call above */ + data->dns.hostcache = NULL; + data->dns.hostcachetype = HCACHE_NONE; + } + + Curl_wildcard_dtor(&data->wildcard); + + /* change state without using multistate(), only to make singlesocket() do + what we want */ + data->mstate = MSTATE_COMPLETED; + + /* This ignores the return code even in case of problems because there's + nothing more to do about that, here */ + (void)singlesocket(multi, easy); /* to let the application know what sockets + that vanish with this handle */ + + /* Remove the association between the connection and the handle */ + Curl_detach_connection(data); + + if(data->set.connect_only && !data->multi_easy) { + /* This removes a handle that was part the multi interface that used + CONNECT_ONLY, that connection is now left alive but since this handle + has bits.close set nothing can use that transfer anymore and it is + forbidden from reuse. And this easy handle cannot find the connection + anymore once removed from the multi handle + + Better close the connection here, at once. + */ + struct connectdata *c; + curl_socket_t s; + s = Curl_getconnectinfo(data, &c); + if((s != CURL_SOCKET_BAD) && c) { + Curl_conncache_remove_conn(data, c, TRUE); + Curl_disconnect(data, c, TRUE); + } + } + + if(data->state.lastconnect_id != -1) { + /* Mark any connect-only connection for closure */ + Curl_conncache_foreach(data, data->state.conn_cache, + NULL, close_connect_only); + } + +#ifdef USE_LIBPSL + /* Remove the PSL association. */ + if(data->psl == &multi->psl) + data->psl = NULL; +#endif + + /* as this was using a shared connection cache we clear the pointer to that + since we're not part of that multi handle anymore */ + data->state.conn_cache = NULL; + + data->multi = NULL; /* clear the association to this multi handle */ + + /* make sure there's no pending message in the queue sent from this easy + handle */ + for(e = multi->msglist.head; e; e = e->next) { + struct Curl_message *msg = e->ptr; + + if(msg->extmsg.easy_handle == easy) { + Curl_llist_remove(&multi->msglist, e, NULL); + /* there can only be one from this specific handle */ + break; + } + } + + /* NOTE NOTE NOTE + We do not touch the easy handle here! */ + multi->num_easy--; /* one less to care about now */ + + process_pending_handles(multi); + + rc = Curl_update_timer(multi); + if(rc) + return rc; + return CURLM_OK; +} + +/* Return TRUE if the application asked for multiplexing */ +bool Curl_multiplex_wanted(const struct Curl_multi *multi) +{ + return (multi && (multi->multiplexing)); +} + +/* + * Curl_detach_connection() removes the given transfer from the connection. + * + * This is the only function that should clear data->conn. This will + * occasionally be called with the data->conn pointer already cleared. + */ +void Curl_detach_connection(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + if(conn) { + Curl_conn_ev_data_detach(conn, data); + Curl_llist_remove(&conn->easyq, &data->conn_queue, NULL); + } + data->conn = NULL; +} + +/* + * Curl_attach_connection() attaches this transfer to this connection. + * + * This is the only function that should assign data->conn + */ +void Curl_attach_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + DEBUGASSERT(!data->conn); + DEBUGASSERT(conn); + data->conn = conn; + Curl_llist_append(&conn->easyq, data, &data->conn_queue); + if(conn->handler && conn->handler->attach) + conn->handler->attach(data, conn); + Curl_conn_ev_data_attach(conn, data); +} + +static int connecting_getsock(struct Curl_easy *data, curl_socket_t *socks) +{ + struct connectdata *conn = data->conn; + (void)socks; + /* Not using `conn->sockfd` as `Curl_xfer_setup()` initializes + * that *after* the connect. */ + if(conn && conn->sock[FIRSTSOCKET] != CURL_SOCKET_BAD) { + /* Default is to wait to something from the server */ + socks[0] = conn->sock[FIRSTSOCKET]; + return GETSOCK_READSOCK(0); + } + return GETSOCK_BLANK; +} + +static int protocol_getsock(struct Curl_easy *data, curl_socket_t *socks) +{ + struct connectdata *conn = data->conn; + if(conn && conn->handler->proto_getsock) + return conn->handler->proto_getsock(data, conn, socks); + else if(conn && conn->sockfd != CURL_SOCKET_BAD) { + /* Default is to wait to something from the server */ + socks[0] = conn->sockfd; + return GETSOCK_READSOCK(0); + } + return GETSOCK_BLANK; +} + +static int domore_getsock(struct Curl_easy *data, curl_socket_t *socks) +{ + struct connectdata *conn = data->conn; + if(conn && conn->handler->domore_getsock) + return conn->handler->domore_getsock(data, conn, socks); + else if(conn && conn->sockfd != CURL_SOCKET_BAD) { + /* Default is that we want to send something to the server */ + socks[0] = conn->sockfd; + return GETSOCK_WRITESOCK(0); + } + return GETSOCK_BLANK; +} + +static int doing_getsock(struct Curl_easy *data, curl_socket_t *socks) +{ + struct connectdata *conn = data->conn; + if(conn && conn->handler->doing_getsock) + return conn->handler->doing_getsock(data, conn, socks); + else if(conn && conn->sockfd != CURL_SOCKET_BAD) { + /* Default is that we want to send something to the server */ + socks[0] = conn->sockfd; + return GETSOCK_WRITESOCK(0); + } + return GETSOCK_BLANK; +} + +static int perform_getsock(struct Curl_easy *data, curl_socket_t *sock) +{ + struct connectdata *conn = data->conn; + + if(!conn) + return GETSOCK_BLANK; + else if(conn->handler->perform_getsock) + return conn->handler->perform_getsock(data, conn, sock); + else { + /* Default is to obey the data->req.keepon flags for send/recv */ + int bitmap = GETSOCK_BLANK; + unsigned sockindex = 0; + if(CURL_WANT_RECV(data)) { + DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD); + bitmap |= GETSOCK_READSOCK(sockindex); + sock[sockindex] = conn->sockfd; + } + + if(CURL_WANT_SEND(data)) { + if((conn->sockfd != conn->writesockfd) || + bitmap == GETSOCK_BLANK) { + /* only if they are not the same socket and we have a readable + one, we increase index */ + if(bitmap != GETSOCK_BLANK) + sockindex++; /* increase index if we need two entries */ + + DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD); + sock[sockindex] = conn->writesockfd; + } + bitmap |= GETSOCK_WRITESOCK(sockindex); + } + return bitmap; + } +} + +/* Initializes `poll_set` with the current socket poll actions needed + * for transfer `data`. */ +static void multi_getsock(struct Curl_easy *data, + struct easy_pollset *ps) +{ + /* The no connection case can happen when this is called from + curl_multi_remove_handle() => singlesocket() => multi_getsock(). + */ + Curl_pollset_reset(data, ps); + if(!data->conn) + return; + + switch(data->mstate) { + case MSTATE_INIT: + case MSTATE_PENDING: + case MSTATE_SETUP: + case MSTATE_CONNECT: + /* nothing to poll for yet */ + break; + + case MSTATE_RESOLVING: + Curl_pollset_add_socks(data, ps, Curl_resolv_getsock); + /* connection filters are not involved in this phase */ + break; + + case MSTATE_CONNECTING: + case MSTATE_TUNNELING: + Curl_pollset_add_socks(data, ps, connecting_getsock); + Curl_conn_adjust_pollset(data, ps); + break; + + case MSTATE_PROTOCONNECT: + case MSTATE_PROTOCONNECTING: + Curl_pollset_add_socks(data, ps, protocol_getsock); + Curl_conn_adjust_pollset(data, ps); + break; + + case MSTATE_DO: + case MSTATE_DOING: + Curl_pollset_add_socks(data, ps, doing_getsock); + Curl_conn_adjust_pollset(data, ps); + break; + + case MSTATE_DOING_MORE: + Curl_pollset_add_socks(data, ps, domore_getsock); + Curl_conn_adjust_pollset(data, ps); + break; + + case MSTATE_DID: /* same as PERFORMING in regard to polling */ + case MSTATE_PERFORMING: + Curl_pollset_add_socks(data, ps, perform_getsock); + Curl_conn_adjust_pollset(data, ps); + break; + + case MSTATE_RATELIMITING: + /* we need to let time pass, ignore socket(s) */ + break; + + case MSTATE_DONE: + case MSTATE_COMPLETED: + case MSTATE_MSGSENT: + /* nothing more to poll for */ + break; + + default: + failf(data, "multi_getsock: unexpected multi state %d", data->mstate); + DEBUGASSERT(0); + break; + } +} + +CURLMcode curl_multi_fdset(struct Curl_multi *multi, + fd_set *read_fd_set, fd_set *write_fd_set, + fd_set *exc_fd_set, int *max_fd) +{ + /* Scan through all the easy handles to get the file descriptors set. + Some easy handles may not have connected to the remote host yet, + and then we must make sure that is done. */ + struct Curl_easy *data; + int this_max_fd = -1; + struct easy_pollset ps; + unsigned int i; + (void)exc_fd_set; /* not used */ + + if(!GOOD_MULTI_HANDLE(multi)) + return CURLM_BAD_HANDLE; + + if(multi->in_callback) + return CURLM_RECURSIVE_API_CALL; + + memset(&ps, 0, sizeof(ps)); + for(data = multi->easyp; data; data = data->next) { + multi_getsock(data, &ps); + + for(i = 0; i < ps.num; i++) { + if(!FDSET_SOCK(ps.sockets[i])) + /* pretend it doesn't exist */ + continue; + if(ps.actions[i] & CURL_POLL_IN) + FD_SET(ps.sockets[i], read_fd_set); + if(ps.actions[i] & CURL_POLL_OUT) + FD_SET(ps.sockets[i], write_fd_set); + if((int)ps.sockets[i] > this_max_fd) + this_max_fd = (int)ps.sockets[i]; + } + } + + *max_fd = this_max_fd; + + return CURLM_OK; +} + +CURLMcode curl_multi_waitfds(struct Curl_multi *multi, + struct curl_waitfd *ufds, + unsigned int size, + unsigned int *fd_count) +{ + struct Curl_easy *data; + unsigned int nfds = 0; + struct easy_pollset ps; + unsigned int i; + CURLMcode result = CURLM_OK; + struct curl_waitfd *ufd; + unsigned int j; + + if(!ufds) + return CURLM_BAD_FUNCTION_ARGUMENT; + + if(!GOOD_MULTI_HANDLE(multi)) + return CURLM_BAD_HANDLE; + + if(multi->in_callback) + return CURLM_RECURSIVE_API_CALL; + + memset(&ps, 0, sizeof(ps)); + for(data = multi->easyp; data; data = data->next) { + multi_getsock(data, &ps); + + for(i = 0; i < ps.num; i++) { + if(nfds < size) { + curl_socket_t fd = ps.sockets[i]; + int fd_idx = -1; + + /* Simple linear search to skip an already added descriptor */ + for(j = 0; j < nfds; j++) { + if(ufds[j].fd == fd) { + fd_idx = (int)j; + break; + } + } + + if(fd_idx < 0) { + ufd = &ufds[nfds++]; + ufd->fd = ps.sockets[i]; + ufd->events = 0; + } + else + ufd = &ufds[fd_idx]; + + if(ps.actions[i] & CURL_POLL_IN) + ufd->events |= CURL_WAIT_POLLIN; + if(ps.actions[i] & CURL_POLL_OUT) + ufd->events |= CURL_WAIT_POLLOUT; + } + else + return CURLM_OUT_OF_MEMORY; + } + } + + if(fd_count) + *fd_count = nfds; + return result; +} + +#ifdef USE_WINSOCK +/* Reset FD_WRITE for TCP sockets. Nothing is actually sent. UDP sockets can't + * be reset this way because an empty datagram would be sent. #9203 + * + * "On Windows the internal state of FD_WRITE as returned from + * WSAEnumNetworkEvents is only reset after successful send()." + */ +static void reset_socket_fdwrite(curl_socket_t s) +{ + int t; + int l = (int)sizeof(t); + if(!getsockopt(s, SOL_SOCKET, SO_TYPE, (char *)&t, &l) && t == SOCK_STREAM) + send(s, NULL, 0, 0); +} +#endif + +static CURLMcode ufds_increase(struct pollfd **pfds, unsigned int *pfds_len, + unsigned int inc, bool *is_malloced) +{ + struct pollfd *new_fds, *old_fds = *pfds; + unsigned int new_len = *pfds_len + inc; + + new_fds = calloc(new_len, sizeof(struct pollfd)); + if(!new_fds) { + if(*is_malloced) + free(old_fds); + *pfds = NULL; + *pfds_len = 0; + return CURLM_OUT_OF_MEMORY; + } + memcpy(new_fds, old_fds, (*pfds_len) * sizeof(struct pollfd)); + if(*is_malloced) + free(old_fds); + *pfds = new_fds; + *pfds_len = new_len; + *is_malloced = TRUE; + return CURLM_OK; +} + +#define NUM_POLLS_ON_STACK 10 + +static CURLMcode multi_wait(struct Curl_multi *multi, + struct curl_waitfd extra_fds[], + unsigned int extra_nfds, + int timeout_ms, + int *ret, + bool extrawait, /* when no socket, wait */ + bool use_wakeup) +{ + struct Curl_easy *data; + struct easy_pollset ps; + size_t i; + long timeout_internal; + int retcode = 0; + struct pollfd a_few_on_stack[NUM_POLLS_ON_STACK]; + struct pollfd *ufds = &a_few_on_stack[0]; + unsigned int ufds_len = NUM_POLLS_ON_STACK; + unsigned int nfds = 0, curl_nfds = 0; /* how many ufds are in use */ + bool ufds_malloc = FALSE; +#ifdef USE_WINSOCK + WSANETWORKEVENTS wsa_events; + DEBUGASSERT(multi->wsa_event != WSA_INVALID_EVENT); +#endif +#ifndef ENABLE_WAKEUP + (void)use_wakeup; +#endif + + if(!GOOD_MULTI_HANDLE(multi)) + return CURLM_BAD_HANDLE; + + if(multi->in_callback) + return CURLM_RECURSIVE_API_CALL; + + if(timeout_ms < 0) + return CURLM_BAD_FUNCTION_ARGUMENT; + + /* If the internally desired timeout is actually shorter than requested from + the outside, then use the shorter time! But only if the internal timer + is actually larger than -1! */ + (void)multi_timeout(multi, &timeout_internal); + if((timeout_internal >= 0) && (timeout_internal < (long)timeout_ms)) + timeout_ms = (int)timeout_internal; + + memset(ufds, 0, ufds_len * sizeof(struct pollfd)); + memset(&ps, 0, sizeof(ps)); + + /* Add the curl handles to our pollfds first */ + for(data = multi->easyp; data; data = data->next) { + multi_getsock(data, &ps); + + for(i = 0; i < ps.num; i++) { + short events = 0; +#ifdef USE_WINSOCK + long mask = 0; +#endif + if(ps.actions[i] & CURL_POLL_IN) { +#ifdef USE_WINSOCK + mask |= FD_READ|FD_ACCEPT|FD_CLOSE; +#endif + events |= POLLIN; + } + if(ps.actions[i] & CURL_POLL_OUT) { +#ifdef USE_WINSOCK + mask |= FD_WRITE|FD_CONNECT|FD_CLOSE; + reset_socket_fdwrite(ps.sockets[i]); +#endif + events |= POLLOUT; + } + if(events) { + if(nfds && ps.sockets[i] == ufds[nfds-1].fd) { + ufds[nfds-1].events |= events; + } + else { + if(nfds >= ufds_len) { + if(ufds_increase(&ufds, &ufds_len, 100, &ufds_malloc)) + return CURLM_OUT_OF_MEMORY; + } + DEBUGASSERT(nfds < ufds_len); + ufds[nfds].fd = ps.sockets[i]; + ufds[nfds].events = events; + ++nfds; + } + } +#ifdef USE_WINSOCK + if(mask) { + if(WSAEventSelect(ps.sockets[i], multi->wsa_event, mask) != 0) { + if(ufds_malloc) + free(ufds); + return CURLM_INTERNAL_ERROR; + } + } +#endif + } + } + + curl_nfds = nfds; /* what curl internally used in ufds */ + + /* Add external file descriptions from poll-like struct curl_waitfd */ + for(i = 0; i < extra_nfds; i++) { +#ifdef USE_WINSOCK + long mask = 0; + if(extra_fds[i].events & CURL_WAIT_POLLIN) + mask |= FD_READ|FD_ACCEPT|FD_CLOSE; + if(extra_fds[i].events & CURL_WAIT_POLLPRI) + mask |= FD_OOB; + if(extra_fds[i].events & CURL_WAIT_POLLOUT) { + mask |= FD_WRITE|FD_CONNECT|FD_CLOSE; + reset_socket_fdwrite(extra_fds[i].fd); + } + if(WSAEventSelect(extra_fds[i].fd, multi->wsa_event, mask) != 0) { + if(ufds_malloc) + free(ufds); + return CURLM_INTERNAL_ERROR; + } +#endif + if(nfds >= ufds_len) { + if(ufds_increase(&ufds, &ufds_len, 100, &ufds_malloc)) + return CURLM_OUT_OF_MEMORY; + } + DEBUGASSERT(nfds < ufds_len); + ufds[nfds].fd = extra_fds[i].fd; + ufds[nfds].events = 0; + if(extra_fds[i].events & CURL_WAIT_POLLIN) + ufds[nfds].events |= POLLIN; + if(extra_fds[i].events & CURL_WAIT_POLLPRI) + ufds[nfds].events |= POLLPRI; + if(extra_fds[i].events & CURL_WAIT_POLLOUT) + ufds[nfds].events |= POLLOUT; + ++nfds; + } + +#ifdef ENABLE_WAKEUP +#ifndef USE_WINSOCK + if(use_wakeup && multi->wakeup_pair[0] != CURL_SOCKET_BAD) { + if(nfds >= ufds_len) { + if(ufds_increase(&ufds, &ufds_len, 100, &ufds_malloc)) + return CURLM_OUT_OF_MEMORY; + } + DEBUGASSERT(nfds < ufds_len); + ufds[nfds].fd = multi->wakeup_pair[0]; + ufds[nfds].events = POLLIN; + ++nfds; + } +#endif +#endif + +#if defined(ENABLE_WAKEUP) && defined(USE_WINSOCK) + if(nfds || use_wakeup) { +#else + if(nfds) { +#endif + int pollrc; +#ifdef USE_WINSOCK + if(nfds) + pollrc = Curl_poll(ufds, nfds, 0); /* just pre-check with WinSock */ + else + pollrc = 0; +#else + pollrc = Curl_poll(ufds, nfds, timeout_ms); /* wait... */ +#endif + if(pollrc < 0) + return CURLM_UNRECOVERABLE_POLL; + + if(pollrc > 0) { + retcode = pollrc; +#ifdef USE_WINSOCK + } + else { /* now wait... if not ready during the pre-check (pollrc == 0) */ + WSAWaitForMultipleEvents(1, &multi->wsa_event, FALSE, timeout_ms, FALSE); + } + /* With WinSock, we have to run the following section unconditionally + to call WSAEventSelect(fd, event, 0) on all the sockets */ + { +#endif + /* copy revents results from the poll to the curl_multi_wait poll + struct, the bit values of the actual underlying poll() implementation + may not be the same as the ones in the public libcurl API! */ + for(i = 0; i < extra_nfds; i++) { + unsigned r = ufds[curl_nfds + i].revents; + unsigned short mask = 0; +#ifdef USE_WINSOCK + curl_socket_t s = extra_fds[i].fd; + wsa_events.lNetworkEvents = 0; + if(WSAEnumNetworkEvents(s, NULL, &wsa_events) == 0) { + if(wsa_events.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE)) + mask |= CURL_WAIT_POLLIN; + if(wsa_events.lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE)) + mask |= CURL_WAIT_POLLOUT; + if(wsa_events.lNetworkEvents & FD_OOB) + mask |= CURL_WAIT_POLLPRI; + if(ret && !pollrc && wsa_events.lNetworkEvents) + retcode++; + } + WSAEventSelect(s, multi->wsa_event, 0); + if(!pollrc) { + extra_fds[i].revents = mask; + continue; + } +#endif + if(r & POLLIN) + mask |= CURL_WAIT_POLLIN; + if(r & POLLOUT) + mask |= CURL_WAIT_POLLOUT; + if(r & POLLPRI) + mask |= CURL_WAIT_POLLPRI; + extra_fds[i].revents = mask; + } + +#ifdef USE_WINSOCK + /* Count up all our own sockets that had activity, + and remove them from the event. */ + if(curl_nfds) { + + for(data = multi->easyp; data; data = data->next) { + multi_getsock(data, &ps); + + for(i = 0; i < ps.num; i++) { + wsa_events.lNetworkEvents = 0; + if(WSAEnumNetworkEvents(ps.sockets[i], NULL, + &wsa_events) == 0) { + if(ret && !pollrc && wsa_events.lNetworkEvents) + retcode++; + } + WSAEventSelect(ps.sockets[i], multi->wsa_event, 0); + } + } + } + + WSAResetEvent(multi->wsa_event); +#else +#ifdef ENABLE_WAKEUP + if(use_wakeup && multi->wakeup_pair[0] != CURL_SOCKET_BAD) { + if(ufds[curl_nfds + extra_nfds].revents & POLLIN) { + char buf[64]; + ssize_t nread; + while(1) { + /* the reading socket is non-blocking, try to read + data from it until it receives an error (except EINTR). + In normal cases it will get EAGAIN or EWOULDBLOCK + when there is no more data, breaking the loop. */ + nread = wakeup_read(multi->wakeup_pair[0], buf, sizeof(buf)); + if(nread <= 0) { + if(nread < 0 && EINTR == SOCKERRNO) + continue; + break; + } + } + /* do not count the wakeup socket into the returned value */ + retcode--; + } + } +#endif +#endif + } + } + + if(ufds_malloc) + free(ufds); + if(ret) + *ret = retcode; +#if defined(ENABLE_WAKEUP) && defined(USE_WINSOCK) + if(extrawait && !nfds && !use_wakeup) { +#else + if(extrawait && !nfds) { +#endif + long sleep_ms = 0; + + /* Avoid busy-looping when there's nothing particular to wait for */ + if(!curl_multi_timeout(multi, &sleep_ms) && sleep_ms) { + if(sleep_ms > timeout_ms) + sleep_ms = timeout_ms; + /* when there are no easy handles in the multi, this holds a -1 + timeout */ + else if(sleep_ms < 0) + sleep_ms = timeout_ms; + Curl_wait_ms(sleep_ms); + } + } + + return CURLM_OK; +} + +CURLMcode curl_multi_wait(struct Curl_multi *multi, + struct curl_waitfd extra_fds[], + unsigned int extra_nfds, + int timeout_ms, + int *ret) +{ + return multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, FALSE, + FALSE); +} + +CURLMcode curl_multi_poll(struct Curl_multi *multi, + struct curl_waitfd extra_fds[], + unsigned int extra_nfds, + int timeout_ms, + int *ret) +{ + return multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, TRUE, + TRUE); +} + +CURLMcode curl_multi_wakeup(struct Curl_multi *multi) +{ + /* this function is usually called from another thread, + it has to be careful only to access parts of the + Curl_multi struct that are constant */ + + /* GOOD_MULTI_HANDLE can be safely called */ + if(!GOOD_MULTI_HANDLE(multi)) + return CURLM_BAD_HANDLE; + +#ifdef ENABLE_WAKEUP +#ifdef USE_WINSOCK + if(WSASetEvent(multi->wsa_event)) + return CURLM_OK; +#else + /* the wakeup_pair variable is only written during init and cleanup, + making it safe to access from another thread after the init part + and before cleanup */ + if(multi->wakeup_pair[1] != CURL_SOCKET_BAD) { + char buf[1]; + buf[0] = 1; + while(1) { + /* swrite() is not thread-safe in general, because concurrent calls + can have their messages interleaved, but in this case the content + of the messages does not matter, which makes it ok to call. + + The write socket is set to non-blocking, this way this function + cannot block, making it safe to call even from the same thread + that will call curl_multi_wait(). If swrite() returns that it + would block, it's considered successful because it means that + previous calls to this function will wake up the poll(). */ + if(wakeup_write(multi->wakeup_pair[1], buf, sizeof(buf)) < 0) { + int err = SOCKERRNO; + int return_success; +#ifdef USE_WINSOCK + return_success = WSAEWOULDBLOCK == err; +#else + if(EINTR == err) + continue; + return_success = EWOULDBLOCK == err || EAGAIN == err; +#endif + if(!return_success) + return CURLM_WAKEUP_FAILURE; + } + return CURLM_OK; + } + } +#endif +#endif + return CURLM_WAKEUP_FAILURE; +} + +/* + * multi_ischanged() is called + * + * Returns TRUE/FALSE whether the state is changed to trigger a CONNECT_PEND + * => CONNECT action. + * + * Set 'clear' to TRUE to have it also clear the state variable. + */ +static bool multi_ischanged(struct Curl_multi *multi, bool clear) +{ + bool retval = multi->recheckstate; + if(clear) + multi->recheckstate = FALSE; + return retval; +} + +/* + * Curl_multi_connchanged() is called to tell that there is a connection in + * this multi handle that has changed state (multiplexing become possible, the + * number of allowed streams changed or similar), and a subsequent use of this + * multi handle should move CONNECT_PEND handles back to CONNECT to have them + * retry. + */ +void Curl_multi_connchanged(struct Curl_multi *multi) +{ + multi->recheckstate = TRUE; +} + +CURLMcode Curl_multi_add_perform(struct Curl_multi *multi, + struct Curl_easy *data, + struct connectdata *conn) +{ + CURLMcode rc; + + if(multi->in_callback) + return CURLM_RECURSIVE_API_CALL; + + rc = curl_multi_add_handle(multi, data); + if(!rc) { + struct SingleRequest *k = &data->req; + + /* pass in NULL for 'conn' here since we don't want to init the + connection, only this transfer */ + Curl_init_do(data, NULL); + + /* take this handle to the perform state right away */ + multistate(data, MSTATE_PERFORMING); + Curl_attach_connection(data, conn); + k->keepon |= KEEP_RECV; /* setup to receive! */ + } + return rc; +} + +static CURLcode multi_do(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + DEBUGASSERT(conn); + DEBUGASSERT(conn->handler); + + if(conn->handler->do_it) + result = conn->handler->do_it(data, done); + + return result; +} + +/* + * multi_do_more() is called during the DO_MORE multi state. It is basically a + * second stage DO state which (wrongly) was introduced to support FTP's + * second connection. + * + * 'complete' can return 0 for incomplete, 1 for done and -1 for go back to + * DOING state there's more work to do! + */ + +static CURLcode multi_do_more(struct Curl_easy *data, int *complete) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + *complete = 0; + + if(conn->handler->do_more) + result = conn->handler->do_more(data, complete); + + return result; +} + +/* + * Check whether a timeout occurred, and handle it if it did + */ +static bool multi_handle_timeout(struct Curl_easy *data, + struct curltime *now, + bool *stream_error, + CURLcode *result, + bool connect_timeout) +{ + timediff_t timeout_ms = Curl_timeleft(data, now, connect_timeout); + if(timeout_ms < 0) { + /* Handle timed out */ + struct curltime since; + if(connect_timeout) + since = data->progress.t_startsingle; + else + since = data->progress.t_startop; + if(data->mstate == MSTATE_RESOLVING) + failf(data, "Resolving timed out after %" CURL_FORMAT_TIMEDIFF_T + " milliseconds", Curl_timediff(*now, since)); + else if(data->mstate == MSTATE_CONNECTING) + failf(data, "Connection timed out after %" CURL_FORMAT_TIMEDIFF_T + " milliseconds", Curl_timediff(*now, since)); + else { + struct SingleRequest *k = &data->req; + if(k->size != -1) { + failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T + " milliseconds with %" CURL_FORMAT_CURL_OFF_T " out of %" + CURL_FORMAT_CURL_OFF_T " bytes received", + Curl_timediff(*now, since), k->bytecount, k->size); + } + else { + failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T + " milliseconds with %" CURL_FORMAT_CURL_OFF_T + " bytes received", Curl_timediff(*now, since), k->bytecount); + } + } + *result = CURLE_OPERATION_TIMEDOUT; + if(data->conn) { + /* Force connection closed if the connection has indeed been used */ + if(data->mstate > MSTATE_DO) { + streamclose(data->conn, "Disconnect due to timeout"); + *stream_error = TRUE; + } + (void)multi_done(data, *result, TRUE); + } + return TRUE; + } + + return FALSE; +} + +/* + * We are doing protocol-specific connecting and this is being called over and + * over from the multi interface until the connection phase is done on + * protocol layer. + */ + +static CURLcode protocol_connecting(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + if(conn && conn->handler->connecting) { + *done = FALSE; + result = conn->handler->connecting(data, done); + } + else + *done = TRUE; + + return result; +} + +/* + * We are DOING this is being called over and over from the multi interface + * until the DOING phase is done on protocol layer. + */ + +static CURLcode protocol_doing(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + if(conn && conn->handler->doing) { + *done = FALSE; + result = conn->handler->doing(data, done); + } + else + *done = TRUE; + + return result; +} + +/* + * We have discovered that the TCP connection has been successful, we can now + * proceed with some action. + * + */ +static CURLcode protocol_connect(struct Curl_easy *data, + bool *protocol_done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + DEBUGASSERT(conn); + DEBUGASSERT(protocol_done); + + *protocol_done = FALSE; + + if(Curl_conn_is_connected(conn, FIRSTSOCKET) + && conn->bits.protoconnstart) { + /* We already are connected, get back. This may happen when the connect + worked fine in the first call, like when we connect to a local server + or proxy. Note that we don't know if the protocol is actually done. + + Unless this protocol doesn't have any protocol-connect callback, as + then we know we're done. */ + if(!conn->handler->connecting) + *protocol_done = TRUE; + + return CURLE_OK; + } + + if(!conn->bits.protoconnstart) { + if(conn->handler->connect_it) { + /* is there a protocol-specific connect() procedure? */ + + /* Call the protocol-specific connect function */ + result = conn->handler->connect_it(data, protocol_done); + } + else + *protocol_done = TRUE; + + /* it has started, possibly even completed but that knowledge isn't stored + in this bit! */ + if(!result) + conn->bits.protoconnstart = TRUE; + } + + return result; /* pass back status */ +} + +static void set_in_callback(struct Curl_multi *multi, bool value) +{ + multi->in_callback = value; +} + +static CURLMcode multi_runsingle(struct Curl_multi *multi, + struct curltime *nowp, + struct Curl_easy *data) +{ + struct Curl_message *msg = NULL; + bool connected; + bool async; + bool protocol_connected = FALSE; + bool dophase_done = FALSE; + CURLMcode rc; + CURLcode result = CURLE_OK; + timediff_t recv_timeout_ms; + timediff_t send_timeout_ms; + int control; + + if(!GOOD_EASY_HANDLE(data)) + return CURLM_BAD_EASY_HANDLE; + + if(multi->dead) { + /* a multi-level callback returned error before, meaning every individual + transfer now has failed */ + result = CURLE_ABORTED_BY_CALLBACK; + Curl_posttransfer(data); + multi_done(data, result, FALSE); + multistate(data, MSTATE_COMPLETED); + } + + multi_warn_debug(multi, data); + + do { + /* A "stream" here is a logical stream if the protocol can handle that + (HTTP/2), or the full connection for older protocols */ + bool stream_error = FALSE; + rc = CURLM_OK; + + if(multi_ischanged(multi, TRUE)) { + DEBUGF(infof(data, "multi changed, check CONNECT_PEND queue")); + process_pending_handles(multi); /* multiplexed */ + } + + if(data->mstate > MSTATE_CONNECT && + data->mstate < MSTATE_COMPLETED) { + /* Make sure we set the connection's current owner */ + DEBUGASSERT(data->conn); + if(!data->conn) + return CURLM_INTERNAL_ERROR; + } + + /* Wait for the connect state as only then is the start time stored, but + we must not check already completed handles */ + if((data->mstate >= MSTATE_CONNECT) && (data->mstate < MSTATE_COMPLETED) && + multi_handle_timeout(data, nowp, &stream_error, &result, FALSE)) + /* Skip the statemachine and go directly to error handling section. */ + goto statemachine_end; + + switch(data->mstate) { + case MSTATE_INIT: + /* Transitional state. init this transfer. A handle never comes + back to this state. */ + result = Curl_pretransfer(data); + if(result) + break; + + /* after init, go SETUP */ + multistate(data, MSTATE_SETUP); + (void)Curl_pgrsTime(data, TIMER_STARTOP); + FALLTHROUGH(); + + case MSTATE_SETUP: + /* Transitional state. Setup things for a new transfer. The handle + can come back to this state on a redirect. */ + *nowp = Curl_pgrsTime(data, TIMER_STARTSINGLE); + if(data->set.timeout) + Curl_expire(data, data->set.timeout, EXPIRE_TIMEOUT); + if(data->set.connecttimeout) + /* Since a connection might go to pending and back to CONNECT several + times before it actually takes off, we need to set the timeout once + in SETUP before we enter CONNECT the first time. */ + Curl_expire(data, data->set.connecttimeout, EXPIRE_CONNECTTIMEOUT); + + multistate(data, MSTATE_CONNECT); + FALLTHROUGH(); + + case MSTATE_CONNECT: + /* Connect. We want to get a connection identifier filled in. This state + can be entered from SETUP and from PENDING. */ + result = Curl_connect(data, &async, &connected); + if(CURLE_NO_CONNECTION_AVAILABLE == result) { + /* There was no connection available. We will go to the pending + state and wait for an available connection. */ + multistate(data, MSTATE_PENDING); + + /* add this handle to the list of connect-pending handles */ + Curl_llist_append(&multi->pending, data, &data->connect_queue); + /* unlink from the main list */ + unlink_easy(multi, data); + result = CURLE_OK; + break; + } + else + process_pending_handles(data->multi); + + if(!result) { + *nowp = Curl_pgrsTime(data, TIMER_POSTQUEUE); + if(async) + /* We're now waiting for an asynchronous name lookup */ + multistate(data, MSTATE_RESOLVING); + else { + /* after the connect has been sent off, go WAITCONNECT unless the + protocol connect is already done and we can go directly to + WAITDO or DO! */ + rc = CURLM_CALL_MULTI_PERFORM; + + if(connected) + multistate(data, MSTATE_PROTOCONNECT); + else { + multistate(data, MSTATE_CONNECTING); + } + } + } + break; + + case MSTATE_RESOLVING: + /* awaiting an asynch name resolve to complete */ + { + struct Curl_dns_entry *dns = NULL; + struct connectdata *conn = data->conn; + const char *hostname; + + DEBUGASSERT(conn); +#ifndef CURL_DISABLE_PROXY + if(conn->bits.httpproxy) + hostname = conn->http_proxy.host.name; + else +#endif + if(conn->bits.conn_to_host) + hostname = conn->conn_to_host.name; + else + hostname = conn->host.name; + + /* check if we have the name resolved by now */ + dns = Curl_fetch_addr(data, hostname, conn->primary.remote_port); + + if(dns) { +#ifdef CURLRES_ASYNCH + data->state.async.dns = dns; + data->state.async.done = TRUE; +#endif + result = CURLE_OK; + infof(data, "Hostname '%s' was found in DNS cache", hostname); + } + + if(!dns) + result = Curl_resolv_check(data, &dns); + + /* Update sockets here, because the socket(s) may have been + closed and the application thus needs to be told, even if it + is likely that the same socket(s) will again be used further + down. If the name has not yet been resolved, it is likely + that new sockets have been opened in an attempt to contact + another resolver. */ + rc = singlesocket(multi, data); + if(rc) + return rc; + + if(dns) { + /* Perform the next step in the connection phase, and then move on + to the WAITCONNECT state */ + result = Curl_once_resolved(data, &connected); + + if(result) + /* if Curl_once_resolved() returns failure, the connection struct + is already freed and gone */ + data->conn = NULL; /* no more connection */ + else { + /* call again please so that we get the next socket setup */ + rc = CURLM_CALL_MULTI_PERFORM; + if(connected) + multistate(data, MSTATE_PROTOCONNECT); + else { + multistate(data, MSTATE_CONNECTING); + } + } + } + + if(result) { + /* failure detected */ + stream_error = TRUE; + break; + } + } + break; + +#ifndef CURL_DISABLE_HTTP + case MSTATE_TUNNELING: + /* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */ + DEBUGASSERT(data->conn); + result = Curl_http_connect(data, &protocol_connected); +#ifndef CURL_DISABLE_PROXY + if(data->conn->bits.proxy_connect_closed) { + rc = CURLM_CALL_MULTI_PERFORM; + /* connect back to proxy again */ + result = CURLE_OK; + multi_done(data, CURLE_OK, FALSE); + multistate(data, MSTATE_CONNECT); + } + else +#endif + if(!result) { + rc = CURLM_CALL_MULTI_PERFORM; + /* initiate protocol connect phase */ + multistate(data, MSTATE_PROTOCONNECT); + } + else + stream_error = TRUE; + break; +#endif + + case MSTATE_CONNECTING: + /* awaiting a completion of an asynch TCP connect */ + DEBUGASSERT(data->conn); + result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &connected); + if(connected && !result) { + rc = CURLM_CALL_MULTI_PERFORM; + multistate(data, MSTATE_PROTOCONNECT); + } + else if(result) { + /* failure detected */ + Curl_posttransfer(data); + multi_done(data, result, TRUE); + stream_error = TRUE; + break; + } + break; + + case MSTATE_PROTOCONNECT: + if(!result && data->conn->bits.reuse) { + /* ftp seems to hang when protoconnect on reused connection + * since we handle PROTOCONNECT in general inside the filers, it + * seems wrong to restart this on a reused connection. */ + multistate(data, MSTATE_DO); + rc = CURLM_CALL_MULTI_PERFORM; + break; + } + if(!result) + result = protocol_connect(data, &protocol_connected); + if(!result && !protocol_connected) { + /* switch to waiting state */ + multistate(data, MSTATE_PROTOCONNECTING); + rc = CURLM_CALL_MULTI_PERFORM; + } + else if(!result) { + /* protocol connect has completed, go WAITDO or DO */ + multistate(data, MSTATE_DO); + rc = CURLM_CALL_MULTI_PERFORM; + } + else { + /* failure detected */ + Curl_posttransfer(data); + multi_done(data, result, TRUE); + stream_error = TRUE; + } + break; + + case MSTATE_PROTOCONNECTING: + /* protocol-specific connect phase */ + result = protocol_connecting(data, &protocol_connected); + if(!result && protocol_connected) { + /* after the connect has completed, go WAITDO or DO */ + multistate(data, MSTATE_DO); + rc = CURLM_CALL_MULTI_PERFORM; + } + else if(result) { + /* failure detected */ + Curl_posttransfer(data); + multi_done(data, result, TRUE); + stream_error = TRUE; + } + break; + + case MSTATE_DO: + if(data->set.fprereq) { + int prereq_rc; + + /* call the prerequest callback function */ + Curl_set_in_callback(data, true); + prereq_rc = data->set.fprereq(data->set.prereq_userp, + data->info.primary.remote_ip, + data->info.primary.local_ip, + data->info.primary.remote_port, + data->info.primary.local_port); + Curl_set_in_callback(data, false); + if(prereq_rc != CURL_PREREQFUNC_OK) { + failf(data, "operation aborted by pre-request callback"); + /* failure in pre-request callback - don't do any other processing */ + result = CURLE_ABORTED_BY_CALLBACK; + Curl_posttransfer(data); + multi_done(data, result, FALSE); + stream_error = TRUE; + break; + } + } + + if(data->set.connect_only == 1) { + /* keep connection open for application to use the socket */ + connkeep(data->conn, "CONNECT_ONLY"); + multistate(data, MSTATE_DONE); + result = CURLE_OK; + rc = CURLM_CALL_MULTI_PERFORM; + } + else { + /* Perform the protocol's DO action */ + result = multi_do(data, &dophase_done); + + /* When multi_do() returns failure, data->conn might be NULL! */ + + if(!result) { + if(!dophase_done) { +#ifndef CURL_DISABLE_FTP + /* some steps needed for wildcard matching */ + if(data->state.wildcardmatch) { + struct WildcardData *wc = data->wildcard; + if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) { + /* skip some states if it is important */ + multi_done(data, CURLE_OK, FALSE); + + /* if there's no connection left, skip the DONE state */ + multistate(data, data->conn ? + MSTATE_DONE : MSTATE_COMPLETED); + rc = CURLM_CALL_MULTI_PERFORM; + break; + } + } +#endif + /* DO was not completed in one function call, we must continue + DOING... */ + multistate(data, MSTATE_DOING); + rc = CURLM_CALL_MULTI_PERFORM; + } + + /* after DO, go DO_DONE... or DO_MORE */ + else if(data->conn->bits.do_more) { + /* we're supposed to do more, but we need to sit down, relax + and wait a little while first */ + multistate(data, MSTATE_DOING_MORE); + rc = CURLM_CALL_MULTI_PERFORM; + } + else { + /* we're done with the DO, now DID */ + multistate(data, MSTATE_DID); + rc = CURLM_CALL_MULTI_PERFORM; + } + } + else if((CURLE_SEND_ERROR == result) && + data->conn->bits.reuse) { + /* + * In this situation, a connection that we were trying to use + * may have unexpectedly died. If possible, send the connection + * back to the CONNECT phase so we can try again. + */ + char *newurl = NULL; + followtype follow = FOLLOW_NONE; + CURLcode drc; + + drc = Curl_retry_request(data, &newurl); + if(drc) { + /* a failure here pretty much implies an out of memory */ + result = drc; + stream_error = TRUE; + } + + Curl_posttransfer(data); + drc = multi_done(data, result, FALSE); + + /* When set to retry the connection, we must go back to the CONNECT + * state */ + if(newurl) { + if(!drc || (drc == CURLE_SEND_ERROR)) { + follow = FOLLOW_RETRY; + drc = Curl_follow(data, newurl, follow); + if(!drc) { + multistate(data, MSTATE_SETUP); + rc = CURLM_CALL_MULTI_PERFORM; + result = CURLE_OK; + } + else { + /* Follow failed */ + result = drc; + } + } + else { + /* done didn't return OK or SEND_ERROR */ + result = drc; + } + } + else { + /* Have error handler disconnect conn if we can't retry */ + stream_error = TRUE; + } + free(newurl); + } + else { + /* failure detected */ + Curl_posttransfer(data); + if(data->conn) + multi_done(data, result, FALSE); + stream_error = TRUE; + } + } + break; + + case MSTATE_DOING: + /* we continue DOING until the DO phase is complete */ + DEBUGASSERT(data->conn); + result = protocol_doing(data, &dophase_done); + if(!result) { + if(dophase_done) { + /* after DO, go DO_DONE or DO_MORE */ + multistate(data, data->conn->bits.do_more? + MSTATE_DOING_MORE : MSTATE_DID); + rc = CURLM_CALL_MULTI_PERFORM; + } /* dophase_done */ + } + else { + /* failure detected */ + Curl_posttransfer(data); + multi_done(data, result, FALSE); + stream_error = TRUE; + } + break; + + case MSTATE_DOING_MORE: + /* + * When we are connected, DOING MORE and then go DID + */ + DEBUGASSERT(data->conn); + result = multi_do_more(data, &control); + + if(!result) { + if(control) { + /* if positive, advance to DO_DONE + if negative, go back to DOING */ + multistate(data, control == 1? + MSTATE_DID : MSTATE_DOING); + rc = CURLM_CALL_MULTI_PERFORM; + } + /* else + stay in DO_MORE */ + } + else { + /* failure detected */ + Curl_posttransfer(data); + multi_done(data, result, FALSE); + stream_error = TRUE; + } + break; + + case MSTATE_DID: + DEBUGASSERT(data->conn); + if(data->conn->bits.multiplex) + /* Check if we can move pending requests to send pipe */ + process_pending_handles(multi); /* multiplexed */ + + /* Only perform the transfer if there's a good socket to work with. + Having both BAD is a signal to skip immediately to DONE */ + if((data->conn->sockfd != CURL_SOCKET_BAD) || + (data->conn->writesockfd != CURL_SOCKET_BAD)) + multistate(data, MSTATE_PERFORMING); + else { +#ifndef CURL_DISABLE_FTP + if(data->state.wildcardmatch && + ((data->conn->handler->flags & PROTOPT_WILDCARD) == 0)) { + data->wildcard->state = CURLWC_DONE; + } +#endif + multistate(data, MSTATE_DONE); + } + rc = CURLM_CALL_MULTI_PERFORM; + break; + + case MSTATE_RATELIMITING: /* limit-rate exceeded in either direction */ + DEBUGASSERT(data->conn); + /* if both rates are within spec, resume transfer */ + if(Curl_pgrsUpdate(data)) + result = CURLE_ABORTED_BY_CALLBACK; + else + result = Curl_speedcheck(data, *nowp); + + if(result) { + if(!(data->conn->handler->flags & PROTOPT_DUAL) && + result != CURLE_HTTP2_STREAM) + streamclose(data->conn, "Transfer returned error"); + + Curl_posttransfer(data); + multi_done(data, result, TRUE); + } + else { + send_timeout_ms = 0; + if(data->set.max_send_speed) + send_timeout_ms = + Curl_pgrsLimitWaitTime(data->progress.uploaded, + data->progress.ul_limit_size, + data->set.max_send_speed, + data->progress.ul_limit_start, + *nowp); + + recv_timeout_ms = 0; + if(data->set.max_recv_speed) + recv_timeout_ms = + Curl_pgrsLimitWaitTime(data->progress.downloaded, + data->progress.dl_limit_size, + data->set.max_recv_speed, + data->progress.dl_limit_start, + *nowp); + + if(!send_timeout_ms && !recv_timeout_ms) { + multistate(data, MSTATE_PERFORMING); + Curl_ratelimit(data, *nowp); + } + else if(send_timeout_ms >= recv_timeout_ms) + Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST); + else + Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST); + } + break; + + case MSTATE_PERFORMING: + { + char *newurl = NULL; + bool retry = FALSE; + /* check if over send speed */ + send_timeout_ms = 0; + if(data->set.max_send_speed) + send_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.uploaded, + data->progress.ul_limit_size, + data->set.max_send_speed, + data->progress.ul_limit_start, + *nowp); + + /* check if over recv speed */ + recv_timeout_ms = 0; + if(data->set.max_recv_speed) + recv_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.downloaded, + data->progress.dl_limit_size, + data->set.max_recv_speed, + data->progress.dl_limit_start, + *nowp); + + if(send_timeout_ms || recv_timeout_ms) { + Curl_ratelimit(data, *nowp); + multistate(data, MSTATE_RATELIMITING); + if(send_timeout_ms >= recv_timeout_ms) + Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST); + else + Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST); + break; + } + + /* read/write data if it is ready to do so */ + result = Curl_readwrite(data); + + if(data->req.done || (result == CURLE_RECV_ERROR)) { + /* If CURLE_RECV_ERROR happens early enough, we assume it was a race + * condition and the server closed the reused connection exactly when + * we wanted to use it, so figure out if that is indeed the case. + */ + CURLcode ret = Curl_retry_request(data, &newurl); + if(!ret) + retry = (newurl)?TRUE:FALSE; + else if(!result) + result = ret; + + if(retry) { + /* if we are to retry, set the result to OK and consider the + request as done */ + result = CURLE_OK; + data->req.done = TRUE; + } + } + else if((CURLE_HTTP2_STREAM == result) && + Curl_h2_http_1_1_error(data)) { + CURLcode ret = Curl_retry_request(data, &newurl); + + if(!ret) { + infof(data, "Downgrades to HTTP/1.1"); + streamclose(data->conn, "Disconnect HTTP/2 for HTTP/1"); + data->state.httpwant = CURL_HTTP_VERSION_1_1; + /* clear the error message bit too as we ignore the one we got */ + data->state.errorbuf = FALSE; + if(!newurl) + /* typically for HTTP_1_1_REQUIRED error on first flight */ + newurl = strdup(data->state.url); + /* if we are to retry, set the result to OK and consider the request + as done */ + retry = TRUE; + result = CURLE_OK; + data->req.done = TRUE; + } + else + result = ret; + } + + if(result) { + /* + * The transfer phase returned error, we mark the connection to get + * closed to prevent being reused. This is because we can't possibly + * know if the connection is in a good shape or not now. Unless it is + * a protocol which uses two "channels" like FTP, as then the error + * happened in the data connection. + */ + + if(!(data->conn->handler->flags & PROTOPT_DUAL) && + result != CURLE_HTTP2_STREAM) + streamclose(data->conn, "Transfer returned error"); + + Curl_posttransfer(data); + multi_done(data, result, TRUE); + } + else if(data->req.done && !Curl_cwriter_is_paused(data)) { + + /* call this even if the readwrite function returned error */ + Curl_posttransfer(data); + + /* When we follow redirects or is set to retry the connection, we must + to go back to the CONNECT state */ + if(data->req.newurl || retry) { + followtype follow = FOLLOW_NONE; + if(!retry) { + /* if the URL is a follow-location and not just a retried request + then figure out the URL here */ + free(newurl); + newurl = data->req.newurl; + data->req.newurl = NULL; + follow = FOLLOW_REDIR; + } + else + follow = FOLLOW_RETRY; + (void)multi_done(data, CURLE_OK, FALSE); + /* multi_done() might return CURLE_GOT_NOTHING */ + result = Curl_follow(data, newurl, follow); + if(!result) { + multistate(data, MSTATE_SETUP); + rc = CURLM_CALL_MULTI_PERFORM; + } + } + else { + /* after the transfer is done, go DONE */ + + /* but first check to see if we got a location info even though we're + not following redirects */ + if(data->req.location) { + free(newurl); + newurl = data->req.location; + data->req.location = NULL; + result = Curl_follow(data, newurl, FOLLOW_FAKE); + if(result) { + stream_error = TRUE; + result = multi_done(data, result, TRUE); + } + } + + if(!result) { + multistate(data, MSTATE_DONE); + rc = CURLM_CALL_MULTI_PERFORM; + } + } + } + else if(data->state.select_bits) { + /* This avoids CURLM_CALL_MULTI_PERFORM so that a very fast transfer + won't get stuck on this transfer at the expense of other concurrent + transfers */ + Curl_expire(data, 0, EXPIRE_RUN_NOW); + } + free(newurl); + break; + } + + case MSTATE_DONE: + /* this state is highly transient, so run another loop after this */ + rc = CURLM_CALL_MULTI_PERFORM; + + if(data->conn) { + CURLcode res; + + if(data->conn->bits.multiplex) + /* Check if we can move pending requests to connection */ + process_pending_handles(multi); /* multiplexing */ + + /* post-transfer command */ + res = multi_done(data, result, FALSE); + + /* allow a previously set error code take precedence */ + if(!result) + result = res; + } + +#ifndef CURL_DISABLE_FTP + if(data->state.wildcardmatch) { + if(data->wildcard->state != CURLWC_DONE) { + /* if a wildcard is set and we are not ending -> lets start again + with MSTATE_INIT */ + multistate(data, MSTATE_INIT); + break; + } + } +#endif + /* after we have DONE what we're supposed to do, go COMPLETED, and + it doesn't matter what the multi_done() returned! */ + multistate(data, MSTATE_COMPLETED); + break; + + case MSTATE_COMPLETED: + break; + + case MSTATE_PENDING: + case MSTATE_MSGSENT: + /* handles in these states should NOT be in this list */ + DEBUGASSERT(0); + break; + + default: + return CURLM_INTERNAL_ERROR; + } + + if(data->mstate >= MSTATE_CONNECT && + data->mstate < MSTATE_DO && + rc != CURLM_CALL_MULTI_PERFORM && + !multi_ischanged(multi, false)) { + /* We now handle stream timeouts if and only if this will be the last + * loop iteration. We only check this on the last iteration to ensure + * that if we know we have additional work to do immediately + * (i.e. CURLM_CALL_MULTI_PERFORM == TRUE) then we should do that before + * declaring the connection timed out as we may almost have a completed + * connection. */ + multi_handle_timeout(data, nowp, &stream_error, &result, FALSE); + } + +statemachine_end: + + if(data->mstate < MSTATE_COMPLETED) { + if(result) { + /* + * If an error was returned, and we aren't in completed state now, + * then we go to completed and consider this transfer aborted. + */ + + /* NOTE: no attempt to disconnect connections must be made + in the case blocks above - cleanup happens only here */ + + /* Check if we can move pending requests to send pipe */ + process_pending_handles(multi); /* connection */ + + if(data->conn) { + if(stream_error) { + /* Don't attempt to send data over a connection that timed out */ + bool dead_connection = result == CURLE_OPERATION_TIMEDOUT; + struct connectdata *conn = data->conn; + + /* This is where we make sure that the conn pointer is reset. + We don't have to do this in every case block above where a + failure is detected */ + Curl_detach_connection(data); + + /* remove connection from cache */ + Curl_conncache_remove_conn(data, conn, TRUE); + + /* disconnect properly */ + Curl_disconnect(data, conn, dead_connection); + } + } + else if(data->mstate == MSTATE_CONNECT) { + /* Curl_connect() failed */ + (void)Curl_posttransfer(data); + } + + multistate(data, MSTATE_COMPLETED); + rc = CURLM_CALL_MULTI_PERFORM; + } + /* if there's still a connection to use, call the progress function */ + else if(data->conn && Curl_pgrsUpdate(data)) { + /* aborted due to progress callback return code must close the + connection */ + result = CURLE_ABORTED_BY_CALLBACK; + streamclose(data->conn, "Aborted by callback"); + + /* if not yet in DONE state, go there, otherwise COMPLETED */ + multistate(data, (data->mstate < MSTATE_DONE)? + MSTATE_DONE: MSTATE_COMPLETED); + rc = CURLM_CALL_MULTI_PERFORM; + } + } + + if(MSTATE_COMPLETED == data->mstate) { + if(data->set.fmultidone) { + /* signal via callback instead */ + data->set.fmultidone(data, result); + } + else { + /* now fill in the Curl_message with this info */ + msg = &data->msg; + + msg->extmsg.msg = CURLMSG_DONE; + msg->extmsg.easy_handle = data; + msg->extmsg.data.result = result; + + multi_addmsg(multi, msg); + DEBUGASSERT(!data->conn); + } + multistate(data, MSTATE_MSGSENT); + + /* add this handle to the list of msgsent handles */ + Curl_llist_append(&multi->msgsent, data, &data->connect_queue); + /* unlink from the main list */ + unlink_easy(multi, data); + return CURLM_OK; + } + } while((rc == CURLM_CALL_MULTI_PERFORM) || multi_ischanged(multi, FALSE)); + + data->result = result; + return rc; +} + + +CURLMcode curl_multi_perform(struct Curl_multi *multi, int *running_handles) +{ + struct Curl_easy *data; + CURLMcode returncode = CURLM_OK; + struct Curl_tree *t; + struct curltime now = Curl_now(); + + if(!GOOD_MULTI_HANDLE(multi)) + return CURLM_BAD_HANDLE; + + if(multi->in_callback) + return CURLM_RECURSIVE_API_CALL; + + data = multi->easyp; + if(data) { + CURLMcode result; + bool nosig = data->set.no_signal; + SIGPIPE_VARIABLE(pipe_st); + sigpipe_ignore(data, &pipe_st); + /* Do the loop and only alter the signal ignore state if the next handle + has a different NO_SIGNAL state than the previous */ + do { + /* the current node might be unlinked in multi_runsingle(), get the next + pointer now */ + struct Curl_easy *datanext = data->next; + if(data->set.no_signal != nosig) { + sigpipe_restore(&pipe_st); + sigpipe_ignore(data, &pipe_st); + nosig = data->set.no_signal; + } + result = multi_runsingle(multi, &now, data); + if(result) + returncode = result; + data = datanext; /* operate on next handle */ + } while(data); + sigpipe_restore(&pipe_st); + } + + /* + * Simply remove all expired timers from the splay since handles are dealt + * with unconditionally by this function and curl_multi_timeout() requires + * that already passed/handled expire times are removed from the splay. + * + * It is important that the 'now' value is set at the entry of this function + * and not for the current time as it may have ticked a little while since + * then and then we risk this loop to remove timers that actually have not + * been handled! + */ + do { + multi->timetree = Curl_splaygetbest(now, multi->timetree, &t); + if(t) { + /* the removed may have another timeout in queue */ + data = t->payload; + if(data->mstate == MSTATE_PENDING) { + bool stream_unused; + CURLcode result_unused; + if(multi_handle_timeout(data, &now, &stream_unused, &result_unused, + FALSE)) { + infof(data, "PENDING handle timeout"); + move_pending_to_connect(multi, data); + } + } + (void)add_next_timeout(now, multi, t->payload); + } + } while(t); + + *running_handles = multi->num_alive; + + if(CURLM_OK >= returncode) + returncode = Curl_update_timer(multi); + + return returncode; +} + +/* unlink_all_msgsent_handles() detaches all those easy handles from this + multi handle */ +static void unlink_all_msgsent_handles(struct Curl_multi *multi) +{ + struct Curl_llist_element *e = multi->msgsent.head; + if(e) { + struct Curl_easy *data = e->ptr; + DEBUGASSERT(data->mstate == MSTATE_MSGSENT); + data->multi = NULL; + } +} + +CURLMcode curl_multi_cleanup(struct Curl_multi *multi) +{ + struct Curl_easy *data; + struct Curl_easy *nextdata; + + if(GOOD_MULTI_HANDLE(multi)) { + if(multi->in_callback) + return CURLM_RECURSIVE_API_CALL; + + multi->magic = 0; /* not good anymore */ + + unlink_all_msgsent_handles(multi); + process_pending_handles(multi); + /* First remove all remaining easy handles */ + data = multi->easyp; + while(data) { + nextdata = data->next; + if(!data->state.done && data->conn) + /* if DONE was never called for this handle */ + (void)multi_done(data, CURLE_OK, TRUE); + if(data->dns.hostcachetype == HCACHE_MULTI) { + /* clear out the usage of the shared DNS cache */ + Curl_hostcache_clean(data, data->dns.hostcache); + data->dns.hostcache = NULL; + data->dns.hostcachetype = HCACHE_NONE; + } + + /* Clear the pointer to the connection cache */ + data->state.conn_cache = NULL; + data->multi = NULL; /* clear the association */ + +#ifdef USE_LIBPSL + if(data->psl == &multi->psl) + data->psl = NULL; +#endif + + data = nextdata; + } + + /* Close all the connections in the connection cache */ + Curl_conncache_close_all_connections(&multi->conn_cache); + + sockhash_destroy(&multi->sockhash); + Curl_conncache_destroy(&multi->conn_cache); + Curl_hash_destroy(&multi->hostcache); + Curl_psl_destroy(&multi->psl); + +#ifdef USE_WINSOCK + WSACloseEvent(multi->wsa_event); +#else +#ifdef ENABLE_WAKEUP + wakeup_close(multi->wakeup_pair[0]); + wakeup_close(multi->wakeup_pair[1]); +#endif +#endif + +#ifdef USE_SSL + Curl_free_multi_ssl_backend_data(multi->ssl_backend_data); +#endif + + multi_xfer_bufs_free(multi); + free(multi); + + return CURLM_OK; + } + return CURLM_BAD_HANDLE; +} + +/* + * curl_multi_info_read() + * + * This function is the primary way for a multi/multi_socket application to + * figure out if a transfer has ended. We MUST make this function as fast as + * possible as it will be polled frequently and we MUST NOT scan any lists in + * here to figure out things. We must scale fine to thousands of handles and + * beyond. The current design is fully O(1). + */ + +CURLMsg *curl_multi_info_read(struct Curl_multi *multi, int *msgs_in_queue) +{ + struct Curl_message *msg; + + *msgs_in_queue = 0; /* default to none */ + + if(GOOD_MULTI_HANDLE(multi) && + !multi->in_callback && + Curl_llist_count(&multi->msglist)) { + /* there is one or more messages in the list */ + struct Curl_llist_element *e; + + /* extract the head of the list to return */ + e = multi->msglist.head; + + msg = e->ptr; + + /* remove the extracted entry */ + Curl_llist_remove(&multi->msglist, e, NULL); + + *msgs_in_queue = curlx_uztosi(Curl_llist_count(&multi->msglist)); + + return &msg->extmsg; + } + return NULL; +} + +/* + * singlesocket() checks what sockets we deal with and their "action state" + * and if we have a different state in any of those sockets from last time we + * call the callback accordingly. + */ +static CURLMcode singlesocket(struct Curl_multi *multi, + struct Curl_easy *data) +{ + struct easy_pollset cur_poll; + unsigned int i; + struct Curl_sh_entry *entry; + curl_socket_t s; + int rc; + + /* Fill in the 'current' struct with the state as it is now: what sockets to + supervise and for what actions */ + multi_getsock(data, &cur_poll); + + /* We have 0 .. N sockets already and we get to know about the 0 .. M + sockets we should have from now on. Detect the differences, remove no + longer supervised ones and add new ones */ + + /* walk over the sockets we got right now */ + for(i = 0; i < cur_poll.num; i++) { + unsigned char cur_action = cur_poll.actions[i]; + unsigned char last_action = 0; + int comboaction; + + s = cur_poll.sockets[i]; + + /* get it from the hash */ + entry = sh_getentry(&multi->sockhash, s); + if(entry) { + /* check if new for this transfer */ + unsigned int j; + for(j = 0; j< data->last_poll.num; j++) { + if(s == data->last_poll.sockets[j]) { + last_action = data->last_poll.actions[j]; + break; + } + } + } + else { + /* this is a socket we didn't have before, add it to the hash! */ + entry = sh_addentry(&multi->sockhash, s); + if(!entry) + /* fatal */ + return CURLM_OUT_OF_MEMORY; + } + if(last_action && (last_action != cur_action)) { + /* Socket was used already, but different action now */ + if(last_action & CURL_POLL_IN) + entry->readers--; + if(last_action & CURL_POLL_OUT) + entry->writers--; + if(cur_action & CURL_POLL_IN) + entry->readers++; + if(cur_action & CURL_POLL_OUT) + entry->writers++; + } + else if(!last_action) { + /* a new transfer using this socket */ + entry->users++; + if(cur_action & CURL_POLL_IN) + entry->readers++; + if(cur_action & CURL_POLL_OUT) + entry->writers++; + + /* add 'data' to the transfer hash on this socket! */ + if(!Curl_hash_add(&entry->transfers, (char *)&data, /* hash key */ + sizeof(struct Curl_easy *), data)) { + Curl_hash_destroy(&entry->transfers); + return CURLM_OUT_OF_MEMORY; + } + } + + comboaction = (entry->writers ? CURL_POLL_OUT : 0) | + (entry->readers ? CURL_POLL_IN : 0); + + /* socket existed before and has the same action set as before */ + if(last_action && ((int)entry->action == comboaction)) + /* same, continue */ + continue; + + if(multi->socket_cb) { + set_in_callback(multi, TRUE); + rc = multi->socket_cb(data, s, comboaction, multi->socket_userp, + entry->socketp); + + set_in_callback(multi, FALSE); + if(rc == -1) { + multi->dead = TRUE; + return CURLM_ABORTED_BY_CALLBACK; + } + } + + entry->action = comboaction; /* store the current action state */ + } + + /* Check for last_poll.sockets that no longer appear in cur_poll.sockets. + * Need to remove the easy handle from the multi->sockhash->transfers and + * remove multi->sockhash entry when this was the last transfer */ + for(i = 0; i< data->last_poll.num; i++) { + unsigned int j; + bool stillused = FALSE; + s = data->last_poll.sockets[i]; + for(j = 0; j < cur_poll.num; j++) { + if(s == cur_poll.sockets[j]) { + /* this is still supervised */ + stillused = TRUE; + break; + } + } + if(stillused) + continue; + + entry = sh_getentry(&multi->sockhash, s); + /* if this is NULL here, the socket has been closed and notified so + already by Curl_multi_closed() */ + if(entry) { + unsigned char oldactions = data->last_poll.actions[i]; + /* this socket has been removed. Decrease user count */ + entry->users--; + if(oldactions & CURL_POLL_OUT) + entry->writers--; + if(oldactions & CURL_POLL_IN) + entry->readers--; + if(!entry->users) { + if(multi->socket_cb) { + set_in_callback(multi, TRUE); + rc = multi->socket_cb(data, s, CURL_POLL_REMOVE, + multi->socket_userp, entry->socketp); + set_in_callback(multi, FALSE); + if(rc == -1) { + multi->dead = TRUE; + return CURLM_ABORTED_BY_CALLBACK; + } + } + sh_delentry(entry, &multi->sockhash, s); + } + else { + /* still users, but remove this handle as a user of this socket */ + if(Curl_hash_delete(&entry->transfers, (char *)&data, + sizeof(struct Curl_easy *))) { + DEBUGASSERT(NULL); + } + } + } + } /* for loop over num */ + + /* Remember for next time */ + memcpy(&data->last_poll, &cur_poll, sizeof(data->last_poll)); + return CURLM_OK; +} + +CURLcode Curl_updatesocket(struct Curl_easy *data) +{ + if(singlesocket(data->multi, data)) + return CURLE_ABORTED_BY_CALLBACK; + return CURLE_OK; +} + + +/* + * Curl_multi_closed() + * + * Used by the connect code to tell the multi_socket code that one of the + * sockets we were using is about to be closed. This function will then + * remove it from the sockethash for this handle to make the multi_socket API + * behave properly, especially for the case when libcurl will create another + * socket again and it gets the same file descriptor number. + */ + +void Curl_multi_closed(struct Curl_easy *data, curl_socket_t s) +{ + if(data) { + /* if there's still an easy handle associated with this connection */ + struct Curl_multi *multi = data->multi; + if(multi) { + /* this is set if this connection is part of a handle that is added to + a multi handle, and only then this is necessary */ + struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); + + if(entry) { + int rc = 0; + if(multi->socket_cb) { + set_in_callback(multi, TRUE); + rc = multi->socket_cb(data, s, CURL_POLL_REMOVE, + multi->socket_userp, entry->socketp); + set_in_callback(multi, FALSE); + } + + /* now remove it from the socket hash */ + sh_delentry(entry, &multi->sockhash, s); + if(rc == -1) + /* This just marks the multi handle as "dead" without returning an + error code primarily because this function is used from many + places where propagating an error back is tricky. */ + multi->dead = TRUE; + } + } + } +} + +/* + * add_next_timeout() + * + * Each Curl_easy has a list of timeouts. The add_next_timeout() is called + * when it has just been removed from the splay tree because the timeout has + * expired. This function is then to advance in the list to pick the next + * timeout to use (skip the already expired ones) and add this node back to + * the splay tree again. + * + * The splay tree only has each sessionhandle as a single node and the nearest + * timeout is used to sort it on. + */ +static CURLMcode add_next_timeout(struct curltime now, + struct Curl_multi *multi, + struct Curl_easy *d) +{ + struct curltime *tv = &d->state.expiretime; + struct Curl_llist *list = &d->state.timeoutlist; + struct Curl_llist_element *e; + struct time_node *node = NULL; + + /* move over the timeout list for this specific handle and remove all + timeouts that are now passed tense and store the next pending + timeout in *tv */ + for(e = list->head; e;) { + struct Curl_llist_element *n = e->next; + timediff_t diff; + node = (struct time_node *)e->ptr; + diff = Curl_timediff_us(node->time, now); + if(diff <= 0) + /* remove outdated entry */ + Curl_llist_remove(list, e, NULL); + else + /* the list is sorted so get out on the first mismatch */ + break; + e = n; + } + e = list->head; + if(!e) { + /* clear the expire times within the handles that we remove from the + splay tree */ + tv->tv_sec = 0; + tv->tv_usec = 0; + } + else { + /* copy the first entry to 'tv' */ + memcpy(tv, &node->time, sizeof(*tv)); + + /* Insert this node again into the splay. Keep the timer in the list in + case we need to recompute future timers. */ + multi->timetree = Curl_splayinsert(*tv, multi->timetree, + &d->state.timenode); + } + return CURLM_OK; +} + +static CURLMcode multi_socket(struct Curl_multi *multi, + bool checkall, + curl_socket_t s, + int ev_bitmask, + int *running_handles) +{ + CURLMcode result = CURLM_OK; + struct Curl_easy *data = NULL; + struct Curl_tree *t; + struct curltime now = Curl_now(); + bool first = FALSE; + bool nosig = FALSE; + SIGPIPE_VARIABLE(pipe_st); + + if(checkall) { + /* *perform() deals with running_handles on its own */ + result = curl_multi_perform(multi, running_handles); + + /* walk through each easy handle and do the socket state change magic + and callbacks */ + if(result != CURLM_BAD_HANDLE) { + data = multi->easyp; + while(data && !result) { + result = singlesocket(multi, data); + data = data->next; + } + } + + /* or should we fall-through and do the timer-based stuff? */ + return result; + } + if(s != CURL_SOCKET_TIMEOUT) { + struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); + + if(!entry) + /* Unmatched socket, we can't act on it but we ignore this fact. In + real-world tests it has been proved that libevent can in fact give + the application actions even though the socket was just previously + asked to get removed, so thus we better survive stray socket actions + and just move on. */ + ; + else { + struct Curl_hash_iterator iter; + struct Curl_hash_element *he; + + /* the socket can be shared by many transfers, iterate */ + Curl_hash_start_iterate(&entry->transfers, &iter); + for(he = Curl_hash_next_element(&iter); he; + he = Curl_hash_next_element(&iter)) { + data = (struct Curl_easy *)he->ptr; + DEBUGASSERT(data); + DEBUGASSERT(data->magic == CURLEASY_MAGIC_NUMBER); + + if(data->conn && !(data->conn->handler->flags & PROTOPT_DIRLOCK)) + /* set socket event bitmask if they're not locked */ + data->state.select_bits |= (unsigned char)ev_bitmask; + + Curl_expire(data, 0, EXPIRE_RUN_NOW); + } + + /* Now we fall-through and do the timer-based stuff, since we don't want + to force the user to have to deal with timeouts as long as at least + one connection in fact has traffic. */ + + data = NULL; /* set data to NULL again to avoid calling + multi_runsingle() in case there's no need to */ + now = Curl_now(); /* get a newer time since the multi_runsingle() loop + may have taken some time */ + } + } + else { + /* Asked to run due to time-out. Clear the 'lastcall' variable to force + Curl_update_timer() to trigger a callback to the app again even if the + same timeout is still the one to run after this call. That handles the + case when the application asks libcurl to run the timeout + prematurely. */ + memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall)); + } + + /* + * The loop following here will go on as long as there are expire-times left + * to process in the splay and 'data' will be re-assigned for every expired + * handle we deal with. + */ + do { + /* the first loop lap 'data' can be NULL */ + if(data) { + if(!first) { + first = TRUE; + nosig = data->set.no_signal; /* initial state */ + sigpipe_ignore(data, &pipe_st); + } + else if(data->set.no_signal != nosig) { + sigpipe_restore(&pipe_st); + sigpipe_ignore(data, &pipe_st); + nosig = data->set.no_signal; /* remember new state */ + } + result = multi_runsingle(multi, &now, data); + + if(CURLM_OK >= result) { + /* get the socket(s) and check if the state has been changed since + last */ + result = singlesocket(multi, data); + if(result) + break; + } + } + + /* Check if there's one (more) expired timer to deal with! This function + extracts a matching node if there is one */ + + multi->timetree = Curl_splaygetbest(now, multi->timetree, &t); + if(t) { + data = t->payload; /* assign this for next loop */ + (void)add_next_timeout(now, multi, t->payload); + } + + } while(t); + if(first) + sigpipe_restore(&pipe_st); + + *running_handles = multi->num_alive; + return result; +} + +#undef curl_multi_setopt +CURLMcode curl_multi_setopt(struct Curl_multi *multi, + CURLMoption option, ...) +{ + CURLMcode res = CURLM_OK; + va_list param; + unsigned long uarg; + + if(!GOOD_MULTI_HANDLE(multi)) + return CURLM_BAD_HANDLE; + + if(multi->in_callback) + return CURLM_RECURSIVE_API_CALL; + + va_start(param, option); + + switch(option) { + case CURLMOPT_SOCKETFUNCTION: + multi->socket_cb = va_arg(param, curl_socket_callback); + break; + case CURLMOPT_SOCKETDATA: + multi->socket_userp = va_arg(param, void *); + break; + case CURLMOPT_PUSHFUNCTION: + multi->push_cb = va_arg(param, curl_push_callback); + break; + case CURLMOPT_PUSHDATA: + multi->push_userp = va_arg(param, void *); + break; + case CURLMOPT_PIPELINING: + multi->multiplexing = va_arg(param, long) & CURLPIPE_MULTIPLEX ? 1 : 0; + break; + case CURLMOPT_TIMERFUNCTION: + multi->timer_cb = va_arg(param, curl_multi_timer_callback); + break; + case CURLMOPT_TIMERDATA: + multi->timer_userp = va_arg(param, void *); + break; + case CURLMOPT_MAXCONNECTS: + uarg = va_arg(param, unsigned long); + if(uarg <= UINT_MAX) + multi->maxconnects = (unsigned int)uarg; + break; + case CURLMOPT_MAX_HOST_CONNECTIONS: + multi->max_host_connections = va_arg(param, long); + break; + case CURLMOPT_MAX_TOTAL_CONNECTIONS: + multi->max_total_connections = va_arg(param, long); + break; + /* options formerly used for pipelining */ + case CURLMOPT_MAX_PIPELINE_LENGTH: + break; + case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE: + break; + case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE: + break; + case CURLMOPT_PIPELINING_SITE_BL: + break; + case CURLMOPT_PIPELINING_SERVER_BL: + break; + case CURLMOPT_MAX_CONCURRENT_STREAMS: + { + long streams = va_arg(param, long); + if((streams < 1) || (streams > INT_MAX)) + streams = 100; + multi->max_concurrent_streams = (unsigned int)streams; + } + break; + default: + res = CURLM_UNKNOWN_OPTION; + break; + } + va_end(param); + return res; +} + +/* we define curl_multi_socket() in the public multi.h header */ +#undef curl_multi_socket + +CURLMcode curl_multi_socket(struct Curl_multi *multi, curl_socket_t s, + int *running_handles) +{ + CURLMcode result; + if(multi->in_callback) + return CURLM_RECURSIVE_API_CALL; + result = multi_socket(multi, FALSE, s, 0, running_handles); + if(CURLM_OK >= result) + result = Curl_update_timer(multi); + return result; +} + +CURLMcode curl_multi_socket_action(struct Curl_multi *multi, curl_socket_t s, + int ev_bitmask, int *running_handles) +{ + CURLMcode result; + if(multi->in_callback) + return CURLM_RECURSIVE_API_CALL; + result = multi_socket(multi, FALSE, s, ev_bitmask, running_handles); + if(CURLM_OK >= result) + result = Curl_update_timer(multi); + return result; +} + +CURLMcode curl_multi_socket_all(struct Curl_multi *multi, int *running_handles) +{ + CURLMcode result; + if(multi->in_callback) + return CURLM_RECURSIVE_API_CALL; + result = multi_socket(multi, TRUE, CURL_SOCKET_BAD, 0, running_handles); + if(CURLM_OK >= result) + result = Curl_update_timer(multi); + return result; +} + +static CURLMcode multi_timeout(struct Curl_multi *multi, + long *timeout_ms) +{ + static const struct curltime tv_zero = {0, 0}; + + if(multi->dead) { + *timeout_ms = 0; + return CURLM_OK; + } + + if(multi->timetree) { + /* we have a tree of expire times */ + struct curltime now = Curl_now(); + + /* splay the lowest to the bottom */ + multi->timetree = Curl_splay(tv_zero, multi->timetree); + + if(Curl_splaycomparekeys(multi->timetree->key, now) > 0) { + /* some time left before expiration */ + timediff_t diff = Curl_timediff_ceil(multi->timetree->key, now); + /* this should be safe even on 32 bit archs, as we don't use that + overly long timeouts */ + *timeout_ms = (long)diff; + } + else + /* 0 means immediately */ + *timeout_ms = 0; + } + else + *timeout_ms = -1; + + return CURLM_OK; +} + +CURLMcode curl_multi_timeout(struct Curl_multi *multi, + long *timeout_ms) +{ + /* First, make some basic checks that the CURLM handle is a good handle */ + if(!GOOD_MULTI_HANDLE(multi)) + return CURLM_BAD_HANDLE; + + if(multi->in_callback) + return CURLM_RECURSIVE_API_CALL; + + return multi_timeout(multi, timeout_ms); +} + +/* + * Tell the application it should update its timers, if it subscribes to the + * update timer callback. + */ +CURLMcode Curl_update_timer(struct Curl_multi *multi) +{ + long timeout_ms; + int rc; + + if(!multi->timer_cb || multi->dead) + return CURLM_OK; + if(multi_timeout(multi, &timeout_ms)) { + return CURLM_OK; + } + if(timeout_ms < 0) { + static const struct curltime none = {0, 0}; + if(Curl_splaycomparekeys(none, multi->timer_lastcall)) { + multi->timer_lastcall = none; + /* there's no timeout now but there was one previously, tell the app to + disable it */ + set_in_callback(multi, TRUE); + rc = multi->timer_cb(multi, -1, multi->timer_userp); + set_in_callback(multi, FALSE); + if(rc == -1) { + multi->dead = TRUE; + return CURLM_ABORTED_BY_CALLBACK; + } + return CURLM_OK; + } + return CURLM_OK; + } + + /* When multi_timeout() is done, multi->timetree points to the node with the + * timeout we got the (relative) time-out time for. We can thus easily check + * if this is the same (fixed) time as we got in a previous call and then + * avoid calling the callback again. */ + if(Curl_splaycomparekeys(multi->timetree->key, multi->timer_lastcall) == 0) + return CURLM_OK; + + multi->timer_lastcall = multi->timetree->key; + + set_in_callback(multi, TRUE); + rc = multi->timer_cb(multi, timeout_ms, multi->timer_userp); + set_in_callback(multi, FALSE); + if(rc == -1) { + multi->dead = TRUE; + return CURLM_ABORTED_BY_CALLBACK; + } + return CURLM_OK; +} + +/* + * multi_deltimeout() + * + * Remove a given timestamp from the list of timeouts. + */ +static void +multi_deltimeout(struct Curl_easy *data, expire_id eid) +{ + struct Curl_llist_element *e; + struct Curl_llist *timeoutlist = &data->state.timeoutlist; + /* find and remove the specific node from the list */ + for(e = timeoutlist->head; e; e = e->next) { + struct time_node *n = (struct time_node *)e->ptr; + if(n->eid == eid) { + Curl_llist_remove(timeoutlist, e, NULL); + return; + } + } +} + +/* + * multi_addtimeout() + * + * Add a timestamp to the list of timeouts. Keep the list sorted so that head + * of list is always the timeout nearest in time. + * + */ +static CURLMcode +multi_addtimeout(struct Curl_easy *data, + struct curltime *stamp, + expire_id eid) +{ + struct Curl_llist_element *e; + struct time_node *node; + struct Curl_llist_element *prev = NULL; + size_t n; + struct Curl_llist *timeoutlist = &data->state.timeoutlist; + + node = &data->state.expires[eid]; + + /* copy the timestamp and id */ + memcpy(&node->time, stamp, sizeof(*stamp)); + node->eid = eid; /* also marks it as in use */ + + n = Curl_llist_count(timeoutlist); + if(n) { + /* find the correct spot in the list */ + for(e = timeoutlist->head; e; e = e->next) { + struct time_node *check = (struct time_node *)e->ptr; + timediff_t diff = Curl_timediff(check->time, node->time); + if(diff > 0) + break; + prev = e; + } + + } + /* else + this is the first timeout on the list */ + + Curl_llist_insert_next(timeoutlist, prev, node, &node->list); + return CURLM_OK; +} + +/* + * Curl_expire() + * + * given a number of milliseconds from now to use to set the 'act before + * this'-time for the transfer, to be extracted by curl_multi_timeout() + * + * The timeout will be added to a queue of timeouts if it defines a moment in + * time that is later than the current head of queue. + * + * Expire replaces a former timeout using the same id if already set. + */ +void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id id) +{ + struct Curl_multi *multi = data->multi; + struct curltime *nowp = &data->state.expiretime; + struct curltime set; + + /* this is only interesting while there is still an associated multi struct + remaining! */ + if(!multi) + return; + + DEBUGASSERT(id < EXPIRE_LAST); + + set = Curl_now(); + set.tv_sec += (time_t)(milli/1000); /* might be a 64 to 32 bit conversion */ + set.tv_usec += (unsigned int)(milli%1000)*1000; + + if(set.tv_usec >= 1000000) { + set.tv_sec++; + set.tv_usec -= 1000000; + } + + /* Remove any timer with the same id just in case. */ + multi_deltimeout(data, id); + + /* Add it to the timer list. It must stay in the list until it has expired + in case we need to recompute the minimum timer later. */ + multi_addtimeout(data, &set, id); + + if(nowp->tv_sec || nowp->tv_usec) { + /* This means that the struct is added as a node in the splay tree. + Compare if the new time is earlier, and only remove-old/add-new if it + is. */ + timediff_t diff = Curl_timediff(set, *nowp); + int rc; + + if(diff > 0) { + /* The current splay tree entry is sooner than this new expiry time. + We don't need to update our splay tree entry. */ + return; + } + + /* Since this is an updated time, we must remove the previous entry from + the splay tree first and then re-add the new value */ + rc = Curl_splayremove(multi->timetree, &data->state.timenode, + &multi->timetree); + if(rc) + infof(data, "Internal error removing splay node = %d", rc); + } + + /* Indicate that we are in the splay tree and insert the new timer expiry + value since it is our local minimum. */ + *nowp = set; + data->state.timenode.payload = data; + multi->timetree = Curl_splayinsert(*nowp, multi->timetree, + &data->state.timenode); +} + +/* + * Curl_expire_done() + * + * Removes the expire timer. Marks it as done. + * + */ +void Curl_expire_done(struct Curl_easy *data, expire_id id) +{ + /* remove the timer, if there */ + multi_deltimeout(data, id); +} + +/* + * Curl_expire_clear() + * + * Clear ALL timeout values for this handle. + */ +void Curl_expire_clear(struct Curl_easy *data) +{ + struct Curl_multi *multi = data->multi; + struct curltime *nowp = &data->state.expiretime; + + /* this is only interesting while there is still an associated multi struct + remaining! */ + if(!multi) + return; + + if(nowp->tv_sec || nowp->tv_usec) { + /* Since this is an cleared time, we must remove the previous entry from + the splay tree */ + struct Curl_llist *list = &data->state.timeoutlist; + int rc; + + rc = Curl_splayremove(multi->timetree, &data->state.timenode, + &multi->timetree); + if(rc) + infof(data, "Internal error clearing splay node = %d", rc); + + /* flush the timeout list too */ + while(list->size > 0) { + Curl_llist_remove(list, list->tail, NULL); + } + +#ifdef DEBUGBUILD + infof(data, "Expire cleared"); +#endif + nowp->tv_sec = 0; + nowp->tv_usec = 0; + } +} + + + + +CURLMcode curl_multi_assign(struct Curl_multi *multi, curl_socket_t s, + void *hashp) +{ + struct Curl_sh_entry *there = NULL; + + there = sh_getentry(&multi->sockhash, s); + + if(!there) + return CURLM_BAD_SOCKET; + + there->socketp = hashp; + + return CURLM_OK; +} + +size_t Curl_multi_max_host_connections(struct Curl_multi *multi) +{ + return multi ? multi->max_host_connections : 0; +} + +size_t Curl_multi_max_total_connections(struct Curl_multi *multi) +{ + return multi ? multi->max_total_connections : 0; +} + +/* + * When information about a connection has appeared, call this! + */ + +void Curl_multiuse_state(struct Curl_easy *data, + int bundlestate) /* use BUNDLE_* defines */ +{ + struct connectdata *conn; + DEBUGASSERT(data); + DEBUGASSERT(data->multi); + conn = data->conn; + DEBUGASSERT(conn); + DEBUGASSERT(conn->bundle); + + conn->bundle->multiuse = bundlestate; + process_pending_handles(data->multi); +} + +static void move_pending_to_connect(struct Curl_multi *multi, + struct Curl_easy *data) +{ + DEBUGASSERT(data->mstate == MSTATE_PENDING); + + /* put it back into the main list */ + link_easy(multi, data); + + multistate(data, MSTATE_CONNECT); + + /* Remove this node from the pending list */ + Curl_llist_remove(&multi->pending, &data->connect_queue, NULL); + + /* Make sure that the handle will be processed soonish. */ + Curl_expire(data, 0, EXPIRE_RUN_NOW); +} + +/* process_pending_handles() moves a handle from PENDING back into the main + list and change state to CONNECT. + + We do not move all transfers because that can be a significant amount. + Since this is tried every now and then doing too many too often becomes a + performance problem. + + When there is a change for connection limits like max host connections etc, + this likely only allows one new transfer. When there is a pipewait change, + it can potentially allow hundreds of new transfers. + + We could consider an improvement where we store the queue reason and allow + more pipewait rechecks than others. +*/ +static void process_pending_handles(struct Curl_multi *multi) +{ + struct Curl_llist_element *e = multi->pending.head; + if(e) { + struct Curl_easy *data = e->ptr; + move_pending_to_connect(multi, data); + } +} + +void Curl_set_in_callback(struct Curl_easy *data, bool value) +{ + if(data && data->multi) + data->multi->in_callback = value; +} + +bool Curl_is_in_callback(struct Curl_easy *data) +{ + return (data && data->multi && data->multi->in_callback); +} + +unsigned int Curl_multi_max_concurrent_streams(struct Curl_multi *multi) +{ + DEBUGASSERT(multi); + return multi->max_concurrent_streams; +} + +struct Curl_easy **curl_multi_get_handles(struct Curl_multi *multi) +{ + struct Curl_easy **a = malloc(sizeof(struct Curl_easy *) * + (multi->num_easy + 1)); + if(a) { + unsigned int i = 0; + struct Curl_easy *e = multi->easyp; + while(e) { + DEBUGASSERT(i < multi->num_easy); + if(!e->state.internal) + a[i++] = e; + e = e->next; + } + a[i] = NULL; /* last entry is a NULL */ + } + return a; +} + +CURLcode Curl_multi_xfer_buf_borrow(struct Curl_easy *data, + char **pbuf, size_t *pbuflen) +{ + DEBUGASSERT(data); + DEBUGASSERT(data->multi); + *pbuf = NULL; + *pbuflen = 0; + if(!data->multi) { + failf(data, "transfer has no multi handle"); + return CURLE_FAILED_INIT; + } + if(!data->set.buffer_size) { + failf(data, "transfer buffer size is 0"); + return CURLE_FAILED_INIT; + } + if(data->multi->xfer_buf_borrowed) { + failf(data, "attempt to borrow xfer_buf when already borrowed"); + return CURLE_AGAIN; + } + + if(data->multi->xfer_buf && + data->set.buffer_size > data->multi->xfer_buf_len) { + /* not large enough, get a new one */ + free(data->multi->xfer_buf); + data->multi->xfer_buf = NULL; + data->multi->xfer_buf_len = 0; + } + + if(!data->multi->xfer_buf) { + data->multi->xfer_buf = malloc((size_t)data->set.buffer_size); + if(!data->multi->xfer_buf) { + failf(data, "could not allocate xfer_buf of %zu bytes", + (size_t)data->set.buffer_size); + return CURLE_OUT_OF_MEMORY; + } + data->multi->xfer_buf_len = data->set.buffer_size; + } + + data->multi->xfer_buf_borrowed = TRUE; + *pbuf = data->multi->xfer_buf; + *pbuflen = data->multi->xfer_buf_len; + return CURLE_OK; +} + +void Curl_multi_xfer_buf_release(struct Curl_easy *data, char *buf) +{ + (void)buf; + DEBUGASSERT(data); + DEBUGASSERT(data->multi); + DEBUGASSERT(!buf || data->multi->xfer_buf == buf); + data->multi->xfer_buf_borrowed = FALSE; +} + +CURLcode Curl_multi_xfer_ulbuf_borrow(struct Curl_easy *data, + char **pbuf, size_t *pbuflen) +{ + DEBUGASSERT(data); + DEBUGASSERT(data->multi); + *pbuf = NULL; + *pbuflen = 0; + if(!data->multi) { + failf(data, "transfer has no multi handle"); + return CURLE_FAILED_INIT; + } + if(!data->set.upload_buffer_size) { + failf(data, "transfer upload buffer size is 0"); + return CURLE_FAILED_INIT; + } + if(data->multi->xfer_ulbuf_borrowed) { + failf(data, "attempt to borrow xfer_ulbuf when already borrowed"); + return CURLE_AGAIN; + } + + if(data->multi->xfer_ulbuf && + data->set.upload_buffer_size > data->multi->xfer_ulbuf_len) { + /* not large enough, get a new one */ + free(data->multi->xfer_ulbuf); + data->multi->xfer_ulbuf = NULL; + data->multi->xfer_ulbuf_len = 0; + } + + if(!data->multi->xfer_ulbuf) { + data->multi->xfer_ulbuf = malloc((size_t)data->set.upload_buffer_size); + if(!data->multi->xfer_ulbuf) { + failf(data, "could not allocate xfer_ulbuf of %zu bytes", + (size_t)data->set.upload_buffer_size); + return CURLE_OUT_OF_MEMORY; + } + data->multi->xfer_ulbuf_len = data->set.upload_buffer_size; + } + + data->multi->xfer_ulbuf_borrowed = TRUE; + *pbuf = data->multi->xfer_ulbuf; + *pbuflen = data->multi->xfer_ulbuf_len; + return CURLE_OK; +} + +void Curl_multi_xfer_ulbuf_release(struct Curl_easy *data, char *buf) +{ + (void)buf; + DEBUGASSERT(data); + DEBUGASSERT(data->multi); + DEBUGASSERT(!buf || data->multi->xfer_ulbuf == buf); + data->multi->xfer_ulbuf_borrowed = FALSE; +} + +static void multi_xfer_bufs_free(struct Curl_multi *multi) +{ + DEBUGASSERT(multi); + Curl_safefree(multi->xfer_buf); + multi->xfer_buf_len = 0; + multi->xfer_buf_borrowed = FALSE; + Curl_safefree(multi->xfer_ulbuf); + multi->xfer_ulbuf_len = 0; + multi->xfer_ulbuf_borrowed = FALSE; +} diff --git a/third_party/curl/lib/multihandle.h b/third_party/curl/lib/multihandle.h new file mode 100644 index 0000000..add9a05 --- /dev/null +++ b/third_party/curl/lib/multihandle.h @@ -0,0 +1,189 @@ +#ifndef HEADER_CURL_MULTIHANDLE_H +#define HEADER_CURL_MULTIHANDLE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "llist.h" +#include "hash.h" +#include "conncache.h" +#include "psl.h" +#include "socketpair.h" + +struct connectdata; + +struct Curl_message { + struct Curl_llist_element list; + /* the 'CURLMsg' is the part that is visible to the external user */ + struct CURLMsg extmsg; +}; + +/* NOTE: if you add a state here, add the name to the statename[] array as + well! +*/ +typedef enum { + MSTATE_INIT, /* 0 - start in this state */ + MSTATE_PENDING, /* 1 - no connections, waiting for one */ + MSTATE_SETUP, /* 2 - start a new transfer */ + MSTATE_CONNECT, /* 3 - resolve/connect has been sent off */ + MSTATE_RESOLVING, /* 4 - awaiting the resolve to finalize */ + MSTATE_CONNECTING, /* 5 - awaiting the TCP connect to finalize */ + MSTATE_TUNNELING, /* 6 - awaiting HTTPS proxy SSL initialization to + complete and/or proxy CONNECT to finalize */ + MSTATE_PROTOCONNECT, /* 7 - initiate protocol connect procedure */ + MSTATE_PROTOCONNECTING, /* 8 - completing the protocol-specific connect + phase */ + MSTATE_DO, /* 9 - start send off the request (part 1) */ + MSTATE_DOING, /* 10 - sending off the request (part 1) */ + MSTATE_DOING_MORE, /* 11 - send off the request (part 2) */ + MSTATE_DID, /* 12 - done sending off request */ + MSTATE_PERFORMING, /* 13 - transfer data */ + MSTATE_RATELIMITING, /* 14 - wait because limit-rate exceeded */ + MSTATE_DONE, /* 15 - post data transfer operation */ + MSTATE_COMPLETED, /* 16 - operation complete */ + MSTATE_MSGSENT, /* 17 - the operation complete message is sent */ + MSTATE_LAST /* 18 - not a true state, never use this */ +} CURLMstate; + +/* we support N sockets per easy handle. Set the corresponding bit to what + action we should wait for */ +#define MAX_SOCKSPEREASYHANDLE 5 +#define GETSOCK_READABLE (0x00ff) +#define GETSOCK_WRITABLE (0xff00) + +#define CURLPIPE_ANY (CURLPIPE_MULTIPLEX) + +#if !defined(CURL_DISABLE_SOCKETPAIR) +#define ENABLE_WAKEUP +#endif + +/* value for MAXIMUM CONCURRENT STREAMS upper limit */ +#define INITIAL_MAX_CONCURRENT_STREAMS ((1U << 31) - 1) + +/* Curl_multi SSL backend-specific data; declared differently by each SSL + backend */ +struct multi_ssl_backend_data; + +/* This is the struct known as CURLM on the outside */ +struct Curl_multi { + /* First a simple identifier to easier detect if a user mix up + this multi handle with an easy handle. Set this to CURL_MULTI_HANDLE. */ + unsigned int magic; + + /* We have a doubly-linked list with easy handles */ + struct Curl_easy *easyp; + struct Curl_easy *easylp; /* last node */ + + unsigned int num_easy; /* amount of entries in the linked list above. */ + unsigned int num_alive; /* amount of easy handles that are added but have + not yet reached COMPLETE state */ + + struct Curl_llist msglist; /* a list of messages from completed transfers */ + + struct Curl_llist pending; /* Curl_easys that are in the + MSTATE_PENDING state */ + struct Curl_llist msgsent; /* Curl_easys that are in the + MSTATE_MSGSENT state */ + + /* callback function and user data pointer for the *socket() API */ + curl_socket_callback socket_cb; + void *socket_userp; + + /* callback function and user data pointer for server push */ + curl_push_callback push_cb; + void *push_userp; + + /* Hostname cache */ + struct Curl_hash hostcache; + +#ifdef USE_LIBPSL + /* PSL cache. */ + struct PslCache psl; +#endif + + /* timetree points to the splay-tree of time nodes to figure out expire + times of all currently set timers */ + struct Curl_tree *timetree; + + /* buffer used for transfer data, lazy initialized */ + char *xfer_buf; /* the actual buffer */ + size_t xfer_buf_len; /* the allocated length */ + /* buffer used for upload data, lazy initialized */ + char *xfer_ulbuf; /* the actual buffer */ + size_t xfer_ulbuf_len; /* the allocated length */ + +#if defined(USE_SSL) + struct multi_ssl_backend_data *ssl_backend_data; +#endif + + /* 'sockhash' is the lookup hash for socket descriptor => easy handles (note + the pluralis form, there can be more than one easy handle waiting on the + same actual socket) */ + struct Curl_hash sockhash; + + /* Shared connection cache (bundles)*/ + struct conncache conn_cache; + + long max_host_connections; /* if >0, a fixed limit of the maximum number + of connections per host */ + + long max_total_connections; /* if >0, a fixed limit of the maximum number + of connections in total */ + + /* timer callback and user data pointer for the *socket() API */ + curl_multi_timer_callback timer_cb; + void *timer_userp; + struct curltime timer_lastcall; /* the fixed time for the timeout for the + previous callback */ +#ifdef USE_WINSOCK + WSAEVENT wsa_event; /* winsock event used for waits */ +#else +#ifdef ENABLE_WAKEUP + curl_socket_t wakeup_pair[2]; /* pipe()/socketpair() used for wakeup + 0 is used for read, 1 is used for write */ +#endif +#endif + unsigned int max_concurrent_streams; + unsigned int maxconnects; /* if >0, a fixed limit of the maximum number of + entries we're allowed to grow the connection + cache to */ +#define IPV6_UNKNOWN 0 +#define IPV6_DEAD 1 +#define IPV6_WORKS 2 + unsigned char ipv6_up; /* IPV6_* defined */ + BIT(multiplexing); /* multiplexing wanted */ + BIT(recheckstate); /* see Curl_multi_connchanged */ + BIT(in_callback); /* true while executing a callback */ +#ifdef USE_OPENSSL + BIT(ssl_seeded); +#endif + BIT(dead); /* a callback returned error, everything needs to crash and + burn */ + BIT(xfer_buf_borrowed); /* xfer_buf is currently being borrowed */ + BIT(xfer_ulbuf_borrowed); /* xfer_ulbuf is currently being borrowed */ +#ifdef DEBUGBUILD + BIT(warned); /* true after user warned of DEBUGBUILD */ +#endif +}; + +#endif /* HEADER_CURL_MULTIHANDLE_H */ diff --git a/third_party/curl/lib/multiif.h b/third_party/curl/lib/multiif.h new file mode 100644 index 0000000..59a3064 --- /dev/null +++ b/third_party/curl/lib/multiif.h @@ -0,0 +1,147 @@ +#ifndef HEADER_CURL_MULTIIF_H +#define HEADER_CURL_MULTIIF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Prototypes for library-wide functions provided by multi.c + */ + +CURLcode Curl_updatesocket(struct Curl_easy *data); +void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id); +void Curl_expire_clear(struct Curl_easy *data); +void Curl_expire_done(struct Curl_easy *data, expire_id id); +CURLMcode Curl_update_timer(struct Curl_multi *multi) WARN_UNUSED_RESULT; +void Curl_attach_connection(struct Curl_easy *data, + struct connectdata *conn); +void Curl_detach_connection(struct Curl_easy *data); +bool Curl_multiplex_wanted(const struct Curl_multi *multi); +void Curl_set_in_callback(struct Curl_easy *data, bool value); +bool Curl_is_in_callback(struct Curl_easy *data); +CURLcode Curl_preconnect(struct Curl_easy *data); + +void Curl_multi_connchanged(struct Curl_multi *multi); + +/* Internal version of curl_multi_init() accepts size parameters for the + socket, connection and dns hashes */ +struct Curl_multi *Curl_multi_handle(size_t hashsize, + size_t chashsize, + size_t dnssize); + +/* the write bits start at bit 16 for the *getsock() bitmap */ +#define GETSOCK_WRITEBITSTART 16 + +#define GETSOCK_BLANK 0 /* no bits set */ + +/* set the bit for the given sock number to make the bitmap for writable */ +#define GETSOCK_WRITESOCK(x) (1 << (GETSOCK_WRITEBITSTART + (x))) + +/* set the bit for the given sock number to make the bitmap for readable */ +#define GETSOCK_READSOCK(x) (1 << (x)) + +/* mask for checking if read and/or write is set for index x */ +#define GETSOCK_MASK_RW(x) (GETSOCK_READSOCK(x)|GETSOCK_WRITESOCK(x)) + +/* Return the value of the CURLMOPT_MAX_HOST_CONNECTIONS option */ +size_t Curl_multi_max_host_connections(struct Curl_multi *multi); + +/* Return the value of the CURLMOPT_MAX_TOTAL_CONNECTIONS option */ +size_t Curl_multi_max_total_connections(struct Curl_multi *multi); + +void Curl_multiuse_state(struct Curl_easy *data, + int bundlestate); /* use BUNDLE_* defines */ + +/* + * Curl_multi_closed() + * + * Used by the connect code to tell the multi_socket code that one of the + * sockets we were using is about to be closed. This function will then + * remove it from the sockethash for this handle to make the multi_socket API + * behave properly, especially for the case when libcurl will create another + * socket again and it gets the same file descriptor number. + */ + +void Curl_multi_closed(struct Curl_easy *data, curl_socket_t s); + +/* + * Add a handle and move it into PERFORM state at once. For pushed streams. + */ +CURLMcode Curl_multi_add_perform(struct Curl_multi *multi, + struct Curl_easy *data, + struct connectdata *conn); + + +/* Return the value of the CURLMOPT_MAX_CONCURRENT_STREAMS option */ +unsigned int Curl_multi_max_concurrent_streams(struct Curl_multi *multi); + +/** + * Borrow the transfer buffer from the multi, suitable + * for the given transfer `data`. The buffer may only be used in one + * multi processing of the easy handle. It MUST be returned to the + * multi before it can be borrowed again. + * Pointers into the buffer remain only valid as long as it is borrowed. + * + * @param data the easy handle + * @param pbuf on return, the buffer to use or NULL on error + * @param pbuflen on return, the size of *pbuf or 0 on error + * @return CURLE_OK when buffer is available and is returned. + * CURLE_OUT_OF_MEMORy on failure to allocate the buffer, + * CURLE_FAILED_INIT if the easy handle is without multi. + * CURLE_AGAIN if the buffer is borrowed already. + */ +CURLcode Curl_multi_xfer_buf_borrow(struct Curl_easy *data, + char **pbuf, size_t *pbuflen); +/** + * Release the borrowed buffer. All references into the buffer become + * invalid after this. + * @param buf the buffer pointer borrowed for coding error checks. + */ +void Curl_multi_xfer_buf_release(struct Curl_easy *data, char *buf); + +/** + * Borrow the upload buffer from the multi, suitable + * for the given transfer `data`. The buffer may only be used in one + * multi processing of the easy handle. It MUST be returned to the + * multi before it can be borrowed again. + * Pointers into the buffer remain only valid as long as it is borrowed. + * + * @param data the easy handle + * @param pbuf on return, the buffer to use or NULL on error + * @param pbuflen on return, the size of *pbuf or 0 on error + * @return CURLE_OK when buffer is available and is returned. + * CURLE_OUT_OF_MEMORy on failure to allocate the buffer, + * CURLE_FAILED_INIT if the easy handle is without multi. + * CURLE_AGAIN if the buffer is borrowed already. + */ +CURLcode Curl_multi_xfer_ulbuf_borrow(struct Curl_easy *data, + char **pbuf, size_t *pbuflen); + +/** + * Release the borrowed upload buffer. All references into the buffer become + * invalid after this. + * @param buf the upload buffer pointer borrowed for coding error checks. + */ +void Curl_multi_xfer_ulbuf_release(struct Curl_easy *data, char *buf); + +#endif /* HEADER_CURL_MULTIIF_H */ diff --git a/third_party/curl/lib/netrc.c b/third_party/curl/lib/netrc.c new file mode 100644 index 0000000..cd2a284 --- /dev/null +++ b/third_party/curl/lib/netrc.c @@ -0,0 +1,353 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#ifndef CURL_DISABLE_NETRC + +#ifdef HAVE_PWD_H +#include +#endif + +#include +#include "netrc.h" +#include "strtok.h" +#include "strcase.h" +#include "curl_get_line.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* Get user and password from .netrc when given a machine name */ + +enum host_lookup_state { + NOTHING, + HOSTFOUND, /* the 'machine' keyword was found */ + HOSTVALID, /* this is "our" machine! */ + MACDEF +}; + +#define NETRC_FILE_MISSING 1 +#define NETRC_FAILED -1 +#define NETRC_SUCCESS 0 + +#define MAX_NETRC_LINE 4096 + +/* + * Returns zero on success. + */ +static int parsenetrc(const char *host, + char **loginp, + char **passwordp, + char *netrcfile) +{ + FILE *file; + int retcode = NETRC_FILE_MISSING; + char *login = *loginp; + char *password = *passwordp; + bool specific_login = (login && *login != 0); + bool login_alloc = FALSE; + bool password_alloc = FALSE; + enum host_lookup_state state = NOTHING; + + char state_login = 0; /* Found a login keyword */ + char state_password = 0; /* Found a password keyword */ + int state_our_login = TRUE; /* With specific_login, found *our* login + name (or login-less line) */ + + DEBUGASSERT(netrcfile); + + file = fopen(netrcfile, FOPEN_READTEXT); + if(file) { + bool done = FALSE; + struct dynbuf buf; + Curl_dyn_init(&buf, MAX_NETRC_LINE); + + while(!done && Curl_get_line(&buf, file)) { + char *tok; + char *tok_end; + bool quoted; + char *netrcbuffer = Curl_dyn_ptr(&buf); + if(state == MACDEF) { + if((netrcbuffer[0] == '\n') || (netrcbuffer[0] == '\r')) + state = NOTHING; + else + continue; + } + tok = netrcbuffer; + while(tok) { + while(ISBLANK(*tok)) + tok++; + /* tok is first non-space letter */ + if(!*tok || (*tok == '#')) + /* end of line or the rest is a comment */ + break; + + /* leading double-quote means quoted string */ + quoted = (*tok == '\"'); + + tok_end = tok; + if(!quoted) { + while(!ISSPACE(*tok_end)) + tok_end++; + *tok_end = 0; + } + else { + bool escape = FALSE; + bool endquote = FALSE; + char *store = tok; + tok_end++; /* pass the leading quote */ + while(*tok_end) { + char s = *tok_end; + if(escape) { + escape = FALSE; + switch(s) { + case 'n': + s = '\n'; + break; + case 'r': + s = '\r'; + break; + case 't': + s = '\t'; + break; + } + } + else if(s == '\\') { + escape = TRUE; + tok_end++; + continue; + } + else if(s == '\"') { + tok_end++; /* pass the ending quote */ + endquote = TRUE; + break; + } + *store++ = s; + tok_end++; + } + *store = 0; + if(escape || !endquote) { + /* bad syntax, get out */ + retcode = NETRC_FAILED; + goto out; + } + } + + if((login && *login) && (password && *password)) { + done = TRUE; + break; + } + + switch(state) { + case NOTHING: + if(strcasecompare("macdef", tok)) { + /* Define a macro. A macro is defined with the specified name; its + contents begin with the next .netrc line and continue until a + null line (consecutive new-line characters) is encountered. */ + state = MACDEF; + } + else if(strcasecompare("machine", tok)) { + /* the next tok is the machine name, this is in itself the + delimiter that starts the stuff entered for this machine, + after this we need to search for 'login' and + 'password'. */ + state = HOSTFOUND; + } + else if(strcasecompare("default", tok)) { + state = HOSTVALID; + retcode = NETRC_SUCCESS; /* we did find our host */ + } + break; + case MACDEF: + if(!strlen(tok)) { + state = NOTHING; + } + break; + case HOSTFOUND: + if(strcasecompare(host, tok)) { + /* and yes, this is our host! */ + state = HOSTVALID; + retcode = NETRC_SUCCESS; /* we did find our host */ + } + else + /* not our host */ + state = NOTHING; + break; + case HOSTVALID: + /* we are now parsing sub-keywords concerning "our" host */ + if(state_login) { + if(specific_login) { + state_our_login = !Curl_timestrcmp(login, tok); + } + else if(!login || Curl_timestrcmp(login, tok)) { + if(login_alloc) { + free(login); + login_alloc = FALSE; + } + login = strdup(tok); + if(!login) { + retcode = NETRC_FAILED; /* allocation failed */ + goto out; + } + login_alloc = TRUE; + } + state_login = 0; + } + else if(state_password) { + if((state_our_login || !specific_login) + && (!password || Curl_timestrcmp(password, tok))) { + if(password_alloc) { + free(password); + password_alloc = FALSE; + } + password = strdup(tok); + if(!password) { + retcode = NETRC_FAILED; /* allocation failed */ + goto out; + } + password_alloc = TRUE; + } + state_password = 0; + } + else if(strcasecompare("login", tok)) + state_login = 1; + else if(strcasecompare("password", tok)) + state_password = 1; + else if(strcasecompare("machine", tok)) { + /* ok, there's machine here go => */ + state = HOSTFOUND; + state_our_login = FALSE; + } + break; + } /* switch (state) */ + tok = ++tok_end; + } + } /* while Curl_get_line() */ + +out: + Curl_dyn_free(&buf); + if(!retcode) { + /* success */ + if(login_alloc) { + if(*loginp) + free(*loginp); + *loginp = login; + } + if(password_alloc) { + if(*passwordp) + free(*passwordp); + *passwordp = password; + } + } + else { + if(login_alloc) + free(login); + if(password_alloc) + free(password); + } + fclose(file); + } + + return retcode; +} + +/* + * @unittest: 1304 + * + * *loginp and *passwordp MUST be allocated if they aren't NULL when passed + * in. + */ +int Curl_parsenetrc(const char *host, char **loginp, char **passwordp, + char *netrcfile) +{ + int retcode = 1; + char *filealloc = NULL; + + if(!netrcfile) { +#if defined(HAVE_GETPWUID_R) && defined(HAVE_GETEUID) + char pwbuf[1024]; +#endif + char *home = NULL; + char *homea = curl_getenv("HOME"); /* portable environment reader */ + if(homea) { + home = homea; +#if defined(HAVE_GETPWUID_R) && defined(HAVE_GETEUID) + } + else { + struct passwd pw, *pw_res; + if(!getpwuid_r(geteuid(), &pw, pwbuf, sizeof(pwbuf), &pw_res) + && pw_res) { + home = pw.pw_dir; + } +#elif defined(HAVE_GETPWUID) && defined(HAVE_GETEUID) + } + else { + struct passwd *pw; + pw = getpwuid(geteuid()); + if(pw) { + home = pw->pw_dir; + } +#elif defined(_WIN32) + } + else { + homea = curl_getenv("USERPROFILE"); + if(homea) { + home = homea; + } +#endif + } + + if(!home) + return retcode; /* no home directory found (or possibly out of + memory) */ + + filealloc = curl_maprintf("%s%s.netrc", home, DIR_CHAR); + if(!filealloc) { + free(homea); + return -1; + } + retcode = parsenetrc(host, loginp, passwordp, filealloc); + free(filealloc); +#ifdef _WIN32 + if(retcode == NETRC_FILE_MISSING) { + /* fallback to the old-style "_netrc" file */ + filealloc = curl_maprintf("%s%s_netrc", home, DIR_CHAR); + if(!filealloc) { + free(homea); + return -1; + } + retcode = parsenetrc(host, loginp, passwordp, filealloc); + free(filealloc); + } +#endif + free(homea); + } + else + retcode = parsenetrc(host, loginp, passwordp, netrcfile); + return retcode; +} + +#endif diff --git a/third_party/curl/lib/netrc.h b/third_party/curl/lib/netrc.h new file mode 100644 index 0000000..9f2815f --- /dev/null +++ b/third_party/curl/lib/netrc.h @@ -0,0 +1,43 @@ +#ifndef HEADER_CURL_NETRC_H +#define HEADER_CURL_NETRC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#ifndef CURL_DISABLE_NETRC + +/* returns -1 on failure, 0 if the host is found, 1 is the host isn't found */ +int Curl_parsenetrc(const char *host, char **loginp, + char **passwordp, char *filename); + /* Assume: (*passwordp)[0]=0, host[0] != 0. + * If (*loginp)[0] = 0, search for login and password within a machine + * section in the netrc. + * If (*loginp)[0] != 0, search for password within machine and login. + */ +#else +/* disabled */ +#define Curl_parsenetrc(a,b,c,d,e,f) 1 +#endif + +#endif /* HEADER_CURL_NETRC_H */ diff --git a/third_party/curl/lib/nonblock.c b/third_party/curl/lib/nonblock.c new file mode 100644 index 0000000..f4eb656 --- /dev/null +++ b/third_party/curl/lib/nonblock.c @@ -0,0 +1,84 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_SYS_IOCTL_H +#include +#endif +#ifdef HAVE_FCNTL_H +#include +#endif + +#ifdef __VMS +#include +#include +#endif + +#include "nonblock.h" + +/* + * curlx_nonblock() set the given socket to either blocking or non-blocking + * mode based on the 'nonblock' boolean argument. This function is highly + * portable. + */ +int curlx_nonblock(curl_socket_t sockfd, /* operate on this */ + int nonblock /* TRUE or FALSE */) +{ +#if defined(HAVE_FCNTL_O_NONBLOCK) + /* most recent unix versions */ + int flags; + flags = sfcntl(sockfd, F_GETFL, 0); + if(nonblock) + return sfcntl(sockfd, F_SETFL, flags | O_NONBLOCK); + return sfcntl(sockfd, F_SETFL, flags & (~O_NONBLOCK)); + +#elif defined(HAVE_IOCTL_FIONBIO) + + /* older unix versions */ + int flags = nonblock ? 1 : 0; + return ioctl(sockfd, FIONBIO, &flags); + +#elif defined(HAVE_IOCTLSOCKET_FIONBIO) + + /* Windows */ + unsigned long flags = nonblock ? 1UL : 0UL; + return ioctlsocket(sockfd, FIONBIO, &flags); + +#elif defined(HAVE_IOCTLSOCKET_CAMEL_FIONBIO) + + /* Amiga */ + long flags = nonblock ? 1L : 0L; + return IoctlSocket(sockfd, FIONBIO, (char *)&flags); + +#elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK) + + /* Orbis OS */ + long b = nonblock ? 1L : 0L; + return setsockopt(sockfd, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b)); + +#else +# error "no non-blocking method was found/used/set" +#endif +} diff --git a/third_party/curl/lib/nonblock.h b/third_party/curl/lib/nonblock.h new file mode 100644 index 0000000..4a1a615 --- /dev/null +++ b/third_party/curl/lib/nonblock.h @@ -0,0 +1,32 @@ +#ifndef HEADER_CURL_NONBLOCK_H +#define HEADER_CURL_NONBLOCK_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include /* for curl_socket_t */ + +int curlx_nonblock(curl_socket_t sockfd, /* operate on this */ + int nonblock /* TRUE or FALSE */); + +#endif /* HEADER_CURL_NONBLOCK_H */ diff --git a/third_party/curl/lib/noproxy.c b/third_party/curl/lib/noproxy.c new file mode 100644 index 0000000..62299e2 --- /dev/null +++ b/third_party/curl/lib/noproxy.c @@ -0,0 +1,265 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_PROXY + +#include "inet_pton.h" +#include "strcase.h" +#include "noproxy.h" + +#ifdef HAVE_NETINET_IN_H +#include +#endif + +#ifdef HAVE_ARPA_INET_H +#include +#endif + +/* + * Curl_cidr4_match() returns TRUE if the given IPv4 address is within the + * specified CIDR address range. + */ +UNITTEST bool Curl_cidr4_match(const char *ipv4, /* 1.2.3.4 address */ + const char *network, /* 1.2.3.4 address */ + unsigned int bits) +{ + unsigned int address = 0; + unsigned int check = 0; + + if(bits > 32) + /* strange input */ + return FALSE; + + if(1 != Curl_inet_pton(AF_INET, ipv4, &address)) + return FALSE; + if(1 != Curl_inet_pton(AF_INET, network, &check)) + return FALSE; + + if(bits && (bits != 32)) { + unsigned int mask = 0xffffffff << (32 - bits); + unsigned int haddr = htonl(address); + unsigned int hcheck = htonl(check); +#if 0 + fprintf(stderr, "Host %s (%x) network %s (%x) bits %u mask %x => %x\n", + ipv4, haddr, network, hcheck, bits, mask, + (haddr ^ hcheck) & mask); +#endif + if((haddr ^ hcheck) & mask) + return FALSE; + return TRUE; + } + return (address == check); +} + +UNITTEST bool Curl_cidr6_match(const char *ipv6, + const char *network, + unsigned int bits) +{ +#ifdef USE_IPV6 + int bytes; + int rest; + unsigned char address[16]; + unsigned char check[16]; + + if(!bits) + bits = 128; + + bytes = bits/8; + rest = bits & 0x07; + if(1 != Curl_inet_pton(AF_INET6, ipv6, address)) + return FALSE; + if(1 != Curl_inet_pton(AF_INET6, network, check)) + return FALSE; + if((bytes > 16) || ((bytes == 16) && rest)) + return FALSE; + if(bytes && memcmp(address, check, bytes)) + return FALSE; + if(rest && !((address[bytes] ^ check[bytes]) & (0xff << (8 - rest)))) + return FALSE; + + return TRUE; +#else + (void)ipv6; + (void)network; + (void)bits; + return FALSE; +#endif +} + +enum nametype { + TYPE_HOST, + TYPE_IPV4, + TYPE_IPV6 +}; + +/**************************************************************** +* Checks if the host is in the noproxy list. returns TRUE if it matches and +* therefore the proxy should NOT be used. +****************************************************************/ +bool Curl_check_noproxy(const char *name, const char *no_proxy, + bool *spacesep) +{ + char hostip[128]; + *spacesep = FALSE; + /* + * If we don't have a hostname at all, like for example with a FILE + * transfer, we have nothing to interrogate the noproxy list with. + */ + if(!name || name[0] == '\0') + return FALSE; + + /* no_proxy=domain1.dom,host.domain2.dom + * (a comma-separated list of hosts which should + * not be proxied, or an asterisk to override + * all proxy variables) + */ + if(no_proxy && no_proxy[0]) { + const char *p = no_proxy; + size_t namelen; + enum nametype type = TYPE_HOST; + if(!strcmp("*", no_proxy)) + return TRUE; + + /* NO_PROXY was specified and it wasn't just an asterisk */ + + if(name[0] == '[') { + char *endptr; + /* IPv6 numerical address */ + endptr = strchr(name, ']'); + if(!endptr) + return FALSE; + name++; + namelen = endptr - name; + if(namelen >= sizeof(hostip)) + return FALSE; + memcpy(hostip, name, namelen); + hostip[namelen] = 0; + name = hostip; + type = TYPE_IPV6; + } + else { + unsigned int address; + namelen = strlen(name); + if(1 == Curl_inet_pton(AF_INET, name, &address)) + type = TYPE_IPV4; + else { + /* ignore trailing dots in the host name */ + if(name[namelen - 1] == '.') + namelen--; + } + } + + while(*p) { + const char *token; + size_t tokenlen = 0; + bool match = FALSE; + + /* pass blanks */ + while(*p && ISBLANK(*p)) + p++; + + token = p; + /* pass over the pattern */ + while(*p && !ISBLANK(*p) && (*p != ',')) { + p++; + tokenlen++; + } + + if(tokenlen) { + switch(type) { + case TYPE_HOST: + /* ignore trailing dots in the token to check */ + if(token[tokenlen - 1] == '.') + tokenlen--; + + if(tokenlen && (*token == '.')) { + /* ignore leading token dot as well */ + token++; + tokenlen--; + } + /* A: example.com matches 'example.com' + B: www.example.com matches 'example.com' + C: nonexample.com DOES NOT match 'example.com' + */ + if(tokenlen == namelen) + /* case A, exact match */ + match = strncasecompare(token, name, namelen); + else if(tokenlen < namelen) { + /* case B, tailmatch domain */ + match = (name[namelen - tokenlen - 1] == '.') && + strncasecompare(token, name + (namelen - tokenlen), + tokenlen); + } + /* case C passes through, not a match */ + break; + case TYPE_IPV4: + case TYPE_IPV6: { + const char *check = token; + char *slash; + unsigned int bits = 0; + char checkip[128]; + if(tokenlen >= sizeof(checkip)) + /* this cannot match */ + break; + /* copy the check name to a temp buffer */ + memcpy(checkip, check, tokenlen); + checkip[tokenlen] = 0; + check = checkip; + + slash = strchr(check, '/'); + /* if the slash is part of this token, use it */ + if(slash) { + bits = atoi(slash + 1); + *slash = 0; /* null terminate there */ + } + if(type == TYPE_IPV6) + match = Curl_cidr6_match(name, check, bits); + else + match = Curl_cidr4_match(name, check, bits); + break; + } + } + if(match) + return TRUE; + } /* if(tokenlen) */ + /* pass blanks after pattern */ + while(ISBLANK(*p)) + p++; + /* if not a comma! */ + if(*p && (*p != ',')) { + *spacesep = TRUE; + continue; + } + /* pass any number of commas */ + while(*p == ',') + p++; + } /* while(*p) */ + } /* NO_PROXY was specified and it wasn't just an asterisk */ + + return FALSE; +} + +#endif /* CURL_DISABLE_PROXY */ diff --git a/third_party/curl/lib/noproxy.h b/third_party/curl/lib/noproxy.h new file mode 100644 index 0000000..a3a6807 --- /dev/null +++ b/third_party/curl/lib/noproxy.h @@ -0,0 +1,45 @@ +#ifndef HEADER_CURL_NOPROXY_H +#define HEADER_CURL_NOPROXY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_PROXY + +#ifdef DEBUGBUILD + +UNITTEST bool Curl_cidr4_match(const char *ipv4, /* 1.2.3.4 address */ + const char *network, /* 1.2.3.4 address */ + unsigned int bits); +UNITTEST bool Curl_cidr6_match(const char *ipv6, + const char *network, + unsigned int bits); +#endif + +bool Curl_check_noproxy(const char *name, const char *no_proxy, + bool *spacesep); + +#endif + +#endif /* HEADER_CURL_NOPROXY_H */ diff --git a/third_party/curl/lib/openldap.c b/third_party/curl/lib/openldap.c new file mode 100644 index 0000000..0348ef5 --- /dev/null +++ b/third_party/curl/lib/openldap.c @@ -0,0 +1,1224 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (C) Howard Chu, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_LDAP) && defined(USE_OPENLDAP) + +/* + * Notice that USE_OPENLDAP is only a source code selection switch. When + * libcurl is built with USE_OPENLDAP defined the libcurl source code that + * gets compiled is the code from openldap.c, otherwise the code that gets + * compiled is the code from ldap.c. + * + * When USE_OPENLDAP is defined a recent version of the OpenLDAP library + * might be required for compilation and runtime. In order to use ancient + * OpenLDAP library versions, USE_OPENLDAP shall not be defined. + */ + +#include + +#include "urldata.h" +#include +#include "sendf.h" +#include "vtls/vtls.h" +#include "transfer.h" +#include "curl_ldap.h" +#include "curl_base64.h" +#include "cfilters.h" +#include "connect.h" +#include "curl_sasl.h" +#include "strcase.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Uncommenting this will enable the built-in debug logging of the openldap + * library. The debug log level can be set using the CURL_OPENLDAP_TRACE + * environment variable. The debug output is written to stderr. + * + * The library supports the following debug flags: + * LDAP_DEBUG_NONE 0x0000 + * LDAP_DEBUG_TRACE 0x0001 + * LDAP_DEBUG_CONSTRUCT 0x0002 + * LDAP_DEBUG_DESTROY 0x0004 + * LDAP_DEBUG_PARAMETER 0x0008 + * LDAP_DEBUG_ANY 0xffff + * + * For example, use CURL_OPENLDAP_TRACE=0 for no debug, + * CURL_OPENLDAP_TRACE=2 for LDAP_DEBUG_CONSTRUCT messages only, + * CURL_OPENLDAP_TRACE=65535 for all debug message levels. + */ +/* #define CURL_OPENLDAP_DEBUG */ + +/* Machine states. */ +typedef enum { + OLDAP_STOP, /* Do nothing state, stops the state machine */ + OLDAP_SSL, /* Performing SSL handshake. */ + OLDAP_STARTTLS, /* STARTTLS request sent. */ + OLDAP_TLS, /* Performing TLS handshake. */ + OLDAP_MECHS, /* Get SASL authentication mechanisms. */ + OLDAP_SASL, /* SASL binding reply. */ + OLDAP_BIND, /* Simple bind reply. */ + OLDAP_BINDV2, /* Simple bind reply in protocol version 2. */ + OLDAP_LAST /* Never used */ +} ldapstate; + +#ifndef _LDAP_PVT_H +extern int ldap_pvt_url_scheme2proto(const char *); +extern int ldap_init_fd(ber_socket_t fd, int proto, const char *url, + LDAP **ld); +#endif + +static CURLcode oldap_setup_connection(struct Curl_easy *data, + struct connectdata *conn); +static CURLcode oldap_do(struct Curl_easy *data, bool *done); +static CURLcode oldap_done(struct Curl_easy *data, CURLcode, bool); +static CURLcode oldap_connect(struct Curl_easy *data, bool *done); +static CURLcode oldap_connecting(struct Curl_easy *data, bool *done); +static CURLcode oldap_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead); + +static CURLcode oldap_perform_auth(struct Curl_easy *data, const char *mech, + const struct bufref *initresp); +static CURLcode oldap_continue_auth(struct Curl_easy *data, const char *mech, + const struct bufref *resp); +static CURLcode oldap_cancel_auth(struct Curl_easy *data, const char *mech); +static CURLcode oldap_get_message(struct Curl_easy *data, struct bufref *out); + +static Curl_recv oldap_recv; + +/* + * LDAP protocol handler. + */ + +const struct Curl_handler Curl_handler_ldap = { + "ldap", /* scheme */ + oldap_setup_connection, /* setup_connection */ + oldap_do, /* do_it */ + oldap_done, /* done */ + ZERO_NULL, /* do_more */ + oldap_connect, /* connect_it */ + oldap_connecting, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + oldap_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_LDAP, /* defport */ + CURLPROTO_LDAP, /* protocol */ + CURLPROTO_LDAP, /* family */ + PROTOPT_NONE /* flags */ +}; + +#ifdef USE_SSL +/* + * LDAPS protocol handler. + */ + +const struct Curl_handler Curl_handler_ldaps = { + "ldaps", /* scheme */ + oldap_setup_connection, /* setup_connection */ + oldap_do, /* do_it */ + oldap_done, /* done */ + ZERO_NULL, /* do_more */ + oldap_connect, /* connect_it */ + oldap_connecting, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + oldap_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_LDAPS, /* defport */ + CURLPROTO_LDAPS, /* protocol */ + CURLPROTO_LDAP, /* family */ + PROTOPT_SSL /* flags */ +}; +#endif + +/* SASL parameters for the ldap protocol */ +static const struct SASLproto saslldap = { + "ldap", /* The service name */ + oldap_perform_auth, /* Send authentication command */ + oldap_continue_auth, /* Send authentication continuation */ + oldap_cancel_auth, /* Send authentication cancellation */ + oldap_get_message, /* Get SASL response message */ + 0, /* Maximum initial response length (no max) */ + LDAP_SASL_BIND_IN_PROGRESS, /* Code received when continuation is expected */ + LDAP_SUCCESS, /* Code to receive upon authentication success */ + SASL_AUTH_NONE, /* Default mechanisms */ + 0 /* Configuration flags */ +}; + +struct ldapconninfo { + struct SASL sasl; /* SASL-related parameters */ + LDAP *ld; /* Openldap connection handle. */ + Curl_recv *recv; /* For stacking SSL handler */ + Curl_send *send; + struct berval *servercred; /* SASL data from server. */ + ldapstate state; /* Current machine state. */ + int proto; /* LDAP_PROTO_TCP/LDAP_PROTO_UDP/LDAP_PROTO_IPC */ + int msgid; /* Current message id. */ +}; + +struct ldapreqinfo { + int msgid; + int nument; +}; + +/* + * oldap_state() + * + * This is the ONLY way to change LDAP state! + */ +static void oldap_state(struct Curl_easy *data, ldapstate newstate) +{ + struct ldapconninfo *ldapc = data->conn->proto.ldapc; + +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + /* for debug purposes */ + static const char * const names[] = { + "STOP", + "SSL", + "STARTTLS", + "TLS", + "MECHS", + "SASL", + "BIND", + "BINDV2", + /* LAST */ + }; + + if(ldapc->state != newstate) + infof(data, "LDAP %p state change from %s to %s", + (void *)ldapc, names[ldapc->state], names[newstate]); +#endif + + ldapc->state = newstate; +} + +/* Map some particular LDAP error codes to CURLcode values. */ +static CURLcode oldap_map_error(int rc, CURLcode result) +{ + switch(rc) { + case LDAP_NO_MEMORY: + result = CURLE_OUT_OF_MEMORY; + break; + case LDAP_INVALID_CREDENTIALS: + result = CURLE_LOGIN_DENIED; + break; + case LDAP_PROTOCOL_ERROR: + result = CURLE_UNSUPPORTED_PROTOCOL; + break; + case LDAP_INSUFFICIENT_ACCESS: + result = CURLE_REMOTE_ACCESS_DENIED; + break; + } + return result; +} + +static CURLcode oldap_url_parse(struct Curl_easy *data, LDAPURLDesc **ludp) +{ + CURLcode result = CURLE_OK; + int rc = LDAP_URL_ERR_BADURL; + static const char * const url_errs[] = { + "success", + "out of memory", + "bad parameter", + "unrecognized scheme", + "unbalanced delimiter", + "bad URL", + "bad host or port", + "bad or missing attributes", + "bad or missing scope", + "bad or missing filter", + "bad or missing extensions" + }; + + *ludp = NULL; + if(!data->state.up.user && !data->state.up.password && + !data->state.up.options) + rc = ldap_url_parse(data->state.url, ludp); + if(rc != LDAP_URL_SUCCESS) { + const char *msg = "url parsing problem"; + + result = rc == LDAP_URL_ERR_MEM? CURLE_OUT_OF_MEMORY: CURLE_URL_MALFORMAT; + rc -= LDAP_URL_SUCCESS; + if((size_t) rc < sizeof(url_errs) / sizeof(url_errs[0])) + msg = url_errs[rc]; + failf(data, "LDAP local: %s", msg); + } + return result; +} + +/* Parse the login options. */ +static CURLcode oldap_parse_login_options(struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + struct ldapconninfo *li = conn->proto.ldapc; + const char *ptr = conn->options; + + while(!result && ptr && *ptr) { + const char *key = ptr; + const char *value; + + while(*ptr && *ptr != '=') + ptr++; + + value = ptr + 1; + + while(*ptr && *ptr != ';') + ptr++; + + if(checkprefix("AUTH=", key)) + result = Curl_sasl_parse_url_auth_option(&li->sasl, value, ptr - value); + else + result = CURLE_SETOPT_OPTION_SYNTAX; + + if(*ptr == ';') + ptr++; + } + + return result == CURLE_URL_MALFORMAT? CURLE_SETOPT_OPTION_SYNTAX: result; +} + +static CURLcode oldap_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result; + LDAPURLDesc *lud; + (void)conn; + + /* Early URL syntax check. */ + result = oldap_url_parse(data, &lud); + ldap_free_urldesc(lud); + + return result; +} + +/* + * Get the SASL authentication challenge from the server credential buffer. + */ +static CURLcode oldap_get_message(struct Curl_easy *data, struct bufref *out) +{ + struct berval *servercred = data->conn->proto.ldapc->servercred; + + if(!servercred || !servercred->bv_val) + return CURLE_WEIRD_SERVER_REPLY; + Curl_bufref_set(out, servercred->bv_val, servercred->bv_len, NULL); + return CURLE_OK; +} + +/* + * Sends an initial SASL bind request to the server. + */ +static CURLcode oldap_perform_auth(struct Curl_easy *data, const char *mech, + const struct bufref *initresp) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li = conn->proto.ldapc; + CURLcode result = CURLE_OK; + struct berval cred; + struct berval *pcred = &cred; + int rc; + + cred.bv_val = (char *) Curl_bufref_ptr(initresp); + cred.bv_len = Curl_bufref_len(initresp); + if(!cred.bv_val) + pcred = NULL; + rc = ldap_sasl_bind(li->ld, NULL, mech, pcred, NULL, NULL, &li->msgid); + if(rc != LDAP_SUCCESS) + result = oldap_map_error(rc, CURLE_LDAP_CANNOT_BIND); + return result; +} + +/* + * Sends SASL continuation. + */ +static CURLcode oldap_continue_auth(struct Curl_easy *data, const char *mech, + const struct bufref *resp) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li = conn->proto.ldapc; + CURLcode result = CURLE_OK; + struct berval cred; + struct berval *pcred = &cred; + int rc; + + cred.bv_val = (char *) Curl_bufref_ptr(resp); + cred.bv_len = Curl_bufref_len(resp); + if(!cred.bv_val) + pcred = NULL; + rc = ldap_sasl_bind(li->ld, NULL, mech, pcred, NULL, NULL, &li->msgid); + if(rc != LDAP_SUCCESS) + result = oldap_map_error(rc, CURLE_LDAP_CANNOT_BIND); + return result; +} + +/* + * Sends SASL bind cancellation. + */ +static CURLcode oldap_cancel_auth(struct Curl_easy *data, const char *mech) +{ + struct ldapconninfo *li = data->conn->proto.ldapc; + CURLcode result = CURLE_OK; + int rc = ldap_sasl_bind(li->ld, NULL, LDAP_SASL_NULL, NULL, NULL, NULL, + &li->msgid); + + (void)mech; + if(rc != LDAP_SUCCESS) + result = oldap_map_error(rc, CURLE_LDAP_CANNOT_BIND); + return result; +} + +/* Starts LDAP simple bind. */ +static CURLcode oldap_perform_bind(struct Curl_easy *data, ldapstate newstate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct ldapconninfo *li = conn->proto.ldapc; + char *binddn = NULL; + struct berval passwd; + int rc; + + passwd.bv_val = NULL; + passwd.bv_len = 0; + + if(data->state.aptr.user) { + binddn = conn->user; + passwd.bv_val = conn->passwd; + passwd.bv_len = strlen(passwd.bv_val); + } + + rc = ldap_sasl_bind(li->ld, binddn, LDAP_SASL_SIMPLE, &passwd, + NULL, NULL, &li->msgid); + if(rc == LDAP_SUCCESS) + oldap_state(data, newstate); + else + result = oldap_map_error(rc, + data->state.aptr.user? + CURLE_LOGIN_DENIED: CURLE_LDAP_CANNOT_BIND); + return result; +} + +/* Query the supported SASL authentication mechanisms. */ +static CURLcode oldap_perform_mechs(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct ldapconninfo *li = data->conn->proto.ldapc; + int rc; + static const char * const supportedSASLMechanisms[] = { + "supportedSASLMechanisms", + NULL + }; + + rc = ldap_search_ext(li->ld, "", LDAP_SCOPE_BASE, "(objectclass=*)", + (char **) supportedSASLMechanisms, 0, + NULL, NULL, NULL, 0, &li->msgid); + if(rc == LDAP_SUCCESS) + oldap_state(data, OLDAP_MECHS); + else + result = oldap_map_error(rc, CURLE_LOGIN_DENIED); + return result; +} + +/* Starts SASL bind. */ +static CURLcode oldap_perform_sasl(struct Curl_easy *data) +{ + saslprogress progress = SASL_IDLE; + struct ldapconninfo *li = data->conn->proto.ldapc; + CURLcode result = Curl_sasl_start(&li->sasl, data, TRUE, &progress); + + oldap_state(data, OLDAP_SASL); + if(!result && progress != SASL_INPROGRESS) + result = CURLE_LOGIN_DENIED; + return result; +} + +#ifdef USE_SSL +static Sockbuf_IO ldapsb_tls; + +static bool ssl_installed(struct connectdata *conn) +{ + return conn->proto.ldapc->recv != NULL; +} + +static CURLcode oldap_ssl_connect(struct Curl_easy *data, ldapstate newstate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct ldapconninfo *li = conn->proto.ldapc; + bool ssldone = 0; + + result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &ssldone); + if(!result) { + oldap_state(data, newstate); + + if(ssldone) { + Sockbuf *sb; + + /* Install the libcurl SSL handlers into the sockbuf. */ + ldap_get_option(li->ld, LDAP_OPT_SOCKBUF, &sb); + ber_sockbuf_add_io(sb, &ldapsb_tls, LBER_SBIOD_LEVEL_TRANSPORT, data); + li->recv = conn->recv[FIRSTSOCKET]; + li->send = conn->send[FIRSTSOCKET]; + } + } + + return result; +} + +/* Send the STARTTLS request */ +static CURLcode oldap_perform_starttls(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct ldapconninfo *li = data->conn->proto.ldapc; + int rc = ldap_start_tls(li->ld, NULL, NULL, &li->msgid); + + if(rc == LDAP_SUCCESS) + oldap_state(data, OLDAP_STARTTLS); + else + result = oldap_map_error(rc, CURLE_USE_SSL_FAILED); + return result; +} +#endif + +static CURLcode oldap_connect(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li; + static const int version = LDAP_VERSION3; + int rc; + char *hosturl; +#ifdef CURL_OPENLDAP_DEBUG + static int do_trace = -1; +#endif + + (void)done; + + DEBUGASSERT(!conn->proto.ldapc); + li = calloc(1, sizeof(struct ldapconninfo)); + if(!li) + return CURLE_OUT_OF_MEMORY; + else { + CURLcode result; + li->proto = ldap_pvt_url_scheme2proto(data->state.up.scheme); + conn->proto.ldapc = li; + + /* Initialize the SASL storage */ + Curl_sasl_init(&li->sasl, data, &saslldap); + + /* Clear the TLS upgraded flag */ + conn->bits.tls_upgraded = FALSE; + + result = oldap_parse_login_options(conn); + if(result) + return result; + } + + hosturl = aprintf("%s://%s%s%s:%d", + conn->handler->scheme, + conn->bits.ipv6_ip? "[": "", + conn->host.name, + conn->bits.ipv6_ip? "]": "", + conn->remote_port); + if(!hosturl) + return CURLE_OUT_OF_MEMORY; + + rc = ldap_init_fd(conn->sock[FIRSTSOCKET], li->proto, hosturl, &li->ld); + if(rc) { + failf(data, "LDAP local: Cannot connect to %s, %s", + hosturl, ldap_err2string(rc)); + free(hosturl); + return CURLE_COULDNT_CONNECT; + } + + free(hosturl); + +#ifdef CURL_OPENLDAP_DEBUG + if(do_trace < 0) { + const char *env = getenv("CURL_OPENLDAP_TRACE"); + do_trace = (env && strtol(env, NULL, 10) > 0); + } + if(do_trace) + ldap_set_option(li->ld, LDAP_OPT_DEBUG_LEVEL, &do_trace); +#endif + + /* Try version 3 first. */ + ldap_set_option(li->ld, LDAP_OPT_PROTOCOL_VERSION, &version); + + /* Do not chase referrals. */ + ldap_set_option(li->ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF); + +#ifdef USE_SSL + if(conn->handler->flags & PROTOPT_SSL) + return oldap_ssl_connect(data, OLDAP_SSL); + + if(data->set.use_ssl) { + CURLcode result = oldap_perform_starttls(data); + + if(!result || data->set.use_ssl != CURLUSESSL_TRY) + return result; + } +#endif + + if(li->sasl.prefmech != SASL_AUTH_NONE) + return oldap_perform_mechs(data); + + /* Force bind even if anonymous bind is not needed in protocol version 3 + to detect missing version 3 support. */ + return oldap_perform_bind(data, OLDAP_BIND); +} + +/* Handle the supported SASL mechanisms query response */ +static CURLcode oldap_state_mechs_resp(struct Curl_easy *data, + LDAPMessage *msg, int code) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li = conn->proto.ldapc; + int rc; + BerElement *ber = NULL; + CURLcode result = CURLE_OK; + struct berval bv, *bvals; + + switch(ldap_msgtype(msg)) { + case LDAP_RES_SEARCH_ENTRY: + /* Got a list of supported SASL mechanisms. */ + if(code != LDAP_SUCCESS && code != LDAP_NO_RESULTS_RETURNED) + return CURLE_LOGIN_DENIED; + + rc = ldap_get_dn_ber(li->ld, msg, &ber, &bv); + if(rc < 0) + return oldap_map_error(rc, CURLE_BAD_CONTENT_ENCODING); + for(rc = ldap_get_attribute_ber(li->ld, msg, ber, &bv, &bvals); + rc == LDAP_SUCCESS; + rc = ldap_get_attribute_ber(li->ld, msg, ber, &bv, &bvals)) { + int i; + + if(!bv.bv_val) + break; + + if(bvals) { + for(i = 0; bvals[i].bv_val; i++) { + size_t llen; + unsigned short mech = Curl_sasl_decode_mech((char *) bvals[i].bv_val, + bvals[i].bv_len, &llen); + if(bvals[i].bv_len == llen) + li->sasl.authmechs |= mech; + } + ber_memfree(bvals); + } + } + ber_free(ber, 0); + break; + + case LDAP_RES_SEARCH_RESULT: + switch(code) { + case LDAP_SIZELIMIT_EXCEEDED: + infof(data, "Too many authentication mechanisms\n"); + FALLTHROUGH(); + case LDAP_SUCCESS: + case LDAP_NO_RESULTS_RETURNED: + if(Curl_sasl_can_authenticate(&li->sasl, data)) + result = oldap_perform_sasl(data); + else + result = CURLE_LOGIN_DENIED; + break; + default: + result = oldap_map_error(code, CURLE_LOGIN_DENIED); + break; + } + break; + default: + break; + } + return result; +} + +/* Handle a SASL bind response. */ +static CURLcode oldap_state_sasl_resp(struct Curl_easy *data, + LDAPMessage *msg, int code) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li = conn->proto.ldapc; + CURLcode result = CURLE_OK; + saslprogress progress; + int rc; + + li->servercred = NULL; + rc = ldap_parse_sasl_bind_result(li->ld, msg, &li->servercred, 0); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: sasl ldap_parse_result %s", ldap_err2string(rc)); + result = oldap_map_error(rc, CURLE_LOGIN_DENIED); + } + else { + result = Curl_sasl_continue(&li->sasl, data, code, &progress); + if(!result && progress != SASL_INPROGRESS) + oldap_state(data, OLDAP_STOP); + } + + if(li->servercred) + ber_bvfree(li->servercred); + return result; +} + +/* Handle a simple bind response. */ +static CURLcode oldap_state_bind_resp(struct Curl_easy *data, LDAPMessage *msg, + int code) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li = conn->proto.ldapc; + CURLcode result = CURLE_OK; + struct berval *bv = NULL; + int rc; + + if(code != LDAP_SUCCESS) + return oldap_map_error(code, CURLE_LDAP_CANNOT_BIND); + + rc = ldap_parse_sasl_bind_result(li->ld, msg, &bv, 0); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: bind ldap_parse_sasl_bind_result %s", + ldap_err2string(rc)); + result = oldap_map_error(rc, CURLE_LDAP_CANNOT_BIND); + } + else + oldap_state(data, OLDAP_STOP); + + if(bv) + ber_bvfree(bv); + return result; +} + +static CURLcode oldap_connecting(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct ldapconninfo *li = conn->proto.ldapc; + LDAPMessage *msg = NULL; + struct timeval tv = {0, 0}; + int code = LDAP_SUCCESS; + int rc; + + if(li->state != OLDAP_SSL && li->state != OLDAP_TLS) { + /* Get response to last command. */ + rc = ldap_result(li->ld, li->msgid, LDAP_MSG_ONE, &tv, &msg); + switch(rc) { + case 0: /* Timed out. */ + return CURLE_OK; + case LDAP_RES_SEARCH_ENTRY: + case LDAP_RES_SEARCH_REFERENCE: + break; + default: + li->msgid = 0; /* Nothing to abandon upon error. */ + if(rc < 0) { + failf(data, "LDAP local: connecting ldap_result %s", + ldap_err2string(rc)); + return oldap_map_error(rc, CURLE_COULDNT_CONNECT); + } + break; + } + + /* Get error code from message. */ + rc = ldap_parse_result(li->ld, msg, &code, NULL, NULL, NULL, NULL, 0); + if(rc) + code = rc; + else { + /* store the latest code for later retrieval */ + data->info.httpcode = code; + } + + /* If protocol version 3 is not supported, fallback to version 2. */ + if(code == LDAP_PROTOCOL_ERROR && li->state != OLDAP_BINDV2 && +#ifdef USE_SSL + (ssl_installed(conn) || data->set.use_ssl <= CURLUSESSL_TRY) && +#endif + li->sasl.prefmech == SASL_AUTH_NONE) { + static const int version = LDAP_VERSION2; + + ldap_set_option(li->ld, LDAP_OPT_PROTOCOL_VERSION, &version); + ldap_msgfree(msg); + return oldap_perform_bind(data, OLDAP_BINDV2); + } + } + + /* Handle response message according to current state. */ + switch(li->state) { + +#ifdef USE_SSL + case OLDAP_SSL: + result = oldap_ssl_connect(data, OLDAP_SSL); + if(!result && ssl_installed(conn)) { + if(li->sasl.prefmech != SASL_AUTH_NONE) + result = oldap_perform_mechs(data); + else + result = oldap_perform_bind(data, OLDAP_BIND); + } + break; + case OLDAP_STARTTLS: + if(code != LDAP_SUCCESS) { + if(data->set.use_ssl != CURLUSESSL_TRY) + result = oldap_map_error(code, CURLE_USE_SSL_FAILED); + else if(li->sasl.prefmech != SASL_AUTH_NONE) + result = oldap_perform_mechs(data); + else + result = oldap_perform_bind(data, OLDAP_BIND); + break; + } + result = Curl_ssl_cfilter_add(data, conn, FIRSTSOCKET); + if(result) + break; + FALLTHROUGH(); + case OLDAP_TLS: + result = oldap_ssl_connect(data, OLDAP_TLS); + if(result) + result = oldap_map_error(code, CURLE_USE_SSL_FAILED); + else if(ssl_installed(conn)) { + conn->bits.tls_upgraded = TRUE; + if(li->sasl.prefmech != SASL_AUTH_NONE) + result = oldap_perform_mechs(data); + else if(data->state.aptr.user) + result = oldap_perform_bind(data, OLDAP_BIND); + else { + /* Version 3 supported: no bind required */ + oldap_state(data, OLDAP_STOP); + result = CURLE_OK; + } + } + break; +#endif + + case OLDAP_MECHS: + result = oldap_state_mechs_resp(data, msg, code); + break; + case OLDAP_SASL: + result = oldap_state_sasl_resp(data, msg, code); + break; + case OLDAP_BIND: + case OLDAP_BINDV2: + result = oldap_state_bind_resp(data, msg, code); + break; + default: + /* internal error */ + result = CURLE_COULDNT_CONNECT; + break; + } + + ldap_msgfree(msg); + + *done = li->state == OLDAP_STOP; + if(*done) + conn->recv[FIRSTSOCKET] = oldap_recv; + + if(result && li->msgid) { + ldap_abandon_ext(li->ld, li->msgid, NULL, NULL); + li->msgid = 0; + } + return result; +} + +static CURLcode oldap_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + struct ldapconninfo *li = conn->proto.ldapc; + (void) dead_connection; +#ifndef USE_SSL + (void)data; +#endif + + if(li) { + if(li->ld) { +#ifdef USE_SSL + if(ssl_installed(conn)) { + Sockbuf *sb; + ldap_get_option(li->ld, LDAP_OPT_SOCKBUF, &sb); + ber_sockbuf_add_io(sb, &ldapsb_tls, LBER_SBIOD_LEVEL_TRANSPORT, data); + } +#endif + ldap_unbind_ext(li->ld, NULL, NULL); + li->ld = NULL; + } + Curl_sasl_cleanup(conn, li->sasl.authused); + conn->proto.ldapc = NULL; + free(li); + } + return CURLE_OK; +} + +static CURLcode oldap_do(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li = conn->proto.ldapc; + struct ldapreqinfo *lr; + CURLcode result; + int rc; + LDAPURLDesc *lud; + int msgid; + + connkeep(conn, "OpenLDAP do"); + + infof(data, "LDAP local: %s", data->state.url); + + result = oldap_url_parse(data, &lud); + if(!result) { +#ifdef USE_SSL + if(ssl_installed(conn)) { + Sockbuf *sb; + /* re-install the libcurl SSL handlers into the sockbuf. */ + ldap_get_option(li->ld, LDAP_OPT_SOCKBUF, &sb); + ber_sockbuf_add_io(sb, &ldapsb_tls, LBER_SBIOD_LEVEL_TRANSPORT, data); + } +#endif + + rc = ldap_search_ext(li->ld, lud->lud_dn, lud->lud_scope, + lud->lud_filter, lud->lud_attrs, 0, + NULL, NULL, NULL, 0, &msgid); + ldap_free_urldesc(lud); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ldap_search_ext %s", ldap_err2string(rc)); + result = CURLE_LDAP_SEARCH_FAILED; + } + else { + lr = calloc(1, sizeof(struct ldapreqinfo)); + if(!lr) { + ldap_abandon_ext(li->ld, msgid, NULL, NULL); + result = CURLE_OUT_OF_MEMORY; + } + else { + lr->msgid = msgid; + data->req.p.ldap = lr; + Curl_xfer_setup(data, FIRSTSOCKET, -1, FALSE, -1); + *done = TRUE; + } + } + } + return result; +} + +static CURLcode oldap_done(struct Curl_easy *data, CURLcode res, + bool premature) +{ + struct connectdata *conn = data->conn; + struct ldapreqinfo *lr = data->req.p.ldap; + + (void)res; + (void)premature; + + if(lr) { + /* if there was a search in progress, abandon it */ + if(lr->msgid) { + struct ldapconninfo *li = conn->proto.ldapc; + ldap_abandon_ext(li->ld, lr->msgid, NULL, NULL); + lr->msgid = 0; + } + data->req.p.ldap = NULL; + free(lr); + } + + return CURLE_OK; +} + +static CURLcode client_write(struct Curl_easy *data, + const char *prefix, size_t plen, + const char *value, size_t len, + const char *suffix, size_t slen) +{ + CURLcode result = CURLE_OK; + + if(prefix) { + /* If we have a zero-length value and the prefix ends with a space + separator, drop the latter. */ + if(!len && plen && prefix[plen - 1] == ' ') + plen--; + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *) prefix, plen); + } + if(!result && value) { + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *) value, len); + } + if(!result && suffix) { + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *) suffix, slen); + } + return result; +} + +static ssize_t oldap_recv(struct Curl_easy *data, int sockindex, char *buf, + size_t len, CURLcode *err) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li = conn->proto.ldapc; + struct ldapreqinfo *lr = data->req.p.ldap; + int rc; + LDAPMessage *msg = NULL; + BerElement *ber = NULL; + struct timeval tv = {0, 0}; + struct berval bv, *bvals; + int binary = 0; + CURLcode result = CURLE_AGAIN; + int code; + char *info = NULL; + + (void)len; + (void)buf; + (void)sockindex; + + rc = ldap_result(li->ld, lr->msgid, LDAP_MSG_ONE, &tv, &msg); + if(rc < 0) { + failf(data, "LDAP local: search ldap_result %s", ldap_err2string(rc)); + result = CURLE_RECV_ERROR; + } + + *err = result; + + /* error or timed out */ + if(!msg) + return -1; + + result = CURLE_OK; + + switch(ldap_msgtype(msg)) { + case LDAP_RES_SEARCH_RESULT: + lr->msgid = 0; + rc = ldap_parse_result(li->ld, msg, &code, NULL, &info, NULL, NULL, 0); + if(rc) { + failf(data, "LDAP local: search ldap_parse_result %s", + ldap_err2string(rc)); + result = CURLE_LDAP_SEARCH_FAILED; + break; + } + + /* store the latest code for later retrieval */ + data->info.httpcode = code; + + switch(code) { + case LDAP_SIZELIMIT_EXCEEDED: + infof(data, "There are more than %d entries", lr->nument); + FALLTHROUGH(); + case LDAP_SUCCESS: + data->req.size = data->req.bytecount; + break; + default: + failf(data, "LDAP remote: search failed %s %s", ldap_err2string(code), + info ? info : ""); + result = CURLE_LDAP_SEARCH_FAILED; + break; + } + if(info) + ldap_memfree(info); + break; + case LDAP_RES_SEARCH_ENTRY: + lr->nument++; + rc = ldap_get_dn_ber(li->ld, msg, &ber, &bv); + if(rc < 0) { + result = CURLE_RECV_ERROR; + break; + } + + result = client_write(data, STRCONST("DN: "), bv.bv_val, bv.bv_len, + STRCONST("\n")); + if(result) + break; + + for(rc = ldap_get_attribute_ber(li->ld, msg, ber, &bv, &bvals); + rc == LDAP_SUCCESS; + rc = ldap_get_attribute_ber(li->ld, msg, ber, &bv, &bvals)) { + int i; + + if(!bv.bv_val) + break; + + if(!bvals) { + result = client_write(data, STRCONST("\t"), bv.bv_val, bv.bv_len, + STRCONST(":\n")); + if(result) + break; + continue; + } + + binary = bv.bv_len > 7 && + !strncmp(bv.bv_val + bv.bv_len - 7, ";binary", 7); + + for(i = 0; bvals[i].bv_val != NULL; i++) { + int binval = 0; + + result = client_write(data, STRCONST("\t"), bv.bv_val, bv.bv_len, + STRCONST(":")); + if(result) + break; + + if(!binary) { + /* check for leading or trailing whitespace */ + if(ISBLANK(bvals[i].bv_val[0]) || + ISBLANK(bvals[i].bv_val[bvals[i].bv_len - 1])) + binval = 1; + else { + /* check for unprintable characters */ + unsigned int j; + for(j = 0; j < bvals[i].bv_len; j++) + if(!ISPRINT(bvals[i].bv_val[j])) { + binval = 1; + break; + } + } + } + if(binary || binval) { + char *val_b64 = NULL; + size_t val_b64_sz = 0; + + /* Binary value, encode to base64. */ + if(bvals[i].bv_len) + result = Curl_base64_encode(bvals[i].bv_val, bvals[i].bv_len, + &val_b64, &val_b64_sz); + if(!result) + result = client_write(data, STRCONST(": "), val_b64, val_b64_sz, + STRCONST("\n")); + free(val_b64); + } + else + result = client_write(data, STRCONST(" "), + bvals[i].bv_val, bvals[i].bv_len, + STRCONST("\n")); + if(result) + break; + } + + ber_memfree(bvals); + bvals = NULL; + if(!result) + result = client_write(data, STRCONST("\n"), NULL, 0, NULL, 0); + if(result) + break; + } + + ber_free(ber, 0); + + if(!result) + result = client_write(data, STRCONST("\n"), NULL, 0, NULL, 0); + if(!result) + result = CURLE_AGAIN; + break; + } + + ldap_msgfree(msg); + *err = result; + return result? -1: 0; +} + +#ifdef USE_SSL +static int +ldapsb_tls_setup(Sockbuf_IO_Desc *sbiod, void *arg) +{ + sbiod->sbiod_pvt = arg; + return 0; +} + +static int +ldapsb_tls_remove(Sockbuf_IO_Desc *sbiod) +{ + sbiod->sbiod_pvt = NULL; + return 0; +} + +/* We don't need to do anything because libcurl does it already */ +static int +ldapsb_tls_close(Sockbuf_IO_Desc *sbiod) +{ + (void)sbiod; + return 0; +} + +static int +ldapsb_tls_ctrl(Sockbuf_IO_Desc *sbiod, int opt, void *arg) +{ + (void)arg; + if(opt == LBER_SB_OPT_DATA_READY) { + struct Curl_easy *data = sbiod->sbiod_pvt; + return Curl_conn_data_pending(data, FIRSTSOCKET); + } + return 0; +} + +static ber_slen_t +ldapsb_tls_read(Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len) +{ + struct Curl_easy *data = sbiod->sbiod_pvt; + ber_slen_t ret = 0; + if(data) { + struct connectdata *conn = data->conn; + if(conn) { + struct ldapconninfo *li = conn->proto.ldapc; + CURLcode err = CURLE_RECV_ERROR; + + ret = (li->recv)(data, FIRSTSOCKET, buf, len, &err); + if(ret < 0 && err == CURLE_AGAIN) { + SET_SOCKERRNO(EWOULDBLOCK); + } + } + } + return ret; +} + +static ber_slen_t +ldapsb_tls_write(Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len) +{ + struct Curl_easy *data = sbiod->sbiod_pvt; + ber_slen_t ret = 0; + if(data) { + struct connectdata *conn = data->conn; + if(conn) { + struct ldapconninfo *li = conn->proto.ldapc; + CURLcode err = CURLE_SEND_ERROR; + ret = (li->send)(data, FIRSTSOCKET, buf, len, &err); + if(ret < 0 && err == CURLE_AGAIN) { + SET_SOCKERRNO(EWOULDBLOCK); + } + } + } + return ret; +} + +static Sockbuf_IO ldapsb_tls = +{ + ldapsb_tls_setup, + ldapsb_tls_remove, + ldapsb_tls_ctrl, + ldapsb_tls_read, + ldapsb_tls_write, + ldapsb_tls_close +}; +#endif /* USE_SSL */ + +#endif /* !CURL_DISABLE_LDAP && USE_OPENLDAP */ diff --git a/third_party/curl/lib/parsedate.c b/third_party/curl/lib/parsedate.c new file mode 100644 index 0000000..1a7195b --- /dev/null +++ b/third_party/curl/lib/parsedate.c @@ -0,0 +1,644 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + A brief summary of the date string formats this parser groks: + + RFC 2616 3.3.1 + + Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 + Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036 + Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format + + we support dates without week day name: + + 06 Nov 1994 08:49:37 GMT + 06-Nov-94 08:49:37 GMT + Nov 6 08:49:37 1994 + + without the time zone: + + 06 Nov 1994 08:49:37 + 06-Nov-94 08:49:37 + + weird order: + + 1994 Nov 6 08:49:37 (GNU date fails) + GMT 08:49:37 06-Nov-94 Sunday + 94 6 Nov 08:49:37 (GNU date fails) + + time left out: + + 1994 Nov 6 + 06-Nov-94 + Sun Nov 6 94 + + unusual separators: + + 1994.Nov.6 + Sun/Nov/6/94/GMT + + commonly used time zone names: + + Sun, 06 Nov 1994 08:49:37 CET + 06 Nov 1994 08:49:37 EST + + time zones specified using RFC822 style: + + Sun, 12 Sep 2004 15:05:58 -0700 + Sat, 11 Sep 2004 21:32:11 +0200 + + compact numerical date strings: + + 20040912 15:05:58 -0700 + 20040911 +0200 + +*/ + +#include "curl_setup.h" + +#include + +#include +#include "strcase.h" +#include "warnless.h" +#include "parsedate.h" + +/* + * parsedate() + * + * Returns: + * + * PARSEDATE_OK - a fine conversion + * PARSEDATE_FAIL - failed to convert + * PARSEDATE_LATER - time overflow at the far end of time_t + * PARSEDATE_SOONER - time underflow at the low end of time_t + */ + +static int parsedate(const char *date, time_t *output); + +#define PARSEDATE_OK 0 +#define PARSEDATE_FAIL -1 +#define PARSEDATE_LATER 1 +#define PARSEDATE_SOONER 2 + +#if !defined(CURL_DISABLE_PARSEDATE) || !defined(CURL_DISABLE_FTP) || \ + !defined(CURL_DISABLE_FILE) +/* These names are also used by FTP and FILE code */ +const char * const Curl_wkday[] = +{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}; +const char * const Curl_month[]= +{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; +#endif + +#ifndef CURL_DISABLE_PARSEDATE +static const char * const weekday[] = +{ "Monday", "Tuesday", "Wednesday", "Thursday", + "Friday", "Saturday", "Sunday" }; + +struct tzinfo { + char name[5]; + int offset; /* +/- in minutes */ +}; + +/* Here's a bunch of frequently used time zone names. These were supported + by the old getdate parser. */ +#define tDAYZONE -60 /* offset for daylight savings time */ +static const struct tzinfo tz[]= { + {"GMT", 0}, /* Greenwich Mean */ + {"UT", 0}, /* Universal Time */ + {"UTC", 0}, /* Universal (Coordinated) */ + {"WET", 0}, /* Western European */ + {"BST", 0 tDAYZONE}, /* British Summer */ + {"WAT", 60}, /* West Africa */ + {"AST", 240}, /* Atlantic Standard */ + {"ADT", 240 tDAYZONE}, /* Atlantic Daylight */ + {"EST", 300}, /* Eastern Standard */ + {"EDT", 300 tDAYZONE}, /* Eastern Daylight */ + {"CST", 360}, /* Central Standard */ + {"CDT", 360 tDAYZONE}, /* Central Daylight */ + {"MST", 420}, /* Mountain Standard */ + {"MDT", 420 tDAYZONE}, /* Mountain Daylight */ + {"PST", 480}, /* Pacific Standard */ + {"PDT", 480 tDAYZONE}, /* Pacific Daylight */ + {"YST", 540}, /* Yukon Standard */ + {"YDT", 540 tDAYZONE}, /* Yukon Daylight */ + {"HST", 600}, /* Hawaii Standard */ + {"HDT", 600 tDAYZONE}, /* Hawaii Daylight */ + {"CAT", 600}, /* Central Alaska */ + {"AHST", 600}, /* Alaska-Hawaii Standard */ + {"NT", 660}, /* Nome */ + {"IDLW", 720}, /* International Date Line West */ + {"CET", -60}, /* Central European */ + {"MET", -60}, /* Middle European */ + {"MEWT", -60}, /* Middle European Winter */ + {"MEST", -60 tDAYZONE}, /* Middle European Summer */ + {"CEST", -60 tDAYZONE}, /* Central European Summer */ + {"MESZ", -60 tDAYZONE}, /* Middle European Summer */ + {"FWT", -60}, /* French Winter */ + {"FST", -60 tDAYZONE}, /* French Summer */ + {"EET", -120}, /* Eastern Europe, USSR Zone 1 */ + {"WAST", -420}, /* West Australian Standard */ + {"WADT", -420 tDAYZONE}, /* West Australian Daylight */ + {"CCT", -480}, /* China Coast, USSR Zone 7 */ + {"JST", -540}, /* Japan Standard, USSR Zone 8 */ + {"EAST", -600}, /* Eastern Australian Standard */ + {"EADT", -600 tDAYZONE}, /* Eastern Australian Daylight */ + {"GST", -600}, /* Guam Standard, USSR Zone 9 */ + {"NZT", -720}, /* New Zealand */ + {"NZST", -720}, /* New Zealand Standard */ + {"NZDT", -720 tDAYZONE}, /* New Zealand Daylight */ + {"IDLE", -720}, /* International Date Line East */ + /* Next up: Military timezone names. RFC822 allowed these, but (as noted in + RFC 1123) had their signs wrong. Here we use the correct signs to match + actual military usage. + */ + {"A", 1 * 60}, /* Alpha */ + {"B", 2 * 60}, /* Bravo */ + {"C", 3 * 60}, /* Charlie */ + {"D", 4 * 60}, /* Delta */ + {"E", 5 * 60}, /* Echo */ + {"F", 6 * 60}, /* Foxtrot */ + {"G", 7 * 60}, /* Golf */ + {"H", 8 * 60}, /* Hotel */ + {"I", 9 * 60}, /* India */ + /* "J", Juliet is not used as a timezone, to indicate the observer's local + time */ + {"K", 10 * 60}, /* Kilo */ + {"L", 11 * 60}, /* Lima */ + {"M", 12 * 60}, /* Mike */ + {"N", -1 * 60}, /* November */ + {"O", -2 * 60}, /* Oscar */ + {"P", -3 * 60}, /* Papa */ + {"Q", -4 * 60}, /* Quebec */ + {"R", -5 * 60}, /* Romeo */ + {"S", -6 * 60}, /* Sierra */ + {"T", -7 * 60}, /* Tango */ + {"U", -8 * 60}, /* Uniform */ + {"V", -9 * 60}, /* Victor */ + {"W", -10 * 60}, /* Whiskey */ + {"X", -11 * 60}, /* X-ray */ + {"Y", -12 * 60}, /* Yankee */ + {"Z", 0}, /* Zulu, zero meridian, a.k.a. UTC */ +}; + +/* returns: + -1 no day + 0 monday - 6 sunday +*/ + +static int checkday(const char *check, size_t len) +{ + int i; + const char * const *what; + if(len > 3) + what = &weekday[0]; + else if(len == 3) + what = &Curl_wkday[0]; + else + return -1; /* too short */ + for(i = 0; i<7; i++) { + size_t ilen = strlen(what[0]); + if((ilen == len) && + strncasecompare(check, what[0], len)) + return i; + what++; + } + return -1; +} + +static int checkmonth(const char *check, size_t len) +{ + int i; + const char * const *what = &Curl_month[0]; + if(len != 3) + return -1; /* not a month */ + + for(i = 0; i<12; i++) { + if(strncasecompare(check, what[0], 3)) + return i; + what++; + } + return -1; /* return the offset or -1, no real offset is -1 */ +} + +/* return the time zone offset between GMT and the input one, in number + of seconds or -1 if the timezone wasn't found/legal */ + +static int checktz(const char *check, size_t len) +{ + unsigned int i; + const struct tzinfo *what = tz; + if(len > 4) /* longer than any valid timezone */ + return -1; + + for(i = 0; i< sizeof(tz)/sizeof(tz[0]); i++) { + size_t ilen = strlen(what->name); + if((ilen == len) && + strncasecompare(check, what->name, len)) + return what->offset*60; + what++; + } + return -1; +} + +static void skip(const char **date) +{ + /* skip everything that aren't letters or digits */ + while(**date && !ISALNUM(**date)) + (*date)++; +} + +enum assume { + DATE_MDAY, + DATE_YEAR, + DATE_TIME +}; + +/* + * time2epoch: time stamp to seconds since epoch in GMT time zone. Similar to + * mktime but for GMT only. + */ +static time_t time2epoch(int sec, int min, int hour, + int mday, int mon, int year) +{ + static const int month_days_cumulative [12] = + { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; + int leap_days = year - (mon <= 1); + leap_days = ((leap_days / 4) - (leap_days / 100) + (leap_days / 400) + - (1969 / 4) + (1969 / 100) - (1969 / 400)); + return ((((time_t) (year - 1970) * 365 + + leap_days + month_days_cumulative[mon] + mday - 1) * 24 + + hour) * 60 + min) * 60 + sec; +} + +/* Returns the value of a single-digit or two-digit decimal number, return + then pointer to after the number. The 'date' pointer is known to point to a + digit. */ +static int oneortwodigit(const char *date, const char **endp) +{ + int num = date[0] - '0'; + if(ISDIGIT(date[1])) { + *endp = &date[2]; + return num*10 + (date[1] - '0'); + } + *endp = &date[1]; + return num; +} + + +/* HH:MM:SS or HH:MM and accept single-digits too */ +static bool match_time(const char *date, + int *h, int *m, int *s, char **endp) +{ + const char *p; + int hh, mm, ss = 0; + hh = oneortwodigit(date, &p); + if((hh < 24) && (*p == ':') && ISDIGIT(p[1])) { + mm = oneortwodigit(&p[1], &p); + if(mm < 60) { + if((*p == ':') && ISDIGIT(p[1])) { + ss = oneortwodigit(&p[1], &p); + if(ss <= 60) { + /* valid HH:MM:SS */ + goto match; + } + } + else { + /* valid HH:MM */ + goto match; + } + } + } + return FALSE; /* not a time string */ +match: + *h = hh; + *m = mm; + *s = ss; + *endp = (char *)p; + return TRUE; +} + +/* + * parsedate() + * + * Returns: + * + * PARSEDATE_OK - a fine conversion + * PARSEDATE_FAIL - failed to convert + * PARSEDATE_LATER - time overflow at the far end of time_t + * PARSEDATE_SOONER - time underflow at the low end of time_t + */ + +/* Wednesday is the longest name this parser knows about */ +#define NAME_LEN 12 + +static int parsedate(const char *date, time_t *output) +{ + time_t t = 0; + int wdaynum = -1; /* day of the week number, 0-6 (mon-sun) */ + int monnum = -1; /* month of the year number, 0-11 */ + int mdaynum = -1; /* day of month, 1 - 31 */ + int hournum = -1; + int minnum = -1; + int secnum = -1; + int yearnum = -1; + int tzoff = -1; + enum assume dignext = DATE_MDAY; + const char *indate = date; /* save the original pointer */ + int part = 0; /* max 6 parts */ + + while(*date && (part < 6)) { + bool found = FALSE; + + skip(&date); + + if(ISALPHA(*date)) { + /* a name coming up */ + size_t len = 0; + const char *p = date; + while(ISALPHA(*p) && (len < NAME_LEN)) { + p++; + len++; + } + + if(len != NAME_LEN) { + if(wdaynum == -1) { + wdaynum = checkday(date, len); + if(wdaynum != -1) + found = TRUE; + } + if(!found && (monnum == -1)) { + monnum = checkmonth(date, len); + if(monnum != -1) + found = TRUE; + } + + if(!found && (tzoff == -1)) { + /* this just must be a time zone string */ + tzoff = checktz(date, len); + if(tzoff != -1) + found = TRUE; + } + } + if(!found) + return PARSEDATE_FAIL; /* bad string */ + + date += len; + } + else if(ISDIGIT(*date)) { + /* a digit */ + int val; + char *end; + if((secnum == -1) && + match_time(date, &hournum, &minnum, &secnum, &end)) { + /* time stamp */ + date = end; + } + else { + long lval; + int error; + int old_errno; + + old_errno = errno; + errno = 0; + lval = strtol(date, &end, 10); + error = errno; + if(errno != old_errno) + errno = old_errno; + + if(error) + return PARSEDATE_FAIL; + +#if LONG_MAX != INT_MAX + if((lval > (long)INT_MAX) || (lval < (long)INT_MIN)) + return PARSEDATE_FAIL; +#endif + + val = curlx_sltosi(lval); + + if((tzoff == -1) && + ((end - date) == 4) && + (val <= 1400) && + (indate< date) && + ((date[-1] == '+' || date[-1] == '-'))) { + /* four digits and a value less than or equal to 1400 (to take into + account all sorts of funny time zone diffs) and it is preceded + with a plus or minus. This is a time zone indication. 1400 is + picked since +1300 is frequently used and +1400 is mentioned as + an edge number in the document "ISO C 200X Proposal: Timezone + Functions" at http://david.tribble.com/text/c0xtimezone.html If + anyone has a more authoritative source for the exact maximum time + zone offsets, please speak up! */ + found = TRUE; + tzoff = (val/100 * 60 + val%100)*60; + + /* the + and - prefix indicates the local time compared to GMT, + this we need their reversed math to get what we want */ + tzoff = date[-1]=='+'?-tzoff:tzoff; + } + + if(((end - date) == 8) && + (yearnum == -1) && + (monnum == -1) && + (mdaynum == -1)) { + /* 8 digits, no year, month or day yet. This is YYYYMMDD */ + found = TRUE; + yearnum = val/10000; + monnum = (val%10000)/100-1; /* month is 0 - 11 */ + mdaynum = val%100; + } + + if(!found && (dignext == DATE_MDAY) && (mdaynum == -1)) { + if((val > 0) && (val<32)) { + mdaynum = val; + found = TRUE; + } + dignext = DATE_YEAR; + } + + if(!found && (dignext == DATE_YEAR) && (yearnum == -1)) { + yearnum = val; + found = TRUE; + if(yearnum < 100) { + if(yearnum > 70) + yearnum += 1900; + else + yearnum += 2000; + } + if(mdaynum == -1) + dignext = DATE_MDAY; + } + + if(!found) + return PARSEDATE_FAIL; + + date = end; + } + } + + part++; + } + + if(-1 == secnum) + secnum = minnum = hournum = 0; /* no time, make it zero */ + + if((-1 == mdaynum) || + (-1 == monnum) || + (-1 == yearnum)) + /* lacks vital info, fail */ + return PARSEDATE_FAIL; + +#ifdef HAVE_TIME_T_UNSIGNED + if(yearnum < 1970) { + /* only positive numbers cannot return earlier */ + *output = TIME_T_MIN; + return PARSEDATE_SOONER; + } +#endif + +#if (SIZEOF_TIME_T < 5) + +#ifdef HAVE_TIME_T_UNSIGNED + /* an unsigned 32 bit time_t can only hold dates to 2106 */ + if(yearnum > 2105) { + *output = TIME_T_MAX; + return PARSEDATE_LATER; + } +#else + /* a signed 32 bit time_t can only hold dates to the beginning of 2038 */ + if(yearnum > 2037) { + *output = TIME_T_MAX; + return PARSEDATE_LATER; + } + if(yearnum < 1903) { + *output = TIME_T_MIN; + return PARSEDATE_SOONER; + } +#endif + +#else + /* The Gregorian calendar was introduced 1582 */ + if(yearnum < 1583) + return PARSEDATE_FAIL; +#endif + + if((mdaynum > 31) || (monnum > 11) || + (hournum > 23) || (minnum > 59) || (secnum > 60)) + return PARSEDATE_FAIL; /* clearly an illegal date */ + + /* time2epoch() returns a time_t. time_t is often 32 bits, sometimes even on + architectures that feature 64 bit 'long' but ultimately time_t is the + correct data type to use. + */ + t = time2epoch(secnum, minnum, hournum, mdaynum, monnum, yearnum); + + /* Add the time zone diff between local time zone and GMT. */ + if(tzoff == -1) + tzoff = 0; + + if((tzoff > 0) && (t > TIME_T_MAX - tzoff)) { + *output = TIME_T_MAX; + return PARSEDATE_LATER; /* time_t overflow */ + } + + t += tzoff; + + *output = t; + + return PARSEDATE_OK; +} +#else +/* disabled */ +static int parsedate(const char *date, time_t *output) +{ + (void)date; + *output = 0; + return PARSEDATE_OK; /* a lie */ +} +#endif + +time_t curl_getdate(const char *p, const time_t *now) +{ + time_t parsed = -1; + int rc = parsedate(p, &parsed); + (void)now; /* legacy argument from the past that we ignore */ + + if(rc == PARSEDATE_OK) { + if(parsed == -1) + /* avoid returning -1 for a working scenario */ + parsed++; + return parsed; + } + /* everything else is fail */ + return -1; +} + +/* Curl_getdate_capped() differs from curl_getdate() in that this will return + TIME_T_MAX in case the parsed time value was too big, instead of an + error. */ + +time_t Curl_getdate_capped(const char *p) +{ + time_t parsed = -1; + int rc = parsedate(p, &parsed); + + switch(rc) { + case PARSEDATE_OK: + if(parsed == -1) + /* avoid returning -1 for a working scenario */ + parsed++; + return parsed; + case PARSEDATE_LATER: + /* this returns the maximum time value */ + return parsed; + default: + return -1; /* everything else is fail */ + } + /* UNREACHABLE */ +} + +/* + * Curl_gmtime() is a gmtime() replacement for portability. Do not use the + * gmtime_r() or gmtime() functions anywhere else but here. + * + */ + +CURLcode Curl_gmtime(time_t intime, struct tm *store) +{ + const struct tm *tm; +#ifdef HAVE_GMTIME_R + /* thread-safe version */ + tm = (struct tm *)gmtime_r(&intime, store); +#else + /* !checksrc! disable BANNEDFUNC 1 */ + tm = gmtime(&intime); + if(tm) + *store = *tm; /* copy the pointed struct to the local copy */ +#endif + + if(!tm) + return CURLE_BAD_FUNCTION_ARGUMENT; + return CURLE_OK; +} diff --git a/third_party/curl/lib/parsedate.h b/third_party/curl/lib/parsedate.h new file mode 100644 index 0000000..84c37f1 --- /dev/null +++ b/third_party/curl/lib/parsedate.h @@ -0,0 +1,38 @@ +#ifndef HEADER_CURL_PARSEDATE_H +#define HEADER_CURL_PARSEDATE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +extern const char * const Curl_wkday[7]; +extern const char * const Curl_month[12]; + +CURLcode Curl_gmtime(time_t intime, struct tm *store); + +/* Curl_getdate_capped() differs from curl_getdate() in that this will return + TIME_T_MAX in case the parsed time value was too big, instead of an + error. */ + +time_t Curl_getdate_capped(const char *p); + +#endif /* HEADER_CURL_PARSEDATE_H */ diff --git a/third_party/curl/lib/pingpong.c b/third_party/curl/lib/pingpong.c new file mode 100644 index 0000000..81576c0 --- /dev/null +++ b/third_party/curl/lib/pingpong.c @@ -0,0 +1,438 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * 'pingpong' is for generic back-and-forth support functions used by FTP, + * IMAP, POP3, SMTP and whatever more that likes them. + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "urldata.h" +#include "cfilters.h" +#include "sendf.h" +#include "select.h" +#include "progress.h" +#include "speedcheck.h" +#include "pingpong.h" +#include "multiif.h" +#include "vtls/vtls.h" +#include "strdup.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#ifdef USE_PINGPONG + +/* Returns timeout in ms. 0 or negative number means the timeout has already + triggered */ +timediff_t Curl_pp_state_timeout(struct Curl_easy *data, + struct pingpong *pp, bool disconnecting) +{ + struct connectdata *conn = data->conn; + timediff_t timeout_ms; /* in milliseconds */ + timediff_t response_time = (data->set.server_response_timeout)? + data->set.server_response_timeout: pp->response_time; + + /* if CURLOPT_SERVER_RESPONSE_TIMEOUT is set, use that to determine + remaining time, or use pp->response because SERVER_RESPONSE_TIMEOUT is + supposed to govern the response for any given server response, not for + the time from connect to the given server response. */ + + /* Without a requested timeout, we only wait 'response_time' seconds for the + full response to arrive before we bail out */ + timeout_ms = response_time - + Curl_timediff(Curl_now(), pp->response); /* spent time */ + + if(data->set.timeout && !disconnecting) { + /* if timeout is requested, find out how much remaining time we have */ + timediff_t timeout2_ms = data->set.timeout - /* timeout time */ + Curl_timediff(Curl_now(), conn->now); /* spent time */ + + /* pick the lowest number */ + timeout_ms = CURLMIN(timeout_ms, timeout2_ms); + } + + return timeout_ms; +} + +/* + * Curl_pp_statemach() + */ +CURLcode Curl_pp_statemach(struct Curl_easy *data, + struct pingpong *pp, bool block, + bool disconnecting) +{ + struct connectdata *conn = data->conn; + curl_socket_t sock = conn->sock[FIRSTSOCKET]; + int rc; + timediff_t interval_ms; + timediff_t timeout_ms = Curl_pp_state_timeout(data, pp, disconnecting); + CURLcode result = CURLE_OK; + + if(timeout_ms <= 0) { + failf(data, "server response timeout"); + return CURLE_OPERATION_TIMEDOUT; /* already too little time */ + } + + if(block) { + interval_ms = 1000; /* use 1 second timeout intervals */ + if(timeout_ms < interval_ms) + interval_ms = timeout_ms; + } + else + interval_ms = 0; /* immediate */ + + if(Curl_conn_data_pending(data, FIRSTSOCKET)) + rc = 1; + else if(pp->overflow) + /* We are receiving and there is data in the cache so just read it */ + rc = 1; + else if(!pp->sendleft && Curl_conn_data_pending(data, FIRSTSOCKET)) + /* We are receiving and there is data ready in the SSL library */ + rc = 1; + else + rc = Curl_socket_check(pp->sendleft?CURL_SOCKET_BAD:sock, /* reading */ + CURL_SOCKET_BAD, + pp->sendleft?sock:CURL_SOCKET_BAD, /* writing */ + interval_ms); + + if(block) { + /* if we didn't wait, we don't have to spend time on this now */ + if(Curl_pgrsUpdate(data)) + result = CURLE_ABORTED_BY_CALLBACK; + else + result = Curl_speedcheck(data, Curl_now()); + + if(result) + return result; + } + + if(rc == -1) { + failf(data, "select/poll error"); + result = CURLE_OUT_OF_MEMORY; + } + else if(rc) + result = pp->statemachine(data, data->conn); + + return result; +} + +/* initialize stuff to prepare for reading a fresh new response */ +void Curl_pp_init(struct pingpong *pp) +{ + pp->nread_resp = 0; + pp->response = Curl_now(); /* start response time-out now! */ + pp->pending_resp = TRUE; + Curl_dyn_init(&pp->sendbuf, DYN_PINGPPONG_CMD); + Curl_dyn_init(&pp->recvbuf, DYN_PINGPPONG_CMD); +} + +/*********************************************************************** + * + * Curl_pp_vsendf() + * + * Send the formatted string as a command to a pingpong server. Note that + * the string should not have any CRLF appended, as this function will + * append the necessary things itself. + * + * made to never block + */ +CURLcode Curl_pp_vsendf(struct Curl_easy *data, + struct pingpong *pp, + const char *fmt, + va_list args) +{ + size_t bytes_written = 0; + size_t write_len; + char *s; + CURLcode result; + struct connectdata *conn = data->conn; + +#ifdef HAVE_GSSAPI + enum protection_level data_sec; +#endif + + DEBUGASSERT(pp->sendleft == 0); + DEBUGASSERT(pp->sendsize == 0); + DEBUGASSERT(pp->sendthis == NULL); + + if(!conn) + /* can't send without a connection! */ + return CURLE_SEND_ERROR; + + Curl_dyn_reset(&pp->sendbuf); + result = Curl_dyn_vaddf(&pp->sendbuf, fmt, args); + if(result) + return result; + + /* append CRLF */ + result = Curl_dyn_addn(&pp->sendbuf, "\r\n", 2); + if(result) + return result; + + pp->pending_resp = TRUE; + write_len = Curl_dyn_len(&pp->sendbuf); + s = Curl_dyn_ptr(&pp->sendbuf); + +#ifdef HAVE_GSSAPI + conn->data_prot = PROT_CMD; +#endif + result = Curl_conn_send(data, FIRSTSOCKET, s, write_len, &bytes_written); + if(result == CURLE_AGAIN) { + bytes_written = 0; + } + else if(result) + return result; +#ifdef HAVE_GSSAPI + data_sec = conn->data_prot; + DEBUGASSERT(data_sec > PROT_NONE && data_sec < PROT_LAST); + conn->data_prot = (unsigned char)data_sec; +#endif + + Curl_debug(data, CURLINFO_HEADER_OUT, s, bytes_written); + + if(bytes_written != write_len) { + /* the whole chunk was not sent, keep it around and adjust sizes */ + pp->sendthis = s; + pp->sendsize = write_len; + pp->sendleft = write_len - bytes_written; + } + else { + pp->sendthis = NULL; + pp->sendleft = pp->sendsize = 0; + pp->response = Curl_now(); + } + + return CURLE_OK; +} + + +/*********************************************************************** + * + * Curl_pp_sendf() + * + * Send the formatted string as a command to a pingpong server. Note that + * the string should not have any CRLF appended, as this function will + * append the necessary things itself. + * + * made to never block + */ +CURLcode Curl_pp_sendf(struct Curl_easy *data, struct pingpong *pp, + const char *fmt, ...) +{ + CURLcode result; + va_list ap; + va_start(ap, fmt); + + result = Curl_pp_vsendf(data, pp, fmt, ap); + + va_end(ap); + + return result; +} + +static CURLcode pingpong_read(struct Curl_easy *data, + int sockindex, + char *buffer, + size_t buflen, + ssize_t *nread) +{ + CURLcode result; +#ifdef HAVE_GSSAPI + enum protection_level prot = data->conn->data_prot; + data->conn->data_prot = PROT_CLEAR; +#endif + result = Curl_conn_recv(data, sockindex, buffer, buflen, nread); +#ifdef HAVE_GSSAPI + DEBUGASSERT(prot > PROT_NONE && prot < PROT_LAST); + data->conn->data_prot = (unsigned char)prot; +#endif + return result; +} + +/* + * Curl_pp_readresp() + * + * Reads a piece of a server response. + */ +CURLcode Curl_pp_readresp(struct Curl_easy *data, + int sockindex, + struct pingpong *pp, + int *code, /* return the server code if done */ + size_t *size) /* size of the response */ +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + + *code = 0; /* 0 for errors or not done */ + *size = 0; + + if(pp->nfinal) { + /* a previous call left this many bytes in the beginning of the buffer as + that was the final line; now ditch that */ + size_t full = Curl_dyn_len(&pp->recvbuf); + + /* trim off the "final" leading part */ + Curl_dyn_tail(&pp->recvbuf, full - pp->nfinal); + + pp->nfinal = 0; /* now gone */ + } + if(!pp->overflow) { + ssize_t gotbytes = 0; + char buffer[900]; + + result = pingpong_read(data, sockindex, buffer, sizeof(buffer), &gotbytes); + if(result == CURLE_AGAIN) + return CURLE_OK; + + if(result) + return result; + + if(gotbytes <= 0) { + failf(data, "response reading failed (errno: %d)", SOCKERRNO); + return CURLE_RECV_ERROR; + } + + result = Curl_dyn_addn(&pp->recvbuf, buffer, gotbytes); + if(result) + return result; + + data->req.headerbytecount += (unsigned int)gotbytes; + + pp->nread_resp += gotbytes; + } + + do { + char *line = Curl_dyn_ptr(&pp->recvbuf); + char *nl = memchr(line, '\n', Curl_dyn_len(&pp->recvbuf)); + if(nl) { + /* a newline is CRLF in pp-talk, so the CR is ignored as + the line isn't really terminated until the LF comes */ + size_t length = nl - line + 1; + + /* output debug output if that is requested */ +#ifdef HAVE_GSSAPI + if(!conn->sec_complete) +#endif + Curl_debug(data, CURLINFO_HEADER_IN, line, length); + + /* + * Pass all response-lines to the callback function registered for + * "headers". The response lines can be seen as a kind of headers. + */ + result = Curl_client_write(data, CLIENTWRITE_INFO, line, length); + if(result) + return result; + + if(pp->endofresp(data, conn, line, length, code)) { + /* When at "end of response", keep the endofresp line first in the + buffer since it will be accessed outside (by pingpong + parsers). Store the overflow counter to inform about additional + data in this buffer after the endofresp line. */ + pp->nfinal = length; + if(Curl_dyn_len(&pp->recvbuf) > length) + pp->overflow = Curl_dyn_len(&pp->recvbuf) - length; + else + pp->overflow = 0; + *size = pp->nread_resp; /* size of the response */ + pp->nread_resp = 0; /* restart */ + break; + } + if(Curl_dyn_len(&pp->recvbuf) > length) + /* keep the remaining piece */ + Curl_dyn_tail((&pp->recvbuf), Curl_dyn_len(&pp->recvbuf) - length); + else + Curl_dyn_reset(&pp->recvbuf); + } + else { + /* without a newline, there is no overflow */ + pp->overflow = 0; + break; + } + + } while(1); /* while there's buffer left to scan */ + + pp->pending_resp = FALSE; + + return result; +} + +int Curl_pp_getsock(struct Curl_easy *data, + struct pingpong *pp, curl_socket_t *socks) +{ + struct connectdata *conn = data->conn; + socks[0] = conn->sock[FIRSTSOCKET]; + + if(pp->sendleft) { + /* write mode */ + return GETSOCK_WRITESOCK(0); + } + + /* read mode */ + return GETSOCK_READSOCK(0); +} + +CURLcode Curl_pp_flushsend(struct Curl_easy *data, + struct pingpong *pp) +{ + /* we have a piece of a command still left to send */ + size_t written; + CURLcode result; + + result = Curl_conn_send(data, FIRSTSOCKET, + pp->sendthis + pp->sendsize - pp->sendleft, + pp->sendleft, &written); + if(result == CURLE_AGAIN) { + result = CURLE_OK; + written = 0; + } + if(result) + return result; + + if(written != pp->sendleft) { + /* only a fraction was sent */ + pp->sendleft -= written; + } + else { + pp->sendthis = NULL; + pp->sendleft = pp->sendsize = 0; + pp->response = Curl_now(); + } + return CURLE_OK; +} + +CURLcode Curl_pp_disconnect(struct pingpong *pp) +{ + Curl_dyn_free(&pp->sendbuf); + Curl_dyn_free(&pp->recvbuf); + return CURLE_OK; +} + +bool Curl_pp_moredata(struct pingpong *pp) +{ + return (!pp->sendleft && Curl_dyn_len(&pp->recvbuf) > pp->nfinal); +} + +#endif diff --git a/third_party/curl/lib/pingpong.h b/third_party/curl/lib/pingpong.h new file mode 100644 index 0000000..28172c7 --- /dev/null +++ b/third_party/curl/lib/pingpong.h @@ -0,0 +1,160 @@ +#ifndef HEADER_CURL_PINGPONG_H +#define HEADER_CURL_PINGPONG_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_FTP) || \ + !defined(CURL_DISABLE_POP3) || !defined(CURL_DISABLE_SMTP) +#define USE_PINGPONG +#endif + +/* forward-declaration, this is defined in urldata.h */ +struct connectdata; + +typedef enum { + PPTRANSFER_BODY, /* yes do transfer a body */ + PPTRANSFER_INFO, /* do still go through to get info/headers */ + PPTRANSFER_NONE /* don't get anything and don't get info */ +} curl_pp_transfer; + +/* + * 'pingpong' is the generic struct used for protocols doing server<->client + * conversations in a back-and-forth style such as FTP, IMAP, POP3, SMTP etc. + * + * It holds response cache and non-blocking sending data. + */ +struct pingpong { + size_t nread_resp; /* number of bytes currently read of a server response */ + bool pending_resp; /* set TRUE when a server response is pending or in + progress, and is cleared once the last response is + read */ + char *sendthis; /* pointer to a buffer that is to be sent to the server */ + size_t sendleft; /* number of bytes left to send from the sendthis buffer */ + size_t sendsize; /* total size of the sendthis buffer */ + struct curltime response; /* set to Curl_now() when a command has been sent + off, used to time-out response reading */ + timediff_t response_time; /* When no timeout is given, this is the amount of + milliseconds we await for a server response. */ + struct dynbuf sendbuf; + struct dynbuf recvbuf; + size_t overflow; /* number of bytes left after a final response line */ + size_t nfinal; /* number of bytes in the final response line, which + after a match is first in the receice buffer */ + + /* Function pointers the protocols MUST implement and provide for the + pingpong layer to function */ + + CURLcode (*statemachine)(struct Curl_easy *data, struct connectdata *conn); + bool (*endofresp)(struct Curl_easy *data, struct connectdata *conn, + char *ptr, size_t len, int *code); +}; + +#define PINGPONG_SETUP(pp,s,e) \ + do { \ + pp->response_time = RESP_TIMEOUT; \ + pp->statemachine = s; \ + pp->endofresp = e; \ + } while(0) + +/* + * Curl_pp_statemach() + * + * called repeatedly until done. Set 'wait' to make it wait a while on the + * socket if there's no traffic. + */ +CURLcode Curl_pp_statemach(struct Curl_easy *data, struct pingpong *pp, + bool block, bool disconnecting); + +/* initialize stuff to prepare for reading a fresh new response */ +void Curl_pp_init(struct pingpong *pp); + +/* Returns timeout in ms. 0 or negative number means the timeout has already + triggered */ +timediff_t Curl_pp_state_timeout(struct Curl_easy *data, + struct pingpong *pp, bool disconnecting); + + +/*********************************************************************** + * + * Curl_pp_sendf() + * + * Send the formatted string as a command to a pingpong server. Note that + * the string should not have any CRLF appended, as this function will + * append the necessary things itself. + * + * made to never block + */ +CURLcode Curl_pp_sendf(struct Curl_easy *data, + struct pingpong *pp, + const char *fmt, ...) CURL_PRINTF(3, 4); + +/*********************************************************************** + * + * Curl_pp_vsendf() + * + * Send the formatted string as a command to a pingpong server. Note that + * the string should not have any CRLF appended, as this function will + * append the necessary things itself. + * + * made to never block + */ +CURLcode Curl_pp_vsendf(struct Curl_easy *data, + struct pingpong *pp, + const char *fmt, + va_list args) CURL_PRINTF(3, 0); + +/* + * Curl_pp_readresp() + * + * Reads a piece of a server response. + */ +CURLcode Curl_pp_readresp(struct Curl_easy *data, + int sockindex, + struct pingpong *pp, + int *code, /* return the server code if done */ + size_t *size); /* size of the response */ + + +CURLcode Curl_pp_flushsend(struct Curl_easy *data, + struct pingpong *pp); + +/* call this when a pingpong connection is disconnected */ +CURLcode Curl_pp_disconnect(struct pingpong *pp); + +int Curl_pp_getsock(struct Curl_easy *data, struct pingpong *pp, + curl_socket_t *socks); + + +/*********************************************************************** + * + * Curl_pp_moredata() + * + * Returns whether there are still more data in the cache and so a call + * to Curl_pp_readresp() will not block. + */ +bool Curl_pp_moredata(struct pingpong *pp); + +#endif /* HEADER_CURL_PINGPONG_H */ diff --git a/third_party/curl/lib/pop3.c b/third_party/curl/lib/pop3.c new file mode 100644 index 0000000..9a30331 --- /dev/null +++ b/third_party/curl/lib/pop3.c @@ -0,0 +1,1584 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * RFC1734 POP3 Authentication + * RFC1939 POP3 protocol + * RFC2195 CRAM-MD5 authentication + * RFC2384 POP URL Scheme + * RFC2449 POP3 Extension Mechanism + * RFC2595 Using TLS with IMAP, POP3 and ACAP + * RFC2831 DIGEST-MD5 authentication + * RFC4422 Simple Authentication and Security Layer (SASL) + * RFC4616 PLAIN authentication + * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism + * RFC5034 POP3 SASL Authentication Mechanism + * RFC6749 OAuth 2.0 Authorization Framework + * RFC8314 Use of TLS for Email Submission and Access + * Draft LOGIN SASL Mechanism + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_POP3 + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef __VMS +#include +#include +#endif + +#include +#include "urldata.h" +#include "sendf.h" +#include "hostip.h" +#include "progress.h" +#include "transfer.h" +#include "escape.h" +#include "http.h" /* for HTTP proxy tunnel stuff */ +#include "socks.h" +#include "pop3.h" +#include "strtoofft.h" +#include "strcase.h" +#include "vtls/vtls.h" +#include "cfilters.h" +#include "connect.h" +#include "select.h" +#include "multiif.h" +#include "url.h" +#include "bufref.h" +#include "curl_sasl.h" +#include "curl_md5.h" +#include "warnless.h" +#include "strdup.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* Local API functions */ +static CURLcode pop3_regular_transfer(struct Curl_easy *data, bool *done); +static CURLcode pop3_do(struct Curl_easy *data, bool *done); +static CURLcode pop3_done(struct Curl_easy *data, CURLcode status, + bool premature); +static CURLcode pop3_connect(struct Curl_easy *data, bool *done); +static CURLcode pop3_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead); +static CURLcode pop3_multi_statemach(struct Curl_easy *data, bool *done); +static int pop3_getsock(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *socks); +static CURLcode pop3_doing(struct Curl_easy *data, bool *dophase_done); +static CURLcode pop3_setup_connection(struct Curl_easy *data, + struct connectdata *conn); +static CURLcode pop3_parse_url_options(struct connectdata *conn); +static CURLcode pop3_parse_url_path(struct Curl_easy *data); +static CURLcode pop3_parse_custom_request(struct Curl_easy *data); +static CURLcode pop3_perform_auth(struct Curl_easy *data, const char *mech, + const struct bufref *initresp); +static CURLcode pop3_continue_auth(struct Curl_easy *data, const char *mech, + const struct bufref *resp); +static CURLcode pop3_cancel_auth(struct Curl_easy *data, const char *mech); +static CURLcode pop3_get_message(struct Curl_easy *data, struct bufref *out); + +/* + * POP3 protocol handler. + */ + +const struct Curl_handler Curl_handler_pop3 = { + "pop3", /* scheme */ + pop3_setup_connection, /* setup_connection */ + pop3_do, /* do_it */ + pop3_done, /* done */ + ZERO_NULL, /* do_more */ + pop3_connect, /* connect_it */ + pop3_multi_statemach, /* connecting */ + pop3_doing, /* doing */ + pop3_getsock, /* proto_getsock */ + pop3_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + pop3_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_POP3, /* defport */ + CURLPROTO_POP3, /* protocol */ + CURLPROTO_POP3, /* family */ + PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY | /* flags */ + PROTOPT_URLOPTIONS +}; + +#ifdef USE_SSL +/* + * POP3S protocol handler. + */ + +const struct Curl_handler Curl_handler_pop3s = { + "pop3s", /* scheme */ + pop3_setup_connection, /* setup_connection */ + pop3_do, /* do_it */ + pop3_done, /* done */ + ZERO_NULL, /* do_more */ + pop3_connect, /* connect_it */ + pop3_multi_statemach, /* connecting */ + pop3_doing, /* doing */ + pop3_getsock, /* proto_getsock */ + pop3_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + pop3_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_POP3S, /* defport */ + CURLPROTO_POP3S, /* protocol */ + CURLPROTO_POP3, /* family */ + PROTOPT_CLOSEACTION | PROTOPT_SSL + | PROTOPT_NOURLQUERY | PROTOPT_URLOPTIONS /* flags */ +}; +#endif + +/* SASL parameters for the pop3 protocol */ +static const struct SASLproto saslpop3 = { + "pop", /* The service name */ + pop3_perform_auth, /* Send authentication command */ + pop3_continue_auth, /* Send authentication continuation */ + pop3_cancel_auth, /* Send authentication cancellation */ + pop3_get_message, /* Get SASL response message */ + 255 - 8, /* Max line len - strlen("AUTH ") - 1 space - crlf */ + '*', /* Code received when continuation is expected */ + '+', /* Code to receive upon authentication success */ + SASL_AUTH_DEFAULT, /* Default mechanisms */ + SASL_FLAG_BASE64 /* Configuration flags */ +}; + +#ifdef USE_SSL +static void pop3_to_pop3s(struct connectdata *conn) +{ + /* Change the connection handler */ + conn->handler = &Curl_handler_pop3s; + + /* Set the connection's upgraded to TLS flag */ + conn->bits.tls_upgraded = TRUE; +} +#else +#define pop3_to_pop3s(x) Curl_nop_stmt +#endif + +/*********************************************************************** + * + * pop3_endofresp() + * + * Checks for an ending POP3 status code at the start of the given string, but + * also detects the APOP timestamp from the server greeting and various + * capabilities from the CAPA response including the supported authentication + * types and allowed SASL mechanisms. + */ +static bool pop3_endofresp(struct Curl_easy *data, struct connectdata *conn, + char *line, size_t len, int *resp) +{ + struct pop3_conn *pop3c = &conn->proto.pop3c; + (void)data; + + /* Do we have an error response? */ + if(len >= 4 && !memcmp("-ERR", line, 4)) { + *resp = '-'; + + return TRUE; + } + + /* Are we processing CAPA command responses? */ + if(pop3c->state == POP3_CAPA) { + /* Do we have the terminating line? */ + if(len >= 1 && line[0] == '.') + /* Treat the response as a success */ + *resp = '+'; + else + /* Treat the response as an untagged continuation */ + *resp = '*'; + + return TRUE; + } + + /* Do we have a success response? */ + if(len >= 3 && !memcmp("+OK", line, 3)) { + *resp = '+'; + + return TRUE; + } + + /* Do we have a continuation response? */ + if(len >= 1 && line[0] == '+') { + *resp = '*'; + + return TRUE; + } + + return FALSE; /* Nothing for us */ +} + +/*********************************************************************** + * + * pop3_get_message() + * + * Gets the authentication message from the response buffer. + */ +static CURLcode pop3_get_message(struct Curl_easy *data, struct bufref *out) +{ + char *message = Curl_dyn_ptr(&data->conn->proto.pop3c.pp.recvbuf); + size_t len = data->conn->proto.pop3c.pp.nfinal; + + if(len > 2) { + /* Find the start of the message */ + len -= 2; + for(message += 2; *message == ' ' || *message == '\t'; message++, len--) + ; + + /* Find the end of the message */ + while(len--) + if(message[len] != '\r' && message[len] != '\n' && message[len] != ' ' && + message[len] != '\t') + break; + + /* Terminate the message */ + message[++len] = '\0'; + Curl_bufref_set(out, message, len, NULL); + } + else + /* junk input => zero length output */ + Curl_bufref_set(out, "", 0, NULL); + + return CURLE_OK; +} + +/*********************************************************************** + * + * pop3_state() + * + * This is the ONLY way to change POP3 state! + */ +static void pop3_state(struct Curl_easy *data, pop3state newstate) +{ + struct pop3_conn *pop3c = &data->conn->proto.pop3c; +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + /* for debug purposes */ + static const char * const names[] = { + "STOP", + "SERVERGREET", + "CAPA", + "STARTTLS", + "UPGRADETLS", + "AUTH", + "APOP", + "USER", + "PASS", + "COMMAND", + "QUIT", + /* LAST */ + }; + + if(pop3c->state != newstate) + infof(data, "POP3 %p state change from %s to %s", + (void *)pop3c, names[pop3c->state], names[newstate]); +#endif + + pop3c->state = newstate; +} + +/*********************************************************************** + * + * pop3_perform_capa() + * + * Sends the CAPA command in order to obtain a list of server side supported + * capabilities. + */ +static CURLcode pop3_perform_capa(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + struct pop3_conn *pop3c = &conn->proto.pop3c; + + pop3c->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanisms yet */ + pop3c->sasl.authused = SASL_AUTH_NONE; /* Clear the auth. mechanism used */ + pop3c->tls_supported = FALSE; /* Clear the TLS capability */ + + /* Send the CAPA command */ + result = Curl_pp_sendf(data, &pop3c->pp, "%s", "CAPA"); + + if(!result) + pop3_state(data, POP3_CAPA); + + return result; +} + +/*********************************************************************** + * + * pop3_perform_starttls() + * + * Sends the STLS command to start the upgrade to TLS. + */ +static CURLcode pop3_perform_starttls(struct Curl_easy *data, + struct connectdata *conn) +{ + /* Send the STLS command */ + CURLcode result = Curl_pp_sendf(data, &conn->proto.pop3c.pp, "%s", "STLS"); + + if(!result) + pop3_state(data, POP3_STARTTLS); + + return result; +} + +/*********************************************************************** + * + * pop3_perform_upgrade_tls() + * + * Performs the upgrade to TLS. + */ +static CURLcode pop3_perform_upgrade_tls(struct Curl_easy *data, + struct connectdata *conn) +{ + /* Start the SSL connection */ + struct pop3_conn *pop3c = &conn->proto.pop3c; + CURLcode result; + bool ssldone = FALSE; + + if(!Curl_conn_is_ssl(conn, FIRSTSOCKET)) { + result = Curl_ssl_cfilter_add(data, conn, FIRSTSOCKET); + if(result) + goto out; + } + + result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &ssldone); + + if(!result) { + pop3c->ssldone = ssldone; + if(pop3c->state != POP3_UPGRADETLS) + pop3_state(data, POP3_UPGRADETLS); + + if(pop3c->ssldone) { + pop3_to_pop3s(conn); + result = pop3_perform_capa(data, conn); + } + } +out: + return result; +} + +/*********************************************************************** + * + * pop3_perform_user() + * + * Sends a clear text USER command to authenticate with. + */ +static CURLcode pop3_perform_user(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + + /* Check we have a username and password to authenticate with and end the + connect phase if we don't */ + if(!data->state.aptr.user) { + pop3_state(data, POP3_STOP); + + return result; + } + + /* Send the USER command */ + result = Curl_pp_sendf(data, &conn->proto.pop3c.pp, "USER %s", + conn->user ? conn->user : ""); + if(!result) + pop3_state(data, POP3_USER); + + return result; +} + +#ifndef CURL_DISABLE_DIGEST_AUTH +/*********************************************************************** + * + * pop3_perform_apop() + * + * Sends an APOP command to authenticate with. + */ +static CURLcode pop3_perform_apop(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + struct pop3_conn *pop3c = &conn->proto.pop3c; + size_t i; + struct MD5_context *ctxt; + unsigned char digest[MD5_DIGEST_LEN]; + char secret[2 * MD5_DIGEST_LEN + 1]; + + /* Check we have a username and password to authenticate with and end the + connect phase if we don't */ + if(!data->state.aptr.user) { + pop3_state(data, POP3_STOP); + + return result; + } + + /* Create the digest */ + ctxt = Curl_MD5_init(Curl_DIGEST_MD5); + if(!ctxt) + return CURLE_OUT_OF_MEMORY; + + Curl_MD5_update(ctxt, (const unsigned char *) pop3c->apoptimestamp, + curlx_uztoui(strlen(pop3c->apoptimestamp))); + + Curl_MD5_update(ctxt, (const unsigned char *) conn->passwd, + curlx_uztoui(strlen(conn->passwd))); + + /* Finalise the digest */ + Curl_MD5_final(ctxt, digest); + + /* Convert the calculated 16 octet digest into a 32 byte hex string */ + for(i = 0; i < MD5_DIGEST_LEN; i++) + msnprintf(&secret[2 * i], 3, "%02x", digest[i]); + + result = Curl_pp_sendf(data, &pop3c->pp, "APOP %s %s", conn->user, secret); + + if(!result) + pop3_state(data, POP3_APOP); + + return result; +} +#endif + +/*********************************************************************** + * + * pop3_perform_auth() + * + * Sends an AUTH command allowing the client to login with the given SASL + * authentication mechanism. + */ +static CURLcode pop3_perform_auth(struct Curl_easy *data, + const char *mech, + const struct bufref *initresp) +{ + CURLcode result = CURLE_OK; + struct pop3_conn *pop3c = &data->conn->proto.pop3c; + const char *ir = (const char *) Curl_bufref_ptr(initresp); + + if(ir) { /* AUTH ... */ + /* Send the AUTH command with the initial response */ + result = Curl_pp_sendf(data, &pop3c->pp, "AUTH %s %s", mech, ir); + } + else { + /* Send the AUTH command */ + result = Curl_pp_sendf(data, &pop3c->pp, "AUTH %s", mech); + } + + return result; +} + +/*********************************************************************** + * + * pop3_continue_auth() + * + * Sends SASL continuation data. + */ +static CURLcode pop3_continue_auth(struct Curl_easy *data, + const char *mech, + const struct bufref *resp) +{ + struct pop3_conn *pop3c = &data->conn->proto.pop3c; + + (void)mech; + + return Curl_pp_sendf(data, &pop3c->pp, + "%s", (const char *) Curl_bufref_ptr(resp)); +} + +/*********************************************************************** + * + * pop3_cancel_auth() + * + * Sends SASL cancellation. + */ +static CURLcode pop3_cancel_auth(struct Curl_easy *data, const char *mech) +{ + struct pop3_conn *pop3c = &data->conn->proto.pop3c; + + (void)mech; + + return Curl_pp_sendf(data, &pop3c->pp, "*"); +} + +/*********************************************************************** + * + * pop3_perform_authentication() + * + * Initiates the authentication sequence, with the appropriate SASL + * authentication mechanism, falling back to APOP and clear text should a + * common mechanism not be available between the client and server. + */ +static CURLcode pop3_perform_authentication(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + struct pop3_conn *pop3c = &conn->proto.pop3c; + saslprogress progress = SASL_IDLE; + + /* Check we have enough data to authenticate with and end the + connect phase if we don't */ + if(!Curl_sasl_can_authenticate(&pop3c->sasl, data)) { + pop3_state(data, POP3_STOP); + return result; + } + + if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_SASL) { + /* Calculate the SASL login details */ + result = Curl_sasl_start(&pop3c->sasl, data, FALSE, &progress); + + if(!result) + if(progress == SASL_INPROGRESS) + pop3_state(data, POP3_AUTH); + } + + if(!result && progress == SASL_IDLE) { +#ifndef CURL_DISABLE_DIGEST_AUTH + if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_APOP) + /* Perform APOP authentication */ + result = pop3_perform_apop(data, conn); + else +#endif + if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_CLEARTEXT) + /* Perform clear text authentication */ + result = pop3_perform_user(data, conn); + else { + /* Other mechanisms not supported */ + infof(data, "No known authentication mechanisms supported"); + result = CURLE_LOGIN_DENIED; + } + } + + return result; +} + +/*********************************************************************** + * + * pop3_perform_command() + * + * Sends a POP3 based command. + */ +static CURLcode pop3_perform_command(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct POP3 *pop3 = data->req.p.pop3; + const char *command = NULL; + + /* Calculate the default command */ + if(pop3->id[0] == '\0' || data->set.list_only) { + command = "LIST"; + + if(pop3->id[0] != '\0') + /* Message specific LIST so skip the BODY transfer */ + pop3->transfer = PPTRANSFER_INFO; + } + else + command = "RETR"; + + /* Send the command */ + if(pop3->id[0] != '\0') + result = Curl_pp_sendf(data, &conn->proto.pop3c.pp, "%s %s", + (pop3->custom && pop3->custom[0] != '\0' ? + pop3->custom : command), pop3->id); + else + result = Curl_pp_sendf(data, &conn->proto.pop3c.pp, "%s", + (pop3->custom && pop3->custom[0] != '\0' ? + pop3->custom : command)); + + if(!result) + pop3_state(data, POP3_COMMAND); + + return result; +} + +/*********************************************************************** + * + * pop3_perform_quit() + * + * Performs the quit action prior to sclose() be called. + */ +static CURLcode pop3_perform_quit(struct Curl_easy *data, + struct connectdata *conn) +{ + /* Send the QUIT command */ + CURLcode result = Curl_pp_sendf(data, &conn->proto.pop3c.pp, "%s", "QUIT"); + + if(!result) + pop3_state(data, POP3_QUIT); + + return result; +} + +/* For the initial server greeting */ +static CURLcode pop3_state_servergreet_resp(struct Curl_easy *data, + int pop3code, + pop3state instate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct pop3_conn *pop3c = &conn->proto.pop3c; + const char *line = Curl_dyn_ptr(&data->conn->proto.pop3c.pp.recvbuf); + size_t len = data->conn->proto.pop3c.pp.nfinal; + + (void)instate; /* no use for this yet */ + + if(pop3code != '+') { + failf(data, "Got unexpected pop3-server response"); + result = CURLE_WEIRD_SERVER_REPLY; + } + else if(len > 3) { + /* Does the server support APOP authentication? */ + char *lt; + char *gt = NULL; + + /* Look for the APOP timestamp */ + lt = memchr(line, '<', len); + if(lt) + /* search the remainder for '>' */ + gt = memchr(lt, '>', len - (lt - line)); + if(gt) { + /* the length of the timestamp, including the brackets */ + size_t timestamplen = gt - lt + 1; + char *at = memchr(lt, '@', timestamplen); + /* If the timestamp does not contain '@' it is not (as required by + RFC-1939) conformant to the RFC-822 message id syntax, and we + therefore do not use APOP authentication. */ + if(at) { + /* dupe the timestamp */ + pop3c->apoptimestamp = Curl_memdup0(lt, timestamplen); + if(!pop3c->apoptimestamp) + return CURLE_OUT_OF_MEMORY; + /* Store the APOP capability */ + pop3c->authtypes |= POP3_TYPE_APOP; + } + } + + if(!result) + result = pop3_perform_capa(data, conn); + } + + return result; +} + +/* For CAPA responses */ +static CURLcode pop3_state_capa_resp(struct Curl_easy *data, int pop3code, + pop3state instate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct pop3_conn *pop3c = &conn->proto.pop3c; + const char *line = Curl_dyn_ptr(&data->conn->proto.pop3c.pp.recvbuf); + size_t len = data->conn->proto.pop3c.pp.nfinal; + + (void)instate; /* no use for this yet */ + + /* Do we have a untagged continuation response? */ + if(pop3code == '*') { + /* Does the server support the STLS capability? */ + if(len >= 4 && !memcmp(line, "STLS", 4)) + pop3c->tls_supported = TRUE; + + /* Does the server support clear text authentication? */ + else if(len >= 4 && !memcmp(line, "USER", 4)) + pop3c->authtypes |= POP3_TYPE_CLEARTEXT; + + /* Does the server support SASL based authentication? */ + else if(len >= 5 && !memcmp(line, "SASL ", 5)) { + pop3c->authtypes |= POP3_TYPE_SASL; + + /* Advance past the SASL keyword */ + line += 5; + len -= 5; + + /* Loop through the data line */ + for(;;) { + size_t llen; + size_t wordlen; + unsigned short mechbit; + + while(len && + (*line == ' ' || *line == '\t' || + *line == '\r' || *line == '\n')) { + + line++; + len--; + } + + if(!len) + break; + + /* Extract the word */ + for(wordlen = 0; wordlen < len && line[wordlen] != ' ' && + line[wordlen] != '\t' && line[wordlen] != '\r' && + line[wordlen] != '\n';) + wordlen++; + + /* Test the word for a matching authentication mechanism */ + mechbit = Curl_sasl_decode_mech(line, wordlen, &llen); + if(mechbit && llen == wordlen) + pop3c->sasl.authmechs |= mechbit; + + line += wordlen; + len -= wordlen; + } + } + } + else { + /* Clear text is supported when CAPA isn't recognised */ + if(pop3code != '+') + pop3c->authtypes |= POP3_TYPE_CLEARTEXT; + + if(!data->set.use_ssl || Curl_conn_is_ssl(conn, FIRSTSOCKET)) + result = pop3_perform_authentication(data, conn); + else if(pop3code == '+' && pop3c->tls_supported) + /* Switch to TLS connection now */ + result = pop3_perform_starttls(data, conn); + else if(data->set.use_ssl <= CURLUSESSL_TRY) + /* Fallback and carry on with authentication */ + result = pop3_perform_authentication(data, conn); + else { + failf(data, "STLS not supported."); + result = CURLE_USE_SSL_FAILED; + } + } + + return result; +} + +/* For STARTTLS responses */ +static CURLcode pop3_state_starttls_resp(struct Curl_easy *data, + struct connectdata *conn, + int pop3code, + pop3state instate) +{ + CURLcode result = CURLE_OK; + (void)instate; /* no use for this yet */ + + /* Pipelining in response is forbidden. */ + if(data->conn->proto.pop3c.pp.overflow) + return CURLE_WEIRD_SERVER_REPLY; + + if(pop3code != '+') { + if(data->set.use_ssl != CURLUSESSL_TRY) { + failf(data, "STARTTLS denied"); + result = CURLE_USE_SSL_FAILED; + } + else + result = pop3_perform_authentication(data, conn); + } + else + result = pop3_perform_upgrade_tls(data, conn); + + return result; +} + +/* For SASL authentication responses */ +static CURLcode pop3_state_auth_resp(struct Curl_easy *data, + int pop3code, + pop3state instate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct pop3_conn *pop3c = &conn->proto.pop3c; + saslprogress progress; + + (void)instate; /* no use for this yet */ + + result = Curl_sasl_continue(&pop3c->sasl, data, pop3code, &progress); + if(!result) + switch(progress) { + case SASL_DONE: + pop3_state(data, POP3_STOP); /* Authenticated */ + break; + case SASL_IDLE: /* No mechanism left after cancellation */ +#ifndef CURL_DISABLE_DIGEST_AUTH + if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_APOP) + /* Perform APOP authentication */ + result = pop3_perform_apop(data, conn); + else +#endif + if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_CLEARTEXT) + /* Perform clear text authentication */ + result = pop3_perform_user(data, conn); + else { + failf(data, "Authentication cancelled"); + result = CURLE_LOGIN_DENIED; + } + break; + default: + break; + } + + return result; +} + +#ifndef CURL_DISABLE_DIGEST_AUTH +/* For APOP responses */ +static CURLcode pop3_state_apop_resp(struct Curl_easy *data, int pop3code, + pop3state instate) +{ + CURLcode result = CURLE_OK; + (void)instate; /* no use for this yet */ + + if(pop3code != '+') { + failf(data, "Authentication failed: %d", pop3code); + result = CURLE_LOGIN_DENIED; + } + else + /* End of connect phase */ + pop3_state(data, POP3_STOP); + + return result; +} +#endif + +/* For USER responses */ +static CURLcode pop3_state_user_resp(struct Curl_easy *data, int pop3code, + pop3state instate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + (void)instate; /* no use for this yet */ + + if(pop3code != '+') { + failf(data, "Access denied. %c", pop3code); + result = CURLE_LOGIN_DENIED; + } + else + /* Send the PASS command */ + result = Curl_pp_sendf(data, &conn->proto.pop3c.pp, "PASS %s", + conn->passwd ? conn->passwd : ""); + if(!result) + pop3_state(data, POP3_PASS); + + return result; +} + +/* For PASS responses */ +static CURLcode pop3_state_pass_resp(struct Curl_easy *data, int pop3code, + pop3state instate) +{ + CURLcode result = CURLE_OK; + (void)instate; /* no use for this yet */ + + if(pop3code != '+') { + failf(data, "Access denied. %c", pop3code); + result = CURLE_LOGIN_DENIED; + } + else + /* End of connect phase */ + pop3_state(data, POP3_STOP); + + return result; +} + +/* For command responses */ +static CURLcode pop3_state_command_resp(struct Curl_easy *data, + int pop3code, + pop3state instate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct POP3 *pop3 = data->req.p.pop3; + struct pop3_conn *pop3c = &conn->proto.pop3c; + struct pingpong *pp = &pop3c->pp; + + (void)instate; /* no use for this yet */ + + if(pop3code != '+') { + pop3_state(data, POP3_STOP); + return CURLE_WEIRD_SERVER_REPLY; + } + + /* This 'OK' line ends with a CR LF pair which is the two first bytes of the + EOB string so count this is two matching bytes. This is necessary to make + the code detect the EOB if the only data than comes now is %2e CR LF like + when there is no body to return. */ + pop3c->eob = 2; + + /* But since this initial CR LF pair is not part of the actual body, we set + the strip counter here so that these bytes won't be delivered. */ + pop3c->strip = 2; + + if(pop3->transfer == PPTRANSFER_BODY) { + /* POP3 download */ + Curl_xfer_setup(data, FIRSTSOCKET, -1, FALSE, -1); + + if(pp->overflow) { + /* The recv buffer contains data that is actually body content so send + it as such. Note that there may even be additional "headers" after + the body */ + + /* keep only the overflow */ + Curl_dyn_tail(&pp->recvbuf, pp->overflow); + pp->nfinal = 0; /* done */ + + if(!data->req.no_body) { + result = Curl_pop3_write(data, Curl_dyn_ptr(&pp->recvbuf), + Curl_dyn_len(&pp->recvbuf)); + if(result) + return result; + } + + /* reset the buffer */ + Curl_dyn_reset(&pp->recvbuf); + pp->overflow = 0; + } + } + else + pp->overflow = 0; + + /* End of DO phase */ + pop3_state(data, POP3_STOP); + + return result; +} + +static CURLcode pop3_statemachine(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + int pop3code; + struct pop3_conn *pop3c = &conn->proto.pop3c; + struct pingpong *pp = &pop3c->pp; + size_t nread = 0; + (void)data; + + /* Busy upgrading the connection; right now all I/O is SSL/TLS, not POP3 */ + if(pop3c->state == POP3_UPGRADETLS) + return pop3_perform_upgrade_tls(data, conn); + + /* Flush any data that needs to be sent */ + if(pp->sendleft) + return Curl_pp_flushsend(data, pp); + + do { + /* Read the response from the server */ + result = Curl_pp_readresp(data, FIRSTSOCKET, pp, &pop3code, &nread); + if(result) + return result; + + if(!pop3code) + break; + + /* We have now received a full POP3 server response */ + switch(pop3c->state) { + case POP3_SERVERGREET: + result = pop3_state_servergreet_resp(data, pop3code, pop3c->state); + break; + + case POP3_CAPA: + result = pop3_state_capa_resp(data, pop3code, pop3c->state); + break; + + case POP3_STARTTLS: + result = pop3_state_starttls_resp(data, conn, pop3code, pop3c->state); + break; + + case POP3_AUTH: + result = pop3_state_auth_resp(data, pop3code, pop3c->state); + break; + +#ifndef CURL_DISABLE_DIGEST_AUTH + case POP3_APOP: + result = pop3_state_apop_resp(data, pop3code, pop3c->state); + break; +#endif + + case POP3_USER: + result = pop3_state_user_resp(data, pop3code, pop3c->state); + break; + + case POP3_PASS: + result = pop3_state_pass_resp(data, pop3code, pop3c->state); + break; + + case POP3_COMMAND: + result = pop3_state_command_resp(data, pop3code, pop3c->state); + break; + + case POP3_QUIT: + pop3_state(data, POP3_STOP); + break; + + default: + /* internal error */ + pop3_state(data, POP3_STOP); + break; + } + } while(!result && pop3c->state != POP3_STOP && Curl_pp_moredata(pp)); + + return result; +} + +/* Called repeatedly until done from multi.c */ +static CURLcode pop3_multi_statemach(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct pop3_conn *pop3c = &conn->proto.pop3c; + + if((conn->handler->flags & PROTOPT_SSL) && !pop3c->ssldone) { + bool ssldone = FALSE; + result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &ssldone); + pop3c->ssldone = ssldone; + if(result || !pop3c->ssldone) + return result; + } + + result = Curl_pp_statemach(data, &pop3c->pp, FALSE, FALSE); + *done = (pop3c->state == POP3_STOP) ? TRUE : FALSE; + + return result; +} + +static CURLcode pop3_block_statemach(struct Curl_easy *data, + struct connectdata *conn, + bool disconnecting) +{ + CURLcode result = CURLE_OK; + struct pop3_conn *pop3c = &conn->proto.pop3c; + + while(pop3c->state != POP3_STOP && !result) + result = Curl_pp_statemach(data, &pop3c->pp, TRUE, disconnecting); + + return result; +} + +/* Allocate and initialize the POP3 struct for the current Curl_easy if + required */ +static CURLcode pop3_init(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct POP3 *pop3; + + pop3 = data->req.p.pop3 = calloc(1, sizeof(struct POP3)); + if(!pop3) + result = CURLE_OUT_OF_MEMORY; + + return result; +} + +/* For the POP3 "protocol connect" and "doing" phases only */ +static int pop3_getsock(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *socks) +{ + return Curl_pp_getsock(data, &conn->proto.pop3c.pp, socks); +} + +/*********************************************************************** + * + * pop3_connect() + * + * This function should do everything that is to be considered a part of the + * connection phase. + * + * The variable 'done' points to will be TRUE if the protocol-layer connect + * phase is done when this function returns, or FALSE if not. + */ +static CURLcode pop3_connect(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct pop3_conn *pop3c = &conn->proto.pop3c; + struct pingpong *pp = &pop3c->pp; + + *done = FALSE; /* default to not done yet */ + + /* We always support persistent connections in POP3 */ + connkeep(conn, "POP3 default"); + + PINGPONG_SETUP(pp, pop3_statemachine, pop3_endofresp); + + /* Set the default preferred authentication type and mechanism */ + pop3c->preftype = POP3_TYPE_ANY; + Curl_sasl_init(&pop3c->sasl, data, &saslpop3); + + /* Initialise the pingpong layer */ + Curl_pp_init(pp); + + /* Parse the URL options */ + result = pop3_parse_url_options(conn); + if(result) + return result; + + /* Start off waiting for the server greeting response */ + pop3_state(data, POP3_SERVERGREET); + + result = pop3_multi_statemach(data, done); + + return result; +} + +/*********************************************************************** + * + * pop3_done() + * + * The DONE function. This does what needs to be done after a single DO has + * performed. + * + * Input argument is already checked for validity. + */ +static CURLcode pop3_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + CURLcode result = CURLE_OK; + struct POP3 *pop3 = data->req.p.pop3; + + (void)premature; + + if(!pop3) + return CURLE_OK; + + if(status) { + connclose(data->conn, "POP3 done with bad status"); + result = status; /* use the already set error code */ + } + + /* Cleanup our per-request based variables */ + Curl_safefree(pop3->id); + Curl_safefree(pop3->custom); + + /* Clear the transfer mode for the next request */ + pop3->transfer = PPTRANSFER_BODY; + + return result; +} + +/*********************************************************************** + * + * pop3_perform() + * + * This is the actual DO function for POP3. Get a message/listing according to + * the options previously setup. + */ +static CURLcode pop3_perform(struct Curl_easy *data, bool *connected, + bool *dophase_done) +{ + /* This is POP3 and no proxy */ + CURLcode result = CURLE_OK; + struct POP3 *pop3 = data->req.p.pop3; + + DEBUGF(infof(data, "DO phase starts")); + + if(data->req.no_body) { + /* Requested no body means no transfer */ + pop3->transfer = PPTRANSFER_INFO; + } + + *dophase_done = FALSE; /* not done yet */ + + /* Start the first command in the DO phase */ + result = pop3_perform_command(data); + if(result) + return result; + + /* Run the state-machine */ + result = pop3_multi_statemach(data, dophase_done); + *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET); + + if(*dophase_done) + DEBUGF(infof(data, "DO phase is complete")); + + return result; +} + +/*********************************************************************** + * + * pop3_do() + * + * This function is registered as 'curl_do' function. It decodes the path + * parts etc as a wrapper to the actual DO function (pop3_perform). + * + * The input argument is already checked for validity. + */ +static CURLcode pop3_do(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + *done = FALSE; /* default to false */ + + /* Parse the URL path */ + result = pop3_parse_url_path(data); + if(result) + return result; + + /* Parse the custom request */ + result = pop3_parse_custom_request(data); + if(result) + return result; + + result = pop3_regular_transfer(data, done); + + return result; +} + +/*********************************************************************** + * + * pop3_disconnect() + * + * Disconnect from an POP3 server. Cleanup protocol-specific per-connection + * resources. BLOCKING. + */ +static CURLcode pop3_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead_connection) +{ + struct pop3_conn *pop3c = &conn->proto.pop3c; + (void)data; + + /* We cannot send quit unconditionally. If this connection is stale or + bad in any way, sending quit and waiting around here will make the + disconnect wait in vain and cause more problems than we need to. */ + + if(!dead_connection && conn->bits.protoconnstart) { + if(!pop3_perform_quit(data, conn)) + (void)pop3_block_statemach(data, conn, TRUE); /* ignore errors on QUIT */ + } + + /* Disconnect from the server */ + Curl_pp_disconnect(&pop3c->pp); + + /* Cleanup the SASL module */ + Curl_sasl_cleanup(conn, pop3c->sasl.authused); + + /* Cleanup our connection based variables */ + Curl_safefree(pop3c->apoptimestamp); + + return CURLE_OK; +} + +/* Call this when the DO phase has completed */ +static CURLcode pop3_dophase_done(struct Curl_easy *data, bool connected) +{ + (void)data; + (void)connected; + + return CURLE_OK; +} + +/* Called from multi.c while DOing */ +static CURLcode pop3_doing(struct Curl_easy *data, bool *dophase_done) +{ + CURLcode result = pop3_multi_statemach(data, dophase_done); + + if(result) + DEBUGF(infof(data, "DO phase failed")); + else if(*dophase_done) { + result = pop3_dophase_done(data, FALSE /* not connected */); + + DEBUGF(infof(data, "DO phase is complete")); + } + + return result; +} + +/*********************************************************************** + * + * pop3_regular_transfer() + * + * The input argument is already checked for validity. + * + * Performs all commands done before a regular transfer between a local and a + * remote host. + */ +static CURLcode pop3_regular_transfer(struct Curl_easy *data, + bool *dophase_done) +{ + CURLcode result = CURLE_OK; + bool connected = FALSE; + + /* Make sure size is unknown at this point */ + data->req.size = -1; + + /* Set the progress data */ + Curl_pgrsSetUploadCounter(data, 0); + Curl_pgrsSetDownloadCounter(data, 0); + Curl_pgrsSetUploadSize(data, -1); + Curl_pgrsSetDownloadSize(data, -1); + + /* Carry out the perform */ + result = pop3_perform(data, &connected, dophase_done); + + /* Perform post DO phase operations if necessary */ + if(!result && *dophase_done) + result = pop3_dophase_done(data, connected); + + return result; +} + +static CURLcode pop3_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + /* Initialise the POP3 layer */ + CURLcode result = pop3_init(data); + if(result) + return result; + + /* Clear the TLS upgraded flag */ + conn->bits.tls_upgraded = FALSE; + + return CURLE_OK; +} + +/*********************************************************************** + * + * pop3_parse_url_options() + * + * Parse the URL login options. + */ +static CURLcode pop3_parse_url_options(struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + struct pop3_conn *pop3c = &conn->proto.pop3c; + const char *ptr = conn->options; + + while(!result && ptr && *ptr) { + const char *key = ptr; + const char *value; + + while(*ptr && *ptr != '=') + ptr++; + + value = ptr + 1; + + while(*ptr && *ptr != ';') + ptr++; + + if(strncasecompare(key, "AUTH=", 5)) { + result = Curl_sasl_parse_url_auth_option(&pop3c->sasl, + value, ptr - value); + + if(result && strncasecompare(value, "+APOP", ptr - value)) { + pop3c->preftype = POP3_TYPE_APOP; + pop3c->sasl.prefmech = SASL_AUTH_NONE; + result = CURLE_OK; + } + } + else + result = CURLE_URL_MALFORMAT; + + if(*ptr == ';') + ptr++; + } + + if(pop3c->preftype != POP3_TYPE_APOP) + switch(pop3c->sasl.prefmech) { + case SASL_AUTH_NONE: + pop3c->preftype = POP3_TYPE_NONE; + break; + case SASL_AUTH_DEFAULT: + pop3c->preftype = POP3_TYPE_ANY; + break; + default: + pop3c->preftype = POP3_TYPE_SASL; + break; + } + + return result; +} + +/*********************************************************************** + * + * pop3_parse_url_path() + * + * Parse the URL path into separate path components. + */ +static CURLcode pop3_parse_url_path(struct Curl_easy *data) +{ + /* The POP3 struct is already initialised in pop3_connect() */ + struct POP3 *pop3 = data->req.p.pop3; + const char *path = &data->state.up.path[1]; /* skip leading path */ + + /* URL decode the path for the message ID */ + return Curl_urldecode(path, 0, &pop3->id, NULL, REJECT_CTRL); +} + +/*********************************************************************** + * + * pop3_parse_custom_request() + * + * Parse the custom request. + */ +static CURLcode pop3_parse_custom_request(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct POP3 *pop3 = data->req.p.pop3; + const char *custom = data->set.str[STRING_CUSTOMREQUEST]; + + /* URL decode the custom request */ + if(custom) + result = Curl_urldecode(custom, 0, &pop3->custom, NULL, REJECT_CTRL); + + return result; +} + +/*********************************************************************** + * + * Curl_pop3_write() + * + * This function scans the body after the end-of-body and writes everything + * until the end is found. + */ +CURLcode Curl_pop3_write(struct Curl_easy *data, const char *str, size_t nread) +{ + /* This code could be made into a special function in the handler struct */ + CURLcode result = CURLE_OK; + struct SingleRequest *k = &data->req; + struct connectdata *conn = data->conn; + struct pop3_conn *pop3c = &conn->proto.pop3c; + bool strip_dot = FALSE; + size_t last = 0; + size_t i; + + /* Search through the buffer looking for the end-of-body marker which is + 5 bytes (0d 0a 2e 0d 0a). Note that a line starting with a dot matches + the eob so the server will have prefixed it with an extra dot which we + need to strip out. Additionally the marker could of course be spread out + over 5 different data chunks. */ + for(i = 0; i < nread; i++) { + size_t prev = pop3c->eob; + + switch(str[i]) { + case 0x0d: + if(pop3c->eob == 0) { + pop3c->eob++; + + if(i) { + /* Write out the body part that didn't match */ + result = Curl_client_write(data, CLIENTWRITE_BODY, &str[last], + i - last); + + if(result) + return result; + + last = i; + } + } + else if(pop3c->eob == 3) + pop3c->eob++; + else + /* If the character match wasn't at position 0 or 3 then restart the + pattern matching */ + pop3c->eob = 1; + break; + + case 0x0a: + if(pop3c->eob == 1 || pop3c->eob == 4) + pop3c->eob++; + else + /* If the character match wasn't at position 1 or 4 then start the + search again */ + pop3c->eob = 0; + break; + + case 0x2e: + if(pop3c->eob == 2) + pop3c->eob++; + else if(pop3c->eob == 3) { + /* We have an extra dot after the CRLF which we need to strip off */ + strip_dot = TRUE; + pop3c->eob = 0; + } + else + /* If the character match wasn't at position 2 then start the search + again */ + pop3c->eob = 0; + break; + + default: + pop3c->eob = 0; + break; + } + + /* Did we have a partial match which has subsequently failed? */ + if(prev && prev >= pop3c->eob) { + /* Strip can only be non-zero for the very first mismatch after CRLF + and then both prev and strip are equal and nothing will be output + below */ + while(prev && pop3c->strip) { + prev--; + pop3c->strip--; + } + + if(prev) { + /* If the partial match was the CRLF and dot then only write the CRLF + as the server would have inserted the dot */ + if(strip_dot && prev - 1 > 0) { + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)POP3_EOB, + prev - 1); + } + else if(!strip_dot) { + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)POP3_EOB, + prev); + } + else { + result = CURLE_OK; + } + + if(result) + return result; + + last = i; + strip_dot = FALSE; + } + } + } + + if(pop3c->eob == POP3_EOB_LEN) { + /* We have a full match so the transfer is done, however we must transfer + the CRLF at the start of the EOB as this is considered to be part of the + message as per RFC-1939, sect. 3 */ + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)POP3_EOB, 2); + + k->keepon &= ~KEEP_RECV; + pop3c->eob = 0; + + return result; + } + + if(pop3c->eob) + /* While EOB is matching nothing should be output */ + return CURLE_OK; + + if(nread - last) { + result = Curl_client_write(data, CLIENTWRITE_BODY, &str[last], + nread - last); + } + + return result; +} + +#endif /* CURL_DISABLE_POP3 */ diff --git a/third_party/curl/lib/pop3.h b/third_party/curl/lib/pop3.h new file mode 100644 index 0000000..e8e98db --- /dev/null +++ b/third_party/curl/lib/pop3.h @@ -0,0 +1,98 @@ +#ifndef HEADER_CURL_POP3_H +#define HEADER_CURL_POP3_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "pingpong.h" +#include "curl_sasl.h" + +/**************************************************************************** + * POP3 unique setup + ***************************************************************************/ +typedef enum { + POP3_STOP, /* do nothing state, stops the state machine */ + POP3_SERVERGREET, /* waiting for the initial greeting immediately after + a connect */ + POP3_CAPA, + POP3_STARTTLS, + POP3_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS + (multi mode only) */ + POP3_AUTH, + POP3_APOP, + POP3_USER, + POP3_PASS, + POP3_COMMAND, + POP3_QUIT, + POP3_LAST /* never used */ +} pop3state; + +/* This POP3 struct is used in the Curl_easy. All POP3 data that is + connection-oriented must be in pop3_conn to properly deal with the fact that + perhaps the Curl_easy is changed between the times the connection is + used. */ +struct POP3 { + curl_pp_transfer transfer; + char *id; /* Message ID */ + char *custom; /* Custom Request */ +}; + +/* pop3_conn is used for struct connection-oriented data in the connectdata + struct */ +struct pop3_conn { + struct pingpong pp; + pop3state state; /* Always use pop3.c:state() to change state! */ + size_t eob; /* Number of bytes of the EOB (End Of Body) that + have been received so far */ + size_t strip; /* Number of bytes from the start to ignore as + non-body */ + struct SASL sasl; /* SASL-related storage */ + char *apoptimestamp; /* APOP timestamp from the server greeting */ + unsigned char authtypes; /* Accepted authentication types */ + unsigned char preftype; /* Preferred authentication type */ + BIT(ssldone); /* Is connect() over SSL done? */ + BIT(tls_supported); /* StartTLS capability supported by server */ +}; + +extern const struct Curl_handler Curl_handler_pop3; +extern const struct Curl_handler Curl_handler_pop3s; + +/* Authentication type flags */ +#define POP3_TYPE_CLEARTEXT (1 << 0) +#define POP3_TYPE_APOP (1 << 1) +#define POP3_TYPE_SASL (1 << 2) + +/* Authentication type values */ +#define POP3_TYPE_NONE 0 +#define POP3_TYPE_ANY (POP3_TYPE_CLEARTEXT|POP3_TYPE_APOP|POP3_TYPE_SASL) + +/* This is the 5-bytes End-Of-Body marker for POP3 */ +#define POP3_EOB "\x0d\x0a\x2e\x0d\x0a" +#define POP3_EOB_LEN 5 + +/* This function scans the body after the end-of-body and writes everything + * until the end is found */ +CURLcode Curl_pop3_write(struct Curl_easy *data, + const char *str, size_t nread); + +#endif /* HEADER_CURL_POP3_H */ diff --git a/third_party/curl/lib/progress.c b/third_party/curl/lib/progress.c new file mode 100644 index 0000000..d05fcc3 --- /dev/null +++ b/third_party/curl/lib/progress.c @@ -0,0 +1,633 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "urldata.h" +#include "sendf.h" +#include "multiif.h" +#include "progress.h" +#include "timeval.h" +#include "curl_printf.h" + +/* check rate limits within this many recent milliseconds, at minimum. */ +#define MIN_RATE_LIMIT_PERIOD 3000 + +#ifndef CURL_DISABLE_PROGRESS_METER +/* Provide a string that is 2 + 1 + 2 + 1 + 2 = 8 letters long (plus the zero + byte) */ +static void time2str(char *r, curl_off_t seconds) +{ + curl_off_t h; + if(seconds <= 0) { + strcpy(r, "--:--:--"); + return; + } + h = seconds / CURL_OFF_T_C(3600); + if(h <= CURL_OFF_T_C(99)) { + curl_off_t m = (seconds - (h*CURL_OFF_T_C(3600))) / CURL_OFF_T_C(60); + curl_off_t s = (seconds - (h*CURL_OFF_T_C(3600))) - (m*CURL_OFF_T_C(60)); + msnprintf(r, 9, "%2" CURL_FORMAT_CURL_OFF_T ":%02" CURL_FORMAT_CURL_OFF_T + ":%02" CURL_FORMAT_CURL_OFF_T, h, m, s); + } + else { + /* this equals to more than 99 hours, switch to a more suitable output + format to fit within the limits. */ + curl_off_t d = seconds / CURL_OFF_T_C(86400); + h = (seconds - (d*CURL_OFF_T_C(86400))) / CURL_OFF_T_C(3600); + if(d <= CURL_OFF_T_C(999)) + msnprintf(r, 9, "%3" CURL_FORMAT_CURL_OFF_T + "d %02" CURL_FORMAT_CURL_OFF_T "h", d, h); + else + msnprintf(r, 9, "%7" CURL_FORMAT_CURL_OFF_T "d", d); + } +} + +/* The point of this function would be to return a string of the input data, + but never longer than 5 columns (+ one zero byte). + Add suffix k, M, G when suitable... */ +static char *max5data(curl_off_t bytes, char *max5) +{ +#define ONE_KILOBYTE CURL_OFF_T_C(1024) +#define ONE_MEGABYTE (CURL_OFF_T_C(1024) * ONE_KILOBYTE) +#define ONE_GIGABYTE (CURL_OFF_T_C(1024) * ONE_MEGABYTE) +#define ONE_TERABYTE (CURL_OFF_T_C(1024) * ONE_GIGABYTE) +#define ONE_PETABYTE (CURL_OFF_T_C(1024) * ONE_TERABYTE) + + if(bytes < CURL_OFF_T_C(100000)) + msnprintf(max5, 6, "%5" CURL_FORMAT_CURL_OFF_T, bytes); + + else if(bytes < CURL_OFF_T_C(10000) * ONE_KILOBYTE) + msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "k", bytes/ONE_KILOBYTE); + + else if(bytes < CURL_OFF_T_C(100) * ONE_MEGABYTE) + /* 'XX.XM' is good as long as we're less than 100 megs */ + msnprintf(max5, 6, "%2" CURL_FORMAT_CURL_OFF_T ".%0" + CURL_FORMAT_CURL_OFF_T "M", bytes/ONE_MEGABYTE, + (bytes%ONE_MEGABYTE) / (ONE_MEGABYTE/CURL_OFF_T_C(10)) ); + + else if(bytes < CURL_OFF_T_C(10000) * ONE_MEGABYTE) + /* 'XXXXM' is good until we're at 10000MB or above */ + msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "M", bytes/ONE_MEGABYTE); + + else if(bytes < CURL_OFF_T_C(100) * ONE_GIGABYTE) + /* 10000 MB - 100 GB, we show it as XX.XG */ + msnprintf(max5, 6, "%2" CURL_FORMAT_CURL_OFF_T ".%0" + CURL_FORMAT_CURL_OFF_T "G", bytes/ONE_GIGABYTE, + (bytes%ONE_GIGABYTE) / (ONE_GIGABYTE/CURL_OFF_T_C(10)) ); + + else if(bytes < CURL_OFF_T_C(10000) * ONE_GIGABYTE) + /* up to 10000GB, display without decimal: XXXXG */ + msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "G", bytes/ONE_GIGABYTE); + + else if(bytes < CURL_OFF_T_C(10000) * ONE_TERABYTE) + /* up to 10000TB, display without decimal: XXXXT */ + msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "T", bytes/ONE_TERABYTE); + + else + /* up to 10000PB, display without decimal: XXXXP */ + msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "P", bytes/ONE_PETABYTE); + + /* 16384 petabytes (16 exabytes) is the maximum a 64 bit unsigned number can + hold, but our data type is signed so 8192PB will be the maximum. */ + + return max5; +} +#endif + +/* + + New proposed interface, 9th of February 2000: + + pgrsStartNow() - sets start time + pgrsSetDownloadSize(x) - known expected download size + pgrsSetUploadSize(x) - known expected upload size + pgrsSetDownloadCounter() - amount of data currently downloaded + pgrsSetUploadCounter() - amount of data currently uploaded + pgrsUpdate() - show progress + pgrsDone() - transfer complete + +*/ + +int Curl_pgrsDone(struct Curl_easy *data) +{ + int rc; + data->progress.lastshow = 0; + rc = Curl_pgrsUpdate(data); /* the final (forced) update */ + if(rc) + return rc; + + if(!(data->progress.flags & PGRS_HIDE) && + !data->progress.callback) + /* only output if we don't use a progress callback and we're not + * hidden */ + fprintf(data->set.err, "\n"); + + data->progress.speeder_c = 0; /* reset the progress meter display */ + return 0; +} + +/* reset the known transfer sizes */ +void Curl_pgrsResetTransferSizes(struct Curl_easy *data) +{ + Curl_pgrsSetDownloadSize(data, -1); + Curl_pgrsSetUploadSize(data, -1); +} + +/* + * + * Curl_pgrsTimeWas(). Store the timestamp time at the given label. + */ +void Curl_pgrsTimeWas(struct Curl_easy *data, timerid timer, + struct curltime timestamp) +{ + timediff_t *delta = NULL; + + switch(timer) { + default: + case TIMER_NONE: + /* mistake filter */ + break; + case TIMER_STARTOP: + /* This is set at the start of a transfer */ + data->progress.t_startop = timestamp; + break; + case TIMER_STARTSINGLE: + /* This is set at the start of each single transfer */ + data->progress.t_startsingle = timestamp; + data->progress.is_t_startransfer_set = false; + break; + case TIMER_POSTQUEUE: + /* Set when the transfer starts (after potentially having been brought + back from the waiting queue). It needs to count from t_startop and not + t_startsingle since the latter is reset when a connection is brought + back from the pending queue. */ + data->progress.t_postqueue = + Curl_timediff_us(timestamp, data->progress.t_startop); + break; + case TIMER_STARTACCEPT: + data->progress.t_acceptdata = timestamp; + break; + case TIMER_NAMELOOKUP: + delta = &data->progress.t_nslookup; + break; + case TIMER_CONNECT: + delta = &data->progress.t_connect; + break; + case TIMER_APPCONNECT: + delta = &data->progress.t_appconnect; + break; + case TIMER_PRETRANSFER: + delta = &data->progress.t_pretransfer; + break; + case TIMER_STARTTRANSFER: + delta = &data->progress.t_starttransfer; + /* prevent updating t_starttransfer unless: + * 1) this is the first time we're setting t_starttransfer + * 2) a redirect has occurred since the last time t_starttransfer was set + * This prevents repeated invocations of the function from incorrectly + * changing the t_starttransfer time. + */ + if(data->progress.is_t_startransfer_set) { + return; + } + else { + data->progress.is_t_startransfer_set = true; + break; + } + case TIMER_POSTRANSFER: + /* this is the normal end-of-transfer thing */ + break; + case TIMER_REDIRECT: + data->progress.t_redirect = Curl_timediff_us(timestamp, + data->progress.start); + break; + } + if(delta) { + timediff_t us = Curl_timediff_us(timestamp, data->progress.t_startsingle); + if(us < 1) + us = 1; /* make sure at least one microsecond passed */ + *delta += us; + } +} + +/* + * + * Curl_pgrsTime(). Store the current time at the given label. This fetches a + * fresh "now" and returns it. + * + * @unittest: 1399 + */ +struct curltime Curl_pgrsTime(struct Curl_easy *data, timerid timer) +{ + struct curltime now = Curl_now(); + + Curl_pgrsTimeWas(data, timer, now); + return now; +} + +void Curl_pgrsStartNow(struct Curl_easy *data) +{ + data->progress.speeder_c = 0; /* reset the progress meter display */ + data->progress.start = Curl_now(); + data->progress.is_t_startransfer_set = false; + data->progress.ul_limit_start = data->progress.start; + data->progress.dl_limit_start = data->progress.start; + data->progress.ul_limit_size = 0; + data->progress.dl_limit_size = 0; + data->progress.downloaded = 0; + data->progress.uploaded = 0; + /* clear all bits except HIDE and HEADERS_OUT */ + data->progress.flags &= PGRS_HIDE|PGRS_HEADERS_OUT; + Curl_ratelimit(data, data->progress.start); +} + +/* + * This is used to handle speed limits, calculating how many milliseconds to + * wait until we're back under the speed limit, if needed. + * + * The way it works is by having a "starting point" (time & amount of data + * transferred by then) used in the speed computation, to be used instead of + * the start of the transfer. This starting point is regularly moved as + * transfer goes on, to keep getting accurate values (instead of average over + * the entire transfer). + * + * This function takes the current amount of data transferred, the amount at + * the starting point, the limit (in bytes/s), the time of the starting point + * and the current time. + * + * Returns 0 if no waiting is needed or when no waiting is needed but the + * starting point should be reset (to current); or the number of milliseconds + * to wait to get back under the speed limit. + */ +timediff_t Curl_pgrsLimitWaitTime(curl_off_t cursize, + curl_off_t startsize, + curl_off_t limit, + struct curltime start, + struct curltime now) +{ + curl_off_t size = cursize - startsize; + timediff_t minimum; + timediff_t actual; + + if(!limit || !size) + return 0; + + /* + * 'minimum' is the number of milliseconds 'size' should take to download to + * stay below 'limit'. + */ + if(size < CURL_OFF_T_MAX/1000) + minimum = (timediff_t) (CURL_OFF_T_C(1000) * size / limit); + else { + minimum = (timediff_t) (size / limit); + if(minimum < TIMEDIFF_T_MAX/1000) + minimum *= 1000; + else + minimum = TIMEDIFF_T_MAX; + } + + /* + * 'actual' is the time in milliseconds it took to actually download the + * last 'size' bytes. + */ + actual = Curl_timediff_ceil(now, start); + if(actual < minimum) { + /* if it downloaded the data faster than the limit, make it wait the + difference */ + return (minimum - actual); + } + + return 0; +} + +/* + * Set the number of downloaded bytes so far. + */ +CURLcode Curl_pgrsSetDownloadCounter(struct Curl_easy *data, curl_off_t size) +{ + data->progress.downloaded = size; + return CURLE_OK; +} + +/* + * Update the timestamp and sizestamp to use for rate limit calculations. + */ +void Curl_ratelimit(struct Curl_easy *data, struct curltime now) +{ + /* don't set a new stamp unless the time since last update is long enough */ + if(data->set.max_recv_speed) { + if(Curl_timediff(now, data->progress.dl_limit_start) >= + MIN_RATE_LIMIT_PERIOD) { + data->progress.dl_limit_start = now; + data->progress.dl_limit_size = data->progress.downloaded; + } + } + if(data->set.max_send_speed) { + if(Curl_timediff(now, data->progress.ul_limit_start) >= + MIN_RATE_LIMIT_PERIOD) { + data->progress.ul_limit_start = now; + data->progress.ul_limit_size = data->progress.uploaded; + } + } +} + +/* + * Set the number of uploaded bytes so far. + */ +void Curl_pgrsSetUploadCounter(struct Curl_easy *data, curl_off_t size) +{ + data->progress.uploaded = size; +} + +void Curl_pgrsSetDownloadSize(struct Curl_easy *data, curl_off_t size) +{ + if(size >= 0) { + data->progress.size_dl = size; + data->progress.flags |= PGRS_DL_SIZE_KNOWN; + } + else { + data->progress.size_dl = 0; + data->progress.flags &= ~PGRS_DL_SIZE_KNOWN; + } +} + +void Curl_pgrsSetUploadSize(struct Curl_easy *data, curl_off_t size) +{ + if(size >= 0) { + data->progress.size_ul = size; + data->progress.flags |= PGRS_UL_SIZE_KNOWN; + } + else { + data->progress.size_ul = 0; + data->progress.flags &= ~PGRS_UL_SIZE_KNOWN; + } +} + +/* returns the average speed in bytes / second */ +static curl_off_t trspeed(curl_off_t size, /* number of bytes */ + curl_off_t us) /* microseconds */ +{ + if(us < 1) + return size * 1000000; + else if(size < CURL_OFF_T_MAX/1000000) + return (size * 1000000) / us; + else if(us >= 1000000) + return size / (us / 1000000); + else + return CURL_OFF_T_MAX; +} + +/* returns TRUE if it's time to show the progress meter */ +static bool progress_calc(struct Curl_easy *data, struct curltime now) +{ + bool timetoshow = FALSE; + struct Progress * const p = &data->progress; + + /* The time spent so far (from the start) in microseconds */ + p->timespent = Curl_timediff_us(now, p->start); + p->dlspeed = trspeed(p->downloaded, p->timespent); + p->ulspeed = trspeed(p->uploaded, p->timespent); + + /* Calculations done at most once a second, unless end is reached */ + if(p->lastshow != now.tv_sec) { + int countindex; /* amount of seconds stored in the speeder array */ + int nowindex = p->speeder_c% CURR_TIME; + p->lastshow = now.tv_sec; + timetoshow = TRUE; + + /* Let's do the "current speed" thing, with the dl + ul speeds + combined. Store the speed at entry 'nowindex'. */ + p->speeder[ nowindex ] = p->downloaded + p->uploaded; + + /* remember the exact time for this moment */ + p->speeder_time [ nowindex ] = now; + + /* advance our speeder_c counter, which is increased every time we get + here and we expect it to never wrap as 2^32 is a lot of seconds! */ + p->speeder_c++; + + /* figure out how many index entries of data we have stored in our speeder + array. With N_ENTRIES filled in, we have about N_ENTRIES-1 seconds of + transfer. Imagine, after one second we have filled in two entries, + after two seconds we've filled in three entries etc. */ + countindex = ((p->speeder_c >= CURR_TIME)? CURR_TIME:p->speeder_c) - 1; + + /* first of all, we don't do this if there's no counted seconds yet */ + if(countindex) { + int checkindex; + timediff_t span_ms; + curl_off_t amount; + + /* Get the index position to compare with the 'nowindex' position. + Get the oldest entry possible. While we have less than CURR_TIME + entries, the first entry will remain the oldest. */ + checkindex = (p->speeder_c >= CURR_TIME)? p->speeder_c%CURR_TIME:0; + + /* Figure out the exact time for the time span */ + span_ms = Curl_timediff(now, p->speeder_time[checkindex]); + if(0 == span_ms) + span_ms = 1; /* at least one millisecond MUST have passed */ + + /* Calculate the average speed the last 'span_ms' milliseconds */ + amount = p->speeder[nowindex]- p->speeder[checkindex]; + + if(amount > CURL_OFF_T_C(4294967) /* 0xffffffff/1000 */) + /* the 'amount' value is bigger than would fit in 32 bits if + multiplied with 1000, so we use the double math for this */ + p->current_speed = (curl_off_t) + ((double)amount/((double)span_ms/1000.0)); + else + /* the 'amount' value is small enough to fit within 32 bits even + when multiplied with 1000 */ + p->current_speed = amount*CURL_OFF_T_C(1000)/span_ms; + } + else + /* the first second we use the average */ + p->current_speed = p->ulspeed + p->dlspeed; + + } /* Calculations end */ + return timetoshow; +} + +#ifndef CURL_DISABLE_PROGRESS_METER +static void progress_meter(struct Curl_easy *data) +{ + char max5[6][10]; + curl_off_t dlpercen = 0; + curl_off_t ulpercen = 0; + curl_off_t total_percen = 0; + curl_off_t total_transfer; + curl_off_t total_expected_transfer; + char time_left[10]; + char time_total[10]; + char time_spent[10]; + curl_off_t ulestimate = 0; + curl_off_t dlestimate = 0; + curl_off_t total_estimate; + curl_off_t timespent = + (curl_off_t)data->progress.timespent/1000000; /* seconds */ + + if(!(data->progress.flags & PGRS_HEADERS_OUT)) { + if(data->state.resume_from) { + fprintf(data->set.err, + "** Resuming transfer from byte position %" + CURL_FORMAT_CURL_OFF_T "\n", data->state.resume_from); + } + fprintf(data->set.err, + " %% Total %% Received %% Xferd Average Speed " + "Time Time Time Current\n" + " Dload Upload " + "Total Spent Left Speed\n"); + data->progress.flags |= PGRS_HEADERS_OUT; /* headers are shown */ + } + + /* Figure out the estimated time of arrival for the upload */ + if((data->progress.flags & PGRS_UL_SIZE_KNOWN) && + (data->progress.ulspeed > CURL_OFF_T_C(0))) { + ulestimate = data->progress.size_ul / data->progress.ulspeed; + + if(data->progress.size_ul > CURL_OFF_T_C(10000)) + ulpercen = data->progress.uploaded / + (data->progress.size_ul/CURL_OFF_T_C(100)); + else if(data->progress.size_ul > CURL_OFF_T_C(0)) + ulpercen = (data->progress.uploaded*100) / + data->progress.size_ul; + } + + /* ... and the download */ + if((data->progress.flags & PGRS_DL_SIZE_KNOWN) && + (data->progress.dlspeed > CURL_OFF_T_C(0))) { + dlestimate = data->progress.size_dl / data->progress.dlspeed; + + if(data->progress.size_dl > CURL_OFF_T_C(10000)) + dlpercen = data->progress.downloaded / + (data->progress.size_dl/CURL_OFF_T_C(100)); + else if(data->progress.size_dl > CURL_OFF_T_C(0)) + dlpercen = (data->progress.downloaded*100) / + data->progress.size_dl; + } + + /* Now figure out which of them is slower and use that one for the + total estimate! */ + total_estimate = ulestimate>dlestimate?ulestimate:dlestimate; + + /* create the three time strings */ + time2str(time_left, total_estimate > 0?(total_estimate - timespent):0); + time2str(time_total, total_estimate); + time2str(time_spent, timespent); + + /* Get the total amount of data expected to get transferred */ + total_expected_transfer = + ((data->progress.flags & PGRS_UL_SIZE_KNOWN)? + data->progress.size_ul:data->progress.uploaded)+ + ((data->progress.flags & PGRS_DL_SIZE_KNOWN)? + data->progress.size_dl:data->progress.downloaded); + + /* We have transferred this much so far */ + total_transfer = data->progress.downloaded + data->progress.uploaded; + + /* Get the percentage of data transferred so far */ + if(total_expected_transfer > CURL_OFF_T_C(10000)) + total_percen = total_transfer / + (total_expected_transfer/CURL_OFF_T_C(100)); + else if(total_expected_transfer > CURL_OFF_T_C(0)) + total_percen = (total_transfer*100) / total_expected_transfer; + + fprintf(data->set.err, + "\r" + "%3" CURL_FORMAT_CURL_OFF_T " %s " + "%3" CURL_FORMAT_CURL_OFF_T " %s " + "%3" CURL_FORMAT_CURL_OFF_T " %s %s %s %s %s %s %s", + total_percen, /* 3 letters */ /* total % */ + max5data(total_expected_transfer, max5[2]), /* total size */ + dlpercen, /* 3 letters */ /* rcvd % */ + max5data(data->progress.downloaded, max5[0]), /* rcvd size */ + ulpercen, /* 3 letters */ /* xfer % */ + max5data(data->progress.uploaded, max5[1]), /* xfer size */ + max5data(data->progress.dlspeed, max5[3]), /* avrg dl speed */ + max5data(data->progress.ulspeed, max5[4]), /* avrg ul speed */ + time_total, /* 8 letters */ /* total time */ + time_spent, /* 8 letters */ /* time spent */ + time_left, /* 8 letters */ /* time left */ + max5data(data->progress.current_speed, max5[5]) + ); + + /* we flush the output stream to make it appear as soon as possible */ + fflush(data->set.err); +} +#else + /* progress bar disabled */ +#define progress_meter(x) Curl_nop_stmt +#endif + + +/* + * Curl_pgrsUpdate() returns 0 for success or the value returned by the + * progress callback! + */ +int Curl_pgrsUpdate(struct Curl_easy *data) +{ + struct curltime now = Curl_now(); /* what time is it */ + bool showprogress = progress_calc(data, now); + if(!(data->progress.flags & PGRS_HIDE)) { + if(data->set.fxferinfo) { + int result; + /* There's a callback set, call that */ + Curl_set_in_callback(data, true); + result = data->set.fxferinfo(data->set.progress_client, + data->progress.size_dl, + data->progress.downloaded, + data->progress.size_ul, + data->progress.uploaded); + Curl_set_in_callback(data, false); + if(result != CURL_PROGRESSFUNC_CONTINUE) { + if(result) + failf(data, "Callback aborted"); + return result; + } + } + else if(data->set.fprogress) { + int result; + /* The older deprecated callback is set, call that */ + Curl_set_in_callback(data, true); + result = data->set.fprogress(data->set.progress_client, + (double)data->progress.size_dl, + (double)data->progress.downloaded, + (double)data->progress.size_ul, + (double)data->progress.uploaded); + Curl_set_in_callback(data, false); + if(result != CURL_PROGRESSFUNC_CONTINUE) { + if(result) + failf(data, "Callback aborted"); + return result; + } + } + + if(showprogress) + progress_meter(data); + } + + return 0; +} diff --git a/third_party/curl/lib/progress.h b/third_party/curl/lib/progress.h new file mode 100644 index 0000000..7374941 --- /dev/null +++ b/third_party/curl/lib/progress.h @@ -0,0 +1,77 @@ +#ifndef HEADER_CURL_PROGRESS_H +#define HEADER_CURL_PROGRESS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "timeval.h" + + +typedef enum { + TIMER_NONE, + TIMER_STARTOP, + TIMER_STARTSINGLE, /* start of transfer, might get queued */ + TIMER_POSTQUEUE, /* start, immediately after dequeue */ + TIMER_NAMELOOKUP, + TIMER_CONNECT, + TIMER_APPCONNECT, + TIMER_PRETRANSFER, + TIMER_STARTTRANSFER, + TIMER_POSTRANSFER, + TIMER_STARTACCEPT, + TIMER_REDIRECT, + TIMER_LAST /* must be last */ +} timerid; + +int Curl_pgrsDone(struct Curl_easy *data); +void Curl_pgrsStartNow(struct Curl_easy *data); +void Curl_pgrsSetDownloadSize(struct Curl_easy *data, curl_off_t size); +void Curl_pgrsSetUploadSize(struct Curl_easy *data, curl_off_t size); + +/* It is fine to not check the return code if 'size' is set to 0 */ +CURLcode Curl_pgrsSetDownloadCounter(struct Curl_easy *data, curl_off_t size); + +void Curl_pgrsSetUploadCounter(struct Curl_easy *data, curl_off_t size); +void Curl_ratelimit(struct Curl_easy *data, struct curltime now); +int Curl_pgrsUpdate(struct Curl_easy *data); +void Curl_pgrsResetTransferSizes(struct Curl_easy *data); +struct curltime Curl_pgrsTime(struct Curl_easy *data, timerid timer); +timediff_t Curl_pgrsLimitWaitTime(curl_off_t cursize, + curl_off_t startsize, + curl_off_t limit, + struct curltime start, + struct curltime now); +/** + * Update progress timer with the elapsed time from its start to `timestamp`. + * This allows updating timers later and is used by happy eyeballing, where + * we only want to record the winner's times. + */ +void Curl_pgrsTimeWas(struct Curl_easy *data, timerid timer, + struct curltime timestamp); + +#define PGRS_HIDE (1<<4) +#define PGRS_UL_SIZE_KNOWN (1<<5) +#define PGRS_DL_SIZE_KNOWN (1<<6) +#define PGRS_HEADERS_OUT (1<<7) /* set when the headers have been written */ + +#endif /* HEADER_CURL_PROGRESS_H */ diff --git a/third_party/curl/lib/psl.c b/third_party/curl/lib/psl.c new file mode 100644 index 0000000..626a203 --- /dev/null +++ b/third_party/curl/lib/psl.c @@ -0,0 +1,113 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#ifdef USE_LIBPSL + +#include "psl.h" +#include "share.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +void Curl_psl_destroy(struct PslCache *pslcache) +{ + if(pslcache->psl) { + if(pslcache->dynamic) + psl_free((psl_ctx_t *) pslcache->psl); + pslcache->psl = NULL; + pslcache->dynamic = FALSE; + } +} + +static time_t now_seconds(void) +{ + struct curltime now = Curl_now(); + + return now.tv_sec; +} + +const psl_ctx_t *Curl_psl_use(struct Curl_easy *easy) +{ + struct PslCache *pslcache = easy->psl; + const psl_ctx_t *psl; + time_t now; + + if(!pslcache) + return NULL; + + Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SHARED); + now = now_seconds(); + if(!pslcache->psl || pslcache->expires <= now) { + /* Let a chance to other threads to do the job: avoids deadlock. */ + Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); + + /* Update cache: this needs an exclusive lock. */ + Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SINGLE); + + /* Recheck in case another thread did the job. */ + now = now_seconds(); + if(!pslcache->psl || pslcache->expires <= now) { + bool dynamic = FALSE; + time_t expires = TIME_T_MAX; + +#if defined(PSL_VERSION_NUMBER) && PSL_VERSION_NUMBER >= 0x001000 + psl = psl_latest(NULL); + dynamic = psl != NULL; + /* Take care of possible time computation overflow. */ + expires = now < TIME_T_MAX - PSL_TTL? now + PSL_TTL: TIME_T_MAX; + + /* Only get the built-in PSL if we do not already have the "latest". */ + if(!psl && !pslcache->dynamic) +#endif + + psl = psl_builtin(); + + if(psl) { + Curl_psl_destroy(pslcache); + pslcache->psl = psl; + pslcache->dynamic = dynamic; + pslcache->expires = expires; + } + } + Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); /* Release exclusive lock. */ + Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SHARED); + } + psl = pslcache->psl; + if(!psl) + Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); + return psl; +} + +void Curl_psl_release(struct Curl_easy *easy) +{ + Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); +} + +#endif /* USE_LIBPSL */ diff --git a/third_party/curl/lib/psl.h b/third_party/curl/lib/psl.h new file mode 100644 index 0000000..23cfa92 --- /dev/null +++ b/third_party/curl/lib/psl.h @@ -0,0 +1,49 @@ +#ifndef HEADER_PSL_H +#define HEADER_PSL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifdef USE_LIBPSL +#include + +#define PSL_TTL (72 * 3600) /* PSL time to live before a refresh. */ + +struct PslCache { + const psl_ctx_t *psl; /* The PSL. */ + time_t expires; /* Time this PSL life expires. */ + bool dynamic; /* PSL should be released when no longer needed. */ +}; + +const psl_ctx_t *Curl_psl_use(struct Curl_easy *easy); +void Curl_psl_release(struct Curl_easy *easy); +void Curl_psl_destroy(struct PslCache *pslcache); + +#else + +#define Curl_psl_use(easy) NULL +#define Curl_psl_release(easy) +#define Curl_psl_destroy(pslcache) + +#endif /* USE_LIBPSL */ +#endif /* HEADER_PSL_H */ diff --git a/third_party/curl/lib/rand.c b/third_party/curl/lib/rand.c new file mode 100644 index 0000000..c62b1a4 --- /dev/null +++ b/third_party/curl/lib/rand.c @@ -0,0 +1,291 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#ifdef HAVE_FCNTL_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif + +#include +#include "urldata.h" +#include "vtls/vtls.h" +#include "sendf.h" +#include "timeval.h" +#include "rand.h" +#include "escape.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#ifdef _WIN32 + +#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x600 +# define HAVE_WIN_BCRYPTGENRANDOM +# include +# ifdef _MSC_VER +# pragma comment(lib, "bcrypt.lib") +# endif +# ifndef BCRYPT_USE_SYSTEM_PREFERRED_RNG +# define BCRYPT_USE_SYSTEM_PREFERRED_RNG 0x00000002 +# endif +# ifndef STATUS_SUCCESS +# define STATUS_SUCCESS ((NTSTATUS)0x00000000L) +# endif +#elif defined(USE_WIN32_CRYPTO) +# include +# ifdef _MSC_VER +# pragma comment(lib, "advapi32.lib") +# endif +#endif + +CURLcode Curl_win32_random(unsigned char *entropy, size_t length) +{ + memset(entropy, 0, length); + +#if defined(HAVE_WIN_BCRYPTGENRANDOM) + if(BCryptGenRandom(NULL, entropy, (ULONG)length, + BCRYPT_USE_SYSTEM_PREFERRED_RNG) != STATUS_SUCCESS) + return CURLE_FAILED_INIT; + + return CURLE_OK; +#elif defined(USE_WIN32_CRYPTO) + { + HCRYPTPROV hCryptProv = 0; + + if(!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + return CURLE_FAILED_INIT; + + if(!CryptGenRandom(hCryptProv, (DWORD)length, entropy)) { + CryptReleaseContext(hCryptProv, 0UL); + return CURLE_FAILED_INIT; + } + + CryptReleaseContext(hCryptProv, 0UL); + } + return CURLE_OK; +#else + return CURLE_NOT_BUILT_IN; +#endif +} +#endif + +static CURLcode randit(struct Curl_easy *data, unsigned int *rnd) +{ + CURLcode result = CURLE_OK; + static unsigned int randseed; + static bool seeded = FALSE; + +#ifdef CURLDEBUG + char *force_entropy = getenv("CURL_ENTROPY"); + if(force_entropy) { + if(!seeded) { + unsigned int seed = 0; + size_t elen = strlen(force_entropy); + size_t clen = sizeof(seed); + size_t min = elen < clen ? elen : clen; + memcpy((char *)&seed, force_entropy, min); + randseed = ntohl(seed); + seeded = TRUE; + } + else + randseed++; + *rnd = randseed; + return CURLE_OK; + } +#endif + + /* data may be NULL! */ + result = Curl_ssl_random(data, (unsigned char *)rnd, sizeof(*rnd)); + if(result != CURLE_NOT_BUILT_IN) + /* only if there is no random function in the TLS backend do the non crypto + version, otherwise return result */ + return result; + + /* ---- non-cryptographic version following ---- */ + +#ifdef _WIN32 + if(!seeded) { + result = Curl_win32_random((unsigned char *)rnd, sizeof(*rnd)); + if(result != CURLE_NOT_BUILT_IN) + return result; + } +#endif + +#if defined(HAVE_ARC4RANDOM) && !defined(USE_OPENSSL) + if(!seeded) { + *rnd = (unsigned int)arc4random(); + return CURLE_OK; + } +#endif + +#if defined(RANDOM_FILE) && !defined(_WIN32) + if(!seeded) { + /* if there's a random file to read a seed from, use it */ + int fd = open(RANDOM_FILE, O_RDONLY); + if(fd > -1) { + /* read random data into the randseed variable */ + ssize_t nread = read(fd, &randseed, sizeof(randseed)); + if(nread == sizeof(randseed)) + seeded = TRUE; + close(fd); + } + } +#endif + + if(!seeded) { + struct curltime now = Curl_now(); + infof(data, "WARNING: using weak random seed"); + randseed += (unsigned int)now.tv_usec + (unsigned int)now.tv_sec; + randseed = randseed * 1103515245 + 12345; + randseed = randseed * 1103515245 + 12345; + randseed = randseed * 1103515245 + 12345; + seeded = TRUE; + } + + { + unsigned int r; + /* Return an unsigned 32-bit pseudo-random number. */ + r = randseed = randseed * 1103515245 + 12345; + *rnd = (r << 16) | ((r >> 16) & 0xFFFF); + } + return CURLE_OK; +} + +/* + * Curl_rand() stores 'num' number of random unsigned characters in the buffer + * 'rnd' points to. + * + * If libcurl is built without TLS support or with a TLS backend that lacks a + * proper random API (rustls or mbedTLS), this function will use "weak" + * random. + * + * When built *with* TLS support and a backend that offers strong random, it + * will return error if it cannot provide strong random values. + * + * NOTE: 'data' may be passed in as NULL when coming from external API without + * easy handle! + * + */ + +CURLcode Curl_rand(struct Curl_easy *data, unsigned char *rnd, size_t num) +{ + CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT; + + DEBUGASSERT(num); + + while(num) { + unsigned int r; + size_t left = num < sizeof(unsigned int) ? num : sizeof(unsigned int); + + result = randit(data, &r); + if(result) + return result; + + while(left) { + *rnd++ = (unsigned char)(r & 0xFF); + r >>= 8; + --num; + --left; + } + } + + return result; +} + +/* + * Curl_rand_hex() fills the 'rnd' buffer with a given 'num' size with random + * hexadecimal digits PLUS a null-terminating byte. It must be an odd number + * size. + */ + +CURLcode Curl_rand_hex(struct Curl_easy *data, unsigned char *rnd, + size_t num) +{ + CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT; + unsigned char buffer[128]; + DEBUGASSERT(num > 1); + +#ifdef __clang_analyzer__ + /* This silences a scan-build warning about accessing this buffer with + uninitialized memory. */ + memset(buffer, 0, sizeof(buffer)); +#endif + + if((num/2 >= sizeof(buffer)) || !(num&1)) { + /* make sure it fits in the local buffer and that it is an odd number! */ + DEBUGF(infof(data, "invalid buffer size with Curl_rand_hex")); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + num--; /* save one for null-termination */ + + result = Curl_rand(data, buffer, num/2); + if(result) + return result; + + Curl_hexencode(buffer, num/2, rnd, num + 1); + return result; +} + +/* + * Curl_rand_alnum() fills the 'rnd' buffer with a given 'num' size with random + * alphanumerical chars PLUS a null-terminating byte. + */ + +static const char alnum[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + +CURLcode Curl_rand_alnum(struct Curl_easy *data, unsigned char *rnd, + size_t num) +{ + CURLcode result = CURLE_OK; + const int alnumspace = sizeof(alnum) - 1; + unsigned int r; + DEBUGASSERT(num > 1); + + num--; /* save one for null-termination */ + + while(num) { + do { + result = randit(data, &r); + if(result) + return result; + } while(r >= (UINT_MAX - UINT_MAX % alnumspace)); + + *rnd++ = alnum[r % alnumspace]; + num--; + } + *rnd = 0; + + return result; +} diff --git a/third_party/curl/lib/rand.h b/third_party/curl/lib/rand.h new file mode 100644 index 0000000..bc05239 --- /dev/null +++ b/third_party/curl/lib/rand.h @@ -0,0 +1,50 @@ +#ifndef HEADER_CURL_RAND_H +#define HEADER_CURL_RAND_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +CURLcode Curl_rand(struct Curl_easy *data, unsigned char *rnd, size_t num); + +/* + * Curl_rand_hex() fills the 'rnd' buffer with a given 'num' size with random + * hexadecimal digits PLUS a null-terminating byte. It must be an odd number + * size. + */ +CURLcode Curl_rand_hex(struct Curl_easy *data, unsigned char *rnd, + size_t num); + +/* + * Curl_rand_alnum() fills the 'rnd' buffer with a given 'num' size with random + * alphanumerical chars PLUS a null-terminating byte. + */ +CURLcode Curl_rand_alnum(struct Curl_easy *data, unsigned char *rnd, + size_t num); + +#ifdef _WIN32 +/* Random generator shared between the Schannel vtls and Curl_rand*() + functions */ +CURLcode Curl_win32_random(unsigned char *entropy, size_t length); +#endif + +#endif /* HEADER_CURL_RAND_H */ diff --git a/third_party/curl/lib/rename.c b/third_party/curl/lib/rename.c new file mode 100644 index 0000000..4c88698 --- /dev/null +++ b/third_party/curl/lib/rename.c @@ -0,0 +1,73 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "rename.h" + +#include "curl_setup.h" + +#if (!defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_COOKIES)) || \ + !defined(CURL_DISABLE_ALTSVC) + +#include "curl_multibyte.h" +#include "timeval.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* return 0 on success, 1 on error */ +int Curl_rename(const char *oldpath, const char *newpath) +{ +#ifdef _WIN32 + /* rename() on Windows doesn't overwrite, so we can't use it here. + MoveFileEx() will overwrite and is usually atomic, however it fails + when there are open handles to the file. */ + const int max_wait_ms = 1000; + struct curltime start = Curl_now(); + TCHAR *tchar_oldpath = curlx_convert_UTF8_to_tchar((char *)oldpath); + TCHAR *tchar_newpath = curlx_convert_UTF8_to_tchar((char *)newpath); + for(;;) { + timediff_t diff; + if(MoveFileEx(tchar_oldpath, tchar_newpath, MOVEFILE_REPLACE_EXISTING)) { + curlx_unicodefree(tchar_oldpath); + curlx_unicodefree(tchar_newpath); + break; + } + diff = Curl_timediff(Curl_now(), start); + if(diff < 0 || diff > max_wait_ms) { + curlx_unicodefree(tchar_oldpath); + curlx_unicodefree(tchar_newpath); + return 1; + } + Sleep(1); + } +#else + if(rename(oldpath, newpath)) + return 1; +#endif + return 0; +} + +#endif diff --git a/third_party/curl/lib/rename.h b/third_party/curl/lib/rename.h new file mode 100644 index 0000000..0444082 --- /dev/null +++ b/third_party/curl/lib/rename.h @@ -0,0 +1,29 @@ +#ifndef HEADER_CURL_RENAME_H +#define HEADER_CURL_RENAME_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +int Curl_rename(const char *oldpath, const char *newpath); + +#endif /* HEADER_CURL_RENAME_H */ diff --git a/third_party/curl/lib/request.c b/third_party/curl/lib/request.c new file mode 100644 index 0000000..26741fa --- /dev/null +++ b/third_party/curl/lib/request.c @@ -0,0 +1,409 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "urldata.h" +#include "cfilters.h" +#include "dynbuf.h" +#include "doh.h" +#include "multiif.h" +#include "progress.h" +#include "request.h" +#include "sendf.h" +#include "transfer.h" +#include "url.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +void Curl_req_init(struct SingleRequest *req) +{ + memset(req, 0, sizeof(*req)); +} + +CURLcode Curl_req_soft_reset(struct SingleRequest *req, + struct Curl_easy *data) +{ + CURLcode result; + + req->done = FALSE; + req->upload_done = FALSE; + req->download_done = FALSE; + req->ignorebody = FALSE; + req->bytecount = 0; + req->writebytecount = 0; + req->header = TRUE; /* assume header */ + req->headerline = 0; + req->headerbytecount = 0; + req->allheadercount = 0; + req->deductheadercount = 0; + + result = Curl_client_start(data); + if(result) + return result; + + if(!req->sendbuf_init) { + Curl_bufq_init2(&req->sendbuf, data->set.upload_buffer_size, 1, + BUFQ_OPT_SOFT_LIMIT); + req->sendbuf_init = TRUE; + } + else { + Curl_bufq_reset(&req->sendbuf); + if(data->set.upload_buffer_size != req->sendbuf.chunk_size) { + Curl_bufq_free(&req->sendbuf); + Curl_bufq_init2(&req->sendbuf, data->set.upload_buffer_size, 1, + BUFQ_OPT_SOFT_LIMIT); + } + } + + return CURLE_OK; +} + +CURLcode Curl_req_start(struct SingleRequest *req, + struct Curl_easy *data) +{ + req->start = Curl_now(); + return Curl_req_soft_reset(req, data); +} + +static CURLcode req_flush(struct Curl_easy *data); + +CURLcode Curl_req_done(struct SingleRequest *req, + struct Curl_easy *data, bool aborted) +{ + (void)req; + if(!aborted) + (void)req_flush(data); + Curl_client_reset(data); + return CURLE_OK; +} + +void Curl_req_hard_reset(struct SingleRequest *req, struct Curl_easy *data) +{ + struct curltime t0 = {0, 0}; + + /* This is a bit ugly. `req->p` is a union and we assume we can + * free this safely without leaks. */ + Curl_safefree(req->p.http); + Curl_safefree(req->newurl); + Curl_client_reset(data); + if(req->sendbuf_init) + Curl_bufq_reset(&req->sendbuf); + +#ifndef CURL_DISABLE_DOH + if(req->doh) { + Curl_close(&req->doh->probe[0].easy); + Curl_close(&req->doh->probe[1].easy); + } +#endif + /* Can no longer memset() this struct as we need to keep some state */ + req->size = -1; + req->maxdownload = -1; + req->bytecount = 0; + req->writebytecount = 0; + req->start = t0; + req->headerbytecount = 0; + req->allheadercount = 0; + req->deductheadercount = 0; + req->headerline = 0; + req->offset = 0; + req->httpcode = 0; + req->keepon = 0; + req->upgr101 = UPGR101_INIT; + req->timeofdoc = 0; + req->bodywrites = 0; + req->location = NULL; + req->newurl = NULL; +#ifndef CURL_DISABLE_COOKIES + req->setcookies = 0; +#endif + req->header = FALSE; + req->content_range = FALSE; + req->download_done = FALSE; + req->eos_written = FALSE; + req->eos_read = FALSE; + req->upload_done = FALSE; + req->upload_aborted = FALSE; + req->ignorebody = FALSE; + req->http_bodyless = FALSE; + req->chunk = FALSE; + req->ignore_cl = FALSE; + req->upload_chunky = FALSE; + req->getheader = FALSE; + req->no_body = data->set.opt_no_body; + req->authneg = FALSE; +} + +void Curl_req_free(struct SingleRequest *req, struct Curl_easy *data) +{ + /* This is a bit ugly. `req->p` is a union and we assume we can + * free this safely without leaks. */ + Curl_safefree(req->p.http); + Curl_safefree(req->newurl); + if(req->sendbuf_init) + Curl_bufq_free(&req->sendbuf); + Curl_client_cleanup(data); + +#ifndef CURL_DISABLE_DOH + if(req->doh) { + Curl_close(&req->doh->probe[0].easy); + Curl_close(&req->doh->probe[1].easy); + Curl_dyn_free(&req->doh->probe[0].serverdoh); + Curl_dyn_free(&req->doh->probe[1].serverdoh); + curl_slist_free_all(req->doh->headers); + Curl_safefree(req->doh); + } +#endif +} + +static CURLcode xfer_send(struct Curl_easy *data, + const char *buf, size_t blen, + size_t hds_len, size_t *pnwritten) +{ + CURLcode result = CURLE_OK; + + *pnwritten = 0; +#ifdef CURLDEBUG + { + /* Allow debug builds to override this logic to force short initial + sends + */ + char *p = getenv("CURL_SMALLREQSEND"); + if(p) { + size_t altsize = (size_t)strtoul(p, NULL, 10); + if(altsize && altsize < blen) + blen = altsize; + } + } +#endif + /* Make sure this doesn't send more body bytes than what the max send + speed says. The headers do not count to the max speed. */ + if(data->set.max_send_speed) { + size_t body_bytes = blen - hds_len; + if((curl_off_t)body_bytes > data->set.max_send_speed) + blen = hds_len + (size_t)data->set.max_send_speed; + } + + result = Curl_xfer_send(data, buf, blen, pnwritten); + if(!result && *pnwritten) { + if(hds_len) + Curl_debug(data, CURLINFO_HEADER_OUT, (char *)buf, + CURLMIN(hds_len, *pnwritten)); + if(*pnwritten > hds_len) { + size_t body_len = *pnwritten - hds_len; + Curl_debug(data, CURLINFO_DATA_OUT, (char *)buf + hds_len, body_len); + data->req.writebytecount += body_len; + Curl_pgrsSetUploadCounter(data, data->req.writebytecount); + } + } + return result; +} + +static CURLcode req_send_buffer_flush(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + const unsigned char *buf; + size_t blen; + + while(Curl_bufq_peek(&data->req.sendbuf, &buf, &blen)) { + size_t nwritten, hds_len = CURLMIN(data->req.sendbuf_hds_len, blen); + result = xfer_send(data, (const char *)buf, blen, hds_len, &nwritten); + if(result) + break; + + Curl_bufq_skip(&data->req.sendbuf, nwritten); + if(hds_len) { + data->req.sendbuf_hds_len -= CURLMIN(hds_len, nwritten); + } + /* leave if we could not send all. Maybe network blocking or + * speed limits on transfer */ + if(nwritten < blen) + break; + } + return result; +} + +static CURLcode req_set_upload_done(struct Curl_easy *data) +{ + DEBUGASSERT(!data->req.upload_done); + data->req.upload_done = TRUE; + data->req.keepon &= ~(KEEP_SEND|KEEP_SEND_TIMED); /* we're done sending */ + + Curl_creader_done(data, data->req.upload_aborted); + + if(data->req.upload_aborted) { + if(data->req.writebytecount) + infof(data, "abort upload after having sent %" CURL_FORMAT_CURL_OFF_T + " bytes", data->req.writebytecount); + else + infof(data, "abort upload"); + } + else if(data->req.writebytecount) + infof(data, "upload completely sent off: %" CURL_FORMAT_CURL_OFF_T + " bytes", data->req.writebytecount); + else if(!data->req.download_done) + infof(data, Curl_creader_total_length(data)? + "We are completely uploaded and fine" : + "Request completely sent off"); + + return Curl_xfer_send_close(data); +} + +static CURLcode req_flush(struct Curl_easy *data) +{ + CURLcode result; + + if(!data || !data->conn) + return CURLE_FAILED_INIT; + + if(!Curl_bufq_is_empty(&data->req.sendbuf)) { + result = req_send_buffer_flush(data); + if(result) + return result; + if(!Curl_bufq_is_empty(&data->req.sendbuf)) { + return CURLE_AGAIN; + } + } + + if(!data->req.upload_done && data->req.eos_read && + Curl_bufq_is_empty(&data->req.sendbuf)) { + return req_set_upload_done(data); + } + return CURLE_OK; +} + +static ssize_t add_from_client(void *reader_ctx, + unsigned char *buf, size_t buflen, + CURLcode *err) +{ + struct Curl_easy *data = reader_ctx; + size_t nread; + bool eos; + + *err = Curl_client_read(data, (char *)buf, buflen, &nread, &eos); + if(*err) + return -1; + if(eos) + data->req.eos_read = TRUE; + return (ssize_t)nread; +} + +#ifndef USE_HYPER + +static CURLcode req_send_buffer_add(struct Curl_easy *data, + const char *buf, size_t blen, + size_t hds_len) +{ + CURLcode result = CURLE_OK; + ssize_t n; + n = Curl_bufq_write(&data->req.sendbuf, + (const unsigned char *)buf, blen, &result); + if(n < 0) + return result; + /* We rely on a SOFTLIMIT on sendbuf, so it can take all data in */ + DEBUGASSERT((size_t)n == blen); + data->req.sendbuf_hds_len += hds_len; + return CURLE_OK; +} + +CURLcode Curl_req_send(struct Curl_easy *data, struct dynbuf *req) +{ + CURLcode result; + const char *buf; + size_t blen, nwritten; + + if(!data || !data->conn) + return CURLE_FAILED_INIT; + + buf = Curl_dyn_ptr(req); + blen = Curl_dyn_len(req); + if(!Curl_creader_total_length(data)) { + /* Request without body. Try to send directly from the buf given. */ + data->req.eos_read = TRUE; + result = xfer_send(data, buf, blen, blen, &nwritten); + if(result) + return result; + buf += nwritten; + blen -= nwritten; + } + + if(blen) { + /* Either we have a request body, or we could not send the complete + * request in one go. Buffer the remainder and try to add as much + * body bytes as room is left in the buffer. Then flush. */ + result = req_send_buffer_add(data, buf, blen, blen); + if(result) + return result; + + return Curl_req_send_more(data); + } + return CURLE_OK; +} +#endif /* !USE_HYPER */ + +bool Curl_req_want_send(struct Curl_easy *data) +{ + return data->req.sendbuf_init && !Curl_bufq_is_empty(&data->req.sendbuf); +} + +bool Curl_req_done_sending(struct Curl_easy *data) +{ + if(data->req.upload_done) { + DEBUGASSERT(Curl_bufq_is_empty(&data->req.sendbuf)); + return TRUE; + } + return FALSE; +} + +CURLcode Curl_req_send_more(struct Curl_easy *data) +{ + CURLcode result; + + /* Fill our send buffer if more from client can be read. */ + if(!data->req.eos_read && !Curl_bufq_is_full(&data->req.sendbuf)) { + ssize_t nread = Curl_bufq_sipn(&data->req.sendbuf, 0, + add_from_client, data, &result); + if(nread < 0 && result != CURLE_AGAIN) + return result; + } + + result = req_flush(data); + if(result == CURLE_AGAIN) + result = CURLE_OK; + + return result; +} + +CURLcode Curl_req_abort_sending(struct Curl_easy *data) +{ + if(!data->req.upload_done) { + Curl_bufq_reset(&data->req.sendbuf); + data->req.upload_aborted = TRUE; + return req_set_upload_done(data); + } + return CURLE_OK; +} diff --git a/third_party/curl/lib/request.h b/third_party/curl/lib/request.h new file mode 100644 index 0000000..f9be6f2 --- /dev/null +++ b/third_party/curl/lib/request.h @@ -0,0 +1,227 @@ +#ifndef HEADER_CURL_REQUEST_H +#define HEADER_CURL_REQUEST_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* This file is for lib internal stuff */ + +#include "curl_setup.h" + +#include "bufq.h" + +/* forward declarations */ +struct UserDefined; + +enum expect100 { + EXP100_SEND_DATA, /* enough waiting, just send the body now */ + EXP100_AWAITING_CONTINUE, /* waiting for the 100 Continue header */ + EXP100_SENDING_REQUEST, /* still sending the request but will wait for + the 100 header once done with the request */ + EXP100_FAILED /* used on 417 Expectation Failed */ +}; + +enum upgrade101 { + UPGR101_INIT, /* default state */ + UPGR101_WS, /* upgrade to WebSockets requested */ + UPGR101_H2, /* upgrade to HTTP/2 requested */ + UPGR101_RECEIVED, /* 101 response received */ + UPGR101_WORKING /* talking upgraded protocol */ +}; + + +/* + * Request specific data in the easy handle (Curl_easy). Previously, + * these members were on the connectdata struct but since a conn struct may + * now be shared between different Curl_easys, we store connection-specific + * data here. This struct only keeps stuff that's interesting for *this* + * request, as it will be cleared between multiple ones + */ +struct SingleRequest { + curl_off_t size; /* -1 if unknown at this point */ + curl_off_t maxdownload; /* in bytes, the maximum amount of data to fetch, + -1 means unlimited */ + curl_off_t bytecount; /* total number of bytes read */ + curl_off_t writebytecount; /* number of bytes written */ + + struct curltime start; /* transfer started at this time */ + unsigned int headerbytecount; /* received server headers (not CONNECT + headers) */ + unsigned int allheadercount; /* all received headers (server + CONNECT) */ + unsigned int deductheadercount; /* this amount of bytes doesn't count when + we check if anything has been transferred + at the end of a connection. We use this + counter to make only a 100 reply (without + a following second response code) result + in a CURLE_GOT_NOTHING error code */ + int headerline; /* counts header lines to better track the + first one */ + curl_off_t offset; /* possible resume offset read from the + Content-Range: header */ + int httpversion; /* Version in response (09, 10, 11, etc.) */ + int httpcode; /* error code from the 'HTTP/1.? XXX' or + 'RTSP/1.? XXX' line */ + int keepon; + enum upgrade101 upgr101; /* 101 upgrade state */ + + /* Client Writer stack, handles transfer- and content-encodings, protocol + * checks, pausing by client callbacks. */ + struct Curl_cwriter *writer_stack; + /* Client Reader stack, handles transfer- and content-encodings, protocol + * checks, pausing by client callbacks. */ + struct Curl_creader *reader_stack; + struct bufq sendbuf; /* data which needs to be send to the server */ + size_t sendbuf_hds_len; /* amount of header bytes in sendbuf */ + time_t timeofdoc; + long bodywrites; + char *location; /* This points to an allocated version of the Location: + header data */ + char *newurl; /* Set to the new URL to use when a redirect or a retry is + wanted */ + + /* Allocated protocol-specific data. Each protocol handler makes sure this + points to data it needs. */ + union { + struct FILEPROTO *file; + struct FTP *ftp; + struct HTTP *http; + struct IMAP *imap; + struct ldapreqinfo *ldap; + struct MQTT *mqtt; + struct POP3 *pop3; + struct RTSP *rtsp; + struct smb_request *smb; + struct SMTP *smtp; + struct SSHPROTO *ssh; + struct TELNET *telnet; + } p; +#ifndef CURL_DISABLE_DOH + struct dohdata *doh; /* DoH specific data for this request */ +#endif +#ifndef CURL_DISABLE_COOKIES + unsigned char setcookies; +#endif + BIT(header); /* incoming data has HTTP header */ + BIT(done); /* request is done, e.g. no more send/recv should + * happen. This can be TRUE before `upload_done` or + * `download_done` is TRUE. */ + BIT(content_range); /* set TRUE if Content-Range: was found */ + BIT(download_done); /* set to TRUE when download is complete */ + BIT(eos_written); /* iff EOS has been written to client */ + BIT(eos_read); /* iff EOS has been read from the client */ + BIT(rewind_read); /* iff reader needs rewind at next start */ + BIT(upload_done); /* set to TRUE when all request data has been sent */ + BIT(upload_aborted); /* set to TRUE when upload was aborted. Will also + * show `upload_done` as TRUE. */ + BIT(ignorebody); /* we read a response-body but we ignore it! */ + BIT(http_bodyless); /* HTTP response status code is between 100 and 199, + 204 or 304 */ + BIT(chunk); /* if set, this is a chunked transfer-encoding */ + BIT(ignore_cl); /* ignore content-length */ + BIT(upload_chunky); /* set TRUE if we are doing chunked transfer-encoding + on upload */ + BIT(getheader); /* TRUE if header parsing is wanted */ + BIT(no_body); /* the response has no body */ + BIT(authneg); /* TRUE when the auth phase has started, which means + that we are creating a request with an auth header, + but it is not the final request in the auth + negotiation. */ + BIT(sendbuf_init); /* sendbuf is initialized */ +}; + +/** + * Initialize the state of the request for first use. + */ +void Curl_req_init(struct SingleRequest *req); + +/** + * The request is about to start. Record time and do a soft reset. + */ +CURLcode Curl_req_start(struct SingleRequest *req, + struct Curl_easy *data); + +/** + * The request may continue with a follow up. Reset + * members, but keep start time for overall duration calc. + */ +CURLcode Curl_req_soft_reset(struct SingleRequest *req, + struct Curl_easy *data); + +/** + * The request is done. If not aborted, make sure that buffers are + * flushed to the client. + * @param req the request + * @param data the transfer + * @param aborted TRUE iff the request was aborted/errored + */ +CURLcode Curl_req_done(struct SingleRequest *req, + struct Curl_easy *data, bool aborted); + +/** + * Free the state of the request, not usable afterwards. + */ +void Curl_req_free(struct SingleRequest *req, struct Curl_easy *data); + +/** + * Hard reset the state of the request to virgin state base on + * transfer settings. + */ +void Curl_req_hard_reset(struct SingleRequest *req, struct Curl_easy *data); + +#ifndef USE_HYPER +/** + * Send request headers. If not all could be sent + * they will be buffered. Use `Curl_req_flush()` to make sure + * bytes are really send. + * @param data the transfer making the request + * @param buf the complete header bytes, no body + * @return CURLE_OK (on blocking with *pnwritten == 0) or error. + */ +CURLcode Curl_req_send(struct Curl_easy *data, struct dynbuf *buf); + +#endif /* !USE_HYPER */ + +/** + * TRUE iff the request has sent all request headers and data. + */ +bool Curl_req_done_sending(struct Curl_easy *data); + +/* + * Read more from client and flush all buffered request bytes. + * @return CURLE_OK on success or the error on the sending. + * Never returns CURLE_AGAIN. + */ +CURLcode Curl_req_send_more(struct Curl_easy *data); + +/** + * TRUE iff the request wants to send, e.g. has buffered bytes. + */ +bool Curl_req_want_send(struct Curl_easy *data); + +/** + * Stop sending any more request data to the server. + * Will clear the send buffer and mark request sending as done. + */ +CURLcode Curl_req_abort_sending(struct Curl_easy *data); + +#endif /* HEADER_CURL_REQUEST_H */ diff --git a/third_party/curl/lib/rtsp.c b/third_party/curl/lib/rtsp.c new file mode 100644 index 0000000..1f162da --- /dev/null +++ b/third_party/curl/lib/rtsp.c @@ -0,0 +1,1040 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_RTSP) && !defined(USE_HYPER) + +#include "urldata.h" +#include +#include "transfer.h" +#include "sendf.h" +#include "multiif.h" +#include "http.h" +#include "url.h" +#include "progress.h" +#include "rtsp.h" +#include "strcase.h" +#include "select.h" +#include "connect.h" +#include "cfilters.h" +#include "strdup.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#define RTP_PKT_LENGTH(p) ((((unsigned int)((unsigned char)((p)[2]))) << 8) | \ + ((unsigned int)((unsigned char)((p)[3])))) + +/* protocol-specific functions set up to be called by the main engine */ +static CURLcode rtsp_do(struct Curl_easy *data, bool *done); +static CURLcode rtsp_done(struct Curl_easy *data, CURLcode, bool premature); +static CURLcode rtsp_connect(struct Curl_easy *data, bool *done); +static CURLcode rtsp_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead); +static int rtsp_getsock_do(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *socks); + +/* + * Parse and write out an RTSP response. + * @param data the transfer + * @param conn the connection + * @param buf data read from connection + * @param blen amount of data in buf + * @param is_eos TRUE iff this is the last write + * @param readmore out, TRUE iff complete buf was consumed and more data + * is needed + */ +static CURLcode rtsp_rtp_write_resp(struct Curl_easy *data, + const char *buf, + size_t blen, + bool is_eos); + +static CURLcode rtsp_setup_connection(struct Curl_easy *data, + struct connectdata *conn); +static unsigned int rtsp_conncheck(struct Curl_easy *data, + struct connectdata *check, + unsigned int checks_to_perform); + +/* this returns the socket to wait for in the DO and DOING state for the multi + interface and then we're always _sending_ a request and thus we wait for + the single socket to become writable only */ +static int rtsp_getsock_do(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t *socks) +{ + /* write mode */ + (void)data; + socks[0] = conn->sock[FIRSTSOCKET]; + return GETSOCK_WRITESOCK(0); +} + +static +CURLcode rtp_client_write(struct Curl_easy *data, const char *ptr, size_t len); +static +CURLcode rtsp_parse_transport(struct Curl_easy *data, const char *transport); + + +/* + * RTSP handler interface. + */ +const struct Curl_handler Curl_handler_rtsp = { + "rtsp", /* scheme */ + rtsp_setup_connection, /* setup_connection */ + rtsp_do, /* do_it */ + rtsp_done, /* done */ + ZERO_NULL, /* do_more */ + rtsp_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + rtsp_getsock_do, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + rtsp_disconnect, /* disconnect */ + rtsp_rtp_write_resp, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + rtsp_conncheck, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_RTSP, /* defport */ + CURLPROTO_RTSP, /* protocol */ + CURLPROTO_RTSP, /* family */ + PROTOPT_NONE /* flags */ +}; + +#define MAX_RTP_BUFFERSIZE 1000000 /* arbitrary */ + +static CURLcode rtsp_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + struct RTSP *rtsp; + (void)conn; + + data->req.p.rtsp = rtsp = calloc(1, sizeof(struct RTSP)); + if(!rtsp) + return CURLE_OUT_OF_MEMORY; + + Curl_dyn_init(&conn->proto.rtspc.buf, MAX_RTP_BUFFERSIZE); + return CURLE_OK; +} + + +/* + * Function to check on various aspects of a connection. + */ +static unsigned int rtsp_conncheck(struct Curl_easy *data, + struct connectdata *conn, + unsigned int checks_to_perform) +{ + unsigned int ret_val = CONNRESULT_NONE; + (void)data; + + if(checks_to_perform & CONNCHECK_ISDEAD) { + bool input_pending; + if(!Curl_conn_is_alive(data, conn, &input_pending)) + ret_val |= CONNRESULT_DEAD; + } + + return ret_val; +} + + +static CURLcode rtsp_connect(struct Curl_easy *data, bool *done) +{ + CURLcode httpStatus; + + httpStatus = Curl_http_connect(data, done); + + /* Initialize the CSeq if not already done */ + if(data->state.rtsp_next_client_CSeq == 0) + data->state.rtsp_next_client_CSeq = 1; + if(data->state.rtsp_next_server_CSeq == 0) + data->state.rtsp_next_server_CSeq = 1; + + data->conn->proto.rtspc.rtp_channel = -1; + + return httpStatus; +} + +static CURLcode rtsp_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead) +{ + (void) dead; + (void) data; + Curl_dyn_free(&conn->proto.rtspc.buf); + return CURLE_OK; +} + + +static CURLcode rtsp_done(struct Curl_easy *data, + CURLcode status, bool premature) +{ + struct RTSP *rtsp = data->req.p.rtsp; + CURLcode httpStatus; + + /* Bypass HTTP empty-reply checks on receive */ + if(data->set.rtspreq == RTSPREQ_RECEIVE) + premature = TRUE; + + httpStatus = Curl_http_done(data, status, premature); + + if(rtsp && !status && !httpStatus) { + /* Check the sequence numbers */ + long CSeq_sent = rtsp->CSeq_sent; + long CSeq_recv = rtsp->CSeq_recv; + if((data->set.rtspreq != RTSPREQ_RECEIVE) && (CSeq_sent != CSeq_recv)) { + failf(data, + "The CSeq of this request %ld did not match the response %ld", + CSeq_sent, CSeq_recv); + return CURLE_RTSP_CSEQ_ERROR; + } + if(data->set.rtspreq == RTSPREQ_RECEIVE && + (data->conn->proto.rtspc.rtp_channel == -1)) { + infof(data, "Got an RTP Receive with a CSeq of %ld", CSeq_recv); + } + } + + return httpStatus; +} + +static CURLcode rtsp_do(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + Curl_RtspReq rtspreq = data->set.rtspreq; + struct RTSP *rtsp = data->req.p.rtsp; + struct dynbuf req_buffer; + + const char *p_request = NULL; + const char *p_session_id = NULL; + const char *p_accept = NULL; + const char *p_accept_encoding = NULL; + const char *p_range = NULL; + const char *p_referrer = NULL; + const char *p_stream_uri = NULL; + const char *p_transport = NULL; + const char *p_uagent = NULL; + const char *p_proxyuserpwd = NULL; + const char *p_userpwd = NULL; + + *done = TRUE; + /* Initialize a dynamic send buffer */ + Curl_dyn_init(&req_buffer, DYN_RTSP_REQ_HEADER); + + rtsp->CSeq_sent = data->state.rtsp_next_client_CSeq; + rtsp->CSeq_recv = 0; + + /* Setup the first_* fields to allow auth details get sent + to this origin */ + + if(!data->state.first_host) { + data->state.first_host = strdup(conn->host.name); + if(!data->state.first_host) + return CURLE_OUT_OF_MEMORY; + + data->state.first_remote_port = conn->remote_port; + data->state.first_remote_protocol = conn->handler->protocol; + } + + /* Setup the 'p_request' pointer to the proper p_request string + * Since all RTSP requests are included here, there is no need to + * support custom requests like HTTP. + **/ + data->req.no_body = TRUE; /* most requests don't contain a body */ + switch(rtspreq) { + default: + failf(data, "Got invalid RTSP request"); + return CURLE_BAD_FUNCTION_ARGUMENT; + case RTSPREQ_OPTIONS: + p_request = "OPTIONS"; + break; + case RTSPREQ_DESCRIBE: + p_request = "DESCRIBE"; + data->req.no_body = FALSE; + break; + case RTSPREQ_ANNOUNCE: + p_request = "ANNOUNCE"; + break; + case RTSPREQ_SETUP: + p_request = "SETUP"; + break; + case RTSPREQ_PLAY: + p_request = "PLAY"; + break; + case RTSPREQ_PAUSE: + p_request = "PAUSE"; + break; + case RTSPREQ_TEARDOWN: + p_request = "TEARDOWN"; + break; + case RTSPREQ_GET_PARAMETER: + /* GET_PARAMETER's no_body status is determined later */ + p_request = "GET_PARAMETER"; + data->req.no_body = FALSE; + break; + case RTSPREQ_SET_PARAMETER: + p_request = "SET_PARAMETER"; + break; + case RTSPREQ_RECORD: + p_request = "RECORD"; + break; + case RTSPREQ_RECEIVE: + p_request = ""; + /* Treat interleaved RTP as body */ + data->req.no_body = FALSE; + break; + case RTSPREQ_LAST: + failf(data, "Got invalid RTSP request: RTSPREQ_LAST"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + if(rtspreq == RTSPREQ_RECEIVE) { + Curl_xfer_setup(data, FIRSTSOCKET, -1, TRUE, -1); + goto out; + } + + p_session_id = data->set.str[STRING_RTSP_SESSION_ID]; + if(!p_session_id && + (rtspreq & ~(RTSPREQ_OPTIONS | RTSPREQ_DESCRIBE | RTSPREQ_SETUP))) { + failf(data, "Refusing to issue an RTSP request [%s] without a session ID.", + p_request); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + + /* Stream URI. Default to server '*' if not specified */ + if(data->set.str[STRING_RTSP_STREAM_URI]) { + p_stream_uri = data->set.str[STRING_RTSP_STREAM_URI]; + } + else { + p_stream_uri = "*"; + } + + /* Transport Header for SETUP requests */ + p_transport = Curl_checkheaders(data, STRCONST("Transport")); + if(rtspreq == RTSPREQ_SETUP && !p_transport) { + /* New Transport: setting? */ + if(data->set.str[STRING_RTSP_TRANSPORT]) { + Curl_safefree(data->state.aptr.rtsp_transport); + + data->state.aptr.rtsp_transport = + aprintf("Transport: %s\r\n", + data->set.str[STRING_RTSP_TRANSPORT]); + if(!data->state.aptr.rtsp_transport) + return CURLE_OUT_OF_MEMORY; + } + else { + failf(data, + "Refusing to issue an RTSP SETUP without a Transport: header."); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + + p_transport = data->state.aptr.rtsp_transport; + } + + /* Accept Headers for DESCRIBE requests */ + if(rtspreq == RTSPREQ_DESCRIBE) { + /* Accept Header */ + p_accept = Curl_checkheaders(data, STRCONST("Accept"))? + NULL:"Accept: application/sdp\r\n"; + + /* Accept-Encoding header */ + if(!Curl_checkheaders(data, STRCONST("Accept-Encoding")) && + data->set.str[STRING_ENCODING]) { + Curl_safefree(data->state.aptr.accept_encoding); + data->state.aptr.accept_encoding = + aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]); + + if(!data->state.aptr.accept_encoding) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + p_accept_encoding = data->state.aptr.accept_encoding; + } + } + + /* The User-Agent string might have been allocated in url.c already, because + it might have been used in the proxy connect, but if we have got a header + with the user-agent string specified, we erase the previously made string + here. */ + if(Curl_checkheaders(data, STRCONST("User-Agent")) && + data->state.aptr.uagent) { + Curl_safefree(data->state.aptr.uagent); + } + else if(!Curl_checkheaders(data, STRCONST("User-Agent")) && + data->set.str[STRING_USERAGENT]) { + p_uagent = data->state.aptr.uagent; + } + + /* setup the authentication headers */ + result = Curl_http_output_auth(data, conn, p_request, HTTPREQ_GET, + p_stream_uri, FALSE); + if(result) + goto out; + +#ifndef CURL_DISABLE_PROXY + p_proxyuserpwd = data->state.aptr.proxyuserpwd; +#endif + p_userpwd = data->state.aptr.userpwd; + + /* Referrer */ + Curl_safefree(data->state.aptr.ref); + if(data->state.referer && !Curl_checkheaders(data, STRCONST("Referer"))) + data->state.aptr.ref = aprintf("Referer: %s\r\n", data->state.referer); + + p_referrer = data->state.aptr.ref; + + /* + * Range Header + * Only applies to PLAY, PAUSE, RECORD + * + * Go ahead and use the Range stuff supplied for HTTP + */ + if(data->state.use_range && + (rtspreq & (RTSPREQ_PLAY | RTSPREQ_PAUSE | RTSPREQ_RECORD))) { + + /* Check to see if there is a range set in the custom headers */ + if(!Curl_checkheaders(data, STRCONST("Range")) && data->state.range) { + Curl_safefree(data->state.aptr.rangeline); + data->state.aptr.rangeline = aprintf("Range: %s\r\n", data->state.range); + p_range = data->state.aptr.rangeline; + } + } + + /* + * Sanity check the custom headers + */ + if(Curl_checkheaders(data, STRCONST("CSeq"))) { + failf(data, "CSeq cannot be set as a custom header."); + result = CURLE_RTSP_CSEQ_ERROR; + goto out; + } + if(Curl_checkheaders(data, STRCONST("Session"))) { + failf(data, "Session ID cannot be set as a custom header."); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + + result = + Curl_dyn_addf(&req_buffer, + "%s %s RTSP/1.0\r\n" /* Request Stream-URI RTSP/1.0 */ + "CSeq: %ld\r\n", /* CSeq */ + p_request, p_stream_uri, rtsp->CSeq_sent); + if(result) + goto out; + + /* + * Rather than do a normal alloc line, keep the session_id unformatted + * to make comparison easier + */ + if(p_session_id) { + result = Curl_dyn_addf(&req_buffer, "Session: %s\r\n", p_session_id); + if(result) + goto out; + } + + /* + * Shared HTTP-like options + */ + result = Curl_dyn_addf(&req_buffer, + "%s" /* transport */ + "%s" /* accept */ + "%s" /* accept-encoding */ + "%s" /* range */ + "%s" /* referrer */ + "%s" /* user-agent */ + "%s" /* proxyuserpwd */ + "%s" /* userpwd */ + , + p_transport ? p_transport : "", + p_accept ? p_accept : "", + p_accept_encoding ? p_accept_encoding : "", + p_range ? p_range : "", + p_referrer ? p_referrer : "", + p_uagent ? p_uagent : "", + p_proxyuserpwd ? p_proxyuserpwd : "", + p_userpwd ? p_userpwd : ""); + + /* + * Free userpwd now --- cannot reuse this for Negotiate and possibly NTLM + * with basic and digest, it will be freed anyway by the next request + */ + Curl_safefree(data->state.aptr.userpwd); + + if(result) + goto out; + + if((rtspreq == RTSPREQ_SETUP) || (rtspreq == RTSPREQ_DESCRIBE)) { + result = Curl_add_timecondition(data, &req_buffer); + if(result) + goto out; + } + + result = Curl_add_custom_headers(data, FALSE, &req_buffer); + if(result) + goto out; + + if(rtspreq == RTSPREQ_ANNOUNCE || + rtspreq == RTSPREQ_SET_PARAMETER || + rtspreq == RTSPREQ_GET_PARAMETER) { + curl_off_t req_clen; /* request content length */ + + if(data->state.upload) { + req_clen = data->state.infilesize; + data->state.httpreq = HTTPREQ_PUT; + result = Curl_creader_set_fread(data, req_clen); + if(result) + goto out; + } + else { + if(data->set.postfields) { + size_t plen = strlen(data->set.postfields); + req_clen = (curl_off_t)plen; + result = Curl_creader_set_buf(data, data->set.postfields, plen); + } + else if(data->state.infilesize >= 0) { + req_clen = data->state.infilesize; + result = Curl_creader_set_fread(data, req_clen); + } + else { + req_clen = 0; + result = Curl_creader_set_null(data); + } + if(result) + goto out; + } + + if(req_clen > 0) { + /* As stated in the http comments, it is probably not wise to + * actually set a custom Content-Length in the headers */ + if(!Curl_checkheaders(data, STRCONST("Content-Length"))) { + result = + Curl_dyn_addf(&req_buffer, + "Content-Length: %" CURL_FORMAT_CURL_OFF_T"\r\n", + req_clen); + if(result) + goto out; + } + + if(rtspreq == RTSPREQ_SET_PARAMETER || + rtspreq == RTSPREQ_GET_PARAMETER) { + if(!Curl_checkheaders(data, STRCONST("Content-Type"))) { + result = Curl_dyn_addn(&req_buffer, + STRCONST("Content-Type: " + "text/parameters\r\n")); + if(result) + goto out; + } + } + + if(rtspreq == RTSPREQ_ANNOUNCE) { + if(!Curl_checkheaders(data, STRCONST("Content-Type"))) { + result = Curl_dyn_addn(&req_buffer, + STRCONST("Content-Type: " + "application/sdp\r\n")); + if(result) + goto out; + } + } + } + else if(rtspreq == RTSPREQ_GET_PARAMETER) { + /* Check for an empty GET_PARAMETER (heartbeat) request */ + data->state.httpreq = HTTPREQ_HEAD; + data->req.no_body = TRUE; + } + } + else { + result = Curl_creader_set_null(data); + if(result) + goto out; + } + + /* Finish the request buffer */ + result = Curl_dyn_addn(&req_buffer, STRCONST("\r\n")); + if(result) + goto out; + + Curl_xfer_setup(data, FIRSTSOCKET, -1, TRUE, FIRSTSOCKET); + + /* issue the request */ + result = Curl_req_send(data, &req_buffer); + if(result) { + failf(data, "Failed sending RTSP request"); + goto out; + } + + /* Increment the CSeq on success */ + data->state.rtsp_next_client_CSeq++; + + if(data->req.writebytecount) { + /* if a request-body has been sent off, we make sure this progress is + noted properly */ + Curl_pgrsSetUploadCounter(data, data->req.writebytecount); + if(Curl_pgrsUpdate(data)) + result = CURLE_ABORTED_BY_CALLBACK; + } +out: + Curl_dyn_free(&req_buffer); + return result; +} + +/** + * write any BODY bytes missing to the client, ignore the rest. + */ +static CURLcode rtp_write_body_junk(struct Curl_easy *data, + const char *buf, + size_t blen) +{ + struct rtsp_conn *rtspc = &(data->conn->proto.rtspc); + curl_off_t body_remain; + bool in_body; + + in_body = (data->req.headerline && !rtspc->in_header) && + (data->req.size >= 0) && + (data->req.bytecount < data->req.size); + body_remain = in_body? (data->req.size - data->req.bytecount) : 0; + DEBUGASSERT(body_remain >= 0); + if(body_remain) { + if((curl_off_t)blen > body_remain) + blen = (size_t)body_remain; + return Curl_client_write(data, CLIENTWRITE_BODY, (char *)buf, blen); + } + return CURLE_OK; +} + +static CURLcode rtsp_filter_rtp(struct Curl_easy *data, + const char *buf, + size_t blen, + size_t *pconsumed) +{ + struct rtsp_conn *rtspc = &(data->conn->proto.rtspc); + CURLcode result = CURLE_OK; + size_t skip_len = 0; + + *pconsumed = 0; + while(blen) { + bool in_body = (data->req.headerline && !rtspc->in_header) && + (data->req.size >= 0) && + (data->req.bytecount < data->req.size); + switch(rtspc->state) { + + case RTP_PARSE_SKIP: { + DEBUGASSERT(Curl_dyn_len(&rtspc->buf) == 0); + while(blen && buf[0] != '$') { + if(!in_body && buf[0] == 'R' && + data->set.rtspreq != RTSPREQ_RECEIVE) { + if(strncmp(buf, "RTSP/", (blen < 5) ? blen : 5) == 0) { + /* This could be the next response, no consume and return */ + if(*pconsumed) { + DEBUGF(infof(data, "RTP rtsp_filter_rtp[SKIP] RTSP/ prefix, " + "skipping %zd bytes of junk", *pconsumed)); + } + rtspc->state = RTP_PARSE_SKIP; + rtspc->in_header = TRUE; + goto out; + } + } + /* junk/BODY, consume without buffering */ + *pconsumed += 1; + ++buf; + --blen; + ++skip_len; + } + if(blen && buf[0] == '$') { + /* possible start of an RTP message, buffer */ + if(skip_len) { + /* end of junk/BODY bytes, flush */ + result = rtp_write_body_junk(data, + (char *)(buf - skip_len), skip_len); + skip_len = 0; + if(result) + goto out; + } + if(Curl_dyn_addn(&rtspc->buf, buf, 1)) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + *pconsumed += 1; + ++buf; + --blen; + rtspc->state = RTP_PARSE_CHANNEL; + } + break; + } + + case RTP_PARSE_CHANNEL: { + int idx = ((unsigned char)buf[0]) / 8; + int off = ((unsigned char)buf[0]) % 8; + DEBUGASSERT(Curl_dyn_len(&rtspc->buf) == 1); + if(!(data->state.rtp_channel_mask[idx] & (1 << off))) { + /* invalid channel number, junk or BODY data */ + rtspc->state = RTP_PARSE_SKIP; + DEBUGASSERT(skip_len == 0); + /* we do not consume this byte, it is BODY data */ + DEBUGF(infof(data, "RTSP: invalid RTP channel %d, skipping", idx)); + if(*pconsumed == 0) { + /* We did not consume the initial '$' in our buffer, but had + * it from an earlier call. We cannot un-consume it and have + * to write it directly as BODY data */ + result = rtp_write_body_junk(data, Curl_dyn_ptr(&rtspc->buf), 1); + if(result) + goto out; + } + else { + /* count the '$' as skip and continue */ + skip_len = 1; + } + Curl_dyn_free(&rtspc->buf); + break; + } + /* a valid channel, so we expect this to be a real RTP message */ + rtspc->rtp_channel = (unsigned char)buf[0]; + if(Curl_dyn_addn(&rtspc->buf, buf, 1)) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + *pconsumed += 1; + ++buf; + --blen; + rtspc->state = RTP_PARSE_LEN; + break; + } + + case RTP_PARSE_LEN: { + size_t rtp_len = Curl_dyn_len(&rtspc->buf); + const char *rtp_buf; + DEBUGASSERT(rtp_len >= 2 && rtp_len < 4); + if(Curl_dyn_addn(&rtspc->buf, buf, 1)) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + *pconsumed += 1; + ++buf; + --blen; + if(rtp_len == 2) + break; + rtp_buf = Curl_dyn_ptr(&rtspc->buf); + rtspc->rtp_len = RTP_PKT_LENGTH(rtp_buf) + 4; + rtspc->state = RTP_PARSE_DATA; + break; + } + + case RTP_PARSE_DATA: { + size_t rtp_len = Curl_dyn_len(&rtspc->buf); + size_t needed; + DEBUGASSERT(rtp_len < rtspc->rtp_len); + needed = rtspc->rtp_len - rtp_len; + if(needed <= blen) { + if(Curl_dyn_addn(&rtspc->buf, buf, needed)) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + *pconsumed += needed; + buf += needed; + blen -= needed; + /* complete RTP message in buffer */ + DEBUGF(infof(data, "RTP write channel %d rtp_len %zu", + rtspc->rtp_channel, rtspc->rtp_len)); + result = rtp_client_write(data, Curl_dyn_ptr(&rtspc->buf), + rtspc->rtp_len); + Curl_dyn_free(&rtspc->buf); + rtspc->state = RTP_PARSE_SKIP; + if(result) + goto out; + } + else { + if(Curl_dyn_addn(&rtspc->buf, buf, blen)) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + *pconsumed += blen; + buf += blen; + blen = 0; + } + break; + } + + default: + DEBUGASSERT(0); + return CURLE_RECV_ERROR; + } + } +out: + if(!result && skip_len) + result = rtp_write_body_junk(data, (char *)(buf - skip_len), skip_len); + return result; +} + +static CURLcode rtsp_rtp_write_resp(struct Curl_easy *data, + const char *buf, + size_t blen, + bool is_eos) +{ + struct rtsp_conn *rtspc = &(data->conn->proto.rtspc); + CURLcode result = CURLE_OK; + size_t consumed = 0; + + if(!data->req.header) + rtspc->in_header = FALSE; + if(!blen) { + goto out; + } + + DEBUGF(infof(data, "rtsp_rtp_write_resp(len=%zu, in_header=%d, eos=%d)", + blen, rtspc->in_header, is_eos)); + + /* If header parsing is not ongoing, extract RTP messages */ + if(!rtspc->in_header) { + result = rtsp_filter_rtp(data, buf, blen, &consumed); + if(result) + goto out; + buf += consumed; + blen -= consumed; + /* either we consumed all or are at the start of header parsing */ + if(blen && !data->req.header) + DEBUGF(infof(data, "RTSP: %zu bytes, possibly excess in response body", + blen)); + } + + /* we want to parse headers, do so */ + if(data->req.header && blen) { + rtspc->in_header = TRUE; + result = Curl_http_write_resp_hds(data, buf, blen, &consumed); + if(result) + goto out; + + buf += consumed; + blen -= consumed; + + if(!data->req.header) + rtspc->in_header = FALSE; + + if(!rtspc->in_header) { + /* If header parsing is done, extract interleaved RTP messages */ + if(data->req.size <= -1) { + /* Respect section 4.4 of rfc2326: If the Content-Length header is + absent, a length 0 must be assumed. */ + data->req.size = 0; + data->req.download_done = TRUE; + } + result = rtsp_filter_rtp(data, buf, blen, &consumed); + if(result) + goto out; + blen -= consumed; + } + } + + if(rtspc->state != RTP_PARSE_SKIP) + data->req.done = FALSE; + /* we SHOULD have consumed all bytes, unless the response is borked. + * In which case we write out the left over bytes, letting the client + * writer deal with it (it will report EXCESS and fail the transfer). */ + DEBUGF(infof(data, "rtsp_rtp_write_resp(len=%zu, in_header=%d, done=%d " + " rtspc->state=%d, req.size=%" CURL_FORMAT_CURL_OFF_T ")", + blen, rtspc->in_header, data->req.done, rtspc->state, + data->req.size)); + if(!result && (is_eos || blen)) { + result = Curl_client_write(data, CLIENTWRITE_BODY| + (is_eos? CLIENTWRITE_EOS:0), + (char *)buf, blen); + } + +out: + if((data->set.rtspreq == RTSPREQ_RECEIVE) && + (rtspc->state == RTP_PARSE_SKIP)) { + /* In special mode RECEIVE, we just process one chunk of network + * data, so we stop the transfer here, if we have no incomplete + * RTP message pending. */ + data->req.download_done = TRUE; + } + return result; +} + +static +CURLcode rtp_client_write(struct Curl_easy *data, const char *ptr, size_t len) +{ + size_t wrote; + curl_write_callback writeit; + void *user_ptr; + + if(len == 0) { + failf(data, "Cannot write a 0 size RTP packet."); + return CURLE_WRITE_ERROR; + } + + /* If the user has configured CURLOPT_INTERLEAVEFUNCTION then use that + function and any configured CURLOPT_INTERLEAVEDATA to write out the RTP + data. Otherwise, use the CURLOPT_WRITEFUNCTION with the CURLOPT_WRITEDATA + pointer to write out the RTP data. */ + if(data->set.fwrite_rtp) { + writeit = data->set.fwrite_rtp; + user_ptr = data->set.rtp_out; + } + else { + writeit = data->set.fwrite_func; + user_ptr = data->set.out; + } + + Curl_set_in_callback(data, true); + wrote = writeit((char *)ptr, 1, len, user_ptr); + Curl_set_in_callback(data, false); + + if(CURL_WRITEFUNC_PAUSE == wrote) { + failf(data, "Cannot pause RTP"); + return CURLE_WRITE_ERROR; + } + + if(wrote != len) { + failf(data, "Failed writing RTP data"); + return CURLE_WRITE_ERROR; + } + + return CURLE_OK; +} + +CURLcode Curl_rtsp_parseheader(struct Curl_easy *data, const char *header) +{ + if(checkprefix("CSeq:", header)) { + long CSeq = 0; + char *endp; + const char *p = &header[5]; + while(ISBLANK(*p)) + p++; + CSeq = strtol(p, &endp, 10); + if(p != endp) { + struct RTSP *rtsp = data->req.p.rtsp; + rtsp->CSeq_recv = CSeq; /* mark the request */ + data->state.rtsp_CSeq_recv = CSeq; /* update the handle */ + } + else { + failf(data, "Unable to read the CSeq header: [%s]", header); + return CURLE_RTSP_CSEQ_ERROR; + } + } + else if(checkprefix("Session:", header)) { + const char *start, *end; + size_t idlen; + + /* Find the first non-space letter */ + start = header + 8; + while(*start && ISBLANK(*start)) + start++; + + if(!*start) { + failf(data, "Got a blank Session ID"); + return CURLE_RTSP_SESSION_ERROR; + } + + /* Find the end of Session ID + * + * Allow any non whitespace content, up to the field separator or end of + * line. RFC 2326 isn't 100% clear on the session ID and for example + * gstreamer does url-encoded session ID's not covered by the standard. + */ + end = start; + while(*end && *end != ';' && !ISSPACE(*end)) + end++; + idlen = end - start; + + if(data->set.str[STRING_RTSP_SESSION_ID]) { + + /* If the Session ID is set, then compare */ + if(strlen(data->set.str[STRING_RTSP_SESSION_ID]) != idlen || + strncmp(start, data->set.str[STRING_RTSP_SESSION_ID], idlen)) { + failf(data, "Got RTSP Session ID Line [%s], but wanted ID [%s]", + start, data->set.str[STRING_RTSP_SESSION_ID]); + return CURLE_RTSP_SESSION_ERROR; + } + } + else { + /* If the Session ID is not set, and we find it in a response, then set + * it. + */ + + /* Copy the id substring into a new buffer */ + data->set.str[STRING_RTSP_SESSION_ID] = Curl_memdup0(start, idlen); + if(!data->set.str[STRING_RTSP_SESSION_ID]) + return CURLE_OUT_OF_MEMORY; + } + } + else if(checkprefix("Transport:", header)) { + CURLcode result; + result = rtsp_parse_transport(data, header + 10); + if(result) + return result; + } + return CURLE_OK; +} + +static +CURLcode rtsp_parse_transport(struct Curl_easy *data, const char *transport) +{ + /* If we receive multiple Transport response-headers, the linterleaved + channels of each response header is recorded and used together for + subsequent data validity checks.*/ + /* e.g.: ' RTP/AVP/TCP;unicast;interleaved=5-6' */ + const char *start, *end; + start = transport; + while(start && *start) { + while(*start && ISBLANK(*start) ) + start++; + end = strchr(start, ';'); + if(checkprefix("interleaved=", start)) { + long chan1, chan2, chan; + char *endp; + const char *p = start + 12; + chan1 = strtol(p, &endp, 10); + if(p != endp && chan1 >= 0 && chan1 <= 255) { + unsigned char *rtp_channel_mask = data->state.rtp_channel_mask; + chan2 = chan1; + if(*endp == '-') { + p = endp + 1; + chan2 = strtol(p, &endp, 10); + if(p == endp || chan2 < 0 || chan2 > 255) { + infof(data, "Unable to read the interleaved parameter from " + "Transport header: [%s]", transport); + chan2 = chan1; + } + } + for(chan = chan1; chan <= chan2; chan++) { + long idx = chan / 8; + long off = chan % 8; + rtp_channel_mask[idx] |= (unsigned char)(1 << off); + } + } + else { + infof(data, "Unable to read the interleaved parameter from " + "Transport header: [%s]", transport); + } + break; + } + /* skip to next parameter */ + start = (!end) ? end : (end + 1); + } + return CURLE_OK; +} + + +#endif /* CURL_DISABLE_RTSP or using Hyper */ diff --git a/third_party/curl/lib/rtsp.h b/third_party/curl/lib/rtsp.h new file mode 100644 index 0000000..b1ffa5c --- /dev/null +++ b/third_party/curl/lib/rtsp.h @@ -0,0 +1,80 @@ +#ifndef HEADER_CURL_RTSP_H +#define HEADER_CURL_RTSP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifdef USE_HYPER +#define CURL_DISABLE_RTSP 1 +#endif + +#ifndef CURL_DISABLE_RTSP + +extern const struct Curl_handler Curl_handler_rtsp; + +CURLcode Curl_rtsp_parseheader(struct Curl_easy *data, const char *header); + +#else +/* disabled */ +#define Curl_rtsp_parseheader(x,y) CURLE_NOT_BUILT_IN + +#endif /* CURL_DISABLE_RTSP */ + +typedef enum { + RTP_PARSE_SKIP, + RTP_PARSE_CHANNEL, + RTP_PARSE_LEN, + RTP_PARSE_DATA +} rtp_parse_st; +/* + * RTSP Connection data + * + * Currently, only used for tracking incomplete RTP data reads + */ +struct rtsp_conn { + struct dynbuf buf; + int rtp_channel; + size_t rtp_len; + rtp_parse_st state; + BIT(in_header); +}; + +/**************************************************************************** + * RTSP unique setup + ***************************************************************************/ +struct RTSP { + /* + * http_wrapper MUST be the first element of this structure for the wrap + * logic to work. In this way, we get a cheap polymorphism because + * &(data->state.proto.rtsp) == &(data->state.proto.http) per the C spec + * + * HTTP functions can safely treat this as an HTTP struct, but RTSP aware + * functions can also index into the later elements. + */ + struct HTTP http_wrapper; /* wrap HTTP to do the heavy lifting */ + + long CSeq_sent; /* CSeq of this request */ + long CSeq_recv; /* CSeq received */ +}; + + +#endif /* HEADER_CURL_RTSP_H */ diff --git a/third_party/curl/lib/select.c b/third_party/curl/lib/select.c new file mode 100644 index 0000000..d92e745 --- /dev/null +++ b/third_party/curl/lib/select.c @@ -0,0 +1,403 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif + +#if !defined(HAVE_SELECT) && !defined(HAVE_POLL_FINE) +#error "We can't compile without select() or poll() support." +#endif + +#ifdef MSDOS +#include /* delay() */ +#endif + +#include + +#include "urldata.h" +#include "connect.h" +#include "select.h" +#include "timediff.h" +#include "warnless.h" + +/* + * Internal function used for waiting a specific amount of ms + * in Curl_socket_check() and Curl_poll() when no file descriptor + * is provided to wait on, just being used to delay execution. + * WinSock select() and poll() timeout mechanisms need a valid + * socket descriptor in a not null file descriptor set to work. + * Waiting indefinitely with this function is not allowed, a + * zero or negative timeout value will return immediately. + * Timeout resolution, accuracy, as well as maximum supported + * value is system dependent, neither factor is a critical issue + * for the intended use of this function in the library. + * + * Return values: + * -1 = system call error, or invalid timeout value + * 0 = specified timeout has elapsed, or interrupted + */ +int Curl_wait_ms(timediff_t timeout_ms) +{ + int r = 0; + + if(!timeout_ms) + return 0; + if(timeout_ms < 0) { + SET_SOCKERRNO(EINVAL); + return -1; + } +#if defined(MSDOS) + delay(timeout_ms); +#elif defined(_WIN32) + /* prevent overflow, timeout_ms is typecast to ULONG/DWORD. */ +#if TIMEDIFF_T_MAX >= ULONG_MAX + if(timeout_ms >= ULONG_MAX) + timeout_ms = ULONG_MAX-1; + /* don't use ULONG_MAX, because that is equal to INFINITE */ +#endif + Sleep((ULONG)timeout_ms); +#else +#if defined(HAVE_POLL_FINE) + /* prevent overflow, timeout_ms is typecast to int. */ +#if TIMEDIFF_T_MAX > INT_MAX + if(timeout_ms > INT_MAX) + timeout_ms = INT_MAX; +#endif + r = poll(NULL, 0, (int)timeout_ms); +#else + { + struct timeval pending_tv; + r = select(0, NULL, NULL, NULL, curlx_mstotv(&pending_tv, timeout_ms)); + } +#endif /* HAVE_POLL_FINE */ +#endif /* USE_WINSOCK */ + if(r) { + if((r == -1) && (SOCKERRNO == EINTR)) + /* make EINTR from select or poll not a "lethal" error */ + r = 0; + else + r = -1; + } + return r; +} + +#ifndef HAVE_POLL_FINE +/* + * This is a wrapper around select() to aid in Windows compatibility. + * A negative timeout value makes this function wait indefinitely, + * unless no valid file descriptor is given, when this happens the + * negative timeout is ignored and the function times out immediately. + * + * Return values: + * -1 = system call error or fd >= FD_SETSIZE + * 0 = timeout + * N = number of signalled file descriptors + */ +static int our_select(curl_socket_t maxfd, /* highest socket number */ + fd_set *fds_read, /* sockets ready for reading */ + fd_set *fds_write, /* sockets ready for writing */ + fd_set *fds_err, /* sockets with errors */ + timediff_t timeout_ms) /* milliseconds to wait */ +{ + struct timeval pending_tv; + struct timeval *ptimeout; + +#ifdef USE_WINSOCK + /* WinSock select() can't handle zero events. See the comment below. */ + if((!fds_read || fds_read->fd_count == 0) && + (!fds_write || fds_write->fd_count == 0) && + (!fds_err || fds_err->fd_count == 0)) { + /* no sockets, just wait */ + return Curl_wait_ms(timeout_ms); + } +#endif + + ptimeout = curlx_mstotv(&pending_tv, timeout_ms); + +#ifdef USE_WINSOCK + /* WinSock select() must not be called with an fd_set that contains zero + fd flags, or it will return WSAEINVAL. But, it also can't be called + with no fd_sets at all! From the documentation: + + Any two of the parameters, readfds, writefds, or exceptfds, can be + given as null. At least one must be non-null, and any non-null + descriptor set must contain at least one handle to a socket. + + It is unclear why WinSock doesn't just handle this for us instead of + calling this an error. Luckily, with WinSock, we can _also_ ask how + many bits are set on an fd_set. So, let's just check it beforehand. + */ + return select((int)maxfd + 1, + fds_read && fds_read->fd_count ? fds_read : NULL, + fds_write && fds_write->fd_count ? fds_write : NULL, + fds_err && fds_err->fd_count ? fds_err : NULL, ptimeout); +#else + return select((int)maxfd + 1, fds_read, fds_write, fds_err, ptimeout); +#endif +} + +#endif + +/* + * Wait for read or write events on a set of file descriptors. It uses poll() + * when a fine poll() is available, in order to avoid limits with FD_SETSIZE, + * otherwise select() is used. An error is returned if select() is being used + * and a file descriptor is too large for FD_SETSIZE. + * + * A negative timeout value makes this function wait indefinitely, + * unless no valid file descriptor is given, when this happens the + * negative timeout is ignored and the function times out immediately. + * + * Return values: + * -1 = system call error or fd >= FD_SETSIZE + * 0 = timeout + * [bitmask] = action as described below + * + * CURL_CSELECT_IN - first socket is readable + * CURL_CSELECT_IN2 - second socket is readable + * CURL_CSELECT_OUT - write socket is writable + * CURL_CSELECT_ERR - an error condition occurred + */ +int Curl_socket_check(curl_socket_t readfd0, /* two sockets to read from */ + curl_socket_t readfd1, + curl_socket_t writefd, /* socket to write to */ + timediff_t timeout_ms) /* milliseconds to wait */ +{ + struct pollfd pfd[3]; + int num; + int r; + + if((readfd0 == CURL_SOCKET_BAD) && (readfd1 == CURL_SOCKET_BAD) && + (writefd == CURL_SOCKET_BAD)) { + /* no sockets, just wait */ + return Curl_wait_ms(timeout_ms); + } + + /* Avoid initial timestamp, avoid Curl_now() call, when elapsed + time in this function does not need to be measured. This happens + when function is called with a zero timeout or a negative timeout + value indicating a blocking call should be performed. */ + + num = 0; + if(readfd0 != CURL_SOCKET_BAD) { + pfd[num].fd = readfd0; + pfd[num].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI; + pfd[num].revents = 0; + num++; + } + if(readfd1 != CURL_SOCKET_BAD) { + pfd[num].fd = readfd1; + pfd[num].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI; + pfd[num].revents = 0; + num++; + } + if(writefd != CURL_SOCKET_BAD) { + pfd[num].fd = writefd; + pfd[num].events = POLLWRNORM|POLLOUT|POLLPRI; + pfd[num].revents = 0; + num++; + } + + r = Curl_poll(pfd, num, timeout_ms); + if(r <= 0) + return r; + + r = 0; + num = 0; + if(readfd0 != CURL_SOCKET_BAD) { + if(pfd[num].revents & (POLLRDNORM|POLLIN|POLLERR|POLLHUP)) + r |= CURL_CSELECT_IN; + if(pfd[num].revents & (POLLPRI|POLLNVAL)) + r |= CURL_CSELECT_ERR; + num++; + } + if(readfd1 != CURL_SOCKET_BAD) { + if(pfd[num].revents & (POLLRDNORM|POLLIN|POLLERR|POLLHUP)) + r |= CURL_CSELECT_IN2; + if(pfd[num].revents & (POLLPRI|POLLNVAL)) + r |= CURL_CSELECT_ERR; + num++; + } + if(writefd != CURL_SOCKET_BAD) { + if(pfd[num].revents & (POLLWRNORM|POLLOUT)) + r |= CURL_CSELECT_OUT; + if(pfd[num].revents & (POLLERR|POLLHUP|POLLPRI|POLLNVAL)) + r |= CURL_CSELECT_ERR; + } + + return r; +} + +/* + * This is a wrapper around poll(). If poll() does not exist, then + * select() is used instead. An error is returned if select() is + * being used and a file descriptor is too large for FD_SETSIZE. + * A negative timeout value makes this function wait indefinitely, + * unless no valid file descriptor is given, when this happens the + * negative timeout is ignored and the function times out immediately. + * + * Return values: + * -1 = system call error or fd >= FD_SETSIZE + * 0 = timeout + * N = number of structures with non zero revent fields + */ +int Curl_poll(struct pollfd ufds[], unsigned int nfds, timediff_t timeout_ms) +{ +#ifdef HAVE_POLL_FINE + int pending_ms; +#else + fd_set fds_read; + fd_set fds_write; + fd_set fds_err; + curl_socket_t maxfd; +#endif + bool fds_none = TRUE; + unsigned int i; + int r; + + if(ufds) { + for(i = 0; i < nfds; i++) { + if(ufds[i].fd != CURL_SOCKET_BAD) { + fds_none = FALSE; + break; + } + } + } + if(fds_none) { + /* no sockets, just wait */ + return Curl_wait_ms(timeout_ms); + } + + /* Avoid initial timestamp, avoid Curl_now() call, when elapsed + time in this function does not need to be measured. This happens + when function is called with a zero timeout or a negative timeout + value indicating a blocking call should be performed. */ + +#ifdef HAVE_POLL_FINE + + /* prevent overflow, timeout_ms is typecast to int. */ +#if TIMEDIFF_T_MAX > INT_MAX + if(timeout_ms > INT_MAX) + timeout_ms = INT_MAX; +#endif + if(timeout_ms > 0) + pending_ms = (int)timeout_ms; + else if(timeout_ms < 0) + pending_ms = -1; + else + pending_ms = 0; + r = poll(ufds, nfds, pending_ms); + if(r <= 0) { + if((r == -1) && (SOCKERRNO == EINTR)) + /* make EINTR from select or poll not a "lethal" error */ + r = 0; + return r; + } + + for(i = 0; i < nfds; i++) { + if(ufds[i].fd == CURL_SOCKET_BAD) + continue; + if(ufds[i].revents & POLLHUP) + ufds[i].revents |= POLLIN; + if(ufds[i].revents & POLLERR) + ufds[i].revents |= POLLIN|POLLOUT; + } + +#else /* HAVE_POLL_FINE */ + + FD_ZERO(&fds_read); + FD_ZERO(&fds_write); + FD_ZERO(&fds_err); + maxfd = (curl_socket_t)-1; + + for(i = 0; i < nfds; i++) { + ufds[i].revents = 0; + if(ufds[i].fd == CURL_SOCKET_BAD) + continue; + VERIFY_SOCK(ufds[i].fd); + if(ufds[i].events & (POLLIN|POLLOUT|POLLPRI| + POLLRDNORM|POLLWRNORM|POLLRDBAND)) { + if(ufds[i].fd > maxfd) + maxfd = ufds[i].fd; + if(ufds[i].events & (POLLRDNORM|POLLIN)) + FD_SET(ufds[i].fd, &fds_read); + if(ufds[i].events & (POLLWRNORM|POLLOUT)) + FD_SET(ufds[i].fd, &fds_write); + if(ufds[i].events & (POLLRDBAND|POLLPRI)) + FD_SET(ufds[i].fd, &fds_err); + } + } + + /* + Note also that WinSock ignores the first argument, so we don't worry + about the fact that maxfd is computed incorrectly with WinSock (since + curl_socket_t is unsigned in such cases and thus -1 is the largest + value). + */ + r = our_select(maxfd, &fds_read, &fds_write, &fds_err, timeout_ms); + if(r <= 0) { + if((r == -1) && (SOCKERRNO == EINTR)) + /* make EINTR from select or poll not a "lethal" error */ + r = 0; + return r; + } + + r = 0; + for(i = 0; i < nfds; i++) { + ufds[i].revents = 0; + if(ufds[i].fd == CURL_SOCKET_BAD) + continue; + if(FD_ISSET(ufds[i].fd, &fds_read)) { + if(ufds[i].events & POLLRDNORM) + ufds[i].revents |= POLLRDNORM; + if(ufds[i].events & POLLIN) + ufds[i].revents |= POLLIN; + } + if(FD_ISSET(ufds[i].fd, &fds_write)) { + if(ufds[i].events & POLLWRNORM) + ufds[i].revents |= POLLWRNORM; + if(ufds[i].events & POLLOUT) + ufds[i].revents |= POLLOUT; + } + if(FD_ISSET(ufds[i].fd, &fds_err)) { + if(ufds[i].events & POLLRDBAND) + ufds[i].revents |= POLLRDBAND; + if(ufds[i].events & POLLPRI) + ufds[i].revents |= POLLPRI; + } + if(ufds[i].revents) + r++; + } + +#endif /* HAVE_POLL_FINE */ + + return r; +} diff --git a/third_party/curl/lib/select.h b/third_party/curl/lib/select.h new file mode 100644 index 0000000..5b1ca23 --- /dev/null +++ b/third_party/curl/lib/select.h @@ -0,0 +1,114 @@ +#ifndef HEADER_CURL_SELECT_H +#define HEADER_CURL_SELECT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_POLL_H +#include +#elif defined(HAVE_SYS_POLL_H) +#include +#endif + +/* + * Definition of pollfd struct and constants for platforms lacking them. + */ + +#if !defined(HAVE_SYS_POLL_H) && \ + !defined(HAVE_POLL_H) && \ + !defined(POLLIN) + +#define POLLIN 0x01 +#define POLLPRI 0x02 +#define POLLOUT 0x04 +#define POLLERR 0x08 +#define POLLHUP 0x10 +#define POLLNVAL 0x20 + +struct pollfd +{ + curl_socket_t fd; + short events; + short revents; +}; + +#endif + +#ifndef POLLRDNORM +#define POLLRDNORM POLLIN +#endif + +#ifndef POLLWRNORM +#define POLLWRNORM POLLOUT +#endif + +#ifndef POLLRDBAND +#define POLLRDBAND POLLPRI +#endif + +/* there are three CSELECT defines that are defined in the public header that + are exposed to users, but this *IN2 bit is only ever used internally and + therefore defined here */ +#define CURL_CSELECT_IN2 (CURL_CSELECT_ERR << 1) + +int Curl_socket_check(curl_socket_t readfd, curl_socket_t readfd2, + curl_socket_t writefd, + timediff_t timeout_ms); +#define SOCKET_READABLE(x,z) \ + Curl_socket_check(x, CURL_SOCKET_BAD, CURL_SOCKET_BAD, z) +#define SOCKET_WRITABLE(x,z) \ + Curl_socket_check(CURL_SOCKET_BAD, CURL_SOCKET_BAD, x, z) + +int Curl_poll(struct pollfd ufds[], unsigned int nfds, timediff_t timeout_ms); +int Curl_wait_ms(timediff_t timeout_ms); + +/* + With Winsock the valid range is [0..INVALID_SOCKET-1] according to + https://docs.microsoft.com/en-us/windows/win32/winsock/socket-data-type-2 +*/ +#ifdef USE_WINSOCK +#define VALID_SOCK(s) ((s) < INVALID_SOCKET) +#define FDSET_SOCK(x) 1 +#define VERIFY_SOCK(x) do { \ + if(!VALID_SOCK(x)) { \ + SET_SOCKERRNO(WSAEINVAL); \ + return -1; \ + } \ +} while(0) +#else +#define VALID_SOCK(s) ((s) >= 0) + +/* If the socket is small enough to get set or read from an fdset */ +#define FDSET_SOCK(s) ((s) < FD_SETSIZE) + +#define VERIFY_SOCK(x) do { \ + if(!VALID_SOCK(x) || !FDSET_SOCK(x)) { \ + SET_SOCKERRNO(EINVAL); \ + return -1; \ + } \ + } while(0) +#endif + +#endif /* HEADER_CURL_SELECT_H */ diff --git a/third_party/curl/lib/sendf.c b/third_party/curl/lib/sendf.c new file mode 100644 index 0000000..68a8bf3 --- /dev/null +++ b/third_party/curl/lib/sendf.c @@ -0,0 +1,1378 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include +#endif + +#ifdef HAVE_LINUX_TCP_H +#include +#elif defined(HAVE_NETINET_TCP_H) +#include +#endif + +#include + +#include "urldata.h" +#include "sendf.h" +#include "cfilters.h" +#include "connect.h" +#include "content_encoding.h" +#include "cw-out.h" +#include "vtls/vtls.h" +#include "vssh/ssh.h" +#include "easyif.h" +#include "multiif.h" +#include "strerror.h" +#include "select.h" +#include "strdup.h" +#include "http2.h" +#include "progress.h" +#include "warnless.h" +#include "ws.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +static CURLcode do_init_writer_stack(struct Curl_easy *data); + +/* Curl_client_write() sends data to the write callback(s) + + The bit pattern defines to what "streams" to write to. Body and/or header. + The defines are in sendf.h of course. + */ +CURLcode Curl_client_write(struct Curl_easy *data, + int type, const char *buf, size_t blen) +{ + CURLcode result; + + /* it is one of those, at least */ + DEBUGASSERT(type & (CLIENTWRITE_BODY|CLIENTWRITE_HEADER|CLIENTWRITE_INFO)); + /* BODY is only BODY (with optional EOS) */ + DEBUGASSERT(!(type & CLIENTWRITE_BODY) || + ((type & ~(CLIENTWRITE_BODY|CLIENTWRITE_EOS)) == 0)); + /* INFO is only INFO (with optional EOS) */ + DEBUGASSERT(!(type & CLIENTWRITE_INFO) || + ((type & ~(CLIENTWRITE_INFO|CLIENTWRITE_EOS)) == 0)); + + if(!data->req.writer_stack) { + result = do_init_writer_stack(data); + if(result) + return result; + DEBUGASSERT(data->req.writer_stack); + } + + result = Curl_cwriter_write(data, data->req.writer_stack, type, buf, blen); + CURL_TRC_WRITE(data, "client_write(type=%x, len=%zu) -> %d", + type, blen, result); + return result; +} + +static void cl_reset_writer(struct Curl_easy *data) +{ + struct Curl_cwriter *writer = data->req.writer_stack; + while(writer) { + data->req.writer_stack = writer->next; + writer->cwt->do_close(data, writer); + free(writer); + writer = data->req.writer_stack; + } +} + +static void cl_reset_reader(struct Curl_easy *data) +{ + struct Curl_creader *reader = data->req.reader_stack; + while(reader) { + data->req.reader_stack = reader->next; + reader->crt->do_close(data, reader); + free(reader); + reader = data->req.reader_stack; + } +} + +void Curl_client_cleanup(struct Curl_easy *data) +{ + cl_reset_reader(data); + cl_reset_writer(data); + + data->req.bytecount = 0; + data->req.headerline = 0; +} + +void Curl_client_reset(struct Curl_easy *data) +{ + if(data->req.rewind_read) { + /* already requested */ + CURL_TRC_READ(data, "client_reset, will rewind reader"); + } + else { + CURL_TRC_READ(data, "client_reset, clear readers"); + cl_reset_reader(data); + } + cl_reset_writer(data); + + data->req.bytecount = 0; + data->req.headerline = 0; +} + +CURLcode Curl_client_start(struct Curl_easy *data) +{ + if(data->req.rewind_read) { + struct Curl_creader *r = data->req.reader_stack; + CURLcode result = CURLE_OK; + + CURL_TRC_READ(data, "client start, rewind readers"); + while(r) { + result = r->crt->rewind(data, r); + if(result) { + failf(data, "rewind of client reader '%s' failed: %d", + r->crt->name, result); + return result; + } + r = r->next; + } + data->req.rewind_read = FALSE; + cl_reset_reader(data); + } + return CURLE_OK; +} + +bool Curl_creader_will_rewind(struct Curl_easy *data) +{ + return data->req.rewind_read; +} + +void Curl_creader_set_rewind(struct Curl_easy *data, bool enable) +{ + data->req.rewind_read = !!enable; +} + +/* Write data using an unencoding writer stack. */ +CURLcode Curl_cwriter_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + if(!writer) + return CURLE_WRITE_ERROR; + return writer->cwt->do_write(data, writer, type, buf, nbytes); +} + +CURLcode Curl_cwriter_def_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + (void)data; + (void)writer; + return CURLE_OK; +} + +CURLcode Curl_cwriter_def_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); +} + +void Curl_cwriter_def_close(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + (void) data; + (void) writer; +} + +static size_t get_max_body_write_len(struct Curl_easy *data, curl_off_t limit) +{ + if(limit != -1) { + /* How much more are we allowed to write? */ + curl_off_t remain_diff; + remain_diff = limit - data->req.bytecount; + if(remain_diff < 0) { + /* already written too much! */ + return 0; + } +#if SIZEOF_CURL_OFF_T > SIZEOF_SIZE_T + else if(remain_diff > SSIZE_T_MAX) { + return SIZE_T_MAX; + } +#endif + else { + return (size_t)remain_diff; + } + } + return SIZE_T_MAX; +} + +struct cw_download_ctx { + struct Curl_cwriter super; + BIT(started_response); +}; +/* Download client writer in phase CURL_CW_PROTOCOL that + * sees the "real" download body data. */ +static CURLcode cw_download_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + struct cw_download_ctx *ctx = writer->ctx; + CURLcode result; + size_t nwrite, excess_len = 0; + bool is_connect = !!(type & CLIENTWRITE_CONNECT); + + if(!is_connect && !ctx->started_response) { + Curl_pgrsTime(data, TIMER_STARTTRANSFER); + ctx->started_response = TRUE; + } + + if(!(type & CLIENTWRITE_BODY)) { + if(is_connect && data->set.suppress_connect_headers) + return CURLE_OK; + result = Curl_cwriter_write(data, writer->next, type, buf, nbytes); + CURL_TRC_WRITE(data, "download_write header(type=%x, blen=%zu) -> %d", + type, nbytes, result); + return result; + } + + /* Here, we deal with REAL BODY bytes. All filtering and transfer + * encodings have been applied and only the true content, e.g. BODY, + * bytes are passed here. + * This allows us to check sizes, update stats, etc. independent + * from the protocol in play. */ + + if(data->req.no_body && nbytes > 0) { + /* BODY arrives although we want none, bail out */ + streamclose(data->conn, "ignoring body"); + CURL_TRC_WRITE(data, "download_write body(type=%x, blen=%zu), " + "did not want a BODY", type, nbytes); + data->req.download_done = TRUE; + if(data->info.header_size) + /* if headers have been received, this is fine */ + return CURLE_OK; + return CURLE_WEIRD_SERVER_REPLY; + } + + /* Determine if we see any bytes in excess to what is allowed. + * We write the allowed bytes and handle excess further below. + * This gives deterministic BODY writes on varying buffer receive + * lengths. */ + nwrite = nbytes; + if(-1 != data->req.maxdownload) { + size_t wmax = get_max_body_write_len(data, data->req.maxdownload); + if(nwrite > wmax) { + excess_len = nbytes - wmax; + nwrite = wmax; + } + + if(nwrite == wmax) { + data->req.download_done = TRUE; + } + } + + /* Error on too large filesize is handled below, after writing + * the permitted bytes */ + if(data->set.max_filesize) { + size_t wmax = get_max_body_write_len(data, data->set.max_filesize); + if(nwrite > wmax) { + nwrite = wmax; + } + } + + if(!data->req.ignorebody && (nwrite || (type & CLIENTWRITE_EOS))) { + result = Curl_cwriter_write(data, writer->next, type, buf, nwrite); + CURL_TRC_WRITE(data, "download_write body(type=%x, blen=%zu) -> %d", + type, nbytes, result); + if(result) + return result; + } + /* Update stats, write and report progress */ + data->req.bytecount += nwrite; + ++data->req.bodywrites; + result = Curl_pgrsSetDownloadCounter(data, data->req.bytecount); + if(result) + return result; + + if(excess_len) { + if(!data->req.ignorebody) { + infof(data, + "Excess found writing body:" + " excess = %zu" + ", size = %" CURL_FORMAT_CURL_OFF_T + ", maxdownload = %" CURL_FORMAT_CURL_OFF_T + ", bytecount = %" CURL_FORMAT_CURL_OFF_T, + excess_len, data->req.size, data->req.maxdownload, + data->req.bytecount); + connclose(data->conn, "excess found in a read"); + } + } + else if(nwrite < nbytes) { + failf(data, "Exceeded the maximum allowed file size " + "(%" CURL_FORMAT_CURL_OFF_T ") with %" + CURL_FORMAT_CURL_OFF_T " bytes", + data->set.max_filesize, data->req.bytecount); + return CURLE_FILESIZE_EXCEEDED; + } + + return CURLE_OK; +} + +static const struct Curl_cwtype cw_download = { + "protocol", + NULL, + Curl_cwriter_def_init, + cw_download_write, + Curl_cwriter_def_close, + sizeof(struct cw_download_ctx) +}; + +/* RAW client writer in phase CURL_CW_RAW that + * enabled tracing of raw data. */ +static CURLcode cw_raw_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + if(type & CLIENTWRITE_BODY && data->set.verbose && !data->req.ignorebody) { + Curl_debug(data, CURLINFO_DATA_IN, (char *)buf, nbytes); + } + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); +} + +static const struct Curl_cwtype cw_raw = { + "raw", + NULL, + Curl_cwriter_def_init, + cw_raw_write, + Curl_cwriter_def_close, + sizeof(struct Curl_cwriter) +}; + +/* Create an unencoding writer stage using the given handler. */ +CURLcode Curl_cwriter_create(struct Curl_cwriter **pwriter, + struct Curl_easy *data, + const struct Curl_cwtype *cwt, + Curl_cwriter_phase phase) +{ + struct Curl_cwriter *writer = NULL; + CURLcode result = CURLE_OUT_OF_MEMORY; + void *p; + + DEBUGASSERT(cwt->cwriter_size >= sizeof(struct Curl_cwriter)); + p = calloc(1, cwt->cwriter_size); + if(!p) + goto out; + + writer = (struct Curl_cwriter *)p; + writer->cwt = cwt; + writer->ctx = p; + writer->phase = phase; + result = cwt->do_init(data, writer); + +out: + *pwriter = result? NULL : writer; + if(result) + free(writer); + return result; +} + +void Curl_cwriter_free(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + if(writer) { + writer->cwt->do_close(data, writer); + free(writer); + } +} + +size_t Curl_cwriter_count(struct Curl_easy *data, Curl_cwriter_phase phase) +{ + struct Curl_cwriter *w; + size_t n = 0; + + for(w = data->req.writer_stack; w; w = w->next) { + if(w->phase == phase) + ++n; + } + return n; +} + +static CURLcode do_init_writer_stack(struct Curl_easy *data) +{ + struct Curl_cwriter *writer; + CURLcode result; + + DEBUGASSERT(!data->req.writer_stack); + result = Curl_cwriter_create(&data->req.writer_stack, + data, &Curl_cwt_out, CURL_CW_CLIENT); + if(result) + return result; + + result = Curl_cwriter_create(&writer, data, &cw_download, CURL_CW_PROTOCOL); + if(result) + return result; + result = Curl_cwriter_add(data, writer); + if(result) { + Curl_cwriter_free(data, writer); + } + + result = Curl_cwriter_create(&writer, data, &cw_raw, CURL_CW_RAW); + if(result) + return result; + result = Curl_cwriter_add(data, writer); + if(result) { + Curl_cwriter_free(data, writer); + } + return result; +} + +CURLcode Curl_cwriter_add(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + CURLcode result; + struct Curl_cwriter **anchor = &data->req.writer_stack; + + if(!*anchor) { + result = do_init_writer_stack(data); + if(result) + return result; + } + + /* Insert the writer as first in its phase. + * Skip existing writers of lower phases. */ + while(*anchor && (*anchor)->phase < writer->phase) + anchor = &((*anchor)->next); + writer->next = *anchor; + *anchor = writer; + return CURLE_OK; +} + +struct Curl_cwriter *Curl_cwriter_get_by_name(struct Curl_easy *data, + const char *name) +{ + struct Curl_cwriter *writer; + for(writer = data->req.writer_stack; writer; writer = writer->next) { + if(!strcmp(name, writer->cwt->name)) + return writer; + } + return NULL; +} + +struct Curl_cwriter *Curl_cwriter_get_by_type(struct Curl_easy *data, + const struct Curl_cwtype *cwt) +{ + struct Curl_cwriter *writer; + for(writer = data->req.writer_stack; writer; writer = writer->next) { + if(writer->cwt == cwt) + return writer; + } + return NULL; +} + +void Curl_cwriter_remove_by_name(struct Curl_easy *data, + const char *name) +{ + struct Curl_cwriter **anchor = &data->req.writer_stack; + + while(*anchor) { + if(!strcmp(name, (*anchor)->cwt->name)) { + struct Curl_cwriter *w = (*anchor); + *anchor = w->next; + Curl_cwriter_free(data, w); + continue; + } + anchor = &((*anchor)->next); + } +} + +bool Curl_cwriter_is_paused(struct Curl_easy *data) +{ + return Curl_cw_out_is_paused(data); +} + +CURLcode Curl_cwriter_unpause(struct Curl_easy *data) +{ + return Curl_cw_out_unpause(data); +} + +CURLcode Curl_creader_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, size_t *nread, bool *eos) +{ + *nread = 0; + *eos = FALSE; + if(!reader) + return CURLE_READ_ERROR; + return reader->crt->do_read(data, reader, buf, blen, nread, eos); +} + +CURLcode Curl_creader_def_init(struct Curl_easy *data, + struct Curl_creader *reader) +{ + (void)data; + (void)reader; + return CURLE_OK; +} + +void Curl_creader_def_close(struct Curl_easy *data, + struct Curl_creader *reader) +{ + (void)data; + (void)reader; +} + +CURLcode Curl_creader_def_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *nread, bool *eos) +{ + if(reader->next) + return reader->next->crt->do_read(data, reader->next, buf, blen, + nread, eos); + else { + *nread = 0; + *eos = FALSE; + return CURLE_READ_ERROR; + } +} + +bool Curl_creader_def_needs_rewind(struct Curl_easy *data, + struct Curl_creader *reader) +{ + (void)data; + (void)reader; + return FALSE; +} + +curl_off_t Curl_creader_def_total_length(struct Curl_easy *data, + struct Curl_creader *reader) +{ + return reader->next? + reader->next->crt->total_length(data, reader->next) : -1; +} + +CURLcode Curl_creader_def_resume_from(struct Curl_easy *data, + struct Curl_creader *reader, + curl_off_t offset) +{ + (void)data; + (void)reader; + (void)offset; + return CURLE_READ_ERROR; +} + +CURLcode Curl_creader_def_rewind(struct Curl_easy *data, + struct Curl_creader *reader) +{ + (void)data; + (void)reader; + return CURLE_OK; +} + +CURLcode Curl_creader_def_unpause(struct Curl_easy *data, + struct Curl_creader *reader) +{ + (void)data; + (void)reader; + return CURLE_OK; +} + +void Curl_creader_def_done(struct Curl_easy *data, + struct Curl_creader *reader, int premature) +{ + (void)data; + (void)reader; + (void)premature; +} + +struct cr_in_ctx { + struct Curl_creader super; + curl_read_callback read_cb; + void *cb_user_data; + curl_off_t total_len; + curl_off_t read_len; + CURLcode error_result; + BIT(seen_eos); + BIT(errored); + BIT(has_used_cb); +}; + +static CURLcode cr_in_init(struct Curl_easy *data, struct Curl_creader *reader) +{ + struct cr_in_ctx *ctx = reader->ctx; + (void)data; + ctx->read_cb = data->state.fread_func; + ctx->cb_user_data = data->state.in; + ctx->total_len = -1; + ctx->read_len = 0; + return CURLE_OK; +} + +/* Real client reader to installed client callbacks. */ +static CURLcode cr_in_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *pnread, bool *peos) +{ + struct cr_in_ctx *ctx = reader->ctx; + size_t nread; + + /* Once we have errored, we will return the same error forever */ + if(ctx->errored) { + *pnread = 0; + *peos = FALSE; + return ctx->error_result; + } + if(ctx->seen_eos) { + *pnread = 0; + *peos = TRUE; + return CURLE_OK; + } + /* respect length limitations */ + if(ctx->total_len >= 0) { + curl_off_t remain = ctx->total_len - ctx->read_len; + if(remain <= 0) + blen = 0; + else if(remain < (curl_off_t)blen) + blen = (size_t)remain; + } + nread = 0; + if(ctx->read_cb && blen) { + Curl_set_in_callback(data, true); + nread = ctx->read_cb(buf, 1, blen, ctx->cb_user_data); + Curl_set_in_callback(data, false); + ctx->has_used_cb = TRUE; + } + + switch(nread) { + case 0: + if((ctx->total_len >= 0) && (ctx->read_len < ctx->total_len)) { + failf(data, "client read function EOF fail, " + "only %"CURL_FORMAT_CURL_OFF_T"/%"CURL_FORMAT_CURL_OFF_T + " of needed bytes read", ctx->read_len, ctx->total_len); + return CURLE_READ_ERROR; + } + *pnread = 0; + *peos = TRUE; + ctx->seen_eos = TRUE; + break; + + case CURL_READFUNC_ABORT: + failf(data, "operation aborted by callback"); + *pnread = 0; + *peos = FALSE; + ctx->errored = TRUE; + ctx->error_result = CURLE_ABORTED_BY_CALLBACK; + return CURLE_ABORTED_BY_CALLBACK; + + case CURL_READFUNC_PAUSE: + if(data->conn->handler->flags & PROTOPT_NONETWORK) { + /* protocols that work without network cannot be paused. This is + actually only FILE:// just now, and it can't pause since the transfer + isn't done using the "normal" procedure. */ + failf(data, "Read callback asked for PAUSE when not supported"); + return CURLE_READ_ERROR; + } + /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */ + data->req.keepon |= KEEP_SEND_PAUSE; /* mark socket send as paused */ + *pnread = 0; + *peos = FALSE; + break; /* nothing was read */ + + default: + if(nread > blen) { + /* the read function returned a too large value */ + failf(data, "read function returned funny value"); + *pnread = 0; + *peos = FALSE; + ctx->errored = TRUE; + ctx->error_result = CURLE_READ_ERROR; + return CURLE_READ_ERROR; + } + ctx->read_len += nread; + if(ctx->total_len >= 0) + ctx->seen_eos = (ctx->read_len >= ctx->total_len); + *pnread = nread; + *peos = ctx->seen_eos; + break; + } + CURL_TRC_READ(data, "cr_in_read(len=%zu, total=%"CURL_FORMAT_CURL_OFF_T + ", read=%"CURL_FORMAT_CURL_OFF_T") -> %d, nread=%zu, eos=%d", + blen, ctx->total_len, ctx->read_len, CURLE_OK, + *pnread, *peos); + return CURLE_OK; +} + +static bool cr_in_needs_rewind(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_in_ctx *ctx = reader->ctx; + (void)data; + return ctx->has_used_cb; +} + +static curl_off_t cr_in_total_length(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_in_ctx *ctx = reader->ctx; + (void)data; + return ctx->total_len; +} + +static CURLcode cr_in_resume_from(struct Curl_easy *data, + struct Curl_creader *reader, + curl_off_t offset) +{ + struct cr_in_ctx *ctx = reader->ctx; + int seekerr = CURL_SEEKFUNC_CANTSEEK; + + DEBUGASSERT(data->conn); + /* already started reading? */ + if(ctx->read_len) + return CURLE_READ_ERROR; + + if(data->set.seek_func) { + Curl_set_in_callback(data, true); + seekerr = data->set.seek_func(data->set.seek_client, offset, SEEK_SET); + Curl_set_in_callback(data, false); + } + + if(seekerr != CURL_SEEKFUNC_OK) { + curl_off_t passed = 0; + + if(seekerr != CURL_SEEKFUNC_CANTSEEK) { + failf(data, "Could not seek stream"); + return CURLE_READ_ERROR; + } + /* when seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */ + do { + char scratch[4*1024]; + size_t readthisamountnow = + (offset - passed > (curl_off_t)sizeof(scratch)) ? + sizeof(scratch) : + curlx_sotouz(offset - passed); + size_t actuallyread; + + Curl_set_in_callback(data, true); + actuallyread = ctx->read_cb(scratch, 1, readthisamountnow, + ctx->cb_user_data); + Curl_set_in_callback(data, false); + + passed += actuallyread; + if((actuallyread == 0) || (actuallyread > readthisamountnow)) { + /* this checks for greater-than only to make sure that the + CURL_READFUNC_ABORT return code still aborts */ + failf(data, "Could only read %" CURL_FORMAT_CURL_OFF_T + " bytes from the input", passed); + return CURLE_READ_ERROR; + } + } while(passed < offset); + } + + /* now, decrease the size of the read */ + if(ctx->total_len > 0) { + ctx->total_len -= offset; + + if(ctx->total_len <= 0) { + failf(data, "File already completely uploaded"); + return CURLE_PARTIAL_FILE; + } + } + /* we've passed, proceed as normal */ + return CURLE_OK; +} + +static CURLcode cr_in_rewind(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_in_ctx *ctx = reader->ctx; + + /* If we never invoked the callback, there is noting to rewind */ + if(!ctx->has_used_cb) + return CURLE_OK; + + if(data->set.seek_func) { + int err; + + Curl_set_in_callback(data, true); + err = (data->set.seek_func)(data->set.seek_client, 0, SEEK_SET); + Curl_set_in_callback(data, false); + CURL_TRC_READ(data, "cr_in, rewind via set.seek_func -> %d", err); + if(err) { + failf(data, "seek callback returned error %d", (int)err); + return CURLE_SEND_FAIL_REWIND; + } + } + else if(data->set.ioctl_func) { + curlioerr err; + + Curl_set_in_callback(data, true); + err = (data->set.ioctl_func)(data, CURLIOCMD_RESTARTREAD, + data->set.ioctl_client); + Curl_set_in_callback(data, false); + CURL_TRC_READ(data, "cr_in, rewind via set.ioctl_func -> %d", (int)err); + if(err) { + failf(data, "ioctl callback returned error %d", (int)err); + return CURLE_SEND_FAIL_REWIND; + } + } + else { + /* If no CURLOPT_READFUNCTION is used, we know that we operate on a + given FILE * stream and we can actually attempt to rewind that + ourselves with fseek() */ + if(data->state.fread_func == (curl_read_callback)fread) { + int err = fseek(data->state.in, 0, SEEK_SET); + CURL_TRC_READ(data, "cr_in, rewind via fseek -> %d(%d)", + (int)err, (int)errno); + if(-1 != err) + /* successful rewind */ + return CURLE_OK; + } + + /* no callback set or failure above, makes us fail at once */ + failf(data, "necessary data rewind wasn't possible"); + return CURLE_SEND_FAIL_REWIND; + } + return CURLE_OK; +} + + +static const struct Curl_crtype cr_in = { + "cr-in", + cr_in_init, + cr_in_read, + Curl_creader_def_close, + cr_in_needs_rewind, + cr_in_total_length, + cr_in_resume_from, + cr_in_rewind, + Curl_creader_def_unpause, + Curl_creader_def_done, + sizeof(struct cr_in_ctx) +}; + +CURLcode Curl_creader_create(struct Curl_creader **preader, + struct Curl_easy *data, + const struct Curl_crtype *crt, + Curl_creader_phase phase) +{ + struct Curl_creader *reader = NULL; + CURLcode result = CURLE_OUT_OF_MEMORY; + void *p; + + DEBUGASSERT(crt->creader_size >= sizeof(struct Curl_creader)); + p = calloc(1, crt->creader_size); + if(!p) + goto out; + + reader = (struct Curl_creader *)p; + reader->crt = crt; + reader->ctx = p; + reader->phase = phase; + result = crt->do_init(data, reader); + +out: + *preader = result? NULL : reader; + if(result) + free(reader); + return result; +} + +void Curl_creader_free(struct Curl_easy *data, struct Curl_creader *reader) +{ + if(reader) { + reader->crt->do_close(data, reader); + free(reader); + } +} + +struct cr_lc_ctx { + struct Curl_creader super; + struct bufq buf; + BIT(read_eos); /* we read an EOS from the next reader */ + BIT(eos); /* we have returned an EOS */ +}; + +static CURLcode cr_lc_init(struct Curl_easy *data, struct Curl_creader *reader) +{ + struct cr_lc_ctx *ctx = reader->ctx; + (void)data; + Curl_bufq_init2(&ctx->buf, (16 * 1024), 1, BUFQ_OPT_SOFT_LIMIT); + return CURLE_OK; +} + +static void cr_lc_close(struct Curl_easy *data, struct Curl_creader *reader) +{ + struct cr_lc_ctx *ctx = reader->ctx; + (void)data; + Curl_bufq_free(&ctx->buf); +} + +/* client reader doing line end conversions. */ +static CURLcode cr_lc_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *pnread, bool *peos) +{ + struct cr_lc_ctx *ctx = reader->ctx; + CURLcode result; + size_t nread, i, start, n; + bool eos; + + if(ctx->eos) { + *pnread = 0; + *peos = TRUE; + return CURLE_OK; + } + + if(Curl_bufq_is_empty(&ctx->buf)) { + if(ctx->read_eos) { + ctx->eos = TRUE; + *pnread = 0; + *peos = TRUE; + return CURLE_OK; + } + /* Still getting data form the next reader, ctx->buf is empty */ + result = Curl_creader_read(data, reader->next, buf, blen, &nread, &eos); + if(result) + return result; + ctx->read_eos = eos; + + if(!nread || !memchr(buf, '\n', nread)) { + /* nothing to convert, return this right away */ + if(ctx->read_eos) + ctx->eos = TRUE; + *pnread = nread; + *peos = ctx->eos; + goto out; + } + + /* at least one \n needs conversion to '\r\n', place into ctx->buf */ + for(i = start = 0; i < nread; ++i) { + if(buf[i] != '\n') + continue; + /* on a soft limit bufq, we do not need to check length */ + result = Curl_bufq_cwrite(&ctx->buf, buf + start, i - start, &n); + if(!result) + result = Curl_bufq_cwrite(&ctx->buf, STRCONST("\r\n"), &n); + if(result) + return result; + start = i + 1; + if(!data->set.crlf && (data->state.infilesize != -1)) { + /* we're here only because FTP is in ASCII mode... + bump infilesize for the LF we just added */ + data->state.infilesize++; + /* comment: this might work for FTP, but in HTTP we could not change + * the content length after having started the request... */ + } + } + } + + DEBUGASSERT(!Curl_bufq_is_empty(&ctx->buf)); + *peos = FALSE; + result = Curl_bufq_cread(&ctx->buf, buf, blen, pnread); + if(!result && ctx->read_eos && Curl_bufq_is_empty(&ctx->buf)) { + /* no more data, read all, done. */ + ctx->eos = TRUE; + *peos = TRUE; + } + +out: + CURL_TRC_READ(data, "cr_lc_read(len=%zu) -> %d, nread=%zu, eos=%d", + blen, result, *pnread, *peos); + return result; +} + +static curl_off_t cr_lc_total_length(struct Curl_easy *data, + struct Curl_creader *reader) +{ + /* this reader changes length depending on input */ + (void)data; + (void)reader; + return -1; +} + +static const struct Curl_crtype cr_lc = { + "cr-lineconv", + cr_lc_init, + cr_lc_read, + cr_lc_close, + Curl_creader_def_needs_rewind, + cr_lc_total_length, + Curl_creader_def_resume_from, + Curl_creader_def_rewind, + Curl_creader_def_unpause, + Curl_creader_def_done, + sizeof(struct cr_lc_ctx) +}; + +static CURLcode cr_lc_add(struct Curl_easy *data) +{ + struct Curl_creader *reader = NULL; + CURLcode result; + + result = Curl_creader_create(&reader, data, &cr_lc, + CURL_CR_CONTENT_ENCODE); + if(!result) + result = Curl_creader_add(data, reader); + + if(result && reader) + Curl_creader_free(data, reader); + return result; +} + +static CURLcode do_init_reader_stack(struct Curl_easy *data, + struct Curl_creader *r) +{ + CURLcode result = CURLE_OK; + curl_off_t clen; + + DEBUGASSERT(r); + DEBUGASSERT(r->crt); + DEBUGASSERT(r->phase == CURL_CR_CLIENT); + DEBUGASSERT(!data->req.reader_stack); + + data->req.reader_stack = r; + clen = r->crt->total_length(data, r); + /* if we do not have 0 length init, and crlf conversion is wanted, + * add the reader for it */ + if(clen && (data->set.crlf +#ifdef CURL_DO_LINEEND_CONV + || data->state.prefer_ascii +#endif + )) { + result = cr_lc_add(data); + if(result) + return result; + } + + return result; +} + +CURLcode Curl_creader_set_fread(struct Curl_easy *data, curl_off_t len) +{ + CURLcode result; + struct Curl_creader *r; + struct cr_in_ctx *ctx; + + result = Curl_creader_create(&r, data, &cr_in, CURL_CR_CLIENT); + if(result) + goto out; + ctx = r->ctx; + ctx->total_len = len; + + cl_reset_reader(data); + result = do_init_reader_stack(data, r); +out: + CURL_TRC_READ(data, "add fread reader, len=%"CURL_FORMAT_CURL_OFF_T + " -> %d", len, result); + return result; +} + +CURLcode Curl_creader_add(struct Curl_easy *data, + struct Curl_creader *reader) +{ + CURLcode result; + struct Curl_creader **anchor = &data->req.reader_stack; + + if(!*anchor) { + result = Curl_creader_set_fread(data, data->state.infilesize); + if(result) + return result; + } + + /* Insert the writer as first in its phase. + * Skip existing readers of lower phases. */ + while(*anchor && (*anchor)->phase < reader->phase) + anchor = &((*anchor)->next); + reader->next = *anchor; + *anchor = reader; + return CURLE_OK; +} + +CURLcode Curl_creader_set(struct Curl_easy *data, struct Curl_creader *r) +{ + CURLcode result; + + DEBUGASSERT(r); + DEBUGASSERT(r->crt); + DEBUGASSERT(r->phase == CURL_CR_CLIENT); + + cl_reset_reader(data); + result = do_init_reader_stack(data, r); + if(result) + Curl_creader_free(data, r); + return result; +} + +CURLcode Curl_client_read(struct Curl_easy *data, char *buf, size_t blen, + size_t *nread, bool *eos) +{ + CURLcode result; + + DEBUGASSERT(buf); + DEBUGASSERT(blen); + DEBUGASSERT(nread); + DEBUGASSERT(eos); + + if(!data->req.reader_stack) { + result = Curl_creader_set_fread(data, data->state.infilesize); + if(result) + return result; + DEBUGASSERT(data->req.reader_stack); + } + + result = Curl_creader_read(data, data->req.reader_stack, buf, blen, + nread, eos); + CURL_TRC_READ(data, "client_read(len=%zu) -> %d, nread=%zu, eos=%d", + blen, result, *nread, *eos); + return result; +} + +bool Curl_creader_needs_rewind(struct Curl_easy *data) +{ + struct Curl_creader *reader = data->req.reader_stack; + while(reader) { + if(reader->crt->needs_rewind(data, reader)) { + CURL_TRC_READ(data, "client reader needs rewind before next request"); + return TRUE; + } + reader = reader->next; + } + return FALSE; +} + +static CURLcode cr_null_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *pnread, bool *peos) +{ + (void)data; + (void)reader; + (void)buf; + (void)blen; + *pnread = 0; + *peos = TRUE; + return CURLE_OK; +} + +static curl_off_t cr_null_total_length(struct Curl_easy *data, + struct Curl_creader *reader) +{ + /* this reader changes length depending on input */ + (void)data; + (void)reader; + return 0; +} + +static const struct Curl_crtype cr_null = { + "cr-null", + Curl_creader_def_init, + cr_null_read, + Curl_creader_def_close, + Curl_creader_def_needs_rewind, + cr_null_total_length, + Curl_creader_def_resume_from, + Curl_creader_def_rewind, + Curl_creader_def_unpause, + Curl_creader_def_done, + sizeof(struct Curl_creader) +}; + +CURLcode Curl_creader_set_null(struct Curl_easy *data) +{ + struct Curl_creader *r; + CURLcode result; + + result = Curl_creader_create(&r, data, &cr_null, CURL_CR_CLIENT); + if(result) + return result; + + cl_reset_reader(data); + return do_init_reader_stack(data, r); +} + +struct cr_buf_ctx { + struct Curl_creader super; + const char *buf; + size_t blen; + size_t index; +}; + +static CURLcode cr_buf_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *pnread, bool *peos) +{ + struct cr_buf_ctx *ctx = reader->ctx; + size_t nread = ctx->blen - ctx->index; + + (void)data; + if(!nread || !ctx->buf) { + *pnread = 0; + *peos = TRUE; + } + else { + if(nread > blen) + nread = blen; + memcpy(buf, ctx->buf + ctx->index, nread); + *pnread = nread; + ctx->index += nread; + *peos = (ctx->index == ctx->blen); + } + CURL_TRC_READ(data, "cr_buf_read(len=%zu) -> 0, nread=%zu, eos=%d", + blen, *pnread, *peos); + return CURLE_OK; +} + +static bool cr_buf_needs_rewind(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_buf_ctx *ctx = reader->ctx; + (void)data; + return ctx->index > 0; +} + +static curl_off_t cr_buf_total_length(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_buf_ctx *ctx = reader->ctx; + (void)data; + return (curl_off_t)ctx->blen; +} + +static CURLcode cr_buf_resume_from(struct Curl_easy *data, + struct Curl_creader *reader, + curl_off_t offset) +{ + struct cr_buf_ctx *ctx = reader->ctx; + size_t boffset; + + (void)data; + DEBUGASSERT(data->conn); + /* already started reading? */ + if(ctx->index) + return CURLE_READ_ERROR; + if(offset <= 0) + return CURLE_OK; + boffset = (size_t)offset; + if(boffset > ctx->blen) + return CURLE_READ_ERROR; + + ctx->buf += boffset; + ctx->blen -= boffset; + return CURLE_OK; +} + +static const struct Curl_crtype cr_buf = { + "cr-buf", + Curl_creader_def_init, + cr_buf_read, + Curl_creader_def_close, + cr_buf_needs_rewind, + cr_buf_total_length, + cr_buf_resume_from, + Curl_creader_def_rewind, + Curl_creader_def_unpause, + Curl_creader_def_done, + sizeof(struct cr_buf_ctx) +}; + +CURLcode Curl_creader_set_buf(struct Curl_easy *data, + const char *buf, size_t blen) +{ + CURLcode result; + struct Curl_creader *r; + struct cr_buf_ctx *ctx; + + result = Curl_creader_create(&r, data, &cr_buf, CURL_CR_CLIENT); + if(result) + goto out; + ctx = r->ctx; + ctx->buf = buf; + ctx->blen = blen; + ctx->index = 0; + + cl_reset_reader(data); + result = do_init_reader_stack(data, r); +out: + CURL_TRC_READ(data, "add buf reader, len=%zu -> %d", blen, result); + return result; +} + +curl_off_t Curl_creader_total_length(struct Curl_easy *data) +{ + struct Curl_creader *r = data->req.reader_stack; + return r? r->crt->total_length(data, r) : -1; +} + +curl_off_t Curl_creader_client_length(struct Curl_easy *data) +{ + struct Curl_creader *r = data->req.reader_stack; + while(r && r->phase != CURL_CR_CLIENT) + r = r->next; + return r? r->crt->total_length(data, r) : -1; +} + +CURLcode Curl_creader_resume_from(struct Curl_easy *data, curl_off_t offset) +{ + struct Curl_creader *r = data->req.reader_stack; + while(r && r->phase != CURL_CR_CLIENT) + r = r->next; + return r? r->crt->resume_from(data, r, offset) : CURLE_READ_ERROR; +} + +CURLcode Curl_creader_unpause(struct Curl_easy *data) +{ + struct Curl_creader *reader = data->req.reader_stack; + CURLcode result = CURLE_OK; + + while(reader) { + result = reader->crt->unpause(data, reader); + if(result) + break; + reader = reader->next; + } + return result; +} + +void Curl_creader_done(struct Curl_easy *data, int premature) +{ + struct Curl_creader *reader = data->req.reader_stack; + while(reader) { + reader->crt->done(data, reader, premature); + reader = reader->next; + } +} + +struct Curl_creader *Curl_creader_get_by_type(struct Curl_easy *data, + const struct Curl_crtype *crt) +{ + struct Curl_creader *r; + for(r = data->req.reader_stack; r; r = r->next) { + if(r->crt == crt) + return r; + } + return NULL; + +} diff --git a/third_party/curl/lib/sendf.h b/third_party/curl/lib/sendf.h new file mode 100644 index 0000000..82a2902 --- /dev/null +++ b/third_party/curl/lib/sendf.h @@ -0,0 +1,407 @@ +#ifndef HEADER_CURL_SENDF_H +#define HEADER_CURL_SENDF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "curl_trc.h" + +/** + * Type of data that is being written to the client (application) + * - data written can be either BODY or META data + * - META data is either INFO or HEADER + * - INFO is meta information, e.g. not BODY, that cannot be interpreted + * as headers of a response. Example FTP/IMAP pingpong answers. + * - HEADER can have additional bits set (more than one) + * - STATUS special "header", e.g. response status line in HTTP + * - CONNECT header was received during proxying the connection + * - 1XX header is part of an intermediate response, e.g. HTTP 1xx code + * - TRAILER header is trailing response data, e.g. HTTP trailers + * BODY, INFO and HEADER should not be mixed, as this would lead to + * confusion on how to interpret/format/convert the data. + */ +#define CLIENTWRITE_BODY (1<<0) /* non-meta information, BODY */ +#define CLIENTWRITE_INFO (1<<1) /* meta information, not a HEADER */ +#define CLIENTWRITE_HEADER (1<<2) /* meta information, HEADER */ +#define CLIENTWRITE_STATUS (1<<3) /* a special status HEADER */ +#define CLIENTWRITE_CONNECT (1<<4) /* a CONNECT related HEADER */ +#define CLIENTWRITE_1XX (1<<5) /* a 1xx response related HEADER */ +#define CLIENTWRITE_TRAILER (1<<6) /* a trailer HEADER */ +#define CLIENTWRITE_EOS (1<<7) /* End Of transfer download Stream */ + +/** + * Write `len` bytes at `prt` to the client. `type` indicates what + * kind of data is being written. + */ +CURLcode Curl_client_write(struct Curl_easy *data, int type, const char *ptr, + size_t len) WARN_UNUSED_RESULT; + +/** + * Free all resources related to client writing. + */ +void Curl_client_cleanup(struct Curl_easy *data); + +/** + * Reset readers and writer chains, keep rewind information + * when necessary. + */ +void Curl_client_reset(struct Curl_easy *data); + +/** + * A new request is starting, perform any ops like rewinding + * previous readers when needed. + */ +CURLcode Curl_client_start(struct Curl_easy *data); + +/** + * Client Writers - a chain passing transfer BODY data to the client. + * Main application: HTTP and related protocols + * Other uses: monitoring of download progress + * + * Writers in the chain are order by their `phase`. First come all + * writers in CURL_CW_RAW, followed by any in CURL_CW_TRANSFER_DECODE, + * followed by any in CURL_CW_PROTOCOL, etc. + * + * When adding a writer, it is inserted as first in its phase. This means + * the order of adding writers of the same phase matters, but writers for + * different phases may be added in any order. + * + * Writers which do modify the BODY data written are expected to be of + * phases TRANSFER_DECODE or CONTENT_DECODE. The other phases are intended + * for monitoring writers. Which do *not* modify the data but gather + * statistics or update progress reporting. + */ + +/* Phase a writer operates at. */ +typedef enum { + CURL_CW_RAW, /* raw data written, before any decoding */ + CURL_CW_TRANSFER_DECODE, /* remove transfer-encodings */ + CURL_CW_PROTOCOL, /* after transfer, but before content decoding */ + CURL_CW_CONTENT_DECODE, /* remove content-encodings */ + CURL_CW_CLIENT /* data written to client */ +} Curl_cwriter_phase; + +/* Client Writer Type, provides the implementation */ +struct Curl_cwtype { + const char *name; /* writer name. */ + const char *alias; /* writer name alias, maybe NULL. */ + CURLcode (*do_init)(struct Curl_easy *data, + struct Curl_cwriter *writer); + CURLcode (*do_write)(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes); + void (*do_close)(struct Curl_easy *data, + struct Curl_cwriter *writer); + size_t cwriter_size; /* sizeof() allocated struct Curl_cwriter */ +}; + +/* Client writer instance, allocated on creation. + * `void *ctx` is the pointer from the allocation of + * the `struct Curl_cwriter` itself. This is suitable for "downcasting" + * by the writers implementation. See https://github.com/curl/curl/pull/13054 + * for the alignment problems that arise otherwise. + */ +struct Curl_cwriter { + const struct Curl_cwtype *cwt; /* type implementation */ + struct Curl_cwriter *next; /* Downstream writer. */ + void *ctx; /* allocated instance pointer */ + Curl_cwriter_phase phase; /* phase at which it operates */ +}; + +/** + * Create a new cwriter instance with given type and phase. Is not + * inserted into the writer chain by this call. + * Invokes `writer->do_init()`. + */ +CURLcode Curl_cwriter_create(struct Curl_cwriter **pwriter, + struct Curl_easy *data, + const struct Curl_cwtype *ce_handler, + Curl_cwriter_phase phase); + +/** + * Free a cwriter instance. + * Invokes `writer->do_close()`. + */ +void Curl_cwriter_free(struct Curl_easy *data, + struct Curl_cwriter *writer); + +/** + * Count the number of writers installed of the given phase. + */ +size_t Curl_cwriter_count(struct Curl_easy *data, Curl_cwriter_phase phase); + +/** + * Adds a writer to the transfer's writer chain. + * The writers `phase` determines where in the chain it is inserted. + */ +CURLcode Curl_cwriter_add(struct Curl_easy *data, + struct Curl_cwriter *writer); + +/** + * Look up an installed client writer on `data` by its type. + * @return first writer with that type or NULL + */ +struct Curl_cwriter *Curl_cwriter_get_by_type(struct Curl_easy *data, + const struct Curl_cwtype *cwt); + +void Curl_cwriter_remove_by_name(struct Curl_easy *data, + const char *name); + +struct Curl_cwriter *Curl_cwriter_get_by_name(struct Curl_easy *data, + const char *name); + +/** + * Convenience method for calling `writer->do_write()` that + * checks for NULL writer. + */ +CURLcode Curl_cwriter_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes); + +/** + * Return TRUE iff client writer is paused. + */ +bool Curl_cwriter_is_paused(struct Curl_easy *data); + +/** + * Unpause client writer and flush any buffered date to the client. + */ +CURLcode Curl_cwriter_unpause(struct Curl_easy *data); + +/** + * Default implementations for do_init, do_write, do_close that + * do nothing and pass the data through. + */ +CURLcode Curl_cwriter_def_init(struct Curl_easy *data, + struct Curl_cwriter *writer); +CURLcode Curl_cwriter_def_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes); +void Curl_cwriter_def_close(struct Curl_easy *data, + struct Curl_cwriter *writer); + + + +/* Client Reader Type, provides the implementation */ +struct Curl_crtype { + const char *name; /* writer name. */ + CURLcode (*do_init)(struct Curl_easy *data, struct Curl_creader *reader); + CURLcode (*do_read)(struct Curl_easy *data, struct Curl_creader *reader, + char *buf, size_t blen, size_t *nread, bool *eos); + void (*do_close)(struct Curl_easy *data, struct Curl_creader *reader); + bool (*needs_rewind)(struct Curl_easy *data, struct Curl_creader *reader); + curl_off_t (*total_length)(struct Curl_easy *data, + struct Curl_creader *reader); + CURLcode (*resume_from)(struct Curl_easy *data, + struct Curl_creader *reader, curl_off_t offset); + CURLcode (*rewind)(struct Curl_easy *data, struct Curl_creader *reader); + CURLcode (*unpause)(struct Curl_easy *data, struct Curl_creader *reader); + void (*done)(struct Curl_easy *data, + struct Curl_creader *reader, int premature); + size_t creader_size; /* sizeof() allocated struct Curl_creader */ +}; + +/* Phase a reader operates at. */ +typedef enum { + CURL_CR_NET, /* data send to the network (connection filters) */ + CURL_CR_TRANSFER_ENCODE, /* add transfer-encodings */ + CURL_CR_PROTOCOL, /* before transfer, but after content decoding */ + CURL_CR_CONTENT_ENCODE, /* add content-encodings */ + CURL_CR_CLIENT /* data read from client */ +} Curl_creader_phase; + +/* Client reader instance, allocated on creation. + * `void *ctx` is the pointer from the allocation of + * the `struct Curl_cwriter` itself. This is suitable for "downcasting" + * by the writers implementation. See https://github.com/curl/curl/pull/13054 + * for the alignment problems that arise otherwise. + */ +struct Curl_creader { + const struct Curl_crtype *crt; /* type implementation */ + struct Curl_creader *next; /* Downstream reader. */ + void *ctx; + Curl_creader_phase phase; /* phase at which it operates */ +}; + +/** + * Default implementations for do_init, do_write, do_close that + * do nothing and pass the data through. + */ +CURLcode Curl_creader_def_init(struct Curl_easy *data, + struct Curl_creader *reader); +void Curl_creader_def_close(struct Curl_easy *data, + struct Curl_creader *reader); +CURLcode Curl_creader_def_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *nread, bool *eos); +bool Curl_creader_def_needs_rewind(struct Curl_easy *data, + struct Curl_creader *reader); +curl_off_t Curl_creader_def_total_length(struct Curl_easy *data, + struct Curl_creader *reader); +CURLcode Curl_creader_def_resume_from(struct Curl_easy *data, + struct Curl_creader *reader, + curl_off_t offset); +CURLcode Curl_creader_def_rewind(struct Curl_easy *data, + struct Curl_creader *reader); +CURLcode Curl_creader_def_unpause(struct Curl_easy *data, + struct Curl_creader *reader); +void Curl_creader_def_done(struct Curl_easy *data, + struct Curl_creader *reader, int premature); + +/** + * Convenience method for calling `reader->do_read()` that + * checks for NULL reader. + */ +CURLcode Curl_creader_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, size_t *nread, bool *eos); + +/** + * Create a new creader instance with given type and phase. Is not + * inserted into the writer chain by this call. + * Invokes `reader->do_init()`. + */ +CURLcode Curl_creader_create(struct Curl_creader **preader, + struct Curl_easy *data, + const struct Curl_crtype *cr_handler, + Curl_creader_phase phase); + +/** + * Free a creader instance. + * Invokes `reader->do_close()`. + */ +void Curl_creader_free(struct Curl_easy *data, struct Curl_creader *reader); + +/** + * Adds a reader to the transfer's reader chain. + * The readers `phase` determines where in the chain it is inserted. + */ +CURLcode Curl_creader_add(struct Curl_easy *data, + struct Curl_creader *reader); + +/** + * Set the given reader, which needs to be of type CURL_CR_CLIENT, + * as the new first reader. Discard any installed readers and init + * the reader chain anew. + * The function takes ownership of `r`. + */ +CURLcode Curl_creader_set(struct Curl_easy *data, struct Curl_creader *r); + +/** + * Read at most `blen` bytes at `buf` from the client. + * @param data the transfer to read client bytes for + * @param buf the memory location to read to + * @param blen the amount of memory at `buf` + * @param nread on return the number of bytes read into `buf` + * @param eos TRUE iff bytes are the end of data from client + * @return CURLE_OK on successful read (even 0 length) or error + */ +CURLcode Curl_client_read(struct Curl_easy *data, char *buf, size_t blen, + size_t *nread, bool *eos) WARN_UNUSED_RESULT; + +/** + * TRUE iff client reader needs rewing before it can be used for + * a retry request. + */ +bool Curl_creader_needs_rewind(struct Curl_easy *data); + +/** + * TRUE iff client reader will rewind at next start + */ +bool Curl_creader_will_rewind(struct Curl_easy *data); + +/** + * En-/disable rewind of client reader at next start. + */ +void Curl_creader_set_rewind(struct Curl_easy *data, bool enable); + +/** + * Get the total length of bytes provided by the installed readers. + * This is independent of the amount already delivered and is calculated + * by all readers in the stack. If a reader like "chunked" or + * "crlf conversion" is installed, the returned length will be -1. + * @return -1 if length is indeterminate + */ +curl_off_t Curl_creader_total_length(struct Curl_easy *data); + +/** + * Get the total length of bytes provided by the reader at phase + * CURL_CR_CLIENT. This may not match the amount of bytes read + * for a request, depending if other, encoding readers are also installed. + * However it allows for rough estimation of the overall length. + * @return -1 if length is indeterminate + */ +curl_off_t Curl_creader_client_length(struct Curl_easy *data); + +/** + * Ask the installed reader at phase CURL_CR_CLIENT to start + * reading from the given offset. On success, this will reduce + * the `total_length()` by the amount. + * @param data the transfer to read client bytes for + * @param offset the offset where to start reads from, negative + * values will be ignored. + * @return CURLE_OK if offset could be set + * CURLE_READ_ERROR if not supported by reader or seek/read failed + * of offset larger then total length + * CURLE_PARTIAL_FILE if offset led to 0 total length + */ +CURLcode Curl_creader_resume_from(struct Curl_easy *data, curl_off_t offset); + +/** + * Unpause all installed readers. + */ +CURLcode Curl_creader_unpause(struct Curl_easy *data); + +/** + * Tell all client readers that they are done. + */ +void Curl_creader_done(struct Curl_easy *data, int premature); + +/** + * Look up an installed client reader on `data` by its type. + * @return first reader with that type or NULL + */ +struct Curl_creader *Curl_creader_get_by_type(struct Curl_easy *data, + const struct Curl_crtype *crt); + + +/** + * Set the client reader to provide 0 bytes, immediate EOS. + */ +CURLcode Curl_creader_set_null(struct Curl_easy *data); + +/** + * Set the client reader the reads from fread callback. + */ +CURLcode Curl_creader_set_fread(struct Curl_easy *data, curl_off_t len); + +/** + * Set the client reader the reads from the supplied buf (NOT COPIED). + */ +CURLcode Curl_creader_set_buf(struct Curl_easy *data, + const char *buf, size_t blen); + +#endif /* HEADER_CURL_SENDF_H */ diff --git a/third_party/curl/lib/setopt.c b/third_party/curl/lib/setopt.c new file mode 100644 index 0000000..e8b2545 --- /dev/null +++ b/third_party/curl/lib/setopt.c @@ -0,0 +1,3213 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#ifdef HAVE_NETINET_IN_H +#include +#endif + +#ifdef HAVE_LINUX_TCP_H +#include +#elif defined(HAVE_NETINET_TCP_H) +#include +#endif + +#include "urldata.h" +#include "url.h" +#include "progress.h" +#include "content_encoding.h" +#include "strcase.h" +#include "share.h" +#include "vtls/vtls.h" +#include "warnless.h" +#include "sendf.h" +#include "http2.h" +#include "setopt.h" +#include "multiif.h" +#include "altsvc.h" +#include "hsts.h" +#include "tftp.h" +#include "strdup.h" +#include "escape.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +CURLcode Curl_setstropt(char **charp, const char *s) +{ + /* Release the previous storage at `charp' and replace by a dynamic storage + copy of `s'. Return CURLE_OK or CURLE_OUT_OF_MEMORY. */ + + Curl_safefree(*charp); + + if(s) { + if(strlen(s) > CURL_MAX_INPUT_LENGTH) + return CURLE_BAD_FUNCTION_ARGUMENT; + + *charp = strdup(s); + if(!*charp) + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} + +CURLcode Curl_setblobopt(struct curl_blob **blobp, + const struct curl_blob *blob) +{ + /* free the previous storage at `blobp' and replace by a dynamic storage + copy of blob. If CURL_BLOB_COPY is set, the data is copied. */ + + Curl_safefree(*blobp); + + if(blob) { + struct curl_blob *nblob; + if(blob->len > CURL_MAX_INPUT_LENGTH) + return CURLE_BAD_FUNCTION_ARGUMENT; + nblob = (struct curl_blob *) + malloc(sizeof(struct curl_blob) + + ((blob->flags & CURL_BLOB_COPY) ? blob->len : 0)); + if(!nblob) + return CURLE_OUT_OF_MEMORY; + *nblob = *blob; + if(blob->flags & CURL_BLOB_COPY) { + /* put the data after the blob struct in memory */ + nblob->data = (char *)nblob + sizeof(struct curl_blob); + memcpy(nblob->data, blob->data, blob->len); + } + + *blobp = nblob; + return CURLE_OK; + } + + return CURLE_OK; +} + +static CURLcode setstropt_userpwd(char *option, char **userp, char **passwdp) +{ + char *user = NULL; + char *passwd = NULL; + + DEBUGASSERT(userp); + DEBUGASSERT(passwdp); + + /* Parse the login details if specified. It not then we treat NULL as a hint + to clear the existing data */ + if(option) { + size_t len = strlen(option); + CURLcode result; + if(len > CURL_MAX_INPUT_LENGTH) + return CURLE_BAD_FUNCTION_ARGUMENT; + + result = Curl_parse_login_details(option, len, &user, &passwd, NULL); + if(result) + return result; + } + + free(*userp); + *userp = user; + + free(*passwdp); + *passwdp = passwd; + + return CURLE_OK; +} + +#define C_SSLVERSION_VALUE(x) (x & 0xffff) +#define C_SSLVERSION_MAX_VALUE(x) (x & 0xffff0000) + +static CURLcode protocol2num(const char *str, curl_prot_t *val) +{ + /* + * We are asked to cherry-pick protocols, so play it safe and disallow all + * protocols to start with, and re-add the wanted ones back in. + */ + *val = 0; + + if(!str) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(curl_strequal(str, "all")) { + *val = ~(curl_prot_t) 0; + return CURLE_OK; + } + + do { + const char *token = str; + size_t tlen; + + str = strchr(str, ','); + tlen = str? (size_t) (str - token): strlen(token); + if(tlen) { + const struct Curl_handler *h = Curl_getn_scheme_handler(token, tlen); + + if(!h) + return CURLE_UNSUPPORTED_PROTOCOL; + + *val |= h->protocol; + } + } while(str && str++); + + if(!*val) + /* no protocol listed */ + return CURLE_BAD_FUNCTION_ARGUMENT; + return CURLE_OK; +} + +/* + * Do not make Curl_vsetopt() static: it is called from + * packages/OS400/ccsidcurl.c. + */ +CURLcode Curl_vsetopt(struct Curl_easy *data, CURLoption option, va_list param) +{ + char *argptr; + CURLcode result = CURLE_OK; + long arg; + unsigned long uarg; + curl_off_t bigsize; + + switch(option) { + case CURLOPT_DNS_CACHE_TIMEOUT: + arg = va_arg(param, long); + if(arg < -1) + return CURLE_BAD_FUNCTION_ARGUMENT; + else if(arg > INT_MAX) + arg = INT_MAX; + + data->set.dns_cache_timeout = (int)arg; + break; + case CURLOPT_CA_CACHE_TIMEOUT: + arg = va_arg(param, long); + if(arg < -1) + return CURLE_BAD_FUNCTION_ARGUMENT; + else if(arg > INT_MAX) + arg = INT_MAX; + + data->set.general_ssl.ca_cache_timeout = (int)arg; + break; + case CURLOPT_DNS_USE_GLOBAL_CACHE: + /* deprecated */ + break; + case CURLOPT_SSL_CIPHER_LIST: + /* set a list of cipher we want to use in the SSL connection */ + result = Curl_setstropt(&data->set.str[STRING_SSL_CIPHER_LIST], + va_arg(param, char *)); + break; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_SSL_CIPHER_LIST: + /* set a list of cipher we want to use in the SSL connection for proxy */ + result = Curl_setstropt(&data->set.str[STRING_SSL_CIPHER_LIST_PROXY], + va_arg(param, char *)); + break; +#endif + case CURLOPT_TLS13_CIPHERS: + if(Curl_ssl_supports(data, SSLSUPP_TLS13_CIPHERSUITES)) { + /* set preferred list of TLS 1.3 cipher suites */ + result = Curl_setstropt(&data->set.str[STRING_SSL_CIPHER13_LIST], + va_arg(param, char *)); + } + else + return CURLE_NOT_BUILT_IN; + break; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_TLS13_CIPHERS: + if(Curl_ssl_supports(data, SSLSUPP_TLS13_CIPHERSUITES)) { + /* set preferred list of TLS 1.3 cipher suites for proxy */ + result = Curl_setstropt(&data->set.str[STRING_SSL_CIPHER13_LIST_PROXY], + va_arg(param, char *)); + } + else + return CURLE_NOT_BUILT_IN; + break; +#endif + case CURLOPT_RANDOM_FILE: + break; + case CURLOPT_EGDSOCKET: + break; + case CURLOPT_MAXCONNECTS: + /* + * Set the absolute number of maximum simultaneous alive connection that + * libcurl is allowed to have. + */ + uarg = va_arg(param, unsigned long); + if(uarg > UINT_MAX) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.maxconnects = (unsigned int)uarg; + break; + case CURLOPT_FORBID_REUSE: + /* + * When this transfer is done, it must not be left to be reused by a + * subsequent transfer but shall be closed immediately. + */ + data->set.reuse_forbid = (0 != va_arg(param, long)); + break; + case CURLOPT_FRESH_CONNECT: + /* + * This transfer shall not use a previously cached connection but + * should be made with a fresh new connect! + */ + data->set.reuse_fresh = (0 != va_arg(param, long)); + break; + case CURLOPT_VERBOSE: + /* + * Verbose means infof() calls that give a lot of information about + * the connection and transfer procedures as well as internal choices. + */ + data->set.verbose = (0 != va_arg(param, long)); + break; + case CURLOPT_HEADER: + /* + * Set to include the header in the general data output stream. + */ + data->set.include_header = (0 != va_arg(param, long)); + break; + case CURLOPT_NOPROGRESS: + /* + * Shut off the internal supported progress meter + */ + data->set.hide_progress = (0 != va_arg(param, long)); + if(data->set.hide_progress) + data->progress.flags |= PGRS_HIDE; + else + data->progress.flags &= ~PGRS_HIDE; + break; + case CURLOPT_NOBODY: + /* + * Do not include the body part in the output data stream. + */ + data->set.opt_no_body = (0 != va_arg(param, long)); +#ifndef CURL_DISABLE_HTTP + if(data->set.opt_no_body) + /* in HTTP lingo, no body means using the HEAD request... */ + data->set.method = HTTPREQ_HEAD; + else if(data->set.method == HTTPREQ_HEAD) + data->set.method = HTTPREQ_GET; +#endif + break; + case CURLOPT_FAILONERROR: + /* + * Don't output the >=400 error code HTML-page, but instead only + * return error. + */ + data->set.http_fail_on_error = (0 != va_arg(param, long)); + break; + case CURLOPT_KEEP_SENDING_ON_ERROR: + data->set.http_keep_sending_on_error = (0 != va_arg(param, long)); + break; + case CURLOPT_UPLOAD: + case CURLOPT_PUT: + /* + * We want to sent data to the remote host. If this is HTTP, that equals + * using the PUT request. + */ + arg = va_arg(param, long); + if(arg) { + /* If this is HTTP, PUT is what's needed to "upload" */ + data->set.method = HTTPREQ_PUT; + data->set.opt_no_body = FALSE; /* this is implied */ + } + else + /* In HTTP, the opposite of upload is GET (unless NOBODY is true as + then this can be changed to HEAD later on) */ + data->set.method = HTTPREQ_GET; + break; + case CURLOPT_REQUEST_TARGET: + result = Curl_setstropt(&data->set.str[STRING_TARGET], + va_arg(param, char *)); + break; + case CURLOPT_FILETIME: + /* + * Try to get the file time of the remote document. The time will + * later (possibly) become available using curl_easy_getinfo(). + */ + data->set.get_filetime = (0 != va_arg(param, long)); + break; + case CURLOPT_SERVER_RESPONSE_TIMEOUT: + /* + * Option that specifies how quickly a server response must be obtained + * before it is considered failure. For pingpong protocols. + */ + arg = va_arg(param, long); + if((arg >= 0) && (arg <= (INT_MAX/1000))) + data->set.server_response_timeout = (unsigned int)arg * 1000; + else + return CURLE_BAD_FUNCTION_ARGUMENT; + break; + case CURLOPT_SERVER_RESPONSE_TIMEOUT_MS: + /* + * Option that specifies how quickly a server response must be obtained + * before it is considered failure. For pingpong protocols. + */ + arg = va_arg(param, long); + if((arg >= 0) && (arg <= INT_MAX)) + data->set.server_response_timeout = (unsigned int)arg; + else + return CURLE_BAD_FUNCTION_ARGUMENT; + break; +#ifndef CURL_DISABLE_TFTP + case CURLOPT_TFTP_NO_OPTIONS: + /* + * Option that prevents libcurl from sending TFTP option requests to the + * server. + */ + data->set.tftp_no_options = va_arg(param, long) != 0; + break; + case CURLOPT_TFTP_BLKSIZE: + /* + * TFTP option that specifies the block size to use for data transmission. + */ + arg = va_arg(param, long); + if(arg > TFTP_BLKSIZE_MAX || arg < TFTP_BLKSIZE_MIN) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.tftp_blksize = arg; + break; +#endif +#ifndef CURL_DISABLE_NETRC + case CURLOPT_NETRC: + /* + * Parse the $HOME/.netrc file + */ + arg = va_arg(param, long); + if((arg < CURL_NETRC_IGNORED) || (arg >= CURL_NETRC_LAST)) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.use_netrc = (unsigned char)arg; + break; + case CURLOPT_NETRC_FILE: + /* + * Use this file instead of the $HOME/.netrc file + */ + result = Curl_setstropt(&data->set.str[STRING_NETRC_FILE], + va_arg(param, char *)); + break; +#endif + case CURLOPT_TRANSFERTEXT: + /* + * This option was previously named 'FTPASCII'. Renamed to work with + * more protocols than merely FTP. + * + * Transfer using ASCII (instead of BINARY). + */ + data->set.prefer_ascii = (0 != va_arg(param, long)); + break; + case CURLOPT_TIMECONDITION: + /* + * Set HTTP time condition. This must be one of the defines in the + * curl/curl.h header file. + */ + arg = va_arg(param, long); + if((arg < CURL_TIMECOND_NONE) || (arg >= CURL_TIMECOND_LAST)) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.timecondition = (unsigned char)(curl_TimeCond)arg; + break; + case CURLOPT_TIMEVALUE: + /* + * This is the value to compare with the remote document with the + * method set with CURLOPT_TIMECONDITION + */ + data->set.timevalue = (time_t)va_arg(param, long); + break; + + case CURLOPT_TIMEVALUE_LARGE: + /* + * This is the value to compare with the remote document with the + * method set with CURLOPT_TIMECONDITION + */ + data->set.timevalue = (time_t)va_arg(param, curl_off_t); + break; + + case CURLOPT_SSLVERSION: +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_SSLVERSION: +#endif + /* + * Set explicit SSL version to try to connect with, as some SSL + * implementations are lame. + */ +#ifdef USE_SSL + { + long version, version_max; + struct ssl_primary_config *primary = &data->set.ssl.primary; +#ifndef CURL_DISABLE_PROXY + if(option != CURLOPT_SSLVERSION) + primary = &data->set.proxy_ssl.primary; +#endif + + arg = va_arg(param, long); + + version = C_SSLVERSION_VALUE(arg); + version_max = C_SSLVERSION_MAX_VALUE(arg); + + if(version < CURL_SSLVERSION_DEFAULT || + version == CURL_SSLVERSION_SSLv2 || + version == CURL_SSLVERSION_SSLv3 || + version >= CURL_SSLVERSION_LAST || + version_max < CURL_SSLVERSION_MAX_NONE || + version_max >= CURL_SSLVERSION_MAX_LAST) + return CURLE_BAD_FUNCTION_ARGUMENT; + + primary->version = (unsigned char)version; + primary->version_max = (unsigned int)version_max; + } +#else + result = CURLE_NOT_BUILT_IN; +#endif + break; + + /* MQTT "borrows" some of the HTTP options */ +#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_MQTT) + case CURLOPT_COPYPOSTFIELDS: + /* + * A string with POST data. Makes curl HTTP POST. Even if it is NULL. + * If needed, CURLOPT_POSTFIELDSIZE must have been set prior to + * CURLOPT_COPYPOSTFIELDS and not altered later. + */ + argptr = va_arg(param, char *); + + if(!argptr || data->set.postfieldsize == -1) + result = Curl_setstropt(&data->set.str[STRING_COPYPOSTFIELDS], argptr); + else { + /* + * Check that requested length does not overflow the size_t type. + */ + + if((data->set.postfieldsize < 0) || + ((sizeof(curl_off_t) != sizeof(size_t)) && + (data->set.postfieldsize > (curl_off_t)((size_t)-1)))) + result = CURLE_OUT_OF_MEMORY; + else { + /* Allocate even when size == 0. This satisfies the need of possible + later address compare to detect the COPYPOSTFIELDS mode, and to + mark that postfields is used rather than read function or form + data. + */ + char *p = Curl_memdup0(argptr, (size_t)data->set.postfieldsize); + if(!p) + result = CURLE_OUT_OF_MEMORY; + else { + free(data->set.str[STRING_COPYPOSTFIELDS]); + data->set.str[STRING_COPYPOSTFIELDS] = p; + } + } + } + + data->set.postfields = data->set.str[STRING_COPYPOSTFIELDS]; + data->set.method = HTTPREQ_POST; + break; + + case CURLOPT_POSTFIELDS: + /* + * Like above, but use static data instead of copying it. + */ + data->set.postfields = va_arg(param, void *); + /* Release old copied data. */ + Curl_safefree(data->set.str[STRING_COPYPOSTFIELDS]); + data->set.method = HTTPREQ_POST; + break; + + case CURLOPT_POSTFIELDSIZE: + /* + * The size of the POSTFIELD data to prevent libcurl to do strlen() to + * figure it out. Enables binary posts. + */ + bigsize = va_arg(param, long); + if(bigsize < -1) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(data->set.postfieldsize < bigsize && + data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) { + /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */ + Curl_safefree(data->set.str[STRING_COPYPOSTFIELDS]); + data->set.postfields = NULL; + } + + data->set.postfieldsize = bigsize; + break; + + case CURLOPT_POSTFIELDSIZE_LARGE: + /* + * The size of the POSTFIELD data to prevent libcurl to do strlen() to + * figure it out. Enables binary posts. + */ + bigsize = va_arg(param, curl_off_t); + if(bigsize < -1) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(data->set.postfieldsize < bigsize && + data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) { + /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */ + Curl_safefree(data->set.str[STRING_COPYPOSTFIELDS]); + data->set.postfields = NULL; + } + + data->set.postfieldsize = bigsize; + break; +#endif +#ifndef CURL_DISABLE_HTTP + case CURLOPT_AUTOREFERER: + /* + * Switch on automatic referer that gets set if curl follows locations. + */ + data->set.http_auto_referer = (0 != va_arg(param, long)); + break; + + case CURLOPT_ACCEPT_ENCODING: + /* + * String to use at the value of Accept-Encoding header. + * + * If the encoding is set to "" we use an Accept-Encoding header that + * encompasses all the encodings we support. + * If the encoding is set to NULL we don't send an Accept-Encoding header + * and ignore an received Content-Encoding header. + * + */ + argptr = va_arg(param, char *); + if(argptr && !*argptr) { + char all[256]; + Curl_all_content_encodings(all, sizeof(all)); + result = Curl_setstropt(&data->set.str[STRING_ENCODING], all); + } + else + result = Curl_setstropt(&data->set.str[STRING_ENCODING], argptr); + break; + + case CURLOPT_TRANSFER_ENCODING: + data->set.http_transfer_encoding = (0 != va_arg(param, long)); + break; + + case CURLOPT_FOLLOWLOCATION: + /* + * Follow Location: header hints on an HTTP-server. + */ + data->set.http_follow_location = (0 != va_arg(param, long)); + break; + + case CURLOPT_UNRESTRICTED_AUTH: + /* + * Send authentication (user+password) when following locations, even when + * hostname changed. + */ + data->set.allow_auth_to_other_hosts = (0 != va_arg(param, long)); + break; + + case CURLOPT_MAXREDIRS: + /* + * The maximum amount of hops you allow curl to follow Location: + * headers. This should mostly be used to detect never-ending loops. + */ + arg = va_arg(param, long); + if(arg < -1) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.maxredirs = arg; + break; + + case CURLOPT_POSTREDIR: + /* + * Set the behavior of POST when redirecting + * CURL_REDIR_GET_ALL - POST is changed to GET after 301 and 302 + * CURL_REDIR_POST_301 - POST is kept as POST after 301 + * CURL_REDIR_POST_302 - POST is kept as POST after 302 + * CURL_REDIR_POST_303 - POST is kept as POST after 303 + * CURL_REDIR_POST_ALL - POST is kept as POST after 301, 302 and 303 + * other - POST is kept as POST after 301 and 302 + */ + arg = va_arg(param, long); + if(arg < CURL_REDIR_GET_ALL) + /* no return error on too high numbers since the bitmask could be + extended in a future */ + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.keep_post = arg & CURL_REDIR_POST_ALL; + break; + + case CURLOPT_POST: + /* Does this option serve a purpose anymore? Yes it does, when + CURLOPT_POSTFIELDS isn't used and the POST data is read off the + callback! */ + if(va_arg(param, long)) { + data->set.method = HTTPREQ_POST; + data->set.opt_no_body = FALSE; /* this is implied */ + } + else + data->set.method = HTTPREQ_GET; + break; + +#ifndef CURL_DISABLE_FORM_API + case CURLOPT_HTTPPOST: + /* + * Set to make us do HTTP POST. Legacy API-style. + */ + data->set.httppost = va_arg(param, struct curl_httppost *); + data->set.method = HTTPREQ_POST_FORM; + data->set.opt_no_body = FALSE; /* this is implied */ + Curl_mime_cleanpart(data->state.formp); + Curl_safefree(data->state.formp); + data->state.mimepost = NULL; + break; +#endif + +#if !defined(CURL_DISABLE_AWS) + case CURLOPT_AWS_SIGV4: + /* + * String that is merged to some authentication + * parameters are used by the algorithm. + */ + result = Curl_setstropt(&data->set.str[STRING_AWS_SIGV4], + va_arg(param, char *)); + /* + * Basic been set by default it need to be unset here + */ + if(data->set.str[STRING_AWS_SIGV4]) + data->set.httpauth = CURLAUTH_AWS_SIGV4; + break; +#endif + + case CURLOPT_REFERER: + /* + * String to set in the HTTP Referer: field. + */ + if(data->state.referer_alloc) { + Curl_safefree(data->state.referer); + data->state.referer_alloc = FALSE; + } + result = Curl_setstropt(&data->set.str[STRING_SET_REFERER], + va_arg(param, char *)); + data->state.referer = data->set.str[STRING_SET_REFERER]; + break; + + case CURLOPT_USERAGENT: + /* + * String to use in the HTTP User-Agent field + */ + result = Curl_setstropt(&data->set.str[STRING_USERAGENT], + va_arg(param, char *)); + break; + +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXYHEADER: + /* + * Set a list with proxy headers to use (or replace internals with) + * + * Since CURLOPT_HTTPHEADER was the only way to set HTTP headers for a + * long time we remain doing it this way until CURLOPT_PROXYHEADER is + * used. As soon as this option has been used, if set to anything but + * NULL, custom headers for proxies are only picked from this list. + * + * Set this option to NULL to restore the previous behavior. + */ + data->set.proxyheaders = va_arg(param, struct curl_slist *); + break; +#endif + case CURLOPT_HEADEROPT: + /* + * Set header option. + */ + arg = va_arg(param, long); + data->set.sep_headers = !!(arg & CURLHEADER_SEPARATE); + break; + +#if !defined(CURL_DISABLE_COOKIES) + case CURLOPT_COOKIE: + /* + * Cookie string to send to the remote server in the request. + */ + result = Curl_setstropt(&data->set.str[STRING_COOKIE], + va_arg(param, char *)); + break; + + case CURLOPT_COOKIEFILE: + /* + * Set cookie file to read and parse. Can be used multiple times. + */ + argptr = (char *)va_arg(param, void *); + if(argptr) { + struct curl_slist *cl; + /* general protection against mistakes and abuse */ + if(strlen(argptr) > CURL_MAX_INPUT_LENGTH) + return CURLE_BAD_FUNCTION_ARGUMENT; + /* append the cookie file name to the list of file names, and deal with + them later */ + cl = curl_slist_append(data->state.cookielist, argptr); + if(!cl) { + curl_slist_free_all(data->state.cookielist); + data->state.cookielist = NULL; + return CURLE_OUT_OF_MEMORY; + } + data->state.cookielist = cl; /* store the list for later use */ + } + else { + /* clear the list of cookie files */ + curl_slist_free_all(data->state.cookielist); + data->state.cookielist = NULL; + + if(!data->share || !data->share->cookies) { + /* throw away all existing cookies if this isn't a shared cookie + container */ + Curl_cookie_clearall(data->cookies); + Curl_cookie_cleanup(data->cookies); + } + /* disable the cookie engine */ + data->cookies = NULL; + } + break; + + case CURLOPT_COOKIEJAR: + /* + * Set cookie file name to dump all cookies to when we're done. + */ + result = Curl_setstropt(&data->set.str[STRING_COOKIEJAR], + va_arg(param, char *)); + if(!result) { + /* + * Activate the cookie parser. This may or may not already + * have been made. + */ + struct CookieInfo *newcookies = + Curl_cookie_init(data, NULL, data->cookies, data->set.cookiesession); + if(!newcookies) + result = CURLE_OUT_OF_MEMORY; + data->cookies = newcookies; + } + break; + + case CURLOPT_COOKIESESSION: + /* + * Set this option to TRUE to start a new "cookie session". It will + * prevent the forthcoming read-cookies-from-file actions to accept + * cookies that are marked as being session cookies, as they belong to a + * previous session. + */ + data->set.cookiesession = (0 != va_arg(param, long)); + break; + + case CURLOPT_COOKIELIST: + argptr = va_arg(param, char *); + + if(!argptr) + break; + + if(strcasecompare(argptr, "ALL")) { + /* clear all cookies */ + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + Curl_cookie_clearall(data->cookies); + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); + } + else if(strcasecompare(argptr, "SESS")) { + /* clear session cookies */ + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + Curl_cookie_clearsess(data->cookies); + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); + } + else if(strcasecompare(argptr, "FLUSH")) { + /* flush cookies to file, takes care of the locking */ + Curl_flush_cookies(data, FALSE); + } + else if(strcasecompare(argptr, "RELOAD")) { + /* reload cookies from file */ + Curl_cookie_loadfiles(data); + break; + } + else { + if(!data->cookies) + /* if cookie engine was not running, activate it */ + data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE); + + /* general protection against mistakes and abuse */ + if(strlen(argptr) > CURL_MAX_INPUT_LENGTH) + return CURLE_BAD_FUNCTION_ARGUMENT; + argptr = strdup(argptr); + if(!argptr || !data->cookies) { + result = CURLE_OUT_OF_MEMORY; + free(argptr); + } + else { + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + + if(checkprefix("Set-Cookie:", argptr)) + /* HTTP Header format line */ + Curl_cookie_add(data, data->cookies, TRUE, FALSE, argptr + 11, NULL, + NULL, TRUE); + + else + /* Netscape format line */ + Curl_cookie_add(data, data->cookies, FALSE, FALSE, argptr, NULL, + NULL, TRUE); + + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); + free(argptr); + } + } + + break; +#endif /* !CURL_DISABLE_COOKIES */ + + case CURLOPT_HTTPGET: + /* + * Set to force us do HTTP GET + */ + if(va_arg(param, long)) { + data->set.method = HTTPREQ_GET; + data->set.opt_no_body = FALSE; /* this is implied */ + } + break; + + case CURLOPT_HTTP_VERSION: + /* + * This sets a requested HTTP version to be used. The value is one of + * the listed enums in curl/curl.h. + */ + arg = va_arg(param, long); + switch(arg) { + case CURL_HTTP_VERSION_NONE: +#ifdef USE_HTTP2 + /* TODO: this seems an undesirable quirk to force a behaviour on + * lower implementations that they should recognize independently? */ + arg = CURL_HTTP_VERSION_2TLS; +#endif + /* accepted */ + break; + case CURL_HTTP_VERSION_1_0: + case CURL_HTTP_VERSION_1_1: + /* accepted */ + break; +#ifdef USE_HTTP2 + case CURL_HTTP_VERSION_2_0: + case CURL_HTTP_VERSION_2TLS: + case CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE: + /* accepted */ + break; +#endif +#ifdef USE_HTTP3 + case CURL_HTTP_VERSION_3: + case CURL_HTTP_VERSION_3ONLY: + /* accepted */ + break; +#endif + default: + /* not accepted */ + if(arg < CURL_HTTP_VERSION_NONE) + return CURLE_BAD_FUNCTION_ARGUMENT; + return CURLE_UNSUPPORTED_PROTOCOL; + } + data->set.httpwant = (unsigned char)arg; + break; + + case CURLOPT_EXPECT_100_TIMEOUT_MS: + /* + * Time to wait for a response to an HTTP request containing an + * Expect: 100-continue header before sending the data anyway. + */ + arg = va_arg(param, long); + if(arg < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.expect_100_timeout = arg; + break; + + case CURLOPT_HTTP09_ALLOWED: + arg = va_arg(param, unsigned long); + if(arg > 1L) + return CURLE_BAD_FUNCTION_ARGUMENT; +#ifdef USE_HYPER + /* Hyper does not support HTTP/0.9 */ + if(arg) + return CURLE_BAD_FUNCTION_ARGUMENT; +#else + data->set.http09_allowed = !!arg; +#endif + break; + + case CURLOPT_HTTP200ALIASES: + /* + * Set a list of aliases for HTTP 200 in response header + */ + data->set.http200aliases = va_arg(param, struct curl_slist *); + break; +#endif /* CURL_DISABLE_HTTP */ + +#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_IMAP) +# if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_MIME) + case CURLOPT_HTTPHEADER: + /* + * Set a list with HTTP headers to use (or replace internals with) + */ + data->set.headers = va_arg(param, struct curl_slist *); + break; +# endif + +# ifndef CURL_DISABLE_MIME + case CURLOPT_MIMEPOST: + /* + * Set to make us do MIME POST + */ + result = Curl_mime_set_subparts(&data->set.mimepost, + va_arg(param, curl_mime *), FALSE); + if(!result) { + data->set.method = HTTPREQ_POST_MIME; + data->set.opt_no_body = FALSE; /* this is implied */ +#ifndef CURL_DISABLE_FORM_API + Curl_mime_cleanpart(data->state.formp); + Curl_safefree(data->state.formp); + data->state.mimepost = NULL; +#endif + } + break; + + case CURLOPT_MIME_OPTIONS: + arg = va_arg(param, long); + data->set.mime_formescape = !!(arg & CURLMIMEOPT_FORMESCAPE); + break; +# endif +#endif + + case CURLOPT_HTTPAUTH: + /* + * Set HTTP Authentication type BITMASK. + */ + { + int bitcheck; + bool authbits; + unsigned long auth = va_arg(param, unsigned long); + + if(auth == CURLAUTH_NONE) { + data->set.httpauth = auth; + break; + } + + /* the DIGEST_IE bit is only used to set a special marker, for all the + rest we need to handle it as normal DIGEST */ + data->state.authhost.iestyle = !!(auth & CURLAUTH_DIGEST_IE); + + if(auth & CURLAUTH_DIGEST_IE) { + auth |= CURLAUTH_DIGEST; /* set standard digest bit */ + auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */ + } + + /* switch off bits we can't support */ +#ifndef USE_NTLM + auth &= ~CURLAUTH_NTLM; /* no NTLM support */ +#endif +#ifndef USE_SPNEGO + auth &= ~CURLAUTH_NEGOTIATE; /* no Negotiate (SPNEGO) auth without + GSS-API or SSPI */ +#endif + + /* check if any auth bit lower than CURLAUTH_ONLY is still set */ + bitcheck = 0; + authbits = FALSE; + while(bitcheck < 31) { + if(auth & (1UL << bitcheck++)) { + authbits = TRUE; + break; + } + } + if(!authbits) + return CURLE_NOT_BUILT_IN; /* no supported types left! */ + + data->set.httpauth = auth; + } + break; + + case CURLOPT_CUSTOMREQUEST: + /* + * Set a custom string to use as request + */ + result = Curl_setstropt(&data->set.str[STRING_CUSTOMREQUEST], + va_arg(param, char *)); + + /* we don't set + data->set.method = HTTPREQ_CUSTOM; + here, we continue as if we were using the already set type + and this just changes the actual request keyword */ + break; + +#ifndef CURL_DISABLE_PROXY + case CURLOPT_HTTPPROXYTUNNEL: + /* + * Tunnel operations through the proxy instead of normal proxy use + */ + data->set.tunnel_thru_httpproxy = (0 != va_arg(param, long)); + break; + + case CURLOPT_PROXYPORT: + /* + * Explicitly set HTTP proxy port number. + */ + arg = va_arg(param, long); + if((arg < 0) || (arg > 65535)) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.proxyport = (unsigned short)arg; + break; + + case CURLOPT_PROXYAUTH: + /* + * Set HTTP Authentication type BITMASK. + */ + { + int bitcheck; + bool authbits; + unsigned long auth = va_arg(param, unsigned long); + + if(auth == CURLAUTH_NONE) { + data->set.proxyauth = auth; + break; + } + + /* the DIGEST_IE bit is only used to set a special marker, for all the + rest we need to handle it as normal DIGEST */ + data->state.authproxy.iestyle = !!(auth & CURLAUTH_DIGEST_IE); + + if(auth & CURLAUTH_DIGEST_IE) { + auth |= CURLAUTH_DIGEST; /* set standard digest bit */ + auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */ + } + /* switch off bits we can't support */ +#ifndef USE_NTLM + auth &= ~CURLAUTH_NTLM; /* no NTLM support */ +#endif +#ifndef USE_SPNEGO + auth &= ~CURLAUTH_NEGOTIATE; /* no Negotiate (SPNEGO) auth without + GSS-API or SSPI */ +#endif + + /* check if any auth bit lower than CURLAUTH_ONLY is still set */ + bitcheck = 0; + authbits = FALSE; + while(bitcheck < 31) { + if(auth & (1UL << bitcheck++)) { + authbits = TRUE; + break; + } + } + if(!authbits) + return CURLE_NOT_BUILT_IN; /* no supported types left! */ + + data->set.proxyauth = auth; + } + break; + + case CURLOPT_PROXY: + /* + * Set proxy server:port to use as proxy. + * + * If the proxy is set to "" (and CURLOPT_SOCKS_PROXY is set to "" or NULL) + * we explicitly say that we don't want to use a proxy + * (even though there might be environment variables saying so). + * + * Setting it to NULL, means no proxy but allows the environment variables + * to decide for us (if CURLOPT_SOCKS_PROXY setting it to NULL). + */ + result = Curl_setstropt(&data->set.str[STRING_PROXY], + va_arg(param, char *)); + break; + + case CURLOPT_PRE_PROXY: + /* + * Set proxy server:port to use as SOCKS proxy. + * + * If the proxy is set to "" or NULL we explicitly say that we don't want + * to use the socks proxy. + */ + result = Curl_setstropt(&data->set.str[STRING_PRE_PROXY], + va_arg(param, char *)); + break; + + case CURLOPT_PROXYTYPE: + /* + * Set proxy type. + */ + arg = va_arg(param, long); + if((arg < CURLPROXY_HTTP) || (arg > CURLPROXY_SOCKS5_HOSTNAME)) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.proxytype = (unsigned char)(curl_proxytype)arg; + break; + + case CURLOPT_PROXY_TRANSFER_MODE: + /* + * set transfer mode (;type=) when doing FTP via an HTTP proxy + */ + switch(va_arg(param, long)) { + case 0: + data->set.proxy_transfer_mode = FALSE; + break; + case 1: + data->set.proxy_transfer_mode = TRUE; + break; + default: + /* reserve other values for future use */ + result = CURLE_BAD_FUNCTION_ARGUMENT; + break; + } + break; + + case CURLOPT_SOCKS5_AUTH: + data->set.socks5auth = (unsigned char)va_arg(param, unsigned long); + if(data->set.socks5auth & ~(CURLAUTH_BASIC | CURLAUTH_GSSAPI)) + result = CURLE_NOT_BUILT_IN; + break; +#endif /* CURL_DISABLE_PROXY */ + +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + case CURLOPT_SOCKS5_GSSAPI_NEC: + /* + * Set flag for NEC SOCK5 support + */ + data->set.socks5_gssapi_nec = (0 != va_arg(param, long)); + break; +#endif +#ifndef CURL_DISABLE_PROXY + case CURLOPT_SOCKS5_GSSAPI_SERVICE: + case CURLOPT_PROXY_SERVICE_NAME: + /* + * Set proxy authentication service name for Kerberos 5 and SPNEGO + */ + result = Curl_setstropt(&data->set.str[STRING_PROXY_SERVICE_NAME], + va_arg(param, char *)); + break; +#endif + case CURLOPT_SERVICE_NAME: + /* + * Set authentication service name for DIGEST-MD5, Kerberos 5 and SPNEGO + */ + result = Curl_setstropt(&data->set.str[STRING_SERVICE_NAME], + va_arg(param, char *)); + break; + + case CURLOPT_HEADERDATA: + /* + * Custom pointer to pass the header write callback function + */ + data->set.writeheader = (void *)va_arg(param, void *); + break; + case CURLOPT_ERRORBUFFER: + /* + * Error buffer provided by the caller to get the human readable + * error string in. + */ + data->set.errorbuffer = va_arg(param, char *); + break; + case CURLOPT_WRITEDATA: + /* + * FILE pointer to write to. Or possibly + * used as argument to the write callback. + */ + data->set.out = va_arg(param, void *); + break; + +#ifdef CURL_LIST_ONLY_PROTOCOL + case CURLOPT_DIRLISTONLY: + /* + * An option that changes the command to one that asks for a list only, no + * file info details. Used for FTP, POP3 and SFTP. + */ + data->set.list_only = (0 != va_arg(param, long)); + break; +#endif + case CURLOPT_APPEND: + /* + * We want to upload and append to an existing file. Used for FTP and + * SFTP. + */ + data->set.remote_append = (0 != va_arg(param, long)); + break; + +#ifndef CURL_DISABLE_FTP + case CURLOPT_FTP_FILEMETHOD: + /* + * How do access files over FTP. + */ + arg = va_arg(param, long); + if((arg < CURLFTPMETHOD_DEFAULT) || (arg >= CURLFTPMETHOD_LAST)) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.ftp_filemethod = (unsigned char)arg; + break; + case CURLOPT_FTPPORT: + /* + * Use FTP PORT, this also specifies which IP address to use + */ + result = Curl_setstropt(&data->set.str[STRING_FTPPORT], + va_arg(param, char *)); + data->set.ftp_use_port = !!(data->set.str[STRING_FTPPORT]); + break; + + case CURLOPT_FTP_USE_EPRT: + data->set.ftp_use_eprt = (0 != va_arg(param, long)); + break; + + case CURLOPT_FTP_USE_EPSV: + data->set.ftp_use_epsv = (0 != va_arg(param, long)); + break; + + case CURLOPT_FTP_USE_PRET: + data->set.ftp_use_pret = (0 != va_arg(param, long)); + break; + + case CURLOPT_FTP_SSL_CCC: + arg = va_arg(param, long); + if((arg < CURLFTPSSL_CCC_NONE) || (arg >= CURLFTPSSL_CCC_LAST)) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.ftp_ccc = (unsigned char)arg; + break; + + case CURLOPT_FTP_SKIP_PASV_IP: + /* + * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the + * bypass of the IP address in PASV responses. + */ + data->set.ftp_skip_ip = (0 != va_arg(param, long)); + break; + + case CURLOPT_FTP_ACCOUNT: + result = Curl_setstropt(&data->set.str[STRING_FTP_ACCOUNT], + va_arg(param, char *)); + break; + + case CURLOPT_FTP_ALTERNATIVE_TO_USER: + result = Curl_setstropt(&data->set.str[STRING_FTP_ALTERNATIVE_TO_USER], + va_arg(param, char *)); + break; + + case CURLOPT_FTPSSLAUTH: + /* + * Set a specific auth for FTP-SSL transfers. + */ + arg = va_arg(param, long); + if((arg < CURLFTPAUTH_DEFAULT) || (arg >= CURLFTPAUTH_LAST)) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.ftpsslauth = (unsigned char)(curl_ftpauth)arg; + break; +#ifdef HAVE_GSSAPI + case CURLOPT_KRBLEVEL: + /* + * A string that defines the kerberos security level. + */ + result = Curl_setstropt(&data->set.str[STRING_KRB_LEVEL], + va_arg(param, char *)); + data->set.krb = !!(data->set.str[STRING_KRB_LEVEL]); + break; +#endif +#endif +#if !defined(CURL_DISABLE_FTP) || defined(USE_SSH) + case CURLOPT_FTP_CREATE_MISSING_DIRS: + /* + * An FTP/SFTP option that modifies an upload to create missing + * directories on the server. + */ + arg = va_arg(param, long); + /* reserve other values for future use */ + if((arg < CURLFTP_CREATE_DIR_NONE) || + (arg > CURLFTP_CREATE_DIR_RETRY)) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else + data->set.ftp_create_missing_dirs = (unsigned char)arg; + break; + + case CURLOPT_POSTQUOTE: + /* + * List of RAW FTP commands to use after a transfer + */ + data->set.postquote = va_arg(param, struct curl_slist *); + break; + case CURLOPT_PREQUOTE: + /* + * List of RAW FTP commands to use prior to RETR (Wesley Laxton) + */ + data->set.prequote = va_arg(param, struct curl_slist *); + break; + case CURLOPT_QUOTE: + /* + * List of RAW FTP commands to use before a transfer + */ + data->set.quote = va_arg(param, struct curl_slist *); + break; +#endif + case CURLOPT_READDATA: + /* + * FILE pointer to read the file to be uploaded from. Or possibly + * used as argument to the read callback. + */ + data->set.in_set = va_arg(param, void *); + break; + case CURLOPT_INFILESIZE: + /* + * If known, this should inform curl about the file size of the + * to-be-uploaded file. + */ + arg = va_arg(param, long); + if(arg < -1) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.filesize = arg; + break; + case CURLOPT_INFILESIZE_LARGE: + /* + * If known, this should inform curl about the file size of the + * to-be-uploaded file. + */ + bigsize = va_arg(param, curl_off_t); + if(bigsize < -1) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.filesize = bigsize; + break; + case CURLOPT_LOW_SPEED_LIMIT: + /* + * The low speed limit that if transfers are below this for + * CURLOPT_LOW_SPEED_TIME, the transfer is aborted. + */ + arg = va_arg(param, long); + if(arg < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.low_speed_limit = arg; + break; + case CURLOPT_MAX_SEND_SPEED_LARGE: + /* + * When transfer uploads are faster then CURLOPT_MAX_SEND_SPEED_LARGE + * bytes per second the transfer is throttled.. + */ + bigsize = va_arg(param, curl_off_t); + if(bigsize < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.max_send_speed = bigsize; + break; + case CURLOPT_MAX_RECV_SPEED_LARGE: + /* + * When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per + * second the transfer is throttled.. + */ + bigsize = va_arg(param, curl_off_t); + if(bigsize < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.max_recv_speed = bigsize; + break; + case CURLOPT_LOW_SPEED_TIME: + /* + * The low speed time that if transfers are below the set + * CURLOPT_LOW_SPEED_LIMIT during this time, the transfer is aborted. + */ + arg = va_arg(param, long); + if(arg < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.low_speed_time = arg; + break; + case CURLOPT_CURLU: + /* + * pass CURLU to set URL + */ + data->set.uh = va_arg(param, CURLU *); + break; + case CURLOPT_URL: + /* + * The URL to fetch. + */ + if(data->state.url_alloc) { + /* the already set URL is allocated, free it first! */ + Curl_safefree(data->state.url); + data->state.url_alloc = FALSE; + } + result = Curl_setstropt(&data->set.str[STRING_SET_URL], + va_arg(param, char *)); + data->state.url = data->set.str[STRING_SET_URL]; + break; + case CURLOPT_PORT: + /* + * The port number to use when getting the URL. 0 disables it. + */ + arg = va_arg(param, long); + if((arg < 0) || (arg > 65535)) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.use_port = (unsigned short)arg; + break; + case CURLOPT_TIMEOUT: + /* + * The maximum time you allow curl to use for a single transfer + * operation. + */ + arg = va_arg(param, long); + if((arg >= 0) && (arg <= (INT_MAX/1000))) + data->set.timeout = (unsigned int)arg * 1000; + else + return CURLE_BAD_FUNCTION_ARGUMENT; + break; + + case CURLOPT_TIMEOUT_MS: + uarg = va_arg(param, unsigned long); + if(uarg > UINT_MAX) + uarg = UINT_MAX; + data->set.timeout = (unsigned int)uarg; + break; + + case CURLOPT_CONNECTTIMEOUT: + /* + * The maximum time you allow curl to use to connect. + */ + arg = va_arg(param, long); + if((arg >= 0) && (arg <= (INT_MAX/1000))) + data->set.connecttimeout = (unsigned int)arg * 1000; + else + return CURLE_BAD_FUNCTION_ARGUMENT; + break; + + case CURLOPT_CONNECTTIMEOUT_MS: + uarg = va_arg(param, unsigned long); + if(uarg > UINT_MAX) + uarg = UINT_MAX; + data->set.connecttimeout = (unsigned int)uarg; + break; + +#ifndef CURL_DISABLE_FTP + case CURLOPT_ACCEPTTIMEOUT_MS: + /* + * The maximum time for curl to wait for FTP server connect + */ + uarg = va_arg(param, unsigned long); + if(uarg > UINT_MAX) + uarg = UINT_MAX; + data->set.accepttimeout = (unsigned int)uarg; + break; +#endif + + case CURLOPT_USERPWD: + /* + * user:password to use in the operation + */ + result = setstropt_userpwd(va_arg(param, char *), + &data->set.str[STRING_USERNAME], + &data->set.str[STRING_PASSWORD]); + break; + + case CURLOPT_USERNAME: + /* + * authentication user name to use in the operation + */ + result = Curl_setstropt(&data->set.str[STRING_USERNAME], + va_arg(param, char *)); + break; + case CURLOPT_PASSWORD: + /* + * authentication password to use in the operation + */ + result = Curl_setstropt(&data->set.str[STRING_PASSWORD], + va_arg(param, char *)); + break; + + case CURLOPT_LOGIN_OPTIONS: + /* + * authentication options to use in the operation + */ + result = Curl_setstropt(&data->set.str[STRING_OPTIONS], + va_arg(param, char *)); + break; + + case CURLOPT_XOAUTH2_BEARER: + /* + * OAuth 2.0 bearer token to use in the operation + */ + result = Curl_setstropt(&data->set.str[STRING_BEARER], + va_arg(param, char *)); + break; + + case CURLOPT_RESOLVE: + /* + * List of HOST:PORT:[addresses] strings to populate the DNS cache with + * Entries added this way will remain in the cache until explicitly + * removed or the handle is cleaned up. + * + * Prefix the HOST with plus sign (+) to have the entry expire just like + * automatically added entries. + * + * Prefix the HOST with dash (-) to _remove_ the entry from the cache. + * + * This API can remove any entry from the DNS cache, but only entries + * that aren't actually in use right now will be pruned immediately. + */ + data->set.resolve = va_arg(param, struct curl_slist *); + data->state.resolve = data->set.resolve; + break; + case CURLOPT_PROGRESSFUNCTION: + /* + * Progress callback function + */ + data->set.fprogress = va_arg(param, curl_progress_callback); + if(data->set.fprogress) + data->progress.callback = TRUE; /* no longer internal */ + else + data->progress.callback = FALSE; /* NULL enforces internal */ + break; + + case CURLOPT_XFERINFOFUNCTION: + /* + * Transfer info callback function + */ + data->set.fxferinfo = va_arg(param, curl_xferinfo_callback); + if(data->set.fxferinfo) + data->progress.callback = TRUE; /* no longer internal */ + else + data->progress.callback = FALSE; /* NULL enforces internal */ + + break; + + case CURLOPT_PROGRESSDATA: + /* + * Custom client data to pass to the progress callback + */ + data->set.progress_client = va_arg(param, void *); + break; + +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXYUSERPWD: { + /* + * user:password needed to use the proxy + */ + char *u = NULL; + char *p = NULL; + result = setstropt_userpwd(va_arg(param, char *), &u, &p); + + /* URL decode the components */ + if(!result && u) + result = Curl_urldecode(u, 0, &data->set.str[STRING_PROXYUSERNAME], NULL, + REJECT_ZERO); + if(!result && p) + result = Curl_urldecode(p, 0, &data->set.str[STRING_PROXYPASSWORD], NULL, + REJECT_ZERO); + free(u); + free(p); + } + break; + case CURLOPT_PROXYUSERNAME: + /* + * authentication user name to use in the operation + */ + result = Curl_setstropt(&data->set.str[STRING_PROXYUSERNAME], + va_arg(param, char *)); + break; + case CURLOPT_PROXYPASSWORD: + /* + * authentication password to use in the operation + */ + result = Curl_setstropt(&data->set.str[STRING_PROXYPASSWORD], + va_arg(param, char *)); + break; + case CURLOPT_NOPROXY: + /* + * proxy exception list + */ + result = Curl_setstropt(&data->set.str[STRING_NOPROXY], + va_arg(param, char *)); + break; +#endif + + case CURLOPT_RANGE: + /* + * What range of the file you want to transfer + */ + result = Curl_setstropt(&data->set.str[STRING_SET_RANGE], + va_arg(param, char *)); + break; + case CURLOPT_RESUME_FROM: + /* + * Resume transfer at the given file position + */ + arg = va_arg(param, long); + if(arg < -1) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.set_resume_from = arg; + break; + case CURLOPT_RESUME_FROM_LARGE: + /* + * Resume transfer at the given file position + */ + bigsize = va_arg(param, curl_off_t); + if(bigsize < -1) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.set_resume_from = bigsize; + break; + case CURLOPT_DEBUGFUNCTION: + /* + * stderr write callback. + */ + data->set.fdebug = va_arg(param, curl_debug_callback); + /* + * if the callback provided is NULL, it'll use the default callback + */ + break; + case CURLOPT_DEBUGDATA: + /* + * Set to a void * that should receive all error writes. This + * defaults to CURLOPT_STDERR for normal operations. + */ + data->set.debugdata = va_arg(param, void *); + break; + case CURLOPT_STDERR: + /* + * Set to a FILE * that should receive all error writes. This + * defaults to stderr for normal operations. + */ + data->set.err = va_arg(param, FILE *); + if(!data->set.err) + data->set.err = stderr; + break; + case CURLOPT_HEADERFUNCTION: + /* + * Set header write callback + */ + data->set.fwrite_header = va_arg(param, curl_write_callback); + break; + case CURLOPT_WRITEFUNCTION: + /* + * Set data write callback + */ + data->set.fwrite_func = va_arg(param, curl_write_callback); + if(!data->set.fwrite_func) + /* When set to NULL, reset to our internal default function */ + data->set.fwrite_func = (curl_write_callback)fwrite; + break; + case CURLOPT_READFUNCTION: + /* + * Read data callback + */ + data->set.fread_func_set = va_arg(param, curl_read_callback); + if(!data->set.fread_func_set) { + data->set.is_fread_set = 0; + /* When set to NULL, reset to our internal default function */ + data->set.fread_func_set = (curl_read_callback)fread; + } + else + data->set.is_fread_set = 1; + break; + case CURLOPT_SEEKFUNCTION: + /* + * Seek callback. Might be NULL. + */ + data->set.seek_func = va_arg(param, curl_seek_callback); + break; + case CURLOPT_SEEKDATA: + /* + * Seek control callback. Might be NULL. + */ + data->set.seek_client = va_arg(param, void *); + break; + case CURLOPT_IOCTLFUNCTION: + /* + * I/O control callback. Might be NULL. + */ + data->set.ioctl_func = va_arg(param, curl_ioctl_callback); + break; + case CURLOPT_IOCTLDATA: + /* + * I/O control data pointer. Might be NULL. + */ + data->set.ioctl_client = va_arg(param, void *); + break; + case CURLOPT_SSLCERT: + /* + * String that holds file name of the SSL certificate to use + */ + result = Curl_setstropt(&data->set.str[STRING_CERT], + va_arg(param, char *)); + break; + case CURLOPT_SSLCERT_BLOB: + /* + * Blob that holds file content of the SSL certificate to use + */ + result = Curl_setblobopt(&data->set.blobs[BLOB_CERT], + va_arg(param, struct curl_blob *)); + break; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_SSLCERT: + /* + * String that holds file name of the SSL certificate to use for proxy + */ + result = Curl_setstropt(&data->set.str[STRING_CERT_PROXY], + va_arg(param, char *)); + break; + case CURLOPT_PROXY_SSLCERT_BLOB: + /* + * Blob that holds file content of the SSL certificate to use for proxy + */ + result = Curl_setblobopt(&data->set.blobs[BLOB_CERT_PROXY], + va_arg(param, struct curl_blob *)); + break; +#endif + case CURLOPT_SSLCERTTYPE: + /* + * String that holds file type of the SSL certificate to use + */ + result = Curl_setstropt(&data->set.str[STRING_CERT_TYPE], + va_arg(param, char *)); + break; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_SSLCERTTYPE: + /* + * String that holds file type of the SSL certificate to use for proxy + */ + result = Curl_setstropt(&data->set.str[STRING_CERT_TYPE_PROXY], + va_arg(param, char *)); + break; +#endif + case CURLOPT_SSLKEY: + /* + * String that holds file name of the SSL key to use + */ + result = Curl_setstropt(&data->set.str[STRING_KEY], + va_arg(param, char *)); + break; + case CURLOPT_SSLKEY_BLOB: + /* + * Blob that holds file content of the SSL key to use + */ + result = Curl_setblobopt(&data->set.blobs[BLOB_KEY], + va_arg(param, struct curl_blob *)); + break; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_SSLKEY: + /* + * String that holds file name of the SSL key to use for proxy + */ + result = Curl_setstropt(&data->set.str[STRING_KEY_PROXY], + va_arg(param, char *)); + break; + case CURLOPT_PROXY_SSLKEY_BLOB: + /* + * Blob that holds file content of the SSL key to use for proxy + */ + result = Curl_setblobopt(&data->set.blobs[BLOB_KEY_PROXY], + va_arg(param, struct curl_blob *)); + break; +#endif + case CURLOPT_SSLKEYTYPE: + /* + * String that holds file type of the SSL key to use + */ + result = Curl_setstropt(&data->set.str[STRING_KEY_TYPE], + va_arg(param, char *)); + break; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_SSLKEYTYPE: + /* + * String that holds file type of the SSL key to use for proxy + */ + result = Curl_setstropt(&data->set.str[STRING_KEY_TYPE_PROXY], + va_arg(param, char *)); + break; +#endif + case CURLOPT_KEYPASSWD: + /* + * String that holds the SSL or SSH private key password. + */ + result = Curl_setstropt(&data->set.str[STRING_KEY_PASSWD], + va_arg(param, char *)); + break; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_KEYPASSWD: + /* + * String that holds the SSL private key password for proxy. + */ + result = Curl_setstropt(&data->set.str[STRING_KEY_PASSWD_PROXY], + va_arg(param, char *)); + break; +#endif + case CURLOPT_SSLENGINE: + /* + * String that holds the SSL crypto engine. + */ + argptr = va_arg(param, char *); + if(argptr && argptr[0]) { + result = Curl_setstropt(&data->set.str[STRING_SSL_ENGINE], argptr); + if(!result) { + result = Curl_ssl_set_engine(data, argptr); + } + } + break; + + case CURLOPT_SSLENGINE_DEFAULT: + /* + * flag to set engine as default. + */ + Curl_safefree(data->set.str[STRING_SSL_ENGINE]); + result = Curl_ssl_set_engine_default(data); + break; + case CURLOPT_CRLF: + /* + * Kludgy option to enable CRLF conversions. Subject for removal. + */ + data->set.crlf = (0 != va_arg(param, long)); + break; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_HAPROXYPROTOCOL: + /* + * Set to send the HAProxy Proxy Protocol header + */ + data->set.haproxyprotocol = (0 != va_arg(param, long)); + break; + case CURLOPT_HAPROXY_CLIENT_IP: + /* + * Set the client IP to send through HAProxy PROXY protocol + */ + result = Curl_setstropt(&data->set.str[STRING_HAPROXY_CLIENT_IP], + va_arg(param, char *)); + /* We enable implicitly the HAProxy protocol if we use this flag. */ + data->set.haproxyprotocol = TRUE; + break; +#endif + case CURLOPT_INTERFACE: + /* + * Set what interface or address/hostname to bind the socket to when + * performing an operation and thus what from-IP your connection will use. + */ + result = Curl_setstropt(&data->set.str[STRING_DEVICE], + va_arg(param, char *)); + break; +#ifndef CURL_DISABLE_BINDLOCAL + case CURLOPT_LOCALPORT: + /* + * Set what local port to bind the socket to when performing an operation. + */ + arg = va_arg(param, long); + if((arg < 0) || (arg > 65535)) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.localport = curlx_sltous(arg); + break; + case CURLOPT_LOCALPORTRANGE: + /* + * Set number of local ports to try, starting with CURLOPT_LOCALPORT. + */ + arg = va_arg(param, long); + if((arg < 0) || (arg > 65535)) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.localportrange = curlx_sltous(arg); + break; +#endif + case CURLOPT_GSSAPI_DELEGATION: + /* + * GSS-API credential delegation bitmask + */ + uarg = va_arg(param, unsigned long); + data->set.gssapi_delegation = (unsigned char)uarg& + (CURLGSSAPI_DELEGATION_POLICY_FLAG|CURLGSSAPI_DELEGATION_FLAG); + break; + case CURLOPT_SSL_VERIFYPEER: + /* + * Enable peer SSL verifying. + */ + data->set.ssl.primary.verifypeer = (0 != va_arg(param, long)); + + /* Update the current connection ssl_config. */ + Curl_ssl_conn_config_update(data, FALSE); + break; +#ifndef CURL_DISABLE_DOH + case CURLOPT_DOH_SSL_VERIFYPEER: + /* + * Enable peer SSL verifying for DoH. + */ + data->set.doh_verifypeer = (0 != va_arg(param, long)); + break; +#endif +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_SSL_VERIFYPEER: + /* + * Enable peer SSL verifying for proxy. + */ + data->set.proxy_ssl.primary.verifypeer = + (0 != va_arg(param, long))?TRUE:FALSE; + + /* Update the current connection proxy_ssl_config. */ + Curl_ssl_conn_config_update(data, TRUE); + break; +#endif + case CURLOPT_SSL_VERIFYHOST: + /* + * Enable verification of the host name in the peer certificate + */ + arg = va_arg(param, long); + + /* Obviously people are not reading documentation and too many thought + this argument took a boolean when it wasn't and misused it. + Treat 1 and 2 the same */ + data->set.ssl.primary.verifyhost = !!(arg & 3); + + /* Update the current connection ssl_config. */ + Curl_ssl_conn_config_update(data, FALSE); + break; +#ifndef CURL_DISABLE_DOH + case CURLOPT_DOH_SSL_VERIFYHOST: + /* + * Enable verification of the host name in the peer certificate for DoH + */ + arg = va_arg(param, long); + + /* Treat both 1 and 2 as TRUE */ + data->set.doh_verifyhost = !!(arg & 3); + break; +#endif +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_SSL_VERIFYHOST: + /* + * Enable verification of the host name in the peer certificate for proxy + */ + arg = va_arg(param, long); + + /* Treat both 1 and 2 as TRUE */ + data->set.proxy_ssl.primary.verifyhost = (bool)((arg & 3)?TRUE:FALSE); + /* Update the current connection proxy_ssl_config. */ + Curl_ssl_conn_config_update(data, TRUE); + break; +#endif + case CURLOPT_SSL_VERIFYSTATUS: + /* + * Enable certificate status verifying. + */ + if(!Curl_ssl_cert_status_request()) { + result = CURLE_NOT_BUILT_IN; + break; + } + + data->set.ssl.primary.verifystatus = (0 != va_arg(param, long)); + + /* Update the current connection ssl_config. */ + Curl_ssl_conn_config_update(data, FALSE); + break; +#ifndef CURL_DISABLE_DOH + case CURLOPT_DOH_SSL_VERIFYSTATUS: + /* + * Enable certificate status verifying for DoH. + */ + if(!Curl_ssl_cert_status_request()) { + result = CURLE_NOT_BUILT_IN; + break; + } + + data->set.doh_verifystatus = (0 != va_arg(param, long)); + break; +#endif + case CURLOPT_SSL_CTX_FUNCTION: + /* + * Set a SSL_CTX callback + */ +#ifdef USE_SSL + if(Curl_ssl_supports(data, SSLSUPP_SSL_CTX)) + data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback); + else +#endif + result = CURLE_NOT_BUILT_IN; + break; + case CURLOPT_SSL_CTX_DATA: + /* + * Set a SSL_CTX callback parameter pointer + */ +#ifdef USE_SSL + if(Curl_ssl_supports(data, SSLSUPP_SSL_CTX)) + data->set.ssl.fsslctxp = va_arg(param, void *); + else +#endif + result = CURLE_NOT_BUILT_IN; + break; + case CURLOPT_SSL_FALSESTART: + /* + * Enable TLS false start. + */ + if(!Curl_ssl_false_start(data)) { + result = CURLE_NOT_BUILT_IN; + break; + } + + data->set.ssl.falsestart = (0 != va_arg(param, long)); + break; + case CURLOPT_CERTINFO: +#ifdef USE_SSL + if(Curl_ssl_supports(data, SSLSUPP_CERTINFO)) + data->set.ssl.certinfo = (0 != va_arg(param, long)); + else +#endif + result = CURLE_NOT_BUILT_IN; + break; + case CURLOPT_PINNEDPUBLICKEY: + /* + * Set pinned public key for SSL connection. + * Specify file name of the public key in DER format. + */ +#ifdef USE_SSL + if(Curl_ssl_supports(data, SSLSUPP_PINNEDPUBKEY)) + result = Curl_setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY], + va_arg(param, char *)); + else +#endif + result = CURLE_NOT_BUILT_IN; + break; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_PINNEDPUBLICKEY: + /* + * Set pinned public key for SSL connection. + * Specify file name of the public key in DER format. + */ +#ifdef USE_SSL + if(Curl_ssl_supports(data, SSLSUPP_PINNEDPUBKEY)) + result = Curl_setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY], + va_arg(param, char *)); + else +#endif + result = CURLE_NOT_BUILT_IN; + break; +#endif + case CURLOPT_CAINFO: + /* + * Set CA info for SSL connection. Specify file name of the CA certificate + */ + result = Curl_setstropt(&data->set.str[STRING_SSL_CAFILE], + va_arg(param, char *)); + break; + case CURLOPT_CAINFO_BLOB: + /* + * Blob that holds CA info for SSL connection. + * Specify entire PEM of the CA certificate + */ +#ifdef USE_SSL + if(Curl_ssl_supports(data, SSLSUPP_CAINFO_BLOB)) { + result = Curl_setblobopt(&data->set.blobs[BLOB_CAINFO], + va_arg(param, struct curl_blob *)); + break; + } + else +#endif + return CURLE_NOT_BUILT_IN; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_CAINFO: + /* + * Set CA info SSL connection for proxy. Specify file name of the + * CA certificate + */ + result = Curl_setstropt(&data->set.str[STRING_SSL_CAFILE_PROXY], + va_arg(param, char *)); + break; + case CURLOPT_PROXY_CAINFO_BLOB: + /* + * Blob that holds CA info for SSL connection proxy. + * Specify entire PEM of the CA certificate + */ +#ifdef USE_SSL + if(Curl_ssl_supports(data, SSLSUPP_CAINFO_BLOB)) { + result = Curl_setblobopt(&data->set.blobs[BLOB_CAINFO_PROXY], + va_arg(param, struct curl_blob *)); + break; + } + else +#endif + return CURLE_NOT_BUILT_IN; +#endif + case CURLOPT_CAPATH: + /* + * Set CA path info for SSL connection. Specify directory name of the CA + * certificates which have been prepared using openssl c_rehash utility. + */ +#ifdef USE_SSL + if(Curl_ssl_supports(data, SSLSUPP_CA_PATH)) + /* This does not work on windows. */ + result = Curl_setstropt(&data->set.str[STRING_SSL_CAPATH], + va_arg(param, char *)); + else +#endif + result = CURLE_NOT_BUILT_IN; + break; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_CAPATH: + /* + * Set CA path info for SSL connection proxy. Specify directory name of the + * CA certificates which have been prepared using openssl c_rehash utility. + */ +#ifdef USE_SSL + if(Curl_ssl_supports(data, SSLSUPP_CA_PATH)) + /* This does not work on windows. */ + result = Curl_setstropt(&data->set.str[STRING_SSL_CAPATH_PROXY], + va_arg(param, char *)); + else +#endif + result = CURLE_NOT_BUILT_IN; + break; +#endif + case CURLOPT_CRLFILE: + /* + * Set CRL file info for SSL connection. Specify file name of the CRL + * to check certificates revocation + */ + result = Curl_setstropt(&data->set.str[STRING_SSL_CRLFILE], + va_arg(param, char *)); + break; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_CRLFILE: + /* + * Set CRL file info for SSL connection for proxy. Specify file name of the + * CRL to check certificates revocation + */ + result = Curl_setstropt(&data->set.str[STRING_SSL_CRLFILE_PROXY], + va_arg(param, char *)); + break; +#endif + case CURLOPT_ISSUERCERT: + /* + * Set Issuer certificate file + * to check certificates issuer + */ + result = Curl_setstropt(&data->set.str[STRING_SSL_ISSUERCERT], + va_arg(param, char *)); + break; + case CURLOPT_ISSUERCERT_BLOB: + /* + * Blob that holds Issuer certificate to check certificates issuer + */ + result = Curl_setblobopt(&data->set.blobs[BLOB_SSL_ISSUERCERT], + va_arg(param, struct curl_blob *)); + break; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_ISSUERCERT: + /* + * Set Issuer certificate file + * to check certificates issuer + */ + result = Curl_setstropt(&data->set.str[STRING_SSL_ISSUERCERT_PROXY], + va_arg(param, char *)); + break; + case CURLOPT_PROXY_ISSUERCERT_BLOB: + /* + * Blob that holds Issuer certificate to check certificates issuer + */ + result = Curl_setblobopt(&data->set.blobs[BLOB_SSL_ISSUERCERT_PROXY], + va_arg(param, struct curl_blob *)); + break; +#endif +#ifndef CURL_DISABLE_TELNET + case CURLOPT_TELNETOPTIONS: + /* + * Set a linked list of telnet options + */ + data->set.telnet_options = va_arg(param, struct curl_slist *); + break; +#endif + case CURLOPT_BUFFERSIZE: + /* + * The application kindly asks for a differently sized receive buffer. + * If it seems reasonable, we'll use it. + */ + arg = va_arg(param, long); + + if(arg > READBUFFER_MAX) + arg = READBUFFER_MAX; + else if(arg < 1) + arg = READBUFFER_SIZE; + else if(arg < READBUFFER_MIN) + arg = READBUFFER_MIN; + + data->set.buffer_size = (unsigned int)arg; + break; + + case CURLOPT_UPLOAD_BUFFERSIZE: + /* + * The application kindly asks for a differently sized upload buffer. + * Cap it to sensible. + */ + arg = va_arg(param, long); + + if(arg > UPLOADBUFFER_MAX) + arg = UPLOADBUFFER_MAX; + else if(arg < UPLOADBUFFER_MIN) + arg = UPLOADBUFFER_MIN; + + data->set.upload_buffer_size = (unsigned int)arg; + break; + + case CURLOPT_NOSIGNAL: + /* + * The application asks not to set any signal() or alarm() handlers, + * even when using a timeout. + */ + data->set.no_signal = (0 != va_arg(param, long)); + break; + + case CURLOPT_SHARE: + { + struct Curl_share *set; + set = va_arg(param, struct Curl_share *); + + /* disconnect from old share, if any */ + if(data->share) { + Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE); + + if(data->dns.hostcachetype == HCACHE_SHARED) { + data->dns.hostcache = NULL; + data->dns.hostcachetype = HCACHE_NONE; + } + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) + if(data->share->cookies == data->cookies) + data->cookies = NULL; +#endif + +#ifndef CURL_DISABLE_HSTS + if(data->share->hsts == data->hsts) + data->hsts = NULL; +#endif +#ifdef USE_SSL + if(data->share->sslsession == data->state.session) + data->state.session = NULL; +#endif +#ifdef USE_LIBPSL + if(data->psl == &data->share->psl) + data->psl = data->multi? &data->multi->psl: NULL; +#endif + + data->share->dirty--; + + Curl_share_unlock(data, CURL_LOCK_DATA_SHARE); + data->share = NULL; + } + + if(GOOD_SHARE_HANDLE(set)) + /* use new share if it set */ + data->share = set; + if(data->share) { + + Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE); + + data->share->dirty++; + + if(data->share->specifier & (1<< CURL_LOCK_DATA_DNS)) { + /* use shared host cache */ + data->dns.hostcache = &data->share->hostcache; + data->dns.hostcachetype = HCACHE_SHARED; + } +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) + if(data->share->cookies) { + /* use shared cookie list, first free own one if any */ + Curl_cookie_cleanup(data->cookies); + /* enable cookies since we now use a share that uses cookies! */ + data->cookies = data->share->cookies; + } +#endif /* CURL_DISABLE_HTTP */ +#ifndef CURL_DISABLE_HSTS + if(data->share->hsts) { + /* first free the private one if any */ + Curl_hsts_cleanup(&data->hsts); + data->hsts = data->share->hsts; + } +#endif +#ifdef USE_SSL + if(data->share->sslsession) { + data->set.general_ssl.max_ssl_sessions = data->share->max_ssl_sessions; + data->state.session = data->share->sslsession; + } +#endif +#ifdef USE_LIBPSL + if(data->share->specifier & (1 << CURL_LOCK_DATA_PSL)) + data->psl = &data->share->psl; +#endif + + Curl_share_unlock(data, CURL_LOCK_DATA_SHARE); + } + /* check for host cache not needed, + * it will be done by curl_easy_perform */ + } + break; + + case CURLOPT_PRIVATE: + /* + * Set private data pointer. + */ + data->set.private_data = va_arg(param, void *); + break; + + case CURLOPT_MAXFILESIZE: + /* + * Set the maximum size of a file to download. + */ + arg = va_arg(param, long); + if(arg < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.max_filesize = arg; + break; + +#ifdef USE_SSL + case CURLOPT_USE_SSL: + /* + * Make transfers attempt to use SSL/TLS. + */ + arg = va_arg(param, long); + if((arg < CURLUSESSL_NONE) || (arg >= CURLUSESSL_LAST)) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.use_ssl = (unsigned char)arg; + break; + + case CURLOPT_SSL_OPTIONS: + arg = va_arg(param, long); + data->set.ssl.primary.ssl_options = (unsigned char)(arg & 0xff); + data->set.ssl.enable_beast = !!(arg & CURLSSLOPT_ALLOW_BEAST); + data->set.ssl.no_revoke = !!(arg & CURLSSLOPT_NO_REVOKE); + data->set.ssl.no_partialchain = !!(arg & CURLSSLOPT_NO_PARTIALCHAIN); + data->set.ssl.revoke_best_effort = !!(arg & CURLSSLOPT_REVOKE_BEST_EFFORT); + data->set.ssl.native_ca_store = !!(arg & CURLSSLOPT_NATIVE_CA); + data->set.ssl.auto_client_cert = !!(arg & CURLSSLOPT_AUTO_CLIENT_CERT); + /* If a setting is added here it should also be added in dohprobe() + which sets its own CURLOPT_SSL_OPTIONS based on these settings. */ + break; + +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_SSL_OPTIONS: + arg = va_arg(param, long); + data->set.proxy_ssl.primary.ssl_options = (unsigned char)(arg & 0xff); + data->set.proxy_ssl.enable_beast = !!(arg & CURLSSLOPT_ALLOW_BEAST); + data->set.proxy_ssl.no_revoke = !!(arg & CURLSSLOPT_NO_REVOKE); + data->set.proxy_ssl.no_partialchain = !!(arg & CURLSSLOPT_NO_PARTIALCHAIN); + data->set.proxy_ssl.revoke_best_effort = + !!(arg & CURLSSLOPT_REVOKE_BEST_EFFORT); + data->set.proxy_ssl.native_ca_store = !!(arg & CURLSSLOPT_NATIVE_CA); + data->set.proxy_ssl.auto_client_cert = + !!(arg & CURLSSLOPT_AUTO_CLIENT_CERT); + break; +#endif + + case CURLOPT_SSL_EC_CURVES: + /* + * Set accepted curves in SSL connection setup. + * Specify colon-delimited list of curve algorithm names. + */ + result = Curl_setstropt(&data->set.str[STRING_SSL_EC_CURVES], + va_arg(param, char *)); + break; +#endif + case CURLOPT_IPRESOLVE: + arg = va_arg(param, long); + if((arg < CURL_IPRESOLVE_WHATEVER) || (arg > CURL_IPRESOLVE_V6)) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.ipver = (unsigned char) arg; + break; + + case CURLOPT_MAXFILESIZE_LARGE: + /* + * Set the maximum size of a file to download. + */ + bigsize = va_arg(param, curl_off_t); + if(bigsize < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.max_filesize = bigsize; + break; + + case CURLOPT_TCP_NODELAY: + /* + * Enable or disable TCP_NODELAY, which will disable/enable the Nagle + * algorithm + */ + data->set.tcp_nodelay = (0 != va_arg(param, long)); + break; + + case CURLOPT_IGNORE_CONTENT_LENGTH: + data->set.ignorecl = (0 != va_arg(param, long)); + break; + + case CURLOPT_CONNECT_ONLY: + /* + * No data transfer. + * (1) - only do connection + * (2) - do first get request but get no content + */ + arg = va_arg(param, long); + if(arg > 2) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.connect_only = (unsigned char)arg; + break; + + case CURLOPT_SOCKOPTFUNCTION: + /* + * socket callback function: called after socket() but before connect() + */ + data->set.fsockopt = va_arg(param, curl_sockopt_callback); + break; + + case CURLOPT_SOCKOPTDATA: + /* + * socket callback data pointer. Might be NULL. + */ + data->set.sockopt_client = va_arg(param, void *); + break; + + case CURLOPT_OPENSOCKETFUNCTION: + /* + * open/create socket callback function: called instead of socket(), + * before connect() + */ + data->set.fopensocket = va_arg(param, curl_opensocket_callback); + break; + + case CURLOPT_OPENSOCKETDATA: + /* + * socket callback data pointer. Might be NULL. + */ + data->set.opensocket_client = va_arg(param, void *); + break; + + case CURLOPT_CLOSESOCKETFUNCTION: + /* + * close socket callback function: called instead of close() + * when shutting down a connection + */ + data->set.fclosesocket = va_arg(param, curl_closesocket_callback); + break; + + case CURLOPT_RESOLVER_START_FUNCTION: + /* + * resolver start callback function: called before a new resolver request + * is started + */ + data->set.resolver_start = va_arg(param, curl_resolver_start_callback); + break; + + case CURLOPT_RESOLVER_START_DATA: + /* + * resolver start callback data pointer. Might be NULL. + */ + data->set.resolver_start_client = va_arg(param, void *); + break; + + case CURLOPT_CLOSESOCKETDATA: + /* + * socket callback data pointer. Might be NULL. + */ + data->set.closesocket_client = va_arg(param, void *); + break; + + case CURLOPT_SSL_SESSIONID_CACHE: + data->set.ssl.primary.sessionid = (0 != va_arg(param, long)); +#ifndef CURL_DISABLE_PROXY + data->set.proxy_ssl.primary.sessionid = data->set.ssl.primary.sessionid; +#endif + break; + +#ifdef USE_SSH + /* we only include SSH options if explicitly built to support SSH */ + case CURLOPT_SSH_AUTH_TYPES: + data->set.ssh_auth_types = (unsigned int)va_arg(param, long); + break; + + case CURLOPT_SSH_PUBLIC_KEYFILE: + /* + * Use this file instead of the $HOME/.ssh/id_dsa.pub file + */ + result = Curl_setstropt(&data->set.str[STRING_SSH_PUBLIC_KEY], + va_arg(param, char *)); + break; + + case CURLOPT_SSH_PRIVATE_KEYFILE: + /* + * Use this file instead of the $HOME/.ssh/id_dsa file + */ + result = Curl_setstropt(&data->set.str[STRING_SSH_PRIVATE_KEY], + va_arg(param, char *)); + break; + case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5: + /* + * Option to allow for the MD5 of the host public key to be checked + * for validation purposes. + */ + result = Curl_setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5], + va_arg(param, char *)); + break; + + case CURLOPT_SSH_KNOWNHOSTS: + /* + * Store the file name to read known hosts from. + */ + result = Curl_setstropt(&data->set.str[STRING_SSH_KNOWNHOSTS], + va_arg(param, char *)); + break; +#ifdef USE_LIBSSH2 + case CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256: + /* + * Option to allow for the SHA256 of the host public key to be checked + * for validation purposes. + */ + result = Curl_setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_SHA256], + va_arg(param, char *)); + break; + + case CURLOPT_SSH_HOSTKEYFUNCTION: + /* the callback to check the hostkey without the knownhost file */ + data->set.ssh_hostkeyfunc = va_arg(param, curl_sshhostkeycallback); + break; + + case CURLOPT_SSH_HOSTKEYDATA: + /* + * Custom client data to pass to the SSH keyfunc callback + */ + data->set.ssh_hostkeyfunc_userp = va_arg(param, void *); + break; +#endif + + case CURLOPT_SSH_KEYFUNCTION: + /* setting to NULL is fine since the ssh.c functions themselves will + then revert to use the internal default */ + data->set.ssh_keyfunc = va_arg(param, curl_sshkeycallback); + break; + + case CURLOPT_SSH_KEYDATA: + /* + * Custom client data to pass to the SSH keyfunc callback + */ + data->set.ssh_keyfunc_userp = va_arg(param, void *); + break; + + case CURLOPT_SSH_COMPRESSION: + data->set.ssh_compression = (0 != va_arg(param, long))?TRUE:FALSE; + break; +#endif /* USE_SSH */ + + case CURLOPT_HTTP_TRANSFER_DECODING: + /* + * disable libcurl transfer encoding is used + */ +#ifndef USE_HYPER + data->set.http_te_skip = (0 == va_arg(param, long)); + break; +#else + return CURLE_NOT_BUILT_IN; /* hyper doesn't support */ +#endif + + case CURLOPT_HTTP_CONTENT_DECODING: + /* + * raw data passed to the application when content encoding is used + */ + data->set.http_ce_skip = (0 == va_arg(param, long)); + break; + +#if !defined(CURL_DISABLE_FTP) || defined(USE_SSH) + case CURLOPT_NEW_FILE_PERMS: + /* + * Uses these permissions instead of 0644 + */ + arg = va_arg(param, long); + if((arg < 0) || (arg > 0777)) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.new_file_perms = (unsigned int)arg; + break; +#endif +#ifdef USE_SSH + case CURLOPT_NEW_DIRECTORY_PERMS: + /* + * Uses these permissions instead of 0755 + */ + arg = va_arg(param, long); + if((arg < 0) || (arg > 0777)) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.new_directory_perms = (unsigned int)arg; + break; +#endif + +#ifdef USE_IPV6 + case CURLOPT_ADDRESS_SCOPE: + /* + * Use this scope id when using IPv6 + * We always get longs when passed plain numericals so we should check + * that the value fits into an unsigned 32 bit integer. + */ + uarg = va_arg(param, unsigned long); +#if SIZEOF_LONG > 4 + if(uarg > UINT_MAX) + return CURLE_BAD_FUNCTION_ARGUMENT; +#endif + data->set.scope_id = (unsigned int)uarg; + break; +#endif + + case CURLOPT_PROTOCOLS: + /* 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. */ + data->set.allowed_protocols = (curl_prot_t)va_arg(param, long); + break; + + case CURLOPT_REDIR_PROTOCOLS: + /* 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. */ + data->set.redir_protocols = (curl_prot_t)va_arg(param, long); + break; + + case CURLOPT_PROTOCOLS_STR: { + argptr = va_arg(param, char *); + result = protocol2num(argptr, &data->set.allowed_protocols); + if(result) + return result; + break; + } + + case CURLOPT_REDIR_PROTOCOLS_STR: { + argptr = va_arg(param, char *); + result = protocol2num(argptr, &data->set.redir_protocols); + if(result) + return result; + break; + } + + case CURLOPT_DEFAULT_PROTOCOL: + /* Set the protocol to use when the URL doesn't include any protocol */ + result = Curl_setstropt(&data->set.str[STRING_DEFAULT_PROTOCOL], + va_arg(param, char *)); + break; +#ifndef CURL_DISABLE_SMTP + case CURLOPT_MAIL_FROM: + /* Set the SMTP mail originator */ + result = Curl_setstropt(&data->set.str[STRING_MAIL_FROM], + va_arg(param, char *)); + break; + + case CURLOPT_MAIL_AUTH: + /* Set the SMTP auth originator */ + result = Curl_setstropt(&data->set.str[STRING_MAIL_AUTH], + va_arg(param, char *)); + break; + + case CURLOPT_MAIL_RCPT: + /* Set the list of mail recipients */ + data->set.mail_rcpt = va_arg(param, struct curl_slist *); + break; + case CURLOPT_MAIL_RCPT_ALLOWFAILS: + /* allow RCPT TO command to fail for some recipients */ + data->set.mail_rcpt_allowfails = (0 != va_arg(param, long)); + break; +#endif + + case CURLOPT_SASL_AUTHZID: + /* Authorization identity (identity to act as) */ + result = Curl_setstropt(&data->set.str[STRING_SASL_AUTHZID], + va_arg(param, char *)); + break; + + case CURLOPT_SASL_IR: + /* Enable/disable SASL initial response */ + data->set.sasl_ir = (0 != va_arg(param, long)); + break; +#ifndef CURL_DISABLE_RTSP + case CURLOPT_RTSP_REQUEST: + { + /* + * Set the RTSP request method (OPTIONS, SETUP, PLAY, etc...) + * Would this be better if the RTSPREQ_* were just moved into here? + */ + long in_rtspreq = va_arg(param, long); + Curl_RtspReq rtspreq = RTSPREQ_NONE; + switch(in_rtspreq) { + case CURL_RTSPREQ_OPTIONS: + rtspreq = RTSPREQ_OPTIONS; + break; + + case CURL_RTSPREQ_DESCRIBE: + rtspreq = RTSPREQ_DESCRIBE; + break; + + case CURL_RTSPREQ_ANNOUNCE: + rtspreq = RTSPREQ_ANNOUNCE; + break; + + case CURL_RTSPREQ_SETUP: + rtspreq = RTSPREQ_SETUP; + break; + + case CURL_RTSPREQ_PLAY: + rtspreq = RTSPREQ_PLAY; + break; + + case CURL_RTSPREQ_PAUSE: + rtspreq = RTSPREQ_PAUSE; + break; + + case CURL_RTSPREQ_TEARDOWN: + rtspreq = RTSPREQ_TEARDOWN; + break; + + case CURL_RTSPREQ_GET_PARAMETER: + rtspreq = RTSPREQ_GET_PARAMETER; + break; + + case CURL_RTSPREQ_SET_PARAMETER: + rtspreq = RTSPREQ_SET_PARAMETER; + break; + + case CURL_RTSPREQ_RECORD: + rtspreq = RTSPREQ_RECORD; + break; + + case CURL_RTSPREQ_RECEIVE: + rtspreq = RTSPREQ_RECEIVE; + break; + default: + rtspreq = RTSPREQ_NONE; + } + + data->set.rtspreq = rtspreq; + break; + } + + + case CURLOPT_RTSP_SESSION_ID: + /* + * Set the RTSP Session ID manually. Useful if the application is + * resuming a previously established RTSP session + */ + result = Curl_setstropt(&data->set.str[STRING_RTSP_SESSION_ID], + va_arg(param, char *)); + break; + + case CURLOPT_RTSP_STREAM_URI: + /* + * Set the Stream URI for the RTSP request. Unless the request is + * for generic server options, the application will need to set this. + */ + result = Curl_setstropt(&data->set.str[STRING_RTSP_STREAM_URI], + va_arg(param, char *)); + break; + + case CURLOPT_RTSP_TRANSPORT: + /* + * The content of the Transport: header for the RTSP request + */ + result = Curl_setstropt(&data->set.str[STRING_RTSP_TRANSPORT], + va_arg(param, char *)); + break; + + case CURLOPT_RTSP_CLIENT_CSEQ: + /* + * Set the CSEQ number to issue for the next RTSP request. Useful if the + * application is resuming a previously broken connection. The CSEQ + * will increment from this new number henceforth. + */ + data->state.rtsp_next_client_CSeq = va_arg(param, long); + break; + + case CURLOPT_RTSP_SERVER_CSEQ: + /* Same as the above, but for server-initiated requests */ + data->state.rtsp_next_server_CSeq = va_arg(param, long); + break; + + case CURLOPT_INTERLEAVEDATA: + data->set.rtp_out = va_arg(param, void *); + break; + case CURLOPT_INTERLEAVEFUNCTION: + /* Set the user defined RTP write function */ + data->set.fwrite_rtp = va_arg(param, curl_write_callback); + break; +#endif +#ifndef CURL_DISABLE_FTP + case CURLOPT_WILDCARDMATCH: + data->set.wildcard_enabled = (0 != va_arg(param, long)); + break; + case CURLOPT_CHUNK_BGN_FUNCTION: + data->set.chunk_bgn = va_arg(param, curl_chunk_bgn_callback); + break; + case CURLOPT_CHUNK_END_FUNCTION: + data->set.chunk_end = va_arg(param, curl_chunk_end_callback); + break; + case CURLOPT_FNMATCH_FUNCTION: + data->set.fnmatch = va_arg(param, curl_fnmatch_callback); + break; + case CURLOPT_CHUNK_DATA: + data->set.wildcardptr = va_arg(param, void *); + break; + case CURLOPT_FNMATCH_DATA: + data->set.fnmatch_data = va_arg(param, void *); + break; +#endif +#ifdef USE_TLS_SRP + case CURLOPT_TLSAUTH_USERNAME: + result = Curl_setstropt(&data->set.str[STRING_TLSAUTH_USERNAME], + va_arg(param, char *)); + break; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_TLSAUTH_USERNAME: + result = Curl_setstropt(&data->set.str[STRING_TLSAUTH_USERNAME_PROXY], + va_arg(param, char *)); + break; +#endif + case CURLOPT_TLSAUTH_PASSWORD: + result = Curl_setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD], + va_arg(param, char *)); + break; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_TLSAUTH_PASSWORD: + result = Curl_setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD_PROXY], + va_arg(param, char *)); + break; +#endif + case CURLOPT_TLSAUTH_TYPE: + argptr = va_arg(param, char *); + if(argptr && !strcasecompare(argptr, "SRP")) + return CURLE_BAD_FUNCTION_ARGUMENT; + break; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_TLSAUTH_TYPE: + argptr = va_arg(param, char *); + if(argptr && !strcasecompare(argptr, "SRP")) + return CURLE_BAD_FUNCTION_ARGUMENT; + break; +#endif +#endif +#ifdef USE_ARES + case CURLOPT_DNS_SERVERS: + result = Curl_setstropt(&data->set.str[STRING_DNS_SERVERS], + va_arg(param, char *)); + if(result) + return result; + result = Curl_set_dns_servers(data, data->set.str[STRING_DNS_SERVERS]); + break; + case CURLOPT_DNS_INTERFACE: + result = Curl_setstropt(&data->set.str[STRING_DNS_INTERFACE], + va_arg(param, char *)); + if(result) + return result; + result = Curl_set_dns_interface(data, data->set.str[STRING_DNS_INTERFACE]); + break; + case CURLOPT_DNS_LOCAL_IP4: + result = Curl_setstropt(&data->set.str[STRING_DNS_LOCAL_IP4], + va_arg(param, char *)); + if(result) + return result; + result = Curl_set_dns_local_ip4(data, data->set.str[STRING_DNS_LOCAL_IP4]); + break; + case CURLOPT_DNS_LOCAL_IP6: + result = Curl_setstropt(&data->set.str[STRING_DNS_LOCAL_IP6], + va_arg(param, char *)); + if(result) + return result; + result = Curl_set_dns_local_ip6(data, data->set.str[STRING_DNS_LOCAL_IP6]); + break; +#endif + case CURLOPT_TCP_KEEPALIVE: + data->set.tcp_keepalive = (0 != va_arg(param, long)); + break; + case CURLOPT_TCP_KEEPIDLE: + arg = va_arg(param, long); + if(arg < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; + else if(arg > INT_MAX) + arg = INT_MAX; + data->set.tcp_keepidle = (int)arg; + break; + case CURLOPT_TCP_KEEPINTVL: + arg = va_arg(param, long); + if(arg < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; + else if(arg > INT_MAX) + arg = INT_MAX; + data->set.tcp_keepintvl = (int)arg; + break; + case CURLOPT_TCP_FASTOPEN: +#if defined(CONNECT_DATA_IDEMPOTENT) || defined(MSG_FASTOPEN) || \ + defined(TCP_FASTOPEN_CONNECT) + data->set.tcp_fastopen = (0 != va_arg(param, long))?TRUE:FALSE; +#else + result = CURLE_NOT_BUILT_IN; +#endif + break; + case CURLOPT_SSL_ENABLE_NPN: + break; + case CURLOPT_SSL_ENABLE_ALPN: + data->set.ssl_enable_alpn = (0 != va_arg(param, long)); + break; +#ifdef USE_UNIX_SOCKETS + case CURLOPT_UNIX_SOCKET_PATH: + data->set.abstract_unix_socket = FALSE; + result = Curl_setstropt(&data->set.str[STRING_UNIX_SOCKET_PATH], + va_arg(param, char *)); + break; + case CURLOPT_ABSTRACT_UNIX_SOCKET: + data->set.abstract_unix_socket = TRUE; + result = Curl_setstropt(&data->set.str[STRING_UNIX_SOCKET_PATH], + va_arg(param, char *)); + break; +#endif + + case CURLOPT_PATH_AS_IS: + data->set.path_as_is = (0 != va_arg(param, long)); + break; + case CURLOPT_PIPEWAIT: + data->set.pipewait = (0 != va_arg(param, long)); + break; + case CURLOPT_STREAM_WEIGHT: +#if defined(USE_HTTP2) || defined(USE_HTTP3) + arg = va_arg(param, long); + if((arg >= 1) && (arg <= 256)) + data->set.priority.weight = (int)arg; + break; +#else + return CURLE_NOT_BUILT_IN; +#endif + case CURLOPT_STREAM_DEPENDS: + case CURLOPT_STREAM_DEPENDS_E: + { + struct Curl_easy *dep = va_arg(param, struct Curl_easy *); + if(!dep || GOOD_EASY_HANDLE(dep)) { + return Curl_data_priority_add_child(dep, data, + option == CURLOPT_STREAM_DEPENDS_E); + } + break; + } + case CURLOPT_CONNECT_TO: + data->set.connect_to = va_arg(param, struct curl_slist *); + break; + case CURLOPT_SUPPRESS_CONNECT_HEADERS: + data->set.suppress_connect_headers = (0 != va_arg(param, long))?TRUE:FALSE; + break; + case CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS: + uarg = va_arg(param, unsigned long); + if(uarg > UINT_MAX) + uarg = UINT_MAX; + data->set.happy_eyeballs_timeout = (unsigned int)uarg; + break; +#ifndef CURL_DISABLE_SHUFFLE_DNS + case CURLOPT_DNS_SHUFFLE_ADDRESSES: + data->set.dns_shuffle_addresses = (0 != va_arg(param, long)); + break; +#endif + case CURLOPT_DISALLOW_USERNAME_IN_URL: + data->set.disallow_username_in_url = (0 != va_arg(param, long)); + break; +#ifndef CURL_DISABLE_DOH + case CURLOPT_DOH_URL: + result = Curl_setstropt(&data->set.str[STRING_DOH], + va_arg(param, char *)); + data->set.doh = data->set.str[STRING_DOH]?TRUE:FALSE; + break; +#endif + case CURLOPT_UPKEEP_INTERVAL_MS: + arg = va_arg(param, long); + if(arg < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.upkeep_interval_ms = arg; + break; + case CURLOPT_MAXAGE_CONN: + arg = va_arg(param, long); + if(arg < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.maxage_conn = arg; + break; + case CURLOPT_MAXLIFETIME_CONN: + arg = va_arg(param, long); + if(arg < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; + data->set.maxlifetime_conn = arg; + break; + case CURLOPT_TRAILERFUNCTION: +#ifndef CURL_DISABLE_HTTP + data->set.trailer_callback = va_arg(param, curl_trailer_callback); +#endif + break; + case CURLOPT_TRAILERDATA: +#ifndef CURL_DISABLE_HTTP + data->set.trailer_data = va_arg(param, void *); +#endif + break; +#ifndef CURL_DISABLE_HSTS + case CURLOPT_HSTSREADFUNCTION: + data->set.hsts_read = va_arg(param, curl_hstsread_callback); + break; + case CURLOPT_HSTSREADDATA: + data->set.hsts_read_userp = va_arg(param, void *); + break; + case CURLOPT_HSTSWRITEFUNCTION: + data->set.hsts_write = va_arg(param, curl_hstswrite_callback); + break; + case CURLOPT_HSTSWRITEDATA: + data->set.hsts_write_userp = va_arg(param, void *); + break; + case CURLOPT_HSTS: { + struct curl_slist *h; + if(!data->hsts) { + data->hsts = Curl_hsts_init(); + if(!data->hsts) + return CURLE_OUT_OF_MEMORY; + } + argptr = va_arg(param, char *); + if(argptr) { + result = Curl_setstropt(&data->set.str[STRING_HSTS], argptr); + if(result) + return result; + /* this needs to build a list of file names to read from, so that it can + read them later, as we might get a shared HSTS handle to load them + into */ + h = curl_slist_append(data->state.hstslist, argptr); + if(!h) { + curl_slist_free_all(data->state.hstslist); + data->state.hstslist = NULL; + return CURLE_OUT_OF_MEMORY; + } + data->state.hstslist = h; /* store the list for later use */ + } + else { + /* clear the list of HSTS files */ + curl_slist_free_all(data->state.hstslist); + data->state.hstslist = NULL; + if(!data->share || !data->share->hsts) + /* throw away the HSTS cache unless shared */ + Curl_hsts_cleanup(&data->hsts); + } + break; + } + case CURLOPT_HSTS_CTRL: + arg = va_arg(param, long); + if(arg & CURLHSTS_ENABLE) { + if(!data->hsts) { + data->hsts = Curl_hsts_init(); + if(!data->hsts) + return CURLE_OUT_OF_MEMORY; + } + } + else + Curl_hsts_cleanup(&data->hsts); + break; +#endif +#ifndef CURL_DISABLE_ALTSVC + case CURLOPT_ALTSVC: + if(!data->asi) { + data->asi = Curl_altsvc_init(); + if(!data->asi) + return CURLE_OUT_OF_MEMORY; + } + argptr = va_arg(param, char *); + result = Curl_setstropt(&data->set.str[STRING_ALTSVC], argptr); + if(result) + return result; + if(argptr) + (void)Curl_altsvc_load(data->asi, argptr); + break; + case CURLOPT_ALTSVC_CTRL: + if(!data->asi) { + data->asi = Curl_altsvc_init(); + if(!data->asi) + return CURLE_OUT_OF_MEMORY; + } + arg = va_arg(param, long); + if(!arg) { + DEBUGF(infof(data, "bad CURLOPT_ALTSVC_CTRL input")); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + result = Curl_altsvc_ctrl(data->asi, arg); + if(result) + return result; + break; +#endif + case CURLOPT_PREREQFUNCTION: + data->set.fprereq = va_arg(param, curl_prereq_callback); + break; + case CURLOPT_PREREQDATA: + data->set.prereq_userp = va_arg(param, void *); + break; +#ifdef USE_WEBSOCKETS + case CURLOPT_WS_OPTIONS: { + bool raw; + arg = va_arg(param, long); + raw = (arg & CURLWS_RAW_MODE); + data->set.ws_raw_mode = raw; + break; + } +#endif +#ifdef USE_ECH + case CURLOPT_ECH: { + size_t plen = 0; + + argptr = va_arg(param, char *); + if(!argptr) { + data->set.tls_ech = CURLECH_DISABLE; + result = CURLE_BAD_FUNCTION_ARGUMENT; + return result; + } + plen = strlen(argptr); + if(plen > CURL_MAX_INPUT_LENGTH) { + data->set.tls_ech = CURLECH_DISABLE; + result = CURLE_BAD_FUNCTION_ARGUMENT; + return result; + } + /* set tls_ech flag value, preserving CLA_CFG bit */ + if(plen == 5 && !strcmp(argptr, "false")) + data->set.tls_ech = CURLECH_DISABLE + | (data->set.tls_ech & CURLECH_CLA_CFG); + else if(plen == 6 && !strcmp(argptr, "grease")) + data->set.tls_ech = CURLECH_GREASE + | (data->set.tls_ech & CURLECH_CLA_CFG); + else if(plen == 4 && !strcmp(argptr, "true")) + data->set.tls_ech = CURLECH_ENABLE + | (data->set.tls_ech & CURLECH_CLA_CFG); + else if(plen == 4 && !strcmp(argptr, "hard")) + data->set.tls_ech = CURLECH_HARD + | (data->set.tls_ech & CURLECH_CLA_CFG); + else if(plen > 5 && !strncmp(argptr, "ecl:", 4)) { + result = Curl_setstropt(&data->set.str[STRING_ECH_CONFIG], argptr + 4); + if(result) + return result; + data->set.tls_ech |= CURLECH_CLA_CFG; + } + else if(plen > 4 && !strncmp(argptr, "pn:", 3)) { + result = Curl_setstropt(&data->set.str[STRING_ECH_PUBLIC], argptr + 3); + if(result) + return result; + } + break; + } +#endif + case CURLOPT_QUICK_EXIT: + data->set.quick_exit = (0 != va_arg(param, long)) ? 1L:0L; + break; + default: + /* unknown tag and its companion, just ignore: */ + result = CURLE_UNKNOWN_OPTION; + break; + } + + return result; +} + +/* + * curl_easy_setopt() is the external interface for setting options on an + * easy handle. + * + * NOTE: This is one of few API functions that are allowed to be called from + * within a callback. + */ + +#undef curl_easy_setopt +CURLcode curl_easy_setopt(struct Curl_easy *data, CURLoption tag, ...) +{ + va_list arg; + CURLcode result; + + if(!data) + return CURLE_BAD_FUNCTION_ARGUMENT; + + va_start(arg, tag); + + result = Curl_vsetopt(data, tag, arg); + + va_end(arg); +#ifdef DEBUGBUILD + if(result == CURLE_BAD_FUNCTION_ARGUMENT) + infof(data, "setopt arg 0x%x returned CURLE_BAD_FUNCTION_ARGUMENT", tag); +#endif + return result; +} diff --git a/third_party/curl/lib/setopt.h b/third_party/curl/lib/setopt.h new file mode 100644 index 0000000..b023746 --- /dev/null +++ b/third_party/curl/lib/setopt.h @@ -0,0 +1,33 @@ +#ifndef HEADER_CURL_SETOPT_H +#define HEADER_CURL_SETOPT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +CURLcode Curl_setstropt(char **charp, const char *s) WARN_UNUSED_RESULT; +CURLcode Curl_setblobopt(struct curl_blob **blobp, + const struct curl_blob *blob) WARN_UNUSED_RESULT; +CURLcode Curl_vsetopt(struct Curl_easy *data, CURLoption option, va_list arg) + WARN_UNUSED_RESULT; + +#endif /* HEADER_CURL_SETOPT_H */ diff --git a/third_party/curl/lib/setup-os400.h b/third_party/curl/lib/setup-os400.h new file mode 100644 index 0000000..53e9177 --- /dev/null +++ b/third_party/curl/lib/setup-os400.h @@ -0,0 +1,144 @@ +#ifndef HEADER_CURL_SETUP_OS400_H +#define HEADER_CURL_SETUP_OS400_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + + +/* OS/400 netdb.h does not define NI_MAXHOST. */ +#define NI_MAXHOST 1025 + +/* OS/400 netdb.h does not define NI_MAXSERV. */ +#define NI_MAXSERV 32 + +/* No OS/400 header file defines u_int32_t. */ +typedef unsigned long u_int32_t; + +/* OS/400 has no idea of a tty! */ +#define isatty(fd) 0 + + +/* System API wrapper prototypes & definitions to support ASCII parameters. */ + +#include +#include +#include +#include +#include + +extern int Curl_getaddrinfo_a(const char *nodename, + const char *servname, + const struct addrinfo *hints, + struct addrinfo **res); +#define getaddrinfo Curl_getaddrinfo_a + +/* Note socklen_t must be used as this is declared before curl_socklen_t */ +extern int Curl_getnameinfo_a(const struct sockaddr *sa, + socklen_t salen, + char *nodename, socklen_t nodenamelen, + char *servname, socklen_t servnamelen, + int flags); +#define getnameinfo Curl_getnameinfo_a + +/* GSSAPI wrappers. */ + +extern OM_uint32 Curl_gss_import_name_a(OM_uint32 * minor_status, + gss_buffer_t in_name, + gss_OID in_name_type, + gss_name_t * out_name); +#define gss_import_name Curl_gss_import_name_a + + +extern OM_uint32 Curl_gss_display_status_a(OM_uint32 * minor_status, + OM_uint32 status_value, + int status_type, gss_OID mech_type, + gss_msg_ctx_t * message_context, + gss_buffer_t status_string); +#define gss_display_status Curl_gss_display_status_a + + +extern OM_uint32 Curl_gss_init_sec_context_a(OM_uint32 * minor_status, + gss_cred_id_t cred_handle, + gss_ctx_id_t * context_handle, + gss_name_t target_name, + gss_OID mech_type, + gss_flags_t req_flags, + OM_uint32 time_req, + gss_channel_bindings_t + input_chan_bindings, + gss_buffer_t input_token, + gss_OID * actual_mech_type, + gss_buffer_t output_token, + gss_flags_t * ret_flags, + OM_uint32 * time_rec); +#define gss_init_sec_context Curl_gss_init_sec_context_a + + +extern OM_uint32 Curl_gss_delete_sec_context_a(OM_uint32 * minor_status, + gss_ctx_id_t * context_handle, + gss_buffer_t output_token); +#define gss_delete_sec_context Curl_gss_delete_sec_context_a + + +/* LDAP wrappers. */ + +#define BerValue struct berval + +#define ldap_url_parse ldap_url_parse_utf8 +#define ldap_init Curl_ldap_init_a +#define ldap_simple_bind_s Curl_ldap_simple_bind_s_a +#define ldap_search_s Curl_ldap_search_s_a +#define ldap_get_values_len Curl_ldap_get_values_len_a +#define ldap_err2string Curl_ldap_err2string_a +#define ldap_get_dn Curl_ldap_get_dn_a +#define ldap_first_attribute Curl_ldap_first_attribute_a +#define ldap_next_attribute Curl_ldap_next_attribute_a + +/* Some socket functions must be wrapped to process textual addresses + like AF_UNIX. */ + +extern int Curl_os400_connect(int sd, struct sockaddr *destaddr, int addrlen); +extern int Curl_os400_bind(int sd, struct sockaddr *localaddr, int addrlen); +extern int Curl_os400_sendto(int sd, char *buffer, int buflen, int flags, + const struct sockaddr *dstaddr, int addrlen); +extern int Curl_os400_recvfrom(int sd, char *buffer, int buflen, int flags, + struct sockaddr *fromaddr, int *addrlen); +extern int Curl_os400_getpeername(int sd, struct sockaddr *addr, int *addrlen); +extern int Curl_os400_getsockname(int sd, struct sockaddr *addr, int *addrlen); + +#define connect Curl_os400_connect +#define bind Curl_os400_bind +#define sendto Curl_os400_sendto +#define recvfrom Curl_os400_recvfrom +#define getpeername Curl_os400_getpeername +#define getsockname Curl_os400_getsockname + +#ifdef HAVE_LIBZ +#define zlibVersion Curl_os400_zlibVersion +#define inflateInit_ Curl_os400_inflateInit_ +#define inflateInit2_ Curl_os400_inflateInit2_ +#define inflate Curl_os400_inflate +#define inflateEnd Curl_os400_inflateEnd +#endif + +#endif /* HEADER_CURL_SETUP_OS400_H */ diff --git a/third_party/curl/lib/setup-vms.h b/third_party/curl/lib/setup-vms.h new file mode 100644 index 0000000..ea3936c --- /dev/null +++ b/third_party/curl/lib/setup-vms.h @@ -0,0 +1,444 @@ +#ifndef HEADER_CURL_SETUP_VMS_H +#define HEADER_CURL_SETUP_VMS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* */ +/* JEM, 12/30/12, VMS now generates config.h, so only define wrappers for */ +/* getenv(), getpwuid() and provide is_vms_shell() */ +/* Also need upper case symbols for system services, and */ +/* OpenSSL, and some Kerberos image */ + +#ifdef __DECC +#pragma message save +#pragma message disable dollarid +#endif + +/* Hide the stuff we are overriding */ +#define getenv decc_getenv +#ifdef __DECC +# if __INITIAL_POINTER_SIZE != 64 +# define getpwuid decc_getpwuid +# endif +#endif +#include +char *decc$getenv(const char *__name); +#include + +#include +#include + +#undef getenv +#undef getpwuid +#define getenv vms_getenv +#define getpwuid vms_getpwuid + +/* VAX needs these in upper case when compiling exact case */ +#define sys$assign SYS$ASSIGN +#define sys$dassgn SYS$DASSGN +#define sys$qiow SYS$QIOW + +#ifdef __DECC +# if __INITIAL_POINTER_SIZE +# pragma __pointer_size __save +# endif +#endif + +#if __USE_LONG_GID_T +# define decc_getpwuid DECC$__LONG_GID_GETPWUID +#else +# if __INITIAL_POINTER_SIZE +# define decc_getpwuid decc$__32_getpwuid +# else +# define decc_getpwuid decc$getpwuid +# endif +#endif + + struct passwd *decc_getpwuid(uid_t uid); + +#ifdef __DECC +# if __INITIAL_POINTER_SIZE == 32 +/* Translate the path, but only if the path is a VMS file specification */ +/* The translation is usually only needed for older versions of VMS */ +static char *vms_translate_path(const char *path) +{ + char *unix_path; + char *test_str; + + /* See if the result is in VMS format, if not, we are done */ + /* Assume that this is a PATH, not just some data */ + test_str = strpbrk(path, ":[<^"); + if(!test_str) { + return (char *)path; + } + + unix_path = decc$translate_vms(path); + + if((int)unix_path <= 0) { + /* We can not translate it, so return the original string */ + return (char *)path; + } +} +# else + /* VMS translate path is actually not needed on the current 64 bit */ + /* VMS platforms, so instead of figuring out the pointer settings */ + /* Change it to a noop */ +# define vms_translate_path(__path) __path +# endif +#endif + +#ifdef __DECC +# if __INITIAL_POINTER_SIZE +# pragma __pointer_size __restore +# endif +#endif + +static char *vms_getenv(const char *envvar) +{ + char *result; + char *vms_path; + + /* first use the DECC getenv() function */ + result = decc$getenv(envvar); + if(!result) { + return result; + } + + vms_path = result; + result = vms_translate_path(vms_path); + + /* note that if you backport this to use VAX C RTL, that the VAX C RTL */ + /* may do a malloc(2048) for each call to getenv(), so you will need */ + /* to add a free(vms_path) */ + /* Do not do a free() for DEC C RTL builds, which should be used for */ + /* VMS 5.5-2 and later, even if using GCC */ + + return result; +} + + +static struct passwd vms_passwd_cache; + +static struct passwd *vms_getpwuid(uid_t uid) +{ + struct passwd *my_passwd; + +/* Hack needed to support 64 bit builds, decc_getpwnam is 32 bit only */ +#ifdef __DECC +# if __INITIAL_POINTER_SIZE + __char_ptr32 unix_path; +# else + char *unix_path; +# endif +#else + char *unix_path; +#endif + + my_passwd = decc_getpwuid(uid); + if(!my_passwd) { + return my_passwd; + } + + unix_path = vms_translate_path(my_passwd->pw_dir); + + if((long)unix_path <= 0) { + /* We can not translate it, so return the original string */ + return my_passwd; + } + + /* If no changes needed just return it */ + if(unix_path == my_passwd->pw_dir) { + return my_passwd; + } + + /* Need to copy the structure returned */ + /* Since curl is only using pw_dir, no need to fix up */ + /* the pw_shell when running under Bash */ + vms_passwd_cache.pw_name = my_passwd->pw_name; + vms_passwd_cache.pw_uid = my_passwd->pw_uid; + vms_passwd_cache.pw_gid = my_passwd->pw_uid; + vms_passwd_cache.pw_dir = unix_path; + vms_passwd_cache.pw_shell = my_passwd->pw_shell; + + return &vms_passwd_cache; +} + +#ifdef __DECC +#pragma message restore +#endif + +/* Bug - VMS OpenSSL and Kerberos universal symbols are in uppercase only */ +/* VMS libraries should have universal symbols in exact and uppercase */ + +#define ASN1_INTEGER_get ASN1_INTEGER_GET +#define ASN1_STRING_data ASN1_STRING_DATA +#define ASN1_STRING_length ASN1_STRING_LENGTH +#define ASN1_STRING_print ASN1_STRING_PRINT +#define ASN1_STRING_to_UTF8 ASN1_STRING_TO_UTF8 +#define ASN1_STRING_type ASN1_STRING_TYPE +#define BIO_ctrl BIO_CTRL +#define BIO_free BIO_FREE +#define BIO_new BIO_NEW +#define BIO_s_mem BIO_S_MEM +#define BN_bn2bin BN_BN2BIN +#define BN_num_bits BN_NUM_BITS +#define CRYPTO_cleanup_all_ex_data CRYPTO_CLEANUP_ALL_EX_DATA +#define CRYPTO_free CRYPTO_FREE +#define CRYPTO_malloc CRYPTO_MALLOC +#define CONF_modules_load_file CONF_MODULES_LOAD_FILE +#ifdef __VAX +# ifdef VMS_OLD_SSL + /* Ancient OpenSSL on VAX/VMS missing this constant */ +# define CONF_MFLAGS_IGNORE_MISSING_FILE 0x10 +# undef CONF_modules_load_file + static int CONF_modules_load_file(const char *filename, + const char *appname, + unsigned long flags) { + return 1; + } +# endif +#endif +#define DES_ecb_encrypt DES_ECB_ENCRYPT +#define DES_set_key DES_SET_KEY +#define DES_set_odd_parity DES_SET_ODD_PARITY +#define ENGINE_ctrl ENGINE_CTRL +#define ENGINE_ctrl_cmd ENGINE_CTRL_CMD +#define ENGINE_finish ENGINE_FINISH +#define ENGINE_free ENGINE_FREE +#define ENGINE_get_first ENGINE_GET_FIRST +#define ENGINE_get_id ENGINE_GET_ID +#define ENGINE_get_next ENGINE_GET_NEXT +#define ENGINE_init ENGINE_INIT +#define ENGINE_load_builtin_engines ENGINE_LOAD_BUILTIN_ENGINES +#define ENGINE_load_private_key ENGINE_LOAD_PRIVATE_KEY +#define ENGINE_set_default ENGINE_SET_DEFAULT +#define ERR_clear_error ERR_CLEAR_ERROR +#define ERR_error_string ERR_ERROR_STRING +#define ERR_error_string_n ERR_ERROR_STRING_N +#define ERR_free_strings ERR_FREE_STRINGS +#define ERR_get_error ERR_GET_ERROR +#define ERR_peek_error ERR_PEEK_ERROR +#define ERR_remove_state ERR_REMOVE_STATE +#define EVP_PKEY_copy_parameters EVP_PKEY_COPY_PARAMETERS +#define EVP_PKEY_free EVP_PKEY_FREE +#define EVP_cleanup EVP_CLEANUP +#define GENERAL_NAMES_free GENERAL_NAMES_FREE +#define i2d_X509_PUBKEY I2D_X509_PUBKEY +#define MD4_Final MD4_FINAL +#define MD4_Init MD4_INIT +#define MD4_Update MD4_UPDATE +#define MD5_Final MD5_FINAL +#define MD5_Init MD5_INIT +#define MD5_Update MD5_UPDATE +#define OPENSSL_add_all_algo_noconf OPENSSL_ADD_ALL_ALGO_NOCONF +#ifndef __VAX +#define OPENSSL_load_builtin_modules OPENSSL_LOAD_BUILTIN_MODULES +#endif +#define PEM_read_X509 PEM_READ_X509 +#define PEM_write_bio_X509 PEM_WRITE_BIO_X509 +#define PKCS12_PBE_add PKCS12_PBE_ADD +#define PKCS12_free PKCS12_FREE +#define PKCS12_parse PKCS12_PARSE +#define RAND_add RAND_ADD +#define RAND_bytes RAND_BYTES +#define RAND_file_name RAND_FILE_NAME +#define RAND_load_file RAND_LOAD_FILE +#define RAND_status RAND_STATUS +#define SSL_CIPHER_get_name SSL_CIPHER_GET_NAME +#define SSL_CTX_add_client_CA SSL_CTX_ADD_CLIENT_CA +#define SSL_CTX_callback_ctrl SSL_CTX_CALLBACK_CTRL +#define SSL_CTX_check_private_key SSL_CTX_CHECK_PRIVATE_KEY +#define SSL_CTX_ctrl SSL_CTX_CTRL +#define SSL_CTX_free SSL_CTX_FREE +#define SSL_CTX_get_cert_store SSL_CTX_GET_CERT_STORE +#define SSL_CTX_load_verify_locations SSL_CTX_LOAD_VERIFY_LOCATIONS +#define SSL_CTX_new SSL_CTX_NEW +#define SSL_CTX_set_cipher_list SSL_CTX_SET_CIPHER_LIST +#define SSL_CTX_set_def_passwd_cb_ud SSL_CTX_SET_DEF_PASSWD_CB_UD +#define SSL_CTX_set_default_passwd_cb SSL_CTX_SET_DEFAULT_PASSWD_CB +#define SSL_CTX_set_msg_callback SSL_CTX_SET_MSG_CALLBACK +#define SSL_CTX_set_verify SSL_CTX_SET_VERIFY +#define SSL_CTX_use_PrivateKey SSL_CTX_USE_PRIVATEKEY +#define SSL_CTX_use_PrivateKey_file SSL_CTX_USE_PRIVATEKEY_FILE +#define SSL_CTX_use_cert_chain_file SSL_CTX_USE_CERT_CHAIN_FILE +#define SSL_CTX_use_certificate SSL_CTX_USE_CERTIFICATE +#define SSL_CTX_use_certificate_file SSL_CTX_USE_CERTIFICATE_FILE +#define SSL_SESSION_free SSL_SESSION_FREE +#define SSL_connect SSL_CONNECT +#define SSL_free SSL_FREE +#define SSL_get1_session SSL_GET1_SESSION +#define SSL_get_certificate SSL_GET_CERTIFICATE +#define SSL_get_current_cipher SSL_GET_CURRENT_CIPHER +#define SSL_get_error SSL_GET_ERROR +#define SSL_get_peer_cert_chain SSL_GET_PEER_CERT_CHAIN +#define SSL_get_peer_certificate SSL_GET_PEER_CERTIFICATE +#define SSL_get_privatekey SSL_GET_PRIVATEKEY +#define SSL_get_session SSL_GET_SESSION +#define SSL_get_shutdown SSL_GET_SHUTDOWN +#define SSL_get_verify_result SSL_GET_VERIFY_RESULT +#define SSL_library_init SSL_LIBRARY_INIT +#define SSL_load_error_strings SSL_LOAD_ERROR_STRINGS +#define SSL_new SSL_NEW +#define SSL_peek SSL_PEEK +#define SSL_pending SSL_PENDING +#define SSL_read SSL_READ +#define SSL_set_connect_state SSL_SET_CONNECT_STATE +#define SSL_set_fd SSL_SET_FD +#define SSL_set_session SSL_SET_SESSION +#define SSL_shutdown SSL_SHUTDOWN +#define SSL_version SSL_VERSION +#define SSL_write SSL_WRITE +#define SSLeay SSLEAY +#define SSLv23_client_method SSLV23_CLIENT_METHOD +#define SSLv3_client_method SSLV3_CLIENT_METHOD +#define TLSv1_client_method TLSV1_CLIENT_METHOD +#define UI_create_method UI_CREATE_METHOD +#define UI_destroy_method UI_DESTROY_METHOD +#define UI_get0_user_data UI_GET0_USER_DATA +#define UI_get_input_flags UI_GET_INPUT_FLAGS +#define UI_get_string_type UI_GET_STRING_TYPE +#define UI_create_method UI_CREATE_METHOD +#define UI_destroy_method UI_DESTROY_METHOD +#define UI_method_get_closer UI_METHOD_GET_CLOSER +#define UI_method_get_opener UI_METHOD_GET_OPENER +#define UI_method_get_reader UI_METHOD_GET_READER +#define UI_method_get_writer UI_METHOD_GET_WRITER +#define UI_method_set_closer UI_METHOD_SET_CLOSER +#define UI_method_set_opener UI_METHOD_SET_OPENER +#define UI_method_set_reader UI_METHOD_SET_READER +#define UI_method_set_writer UI_METHOD_SET_WRITER +#define UI_OpenSSL UI_OPENSSL +#define UI_set_result UI_SET_RESULT +#define X509V3_EXT_print X509V3_EXT_PRINT +#define X509_EXTENSION_get_critical X509_EXTENSION_GET_CRITICAL +#define X509_EXTENSION_get_data X509_EXTENSION_GET_DATA +#define X509_EXTENSION_get_object X509_EXTENSION_GET_OBJECT +#define X509_LOOKUP_file X509_LOOKUP_FILE +#define X509_NAME_ENTRY_get_data X509_NAME_ENTRY_GET_DATA +#define X509_NAME_get_entry X509_NAME_GET_ENTRY +#define X509_NAME_get_index_by_NID X509_NAME_GET_INDEX_BY_NID +#define X509_NAME_print_ex X509_NAME_PRINT_EX +#define X509_STORE_CTX_get_current_cert X509_STORE_CTX_GET_CURRENT_CERT +#define X509_STORE_add_lookup X509_STORE_ADD_LOOKUP +#define X509_STORE_set_flags X509_STORE_SET_FLAGS +#define X509_check_issued X509_CHECK_ISSUED +#define X509_free X509_FREE +#define X509_get_ext_d2i X509_GET_EXT_D2I +#define X509_get_issuer_name X509_GET_ISSUER_NAME +#define X509_get_pubkey X509_GET_PUBKEY +#define X509_get_serialNumber X509_GET_SERIALNUMBER +#define X509_get_subject_name X509_GET_SUBJECT_NAME +#define X509_load_crl_file X509_LOAD_CRL_FILE +#define X509_verify_cert_error_string X509_VERIFY_CERT_ERROR_STRING +#define d2i_PKCS12_fp D2I_PKCS12_FP +#define i2t_ASN1_OBJECT I2T_ASN1_OBJECT +#define sk_num SK_NUM +#define sk_pop SK_POP +#define sk_pop_free SK_POP_FREE +#define sk_value SK_VALUE +#ifdef __VAX +#define OPENSSL_NO_SHA256 +#endif +#define SHA256_Final SHA256_FINAL +#define SHA256_Init SHA256_INIT +#define SHA256_Update SHA256_UPDATE + +#define USE_UPPERCASE_GSSAPI 1 +#define gss_seal GSS_SEAL +#define gss_unseal GSS_UNSEAL + +#define USE_UPPERCASE_KRBAPI 1 + +/* AI_NUMERICHOST needed for IP V6 support in Curl */ +#ifdef HAVE_NETDB_H +#include +#ifndef AI_NUMERICHOST +#ifdef USE_IPV6 +#undef USE_IPV6 +#endif +#endif +#endif + +/* VAX symbols are always in uppercase */ +#ifdef __VAX +#define inflate INFLATE +#define inflateEnd INFLATEEND +#define inflateInit2_ INFLATEINIT2_ +#define inflateInit_ INFLATEINIT_ +#define zlibVersion ZLIBVERSION +#endif + +/* Older VAX OpenSSL port defines these as Macros */ +/* Need to include the headers first and then redefine */ +/* that way a newer port will also work if some one has one */ +#ifdef __VAX + +# if (OPENSSL_VERSION_NUMBER < 0x00907001L) +# define des_set_odd_parity DES_SET_ODD_PARITY +# define des_set_key DES_SET_KEY +# define des_ecb_encrypt DES_ECB_ENCRYPT + +# endif +# include +# ifndef OpenSSL_add_all_algorithms +# define OpenSSL_add_all_algorithms OPENSSL_ADD_ALL_ALGORITHMS + void OPENSSL_ADD_ALL_ALGORITHMS(void); +# endif + + /* Curl defines these to lower case and VAX needs them in upper case */ + /* So we need static routines */ +# if (OPENSSL_VERSION_NUMBER < 0x00907001L) + +# undef des_set_odd_parity +# undef DES_set_odd_parity +# undef des_set_key +# undef DES_set_key +# undef des_ecb_encrypt +# undef DES_ecb_encrypt + + static void des_set_odd_parity(des_cblock *key) { + DES_SET_ODD_PARITY(key); + } + + static int des_set_key(const_des_cblock *key, + des_key_schedule schedule) { + return DES_SET_KEY(key, schedule); + } + + static void des_ecb_encrypt(const_des_cblock *input, + des_cblock *output, + des_key_schedule ks, int enc) { + DES_ECB_ENCRYPT(input, output, ks, enc); + } +#endif +/* Need this to stop a macro redefinition error */ +#if OPENSSL_VERSION_NUMBER < 0x00907000L +# ifdef X509_STORE_set_flags +# undef X509_STORE_set_flags +# define X509_STORE_set_flags(x,y) Curl_nop_stmt +# endif +#endif +#endif + +#endif /* HEADER_CURL_SETUP_VMS_H */ diff --git a/third_party/curl/lib/setup-win32.h b/third_party/curl/lib/setup-win32.h new file mode 100644 index 0000000..d7e2e6b --- /dev/null +++ b/third_party/curl/lib/setup-win32.h @@ -0,0 +1,138 @@ +#ifndef HEADER_CURL_SETUP_WIN32_H +#define HEADER_CURL_SETUP_WIN32_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#undef USE_WINSOCK +/* ---------------------------------------------------------------- */ +/* Watt-32 TCP/IP SPECIFIC */ +/* ---------------------------------------------------------------- */ +#ifdef USE_WATT32 +# include +# undef byte +# undef word +# define HAVE_SYS_IOCTL_H +# define HAVE_SYS_SOCKET_H +# define HAVE_NETINET_IN_H +# define HAVE_NETDB_H +# define HAVE_ARPA_INET_H +# define SOCKET int +/* ---------------------------------------------------------------- */ +/* BSD-style lwIP TCP/IP stack SPECIFIC */ +/* ---------------------------------------------------------------- */ +#elif defined(USE_LWIPSOCK) + /* Define to use BSD-style lwIP TCP/IP stack. */ + /* #define USE_LWIPSOCK 1 */ +# undef HAVE_GETHOSTNAME +# undef LWIP_POSIX_SOCKETS_IO_NAMES +# undef RECV_TYPE_ARG1 +# undef RECV_TYPE_ARG3 +# undef SEND_TYPE_ARG1 +# undef SEND_TYPE_ARG3 +# define HAVE_GETHOSTBYNAME_R +# define HAVE_GETHOSTBYNAME_R_6 +# define LWIP_POSIX_SOCKETS_IO_NAMES 0 +# define RECV_TYPE_ARG1 int +# define RECV_TYPE_ARG3 size_t +# define SEND_TYPE_ARG1 int +# define SEND_TYPE_ARG3 size_t +#elif defined(_WIN32) +# define USE_WINSOCK 2 +#endif + +/* + * Include header files for windows builds before redefining anything. + * Use this preprocessor block only to include or exclude windows.h, + * winsock2.h or ws2tcpip.h. Any other windows thing belongs + * to any other further and independent block. Under Cygwin things work + * just as under linux (e.g. ) and the winsock headers should + * never be included when __CYGWIN__ is defined. + */ + +#ifdef _WIN32 +# if defined(UNICODE) && !defined(_UNICODE) +# error "UNICODE is defined but _UNICODE is not defined" +# endif +# if defined(_UNICODE) && !defined(UNICODE) +# error "_UNICODE is defined but UNICODE is not defined" +# endif +/* + * Don't include unneeded stuff in Windows headers to avoid compiler + * warnings and macro clashes. + * Make sure to define this macro before including any Windows headers. + */ +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# ifndef NOGDI +# define NOGDI +# endif +# include +# include +# include +# include +# include +# ifdef UNICODE + typedef wchar_t *(*curl_wcsdup_callback)(const wchar_t *str); +# endif +#endif + +/* + * Define _WIN32_WINNT_[OS] symbols because not all Windows build systems have + * those symbols to compare against, and even those that do may be missing + * newer symbols. + */ + +#ifndef _WIN32_WINNT_NT4 +#define _WIN32_WINNT_NT4 0x0400 /* Windows NT 4.0 */ +#endif +#ifndef _WIN32_WINNT_WIN2K +#define _WIN32_WINNT_WIN2K 0x0500 /* Windows 2000 */ +#endif +#ifndef _WIN32_WINNT_WINXP +#define _WIN32_WINNT_WINXP 0x0501 /* Windows XP */ +#endif +#ifndef _WIN32_WINNT_WS03 +#define _WIN32_WINNT_WS03 0x0502 /* Windows Server 2003 */ +#endif +#ifndef _WIN32_WINNT_VISTA +#define _WIN32_WINNT_VISTA 0x0600 /* Windows Vista */ +#endif +#ifndef _WIN32_WINNT_WS08 +#define _WIN32_WINNT_WS08 0x0600 /* Windows Server 2008 */ +#endif +#ifndef _WIN32_WINNT_WIN7 +#define _WIN32_WINNT_WIN7 0x0601 /* Windows 7 */ +#endif +#ifndef _WIN32_WINNT_WIN8 +#define _WIN32_WINNT_WIN8 0x0602 /* Windows 8 */ +#endif +#ifndef _WIN32_WINNT_WINBLUE +#define _WIN32_WINNT_WINBLUE 0x0603 /* Windows 8.1 */ +#endif +#ifndef _WIN32_WINNT_WIN10 +#define _WIN32_WINNT_WIN10 0x0A00 /* Windows 10 */ +#endif + +#endif /* HEADER_CURL_SETUP_WIN32_H */ diff --git a/third_party/curl/lib/sha256.c b/third_party/curl/lib/sha256.c new file mode 100644 index 0000000..4a02045 --- /dev/null +++ b/third_party/curl/lib/sha256.c @@ -0,0 +1,545 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Florin Petriuc, + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_AWS) || !defined(CURL_DISABLE_DIGEST_AUTH) \ + || defined(USE_LIBSSH2) + +#include "warnless.h" +#include "curl_sha256.h" +#include "curl_hmac.h" + +#ifdef USE_WOLFSSL +#include +#ifndef NO_SHA256 +#define USE_OPENSSL_SHA256 +#endif +#endif + +#if defined(USE_OPENSSL) + +#include + +#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) +#define USE_OPENSSL_SHA256 +#endif + +#endif /* USE_OPENSSL */ + +#ifdef USE_MBEDTLS +#include + +#if(MBEDTLS_VERSION_NUMBER >= 0x02070000) && \ + (MBEDTLS_VERSION_NUMBER < 0x03000000) + #define HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS +#endif +#endif /* USE_MBEDTLS */ + +#if defined(USE_OPENSSL_SHA256) + +/* When OpenSSL or wolfSSL is available we use their SHA256-functions. */ +#if defined(USE_OPENSSL) +#include +#elif defined(USE_WOLFSSL) +#include +#endif + +#elif defined(USE_GNUTLS) +#include +#elif defined(USE_MBEDTLS) +#include +#elif (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \ + (__MAC_OS_X_VERSION_MAX_ALLOWED >= 1040)) || \ + (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \ + (__IPHONE_OS_VERSION_MAX_ALLOWED >= 20000)) +#include +#define AN_APPLE_OS +#elif defined(USE_WIN32_CRYPTO) +#include +#endif + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* Please keep the SSL backend-specific #if branches in this order: + * + * 1. USE_OPENSSL + * 2. USE_GNUTLS + * 3. USE_MBEDTLS + * 4. USE_COMMON_CRYPTO + * 5. USE_WIN32_CRYPTO + * + * This ensures that the same SSL branch gets activated throughout this source + * file even if multiple backends are enabled at the same time. + */ + +#if defined(USE_OPENSSL_SHA256) + +struct sha256_ctx { + EVP_MD_CTX *openssl_ctx; +}; +typedef struct sha256_ctx my_sha256_ctx; + +static CURLcode my_sha256_init(my_sha256_ctx *ctx) +{ + ctx->openssl_ctx = EVP_MD_CTX_create(); + if(!ctx->openssl_ctx) + return CURLE_OUT_OF_MEMORY; + + if(!EVP_DigestInit_ex(ctx->openssl_ctx, EVP_sha256(), NULL)) { + EVP_MD_CTX_destroy(ctx->openssl_ctx); + return CURLE_FAILED_INIT; + } + return CURLE_OK; +} + +static void my_sha256_update(my_sha256_ctx *ctx, + const unsigned char *data, + unsigned int length) +{ + EVP_DigestUpdate(ctx->openssl_ctx, data, length); +} + +static void my_sha256_final(unsigned char *digest, my_sha256_ctx *ctx) +{ + EVP_DigestFinal_ex(ctx->openssl_ctx, digest, NULL); + EVP_MD_CTX_destroy(ctx->openssl_ctx); +} + +#elif defined(USE_GNUTLS) + +typedef struct sha256_ctx my_sha256_ctx; + +static CURLcode my_sha256_init(my_sha256_ctx *ctx) +{ + sha256_init(ctx); + return CURLE_OK; +} + +static void my_sha256_update(my_sha256_ctx *ctx, + const unsigned char *data, + unsigned int length) +{ + sha256_update(ctx, length, data); +} + +static void my_sha256_final(unsigned char *digest, my_sha256_ctx *ctx) +{ + sha256_digest(ctx, SHA256_DIGEST_SIZE, digest); +} + +#elif defined(USE_MBEDTLS) + +typedef mbedtls_sha256_context my_sha256_ctx; + +static CURLcode my_sha256_init(my_sha256_ctx *ctx) +{ +#if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS) + (void) mbedtls_sha256_starts(ctx, 0); +#else + (void) mbedtls_sha256_starts_ret(ctx, 0); +#endif + return CURLE_OK; +} + +static void my_sha256_update(my_sha256_ctx *ctx, + const unsigned char *data, + unsigned int length) +{ +#if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS) + (void) mbedtls_sha256_update(ctx, data, length); +#else + (void) mbedtls_sha256_update_ret(ctx, data, length); +#endif +} + +static void my_sha256_final(unsigned char *digest, my_sha256_ctx *ctx) +{ +#if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS) + (void) mbedtls_sha256_finish(ctx, digest); +#else + (void) mbedtls_sha256_finish_ret(ctx, digest); +#endif +} + +#elif defined(AN_APPLE_OS) +typedef CC_SHA256_CTX my_sha256_ctx; + +static CURLcode my_sha256_init(my_sha256_ctx *ctx) +{ + (void) CC_SHA256_Init(ctx); + return CURLE_OK; +} + +static void my_sha256_update(my_sha256_ctx *ctx, + const unsigned char *data, + unsigned int length) +{ + (void) CC_SHA256_Update(ctx, data, length); +} + +static void my_sha256_final(unsigned char *digest, my_sha256_ctx *ctx) +{ + (void) CC_SHA256_Final(digest, ctx); +} + +#elif defined(USE_WIN32_CRYPTO) + +struct sha256_ctx { + HCRYPTPROV hCryptProv; + HCRYPTHASH hHash; +}; +typedef struct sha256_ctx my_sha256_ctx; + +#if !defined(CALG_SHA_256) +#define CALG_SHA_256 0x0000800c +#endif + +static CURLcode my_sha256_init(my_sha256_ctx *ctx) +{ + if(!CryptAcquireContext(&ctx->hCryptProv, NULL, NULL, PROV_RSA_AES, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + return CURLE_OUT_OF_MEMORY; + + if(!CryptCreateHash(ctx->hCryptProv, CALG_SHA_256, 0, 0, &ctx->hHash)) { + CryptReleaseContext(ctx->hCryptProv, 0); + ctx->hCryptProv = 0; + return CURLE_FAILED_INIT; + } + + return CURLE_OK; +} + +static void my_sha256_update(my_sha256_ctx *ctx, + const unsigned char *data, + unsigned int length) +{ + CryptHashData(ctx->hHash, (unsigned char *) data, length, 0); +} + +static void my_sha256_final(unsigned char *digest, my_sha256_ctx *ctx) +{ + unsigned long length = 0; + + CryptGetHashParam(ctx->hHash, HP_HASHVAL, NULL, &length, 0); + if(length == SHA256_DIGEST_LENGTH) + CryptGetHashParam(ctx->hHash, HP_HASHVAL, digest, &length, 0); + + if(ctx->hHash) + CryptDestroyHash(ctx->hHash); + + if(ctx->hCryptProv) + CryptReleaseContext(ctx->hCryptProv, 0); +} + +#else + +/* When no other crypto library is available we use this code segment */ + +/* This is based on SHA256 implementation in LibTomCrypt that was released into + * public domain by Tom St Denis. */ + +#define WPA_GET_BE32(a) ((((unsigned long)(a)[0]) << 24) | \ + (((unsigned long)(a)[1]) << 16) | \ + (((unsigned long)(a)[2]) << 8) | \ + ((unsigned long)(a)[3])) +#define WPA_PUT_BE32(a, val) \ +do { \ + (a)[0] = (unsigned char)((((unsigned long) (val)) >> 24) & 0xff); \ + (a)[1] = (unsigned char)((((unsigned long) (val)) >> 16) & 0xff); \ + (a)[2] = (unsigned char)((((unsigned long) (val)) >> 8) & 0xff); \ + (a)[3] = (unsigned char)(((unsigned long) (val)) & 0xff); \ +} while(0) + +#ifdef HAVE_LONGLONG +#define WPA_PUT_BE64(a, val) \ +do { \ + (a)[0] = (unsigned char)(((unsigned long long)(val)) >> 56); \ + (a)[1] = (unsigned char)(((unsigned long long)(val)) >> 48); \ + (a)[2] = (unsigned char)(((unsigned long long)(val)) >> 40); \ + (a)[3] = (unsigned char)(((unsigned long long)(val)) >> 32); \ + (a)[4] = (unsigned char)(((unsigned long long)(val)) >> 24); \ + (a)[5] = (unsigned char)(((unsigned long long)(val)) >> 16); \ + (a)[6] = (unsigned char)(((unsigned long long)(val)) >> 8); \ + (a)[7] = (unsigned char)(((unsigned long long)(val)) & 0xff); \ +} while(0) +#else +#define WPA_PUT_BE64(a, val) \ +do { \ + (a)[0] = (unsigned char)(((unsigned __int64)(val)) >> 56); \ + (a)[1] = (unsigned char)(((unsigned __int64)(val)) >> 48); \ + (a)[2] = (unsigned char)(((unsigned __int64)(val)) >> 40); \ + (a)[3] = (unsigned char)(((unsigned __int64)(val)) >> 32); \ + (a)[4] = (unsigned char)(((unsigned __int64)(val)) >> 24); \ + (a)[5] = (unsigned char)(((unsigned __int64)(val)) >> 16); \ + (a)[6] = (unsigned char)(((unsigned __int64)(val)) >> 8); \ + (a)[7] = (unsigned char)(((unsigned __int64)(val)) & 0xff); \ +} while(0) +#endif + +struct sha256_state { +#ifdef HAVE_LONGLONG + unsigned long long length; +#else + unsigned __int64 length; +#endif + unsigned long state[8], curlen; + unsigned char buf[64]; +}; +typedef struct sha256_state my_sha256_ctx; + +/* The K array */ +static const unsigned long K[64] = { + 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL, + 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL, + 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, + 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, + 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL, + 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL, + 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, + 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, + 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL, + 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL, + 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, + 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, + 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL +}; + +/* Various logical functions */ +#define RORc(x, y) \ +(((((unsigned long)(x) & 0xFFFFFFFFUL) >> (unsigned long)((y) & 31)) | \ + ((unsigned long)(x) << (unsigned long)(32 - ((y) & 31)))) & 0xFFFFFFFFUL) +#define Ch(x,y,z) (z ^ (x & (y ^ z))) +#define Maj(x,y,z) (((x | y) & z) | (x & y)) +#define S(x, n) RORc((x), (n)) +#define R(x, n) (((x)&0xFFFFFFFFUL)>>(n)) +#define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22)) +#define Sigma1(x) (S(x, 6) ^ S(x, 11) ^ S(x, 25)) +#define Gamma0(x) (S(x, 7) ^ S(x, 18) ^ R(x, 3)) +#define Gamma1(x) (S(x, 17) ^ S(x, 19) ^ R(x, 10)) + +/* Compress 512-bits */ +static int sha256_compress(struct sha256_state *md, + unsigned char *buf) +{ + unsigned long S[8], W[64]; + int i; + + /* Copy state into S */ + for(i = 0; i < 8; i++) { + S[i] = md->state[i]; + } + /* copy the state into 512-bits into W[0..15] */ + for(i = 0; i < 16; i++) + W[i] = WPA_GET_BE32(buf + (4 * i)); + /* fill W[16..63] */ + for(i = 16; i < 64; i++) { + W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + + W[i - 16]; + } + + /* Compress */ +#define RND(a,b,c,d,e,f,g,h,i) \ + do { \ + unsigned long t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \ + unsigned long t1 = Sigma0(a) + Maj(a, b, c); \ + d += t0; \ + h = t0 + t1; \ + } while(0) + + for(i = 0; i < 64; ++i) { + unsigned long t; + RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], i); + t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4]; + S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t; + } + + /* Feedback */ + for(i = 0; i < 8; i++) { + md->state[i] = md->state[i] + S[i]; + } + + return 0; +} + +/* Initialize the hash state */ +static CURLcode my_sha256_init(struct sha256_state *md) +{ + md->curlen = 0; + md->length = 0; + md->state[0] = 0x6A09E667UL; + md->state[1] = 0xBB67AE85UL; + md->state[2] = 0x3C6EF372UL; + md->state[3] = 0xA54FF53AUL; + md->state[4] = 0x510E527FUL; + md->state[5] = 0x9B05688CUL; + md->state[6] = 0x1F83D9ABUL; + md->state[7] = 0x5BE0CD19UL; + + return CURLE_OK; +} + +/* + Process a block of memory though the hash + @param md The hash state + @param in The data to hash + @param inlen The length of the data (octets) + @return 0 if successful +*/ +static int my_sha256_update(struct sha256_state *md, + const unsigned char *in, + unsigned long inlen) +{ + unsigned long n; + +#define block_size 64 + if(md->curlen > sizeof(md->buf)) + return -1; + while(inlen > 0) { + if(md->curlen == 0 && inlen >= block_size) { + if(sha256_compress(md, (unsigned char *)in) < 0) + return -1; + md->length += block_size * 8; + in += block_size; + inlen -= block_size; + } + else { + n = CURLMIN(inlen, (block_size - md->curlen)); + memcpy(md->buf + md->curlen, in, n); + md->curlen += n; + in += n; + inlen -= n; + if(md->curlen == block_size) { + if(sha256_compress(md, md->buf) < 0) + return -1; + md->length += 8 * block_size; + md->curlen = 0; + } + } + } + + return 0; +} + +/* + Terminate the hash to get the digest + @param md The hash state + @param out [out] The destination of the hash (32 bytes) + @return 0 if successful +*/ +static int my_sha256_final(unsigned char *out, + struct sha256_state *md) +{ + int i; + + if(md->curlen >= sizeof(md->buf)) + return -1; + + /* Increase the length of the message */ + md->length += md->curlen * 8; + + /* Append the '1' bit */ + md->buf[md->curlen++] = (unsigned char)0x80; + + /* If the length is currently above 56 bytes we append zeros + * then compress. Then we can fall back to padding zeros and length + * encoding like normal. + */ + if(md->curlen > 56) { + while(md->curlen < 64) { + md->buf[md->curlen++] = (unsigned char)0; + } + sha256_compress(md, md->buf); + md->curlen = 0; + } + + /* Pad up to 56 bytes of zeroes */ + while(md->curlen < 56) { + md->buf[md->curlen++] = (unsigned char)0; + } + + /* Store length */ + WPA_PUT_BE64(md->buf + 56, md->length); + sha256_compress(md, md->buf); + + /* Copy output */ + for(i = 0; i < 8; i++) + WPA_PUT_BE32(out + (4 * i), md->state[i]); + + return 0; +} + +#endif /* CRYPTO LIBS */ + +/* + * Curl_sha256it() + * + * Generates a SHA256 hash for the given input data. + * + * Parameters: + * + * output [in/out] - The output buffer. + * input [in] - The input data. + * length [in] - The input length. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_sha256it(unsigned char *output, const unsigned char *input, + const size_t length) +{ + CURLcode result; + my_sha256_ctx ctx; + + result = my_sha256_init(&ctx); + if(!result) { + my_sha256_update(&ctx, input, curlx_uztoui(length)); + my_sha256_final(output, &ctx); + } + return result; +} + + +const struct HMAC_params Curl_HMAC_SHA256[] = { + { + /* Hash initialization function. */ + CURLX_FUNCTION_CAST(HMAC_hinit_func, my_sha256_init), + /* Hash update function. */ + CURLX_FUNCTION_CAST(HMAC_hupdate_func, my_sha256_update), + /* Hash computation end function. */ + CURLX_FUNCTION_CAST(HMAC_hfinal_func, my_sha256_final), + /* Size of hash context structure. */ + sizeof(my_sha256_ctx), + /* Maximum key length. */ + 64, + /* Result size. */ + 32 + } +}; + + +#endif /* AWS, DIGEST, or libSSH2 */ diff --git a/third_party/curl/lib/share.c b/third_party/curl/lib/share.c new file mode 100644 index 0000000..8fa5cda --- /dev/null +++ b/third_party/curl/lib/share.c @@ -0,0 +1,290 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include +#include "urldata.h" +#include "share.h" +#include "psl.h" +#include "vtls/vtls.h" +#include "hsts.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +struct Curl_share * +curl_share_init(void) +{ + struct Curl_share *share = calloc(1, sizeof(struct Curl_share)); + if(share) { + share->magic = CURL_GOOD_SHARE; + share->specifier |= (1<hostcache, 23); + } + + return share; +} + +#undef curl_share_setopt +CURLSHcode +curl_share_setopt(struct Curl_share *share, CURLSHoption option, ...) +{ + va_list param; + int type; + curl_lock_function lockfunc; + curl_unlock_function unlockfunc; + void *ptr; + CURLSHcode res = CURLSHE_OK; + + if(!GOOD_SHARE_HANDLE(share)) + return CURLSHE_INVALID; + + if(share->dirty) + /* don't allow setting options while one or more handles are already + using this share */ + return CURLSHE_IN_USE; + + va_start(param, option); + + switch(option) { + case CURLSHOPT_SHARE: + /* this is a type this share will share */ + type = va_arg(param, int); + + switch(type) { + case CURL_LOCK_DATA_DNS: + break; + + case CURL_LOCK_DATA_COOKIE: +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) + if(!share->cookies) { + share->cookies = Curl_cookie_init(NULL, NULL, NULL, TRUE); + if(!share->cookies) + res = CURLSHE_NOMEM; + } +#else /* CURL_DISABLE_HTTP */ + res = CURLSHE_NOT_BUILT_IN; +#endif + break; + + case CURL_LOCK_DATA_HSTS: +#ifndef CURL_DISABLE_HSTS + if(!share->hsts) { + share->hsts = Curl_hsts_init(); + if(!share->hsts) + res = CURLSHE_NOMEM; + } +#else /* CURL_DISABLE_HSTS */ + res = CURLSHE_NOT_BUILT_IN; +#endif + break; + + case CURL_LOCK_DATA_SSL_SESSION: +#ifdef USE_SSL + if(!share->sslsession) { + share->max_ssl_sessions = 8; + share->sslsession = calloc(share->max_ssl_sessions, + sizeof(struct Curl_ssl_session)); + share->sessionage = 0; + if(!share->sslsession) + res = CURLSHE_NOMEM; + } +#else + res = CURLSHE_NOT_BUILT_IN; +#endif + break; + + case CURL_LOCK_DATA_CONNECT: + if(Curl_conncache_init(&share->conn_cache, 103)) + res = CURLSHE_NOMEM; + break; + + case CURL_LOCK_DATA_PSL: +#ifndef USE_LIBPSL + res = CURLSHE_NOT_BUILT_IN; +#endif + break; + + default: + res = CURLSHE_BAD_OPTION; + } + if(!res) + share->specifier |= (unsigned int)(1<specifier &= ~(unsigned int)(1<cookies) { + Curl_cookie_cleanup(share->cookies); + share->cookies = NULL; + } +#else /* CURL_DISABLE_HTTP */ + res = CURLSHE_NOT_BUILT_IN; +#endif + break; + + case CURL_LOCK_DATA_HSTS: +#ifndef CURL_DISABLE_HSTS + if(share->hsts) { + Curl_hsts_cleanup(&share->hsts); + } +#else /* CURL_DISABLE_HSTS */ + res = CURLSHE_NOT_BUILT_IN; +#endif + break; + + case CURL_LOCK_DATA_SSL_SESSION: +#ifdef USE_SSL + Curl_safefree(share->sslsession); +#else + res = CURLSHE_NOT_BUILT_IN; +#endif + break; + + case CURL_LOCK_DATA_CONNECT: + break; + + default: + res = CURLSHE_BAD_OPTION; + break; + } + break; + + case CURLSHOPT_LOCKFUNC: + lockfunc = va_arg(param, curl_lock_function); + share->lockfunc = lockfunc; + break; + + case CURLSHOPT_UNLOCKFUNC: + unlockfunc = va_arg(param, curl_unlock_function); + share->unlockfunc = unlockfunc; + break; + + case CURLSHOPT_USERDATA: + ptr = va_arg(param, void *); + share->clientdata = ptr; + break; + + default: + res = CURLSHE_BAD_OPTION; + break; + } + + va_end(param); + + return res; +} + +CURLSHcode +curl_share_cleanup(struct Curl_share *share) +{ + if(!GOOD_SHARE_HANDLE(share)) + return CURLSHE_INVALID; + + if(share->lockfunc) + share->lockfunc(NULL, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE, + share->clientdata); + + if(share->dirty) { + if(share->unlockfunc) + share->unlockfunc(NULL, CURL_LOCK_DATA_SHARE, share->clientdata); + return CURLSHE_IN_USE; + } + + Curl_conncache_close_all_connections(&share->conn_cache); + Curl_conncache_destroy(&share->conn_cache); + Curl_hash_destroy(&share->hostcache); + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) + Curl_cookie_cleanup(share->cookies); +#endif + +#ifndef CURL_DISABLE_HSTS + Curl_hsts_cleanup(&share->hsts); +#endif + +#ifdef USE_SSL + if(share->sslsession) { + size_t i; + for(i = 0; i < share->max_ssl_sessions; i++) + Curl_ssl_kill_session(&(share->sslsession[i])); + free(share->sslsession); + } +#endif + + Curl_psl_destroy(&share->psl); + + if(share->unlockfunc) + share->unlockfunc(NULL, CURL_LOCK_DATA_SHARE, share->clientdata); + share->magic = 0; + free(share); + + return CURLSHE_OK; +} + + +CURLSHcode +Curl_share_lock(struct Curl_easy *data, curl_lock_data type, + curl_lock_access accesstype) +{ + struct Curl_share *share = data->share; + + if(!share) + return CURLSHE_INVALID; + + if(share->specifier & (unsigned int)(1<lockfunc) /* only call this if set! */ + share->lockfunc(data, type, accesstype, share->clientdata); + } + /* else if we don't share this, pretend successful lock */ + + return CURLSHE_OK; +} + +CURLSHcode +Curl_share_unlock(struct Curl_easy *data, curl_lock_data type) +{ + struct Curl_share *share = data->share; + + if(!share) + return CURLSHE_INVALID; + + if(share->specifier & (unsigned int)(1<unlockfunc) /* only call this if set! */ + share->unlockfunc (data, type, share->clientdata); + } + + return CURLSHE_OK; +} diff --git a/third_party/curl/lib/share.h b/third_party/curl/lib/share.h new file mode 100644 index 0000000..632d919 --- /dev/null +++ b/third_party/curl/lib/share.h @@ -0,0 +1,68 @@ +#ifndef HEADER_CURL_SHARE_H +#define HEADER_CURL_SHARE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include +#include "cookie.h" +#include "psl.h" +#include "urldata.h" +#include "conncache.h" + +#define CURL_GOOD_SHARE 0x7e117a1e +#define GOOD_SHARE_HANDLE(x) ((x) && (x)->magic == CURL_GOOD_SHARE) + +/* this struct is libcurl-private, don't export details */ +struct Curl_share { + unsigned int magic; /* CURL_GOOD_SHARE */ + unsigned int specifier; + volatile unsigned int dirty; + + curl_lock_function lockfunc; + curl_unlock_function unlockfunc; + void *clientdata; + struct conncache conn_cache; + struct Curl_hash hostcache; +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) + struct CookieInfo *cookies; +#endif +#ifdef USE_LIBPSL + struct PslCache psl; +#endif +#ifndef CURL_DISABLE_HSTS + struct hsts *hsts; +#endif +#ifdef USE_SSL + struct Curl_ssl_session *sslsession; + size_t max_ssl_sessions; + long sessionage; +#endif +}; + +CURLSHcode Curl_share_lock(struct Curl_easy *, curl_lock_data, + curl_lock_access); +CURLSHcode Curl_share_unlock(struct Curl_easy *, curl_lock_data); + +#endif /* HEADER_CURL_SHARE_H */ diff --git a/third_party/curl/lib/sigpipe.h b/third_party/curl/lib/sigpipe.h new file mode 100644 index 0000000..9b29403 --- /dev/null +++ b/third_party/curl/lib/sigpipe.h @@ -0,0 +1,80 @@ +#ifndef HEADER_CURL_SIGPIPE_H +#define HEADER_CURL_SIGPIPE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(HAVE_SIGACTION) && \ + (defined(USE_OPENSSL) || defined(USE_MBEDTLS) || defined(USE_WOLFSSL)) +#include + +struct sigpipe_ignore { + struct sigaction old_pipe_act; + bool no_signal; +}; + +#define SIGPIPE_VARIABLE(x) struct sigpipe_ignore x + +/* + * sigpipe_ignore() makes sure we ignore SIGPIPE while running libcurl + * internals, and then sigpipe_restore() will restore the situation when we + * return from libcurl again. + */ +static void sigpipe_ignore(struct Curl_easy *data, + struct sigpipe_ignore *ig) +{ + /* get a local copy of no_signal because the Curl_easy might not be + around when we restore */ + ig->no_signal = data->set.no_signal; + if(!data->set.no_signal) { + struct sigaction action; + /* first, extract the existing situation */ + sigaction(SIGPIPE, NULL, &ig->old_pipe_act); + action = ig->old_pipe_act; + /* ignore this signal */ + action.sa_handler = SIG_IGN; + sigaction(SIGPIPE, &action, NULL); + } +} + +/* + * sigpipe_restore() puts back the outside world's opinion of signal handler + * and SIGPIPE handling. It MUST only be called after a corresponding + * sigpipe_ignore() was used. + */ +static void sigpipe_restore(struct sigpipe_ignore *ig) +{ + if(!ig->no_signal) + /* restore the outside state */ + sigaction(SIGPIPE, &ig->old_pipe_act, NULL); +} + +#else +/* for systems without sigaction */ +#define sigpipe_ignore(x,y) Curl_nop_stmt +#define sigpipe_restore(x) Curl_nop_stmt +#define SIGPIPE_VARIABLE(x) +#endif + +#endif /* HEADER_CURL_SIGPIPE_H */ diff --git a/third_party/curl/lib/slist.c b/third_party/curl/lib/slist.c new file mode 100644 index 0000000..366b247 --- /dev/null +++ b/third_party/curl/lib/slist.c @@ -0,0 +1,146 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "slist.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* returns last node in linked list */ +static struct curl_slist *slist_get_last(struct curl_slist *list) +{ + struct curl_slist *item; + + /* if caller passed us a NULL, return now */ + if(!list) + return NULL; + + /* loop through to find the last item */ + item = list; + while(item->next) { + item = item->next; + } + return item; +} + +/* + * Curl_slist_append_nodup() appends a string to the linked list. Rather than + * copying the string in dynamic storage, it takes its ownership. The string + * should have been malloc()ated. Curl_slist_append_nodup always returns + * the address of the first record, so that you can use this function as an + * initialization function as well as an append function. + * If an error occurs, NULL is returned and the string argument is NOT + * released. + */ +struct curl_slist *Curl_slist_append_nodup(struct curl_slist *list, char *data) +{ + struct curl_slist *last; + struct curl_slist *new_item; + + DEBUGASSERT(data); + + new_item = malloc(sizeof(struct curl_slist)); + if(!new_item) + return NULL; + + new_item->next = NULL; + new_item->data = data; + + /* if this is the first item, then new_item *is* the list */ + if(!list) + return new_item; + + last = slist_get_last(list); + last->next = new_item; + return list; +} + +/* + * curl_slist_append() appends a string to the linked list. It always returns + * the address of the first record, so that you can use this function as an + * initialization function as well as an append function. If you find this + * bothersome, then simply create a separate _init function and call it + * appropriately from within the program. + */ +struct curl_slist *curl_slist_append(struct curl_slist *list, + const char *data) +{ + char *dupdata = strdup(data); + + if(!dupdata) + return NULL; + + list = Curl_slist_append_nodup(list, dupdata); + if(!list) + free(dupdata); + + return list; +} + +/* + * Curl_slist_duplicate() duplicates a linked list. It always returns the + * address of the first record of the cloned list or NULL in case of an + * error (or if the input list was NULL). + */ +struct curl_slist *Curl_slist_duplicate(struct curl_slist *inlist) +{ + struct curl_slist *outlist = NULL; + struct curl_slist *tmp; + + while(inlist) { + tmp = curl_slist_append(outlist, inlist->data); + + if(!tmp) { + curl_slist_free_all(outlist); + return NULL; + } + + outlist = tmp; + inlist = inlist->next; + } + return outlist; +} + +/* be nice and clean up resources */ +void curl_slist_free_all(struct curl_slist *list) +{ + struct curl_slist *next; + struct curl_slist *item; + + if(!list) + return; + + item = list; + do { + next = item->next; + Curl_safefree(item->data); + free(item); + item = next; + } while(next); +} diff --git a/third_party/curl/lib/slist.h b/third_party/curl/lib/slist.h new file mode 100644 index 0000000..9561fd0 --- /dev/null +++ b/third_party/curl/lib/slist.h @@ -0,0 +1,41 @@ +#ifndef HEADER_CURL_SLIST_H +#define HEADER_CURL_SLIST_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Curl_slist_duplicate() duplicates a linked list. It always returns the + * address of the first record of the cloned list or NULL in case of an + * error (or if the input list was NULL). + */ +struct curl_slist *Curl_slist_duplicate(struct curl_slist *inlist); + +/* + * Curl_slist_append_nodup() takes ownership of the given string and appends + * it to the list. + */ +struct curl_slist *Curl_slist_append_nodup(struct curl_slist *list, + char *data); + +#endif /* HEADER_CURL_SLIST_H */ diff --git a/third_party/curl/lib/smb.c b/third_party/curl/lib/smb.c new file mode 100644 index 0000000..cab1e75 --- /dev/null +++ b/third_party/curl/lib/smb.c @@ -0,0 +1,1206 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (C) Bill Nagel , Exacq Technologies + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_SMB) && defined(USE_CURL_NTLM_CORE) + +#ifdef _WIN32 +#define getpid GetCurrentProcessId +#endif + +#include "smb.h" +#include "urldata.h" +#include "sendf.h" +#include "multiif.h" +#include "cfilters.h" +#include "connect.h" +#include "progress.h" +#include "transfer.h" +#include "vtls/vtls.h" +#include "curl_ntlm_core.h" +#include "escape.h" +#include "curl_endian.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Definitions for SMB protocol data structures + */ +#if defined(_MSC_VER) || defined(__ILEC400__) +# define PACK +# pragma pack(push) +# pragma pack(1) +#elif defined(__GNUC__) +# define PACK __attribute__((packed)) +#else +# define PACK +#endif + +#define SMB_COM_CLOSE 0x04 +#define SMB_COM_READ_ANDX 0x2e +#define SMB_COM_WRITE_ANDX 0x2f +#define SMB_COM_TREE_DISCONNECT 0x71 +#define SMB_COM_NEGOTIATE 0x72 +#define SMB_COM_SETUP_ANDX 0x73 +#define SMB_COM_TREE_CONNECT_ANDX 0x75 +#define SMB_COM_NT_CREATE_ANDX 0xa2 +#define SMB_COM_NO_ANDX_COMMAND 0xff + +#define SMB_WC_CLOSE 0x03 +#define SMB_WC_READ_ANDX 0x0c +#define SMB_WC_WRITE_ANDX 0x0e +#define SMB_WC_SETUP_ANDX 0x0d +#define SMB_WC_TREE_CONNECT_ANDX 0x04 +#define SMB_WC_NT_CREATE_ANDX 0x18 + +#define SMB_FLAGS_CANONICAL_PATHNAMES 0x10 +#define SMB_FLAGS_CASELESS_PATHNAMES 0x08 +#define SMB_FLAGS2_UNICODE_STRINGS 0x8000 +#define SMB_FLAGS2_IS_LONG_NAME 0x0040 +#define SMB_FLAGS2_KNOWS_LONG_NAME 0x0001 + +#define SMB_CAP_LARGE_FILES 0x08 +#define SMB_GENERIC_WRITE 0x40000000 +#define SMB_GENERIC_READ 0x80000000 +#define SMB_FILE_SHARE_ALL 0x07 +#define SMB_FILE_OPEN 0x01 +#define SMB_FILE_OVERWRITE_IF 0x05 + +#define SMB_ERR_NOACCESS 0x00050001 + +struct smb_header { + unsigned char nbt_type; + unsigned char nbt_flags; + unsigned short nbt_length; + unsigned char magic[4]; + unsigned char command; + unsigned int status; + unsigned char flags; + unsigned short flags2; + unsigned short pid_high; + unsigned char signature[8]; + unsigned short pad; + unsigned short tid; + unsigned short pid; + unsigned short uid; + unsigned short mid; +} PACK; + +struct smb_negotiate_response { + struct smb_header h; + unsigned char word_count; + unsigned short dialect_index; + unsigned char security_mode; + unsigned short max_mpx_count; + unsigned short max_number_vcs; + unsigned int max_buffer_size; + unsigned int max_raw_size; + unsigned int session_key; + unsigned int capabilities; + unsigned int system_time_low; + unsigned int system_time_high; + unsigned short server_time_zone; + unsigned char encryption_key_length; + unsigned short byte_count; + char bytes[1]; +} PACK; + +struct andx { + unsigned char command; + unsigned char pad; + unsigned short offset; +} PACK; + +struct smb_setup { + unsigned char word_count; + struct andx andx; + unsigned short max_buffer_size; + unsigned short max_mpx_count; + unsigned short vc_number; + unsigned int session_key; + unsigned short lengths[2]; + unsigned int pad; + unsigned int capabilities; + unsigned short byte_count; + char bytes[1024]; +} PACK; + +struct smb_tree_connect { + unsigned char word_count; + struct andx andx; + unsigned short flags; + unsigned short pw_len; + unsigned short byte_count; + char bytes[1024]; +} PACK; + +struct smb_nt_create { + unsigned char word_count; + struct andx andx; + unsigned char pad; + unsigned short name_length; + unsigned int flags; + unsigned int root_fid; + unsigned int access; + curl_off_t allocation_size; + unsigned int ext_file_attributes; + unsigned int share_access; + unsigned int create_disposition; + unsigned int create_options; + unsigned int impersonation_level; + unsigned char security_flags; + unsigned short byte_count; + char bytes[1024]; +} PACK; + +struct smb_nt_create_response { + struct smb_header h; + unsigned char word_count; + struct andx andx; + unsigned char op_lock_level; + unsigned short fid; + unsigned int create_disposition; + + curl_off_t create_time; + curl_off_t last_access_time; + curl_off_t last_write_time; + curl_off_t last_change_time; + unsigned int ext_file_attributes; + curl_off_t allocation_size; + curl_off_t end_of_file; +} PACK; + +struct smb_read { + unsigned char word_count; + struct andx andx; + unsigned short fid; + unsigned int offset; + unsigned short max_bytes; + unsigned short min_bytes; + unsigned int timeout; + unsigned short remaining; + unsigned int offset_high; + unsigned short byte_count; +} PACK; + +struct smb_write { + struct smb_header h; + unsigned char word_count; + struct andx andx; + unsigned short fid; + unsigned int offset; + unsigned int timeout; + unsigned short write_mode; + unsigned short remaining; + unsigned short pad; + unsigned short data_length; + unsigned short data_offset; + unsigned int offset_high; + unsigned short byte_count; + unsigned char pad2; +} PACK; + +struct smb_close { + unsigned char word_count; + unsigned short fid; + unsigned int last_mtime; + unsigned short byte_count; +} PACK; + +struct smb_tree_disconnect { + unsigned char word_count; + unsigned short byte_count; +} PACK; + +#if defined(_MSC_VER) || defined(__ILEC400__) +# pragma pack(pop) +#endif + +/* Local API functions */ +static CURLcode smb_setup_connection(struct Curl_easy *data, + struct connectdata *conn); +static CURLcode smb_connect(struct Curl_easy *data, bool *done); +static CURLcode smb_connection_state(struct Curl_easy *data, bool *done); +static CURLcode smb_do(struct Curl_easy *data, bool *done); +static CURLcode smb_request_state(struct Curl_easy *data, bool *done); +static CURLcode smb_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead); +static int smb_getsock(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t *socks); +static CURLcode smb_parse_url_path(struct Curl_easy *data, + struct connectdata *conn); + +/* + * SMB handler interface + */ +const struct Curl_handler Curl_handler_smb = { + "smb", /* scheme */ + smb_setup_connection, /* setup_connection */ + smb_do, /* do_it */ + ZERO_NULL, /* done */ + ZERO_NULL, /* do_more */ + smb_connect, /* connect_it */ + smb_connection_state, /* connecting */ + smb_request_state, /* doing */ + smb_getsock, /* proto_getsock */ + smb_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + smb_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_SMB, /* defport */ + CURLPROTO_SMB, /* protocol */ + CURLPROTO_SMB, /* family */ + PROTOPT_NONE /* flags */ +}; + +#ifdef USE_SSL +/* + * SMBS handler interface + */ +const struct Curl_handler Curl_handler_smbs = { + "smbs", /* scheme */ + smb_setup_connection, /* setup_connection */ + smb_do, /* do_it */ + ZERO_NULL, /* done */ + ZERO_NULL, /* do_more */ + smb_connect, /* connect_it */ + smb_connection_state, /* connecting */ + smb_request_state, /* doing */ + smb_getsock, /* proto_getsock */ + smb_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + smb_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_SMBS, /* defport */ + CURLPROTO_SMBS, /* protocol */ + CURLPROTO_SMB, /* family */ + PROTOPT_SSL /* flags */ +}; +#endif + +#define MAX_PAYLOAD_SIZE 0x8000 +#define MAX_MESSAGE_SIZE (MAX_PAYLOAD_SIZE + 0x1000) +#define CLIENTNAME "curl" +#define SERVICENAME "?????" + +/* Append a string to an SMB message */ +#define MSGCAT(str) \ + do { \ + strcpy(p, (str)); \ + p += strlen(str); \ + } while(0) + +/* Append a null-terminated string to an SMB message */ +#define MSGCATNULL(str) \ + do { \ + strcpy(p, (str)); \ + p += strlen(str) + 1; \ + } while(0) + +/* SMB is mostly little endian */ +#if (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) || \ + defined(__OS400__) +static unsigned short smb_swap16(unsigned short x) +{ + return (unsigned short) ((x << 8) | ((x >> 8) & 0xff)); +} + +static unsigned int smb_swap32(unsigned int x) +{ + return (x << 24) | ((x << 8) & 0xff0000) | ((x >> 8) & 0xff00) | + ((x >> 24) & 0xff); +} + +static curl_off_t smb_swap64(curl_off_t x) +{ + return ((curl_off_t) smb_swap32((unsigned int) x) << 32) | + smb_swap32((unsigned int) (x >> 32)); +} + +#else +# define smb_swap16(x) (x) +# define smb_swap32(x) (x) +# define smb_swap64(x) (x) +#endif + +/* SMB request state */ +enum smb_req_state { + SMB_REQUESTING, + SMB_TREE_CONNECT, + SMB_OPEN, + SMB_DOWNLOAD, + SMB_UPLOAD, + SMB_CLOSE, + SMB_TREE_DISCONNECT, + SMB_DONE +}; + +/* SMB request data */ +struct smb_request { + enum smb_req_state state; + char *path; + unsigned short tid; /* Even if we connect to the same tree as another */ + unsigned short fid; /* request, the tid will be different */ + CURLcode result; +}; + +static void conn_state(struct Curl_easy *data, enum smb_conn_state newstate) +{ + struct smb_conn *smbc = &data->conn->proto.smbc; +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + /* For debug purposes */ + static const char * const names[] = { + "SMB_NOT_CONNECTED", + "SMB_CONNECTING", + "SMB_NEGOTIATE", + "SMB_SETUP", + "SMB_CONNECTED", + /* LAST */ + }; + + if(smbc->state != newstate) + infof(data, "SMB conn %p state change from %s to %s", + (void *)smbc, names[smbc->state], names[newstate]); +#endif + + smbc->state = newstate; +} + +static void request_state(struct Curl_easy *data, + enum smb_req_state newstate) +{ + struct smb_request *req = data->req.p.smb; +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + /* For debug purposes */ + static const char * const names[] = { + "SMB_REQUESTING", + "SMB_TREE_CONNECT", + "SMB_OPEN", + "SMB_DOWNLOAD", + "SMB_UPLOAD", + "SMB_CLOSE", + "SMB_TREE_DISCONNECT", + "SMB_DONE", + /* LAST */ + }; + + if(req->state != newstate) + infof(data, "SMB request %p state change from %s to %s", + (void *)req, names[req->state], names[newstate]); +#endif + + req->state = newstate; +} + +/* this should setup things in the connection, not in the easy + handle */ +static CURLcode smb_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + struct smb_request *req; + + /* Initialize the request state */ + data->req.p.smb = req = calloc(1, sizeof(struct smb_request)); + if(!req) + return CURLE_OUT_OF_MEMORY; + + /* Parse the URL path */ + return smb_parse_url_path(data, conn); +} + +static CURLcode smb_connect(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct smb_conn *smbc = &conn->proto.smbc; + char *slash; + + (void) done; + + /* Check we have a username and password to authenticate with */ + if(!data->state.aptr.user) + return CURLE_LOGIN_DENIED; + + /* Initialize the connection state */ + smbc->state = SMB_CONNECTING; + smbc->recv_buf = malloc(MAX_MESSAGE_SIZE); + if(!smbc->recv_buf) + return CURLE_OUT_OF_MEMORY; + smbc->send_buf = malloc(MAX_MESSAGE_SIZE); + if(!smbc->send_buf) + return CURLE_OUT_OF_MEMORY; + + /* Multiple requests are allowed with this connection */ + connkeep(conn, "SMB default"); + + /* Parse the username, domain, and password */ + slash = strchr(conn->user, '/'); + if(!slash) + slash = strchr(conn->user, '\\'); + + if(slash) { + smbc->user = slash + 1; + smbc->domain = strdup(conn->user); + if(!smbc->domain) + return CURLE_OUT_OF_MEMORY; + smbc->domain[slash - conn->user] = 0; + } + else { + smbc->user = conn->user; + smbc->domain = strdup(conn->host.name); + if(!smbc->domain) + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} + +static CURLcode smb_recv_message(struct Curl_easy *data, void **msg) +{ + struct connectdata *conn = data->conn; + struct smb_conn *smbc = &conn->proto.smbc; + char *buf = smbc->recv_buf; + ssize_t bytes_read; + size_t nbt_size; + size_t msg_size; + size_t len = MAX_MESSAGE_SIZE - smbc->got; + CURLcode result; + + result = Curl_xfer_recv(data, buf + smbc->got, len, &bytes_read); + if(result) + return result; + + if(!bytes_read) + return CURLE_OK; + + smbc->got += bytes_read; + + /* Check for a 32-bit nbt header */ + if(smbc->got < sizeof(unsigned int)) + return CURLE_OK; + + nbt_size = Curl_read16_be((const unsigned char *) + (buf + sizeof(unsigned short))) + + sizeof(unsigned int); + if(smbc->got < nbt_size) + return CURLE_OK; + + msg_size = sizeof(struct smb_header); + if(nbt_size >= msg_size + 1) { + /* Add the word count */ + msg_size += 1 + ((unsigned char) buf[msg_size]) * sizeof(unsigned short); + if(nbt_size >= msg_size + sizeof(unsigned short)) { + /* Add the byte count */ + msg_size += sizeof(unsigned short) + + Curl_read16_le((const unsigned char *)&buf[msg_size]); + if(nbt_size < msg_size) + return CURLE_READ_ERROR; + } + } + + *msg = buf; + + return CURLE_OK; +} + +static void smb_pop_message(struct connectdata *conn) +{ + struct smb_conn *smbc = &conn->proto.smbc; + + smbc->got = 0; +} + +static void smb_format_message(struct Curl_easy *data, struct smb_header *h, + unsigned char cmd, size_t len) +{ + struct connectdata *conn = data->conn; + struct smb_conn *smbc = &conn->proto.smbc; + struct smb_request *req = data->req.p.smb; + unsigned int pid; + + memset(h, 0, sizeof(*h)); + h->nbt_length = htons((unsigned short) (sizeof(*h) - sizeof(unsigned int) + + len)); + memcpy((char *)h->magic, "\xffSMB", 4); + h->command = cmd; + h->flags = SMB_FLAGS_CANONICAL_PATHNAMES | SMB_FLAGS_CASELESS_PATHNAMES; + h->flags2 = smb_swap16(SMB_FLAGS2_IS_LONG_NAME | SMB_FLAGS2_KNOWS_LONG_NAME); + h->uid = smb_swap16(smbc->uid); + h->tid = smb_swap16(req->tid); + pid = getpid(); + h->pid_high = smb_swap16((unsigned short)(pid >> 16)); + h->pid = smb_swap16((unsigned short) pid); +} + +static CURLcode smb_send(struct Curl_easy *data, size_t len, + size_t upload_size) +{ + struct connectdata *conn = data->conn; + struct smb_conn *smbc = &conn->proto.smbc; + size_t bytes_written; + CURLcode result; + + result = Curl_xfer_send(data, smbc->send_buf, len, &bytes_written); + if(result) + return result; + + if(bytes_written != len) { + smbc->send_size = len; + smbc->sent = bytes_written; + } + + smbc->upload_size = upload_size; + + return CURLE_OK; +} + +static CURLcode smb_flush(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + struct smb_conn *smbc = &conn->proto.smbc; + size_t bytes_written; + size_t len = smbc->send_size - smbc->sent; + CURLcode result; + + if(!smbc->send_size) + return CURLE_OK; + + result = Curl_xfer_send(data, smbc->send_buf + smbc->sent, len, + &bytes_written); + if(result) + return result; + + if(bytes_written != len) + smbc->sent += bytes_written; + else + smbc->send_size = 0; + + return CURLE_OK; +} + +static CURLcode smb_send_message(struct Curl_easy *data, unsigned char cmd, + const void *msg, size_t msg_len) +{ + struct connectdata *conn = data->conn; + struct smb_conn *smbc = &conn->proto.smbc; + + smb_format_message(data, (struct smb_header *)smbc->send_buf, + cmd, msg_len); + DEBUGASSERT((sizeof(struct smb_header) + msg_len) <= MAX_MESSAGE_SIZE); + memcpy(smbc->send_buf + sizeof(struct smb_header), msg, msg_len); + + return smb_send(data, sizeof(struct smb_header) + msg_len, 0); +} + +static CURLcode smb_send_negotiate(struct Curl_easy *data) +{ + const char *msg = "\x00\x0c\x00\x02NT LM 0.12"; + + return smb_send_message(data, SMB_COM_NEGOTIATE, msg, 15); +} + +static CURLcode smb_send_setup(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + struct smb_conn *smbc = &conn->proto.smbc; + struct smb_setup msg; + char *p = msg.bytes; + unsigned char lm_hash[21]; + unsigned char lm[24]; + unsigned char nt_hash[21]; + unsigned char nt[24]; + + size_t byte_count = sizeof(lm) + sizeof(nt); + byte_count += strlen(smbc->user) + strlen(smbc->domain); + byte_count += strlen(OS) + strlen(CLIENTNAME) + 4; /* 4 null chars */ + if(byte_count > sizeof(msg.bytes)) + return CURLE_FILESIZE_EXCEEDED; + + Curl_ntlm_core_mk_lm_hash(conn->passwd, lm_hash); + Curl_ntlm_core_lm_resp(lm_hash, smbc->challenge, lm); + Curl_ntlm_core_mk_nt_hash(conn->passwd, nt_hash); + Curl_ntlm_core_lm_resp(nt_hash, smbc->challenge, nt); + + memset(&msg, 0, sizeof(msg)); + msg.word_count = SMB_WC_SETUP_ANDX; + msg.andx.command = SMB_COM_NO_ANDX_COMMAND; + msg.max_buffer_size = smb_swap16(MAX_MESSAGE_SIZE); + msg.max_mpx_count = smb_swap16(1); + msg.vc_number = smb_swap16(1); + msg.session_key = smb_swap32(smbc->session_key); + msg.capabilities = smb_swap32(SMB_CAP_LARGE_FILES); + msg.lengths[0] = smb_swap16(sizeof(lm)); + msg.lengths[1] = smb_swap16(sizeof(nt)); + memcpy(p, lm, sizeof(lm)); + p += sizeof(lm); + memcpy(p, nt, sizeof(nt)); + p += sizeof(nt); + MSGCATNULL(smbc->user); + MSGCATNULL(smbc->domain); + MSGCATNULL(OS); + MSGCATNULL(CLIENTNAME); + byte_count = p - msg.bytes; + msg.byte_count = smb_swap16((unsigned short)byte_count); + + return smb_send_message(data, SMB_COM_SETUP_ANDX, &msg, + sizeof(msg) - sizeof(msg.bytes) + byte_count); +} + +static CURLcode smb_send_tree_connect(struct Curl_easy *data) +{ + struct smb_tree_connect msg; + struct connectdata *conn = data->conn; + struct smb_conn *smbc = &conn->proto.smbc; + char *p = msg.bytes; + + size_t byte_count = strlen(conn->host.name) + strlen(smbc->share); + byte_count += strlen(SERVICENAME) + 5; /* 2 nulls and 3 backslashes */ + if(byte_count > sizeof(msg.bytes)) + return CURLE_FILESIZE_EXCEEDED; + + memset(&msg, 0, sizeof(msg)); + msg.word_count = SMB_WC_TREE_CONNECT_ANDX; + msg.andx.command = SMB_COM_NO_ANDX_COMMAND; + msg.pw_len = 0; + MSGCAT("\\\\"); + MSGCAT(conn->host.name); + MSGCAT("\\"); + MSGCATNULL(smbc->share); + MSGCATNULL(SERVICENAME); /* Match any type of service */ + byte_count = p - msg.bytes; + msg.byte_count = smb_swap16((unsigned short)byte_count); + + return smb_send_message(data, SMB_COM_TREE_CONNECT_ANDX, &msg, + sizeof(msg) - sizeof(msg.bytes) + byte_count); +} + +static CURLcode smb_send_open(struct Curl_easy *data) +{ + struct smb_request *req = data->req.p.smb; + struct smb_nt_create msg; + size_t byte_count; + + if((strlen(req->path) + 1) > sizeof(msg.bytes)) + return CURLE_FILESIZE_EXCEEDED; + + memset(&msg, 0, sizeof(msg)); + msg.word_count = SMB_WC_NT_CREATE_ANDX; + msg.andx.command = SMB_COM_NO_ANDX_COMMAND; + byte_count = strlen(req->path); + msg.name_length = smb_swap16((unsigned short)byte_count); + msg.share_access = smb_swap32(SMB_FILE_SHARE_ALL); + if(data->state.upload) { + msg.access = smb_swap32(SMB_GENERIC_READ | SMB_GENERIC_WRITE); + msg.create_disposition = smb_swap32(SMB_FILE_OVERWRITE_IF); + } + else { + msg.access = smb_swap32(SMB_GENERIC_READ); + msg.create_disposition = smb_swap32(SMB_FILE_OPEN); + } + msg.byte_count = smb_swap16((unsigned short) ++byte_count); + strcpy(msg.bytes, req->path); + + return smb_send_message(data, SMB_COM_NT_CREATE_ANDX, &msg, + sizeof(msg) - sizeof(msg.bytes) + byte_count); +} + +static CURLcode smb_send_close(struct Curl_easy *data) +{ + struct smb_request *req = data->req.p.smb; + struct smb_close msg; + + memset(&msg, 0, sizeof(msg)); + msg.word_count = SMB_WC_CLOSE; + msg.fid = smb_swap16(req->fid); + + return smb_send_message(data, SMB_COM_CLOSE, &msg, sizeof(msg)); +} + +static CURLcode smb_send_tree_disconnect(struct Curl_easy *data) +{ + struct smb_tree_disconnect msg; + + memset(&msg, 0, sizeof(msg)); + + return smb_send_message(data, SMB_COM_TREE_DISCONNECT, &msg, sizeof(msg)); +} + +static CURLcode smb_send_read(struct Curl_easy *data) +{ + struct smb_request *req = data->req.p.smb; + curl_off_t offset = data->req.offset; + struct smb_read msg; + + memset(&msg, 0, sizeof(msg)); + msg.word_count = SMB_WC_READ_ANDX; + msg.andx.command = SMB_COM_NO_ANDX_COMMAND; + msg.fid = smb_swap16(req->fid); + msg.offset = smb_swap32((unsigned int) offset); + msg.offset_high = smb_swap32((unsigned int) (offset >> 32)); + msg.min_bytes = smb_swap16(MAX_PAYLOAD_SIZE); + msg.max_bytes = smb_swap16(MAX_PAYLOAD_SIZE); + + return smb_send_message(data, SMB_COM_READ_ANDX, &msg, sizeof(msg)); +} + +static CURLcode smb_send_write(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + struct smb_conn *smbc = &conn->proto.smbc; + struct smb_write *msg; + struct smb_request *req = data->req.p.smb; + curl_off_t offset = data->req.offset; + curl_off_t upload_size = data->req.size - data->req.bytecount; + + msg = (struct smb_write *)smbc->send_buf; + if(upload_size >= MAX_PAYLOAD_SIZE - 1) /* There is one byte of padding */ + upload_size = MAX_PAYLOAD_SIZE - 1; + + memset(msg, 0, sizeof(*msg)); + msg->word_count = SMB_WC_WRITE_ANDX; + msg->andx.command = SMB_COM_NO_ANDX_COMMAND; + msg->fid = smb_swap16(req->fid); + msg->offset = smb_swap32((unsigned int) offset); + msg->offset_high = smb_swap32((unsigned int) (offset >> 32)); + msg->data_length = smb_swap16((unsigned short) upload_size); + msg->data_offset = smb_swap16(sizeof(*msg) - sizeof(unsigned int)); + msg->byte_count = smb_swap16((unsigned short) (upload_size + 1)); + + smb_format_message(data, &msg->h, SMB_COM_WRITE_ANDX, + sizeof(*msg) - sizeof(msg->h) + (size_t) upload_size); + + return smb_send(data, sizeof(*msg), (size_t) upload_size); +} + +static CURLcode smb_send_and_recv(struct Curl_easy *data, void **msg) +{ + struct connectdata *conn = data->conn; + struct smb_conn *smbc = &conn->proto.smbc; + CURLcode result; + *msg = NULL; /* if it returns early */ + + /* Check if there is data in the transfer buffer */ + if(!smbc->send_size && smbc->upload_size) { + size_t nread = smbc->upload_size > (size_t)MAX_MESSAGE_SIZE ? + (size_t)MAX_MESSAGE_SIZE : smbc->upload_size; + bool eos; + + result = Curl_client_read(data, smbc->send_buf, nread, &nread, &eos); + if(result && result != CURLE_AGAIN) + return result; + if(!nread) + return CURLE_OK; + + smbc->upload_size -= nread; + smbc->send_size = nread; + smbc->sent = 0; + } + + /* Check if there is data to send */ + if(smbc->send_size) { + result = smb_flush(data); + if(result) + return result; + } + + /* Check if there is still data to be sent */ + if(smbc->send_size || smbc->upload_size) + return CURLE_AGAIN; + + return smb_recv_message(data, msg); +} + +static CURLcode smb_connection_state(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct smb_conn *smbc = &conn->proto.smbc; + struct smb_negotiate_response *nrsp; + struct smb_header *h; + CURLcode result; + void *msg = NULL; + + if(smbc->state == SMB_CONNECTING) { +#ifdef USE_SSL + if((conn->handler->flags & PROTOPT_SSL)) { + bool ssl_done = FALSE; + result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &ssl_done); + if(result && result != CURLE_AGAIN) + return result; + if(!ssl_done) + return CURLE_OK; + } +#endif + + result = smb_send_negotiate(data); + if(result) { + connclose(conn, "SMB: failed to send negotiate message"); + return result; + } + + conn_state(data, SMB_NEGOTIATE); + } + + /* Send the previous message and check for a response */ + result = smb_send_and_recv(data, &msg); + if(result && result != CURLE_AGAIN) { + connclose(conn, "SMB: failed to communicate"); + return result; + } + + if(!msg) + return CURLE_OK; + + h = msg; + + switch(smbc->state) { + case SMB_NEGOTIATE: + if((smbc->got < sizeof(*nrsp) + sizeof(smbc->challenge) - 1) || + h->status) { + connclose(conn, "SMB: negotiation failed"); + return CURLE_COULDNT_CONNECT; + } + nrsp = msg; + memcpy(smbc->challenge, nrsp->bytes, sizeof(smbc->challenge)); + smbc->session_key = smb_swap32(nrsp->session_key); + result = smb_send_setup(data); + if(result) { + connclose(conn, "SMB: failed to send setup message"); + return result; + } + conn_state(data, SMB_SETUP); + break; + + case SMB_SETUP: + if(h->status) { + connclose(conn, "SMB: authentication failed"); + return CURLE_LOGIN_DENIED; + } + smbc->uid = smb_swap16(h->uid); + conn_state(data, SMB_CONNECTED); + *done = true; + break; + + default: + smb_pop_message(conn); + return CURLE_OK; /* ignore */ + } + + smb_pop_message(conn); + + return CURLE_OK; +} + +/* + * Convert a timestamp from the Windows world (100 nsec units from 1 Jan 1601) + * to Posix time. Cap the output to fit within a time_t. + */ +static void get_posix_time(time_t *out, curl_off_t timestamp) +{ + timestamp -= 116444736000000000; + timestamp /= 10000000; +#if SIZEOF_TIME_T < SIZEOF_CURL_OFF_T + if(timestamp > TIME_T_MAX) + *out = TIME_T_MAX; + else if(timestamp < TIME_T_MIN) + *out = TIME_T_MIN; + else +#endif + *out = (time_t) timestamp; +} + +static CURLcode smb_request_state(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct smb_request *req = data->req.p.smb; + struct smb_header *h; + struct smb_conn *smbc = &conn->proto.smbc; + enum smb_req_state next_state = SMB_DONE; + unsigned short len; + unsigned short off; + CURLcode result; + void *msg = NULL; + const struct smb_nt_create_response *smb_m; + + if(data->state.upload && (data->state.infilesize < 0)) { + failf(data, "SMB upload needs to know the size up front"); + return CURLE_SEND_ERROR; + } + + /* Start the request */ + if(req->state == SMB_REQUESTING) { + result = smb_send_tree_connect(data); + if(result) { + connclose(conn, "SMB: failed to send tree connect message"); + return result; + } + + request_state(data, SMB_TREE_CONNECT); + } + + /* Send the previous message and check for a response */ + result = smb_send_and_recv(data, &msg); + if(result && result != CURLE_AGAIN) { + connclose(conn, "SMB: failed to communicate"); + return result; + } + + if(!msg) + return CURLE_OK; + + h = msg; + + switch(req->state) { + case SMB_TREE_CONNECT: + if(h->status) { + req->result = CURLE_REMOTE_FILE_NOT_FOUND; + if(h->status == smb_swap32(SMB_ERR_NOACCESS)) + req->result = CURLE_REMOTE_ACCESS_DENIED; + break; + } + req->tid = smb_swap16(h->tid); + next_state = SMB_OPEN; + break; + + case SMB_OPEN: + if(h->status || smbc->got < sizeof(struct smb_nt_create_response)) { + req->result = CURLE_REMOTE_FILE_NOT_FOUND; + if(h->status == smb_swap32(SMB_ERR_NOACCESS)) + req->result = CURLE_REMOTE_ACCESS_DENIED; + next_state = SMB_TREE_DISCONNECT; + break; + } + smb_m = (const struct smb_nt_create_response*) msg; + req->fid = smb_swap16(smb_m->fid); + data->req.offset = 0; + if(data->state.upload) { + data->req.size = data->state.infilesize; + Curl_pgrsSetUploadSize(data, data->req.size); + next_state = SMB_UPLOAD; + } + else { + data->req.size = smb_swap64(smb_m->end_of_file); + if(data->req.size < 0) { + req->result = CURLE_WEIRD_SERVER_REPLY; + next_state = SMB_CLOSE; + } + else { + Curl_pgrsSetDownloadSize(data, data->req.size); + if(data->set.get_filetime) + get_posix_time(&data->info.filetime, smb_m->last_change_time); + next_state = SMB_DOWNLOAD; + } + } + break; + + case SMB_DOWNLOAD: + if(h->status || smbc->got < sizeof(struct smb_header) + 14) { + req->result = CURLE_RECV_ERROR; + next_state = SMB_CLOSE; + break; + } + len = Curl_read16_le(((const unsigned char *) msg) + + sizeof(struct smb_header) + 11); + off = Curl_read16_le(((const unsigned char *) msg) + + sizeof(struct smb_header) + 13); + if(len > 0) { + if(off + sizeof(unsigned int) + len > smbc->got) { + failf(data, "Invalid input packet"); + result = CURLE_RECV_ERROR; + } + else + result = Curl_client_write(data, CLIENTWRITE_BODY, + (char *)msg + off + sizeof(unsigned int), + len); + if(result) { + req->result = result; + next_state = SMB_CLOSE; + break; + } + } + data->req.offset += len; + next_state = (len < MAX_PAYLOAD_SIZE) ? SMB_CLOSE : SMB_DOWNLOAD; + break; + + case SMB_UPLOAD: + if(h->status || smbc->got < sizeof(struct smb_header) + 6) { + req->result = CURLE_UPLOAD_FAILED; + next_state = SMB_CLOSE; + break; + } + len = Curl_read16_le(((const unsigned char *) msg) + + sizeof(struct smb_header) + 5); + data->req.bytecount += len; + data->req.offset += len; + Curl_pgrsSetUploadCounter(data, data->req.bytecount); + if(data->req.bytecount >= data->req.size) + next_state = SMB_CLOSE; + else + next_state = SMB_UPLOAD; + break; + + case SMB_CLOSE: + /* We don't care if the close failed, proceed to tree disconnect anyway */ + next_state = SMB_TREE_DISCONNECT; + break; + + case SMB_TREE_DISCONNECT: + next_state = SMB_DONE; + break; + + default: + smb_pop_message(conn); + return CURLE_OK; /* ignore */ + } + + smb_pop_message(conn); + + switch(next_state) { + case SMB_OPEN: + result = smb_send_open(data); + break; + + case SMB_DOWNLOAD: + result = smb_send_read(data); + break; + + case SMB_UPLOAD: + result = smb_send_write(data); + break; + + case SMB_CLOSE: + result = smb_send_close(data); + break; + + case SMB_TREE_DISCONNECT: + result = smb_send_tree_disconnect(data); + break; + + case SMB_DONE: + result = req->result; + *done = true; + break; + + default: + break; + } + + if(result) { + connclose(conn, "SMB: failed to send message"); + return result; + } + + request_state(data, next_state); + + return CURLE_OK; +} + +static CURLcode smb_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead) +{ + struct smb_conn *smbc = &conn->proto.smbc; + (void) dead; + (void) data; + Curl_safefree(smbc->share); + Curl_safefree(smbc->domain); + Curl_safefree(smbc->recv_buf); + Curl_safefree(smbc->send_buf); + return CURLE_OK; +} + +static int smb_getsock(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *socks) +{ + (void)data; + socks[0] = conn->sock[FIRSTSOCKET]; + return GETSOCK_READSOCK(0) | GETSOCK_WRITESOCK(0); +} + +static CURLcode smb_do(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct smb_conn *smbc = &conn->proto.smbc; + + *done = FALSE; + if(smbc->share) { + return CURLE_OK; + } + return CURLE_URL_MALFORMAT; +} + +static CURLcode smb_parse_url_path(struct Curl_easy *data, + struct connectdata *conn) +{ + struct smb_request *req = data->req.p.smb; + struct smb_conn *smbc = &conn->proto.smbc; + char *path; + char *slash; + + /* URL decode the path */ + CURLcode result = Curl_urldecode(data->state.up.path, 0, &path, NULL, + REJECT_CTRL); + if(result) + return result; + + /* Parse the path for the share */ + smbc->share = strdup((*path == '/' || *path == '\\') ? path + 1 : path); + free(path); + if(!smbc->share) + return CURLE_OUT_OF_MEMORY; + + slash = strchr(smbc->share, '/'); + if(!slash) + slash = strchr(smbc->share, '\\'); + + /* The share must be present */ + if(!slash) { + Curl_safefree(smbc->share); + failf(data, "missing share in URL path for SMB"); + return CURLE_URL_MALFORMAT; + } + + /* Parse the path for the file path converting any forward slashes into + backslashes */ + *slash++ = 0; + req->path = slash; + + for(; *slash; slash++) { + if(*slash == '/') + *slash = '\\'; + } + return CURLE_OK; +} + +#endif /* CURL_DISABLE_SMB && USE_CURL_NTLM_CORE && + SIZEOF_CURL_OFF_T > 4 */ diff --git a/third_party/curl/lib/smb.h b/third_party/curl/lib/smb.h new file mode 100644 index 0000000..9ea2a8c --- /dev/null +++ b/third_party/curl/lib/smb.h @@ -0,0 +1,61 @@ +#ifndef HEADER_CURL_SMB_H +#define HEADER_CURL_SMB_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Bill Nagel , Exacq Technologies + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +enum smb_conn_state { + SMB_NOT_CONNECTED = 0, + SMB_CONNECTING, + SMB_NEGOTIATE, + SMB_SETUP, + SMB_CONNECTED +}; + +struct smb_conn { + enum smb_conn_state state; + char *user; + char *domain; + char *share; + unsigned char challenge[8]; + unsigned int session_key; + unsigned short uid; + char *recv_buf; + char *send_buf; + size_t upload_size; + size_t send_size; + size_t sent; + size_t got; +}; + +#if !defined(CURL_DISABLE_SMB) && defined(USE_CURL_NTLM_CORE) && \ + (SIZEOF_CURL_OFF_T > 4) + +extern const struct Curl_handler Curl_handler_smb; +extern const struct Curl_handler Curl_handler_smbs; + +#endif /* CURL_DISABLE_SMB && USE_CURL_NTLM_CORE && + SIZEOF_CURL_OFF_T > 4 */ + +#endif /* HEADER_CURL_SMB_H */ diff --git a/third_party/curl/lib/smtp.c b/third_party/curl/lib/smtp.c new file mode 100644 index 0000000..dd231a5 --- /dev/null +++ b/third_party/curl/lib/smtp.c @@ -0,0 +1,1947 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * RFC1870 SMTP Service Extension for Message Size + * RFC2195 CRAM-MD5 authentication + * RFC2831 DIGEST-MD5 authentication + * RFC3207 SMTP over TLS + * RFC4422 Simple Authentication and Security Layer (SASL) + * RFC4616 PLAIN authentication + * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism + * RFC4954 SMTP Authentication + * RFC5321 SMTP protocol + * RFC5890 Internationalized Domain Names for Applications (IDNA) + * RFC6531 SMTP Extension for Internationalized Email + * RFC6532 Internationalized Email Headers + * RFC6749 OAuth 2.0 Authorization Framework + * RFC8314 Use of TLS for Email Submission and Access + * Draft SMTP URL Interface + * Draft LOGIN SASL Mechanism + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_SMTP + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef __VMS +#include +#include +#endif + +#include +#include "urldata.h" +#include "sendf.h" +#include "hostip.h" +#include "progress.h" +#include "transfer.h" +#include "escape.h" +#include "http.h" /* for HTTP proxy tunnel stuff */ +#include "mime.h" +#include "socks.h" +#include "smtp.h" +#include "strtoofft.h" +#include "strcase.h" +#include "vtls/vtls.h" +#include "cfilters.h" +#include "connect.h" +#include "select.h" +#include "multiif.h" +#include "url.h" +#include "curl_gethostname.h" +#include "bufref.h" +#include "curl_sasl.h" +#include "warnless.h" +#include "idn.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* Local API functions */ +static CURLcode smtp_regular_transfer(struct Curl_easy *data, bool *done); +static CURLcode smtp_do(struct Curl_easy *data, bool *done); +static CURLcode smtp_done(struct Curl_easy *data, CURLcode status, + bool premature); +static CURLcode smtp_connect(struct Curl_easy *data, bool *done); +static CURLcode smtp_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead); +static CURLcode smtp_multi_statemach(struct Curl_easy *data, bool *done); +static int smtp_getsock(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *socks); +static CURLcode smtp_doing(struct Curl_easy *data, bool *dophase_done); +static CURLcode smtp_setup_connection(struct Curl_easy *data, + struct connectdata *conn); +static CURLcode smtp_parse_url_options(struct connectdata *conn); +static CURLcode smtp_parse_url_path(struct Curl_easy *data); +static CURLcode smtp_parse_custom_request(struct Curl_easy *data); +static CURLcode smtp_parse_address(const char *fqma, + char **address, struct hostname *host); +static CURLcode smtp_perform_auth(struct Curl_easy *data, const char *mech, + const struct bufref *initresp); +static CURLcode smtp_continue_auth(struct Curl_easy *data, const char *mech, + const struct bufref *resp); +static CURLcode smtp_cancel_auth(struct Curl_easy *data, const char *mech); +static CURLcode smtp_get_message(struct Curl_easy *data, struct bufref *out); +static CURLcode cr_eob_add(struct Curl_easy *data); + +/* + * SMTP protocol handler. + */ + +const struct Curl_handler Curl_handler_smtp = { + "smtp", /* scheme */ + smtp_setup_connection, /* setup_connection */ + smtp_do, /* do_it */ + smtp_done, /* done */ + ZERO_NULL, /* do_more */ + smtp_connect, /* connect_it */ + smtp_multi_statemach, /* connecting */ + smtp_doing, /* doing */ + smtp_getsock, /* proto_getsock */ + smtp_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + smtp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_SMTP, /* defport */ + CURLPROTO_SMTP, /* protocol */ + CURLPROTO_SMTP, /* family */ + PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY | /* flags */ + PROTOPT_URLOPTIONS +}; + +#ifdef USE_SSL +/* + * SMTPS protocol handler. + */ + +const struct Curl_handler Curl_handler_smtps = { + "smtps", /* scheme */ + smtp_setup_connection, /* setup_connection */ + smtp_do, /* do_it */ + smtp_done, /* done */ + ZERO_NULL, /* do_more */ + smtp_connect, /* connect_it */ + smtp_multi_statemach, /* connecting */ + smtp_doing, /* doing */ + smtp_getsock, /* proto_getsock */ + smtp_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + smtp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_SMTPS, /* defport */ + CURLPROTO_SMTPS, /* protocol */ + CURLPROTO_SMTP, /* family */ + PROTOPT_CLOSEACTION | PROTOPT_SSL + | PROTOPT_NOURLQUERY | PROTOPT_URLOPTIONS /* flags */ +}; +#endif + +/* SASL parameters for the smtp protocol */ +static const struct SASLproto saslsmtp = { + "smtp", /* The service name */ + smtp_perform_auth, /* Send authentication command */ + smtp_continue_auth, /* Send authentication continuation */ + smtp_cancel_auth, /* Cancel authentication */ + smtp_get_message, /* Get SASL response message */ + 512 - 8, /* Max line len - strlen("AUTH ") - 1 space - crlf */ + 334, /* Code received when continuation is expected */ + 235, /* Code to receive upon authentication success */ + SASL_AUTH_DEFAULT, /* Default mechanisms */ + SASL_FLAG_BASE64 /* Configuration flags */ +}; + +#ifdef USE_SSL +static void smtp_to_smtps(struct connectdata *conn) +{ + /* Change the connection handler */ + conn->handler = &Curl_handler_smtps; + + /* Set the connection's upgraded to TLS flag */ + conn->bits.tls_upgraded = TRUE; +} +#else +#define smtp_to_smtps(x) Curl_nop_stmt +#endif + +/*********************************************************************** + * + * smtp_endofresp() + * + * Checks for an ending SMTP status code at the start of the given string, but + * also detects various capabilities from the EHLO response including the + * supported authentication mechanisms. + */ +static bool smtp_endofresp(struct Curl_easy *data, struct connectdata *conn, + char *line, size_t len, int *resp) +{ + struct smtp_conn *smtpc = &conn->proto.smtpc; + bool result = FALSE; + (void)data; + + /* Nothing for us */ + if(len < 4 || !ISDIGIT(line[0]) || !ISDIGIT(line[1]) || !ISDIGIT(line[2])) + return FALSE; + + /* Do we have a command response? This should be the response code followed + by a space and optionally some text as per RFC-5321 and as outlined in + Section 4. Examples of RFC-4954 but some email servers ignore this and + only send the response code instead as per Section 4.2. */ + if(line[3] == ' ' || len == 5) { + char tmpline[6]; + + result = TRUE; + memset(tmpline, '\0', sizeof(tmpline)); + memcpy(tmpline, line, (len == 5 ? 5 : 3)); + *resp = curlx_sltosi(strtol(tmpline, NULL, 10)); + + /* Make sure real server never sends internal value */ + if(*resp == 1) + *resp = 0; + } + /* Do we have a multiline (continuation) response? */ + else if(line[3] == '-' && + (smtpc->state == SMTP_EHLO || smtpc->state == SMTP_COMMAND)) { + result = TRUE; + *resp = 1; /* Internal response code */ + } + + return result; +} + +/*********************************************************************** + * + * smtp_get_message() + * + * Gets the authentication message from the response buffer. + */ +static CURLcode smtp_get_message(struct Curl_easy *data, struct bufref *out) +{ + char *message = Curl_dyn_ptr(&data->conn->proto.smtpc.pp.recvbuf); + size_t len = data->conn->proto.smtpc.pp.nfinal; + + if(len > 4) { + /* Find the start of the message */ + len -= 4; + for(message += 4; *message == ' ' || *message == '\t'; message++, len--) + ; + + /* Find the end of the message */ + while(len--) + if(message[len] != '\r' && message[len] != '\n' && message[len] != ' ' && + message[len] != '\t') + break; + + /* Terminate the message */ + message[++len] = '\0'; + Curl_bufref_set(out, message, len, NULL); + } + else + /* junk input => zero length output */ + Curl_bufref_set(out, "", 0, NULL); + + return CURLE_OK; +} + +/*********************************************************************** + * + * smtp_state() + * + * This is the ONLY way to change SMTP state! + */ +static void smtp_state(struct Curl_easy *data, smtpstate newstate) +{ + struct smtp_conn *smtpc = &data->conn->proto.smtpc; +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + /* for debug purposes */ + static const char * const names[] = { + "STOP", + "SERVERGREET", + "EHLO", + "HELO", + "STARTTLS", + "UPGRADETLS", + "AUTH", + "COMMAND", + "MAIL", + "RCPT", + "DATA", + "POSTDATA", + "QUIT", + /* LAST */ + }; + + if(smtpc->state != newstate) + infof(data, "SMTP %p state change from %s to %s", + (void *)smtpc, names[smtpc->state], names[newstate]); +#endif + + smtpc->state = newstate; +} + +/*********************************************************************** + * + * smtp_perform_ehlo() + * + * Sends the EHLO command to not only initialise communication with the ESMTP + * server but to also obtain a list of server side supported capabilities. + */ +static CURLcode smtp_perform_ehlo(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct smtp_conn *smtpc = &conn->proto.smtpc; + + smtpc->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanism yet */ + smtpc->sasl.authused = SASL_AUTH_NONE; /* Clear the authentication mechanism + used for esmtp connections */ + smtpc->tls_supported = FALSE; /* Clear the TLS capability */ + smtpc->auth_supported = FALSE; /* Clear the AUTH capability */ + + /* Send the EHLO command */ + result = Curl_pp_sendf(data, &smtpc->pp, "EHLO %s", smtpc->domain); + + if(!result) + smtp_state(data, SMTP_EHLO); + + return result; +} + +/*********************************************************************** + * + * smtp_perform_helo() + * + * Sends the HELO command to initialise communication with the SMTP server. + */ +static CURLcode smtp_perform_helo(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + struct smtp_conn *smtpc = &conn->proto.smtpc; + + smtpc->sasl.authused = SASL_AUTH_NONE; /* No authentication mechanism used + in smtp connections */ + + /* Send the HELO command */ + result = Curl_pp_sendf(data, &smtpc->pp, "HELO %s", smtpc->domain); + + if(!result) + smtp_state(data, SMTP_HELO); + + return result; +} + +/*********************************************************************** + * + * smtp_perform_starttls() + * + * Sends the STLS command to start the upgrade to TLS. + */ +static CURLcode smtp_perform_starttls(struct Curl_easy *data, + struct connectdata *conn) +{ + /* Send the STARTTLS command */ + CURLcode result = Curl_pp_sendf(data, &conn->proto.smtpc.pp, + "%s", "STARTTLS"); + + if(!result) + smtp_state(data, SMTP_STARTTLS); + + return result; +} + +/*********************************************************************** + * + * smtp_perform_upgrade_tls() + * + * Performs the upgrade to TLS. + */ +static CURLcode smtp_perform_upgrade_tls(struct Curl_easy *data) +{ + /* Start the SSL connection */ + struct connectdata *conn = data->conn; + struct smtp_conn *smtpc = &conn->proto.smtpc; + CURLcode result; + bool ssldone = FALSE; + + if(!Curl_conn_is_ssl(conn, FIRSTSOCKET)) { + result = Curl_ssl_cfilter_add(data, conn, FIRSTSOCKET); + if(result) + goto out; + } + + result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &ssldone); + if(!result) { + smtpc->ssldone = ssldone; + if(smtpc->state != SMTP_UPGRADETLS) + smtp_state(data, SMTP_UPGRADETLS); + + if(smtpc->ssldone) { + smtp_to_smtps(conn); + result = smtp_perform_ehlo(data); + } + } +out: + return result; +} + +/*********************************************************************** + * + * smtp_perform_auth() + * + * Sends an AUTH command allowing the client to login with the given SASL + * authentication mechanism. + */ +static CURLcode smtp_perform_auth(struct Curl_easy *data, + const char *mech, + const struct bufref *initresp) +{ + CURLcode result = CURLE_OK; + struct smtp_conn *smtpc = &data->conn->proto.smtpc; + const char *ir = (const char *) Curl_bufref_ptr(initresp); + + if(ir) { /* AUTH ... */ + /* Send the AUTH command with the initial response */ + result = Curl_pp_sendf(data, &smtpc->pp, "AUTH %s %s", mech, ir); + } + else { + /* Send the AUTH command */ + result = Curl_pp_sendf(data, &smtpc->pp, "AUTH %s", mech); + } + + return result; +} + +/*********************************************************************** + * + * smtp_continue_auth() + * + * Sends SASL continuation data. + */ +static CURLcode smtp_continue_auth(struct Curl_easy *data, + const char *mech, + const struct bufref *resp) +{ + struct smtp_conn *smtpc = &data->conn->proto.smtpc; + + (void)mech; + + return Curl_pp_sendf(data, &smtpc->pp, + "%s", (const char *) Curl_bufref_ptr(resp)); +} + +/*********************************************************************** + * + * smtp_cancel_auth() + * + * Sends SASL cancellation. + */ +static CURLcode smtp_cancel_auth(struct Curl_easy *data, const char *mech) +{ + struct smtp_conn *smtpc = &data->conn->proto.smtpc; + + (void)mech; + + return Curl_pp_sendf(data, &smtpc->pp, "*"); +} + +/*********************************************************************** + * + * smtp_perform_authentication() + * + * Initiates the authentication sequence, with the appropriate SASL + * authentication mechanism. + */ +static CURLcode smtp_perform_authentication(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct smtp_conn *smtpc = &conn->proto.smtpc; + saslprogress progress; + + /* Check we have enough data to authenticate with, and the + server supports authentication, and end the connect phase if not */ + if(!smtpc->auth_supported || + !Curl_sasl_can_authenticate(&smtpc->sasl, data)) { + smtp_state(data, SMTP_STOP); + return result; + } + + /* Calculate the SASL login details */ + result = Curl_sasl_start(&smtpc->sasl, data, FALSE, &progress); + + if(!result) { + if(progress == SASL_INPROGRESS) + smtp_state(data, SMTP_AUTH); + else { + /* Other mechanisms not supported */ + infof(data, "No known authentication mechanisms supported"); + result = CURLE_LOGIN_DENIED; + } + } + + return result; +} + +/*********************************************************************** + * + * smtp_perform_command() + * + * Sends a SMTP based command. + */ +static CURLcode smtp_perform_command(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct SMTP *smtp = data->req.p.smtp; + + if(smtp->rcpt) { + /* We notify the server we are sending UTF-8 data if a) it supports the + SMTPUTF8 extension and b) The mailbox contains UTF-8 characters, in + either the local address or host name parts. This is regardless of + whether the host name is encoded using IDN ACE */ + bool utf8 = FALSE; + + if((!smtp->custom) || (!smtp->custom[0])) { + char *address = NULL; + struct hostname host = { NULL, NULL, NULL, NULL }; + + /* Parse the mailbox to verify into the local address and host name + parts, converting the host name to an IDN A-label if necessary */ + result = smtp_parse_address(smtp->rcpt->data, + &address, &host); + if(result) + return result; + + /* Establish whether we should report SMTPUTF8 to the server for this + mailbox as per RFC-6531 sect. 3.1 point 6 */ + utf8 = (conn->proto.smtpc.utf8_supported) && + ((host.encalloc) || (!Curl_is_ASCII_name(address)) || + (!Curl_is_ASCII_name(host.name))); + + /* Send the VRFY command (Note: The host name part may be absent when the + host is a local system) */ + result = Curl_pp_sendf(data, &conn->proto.smtpc.pp, "VRFY %s%s%s%s", + address, + host.name ? "@" : "", + host.name ? host.name : "", + utf8 ? " SMTPUTF8" : ""); + + Curl_free_idnconverted_hostname(&host); + free(address); + } + else { + /* Establish whether we should report that we support SMTPUTF8 for EXPN + commands to the server as per RFC-6531 sect. 3.1 point 6 */ + utf8 = (conn->proto.smtpc.utf8_supported) && + (!strcmp(smtp->custom, "EXPN")); + + /* Send the custom recipient based command such as the EXPN command */ + result = Curl_pp_sendf(data, &conn->proto.smtpc.pp, + "%s %s%s", smtp->custom, + smtp->rcpt->data, + utf8 ? " SMTPUTF8" : ""); + } + } + else + /* Send the non-recipient based command such as HELP */ + result = Curl_pp_sendf(data, &conn->proto.smtpc.pp, "%s", + smtp->custom && smtp->custom[0] != '\0' ? + smtp->custom : "HELP"); + + if(!result) + smtp_state(data, SMTP_COMMAND); + + return result; +} + +/*********************************************************************** + * + * smtp_perform_mail() + * + * Sends an MAIL command to initiate the upload of a message. + */ +static CURLcode smtp_perform_mail(struct Curl_easy *data) +{ + char *from = NULL; + char *auth = NULL; + char *size = NULL; + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + /* We notify the server we are sending UTF-8 data if a) it supports the + SMTPUTF8 extension and b) The mailbox contains UTF-8 characters, in + either the local address or host name parts. This is regardless of + whether the host name is encoded using IDN ACE */ + bool utf8 = FALSE; + + /* Calculate the FROM parameter */ + if(data->set.str[STRING_MAIL_FROM]) { + char *address = NULL; + struct hostname host = { NULL, NULL, NULL, NULL }; + + /* Parse the FROM mailbox into the local address and host name parts, + converting the host name to an IDN A-label if necessary */ + result = smtp_parse_address(data->set.str[STRING_MAIL_FROM], + &address, &host); + if(result) + goto out; + + /* Establish whether we should report SMTPUTF8 to the server for this + mailbox as per RFC-6531 sect. 3.1 point 4 and sect. 3.4 */ + utf8 = (conn->proto.smtpc.utf8_supported) && + ((host.encalloc) || (!Curl_is_ASCII_name(address)) || + (!Curl_is_ASCII_name(host.name))); + + if(host.name) { + from = aprintf("<%s@%s>", address, host.name); + + Curl_free_idnconverted_hostname(&host); + } + else + /* An invalid mailbox was provided but we'll simply let the server worry + about that and reply with a 501 error */ + from = aprintf("<%s>", address); + + free(address); + } + else + /* Null reverse-path, RFC-5321, sect. 3.6.3 */ + from = strdup("<>"); + + if(!from) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + /* Calculate the optional AUTH parameter */ + if(data->set.str[STRING_MAIL_AUTH] && conn->proto.smtpc.sasl.authused) { + if(data->set.str[STRING_MAIL_AUTH][0] != '\0') { + char *address = NULL; + struct hostname host = { NULL, NULL, NULL, NULL }; + + /* Parse the AUTH mailbox into the local address and host name parts, + converting the host name to an IDN A-label if necessary */ + result = smtp_parse_address(data->set.str[STRING_MAIL_AUTH], + &address, &host); + if(result) + goto out; + + /* Establish whether we should report SMTPUTF8 to the server for this + mailbox as per RFC-6531 sect. 3.1 point 4 and sect. 3.4 */ + if((!utf8) && (conn->proto.smtpc.utf8_supported) && + ((host.encalloc) || (!Curl_is_ASCII_name(address)) || + (!Curl_is_ASCII_name(host.name)))) + utf8 = TRUE; + + if(host.name) { + auth = aprintf("<%s@%s>", address, host.name); + + Curl_free_idnconverted_hostname(&host); + } + else + /* An invalid mailbox was provided but we'll simply let the server + worry about it */ + auth = aprintf("<%s>", address); + free(address); + } + else + /* Empty AUTH, RFC-2554, sect. 5 */ + auth = strdup("<>"); + + if(!auth) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + +#ifndef CURL_DISABLE_MIME + /* Prepare the mime data if some. */ + if(data->set.mimepost.kind != MIMEKIND_NONE) { + /* Use the whole structure as data. */ + data->set.mimepost.flags &= ~MIME_BODY_ONLY; + + /* Add external headers and mime version. */ + curl_mime_headers(&data->set.mimepost, data->set.headers, 0); + result = Curl_mime_prepare_headers(data, &data->set.mimepost, NULL, + NULL, MIMESTRATEGY_MAIL); + + if(!result) + if(!Curl_checkheaders(data, STRCONST("Mime-Version"))) + result = Curl_mime_add_header(&data->set.mimepost.curlheaders, + "Mime-Version: 1.0"); + + if(!result) + result = Curl_creader_set_mime(data, &data->set.mimepost); + if(result) + goto out; + data->state.infilesize = Curl_creader_total_length(data); + } + else +#endif + { + result = Curl_creader_set_fread(data, data->state.infilesize); + if(result) + goto out; + } + + /* Calculate the optional SIZE parameter */ + if(conn->proto.smtpc.size_supported && data->state.infilesize > 0) { + size = aprintf("%" CURL_FORMAT_CURL_OFF_T, data->state.infilesize); + + if(!size) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + + /* If the mailboxes in the FROM and AUTH parameters don't include a UTF-8 + based address then quickly scan through the recipient list and check if + any there do, as we need to correctly identify our support for SMTPUTF8 + in the envelope, as per RFC-6531 sect. 3.4 */ + if(conn->proto.smtpc.utf8_supported && !utf8) { + struct SMTP *smtp = data->req.p.smtp; + struct curl_slist *rcpt = smtp->rcpt; + + while(rcpt && !utf8) { + /* Does the host name contain non-ASCII characters? */ + if(!Curl_is_ASCII_name(rcpt->data)) + utf8 = TRUE; + + rcpt = rcpt->next; + } + } + + /* Add the client reader doing STMP EOB escaping */ + result = cr_eob_add(data); + if(result) + goto out; + + /* Send the MAIL command */ + result = Curl_pp_sendf(data, &conn->proto.smtpc.pp, + "MAIL FROM:%s%s%s%s%s%s", + from, /* Mandatory */ + auth ? " AUTH=" : "", /* Optional on AUTH support */ + auth ? auth : "", /* */ + size ? " SIZE=" : "", /* Optional on SIZE support */ + size ? size : "", /* */ + utf8 ? " SMTPUTF8" /* Internationalised mailbox */ + : ""); /* included in our envelope */ + +out: + free(from); + free(auth); + free(size); + + if(!result) + smtp_state(data, SMTP_MAIL); + + return result; +} + +/*********************************************************************** + * + * smtp_perform_rcpt_to() + * + * Sends a RCPT TO command for a given recipient as part of the message upload + * process. + */ +static CURLcode smtp_perform_rcpt_to(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct SMTP *smtp = data->req.p.smtp; + char *address = NULL; + struct hostname host = { NULL, NULL, NULL, NULL }; + + /* Parse the recipient mailbox into the local address and host name parts, + converting the host name to an IDN A-label if necessary */ + result = smtp_parse_address(smtp->rcpt->data, + &address, &host); + if(result) + return result; + + /* Send the RCPT TO command */ + if(host.name) + result = Curl_pp_sendf(data, &conn->proto.smtpc.pp, "RCPT TO:<%s@%s>", + address, host.name); + else + /* An invalid mailbox was provided but we'll simply let the server worry + about that and reply with a 501 error */ + result = Curl_pp_sendf(data, &conn->proto.smtpc.pp, "RCPT TO:<%s>", + address); + + Curl_free_idnconverted_hostname(&host); + free(address); + + if(!result) + smtp_state(data, SMTP_RCPT); + + return result; +} + +/*********************************************************************** + * + * smtp_perform_quit() + * + * Performs the quit action prior to sclose() being called. + */ +static CURLcode smtp_perform_quit(struct Curl_easy *data, + struct connectdata *conn) +{ + /* Send the QUIT command */ + CURLcode result = Curl_pp_sendf(data, &conn->proto.smtpc.pp, "%s", "QUIT"); + + if(!result) + smtp_state(data, SMTP_QUIT); + + return result; +} + +/* For the initial server greeting */ +static CURLcode smtp_state_servergreet_resp(struct Curl_easy *data, + int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + (void)instate; /* no use for this yet */ + + if(smtpcode/100 != 2) { + failf(data, "Got unexpected smtp-server response: %d", smtpcode); + result = CURLE_WEIRD_SERVER_REPLY; + } + else + result = smtp_perform_ehlo(data); + + return result; +} + +/* For STARTTLS responses */ +static CURLcode smtp_state_starttls_resp(struct Curl_easy *data, + int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + (void)instate; /* no use for this yet */ + + /* Pipelining in response is forbidden. */ + if(data->conn->proto.smtpc.pp.overflow) + return CURLE_WEIRD_SERVER_REPLY; + + if(smtpcode != 220) { + if(data->set.use_ssl != CURLUSESSL_TRY) { + failf(data, "STARTTLS denied, code %d", smtpcode); + result = CURLE_USE_SSL_FAILED; + } + else + result = smtp_perform_authentication(data); + } + else + result = smtp_perform_upgrade_tls(data); + + return result; +} + +/* For EHLO responses */ +static CURLcode smtp_state_ehlo_resp(struct Curl_easy *data, + struct connectdata *conn, int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + struct smtp_conn *smtpc = &conn->proto.smtpc; + const char *line = Curl_dyn_ptr(&smtpc->pp.recvbuf); + size_t len = smtpc->pp.nfinal; + + (void)instate; /* no use for this yet */ + + if(smtpcode/100 != 2 && smtpcode != 1) { + if(data->set.use_ssl <= CURLUSESSL_TRY + || Curl_conn_is_ssl(conn, FIRSTSOCKET)) + result = smtp_perform_helo(data, conn); + else { + failf(data, "Remote access denied: %d", smtpcode); + result = CURLE_REMOTE_ACCESS_DENIED; + } + } + else if(len >= 4) { + line += 4; + len -= 4; + + /* Does the server support the STARTTLS capability? */ + if(len >= 8 && !memcmp(line, "STARTTLS", 8)) + smtpc->tls_supported = TRUE; + + /* Does the server support the SIZE capability? */ + else if(len >= 4 && !memcmp(line, "SIZE", 4)) + smtpc->size_supported = TRUE; + + /* Does the server support the UTF-8 capability? */ + else if(len >= 8 && !memcmp(line, "SMTPUTF8", 8)) + smtpc->utf8_supported = TRUE; + + /* Does the server support authentication? */ + else if(len >= 5 && !memcmp(line, "AUTH ", 5)) { + smtpc->auth_supported = TRUE; + + /* Advance past the AUTH keyword */ + line += 5; + len -= 5; + + /* Loop through the data line */ + for(;;) { + size_t llen; + size_t wordlen; + unsigned short mechbit; + + while(len && + (*line == ' ' || *line == '\t' || + *line == '\r' || *line == '\n')) { + + line++; + len--; + } + + if(!len) + break; + + /* Extract the word */ + for(wordlen = 0; wordlen < len && line[wordlen] != ' ' && + line[wordlen] != '\t' && line[wordlen] != '\r' && + line[wordlen] != '\n';) + wordlen++; + + /* Test the word for a matching authentication mechanism */ + mechbit = Curl_sasl_decode_mech(line, wordlen, &llen); + if(mechbit && llen == wordlen) + smtpc->sasl.authmechs |= mechbit; + + line += wordlen; + len -= wordlen; + } + } + + if(smtpcode != 1) { + if(data->set.use_ssl && !Curl_conn_is_ssl(conn, FIRSTSOCKET)) { + /* We don't have a SSL/TLS connection yet, but SSL is requested */ + if(smtpc->tls_supported) + /* Switch to TLS connection now */ + result = smtp_perform_starttls(data, conn); + else if(data->set.use_ssl == CURLUSESSL_TRY) + /* Fallback and carry on with authentication */ + result = smtp_perform_authentication(data); + else { + failf(data, "STARTTLS not supported."); + result = CURLE_USE_SSL_FAILED; + } + } + else + result = smtp_perform_authentication(data); + } + } + else { + failf(data, "Unexpectedly short EHLO response"); + result = CURLE_WEIRD_SERVER_REPLY; + } + + return result; +} + +/* For HELO responses */ +static CURLcode smtp_state_helo_resp(struct Curl_easy *data, int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + (void)instate; /* no use for this yet */ + + if(smtpcode/100 != 2) { + failf(data, "Remote access denied: %d", smtpcode); + result = CURLE_REMOTE_ACCESS_DENIED; + } + else + /* End of connect phase */ + smtp_state(data, SMTP_STOP); + + return result; +} + +/* For SASL authentication responses */ +static CURLcode smtp_state_auth_resp(struct Curl_easy *data, + int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct smtp_conn *smtpc = &conn->proto.smtpc; + saslprogress progress; + + (void)instate; /* no use for this yet */ + + result = Curl_sasl_continue(&smtpc->sasl, data, smtpcode, &progress); + if(!result) + switch(progress) { + case SASL_DONE: + smtp_state(data, SMTP_STOP); /* Authenticated */ + break; + case SASL_IDLE: /* No mechanism left after cancellation */ + failf(data, "Authentication cancelled"); + result = CURLE_LOGIN_DENIED; + break; + default: + break; + } + + return result; +} + +/* For command responses */ +static CURLcode smtp_state_command_resp(struct Curl_easy *data, int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + struct SMTP *smtp = data->req.p.smtp; + char *line = Curl_dyn_ptr(&data->conn->proto.smtpc.pp.recvbuf); + size_t len = data->conn->proto.smtpc.pp.nfinal; + + (void)instate; /* no use for this yet */ + + if((smtp->rcpt && smtpcode/100 != 2 && smtpcode != 553 && smtpcode != 1) || + (!smtp->rcpt && smtpcode/100 != 2 && smtpcode != 1)) { + failf(data, "Command failed: %d", smtpcode); + result = CURLE_WEIRD_SERVER_REPLY; + } + else { + if(!data->req.no_body) + result = Curl_client_write(data, CLIENTWRITE_BODY, line, len); + + if(smtpcode != 1) { + if(smtp->rcpt) { + smtp->rcpt = smtp->rcpt->next; + + if(smtp->rcpt) { + /* Send the next command */ + result = smtp_perform_command(data); + } + else + /* End of DO phase */ + smtp_state(data, SMTP_STOP); + } + else + /* End of DO phase */ + smtp_state(data, SMTP_STOP); + } + } + + return result; +} + +/* For MAIL responses */ +static CURLcode smtp_state_mail_resp(struct Curl_easy *data, int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + (void)instate; /* no use for this yet */ + + if(smtpcode/100 != 2) { + failf(data, "MAIL failed: %d", smtpcode); + result = CURLE_SEND_ERROR; + } + else + /* Start the RCPT TO command */ + result = smtp_perform_rcpt_to(data); + + return result; +} + +/* For RCPT responses */ +static CURLcode smtp_state_rcpt_resp(struct Curl_easy *data, + struct connectdata *conn, int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + struct SMTP *smtp = data->req.p.smtp; + bool is_smtp_err = FALSE; + bool is_smtp_blocking_err = FALSE; + + (void)instate; /* no use for this yet */ + + is_smtp_err = (smtpcode/100 != 2) ? TRUE : FALSE; + + /* If there's multiple RCPT TO to be issued, it's possible to ignore errors + and proceed with only the valid addresses. */ + is_smtp_blocking_err = + (is_smtp_err && !data->set.mail_rcpt_allowfails) ? TRUE : FALSE; + + if(is_smtp_err) { + /* Remembering the last failure which we can report if all "RCPT TO" have + failed and we cannot proceed. */ + smtp->rcpt_last_error = smtpcode; + + if(is_smtp_blocking_err) { + failf(data, "RCPT failed: %d", smtpcode); + result = CURLE_SEND_ERROR; + } + } + else { + /* Some RCPT TO commands have succeeded. */ + smtp->rcpt_had_ok = TRUE; + } + + if(!is_smtp_blocking_err) { + smtp->rcpt = smtp->rcpt->next; + + if(smtp->rcpt) + /* Send the next RCPT TO command */ + result = smtp_perform_rcpt_to(data); + else { + /* We weren't able to issue a successful RCPT TO command while going + over recipients (potentially multiple). Sending back last error. */ + if(!smtp->rcpt_had_ok) { + failf(data, "RCPT failed: %d (last error)", smtp->rcpt_last_error); + result = CURLE_SEND_ERROR; + } + else { + /* Send the DATA command */ + result = Curl_pp_sendf(data, &conn->proto.smtpc.pp, "%s", "DATA"); + + if(!result) + smtp_state(data, SMTP_DATA); + } + } + } + + return result; +} + +/* For DATA response */ +static CURLcode smtp_state_data_resp(struct Curl_easy *data, int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + (void)instate; /* no use for this yet */ + + if(smtpcode != 354) { + failf(data, "DATA failed: %d", smtpcode); + result = CURLE_SEND_ERROR; + } + else { + /* Set the progress upload size */ + Curl_pgrsSetUploadSize(data, data->state.infilesize); + + /* SMTP upload */ + Curl_xfer_setup(data, -1, -1, FALSE, FIRSTSOCKET); + + /* End of DO phase */ + smtp_state(data, SMTP_STOP); + } + + return result; +} + +/* For POSTDATA responses, which are received after the entire DATA + part has been sent to the server */ +static CURLcode smtp_state_postdata_resp(struct Curl_easy *data, + int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + + (void)instate; /* no use for this yet */ + + if(smtpcode != 250) + result = CURLE_WEIRD_SERVER_REPLY; + + /* End of DONE phase */ + smtp_state(data, SMTP_STOP); + + return result; +} + +static CURLcode smtp_statemachine(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + int smtpcode; + struct smtp_conn *smtpc = &conn->proto.smtpc; + struct pingpong *pp = &smtpc->pp; + size_t nread = 0; + + /* Busy upgrading the connection; right now all I/O is SSL/TLS, not SMTP */ + if(smtpc->state == SMTP_UPGRADETLS) + return smtp_perform_upgrade_tls(data); + + /* Flush any data that needs to be sent */ + if(pp->sendleft) + return Curl_pp_flushsend(data, pp); + + do { + /* Read the response from the server */ + result = Curl_pp_readresp(data, FIRSTSOCKET, pp, &smtpcode, &nread); + if(result) + return result; + + /* Store the latest response for later retrieval if necessary */ + if(smtpc->state != SMTP_QUIT && smtpcode != 1) + data->info.httpcode = smtpcode; + + if(!smtpcode) + break; + + /* We have now received a full SMTP server response */ + switch(smtpc->state) { + case SMTP_SERVERGREET: + result = smtp_state_servergreet_resp(data, smtpcode, smtpc->state); + break; + + case SMTP_EHLO: + result = smtp_state_ehlo_resp(data, conn, smtpcode, smtpc->state); + break; + + case SMTP_HELO: + result = smtp_state_helo_resp(data, smtpcode, smtpc->state); + break; + + case SMTP_STARTTLS: + result = smtp_state_starttls_resp(data, smtpcode, smtpc->state); + break; + + case SMTP_AUTH: + result = smtp_state_auth_resp(data, smtpcode, smtpc->state); + break; + + case SMTP_COMMAND: + result = smtp_state_command_resp(data, smtpcode, smtpc->state); + break; + + case SMTP_MAIL: + result = smtp_state_mail_resp(data, smtpcode, smtpc->state); + break; + + case SMTP_RCPT: + result = smtp_state_rcpt_resp(data, conn, smtpcode, smtpc->state); + break; + + case SMTP_DATA: + result = smtp_state_data_resp(data, smtpcode, smtpc->state); + break; + + case SMTP_POSTDATA: + result = smtp_state_postdata_resp(data, smtpcode, smtpc->state); + break; + + case SMTP_QUIT: + default: + /* internal error */ + smtp_state(data, SMTP_STOP); + break; + } + } while(!result && smtpc->state != SMTP_STOP && Curl_pp_moredata(pp)); + + return result; +} + +/* Called repeatedly until done from multi.c */ +static CURLcode smtp_multi_statemach(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct smtp_conn *smtpc = &conn->proto.smtpc; + + if((conn->handler->flags & PROTOPT_SSL) && !smtpc->ssldone) { + bool ssldone = FALSE; + result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &ssldone); + smtpc->ssldone = ssldone; + if(result || !smtpc->ssldone) + return result; + } + + result = Curl_pp_statemach(data, &smtpc->pp, FALSE, FALSE); + *done = (smtpc->state == SMTP_STOP) ? TRUE : FALSE; + + return result; +} + +static CURLcode smtp_block_statemach(struct Curl_easy *data, + struct connectdata *conn, + bool disconnecting) +{ + CURLcode result = CURLE_OK; + struct smtp_conn *smtpc = &conn->proto.smtpc; + + while(smtpc->state != SMTP_STOP && !result) + result = Curl_pp_statemach(data, &smtpc->pp, TRUE, disconnecting); + + return result; +} + +/* Allocate and initialize the SMTP struct for the current Curl_easy if + required */ +static CURLcode smtp_init(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct SMTP *smtp; + + smtp = data->req.p.smtp = calloc(1, sizeof(struct SMTP)); + if(!smtp) + result = CURLE_OUT_OF_MEMORY; + + return result; +} + +/* For the SMTP "protocol connect" and "doing" phases only */ +static int smtp_getsock(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *socks) +{ + return Curl_pp_getsock(data, &conn->proto.smtpc.pp, socks); +} + +/*********************************************************************** + * + * smtp_connect() + * + * This function should do everything that is to be considered a part of + * the connection phase. + * + * The variable pointed to by 'done' will be TRUE if the protocol-layer + * connect phase is done when this function returns, or FALSE if not. + */ +static CURLcode smtp_connect(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct smtp_conn *smtpc = &conn->proto.smtpc; + struct pingpong *pp = &smtpc->pp; + + *done = FALSE; /* default to not done yet */ + + /* We always support persistent connections in SMTP */ + connkeep(conn, "SMTP default"); + + PINGPONG_SETUP(pp, smtp_statemachine, smtp_endofresp); + + /* Initialize the SASL storage */ + Curl_sasl_init(&smtpc->sasl, data, &saslsmtp); + + /* Initialise the pingpong layer */ + Curl_pp_init(pp); + + /* Parse the URL options */ + result = smtp_parse_url_options(conn); + if(result) + return result; + + /* Parse the URL path */ + result = smtp_parse_url_path(data); + if(result) + return result; + + /* Start off waiting for the server greeting response */ + smtp_state(data, SMTP_SERVERGREET); + + result = smtp_multi_statemach(data, done); + + return result; +} + +/*********************************************************************** + * + * smtp_done() + * + * The DONE function. This does what needs to be done after a single DO has + * performed. + * + * Input argument is already checked for validity. + */ +static CURLcode smtp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct SMTP *smtp = data->req.p.smtp; + + (void)premature; + + if(!smtp) + return CURLE_OK; + + /* Cleanup our per-request based variables */ + Curl_safefree(smtp->custom); + + if(status) { + connclose(conn, "SMTP done with bad status"); /* marked for closure */ + result = status; /* use the already set error code */ + } + else if(!data->set.connect_only && data->set.mail_rcpt && + (data->state.upload || IS_MIME_POST(data))) { + + smtp_state(data, SMTP_POSTDATA); + + /* Run the state-machine */ + result = smtp_block_statemach(data, conn, FALSE); + } + + /* Clear the transfer mode for the next request */ + smtp->transfer = PPTRANSFER_BODY; + + return result; +} + +/*********************************************************************** + * + * smtp_perform() + * + * This is the actual DO function for SMTP. Transfer a mail, send a command + * or get some data according to the options previously setup. + */ +static CURLcode smtp_perform(struct Curl_easy *data, bool *connected, + bool *dophase_done) +{ + /* This is SMTP and no proxy */ + CURLcode result = CURLE_OK; + struct SMTP *smtp = data->req.p.smtp; + + DEBUGF(infof(data, "DO phase starts")); + + if(data->req.no_body) { + /* Requested no body means no transfer */ + smtp->transfer = PPTRANSFER_INFO; + } + + *dophase_done = FALSE; /* not done yet */ + + /* Store the first recipient (or NULL if not specified) */ + smtp->rcpt = data->set.mail_rcpt; + + /* Track of whether we've successfully sent at least one RCPT TO command */ + smtp->rcpt_had_ok = FALSE; + + /* Track of the last error we've received by sending RCPT TO command */ + smtp->rcpt_last_error = 0; + + /* Initial data character is the first character in line: it is implicitly + preceded by a virtual CRLF. */ + smtp->trailing_crlf = TRUE; + smtp->eob = 2; + + /* Start the first command in the DO phase */ + if((data->state.upload || IS_MIME_POST(data)) && data->set.mail_rcpt) + /* MAIL transfer */ + result = smtp_perform_mail(data); + else + /* SMTP based command (VRFY, EXPN, NOOP, RSET or HELP) */ + result = smtp_perform_command(data); + + if(result) + return result; + + /* Run the state-machine */ + result = smtp_multi_statemach(data, dophase_done); + + *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET); + + if(*dophase_done) + DEBUGF(infof(data, "DO phase is complete")); + + return result; +} + +/*********************************************************************** + * + * smtp_do() + * + * This function is registered as 'curl_do' function. It decodes the path + * parts etc as a wrapper to the actual DO function (smtp_perform). + * + * The input argument is already checked for validity. + */ +static CURLcode smtp_do(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + *done = FALSE; /* default to false */ + + /* Parse the custom request */ + result = smtp_parse_custom_request(data); + if(result) + return result; + + result = smtp_regular_transfer(data, done); + + return result; +} + +/*********************************************************************** + * + * smtp_disconnect() + * + * Disconnect from an SMTP server. Cleanup protocol-specific per-connection + * resources. BLOCKING. + */ +static CURLcode smtp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + struct smtp_conn *smtpc = &conn->proto.smtpc; + (void)data; + + /* We cannot send quit unconditionally. If this connection is stale or + bad in any way, sending quit and waiting around here will make the + disconnect wait in vain and cause more problems than we need to. */ + + if(!dead_connection && conn->bits.protoconnstart) { + if(!smtp_perform_quit(data, conn)) + (void)smtp_block_statemach(data, conn, TRUE); /* ignore errors on QUIT */ + } + + /* Disconnect from the server */ + Curl_pp_disconnect(&smtpc->pp); + + /* Cleanup the SASL module */ + Curl_sasl_cleanup(conn, smtpc->sasl.authused); + + /* Cleanup our connection based variables */ + Curl_safefree(smtpc->domain); + + return CURLE_OK; +} + +/* Call this when the DO phase has completed */ +static CURLcode smtp_dophase_done(struct Curl_easy *data, bool connected) +{ + struct SMTP *smtp = data->req.p.smtp; + + (void)connected; + + if(smtp->transfer != PPTRANSFER_BODY) + /* no data to transfer */ + Curl_xfer_setup(data, -1, -1, FALSE, -1); + + return CURLE_OK; +} + +/* Called from multi.c while DOing */ +static CURLcode smtp_doing(struct Curl_easy *data, bool *dophase_done) +{ + CURLcode result = smtp_multi_statemach(data, dophase_done); + + if(result) + DEBUGF(infof(data, "DO phase failed")); + else if(*dophase_done) { + result = smtp_dophase_done(data, FALSE /* not connected */); + + DEBUGF(infof(data, "DO phase is complete")); + } + + return result; +} + +/*********************************************************************** + * + * smtp_regular_transfer() + * + * The input argument is already checked for validity. + * + * Performs all commands done before a regular transfer between a local and a + * remote host. + */ +static CURLcode smtp_regular_transfer(struct Curl_easy *data, + bool *dophase_done) +{ + CURLcode result = CURLE_OK; + bool connected = FALSE; + + /* Make sure size is unknown at this point */ + data->req.size = -1; + + /* Set the progress data */ + Curl_pgrsSetUploadCounter(data, 0); + Curl_pgrsSetDownloadCounter(data, 0); + Curl_pgrsSetUploadSize(data, -1); + Curl_pgrsSetDownloadSize(data, -1); + + /* Carry out the perform */ + result = smtp_perform(data, &connected, dophase_done); + + /* Perform post DO phase operations if necessary */ + if(!result && *dophase_done) + result = smtp_dophase_done(data, connected); + + return result; +} + +static CURLcode smtp_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result; + + /* Clear the TLS upgraded flag */ + conn->bits.tls_upgraded = FALSE; + + /* Initialise the SMTP layer */ + result = smtp_init(data); + if(result) + return result; + + return CURLE_OK; +} + +/*********************************************************************** + * + * smtp_parse_url_options() + * + * Parse the URL login options. + */ +static CURLcode smtp_parse_url_options(struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + struct smtp_conn *smtpc = &conn->proto.smtpc; + const char *ptr = conn->options; + + while(!result && ptr && *ptr) { + const char *key = ptr; + const char *value; + + while(*ptr && *ptr != '=') + ptr++; + + value = ptr + 1; + + while(*ptr && *ptr != ';') + ptr++; + + if(strncasecompare(key, "AUTH=", 5)) + result = Curl_sasl_parse_url_auth_option(&smtpc->sasl, + value, ptr - value); + else + result = CURLE_URL_MALFORMAT; + + if(*ptr == ';') + ptr++; + } + + return result; +} + +/*********************************************************************** + * + * smtp_parse_url_path() + * + * Parse the URL path into separate path components. + */ +static CURLcode smtp_parse_url_path(struct Curl_easy *data) +{ + /* The SMTP struct is already initialised in smtp_connect() */ + struct connectdata *conn = data->conn; + struct smtp_conn *smtpc = &conn->proto.smtpc; + const char *path = &data->state.up.path[1]; /* skip leading path */ + char localhost[HOSTNAME_MAX + 1]; + + /* Calculate the path if necessary */ + if(!*path) { + if(!Curl_gethostname(localhost, sizeof(localhost))) + path = localhost; + else + path = "localhost"; + } + + /* URL decode the path and use it as the domain in our EHLO */ + return Curl_urldecode(path, 0, &smtpc->domain, NULL, REJECT_CTRL); +} + +/*********************************************************************** + * + * smtp_parse_custom_request() + * + * Parse the custom request. + */ +static CURLcode smtp_parse_custom_request(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct SMTP *smtp = data->req.p.smtp; + const char *custom = data->set.str[STRING_CUSTOMREQUEST]; + + /* URL decode the custom request */ + if(custom) + result = Curl_urldecode(custom, 0, &smtp->custom, NULL, REJECT_CTRL); + + return result; +} + +/*********************************************************************** + * + * smtp_parse_address() + * + * Parse the fully qualified mailbox address into a local address part and the + * host name, converting the host name to an IDN A-label, as per RFC-5890, if + * necessary. + * + * Parameters: + * + * conn [in] - The connection handle. + * fqma [in] - The fully qualified mailbox address (which may or + * may not contain UTF-8 characters). + * address [in/out] - A new allocated buffer which holds the local + * address part of the mailbox. This buffer must be + * free'ed by the caller. + * host [in/out] - The host name structure that holds the original, + * and optionally encoded, host name. + * Curl_free_idnconverted_hostname() must be called + * once the caller has finished with the structure. + * + * Returns CURLE_OK on success. + * + * Notes: + * + * Should a UTF-8 host name require conversion to IDN ACE and we cannot honor + * that conversion then we shall return success. This allow the caller to send + * the data to the server as a U-label (as per RFC-6531 sect. 3.2). + * + * If an mailbox '@' separator cannot be located then the mailbox is considered + * to be either a local mailbox or an invalid mailbox (depending on what the + * calling function deems it to be) then the input will simply be returned in + * the address part with the host name being NULL. + */ +static CURLcode smtp_parse_address(const char *fqma, char **address, + struct hostname *host) +{ + CURLcode result = CURLE_OK; + size_t length; + + /* Duplicate the fully qualified email address so we can manipulate it, + ensuring it doesn't contain the delimiters if specified */ + char *dup = strdup(fqma[0] == '<' ? fqma + 1 : fqma); + if(!dup) + return CURLE_OUT_OF_MEMORY; + + length = strlen(dup); + if(length) { + if(dup[length - 1] == '>') + dup[length - 1] = '\0'; + } + + /* Extract the host name from the address (if we can) */ + host->name = strpbrk(dup, "@"); + if(host->name) { + *host->name = '\0'; + host->name = host->name + 1; + + /* Attempt to convert the host name to IDN ACE */ + (void) Curl_idnconvert_hostname(host); + + /* If Curl_idnconvert_hostname() fails then we shall attempt to continue + and send the host name using UTF-8 rather than as 7-bit ACE (which is + our preference) */ + } + + /* Extract the local address from the mailbox */ + *address = dup; + + return result; +} + +struct cr_eob_ctx { + struct Curl_creader super; + struct bufq buf; + size_t n_eob; /* how many EOB bytes we matched so far */ + size_t eob; /* Number of bytes of the EOB (End Of Body) that + have been received so far */ + BIT(read_eos); /* we read an EOS from the next reader */ + BIT(eos); /* we have returned an EOS */ +}; + +static CURLcode cr_eob_init(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_eob_ctx *ctx = reader->ctx; + (void)data; + /* The first char we read is the first on a line, as if we had + * read CRLF just before */ + ctx->n_eob = 2; + Curl_bufq_init2(&ctx->buf, (16 * 1024), 1, BUFQ_OPT_SOFT_LIMIT); + return CURLE_OK; +} + +static void cr_eob_close(struct Curl_easy *data, struct Curl_creader *reader) +{ + struct cr_eob_ctx *ctx = reader->ctx; + (void)data; + Curl_bufq_free(&ctx->buf); +} + +/* this is the 5-bytes End-Of-Body marker for SMTP */ +#define SMTP_EOB "\r\n.\r\n" +#define SMTP_EOB_FIND_LEN 3 + +/* client reader doing SMTP End-Of-Body escaping. */ +static CURLcode cr_eob_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *pnread, bool *peos) +{ + struct cr_eob_ctx *ctx = reader->ctx; + CURLcode result = CURLE_OK; + size_t nread, i, start, n; + bool eos; + + if(!ctx->read_eos && Curl_bufq_is_empty(&ctx->buf)) { + /* Get more and convert it when needed */ + result = Curl_creader_read(data, reader->next, buf, blen, &nread, &eos); + if(result) + return result; + + ctx->read_eos = eos; + if(nread) { + if(!ctx->n_eob && !memchr(buf, SMTP_EOB[0], nread)) { + /* not in the middle of a match, no EOB start found, just pass */ + *pnread = nread; + *peos = FALSE; + return CURLE_OK; + } + /* scan for EOB (continuation) and convert */ + for(i = start = 0; i < nread; ++i) { + if(ctx->n_eob >= SMTP_EOB_FIND_LEN) { + /* matched the EOB prefix and seeing additional char, add '.' */ + result = Curl_bufq_cwrite(&ctx->buf, buf + start, i - start, &n); + if(result) + return result; + result = Curl_bufq_cwrite(&ctx->buf, ".", 1, &n); + if(result) + return result; + ctx->n_eob = 0; + start = i; + if(data->state.infilesize > 0) + data->state.infilesize++; + } + + if(buf[i] != SMTP_EOB[ctx->n_eob]) + ctx->n_eob = 0; + + if(buf[i] == SMTP_EOB[ctx->n_eob]) { + /* matching another char of the EOB */ + ++ctx->n_eob; + } + } + + /* add any remainder to buf */ + if(start < nread) { + result = Curl_bufq_cwrite(&ctx->buf, buf + start, nread - start, &n); + if(result) + return result; + } + } + + if(ctx->read_eos) { + /* if we last matched a CRLF or if the data was empty, add ".\r\n" + * to end the body. If we sent something and it did not end with "\r\n", + * add "\r\n.\r\n" to end the body */ + const char *eob = SMTP_EOB; + switch(ctx->n_eob) { + case 2: + /* seen a CRLF at the end, just add the remainder */ + eob = &SMTP_EOB[2]; + break; + case 3: + /* ended with '\r\n.', we should escpe the last '.' */ + eob = "." SMTP_EOB; + break; + default: + break; + } + result = Curl_bufq_cwrite(&ctx->buf, eob, strlen(eob), &n); + if(result) + return result; + } + } + + *peos = FALSE; + if(!Curl_bufq_is_empty(&ctx->buf)) { + result = Curl_bufq_cread(&ctx->buf, buf, blen, pnread); + } + else + *pnread = 0; + + if(ctx->read_eos && Curl_bufq_is_empty(&ctx->buf)) { + /* no more data, read all, done. */ + ctx->eos = TRUE; + } + *peos = ctx->eos; + DEBUGF(infof(data, "cr_eob_read(%zu) -> %d, %zd, %d", + blen, result, *pnread, *peos)); + return result; +} + +static curl_off_t cr_eob_total_length(struct Curl_easy *data, + struct Curl_creader *reader) +{ + /* this reader changes length depending on input */ + (void)data; + (void)reader; + return -1; +} + +static const struct Curl_crtype cr_eob = { + "cr-smtp-eob", + cr_eob_init, + cr_eob_read, + cr_eob_close, + Curl_creader_def_needs_rewind, + cr_eob_total_length, + Curl_creader_def_resume_from, + Curl_creader_def_rewind, + Curl_creader_def_unpause, + Curl_creader_def_done, + sizeof(struct cr_eob_ctx) +}; + +static CURLcode cr_eob_add(struct Curl_easy *data) +{ + struct Curl_creader *reader = NULL; + CURLcode result; + + result = Curl_creader_create(&reader, data, &cr_eob, + CURL_CR_CONTENT_ENCODE); + if(!result) + result = Curl_creader_add(data, reader); + + if(result && reader) + Curl_creader_free(data, reader); + return result; +} + +#endif /* CURL_DISABLE_SMTP */ diff --git a/third_party/curl/lib/smtp.h b/third_party/curl/lib/smtp.h new file mode 100644 index 0000000..7c2af68 --- /dev/null +++ b/third_party/curl/lib/smtp.h @@ -0,0 +1,87 @@ +#ifndef HEADER_CURL_SMTP_H +#define HEADER_CURL_SMTP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "pingpong.h" +#include "curl_sasl.h" + +/**************************************************************************** + * SMTP unique setup + ***************************************************************************/ +typedef enum { + SMTP_STOP, /* do nothing state, stops the state machine */ + SMTP_SERVERGREET, /* waiting for the initial greeting immediately after + a connect */ + SMTP_EHLO, + SMTP_HELO, + SMTP_STARTTLS, + SMTP_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS + (multi mode only) */ + SMTP_AUTH, + SMTP_COMMAND, /* VRFY, EXPN, NOOP, RSET and HELP */ + SMTP_MAIL, /* MAIL FROM */ + SMTP_RCPT, /* RCPT TO */ + SMTP_DATA, + SMTP_POSTDATA, + SMTP_QUIT, + SMTP_LAST /* never used */ +} smtpstate; + +/* This SMTP struct is used in the Curl_easy. All SMTP data that is + connection-oriented must be in smtp_conn to properly deal with the fact that + perhaps the Curl_easy is changed between the times the connection is + used. */ +struct SMTP { + curl_pp_transfer transfer; + char *custom; /* Custom Request */ + struct curl_slist *rcpt; /* Recipient list */ + int rcpt_last_error; /* The last error received for RCPT TO command */ + size_t eob; /* Number of bytes of the EOB (End Of Body) that + have been received so far */ + BIT(rcpt_had_ok); /* Whether any of RCPT TO commands (depends on + total number of recipients) succeeded so far */ + BIT(trailing_crlf); /* Specifies if the trailing CRLF is present */ +}; + +/* smtp_conn is used for struct connection-oriented data in the connectdata + struct */ +struct smtp_conn { + struct pingpong pp; + struct SASL sasl; /* SASL-related storage */ + smtpstate state; /* Always use smtp.c:state() to change state! */ + char *domain; /* Client address/name to send in the EHLO */ + BIT(ssldone); /* Is connect() over SSL done? */ + BIT(tls_supported); /* StartTLS capability supported by server */ + BIT(size_supported); /* If server supports SIZE extension according to + RFC 1870 */ + BIT(utf8_supported); /* If server supports SMTPUTF8 extension according + to RFC 6531 */ + BIT(auth_supported); /* AUTH capability supported by server */ +}; + +extern const struct Curl_handler Curl_handler_smtp; +extern const struct Curl_handler Curl_handler_smtps; + +#endif /* HEADER_CURL_SMTP_H */ diff --git a/third_party/curl/lib/sockaddr.h b/third_party/curl/lib/sockaddr.h new file mode 100644 index 0000000..2e2d375 --- /dev/null +++ b/third_party/curl/lib/sockaddr.h @@ -0,0 +1,44 @@ +#ifndef HEADER_CURL_SOCKADDR_H +#define HEADER_CURL_SOCKADDR_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +struct Curl_sockaddr_storage { + union { + struct sockaddr sa; + struct sockaddr_in sa_in; +#ifdef USE_IPV6 + struct sockaddr_in6 sa_in6; +#endif +#ifdef HAVE_STRUCT_SOCKADDR_STORAGE + struct sockaddr_storage sa_stor; +#else + char cbuf[256]; /* this should be big enough to fit a lot */ +#endif + } buffer; +}; + +#endif /* HEADER_CURL_SOCKADDR_H */ diff --git a/third_party/curl/lib/socketpair.c b/third_party/curl/lib/socketpair.c new file mode 100644 index 0000000..d7e3afd --- /dev/null +++ b/third_party/curl/lib/socketpair.c @@ -0,0 +1,211 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "socketpair.h" +#include "urldata.h" +#include "rand.h" + +#if defined(HAVE_PIPE) && defined(HAVE_FCNTL) +#include + +int Curl_pipe(curl_socket_t socks[2]) +{ + if(pipe(socks)) + return -1; + + if(fcntl(socks[0], F_SETFD, FD_CLOEXEC) || + fcntl(socks[1], F_SETFD, FD_CLOEXEC) ) { + close(socks[0]); + close(socks[1]); + socks[0] = socks[1] = CURL_SOCKET_BAD; + return -1; + } + + return 0; +} +#endif + + +#if !defined(HAVE_SOCKETPAIR) && !defined(CURL_DISABLE_SOCKETPAIR) +#ifdef _WIN32 +/* + * This is a socketpair() implementation for Windows. + */ +#include +#include +#else +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include /* IPPROTO_TCP */ +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifndef INADDR_LOOPBACK +#define INADDR_LOOPBACK 0x7f000001 +#endif /* !INADDR_LOOPBACK */ +#endif /* !_WIN32 */ + +#include "nonblock.h" /* for curlx_nonblock */ +#include "timeval.h" /* needed before select.h */ +#include "select.h" /* for Curl_poll */ + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +int Curl_socketpair(int domain, int type, int protocol, + curl_socket_t socks[2]) +{ + union { + struct sockaddr_in inaddr; + struct sockaddr addr; + } a; + curl_socket_t listener; + curl_socklen_t addrlen = sizeof(a.inaddr); + int reuse = 1; + struct pollfd pfd[1]; + (void)domain; + (void)type; + (void)protocol; + + listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if(listener == CURL_SOCKET_BAD) + return -1; + + memset(&a, 0, sizeof(a)); + a.inaddr.sin_family = AF_INET; + a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + a.inaddr.sin_port = 0; + + socks[0] = socks[1] = CURL_SOCKET_BAD; + +#if defined(_WIN32) || defined(__CYGWIN__) + /* don't set SO_REUSEADDR on Windows */ + (void)reuse; +#ifdef SO_EXCLUSIVEADDRUSE + { + int exclusive = 1; + if(setsockopt(listener, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, + (char *)&exclusive, (curl_socklen_t)sizeof(exclusive)) == -1) + goto error; + } +#endif +#else + if(setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, + (char *)&reuse, (curl_socklen_t)sizeof(reuse)) == -1) + goto error; +#endif + if(bind(listener, &a.addr, sizeof(a.inaddr)) == -1) + goto error; + if(getsockname(listener, &a.addr, &addrlen) == -1 || + addrlen < (int)sizeof(a.inaddr)) + goto error; + if(listen(listener, 1) == -1) + goto error; + socks[0] = socket(AF_INET, SOCK_STREAM, 0); + if(socks[0] == CURL_SOCKET_BAD) + goto error; + if(connect(socks[0], &a.addr, sizeof(a.inaddr)) == -1) + goto error; + + /* use non-blocking accept to make sure we don't block forever */ + if(curlx_nonblock(listener, TRUE) < 0) + goto error; + pfd[0].fd = listener; + pfd[0].events = POLLIN; + pfd[0].revents = 0; + (void)Curl_poll(pfd, 1, 1000); /* one second */ + socks[1] = accept(listener, NULL, NULL); + if(socks[1] == CURL_SOCKET_BAD) + goto error; + else { + struct curltime start = Curl_now(); + char rnd[9]; + char check[sizeof(rnd)]; + char *p = &check[0]; + size_t s = sizeof(check); + + if(Curl_rand(NULL, (unsigned char *)rnd, sizeof(rnd))) + goto error; + + /* write data to the socket */ + swrite(socks[0], rnd, sizeof(rnd)); + /* verify that we read the correct data */ + do { + ssize_t nread; + + pfd[0].fd = socks[1]; + pfd[0].events = POLLIN; + pfd[0].revents = 0; + (void)Curl_poll(pfd, 1, 1000); /* one second */ + + nread = sread(socks[1], p, s); + if(nread == -1) { + int sockerr = SOCKERRNO; + /* Don't block forever */ + if(Curl_timediff(Curl_now(), start) > (60 * 1000)) + goto error; + if( +#ifdef WSAEWOULDBLOCK + /* This is how Windows does it */ + (WSAEWOULDBLOCK == sockerr) +#else + /* errno may be EWOULDBLOCK or on some systems EAGAIN when it + returned due to its inability to send off data without + blocking. We therefore treat both error codes the same here */ + (EWOULDBLOCK == sockerr) || (EAGAIN == sockerr) || + (EINTR == sockerr) || (EINPROGRESS == sockerr) +#endif + ) { + continue; + } + goto error; + } + s -= nread; + if(s) { + p += nread; + continue; + } + if(memcmp(rnd, check, sizeof(check))) + goto error; + break; + } while(1); + } + + sclose(listener); + return 0; + +error: + sclose(listener); + sclose(socks[0]); + sclose(socks[1]); + return -1; +} + +#endif /* ! HAVE_SOCKETPAIR */ diff --git a/third_party/curl/lib/socketpair.h b/third_party/curl/lib/socketpair.h new file mode 100644 index 0000000..ddd4437 --- /dev/null +++ b/third_party/curl/lib/socketpair.h @@ -0,0 +1,78 @@ +#ifndef HEADER_CURL_SOCKETPAIR_H +#define HEADER_CURL_SOCKETPAIR_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_PIPE + +#define wakeup_write write +#define wakeup_read read +#define wakeup_close close +#define wakeup_create(p) Curl_pipe(p) + +#ifdef HAVE_FCNTL +#include +int Curl_pipe(curl_socket_t socks[2]); +#else +#define Curl_pipe(p) pipe(p) +#endif + +#else /* HAVE_PIPE */ + +#define wakeup_write swrite +#define wakeup_read sread +#define wakeup_close sclose + +#if defined(USE_UNIX_SOCKETS) && defined(HAVE_SOCKETPAIR) +#define SOCKETPAIR_FAMILY AF_UNIX +#elif !defined(HAVE_SOCKETPAIR) +#define SOCKETPAIR_FAMILY 0 /* not used */ +#else +#error "unsupported unix domain and socketpair build combo" +#endif + +#ifdef SOCK_CLOEXEC +#define SOCKETPAIR_TYPE (SOCK_STREAM | SOCK_CLOEXEC) +#else +#define SOCKETPAIR_TYPE SOCK_STREAM +#endif + +#define wakeup_create(p)\ +Curl_socketpair(SOCKETPAIR_FAMILY, SOCKETPAIR_TYPE, 0, p) + +#endif /* HAVE_PIPE */ + + +#ifndef HAVE_SOCKETPAIR +#include + +int Curl_socketpair(int domain, int type, int protocol, + curl_socket_t socks[2]); +#else +#define Curl_socketpair(a,b,c,d) socketpair(a,b,c,d) +#endif + +#endif /* HEADER_CURL_SOCKETPAIR_H */ diff --git a/third_party/curl/lib/socks.c b/third_party/curl/lib/socks.c new file mode 100644 index 0000000..4ade4eb --- /dev/null +++ b/third_party/curl/lib/socks.c @@ -0,0 +1,1276 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_PROXY) + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif + +#include "urldata.h" +#include "sendf.h" +#include "select.h" +#include "cfilters.h" +#include "connect.h" +#include "timeval.h" +#include "socks.h" +#include "multiif.h" /* for getsock macros */ +#include "inet_pton.h" +#include "url.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* for the (SOCKS) connect state machine */ +enum connect_t { + CONNECT_INIT, + CONNECT_SOCKS_INIT, /* 1 */ + CONNECT_SOCKS_SEND, /* 2 waiting to send more first data */ + CONNECT_SOCKS_READ_INIT, /* 3 set up read */ + CONNECT_SOCKS_READ, /* 4 read server response */ + CONNECT_GSSAPI_INIT, /* 5 */ + CONNECT_AUTH_INIT, /* 6 setup outgoing auth buffer */ + CONNECT_AUTH_SEND, /* 7 send auth */ + CONNECT_AUTH_READ, /* 8 read auth response */ + CONNECT_REQ_INIT, /* 9 init SOCKS "request" */ + CONNECT_RESOLVING, /* 10 */ + CONNECT_RESOLVED, /* 11 */ + CONNECT_RESOLVE_REMOTE, /* 12 */ + CONNECT_REQ_SEND, /* 13 */ + CONNECT_REQ_SENDING, /* 14 */ + CONNECT_REQ_READ, /* 15 */ + CONNECT_REQ_READ_MORE, /* 16 */ + CONNECT_DONE /* 17 connected fine to the remote or the SOCKS proxy */ +}; + +#define CURL_SOCKS_BUF_SIZE 600 + +/* make sure we configure it not too low */ +#if CURL_SOCKS_BUF_SIZE < 600 +#error CURL_SOCKS_BUF_SIZE must be at least 600 +#endif + + +struct socks_state { + enum connect_t state; + ssize_t outstanding; /* send this many bytes more */ + unsigned char buffer[CURL_SOCKS_BUF_SIZE]; + unsigned char *outp; /* send from this pointer */ + + const char *hostname; + int remote_port; + const char *proxy_user; + const char *proxy_password; +}; + +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) +/* + * Helper read-from-socket functions. Does the same as Curl_read() but it + * blocks until all bytes amount of buffersize will be read. No more, no less. + * + * This is STUPID BLOCKING behavior. Only used by the SOCKS GSSAPI functions. + */ +int Curl_blockread_all(struct Curl_cfilter *cf, + struct Curl_easy *data, /* transfer */ + char *buf, /* store read data here */ + ssize_t buffersize, /* max amount to read */ + ssize_t *n) /* amount bytes read */ +{ + ssize_t nread = 0; + ssize_t allread = 0; + int result; + CURLcode err = CURLE_OK; + + *n = 0; + for(;;) { + timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE); + if(timeout_ms < 0) { + /* we already got the timeout */ + result = CURLE_OPERATION_TIMEDOUT; + break; + } + if(!timeout_ms) + timeout_ms = TIMEDIFF_T_MAX; + if(SOCKET_READABLE(cf->conn->sock[cf->sockindex], timeout_ms) <= 0) { + result = ~CURLE_OK; + break; + } + nread = Curl_conn_cf_recv(cf->next, data, buf, buffersize, &err); + if(nread <= 0) { + result = err; + if(CURLE_AGAIN == err) + continue; + if(err) { + break; + } + } + + if(buffersize == nread) { + allread += nread; + *n = allread; + result = CURLE_OK; + break; + } + if(!nread) { + result = ~CURLE_OK; + break; + } + + buffersize -= nread; + buf += nread; + allread += nread; + } + return result; +} +#endif + +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) +#define DEBUG_AND_VERBOSE +#define sxstate(x,d,y) socksstate(x,d,y, __LINE__) +#else +#define sxstate(x,d,y) socksstate(x,d,y) +#endif + +/* always use this function to change state, to make debugging easier */ +static void socksstate(struct socks_state *sx, struct Curl_easy *data, + enum connect_t state +#ifdef DEBUG_AND_VERBOSE + , int lineno +#endif +) +{ + enum connect_t oldstate = sx->state; +#ifdef DEBUG_AND_VERBOSE + /* synced with the state list in urldata.h */ + static const char * const socks_statename[] = { + "INIT", + "SOCKS_INIT", + "SOCKS_SEND", + "SOCKS_READ_INIT", + "SOCKS_READ", + "GSSAPI_INIT", + "AUTH_INIT", + "AUTH_SEND", + "AUTH_READ", + "REQ_INIT", + "RESOLVING", + "RESOLVED", + "RESOLVE_REMOTE", + "REQ_SEND", + "REQ_SENDING", + "REQ_READ", + "REQ_READ_MORE", + "DONE" + }; +#endif + + (void)data; + if(oldstate == state) + /* don't bother when the new state is the same as the old state */ + return; + + sx->state = state; + +#ifdef DEBUG_AND_VERBOSE + infof(data, + "SXSTATE: %s => %s; line %d", + socks_statename[oldstate], socks_statename[sx->state], + lineno); +#endif +} + +static CURLproxycode socks_state_send(struct Curl_cfilter *cf, + struct socks_state *sx, + struct Curl_easy *data, + CURLproxycode failcode, + const char *description) +{ + ssize_t nwritten; + CURLcode result; + + nwritten = Curl_conn_cf_send(cf->next, data, (char *)sx->outp, + sx->outstanding, &result); + if(nwritten <= 0) { + if(CURLE_AGAIN == result) { + return CURLPX_OK; + } + else if(CURLE_OK == result) { + /* connection closed */ + failf(data, "connection to proxy closed"); + return CURLPX_CLOSED; + } + failf(data, "Failed to send %s: %s", description, + curl_easy_strerror(result)); + return failcode; + } + DEBUGASSERT(sx->outstanding >= nwritten); + /* not done, remain in state */ + sx->outstanding -= nwritten; + sx->outp += nwritten; + return CURLPX_OK; +} + +static CURLproxycode socks_state_recv(struct Curl_cfilter *cf, + struct socks_state *sx, + struct Curl_easy *data, + CURLproxycode failcode, + const char *description) +{ + ssize_t nread; + CURLcode result; + + nread = Curl_conn_cf_recv(cf->next, data, (char *)sx->outp, + sx->outstanding, &result); + if(nread <= 0) { + if(CURLE_AGAIN == result) { + return CURLPX_OK; + } + else if(CURLE_OK == result) { + /* connection closed */ + failf(data, "connection to proxy closed"); + return CURLPX_CLOSED; + } + failf(data, "SOCKS: Failed receiving %s: %s", description, + curl_easy_strerror(result)); + return failcode; + } + /* remain in reading state */ + DEBUGASSERT(sx->outstanding >= nread); + sx->outstanding -= nread; + sx->outp += nread; + return CURLPX_OK; +} + +/* +* This function logs in to a SOCKS4 proxy and sends the specifics to the final +* destination server. +* +* Reference : +* https://www.openssh.com/txt/socks4.protocol +* +* Note : +* Set protocol4a=true for "SOCKS 4A (Simple Extension to SOCKS 4 Protocol)" +* Nonsupport "Identification Protocol (RFC1413)" +*/ +static CURLproxycode do_SOCKS4(struct Curl_cfilter *cf, + struct socks_state *sx, + struct Curl_easy *data) +{ + struct connectdata *conn = cf->conn; + const bool protocol4a = + (conn->socks_proxy.proxytype == CURLPROXY_SOCKS4A) ? TRUE : FALSE; + unsigned char *socksreq = sx->buffer; + CURLcode result; + CURLproxycode presult; + struct Curl_dns_entry *dns = NULL; + + switch(sx->state) { + case CONNECT_SOCKS_INIT: + /* SOCKS4 can only do IPv4, insist! */ + conn->ip_version = CURL_IPRESOLVE_V4; + if(conn->bits.httpproxy) + infof(data, "SOCKS4%s: connecting to HTTP proxy %s port %d", + protocol4a ? "a" : "", sx->hostname, sx->remote_port); + + infof(data, "SOCKS4 communication to %s:%d", + sx->hostname, sx->remote_port); + + /* + * Compose socks4 request + * + * Request format + * + * +----+----+----+----+----+----+----+----+----+----+....+----+ + * | VN | CD | DSTPORT | DSTIP | USERID |NULL| + * +----+----+----+----+----+----+----+----+----+----+....+----+ + * # of bytes: 1 1 2 4 variable 1 + */ + + socksreq[0] = 4; /* version (SOCKS4) */ + socksreq[1] = 1; /* connect */ + socksreq[2] = (unsigned char)((sx->remote_port >> 8) & 0xff); /* MSB */ + socksreq[3] = (unsigned char)(sx->remote_port & 0xff); /* LSB */ + + /* DNS resolve only for SOCKS4, not SOCKS4a */ + if(!protocol4a) { + enum resolve_t rc = + Curl_resolv(data, sx->hostname, sx->remote_port, TRUE, &dns); + + if(rc == CURLRESOLV_ERROR) + return CURLPX_RESOLVE_HOST; + else if(rc == CURLRESOLV_PENDING) { + sxstate(sx, data, CONNECT_RESOLVING); + infof(data, "SOCKS4 non-blocking resolve of %s", sx->hostname); + return CURLPX_OK; + } + sxstate(sx, data, CONNECT_RESOLVED); + goto CONNECT_RESOLVED; + } + + /* socks4a doesn't resolve anything locally */ + sxstate(sx, data, CONNECT_REQ_INIT); + goto CONNECT_REQ_INIT; + + case CONNECT_RESOLVING: + /* check if we have the name resolved by now */ + dns = Curl_fetch_addr(data, sx->hostname, conn->primary.remote_port); + + if(dns) { +#ifdef CURLRES_ASYNCH + data->state.async.dns = dns; + data->state.async.done = TRUE; +#endif + infof(data, "Hostname '%s' was found", sx->hostname); + sxstate(sx, data, CONNECT_RESOLVED); + } + else { + result = Curl_resolv_check(data, &dns); + if(!dns) { + if(result) + return CURLPX_RESOLVE_HOST; + return CURLPX_OK; + } + } + FALLTHROUGH(); + case CONNECT_RESOLVED: +CONNECT_RESOLVED: + { + struct Curl_addrinfo *hp = NULL; + /* + * We cannot use 'hostent' as a struct that Curl_resolv() returns. It + * returns a Curl_addrinfo pointer that may not always look the same. + */ + if(dns) { + hp = dns->addr; + + /* scan for the first IPv4 address */ + while(hp && (hp->ai_family != AF_INET)) + hp = hp->ai_next; + + if(hp) { + struct sockaddr_in *saddr_in; + char buf[64]; + Curl_printable_address(hp, buf, sizeof(buf)); + + saddr_in = (struct sockaddr_in *)(void *)hp->ai_addr; + socksreq[4] = ((unsigned char *)&saddr_in->sin_addr.s_addr)[0]; + socksreq[5] = ((unsigned char *)&saddr_in->sin_addr.s_addr)[1]; + socksreq[6] = ((unsigned char *)&saddr_in->sin_addr.s_addr)[2]; + socksreq[7] = ((unsigned char *)&saddr_in->sin_addr.s_addr)[3]; + + infof(data, "SOCKS4 connect to IPv4 %s (locally resolved)", buf); + + Curl_resolv_unlock(data, dns); /* not used anymore from now on */ + } + else + failf(data, "SOCKS4 connection to %s not supported", sx->hostname); + } + else + failf(data, "Failed to resolve \"%s\" for SOCKS4 connect.", + sx->hostname); + + if(!hp) + return CURLPX_RESOLVE_HOST; + } + FALLTHROUGH(); + case CONNECT_REQ_INIT: +CONNECT_REQ_INIT: + /* + * This is currently not supporting "Identification Protocol (RFC1413)". + */ + socksreq[8] = 0; /* ensure empty userid is NUL-terminated */ + if(sx->proxy_user) { + size_t plen = strlen(sx->proxy_user); + if(plen > 255) { + /* there is no real size limit to this field in the protocol, but + SOCKS5 limits the proxy user field to 255 bytes and it seems likely + that a longer field is either a mistake or malicious input */ + failf(data, "Too long SOCKS proxy user name"); + return CURLPX_LONG_USER; + } + /* copy the proxy name WITH trailing zero */ + memcpy(socksreq + 8, sx->proxy_user, plen + 1); + } + + /* + * Make connection + */ + { + size_t packetsize = 9 + + strlen((char *)socksreq + 8); /* size including NUL */ + + /* If SOCKS4a, set special invalid IP address 0.0.0.x */ + if(protocol4a) { + size_t hostnamelen = 0; + socksreq[4] = 0; + socksreq[5] = 0; + socksreq[6] = 0; + socksreq[7] = 1; + /* append hostname */ + hostnamelen = strlen(sx->hostname) + 1; /* length including NUL */ + if((hostnamelen <= 255) && + (packetsize + hostnamelen < sizeof(sx->buffer))) + strcpy((char *)socksreq + packetsize, sx->hostname); + else { + failf(data, "SOCKS4: too long host name"); + return CURLPX_LONG_HOSTNAME; + } + packetsize += hostnamelen; + } + sx->outp = socksreq; + DEBUGASSERT(packetsize <= sizeof(sx->buffer)); + sx->outstanding = packetsize; + sxstate(sx, data, CONNECT_REQ_SENDING); + } + FALLTHROUGH(); + case CONNECT_REQ_SENDING: + /* Send request */ + presult = socks_state_send(cf, sx, data, CURLPX_SEND_CONNECT, + "SOCKS4 connect request"); + if(CURLPX_OK != presult) + return presult; + else if(sx->outstanding) { + /* remain in sending state */ + return CURLPX_OK; + } + /* done sending! */ + sx->outstanding = 8; /* receive data size */ + sx->outp = socksreq; + sxstate(sx, data, CONNECT_SOCKS_READ); + + FALLTHROUGH(); + case CONNECT_SOCKS_READ: + /* Receive response */ + presult = socks_state_recv(cf, sx, data, CURLPX_RECV_CONNECT, + "connect request ack"); + if(CURLPX_OK != presult) + return presult; + else if(sx->outstanding) { + /* remain in reading state */ + return CURLPX_OK; + } + sxstate(sx, data, CONNECT_DONE); + break; + default: /* lots of unused states in SOCKS4 */ + break; + } + + /* + * Response format + * + * +----+----+----+----+----+----+----+----+ + * | VN | CD | DSTPORT | DSTIP | + * +----+----+----+----+----+----+----+----+ + * # of bytes: 1 1 2 4 + * + * VN is the version of the reply code and should be 0. CD is the result + * code with one of the following values: + * + * 90: request granted + * 91: request rejected or failed + * 92: request rejected because SOCKS server cannot connect to + * identd on the client + * 93: request rejected because the client program and identd + * report different user-ids + */ + + /* wrong version ? */ + if(socksreq[0]) { + failf(data, + "SOCKS4 reply has wrong version, version should be 0."); + return CURLPX_BAD_VERSION; + } + + /* Result */ + switch(socksreq[1]) { + case 90: + infof(data, "SOCKS4%s request granted.", protocol4a?"a":""); + break; + case 91: + failf(data, + "Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)" + ", request rejected or failed.", + socksreq[4], socksreq[5], socksreq[6], socksreq[7], + (((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]), + (unsigned char)socksreq[1]); + return CURLPX_REQUEST_FAILED; + case 92: + failf(data, + "Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)" + ", request rejected because SOCKS server cannot connect to " + "identd on the client.", + socksreq[4], socksreq[5], socksreq[6], socksreq[7], + (((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]), + (unsigned char)socksreq[1]); + return CURLPX_IDENTD; + case 93: + failf(data, + "Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)" + ", request rejected because the client program and identd " + "report different user-ids.", + socksreq[4], socksreq[5], socksreq[6], socksreq[7], + (((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]), + (unsigned char)socksreq[1]); + return CURLPX_IDENTD_DIFFER; + default: + failf(data, + "Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)" + ", Unknown.", + socksreq[4], socksreq[5], socksreq[6], socksreq[7], + (((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]), + (unsigned char)socksreq[1]); + return CURLPX_UNKNOWN_FAIL; + } + + return CURLPX_OK; /* Proxy was successful! */ +} + +/* + * This function logs in to a SOCKS5 proxy and sends the specifics to the final + * destination server. + */ +static CURLproxycode do_SOCKS5(struct Curl_cfilter *cf, + struct socks_state *sx, + struct Curl_easy *data) +{ + /* + According to the RFC1928, section "6. Replies". This is what a SOCK5 + replies: + + +----+-----+-------+------+----------+----------+ + |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | + +----+-----+-------+------+----------+----------+ + | 1 | 1 | X'00' | 1 | Variable | 2 | + +----+-----+-------+------+----------+----------+ + + Where: + + o VER protocol version: X'05' + o REP Reply field: + o X'00' succeeded + */ + struct connectdata *conn = cf->conn; + unsigned char *socksreq = sx->buffer; + size_t idx; + CURLcode result; + CURLproxycode presult; + bool socks5_resolve_local = + (conn->socks_proxy.proxytype == CURLPROXY_SOCKS5) ? TRUE : FALSE; + const size_t hostname_len = strlen(sx->hostname); + size_t len = 0; + const unsigned char auth = data->set.socks5auth; + bool allow_gssapi = FALSE; + struct Curl_dns_entry *dns = NULL; + + DEBUGASSERT(auth & (CURLAUTH_BASIC | CURLAUTH_GSSAPI)); + switch(sx->state) { + case CONNECT_SOCKS_INIT: + if(conn->bits.httpproxy) + infof(data, "SOCKS5: connecting to HTTP proxy %s port %d", + sx->hostname, sx->remote_port); + + /* RFC1928 chapter 5 specifies max 255 chars for domain name in packet */ + if(!socks5_resolve_local && hostname_len > 255) { + failf(data, "SOCKS5: the destination hostname is too long to be " + "resolved remotely by the proxy."); + return CURLPX_LONG_HOSTNAME; + } + + if(auth & ~(CURLAUTH_BASIC | CURLAUTH_GSSAPI)) + infof(data, + "warning: unsupported value passed to CURLOPT_SOCKS5_AUTH: %u", + auth); + if(!(auth & CURLAUTH_BASIC)) + /* disable username/password auth */ + sx->proxy_user = NULL; +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + if(auth & CURLAUTH_GSSAPI) + allow_gssapi = TRUE; +#endif + + idx = 0; + socksreq[idx++] = 5; /* version */ + idx++; /* number of authentication methods */ + socksreq[idx++] = 0; /* no authentication */ + if(allow_gssapi) + socksreq[idx++] = 1; /* GSS-API */ + if(sx->proxy_user) + socksreq[idx++] = 2; /* username/password */ + /* write the number of authentication methods */ + socksreq[1] = (unsigned char) (idx - 2); + + sx->outp = socksreq; + DEBUGASSERT(idx <= sizeof(sx->buffer)); + sx->outstanding = idx; + presult = socks_state_send(cf, sx, data, CURLPX_SEND_CONNECT, + "initial SOCKS5 request"); + if(CURLPX_OK != presult) + return presult; + else if(sx->outstanding) { + /* remain in sending state */ + return CURLPX_OK; + } + sxstate(sx, data, CONNECT_SOCKS_READ); + goto CONNECT_SOCKS_READ_INIT; + case CONNECT_SOCKS_SEND: + presult = socks_state_send(cf, sx, data, CURLPX_SEND_CONNECT, + "initial SOCKS5 request"); + if(CURLPX_OK != presult) + return presult; + else if(sx->outstanding) { + /* remain in sending state */ + return CURLPX_OK; + } + FALLTHROUGH(); + case CONNECT_SOCKS_READ_INIT: +CONNECT_SOCKS_READ_INIT: + sx->outstanding = 2; /* expect two bytes */ + sx->outp = socksreq; /* store it here */ + FALLTHROUGH(); + case CONNECT_SOCKS_READ: + presult = socks_state_recv(cf, sx, data, CURLPX_RECV_CONNECT, + "initial SOCKS5 response"); + if(CURLPX_OK != presult) + return presult; + else if(sx->outstanding) { + /* remain in reading state */ + return CURLPX_OK; + } + else if(socksreq[0] != 5) { + failf(data, "Received invalid version in initial SOCKS5 response."); + return CURLPX_BAD_VERSION; + } + else if(socksreq[1] == 0) { + /* DONE! No authentication needed. Send request. */ + sxstate(sx, data, CONNECT_REQ_INIT); + goto CONNECT_REQ_INIT; + } + else if(socksreq[1] == 2) { + /* regular name + password authentication */ + sxstate(sx, data, CONNECT_AUTH_INIT); + goto CONNECT_AUTH_INIT; + } +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + else if(allow_gssapi && (socksreq[1] == 1)) { + sxstate(sx, data, CONNECT_GSSAPI_INIT); + result = Curl_SOCKS5_gssapi_negotiate(cf, data); + if(result) { + failf(data, "Unable to negotiate SOCKS5 GSS-API context."); + return CURLPX_GSSAPI; + } + } +#endif + else { + /* error */ + if(!allow_gssapi && (socksreq[1] == 1)) { + failf(data, + "SOCKS5 GSSAPI per-message authentication is not supported."); + return CURLPX_GSSAPI_PERMSG; + } + else if(socksreq[1] == 255) { + failf(data, "No authentication method was acceptable."); + return CURLPX_NO_AUTH; + } + } + failf(data, + "Undocumented SOCKS5 mode attempted to be used by server."); + return CURLPX_UNKNOWN_MODE; +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + case CONNECT_GSSAPI_INIT: + /* GSSAPI stuff done non-blocking */ + break; +#endif + + default: /* do nothing! */ + break; + +CONNECT_AUTH_INIT: + case CONNECT_AUTH_INIT: { + /* Needs user name and password */ + size_t proxy_user_len, proxy_password_len; + if(sx->proxy_user && sx->proxy_password) { + proxy_user_len = strlen(sx->proxy_user); + proxy_password_len = strlen(sx->proxy_password); + } + else { + proxy_user_len = 0; + proxy_password_len = 0; + } + + /* username/password request looks like + * +----+------+----------+------+----------+ + * |VER | ULEN | UNAME | PLEN | PASSWD | + * +----+------+----------+------+----------+ + * | 1 | 1 | 1 to 255 | 1 | 1 to 255 | + * +----+------+----------+------+----------+ + */ + len = 0; + socksreq[len++] = 1; /* username/pw subnegotiation version */ + socksreq[len++] = (unsigned char) proxy_user_len; + if(sx->proxy_user && proxy_user_len) { + /* the length must fit in a single byte */ + if(proxy_user_len > 255) { + failf(data, "Excessive user name length for proxy auth"); + return CURLPX_LONG_USER; + } + memcpy(socksreq + len, sx->proxy_user, proxy_user_len); + } + len += proxy_user_len; + socksreq[len++] = (unsigned char) proxy_password_len; + if(sx->proxy_password && proxy_password_len) { + /* the length must fit in a single byte */ + if(proxy_password_len > 255) { + failf(data, "Excessive password length for proxy auth"); + return CURLPX_LONG_PASSWD; + } + memcpy(socksreq + len, sx->proxy_password, proxy_password_len); + } + len += proxy_password_len; + sxstate(sx, data, CONNECT_AUTH_SEND); + DEBUGASSERT(len <= sizeof(sx->buffer)); + sx->outstanding = len; + sx->outp = socksreq; + } + FALLTHROUGH(); + case CONNECT_AUTH_SEND: + presult = socks_state_send(cf, sx, data, CURLPX_SEND_AUTH, + "SOCKS5 sub-negotiation request"); + if(CURLPX_OK != presult) + return presult; + else if(sx->outstanding) { + /* remain in sending state */ + return CURLPX_OK; + } + sx->outp = socksreq; + sx->outstanding = 2; + sxstate(sx, data, CONNECT_AUTH_READ); + FALLTHROUGH(); + case CONNECT_AUTH_READ: + presult = socks_state_recv(cf, sx, data, CURLPX_RECV_AUTH, + "SOCKS5 sub-negotiation response"); + if(CURLPX_OK != presult) + return presult; + else if(sx->outstanding) { + /* remain in reading state */ + return CURLPX_OK; + } + /* ignore the first (VER) byte */ + else if(socksreq[1]) { /* status */ + failf(data, "User was rejected by the SOCKS5 server (%d %d).", + socksreq[0], socksreq[1]); + return CURLPX_USER_REJECTED; + } + + /* Everything is good so far, user was authenticated! */ + sxstate(sx, data, CONNECT_REQ_INIT); + FALLTHROUGH(); + case CONNECT_REQ_INIT: +CONNECT_REQ_INIT: + if(socks5_resolve_local) { + enum resolve_t rc = Curl_resolv(data, sx->hostname, sx->remote_port, + TRUE, &dns); + + if(rc == CURLRESOLV_ERROR) + return CURLPX_RESOLVE_HOST; + + if(rc == CURLRESOLV_PENDING) { + sxstate(sx, data, CONNECT_RESOLVING); + return CURLPX_OK; + } + sxstate(sx, data, CONNECT_RESOLVED); + goto CONNECT_RESOLVED; + } + goto CONNECT_RESOLVE_REMOTE; + + case CONNECT_RESOLVING: + /* check if we have the name resolved by now */ + dns = Curl_fetch_addr(data, sx->hostname, sx->remote_port); + + if(dns) { +#ifdef CURLRES_ASYNCH + data->state.async.dns = dns; + data->state.async.done = TRUE; +#endif + infof(data, "SOCKS5: hostname '%s' found", sx->hostname); + } + + if(!dns) { + result = Curl_resolv_check(data, &dns); + if(!dns) { + if(result) + return CURLPX_RESOLVE_HOST; + return CURLPX_OK; + } + } + FALLTHROUGH(); + case CONNECT_RESOLVED: +CONNECT_RESOLVED: + { + char dest[MAX_IPADR_LEN]; /* printable address */ + struct Curl_addrinfo *hp = NULL; + if(dns) + hp = dns->addr; +#ifdef USE_IPV6 + if(data->set.ipver != CURL_IPRESOLVE_WHATEVER) { + int wanted_family = data->set.ipver == CURL_IPRESOLVE_V4 ? + AF_INET : AF_INET6; + /* scan for the first proper address */ + while(hp && (hp->ai_family != wanted_family)) + hp = hp->ai_next; + } +#endif + if(!hp) { + failf(data, "Failed to resolve \"%s\" for SOCKS5 connect.", + sx->hostname); + return CURLPX_RESOLVE_HOST; + } + + Curl_printable_address(hp, dest, sizeof(dest)); + + len = 0; + socksreq[len++] = 5; /* version (SOCKS5) */ + socksreq[len++] = 1; /* connect */ + socksreq[len++] = 0; /* must be zero */ + if(hp->ai_family == AF_INET) { + int i; + struct sockaddr_in *saddr_in; + socksreq[len++] = 1; /* ATYP: IPv4 = 1 */ + + saddr_in = (struct sockaddr_in *)(void *)hp->ai_addr; + for(i = 0; i < 4; i++) { + socksreq[len++] = ((unsigned char *)&saddr_in->sin_addr.s_addr)[i]; + } + + infof(data, "SOCKS5 connect to %s:%d (locally resolved)", dest, + sx->remote_port); + } +#ifdef USE_IPV6 + else if(hp->ai_family == AF_INET6) { + int i; + struct sockaddr_in6 *saddr_in6; + socksreq[len++] = 4; /* ATYP: IPv6 = 4 */ + + saddr_in6 = (struct sockaddr_in6 *)(void *)hp->ai_addr; + for(i = 0; i < 16; i++) { + socksreq[len++] = + ((unsigned char *)&saddr_in6->sin6_addr.s6_addr)[i]; + } + + infof(data, "SOCKS5 connect to [%s]:%d (locally resolved)", dest, + sx->remote_port); + } +#endif + else { + hp = NULL; /* fail! */ + failf(data, "SOCKS5 connection to %s not supported", dest); + } + + Curl_resolv_unlock(data, dns); /* not used anymore from now on */ + goto CONNECT_REQ_SEND; + } +CONNECT_RESOLVE_REMOTE: + case CONNECT_RESOLVE_REMOTE: + /* Authentication is complete, now specify destination to the proxy */ + len = 0; + socksreq[len++] = 5; /* version (SOCKS5) */ + socksreq[len++] = 1; /* connect */ + socksreq[len++] = 0; /* must be zero */ + + if(!socks5_resolve_local) { + /* ATYP: domain name = 3, + IPv6 == 4, + IPv4 == 1 */ + unsigned char ip4[4]; +#ifdef USE_IPV6 + if(conn->bits.ipv6_ip) { + char ip6[16]; + if(1 != Curl_inet_pton(AF_INET6, sx->hostname, ip6)) + return CURLPX_BAD_ADDRESS_TYPE; + socksreq[len++] = 4; + memcpy(&socksreq[len], ip6, sizeof(ip6)); + len += sizeof(ip6); + } + else +#endif + if(1 == Curl_inet_pton(AF_INET, sx->hostname, ip4)) { + socksreq[len++] = 1; + memcpy(&socksreq[len], ip4, sizeof(ip4)); + len += sizeof(ip4); + } + else { + socksreq[len++] = 3; + socksreq[len++] = (unsigned char) hostname_len; /* one byte length */ + memcpy(&socksreq[len], sx->hostname, hostname_len); /* w/o NULL */ + len += hostname_len; + } + infof(data, "SOCKS5 connect to %s:%d (remotely resolved)", + sx->hostname, sx->remote_port); + } + FALLTHROUGH(); + + case CONNECT_REQ_SEND: +CONNECT_REQ_SEND: + /* PORT MSB */ + socksreq[len++] = (unsigned char)((sx->remote_port >> 8) & 0xff); + /* PORT LSB */ + socksreq[len++] = (unsigned char)(sx->remote_port & 0xff); + +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + if(conn->socks5_gssapi_enctype) { + failf(data, "SOCKS5 GSS-API protection not yet implemented."); + return CURLPX_GSSAPI_PROTECTION; + } +#endif + sx->outp = socksreq; + DEBUGASSERT(len <= sizeof(sx->buffer)); + sx->outstanding = len; + sxstate(sx, data, CONNECT_REQ_SENDING); + FALLTHROUGH(); + case CONNECT_REQ_SENDING: + presult = socks_state_send(cf, sx, data, CURLPX_SEND_REQUEST, + "SOCKS5 connect request"); + if(CURLPX_OK != presult) + return presult; + else if(sx->outstanding) { + /* remain in send state */ + return CURLPX_OK; + } +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + if(conn->socks5_gssapi_enctype) { + failf(data, "SOCKS5 GSS-API protection not yet implemented."); + return CURLPX_GSSAPI_PROTECTION; + } +#endif + sx->outstanding = 10; /* minimum packet size is 10 */ + sx->outp = socksreq; + sxstate(sx, data, CONNECT_REQ_READ); + FALLTHROUGH(); + case CONNECT_REQ_READ: + presult = socks_state_recv(cf, sx, data, CURLPX_RECV_REQACK, + "SOCKS5 connect request ack"); + if(CURLPX_OK != presult) + return presult; + else if(sx->outstanding) { + /* remain in reading state */ + return CURLPX_OK; + } + else if(socksreq[0] != 5) { /* version */ + failf(data, + "SOCKS5 reply has wrong version, version should be 5."); + return CURLPX_BAD_VERSION; + } + else if(socksreq[1]) { /* Anything besides 0 is an error */ + CURLproxycode rc = CURLPX_REPLY_UNASSIGNED; + int code = socksreq[1]; + failf(data, "Can't complete SOCKS5 connection to %s. (%d)", + sx->hostname, (unsigned char)socksreq[1]); + if(code < 9) { + /* RFC 1928 section 6 lists: */ + static const CURLproxycode lookup[] = { + CURLPX_OK, + CURLPX_REPLY_GENERAL_SERVER_FAILURE, + CURLPX_REPLY_NOT_ALLOWED, + CURLPX_REPLY_NETWORK_UNREACHABLE, + CURLPX_REPLY_HOST_UNREACHABLE, + CURLPX_REPLY_CONNECTION_REFUSED, + CURLPX_REPLY_TTL_EXPIRED, + CURLPX_REPLY_COMMAND_NOT_SUPPORTED, + CURLPX_REPLY_ADDRESS_TYPE_NOT_SUPPORTED, + }; + rc = lookup[code]; + } + return rc; + } + + /* Fix: in general, returned BND.ADDR is variable length parameter by RFC + 1928, so the reply packet should be read until the end to avoid errors + at subsequent protocol level. + + +----+-----+-------+------+----------+----------+ + |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | + +----+-----+-------+------+----------+----------+ + | 1 | 1 | X'00' | 1 | Variable | 2 | + +----+-----+-------+------+----------+----------+ + + ATYP: + o IP v4 address: X'01', BND.ADDR = 4 byte + o domain name: X'03', BND.ADDR = [ 1 byte length, string ] + o IP v6 address: X'04', BND.ADDR = 16 byte + */ + + /* Calculate real packet size */ + if(socksreq[3] == 3) { + /* domain name */ + int addrlen = (int) socksreq[4]; + len = 5 + addrlen + 2; + } + else if(socksreq[3] == 4) { + /* IPv6 */ + len = 4 + 16 + 2; + } + else if(socksreq[3] == 1) { + len = 4 + 4 + 2; + } + else { + failf(data, "SOCKS5 reply has wrong address type."); + return CURLPX_BAD_ADDRESS_TYPE; + } + + /* At this point we already read first 10 bytes */ +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + if(!conn->socks5_gssapi_enctype) { + /* decrypt_gssapi_blockread already read the whole packet */ +#endif + if(len > 10) { + DEBUGASSERT(len <= sizeof(sx->buffer)); + sx->outstanding = len - 10; /* get the rest */ + sx->outp = &socksreq[10]; + sxstate(sx, data, CONNECT_REQ_READ_MORE); + } + else { + sxstate(sx, data, CONNECT_DONE); + break; + } +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + } +#endif + FALLTHROUGH(); + case CONNECT_REQ_READ_MORE: + presult = socks_state_recv(cf, sx, data, CURLPX_RECV_ADDRESS, + "SOCKS5 connect request address"); + if(CURLPX_OK != presult) + return presult; + else if(sx->outstanding) { + /* remain in reading state */ + return CURLPX_OK; + } + sxstate(sx, data, CONNECT_DONE); + } + infof(data, "SOCKS5 request granted."); + + return CURLPX_OK; /* Proxy was successful! */ +} + +static CURLcode connect_SOCKS(struct Curl_cfilter *cf, + struct socks_state *sxstate, + struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + CURLproxycode pxresult = CURLPX_OK; + struct connectdata *conn = cf->conn; + + switch(conn->socks_proxy.proxytype) { + case CURLPROXY_SOCKS5: + case CURLPROXY_SOCKS5_HOSTNAME: + pxresult = do_SOCKS5(cf, sxstate, data); + break; + + case CURLPROXY_SOCKS4: + case CURLPROXY_SOCKS4A: + pxresult = do_SOCKS4(cf, sxstate, data); + break; + + default: + failf(data, "unknown proxytype option given"); + result = CURLE_COULDNT_CONNECT; + } /* switch proxytype */ + if(pxresult) { + result = CURLE_PROXY; + data->info.pxcode = pxresult; + } + + return result; +} + +static void socks_proxy_cf_free(struct Curl_cfilter *cf) +{ + struct socks_state *sxstate = cf->ctx; + if(sxstate) { + free(sxstate); + cf->ctx = NULL; + } +} + +/* After a TCP connection to the proxy has been verified, this function does + the next magic steps. If 'done' isn't set TRUE, it is not done yet and + must be called again. + + Note: this function's sub-functions call failf() + +*/ +static CURLcode socks_proxy_cf_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + CURLcode result; + struct connectdata *conn = cf->conn; + int sockindex = cf->sockindex; + struct socks_state *sx = cf->ctx; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + result = cf->next->cft->do_connect(cf->next, data, blocking, done); + if(result || !*done) + return result; + + if(!sx) { + sx = calloc(1, sizeof(*sx)); + if(!sx) + return CURLE_OUT_OF_MEMORY; + cf->ctx = sx; + } + + if(sx->state == CONNECT_INIT) { + /* for the secondary socket (FTP), use the "connect to host" + * but ignore the "connect to port" (use the secondary port) + */ + sxstate(sx, data, CONNECT_SOCKS_INIT); + sx->hostname = + conn->bits.httpproxy ? + conn->http_proxy.host.name : + conn->bits.conn_to_host ? + conn->conn_to_host.name : + sockindex == SECONDARYSOCKET ? + conn->secondaryhostname : conn->host.name; + sx->remote_port = + conn->bits.httpproxy ? (int)conn->http_proxy.port : + sockindex == SECONDARYSOCKET ? conn->secondary_port : + conn->bits.conn_to_port ? conn->conn_to_port : + conn->remote_port; + sx->proxy_user = conn->socks_proxy.user; + sx->proxy_password = conn->socks_proxy.passwd; + } + + result = connect_SOCKS(cf, sx, data); + if(!result && sx->state == CONNECT_DONE) { + cf->connected = TRUE; + Curl_verboseconnect(data, conn, cf->sockindex); + socks_proxy_cf_free(cf); + } + + *done = cf->connected; + return result; +} + +static void socks_cf_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct socks_state *sx = cf->ctx; + + if(!cf->connected && sx) { + /* If we are not connected, the filter below is and has nothing + * to wait on, we determine what to wait for. */ + curl_socket_t sock = Curl_conn_cf_get_socket(cf, data); + switch(sx->state) { + case CONNECT_RESOLVING: + case CONNECT_SOCKS_READ: + case CONNECT_AUTH_READ: + case CONNECT_REQ_READ: + case CONNECT_REQ_READ_MORE: + Curl_pollset_set_in_only(data, ps, sock); + break; + default: + Curl_pollset_set_out_only(data, ps, sock); + break; + } + } +} + +static void socks_proxy_cf_close(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + + DEBUGASSERT(cf->next); + cf->connected = FALSE; + socks_proxy_cf_free(cf); + cf->next->cft->do_close(cf->next, data); +} + +static void socks_proxy_cf_destroy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + (void)data; + socks_proxy_cf_free(cf); +} + +static void socks_cf_get_host(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char **phost, + const char **pdisplay_host, + int *pport) +{ + (void)data; + if(!cf->connected) { + *phost = cf->conn->socks_proxy.host.name; + *pdisplay_host = cf->conn->http_proxy.host.dispname; + *pport = (int)cf->conn->socks_proxy.port; + } + else { + cf->next->cft->get_host(cf->next, data, phost, pdisplay_host, pport); + } +} + +struct Curl_cftype Curl_cft_socks_proxy = { + "SOCKS-PROXYY", + CF_TYPE_IP_CONNECT|CF_TYPE_PROXY, + 0, + socks_proxy_cf_destroy, + socks_proxy_cf_connect, + socks_proxy_cf_close, + socks_cf_get_host, + socks_cf_adjust_pollset, + Curl_cf_def_data_pending, + Curl_cf_def_send, + Curl_cf_def_recv, + Curl_cf_def_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + Curl_cf_def_query, +}; + +CURLcode Curl_cf_socks_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data) +{ + struct Curl_cfilter *cf; + CURLcode result; + + (void)data; + result = Curl_cf_create(&cf, &Curl_cft_socks_proxy, NULL); + if(!result) + Curl_conn_cf_insert_after(cf_at, cf); + return result; +} + +#endif /* CURL_DISABLE_PROXY */ diff --git a/third_party/curl/lib/socks.h b/third_party/curl/lib/socks.h new file mode 100644 index 0000000..a3adcc6 --- /dev/null +++ b/third_party/curl/lib/socks.h @@ -0,0 +1,61 @@ +#ifndef HEADER_CURL_SOCKS_H +#define HEADER_CURL_SOCKS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef CURL_DISABLE_PROXY +#define Curl_SOCKS4(a,b,c,d,e) CURLE_NOT_BUILT_IN +#define Curl_SOCKS5(a,b,c,d,e,f) CURLE_NOT_BUILT_IN +#define Curl_SOCKS_getsock(x,y,z) 0 +#else +/* + * Helper read-from-socket functions. Does the same as Curl_read() but it + * blocks until all bytes amount of buffersize will be read. No more, no less. + * + * This is STUPID BLOCKING behavior + */ +int Curl_blockread_all(struct Curl_cfilter *cf, + struct Curl_easy *data, + char *buf, + ssize_t buffersize, + ssize_t *n); + +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) +/* + * This function handles the SOCKS5 GSS-API negotiation and initialization + */ +CURLcode Curl_SOCKS5_gssapi_negotiate(struct Curl_cfilter *cf, + struct Curl_easy *data); +#endif + +CURLcode Curl_cf_socks_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data); + +extern struct Curl_cftype Curl_cft_socks_proxy; + +#endif /* CURL_DISABLE_PROXY */ + +#endif /* HEADER_CURL_SOCKS_H */ diff --git a/third_party/curl/lib/socks_gssapi.c b/third_party/curl/lib/socks_gssapi.c new file mode 100644 index 0000000..c0b42b8 --- /dev/null +++ b/third_party/curl/lib/socks_gssapi.c @@ -0,0 +1,535 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (C) Markus Moeller, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(HAVE_GSSAPI) && !defined(CURL_DISABLE_PROXY) + +#include "curl_gssapi.h" +#include "urldata.h" +#include "sendf.h" +#include "cfilters.h" +#include "connect.h" +#include "timeval.h" +#include "socks.h" +#include "warnless.h" +#include "strdup.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +static gss_ctx_id_t gss_context = GSS_C_NO_CONTEXT; + +/* + * Helper GSS-API error functions. + */ +static int check_gss_err(struct Curl_easy *data, + OM_uint32 major_status, + OM_uint32 minor_status, + const char *function) +{ + if(GSS_ERROR(major_status)) { + OM_uint32 maj_stat, min_stat; + OM_uint32 msg_ctx = 0; + gss_buffer_desc status_string = GSS_C_EMPTY_BUFFER; + char buf[1024]; + size_t len; + + len = 0; + msg_ctx = 0; + while(!msg_ctx) { + /* convert major status code (GSS-API error) to text */ + maj_stat = gss_display_status(&min_stat, major_status, + GSS_C_GSS_CODE, + GSS_C_NULL_OID, + &msg_ctx, &status_string); + if(maj_stat == GSS_S_COMPLETE) { + if(sizeof(buf) > len + status_string.length + 1) { + strcpy(buf + len, (char *) status_string.value); + len += status_string.length; + } + gss_release_buffer(&min_stat, &status_string); + break; + } + gss_release_buffer(&min_stat, &status_string); + } + if(sizeof(buf) > len + 3) { + strcpy(buf + len, ".\n"); + len += 2; + } + msg_ctx = 0; + while(!msg_ctx) { + /* convert minor status code (underlying routine error) to text */ + maj_stat = gss_display_status(&min_stat, minor_status, + GSS_C_MECH_CODE, + GSS_C_NULL_OID, + &msg_ctx, &status_string); + if(maj_stat == GSS_S_COMPLETE) { + if(sizeof(buf) > len + status_string.length) + strcpy(buf + len, (char *) status_string.value); + gss_release_buffer(&min_stat, &status_string); + break; + } + gss_release_buffer(&min_stat, &status_string); + } + failf(data, "GSS-API error: %s failed: %s", function, buf); + return 1; + } + + return 0; +} + +CURLcode Curl_SOCKS5_gssapi_negotiate(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct connectdata *conn = cf->conn; + curl_socket_t sock = conn->sock[cf->sockindex]; + CURLcode code; + ssize_t actualread; + ssize_t nwritten; + int result; + OM_uint32 gss_major_status, gss_minor_status, gss_status; + OM_uint32 gss_ret_flags; + int gss_conf_state, gss_enc; + gss_buffer_desc service = GSS_C_EMPTY_BUFFER; + gss_buffer_desc gss_send_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc gss_recv_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc gss_w_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc *gss_token = GSS_C_NO_BUFFER; + gss_name_t server = GSS_C_NO_NAME; + gss_name_t gss_client_name = GSS_C_NO_NAME; + unsigned short us_length; + char *user = NULL; + unsigned char socksreq[4]; /* room for GSS-API exchange header only */ + const char *serviceptr = data->set.str[STRING_PROXY_SERVICE_NAME] ? + data->set.str[STRING_PROXY_SERVICE_NAME] : "rcmd"; + const size_t serviceptr_length = strlen(serviceptr); + + /* GSS-API request looks like + * +----+------+-----+----------------+ + * |VER | MTYP | LEN | TOKEN | + * +----+------+----------------------+ + * | 1 | 1 | 2 | up to 2^16 - 1 | + * +----+------+-----+----------------+ + */ + + /* prepare service name */ + if(strchr(serviceptr, '/')) { + service.length = serviceptr_length; + service.value = Curl_memdup(serviceptr, service.length); + if(!service.value) + return CURLE_OUT_OF_MEMORY; + + gss_major_status = gss_import_name(&gss_minor_status, &service, + (gss_OID) GSS_C_NULL_OID, &server); + } + else { + service.value = malloc(serviceptr_length + + strlen(conn->socks_proxy.host.name) + 2); + if(!service.value) + return CURLE_OUT_OF_MEMORY; + service.length = serviceptr_length + + strlen(conn->socks_proxy.host.name) + 1; + msnprintf(service.value, service.length + 1, "%s@%s", + serviceptr, conn->socks_proxy.host.name); + + gss_major_status = gss_import_name(&gss_minor_status, &service, + GSS_C_NT_HOSTBASED_SERVICE, &server); + } + + gss_release_buffer(&gss_status, &service); /* clear allocated memory */ + + if(check_gss_err(data, gss_major_status, + gss_minor_status, "gss_import_name()")) { + failf(data, "Failed to create service name."); + gss_release_name(&gss_status, &server); + return CURLE_COULDNT_CONNECT; + } + + (void)curlx_nonblock(sock, FALSE); + + /* As long as we need to keep sending some context info, and there's no */ + /* errors, keep sending it... */ + for(;;) { + gss_major_status = Curl_gss_init_sec_context(data, + &gss_minor_status, + &gss_context, + server, + &Curl_krb5_mech_oid, + NULL, + gss_token, + &gss_send_token, + TRUE, + &gss_ret_flags); + + if(gss_token != GSS_C_NO_BUFFER) + gss_release_buffer(&gss_status, &gss_recv_token); + if(check_gss_err(data, gss_major_status, + gss_minor_status, "gss_init_sec_context")) { + gss_release_name(&gss_status, &server); + gss_release_buffer(&gss_status, &gss_recv_token); + gss_release_buffer(&gss_status, &gss_send_token); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + failf(data, "Failed to initial GSS-API token."); + return CURLE_COULDNT_CONNECT; + } + + if(gss_send_token.length) { + socksreq[0] = 1; /* GSS-API subnegotiation version */ + socksreq[1] = 1; /* authentication message type */ + us_length = htons((short)gss_send_token.length); + memcpy(socksreq + 2, &us_length, sizeof(short)); + + nwritten = Curl_conn_cf_send(cf->next, data, (char *)socksreq, 4, &code); + if(code || (4 != nwritten)) { + failf(data, "Failed to send GSS-API authentication request."); + gss_release_name(&gss_status, &server); + gss_release_buffer(&gss_status, &gss_recv_token); + gss_release_buffer(&gss_status, &gss_send_token); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + nwritten = Curl_conn_cf_send(cf->next, data, + (char *)gss_send_token.value, + gss_send_token.length, &code); + if(code || ((ssize_t)gss_send_token.length != nwritten)) { + failf(data, "Failed to send GSS-API authentication token."); + gss_release_name(&gss_status, &server); + gss_release_buffer(&gss_status, &gss_recv_token); + gss_release_buffer(&gss_status, &gss_send_token); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + } + + gss_release_buffer(&gss_status, &gss_send_token); + gss_release_buffer(&gss_status, &gss_recv_token); + if(gss_major_status != GSS_S_CONTINUE_NEEDED) + break; + + /* analyse response */ + + /* GSS-API response looks like + * +----+------+-----+----------------+ + * |VER | MTYP | LEN | TOKEN | + * +----+------+----------------------+ + * | 1 | 1 | 2 | up to 2^16 - 1 | + * +----+------+-----+----------------+ + */ + + result = Curl_blockread_all(cf, data, (char *)socksreq, 4, &actualread); + if(result || (actualread != 4)) { + failf(data, "Failed to receive GSS-API authentication response."); + gss_release_name(&gss_status, &server); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + /* ignore the first (VER) byte */ + if(socksreq[1] == 255) { /* status / message type */ + failf(data, "User was rejected by the SOCKS5 server (%d %d).", + socksreq[0], socksreq[1]); + gss_release_name(&gss_status, &server); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + if(socksreq[1] != 1) { /* status / message type */ + failf(data, "Invalid GSS-API authentication response type (%d %d).", + socksreq[0], socksreq[1]); + gss_release_name(&gss_status, &server); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + memcpy(&us_length, socksreq + 2, sizeof(short)); + us_length = ntohs(us_length); + + gss_recv_token.length = us_length; + gss_recv_token.value = malloc(us_length); + if(!gss_recv_token.value) { + failf(data, + "Could not allocate memory for GSS-API authentication " + "response token."); + gss_release_name(&gss_status, &server); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_OUT_OF_MEMORY; + } + + result = Curl_blockread_all(cf, data, (char *)gss_recv_token.value, + gss_recv_token.length, &actualread); + + if(result || (actualread != us_length)) { + failf(data, "Failed to receive GSS-API authentication token."); + gss_release_name(&gss_status, &server); + gss_release_buffer(&gss_status, &gss_recv_token); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + gss_token = &gss_recv_token; + } + + gss_release_name(&gss_status, &server); + + /* Everything is good so far, user was authenticated! */ + gss_major_status = gss_inquire_context(&gss_minor_status, gss_context, + &gss_client_name, NULL, NULL, NULL, + NULL, NULL, NULL); + if(check_gss_err(data, gss_major_status, + gss_minor_status, "gss_inquire_context")) { + gss_delete_sec_context(&gss_status, &gss_context, NULL); + gss_release_name(&gss_status, &gss_client_name); + failf(data, "Failed to determine user name."); + return CURLE_COULDNT_CONNECT; + } + gss_major_status = gss_display_name(&gss_minor_status, gss_client_name, + &gss_send_token, NULL); + if(check_gss_err(data, gss_major_status, + gss_minor_status, "gss_display_name")) { + gss_delete_sec_context(&gss_status, &gss_context, NULL); + gss_release_name(&gss_status, &gss_client_name); + gss_release_buffer(&gss_status, &gss_send_token); + failf(data, "Failed to determine user name."); + return CURLE_COULDNT_CONNECT; + } + user = malloc(gss_send_token.length + 1); + if(!user) { + gss_delete_sec_context(&gss_status, &gss_context, NULL); + gss_release_name(&gss_status, &gss_client_name); + gss_release_buffer(&gss_status, &gss_send_token); + return CURLE_OUT_OF_MEMORY; + } + + memcpy(user, gss_send_token.value, gss_send_token.length); + user[gss_send_token.length] = '\0'; + gss_release_name(&gss_status, &gss_client_name); + gss_release_buffer(&gss_status, &gss_send_token); + infof(data, "SOCKS5 server authenticated user %s with GSS-API.",user); + free(user); + user = NULL; + + /* Do encryption */ + socksreq[0] = 1; /* GSS-API subnegotiation version */ + socksreq[1] = 2; /* encryption message type */ + + gss_enc = 0; /* no data protection */ + /* do confidentiality protection if supported */ + if(gss_ret_flags & GSS_C_CONF_FLAG) + gss_enc = 2; + /* else do integrity protection */ + else if(gss_ret_flags & GSS_C_INTEG_FLAG) + gss_enc = 1; + + infof(data, "SOCKS5 server supports GSS-API %s data protection.", + (gss_enc == 0)?"no":((gss_enc==1)?"integrity":"confidentiality")); + /* force for the moment to no data protection */ + gss_enc = 0; + /* + * Sending the encryption type in clear seems wrong. It should be + * protected with gss_seal()/gss_wrap(). See RFC1961 extract below + * The NEC reference implementations on which this is based is + * therefore at fault + * + * +------+------+------+.......................+ + * + ver | mtyp | len | token | + * +------+------+------+.......................+ + * + 0x01 | 0x02 | 0x02 | up to 2^16 - 1 octets | + * +------+------+------+.......................+ + * + * Where: + * + * - "ver" is the protocol version number, here 1 to represent the + * first version of the SOCKS/GSS-API protocol + * + * - "mtyp" is the message type, here 2 to represent a protection + * -level negotiation message + * + * - "len" is the length of the "token" field in octets + * + * - "token" is the GSS-API encapsulated protection level + * + * The token is produced by encapsulating an octet containing the + * required protection level using gss_seal()/gss_wrap() with conf_req + * set to FALSE. The token is verified using gss_unseal()/ + * gss_unwrap(). + * + */ + if(data->set.socks5_gssapi_nec) { + us_length = htons((short)1); + memcpy(socksreq + 2, &us_length, sizeof(short)); + } + else { + gss_send_token.length = 1; + gss_send_token.value = Curl_memdup(&gss_enc, 1); + if(!gss_send_token.value) { + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_OUT_OF_MEMORY; + } + + gss_major_status = gss_wrap(&gss_minor_status, gss_context, 0, + GSS_C_QOP_DEFAULT, &gss_send_token, + &gss_conf_state, &gss_w_token); + + if(check_gss_err(data, gss_major_status, gss_minor_status, "gss_wrap")) { + gss_release_buffer(&gss_status, &gss_send_token); + gss_release_buffer(&gss_status, &gss_w_token); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + failf(data, "Failed to wrap GSS-API encryption value into token."); + return CURLE_COULDNT_CONNECT; + } + gss_release_buffer(&gss_status, &gss_send_token); + + us_length = htons((short)gss_w_token.length); + memcpy(socksreq + 2, &us_length, sizeof(short)); + } + + nwritten = Curl_conn_cf_send(cf->next, data, (char *)socksreq, 4, &code); + if(code || (4 != nwritten)) { + failf(data, "Failed to send GSS-API encryption request."); + gss_release_buffer(&gss_status, &gss_w_token); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + if(data->set.socks5_gssapi_nec) { + memcpy(socksreq, &gss_enc, 1); + nwritten = Curl_conn_cf_send(cf->next, data, (char *)socksreq, 1, &code); + if(code || ( 1 != nwritten)) { + failf(data, "Failed to send GSS-API encryption type."); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + } + else { + nwritten = Curl_conn_cf_send(cf->next, data, + (char *)gss_w_token.value, + gss_w_token.length, &code); + if(code || ((ssize_t)gss_w_token.length != nwritten)) { + failf(data, "Failed to send GSS-API encryption type."); + gss_release_buffer(&gss_status, &gss_w_token); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + gss_release_buffer(&gss_status, &gss_w_token); + } + + result = Curl_blockread_all(cf, data, (char *)socksreq, 4, &actualread); + if(result || (actualread != 4)) { + failf(data, "Failed to receive GSS-API encryption response."); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + /* ignore the first (VER) byte */ + if(socksreq[1] == 255) { /* status / message type */ + failf(data, "User was rejected by the SOCKS5 server (%d %d).", + socksreq[0], socksreq[1]); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + if(socksreq[1] != 2) { /* status / message type */ + failf(data, "Invalid GSS-API encryption response type (%d %d).", + socksreq[0], socksreq[1]); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + memcpy(&us_length, socksreq + 2, sizeof(short)); + us_length = ntohs(us_length); + + gss_recv_token.length = us_length; + gss_recv_token.value = malloc(gss_recv_token.length); + if(!gss_recv_token.value) { + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_OUT_OF_MEMORY; + } + result = Curl_blockread_all(cf, data, (char *)gss_recv_token.value, + gss_recv_token.length, &actualread); + + if(result || (actualread != us_length)) { + failf(data, "Failed to receive GSS-API encryption type."); + gss_release_buffer(&gss_status, &gss_recv_token); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + if(!data->set.socks5_gssapi_nec) { + gss_major_status = gss_unwrap(&gss_minor_status, gss_context, + &gss_recv_token, &gss_w_token, + 0, GSS_C_QOP_DEFAULT); + + if(check_gss_err(data, gss_major_status, gss_minor_status, "gss_unwrap")) { + gss_release_buffer(&gss_status, &gss_recv_token); + gss_release_buffer(&gss_status, &gss_w_token); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + failf(data, "Failed to unwrap GSS-API encryption value into token."); + return CURLE_COULDNT_CONNECT; + } + gss_release_buffer(&gss_status, &gss_recv_token); + + if(gss_w_token.length != 1) { + failf(data, "Invalid GSS-API encryption response length (%zu).", + gss_w_token.length); + gss_release_buffer(&gss_status, &gss_w_token); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + memcpy(socksreq, gss_w_token.value, gss_w_token.length); + gss_release_buffer(&gss_status, &gss_w_token); + } + else { + if(gss_recv_token.length != 1) { + failf(data, "Invalid GSS-API encryption response length (%zu).", + gss_recv_token.length); + gss_release_buffer(&gss_status, &gss_recv_token); + gss_delete_sec_context(&gss_status, &gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + memcpy(socksreq, gss_recv_token.value, gss_recv_token.length); + gss_release_buffer(&gss_status, &gss_recv_token); + } + + (void)curlx_nonblock(sock, TRUE); + + infof(data, "SOCKS5 access with%s protection granted.", + (socksreq[0] == 0)?"out GSS-API data": + ((socksreq[0] == 1)?" GSS-API integrity":" GSS-API confidentiality")); + + conn->socks5_gssapi_enctype = socksreq[0]; + if(socksreq[0] == 0) + gss_delete_sec_context(&gss_status, &gss_context, NULL); + + return CURLE_OK; +} + +#endif /* HAVE_GSSAPI && !CURL_DISABLE_PROXY */ diff --git a/third_party/curl/lib/socks_sspi.c b/third_party/curl/lib/socks_sspi.c new file mode 100644 index 0000000..2baae2c --- /dev/null +++ b/third_party/curl/lib/socks_sspi.c @@ -0,0 +1,620 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (C) Markus Moeller, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_WINDOWS_SSPI) && !defined(CURL_DISABLE_PROXY) + +#include "urldata.h" +#include "sendf.h" +#include "cfilters.h" +#include "connect.h" +#include "strerror.h" +#include "timeval.h" +#include "socks.h" +#include "curl_sspi.h" +#include "curl_multibyte.h" +#include "warnless.h" +#include "strdup.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Helper sspi error functions. + */ +static int check_sspi_err(struct Curl_easy *data, + SECURITY_STATUS status, + const char *function) +{ + if(status != SEC_E_OK && + status != SEC_I_COMPLETE_AND_CONTINUE && + status != SEC_I_COMPLETE_NEEDED && + status != SEC_I_CONTINUE_NEEDED) { + char buffer[STRERROR_LEN]; + failf(data, "SSPI error: %s failed: %s", function, + Curl_sspi_strerror(status, buffer, sizeof(buffer))); + return 1; + } + return 0; +} + +/* This is the SSPI-using version of this function */ +CURLcode Curl_SOCKS5_gssapi_negotiate(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct connectdata *conn = cf->conn; + curl_socket_t sock = conn->sock[cf->sockindex]; + CURLcode code; + ssize_t actualread; + ssize_t written; + int result; + /* Needs GSS-API authentication */ + SECURITY_STATUS status; + unsigned long sspi_ret_flags = 0; + unsigned char gss_enc; + SecBuffer sspi_send_token, sspi_recv_token, sspi_w_token[3]; + SecBufferDesc input_desc, output_desc, wrap_desc; + SecPkgContext_Sizes sspi_sizes; + CredHandle cred_handle; + CtxtHandle sspi_context; + PCtxtHandle context_handle = NULL; + SecPkgCredentials_Names names; + TimeStamp expiry; + char *service_name = NULL; + unsigned short us_length; + unsigned long qop; + unsigned char socksreq[4]; /* room for GSS-API exchange header only */ + const char *service = data->set.str[STRING_PROXY_SERVICE_NAME] ? + data->set.str[STRING_PROXY_SERVICE_NAME] : "rcmd"; + const size_t service_length = strlen(service); + + /* GSS-API request looks like + * +----+------+-----+----------------+ + * |VER | MTYP | LEN | TOKEN | + * +----+------+----------------------+ + * | 1 | 1 | 2 | up to 2^16 - 1 | + * +----+------+-----+----------------+ + */ + + /* prepare service name */ + if(strchr(service, '/')) { + service_name = strdup(service); + if(!service_name) + return CURLE_OUT_OF_MEMORY; + } + else { + service_name = malloc(service_length + + strlen(conn->socks_proxy.host.name) + 2); + if(!service_name) + return CURLE_OUT_OF_MEMORY; + msnprintf(service_name, service_length + + strlen(conn->socks_proxy.host.name) + 2, "%s/%s", + service, conn->socks_proxy.host.name); + } + + input_desc.cBuffers = 1; + input_desc.pBuffers = &sspi_recv_token; + input_desc.ulVersion = SECBUFFER_VERSION; + + sspi_recv_token.BufferType = SECBUFFER_TOKEN; + sspi_recv_token.cbBuffer = 0; + sspi_recv_token.pvBuffer = NULL; + + output_desc.cBuffers = 1; + output_desc.pBuffers = &sspi_send_token; + output_desc.ulVersion = SECBUFFER_VERSION; + + sspi_send_token.BufferType = SECBUFFER_TOKEN; + sspi_send_token.cbBuffer = 0; + sspi_send_token.pvBuffer = NULL; + + wrap_desc.cBuffers = 3; + wrap_desc.pBuffers = sspi_w_token; + wrap_desc.ulVersion = SECBUFFER_VERSION; + + cred_handle.dwLower = 0; + cred_handle.dwUpper = 0; + + status = s_pSecFn->AcquireCredentialsHandle(NULL, + (TCHAR *) TEXT("Kerberos"), + SECPKG_CRED_OUTBOUND, + NULL, + NULL, + NULL, + NULL, + &cred_handle, + &expiry); + + if(check_sspi_err(data, status, "AcquireCredentialsHandle")) { + failf(data, "Failed to acquire credentials."); + free(service_name); + s_pSecFn->FreeCredentialsHandle(&cred_handle); + return CURLE_COULDNT_CONNECT; + } + + (void)curlx_nonblock(sock, FALSE); + + /* As long as we need to keep sending some context info, and there's no */ + /* errors, keep sending it... */ + for(;;) { + TCHAR *sname; + + sname = curlx_convert_UTF8_to_tchar(service_name); + if(!sname) + return CURLE_OUT_OF_MEMORY; + + status = s_pSecFn->InitializeSecurityContext(&cred_handle, + context_handle, + sname, + ISC_REQ_MUTUAL_AUTH | + ISC_REQ_ALLOCATE_MEMORY | + ISC_REQ_CONFIDENTIALITY | + ISC_REQ_REPLAY_DETECT, + 0, + SECURITY_NATIVE_DREP, + &input_desc, + 0, + &sspi_context, + &output_desc, + &sspi_ret_flags, + &expiry); + + curlx_unicodefree(sname); + + if(sspi_recv_token.pvBuffer) { + s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer); + sspi_recv_token.pvBuffer = NULL; + sspi_recv_token.cbBuffer = 0; + } + + if(check_sspi_err(data, status, "InitializeSecurityContext")) { + free(service_name); + s_pSecFn->FreeCredentialsHandle(&cred_handle); + s_pSecFn->DeleteSecurityContext(&sspi_context); + if(sspi_recv_token.pvBuffer) + s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer); + failf(data, "Failed to initialise security context."); + return CURLE_COULDNT_CONNECT; + } + + if(sspi_send_token.cbBuffer) { + socksreq[0] = 1; /* GSS-API subnegotiation version */ + socksreq[1] = 1; /* authentication message type */ + us_length = htons((short)sspi_send_token.cbBuffer); + memcpy(socksreq + 2, &us_length, sizeof(short)); + + written = Curl_conn_cf_send(cf->next, data, (char *)socksreq, 4, &code); + if(code || (4 != written)) { + failf(data, "Failed to send SSPI authentication request."); + free(service_name); + if(sspi_send_token.pvBuffer) + s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer); + if(sspi_recv_token.pvBuffer) + s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer); + s_pSecFn->FreeCredentialsHandle(&cred_handle); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_COULDNT_CONNECT; + } + + written = Curl_conn_cf_send(cf->next, data, + (char *)sspi_send_token.pvBuffer, + sspi_send_token.cbBuffer, &code); + if(code || (sspi_send_token.cbBuffer != (size_t)written)) { + failf(data, "Failed to send SSPI authentication token."); + free(service_name); + if(sspi_send_token.pvBuffer) + s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer); + if(sspi_recv_token.pvBuffer) + s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer); + s_pSecFn->FreeCredentialsHandle(&cred_handle); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_COULDNT_CONNECT; + } + + } + + if(sspi_send_token.pvBuffer) { + s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer); + sspi_send_token.pvBuffer = NULL; + } + sspi_send_token.cbBuffer = 0; + + if(sspi_recv_token.pvBuffer) { + s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer); + sspi_recv_token.pvBuffer = NULL; + } + sspi_recv_token.cbBuffer = 0; + + if(status != SEC_I_CONTINUE_NEEDED) + break; + + /* analyse response */ + + /* GSS-API response looks like + * +----+------+-----+----------------+ + * |VER | MTYP | LEN | TOKEN | + * +----+------+----------------------+ + * | 1 | 1 | 2 | up to 2^16 - 1 | + * +----+------+-----+----------------+ + */ + + result = Curl_blockread_all(cf, data, (char *)socksreq, 4, &actualread); + if(result || (actualread != 4)) { + failf(data, "Failed to receive SSPI authentication response."); + free(service_name); + s_pSecFn->FreeCredentialsHandle(&cred_handle); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_COULDNT_CONNECT; + } + + /* ignore the first (VER) byte */ + if(socksreq[1] == 255) { /* status / message type */ + failf(data, "User was rejected by the SOCKS5 server (%u %u).", + (unsigned int)socksreq[0], (unsigned int)socksreq[1]); + free(service_name); + s_pSecFn->FreeCredentialsHandle(&cred_handle); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_COULDNT_CONNECT; + } + + if(socksreq[1] != 1) { /* status / message type */ + failf(data, "Invalid SSPI authentication response type (%u %u).", + (unsigned int)socksreq[0], (unsigned int)socksreq[1]); + free(service_name); + s_pSecFn->FreeCredentialsHandle(&cred_handle); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_COULDNT_CONNECT; + } + + memcpy(&us_length, socksreq + 2, sizeof(short)); + us_length = ntohs(us_length); + + sspi_recv_token.cbBuffer = us_length; + sspi_recv_token.pvBuffer = malloc(us_length); + + if(!sspi_recv_token.pvBuffer) { + free(service_name); + s_pSecFn->FreeCredentialsHandle(&cred_handle); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_OUT_OF_MEMORY; + } + result = Curl_blockread_all(cf, data, (char *)sspi_recv_token.pvBuffer, + sspi_recv_token.cbBuffer, &actualread); + + if(result || (actualread != us_length)) { + failf(data, "Failed to receive SSPI authentication token."); + free(service_name); + if(sspi_recv_token.pvBuffer) + s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer); + s_pSecFn->FreeCredentialsHandle(&cred_handle); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_COULDNT_CONNECT; + } + + context_handle = &sspi_context; + } + + free(service_name); + + /* Everything is good so far, user was authenticated! */ + status = s_pSecFn->QueryCredentialsAttributes(&cred_handle, + SECPKG_CRED_ATTR_NAMES, + &names); + s_pSecFn->FreeCredentialsHandle(&cred_handle); + if(check_sspi_err(data, status, "QueryCredentialAttributes")) { + s_pSecFn->DeleteSecurityContext(&sspi_context); + s_pSecFn->FreeContextBuffer(names.sUserName); + failf(data, "Failed to determine user name."); + return CURLE_COULDNT_CONNECT; + } + else { +#ifndef CURL_DISABLE_VERBOSE_STRINGS + char *user_utf8 = curlx_convert_tchar_to_UTF8(names.sUserName); + infof(data, "SOCKS5 server authenticated user %s with GSS-API.", + (user_utf8 ? user_utf8 : "(unknown)")); + curlx_unicodefree(user_utf8); +#endif + s_pSecFn->FreeContextBuffer(names.sUserName); + } + + /* Do encryption */ + socksreq[0] = 1; /* GSS-API subnegotiation version */ + socksreq[1] = 2; /* encryption message type */ + + gss_enc = 0; /* no data protection */ + /* do confidentiality protection if supported */ + if(sspi_ret_flags & ISC_REQ_CONFIDENTIALITY) + gss_enc = 2; + /* else do integrity protection */ + else if(sspi_ret_flags & ISC_REQ_INTEGRITY) + gss_enc = 1; + + infof(data, "SOCKS5 server supports GSS-API %s data protection.", + (gss_enc == 0)?"no":((gss_enc == 1)?"integrity":"confidentiality") ); + /* force to no data protection, avoid encryption/decryption for now */ + gss_enc = 0; + /* + * Sending the encryption type in clear seems wrong. It should be + * protected with gss_seal()/gss_wrap(). See RFC1961 extract below + * The NEC reference implementations on which this is based is + * therefore at fault + * + * +------+------+------+.......................+ + * + ver | mtyp | len | token | + * +------+------+------+.......................+ + * + 0x01 | 0x02 | 0x02 | up to 2^16 - 1 octets | + * +------+------+------+.......................+ + * + * Where: + * + * - "ver" is the protocol version number, here 1 to represent the + * first version of the SOCKS/GSS-API protocol + * + * - "mtyp" is the message type, here 2 to represent a protection + * -level negotiation message + * + * - "len" is the length of the "token" field in octets + * + * - "token" is the GSS-API encapsulated protection level + * + * The token is produced by encapsulating an octet containing the + * required protection level using gss_seal()/gss_wrap() with conf_req + * set to FALSE. The token is verified using gss_unseal()/ + * gss_unwrap(). + * + */ + + if(data->set.socks5_gssapi_nec) { + us_length = htons((short)1); + memcpy(socksreq + 2, &us_length, sizeof(short)); + } + else { + status = s_pSecFn->QueryContextAttributes(&sspi_context, + SECPKG_ATTR_SIZES, + &sspi_sizes); + if(check_sspi_err(data, status, "QueryContextAttributes")) { + s_pSecFn->DeleteSecurityContext(&sspi_context); + failf(data, "Failed to query security context attributes."); + return CURLE_COULDNT_CONNECT; + } + + sspi_w_token[0].cbBuffer = sspi_sizes.cbSecurityTrailer; + sspi_w_token[0].BufferType = SECBUFFER_TOKEN; + sspi_w_token[0].pvBuffer = malloc(sspi_sizes.cbSecurityTrailer); + + if(!sspi_w_token[0].pvBuffer) { + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_OUT_OF_MEMORY; + } + + sspi_w_token[1].cbBuffer = 1; + sspi_w_token[1].pvBuffer = malloc(1); + if(!sspi_w_token[1].pvBuffer) { + s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_OUT_OF_MEMORY; + } + + memcpy(sspi_w_token[1].pvBuffer, &gss_enc, 1); + sspi_w_token[2].BufferType = SECBUFFER_PADDING; + sspi_w_token[2].cbBuffer = sspi_sizes.cbBlockSize; + sspi_w_token[2].pvBuffer = malloc(sspi_sizes.cbBlockSize); + if(!sspi_w_token[2].pvBuffer) { + s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); + s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_OUT_OF_MEMORY; + } + status = s_pSecFn->EncryptMessage(&sspi_context, + KERB_WRAP_NO_ENCRYPT, + &wrap_desc, + 0); + if(check_sspi_err(data, status, "EncryptMessage")) { + s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); + s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer); + s_pSecFn->FreeContextBuffer(sspi_w_token[2].pvBuffer); + s_pSecFn->DeleteSecurityContext(&sspi_context); + failf(data, "Failed to query security context attributes."); + return CURLE_COULDNT_CONNECT; + } + sspi_send_token.cbBuffer = sspi_w_token[0].cbBuffer + + sspi_w_token[1].cbBuffer + + sspi_w_token[2].cbBuffer; + sspi_send_token.pvBuffer = malloc(sspi_send_token.cbBuffer); + if(!sspi_send_token.pvBuffer) { + s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); + s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer); + s_pSecFn->FreeContextBuffer(sspi_w_token[2].pvBuffer); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_OUT_OF_MEMORY; + } + + memcpy(sspi_send_token.pvBuffer, sspi_w_token[0].pvBuffer, + sspi_w_token[0].cbBuffer); + memcpy((PUCHAR) sspi_send_token.pvBuffer +(int)sspi_w_token[0].cbBuffer, + sspi_w_token[1].pvBuffer, sspi_w_token[1].cbBuffer); + memcpy((PUCHAR) sspi_send_token.pvBuffer + + sspi_w_token[0].cbBuffer + + sspi_w_token[1].cbBuffer, + sspi_w_token[2].pvBuffer, sspi_w_token[2].cbBuffer); + + s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); + sspi_w_token[0].pvBuffer = NULL; + sspi_w_token[0].cbBuffer = 0; + s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer); + sspi_w_token[1].pvBuffer = NULL; + sspi_w_token[1].cbBuffer = 0; + s_pSecFn->FreeContextBuffer(sspi_w_token[2].pvBuffer); + sspi_w_token[2].pvBuffer = NULL; + sspi_w_token[2].cbBuffer = 0; + + us_length = htons((short)sspi_send_token.cbBuffer); + memcpy(socksreq + 2, &us_length, sizeof(short)); + } + + written = Curl_conn_cf_send(cf->next, data, (char *)socksreq, 4, &code); + if(code || (4 != written)) { + failf(data, "Failed to send SSPI encryption request."); + if(sspi_send_token.pvBuffer) + s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_COULDNT_CONNECT; + } + + if(data->set.socks5_gssapi_nec) { + memcpy(socksreq, &gss_enc, 1); + written = Curl_conn_cf_send(cf->next, data, (char *)socksreq, 1, &code); + if(code || (1 != written)) { + failf(data, "Failed to send SSPI encryption type."); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_COULDNT_CONNECT; + } + } + else { + written = Curl_conn_cf_send(cf->next, data, + (char *)sspi_send_token.pvBuffer, + sspi_send_token.cbBuffer, &code); + if(code || (sspi_send_token.cbBuffer != (size_t)written)) { + failf(data, "Failed to send SSPI encryption type."); + if(sspi_send_token.pvBuffer) + s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_COULDNT_CONNECT; + } + if(sspi_send_token.pvBuffer) + s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer); + } + + result = Curl_blockread_all(cf, data, (char *)socksreq, 4, &actualread); + if(result || (actualread != 4)) { + failf(data, "Failed to receive SSPI encryption response."); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_COULDNT_CONNECT; + } + + /* ignore the first (VER) byte */ + if(socksreq[1] == 255) { /* status / message type */ + failf(data, "User was rejected by the SOCKS5 server (%u %u).", + (unsigned int)socksreq[0], (unsigned int)socksreq[1]); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_COULDNT_CONNECT; + } + + if(socksreq[1] != 2) { /* status / message type */ + failf(data, "Invalid SSPI encryption response type (%u %u).", + (unsigned int)socksreq[0], (unsigned int)socksreq[1]); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_COULDNT_CONNECT; + } + + memcpy(&us_length, socksreq + 2, sizeof(short)); + us_length = ntohs(us_length); + + sspi_w_token[0].cbBuffer = us_length; + sspi_w_token[0].pvBuffer = malloc(us_length); + if(!sspi_w_token[0].pvBuffer) { + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_OUT_OF_MEMORY; + } + + result = Curl_blockread_all(cf, data, (char *)sspi_w_token[0].pvBuffer, + sspi_w_token[0].cbBuffer, &actualread); + + if(result || (actualread != us_length)) { + failf(data, "Failed to receive SSPI encryption type."); + s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_COULDNT_CONNECT; + } + + + if(!data->set.socks5_gssapi_nec) { + wrap_desc.cBuffers = 2; + sspi_w_token[0].BufferType = SECBUFFER_STREAM; + sspi_w_token[1].BufferType = SECBUFFER_DATA; + sspi_w_token[1].cbBuffer = 0; + sspi_w_token[1].pvBuffer = NULL; + + status = s_pSecFn->DecryptMessage(&sspi_context, + &wrap_desc, + 0, + &qop); + + if(check_sspi_err(data, status, "DecryptMessage")) { + if(sspi_w_token[0].pvBuffer) + s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); + if(sspi_w_token[1].pvBuffer) + s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer); + s_pSecFn->DeleteSecurityContext(&sspi_context); + failf(data, "Failed to query security context attributes."); + return CURLE_COULDNT_CONNECT; + } + + if(sspi_w_token[1].cbBuffer != 1) { + failf(data, "Invalid SSPI encryption response length (%lu).", + (unsigned long)sspi_w_token[1].cbBuffer); + if(sspi_w_token[0].pvBuffer) + s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); + if(sspi_w_token[1].pvBuffer) + s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_COULDNT_CONNECT; + } + + memcpy(socksreq, sspi_w_token[1].pvBuffer, sspi_w_token[1].cbBuffer); + s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); + s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer); + } + else { + if(sspi_w_token[0].cbBuffer != 1) { + failf(data, "Invalid SSPI encryption response length (%lu).", + (unsigned long)sspi_w_token[0].cbBuffer); + s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); + s_pSecFn->DeleteSecurityContext(&sspi_context); + return CURLE_COULDNT_CONNECT; + } + memcpy(socksreq, sspi_w_token[0].pvBuffer, sspi_w_token[0].cbBuffer); + s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); + } + (void)curlx_nonblock(sock, TRUE); + + infof(data, "SOCKS5 access with%s protection granted.", + (socksreq[0] == 0)?"out GSS-API data": + ((socksreq[0] == 1)?" GSS-API integrity":" GSS-API confidentiality")); + + /* For later use if encryption is required + conn->socks5_gssapi_enctype = socksreq[0]; + if(socksreq[0] != 0) + conn->socks5_sspi_context = sspi_context; + else { + s_pSecFn->DeleteSecurityContext(&sspi_context); + conn->socks5_sspi_context = sspi_context; + } + */ + return CURLE_OK; +} +#endif diff --git a/third_party/curl/lib/speedcheck.c b/third_party/curl/lib/speedcheck.c new file mode 100644 index 0000000..580efbd --- /dev/null +++ b/third_party/curl/lib/speedcheck.c @@ -0,0 +1,79 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include +#include "urldata.h" +#include "sendf.h" +#include "multiif.h" +#include "speedcheck.h" + +void Curl_speedinit(struct Curl_easy *data) +{ + memset(&data->state.keeps_speed, 0, sizeof(struct curltime)); +} + +/* + * @unittest: 1606 + */ +CURLcode Curl_speedcheck(struct Curl_easy *data, + struct curltime now) +{ + if(data->req.keepon & KEEP_RECV_PAUSE) + /* A paused transfer is not qualified for speed checks */ + return CURLE_OK; + + if((data->progress.current_speed >= 0) && data->set.low_speed_time) { + if(data->progress.current_speed < data->set.low_speed_limit) { + if(!data->state.keeps_speed.tv_sec) + /* under the limit at this very moment */ + data->state.keeps_speed = now; + else { + /* how long has it been under the limit */ + timediff_t howlong = Curl_timediff(now, data->state.keeps_speed); + + if(howlong >= data->set.low_speed_time * 1000) { + /* too long */ + failf(data, + "Operation too slow. " + "Less than %ld bytes/sec transferred the last %ld seconds", + data->set.low_speed_limit, + data->set.low_speed_time); + return CURLE_OPERATION_TIMEDOUT; + } + } + } + else + /* faster right now */ + data->state.keeps_speed.tv_sec = 0; + } + + if(data->set.low_speed_limit) + /* if low speed limit is enabled, set the expire timer to make this + connection's speed get checked again in a second */ + Curl_expire(data, 1000, EXPIRE_SPEEDCHECK); + + return CURLE_OK; +} diff --git a/third_party/curl/lib/speedcheck.h b/third_party/curl/lib/speedcheck.h new file mode 100644 index 0000000..bff2f32 --- /dev/null +++ b/third_party/curl/lib/speedcheck.h @@ -0,0 +1,35 @@ +#ifndef HEADER_CURL_SPEEDCHECK_H +#define HEADER_CURL_SPEEDCHECK_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "timeval.h" + +void Curl_speedinit(struct Curl_easy *data); +CURLcode Curl_speedcheck(struct Curl_easy *data, + struct curltime now); + +#endif /* HEADER_CURL_SPEEDCHECK_H */ diff --git a/third_party/curl/lib/splay.c b/third_party/curl/lib/splay.c new file mode 100644 index 0000000..48e079b --- /dev/null +++ b/third_party/curl/lib/splay.c @@ -0,0 +1,278 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "splay.h" + +/* + * This macro compares two node keys i and j and returns: + * + * negative value: when i is smaller than j + * zero : when i is equal to j + * positive when : when i is larger than j + */ +#define compare(i,j) Curl_splaycomparekeys((i),(j)) + +/* + * Splay using the key i (which may or may not be in the tree.) The starting + * root is t. + */ +struct Curl_tree *Curl_splay(struct curltime i, + struct Curl_tree *t) +{ + struct Curl_tree N, *l, *r, *y; + + if(!t) + return t; + N.smaller = N.larger = NULL; + l = r = &N; + + for(;;) { + long comp = compare(i, t->key); + if(comp < 0) { + if(!t->smaller) + break; + if(compare(i, t->smaller->key) < 0) { + y = t->smaller; /* rotate smaller */ + t->smaller = y->larger; + y->larger = t; + t = y; + if(!t->smaller) + break; + } + r->smaller = t; /* link smaller */ + r = t; + t = t->smaller; + } + else if(comp > 0) { + if(!t->larger) + break; + if(compare(i, t->larger->key) > 0) { + y = t->larger; /* rotate larger */ + t->larger = y->smaller; + y->smaller = t; + t = y; + if(!t->larger) + break; + } + l->larger = t; /* link larger */ + l = t; + t = t->larger; + } + else + break; + } + + l->larger = t->smaller; /* assemble */ + r->smaller = t->larger; + t->smaller = N.larger; + t->larger = N.smaller; + + return t; +} + +/* Insert key i into the tree t. Return a pointer to the resulting tree or + * NULL if something went wrong. + * + * @unittest: 1309 + */ +struct Curl_tree *Curl_splayinsert(struct curltime i, + struct Curl_tree *t, + struct Curl_tree *node) +{ + static const struct curltime KEY_NOTUSED = { + ~0, -1 + }; /* will *NEVER* appear */ + + if(!node) + return t; + + if(t) { + t = Curl_splay(i, t); + if(compare(i, t->key) == 0) { + /* There already exists a node in the tree with the very same key. Build + a doubly-linked circular list of nodes. We add the new 'node' struct + to the end of this list. */ + + node->key = KEY_NOTUSED; /* we set the key in the sub node to NOTUSED + to quickly identify this node as a subnode */ + node->samen = t; + node->samep = t->samep; + t->samep->samen = node; + t->samep = node; + + return t; /* the root node always stays the same */ + } + } + + if(!t) { + node->smaller = node->larger = NULL; + } + else if(compare(i, t->key) < 0) { + node->smaller = t->smaller; + node->larger = t; + t->smaller = NULL; + + } + else { + node->larger = t->larger; + node->smaller = t; + t->larger = NULL; + } + node->key = i; + + /* no identical nodes (yet), we are the only one in the list of nodes */ + node->samen = node; + node->samep = node; + return node; +} + +/* Finds and deletes the best-fit node from the tree. Return a pointer to the + resulting tree. best-fit means the smallest node if it is not larger than + the key */ +struct Curl_tree *Curl_splaygetbest(struct curltime i, + struct Curl_tree *t, + struct Curl_tree **removed) +{ + static const struct curltime tv_zero = {0, 0}; + struct Curl_tree *x; + + if(!t) { + *removed = NULL; /* none removed since there was no root */ + return NULL; + } + + /* find smallest */ + t = Curl_splay(tv_zero, t); + if(compare(i, t->key) < 0) { + /* even the smallest is too big */ + *removed = NULL; + return t; + } + + /* FIRST! Check if there is a list with identical keys */ + x = t->samen; + if(x != t) { + /* there is, pick one from the list */ + + /* 'x' is the new root node */ + + x->key = t->key; + x->larger = t->larger; + x->smaller = t->smaller; + x->samep = t->samep; + t->samep->samen = x; + + *removed = t; + return x; /* new root */ + } + + /* we splayed the tree to the smallest element, there is no smaller */ + x = t->larger; + *removed = t; + + return x; +} + + +/* Deletes the very node we point out from the tree if it's there. Stores a + * pointer to the new resulting tree in 'newroot'. + * + * Returns zero on success and non-zero on errors! + * When returning error, it does not touch the 'newroot' pointer. + * + * NOTE: when the last node of the tree is removed, there's no tree left so + * 'newroot' will be made to point to NULL. + * + * @unittest: 1309 + */ +int Curl_splayremove(struct Curl_tree *t, + struct Curl_tree *removenode, + struct Curl_tree **newroot) +{ + static const struct curltime KEY_NOTUSED = { + ~0, -1 + }; /* will *NEVER* appear */ + struct Curl_tree *x; + + if(!t || !removenode) + return 1; + + if(compare(KEY_NOTUSED, removenode->key) == 0) { + /* Key set to NOTUSED means it is a subnode within a 'same' linked list + and thus we can unlink it easily. */ + if(removenode->samen == removenode) + /* A non-subnode should never be set to KEY_NOTUSED */ + return 3; + + removenode->samep->samen = removenode->samen; + removenode->samen->samep = removenode->samep; + + /* Ensures that double-remove gets caught. */ + removenode->samen = removenode; + + *newroot = t; /* return the same root */ + return 0; + } + + t = Curl_splay(removenode->key, t); + + /* First make sure that we got the same root node as the one we want + to remove, as otherwise we might be trying to remove a node that + isn't actually in the tree. + + We cannot just compare the keys here as a double remove in quick + succession of a node with key != KEY_NOTUSED && same != NULL + could return the same key but a different node. */ + if(t != removenode) + return 2; + + /* Check if there is a list with identical sizes, as then we're trying to + remove the root node of a list of nodes with identical keys. */ + x = t->samen; + if(x != t) { + /* 'x' is the new root node, we just make it use the root node's + smaller/larger links */ + + x->key = t->key; + x->larger = t->larger; + x->smaller = t->smaller; + x->samep = t->samep; + t->samep->samen = x; + } + else { + /* Remove the root node */ + if(!t->smaller) + x = t->larger; + else { + x = Curl_splay(removenode->key, t->smaller); + x->larger = t->larger; + } + } + + *newroot = x; /* store new root pointer */ + + return 0; +} diff --git a/third_party/curl/lib/splay.h b/third_party/curl/lib/splay.h new file mode 100644 index 0000000..dd1d07a --- /dev/null +++ b/third_party/curl/lib/splay.h @@ -0,0 +1,58 @@ +#ifndef HEADER_CURL_SPLAY_H +#define HEADER_CURL_SPLAY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "timeval.h" + +struct Curl_tree { + struct Curl_tree *smaller; /* smaller node */ + struct Curl_tree *larger; /* larger node */ + struct Curl_tree *samen; /* points to the next node with identical key */ + struct Curl_tree *samep; /* points to the prev node with identical key */ + struct curltime key; /* this node's "sort" key */ + void *payload; /* data the splay code doesn't care about */ +}; + +struct Curl_tree *Curl_splay(struct curltime i, + struct Curl_tree *t); + +struct Curl_tree *Curl_splayinsert(struct curltime key, + struct Curl_tree *t, + struct Curl_tree *newnode); + +struct Curl_tree *Curl_splaygetbest(struct curltime key, + struct Curl_tree *t, + struct Curl_tree **removed); + +int Curl_splayremove(struct Curl_tree *t, + struct Curl_tree *removenode, + struct Curl_tree **newroot); + +#define Curl_splaycomparekeys(i,j) ( ((i.tv_sec) < (j.tv_sec)) ? -1 : \ + ( ((i.tv_sec) > (j.tv_sec)) ? 1 : \ + ( ((i.tv_usec) < (j.tv_usec)) ? -1 : \ + ( ((i.tv_usec) > (j.tv_usec)) ? 1 : 0)))) + +#endif /* HEADER_CURL_SPLAY_H */ diff --git a/third_party/curl/lib/strcase.c b/third_party/curl/lib/strcase.c new file mode 100644 index 0000000..14d76f7 --- /dev/null +++ b/third_party/curl/lib/strcase.c @@ -0,0 +1,204 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "strcase.h" + +/* Mapping table to go from lowercase to uppercase for plain ASCII.*/ +static const unsigned char touppermap[256] = { +0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, +22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, +41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, +60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, +79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 65, +66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, +85, 86, 87, 88, 89, 90, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, +134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, +150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, +166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, +182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, +198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, +214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, +230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, +246, 247, 248, 249, 250, 251, 252, 253, 254, 255 +}; + +/* Mapping table to go from uppercase to lowercase for plain ASCII.*/ +static const unsigned char tolowermap[256] = { +0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, +22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, +42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, +62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, +111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 91, 92, 93, 94, 95, +96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, +112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, +128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, +144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, +160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, +176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, +192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, +208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, +224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, +240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255 +}; + + +/* Portable, consistent toupper. Do not use toupper() because its behavior is + altered by the current locale. */ +char Curl_raw_toupper(char in) +{ + return (char)touppermap[(unsigned char) in]; +} + + +/* Portable, consistent tolower. Do not use tolower() because its behavior is + altered by the current locale. */ +char Curl_raw_tolower(char in) +{ + return (char)tolowermap[(unsigned char) in]; +} + +/* + * curl_strequal() is for doing "raw" case insensitive strings. This is meant + * to be locale independent and only compare strings we know are safe for + * this. See https://daniel.haxx.se/blog/2008/10/15/strcasecmp-in-turkish/ for + * further explanations as to why this function is necessary. + */ + +static int casecompare(const char *first, const char *second) +{ + while(*first && *second) { + if(Curl_raw_toupper(*first) != Curl_raw_toupper(*second)) + /* get out of the loop as soon as they don't match */ + return 0; + first++; + second++; + } + /* If we're here either the strings are the same or the length is different. + We can just test if the "current" character is non-zero for one and zero + for the other. Note that the characters may not be exactly the same even + if they match, we only want to compare zero-ness. */ + return !*first == !*second; +} + +/* --- public function --- */ +int curl_strequal(const char *first, const char *second) +{ + if(first && second) + /* both pointers point to something then compare them */ + return casecompare(first, second); + + /* if both pointers are NULL then treat them as equal */ + return (NULL == first && NULL == second); +} + +static int ncasecompare(const char *first, const char *second, size_t max) +{ + while(*first && *second && max) { + if(Curl_raw_toupper(*first) != Curl_raw_toupper(*second)) + return 0; + max--; + first++; + second++; + } + if(0 == max) + return 1; /* they are equal this far */ + + return Curl_raw_toupper(*first) == Curl_raw_toupper(*second); +} + +/* --- public function --- */ +int curl_strnequal(const char *first, const char *second, size_t max) +{ + if(first && second) + /* both pointers point to something then compare them */ + return ncasecompare(first, second, max); + + /* if both pointers are NULL then treat them as equal if max is non-zero */ + return (NULL == first && NULL == second && max); +} +/* Copy an upper case version of the string from src to dest. The + * strings may overlap. No more than n characters of the string are copied + * (including any NUL) and the destination string will NOT be + * NUL-terminated if that limit is reached. + */ +void Curl_strntoupper(char *dest, const char *src, size_t n) +{ + if(n < 1) + return; + + do { + *dest++ = Curl_raw_toupper(*src); + } while(*src++ && --n); +} + +/* Copy a lower case version of the string from src to dest. The + * strings may overlap. No more than n characters of the string are copied + * (including any NUL) and the destination string will NOT be + * NUL-terminated if that limit is reached. + */ +void Curl_strntolower(char *dest, const char *src, size_t n) +{ + if(n < 1) + return; + + do { + *dest++ = Curl_raw_tolower(*src); + } while(*src++ && --n); +} + +/* Compare case-sensitive NUL-terminated strings, taking care of possible + * null pointers. Return true if arguments match. + */ +bool Curl_safecmp(char *a, char *b) +{ + if(a && b) + return !strcmp(a, b); + return !a && !b; +} + +/* + * Curl_timestrcmp() returns 0 if the two strings are identical. The time this + * function spends is a function of the shortest string, not of the contents. + */ +int Curl_timestrcmp(const char *a, const char *b) +{ + int match = 0; + int i = 0; + + if(a && b) { + while(1) { + match |= a[i]^b[i]; + if(!a[i] || !b[i]) + break; + i++; + } + } + else + return a || b; + return match; +} diff --git a/third_party/curl/lib/strcase.h b/third_party/curl/lib/strcase.h new file mode 100644 index 0000000..8c50bbc --- /dev/null +++ b/third_party/curl/lib/strcase.h @@ -0,0 +1,54 @@ +#ifndef HEADER_CURL_STRCASE_H +#define HEADER_CURL_STRCASE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include + +/* + * Only "raw" case insensitive strings. This is meant to be locale independent + * and only compare strings we know are safe for this. + * + * The function is capable of comparing a-z case insensitively. + * + * Result is 1 if text matches and 0 if not. + */ + +#define strcasecompare(a,b) curl_strequal(a,b) +#define strncasecompare(a,b,c) curl_strnequal(a,b,c) + +char Curl_raw_toupper(char in); +char Curl_raw_tolower(char in); + +/* checkprefix() is a shorter version of the above, used when the first + argument is the string literal */ +#define checkprefix(a,b) curl_strnequal(b, STRCONST(a)) + +void Curl_strntoupper(char *dest, const char *src, size_t n); +void Curl_strntolower(char *dest, const char *src, size_t n); + +bool Curl_safecmp(char *a, char *b); +int Curl_timestrcmp(const char *first, const char *second); + +#endif /* HEADER_CURL_STRCASE_H */ diff --git a/third_party/curl/lib/strdup.c b/third_party/curl/lib/strdup.c new file mode 100644 index 0000000..299c9cc --- /dev/null +++ b/third_party/curl/lib/strdup.c @@ -0,0 +1,143 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#ifdef _WIN32 +#include +#endif + +#include "strdup.h" +#include "curl_memory.h" + +/* The last #include file should be: */ +#include "memdebug.h" + +#ifndef HAVE_STRDUP +char *Curl_strdup(const char *str) +{ + size_t len; + char *newstr; + + if(!str) + return (char *)NULL; + + len = strlen(str) + 1; + + newstr = malloc(len); + if(!newstr) + return (char *)NULL; + + memcpy(newstr, str, len); + return newstr; +} +#endif + +#ifdef _WIN32 +/*************************************************************************** + * + * Curl_wcsdup(source) + * + * Copies the 'source' wchar string to a newly allocated buffer (that is + * returned). + * + * Returns the new pointer or NULL on failure. + * + ***************************************************************************/ +wchar_t *Curl_wcsdup(const wchar_t *src) +{ + size_t length = wcslen(src); + + if(length > (SIZE_T_MAX / sizeof(wchar_t)) - 1) + return (wchar_t *)NULL; /* integer overflow */ + + return (wchar_t *)Curl_memdup(src, (length + 1) * sizeof(wchar_t)); +} +#endif + +/*************************************************************************** + * + * Curl_memdup(source, length) + * + * Copies the 'source' data to a newly allocated buffer (that is + * returned). Copies 'length' bytes. + * + * Returns the new pointer or NULL on failure. + * + ***************************************************************************/ +void *Curl_memdup(const void *src, size_t length) +{ + void *buffer = malloc(length); + if(!buffer) + return NULL; /* fail */ + + memcpy(buffer, src, length); + + return buffer; +} + +/*************************************************************************** + * + * Curl_memdup0(source, length) + * + * Copies the 'source' string to a newly allocated buffer (that is returned). + * Copies 'length' bytes then adds a null terminator. + * + * Returns the new pointer or NULL on failure. + * + ***************************************************************************/ +void *Curl_memdup0(const char *src, size_t length) +{ + char *buf = malloc(length + 1); + if(!buf) + return NULL; + memcpy(buf, src, length); + buf[length] = 0; + return buf; +} + +/*************************************************************************** + * + * Curl_saferealloc(ptr, size) + * + * Does a normal realloc(), but will free the data pointer if the realloc + * fails. If 'size' is non-zero, it will free the data and return a failure. + * + * This convenience function is provided and used to help us avoid a common + * mistake pattern when we could pass in a zero, catch the NULL return and end + * up free'ing the memory twice. + * + * Returns the new pointer or NULL on failure. + * + ***************************************************************************/ +void *Curl_saferealloc(void *ptr, size_t size) +{ + void *datap = realloc(ptr, size); + if(size && !datap) + /* only free 'ptr' if size was non-zero */ + free(ptr); + return datap; +} diff --git a/third_party/curl/lib/strdup.h b/third_party/curl/lib/strdup.h new file mode 100644 index 0000000..238a261 --- /dev/null +++ b/third_party/curl/lib/strdup.h @@ -0,0 +1,38 @@ +#ifndef HEADER_CURL_STRDUP_H +#define HEADER_CURL_STRDUP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef HAVE_STRDUP +char *Curl_strdup(const char *str); +#endif +#ifdef _WIN32 +wchar_t* Curl_wcsdup(const wchar_t* src); +#endif +void *Curl_memdup(const void *src, size_t buffer_length); +void *Curl_saferealloc(void *ptr, size_t size); +void *Curl_memdup0(const char *src, size_t length); + +#endif /* HEADER_CURL_STRDUP_H */ diff --git a/third_party/curl/lib/strerror.c b/third_party/curl/lib/strerror.c new file mode 100644 index 0000000..f142cf1 --- /dev/null +++ b/third_party/curl/lib/strerror.c @@ -0,0 +1,1117 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_STRERROR_R +# if (!defined(HAVE_POSIX_STRERROR_R) && \ + !defined(HAVE_GLIBC_STRERROR_R)) || \ + (defined(HAVE_POSIX_STRERROR_R) && defined(HAVE_GLIBC_STRERROR_R)) +# error "strerror_r MUST be either POSIX, glibc style" +# endif +#endif + +#include + +#ifdef USE_LIBIDN2 +#include +#endif + +#ifdef USE_WINDOWS_SSPI +#include "curl_sspi.h" +#endif + +#include "strerror.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if defined(_WIN32) || defined(_WIN32_WCE) +#define PRESERVE_WINDOWS_ERROR_CODE +#endif + +const char * +curl_easy_strerror(CURLcode error) +{ +#ifndef CURL_DISABLE_VERBOSE_STRINGS + switch(error) { + case CURLE_OK: + return "No error"; + + case CURLE_UNSUPPORTED_PROTOCOL: + return "Unsupported protocol"; + + case CURLE_FAILED_INIT: + return "Failed initialization"; + + case CURLE_URL_MALFORMAT: + return "URL using bad/illegal format or missing URL"; + + case CURLE_NOT_BUILT_IN: + return "A requested feature, protocol or option was not found built-in in" + " this libcurl due to a build-time decision."; + + case CURLE_COULDNT_RESOLVE_PROXY: + return "Couldn't resolve proxy name"; + + case CURLE_COULDNT_RESOLVE_HOST: + return "Couldn't resolve host name"; + + case CURLE_COULDNT_CONNECT: + return "Couldn't connect to server"; + + case CURLE_WEIRD_SERVER_REPLY: + return "Weird server reply"; + + case CURLE_REMOTE_ACCESS_DENIED: + return "Access denied to remote resource"; + + case CURLE_FTP_ACCEPT_FAILED: + return "FTP: The server failed to connect to data port"; + + case CURLE_FTP_ACCEPT_TIMEOUT: + return "FTP: Accepting server connect has timed out"; + + case CURLE_FTP_PRET_FAILED: + return "FTP: The server did not accept the PRET command."; + + case CURLE_FTP_WEIRD_PASS_REPLY: + return "FTP: unknown PASS reply"; + + case CURLE_FTP_WEIRD_PASV_REPLY: + return "FTP: unknown PASV reply"; + + case CURLE_FTP_WEIRD_227_FORMAT: + return "FTP: unknown 227 response format"; + + case CURLE_FTP_CANT_GET_HOST: + return "FTP: can't figure out the host in the PASV response"; + + case CURLE_HTTP2: + return "Error in the HTTP2 framing layer"; + + case CURLE_FTP_COULDNT_SET_TYPE: + return "FTP: couldn't set file type"; + + case CURLE_PARTIAL_FILE: + return "Transferred a partial file"; + + case CURLE_FTP_COULDNT_RETR_FILE: + return "FTP: couldn't retrieve (RETR failed) the specified file"; + + case CURLE_QUOTE_ERROR: + return "Quote command returned error"; + + case CURLE_HTTP_RETURNED_ERROR: + return "HTTP response code said error"; + + case CURLE_WRITE_ERROR: + return "Failed writing received data to disk/application"; + + case CURLE_UPLOAD_FAILED: + return "Upload failed (at start/before it took off)"; + + case CURLE_READ_ERROR: + return "Failed to open/read local data from file/application"; + + case CURLE_OUT_OF_MEMORY: + return "Out of memory"; + + case CURLE_OPERATION_TIMEDOUT: + return "Timeout was reached"; + + case CURLE_FTP_PORT_FAILED: + return "FTP: command PORT failed"; + + case CURLE_FTP_COULDNT_USE_REST: + return "FTP: command REST failed"; + + case CURLE_RANGE_ERROR: + return "Requested range was not delivered by the server"; + + case CURLE_HTTP_POST_ERROR: + return "Internal problem setting up the POST"; + + case CURLE_SSL_CONNECT_ERROR: + return "SSL connect error"; + + case CURLE_BAD_DOWNLOAD_RESUME: + return "Couldn't resume download"; + + case CURLE_FILE_COULDNT_READ_FILE: + return "Couldn't read a file:// file"; + + case CURLE_LDAP_CANNOT_BIND: + return "LDAP: cannot bind"; + + case CURLE_LDAP_SEARCH_FAILED: + return "LDAP: search failed"; + + case CURLE_FUNCTION_NOT_FOUND: + return "A required function in the library was not found"; + + case CURLE_ABORTED_BY_CALLBACK: + return "Operation was aborted by an application callback"; + + case CURLE_BAD_FUNCTION_ARGUMENT: + return "A libcurl function was given a bad argument"; + + case CURLE_INTERFACE_FAILED: + return "Failed binding local connection end"; + + case CURLE_TOO_MANY_REDIRECTS: + return "Number of redirects hit maximum amount"; + + case CURLE_UNKNOWN_OPTION: + return "An unknown option was passed in to libcurl"; + + case CURLE_SETOPT_OPTION_SYNTAX: + return "Malformed option provided in a setopt"; + + case CURLE_GOT_NOTHING: + return "Server returned nothing (no headers, no data)"; + + case CURLE_SSL_ENGINE_NOTFOUND: + return "SSL crypto engine not found"; + + case CURLE_SSL_ENGINE_SETFAILED: + return "Can not set SSL crypto engine as default"; + + case CURLE_SSL_ENGINE_INITFAILED: + return "Failed to initialise SSL crypto engine"; + + case CURLE_SEND_ERROR: + return "Failed sending data to the peer"; + + case CURLE_RECV_ERROR: + return "Failure when receiving data from the peer"; + + case CURLE_SSL_CERTPROBLEM: + return "Problem with the local SSL certificate"; + + case CURLE_SSL_CIPHER: + return "Couldn't use specified SSL cipher"; + + case CURLE_PEER_FAILED_VERIFICATION: + return "SSL peer certificate or SSH remote key was not OK"; + + case CURLE_SSL_CACERT_BADFILE: + return "Problem with the SSL CA cert (path? access rights?)"; + + case CURLE_BAD_CONTENT_ENCODING: + return "Unrecognized or bad HTTP Content or Transfer-Encoding"; + + case CURLE_FILESIZE_EXCEEDED: + return "Maximum file size exceeded"; + + case CURLE_USE_SSL_FAILED: + return "Requested SSL level failed"; + + case CURLE_SSL_SHUTDOWN_FAILED: + return "Failed to shut down the SSL connection"; + + case CURLE_SSL_CRL_BADFILE: + return "Failed to load CRL file (path? access rights?, format?)"; + + case CURLE_SSL_ISSUER_ERROR: + return "Issuer check against peer certificate failed"; + + case CURLE_SEND_FAIL_REWIND: + return "Send failed since rewinding of the data stream failed"; + + case CURLE_LOGIN_DENIED: + return "Login denied"; + + case CURLE_TFTP_NOTFOUND: + return "TFTP: File Not Found"; + + case CURLE_TFTP_PERM: + return "TFTP: Access Violation"; + + case CURLE_REMOTE_DISK_FULL: + return "Disk full or allocation exceeded"; + + case CURLE_TFTP_ILLEGAL: + return "TFTP: Illegal operation"; + + case CURLE_TFTP_UNKNOWNID: + return "TFTP: Unknown transfer ID"; + + case CURLE_REMOTE_FILE_EXISTS: + return "Remote file already exists"; + + case CURLE_TFTP_NOSUCHUSER: + return "TFTP: No such user"; + + case CURLE_REMOTE_FILE_NOT_FOUND: + return "Remote file not found"; + + case CURLE_SSH: + return "Error in the SSH layer"; + + case CURLE_AGAIN: + return "Socket not ready for send/recv"; + + case CURLE_RTSP_CSEQ_ERROR: + return "RTSP CSeq mismatch or invalid CSeq"; + + case CURLE_RTSP_SESSION_ERROR: + return "RTSP session error"; + + case CURLE_FTP_BAD_FILE_LIST: + return "Unable to parse FTP file list"; + + case CURLE_CHUNK_FAILED: + return "Chunk callback failed"; + + case CURLE_NO_CONNECTION_AVAILABLE: + return "The max connection limit is reached"; + + case CURLE_SSL_PINNEDPUBKEYNOTMATCH: + return "SSL public key does not match pinned public key"; + + case CURLE_SSL_INVALIDCERTSTATUS: + return "SSL server certificate status verification FAILED"; + + case CURLE_HTTP2_STREAM: + return "Stream error in the HTTP/2 framing layer"; + + case CURLE_RECURSIVE_API_CALL: + return "API function called from within callback"; + + case CURLE_AUTH_ERROR: + return "An authentication function returned an error"; + + case CURLE_HTTP3: + return "HTTP/3 error"; + + case CURLE_QUIC_CONNECT_ERROR: + return "QUIC connection error"; + + case CURLE_PROXY: + return "proxy handshake error"; + + case CURLE_SSL_CLIENTCERT: + return "SSL Client Certificate required"; + + case CURLE_UNRECOVERABLE_POLL: + return "Unrecoverable error in select/poll"; + + case CURLE_TOO_LARGE: + return "A value or data field grew larger than allowed"; + + case CURLE_ECH_REQUIRED: + return "ECH attempted but failed"; + + /* error codes not used by current libcurl */ + case CURLE_OBSOLETE20: + case CURLE_OBSOLETE24: + case CURLE_OBSOLETE29: + case CURLE_OBSOLETE32: + case CURLE_OBSOLETE40: + case CURLE_OBSOLETE44: + case CURLE_OBSOLETE46: + case CURLE_OBSOLETE50: + case CURLE_OBSOLETE51: + case CURLE_OBSOLETE57: + case CURLE_OBSOLETE62: + case CURLE_OBSOLETE75: + case CURLE_OBSOLETE76: + case CURL_LAST: + break; + } + /* + * By using a switch, gcc -Wall will complain about enum values + * which do not appear, helping keep this function up-to-date. + * By using gcc -Wall -Werror, you can't forget. + * + * A table would not have the same benefit. Most compilers will + * generate code very similar to a table in any case, so there + * is little performance gain from a table. And something is broken + * for the user's application, anyways, so does it matter how fast + * it _doesn't_ work? + * + * The line number for the error will be near this comment, which + * is why it is here, and not at the start of the switch. + */ + return "Unknown error"; +#else + if(!error) + return "No error"; + else + return "Error"; +#endif +} + +const char * +curl_multi_strerror(CURLMcode error) +{ +#ifndef CURL_DISABLE_VERBOSE_STRINGS + switch(error) { + case CURLM_CALL_MULTI_PERFORM: + return "Please call curl_multi_perform() soon"; + + case CURLM_OK: + return "No error"; + + case CURLM_BAD_HANDLE: + return "Invalid multi handle"; + + case CURLM_BAD_EASY_HANDLE: + return "Invalid easy handle"; + + case CURLM_OUT_OF_MEMORY: + return "Out of memory"; + + case CURLM_INTERNAL_ERROR: + return "Internal error"; + + case CURLM_BAD_SOCKET: + return "Invalid socket argument"; + + case CURLM_UNKNOWN_OPTION: + return "Unknown option"; + + case CURLM_ADDED_ALREADY: + return "The easy handle is already added to a multi handle"; + + case CURLM_RECURSIVE_API_CALL: + return "API function called from within callback"; + + case CURLM_WAKEUP_FAILURE: + return "Wakeup is unavailable or failed"; + + case CURLM_BAD_FUNCTION_ARGUMENT: + return "A libcurl function was given a bad argument"; + + case CURLM_ABORTED_BY_CALLBACK: + return "Operation was aborted by an application callback"; + + case CURLM_UNRECOVERABLE_POLL: + return "Unrecoverable error in select/poll"; + + case CURLM_LAST: + break; + } + + return "Unknown error"; +#else + if(error == CURLM_OK) + return "No error"; + else + return "Error"; +#endif +} + +const char * +curl_share_strerror(CURLSHcode error) +{ +#ifndef CURL_DISABLE_VERBOSE_STRINGS + switch(error) { + case CURLSHE_OK: + return "No error"; + + case CURLSHE_BAD_OPTION: + return "Unknown share option"; + + case CURLSHE_IN_USE: + return "Share currently in use"; + + case CURLSHE_INVALID: + return "Invalid share handle"; + + case CURLSHE_NOMEM: + return "Out of memory"; + + case CURLSHE_NOT_BUILT_IN: + return "Feature not enabled in this library"; + + case CURLSHE_LAST: + break; + } + + return "CURLSHcode unknown"; +#else + if(error == CURLSHE_OK) + return "No error"; + else + return "Error"; +#endif +} + +const char * +curl_url_strerror(CURLUcode error) +{ +#ifndef CURL_DISABLE_VERBOSE_STRINGS + switch(error) { + case CURLUE_OK: + return "No error"; + + case CURLUE_BAD_HANDLE: + return "An invalid CURLU pointer was passed as argument"; + + case CURLUE_BAD_PARTPOINTER: + return "An invalid 'part' argument was passed as argument"; + + case CURLUE_MALFORMED_INPUT: + return "Malformed input to a URL function"; + + case CURLUE_BAD_PORT_NUMBER: + return "Port number was not a decimal number between 0 and 65535"; + + case CURLUE_UNSUPPORTED_SCHEME: + return "Unsupported URL scheme"; + + case CURLUE_URLDECODE: + return "URL decode error, most likely because of rubbish in the input"; + + case CURLUE_OUT_OF_MEMORY: + return "A memory function failed"; + + case CURLUE_USER_NOT_ALLOWED: + return "Credentials was passed in the URL when prohibited"; + + case CURLUE_UNKNOWN_PART: + return "An unknown part ID was passed to a URL API function"; + + case CURLUE_NO_SCHEME: + return "No scheme part in the URL"; + + case CURLUE_NO_USER: + return "No user part in the URL"; + + case CURLUE_NO_PASSWORD: + return "No password part in the URL"; + + case CURLUE_NO_OPTIONS: + return "No options part in the URL"; + + case CURLUE_NO_HOST: + return "No host part in the URL"; + + case CURLUE_NO_PORT: + return "No port part in the URL"; + + case CURLUE_NO_QUERY: + return "No query part in the URL"; + + case CURLUE_NO_FRAGMENT: + return "No fragment part in the URL"; + + case CURLUE_NO_ZONEID: + return "No zoneid part in the URL"; + + case CURLUE_BAD_LOGIN: + return "Bad login part"; + + case CURLUE_BAD_IPV6: + return "Bad IPv6 address"; + + case CURLUE_BAD_HOSTNAME: + return "Bad hostname"; + + case CURLUE_BAD_FILE_URL: + return "Bad file:// URL"; + + case CURLUE_BAD_SLASHES: + return "Unsupported number of slashes following scheme"; + + case CURLUE_BAD_SCHEME: + return "Bad scheme"; + + case CURLUE_BAD_PATH: + return "Bad path"; + + case CURLUE_BAD_FRAGMENT: + return "Bad fragment"; + + case CURLUE_BAD_QUERY: + return "Bad query"; + + case CURLUE_BAD_PASSWORD: + return "Bad password"; + + case CURLUE_BAD_USER: + return "Bad user"; + + case CURLUE_LACKS_IDN: + return "libcurl lacks IDN support"; + + case CURLUE_TOO_LARGE: + return "A value or data field is larger than allowed"; + + case CURLUE_LAST: + break; + } + + return "CURLUcode unknown"; +#else + if(error == CURLUE_OK) + return "No error"; + else + return "Error"; +#endif +} + +#ifdef USE_WINSOCK +/* This is a helper function for Curl_strerror that converts Winsock error + * codes (WSAGetLastError) to error messages. + * Returns NULL if no error message was found for error code. + */ +static const char * +get_winsock_error(int err, char *buf, size_t len) +{ +#ifndef CURL_DISABLE_VERBOSE_STRINGS + const char *p; + size_t alen; +#endif + + if(!len) + return NULL; + + *buf = '\0'; + +#ifdef CURL_DISABLE_VERBOSE_STRINGS + (void)err; + return NULL; +#else + switch(err) { + case WSAEINTR: + p = "Call interrupted"; + break; + case WSAEBADF: + p = "Bad file"; + break; + case WSAEACCES: + p = "Bad access"; + break; + case WSAEFAULT: + p = "Bad argument"; + break; + case WSAEINVAL: + p = "Invalid arguments"; + break; + case WSAEMFILE: + p = "Out of file descriptors"; + break; + case WSAEWOULDBLOCK: + p = "Call would block"; + break; + case WSAEINPROGRESS: + case WSAEALREADY: + p = "Blocking call in progress"; + break; + case WSAENOTSOCK: + p = "Descriptor is not a socket"; + break; + case WSAEDESTADDRREQ: + p = "Need destination address"; + break; + case WSAEMSGSIZE: + p = "Bad message size"; + break; + case WSAEPROTOTYPE: + p = "Bad protocol"; + break; + case WSAENOPROTOOPT: + p = "Protocol option is unsupported"; + break; + case WSAEPROTONOSUPPORT: + p = "Protocol is unsupported"; + break; + case WSAESOCKTNOSUPPORT: + p = "Socket is unsupported"; + break; + case WSAEOPNOTSUPP: + p = "Operation not supported"; + break; + case WSAEAFNOSUPPORT: + p = "Address family not supported"; + break; + case WSAEPFNOSUPPORT: + p = "Protocol family not supported"; + break; + case WSAEADDRINUSE: + p = "Address already in use"; + break; + case WSAEADDRNOTAVAIL: + p = "Address not available"; + break; + case WSAENETDOWN: + p = "Network down"; + break; + case WSAENETUNREACH: + p = "Network unreachable"; + break; + case WSAENETRESET: + p = "Network has been reset"; + break; + case WSAECONNABORTED: + p = "Connection was aborted"; + break; + case WSAECONNRESET: + p = "Connection was reset"; + break; + case WSAENOBUFS: + p = "No buffer space"; + break; + case WSAEISCONN: + p = "Socket is already connected"; + break; + case WSAENOTCONN: + p = "Socket is not connected"; + break; + case WSAESHUTDOWN: + p = "Socket has been shut down"; + break; + case WSAETOOMANYREFS: + p = "Too many references"; + break; + case WSAETIMEDOUT: + p = "Timed out"; + break; + case WSAECONNREFUSED: + p = "Connection refused"; + break; + case WSAELOOP: + p = "Loop??"; + break; + case WSAENAMETOOLONG: + p = "Name too long"; + break; + case WSAEHOSTDOWN: + p = "Host down"; + break; + case WSAEHOSTUNREACH: + p = "Host unreachable"; + break; + case WSAENOTEMPTY: + p = "Not empty"; + break; + case WSAEPROCLIM: + p = "Process limit reached"; + break; + case WSAEUSERS: + p = "Too many users"; + break; + case WSAEDQUOT: + p = "Bad quota"; + break; + case WSAESTALE: + p = "Something is stale"; + break; + case WSAEREMOTE: + p = "Remote error"; + break; +#ifdef WSAEDISCON /* missing in SalfordC! */ + case WSAEDISCON: + p = "Disconnected"; + break; +#endif + /* Extended Winsock errors */ + case WSASYSNOTREADY: + p = "Winsock library is not ready"; + break; + case WSANOTINITIALISED: + p = "Winsock library not initialised"; + break; + case WSAVERNOTSUPPORTED: + p = "Winsock version not supported"; + break; + + /* getXbyY() errors (already handled in herrmsg): + * Authoritative Answer: Host not found */ + case WSAHOST_NOT_FOUND: + p = "Host not found"; + break; + + /* Non-Authoritative: Host not found, or SERVERFAIL */ + case WSATRY_AGAIN: + p = "Host not found, try again"; + break; + + /* Non recoverable errors, FORMERR, REFUSED, NOTIMP */ + case WSANO_RECOVERY: + p = "Unrecoverable error in call to nameserver"; + break; + + /* Valid name, no data record of requested type */ + case WSANO_DATA: + p = "No data record of requested type"; + break; + + default: + return NULL; + } + alen = strlen(p); + if(alen < len) + strcpy(buf, p); + return buf; +#endif +} +#endif /* USE_WINSOCK */ + +#if defined(_WIN32) || defined(_WIN32_WCE) +/* This is a helper function for Curl_strerror that converts Windows API error + * codes (GetLastError) to error messages. + * Returns NULL if no error message was found for error code. + */ +static const char * +get_winapi_error(int err, char *buf, size_t buflen) +{ + char *p; + wchar_t wbuf[256]; + + if(!buflen) + return NULL; + + *buf = '\0'; + *wbuf = L'\0'; + + /* We return the local codepage version of the error string because if it is + output to the user's terminal it will likely be with functions which + expect the local codepage (eg fprintf, failf, infof). + FormatMessageW -> wcstombs is used for Windows CE compatibility. */ + if(FormatMessageW((FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS), NULL, err, + LANG_NEUTRAL, wbuf, sizeof(wbuf)/sizeof(wchar_t), NULL)) { + size_t written = wcstombs(buf, wbuf, buflen - 1); + if(written != (size_t)-1) + buf[written] = '\0'; + else + *buf = '\0'; + } + + /* Truncate multiple lines */ + p = strchr(buf, '\n'); + if(p) { + if(p > buf && *(p-1) == '\r') + *(p-1) = '\0'; + else + *p = '\0'; + } + + return (*buf ? buf : NULL); +} +#endif /* _WIN32 || _WIN32_WCE */ + +/* + * Our thread-safe and smart strerror() replacement. + * + * The 'err' argument passed in to this function MUST be a true errno number + * as reported on this system. We do no range checking on the number before + * we pass it to the "number-to-message" conversion function and there might + * be systems that don't do proper range checking in there themselves. + * + * We don't do range checking (on systems other than Windows) since there is + * no good reliable and portable way to do it. + * + * On Windows different types of error codes overlap. This function has an + * order of preference when trying to match error codes: + * CRT (errno), Winsock (WSAGetLastError), Windows API (GetLastError). + * + * It may be more correct to call one of the variant functions instead: + * Call Curl_sspi_strerror if the error code is definitely Windows SSPI. + * Call Curl_winapi_strerror if the error code is definitely Windows API. + */ +const char *Curl_strerror(int err, char *buf, size_t buflen) +{ +#ifdef PRESERVE_WINDOWS_ERROR_CODE + DWORD old_win_err = GetLastError(); +#endif + int old_errno = errno; + char *p; + + if(!buflen) + return NULL; + +#ifndef _WIN32 + DEBUGASSERT(err >= 0); +#endif + + *buf = '\0'; + +#if defined(_WIN32) || defined(_WIN32_WCE) +#if defined(_WIN32) + /* 'sys_nerr' is the maximum errno number, it is not widely portable */ + if(err >= 0 && err < sys_nerr) + msnprintf(buf, buflen, "%s", sys_errlist[err]); + else +#endif + { + if( +#ifdef USE_WINSOCK + !get_winsock_error(err, buf, buflen) && +#endif + !get_winapi_error((DWORD)err, buf, buflen)) + msnprintf(buf, buflen, "Unknown error %d (%#x)", err, err); + } +#else /* not Windows coming up */ + +#if defined(HAVE_STRERROR_R) && defined(HAVE_POSIX_STRERROR_R) + /* + * The POSIX-style strerror_r() may set errno to ERANGE if insufficient + * storage is supplied via 'strerrbuf' and 'buflen' to hold the generated + * message string, or EINVAL if 'errnum' is not a valid error number. + */ + if(0 != strerror_r(err, buf, buflen)) { + if('\0' == buf[0]) + msnprintf(buf, buflen, "Unknown error %d", err); + } +#elif defined(HAVE_STRERROR_R) && defined(HAVE_GLIBC_STRERROR_R) + /* + * The glibc-style strerror_r() only *might* use the buffer we pass to + * the function, but it always returns the error message as a pointer, + * so we must copy that string unconditionally (if non-NULL). + */ + { + char buffer[256]; + char *msg = strerror_r(err, buffer, sizeof(buffer)); + if(msg) + msnprintf(buf, buflen, "%s", msg); + else + msnprintf(buf, buflen, "Unknown error %d", err); + } +#else + { + /* !checksrc! disable STRERROR 1 */ + const char *msg = strerror(err); + if(msg) + msnprintf(buf, buflen, "%s", msg); + else + msnprintf(buf, buflen, "Unknown error %d", err); + } +#endif + +#endif /* end of not Windows */ + + /* strip trailing '\r\n' or '\n'. */ + p = strrchr(buf, '\n'); + if(p && (p - buf) >= 2) + *p = '\0'; + p = strrchr(buf, '\r'); + if(p && (p - buf) >= 1) + *p = '\0'; + + if(errno != old_errno) + errno = old_errno; + +#ifdef PRESERVE_WINDOWS_ERROR_CODE + if(old_win_err != GetLastError()) + SetLastError(old_win_err); +#endif + + return buf; +} + +/* + * Curl_winapi_strerror: + * Variant of Curl_strerror if the error code is definitely Windows API. + */ +#if defined(_WIN32) || defined(_WIN32_WCE) +const char *Curl_winapi_strerror(DWORD err, char *buf, size_t buflen) +{ +#ifdef PRESERVE_WINDOWS_ERROR_CODE + DWORD old_win_err = GetLastError(); +#endif + int old_errno = errno; + + if(!buflen) + return NULL; + + *buf = '\0'; + +#ifndef CURL_DISABLE_VERBOSE_STRINGS + if(!get_winapi_error(err, buf, buflen)) { + msnprintf(buf, buflen, "Unknown error %lu (0x%08lX)", err, err); + } +#else + { + const char *txt = (err == ERROR_SUCCESS) ? "No error" : "Error"; + if(strlen(txt) < buflen) + strcpy(buf, txt); + } +#endif + + if(errno != old_errno) + errno = old_errno; + +#ifdef PRESERVE_WINDOWS_ERROR_CODE + if(old_win_err != GetLastError()) + SetLastError(old_win_err); +#endif + + return buf; +} +#endif /* _WIN32 || _WIN32_WCE */ + +#ifdef USE_WINDOWS_SSPI +/* + * Curl_sspi_strerror: + * Variant of Curl_strerror if the error code is definitely Windows SSPI. + */ +const char *Curl_sspi_strerror(int err, char *buf, size_t buflen) +{ +#ifdef PRESERVE_WINDOWS_ERROR_CODE + DWORD old_win_err = GetLastError(); +#endif + int old_errno = errno; + const char *txt; + + if(!buflen) + return NULL; + + *buf = '\0'; + +#ifndef CURL_DISABLE_VERBOSE_STRINGS + + switch(err) { + case SEC_E_OK: + txt = "No error"; + break; +#define SEC2TXT(sec) case sec: txt = #sec; break + SEC2TXT(CRYPT_E_REVOKED); + SEC2TXT(CRYPT_E_NO_REVOCATION_DLL); + SEC2TXT(CRYPT_E_NO_REVOCATION_CHECK); + SEC2TXT(CRYPT_E_REVOCATION_OFFLINE); + SEC2TXT(CRYPT_E_NOT_IN_REVOCATION_DATABASE); + SEC2TXT(SEC_E_ALGORITHM_MISMATCH); + SEC2TXT(SEC_E_BAD_BINDINGS); + SEC2TXT(SEC_E_BAD_PKGID); + SEC2TXT(SEC_E_BUFFER_TOO_SMALL); + SEC2TXT(SEC_E_CANNOT_INSTALL); + SEC2TXT(SEC_E_CANNOT_PACK); + SEC2TXT(SEC_E_CERT_EXPIRED); + SEC2TXT(SEC_E_CERT_UNKNOWN); + SEC2TXT(SEC_E_CERT_WRONG_USAGE); + SEC2TXT(SEC_E_CONTEXT_EXPIRED); + SEC2TXT(SEC_E_CROSSREALM_DELEGATION_FAILURE); + SEC2TXT(SEC_E_CRYPTO_SYSTEM_INVALID); + SEC2TXT(SEC_E_DECRYPT_FAILURE); + SEC2TXT(SEC_E_DELEGATION_POLICY); + SEC2TXT(SEC_E_DELEGATION_REQUIRED); + SEC2TXT(SEC_E_DOWNGRADE_DETECTED); + SEC2TXT(SEC_E_ENCRYPT_FAILURE); + SEC2TXT(SEC_E_ILLEGAL_MESSAGE); + SEC2TXT(SEC_E_INCOMPLETE_CREDENTIALS); + SEC2TXT(SEC_E_INCOMPLETE_MESSAGE); + SEC2TXT(SEC_E_INSUFFICIENT_MEMORY); + SEC2TXT(SEC_E_INTERNAL_ERROR); + SEC2TXT(SEC_E_INVALID_HANDLE); + SEC2TXT(SEC_E_INVALID_PARAMETER); + SEC2TXT(SEC_E_INVALID_TOKEN); + SEC2TXT(SEC_E_ISSUING_CA_UNTRUSTED); + SEC2TXT(SEC_E_ISSUING_CA_UNTRUSTED_KDC); + SEC2TXT(SEC_E_KDC_CERT_EXPIRED); + SEC2TXT(SEC_E_KDC_CERT_REVOKED); + SEC2TXT(SEC_E_KDC_INVALID_REQUEST); + SEC2TXT(SEC_E_KDC_UNABLE_TO_REFER); + SEC2TXT(SEC_E_KDC_UNKNOWN_ETYPE); + SEC2TXT(SEC_E_LOGON_DENIED); + SEC2TXT(SEC_E_MAX_REFERRALS_EXCEEDED); + SEC2TXT(SEC_E_MESSAGE_ALTERED); + SEC2TXT(SEC_E_MULTIPLE_ACCOUNTS); + SEC2TXT(SEC_E_MUST_BE_KDC); + SEC2TXT(SEC_E_NOT_OWNER); + SEC2TXT(SEC_E_NO_AUTHENTICATING_AUTHORITY); + SEC2TXT(SEC_E_NO_CREDENTIALS); + SEC2TXT(SEC_E_NO_IMPERSONATION); + SEC2TXT(SEC_E_NO_IP_ADDRESSES); + SEC2TXT(SEC_E_NO_KERB_KEY); + SEC2TXT(SEC_E_NO_PA_DATA); + SEC2TXT(SEC_E_NO_S4U_PROT_SUPPORT); + SEC2TXT(SEC_E_NO_TGT_REPLY); + SEC2TXT(SEC_E_OUT_OF_SEQUENCE); + SEC2TXT(SEC_E_PKINIT_CLIENT_FAILURE); + SEC2TXT(SEC_E_PKINIT_NAME_MISMATCH); + SEC2TXT(SEC_E_POLICY_NLTM_ONLY); + SEC2TXT(SEC_E_QOP_NOT_SUPPORTED); + SEC2TXT(SEC_E_REVOCATION_OFFLINE_C); + SEC2TXT(SEC_E_REVOCATION_OFFLINE_KDC); + SEC2TXT(SEC_E_SECPKG_NOT_FOUND); + SEC2TXT(SEC_E_SECURITY_QOS_FAILED); + SEC2TXT(SEC_E_SHUTDOWN_IN_PROGRESS); + SEC2TXT(SEC_E_SMARTCARD_CERT_EXPIRED); + SEC2TXT(SEC_E_SMARTCARD_CERT_REVOKED); + SEC2TXT(SEC_E_SMARTCARD_LOGON_REQUIRED); + SEC2TXT(SEC_E_STRONG_CRYPTO_NOT_SUPPORTED); + SEC2TXT(SEC_E_TARGET_UNKNOWN); + SEC2TXT(SEC_E_TIME_SKEW); + SEC2TXT(SEC_E_TOO_MANY_PRINCIPALS); + SEC2TXT(SEC_E_UNFINISHED_CONTEXT_DELETED); + SEC2TXT(SEC_E_UNKNOWN_CREDENTIALS); + SEC2TXT(SEC_E_UNSUPPORTED_FUNCTION); + SEC2TXT(SEC_E_UNSUPPORTED_PREAUTH); + SEC2TXT(SEC_E_UNTRUSTED_ROOT); + SEC2TXT(SEC_E_WRONG_CREDENTIAL_HANDLE); + SEC2TXT(SEC_E_WRONG_PRINCIPAL); + SEC2TXT(SEC_I_COMPLETE_AND_CONTINUE); + SEC2TXT(SEC_I_COMPLETE_NEEDED); + SEC2TXT(SEC_I_CONTEXT_EXPIRED); + SEC2TXT(SEC_I_CONTINUE_NEEDED); + SEC2TXT(SEC_I_INCOMPLETE_CREDENTIALS); + SEC2TXT(SEC_I_LOCAL_LOGON); + SEC2TXT(SEC_I_NO_LSA_CONTEXT); + SEC2TXT(SEC_I_RENEGOTIATE); + SEC2TXT(SEC_I_SIGNATURE_NEEDED); + default: + txt = "Unknown error"; + } + + if(err == SEC_E_ILLEGAL_MESSAGE) { + msnprintf(buf, buflen, + "SEC_E_ILLEGAL_MESSAGE (0x%08X) - This error usually occurs " + "when a fatal SSL/TLS alert is received (e.g. handshake failed)." + " More detail may be available in the Windows System event log.", + err); + } + else { + char msgbuf[256]; + if(get_winapi_error(err, msgbuf, sizeof(msgbuf))) + msnprintf(buf, buflen, "%s (0x%08X) - %s", txt, err, msgbuf); + else + msnprintf(buf, buflen, "%s (0x%08X)", txt, err); + } + +#else + if(err == SEC_E_OK) + txt = "No error"; + else + txt = "Error"; + if(buflen > strlen(txt)) + strcpy(buf, txt); +#endif + + if(errno != old_errno) + errno = old_errno; + +#ifdef PRESERVE_WINDOWS_ERROR_CODE + if(old_win_err != GetLastError()) + SetLastError(old_win_err); +#endif + + return buf; +} +#endif /* USE_WINDOWS_SSPI */ diff --git a/third_party/curl/lib/strerror.h b/third_party/curl/lib/strerror.h new file mode 100644 index 0000000..6806867 --- /dev/null +++ b/third_party/curl/lib/strerror.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_STRERROR_H +#define HEADER_CURL_STRERROR_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "urldata.h" + +#define STRERROR_LEN 256 /* a suitable length */ + +const char *Curl_strerror(int err, char *buf, size_t buflen); +#if defined(_WIN32) || defined(_WIN32_WCE) +const char *Curl_winapi_strerror(DWORD err, char *buf, size_t buflen); +#endif +#ifdef USE_WINDOWS_SSPI +const char *Curl_sspi_strerror(int err, char *buf, size_t buflen); +#endif + +#endif /* HEADER_CURL_STRERROR_H */ diff --git a/third_party/curl/lib/strtok.c b/third_party/curl/lib/strtok.c new file mode 100644 index 0000000..d8e1e81 --- /dev/null +++ b/third_party/curl/lib/strtok.c @@ -0,0 +1,68 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef HAVE_STRTOK_R +#include + +#include "strtok.h" + +char * +Curl_strtok_r(char *ptr, const char *sep, char **end) +{ + if(!ptr) + /* we got NULL input so then we get our last position instead */ + ptr = *end; + + /* pass all letters that are including in the separator string */ + while(*ptr && strchr(sep, *ptr)) + ++ptr; + + if(*ptr) { + /* so this is where the next piece of string starts */ + char *start = ptr; + + /* set the end pointer to the first byte after the start */ + *end = start + 1; + + /* scan through the string to find where it ends, it ends on a + null byte or a character that exists in the separator string */ + while(**end && !strchr(sep, **end)) + ++*end; + + if(**end) { + /* the end is not a null byte */ + **end = '\0'; /* null-terminate it! */ + ++*end; /* advance the last pointer to beyond the null byte */ + } + + return start; /* return the position where the string starts */ + } + + /* we ended up on a null byte, there are no more strings to find! */ + return NULL; +} + +#endif /* this was only compiled if strtok_r wasn't present */ diff --git a/third_party/curl/lib/strtok.h b/third_party/curl/lib/strtok.h new file mode 100644 index 0000000..321cba2 --- /dev/null +++ b/third_party/curl/lib/strtok.h @@ -0,0 +1,36 @@ +#ifndef HEADER_CURL_STRTOK_H +#define HEADER_CURL_STRTOK_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include + +#ifndef HAVE_STRTOK_R +char *Curl_strtok_r(char *s, const char *delim, char **last); +#define strtok_r Curl_strtok_r +#else +#include +#endif + +#endif /* HEADER_CURL_STRTOK_H */ diff --git a/third_party/curl/lib/strtoofft.c b/third_party/curl/lib/strtoofft.c new file mode 100644 index 0000000..580fd23 --- /dev/null +++ b/third_party/curl/lib/strtoofft.c @@ -0,0 +1,240 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include +#include "curl_setup.h" + +#include "strtoofft.h" + +/* + * NOTE: + * + * In the ISO C standard (IEEE Std 1003.1), there is a strtoimax() function we + * could use in case strtoll() doesn't exist... See + * https://www.opengroup.org/onlinepubs/009695399/functions/strtoimax.html + */ + +#if (SIZEOF_CURL_OFF_T > SIZEOF_LONG) +# ifdef HAVE_STRTOLL +# define strtooff strtoll +# else +# if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_INTEGRAL_MAX_BITS >= 64) +# if defined(_SAL_VERSION) + _Check_return_ _CRTIMP __int64 __cdecl _strtoi64( + _In_z_ const char *_String, + _Out_opt_ _Deref_post_z_ char **_EndPtr, _In_ int _Radix); +# else + _CRTIMP __int64 __cdecl _strtoi64(const char *_String, + char **_EndPtr, int _Radix); +# endif +# define strtooff _strtoi64 +# else +# define PRIVATE_STRTOOFF 1 +# endif +# endif +#else +# define strtooff strtol +#endif + +#ifdef PRIVATE_STRTOOFF + +/* Range tests can be used for alphanum decoding if characters are consecutive, + like in ASCII. Else an array is scanned. Determine this condition now. */ + +#if('9' - '0') != 9 || ('Z' - 'A') != 25 || ('z' - 'a') != 25 + +#define NO_RANGE_TEST + +static const char valchars[] = + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; +#endif + +static int get_char(char c, int base); + +/** + * Custom version of the strtooff function. This extracts a curl_off_t + * value from the given input string and returns it. + */ +static curl_off_t strtooff(const char *nptr, char **endptr, int base) +{ + char *end; + bool is_negative = FALSE; + bool overflow = FALSE; + int i; + curl_off_t value = 0; + + /* Skip leading whitespace. */ + end = (char *)nptr; + while(ISBLANK(end[0])) { + end++; + } + + /* Handle the sign, if any. */ + if(end[0] == '-') { + is_negative = TRUE; + end++; + } + else if(end[0] == '+') { + end++; + } + else if(end[0] == '\0') { + /* We had nothing but perhaps some whitespace -- there was no number. */ + if(endptr) { + *endptr = end; + } + return 0; + } + + /* Handle special beginnings, if present and allowed. */ + if(end[0] == '0' && end[1] == 'x') { + if(base == 16 || base == 0) { + end += 2; + base = 16; + } + } + else if(end[0] == '0') { + if(base == 8 || base == 0) { + end++; + base = 8; + } + } + + /* Matching strtol, if the base is 0 and it doesn't look like + * the number is octal or hex, we assume it's base 10. + */ + if(base == 0) { + base = 10; + } + + /* Loop handling digits. */ + for(i = get_char(end[0], base); + i != -1; + end++, i = get_char(end[0], base)) { + + if(value > (CURL_OFF_T_MAX - i) / base) { + overflow = TRUE; + break; + } + value = base * value + i; + } + + if(!overflow) { + if(is_negative) { + /* Fix the sign. */ + value *= -1; + } + } + else { + if(is_negative) + value = CURL_OFF_T_MIN; + else + value = CURL_OFF_T_MAX; + + errno = ERANGE; + } + + if(endptr) + *endptr = end; + + return value; +} + +/** + * Returns the value of c in the given base, or -1 if c cannot + * be interpreted properly in that base (i.e., is out of range, + * is a null, etc.). + * + * @param c the character to interpret according to base + * @param base the base in which to interpret c + * + * @return the value of c in base, or -1 if c isn't in range + */ +static int get_char(char c, int base) +{ +#ifndef NO_RANGE_TEST + int value = -1; + if(c <= '9' && c >= '0') { + value = c - '0'; + } + else if(c <= 'Z' && c >= 'A') { + value = c - 'A' + 10; + } + else if(c <= 'z' && c >= 'a') { + value = c - 'a' + 10; + } +#else + const char *cp; + int value; + + cp = memchr(valchars, c, 10 + 26 + 26); + + if(!cp) + return -1; + + value = cp - valchars; + + if(value >= 10 + 26) + value -= 26; /* Lowercase. */ +#endif + + if(value >= base) { + value = -1; + } + + return value; +} +#endif /* Only present if we need strtoll, but don't have it. */ + +/* + * Parse a *positive* up to 64 bit number written in ascii. + */ +CURLofft curlx_strtoofft(const char *str, char **endp, int base, + curl_off_t *num) +{ + char *end = NULL; + curl_off_t number; + errno = 0; + *num = 0; /* clear by default */ + DEBUGASSERT(base); /* starting now, avoid base zero */ + + while(*str && ISBLANK(*str)) + str++; + if(('-' == *str) || (ISSPACE(*str))) { + if(endp) + *endp = (char *)str; /* didn't actually move */ + return CURL_OFFT_INVAL; /* nothing parsed */ + } + number = strtooff(str, &end, base); + if(endp) + *endp = end; + if(errno == ERANGE) + /* overflow/underflow */ + return CURL_OFFT_FLOW; + else if(str == end) + /* nothing parsed */ + return CURL_OFFT_INVAL; + + *num = number; + return CURL_OFFT_OK; +} diff --git a/third_party/curl/lib/strtoofft.h b/third_party/curl/lib/strtoofft.h new file mode 100644 index 0000000..34d293b --- /dev/null +++ b/third_party/curl/lib/strtoofft.h @@ -0,0 +1,54 @@ +#ifndef HEADER_CURL_STRTOOFFT_H +#define HEADER_CURL_STRTOOFFT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +/* + * Determine which string to integral data type conversion function we use + * to implement string conversion to our curl_off_t integral data type. + * + * Notice that curl_off_t might be 64 or 32 bit wide, and that it might use + * an underlying data type which might be 'long', 'int64_t', 'long long' or + * '__int64' and more remotely other data types. + * + * On systems where the size of curl_off_t is greater than the size of 'long' + * the conversion function to use is strtoll() if it is available, otherwise, + * we emulate its functionality with our own clone. + * + * On systems where the size of curl_off_t is smaller or equal than the size + * of 'long' the conversion function to use is strtol(). + */ + +typedef enum { + CURL_OFFT_OK, /* parsed fine */ + CURL_OFFT_FLOW, /* over or underflow */ + CURL_OFFT_INVAL /* nothing was parsed */ +} CURLofft; + +CURLofft curlx_strtoofft(const char *str, char **endp, int base, + curl_off_t *num); + +#endif /* HEADER_CURL_STRTOOFFT_H */ diff --git a/third_party/curl/lib/system_win32.c b/third_party/curl/lib/system_win32.c new file mode 100644 index 0000000..d2862de --- /dev/null +++ b/third_party/curl/lib/system_win32.c @@ -0,0 +1,270 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, . + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(_WIN32) + +#include +#include "system_win32.h" +#include "version_win32.h" +#include "curl_sspi.h" +#include "warnless.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +LARGE_INTEGER Curl_freq; +bool Curl_isVistaOrGreater; +bool Curl_isWindows8OrGreater; + +/* Handle of iphlpapp.dll */ +static HMODULE s_hIpHlpApiDll = NULL; + +/* Function pointers */ +IF_NAMETOINDEX_FN Curl_if_nametoindex = NULL; +FREEADDRINFOEXW_FN Curl_FreeAddrInfoExW = NULL; +GETADDRINFOEXCANCEL_FN Curl_GetAddrInfoExCancel = NULL; +GETADDRINFOEXW_FN Curl_GetAddrInfoExW = NULL; + +/* Curl_win32_init() performs win32 global initialization */ +CURLcode Curl_win32_init(long flags) +{ +#ifdef USE_WINSOCK + HMODULE ws2_32Dll; +#endif + /* CURL_GLOBAL_WIN32 controls the *optional* part of the initialization which + is just for Winsock at the moment. Any required win32 initialization + should take place after this block. */ + if(flags & CURL_GLOBAL_WIN32) { +#ifdef USE_WINSOCK + WORD wVersionRequested; + WSADATA wsaData; + int res; + + wVersionRequested = MAKEWORD(2, 2); + res = WSAStartup(wVersionRequested, &wsaData); + + if(res) + /* Tell the user that we couldn't find a usable */ + /* winsock.dll. */ + return CURLE_FAILED_INIT; + + /* Confirm that the Windows Sockets DLL supports what we need.*/ + /* Note that if the DLL supports versions greater */ + /* than wVersionRequested, it will still return */ + /* wVersionRequested in wVersion. wHighVersion contains the */ + /* highest supported version. */ + + if(LOBYTE(wsaData.wVersion) != LOBYTE(wVersionRequested) || + HIBYTE(wsaData.wVersion) != HIBYTE(wVersionRequested) ) { + /* Tell the user that we couldn't find a usable */ + + /* winsock.dll. */ + WSACleanup(); + return CURLE_FAILED_INIT; + } + /* The Windows Sockets DLL is acceptable. Proceed. */ +#elif defined(USE_LWIPSOCK) + lwip_init(); +#endif + } /* CURL_GLOBAL_WIN32 */ + +#ifdef USE_WINDOWS_SSPI + { + CURLcode result = Curl_sspi_global_init(); + if(result) + return result; + } +#endif + + s_hIpHlpApiDll = Curl_load_library(TEXT("iphlpapi.dll")); + if(s_hIpHlpApiDll) { + /* Get the address of the if_nametoindex function */ + IF_NAMETOINDEX_FN pIfNameToIndex = + CURLX_FUNCTION_CAST(IF_NAMETOINDEX_FN, + (GetProcAddress(s_hIpHlpApiDll, "if_nametoindex"))); + + if(pIfNameToIndex) + Curl_if_nametoindex = pIfNameToIndex; + } + +#ifdef USE_WINSOCK + ws2_32Dll = GetModuleHandleA("ws2_32"); + if(ws2_32Dll) { + Curl_FreeAddrInfoExW = CURLX_FUNCTION_CAST(FREEADDRINFOEXW_FN, + GetProcAddress(ws2_32Dll, "FreeAddrInfoExW")); + Curl_GetAddrInfoExCancel = CURLX_FUNCTION_CAST(GETADDRINFOEXCANCEL_FN, + GetProcAddress(ws2_32Dll, "GetAddrInfoExCancel")); + Curl_GetAddrInfoExW = CURLX_FUNCTION_CAST(GETADDRINFOEXW_FN, + GetProcAddress(ws2_32Dll, "GetAddrInfoExW")); + } +#endif + + /* curlx_verify_windows_version must be called during init at least once + because it has its own initialization routine. */ + if(curlx_verify_windows_version(6, 0, 0, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) { + Curl_isVistaOrGreater = TRUE; + } + else + Curl_isVistaOrGreater = FALSE; + + if(curlx_verify_windows_version(6, 2, 0, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) { + Curl_isWindows8OrGreater = TRUE; + } + else + Curl_isWindows8OrGreater = FALSE; + + QueryPerformanceFrequency(&Curl_freq); + return CURLE_OK; +} + +/* Curl_win32_cleanup() is the opposite of Curl_win32_init() */ +void Curl_win32_cleanup(long init_flags) +{ + Curl_FreeAddrInfoExW = NULL; + Curl_GetAddrInfoExCancel = NULL; + Curl_GetAddrInfoExW = NULL; + if(s_hIpHlpApiDll) { + FreeLibrary(s_hIpHlpApiDll); + s_hIpHlpApiDll = NULL; + Curl_if_nametoindex = NULL; + } + +#ifdef USE_WINDOWS_SSPI + Curl_sspi_global_cleanup(); +#endif + + if(init_flags & CURL_GLOBAL_WIN32) { +#ifdef USE_WINSOCK + WSACleanup(); +#endif + } +} + +#if !defined(LOAD_WITH_ALTERED_SEARCH_PATH) +#define LOAD_WITH_ALTERED_SEARCH_PATH 0x00000008 +#endif + +#if !defined(LOAD_LIBRARY_SEARCH_SYSTEM32) +#define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800 +#endif + +/* We use our own typedef here since some headers might lack these */ +typedef HMODULE (APIENTRY *LOADLIBRARYEX_FN)(LPCTSTR, HANDLE, DWORD); + +/* See function definitions in winbase.h */ +#ifdef UNICODE +# ifdef _WIN32_WCE +# define LOADLIBARYEX L"LoadLibraryExW" +# else +# define LOADLIBARYEX "LoadLibraryExW" +# endif +#else +# define LOADLIBARYEX "LoadLibraryExA" +#endif + +/* + * Curl_load_library() + * + * This is used to dynamically load DLLs using the most secure method available + * for the version of Windows that we are running on. + * + * Parameters: + * + * filename [in] - The filename or full path of the DLL to load. If only the + * filename is passed then the DLL will be loaded from the + * Windows system directory. + * + * Returns the handle of the module on success; otherwise NULL. + */ +HMODULE Curl_load_library(LPCTSTR filename) +{ +#ifndef CURL_WINDOWS_APP + HMODULE hModule = NULL; + LOADLIBRARYEX_FN pLoadLibraryEx = NULL; + + /* Get a handle to kernel32 so we can access it's functions at runtime */ + HMODULE hKernel32 = GetModuleHandle(TEXT("kernel32")); + if(!hKernel32) + return NULL; + + /* Attempt to find LoadLibraryEx() which is only available on Windows 2000 + and above */ + pLoadLibraryEx = + CURLX_FUNCTION_CAST(LOADLIBRARYEX_FN, + (GetProcAddress(hKernel32, LOADLIBARYEX))); + + /* Detect if there's already a path in the filename and load the library if + there is. Note: Both back slashes and forward slashes have been supported + since the earlier days of DOS at an API level although they are not + supported by command prompt */ + if(_tcspbrk(filename, TEXT("\\/"))) { + /** !checksrc! disable BANNEDFUNC 1 **/ + hModule = pLoadLibraryEx ? + pLoadLibraryEx(filename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH) : + LoadLibrary(filename); + } + /* Detect if KB2533623 is installed, as LOAD_LIBRARY_SEARCH_SYSTEM32 is only + supported on Windows Vista, Windows Server 2008, Windows 7 and Windows + Server 2008 R2 with this patch or natively on Windows 8 and above */ + else if(pLoadLibraryEx && GetProcAddress(hKernel32, "AddDllDirectory")) { + /* Load the DLL from the Windows system directory */ + hModule = pLoadLibraryEx(filename, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); + } + else { + /* Attempt to get the Windows system path */ + UINT systemdirlen = GetSystemDirectory(NULL, 0); + if(systemdirlen) { + /* Allocate space for the full DLL path (Room for the null terminator + is included in systemdirlen) */ + size_t filenamelen = _tcslen(filename); + TCHAR *path = malloc(sizeof(TCHAR) * (systemdirlen + 1 + filenamelen)); + if(path && GetSystemDirectory(path, systemdirlen)) { + /* Calculate the full DLL path */ + _tcscpy(path + _tcslen(path), TEXT("\\")); + _tcscpy(path + _tcslen(path), filename); + + /* Load the DLL from the Windows system directory */ + /** !checksrc! disable BANNEDFUNC 1 **/ + hModule = pLoadLibraryEx ? + pLoadLibraryEx(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH) : + LoadLibrary(path); + + } + free(path); + } + } + return hModule; +#else + /* the Universal Windows Platform (UWP) can't do this */ + (void)filename; + return NULL; +#endif +} + +#endif /* _WIN32 */ diff --git a/third_party/curl/lib/system_win32.h b/third_party/curl/lib/system_win32.h new file mode 100644 index 0000000..bd490ca --- /dev/null +++ b/third_party/curl/lib/system_win32.h @@ -0,0 +1,77 @@ +#ifndef HEADER_CURL_SYSTEM_WIN32_H +#define HEADER_CURL_SYSTEM_WIN32_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, . + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef _WIN32 + +extern LARGE_INTEGER Curl_freq; +extern bool Curl_isVistaOrGreater; +extern bool Curl_isWindows8OrGreater; + +CURLcode Curl_win32_init(long flags); +void Curl_win32_cleanup(long init_flags); + +/* We use our own typedef here since some headers might lack this */ +typedef unsigned int(WINAPI *IF_NAMETOINDEX_FN)(const char *); + +/* This is used instead of if_nametoindex if available on Windows */ +extern IF_NAMETOINDEX_FN Curl_if_nametoindex; + +/* Identical copy of addrinfoexW/ADDRINFOEXW */ +typedef struct addrinfoexW_ +{ + int ai_flags; + int ai_family; + int ai_socktype; + int ai_protocol; + size_t ai_addrlen; + PWSTR ai_canonname; + struct sockaddr *ai_addr; + void *ai_blob; + size_t ai_bloblen; + LPGUID ai_provider; + struct addrinfoexW_ *ai_next; +} ADDRINFOEXW_; + +typedef void (CALLBACK *LOOKUP_COMPLETION_FN)(DWORD, DWORD, LPWSAOVERLAPPED); +typedef void (WSAAPI *FREEADDRINFOEXW_FN)(ADDRINFOEXW_*); +typedef int (WSAAPI *GETADDRINFOEXCANCEL_FN)(LPHANDLE); +typedef int (WSAAPI *GETADDRINFOEXW_FN)(PCWSTR, PCWSTR, DWORD, LPGUID, + const ADDRINFOEXW_*, ADDRINFOEXW_**, struct timeval*, LPOVERLAPPED, + LOOKUP_COMPLETION_FN, LPHANDLE); + +extern FREEADDRINFOEXW_FN Curl_FreeAddrInfoExW; +extern GETADDRINFOEXCANCEL_FN Curl_GetAddrInfoExCancel; +extern GETADDRINFOEXW_FN Curl_GetAddrInfoExW; + +/* This is used to dynamically load DLLs */ +HMODULE Curl_load_library(LPCTSTR filename); +#else /* _WIN32 */ +#define Curl_win32_init(x) CURLE_OK +#endif /* !_WIN32 */ + +#endif /* HEADER_CURL_SYSTEM_WIN32_H */ diff --git a/third_party/curl/lib/telnet.c b/third_party/curl/lib/telnet.c new file mode 100644 index 0000000..227a166 --- /dev/null +++ b/third_party/curl/lib/telnet.c @@ -0,0 +1,1652 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_TELNET + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NET_IF_H +#include +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif + +#ifdef HAVE_SYS_PARAM_H +#include +#endif + +#include "urldata.h" +#include +#include "transfer.h" +#include "sendf.h" +#include "telnet.h" +#include "connect.h" +#include "progress.h" +#include "system_win32.h" +#include "arpa_telnet.h" +#include "select.h" +#include "strcase.h" +#include "warnless.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#define SUBBUFSIZE 512 + +#define CURL_SB_CLEAR(x) x->subpointer = x->subbuffer +#define CURL_SB_TERM(x) \ + do { \ + x->subend = x->subpointer; \ + CURL_SB_CLEAR(x); \ + } while(0) +#define CURL_SB_ACCUM(x,c) \ + do { \ + if(x->subpointer < (x->subbuffer + sizeof(x->subbuffer))) \ + *x->subpointer++ = (c); \ + } while(0) + +#define CURL_SB_GET(x) ((*x->subpointer++)&0xff) +#define CURL_SB_LEN(x) (x->subend - x->subpointer) + +/* For posterity: +#define CURL_SB_PEEK(x) ((*x->subpointer)&0xff) +#define CURL_SB_EOF(x) (x->subpointer >= x->subend) */ + +#ifdef CURL_DISABLE_VERBOSE_STRINGS +#define printoption(a,b,c,d) Curl_nop_stmt +#endif + +static +CURLcode telrcv(struct Curl_easy *data, + const unsigned char *inbuf, /* Data received from socket */ + ssize_t count); /* Number of bytes received */ + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +static void printoption(struct Curl_easy *data, + const char *direction, + int cmd, int option); +#endif + +static void negotiate(struct Curl_easy *data); +static void send_negotiation(struct Curl_easy *data, int cmd, int option); +static void set_local_option(struct Curl_easy *data, + int option, int newstate); +static void set_remote_option(struct Curl_easy *data, + int option, int newstate); + +static void printsub(struct Curl_easy *data, + int direction, unsigned char *pointer, + size_t length); +static void suboption(struct Curl_easy *data); +static void sendsuboption(struct Curl_easy *data, int option); + +static CURLcode telnet_do(struct Curl_easy *data, bool *done); +static CURLcode telnet_done(struct Curl_easy *data, + CURLcode, bool premature); +static CURLcode send_telnet_data(struct Curl_easy *data, + char *buffer, ssize_t nread); + +/* For negotiation compliant to RFC 1143 */ +#define CURL_NO 0 +#define CURL_YES 1 +#define CURL_WANTYES 2 +#define CURL_WANTNO 3 + +#define CURL_EMPTY 0 +#define CURL_OPPOSITE 1 + +/* + * Telnet receiver states for fsm + */ +typedef enum +{ + CURL_TS_DATA = 0, + CURL_TS_IAC, + CURL_TS_WILL, + CURL_TS_WONT, + CURL_TS_DO, + CURL_TS_DONT, + CURL_TS_CR, + CURL_TS_SB, /* sub-option collection */ + CURL_TS_SE /* looking for sub-option end */ +} TelnetReceive; + +struct TELNET { + int please_negotiate; + int already_negotiated; + int us[256]; + int usq[256]; + int us_preferred[256]; + int him[256]; + int himq[256]; + int him_preferred[256]; + int subnegotiation[256]; + char subopt_ttype[32]; /* Set with suboption TTYPE */ + char subopt_xdisploc[128]; /* Set with suboption XDISPLOC */ + unsigned short subopt_wsx; /* Set with suboption NAWS */ + unsigned short subopt_wsy; /* Set with suboption NAWS */ + TelnetReceive telrcv_state; + struct curl_slist *telnet_vars; /* Environment variables */ + struct dynbuf out; /* output buffer */ + + /* suboptions */ + unsigned char subbuffer[SUBBUFSIZE]; + unsigned char *subpointer, *subend; /* buffer for sub-options */ +}; + + +/* + * TELNET protocol handler. + */ + +const struct Curl_handler Curl_handler_telnet = { + "telnet", /* scheme */ + ZERO_NULL, /* setup_connection */ + telnet_do, /* do_it */ + telnet_done, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_TELNET, /* defport */ + CURLPROTO_TELNET, /* protocol */ + CURLPROTO_TELNET, /* family */ + PROTOPT_NONE | PROTOPT_NOURLQUERY /* flags */ +}; + + +static +CURLcode init_telnet(struct Curl_easy *data) +{ + struct TELNET *tn; + + tn = calloc(1, sizeof(struct TELNET)); + if(!tn) + return CURLE_OUT_OF_MEMORY; + + Curl_dyn_init(&tn->out, 0xffff); + data->req.p.telnet = tn; /* make us known */ + + tn->telrcv_state = CURL_TS_DATA; + + /* Init suboptions */ + CURL_SB_CLEAR(tn); + + /* Set the options we want by default */ + tn->us_preferred[CURL_TELOPT_SGA] = CURL_YES; + tn->him_preferred[CURL_TELOPT_SGA] = CURL_YES; + + /* To be compliant with previous releases of libcurl + we enable this option by default. This behavior + can be changed thanks to the "BINARY" option in + CURLOPT_TELNETOPTIONS + */ + tn->us_preferred[CURL_TELOPT_BINARY] = CURL_YES; + tn->him_preferred[CURL_TELOPT_BINARY] = CURL_YES; + + /* We must allow the server to echo what we sent + but it is not necessary to request the server + to do so (it might forces the server to close + the connection). Hence, we ignore ECHO in the + negotiate function + */ + tn->him_preferred[CURL_TELOPT_ECHO] = CURL_YES; + + /* Set the subnegotiation fields to send information + just after negotiation passed (do/will) + + Default values are (0,0) initialized by calloc. + According to the RFC1013 it is valid: + A value equal to zero is acceptable for the width (or height), + and means that no character width (or height) is being sent. + In this case, the width (or height) that will be assumed by the + Telnet server is operating system specific (it will probably be + based upon the terminal type information that may have been sent + using the TERMINAL TYPE Telnet option). */ + tn->subnegotiation[CURL_TELOPT_NAWS] = CURL_YES; + return CURLE_OK; +} + +static void negotiate(struct Curl_easy *data) +{ + int i; + struct TELNET *tn = data->req.p.telnet; + + for(i = 0; i < CURL_NTELOPTS; i++) { + if(i == CURL_TELOPT_ECHO) + continue; + + if(tn->us_preferred[i] == CURL_YES) + set_local_option(data, i, CURL_YES); + + if(tn->him_preferred[i] == CURL_YES) + set_remote_option(data, i, CURL_YES); + } +} + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +static void printoption(struct Curl_easy *data, + const char *direction, int cmd, int option) +{ + if(data->set.verbose) { + if(cmd == CURL_IAC) { + if(CURL_TELCMD_OK(option)) + infof(data, "%s IAC %s", direction, CURL_TELCMD(option)); + else + infof(data, "%s IAC %d", direction, option); + } + else { + const char *fmt = (cmd == CURL_WILL) ? "WILL" : + (cmd == CURL_WONT) ? "WONT" : + (cmd == CURL_DO) ? "DO" : + (cmd == CURL_DONT) ? "DONT" : 0; + if(fmt) { + const char *opt; + if(CURL_TELOPT_OK(option)) + opt = CURL_TELOPT(option); + else if(option == CURL_TELOPT_EXOPL) + opt = "EXOPL"; + else + opt = NULL; + + if(opt) + infof(data, "%s %s %s", direction, fmt, opt); + else + infof(data, "%s %s %d", direction, fmt, option); + } + else + infof(data, "%s %d %d", direction, cmd, option); + } + } +} +#endif + +static void send_negotiation(struct Curl_easy *data, int cmd, int option) +{ + unsigned char buf[3]; + ssize_t bytes_written; + struct connectdata *conn = data->conn; + + buf[0] = CURL_IAC; + buf[1] = (unsigned char)cmd; + buf[2] = (unsigned char)option; + + bytes_written = swrite(conn->sock[FIRSTSOCKET], buf, 3); + if(bytes_written < 0) { + int err = SOCKERRNO; + failf(data,"Sending data failed (%d)",err); + } + + printoption(data, "SENT", cmd, option); +} + +static +void set_remote_option(struct Curl_easy *data, int option, int newstate) +{ + struct TELNET *tn = data->req.p.telnet; + if(newstate == CURL_YES) { + switch(tn->him[option]) { + case CURL_NO: + tn->him[option] = CURL_WANTYES; + send_negotiation(data, CURL_DO, option); + break; + + case CURL_YES: + /* Already enabled */ + break; + + case CURL_WANTNO: + switch(tn->himq[option]) { + case CURL_EMPTY: + /* Already negotiating for CURL_YES, queue the request */ + tn->himq[option] = CURL_OPPOSITE; + break; + case CURL_OPPOSITE: + /* Error: already queued an enable request */ + break; + } + break; + + case CURL_WANTYES: + switch(tn->himq[option]) { + case CURL_EMPTY: + /* Error: already negotiating for enable */ + break; + case CURL_OPPOSITE: + tn->himq[option] = CURL_EMPTY; + break; + } + break; + } + } + else { /* NO */ + switch(tn->him[option]) { + case CURL_NO: + /* Already disabled */ + break; + + case CURL_YES: + tn->him[option] = CURL_WANTNO; + send_negotiation(data, CURL_DONT, option); + break; + + case CURL_WANTNO: + switch(tn->himq[option]) { + case CURL_EMPTY: + /* Already negotiating for NO */ + break; + case CURL_OPPOSITE: + tn->himq[option] = CURL_EMPTY; + break; + } + break; + + case CURL_WANTYES: + switch(tn->himq[option]) { + case CURL_EMPTY: + tn->himq[option] = CURL_OPPOSITE; + break; + case CURL_OPPOSITE: + break; + } + break; + } + } +} + +static +void rec_will(struct Curl_easy *data, int option) +{ + struct TELNET *tn = data->req.p.telnet; + switch(tn->him[option]) { + case CURL_NO: + if(tn->him_preferred[option] == CURL_YES) { + tn->him[option] = CURL_YES; + send_negotiation(data, CURL_DO, option); + } + else + send_negotiation(data, CURL_DONT, option); + + break; + + case CURL_YES: + /* Already enabled */ + break; + + case CURL_WANTNO: + switch(tn->himq[option]) { + case CURL_EMPTY: + /* Error: DONT answered by WILL */ + tn->him[option] = CURL_NO; + break; + case CURL_OPPOSITE: + /* Error: DONT answered by WILL */ + tn->him[option] = CURL_YES; + tn->himq[option] = CURL_EMPTY; + break; + } + break; + + case CURL_WANTYES: + switch(tn->himq[option]) { + case CURL_EMPTY: + tn->him[option] = CURL_YES; + break; + case CURL_OPPOSITE: + tn->him[option] = CURL_WANTNO; + tn->himq[option] = CURL_EMPTY; + send_negotiation(data, CURL_DONT, option); + break; + } + break; + } +} + +static +void rec_wont(struct Curl_easy *data, int option) +{ + struct TELNET *tn = data->req.p.telnet; + switch(tn->him[option]) { + case CURL_NO: + /* Already disabled */ + break; + + case CURL_YES: + tn->him[option] = CURL_NO; + send_negotiation(data, CURL_DONT, option); + break; + + case CURL_WANTNO: + switch(tn->himq[option]) { + case CURL_EMPTY: + tn->him[option] = CURL_NO; + break; + + case CURL_OPPOSITE: + tn->him[option] = CURL_WANTYES; + tn->himq[option] = CURL_EMPTY; + send_negotiation(data, CURL_DO, option); + break; + } + break; + + case CURL_WANTYES: + switch(tn->himq[option]) { + case CURL_EMPTY: + tn->him[option] = CURL_NO; + break; + case CURL_OPPOSITE: + tn->him[option] = CURL_NO; + tn->himq[option] = CURL_EMPTY; + break; + } + break; + } +} + +static void +set_local_option(struct Curl_easy *data, int option, int newstate) +{ + struct TELNET *tn = data->req.p.telnet; + if(newstate == CURL_YES) { + switch(tn->us[option]) { + case CURL_NO: + tn->us[option] = CURL_WANTYES; + send_negotiation(data, CURL_WILL, option); + break; + + case CURL_YES: + /* Already enabled */ + break; + + case CURL_WANTNO: + switch(tn->usq[option]) { + case CURL_EMPTY: + /* Already negotiating for CURL_YES, queue the request */ + tn->usq[option] = CURL_OPPOSITE; + break; + case CURL_OPPOSITE: + /* Error: already queued an enable request */ + break; + } + break; + + case CURL_WANTYES: + switch(tn->usq[option]) { + case CURL_EMPTY: + /* Error: already negotiating for enable */ + break; + case CURL_OPPOSITE: + tn->usq[option] = CURL_EMPTY; + break; + } + break; + } + } + else { /* NO */ + switch(tn->us[option]) { + case CURL_NO: + /* Already disabled */ + break; + + case CURL_YES: + tn->us[option] = CURL_WANTNO; + send_negotiation(data, CURL_WONT, option); + break; + + case CURL_WANTNO: + switch(tn->usq[option]) { + case CURL_EMPTY: + /* Already negotiating for NO */ + break; + case CURL_OPPOSITE: + tn->usq[option] = CURL_EMPTY; + break; + } + break; + + case CURL_WANTYES: + switch(tn->usq[option]) { + case CURL_EMPTY: + tn->usq[option] = CURL_OPPOSITE; + break; + case CURL_OPPOSITE: + break; + } + break; + } + } +} + +static +void rec_do(struct Curl_easy *data, int option) +{ + struct TELNET *tn = data->req.p.telnet; + switch(tn->us[option]) { + case CURL_NO: + if(tn->us_preferred[option] == CURL_YES) { + tn->us[option] = CURL_YES; + send_negotiation(data, CURL_WILL, option); + if(tn->subnegotiation[option] == CURL_YES) + /* transmission of data option */ + sendsuboption(data, option); + } + else if(tn->subnegotiation[option] == CURL_YES) { + /* send information to achieve this option */ + tn->us[option] = CURL_YES; + send_negotiation(data, CURL_WILL, option); + sendsuboption(data, option); + } + else + send_negotiation(data, CURL_WONT, option); + break; + + case CURL_YES: + /* Already enabled */ + break; + + case CURL_WANTNO: + switch(tn->usq[option]) { + case CURL_EMPTY: + /* Error: DONT answered by WILL */ + tn->us[option] = CURL_NO; + break; + case CURL_OPPOSITE: + /* Error: DONT answered by WILL */ + tn->us[option] = CURL_YES; + tn->usq[option] = CURL_EMPTY; + break; + } + break; + + case CURL_WANTYES: + switch(tn->usq[option]) { + case CURL_EMPTY: + tn->us[option] = CURL_YES; + if(tn->subnegotiation[option] == CURL_YES) { + /* transmission of data option */ + sendsuboption(data, option); + } + break; + case CURL_OPPOSITE: + tn->us[option] = CURL_WANTNO; + tn->himq[option] = CURL_EMPTY; + send_negotiation(data, CURL_WONT, option); + break; + } + break; + } +} + +static +void rec_dont(struct Curl_easy *data, int option) +{ + struct TELNET *tn = data->req.p.telnet; + switch(tn->us[option]) { + case CURL_NO: + /* Already disabled */ + break; + + case CURL_YES: + tn->us[option] = CURL_NO; + send_negotiation(data, CURL_WONT, option); + break; + + case CURL_WANTNO: + switch(tn->usq[option]) { + case CURL_EMPTY: + tn->us[option] = CURL_NO; + break; + + case CURL_OPPOSITE: + tn->us[option] = CURL_WANTYES; + tn->usq[option] = CURL_EMPTY; + send_negotiation(data, CURL_WILL, option); + break; + } + break; + + case CURL_WANTYES: + switch(tn->usq[option]) { + case CURL_EMPTY: + tn->us[option] = CURL_NO; + break; + case CURL_OPPOSITE: + tn->us[option] = CURL_NO; + tn->usq[option] = CURL_EMPTY; + break; + } + break; + } +} + + +static void printsub(struct Curl_easy *data, + int direction, /* '<' or '>' */ + unsigned char *pointer, /* where suboption data is */ + size_t length) /* length of suboption data */ +{ + if(data->set.verbose) { + unsigned int i = 0; + if(direction) { + infof(data, "%s IAC SB ", (direction == '<')? "RCVD":"SENT"); + if(length >= 3) { + int j; + + i = pointer[length-2]; + j = pointer[length-1]; + + if(i != CURL_IAC || j != CURL_SE) { + infof(data, "(terminated by "); + if(CURL_TELOPT_OK(i)) + infof(data, "%s ", CURL_TELOPT(i)); + else if(CURL_TELCMD_OK(i)) + infof(data, "%s ", CURL_TELCMD(i)); + else + infof(data, "%u ", i); + if(CURL_TELOPT_OK(j)) + infof(data, "%s", CURL_TELOPT(j)); + else if(CURL_TELCMD_OK(j)) + infof(data, "%s", CURL_TELCMD(j)); + else + infof(data, "%d", j); + infof(data, ", not IAC SE) "); + } + } + length -= 2; + } + if(length < 1) { + infof(data, "(Empty suboption?)"); + return; + } + + if(CURL_TELOPT_OK(pointer[0])) { + switch(pointer[0]) { + case CURL_TELOPT_TTYPE: + case CURL_TELOPT_XDISPLOC: + case CURL_TELOPT_NEW_ENVIRON: + case CURL_TELOPT_NAWS: + infof(data, "%s", CURL_TELOPT(pointer[0])); + break; + default: + infof(data, "%s (unsupported)", CURL_TELOPT(pointer[0])); + break; + } + } + else + infof(data, "%d (unknown)", pointer[i]); + + switch(pointer[0]) { + case CURL_TELOPT_NAWS: + if(length > 4) + infof(data, "Width: %d ; Height: %d", (pointer[1]<<8) | pointer[2], + (pointer[3]<<8) | pointer[4]); + break; + default: + switch(pointer[1]) { + case CURL_TELQUAL_IS: + infof(data, " IS"); + break; + case CURL_TELQUAL_SEND: + infof(data, " SEND"); + break; + case CURL_TELQUAL_INFO: + infof(data, " INFO/REPLY"); + break; + case CURL_TELQUAL_NAME: + infof(data, " NAME"); + break; + } + + switch(pointer[0]) { + case CURL_TELOPT_TTYPE: + case CURL_TELOPT_XDISPLOC: + pointer[length] = 0; + infof(data, " \"%s\"", &pointer[2]); + break; + case CURL_TELOPT_NEW_ENVIRON: + if(pointer[1] == CURL_TELQUAL_IS) { + infof(data, " "); + for(i = 3; i < length; i++) { + switch(pointer[i]) { + case CURL_NEW_ENV_VAR: + infof(data, ", "); + break; + case CURL_NEW_ENV_VALUE: + infof(data, " = "); + break; + default: + infof(data, "%c", pointer[i]); + break; + } + } + } + break; + default: + for(i = 2; i < length; i++) + infof(data, " %.2x", pointer[i]); + break; + } + } + } +} + +#ifdef _MSC_VER +#pragma warning(push) +/* warning C4706: assignment within conditional expression */ +#pragma warning(disable:4706) +#endif +static bool str_is_nonascii(const char *str) +{ + char c; + while((c = *str++)) + if(c & 0x80) + return TRUE; + + return FALSE; +} +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +static CURLcode check_telnet_options(struct Curl_easy *data) +{ + struct curl_slist *head; + struct curl_slist *beg; + struct TELNET *tn = data->req.p.telnet; + CURLcode result = CURLE_OK; + + /* Add the user name as an environment variable if it + was given on the command line */ + if(data->state.aptr.user) { + char buffer[256]; + if(str_is_nonascii(data->conn->user)) { + DEBUGF(infof(data, "set a non ASCII user name in telnet")); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + msnprintf(buffer, sizeof(buffer), "USER,%s", data->conn->user); + beg = curl_slist_append(tn->telnet_vars, buffer); + if(!beg) { + curl_slist_free_all(tn->telnet_vars); + tn->telnet_vars = NULL; + return CURLE_OUT_OF_MEMORY; + } + tn->telnet_vars = beg; + tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES; + } + + for(head = data->set.telnet_options; head && !result; head = head->next) { + size_t olen; + char *option = head->data; + char *arg; + char *sep = strchr(option, '='); + if(sep) { + olen = sep - option; + arg = ++sep; + if(str_is_nonascii(arg)) + continue; + switch(olen) { + case 5: + /* Terminal type */ + if(strncasecompare(option, "TTYPE", 5)) { + size_t l = strlen(arg); + if(l < sizeof(tn->subopt_ttype)) { + strcpy(tn->subopt_ttype, arg); + tn->us_preferred[CURL_TELOPT_TTYPE] = CURL_YES; + break; + } + } + result = CURLE_UNKNOWN_OPTION; + break; + + case 8: + /* Display variable */ + if(strncasecompare(option, "XDISPLOC", 8)) { + size_t l = strlen(arg); + if(l < sizeof(tn->subopt_xdisploc)) { + strcpy(tn->subopt_xdisploc, arg); + tn->us_preferred[CURL_TELOPT_XDISPLOC] = CURL_YES; + break; + } + } + result = CURLE_UNKNOWN_OPTION; + break; + + case 7: + /* Environment variable */ + if(strncasecompare(option, "NEW_ENV", 7)) { + beg = curl_slist_append(tn->telnet_vars, arg); + if(!beg) { + result = CURLE_OUT_OF_MEMORY; + break; + } + tn->telnet_vars = beg; + tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES; + } + else + result = CURLE_UNKNOWN_OPTION; + break; + + case 2: + /* Window Size */ + if(strncasecompare(option, "WS", 2)) { + char *p; + unsigned long x = strtoul(arg, &p, 10); + unsigned long y = 0; + if(x && (x <= 0xffff) && Curl_raw_tolower(*p) == 'x') { + p++; + y = strtoul(p, NULL, 10); + if(y && (y <= 0xffff)) { + tn->subopt_wsx = (unsigned short)x; + tn->subopt_wsy = (unsigned short)y; + tn->us_preferred[CURL_TELOPT_NAWS] = CURL_YES; + } + } + if(!y) { + failf(data, "Syntax error in telnet option: %s", head->data); + result = CURLE_SETOPT_OPTION_SYNTAX; + } + } + else + result = CURLE_UNKNOWN_OPTION; + break; + + case 6: + /* To take care or not of the 8th bit in data exchange */ + if(strncasecompare(option, "BINARY", 6)) { + int binary_option = atoi(arg); + if(binary_option != 1) { + tn->us_preferred[CURL_TELOPT_BINARY] = CURL_NO; + tn->him_preferred[CURL_TELOPT_BINARY] = CURL_NO; + } + } + else + result = CURLE_UNKNOWN_OPTION; + break; + default: + failf(data, "Unknown telnet option %s", head->data); + result = CURLE_UNKNOWN_OPTION; + break; + } + } + else { + failf(data, "Syntax error in telnet option: %s", head->data); + result = CURLE_SETOPT_OPTION_SYNTAX; + } + } + + if(result) { + curl_slist_free_all(tn->telnet_vars); + tn->telnet_vars = NULL; + } + + return result; +} + +/* + * suboption() + * + * Look at the sub-option buffer, and try to be helpful to the other + * side. + */ + +static void suboption(struct Curl_easy *data) +{ + struct curl_slist *v; + unsigned char temp[2048]; + ssize_t bytes_written; + size_t len; + int err; + struct TELNET *tn = data->req.p.telnet; + struct connectdata *conn = data->conn; + + printsub(data, '<', (unsigned char *)tn->subbuffer, CURL_SB_LEN(tn) + 2); + switch(CURL_SB_GET(tn)) { + case CURL_TELOPT_TTYPE: + len = strlen(tn->subopt_ttype) + 4 + 2; + msnprintf((char *)temp, sizeof(temp), + "%c%c%c%c%s%c%c", CURL_IAC, CURL_SB, CURL_TELOPT_TTYPE, + CURL_TELQUAL_IS, tn->subopt_ttype, CURL_IAC, CURL_SE); + bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len); + if(bytes_written < 0) { + err = SOCKERRNO; + failf(data,"Sending data failed (%d)",err); + } + printsub(data, '>', &temp[2], len-2); + break; + case CURL_TELOPT_XDISPLOC: + len = strlen(tn->subopt_xdisploc) + 4 + 2; + msnprintf((char *)temp, sizeof(temp), + "%c%c%c%c%s%c%c", CURL_IAC, CURL_SB, CURL_TELOPT_XDISPLOC, + CURL_TELQUAL_IS, tn->subopt_xdisploc, CURL_IAC, CURL_SE); + bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len); + if(bytes_written < 0) { + err = SOCKERRNO; + failf(data,"Sending data failed (%d)",err); + } + printsub(data, '>', &temp[2], len-2); + break; + case CURL_TELOPT_NEW_ENVIRON: + msnprintf((char *)temp, sizeof(temp), + "%c%c%c%c", CURL_IAC, CURL_SB, CURL_TELOPT_NEW_ENVIRON, + CURL_TELQUAL_IS); + len = 4; + + for(v = tn->telnet_vars; v; v = v->next) { + size_t tmplen = (strlen(v->data) + 1); + /* Add the variable if it fits */ + if(len + tmplen < (int)sizeof(temp)-6) { + char *s = strchr(v->data, ','); + if(!s) + len += msnprintf((char *)&temp[len], sizeof(temp) - len, + "%c%s", CURL_NEW_ENV_VAR, v->data); + else { + size_t vlen = s - v->data; + len += msnprintf((char *)&temp[len], sizeof(temp) - len, + "%c%.*s%c%s", CURL_NEW_ENV_VAR, + (int)vlen, v->data, CURL_NEW_ENV_VALUE, ++s); + } + } + } + msnprintf((char *)&temp[len], sizeof(temp) - len, + "%c%c", CURL_IAC, CURL_SE); + len += 2; + bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len); + if(bytes_written < 0) { + err = SOCKERRNO; + failf(data,"Sending data failed (%d)",err); + } + printsub(data, '>', &temp[2], len-2); + break; + } + return; +} + + +/* + * sendsuboption() + * + * Send suboption information to the server side. + */ + +static void sendsuboption(struct Curl_easy *data, int option) +{ + ssize_t bytes_written; + int err; + unsigned short x, y; + unsigned char *uc1, *uc2; + struct TELNET *tn = data->req.p.telnet; + struct connectdata *conn = data->conn; + + switch(option) { + case CURL_TELOPT_NAWS: + /* We prepare data to be sent */ + CURL_SB_CLEAR(tn); + CURL_SB_ACCUM(tn, CURL_IAC); + CURL_SB_ACCUM(tn, CURL_SB); + CURL_SB_ACCUM(tn, CURL_TELOPT_NAWS); + /* We must deal either with little or big endian processors */ + /* Window size must be sent according to the 'network order' */ + x = htons(tn->subopt_wsx); + y = htons(tn->subopt_wsy); + uc1 = (unsigned char *)&x; + uc2 = (unsigned char *)&y; + CURL_SB_ACCUM(tn, uc1[0]); + CURL_SB_ACCUM(tn, uc1[1]); + CURL_SB_ACCUM(tn, uc2[0]); + CURL_SB_ACCUM(tn, uc2[1]); + + CURL_SB_ACCUM(tn, CURL_IAC); + CURL_SB_ACCUM(tn, CURL_SE); + CURL_SB_TERM(tn); + /* data suboption is now ready */ + + printsub(data, '>', (unsigned char *)tn->subbuffer + 2, + CURL_SB_LEN(tn)-2); + + /* we send the header of the suboption... */ + bytes_written = swrite(conn->sock[FIRSTSOCKET], tn->subbuffer, 3); + if(bytes_written < 0) { + err = SOCKERRNO; + failf(data, "Sending data failed (%d)", err); + } + /* ... then the window size with the send_telnet_data() function + to deal with 0xFF cases ... */ + send_telnet_data(data, (char *)tn->subbuffer + 3, 4); + /* ... and the footer */ + bytes_written = swrite(conn->sock[FIRSTSOCKET], tn->subbuffer + 7, 2); + if(bytes_written < 0) { + err = SOCKERRNO; + failf(data, "Sending data failed (%d)", err); + } + break; + } +} + + +static +CURLcode telrcv(struct Curl_easy *data, + const unsigned char *inbuf, /* Data received from socket */ + ssize_t count) /* Number of bytes received */ +{ + unsigned char c; + CURLcode result; + int in = 0; + int startwrite = -1; + struct TELNET *tn = data->req.p.telnet; + +#define startskipping() \ + if(startwrite >= 0) { \ + result = Curl_client_write(data, \ + CLIENTWRITE_BODY, \ + (char *)&inbuf[startwrite], \ + in-startwrite); \ + if(result) \ + return result; \ + } \ + startwrite = -1 + +#define writebyte() \ + if(startwrite < 0) \ + startwrite = in + +#define bufferflush() startskipping() + + while(count--) { + c = inbuf[in]; + + switch(tn->telrcv_state) { + case CURL_TS_CR: + tn->telrcv_state = CURL_TS_DATA; + if(c == '\0') { + startskipping(); + break; /* Ignore \0 after CR */ + } + writebyte(); + break; + + case CURL_TS_DATA: + if(c == CURL_IAC) { + tn->telrcv_state = CURL_TS_IAC; + startskipping(); + break; + } + else if(c == '\r') + tn->telrcv_state = CURL_TS_CR; + writebyte(); + break; + + case CURL_TS_IAC: +process_iac: + DEBUGASSERT(startwrite < 0); + switch(c) { + case CURL_WILL: + tn->telrcv_state = CURL_TS_WILL; + break; + case CURL_WONT: + tn->telrcv_state = CURL_TS_WONT; + break; + case CURL_DO: + tn->telrcv_state = CURL_TS_DO; + break; + case CURL_DONT: + tn->telrcv_state = CURL_TS_DONT; + break; + case CURL_SB: + CURL_SB_CLEAR(tn); + tn->telrcv_state = CURL_TS_SB; + break; + case CURL_IAC: + tn->telrcv_state = CURL_TS_DATA; + writebyte(); + break; + case CURL_DM: + case CURL_NOP: + case CURL_GA: + default: + tn->telrcv_state = CURL_TS_DATA; + printoption(data, "RCVD", CURL_IAC, c); + break; + } + break; + + case CURL_TS_WILL: + printoption(data, "RCVD", CURL_WILL, c); + tn->please_negotiate = 1; + rec_will(data, c); + tn->telrcv_state = CURL_TS_DATA; + break; + + case CURL_TS_WONT: + printoption(data, "RCVD", CURL_WONT, c); + tn->please_negotiate = 1; + rec_wont(data, c); + tn->telrcv_state = CURL_TS_DATA; + break; + + case CURL_TS_DO: + printoption(data, "RCVD", CURL_DO, c); + tn->please_negotiate = 1; + rec_do(data, c); + tn->telrcv_state = CURL_TS_DATA; + break; + + case CURL_TS_DONT: + printoption(data, "RCVD", CURL_DONT, c); + tn->please_negotiate = 1; + rec_dont(data, c); + tn->telrcv_state = CURL_TS_DATA; + break; + + case CURL_TS_SB: + if(c == CURL_IAC) + tn->telrcv_state = CURL_TS_SE; + else + CURL_SB_ACCUM(tn, c); + break; + + case CURL_TS_SE: + if(c != CURL_SE) { + if(c != CURL_IAC) { + /* + * This is an error. We only expect to get "IAC IAC" or "IAC SE". + * Several things may have happened. An IAC was not doubled, the + * IAC SE was left off, or another option got inserted into the + * suboption are all possibilities. If we assume that the IAC was + * not doubled, and really the IAC SE was left off, we could get + * into an infinite loop here. So, instead, we terminate the + * suboption, and process the partial suboption if we can. + */ + CURL_SB_ACCUM(tn, CURL_IAC); + CURL_SB_ACCUM(tn, c); + tn->subpointer -= 2; + CURL_SB_TERM(tn); + + printoption(data, "In SUBOPTION processing, RCVD", CURL_IAC, c); + suboption(data); /* handle sub-option */ + tn->telrcv_state = CURL_TS_IAC; + goto process_iac; + } + CURL_SB_ACCUM(tn, c); + tn->telrcv_state = CURL_TS_SB; + } + else { + CURL_SB_ACCUM(tn, CURL_IAC); + CURL_SB_ACCUM(tn, CURL_SE); + tn->subpointer -= 2; + CURL_SB_TERM(tn); + suboption(data); /* handle sub-option */ + tn->telrcv_state = CURL_TS_DATA; + } + break; + } + ++in; + } + bufferflush(); + return CURLE_OK; +} + +/* Escape and send a telnet data block */ +static CURLcode send_telnet_data(struct Curl_easy *data, + char *buffer, ssize_t nread) +{ + size_t i, outlen; + unsigned char *outbuf; + CURLcode result = CURLE_OK; + size_t bytes_written; + size_t total_written = 0; + struct connectdata *conn = data->conn; + struct TELNET *tn = data->req.p.telnet; + + DEBUGASSERT(tn); + DEBUGASSERT(nread > 0); + if(nread < 0) + return CURLE_TOO_LARGE; + + if(memchr(buffer, CURL_IAC, nread)) { + /* only use the escape buffer when necessary */ + Curl_dyn_reset(&tn->out); + + for(i = 0; i < (size_t)nread && !result; i++) { + result = Curl_dyn_addn(&tn->out, &buffer[i], 1); + if(!result && ((unsigned char)buffer[i] == CURL_IAC)) + /* IAC is FF in hex */ + result = Curl_dyn_addn(&tn->out, "\xff", 1); + } + + outlen = Curl_dyn_len(&tn->out); + outbuf = Curl_dyn_uptr(&tn->out); + } + else { + outlen = (size_t)nread; + outbuf = (unsigned char *)buffer; + } + while(!result && total_written < outlen) { + /* Make sure socket is writable to avoid EWOULDBLOCK condition */ + struct pollfd pfd[1]; + pfd[0].fd = conn->sock[FIRSTSOCKET]; + pfd[0].events = POLLOUT; + switch(Curl_poll(pfd, 1, -1)) { + case -1: /* error, abort writing */ + case 0: /* timeout (will never happen) */ + result = CURLE_SEND_ERROR; + break; + default: /* write! */ + bytes_written = 0; + result = Curl_xfer_send(data, outbuf + total_written, + outlen - total_written, &bytes_written); + total_written += bytes_written; + break; + } + } + + return result; +} + +static CURLcode telnet_done(struct Curl_easy *data, + CURLcode status, bool premature) +{ + struct TELNET *tn = data->req.p.telnet; + (void)status; /* unused */ + (void)premature; /* not used */ + + if(!tn) + return CURLE_OK; + + curl_slist_free_all(tn->telnet_vars); + tn->telnet_vars = NULL; + Curl_dyn_free(&tn->out); + return CURLE_OK; +} + +static CURLcode telnet_do(struct Curl_easy *data, bool *done) +{ + CURLcode result; + struct connectdata *conn = data->conn; + curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; +#ifdef USE_WINSOCK + WSAEVENT event_handle; + WSANETWORKEVENTS events; + HANDLE stdin_handle; + HANDLE objs[2]; + DWORD obj_count; + DWORD wait_timeout; + DWORD readfile_read; + int err; +#else + timediff_t interval_ms; + struct pollfd pfd[2]; + int poll_cnt; + curl_off_t total_dl = 0; + curl_off_t total_ul = 0; +#endif + ssize_t nread; + struct curltime now; + bool keepon = TRUE; + char buffer[4*1024]; + struct TELNET *tn; + + *done = TRUE; /* unconditionally */ + + result = init_telnet(data); + if(result) + return result; + + tn = data->req.p.telnet; + + result = check_telnet_options(data); + if(result) + return result; + +#ifdef USE_WINSOCK + /* We want to wait for both stdin and the socket. Since + ** the select() function in winsock only works on sockets + ** we have to use the WaitForMultipleObjects() call. + */ + + /* First, create a sockets event object */ + event_handle = WSACreateEvent(); + if(event_handle == WSA_INVALID_EVENT) { + failf(data, "WSACreateEvent failed (%d)", SOCKERRNO); + return CURLE_FAILED_INIT; + } + + /* Tell winsock what events we want to listen to */ + if(WSAEventSelect(sockfd, event_handle, FD_READ|FD_CLOSE) == SOCKET_ERROR) { + WSACloseEvent(event_handle); + return CURLE_OK; + } + + /* The get the Windows file handle for stdin */ + stdin_handle = GetStdHandle(STD_INPUT_HANDLE); + + /* Create the list of objects to wait for */ + objs[0] = event_handle; + objs[1] = stdin_handle; + + /* If stdin_handle is a pipe, use PeekNamedPipe() method to check it, + else use the old WaitForMultipleObjects() way */ + if(GetFileType(stdin_handle) == FILE_TYPE_PIPE || + data->set.is_fread_set) { + /* Don't wait for stdin_handle, just wait for event_handle */ + obj_count = 1; + /* Check stdin_handle per 100 milliseconds */ + wait_timeout = 100; + } + else { + obj_count = 2; + wait_timeout = 1000; + } + + /* Keep on listening and act on events */ + while(keepon) { + const DWORD buf_size = (DWORD)sizeof(buffer); + DWORD waitret = WaitForMultipleObjects(obj_count, objs, + FALSE, wait_timeout); + switch(waitret) { + + case WAIT_TIMEOUT: + { + for(;;) { + if(data->set.is_fread_set) { + size_t n; + /* read from user-supplied method */ + n = data->state.fread_func(buffer, 1, buf_size, data->state.in); + if(n == CURL_READFUNC_ABORT) { + keepon = FALSE; + result = CURLE_READ_ERROR; + break; + } + + if(n == CURL_READFUNC_PAUSE) + break; + + if(n == 0) /* no bytes */ + break; + + /* fall through with number of bytes read */ + readfile_read = (DWORD)n; + } + else { + /* read from stdin */ + if(!PeekNamedPipe(stdin_handle, NULL, 0, NULL, + &readfile_read, NULL)) { + keepon = FALSE; + result = CURLE_READ_ERROR; + break; + } + + if(!readfile_read) + break; + + if(!ReadFile(stdin_handle, buffer, buf_size, + &readfile_read, NULL)) { + keepon = FALSE; + result = CURLE_READ_ERROR; + break; + } + } + + result = send_telnet_data(data, buffer, readfile_read); + if(result) { + keepon = FALSE; + break; + } + } + } + break; + + case WAIT_OBJECT_0 + 1: + { + if(!ReadFile(stdin_handle, buffer, buf_size, + &readfile_read, NULL)) { + keepon = FALSE; + result = CURLE_READ_ERROR; + break; + } + + result = send_telnet_data(data, buffer, readfile_read); + if(result) { + keepon = FALSE; + break; + } + } + break; + + case WAIT_OBJECT_0: + { + events.lNetworkEvents = 0; + if(WSAEnumNetworkEvents(sockfd, event_handle, &events) == SOCKET_ERROR) { + err = SOCKERRNO; + if(err != EINPROGRESS) { + infof(data, "WSAEnumNetworkEvents failed (%d)", err); + keepon = FALSE; + result = CURLE_READ_ERROR; + } + break; + } + if(events.lNetworkEvents & FD_READ) { + /* read data from network */ + result = Curl_xfer_recv(data, buffer, sizeof(buffer), &nread); + /* read would've blocked. Loop again */ + if(result == CURLE_AGAIN) + break; + /* returned not-zero, this an error */ + else if(result) { + keepon = FALSE; + break; + } + /* returned zero but actually received 0 or less here, + the server closed the connection and we bail out */ + else if(nread <= 0) { + keepon = FALSE; + break; + } + + result = telrcv(data, (unsigned char *) buffer, nread); + if(result) { + keepon = FALSE; + break; + } + + /* Negotiate if the peer has started negotiating, + otherwise don't. We don't want to speak telnet with + non-telnet servers, like POP or SMTP. */ + if(tn->please_negotiate && !tn->already_negotiated) { + negotiate(data); + tn->already_negotiated = 1; + } + } + if(events.lNetworkEvents & FD_CLOSE) { + keepon = FALSE; + } + } + break; + + } + + if(data->set.timeout) { + now = Curl_now(); + if(Curl_timediff(now, conn->created) >= data->set.timeout) { + failf(data, "Time-out"); + result = CURLE_OPERATION_TIMEDOUT; + keepon = FALSE; + } + } + } + + /* We called WSACreateEvent, so call WSACloseEvent */ + if(!WSACloseEvent(event_handle)) { + infof(data, "WSACloseEvent failed (%d)", SOCKERRNO); + } +#else + pfd[0].fd = sockfd; + pfd[0].events = POLLIN; + + if(data->set.is_fread_set) { + poll_cnt = 1; + interval_ms = 100; /* poll user-supplied read function */ + } + else { + /* really using fread, so infile is a FILE* */ + pfd[1].fd = fileno((FILE *)data->state.in); + pfd[1].events = POLLIN; + poll_cnt = 2; + interval_ms = 1 * 1000; + if(pfd[1].fd < 0) { + failf(data, "cannot read input"); + result = CURLE_RECV_ERROR; + keepon = FALSE; + } + } + + while(keepon) { + DEBUGF(infof(data, "telnet_do, poll %d fds", poll_cnt)); + switch(Curl_poll(pfd, poll_cnt, interval_ms)) { + case -1: /* error, stop reading */ + keepon = FALSE; + continue; + case 0: /* timeout */ + pfd[0].revents = 0; + pfd[1].revents = 0; + FALLTHROUGH(); + default: /* read! */ + if(pfd[0].revents & POLLIN) { + /* read data from network */ + result = Curl_xfer_recv(data, buffer, sizeof(buffer), &nread); + /* read would've blocked. Loop again */ + if(result == CURLE_AGAIN) + break; + /* returned not-zero, this an error */ + if(result) { + keepon = FALSE; + /* TODO: in test 1452, macOS sees a ECONNRESET sometimes? + * Is this the telnet test server not shutting down the socket + * in a clean way? Seems to be timing related, happens more + * on slow debug build */ + if(data->state.os_errno == ECONNRESET) { + DEBUGF(infof(data, "telnet_do, unexpected ECONNRESET on recv")); + } + break; + } + /* returned zero but actually received 0 or less here, + the server closed the connection and we bail out */ + else if(nread <= 0) { + keepon = FALSE; + break; + } + + total_dl += nread; + result = Curl_pgrsSetDownloadCounter(data, total_dl); + if(!result) + result = telrcv(data, (unsigned char *)buffer, nread); + if(result) { + keepon = FALSE; + break; + } + + /* Negotiate if the peer has started negotiating, + otherwise don't. We don't want to speak telnet with + non-telnet servers, like POP or SMTP. */ + if(tn->please_negotiate && !tn->already_negotiated) { + negotiate(data); + tn->already_negotiated = 1; + } + } + + nread = 0; + if(poll_cnt == 2) { + if(pfd[1].revents & POLLIN) { /* read from in file */ + nread = read(pfd[1].fd, buffer, sizeof(buffer)); + } + } + else { + /* read from user-supplied method */ + nread = (int)data->state.fread_func(buffer, 1, sizeof(buffer), + data->state.in); + if(nread == CURL_READFUNC_ABORT) { + keepon = FALSE; + break; + } + if(nread == CURL_READFUNC_PAUSE) + break; + } + + if(nread > 0) { + result = send_telnet_data(data, buffer, nread); + if(result) { + keepon = FALSE; + break; + } + total_ul += nread; + Curl_pgrsSetUploadCounter(data, total_ul); + } + else if(nread < 0) + keepon = FALSE; + + break; + } /* poll switch statement */ + + if(data->set.timeout) { + now = Curl_now(); + if(Curl_timediff(now, conn->created) >= data->set.timeout) { + failf(data, "Time-out"); + result = CURLE_OPERATION_TIMEDOUT; + keepon = FALSE; + } + } + + if(Curl_pgrsUpdate(data)) { + result = CURLE_ABORTED_BY_CALLBACK; + break; + } + } +#endif + /* mark this as "no further transfer wanted" */ + Curl_xfer_setup(data, -1, -1, FALSE, -1); + + return result; +} +#endif diff --git a/third_party/curl/lib/telnet.h b/third_party/curl/lib/telnet.h new file mode 100644 index 0000000..30782d8 --- /dev/null +++ b/third_party/curl/lib/telnet.h @@ -0,0 +1,30 @@ +#ifndef HEADER_CURL_TELNET_H +#define HEADER_CURL_TELNET_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifndef CURL_DISABLE_TELNET +extern const struct Curl_handler Curl_handler_telnet; +#endif + +#endif /* HEADER_CURL_TELNET_H */ diff --git a/third_party/curl/lib/tftp.c b/third_party/curl/lib/tftp.c new file mode 100644 index 0000000..310a0fa --- /dev/null +++ b/third_party/curl/lib/tftp.c @@ -0,0 +1,1407 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_TFTP + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NET_IF_H +#include +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif + +#ifdef HAVE_SYS_PARAM_H +#include +#endif + +#include "urldata.h" +#include +#include "cf-socket.h" +#include "transfer.h" +#include "sendf.h" +#include "tftp.h" +#include "progress.h" +#include "connect.h" +#include "strerror.h" +#include "sockaddr.h" /* required for Curl_sockaddr_storage */ +#include "multiif.h" +#include "url.h" +#include "strcase.h" +#include "speedcheck.h" +#include "select.h" +#include "escape.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* RFC2348 allows the block size to be negotiated */ +#define TFTP_BLKSIZE_DEFAULT 512 +#define TFTP_OPTION_BLKSIZE "blksize" + +/* from RFC2349: */ +#define TFTP_OPTION_TSIZE "tsize" +#define TFTP_OPTION_INTERVAL "timeout" + +typedef enum { + TFTP_MODE_NETASCII = 0, + TFTP_MODE_OCTET +} tftp_mode_t; + +typedef enum { + TFTP_STATE_START = 0, + TFTP_STATE_RX, + TFTP_STATE_TX, + TFTP_STATE_FIN +} tftp_state_t; + +typedef enum { + TFTP_EVENT_NONE = -1, + TFTP_EVENT_INIT = 0, + TFTP_EVENT_RRQ = 1, + TFTP_EVENT_WRQ = 2, + TFTP_EVENT_DATA = 3, + TFTP_EVENT_ACK = 4, + TFTP_EVENT_ERROR = 5, + TFTP_EVENT_OACK = 6, + TFTP_EVENT_TIMEOUT +} tftp_event_t; + +typedef enum { + TFTP_ERR_UNDEF = 0, + TFTP_ERR_NOTFOUND, + TFTP_ERR_PERM, + TFTP_ERR_DISKFULL, + TFTP_ERR_ILLEGAL, + TFTP_ERR_UNKNOWNID, + TFTP_ERR_EXISTS, + TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */ + + /* The remaining error codes are internal to curl */ + TFTP_ERR_NONE = -100, + TFTP_ERR_TIMEOUT, + TFTP_ERR_NORESPONSE +} tftp_error_t; + +struct tftp_packet { + unsigned char *data; +}; + +struct tftp_state_data { + tftp_state_t state; + tftp_mode_t mode; + tftp_error_t error; + tftp_event_t event; + struct Curl_easy *data; + curl_socket_t sockfd; + int retries; + int retry_time; + int retry_max; + time_t rx_time; + struct Curl_sockaddr_storage local_addr; + struct Curl_sockaddr_storage remote_addr; + curl_socklen_t remote_addrlen; + int rbytes; + int sbytes; + int blksize; + int requested_blksize; + unsigned short block; + struct tftp_packet rpacket; + struct tftp_packet spacket; +}; + + +/* Forward declarations */ +static CURLcode tftp_rx(struct tftp_state_data *state, tftp_event_t event); +static CURLcode tftp_tx(struct tftp_state_data *state, tftp_event_t event); +static CURLcode tftp_connect(struct Curl_easy *data, bool *done); +static CURLcode tftp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection); +static CURLcode tftp_do(struct Curl_easy *data, bool *done); +static CURLcode tftp_done(struct Curl_easy *data, + CURLcode, bool premature); +static CURLcode tftp_setup_connection(struct Curl_easy *data, + struct connectdata *conn); +static CURLcode tftp_multi_statemach(struct Curl_easy *data, bool *done); +static CURLcode tftp_doing(struct Curl_easy *data, bool *dophase_done); +static int tftp_getsock(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t *socks); +static CURLcode tftp_translate_code(tftp_error_t error); + + +/* + * TFTP protocol handler. + */ + +const struct Curl_handler Curl_handler_tftp = { + "tftp", /* scheme */ + tftp_setup_connection, /* setup_connection */ + tftp_do, /* do_it */ + tftp_done, /* done */ + ZERO_NULL, /* do_more */ + tftp_connect, /* connect_it */ + tftp_multi_statemach, /* connecting */ + tftp_doing, /* doing */ + tftp_getsock, /* proto_getsock */ + tftp_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + tftp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_TFTP, /* defport */ + CURLPROTO_TFTP, /* protocol */ + CURLPROTO_TFTP, /* family */ + PROTOPT_NOTCPPROXY | PROTOPT_NOURLQUERY /* flags */ +}; + +/********************************************************** + * + * tftp_set_timeouts - + * + * Set timeouts based on state machine state. + * Use user provided connect timeouts until DATA or ACK + * packet is received, then use user-provided transfer timeouts + * + * + **********************************************************/ +static CURLcode tftp_set_timeouts(struct tftp_state_data *state) +{ + time_t maxtime, timeout; + timediff_t timeout_ms; + bool start = (state->state == TFTP_STATE_START) ? TRUE : FALSE; + + /* Compute drop-dead time */ + timeout_ms = Curl_timeleft(state->data, NULL, start); + + if(timeout_ms < 0) { + /* time-out, bail out, go home */ + failf(state->data, "Connection time-out"); + return CURLE_OPERATION_TIMEDOUT; + } + + if(timeout_ms > 0) + maxtime = (time_t)(timeout_ms + 500) / 1000; + else + maxtime = 3600; /* use for calculating block timeouts */ + + /* Set per-block timeout to total */ + timeout = maxtime; + + /* Average reposting an ACK after 5 seconds */ + state->retry_max = (int)timeout/5; + + /* But bound the total number */ + if(state->retry_max<3) + state->retry_max = 3; + + if(state->retry_max>50) + state->retry_max = 50; + + /* Compute the re-ACK interval to suit the timeout */ + state->retry_time = (int)(timeout/state->retry_max); + if(state->retry_time<1) + state->retry_time = 1; + + infof(state->data, + "set timeouts for state %d; Total % " CURL_FORMAT_CURL_OFF_T + ", retry %d maxtry %d", + (int)state->state, timeout_ms, state->retry_time, state->retry_max); + + /* init RX time */ + time(&state->rx_time); + + return CURLE_OK; +} + +/********************************************************** + * + * tftp_set_send_first + * + * Event handler for the START state + * + **********************************************************/ + +static void setpacketevent(struct tftp_packet *packet, unsigned short num) +{ + packet->data[0] = (unsigned char)(num >> 8); + packet->data[1] = (unsigned char)(num & 0xff); +} + + +static void setpacketblock(struct tftp_packet *packet, unsigned short num) +{ + packet->data[2] = (unsigned char)(num >> 8); + packet->data[3] = (unsigned char)(num & 0xff); +} + +static unsigned short getrpacketevent(const struct tftp_packet *packet) +{ + return (unsigned short)((packet->data[0] << 8) | packet->data[1]); +} + +static unsigned short getrpacketblock(const struct tftp_packet *packet) +{ + return (unsigned short)((packet->data[2] << 8) | packet->data[3]); +} + +static size_t tftp_strnlen(const char *string, size_t maxlen) +{ + const char *end = memchr(string, '\0', maxlen); + return end ? (size_t) (end - string) : maxlen; +} + +static const char *tftp_option_get(const char *buf, size_t len, + const char **option, const char **value) +{ + size_t loc; + + loc = tftp_strnlen(buf, len); + loc++; /* NULL term */ + + if(loc >= len) + return NULL; + *option = buf; + + loc += tftp_strnlen(buf + loc, len-loc); + loc++; /* NULL term */ + + if(loc > len) + return NULL; + *value = &buf[strlen(*option) + 1]; + + return &buf[loc]; +} + +static CURLcode tftp_parse_option_ack(struct tftp_state_data *state, + const char *ptr, int len) +{ + const char *tmp = ptr; + struct Curl_easy *data = state->data; + + /* if OACK doesn't contain blksize option, the default (512) must be used */ + state->blksize = TFTP_BLKSIZE_DEFAULT; + + while(tmp < ptr + len) { + const char *option, *value; + + tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value); + if(!tmp) { + failf(data, "Malformed ACK packet, rejecting"); + return CURLE_TFTP_ILLEGAL; + } + + infof(data, "got option=(%s) value=(%s)", option, value); + + if(checkprefix(TFTP_OPTION_BLKSIZE, option)) { + long blksize; + + blksize = strtol(value, NULL, 10); + + if(!blksize) { + failf(data, "invalid blocksize value in OACK packet"); + return CURLE_TFTP_ILLEGAL; + } + if(blksize > TFTP_BLKSIZE_MAX) { + failf(data, "%s (%d)", "blksize is larger than max supported", + TFTP_BLKSIZE_MAX); + return CURLE_TFTP_ILLEGAL; + } + else if(blksize < TFTP_BLKSIZE_MIN) { + failf(data, "%s (%d)", "blksize is smaller than min supported", + TFTP_BLKSIZE_MIN); + return CURLE_TFTP_ILLEGAL; + } + else if(blksize > state->requested_blksize) { + /* could realloc pkt buffers here, but the spec doesn't call out + * support for the server requesting a bigger blksize than the client + * requests */ + failf(data, "%s (%ld)", + "server requested blksize larger than allocated", blksize); + return CURLE_TFTP_ILLEGAL; + } + + state->blksize = (int)blksize; + infof(data, "%s (%d) %s (%d)", "blksize parsed from OACK", + state->blksize, "requested", state->requested_blksize); + } + else if(checkprefix(TFTP_OPTION_TSIZE, option)) { + long tsize = 0; + + tsize = strtol(value, NULL, 10); + infof(data, "%s (%ld)", "tsize parsed from OACK", tsize); + + /* tsize should be ignored on upload: Who cares about the size of the + remote file? */ + if(!data->state.upload) { + if(!tsize) { + failf(data, "invalid tsize -:%s:- value in OACK packet", value); + return CURLE_TFTP_ILLEGAL; + } + Curl_pgrsSetDownloadSize(data, tsize); + } + } + } + + return CURLE_OK; +} + +static CURLcode tftp_option_add(struct tftp_state_data *state, size_t *csize, + char *buf, const char *option) +{ + if(( strlen(option) + *csize + 1) > (size_t)state->blksize) + return CURLE_TFTP_ILLEGAL; + strcpy(buf, option); + *csize += strlen(option) + 1; + return CURLE_OK; +} + +static CURLcode tftp_connect_for_tx(struct tftp_state_data *state, + tftp_event_t event) +{ + CURLcode result; +#ifndef CURL_DISABLE_VERBOSE_STRINGS + struct Curl_easy *data = state->data; + + infof(data, "%s", "Connected for transmit"); +#endif + state->state = TFTP_STATE_TX; + result = tftp_set_timeouts(state); + if(result) + return result; + return tftp_tx(state, event); +} + +static CURLcode tftp_connect_for_rx(struct tftp_state_data *state, + tftp_event_t event) +{ + CURLcode result; +#ifndef CURL_DISABLE_VERBOSE_STRINGS + struct Curl_easy *data = state->data; + + infof(data, "%s", "Connected for receive"); +#endif + state->state = TFTP_STATE_RX; + result = tftp_set_timeouts(state); + if(result) + return result; + return tftp_rx(state, event); +} + +static CURLcode tftp_send_first(struct tftp_state_data *state, + tftp_event_t event) +{ + size_t sbytes; + ssize_t senddata; + const char *mode = "octet"; + char *filename; + struct Curl_easy *data = state->data; + CURLcode result = CURLE_OK; + + /* Set ascii mode if -B flag was used */ + if(data->state.prefer_ascii) + mode = "netascii"; + + switch(event) { + + case TFTP_EVENT_INIT: /* Send the first packet out */ + case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */ + /* Increment the retry counter, quit if over the limit */ + state->retries++; + if(state->retries>state->retry_max) { + state->error = TFTP_ERR_NORESPONSE; + state->state = TFTP_STATE_FIN; + return result; + } + + if(data->state.upload) { + /* If we are uploading, send an WRQ */ + setpacketevent(&state->spacket, TFTP_EVENT_WRQ); + if(data->state.infilesize != -1) + Curl_pgrsSetUploadSize(data, data->state.infilesize); + } + else { + /* If we are downloading, send an RRQ */ + setpacketevent(&state->spacket, TFTP_EVENT_RRQ); + } + /* As RFC3617 describes the separator slash is not actually part of the + file name so we skip the always-present first letter of the path + string. */ + result = Curl_urldecode(&state->data->state.up.path[1], 0, + &filename, NULL, REJECT_ZERO); + if(result) + return result; + + if(strlen(filename) > (state->blksize - strlen(mode) - 4)) { + failf(data, "TFTP file name too long"); + free(filename); + return CURLE_TFTP_ILLEGAL; /* too long file name field */ + } + + msnprintf((char *)state->spacket.data + 2, + state->blksize, + "%s%c%s%c", filename, '\0', mode, '\0'); + sbytes = 4 + strlen(filename) + strlen(mode); + + /* optional addition of TFTP options */ + if(!data->set.tftp_no_options) { + char buf[64]; + /* add tsize option */ + if(data->state.upload && (data->state.infilesize != -1)) + msnprintf(buf, sizeof(buf), "%" CURL_FORMAT_CURL_OFF_T, + data->state.infilesize); + else + strcpy(buf, "0"); /* the destination is large enough */ + + result = tftp_option_add(state, &sbytes, + (char *)state->spacket.data + sbytes, + TFTP_OPTION_TSIZE); + if(result == CURLE_OK) + result = tftp_option_add(state, &sbytes, + (char *)state->spacket.data + sbytes, buf); + + /* add blksize option */ + msnprintf(buf, sizeof(buf), "%d", state->requested_blksize); + if(result == CURLE_OK) + result = tftp_option_add(state, &sbytes, + (char *)state->spacket.data + sbytes, + TFTP_OPTION_BLKSIZE); + if(result == CURLE_OK) + result = tftp_option_add(state, &sbytes, + (char *)state->spacket.data + sbytes, buf); + + /* add timeout option */ + msnprintf(buf, sizeof(buf), "%d", state->retry_time); + if(result == CURLE_OK) + result = tftp_option_add(state, &sbytes, + (char *)state->spacket.data + sbytes, + TFTP_OPTION_INTERVAL); + if(result == CURLE_OK) + result = tftp_option_add(state, &sbytes, + (char *)state->spacket.data + sbytes, buf); + + if(result != CURLE_OK) { + failf(data, "TFTP buffer too small for options"); + free(filename); + return CURLE_TFTP_ILLEGAL; + } + } + + /* the typecase for the 3rd argument is mostly for systems that do + not have a size_t argument, like older unixes that want an 'int' */ + senddata = sendto(state->sockfd, (void *)state->spacket.data, + (SEND_TYPE_ARG3)sbytes, 0, + &data->conn->remote_addr->sa_addr, + data->conn->remote_addr->addrlen); + if(senddata != (ssize_t)sbytes) { + char buffer[STRERROR_LEN]; + failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + } + free(filename); + break; + + case TFTP_EVENT_OACK: + if(data->state.upload) { + result = tftp_connect_for_tx(state, event); + } + else { + result = tftp_connect_for_rx(state, event); + } + break; + + case TFTP_EVENT_ACK: /* Connected for transmit */ + result = tftp_connect_for_tx(state, event); + break; + + case TFTP_EVENT_DATA: /* Connected for receive */ + result = tftp_connect_for_rx(state, event); + break; + + case TFTP_EVENT_ERROR: + state->state = TFTP_STATE_FIN; + break; + + default: + failf(state->data, "tftp_send_first: internal error"); + break; + } + + return result; +} + +/* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit + boundary */ +#define NEXT_BLOCKNUM(x) (((x) + 1)&0xffff) + +/********************************************************** + * + * tftp_rx + * + * Event handler for the RX state + * + **********************************************************/ +static CURLcode tftp_rx(struct tftp_state_data *state, + tftp_event_t event) +{ + ssize_t sbytes; + int rblock; + struct Curl_easy *data = state->data; + char buffer[STRERROR_LEN]; + + switch(event) { + + case TFTP_EVENT_DATA: + /* Is this the block we expect? */ + rblock = getrpacketblock(&state->rpacket); + if(NEXT_BLOCKNUM(state->block) == rblock) { + /* This is the expected block. Reset counters and ACK it. */ + state->retries = 0; + } + else if(state->block == rblock) { + /* This is the last recently received block again. Log it and ACK it + again. */ + infof(data, "Received last DATA packet block %d again.", rblock); + } + else { + /* totally unexpected, just log it */ + infof(data, + "Received unexpected DATA packet block %d, expecting block %d", + rblock, NEXT_BLOCKNUM(state->block)); + break; + } + + /* ACK this block. */ + state->block = (unsigned short)rblock; + setpacketevent(&state->spacket, TFTP_EVENT_ACK); + setpacketblock(&state->spacket, state->block); + sbytes = sendto(state->sockfd, (void *)state->spacket.data, + 4, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + if(sbytes < 0) { + failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + + /* Check if completed (That is, a less than full packet is received) */ + if(state->rbytes < (ssize_t)state->blksize + 4) { + state->state = TFTP_STATE_FIN; + } + else { + state->state = TFTP_STATE_RX; + } + time(&state->rx_time); + break; + + case TFTP_EVENT_OACK: + /* ACK option acknowledgement so we can move on to data */ + state->block = 0; + state->retries = 0; + setpacketevent(&state->spacket, TFTP_EVENT_ACK); + setpacketblock(&state->spacket, state->block); + sbytes = sendto(state->sockfd, (void *)state->spacket.data, + 4, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + if(sbytes < 0) { + failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + + /* we're ready to RX data */ + state->state = TFTP_STATE_RX; + time(&state->rx_time); + break; + + case TFTP_EVENT_TIMEOUT: + /* Increment the retry count and fail if over the limit */ + state->retries++; + infof(data, + "Timeout waiting for block %d ACK. Retries = %d", + NEXT_BLOCKNUM(state->block), state->retries); + if(state->retries > state->retry_max) { + state->error = TFTP_ERR_TIMEOUT; + state->state = TFTP_STATE_FIN; + } + else { + /* Resend the previous ACK */ + sbytes = sendto(state->sockfd, (void *)state->spacket.data, + 4, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + if(sbytes<0) { + failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + } + break; + + case TFTP_EVENT_ERROR: + setpacketevent(&state->spacket, TFTP_EVENT_ERROR); + setpacketblock(&state->spacket, state->block); + (void)sendto(state->sockfd, (void *)state->spacket.data, + 4, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + /* don't bother with the return code, but if the socket is still up we + * should be a good TFTP client and let the server know we're done */ + state->state = TFTP_STATE_FIN; + break; + + default: + failf(data, "%s", "tftp_rx: internal error"); + return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for + this */ + } + return CURLE_OK; +} + +/********************************************************** + * + * tftp_tx + * + * Event handler for the TX state + * + **********************************************************/ +static CURLcode tftp_tx(struct tftp_state_data *state, tftp_event_t event) +{ + struct Curl_easy *data = state->data; + ssize_t sbytes; + CURLcode result = CURLE_OK; + struct SingleRequest *k = &data->req; + size_t cb; /* Bytes currently read */ + char buffer[STRERROR_LEN]; + char *bufptr; + bool eos; + + switch(event) { + + case TFTP_EVENT_ACK: + case TFTP_EVENT_OACK: + if(event == TFTP_EVENT_ACK) { + /* Ack the packet */ + int rblock = getrpacketblock(&state->rpacket); + + if(rblock != state->block && + /* There's a bug in tftpd-hpa that causes it to send us an ack for + * 65535 when the block number wraps to 0. So when we're expecting + * 0, also accept 65535. See + * https://www.syslinux.org/archives/2010-September/015612.html + * */ + !(state->block == 0 && rblock == 65535)) { + /* This isn't the expected block. Log it and up the retry counter */ + infof(data, "Received ACK for block %d, expecting %d", + rblock, state->block); + state->retries++; + /* Bail out if over the maximum */ + if(state->retries>state->retry_max) { + failf(data, "tftp_tx: giving up waiting for block %d ack", + state->block); + result = CURLE_SEND_ERROR; + } + else { + /* Re-send the data packet */ + sbytes = sendto(state->sockfd, (void *)state->spacket.data, + 4 + state->sbytes, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + /* Check all sbytes were sent */ + if(sbytes<0) { + failf(data, "%s", Curl_strerror(SOCKERRNO, + buffer, sizeof(buffer))); + result = CURLE_SEND_ERROR; + } + } + + return result; + } + /* This is the expected packet. Reset the counters and send the next + block */ + time(&state->rx_time); + state->block++; + } + else + state->block = 1; /* first data block is 1 when using OACK */ + + state->retries = 0; + setpacketevent(&state->spacket, TFTP_EVENT_DATA); + setpacketblock(&state->spacket, state->block); + if(state->block > 1 && state->sbytes < state->blksize) { + state->state = TFTP_STATE_FIN; + return CURLE_OK; + } + + /* TFTP considers data block size < 512 bytes as an end of session. So + * in some cases we must wait for additional data to build full (512 bytes) + * data block. + * */ + state->sbytes = 0; + bufptr = (char *)state->spacket.data + 4; + do { + result = Curl_client_read(data, bufptr, state->blksize - state->sbytes, + &cb, &eos); + if(result) + return result; + state->sbytes += (int)cb; + bufptr += cb; + } while(state->sbytes < state->blksize && cb); + + sbytes = sendto(state->sockfd, (void *) state->spacket.data, + 4 + state->sbytes, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + /* Check all sbytes were sent */ + if(sbytes<0) { + failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + /* Update the progress meter */ + k->writebytecount += state->sbytes; + Curl_pgrsSetUploadCounter(data, k->writebytecount); + break; + + case TFTP_EVENT_TIMEOUT: + /* Increment the retry counter and log the timeout */ + state->retries++; + infof(data, "Timeout waiting for block %d ACK. " + " Retries = %d", NEXT_BLOCKNUM(state->block), state->retries); + /* Decide if we've had enough */ + if(state->retries > state->retry_max) { + state->error = TFTP_ERR_TIMEOUT; + state->state = TFTP_STATE_FIN; + } + else { + /* Re-send the data packet */ + sbytes = sendto(state->sockfd, (void *)state->spacket.data, + 4 + state->sbytes, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + /* Check all sbytes were sent */ + if(sbytes<0) { + failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + /* since this was a re-send, we remain at the still byte position */ + Curl_pgrsSetUploadCounter(data, k->writebytecount); + } + break; + + case TFTP_EVENT_ERROR: + state->state = TFTP_STATE_FIN; + setpacketevent(&state->spacket, TFTP_EVENT_ERROR); + setpacketblock(&state->spacket, state->block); + (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + /* don't bother with the return code, but if the socket is still up we + * should be a good TFTP client and let the server know we're done */ + state->state = TFTP_STATE_FIN; + break; + + default: + failf(data, "tftp_tx: internal error, event: %i", (int)(event)); + break; + } + + return result; +} + +/********************************************************** + * + * tftp_translate_code + * + * Translate internal error codes to CURL error codes + * + **********************************************************/ +static CURLcode tftp_translate_code(tftp_error_t error) +{ + CURLcode result = CURLE_OK; + + if(error != TFTP_ERR_NONE) { + switch(error) { + case TFTP_ERR_NOTFOUND: + result = CURLE_TFTP_NOTFOUND; + break; + case TFTP_ERR_PERM: + result = CURLE_TFTP_PERM; + break; + case TFTP_ERR_DISKFULL: + result = CURLE_REMOTE_DISK_FULL; + break; + case TFTP_ERR_UNDEF: + case TFTP_ERR_ILLEGAL: + result = CURLE_TFTP_ILLEGAL; + break; + case TFTP_ERR_UNKNOWNID: + result = CURLE_TFTP_UNKNOWNID; + break; + case TFTP_ERR_EXISTS: + result = CURLE_REMOTE_FILE_EXISTS; + break; + case TFTP_ERR_NOSUCHUSER: + result = CURLE_TFTP_NOSUCHUSER; + break; + case TFTP_ERR_TIMEOUT: + result = CURLE_OPERATION_TIMEDOUT; + break; + case TFTP_ERR_NORESPONSE: + result = CURLE_COULDNT_CONNECT; + break; + default: + result = CURLE_ABORTED_BY_CALLBACK; + break; + } + } + else + result = CURLE_OK; + + return result; +} + +/********************************************************** + * + * tftp_state_machine + * + * The tftp state machine event dispatcher + * + **********************************************************/ +static CURLcode tftp_state_machine(struct tftp_state_data *state, + tftp_event_t event) +{ + CURLcode result = CURLE_OK; + struct Curl_easy *data = state->data; + + switch(state->state) { + case TFTP_STATE_START: + DEBUGF(infof(data, "TFTP_STATE_START")); + result = tftp_send_first(state, event); + break; + case TFTP_STATE_RX: + DEBUGF(infof(data, "TFTP_STATE_RX")); + result = tftp_rx(state, event); + break; + case TFTP_STATE_TX: + DEBUGF(infof(data, "TFTP_STATE_TX")); + result = tftp_tx(state, event); + break; + case TFTP_STATE_FIN: + infof(data, "%s", "TFTP finished"); + break; + default: + DEBUGF(infof(data, "STATE: %d", state->state)); + failf(data, "%s", "Internal state machine error"); + result = CURLE_TFTP_ILLEGAL; + break; + } + + return result; +} + +/********************************************************** + * + * tftp_disconnect + * + * The disconnect callback + * + **********************************************************/ +static CURLcode tftp_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead_connection) +{ + struct tftp_state_data *state = conn->proto.tftpc; + (void) data; + (void) dead_connection; + + /* done, free dynamically allocated pkt buffers */ + if(state) { + Curl_safefree(state->rpacket.data); + Curl_safefree(state->spacket.data); + free(state); + } + + return CURLE_OK; +} + +/********************************************************** + * + * tftp_connect + * + * The connect callback + * + **********************************************************/ +static CURLcode tftp_connect(struct Curl_easy *data, bool *done) +{ + struct tftp_state_data *state; + int blksize; + int need_blksize; + struct connectdata *conn = data->conn; + + blksize = TFTP_BLKSIZE_DEFAULT; + + state = conn->proto.tftpc = calloc(1, sizeof(struct tftp_state_data)); + if(!state) + return CURLE_OUT_OF_MEMORY; + + /* alloc pkt buffers based on specified blksize */ + if(data->set.tftp_blksize) + /* range checked when set */ + blksize = (int)data->set.tftp_blksize; + + need_blksize = blksize; + /* default size is the fallback when no OACK is received */ + if(need_blksize < TFTP_BLKSIZE_DEFAULT) + need_blksize = TFTP_BLKSIZE_DEFAULT; + + if(!state->rpacket.data) { + state->rpacket.data = calloc(1, need_blksize + 2 + 2); + + if(!state->rpacket.data) + return CURLE_OUT_OF_MEMORY; + } + + if(!state->spacket.data) { + state->spacket.data = calloc(1, need_blksize + 2 + 2); + + if(!state->spacket.data) + return CURLE_OUT_OF_MEMORY; + } + + /* we don't keep TFTP connections up basically because there's none or very + * little gain for UDP */ + connclose(conn, "TFTP"); + + state->data = data; + state->sockfd = conn->sock[FIRSTSOCKET]; + state->state = TFTP_STATE_START; + state->error = TFTP_ERR_NONE; + state->blksize = TFTP_BLKSIZE_DEFAULT; /* Unless updated by OACK response */ + state->requested_blksize = blksize; + + ((struct sockaddr *)&state->local_addr)->sa_family = + (CURL_SA_FAMILY_T)(conn->remote_addr->family); + + tftp_set_timeouts(state); + + if(!conn->bits.bound) { + /* If not already bound, bind to any interface, random UDP port. If it is + * reused or a custom local port was desired, this has already been done! + * + * We once used the size of the local_addr struct as the third argument + * for bind() to better work with IPv6 or whatever size the struct could + * have, but we learned that at least Tru64, AIX and IRIX *requires* the + * size of that argument to match the exact size of a 'sockaddr_in' struct + * when running IPv4-only. + * + * Therefore we use the size from the address we connected to, which we + * assume uses the same IP version and thus hopefully this works for both + * IPv4 and IPv6... + */ + int rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr, + conn->remote_addr->addrlen); + if(rc) { + char buffer[STRERROR_LEN]; + failf(data, "bind() failed; %s", + Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_COULDNT_CONNECT; + } + conn->bits.bound = TRUE; + } + + Curl_pgrsStartNow(data); + + *done = TRUE; + + return CURLE_OK; +} + +/********************************************************** + * + * tftp_done + * + * The done callback + * + **********************************************************/ +static CURLcode tftp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct tftp_state_data *state = conn->proto.tftpc; + + (void)status; /* unused */ + (void)premature; /* not used */ + + if(Curl_pgrsDone(data)) + return CURLE_ABORTED_BY_CALLBACK; + + /* If we have encountered an error */ + if(state) + result = tftp_translate_code(state->error); + + return result; +} + +/********************************************************** + * + * tftp_getsock + * + * The getsock callback + * + **********************************************************/ +static int tftp_getsock(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *socks) +{ + (void)data; + socks[0] = conn->sock[FIRSTSOCKET]; + return GETSOCK_READSOCK(0); +} + +/********************************************************** + * + * tftp_receive_packet + * + * Called once select fires and data is ready on the socket + * + **********************************************************/ +static CURLcode tftp_receive_packet(struct Curl_easy *data) +{ + struct Curl_sockaddr_storage fromaddr; + curl_socklen_t fromlen; + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct tftp_state_data *state = conn->proto.tftpc; + + /* Receive the packet */ + fromlen = sizeof(fromaddr); + state->rbytes = (int)recvfrom(state->sockfd, + (void *)state->rpacket.data, + state->blksize + 4, + 0, + (struct sockaddr *)&fromaddr, + &fromlen); + if(state->remote_addrlen == 0) { + memcpy(&state->remote_addr, &fromaddr, fromlen); + state->remote_addrlen = fromlen; + } + + /* Sanity check packet length */ + if(state->rbytes < 4) { + failf(data, "Received too short packet"); + /* Not a timeout, but how best to handle it? */ + state->event = TFTP_EVENT_TIMEOUT; + } + else { + /* The event is given by the TFTP packet time */ + unsigned short event = getrpacketevent(&state->rpacket); + state->event = (tftp_event_t)event; + + switch(state->event) { + case TFTP_EVENT_DATA: + /* Don't pass to the client empty or retransmitted packets */ + if(state->rbytes > 4 && + (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) { + result = Curl_client_write(data, CLIENTWRITE_BODY, + (char *)state->rpacket.data + 4, + state->rbytes-4); + if(result) { + tftp_state_machine(state, TFTP_EVENT_ERROR); + return result; + } + } + break; + case TFTP_EVENT_ERROR: + { + unsigned short error = getrpacketblock(&state->rpacket); + char *str = (char *)state->rpacket.data + 4; + size_t strn = state->rbytes - 4; + state->error = (tftp_error_t)error; + if(tftp_strnlen(str, strn) < strn) + infof(data, "TFTP error: %s", str); + break; + } + case TFTP_EVENT_ACK: + break; + case TFTP_EVENT_OACK: + result = tftp_parse_option_ack(state, + (const char *)state->rpacket.data + 2, + state->rbytes-2); + if(result) + return result; + break; + case TFTP_EVENT_RRQ: + case TFTP_EVENT_WRQ: + default: + failf(data, "%s", "Internal error: Unexpected packet"); + break; + } + + /* Update the progress meter */ + if(Curl_pgrsUpdate(data)) { + tftp_state_machine(state, TFTP_EVENT_ERROR); + return CURLE_ABORTED_BY_CALLBACK; + } + } + return result; +} + +/********************************************************** + * + * tftp_state_timeout + * + * Check if timeouts have been reached + * + **********************************************************/ +static timediff_t tftp_state_timeout(struct Curl_easy *data, + tftp_event_t *event) +{ + time_t current; + struct connectdata *conn = data->conn; + struct tftp_state_data *state = conn->proto.tftpc; + timediff_t timeout_ms; + + if(event) + *event = TFTP_EVENT_NONE; + + timeout_ms = Curl_timeleft(state->data, NULL, + (state->state == TFTP_STATE_START)); + if(timeout_ms < 0) { + state->error = TFTP_ERR_TIMEOUT; + state->state = TFTP_STATE_FIN; + return 0; + } + current = time(NULL); + if(current > state->rx_time + state->retry_time) { + if(event) + *event = TFTP_EVENT_TIMEOUT; + time(&state->rx_time); /* update even though we received nothing */ + } + + return timeout_ms; +} + +/********************************************************** + * + * tftp_multi_statemach + * + * Handle single RX socket event and return + * + **********************************************************/ +static CURLcode tftp_multi_statemach(struct Curl_easy *data, bool *done) +{ + tftp_event_t event; + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct tftp_state_data *state = conn->proto.tftpc; + timediff_t timeout_ms = tftp_state_timeout(data, &event); + + *done = FALSE; + + if(timeout_ms < 0) { + failf(data, "TFTP response timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + if(event != TFTP_EVENT_NONE) { + result = tftp_state_machine(state, event); + if(result) + return result; + *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE; + if(*done) + /* Tell curl we're done */ + Curl_xfer_setup(data, -1, -1, FALSE, -1); + } + else { + /* no timeouts to handle, check our socket */ + int rc = SOCKET_READABLE(state->sockfd, 0); + + if(rc == -1) { + /* bail out */ + int error = SOCKERRNO; + char buffer[STRERROR_LEN]; + failf(data, "%s", Curl_strerror(error, buffer, sizeof(buffer))); + state->event = TFTP_EVENT_ERROR; + } + else if(rc) { + result = tftp_receive_packet(data); + if(result) + return result; + result = tftp_state_machine(state, state->event); + if(result) + return result; + *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE; + if(*done) + /* Tell curl we're done */ + Curl_xfer_setup(data, -1, -1, FALSE, -1); + } + /* if rc == 0, then select() timed out */ + } + + return result; +} + +/********************************************************** + * + * tftp_doing + * + * Called from multi.c while DOing + * + **********************************************************/ +static CURLcode tftp_doing(struct Curl_easy *data, bool *dophase_done) +{ + CURLcode result; + result = tftp_multi_statemach(data, dophase_done); + + if(*dophase_done) { + DEBUGF(infof(data, "DO phase is complete")); + } + else if(!result) { + /* The multi code doesn't have this logic for the DOING state so we + provide it for TFTP since it may do the entire transfer in this + state. */ + if(Curl_pgrsUpdate(data)) + result = CURLE_ABORTED_BY_CALLBACK; + else + result = Curl_speedcheck(data, Curl_now()); + } + return result; +} + +/********************************************************** + * + * tftp_perform + * + * Entry point for transfer from tftp_do, starts state mach + * + **********************************************************/ +static CURLcode tftp_perform(struct Curl_easy *data, bool *dophase_done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct tftp_state_data *state = conn->proto.tftpc; + + *dophase_done = FALSE; + + result = tftp_state_machine(state, TFTP_EVENT_INIT); + + if((state->state == TFTP_STATE_FIN) || result) + return result; + + tftp_multi_statemach(data, dophase_done); + + if(*dophase_done) + DEBUGF(infof(data, "DO phase is complete")); + + return result; +} + + +/********************************************************** + * + * tftp_do + * + * The do callback + * + * This callback initiates the TFTP transfer + * + **********************************************************/ + +static CURLcode tftp_do(struct Curl_easy *data, bool *done) +{ + struct tftp_state_data *state; + CURLcode result; + struct connectdata *conn = data->conn; + + *done = FALSE; + + if(!conn->proto.tftpc) { + result = tftp_connect(data, done); + if(result) + return result; + } + + state = conn->proto.tftpc; + if(!state) + return CURLE_TFTP_ILLEGAL; + + result = tftp_perform(data, done); + + /* If tftp_perform() returned an error, use that for return code. If it + was OK, see if tftp_translate_code() has an error. */ + if(!result) + /* If we have encountered an internal tftp error, translate it. */ + result = tftp_translate_code(state->error); + + return result; +} + +static CURLcode tftp_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + char *type; + + conn->transport = TRNSPRT_UDP; + + /* TFTP URLs support an extension like ";mode=" that + * we'll try to get now! */ + type = strstr(data->state.up.path, ";mode="); + + if(!type) + type = strstr(conn->host.rawalloc, ";mode="); + + if(type) { + char command; + *type = 0; /* it was in the middle of the hostname */ + command = Curl_raw_toupper(type[6]); + + switch(command) { + case 'A': /* ASCII mode */ + case 'N': /* NETASCII mode */ + data->state.prefer_ascii = TRUE; + break; + + case 'O': /* octet mode */ + case 'I': /* binary mode */ + default: + /* switch off ASCII */ + data->state.prefer_ascii = FALSE; + break; + } + } + + return CURLE_OK; +} +#endif diff --git a/third_party/curl/lib/tftp.h b/third_party/curl/lib/tftp.h new file mode 100644 index 0000000..12404bf --- /dev/null +++ b/third_party/curl/lib/tftp.h @@ -0,0 +1,33 @@ +#ifndef HEADER_CURL_TFTP_H +#define HEADER_CURL_TFTP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifndef CURL_DISABLE_TFTP +extern const struct Curl_handler Curl_handler_tftp; + +#define TFTP_BLKSIZE_MIN 8 +#define TFTP_BLKSIZE_MAX 65464 +#endif + +#endif /* HEADER_CURL_TFTP_H */ diff --git a/third_party/curl/lib/timediff.c b/third_party/curl/lib/timediff.c new file mode 100644 index 0000000..d0824d1 --- /dev/null +++ b/third_party/curl/lib/timediff.c @@ -0,0 +1,88 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "timediff.h" + +#include + +/* + * Converts number of milliseconds into a timeval structure. + * + * Return values: + * NULL IF tv is NULL or ms < 0 (eg. no timeout -> blocking select) + * tv with 0 in both fields IF ms == 0 (eg. 0ms timeout -> polling select) + * tv with converted fields IF ms > 0 (eg. >0ms timeout -> waiting select) + */ +struct timeval *curlx_mstotv(struct timeval *tv, timediff_t ms) +{ + if(!tv) + return NULL; + + if(ms < 0) + return NULL; + + if(ms > 0) { + timediff_t tv_sec = ms / 1000; + timediff_t tv_usec = (ms % 1000) * 1000; /* max=999999 */ +#ifdef HAVE_SUSECONDS_T +#if TIMEDIFF_T_MAX > TIME_T_MAX + /* tv_sec overflow check in case time_t is signed */ + if(tv_sec > TIME_T_MAX) + tv_sec = TIME_T_MAX; +#endif + tv->tv_sec = (time_t)tv_sec; + tv->tv_usec = (suseconds_t)tv_usec; +#elif defined(_WIN32) /* maybe also others in the future */ +#if TIMEDIFF_T_MAX > LONG_MAX + /* tv_sec overflow check on Windows there we know it is long */ + if(tv_sec > LONG_MAX) + tv_sec = LONG_MAX; +#endif + tv->tv_sec = (long)tv_sec; + tv->tv_usec = (long)tv_usec; +#else +#if TIMEDIFF_T_MAX > INT_MAX + /* tv_sec overflow check in case time_t is signed */ + if(tv_sec > INT_MAX) + tv_sec = INT_MAX; +#endif + tv->tv_sec = (int)tv_sec; + tv->tv_usec = (int)tv_usec; +#endif + } + else { + tv->tv_sec = 0; + tv->tv_usec = 0; + } + + return tv; +} + +/* + * Converts a timeval structure into number of milliseconds. + */ +timediff_t curlx_tvtoms(struct timeval *tv) +{ + return (tv->tv_sec*1000) + (timediff_t)(((double)tv->tv_usec)/1000.0); +} diff --git a/third_party/curl/lib/timediff.h b/third_party/curl/lib/timediff.h new file mode 100644 index 0000000..fb318d4 --- /dev/null +++ b/third_party/curl/lib/timediff.h @@ -0,0 +1,52 @@ +#ifndef HEADER_CURL_TIMEDIFF_H +#define HEADER_CURL_TIMEDIFF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +/* Use a larger type even for 32 bit time_t systems so that we can keep + microsecond accuracy in it */ +typedef curl_off_t timediff_t; +#define CURL_FORMAT_TIMEDIFF_T CURL_FORMAT_CURL_OFF_T + +#define TIMEDIFF_T_MAX CURL_OFF_T_MAX +#define TIMEDIFF_T_MIN CURL_OFF_T_MIN + +/* + * Converts number of milliseconds into a timeval structure. + * + * Return values: + * NULL IF tv is NULL or ms < 0 (eg. no timeout -> blocking select) + * tv with 0 in both fields IF ms == 0 (eg. 0ms timeout -> polling select) + * tv with converted fields IF ms > 0 (eg. >0ms timeout -> waiting select) + */ +struct timeval *curlx_mstotv(struct timeval *tv, timediff_t ms); + +/* + * Converts a timeval structure into number of milliseconds. + */ +timediff_t curlx_tvtoms(struct timeval *tv); + +#endif /* HEADER_CURL_TIMEDIFF_H */ diff --git a/third_party/curl/lib/timeval.c b/third_party/curl/lib/timeval.c new file mode 100644 index 0000000..5a6727c --- /dev/null +++ b/third_party/curl/lib/timeval.c @@ -0,0 +1,237 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "timeval.h" + +#if defined(_WIN32) + +#include +#include "system_win32.h" + +/* In case of bug fix this function has a counterpart in tool_util.c */ +struct curltime Curl_now(void) +{ + struct curltime now; + if(Curl_isVistaOrGreater) { /* QPC timer might have issues pre-Vista */ + LARGE_INTEGER count; + QueryPerformanceCounter(&count); + now.tv_sec = (time_t)(count.QuadPart / Curl_freq.QuadPart); + now.tv_usec = (int)((count.QuadPart % Curl_freq.QuadPart) * 1000000 / + Curl_freq.QuadPart); + } + else { + /* Disable /analyze warning that GetTickCount64 is preferred */ +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable:28159) +#endif + DWORD milliseconds = GetTickCount(); +#if defined(_MSC_VER) +#pragma warning(pop) +#endif + + now.tv_sec = milliseconds / 1000; + now.tv_usec = (milliseconds % 1000) * 1000; + } + return now; +} + +#elif defined(HAVE_CLOCK_GETTIME_MONOTONIC) || \ + defined(HAVE_CLOCK_GETTIME_MONOTONIC_RAW) + +struct curltime Curl_now(void) +{ + /* + ** clock_gettime() is granted to be increased monotonically when the + ** monotonic clock is queried. Time starting point is unspecified, it + ** could be the system start-up time, the Epoch, or something else, + ** in any case the time starting point does not change once that the + ** system has started up. + */ +#ifdef HAVE_GETTIMEOFDAY + struct timeval now; +#endif + struct curltime cnow; + struct timespec tsnow; + + /* + ** clock_gettime() may be defined by Apple's SDK as weak symbol thus + ** code compiles but fails during run-time if clock_gettime() is + ** called on unsupported OS version. + */ +#if defined(__APPLE__) && defined(HAVE_BUILTIN_AVAILABLE) && \ + (HAVE_BUILTIN_AVAILABLE == 1) + bool have_clock_gettime = FALSE; + if(__builtin_available(macOS 10.12, iOS 10, tvOS 10, watchOS 3, *)) + have_clock_gettime = TRUE; +#endif + +#ifdef HAVE_CLOCK_GETTIME_MONOTONIC_RAW + if( +#if defined(__APPLE__) && defined(HAVE_BUILTIN_AVAILABLE) && \ + (HAVE_BUILTIN_AVAILABLE == 1) + have_clock_gettime && +#endif + (0 == clock_gettime(CLOCK_MONOTONIC_RAW, &tsnow))) { + cnow.tv_sec = tsnow.tv_sec; + cnow.tv_usec = (unsigned int)(tsnow.tv_nsec / 1000); + } + else +#endif + + if( +#if defined(__APPLE__) && defined(HAVE_BUILTIN_AVAILABLE) && \ + (HAVE_BUILTIN_AVAILABLE == 1) + have_clock_gettime && +#endif + (0 == clock_gettime(CLOCK_MONOTONIC, &tsnow))) { + cnow.tv_sec = tsnow.tv_sec; + cnow.tv_usec = (unsigned int)(tsnow.tv_nsec / 1000); + } + /* + ** Even when the configure process has truly detected monotonic clock + ** availability, it might happen that it is not actually available at + ** run-time. When this occurs simply fallback to other time source. + */ +#ifdef HAVE_GETTIMEOFDAY + else { + (void)gettimeofday(&now, NULL); + cnow.tv_sec = now.tv_sec; + cnow.tv_usec = (unsigned int)now.tv_usec; + } +#else + else { + cnow.tv_sec = time(NULL); + cnow.tv_usec = 0; + } +#endif + return cnow; +} + +#elif defined(HAVE_MACH_ABSOLUTE_TIME) + +#include +#include + +struct curltime Curl_now(void) +{ + /* + ** Monotonic timer on Mac OS is provided by mach_absolute_time(), which + ** returns time in Mach "absolute time units," which are platform-dependent. + ** To convert to nanoseconds, one must use conversion factors specified by + ** mach_timebase_info(). + */ + static mach_timebase_info_data_t timebase; + struct curltime cnow; + uint64_t usecs; + + if(0 == timebase.denom) + (void) mach_timebase_info(&timebase); + + usecs = mach_absolute_time(); + usecs *= timebase.numer; + usecs /= timebase.denom; + usecs /= 1000; + + cnow.tv_sec = usecs / 1000000; + cnow.tv_usec = (int)(usecs % 1000000); + + return cnow; +} + +#elif defined(HAVE_GETTIMEOFDAY) + +struct curltime Curl_now(void) +{ + /* + ** gettimeofday() is not granted to be increased monotonically, due to + ** clock drifting and external source time synchronization it can jump + ** forward or backward in time. + */ + struct timeval now; + struct curltime ret; + (void)gettimeofday(&now, NULL); + ret.tv_sec = now.tv_sec; + ret.tv_usec = (int)now.tv_usec; + return ret; +} + +#else + +struct curltime Curl_now(void) +{ + /* + ** time() returns the value of time in seconds since the Epoch. + */ + struct curltime now; + now.tv_sec = time(NULL); + now.tv_usec = 0; + return now; +} + +#endif + +/* + * Returns: time difference in number of milliseconds. For too large diffs it + * returns max value. + * + * @unittest: 1323 + */ +timediff_t Curl_timediff(struct curltime newer, struct curltime older) +{ + timediff_t diff = (timediff_t)newer.tv_sec-older.tv_sec; + if(diff >= (TIMEDIFF_T_MAX/1000)) + return TIMEDIFF_T_MAX; + else if(diff <= (TIMEDIFF_T_MIN/1000)) + return TIMEDIFF_T_MIN; + return diff * 1000 + (newer.tv_usec-older.tv_usec)/1000; +} + +/* + * Returns: time difference in number of milliseconds, rounded up. + * For too large diffs it returns max value. + */ +timediff_t Curl_timediff_ceil(struct curltime newer, struct curltime older) +{ + timediff_t diff = (timediff_t)newer.tv_sec-older.tv_sec; + if(diff >= (TIMEDIFF_T_MAX/1000)) + return TIMEDIFF_T_MAX; + else if(diff <= (TIMEDIFF_T_MIN/1000)) + return TIMEDIFF_T_MIN; + return diff * 1000 + (newer.tv_usec - older.tv_usec + 999)/1000; +} + +/* + * Returns: time difference in number of microseconds. For too large diffs it + * returns max value. + */ +timediff_t Curl_timediff_us(struct curltime newer, struct curltime older) +{ + timediff_t diff = (timediff_t)newer.tv_sec-older.tv_sec; + if(diff >= (TIMEDIFF_T_MAX/1000000)) + return TIMEDIFF_T_MAX; + else if(diff <= (TIMEDIFF_T_MIN/1000000)) + return TIMEDIFF_T_MIN; + return diff * 1000000 + newer.tv_usec-older.tv_usec; +} diff --git a/third_party/curl/lib/timeval.h b/third_party/curl/lib/timeval.h new file mode 100644 index 0000000..33dfb5b --- /dev/null +++ b/third_party/curl/lib/timeval.h @@ -0,0 +1,62 @@ +#ifndef HEADER_CURL_TIMEVAL_H +#define HEADER_CURL_TIMEVAL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "timediff.h" + +struct curltime { + time_t tv_sec; /* seconds */ + int tv_usec; /* microseconds */ +}; + +struct curltime Curl_now(void); + +/* + * Make sure that the first argument (newer) is the more recent time and older + * is the older time, as otherwise you get a weird negative time-diff back... + * + * Returns: the time difference in number of milliseconds. + */ +timediff_t Curl_timediff(struct curltime newer, struct curltime older); + +/* + * Make sure that the first argument (newer) is the more recent time and older + * is the older time, as otherwise you get a weird negative time-diff back... + * + * Returns: the time difference in number of milliseconds, rounded up. + */ +timediff_t Curl_timediff_ceil(struct curltime newer, struct curltime older); + +/* + * Make sure that the first argument (newer) is the more recent time and older + * is the older time, as otherwise you get a weird negative time-diff back... + * + * Returns: the time difference in number of microseconds. + */ +timediff_t Curl_timediff_us(struct curltime newer, struct curltime older); + +#endif /* HEADER_CURL_TIMEVAL_H */ diff --git a/third_party/curl/lib/transfer.c b/third_party/curl/lib/transfer.c new file mode 100644 index 0000000..744227e --- /dev/null +++ b/third_party/curl/lib/transfer.c @@ -0,0 +1,1278 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "strtoofft.h" + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NET_IF_H +#include +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif +#include + +#ifdef HAVE_SYS_PARAM_H +#include +#endif + +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif + +#ifndef HAVE_SOCKET +#error "We can't compile without socket() support!" +#endif + +#include "urldata.h" +#include +#include "netrc.h" + +#include "content_encoding.h" +#include "hostip.h" +#include "cfilters.h" +#include "cw-out.h" +#include "transfer.h" +#include "sendf.h" +#include "speedcheck.h" +#include "progress.h" +#include "http.h" +#include "url.h" +#include "getinfo.h" +#include "vtls/vtls.h" +#include "vquic/vquic.h" +#include "select.h" +#include "multiif.h" +#include "connect.h" +#include "http2.h" +#include "mime.h" +#include "strcase.h" +#include "urlapi-int.h" +#include "hsts.h" +#include "setopt.h" +#include "headers.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_IMAP) +/* + * checkheaders() checks the linked list of custom headers for a + * particular header (prefix). Provide the prefix without colon! + * + * Returns a pointer to the first matching header or NULL if none matched. + */ +char *Curl_checkheaders(const struct Curl_easy *data, + const char *thisheader, + const size_t thislen) +{ + struct curl_slist *head; + DEBUGASSERT(thislen); + DEBUGASSERT(thisheader[thislen-1] != ':'); + + for(head = data->set.headers; head; head = head->next) { + if(strncasecompare(head->data, thisheader, thislen) && + Curl_headersep(head->data[thislen]) ) + return head->data; + } + + return NULL; +} +#endif + +static int data_pending(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + + if(conn->handler->protocol&PROTO_FAMILY_FTP) + return Curl_conn_data_pending(data, SECONDARYSOCKET); + + /* in the case of libssh2, we can never be really sure that we have emptied + its internal buffers so we MUST always try until we get EAGAIN back */ + return conn->handler->protocol&(CURLPROTO_SCP|CURLPROTO_SFTP) || + Curl_conn_data_pending(data, FIRSTSOCKET); +} + +/* + * Check to see if CURLOPT_TIMECONDITION was met by comparing the time of the + * remote document with the time provided by CURLOPT_TIMEVAL + */ +bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc) +{ + if((timeofdoc == 0) || (data->set.timevalue == 0)) + return TRUE; + + switch(data->set.timecondition) { + case CURL_TIMECOND_IFMODSINCE: + default: + if(timeofdoc <= data->set.timevalue) { + infof(data, + "The requested document is not new enough"); + data->info.timecond = TRUE; + return FALSE; + } + break; + case CURL_TIMECOND_IFUNMODSINCE: + if(timeofdoc >= data->set.timevalue) { + infof(data, + "The requested document is not old enough"); + data->info.timecond = TRUE; + return FALSE; + } + break; + } + + return TRUE; +} + +/** + * Receive raw response data for the transfer. + * @param data the transfer + * @param buf buffer to keep response data received + * @param blen length of `buf` + * @param eos_reliable if EOS detection in underlying connection is reliable + * @param err error code in case of -1 return + * @return number of bytes read or -1 for error + */ +static ssize_t Curl_xfer_recv_resp(struct Curl_easy *data, + char *buf, size_t blen, + bool eos_reliable, + CURLcode *err) +{ + ssize_t nread; + + DEBUGASSERT(blen > 0); + /* If we are reading BODY data and the connection does NOT handle EOF + * and we know the size of the BODY data, limit the read amount */ + if(!eos_reliable && !data->req.header && data->req.size != -1) { + curl_off_t totalleft = data->req.size - data->req.bytecount; + if(totalleft <= 0) + blen = 0; + else if(totalleft < (curl_off_t)blen) + blen = (size_t)totalleft; + } + + if(!blen) { + /* want nothing - continue as if read nothing. */ + DEBUGF(infof(data, "readwrite_data: we're done")); + *err = CURLE_OK; + return 0; + } + + *err = Curl_xfer_recv(data, buf, blen, &nread); + if(*err) + return -1; + DEBUGASSERT(nread >= 0); + return nread; +} + +/* + * Go ahead and do a read if we have a readable socket or if + * the stream was rewound (in which case we have data in a + * buffer) + */ +static CURLcode readwrite_data(struct Curl_easy *data, + struct SingleRequest *k, + int *didwhat) +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + char *buf, *xfer_buf; + size_t blen, xfer_blen; + int maxloops = 10; + curl_off_t total_received = 0; + bool is_multiplex = FALSE; + + result = Curl_multi_xfer_buf_borrow(data, &xfer_buf, &xfer_blen); + if(result) + goto out; + + /* This is where we loop until we have read everything there is to + read or we get a CURLE_AGAIN */ + do { + bool is_eos = FALSE; + size_t bytestoread; + ssize_t nread; + + if(!is_multiplex) { + /* Multiplexed connection have inherent handling of EOF and we do not + * have to carefully restrict the amount we try to read. + * Multiplexed changes only in one direction. */ + is_multiplex = Curl_conn_is_multiplex(conn, FIRSTSOCKET); + } + + buf = xfer_buf; + bytestoread = xfer_blen; + + if(bytestoread && data->set.max_recv_speed) { + /* In case of speed limit on receiving: if this loop already got + * data, break out. If not, limit the amount of bytes to receive. + * The overall, timed, speed limiting is done in multi.c */ + if(total_received) + break; + if((size_t)data->set.max_recv_speed < bytestoread) + bytestoread = (size_t)data->set.max_recv_speed; + } + + nread = Curl_xfer_recv_resp(data, buf, bytestoread, + is_multiplex, &result); + if(nread < 0) { + if(CURLE_AGAIN == result) { + result = CURLE_OK; + break; /* get out of loop */ + } + goto out; /* real error */ + } + + /* We only get a 0-length read on EndOfStream */ + blen = (size_t)nread; + is_eos = (blen == 0); + *didwhat |= KEEP_RECV; + + if(!blen) { + /* if we receive 0 or less here, either the data transfer is done or the + server closed the connection and we bail out from this! */ + if(is_multiplex) + DEBUGF(infof(data, "nread == 0, stream closed, bailing")); + else + DEBUGF(infof(data, "nread <= 0, server closed connection, bailing")); + k->keepon &= ~(KEEP_RECV|KEEP_SEND); /* stop sending as well */ + if(k->eos_written) /* already did write this to client, leave */ + break; + } + total_received += blen; + + result = Curl_xfer_write_resp(data, buf, blen, is_eos); + if(result || data->req.done) + goto out; + + /* if we are done, we stop receiving. On multiplexed connections, + * we should read the EOS. Which may arrive as meta data after + * the bytes. Not taking it in might lead to RST of streams. */ + if((!is_multiplex && data->req.download_done) || is_eos) { + data->req.keepon &= ~KEEP_RECV; + } + /* if we are PAUSEd or stopped receiving, leave the loop */ + if((k->keepon & KEEP_RECV_PAUSE) || !(k->keepon & KEEP_RECV)) + break; + + } while(maxloops-- && data_pending(data)); + + if(maxloops <= 0) { + /* did not read until EAGAIN, mark read-again-please */ + data->state.select_bits = CURL_CSELECT_IN; + if((k->keepon & KEEP_SENDBITS) == KEEP_SEND) + data->state.select_bits |= CURL_CSELECT_OUT; + } + + if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) && + (conn->bits.close || is_multiplex)) { + /* When we've read the entire thing and the close bit is set, the server + may now close the connection. If there's now any kind of sending going + on from our side, we need to stop that immediately. */ + infof(data, "we are done reading and this is set to close, stop send"); + k->keepon &= ~KEEP_SEND; /* no writing anymore either */ + k->keepon &= ~KEEP_SEND_PAUSE; /* no pausing anymore either */ + } + +out: + Curl_multi_xfer_buf_release(data, xfer_buf); + if(result) + DEBUGF(infof(data, "readwrite_data() -> %d", result)); + return result; +} + +#if defined(_WIN32) && defined(USE_WINSOCK) +#ifndef SIO_IDEAL_SEND_BACKLOG_QUERY +#define SIO_IDEAL_SEND_BACKLOG_QUERY 0x4004747B +#endif + +static void win_update_buffer_size(curl_socket_t sockfd) +{ + int result; + ULONG ideal; + DWORD ideallen; + result = WSAIoctl(sockfd, SIO_IDEAL_SEND_BACKLOG_QUERY, 0, 0, + &ideal, sizeof(ideal), &ideallen, 0, 0); + if(result == 0) { + setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, + (const char *)&ideal, sizeof(ideal)); + } +} +#else +#define win_update_buffer_size(x) +#endif + +#define curl_upload_refill_watermark(data) \ + ((size_t)((data)->set.upload_buffer_size >> 5)) + +/* + * Send data to upload to the server, when the socket is writable. + */ +static CURLcode readwrite_upload(struct Curl_easy *data, int *didwhat) +{ + CURLcode result = CURLE_OK; + + if((data->req.keepon & KEEP_SEND_PAUSE)) + return CURLE_OK; + + /* We should not get here when the sending is already done. It + * probably means that someone set `data-req.keepon |= KEEP_SEND` + * when it should not. */ + DEBUGASSERT(!Curl_req_done_sending(data)); + + if(!Curl_req_done_sending(data)) { + *didwhat |= KEEP_SEND; + result = Curl_req_send_more(data); + if(result) + return result; + +#if defined(_WIN32) && defined(USE_WINSOCK) + /* FIXME: this looks like it would fit better into cf-socket.c + * but then I do not know enough Windows to say... */ + { + struct curltime n = Curl_now(); + if(Curl_timediff(n, data->conn->last_sndbuf_update) > 1000) { + win_update_buffer_size(data->conn->writesockfd); + data->conn->last_sndbuf_update = n; + } + } +#endif + } + return result; +} + +static int select_bits_paused(struct Curl_easy *data, int select_bits) +{ + /* See issue #11982: we really need to be careful not to progress + * a transfer direction when that direction is paused. Not all parts + * of our state machine are handling PAUSED transfers correctly. So, we + * do not want to go there. + * NOTE: we are only interested in PAUSE, not HOLD. */ + + /* if there is data in a direction not paused, return false */ + if(((select_bits & CURL_CSELECT_IN) && + !(data->req.keepon & KEEP_RECV_PAUSE)) || + ((select_bits & CURL_CSELECT_OUT) && + !(data->req.keepon & KEEP_SEND_PAUSE))) + return FALSE; + + return (data->req.keepon & (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)); +} + +/* + * Curl_readwrite() is the low-level function to be called when data is to + * be read and written to/from the connection. + */ +CURLcode Curl_readwrite(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + struct SingleRequest *k = &data->req; + CURLcode result; + struct curltime now; + int didwhat = 0; + int select_bits; + + /* Check if client writes had been paused and can resume now. */ + if(!(k->keepon & KEEP_RECV_PAUSE) && Curl_cwriter_is_paused(data)) { + Curl_conn_ev_data_pause(data, FALSE); + result = Curl_cwriter_unpause(data); + if(result) + goto out; + } + + if(data->state.select_bits) { + if(select_bits_paused(data, data->state.select_bits)) { + /* leave the bits unchanged, so they'll tell us what to do when + * this transfer gets unpaused. */ + DEBUGF(infof(data, "readwrite, select_bits, early return on PAUSED")); + result = CURLE_OK; + goto out; + } + select_bits = data->state.select_bits; + data->state.select_bits = 0; + } + else { + curl_socket_t fd_read; + curl_socket_t fd_write; + /* only use the proper socket if the *_HOLD bit is not set simultaneously + as then we are in rate limiting state in that transfer direction */ + if((k->keepon & KEEP_RECVBITS) == KEEP_RECV) + fd_read = conn->sockfd; + else + fd_read = CURL_SOCKET_BAD; + + if((k->keepon & KEEP_SENDBITS) == KEEP_SEND) + fd_write = conn->writesockfd; + else + fd_write = CURL_SOCKET_BAD; + + select_bits = Curl_socket_check(fd_read, CURL_SOCKET_BAD, fd_write, 0); + } + + if(select_bits == CURL_CSELECT_ERR) { + failf(data, "select/poll returned error"); + result = CURLE_SEND_ERROR; + goto out; + } + +#ifdef USE_HYPER + if(conn->datastream) { + result = conn->datastream(data, conn, &didwhat, select_bits); + if(result || data->req.done) + goto out; + } + else { +#endif + /* We go ahead and do a read if we have a readable socket or if + the stream was rewound (in which case we have data in a + buffer) */ + if((k->keepon & KEEP_RECV) && (select_bits & CURL_CSELECT_IN)) { + result = readwrite_data(data, k, &didwhat); + if(result || data->req.done) + goto out; + } + + /* If we still have writing to do, we check if we have a writable socket. */ + if(((k->keepon & KEEP_SEND) && (select_bits & CURL_CSELECT_OUT)) || + (k->keepon & KEEP_SEND_TIMED)) { + /* write */ + + result = readwrite_upload(data, &didwhat); + if(result) + goto out; + } +#ifdef USE_HYPER + } +#endif + + now = Curl_now(); + if(!didwhat) { + result = Curl_conn_ev_data_idle(data); + if(result) + goto out; + } + + if(Curl_pgrsUpdate(data)) + result = CURLE_ABORTED_BY_CALLBACK; + else + result = Curl_speedcheck(data, now); + if(result) + goto out; + + if(k->keepon) { + if(0 > Curl_timeleft(data, &now, FALSE)) { + if(k->size != -1) { + failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T + " milliseconds with %" CURL_FORMAT_CURL_OFF_T " out of %" + CURL_FORMAT_CURL_OFF_T " bytes received", + Curl_timediff(now, data->progress.t_startsingle), + k->bytecount, k->size); + } + else { + failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T + " milliseconds with %" CURL_FORMAT_CURL_OFF_T " bytes received", + Curl_timediff(now, data->progress.t_startsingle), + k->bytecount); + } + result = CURLE_OPERATION_TIMEDOUT; + goto out; + } + } + else { + /* + * The transfer has been performed. Just make some general checks before + * returning. + */ + if(!(data->req.no_body) && (k->size != -1) && + (k->bytecount != k->size) && +#ifdef CURL_DO_LINEEND_CONV + /* Most FTP servers don't adjust their file SIZE response for CRLFs, + so we'll check to see if the discrepancy can be explained + by the number of CRLFs we've changed to LFs. + */ + (k->bytecount != (k->size + data->state.crlf_conversions)) && +#endif /* CURL_DO_LINEEND_CONV */ + !k->newurl) { + failf(data, "transfer closed with %" CURL_FORMAT_CURL_OFF_T + " bytes remaining to read", k->size - k->bytecount); + result = CURLE_PARTIAL_FILE; + goto out; + } + if(Curl_pgrsUpdate(data)) { + result = CURLE_ABORTED_BY_CALLBACK; + goto out; + } + } + + /* If there is nothing more to send/recv, the request is done */ + if(0 == (k->keepon&(KEEP_RECVBITS|KEEP_SENDBITS))) + data->req.done = TRUE; + +out: + if(result) + DEBUGF(infof(data, "Curl_readwrite() -> %d", result)); + return result; +} + +/* Curl_init_CONNECT() gets called each time the handle switches to CONNECT + which means this gets called once for each subsequent redirect etc */ +void Curl_init_CONNECT(struct Curl_easy *data) +{ + data->state.fread_func = data->set.fread_func_set; + data->state.in = data->set.in_set; + data->state.upload = (data->state.httpreq == HTTPREQ_PUT); +} + +/* + * Curl_pretransfer() is called immediately before a transfer starts, and only + * once for one transfer no matter if it has redirects or do multi-pass + * authentication etc. + */ +CURLcode Curl_pretransfer(struct Curl_easy *data) +{ + CURLcode result; + + if(!data->state.url && !data->set.uh) { + /* we can't do anything without URL */ + failf(data, "No URL set"); + return CURLE_URL_MALFORMAT; + } + + /* since the URL may have been redirected in a previous use of this handle */ + if(data->state.url_alloc) { + /* the already set URL is allocated, free it first! */ + Curl_safefree(data->state.url); + data->state.url_alloc = FALSE; + } + + if(!data->state.url && data->set.uh) { + CURLUcode uc; + free(data->set.str[STRING_SET_URL]); + uc = curl_url_get(data->set.uh, + CURLUPART_URL, &data->set.str[STRING_SET_URL], 0); + if(uc) { + failf(data, "No URL set"); + return CURLE_URL_MALFORMAT; + } + } + + if(data->set.postfields && data->set.set_resume_from) { + /* we can't */ + failf(data, "cannot mix POSTFIELDS with RESUME_FROM"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + data->state.prefer_ascii = data->set.prefer_ascii; +#ifdef CURL_LIST_ONLY_PROTOCOL + data->state.list_only = data->set.list_only; +#endif + data->state.httpreq = data->set.method; + data->state.url = data->set.str[STRING_SET_URL]; + + /* Init the SSL session ID cache here. We do it here since we want to do it + after the *_setopt() calls (that could specify the size of the cache) but + before any transfer takes place. */ + result = Curl_ssl_initsessions(data, data->set.general_ssl.max_ssl_sessions); + if(result) + return result; + + data->state.requests = 0; + data->state.followlocation = 0; /* reset the location-follow counter */ + data->state.this_is_a_follow = FALSE; /* reset this */ + data->state.errorbuf = FALSE; /* no error has occurred */ + data->state.httpwant = data->set.httpwant; + data->state.httpversion = 0; + data->state.authproblem = FALSE; + data->state.authhost.want = data->set.httpauth; + data->state.authproxy.want = data->set.proxyauth; + Curl_safefree(data->info.wouldredirect); + Curl_data_priority_clear_state(data); + + if(data->state.httpreq == HTTPREQ_PUT) + data->state.infilesize = data->set.filesize; + else if((data->state.httpreq != HTTPREQ_GET) && + (data->state.httpreq != HTTPREQ_HEAD)) { + data->state.infilesize = data->set.postfieldsize; + if(data->set.postfields && (data->state.infilesize == -1)) + data->state.infilesize = (curl_off_t)strlen(data->set.postfields); + } + else + data->state.infilesize = 0; + + /* If there is a list of cookie files to read, do it now! */ + Curl_cookie_loadfiles(data); + + /* If there is a list of host pairs to deal with */ + if(data->state.resolve) + result = Curl_loadhostpairs(data); + + /* If there is a list of hsts files to read */ + Curl_hsts_loadfiles(data); + + if(!result) { + /* Allow data->set.use_port to set which port to use. This needs to be + * disabled for example when we follow Location: headers to URLs using + * different ports! */ + data->state.allow_port = TRUE; + +#if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL) + /************************************************************* + * Tell signal handler to ignore SIGPIPE + *************************************************************/ + if(!data->set.no_signal) + data->state.prev_signal = signal(SIGPIPE, SIG_IGN); +#endif + + Curl_initinfo(data); /* reset session-specific information "variables" */ + Curl_pgrsResetTransferSizes(data); + Curl_pgrsStartNow(data); + + /* In case the handle is reused and an authentication method was picked + in the session we need to make sure we only use the one(s) we now + consider to be fine */ + data->state.authhost.picked &= data->state.authhost.want; + data->state.authproxy.picked &= data->state.authproxy.want; + +#ifndef CURL_DISABLE_FTP + data->state.wildcardmatch = data->set.wildcard_enabled; + if(data->state.wildcardmatch) { + struct WildcardData *wc; + if(!data->wildcard) { + data->wildcard = calloc(1, sizeof(struct WildcardData)); + if(!data->wildcard) + return CURLE_OUT_OF_MEMORY; + } + wc = data->wildcard; + if(wc->state < CURLWC_INIT) { + if(wc->ftpwc) + wc->dtor(wc->ftpwc); + Curl_safefree(wc->pattern); + Curl_safefree(wc->path); + result = Curl_wildcard_init(wc); /* init wildcard structures */ + if(result) + return CURLE_OUT_OF_MEMORY; + } + } +#endif + result = Curl_hsts_loadcb(data, data->hsts); + } + + /* + * Set user-agent. Used for HTTP, but since we can attempt to tunnel + * basically anything through an HTTP proxy we can't limit this based on + * protocol. + */ + if(data->set.str[STRING_USERAGENT]) { + Curl_safefree(data->state.aptr.uagent); + data->state.aptr.uagent = + aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]); + if(!data->state.aptr.uagent) + return CURLE_OUT_OF_MEMORY; + } + + if(!result) + result = Curl_setstropt(&data->state.aptr.user, + data->set.str[STRING_USERNAME]); + if(!result) + result = Curl_setstropt(&data->state.aptr.passwd, + data->set.str[STRING_PASSWORD]); +#ifndef CURL_DISABLE_PROXY + if(!result) + result = Curl_setstropt(&data->state.aptr.proxyuser, + data->set.str[STRING_PROXYUSERNAME]); + if(!result) + result = Curl_setstropt(&data->state.aptr.proxypasswd, + data->set.str[STRING_PROXYPASSWORD]); +#endif + + data->req.headerbytecount = 0; + Curl_headers_cleanup(data); + return result; +} + +/* + * Curl_posttransfer() is called immediately after a transfer ends + */ +CURLcode Curl_posttransfer(struct Curl_easy *data) +{ +#if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL) + /* restore the signal handler for SIGPIPE before we get back */ + if(!data->set.no_signal) + signal(SIGPIPE, data->state.prev_signal); +#else + (void)data; /* unused parameter */ +#endif + + return CURLE_OK; +} + +/* + * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string + * as given by the remote server and set up the new URL to request. + * + * This function DOES NOT FREE the given url. + */ +CURLcode Curl_follow(struct Curl_easy *data, + char *newurl, /* the Location: string */ + followtype type) /* see transfer.h */ +{ +#ifdef CURL_DISABLE_HTTP + (void)data; + (void)newurl; + (void)type; + /* Location: following will not happen when HTTP is disabled */ + return CURLE_TOO_MANY_REDIRECTS; +#else + + /* Location: redirect */ + bool disallowport = FALSE; + bool reachedmax = FALSE; + CURLUcode uc; + + DEBUGASSERT(type != FOLLOW_NONE); + + if(type != FOLLOW_FAKE) + data->state.requests++; /* count all real follows */ + if(type == FOLLOW_REDIR) { + if((data->set.maxredirs != -1) && + (data->state.followlocation >= data->set.maxredirs)) { + reachedmax = TRUE; + type = FOLLOW_FAKE; /* switch to fake to store the would-be-redirected + to URL */ + } + else { + data->state.followlocation++; /* count redirect-followings, including + auth reloads */ + + if(data->set.http_auto_referer) { + CURLU *u; + char *referer = NULL; + + /* We are asked to automatically set the previous URL as the referer + when we get the next URL. We pick the ->url field, which may or may + not be 100% correct */ + + if(data->state.referer_alloc) { + Curl_safefree(data->state.referer); + data->state.referer_alloc = FALSE; + } + + /* Make a copy of the URL without credentials and fragment */ + u = curl_url(); + if(!u) + return CURLE_OUT_OF_MEMORY; + + uc = curl_url_set(u, CURLUPART_URL, data->state.url, 0); + if(!uc) + uc = curl_url_set(u, CURLUPART_FRAGMENT, NULL, 0); + if(!uc) + uc = curl_url_set(u, CURLUPART_USER, NULL, 0); + if(!uc) + uc = curl_url_set(u, CURLUPART_PASSWORD, NULL, 0); + if(!uc) + uc = curl_url_get(u, CURLUPART_URL, &referer, 0); + + curl_url_cleanup(u); + + if(uc || !referer) + return CURLE_OUT_OF_MEMORY; + + data->state.referer = referer; + data->state.referer_alloc = TRUE; /* yes, free this later */ + } + } + } + + if((type != FOLLOW_RETRY) && + (data->req.httpcode != 401) && (data->req.httpcode != 407) && + Curl_is_absolute_url(newurl, NULL, 0, FALSE)) { + /* If this is not redirect due to a 401 or 407 response and an absolute + URL: don't allow a custom port number */ + disallowport = TRUE; + } + + DEBUGASSERT(data->state.uh); + uc = curl_url_set(data->state.uh, CURLUPART_URL, newurl, + (type == FOLLOW_FAKE) ? CURLU_NON_SUPPORT_SCHEME : + ((type == FOLLOW_REDIR) ? CURLU_URLENCODE : 0) | + CURLU_ALLOW_SPACE | + (data->set.path_as_is ? CURLU_PATH_AS_IS : 0)); + if(uc) { + if(type != FOLLOW_FAKE) { + failf(data, "The redirect target URL could not be parsed: %s", + curl_url_strerror(uc)); + return Curl_uc_to_curlcode(uc); + } + + /* the URL could not be parsed for some reason, but since this is FAKE + mode, just duplicate the field as-is */ + newurl = strdup(newurl); + if(!newurl) + return CURLE_OUT_OF_MEMORY; + } + else { + uc = curl_url_get(data->state.uh, CURLUPART_URL, &newurl, 0); + if(uc) + return Curl_uc_to_curlcode(uc); + + /* Clear auth if this redirects to a different port number or protocol, + unless permitted */ + if(!data->set.allow_auth_to_other_hosts && (type != FOLLOW_FAKE)) { + char *portnum; + int port; + bool clear = FALSE; + + if(data->set.use_port && data->state.allow_port) + /* a custom port is used */ + port = (int)data->set.use_port; + else { + uc = curl_url_get(data->state.uh, CURLUPART_PORT, &portnum, + CURLU_DEFAULT_PORT); + if(uc) { + free(newurl); + return Curl_uc_to_curlcode(uc); + } + port = atoi(portnum); + free(portnum); + } + if(port != data->info.conn_remote_port) { + infof(data, "Clear auth, redirects to port from %u to %u", + data->info.conn_remote_port, port); + clear = TRUE; + } + else { + char *scheme; + const struct Curl_handler *p; + uc = curl_url_get(data->state.uh, CURLUPART_SCHEME, &scheme, 0); + if(uc) { + free(newurl); + return Curl_uc_to_curlcode(uc); + } + + p = Curl_get_scheme_handler(scheme); + if(p && (p->protocol != data->info.conn_protocol)) { + infof(data, "Clear auth, redirects scheme from %s to %s", + data->info.conn_scheme, scheme); + clear = TRUE; + } + free(scheme); + } + if(clear) { + Curl_safefree(data->state.aptr.user); + Curl_safefree(data->state.aptr.passwd); + } + } + } + + if(type == FOLLOW_FAKE) { + /* we're only figuring out the new url if we would've followed locations + but now we're done so we can get out! */ + data->info.wouldredirect = newurl; + + if(reachedmax) { + failf(data, "Maximum (%ld) redirects followed", data->set.maxredirs); + return CURLE_TOO_MANY_REDIRECTS; + } + return CURLE_OK; + } + + if(disallowport) + data->state.allow_port = FALSE; + + if(data->state.url_alloc) + Curl_safefree(data->state.url); + + data->state.url = newurl; + data->state.url_alloc = TRUE; + Curl_req_soft_reset(&data->req, data); + infof(data, "Issue another request to this URL: '%s'", data->state.url); + + /* + * We get here when the HTTP code is 300-399 (and 401). We need to perform + * differently based on exactly what return code there was. + * + * News from 7.10.6: we can also get here on a 401 or 407, in case we act on + * an HTTP (proxy-) authentication scheme other than Basic. + */ + switch(data->info.httpcode) { + /* 401 - Act on a WWW-Authenticate, we keep on moving and do the + Authorization: XXXX header in the HTTP request code snippet */ + /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the + Proxy-Authorization: XXXX header in the HTTP request code snippet */ + /* 300 - Multiple Choices */ + /* 306 - Not used */ + /* 307 - Temporary Redirect */ + default: /* for all above (and the unknown ones) */ + /* Some codes are explicitly mentioned since I've checked RFC2616 and they + * seem to be OK to POST to. + */ + break; + case 301: /* Moved Permanently */ + /* (quote from RFC7231, section 6.4.2) + * + * Note: For historical reasons, a user agent MAY change the request + * method from POST to GET for the subsequent request. If this + * behavior is undesired, the 307 (Temporary Redirect) status code + * can be used instead. + * + * ---- + * + * Many webservers expect this, so these servers often answers to a POST + * request with an error page. To be sure that libcurl gets the page that + * most user agents would get, libcurl has to force GET. + * + * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and + * can be overridden with CURLOPT_POSTREDIR. + */ + if((data->state.httpreq == HTTPREQ_POST + || data->state.httpreq == HTTPREQ_POST_FORM + || data->state.httpreq == HTTPREQ_POST_MIME) + && !(data->set.keep_post & CURL_REDIR_POST_301)) { + infof(data, "Switch from POST to GET"); + data->state.httpreq = HTTPREQ_GET; + Curl_creader_set_rewind(data, FALSE); + } + break; + case 302: /* Found */ + /* (quote from RFC7231, section 6.4.3) + * + * Note: For historical reasons, a user agent MAY change the request + * method from POST to GET for the subsequent request. If this + * behavior is undesired, the 307 (Temporary Redirect) status code + * can be used instead. + * + * ---- + * + * Many webservers expect this, so these servers often answers to a POST + * request with an error page. To be sure that libcurl gets the page that + * most user agents would get, libcurl has to force GET. + * + * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and + * can be overridden with CURLOPT_POSTREDIR. + */ + if((data->state.httpreq == HTTPREQ_POST + || data->state.httpreq == HTTPREQ_POST_FORM + || data->state.httpreq == HTTPREQ_POST_MIME) + && !(data->set.keep_post & CURL_REDIR_POST_302)) { + infof(data, "Switch from POST to GET"); + data->state.httpreq = HTTPREQ_GET; + Curl_creader_set_rewind(data, FALSE); + } + break; + + case 303: /* See Other */ + /* 'See Other' location is not the resource but a substitute for the + * resource. In this case we switch the method to GET/HEAD, unless the + * method is POST and the user specified to keep it as POST. + * https://github.com/curl/curl/issues/5237#issuecomment-614641049 + */ + if(data->state.httpreq != HTTPREQ_GET && + ((data->state.httpreq != HTTPREQ_POST && + data->state.httpreq != HTTPREQ_POST_FORM && + data->state.httpreq != HTTPREQ_POST_MIME) || + !(data->set.keep_post & CURL_REDIR_POST_303))) { + data->state.httpreq = HTTPREQ_GET; + infof(data, "Switch to %s", + data->req.no_body?"HEAD":"GET"); + } + break; + case 304: /* Not Modified */ + /* 304 means we did a conditional request and it was "Not modified". + * We shouldn't get any Location: header in this response! + */ + break; + case 305: /* Use Proxy */ + /* (quote from RFC2616, section 10.3.6): + * "The requested resource MUST be accessed through the proxy given + * by the Location field. The Location field gives the URI of the + * proxy. The recipient is expected to repeat this single request + * via the proxy. 305 responses MUST only be generated by origin + * servers." + */ + break; + } + Curl_pgrsTime(data, TIMER_REDIRECT); + Curl_pgrsResetTransferSizes(data); + + return CURLE_OK; +#endif /* CURL_DISABLE_HTTP */ +} + +/* Returns CURLE_OK *and* sets '*url' if a request retry is wanted. + + NOTE: that the *url is malloc()ed. */ +CURLcode Curl_retry_request(struct Curl_easy *data, char **url) +{ + struct connectdata *conn = data->conn; + bool retry = FALSE; + *url = NULL; + + /* if we're talking upload, we can't do the checks below, unless the protocol + is HTTP as when uploading over HTTP we will still get a response */ + if(data->state.upload && + !(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP))) + return CURLE_OK; + + if((data->req.bytecount + data->req.headerbytecount == 0) && + conn->bits.reuse && + (!data->req.no_body || (conn->handler->protocol & PROTO_FAMILY_HTTP)) +#ifndef CURL_DISABLE_RTSP + && (data->set.rtspreq != RTSPREQ_RECEIVE) +#endif + ) + /* We got no data, we attempted to reuse a connection. For HTTP this + can be a retry so we try again regardless if we expected a body. + For other protocols we only try again only if we expected a body. + + This might happen if the connection was left alive when we were + done using it before, but that was closed when we wanted to read from + it again. Bad luck. Retry the same request on a fresh connect! */ + retry = TRUE; + else if(data->state.refused_stream && + (data->req.bytecount + data->req.headerbytecount == 0) ) { + /* This was sent on a refused stream, safe to rerun. A refused stream + error can typically only happen on HTTP/2 level if the stream is safe + to issue again, but the nghttp2 API can deliver the message to other + streams as well, which is why this adds the check the data counters + too. */ + infof(data, "REFUSED_STREAM, retrying a fresh connect"); + data->state.refused_stream = FALSE; /* clear again */ + retry = TRUE; + } + if(retry) { +#define CONN_MAX_RETRIES 5 + if(data->state.retrycount++ >= CONN_MAX_RETRIES) { + failf(data, "Connection died, tried %d times before giving up", + CONN_MAX_RETRIES); + data->state.retrycount = 0; + return CURLE_SEND_ERROR; + } + infof(data, "Connection died, retrying a fresh connect (retry count: %d)", + data->state.retrycount); + *url = strdup(data->state.url); + if(!*url) + return CURLE_OUT_OF_MEMORY; + + connclose(conn, "retry"); /* close this connection */ + conn->bits.retry = TRUE; /* mark this as a connection we're about + to retry. Marking it this way should + prevent i.e HTTP transfers to return + error just because nothing has been + transferred! */ + Curl_creader_set_rewind(data, TRUE); + } + return CURLE_OK; +} + +/* + * Curl_xfer_setup() is called to setup some basic properties for the + * upcoming transfer. + */ +void Curl_xfer_setup( + struct Curl_easy *data, /* transfer */ + int sockindex, /* socket index to read from or -1 */ + curl_off_t size, /* -1 if unknown at this point */ + bool getheader, /* TRUE if header parsing is wanted */ + int writesockindex /* socket index to write to, it may very well be + the same we read from. -1 disables */ + ) +{ + struct SingleRequest *k = &data->req; + struct connectdata *conn = data->conn; + bool want_send = Curl_req_want_send(data); + + DEBUGASSERT(conn != NULL); + DEBUGASSERT((sockindex <= 1) && (sockindex >= -1)); + DEBUGASSERT((writesockindex <= 1) && (writesockindex >= -1)); + + if(conn->bits.multiplex || conn->httpversion >= 20 || want_send) { + /* when multiplexing, the read/write sockets need to be the same! */ + conn->sockfd = sockindex == -1 ? + ((writesockindex == -1 ? CURL_SOCKET_BAD : conn->sock[writesockindex])) : + conn->sock[sockindex]; + conn->writesockfd = conn->sockfd; + if(want_send) + /* special and very HTTP-specific */ + writesockindex = FIRSTSOCKET; + } + else { + conn->sockfd = sockindex == -1 ? + CURL_SOCKET_BAD : conn->sock[sockindex]; + conn->writesockfd = writesockindex == -1 ? + CURL_SOCKET_BAD:conn->sock[writesockindex]; + } + k->getheader = getheader; + + k->size = size; + + /* The code sequence below is placed in this function just because all + necessary input is not always known in do_complete() as this function may + be called after that */ + + if(!k->getheader) { + k->header = FALSE; + if(size > 0) + Curl_pgrsSetDownloadSize(data, size); + } + /* we want header and/or body, if neither then don't do this! */ + if(k->getheader || !data->req.no_body) { + + if(sockindex != -1) + k->keepon |= KEEP_RECV; + + if(writesockindex != -1) + k->keepon |= KEEP_SEND; + } /* if(k->getheader || !data->req.no_body) */ + +} + +CURLcode Curl_xfer_write_resp(struct Curl_easy *data, + const char *buf, size_t blen, + bool is_eos) +{ + CURLcode result = CURLE_OK; + + if(data->conn->handler->write_resp) { + /* protocol handlers offering this function take full responsibility + * for writing all received download data to the client. */ + result = data->conn->handler->write_resp(data, buf, blen, is_eos); + } + else { + /* No special handling by protocol handler, write all received data + * as BODY to the client. */ + if(blen || is_eos) { + int cwtype = CLIENTWRITE_BODY; + if(is_eos) + cwtype |= CLIENTWRITE_EOS; + +#ifndef CURL_DISABLE_POP3 + if(blen && data->conn->handler->protocol & PROTO_FAMILY_POP3) { + result = data->req.ignorebody? CURLE_OK : + Curl_pop3_write(data, buf, blen); + } + else +#endif /* CURL_DISABLE_POP3 */ + result = Curl_client_write(data, cwtype, buf, blen); + } + } + + if(!result && is_eos) { + /* If we wrote the EOS, we are definitely done */ + data->req.eos_written = TRUE; + data->req.download_done = TRUE; + } + CURL_TRC_WRITE(data, "xfer_write_resp(len=%zu, eos=%d) -> %d", + blen, is_eos, result); + return result; +} + +CURLcode Curl_xfer_write_resp_hd(struct Curl_easy *data, + const char *hd0, size_t hdlen, bool is_eos) +{ + if(data->conn->handler->write_resp_hd) { + /* protocol handlers offering this function take full responsibility + * for writing all received download data to the client. */ + return data->conn->handler->write_resp_hd(data, hd0, hdlen, is_eos); + } + /* No special handling by protocol handler, write as response bytes */ + return Curl_xfer_write_resp(data, hd0, hdlen, is_eos); +} + +CURLcode Curl_xfer_write_done(struct Curl_easy *data, bool premature) +{ + (void)premature; + return Curl_cw_out_done(data); +} + +CURLcode Curl_xfer_send(struct Curl_easy *data, + const void *buf, size_t blen, + size_t *pnwritten) +{ + CURLcode result; + int sockindex; + + if(!data || !data->conn) + return CURLE_FAILED_INIT; + /* FIXME: would like to enable this, but some protocols (MQTT) do not + * setup the transfer correctly, it seems + if(data->conn->writesockfd == CURL_SOCKET_BAD) { + failf(data, "transfer not setup for sending"); + DEBUGASSERT(0); + return CURLE_SEND_ERROR; + } */ + sockindex = ((data->conn->writesockfd != CURL_SOCKET_BAD) && + (data->conn->writesockfd == data->conn->sock[SECONDARYSOCKET])); + result = Curl_conn_send(data, sockindex, buf, blen, pnwritten); + if(result == CURLE_AGAIN) { + result = CURLE_OK; + *pnwritten = 0; + } + else if(!result && *pnwritten) + data->info.request_size += *pnwritten; + + return result; +} + +CURLcode Curl_xfer_recv(struct Curl_easy *data, + char *buf, size_t blen, + ssize_t *pnrcvd) +{ + int sockindex; + + if(!data || !data->conn) + return CURLE_FAILED_INIT; + /* FIXME: would like to enable this, but some protocols (MQTT) do not + * setup the transfer correctly, it seems + if(data->conn->sockfd == CURL_SOCKET_BAD) { + failf(data, "transfer not setup for receiving"); + DEBUGASSERT(0); + return CURLE_RECV_ERROR; + } */ + sockindex = ((data->conn->sockfd != CURL_SOCKET_BAD) && + (data->conn->sockfd == data->conn->sock[SECONDARYSOCKET])); + if(data->set.buffer_size > 0 && (size_t)data->set.buffer_size < blen) + blen = (size_t)data->set.buffer_size; + return Curl_conn_recv(data, sockindex, buf, blen, pnrcvd); +} + +CURLcode Curl_xfer_send_close(struct Curl_easy *data) +{ + Curl_conn_ev_data_done_send(data); + return CURLE_OK; +} diff --git a/third_party/curl/lib/transfer.h b/third_party/curl/lib/transfer.h new file mode 100644 index 0000000..ad0f3a2 --- /dev/null +++ b/third_party/curl/lib/transfer.h @@ -0,0 +1,115 @@ +#ifndef HEADER_CURL_TRANSFER_H +#define HEADER_CURL_TRANSFER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#define Curl_headersep(x) ((((x)==':') || ((x)==';'))) +char *Curl_checkheaders(const struct Curl_easy *data, + const char *thisheader, + const size_t thislen); + +void Curl_init_CONNECT(struct Curl_easy *data); + +CURLcode Curl_pretransfer(struct Curl_easy *data); +CURLcode Curl_posttransfer(struct Curl_easy *data); + +typedef enum { + FOLLOW_NONE, /* not used within the function, just a placeholder to + allow initing to this */ + FOLLOW_FAKE, /* only records stuff, not actually following */ + FOLLOW_RETRY, /* set if this is a request retry as opposed to a real + redirect following */ + FOLLOW_REDIR /* a full true redirect */ +} followtype; + +CURLcode Curl_follow(struct Curl_easy *data, char *newurl, + followtype type); +CURLcode Curl_readwrite(struct Curl_easy *data); +int Curl_single_getsock(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *socks); +CURLcode Curl_retry_request(struct Curl_easy *data, char **url); +bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc); + +/** + * Write the transfer raw response bytes, as received from the connection. + * Will handle all passed bytes or return an error. By default, this will + * write the bytes as BODY to the client. Protocols may provide a + * "write_resp" callback in their handler to add specific treatment. E.g. + * HTTP parses response headers and passes them differently to the client. + * @param data the transfer + * @param buf the raw response bytes + * @param blen the amount of bytes in `buf` + * @param is_eos TRUE iff the connection indicates this to be the last + * bytes of the response + */ +CURLcode Curl_xfer_write_resp(struct Curl_easy *data, + const char *buf, size_t blen, + bool is_eos); + +/** + * Write a single "header" line from a server response. + * @param hd0 the 0-terminated, single header line + * @param hdlen the length of the header line + * @param is_eos TRUE iff this is the end of the response + */ +CURLcode Curl_xfer_write_resp_hd(struct Curl_easy *data, + const char *hd0, size_t hdlen, bool is_eos); + +/* This sets up a forthcoming transfer */ +void Curl_xfer_setup(struct Curl_easy *data, + int sockindex, /* socket index to read from or -1 */ + curl_off_t size, /* -1 if unknown at this point */ + bool getheader, /* TRUE if header parsing is wanted */ + int writesockindex /* socket index to write to. May be + the same we read from. -1 + disables */ + ); + +/** + * Multi has set transfer to DONE. Last chance to trigger + * missing response things like writing an EOS to the client. + */ +CURLcode Curl_xfer_write_done(struct Curl_easy *data, bool premature); + +/** + * Send data on the socket/connection filter designated + * for transfer's outgoing data. + * Will return CURLE_OK on blocking with (*pnwritten == 0). + */ +CURLcode Curl_xfer_send(struct Curl_easy *data, + const void *buf, size_t blen, + size_t *pnwritten); + +/** + * Receive data on the socket/connection filter designated + * for transfer's incoming data. + * Will return CURLE_AGAIN on blocking with (*pnrcvd == 0). + */ +CURLcode Curl_xfer_recv(struct Curl_easy *data, + char *buf, size_t blen, + ssize_t *pnrcvd); + +CURLcode Curl_xfer_send_close(struct Curl_easy *data); + +#endif /* HEADER_CURL_TRANSFER_H */ diff --git a/third_party/curl/lib/url.c b/third_party/curl/lib/url.c new file mode 100644 index 0000000..2814d31 --- /dev/null +++ b/third_party/curl/lib/url.c @@ -0,0 +1,3972 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NET_IF_H +#include +#endif +#ifdef HAVE_IPHLPAPI_H +#include +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif +#ifdef HAVE_SYS_PARAM_H +#include +#endif + +#ifdef __VMS +#include +#include +#endif + +#ifdef HAVE_SYS_UN_H +#include +#endif + +#ifndef HAVE_SOCKET +#error "We can't compile without socket() support!" +#endif + +#include + +#include "doh.h" +#include "urldata.h" +#include "netrc.h" +#include "formdata.h" +#include "mime.h" +#include "vtls/vtls.h" +#include "hostip.h" +#include "transfer.h" +#include "sendf.h" +#include "progress.h" +#include "cookie.h" +#include "strcase.h" +#include "strerror.h" +#include "escape.h" +#include "strtok.h" +#include "share.h" +#include "content_encoding.h" +#include "http_digest.h" +#include "http_negotiate.h" +#include "select.h" +#include "multiif.h" +#include "easyif.h" +#include "speedcheck.h" +#include "warnless.h" +#include "getinfo.h" +#include "urlapi-int.h" +#include "system_win32.h" +#include "hsts.h" +#include "noproxy.h" +#include "cfilters.h" +#include "idn.h" + +/* And now for the protocols */ +#include "ftp.h" +#include "dict.h" +#include "telnet.h" +#include "tftp.h" +#include "http.h" +#include "http2.h" +#include "file.h" +#include "curl_ldap.h" +#include "vssh/ssh.h" +#include "imap.h" +#include "url.h" +#include "connect.h" +#include "inet_ntop.h" +#include "http_ntlm.h" +#include "curl_rtmp.h" +#include "gopher.h" +#include "mqtt.h" +#include "http_proxy.h" +#include "conncache.h" +#include "multihandle.h" +#include "strdup.h" +#include "setopt.h" +#include "altsvc.h" +#include "dynbuf.h" +#include "headers.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#ifndef ARRAYSIZE +#define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) +#endif + +#ifdef USE_NGHTTP2 +static void data_priority_cleanup(struct Curl_easy *data); +#else +#define data_priority_cleanup(x) +#endif + +/* Some parts of the code (e.g. chunked encoding) assume this buffer has at + * more than just a few bytes to play with. Don't let it become too small or + * bad things will happen. + */ +#if READBUFFER_SIZE < READBUFFER_MIN +# error READBUFFER_SIZE is too small +#endif + +#ifdef USE_UNIX_SOCKETS +#define UNIX_SOCKET_PREFIX "localhost" +#endif + +/* Reject URLs exceeding this length */ +#define MAX_URL_LEN 0xffff + +/* +* get_protocol_family() +* +* This is used to return the protocol family for a given protocol. +* +* Parameters: +* +* 'h' [in] - struct Curl_handler pointer. +* +* Returns the family as a single bit protocol identifier. +*/ +static curl_prot_t get_protocol_family(const struct Curl_handler *h) +{ + DEBUGASSERT(h); + DEBUGASSERT(h->family); + return h->family; +} + +void Curl_freeset(struct Curl_easy *data) +{ + /* Free all dynamic strings stored in the data->set substructure. */ + enum dupstring i; + enum dupblob j; + + for(i = (enum dupstring)0; i < STRING_LAST; i++) { + Curl_safefree(data->set.str[i]); + } + + for(j = (enum dupblob)0; j < BLOB_LAST; j++) { + Curl_safefree(data->set.blobs[j]); + } + + if(data->state.referer_alloc) { + Curl_safefree(data->state.referer); + data->state.referer_alloc = FALSE; + } + data->state.referer = NULL; + if(data->state.url_alloc) { + Curl_safefree(data->state.url); + data->state.url_alloc = FALSE; + } + data->state.url = NULL; + + Curl_mime_cleanpart(&data->set.mimepost); + +#ifndef CURL_DISABLE_COOKIES + curl_slist_free_all(data->state.cookielist); + data->state.cookielist = NULL; +#endif +} + +/* free the URL pieces */ +static void up_free(struct Curl_easy *data) +{ + struct urlpieces *up = &data->state.up; + Curl_safefree(up->scheme); + Curl_safefree(up->hostname); + Curl_safefree(up->port); + Curl_safefree(up->user); + Curl_safefree(up->password); + Curl_safefree(up->options); + Curl_safefree(up->path); + Curl_safefree(up->query); + curl_url_cleanup(data->state.uh); + data->state.uh = NULL; +} + +/* + * This is the internal function curl_easy_cleanup() calls. This should + * cleanup and free all resources associated with this sessionhandle. + * + * We ignore SIGPIPE when this is called from curl_easy_cleanup. + */ + +CURLcode Curl_close(struct Curl_easy **datap) +{ + struct Curl_easy *data; + + if(!datap || !*datap) + return CURLE_OK; + + data = *datap; + *datap = NULL; + + Curl_expire_clear(data); /* shut off timers */ + + /* Detach connection if any is left. This should not be normal, but can be + the case for example with CONNECT_ONLY + recv/send (test 556) */ + Curl_detach_connection(data); + if(!data->state.internal) { + if(data->multi) + /* This handle is still part of a multi handle, take care of this first + and detach this handle from there. */ + curl_multi_remove_handle(data->multi, data); + + if(data->multi_easy) { + /* when curl_easy_perform() is used, it creates its own multi handle to + use and this is the one */ + curl_multi_cleanup(data->multi_easy); + data->multi_easy = NULL; + } + } + + data->magic = 0; /* force a clear AFTER the possibly enforced removal from + the multi handle, since that function uses the magic + field! */ + + if(data->state.rangestringalloc) + free(data->state.range); + + /* freed here just in case DONE wasn't called */ + Curl_req_free(&data->req, data); + + /* Close down all open SSL info and sessions */ + Curl_ssl_close_all(data); + Curl_safefree(data->state.first_host); + Curl_safefree(data->state.scratch); + Curl_ssl_free_certinfo(data); + + if(data->state.referer_alloc) { + Curl_safefree(data->state.referer); + data->state.referer_alloc = FALSE; + } + data->state.referer = NULL; + + up_free(data); + Curl_dyn_free(&data->state.headerb); + Curl_flush_cookies(data, TRUE); +#ifndef CURL_DISABLE_ALTSVC + Curl_altsvc_save(data, data->asi, data->set.str[STRING_ALTSVC]); + Curl_altsvc_cleanup(&data->asi); +#endif +#ifndef CURL_DISABLE_HSTS + Curl_hsts_save(data, data->hsts, data->set.str[STRING_HSTS]); + if(!data->share || !data->share->hsts) + Curl_hsts_cleanup(&data->hsts); + curl_slist_free_all(data->state.hstslist); /* clean up list */ +#endif +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_DIGEST_AUTH) + Curl_http_auth_cleanup_digest(data); +#endif + Curl_safefree(data->info.contenttype); + Curl_safefree(data->info.wouldredirect); + + /* this destroys the channel and we cannot use it anymore after this */ + Curl_resolver_cancel(data); + Curl_resolver_cleanup(data->state.async.resolver); + + data_priority_cleanup(data); + + /* No longer a dirty share, if it exists */ + if(data->share) { + Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE); + data->share->dirty--; + Curl_share_unlock(data, CURL_LOCK_DATA_SHARE); + } + +#ifndef CURL_DISABLE_PROXY + Curl_safefree(data->state.aptr.proxyuserpwd); +#endif + Curl_safefree(data->state.aptr.uagent); + Curl_safefree(data->state.aptr.userpwd); + Curl_safefree(data->state.aptr.accept_encoding); + Curl_safefree(data->state.aptr.te); + Curl_safefree(data->state.aptr.rangeline); + Curl_safefree(data->state.aptr.ref); + Curl_safefree(data->state.aptr.host); +#ifndef CURL_DISABLE_COOKIES + Curl_safefree(data->state.aptr.cookiehost); +#endif +#ifndef CURL_DISABLE_RTSP + Curl_safefree(data->state.aptr.rtsp_transport); +#endif + Curl_safefree(data->state.aptr.user); + Curl_safefree(data->state.aptr.passwd); +#ifndef CURL_DISABLE_PROXY + Curl_safefree(data->state.aptr.proxyuser); + Curl_safefree(data->state.aptr.proxypasswd); +#endif + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_FORM_API) + Curl_mime_cleanpart(data->state.formp); + Curl_safefree(data->state.formp); +#endif + + /* destruct wildcard structures if it is needed */ + Curl_wildcard_dtor(&data->wildcard); + Curl_freeset(data); + Curl_headers_cleanup(data); + free(data); + return CURLE_OK; +} + +/* + * Initialize the UserDefined fields within a Curl_easy. + * This may be safely called on a new or existing Curl_easy. + */ +CURLcode Curl_init_userdefined(struct Curl_easy *data) +{ + struct UserDefined *set = &data->set; + CURLcode result = CURLE_OK; + + set->out = stdout; /* default output to stdout */ + set->in_set = stdin; /* default input from stdin */ + set->err = stderr; /* default stderr to stderr */ + + /* use fwrite as default function to store output */ + set->fwrite_func = (curl_write_callback)fwrite; + + /* use fread as default function to read input */ + set->fread_func_set = (curl_read_callback)fread; + set->is_fread_set = 0; + + set->seek_client = ZERO_NULL; + + set->filesize = -1; /* we don't know the size */ + set->postfieldsize = -1; /* unknown size */ + set->maxredirs = 30; /* sensible default */ + + set->method = HTTPREQ_GET; /* Default HTTP request */ +#ifndef CURL_DISABLE_RTSP + set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */ +#endif +#ifndef CURL_DISABLE_FTP + set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */ + set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */ + set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */ + set->ftp_filemethod = FTPFILE_MULTICWD; + set->ftp_skip_ip = TRUE; /* skip PASV IP by default */ +#endif + set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */ + + /* Set the default size of the SSL session ID cache */ + set->general_ssl.max_ssl_sessions = 5; + /* Timeout every 24 hours by default */ + set->general_ssl.ca_cache_timeout = 24 * 60 * 60; + + set->httpauth = CURLAUTH_BASIC; /* defaults to basic */ + +#ifndef CURL_DISABLE_PROXY + set->proxyport = 0; + set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */ + set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */ + /* SOCKS5 proxy auth defaults to username/password + GSS-API */ + set->socks5auth = CURLAUTH_BASIC | CURLAUTH_GSSAPI; +#endif + + /* make libcurl quiet by default: */ + set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */ + + Curl_mime_initpart(&set->mimepost); + + Curl_ssl_easy_config_init(data); +#ifndef CURL_DISABLE_DOH + set->doh_verifyhost = TRUE; + set->doh_verifypeer = TRUE; +#endif +#ifdef USE_SSH + /* defaults to any auth type */ + set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; + set->new_directory_perms = 0755; /* Default permissions */ +#endif + + set->new_file_perms = 0644; /* Default permissions */ + set->allowed_protocols = (curl_prot_t) CURLPROTO_ALL; + set->redir_protocols = CURLPROTO_HTTP | CURLPROTO_HTTPS | CURLPROTO_FTP | + CURLPROTO_FTPS; + +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + /* + * disallow unprotected protection negotiation NEC reference implementation + * seem not to follow rfc1961 section 4.3/4.4 + */ + set->socks5_gssapi_nec = FALSE; +#endif + + /* Set the default CA cert bundle/path detected/specified at build time. + * + * If Schannel or SecureTransport is the selected SSL backend then these + * locations are ignored. We allow setting CA location for schannel and + * securetransport when explicitly specified by the user via + * CURLOPT_CAINFO / --cacert. + */ + if(Curl_ssl_backend() != CURLSSLBACKEND_SCHANNEL && + Curl_ssl_backend() != CURLSSLBACKEND_SECURETRANSPORT) { +#if defined(CURL_CA_BUNDLE) + result = Curl_setstropt(&set->str[STRING_SSL_CAFILE], CURL_CA_BUNDLE); + if(result) + return result; +#ifndef CURL_DISABLE_PROXY + result = Curl_setstropt(&set->str[STRING_SSL_CAFILE_PROXY], + CURL_CA_BUNDLE); + if(result) + return result; +#endif +#endif +#if defined(CURL_CA_PATH) + result = Curl_setstropt(&set->str[STRING_SSL_CAPATH], CURL_CA_PATH); + if(result) + return result; +#ifndef CURL_DISABLE_PROXY + result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_PROXY], CURL_CA_PATH); + if(result) + return result; +#endif +#endif + } + +#ifndef CURL_DISABLE_FTP + set->wildcard_enabled = FALSE; + set->chunk_bgn = ZERO_NULL; + set->chunk_end = ZERO_NULL; + set->fnmatch = ZERO_NULL; +#endif + set->tcp_keepalive = FALSE; + set->tcp_keepintvl = 60; + set->tcp_keepidle = 60; + set->tcp_fastopen = FALSE; + set->tcp_nodelay = TRUE; + set->ssl_enable_alpn = TRUE; + set->expect_100_timeout = 1000L; /* Wait for a second by default. */ + set->sep_headers = TRUE; /* separated header lists by default */ + set->buffer_size = READBUFFER_SIZE; + set->upload_buffer_size = UPLOADBUFFER_DEFAULT; + set->happy_eyeballs_timeout = CURL_HET_DEFAULT; + set->upkeep_interval_ms = CURL_UPKEEP_INTERVAL_DEFAULT; + set->maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */ + set->maxage_conn = 118; + set->maxlifetime_conn = 0; + set->http09_allowed = FALSE; +#ifdef USE_HTTP2 + set->httpwant = CURL_HTTP_VERSION_2TLS +#else + set->httpwant = CURL_HTTP_VERSION_1_1 +#endif + ; +#if defined(USE_HTTP2) || defined(USE_HTTP3) + memset(&set->priority, 0, sizeof(set->priority)); +#endif + set->quick_exit = 0L; + return result; +} + +/** + * Curl_open() + * + * @param curl is a pointer to a sessionhandle pointer that gets set by this + * function. + * @return CURLcode + */ + +CURLcode Curl_open(struct Curl_easy **curl) +{ + CURLcode result; + struct Curl_easy *data; + + /* Very simple start-up: alloc the struct, init it with zeroes and return */ + data = calloc(1, sizeof(struct Curl_easy)); + if(!data) { + /* this is a very serious error */ + DEBUGF(fprintf(stderr, "Error: calloc of Curl_easy failed\n")); + return CURLE_OUT_OF_MEMORY; + } + + data->magic = CURLEASY_MAGIC_NUMBER; + + Curl_req_init(&data->req); + + result = Curl_resolver_init(data, &data->state.async.resolver); + if(result) { + DEBUGF(fprintf(stderr, "Error: resolver_init failed\n")); + Curl_req_free(&data->req, data); + free(data); + return result; + } + + result = Curl_init_userdefined(data); + if(!result) { + Curl_dyn_init(&data->state.headerb, CURL_MAX_HTTP_HEADER); + Curl_initinfo(data); + + /* most recent connection is not yet defined */ + data->state.lastconnect_id = -1; + data->state.recent_conn_id = -1; + /* and not assigned an id yet */ + data->id = -1; + + data->progress.flags |= PGRS_HIDE; + data->state.current_speed = -1; /* init to negative == impossible */ + } + + if(result) { + Curl_resolver_cleanup(data->state.async.resolver); + Curl_dyn_free(&data->state.headerb); + Curl_freeset(data); + Curl_req_free(&data->req, data); + free(data); + data = NULL; + } + else + *curl = data; + + return result; +} + +static void conn_shutdown(struct Curl_easy *data) +{ + DEBUGASSERT(data); + infof(data, "Closing connection"); + + /* possible left-overs from the async name resolvers */ + Curl_resolver_cancel(data); + + Curl_conn_close(data, SECONDARYSOCKET); + Curl_conn_close(data, FIRSTSOCKET); +} + +static void conn_free(struct Curl_easy *data, struct connectdata *conn) +{ + size_t i; + + DEBUGASSERT(conn); + + for(i = 0; i < ARRAYSIZE(conn->cfilter); ++i) { + Curl_conn_cf_discard_all(data, conn, (int)i); + } + + Curl_free_idnconverted_hostname(&conn->host); + Curl_free_idnconverted_hostname(&conn->conn_to_host); +#ifndef CURL_DISABLE_PROXY + Curl_free_idnconverted_hostname(&conn->http_proxy.host); + Curl_free_idnconverted_hostname(&conn->socks_proxy.host); + Curl_safefree(conn->http_proxy.user); + Curl_safefree(conn->socks_proxy.user); + Curl_safefree(conn->http_proxy.passwd); + Curl_safefree(conn->socks_proxy.passwd); + Curl_safefree(conn->http_proxy.host.rawalloc); /* http proxy name buffer */ + Curl_safefree(conn->socks_proxy.host.rawalloc); /* socks proxy name buffer */ +#endif + Curl_safefree(conn->user); + Curl_safefree(conn->passwd); + Curl_safefree(conn->sasl_authzid); + Curl_safefree(conn->options); + Curl_safefree(conn->oauth_bearer); + Curl_safefree(conn->host.rawalloc); /* host name buffer */ + Curl_safefree(conn->conn_to_host.rawalloc); /* host name buffer */ + Curl_safefree(conn->hostname_resolve); + Curl_safefree(conn->secondaryhostname); + Curl_safefree(conn->localdev); + Curl_ssl_conn_config_cleanup(conn); + +#ifdef USE_UNIX_SOCKETS + Curl_safefree(conn->unix_domain_socket); +#endif + + free(conn); /* free all the connection oriented data */ +} + +/* + * Disconnects the given connection. Note the connection may not be the + * primary connection, like when freeing room in the connection cache or + * killing of a dead old connection. + * + * A connection needs an easy handle when closing down. We support this passed + * in separately since the connection to get closed here is often already + * disassociated from an easy handle. + * + * This function MUST NOT reset state in the Curl_easy struct if that + * isn't strictly bound to the life-time of *this* particular connection. + * + */ + +void Curl_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead_connection) +{ + /* there must be a connection to close */ + DEBUGASSERT(conn); + + /* it must be removed from the connection cache */ + DEBUGASSERT(!conn->bundle); + + /* there must be an associated transfer */ + DEBUGASSERT(data); + + /* the transfer must be detached from the connection */ + DEBUGASSERT(!data->conn); + + DEBUGF(infof(data, "Curl_disconnect(conn #%" + CURL_FORMAT_CURL_OFF_T ", dead=%d)", + conn->connection_id, dead_connection)); + /* + * If this connection isn't marked to force-close, leave it open if there + * are other users of it + */ + if(CONN_INUSE(conn) && !dead_connection) { + DEBUGF(infof(data, "Curl_disconnect when inuse: %zu", CONN_INUSE(conn))); + return; + } + + if(conn->dns_entry) { + Curl_resolv_unlock(data, conn->dns_entry); + conn->dns_entry = NULL; + } + + /* Cleanup NTLM connection-related data */ + Curl_http_auth_cleanup_ntlm(conn); + + /* Cleanup NEGOTIATE connection-related data */ + Curl_http_auth_cleanup_negotiate(conn); + + if(conn->connect_only) + /* treat the connection as dead in CONNECT_ONLY situations */ + dead_connection = TRUE; + + /* temporarily attach the connection to this transfer handle for the + disconnect and shutdown */ + Curl_attach_connection(data, conn); + + if(conn->handler && conn->handler->disconnect) + /* This is set if protocol-specific cleanups should be made */ + conn->handler->disconnect(data, conn, dead_connection); + + conn_shutdown(data); + + /* detach it again */ + Curl_detach_connection(data); + + conn_free(data, conn); +} + +/* + * IsMultiplexingPossible() + * + * Return a bitmask with the available multiplexing options for the given + * requested connection. + */ +static int IsMultiplexingPossible(const struct Curl_easy *handle, + const struct connectdata *conn) +{ + int avail = 0; + + /* If an HTTP protocol and multiplexing is enabled */ + if((conn->handler->protocol & PROTO_FAMILY_HTTP) && + (!conn->bits.protoconnstart || !conn->bits.close)) { + + if(Curl_multiplex_wanted(handle->multi) && + (handle->state.httpwant >= CURL_HTTP_VERSION_2)) + /* allows HTTP/2 */ + avail |= CURLPIPE_MULTIPLEX; + } + return avail; +} + +#ifndef CURL_DISABLE_PROXY +static bool +proxy_info_matches(const struct proxy_info *data, + const struct proxy_info *needle) +{ + if((data->proxytype == needle->proxytype) && + (data->port == needle->port) && + strcasecompare(data->host.name, needle->host.name)) + return TRUE; + + return FALSE; +} + +static bool +socks_proxy_info_matches(const struct proxy_info *data, + const struct proxy_info *needle) +{ + if(!proxy_info_matches(data, needle)) + return FALSE; + + /* the user information is case-sensitive + or at least it is not defined as case-insensitive + see https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.1 */ + + /* curl_strequal does a case insensitive comparison, + so do not use it here! */ + if(Curl_timestrcmp(data->user, needle->user) || + Curl_timestrcmp(data->passwd, needle->passwd)) + return FALSE; + return TRUE; +} +#else +/* disabled, won't get called */ +#define proxy_info_matches(x,y) FALSE +#define socks_proxy_info_matches(x,y) FALSE +#endif + +/* A connection has to have been idle for a shorter time than 'maxage_conn' + (the success rate is just too low after this), or created less than + 'maxlifetime_conn' ago, to be subject for reuse. */ + +static bool conn_maxage(struct Curl_easy *data, + struct connectdata *conn, + struct curltime now) +{ + timediff_t idletime, lifetime; + + idletime = Curl_timediff(now, conn->lastused); + idletime /= 1000; /* integer seconds is fine */ + + if(idletime > data->set.maxage_conn) { + infof(data, "Too old connection (%" CURL_FORMAT_TIMEDIFF_T + " seconds idle), disconnect it", idletime); + return TRUE; + } + + lifetime = Curl_timediff(now, conn->created); + lifetime /= 1000; /* integer seconds is fine */ + + if(data->set.maxlifetime_conn && lifetime > data->set.maxlifetime_conn) { + infof(data, + "Too old connection (%" CURL_FORMAT_TIMEDIFF_T + " seconds since creation), disconnect it", lifetime); + return TRUE; + } + + + return FALSE; +} + +/* + * This function checks if the given connection is dead and prunes it from + * the connection cache if so. + * + * When this is called as a Curl_conncache_foreach() callback, the connection + * cache lock is held! + * + * Returns TRUE if the connection was dead and pruned. + */ +static bool prune_if_dead(struct connectdata *conn, + struct Curl_easy *data) +{ + if(!CONN_INUSE(conn)) { + /* The check for a dead socket makes sense only if the connection isn't in + use */ + bool dead; + struct curltime now = Curl_now(); + if(conn_maxage(data, conn, now)) { + /* avoid check if already too old */ + dead = TRUE; + } + else if(conn->handler->connection_check) { + /* The protocol has a special method for checking the state of the + connection. Use it to check if the connection is dead. */ + unsigned int state; + + /* briefly attach the connection to this transfer for the purpose of + checking it */ + Curl_attach_connection(data, conn); + + state = conn->handler->connection_check(data, conn, CONNCHECK_ISDEAD); + dead = (state & CONNRESULT_DEAD); + /* detach the connection again */ + Curl_detach_connection(data); + + } + else { + bool input_pending = FALSE; + + Curl_attach_connection(data, conn); + dead = !Curl_conn_is_alive(data, conn, &input_pending); + if(input_pending) { + /* For reuse, we want a "clean" connection state. The includes + * that we expect - in general - no waiting input data. Input + * waiting might be a TLS Notify Close, for example. We reject + * that. + * For protocols where data from other end may arrive at + * any time (HTTP/2 PING for example), the protocol handler needs + * to install its own `connection_check` callback. + */ + dead = TRUE; + } + Curl_detach_connection(data); + } + + if(dead) { + /* remove connection from cache */ + infof(data, "Connection %" CURL_FORMAT_CURL_OFF_T " seems to be dead", + conn->connection_id); + Curl_conncache_remove_conn(data, conn, FALSE); + return TRUE; + } + } + return FALSE; +} + +/* + * Wrapper to use prune_if_dead() function in Curl_conncache_foreach() + * + */ +static int call_prune_if_dead(struct Curl_easy *data, + struct connectdata *conn, void *param) +{ + struct connectdata **pruned = (struct connectdata **)param; + if(prune_if_dead(conn, data)) { + /* stop the iteration here, pass back the connection that was pruned */ + *pruned = conn; + return 1; + } + return 0; /* continue iteration */ +} + +/* + * This function scans the connection cache for half-open/dead connections, + * closes and removes them. The cleanup is done at most once per second. + * + * When called, this transfer has no connection attached. + */ +static void prune_dead_connections(struct Curl_easy *data) +{ + struct curltime now = Curl_now(); + timediff_t elapsed; + + DEBUGASSERT(!data->conn); /* no connection */ + CONNCACHE_LOCK(data); + elapsed = + Curl_timediff(now, data->state.conn_cache->last_cleanup); + CONNCACHE_UNLOCK(data); + + if(elapsed >= 1000L) { + struct connectdata *pruned = NULL; + while(Curl_conncache_foreach(data, data->state.conn_cache, &pruned, + call_prune_if_dead)) { + /* unlocked */ + + /* connection previously removed from cache in prune_if_dead() */ + + /* disconnect it */ + Curl_disconnect(data, pruned, TRUE); + } + CONNCACHE_LOCK(data); + data->state.conn_cache->last_cleanup = now; + CONNCACHE_UNLOCK(data); + } +} + +#ifdef USE_SSH +static bool ssh_config_matches(struct connectdata *one, + struct connectdata *two) +{ + return (Curl_safecmp(one->proto.sshc.rsa, two->proto.sshc.rsa) && + Curl_safecmp(one->proto.sshc.rsa_pub, two->proto.sshc.rsa_pub)); +} +#else +#define ssh_config_matches(x,y) FALSE +#endif + +/* + * Given one filled in connection struct (named needle), this function should + * detect if there already is one that has all the significant details + * exactly the same and thus should be used instead. + * + * If there is a match, this function returns TRUE - and has marked the + * connection as 'in-use'. It must later be called with ConnectionDone() to + * return back to 'idle' (unused) state. + * + * The force_reuse flag is set if the connection must be used. + */ +static bool +ConnectionExists(struct Curl_easy *data, + struct connectdata *needle, + struct connectdata **usethis, + bool *force_reuse, + bool *waitpipe) +{ + struct connectdata *chosen = NULL; + bool foundPendingCandidate = FALSE; + bool canmultiplex = FALSE; + struct connectbundle *bundle; + struct Curl_llist_element *curr; + +#ifdef USE_NTLM + bool wantNTLMhttp = ((data->state.authhost.want & CURLAUTH_NTLM) && + (needle->handler->protocol & PROTO_FAMILY_HTTP)); +#ifndef CURL_DISABLE_PROXY + bool wantProxyNTLMhttp = (needle->bits.proxy_user_passwd && + ((data->state.authproxy.want & + CURLAUTH_NTLM) && + (needle->handler->protocol & PROTO_FAMILY_HTTP))); +#else + bool wantProxyNTLMhttp = FALSE; +#endif +#endif + /* plain HTTP with upgrade */ + bool h2upgrade = (data->state.httpwant == CURL_HTTP_VERSION_2_0) && + (needle->handler->protocol & CURLPROTO_HTTP); + + *usethis = NULL; + *force_reuse = FALSE; + *waitpipe = FALSE; + + /* Look up the bundle with all the connections to this particular host. + Locks the connection cache, beware of early returns! */ + bundle = Curl_conncache_find_bundle(data, needle, data->state.conn_cache); + if(!bundle) { + CONNCACHE_UNLOCK(data); + return FALSE; + } + infof(data, "Found bundle for host: %p [%s]", + (void *)bundle, (bundle->multiuse == BUNDLE_MULTIPLEX ? + "can multiplex" : "serially")); + + /* We can only multiplex iff the transfer allows it AND we know + * that the server we want to talk to supports it as well. */ + canmultiplex = FALSE; + if(IsMultiplexingPossible(data, needle)) { + if(bundle->multiuse == BUNDLE_UNKNOWN) { + if(data->set.pipewait) { + infof(data, "Server doesn't support multiplex yet, wait"); + *waitpipe = TRUE; + CONNCACHE_UNLOCK(data); + return FALSE; /* no reuse */ + } + infof(data, "Server doesn't support multiplex (yet)"); + } + else if(bundle->multiuse == BUNDLE_MULTIPLEX) { + if(Curl_multiplex_wanted(data->multi)) + canmultiplex = TRUE; + else + infof(data, "Could multiplex, but not asked to"); + } + else if(bundle->multiuse == BUNDLE_NO_MULTIUSE) { + infof(data, "Can not multiplex, even if we wanted to"); + } + } + + curr = bundle->conn_list.head; + while(curr) { + struct connectdata *check = curr->ptr; + /* Get next node now. We might remove a dead `check` connection which + * would invalidate `curr` as well. */ + curr = curr->next; + + /* Note that if we use an HTTP proxy in normal mode (no tunneling), we + * check connections to that proxy and not to the actual remote server. + */ + if(check->connect_only || check->bits.close) + /* connect-only or to-be-closed connections will not be reused */ + continue; + + if(data->set.ipver != CURL_IPRESOLVE_WHATEVER + && data->set.ipver != check->ip_version) { + /* skip because the connection is not via the requested IP version */ + continue; + } + + if(!canmultiplex) { + if(Curl_resolver_asynch() && + /* remote_ip[0] is NUL only if the resolving of the name hasn't + completed yet and until then we don't reuse this connection */ + !check->primary.remote_ip[0]) + continue; + } + + if(CONN_INUSE(check)) { + if(!canmultiplex) { + /* transfer can't be multiplexed and check is in use */ + continue; + } + else { + /* Could multiplex, but not when check belongs to another multi */ + struct Curl_llist_element *e = check->easyq.head; + struct Curl_easy *entry = e->ptr; + if(entry->multi != data->multi) + continue; + } + } + + if(!Curl_conn_is_connected(check, FIRSTSOCKET)) { + foundPendingCandidate = TRUE; + /* Don't pick a connection that hasn't connected yet */ + infof(data, "Connection #%" CURL_FORMAT_CURL_OFF_T + " isn't open enough, can't reuse", check->connection_id); + continue; + } + + /* `check` is connected. if it is in use and does not support multiplex, + * we cannot use it. */ + if(!check->bits.multiplex && CONN_INUSE(check)) + continue; + +#ifdef USE_UNIX_SOCKETS + if(needle->unix_domain_socket) { + if(!check->unix_domain_socket) + continue; + if(strcmp(needle->unix_domain_socket, check->unix_domain_socket)) + continue; + if(needle->bits.abstract_unix_socket != + check->bits.abstract_unix_socket) + continue; + } + else if(check->unix_domain_socket) + continue; +#endif + + if((needle->handler->flags&PROTOPT_SSL) != + (check->handler->flags&PROTOPT_SSL)) + /* don't do mixed SSL and non-SSL connections */ + if(get_protocol_family(check->handler) != + needle->handler->protocol || !check->bits.tls_upgraded) + /* except protocols that have been upgraded via TLS */ + continue; + + if(needle->bits.conn_to_host != check->bits.conn_to_host) + /* don't mix connections that use the "connect to host" feature and + * connections that don't use this feature */ + continue; + + if(needle->bits.conn_to_port != check->bits.conn_to_port) + /* don't mix connections that use the "connect to port" feature and + * connections that don't use this feature */ + continue; + +#ifndef CURL_DISABLE_PROXY + if(needle->bits.httpproxy != check->bits.httpproxy || + needle->bits.socksproxy != check->bits.socksproxy) + continue; + + if(needle->bits.socksproxy && + !socks_proxy_info_matches(&needle->socks_proxy, + &check->socks_proxy)) + continue; + + if(needle->bits.httpproxy) { + if(needle->bits.tunnel_proxy != check->bits.tunnel_proxy) + continue; + + if(!proxy_info_matches(&needle->http_proxy, &check->http_proxy)) + continue; + + if(IS_HTTPS_PROXY(needle->http_proxy.proxytype)) { + /* https proxies come in different types, http/1.1, h2, ... */ + if(needle->http_proxy.proxytype != check->http_proxy.proxytype) + continue; + /* match SSL config to proxy */ + if(!Curl_ssl_conn_config_match(data, check, TRUE)) { + DEBUGF(infof(data, + "Connection #%" CURL_FORMAT_CURL_OFF_T + " has different SSL proxy parameters, can't reuse", + check->connection_id)); + continue; + } + /* the SSL config to the server, which may apply here is checked + * further below */ + } + } +#endif + + if(h2upgrade && !check->httpversion && canmultiplex) { + if(data->set.pipewait) { + infof(data, "Server upgrade doesn't support multiplex yet, wait"); + *waitpipe = TRUE; + CONNCACHE_UNLOCK(data); + return FALSE; /* no reuse */ + } + infof(data, "Server upgrade cannot be used"); + continue; /* can't be used atm */ + } + + if(needle->localdev || needle->localport) { + /* If we are bound to a specific local end (IP+port), we must not + reuse a random other one, although if we didn't ask for a + particular one we can reuse one that was bound. + + This comparison is a bit rough and too strict. Since the input + parameters can be specified in numerous ways and still end up the + same it would take a lot of processing to make it really accurate. + Instead, this matching will assume that reuses of bound connections + will most likely also reuse the exact same binding parameters and + missing out a few edge cases shouldn't hurt anyone very much. + */ + if((check->localport != needle->localport) || + (check->localportrange != needle->localportrange) || + (needle->localdev && + (!check->localdev || strcmp(check->localdev, needle->localdev)))) + continue; + } + + if(!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) { + /* This protocol requires credentials per connection, + so verify that we're using the same name and password as well */ + if(Curl_timestrcmp(needle->user, check->user) || + Curl_timestrcmp(needle->passwd, check->passwd) || + Curl_timestrcmp(needle->sasl_authzid, check->sasl_authzid) || + Curl_timestrcmp(needle->oauth_bearer, check->oauth_bearer)) { + /* one of them was different */ + continue; + } + } + + /* GSS delegation differences do not actually affect every connection + and auth method, but this check takes precaution before efficiency */ + if(needle->gssapi_delegation != check->gssapi_delegation) + continue; + + /* If looking for HTTP and the HTTP version we want is less + * than the HTTP version of the check connection, continue looking */ + if((needle->handler->protocol & PROTO_FAMILY_HTTP) && + (((check->httpversion >= 20) && + (data->state.httpwant < CURL_HTTP_VERSION_2_0)) + || ((check->httpversion >= 30) && + (data->state.httpwant < CURL_HTTP_VERSION_3)))) + continue; +#ifdef USE_SSH + else if(get_protocol_family(needle->handler) & PROTO_FAMILY_SSH) { + if(!ssh_config_matches(needle, check)) + continue; + } +#endif +#ifndef CURL_DISABLE_FTP + else if(get_protocol_family(needle->handler) & PROTO_FAMILY_FTP) { + /* Also match ACCOUNT, ALTERNATIVE-TO-USER, USE_SSL and CCC options */ + if(Curl_timestrcmp(needle->proto.ftpc.account, + check->proto.ftpc.account) || + Curl_timestrcmp(needle->proto.ftpc.alternative_to_user, + check->proto.ftpc.alternative_to_user) || + (needle->proto.ftpc.use_ssl != check->proto.ftpc.use_ssl) || + (needle->proto.ftpc.ccc != check->proto.ftpc.ccc)) + continue; + } +#endif + + /* Additional match requirements if talking TLS OR + * not talking to a HTTP proxy OR using a tunnel through a proxy */ + if((needle->handler->flags&PROTOPT_SSL) +#ifndef CURL_DISABLE_PROXY + || !needle->bits.httpproxy || needle->bits.tunnel_proxy +#endif + ) { + /* Talking the same protocol scheme or a TLS upgraded protocol in the + * same protocol family? */ + if(!strcasecompare(needle->handler->scheme, check->handler->scheme) && + (get_protocol_family(check->handler) != + needle->handler->protocol || !check->bits.tls_upgraded)) + continue; + + /* If needle has "conn_to_*" set, check must match this */ + if((needle->bits.conn_to_host && !strcasecompare( + needle->conn_to_host.name, check->conn_to_host.name)) || + (needle->bits.conn_to_port && + needle->conn_to_port != check->conn_to_port)) + continue; + + /* hostname and port must match */ + if(!strcasecompare(needle->host.name, check->host.name) || + needle->remote_port != check->remote_port) + continue; + + /* If talking TLS, check needs to use the same SSL options. */ + if((needle->handler->flags & PROTOPT_SSL) && + !Curl_ssl_conn_config_match(data, check, FALSE)) { + DEBUGF(infof(data, + "Connection #%" CURL_FORMAT_CURL_OFF_T + " has different SSL parameters, can't reuse", + check->connection_id)); + continue; + } + } + +#if defined(USE_NTLM) + /* If we are looking for an HTTP+NTLM connection, check if this is + already authenticating with the right credentials. If not, keep + looking so that we can reuse NTLM connections if + possible. (Especially we must not reuse the same connection if + partway through a handshake!) */ + if(wantNTLMhttp) { + if(Curl_timestrcmp(needle->user, check->user) || + Curl_timestrcmp(needle->passwd, check->passwd)) { + + /* we prefer a credential match, but this is at least a connection + that can be reused and "upgraded" to NTLM */ + if(check->http_ntlm_state == NTLMSTATE_NONE) + chosen = check; + continue; + } + } + else if(check->http_ntlm_state != NTLMSTATE_NONE) { + /* Connection is using NTLM auth but we don't want NTLM */ + continue; + } + +#ifndef CURL_DISABLE_PROXY + /* Same for Proxy NTLM authentication */ + if(wantProxyNTLMhttp) { + /* Both check->http_proxy.user and check->http_proxy.passwd can be + * NULL */ + if(!check->http_proxy.user || !check->http_proxy.passwd) + continue; + + if(Curl_timestrcmp(needle->http_proxy.user, + check->http_proxy.user) || + Curl_timestrcmp(needle->http_proxy.passwd, + check->http_proxy.passwd)) + continue; + } + else if(check->proxy_ntlm_state != NTLMSTATE_NONE) { + /* Proxy connection is using NTLM auth but we don't want NTLM */ + continue; + } +#endif + if(wantNTLMhttp || wantProxyNTLMhttp) { + /* Credentials are already checked, we may use this connection. + * With NTLM being weird as it is, we MUST use a + * connection where it has already been fully negotiated. + * If it has not, we keep on looking for a better one. */ + chosen = check; + + if((wantNTLMhttp && + (check->http_ntlm_state != NTLMSTATE_NONE)) || + (wantProxyNTLMhttp && + (check->proxy_ntlm_state != NTLMSTATE_NONE))) { + /* We must use this connection, no other */ + *force_reuse = TRUE; + break; + } + /* Continue look up for a better connection */ + continue; + } +#endif + + if(CONN_INUSE(check)) { + DEBUGASSERT(canmultiplex); + DEBUGASSERT(check->bits.multiplex); + /* If multiplexed, make sure we don't go over concurrency limit */ + if(CONN_INUSE(check) >= + Curl_multi_max_concurrent_streams(data->multi)) { + infof(data, "client side MAX_CONCURRENT_STREAMS reached" + ", skip (%zu)", CONN_INUSE(check)); + continue; + } + if(CONN_INUSE(check) >= + Curl_conn_get_max_concurrent(data, check, FIRSTSOCKET)) { + infof(data, "MAX_CONCURRENT_STREAMS reached, skip (%zu)", + CONN_INUSE(check)); + continue; + } + /* When not multiplexed, we have a match here! */ + infof(data, "Multiplexed connection found"); + } + else if(prune_if_dead(check, data)) { + /* disconnect it */ + Curl_disconnect(data, check, TRUE); + continue; + } + + /* We have found a connection. Let's stop searching. */ + chosen = check; + break; + } /* loop over connection bundle */ + + if(chosen) { + /* mark it as used before releasing the lock */ + Curl_attach_connection(data, chosen); + CONNCACHE_UNLOCK(data); + *usethis = chosen; + return TRUE; /* yes, we found one to use! */ + } + CONNCACHE_UNLOCK(data); + + if(foundPendingCandidate && data->set.pipewait) { + infof(data, + "Found pending candidate for reuse and CURLOPT_PIPEWAIT is set"); + *waitpipe = TRUE; + } + + return FALSE; /* no matching connecting exists */ +} + +/* + * verboseconnect() displays verbose information after a connect + */ +#ifndef CURL_DISABLE_VERBOSE_STRINGS +void Curl_verboseconnect(struct Curl_easy *data, + struct connectdata *conn, int sockindex) +{ + if(data->set.verbose && sockindex == SECONDARYSOCKET) + infof(data, "Connected 2nd connection to %s port %u", + conn->secondary.remote_ip, conn->secondary.remote_port); + else + infof(data, "Connected to %s (%s) port %u", + CURL_CONN_HOST_DISPNAME(conn), conn->primary.remote_ip, + conn->primary.remote_port); +} +#endif + +/* + * Allocate and initialize a new connectdata object. + */ +static struct connectdata *allocate_conn(struct Curl_easy *data) +{ + struct connectdata *conn = calloc(1, sizeof(struct connectdata)); + if(!conn) + return NULL; + + /* and we setup a few fields in case we end up actually using this struct */ + + conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */ + conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */ + conn->sockfd = CURL_SOCKET_BAD; + conn->writesockfd = CURL_SOCKET_BAD; + conn->connection_id = -1; /* no ID */ + conn->primary.remote_port = -1; /* unknown at this point */ + conn->remote_port = -1; /* unknown at this point */ + + /* Default protocol-independent behavior doesn't support persistent + connections, so we set this to force-close. Protocols that support + this need to set this to FALSE in their "curl_do" functions. */ + connclose(conn, "Default to force-close"); + + /* Store creation time to help future close decision making */ + conn->created = Curl_now(); + + /* Store current time to give a baseline to keepalive connection times. */ + conn->keepalive = conn->created; + +#ifndef CURL_DISABLE_PROXY + conn->http_proxy.proxytype = data->set.proxytype; + conn->socks_proxy.proxytype = CURLPROXY_SOCKS4; + + /* note that these two proxy bits are now just on what looks to be + requested, they may be altered down the road */ + conn->bits.proxy = (data->set.str[STRING_PROXY] && + *data->set.str[STRING_PROXY]) ? TRUE : FALSE; + conn->bits.httpproxy = (conn->bits.proxy && + (conn->http_proxy.proxytype == CURLPROXY_HTTP || + conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0 || + IS_HTTPS_PROXY(conn->http_proxy.proxytype))) ? + TRUE : FALSE; + conn->bits.socksproxy = (conn->bits.proxy && + !conn->bits.httpproxy) ? TRUE : FALSE; + + if(data->set.str[STRING_PRE_PROXY] && *data->set.str[STRING_PRE_PROXY]) { + conn->bits.proxy = TRUE; + conn->bits.socksproxy = TRUE; + } + + conn->bits.proxy_user_passwd = + (data->state.aptr.proxyuser) ? TRUE : FALSE; + conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy; +#endif /* CURL_DISABLE_PROXY */ + +#ifndef CURL_DISABLE_FTP + conn->bits.ftp_use_epsv = data->set.ftp_use_epsv; + conn->bits.ftp_use_eprt = data->set.ftp_use_eprt; +#endif + conn->ip_version = data->set.ipver; + conn->connect_only = data->set.connect_only; + conn->transport = TRNSPRT_TCP; /* most of them are TCP streams */ + + /* Initialize the easy handle list */ + Curl_llist_init(&conn->easyq, NULL); + +#ifdef HAVE_GSSAPI + conn->data_prot = PROT_CLEAR; +#endif + + /* Store the local bind parameters that will be used for this connection */ + if(data->set.str[STRING_DEVICE]) { + conn->localdev = strdup(data->set.str[STRING_DEVICE]); + if(!conn->localdev) + goto error; + } +#ifndef CURL_DISABLE_BINDLOCAL + conn->localportrange = data->set.localportrange; + conn->localport = data->set.localport; +#endif + + /* the close socket stuff needs to be copied to the connection struct as + it may live on without (this specific) Curl_easy */ + conn->fclosesocket = data->set.fclosesocket; + conn->closesocket_client = data->set.closesocket_client; + conn->lastused = conn->created; + conn->gssapi_delegation = data->set.gssapi_delegation; + + return conn; +error: + + free(conn->localdev); + free(conn); + return NULL; +} + +const struct Curl_handler *Curl_get_scheme_handler(const char *scheme) +{ + return Curl_getn_scheme_handler(scheme, strlen(scheme)); +} + +/* returns the handler if the given scheme is built-in */ +const struct Curl_handler *Curl_getn_scheme_handler(const char *scheme, + size_t len) +{ + /* table generated by schemetable.c: + 1. gcc schemetable.c && ./a.out + 2. check how small the table gets + 3. tweak the hash algorithm, then rerun from 1 + 4. when the table is good enough + 5. copy the table into this source code + 6. make sure this function uses the same hash function that worked for + schemetable.c + 7. if needed, adjust the #ifdefs in schemetable.c and rerun + */ + static const struct Curl_handler * const protocols[67] = { +#ifndef CURL_DISABLE_FILE + &Curl_handler_file, +#else + NULL, +#endif + NULL, NULL, +#if defined(USE_SSL) && !defined(CURL_DISABLE_GOPHER) + &Curl_handler_gophers, +#else + NULL, +#endif + NULL, +#ifdef USE_LIBRTMP + &Curl_handler_rtmpe, +#else + NULL, +#endif +#ifndef CURL_DISABLE_SMTP + &Curl_handler_smtp, +#else + NULL, +#endif +#if defined(USE_SSH) + &Curl_handler_sftp, +#else + NULL, +#endif +#if !defined(CURL_DISABLE_SMB) && defined(USE_CURL_NTLM_CORE) && \ + (SIZEOF_CURL_OFF_T > 4) + &Curl_handler_smb, +#else + NULL, +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_SMTP) + &Curl_handler_smtps, +#else + NULL, +#endif +#ifndef CURL_DISABLE_TELNET + &Curl_handler_telnet, +#else + NULL, +#endif +#ifndef CURL_DISABLE_GOPHER + &Curl_handler_gopher, +#else + NULL, +#endif +#ifndef CURL_DISABLE_TFTP + &Curl_handler_tftp, +#else + NULL, +#endif + NULL, NULL, NULL, +#if defined(USE_SSL) && !defined(CURL_DISABLE_FTP) + &Curl_handler_ftps, +#else + NULL, +#endif +#ifndef CURL_DISABLE_HTTP + &Curl_handler_http, +#else + NULL, +#endif +#ifndef CURL_DISABLE_IMAP + &Curl_handler_imap, +#else + NULL, +#endif +#ifdef USE_LIBRTMP + &Curl_handler_rtmps, +#else + NULL, +#endif +#ifdef USE_LIBRTMP + &Curl_handler_rtmpt, +#else + NULL, +#endif + NULL, NULL, NULL, +#if !defined(CURL_DISABLE_LDAP) && \ + !defined(CURL_DISABLE_LDAPS) && \ + ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \ + (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL))) + &Curl_handler_ldaps, +#else + NULL, +#endif +#if defined(USE_WEBSOCKETS) && \ + defined(USE_SSL) && !defined(CURL_DISABLE_HTTP) + &Curl_handler_wss, +#else + NULL, +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP) + &Curl_handler_https, +#else + NULL, +#endif + NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, +#ifndef CURL_DISABLE_RTSP + &Curl_handler_rtsp, +#else + NULL, +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_SMB) && \ + defined(USE_CURL_NTLM_CORE) && (SIZEOF_CURL_OFF_T > 4) + &Curl_handler_smbs, +#else + NULL, +#endif +#if defined(USE_SSH) && !defined(USE_WOLFSSH) + &Curl_handler_scp, +#else + NULL, +#endif + NULL, NULL, NULL, +#ifndef CURL_DISABLE_POP3 + &Curl_handler_pop3, +#else + NULL, +#endif + NULL, NULL, +#ifdef USE_LIBRTMP + &Curl_handler_rtmp, +#else + NULL, +#endif + NULL, NULL, NULL, +#ifdef USE_LIBRTMP + &Curl_handler_rtmpte, +#else + NULL, +#endif + NULL, NULL, NULL, +#ifndef CURL_DISABLE_DICT + &Curl_handler_dict, +#else + NULL, +#endif + NULL, NULL, NULL, +#ifndef CURL_DISABLE_MQTT + &Curl_handler_mqtt, +#else + NULL, +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_POP3) + &Curl_handler_pop3s, +#else + NULL, +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_IMAP) + &Curl_handler_imaps, +#else + NULL, +#endif + NULL, +#if defined(USE_WEBSOCKETS) && !defined(CURL_DISABLE_HTTP) + &Curl_handler_ws, +#else + NULL, +#endif + NULL, +#ifdef USE_LIBRTMP + &Curl_handler_rtmpts, +#else + NULL, +#endif +#ifndef CURL_DISABLE_LDAP + &Curl_handler_ldap, +#else + NULL, +#endif + NULL, NULL, +#ifndef CURL_DISABLE_FTP + &Curl_handler_ftp, +#else + NULL, +#endif + }; + + if(len && (len <= 7)) { + const char *s = scheme; + size_t l = len; + const struct Curl_handler *h; + unsigned int c = 978; + while(l) { + c <<= 5; + c += Curl_raw_tolower(*s); + s++; + l--; + } + + h = protocols[c % 67]; + if(h && strncasecompare(scheme, h->scheme, len) && !h->scheme[len]) + return h; + } + return NULL; +} + +static CURLcode findprotocol(struct Curl_easy *data, + struct connectdata *conn, + const char *protostr) +{ + const struct Curl_handler *p = Curl_get_scheme_handler(protostr); + + if(p && /* Protocol found in table. Check if allowed */ + (data->set.allowed_protocols & p->protocol)) { + + /* it is allowed for "normal" request, now do an extra check if this is + the result of a redirect */ + if(data->state.this_is_a_follow && + !(data->set.redir_protocols & p->protocol)) + /* nope, get out */ + ; + else { + /* Perform setup complement if some. */ + conn->handler = conn->given = p; + /* 'port' and 'remote_port' are set in setup_connection_internals() */ + return CURLE_OK; + } + } + + /* The protocol was not found in the table, but we don't have to assign it + to anything since it is already assigned to a dummy-struct in the + create_conn() function when the connectdata struct is allocated. */ + failf(data, "Protocol \"%s\" %s%s", protostr, + p ? "disabled" : "not supported", + data->state.this_is_a_follow ? " (in redirect)":""); + + return CURLE_UNSUPPORTED_PROTOCOL; +} + + +CURLcode Curl_uc_to_curlcode(CURLUcode uc) +{ + switch(uc) { + default: + return CURLE_URL_MALFORMAT; + case CURLUE_UNSUPPORTED_SCHEME: + return CURLE_UNSUPPORTED_PROTOCOL; + case CURLUE_OUT_OF_MEMORY: + return CURLE_OUT_OF_MEMORY; + case CURLUE_USER_NOT_ALLOWED: + return CURLE_LOGIN_DENIED; + } +} + +#ifdef USE_IPV6 +/* + * If the URL was set with an IPv6 numerical address with a zone id part, set + * the scope_id based on that! + */ + +static void zonefrom_url(CURLU *uh, struct Curl_easy *data, + struct connectdata *conn) +{ + char *zoneid; + CURLUcode uc = curl_url_get(uh, CURLUPART_ZONEID, &zoneid, 0); +#ifdef CURL_DISABLE_VERBOSE_STRINGS + (void)data; +#endif + + if(!uc && zoneid) { + char *endp; + unsigned long scope = strtoul(zoneid, &endp, 10); + if(!*endp && (scope < UINT_MAX)) + /* A plain number, use it directly as a scope id. */ + conn->scope_id = (unsigned int)scope; +#if defined(HAVE_IF_NAMETOINDEX) + else { +#elif defined(_WIN32) + else if(Curl_if_nametoindex) { +#endif + +#if defined(HAVE_IF_NAMETOINDEX) || defined(_WIN32) + /* Zone identifier is not numeric */ + unsigned int scopeidx = 0; +#if defined(_WIN32) + scopeidx = Curl_if_nametoindex(zoneid); +#else + scopeidx = if_nametoindex(zoneid); +#endif + if(!scopeidx) { +#ifndef CURL_DISABLE_VERBOSE_STRINGS + char buffer[STRERROR_LEN]; + infof(data, "Invalid zoneid: %s; %s", zoneid, + Curl_strerror(errno, buffer, sizeof(buffer))); +#endif + } + else + conn->scope_id = scopeidx; + } +#endif /* HAVE_IF_NAMETOINDEX || _WIN32 */ + + free(zoneid); + } +} +#else +#define zonefrom_url(a,b,c) Curl_nop_stmt +#endif + +/* + * Parse URL and fill in the relevant members of the connection struct. + */ +static CURLcode parseurlandfillconn(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result; + CURLU *uh; + CURLUcode uc; + char *hostname; + bool use_set_uh = (data->set.uh && !data->state.this_is_a_follow); + + up_free(data); /* cleanup previous leftovers first */ + + /* parse the URL */ + if(use_set_uh) { + uh = data->state.uh = curl_url_dup(data->set.uh); + } + else { + uh = data->state.uh = curl_url(); + } + + if(!uh) + return CURLE_OUT_OF_MEMORY; + + if(data->set.str[STRING_DEFAULT_PROTOCOL] && + !Curl_is_absolute_url(data->state.url, NULL, 0, TRUE)) { + char *url = aprintf("%s://%s", data->set.str[STRING_DEFAULT_PROTOCOL], + data->state.url); + if(!url) + return CURLE_OUT_OF_MEMORY; + if(data->state.url_alloc) + free(data->state.url); + data->state.url = url; + data->state.url_alloc = TRUE; + } + + if(!use_set_uh) { + char *newurl; + uc = curl_url_set(uh, CURLUPART_URL, data->state.url, + CURLU_GUESS_SCHEME | + CURLU_NON_SUPPORT_SCHEME | + (data->set.disallow_username_in_url ? + CURLU_DISALLOW_USER : 0) | + (data->set.path_as_is ? CURLU_PATH_AS_IS : 0)); + if(uc) { + failf(data, "URL rejected: %s", curl_url_strerror(uc)); + return Curl_uc_to_curlcode(uc); + } + + /* after it was parsed, get the generated normalized version */ + uc = curl_url_get(uh, CURLUPART_URL, &newurl, 0); + if(uc) + return Curl_uc_to_curlcode(uc); + if(data->state.url_alloc) + free(data->state.url); + data->state.url = newurl; + data->state.url_alloc = TRUE; + } + + uc = curl_url_get(uh, CURLUPART_SCHEME, &data->state.up.scheme, 0); + if(uc) + return Curl_uc_to_curlcode(uc); + + uc = curl_url_get(uh, CURLUPART_HOST, &data->state.up.hostname, 0); + if(uc) { + if(!strcasecompare("file", data->state.up.scheme)) + return CURLE_OUT_OF_MEMORY; + } + else if(strlen(data->state.up.hostname) > MAX_URL_LEN) { + failf(data, "Too long host name (maximum is %d)", MAX_URL_LEN); + return CURLE_URL_MALFORMAT; + } + hostname = data->state.up.hostname; + + if(hostname && hostname[0] == '[') { + /* This looks like an IPv6 address literal. See if there is an address + scope. */ + size_t hlen; + conn->bits.ipv6_ip = TRUE; + /* cut off the brackets! */ + hostname++; + hlen = strlen(hostname); + hostname[hlen - 1] = 0; + + zonefrom_url(uh, data, conn); + } + + /* make sure the connect struct gets its own copy of the host name */ + conn->host.rawalloc = strdup(hostname ? hostname : ""); + if(!conn->host.rawalloc) + return CURLE_OUT_OF_MEMORY; + conn->host.name = conn->host.rawalloc; + + /************************************************************* + * IDN-convert the hostnames + *************************************************************/ + result = Curl_idnconvert_hostname(&conn->host); + if(result) + return result; + +#ifndef CURL_DISABLE_HSTS + /* HSTS upgrade */ + if(data->hsts && strcasecompare("http", data->state.up.scheme)) { + /* This MUST use the IDN decoded name */ + if(Curl_hsts(data->hsts, conn->host.name, TRUE)) { + char *url; + Curl_safefree(data->state.up.scheme); + uc = curl_url_set(uh, CURLUPART_SCHEME, "https", 0); + if(uc) + return Curl_uc_to_curlcode(uc); + if(data->state.url_alloc) + Curl_safefree(data->state.url); + /* after update, get the updated version */ + uc = curl_url_get(uh, CURLUPART_URL, &url, 0); + if(uc) + return Curl_uc_to_curlcode(uc); + uc = curl_url_get(uh, CURLUPART_SCHEME, &data->state.up.scheme, 0); + if(uc) { + free(url); + return Curl_uc_to_curlcode(uc); + } + data->state.url = url; + data->state.url_alloc = TRUE; + infof(data, "Switched from HTTP to HTTPS due to HSTS => %s", + data->state.url); + } + } +#endif + + result = findprotocol(data, conn, data->state.up.scheme); + if(result) + return result; + + /* + * User name and password set with their own options override the + * credentials possibly set in the URL. + */ + if(!data->set.str[STRING_PASSWORD]) { + uc = curl_url_get(uh, CURLUPART_PASSWORD, &data->state.up.password, 0); + if(!uc) { + char *decoded; + result = Curl_urldecode(data->state.up.password, 0, &decoded, NULL, + conn->handler->flags&PROTOPT_USERPWDCTRL ? + REJECT_ZERO : REJECT_CTRL); + if(result) + return result; + conn->passwd = decoded; + result = Curl_setstropt(&data->state.aptr.passwd, decoded); + if(result) + return result; + } + else if(uc != CURLUE_NO_PASSWORD) + return Curl_uc_to_curlcode(uc); + } + + if(!data->set.str[STRING_USERNAME]) { + /* we don't use the URL API's URL decoder option here since it rejects + control codes and we want to allow them for some schemes in the user + and password fields */ + uc = curl_url_get(uh, CURLUPART_USER, &data->state.up.user, 0); + if(!uc) { + char *decoded; + result = Curl_urldecode(data->state.up.user, 0, &decoded, NULL, + conn->handler->flags&PROTOPT_USERPWDCTRL ? + REJECT_ZERO : REJECT_CTRL); + if(result) + return result; + conn->user = decoded; + result = Curl_setstropt(&data->state.aptr.user, decoded); + } + else if(uc != CURLUE_NO_USER) + return Curl_uc_to_curlcode(uc); + else if(data->state.aptr.passwd) { + /* no user was set but a password, set a blank user */ + result = Curl_setstropt(&data->state.aptr.user, ""); + } + if(result) + return result; + } + + uc = curl_url_get(uh, CURLUPART_OPTIONS, &data->state.up.options, + CURLU_URLDECODE); + if(!uc) { + conn->options = strdup(data->state.up.options); + if(!conn->options) + return CURLE_OUT_OF_MEMORY; + } + else if(uc != CURLUE_NO_OPTIONS) + return Curl_uc_to_curlcode(uc); + + uc = curl_url_get(uh, CURLUPART_PATH, &data->state.up.path, + CURLU_URLENCODE); + if(uc) + return Curl_uc_to_curlcode(uc); + + uc = curl_url_get(uh, CURLUPART_PORT, &data->state.up.port, + CURLU_DEFAULT_PORT); + if(uc) { + if(!strcasecompare("file", data->state.up.scheme)) + return CURLE_OUT_OF_MEMORY; + } + else { + unsigned long port = strtoul(data->state.up.port, NULL, 10); + conn->primary.remote_port = conn->remote_port = + (data->set.use_port && data->state.allow_port) ? + data->set.use_port : curlx_ultous(port); + } + + (void)curl_url_get(uh, CURLUPART_QUERY, &data->state.up.query, 0); + +#ifdef USE_IPV6 + if(data->set.scope_id) + /* Override any scope that was set above. */ + conn->scope_id = data->set.scope_id; +#endif + + return CURLE_OK; +} + + +/* + * If we're doing a resumed transfer, we need to setup our stuff + * properly. + */ +static CURLcode setup_range(struct Curl_easy *data) +{ + struct UrlState *s = &data->state; + s->resume_from = data->set.set_resume_from; + if(s->resume_from || data->set.str[STRING_SET_RANGE]) { + if(s->rangestringalloc) + free(s->range); + + if(s->resume_from) + s->range = aprintf("%" CURL_FORMAT_CURL_OFF_T "-", s->resume_from); + else + s->range = strdup(data->set.str[STRING_SET_RANGE]); + + s->rangestringalloc = (s->range) ? TRUE : FALSE; + + if(!s->range) + return CURLE_OUT_OF_MEMORY; + + /* tell ourselves to fetch this range */ + s->use_range = TRUE; /* enable range download */ + } + else + s->use_range = FALSE; /* disable range download */ + + return CURLE_OK; +} + + +/* + * setup_connection_internals() - + * + * Setup connection internals specific to the requested protocol in the + * Curl_easy. This is inited and setup before the connection is made but + * is about the particular protocol that is to be used. + * + * This MUST get called after proxy magic has been figured out. + */ +static CURLcode setup_connection_internals(struct Curl_easy *data, + struct connectdata *conn) +{ + const struct Curl_handler *p; + CURLcode result; + + /* Perform setup complement if some. */ + p = conn->handler; + + if(p->setup_connection) { + result = (*p->setup_connection)(data, conn); + + if(result) + return result; + + p = conn->handler; /* May have changed. */ + } + + if(conn->primary.remote_port < 0) + /* we check for -1 here since if proxy was detected already, this + was very likely already set to the proxy port */ + conn->primary.remote_port = p->defport; + + return CURLE_OK; +} + + +#ifndef CURL_DISABLE_PROXY + +#ifndef CURL_DISABLE_HTTP +/**************************************************************** +* Detect what (if any) proxy to use. Remember that this selects a host +* name and is not limited to HTTP proxies only. +* The returned pointer must be freed by the caller (unless NULL) +****************************************************************/ +static char *detect_proxy(struct Curl_easy *data, + struct connectdata *conn) +{ + char *proxy = NULL; + + /* If proxy was not specified, we check for default proxy environment + * variables, to enable i.e Lynx compliance: + * + * http_proxy=http://some.server.dom:port/ + * https_proxy=http://some.server.dom:port/ + * ftp_proxy=http://some.server.dom:port/ + * no_proxy=domain1.dom,host.domain2.dom + * (a comma-separated list of hosts which should + * not be proxied, or an asterisk to override + * all proxy variables) + * all_proxy=http://some.server.dom:port/ + * (seems to exist for the CERN www lib. Probably + * the first to check for.) + * + * For compatibility, the all-uppercase versions of these variables are + * checked if the lowercase versions don't exist. + */ + char proxy_env[20]; + char *envp = proxy_env; +#ifdef CURL_DISABLE_VERBOSE_STRINGS + (void)data; +#endif + + msnprintf(proxy_env, sizeof(proxy_env), "%s_proxy", conn->handler->scheme); + + /* read the protocol proxy: */ + proxy = curl_getenv(proxy_env); + + /* + * We don't try the uppercase version of HTTP_PROXY because of + * security reasons: + * + * When curl is used in a webserver application + * environment (cgi or php), this environment variable can + * be controlled by the web server user by setting the + * http header 'Proxy:' to some value. + * + * This can cause 'internal' http/ftp requests to be + * arbitrarily redirected by any external attacker. + */ + if(!proxy && !strcasecompare("http_proxy", proxy_env)) { + /* There was no lowercase variable, try the uppercase version: */ + Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env)); + proxy = curl_getenv(proxy_env); + } + + if(!proxy) { +#ifdef USE_WEBSOCKETS + /* websocket proxy fallbacks */ + if(strcasecompare("ws_proxy", proxy_env)) { + proxy = curl_getenv("http_proxy"); + } + else if(strcasecompare("wss_proxy", proxy_env)) { + proxy = curl_getenv("https_proxy"); + if(!proxy) + proxy = curl_getenv("HTTPS_PROXY"); + } + if(!proxy) { +#endif + envp = (char *)"all_proxy"; + proxy = curl_getenv(envp); /* default proxy to use */ + if(!proxy) { + envp = (char *)"ALL_PROXY"; + proxy = curl_getenv(envp); + } +#ifdef USE_WEBSOCKETS + } +#endif + } + if(proxy) + infof(data, "Uses proxy env variable %s == '%s'", envp, proxy); + + return proxy; +} +#endif /* CURL_DISABLE_HTTP */ + +/* + * If this is supposed to use a proxy, we need to figure out the proxy + * host name, so that we can reuse an existing connection + * that may exist registered to the same proxy host. + */ +static CURLcode parse_proxy(struct Curl_easy *data, + struct connectdata *conn, char *proxy, + curl_proxytype proxytype) +{ + char *portptr = NULL; + int port = -1; + char *proxyuser = NULL; + char *proxypasswd = NULL; + char *host = NULL; + bool sockstype; + CURLUcode uc; + struct proxy_info *proxyinfo; + CURLU *uhp = curl_url(); + CURLcode result = CURLE_OK; + char *scheme = NULL; +#ifdef USE_UNIX_SOCKETS + char *path = NULL; + bool is_unix_proxy = FALSE; +#endif + + + if(!uhp) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + /* When parsing the proxy, allowing non-supported schemes since we have + these made up ones for proxies. Guess scheme for URLs without it. */ + uc = curl_url_set(uhp, CURLUPART_URL, proxy, + CURLU_NON_SUPPORT_SCHEME|CURLU_GUESS_SCHEME); + if(!uc) { + /* parsed okay as a URL */ + uc = curl_url_get(uhp, CURLUPART_SCHEME, &scheme, 0); + if(uc) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + if(strcasecompare("https", scheme)) { + if(proxytype != CURLPROXY_HTTPS2) + proxytype = CURLPROXY_HTTPS; + else + proxytype = CURLPROXY_HTTPS2; + } + else if(strcasecompare("socks5h", scheme)) + proxytype = CURLPROXY_SOCKS5_HOSTNAME; + else if(strcasecompare("socks5", scheme)) + proxytype = CURLPROXY_SOCKS5; + else if(strcasecompare("socks4a", scheme)) + proxytype = CURLPROXY_SOCKS4A; + else if(strcasecompare("socks4", scheme) || + strcasecompare("socks", scheme)) + proxytype = CURLPROXY_SOCKS4; + else if(strcasecompare("http", scheme)) + ; /* leave it as HTTP or HTTP/1.0 */ + else { + /* Any other xxx:// reject! */ + failf(data, "Unsupported proxy scheme for \'%s\'", proxy); + result = CURLE_COULDNT_CONNECT; + goto error; + } + } + else { + failf(data, "Unsupported proxy syntax in \'%s\': %s", proxy, + curl_url_strerror(uc)); + result = CURLE_COULDNT_RESOLVE_PROXY; + goto error; + } + +#ifdef USE_SSL + if(!Curl_ssl_supports(data, SSLSUPP_HTTPS_PROXY)) +#endif + if(IS_HTTPS_PROXY(proxytype)) { + failf(data, "Unsupported proxy \'%s\', libcurl is built without the " + "HTTPS-proxy support.", proxy); + result = CURLE_NOT_BUILT_IN; + goto error; + } + + sockstype = + proxytype == CURLPROXY_SOCKS5_HOSTNAME || + proxytype == CURLPROXY_SOCKS5 || + proxytype == CURLPROXY_SOCKS4A || + proxytype == CURLPROXY_SOCKS4; + + proxyinfo = sockstype ? &conn->socks_proxy : &conn->http_proxy; + proxyinfo->proxytype = (unsigned char)proxytype; + + /* Is there a username and password given in this proxy url? */ + uc = curl_url_get(uhp, CURLUPART_USER, &proxyuser, CURLU_URLDECODE); + if(uc && (uc != CURLUE_NO_USER)) + goto error; + uc = curl_url_get(uhp, CURLUPART_PASSWORD, &proxypasswd, CURLU_URLDECODE); + if(uc && (uc != CURLUE_NO_PASSWORD)) + goto error; + + if(proxyuser || proxypasswd) { + Curl_safefree(proxyinfo->user); + proxyinfo->user = proxyuser; + result = Curl_setstropt(&data->state.aptr.proxyuser, proxyuser); + proxyuser = NULL; + if(result) + goto error; + Curl_safefree(proxyinfo->passwd); + if(!proxypasswd) { + proxypasswd = strdup(""); + if(!proxypasswd) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + } + proxyinfo->passwd = proxypasswd; + result = Curl_setstropt(&data->state.aptr.proxypasswd, proxypasswd); + proxypasswd = NULL; + if(result) + goto error; + conn->bits.proxy_user_passwd = TRUE; /* enable it */ + } + + (void)curl_url_get(uhp, CURLUPART_PORT, &portptr, 0); + + if(portptr) { + port = (int)strtol(portptr, NULL, 10); + free(portptr); + } + else { + if(data->set.proxyport) + /* None given in the proxy string, then get the default one if it is + given */ + port = (int)data->set.proxyport; + else { + if(IS_HTTPS_PROXY(proxytype)) + port = CURL_DEFAULT_HTTPS_PROXY_PORT; + else + port = CURL_DEFAULT_PROXY_PORT; + } + } + if(port >= 0) { + proxyinfo->port = port; + if(conn->primary.remote_port < 0 || sockstype || + !conn->socks_proxy.host.rawalloc) + conn->primary.remote_port = port; + } + + /* now, clone the proxy host name */ + uc = curl_url_get(uhp, CURLUPART_HOST, &host, CURLU_URLDECODE); + if(uc) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } +#ifdef USE_UNIX_SOCKETS + if(sockstype && strcasecompare(UNIX_SOCKET_PREFIX, host)) { + uc = curl_url_get(uhp, CURLUPART_PATH, &path, CURLU_URLDECODE); + if(uc) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + /* path will be "/", if no path was found */ + if(strcmp("/", path)) { + is_unix_proxy = TRUE; + free(host); + host = aprintf(UNIX_SOCKET_PREFIX"%s", path); + if(!host) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + Curl_safefree(proxyinfo->host.rawalloc); + proxyinfo->host.rawalloc = host; + proxyinfo->host.name = host; + host = NULL; + } + } + + if(!is_unix_proxy) { +#endif + Curl_safefree(proxyinfo->host.rawalloc); + proxyinfo->host.rawalloc = host; + if(host[0] == '[') { + /* this is a numerical IPv6, strip off the brackets */ + size_t len = strlen(host); + host[len-1] = 0; /* clear the trailing bracket */ + host++; + zonefrom_url(uhp, data, conn); + } + proxyinfo->host.name = host; + host = NULL; +#ifdef USE_UNIX_SOCKETS + } +#endif + +error: + free(proxyuser); + free(proxypasswd); + free(host); + free(scheme); +#ifdef USE_UNIX_SOCKETS + free(path); +#endif + curl_url_cleanup(uhp); + return result; +} + +/* + * Extract the user and password from the authentication string + */ +static CURLcode parse_proxy_auth(struct Curl_easy *data, + struct connectdata *conn) +{ + const char *proxyuser = data->state.aptr.proxyuser ? + data->state.aptr.proxyuser : ""; + const char *proxypasswd = data->state.aptr.proxypasswd ? + data->state.aptr.proxypasswd : ""; + CURLcode result = CURLE_OUT_OF_MEMORY; + + conn->http_proxy.user = strdup(proxyuser); + if(conn->http_proxy.user) { + conn->http_proxy.passwd = strdup(proxypasswd); + if(conn->http_proxy.passwd) + result = CURLE_OK; + else + Curl_safefree(conn->http_proxy.user); + } + return result; +} + +/* create_conn helper to parse and init proxy values. to be called after unix + socket init but before any proxy vars are evaluated. */ +static CURLcode create_conn_helper_init_proxy(struct Curl_easy *data, + struct connectdata *conn) +{ + char *proxy = NULL; + char *socksproxy = NULL; + char *no_proxy = NULL; + CURLcode result = CURLE_OK; + bool spacesep = FALSE; + + /************************************************************* + * Extract the user and password from the authentication string + *************************************************************/ + if(conn->bits.proxy_user_passwd) { + result = parse_proxy_auth(data, conn); + if(result) + goto out; + } + + /************************************************************* + * Detect what (if any) proxy to use + *************************************************************/ + if(data->set.str[STRING_PROXY]) { + proxy = strdup(data->set.str[STRING_PROXY]); + /* if global proxy is set, this is it */ + if(!proxy) { + failf(data, "memory shortage"); + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + + if(data->set.str[STRING_PRE_PROXY]) { + socksproxy = strdup(data->set.str[STRING_PRE_PROXY]); + /* if global socks proxy is set, this is it */ + if(!socksproxy) { + failf(data, "memory shortage"); + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + + if(!data->set.str[STRING_NOPROXY]) { + const char *p = "no_proxy"; + no_proxy = curl_getenv(p); + if(!no_proxy) { + p = "NO_PROXY"; + no_proxy = curl_getenv(p); + } + if(no_proxy) { + infof(data, "Uses proxy env variable %s == '%s'", p, no_proxy); + } + } + + if(Curl_check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY] ? + data->set.str[STRING_NOPROXY] : no_proxy, + &spacesep)) { + Curl_safefree(proxy); + Curl_safefree(socksproxy); + } +#ifndef CURL_DISABLE_HTTP + else if(!proxy && !socksproxy) + /* if the host is not in the noproxy list, detect proxy. */ + proxy = detect_proxy(data, conn); +#endif /* CURL_DISABLE_HTTP */ + if(spacesep) + infof(data, "space-separated NOPROXY patterns are deprecated"); + + Curl_safefree(no_proxy); + +#ifdef USE_UNIX_SOCKETS + /* For the time being do not mix proxy and unix domain sockets. See #1274 */ + if(proxy && conn->unix_domain_socket) { + free(proxy); + proxy = NULL; + } +#endif + + if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) { + free(proxy); /* Don't bother with an empty proxy string or if the + protocol doesn't work with network */ + proxy = NULL; + } + if(socksproxy && (!*socksproxy || + (conn->handler->flags & PROTOPT_NONETWORK))) { + free(socksproxy); /* Don't bother with an empty socks proxy string or if + the protocol doesn't work with network */ + socksproxy = NULL; + } + + /*********************************************************************** + * If this is supposed to use a proxy, we need to figure out the proxy host + * name, proxy type and port number, so that we can reuse an existing + * connection that may exist registered to the same proxy host. + ***********************************************************************/ + if(proxy || socksproxy) { + curl_proxytype ptype = (curl_proxytype)conn->http_proxy.proxytype; + if(proxy) { + result = parse_proxy(data, conn, proxy, ptype); + Curl_safefree(proxy); /* parse_proxy copies the proxy string */ + if(result) + goto out; + } + + if(socksproxy) { + result = parse_proxy(data, conn, socksproxy, ptype); + /* parse_proxy copies the socks proxy string */ + Curl_safefree(socksproxy); + if(result) + goto out; + } + + if(conn->http_proxy.host.rawalloc) { +#ifdef CURL_DISABLE_HTTP + /* asking for an HTTP proxy is a bit funny when HTTP is disabled... */ + result = CURLE_UNSUPPORTED_PROTOCOL; + goto out; +#else + /* force this connection's protocol to become HTTP if compatible */ + if(!(conn->handler->protocol & PROTO_FAMILY_HTTP)) { + if((conn->handler->flags & PROTOPT_PROXY_AS_HTTP) && + !conn->bits.tunnel_proxy) + conn->handler = &Curl_handler_http; + else + /* if not converting to HTTP over the proxy, enforce tunneling */ + conn->bits.tunnel_proxy = TRUE; + } + conn->bits.httpproxy = TRUE; +#endif + } + else { + conn->bits.httpproxy = FALSE; /* not an HTTP proxy */ + conn->bits.tunnel_proxy = FALSE; /* no tunneling if not HTTP */ + } + + if(conn->socks_proxy.host.rawalloc) { + if(!conn->http_proxy.host.rawalloc) { + /* once a socks proxy */ + if(!conn->socks_proxy.user) { + conn->socks_proxy.user = conn->http_proxy.user; + conn->http_proxy.user = NULL; + Curl_safefree(conn->socks_proxy.passwd); + conn->socks_proxy.passwd = conn->http_proxy.passwd; + conn->http_proxy.passwd = NULL; + } + } + conn->bits.socksproxy = TRUE; + } + else + conn->bits.socksproxy = FALSE; /* not a socks proxy */ + } + else { + conn->bits.socksproxy = FALSE; + conn->bits.httpproxy = FALSE; + } + conn->bits.proxy = conn->bits.httpproxy || conn->bits.socksproxy; + + if(!conn->bits.proxy) { + /* we aren't using the proxy after all... */ + conn->bits.proxy = FALSE; + conn->bits.httpproxy = FALSE; + conn->bits.socksproxy = FALSE; + conn->bits.proxy_user_passwd = FALSE; + conn->bits.tunnel_proxy = FALSE; + /* CURLPROXY_HTTPS does not have its own flag in conn->bits, yet we need + to signal that CURLPROXY_HTTPS is not used for this connection */ + conn->http_proxy.proxytype = CURLPROXY_HTTP; + } + +out: + + free(socksproxy); + free(proxy); + return result; +} +#endif /* CURL_DISABLE_PROXY */ + +/* + * Curl_parse_login_details() + * + * This is used to parse a login string for user name, password and options in + * the following formats: + * + * user + * user:password + * user:password;options + * user;options + * user;options:password + * :password + * :password;options + * ;options + * ;options:password + * + * Parameters: + * + * login [in] - login string. + * len [in] - length of the login string. + * userp [in/out] - address where a pointer to newly allocated memory + * holding the user will be stored upon completion. + * passwdp [in/out] - address where a pointer to newly allocated memory + * holding the password will be stored upon completion. + * optionsp [in/out] - OPTIONAL address where a pointer to newly allocated + * memory holding the options will be stored upon + * completion. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_parse_login_details(const char *login, const size_t len, + char **userp, char **passwdp, + char **optionsp) +{ + char *ubuf = NULL; + char *pbuf = NULL; + const char *psep = NULL; + const char *osep = NULL; + size_t ulen; + size_t plen; + size_t olen; + + DEBUGASSERT(userp); + DEBUGASSERT(passwdp); + + /* Attempt to find the password separator */ + psep = memchr(login, ':', len); + + /* Attempt to find the options separator */ + if(optionsp) + osep = memchr(login, ';', len); + + /* Calculate the portion lengths */ + ulen = (psep ? + (size_t)(osep && psep > osep ? osep - login : psep - login) : + (osep ? (size_t)(osep - login) : len)); + plen = (psep ? + (osep && osep > psep ? (size_t)(osep - psep) : + (size_t)(login + len - psep)) - 1 : 0); + olen = (osep ? + (psep && psep > osep ? (size_t)(psep - osep) : + (size_t)(login + len - osep)) - 1 : 0); + + /* Clone the user portion buffer, which can be zero length */ + ubuf = Curl_memdup0(login, ulen); + if(!ubuf) + goto error; + + /* Clone the password portion buffer */ + if(psep) { + pbuf = Curl_memdup0(&psep[1], plen); + if(!pbuf) + goto error; + } + + /* Allocate the options portion buffer */ + if(optionsp) { + char *obuf = NULL; + if(olen) { + obuf = Curl_memdup0(&osep[1], olen); + if(!obuf) + goto error; + } + *optionsp = obuf; + } + *userp = ubuf; + *passwdp = pbuf; + return CURLE_OK; +error: + free(ubuf); + free(pbuf); + return CURLE_OUT_OF_MEMORY; +} + +/************************************************************* + * Figure out the remote port number and fix it in the URL + * + * No matter if we use a proxy or not, we have to figure out the remote + * port number of various reasons. + * + * The port number embedded in the URL is replaced, if necessary. + *************************************************************/ +static CURLcode parse_remote_port(struct Curl_easy *data, + struct connectdata *conn) +{ + + if(data->set.use_port && data->state.allow_port) { + /* if set, we use this instead of the port possibly given in the URL */ + char portbuf[16]; + CURLUcode uc; + conn->remote_port = data->set.use_port; + msnprintf(portbuf, sizeof(portbuf), "%d", conn->remote_port); + uc = curl_url_set(data->state.uh, CURLUPART_PORT, portbuf, 0); + if(uc) + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} + +/* + * Override the login details from the URL with that in the CURLOPT_USERPWD + * option or a .netrc file, if applicable. + */ +static CURLcode override_login(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLUcode uc; + char **userp = &conn->user; + char **passwdp = &conn->passwd; + char **optionsp = &conn->options; + + if(data->set.str[STRING_OPTIONS]) { + free(*optionsp); + *optionsp = strdup(data->set.str[STRING_OPTIONS]); + if(!*optionsp) + return CURLE_OUT_OF_MEMORY; + } + +#ifndef CURL_DISABLE_NETRC + if(data->set.use_netrc == CURL_NETRC_REQUIRED) { + Curl_safefree(*userp); + Curl_safefree(*passwdp); + } + conn->bits.netrc = FALSE; + if(data->set.use_netrc && !data->set.str[STRING_USERNAME]) { + int ret; + bool url_provided = FALSE; + + if(data->state.aptr.user) { + /* there was a user name in the URL. Use the URL decoded version */ + userp = &data->state.aptr.user; + url_provided = TRUE; + } + + ret = Curl_parsenetrc(conn->host.name, + userp, passwdp, + data->set.str[STRING_NETRC_FILE]); + if(ret > 0) { + infof(data, "Couldn't find host %s in the %s file; using defaults", + conn->host.name, + (data->set.str[STRING_NETRC_FILE] ? + data->set.str[STRING_NETRC_FILE] : ".netrc")); + } + else if(ret < 0) { + failf(data, ".netrc parser error"); + return CURLE_READ_ERROR; + } + else { + /* set bits.netrc TRUE to remember that we got the name from a .netrc + file, so that it is safe to use even if we followed a Location: to a + different host or similar. */ + conn->bits.netrc = TRUE; + } + if(url_provided) { + Curl_safefree(conn->user); + conn->user = strdup(*userp); + if(!conn->user) + return CURLE_OUT_OF_MEMORY; + } + /* no user was set but a password, set a blank user */ + if(!*userp && *passwdp) { + *userp = strdup(""); + if(!*userp) + return CURLE_OUT_OF_MEMORY; + } + } +#endif + + /* for updated strings, we update them in the URL */ + if(*userp) { + CURLcode result; + if(data->state.aptr.user != *userp) { + /* nothing to do then */ + result = Curl_setstropt(&data->state.aptr.user, *userp); + if(result) + return result; + } + } + if(data->state.aptr.user) { + uc = curl_url_set(data->state.uh, CURLUPART_USER, data->state.aptr.user, + CURLU_URLENCODE); + if(uc) + return Curl_uc_to_curlcode(uc); + if(!*userp) { + *userp = strdup(data->state.aptr.user); + if(!*userp) + return CURLE_OUT_OF_MEMORY; + } + } + if(*passwdp) { + CURLcode result = Curl_setstropt(&data->state.aptr.passwd, *passwdp); + if(result) + return result; + } + if(data->state.aptr.passwd) { + uc = curl_url_set(data->state.uh, CURLUPART_PASSWORD, + data->state.aptr.passwd, CURLU_URLENCODE); + if(uc) + return Curl_uc_to_curlcode(uc); + if(!*passwdp) { + *passwdp = strdup(data->state.aptr.passwd); + if(!*passwdp) + return CURLE_OUT_OF_MEMORY; + } + } + + return CURLE_OK; +} + +/* + * Set the login details so they're available in the connection + */ +static CURLcode set_login(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + const char *setuser = CURL_DEFAULT_USER; + const char *setpasswd = CURL_DEFAULT_PASSWORD; + + /* If our protocol needs a password and we have none, use the defaults */ + if((conn->handler->flags & PROTOPT_NEEDSPWD) && !data->state.aptr.user) + ; + else { + setuser = ""; + setpasswd = ""; + } + /* Store the default user */ + if(!conn->user) { + conn->user = strdup(setuser); + if(!conn->user) + return CURLE_OUT_OF_MEMORY; + } + + /* Store the default password */ + if(!conn->passwd) { + conn->passwd = strdup(setpasswd); + if(!conn->passwd) + result = CURLE_OUT_OF_MEMORY; + } + + return result; +} + +/* + * Parses a "host:port" string to connect to. + * The hostname and the port may be empty; in this case, NULL is returned for + * the hostname and -1 for the port. + */ +static CURLcode parse_connect_to_host_port(struct Curl_easy *data, + const char *host, + char **hostname_result, + int *port_result) +{ + char *host_dup; + char *hostptr; + char *host_portno; + char *portptr; + int port = -1; + CURLcode result = CURLE_OK; + +#if defined(CURL_DISABLE_VERBOSE_STRINGS) + (void) data; +#endif + + *hostname_result = NULL; + *port_result = -1; + + if(!host || !*host) + return CURLE_OK; + + host_dup = strdup(host); + if(!host_dup) + return CURLE_OUT_OF_MEMORY; + + hostptr = host_dup; + + /* start scanning for port number at this point */ + portptr = hostptr; + + /* detect and extract RFC6874-style IPv6-addresses */ + if(*hostptr == '[') { +#ifdef USE_IPV6 + char *ptr = ++hostptr; /* advance beyond the initial bracket */ + while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.'))) + ptr++; + if(*ptr == '%') { + /* There might be a zone identifier */ + if(strncmp("%25", ptr, 3)) + infof(data, "Please URL encode %% as %%25, see RFC 6874."); + ptr++; + /* Allow unreserved characters as defined in RFC 3986 */ + while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') || + (*ptr == '.') || (*ptr == '_') || (*ptr == '~'))) + ptr++; + } + if(*ptr == ']') + /* yeps, it ended nicely with a bracket as well */ + *ptr++ = '\0'; + else + infof(data, "Invalid IPv6 address format"); + portptr = ptr; + /* Note that if this didn't end with a bracket, we still advanced the + * hostptr first, but I can't see anything wrong with that as no host + * name nor a numeric can legally start with a bracket. + */ +#else + failf(data, "Use of IPv6 in *_CONNECT_TO without IPv6 support built-in"); + result = CURLE_NOT_BUILT_IN; + goto error; +#endif + } + + /* Get port number off server.com:1080 */ + host_portno = strchr(portptr, ':'); + if(host_portno) { + char *endp = NULL; + *host_portno = '\0'; /* cut off number from host name */ + host_portno++; + if(*host_portno) { + long portparse = strtol(host_portno, &endp, 10); + if((endp && *endp) || (portparse < 0) || (portparse > 65535)) { + failf(data, "No valid port number in connect to host string (%s)", + host_portno); + result = CURLE_SETOPT_OPTION_SYNTAX; + goto error; + } + else + port = (int)portparse; /* we know it will fit */ + } + } + + /* now, clone the cleaned host name */ + DEBUGASSERT(hostptr); + *hostname_result = strdup(hostptr); + if(!*hostname_result) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + *port_result = port; + +error: + free(host_dup); + return result; +} + +/* + * Parses one "connect to" string in the form: + * "HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT". + */ +static CURLcode parse_connect_to_string(struct Curl_easy *data, + struct connectdata *conn, + const char *conn_to_host, + char **host_result, + int *port_result) +{ + CURLcode result = CURLE_OK; + const char *ptr = conn_to_host; + int host_match = FALSE; + int port_match = FALSE; + + *host_result = NULL; + *port_result = -1; + + if(*ptr == ':') { + /* an empty hostname always matches */ + host_match = TRUE; + ptr++; + } + else { + /* check whether the URL's hostname matches */ + size_t hostname_to_match_len; + char *hostname_to_match = aprintf("%s%s%s", + conn->bits.ipv6_ip ? "[" : "", + conn->host.name, + conn->bits.ipv6_ip ? "]" : ""); + if(!hostname_to_match) + return CURLE_OUT_OF_MEMORY; + hostname_to_match_len = strlen(hostname_to_match); + host_match = strncasecompare(ptr, hostname_to_match, + hostname_to_match_len); + free(hostname_to_match); + ptr += hostname_to_match_len; + + host_match = host_match && *ptr == ':'; + ptr++; + } + + if(host_match) { + if(*ptr == ':') { + /* an empty port always matches */ + port_match = TRUE; + ptr++; + } + else { + /* check whether the URL's port matches */ + char *ptr_next = strchr(ptr, ':'); + if(ptr_next) { + char *endp = NULL; + long port_to_match = strtol(ptr, &endp, 10); + if((endp == ptr_next) && (port_to_match == conn->remote_port)) { + port_match = TRUE; + ptr = ptr_next + 1; + } + } + } + } + + if(host_match && port_match) { + /* parse the hostname and port to connect to */ + result = parse_connect_to_host_port(data, ptr, host_result, port_result); + } + + return result; +} + +/* + * Processes all strings in the "connect to" slist, and uses the "connect + * to host" and "connect to port" of the first string that matches. + */ +static CURLcode parse_connect_to_slist(struct Curl_easy *data, + struct connectdata *conn, + struct curl_slist *conn_to_host) +{ + CURLcode result = CURLE_OK; + char *host = NULL; + int port = -1; + + while(conn_to_host && !host && port == -1) { + result = parse_connect_to_string(data, conn, conn_to_host->data, + &host, &port); + if(result) + return result; + + if(host && *host) { + conn->conn_to_host.rawalloc = host; + conn->conn_to_host.name = host; + conn->bits.conn_to_host = TRUE; + + infof(data, "Connecting to hostname: %s", host); + } + else { + /* no "connect to host" */ + conn->bits.conn_to_host = FALSE; + Curl_safefree(host); + } + + if(port >= 0) { + conn->conn_to_port = port; + conn->bits.conn_to_port = TRUE; + infof(data, "Connecting to port: %d", port); + } + else { + /* no "connect to port" */ + conn->bits.conn_to_port = FALSE; + port = -1; + } + + conn_to_host = conn_to_host->next; + } + +#ifndef CURL_DISABLE_ALTSVC + if(data->asi && !host && (port == -1) && + ((conn->handler->protocol == CURLPROTO_HTTPS) || +#ifdef CURLDEBUG + /* allow debug builds to circumvent the HTTPS restriction */ + getenv("CURL_ALTSVC_HTTP") +#else + 0 +#endif + )) { + /* no connect_to match, try alt-svc! */ + enum alpnid srcalpnid; + bool hit; + struct altsvc *as; + const int allowed_versions = ( ALPN_h1 +#ifdef USE_HTTP2 + | ALPN_h2 +#endif +#ifdef USE_HTTP3 + | ALPN_h3 +#endif + ) & data->asi->flags; + + host = conn->host.rawalloc; +#ifdef USE_HTTP2 + /* with h2 support, check that first */ + srcalpnid = ALPN_h2; + hit = Curl_altsvc_lookup(data->asi, + srcalpnid, host, conn->remote_port, /* from */ + &as /* to */, + allowed_versions); + if(!hit) +#endif + { + srcalpnid = ALPN_h1; + hit = Curl_altsvc_lookup(data->asi, + srcalpnid, host, conn->remote_port, /* from */ + &as /* to */, + allowed_versions); + } + if(hit) { + char *hostd = strdup((char *)as->dst.host); + if(!hostd) + return CURLE_OUT_OF_MEMORY; + conn->conn_to_host.rawalloc = hostd; + conn->conn_to_host.name = hostd; + conn->bits.conn_to_host = TRUE; + conn->conn_to_port = as->dst.port; + conn->bits.conn_to_port = TRUE; + conn->bits.altused = TRUE; + infof(data, "Alt-svc connecting from [%s]%s:%d to [%s]%s:%d", + Curl_alpnid2str(srcalpnid), host, conn->remote_port, + Curl_alpnid2str(as->dst.alpnid), hostd, as->dst.port); + if(srcalpnid != as->dst.alpnid) { + /* protocol version switch */ + switch(as->dst.alpnid) { + case ALPN_h1: + conn->httpversion = 11; + break; + case ALPN_h2: + conn->httpversion = 20; + break; + case ALPN_h3: + conn->transport = TRNSPRT_QUIC; + conn->httpversion = 30; + break; + default: /* shouldn't be possible */ + break; + } + } + } + } +#endif + + return result; +} + +#ifdef USE_UNIX_SOCKETS +static CURLcode resolve_unix(struct Curl_easy *data, + struct connectdata *conn, + char *unix_path) +{ + struct Curl_dns_entry *hostaddr = NULL; + bool longpath = FALSE; + + DEBUGASSERT(unix_path); + DEBUGASSERT(conn->dns_entry == NULL); + + /* Unix domain sockets are local. The host gets ignored, just use the + * specified domain socket address. Do not cache "DNS entries". There is + * no DNS involved and we already have the filesystem path available. */ + hostaddr = calloc(1, sizeof(struct Curl_dns_entry)); + if(!hostaddr) + return CURLE_OUT_OF_MEMORY; + + hostaddr->addr = Curl_unix2addr(unix_path, &longpath, + conn->bits.abstract_unix_socket); + if(!hostaddr->addr) { + if(longpath) + /* Long paths are not supported for now */ + failf(data, "Unix socket path too long: '%s'", unix_path); + free(hostaddr); + return longpath ? CURLE_COULDNT_RESOLVE_HOST : CURLE_OUT_OF_MEMORY; + } + + hostaddr->inuse++; + conn->dns_entry = hostaddr; + return CURLE_OK; +} +#endif + +#ifndef CURL_DISABLE_PROXY +static CURLcode resolve_proxy(struct Curl_easy *data, + struct connectdata *conn, + bool *async) +{ + struct Curl_dns_entry *hostaddr = NULL; + struct hostname *host; + timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE); + int rc; + + DEBUGASSERT(conn->dns_entry == NULL); + + host = conn->bits.socksproxy ? &conn->socks_proxy.host : + &conn->http_proxy.host; + + conn->hostname_resolve = strdup(host->name); + if(!conn->hostname_resolve) + return CURLE_OUT_OF_MEMORY; + + rc = Curl_resolv_timeout(data, conn->hostname_resolve, + conn->primary.remote_port, &hostaddr, timeout_ms); + conn->dns_entry = hostaddr; + if(rc == CURLRESOLV_PENDING) + *async = TRUE; + else if(rc == CURLRESOLV_TIMEDOUT) + return CURLE_OPERATION_TIMEDOUT; + else if(!hostaddr) { + failf(data, "Couldn't resolve proxy '%s'", host->dispname); + return CURLE_COULDNT_RESOLVE_PROXY; + } + + return CURLE_OK; +} +#endif + +static CURLcode resolve_host(struct Curl_easy *data, + struct connectdata *conn, + bool *async) +{ + struct Curl_dns_entry *hostaddr = NULL; + struct hostname *connhost; + timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE); + int rc; + + DEBUGASSERT(conn->dns_entry == NULL); + + connhost = conn->bits.conn_to_host ? &conn->conn_to_host : &conn->host; + + /* If not connecting via a proxy, extract the port from the URL, if it is + * there, thus overriding any defaults that might have been set above. */ + conn->primary.remote_port = conn->bits.conn_to_port ? conn->conn_to_port : + conn->remote_port; + + /* Resolve target host right on */ + conn->hostname_resolve = strdup(connhost->name); + if(!conn->hostname_resolve) + return CURLE_OUT_OF_MEMORY; + + rc = Curl_resolv_timeout(data, conn->hostname_resolve, + conn->primary.remote_port, &hostaddr, timeout_ms); + conn->dns_entry = hostaddr; + if(rc == CURLRESOLV_PENDING) + *async = TRUE; + else if(rc == CURLRESOLV_TIMEDOUT) { + failf(data, "Failed to resolve host '%s' with timeout after %" + CURL_FORMAT_TIMEDIFF_T " ms", connhost->dispname, + Curl_timediff(Curl_now(), data->progress.t_startsingle)); + return CURLE_OPERATION_TIMEDOUT; + } + else if(!hostaddr) { + failf(data, "Could not resolve host: %s", connhost->dispname); + return CURLE_COULDNT_RESOLVE_HOST; + } + + return CURLE_OK; +} + +/* Perform a fresh resolve */ +static CURLcode resolve_fresh(struct Curl_easy *data, + struct connectdata *conn, + bool *async) +{ +#ifdef USE_UNIX_SOCKETS + char *unix_path = conn->unix_domain_socket; + +#ifndef CURL_DISABLE_PROXY + if(!unix_path && conn->socks_proxy.host.name && + !strncmp(UNIX_SOCKET_PREFIX"/", + conn->socks_proxy.host.name, sizeof(UNIX_SOCKET_PREFIX))) + unix_path = conn->socks_proxy.host.name + sizeof(UNIX_SOCKET_PREFIX) - 1; +#endif + + if(unix_path) { + conn->transport = TRNSPRT_UNIX; + return resolve_unix(data, conn, unix_path); + } +#endif + +#ifndef CURL_DISABLE_PROXY + if(CONN_IS_PROXIED(conn)) + return resolve_proxy(data, conn, async); +#endif + + return resolve_host(data, conn, async); +} + +/************************************************************* + * Resolve the address of the server or proxy + *************************************************************/ +static CURLcode resolve_server(struct Curl_easy *data, + struct connectdata *conn, + bool *async) +{ + DEBUGASSERT(conn); + DEBUGASSERT(data); + + /* Resolve the name of the server or proxy */ + if(conn->bits.reuse) { + /* We're reusing the connection - no need to resolve anything, and + idnconvert_hostname() was called already in create_conn() for the reuse + case. */ + *async = FALSE; + return CURLE_OK; + } + + return resolve_fresh(data, conn, async); +} + +/* + * Cleanup the connection `temp`, just allocated for `data`, before using the + * previously `existing` one for `data`. All relevant info is copied over + * and `temp` is freed. + */ +static void reuse_conn(struct Curl_easy *data, + struct connectdata *temp, + struct connectdata *existing) +{ + /* get the user+password information from the temp struct since it may + * be new for this request even when we reuse an existing connection */ + if(temp->user) { + /* use the new user name and password though */ + Curl_safefree(existing->user); + Curl_safefree(existing->passwd); + existing->user = temp->user; + existing->passwd = temp->passwd; + temp->user = NULL; + temp->passwd = NULL; + } + +#ifndef CURL_DISABLE_PROXY + existing->bits.proxy_user_passwd = temp->bits.proxy_user_passwd; + if(existing->bits.proxy_user_passwd) { + /* use the new proxy user name and proxy password though */ + Curl_safefree(existing->http_proxy.user); + Curl_safefree(existing->socks_proxy.user); + Curl_safefree(existing->http_proxy.passwd); + Curl_safefree(existing->socks_proxy.passwd); + existing->http_proxy.user = temp->http_proxy.user; + existing->socks_proxy.user = temp->socks_proxy.user; + existing->http_proxy.passwd = temp->http_proxy.passwd; + existing->socks_proxy.passwd = temp->socks_proxy.passwd; + temp->http_proxy.user = NULL; + temp->socks_proxy.user = NULL; + temp->http_proxy.passwd = NULL; + temp->socks_proxy.passwd = NULL; + } +#endif + + /* Finding a connection for reuse in the cache matches, among other + * things on the "remote-relevant" hostname. This is not necessarily + * the authority of the URL, e.g. conn->host. For example: + * - we use a proxy (not tunneling). we want to send all requests + * that use the same proxy on this connection. + * - we have a "connect-to" setting that may redirect the hostname of + * a new request to the same remote endpoint of an existing conn. + * We want to reuse an existing conn to the remote endpoint. + * Since connection reuse does not match on conn->host necessarily, we + * switch `existing` conn to `temp` conn's host settings. + * TODO: is this correct in the case of TLS connections that have + * used the original hostname in SNI to negotiate? Do we send + * requests for another host through the different SNI? + */ + Curl_free_idnconverted_hostname(&existing->host); + Curl_free_idnconverted_hostname(&existing->conn_to_host); + Curl_safefree(existing->host.rawalloc); + Curl_safefree(existing->conn_to_host.rawalloc); + existing->host = temp->host; + temp->host.rawalloc = NULL; + temp->host.encalloc = NULL; + existing->conn_to_host = temp->conn_to_host; + temp->conn_to_host.rawalloc = NULL; + existing->conn_to_port = temp->conn_to_port; + existing->remote_port = temp->remote_port; + Curl_safefree(existing->hostname_resolve); + + existing->hostname_resolve = temp->hostname_resolve; + temp->hostname_resolve = NULL; + + /* reuse init */ + existing->bits.reuse = TRUE; /* yes, we're reusing here */ + + conn_free(data, temp); +} + +/** + * create_conn() sets up a new connectdata struct, or reuses an already + * existing one, and resolves host name. + * + * if this function returns CURLE_OK and *async is set to TRUE, the resolve + * response will be coming asynchronously. If *async is FALSE, the name is + * already resolved. + * + * @param data The sessionhandle pointer + * @param in_connect is set to the next connection data pointer + * @param async is set TRUE when an async DNS resolution is pending + * @see Curl_setup_conn() + * + */ + +static CURLcode create_conn(struct Curl_easy *data, + struct connectdata **in_connect, + bool *async) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn; + struct connectdata *existing = NULL; + bool reuse; + bool connections_available = TRUE; + bool force_reuse = FALSE; + bool waitpipe = FALSE; + size_t max_host_connections = Curl_multi_max_host_connections(data->multi); + size_t max_total_connections = Curl_multi_max_total_connections(data->multi); + + *async = FALSE; + *in_connect = NULL; + + /************************************************************* + * Check input data + *************************************************************/ + if(!data->state.url) { + result = CURLE_URL_MALFORMAT; + goto out; + } + + /* First, split up the current URL in parts so that we can use the + parts for checking against the already present connections. In order + to not have to modify everything at once, we allocate a temporary + connection data struct and fill in for comparison purposes. */ + conn = allocate_conn(data); + + if(!conn) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + /* We must set the return variable as soon as possible, so that our + parent can cleanup any possible allocs we may have done before + any failure */ + *in_connect = conn; + + result = parseurlandfillconn(data, conn); + if(result) + goto out; + + if(data->set.str[STRING_SASL_AUTHZID]) { + conn->sasl_authzid = strdup(data->set.str[STRING_SASL_AUTHZID]); + if(!conn->sasl_authzid) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + + if(data->set.str[STRING_BEARER]) { + conn->oauth_bearer = strdup(data->set.str[STRING_BEARER]); + if(!conn->oauth_bearer) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + +#ifdef USE_UNIX_SOCKETS + if(data->set.str[STRING_UNIX_SOCKET_PATH]) { + conn->unix_domain_socket = strdup(data->set.str[STRING_UNIX_SOCKET_PATH]); + if(!conn->unix_domain_socket) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + conn->bits.abstract_unix_socket = data->set.abstract_unix_socket; + } +#endif + + /* After the unix socket init but before the proxy vars are used, parse and + initialize the proxy vars */ +#ifndef CURL_DISABLE_PROXY + result = create_conn_helper_init_proxy(data, conn); + if(result) + goto out; + + /************************************************************* + * If the protocol is using SSL and HTTP proxy is used, we set + * the tunnel_proxy bit. + *************************************************************/ + if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy) + conn->bits.tunnel_proxy = TRUE; +#endif + + /************************************************************* + * Figure out the remote port number and fix it in the URL + *************************************************************/ + result = parse_remote_port(data, conn); + if(result) + goto out; + + /* Check for overridden login details and set them accordingly so that + they are known when protocol->setup_connection is called! */ + result = override_login(data, conn); + if(result) + goto out; + + result = set_login(data, conn); /* default credentials */ + if(result) + goto out; + + /************************************************************* + * Process the "connect to" linked list of hostname/port mappings. + * Do this after the remote port number has been fixed in the URL. + *************************************************************/ + result = parse_connect_to_slist(data, conn, data->set.connect_to); + if(result) + goto out; + + /************************************************************* + * IDN-convert the proxy hostnames + *************************************************************/ +#ifndef CURL_DISABLE_PROXY + if(conn->bits.httpproxy) { + result = Curl_idnconvert_hostname(&conn->http_proxy.host); + if(result) + return result; + } + if(conn->bits.socksproxy) { + result = Curl_idnconvert_hostname(&conn->socks_proxy.host); + if(result) + return result; + } +#endif + if(conn->bits.conn_to_host) { + result = Curl_idnconvert_hostname(&conn->conn_to_host); + if(result) + return result; + } + + /************************************************************* + * Check whether the host and the "connect to host" are equal. + * Do this after the hostnames have been IDN-converted. + *************************************************************/ + if(conn->bits.conn_to_host && + strcasecompare(conn->conn_to_host.name, conn->host.name)) { + conn->bits.conn_to_host = FALSE; + } + + /************************************************************* + * Check whether the port and the "connect to port" are equal. + * Do this after the remote port number has been fixed in the URL. + *************************************************************/ + if(conn->bits.conn_to_port && conn->conn_to_port == conn->remote_port) { + conn->bits.conn_to_port = FALSE; + } + +#ifndef CURL_DISABLE_PROXY + /************************************************************* + * If the "connect to" feature is used with an HTTP proxy, + * we set the tunnel_proxy bit. + *************************************************************/ + if((conn->bits.conn_to_host || conn->bits.conn_to_port) && + conn->bits.httpproxy) + conn->bits.tunnel_proxy = TRUE; +#endif + + /************************************************************* + * Setup internals depending on protocol. Needs to be done after + * we figured out what/if proxy to use. + *************************************************************/ + result = setup_connection_internals(data, conn); + if(result) + goto out; + + /*********************************************************************** + * file: is a special case in that it doesn't need a network connection + ***********************************************************************/ +#ifndef CURL_DISABLE_FILE + if(conn->handler->flags & PROTOPT_NONETWORK) { + bool done; + /* this is supposed to be the connect function so we better at least check + that the file is present here! */ + DEBUGASSERT(conn->handler->connect_it); + Curl_persistconninfo(data, conn, NULL); + result = conn->handler->connect_it(data, &done); + + /* Setup a "faked" transfer that'll do nothing */ + if(!result) { + Curl_attach_connection(data, conn); + result = Curl_conncache_add_conn(data); + if(result) + goto out; + + /* + * Setup whatever necessary for a resumed transfer + */ + result = setup_range(data); + if(result) { + DEBUGASSERT(conn->handler->done); + /* we ignore the return code for the protocol-specific DONE */ + (void)conn->handler->done(data, result, FALSE); + goto out; + } + Curl_xfer_setup(data, -1, -1, FALSE, -1); + } + + /* since we skip do_init() */ + Curl_init_do(data, conn); + + goto out; + } +#endif + + /* Setup filter for network connections */ + conn->recv[FIRSTSOCKET] = Curl_cf_recv; + conn->send[FIRSTSOCKET] = Curl_cf_send; + conn->recv[SECONDARYSOCKET] = Curl_cf_recv; + conn->send[SECONDARYSOCKET] = Curl_cf_send; + conn->bits.tcp_fastopen = data->set.tcp_fastopen; + + /* Complete the easy's SSL configuration for connection cache matching */ + result = Curl_ssl_easy_config_complete(data); + if(result) + goto out; + + prune_dead_connections(data); + + /************************************************************* + * Check the current list of connections to see if we can + * reuse an already existing one or if we have to create a + * new one. + *************************************************************/ + + DEBUGASSERT(conn->user); + DEBUGASSERT(conn->passwd); + + /* reuse_fresh is TRUE if we are told to use a new connection by force, but + we only acknowledge this option if this is not a reused connection + already (which happens due to follow-location or during an HTTP + authentication phase). CONNECT_ONLY transfers also refuse reuse. */ + if((data->set.reuse_fresh && !data->state.followlocation) || + data->set.connect_only) + reuse = FALSE; + else + reuse = ConnectionExists(data, conn, &existing, &force_reuse, &waitpipe); + + if(reuse) { + /* + * We already have a connection for this, we got the former connection in + * `existing` and thus we need to cleanup the one we just + * allocated before we can move along and use `existing`. + */ + reuse_conn(data, conn, existing); + conn = existing; + *in_connect = conn; + +#ifndef CURL_DISABLE_PROXY + infof(data, "Re-using existing connection with %s %s", + conn->bits.proxy?"proxy":"host", + conn->socks_proxy.host.name ? conn->socks_proxy.host.dispname : + conn->http_proxy.host.name ? conn->http_proxy.host.dispname : + conn->host.dispname); +#else + infof(data, "Re-using existing connection with host %s", + conn->host.dispname); +#endif + } + else { + /* We have decided that we want a new connection. However, we may not + be able to do that if we have reached the limit of how many + connections we are allowed to open. */ + + if(conn->handler->flags & PROTOPT_ALPN) { + /* The protocol wants it, so set the bits if enabled in the easy handle + (default) */ + if(data->set.ssl_enable_alpn) + conn->bits.tls_enable_alpn = TRUE; + } + + if(waitpipe) + /* There is a connection that *might* become usable for multiplexing + "soon", and we wait for that */ + connections_available = FALSE; + else { + /* this gets a lock on the conncache */ + struct connectbundle *bundle = + Curl_conncache_find_bundle(data, conn, data->state.conn_cache); + + if(max_host_connections > 0 && bundle && + (bundle->num_connections >= max_host_connections)) { + struct connectdata *conn_candidate; + + /* The bundle is full. Extract the oldest connection. */ + conn_candidate = Curl_conncache_extract_bundle(data, bundle); + CONNCACHE_UNLOCK(data); + + if(conn_candidate) + Curl_disconnect(data, conn_candidate, FALSE); + else { + infof(data, "No more connections allowed to host: %zu", + max_host_connections); + connections_available = FALSE; + } + } + else + CONNCACHE_UNLOCK(data); + + } + + if(connections_available && + (max_total_connections > 0) && + (Curl_conncache_size(data) >= max_total_connections)) { + struct connectdata *conn_candidate; + + /* The cache is full. Let's see if we can kill a connection. */ + conn_candidate = Curl_conncache_extract_oldest(data); + if(conn_candidate) + Curl_disconnect(data, conn_candidate, FALSE); + else { + infof(data, "No connections available in cache"); + connections_available = FALSE; + } + } + + if(!connections_available) { + infof(data, "No connections available."); + + conn_free(data, conn); + *in_connect = NULL; + + result = CURLE_NO_CONNECTION_AVAILABLE; + goto out; + } + else { + /* + * This is a brand new connection, so let's store it in the connection + * cache of ours! + */ + result = Curl_ssl_conn_config_init(data, conn); + if(result) { + DEBUGF(fprintf(stderr, "Error: init connection ssl config\n")); + goto out; + } + + Curl_attach_connection(data, conn); + result = Curl_conncache_add_conn(data); + if(result) + goto out; + } + +#if defined(USE_NTLM) + /* If NTLM is requested in a part of this connection, make sure we don't + assume the state is fine as this is a fresh connection and NTLM is + connection based. */ + if((data->state.authhost.picked & CURLAUTH_NTLM) && + data->state.authhost.done) { + infof(data, "NTLM picked AND auth done set, clear picked"); + data->state.authhost.picked = CURLAUTH_NONE; + data->state.authhost.done = FALSE; + } + + if((data->state.authproxy.picked & CURLAUTH_NTLM) && + data->state.authproxy.done) { + infof(data, "NTLM-proxy picked AND auth done set, clear picked"); + data->state.authproxy.picked = CURLAUTH_NONE; + data->state.authproxy.done = FALSE; + } +#endif + } + + /* Setup and init stuff before DO starts, in preparing for the transfer. */ + Curl_init_do(data, conn); + + /* + * Setup whatever necessary for a resumed transfer + */ + result = setup_range(data); + if(result) + goto out; + + /* Continue connectdata initialization here. */ + + /************************************************************* + * Resolve the address of the server or proxy + *************************************************************/ + result = resolve_server(data, conn, async); + if(result) + goto out; + + /* Everything general done, inform filters that they need + * to prepare for a data transfer. + */ + result = Curl_conn_ev_data_setup(data); + +out: + return result; +} + +/* Curl_setup_conn() is called after the name resolve initiated in + * create_conn() is all done. + * + * Curl_setup_conn() also handles reused connections + */ +CURLcode Curl_setup_conn(struct Curl_easy *data, + bool *protocol_done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + Curl_pgrsTime(data, TIMER_NAMELOOKUP); + + if(conn->handler->flags & PROTOPT_NONETWORK) { + /* nothing to setup when not using a network */ + *protocol_done = TRUE; + return result; + } + +#ifndef CURL_DISABLE_PROXY + /* set proxy_connect_closed to false unconditionally already here since it + is used strictly to provide extra information to a parent function in the + case of proxy CONNECT failures and we must make sure we don't have it + lingering set from a previous invoke */ + conn->bits.proxy_connect_closed = FALSE; +#endif + +#ifdef CURL_DO_LINEEND_CONV + data->state.crlf_conversions = 0; /* reset CRLF conversion counter */ +#endif /* CURL_DO_LINEEND_CONV */ + + /* set start time here for timeout purposes in the connect procedure, it + is later set again for the progress meter purpose */ + conn->now = Curl_now(); + if(!conn->bits.reuse) + result = Curl_conn_setup(data, conn, FIRSTSOCKET, conn->dns_entry, + CURL_CF_SSL_DEFAULT); + if(!result) + result = Curl_headers_init(data); + + /* not sure we need this flag to be passed around any more */ + *protocol_done = FALSE; + return result; +} + +CURLcode Curl_connect(struct Curl_easy *data, + bool *asyncp, + bool *protocol_done) +{ + CURLcode result; + struct connectdata *conn; + + *asyncp = FALSE; /* assume synchronous resolves by default */ + + /* Set the request to virgin state based on transfer settings */ + Curl_req_hard_reset(&data->req, data); + + /* call the stuff that needs to be called */ + result = create_conn(data, &conn, asyncp); + + if(!result) { + if(CONN_INUSE(conn) > 1) + /* multiplexed */ + *protocol_done = TRUE; + else if(!*asyncp) { + /* DNS resolution is done: that's either because this is a reused + connection, in which case DNS was unnecessary, or because DNS + really did finish already (synch resolver/fast async resolve) */ + result = Curl_setup_conn(data, protocol_done); + } + } + + if(result == CURLE_NO_CONNECTION_AVAILABLE) { + return result; + } + else if(result && conn) { + /* We're not allowed to return failure with memory left allocated in the + connectdata struct, free those here */ + Curl_detach_connection(data); + Curl_conncache_remove_conn(data, conn, TRUE); + Curl_disconnect(data, conn, TRUE); + } + + return result; +} + +/* + * Curl_init_do() inits the readwrite session. This is inited each time (in + * the DO function before the protocol-specific DO functions are invoked) for + * a transfer, sometimes multiple times on the same Curl_easy. Make sure + * nothing in here depends on stuff that are setup dynamically for the + * transfer. + * + * Allow this function to get called with 'conn' set to NULL. + */ + +CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn) +{ + /* if this is a pushed stream, we need this: */ + CURLcode result; + + if(conn) { + conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to + use */ + /* if the protocol used doesn't support wildcards, switch it off */ + if(data->state.wildcardmatch && + !(conn->handler->flags & PROTOPT_WILDCARD)) + data->state.wildcardmatch = FALSE; + } + + data->state.done = FALSE; /* *_done() is not called yet */ + + if(data->req.no_body) + /* in HTTP lingo, no body means using the HEAD request... */ + data->state.httpreq = HTTPREQ_HEAD; + + result = Curl_req_start(&data->req, data); + if(!result) { + Curl_speedinit(data); + Curl_pgrsSetUploadCounter(data, 0); + Curl_pgrsSetDownloadCounter(data, 0); + } + return result; +} + +#if defined(USE_HTTP2) || defined(USE_HTTP3) + +#ifdef USE_NGHTTP2 + +static void priority_remove_child(struct Curl_easy *parent, + struct Curl_easy *child) +{ + struct Curl_data_prio_node **pnext = &parent->set.priority.children; + struct Curl_data_prio_node *pnode = parent->set.priority.children; + + DEBUGASSERT(child->set.priority.parent == parent); + while(pnode && pnode->data != child) { + pnext = &pnode->next; + pnode = pnode->next; + } + + DEBUGASSERT(pnode); + if(pnode) { + *pnext = pnode->next; + free(pnode); + } + + child->set.priority.parent = 0; + child->set.priority.exclusive = FALSE; +} + +CURLcode Curl_data_priority_add_child(struct Curl_easy *parent, + struct Curl_easy *child, + bool exclusive) +{ + if(child->set.priority.parent) { + priority_remove_child(child->set.priority.parent, child); + } + + if(parent) { + struct Curl_data_prio_node **tail; + struct Curl_data_prio_node *pnode; + + pnode = calloc(1, sizeof(*pnode)); + if(!pnode) + return CURLE_OUT_OF_MEMORY; + pnode->data = child; + + if(parent->set.priority.children && exclusive) { + /* exclusive: move all existing children underneath the new child */ + struct Curl_data_prio_node *node = parent->set.priority.children; + while(node) { + node->data->set.priority.parent = child; + node = node->next; + } + + tail = &child->set.priority.children; + while(*tail) + tail = &(*tail)->next; + + DEBUGASSERT(!*tail); + *tail = parent->set.priority.children; + parent->set.priority.children = 0; + } + + tail = &parent->set.priority.children; + while(*tail) { + (*tail)->data->set.priority.exclusive = FALSE; + tail = &(*tail)->next; + } + + DEBUGASSERT(!*tail); + *tail = pnode; + } + + child->set.priority.parent = parent; + child->set.priority.exclusive = exclusive; + return CURLE_OK; +} + +#endif /* USE_NGHTTP2 */ + +#ifdef USE_NGHTTP2 +static void data_priority_cleanup(struct Curl_easy *data) +{ + while(data->set.priority.children) { + struct Curl_easy *tmp = data->set.priority.children->data; + priority_remove_child(data, tmp); + if(data->set.priority.parent) + Curl_data_priority_add_child(data->set.priority.parent, tmp, FALSE); + } + + if(data->set.priority.parent) + priority_remove_child(data->set.priority.parent, data); +} +#endif + +void Curl_data_priority_clear_state(struct Curl_easy *data) +{ + memset(&data->state.priority, 0, sizeof(data->state.priority)); +} + +#endif /* defined(USE_HTTP2) || defined(USE_HTTP3) */ diff --git a/third_party/curl/lib/url.h b/third_party/curl/lib/url.h new file mode 100644 index 0000000..198a00a --- /dev/null +++ b/third_party/curl/lib/url.h @@ -0,0 +1,81 @@ +#ifndef HEADER_CURL_URL_H +#define HEADER_CURL_URL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* + * Prototypes for library-wide functions provided by url.c + */ + +CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn); +CURLcode Curl_open(struct Curl_easy **curl); +CURLcode Curl_init_userdefined(struct Curl_easy *data); + +void Curl_freeset(struct Curl_easy *data); +CURLcode Curl_uc_to_curlcode(CURLUcode uc); +CURLcode Curl_close(struct Curl_easy **datap); /* opposite of curl_open() */ +CURLcode Curl_connect(struct Curl_easy *, bool *async, bool *protocol_connect); +void Curl_disconnect(struct Curl_easy *data, + struct connectdata *, bool dead_connection); +CURLcode Curl_setup_conn(struct Curl_easy *data, + bool *protocol_done); +CURLcode Curl_parse_login_details(const char *login, const size_t len, + char **userptr, char **passwdptr, + char **optionsptr); + +/* Get protocol handler for a URI scheme + * @param scheme URI scheme, case-insensitive + * @return NULL of handler not found + */ +const struct Curl_handler *Curl_get_scheme_handler(const char *scheme); +const struct Curl_handler *Curl_getn_scheme_handler(const char *scheme, + size_t len); + +#define CURL_DEFAULT_PROXY_PORT 1080 /* default proxy port unless specified */ +#define CURL_DEFAULT_HTTPS_PROXY_PORT 443 /* default https proxy port unless + specified */ + +#ifdef CURL_DISABLE_VERBOSE_STRINGS +#define Curl_verboseconnect(x,y,z) Curl_nop_stmt +#else +void Curl_verboseconnect(struct Curl_easy *data, struct connectdata *conn, + int sockindex); +#endif + +#if defined(USE_HTTP2) || defined(USE_HTTP3) +void Curl_data_priority_clear_state(struct Curl_easy *data); +#else +#define Curl_data_priority_clear_state(x) +#endif /* !(defined(USE_HTTP2) || defined(USE_HTTP3)) */ + +#ifdef USE_NGHTTP2 +CURLcode Curl_data_priority_add_child(struct Curl_easy *parent, + struct Curl_easy *child, + bool exclusive); +#else +#define Curl_data_priority_add_child(x, y, z) CURLE_NOT_BUILT_IN +#endif + +#endif /* HEADER_CURL_URL_H */ diff --git a/third_party/curl/lib/urlapi-int.h b/third_party/curl/lib/urlapi-int.h new file mode 100644 index 0000000..c40281a --- /dev/null +++ b/third_party/curl/lib/urlapi-int.h @@ -0,0 +1,38 @@ +#ifndef HEADER_CURL_URLAPI_INT_H +#define HEADER_CURL_URLAPI_INT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +size_t Curl_is_absolute_url(const char *url, char *buf, size_t buflen, + bool guess_scheme); + +CURLUcode Curl_url_set_authority(CURLU *u, const char *authority); + +#ifdef DEBUGBUILD +CURLUcode Curl_parse_port(struct Curl_URL *u, struct dynbuf *host, + bool has_scheme); +#endif + +#endif /* HEADER_CURL_URLAPI_INT_H */ diff --git a/third_party/curl/lib/urlapi.c b/third_party/curl/lib/urlapi.c new file mode 100644 index 0000000..eb03966 --- /dev/null +++ b/third_party/curl/lib/urlapi.c @@ -0,0 +1,1995 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "urldata.h" +#include "urlapi-int.h" +#include "strcase.h" +#include "url.h" +#include "escape.h" +#include "curl_ctype.h" +#include "inet_pton.h" +#include "inet_ntop.h" +#include "strdup.h" +#include "idn.h" +#include "curl_memrchr.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + /* MSDOS/Windows style drive prefix, eg c: in c:foo */ +#define STARTS_WITH_DRIVE_PREFIX(str) \ + ((('a' <= str[0] && str[0] <= 'z') || \ + ('A' <= str[0] && str[0] <= 'Z')) && \ + (str[1] == ':')) + + /* MSDOS/Windows style drive prefix, optionally with + * a '|' instead of ':', followed by a slash or NUL */ +#define STARTS_WITH_URL_DRIVE_PREFIX(str) \ + ((('a' <= (str)[0] && (str)[0] <= 'z') || \ + ('A' <= (str)[0] && (str)[0] <= 'Z')) && \ + ((str)[1] == ':' || (str)[1] == '|') && \ + ((str)[2] == '/' || (str)[2] == '\\' || (str)[2] == 0)) + +/* scheme is not URL encoded, the longest libcurl supported ones are... */ +#define MAX_SCHEME_LEN 40 + +/* + * If USE_IPV6 is disabled, we still want to parse IPv6 addresses, so make + * sure we have _some_ value for AF_INET6 without polluting our fake value + * everywhere. + */ +#if !defined(USE_IPV6) && !defined(AF_INET6) +#define AF_INET6 (AF_INET + 1) +#endif + +/* Internal representation of CURLU. Point to URL-encoded strings. */ +struct Curl_URL { + char *scheme; + char *user; + char *password; + char *options; /* IMAP only? */ + char *host; + char *zoneid; /* for numerical IPv6 addresses */ + char *port; + char *path; + char *query; + char *fragment; + unsigned short portnum; /* the numerical version (if 'port' is set) */ + BIT(query_present); /* to support blank */ + BIT(fragment_present); /* to support blank */ +}; + +#define DEFAULT_SCHEME "https" + +static void free_urlhandle(struct Curl_URL *u) +{ + free(u->scheme); + free(u->user); + free(u->password); + free(u->options); + free(u->host); + free(u->zoneid); + free(u->port); + free(u->path); + free(u->query); + free(u->fragment); +} + +/* + * Find the separator at the end of the host name, or the '?' in cases like + * http://www.example.com?id=2380 + */ +static const char *find_host_sep(const char *url) +{ + const char *sep; + const char *query; + + /* Find the start of the hostname */ + sep = strstr(url, "//"); + if(!sep) + sep = url; + else + sep += 2; + + query = strchr(sep, '?'); + sep = strchr(sep, '/'); + + if(!sep) + sep = url + strlen(url); + + if(!query) + query = url + strlen(url); + + return sep < query ? sep : query; +} + +/* convert CURLcode to CURLUcode */ +#define cc2cu(x) ((x) == CURLE_TOO_LARGE ? CURLUE_TOO_LARGE : \ + CURLUE_OUT_OF_MEMORY) +/* + * Decide whether a character in a URL must be escaped. + */ +#define urlchar_needs_escaping(c) (!(ISCNTRL(c) || ISSPACE(c) || ISGRAPH(c))) + +static const char hexdigits[] = "0123456789abcdef"; +/* urlencode_str() writes data into an output dynbuf and URL-encodes the + * spaces in the source URL accordingly. + * + * URL encoding should be skipped for host names, otherwise IDN resolution + * will fail. + */ +static CURLUcode urlencode_str(struct dynbuf *o, const char *url, + size_t len, bool relative, + bool query) +{ + /* we must add this with whitespace-replacing */ + bool left = !query; + const unsigned char *iptr; + const unsigned char *host_sep = (const unsigned char *) url; + CURLcode result; + + if(!relative) + host_sep = (const unsigned char *) find_host_sep(url); + + for(iptr = (unsigned char *)url; /* read from here */ + len; iptr++, len--) { + + if(iptr < host_sep) { + result = Curl_dyn_addn(o, iptr, 1); + if(result) + return cc2cu(result); + continue; + } + + if(*iptr == ' ') { + if(left) + result = Curl_dyn_addn(o, "%20", 3); + else + result = Curl_dyn_addn(o, "+", 1); + if(result) + return cc2cu(result); + continue; + } + + if(*iptr == '?') + left = FALSE; + + if(urlchar_needs_escaping(*iptr)) { + char out[3]={'%'}; + out[1] = hexdigits[*iptr>>4]; + out[2] = hexdigits[*iptr & 0xf]; + result = Curl_dyn_addn(o, out, 3); + } + else + result = Curl_dyn_addn(o, iptr, 1); + if(result) + return cc2cu(result); + } + + return CURLUE_OK; +} + +/* + * Returns the length of the scheme if the given URL is absolute (as opposed + * to relative). Stores the scheme in the buffer if TRUE and 'buf' is + * non-NULL. The buflen must be larger than MAX_SCHEME_LEN if buf is set. + * + * If 'guess_scheme' is TRUE, it means the URL might be provided without + * scheme. + */ +size_t Curl_is_absolute_url(const char *url, char *buf, size_t buflen, + bool guess_scheme) +{ + int i = 0; + DEBUGASSERT(!buf || (buflen > MAX_SCHEME_LEN)); + (void)buflen; /* only used in debug-builds */ + if(buf) + buf[0] = 0; /* always leave a defined value in buf */ +#ifdef _WIN32 + if(guess_scheme && STARTS_WITH_DRIVE_PREFIX(url)) + return 0; +#endif + if(ISALPHA(url[0])) + for(i = 1; i < MAX_SCHEME_LEN; ++i) { + char s = url[i]; + if(s && (ISALNUM(s) || (s == '+') || (s == '-') || (s == '.') )) { + /* RFC 3986 3.1 explains: + scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + */ + } + else { + break; + } + } + if(i && (url[i] == ':') && ((url[i + 1] == '/') || !guess_scheme)) { + /* If this does not guess scheme, the scheme always ends with the colon so + that this also detects data: URLs etc. In guessing mode, data: could + be the host name "data" with a specified port number. */ + + /* the length of the scheme is the name part only */ + size_t len = i; + if(buf) { + Curl_strntolower(buf, url, i); + buf[i] = 0; + } + return len; + } + return 0; +} + +/* + * Concatenate a relative URL to a base URL making it absolute. + * URL-encodes any spaces. + * The returned pointer must be freed by the caller unless NULL + * (returns NULL on out of memory). + * + * Note that this function destroys the 'base' string. + */ +static CURLcode concat_url(char *base, const char *relurl, char **newurl) +{ + /*** + TRY to append this new path to the old URL + to the right of the host part. Oh crap, this is doomed to cause + problems in the future... + */ + struct dynbuf newest; + char *protsep; + char *pathsep; + bool host_changed = FALSE; + const char *useurl = relurl; + CURLcode result = CURLE_OK; + CURLUcode uc; + bool skip_slash = FALSE; + *newurl = NULL; + + /* protsep points to the start of the host name */ + protsep = strstr(base, "//"); + if(!protsep) + protsep = base; + else + protsep += 2; /* pass the slashes */ + + if('/' != relurl[0]) { + int level = 0; + + /* First we need to find out if there's a ?-letter in the URL, + and cut it and the right-side of that off */ + pathsep = strchr(protsep, '?'); + if(pathsep) + *pathsep = 0; + + /* we have a relative path to append to the last slash if there's one + available, or the new URL is just a query string (starts with a '?') or + a fragment (starts with '#') we append the new one at the end of the + current URL */ + if((useurl[0] != '?') && (useurl[0] != '#')) { + pathsep = strrchr(protsep, '/'); + if(pathsep) + *pathsep = 0; + + /* Check if there's any slash after the host name, and if so, remember + that position instead */ + pathsep = strchr(protsep, '/'); + if(pathsep) + protsep = pathsep + 1; + else + protsep = NULL; + + /* now deal with one "./" or any amount of "../" in the newurl + and act accordingly */ + + if((useurl[0] == '.') && (useurl[1] == '/')) + useurl += 2; /* just skip the "./" */ + + while((useurl[0] == '.') && + (useurl[1] == '.') && + (useurl[2] == '/')) { + level++; + useurl += 3; /* pass the "../" */ + } + + if(protsep) { + while(level--) { + /* cut off one more level from the right of the original URL */ + pathsep = strrchr(protsep, '/'); + if(pathsep) + *pathsep = 0; + else { + *protsep = 0; + break; + } + } + } + } + else + skip_slash = TRUE; + } + else { + /* We got a new absolute path for this server */ + + if(relurl[1] == '/') { + /* the new URL starts with //, just keep the protocol part from the + original one */ + *protsep = 0; + useurl = &relurl[2]; /* we keep the slashes from the original, so we + skip the new ones */ + host_changed = TRUE; + } + else { + /* cut off the original URL from the first slash, or deal with URLs + without slash */ + pathsep = strchr(protsep, '/'); + if(pathsep) { + /* When people use badly formatted URLs, such as + "http://www.example.com?dir=/home/daniel" we must not use the first + slash, if there's a ?-letter before it! */ + char *sep = strchr(protsep, '?'); + if(sep && (sep < pathsep)) + pathsep = sep; + *pathsep = 0; + } + else { + /* There was no slash. Now, since we might be operating on a badly + formatted URL, such as "http://www.example.com?id=2380" which + doesn't use a slash separator as it is supposed to, we need to check + for a ?-letter as well! */ + pathsep = strchr(protsep, '?'); + if(pathsep) + *pathsep = 0; + } + } + } + + Curl_dyn_init(&newest, CURL_MAX_INPUT_LENGTH); + + /* copy over the root url part */ + result = Curl_dyn_add(&newest, base); + if(result) + return result; + + /* check if we need to append a slash */ + if(('/' == useurl[0]) || (protsep && !*protsep) || skip_slash) + ; + else { + result = Curl_dyn_addn(&newest, "/", 1); + if(result) + return result; + } + + /* then append the new piece on the right side */ + uc = urlencode_str(&newest, useurl, strlen(useurl), !host_changed, + FALSE); + if(uc) + return (uc == CURLUE_TOO_LARGE) ? CURLE_TOO_LARGE : CURLE_OUT_OF_MEMORY; + + *newurl = Curl_dyn_ptr(&newest); + return CURLE_OK; +} + +/* scan for byte values <= 31, 127 and sometimes space */ +static CURLUcode junkscan(const char *url, size_t *urllen, unsigned int flags) +{ + static const char badbytes[]={ + /* */ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x7f, 0x00 /* null-terminate */ + }; + size_t n = strlen(url); + size_t nfine; + + if(n > CURL_MAX_INPUT_LENGTH) + /* excessive input length */ + return CURLUE_MALFORMED_INPUT; + + nfine = strcspn(url, badbytes); + if((nfine != n) || + (!(flags & CURLU_ALLOW_SPACE) && strchr(url, ' '))) + return CURLUE_MALFORMED_INPUT; + + *urllen = n; + return CURLUE_OK; +} + +/* + * parse_hostname_login() + * + * Parse the login details (user name, password and options) from the URL and + * strip them out of the host name + * + */ +static CURLUcode parse_hostname_login(struct Curl_URL *u, + const char *login, + size_t len, + unsigned int flags, + size_t *offset) /* to the host name */ +{ + CURLUcode result = CURLUE_OK; + CURLcode ccode; + char *userp = NULL; + char *passwdp = NULL; + char *optionsp = NULL; + const struct Curl_handler *h = NULL; + + /* At this point, we assume all the other special cases have been taken + * care of, so the host is at most + * + * [user[:password][;options]]@]hostname + * + * We need somewhere to put the embedded details, so do that first. + */ + char *ptr; + + DEBUGASSERT(login); + + *offset = 0; + ptr = memchr(login, '@', len); + if(!ptr) + goto out; + + /* We will now try to extract the + * possible login information in a string like: + * ftp://user:password@ftp.my.site:8021/README */ + ptr++; + + /* if this is a known scheme, get some details */ + if(u->scheme) + h = Curl_get_scheme_handler(u->scheme); + + /* We could use the login information in the URL so extract it. Only parse + options if the handler says we should. Note that 'h' might be NULL! */ + ccode = Curl_parse_login_details(login, ptr - login - 1, + &userp, &passwdp, + (h && (h->flags & PROTOPT_URLOPTIONS)) ? + &optionsp:NULL); + if(ccode) { + result = CURLUE_BAD_LOGIN; + goto out; + } + + if(userp) { + if(flags & CURLU_DISALLOW_USER) { + /* Option DISALLOW_USER is set and url contains username. */ + result = CURLUE_USER_NOT_ALLOWED; + goto out; + } + free(u->user); + u->user = userp; + } + + if(passwdp) { + free(u->password); + u->password = passwdp; + } + + if(optionsp) { + free(u->options); + u->options = optionsp; + } + + /* the host name starts at this offset */ + *offset = ptr - login; + return CURLUE_OK; + +out: + + free(userp); + free(passwdp); + free(optionsp); + u->user = NULL; + u->password = NULL; + u->options = NULL; + + return result; +} + +UNITTEST CURLUcode Curl_parse_port(struct Curl_URL *u, struct dynbuf *host, + bool has_scheme) +{ + char *portptr; + char *hostname = Curl_dyn_ptr(host); + /* + * Find the end of an IPv6 address on the ']' ending bracket. + */ + if(hostname[0] == '[') { + portptr = strchr(hostname, ']'); + if(!portptr) + return CURLUE_BAD_IPV6; + portptr++; + /* this is a RFC2732-style specified IP-address */ + if(*portptr) { + if(*portptr != ':') + return CURLUE_BAD_PORT_NUMBER; + } + else + portptr = NULL; + } + else + portptr = strchr(hostname, ':'); + + if(portptr) { + char *rest = NULL; + unsigned long port; + size_t keep = portptr - hostname; + + /* Browser behavior adaptation. If there's a colon with no digits after, + just cut off the name there which makes us ignore the colon and just + use the default port. Firefox, Chrome and Safari all do that. + + Don't do it if the URL has no scheme, to make something that looks like + a scheme not work! + */ + Curl_dyn_setlen(host, keep); + portptr++; + if(!*portptr) + return has_scheme ? CURLUE_OK : CURLUE_BAD_PORT_NUMBER; + + if(!ISDIGIT(*portptr)) + return CURLUE_BAD_PORT_NUMBER; + + errno = 0; + port = strtoul(portptr, &rest, 10); /* Port number must be decimal */ + + if(errno || (port > 0xffff) || *rest) + return CURLUE_BAD_PORT_NUMBER; + + u->portnum = (unsigned short) port; + /* generate a new port number string to get rid of leading zeroes etc */ + free(u->port); + u->port = aprintf("%ld", port); + if(!u->port) + return CURLUE_OUT_OF_MEMORY; + } + + return CURLUE_OK; +} + +/* this assumes 'hostname' now starts with [ */ +static CURLUcode ipv6_parse(struct Curl_URL *u, char *hostname, + size_t hlen) /* length of hostname */ +{ + size_t len; + DEBUGASSERT(*hostname == '['); + if(hlen < 4) /* '[::]' is the shortest possible valid string */ + return CURLUE_BAD_IPV6; + hostname++; + hlen -= 2; + + /* only valid IPv6 letters are ok */ + len = strspn(hostname, "0123456789abcdefABCDEF:."); + + if(hlen != len) { + hlen = len; + if(hostname[len] == '%') { + /* this could now be '%[zone id]' */ + char zoneid[16]; + int i = 0; + char *h = &hostname[len + 1]; + /* pass '25' if present and is a url encoded percent sign */ + if(!strncmp(h, "25", 2) && h[2] && (h[2] != ']')) + h += 2; + while(*h && (*h != ']') && (i < 15)) + zoneid[i++] = *h++; + if(!i || (']' != *h)) + return CURLUE_BAD_IPV6; + zoneid[i] = 0; + u->zoneid = strdup(zoneid); + if(!u->zoneid) + return CURLUE_OUT_OF_MEMORY; + hostname[len] = ']'; /* insert end bracket */ + hostname[len + 1] = 0; /* terminate the hostname */ + } + else + return CURLUE_BAD_IPV6; + /* hostname is fine */ + } + + /* Check the IPv6 address. */ + { + char dest[16]; /* fits a binary IPv6 address */ + char norm[MAX_IPADR_LEN]; + hostname[hlen] = 0; /* end the address there */ + if(1 != Curl_inet_pton(AF_INET6, hostname, dest)) + return CURLUE_BAD_IPV6; + + /* check if it can be done shorter */ + if(Curl_inet_ntop(AF_INET6, dest, norm, sizeof(norm)) && + (strlen(norm) < hlen)) { + strcpy(hostname, norm); + hlen = strlen(norm); + hostname[hlen + 1] = 0; + } + hostname[hlen] = ']'; /* restore ending bracket */ + } + return CURLUE_OK; +} + +static CURLUcode hostname_check(struct Curl_URL *u, char *hostname, + size_t hlen) /* length of hostname */ +{ + size_t len; + DEBUGASSERT(hostname); + + if(!hlen) + return CURLUE_NO_HOST; + else if(hostname[0] == '[') + return ipv6_parse(u, hostname, hlen); + else { + /* letters from the second string are not ok */ + len = strcspn(hostname, " \r\n\t/:#?!@{}[]\\$\'\"^`*<>=;,+&()%"); + if(hlen != len) + /* hostname with bad content */ + return CURLUE_BAD_HOSTNAME; + } + return CURLUE_OK; +} + +/* + * Handle partial IPv4 numerical addresses and different bases, like + * '16843009', '0x7f', '0x7f.1' '0177.1.1.1' etc. + * + * If the given input string is syntactically wrong IPv4 or any part for + * example is too big, this function returns HOST_NAME. + * + * Output the "normalized" version of that input string in plain quad decimal + * integers. + * + * Returns the host type. + */ + +#define HOST_ERROR -1 /* out of memory */ +#define HOST_BAD -2 /* bad IPv4 address */ + +#define HOST_NAME 1 +#define HOST_IPV4 2 +#define HOST_IPV6 3 + +static int ipv4_normalize(struct dynbuf *host) +{ + bool done = FALSE; + int n = 0; + const char *c = Curl_dyn_ptr(host); + unsigned long parts[4] = {0, 0, 0, 0}; + CURLcode result = CURLE_OK; + + if(*c == '[') + return HOST_IPV6; + + errno = 0; /* for strtoul */ + while(!done) { + char *endp = NULL; + unsigned long l; + if(!ISDIGIT(*c)) + /* most importantly this doesn't allow a leading plus or minus */ + return HOST_NAME; + l = strtoul(c, &endp, 0); + if(errno) + return HOST_NAME; +#if SIZEOF_LONG > 4 + /* a value larger than 32 bits */ + if(l > UINT_MAX) + return HOST_NAME; +#endif + + parts[n] = l; + c = endp; + + switch(*c) { + case '.': + if(n == 3) + return HOST_NAME; + n++; + c++; + break; + + case '\0': + done = TRUE; + break; + + default: + return HOST_NAME; + } + } + + switch(n) { + case 0: /* a -- 32 bits */ + Curl_dyn_reset(host); + + result = Curl_dyn_addf(host, "%u.%u.%u.%u", + (unsigned int)(parts[0] >> 24), + (unsigned int)((parts[0] >> 16) & 0xff), + (unsigned int)((parts[0] >> 8) & 0xff), + (unsigned int)(parts[0] & 0xff)); + break; + case 1: /* a.b -- 8.24 bits */ + if((parts[0] > 0xff) || (parts[1] > 0xffffff)) + return HOST_NAME; + Curl_dyn_reset(host); + result = Curl_dyn_addf(host, "%u.%u.%u.%u", + (unsigned int)(parts[0]), + (unsigned int)((parts[1] >> 16) & 0xff), + (unsigned int)((parts[1] >> 8) & 0xff), + (unsigned int)(parts[1] & 0xff)); + break; + case 2: /* a.b.c -- 8.8.16 bits */ + if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xffff)) + return HOST_NAME; + Curl_dyn_reset(host); + result = Curl_dyn_addf(host, "%u.%u.%u.%u", + (unsigned int)(parts[0]), + (unsigned int)(parts[1]), + (unsigned int)((parts[2] >> 8) & 0xff), + (unsigned int)(parts[2] & 0xff)); + break; + case 3: /* a.b.c.d -- 8.8.8.8 bits */ + if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff) || + (parts[3] > 0xff)) + return HOST_NAME; + Curl_dyn_reset(host); + result = Curl_dyn_addf(host, "%u.%u.%u.%u", + (unsigned int)(parts[0]), + (unsigned int)(parts[1]), + (unsigned int)(parts[2]), + (unsigned int)(parts[3])); + break; + } + if(result) + return HOST_ERROR; + return HOST_IPV4; +} + +/* if necessary, replace the host content with a URL decoded version */ +static CURLUcode urldecode_host(struct dynbuf *host) +{ + char *per = NULL; + const char *hostname = Curl_dyn_ptr(host); + per = strchr(hostname, '%'); + if(!per) + /* nothing to decode */ + return CURLUE_OK; + else { + /* encoded */ + size_t dlen; + char *decoded; + CURLcode result = Curl_urldecode(hostname, 0, &decoded, &dlen, + REJECT_CTRL); + if(result) + return CURLUE_BAD_HOSTNAME; + Curl_dyn_reset(host); + result = Curl_dyn_addn(host, decoded, dlen); + free(decoded); + if(result) + return cc2cu(result); + } + + return CURLUE_OK; +} + +static CURLUcode parse_authority(struct Curl_URL *u, + const char *auth, size_t authlen, + unsigned int flags, + struct dynbuf *host, + bool has_scheme) +{ + size_t offset; + CURLUcode uc; + CURLcode result; + + /* + * Parse the login details and strip them out of the host name. + */ + uc = parse_hostname_login(u, auth, authlen, flags, &offset); + if(uc) + goto out; + + result = Curl_dyn_addn(host, auth + offset, authlen - offset); + if(result) { + uc = cc2cu(result); + goto out; + } + + uc = Curl_parse_port(u, host, has_scheme); + if(uc) + goto out; + + if(!Curl_dyn_len(host)) + return CURLUE_NO_HOST; + + switch(ipv4_normalize(host)) { + case HOST_IPV4: + break; + case HOST_IPV6: + uc = ipv6_parse(u, Curl_dyn_ptr(host), Curl_dyn_len(host)); + break; + case HOST_NAME: + uc = urldecode_host(host); + if(!uc) + uc = hostname_check(u, Curl_dyn_ptr(host), Curl_dyn_len(host)); + break; + case HOST_ERROR: + uc = CURLUE_OUT_OF_MEMORY; + break; + case HOST_BAD: + default: + uc = CURLUE_BAD_HOSTNAME; /* Bad IPv4 address even */ + break; + } + +out: + return uc; +} + +/* used for HTTP/2 server push */ +CURLUcode Curl_url_set_authority(CURLU *u, const char *authority) +{ + CURLUcode result; + struct dynbuf host; + + DEBUGASSERT(authority); + Curl_dyn_init(&host, CURL_MAX_INPUT_LENGTH); + + result = parse_authority(u, authority, strlen(authority), + CURLU_DISALLOW_USER, &host, !!u->scheme); + if(result) + Curl_dyn_free(&host); + else { + free(u->host); + u->host = Curl_dyn_ptr(&host); + } + return result; +} + +/* + * "Remove Dot Segments" + * https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 + */ + +/* + * dedotdotify() + * @unittest: 1395 + * + * This function gets a null-terminated path with dot and dotdot sequences + * passed in and strips them off according to the rules in RFC 3986 section + * 5.2.4. + * + * The function handles a query part ('?' + stuff) appended but it expects + * that fragments ('#' + stuff) have already been cut off. + * + * RETURNS + * + * Zero for success and 'out' set to an allocated dedotdotified string. + */ +UNITTEST int dedotdotify(const char *input, size_t clen, char **outp); +UNITTEST int dedotdotify(const char *input, size_t clen, char **outp) +{ + char *outptr; + const char *endp = &input[clen]; + char *out; + + *outp = NULL; + /* the path always starts with a slash, and a slash has not dot */ + if((clen < 2) || !memchr(input, '.', clen)) + return 0; + + out = malloc(clen + 1); + if(!out) + return 1; /* out of memory */ + + *out = 0; /* null-terminates, for inputs like "./" */ + outptr = out; + + do { + bool dotdot = TRUE; + if(*input == '.') { + /* A. If the input buffer begins with a prefix of "../" or "./", then + remove that prefix from the input buffer; otherwise, */ + + if(!strncmp("./", input, 2)) { + input += 2; + clen -= 2; + } + else if(!strncmp("../", input, 3)) { + input += 3; + clen -= 3; + } + /* D. if the input buffer consists only of "." or "..", then remove + that from the input buffer; otherwise, */ + + else if(!strcmp(".", input) || !strcmp("..", input) || + !strncmp(".?", input, 2) || !strncmp("..?", input, 3)) { + *out = 0; + break; + } + else + dotdot = FALSE; + } + else if(*input == '/') { + /* B. if the input buffer begins with a prefix of "/./" or "/.", where + "." is a complete path segment, then replace that prefix with "/" in + the input buffer; otherwise, */ + if(!strncmp("/./", input, 3)) { + input += 2; + clen -= 2; + } + else if(!strcmp("/.", input) || !strncmp("/.?", input, 3)) { + *outptr++ = '/'; + *outptr = 0; + break; + } + + /* C. if the input buffer begins with a prefix of "/../" or "/..", + where ".." is a complete path segment, then replace that prefix with + "/" in the input buffer and remove the last segment and its + preceding "/" (if any) from the output buffer; otherwise, */ + + else if(!strncmp("/../", input, 4)) { + input += 3; + clen -= 3; + /* remove the last segment from the output buffer */ + while(outptr > out) { + outptr--; + if(*outptr == '/') + break; + } + *outptr = 0; /* null-terminate where it stops */ + } + else if(!strcmp("/..", input) || !strncmp("/..?", input, 4)) { + /* remove the last segment from the output buffer */ + while(outptr > out) { + outptr--; + if(*outptr == '/') + break; + } + *outptr++ = '/'; + *outptr = 0; /* null-terminate where it stops */ + break; + } + else + dotdot = FALSE; + } + else + dotdot = FALSE; + + if(!dotdot) { + /* E. move the first path segment in the input buffer to the end of + the output buffer, including the initial "/" character (if any) and + any subsequent characters up to, but not including, the next "/" + character or the end of the input buffer. */ + + do { + *outptr++ = *input++; + clen--; + } while(*input && (*input != '/') && (*input != '?')); + *outptr = 0; + } + + /* continue until end of path */ + } while(input < endp); + + *outp = out; + return 0; /* success */ +} + +static CURLUcode parseurl(const char *url, CURLU *u, unsigned int flags) +{ + const char *path; + size_t pathlen; + char *query = NULL; + char *fragment = NULL; + char schemebuf[MAX_SCHEME_LEN + 1]; + size_t schemelen = 0; + size_t urllen; + CURLUcode result = CURLUE_OK; + size_t fraglen = 0; + struct dynbuf host; + + DEBUGASSERT(url); + + Curl_dyn_init(&host, CURL_MAX_INPUT_LENGTH); + + result = junkscan(url, &urllen, flags); + if(result) + goto fail; + + schemelen = Curl_is_absolute_url(url, schemebuf, sizeof(schemebuf), + flags & (CURLU_GUESS_SCHEME| + CURLU_DEFAULT_SCHEME)); + + /* handle the file: scheme */ + if(schemelen && !strcmp(schemebuf, "file")) { + bool uncpath = FALSE; + if(urllen <= 6) { + /* file:/ is not enough to actually be a complete file: URL */ + result = CURLUE_BAD_FILE_URL; + goto fail; + } + + /* path has been allocated large enough to hold this */ + path = (char *)&url[5]; + pathlen = urllen - 5; + + u->scheme = strdup("file"); + if(!u->scheme) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + + /* Extra handling URLs with an authority component (i.e. that start with + * "file://") + * + * We allow omitted hostname (e.g. file:/) -- valid according to + * RFC 8089, but not the (current) WHAT-WG URL spec. + */ + if(path[0] == '/' && path[1] == '/') { + /* swallow the two slashes */ + const char *ptr = &path[2]; + + /* + * According to RFC 8089, a file: URL can be reliably dereferenced if: + * + * o it has no/blank hostname, or + * + * o the hostname matches "localhost" (case-insensitively), or + * + * o the hostname is a FQDN that resolves to this machine, or + * + * o it is an UNC String transformed to an URI (Windows only, RFC 8089 + * Appendix E.3). + * + * For brevity, we only consider URLs with empty, "localhost", or + * "127.0.0.1" hostnames as local, otherwise as an UNC String. + * + * Additionally, there is an exception for URLs with a Windows drive + * letter in the authority (which was accidentally omitted from RFC 8089 + * Appendix E, but believe me, it was meant to be there. --MK) + */ + if(ptr[0] != '/' && !STARTS_WITH_URL_DRIVE_PREFIX(ptr)) { + /* the URL includes a host name, it must match "localhost" or + "127.0.0.1" to be valid */ + if(checkprefix("localhost/", ptr) || + checkprefix("127.0.0.1/", ptr)) { + ptr += 9; /* now points to the slash after the host */ + } + else { +#if defined(_WIN32) + size_t len; + + /* the host name, NetBIOS computer name, can not contain disallowed + chars, and the delimiting slash character must be appended to the + host name */ + path = strpbrk(ptr, "/\\:*?\"<>|"); + if(!path || *path != '/') { + result = CURLUE_BAD_FILE_URL; + goto fail; + } + + len = path - ptr; + if(len) { + CURLcode code = Curl_dyn_addn(&host, ptr, len); + if(code) { + result = cc2cu(code); + goto fail; + } + uncpath = TRUE; + } + + ptr -= 2; /* now points to the // before the host in UNC */ +#else + /* Invalid file://hostname/, expected localhost or 127.0.0.1 or + none */ + result = CURLUE_BAD_FILE_URL; + goto fail; +#endif + } + } + + path = ptr; + pathlen = urllen - (ptr - url); + } + + if(!uncpath) + /* no host for file: URLs by default */ + Curl_dyn_reset(&host); + +#if !defined(_WIN32) && !defined(MSDOS) && !defined(__CYGWIN__) + /* Don't allow Windows drive letters when not in Windows. + * This catches both "file:/c:" and "file:c:" */ + if(('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) || + STARTS_WITH_URL_DRIVE_PREFIX(path)) { + /* File drive letters are only accepted in MSDOS/Windows */ + result = CURLUE_BAD_FILE_URL; + goto fail; + } +#else + /* If the path starts with a slash and a drive letter, ditch the slash */ + if('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) { + /* This cannot be done with strcpy, as the memory chunks overlap! */ + path++; + pathlen--; + } +#endif + + } + else { + /* clear path */ + const char *schemep = NULL; + const char *hostp; + size_t hostlen; + + if(schemelen) { + int i = 0; + const char *p = &url[schemelen + 1]; + while((*p == '/') && (i < 4)) { + p++; + i++; + } + + schemep = schemebuf; + if(!Curl_get_scheme_handler(schemep) && + !(flags & CURLU_NON_SUPPORT_SCHEME)) { + result = CURLUE_UNSUPPORTED_SCHEME; + goto fail; + } + + if((i < 1) || (i > 3)) { + /* less than one or more than three slashes */ + result = CURLUE_BAD_SLASHES; + goto fail; + } + hostp = p; /* host name starts here */ + } + else { + /* no scheme! */ + + if(!(flags & (CURLU_DEFAULT_SCHEME|CURLU_GUESS_SCHEME))) { + result = CURLUE_BAD_SCHEME; + goto fail; + } + if(flags & CURLU_DEFAULT_SCHEME) + schemep = DEFAULT_SCHEME; + + /* + * The URL was badly formatted, let's try without scheme specified. + */ + hostp = url; + } + + if(schemep) { + u->scheme = strdup(schemep); + if(!u->scheme) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + } + + /* find the end of the host name + port number */ + hostlen = strcspn(hostp, "/?#"); + path = &hostp[hostlen]; + + /* this pathlen also contains the query and the fragment */ + pathlen = urllen - (path - url); + if(hostlen) { + + result = parse_authority(u, hostp, hostlen, flags, &host, schemelen); + if(result) + goto fail; + + if((flags & CURLU_GUESS_SCHEME) && !schemep) { + const char *hostname = Curl_dyn_ptr(&host); + /* legacy curl-style guess based on host name */ + if(checkprefix("ftp.", hostname)) + schemep = "ftp"; + else if(checkprefix("dict.", hostname)) + schemep = "dict"; + else if(checkprefix("ldap.", hostname)) + schemep = "ldap"; + else if(checkprefix("imap.", hostname)) + schemep = "imap"; + else if(checkprefix("smtp.", hostname)) + schemep = "smtp"; + else if(checkprefix("pop3.", hostname)) + schemep = "pop3"; + else + schemep = "http"; + + u->scheme = strdup(schemep); + if(!u->scheme) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + } + } + else if(flags & CURLU_NO_AUTHORITY) { + /* allowed to be empty. */ + if(Curl_dyn_add(&host, "")) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + } + else { + result = CURLUE_NO_HOST; + goto fail; + } + } + + fragment = strchr(path, '#'); + if(fragment) { + fraglen = pathlen - (fragment - path); + u->fragment_present = TRUE; + if(fraglen > 1) { + /* skip the leading '#' in the copy but include the terminating null */ + if(flags & CURLU_URLENCODE) { + struct dynbuf enc; + Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH); + result = urlencode_str(&enc, fragment + 1, fraglen - 1, TRUE, FALSE); + if(result) + goto fail; + u->fragment = Curl_dyn_ptr(&enc); + } + else { + u->fragment = Curl_memdup0(fragment + 1, fraglen - 1); + if(!u->fragment) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + } + } + /* after this, pathlen still contains the query */ + pathlen -= fraglen; + } + + query = memchr(path, '?', pathlen); + if(query) { + size_t qlen = fragment ? (size_t)(fragment - query) : + pathlen - (query - path); + pathlen -= qlen; + u->query_present = TRUE; + if(qlen > 1) { + if(flags & CURLU_URLENCODE) { + struct dynbuf enc; + Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH); + /* skip the leading question mark */ + result = urlencode_str(&enc, query + 1, qlen - 1, TRUE, TRUE); + if(result) + goto fail; + u->query = Curl_dyn_ptr(&enc); + } + else { + u->query = Curl_memdup0(query + 1, qlen - 1); + if(!u->query) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + } + } + else { + /* single byte query */ + u->query = strdup(""); + if(!u->query) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + } + } + + if(pathlen && (flags & CURLU_URLENCODE)) { + struct dynbuf enc; + Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH); + result = urlencode_str(&enc, path, pathlen, TRUE, FALSE); + if(result) + goto fail; + pathlen = Curl_dyn_len(&enc); + path = u->path = Curl_dyn_ptr(&enc); + } + + if(pathlen <= 1) { + /* there is no path left or just the slash, unset */ + path = NULL; + } + else { + if(!u->path) { + u->path = Curl_memdup0(path, pathlen); + if(!u->path) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + path = u->path; + } + else if(flags & CURLU_URLENCODE) + /* it might have encoded more than just the path so cut it */ + u->path[pathlen] = 0; + + if(!(flags & CURLU_PATH_AS_IS)) { + /* remove ../ and ./ sequences according to RFC3986 */ + char *dedot; + int err = dedotdotify((char *)path, pathlen, &dedot); + if(err) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + if(dedot) { + free(u->path); + u->path = dedot; + } + } + } + + u->host = Curl_dyn_ptr(&host); + + return result; +fail: + Curl_dyn_free(&host); + free_urlhandle(u); + return result; +} + +/* + * Parse the URL and, if successful, replace everything in the Curl_URL struct. + */ +static CURLUcode parseurl_and_replace(const char *url, CURLU *u, + unsigned int flags) +{ + CURLUcode result; + CURLU tmpurl; + memset(&tmpurl, 0, sizeof(tmpurl)); + result = parseurl(url, &tmpurl, flags); + if(!result) { + free_urlhandle(u); + *u = tmpurl; + } + return result; +} + +/* + */ +CURLU *curl_url(void) +{ + return calloc(1, sizeof(struct Curl_URL)); +} + +void curl_url_cleanup(CURLU *u) +{ + if(u) { + free_urlhandle(u); + free(u); + } +} + +#define DUP(dest, src, name) \ + do { \ + if(src->name) { \ + dest->name = strdup(src->name); \ + if(!dest->name) \ + goto fail; \ + } \ + } while(0) + +CURLU *curl_url_dup(const CURLU *in) +{ + struct Curl_URL *u = calloc(1, sizeof(struct Curl_URL)); + if(u) { + DUP(u, in, scheme); + DUP(u, in, user); + DUP(u, in, password); + DUP(u, in, options); + DUP(u, in, host); + DUP(u, in, port); + DUP(u, in, path); + DUP(u, in, query); + DUP(u, in, fragment); + DUP(u, in, zoneid); + u->portnum = in->portnum; + u->fragment_present = in->fragment_present; + u->query_present = in->query_present; + } + return u; +fail: + curl_url_cleanup(u); + return NULL; +} + +CURLUcode curl_url_get(const CURLU *u, CURLUPart what, + char **part, unsigned int flags) +{ + const char *ptr; + CURLUcode ifmissing = CURLUE_UNKNOWN_PART; + char portbuf[7]; + bool urldecode = (flags & CURLU_URLDECODE)?1:0; + bool urlencode = (flags & CURLU_URLENCODE)?1:0; + bool punycode = FALSE; + bool depunyfy = FALSE; + bool plusdecode = FALSE; + (void)flags; + if(!u) + return CURLUE_BAD_HANDLE; + if(!part) + return CURLUE_BAD_PARTPOINTER; + *part = NULL; + + switch(what) { + case CURLUPART_SCHEME: + ptr = u->scheme; + ifmissing = CURLUE_NO_SCHEME; + urldecode = FALSE; /* never for schemes */ + break; + case CURLUPART_USER: + ptr = u->user; + ifmissing = CURLUE_NO_USER; + break; + case CURLUPART_PASSWORD: + ptr = u->password; + ifmissing = CURLUE_NO_PASSWORD; + break; + case CURLUPART_OPTIONS: + ptr = u->options; + ifmissing = CURLUE_NO_OPTIONS; + break; + case CURLUPART_HOST: + ptr = u->host; + ifmissing = CURLUE_NO_HOST; + punycode = (flags & CURLU_PUNYCODE)?1:0; + depunyfy = (flags & CURLU_PUNY2IDN)?1:0; + break; + case CURLUPART_ZONEID: + ptr = u->zoneid; + ifmissing = CURLUE_NO_ZONEID; + break; + case CURLUPART_PORT: + ptr = u->port; + ifmissing = CURLUE_NO_PORT; + urldecode = FALSE; /* never for port */ + if(!ptr && (flags & CURLU_DEFAULT_PORT) && u->scheme) { + /* there's no stored port number, but asked to deliver + a default one for the scheme */ + const struct Curl_handler *h = Curl_get_scheme_handler(u->scheme); + if(h) { + msnprintf(portbuf, sizeof(portbuf), "%u", h->defport); + ptr = portbuf; + } + } + else if(ptr && u->scheme) { + /* there is a stored port number, but ask to inhibit if + it matches the default one for the scheme */ + const struct Curl_handler *h = Curl_get_scheme_handler(u->scheme); + if(h && (h->defport == u->portnum) && + (flags & CURLU_NO_DEFAULT_PORT)) + ptr = NULL; + } + break; + case CURLUPART_PATH: + ptr = u->path; + if(!ptr) + ptr = "/"; + break; + case CURLUPART_QUERY: + ptr = u->query; + ifmissing = CURLUE_NO_QUERY; + plusdecode = urldecode; + if(ptr && !ptr[0] && !(flags & CURLU_GET_EMPTY)) + /* there was a blank query and the user do not ask for it */ + ptr = NULL; + break; + case CURLUPART_FRAGMENT: + ptr = u->fragment; + ifmissing = CURLUE_NO_FRAGMENT; + if(!ptr && u->fragment_present && flags & CURLU_GET_EMPTY) + /* there was a blank fragment and the user asks for it */ + ptr = ""; + break; + case CURLUPART_URL: { + char *url; + char *scheme; + char *options = u->options; + char *port = u->port; + char *allochost = NULL; + bool show_fragment = + u->fragment || (u->fragment_present && flags & CURLU_GET_EMPTY); + bool show_query = + (u->query && u->query[0]) || + (u->query_present && flags & CURLU_GET_EMPTY); + punycode = (flags & CURLU_PUNYCODE)?1:0; + depunyfy = (flags & CURLU_PUNY2IDN)?1:0; + if(u->scheme && strcasecompare("file", u->scheme)) { + url = aprintf("file://%s%s%s", + u->path, + show_fragment ? "#": "", + u->fragment ? u->fragment : ""); + } + else if(!u->host) + return CURLUE_NO_HOST; + else { + const struct Curl_handler *h = NULL; + if(u->scheme) + scheme = u->scheme; + else if(flags & CURLU_DEFAULT_SCHEME) + scheme = (char *) DEFAULT_SCHEME; + else + return CURLUE_NO_SCHEME; + + h = Curl_get_scheme_handler(scheme); + if(!port && (flags & CURLU_DEFAULT_PORT)) { + /* there's no stored port number, but asked to deliver + a default one for the scheme */ + if(h) { + msnprintf(portbuf, sizeof(portbuf), "%u", h->defport); + port = portbuf; + } + } + else if(port) { + /* there is a stored port number, but asked to inhibit if it matches + the default one for the scheme */ + if(h && (h->defport == u->portnum) && + (flags & CURLU_NO_DEFAULT_PORT)) + port = NULL; + } + + if(h && !(h->flags & PROTOPT_URLOPTIONS)) + options = NULL; + + if(u->host[0] == '[') { + if(u->zoneid) { + /* make it '[ host %25 zoneid ]' */ + struct dynbuf enc; + size_t hostlen = strlen(u->host); + Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH); + if(Curl_dyn_addf(&enc, "%.*s%%25%s]", (int)hostlen - 1, u->host, + u->zoneid)) + return CURLUE_OUT_OF_MEMORY; + allochost = Curl_dyn_ptr(&enc); + } + } + else if(urlencode) { + allochost = curl_easy_escape(NULL, u->host, 0); + if(!allochost) + return CURLUE_OUT_OF_MEMORY; + } + else if(punycode) { + if(!Curl_is_ASCII_name(u->host)) { +#ifndef USE_IDN + return CURLUE_LACKS_IDN; +#else + CURLcode result = Curl_idn_decode(u->host, &allochost); + if(result) + return (result == CURLE_OUT_OF_MEMORY) ? + CURLUE_OUT_OF_MEMORY : CURLUE_BAD_HOSTNAME; +#endif + } + } + else if(depunyfy) { + if(Curl_is_ASCII_name(u->host) && !strncmp("xn--", u->host, 4)) { +#ifndef USE_IDN + return CURLUE_LACKS_IDN; +#else + CURLcode result = Curl_idn_encode(u->host, &allochost); + if(result) + /* this is the most likely error */ + return (result == CURLE_OUT_OF_MEMORY) ? + CURLUE_OUT_OF_MEMORY : CURLUE_BAD_HOSTNAME; +#endif + } + } + + url = aprintf("%s://%s%s%s%s%s%s%s%s%s%s%s%s%s%s", + scheme, + u->user ? u->user : "", + u->password ? ":": "", + u->password ? u->password : "", + options ? ";" : "", + options ? options : "", + (u->user || u->password || options) ? "@": "", + allochost ? allochost : u->host, + port ? ":": "", + port ? port : "", + u->path ? u->path : "/", + show_query ? "?": "", + u->query ? u->query : "", + show_fragment ? "#": "", + u->fragment? u->fragment : ""); + free(allochost); + } + if(!url) + return CURLUE_OUT_OF_MEMORY; + *part = url; + return CURLUE_OK; + } + default: + ptr = NULL; + break; + } + if(ptr) { + size_t partlen = strlen(ptr); + size_t i = 0; + *part = Curl_memdup0(ptr, partlen); + if(!*part) + return CURLUE_OUT_OF_MEMORY; + if(plusdecode) { + /* convert + to space */ + char *plus = *part; + for(i = 0; i < partlen; ++plus, i++) { + if(*plus == '+') + *plus = ' '; + } + } + if(urldecode) { + char *decoded; + size_t dlen; + /* this unconditional rejection of control bytes is documented + API behavior */ + CURLcode res = Curl_urldecode(*part, 0, &decoded, &dlen, REJECT_CTRL); + free(*part); + if(res) { + *part = NULL; + return CURLUE_URLDECODE; + } + *part = decoded; + partlen = dlen; + } + if(urlencode) { + struct dynbuf enc; + CURLUcode uc; + Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH); + uc = urlencode_str(&enc, *part, partlen, TRUE, what == CURLUPART_QUERY); + if(uc) + return uc; + free(*part); + *part = Curl_dyn_ptr(&enc); + } + else if(punycode) { + if(!Curl_is_ASCII_name(u->host)) { +#ifndef USE_IDN + return CURLUE_LACKS_IDN; +#else + char *allochost; + CURLcode result = Curl_idn_decode(*part, &allochost); + if(result) + return (result == CURLE_OUT_OF_MEMORY) ? + CURLUE_OUT_OF_MEMORY : CURLUE_BAD_HOSTNAME; + free(*part); + *part = allochost; +#endif + } + } + else if(depunyfy) { + if(Curl_is_ASCII_name(u->host) && !strncmp("xn--", u->host, 4)) { +#ifndef USE_IDN + return CURLUE_LACKS_IDN; +#else + char *allochost; + CURLcode result = Curl_idn_encode(*part, &allochost); + if(result) + return (result == CURLE_OUT_OF_MEMORY) ? + CURLUE_OUT_OF_MEMORY : CURLUE_BAD_HOSTNAME; + free(*part); + *part = allochost; +#endif + } + } + + return CURLUE_OK; + } + else + return ifmissing; +} + +CURLUcode curl_url_set(CURLU *u, CURLUPart what, + const char *part, unsigned int flags) +{ + char **storep = NULL; + bool urlencode = (flags & CURLU_URLENCODE)? 1 : 0; + bool plusencode = FALSE; + bool urlskipslash = FALSE; + bool leadingslash = FALSE; + bool appendquery = FALSE; + bool equalsencode = FALSE; + size_t nalloc; + + if(!u) + return CURLUE_BAD_HANDLE; + if(!part) { + /* setting a part to NULL clears it */ + switch(what) { + case CURLUPART_URL: + break; + case CURLUPART_SCHEME: + storep = &u->scheme; + break; + case CURLUPART_USER: + storep = &u->user; + break; + case CURLUPART_PASSWORD: + storep = &u->password; + break; + case CURLUPART_OPTIONS: + storep = &u->options; + break; + case CURLUPART_HOST: + storep = &u->host; + break; + case CURLUPART_ZONEID: + storep = &u->zoneid; + break; + case CURLUPART_PORT: + u->portnum = 0; + storep = &u->port; + break; + case CURLUPART_PATH: + storep = &u->path; + break; + case CURLUPART_QUERY: + storep = &u->query; + u->query_present = FALSE; + break; + case CURLUPART_FRAGMENT: + storep = &u->fragment; + u->fragment_present = FALSE; + break; + default: + return CURLUE_UNKNOWN_PART; + } + if(storep && *storep) { + Curl_safefree(*storep); + } + else if(!storep) { + free_urlhandle(u); + memset(u, 0, sizeof(struct Curl_URL)); + } + return CURLUE_OK; + } + + nalloc = strlen(part); + if(nalloc > CURL_MAX_INPUT_LENGTH) + /* excessive input length */ + return CURLUE_MALFORMED_INPUT; + + switch(what) { + case CURLUPART_SCHEME: { + size_t plen = strlen(part); + const char *s = part; + if((plen > MAX_SCHEME_LEN) || (plen < 1)) + /* too long or too short */ + return CURLUE_BAD_SCHEME; + /* verify that it is a fine scheme */ + if(!(flags & CURLU_NON_SUPPORT_SCHEME) && !Curl_get_scheme_handler(part)) + return CURLUE_UNSUPPORTED_SCHEME; + storep = &u->scheme; + urlencode = FALSE; /* never */ + if(ISALPHA(*s)) { + /* ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) */ + while(--plen) { + if(ISALNUM(*s) || (*s == '+') || (*s == '-') || (*s == '.')) + s++; /* fine */ + else + return CURLUE_BAD_SCHEME; + } + } + else + return CURLUE_BAD_SCHEME; + break; + } + case CURLUPART_USER: + storep = &u->user; + break; + case CURLUPART_PASSWORD: + storep = &u->password; + break; + case CURLUPART_OPTIONS: + storep = &u->options; + break; + case CURLUPART_HOST: + storep = &u->host; + Curl_safefree(u->zoneid); + break; + case CURLUPART_ZONEID: + storep = &u->zoneid; + break; + case CURLUPART_PORT: + if(!ISDIGIT(part[0])) + /* not a number */ + return CURLUE_BAD_PORT_NUMBER; + else { + char *tmp; + char *endp; + unsigned long port; + errno = 0; + port = strtoul(part, &endp, 10); /* must be decimal */ + if(errno || (port > 0xffff) || *endp) + /* weirdly provided number, not good! */ + return CURLUE_BAD_PORT_NUMBER; + tmp = strdup(part); + if(!tmp) + return CURLUE_OUT_OF_MEMORY; + free(u->port); + u->port = tmp; + u->portnum = (unsigned short)port; + return CURLUE_OK; + } + case CURLUPART_PATH: + urlskipslash = TRUE; + leadingslash = TRUE; /* enforce */ + storep = &u->path; + break; + case CURLUPART_QUERY: + plusencode = urlencode; + appendquery = (flags & CURLU_APPENDQUERY)?1:0; + equalsencode = appendquery; + storep = &u->query; + u->query_present = TRUE; + break; + case CURLUPART_FRAGMENT: + storep = &u->fragment; + u->fragment_present = TRUE; + break; + case CURLUPART_URL: { + /* + * Allow a new URL to replace the existing (if any) contents. + * + * If the existing contents is enough for a URL, allow a relative URL to + * replace it. + */ + CURLcode result; + CURLUcode uc; + char *oldurl; + char *redired_url; + + if(!nalloc) + /* a blank URL is not a valid URL */ + return CURLUE_MALFORMED_INPUT; + + /* if the new thing is absolute or the old one is not + * (we could not get an absolute url in 'oldurl'), + * then replace the existing with the new. */ + if(Curl_is_absolute_url(part, NULL, 0, + flags & (CURLU_GUESS_SCHEME| + CURLU_DEFAULT_SCHEME)) + || curl_url_get(u, CURLUPART_URL, &oldurl, flags)) { + return parseurl_and_replace(part, u, flags); + } + + /* apply the relative part to create a new URL + * and replace the existing one with it. */ + result = concat_url(oldurl, part, &redired_url); + free(oldurl); + if(result) + return cc2cu(result); + + uc = parseurl_and_replace(redired_url, u, flags); + free(redired_url); + return uc; + } + default: + return CURLUE_UNKNOWN_PART; + } + DEBUGASSERT(storep); + { + const char *newp; + struct dynbuf enc; + Curl_dyn_init(&enc, nalloc * 3 + 1 + leadingslash); + + if(leadingslash && (part[0] != '/')) { + CURLcode result = Curl_dyn_addn(&enc, "/", 1); + if(result) + return cc2cu(result); + } + if(urlencode) { + const unsigned char *i; + + for(i = (const unsigned char *)part; *i; i++) { + CURLcode result; + if((*i == ' ') && plusencode) { + result = Curl_dyn_addn(&enc, "+", 1); + if(result) + return CURLUE_OUT_OF_MEMORY; + } + else if(ISUNRESERVED(*i) || + ((*i == '/') && urlskipslash) || + ((*i == '=') && equalsencode)) { + if((*i == '=') && equalsencode) + /* only skip the first equals sign */ + equalsencode = FALSE; + result = Curl_dyn_addn(&enc, i, 1); + if(result) + return cc2cu(result); + } + else { + char out[3]={'%'}; + out[1] = hexdigits[*i>>4]; + out[2] = hexdigits[*i & 0xf]; + result = Curl_dyn_addn(&enc, out, 3); + if(result) + return cc2cu(result); + } + } + } + else { + char *p; + CURLcode result = Curl_dyn_add(&enc, part); + if(result) + return cc2cu(result); + p = Curl_dyn_ptr(&enc); + while(*p) { + /* make sure percent encoded are lower case */ + if((*p == '%') && ISXDIGIT(p[1]) && ISXDIGIT(p[2]) && + (ISUPPER(p[1]) || ISUPPER(p[2]))) { + p[1] = Curl_raw_tolower(p[1]); + p[2] = Curl_raw_tolower(p[2]); + p += 3; + } + else + p++; + } + } + newp = Curl_dyn_ptr(&enc); + + if(appendquery && newp) { + /* Append the 'newp' string onto the old query. Add a '&' separator if + none is present at the end of the existing query already */ + + size_t querylen = u->query ? strlen(u->query) : 0; + bool addamperand = querylen && (u->query[querylen -1] != '&'); + if(querylen) { + struct dynbuf qbuf; + Curl_dyn_init(&qbuf, CURL_MAX_INPUT_LENGTH); + + if(Curl_dyn_addn(&qbuf, u->query, querylen)) /* add original query */ + goto nomem; + + if(addamperand) { + if(Curl_dyn_addn(&qbuf, "&", 1)) + goto nomem; + } + if(Curl_dyn_add(&qbuf, newp)) + goto nomem; + Curl_dyn_free(&enc); + free(*storep); + *storep = Curl_dyn_ptr(&qbuf); + return CURLUE_OK; +nomem: + Curl_dyn_free(&enc); + return CURLUE_OUT_OF_MEMORY; + } + } + + else if(what == CURLUPART_HOST) { + size_t n = Curl_dyn_len(&enc); + if(!n && (flags & CURLU_NO_AUTHORITY)) { + /* Skip hostname check, it's allowed to be empty. */ + } + else { + if(!n || hostname_check(u, (char *)newp, n)) { + Curl_dyn_free(&enc); + return CURLUE_BAD_HOSTNAME; + } + } + } + + free(*storep); + *storep = (char *)newp; + } + return CURLUE_OK; +} diff --git a/third_party/curl/lib/urldata.h b/third_party/curl/lib/urldata.h new file mode 100644 index 0000000..8b1bd65 --- /dev/null +++ b/third_party/curl/lib/urldata.h @@ -0,0 +1,1981 @@ +#ifndef HEADER_CURL_URLDATA_H +#define HEADER_CURL_URLDATA_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* This file is for lib internal stuff */ + +#include "curl_setup.h" + +#define PORT_FTP 21 +#define PORT_FTPS 990 +#define PORT_TELNET 23 +#define PORT_HTTP 80 +#define PORT_HTTPS 443 +#define PORT_DICT 2628 +#define PORT_LDAP 389 +#define PORT_LDAPS 636 +#define PORT_TFTP 69 +#define PORT_SSH 22 +#define PORT_IMAP 143 +#define PORT_IMAPS 993 +#define PORT_POP3 110 +#define PORT_POP3S 995 +#define PORT_SMB 445 +#define PORT_SMBS 445 +#define PORT_SMTP 25 +#define PORT_SMTPS 465 /* sometimes called SSMTP */ +#define PORT_RTSP 554 +#define PORT_RTMP 1935 +#define PORT_RTMPT PORT_HTTP +#define PORT_RTMPS PORT_HTTPS +#define PORT_GOPHER 70 +#define PORT_MQTT 1883 + +struct curl_trc_featt; + +#ifdef USE_ECH +/* CURLECH_ bits for the tls_ech option */ +# define CURLECH_DISABLE (1<<0) +# define CURLECH_GREASE (1<<1) +# define CURLECH_ENABLE (1<<2) +# define CURLECH_HARD (1<<3) +# define CURLECH_CLA_CFG (1<<4) +#endif + +#ifdef USE_WEBSOCKETS +/* CURLPROTO_GOPHERS (29) is the highest publicly used protocol bit number, + * the rest are internal information. If we use higher bits we only do this on + * platforms that have a >= 64 bit type and then we use such a type for the + * protocol fields in the protocol handler. + */ +#define CURLPROTO_WS (1<<30) +#define CURLPROTO_WSS ((curl_prot_t)1<<31) +#else +#define CURLPROTO_WS 0 +#define CURLPROTO_WSS 0 +#endif + +/* This should be undefined once we need bit 32 or higher */ +#define PROTO_TYPE_SMALL + +#ifndef PROTO_TYPE_SMALL +typedef curl_off_t curl_prot_t; +#else +typedef unsigned int curl_prot_t; +#endif + +/* This mask is for all the old protocols that are provided and defined in the + public header and shall exclude protocols added since which are not exposed + in the API */ +#define CURLPROTO_MASK (0x3ffffff) + +#define DICT_MATCH "/MATCH:" +#define DICT_MATCH2 "/M:" +#define DICT_MATCH3 "/FIND:" +#define DICT_DEFINE "/DEFINE:" +#define DICT_DEFINE2 "/D:" +#define DICT_DEFINE3 "/LOOKUP:" + +#define CURL_DEFAULT_USER "anonymous" +#define CURL_DEFAULT_PASSWORD "ftp@example.com" + +/* Convenience defines for checking protocols or their SSL based version. Each + protocol handler should only ever have a single CURLPROTO_ in its protocol + field. */ +#define PROTO_FAMILY_HTTP (CURLPROTO_HTTP|CURLPROTO_HTTPS|CURLPROTO_WS| \ + CURLPROTO_WSS) +#define PROTO_FAMILY_FTP (CURLPROTO_FTP|CURLPROTO_FTPS) +#define PROTO_FAMILY_POP3 (CURLPROTO_POP3|CURLPROTO_POP3S) +#define PROTO_FAMILY_SMB (CURLPROTO_SMB|CURLPROTO_SMBS) +#define PROTO_FAMILY_SMTP (CURLPROTO_SMTP|CURLPROTO_SMTPS) +#define PROTO_FAMILY_SSH (CURLPROTO_SCP|CURLPROTO_SFTP) + +#if !defined(CURL_DISABLE_FTP) || defined(USE_SSH) || \ + !defined(CURL_DISABLE_POP3) || !defined(CURL_DISABLE_FILE) +/* these protocols support CURLOPT_DIRLISTONLY */ +#define CURL_LIST_ONLY_PROTOCOL 1 +#endif + +#define DEFAULT_CONNCACHE_SIZE 5 + +/* length of longest IPv6 address string including the trailing null */ +#define MAX_IPADR_LEN sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255") + +/* Default FTP/IMAP etc response timeout in milliseconds */ +#define RESP_TIMEOUT (120*1000) + +/* Max string input length is a precaution against abuse and to detect junk + input easier and better. */ +#define CURL_MAX_INPUT_LENGTH 8000000 + + +#include "cookie.h" +#include "psl.h" +#include "formdata.h" + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif + +#include "timeval.h" + +#include + +#include "http_chunks.h" /* for the structs and enum stuff */ +#include "hostip.h" +#include "hash.h" +#include "splay.h" +#include "dynbuf.h" +#include "dynhds.h" +#include "request.h" + +/* return the count of bytes sent, or -1 on error */ +typedef ssize_t (Curl_send)(struct Curl_easy *data, /* transfer */ + int sockindex, /* socketindex */ + const void *buf, /* data to write */ + size_t len, /* max amount to write */ + CURLcode *err); /* error to return */ + +/* return the count of bytes read, or -1 on error */ +typedef ssize_t (Curl_recv)(struct Curl_easy *data, /* transfer */ + int sockindex, /* socketindex */ + char *buf, /* store data here */ + size_t len, /* max amount to read */ + CURLcode *err); /* error to return */ + +#ifdef USE_HYPER +typedef CURLcode (*Curl_datastream)(struct Curl_easy *data, + struct connectdata *conn, + int *didwhat, + int select_res); +#endif + +#include "mime.h" +#include "imap.h" +#include "pop3.h" +#include "smtp.h" +#include "ftp.h" +#include "file.h" +#include "vssh/ssh.h" +#include "http.h" +#include "rtsp.h" +#include "smb.h" +#include "mqtt.h" +#include "ftplistparser.h" +#include "multihandle.h" +#include "c-hyper.h" +#include "cf-socket.h" + +#ifdef HAVE_GSSAPI +# ifdef HAVE_GSSGNU +# include +# elif defined HAVE_GSSAPI_GSSAPI_H +# include +# else +# include +# endif +# ifdef HAVE_GSSAPI_GSSAPI_GENERIC_H +# include +# endif +#endif + +#ifdef USE_LIBSSH2 +#include +#include +#endif /* USE_LIBSSH2 */ + +#define READBUFFER_SIZE CURL_MAX_WRITE_SIZE +#define READBUFFER_MAX CURL_MAX_READ_SIZE +#define READBUFFER_MIN 1024 + +/* The default upload buffer size, should not be smaller than + CURL_MAX_WRITE_SIZE, as it needs to hold a full buffer as could be sent in + a write callback. + + The size was 16KB for many years but was bumped to 64KB because it makes + libcurl able to do significantly faster uploads in some circumstances. Even + larger buffers can help further, but this is deemed a fair memory/speed + compromise. */ +#define UPLOADBUFFER_DEFAULT 65536 +#define UPLOADBUFFER_MAX (2*1024*1024) +#define UPLOADBUFFER_MIN CURL_MAX_WRITE_SIZE + +#define CURLEASY_MAGIC_NUMBER 0xc0dedbadU +#ifdef DEBUGBUILD +/* On a debug build, we want to fail hard on easy handles that + * are not NULL, but no longer have the MAGIC touch. This gives + * us early warning on things only discovered by valgrind otherwise. */ +#define GOOD_EASY_HANDLE(x) \ + (((x) && ((x)->magic == CURLEASY_MAGIC_NUMBER))? TRUE: \ + (DEBUGASSERT(!(x)), FALSE)) +#else +#define GOOD_EASY_HANDLE(x) \ + ((x) && ((x)->magic == CURLEASY_MAGIC_NUMBER)) +#endif + +#ifdef HAVE_GSSAPI +/* Types needed for krb5-ftp connections */ +struct krb5buffer { + struct dynbuf buf; + size_t index; + BIT(eof_flag); +}; + +enum protection_level { + PROT_NONE, /* first in list */ + PROT_CLEAR, + PROT_SAFE, + PROT_CONFIDENTIAL, + PROT_PRIVATE, + PROT_CMD, + PROT_LAST /* last in list */ +}; +#endif + +/* enum for the nonblocking SSL connection state machine */ +typedef enum { + ssl_connect_1, + ssl_connect_2, + ssl_connect_2_reading, + ssl_connect_2_writing, + ssl_connect_3, + ssl_connect_done +} ssl_connect_state; + +typedef enum { + ssl_connection_none, + ssl_connection_negotiating, + ssl_connection_complete +} ssl_connection_state; + +/* SSL backend-specific data; declared differently by each SSL backend */ +struct ssl_backend_data; + +typedef enum { + CURL_SSL_PEER_DNS, + CURL_SSL_PEER_IPV4, + CURL_SSL_PEER_IPV6 +} ssl_peer_type; + +struct ssl_peer { + char *hostname; /* hostname for verification */ + char *dispname; /* display version of hostname */ + char *sni; /* SNI version of hostname or NULL if not usable */ + ssl_peer_type type; /* type of the peer information */ + int port; /* port we are talking to */ + int transport; /* TCP or QUIC */ +}; + +struct ssl_primary_config { + char *CApath; /* certificate dir (doesn't work on windows) */ + char *CAfile; /* certificate to verify peer against */ + char *issuercert; /* optional issuer certificate filename */ + char *clientcert; + char *cipher_list; /* list of ciphers to use */ + char *cipher_list13; /* list of TLS 1.3 cipher suites to use */ + char *pinned_key; + char *CRLfile; /* CRL to check certificate revocation */ + struct curl_blob *cert_blob; + struct curl_blob *ca_info_blob; + struct curl_blob *issuercert_blob; +#ifdef USE_TLS_SRP + char *username; /* TLS username (for, e.g., SRP) */ + char *password; /* TLS password (for, e.g., SRP) */ +#endif + char *curves; /* list of curves to use */ + unsigned char ssl_options; /* the CURLOPT_SSL_OPTIONS bitmask */ + unsigned int version_max; /* max supported version the client wants to use */ + unsigned char version; /* what version the client wants to use */ + BIT(verifypeer); /* set TRUE if this is desired */ + BIT(verifyhost); /* set TRUE if CN/SAN must match hostname */ + BIT(verifystatus); /* set TRUE if certificate status must be checked */ + BIT(sessionid); /* cache session IDs or not */ +}; + +struct ssl_config_data { + struct ssl_primary_config primary; + long certverifyresult; /* result from the certificate verification */ + curl_ssl_ctx_callback fsslctx; /* function to initialize ssl ctx */ + void *fsslctxp; /* parameter for call back */ + char *cert_type; /* format for certificate (default: PEM)*/ + char *key; /* private key file name */ + struct curl_blob *key_blob; + char *key_type; /* format for private key (default: PEM) */ + char *key_passwd; /* plain text private key password */ + BIT(certinfo); /* gather lots of certificate info */ + BIT(falsestart); + BIT(enable_beast); /* allow this flaw for interoperability's sake */ + BIT(no_revoke); /* disable SSL certificate revocation checks */ + BIT(no_partialchain); /* don't accept partial certificate chains */ + BIT(revoke_best_effort); /* ignore SSL revocation offline/missing revocation + list errors */ + BIT(native_ca_store); /* use the native ca store of operating system */ + BIT(auto_client_cert); /* automatically locate and use a client + certificate for authentication (Schannel) */ +}; + +struct ssl_general_config { + size_t max_ssl_sessions; /* SSL session id cache size */ + int ca_cache_timeout; /* Certificate store cache timeout (seconds) */ +}; + +typedef void Curl_ssl_sessionid_dtor(void *sessionid, size_t idsize); + +/* information stored about one single SSL session */ +struct Curl_ssl_session { + char *name; /* host name for which this ID was used */ + char *conn_to_host; /* host name for the connection (may be NULL) */ + const char *scheme; /* protocol scheme used */ + void *sessionid; /* as returned from the SSL layer */ + size_t idsize; /* if known, otherwise 0 */ + Curl_ssl_sessionid_dtor *sessionid_free; /* free `sessionid` callback */ + long age; /* just a number, the higher the more recent */ + int remote_port; /* remote port */ + int conn_to_port; /* remote port for the connection (may be -1) */ + int transport; /* TCP or QUIC */ + struct ssl_primary_config ssl_config; /* setup for this session */ +}; + +#ifdef USE_WINDOWS_SSPI +#include "curl_sspi.h" +#endif + +#ifndef CURL_DISABLE_DIGEST_AUTH +/* Struct used for Digest challenge-response authentication */ +struct digestdata { +#if defined(USE_WINDOWS_SSPI) + BYTE *input_token; + size_t input_token_len; + CtxtHandle *http_context; + /* copy of user/passwd used to make the identity for http_context. + either may be NULL. */ + char *user; + char *passwd; +#else + char *nonce; + char *cnonce; + char *realm; + char *opaque; + char *qop; + char *algorithm; + int nc; /* nonce count */ + unsigned char algo; + BIT(stale); /* set true for re-negotiation */ + BIT(userhash); +#endif +}; +#endif + +typedef enum { + NTLMSTATE_NONE, + NTLMSTATE_TYPE1, + NTLMSTATE_TYPE2, + NTLMSTATE_TYPE3, + NTLMSTATE_LAST +} curlntlm; + +typedef enum { + GSS_AUTHNONE, + GSS_AUTHRECV, + GSS_AUTHSENT, + GSS_AUTHDONE, + GSS_AUTHSUCC +} curlnegotiate; + +/* Struct used for GSSAPI (Kerberos V5) authentication */ +#if defined(USE_KERBEROS5) +struct kerberos5data { +#if defined(USE_WINDOWS_SSPI) + CredHandle *credentials; + CtxtHandle *context; + TCHAR *spn; + SEC_WINNT_AUTH_IDENTITY identity; + SEC_WINNT_AUTH_IDENTITY *p_identity; + size_t token_max; + BYTE *output_token; +#else + gss_ctx_id_t context; + gss_name_t spn; +#endif +}; +#endif + +/* Struct used for SCRAM-SHA-1 authentication */ +#ifdef USE_GSASL +#include +struct gsasldata { + Gsasl *ctx; + Gsasl_session *client; +}; +#endif + +/* Struct used for NTLM challenge-response authentication */ +#if defined(USE_NTLM) +struct ntlmdata { +#ifdef USE_WINDOWS_SSPI +/* The sslContext is used for the Schannel bindings. The + * api is available on the Windows 7 SDK and later. + */ +#ifdef SECPKG_ATTR_ENDPOINT_BINDINGS + CtxtHandle *sslContext; +#endif + CredHandle *credentials; + CtxtHandle *context; + SEC_WINNT_AUTH_IDENTITY identity; + SEC_WINNT_AUTH_IDENTITY *p_identity; + size_t token_max; + BYTE *output_token; + BYTE *input_token; + size_t input_token_len; + TCHAR *spn; +#else + unsigned int flags; + unsigned char nonce[8]; + unsigned int target_info_len; + void *target_info; /* TargetInfo received in the ntlm type-2 message */ +#endif +}; +#endif + +/* Struct used for Negotiate (SPNEGO) authentication */ +#ifdef USE_SPNEGO +struct negotiatedata { +#ifdef HAVE_GSSAPI + OM_uint32 status; + gss_ctx_id_t context; + gss_name_t spn; + gss_buffer_desc output_token; +#else +#ifdef USE_WINDOWS_SSPI +#ifdef SECPKG_ATTR_ENDPOINT_BINDINGS + CtxtHandle *sslContext; +#endif + DWORD status; + CredHandle *credentials; + CtxtHandle *context; + SEC_WINNT_AUTH_IDENTITY identity; + SEC_WINNT_AUTH_IDENTITY *p_identity; + TCHAR *spn; + size_t token_max; + BYTE *output_token; + size_t output_token_length; +#endif +#endif + BIT(noauthpersist); + BIT(havenoauthpersist); + BIT(havenegdata); + BIT(havemultiplerequests); +}; +#endif + +#ifdef CURL_DISABLE_PROXY +#define CONN_IS_PROXIED(x) 0 +#else +#define CONN_IS_PROXIED(x) x->bits.proxy +#endif + +/* + * Boolean values that concerns this connection. + */ +struct ConnectBits { +#ifndef CURL_DISABLE_PROXY + BIT(httpproxy); /* if set, this transfer is done through an HTTP proxy */ + BIT(socksproxy); /* if set, this transfer is done through a socks proxy */ + BIT(proxy_user_passwd); /* user+password for the proxy? */ + BIT(tunnel_proxy); /* if CONNECT is used to "tunnel" through the proxy. + This is implicit when SSL-protocols are used through + proxies, but can also be enabled explicitly by + apps */ + BIT(proxy_connect_closed); /* TRUE if a proxy disconnected the connection + in a CONNECT request with auth, so that + libcurl should reconnect and continue. */ + BIT(proxy); /* if set, this transfer is done through a proxy - any type */ +#endif + /* always modify bits.close with the connclose() and connkeep() macros! */ + BIT(close); /* if set, we close the connection after this request */ + BIT(reuse); /* if set, this is a reused connection */ + BIT(altused); /* this is an alt-svc "redirect" */ + BIT(conn_to_host); /* if set, this connection has a "connect to host" + that overrides the host in the URL */ + BIT(conn_to_port); /* if set, this connection has a "connect to port" + that overrides the port in the URL (remote port) */ + BIT(ipv6_ip); /* we communicate with a remote site specified with pure IPv6 + IP address */ + BIT(ipv6); /* we communicate with a site using an IPv6 address */ + BIT(do_more); /* this is set TRUE if the ->curl_do_more() function is + supposed to be called, after ->curl_do() */ + BIT(protoconnstart);/* the protocol layer has STARTED its operation after + the TCP layer connect */ + BIT(retry); /* this connection is about to get closed and then + re-attempted at another connection. */ +#ifndef CURL_DISABLE_FTP + BIT(ftp_use_epsv); /* As set with CURLOPT_FTP_USE_EPSV, but if we find out + EPSV doesn't work we disable it for the forthcoming + requests */ + BIT(ftp_use_eprt); /* As set with CURLOPT_FTP_USE_EPRT, but if we find out + EPRT doesn't work we disable it for the forthcoming + requests */ + BIT(ftp_use_data_ssl); /* Enabled SSL for the data connection */ + BIT(ftp_use_control_ssl); /* Enabled SSL for the control connection */ +#endif +#ifndef CURL_DISABLE_NETRC + BIT(netrc); /* name+password provided by netrc */ +#endif + BIT(bound); /* set true if bind() has already been done on this socket/ + connection */ + BIT(multiplex); /* connection is multiplexed */ + BIT(tcp_fastopen); /* use TCP Fast Open */ + BIT(tls_enable_alpn); /* TLS ALPN extension? */ +#ifndef CURL_DISABLE_DOH + BIT(doh); +#endif +#ifdef USE_UNIX_SOCKETS + BIT(abstract_unix_socket); +#endif + BIT(tls_upgraded); + BIT(sock_accepted); /* TRUE if the SECONDARYSOCKET was created with + accept() */ + BIT(parallel_connect); /* set TRUE when a parallel connect attempt has + started (happy eyeballs) */ +}; + +struct hostname { + char *rawalloc; /* allocated "raw" version of the name */ + char *encalloc; /* allocated IDN-encoded version of the name */ + char *name; /* name to use internally, might be encoded, might be raw */ + const char *dispname; /* name to display, as 'name' might be encoded */ +}; + +/* + * Flags on the keepon member of the Curl_transfer_keeper + */ + +#define KEEP_NONE 0 +#define KEEP_RECV (1<<0) /* there is or may be data to read */ +#define KEEP_SEND (1<<1) /* there is or may be data to write */ +#define KEEP_RECV_HOLD (1<<2) /* when set, no reading should be done but there + might still be data to read */ +#define KEEP_SEND_HOLD (1<<3) /* when set, no writing should be done but there + might still be data to write */ +#define KEEP_RECV_PAUSE (1<<4) /* reading is paused */ +#define KEEP_SEND_PAUSE (1<<5) /* writing is paused */ + +/* KEEP_SEND_TIMED is set when the transfer should attempt sending + * at timer (or other) events. A transfer waiting on a timer will + * remove KEEP_SEND to suppress POLLOUTs of the connection. + * Adding KEEP_SEND_TIMED will then attempt to send whenever the transfer + * enters the "readwrite" loop, e.g. when a timer fires. + * This is used in HTTP for 'Expect: 100-continue' waiting. */ +#define KEEP_SEND_TIMED (1<<6) + +#define KEEP_RECVBITS (KEEP_RECV | KEEP_RECV_HOLD | KEEP_RECV_PAUSE) +#define KEEP_SENDBITS (KEEP_SEND | KEEP_SEND_HOLD | KEEP_SEND_PAUSE) + +/* transfer wants to send is not PAUSE or HOLD */ +#define CURL_WANT_SEND(data) \ + (((data)->req.keepon & KEEP_SENDBITS) == KEEP_SEND) +/* transfer receive is not on PAUSE or HOLD */ +#define CURL_WANT_RECV(data) \ + (((data)->req.keepon & KEEP_RECVBITS) == KEEP_RECV) + +#if defined(CURLRES_ASYNCH) || !defined(CURL_DISABLE_DOH) +#define USE_CURL_ASYNC +struct Curl_async { + char *hostname; + struct Curl_dns_entry *dns; + struct thread_data *tdata; + void *resolver; /* resolver state, if it is used in the URL state - + ares_channel e.g. */ + int port; + int status; /* if done is TRUE, this is the status from the callback */ + BIT(done); /* set TRUE when the lookup is complete */ +}; + +#endif + +#define FIRSTSOCKET 0 +#define SECONDARYSOCKET 1 + +/* Polling requested by an easy handle. + * `action` is CURL_POLL_IN, CURL_POLL_OUT or CURL_POLL_INOUT. + */ +struct easy_pollset { + curl_socket_t sockets[MAX_SOCKSPEREASYHANDLE]; + unsigned int num; + unsigned char actions[MAX_SOCKSPEREASYHANDLE]; +}; + +enum doh_slots { + /* Explicit values for first two symbols so as to match hard-coded + * constants in existing code + */ + DOH_PROBE_SLOT_IPADDR_V4 = 0, /* make 'V4' stand out for readability */ + DOH_PROBE_SLOT_IPADDR_V6 = 1, /* 'V6' likewise */ + + /* Space here for (possibly build-specific) additional slot definitions */ +#ifdef USE_HTTPSRR + DOH_PROBE_SLOT_HTTPS = 2, /* for HTTPS RR */ +#endif + + /* for example */ + /* #ifdef WANT_DOH_FOOBAR_TXT */ + /* DOH_PROBE_SLOT_FOOBAR_TXT, */ + /* #endif */ + + /* AFTER all slot definitions, establish how many we have */ + DOH_PROBE_SLOTS +}; + +/* + * Specific protocol handler. + */ + +struct Curl_handler { + const char *scheme; /* URL scheme name in lowercase */ + + /* Complement to setup_connection_internals(). This is done before the + transfer "owns" the connection. */ + CURLcode (*setup_connection)(struct Curl_easy *data, + struct connectdata *conn); + + /* These two functions MUST be set to be protocol dependent */ + CURLcode (*do_it)(struct Curl_easy *data, bool *done); + CURLcode (*done)(struct Curl_easy *, CURLcode, bool); + + /* If the curl_do() function is better made in two halves, this + * curl_do_more() function will be called afterwards, if set. For example + * for doing the FTP stuff after the PASV/PORT command. + */ + CURLcode (*do_more)(struct Curl_easy *, int *); + + /* This function *MAY* be set to a protocol-dependent function that is run + * after the connect() and everything is done, as a step in the connection. + * The 'done' pointer points to a bool that should be set to TRUE if the + * function completes before return. If it doesn't complete, the caller + * should call the ->connecting() function until it is. + */ + CURLcode (*connect_it)(struct Curl_easy *data, bool *done); + + /* See above. */ + CURLcode (*connecting)(struct Curl_easy *data, bool *done); + CURLcode (*doing)(struct Curl_easy *data, bool *done); + + /* Called from the multi interface during the PROTOCONNECT phase, and it + should then return a proper fd set */ + int (*proto_getsock)(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *socks); + + /* Called from the multi interface during the DOING phase, and it should + then return a proper fd set */ + int (*doing_getsock)(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *socks); + + /* Called from the multi interface during the DO_MORE phase, and it should + then return a proper fd set */ + int (*domore_getsock)(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *socks); + + /* Called from the multi interface during the DO_DONE, PERFORM and + WAITPERFORM phases, and it should then return a proper fd set. Not setting + this will make libcurl use the generic default one. */ + int (*perform_getsock)(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *socks); + + /* This function *MAY* be set to a protocol-dependent function that is run + * by the curl_disconnect(), as a step in the disconnection. If the handler + * is called because the connection has been considered dead, + * dead_connection is set to TRUE. The connection is (again) associated with + * the transfer here. + */ + CURLcode (*disconnect)(struct Curl_easy *, struct connectdata *, + bool dead_connection); + + /* If used, this function gets called from transfer.c to + allow the protocol to do extra handling in writing response to + the client. */ + CURLcode (*write_resp)(struct Curl_easy *data, const char *buf, size_t blen, + bool is_eos); + + /* If used, this function gets called from transfer.c to + allow the protocol to do extra handling in writing a single response + header line to the client. */ + CURLcode (*write_resp_hd)(struct Curl_easy *data, + const char *hd, size_t hdlen, bool is_eos); + + /* This function can perform various checks on the connection. See + CONNCHECK_* for more information about the checks that can be performed, + and CONNRESULT_* for the results that can be returned. */ + unsigned int (*connection_check)(struct Curl_easy *data, + struct connectdata *conn, + unsigned int checks_to_perform); + + /* attach() attaches this transfer to this connection */ + void (*attach)(struct Curl_easy *data, struct connectdata *conn); + + int defport; /* Default port. */ + curl_prot_t protocol; /* See CURLPROTO_* - this needs to be the single + specific protocol bit */ + curl_prot_t family; /* single bit for protocol family; basically the + non-TLS name of the protocol this is */ + unsigned int flags; /* Extra particular characteristics, see PROTOPT_* */ + +}; + +#define PROTOPT_NONE 0 /* nothing extra */ +#define PROTOPT_SSL (1<<0) /* uses SSL */ +#define PROTOPT_DUAL (1<<1) /* this protocol uses two connections */ +#define PROTOPT_CLOSEACTION (1<<2) /* need action before socket close */ +/* some protocols will have to call the underlying functions without regard to + what exact state the socket signals. IE even if the socket says "readable", + the send function might need to be called while uploading, or vice versa. +*/ +#define PROTOPT_DIRLOCK (1<<3) +#define PROTOPT_NONETWORK (1<<4) /* protocol doesn't use the network! */ +#define PROTOPT_NEEDSPWD (1<<5) /* needs a password, and if none is set it + gets a default */ +#define PROTOPT_NOURLQUERY (1<<6) /* protocol can't handle + url query strings (?foo=bar) ! */ +#define PROTOPT_CREDSPERREQUEST (1<<7) /* requires login credentials per + request instead of per connection */ +#define PROTOPT_ALPN (1<<8) /* set ALPN for this */ +/* (1<<9) was PROTOPT_STREAM, now free */ +#define PROTOPT_URLOPTIONS (1<<10) /* allow options part in the userinfo field + of the URL */ +#define PROTOPT_PROXY_AS_HTTP (1<<11) /* allow this non-HTTP scheme over a + HTTP proxy as HTTP proxies may know + this protocol and act as a gateway */ +#define PROTOPT_WILDCARD (1<<12) /* protocol supports wildcard matching */ +#define PROTOPT_USERPWDCTRL (1<<13) /* Allow "control bytes" (< 32 ascii) in + user name and password */ +#define PROTOPT_NOTCPPROXY (1<<14) /* this protocol can't proxy over TCP */ + +#define CONNCHECK_NONE 0 /* No checks */ +#define CONNCHECK_ISDEAD (1<<0) /* Check if the connection is dead. */ +#define CONNCHECK_KEEPALIVE (1<<1) /* Perform any keepalive function. */ + +#define CONNRESULT_NONE 0 /* No extra information. */ +#define CONNRESULT_DEAD (1<<0) /* The connection is dead. */ + +struct ip_quadruple { + char remote_ip[MAX_IPADR_LEN]; + char local_ip[MAX_IPADR_LEN]; + int remote_port; + int local_port; +}; + +struct proxy_info { + struct hostname host; + int port; + unsigned char proxytype; /* curl_proxytype: what kind of proxy that is in + use */ + char *user; /* proxy user name string, allocated */ + char *passwd; /* proxy password string, allocated */ +}; + +struct ldapconninfo; + +#define TRNSPRT_TCP 3 +#define TRNSPRT_UDP 4 +#define TRNSPRT_QUIC 5 +#define TRNSPRT_UNIX 6 + +/* + * The connectdata struct contains all fields and variables that should be + * unique for an entire connection. + */ +struct connectdata { + struct Curl_llist_element bundle_node; /* conncache */ + + curl_closesocket_callback fclosesocket; /* function closing the socket(s) */ + void *closesocket_client; + + /* This is used by the connection cache logic. If this returns TRUE, this + handle is still used by one or more easy handles and can only used by any + other easy handle without careful consideration (== only for + multiplexing) and it cannot be used by another multi handle! */ +#define CONN_INUSE(c) ((c)->easyq.size) + + /**** Fields set when inited and not modified again */ + curl_off_t connection_id; /* Contains a unique number to make it easier to + track the connections in the log output */ + + /* 'dns_entry' is the particular host we use. This points to an entry in the + DNS cache and it will not get pruned while locked. It gets unlocked in + multi_done(). This entry will be NULL if the connection is reused as then + there is no name resolve done. */ + struct Curl_dns_entry *dns_entry; + + /* 'remote_addr' is the particular IP we connected to. it is owned, set + * and NULLed by the connected socket filter (if there is one). */ + const struct Curl_sockaddr_ex *remote_addr; + + struct hostname host; + char *hostname_resolve; /* host name to resolve to address, allocated */ + char *secondaryhostname; /* secondary socket host name (ftp) */ + struct hostname conn_to_host; /* the host to connect to. valid only if + bits.conn_to_host is set */ +#ifndef CURL_DISABLE_PROXY + struct proxy_info socks_proxy; + struct proxy_info http_proxy; +#endif + /* 'primary' and 'secondary' get filled with IP quadruple + (local/remote numerical ip address and port) whenever a is *attempted*. + When more than one address is tried for a connection these will hold data + for the last attempt. When the connection is actually established + these are updated with data which comes directly from the socket. */ + struct ip_quadruple primary; + struct ip_quadruple secondary; + char *user; /* user name string, allocated */ + char *passwd; /* password string, allocated */ + char *options; /* options string, allocated */ + char *sasl_authzid; /* authorization identity string, allocated */ + char *oauth_bearer; /* OAUTH2 bearer, allocated */ + struct curltime now; /* "current" time */ + struct curltime created; /* creation time */ + struct curltime lastused; /* when returned to the connection cache */ + curl_socket_t sock[2]; /* two sockets, the second is used for the data + transfer when doing FTP */ + Curl_recv *recv[2]; + Curl_send *send[2]; + struct Curl_cfilter *cfilter[2]; /* connection filters */ + + struct ssl_primary_config ssl_config; +#ifndef CURL_DISABLE_PROXY + struct ssl_primary_config proxy_ssl_config; +#endif + struct ConnectBits bits; /* various state-flags for this connection */ + + const struct Curl_handler *handler; /* Connection's protocol handler */ + const struct Curl_handler *given; /* The protocol first given */ + + /* Protocols can use a custom keepalive mechanism to keep connections alive. + This allows those protocols to track the last time the keepalive mechanism + was used on this connection. */ + struct curltime keepalive; + + /**** curl_get() phase fields */ + + curl_socket_t sockfd; /* socket to read from or CURL_SOCKET_BAD */ + curl_socket_t writesockfd; /* socket to write to, it may very + well be the same we read from. + CURL_SOCKET_BAD disables */ + +#ifdef HAVE_GSSAPI + BIT(sec_complete); /* if Kerberos is enabled for this connection */ + unsigned char command_prot; /* enum protection_level */ + unsigned char data_prot; /* enum protection_level */ + unsigned char request_data_prot; /* enum protection_level */ + size_t buffer_size; + struct krb5buffer in_buffer; + void *app_data; + const struct Curl_sec_client_mech *mech; + struct sockaddr_in local_addr; +#endif + +#if defined(USE_KERBEROS5) /* Consider moving some of the above GSS-API */ + struct kerberos5data krb5; /* variables into the structure definition, */ +#endif /* however, some of them are ftp specific. */ + + struct Curl_llist easyq; /* List of easy handles using this connection */ + + /*************** Request - specific items ************/ +#if defined(USE_WINDOWS_SSPI) && defined(SECPKG_ATTR_ENDPOINT_BINDINGS) + CtxtHandle *sslContext; +#endif + +#if defined(_WIN32) && defined(USE_WINSOCK) + struct curltime last_sndbuf_update; /* last time readwrite_upload called + win_update_buffer_size */ +#endif + +#ifdef USE_GSASL + struct gsasldata gsasl; +#endif + +#if defined(USE_NTLM) + curlntlm http_ntlm_state; + curlntlm proxy_ntlm_state; + + struct ntlmdata ntlm; /* NTLM differs from other authentication schemes + because it authenticates connections, not + single requests! */ + struct ntlmdata proxyntlm; /* NTLM data for proxy */ +#endif + +#ifdef USE_SPNEGO + curlnegotiate http_negotiate_state; + curlnegotiate proxy_negotiate_state; + + struct negotiatedata negotiate; /* state data for host Negotiate auth */ + struct negotiatedata proxyneg; /* state data for proxy Negotiate auth */ +#endif + + union { +#ifndef CURL_DISABLE_FTP + struct ftp_conn ftpc; +#endif +#ifdef USE_SSH + struct ssh_conn sshc; +#endif +#ifndef CURL_DISABLE_TFTP + struct tftp_state_data *tftpc; +#endif +#ifndef CURL_DISABLE_IMAP + struct imap_conn imapc; +#endif +#ifndef CURL_DISABLE_POP3 + struct pop3_conn pop3c; +#endif +#ifndef CURL_DISABLE_SMTP + struct smtp_conn smtpc; +#endif +#ifndef CURL_DISABLE_RTSP + struct rtsp_conn rtspc; +#endif +#ifndef CURL_DISABLE_SMB + struct smb_conn smbc; +#endif +#ifdef USE_LIBRTMP + void *rtmp; +#endif +#ifdef USE_OPENLDAP + struct ldapconninfo *ldapc; +#endif +#ifndef CURL_DISABLE_MQTT + struct mqtt_conn mqtt; +#endif +#ifdef USE_WEBSOCKETS + struct websocket *ws; +#endif + unsigned int unused:1; /* avoids empty union */ + } proto; + + struct connectbundle *bundle; /* The bundle we are member of */ +#ifdef USE_UNIX_SOCKETS + char *unix_domain_socket; +#endif +#ifdef USE_HYPER + /* if set, an alternative data transfer function */ + Curl_datastream datastream; +#endif + /* When this connection is created, store the conditions for the local end + bind. This is stored before the actual bind and before any connection is + made and will serve the purpose of being used for comparison reasons so + that subsequent bound-requested connections aren't accidentally reusing + wrong connections. */ + char *localdev; + unsigned short localportrange; + int waitfor; /* current READ/WRITE bits to wait for */ +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + int socks5_gssapi_enctype; +#endif + /* The field below gets set in connect.c:connecthost() */ + int remote_port; /* the remote port, not the proxy port! */ + int conn_to_port; /* the remote port to connect to. valid only if + bits.conn_to_port is set */ +#ifdef USE_IPV6 + unsigned int scope_id; /* Scope id for IPv6 */ +#endif + unsigned short localport; + unsigned short secondary_port; /* secondary socket remote port to connect to + (ftp) */ + unsigned char alpn; /* APLN TLS negotiated protocol, a CURL_HTTP_VERSION* + value */ +#ifndef CURL_DISABLE_PROXY + unsigned char proxy_alpn; /* APLN of proxy tunnel, CURL_HTTP_VERSION* */ +#endif + unsigned char transport; /* one of the TRNSPRT_* defines */ + unsigned char ip_version; /* copied from the Curl_easy at creation time */ + unsigned char httpversion; /* the HTTP version*10 reported by the server */ + unsigned char connect_only; + unsigned char gssapi_delegation; /* inherited from set.gssapi_delegation */ +}; + +#ifndef CURL_DISABLE_PROXY +#define CURL_CONN_HOST_DISPNAME(c) \ + ((c)->bits.socksproxy ? (c)->socks_proxy.host.dispname : \ + (c)->bits.httpproxy ? (c)->http_proxy.host.dispname : \ + (c)->bits.conn_to_host ? (c)->conn_to_host.dispname : \ + (c)->host.dispname) +#else +#define CURL_CONN_HOST_DISPNAME(c) \ + (c)->bits.conn_to_host ? (c)->conn_to_host.dispname : \ + (c)->host.dispname +#endif + +/* The end of connectdata. */ + +/* + * Struct to keep statistical and informational data. + * All variables in this struct must be initialized/reset in Curl_initinfo(). + */ +struct PureInfo { + int httpcode; /* Recent HTTP, FTP, RTSP or SMTP response code */ + int httpproxycode; /* response code from proxy when received separate */ + int httpversion; /* the http version number X.Y = X*10+Y */ + time_t filetime; /* If requested, this is might get set. Set to -1 if the + time was unretrievable. */ + curl_off_t request_size; /* the amount of bytes sent in the request(s) */ + unsigned long proxyauthavail; /* what proxy auth types were announced */ + unsigned long httpauthavail; /* what host auth types were announced */ + long numconnects; /* how many new connection did libcurl created */ + char *contenttype; /* the content type of the object */ + char *wouldredirect; /* URL this would've been redirected to if asked to */ + curl_off_t retry_after; /* info from Retry-After: header */ + unsigned int header_size; /* size of read header(s) in bytes */ + + /* PureInfo primary ip_quadruple is copied over from the connectdata + struct in order to allow curl_easy_getinfo() to return this information + even when the session handle is no longer associated with a connection, + and also allow curl_easy_reset() to clear this information from the + session handle without disturbing information which is still alive, and + that might be reused, in the connection cache. */ + struct ip_quadruple primary; + int conn_remote_port; /* this is the "remote port", which is the port + number of the used URL, independent of proxy or + not */ + const char *conn_scheme; + unsigned int conn_protocol; + struct curl_certinfo certs; /* info about the certs. Asked for with + CURLOPT_CERTINFO / CURLINFO_CERTINFO */ + CURLproxycode pxcode; + BIT(timecond); /* set to TRUE if the time condition didn't match, which + thus made the document NOT get fetched */ + BIT(used_proxy); /* the transfer used a proxy */ +}; + + +struct Progress { + time_t lastshow; /* time() of the last displayed progress meter or NULL to + force redraw at next call */ + curl_off_t size_dl; /* total expected size */ + curl_off_t size_ul; /* total expected size */ + curl_off_t downloaded; /* transferred so far */ + curl_off_t uploaded; /* transferred so far */ + + curl_off_t current_speed; /* uses the currently fastest transfer */ + + int width; /* screen width at download start */ + int flags; /* see progress.h */ + + timediff_t timespent; + + curl_off_t dlspeed; + curl_off_t ulspeed; + + timediff_t t_postqueue; + timediff_t t_nslookup; + timediff_t t_connect; + timediff_t t_appconnect; + timediff_t t_pretransfer; + timediff_t t_starttransfer; + timediff_t t_redirect; + + struct curltime start; + struct curltime t_startsingle; + struct curltime t_startop; + struct curltime t_acceptdata; + + + /* upload speed limit */ + struct curltime ul_limit_start; + curl_off_t ul_limit_size; + /* download speed limit */ + struct curltime dl_limit_start; + curl_off_t dl_limit_size; + +#define CURR_TIME (5 + 1) /* 6 entries for 5 seconds */ + + curl_off_t speeder[ CURR_TIME ]; + struct curltime speeder_time[ CURR_TIME ]; + int speeder_c; + BIT(callback); /* set when progress callback is used */ + BIT(is_t_startransfer_set); +}; + +typedef enum { + RTSPREQ_NONE, /* first in list */ + RTSPREQ_OPTIONS, + RTSPREQ_DESCRIBE, + RTSPREQ_ANNOUNCE, + RTSPREQ_SETUP, + RTSPREQ_PLAY, + RTSPREQ_PAUSE, + RTSPREQ_TEARDOWN, + RTSPREQ_GET_PARAMETER, + RTSPREQ_SET_PARAMETER, + RTSPREQ_RECORD, + RTSPREQ_RECEIVE, + RTSPREQ_LAST /* last in list */ +} Curl_RtspReq; + +struct auth { + unsigned long want; /* Bitmask set to the authentication methods wanted by + app (with CURLOPT_HTTPAUTH or CURLOPT_PROXYAUTH). */ + unsigned long picked; + unsigned long avail; /* Bitmask for what the server reports to support for + this resource */ + BIT(done); /* TRUE when the auth phase is done and ready to do the + actual request */ + BIT(multipass); /* TRUE if this is not yet authenticated but within the + auth multipass negotiation */ + BIT(iestyle); /* TRUE if digest should be done IE-style or FALSE if it + should be RFC compliant */ +}; + +#ifdef USE_NGHTTP2 +struct Curl_data_prio_node { + struct Curl_data_prio_node *next; + struct Curl_easy *data; +}; +#endif + +/** + * Priority information for an easy handle in relation to others + * on the same connection. + * TODO: we need to adapt it to the new priority scheme as defined in RFC 9218 + */ +struct Curl_data_priority { +#ifdef USE_NGHTTP2 + /* tree like dependencies only implemented in nghttp2 */ + struct Curl_easy *parent; + struct Curl_data_prio_node *children; +#endif + int weight; +#ifdef USE_NGHTTP2 + BIT(exclusive); +#endif +}; + +/* Timers */ +typedef enum { + EXPIRE_100_TIMEOUT, + EXPIRE_ASYNC_NAME, + EXPIRE_CONNECTTIMEOUT, + EXPIRE_DNS_PER_NAME, /* family1 */ + EXPIRE_DNS_PER_NAME2, /* family2 */ + EXPIRE_HAPPY_EYEBALLS_DNS, /* See asyn-ares.c */ + EXPIRE_HAPPY_EYEBALLS, + EXPIRE_MULTI_PENDING, + EXPIRE_RUN_NOW, + EXPIRE_SPEEDCHECK, + EXPIRE_TIMEOUT, + EXPIRE_TOOFAST, + EXPIRE_QUIC, + EXPIRE_FTP_ACCEPT, + EXPIRE_ALPN_EYEBALLS, + EXPIRE_LAST /* not an actual timer, used as a marker only */ +} expire_id; + + +typedef enum { + TRAILERS_NONE, + TRAILERS_INITIALIZED, + TRAILERS_SENDING, + TRAILERS_DONE +} trailers_state; + + +/* + * One instance for each timeout an easy handle can set. + */ +struct time_node { + struct Curl_llist_element list; + struct curltime time; + expire_id eid; +}; + +/* individual pieces of the URL */ +struct urlpieces { + char *scheme; + char *hostname; + char *port; + char *user; + char *password; + char *options; + char *path; + char *query; +}; + +struct UrlState { + /* Points to the connection cache */ + struct conncache *conn_cache; + /* buffers to store authentication data in, as parsed from input options */ + struct curltime keeps_speed; /* for the progress meter really */ + + curl_off_t lastconnect_id; /* The last connection, -1 if undefined */ + curl_off_t recent_conn_id; /* The most recent connection used, might no + * longer exist */ + struct dynbuf headerb; /* buffer to store headers in */ + struct curl_slist *hstslist; /* list of HSTS files set by + curl_easy_setopt(HSTS) calls */ + curl_off_t current_speed; /* the ProgressShow() function sets this, + bytes / second */ + + /* host name, port number and protocol of the first (not followed) request. + if set, this should be the host name that we will sent authorization to, + no else. Used to make Location: following not keep sending user+password. + This is strdup()ed data. */ + char *first_host; + int first_remote_port; + curl_prot_t first_remote_protocol; + + int retrycount; /* number of retries on a new connection */ + struct Curl_ssl_session *session; /* array of 'max_ssl_sessions' size */ + long sessionage; /* number of the most recent session */ + int os_errno; /* filled in with errno whenever an error occurs */ + char *scratch; /* huge buffer[set.buffer_size*2] for upload CRLF replacing */ + long followlocation; /* redirect counter */ + int requests; /* request counter: redirects + authentication retakes */ +#ifdef HAVE_SIGNAL + /* storage for the previous bag^H^H^HSIGPIPE signal handler :-) */ + void (*prev_signal)(int sig); +#endif +#ifndef CURL_DISABLE_DIGEST_AUTH + struct digestdata digest; /* state data for host Digest auth */ + struct digestdata proxydigest; /* state data for proxy Digest auth */ +#endif + struct auth authhost; /* auth details for host */ + struct auth authproxy; /* auth details for proxy */ +#ifdef USE_CURL_ASYNC + struct Curl_async async; /* asynchronous name resolver data */ +#endif + +#if defined(USE_OPENSSL) + /* void instead of ENGINE to avoid bleeding OpenSSL into this header */ + void *engine; +#endif /* USE_OPENSSL */ + struct curltime expiretime; /* set this with Curl_expire() only */ + struct Curl_tree timenode; /* for the splay stuff */ + struct Curl_llist timeoutlist; /* list of pending timeouts */ + struct time_node expires[EXPIRE_LAST]; /* nodes for each expire type */ + + /* a place to store the most recently set (S)FTP entrypath */ + char *most_recent_ftp_entrypath; +#if !defined(_WIN32) && !defined(MSDOS) && !defined(__EMX__) +/* do FTP line-end conversions on most platforms */ +#define CURL_DO_LINEEND_CONV + /* for FTP downloads: how many CRLFs did we converted to LFs? */ + curl_off_t crlf_conversions; +#endif + char *range; /* range, if used. See README for detailed specification on + this syntax. */ + curl_off_t resume_from; /* continue [ftp] transfer from here */ + +#ifndef CURL_DISABLE_RTSP + /* This RTSP state information survives requests and connections */ + long rtsp_next_client_CSeq; /* the session's next client CSeq */ + long rtsp_next_server_CSeq; /* the session's next server CSeq */ + long rtsp_CSeq_recv; /* most recent CSeq received */ + + unsigned char rtp_channel_mask[32]; /* for the correctness checking of the + interleaved data */ +#endif + + curl_off_t infilesize; /* size of file to upload, -1 means unknown. + Copied from set.filesize at start of operation */ +#if defined(USE_HTTP2) || defined(USE_HTTP3) + struct Curl_data_priority priority; /* shallow copy of data->set */ +#endif + + curl_read_callback fread_func; /* read callback/function */ + void *in; /* CURLOPT_READDATA */ + CURLU *uh; /* URL handle for the current parsed URL */ + struct urlpieces up; + char *url; /* work URL, copied from UserDefined */ + char *referer; /* referer string */ + struct curl_slist *resolve; /* set to point to the set.resolve list when + this should be dealt with in pretransfer */ +#ifndef CURL_DISABLE_HTTP + curl_mimepart *mimepost; +#ifndef CURL_DISABLE_FORM_API + curl_mimepart *formp; /* storage for old API form-posting, allocated on + demand */ +#endif + size_t trailers_bytes_sent; + struct dynbuf trailers_buf; /* a buffer containing the compiled trailing + headers */ + struct Curl_llist httphdrs; /* received headers */ + struct curl_header headerout[2]; /* for external purposes */ + struct Curl_header_store *prevhead; /* the latest added header */ + trailers_state trailers_state; /* whether we are sending trailers + and what stage are we at */ +#endif +#ifndef CURL_DISABLE_COOKIES + struct curl_slist *cookielist; /* list of cookie files set by + curl_easy_setopt(COOKIEFILE) calls */ +#endif +#ifdef USE_HYPER + bool hconnect; /* set if a CONNECT request */ + CURLcode hresult; /* used to pass return codes back from hyper callbacks */ +#endif + +#ifndef CURL_DISABLE_VERBOSE_STRINGS + struct curl_trc_feat *feat; /* opt. trace feature transfer is part of */ +#endif + + /* Dynamically allocated strings, MUST be freed before this struct is + killed. */ + struct dynamically_allocated_data { + char *uagent; + char *accept_encoding; + char *userpwd; + char *rangeline; + char *ref; + char *host; +#ifndef CURL_DISABLE_COOKIES + char *cookiehost; +#endif +#ifndef CURL_DISABLE_RTSP + char *rtsp_transport; +#endif + char *te; /* TE: request header */ + + /* transfer credentials */ + char *user; + char *passwd; +#ifndef CURL_DISABLE_PROXY + char *proxyuserpwd; + char *proxyuser; + char *proxypasswd; +#endif + } aptr; + + unsigned char httpwant; /* when non-zero, a specific HTTP version requested + to be used in the library's request(s) */ + unsigned char httpversion; /* the lowest HTTP version*10 reported by any + server involved in this request */ + unsigned char httpreq; /* Curl_HttpReq; what kind of HTTP request (if any) + is this */ + unsigned char select_bits; /* != 0 -> bitmask of socket events for this + transfer overriding anything the socket may + report */ +#ifdef CURLDEBUG + BIT(conncache_lock); +#endif + /* when curl_easy_perform() is called, the multi handle is "owned" by + the easy handle so curl_easy_cleanup() on such an easy handle will + also close the multi handle! */ + BIT(multi_owned_by_easy); + + BIT(this_is_a_follow); /* this is a followed Location: request */ + BIT(refused_stream); /* this was refused, try again */ + BIT(errorbuf); /* Set to TRUE if the error buffer is already filled in. + This must be set to FALSE every time _easy_perform() is + called. */ + BIT(allow_port); /* Is set.use_port allowed to take effect or not. This + is always set TRUE when curl_easy_perform() is called. */ + BIT(authproblem); /* TRUE if there's some problem authenticating */ + /* set after initial USER failure, to prevent an authentication loop */ + BIT(wildcardmatch); /* enable wildcard matching */ + BIT(disableexpect); /* TRUE if Expect: is disabled due to a previous + 417 response */ + BIT(use_range); + BIT(rangestringalloc); /* the range string is malloc()'ed */ + BIT(done); /* set to FALSE when Curl_init_do() is called and set to TRUE + when multi_done() is called, to prevent multi_done() to get + invoked twice when the multi interface is used. */ +#ifndef CURL_DISABLE_COOKIES + BIT(cookie_engine); +#endif + BIT(prefer_ascii); /* ASCII rather than binary */ +#ifdef CURL_LIST_ONLY_PROTOCOL + BIT(list_only); /* list directory contents */ +#endif + BIT(url_alloc); /* URL string is malloc()'ed */ + BIT(referer_alloc); /* referer string is malloc()ed */ + BIT(wildcard_resolve); /* Set to true if any resolve change is a wildcard */ + BIT(upload); /* upload request */ + BIT(internal); /* internal: true if this easy handle was created for + internal use and the user does not have ownership of the + handle. */ +}; + +/* + * This 'UserDefined' struct must only contain data that is set once to go + * for many (perhaps) independent connections. Values that are generated or + * calculated internally for the "session handle" MUST be defined within the + * 'struct UrlState' instead. The only exceptions MUST note the changes in + * the 'DynamicStatic' struct. + * Character pointer fields point to dynamic storage, unless otherwise stated. + */ + +struct Curl_multi; /* declared in multihandle.c */ + +enum dupstring { + STRING_CERT, /* client certificate file name */ + STRING_CERT_TYPE, /* format for certificate (default: PEM)*/ + STRING_KEY, /* private key file name */ + STRING_KEY_PASSWD, /* plain text private key password */ + STRING_KEY_TYPE, /* format for private key (default: PEM) */ + STRING_SSL_CAPATH, /* CA directory name (doesn't work on windows) */ + STRING_SSL_CAFILE, /* certificate file to verify peer against */ + STRING_SSL_PINNEDPUBLICKEY, /* public key file to verify peer against */ + STRING_SSL_CIPHER_LIST, /* list of ciphers to use */ + STRING_SSL_CIPHER13_LIST, /* list of TLS 1.3 ciphers to use */ + STRING_SSL_CRLFILE, /* crl file to check certificate */ + STRING_SSL_ISSUERCERT, /* issuer cert file to check certificate */ + STRING_SERVICE_NAME, /* Service name */ +#ifndef CURL_DISABLE_PROXY + STRING_CERT_PROXY, /* client certificate file name */ + STRING_CERT_TYPE_PROXY, /* format for certificate (default: PEM)*/ + STRING_KEY_PROXY, /* private key file name */ + STRING_KEY_PASSWD_PROXY, /* plain text private key password */ + STRING_KEY_TYPE_PROXY, /* format for private key (default: PEM) */ + STRING_SSL_CAPATH_PROXY, /* CA directory name (doesn't work on windows) */ + STRING_SSL_CAFILE_PROXY, /* certificate file to verify peer against */ + STRING_SSL_PINNEDPUBLICKEY_PROXY, /* public key file to verify proxy */ + STRING_SSL_CIPHER_LIST_PROXY, /* list of ciphers to use */ + STRING_SSL_CIPHER13_LIST_PROXY, /* list of TLS 1.3 ciphers to use */ + STRING_SSL_CRLFILE_PROXY, /* crl file to check certificate */ + STRING_SSL_ISSUERCERT_PROXY, /* issuer cert file to check certificate */ + STRING_PROXY_SERVICE_NAME, /* Proxy service name */ +#endif +#ifndef CURL_DISABLE_COOKIES + STRING_COOKIE, /* HTTP cookie string to send */ + STRING_COOKIEJAR, /* dump all cookies to this file */ +#endif + STRING_CUSTOMREQUEST, /* HTTP/FTP/RTSP request/method to use */ + STRING_DEFAULT_PROTOCOL, /* Protocol to use when the URL doesn't specify */ + STRING_DEVICE, /* local network interface/address to use */ + STRING_ENCODING, /* Accept-Encoding string */ +#ifndef CURL_DISABLE_FTP + STRING_FTP_ACCOUNT, /* ftp account data */ + STRING_FTP_ALTERNATIVE_TO_USER, /* command to send if USER/PASS fails */ + STRING_FTPPORT, /* port to send with the FTP PORT command */ +#endif +#if defined(HAVE_GSSAPI) + STRING_KRB_LEVEL, /* krb security level */ +#endif +#ifndef CURL_DISABLE_NETRC + STRING_NETRC_FILE, /* if not NULL, use this instead of trying to find + $HOME/.netrc */ +#endif +#ifndef CURL_DISABLE_PROXY + STRING_PROXY, /* proxy to use */ + STRING_PRE_PROXY, /* pre socks proxy to use */ +#endif + STRING_SET_RANGE, /* range, if used */ + STRING_SET_REFERER, /* custom string for the HTTP referer field */ + STRING_SET_URL, /* what original URL to work on */ + STRING_USERAGENT, /* User-Agent string */ + STRING_SSL_ENGINE, /* name of ssl engine */ + STRING_USERNAME, /* , if used */ + STRING_PASSWORD, /* , if used */ + STRING_OPTIONS, /* , if used */ +#ifndef CURL_DISABLE_PROXY + STRING_PROXYUSERNAME, /* Proxy , if used */ + STRING_PROXYPASSWORD, /* Proxy , if used */ + STRING_NOPROXY, /* List of hosts which should not use the proxy, if + used */ +#endif +#ifndef CURL_DISABLE_RTSP + STRING_RTSP_SESSION_ID, /* Session ID to use */ + STRING_RTSP_STREAM_URI, /* Stream URI for this request */ + STRING_RTSP_TRANSPORT, /* Transport for this session */ +#endif +#ifdef USE_SSH + STRING_SSH_PRIVATE_KEY, /* path to the private key file for auth */ + STRING_SSH_PUBLIC_KEY, /* path to the public key file for auth */ + STRING_SSH_HOST_PUBLIC_KEY_MD5, /* md5 of host public key in ascii hex */ + STRING_SSH_HOST_PUBLIC_KEY_SHA256, /* sha256 of host public key in base64 */ + STRING_SSH_KNOWNHOSTS, /* file name of knownhosts file */ +#endif +#ifndef CURL_DISABLE_SMTP + STRING_MAIL_FROM, + STRING_MAIL_AUTH, +#endif +#ifdef USE_TLS_SRP + STRING_TLSAUTH_USERNAME, /* TLS auth */ + STRING_TLSAUTH_PASSWORD, /* TLS auth */ +#ifndef CURL_DISABLE_PROXY + STRING_TLSAUTH_USERNAME_PROXY, /* TLS auth */ + STRING_TLSAUTH_PASSWORD_PROXY, /* TLS auth */ +#endif +#endif + STRING_BEARER, /* , if used */ +#ifdef USE_UNIX_SOCKETS + STRING_UNIX_SOCKET_PATH, /* path to Unix socket, if used */ +#endif + STRING_TARGET, /* CURLOPT_REQUEST_TARGET */ +#ifndef CURL_DISABLE_DOH + STRING_DOH, /* CURLOPT_DOH_URL */ +#endif +#ifndef CURL_DISABLE_ALTSVC + STRING_ALTSVC, /* CURLOPT_ALTSVC */ +#endif +#ifndef CURL_DISABLE_HSTS + STRING_HSTS, /* CURLOPT_HSTS */ +#endif + STRING_SASL_AUTHZID, /* CURLOPT_SASL_AUTHZID */ +#ifdef USE_ARES + STRING_DNS_SERVERS, + STRING_DNS_INTERFACE, + STRING_DNS_LOCAL_IP4, + STRING_DNS_LOCAL_IP6, +#endif + STRING_SSL_EC_CURVES, +#ifndef CURL_DISABLE_AWS + STRING_AWS_SIGV4, /* Parameters for V4 signature */ +#endif +#ifndef CURL_DISABLE_PROXY + STRING_HAPROXY_CLIENT_IP, /* CURLOPT_HAPROXY_CLIENT_IP */ +#endif + STRING_ECH_CONFIG, /* CURLOPT_ECH_CONFIG */ + STRING_ECH_PUBLIC, /* CURLOPT_ECH_PUBLIC */ + + /* -- end of null-terminated strings -- */ + + STRING_LASTZEROTERMINATED, + + /* -- below this are pointers to binary data that cannot be strdup'ed. --- */ + + STRING_COPYPOSTFIELDS, /* if POST, set the fields' values here */ + + STRING_LAST /* not used, just an end-of-list marker */ +}; + +enum dupblob { + BLOB_CERT, + BLOB_KEY, + BLOB_SSL_ISSUERCERT, + BLOB_CAINFO, +#ifndef CURL_DISABLE_PROXY + BLOB_CERT_PROXY, + BLOB_KEY_PROXY, + BLOB_SSL_ISSUERCERT_PROXY, + BLOB_CAINFO_PROXY, +#endif + BLOB_LAST +}; + +/* callback that gets called when this easy handle is completed within a multi + handle. Only used for internally created transfers, like for example + DoH. */ +typedef int (*multidone_func)(struct Curl_easy *easy, CURLcode result); + +struct UserDefined { + FILE *err; /* the stderr user data goes here */ + void *debugdata; /* the data that will be passed to fdebug */ + char *errorbuffer; /* (Static) store failure messages in here */ + void *out; /* CURLOPT_WRITEDATA */ + void *in_set; /* CURLOPT_READDATA */ + void *writeheader; /* write the header to this if non-NULL */ + unsigned short use_port; /* which port to use (when not using default) */ + unsigned long httpauth; /* kind of HTTP authentication to use (bitmask) */ + unsigned long proxyauth; /* kind of proxy authentication to use (bitmask) */ + long maxredirs; /* maximum no. of http(s) redirects to follow, set to -1 + for infinity */ + + void *postfields; /* if POST, set the fields' values here */ + curl_seek_callback seek_func; /* function that seeks the input */ + curl_off_t postfieldsize; /* if POST, this might have a size to use instead + of strlen(), and then the data *may* be binary + (contain zero bytes) */ +#ifndef CURL_DISABLE_BINDLOCAL + unsigned short localport; /* local port number to bind to */ + unsigned short localportrange; /* number of additional port numbers to test + in case the 'localport' one can't be + bind()ed */ +#endif + curl_write_callback fwrite_func; /* function that stores the output */ + curl_write_callback fwrite_header; /* function that stores headers */ + curl_write_callback fwrite_rtp; /* function that stores interleaved RTP */ + curl_read_callback fread_func_set; /* function that reads the input */ + curl_progress_callback fprogress; /* OLD and deprecated progress callback */ + curl_xferinfo_callback fxferinfo; /* progress callback */ + curl_debug_callback fdebug; /* function that write informational data */ + curl_ioctl_callback ioctl_func; /* function for I/O control */ + curl_sockopt_callback fsockopt; /* function for setting socket options */ + void *sockopt_client; /* pointer to pass to the socket options callback */ + curl_opensocket_callback fopensocket; /* function for checking/translating + the address and opening the + socket */ + void *opensocket_client; + curl_closesocket_callback fclosesocket; /* function for closing the + socket */ + void *closesocket_client; + curl_prereq_callback fprereq; /* pre-initial request callback */ + void *prereq_userp; /* pre-initial request user data */ + + void *seek_client; /* pointer to pass to the seek callback */ +#ifndef CURL_DISABLE_HSTS + curl_hstsread_callback hsts_read; + void *hsts_read_userp; + curl_hstswrite_callback hsts_write; + void *hsts_write_userp; +#endif + void *progress_client; /* pointer to pass to the progress callback */ + void *ioctl_client; /* pointer to pass to the ioctl callback */ + unsigned int timeout; /* ms, 0 means no timeout */ + unsigned int connecttimeout; /* ms, 0 means no timeout */ + unsigned int happy_eyeballs_timeout; /* ms, 0 is a valid value */ + unsigned int server_response_timeout; /* ms, 0 means no timeout */ + long maxage_conn; /* in seconds, max idle time to allow a connection that + is to be reused */ + long maxlifetime_conn; /* in seconds, max time since creation to allow a + connection that is to be reused */ +#ifndef CURL_DISABLE_TFTP + long tftp_blksize; /* in bytes, 0 means use default */ +#endif + curl_off_t filesize; /* size of file to upload, -1 means unknown */ + long low_speed_limit; /* bytes/second */ + long low_speed_time; /* number of seconds */ + curl_off_t max_send_speed; /* high speed limit in bytes/second for upload */ + curl_off_t max_recv_speed; /* high speed limit in bytes/second for + download */ + curl_off_t set_resume_from; /* continue [ftp] transfer from here */ + struct curl_slist *headers; /* linked list of extra headers */ + struct curl_httppost *httppost; /* linked list of old POST data */ +#if !defined(CURL_DISABLE_MIME) || !defined(CURL_DISABLE_FORM_API) + curl_mimepart mimepost; /* MIME/POST data. */ +#endif +#ifndef CURL_DISABLE_TELNET + struct curl_slist *telnet_options; /* linked list of telnet options */ +#endif + struct curl_slist *resolve; /* list of names to add/remove from + DNS cache */ + struct curl_slist *connect_to; /* list of host:port mappings to override + the hostname and port to connect to */ + time_t timevalue; /* what time to compare with */ + unsigned char timecondition; /* kind of time comparison: curl_TimeCond */ + unsigned char method; /* what kind of HTTP request: Curl_HttpReq */ + unsigned char httpwant; /* when non-zero, a specific HTTP version requested + to be used in the library's request(s) */ + struct ssl_config_data ssl; /* user defined SSL stuff */ +#ifndef CURL_DISABLE_PROXY + struct ssl_config_data proxy_ssl; /* user defined SSL stuff for proxy */ + struct curl_slist *proxyheaders; /* linked list of extra CONNECT headers */ + unsigned short proxyport; /* If non-zero, use this port number by + default. If the proxy string features a + ":[port]" that one will override this. */ + unsigned char proxytype; /* what kind of proxy: curl_proxytype */ + unsigned char socks5auth;/* kind of SOCKS5 authentication to use (bitmask) */ +#endif + struct ssl_general_config general_ssl; /* general user defined SSL stuff */ + int dns_cache_timeout; /* DNS cache timeout (seconds) */ + unsigned int buffer_size; /* size of receive buffer to use */ + unsigned int upload_buffer_size; /* size of upload buffer to use, + keep it >= CURL_MAX_WRITE_SIZE */ + void *private_data; /* application-private data */ +#ifndef CURL_DISABLE_HTTP + struct curl_slist *http200aliases; /* linked list of aliases for http200 */ +#endif + unsigned char ipver; /* the CURL_IPRESOLVE_* defines in the public header + file 0 - whatever, 1 - v2, 2 - v6 */ + curl_off_t max_filesize; /* Maximum file size to download */ +#ifndef CURL_DISABLE_FTP + unsigned char ftp_filemethod; /* how to get to a file: curl_ftpfile */ + unsigned char ftpsslauth; /* what AUTH XXX to try: curl_ftpauth */ + unsigned char ftp_ccc; /* FTP CCC options: curl_ftpccc */ + unsigned int accepttimeout; /* in milliseconds, 0 means no timeout */ +#endif +#if !defined(CURL_DISABLE_FTP) || defined(USE_SSH) + struct curl_slist *quote; /* after connection is established */ + struct curl_slist *postquote; /* after the transfer */ + struct curl_slist *prequote; /* before the transfer, after type */ + /* Despite the name, ftp_create_missing_dirs is for FTP(S) and SFTP + 1 - create directories that don't exist + 2 - the same but also allow MKD to fail once + */ + unsigned char ftp_create_missing_dirs; +#endif +#ifdef USE_LIBSSH2 + curl_sshhostkeycallback ssh_hostkeyfunc; /* hostkey check callback */ + void *ssh_hostkeyfunc_userp; /* custom pointer to callback */ +#endif +#ifdef USE_SSH + curl_sshkeycallback ssh_keyfunc; /* key matching callback */ + void *ssh_keyfunc_userp; /* custom pointer to callback */ + int ssh_auth_types; /* allowed SSH auth types */ + unsigned int new_directory_perms; /* when creating remote dirs */ +#endif +#ifndef CURL_DISABLE_NETRC + unsigned char use_netrc; /* enum CURL_NETRC_OPTION values */ +#endif + unsigned int new_file_perms; /* when creating remote files */ + char *str[STRING_LAST]; /* array of strings, pointing to allocated memory */ + struct curl_blob *blobs[BLOB_LAST]; +#ifdef USE_IPV6 + unsigned int scope_id; /* Scope id for IPv6 */ +#endif + curl_prot_t allowed_protocols; + curl_prot_t redir_protocols; +#ifndef CURL_DISABLE_RTSP + void *rtp_out; /* write RTP to this if non-NULL */ + /* Common RTSP header options */ + Curl_RtspReq rtspreq; /* RTSP request type */ +#endif +#ifndef CURL_DISABLE_FTP + curl_chunk_bgn_callback chunk_bgn; /* called before part of transfer + starts */ + curl_chunk_end_callback chunk_end; /* called after part transferring + stopped */ + curl_fnmatch_callback fnmatch; /* callback to decide which file corresponds + to pattern (e.g. if WILDCARDMATCH is on) */ + void *fnmatch_data; + void *wildcardptr; +#endif + /* GSS-API credential delegation, see the documentation of + CURLOPT_GSSAPI_DELEGATION */ + unsigned char gssapi_delegation; + + int tcp_keepidle; /* seconds in idle before sending keepalive probe */ + int tcp_keepintvl; /* seconds between TCP keepalive probes */ + + long expect_100_timeout; /* in milliseconds */ +#if defined(USE_HTTP2) || defined(USE_HTTP3) + struct Curl_data_priority priority; +#endif + curl_resolver_start_callback resolver_start; /* optional callback called + before resolver start */ + void *resolver_start_client; /* pointer to pass to resolver start callback */ + long upkeep_interval_ms; /* Time between calls for connection upkeep. */ + multidone_func fmultidone; +#ifndef CURL_DISABLE_DOH + struct Curl_easy *dohfor; /* this is a DoH request for that transfer */ +#endif + CURLU *uh; /* URL handle for the current parsed URL */ +#ifndef CURL_DISABLE_HTTP + void *trailer_data; /* pointer to pass to trailer data callback */ + curl_trailer_callback trailer_callback; /* trailing data callback */ +#endif + char keep_post; /* keep POSTs as POSTs after a 30x request; each + bit represents a request, from 301 to 303 */ +#ifndef CURL_DISABLE_SMTP + struct curl_slist *mail_rcpt; /* linked list of mail recipients */ + BIT(mail_rcpt_allowfails); /* allow RCPT TO command to fail for some + recipients */ +#endif + unsigned int maxconnects; /* Max idle connections in the connection cache */ + unsigned char use_ssl; /* if AUTH TLS is to be attempted etc, for FTP or + IMAP or POP3 or others! (type: curl_usessl)*/ + unsigned char connect_only; /* make connection/request, then let + application use the socket */ +#ifndef CURL_DISABLE_MIME + BIT(mime_formescape); +#endif + BIT(is_fread_set); /* has read callback been set to non-NULL? */ +#ifndef CURL_DISABLE_TFTP + BIT(tftp_no_options); /* do not send TFTP options requests */ +#endif + BIT(sep_headers); /* handle host and proxy headers separately */ +#ifndef CURL_DISABLE_COOKIES + BIT(cookiesession); /* new cookie session? */ +#endif + BIT(crlf); /* convert crlf on ftp upload(?) */ +#ifdef USE_SSH + BIT(ssh_compression); /* enable SSH compression */ +#endif + +/* Here follows boolean settings that define how to behave during + this session. They are STATIC, set by libcurl users or at least initially + and they don't change during operations. */ + BIT(quick_exit); /* set 1L when it is okay to leak things (like + threads), as we're about to exit() anyway and + don't want lengthy cleanups to delay termination, + e.g. after a DNS timeout */ + BIT(get_filetime); /* get the time and get of the remote file */ +#ifndef CURL_DISABLE_PROXY + BIT(tunnel_thru_httpproxy); /* use CONNECT through an HTTP proxy */ +#endif + BIT(prefer_ascii); /* ASCII rather than binary */ + BIT(remote_append); /* append, not overwrite, on upload */ +#ifdef CURL_LIST_ONLY_PROTOCOL + BIT(list_only); /* list directory */ +#endif +#ifndef CURL_DISABLE_FTP + BIT(ftp_use_port); /* use the FTP PORT command */ + BIT(ftp_use_epsv); /* if EPSV is to be attempted or not */ + BIT(ftp_use_eprt); /* if EPRT is to be attempted or not */ + BIT(ftp_use_pret); /* if PRET is to be used before PASV or not */ + BIT(ftp_skip_ip); /* skip the IP address the FTP server passes on to + us */ + BIT(wildcard_enabled); /* enable wildcard matching */ +#endif + BIT(hide_progress); /* don't use the progress meter */ + BIT(http_fail_on_error); /* fail on HTTP error codes >= 400 */ + BIT(http_keep_sending_on_error); /* for HTTP status codes >= 300 */ + BIT(http_follow_location); /* follow HTTP redirects */ + BIT(http_transfer_encoding); /* request compressed HTTP transfer-encoding */ + BIT(allow_auth_to_other_hosts); + BIT(include_header); /* include received protocol headers in data output */ + BIT(http_set_referer); /* is a custom referer used */ + BIT(http_auto_referer); /* set "correct" referer when following + location: */ + BIT(opt_no_body); /* as set with CURLOPT_NOBODY */ + BIT(verbose); /* output verbosity */ +#if defined(HAVE_GSSAPI) + BIT(krb); /* Kerberos connection requested */ +#endif + BIT(reuse_forbid); /* forbidden to be reused, close after use */ + BIT(reuse_fresh); /* do not reuse an existing connection */ + BIT(no_signal); /* do not use any signal/alarm handler */ + BIT(tcp_nodelay); /* whether to enable TCP_NODELAY or not */ + BIT(ignorecl); /* ignore content length */ + BIT(http_te_skip); /* pass the raw body data to the user, even when + transfer-encoded (chunked, compressed) */ + BIT(http_ce_skip); /* pass the raw body data to the user, even when + content-encoded (chunked, compressed) */ + BIT(proxy_transfer_mode); /* set transfer mode (;type=) when doing + FTP via an HTTP proxy */ +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + BIT(socks5_gssapi_nec); /* Flag to support NEC SOCKS5 server */ +#endif + BIT(sasl_ir); /* Enable/disable SASL initial response */ + BIT(tcp_keepalive); /* use TCP keepalives */ + BIT(tcp_fastopen); /* use TCP Fast Open */ + BIT(ssl_enable_alpn);/* TLS ALPN extension? */ + BIT(path_as_is); /* allow dotdots? */ + BIT(pipewait); /* wait for multiplex status before starting a new + connection */ + BIT(suppress_connect_headers); /* suppress proxy CONNECT response headers + from user callbacks */ + BIT(dns_shuffle_addresses); /* whether to shuffle addresses before use */ +#ifndef CURL_DISABLE_PROXY + BIT(haproxyprotocol); /* whether to send HAProxy PROXY protocol v1 + header */ +#endif +#ifdef USE_UNIX_SOCKETS + BIT(abstract_unix_socket); +#endif + BIT(disallow_username_in_url); /* disallow username in url */ +#ifndef CURL_DISABLE_DOH + BIT(doh); /* DNS-over-HTTPS enabled */ + BIT(doh_verifypeer); /* DoH certificate peer verification */ + BIT(doh_verifyhost); /* DoH certificate hostname verification */ + BIT(doh_verifystatus); /* DoH certificate status verification */ +#endif + BIT(http09_allowed); /* allow HTTP/0.9 responses */ +#ifdef USE_WEBSOCKETS + BIT(ws_raw_mode); +#endif +#ifdef USE_ECH + int tls_ech; /* TLS ECH configuration */ +#endif +}; + +#ifndef CURL_DISABLE_MIME +#define IS_MIME_POST(a) ((a)->set.mimepost.kind != MIMEKIND_NONE) +#else +#define IS_MIME_POST(a) FALSE +#endif + +struct Names { + struct Curl_hash *hostcache; + enum { + HCACHE_NONE, /* not pointing to anything */ + HCACHE_MULTI, /* points to a shared one in the multi handle */ + HCACHE_SHARED /* points to a shared one in a shared object */ + } hostcachetype; +}; + +/* + * The 'connectdata' struct MUST have all the connection oriented stuff as we + * may have several simultaneous connections and connection structs in memory. + * + * The 'struct UserDefined' must only contain data that is set once to go for + * many (perhaps) independent connections. Values that are generated or + * calculated internally for the "session handle" must be defined within the + * 'struct UrlState' instead. + */ + +struct Curl_easy { + /* First a simple identifier to easier detect if a user mix up this easy + handle with a multi handle. Set this to CURLEASY_MAGIC_NUMBER */ + unsigned int magic; + /* once an easy handle is tied to a connection cache + a non-negative number to distinguish this transfer from + other using the same cache. For easier tracking + in log output. + This may wrap around after LONG_MAX to 0 again, so it + has no uniqueness guarantee for very large processings. */ + curl_off_t id; + + /* first, two fields for the linked list of these */ + struct Curl_easy *next; + struct Curl_easy *prev; + + struct connectdata *conn; + struct Curl_llist_element connect_queue; /* for the pending and msgsent + lists */ + struct Curl_llist_element conn_queue; /* list per connectdata */ + + CURLMstate mstate; /* the handle's state */ + CURLcode result; /* previous result */ + + struct Curl_message msg; /* A single posted message. */ + + /* Array with the plain socket numbers this handle takes care of, in no + particular order. Note that all sockets are added to the sockhash, where + the state etc are also kept. This array is mostly used to detect when a + socket is to be removed from the hash. See singlesocket(). */ + struct easy_pollset last_poll; + + struct Names dns; + struct Curl_multi *multi; /* if non-NULL, points to the multi handle + struct to which this "belongs" when used by + the multi interface */ + struct Curl_multi *multi_easy; /* if non-NULL, points to the multi handle + struct to which this "belongs" when used + by the easy interface */ + struct Curl_share *share; /* Share, handles global variable mutexing */ +#ifdef USE_LIBPSL + struct PslCache *psl; /* The associated PSL cache. */ +#endif + struct SingleRequest req; /* Request-specific data */ + struct UserDefined set; /* values set by the libcurl user */ +#ifndef CURL_DISABLE_COOKIES + struct CookieInfo *cookies; /* the cookies, read from files and servers. + NOTE that the 'cookie' field in the + UserDefined struct defines if the "engine" + is to be used or not. */ +#endif +#ifndef CURL_DISABLE_HSTS + struct hsts *hsts; +#endif +#ifndef CURL_DISABLE_ALTSVC + struct altsvcinfo *asi; /* the alt-svc cache */ +#endif + struct Progress progress; /* for all the progress meter data */ + struct UrlState state; /* struct for fields used for state info and + other dynamic purposes */ +#ifndef CURL_DISABLE_FTP + struct WildcardData *wildcard; /* wildcard download state info */ +#endif + struct PureInfo info; /* stats, reports and info data */ + struct curl_tlssessioninfo tsi; /* Information about the TLS session, only + valid after a client has asked for it */ +#ifdef USE_HYPER + struct hyptransfer hyp; +#endif +}; + +#define LIBCURL_NAME "libcurl" + +#endif /* HEADER_CURL_URLDATA_H */ diff --git a/third_party/curl/lib/vauth/cleartext.c b/third_party/curl/lib/vauth/cleartext.c new file mode 100644 index 0000000..29389c2 --- /dev/null +++ b/third_party/curl/lib/vauth/cleartext.c @@ -0,0 +1,137 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * RFC4616 PLAIN authentication + * Draft LOGIN SASL Mechanism + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_POP3) || \ + (!defined(CURL_DISABLE_LDAP) && defined(USE_OPENLDAP)) + +#include +#include "urldata.h" + +#include "vauth/vauth.h" +#include "warnless.h" +#include "strtok.h" +#include "sendf.h" +#include "curl_printf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_create_plain_message() + * + * This is used to generate an already encoded PLAIN message ready + * for sending to the recipient. + * + * Parameters: + * + * authzid [in] - The authorization identity. + * authcid [in] - The authentication identity. + * passwd [in] - The password. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_plain_message(const char *authzid, + const char *authcid, + const char *passwd, + struct bufref *out) +{ + char *plainauth; + size_t plainlen; + size_t zlen; + size_t clen; + size_t plen; + + zlen = (authzid == NULL ? 0 : strlen(authzid)); + clen = strlen(authcid); + plen = strlen(passwd); + + /* Compute binary message length. Check for overflows. */ + if((zlen > SIZE_T_MAX/4) || (clen > SIZE_T_MAX/4) || + (plen > (SIZE_T_MAX/2 - 2))) + return CURLE_OUT_OF_MEMORY; + plainlen = zlen + clen + plen + 2; + + plainauth = malloc(plainlen + 1); + if(!plainauth) + return CURLE_OUT_OF_MEMORY; + + /* Calculate the reply */ + if(zlen) + memcpy(plainauth, authzid, zlen); + plainauth[zlen] = '\0'; + memcpy(plainauth + zlen + 1, authcid, clen); + plainauth[zlen + clen + 1] = '\0'; + memcpy(plainauth + zlen + clen + 2, passwd, plen); + plainauth[plainlen] = '\0'; + Curl_bufref_set(out, plainauth, plainlen, curl_free); + return CURLE_OK; +} + +/* + * Curl_auth_create_login_message() + * + * This is used to generate an already encoded LOGIN message containing the + * user name or password ready for sending to the recipient. + * + * Parameters: + * + * valuep [in] - The user name or user's password. + * out [out] - The result storage. + * + * Returns void. + */ +void Curl_auth_create_login_message(const char *valuep, struct bufref *out) +{ + Curl_bufref_set(out, valuep, strlen(valuep), NULL); +} + +/* + * Curl_auth_create_external_message() + * + * This is used to generate an already encoded EXTERNAL message containing + * the user name ready for sending to the recipient. + * + * Parameters: + * + * user [in] - The user name. + * out [out] - The result storage. + * + * Returns void. + */ +void Curl_auth_create_external_message(const char *user, + struct bufref *out) +{ + /* This is the same formatting as the login message */ + Curl_auth_create_login_message(user, out); +} + +#endif /* if no users */ diff --git a/third_party/curl/lib/vauth/cram.c b/third_party/curl/lib/vauth/cram.c new file mode 100644 index 0000000..91fb261 --- /dev/null +++ b/third_party/curl/lib/vauth/cram.c @@ -0,0 +1,97 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * RFC2195 CRAM-MD5 authentication + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_DIGEST_AUTH + +#include +#include "urldata.h" + +#include "vauth/vauth.h" +#include "curl_hmac.h" +#include "curl_md5.h" +#include "warnless.h" +#include "curl_printf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + + +/* + * Curl_auth_create_cram_md5_message() + * + * This is used to generate a CRAM-MD5 response message ready for sending to + * the recipient. + * + * Parameters: + * + * chlg [in] - The challenge. + * userp [in] - The user name. + * passwdp [in] - The user's password. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_cram_md5_message(const struct bufref *chlg, + const char *userp, + const char *passwdp, + struct bufref *out) +{ + struct HMAC_context *ctxt; + unsigned char digest[MD5_DIGEST_LEN]; + char *response; + + /* Compute the digest using the password as the key */ + ctxt = Curl_HMAC_init(Curl_HMAC_MD5, + (const unsigned char *) passwdp, + curlx_uztoui(strlen(passwdp))); + if(!ctxt) + return CURLE_OUT_OF_MEMORY; + + /* Update the digest with the given challenge */ + if(Curl_bufref_len(chlg)) + Curl_HMAC_update(ctxt, Curl_bufref_ptr(chlg), + curlx_uztoui(Curl_bufref_len(chlg))); + + /* Finalise the digest */ + Curl_HMAC_final(ctxt, digest); + + /* Generate the response */ + response = aprintf( + "%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", + userp, digest[0], digest[1], digest[2], digest[3], digest[4], + digest[5], digest[6], digest[7], digest[8], digest[9], digest[10], + digest[11], digest[12], digest[13], digest[14], digest[15]); + if(!response) + return CURLE_OUT_OF_MEMORY; + + Curl_bufref_set(out, response, strlen(response), curl_free); + return CURLE_OK; +} + +#endif /* !CURL_DISABLE_DIGEST_AUTH */ diff --git a/third_party/curl/lib/vauth/digest.c b/third_party/curl/lib/vauth/digest.c new file mode 100644 index 0000000..a742cce --- /dev/null +++ b/third_party/curl/lib/vauth/digest.c @@ -0,0 +1,1031 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * RFC2831 DIGEST-MD5 authentication + * RFC7616 DIGEST-SHA256, DIGEST-SHA512-256 authentication + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_DIGEST_AUTH + +#include + +#include "vauth/vauth.h" +#include "vauth/digest.h" +#include "urldata.h" +#include "curl_base64.h" +#include "curl_hmac.h" +#include "curl_md5.h" +#include "curl_sha256.h" +#include "curl_sha512_256.h" +#include "vtls/vtls.h" +#include "warnless.h" +#include "strtok.h" +#include "strcase.h" +#include "curl_printf.h" +#include "rand.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +#define SESSION_ALGO 1 /* for algos with this bit set */ + +#define ALGO_MD5 0 +#define ALGO_MD5SESS (ALGO_MD5 | SESSION_ALGO) +#define ALGO_SHA256 2 +#define ALGO_SHA256SESS (ALGO_SHA256 | SESSION_ALGO) +#define ALGO_SHA512_256 4 +#define ALGO_SHA512_256SESS (ALGO_SHA512_256 | SESSION_ALGO) + +#if !defined(USE_WINDOWS_SSPI) +#define DIGEST_QOP_VALUE_AUTH (1 << 0) +#define DIGEST_QOP_VALUE_AUTH_INT (1 << 1) +#define DIGEST_QOP_VALUE_AUTH_CONF (1 << 2) + +#define DIGEST_QOP_VALUE_STRING_AUTH "auth" +#define DIGEST_QOP_VALUE_STRING_AUTH_INT "auth-int" +#define DIGEST_QOP_VALUE_STRING_AUTH_CONF "auth-conf" +#endif + +bool Curl_auth_digest_get_pair(const char *str, char *value, char *content, + const char **endptr) +{ + int c; + bool starts_with_quote = FALSE; + bool escape = FALSE; + + for(c = DIGEST_MAX_VALUE_LENGTH - 1; (*str && (*str != '=') && c--);) + *value++ = *str++; + *value = 0; + + if('=' != *str++) + /* eek, no match */ + return FALSE; + + if('\"' == *str) { + /* This starts with a quote so it must end with one as well! */ + str++; + starts_with_quote = TRUE; + } + + for(c = DIGEST_MAX_CONTENT_LENGTH - 1; *str && c--; str++) { + if(!escape) { + switch(*str) { + case '\\': + if(starts_with_quote) { + /* the start of an escaped quote */ + escape = TRUE; + continue; + } + break; + + case ',': + if(!starts_with_quote) { + /* This signals the end of the content if we didn't get a starting + quote and then we do "sloppy" parsing */ + c = 0; /* the end */ + continue; + } + break; + + case '\r': + case '\n': + /* end of string */ + if(starts_with_quote) + return FALSE; /* No closing quote */ + c = 0; + continue; + + case '\"': + if(starts_with_quote) { + /* end of string */ + c = 0; + continue; + } + else + return FALSE; + } + } + + escape = FALSE; + *content++ = *str; + } + if(escape) + return FALSE; /* No character after backslash */ + + *content = 0; + *endptr = str; + + return TRUE; +} + +#if !defined(USE_WINDOWS_SSPI) +/* Convert md5 chunk to RFC2617 (section 3.1.3) -suitable ascii string */ +static void auth_digest_md5_to_ascii(unsigned char *source, /* 16 bytes */ + unsigned char *dest) /* 33 bytes */ +{ + int i; + for(i = 0; i < 16; i++) + msnprintf((char *) &dest[i * 2], 3, "%02x", source[i]); +} + +/* Convert sha256 or SHA-512/256 chunk to RFC7616 -suitable ascii string */ +static void auth_digest_sha256_to_ascii(unsigned char *source, /* 32 bytes */ + unsigned char *dest) /* 65 bytes */ +{ + int i; + for(i = 0; i < 32; i++) + msnprintf((char *) &dest[i * 2], 3, "%02x", source[i]); +} + +/* Perform quoted-string escaping as described in RFC2616 and its errata */ +static char *auth_digest_string_quoted(const char *source) +{ + char *dest; + const char *s = source; + size_t n = 1; /* null terminator */ + + /* Calculate size needed */ + while(*s) { + ++n; + if(*s == '"' || *s == '\\') { + ++n; + } + ++s; + } + + dest = malloc(n); + if(dest) { + char *d = dest; + s = source; + while(*s) { + if(*s == '"' || *s == '\\') { + *d++ = '\\'; + } + *d++ = *s++; + } + *d = '\0'; + } + + return dest; +} + +/* Retrieves the value for a corresponding key from the challenge string + * returns TRUE if the key could be found, FALSE if it does not exists + */ +static bool auth_digest_get_key_value(const char *chlg, + const char *key, + char *value, + size_t max_val_len, + char end_char) +{ + char *find_pos; + size_t i; + + find_pos = strstr(chlg, key); + if(!find_pos) + return FALSE; + + find_pos += strlen(key); + + for(i = 0; *find_pos && *find_pos != end_char && i < max_val_len - 1; ++i) + value[i] = *find_pos++; + value[i] = '\0'; + + return TRUE; +} + +static CURLcode auth_digest_get_qop_values(const char *options, int *value) +{ + char *tmp; + char *token; + char *tok_buf = NULL; + + /* Initialise the output */ + *value = 0; + + /* Tokenise the list of qop values. Use a temporary clone of the buffer since + strtok_r() ruins it. */ + tmp = strdup(options); + if(!tmp) + return CURLE_OUT_OF_MEMORY; + + token = strtok_r(tmp, ",", &tok_buf); + while(token) { + if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH)) + *value |= DIGEST_QOP_VALUE_AUTH; + else if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH_INT)) + *value |= DIGEST_QOP_VALUE_AUTH_INT; + else if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH_CONF)) + *value |= DIGEST_QOP_VALUE_AUTH_CONF; + + token = strtok_r(NULL, ",", &tok_buf); + } + + free(tmp); + + return CURLE_OK; +} + +/* + * auth_decode_digest_md5_message() + * + * This is used internally to decode an already encoded DIGEST-MD5 challenge + * message into the separate attributes. + * + * Parameters: + * + * chlgref [in] - The challenge message. + * nonce [in/out] - The buffer where the nonce will be stored. + * nlen [in] - The length of the nonce buffer. + * realm [in/out] - The buffer where the realm will be stored. + * rlen [in] - The length of the realm buffer. + * alg [in/out] - The buffer where the algorithm will be stored. + * alen [in] - The length of the algorithm buffer. + * qop [in/out] - The buffer where the qop-options will be stored. + * qlen [in] - The length of the qop buffer. + * + * Returns CURLE_OK on success. + */ +static CURLcode auth_decode_digest_md5_message(const struct bufref *chlgref, + char *nonce, size_t nlen, + char *realm, size_t rlen, + char *alg, size_t alen, + char *qop, size_t qlen) +{ + const char *chlg = (const char *) Curl_bufref_ptr(chlgref); + + /* Ensure we have a valid challenge message */ + if(!Curl_bufref_len(chlgref)) + return CURLE_BAD_CONTENT_ENCODING; + + /* Retrieve nonce string from the challenge */ + if(!auth_digest_get_key_value(chlg, "nonce=\"", nonce, nlen, '\"')) + return CURLE_BAD_CONTENT_ENCODING; + + /* Retrieve realm string from the challenge */ + if(!auth_digest_get_key_value(chlg, "realm=\"", realm, rlen, '\"')) { + /* Challenge does not have a realm, set empty string [RFC2831] page 6 */ + *realm = '\0'; + } + + /* Retrieve algorithm string from the challenge */ + if(!auth_digest_get_key_value(chlg, "algorithm=", alg, alen, ',')) + return CURLE_BAD_CONTENT_ENCODING; + + /* Retrieve qop-options string from the challenge */ + if(!auth_digest_get_key_value(chlg, "qop=\"", qop, qlen, '\"')) + return CURLE_BAD_CONTENT_ENCODING; + + return CURLE_OK; +} + +/* + * Curl_auth_is_digest_supported() + * + * This is used to evaluate if DIGEST is supported. + * + * Parameters: None + * + * Returns TRUE as DIGEST as handled by libcurl. + */ +bool Curl_auth_is_digest_supported(void) +{ + return TRUE; +} + +/* + * Curl_auth_create_digest_md5_message() + * + * This is used to generate an already encoded DIGEST-MD5 response message + * ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * chlg [in] - The challenge message. + * userp [in] - The user name. + * passwdp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_digest_md5_message(struct Curl_easy *data, + const struct bufref *chlg, + const char *userp, + const char *passwdp, + const char *service, + struct bufref *out) +{ + size_t i; + struct MD5_context *ctxt; + char *response = NULL; + unsigned char digest[MD5_DIGEST_LEN]; + char HA1_hex[2 * MD5_DIGEST_LEN + 1]; + char HA2_hex[2 * MD5_DIGEST_LEN + 1]; + char resp_hash_hex[2 * MD5_DIGEST_LEN + 1]; + char nonce[64]; + char realm[128]; + char algorithm[64]; + char qop_options[64]; + int qop_values; + char cnonce[33]; + char nonceCount[] = "00000001"; + char method[] = "AUTHENTICATE"; + char qop[] = DIGEST_QOP_VALUE_STRING_AUTH; + char *spn = NULL; + + /* Decode the challenge message */ + CURLcode result = auth_decode_digest_md5_message(chlg, + nonce, sizeof(nonce), + realm, sizeof(realm), + algorithm, + sizeof(algorithm), + qop_options, + sizeof(qop_options)); + if(result) + return result; + + /* We only support md5 sessions */ + if(strcmp(algorithm, "md5-sess") != 0) + return CURLE_BAD_CONTENT_ENCODING; + + /* Get the qop-values from the qop-options */ + result = auth_digest_get_qop_values(qop_options, &qop_values); + if(result) + return result; + + /* We only support auth quality-of-protection */ + if(!(qop_values & DIGEST_QOP_VALUE_AUTH)) + return CURLE_BAD_CONTENT_ENCODING; + + /* Generate 32 random hex chars, 32 bytes + 1 null-termination */ + result = Curl_rand_hex(data, (unsigned char *)cnonce, sizeof(cnonce)); + if(result) + return result; + + /* So far so good, now calculate A1 and H(A1) according to RFC 2831 */ + ctxt = Curl_MD5_init(Curl_DIGEST_MD5); + if(!ctxt) + return CURLE_OUT_OF_MEMORY; + + Curl_MD5_update(ctxt, (const unsigned char *) userp, + curlx_uztoui(strlen(userp))); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + Curl_MD5_update(ctxt, (const unsigned char *) realm, + curlx_uztoui(strlen(realm))); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + Curl_MD5_update(ctxt, (const unsigned char *) passwdp, + curlx_uztoui(strlen(passwdp))); + Curl_MD5_final(ctxt, digest); + + ctxt = Curl_MD5_init(Curl_DIGEST_MD5); + if(!ctxt) + return CURLE_OUT_OF_MEMORY; + + Curl_MD5_update(ctxt, (const unsigned char *) digest, MD5_DIGEST_LEN); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + Curl_MD5_update(ctxt, (const unsigned char *) nonce, + curlx_uztoui(strlen(nonce))); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + Curl_MD5_update(ctxt, (const unsigned char *) cnonce, + curlx_uztoui(strlen(cnonce))); + Curl_MD5_final(ctxt, digest); + + /* Convert calculated 16 octet hex into 32 bytes string */ + for(i = 0; i < MD5_DIGEST_LEN; i++) + msnprintf(&HA1_hex[2 * i], 3, "%02x", digest[i]); + + /* Generate our SPN */ + spn = Curl_auth_build_spn(service, data->conn->host.name, NULL); + if(!spn) + return CURLE_OUT_OF_MEMORY; + + /* Calculate H(A2) */ + ctxt = Curl_MD5_init(Curl_DIGEST_MD5); + if(!ctxt) { + free(spn); + + return CURLE_OUT_OF_MEMORY; + } + + Curl_MD5_update(ctxt, (const unsigned char *) method, + curlx_uztoui(strlen(method))); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + Curl_MD5_update(ctxt, (const unsigned char *) spn, + curlx_uztoui(strlen(spn))); + Curl_MD5_final(ctxt, digest); + + for(i = 0; i < MD5_DIGEST_LEN; i++) + msnprintf(&HA2_hex[2 * i], 3, "%02x", digest[i]); + + /* Now calculate the response hash */ + ctxt = Curl_MD5_init(Curl_DIGEST_MD5); + if(!ctxt) { + free(spn); + + return CURLE_OUT_OF_MEMORY; + } + + Curl_MD5_update(ctxt, (const unsigned char *) HA1_hex, 2 * MD5_DIGEST_LEN); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + Curl_MD5_update(ctxt, (const unsigned char *) nonce, + curlx_uztoui(strlen(nonce))); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + + Curl_MD5_update(ctxt, (const unsigned char *) nonceCount, + curlx_uztoui(strlen(nonceCount))); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + Curl_MD5_update(ctxt, (const unsigned char *) cnonce, + curlx_uztoui(strlen(cnonce))); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + Curl_MD5_update(ctxt, (const unsigned char *) qop, + curlx_uztoui(strlen(qop))); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + + Curl_MD5_update(ctxt, (const unsigned char *) HA2_hex, 2 * MD5_DIGEST_LEN); + Curl_MD5_final(ctxt, digest); + + for(i = 0; i < MD5_DIGEST_LEN; i++) + msnprintf(&resp_hash_hex[2 * i], 3, "%02x", digest[i]); + + /* Generate the response */ + response = aprintf("username=\"%s\",realm=\"%s\",nonce=\"%s\"," + "cnonce=\"%s\",nc=\"%s\",digest-uri=\"%s\",response=%s," + "qop=%s", + userp, realm, nonce, + cnonce, nonceCount, spn, resp_hash_hex, qop); + free(spn); + if(!response) + return CURLE_OUT_OF_MEMORY; + + /* Return the response. */ + Curl_bufref_set(out, response, strlen(response), curl_free); + return result; +} + +/* + * Curl_auth_decode_digest_http_message() + * + * This is used to decode an HTTP DIGEST challenge message into the separate + * attributes. + * + * Parameters: + * + * chlg [in] - The challenge message. + * digest [in/out] - The digest data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_digest_http_message(const char *chlg, + struct digestdata *digest) +{ + bool before = FALSE; /* got a nonce before */ + bool foundAuth = FALSE; + bool foundAuthInt = FALSE; + char *token = NULL; + char *tmp = NULL; + + /* If we already have received a nonce, keep that in mind */ + if(digest->nonce) + before = TRUE; + + /* Clean up any former leftovers and initialise to defaults */ + Curl_auth_digest_cleanup(digest); + + for(;;) { + char value[DIGEST_MAX_VALUE_LENGTH]; + char content[DIGEST_MAX_CONTENT_LENGTH]; + + /* Pass all additional spaces here */ + while(*chlg && ISBLANK(*chlg)) + chlg++; + + /* Extract a value=content pair */ + if(Curl_auth_digest_get_pair(chlg, value, content, &chlg)) { + if(strcasecompare(value, "nonce")) { + free(digest->nonce); + digest->nonce = strdup(content); + if(!digest->nonce) + return CURLE_OUT_OF_MEMORY; + } + else if(strcasecompare(value, "stale")) { + if(strcasecompare(content, "true")) { + digest->stale = TRUE; + digest->nc = 1; /* we make a new nonce now */ + } + } + else if(strcasecompare(value, "realm")) { + free(digest->realm); + digest->realm = strdup(content); + if(!digest->realm) + return CURLE_OUT_OF_MEMORY; + } + else if(strcasecompare(value, "opaque")) { + free(digest->opaque); + digest->opaque = strdup(content); + if(!digest->opaque) + return CURLE_OUT_OF_MEMORY; + } + else if(strcasecompare(value, "qop")) { + char *tok_buf = NULL; + /* Tokenize the list and choose auth if possible, use a temporary + clone of the buffer since strtok_r() ruins it */ + tmp = strdup(content); + if(!tmp) + return CURLE_OUT_OF_MEMORY; + + token = strtok_r(tmp, ",", &tok_buf); + while(token) { + /* Pass additional spaces here */ + while(*token && ISBLANK(*token)) + token++; + if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH)) { + foundAuth = TRUE; + } + else if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH_INT)) { + foundAuthInt = TRUE; + } + token = strtok_r(NULL, ",", &tok_buf); + } + + free(tmp); + + /* Select only auth or auth-int. Otherwise, ignore */ + if(foundAuth) { + free(digest->qop); + digest->qop = strdup(DIGEST_QOP_VALUE_STRING_AUTH); + if(!digest->qop) + return CURLE_OUT_OF_MEMORY; + } + else if(foundAuthInt) { + free(digest->qop); + digest->qop = strdup(DIGEST_QOP_VALUE_STRING_AUTH_INT); + if(!digest->qop) + return CURLE_OUT_OF_MEMORY; + } + } + else if(strcasecompare(value, "algorithm")) { + free(digest->algorithm); + digest->algorithm = strdup(content); + if(!digest->algorithm) + return CURLE_OUT_OF_MEMORY; + + if(strcasecompare(content, "MD5-sess")) + digest->algo = ALGO_MD5SESS; + else if(strcasecompare(content, "MD5")) + digest->algo = ALGO_MD5; + else if(strcasecompare(content, "SHA-256")) + digest->algo = ALGO_SHA256; + else if(strcasecompare(content, "SHA-256-SESS")) + digest->algo = ALGO_SHA256SESS; + else if(strcasecompare(content, "SHA-512-256")) { +#ifdef CURL_HAVE_SHA512_256 + digest->algo = ALGO_SHA512_256; +#else /* ! CURL_HAVE_SHA512_256 */ + return CURLE_NOT_BUILT_IN; +#endif /* ! CURL_HAVE_SHA512_256 */ + } + else if(strcasecompare(content, "SHA-512-256-SESS")) { +#ifdef CURL_HAVE_SHA512_256 + digest->algo = ALGO_SHA512_256SESS; +#else /* ! CURL_HAVE_SHA512_256 */ + return CURLE_NOT_BUILT_IN; +#endif /* ! CURL_HAVE_SHA512_256 */ + } + else + return CURLE_BAD_CONTENT_ENCODING; + } + else if(strcasecompare(value, "userhash")) { + if(strcasecompare(content, "true")) { + digest->userhash = TRUE; + } + } + else { + /* Unknown specifier, ignore it! */ + } + } + else + break; /* We're done here */ + + /* Pass all additional spaces here */ + while(*chlg && ISBLANK(*chlg)) + chlg++; + + /* Allow the list to be comma-separated */ + if(',' == *chlg) + chlg++; + } + + /* We had a nonce since before, and we got another one now without + 'stale=true'. This means we provided bad credentials in the previous + request */ + if(before && !digest->stale) + return CURLE_BAD_CONTENT_ENCODING; + + /* We got this header without a nonce, that's a bad Digest line! */ + if(!digest->nonce) + return CURLE_BAD_CONTENT_ENCODING; + + /* "-sess" protocol versions require "auth" or "auth-int" qop */ + if(!digest->qop && (digest->algo & SESSION_ALGO)) + return CURLE_BAD_CONTENT_ENCODING; + + return CURLE_OK; +} + +/* + * auth_create_digest_http_message() + * + * This is used to generate an HTTP DIGEST response message ready for sending + * to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name. + * passwdp [in] - The user's password. + * request [in] - The HTTP request. + * uripath [in] - The path of the HTTP uri. + * digest [in/out] - The digest data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +static CURLcode auth_create_digest_http_message( + struct Curl_easy *data, + const char *userp, + const char *passwdp, + const unsigned char *request, + const unsigned char *uripath, + struct digestdata *digest, + char **outptr, size_t *outlen, + void (*convert_to_ascii)(unsigned char *, unsigned char *), + CURLcode (*hash)(unsigned char *, const unsigned char *, + const size_t)) +{ + CURLcode result; + unsigned char hashbuf[32]; /* 32 bytes/256 bits */ + unsigned char request_digest[65]; + unsigned char ha1[65]; /* 64 digits and 1 zero byte */ + unsigned char ha2[65]; /* 64 digits and 1 zero byte */ + char userh[65]; + char *cnonce = NULL; + size_t cnonce_sz = 0; + char *userp_quoted; + char *realm_quoted; + char *nonce_quoted; + char *response = NULL; + char *hashthis = NULL; + char *tmp = NULL; + + memset(hashbuf, 0, sizeof(hashbuf)); + if(!digest->nc) + digest->nc = 1; + + if(!digest->cnonce) { + char cnoncebuf[33]; + result = Curl_rand_hex(data, (unsigned char *)cnoncebuf, + sizeof(cnoncebuf)); + if(result) + return result; + + result = Curl_base64_encode(cnoncebuf, strlen(cnoncebuf), + &cnonce, &cnonce_sz); + if(result) + return result; + + digest->cnonce = cnonce; + } + + if(digest->userhash) { + hashthis = aprintf("%s:%s", userp, digest->realm ? digest->realm : ""); + if(!hashthis) + return CURLE_OUT_OF_MEMORY; + + result = hash(hashbuf, (unsigned char *) hashthis, strlen(hashthis)); + free(hashthis); + if(result) + return result; + convert_to_ascii(hashbuf, (unsigned char *)userh); + } + + /* + If the algorithm is "MD5" or unspecified (which then defaults to MD5): + + A1 = unq(username-value) ":" unq(realm-value) ":" passwd + + If the algorithm is "MD5-sess" then: + + A1 = H(unq(username-value) ":" unq(realm-value) ":" passwd) ":" + unq(nonce-value) ":" unq(cnonce-value) + */ + + hashthis = aprintf("%s:%s:%s", userp, digest->realm ? digest->realm : "", + passwdp); + if(!hashthis) + return CURLE_OUT_OF_MEMORY; + + result = hash(hashbuf, (unsigned char *) hashthis, strlen(hashthis)); + free(hashthis); + if(result) + return result; + convert_to_ascii(hashbuf, ha1); + + if(digest->algo & SESSION_ALGO) { + /* nonce and cnonce are OUTSIDE the hash */ + tmp = aprintf("%s:%s:%s", ha1, digest->nonce, digest->cnonce); + if(!tmp) + return CURLE_OUT_OF_MEMORY; + + result = hash(hashbuf, (unsigned char *) tmp, strlen(tmp)); + free(tmp); + if(result) + return result; + convert_to_ascii(hashbuf, ha1); + } + + /* + If the "qop" directive's value is "auth" or is unspecified, then A2 is: + + A2 = Method ":" digest-uri-value + + If the "qop" value is "auth-int", then A2 is: + + A2 = Method ":" digest-uri-value ":" H(entity-body) + + (The "Method" value is the HTTP request method as specified in section + 5.1.1 of RFC 2616) + */ + + hashthis = aprintf("%s:%s", request, uripath); + if(!hashthis) + return CURLE_OUT_OF_MEMORY; + + if(digest->qop && strcasecompare(digest->qop, "auth-int")) { + /* We don't support auth-int for PUT or POST */ + char hashed[65]; + char *hashthis2; + + result = hash(hashbuf, (const unsigned char *)"", 0); + if(result) { + free(hashthis); + return result; + } + convert_to_ascii(hashbuf, (unsigned char *)hashed); + + hashthis2 = aprintf("%s:%s", hashthis, hashed); + free(hashthis); + hashthis = hashthis2; + } + + if(!hashthis) + return CURLE_OUT_OF_MEMORY; + + result = hash(hashbuf, (unsigned char *) hashthis, strlen(hashthis)); + free(hashthis); + if(result) + return result; + convert_to_ascii(hashbuf, ha2); + + if(digest->qop) { + hashthis = aprintf("%s:%s:%08x:%s:%s:%s", ha1, digest->nonce, digest->nc, + digest->cnonce, digest->qop, ha2); + } + else { + hashthis = aprintf("%s:%s:%s", ha1, digest->nonce, ha2); + } + + if(!hashthis) + return CURLE_OUT_OF_MEMORY; + + result = hash(hashbuf, (unsigned char *) hashthis, strlen(hashthis)); + free(hashthis); + if(result) + return result; + convert_to_ascii(hashbuf, request_digest); + + /* For test case 64 (snooped from a Mozilla 1.3a request) + + Authorization: Digest username="testuser", realm="testrealm", \ + nonce="1053604145", uri="/64", response="c55f7f30d83d774a3d2dcacf725abaca" + + Digest parameters are all quoted strings. Username which is provided by + the user will need double quotes and backslashes within it escaped. + realm, nonce, and opaque will need backslashes as well as they were + de-escaped when copied from request header. cnonce is generated with + web-safe characters. uri is already percent encoded. nc is 8 hex + characters. algorithm and qop with standard values only contain web-safe + characters. + */ + userp_quoted = auth_digest_string_quoted(digest->userhash ? userh : userp); + if(!userp_quoted) + return CURLE_OUT_OF_MEMORY; + if(digest->realm) + realm_quoted = auth_digest_string_quoted(digest->realm); + else { + realm_quoted = malloc(1); + if(realm_quoted) + realm_quoted[0] = 0; + } + if(!realm_quoted) { + free(userp_quoted); + return CURLE_OUT_OF_MEMORY; + } + nonce_quoted = auth_digest_string_quoted(digest->nonce); + if(!nonce_quoted) { + free(realm_quoted); + free(userp_quoted); + return CURLE_OUT_OF_MEMORY; + } + + if(digest->qop) { + response = aprintf("username=\"%s\", " + "realm=\"%s\", " + "nonce=\"%s\", " + "uri=\"%s\", " + "cnonce=\"%s\", " + "nc=%08x, " + "qop=%s, " + "response=\"%s\"", + userp_quoted, + realm_quoted, + nonce_quoted, + uripath, + digest->cnonce, + digest->nc, + digest->qop, + request_digest); + + /* Increment nonce-count to use another nc value for the next request */ + digest->nc++; + } + else { + response = aprintf("username=\"%s\", " + "realm=\"%s\", " + "nonce=\"%s\", " + "uri=\"%s\", " + "response=\"%s\"", + userp_quoted, + realm_quoted, + nonce_quoted, + uripath, + request_digest); + } + free(nonce_quoted); + free(realm_quoted); + free(userp_quoted); + if(!response) + return CURLE_OUT_OF_MEMORY; + + /* Add the optional fields */ + if(digest->opaque) { + char *opaque_quoted; + /* Append the opaque */ + opaque_quoted = auth_digest_string_quoted(digest->opaque); + if(!opaque_quoted) { + free(response); + return CURLE_OUT_OF_MEMORY; + } + tmp = aprintf("%s, opaque=\"%s\"", response, opaque_quoted); + free(response); + free(opaque_quoted); + if(!tmp) + return CURLE_OUT_OF_MEMORY; + + response = tmp; + } + + if(digest->algorithm) { + /* Append the algorithm */ + tmp = aprintf("%s, algorithm=%s", response, digest->algorithm); + free(response); + if(!tmp) + return CURLE_OUT_OF_MEMORY; + + response = tmp; + } + + if(digest->userhash) { + /* Append the userhash */ + tmp = aprintf("%s, userhash=true", response); + free(response); + if(!tmp) + return CURLE_OUT_OF_MEMORY; + + response = tmp; + } + + /* Return the output */ + *outptr = response; + *outlen = strlen(response); + + return CURLE_OK; +} + +/* + * Curl_auth_create_digest_http_message() + * + * This is used to generate an HTTP DIGEST response message ready for sending + * to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name. + * passwdp [in] - The user's password. + * request [in] - The HTTP request. + * uripath [in] - The path of the HTTP uri. + * digest [in/out] - The digest data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + const unsigned char *request, + const unsigned char *uripath, + struct digestdata *digest, + char **outptr, size_t *outlen) +{ + if(digest->algo <= ALGO_MD5SESS) + return auth_create_digest_http_message(data, userp, passwdp, + request, uripath, digest, + outptr, outlen, + auth_digest_md5_to_ascii, + Curl_md5it); + + if(digest->algo <= ALGO_SHA256SESS) + return auth_create_digest_http_message(data, userp, passwdp, + request, uripath, digest, + outptr, outlen, + auth_digest_sha256_to_ascii, + Curl_sha256it); +#ifdef CURL_HAVE_SHA512_256 + if(digest->algo <= ALGO_SHA512_256SESS) + return auth_create_digest_http_message(data, userp, passwdp, + request, uripath, digest, + outptr, outlen, + auth_digest_sha256_to_ascii, + Curl_sha512_256it); +#endif /* CURL_HAVE_SHA512_256 */ + + /* Should be unreachable */ + return CURLE_BAD_CONTENT_ENCODING; +} + +/* + * Curl_auth_digest_cleanup() + * + * This is used to clean up the digest specific data. + * + * Parameters: + * + * digest [in/out] - The digest data struct being cleaned up. + * + */ +void Curl_auth_digest_cleanup(struct digestdata *digest) +{ + Curl_safefree(digest->nonce); + Curl_safefree(digest->cnonce); + Curl_safefree(digest->realm); + Curl_safefree(digest->opaque); + Curl_safefree(digest->qop); + Curl_safefree(digest->algorithm); + + digest->nc = 0; + digest->algo = ALGO_MD5; /* default algorithm */ + digest->stale = FALSE; /* default means normal, not stale */ + digest->userhash = FALSE; +} +#endif /* !USE_WINDOWS_SSPI */ + +#endif /* !CURL_DISABLE_DIGEST_AUTH */ diff --git a/third_party/curl/lib/vauth/digest.h b/third_party/curl/lib/vauth/digest.h new file mode 100644 index 0000000..99ce1f9 --- /dev/null +++ b/third_party/curl/lib/vauth/digest.h @@ -0,0 +1,40 @@ +#ifndef HEADER_CURL_DIGEST_H +#define HEADER_CURL_DIGEST_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include + +#ifndef CURL_DISABLE_DIGEST_AUTH + +#define DIGEST_MAX_VALUE_LENGTH 256 +#define DIGEST_MAX_CONTENT_LENGTH 1024 + +/* This is used to extract the realm from a challenge message */ +bool Curl_auth_digest_get_pair(const char *str, char *value, char *content, + const char **endptr); + +#endif + +#endif /* HEADER_CURL_DIGEST_H */ diff --git a/third_party/curl/lib/vauth/digest_sspi.c b/third_party/curl/lib/vauth/digest_sspi.c new file mode 100644 index 0000000..4696f29 --- /dev/null +++ b/third_party/curl/lib/vauth/digest_sspi.c @@ -0,0 +1,672 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, . + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * RFC2831 DIGEST-MD5 authentication + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_WINDOWS_SSPI) && !defined(CURL_DISABLE_DIGEST_AUTH) + +#include + +#include "vauth/vauth.h" +#include "vauth/digest.h" +#include "urldata.h" +#include "warnless.h" +#include "curl_multibyte.h" +#include "sendf.h" +#include "strdup.h" +#include "strcase.h" +#include "strerror.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* +* Curl_auth_is_digest_supported() +* +* This is used to evaluate if DIGEST is supported. +* +* Parameters: None +* +* Returns TRUE if DIGEST is supported by Windows SSPI. +*/ +bool Curl_auth_is_digest_supported(void) +{ + PSecPkgInfo SecurityPackage; + SECURITY_STATUS status; + + /* Query the security package for Digest */ + status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST), + &SecurityPackage); + + /* Release the package buffer as it is not required anymore */ + if(status == SEC_E_OK) { + s_pSecFn->FreeContextBuffer(SecurityPackage); + } + + return (status == SEC_E_OK ? TRUE : FALSE); +} + +/* + * Curl_auth_create_digest_md5_message() + * + * This is used to generate an already encoded DIGEST-MD5 response message + * ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * chlg [in] - The challenge message. + * userp [in] - The user name in the format User or Domain\User. + * passwdp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_digest_md5_message(struct Curl_easy *data, + const struct bufref *chlg, + const char *userp, + const char *passwdp, + const char *service, + struct bufref *out) +{ + CURLcode result = CURLE_OK; + TCHAR *spn = NULL; + size_t token_max = 0; + unsigned char *output_token = NULL; + CredHandle credentials; + CtxtHandle context; + PSecPkgInfo SecurityPackage; + SEC_WINNT_AUTH_IDENTITY identity; + SEC_WINNT_AUTH_IDENTITY *p_identity; + SecBuffer chlg_buf; + SecBuffer resp_buf; + SecBufferDesc chlg_desc; + SecBufferDesc resp_desc; + SECURITY_STATUS status; + unsigned long attrs; + TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ + + /* Ensure we have a valid challenge message */ + if(!Curl_bufref_len(chlg)) { + infof(data, "DIGEST-MD5 handshake failure (empty challenge message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Query the security package for DigestSSP */ + status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST), + &SecurityPackage); + if(status != SEC_E_OK) { + failf(data, "SSPI: couldn't get auth info"); + return CURLE_AUTH_ERROR; + } + + token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + s_pSecFn->FreeContextBuffer(SecurityPackage); + + /* Allocate our response buffer */ + output_token = malloc(token_max); + if(!output_token) + return CURLE_OUT_OF_MEMORY; + + /* Generate our SPN */ + spn = Curl_auth_build_spn(service, data->conn->host.name, NULL); + if(!spn) { + free(output_token); + return CURLE_OUT_OF_MEMORY; + } + + if(userp && *userp) { + /* Populate our identity structure */ + result = Curl_create_sspi_identity(userp, passwdp, &identity); + if(result) { + free(spn); + free(output_token); + return result; + } + + /* Allow proper cleanup of the identity structure */ + p_identity = &identity; + } + else + /* Use the current Windows user */ + p_identity = NULL; + + /* Acquire our credentials handle */ + status = s_pSecFn->AcquireCredentialsHandle(NULL, + (TCHAR *) TEXT(SP_NAME_DIGEST), + SECPKG_CRED_OUTBOUND, NULL, + p_identity, NULL, NULL, + &credentials, &expiry); + + if(status != SEC_E_OK) { + Curl_sspi_free_identity(p_identity); + free(spn); + free(output_token); + return CURLE_LOGIN_DENIED; + } + + /* Setup the challenge "input" security buffer */ + chlg_desc.ulVersion = SECBUFFER_VERSION; + chlg_desc.cBuffers = 1; + chlg_desc.pBuffers = &chlg_buf; + chlg_buf.BufferType = SECBUFFER_TOKEN; + chlg_buf.pvBuffer = (void *) Curl_bufref_ptr(chlg); + chlg_buf.cbBuffer = curlx_uztoul(Curl_bufref_len(chlg)); + + /* Setup the response "output" security buffer */ + resp_desc.ulVersion = SECBUFFER_VERSION; + resp_desc.cBuffers = 1; + resp_desc.pBuffers = &resp_buf; + resp_buf.BufferType = SECBUFFER_TOKEN; + resp_buf.pvBuffer = output_token; + resp_buf.cbBuffer = curlx_uztoul(token_max); + + /* Generate our response message */ + status = s_pSecFn->InitializeSecurityContext(&credentials, NULL, spn, + 0, 0, 0, &chlg_desc, 0, + &context, &resp_desc, &attrs, + &expiry); + + if(status == SEC_I_COMPLETE_NEEDED || + status == SEC_I_COMPLETE_AND_CONTINUE) + s_pSecFn->CompleteAuthToken(&credentials, &resp_desc); + else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) { +#if !defined(CURL_DISABLE_VERBOSE_STRINGS) + char buffer[STRERROR_LEN]; +#endif + + s_pSecFn->FreeCredentialsHandle(&credentials); + Curl_sspi_free_identity(p_identity); + free(spn); + free(output_token); + + if(status == SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + +#if !defined(CURL_DISABLE_VERBOSE_STRINGS) + infof(data, "schannel: InitializeSecurityContext failed: %s", + Curl_sspi_strerror(status, buffer, sizeof(buffer))); +#endif + + return CURLE_AUTH_ERROR; + } + + /* Return the response. */ + Curl_bufref_set(out, output_token, resp_buf.cbBuffer, curl_free); + + /* Free our handles */ + s_pSecFn->DeleteSecurityContext(&context); + s_pSecFn->FreeCredentialsHandle(&credentials); + + /* Free the identity structure */ + Curl_sspi_free_identity(p_identity); + + /* Free the SPN */ + free(spn); + + return result; +} + +/* + * Curl_override_sspi_http_realm() + * + * This is used to populate the domain in a SSPI identity structure + * The realm is extracted from the challenge message and used as the + * domain if it is not already explicitly set. + * + * Parameters: + * + * chlg [in] - The challenge message. + * identity [in/out] - The identity structure. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_override_sspi_http_realm(const char *chlg, + SEC_WINNT_AUTH_IDENTITY *identity) +{ + xcharp_u domain, dup_domain; + + /* If domain is blank or unset, check challenge message for realm */ + if(!identity->Domain || !identity->DomainLength) { + for(;;) { + char value[DIGEST_MAX_VALUE_LENGTH]; + char content[DIGEST_MAX_CONTENT_LENGTH]; + + /* Pass all additional spaces here */ + while(*chlg && ISBLANK(*chlg)) + chlg++; + + /* Extract a value=content pair */ + if(Curl_auth_digest_get_pair(chlg, value, content, &chlg)) { + if(strcasecompare(value, "realm")) { + + /* Setup identity's domain and length */ + domain.tchar_ptr = curlx_convert_UTF8_to_tchar((char *) content); + if(!domain.tchar_ptr) + return CURLE_OUT_OF_MEMORY; + + dup_domain.tchar_ptr = _tcsdup(domain.tchar_ptr); + if(!dup_domain.tchar_ptr) { + curlx_unicodefree(domain.tchar_ptr); + return CURLE_OUT_OF_MEMORY; + } + + free(identity->Domain); + identity->Domain = dup_domain.tbyte_ptr; + identity->DomainLength = curlx_uztoul(_tcslen(dup_domain.tchar_ptr)); + dup_domain.tchar_ptr = NULL; + + curlx_unicodefree(domain.tchar_ptr); + } + else { + /* Unknown specifier, ignore it! */ + } + } + else + break; /* We're done here */ + + /* Pass all additional spaces here */ + while(*chlg && ISBLANK(*chlg)) + chlg++; + + /* Allow the list to be comma-separated */ + if(',' == *chlg) + chlg++; + } + } + + return CURLE_OK; +} + +/* + * Curl_auth_decode_digest_http_message() + * + * This is used to decode an HTTP DIGEST challenge message into the separate + * attributes. + * + * Parameters: + * + * chlg [in] - The challenge message. + * digest [in/out] - The digest data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_digest_http_message(const char *chlg, + struct digestdata *digest) +{ + size_t chlglen = strlen(chlg); + + /* We had an input token before so if there's another one now that means we + provided bad credentials in the previous request or it's stale. */ + if(digest->input_token) { + bool stale = false; + const char *p = chlg; + + /* Check for the 'stale' directive */ + for(;;) { + char value[DIGEST_MAX_VALUE_LENGTH]; + char content[DIGEST_MAX_CONTENT_LENGTH]; + + while(*p && ISBLANK(*p)) + p++; + + if(!Curl_auth_digest_get_pair(p, value, content, &p)) + break; + + if(strcasecompare(value, "stale") && + strcasecompare(content, "true")) { + stale = true; + break; + } + + while(*p && ISBLANK(*p)) + p++; + + if(',' == *p) + p++; + } + + if(stale) + Curl_auth_digest_cleanup(digest); + else + return CURLE_LOGIN_DENIED; + } + + /* Store the challenge for use later */ + digest->input_token = (BYTE *) Curl_memdup(chlg, chlglen + 1); + if(!digest->input_token) + return CURLE_OUT_OF_MEMORY; + + digest->input_token_len = chlglen; + + return CURLE_OK; +} + +/* + * Curl_auth_create_digest_http_message() + * + * This is used to generate an HTTP DIGEST response message ready for sending + * to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name in the format User or Domain\User. + * passwdp [in] - The user's password. + * request [in] - The HTTP request. + * uripath [in] - The path of the HTTP uri. + * digest [in/out] - The digest data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + const unsigned char *request, + const unsigned char *uripath, + struct digestdata *digest, + char **outptr, size_t *outlen) +{ + size_t token_max; + char *resp; + BYTE *output_token; + size_t output_token_len = 0; + PSecPkgInfo SecurityPackage; + SecBuffer chlg_buf[5]; + SecBufferDesc chlg_desc; + SECURITY_STATUS status; + + (void) data; + + /* Query the security package for DigestSSP */ + status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST), + &SecurityPackage); + if(status != SEC_E_OK) { + failf(data, "SSPI: couldn't get auth info"); + return CURLE_AUTH_ERROR; + } + + token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + s_pSecFn->FreeContextBuffer(SecurityPackage); + + /* Allocate the output buffer according to the max token size as indicated + by the security package */ + output_token = malloc(token_max); + if(!output_token) { + return CURLE_OUT_OF_MEMORY; + } + + /* If the user/passwd that was used to make the identity for http_context + has changed then delete that context. */ + if((userp && !digest->user) || (!userp && digest->user) || + (passwdp && !digest->passwd) || (!passwdp && digest->passwd) || + (userp && digest->user && Curl_timestrcmp(userp, digest->user)) || + (passwdp && digest->passwd && Curl_timestrcmp(passwdp, digest->passwd))) { + if(digest->http_context) { + s_pSecFn->DeleteSecurityContext(digest->http_context); + Curl_safefree(digest->http_context); + } + Curl_safefree(digest->user); + Curl_safefree(digest->passwd); + } + + if(digest->http_context) { + chlg_desc.ulVersion = SECBUFFER_VERSION; + chlg_desc.cBuffers = 5; + chlg_desc.pBuffers = chlg_buf; + chlg_buf[0].BufferType = SECBUFFER_TOKEN; + chlg_buf[0].pvBuffer = NULL; + chlg_buf[0].cbBuffer = 0; + chlg_buf[1].BufferType = SECBUFFER_PKG_PARAMS; + chlg_buf[1].pvBuffer = (void *) request; + chlg_buf[1].cbBuffer = curlx_uztoul(strlen((const char *) request)); + chlg_buf[2].BufferType = SECBUFFER_PKG_PARAMS; + chlg_buf[2].pvBuffer = (void *) uripath; + chlg_buf[2].cbBuffer = curlx_uztoul(strlen((const char *) uripath)); + chlg_buf[3].BufferType = SECBUFFER_PKG_PARAMS; + chlg_buf[3].pvBuffer = NULL; + chlg_buf[3].cbBuffer = 0; + chlg_buf[4].BufferType = SECBUFFER_PADDING; + chlg_buf[4].pvBuffer = output_token; + chlg_buf[4].cbBuffer = curlx_uztoul(token_max); + + status = s_pSecFn->MakeSignature(digest->http_context, 0, &chlg_desc, 0); + if(status == SEC_E_OK) + output_token_len = chlg_buf[4].cbBuffer; + else { /* delete the context so a new one can be made */ + infof(data, "digest_sspi: MakeSignature failed, error 0x%08lx", + (long)status); + s_pSecFn->DeleteSecurityContext(digest->http_context); + Curl_safefree(digest->http_context); + } + } + + if(!digest->http_context) { + CredHandle credentials; + SEC_WINNT_AUTH_IDENTITY identity; + SEC_WINNT_AUTH_IDENTITY *p_identity; + SecBuffer resp_buf; + SecBufferDesc resp_desc; + unsigned long attrs; + TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ + TCHAR *spn; + + /* free the copy of user/passwd used to make the previous identity */ + Curl_safefree(digest->user); + Curl_safefree(digest->passwd); + + if(userp && *userp) { + /* Populate our identity structure */ + if(Curl_create_sspi_identity(userp, passwdp, &identity)) { + free(output_token); + return CURLE_OUT_OF_MEMORY; + } + + /* Populate our identity domain */ + if(Curl_override_sspi_http_realm((const char *) digest->input_token, + &identity)) { + free(output_token); + return CURLE_OUT_OF_MEMORY; + } + + /* Allow proper cleanup of the identity structure */ + p_identity = &identity; + } + else + /* Use the current Windows user */ + p_identity = NULL; + + if(userp) { + digest->user = strdup(userp); + + if(!digest->user) { + free(output_token); + return CURLE_OUT_OF_MEMORY; + } + } + + if(passwdp) { + digest->passwd = strdup(passwdp); + + if(!digest->passwd) { + free(output_token); + Curl_safefree(digest->user); + return CURLE_OUT_OF_MEMORY; + } + } + + /* Acquire our credentials handle */ + status = s_pSecFn->AcquireCredentialsHandle(NULL, + (TCHAR *) TEXT(SP_NAME_DIGEST), + SECPKG_CRED_OUTBOUND, NULL, + p_identity, NULL, NULL, + &credentials, &expiry); + if(status != SEC_E_OK) { + Curl_sspi_free_identity(p_identity); + free(output_token); + + return CURLE_LOGIN_DENIED; + } + + /* Setup the challenge "input" security buffer if present */ + chlg_desc.ulVersion = SECBUFFER_VERSION; + chlg_desc.cBuffers = 3; + chlg_desc.pBuffers = chlg_buf; + chlg_buf[0].BufferType = SECBUFFER_TOKEN; + chlg_buf[0].pvBuffer = digest->input_token; + chlg_buf[0].cbBuffer = curlx_uztoul(digest->input_token_len); + chlg_buf[1].BufferType = SECBUFFER_PKG_PARAMS; + chlg_buf[1].pvBuffer = (void *) request; + chlg_buf[1].cbBuffer = curlx_uztoul(strlen((const char *) request)); + chlg_buf[2].BufferType = SECBUFFER_PKG_PARAMS; + chlg_buf[2].pvBuffer = NULL; + chlg_buf[2].cbBuffer = 0; + + /* Setup the response "output" security buffer */ + resp_desc.ulVersion = SECBUFFER_VERSION; + resp_desc.cBuffers = 1; + resp_desc.pBuffers = &resp_buf; + resp_buf.BufferType = SECBUFFER_TOKEN; + resp_buf.pvBuffer = output_token; + resp_buf.cbBuffer = curlx_uztoul(token_max); + + spn = curlx_convert_UTF8_to_tchar((char *) uripath); + if(!spn) { + s_pSecFn->FreeCredentialsHandle(&credentials); + + Curl_sspi_free_identity(p_identity); + free(output_token); + + return CURLE_OUT_OF_MEMORY; + } + + /* Allocate our new context handle */ + digest->http_context = calloc(1, sizeof(CtxtHandle)); + if(!digest->http_context) + return CURLE_OUT_OF_MEMORY; + + /* Generate our response message */ + status = s_pSecFn->InitializeSecurityContext(&credentials, NULL, + spn, + ISC_REQ_USE_HTTP_STYLE, 0, 0, + &chlg_desc, 0, + digest->http_context, + &resp_desc, &attrs, &expiry); + curlx_unicodefree(spn); + + if(status == SEC_I_COMPLETE_NEEDED || + status == SEC_I_COMPLETE_AND_CONTINUE) + s_pSecFn->CompleteAuthToken(&credentials, &resp_desc); + else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) { +#if !defined(CURL_DISABLE_VERBOSE_STRINGS) + char buffer[STRERROR_LEN]; +#endif + + s_pSecFn->FreeCredentialsHandle(&credentials); + + Curl_sspi_free_identity(p_identity); + free(output_token); + + Curl_safefree(digest->http_context); + + if(status == SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + +#if !defined(CURL_DISABLE_VERBOSE_STRINGS) + infof(data, "schannel: InitializeSecurityContext failed: %s", + Curl_sspi_strerror(status, buffer, sizeof(buffer))); +#endif + + return CURLE_AUTH_ERROR; + } + + output_token_len = resp_buf.cbBuffer; + + s_pSecFn->FreeCredentialsHandle(&credentials); + Curl_sspi_free_identity(p_identity); + } + + resp = malloc(output_token_len + 1); + if(!resp) { + free(output_token); + + return CURLE_OUT_OF_MEMORY; + } + + /* Copy the generated response */ + memcpy(resp, output_token, output_token_len); + resp[output_token_len] = 0; + + /* Return the response */ + *outptr = resp; + *outlen = output_token_len; + + /* Free the response buffer */ + free(output_token); + + return CURLE_OK; +} + +/* + * Curl_auth_digest_cleanup() + * + * This is used to clean up the digest specific data. + * + * Parameters: + * + * digest [in/out] - The digest data struct being cleaned up. + * + */ +void Curl_auth_digest_cleanup(struct digestdata *digest) +{ + /* Free the input token */ + Curl_safefree(digest->input_token); + + /* Reset any variables */ + digest->input_token_len = 0; + + /* Delete security context */ + if(digest->http_context) { + s_pSecFn->DeleteSecurityContext(digest->http_context); + Curl_safefree(digest->http_context); + } + + /* Free the copy of user/passwd used to make the identity for http_context */ + Curl_safefree(digest->user); + Curl_safefree(digest->passwd); +} + +#endif /* USE_WINDOWS_SSPI && !CURL_DISABLE_DIGEST_AUTH */ diff --git a/third_party/curl/lib/vauth/gsasl.c b/third_party/curl/lib/vauth/gsasl.c new file mode 100644 index 0000000..c7d0a8d --- /dev/null +++ b/third_party/curl/lib/vauth/gsasl.c @@ -0,0 +1,127 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Simon Josefsson, , 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. + * + * SPDX-License-Identifier: curl + * + * RFC5802 SCRAM-SHA-1 authentication + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_GSASL + +#include + +#include "vauth/vauth.h" +#include "urldata.h" +#include "sendf.h" + +#include + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +bool Curl_auth_gsasl_is_supported(struct Curl_easy *data, + const char *mech, + struct gsasldata *gsasl) +{ + int res; + + res = gsasl_init(&gsasl->ctx); + if(res != GSASL_OK) { + failf(data, "gsasl init: %s\n", gsasl_strerror(res)); + return FALSE; + } + + res = gsasl_client_start(gsasl->ctx, mech, &gsasl->client); + if(res != GSASL_OK) { + gsasl_done(gsasl->ctx); + return FALSE; + } + + return true; +} + +CURLcode Curl_auth_gsasl_start(struct Curl_easy *data, + const char *userp, + const char *passwdp, + struct gsasldata *gsasl) +{ +#if GSASL_VERSION_NUMBER >= 0x010b00 + int res; + res = +#endif + gsasl_property_set(gsasl->client, GSASL_AUTHID, userp); +#if GSASL_VERSION_NUMBER >= 0x010b00 + if(res != GSASL_OK) { + failf(data, "setting AUTHID failed: %s\n", gsasl_strerror(res)); + return CURLE_OUT_OF_MEMORY; + } +#endif + +#if GSASL_VERSION_NUMBER >= 0x010b00 + res = +#endif + gsasl_property_set(gsasl->client, GSASL_PASSWORD, passwdp); +#if GSASL_VERSION_NUMBER >= 0x010b00 + if(res != GSASL_OK) { + failf(data, "setting PASSWORD failed: %s\n", gsasl_strerror(res)); + return CURLE_OUT_OF_MEMORY; + } +#endif + + (void)data; + + return CURLE_OK; +} + +CURLcode Curl_auth_gsasl_token(struct Curl_easy *data, + const struct bufref *chlg, + struct gsasldata *gsasl, + struct bufref *out) +{ + int res; + char *response; + size_t outlen; + + res = gsasl_step(gsasl->client, + (const char *) Curl_bufref_ptr(chlg), Curl_bufref_len(chlg), + &response, &outlen); + if(res != GSASL_OK && res != GSASL_NEEDS_MORE) { + failf(data, "GSASL step: %s\n", gsasl_strerror(res)); + return CURLE_BAD_CONTENT_ENCODING; + } + + Curl_bufref_set(out, response, outlen, gsasl_free); + return CURLE_OK; +} + +void Curl_auth_gsasl_cleanup(struct gsasldata *gsasl) +{ + gsasl_finish(gsasl->client); + gsasl->client = NULL; + + gsasl_done(gsasl->ctx); + gsasl->ctx = NULL; +} +#endif diff --git a/third_party/curl/lib/vauth/krb5_gssapi.c b/third_party/curl/lib/vauth/krb5_gssapi.c new file mode 100644 index 0000000..16b6e40 --- /dev/null +++ b/third_party/curl/lib/vauth/krb5_gssapi.c @@ -0,0 +1,324 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, . + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(HAVE_GSSAPI) && defined(USE_KERBEROS5) + +#include + +#include "vauth/vauth.h" +#include "curl_sasl.h" +#include "urldata.h" +#include "curl_gssapi.h" +#include "sendf.h" +#include "curl_printf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_is_gssapi_supported() + * + * This is used to evaluate if GSSAPI (Kerberos V5) is supported. + * + * Parameters: None + * + * Returns TRUE if Kerberos V5 is supported by the GSS-API library. + */ +bool Curl_auth_is_gssapi_supported(void) +{ + return TRUE; +} + +/* + * Curl_auth_create_gssapi_user_message() + * + * This is used to generate an already encoded GSSAPI (Kerberos V5) user token + * message ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name. + * passwdp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * host [in[ - The host name. + * mutual_auth [in] - Flag specifying whether or not mutual authentication + * is enabled. + * chlg [in] - Optional challenge message. + * krb5 [in/out] - The Kerberos 5 data struct being used and modified. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_gssapi_user_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + const char *service, + const char *host, + const bool mutual_auth, + const struct bufref *chlg, + struct kerberos5data *krb5, + struct bufref *out) +{ + CURLcode result = CURLE_OK; + OM_uint32 major_status; + OM_uint32 minor_status; + OM_uint32 unused_status; + gss_buffer_desc spn_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + + (void) userp; + (void) passwdp; + + if(!krb5->spn) { + /* Generate our SPN */ + char *spn = Curl_auth_build_spn(service, NULL, host); + if(!spn) + return CURLE_OUT_OF_MEMORY; + + /* Populate the SPN structure */ + spn_token.value = spn; + spn_token.length = strlen(spn); + + /* Import the SPN */ + major_status = gss_import_name(&minor_status, &spn_token, + GSS_C_NT_HOSTBASED_SERVICE, &krb5->spn); + if(GSS_ERROR(major_status)) { + Curl_gss_log_error(data, "gss_import_name() failed: ", + major_status, minor_status); + + free(spn); + + return CURLE_AUTH_ERROR; + } + + free(spn); + } + + if(chlg) { + if(!Curl_bufref_len(chlg)) { + infof(data, "GSSAPI handshake failure (empty challenge message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + input_token.value = (void *) Curl_bufref_ptr(chlg); + input_token.length = Curl_bufref_len(chlg); + } + + major_status = Curl_gss_init_sec_context(data, + &minor_status, + &krb5->context, + krb5->spn, + &Curl_krb5_mech_oid, + GSS_C_NO_CHANNEL_BINDINGS, + &input_token, + &output_token, + mutual_auth, + NULL); + + if(GSS_ERROR(major_status)) { + if(output_token.value) + gss_release_buffer(&unused_status, &output_token); + + Curl_gss_log_error(data, "gss_init_sec_context() failed: ", + major_status, minor_status); + + return CURLE_AUTH_ERROR; + } + + if(output_token.value && output_token.length) { + result = Curl_bufref_memdup(out, output_token.value, output_token.length); + gss_release_buffer(&unused_status, &output_token); + } + else + Curl_bufref_set(out, mutual_auth? "": NULL, 0, NULL); + + return result; +} + +/* + * Curl_auth_create_gssapi_security_message() + * + * This is used to generate an already encoded GSSAPI (Kerberos V5) security + * token message ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * authzid [in] - The authorization identity if some. + * chlg [in] - Optional challenge message. + * krb5 [in/out] - The Kerberos 5 data struct being used and modified. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_gssapi_security_message(struct Curl_easy *data, + const char *authzid, + const struct bufref *chlg, + struct kerberos5data *krb5, + struct bufref *out) +{ + CURLcode result = CURLE_OK; + size_t messagelen = 0; + unsigned char *message = NULL; + OM_uint32 major_status; + OM_uint32 minor_status; + OM_uint32 unused_status; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + unsigned char *indata; + gss_qop_t qop = GSS_C_QOP_DEFAULT; + unsigned int sec_layer = 0; + unsigned int max_size = 0; + + /* Ensure we have a valid challenge message */ + if(!Curl_bufref_len(chlg)) { + infof(data, "GSSAPI handshake failure (empty security message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Setup the challenge "input" security buffer */ + input_token.value = (void *) Curl_bufref_ptr(chlg); + input_token.length = Curl_bufref_len(chlg); + + /* Decrypt the inbound challenge and obtain the qop */ + major_status = gss_unwrap(&minor_status, krb5->context, &input_token, + &output_token, NULL, &qop); + if(GSS_ERROR(major_status)) { + Curl_gss_log_error(data, "gss_unwrap() failed: ", + major_status, minor_status); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Not 4 octets long so fail as per RFC4752 Section 3.1 */ + if(output_token.length != 4) { + infof(data, "GSSAPI handshake failure (invalid security data)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Extract the security layer and the maximum message size */ + indata = output_token.value; + sec_layer = indata[0]; + max_size = ((unsigned int)indata[1] << 16) | + ((unsigned int)indata[2] << 8) | indata[3]; + + /* Free the challenge as it is not required anymore */ + gss_release_buffer(&unused_status, &output_token); + + /* Process the security layer */ + if(!(sec_layer & GSSAUTH_P_NONE)) { + infof(data, "GSSAPI handshake failure (invalid security layer)"); + + return CURLE_BAD_CONTENT_ENCODING; + } + sec_layer &= GSSAUTH_P_NONE; /* We do not support a security layer */ + + /* Process the maximum message size the server can receive */ + if(max_size > 0) { + /* The server has told us it supports a maximum receive buffer, however, as + we don't require one unless we are encrypting data, we tell the server + our receive buffer is zero. */ + max_size = 0; + } + + /* Allocate our message */ + messagelen = 4; + if(authzid) + messagelen += strlen(authzid); + message = malloc(messagelen); + if(!message) + return CURLE_OUT_OF_MEMORY; + + /* Populate the message with the security layer and client supported receive + message size. */ + message[0] = sec_layer & 0xFF; + message[1] = (max_size >> 16) & 0xFF; + message[2] = (max_size >> 8) & 0xFF; + message[3] = max_size & 0xFF; + + /* If given, append the authorization identity. */ + + if(authzid && *authzid) + memcpy(message + 4, authzid, messagelen - 4); + + /* Setup the "authentication data" security buffer */ + input_token.value = message; + input_token.length = messagelen; + + /* Encrypt the data */ + major_status = gss_wrap(&minor_status, krb5->context, 0, + GSS_C_QOP_DEFAULT, &input_token, NULL, + &output_token); + if(GSS_ERROR(major_status)) { + Curl_gss_log_error(data, "gss_wrap() failed: ", + major_status, minor_status); + free(message); + return CURLE_AUTH_ERROR; + } + + /* Return the response. */ + result = Curl_bufref_memdup(out, output_token.value, output_token.length); + /* Free the output buffer */ + gss_release_buffer(&unused_status, &output_token); + + /* Free the message buffer */ + free(message); + + return result; +} + +/* + * Curl_auth_cleanup_gssapi() + * + * This is used to clean up the GSSAPI (Kerberos V5) specific data. + * + * Parameters: + * + * krb5 [in/out] - The Kerberos 5 data struct being cleaned up. + * + */ +void Curl_auth_cleanup_gssapi(struct kerberos5data *krb5) +{ + OM_uint32 minor_status; + + /* Free our security context */ + if(krb5->context != GSS_C_NO_CONTEXT) { + gss_delete_sec_context(&minor_status, &krb5->context, GSS_C_NO_BUFFER); + krb5->context = GSS_C_NO_CONTEXT; + } + + /* Free the SPN */ + if(krb5->spn != GSS_C_NO_NAME) { + gss_release_name(&minor_status, &krb5->spn); + krb5->spn = GSS_C_NO_NAME; + } +} + +#endif /* HAVE_GSSAPI && USE_KERBEROS5 */ diff --git a/third_party/curl/lib/vauth/krb5_sspi.c b/third_party/curl/lib/vauth/krb5_sspi.c new file mode 100644 index 0000000..17a517a --- /dev/null +++ b/third_party/curl/lib/vauth/krb5_sspi.c @@ -0,0 +1,475 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, . + * + * 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. + * + * SPDX-License-Identifier: curl + * + * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_WINDOWS_SSPI) && defined(USE_KERBEROS5) + +#include + +#include "vauth/vauth.h" +#include "urldata.h" +#include "warnless.h" +#include "curl_multibyte.h" +#include "sendf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_is_gssapi_supported() + * + * This is used to evaluate if GSSAPI (Kerberos V5) is supported. + * + * Parameters: None + * + * Returns TRUE if Kerberos V5 is supported by Windows SSPI. + */ +bool Curl_auth_is_gssapi_supported(void) +{ + PSecPkgInfo SecurityPackage; + SECURITY_STATUS status; + + /* Query the security package for Kerberos */ + status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) + TEXT(SP_NAME_KERBEROS), + &SecurityPackage); + + /* Release the package buffer as it is not required anymore */ + if(status == SEC_E_OK) { + s_pSecFn->FreeContextBuffer(SecurityPackage); + } + + return (status == SEC_E_OK ? TRUE : FALSE); +} + +/* + * Curl_auth_create_gssapi_user_message() + * + * This is used to generate an already encoded GSSAPI (Kerberos V5) user token + * message ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name in the format User or Domain\User. + * passwdp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * host [in] - The host name. + * mutual_auth [in] - Flag specifying whether or not mutual authentication + * is enabled. + * chlg [in] - Optional challenge message. + * krb5 [in/out] - The Kerberos 5 data struct being used and modified. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_gssapi_user_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + const char *service, + const char *host, + const bool mutual_auth, + const struct bufref *chlg, + struct kerberos5data *krb5, + struct bufref *out) +{ + CURLcode result = CURLE_OK; + CtxtHandle context; + PSecPkgInfo SecurityPackage; + SecBuffer chlg_buf; + SecBuffer resp_buf; + SecBufferDesc chlg_desc; + SecBufferDesc resp_desc; + SECURITY_STATUS status; + unsigned long attrs; + TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ + + if(!krb5->spn) { + /* Generate our SPN */ + krb5->spn = Curl_auth_build_spn(service, host, NULL); + if(!krb5->spn) + return CURLE_OUT_OF_MEMORY; + } + + if(!krb5->output_token) { + /* Query the security package for Kerberos */ + status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) + TEXT(SP_NAME_KERBEROS), + &SecurityPackage); + if(status != SEC_E_OK) { + failf(data, "SSPI: couldn't get auth info"); + return CURLE_AUTH_ERROR; + } + + krb5->token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + s_pSecFn->FreeContextBuffer(SecurityPackage); + + /* Allocate our response buffer */ + krb5->output_token = malloc(krb5->token_max); + if(!krb5->output_token) + return CURLE_OUT_OF_MEMORY; + } + + if(!krb5->credentials) { + /* Do we have credentials to use or are we using single sign-on? */ + if(userp && *userp) { + /* Populate our identity structure */ + result = Curl_create_sspi_identity(userp, passwdp, &krb5->identity); + if(result) + return result; + + /* Allow proper cleanup of the identity structure */ + krb5->p_identity = &krb5->identity; + } + else + /* Use the current Windows user */ + krb5->p_identity = NULL; + + /* Allocate our credentials handle */ + krb5->credentials = calloc(1, sizeof(CredHandle)); + if(!krb5->credentials) + return CURLE_OUT_OF_MEMORY; + + /* Acquire our credentials handle */ + status = s_pSecFn->AcquireCredentialsHandle(NULL, + (TCHAR *) + TEXT(SP_NAME_KERBEROS), + SECPKG_CRED_OUTBOUND, NULL, + krb5->p_identity, NULL, NULL, + krb5->credentials, &expiry); + if(status != SEC_E_OK) + return CURLE_LOGIN_DENIED; + + /* Allocate our new context handle */ + krb5->context = calloc(1, sizeof(CtxtHandle)); + if(!krb5->context) + return CURLE_OUT_OF_MEMORY; + } + + if(chlg) { + if(!Curl_bufref_len(chlg)) { + infof(data, "GSSAPI handshake failure (empty challenge message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Setup the challenge "input" security buffer */ + chlg_desc.ulVersion = SECBUFFER_VERSION; + chlg_desc.cBuffers = 1; + chlg_desc.pBuffers = &chlg_buf; + chlg_buf.BufferType = SECBUFFER_TOKEN; + chlg_buf.pvBuffer = (void *) Curl_bufref_ptr(chlg); + chlg_buf.cbBuffer = curlx_uztoul(Curl_bufref_len(chlg)); + } + + /* Setup the response "output" security buffer */ + resp_desc.ulVersion = SECBUFFER_VERSION; + resp_desc.cBuffers = 1; + resp_desc.pBuffers = &resp_buf; + resp_buf.BufferType = SECBUFFER_TOKEN; + resp_buf.pvBuffer = krb5->output_token; + resp_buf.cbBuffer = curlx_uztoul(krb5->token_max); + + /* Generate our challenge-response message */ + status = s_pSecFn->InitializeSecurityContext(krb5->credentials, + chlg ? krb5->context : NULL, + krb5->spn, + (mutual_auth ? + ISC_REQ_MUTUAL_AUTH : 0), + 0, SECURITY_NATIVE_DREP, + chlg ? &chlg_desc : NULL, 0, + &context, + &resp_desc, &attrs, + &expiry); + + if(status == SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + + if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) + return CURLE_AUTH_ERROR; + + if(memcmp(&context, krb5->context, sizeof(context))) { + s_pSecFn->DeleteSecurityContext(krb5->context); + + memcpy(krb5->context, &context, sizeof(context)); + } + + if(resp_buf.cbBuffer) { + result = Curl_bufref_memdup(out, resp_buf.pvBuffer, resp_buf.cbBuffer); + } + else if(mutual_auth) + Curl_bufref_set(out, "", 0, NULL); + else + Curl_bufref_set(out, NULL, 0, NULL); + + return result; +} + +/* + * Curl_auth_create_gssapi_security_message() + * + * This is used to generate an already encoded GSSAPI (Kerberos V5) security + * token message ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * authzid [in] - The authorization identity if some. + * chlg [in] - The optional challenge message. + * krb5 [in/out] - The Kerberos 5 data struct being used and modified. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_gssapi_security_message(struct Curl_easy *data, + const char *authzid, + const struct bufref *chlg, + struct kerberos5data *krb5, + struct bufref *out) +{ + size_t offset = 0; + size_t messagelen = 0; + size_t appdatalen = 0; + unsigned char *trailer = NULL; + unsigned char *message = NULL; + unsigned char *padding = NULL; + unsigned char *appdata = NULL; + SecBuffer input_buf[2]; + SecBuffer wrap_buf[3]; + SecBufferDesc input_desc; + SecBufferDesc wrap_desc; + unsigned char *indata; + unsigned long qop = 0; + unsigned long sec_layer = 0; + unsigned long max_size = 0; + SecPkgContext_Sizes sizes; + SECURITY_STATUS status; + +#if defined(CURL_DISABLE_VERBOSE_STRINGS) + (void) data; +#endif + + /* Ensure we have a valid challenge message */ + if(!Curl_bufref_len(chlg)) { + infof(data, "GSSAPI handshake failure (empty security message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Get our response size information */ + status = s_pSecFn->QueryContextAttributes(krb5->context, + SECPKG_ATTR_SIZES, + &sizes); + + if(status == SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + + if(status != SEC_E_OK) + return CURLE_AUTH_ERROR; + + /* Setup the "input" security buffer */ + input_desc.ulVersion = SECBUFFER_VERSION; + input_desc.cBuffers = 2; + input_desc.pBuffers = input_buf; + input_buf[0].BufferType = SECBUFFER_STREAM; + input_buf[0].pvBuffer = (void *) Curl_bufref_ptr(chlg); + input_buf[0].cbBuffer = curlx_uztoul(Curl_bufref_len(chlg)); + input_buf[1].BufferType = SECBUFFER_DATA; + input_buf[1].pvBuffer = NULL; + input_buf[1].cbBuffer = 0; + + /* Decrypt the inbound challenge and obtain the qop */ + status = s_pSecFn->DecryptMessage(krb5->context, &input_desc, 0, &qop); + if(status != SEC_E_OK) { + infof(data, "GSSAPI handshake failure (empty security message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Not 4 octets long so fail as per RFC4752 Section 3.1 */ + if(input_buf[1].cbBuffer != 4) { + infof(data, "GSSAPI handshake failure (invalid security data)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Extract the security layer and the maximum message size */ + indata = input_buf[1].pvBuffer; + sec_layer = indata[0]; + max_size = ((unsigned long)indata[1] << 16) | + ((unsigned long)indata[2] << 8) | indata[3]; + + /* Free the challenge as it is not required anymore */ + s_pSecFn->FreeContextBuffer(input_buf[1].pvBuffer); + + /* Process the security layer */ + if(!(sec_layer & KERB_WRAP_NO_ENCRYPT)) { + infof(data, "GSSAPI handshake failure (invalid security layer)"); + return CURLE_BAD_CONTENT_ENCODING; + } + sec_layer &= KERB_WRAP_NO_ENCRYPT; /* We do not support a security layer */ + + /* Process the maximum message size the server can receive */ + if(max_size > 0) { + /* The server has told us it supports a maximum receive buffer, however, as + we don't require one unless we are encrypting data, we tell the server + our receive buffer is zero. */ + max_size = 0; + } + + /* Allocate the trailer */ + trailer = malloc(sizes.cbSecurityTrailer); + if(!trailer) + return CURLE_OUT_OF_MEMORY; + + /* Allocate our message */ + messagelen = 4; + if(authzid) + messagelen += strlen(authzid); + message = malloc(messagelen); + if(!message) { + free(trailer); + + return CURLE_OUT_OF_MEMORY; + } + + /* Populate the message with the security layer and client supported receive + message size. */ + message[0] = sec_layer & 0xFF; + message[1] = (max_size >> 16) & 0xFF; + message[2] = (max_size >> 8) & 0xFF; + message[3] = max_size & 0xFF; + + /* If given, append the authorization identity. */ + + if(authzid && *authzid) + memcpy(message + 4, authzid, messagelen - 4); + + /* Allocate the padding */ + padding = malloc(sizes.cbBlockSize); + if(!padding) { + free(message); + free(trailer); + + return CURLE_OUT_OF_MEMORY; + } + + /* Setup the "authentication data" security buffer */ + wrap_desc.ulVersion = SECBUFFER_VERSION; + wrap_desc.cBuffers = 3; + wrap_desc.pBuffers = wrap_buf; + wrap_buf[0].BufferType = SECBUFFER_TOKEN; + wrap_buf[0].pvBuffer = trailer; + wrap_buf[0].cbBuffer = sizes.cbSecurityTrailer; + wrap_buf[1].BufferType = SECBUFFER_DATA; + wrap_buf[1].pvBuffer = message; + wrap_buf[1].cbBuffer = curlx_uztoul(messagelen); + wrap_buf[2].BufferType = SECBUFFER_PADDING; + wrap_buf[2].pvBuffer = padding; + wrap_buf[2].cbBuffer = sizes.cbBlockSize; + + /* Encrypt the data */ + status = s_pSecFn->EncryptMessage(krb5->context, KERB_WRAP_NO_ENCRYPT, + &wrap_desc, 0); + if(status != SEC_E_OK) { + free(padding); + free(message); + free(trailer); + + if(status == SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + + return CURLE_AUTH_ERROR; + } + + /* Allocate the encryption (wrap) buffer */ + appdatalen = wrap_buf[0].cbBuffer + wrap_buf[1].cbBuffer + + wrap_buf[2].cbBuffer; + appdata = malloc(appdatalen); + if(!appdata) { + free(padding); + free(message); + free(trailer); + + return CURLE_OUT_OF_MEMORY; + } + + /* Populate the encryption buffer */ + memcpy(appdata, wrap_buf[0].pvBuffer, wrap_buf[0].cbBuffer); + offset += wrap_buf[0].cbBuffer; + memcpy(appdata + offset, wrap_buf[1].pvBuffer, wrap_buf[1].cbBuffer); + offset += wrap_buf[1].cbBuffer; + memcpy(appdata + offset, wrap_buf[2].pvBuffer, wrap_buf[2].cbBuffer); + + /* Free all of our local buffers */ + free(padding); + free(message); + free(trailer); + + /* Return the response. */ + Curl_bufref_set(out, appdata, appdatalen, curl_free); + return CURLE_OK; +} + +/* + * Curl_auth_cleanup_gssapi() + * + * This is used to clean up the GSSAPI (Kerberos V5) specific data. + * + * Parameters: + * + * krb5 [in/out] - The Kerberos 5 data struct being cleaned up. + * + */ +void Curl_auth_cleanup_gssapi(struct kerberos5data *krb5) +{ + /* Free our security context */ + if(krb5->context) { + s_pSecFn->DeleteSecurityContext(krb5->context); + free(krb5->context); + krb5->context = NULL; + } + + /* Free our credentials handle */ + if(krb5->credentials) { + s_pSecFn->FreeCredentialsHandle(krb5->credentials); + free(krb5->credentials); + krb5->credentials = NULL; + } + + /* Free our identity */ + Curl_sspi_free_identity(krb5->p_identity); + krb5->p_identity = NULL; + + /* Free the SPN and output token */ + Curl_safefree(krb5->spn); + Curl_safefree(krb5->output_token); + + /* Reset any variables */ + krb5->token_max = 0; +} + +#endif /* USE_WINDOWS_SSPI && USE_KERBEROS5 */ diff --git a/third_party/curl/lib/vauth/ntlm.c b/third_party/curl/lib/vauth/ntlm.c new file mode 100644 index 0000000..018e6a6 --- /dev/null +++ b/third_party/curl/lib/vauth/ntlm.c @@ -0,0 +1,780 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_NTLM) && !defined(USE_WINDOWS_SSPI) + +/* + * NTLM details: + * + * https://davenport.sourceforge.net/ntlm.html + * https://www.innovation.ch/java/ntlm.html + */ + +#define DEBUG_ME 0 + +#include "urldata.h" +#include "sendf.h" +#include "curl_ntlm_core.h" +#include "curl_gethostname.h" +#include "curl_multibyte.h" +#include "curl_md5.h" +#include "warnless.h" +#include "rand.h" +#include "vtls/vtls.h" +#include "strdup.h" + +#define BUILDING_CURL_NTLM_MSGS_C +#include "vauth/vauth.h" +#include "vauth/ntlm.h" +#include "curl_endian.h" +#include "curl_printf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* "NTLMSSP" signature is always in ASCII regardless of the platform */ +#define NTLMSSP_SIGNATURE "\x4e\x54\x4c\x4d\x53\x53\x50" + +/* The fixed host name we provide, in order to not leak our real local host + name. Copy the name used by Firefox. */ +#define NTLM_HOSTNAME "WORKSTATION" + +#if DEBUG_ME +# define DEBUG_OUT(x) x +static void ntlm_print_flags(FILE *handle, unsigned long flags) +{ + if(flags & NTLMFLAG_NEGOTIATE_UNICODE) + fprintf(handle, "NTLMFLAG_NEGOTIATE_UNICODE "); + if(flags & NTLMFLAG_NEGOTIATE_OEM) + fprintf(handle, "NTLMFLAG_NEGOTIATE_OEM "); + if(flags & NTLMFLAG_REQUEST_TARGET) + fprintf(handle, "NTLMFLAG_REQUEST_TARGET "); + if(flags & (1<<3)) + fprintf(handle, "NTLMFLAG_UNKNOWN_3 "); + if(flags & NTLMFLAG_NEGOTIATE_SIGN) + fprintf(handle, "NTLMFLAG_NEGOTIATE_SIGN "); + if(flags & NTLMFLAG_NEGOTIATE_SEAL) + fprintf(handle, "NTLMFLAG_NEGOTIATE_SEAL "); + if(flags & NTLMFLAG_NEGOTIATE_DATAGRAM_STYLE) + fprintf(handle, "NTLMFLAG_NEGOTIATE_DATAGRAM_STYLE "); + if(flags & NTLMFLAG_NEGOTIATE_LM_KEY) + fprintf(handle, "NTLMFLAG_NEGOTIATE_LM_KEY "); + if(flags & NTLMFLAG_NEGOTIATE_NTLM_KEY) + fprintf(handle, "NTLMFLAG_NEGOTIATE_NTLM_KEY "); + if(flags & (1<<10)) + fprintf(handle, "NTLMFLAG_UNKNOWN_10 "); + if(flags & NTLMFLAG_NEGOTIATE_ANONYMOUS) + fprintf(handle, "NTLMFLAG_NEGOTIATE_ANONYMOUS "); + if(flags & NTLMFLAG_NEGOTIATE_DOMAIN_SUPPLIED) + fprintf(handle, "NTLMFLAG_NEGOTIATE_DOMAIN_SUPPLIED "); + if(flags & NTLMFLAG_NEGOTIATE_WORKSTATION_SUPPLIED) + fprintf(handle, "NTLMFLAG_NEGOTIATE_WORKSTATION_SUPPLIED "); + if(flags & NTLMFLAG_NEGOTIATE_LOCAL_CALL) + fprintf(handle, "NTLMFLAG_NEGOTIATE_LOCAL_CALL "); + if(flags & NTLMFLAG_NEGOTIATE_ALWAYS_SIGN) + fprintf(handle, "NTLMFLAG_NEGOTIATE_ALWAYS_SIGN "); + if(flags & NTLMFLAG_TARGET_TYPE_DOMAIN) + fprintf(handle, "NTLMFLAG_TARGET_TYPE_DOMAIN "); + if(flags & NTLMFLAG_TARGET_TYPE_SERVER) + fprintf(handle, "NTLMFLAG_TARGET_TYPE_SERVER "); + if(flags & NTLMFLAG_TARGET_TYPE_SHARE) + fprintf(handle, "NTLMFLAG_TARGET_TYPE_SHARE "); + if(flags & NTLMFLAG_NEGOTIATE_NTLM2_KEY) + fprintf(handle, "NTLMFLAG_NEGOTIATE_NTLM2_KEY "); + if(flags & NTLMFLAG_REQUEST_INIT_RESPONSE) + fprintf(handle, "NTLMFLAG_REQUEST_INIT_RESPONSE "); + if(flags & NTLMFLAG_REQUEST_ACCEPT_RESPONSE) + fprintf(handle, "NTLMFLAG_REQUEST_ACCEPT_RESPONSE "); + if(flags & NTLMFLAG_REQUEST_NONNT_SESSION_KEY) + fprintf(handle, "NTLMFLAG_REQUEST_NONNT_SESSION_KEY "); + if(flags & NTLMFLAG_NEGOTIATE_TARGET_INFO) + fprintf(handle, "NTLMFLAG_NEGOTIATE_TARGET_INFO "); + if(flags & (1<<24)) + fprintf(handle, "NTLMFLAG_UNKNOWN_24 "); + if(flags & (1<<25)) + fprintf(handle, "NTLMFLAG_UNKNOWN_25 "); + if(flags & (1<<26)) + fprintf(handle, "NTLMFLAG_UNKNOWN_26 "); + if(flags & (1<<27)) + fprintf(handle, "NTLMFLAG_UNKNOWN_27 "); + if(flags & (1<<28)) + fprintf(handle, "NTLMFLAG_UNKNOWN_28 "); + if(flags & NTLMFLAG_NEGOTIATE_128) + fprintf(handle, "NTLMFLAG_NEGOTIATE_128 "); + if(flags & NTLMFLAG_NEGOTIATE_KEY_EXCHANGE) + fprintf(handle, "NTLMFLAG_NEGOTIATE_KEY_EXCHANGE "); + if(flags & NTLMFLAG_NEGOTIATE_56) + fprintf(handle, "NTLMFLAG_NEGOTIATE_56 "); +} + +static void ntlm_print_hex(FILE *handle, const char *buf, size_t len) +{ + const char *p = buf; + + (void) handle; + + fprintf(stderr, "0x"); + while(len-- > 0) + fprintf(stderr, "%02.2x", (unsigned int)*p++); +} +#else +# define DEBUG_OUT(x) Curl_nop_stmt +#endif + +/* + * ntlm_decode_type2_target() + * + * This is used to decode the "target info" in the NTLM type-2 message + * received. + * + * Parameters: + * + * data [in] - The session handle. + * type2ref [in] - The type-2 message. + * ntlm [in/out] - The NTLM data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +static CURLcode ntlm_decode_type2_target(struct Curl_easy *data, + const struct bufref *type2ref, + struct ntlmdata *ntlm) +{ + unsigned short target_info_len = 0; + unsigned int target_info_offset = 0; + const unsigned char *type2 = Curl_bufref_ptr(type2ref); + size_t type2len = Curl_bufref_len(type2ref); + +#if defined(CURL_DISABLE_VERBOSE_STRINGS) + (void) data; +#endif + + if(type2len >= 48) { + target_info_len = Curl_read16_le(&type2[40]); + target_info_offset = Curl_read32_le(&type2[44]); + if(target_info_len > 0) { + if((target_info_offset > type2len) || + (target_info_offset + target_info_len) > type2len || + target_info_offset < 48) { + infof(data, "NTLM handshake failure (bad type-2 message). " + "Target Info Offset Len is set incorrect by the peer"); + return CURLE_BAD_CONTENT_ENCODING; + } + + free(ntlm->target_info); /* replace any previous data */ + ntlm->target_info = Curl_memdup(&type2[target_info_offset], + target_info_len); + if(!ntlm->target_info) + return CURLE_OUT_OF_MEMORY; + } + } + + ntlm->target_info_len = target_info_len; + + return CURLE_OK; +} + +/* + NTLM message structure notes: + + A 'short' is a 'network short', a little-endian 16-bit unsigned value. + + A 'long' is a 'network long', a little-endian, 32-bit unsigned value. + + A 'security buffer' represents a triplet used to point to a buffer, + consisting of two shorts and one long: + + 1. A 'short' containing the length of the buffer content in bytes. + 2. A 'short' containing the allocated space for the buffer in bytes. + 3. A 'long' containing the offset to the start of the buffer in bytes, + from the beginning of the NTLM message. +*/ + +/* + * Curl_auth_is_ntlm_supported() + * + * This is used to evaluate if NTLM is supported. + * + * Parameters: None + * + * Returns TRUE as NTLM as handled by libcurl. + */ +bool Curl_auth_is_ntlm_supported(void) +{ + return TRUE; +} + +/* + * Curl_auth_decode_ntlm_type2_message() + * + * This is used to decode an NTLM type-2 message. The raw NTLM message is + * checked * for validity before the appropriate data for creating a type-3 + * message is * written to the given NTLM data structure. + * + * Parameters: + * + * data [in] - The session handle. + * type2ref [in] - The type-2 message. + * ntlm [in/out] - The NTLM data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_ntlm_type2_message(struct Curl_easy *data, + const struct bufref *type2ref, + struct ntlmdata *ntlm) +{ + static const char type2_marker[] = { 0x02, 0x00, 0x00, 0x00 }; + + /* NTLM type-2 message structure: + + Index Description Content + 0 NTLMSSP Signature Null-terminated ASCII "NTLMSSP" + (0x4e544c4d53535000) + 8 NTLM Message Type long (0x02000000) + 12 Target Name security buffer + 20 Flags long + 24 Challenge 8 bytes + (32) Context 8 bytes (two consecutive longs) (*) + (40) Target Information security buffer (*) + (48) OS Version Structure 8 bytes (*) + 32 (48) (56) Start of data block (*) + (*) -> Optional + */ + + CURLcode result = CURLE_OK; + const unsigned char *type2 = Curl_bufref_ptr(type2ref); + size_t type2len = Curl_bufref_len(type2ref); + +#if defined(CURL_DISABLE_VERBOSE_STRINGS) + (void)data; +#endif + + ntlm->flags = 0; + + if((type2len < 32) || + (memcmp(type2, NTLMSSP_SIGNATURE, 8) != 0) || + (memcmp(type2 + 8, type2_marker, sizeof(type2_marker)) != 0)) { + /* This was not a good enough type-2 message */ + infof(data, "NTLM handshake failure (bad type-2 message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + ntlm->flags = Curl_read32_le(&type2[20]); + memcpy(ntlm->nonce, &type2[24], 8); + + if(ntlm->flags & NTLMFLAG_NEGOTIATE_TARGET_INFO) { + result = ntlm_decode_type2_target(data, type2ref, ntlm); + if(result) { + infof(data, "NTLM handshake failure (bad type-2 message)"); + return result; + } + } + + DEBUG_OUT({ + fprintf(stderr, "**** TYPE2 header flags=0x%08.8lx ", ntlm->flags); + ntlm_print_flags(stderr, ntlm->flags); + fprintf(stderr, "\n nonce="); + ntlm_print_hex(stderr, (char *)ntlm->nonce, 8); + fprintf(stderr, "\n****\n"); + fprintf(stderr, "**** Header %s\n ", header); + }); + + return result; +} + +/* copy the source to the destination and fill in zeroes in every + other destination byte! */ +static void unicodecpy(unsigned char *dest, const char *src, size_t length) +{ + size_t i; + for(i = 0; i < length; i++) { + dest[2 * i] = (unsigned char)src[i]; + dest[2 * i + 1] = '\0'; + } +} + +/* + * Curl_auth_create_ntlm_type1_message() + * + * This is used to generate an NTLM type-1 message ready for sending to the + * recipient using the appropriate compile time crypto API. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name in the format User or Domain\User. + * passwdp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * host [in] - The host name. + * ntlm [in/out] - The NTLM data struct being used and modified. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_ntlm_type1_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + const char *service, + const char *hostname, + struct ntlmdata *ntlm, + struct bufref *out) +{ + /* NTLM type-1 message structure: + + Index Description Content + 0 NTLMSSP Signature Null-terminated ASCII "NTLMSSP" + (0x4e544c4d53535000) + 8 NTLM Message Type long (0x01000000) + 12 Flags long + (16) Supplied Domain security buffer (*) + (24) Supplied Workstation security buffer (*) + (32) OS Version Structure 8 bytes (*) + (32) (40) Start of data block (*) + (*) -> Optional + */ + + size_t size; + + char *ntlmbuf; + const char *host = ""; /* empty */ + const char *domain = ""; /* empty */ + size_t hostlen = 0; + size_t domlen = 0; + size_t hostoff = 0; + size_t domoff = hostoff + hostlen; /* This is 0: remember that host and + domain are empty */ + (void)data; + (void)userp; + (void)passwdp; + (void)service; + (void)hostname; + + /* Clean up any former leftovers and initialise to defaults */ + Curl_auth_cleanup_ntlm(ntlm); + + ntlmbuf = aprintf(NTLMSSP_SIGNATURE "%c" + "\x01%c%c%c" /* 32-bit type = 1 */ + "%c%c%c%c" /* 32-bit NTLM flag field */ + "%c%c" /* domain length */ + "%c%c" /* domain allocated space */ + "%c%c" /* domain name offset */ + "%c%c" /* 2 zeroes */ + "%c%c" /* host length */ + "%c%c" /* host allocated space */ + "%c%c" /* host name offset */ + "%c%c" /* 2 zeroes */ + "%s" /* host name */ + "%s", /* domain string */ + 0, /* trailing zero */ + 0, 0, 0, /* part of type-1 long */ + + LONGQUARTET(NTLMFLAG_NEGOTIATE_OEM | + NTLMFLAG_REQUEST_TARGET | + NTLMFLAG_NEGOTIATE_NTLM_KEY | + NTLMFLAG_NEGOTIATE_NTLM2_KEY | + NTLMFLAG_NEGOTIATE_ALWAYS_SIGN), + SHORTPAIR(domlen), + SHORTPAIR(domlen), + SHORTPAIR(domoff), + 0, 0, + SHORTPAIR(hostlen), + SHORTPAIR(hostlen), + SHORTPAIR(hostoff), + 0, 0, + host, /* this is empty */ + domain /* this is empty */); + + if(!ntlmbuf) + return CURLE_OUT_OF_MEMORY; + + /* Initial packet length */ + size = 32 + hostlen + domlen; + + DEBUG_OUT({ + fprintf(stderr, "* TYPE1 header flags=0x%02.2x%02.2x%02.2x%02.2x " + "0x%08.8x ", + LONGQUARTET(NTLMFLAG_NEGOTIATE_OEM | + NTLMFLAG_REQUEST_TARGET | + NTLMFLAG_NEGOTIATE_NTLM_KEY | + NTLMFLAG_NEGOTIATE_NTLM2_KEY | + NTLMFLAG_NEGOTIATE_ALWAYS_SIGN), + NTLMFLAG_NEGOTIATE_OEM | + NTLMFLAG_REQUEST_TARGET | + NTLMFLAG_NEGOTIATE_NTLM_KEY | + NTLMFLAG_NEGOTIATE_NTLM2_KEY | + NTLMFLAG_NEGOTIATE_ALWAYS_SIGN); + ntlm_print_flags(stderr, + NTLMFLAG_NEGOTIATE_OEM | + NTLMFLAG_REQUEST_TARGET | + NTLMFLAG_NEGOTIATE_NTLM_KEY | + NTLMFLAG_NEGOTIATE_NTLM2_KEY | + NTLMFLAG_NEGOTIATE_ALWAYS_SIGN); + fprintf(stderr, "\n****\n"); + }); + + Curl_bufref_set(out, ntlmbuf, size, curl_free); + return CURLE_OK; +} + +/* + * Curl_auth_create_ntlm_type3_message() + * + * This is used to generate an already encoded NTLM type-3 message ready for + * sending to the recipient using the appropriate compile time crypto API. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name in the format User or Domain\User. + * passwdp [in] - The user's password. + * ntlm [in/out] - The NTLM data struct being used and modified. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_ntlm_type3_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + struct ntlmdata *ntlm, + struct bufref *out) +{ + /* NTLM type-3 message structure: + + Index Description Content + 0 NTLMSSP Signature Null-terminated ASCII "NTLMSSP" + (0x4e544c4d53535000) + 8 NTLM Message Type long (0x03000000) + 12 LM/LMv2 Response security buffer + 20 NTLM/NTLMv2 Response security buffer + 28 Target Name security buffer + 36 User Name security buffer + 44 Workstation Name security buffer + (52) Session Key security buffer (*) + (60) Flags long (*) + (64) OS Version Structure 8 bytes (*) + 52 (64) (72) Start of data block + (*) -> Optional + */ + + CURLcode result = CURLE_OK; + size_t size; + unsigned char ntlmbuf[NTLM_BUFSIZE]; + int lmrespoff; + unsigned char lmresp[24]; /* fixed-size */ + int ntrespoff; + unsigned int ntresplen = 24; + unsigned char ntresp[24]; /* fixed-size */ + unsigned char *ptr_ntresp = &ntresp[0]; + unsigned char *ntlmv2resp = NULL; + bool unicode = (ntlm->flags & NTLMFLAG_NEGOTIATE_UNICODE) ? TRUE : FALSE; + char host[HOSTNAME_MAX + 1] = ""; + const char *user; + const char *domain = ""; + size_t hostoff = 0; + size_t useroff = 0; + size_t domoff = 0; + size_t hostlen = 0; + size_t userlen = 0; + size_t domlen = 0; + + memset(lmresp, 0, sizeof(lmresp)); + memset(ntresp, 0, sizeof(ntresp)); + user = strchr(userp, '\\'); + if(!user) + user = strchr(userp, '/'); + + if(user) { + domain = userp; + domlen = (user - domain); + user++; + } + else + user = userp; + + userlen = strlen(user); + +#ifndef NTLM_HOSTNAME + /* Get the machine's un-qualified host name as NTLM doesn't like the fully + qualified domain name */ + if(Curl_gethostname(host, sizeof(host))) { + infof(data, "gethostname() failed, continuing without"); + hostlen = 0; + } + else { + hostlen = strlen(host); + } +#else + (void)msnprintf(host, sizeof(host), "%s", NTLM_HOSTNAME); + hostlen = sizeof(NTLM_HOSTNAME)-1; +#endif + + if(ntlm->flags & NTLMFLAG_NEGOTIATE_NTLM2_KEY) { + unsigned char ntbuffer[0x18]; + unsigned char entropy[8]; + unsigned char ntlmv2hash[0x18]; + + /* Full NTLM version 2 + Although this cannot be negotiated, it is used here if available, as + servers featuring extended security are likely supporting also + NTLMv2. */ + result = Curl_rand(data, entropy, 8); + if(result) + return result; + + result = Curl_ntlm_core_mk_nt_hash(passwdp, ntbuffer); + if(result) + return result; + + result = Curl_ntlm_core_mk_ntlmv2_hash(user, userlen, domain, domlen, + ntbuffer, ntlmv2hash); + if(result) + return result; + + /* LMv2 response */ + result = Curl_ntlm_core_mk_lmv2_resp(ntlmv2hash, entropy, + &ntlm->nonce[0], lmresp); + if(result) + return result; + + /* NTLMv2 response */ + result = Curl_ntlm_core_mk_ntlmv2_resp(ntlmv2hash, entropy, + ntlm, &ntlmv2resp, &ntresplen); + if(result) + return result; + + ptr_ntresp = ntlmv2resp; + } + else { + + unsigned char ntbuffer[0x18]; + unsigned char lmbuffer[0x18]; + + /* NTLM version 1 */ + + result = Curl_ntlm_core_mk_nt_hash(passwdp, ntbuffer); + if(result) + return result; + + Curl_ntlm_core_lm_resp(ntbuffer, &ntlm->nonce[0], ntresp); + + result = Curl_ntlm_core_mk_lm_hash(passwdp, lmbuffer); + if(result) + return result; + + Curl_ntlm_core_lm_resp(lmbuffer, &ntlm->nonce[0], lmresp); + ntlm->flags &= ~NTLMFLAG_NEGOTIATE_NTLM2_KEY; + + /* A safer but less compatible alternative is: + * Curl_ntlm_core_lm_resp(ntbuffer, &ntlm->nonce[0], lmresp); + * See https://davenport.sourceforge.net/ntlm.html#ntlmVersion2 */ + } + + if(unicode) { + domlen = domlen * 2; + userlen = userlen * 2; + hostlen = hostlen * 2; + } + + lmrespoff = 64; /* size of the message header */ + ntrespoff = lmrespoff + 0x18; + domoff = ntrespoff + ntresplen; + useroff = domoff + domlen; + hostoff = useroff + userlen; + + /* Create the big type-3 message binary blob */ + size = msnprintf((char *)ntlmbuf, NTLM_BUFSIZE, + NTLMSSP_SIGNATURE "%c" + "\x03%c%c%c" /* 32-bit type = 3 */ + + "%c%c" /* LanManager length */ + "%c%c" /* LanManager allocated space */ + "%c%c" /* LanManager offset */ + "%c%c" /* 2 zeroes */ + + "%c%c" /* NT-response length */ + "%c%c" /* NT-response allocated space */ + "%c%c" /* NT-response offset */ + "%c%c" /* 2 zeroes */ + + "%c%c" /* domain length */ + "%c%c" /* domain allocated space */ + "%c%c" /* domain name offset */ + "%c%c" /* 2 zeroes */ + + "%c%c" /* user length */ + "%c%c" /* user allocated space */ + "%c%c" /* user offset */ + "%c%c" /* 2 zeroes */ + + "%c%c" /* host length */ + "%c%c" /* host allocated space */ + "%c%c" /* host offset */ + "%c%c" /* 2 zeroes */ + + "%c%c" /* session key length (unknown purpose) */ + "%c%c" /* session key allocated space (unknown purpose) */ + "%c%c" /* session key offset (unknown purpose) */ + "%c%c" /* 2 zeroes */ + + "%c%c%c%c", /* flags */ + + /* domain string */ + /* user string */ + /* host string */ + /* LanManager response */ + /* NT response */ + + 0, /* null-termination */ + 0, 0, 0, /* type-3 long, the 24 upper bits */ + + SHORTPAIR(0x18), /* LanManager response length, twice */ + SHORTPAIR(0x18), + SHORTPAIR(lmrespoff), + 0x0, 0x0, + + SHORTPAIR(ntresplen), /* NT-response length, twice */ + SHORTPAIR(ntresplen), + SHORTPAIR(ntrespoff), + 0x0, 0x0, + + SHORTPAIR(domlen), + SHORTPAIR(domlen), + SHORTPAIR(domoff), + 0x0, 0x0, + + SHORTPAIR(userlen), + SHORTPAIR(userlen), + SHORTPAIR(useroff), + 0x0, 0x0, + + SHORTPAIR(hostlen), + SHORTPAIR(hostlen), + SHORTPAIR(hostoff), + 0x0, 0x0, + + 0x0, 0x0, + 0x0, 0x0, + 0x0, 0x0, + 0x0, 0x0, + + LONGQUARTET(ntlm->flags)); + + DEBUGASSERT(size == 64); + DEBUGASSERT(size == (size_t)lmrespoff); + + /* We append the binary hashes */ + if(size < (NTLM_BUFSIZE - 0x18)) { + memcpy(&ntlmbuf[size], lmresp, 0x18); + size += 0x18; + } + + DEBUG_OUT({ + fprintf(stderr, "**** TYPE3 header lmresp="); + ntlm_print_hex(stderr, (char *)&ntlmbuf[lmrespoff], 0x18); + }); + + /* ntresplen + size should not be risking an integer overflow here */ + if(ntresplen + size > sizeof(ntlmbuf)) { + failf(data, "incoming NTLM message too big"); + return CURLE_OUT_OF_MEMORY; + } + DEBUGASSERT(size == (size_t)ntrespoff); + memcpy(&ntlmbuf[size], ptr_ntresp, ntresplen); + size += ntresplen; + + DEBUG_OUT({ + fprintf(stderr, "\n ntresp="); + ntlm_print_hex(stderr, (char *)&ntlmbuf[ntrespoff], ntresplen); + }); + + free(ntlmv2resp);/* Free the dynamic buffer allocated for NTLMv2 */ + + DEBUG_OUT({ + fprintf(stderr, "\n flags=0x%02.2x%02.2x%02.2x%02.2x 0x%08.8x ", + LONGQUARTET(ntlm->flags), ntlm->flags); + ntlm_print_flags(stderr, ntlm->flags); + fprintf(stderr, "\n****\n"); + }); + + /* Make sure that the domain, user and host strings fit in the + buffer before we copy them there. */ + if(size + userlen + domlen + hostlen >= NTLM_BUFSIZE) { + failf(data, "user + domain + host name too big"); + return CURLE_OUT_OF_MEMORY; + } + + DEBUGASSERT(size == domoff); + if(unicode) + unicodecpy(&ntlmbuf[size], domain, domlen / 2); + else + memcpy(&ntlmbuf[size], domain, domlen); + + size += domlen; + + DEBUGASSERT(size == useroff); + if(unicode) + unicodecpy(&ntlmbuf[size], user, userlen / 2); + else + memcpy(&ntlmbuf[size], user, userlen); + + size += userlen; + + DEBUGASSERT(size == hostoff); + if(unicode) + unicodecpy(&ntlmbuf[size], host, hostlen / 2); + else + memcpy(&ntlmbuf[size], host, hostlen); + + size += hostlen; + + /* Return the binary blob. */ + result = Curl_bufref_memdup(out, ntlmbuf, size); + + Curl_auth_cleanup_ntlm(ntlm); + + return result; +} + +/* + * Curl_auth_cleanup_ntlm() + * + * This is used to clean up the NTLM specific data. + * + * Parameters: + * + * ntlm [in/out] - The NTLM data struct being cleaned up. + * + */ +void Curl_auth_cleanup_ntlm(struct ntlmdata *ntlm) +{ + /* Free the target info */ + Curl_safefree(ntlm->target_info); + + /* Reset any variables */ + ntlm->target_info_len = 0; +} + +#endif /* USE_NTLM && !USE_WINDOWS_SSPI */ diff --git a/third_party/curl/lib/vauth/ntlm.h b/third_party/curl/lib/vauth/ntlm.h new file mode 100644 index 0000000..31ce921 --- /dev/null +++ b/third_party/curl/lib/vauth/ntlm.h @@ -0,0 +1,143 @@ +#ifndef HEADER_VAUTH_NTLM_H +#define HEADER_VAUTH_NTLM_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_NTLM + +/* NTLM buffer fixed size, large enough for long user + host + domain */ +#define NTLM_BUFSIZE 1024 + +/* Stuff only required for curl_ntlm_msgs.c */ +#ifdef BUILDING_CURL_NTLM_MSGS_C + +/* Flag bits definitions based on + https://davenport.sourceforge.net/ntlm.html */ + +#define NTLMFLAG_NEGOTIATE_UNICODE (1<<0) +/* Indicates that Unicode strings are supported for use in security buffer + data. */ + +#define NTLMFLAG_NEGOTIATE_OEM (1<<1) +/* Indicates that OEM strings are supported for use in security buffer data. */ + +#define NTLMFLAG_REQUEST_TARGET (1<<2) +/* Requests that the server's authentication realm be included in the Type 2 + message. */ + +/* unknown (1<<3) */ +#define NTLMFLAG_NEGOTIATE_SIGN (1<<4) +/* Specifies that authenticated communication between the client and server + should carry a digital signature (message integrity). */ + +#define NTLMFLAG_NEGOTIATE_SEAL (1<<5) +/* Specifies that authenticated communication between the client and server + should be encrypted (message confidentiality). */ + +#define NTLMFLAG_NEGOTIATE_DATAGRAM_STYLE (1<<6) +/* Indicates that datagram authentication is being used. */ + +#define NTLMFLAG_NEGOTIATE_LM_KEY (1<<7) +/* Indicates that the LAN Manager session key should be used for signing and + sealing authenticated communications. */ + +#define NTLMFLAG_NEGOTIATE_NTLM_KEY (1<<9) +/* Indicates that NTLM authentication is being used. */ + +/* unknown (1<<10) */ + +#define NTLMFLAG_NEGOTIATE_ANONYMOUS (1<<11) +/* Sent by the client in the Type 3 message to indicate that an anonymous + context has been established. This also affects the response fields. */ + +#define NTLMFLAG_NEGOTIATE_DOMAIN_SUPPLIED (1<<12) +/* Sent by the client in the Type 1 message to indicate that a desired + authentication realm is included in the message. */ + +#define NTLMFLAG_NEGOTIATE_WORKSTATION_SUPPLIED (1<<13) +/* Sent by the client in the Type 1 message to indicate that the client + workstation's name is included in the message. */ + +#define NTLMFLAG_NEGOTIATE_LOCAL_CALL (1<<14) +/* Sent by the server to indicate that the server and client are on the same + machine. Implies that the client may use a pre-established local security + context rather than responding to the challenge. */ + +#define NTLMFLAG_NEGOTIATE_ALWAYS_SIGN (1<<15) +/* Indicates that authenticated communication between the client and server + should be signed with a "dummy" signature. */ + +#define NTLMFLAG_TARGET_TYPE_DOMAIN (1<<16) +/* Sent by the server in the Type 2 message to indicate that the target + authentication realm is a domain. */ + +#define NTLMFLAG_TARGET_TYPE_SERVER (1<<17) +/* Sent by the server in the Type 2 message to indicate that the target + authentication realm is a server. */ + +#define NTLMFLAG_TARGET_TYPE_SHARE (1<<18) +/* Sent by the server in the Type 2 message to indicate that the target + authentication realm is a share. Presumably, this is for share-level + authentication. Usage is unclear. */ + +#define NTLMFLAG_NEGOTIATE_NTLM2_KEY (1<<19) +/* Indicates that the NTLM2 signing and sealing scheme should be used for + protecting authenticated communications. */ + +#define NTLMFLAG_REQUEST_INIT_RESPONSE (1<<20) +/* unknown purpose */ + +#define NTLMFLAG_REQUEST_ACCEPT_RESPONSE (1<<21) +/* unknown purpose */ + +#define NTLMFLAG_REQUEST_NONNT_SESSION_KEY (1<<22) +/* unknown purpose */ + +#define NTLMFLAG_NEGOTIATE_TARGET_INFO (1<<23) +/* Sent by the server in the Type 2 message to indicate that it is including a + Target Information block in the message. */ + +/* unknown (1<24) */ +/* unknown (1<25) */ +/* unknown (1<26) */ +/* unknown (1<27) */ +/* unknown (1<28) */ + +#define NTLMFLAG_NEGOTIATE_128 (1<<29) +/* Indicates that 128-bit encryption is supported. */ + +#define NTLMFLAG_NEGOTIATE_KEY_EXCHANGE (1<<30) +/* Indicates that the client will provide an encrypted master key in + the "Session Key" field of the Type 3 message. */ + +#define NTLMFLAG_NEGOTIATE_56 (1<<31) +/* Indicates that 56-bit encryption is supported. */ + +#endif /* BUILDING_CURL_NTLM_MSGS_C */ + +#endif /* USE_NTLM */ + +#endif /* HEADER_VAUTH_NTLM_H */ diff --git a/third_party/curl/lib/vauth/ntlm_sspi.c b/third_party/curl/lib/vauth/ntlm_sspi.c new file mode 100644 index 0000000..9205431 --- /dev/null +++ b/third_party/curl/lib/vauth/ntlm_sspi.c @@ -0,0 +1,372 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_WINDOWS_SSPI) && defined(USE_NTLM) + +#include + +#include "vauth/vauth.h" +#include "urldata.h" +#include "curl_ntlm_core.h" +#include "warnless.h" +#include "curl_multibyte.h" +#include "sendf.h" +#include "strdup.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_is_ntlm_supported() + * + * This is used to evaluate if NTLM is supported. + * + * Parameters: None + * + * Returns TRUE if NTLM is supported by Windows SSPI. + */ +bool Curl_auth_is_ntlm_supported(void) +{ + PSecPkgInfo SecurityPackage; + SECURITY_STATUS status; + + /* Query the security package for NTLM */ + status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_NTLM), + &SecurityPackage); + + /* Release the package buffer as it is not required anymore */ + if(status == SEC_E_OK) { + s_pSecFn->FreeContextBuffer(SecurityPackage); + } + + return (status == SEC_E_OK ? TRUE : FALSE); +} + +/* + * Curl_auth_create_ntlm_type1_message() + * + * This is used to generate an already encoded NTLM type-1 message ready for + * sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name in the format User or Domain\User. + * passwdp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * host [in] - The host name. + * ntlm [in/out] - The NTLM data struct being used and modified. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_ntlm_type1_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + const char *service, + const char *host, + struct ntlmdata *ntlm, + struct bufref *out) +{ + PSecPkgInfo SecurityPackage; + SecBuffer type_1_buf; + SecBufferDesc type_1_desc; + SECURITY_STATUS status; + unsigned long attrs; + TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ + + /* Clean up any former leftovers and initialise to defaults */ + Curl_auth_cleanup_ntlm(ntlm); + + /* Query the security package for NTLM */ + status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_NTLM), + &SecurityPackage); + if(status != SEC_E_OK) { + failf(data, "SSPI: couldn't get auth info"); + return CURLE_AUTH_ERROR; + } + + ntlm->token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + s_pSecFn->FreeContextBuffer(SecurityPackage); + + /* Allocate our output buffer */ + ntlm->output_token = malloc(ntlm->token_max); + if(!ntlm->output_token) + return CURLE_OUT_OF_MEMORY; + + if(userp && *userp) { + CURLcode result; + + /* Populate our identity structure */ + result = Curl_create_sspi_identity(userp, passwdp, &ntlm->identity); + if(result) + return result; + + /* Allow proper cleanup of the identity structure */ + ntlm->p_identity = &ntlm->identity; + } + else + /* Use the current Windows user */ + ntlm->p_identity = NULL; + + /* Allocate our credentials handle */ + ntlm->credentials = calloc(1, sizeof(CredHandle)); + if(!ntlm->credentials) + return CURLE_OUT_OF_MEMORY; + + /* Acquire our credentials handle */ + status = s_pSecFn->AcquireCredentialsHandle(NULL, + (TCHAR *) TEXT(SP_NAME_NTLM), + SECPKG_CRED_OUTBOUND, NULL, + ntlm->p_identity, NULL, NULL, + ntlm->credentials, &expiry); + if(status != SEC_E_OK) + return CURLE_LOGIN_DENIED; + + /* Allocate our new context handle */ + ntlm->context = calloc(1, sizeof(CtxtHandle)); + if(!ntlm->context) + return CURLE_OUT_OF_MEMORY; + + ntlm->spn = Curl_auth_build_spn(service, host, NULL); + if(!ntlm->spn) + return CURLE_OUT_OF_MEMORY; + + /* Setup the type-1 "output" security buffer */ + type_1_desc.ulVersion = SECBUFFER_VERSION; + type_1_desc.cBuffers = 1; + type_1_desc.pBuffers = &type_1_buf; + type_1_buf.BufferType = SECBUFFER_TOKEN; + type_1_buf.pvBuffer = ntlm->output_token; + type_1_buf.cbBuffer = curlx_uztoul(ntlm->token_max); + + /* Generate our type-1 message */ + status = s_pSecFn->InitializeSecurityContext(ntlm->credentials, NULL, + ntlm->spn, + 0, 0, SECURITY_NETWORK_DREP, + NULL, 0, + ntlm->context, &type_1_desc, + &attrs, &expiry); + if(status == SEC_I_COMPLETE_NEEDED || + status == SEC_I_COMPLETE_AND_CONTINUE) + s_pSecFn->CompleteAuthToken(ntlm->context, &type_1_desc); + else if(status == SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) + return CURLE_AUTH_ERROR; + + /* Return the response. */ + Curl_bufref_set(out, ntlm->output_token, type_1_buf.cbBuffer, NULL); + return CURLE_OK; +} + +/* + * Curl_auth_decode_ntlm_type2_message() + * + * This is used to decode an already encoded NTLM type-2 message. + * + * Parameters: + * + * data [in] - The session handle. + * type2 [in] - The type-2 message. + * ntlm [in/out] - The NTLM data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_ntlm_type2_message(struct Curl_easy *data, + const struct bufref *type2, + struct ntlmdata *ntlm) +{ +#if defined(CURL_DISABLE_VERBOSE_STRINGS) + (void) data; +#endif + + /* Ensure we have a valid type-2 message */ + if(!Curl_bufref_len(type2)) { + infof(data, "NTLM handshake failure (empty type-2 message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Store the challenge for later use */ + ntlm->input_token = Curl_memdup0((const char *)Curl_bufref_ptr(type2), + Curl_bufref_len(type2)); + if(!ntlm->input_token) + return CURLE_OUT_OF_MEMORY; + ntlm->input_token_len = Curl_bufref_len(type2); + + return CURLE_OK; +} + +/* +* Curl_auth_create_ntlm_type3_message() + * Curl_auth_create_ntlm_type3_message() + * + * This is used to generate an already encoded NTLM type-3 message ready for + * sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name in the format User or Domain\User. + * passwdp [in] - The user's password. + * ntlm [in/out] - The NTLM data struct being used and modified. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_ntlm_type3_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + struct ntlmdata *ntlm, + struct bufref *out) +{ + CURLcode result = CURLE_OK; + SecBuffer type_2_bufs[2]; + SecBuffer type_3_buf; + SecBufferDesc type_2_desc; + SecBufferDesc type_3_desc; + SECURITY_STATUS status; + unsigned long attrs; + TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ + +#if defined(CURL_DISABLE_VERBOSE_STRINGS) + (void) data; +#endif + (void) passwdp; + (void) userp; + + /* Setup the type-2 "input" security buffer */ + type_2_desc.ulVersion = SECBUFFER_VERSION; + type_2_desc.cBuffers = 1; + type_2_desc.pBuffers = &type_2_bufs[0]; + type_2_bufs[0].BufferType = SECBUFFER_TOKEN; + type_2_bufs[0].pvBuffer = ntlm->input_token; + type_2_bufs[0].cbBuffer = curlx_uztoul(ntlm->input_token_len); + +#ifdef SECPKG_ATTR_ENDPOINT_BINDINGS + /* ssl context comes from schannel. + * When extended protection is used in IIS server, + * we have to pass a second SecBuffer to the SecBufferDesc + * otherwise IIS will not pass the authentication (401 response). + * Minimum supported version is Windows 7. + * https://docs.microsoft.com/en-us/security-updates + * /SecurityAdvisories/2009/973811 + */ + if(ntlm->sslContext) { + SEC_CHANNEL_BINDINGS channelBindings; + SecPkgContext_Bindings pkgBindings; + pkgBindings.Bindings = &channelBindings; + status = s_pSecFn->QueryContextAttributes( + ntlm->sslContext, + SECPKG_ATTR_ENDPOINT_BINDINGS, + &pkgBindings + ); + if(status == SEC_E_OK) { + type_2_desc.cBuffers++; + type_2_bufs[1].BufferType = SECBUFFER_CHANNEL_BINDINGS; + type_2_bufs[1].cbBuffer = pkgBindings.BindingsLength; + type_2_bufs[1].pvBuffer = pkgBindings.Bindings; + } + } +#endif + + /* Setup the type-3 "output" security buffer */ + type_3_desc.ulVersion = SECBUFFER_VERSION; + type_3_desc.cBuffers = 1; + type_3_desc.pBuffers = &type_3_buf; + type_3_buf.BufferType = SECBUFFER_TOKEN; + type_3_buf.pvBuffer = ntlm->output_token; + type_3_buf.cbBuffer = curlx_uztoul(ntlm->token_max); + + /* Generate our type-3 message */ + status = s_pSecFn->InitializeSecurityContext(ntlm->credentials, + ntlm->context, + ntlm->spn, + 0, 0, SECURITY_NETWORK_DREP, + &type_2_desc, + 0, ntlm->context, + &type_3_desc, + &attrs, &expiry); + if(status != SEC_E_OK) { + infof(data, "NTLM handshake failure (type-3 message): Status=%lx", + status); + + if(status == SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + + return CURLE_AUTH_ERROR; + } + + /* Return the response. */ + result = Curl_bufref_memdup(out, ntlm->output_token, type_3_buf.cbBuffer); + Curl_auth_cleanup_ntlm(ntlm); + return result; +} + +/* + * Curl_auth_cleanup_ntlm() + * + * This is used to clean up the NTLM specific data. + * + * Parameters: + * + * ntlm [in/out] - The NTLM data struct being cleaned up. + * + */ +void Curl_auth_cleanup_ntlm(struct ntlmdata *ntlm) +{ + /* Free our security context */ + if(ntlm->context) { + s_pSecFn->DeleteSecurityContext(ntlm->context); + free(ntlm->context); + ntlm->context = NULL; + } + + /* Free our credentials handle */ + if(ntlm->credentials) { + s_pSecFn->FreeCredentialsHandle(ntlm->credentials); + free(ntlm->credentials); + ntlm->credentials = NULL; + } + + /* Free our identity */ + Curl_sspi_free_identity(ntlm->p_identity); + ntlm->p_identity = NULL; + + /* Free the input and output tokens */ + Curl_safefree(ntlm->input_token); + Curl_safefree(ntlm->output_token); + + /* Reset any variables */ + ntlm->token_max = 0; + + Curl_safefree(ntlm->spn); +} + +#endif /* USE_WINDOWS_SSPI && USE_NTLM */ diff --git a/third_party/curl/lib/vauth/oauth2.c b/third_party/curl/lib/vauth/oauth2.c new file mode 100644 index 0000000..a4adbdc --- /dev/null +++ b/third_party/curl/lib/vauth/oauth2.c @@ -0,0 +1,108 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * RFC6749 OAuth 2.0 Authorization Framework + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_POP3) || \ + (!defined(CURL_DISABLE_LDAP) && defined(USE_OPENLDAP)) + +#include +#include "urldata.h" + +#include "vauth/vauth.h" +#include "warnless.h" +#include "curl_printf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_create_oauth_bearer_message() + * + * This is used to generate an OAuth 2.0 message ready for sending to the + * recipient. + * + * Parameters: + * + * user[in] - The user name. + * host[in] - The host name. + * port[in] - The port(when not Port 80). + * bearer[in] - The bearer token. + * out[out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_oauth_bearer_message(const char *user, + const char *host, + const long port, + const char *bearer, + struct bufref *out) +{ + char *oauth; + + /* Generate the message */ + if(port == 0 || port == 80) + oauth = aprintf("n,a=%s,\1host=%s\1auth=Bearer %s\1\1", user, host, + bearer); + else + oauth = aprintf("n,a=%s,\1host=%s\1port=%ld\1auth=Bearer %s\1\1", user, + host, port, bearer); + if(!oauth) + return CURLE_OUT_OF_MEMORY; + + Curl_bufref_set(out, oauth, strlen(oauth), curl_free); + return CURLE_OK; +} + +/* + * Curl_auth_create_xoauth_bearer_message() + * + * This is used to generate a XOAuth 2.0 message ready for * sending to the + * recipient. + * + * Parameters: + * + * user[in] - The user name. + * bearer[in] - The bearer token. + * out[out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_xoauth_bearer_message(const char *user, + const char *bearer, + struct bufref *out) +{ + /* Generate the message */ + char *xoauth = aprintf("user=%s\1auth=Bearer %s\1\1", user, bearer); + if(!xoauth) + return CURLE_OUT_OF_MEMORY; + + Curl_bufref_set(out, xoauth, strlen(xoauth), curl_free); + return CURLE_OK; +} +#endif /* disabled, no users */ diff --git a/third_party/curl/lib/vauth/spnego_gssapi.c b/third_party/curl/lib/vauth/spnego_gssapi.c new file mode 100644 index 0000000..e1d52b7 --- /dev/null +++ b/third_party/curl/lib/vauth/spnego_gssapi.c @@ -0,0 +1,281 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * RFC4178 Simple and Protected GSS-API Negotiation Mechanism + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(HAVE_GSSAPI) && defined(USE_SPNEGO) + +#include + +#include "vauth/vauth.h" +#include "urldata.h" +#include "curl_base64.h" +#include "curl_gssapi.h" +#include "warnless.h" +#include "curl_multibyte.h" +#include "sendf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_is_spnego_supported() + * + * This is used to evaluate if SPNEGO (Negotiate) is supported. + * + * Parameters: None + * + * Returns TRUE if Negotiate supported by the GSS-API library. + */ +bool Curl_auth_is_spnego_supported(void) +{ + return TRUE; +} + +/* + * Curl_auth_decode_spnego_message() + * + * This is used to decode an already encoded SPNEGO (Negotiate) challenge + * message. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name in the format User or Domain\User. + * passwdp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * host [in] - The host name. + * chlg64 [in] - The optional base64 encoded challenge message. + * nego [in/out] - The Negotiate data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_spnego_message(struct Curl_easy *data, + const char *user, + const char *password, + const char *service, + const char *host, + const char *chlg64, + struct negotiatedata *nego) +{ + CURLcode result = CURLE_OK; + size_t chlglen = 0; + unsigned char *chlg = NULL; + OM_uint32 major_status; + OM_uint32 minor_status; + OM_uint32 unused_status; + gss_buffer_desc spn_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + + (void) user; + (void) password; + + if(nego->context && nego->status == GSS_S_COMPLETE) { + /* We finished successfully our part of authentication, but server + * rejected it (since we're again here). Exit with an error since we + * can't invent anything better */ + Curl_auth_cleanup_spnego(nego); + return CURLE_LOGIN_DENIED; + } + + if(!nego->spn) { + /* Generate our SPN */ + char *spn = Curl_auth_build_spn(service, NULL, host); + if(!spn) + return CURLE_OUT_OF_MEMORY; + + /* Populate the SPN structure */ + spn_token.value = spn; + spn_token.length = strlen(spn); + + /* Import the SPN */ + major_status = gss_import_name(&minor_status, &spn_token, + GSS_C_NT_HOSTBASED_SERVICE, + &nego->spn); + if(GSS_ERROR(major_status)) { + Curl_gss_log_error(data, "gss_import_name() failed: ", + major_status, minor_status); + + free(spn); + + return CURLE_AUTH_ERROR; + } + + free(spn); + } + + if(chlg64 && *chlg64) { + /* Decode the base-64 encoded challenge message */ + if(*chlg64 != '=') { + result = Curl_base64_decode(chlg64, &chlg, &chlglen); + if(result) + return result; + } + + /* Ensure we have a valid challenge message */ + if(!chlg) { + infof(data, "SPNEGO handshake failure (empty challenge message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Setup the challenge "input" security buffer */ + input_token.value = chlg; + input_token.length = chlglen; + } + + /* Generate our challenge-response message */ + major_status = Curl_gss_init_sec_context(data, + &minor_status, + &nego->context, + nego->spn, + &Curl_spnego_mech_oid, + GSS_C_NO_CHANNEL_BINDINGS, + &input_token, + &output_token, + TRUE, + NULL); + + /* Free the decoded challenge as it is not required anymore */ + Curl_safefree(input_token.value); + + nego->status = major_status; + if(GSS_ERROR(major_status)) { + if(output_token.value) + gss_release_buffer(&unused_status, &output_token); + + Curl_gss_log_error(data, "gss_init_sec_context() failed: ", + major_status, minor_status); + + return CURLE_AUTH_ERROR; + } + + if(!output_token.value || !output_token.length) { + if(output_token.value) + gss_release_buffer(&unused_status, &output_token); + + return CURLE_AUTH_ERROR; + } + + /* Free previous token */ + if(nego->output_token.length && nego->output_token.value) + gss_release_buffer(&unused_status, &nego->output_token); + + nego->output_token = output_token; + + return CURLE_OK; +} + +/* + * Curl_auth_create_spnego_message() + * + * This is used to generate an already encoded SPNEGO (Negotiate) response + * message ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * nego [in/out] - The Negotiate data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_spnego_message(struct negotiatedata *nego, + char **outptr, size_t *outlen) +{ + CURLcode result; + OM_uint32 minor_status; + + /* Base64 encode the already generated response */ + result = Curl_base64_encode(nego->output_token.value, + nego->output_token.length, + outptr, outlen); + + if(result) { + gss_release_buffer(&minor_status, &nego->output_token); + nego->output_token.value = NULL; + nego->output_token.length = 0; + + return result; + } + + if(!*outptr || !*outlen) { + gss_release_buffer(&minor_status, &nego->output_token); + nego->output_token.value = NULL; + nego->output_token.length = 0; + + return CURLE_REMOTE_ACCESS_DENIED; + } + + return CURLE_OK; +} + +/* + * Curl_auth_cleanup_spnego() + * + * This is used to clean up the SPNEGO (Negotiate) specific data. + * + * Parameters: + * + * nego [in/out] - The Negotiate data struct being cleaned up. + * + */ +void Curl_auth_cleanup_spnego(struct negotiatedata *nego) +{ + OM_uint32 minor_status; + + /* Free our security context */ + if(nego->context != GSS_C_NO_CONTEXT) { + gss_delete_sec_context(&minor_status, &nego->context, GSS_C_NO_BUFFER); + nego->context = GSS_C_NO_CONTEXT; + } + + /* Free the output token */ + if(nego->output_token.value) { + gss_release_buffer(&minor_status, &nego->output_token); + nego->output_token.value = NULL; + nego->output_token.length = 0; + + } + + /* Free the SPN */ + if(nego->spn != GSS_C_NO_NAME) { + gss_release_name(&minor_status, &nego->spn); + nego->spn = GSS_C_NO_NAME; + } + + /* Reset any variables */ + nego->status = 0; + nego->noauthpersist = FALSE; + nego->havenoauthpersist = FALSE; + nego->havenegdata = FALSE; + nego->havemultiplerequests = FALSE; +} + +#endif /* HAVE_GSSAPI && USE_SPNEGO */ diff --git a/third_party/curl/lib/vauth/spnego_sspi.c b/third_party/curl/lib/vauth/spnego_sspi.c new file mode 100644 index 0000000..d3245d0 --- /dev/null +++ b/third_party/curl/lib/vauth/spnego_sspi.c @@ -0,0 +1,364 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * RFC4178 Simple and Protected GSS-API Negotiation Mechanism + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_WINDOWS_SSPI) && defined(USE_SPNEGO) + +#include + +#include "vauth/vauth.h" +#include "urldata.h" +#include "curl_base64.h" +#include "warnless.h" +#include "curl_multibyte.h" +#include "sendf.h" +#include "strerror.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_is_spnego_supported() + * + * This is used to evaluate if SPNEGO (Negotiate) is supported. + * + * Parameters: None + * + * Returns TRUE if Negotiate is supported by Windows SSPI. + */ +bool Curl_auth_is_spnego_supported(void) +{ + PSecPkgInfo SecurityPackage; + SECURITY_STATUS status; + + /* Query the security package for Negotiate */ + status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) + TEXT(SP_NAME_NEGOTIATE), + &SecurityPackage); + + /* Release the package buffer as it is not required anymore */ + if(status == SEC_E_OK) { + s_pSecFn->FreeContextBuffer(SecurityPackage); + } + + + return (status == SEC_E_OK ? TRUE : FALSE); +} + +/* + * Curl_auth_decode_spnego_message() + * + * This is used to decode an already encoded SPNEGO (Negotiate) challenge + * message. + * + * Parameters: + * + * data [in] - The session handle. + * user [in] - The user name in the format User or Domain\User. + * password [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * host [in] - The host name. + * chlg64 [in] - The optional base64 encoded challenge message. + * nego [in/out] - The Negotiate data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_spnego_message(struct Curl_easy *data, + const char *user, + const char *password, + const char *service, + const char *host, + const char *chlg64, + struct negotiatedata *nego) +{ + CURLcode result = CURLE_OK; + size_t chlglen = 0; + unsigned char *chlg = NULL; + PSecPkgInfo SecurityPackage; + SecBuffer chlg_buf[2]; + SecBuffer resp_buf; + SecBufferDesc chlg_desc; + SecBufferDesc resp_desc; + unsigned long attrs; + TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ + +#if defined(CURL_DISABLE_VERBOSE_STRINGS) + (void) data; +#endif + + if(nego->context && nego->status == SEC_E_OK) { + /* We finished successfully our part of authentication, but server + * rejected it (since we're again here). Exit with an error since we + * can't invent anything better */ + Curl_auth_cleanup_spnego(nego); + return CURLE_LOGIN_DENIED; + } + + if(!nego->spn) { + /* Generate our SPN */ + nego->spn = Curl_auth_build_spn(service, host, NULL); + if(!nego->spn) + return CURLE_OUT_OF_MEMORY; + } + + if(!nego->output_token) { + /* Query the security package for Negotiate */ + nego->status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) + TEXT(SP_NAME_NEGOTIATE), + &SecurityPackage); + if(nego->status != SEC_E_OK) { + failf(data, "SSPI: couldn't get auth info"); + return CURLE_AUTH_ERROR; + } + + nego->token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + s_pSecFn->FreeContextBuffer(SecurityPackage); + + /* Allocate our output buffer */ + nego->output_token = malloc(nego->token_max); + if(!nego->output_token) + return CURLE_OUT_OF_MEMORY; + } + + if(!nego->credentials) { + /* Do we have credentials to use or are we using single sign-on? */ + if(user && *user) { + /* Populate our identity structure */ + result = Curl_create_sspi_identity(user, password, &nego->identity); + if(result) + return result; + + /* Allow proper cleanup of the identity structure */ + nego->p_identity = &nego->identity; + } + else + /* Use the current Windows user */ + nego->p_identity = NULL; + + /* Allocate our credentials handle */ + nego->credentials = calloc(1, sizeof(CredHandle)); + if(!nego->credentials) + return CURLE_OUT_OF_MEMORY; + + /* Acquire our credentials handle */ + nego->status = + s_pSecFn->AcquireCredentialsHandle(NULL, + (TCHAR *)TEXT(SP_NAME_NEGOTIATE), + SECPKG_CRED_OUTBOUND, NULL, + nego->p_identity, NULL, NULL, + nego->credentials, &expiry); + if(nego->status != SEC_E_OK) + return CURLE_AUTH_ERROR; + + /* Allocate our new context handle */ + nego->context = calloc(1, sizeof(CtxtHandle)); + if(!nego->context) + return CURLE_OUT_OF_MEMORY; + } + + if(chlg64 && *chlg64) { + /* Decode the base-64 encoded challenge message */ + if(*chlg64 != '=') { + result = Curl_base64_decode(chlg64, &chlg, &chlglen); + if(result) + return result; + } + + /* Ensure we have a valid challenge message */ + if(!chlg) { + infof(data, "SPNEGO handshake failure (empty challenge message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Setup the challenge "input" security buffer */ + chlg_desc.ulVersion = SECBUFFER_VERSION; + chlg_desc.cBuffers = 1; + chlg_desc.pBuffers = &chlg_buf[0]; + chlg_buf[0].BufferType = SECBUFFER_TOKEN; + chlg_buf[0].pvBuffer = chlg; + chlg_buf[0].cbBuffer = curlx_uztoul(chlglen); + +#ifdef SECPKG_ATTR_ENDPOINT_BINDINGS + /* ssl context comes from Schannel. + * When extended protection is used in IIS server, + * we have to pass a second SecBuffer to the SecBufferDesc + * otherwise IIS will not pass the authentication (401 response). + * Minimum supported version is Windows 7. + * https://docs.microsoft.com/en-us/security-updates + * /SecurityAdvisories/2009/973811 + */ + if(nego->sslContext) { + SEC_CHANNEL_BINDINGS channelBindings; + SecPkgContext_Bindings pkgBindings; + pkgBindings.Bindings = &channelBindings; + nego->status = s_pSecFn->QueryContextAttributes( + nego->sslContext, + SECPKG_ATTR_ENDPOINT_BINDINGS, + &pkgBindings + ); + if(nego->status == SEC_E_OK) { + chlg_desc.cBuffers++; + chlg_buf[1].BufferType = SECBUFFER_CHANNEL_BINDINGS; + chlg_buf[1].cbBuffer = pkgBindings.BindingsLength; + chlg_buf[1].pvBuffer = pkgBindings.Bindings; + } + } +#endif + } + + /* Setup the response "output" security buffer */ + resp_desc.ulVersion = SECBUFFER_VERSION; + resp_desc.cBuffers = 1; + resp_desc.pBuffers = &resp_buf; + resp_buf.BufferType = SECBUFFER_TOKEN; + resp_buf.pvBuffer = nego->output_token; + resp_buf.cbBuffer = curlx_uztoul(nego->token_max); + + /* Generate our challenge-response message */ + nego->status = s_pSecFn->InitializeSecurityContext(nego->credentials, + chlg ? nego->context : + NULL, + nego->spn, + ISC_REQ_CONFIDENTIALITY, + 0, SECURITY_NATIVE_DREP, + chlg ? &chlg_desc : NULL, + 0, nego->context, + &resp_desc, &attrs, + &expiry); + + /* Free the decoded challenge as it is not required anymore */ + free(chlg); + + if(GSS_ERROR(nego->status)) { + char buffer[STRERROR_LEN]; + failf(data, "InitializeSecurityContext failed: %s", + Curl_sspi_strerror(nego->status, buffer, sizeof(buffer))); + + if(nego->status == (DWORD)SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + + return CURLE_AUTH_ERROR; + } + + if(nego->status == SEC_I_COMPLETE_NEEDED || + nego->status == SEC_I_COMPLETE_AND_CONTINUE) { + nego->status = s_pSecFn->CompleteAuthToken(nego->context, &resp_desc); + if(GSS_ERROR(nego->status)) { + char buffer[STRERROR_LEN]; + failf(data, "CompleteAuthToken failed: %s", + Curl_sspi_strerror(nego->status, buffer, sizeof(buffer))); + + if(nego->status == (DWORD)SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + + return CURLE_AUTH_ERROR; + } + } + + nego->output_token_length = resp_buf.cbBuffer; + + return result; +} + +/* + * Curl_auth_create_spnego_message() + * + * This is used to generate an already encoded SPNEGO (Negotiate) response + * message ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * nego [in/out] - The Negotiate data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_spnego_message(struct negotiatedata *nego, + char **outptr, size_t *outlen) +{ + /* Base64 encode the already generated response */ + CURLcode result = Curl_base64_encode((const char *) nego->output_token, + nego->output_token_length, outptr, + outlen); + if(!result && (!*outptr || !*outlen)) { + free(*outptr); + result = CURLE_REMOTE_ACCESS_DENIED; + } + + return result; +} + +/* + * Curl_auth_cleanup_spnego() + * + * This is used to clean up the SPNEGO (Negotiate) specific data. + * + * Parameters: + * + * nego [in/out] - The Negotiate data struct being cleaned up. + * + */ +void Curl_auth_cleanup_spnego(struct negotiatedata *nego) +{ + /* Free our security context */ + if(nego->context) { + s_pSecFn->DeleteSecurityContext(nego->context); + free(nego->context); + nego->context = NULL; + } + + /* Free our credentials handle */ + if(nego->credentials) { + s_pSecFn->FreeCredentialsHandle(nego->credentials); + free(nego->credentials); + nego->credentials = NULL; + } + + /* Free our identity */ + Curl_sspi_free_identity(nego->p_identity); + nego->p_identity = NULL; + + /* Free the SPN and output token */ + Curl_safefree(nego->spn); + Curl_safefree(nego->output_token); + + /* Reset any variables */ + nego->status = 0; + nego->token_max = 0; + nego->noauthpersist = FALSE; + nego->havenoauthpersist = FALSE; + nego->havenegdata = FALSE; + nego->havemultiplerequests = FALSE; +} + +#endif /* USE_WINDOWS_SSPI && USE_SPNEGO */ diff --git a/third_party/curl/lib/vauth/vauth.c b/third_party/curl/lib/vauth/vauth.c new file mode 100644 index 0000000..62fc7c4 --- /dev/null +++ b/third_party/curl/lib/vauth/vauth.c @@ -0,0 +1,163 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, . + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "vauth.h" +#include "urldata.h" +#include "strcase.h" +#include "curl_multibyte.h" +#include "curl_printf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_build_spn() + * + * This is used to build a SPN string in the following formats: + * + * service/host@realm (Not currently used) + * service/host (Not used by GSS-API) + * service@realm (Not used by Windows SSPI) + * + * Parameters: + * + * service [in] - The service type such as http, smtp, pop or imap. + * host [in] - The host name. + * realm [in] - The realm. + * + * Returns a pointer to the newly allocated SPN. + */ +#if !defined(USE_WINDOWS_SSPI) +char *Curl_auth_build_spn(const char *service, const char *host, + const char *realm) +{ + char *spn = NULL; + + /* Generate our SPN */ + if(host && realm) + spn = aprintf("%s/%s@%s", service, host, realm); + else if(host) + spn = aprintf("%s/%s", service, host); + else if(realm) + spn = aprintf("%s@%s", service, realm); + + /* Return our newly allocated SPN */ + return spn; +} +#else +TCHAR *Curl_auth_build_spn(const char *service, const char *host, + const char *realm) +{ + char *utf8_spn = NULL; + TCHAR *tchar_spn = NULL; + TCHAR *dupe_tchar_spn = NULL; + + (void) realm; + + /* Note: We could use DsMakeSPN() or DsClientMakeSpnForTargetServer() rather + than doing this ourselves but the first is only available in Windows XP + and Windows Server 2003 and the latter is only available in Windows 2000 + but not Windows95/98/ME or Windows NT4.0 unless the Active Directory + Client Extensions are installed. As such it is far simpler for us to + formulate the SPN instead. */ + + /* Generate our UTF8 based SPN */ + utf8_spn = aprintf("%s/%s", service, host); + if(!utf8_spn) + return NULL; + + /* Allocate and return a TCHAR based SPN. Since curlx_convert_UTF8_to_tchar + must be freed by curlx_unicodefree we'll dupe the result so that the + pointer this function returns can be normally free'd. */ + tchar_spn = curlx_convert_UTF8_to_tchar(utf8_spn); + free(utf8_spn); + if(!tchar_spn) + return NULL; + dupe_tchar_spn = _tcsdup(tchar_spn); + curlx_unicodefree(tchar_spn); + return dupe_tchar_spn; +} +#endif /* USE_WINDOWS_SSPI */ + +/* + * Curl_auth_user_contains_domain() + * + * This is used to test if the specified user contains a Windows domain name as + * follows: + * + * Domain\User (Down-level Logon Name) + * Domain/User (curl Down-level format - for compatibility with existing code) + * User@Domain (User Principal Name) + * + * Note: The user name may be empty when using a GSS-API library or Windows + * SSPI as the user and domain are either obtained from the credentials cache + * when using GSS-API or via the currently logged in user's credentials when + * using Windows SSPI. + * + * Parameters: + * + * user [in] - The user name. + * + * Returns TRUE on success; otherwise FALSE. + */ +bool Curl_auth_user_contains_domain(const char *user) +{ + bool valid = FALSE; + + if(user && *user) { + /* Check we have a domain name or UPN present */ + char *p = strpbrk(user, "\\/@"); + + valid = (p != NULL && p > user && p < user + strlen(user) - 1 ? TRUE : + FALSE); + } +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + else + /* User and domain are obtained from the GSS-API credentials cache or the + currently logged in user from Windows */ + valid = TRUE; +#endif + + return valid; +} + +/* + * Curl_auth_ollowed_to_host() tells if authentication, cookies or other + * "sensitive data" can (still) be sent to this host. + */ +bool Curl_auth_allowed_to_host(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + return (!data->state.this_is_a_follow || + data->set.allow_auth_to_other_hosts || + (data->state.first_host && + strcasecompare(data->state.first_host, conn->host.name) && + (data->state.first_remote_port == conn->remote_port) && + (data->state.first_remote_protocol == conn->handler->protocol))); +} diff --git a/third_party/curl/lib/vauth/vauth.h b/third_party/curl/lib/vauth/vauth.h new file mode 100644 index 0000000..7e82348 --- /dev/null +++ b/third_party/curl/lib/vauth/vauth.h @@ -0,0 +1,236 @@ +#ifndef HEADER_CURL_VAUTH_H +#define HEADER_CURL_VAUTH_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, . + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include + +#include "bufref.h" + +struct Curl_easy; + +#if !defined(CURL_DISABLE_DIGEST_AUTH) +struct digestdata; +#endif + +#if defined(USE_NTLM) +struct ntlmdata; +#endif + +#if defined(USE_KERBEROS5) +struct kerberos5data; +#endif + +#if (defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)) && defined(USE_SPNEGO) +struct negotiatedata; +#endif + +#if defined(USE_GSASL) +struct gsasldata; +#endif + +#if defined(USE_WINDOWS_SSPI) +#define GSS_ERROR(status) ((status) & 0x80000000) +#endif + +/* + * Curl_auth_allowed_to_host() tells if authentication, cookies or other + * "sensitive data" can (still) be sent to this host. + */ +bool Curl_auth_allowed_to_host(struct Curl_easy *data); + +/* This is used to build a SPN string */ +#if !defined(USE_WINDOWS_SSPI) +char *Curl_auth_build_spn(const char *service, const char *host, + const char *realm); +#else +TCHAR *Curl_auth_build_spn(const char *service, const char *host, + const char *realm); +#endif + +/* This is used to test if the user contains a Windows domain name */ +bool Curl_auth_user_contains_domain(const char *user); + +/* This is used to generate a PLAIN cleartext message */ +CURLcode Curl_auth_create_plain_message(const char *authzid, + const char *authcid, + const char *passwd, + struct bufref *out); + +/* This is used to generate a LOGIN cleartext message */ +void Curl_auth_create_login_message(const char *value, struct bufref *out); + +/* This is used to generate an EXTERNAL cleartext message */ +void Curl_auth_create_external_message(const char *user, struct bufref *out); + +#ifndef CURL_DISABLE_DIGEST_AUTH +/* This is used to generate a CRAM-MD5 response message */ +CURLcode Curl_auth_create_cram_md5_message(const struct bufref *chlg, + const char *userp, + const char *passwdp, + struct bufref *out); + +/* This is used to evaluate if DIGEST is supported */ +bool Curl_auth_is_digest_supported(void); + +/* This is used to generate a base64 encoded DIGEST-MD5 response message */ +CURLcode Curl_auth_create_digest_md5_message(struct Curl_easy *data, + const struct bufref *chlg, + const char *userp, + const char *passwdp, + const char *service, + struct bufref *out); + +/* This is used to decode an HTTP DIGEST challenge message */ +CURLcode Curl_auth_decode_digest_http_message(const char *chlg, + struct digestdata *digest); + +/* This is used to generate an HTTP DIGEST response message */ +CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + const unsigned char *request, + const unsigned char *uri, + struct digestdata *digest, + char **outptr, size_t *outlen); + +/* This is used to clean up the digest specific data */ +void Curl_auth_digest_cleanup(struct digestdata *digest); +#endif /* !CURL_DISABLE_DIGEST_AUTH */ + +#ifdef USE_GSASL +/* This is used to evaluate if MECH is supported by gsasl */ +bool Curl_auth_gsasl_is_supported(struct Curl_easy *data, + const char *mech, + struct gsasldata *gsasl); +/* This is used to start a gsasl method */ +CURLcode Curl_auth_gsasl_start(struct Curl_easy *data, + const char *userp, + const char *passwdp, + struct gsasldata *gsasl); + +/* This is used to process and generate a new SASL token */ +CURLcode Curl_auth_gsasl_token(struct Curl_easy *data, + const struct bufref *chlg, + struct gsasldata *gsasl, + struct bufref *out); + +/* This is used to clean up the gsasl specific data */ +void Curl_auth_gsasl_cleanup(struct gsasldata *digest); +#endif + +#if defined(USE_NTLM) +/* This is used to evaluate if NTLM is supported */ +bool Curl_auth_is_ntlm_supported(void); + +/* This is used to generate a base64 encoded NTLM type-1 message */ +CURLcode Curl_auth_create_ntlm_type1_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + const char *service, + const char *host, + struct ntlmdata *ntlm, + struct bufref *out); + +/* This is used to decode a base64 encoded NTLM type-2 message */ +CURLcode Curl_auth_decode_ntlm_type2_message(struct Curl_easy *data, + const struct bufref *type2, + struct ntlmdata *ntlm); + +/* This is used to generate a base64 encoded NTLM type-3 message */ +CURLcode Curl_auth_create_ntlm_type3_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + struct ntlmdata *ntlm, + struct bufref *out); + +/* This is used to clean up the NTLM specific data */ +void Curl_auth_cleanup_ntlm(struct ntlmdata *ntlm); +#endif /* USE_NTLM */ + +/* This is used to generate a base64 encoded OAuth 2.0 message */ +CURLcode Curl_auth_create_oauth_bearer_message(const char *user, + const char *host, + const long port, + const char *bearer, + struct bufref *out); + +/* This is used to generate a base64 encoded XOAuth 2.0 message */ +CURLcode Curl_auth_create_xoauth_bearer_message(const char *user, + const char *bearer, + struct bufref *out); + +#if defined(USE_KERBEROS5) +/* This is used to evaluate if GSSAPI (Kerberos V5) is supported */ +bool Curl_auth_is_gssapi_supported(void); + +/* This is used to generate a base64 encoded GSSAPI (Kerberos V5) user token + message */ +CURLcode Curl_auth_create_gssapi_user_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + const char *service, + const char *host, + const bool mutual, + const struct bufref *chlg, + struct kerberos5data *krb5, + struct bufref *out); + +/* This is used to generate a base64 encoded GSSAPI (Kerberos V5) security + token message */ +CURLcode Curl_auth_create_gssapi_security_message(struct Curl_easy *data, + const char *authzid, + const struct bufref *chlg, + struct kerberos5data *krb5, + struct bufref *out); + +/* This is used to clean up the GSSAPI specific data */ +void Curl_auth_cleanup_gssapi(struct kerberos5data *krb5); +#endif /* USE_KERBEROS5 */ + +#if defined(USE_SPNEGO) +/* This is used to evaluate if SPNEGO (Negotiate) is supported */ +bool Curl_auth_is_spnego_supported(void); + +/* This is used to decode a base64 encoded SPNEGO (Negotiate) challenge + message */ +CURLcode Curl_auth_decode_spnego_message(struct Curl_easy *data, + const char *user, + const char *password, + const char *service, + const char *host, + const char *chlg64, + struct negotiatedata *nego); + +/* This is used to generate a base64 encoded SPNEGO (Negotiate) response + message */ +CURLcode Curl_auth_create_spnego_message(struct negotiatedata *nego, + char **outptr, size_t *outlen); + +/* This is used to clean up the SPNEGO specific data */ +void Curl_auth_cleanup_spnego(struct negotiatedata *nego); + +#endif /* USE_SPNEGO */ + +#endif /* HEADER_CURL_VAUTH_H */ diff --git a/third_party/curl/lib/version.c b/third_party/curl/lib/version.c new file mode 100644 index 0000000..a5c8c4e --- /dev/null +++ b/third_party/curl/lib/version.c @@ -0,0 +1,690 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_NGHTTP2 +#include +#endif + +#include +#include "urldata.h" +#include "vtls/vtls.h" +#include "http2.h" +#include "vssh/ssh.h" +#include "vquic/vquic.h" +#include "curl_printf.h" +#include "easy_lock.h" + +#ifdef USE_ARES +# if defined(CURL_STATICLIB) && !defined(CARES_STATICLIB) && \ + defined(_WIN32) +# define CARES_STATICLIB +# endif +# include +#endif + +#ifdef USE_LIBIDN2 +#include +#endif + +#ifdef USE_LIBPSL +#include +#endif + +#ifdef USE_LIBRTMP +#include +#include "curl_rtmp.h" +#endif + +#ifdef HAVE_LIBZ +#include +#endif + +#ifdef HAVE_BROTLI +#if defined(__GNUC__) +/* Ignore -Wvla warnings in brotli headers */ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wvla" +#endif +#include +#if defined(__GNUC__) +#pragma GCC diagnostic pop +#endif +#endif + +#ifdef HAVE_ZSTD +#include +#endif + +#ifdef USE_GSASL +#include +#endif + +#ifdef USE_OPENLDAP +#include +#endif + +#ifdef HAVE_BROTLI +static void brotli_version(char *buf, size_t bufsz) +{ + uint32_t brotli_version = BrotliDecoderVersion(); + unsigned int major = brotli_version >> 24; + unsigned int minor = (brotli_version & 0x00FFFFFF) >> 12; + unsigned int patch = brotli_version & 0x00000FFF; + (void)msnprintf(buf, bufsz, "%u.%u.%u", major, minor, patch); +} +#endif + +#ifdef HAVE_ZSTD +static void zstd_version(char *buf, size_t bufsz) +{ + unsigned long zstd_version = (unsigned long)ZSTD_versionNumber(); + unsigned int major = (unsigned int)(zstd_version / (100 * 100)); + unsigned int minor = (unsigned int)((zstd_version - + (major * 100 * 100)) / 100); + unsigned int patch = (unsigned int)(zstd_version - + (major * 100 * 100) - (minor * 100)); + (void)msnprintf(buf, bufsz, "%u.%u.%u", major, minor, patch); +} +#endif + +/* + * curl_version() returns a pointer to a static buffer. + * + * It is implemented to work multi-threaded by making sure repeated invokes + * generate the exact same string and never write any temporary data like + * zeros in the data. + */ + +#define VERSION_PARTS 16 /* number of substrings we can concatenate */ + +char *curl_version(void) +{ + static char out[300]; + char *outp; + size_t outlen; + const char *src[VERSION_PARTS]; +#ifdef USE_SSL + char ssl_version[200]; +#endif +#ifdef HAVE_LIBZ + char z_version[40]; +#endif +#ifdef HAVE_BROTLI + char br_version[40] = "brotli/"; +#endif +#ifdef HAVE_ZSTD + char zst_version[40] = "zstd/"; +#endif +#ifdef USE_ARES + char cares_version[40]; +#endif +#if defined(USE_LIBIDN2) + char idn_version[40]; +#endif +#ifdef USE_LIBPSL + char psl_version[40]; +#endif +#ifdef USE_SSH + char ssh_version[40]; +#endif +#ifdef USE_NGHTTP2 + char h2_version[40]; +#endif +#ifdef USE_HTTP3 + char h3_version[40]; +#endif +#ifdef USE_LIBRTMP + char rtmp_version[40]; +#endif +#ifdef USE_HYPER + char hyper_buf[30]; +#endif +#ifdef USE_GSASL + char gsasl_buf[30]; +#endif +#ifdef USE_OPENLDAP + char ldap_buf[30]; +#endif + int i = 0; + int j; + +#ifdef DEBUGBUILD + /* Override version string when environment variable CURL_VERSION is set */ + const char *debugversion = getenv("CURL_VERSION"); + if(debugversion) { + msnprintf(out, sizeof(out), "%s", debugversion); + return out; + } +#endif + + src[i++] = LIBCURL_NAME "/" LIBCURL_VERSION; +#ifdef USE_SSL + Curl_ssl_version(ssl_version, sizeof(ssl_version)); + src[i++] = ssl_version; +#endif +#ifdef HAVE_LIBZ + msnprintf(z_version, sizeof(z_version), "zlib/%s", zlibVersion()); + src[i++] = z_version; +#endif +#ifdef HAVE_BROTLI + brotli_version(&br_version[7], sizeof(br_version) - 7); + src[i++] = br_version; +#endif +#ifdef HAVE_ZSTD + zstd_version(&zst_version[5], sizeof(zst_version) - 5); + src[i++] = zst_version; +#endif +#ifdef USE_ARES + msnprintf(cares_version, sizeof(cares_version), + "c-ares/%s", ares_version(NULL)); + src[i++] = cares_version; +#endif +#ifdef USE_LIBIDN2 + msnprintf(idn_version, sizeof(idn_version), + "libidn2/%s", idn2_check_version(NULL)); + src[i++] = idn_version; +#elif defined(USE_WIN32_IDN) + src[i++] = (char *)"WinIDN"; +#elif defined(USE_APPLE_IDN) + src[i++] = (char *)"AppleIDN"; +#endif + +#ifdef USE_LIBPSL + { +#if defined(PSL_VERSION_MAJOR) && (PSL_VERSION_MAJOR > 0 || \ + PSL_VERSION_MINOR >= 11) + int num = psl_check_version_number(0); + msnprintf(psl_version, sizeof(psl_version), "libpsl/%d.%d.%d", + num >> 16, (num >> 8) & 0xff, num & 0xff); +#else + msnprintf(psl_version, sizeof(psl_version), "libpsl/%s", + psl_get_version()); +#endif + src[i++] = psl_version; + } +#endif + +#ifdef USE_SSH + Curl_ssh_version(ssh_version, sizeof(ssh_version)); + src[i++] = ssh_version; +#endif +#ifdef USE_NGHTTP2 + Curl_http2_ver(h2_version, sizeof(h2_version)); + src[i++] = h2_version; +#endif +#ifdef USE_HTTP3 + Curl_quic_ver(h3_version, sizeof(h3_version)); + src[i++] = h3_version; +#endif +#ifdef USE_LIBRTMP + Curl_rtmp_version(rtmp_version, sizeof(rtmp_version)); + src[i++] = rtmp_version; +#endif +#ifdef USE_HYPER + msnprintf(hyper_buf, sizeof(hyper_buf), "Hyper/%s", hyper_version()); + src[i++] = hyper_buf; +#endif +#ifdef USE_GSASL + msnprintf(gsasl_buf, sizeof(gsasl_buf), "libgsasl/%s", + gsasl_check_version(NULL)); + src[i++] = gsasl_buf; +#endif +#ifdef USE_OPENLDAP + { + LDAPAPIInfo api; + api.ldapai_info_version = LDAP_API_INFO_VERSION; + + if(ldap_get_option(NULL, LDAP_OPT_API_INFO, &api) == LDAP_OPT_SUCCESS) { + unsigned int patch = api.ldapai_vendor_version % 100; + unsigned int major = api.ldapai_vendor_version / 10000; + unsigned int minor = + ((api.ldapai_vendor_version - major * 10000) - patch) / 100; + msnprintf(ldap_buf, sizeof(ldap_buf), "%s/%u.%u.%u", + api.ldapai_vendor_name, major, minor, patch); + src[i++] = ldap_buf; + ldap_memfree(api.ldapai_vendor_name); + ber_memvfree((void **)api.ldapai_extensions); + } + } +#endif + + DEBUGASSERT(i <= VERSION_PARTS); + + outp = &out[0]; + outlen = sizeof(out); + for(j = 0; j < i; j++) { + size_t n = strlen(src[j]); + /* we need room for a space, the string and the final zero */ + if(outlen <= (n + 2)) + break; + if(j) { + /* prepend a space if not the first */ + *outp++ = ' '; + outlen--; + } + memcpy(outp, src[j], n); + outp += n; + outlen -= n; + } + *outp = 0; + + return out; +} + +/* data for curl_version_info + + Keep the list sorted alphabetically. It is also written so that each + protocol line has its own #if line to make things easier on the eye. + */ + +static const char * const supported_protocols[] = { +#ifndef CURL_DISABLE_DICT + "dict", +#endif +#ifndef CURL_DISABLE_FILE + "file", +#endif +#ifndef CURL_DISABLE_FTP + "ftp", +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_FTP) + "ftps", +#endif +#ifndef CURL_DISABLE_GOPHER + "gopher", +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_GOPHER) + "gophers", +#endif +#ifndef CURL_DISABLE_HTTP + "http", +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP) + "https", +#endif +#ifndef CURL_DISABLE_IMAP + "imap", +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_IMAP) + "imaps", +#endif +#ifndef CURL_DISABLE_LDAP + "ldap", +#if !defined(CURL_DISABLE_LDAPS) && \ + ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \ + (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL))) + "ldaps", +#endif +#endif +#ifndef CURL_DISABLE_MQTT + "mqtt", +#endif +#ifndef CURL_DISABLE_POP3 + "pop3", +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_POP3) + "pop3s", +#endif +#ifdef USE_LIBRTMP + "rtmp", + "rtmpe", + "rtmps", + "rtmpt", + "rtmpte", + "rtmpts", +#endif +#ifndef CURL_DISABLE_RTSP + "rtsp", +#endif +#if defined(USE_SSH) && !defined(USE_WOLFSSH) + "scp", +#endif +#ifdef USE_SSH + "sftp", +#endif +#if !defined(CURL_DISABLE_SMB) && defined(USE_CURL_NTLM_CORE) + "smb", +# ifdef USE_SSL + "smbs", +# endif +#endif +#ifndef CURL_DISABLE_SMTP + "smtp", +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_SMTP) + "smtps", +#endif +#ifndef CURL_DISABLE_TELNET + "telnet", +#endif +#ifndef CURL_DISABLE_TFTP + "tftp", +#endif +#ifdef USE_WEBSOCKETS + "ws", +#endif +#if defined(USE_SSL) && defined(USE_WEBSOCKETS) + "wss", +#endif + + NULL +}; + +/* + * Feature presence run-time check functions. + * + * Warning: the value returned by these should not change between + * curl_global_init() and curl_global_cleanup() calls. + */ + +#if defined(USE_LIBIDN2) +static int idn_present(curl_version_info_data *info) +{ + return info->libidn != NULL; +} +#else +#define idn_present NULL +#endif + +#if defined(USE_SSL) && !defined(CURL_DISABLE_PROXY) && \ + !defined(CURL_DISABLE_HTTP) +static int https_proxy_present(curl_version_info_data *info) +{ + (void) info; + return Curl_ssl_supports(NULL, SSLSUPP_HTTPS_PROXY); +} +#endif + +#if defined(USE_SSL) && defined(USE_ECH) +static int ech_present(curl_version_info_data *info) +{ + (void) info; + return Curl_ssl_supports(NULL, SSLSUPP_ECH); +} +#endif + +/* + * Features table. + * + * Keep the features alphabetically sorted. + * Use FEATURE() macro to define an entry: this allows documentation check. + */ + +#define FEATURE(name, present, bitmask) {(name), (present), (bitmask)} + +struct feat { + const char *name; + int (*present)(curl_version_info_data *info); + int bitmask; +}; + +static const struct feat features_table[] = { +#ifndef CURL_DISABLE_ALTSVC + FEATURE("alt-svc", NULL, CURL_VERSION_ALTSVC), +#endif +#ifdef CURLRES_ASYNCH + FEATURE("AsynchDNS", NULL, CURL_VERSION_ASYNCHDNS), +#endif +#ifdef HAVE_BROTLI + FEATURE("brotli", NULL, CURL_VERSION_BROTLI), +#endif +#ifdef DEBUGBUILD + FEATURE("Debug", NULL, CURL_VERSION_DEBUG), +#endif +#if defined(USE_SSL) && defined(USE_ECH) + FEATURE("ECH", ech_present, 0), +#endif +#ifdef USE_GSASL + FEATURE("gsasl", NULL, CURL_VERSION_GSASL), +#endif +#ifdef HAVE_GSSAPI + FEATURE("GSS-API", NULL, CURL_VERSION_GSSAPI), +#endif +#ifndef CURL_DISABLE_HSTS + FEATURE("HSTS", NULL, CURL_VERSION_HSTS), +#endif +#if defined(USE_NGHTTP2) + FEATURE("HTTP2", NULL, CURL_VERSION_HTTP2), +#endif +#if defined(USE_HTTP3) + FEATURE("HTTP3", NULL, CURL_VERSION_HTTP3), +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_PROXY) && \ + !defined(CURL_DISABLE_HTTP) + FEATURE("HTTPS-proxy", https_proxy_present, CURL_VERSION_HTTPS_PROXY), +#endif +#if defined(USE_LIBIDN2) || defined(USE_WIN32_IDN) || defined(USE_APPLE_IDN) + FEATURE("IDN", idn_present, CURL_VERSION_IDN), +#endif +#ifdef USE_IPV6 + FEATURE("IPv6", NULL, CURL_VERSION_IPV6), +#endif +#ifdef USE_KERBEROS5 + FEATURE("Kerberos", NULL, CURL_VERSION_KERBEROS5), +#endif +#if (SIZEOF_CURL_OFF_T > 4) && \ + ( (SIZEOF_OFF_T > 4) || defined(USE_WIN32_LARGE_FILES) ) + FEATURE("Largefile", NULL, CURL_VERSION_LARGEFILE), +#endif +#ifdef HAVE_LIBZ + FEATURE("libz", NULL, CURL_VERSION_LIBZ), +#endif +#ifdef CURL_WITH_MULTI_SSL + FEATURE("MultiSSL", NULL, CURL_VERSION_MULTI_SSL), +#endif +#ifdef USE_NTLM + FEATURE("NTLM", NULL, CURL_VERSION_NTLM), +#endif +#if defined(USE_LIBPSL) + FEATURE("PSL", NULL, CURL_VERSION_PSL), +#endif +#ifdef USE_SPNEGO + FEATURE("SPNEGO", NULL, CURL_VERSION_SPNEGO), +#endif +#ifdef USE_SSL + FEATURE("SSL", NULL, CURL_VERSION_SSL), +#endif +#ifdef USE_WINDOWS_SSPI + FEATURE("SSPI", NULL, CURL_VERSION_SSPI), +#endif +#ifdef GLOBAL_INIT_IS_THREADSAFE + FEATURE("threadsafe", NULL, CURL_VERSION_THREADSAFE), +#endif +#ifdef USE_TLS_SRP + FEATURE("TLS-SRP", NULL, CURL_VERSION_TLSAUTH_SRP), +#endif +#ifdef CURLDEBUG + FEATURE("TrackMemory", NULL, CURL_VERSION_CURLDEBUG), +#endif +#if defined(_WIN32) && defined(UNICODE) && defined(_UNICODE) + FEATURE("Unicode", NULL, CURL_VERSION_UNICODE), +#endif +#ifdef USE_UNIX_SOCKETS + FEATURE("UnixSockets", NULL, CURL_VERSION_UNIX_SOCKETS), +#endif +#ifdef HAVE_ZSTD + FEATURE("zstd", NULL, CURL_VERSION_ZSTD), +#endif + {NULL, NULL, 0} +}; + +static const char *feature_names[sizeof(features_table) / + sizeof(features_table[0])] = {NULL}; + + +static curl_version_info_data version_info = { + CURLVERSION_NOW, + LIBCURL_VERSION, + LIBCURL_VERSION_NUM, + OS, /* as found by configure or set by hand at build-time */ + 0, /* features bitmask is built at run-time */ + NULL, /* ssl_version */ + 0, /* ssl_version_num, this is kept at zero */ + NULL, /* zlib_version */ + supported_protocols, + NULL, /* c-ares version */ + 0, /* c-ares version numerical */ + NULL, /* libidn version */ + 0, /* iconv version */ + NULL, /* ssh lib version */ + 0, /* brotli_ver_num */ + NULL, /* brotli version */ + 0, /* nghttp2 version number */ + NULL, /* nghttp2 version string */ + NULL, /* quic library string */ +#ifdef CURL_CA_BUNDLE + CURL_CA_BUNDLE, /* cainfo */ +#else + NULL, +#endif +#ifdef CURL_CA_PATH + CURL_CA_PATH, /* capath */ +#else + NULL, +#endif + 0, /* zstd_ver_num */ + NULL, /* zstd version */ + NULL, /* Hyper version */ + NULL, /* gsasl version */ + feature_names, + NULL /* rtmp version */ +}; + +curl_version_info_data *curl_version_info(CURLversion stamp) +{ + size_t n; + const struct feat *p; + int features = 0; + +#if defined(USE_SSH) + static char ssh_buffer[80]; +#endif +#ifdef USE_SSL +#ifdef CURL_WITH_MULTI_SSL + static char ssl_buffer[200]; +#else + static char ssl_buffer[80]; +#endif +#endif +#ifdef HAVE_BROTLI + static char brotli_buffer[80]; +#endif +#ifdef HAVE_ZSTD + static char zstd_buffer[80]; +#endif + + (void)stamp; /* avoid compiler warnings, we don't use this */ + +#ifdef USE_SSL + Curl_ssl_version(ssl_buffer, sizeof(ssl_buffer)); + version_info.ssl_version = ssl_buffer; +#endif + +#ifdef HAVE_LIBZ + version_info.libz_version = zlibVersion(); + /* libz left NULL if non-existing */ +#endif +#ifdef USE_ARES + { + int aresnum; + version_info.ares = ares_version(&aresnum); + version_info.ares_num = aresnum; + } +#endif +#ifdef USE_LIBIDN2 + /* This returns a version string if we use the given version or later, + otherwise it returns NULL */ + version_info.libidn = idn2_check_version(IDN2_VERSION); +#endif + +#if defined(USE_SSH) + Curl_ssh_version(ssh_buffer, sizeof(ssh_buffer)); + version_info.libssh_version = ssh_buffer; +#endif + +#ifdef HAVE_BROTLI + version_info.brotli_ver_num = BrotliDecoderVersion(); + brotli_version(brotli_buffer, sizeof(brotli_buffer)); + version_info.brotli_version = brotli_buffer; +#endif + +#ifdef HAVE_ZSTD + version_info.zstd_ver_num = (unsigned int)ZSTD_versionNumber(); + zstd_version(zstd_buffer, sizeof(zstd_buffer)); + version_info.zstd_version = zstd_buffer; +#endif + +#ifdef USE_NGHTTP2 + { + nghttp2_info *h2 = nghttp2_version(0); + version_info.nghttp2_ver_num = h2->version_num; + version_info.nghttp2_version = h2->version_str; + } +#endif + +#ifdef USE_HTTP3 + { + static char quicbuffer[80]; + Curl_quic_ver(quicbuffer, sizeof(quicbuffer)); + version_info.quic_version = quicbuffer; + } +#endif + +#ifdef USE_HYPER + { + static char hyper_buffer[30]; + msnprintf(hyper_buffer, sizeof(hyper_buffer), "Hyper/%s", hyper_version()); + version_info.hyper_version = hyper_buffer; + } +#endif + +#ifdef USE_GSASL + { + version_info.gsasl_version = gsasl_check_version(NULL); + } +#endif + + /* Get available features, build bitmask and names array. */ + n = 0; + for(p = features_table; p->name; p++) + if(!p->present || p->present(&version_info)) { + features |= p->bitmask; + feature_names[n++] = p->name; + } + + feature_names[n] = NULL; /* Terminate array. */ + version_info.features = features; + +#ifdef USE_LIBRTMP + { + static char rtmp_version[30]; + Curl_rtmp_version(rtmp_version, sizeof(rtmp_version)); + version_info.rtmp_version = rtmp_version; + } +#endif + + return &version_info; +} diff --git a/third_party/curl/lib/version_win32.c b/third_party/curl/lib/version_win32.c new file mode 100644 index 0000000..e0f239e --- /dev/null +++ b/third_party/curl/lib/version_win32.c @@ -0,0 +1,319 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, . + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(_WIN32) + +#include +#include "version_win32.h" +#include "warnless.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* This Unicode version struct works for VerifyVersionInfoW (OSVERSIONINFOEXW) + and RtlVerifyVersionInfo (RTLOSVERSIONINFOEXW) */ +struct OUR_OSVERSIONINFOEXW { + ULONG dwOSVersionInfoSize; + ULONG dwMajorVersion; + ULONG dwMinorVersion; + ULONG dwBuildNumber; + ULONG dwPlatformId; + WCHAR szCSDVersion[128]; + USHORT wServicePackMajor; + USHORT wServicePackMinor; + USHORT wSuiteMask; + UCHAR wProductType; + UCHAR wReserved; +}; + +/* + * curlx_verify_windows_version() + * + * This is used to verify if we are running on a specific windows version. + * + * Parameters: + * + * majorVersion [in] - The major version number. + * minorVersion [in] - The minor version number. + * buildVersion [in] - The build version number. If 0, this parameter is + * ignored. + * platform [in] - The optional platform identifier. + * condition [in] - The test condition used to specifier whether we are + * checking a version less then, equal to or greater than + * what is specified in the major and minor version + * numbers. + * + * Returns TRUE if matched; otherwise FALSE. + */ +bool curlx_verify_windows_version(const unsigned int majorVersion, + const unsigned int minorVersion, + const unsigned int buildVersion, + const PlatformIdentifier platform, + const VersionCondition condition) +{ + bool matched = FALSE; + +#if defined(CURL_WINDOWS_APP) + (void)buildVersion; + + /* We have no way to determine the Windows version from Windows apps, + so let's assume we're running on the target Windows version. */ + const WORD fullVersion = MAKEWORD(minorVersion, majorVersion); + const WORD targetVersion = (WORD)_WIN32_WINNT; + + switch(condition) { + case VERSION_LESS_THAN: + matched = targetVersion < fullVersion; + break; + + case VERSION_LESS_THAN_EQUAL: + matched = targetVersion <= fullVersion; + break; + + case VERSION_EQUAL: + matched = targetVersion == fullVersion; + break; + + case VERSION_GREATER_THAN_EQUAL: + matched = targetVersion >= fullVersion; + break; + + case VERSION_GREATER_THAN: + matched = targetVersion > fullVersion; + break; + } + + if(matched && (platform == PLATFORM_WINDOWS)) { + /* we're always running on PLATFORM_WINNT */ + matched = FALSE; + } +#elif !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_WIN2K) || \ + (_WIN32_WINNT < _WIN32_WINNT_WIN2K) + OSVERSIONINFO osver; + + memset(&osver, 0, sizeof(osver)); + osver.dwOSVersionInfoSize = sizeof(osver); + + /* Find out Windows version */ + if(GetVersionEx(&osver)) { + /* Verify the Operating System version number */ + switch(condition) { + case VERSION_LESS_THAN: + if(osver.dwMajorVersion < majorVersion || + (osver.dwMajorVersion == majorVersion && + osver.dwMinorVersion < minorVersion) || + (buildVersion != 0 && + (osver.dwMajorVersion == majorVersion && + osver.dwMinorVersion == minorVersion && + osver.dwBuildNumber < buildVersion))) + matched = TRUE; + break; + + case VERSION_LESS_THAN_EQUAL: + if(osver.dwMajorVersion < majorVersion || + (osver.dwMajorVersion == majorVersion && + osver.dwMinorVersion < minorVersion) || + (osver.dwMajorVersion == majorVersion && + osver.dwMinorVersion == minorVersion && + (buildVersion == 0 || + osver.dwBuildNumber <= buildVersion))) + matched = TRUE; + break; + + case VERSION_EQUAL: + if(osver.dwMajorVersion == majorVersion && + osver.dwMinorVersion == minorVersion && + (buildVersion == 0 || + osver.dwBuildNumber == buildVersion)) + matched = TRUE; + break; + + case VERSION_GREATER_THAN_EQUAL: + if(osver.dwMajorVersion > majorVersion || + (osver.dwMajorVersion == majorVersion && + osver.dwMinorVersion > minorVersion) || + (osver.dwMajorVersion == majorVersion && + osver.dwMinorVersion == minorVersion && + (buildVersion == 0 || + osver.dwBuildNumber >= buildVersion))) + matched = TRUE; + break; + + case VERSION_GREATER_THAN: + if(osver.dwMajorVersion > majorVersion || + (osver.dwMajorVersion == majorVersion && + osver.dwMinorVersion > minorVersion) || + (buildVersion != 0 && + (osver.dwMajorVersion == majorVersion && + osver.dwMinorVersion == minorVersion && + osver.dwBuildNumber > buildVersion))) + matched = TRUE; + break; + } + + /* Verify the platform identifier (if necessary) */ + if(matched) { + switch(platform) { + case PLATFORM_WINDOWS: + if(osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) + matched = FALSE; + break; + + case PLATFORM_WINNT: + if(osver.dwPlatformId != VER_PLATFORM_WIN32_NT) + matched = FALSE; + break; + + default: /* like platform == PLATFORM_DONT_CARE */ + break; + } + } + } +#else + ULONGLONG cm = 0; + struct OUR_OSVERSIONINFOEXW osver; + BYTE majorCondition; + BYTE minorCondition; + BYTE buildCondition; + BYTE spMajorCondition; + BYTE spMinorCondition; + DWORD dwTypeMask = VER_MAJORVERSION | VER_MINORVERSION | + VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR; + + typedef LONG (APIENTRY *RTLVERIFYVERSIONINFO_FN) + (struct OUR_OSVERSIONINFOEXW *, ULONG, ULONGLONG); + static RTLVERIFYVERSIONINFO_FN pRtlVerifyVersionInfo; + static bool onetime = true; /* safe because first call is during init */ + + if(onetime) { + pRtlVerifyVersionInfo = CURLX_FUNCTION_CAST(RTLVERIFYVERSIONINFO_FN, + (GetProcAddress(GetModuleHandleA("ntdll"), "RtlVerifyVersionInfo"))); + onetime = false; + } + + switch(condition) { + case VERSION_LESS_THAN: + majorCondition = VER_LESS; + minorCondition = VER_LESS; + buildCondition = VER_LESS; + spMajorCondition = VER_LESS_EQUAL; + spMinorCondition = VER_LESS_EQUAL; + break; + + case VERSION_LESS_THAN_EQUAL: + majorCondition = VER_LESS_EQUAL; + minorCondition = VER_LESS_EQUAL; + buildCondition = VER_LESS_EQUAL; + spMajorCondition = VER_LESS_EQUAL; + spMinorCondition = VER_LESS_EQUAL; + break; + + case VERSION_EQUAL: + majorCondition = VER_EQUAL; + minorCondition = VER_EQUAL; + buildCondition = VER_EQUAL; + spMajorCondition = VER_GREATER_EQUAL; + spMinorCondition = VER_GREATER_EQUAL; + break; + + case VERSION_GREATER_THAN_EQUAL: + majorCondition = VER_GREATER_EQUAL; + minorCondition = VER_GREATER_EQUAL; + buildCondition = VER_GREATER_EQUAL; + spMajorCondition = VER_GREATER_EQUAL; + spMinorCondition = VER_GREATER_EQUAL; + break; + + case VERSION_GREATER_THAN: + majorCondition = VER_GREATER; + minorCondition = VER_GREATER; + buildCondition = VER_GREATER; + spMajorCondition = VER_GREATER_EQUAL; + spMinorCondition = VER_GREATER_EQUAL; + break; + + default: + return FALSE; + } + + memset(&osver, 0, sizeof(osver)); + osver.dwOSVersionInfoSize = sizeof(osver); + osver.dwMajorVersion = majorVersion; + osver.dwMinorVersion = minorVersion; + osver.dwBuildNumber = buildVersion; + if(platform == PLATFORM_WINDOWS) + osver.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS; + else if(platform == PLATFORM_WINNT) + osver.dwPlatformId = VER_PLATFORM_WIN32_NT; + + cm = VerSetConditionMask(cm, VER_MAJORVERSION, majorCondition); + cm = VerSetConditionMask(cm, VER_MINORVERSION, minorCondition); + cm = VerSetConditionMask(cm, VER_SERVICEPACKMAJOR, spMajorCondition); + cm = VerSetConditionMask(cm, VER_SERVICEPACKMINOR, spMinorCondition); + + if(platform != PLATFORM_DONT_CARE) { + cm = VerSetConditionMask(cm, VER_PLATFORMID, VER_EQUAL); + dwTypeMask |= VER_PLATFORMID; + } + + /* Later versions of Windows have version functions that may not return the + real version of Windows unless the application is so manifested. We prefer + the real version always, so we use the Rtl variant of the function when + possible. Note though the function signatures have underlying fundamental + types that are the same, the return values are different. */ + if(pRtlVerifyVersionInfo) + matched = !pRtlVerifyVersionInfo(&osver, dwTypeMask, cm); + else + matched = !!VerifyVersionInfoW((OSVERSIONINFOEXW *)&osver, dwTypeMask, cm); + + /* Compare the build number separately. VerifyVersionInfo normally compares + major.minor in hierarchical order (eg 1.9 is less than 2.0) but does not + do the same for build (eg 1.9 build 222 is not less than 2.0 build 111). + Build comparison is only needed when build numbers are equal (eg 1.9 is + always less than 2.0 so build comparison is not needed). */ + if(matched && buildVersion && + (condition == VERSION_EQUAL || + ((condition == VERSION_GREATER_THAN_EQUAL || + condition == VERSION_LESS_THAN_EQUAL) && + curlx_verify_windows_version(majorVersion, minorVersion, 0, + platform, VERSION_EQUAL)))) { + + cm = VerSetConditionMask(0, VER_BUILDNUMBER, buildCondition); + dwTypeMask = VER_BUILDNUMBER; + if(pRtlVerifyVersionInfo) + matched = !pRtlVerifyVersionInfo(&osver, dwTypeMask, cm); + else + matched = !!VerifyVersionInfoW((OSVERSIONINFOEXW *)&osver, + dwTypeMask, cm); + } + +#endif + + return matched; +} + +#endif /* _WIN32 */ diff --git a/third_party/curl/lib/version_win32.h b/third_party/curl/lib/version_win32.h new file mode 100644 index 0000000..95c0661 --- /dev/null +++ b/third_party/curl/lib/version_win32.h @@ -0,0 +1,56 @@ +#ifndef HEADER_CURL_VERSION_WIN32_H +#define HEADER_CURL_VERSION_WIN32_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, . + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(_WIN32) + +/* Version condition */ +typedef enum { + VERSION_LESS_THAN, + VERSION_LESS_THAN_EQUAL, + VERSION_EQUAL, + VERSION_GREATER_THAN_EQUAL, + VERSION_GREATER_THAN +} VersionCondition; + +/* Platform identifier */ +typedef enum { + PLATFORM_DONT_CARE, + PLATFORM_WINDOWS, + PLATFORM_WINNT +} PlatformIdentifier; + +/* This is used to verify if we are running on a specific windows version */ +bool curlx_verify_windows_version(const unsigned int majorVersion, + const unsigned int minorVersion, + const unsigned int buildVersion, + const PlatformIdentifier platform, + const VersionCondition condition); + +#endif /* _WIN32 */ + +#endif /* HEADER_CURL_VERSION_WIN32_H */ diff --git a/third_party/curl/lib/vquic/curl_msh3.c b/third_party/curl/lib/vquic/curl_msh3.c new file mode 100644 index 0000000..d49af6e --- /dev/null +++ b/third_party/curl/lib/vquic/curl_msh3.c @@ -0,0 +1,1115 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_MSH3 + +#include "urldata.h" +#include "hash.h" +#include "timeval.h" +#include "multiif.h" +#include "sendf.h" +#include "curl_trc.h" +#include "cfilters.h" +#include "cf-socket.h" +#include "connect.h" +#include "progress.h" +#include "http1.h" +#include "curl_msh3.h" +#include "socketpair.h" +#include "vtls/vtls.h" +#include "vquic/vquic.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#ifdef CURL_DISABLE_SOCKETPAIR +#error "MSH3 cannot be build with CURL_DISABLE_SOCKETPAIR set" +#endif + +#define H3_STREAM_WINDOW_SIZE (128 * 1024) +#define H3_STREAM_CHUNK_SIZE (16 * 1024) +#define H3_STREAM_RECV_CHUNKS \ + (H3_STREAM_WINDOW_SIZE / H3_STREAM_CHUNK_SIZE) + +#ifdef _WIN32 +#define msh3_lock CRITICAL_SECTION +#define msh3_lock_initialize(lock) InitializeCriticalSection(lock) +#define msh3_lock_uninitialize(lock) DeleteCriticalSection(lock) +#define msh3_lock_acquire(lock) EnterCriticalSection(lock) +#define msh3_lock_release(lock) LeaveCriticalSection(lock) +#else /* !_WIN32 */ +#include +#define msh3_lock pthread_mutex_t +#define msh3_lock_initialize(lock) do { \ + pthread_mutexattr_t attr; \ + pthread_mutexattr_init(&attr); \ + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); \ + pthread_mutex_init(lock, &attr); \ + pthread_mutexattr_destroy(&attr); \ +}while(0) +#define msh3_lock_uninitialize(lock) pthread_mutex_destroy(lock) +#define msh3_lock_acquire(lock) pthread_mutex_lock(lock) +#define msh3_lock_release(lock) pthread_mutex_unlock(lock) +#endif /* _WIN32 */ + + +static void MSH3_CALL msh3_conn_connected(MSH3_CONNECTION *Connection, + void *IfContext); +static void MSH3_CALL msh3_conn_shutdown_complete(MSH3_CONNECTION *Connection, + void *IfContext); +static void MSH3_CALL msh3_conn_new_request(MSH3_CONNECTION *Connection, + void *IfContext, + MSH3_REQUEST *Request); +static void MSH3_CALL msh3_header_received(MSH3_REQUEST *Request, + void *IfContext, + const MSH3_HEADER *Header); +static bool MSH3_CALL msh3_data_received(MSH3_REQUEST *Request, + void *IfContext, uint32_t *Length, + const uint8_t *Data); +static void MSH3_CALL msh3_complete(MSH3_REQUEST *Request, void *IfContext, + bool Aborted, uint64_t AbortError); +static void MSH3_CALL msh3_shutdown_complete(MSH3_REQUEST *Request, + void *IfContext); +static void MSH3_CALL msh3_data_sent(MSH3_REQUEST *Request, + void *IfContext, void *SendContext); + + +void Curl_msh3_ver(char *p, size_t len) +{ + uint32_t v[4]; + MsH3Version(v); + (void)msnprintf(p, len, "msh3/%d.%d.%d.%d", v[0], v[1], v[2], v[3]); +} + +#define SP_LOCAL 0 +#define SP_REMOTE 1 + +struct cf_msh3_ctx { + MSH3_API *api; + MSH3_CONNECTION *qconn; + struct Curl_sockaddr_ex addr; + curl_socket_t sock[2]; /* fake socket pair until we get support in msh3 */ + char l_ip[MAX_IPADR_LEN]; /* local IP as string */ + int l_port; /* local port number */ + struct cf_call_data call_data; + struct curltime connect_started; /* time the current attempt started */ + struct curltime handshake_at; /* time connect handshake finished */ + struct Curl_hash streams; /* hash `data->id` to `stream_ctx` */ + /* Flags written by msh3/msquic thread */ + bool handshake_complete; + bool handshake_succeeded; + bool connected; + /* Flags written by curl thread */ + BIT(verbose); + BIT(active); +}; + +static struct cf_msh3_ctx *h3_get_msh3_ctx(struct Curl_easy *data); + +/* How to access `call_data` from a cf_msh3 filter */ +#undef CF_CTX_CALL_DATA +#define CF_CTX_CALL_DATA(cf) \ + ((struct cf_msh3_ctx *)(cf)->ctx)->call_data + +/** + * All about the H3 internals of a stream + */ +struct stream_ctx { + struct MSH3_REQUEST *req; + struct bufq recvbuf; /* h3 response */ +#ifdef _WIN32 + CRITICAL_SECTION recv_lock; +#else /* !_WIN32 */ + pthread_mutex_t recv_lock; +#endif /* _WIN32 */ + uint64_t error3; /* HTTP/3 stream error code */ + int status_code; /* HTTP status code */ + CURLcode recv_error; + bool closed; + bool reset; + bool upload_done; + bool firstheader; /* FALSE until headers arrive */ + bool recv_header_complete; +}; + +#define H3_STREAM_CTX(ctx,data) ((struct stream_ctx *)((data && ctx)? \ + Curl_hash_offt_get(&(ctx)->streams, (data)->id) : NULL)) + +static void h3_stream_ctx_free(struct stream_ctx *stream) +{ + Curl_bufq_free(&stream->recvbuf); + free(stream); +} + +static void h3_stream_hash_free(void *stream) +{ + DEBUGASSERT(stream); + h3_stream_ctx_free((struct stream_ctx *)stream); +} + +static CURLcode h3_data_setup(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_msh3_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + if(stream) + return CURLE_OK; + + stream = calloc(1, sizeof(*stream)); + if(!stream) + return CURLE_OUT_OF_MEMORY; + + stream->req = ZERO_NULL; + msh3_lock_initialize(&stream->recv_lock); + Curl_bufq_init2(&stream->recvbuf, H3_STREAM_CHUNK_SIZE, + H3_STREAM_RECV_CHUNKS, BUFQ_OPT_SOFT_LIMIT); + CURL_TRC_CF(data, cf, "data setup"); + + if(!Curl_hash_offt_set(&ctx->streams, data->id, stream)) { + h3_stream_ctx_free(stream); + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} + +static void h3_data_done(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_msh3_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + (void)cf; + if(stream) { + CURL_TRC_CF(data, cf, "easy handle is done"); + Curl_hash_offt_remove(&ctx->streams, data->id); + } +} + +static void drain_stream_from_other_thread(struct Curl_easy *data, + struct stream_ctx *stream) +{ + unsigned char bits; + + /* risky */ + bits = CURL_CSELECT_IN; + if(stream && !stream->upload_done) + bits |= CURL_CSELECT_OUT; + if(data->state.select_bits != bits) { + data->state.select_bits = bits; + /* cannot expire from other thread */ + } +} + +static void drain_stream(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_msh3_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + unsigned char bits; + + (void)cf; + bits = CURL_CSELECT_IN; + if(stream && !stream->upload_done) + bits |= CURL_CSELECT_OUT; + if(data->state.select_bits != bits) { + data->state.select_bits = bits; + Curl_expire(data, 0, EXPIRE_RUN_NOW); + } +} + +static const MSH3_CONNECTION_IF msh3_conn_if = { + msh3_conn_connected, + msh3_conn_shutdown_complete, + msh3_conn_new_request +}; + +static void MSH3_CALL msh3_conn_connected(MSH3_CONNECTION *Connection, + void *IfContext) +{ + struct Curl_cfilter *cf = IfContext; + struct cf_msh3_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + (void)Connection; + + CURL_TRC_CF(data, cf, "[MSH3] connected"); + ctx->handshake_succeeded = true; + ctx->connected = true; + ctx->handshake_complete = true; +} + +static void MSH3_CALL msh3_conn_shutdown_complete(MSH3_CONNECTION *Connection, + void *IfContext) +{ + struct Curl_cfilter *cf = IfContext; + struct cf_msh3_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + + (void)Connection; + CURL_TRC_CF(data, cf, "[MSH3] shutdown complete"); + ctx->connected = false; + ctx->handshake_complete = true; +} + +static void MSH3_CALL msh3_conn_new_request(MSH3_CONNECTION *Connection, + void *IfContext, + MSH3_REQUEST *Request) +{ + (void)Connection; + (void)IfContext; + (void)Request; +} + +static const MSH3_REQUEST_IF msh3_request_if = { + msh3_header_received, + msh3_data_received, + msh3_complete, + msh3_shutdown_complete, + msh3_data_sent +}; + +/* Decode HTTP status code. Returns -1 if no valid status code was + decoded. (duplicate from http2.c) */ +static int decode_status_code(const char *value, size_t len) +{ + int i; + int res; + + if(len != 3) { + return -1; + } + + res = 0; + + for(i = 0; i < 3; ++i) { + char c = value[i]; + + if(c < '0' || c > '9') { + return -1; + } + + res *= 10; + res += c - '0'; + } + + return res; +} + +/* + * write_resp_raw() copies response data in raw format to the `data`'s + * receive buffer. If not enough space is available, it appends to the + * `data`'s overflow buffer. + */ +static CURLcode write_resp_raw(struct Curl_easy *data, + const void *mem, size_t memlen) +{ + struct cf_msh3_ctx *ctx = h3_get_msh3_ctx(data); + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURLcode result = CURLE_OK; + ssize_t nwritten; + + if(!stream) + return CURLE_RECV_ERROR; + + nwritten = Curl_bufq_write(&stream->recvbuf, mem, memlen, &result); + if(nwritten < 0) { + return result; + } + + if((size_t)nwritten < memlen) { + /* This MUST not happen. Our recbuf is dimensioned to hold the + * full max_stream_window and then some for this very reason. */ + DEBUGASSERT(0); + return CURLE_RECV_ERROR; + } + return result; +} + +static void MSH3_CALL msh3_header_received(MSH3_REQUEST *Request, + void *userp, + const MSH3_HEADER *hd) +{ + struct Curl_easy *data = userp; + struct cf_msh3_ctx *ctx = h3_get_msh3_ctx(data); + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURLcode result; + (void)Request; + + DEBUGF(infof(data, "[MSH3] header received, stream=%d", !!stream)); + if(!stream || stream->recv_header_complete) { + return; + } + + msh3_lock_acquire(&stream->recv_lock); + + if((hd->NameLength == 7) && + !strncmp(HTTP_PSEUDO_STATUS, (char *)hd->Name, 7)) { + char line[14]; /* status line is always 13 characters long */ + size_t ncopy; + + DEBUGASSERT(!stream->firstheader); + stream->status_code = decode_status_code(hd->Value, hd->ValueLength); + DEBUGASSERT(stream->status_code != -1); + ncopy = msnprintf(line, sizeof(line), "HTTP/3 %03d \r\n", + stream->status_code); + result = write_resp_raw(data, line, ncopy); + if(result) + stream->recv_error = result; + stream->firstheader = TRUE; + } + else { + /* store as an HTTP1-style header */ + DEBUGASSERT(stream->firstheader); + result = write_resp_raw(data, hd->Name, hd->NameLength); + if(!result) + result = write_resp_raw(data, ": ", 2); + if(!result) + result = write_resp_raw(data, hd->Value, hd->ValueLength); + if(!result) + result = write_resp_raw(data, "\r\n", 2); + if(result) { + stream->recv_error = result; + } + } + + drain_stream_from_other_thread(data, stream); + msh3_lock_release(&stream->recv_lock); +} + +static bool MSH3_CALL msh3_data_received(MSH3_REQUEST *Request, + void *IfContext, uint32_t *buflen, + const uint8_t *buf) +{ + struct Curl_easy *data = IfContext; + struct cf_msh3_ctx *ctx = h3_get_msh3_ctx(data); + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURLcode result; + bool rv = FALSE; + + /* TODO: we would like to limit the amount of data we are buffer here. + * There seems to be no mechanism in msh3 to adjust flow control and + * it is undocumented what happens if we return FALSE here or less + * length (buflen is an inout parameter). + */ + (void)Request; + if(!stream) + return FALSE; + + msh3_lock_acquire(&stream->recv_lock); + + if(!stream->recv_header_complete) { + result = write_resp_raw(data, "\r\n", 2); + if(result) { + stream->recv_error = result; + goto out; + } + stream->recv_header_complete = true; + } + + result = write_resp_raw(data, buf, *buflen); + if(result) { + stream->recv_error = result; + } + rv = TRUE; + +out: + msh3_lock_release(&stream->recv_lock); + return rv; +} + +static void MSH3_CALL msh3_complete(MSH3_REQUEST *Request, void *IfContext, + bool aborted, uint64_t error) +{ + struct Curl_easy *data = IfContext; + struct cf_msh3_ctx *ctx = h3_get_msh3_ctx(data); + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + (void)Request; + if(!stream) + return; + msh3_lock_acquire(&stream->recv_lock); + stream->closed = TRUE; + stream->recv_header_complete = true; + if(error) + stream->error3 = error; + if(aborted) + stream->reset = TRUE; + msh3_lock_release(&stream->recv_lock); +} + +static void MSH3_CALL msh3_shutdown_complete(MSH3_REQUEST *Request, + void *IfContext) +{ + struct Curl_easy *data = IfContext; + struct cf_msh3_ctx *ctx = h3_get_msh3_ctx(data); + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + if(!stream) + return; + (void)Request; + (void)stream; +} + +static void MSH3_CALL msh3_data_sent(MSH3_REQUEST *Request, + void *IfContext, void *SendContext) +{ + struct Curl_easy *data = IfContext; + struct cf_msh3_ctx *ctx = h3_get_msh3_ctx(data); + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + if(!stream) + return; + (void)Request; + (void)stream; + (void)SendContext; +} + +static ssize_t recv_closed_stream(struct Curl_cfilter *cf, + struct Curl_easy *data, + CURLcode *err) +{ + struct cf_msh3_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + ssize_t nread = -1; + + if(!stream) { + *err = CURLE_RECV_ERROR; + return -1; + } + (void)cf; + if(stream->reset) { + failf(data, "HTTP/3 stream reset by server"); + *err = CURLE_PARTIAL_FILE; + CURL_TRC_CF(data, cf, "cf_recv, was reset -> %d", *err); + goto out; + } + else if(stream->error3) { + failf(data, "HTTP/3 stream was not closed cleanly: (error %zd)", + (ssize_t)stream->error3); + *err = CURLE_HTTP3; + CURL_TRC_CF(data, cf, "cf_recv, closed uncleanly -> %d", *err); + goto out; + } + else { + CURL_TRC_CF(data, cf, "cf_recv, closed ok -> %d", *err); + } + *err = CURLE_OK; + nread = 0; + +out: + return nread; +} + +static void set_quic_expire(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_msh3_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + /* we have no indication from msh3 when it would be a good time + * to juggle the connection again. So, we compromise by calling + * us again every some milliseconds. */ + (void)cf; + if(stream && stream->req && !stream->closed) { + Curl_expire(data, 10, EXPIRE_QUIC); + } + else { + Curl_expire(data, 50, EXPIRE_QUIC); + } +} + +static ssize_t cf_msh3_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, CURLcode *err) +{ + struct cf_msh3_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + ssize_t nread = -1; + struct cf_call_data save; + + CURL_TRC_CF(data, cf, "cf_recv(len=%zu), stream=%d", len, !!stream); + if(!stream) { + *err = CURLE_RECV_ERROR; + return -1; + } + CF_DATA_SAVE(save, cf, data); + + msh3_lock_acquire(&stream->recv_lock); + + if(stream->recv_error) { + failf(data, "request aborted"); + *err = stream->recv_error; + goto out; + } + + *err = CURLE_OK; + + if(!Curl_bufq_is_empty(&stream->recvbuf)) { + nread = Curl_bufq_read(&stream->recvbuf, + (unsigned char *)buf, len, err); + CURL_TRC_CF(data, cf, "read recvbuf(len=%zu) -> %zd, %d", + len, nread, *err); + if(nread < 0) + goto out; + if(stream->closed) + drain_stream(cf, data); + } + else if(stream->closed) { + nread = recv_closed_stream(cf, data, err); + goto out; + } + else { + CURL_TRC_CF(data, cf, "req: nothing here, call again"); + *err = CURLE_AGAIN; + } + +out: + msh3_lock_release(&stream->recv_lock); + set_quic_expire(cf, data); + CF_DATA_RESTORE(cf, save); + return nread; +} + +static ssize_t cf_msh3_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *buf, size_t len, CURLcode *err) +{ + struct cf_msh3_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + struct h1_req_parser h1; + struct dynhds h2_headers; + MSH3_HEADER *nva = NULL; + size_t nheader, i; + ssize_t nwritten = -1; + struct cf_call_data save; + bool eos; + + CF_DATA_SAVE(save, cf, data); + + Curl_h1_req_parse_init(&h1, H1_PARSE_DEFAULT_MAX_LINE_LEN); + Curl_dynhds_init(&h2_headers, 0, DYN_HTTP_REQUEST); + + /* Sizes must match for cast below to work" */ + DEBUGASSERT(stream); + CURL_TRC_CF(data, cf, "req: send %zu bytes", len); + + if(!stream->req) { + /* The first send on the request contains the headers and possibly some + data. Parse out the headers and create the request, then if there is + any data left over go ahead and send it too. */ + nwritten = Curl_h1_req_parse_read(&h1, buf, len, NULL, 0, err); + if(nwritten < 0) + goto out; + DEBUGASSERT(h1.done); + DEBUGASSERT(h1.req); + + *err = Curl_http_req_to_h2(&h2_headers, h1.req, data); + if(*err) { + nwritten = -1; + goto out; + } + + nheader = Curl_dynhds_count(&h2_headers); + nva = malloc(sizeof(MSH3_HEADER) * nheader); + if(!nva) { + *err = CURLE_OUT_OF_MEMORY; + nwritten = -1; + goto out; + } + + for(i = 0; i < nheader; ++i) { + struct dynhds_entry *e = Curl_dynhds_getn(&h2_headers, i); + nva[i].Name = e->name; + nva[i].NameLength = e->namelen; + nva[i].Value = e->value; + nva[i].ValueLength = e->valuelen; + } + + switch(data->state.httpreq) { + case HTTPREQ_POST: + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + case HTTPREQ_PUT: + /* known request body size or -1 */ + eos = FALSE; + break; + default: + /* there is not request body */ + eos = TRUE; + stream->upload_done = TRUE; + break; + } + + CURL_TRC_CF(data, cf, "req: send %zu headers", nheader); + stream->req = MsH3RequestOpen(ctx->qconn, &msh3_request_if, data, + nva, nheader, + eos ? MSH3_REQUEST_FLAG_FIN : + MSH3_REQUEST_FLAG_NONE); + if(!stream->req) { + failf(data, "request open failed"); + *err = CURLE_SEND_ERROR; + goto out; + } + *err = CURLE_OK; + nwritten = len; + goto out; + } + else { + /* request is open */ + CURL_TRC_CF(data, cf, "req: send %zu body bytes", len); + if(len > 0xFFFFFFFF) { + len = 0xFFFFFFFF; + } + + if(!MsH3RequestSend(stream->req, MSH3_REQUEST_FLAG_NONE, buf, + (uint32_t)len, stream)) { + *err = CURLE_SEND_ERROR; + goto out; + } + + /* TODO - msh3/msquic will hold onto this memory until the send complete + event. How do we make sure curl doesn't free it until then? */ + *err = CURLE_OK; + nwritten = len; + } + +out: + set_quic_expire(cf, data); + free(nva); + Curl_h1_req_parse_free(&h1); + Curl_dynhds_free(&h2_headers); + CF_DATA_RESTORE(cf, save); + return nwritten; +} + +static void cf_msh3_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_msh3_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + if(stream && ctx->sock[SP_LOCAL] != CURL_SOCKET_BAD) { + if(stream->recv_error) { + Curl_pollset_add_in(data, ps, ctx->sock[SP_LOCAL]); + drain_stream(cf, data); + } + else if(stream->req) { + Curl_pollset_add_out(data, ps, ctx->sock[SP_LOCAL]); + drain_stream(cf, data); + } + } +} + +static bool cf_msh3_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct cf_msh3_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + struct cf_call_data save; + bool pending = FALSE; + + CF_DATA_SAVE(save, cf, data); + + (void)cf; + if(stream && stream->req) { + msh3_lock_acquire(&stream->recv_lock); + CURL_TRC_CF((struct Curl_easy *)data, cf, "data pending = %zu", + Curl_bufq_len(&stream->recvbuf)); + pending = !Curl_bufq_is_empty(&stream->recvbuf); + msh3_lock_release(&stream->recv_lock); + if(pending) + drain_stream(cf, (struct Curl_easy *)data); + } + + CF_DATA_RESTORE(cf, save); + return pending; +} + +static CURLcode h3_data_pause(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool pause) +{ + if(!pause) { + drain_stream(cf, data); + Curl_expire(data, 0, EXPIRE_RUN_NOW); + } + return CURLE_OK; +} + +static CURLcode cf_msh3_data_event(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + struct cf_msh3_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + struct cf_call_data save; + CURLcode result = CURLE_OK; + + CF_DATA_SAVE(save, cf, data); + + (void)arg1; + (void)arg2; + switch(event) { + case CF_CTRL_DATA_SETUP: + result = h3_data_setup(cf, data); + break; + case CF_CTRL_DATA_PAUSE: + result = h3_data_pause(cf, data, (arg1 != 0)); + break; + case CF_CTRL_DATA_DONE: + h3_data_done(cf, data); + break; + case CF_CTRL_DATA_DONE_SEND: + CURL_TRC_CF(data, cf, "req: send done"); + if(stream) { + stream->upload_done = TRUE; + if(stream->req) { + char buf[1]; + if(!MsH3RequestSend(stream->req, MSH3_REQUEST_FLAG_FIN, + buf, 0, data)) { + result = CURLE_SEND_ERROR; + } + } + } + break; + default: + break; + } + + CF_DATA_RESTORE(cf, save); + return result; +} + +static CURLcode cf_connect_start(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_msh3_ctx *ctx = cf->ctx; + struct ssl_primary_config *conn_config; + MSH3_ADDR addr = {0}; + CURLcode result; + bool verify; + + Curl_hash_offt_init(&ctx->streams, 63, h3_stream_hash_free); + conn_config = Curl_ssl_cf_get_primary_config(cf); + if(!conn_config) + return CURLE_FAILED_INIT; + verify = !!conn_config->verifypeer; + + memcpy(&addr, &ctx->addr.sa_addr, ctx->addr.addrlen); + MSH3_SET_PORT(&addr, (uint16_t)cf->conn->remote_port); + + if(verify && (conn_config->CAfile || conn_config->CApath)) { + /* TODO: need a way to provide trust anchors to MSH3 */ +#ifdef DEBUGBUILD + /* we need this for our test cases to run */ + CURL_TRC_CF(data, cf, "non-standard CA not supported, " + "switching off verifypeer in DEBUG mode"); + verify = 0; +#else + CURL_TRC_CF(data, cf, "non-standard CA not supported, " + "attempting with built-in verification"); +#endif + } + + CURL_TRC_CF(data, cf, "connecting to %s:%d (verify=%d)", + cf->conn->host.name, (int)cf->conn->remote_port, verify); + + ctx->api = MsH3ApiOpen(); + if(!ctx->api) { + failf(data, "can't create msh3 api"); + return CURLE_FAILED_INIT; + } + + ctx->qconn = MsH3ConnectionOpen(ctx->api, + &msh3_conn_if, + cf, + cf->conn->host.name, + &addr, + !verify); + if(!ctx->qconn) { + failf(data, "can't create msh3 connection"); + if(ctx->api) { + MsH3ApiClose(ctx->api); + ctx->api = NULL; + } + return CURLE_FAILED_INIT; + } + + result = h3_data_setup(cf, data); + if(result) + return result; + + return CURLE_OK; +} + +static CURLcode cf_msh3_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + struct cf_msh3_ctx *ctx = cf->ctx; + struct cf_call_data save; + CURLcode result = CURLE_OK; + + (void)blocking; + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + CF_DATA_SAVE(save, cf, data); + + if(ctx->sock[SP_LOCAL] == CURL_SOCKET_BAD) { + if(Curl_socketpair(AF_UNIX, SOCK_STREAM, 0, &ctx->sock[0]) < 0) { + ctx->sock[SP_LOCAL] = CURL_SOCKET_BAD; + ctx->sock[SP_REMOTE] = CURL_SOCKET_BAD; + return CURLE_COULDNT_CONNECT; + } + } + + *done = FALSE; + if(!ctx->qconn) { + ctx->connect_started = Curl_now(); + result = cf_connect_start(cf, data); + if(result) + goto out; + } + + if(ctx->handshake_complete) { + ctx->handshake_at = Curl_now(); + if(ctx->handshake_succeeded) { + CURL_TRC_CF(data, cf, "handshake succeeded"); + cf->conn->bits.multiplex = TRUE; /* at least potentially multiplexed */ + cf->conn->httpversion = 30; + cf->conn->bundle->multiuse = BUNDLE_MULTIPLEX; + cf->connected = TRUE; + cf->conn->alpn = CURL_HTTP_VERSION_3; + *done = TRUE; + connkeep(cf->conn, "HTTP/3 default"); + Curl_pgrsTime(data, TIMER_APPCONNECT); + } + else { + failf(data, "failed to connect, handshake failed"); + result = CURLE_COULDNT_CONNECT; + } + } + +out: + CF_DATA_RESTORE(cf, save); + return result; +} + +static void cf_msh3_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_msh3_ctx *ctx = cf->ctx; + struct cf_call_data save; + + (void)data; + CF_DATA_SAVE(save, cf, data); + + if(ctx) { + CURL_TRC_CF(data, cf, "destroying"); + if(ctx->qconn) { + MsH3ConnectionClose(ctx->qconn); + ctx->qconn = NULL; + } + if(ctx->api) { + MsH3ApiClose(ctx->api); + ctx->api = NULL; + } + Curl_hash_destroy(&ctx->streams); + + if(ctx->active) { + /* We share our socket at cf->conn->sock[cf->sockindex] when active. + * If it is no longer there, someone has stolen (and hopefully + * closed it) and we just forget about it. + */ + ctx->active = FALSE; + if(ctx->sock[SP_LOCAL] == cf->conn->sock[cf->sockindex]) { + CURL_TRC_CF(data, cf, "cf_msh3_close(%d) active", + (int)ctx->sock[SP_LOCAL]); + cf->conn->sock[cf->sockindex] = CURL_SOCKET_BAD; + } + else { + CURL_TRC_CF(data, cf, "cf_socket_close(%d) no longer at " + "conn->sock[], discarding", (int)ctx->sock[SP_LOCAL]); + ctx->sock[SP_LOCAL] = CURL_SOCKET_BAD; + } + if(cf->sockindex == FIRSTSOCKET) + cf->conn->remote_addr = NULL; + } + if(ctx->sock[SP_LOCAL] != CURL_SOCKET_BAD) { + sclose(ctx->sock[SP_LOCAL]); + } + if(ctx->sock[SP_REMOTE] != CURL_SOCKET_BAD) { + sclose(ctx->sock[SP_REMOTE]); + } + ctx->sock[SP_LOCAL] = CURL_SOCKET_BAD; + ctx->sock[SP_REMOTE] = CURL_SOCKET_BAD; + } + CF_DATA_RESTORE(cf, save); +} + +static void cf_msh3_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + cf_msh3_close(cf, data); + free(cf->ctx); + cf->ctx = NULL; + /* no CF_DATA_RESTORE(cf, save); its gone */ + +} + +static CURLcode cf_msh3_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_msh3_ctx *ctx = cf->ctx; + + switch(query) { + case CF_QUERY_MAX_CONCURRENT: { + /* TODO: we do not have access to this so far, fake it */ + (void)ctx; + *pres1 = 100; + return CURLE_OK; + } + case CF_QUERY_TIMER_CONNECT: { + struct curltime *when = pres2; + /* we do not know when the first byte arrived */ + if(cf->connected) + *when = ctx->handshake_at; + return CURLE_OK; + } + case CF_QUERY_TIMER_APPCONNECT: { + struct curltime *when = pres2; + if(cf->connected) + *when = ctx->handshake_at; + return CURLE_OK; + } + default: + break; + } + return cf->next? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +static bool cf_msh3_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending) +{ + struct cf_msh3_ctx *ctx = cf->ctx; + + (void)data; + *input_pending = FALSE; + return ctx && ctx->sock[SP_LOCAL] != CURL_SOCKET_BAD && ctx->qconn && + ctx->connected; +} + +struct Curl_cftype Curl_cft_http3 = { + "HTTP/3", + CF_TYPE_IP_CONNECT | CF_TYPE_SSL | CF_TYPE_MULTIPLEX, + 0, + cf_msh3_destroy, + cf_msh3_connect, + cf_msh3_close, + Curl_cf_def_get_host, + cf_msh3_adjust_pollset, + cf_msh3_data_pending, + cf_msh3_send, + cf_msh3_recv, + cf_msh3_data_event, + cf_msh3_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_msh3_query, +}; + +static struct cf_msh3_ctx *h3_get_msh3_ctx(struct Curl_easy *data) +{ + if(data && data->conn) { + struct Curl_cfilter *cf = data->conn->cfilter[FIRSTSOCKET]; + while(cf) { + if(cf->cft == &Curl_cft_http3) + return cf->ctx; + cf = cf->next; + } + } + DEBUGF(infof(data, "no filter context found")); + return NULL; +} + +CURLcode Curl_cf_msh3_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai) +{ + struct cf_msh3_ctx *ctx = NULL; + struct Curl_cfilter *cf = NULL; + CURLcode result; + + (void)data; + (void)conn; + (void)ai; /* TODO: msh3 resolves itself? */ + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + Curl_sock_assign_addr(&ctx->addr, ai, TRNSPRT_QUIC); + ctx->sock[SP_LOCAL] = CURL_SOCKET_BAD; + ctx->sock[SP_REMOTE] = CURL_SOCKET_BAD; + + result = Curl_cf_create(&cf, &Curl_cft_http3, ctx); + +out: + *pcf = (!result)? cf : NULL; + if(result) { + Curl_safefree(cf); + Curl_safefree(ctx); + } + + return result; +} + +bool Curl_conn_is_msh3(const struct Curl_easy *data, + const struct connectdata *conn, + int sockindex) +{ + struct Curl_cfilter *cf = conn? conn->cfilter[sockindex] : NULL; + + (void)data; + for(; cf; cf = cf->next) { + if(cf->cft == &Curl_cft_http3) + return TRUE; + if(cf->cft->flags & CF_TYPE_IP_CONNECT) + return FALSE; + } + return FALSE; +} + +#endif /* USE_MSH3 */ diff --git a/third_party/curl/lib/vquic/curl_msh3.h b/third_party/curl/lib/vquic/curl_msh3.h new file mode 100644 index 0000000..33931f5 --- /dev/null +++ b/third_party/curl/lib/vquic/curl_msh3.h @@ -0,0 +1,46 @@ +#ifndef HEADER_CURL_VQUIC_CURL_MSH3_H +#define HEADER_CURL_VQUIC_CURL_MSH3_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_MSH3 + +#include + +void Curl_msh3_ver(char *p, size_t len); + +CURLcode Curl_cf_msh3_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai); + +bool Curl_conn_is_msh3(const struct Curl_easy *data, + const struct connectdata *conn, + int sockindex); + +#endif /* USE_MSQUIC */ + +#endif /* HEADER_CURL_VQUIC_CURL_MSH3_H */ diff --git a/third_party/curl/lib/vquic/curl_ngtcp2.c b/third_party/curl/lib/vquic/curl_ngtcp2.c new file mode 100644 index 0000000..0d9d87f --- /dev/null +++ b/third_party/curl/lib/vquic/curl_ngtcp2.c @@ -0,0 +1,2509 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_NGTCP2) && defined(USE_NGHTTP3) +#include +#include + +#ifdef USE_OPENSSL +#include +#if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) +#include +#else +#include +#endif +#include "vtls/openssl.h" +#elif defined(USE_GNUTLS) +#include +#include "vtls/gtls.h" +#elif defined(USE_WOLFSSL) +#include +#endif + +#include "urldata.h" +#include "hash.h" +#include "sendf.h" +#include "strdup.h" +#include "rand.h" +#include "multiif.h" +#include "strcase.h" +#include "cfilters.h" +#include "cf-socket.h" +#include "connect.h" +#include "progress.h" +#include "strerror.h" +#include "dynbuf.h" +#include "http1.h" +#include "select.h" +#include "inet_pton.h" +#include "transfer.h" +#include "vquic.h" +#include "vquic_int.h" +#include "vquic-tls.h" +#include "vtls/keylog.h" +#include "vtls/vtls.h" +#include "curl_ngtcp2.h" + +#include "warnless.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +#define QUIC_MAX_STREAMS (256*1024) +#define QUIC_MAX_DATA (1*1024*1024) +#define QUIC_HANDSHAKE_TIMEOUT (10*NGTCP2_SECONDS) + +/* A stream window is the maximum amount we need to buffer for + * each active transfer. We use HTTP/3 flow control and only ACK + * when we take things out of the buffer. + * Chunk size is large enough to take a full DATA frame */ +#define H3_STREAM_WINDOW_SIZE (128 * 1024) +#define H3_STREAM_CHUNK_SIZE (16 * 1024) +/* The pool keeps spares around and half of a full stream windows + * seems good. More does not seem to improve performance. + * The benefit of the pool is that stream buffer to not keep + * spares. So memory consumption goes down when streams run empty, + * have a large upload done, etc. */ +#define H3_STREAM_POOL_SPARES \ + (H3_STREAM_WINDOW_SIZE / H3_STREAM_CHUNK_SIZE ) / 2 +/* Receive and Send max number of chunks just follows from the + * chunk size and window size */ +#define H3_STREAM_RECV_CHUNKS \ + (H3_STREAM_WINDOW_SIZE / H3_STREAM_CHUNK_SIZE) +#define H3_STREAM_SEND_CHUNKS \ + (H3_STREAM_WINDOW_SIZE / H3_STREAM_CHUNK_SIZE) + + +/* + * Store ngtcp2 version info in this buffer. + */ +void Curl_ngtcp2_ver(char *p, size_t len) +{ + const ngtcp2_info *ng2 = ngtcp2_version(0); + const nghttp3_info *ht3 = nghttp3_version(0); + (void)msnprintf(p, len, "ngtcp2/%s nghttp3/%s", + ng2->version_str, ht3->version_str); +} + +struct cf_ngtcp2_ctx { + struct cf_quic_ctx q; + struct ssl_peer peer; + struct curl_tls_ctx tls; + ngtcp2_path connected_path; + ngtcp2_conn *qconn; + ngtcp2_cid dcid; + ngtcp2_cid scid; + uint32_t version; + ngtcp2_settings settings; + ngtcp2_transport_params transport_params; + ngtcp2_ccerr last_error; + ngtcp2_crypto_conn_ref conn_ref; + struct cf_call_data call_data; + nghttp3_conn *h3conn; + nghttp3_settings h3settings; + struct curltime started_at; /* time the current attempt started */ + struct curltime handshake_at; /* time connect handshake finished */ + struct curltime reconnect_at; /* time the next attempt should start */ + struct bufc_pool stream_bufcp; /* chunk pool for streams */ + struct dynbuf scratch; /* temp buffer for header construction */ + struct Curl_hash streams; /* hash `data->id` to `h3_stream_ctx` */ + size_t max_stream_window; /* max flow window for one stream */ + uint64_t max_idle_ms; /* max idle time for QUIC connection */ + uint64_t used_bidi_streams; /* bidi streams we have opened */ + uint64_t max_bidi_streams; /* max bidi streams we can open */ + int qlogfd; + BIT(conn_closed); /* connection is closed */ +}; + +/* How to access `call_data` from a cf_ngtcp2 filter */ +#undef CF_CTX_CALL_DATA +#define CF_CTX_CALL_DATA(cf) \ + ((struct cf_ngtcp2_ctx *)(cf)->ctx)->call_data + +struct pkt_io_ctx; +static CURLcode cf_progress_ingress(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct pkt_io_ctx *pktx); +static CURLcode cf_progress_egress(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct pkt_io_ctx *pktx); + +/** + * All about the H3 internals of a stream + */ +struct h3_stream_ctx { + curl_int64_t id; /* HTTP/3 protocol identifier */ + struct bufq sendbuf; /* h3 request body */ + struct h1_req_parser h1; /* h1 request parsing */ + size_t sendbuf_len_in_flight; /* sendbuf amount "in flight" */ + size_t upload_blocked_len; /* the amount written last and EGAINed */ + curl_uint64_t error3; /* HTTP/3 stream error code */ + curl_off_t upload_left; /* number of request bytes left to upload */ + int status_code; /* HTTP status code */ + CURLcode xfer_result; /* result from xfer_resp_write(_hd) */ + bool resp_hds_complete; /* we have a complete, final response */ + bool closed; /* TRUE on stream close */ + bool reset; /* TRUE on stream reset */ + bool send_closed; /* stream is local closed */ + BIT(quic_flow_blocked); /* stream is blocked by QUIC flow control */ +}; + +#define H3_STREAM_CTX(ctx,data) ((struct h3_stream_ctx *)(\ + data? Curl_hash_offt_get(&(ctx)->streams, (data)->id) : NULL)) +#define H3_STREAM_CTX_ID(ctx,id) ((struct h3_stream_ctx *)(\ + Curl_hash_offt_get(&(ctx)->streams, (id)))) + +static void h3_stream_ctx_free(struct h3_stream_ctx *stream) +{ + Curl_bufq_free(&stream->sendbuf); + Curl_h1_req_parse_free(&stream->h1); + free(stream); +} + +static void h3_stream_hash_free(void *stream) +{ + DEBUGASSERT(stream); + h3_stream_ctx_free((struct h3_stream_ctx *)stream); +} + +static CURLcode h3_data_setup(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + if(!data || !data->req.p.http) { + failf(data, "initialization failure, transfer not http initialized"); + return CURLE_FAILED_INIT; + } + + if(stream) + return CURLE_OK; + + stream = calloc(1, sizeof(*stream)); + if(!stream) + return CURLE_OUT_OF_MEMORY; + + stream->id = -1; + /* on send, we control how much we put into the buffer */ + Curl_bufq_initp(&stream->sendbuf, &ctx->stream_bufcp, + H3_STREAM_SEND_CHUNKS, BUFQ_OPT_NONE); + stream->sendbuf_len_in_flight = 0; + Curl_h1_req_parse_init(&stream->h1, H1_PARSE_DEFAULT_MAX_LINE_LEN); + + if(!Curl_hash_offt_set(&ctx->streams, data->id, stream)) { + h3_stream_ctx_free(stream); + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} + +static void cf_ngtcp2_stream_close(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + DEBUGASSERT(data); + DEBUGASSERT(stream); + if(!stream->closed && ctx->qconn && ctx->h3conn) { + CURLcode result; + + nghttp3_conn_set_stream_user_data(ctx->h3conn, stream->id, NULL); + ngtcp2_conn_set_stream_user_data(ctx->qconn, stream->id, NULL); + stream->closed = TRUE; + (void)ngtcp2_conn_shutdown_stream(ctx->qconn, 0, stream->id, + NGHTTP3_H3_REQUEST_CANCELLED); + result = cf_progress_egress(cf, data, NULL); + if(result) + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] cancel stream -> %d", + stream->id, result); + } +} + +static void h3_data_done(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + (void)cf; + if(stream) { + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] easy handle is done", + stream->id); + cf_ngtcp2_stream_close(cf, data, stream); + Curl_hash_offt_remove(&ctx->streams, data->id); + } +} + +static struct Curl_easy *get_stream_easy(struct Curl_cfilter *cf, + struct Curl_easy *data, + int64_t stream_id, + struct h3_stream_ctx **pstream) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *sdata; + struct h3_stream_ctx *stream; + + (void)cf; + stream = H3_STREAM_CTX(ctx, data); + if(stream && stream->id == stream_id) { + *pstream = stream; + return data; + } + else { + DEBUGASSERT(data->multi); + for(sdata = data->multi->easyp; sdata; sdata = sdata->next) { + if(sdata->conn != data->conn) + continue; + stream = H3_STREAM_CTX(ctx, sdata); + if(stream && stream->id == stream_id) { + *pstream = stream; + return sdata; + } + } + } + *pstream = NULL; + return NULL; +} + +static void h3_drain_stream(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + unsigned char bits; + + (void)cf; + bits = CURL_CSELECT_IN; + if(stream && stream->upload_left && !stream->send_closed) + bits |= CURL_CSELECT_OUT; + if(data->state.select_bits != bits) { + data->state.select_bits = bits; + Curl_expire(data, 0, EXPIRE_RUN_NOW); + } +} + +/* ngtcp2 default congestion controller does not perform pacing. Limit + the maximum packet burst to MAX_PKT_BURST packets. */ +#define MAX_PKT_BURST 10 + +struct pkt_io_ctx { + struct Curl_cfilter *cf; + struct Curl_easy *data; + ngtcp2_tstamp ts; + size_t pkt_count; + ngtcp2_path_storage ps; +}; + +static void pktx_update_time(struct pkt_io_ctx *pktx, + struct Curl_cfilter *cf) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + + vquic_ctx_update_time(&ctx->q); + pktx->ts = ctx->q.last_op.tv_sec * NGTCP2_SECONDS + + ctx->q.last_op.tv_usec * NGTCP2_MICROSECONDS; +} + +static void pktx_init(struct pkt_io_ctx *pktx, + struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + pktx->cf = cf; + pktx->data = data; + pktx->pkt_count = 0; + ngtcp2_path_storage_zero(&pktx->ps); + pktx_update_time(pktx, cf); +} + +static int cb_h3_acked_req_body(nghttp3_conn *conn, int64_t stream_id, + uint64_t datalen, void *user_data, + void *stream_user_data); + +static ngtcp2_conn *get_conn(ngtcp2_crypto_conn_ref *conn_ref) +{ + struct Curl_cfilter *cf = conn_ref->user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + return ctx->qconn; +} + +#ifdef DEBUG_NGTCP2 +static void quic_printf(void *user_data, const char *fmt, ...) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + + (void)ctx; /* TODO: need an easy handle to infof() message */ + va_list ap; + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + fprintf(stderr, "\n"); +} +#endif + +static void qlog_callback(void *user_data, uint32_t flags, + const void *data, size_t datalen) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + (void)flags; + if(ctx->qlogfd != -1) { + ssize_t rc = write(ctx->qlogfd, data, datalen); + if(rc == -1) { + /* on write error, stop further write attempts */ + close(ctx->qlogfd); + ctx->qlogfd = -1; + } + } + +} + +static void quic_settings(struct cf_ngtcp2_ctx *ctx, + struct Curl_easy *data, + struct pkt_io_ctx *pktx) +{ + ngtcp2_settings *s = &ctx->settings; + ngtcp2_transport_params *t = &ctx->transport_params; + + ngtcp2_settings_default(s); + ngtcp2_transport_params_default(t); +#ifdef DEBUG_NGTCP2 + s->log_printf = quic_printf; +#else + s->log_printf = NULL; +#endif + + (void)data; + s->initial_ts = pktx->ts; + s->handshake_timeout = QUIC_HANDSHAKE_TIMEOUT; + s->max_window = 100 * ctx->max_stream_window; + s->max_stream_window = ctx->max_stream_window; + + t->initial_max_data = 10 * ctx->max_stream_window; + t->initial_max_stream_data_bidi_local = ctx->max_stream_window; + t->initial_max_stream_data_bidi_remote = ctx->max_stream_window; + t->initial_max_stream_data_uni = ctx->max_stream_window; + t->initial_max_streams_bidi = QUIC_MAX_STREAMS; + t->initial_max_streams_uni = QUIC_MAX_STREAMS; + t->max_idle_timeout = (ctx->max_idle_ms * NGTCP2_MILLISECONDS); + if(ctx->qlogfd != -1) { + s->qlog_write = qlog_callback; + } +} + +static int init_ngh3_conn(struct Curl_cfilter *cf); + +static int cb_handshake_completed(ngtcp2_conn *tconn, void *user_data) +{ + (void)user_data; + (void)tconn; + return 0; +} + +static void cf_ngtcp2_conn_close(struct Curl_cfilter *cf, + struct Curl_easy *data); + +static bool cf_ngtcp2_err_is_fatal(int code) +{ + return (NGTCP2_ERR_FATAL >= code) || + (NGTCP2_ERR_DROP_CONN == code) || + (NGTCP2_ERR_IDLE_CLOSE == code); +} + +static void cf_ngtcp2_err_set(struct Curl_cfilter *cf, + struct Curl_easy *data, int code) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + if(!ctx->last_error.error_code) { + if(NGTCP2_ERR_CRYPTO == code) { + ngtcp2_ccerr_set_tls_alert(&ctx->last_error, + ngtcp2_conn_get_tls_alert(ctx->qconn), + NULL, 0); + } + else { + ngtcp2_ccerr_set_liberr(&ctx->last_error, code, NULL, 0); + } + } + if(cf_ngtcp2_err_is_fatal(code)) + cf_ngtcp2_conn_close(cf, data); +} + +static bool cf_ngtcp2_h3_err_is_fatal(int code) +{ + return (NGHTTP3_ERR_FATAL >= code) || + (NGHTTP3_ERR_H3_CLOSED_CRITICAL_STREAM == code); +} + +static void cf_ngtcp2_h3_err_set(struct Curl_cfilter *cf, + struct Curl_easy *data, int code) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + if(!ctx->last_error.error_code) { + ngtcp2_ccerr_set_application_error(&ctx->last_error, + nghttp3_err_infer_quic_app_error_code(code), NULL, 0); + } + if(cf_ngtcp2_h3_err_is_fatal(code)) + cf_ngtcp2_conn_close(cf, data); +} + +static int cb_recv_stream_data(ngtcp2_conn *tconn, uint32_t flags, + int64_t sid, uint64_t offset, + const uint8_t *buf, size_t buflen, + void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + curl_int64_t stream_id = (curl_int64_t)sid; + nghttp3_ssize nconsumed; + int fin = (flags & NGTCP2_STREAM_DATA_FLAG_FIN) ? 1 : 0; + struct Curl_easy *data = stream_user_data; + (void)offset; + (void)data; + + nconsumed = + nghttp3_conn_read_stream(ctx->h3conn, stream_id, buf, buflen, fin); + if(!data) + data = CF_DATA_CURRENT(cf); + if(data) + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] read_stream(len=%zu) -> %zd", + stream_id, buflen, nconsumed); + if(nconsumed < 0) { + struct h3_stream_ctx *stream = H3_STREAM_CTX_ID(ctx, stream_id); + if(data && stream) { + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] error on known stream, " + "reset=%d, closed=%d", + stream_id, stream->reset, stream->closed); + } + return NGTCP2_ERR_CALLBACK_FAILURE; + } + + /* number of bytes inside buflen which consists of framing overhead + * including QPACK HEADERS. In other words, it does not consume payload of + * DATA frame. */ + ngtcp2_conn_extend_max_stream_offset(tconn, stream_id, nconsumed); + ngtcp2_conn_extend_max_offset(tconn, nconsumed); + + return 0; +} + +static int +cb_acked_stream_data_offset(ngtcp2_conn *tconn, int64_t stream_id, + uint64_t offset, uint64_t datalen, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + int rv; + (void)stream_id; + (void)tconn; + (void)offset; + (void)datalen; + (void)stream_user_data; + + rv = nghttp3_conn_add_ack_offset(ctx->h3conn, stream_id, datalen); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + return NGTCP2_ERR_CALLBACK_FAILURE; + } + + return 0; +} + +static int cb_stream_close(ngtcp2_conn *tconn, uint32_t flags, + int64_t sid, uint64_t app_error_code, + void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + curl_int64_t stream_id = (curl_int64_t)sid; + int rv; + + (void)tconn; + /* stream is closed... */ + if(!data) + data = CF_DATA_CURRENT(cf); + if(!data) + return NGTCP2_ERR_CALLBACK_FAILURE; + + if(!(flags & NGTCP2_STREAM_CLOSE_FLAG_APP_ERROR_CODE_SET)) { + app_error_code = NGHTTP3_H3_NO_ERROR; + } + + rv = nghttp3_conn_close_stream(ctx->h3conn, stream_id, app_error_code); + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] quic close(app_error=%" + CURL_PRIu64 ") -> %d", stream_id, (curl_uint64_t)app_error_code, + rv); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + cf_ngtcp2_h3_err_set(cf, data, rv); + return NGTCP2_ERR_CALLBACK_FAILURE; + } + + return 0; +} + +static int cb_stream_reset(ngtcp2_conn *tconn, int64_t sid, + uint64_t final_size, uint64_t app_error_code, + void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + curl_int64_t stream_id = (curl_int64_t)sid; + struct Curl_easy *data = stream_user_data; + int rv; + (void)tconn; + (void)final_size; + (void)app_error_code; + (void)data; + + rv = nghttp3_conn_shutdown_stream_read(ctx->h3conn, stream_id); + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] reset -> %d", stream_id, rv); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + return NGTCP2_ERR_CALLBACK_FAILURE; + } + + return 0; +} + +static int cb_stream_stop_sending(ngtcp2_conn *tconn, int64_t stream_id, + uint64_t app_error_code, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + int rv; + (void)tconn; + (void)app_error_code; + (void)stream_user_data; + + rv = nghttp3_conn_shutdown_stream_read(ctx->h3conn, stream_id); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + return NGTCP2_ERR_CALLBACK_FAILURE; + } + + return 0; +} + +static int cb_extend_max_local_streams_bidi(ngtcp2_conn *tconn, + uint64_t max_streams, + void *user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + + (void)tconn; + ctx->max_bidi_streams = max_streams; + if(data) + CURL_TRC_CF(data, cf, "max bidi streams now %" CURL_PRIu64 + ", used %" CURL_PRIu64, (curl_uint64_t)ctx->max_bidi_streams, + (curl_uint64_t)ctx->used_bidi_streams); + return 0; +} + +static int cb_extend_max_stream_data(ngtcp2_conn *tconn, int64_t sid, + uint64_t max_data, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + curl_int64_t stream_id = (curl_int64_t)sid; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + struct Curl_easy *s_data; + struct h3_stream_ctx *stream; + int rv; + (void)tconn; + (void)max_data; + (void)stream_user_data; + + rv = nghttp3_conn_unblock_stream(ctx->h3conn, stream_id); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + return NGTCP2_ERR_CALLBACK_FAILURE; + } + s_data = get_stream_easy(cf, data, stream_id, &stream); + if(s_data && stream && stream->quic_flow_blocked) { + CURL_TRC_CF(s_data, cf, "[%" CURL_PRId64 "] unblock quic flow", + stream_id); + stream->quic_flow_blocked = FALSE; + h3_drain_stream(cf, s_data); + } + return 0; +} + +static void cb_rand(uint8_t *dest, size_t destlen, + const ngtcp2_rand_ctx *rand_ctx) +{ + CURLcode result; + (void)rand_ctx; + + result = Curl_rand(NULL, dest, destlen); + if(result) { + /* cb_rand is only used for non-cryptographic context. If Curl_rand + failed, just fill 0 and call it *random*. */ + memset(dest, 0, destlen); + } +} + +static int cb_get_new_connection_id(ngtcp2_conn *tconn, ngtcp2_cid *cid, + uint8_t *token, size_t cidlen, + void *user_data) +{ + CURLcode result; + (void)tconn; + (void)user_data; + + result = Curl_rand(NULL, cid->data, cidlen); + if(result) + return NGTCP2_ERR_CALLBACK_FAILURE; + cid->datalen = cidlen; + + result = Curl_rand(NULL, token, NGTCP2_STATELESS_RESET_TOKENLEN); + if(result) + return NGTCP2_ERR_CALLBACK_FAILURE; + + return 0; +} + +static int cb_recv_rx_key(ngtcp2_conn *tconn, ngtcp2_encryption_level level, + void *user_data) +{ + struct Curl_cfilter *cf = user_data; + (void)tconn; + + if(level != NGTCP2_ENCRYPTION_LEVEL_1RTT) { + return 0; + } + + if(init_ngh3_conn(cf) != CURLE_OK) { + return NGTCP2_ERR_CALLBACK_FAILURE; + } + + return 0; +} + +static ngtcp2_callbacks ng_callbacks = { + ngtcp2_crypto_client_initial_cb, + NULL, /* recv_client_initial */ + ngtcp2_crypto_recv_crypto_data_cb, + cb_handshake_completed, + NULL, /* recv_version_negotiation */ + ngtcp2_crypto_encrypt_cb, + ngtcp2_crypto_decrypt_cb, + ngtcp2_crypto_hp_mask_cb, + cb_recv_stream_data, + cb_acked_stream_data_offset, + NULL, /* stream_open */ + cb_stream_close, + NULL, /* recv_stateless_reset */ + ngtcp2_crypto_recv_retry_cb, + cb_extend_max_local_streams_bidi, + NULL, /* extend_max_local_streams_uni */ + cb_rand, + cb_get_new_connection_id, + NULL, /* remove_connection_id */ + ngtcp2_crypto_update_key_cb, /* update_key */ + NULL, /* path_validation */ + NULL, /* select_preferred_addr */ + cb_stream_reset, + NULL, /* extend_max_remote_streams_bidi */ + NULL, /* extend_max_remote_streams_uni */ + cb_extend_max_stream_data, + NULL, /* dcid_status */ + NULL, /* handshake_confirmed */ + NULL, /* recv_new_token */ + ngtcp2_crypto_delete_crypto_aead_ctx_cb, + ngtcp2_crypto_delete_crypto_cipher_ctx_cb, + NULL, /* recv_datagram */ + NULL, /* ack_datagram */ + NULL, /* lost_datagram */ + ngtcp2_crypto_get_path_challenge_data_cb, + cb_stream_stop_sending, + NULL, /* version_negotiation */ + cb_recv_rx_key, + NULL, /* recv_tx_key */ + NULL, /* early_data_rejected */ +}; + +/** + * Connection maintenance like timeouts on packet ACKs etc. are done by us, not + * the OS like for TCP. POLL events on the socket therefore are not + * sufficient. + * ngtcp2 tells us when it wants to be invoked again. We handle that via + * the `Curl_expire()` mechanisms. + */ +static CURLcode check_and_set_expiry(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct pkt_io_ctx *pktx) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct pkt_io_ctx local_pktx; + ngtcp2_tstamp expiry; + + if(!pktx) { + pktx_init(&local_pktx, cf, data); + pktx = &local_pktx; + } + else { + pktx_update_time(pktx, cf); + } + + expiry = ngtcp2_conn_get_expiry(ctx->qconn); + if(expiry != UINT64_MAX) { + if(expiry <= pktx->ts) { + CURLcode result; + int rv = ngtcp2_conn_handle_expiry(ctx->qconn, pktx->ts); + if(rv) { + failf(data, "ngtcp2_conn_handle_expiry returned error: %s", + ngtcp2_strerror(rv)); + cf_ngtcp2_err_set(cf, data, rv); + return CURLE_SEND_ERROR; + } + result = cf_progress_ingress(cf, data, pktx); + if(result) + return result; + result = cf_progress_egress(cf, data, pktx); + if(result) + return result; + /* ask again, things might have changed */ + expiry = ngtcp2_conn_get_expiry(ctx->qconn); + } + + if(expiry > pktx->ts) { + ngtcp2_duration timeout = expiry - pktx->ts; + if(timeout % NGTCP2_MILLISECONDS) { + timeout += NGTCP2_MILLISECONDS; + } + Curl_expire(data, timeout / NGTCP2_MILLISECONDS, EXPIRE_QUIC); + } + } + return CURLE_OK; +} + +static void cf_ngtcp2_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + bool want_recv, want_send; + + if(!ctx->qconn) + return; + + Curl_pollset_check(data, ps, ctx->q.sockfd, &want_recv, &want_send); + if(want_recv || want_send) { + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + struct cf_call_data save; + bool c_exhaust, s_exhaust; + + CF_DATA_SAVE(save, cf, data); + c_exhaust = want_send && (!ngtcp2_conn_get_cwnd_left(ctx->qconn) || + !ngtcp2_conn_get_max_data_left(ctx->qconn)); + s_exhaust = want_send && stream && stream->id >= 0 && + stream->quic_flow_blocked; + want_recv = (want_recv || c_exhaust || s_exhaust); + want_send = (!s_exhaust && want_send) || + !Curl_bufq_is_empty(&ctx->q.sendbuf); + + Curl_pollset_set(data, ps, ctx->q.sockfd, want_recv, want_send); + CF_DATA_RESTORE(cf, save); + } +} + +static int cb_h3_stream_close(nghttp3_conn *conn, int64_t sid, + uint64_t app_error_code, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + curl_int64_t stream_id = (curl_int64_t)sid; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + (void)conn; + (void)stream_id; + + /* we might be called by nghttp3 after we already cleaned up */ + if(!stream) + return 0; + + stream->closed = TRUE; + stream->error3 = (curl_uint64_t)app_error_code; + if(stream->error3 != NGHTTP3_H3_NO_ERROR) { + stream->reset = TRUE; + stream->send_closed = TRUE; + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] RESET: error %" CURL_PRIu64, + stream->id, stream->error3); + } + else { + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] CLOSED", stream->id); + } + h3_drain_stream(cf, data); + return 0; +} + +static void h3_xfer_write_resp_hd(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream, + const char *buf, size_t blen, bool eos) +{ + + /* If we already encountered an error, skip further writes */ + if(!stream->xfer_result) { + stream->xfer_result = Curl_xfer_write_resp_hd(data, buf, blen, eos); + if(stream->xfer_result) + CURL_TRC_CF(data, cf, "[%"CURL_PRId64"] error %d writing %zu " + "bytes of headers", stream->id, stream->xfer_result, blen); + } +} + +static void h3_xfer_write_resp(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream, + const char *buf, size_t blen, bool eos) +{ + + /* If we already encountered an error, skip further writes */ + if(!stream->xfer_result) { + stream->xfer_result = Curl_xfer_write_resp(data, buf, blen, eos); + /* If the transfer write is errored, we do not want any more data */ + if(stream->xfer_result) { + CURL_TRC_CF(data, cf, "[%"CURL_PRId64"] error %d writing %zu bytes " + "of data", stream->id, stream->xfer_result, blen); + } + } +} + +static int cb_h3_recv_data(nghttp3_conn *conn, int64_t stream3_id, + const uint8_t *buf, size_t blen, + void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + (void)conn; + (void)stream3_id; + + if(!stream) + return NGHTTP3_ERR_CALLBACK_FAILURE; + + h3_xfer_write_resp(cf, data, stream, (char *)buf, blen, FALSE); + if(blen) { + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] ACK %zu bytes of DATA", + stream->id, blen); + ngtcp2_conn_extend_max_stream_offset(ctx->qconn, stream->id, blen); + ngtcp2_conn_extend_max_offset(ctx->qconn, blen); + } + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] DATA len=%zu", stream->id, blen); + return 0; +} + +static int cb_h3_deferred_consume(nghttp3_conn *conn, int64_t stream3_id, + size_t consumed, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + (void)conn; + (void)stream_user_data; + + /* nghttp3 has consumed bytes on the QUIC stream and we need to + * tell the QUIC connection to increase its flow control */ + ngtcp2_conn_extend_max_stream_offset(ctx->qconn, stream3_id, consumed); + ngtcp2_conn_extend_max_offset(ctx->qconn, consumed); + return 0; +} + +static int cb_h3_end_headers(nghttp3_conn *conn, int64_t sid, + int fin, void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + curl_int64_t stream_id = (curl_int64_t)sid; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + (void)conn; + (void)stream_id; + (void)fin; + (void)cf; + + if(!stream) + return 0; + /* add a CRLF only if we've received some headers */ + h3_xfer_write_resp_hd(cf, data, stream, STRCONST("\r\n"), stream->closed); + + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] end_headers, status=%d", + stream_id, stream->status_code); + if(stream->status_code / 100 != 1) { + stream->resp_hds_complete = TRUE; + } + h3_drain_stream(cf, data); + return 0; +} + +static int cb_h3_recv_header(nghttp3_conn *conn, int64_t sid, + int32_t token, nghttp3_rcbuf *name, + nghttp3_rcbuf *value, uint8_t flags, + void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + curl_int64_t stream_id = (curl_int64_t)sid; + nghttp3_vec h3name = nghttp3_rcbuf_get_buf(name); + nghttp3_vec h3val = nghttp3_rcbuf_get_buf(value); + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURLcode result = CURLE_OK; + (void)conn; + (void)stream_id; + (void)token; + (void)flags; + (void)cf; + + /* we might have cleaned up this transfer already */ + if(!stream) + return 0; + + if(token == NGHTTP3_QPACK_TOKEN__STATUS) { + + result = Curl_http_decode_status(&stream->status_code, + (const char *)h3val.base, h3val.len); + if(result) + return -1; + Curl_dyn_reset(&ctx->scratch); + result = Curl_dyn_addn(&ctx->scratch, STRCONST("HTTP/3 ")); + if(!result) + result = Curl_dyn_addn(&ctx->scratch, + (const char *)h3val.base, h3val.len); + if(!result) + result = Curl_dyn_addn(&ctx->scratch, STRCONST(" \r\n")); + if(!result) + h3_xfer_write_resp_hd(cf, data, stream, Curl_dyn_ptr(&ctx->scratch), + Curl_dyn_len(&ctx->scratch), FALSE); + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] status: %s", + stream_id, Curl_dyn_ptr(&ctx->scratch)); + if(result) { + return -1; + } + } + else { + /* store as an HTTP1-style header */ + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] header: %.*s: %.*s", + stream_id, (int)h3name.len, h3name.base, + (int)h3val.len, h3val.base); + Curl_dyn_reset(&ctx->scratch); + result = Curl_dyn_addn(&ctx->scratch, + (const char *)h3name.base, h3name.len); + if(!result) + result = Curl_dyn_addn(&ctx->scratch, STRCONST(": ")); + if(!result) + result = Curl_dyn_addn(&ctx->scratch, + (const char *)h3val.base, h3val.len); + if(!result) + result = Curl_dyn_addn(&ctx->scratch, STRCONST("\r\n")); + if(!result) + h3_xfer_write_resp_hd(cf, data, stream, Curl_dyn_ptr(&ctx->scratch), + Curl_dyn_len(&ctx->scratch), FALSE); + } + return 0; +} + +static int cb_h3_stop_sending(nghttp3_conn *conn, int64_t stream_id, + uint64_t app_error_code, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + int rv; + (void)conn; + (void)stream_user_data; + + rv = ngtcp2_conn_shutdown_stream_read(ctx->qconn, 0, stream_id, + app_error_code); + if(rv && rv != NGTCP2_ERR_STREAM_NOT_FOUND) { + return NGTCP2_ERR_CALLBACK_FAILURE; + } + + return 0; +} + +static int cb_h3_reset_stream(nghttp3_conn *conn, int64_t sid, + uint64_t app_error_code, void *user_data, + void *stream_user_data) { + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + curl_int64_t stream_id = (curl_int64_t)sid; + struct Curl_easy *data = stream_user_data; + int rv; + (void)conn; + (void)data; + + rv = ngtcp2_conn_shutdown_stream_write(ctx->qconn, 0, stream_id, + app_error_code); + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] reset -> %d", stream_id, rv); + if(rv && rv != NGTCP2_ERR_STREAM_NOT_FOUND) { + return NGTCP2_ERR_CALLBACK_FAILURE; + } + + return 0; +} + +static nghttp3_callbacks ngh3_callbacks = { + cb_h3_acked_req_body, /* acked_stream_data */ + cb_h3_stream_close, + cb_h3_recv_data, + cb_h3_deferred_consume, + NULL, /* begin_headers */ + cb_h3_recv_header, + cb_h3_end_headers, + NULL, /* begin_trailers */ + cb_h3_recv_header, + NULL, /* end_trailers */ + cb_h3_stop_sending, + NULL, /* end_stream */ + cb_h3_reset_stream, + NULL, /* shutdown */ + NULL /* recv_settings */ +}; + +static int init_ngh3_conn(struct Curl_cfilter *cf) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + CURLcode result; + int rc; + int64_t ctrl_stream_id, qpack_enc_stream_id, qpack_dec_stream_id; + + if(ngtcp2_conn_get_streams_uni_left(ctx->qconn) < 3) { + return CURLE_QUIC_CONNECT_ERROR; + } + + nghttp3_settings_default(&ctx->h3settings); + + rc = nghttp3_conn_client_new(&ctx->h3conn, + &ngh3_callbacks, + &ctx->h3settings, + nghttp3_mem_default(), + cf); + if(rc) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + rc = ngtcp2_conn_open_uni_stream(ctx->qconn, &ctrl_stream_id, NULL); + if(rc) { + result = CURLE_QUIC_CONNECT_ERROR; + goto fail; + } + + rc = nghttp3_conn_bind_control_stream(ctx->h3conn, ctrl_stream_id); + if(rc) { + result = CURLE_QUIC_CONNECT_ERROR; + goto fail; + } + + rc = ngtcp2_conn_open_uni_stream(ctx->qconn, &qpack_enc_stream_id, NULL); + if(rc) { + result = CURLE_QUIC_CONNECT_ERROR; + goto fail; + } + + rc = ngtcp2_conn_open_uni_stream(ctx->qconn, &qpack_dec_stream_id, NULL); + if(rc) { + result = CURLE_QUIC_CONNECT_ERROR; + goto fail; + } + + rc = nghttp3_conn_bind_qpack_streams(ctx->h3conn, qpack_enc_stream_id, + qpack_dec_stream_id); + if(rc) { + result = CURLE_QUIC_CONNECT_ERROR; + goto fail; + } + + return CURLE_OK; +fail: + + return result; +} + +static ssize_t recv_closed_stream(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream, + CURLcode *err) +{ + ssize_t nread = -1; + + (void)cf; + if(stream->reset) { + failf(data, + "HTTP/3 stream %" CURL_PRId64 " reset by server", stream->id); + *err = data->req.bytecount? CURLE_PARTIAL_FILE : CURLE_HTTP3; + goto out; + } + else if(!stream->resp_hds_complete) { + failf(data, + "HTTP/3 stream %" CURL_PRId64 " was closed cleanly, but before " + "getting all response header fields, treated as error", + stream->id); + *err = CURLE_HTTP3; + goto out; + } + *err = CURLE_OK; + nread = 0; + +out: + return nread; +} + +/* incoming data frames on the h3 stream */ +static ssize_t cf_ngtcp2_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t blen, CURLcode *err) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + ssize_t nread = -1; + struct cf_call_data save; + struct pkt_io_ctx pktx; + + (void)ctx; + (void)buf; + + CF_DATA_SAVE(save, cf, data); + DEBUGASSERT(cf->connected); + DEBUGASSERT(ctx); + DEBUGASSERT(ctx->qconn); + DEBUGASSERT(ctx->h3conn); + *err = CURLE_OK; + + pktx_init(&pktx, cf, data); + + if(!stream || ctx->conn_closed) { + *err = CURLE_RECV_ERROR; + goto out; + } + + if(cf_progress_ingress(cf, data, &pktx)) { + *err = CURLE_RECV_ERROR; + nread = -1; + goto out; + } + + if(stream->xfer_result) { + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] xfer write failed", stream->id); + cf_ngtcp2_stream_close(cf, data, stream); + *err = stream->xfer_result; + nread = -1; + goto out; + } + else if(stream->closed) { + nread = recv_closed_stream(cf, data, stream, err); + goto out; + } + *err = CURLE_AGAIN; + nread = -1; + +out: + if(cf_progress_egress(cf, data, &pktx)) { + *err = CURLE_SEND_ERROR; + nread = -1; + } + else { + CURLcode result2 = check_and_set_expiry(cf, data, &pktx); + if(result2) { + *err = result2; + nread = -1; + } + } + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] cf_recv(blen=%zu) -> %zd, %d", + stream? stream->id : -1, blen, nread, *err); + CF_DATA_RESTORE(cf, save); + return nread; +} + +static int cb_h3_acked_req_body(nghttp3_conn *conn, int64_t stream_id, + uint64_t datalen, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + size_t skiplen; + + (void)cf; + if(!stream) + return 0; + /* The server acknowledged `datalen` of bytes from our request body. + * This is a delta. We have kept this data in `sendbuf` for + * re-transmissions and can free it now. */ + if(datalen >= (uint64_t)stream->sendbuf_len_in_flight) + skiplen = stream->sendbuf_len_in_flight; + else + skiplen = (size_t)datalen; + Curl_bufq_skip(&stream->sendbuf, skiplen); + stream->sendbuf_len_in_flight -= skiplen; + + /* Everything ACKed, we resume upload processing */ + if(!stream->sendbuf_len_in_flight) { + int rv = nghttp3_conn_resume_stream(conn, stream_id); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + return NGTCP2_ERR_CALLBACK_FAILURE; + } + } + return 0; +} + +static nghttp3_ssize +cb_h3_read_req_body(nghttp3_conn *conn, int64_t stream_id, + nghttp3_vec *vec, size_t veccnt, + uint32_t *pflags, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + ssize_t nwritten = 0; + size_t nvecs = 0; + (void)cf; + (void)conn; + (void)stream_id; + (void)user_data; + (void)veccnt; + + if(!stream) + return NGHTTP3_ERR_CALLBACK_FAILURE; + /* nghttp3 keeps references to the sendbuf data until it is ACKed + * by the server (see `cb_h3_acked_req_body()` for updates). + * `sendbuf_len_in_flight` is the amount of bytes in `sendbuf` + * that we have already passed to nghttp3, but which have not been + * ACKed yet. + * Any amount beyond `sendbuf_len_in_flight` we need still to pass + * to nghttp3. Do that now, if we can. */ + if(stream->sendbuf_len_in_flight < Curl_bufq_len(&stream->sendbuf)) { + nvecs = 0; + while(nvecs < veccnt && + Curl_bufq_peek_at(&stream->sendbuf, + stream->sendbuf_len_in_flight, + (const unsigned char **)&vec[nvecs].base, + &vec[nvecs].len)) { + stream->sendbuf_len_in_flight += vec[nvecs].len; + nwritten += vec[nvecs].len; + ++nvecs; + } + DEBUGASSERT(nvecs > 0); /* we SHOULD have been be able to peek */ + } + + if(nwritten > 0 && stream->upload_left != -1) + stream->upload_left -= nwritten; + + /* When we stopped sending and everything in `sendbuf` is "in flight", + * we are at the end of the request body. */ + if(stream->upload_left == 0) { + *pflags = NGHTTP3_DATA_FLAG_EOF; + stream->send_closed = TRUE; + } + else if(!nwritten) { + /* Not EOF, and nothing to give, we signal WOULDBLOCK. */ + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] read req body -> AGAIN", + stream->id); + return NGHTTP3_ERR_WOULDBLOCK; + } + + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] read req body -> " + "%d vecs%s with %zu (buffered=%zu, left=%" + CURL_FORMAT_CURL_OFF_T ")", + stream->id, (int)nvecs, + *pflags == NGHTTP3_DATA_FLAG_EOF?" EOF":"", + nwritten, Curl_bufq_len(&stream->sendbuf), + stream->upload_left); + return (nghttp3_ssize)nvecs; +} + +/* Index where :authority header field will appear in request header + field list. */ +#define AUTHORITY_DST_IDX 3 + +static ssize_t h3_stream_open(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *buf, size_t len, + CURLcode *err) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = NULL; + int64_t sid; + struct dynhds h2_headers; + size_t nheader; + nghttp3_nv *nva = NULL; + int rc = 0; + unsigned int i; + ssize_t nwritten = -1; + nghttp3_data_reader reader; + nghttp3_data_reader *preader = NULL; + + Curl_dynhds_init(&h2_headers, 0, DYN_HTTP_REQUEST); + + *err = h3_data_setup(cf, data); + if(*err) + goto out; + stream = H3_STREAM_CTX(ctx, data); + DEBUGASSERT(stream); + if(!stream) { + *err = CURLE_FAILED_INIT; + goto out; + } + + nwritten = Curl_h1_req_parse_read(&stream->h1, buf, len, NULL, 0, err); + if(nwritten < 0) + goto out; + if(!stream->h1.done) { + /* need more data */ + goto out; + } + DEBUGASSERT(stream->h1.req); + + *err = Curl_http_req_to_h2(&h2_headers, stream->h1.req, data); + if(*err) { + nwritten = -1; + goto out; + } + /* no longer needed */ + Curl_h1_req_parse_free(&stream->h1); + + nheader = Curl_dynhds_count(&h2_headers); + nva = malloc(sizeof(nghttp3_nv) * nheader); + if(!nva) { + *err = CURLE_OUT_OF_MEMORY; + nwritten = -1; + goto out; + } + + for(i = 0; i < nheader; ++i) { + struct dynhds_entry *e = Curl_dynhds_getn(&h2_headers, i); + nva[i].name = (unsigned char *)e->name; + nva[i].namelen = e->namelen; + nva[i].value = (unsigned char *)e->value; + nva[i].valuelen = e->valuelen; + nva[i].flags = NGHTTP3_NV_FLAG_NONE; + } + + rc = ngtcp2_conn_open_bidi_stream(ctx->qconn, &sid, data); + if(rc) { + failf(data, "can get bidi streams"); + *err = CURLE_SEND_ERROR; + nwritten = -1; + goto out; + } + stream->id = (curl_int64_t)sid; + ++ctx->used_bidi_streams; + + switch(data->state.httpreq) { + case HTTPREQ_POST: + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + case HTTPREQ_PUT: + /* known request body size or -1 */ + if(data->state.infilesize != -1) + stream->upload_left = data->state.infilesize; + else + /* data sending without specifying the data amount up front */ + stream->upload_left = -1; /* unknown */ + break; + default: + /* there is not request body */ + stream->upload_left = 0; /* no request body */ + break; + } + + stream->send_closed = (stream->upload_left == 0); + if(!stream->send_closed) { + reader.read_data = cb_h3_read_req_body; + preader = &reader; + } + + rc = nghttp3_conn_submit_request(ctx->h3conn, stream->id, + nva, nheader, preader, data); + if(rc) { + switch(rc) { + case NGHTTP3_ERR_CONN_CLOSING: + CURL_TRC_CF(data, cf, "h3sid[%" CURL_PRId64 "] failed to send, " + "connection is closing", stream->id); + break; + default: + CURL_TRC_CF(data, cf, "h3sid[%" CURL_PRId64 "] failed to send -> " + "%d (%s)", stream->id, rc, ngtcp2_strerror(rc)); + break; + } + *err = CURLE_SEND_ERROR; + nwritten = -1; + goto out; + } + + if(Curl_trc_is_verbose(data)) { + infof(data, "[HTTP/3] [%" CURL_PRId64 "] OPENED stream for %s", + stream->id, data->state.url); + for(i = 0; i < nheader; ++i) { + infof(data, "[HTTP/3] [%" CURL_PRId64 "] [%.*s: %.*s]", stream->id, + (int)nva[i].namelen, nva[i].name, + (int)nva[i].valuelen, nva[i].value); + } + } + +out: + free(nva); + Curl_dynhds_free(&h2_headers); + return nwritten; +} + +static ssize_t cf_ngtcp2_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *buf, size_t len, CURLcode *err) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + ssize_t sent = 0; + struct cf_call_data save; + struct pkt_io_ctx pktx; + CURLcode result; + + CF_DATA_SAVE(save, cf, data); + DEBUGASSERT(cf->connected); + DEBUGASSERT(ctx->qconn); + DEBUGASSERT(ctx->h3conn); + pktx_init(&pktx, cf, data); + *err = CURLE_OK; + + result = cf_progress_ingress(cf, data, &pktx); + if(result) { + *err = result; + sent = -1; + } + + if(!stream || stream->id < 0) { + if(ctx->conn_closed) { + CURL_TRC_CF(data, cf, "cannot open stream on closed connection"); + *err = CURLE_SEND_ERROR; + sent = -1; + goto out; + } + sent = h3_stream_open(cf, data, buf, len, err); + if(sent < 0) { + CURL_TRC_CF(data, cf, "failed to open stream -> %d", *err); + goto out; + } + stream = H3_STREAM_CTX(ctx, data); + } + else if(stream->xfer_result) { + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] xfer write failed", stream->id); + cf_ngtcp2_stream_close(cf, data, stream); + *err = stream->xfer_result; + sent = -1; + goto out; + } + else if(stream->upload_blocked_len) { + /* the data in `buf` has already been submitted or added to the + * buffers, but have been EAGAINed on the last invocation. */ + DEBUGASSERT(len >= stream->upload_blocked_len); + if(len < stream->upload_blocked_len) { + /* Did we get called again with a smaller `len`? This should not + * happen. We are not prepared to handle that. */ + failf(data, "HTTP/3 send again with decreased length"); + *err = CURLE_HTTP3; + sent = -1; + goto out; + } + sent = (ssize_t)stream->upload_blocked_len; + stream->upload_blocked_len = 0; + } + else if(stream->closed) { + if(stream->resp_hds_complete) { + /* Server decided to close the stream after having sent us a final + * response. This is valid if it is not interested in the request + * body. This happens on 30x or 40x responses. + * We silently discard the data sent, since this is not a transport + * error situation. */ + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] discarding data" + "on closed stream with response", stream->id); + *err = CURLE_OK; + sent = (ssize_t)len; + goto out; + } + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] send_body(len=%zu) " + "-> stream closed", stream->id, len); + *err = CURLE_HTTP3; + sent = -1; + goto out; + } + else if(ctx->conn_closed) { + CURL_TRC_CF(data, cf, "cannot send on closed connection"); + *err = CURLE_SEND_ERROR; + sent = -1; + goto out; + } + else { + sent = Curl_bufq_write(&stream->sendbuf, buf, len, err); + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] cf_send, add to " + "sendbuf(len=%zu) -> %zd, %d", + stream->id, len, sent, *err); + if(sent < 0) { + goto out; + } + + (void)nghttp3_conn_resume_stream(ctx->h3conn, stream->id); + } + + result = cf_progress_egress(cf, data, &pktx); + if(result) { + *err = result; + sent = -1; + } + + if(stream && sent > 0 && stream->sendbuf_len_in_flight) { + /* We have unacknowledged DATA and cannot report success to our + * caller. Instead we EAGAIN and remember how much we have already + * "written" into our various internal connection buffers. */ + stream->upload_blocked_len = sent; + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] cf_send(len=%zu), " + "%zu bytes in flight -> EGAIN", stream->id, len, + stream->sendbuf_len_in_flight); + *err = CURLE_AGAIN; + sent = -1; + } + +out: + result = check_and_set_expiry(cf, data, &pktx); + if(result) { + *err = result; + sent = -1; + } + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] cf_send(len=%zu) -> %zd, %d", + stream? stream->id : -1, len, sent, *err); + CF_DATA_RESTORE(cf, save); + return sent; +} + +static CURLcode qng_verify_peer(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + + cf->conn->bits.multiplex = TRUE; /* at least potentially multiplexed */ + cf->conn->httpversion = 30; + cf->conn->bundle->multiuse = BUNDLE_MULTIPLEX; + + return Curl_vquic_tls_verify_peer(&ctx->tls, cf, data, &ctx->peer); +} + +static CURLcode recv_pkt(const unsigned char *pkt, size_t pktlen, + struct sockaddr_storage *remote_addr, + socklen_t remote_addrlen, int ecn, + void *userp) +{ + struct pkt_io_ctx *pktx = userp; + struct cf_ngtcp2_ctx *ctx = pktx->cf->ctx; + ngtcp2_pkt_info pi; + ngtcp2_path path; + int rv; + + ++pktx->pkt_count; + ngtcp2_addr_init(&path.local, (struct sockaddr *)&ctx->q.local_addr, + ctx->q.local_addrlen); + ngtcp2_addr_init(&path.remote, (struct sockaddr *)remote_addr, + remote_addrlen); + pi.ecn = (uint8_t)ecn; + + rv = ngtcp2_conn_read_pkt(ctx->qconn, &path, &pi, pkt, pktlen, pktx->ts); + if(rv) { + CURL_TRC_CF(pktx->data, pktx->cf, "ingress, read_pkt -> %s (%d)", + ngtcp2_strerror(rv), rv); + cf_ngtcp2_err_set(pktx->cf, pktx->data, rv); + + if(rv == NGTCP2_ERR_CRYPTO) + /* this is a "TLS problem", but a failed certificate verification + is a common reason for this */ + return CURLE_PEER_FAILED_VERIFICATION; + return CURLE_RECV_ERROR; + } + + return CURLE_OK; +} + +static CURLcode cf_progress_ingress(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct pkt_io_ctx *pktx) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct pkt_io_ctx local_pktx; + size_t pkts_chunk = 128, i; + CURLcode result = CURLE_OK; + + if(!pktx) { + pktx_init(&local_pktx, cf, data); + pktx = &local_pktx; + } + else { + pktx_update_time(pktx, cf); + } + + result = Curl_vquic_tls_before_recv(&ctx->tls, cf, data); + if(result) + return result; + + for(i = 0; i < 4; ++i) { + if(i) + pktx_update_time(pktx, cf); + pktx->pkt_count = 0; + result = vquic_recv_packets(cf, data, &ctx->q, pkts_chunk, + recv_pkt, pktx); + if(result || !pktx->pkt_count) /* error or got nothing */ + break; + } + return result; +} + +/** + * Read a network packet to send from ngtcp2 into `buf`. + * Return number of bytes written or -1 with *err set. + */ +static ssize_t read_pkt_to_send(void *userp, + unsigned char *buf, size_t buflen, + CURLcode *err) +{ + struct pkt_io_ctx *x = userp; + struct cf_ngtcp2_ctx *ctx = x->cf->ctx; + nghttp3_vec vec[16]; + nghttp3_ssize veccnt; + ngtcp2_ssize ndatalen; + uint32_t flags; + int64_t stream_id; + int fin; + ssize_t nwritten, n; + veccnt = 0; + stream_id = -1; + fin = 0; + + /* ngtcp2 may want to put several frames from different streams into + * this packet. `NGTCP2_WRITE_STREAM_FLAG_MORE` tells it to do so. + * When `NGTCP2_ERR_WRITE_MORE` is returned, we *need* to make + * another iteration. + * When ngtcp2 is happy (because it has no other frame that would fit + * or it has nothing more to send), it returns the total length + * of the assembled packet. This may be 0 if there was nothing to send. */ + nwritten = 0; + *err = CURLE_OK; + for(;;) { + + if(ctx->h3conn && ngtcp2_conn_get_max_data_left(ctx->qconn)) { + veccnt = nghttp3_conn_writev_stream(ctx->h3conn, &stream_id, &fin, vec, + sizeof(vec) / sizeof(vec[0])); + if(veccnt < 0) { + failf(x->data, "nghttp3_conn_writev_stream returned error: %s", + nghttp3_strerror((int)veccnt)); + cf_ngtcp2_h3_err_set(x->cf, x->data, (int)veccnt); + *err = CURLE_SEND_ERROR; + return -1; + } + } + + flags = NGTCP2_WRITE_STREAM_FLAG_MORE | + (fin ? NGTCP2_WRITE_STREAM_FLAG_FIN : 0); + n = ngtcp2_conn_writev_stream(ctx->qconn, &x->ps.path, + NULL, buf, buflen, + &ndatalen, flags, stream_id, + (const ngtcp2_vec *)vec, veccnt, x->ts); + if(n == 0) { + /* nothing to send */ + *err = CURLE_AGAIN; + nwritten = -1; + goto out; + } + else if(n < 0) { + switch(n) { + case NGTCP2_ERR_STREAM_DATA_BLOCKED: { + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, x->data); + DEBUGASSERT(ndatalen == -1); + nghttp3_conn_block_stream(ctx->h3conn, stream_id); + CURL_TRC_CF(x->data, x->cf, "[%" CURL_PRId64 "] block quic flow", + (curl_int64_t)stream_id); + DEBUGASSERT(stream); + if(stream) + stream->quic_flow_blocked = TRUE; + n = 0; + break; + } + case NGTCP2_ERR_STREAM_SHUT_WR: + DEBUGASSERT(ndatalen == -1); + nghttp3_conn_shutdown_stream_write(ctx->h3conn, stream_id); + n = 0; + break; + case NGTCP2_ERR_WRITE_MORE: + /* ngtcp2 wants to send more. update the flow of the stream whose data + * is in the buffer and continue */ + DEBUGASSERT(ndatalen >= 0); + n = 0; + break; + default: + DEBUGASSERT(ndatalen == -1); + failf(x->data, "ngtcp2_conn_writev_stream returned error: %s", + ngtcp2_strerror((int)n)); + cf_ngtcp2_err_set(x->cf, x->data, (int)n); + *err = CURLE_SEND_ERROR; + nwritten = -1; + goto out; + } + } + + if(ndatalen >= 0) { + /* we add the amount of data bytes to the flow windows */ + int rv = nghttp3_conn_add_write_offset(ctx->h3conn, stream_id, ndatalen); + if(rv) { + failf(x->data, "nghttp3_conn_add_write_offset returned error: %s\n", + nghttp3_strerror(rv)); + return CURLE_SEND_ERROR; + } + } + + if(n > 0) { + /* packet assembled, leave */ + nwritten = n; + goto out; + } + } +out: + return nwritten; +} + +static CURLcode cf_progress_egress(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct pkt_io_ctx *pktx) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + ssize_t nread; + size_t max_payload_size, path_max_payload_size, max_pktcnt; + size_t pktcnt = 0; + size_t gsolen = 0; /* this disables gso until we have a clue */ + CURLcode curlcode; + struct pkt_io_ctx local_pktx; + + if(!pktx) { + pktx_init(&local_pktx, cf, data); + pktx = &local_pktx; + } + else { + pktx_update_time(pktx, cf); + ngtcp2_path_storage_zero(&pktx->ps); + } + + curlcode = vquic_flush(cf, data, &ctx->q); + if(curlcode) { + if(curlcode == CURLE_AGAIN) { + Curl_expire(data, 1, EXPIRE_QUIC); + return CURLE_OK; + } + return curlcode; + } + + /* In UDP, there is a maximum theoretical packet paload length and + * a minimum payload length that is "guaranteed" to work. + * To detect if this minimum payload can be increased, ngtcp2 sends + * now and then a packet payload larger than the minimum. It that + * is ACKed by the peer, both parties know that it works and + * the subsequent packets can use a larger one. + * This is called PMTUD (Path Maximum Transmission Unit Discovery). + * Since a PMTUD might be rejected right on send, we do not want it + * be followed by other packets of lesser size. Because those would + * also fail then. So, if we detect a PMTUD while buffering, we flush. + */ + max_payload_size = ngtcp2_conn_get_max_tx_udp_payload_size(ctx->qconn); + path_max_payload_size = + ngtcp2_conn_get_path_max_tx_udp_payload_size(ctx->qconn); + /* maximum number of packets buffered before we flush to the socket */ + max_pktcnt = CURLMIN(MAX_PKT_BURST, + ctx->q.sendbuf.chunk_size / max_payload_size); + + for(;;) { + /* add the next packet to send, if any, to our buffer */ + nread = Curl_bufq_sipn(&ctx->q.sendbuf, max_payload_size, + read_pkt_to_send, pktx, &curlcode); + if(nread < 0) { + if(curlcode != CURLE_AGAIN) + return curlcode; + /* Nothing more to add, flush and leave */ + curlcode = vquic_send(cf, data, &ctx->q, gsolen); + if(curlcode) { + if(curlcode == CURLE_AGAIN) { + Curl_expire(data, 1, EXPIRE_QUIC); + return CURLE_OK; + } + return curlcode; + } + goto out; + } + + DEBUGASSERT(nread > 0); + if(pktcnt == 0) { + /* first packet in buffer. This is either of a known, "good" + * payload size or it is a PMTUD. We'll see. */ + gsolen = (size_t)nread; + } + else if((size_t)nread > gsolen || + (gsolen > path_max_payload_size && (size_t)nread != gsolen)) { + /* The just added packet is a PMTUD *or* the one(s) before the + * just added were PMTUD and the last one is smaller. + * Flush the buffer before the last add. */ + curlcode = vquic_send_tail_split(cf, data, &ctx->q, + gsolen, nread, nread); + if(curlcode) { + if(curlcode == CURLE_AGAIN) { + Curl_expire(data, 1, EXPIRE_QUIC); + return CURLE_OK; + } + return curlcode; + } + pktcnt = 0; + continue; + } + + if(++pktcnt >= max_pktcnt || (size_t)nread < gsolen) { + /* Reached MAX_PKT_BURST *or* + * the capacity of our buffer *or* + * last add was shorter than the previous ones, flush */ + curlcode = vquic_send(cf, data, &ctx->q, gsolen); + if(curlcode) { + if(curlcode == CURLE_AGAIN) { + Curl_expire(data, 1, EXPIRE_QUIC); + return CURLE_OK; + } + return curlcode; + } + /* pktbuf has been completely sent */ + pktcnt = 0; + } + } + +out: + return CURLE_OK; +} + +/* + * Called from transfer.c:data_pending to know if we should keep looping + * to receive more data from the connection. + */ +static bool cf_ngtcp2_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + (void)cf; + (void)data; + return FALSE; +} + +static CURLcode h3_data_pause(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool pause) +{ + /* TODO: there seems right now no API in ngtcp2 to shrink/enlarge + * the streams windows. As we do in HTTP/2. */ + if(!pause) { + h3_drain_stream(cf, data); + Curl_expire(data, 0, EXPIRE_RUN_NOW); + } + return CURLE_OK; +} + +static CURLcode cf_ngtcp2_data_event(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + (void)arg1; + (void)arg2; + switch(event) { + case CF_CTRL_DATA_SETUP: + break; + case CF_CTRL_DATA_PAUSE: + result = h3_data_pause(cf, data, (arg1 != 0)); + break; + case CF_CTRL_DATA_DETACH: + h3_data_done(cf, data); + break; + case CF_CTRL_DATA_DONE: + h3_data_done(cf, data); + break; + case CF_CTRL_DATA_DONE_SEND: { + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + if(stream && !stream->send_closed) { + stream->send_closed = TRUE; + stream->upload_left = Curl_bufq_len(&stream->sendbuf); + (void)nghttp3_conn_resume_stream(ctx->h3conn, stream->id); + } + break; + } + case CF_CTRL_DATA_IDLE: { + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURL_TRC_CF(data, cf, "data idle"); + if(stream && !stream->closed) { + result = check_and_set_expiry(cf, data, NULL); + if(result) + CURL_TRC_CF(data, cf, "data idle, check_and_set_expiry -> %d", result); + } + break; + } + default: + break; + } + CF_DATA_RESTORE(cf, save); + return result; +} + +static void cf_ngtcp2_ctx_clear(struct cf_ngtcp2_ctx *ctx) +{ + struct cf_call_data save = ctx->call_data; + + if(ctx->qlogfd != -1) { + close(ctx->qlogfd); + } + Curl_vquic_tls_cleanup(&ctx->tls); + vquic_ctx_free(&ctx->q); + if(ctx->h3conn) + nghttp3_conn_del(ctx->h3conn); + if(ctx->qconn) + ngtcp2_conn_del(ctx->qconn); + Curl_bufcp_free(&ctx->stream_bufcp); + Curl_dyn_free(&ctx->scratch); + Curl_hash_clean(&ctx->streams); + Curl_hash_destroy(&ctx->streams); + Curl_ssl_peer_cleanup(&ctx->peer); + + memset(ctx, 0, sizeof(*ctx)); + ctx->qlogfd = -1; + ctx->call_data = save; +} + +static void cf_ngtcp2_conn_close(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + if(ctx && ctx->qconn && !ctx->conn_closed) { + char buffer[NGTCP2_MAX_UDP_PAYLOAD_SIZE]; + struct pkt_io_ctx pktx; + ngtcp2_ssize rc; + + ctx->conn_closed = TRUE; + pktx_init(&pktx, cf, data); + rc = ngtcp2_conn_write_connection_close(ctx->qconn, NULL, /* path */ + NULL, /* pkt_info */ + (uint8_t *)buffer, sizeof(buffer), + &ctx->last_error, pktx.ts); + CURL_TRC_CF(data, cf, "closing connection(err_type=%d, err_code=%" + CURL_PRIu64 ") -> %d", ctx->last_error.type, + (curl_uint64_t)ctx->last_error.error_code, (int)rc); + if(rc > 0) { + while((send(ctx->q.sockfd, buffer, (SEND_TYPE_ARG3)rc, 0) == -1) && + SOCKERRNO == EINTR); + } + } +} + +static void cf_ngtcp2_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + if(ctx && ctx->qconn) { + cf_ngtcp2_conn_close(cf, data); + cf_ngtcp2_ctx_clear(ctx); + CURL_TRC_CF(data, cf, "close"); + } + cf->connected = FALSE; + CF_DATA_RESTORE(cf, save); +} + +static void cf_ngtcp2_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + CURL_TRC_CF(data, cf, "destroy"); + if(ctx) { + cf_ngtcp2_ctx_clear(ctx); + free(ctx); + } + cf->ctx = NULL; + /* No CF_DATA_RESTORE(cf, save) possible */ + (void)save; +} + +#ifdef USE_OPENSSL +/* The "new session" callback must return zero if the session can be removed + * or non-zero if the session has been put into the session cache. + */ +static int quic_ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid) +{ + struct Curl_cfilter *cf; + struct cf_ngtcp2_ctx *ctx; + struct Curl_easy *data; + ngtcp2_crypto_conn_ref *cref; + + cref = (ngtcp2_crypto_conn_ref *)SSL_get_app_data(ssl); + cf = cref? cref->user_data : NULL; + ctx = cf? cf->ctx : NULL; + data = cf? CF_DATA_CURRENT(cf) : NULL; + if(cf && data && ctx) { + Curl_ossl_add_session(cf, data, &ctx->peer, ssl_sessionid); + return 1; + } + return 0; +} +#endif /* USE_OPENSSL */ + +static CURLcode tls_ctx_setup(struct Curl_cfilter *cf, + struct Curl_easy *data, + void *user_data) +{ + struct curl_tls_ctx *ctx = user_data; + (void)cf; +#ifdef USE_OPENSSL +#if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) + if(ngtcp2_crypto_boringssl_configure_client_context(ctx->ossl.ssl_ctx) + != 0) { + failf(data, "ngtcp2_crypto_boringssl_configure_client_context failed"); + return CURLE_FAILED_INIT; + } +#else + if(ngtcp2_crypto_quictls_configure_client_context(ctx->ossl.ssl_ctx) != 0) { + failf(data, "ngtcp2_crypto_quictls_configure_client_context failed"); + return CURLE_FAILED_INIT; + } +#endif /* !OPENSSL_IS_BORINGSSL && !OPENSSL_IS_AWSLC */ + /* Enable the session cache because it's a prerequisite for the + * "new session" callback. Use the "external storage" mode to prevent + * OpenSSL from creating an internal session cache. + */ + SSL_CTX_set_session_cache_mode(ctx->ossl.ssl_ctx, + SSL_SESS_CACHE_CLIENT | + SSL_SESS_CACHE_NO_INTERNAL); + SSL_CTX_sess_set_new_cb(ctx->ossl.ssl_ctx, quic_ossl_new_session_cb); + +#elif defined(USE_GNUTLS) + if(ngtcp2_crypto_gnutls_configure_client_session(ctx->gtls.session) != 0) { + failf(data, "ngtcp2_crypto_gnutls_configure_client_session failed"); + return CURLE_FAILED_INIT; + } +#elif defined(USE_WOLFSSL) + if(ngtcp2_crypto_wolfssl_configure_client_context(ctx->ssl_ctx) != 0) { + failf(data, "ngtcp2_crypto_wolfssl_configure_client_context failed"); + return CURLE_FAILED_INIT; + } +#endif + return CURLE_OK; +} + +/* + * Might be called twice for happy eyeballs. + */ +static CURLcode cf_connect_start(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct pkt_io_ctx *pktx) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + int rc; + int rv; + CURLcode result; + const struct Curl_sockaddr_ex *sockaddr = NULL; + int qfd; + + ctx->version = NGTCP2_PROTO_VER_MAX; + ctx->max_stream_window = H3_STREAM_WINDOW_SIZE; + ctx->max_idle_ms = CURL_QUIC_MAX_IDLE_MS; + Curl_bufcp_init(&ctx->stream_bufcp, H3_STREAM_CHUNK_SIZE, + H3_STREAM_POOL_SPARES); + Curl_dyn_init(&ctx->scratch, CURL_MAX_HTTP_HEADER); + Curl_hash_offt_init(&ctx->streams, 63, h3_stream_hash_free); + + result = Curl_ssl_peer_init(&ctx->peer, cf, TRNSPRT_QUIC); + if(result) + return result; + +#define H3_ALPN "\x2h3\x5h3-29" + result = Curl_vquic_tls_init(&ctx->tls, cf, data, &ctx->peer, + H3_ALPN, sizeof(H3_ALPN) - 1, + tls_ctx_setup, &ctx->tls, &ctx->conn_ref); + if(result) + return result; + +#ifdef USE_OPENSSL + SSL_set_quic_use_legacy_codepoint(ctx->tls.ossl.ssl, 0); +#endif + + ctx->dcid.datalen = NGTCP2_MAX_CIDLEN; + result = Curl_rand(data, ctx->dcid.data, NGTCP2_MAX_CIDLEN); + if(result) + return result; + + ctx->scid.datalen = NGTCP2_MAX_CIDLEN; + result = Curl_rand(data, ctx->scid.data, NGTCP2_MAX_CIDLEN); + if(result) + return result; + + (void)Curl_qlogdir(data, ctx->scid.data, NGTCP2_MAX_CIDLEN, &qfd); + ctx->qlogfd = qfd; /* -1 if failure above */ + quic_settings(ctx, data, pktx); + + result = vquic_ctx_init(&ctx->q); + if(result) + return result; + + Curl_cf_socket_peek(cf->next, data, &ctx->q.sockfd, &sockaddr, NULL); + if(!sockaddr) + return CURLE_QUIC_CONNECT_ERROR; + ctx->q.local_addrlen = sizeof(ctx->q.local_addr); + rv = getsockname(ctx->q.sockfd, (struct sockaddr *)&ctx->q.local_addr, + &ctx->q.local_addrlen); + if(rv == -1) + return CURLE_QUIC_CONNECT_ERROR; + + ngtcp2_addr_init(&ctx->connected_path.local, + (struct sockaddr *)&ctx->q.local_addr, + ctx->q.local_addrlen); + ngtcp2_addr_init(&ctx->connected_path.remote, + &sockaddr->sa_addr, sockaddr->addrlen); + + rc = ngtcp2_conn_client_new(&ctx->qconn, &ctx->dcid, &ctx->scid, + &ctx->connected_path, + NGTCP2_PROTO_VER_V1, &ng_callbacks, + &ctx->settings, &ctx->transport_params, + NULL, cf); + if(rc) + return CURLE_QUIC_CONNECT_ERROR; + +#ifdef USE_OPENSSL + ngtcp2_conn_set_tls_native_handle(ctx->qconn, ctx->tls.ossl.ssl); +#elif defined(USE_GNUTLS) + ngtcp2_conn_set_tls_native_handle(ctx->qconn, ctx->tls.gtls.session); +#else + ngtcp2_conn_set_tls_native_handle(ctx->qconn, ctx->tls.ssl); +#endif + + ngtcp2_ccerr_default(&ctx->last_error); + + ctx->conn_ref.get_conn = get_conn; + ctx->conn_ref.user_data = cf; + + return CURLE_OK; +} + +static CURLcode cf_ngtcp2_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + struct cf_call_data save; + struct curltime now; + struct pkt_io_ctx pktx; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + /* Connect the UDP filter first */ + if(!cf->next->connected) { + result = Curl_conn_cf_connect(cf->next, data, blocking, done); + if(result || !*done) + return result; + } + + *done = FALSE; + now = Curl_now(); + pktx_init(&pktx, cf, data); + + CF_DATA_SAVE(save, cf, data); + + if(ctx->reconnect_at.tv_sec && Curl_timediff(now, ctx->reconnect_at) < 0) { + /* Not time yet to attempt the next connect */ + CURL_TRC_CF(data, cf, "waiting for reconnect time"); + goto out; + } + + if(!ctx->qconn) { + ctx->started_at = now; + result = cf_connect_start(cf, data, &pktx); + if(result) + goto out; + result = cf_progress_egress(cf, data, &pktx); + /* we do not expect to be able to recv anything yet */ + goto out; + } + + result = cf_progress_ingress(cf, data, &pktx); + if(result) + goto out; + + result = cf_progress_egress(cf, data, &pktx); + if(result) + goto out; + + if(ngtcp2_conn_get_handshake_completed(ctx->qconn)) { + ctx->handshake_at = now; + CURL_TRC_CF(data, cf, "handshake complete after %dms", + (int)Curl_timediff(now, ctx->started_at)); + result = qng_verify_peer(cf, data); + if(!result) { + CURL_TRC_CF(data, cf, "peer verified"); + cf->connected = TRUE; + cf->conn->alpn = CURL_HTTP_VERSION_3; + *done = TRUE; + connkeep(cf->conn, "HTTP/3 default"); + } + } + +out: + if(result == CURLE_RECV_ERROR && ctx->qconn && + ngtcp2_conn_in_draining_period(ctx->qconn)) { + /* When a QUIC server instance is shutting down, it may send us a + * CONNECTION_CLOSE right away. Our connection then enters the DRAINING + * state. The CONNECT may work in the near future again. Indicate + * that as a "weird" reply. */ + result = CURLE_WEIRD_SERVER_REPLY; + } + +#ifndef CURL_DISABLE_VERBOSE_STRINGS + if(result) { + struct ip_quadruple ip; + + Curl_cf_socket_peek(cf->next, data, NULL, NULL, &ip); + infof(data, "QUIC connect to %s port %u failed: %s", + ip.remote_ip, ip.remote_port, curl_easy_strerror(result)); + } +#endif + if(!result && ctx->qconn) { + result = check_and_set_expiry(cf, data, &pktx); + } + if(result || *done) + CURL_TRC_CF(data, cf, "connect -> %d, done=%d", result, *done); + CF_DATA_RESTORE(cf, save); + return result; +} + +static CURLcode cf_ngtcp2_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct cf_call_data save; + + switch(query) { + case CF_QUERY_MAX_CONCURRENT: { + DEBUGASSERT(pres1); + CF_DATA_SAVE(save, cf, data); + /* Set after transport params arrived and continually updated + * by callback. QUIC counts the number over the lifetime of the + * connection, ever increasing. + * We count the *open* transfers plus the budget for new ones. */ + if(!ctx->qconn || ctx->conn_closed) { + *pres1 = 0; + } + else if(ctx->max_bidi_streams) { + uint64_t avail_bidi_streams = 0; + uint64_t max_streams = CONN_INUSE(cf->conn); + if(ctx->max_bidi_streams > ctx->used_bidi_streams) + avail_bidi_streams = ctx->max_bidi_streams - ctx->used_bidi_streams; + max_streams += avail_bidi_streams; + *pres1 = (max_streams > INT_MAX)? INT_MAX : (int)max_streams; + } + else /* transport params not arrived yet? take our default. */ + *pres1 = Curl_multi_max_concurrent_streams(data->multi); + CURL_TRC_CF(data, cf, "query conn[%" CURL_FORMAT_CURL_OFF_T "]: " + "MAX_CONCURRENT -> %d (%zu in use)", + cf->conn->connection_id, *pres1, CONN_INUSE(cf->conn)); + CF_DATA_RESTORE(cf, save); + return CURLE_OK; + } + case CF_QUERY_CONNECT_REPLY_MS: + if(ctx->q.got_first_byte) { + timediff_t ms = Curl_timediff(ctx->q.first_byte_at, ctx->started_at); + *pres1 = (ms < INT_MAX)? (int)ms : INT_MAX; + } + else + *pres1 = -1; + return CURLE_OK; + case CF_QUERY_TIMER_CONNECT: { + struct curltime *when = pres2; + if(ctx->q.got_first_byte) + *when = ctx->q.first_byte_at; + return CURLE_OK; + } + case CF_QUERY_TIMER_APPCONNECT: { + struct curltime *when = pres2; + if(cf->connected) + *when = ctx->handshake_at; + return CURLE_OK; + } + default: + break; + } + return cf->next? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +static bool cf_ngtcp2_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + bool alive = FALSE; + const ngtcp2_transport_params *rp; + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + *input_pending = FALSE; + if(!ctx->qconn || ctx->conn_closed) + goto out; + + /* Both sides of the QUIC connection announce they max idle times in + * the transport parameters. Look at the minimum of both and if + * we exceed this, regard the connection as dead. The other side + * may have completely purged it and will no longer respond + * to any packets from us. */ + rp = ngtcp2_conn_get_remote_transport_params(ctx->qconn); + if(rp) { + timediff_t idletime; + uint64_t idle_ms = ctx->max_idle_ms; + + if(rp->max_idle_timeout && + (rp->max_idle_timeout / NGTCP2_MILLISECONDS) < idle_ms) + idle_ms = (rp->max_idle_timeout / NGTCP2_MILLISECONDS); + idletime = Curl_timediff(Curl_now(), ctx->q.last_io); + if(idletime > 0 && (uint64_t)idletime > idle_ms) + goto out; + } + + if(!cf->next || !cf->next->cft->is_alive(cf->next, data, input_pending)) + goto out; + + alive = TRUE; + if(*input_pending) { + CURLcode result; + /* This happens before we've sent off a request and the connection is + not in use by any other transfer, there shouldn't be any data here, + only "protocol frames" */ + *input_pending = FALSE; + result = cf_progress_ingress(cf, data, NULL); + CURL_TRC_CF(data, cf, "is_alive, progress ingress -> %d", result); + alive = result? FALSE : TRUE; + } + +out: + CF_DATA_RESTORE(cf, save); + return alive; +} + +struct Curl_cftype Curl_cft_http3 = { + "HTTP/3", + CF_TYPE_IP_CONNECT | CF_TYPE_SSL | CF_TYPE_MULTIPLEX, + 0, + cf_ngtcp2_destroy, + cf_ngtcp2_connect, + cf_ngtcp2_close, + Curl_cf_def_get_host, + cf_ngtcp2_adjust_pollset, + cf_ngtcp2_data_pending, + cf_ngtcp2_send, + cf_ngtcp2_recv, + cf_ngtcp2_data_event, + cf_ngtcp2_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_ngtcp2_query, +}; + +CURLcode Curl_cf_ngtcp2_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai) +{ + struct cf_ngtcp2_ctx *ctx = NULL; + struct Curl_cfilter *cf = NULL, *udp_cf = NULL; + CURLcode result; + + (void)data; + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + ctx->qlogfd = -1; + cf_ngtcp2_ctx_clear(ctx); + + result = Curl_cf_create(&cf, &Curl_cft_http3, ctx); + if(result) + goto out; + + result = Curl_cf_udp_create(&udp_cf, data, conn, ai, TRNSPRT_QUIC); + if(result) + goto out; + + cf->conn = conn; + udp_cf->conn = cf->conn; + udp_cf->sockindex = cf->sockindex; + cf->next = udp_cf; + +out: + *pcf = (!result)? cf : NULL; + if(result) { + if(udp_cf) + Curl_conn_cf_discard_sub(cf, udp_cf, data, TRUE); + Curl_safefree(cf); + Curl_safefree(ctx); + } + return result; +} + +bool Curl_conn_is_ngtcp2(const struct Curl_easy *data, + const struct connectdata *conn, + int sockindex) +{ + struct Curl_cfilter *cf = conn? conn->cfilter[sockindex] : NULL; + + (void)data; + for(; cf; cf = cf->next) { + if(cf->cft == &Curl_cft_http3) + return TRUE; + if(cf->cft->flags & CF_TYPE_IP_CONNECT) + return FALSE; + } + return FALSE; +} + +#endif diff --git a/third_party/curl/lib/vquic/curl_ngtcp2.h b/third_party/curl/lib/vquic/curl_ngtcp2.h new file mode 100644 index 0000000..db3e611 --- /dev/null +++ b/third_party/curl/lib/vquic/curl_ngtcp2.h @@ -0,0 +1,61 @@ +#ifndef HEADER_CURL_VQUIC_CURL_NGTCP2_H +#define HEADER_CURL_VQUIC_CURL_NGTCP2_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_NGTCP2) && defined(USE_NGHTTP3) + +#ifdef HAVE_NETINET_UDP_H +#include +#endif + +#include +#include +#ifdef USE_OPENSSL +#include +#elif defined(USE_WOLFSSL) +#include +#include +#include +#endif + +struct Curl_cfilter; + +#include "urldata.h" + +void Curl_ngtcp2_ver(char *p, size_t len); + +CURLcode Curl_cf_ngtcp2_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai); + +bool Curl_conn_is_ngtcp2(const struct Curl_easy *data, + const struct connectdata *conn, + int sockindex); +#endif + +#endif /* HEADER_CURL_VQUIC_CURL_NGTCP2_H */ diff --git a/third_party/curl/lib/vquic/curl_osslq.c b/third_party/curl/lib/vquic/curl_osslq.c new file mode 100644 index 0000000..8b9e889 --- /dev/null +++ b/third_party/curl/lib/vquic/curl_osslq.c @@ -0,0 +1,2332 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_OPENSSL_QUIC) && defined(USE_NGHTTP3) + +#include +#include +#include +#include + +#include "urldata.h" +#include "hash.h" +#include "sendf.h" +#include "strdup.h" +#include "rand.h" +#include "multiif.h" +#include "strcase.h" +#include "cfilters.h" +#include "cf-socket.h" +#include "connect.h" +#include "progress.h" +#include "strerror.h" +#include "dynbuf.h" +#include "http1.h" +#include "select.h" +#include "inet_pton.h" +#include "vquic.h" +#include "vquic_int.h" +#include "vquic-tls.h" +#include "vtls/keylog.h" +#include "vtls/vtls.h" +#include "vtls/openssl.h" +#include "curl_osslq.h" + +#include "warnless.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* A stream window is the maximum amount we need to buffer for + * each active transfer. We use HTTP/3 flow control and only ACK + * when we take things out of the buffer. + * Chunk size is large enough to take a full DATA frame */ +#define H3_STREAM_WINDOW_SIZE (128 * 1024) +#define H3_STREAM_CHUNK_SIZE (16 * 1024) +/* The pool keeps spares around and half of a full stream window + * seems good. More does not seem to improve performance. + * The benefit of the pool is that stream buffer to not keep + * spares. So memory consumption goes down when streams run empty, + * have a large upload done, etc. */ +#define H3_STREAM_POOL_SPARES \ + (H3_STREAM_WINDOW_SIZE / H3_STREAM_CHUNK_SIZE ) / 2 +/* Receive and Send max number of chunks just follows from the + * chunk size and window size */ +#define H3_STREAM_RECV_CHUNKS \ + (H3_STREAM_WINDOW_SIZE / H3_STREAM_CHUNK_SIZE) +#define H3_STREAM_SEND_CHUNKS \ + (H3_STREAM_WINDOW_SIZE / H3_STREAM_CHUNK_SIZE) + +#ifndef ARRAYSIZE +#define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) +#endif + +#if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) +typedef uint32_t sslerr_t; +#else +typedef unsigned long sslerr_t; +#endif + + +/* How to access `call_data` from a cf_osslq filter */ +#undef CF_CTX_CALL_DATA +#define CF_CTX_CALL_DATA(cf) \ + ((struct cf_osslq_ctx *)(cf)->ctx)->call_data + +static CURLcode cf_progress_ingress(struct Curl_cfilter *cf, + struct Curl_easy *data); + +static const char *osslq_SSL_ERROR_to_str(int err) +{ + switch(err) { + case SSL_ERROR_NONE: + return "SSL_ERROR_NONE"; + case SSL_ERROR_SSL: + return "SSL_ERROR_SSL"; + case SSL_ERROR_WANT_READ: + return "SSL_ERROR_WANT_READ"; + case SSL_ERROR_WANT_WRITE: + return "SSL_ERROR_WANT_WRITE"; + case SSL_ERROR_WANT_X509_LOOKUP: + return "SSL_ERROR_WANT_X509_LOOKUP"; + case SSL_ERROR_SYSCALL: + return "SSL_ERROR_SYSCALL"; + case SSL_ERROR_ZERO_RETURN: + return "SSL_ERROR_ZERO_RETURN"; + case SSL_ERROR_WANT_CONNECT: + return "SSL_ERROR_WANT_CONNECT"; + case SSL_ERROR_WANT_ACCEPT: + return "SSL_ERROR_WANT_ACCEPT"; +#if defined(SSL_ERROR_WANT_ASYNC) + case SSL_ERROR_WANT_ASYNC: + return "SSL_ERROR_WANT_ASYNC"; +#endif +#if defined(SSL_ERROR_WANT_ASYNC_JOB) + case SSL_ERROR_WANT_ASYNC_JOB: + return "SSL_ERROR_WANT_ASYNC_JOB"; +#endif +#if defined(SSL_ERROR_WANT_EARLY) + case SSL_ERROR_WANT_EARLY: + return "SSL_ERROR_WANT_EARLY"; +#endif + default: + return "SSL_ERROR unknown"; + } +} + +/* Return error string for last OpenSSL error */ +static char *osslq_strerror(unsigned long error, char *buf, size_t size) +{ + DEBUGASSERT(size); + *buf = '\0'; + +#if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) + ERR_error_string_n((uint32_t)error, buf, size); +#else + ERR_error_string_n(error, buf, size); +#endif + + if(!*buf) { + const char *msg = error ? "Unknown error" : "No error"; + if(strlen(msg) < size) + strcpy(buf, msg); + } + + return buf; +} + +static CURLcode make_bio_addr(BIO_ADDR **pbio_addr, + const struct Curl_sockaddr_ex *addr) +{ + BIO_ADDR *ba; + CURLcode result = CURLE_FAILED_INIT; + + ba = BIO_ADDR_new(); + if(!ba) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + switch(addr->family) { + case AF_INET: { + struct sockaddr_in * const sin = + (struct sockaddr_in * const)(void *)&addr->sa_addr; + if(!BIO_ADDR_rawmake(ba, AF_INET, &sin->sin_addr, + sizeof(sin->sin_addr), sin->sin_port)) { + goto out; + } + result = CURLE_OK; + break; + } +#ifdef USE_IPV6 + case AF_INET6: { + struct sockaddr_in6 * const sin = + (struct sockaddr_in6 * const)(void *)&addr->sa_addr; + if(!BIO_ADDR_rawmake(ba, AF_INET6, &sin->sin6_addr, + sizeof(sin->sin6_addr), sin->sin6_port)) { + } + result = CURLE_OK; + break; + } +#endif /* USE_IPV6 */ + default: + /* sunsupported */ + DEBUGASSERT(0); + break; + } + +out: + if(result && ba) { + BIO_ADDR_free(ba); + ba = NULL; + } + *pbio_addr = ba; + return result; +} + +/* QUIC stream (not necessarily H3) */ +struct cf_osslq_stream { + curl_int64_t id; + SSL *ssl; + struct bufq recvbuf; /* QUIC war data recv buffer */ + BIT(recvd_eos); + BIT(closed); + BIT(reset); + BIT(send_blocked); +}; + +static CURLcode cf_osslq_stream_open(struct cf_osslq_stream *s, + SSL *conn, + uint64_t flags, + struct bufc_pool *bufcp, + void *user_data) +{ + DEBUGASSERT(!s->ssl); + Curl_bufq_initp(&s->recvbuf, bufcp, 1, BUFQ_OPT_NONE); + s->ssl = SSL_new_stream(conn, flags); + if(!s->ssl) { + return CURLE_FAILED_INIT; + } + s->id = SSL_get_stream_id(s->ssl); + SSL_set_app_data(s->ssl, user_data); + return CURLE_OK; +} + +static void cf_osslq_stream_cleanup(struct cf_osslq_stream *s) +{ + if(s->ssl) { + SSL_set_app_data(s->ssl, NULL); + SSL_free(s->ssl); + } + Curl_bufq_free(&s->recvbuf); + memset(s, 0, sizeof(*s)); +} + +static void cf_osslq_stream_close(struct cf_osslq_stream *s) +{ + if(s->ssl) { + SSL_free(s->ssl); + s->ssl = NULL; + } +} + +struct cf_osslq_h3conn { + nghttp3_conn *conn; + nghttp3_settings settings; + struct cf_osslq_stream s_ctrl; + struct cf_osslq_stream s_qpack_enc; + struct cf_osslq_stream s_qpack_dec; + struct cf_osslq_stream remote_ctrl[3]; /* uni streams opened by the peer */ + size_t remote_ctrl_n; /* number of peer streams opened */ +}; + +static void cf_osslq_h3conn_cleanup(struct cf_osslq_h3conn *h3) +{ + size_t i; + + if(h3->conn) + nghttp3_conn_del(h3->conn); + cf_osslq_stream_cleanup(&h3->s_ctrl); + cf_osslq_stream_cleanup(&h3->s_qpack_enc); + cf_osslq_stream_cleanup(&h3->s_qpack_dec); + for(i = 0; i < h3->remote_ctrl_n; ++i) { + cf_osslq_stream_cleanup(&h3->remote_ctrl[i]); + } +} + +struct cf_osslq_ctx { + struct cf_quic_ctx q; + struct ssl_peer peer; + struct curl_tls_ctx tls; + struct cf_call_data call_data; + struct cf_osslq_h3conn h3; + struct curltime started_at; /* time the current attempt started */ + struct curltime handshake_at; /* time connect handshake finished */ + struct curltime first_byte_at; /* when first byte was recvd */ + struct curltime reconnect_at; /* time the next attempt should start */ + struct bufc_pool stream_bufcp; /* chunk pool for streams */ + struct Curl_hash streams; /* hash `data->id` to `h3_stream_ctx` */ + size_t max_stream_window; /* max flow window for one stream */ + uint64_t max_idle_ms; /* max idle time for QUIC connection */ + BIT(got_first_byte); /* if first byte was received */ +#ifdef USE_OPENSSL + BIT(x509_store_setup); /* if x509 store has been set up */ + BIT(protocol_shutdown); /* QUIC connection is shut down */ +#endif +}; + +static void cf_osslq_ctx_clear(struct cf_osslq_ctx *ctx) +{ + struct cf_call_data save = ctx->call_data; + + cf_osslq_h3conn_cleanup(&ctx->h3); + Curl_vquic_tls_cleanup(&ctx->tls); + vquic_ctx_free(&ctx->q); + Curl_bufcp_free(&ctx->stream_bufcp); + Curl_hash_clean(&ctx->streams); + Curl_hash_destroy(&ctx->streams); + Curl_ssl_peer_cleanup(&ctx->peer); + + memset(ctx, 0, sizeof(*ctx)); + ctx->call_data = save; +} + +static void cf_osslq_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + if(ctx && ctx->tls.ossl.ssl) { + /* TODO: send connection close */ + CURL_TRC_CF(data, cf, "cf_osslq_close()"); + cf_osslq_ctx_clear(ctx); + } + + cf->connected = FALSE; + CF_DATA_RESTORE(cf, save); +} + +static void cf_osslq_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + CURL_TRC_CF(data, cf, "destroy"); + if(ctx) { + CURL_TRC_CF(data, cf, "cf_osslq_destroy()"); + cf_osslq_ctx_clear(ctx); + free(ctx); + } + cf->ctx = NULL; + /* No CF_DATA_RESTORE(cf, save) possible */ + (void)save; +} + +static CURLcode cf_osslq_h3conn_add_stream(struct cf_osslq_h3conn *h3, + SSL *stream_ssl, + struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + int64_t stream_id = SSL_get_stream_id(stream_ssl); + + if(h3->remote_ctrl_n >= ARRAYSIZE(h3->remote_ctrl)) { + /* rejected, we are full */ + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] rejecting remote stream", + (curl_int64_t)stream_id); + SSL_free(stream_ssl); + return CURLE_FAILED_INIT; + } + switch(SSL_get_stream_type(stream_ssl)) { + case SSL_STREAM_TYPE_READ: { + struct cf_osslq_stream *nstream = &h3->remote_ctrl[h3->remote_ctrl_n++]; + nstream->id = stream_id; + nstream->ssl = stream_ssl; + Curl_bufq_initp(&nstream->recvbuf, &ctx->stream_bufcp, 1, BUFQ_OPT_NONE); + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] accepted remote uni stream", + (curl_int64_t)stream_id); + break; + } + default: + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] reject remote non-uni-read" + " stream", (curl_int64_t)stream_id); + SSL_free(stream_ssl); + return CURLE_FAILED_INIT; + } + return CURLE_OK; + +} + +static CURLcode cf_osslq_ssl_err(struct Curl_cfilter *cf, + struct Curl_easy *data, + int detail, CURLcode def_result) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + CURLcode result = def_result; + sslerr_t errdetail; + char ebuf[256] = "unknown"; + const char *err_descr = ebuf; + long lerr; + int lib; + int reason; + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + + errdetail = ERR_get_error(); + lib = ERR_GET_LIB(errdetail); + reason = ERR_GET_REASON(errdetail); + + if((lib == ERR_LIB_SSL) && + ((reason == SSL_R_CERTIFICATE_VERIFY_FAILED) || + (reason == SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED))) { + result = CURLE_PEER_FAILED_VERIFICATION; + + lerr = SSL_get_verify_result(ctx->tls.ossl.ssl); + if(lerr != X509_V_OK) { + ssl_config->certverifyresult = lerr; + msnprintf(ebuf, sizeof(ebuf), + "SSL certificate problem: %s", + X509_verify_cert_error_string(lerr)); + } + else + err_descr = "SSL certificate verification failed"; + } +#if defined(SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED) + /* SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED is only available on + OpenSSL version above v1.1.1, not LibreSSL, BoringSSL, or AWS-LC */ + else if((lib == ERR_LIB_SSL) && + (reason == SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED)) { + /* If client certificate is required, communicate the + error to client */ + result = CURLE_SSL_CLIENTCERT; + osslq_strerror(errdetail, ebuf, sizeof(ebuf)); + } +#endif + else if((lib == ERR_LIB_SSL) && (reason == SSL_R_PROTOCOL_IS_SHUTDOWN)) { + ctx->protocol_shutdown = TRUE; + err_descr = "QUIC connection has been shut down"; + result = def_result; + } + else { + result = def_result; + osslq_strerror(errdetail, ebuf, sizeof(ebuf)); + } + + /* detail is already set to the SSL error above */ + + /* If we e.g. use SSLv2 request-method and the server doesn't like us + * (RST connection, etc.), OpenSSL gives no explanation whatsoever and + * the SO_ERROR is also lost. + */ + if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) { + char extramsg[80]=""; + int sockerr = SOCKERRNO; + struct ip_quadruple ip; + + Curl_cf_socket_peek(cf->next, data, NULL, NULL, &ip); + if(sockerr && detail == SSL_ERROR_SYSCALL) + Curl_strerror(sockerr, extramsg, sizeof(extramsg)); + failf(data, "QUIC connect: %s in connection to %s:%d (%s)", + extramsg[0] ? extramsg : osslq_SSL_ERROR_to_str(detail), + ctx->peer.dispname, ip.remote_port, ip.remote_ip); + } + else { + /* Could be a CERT problem */ + failf(data, "%s", err_descr); + } + return result; +} + +static CURLcode cf_osslq_verify_peer(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + + cf->conn->bits.multiplex = TRUE; /* at least potentially multiplexed */ + cf->conn->httpversion = 30; + cf->conn->bundle->multiuse = BUNDLE_MULTIPLEX; + + return Curl_vquic_tls_verify_peer(&ctx->tls, cf, data, &ctx->peer); +} + +/** + * All about the H3 internals of a stream + */ +struct h3_stream_ctx { + struct cf_osslq_stream s; + struct bufq sendbuf; /* h3 request body */ + struct bufq recvbuf; /* h3 response body */ + struct h1_req_parser h1; /* h1 request parsing */ + size_t sendbuf_len_in_flight; /* sendbuf amount "in flight" */ + size_t upload_blocked_len; /* the amount written last and EGAINed */ + size_t recv_buf_nonflow; /* buffered bytes, not counting for flow control */ + curl_uint64_t error3; /* HTTP/3 stream error code */ + curl_off_t upload_left; /* number of request bytes left to upload */ + curl_off_t download_recvd; /* number of response DATA bytes received */ + int status_code; /* HTTP status code */ + bool resp_hds_complete; /* we have a complete, final response */ + bool closed; /* TRUE on stream close */ + bool reset; /* TRUE on stream reset */ + bool send_closed; /* stream is local closed */ + BIT(quic_flow_blocked); /* stream is blocked by QUIC flow control */ +}; + +#define H3_STREAM_CTX(ctx,data) ((struct h3_stream_ctx *)(\ + data? Curl_hash_offt_get(&(ctx)->streams, (data)->id) : NULL)) + +static void h3_stream_ctx_free(struct h3_stream_ctx *stream) +{ + cf_osslq_stream_cleanup(&stream->s); + Curl_bufq_free(&stream->sendbuf); + Curl_bufq_free(&stream->recvbuf); + Curl_h1_req_parse_free(&stream->h1); + free(stream); +} + +static void h3_stream_hash_free(void *stream) +{ + DEBUGASSERT(stream); + h3_stream_ctx_free((struct h3_stream_ctx *)stream); +} + +static CURLcode h3_data_setup(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + if(!data || !data->req.p.http) { + failf(data, "initialization failure, transfer not http initialized"); + return CURLE_FAILED_INIT; + } + + if(stream) + return CURLE_OK; + + stream = calloc(1, sizeof(*stream)); + if(!stream) + return CURLE_OUT_OF_MEMORY; + + stream->s.id = -1; + /* on send, we control how much we put into the buffer */ + Curl_bufq_initp(&stream->sendbuf, &ctx->stream_bufcp, + H3_STREAM_SEND_CHUNKS, BUFQ_OPT_NONE); + stream->sendbuf_len_in_flight = 0; + /* on recv, we need a flexible buffer limit since we also write + * headers to it that are not counted against the nghttp3 flow limits. */ + Curl_bufq_initp(&stream->recvbuf, &ctx->stream_bufcp, + H3_STREAM_RECV_CHUNKS, BUFQ_OPT_SOFT_LIMIT); + stream->recv_buf_nonflow = 0; + Curl_h1_req_parse_init(&stream->h1, H1_PARSE_DEFAULT_MAX_LINE_LEN); + + if(!Curl_hash_offt_set(&ctx->streams, data->id, stream)) { + h3_stream_ctx_free(stream); + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} + +static void h3_data_done(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + (void)cf; + if(stream) { + CURL_TRC_CF(data, cf, "[%"CURL_PRId64"] easy handle is done", + stream->s.id); + if(ctx->h3.conn && !stream->closed) { + nghttp3_conn_shutdown_stream_read(ctx->h3.conn, stream->s.id); + nghttp3_conn_close_stream(ctx->h3.conn, stream->s.id, + NGHTTP3_H3_REQUEST_CANCELLED); + nghttp3_conn_set_stream_user_data(ctx->h3.conn, stream->s.id, NULL); + stream->closed = TRUE; + } + + Curl_hash_offt_remove(&ctx->streams, data->id); + } +} + +static struct cf_osslq_stream *cf_osslq_get_qstream(struct Curl_cfilter *cf, + struct Curl_easy *data, + int64_t stream_id) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + struct Curl_easy *sdata; + + if(stream && stream->s.id == stream_id) { + return &stream->s; + } + else if(ctx->h3.s_ctrl.id == stream_id) { + return &ctx->h3.s_ctrl; + } + else if(ctx->h3.s_qpack_enc.id == stream_id) { + return &ctx->h3.s_qpack_enc; + } + else if(ctx->h3.s_qpack_dec.id == stream_id) { + return &ctx->h3.s_qpack_dec; + } + else { + DEBUGASSERT(data->multi); + for(sdata = data->multi->easyp; sdata; sdata = sdata->next) { + if(sdata->conn != data->conn) + continue; + stream = H3_STREAM_CTX(ctx, sdata); + if(stream && stream->s.id == stream_id) { + return &stream->s; + } + } + } + return NULL; +} + +static void h3_drain_stream(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + unsigned char bits; + + (void)cf; + bits = CURL_CSELECT_IN; + if(stream && stream->upload_left && !stream->send_closed) + bits |= CURL_CSELECT_OUT; + if(data->state.select_bits != bits) { + data->state.select_bits = bits; + Curl_expire(data, 0, EXPIRE_RUN_NOW); + } +} + +static CURLcode h3_data_pause(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool pause) +{ + if(!pause) { + /* unpaused. make it run again right away */ + h3_drain_stream(cf, data); + Curl_expire(data, 0, EXPIRE_RUN_NOW); + } + return CURLE_OK; +} + +static int cb_h3_stream_close(nghttp3_conn *conn, int64_t stream_id, + uint64_t app_error_code, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_osslq_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + (void)conn; + (void)stream_id; + + /* we might be called by nghttp3 after we already cleaned up */ + if(!stream) + return 0; + + stream->closed = TRUE; + stream->error3 = app_error_code; + if(stream->error3 != NGHTTP3_H3_NO_ERROR) { + stream->reset = TRUE; + stream->send_closed = TRUE; + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] RESET: error %" CURL_PRIu64, + stream->s.id, stream->error3); + } + else { + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] CLOSED", stream->s.id); + } + h3_drain_stream(cf, data); + return 0; +} + +/* + * write_resp_raw() copies response data in raw format to the `data`'s + * receive buffer. If not enough space is available, it appends to the + * `data`'s overflow buffer. + */ +static CURLcode write_resp_raw(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *mem, size_t memlen, + bool flow) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURLcode result = CURLE_OK; + ssize_t nwritten; + + (void)cf; + if(!stream) { + return CURLE_RECV_ERROR; + } + nwritten = Curl_bufq_write(&stream->recvbuf, mem, memlen, &result); + if(nwritten < 0) { + return result; + } + + if(!flow) + stream->recv_buf_nonflow += (size_t)nwritten; + + if((size_t)nwritten < memlen) { + /* This MUST not happen. Our recbuf is dimensioned to hold the + * full max_stream_window and then some for this very reason. */ + DEBUGASSERT(0); + return CURLE_RECV_ERROR; + } + return result; +} + +static int cb_h3_recv_data(nghttp3_conn *conn, int64_t stream3_id, + const uint8_t *buf, size_t buflen, + void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_osslq_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURLcode result; + + (void)conn; + (void)stream3_id; + + if(!stream) + return NGHTTP3_ERR_CALLBACK_FAILURE; + + result = write_resp_raw(cf, data, buf, buflen, TRUE); + if(result) { + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] DATA len=%zu, ERROR %d", + stream->s.id, buflen, result); + return NGHTTP3_ERR_CALLBACK_FAILURE; + } + stream->download_recvd += (curl_off_t)buflen; + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] DATA len=%zu, total=%zd", + stream->s.id, buflen, stream->download_recvd); + h3_drain_stream(cf, data); + return 0; +} + +static int cb_h3_deferred_consume(nghttp3_conn *conn, int64_t stream_id, + size_t consumed, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_osslq_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + (void)conn; + (void)stream_id; + if(stream) + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] deferred consume %zu bytes", + stream->s.id, consumed); + return 0; +} + +static int cb_h3_recv_header(nghttp3_conn *conn, int64_t sid, + int32_t token, nghttp3_rcbuf *name, + nghttp3_rcbuf *value, uint8_t flags, + void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + curl_int64_t stream_id = sid; + struct cf_osslq_ctx *ctx = cf->ctx; + nghttp3_vec h3name = nghttp3_rcbuf_get_buf(name); + nghttp3_vec h3val = nghttp3_rcbuf_get_buf(value); + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURLcode result = CURLE_OK; + (void)conn; + (void)stream_id; + (void)token; + (void)flags; + (void)cf; + + /* we might have cleaned up this transfer already */ + if(!stream) + return 0; + + if(token == NGHTTP3_QPACK_TOKEN__STATUS) { + char line[14]; /* status line is always 13 characters long */ + size_t ncopy; + + result = Curl_http_decode_status(&stream->status_code, + (const char *)h3val.base, h3val.len); + if(result) + return -1; + ncopy = msnprintf(line, sizeof(line), "HTTP/3 %03d \r\n", + stream->status_code); + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] status: %s", stream_id, line); + result = write_resp_raw(cf, data, line, ncopy, FALSE); + if(result) { + return -1; + } + } + else { + /* store as an HTTP1-style header */ + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] header: %.*s: %.*s", + stream_id, (int)h3name.len, h3name.base, + (int)h3val.len, h3val.base); + result = write_resp_raw(cf, data, h3name.base, h3name.len, FALSE); + if(result) { + return -1; + } + result = write_resp_raw(cf, data, ": ", 2, FALSE); + if(result) { + return -1; + } + result = write_resp_raw(cf, data, h3val.base, h3val.len, FALSE); + if(result) { + return -1; + } + result = write_resp_raw(cf, data, "\r\n", 2, FALSE); + if(result) { + return -1; + } + } + return 0; +} + +static int cb_h3_end_headers(nghttp3_conn *conn, int64_t sid, + int fin, void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_osslq_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + curl_int64_t stream_id = sid; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURLcode result = CURLE_OK; + (void)conn; + (void)stream_id; + (void)fin; + (void)cf; + + if(!stream) + return 0; + /* add a CRLF only if we've received some headers */ + result = write_resp_raw(cf, data, "\r\n", 2, FALSE); + if(result) { + return -1; + } + + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] end_headers, status=%d", + stream_id, stream->status_code); + if(stream->status_code / 100 != 1) { + stream->resp_hds_complete = TRUE; + } + h3_drain_stream(cf, data); + return 0; +} + +static int cb_h3_stop_sending(nghttp3_conn *conn, int64_t sid, + uint64_t app_error_code, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_osslq_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + curl_int64_t stream_id = sid; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + (void)conn; + (void)app_error_code; + + if(!stream || !stream->s.ssl) + return 0; + + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] stop_sending", stream_id); + cf_osslq_stream_close(&stream->s); + return 0; +} + +static int cb_h3_reset_stream(nghttp3_conn *conn, int64_t sid, + uint64_t app_error_code, void *user_data, + void *stream_user_data) { + struct Curl_cfilter *cf = user_data; + struct cf_osslq_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + curl_int64_t stream_id = sid; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + int rv; + (void)conn; + + if(stream && stream->s.ssl) { + SSL_STREAM_RESET_ARGS args = {0}; + args.quic_error_code = app_error_code; + rv = !SSL_stream_reset(stream->s.ssl, &args, sizeof(args)); + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] reset -> %d", stream_id, rv); + if(!rv) { + return NGHTTP3_ERR_CALLBACK_FAILURE; + } + } + return 0; +} + +static nghttp3_ssize +cb_h3_read_req_body(nghttp3_conn *conn, int64_t stream_id, + nghttp3_vec *vec, size_t veccnt, + uint32_t *pflags, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_osslq_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + ssize_t nwritten = 0; + size_t nvecs = 0; + (void)cf; + (void)conn; + (void)stream_id; + (void)user_data; + (void)veccnt; + + if(!stream) + return NGHTTP3_ERR_CALLBACK_FAILURE; + /* nghttp3 keeps references to the sendbuf data until it is ACKed + * by the server (see `cb_h3_acked_req_body()` for updates). + * `sendbuf_len_in_flight` is the amount of bytes in `sendbuf` + * that we have already passed to nghttp3, but which have not been + * ACKed yet. + * Any amount beyond `sendbuf_len_in_flight` we need still to pass + * to nghttp3. Do that now, if we can. */ + if(stream->sendbuf_len_in_flight < Curl_bufq_len(&stream->sendbuf)) { + nvecs = 0; + while(nvecs < veccnt && + Curl_bufq_peek_at(&stream->sendbuf, + stream->sendbuf_len_in_flight, + (const unsigned char **)&vec[nvecs].base, + &vec[nvecs].len)) { + stream->sendbuf_len_in_flight += vec[nvecs].len; + nwritten += vec[nvecs].len; + ++nvecs; + } + DEBUGASSERT(nvecs > 0); /* we SHOULD have been be able to peek */ + } + + if(nwritten > 0 && stream->upload_left != -1) + stream->upload_left -= nwritten; + + /* When we stopped sending and everything in `sendbuf` is "in flight", + * we are at the end of the request body. */ + if(stream->upload_left == 0) { + *pflags = NGHTTP3_DATA_FLAG_EOF; + stream->send_closed = TRUE; + } + else if(!nwritten) { + /* Not EOF, and nothing to give, we signal WOULDBLOCK. */ + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] read req body -> AGAIN", + stream->s.id); + return NGHTTP3_ERR_WOULDBLOCK; + } + + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] read req body -> " + "%d vecs%s with %zu (buffered=%zu, left=%" + CURL_FORMAT_CURL_OFF_T ")", + stream->s.id, (int)nvecs, + *pflags == NGHTTP3_DATA_FLAG_EOF?" EOF":"", + nwritten, Curl_bufq_len(&stream->sendbuf), + stream->upload_left); + return (nghttp3_ssize)nvecs; +} + +static int cb_h3_acked_stream_data(nghttp3_conn *conn, int64_t stream_id, + uint64_t datalen, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_osslq_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + size_t skiplen; + + (void)cf; + if(!stream) + return 0; + /* The server acknowledged `datalen` of bytes from our request body. + * This is a delta. We have kept this data in `sendbuf` for + * re-transmissions and can free it now. */ + if(datalen >= (uint64_t)stream->sendbuf_len_in_flight) + skiplen = stream->sendbuf_len_in_flight; + else + skiplen = (size_t)datalen; + Curl_bufq_skip(&stream->sendbuf, skiplen); + stream->sendbuf_len_in_flight -= skiplen; + + /* Everything ACKed, we resume upload processing */ + if(!stream->sendbuf_len_in_flight) { + int rv = nghttp3_conn_resume_stream(conn, stream_id); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + return NGHTTP3_ERR_CALLBACK_FAILURE; + } + } + return 0; +} + +static nghttp3_callbacks ngh3_callbacks = { + cb_h3_acked_stream_data, + cb_h3_stream_close, + cb_h3_recv_data, + cb_h3_deferred_consume, + NULL, /* begin_headers */ + cb_h3_recv_header, + cb_h3_end_headers, + NULL, /* begin_trailers */ + cb_h3_recv_header, + NULL, /* end_trailers */ + cb_h3_stop_sending, + NULL, /* end_stream */ + cb_h3_reset_stream, + NULL, /* shutdown */ + NULL /* recv_settings */ +}; + +static CURLcode cf_osslq_h3conn_init(struct cf_osslq_ctx *ctx, SSL *conn, + void *user_data) +{ + struct cf_osslq_h3conn *h3 = &ctx->h3; + CURLcode result; + int rc; + + nghttp3_settings_default(&h3->settings); + rc = nghttp3_conn_client_new(&h3->conn, + &ngh3_callbacks, + &h3->settings, + nghttp3_mem_default(), + user_data); + if(rc) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + result = cf_osslq_stream_open(&h3->s_ctrl, conn, + SSL_STREAM_FLAG_ADVANCE|SSL_STREAM_FLAG_UNI, + &ctx->stream_bufcp, NULL); + if(result) { + result = CURLE_QUIC_CONNECT_ERROR; + goto out; + } + result = cf_osslq_stream_open(&h3->s_qpack_enc, conn, + SSL_STREAM_FLAG_ADVANCE|SSL_STREAM_FLAG_UNI, + &ctx->stream_bufcp, NULL); + if(result) { + result = CURLE_QUIC_CONNECT_ERROR; + goto out; + } + result = cf_osslq_stream_open(&h3->s_qpack_dec, conn, + SSL_STREAM_FLAG_ADVANCE|SSL_STREAM_FLAG_UNI, + &ctx->stream_bufcp, NULL); + if(result) { + result = CURLE_QUIC_CONNECT_ERROR; + goto out; + } + + rc = nghttp3_conn_bind_control_stream(h3->conn, h3->s_ctrl.id); + if(rc) { + result = CURLE_QUIC_CONNECT_ERROR; + goto out; + } + rc = nghttp3_conn_bind_qpack_streams(h3->conn, h3->s_qpack_enc.id, + h3->s_qpack_dec.id); + if(rc) { + result = CURLE_QUIC_CONNECT_ERROR; + goto out; + } + + result = CURLE_OK; +out: + return result; +} + +static CURLcode cf_osslq_ctx_start(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + CURLcode result; + int rv; + const struct Curl_sockaddr_ex *peer_addr = NULL; + BIO *bio = NULL; + BIO_ADDR *baddr = NULL; + + Curl_bufcp_init(&ctx->stream_bufcp, H3_STREAM_CHUNK_SIZE, + H3_STREAM_POOL_SPARES); + Curl_hash_offt_init(&ctx->streams, 63, h3_stream_hash_free); + result = Curl_ssl_peer_init(&ctx->peer, cf, TRNSPRT_QUIC); + if(result) + goto out; + +#define H3_ALPN "\x2h3" + result = Curl_vquic_tls_init(&ctx->tls, cf, data, &ctx->peer, + H3_ALPN, sizeof(H3_ALPN) - 1, + NULL, NULL, NULL); + if(result) + goto out; + + result = vquic_ctx_init(&ctx->q); + if(result) + goto out; + + result = CURLE_QUIC_CONNECT_ERROR; + Curl_cf_socket_peek(cf->next, data, &ctx->q.sockfd, &peer_addr, NULL); + if(!peer_addr) + goto out; + + ctx->q.local_addrlen = sizeof(ctx->q.local_addr); + rv = getsockname(ctx->q.sockfd, (struct sockaddr *)&ctx->q.local_addr, + &ctx->q.local_addrlen); + if(rv == -1) + goto out; + + result = make_bio_addr(&baddr, peer_addr); + if(result) { + failf(data, "error creating BIO_ADDR from sockaddr"); + goto out; + } + + /* Type conversions, see #12861: OpenSSL wants an `int`, but on 64-bit + * Win32 systems, Microsoft defines SOCKET as `unsigned long long`. + */ +#if defined(_WIN32) && !defined(__LWIP_OPT_H__) && !defined(LWIP_HDR_OPT_H) + if(ctx->q.sockfd > INT_MAX) { + failf(data, "Windows socket identifier larger than MAX_INT, " + "unable to set in OpenSSL dgram API."); + result = CURLE_QUIC_CONNECT_ERROR; + goto out; + } + bio = BIO_new_dgram((int)ctx->q.sockfd, BIO_NOCLOSE); +#else + bio = BIO_new_dgram(ctx->q.sockfd, BIO_NOCLOSE); +#endif + if(!bio) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + if(!SSL_set1_initial_peer_addr(ctx->tls.ossl.ssl, baddr)) { + failf(data, "failed to set the initial peer address"); + result = CURLE_FAILED_INIT; + goto out; + } + if(!SSL_set_blocking_mode(ctx->tls.ossl.ssl, 0)) { + failf(data, "failed to turn off blocking mode"); + result = CURLE_FAILED_INIT; + goto out; + } + +#ifdef SSL_VALUE_QUIC_IDLE_TIMEOUT + /* Added in OpenSSL v3.3.x */ + if(!SSL_set_feature_request_uint(ctx->tls.ossl.ssl, + SSL_VALUE_QUIC_IDLE_TIMEOUT, + CURL_QUIC_MAX_IDLE_MS)) { + CURL_TRC_CF(data, cf, "error setting idle timeout, "); + result = CURLE_FAILED_INIT; + goto out; + } +#endif + + SSL_set_bio(ctx->tls.ossl.ssl, bio, bio); + bio = NULL; + SSL_set_connect_state(ctx->tls.ossl.ssl); + SSL_set_incoming_stream_policy(ctx->tls.ossl.ssl, + SSL_INCOMING_STREAM_POLICY_ACCEPT, 0); + /* setup the H3 things on top of the QUIC connection */ + result = cf_osslq_h3conn_init(ctx, ctx->tls.ossl.ssl, cf); + +out: + if(bio) + BIO_free(bio); + if(baddr) + BIO_ADDR_free(baddr); + CURL_TRC_CF(data, cf, "QUIC tls init -> %d", result); + return result; +} + +struct h3_quic_recv_ctx { + struct Curl_cfilter *cf; + struct Curl_easy *data; + struct cf_osslq_stream *s; +}; + +static ssize_t h3_quic_recv(void *reader_ctx, + unsigned char *buf, size_t len, + CURLcode *err) +{ + struct h3_quic_recv_ctx *x = reader_ctx; + size_t nread; + int rv; + + *err = CURLE_OK; + rv = SSL_read_ex(x->s->ssl, buf, len, &nread); + if(rv <= 0) { + int detail = SSL_get_error(x->s->ssl, rv); + if(detail == SSL_ERROR_WANT_READ || detail == SSL_ERROR_WANT_WRITE) { + *err = CURLE_AGAIN; + return -1; + } + else if(detail == SSL_ERROR_ZERO_RETURN) { + CURL_TRC_CF(x->data, x->cf, "[%" CURL_PRId64 "] h3_quic_recv -> EOS", + x->s->id); + x->s->recvd_eos = TRUE; + return 0; + } + else if(SSL_get_stream_read_state(x->s->ssl) == + SSL_STREAM_STATE_RESET_REMOTE) { + uint64_t app_error_code = NGHTTP3_H3_NO_ERROR; + SSL_get_stream_read_error_code(x->s->ssl, &app_error_code); + CURL_TRC_CF(x->data, x->cf, "[%" CURL_PRId64 "] h3_quic_recv -> RESET, " + "rv=%d, app_err=%" CURL_PRIu64, + x->s->id, rv, (curl_uint64_t)app_error_code); + if(app_error_code != NGHTTP3_H3_NO_ERROR) { + x->s->reset = TRUE; + } + x->s->recvd_eos = TRUE; + return 0; + } + else { + *err = cf_osslq_ssl_err(x->cf, x->data, detail, CURLE_RECV_ERROR); + return -1; + } + } + return (ssize_t)nread; +} + +static CURLcode cf_osslq_stream_recv(struct cf_osslq_stream *s, + struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + ssize_t nread; + struct h3_quic_recv_ctx x; + int rv, eagain = FALSE; + size_t total_recv_len = 0; + + DEBUGASSERT(s); + if(s->closed) + return CURLE_OK; + + x.cf = cf; + x.data = data; + x.s = s; + while(s->ssl && !s->closed && !eagain && + (total_recv_len < H3_STREAM_CHUNK_SIZE)) { + if(Curl_bufq_is_empty(&s->recvbuf) && !s->recvd_eos) { + while(!eagain && !s->recvd_eos && !Curl_bufq_is_full(&s->recvbuf)) { + nread = Curl_bufq_sipn(&s->recvbuf, 0, h3_quic_recv, &x, &result); + if(nread < 0) { + if(result != CURLE_AGAIN) + goto out; + result = CURLE_OK; + eagain = TRUE; + } + } + } + + /* Forward what we have to nghttp3 */ + if(!Curl_bufq_is_empty(&s->recvbuf)) { + const unsigned char *buf; + size_t blen; + + while(Curl_bufq_peek(&s->recvbuf, &buf, &blen)) { + nread = nghttp3_conn_read_stream(ctx->h3.conn, s->id, + buf, blen, 0); + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] forward %zu bytes " + "to nghttp3 -> %zd", s->id, blen, nread); + if(nread < 0) { + failf(data, "nghttp3_conn_read_stream(len=%zu) error: %s", + blen, nghttp3_strerror((int)nread)); + result = CURLE_RECV_ERROR; + goto out; + } + /* success, `nread` is the flow for QUIC to count as "consumed", + * not sure how that will work with OpenSSL. Anyways, without error, + * all data that we passed is not owned by nghttp3. */ + Curl_bufq_skip(&s->recvbuf, blen); + total_recv_len += blen; + } + } + + /* When we forwarded everything, handle RESET/EOS */ + if(Curl_bufq_is_empty(&s->recvbuf) && !s->closed) { + result = CURLE_OK; + if(s->reset) { + uint64_t app_error; + if(!SSL_get_stream_read_error_code(s->ssl, &app_error)) { + failf(data, "SSL_get_stream_read_error_code returned error"); + result = CURLE_RECV_ERROR; + goto out; + } + rv = nghttp3_conn_close_stream(ctx->h3.conn, s->id, app_error); + s->closed = TRUE; + if(rv < 0 && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + failf(data, "nghttp3_conn_close_stream returned error: %s", + nghttp3_strerror(rv)); + result = CURLE_RECV_ERROR; + goto out; + } + } + else if(s->recvd_eos) { + rv = nghttp3_conn_close_stream(ctx->h3.conn, s->id, + NGHTTP3_H3_NO_ERROR); + s->closed = TRUE; + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] close nghttp3 stream -> %d", + s->id, rv); + if(rv < 0 && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + failf(data, "nghttp3_conn_close_stream returned error: %s", + nghttp3_strerror(rv)); + result = CURLE_RECV_ERROR; + goto out; + } + } + } + } +out: + if(result) + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] cf_osslq_stream_recv -> %d", + s->id, result); + return result; +} + +static CURLcode cf_progress_ingress(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + if(!ctx->tls.ossl.ssl) + goto out; + + ERR_clear_error(); + + /* 1. Check for new incoming streams */ + while(1) { + SSL *snew = SSL_accept_stream(ctx->tls.ossl.ssl, + SSL_ACCEPT_STREAM_NO_BLOCK); + if(!snew) + break; + + (void)cf_osslq_h3conn_add_stream(&ctx->h3, snew, cf, data); + } + + if(!SSL_handle_events(ctx->tls.ossl.ssl)) { + int detail = SSL_get_error(ctx->tls.ossl.ssl, 0); + result = cf_osslq_ssl_err(cf, data, detail, CURLE_RECV_ERROR); + } + + if(ctx->h3.conn) { + size_t i; + for(i = 0; i < ctx->h3.remote_ctrl_n; ++i) { + result = cf_osslq_stream_recv(&ctx->h3.remote_ctrl[i], cf, data); + if(result) + goto out; + } + } + + if(ctx->h3.conn) { + struct Curl_easy *sdata; + struct h3_stream_ctx *stream; + /* PULL all open streams */ + DEBUGASSERT(data->multi); + for(sdata = data->multi->easyp; sdata; sdata = sdata->next) { + if(sdata->conn == data->conn && CURL_WANT_RECV(sdata)) { + stream = H3_STREAM_CTX(ctx, sdata); + if(stream && !stream->closed && + !Curl_bufq_is_full(&stream->recvbuf)) { + result = cf_osslq_stream_recv(&stream->s, cf, sdata); + if(result) + goto out; + } + } + } + } + +out: + CURL_TRC_CF(data, cf, "progress_ingress -> %d", result); + return result; +} + +/* Iterate over all streams and check if blocked can be unblocked */ +static CURLcode cf_osslq_check_and_unblock(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + struct Curl_easy *sdata; + struct h3_stream_ctx *stream; + + if(ctx->h3.conn) { + for(sdata = data->multi->easyp; sdata; sdata = sdata->next) { + if(sdata->conn == data->conn) { + stream = H3_STREAM_CTX(ctx, sdata); + if(stream && stream->s.ssl && stream->s.send_blocked && + !SSL_want_write(stream->s.ssl)) { + nghttp3_conn_unblock_stream(ctx->h3.conn, stream->s.id); + stream->s.send_blocked = FALSE; + h3_drain_stream(cf, sdata); + CURL_TRC_CF(sdata, cf, "unblocked"); + } + } + } + } + return CURLE_OK; +} + +static CURLcode h3_send_streams(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + if(!ctx->tls.ossl.ssl || !ctx->h3.conn) + goto out; + + for(;;) { + struct cf_osslq_stream *s = NULL; + nghttp3_vec vec[16]; + nghttp3_ssize n, i; + int64_t stream_id; + size_t written; + int eos, ok, rv; + size_t total_len, acked_len = 0; + bool blocked = FALSE, eos_written = FALSE; + + n = nghttp3_conn_writev_stream(ctx->h3.conn, &stream_id, &eos, + vec, ARRAYSIZE(vec)); + if(n < 0) { + failf(data, "nghttp3_conn_writev_stream returned error: %s", + nghttp3_strerror((int)n)); + result = CURLE_SEND_ERROR; + goto out; + } + if(stream_id < 0) { + result = CURLE_OK; + goto out; + } + + /* Get the stream for this data */ + s = cf_osslq_get_qstream(cf, data, stream_id); + if(!s) { + failf(data, "nghttp3_conn_writev_stream gave unknown stream %" + CURL_PRId64, (curl_int64_t)stream_id); + result = CURLE_SEND_ERROR; + goto out; + } + /* Now write the data to the stream's SSL*, it may not all fit! */ + DEBUGASSERT(s->id == stream_id); + for(i = 0, total_len = 0; i < n; ++i) { + total_len += vec[i].len; + } + for(i = 0; (i < n) && !blocked; ++i) { + /* Without stream->s.ssl, we closed that already, so + * pretend the write did succeed. */ +#ifdef SSL_WRITE_FLAG_CONCLUDE + /* Since OpenSSL v3.3.x, on last chunk set EOS if needed */ + uint64_t flags = (eos && ((i + 1) == n))? SSL_WRITE_FLAG_CONCLUDE : 0; + written = vec[i].len; + ok = !s->ssl || SSL_write_ex2(s->ssl, vec[i].base, vec[i].len, flags, + &written); + if(ok && flags & SSL_WRITE_FLAG_CONCLUDE) + eos_written = TRUE; +#else + written = vec[i].len; + ok = !s->ssl || SSL_write_ex(s->ssl, vec[i].base, vec[i].len, + &written); +#endif + if(ok) { + /* As OpenSSL buffers the data, we count this as acknowledged + * from nghttp3's point of view */ + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] send %zu bytes to QUIC ok", + s->id, vec[i].len); + acked_len += vec[i].len; + } + else { + int detail = SSL_get_error(s->ssl, 0); + switch(detail) { + case SSL_ERROR_WANT_WRITE: + case SSL_ERROR_WANT_READ: + /* QUIC blocked us from writing more */ + CURL_TRC_CF(data, cf, "[%"CURL_PRId64 "] send %zu bytes to " + "QUIC blocked", s->id, vec[i].len); + written = 0; + nghttp3_conn_block_stream(ctx->h3.conn, s->id); + s->send_blocked = blocked = TRUE; + break; + default: + failf(data, "[%"CURL_PRId64 "] send %zu bytes to QUIC, SSL error %d", + s->id, vec[i].len, detail); + result = cf_osslq_ssl_err(cf, data, detail, CURLE_HTTP3); + goto out; + } + } + } + + if(acked_len > 0 || (eos && !s->send_blocked)) { + /* Since QUIC buffers the data written internally, we can tell + * nghttp3 that it can move forward on it */ + ctx->q.last_io = Curl_now(); + rv = nghttp3_conn_add_write_offset(ctx->h3.conn, s->id, acked_len); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + failf(data, "nghttp3_conn_add_write_offset returned error: %s\n", + nghttp3_strerror(rv)); + result = CURLE_SEND_ERROR; + goto out; + } + rv = nghttp3_conn_add_ack_offset(ctx->h3.conn, s->id, acked_len); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + failf(data, "nghttp3_conn_add_ack_offset returned error: %s\n", + nghttp3_strerror(rv)); + result = CURLE_SEND_ERROR; + goto out; + } + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] forwarded %zu/%zu h3 bytes " + "to QUIC, eos=%d", s->id, acked_len, total_len, eos); + } + + if(eos && !s->send_blocked && !eos_written) { + /* wrote everything and H3 indicates end of stream */ + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] closing QUIC stream", s->id); + SSL_stream_conclude(s->ssl, 0); + } + } + +out: + CURL_TRC_CF(data, cf, "h3_send_streams -> %d", result); + return result; +} + +static CURLcode cf_progress_egress(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + if(!ctx->tls.ossl.ssl) + goto out; + + ERR_clear_error(); + result = h3_send_streams(cf, data); + if(result) + goto out; + + if(!SSL_handle_events(ctx->tls.ossl.ssl)) { + int detail = SSL_get_error(ctx->tls.ossl.ssl, 0); + result = cf_osslq_ssl_err(cf, data, detail, CURLE_SEND_ERROR); + } + + result = cf_osslq_check_and_unblock(cf, data); + +out: + CURL_TRC_CF(data, cf, "progress_egress -> %d", result); + return result; +} + +static CURLcode check_and_set_expiry(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + struct timeval tv; + timediff_t timeoutms; + int is_infinite = TRUE; + + if(ctx->tls.ossl.ssl && + SSL_get_event_timeout(ctx->tls.ossl.ssl, &tv, &is_infinite) && + !is_infinite) { + timeoutms = curlx_tvtoms(&tv); + /* QUIC want to be called again latest at the returned timeout */ + if(timeoutms <= 0) { + result = cf_progress_ingress(cf, data); + if(result) + goto out; + result = cf_progress_egress(cf, data); + if(result) + goto out; + if(SSL_get_event_timeout(ctx->tls.ossl.ssl, &tv, &is_infinite)) { + timeoutms = curlx_tvtoms(&tv); + } + } + if(!is_infinite) { + Curl_expire(data, timeoutms, EXPIRE_QUIC); + CURL_TRC_CF(data, cf, "QUIC expiry in %ldms", (long)timeoutms); + } + } +out: + return result; +} + +static CURLcode cf_osslq_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + struct cf_call_data save; + struct curltime now; + int err; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + /* Connect the UDP filter first */ + if(!cf->next->connected) { + result = Curl_conn_cf_connect(cf->next, data, blocking, done); + if(result || !*done) + return result; + } + + *done = FALSE; + now = Curl_now(); + CF_DATA_SAVE(save, cf, data); + + if(ctx->reconnect_at.tv_sec && Curl_timediff(now, ctx->reconnect_at) < 0) { + /* Not time yet to attempt the next connect */ + CURL_TRC_CF(data, cf, "waiting for reconnect time"); + goto out; + } + + if(!ctx->tls.ossl.ssl) { + ctx->started_at = now; + result = cf_osslq_ctx_start(cf, data); + if(result) + goto out; + } + + if(!ctx->got_first_byte) { + int readable = SOCKET_READABLE(ctx->q.sockfd, 0); + if(readable > 0 && (readable & CURL_CSELECT_IN)) { + ctx->got_first_byte = TRUE; + ctx->first_byte_at = Curl_now(); + } + } + + ERR_clear_error(); + err = SSL_do_handshake(ctx->tls.ossl.ssl); + + if(err == 1) { + /* connected */ + ctx->handshake_at = now; + ctx->q.last_io = now; + CURL_TRC_CF(data, cf, "handshake complete after %dms", + (int)Curl_timediff(now, ctx->started_at)); + result = cf_osslq_verify_peer(cf, data); + if(!result) { + CURL_TRC_CF(data, cf, "peer verified"); + cf->connected = TRUE; + cf->conn->alpn = CURL_HTTP_VERSION_3; + *done = TRUE; + connkeep(cf->conn, "HTTP/3 default"); + } + } + else { + int detail = SSL_get_error(ctx->tls.ossl.ssl, err); + switch(detail) { + case SSL_ERROR_WANT_READ: + ctx->q.last_io = now; + CURL_TRC_CF(data, cf, "QUIC SSL_connect() -> WANT_RECV"); + result = Curl_vquic_tls_before_recv(&ctx->tls, cf, data); + goto out; + case SSL_ERROR_WANT_WRITE: + ctx->q.last_io = now; + CURL_TRC_CF(data, cf, "QUIC SSL_connect() -> WANT_SEND"); + result = CURLE_OK; + goto out; +#ifdef SSL_ERROR_WANT_ASYNC + case SSL_ERROR_WANT_ASYNC: + ctx->q.last_io = now; + CURL_TRC_CF(data, cf, "QUIC SSL_connect() -> WANT_ASYNC"); + result = CURLE_OK; + goto out; +#endif +#ifdef SSL_ERROR_WANT_RETRY_VERIFY + case SSL_ERROR_WANT_RETRY_VERIFY: + result = CURLE_OK; + goto out; +#endif + default: + result = cf_osslq_ssl_err(cf, data, detail, CURLE_COULDNT_CONNECT); + goto out; + } + } + +out: + if(result == CURLE_RECV_ERROR && ctx->tls.ossl.ssl && + ctx->protocol_shutdown) { + /* When a QUIC server instance is shutting down, it may send us a + * CONNECTION_CLOSE right away. Our connection then enters the DRAINING + * state. The CONNECT may work in the near future again. Indicate + * that as a "weird" reply. */ + result = CURLE_WEIRD_SERVER_REPLY; + } + +#ifndef CURL_DISABLE_VERBOSE_STRINGS + if(result) { + struct ip_quadruple ip; + + Curl_cf_socket_peek(cf->next, data, NULL, NULL, &ip); + infof(data, "QUIC connect to %s port %u failed: %s", + ip.remote_ip, ip.remote_port, curl_easy_strerror(result)); + } +#endif + if(!result) + result = check_and_set_expiry(cf, data); + if(result || *done) + CURL_TRC_CF(data, cf, "connect -> %d, done=%d", result, *done); + CF_DATA_RESTORE(cf, save); + return result; +} + +static ssize_t h3_stream_open(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *buf, size_t len, + CURLcode *err) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = NULL; + struct dynhds h2_headers; + size_t nheader; + nghttp3_nv *nva = NULL; + int rc = 0; + unsigned int i; + ssize_t nwritten = -1; + nghttp3_data_reader reader; + nghttp3_data_reader *preader = NULL; + + Curl_dynhds_init(&h2_headers, 0, DYN_HTTP_REQUEST); + + *err = h3_data_setup(cf, data); + if(*err) + goto out; + stream = H3_STREAM_CTX(ctx, data); + DEBUGASSERT(stream); + if(!stream) { + *err = CURLE_FAILED_INIT; + goto out; + } + + nwritten = Curl_h1_req_parse_read(&stream->h1, buf, len, NULL, 0, err); + if(nwritten < 0) + goto out; + if(!stream->h1.done) { + /* need more data */ + goto out; + } + DEBUGASSERT(stream->h1.req); + + *err = Curl_http_req_to_h2(&h2_headers, stream->h1.req, data); + if(*err) { + nwritten = -1; + goto out; + } + /* no longer needed */ + Curl_h1_req_parse_free(&stream->h1); + + nheader = Curl_dynhds_count(&h2_headers); + nva = malloc(sizeof(nghttp3_nv) * nheader); + if(!nva) { + *err = CURLE_OUT_OF_MEMORY; + nwritten = -1; + goto out; + } + + for(i = 0; i < nheader; ++i) { + struct dynhds_entry *e = Curl_dynhds_getn(&h2_headers, i); + nva[i].name = (unsigned char *)e->name; + nva[i].namelen = e->namelen; + nva[i].value = (unsigned char *)e->value; + nva[i].valuelen = e->valuelen; + nva[i].flags = NGHTTP3_NV_FLAG_NONE; + } + + DEBUGASSERT(stream->s.id == -1); + *err = cf_osslq_stream_open(&stream->s, ctx->tls.ossl.ssl, 0, + &ctx->stream_bufcp, data); + if(*err) { + failf(data, "can't get bidi streams"); + *err = CURLE_SEND_ERROR; + goto out; + } + + switch(data->state.httpreq) { + case HTTPREQ_POST: + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + case HTTPREQ_PUT: + /* known request body size or -1 */ + if(data->state.infilesize != -1) + stream->upload_left = data->state.infilesize; + else + /* data sending without specifying the data amount up front */ + stream->upload_left = -1; /* unknown */ + break; + default: + /* there is not request body */ + stream->upload_left = 0; /* no request body */ + break; + } + + stream->send_closed = (stream->upload_left == 0); + if(!stream->send_closed) { + reader.read_data = cb_h3_read_req_body; + preader = &reader; + } + + rc = nghttp3_conn_submit_request(ctx->h3.conn, stream->s.id, + nva, nheader, preader, data); + if(rc) { + switch(rc) { + case NGHTTP3_ERR_CONN_CLOSING: + CURL_TRC_CF(data, cf, "h3sid[%"CURL_PRId64"] failed to send, " + "connection is closing", stream->s.id); + break; + default: + CURL_TRC_CF(data, cf, "h3sid[%"CURL_PRId64 "] failed to send -> %d (%s)", + stream->s.id, rc, nghttp3_strerror(rc)); + break; + } + *err = CURLE_SEND_ERROR; + nwritten = -1; + goto out; + } + + if(Curl_trc_is_verbose(data)) { + infof(data, "[HTTP/3] [%" CURL_PRId64 "] OPENED stream for %s", + stream->s.id, data->state.url); + for(i = 0; i < nheader; ++i) { + infof(data, "[HTTP/3] [%" CURL_PRId64 "] [%.*s: %.*s]", + stream->s.id, + (int)nva[i].namelen, nva[i].name, + (int)nva[i].valuelen, nva[i].value); + } + } + +out: + free(nva); + Curl_dynhds_free(&h2_headers); + return nwritten; +} + +static ssize_t cf_osslq_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *buf, size_t len, CURLcode *err) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + struct cf_call_data save; + ssize_t nwritten; + CURLcode result; + + CF_DATA_SAVE(save, cf, data); + DEBUGASSERT(cf->connected); + DEBUGASSERT(ctx->tls.ossl.ssl); + DEBUGASSERT(ctx->h3.conn); + *err = CURLE_OK; + + result = cf_progress_ingress(cf, data); + if(result) { + *err = result; + nwritten = -1; + goto out; + } + + result = cf_progress_egress(cf, data); + if(result) { + *err = result; + nwritten = -1; + goto out; + } + + if(!stream || stream->s.id < 0) { + nwritten = h3_stream_open(cf, data, buf, len, err); + if(nwritten < 0) { + CURL_TRC_CF(data, cf, "failed to open stream -> %d", *err); + goto out; + } + stream = H3_STREAM_CTX(ctx, data); + } + else if(stream->upload_blocked_len) { + /* the data in `buf` has already been submitted or added to the + * buffers, but have been EAGAINed on the last invocation. */ + DEBUGASSERT(len >= stream->upload_blocked_len); + if(len < stream->upload_blocked_len) { + /* Did we get called again with a smaller `len`? This should not + * happen. We are not prepared to handle that. */ + failf(data, "HTTP/3 send again with decreased length"); + *err = CURLE_HTTP3; + nwritten = -1; + goto out; + } + nwritten = (ssize_t)stream->upload_blocked_len; + stream->upload_blocked_len = 0; + } + else if(stream->closed) { + if(stream->resp_hds_complete) { + /* Server decided to close the stream after having sent us a final + * response. This is valid if it is not interested in the request + * body. This happens on 30x or 40x responses. + * We silently discard the data sent, since this is not a transport + * error situation. */ + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] discarding data" + "on closed stream with response", stream->s.id); + *err = CURLE_OK; + nwritten = (ssize_t)len; + goto out; + } + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] send_body(len=%zu) " + "-> stream closed", stream->s.id, len); + *err = CURLE_HTTP3; + nwritten = -1; + goto out; + } + else { + nwritten = Curl_bufq_write(&stream->sendbuf, buf, len, err); + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] cf_send, add to " + "sendbuf(len=%zu) -> %zd, %d", + stream->s.id, len, nwritten, *err); + if(nwritten < 0) { + goto out; + } + + (void)nghttp3_conn_resume_stream(ctx->h3.conn, stream->s.id); + } + + result = cf_progress_egress(cf, data); + if(result) { + *err = result; + nwritten = -1; + } + + if(stream && nwritten > 0 && stream->sendbuf_len_in_flight) { + /* We have unacknowledged DATA and cannot report success to our + * caller. Instead we EAGAIN and remember how much we have already + * "written" into our various internal connection buffers. */ + stream->upload_blocked_len = nwritten; + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] cf_send(len=%zu), " + "%zu bytes in flight -> EGAIN", stream->s.id, len, + stream->sendbuf_len_in_flight); + *err = CURLE_AGAIN; + nwritten = -1; + } + +out: + result = check_and_set_expiry(cf, data); + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] cf_send(len=%zu) -> %zd, %d", + stream? stream->s.id : -1, len, nwritten, *err); + CF_DATA_RESTORE(cf, save); + return nwritten; +} + +static ssize_t recv_closed_stream(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream, + CURLcode *err) +{ + ssize_t nread = -1; + + (void)cf; + if(stream->reset) { + failf(data, + "HTTP/3 stream %" CURL_PRId64 " reset by server", + stream->s.id); + *err = data->req.bytecount? CURLE_PARTIAL_FILE : CURLE_HTTP3; + goto out; + } + else if(!stream->resp_hds_complete) { + failf(data, + "HTTP/3 stream %" CURL_PRId64 + " was closed cleanly, but before getting" + " all response header fields, treated as error", + stream->s.id); + *err = CURLE_HTTP3; + goto out; + } + *err = CURLE_OK; + nread = 0; + +out: + return nread; +} + +static ssize_t cf_osslq_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, CURLcode *err) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + ssize_t nread = -1; + struct cf_call_data save; + CURLcode result; + + (void)ctx; + CF_DATA_SAVE(save, cf, data); + DEBUGASSERT(cf->connected); + DEBUGASSERT(ctx); + DEBUGASSERT(ctx->tls.ossl.ssl); + DEBUGASSERT(ctx->h3.conn); + *err = CURLE_OK; + + if(!stream) { + *err = CURLE_RECV_ERROR; + goto out; + } + + if(!Curl_bufq_is_empty(&stream->recvbuf)) { + nread = Curl_bufq_read(&stream->recvbuf, + (unsigned char *)buf, len, err); + if(nread < 0) { + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] read recvbuf(len=%zu) " + "-> %zd, %d", stream->s.id, len, nread, *err); + goto out; + } + } + + result = cf_progress_ingress(cf, data); + if(result) { + *err = result; + nread = -1; + goto out; + } + + /* recvbuf had nothing before, maybe after progressing ingress? */ + if(nread < 0 && !Curl_bufq_is_empty(&stream->recvbuf)) { + nread = Curl_bufq_read(&stream->recvbuf, + (unsigned char *)buf, len, err); + if(nread < 0) { + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] read recvbuf(len=%zu) " + "-> %zd, %d", stream->s.id, len, nread, *err); + goto out; + } + } + + if(nread > 0) { + h3_drain_stream(cf, data); + } + else { + if(stream->closed) { + nread = recv_closed_stream(cf, data, stream, err); + goto out; + } + *err = CURLE_AGAIN; + nread = -1; + } + +out: + if(cf_progress_egress(cf, data)) { + *err = CURLE_SEND_ERROR; + nread = -1; + } + else { + CURLcode result2 = check_and_set_expiry(cf, data); + if(result2) { + *err = result2; + nread = -1; + } + } + CURL_TRC_CF(data, cf, "[%" CURL_PRId64 "] cf_recv(len=%zu) -> %zd, %d", + stream? stream->s.id : -1, len, nread, *err); + CF_DATA_RESTORE(cf, save); + return nread; +} + +/* + * Called from transfer.c:data_pending to know if we should keep looping + * to receive more data from the connection. + */ +static bool cf_osslq_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + const struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + (void)cf; + return stream && !Curl_bufq_is_empty(&stream->recvbuf); +} + +static CURLcode cf_osslq_data_event(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + (void)arg1; + (void)arg2; + switch(event) { + case CF_CTRL_DATA_SETUP: + break; + case CF_CTRL_DATA_PAUSE: + result = h3_data_pause(cf, data, (arg1 != 0)); + break; + case CF_CTRL_DATA_DETACH: + h3_data_done(cf, data); + break; + case CF_CTRL_DATA_DONE: + h3_data_done(cf, data); + break; + case CF_CTRL_DATA_DONE_SEND: { + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + if(stream && !stream->send_closed) { + stream->send_closed = TRUE; + stream->upload_left = Curl_bufq_len(&stream->sendbuf); + (void)nghttp3_conn_resume_stream(ctx->h3.conn, stream->s.id); + } + break; + } + case CF_CTRL_DATA_IDLE: { + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURL_TRC_CF(data, cf, "data idle"); + if(stream && !stream->closed) { + result = check_and_set_expiry(cf, data); + } + break; + } + default: + break; + } + CF_DATA_RESTORE(cf, save); + return result; +} + +static bool cf_osslq_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + bool alive = FALSE; + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + *input_pending = FALSE; + if(!ctx->tls.ossl.ssl) + goto out; + +#ifdef SSL_VALUE_QUIC_IDLE_TIMEOUT + /* Added in OpenSSL v3.3.x */ + { + timediff_t idletime; + uint64_t idle_ms = ctx->max_idle_ms; + if(!SSL_get_value_uint(ctx->tls.ossl.ssl, + SSL_VALUE_CLASS_FEATURE_NEGOTIATED, + SSL_VALUE_QUIC_IDLE_TIMEOUT, &idle_ms)) { + CURL_TRC_CF(data, cf, "error getting negotiated idle timeout, " + "assume connection is dead."); + goto out; + } + CURL_TRC_CF(data, cf, "negotiated idle timeout: %zums", (size_t)idle_ms); + idletime = Curl_timediff(Curl_now(), ctx->q.last_io); + if(idletime > 0 && (uint64_t)idletime > idle_ms) + goto out; + } + +#endif + + if(!cf->next || !cf->next->cft->is_alive(cf->next, data, input_pending)) + goto out; + + alive = TRUE; + if(*input_pending) { + CURLcode result; + /* This happens before we've sent off a request and the connection is + not in use by any other transfer, there shouldn't be any data here, + only "protocol frames" */ + *input_pending = FALSE; + result = cf_progress_ingress(cf, data); + CURL_TRC_CF(data, cf, "is_alive, progress ingress -> %d", result); + alive = result? FALSE : TRUE; + } + +out: + CF_DATA_RESTORE(cf, save); + return alive; +} + +static void cf_osslq_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + + if(!ctx->tls.ossl.ssl) { + /* NOP */ + } + else if(!cf->connected) { + /* during handshake, transfer has not started yet. we always + * add our socket for polling if SSL wants to send/recv */ + Curl_pollset_set(data, ps, ctx->q.sockfd, + SSL_net_read_desired(ctx->tls.ossl.ssl), + SSL_net_write_desired(ctx->tls.ossl.ssl)); + } + else { + /* once connected, we only modify the socket if it is present. + * this avoids adding it for paused transfers. */ + bool want_recv, want_send; + Curl_pollset_check(data, ps, ctx->q.sockfd, &want_recv, &want_send); + if(want_recv || want_send) { + Curl_pollset_set(data, ps, ctx->q.sockfd, + SSL_net_read_desired(ctx->tls.ossl.ssl), + SSL_net_write_desired(ctx->tls.ossl.ssl)); + } + } +} + +static CURLcode cf_osslq_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + + switch(query) { + case CF_QUERY_MAX_CONCURRENT: { +#ifdef SSL_VALUE_QUIC_STREAM_BIDI_LOCAL_AVAIL + /* Added in OpenSSL v3.3.x */ + uint64_t v; + if(!SSL_get_value_uint(ctx->tls.ossl.ssl, SSL_VALUE_CLASS_GENERIC, + SSL_VALUE_QUIC_STREAM_BIDI_LOCAL_AVAIL, &v)) { + CURL_TRC_CF(data, cf, "error getting available local bidi streams"); + return CURLE_HTTP3; + } + /* we report avail + in_use */ + v += CONN_INUSE(cf->conn); + *pres1 = (v > INT_MAX)? INT_MAX : (int)v; +#else + *pres1 = 100; +#endif + CURL_TRC_CF(data, cf, "query max_conncurrent -> %d", *pres1); + return CURLE_OK; + } + case CF_QUERY_CONNECT_REPLY_MS: + if(ctx->got_first_byte) { + timediff_t ms = Curl_timediff(ctx->first_byte_at, ctx->started_at); + *pres1 = (ms < INT_MAX)? (int)ms : INT_MAX; + } + else + *pres1 = -1; + return CURLE_OK; + case CF_QUERY_TIMER_CONNECT: { + struct curltime *when = pres2; + if(ctx->got_first_byte) + *when = ctx->first_byte_at; + return CURLE_OK; + } + case CF_QUERY_TIMER_APPCONNECT: { + struct curltime *when = pres2; + if(cf->connected) + *when = ctx->handshake_at; + return CURLE_OK; + } + default: + break; + } + return cf->next? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +struct Curl_cftype Curl_cft_http3 = { + "HTTP/3", + CF_TYPE_IP_CONNECT | CF_TYPE_SSL | CF_TYPE_MULTIPLEX, + 0, + cf_osslq_destroy, + cf_osslq_connect, + cf_osslq_close, + Curl_cf_def_get_host, + cf_osslq_adjust_pollset, + cf_osslq_data_pending, + cf_osslq_send, + cf_osslq_recv, + cf_osslq_data_event, + cf_osslq_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_osslq_query, +}; + +CURLcode Curl_cf_osslq_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai) +{ + struct cf_osslq_ctx *ctx = NULL; + struct Curl_cfilter *cf = NULL, *udp_cf = NULL; + CURLcode result; + + (void)data; + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + cf_osslq_ctx_clear(ctx); + + result = Curl_cf_create(&cf, &Curl_cft_http3, ctx); + if(result) + goto out; + + result = Curl_cf_udp_create(&udp_cf, data, conn, ai, TRNSPRT_QUIC); + if(result) + goto out; + + cf->conn = conn; + udp_cf->conn = cf->conn; + udp_cf->sockindex = cf->sockindex; + cf->next = udp_cf; + +out: + *pcf = (!result)? cf : NULL; + if(result) { + if(udp_cf) + Curl_conn_cf_discard_sub(cf, udp_cf, data, TRUE); + Curl_safefree(cf); + Curl_safefree(ctx); + } + return result; +} + +bool Curl_conn_is_osslq(const struct Curl_easy *data, + const struct connectdata *conn, + int sockindex) +{ + struct Curl_cfilter *cf = conn? conn->cfilter[sockindex] : NULL; + + (void)data; + for(; cf; cf = cf->next) { + if(cf->cft == &Curl_cft_http3) + return TRUE; + if(cf->cft->flags & CF_TYPE_IP_CONNECT) + return FALSE; + } + return FALSE; +} + +/* + * Store ngtcp2 version info in this buffer. + */ +void Curl_osslq_ver(char *p, size_t len) +{ + const nghttp3_info *ht3 = nghttp3_version(0); + (void)msnprintf(p, len, "nghttp3/%s", ht3->version_str); +} + +#endif /* USE_OPENSSL_QUIC && USE_NGHTTP3 */ diff --git a/third_party/curl/lib/vquic/curl_osslq.h b/third_party/curl/lib/vquic/curl_osslq.h new file mode 100644 index 0000000..0e12d70 --- /dev/null +++ b/third_party/curl/lib/vquic/curl_osslq.h @@ -0,0 +1,51 @@ +#ifndef HEADER_CURL_VQUIC_CURL_OSSLQ_H +#define HEADER_CURL_VQUIC_CURL_OSSLQ_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_OPENSSL_QUIC) && defined(USE_NGHTTP3) + +#ifdef HAVE_NETINET_UDP_H +#include +#endif + +struct Curl_cfilter; + +#include "urldata.h" + +void Curl_osslq_ver(char *p, size_t len); + +CURLcode Curl_cf_osslq_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai); + +bool Curl_conn_is_osslq(const struct Curl_easy *data, + const struct connectdata *conn, + int sockindex); +#endif + +#endif /* HEADER_CURL_VQUIC_CURL_OSSLQ_H */ diff --git a/third_party/curl/lib/vquic/curl_quiche.c b/third_party/curl/lib/vquic/curl_quiche.c new file mode 100644 index 0000000..a68fc64 --- /dev/null +++ b/third_party/curl/lib/vquic/curl_quiche.c @@ -0,0 +1,1651 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_QUICHE +#include +#include +#include +#include "bufq.h" +#include "hash.h" +#include "urldata.h" +#include "cfilters.h" +#include "cf-socket.h" +#include "sendf.h" +#include "strdup.h" +#include "rand.h" +#include "strcase.h" +#include "multiif.h" +#include "connect.h" +#include "progress.h" +#include "strerror.h" +#include "http1.h" +#include "vquic.h" +#include "vquic_int.h" +#include "vquic-tls.h" +#include "curl_quiche.h" +#include "transfer.h" +#include "inet_pton.h" +#include "vtls/openssl.h" +#include "vtls/keylog.h" +#include "vtls/vtls.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* HTTP/3 error values defined in RFC 9114, ch. 8.1 */ +#define CURL_H3_NO_ERROR (0x0100) + +#define QUIC_MAX_STREAMS (100) + +#define H3_STREAM_WINDOW_SIZE (128 * 1024) +#define H3_STREAM_CHUNK_SIZE (16 * 1024) +/* The pool keeps spares around and half of a full stream windows + * seems good. More does not seem to improve performance. + * The benefit of the pool is that stream buffer to not keep + * spares. So memory consumption goes down when streams run empty, + * have a large upload done, etc. */ +#define H3_STREAM_POOL_SPARES \ + (H3_STREAM_WINDOW_SIZE / H3_STREAM_CHUNK_SIZE ) / 2 +/* Receive and Send max number of chunks just follows from the + * chunk size and window size */ +#define H3_STREAM_RECV_CHUNKS \ + (H3_STREAM_WINDOW_SIZE / H3_STREAM_CHUNK_SIZE) +#define H3_STREAM_SEND_CHUNKS \ + (H3_STREAM_WINDOW_SIZE / H3_STREAM_CHUNK_SIZE) + +/* + * Store quiche version info in this buffer. + */ +void Curl_quiche_ver(char *p, size_t len) +{ + (void)msnprintf(p, len, "quiche/%s", quiche_version()); +} + +struct cf_quiche_ctx { + struct cf_quic_ctx q; + struct ssl_peer peer; + struct curl_tls_ctx tls; + quiche_conn *qconn; + quiche_config *cfg; + quiche_h3_conn *h3c; + quiche_h3_config *h3config; + uint8_t scid[QUICHE_MAX_CONN_ID_LEN]; + struct curltime started_at; /* time the current attempt started */ + struct curltime handshake_at; /* time connect handshake finished */ + struct curltime reconnect_at; /* time the next attempt should start */ + struct bufc_pool stream_bufcp; /* chunk pool for streams */ + struct Curl_hash streams; /* hash `data->id` to `stream_ctx` */ + curl_off_t data_recvd; + BIT(goaway); /* got GOAWAY from server */ + BIT(x509_store_setup); /* if x509 store has been set up */ +}; + +#ifdef DEBUG_QUICHE +static void quiche_debug_log(const char *line, void *argp) +{ + (void)argp; + fprintf(stderr, "%s\n", line); +} +#endif + +static void cf_quiche_ctx_clear(struct cf_quiche_ctx *ctx) +{ + if(ctx) { + if(ctx->h3c) + quiche_h3_conn_free(ctx->h3c); + if(ctx->h3config) + quiche_h3_config_free(ctx->h3config); + if(ctx->qconn) + quiche_conn_free(ctx->qconn); + if(ctx->cfg) + quiche_config_free(ctx->cfg); + /* quiche just freed it */ + ctx->tls.ossl.ssl = NULL; + Curl_vquic_tls_cleanup(&ctx->tls); + Curl_ssl_peer_cleanup(&ctx->peer); + vquic_ctx_free(&ctx->q); + Curl_bufcp_free(&ctx->stream_bufcp); + Curl_hash_clean(&ctx->streams); + Curl_hash_destroy(&ctx->streams); + + memset(ctx, 0, sizeof(*ctx)); + } +} + +static CURLcode cf_flush_egress(struct Curl_cfilter *cf, + struct Curl_easy *data); + +/** + * All about the H3 internals of a stream + */ +struct stream_ctx { + curl_uint64_t id; /* HTTP/3 protocol stream identifier */ + struct bufq recvbuf; /* h3 response */ + struct h1_req_parser h1; /* h1 request parsing */ + curl_uint64_t error3; /* HTTP/3 stream error code */ + curl_off_t upload_left; /* number of request bytes left to upload */ + BIT(opened); /* TRUE after stream has been opened */ + BIT(closed); /* TRUE on stream close */ + BIT(reset); /* TRUE on stream reset */ + BIT(send_closed); /* stream is locally closed */ + BIT(resp_hds_complete); /* final response has been received */ + BIT(resp_got_header); /* TRUE when h3 stream has recvd some HEADER */ + BIT(quic_flow_blocked); /* stream is blocked by QUIC flow control */ +}; + +#define H3_STREAM_CTX(ctx,data) ((struct stream_ctx *)(\ + data? Curl_hash_offt_get(&(ctx)->streams, (data)->id) : NULL)) + +static void h3_stream_ctx_free(struct stream_ctx *stream) +{ + Curl_bufq_free(&stream->recvbuf); + Curl_h1_req_parse_free(&stream->h1); + free(stream); +} + +static void h3_stream_hash_free(void *stream) +{ + DEBUGASSERT(stream); + h3_stream_ctx_free((struct stream_ctx *)stream); +} + +static void check_resumes(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct Curl_easy *sdata; + struct stream_ctx *stream; + + DEBUGASSERT(data->multi); + for(sdata = data->multi->easyp; sdata; sdata = sdata->next) { + if(sdata->conn == data->conn) { + stream = H3_STREAM_CTX(ctx, sdata); + if(stream && stream->quic_flow_blocked) { + stream->quic_flow_blocked = FALSE; + Curl_expire(data, 0, EXPIRE_RUN_NOW); + CURL_TRC_CF(data, cf, "[%"CURL_PRIu64"] unblock", stream->id); + } + } + } +} + +static CURLcode h3_data_setup(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + if(stream) + return CURLE_OK; + + stream = calloc(1, sizeof(*stream)); + if(!stream) + return CURLE_OUT_OF_MEMORY; + + stream->id = -1; + Curl_bufq_initp(&stream->recvbuf, &ctx->stream_bufcp, + H3_STREAM_RECV_CHUNKS, BUFQ_OPT_SOFT_LIMIT); + Curl_h1_req_parse_init(&stream->h1, H1_PARSE_DEFAULT_MAX_LINE_LEN); + + if(!Curl_hash_offt_set(&ctx->streams, data->id, stream)) { + h3_stream_ctx_free(stream); + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} + +static void h3_data_done(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURLcode result; + + (void)cf; + if(stream) { + CURL_TRC_CF(data, cf, "[%"CURL_PRIu64"] easy handle is done", stream->id); + if(ctx->qconn && !stream->closed) { + quiche_conn_stream_shutdown(ctx->qconn, stream->id, + QUICHE_SHUTDOWN_READ, CURL_H3_NO_ERROR); + if(!stream->send_closed) { + quiche_conn_stream_shutdown(ctx->qconn, stream->id, + QUICHE_SHUTDOWN_WRITE, CURL_H3_NO_ERROR); + stream->send_closed = TRUE; + } + stream->closed = TRUE; + result = cf_flush_egress(cf, data); + if(result) + CURL_TRC_CF(data, cf, "data_done, flush egress -> %d", result); + } + Curl_hash_offt_remove(&ctx->streams, data->id); + } +} + +static void drain_stream(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + unsigned char bits; + + (void)cf; + bits = CURL_CSELECT_IN; + if(stream && !stream->send_closed && stream->upload_left) + bits |= CURL_CSELECT_OUT; + if(data->state.select_bits != bits) { + data->state.select_bits = bits; + Curl_expire(data, 0, EXPIRE_RUN_NOW); + } +} + +static struct Curl_easy *get_stream_easy(struct Curl_cfilter *cf, + struct Curl_easy *data, + curl_uint64_t stream_id, + struct stream_ctx **pstream) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct Curl_easy *sdata; + struct stream_ctx *stream; + + (void)cf; + stream = H3_STREAM_CTX(ctx, data); + if(stream && stream->id == stream_id) { + *pstream = stream; + return data; + } + else { + DEBUGASSERT(data->multi); + for(sdata = data->multi->easyp; sdata; sdata = sdata->next) { + if(sdata->conn != data->conn) + continue; + stream = H3_STREAM_CTX(ctx, sdata); + if(stream && stream->id == stream_id) { + *pstream = stream; + return sdata; + } + } + } + *pstream = NULL; + return NULL; +} + +static void cf_quiche_expire_conn_closed(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct Curl_easy *sdata; + + DEBUGASSERT(data->multi); + CURL_TRC_CF(data, cf, "conn closed, expire all transfers"); + for(sdata = data->multi->easyp; sdata; sdata = sdata->next) { + if(sdata == data || sdata->conn != data->conn) + continue; + CURL_TRC_CF(sdata, cf, "conn closed, expire transfer"); + Curl_expire(sdata, 0, EXPIRE_RUN_NOW); + } +} + +/* + * write_resp_raw() copies response data in raw format to the `data`'s + * receive buffer. If not enough space is available, it appends to the + * `data`'s overflow buffer. + */ +static CURLcode write_resp_raw(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *mem, size_t memlen) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURLcode result = CURLE_OK; + ssize_t nwritten; + + (void)cf; + if(!stream) + return CURLE_RECV_ERROR; + nwritten = Curl_bufq_write(&stream->recvbuf, mem, memlen, &result); + if(nwritten < 0) + return result; + + if((size_t)nwritten < memlen) { + /* This MUST not happen. Our recbuf is dimensioned to hold the + * full max_stream_window and then some for this very reason. */ + DEBUGASSERT(0); + return CURLE_RECV_ERROR; + } + return result; +} + +struct cb_ctx { + struct Curl_cfilter *cf; + struct Curl_easy *data; +}; + +static int cb_each_header(uint8_t *name, size_t name_len, + uint8_t *value, size_t value_len, + void *argp) +{ + struct cb_ctx *x = argp; + struct cf_quiche_ctx *ctx = x->cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, x->data); + CURLcode result; + + if(!stream) + return CURLE_OK; + + if((name_len == 7) && !strncmp(HTTP_PSEUDO_STATUS, (char *)name, 7)) { + CURL_TRC_CF(x->data, x->cf, "[%" CURL_PRIu64 "] status: %.*s", + stream->id, (int)value_len, value); + result = write_resp_raw(x->cf, x->data, "HTTP/3 ", sizeof("HTTP/3 ") - 1); + if(!result) + result = write_resp_raw(x->cf, x->data, value, value_len); + if(!result) + result = write_resp_raw(x->cf, x->data, " \r\n", 3); + } + else { + CURL_TRC_CF(x->data, x->cf, "[%" CURL_PRIu64 "] header: %.*s: %.*s", + stream->id, (int)name_len, name, + (int)value_len, value); + result = write_resp_raw(x->cf, x->data, name, name_len); + if(!result) + result = write_resp_raw(x->cf, x->data, ": ", 2); + if(!result) + result = write_resp_raw(x->cf, x->data, value, value_len); + if(!result) + result = write_resp_raw(x->cf, x->data, "\r\n", 2); + } + if(result) { + CURL_TRC_CF(x->data, x->cf, "[%"CURL_PRIu64"] on header error %d", + stream->id, result); + } + return result; +} + +static ssize_t stream_resp_read(void *reader_ctx, + unsigned char *buf, size_t len, + CURLcode *err) +{ + struct cb_ctx *x = reader_ctx; + struct cf_quiche_ctx *ctx = x->cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, x->data); + ssize_t nread; + + if(!stream) { + *err = CURLE_RECV_ERROR; + return -1; + } + + nread = quiche_h3_recv_body(ctx->h3c, ctx->qconn, stream->id, + buf, len); + if(nread >= 0) { + *err = CURLE_OK; + return nread; + } + else { + *err = CURLE_AGAIN; + return -1; + } +} + +static CURLcode cf_recv_body(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + ssize_t nwritten; + struct cb_ctx cb_ctx; + CURLcode result = CURLE_OK; + + if(!stream) + return CURLE_RECV_ERROR; + + if(!stream->resp_hds_complete) { + result = write_resp_raw(cf, data, "\r\n", 2); + if(result) + return result; + stream->resp_hds_complete = TRUE; + } + + cb_ctx.cf = cf; + cb_ctx.data = data; + nwritten = Curl_bufq_slurp(&stream->recvbuf, + stream_resp_read, &cb_ctx, &result); + + if(nwritten < 0 && result != CURLE_AGAIN) { + CURL_TRC_CF(data, cf, "[%"CURL_PRIu64"] recv_body error %zd", + stream->id, nwritten); + failf(data, "Error %d in HTTP/3 response body for stream[%"CURL_PRIu64"]", + result, stream->id); + stream->closed = TRUE; + stream->reset = TRUE; + stream->send_closed = TRUE; + streamclose(cf->conn, "Reset of stream"); + return result; + } + return CURLE_OK; +} + +#ifdef DEBUGBUILD +static const char *cf_ev_name(quiche_h3_event *ev) +{ + switch(quiche_h3_event_type(ev)) { + case QUICHE_H3_EVENT_HEADERS: + return "HEADERS"; + case QUICHE_H3_EVENT_DATA: + return "DATA"; + case QUICHE_H3_EVENT_RESET: + return "RESET"; + case QUICHE_H3_EVENT_FINISHED: + return "FINISHED"; + case QUICHE_H3_EVENT_GOAWAY: + return "GOAWAY"; + default: + return "Unknown"; + } +} +#else +#define cf_ev_name(x) "" +#endif + +static CURLcode h3_process_event(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct stream_ctx *stream, + quiche_h3_event *ev) +{ + struct cb_ctx cb_ctx; + CURLcode result = CURLE_OK; + int rc; + + if(!stream) + return CURLE_OK; + switch(quiche_h3_event_type(ev)) { + case QUICHE_H3_EVENT_HEADERS: + stream->resp_got_header = TRUE; + cb_ctx.cf = cf; + cb_ctx.data = data; + rc = quiche_h3_event_for_each_header(ev, cb_each_header, &cb_ctx); + if(rc) { + failf(data, "Error %d in HTTP/3 response header for stream[%" + CURL_PRIu64"]", rc, stream->id); + return CURLE_RECV_ERROR; + } + CURL_TRC_CF(data, cf, "[%"CURL_PRIu64"] <- [HEADERS]", stream->id); + break; + + case QUICHE_H3_EVENT_DATA: + if(!stream->closed) { + result = cf_recv_body(cf, data); + } + break; + + case QUICHE_H3_EVENT_RESET: + CURL_TRC_CF(data, cf, "[%"CURL_PRIu64"] RESET", stream->id); + stream->closed = TRUE; + stream->reset = TRUE; + stream->send_closed = TRUE; + streamclose(cf->conn, "Reset of stream"); + break; + + case QUICHE_H3_EVENT_FINISHED: + CURL_TRC_CF(data, cf, "[%"CURL_PRIu64"] CLOSED", stream->id); + if(!stream->resp_hds_complete) { + result = write_resp_raw(cf, data, "\r\n", 2); + if(result) + return result; + stream->resp_hds_complete = TRUE; + } + stream->closed = TRUE; + streamclose(cf->conn, "End of stream"); + break; + + case QUICHE_H3_EVENT_GOAWAY: + CURL_TRC_CF(data, cf, "[%"CURL_PRIu64"] <- [GOAWAY]", stream->id); + break; + + default: + CURL_TRC_CF(data, cf, "[%"CURL_PRIu64"] recv, unhandled event %d", + stream->id, quiche_h3_event_type(ev)); + break; + } + return result; +} + +static CURLcode cf_poll_events(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct stream_ctx *stream = NULL; + struct Curl_easy *sdata; + quiche_h3_event *ev; + CURLcode result; + + /* Take in the events and distribute them to the transfers. */ + while(ctx->h3c) { + curl_int64_t stream3_id = quiche_h3_conn_poll(ctx->h3c, ctx->qconn, &ev); + if(stream3_id == QUICHE_H3_ERR_DONE) { + break; + } + else if(stream3_id < 0) { + CURL_TRC_CF(data, cf, "error poll: %"CURL_PRId64, stream3_id); + return CURLE_HTTP3; + } + + sdata = get_stream_easy(cf, data, stream3_id, &stream); + if(!sdata || !stream) { + CURL_TRC_CF(data, cf, "discard event %s for unknown [%"CURL_PRId64"]", + cf_ev_name(ev), stream3_id); + } + else { + result = h3_process_event(cf, sdata, stream, ev); + drain_stream(cf, sdata); + if(result) { + CURL_TRC_CF(data, cf, "error processing event %s " + "for [%"CURL_PRIu64"] -> %d", cf_ev_name(ev), + stream3_id, result); + if(data == sdata) { + /* Only report this error to the caller if it is about the + * transfer we were called with. Otherwise we fail a transfer + * due to a problem in another one. */ + quiche_h3_event_free(ev); + return result; + } + } + quiche_h3_event_free(ev); + } + } + return CURLE_OK; +} + +struct recv_ctx { + struct Curl_cfilter *cf; + struct Curl_easy *data; + int pkts; +}; + +static CURLcode recv_pkt(const unsigned char *pkt, size_t pktlen, + struct sockaddr_storage *remote_addr, + socklen_t remote_addrlen, int ecn, + void *userp) +{ + struct recv_ctx *r = userp; + struct cf_quiche_ctx *ctx = r->cf->ctx; + quiche_recv_info recv_info; + ssize_t nread; + + (void)ecn; + ++r->pkts; + + recv_info.to = (struct sockaddr *)&ctx->q.local_addr; + recv_info.to_len = ctx->q.local_addrlen; + recv_info.from = (struct sockaddr *)remote_addr; + recv_info.from_len = remote_addrlen; + + nread = quiche_conn_recv(ctx->qconn, (unsigned char *)pkt, pktlen, + &recv_info); + if(nread < 0) { + if(QUICHE_ERR_DONE == nread) { + if(quiche_conn_is_draining(ctx->qconn)) { + CURL_TRC_CF(r->data, r->cf, "ingress, connection is draining"); + return CURLE_RECV_ERROR; + } + if(quiche_conn_is_closed(ctx->qconn)) { + CURL_TRC_CF(r->data, r->cf, "ingress, connection is closed"); + return CURLE_RECV_ERROR; + } + CURL_TRC_CF(r->data, r->cf, "ingress, quiche is DONE"); + return CURLE_OK; + } + else if(QUICHE_ERR_TLS_FAIL == nread) { + long verify_ok = SSL_get_verify_result(ctx->tls.ossl.ssl); + if(verify_ok != X509_V_OK) { + failf(r->data, "SSL certificate problem: %s", + X509_verify_cert_error_string(verify_ok)); + return CURLE_PEER_FAILED_VERIFICATION; + } + } + else { + failf(r->data, "quiche_conn_recv() == %zd", nread); + return CURLE_RECV_ERROR; + } + } + else if((size_t)nread < pktlen) { + CURL_TRC_CF(r->data, r->cf, "ingress, quiche only read %zd/%zu bytes", + nread, pktlen); + } + + return CURLE_OK; +} + +static CURLcode cf_process_ingress(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct recv_ctx rctx; + CURLcode result; + + DEBUGASSERT(ctx->qconn); + result = Curl_vquic_tls_before_recv(&ctx->tls, cf, data); + if(result) + return result; + + rctx.cf = cf; + rctx.data = data; + rctx.pkts = 0; + + result = vquic_recv_packets(cf, data, &ctx->q, 1000, recv_pkt, &rctx); + if(result) + return result; + + if(rctx.pkts > 0) { + /* quiche digested ingress packets. It might have opened flow control + * windows again. */ + check_resumes(cf, data); + } + return cf_poll_events(cf, data); +} + +struct read_ctx { + struct Curl_cfilter *cf; + struct Curl_easy *data; + quiche_send_info send_info; +}; + +static ssize_t read_pkt_to_send(void *userp, + unsigned char *buf, size_t buflen, + CURLcode *err) +{ + struct read_ctx *x = userp; + struct cf_quiche_ctx *ctx = x->cf->ctx; + ssize_t nwritten; + + nwritten = quiche_conn_send(ctx->qconn, buf, buflen, &x->send_info); + if(nwritten == QUICHE_ERR_DONE) { + *err = CURLE_AGAIN; + return -1; + } + + if(nwritten < 0) { + failf(x->data, "quiche_conn_send returned %zd", nwritten); + *err = CURLE_SEND_ERROR; + return -1; + } + *err = CURLE_OK; + return nwritten; +} + +/* + * flush_egress drains the buffers and sends off data. + * Calls failf() on errors. + */ +static CURLcode cf_flush_egress(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + ssize_t nread; + CURLcode result; + curl_int64_t expiry_ns; + curl_int64_t timeout_ns; + struct read_ctx readx; + size_t pkt_count, gsolen; + + expiry_ns = quiche_conn_timeout_as_nanos(ctx->qconn); + if(!expiry_ns) { + quiche_conn_on_timeout(ctx->qconn); + if(quiche_conn_is_closed(ctx->qconn)) { + if(quiche_conn_is_timed_out(ctx->qconn)) + failf(data, "connection closed by idle timeout"); + else + failf(data, "connection closed by server"); + /* Connection timed out, expire all transfers belonging to it + * as will not get any more POLL events here. */ + cf_quiche_expire_conn_closed(cf, data); + return CURLE_SEND_ERROR; + } + } + + result = vquic_flush(cf, data, &ctx->q); + if(result) { + if(result == CURLE_AGAIN) { + Curl_expire(data, 1, EXPIRE_QUIC); + return CURLE_OK; + } + return result; + } + + readx.cf = cf; + readx.data = data; + memset(&readx.send_info, 0, sizeof(readx.send_info)); + pkt_count = 0; + gsolen = quiche_conn_max_send_udp_payload_size(ctx->qconn); + for(;;) { + /* add the next packet to send, if any, to our buffer */ + nread = Curl_bufq_sipn(&ctx->q.sendbuf, 0, + read_pkt_to_send, &readx, &result); + if(nread < 0) { + if(result != CURLE_AGAIN) + return result; + /* Nothing more to add, flush and leave */ + result = vquic_send(cf, data, &ctx->q, gsolen); + if(result) { + if(result == CURLE_AGAIN) { + Curl_expire(data, 1, EXPIRE_QUIC); + return CURLE_OK; + } + return result; + } + goto out; + } + + ++pkt_count; + if((size_t)nread < gsolen || pkt_count >= MAX_PKT_BURST) { + result = vquic_send(cf, data, &ctx->q, gsolen); + if(result) { + if(result == CURLE_AGAIN) { + Curl_expire(data, 1, EXPIRE_QUIC); + return CURLE_OK; + } + goto out; + } + pkt_count = 0; + } + } + +out: + timeout_ns = quiche_conn_timeout_as_nanos(ctx->qconn); + if(timeout_ns % 1000000) + timeout_ns += 1000000; + /* expire resolution is milliseconds */ + Curl_expire(data, (timeout_ns / 1000000), EXPIRE_QUIC); + return result; +} + +static ssize_t recv_closed_stream(struct Curl_cfilter *cf, + struct Curl_easy *data, + CURLcode *err) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + ssize_t nread = -1; + + DEBUGASSERT(stream); + if(stream->reset) { + failf(data, + "HTTP/3 stream %" CURL_PRIu64 " reset by server", stream->id); + *err = data->req.bytecount? CURLE_PARTIAL_FILE : CURLE_HTTP3; + CURL_TRC_CF(data, cf, "[%" CURL_PRIu64 "] cf_recv, was reset -> %d", + stream->id, *err); + } + else if(!stream->resp_got_header) { + failf(data, + "HTTP/3 stream %" CURL_PRIu64 " was closed cleanly, but before " + "getting all response header fields, treated as error", + stream->id); + /* *err = CURLE_PARTIAL_FILE; */ + *err = CURLE_HTTP3; + CURL_TRC_CF(data, cf, "[%" CURL_PRIu64 "] cf_recv, closed incomplete" + " -> %d", stream->id, *err); + } + else { + *err = CURLE_OK; + nread = 0; + } + return nread; +} + +static ssize_t cf_quiche_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, CURLcode *err) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + ssize_t nread = -1; + CURLcode result; + + vquic_ctx_update_time(&ctx->q); + + if(!stream) { + *err = CURLE_RECV_ERROR; + return -1; + } + + if(!Curl_bufq_is_empty(&stream->recvbuf)) { + nread = Curl_bufq_read(&stream->recvbuf, + (unsigned char *)buf, len, err); + CURL_TRC_CF(data, cf, "[%" CURL_PRIu64 "] read recvbuf(len=%zu) " + "-> %zd, %d", stream->id, len, nread, *err); + if(nread < 0) + goto out; + } + + if(cf_process_ingress(cf, data)) { + CURL_TRC_CF(data, cf, "cf_recv, error on ingress"); + *err = CURLE_RECV_ERROR; + nread = -1; + goto out; + } + + /* recvbuf had nothing before, maybe after progressing ingress? */ + if(nread < 0 && !Curl_bufq_is_empty(&stream->recvbuf)) { + nread = Curl_bufq_read(&stream->recvbuf, + (unsigned char *)buf, len, err); + CURL_TRC_CF(data, cf, "[%" CURL_PRIu64 "] read recvbuf(len=%zu) " + "-> %zd, %d", stream->id, len, nread, *err); + if(nread < 0) + goto out; + } + + if(nread > 0) { + if(stream->closed) + drain_stream(cf, data); + } + else { + if(stream->closed) { + nread = recv_closed_stream(cf, data, err); + goto out; + } + else if(quiche_conn_is_draining(ctx->qconn)) { + failf(data, "QUIC connection is draining"); + *err = CURLE_HTTP3; + nread = -1; + goto out; + } + *err = CURLE_AGAIN; + nread = -1; + } + +out: + result = cf_flush_egress(cf, data); + if(result) { + CURL_TRC_CF(data, cf, "cf_recv, flush egress failed"); + *err = result; + nread = -1; + } + if(nread > 0) + ctx->data_recvd += nread; + CURL_TRC_CF(data, cf, "[%"CURL_PRIu64"] cf_recv(total=%" + CURL_FORMAT_CURL_OFF_T ") -> %zd, %d", + stream->id, ctx->data_recvd, nread, *err); + return nread; +} + +/* Index where :authority header field will appear in request header + field list. */ +#define AUTHORITY_DST_IDX 3 + +static ssize_t h3_open_stream(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *buf, size_t len, + CURLcode *err) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + size_t nheader, i; + curl_int64_t stream3_id; + struct dynhds h2_headers; + quiche_h3_header *nva = NULL; + ssize_t nwritten; + + if(!stream) { + *err = h3_data_setup(cf, data); + if(*err) { + return -1; + } + stream = H3_STREAM_CTX(ctx, data); + DEBUGASSERT(stream); + } + + Curl_dynhds_init(&h2_headers, 0, DYN_HTTP_REQUEST); + + DEBUGASSERT(stream); + nwritten = Curl_h1_req_parse_read(&stream->h1, buf, len, NULL, 0, err); + if(nwritten < 0) + goto out; + if(!stream->h1.done) { + /* need more data */ + goto out; + } + DEBUGASSERT(stream->h1.req); + + *err = Curl_http_req_to_h2(&h2_headers, stream->h1.req, data); + if(*err) { + nwritten = -1; + goto out; + } + /* no longer needed */ + Curl_h1_req_parse_free(&stream->h1); + + nheader = Curl_dynhds_count(&h2_headers); + nva = malloc(sizeof(quiche_h3_header) * nheader); + if(!nva) { + *err = CURLE_OUT_OF_MEMORY; + nwritten = -1; + goto out; + } + + for(i = 0; i < nheader; ++i) { + struct dynhds_entry *e = Curl_dynhds_getn(&h2_headers, i); + nva[i].name = (unsigned char *)e->name; + nva[i].name_len = e->namelen; + nva[i].value = (unsigned char *)e->value; + nva[i].value_len = e->valuelen; + } + + switch(data->state.httpreq) { + case HTTPREQ_POST: + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + case HTTPREQ_PUT: + if(data->state.infilesize != -1) + stream->upload_left = data->state.infilesize; + else + /* data sending without specifying the data amount up front */ + stream->upload_left = -1; /* unknown */ + break; + default: + stream->upload_left = 0; /* no request body */ + break; + } + + if(stream->upload_left == 0) + stream->send_closed = TRUE; + + stream3_id = quiche_h3_send_request(ctx->h3c, ctx->qconn, nva, nheader, + stream->send_closed); + if(stream3_id < 0) { + if(QUICHE_H3_ERR_STREAM_BLOCKED == stream3_id) { + /* quiche seems to report this error if the connection window is + * exhausted. Which happens frequently and intermittent. */ + CURL_TRC_CF(data, cf, "[%"CURL_PRIu64"] blocked", stream->id); + stream->quic_flow_blocked = TRUE; + *err = CURLE_AGAIN; + nwritten = -1; + goto out; + } + else { + CURL_TRC_CF(data, cf, "send_request(%s) -> %" CURL_PRIu64, + data->state.url, stream3_id); + } + *err = CURLE_SEND_ERROR; + nwritten = -1; + goto out; + } + + DEBUGASSERT(!stream->opened); + *err = CURLE_OK; + stream->id = stream3_id; + stream->opened = TRUE; + stream->closed = FALSE; + stream->reset = FALSE; + + if(Curl_trc_is_verbose(data)) { + infof(data, "[HTTP/3] [%" CURL_PRIu64 "] OPENED stream for %s", + stream->id, data->state.url); + for(i = 0; i < nheader; ++i) { + infof(data, "[HTTP/3] [%" CURL_PRIu64 "] [%.*s: %.*s]", stream->id, + (int)nva[i].name_len, nva[i].name, + (int)nva[i].value_len, nva[i].value); + } + } + +out: + free(nva); + Curl_dynhds_free(&h2_headers); + return nwritten; +} + +static ssize_t cf_quiche_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *buf, size_t len, CURLcode *err) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURLcode result; + ssize_t nwritten; + + vquic_ctx_update_time(&ctx->q); + + *err = cf_process_ingress(cf, data); + if(*err) { + nwritten = -1; + goto out; + } + + if(!stream || !stream->opened) { + nwritten = h3_open_stream(cf, data, buf, len, err); + if(nwritten < 0) + goto out; + stream = H3_STREAM_CTX(ctx, data); + } + else if(stream->closed) { + if(stream->resp_hds_complete) { + /* sending request body on a stream that has been closed by the + * server. If the server has send us a final response, we should + * silently discard the send data. + * This happens for example on redirects where the server, instead + * of reading the full request body just closed the stream after + * sending the 30x response. + * This is sort of a race: had the transfer loop called recv first, + * it would see the response and stop/discard sending on its own- */ + CURL_TRC_CF(data, cf, "[%" CURL_PRIu64 "] discarding data" + "on closed stream with response", stream->id); + *err = CURLE_OK; + nwritten = (ssize_t)len; + goto out; + } + CURL_TRC_CF(data, cf, "[%" CURL_PRIu64 "] send_body(len=%zu) " + "-> stream closed", stream->id, len); + *err = CURLE_HTTP3; + nwritten = -1; + goto out; + } + else { + bool eof = (stream->upload_left >= 0 && + (curl_off_t)len >= stream->upload_left); + nwritten = quiche_h3_send_body(ctx->h3c, ctx->qconn, stream->id, + (uint8_t *)buf, len, eof); + if(nwritten == QUICHE_H3_ERR_DONE || (nwritten == 0 && len > 0)) { + /* TODO: we seem to be blocked on flow control and should HOLD + * sending. But when do we open again? */ + if(!quiche_conn_stream_writable(ctx->qconn, stream->id, len)) { + CURL_TRC_CF(data, cf, "[%" CURL_PRIu64 "] send_body(len=%zu) " + "-> window exhausted", stream->id, len); + stream->quic_flow_blocked = TRUE; + } + *err = CURLE_AGAIN; + nwritten = -1; + goto out; + } + else if(nwritten == QUICHE_H3_TRANSPORT_ERR_INVALID_STREAM_STATE) { + CURL_TRC_CF(data, cf, "[%" CURL_PRIu64 "] send_body(len=%zu) " + "-> invalid stream state", stream->id, len); + *err = CURLE_HTTP3; + nwritten = -1; + goto out; + } + else if(nwritten == QUICHE_H3_TRANSPORT_ERR_FINAL_SIZE) { + CURL_TRC_CF(data, cf, "[%" CURL_PRIu64 "] send_body(len=%zu) " + "-> exceeds size", stream->id, len); + *err = CURLE_SEND_ERROR; + nwritten = -1; + goto out; + } + else if(nwritten < 0) { + CURL_TRC_CF(data, cf, "[%" CURL_PRIu64 "] send_body(len=%zu) " + "-> quiche err %zd", stream->id, len, nwritten); + *err = CURLE_SEND_ERROR; + nwritten = -1; + goto out; + } + else { + /* quiche accepted all or at least a part of the buf */ + if(stream->upload_left > 0) { + stream->upload_left = (nwritten < stream->upload_left)? + (stream->upload_left - nwritten) : 0; + } + if(stream->upload_left == 0) + stream->send_closed = TRUE; + + CURL_TRC_CF(data, cf, "[%" CURL_PRIu64 "] send body(len=%zu, " + "left=%" CURL_FORMAT_CURL_OFF_T ") -> %zd", + stream->id, len, stream->upload_left, nwritten); + *err = CURLE_OK; + } + } + +out: + result = cf_flush_egress(cf, data); + if(result) { + *err = result; + nwritten = -1; + } + CURL_TRC_CF(data, cf, "[%" CURL_PRIu64 "] cf_send(len=%zu) -> %zd, %d", + stream? stream->id : -1, len, nwritten, *err); + return nwritten; +} + +static bool stream_is_writeable(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + return stream && (quiche_conn_stream_writable( + ctx->qconn, (curl_uint64_t)stream->id, 1) > 0); +} + +static void cf_quiche_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + bool want_recv, want_send; + + if(!ctx->qconn) + return; + + Curl_pollset_check(data, ps, ctx->q.sockfd, &want_recv, &want_send); + if(want_recv || want_send) { + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + bool c_exhaust, s_exhaust; + + c_exhaust = FALSE; /* Have not found any call in quiche that tells + us if the connection itself is blocked */ + s_exhaust = want_send && stream && stream->opened && + (stream->quic_flow_blocked || !stream_is_writeable(cf, data)); + want_recv = (want_recv || c_exhaust || s_exhaust); + want_send = (!s_exhaust && want_send) || + !Curl_bufq_is_empty(&ctx->q.sendbuf); + + Curl_pollset_set(data, ps, ctx->q.sockfd, want_recv, want_send); + } +} + +/* + * Called from transfer.c:data_pending to know if we should keep looping + * to receive more data from the connection. + */ +static bool cf_quiche_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + const struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + (void)cf; + return stream && !Curl_bufq_is_empty(&stream->recvbuf); +} + +static CURLcode h3_data_pause(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool pause) +{ + /* TODO: there seems right now no API in quiche to shrink/enlarge + * the streams windows. As we do in HTTP/2. */ + if(!pause) { + drain_stream(cf, data); + Curl_expire(data, 0, EXPIRE_RUN_NOW); + } + return CURLE_OK; +} + +static CURLcode cf_quiche_data_event(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + (void)arg1; + (void)arg2; + switch(event) { + case CF_CTRL_DATA_SETUP: + break; + case CF_CTRL_DATA_PAUSE: + result = h3_data_pause(cf, data, (arg1 != 0)); + break; + case CF_CTRL_DATA_DETACH: + h3_data_done(cf, data); + break; + case CF_CTRL_DATA_DONE: + h3_data_done(cf, data); + break; + case CF_CTRL_DATA_DONE_SEND: { + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + if(stream && !stream->send_closed) { + unsigned char body[1]; + ssize_t sent; + + stream->send_closed = TRUE; + stream->upload_left = 0; + body[0] = 'X'; + sent = cf_quiche_send(cf, data, body, 0, &result); + CURL_TRC_CF(data, cf, "[%"CURL_PRIu64"] DONE_SEND -> %zd, %d", + stream->id, sent, result); + } + break; + } + case CF_CTRL_DATA_IDLE: { + struct stream_ctx *stream = H3_STREAM_CTX(ctx, data); + if(stream && !stream->closed) { + result = cf_flush_egress(cf, data); + if(result) + CURL_TRC_CF(data, cf, "data idle, flush egress -> %d", result); + } + break; + } + default: + break; + } + return result; +} + +static CURLcode cf_connect_start(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + int rv; + CURLcode result; + const struct Curl_sockaddr_ex *sockaddr; + + DEBUGASSERT(ctx->q.sockfd != CURL_SOCKET_BAD); + +#ifdef DEBUG_QUICHE + /* initialize debug log callback only once */ + static int debug_log_init = 0; + if(!debug_log_init) { + quiche_enable_debug_logging(quiche_debug_log, NULL); + debug_log_init = 1; + } +#endif + Curl_bufcp_init(&ctx->stream_bufcp, H3_STREAM_CHUNK_SIZE, + H3_STREAM_POOL_SPARES); + Curl_hash_offt_init(&ctx->streams, 63, h3_stream_hash_free); + ctx->data_recvd = 0; + + result = vquic_ctx_init(&ctx->q); + if(result) + return result; + + result = Curl_ssl_peer_init(&ctx->peer, cf, TRNSPRT_QUIC); + if(result) + return result; + + ctx->cfg = quiche_config_new(QUICHE_PROTOCOL_VERSION); + if(!ctx->cfg) { + failf(data, "can't create quiche config"); + return CURLE_FAILED_INIT; + } + quiche_config_enable_pacing(ctx->cfg, false); + quiche_config_set_max_idle_timeout(ctx->cfg, CURL_QUIC_MAX_IDLE_MS); + quiche_config_set_initial_max_data(ctx->cfg, (1 * 1024 * 1024) + /* (QUIC_MAX_STREAMS/2) * H3_STREAM_WINDOW_SIZE */); + quiche_config_set_initial_max_streams_bidi(ctx->cfg, QUIC_MAX_STREAMS); + quiche_config_set_initial_max_streams_uni(ctx->cfg, QUIC_MAX_STREAMS); + quiche_config_set_initial_max_stream_data_bidi_local(ctx->cfg, + H3_STREAM_WINDOW_SIZE); + quiche_config_set_initial_max_stream_data_bidi_remote(ctx->cfg, + H3_STREAM_WINDOW_SIZE); + quiche_config_set_initial_max_stream_data_uni(ctx->cfg, + H3_STREAM_WINDOW_SIZE); + quiche_config_set_disable_active_migration(ctx->cfg, TRUE); + + quiche_config_set_max_connection_window(ctx->cfg, + 10 * QUIC_MAX_STREAMS * H3_STREAM_WINDOW_SIZE); + quiche_config_set_max_stream_window(ctx->cfg, 10 * H3_STREAM_WINDOW_SIZE); + quiche_config_set_application_protos(ctx->cfg, + (uint8_t *) + QUICHE_H3_APPLICATION_PROTOCOL, + sizeof(QUICHE_H3_APPLICATION_PROTOCOL) + - 1); + + result = Curl_vquic_tls_init(&ctx->tls, cf, data, &ctx->peer, + QUICHE_H3_APPLICATION_PROTOCOL, + sizeof(QUICHE_H3_APPLICATION_PROTOCOL) - 1, + NULL, NULL, cf); + if(result) + return result; + + result = Curl_rand(data, ctx->scid, sizeof(ctx->scid)); + if(result) + return result; + + Curl_cf_socket_peek(cf->next, data, &ctx->q.sockfd, &sockaddr, NULL); + ctx->q.local_addrlen = sizeof(ctx->q.local_addr); + rv = getsockname(ctx->q.sockfd, (struct sockaddr *)&ctx->q.local_addr, + &ctx->q.local_addrlen); + if(rv == -1) + return CURLE_QUIC_CONNECT_ERROR; + + ctx->qconn = quiche_conn_new_with_tls((const uint8_t *)ctx->scid, + sizeof(ctx->scid), NULL, 0, + (struct sockaddr *)&ctx->q.local_addr, + ctx->q.local_addrlen, + &sockaddr->sa_addr, sockaddr->addrlen, + ctx->cfg, ctx->tls.ossl.ssl, false); + if(!ctx->qconn) { + failf(data, "can't create quiche connection"); + return CURLE_OUT_OF_MEMORY; + } + + /* Known to not work on Windows */ +#if !defined(_WIN32) && defined(HAVE_QUICHE_CONN_SET_QLOG_FD) + { + int qfd; + (void)Curl_qlogdir(data, ctx->scid, sizeof(ctx->scid), &qfd); + if(qfd != -1) + quiche_conn_set_qlog_fd(ctx->qconn, qfd, + "qlog title", "curl qlog"); + } +#endif + + result = cf_flush_egress(cf, data); + if(result) + return result; + + { + unsigned char alpn_protocols[] = QUICHE_H3_APPLICATION_PROTOCOL; + unsigned alpn_len, offset = 0; + + /* Replace each ALPN length prefix by a comma. */ + while(offset < sizeof(alpn_protocols) - 1) { + alpn_len = alpn_protocols[offset]; + alpn_protocols[offset] = ','; + offset += 1 + alpn_len; + } + + CURL_TRC_CF(data, cf, "Sent QUIC client Initial, ALPN: %s", + alpn_protocols + 1); + } + + return CURLE_OK; +} + +static CURLcode cf_quiche_verify_peer(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + + cf->conn->bits.multiplex = TRUE; /* at least potentially multiplexed */ + cf->conn->httpversion = 30; + cf->conn->bundle->multiuse = BUNDLE_MULTIPLEX; + + return Curl_vquic_tls_verify_peer(&ctx->tls, cf, data, &ctx->peer); +} + +static CURLcode cf_quiche_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + /* Connect the UDP filter first */ + if(!cf->next->connected) { + result = Curl_conn_cf_connect(cf->next, data, blocking, done); + if(result || !*done) + return result; + } + + *done = FALSE; + vquic_ctx_update_time(&ctx->q); + + if(ctx->reconnect_at.tv_sec && + Curl_timediff(ctx->q.last_op, ctx->reconnect_at) < 0) { + /* Not time yet to attempt the next connect */ + CURL_TRC_CF(data, cf, "waiting for reconnect time"); + goto out; + } + + if(!ctx->qconn) { + result = cf_connect_start(cf, data); + if(result) + goto out; + ctx->started_at = ctx->q.last_op; + result = cf_flush_egress(cf, data); + /* we do not expect to be able to recv anything yet */ + goto out; + } + + result = cf_process_ingress(cf, data); + if(result) + goto out; + + result = cf_flush_egress(cf, data); + if(result) + goto out; + + if(quiche_conn_is_established(ctx->qconn)) { + ctx->handshake_at = ctx->q.last_op; + CURL_TRC_CF(data, cf, "handshake complete after %dms", + (int)Curl_timediff(ctx->handshake_at, ctx->started_at)); + result = cf_quiche_verify_peer(cf, data); + if(!result) { + CURL_TRC_CF(data, cf, "peer verified"); + ctx->h3config = quiche_h3_config_new(); + if(!ctx->h3config) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + /* Create a new HTTP/3 connection on the QUIC connection. */ + ctx->h3c = quiche_h3_conn_new_with_transport(ctx->qconn, ctx->h3config); + if(!ctx->h3c) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + cf->connected = TRUE; + cf->conn->alpn = CURL_HTTP_VERSION_3; + *done = TRUE; + connkeep(cf->conn, "HTTP/3 default"); + } + } + else if(quiche_conn_is_draining(ctx->qconn)) { + /* When a QUIC server instance is shutting down, it may send us a + * CONNECTION_CLOSE right away. Our connection then enters the DRAINING + * state. The CONNECT may work in the near future again. Indicate + * that as a "weird" reply. */ + result = CURLE_WEIRD_SERVER_REPLY; + } + +out: +#ifndef CURL_DISABLE_VERBOSE_STRINGS + if(result && result != CURLE_AGAIN) { + struct ip_quadruple ip; + + Curl_cf_socket_peek(cf->next, data, NULL, NULL, &ip); + infof(data, "connect to %s port %u failed: %s", + ip.remote_ip, ip.remote_port, curl_easy_strerror(result)); + } +#endif + return result; +} + +static void cf_quiche_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + + if(ctx) { + if(ctx->qconn) { + vquic_ctx_update_time(&ctx->q); + (void)quiche_conn_close(ctx->qconn, TRUE, 0, NULL, 0); + /* flushing the egress is not a failsafe way to deliver all the + outstanding packets, but we also don't want to get stuck here... */ + (void)cf_flush_egress(cf, data); + } + cf_quiche_ctx_clear(ctx); + } +} + +static void cf_quiche_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + + (void)data; + cf_quiche_ctx_clear(ctx); + free(ctx); + cf->ctx = NULL; +} + +static CURLcode cf_quiche_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + + switch(query) { + case CF_QUERY_MAX_CONCURRENT: { + curl_uint64_t max_streams = CONN_INUSE(cf->conn); + if(!ctx->goaway) { + max_streams += quiche_conn_peer_streams_left_bidi(ctx->qconn); + } + *pres1 = (max_streams > INT_MAX)? INT_MAX : (int)max_streams; + CURL_TRC_CF(data, cf, "query conn[%" CURL_FORMAT_CURL_OFF_T "]: " + "MAX_CONCURRENT -> %d (%zu in use)", + cf->conn->connection_id, *pres1, CONN_INUSE(cf->conn)); + return CURLE_OK; + } + case CF_QUERY_CONNECT_REPLY_MS: + if(ctx->q.got_first_byte) { + timediff_t ms = Curl_timediff(ctx->q.first_byte_at, ctx->started_at); + *pres1 = (ms < INT_MAX)? (int)ms : INT_MAX; + } + else + *pres1 = -1; + return CURLE_OK; + case CF_QUERY_TIMER_CONNECT: { + struct curltime *when = pres2; + if(ctx->q.got_first_byte) + *when = ctx->q.first_byte_at; + return CURLE_OK; + } + case CF_QUERY_TIMER_APPCONNECT: { + struct curltime *when = pres2; + if(cf->connected) + *when = ctx->handshake_at; + return CURLE_OK; + } + default: + break; + } + return cf->next? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +static bool cf_quiche_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + bool alive = TRUE; + + *input_pending = FALSE; + if(!ctx->qconn) + return FALSE; + + if(quiche_conn_is_closed(ctx->qconn)) { + if(quiche_conn_is_timed_out(ctx->qconn)) + CURL_TRC_CF(data, cf, "connection was closed due to idle timeout"); + else + CURL_TRC_CF(data, cf, "connection is closed"); + return FALSE; + } + + if(!cf->next || !cf->next->cft->is_alive(cf->next, data, input_pending)) + return FALSE; + + if(*input_pending) { + /* This happens before we've sent off a request and the connection is + not in use by any other transfer, there shouldn't be any data here, + only "protocol frames" */ + *input_pending = FALSE; + if(cf_process_ingress(cf, data)) + alive = FALSE; + else { + alive = TRUE; + } + } + + return alive; +} + +struct Curl_cftype Curl_cft_http3 = { + "HTTP/3", + CF_TYPE_IP_CONNECT | CF_TYPE_SSL | CF_TYPE_MULTIPLEX, + 0, + cf_quiche_destroy, + cf_quiche_connect, + cf_quiche_close, + Curl_cf_def_get_host, + cf_quiche_adjust_pollset, + cf_quiche_data_pending, + cf_quiche_send, + cf_quiche_recv, + cf_quiche_data_event, + cf_quiche_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_quiche_query, +}; + +CURLcode Curl_cf_quiche_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai) +{ + struct cf_quiche_ctx *ctx = NULL; + struct Curl_cfilter *cf = NULL, *udp_cf = NULL; + CURLcode result; + + (void)data; + (void)conn; + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + result = Curl_cf_create(&cf, &Curl_cft_http3, ctx); + if(result) + goto out; + + result = Curl_cf_udp_create(&udp_cf, data, conn, ai, TRNSPRT_QUIC); + if(result) + goto out; + + udp_cf->conn = cf->conn; + udp_cf->sockindex = cf->sockindex; + cf->next = udp_cf; + +out: + *pcf = (!result)? cf : NULL; + if(result) { + if(udp_cf) + Curl_conn_cf_discard_sub(cf, udp_cf, data, TRUE); + Curl_safefree(cf); + Curl_safefree(ctx); + } + + return result; +} + +bool Curl_conn_is_quiche(const struct Curl_easy *data, + const struct connectdata *conn, + int sockindex) +{ + struct Curl_cfilter *cf = conn? conn->cfilter[sockindex] : NULL; + + (void)data; + for(; cf; cf = cf->next) { + if(cf->cft == &Curl_cft_http3) + return TRUE; + if(cf->cft->flags & CF_TYPE_IP_CONNECT) + return FALSE; + } + return FALSE; +} + +#endif diff --git a/third_party/curl/lib/vquic/curl_quiche.h b/third_party/curl/lib/vquic/curl_quiche.h new file mode 100644 index 0000000..bce781c --- /dev/null +++ b/third_party/curl/lib/vquic/curl_quiche.h @@ -0,0 +1,50 @@ +#ifndef HEADER_CURL_VQUIC_CURL_QUICHE_H +#define HEADER_CURL_VQUIC_CURL_QUICHE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_QUICHE + +#include +#include + +struct Curl_cfilter; +struct Curl_easy; + +void Curl_quiche_ver(char *p, size_t len); + +CURLcode Curl_cf_quiche_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai); + +bool Curl_conn_is_quiche(const struct Curl_easy *data, + const struct connectdata *conn, + int sockindex); + +#endif + +#endif /* HEADER_CURL_VQUIC_CURL_QUICHE_H */ diff --git a/third_party/curl/lib/vquic/vquic-tls.c b/third_party/curl/lib/vquic/vquic-tls.c new file mode 100644 index 0000000..aca18b4 --- /dev/null +++ b/third_party/curl/lib/vquic/vquic-tls.c @@ -0,0 +1,342 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_HTTP3) && \ + (defined(USE_OPENSSL) || defined(USE_GNUTLS) || defined(USE_WOLFSSL)) + +#ifdef USE_OPENSSL +#include +#include "vtls/openssl.h" +#elif defined(USE_GNUTLS) +#include +#include +#include +#include +#include +#include "vtls/gtls.h" +#elif defined(USE_WOLFSSL) +#include +#include +#include +#include "vtls/wolfssl.h" +#endif + +#include "urldata.h" +#include "curl_trc.h" +#include "cfilters.h" +#include "multiif.h" +#include "vtls/keylog.h" +#include "vtls/vtls.h" +#include "vquic-tls.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#ifndef ARRAYSIZE +#define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) +#endif + +#if defined(USE_WOLFSSL) + +#define QUIC_CIPHERS \ + "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_" \ + "POLY1305_SHA256:TLS_AES_128_CCM_SHA256" +#define QUIC_GROUPS "P-256:P-384:P-521" + +#if defined(HAVE_SECRET_CALLBACK) +static void keylog_callback(const WOLFSSL *ssl, const char *line) +{ + (void)ssl; + Curl_tls_keylog_write_line(line); +} +#endif + +static CURLcode curl_wssl_init_ctx(struct curl_tls_ctx *ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + Curl_vquic_tls_ctx_setup *cb_setup, + void *cb_user_data) +{ + struct ssl_primary_config *conn_config; + CURLcode result = CURLE_FAILED_INIT; + + conn_config = Curl_ssl_cf_get_primary_config(cf); + if(!conn_config) { + result = CURLE_FAILED_INIT; + goto out; + } + + ctx->ssl_ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method()); + if(!ctx->ssl_ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + if(cb_setup) { + result = cb_setup(cf, data, cb_user_data); + if(result) + goto out; + } + + wolfSSL_CTX_set_default_verify_paths(ctx->ssl_ctx); + + if(wolfSSL_CTX_set_cipher_list(ctx->ssl_ctx, conn_config->cipher_list13 ? + conn_config->cipher_list13 : + QUIC_CIPHERS) != 1) { + char error_buffer[256]; + ERR_error_string_n(ERR_get_error(), error_buffer, sizeof(error_buffer)); + failf(data, "wolfSSL failed to set ciphers: %s", error_buffer); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + + if(wolfSSL_CTX_set1_groups_list(ctx->ssl_ctx, conn_config->curves ? + conn_config->curves : + (char *)QUIC_GROUPS) != 1) { + failf(data, "wolfSSL failed to set curves"); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + + /* Open the file if a TLS or QUIC backend has not done this before. */ + Curl_tls_keylog_open(); + if(Curl_tls_keylog_enabled()) { +#if defined(HAVE_SECRET_CALLBACK) + wolfSSL_CTX_set_keylog_callback(ctx->ssl_ctx, keylog_callback); +#else + failf(data, "wolfSSL was built without keylog callback"); + result = CURLE_NOT_BUILT_IN; + goto out; +#endif + } + + if(conn_config->verifypeer) { + const char * const ssl_cafile = conn_config->CAfile; + const char * const ssl_capath = conn_config->CApath; + + wolfSSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, NULL); + if(ssl_cafile || ssl_capath) { + /* tell wolfSSL where to find CA certificates that are used to verify + the server's certificate. */ + int rc = + wolfSSL_CTX_load_verify_locations_ex(ctx->ssl_ctx, ssl_cafile, + ssl_capath, + WOLFSSL_LOAD_FLAG_IGNORE_ERR); + if(SSL_SUCCESS != rc) { + /* Fail if we insist on successfully verifying the server. */ + failf(data, "error setting certificate verify locations:" + " CAfile: %s CApath: %s", + ssl_cafile ? ssl_cafile : "none", + ssl_capath ? ssl_capath : "none"); + result = CURLE_SSL_CACERT_BADFILE; + goto out; + } + infof(data, " CAfile: %s", ssl_cafile ? ssl_cafile : "none"); + infof(data, " CApath: %s", ssl_capath ? ssl_capath : "none"); + } +#ifdef CURL_CA_FALLBACK + else { + /* verifying the peer without any CA certificates won't work so + use wolfssl's built-in default as fallback */ + wolfSSL_CTX_set_default_verify_paths(ctx->ssl_ctx); + } +#endif + } + else { + wolfSSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_NONE, NULL); + } + + /* give application a chance to interfere with SSL set up. */ + if(data->set.ssl.fsslctx) { + Curl_set_in_callback(data, true); + result = (*data->set.ssl.fsslctx)(data, ctx->ssl_ctx, + data->set.ssl.fsslctxp); + Curl_set_in_callback(data, false); + if(result) { + failf(data, "error signaled by ssl ctx callback"); + goto out; + } + } + result = CURLE_OK; + +out: + if(result && ctx->ssl_ctx) { + SSL_CTX_free(ctx->ssl_ctx); + ctx->ssl_ctx = NULL; + } + return result; +} + +/** SSL callbacks ***/ + +static CURLcode curl_wssl_init_ssl(struct curl_tls_ctx *ctx, + struct Curl_easy *data, + struct ssl_peer *peer, + const char *alpn, size_t alpn_len, + void *user_data) +{ + (void)data; + DEBUGASSERT(!ctx->ssl); + DEBUGASSERT(ctx->ssl_ctx); + ctx->ssl = wolfSSL_new(ctx->ssl_ctx); + + wolfSSL_set_app_data(ctx->ssl, user_data); + wolfSSL_set_connect_state(ctx->ssl); + wolfSSL_set_quic_use_legacy_codepoint(ctx->ssl, 0); + + if(alpn) + wolfSSL_set_alpn_protos(ctx->ssl, (const unsigned char *)alpn, + (int)alpn_len); + + if(peer->sni) { + wolfSSL_UseSNI(ctx->ssl, WOLFSSL_SNI_HOST_NAME, + peer->sni, (unsigned short)strlen(peer->sni)); + } + + return CURLE_OK; +} +#endif /* defined(USE_WOLFSSL) */ + +CURLcode Curl_vquic_tls_init(struct curl_tls_ctx *ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + const char *alpn, size_t alpn_len, + Curl_vquic_tls_ctx_setup *cb_setup, + void *cb_user_data, void *ssl_user_data) +{ + CURLcode result; + +#ifdef USE_OPENSSL + (void)result; + return Curl_ossl_ctx_init(&ctx->ossl, cf, data, peer, TRNSPRT_QUIC, + (const unsigned char *)alpn, alpn_len, + cb_setup, cb_user_data, NULL, ssl_user_data); +#elif defined(USE_GNUTLS) + (void)result; + return Curl_gtls_ctx_init(&ctx->gtls, cf, data, peer, + (const unsigned char *)alpn, alpn_len, + cb_setup, cb_user_data, ssl_user_data); +#elif defined(USE_WOLFSSL) + result = curl_wssl_init_ctx(ctx, cf, data, cb_setup, cb_user_data); + if(result) + return result; + + return curl_wssl_init_ssl(ctx, data, peer, alpn, alpn_len, ssl_user_data); +#else +#error "no TLS lib in used, should not happen" + return CURLE_FAILED_INIT; +#endif +} + +void Curl_vquic_tls_cleanup(struct curl_tls_ctx *ctx) +{ +#ifdef USE_OPENSSL + if(ctx->ossl.ssl) + SSL_free(ctx->ossl.ssl); + if(ctx->ossl.ssl_ctx) + SSL_CTX_free(ctx->ossl.ssl_ctx); +#elif defined(USE_GNUTLS) + if(ctx->gtls.cred) + gnutls_certificate_free_credentials(ctx->gtls.cred); + if(ctx->gtls.session) + gnutls_deinit(ctx->gtls.session); +#elif defined(USE_WOLFSSL) + if(ctx->ssl) + wolfSSL_free(ctx->ssl); + if(ctx->ssl_ctx) + wolfSSL_CTX_free(ctx->ssl_ctx); +#endif + memset(ctx, 0, sizeof(*ctx)); +} + +CURLcode Curl_vquic_tls_before_recv(struct curl_tls_ctx *ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data) +{ +#ifdef USE_OPENSSL + if(!ctx->ossl.x509_store_setup) { + CURLcode result = Curl_ssl_setup_x509_store(cf, data, ctx->ossl.ssl_ctx); + if(result) + return result; + ctx->ossl.x509_store_setup = TRUE; + } +#elif defined(USE_GNUTLS) + if(!ctx->gtls.trust_setup) { + CURLcode result = Curl_gtls_client_trust_setup(cf, data, &ctx->gtls); + if(result) + return result; + } +#else + (void)ctx; (void)cf; (void)data; +#endif + return CURLE_OK; +} + +CURLcode Curl_vquic_tls_verify_peer(struct curl_tls_ctx *ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer) +{ + struct ssl_primary_config *conn_config; + CURLcode result = CURLE_OK; + + conn_config = Curl_ssl_cf_get_primary_config(cf); + if(!conn_config) + return CURLE_FAILED_INIT; + +#ifdef USE_OPENSSL + (void)conn_config; + result = Curl_oss_check_peer_cert(cf, data, &ctx->ossl, peer); +#elif defined(USE_GNUTLS) + if(conn_config->verifyhost) { + result = Curl_gtls_verifyserver(data, ctx->gtls.session, + conn_config, &data->set.ssl, peer, + data->set.str[STRING_SSL_PINNEDPUBLICKEY]); + if(result) + return result; + } +#elif defined(USE_WOLFSSL) + (void)data; + if(conn_config->verifyhost) { + if(peer->sni) { + WOLFSSL_X509* cert = wolfSSL_get_peer_certificate(ctx->ssl); + if(wolfSSL_X509_check_host(cert, peer->sni, strlen(peer->sni), 0, NULL) + == WOLFSSL_FAILURE) { + result = CURLE_PEER_FAILED_VERIFICATION; + } + wolfSSL_X509_free(cert); + } + + } +#endif + return result; +} + + +#endif /* !USE_HTTP3 && (USE_OPENSSL || USE_GNUTLS || USE_WOLFSSL) */ diff --git a/third_party/curl/lib/vquic/vquic-tls.h b/third_party/curl/lib/vquic/vquic-tls.h new file mode 100644 index 0000000..1d35fd0 --- /dev/null +++ b/third_party/curl/lib/vquic/vquic-tls.h @@ -0,0 +1,99 @@ +#ifndef HEADER_CURL_VQUIC_TLS_H +#define HEADER_CURL_VQUIC_TLS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "bufq.h" +#include "vtls/openssl.h" + +#if defined(USE_HTTP3) && \ + (defined(USE_OPENSSL) || defined(USE_GNUTLS) || defined(USE_WOLFSSL)) + +struct curl_tls_ctx { +#ifdef USE_OPENSSL + struct ossl_ctx ossl; +#elif defined(USE_GNUTLS) + struct gtls_ctx gtls; +#elif defined(USE_WOLFSSL) + WOLFSSL_CTX *ssl_ctx; + WOLFSSL *ssl; +#endif +}; + +/** + * Callback passed to `Curl_vquic_tls_init()` that can + * do early initializations on the not otherwise configured TLS + * instances created. This varies by TLS backend: + * - openssl/wolfssl: SSL_CTX* has just been created + * - gnutls: gtls_client_init() has run + */ +typedef CURLcode Curl_vquic_tls_ctx_setup(struct Curl_cfilter *cf, + struct Curl_easy *data, + void *cb_user_data); + +/** + * Initialize the QUIC TLS instances based of the SSL configurations + * for the connection filter, transfer and peer. + * @param ctx the TLS context to initialize + * @param cf the connection filter involved + * @param data the transfer involved + * @param peer the peer that will be connected to + * @param alpn the ALPN string in protocol format ((len+bytes+)+), + * may be NULL + * @param alpn_len the overall number of bytes in `alpn` + * @param cb_setup optional callback for very early TLS config + ± @param cb_user_data user_data param for callback + * @param ssl_user_data optional pointer to set in TLS application context + */ +CURLcode Curl_vquic_tls_init(struct curl_tls_ctx *ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + const char *alpn, size_t alpn_len, + Curl_vquic_tls_ctx_setup *cb_setup, + void *cb_user_data, + void *ssl_user_data); + +/** + * Cleanup all data that has been initialized. + */ +void Curl_vquic_tls_cleanup(struct curl_tls_ctx *ctx); + +CURLcode Curl_vquic_tls_before_recv(struct curl_tls_ctx *ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data); + +/** + * After the QUIC basic handshake has been, verify that the peer + * (and its certificate) fulfill our requirements. + */ +CURLcode Curl_vquic_tls_verify_peer(struct curl_tls_ctx *ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer); + +#endif /* !USE_HTTP3 && (USE_OPENSSL || USE_GNUTLS || USE_WOLFSSL) */ + +#endif /* HEADER_CURL_VQUIC_TLS_H */ diff --git a/third_party/curl/lib/vquic/vquic.c b/third_party/curl/lib/vquic/vquic.c new file mode 100644 index 0000000..9ce1e46 --- /dev/null +++ b/third_party/curl/lib/vquic/vquic.c @@ -0,0 +1,677 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* WIP, experimental: use recvmmsg() on linux + * we have no configure check, yet + * and also it is only available for _GNU_SOURCE, which + * we do not use otherwise. +#define HAVE_SENDMMSG + */ +#if defined(HAVE_SENDMMSG) +#define _GNU_SOURCE +#include +#undef _GNU_SOURCE +#endif + +#include "curl_setup.h" + +#ifdef HAVE_FCNTL_H +#include +#endif +#include "urldata.h" +#include "bufq.h" +#include "dynbuf.h" +#include "cfilters.h" +#include "curl_trc.h" +#include "curl_msh3.h" +#include "curl_ngtcp2.h" +#include "curl_osslq.h" +#include "curl_quiche.h" +#include "rand.h" +#include "vquic.h" +#include "vquic_int.h" +#include "strerror.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +#ifdef USE_HTTP3 + +#ifdef O_BINARY +#define QLOGMODE O_WRONLY|O_CREAT|O_BINARY +#else +#define QLOGMODE O_WRONLY|O_CREAT +#endif + +#define NW_CHUNK_SIZE (64 * 1024) +#define NW_SEND_CHUNKS 2 + + +void Curl_quic_ver(char *p, size_t len) +{ +#if defined(USE_NGTCP2) && defined(USE_NGHTTP3) + Curl_ngtcp2_ver(p, len); +#elif defined(USE_OPENSSL_QUIC) && defined(USE_NGHTTP3) + Curl_osslq_ver(p, len); +#elif defined(USE_QUICHE) + Curl_quiche_ver(p, len); +#elif defined(USE_MSH3) + Curl_msh3_ver(p, len); +#endif +} + +CURLcode vquic_ctx_init(struct cf_quic_ctx *qctx) +{ + Curl_bufq_init2(&qctx->sendbuf, NW_CHUNK_SIZE, NW_SEND_CHUNKS, + BUFQ_OPT_SOFT_LIMIT); +#if defined(__linux__) && defined(UDP_SEGMENT) && defined(HAVE_SENDMSG) + qctx->no_gso = FALSE; +#else + qctx->no_gso = TRUE; +#endif +#ifdef DEBUGBUILD + { + char *p = getenv("CURL_DBG_QUIC_WBLOCK"); + if(p) { + long l = strtol(p, NULL, 10); + if(l >= 0 && l <= 100) + qctx->wblock_percent = (int)l; + } + } +#endif + vquic_ctx_update_time(qctx); + + return CURLE_OK; +} + +void vquic_ctx_free(struct cf_quic_ctx *qctx) +{ + Curl_bufq_free(&qctx->sendbuf); +} + +void vquic_ctx_update_time(struct cf_quic_ctx *qctx) +{ + qctx->last_op = Curl_now(); +} + +static CURLcode send_packet_no_gso(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + const uint8_t *pkt, size_t pktlen, + size_t gsolen, size_t *psent); + +static CURLcode do_sendmsg(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + const uint8_t *pkt, size_t pktlen, size_t gsolen, + size_t *psent) +{ +#ifdef HAVE_SENDMSG + struct iovec msg_iov; + struct msghdr msg = {0}; + ssize_t sent; +#if defined(__linux__) && defined(UDP_SEGMENT) + uint8_t msg_ctrl[32]; + struct cmsghdr *cm; +#endif + + *psent = 0; + msg_iov.iov_base = (uint8_t *)pkt; + msg_iov.iov_len = pktlen; + msg.msg_iov = &msg_iov; + msg.msg_iovlen = 1; + +#if defined(__linux__) && defined(UDP_SEGMENT) + if(pktlen > gsolen) { + /* Only set this, when we need it. macOS, for example, + * does not seem to like a msg_control of length 0. */ + msg.msg_control = msg_ctrl; + assert(sizeof(msg_ctrl) >= CMSG_SPACE(sizeof(uint16_t))); + msg.msg_controllen = CMSG_SPACE(sizeof(uint16_t)); + cm = CMSG_FIRSTHDR(&msg); + cm->cmsg_level = SOL_UDP; + cm->cmsg_type = UDP_SEGMENT; + cm->cmsg_len = CMSG_LEN(sizeof(uint16_t)); + *(uint16_t *)(void *)CMSG_DATA(cm) = gsolen & 0xffff; + } +#endif + + + while((sent = sendmsg(qctx->sockfd, &msg, 0)) == -1 && SOCKERRNO == EINTR) + ; + + if(sent == -1) { + switch(SOCKERRNO) { + case EAGAIN: +#if EAGAIN != EWOULDBLOCK + case EWOULDBLOCK: +#endif + return CURLE_AGAIN; + case EMSGSIZE: + /* UDP datagram is too large; caused by PMTUD. Just let it be lost. */ + break; + case EIO: + if(pktlen > gsolen) { + /* GSO failure */ + failf(data, "sendmsg() returned %zd (errno %d); disable GSO", sent, + SOCKERRNO); + qctx->no_gso = TRUE; + return send_packet_no_gso(cf, data, qctx, pkt, pktlen, gsolen, psent); + } + FALLTHROUGH(); + default: + failf(data, "sendmsg() returned %zd (errno %d)", sent, SOCKERRNO); + return CURLE_SEND_ERROR; + } + } + else { + assert(pktlen == (size_t)sent); + } +#else + ssize_t sent; + (void)gsolen; + + *psent = 0; + + while((sent = send(qctx->sockfd, + (const char *)pkt, (SEND_TYPE_ARG3)pktlen, 0)) == -1 && + SOCKERRNO == EINTR) + ; + + if(sent == -1) { + if(SOCKERRNO == EAGAIN || SOCKERRNO == EWOULDBLOCK) { + return CURLE_AGAIN; + } + else { + failf(data, "send() returned %zd (errno %d)", sent, SOCKERRNO); + if(SOCKERRNO != EMSGSIZE) { + return CURLE_SEND_ERROR; + } + /* UDP datagram is too large; caused by PMTUD. Just let it be + lost. */ + } + } +#endif + (void)cf; + *psent = pktlen; + + return CURLE_OK; +} + +static CURLcode send_packet_no_gso(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + const uint8_t *pkt, size_t pktlen, + size_t gsolen, size_t *psent) +{ + const uint8_t *p, *end = pkt + pktlen; + size_t sent; + + *psent = 0; + + for(p = pkt; p < end; p += gsolen) { + size_t len = CURLMIN(gsolen, (size_t)(end - p)); + CURLcode curlcode = do_sendmsg(cf, data, qctx, p, len, len, &sent); + if(curlcode != CURLE_OK) { + return curlcode; + } + *psent += sent; + } + + return CURLE_OK; +} + +static CURLcode vquic_send_packets(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + const uint8_t *pkt, size_t pktlen, + size_t gsolen, size_t *psent) +{ + CURLcode result; +#ifdef DEBUGBUILD + /* simulate network blocking/partial writes */ + if(qctx->wblock_percent > 0) { + unsigned char c; + Curl_rand(data, &c, 1); + if(c >= ((100-qctx->wblock_percent)*256/100)) { + CURL_TRC_CF(data, cf, "vquic_flush() simulate EWOULDBLOCK"); + return CURLE_AGAIN; + } + } +#endif + if(qctx->no_gso && pktlen > gsolen) { + result = send_packet_no_gso(cf, data, qctx, pkt, pktlen, gsolen, psent); + } + else { + result = do_sendmsg(cf, data, qctx, pkt, pktlen, gsolen, psent); + } + if(!result) + qctx->last_io = qctx->last_op; + return result; +} + +CURLcode vquic_flush(struct Curl_cfilter *cf, struct Curl_easy *data, + struct cf_quic_ctx *qctx) +{ + const unsigned char *buf; + size_t blen, sent; + CURLcode result; + size_t gsolen; + + while(Curl_bufq_peek(&qctx->sendbuf, &buf, &blen)) { + gsolen = qctx->gsolen; + if(qctx->split_len) { + gsolen = qctx->split_gsolen; + if(blen > qctx->split_len) + blen = qctx->split_len; + } + + result = vquic_send_packets(cf, data, qctx, buf, blen, gsolen, &sent); + CURL_TRC_CF(data, cf, "vquic_send(len=%zu, gso=%zu) -> %d, sent=%zu", + blen, gsolen, result, sent); + if(result) { + if(result == CURLE_AGAIN) { + Curl_bufq_skip(&qctx->sendbuf, sent); + if(qctx->split_len) + qctx->split_len -= sent; + } + return result; + } + Curl_bufq_skip(&qctx->sendbuf, sent); + if(qctx->split_len) + qctx->split_len -= sent; + } + return CURLE_OK; +} + +CURLcode vquic_send(struct Curl_cfilter *cf, struct Curl_easy *data, + struct cf_quic_ctx *qctx, size_t gsolen) +{ + qctx->gsolen = gsolen; + return vquic_flush(cf, data, qctx); +} + +CURLcode vquic_send_tail_split(struct Curl_cfilter *cf, struct Curl_easy *data, + struct cf_quic_ctx *qctx, size_t gsolen, + size_t tail_len, size_t tail_gsolen) +{ + DEBUGASSERT(Curl_bufq_len(&qctx->sendbuf) > tail_len); + qctx->split_len = Curl_bufq_len(&qctx->sendbuf) - tail_len; + qctx->split_gsolen = gsolen; + qctx->gsolen = tail_gsolen; + CURL_TRC_CF(data, cf, "vquic_send_tail_split: [%zu gso=%zu][%zu gso=%zu]", + qctx->split_len, qctx->split_gsolen, + tail_len, qctx->gsolen); + return vquic_flush(cf, data, qctx); +} + +#ifdef HAVE_SENDMMSG +static CURLcode recvmmsg_packets(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + size_t max_pkts, + vquic_recv_pkt_cb *recv_cb, void *userp) +{ +#define MMSG_NUM 64 + struct iovec msg_iov[MMSG_NUM]; + struct mmsghdr mmsg[MMSG_NUM]; + uint8_t bufs[MMSG_NUM][2*1024]; + struct sockaddr_storage remote_addr[MMSG_NUM]; + size_t total_nread, pkts; + int mcount, i, n; + char errstr[STRERROR_LEN]; + CURLcode result = CURLE_OK; + + DEBUGASSERT(max_pkts > 0); + pkts = 0; + total_nread = 0; + while(pkts < max_pkts) { + n = (int)CURLMIN(MMSG_NUM, max_pkts); + memset(&mmsg, 0, sizeof(mmsg)); + for(i = 0; i < n; ++i) { + msg_iov[i].iov_base = bufs[i]; + msg_iov[i].iov_len = (int)sizeof(bufs[i]); + mmsg[i].msg_hdr.msg_iov = &msg_iov[i]; + mmsg[i].msg_hdr.msg_iovlen = 1; + mmsg[i].msg_hdr.msg_name = &remote_addr[i]; + mmsg[i].msg_hdr.msg_namelen = sizeof(remote_addr[i]); + } + + while((mcount = recvmmsg(qctx->sockfd, mmsg, n, 0, NULL)) == -1 && + SOCKERRNO == EINTR) + ; + if(mcount == -1) { + if(SOCKERRNO == EAGAIN || SOCKERRNO == EWOULDBLOCK) { + CURL_TRC_CF(data, cf, "ingress, recvmmsg -> EAGAIN"); + goto out; + } + if(!cf->connected && SOCKERRNO == ECONNREFUSED) { + struct ip_quadruple ip; + Curl_cf_socket_peek(cf->next, data, NULL, NULL, &ip); + failf(data, "QUIC: connection to %s port %u refused", + ip.remote_ip, ip.remote_port); + result = CURLE_COULDNT_CONNECT; + goto out; + } + Curl_strerror(SOCKERRNO, errstr, sizeof(errstr)); + failf(data, "QUIC: recvmsg() unexpectedly returned %d (errno=%d; %s)", + mcount, SOCKERRNO, errstr); + result = CURLE_RECV_ERROR; + goto out; + } + + CURL_TRC_CF(data, cf, "recvmmsg() -> %d packets", mcount); + pkts += mcount; + for(i = 0; i < mcount; ++i) { + total_nread += mmsg[i].msg_len; + result = recv_cb(bufs[i], mmsg[i].msg_len, + mmsg[i].msg_hdr.msg_name, mmsg[i].msg_hdr.msg_namelen, + 0, userp); + if(result) + goto out; + } + } + +out: + if(total_nread || result) + CURL_TRC_CF(data, cf, "recvd %zu packets with %zu bytes -> %d", + pkts, total_nread, result); + return result; +} + +#elif defined(HAVE_SENDMSG) +static CURLcode recvmsg_packets(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + size_t max_pkts, + vquic_recv_pkt_cb *recv_cb, void *userp) +{ + struct iovec msg_iov; + struct msghdr msg; + uint8_t buf[64*1024]; + struct sockaddr_storage remote_addr; + size_t total_nread, pkts; + ssize_t nread; + char errstr[STRERROR_LEN]; + CURLcode result = CURLE_OK; + + msg_iov.iov_base = buf; + msg_iov.iov_len = (int)sizeof(buf); + + memset(&msg, 0, sizeof(msg)); + msg.msg_iov = &msg_iov; + msg.msg_iovlen = 1; + + DEBUGASSERT(max_pkts > 0); + for(pkts = 0, total_nread = 0; pkts < max_pkts;) { + msg.msg_name = &remote_addr; + msg.msg_namelen = sizeof(remote_addr); + while((nread = recvmsg(qctx->sockfd, &msg, 0)) == -1 && + SOCKERRNO == EINTR) + ; + if(nread == -1) { + if(SOCKERRNO == EAGAIN || SOCKERRNO == EWOULDBLOCK) { + goto out; + } + if(!cf->connected && SOCKERRNO == ECONNREFUSED) { + struct ip_quadruple ip; + Curl_cf_socket_peek(cf->next, data, NULL, NULL, &ip); + failf(data, "QUIC: connection to %s port %u refused", + ip.remote_ip, ip.remote_port); + result = CURLE_COULDNT_CONNECT; + goto out; + } + Curl_strerror(SOCKERRNO, errstr, sizeof(errstr)); + failf(data, "QUIC: recvmsg() unexpectedly returned %zd (errno=%d; %s)", + nread, SOCKERRNO, errstr); + result = CURLE_RECV_ERROR; + goto out; + } + + ++pkts; + total_nread += (size_t)nread; + result = recv_cb(buf, (size_t)nread, msg.msg_name, msg.msg_namelen, + 0, userp); + if(result) + goto out; + } + +out: + if(total_nread || result) + CURL_TRC_CF(data, cf, "recvd %zu packets with %zu bytes -> %d", + pkts, total_nread, result); + return result; +} + +#else /* HAVE_SENDMMSG || HAVE_SENDMSG */ +static CURLcode recvfrom_packets(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + size_t max_pkts, + vquic_recv_pkt_cb *recv_cb, void *userp) +{ + uint8_t buf[64*1024]; + int bufsize = (int)sizeof(buf); + struct sockaddr_storage remote_addr; + socklen_t remote_addrlen = sizeof(remote_addr); + size_t total_nread, pkts; + ssize_t nread; + char errstr[STRERROR_LEN]; + CURLcode result = CURLE_OK; + + DEBUGASSERT(max_pkts > 0); + for(pkts = 0, total_nread = 0; pkts < max_pkts;) { + while((nread = recvfrom(qctx->sockfd, (char *)buf, bufsize, 0, + (struct sockaddr *)&remote_addr, + &remote_addrlen)) == -1 && + SOCKERRNO == EINTR) + ; + if(nread == -1) { + if(SOCKERRNO == EAGAIN || SOCKERRNO == EWOULDBLOCK) { + CURL_TRC_CF(data, cf, "ingress, recvfrom -> EAGAIN"); + goto out; + } + if(!cf->connected && SOCKERRNO == ECONNREFUSED) { + struct ip_quadruple ip; + Curl_cf_socket_peek(cf->next, data, NULL, NULL, &ip); + failf(data, "QUIC: connection to %s port %u refused", + ip.remote_ip, ip.remote_port); + result = CURLE_COULDNT_CONNECT; + goto out; + } + Curl_strerror(SOCKERRNO, errstr, sizeof(errstr)); + failf(data, "QUIC: recvfrom() unexpectedly returned %zd (errno=%d; %s)", + nread, SOCKERRNO, errstr); + result = CURLE_RECV_ERROR; + goto out; + } + + ++pkts; + total_nread += (size_t)nread; + result = recv_cb(buf, (size_t)nread, &remote_addr, remote_addrlen, + 0, userp); + if(result) + goto out; + } + +out: + if(total_nread || result) + CURL_TRC_CF(data, cf, "recvd %zu packets with %zu bytes -> %d", + pkts, total_nread, result); + return result; +} +#endif /* !HAVE_SENDMMSG && !HAVE_SENDMSG */ + +CURLcode vquic_recv_packets(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + size_t max_pkts, + vquic_recv_pkt_cb *recv_cb, void *userp) +{ + CURLcode result; +#if defined(HAVE_SENDMMSG) + result = recvmmsg_packets(cf, data, qctx, max_pkts, recv_cb, userp); +#elif defined(HAVE_SENDMSG) + result = recvmsg_packets(cf, data, qctx, max_pkts, recv_cb, userp); +#else + result = recvfrom_packets(cf, data, qctx, max_pkts, recv_cb, userp); +#endif + if(!result) { + if(!qctx->got_first_byte) { + qctx->got_first_byte = TRUE; + qctx->first_byte_at = qctx->last_op; + } + qctx->last_io = qctx->last_op; + } + return result; +} + +/* + * If the QLOGDIR environment variable is set, open and return a file + * descriptor to write the log to. + * + * This function returns error if something failed outside of failing to + * create the file. Open file success is deemed by seeing if the returned fd + * is != -1. + */ +CURLcode Curl_qlogdir(struct Curl_easy *data, + unsigned char *scid, + size_t scidlen, + int *qlogfdp) +{ + const char *qlog_dir = getenv("QLOGDIR"); + *qlogfdp = -1; + if(qlog_dir) { + struct dynbuf fname; + CURLcode result; + unsigned int i; + Curl_dyn_init(&fname, DYN_QLOG_NAME); + result = Curl_dyn_add(&fname, qlog_dir); + if(!result) + result = Curl_dyn_add(&fname, "/"); + for(i = 0; (i < scidlen) && !result; i++) { + char hex[3]; + msnprintf(hex, 3, "%02x", scid[i]); + result = Curl_dyn_add(&fname, hex); + } + if(!result) + result = Curl_dyn_add(&fname, ".sqlog"); + + if(!result) { + int qlogfd = open(Curl_dyn_ptr(&fname), QLOGMODE, + data->set.new_file_perms); + if(qlogfd != -1) + *qlogfdp = qlogfd; + } + Curl_dyn_free(&fname); + if(result) + return result; + } + + return CURLE_OK; +} + +CURLcode Curl_cf_quic_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai, + int transport) +{ + (void)transport; + DEBUGASSERT(transport == TRNSPRT_QUIC); +#if defined(USE_NGTCP2) && defined(USE_NGHTTP3) + return Curl_cf_ngtcp2_create(pcf, data, conn, ai); +#elif defined(USE_OPENSSL_QUIC) && defined(USE_NGHTTP3) + return Curl_cf_osslq_create(pcf, data, conn, ai); +#elif defined(USE_QUICHE) + return Curl_cf_quiche_create(pcf, data, conn, ai); +#elif defined(USE_MSH3) + return Curl_cf_msh3_create(pcf, data, conn, ai); +#else + *pcf = NULL; + (void)data; + (void)conn; + (void)ai; + return CURLE_NOT_BUILT_IN; +#endif +} + +bool Curl_conn_is_http3(const struct Curl_easy *data, + const struct connectdata *conn, + int sockindex) +{ +#if defined(USE_NGTCP2) && defined(USE_NGHTTP3) + return Curl_conn_is_ngtcp2(data, conn, sockindex); +#elif defined(USE_OPENSSL_QUIC) && defined(USE_NGHTTP3) + return Curl_conn_is_osslq(data, conn, sockindex); +#elif defined(USE_QUICHE) + return Curl_conn_is_quiche(data, conn, sockindex); +#elif defined(USE_MSH3) + return Curl_conn_is_msh3(data, conn, sockindex); +#else + return ((conn->handler->protocol & PROTO_FAMILY_HTTP) && + (conn->httpversion == 30)); +#endif +} + +CURLcode Curl_conn_may_http3(struct Curl_easy *data, + const struct connectdata *conn) +{ + if(conn->transport == TRNSPRT_UNIX) { + /* cannot do QUIC over a unix domain socket */ + return CURLE_QUIC_CONNECT_ERROR; + } + if(!(conn->handler->flags & PROTOPT_SSL)) { + failf(data, "HTTP/3 requested for non-HTTPS URL"); + return CURLE_URL_MALFORMAT; + } +#ifndef CURL_DISABLE_PROXY + if(conn->bits.socksproxy) { + failf(data, "HTTP/3 is not supported over a SOCKS proxy"); + return CURLE_URL_MALFORMAT; + } + if(conn->bits.httpproxy && conn->bits.tunnel_proxy) { + failf(data, "HTTP/3 is not supported over a HTTP proxy"); + return CURLE_URL_MALFORMAT; + } +#endif + + return CURLE_OK; +} + +#else /* USE_HTTP3 */ + +CURLcode Curl_conn_may_http3(struct Curl_easy *data, + const struct connectdata *conn) +{ + (void)conn; + (void)data; + DEBUGF(infof(data, "QUIC is not supported in this build")); + return CURLE_NOT_BUILT_IN; +} + +#endif /* !USE_HTTP3 */ diff --git a/third_party/curl/lib/vquic/vquic.h b/third_party/curl/lib/vquic/vquic.h new file mode 100644 index 0000000..c1ca1df --- /dev/null +++ b/third_party/curl/lib/vquic/vquic.h @@ -0,0 +1,64 @@ +#ifndef HEADER_CURL_VQUIC_QUIC_H +#define HEADER_CURL_VQUIC_QUIC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_HTTP3 +struct Curl_cfilter; +struct Curl_easy; +struct connectdata; +struct Curl_addrinfo; + +void Curl_quic_ver(char *p, size_t len); + +CURLcode Curl_qlogdir(struct Curl_easy *data, + unsigned char *scid, + size_t scidlen, + int *qlogfdp); + + +CURLcode Curl_cf_quic_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai, + int transport); + +bool Curl_conn_is_http3(const struct Curl_easy *data, + const struct connectdata *conn, + int sockindex); + +extern struct Curl_cftype Curl_cft_http3; + +#else /* USE_HTTP3 */ + +#define Curl_conn_is_http3(a,b,c) FALSE + +#endif /* !USE_HTTP3 */ + +CURLcode Curl_conn_may_http3(struct Curl_easy *data, + const struct connectdata *conn); + +#endif /* HEADER_CURL_VQUIC_QUIC_H */ diff --git a/third_party/curl/lib/vquic/vquic_int.h b/third_party/curl/lib/vquic/vquic_int.h new file mode 100644 index 0000000..754e1f5 --- /dev/null +++ b/third_party/curl/lib/vquic/vquic_int.h @@ -0,0 +1,93 @@ +#ifndef HEADER_CURL_VQUIC_QUIC_INT_H +#define HEADER_CURL_VQUIC_QUIC_INT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "bufq.h" + +#ifdef USE_HTTP3 + +#define MAX_PKT_BURST 10 +#define MAX_UDP_PAYLOAD_SIZE 1452 +/* Default QUIC connection timeout we announce from our side */ +#define CURL_QUIC_MAX_IDLE_MS (120 * 1000) + +struct cf_quic_ctx { + curl_socket_t sockfd; /* connected UDP socket */ + struct sockaddr_storage local_addr; /* address socket is bound to */ + socklen_t local_addrlen; /* length of local address */ + + struct bufq sendbuf; /* buffer for sending one or more packets */ + struct curltime first_byte_at; /* when first byte was recvd */ + struct curltime last_op; /* last (attempted) send/recv operation */ + struct curltime last_io; /* last successful socket IO */ + size_t gsolen; /* length of individual packets in send buf */ + size_t split_len; /* if != 0, buffer length after which GSO differs */ + size_t split_gsolen; /* length of individual packets after split_len */ +#ifdef DEBUGBUILD + int wblock_percent; /* percent of writes doing EAGAIN */ +#endif + BIT(got_first_byte); /* if first byte was received */ + BIT(no_gso); /* do not use gso on sending */ +}; + +CURLcode vquic_ctx_init(struct cf_quic_ctx *qctx); +void vquic_ctx_free(struct cf_quic_ctx *qctx); + +void vquic_ctx_update_time(struct cf_quic_ctx *qctx); + +void vquic_push_blocked_pkt(struct Curl_cfilter *cf, + struct cf_quic_ctx *qctx, + const uint8_t *pkt, size_t pktlen, size_t gsolen); + +CURLcode vquic_send_blocked_pkts(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx); + +CURLcode vquic_send(struct Curl_cfilter *cf, struct Curl_easy *data, + struct cf_quic_ctx *qctx, size_t gsolen); + +CURLcode vquic_send_tail_split(struct Curl_cfilter *cf, struct Curl_easy *data, + struct cf_quic_ctx *qctx, size_t gsolen, + size_t tail_len, size_t tail_gsolen); + +CURLcode vquic_flush(struct Curl_cfilter *cf, struct Curl_easy *data, + struct cf_quic_ctx *qctx); + + +typedef CURLcode vquic_recv_pkt_cb(const unsigned char *pkt, size_t pktlen, + struct sockaddr_storage *remote_addr, + socklen_t remote_addrlen, int ecn, + void *userp); + +CURLcode vquic_recv_packets(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + size_t max_pkts, + vquic_recv_pkt_cb *recv_cb, void *userp); + +#endif /* !USE_HTTP3 */ + +#endif /* HEADER_CURL_VQUIC_QUIC_INT_H */ diff --git a/third_party/curl/lib/vssh/libssh.c b/third_party/curl/lib/vssh/libssh.c new file mode 100644 index 0000000..d6ba987 --- /dev/null +++ b/third_party/curl/lib/vssh/libssh.c @@ -0,0 +1,2954 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Red Hat, Inc. + * + * Authors: Nikos Mavrogiannopoulos, Tomas Mraz, Stanislav Zidek, + * Robert Kolcun, Andreas Schneider + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_LIBSSH + +#include + +/* in 0.10.0 or later, ignore deprecated warnings */ +#define SSH_SUPPRESS_DEPRECATED +#include +#include + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef __VMS +#include +#include +#endif + +#include +#include "urldata.h" +#include "sendf.h" +#include "hostip.h" +#include "progress.h" +#include "transfer.h" +#include "escape.h" +#include "http.h" /* for HTTP proxy tunnel stuff */ +#include "ssh.h" +#include "url.h" +#include "speedcheck.h" +#include "getinfo.h" +#include "strdup.h" +#include "strcase.h" +#include "vtls/vtls.h" +#include "cfilters.h" +#include "connect.h" +#include "inet_ntop.h" +#include "parsedate.h" /* for the week day and month names */ +#include "sockaddr.h" /* required for Curl_sockaddr_storage */ +#include "strtoofft.h" +#include "multiif.h" +#include "select.h" +#include "warnless.h" +#include "curl_path.h" + +#ifdef HAVE_SYS_STAT_H +#include +#endif +#ifdef HAVE_UNISTD_H +#include +#endif +#ifdef HAVE_FCNTL_H +#include +#endif + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* A recent macro provided by libssh. Or make our own. */ +#ifndef SSH_STRING_FREE_CHAR +#define SSH_STRING_FREE_CHAR(x) \ + do { \ + if(x) { \ + ssh_string_free_char(x); \ + x = NULL; \ + } \ + } while(0) +#endif + +/* These stat values may not be the same as the user's S_IFMT / S_IFLNK */ +#ifndef SSH_S_IFMT +#define SSH_S_IFMT 00170000 +#endif +#ifndef SSH_S_IFLNK +#define SSH_S_IFLNK 0120000 +#endif + +/* Local functions: */ +static CURLcode myssh_connect(struct Curl_easy *data, bool *done); +static CURLcode myssh_multi_statemach(struct Curl_easy *data, + bool *done); +static CURLcode myssh_do_it(struct Curl_easy *data, bool *done); + +static CURLcode scp_done(struct Curl_easy *data, + CURLcode, bool premature); +static CURLcode scp_doing(struct Curl_easy *data, bool *dophase_done); +static CURLcode scp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection); + +static CURLcode sftp_done(struct Curl_easy *data, + CURLcode, bool premature); +static CURLcode sftp_doing(struct Curl_easy *data, + bool *dophase_done); +static CURLcode sftp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead); +static +CURLcode sftp_perform(struct Curl_easy *data, + bool *connected, + bool *dophase_done); + +static void sftp_quote(struct Curl_easy *data); +static void sftp_quote_stat(struct Curl_easy *data); +static int myssh_getsock(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *sock); + +static CURLcode myssh_setup_connection(struct Curl_easy *data, + struct connectdata *conn); + +/* + * SCP protocol handler. + */ + +const struct Curl_handler Curl_handler_scp = { + "SCP", /* scheme */ + myssh_setup_connection, /* setup_connection */ + myssh_do_it, /* do_it */ + scp_done, /* done */ + ZERO_NULL, /* do_more */ + myssh_connect, /* connect_it */ + myssh_multi_statemach, /* connecting */ + scp_doing, /* doing */ + myssh_getsock, /* proto_getsock */ + myssh_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + myssh_getsock, /* perform_getsock */ + scp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_SSH, /* defport */ + CURLPROTO_SCP, /* protocol */ + CURLPROTO_SCP, /* family */ + PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY /* flags */ +}; + +/* + * SFTP protocol handler. + */ + +const struct Curl_handler Curl_handler_sftp = { + "SFTP", /* scheme */ + myssh_setup_connection, /* setup_connection */ + myssh_do_it, /* do_it */ + sftp_done, /* done */ + ZERO_NULL, /* do_more */ + myssh_connect, /* connect_it */ + myssh_multi_statemach, /* connecting */ + sftp_doing, /* doing */ + myssh_getsock, /* proto_getsock */ + myssh_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + myssh_getsock, /* perform_getsock */ + sftp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_SSH, /* defport */ + CURLPROTO_SFTP, /* protocol */ + CURLPROTO_SFTP, /* family */ + PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION + | PROTOPT_NOURLQUERY /* flags */ +}; + +static CURLcode sftp_error_to_CURLE(int err) +{ + switch(err) { + case SSH_FX_OK: + return CURLE_OK; + + case SSH_FX_NO_SUCH_FILE: + case SSH_FX_NO_SUCH_PATH: + return CURLE_REMOTE_FILE_NOT_FOUND; + + case SSH_FX_PERMISSION_DENIED: + case SSH_FX_WRITE_PROTECT: + return CURLE_REMOTE_ACCESS_DENIED; + + case SSH_FX_FILE_ALREADY_EXISTS: + return CURLE_REMOTE_FILE_EXISTS; + + default: + break; + } + + return CURLE_SSH; +} + +#ifndef DEBUGBUILD +#define state(x,y) mystate(x,y) +#else +#define state(x,y) mystate(x,y, __LINE__) +#endif + +/* + * SSH State machine related code + */ +/* This is the ONLY way to change SSH state! */ +static void mystate(struct Curl_easy *data, sshstate nowstate +#ifdef DEBUGBUILD + , int lineno +#endif + ) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + /* for debug purposes */ + static const char *const names[] = { + "SSH_STOP", + "SSH_INIT", + "SSH_S_STARTUP", + "SSH_HOSTKEY", + "SSH_AUTHLIST", + "SSH_AUTH_PKEY_INIT", + "SSH_AUTH_PKEY", + "SSH_AUTH_PASS_INIT", + "SSH_AUTH_PASS", + "SSH_AUTH_AGENT_INIT", + "SSH_AUTH_AGENT_LIST", + "SSH_AUTH_AGENT", + "SSH_AUTH_HOST_INIT", + "SSH_AUTH_HOST", + "SSH_AUTH_KEY_INIT", + "SSH_AUTH_KEY", + "SSH_AUTH_GSSAPI", + "SSH_AUTH_DONE", + "SSH_SFTP_INIT", + "SSH_SFTP_REALPATH", + "SSH_SFTP_QUOTE_INIT", + "SSH_SFTP_POSTQUOTE_INIT", + "SSH_SFTP_QUOTE", + "SSH_SFTP_NEXT_QUOTE", + "SSH_SFTP_QUOTE_STAT", + "SSH_SFTP_QUOTE_SETSTAT", + "SSH_SFTP_QUOTE_SYMLINK", + "SSH_SFTP_QUOTE_MKDIR", + "SSH_SFTP_QUOTE_RENAME", + "SSH_SFTP_QUOTE_RMDIR", + "SSH_SFTP_QUOTE_UNLINK", + "SSH_SFTP_QUOTE_STATVFS", + "SSH_SFTP_GETINFO", + "SSH_SFTP_FILETIME", + "SSH_SFTP_TRANS_INIT", + "SSH_SFTP_UPLOAD_INIT", + "SSH_SFTP_CREATE_DIRS_INIT", + "SSH_SFTP_CREATE_DIRS", + "SSH_SFTP_CREATE_DIRS_MKDIR", + "SSH_SFTP_READDIR_INIT", + "SSH_SFTP_READDIR", + "SSH_SFTP_READDIR_LINK", + "SSH_SFTP_READDIR_BOTTOM", + "SSH_SFTP_READDIR_DONE", + "SSH_SFTP_DOWNLOAD_INIT", + "SSH_SFTP_DOWNLOAD_STAT", + "SSH_SFTP_CLOSE", + "SSH_SFTP_SHUTDOWN", + "SSH_SCP_TRANS_INIT", + "SSH_SCP_UPLOAD_INIT", + "SSH_SCP_DOWNLOAD_INIT", + "SSH_SCP_DOWNLOAD", + "SSH_SCP_DONE", + "SSH_SCP_SEND_EOF", + "SSH_SCP_WAIT_EOF", + "SSH_SCP_WAIT_CLOSE", + "SSH_SCP_CHANNEL_FREE", + "SSH_SESSION_DISCONNECT", + "SSH_SESSION_FREE", + "QUIT" + }; + + + if(sshc->state != nowstate) { + infof(data, "SSH %p state change from %s to %s (line %d)", + (void *) sshc, names[sshc->state], names[nowstate], + lineno); + } +#endif + + sshc->state = nowstate; +} + +/* Multiple options: + * 1. data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5] is set with an MD5 + * hash (90s style auth, not sure we should have it here) + * 2. data->set.ssh_keyfunc callback is set. Then we do trust on first + * use. We even save on knownhosts if CURLKHSTAT_FINE_ADD_TO_FILE + * is returned by it. + * 3. none of the above. We only accept if it is present on known hosts. + * + * Returns SSH_OK or SSH_ERROR. + */ +static int myssh_is_known(struct Curl_easy *data) +{ + int rc; + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + ssh_key pubkey; + size_t hlen; + unsigned char *hash = NULL; + char *found_base64 = NULL; + char *known_base64 = NULL; + int vstate; + enum curl_khmatch keymatch; + struct curl_khkey foundkey; + struct curl_khkey *knownkeyp = NULL; + curl_sshkeycallback func = + data->set.ssh_keyfunc; + +#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0,9,0) + struct ssh_knownhosts_entry *knownhostsentry = NULL; + struct curl_khkey knownkey; +#endif + +#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0,8,0) + rc = ssh_get_server_publickey(sshc->ssh_session, &pubkey); +#else + rc = ssh_get_publickey(sshc->ssh_session, &pubkey); +#endif + if(rc != SSH_OK) + return rc; + + if(data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5]) { + int i; + char md5buffer[33]; + const char *pubkey_md5 = data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5]; + + rc = ssh_get_publickey_hash(pubkey, SSH_PUBLICKEY_HASH_MD5, + &hash, &hlen); + if(rc != SSH_OK || hlen != 16) { + failf(data, + "Denied establishing ssh session: md5 fingerprint not available"); + goto cleanup; + } + + for(i = 0; i < 16; i++) + msnprintf(&md5buffer[i*2], 3, "%02x", (unsigned char)hash[i]); + + infof(data, "SSH MD5 fingerprint: %s", md5buffer); + + if(!strcasecompare(md5buffer, pubkey_md5)) { + failf(data, + "Denied establishing ssh session: mismatch md5 fingerprint. " + "Remote %s is not equal to %s", md5buffer, pubkey_md5); + rc = SSH_ERROR; + goto cleanup; + } + + rc = SSH_OK; + goto cleanup; + } + + if(data->set.ssl.primary.verifyhost != TRUE) { + rc = SSH_OK; + goto cleanup; + } + +#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0,9,0) + /* Get the known_key from the known hosts file */ + vstate = ssh_session_get_known_hosts_entry(sshc->ssh_session, + &knownhostsentry); + + /* Case an entry was found in a known hosts file */ + if(knownhostsentry) { + if(knownhostsentry->publickey) { + rc = ssh_pki_export_pubkey_base64(knownhostsentry->publickey, + &known_base64); + if(rc != SSH_OK) { + goto cleanup; + } + knownkey.key = known_base64; + knownkey.len = strlen(known_base64); + + switch(ssh_key_type(knownhostsentry->publickey)) { + case SSH_KEYTYPE_RSA: + knownkey.keytype = CURLKHTYPE_RSA; + break; + case SSH_KEYTYPE_RSA1: + knownkey.keytype = CURLKHTYPE_RSA1; + break; + case SSH_KEYTYPE_ECDSA: + case SSH_KEYTYPE_ECDSA_P256: + case SSH_KEYTYPE_ECDSA_P384: + case SSH_KEYTYPE_ECDSA_P521: + knownkey.keytype = CURLKHTYPE_ECDSA; + break; + case SSH_KEYTYPE_ED25519: + knownkey.keytype = CURLKHTYPE_ED25519; + break; + case SSH_KEYTYPE_DSS: + knownkey.keytype = CURLKHTYPE_DSS; + break; + default: + rc = SSH_ERROR; + goto cleanup; + } + knownkeyp = &knownkey; + } + } + + switch(vstate) { + case SSH_KNOWN_HOSTS_OK: + keymatch = CURLKHMATCH_OK; + break; + case SSH_KNOWN_HOSTS_OTHER: + case SSH_KNOWN_HOSTS_NOT_FOUND: + case SSH_KNOWN_HOSTS_UNKNOWN: + case SSH_KNOWN_HOSTS_ERROR: + keymatch = CURLKHMATCH_MISSING; + break; + default: + keymatch = CURLKHMATCH_MISMATCH; + break; + } + +#else + vstate = ssh_is_server_known(sshc->ssh_session); + switch(vstate) { + case SSH_SERVER_KNOWN_OK: + keymatch = CURLKHMATCH_OK; + break; + case SSH_SERVER_FILE_NOT_FOUND: + case SSH_SERVER_NOT_KNOWN: + keymatch = CURLKHMATCH_MISSING; + break; + default: + keymatch = CURLKHMATCH_MISMATCH; + break; + } +#endif + + if(func) { /* use callback to determine action */ + rc = ssh_pki_export_pubkey_base64(pubkey, &found_base64); + if(rc != SSH_OK) + goto cleanup; + + foundkey.key = found_base64; + foundkey.len = strlen(found_base64); + + switch(ssh_key_type(pubkey)) { + case SSH_KEYTYPE_RSA: + foundkey.keytype = CURLKHTYPE_RSA; + break; + case SSH_KEYTYPE_RSA1: + foundkey.keytype = CURLKHTYPE_RSA1; + break; + case SSH_KEYTYPE_ECDSA: +#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0,9,0) + case SSH_KEYTYPE_ECDSA_P256: + case SSH_KEYTYPE_ECDSA_P384: + case SSH_KEYTYPE_ECDSA_P521: +#endif + foundkey.keytype = CURLKHTYPE_ECDSA; + break; +#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0,7,0) + case SSH_KEYTYPE_ED25519: + foundkey.keytype = CURLKHTYPE_ED25519; + break; +#endif + case SSH_KEYTYPE_DSS: + foundkey.keytype = CURLKHTYPE_DSS; + break; + default: + rc = SSH_ERROR; + goto cleanup; + } + + Curl_set_in_callback(data, true); + rc = func(data, knownkeyp, /* from the knownhosts file */ + &foundkey, /* from the remote host */ + keymatch, data->set.ssh_keyfunc_userp); + Curl_set_in_callback(data, false); + + switch(rc) { + case CURLKHSTAT_FINE_ADD_TO_FILE: +#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0,8,0) + rc = ssh_session_update_known_hosts(sshc->ssh_session); +#else + rc = ssh_write_knownhost(sshc->ssh_session); +#endif + if(rc != SSH_OK) { + goto cleanup; + } + break; + case CURLKHSTAT_FINE: + break; + default: /* REJECT/DEFER */ + rc = SSH_ERROR; + goto cleanup; + } + } + else { + if(keymatch != CURLKHMATCH_OK) { + rc = SSH_ERROR; + goto cleanup; + } + } + rc = SSH_OK; + +cleanup: + if(found_base64) { + (free)(found_base64); + } + if(known_base64) { + (free)(known_base64); + } + if(hash) + ssh_clean_pubkey_hash(&hash); + ssh_key_free(pubkey); +#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0,9,0) + if(knownhostsentry) { + ssh_knownhosts_entry_free(knownhostsentry); + } +#endif + return rc; +} + +#define MOVE_TO_ERROR_STATE(_r) do { \ + state(data, SSH_SESSION_DISCONNECT); \ + sshc->actualcode = _r; \ + rc = SSH_ERROR; \ + } while(0) + +#define MOVE_TO_SFTP_CLOSE_STATE() do { \ + state(data, SSH_SFTP_CLOSE); \ + sshc->actualcode = \ + sftp_error_to_CURLE(sftp_get_error(sshc->sftp_session)); \ + rc = SSH_ERROR; \ + } while(0) + +#define MOVE_TO_PASSWD_AUTH do { \ + if(sshc->auth_methods & SSH_AUTH_METHOD_PASSWORD) { \ + rc = SSH_OK; \ + state(data, SSH_AUTH_PASS_INIT); \ + } \ + else { \ + MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED); \ + } \ + } while(0) + +#define MOVE_TO_KEY_AUTH do { \ + if(sshc->auth_methods & SSH_AUTH_METHOD_INTERACTIVE) { \ + rc = SSH_OK; \ + state(data, SSH_AUTH_KEY_INIT); \ + } \ + else { \ + MOVE_TO_PASSWD_AUTH; \ + } \ + } while(0) + +#define MOVE_TO_GSSAPI_AUTH do { \ + if(sshc->auth_methods & SSH_AUTH_METHOD_GSSAPI_MIC) { \ + rc = SSH_OK; \ + state(data, SSH_AUTH_GSSAPI); \ + } \ + else { \ + MOVE_TO_KEY_AUTH; \ + } \ + } while(0) + +static +int myssh_auth_interactive(struct connectdata *conn) +{ + int rc; + struct ssh_conn *sshc = &conn->proto.sshc; + int nprompts; + +restart: + switch(sshc->kbd_state) { + case 0: + rc = ssh_userauth_kbdint(sshc->ssh_session, NULL, NULL); + if(rc == SSH_AUTH_AGAIN) + return SSH_AGAIN; + + if(rc != SSH_AUTH_INFO) + return SSH_ERROR; + + nprompts = ssh_userauth_kbdint_getnprompts(sshc->ssh_session); + if(nprompts != 1) + return SSH_ERROR; + + rc = ssh_userauth_kbdint_setanswer(sshc->ssh_session, 0, conn->passwd); + if(rc < 0) + return SSH_ERROR; + + FALLTHROUGH(); + case 1: + sshc->kbd_state = 1; + + rc = ssh_userauth_kbdint(sshc->ssh_session, NULL, NULL); + if(rc == SSH_AUTH_AGAIN) + return SSH_AGAIN; + else if(rc == SSH_AUTH_SUCCESS) + rc = SSH_OK; + else if(rc == SSH_AUTH_INFO) { + nprompts = ssh_userauth_kbdint_getnprompts(sshc->ssh_session); + if(nprompts) + return SSH_ERROR; + + sshc->kbd_state = 2; + goto restart; + } + else + rc = SSH_ERROR; + break; + case 2: + sshc->kbd_state = 2; + + rc = ssh_userauth_kbdint(sshc->ssh_session, NULL, NULL); + if(rc == SSH_AUTH_AGAIN) + return SSH_AGAIN; + else if(rc == SSH_AUTH_SUCCESS) + rc = SSH_OK; + else + rc = SSH_ERROR; + + break; + default: + return SSH_ERROR; + } + + sshc->kbd_state = 0; + return rc; +} + +/* + * ssh_statemach_act() runs the SSH state machine as far as it can without + * blocking and without reaching the end. The data the pointer 'block' points + * to will be set to TRUE if the libssh function returns SSH_AGAIN + * meaning it wants to be called again when the socket is ready + */ +static CURLcode myssh_statemach_act(struct Curl_easy *data, bool *block) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct SSHPROTO *protop = data->req.p.ssh; + struct ssh_conn *sshc = &conn->proto.sshc; + curl_socket_t sock = conn->sock[FIRSTSOCKET]; + int rc = SSH_NO_ERROR, err; + int seekerr = CURL_SEEKFUNC_OK; + const char *err_msg; + *block = 0; /* we're not blocking by default */ + + do { + + switch(sshc->state) { + case SSH_INIT: + sshc->secondCreateDirs = 0; + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_OK; + +#if 0 + ssh_set_log_level(SSH_LOG_PROTOCOL); +#endif + + /* Set libssh to non-blocking, since everything internally is + non-blocking */ + ssh_set_blocking(sshc->ssh_session, 0); + + state(data, SSH_S_STARTUP); + FALLTHROUGH(); + + case SSH_S_STARTUP: + rc = ssh_connect(sshc->ssh_session); + if(rc == SSH_AGAIN) + break; + + if(rc != SSH_OK) { + failf(data, "Failure establishing ssh session"); + MOVE_TO_ERROR_STATE(CURLE_FAILED_INIT); + break; + } + + state(data, SSH_HOSTKEY); + + FALLTHROUGH(); + case SSH_HOSTKEY: + + rc = myssh_is_known(data); + if(rc != SSH_OK) { + MOVE_TO_ERROR_STATE(CURLE_PEER_FAILED_VERIFICATION); + break; + } + + state(data, SSH_AUTHLIST); + FALLTHROUGH(); + case SSH_AUTHLIST:{ + sshc->authed = FALSE; + + rc = ssh_userauth_none(sshc->ssh_session, NULL); + if(rc == SSH_AUTH_AGAIN) { + rc = SSH_AGAIN; + break; + } + + if(rc == SSH_AUTH_SUCCESS) { + sshc->authed = TRUE; + infof(data, "Authenticated with none"); + state(data, SSH_AUTH_DONE); + break; + } + else if(rc == SSH_AUTH_ERROR) { + MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED); + break; + } + + sshc->auth_methods = ssh_userauth_list(sshc->ssh_session, NULL); + if(sshc->auth_methods) + infof(data, "SSH authentication methods available: %s%s%s%s", + sshc->auth_methods & SSH_AUTH_METHOD_PUBLICKEY ? + "public key, ": "", + sshc->auth_methods & SSH_AUTH_METHOD_GSSAPI_MIC ? + "GSSAPI, " : "", + sshc->auth_methods & SSH_AUTH_METHOD_INTERACTIVE ? + "keyboard-interactive, " : "", + sshc->auth_methods & SSH_AUTH_METHOD_PASSWORD ? + "password": ""); + if(sshc->auth_methods & SSH_AUTH_METHOD_PUBLICKEY) { + state(data, SSH_AUTH_PKEY_INIT); + infof(data, "Authentication using SSH public key file"); + } + else if(sshc->auth_methods & SSH_AUTH_METHOD_GSSAPI_MIC) { + state(data, SSH_AUTH_GSSAPI); + } + else if(sshc->auth_methods & SSH_AUTH_METHOD_INTERACTIVE) { + state(data, SSH_AUTH_KEY_INIT); + } + else if(sshc->auth_methods & SSH_AUTH_METHOD_PASSWORD) { + state(data, SSH_AUTH_PASS_INIT); + } + else { /* unsupported authentication method */ + MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED); + break; + } + + break; + } + case SSH_AUTH_PKEY_INIT: + if(!(data->set.ssh_auth_types & CURLSSH_AUTH_PUBLICKEY)) { + MOVE_TO_GSSAPI_AUTH; + break; + } + + /* Two choices, (1) private key was given on CMD, + * (2) use the "default" keys. */ + if(data->set.str[STRING_SSH_PRIVATE_KEY]) { + if(sshc->pubkey && !data->set.ssl.key_passwd) { + rc = ssh_userauth_try_publickey(sshc->ssh_session, NULL, + sshc->pubkey); + if(rc == SSH_AUTH_AGAIN) { + rc = SSH_AGAIN; + break; + } + + if(rc != SSH_OK) { + MOVE_TO_GSSAPI_AUTH; + break; + } + } + + rc = ssh_pki_import_privkey_file(data-> + set.str[STRING_SSH_PRIVATE_KEY], + data->set.ssl.key_passwd, NULL, + NULL, &sshc->privkey); + if(rc != SSH_OK) { + failf(data, "Could not load private key file %s", + data->set.str[STRING_SSH_PRIVATE_KEY]); + MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED); + break; + } + + state(data, SSH_AUTH_PKEY); + break; + + } + else { + rc = ssh_userauth_publickey_auto(sshc->ssh_session, NULL, + data->set.ssl.key_passwd); + if(rc == SSH_AUTH_AGAIN) { + rc = SSH_AGAIN; + break; + } + if(rc == SSH_AUTH_SUCCESS) { + rc = SSH_OK; + sshc->authed = TRUE; + infof(data, "Completed public key authentication"); + state(data, SSH_AUTH_DONE); + break; + } + + MOVE_TO_GSSAPI_AUTH; + } + break; + case SSH_AUTH_PKEY: + rc = ssh_userauth_publickey(sshc->ssh_session, NULL, sshc->privkey); + if(rc == SSH_AUTH_AGAIN) { + rc = SSH_AGAIN; + break; + } + + if(rc == SSH_AUTH_SUCCESS) { + sshc->authed = TRUE; + infof(data, "Completed public key authentication"); + state(data, SSH_AUTH_DONE); + break; + } + else { + infof(data, "Failed public key authentication (rc: %d)", rc); + MOVE_TO_GSSAPI_AUTH; + } + break; + + case SSH_AUTH_GSSAPI: + if(!(data->set.ssh_auth_types & CURLSSH_AUTH_GSSAPI)) { + MOVE_TO_KEY_AUTH; + break; + } + + rc = ssh_userauth_gssapi(sshc->ssh_session); + if(rc == SSH_AUTH_AGAIN) { + rc = SSH_AGAIN; + break; + } + + if(rc == SSH_AUTH_SUCCESS) { + rc = SSH_OK; + sshc->authed = TRUE; + infof(data, "Completed gssapi authentication"); + state(data, SSH_AUTH_DONE); + break; + } + + MOVE_TO_KEY_AUTH; + break; + + case SSH_AUTH_KEY_INIT: + if(data->set.ssh_auth_types & CURLSSH_AUTH_KEYBOARD) { + state(data, SSH_AUTH_KEY); + } + else { + MOVE_TO_PASSWD_AUTH; + } + break; + + case SSH_AUTH_KEY: + /* keyboard-interactive authentication */ + rc = myssh_auth_interactive(conn); + if(rc == SSH_AGAIN) { + break; + } + if(rc == SSH_OK) { + sshc->authed = TRUE; + infof(data, "completed keyboard interactive authentication"); + state(data, SSH_AUTH_DONE); + } + else { + MOVE_TO_PASSWD_AUTH; + } + break; + + case SSH_AUTH_PASS_INIT: + if(!(data->set.ssh_auth_types & CURLSSH_AUTH_PASSWORD)) { + MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED); + break; + } + state(data, SSH_AUTH_PASS); + FALLTHROUGH(); + + case SSH_AUTH_PASS: + rc = ssh_userauth_password(sshc->ssh_session, NULL, conn->passwd); + if(rc == SSH_AUTH_AGAIN) { + rc = SSH_AGAIN; + break; + } + + if(rc == SSH_AUTH_SUCCESS) { + sshc->authed = TRUE; + infof(data, "Completed password authentication"); + state(data, SSH_AUTH_DONE); + } + else { + MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED); + } + break; + + case SSH_AUTH_DONE: + if(!sshc->authed) { + failf(data, "Authentication failure"); + MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED); + break; + } + + /* + * At this point we have an authenticated ssh session. + */ + infof(data, "Authentication complete"); + + Curl_pgrsTime(data, TIMER_APPCONNECT); /* SSH is connected */ + + conn->sockfd = sock; + conn->writesockfd = CURL_SOCKET_BAD; + + if(conn->handler->protocol == CURLPROTO_SFTP) { + state(data, SSH_SFTP_INIT); + break; + } + infof(data, "SSH CONNECT phase done"); + state(data, SSH_STOP); + break; + + case SSH_SFTP_INIT: + ssh_set_blocking(sshc->ssh_session, 1); + + sshc->sftp_session = sftp_new(sshc->ssh_session); + if(!sshc->sftp_session) { + failf(data, "Failure initializing sftp session: %s", + ssh_get_error(sshc->ssh_session)); + MOVE_TO_ERROR_STATE(CURLE_COULDNT_CONNECT); + break; + } + + rc = sftp_init(sshc->sftp_session); + if(rc != SSH_OK) { + failf(data, "Failure initializing sftp session: %s", + ssh_get_error(sshc->ssh_session)); + MOVE_TO_ERROR_STATE(sftp_error_to_CURLE(SSH_FX_FAILURE)); + break; + } + state(data, SSH_SFTP_REALPATH); + FALLTHROUGH(); + case SSH_SFTP_REALPATH: + /* + * Get the "home" directory + */ + sshc->homedir = sftp_canonicalize_path(sshc->sftp_session, "."); + if(!sshc->homedir) { + MOVE_TO_ERROR_STATE(CURLE_COULDNT_CONNECT); + break; + } + data->state.most_recent_ftp_entrypath = sshc->homedir; + + /* This is the last step in the SFTP connect phase. Do note that while + we get the homedir here, we get the "workingpath" in the DO action + since the homedir will remain the same between request but the + working path will not. */ + DEBUGF(infof(data, "SSH CONNECT phase done")); + state(data, SSH_STOP); + break; + + case SSH_SFTP_QUOTE_INIT: + result = Curl_getworkingpath(data, sshc->homedir, &protop->path); + if(result) { + sshc->actualcode = result; + state(data, SSH_STOP); + break; + } + + if(data->set.quote) { + infof(data, "Sending quote commands"); + sshc->quote_item = data->set.quote; + state(data, SSH_SFTP_QUOTE); + } + else { + state(data, SSH_SFTP_GETINFO); + } + break; + + case SSH_SFTP_POSTQUOTE_INIT: + if(data->set.postquote) { + infof(data, "Sending quote commands"); + sshc->quote_item = data->set.postquote; + state(data, SSH_SFTP_QUOTE); + } + else { + state(data, SSH_STOP); + } + break; + + case SSH_SFTP_QUOTE: + /* Send any quote commands */ + sftp_quote(data); + break; + + case SSH_SFTP_NEXT_QUOTE: + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + + sshc->quote_item = sshc->quote_item->next; + + if(sshc->quote_item) { + state(data, SSH_SFTP_QUOTE); + } + else { + if(sshc->nextstate != SSH_NO_STATE) { + state(data, sshc->nextstate); + sshc->nextstate = SSH_NO_STATE; + } + else { + state(data, SSH_SFTP_GETINFO); + } + } + break; + + case SSH_SFTP_QUOTE_STAT: + sftp_quote_stat(data); + break; + + case SSH_SFTP_QUOTE_SETSTAT: + rc = sftp_setstat(sshc->sftp_session, sshc->quote_path2, + sshc->quote_attrs); + if(rc && !sshc->acceptfail) { + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + failf(data, "Attempt to set SFTP stats failed: %s", + ssh_get_error(sshc->ssh_session)); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + /* sshc->actualcode = sftp_error_to_CURLE(err); + * we do not send the actual error; we return + * the error the libssh2 backend is returning */ + break; + } + state(data, SSH_SFTP_NEXT_QUOTE); + break; + + case SSH_SFTP_QUOTE_SYMLINK: + rc = sftp_symlink(sshc->sftp_session, sshc->quote_path2, + sshc->quote_path1); + if(rc && !sshc->acceptfail) { + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + failf(data, "symlink command failed: %s", + ssh_get_error(sshc->ssh_session)); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + state(data, SSH_SFTP_NEXT_QUOTE); + break; + + case SSH_SFTP_QUOTE_MKDIR: + rc = sftp_mkdir(sshc->sftp_session, sshc->quote_path1, + (mode_t)data->set.new_directory_perms); + if(rc && !sshc->acceptfail) { + Curl_safefree(sshc->quote_path1); + failf(data, "mkdir command failed: %s", + ssh_get_error(sshc->ssh_session)); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + state(data, SSH_SFTP_NEXT_QUOTE); + break; + + case SSH_SFTP_QUOTE_RENAME: + rc = sftp_rename(sshc->sftp_session, sshc->quote_path1, + sshc->quote_path2); + if(rc && !sshc->acceptfail) { + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + failf(data, "rename command failed: %s", + ssh_get_error(sshc->ssh_session)); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + state(data, SSH_SFTP_NEXT_QUOTE); + break; + + case SSH_SFTP_QUOTE_RMDIR: + rc = sftp_rmdir(sshc->sftp_session, sshc->quote_path1); + if(rc && !sshc->acceptfail) { + Curl_safefree(sshc->quote_path1); + failf(data, "rmdir command failed: %s", + ssh_get_error(sshc->ssh_session)); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + state(data, SSH_SFTP_NEXT_QUOTE); + break; + + case SSH_SFTP_QUOTE_UNLINK: + rc = sftp_unlink(sshc->sftp_session, sshc->quote_path1); + if(rc && !sshc->acceptfail) { + Curl_safefree(sshc->quote_path1); + failf(data, "rm command failed: %s", + ssh_get_error(sshc->ssh_session)); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + state(data, SSH_SFTP_NEXT_QUOTE); + break; + + case SSH_SFTP_QUOTE_STATVFS: + { + sftp_statvfs_t statvfs; + + statvfs = sftp_statvfs(sshc->sftp_session, sshc->quote_path1); + if(!statvfs && !sshc->acceptfail) { + Curl_safefree(sshc->quote_path1); + failf(data, "statvfs command failed: %s", + ssh_get_error(sshc->ssh_session)); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + else if(statvfs) { + #ifdef _MSC_VER + #define CURL_LIBSSH_VFS_SIZE_MASK "I64u" + #else + #define CURL_LIBSSH_VFS_SIZE_MASK PRIu64 + #endif + char *tmp = aprintf("statvfs:\n" + "f_bsize: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_frsize: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_blocks: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_bfree: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_bavail: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_files: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_ffree: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_favail: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_fsid: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_flag: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_namemax: %" CURL_LIBSSH_VFS_SIZE_MASK "\n", + statvfs->f_bsize, statvfs->f_frsize, + statvfs->f_blocks, statvfs->f_bfree, + statvfs->f_bavail, statvfs->f_files, + statvfs->f_ffree, statvfs->f_favail, + statvfs->f_fsid, statvfs->f_flag, + statvfs->f_namemax); + sftp_statvfs_free(statvfs); + + if(!tmp) { + result = CURLE_OUT_OF_MEMORY; + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + break; + } + + result = Curl_client_write(data, CLIENTWRITE_HEADER, tmp, strlen(tmp)); + free(tmp); + if(result) { + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + } + } + state(data, SSH_SFTP_NEXT_QUOTE); + break; + } + + case SSH_SFTP_GETINFO: + if(data->set.get_filetime) { + state(data, SSH_SFTP_FILETIME); + } + else { + state(data, SSH_SFTP_TRANS_INIT); + } + break; + + case SSH_SFTP_FILETIME: + { + sftp_attributes attrs; + + attrs = sftp_stat(sshc->sftp_session, protop->path); + if(attrs) { + data->info.filetime = attrs->mtime; + sftp_attributes_free(attrs); + } + + state(data, SSH_SFTP_TRANS_INIT); + break; + } + + case SSH_SFTP_TRANS_INIT: + if(data->state.upload) + state(data, SSH_SFTP_UPLOAD_INIT); + else { + if(protop->path[strlen(protop->path)-1] == '/') + state(data, SSH_SFTP_READDIR_INIT); + else + state(data, SSH_SFTP_DOWNLOAD_INIT); + } + break; + + case SSH_SFTP_UPLOAD_INIT: + { + int flags; + + if(data->state.resume_from) { + sftp_attributes attrs; + + if(data->state.resume_from < 0) { + attrs = sftp_stat(sshc->sftp_session, protop->path); + if(attrs) { + curl_off_t size = attrs->size; + if(size < 0) { + failf(data, "Bad file size (%" CURL_FORMAT_CURL_OFF_T ")", size); + MOVE_TO_ERROR_STATE(CURLE_BAD_DOWNLOAD_RESUME); + break; + } + data->state.resume_from = attrs->size; + + sftp_attributes_free(attrs); + } + else { + data->state.resume_from = 0; + } + } + } + + if(data->set.remote_append) + /* Try to open for append, but create if nonexisting */ + flags = O_WRONLY|O_CREAT|O_APPEND; + else if(data->state.resume_from > 0) + /* If we have restart position then open for append */ + flags = O_WRONLY|O_APPEND; + else + /* Clear file before writing (normal behavior) */ + flags = O_WRONLY|O_CREAT|O_TRUNC; + + if(sshc->sftp_file) + sftp_close(sshc->sftp_file); + sshc->sftp_file = + sftp_open(sshc->sftp_session, protop->path, + flags, (mode_t)data->set.new_file_perms); + if(!sshc->sftp_file) { + err = sftp_get_error(sshc->sftp_session); + + if(((err == SSH_FX_NO_SUCH_FILE || err == SSH_FX_FAILURE || + err == SSH_FX_NO_SUCH_PATH)) && + (data->set.ftp_create_missing_dirs && + (strlen(protop->path) > 1))) { + /* try to create the path remotely */ + rc = 0; + sshc->secondCreateDirs = 1; + state(data, SSH_SFTP_CREATE_DIRS_INIT); + break; + } + else { + MOVE_TO_SFTP_CLOSE_STATE(); + break; + } + } + + /* If we have a restart point then we need to seek to the correct + position. */ + if(data->state.resume_from > 0) { + /* Let's read off the proper amount of bytes from the input. */ + if(data->set.seek_func) { + Curl_set_in_callback(data, true); + seekerr = data->set.seek_func(data->set.seek_client, + data->state.resume_from, SEEK_SET); + Curl_set_in_callback(data, false); + } + + if(seekerr != CURL_SEEKFUNC_OK) { + curl_off_t passed = 0; + + if(seekerr != CURL_SEEKFUNC_CANTSEEK) { + failf(data, "Could not seek stream"); + return CURLE_FTP_COULDNT_USE_REST; + } + /* seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */ + do { + char scratch[4*1024]; + size_t readthisamountnow = + (data->state.resume_from - passed > + (curl_off_t)sizeof(scratch)) ? + sizeof(scratch) : curlx_sotouz(data->state.resume_from - passed); + + size_t actuallyread = + data->state.fread_func(scratch, 1, + readthisamountnow, data->state.in); + + passed += actuallyread; + if((actuallyread == 0) || (actuallyread > readthisamountnow)) { + /* this checks for greater-than only to make sure that the + CURL_READFUNC_ABORT return code still aborts */ + failf(data, "Failed to read data"); + MOVE_TO_ERROR_STATE(CURLE_FTP_COULDNT_USE_REST); + break; + } + } while(passed < data->state.resume_from); + if(rc) + break; + } + + /* now, decrease the size of the read */ + if(data->state.infilesize > 0) { + data->state.infilesize -= data->state.resume_from; + data->req.size = data->state.infilesize; + Curl_pgrsSetUploadSize(data, data->state.infilesize); + } + + rc = sftp_seek64(sshc->sftp_file, data->state.resume_from); + if(rc) { + MOVE_TO_SFTP_CLOSE_STATE(); + break; + } + } + if(data->state.infilesize > 0) { + data->req.size = data->state.infilesize; + Curl_pgrsSetUploadSize(data, data->state.infilesize); + } + /* upload data */ + Curl_xfer_setup(data, -1, -1, FALSE, FIRSTSOCKET); + + /* not set by Curl_xfer_setup to preserve keepon bits */ + conn->sockfd = conn->writesockfd; + + /* store this original bitmask setup to use later on if we can't + figure out a "real" bitmask */ + sshc->orig_waitfor = data->req.keepon; + + /* we want to use the _sending_ function even when the socket turns + out readable as the underlying libssh sftp send function will deal + with both accordingly */ + data->state.select_bits = CURL_CSELECT_OUT; + + /* since we don't really wait for anything at this point, we want the + state machine to move on as soon as possible so we set a very short + timeout here */ + Curl_expire(data, 0, EXPIRE_RUN_NOW); + + state(data, SSH_STOP); + break; + } + + case SSH_SFTP_CREATE_DIRS_INIT: + if(strlen(protop->path) > 1) { + sshc->slash_pos = protop->path + 1; /* ignore the leading '/' */ + state(data, SSH_SFTP_CREATE_DIRS); + } + else { + state(data, SSH_SFTP_UPLOAD_INIT); + } + break; + + case SSH_SFTP_CREATE_DIRS: + sshc->slash_pos = strchr(sshc->slash_pos, '/'); + if(sshc->slash_pos) { + *sshc->slash_pos = 0; + + infof(data, "Creating directory '%s'", protop->path); + state(data, SSH_SFTP_CREATE_DIRS_MKDIR); + break; + } + state(data, SSH_SFTP_UPLOAD_INIT); + break; + + case SSH_SFTP_CREATE_DIRS_MKDIR: + /* 'mode' - parameter is preliminary - default to 0644 */ + rc = sftp_mkdir(sshc->sftp_session, protop->path, + (mode_t)data->set.new_directory_perms); + *sshc->slash_pos = '/'; + ++sshc->slash_pos; + if(rc < 0) { + /* + * Abort if failure wasn't that the dir already exists or the + * permission was denied (creation might succeed further down the + * path) - retry on unspecific FAILURE also + */ + err = sftp_get_error(sshc->sftp_session); + if((err != SSH_FX_FILE_ALREADY_EXISTS) && + (err != SSH_FX_FAILURE) && + (err != SSH_FX_PERMISSION_DENIED)) { + MOVE_TO_SFTP_CLOSE_STATE(); + break; + } + rc = 0; /* clear rc and continue */ + } + state(data, SSH_SFTP_CREATE_DIRS); + break; + + case SSH_SFTP_READDIR_INIT: + Curl_pgrsSetDownloadSize(data, -1); + if(data->req.no_body) { + state(data, SSH_STOP); + break; + } + + /* + * This is a directory that we are trying to get, so produce a directory + * listing + */ + sshc->sftp_dir = sftp_opendir(sshc->sftp_session, + protop->path); + if(!sshc->sftp_dir) { + failf(data, "Could not open directory for reading: %s", + ssh_get_error(sshc->ssh_session)); + MOVE_TO_SFTP_CLOSE_STATE(); + break; + } + state(data, SSH_SFTP_READDIR); + break; + + case SSH_SFTP_READDIR: + Curl_dyn_reset(&sshc->readdir_buf); + if(sshc->readdir_attrs) + sftp_attributes_free(sshc->readdir_attrs); + + sshc->readdir_attrs = sftp_readdir(sshc->sftp_session, sshc->sftp_dir); + if(sshc->readdir_attrs) { + sshc->readdir_filename = sshc->readdir_attrs->name; + sshc->readdir_longentry = sshc->readdir_attrs->longname; + sshc->readdir_len = strlen(sshc->readdir_filename); + + if(data->set.list_only) { + char *tmpLine; + + tmpLine = aprintf("%s\n", sshc->readdir_filename); + if(!tmpLine) { + state(data, SSH_SFTP_CLOSE); + sshc->actualcode = CURLE_OUT_OF_MEMORY; + break; + } + result = Curl_client_write(data, CLIENTWRITE_BODY, + tmpLine, sshc->readdir_len + 1); + free(tmpLine); + + if(result) { + state(data, SSH_STOP); + break; + } + + } + else { + if(Curl_dyn_add(&sshc->readdir_buf, sshc->readdir_longentry)) { + sshc->actualcode = CURLE_OUT_OF_MEMORY; + state(data, SSH_STOP); + break; + } + + if((sshc->readdir_attrs->flags & SSH_FILEXFER_ATTR_PERMISSIONS) && + ((sshc->readdir_attrs->permissions & SSH_S_IFMT) == + SSH_S_IFLNK)) { + sshc->readdir_linkPath = aprintf("%s%s", protop->path, + sshc->readdir_filename); + + if(!sshc->readdir_linkPath) { + state(data, SSH_SFTP_CLOSE); + sshc->actualcode = CURLE_OUT_OF_MEMORY; + break; + } + + state(data, SSH_SFTP_READDIR_LINK); + break; + } + state(data, SSH_SFTP_READDIR_BOTTOM); + break; + } + } + else if(sftp_dir_eof(sshc->sftp_dir)) { + state(data, SSH_SFTP_READDIR_DONE); + break; + } + else { + failf(data, "Could not open remote file for reading: %s", + ssh_get_error(sshc->ssh_session)); + MOVE_TO_SFTP_CLOSE_STATE(); + break; + } + break; + + case SSH_SFTP_READDIR_LINK: + if(sshc->readdir_link_attrs) + sftp_attributes_free(sshc->readdir_link_attrs); + + sshc->readdir_link_attrs = sftp_lstat(sshc->sftp_session, + sshc->readdir_linkPath); + if(sshc->readdir_link_attrs == 0) { + failf(data, "Could not read symlink for reading: %s", + ssh_get_error(sshc->ssh_session)); + MOVE_TO_SFTP_CLOSE_STATE(); + break; + } + + if(!sshc->readdir_link_attrs->name) { + sshc->readdir_tmp = sftp_readlink(sshc->sftp_session, + sshc->readdir_linkPath); + if(!sshc->readdir_filename) + sshc->readdir_len = 0; + else + sshc->readdir_len = strlen(sshc->readdir_tmp); + sshc->readdir_longentry = NULL; + sshc->readdir_filename = sshc->readdir_tmp; + } + else { + sshc->readdir_len = strlen(sshc->readdir_link_attrs->name); + sshc->readdir_filename = sshc->readdir_link_attrs->name; + sshc->readdir_longentry = sshc->readdir_link_attrs->longname; + } + + Curl_safefree(sshc->readdir_linkPath); + + if(Curl_dyn_addf(&sshc->readdir_buf, " -> %s", + sshc->readdir_filename)) { + sshc->actualcode = CURLE_OUT_OF_MEMORY; + break; + } + + sftp_attributes_free(sshc->readdir_link_attrs); + sshc->readdir_link_attrs = NULL; + sshc->readdir_filename = NULL; + sshc->readdir_longentry = NULL; + + state(data, SSH_SFTP_READDIR_BOTTOM); + FALLTHROUGH(); + case SSH_SFTP_READDIR_BOTTOM: + if(Curl_dyn_addn(&sshc->readdir_buf, "\n", 1)) + result = CURLE_OUT_OF_MEMORY; + else + result = Curl_client_write(data, CLIENTWRITE_BODY, + Curl_dyn_ptr(&sshc->readdir_buf), + Curl_dyn_len(&sshc->readdir_buf)); + + ssh_string_free_char(sshc->readdir_tmp); + sshc->readdir_tmp = NULL; + + if(result) { + state(data, SSH_STOP); + } + else + state(data, SSH_SFTP_READDIR); + break; + + case SSH_SFTP_READDIR_DONE: + sftp_closedir(sshc->sftp_dir); + sshc->sftp_dir = NULL; + + /* no data to transfer */ + Curl_xfer_setup(data, -1, -1, FALSE, -1); + state(data, SSH_STOP); + break; + + case SSH_SFTP_DOWNLOAD_INIT: + /* + * Work on getting the specified file + */ + if(sshc->sftp_file) + sftp_close(sshc->sftp_file); + + sshc->sftp_file = sftp_open(sshc->sftp_session, protop->path, + O_RDONLY, (mode_t)data->set.new_file_perms); + if(!sshc->sftp_file) { + failf(data, "Could not open remote file for reading: %s", + ssh_get_error(sshc->ssh_session)); + + MOVE_TO_SFTP_CLOSE_STATE(); + break; + } + sftp_file_set_nonblocking(sshc->sftp_file); + state(data, SSH_SFTP_DOWNLOAD_STAT); + break; + + case SSH_SFTP_DOWNLOAD_STAT: + { + sftp_attributes attrs; + curl_off_t size; + + attrs = sftp_fstat(sshc->sftp_file); + if(!attrs || + !(attrs->flags & SSH_FILEXFER_ATTR_SIZE) || + (attrs->size == 0)) { + /* + * sftp_fstat didn't return an error, so maybe the server + * just doesn't support stat() + * OR the server doesn't return a file size with a stat() + * OR file size is 0 + */ + data->req.size = -1; + data->req.maxdownload = -1; + Curl_pgrsSetDownloadSize(data, -1); + size = 0; + } + else { + size = attrs->size; + + sftp_attributes_free(attrs); + + if(size < 0) { + failf(data, "Bad file size (%" CURL_FORMAT_CURL_OFF_T ")", size); + return CURLE_BAD_DOWNLOAD_RESUME; + } + if(data->state.use_range) { + curl_off_t from, to; + char *ptr; + char *ptr2; + CURLofft to_t; + CURLofft from_t; + + from_t = curlx_strtoofft(data->state.range, &ptr, 10, &from); + if(from_t == CURL_OFFT_FLOW) { + return CURLE_RANGE_ERROR; + } + while(*ptr && (ISBLANK(*ptr) || (*ptr == '-'))) + ptr++; + to_t = curlx_strtoofft(ptr, &ptr2, 10, &to); + if(to_t == CURL_OFFT_FLOW) { + return CURLE_RANGE_ERROR; + } + if((to_t == CURL_OFFT_INVAL) /* no "to" value given */ + || (to >= size)) { + to = size - 1; + } + if(from_t) { + /* from is relative to end of file */ + from = size - to; + to = size - 1; + } + if(from > size) { + failf(data, "Offset (%" + CURL_FORMAT_CURL_OFF_T ") was beyond file size (%" + CURL_FORMAT_CURL_OFF_T ")", from, size); + return CURLE_BAD_DOWNLOAD_RESUME; + } + if(from > to) { + from = to; + size = 0; + } + else { + if((to - from) == CURL_OFF_T_MAX) + return CURLE_RANGE_ERROR; + size = to - from + 1; + } + + rc = sftp_seek64(sshc->sftp_file, from); + if(rc) { + MOVE_TO_SFTP_CLOSE_STATE(); + break; + } + } + data->req.size = size; + data->req.maxdownload = size; + Curl_pgrsSetDownloadSize(data, size); + } + + /* We can resume if we can seek to the resume position */ + if(data->state.resume_from) { + if(data->state.resume_from < 0) { + /* We're supposed to download the last abs(from) bytes */ + if((curl_off_t)size < -data->state.resume_from) { + failf(data, "Offset (%" + CURL_FORMAT_CURL_OFF_T ") was beyond file size (%" + CURL_FORMAT_CURL_OFF_T ")", + data->state.resume_from, size); + return CURLE_BAD_DOWNLOAD_RESUME; + } + /* download from where? */ + data->state.resume_from += size; + } + else { + if((curl_off_t)size < data->state.resume_from) { + failf(data, "Offset (%" CURL_FORMAT_CURL_OFF_T + ") was beyond file size (%" CURL_FORMAT_CURL_OFF_T ")", + data->state.resume_from, size); + return CURLE_BAD_DOWNLOAD_RESUME; + } + } + /* Now store the number of bytes we are expected to download */ + data->req.size = size - data->state.resume_from; + data->req.maxdownload = size - data->state.resume_from; + Curl_pgrsSetDownloadSize(data, + size - data->state.resume_from); + + rc = sftp_seek64(sshc->sftp_file, data->state.resume_from); + if(rc) { + MOVE_TO_SFTP_CLOSE_STATE(); + break; + } + } + } + + /* Setup the actual download */ + if(data->req.size == 0) { + /* no data to transfer */ + Curl_xfer_setup(data, -1, -1, FALSE, -1); + infof(data, "File already completely downloaded"); + state(data, SSH_STOP); + break; + } + Curl_xfer_setup(data, FIRSTSOCKET, data->req.size, FALSE, -1); + + /* not set by Curl_xfer_setup to preserve keepon bits */ + conn->writesockfd = conn->sockfd; + + /* we want to use the _receiving_ function even when the socket turns + out writableable as the underlying libssh recv function will deal + with both accordingly */ + data->state.select_bits = CURL_CSELECT_IN; + + if(result) { + /* this should never occur; the close state should be entered + at the time the error occurs */ + state(data, SSH_SFTP_CLOSE); + sshc->actualcode = result; + } + else { + sshc->sftp_recv_state = 0; + state(data, SSH_STOP); + } + break; + + case SSH_SFTP_CLOSE: + if(sshc->sftp_file) { + sftp_close(sshc->sftp_file); + sshc->sftp_file = NULL; + } + Curl_safefree(protop->path); + + DEBUGF(infof(data, "SFTP DONE done")); + + /* Check if nextstate is set and move .nextstate could be POSTQUOTE_INIT + After nextstate is executed, the control should come back to + SSH_SFTP_CLOSE to pass the correct result back */ + if(sshc->nextstate != SSH_NO_STATE && + sshc->nextstate != SSH_SFTP_CLOSE) { + state(data, sshc->nextstate); + sshc->nextstate = SSH_SFTP_CLOSE; + } + else { + state(data, SSH_STOP); + result = sshc->actualcode; + } + break; + + case SSH_SFTP_SHUTDOWN: + /* during times we get here due to a broken transfer and then the + sftp_handle might not have been taken down so make sure that is done + before we proceed */ + + if(sshc->sftp_file) { + sftp_close(sshc->sftp_file); + sshc->sftp_file = NULL; + } + + if(sshc->sftp_session) { + sftp_free(sshc->sftp_session); + sshc->sftp_session = NULL; + } + + SSH_STRING_FREE_CHAR(sshc->homedir); + data->state.most_recent_ftp_entrypath = NULL; + + state(data, SSH_SESSION_DISCONNECT); + break; + + case SSH_SCP_TRANS_INIT: + result = Curl_getworkingpath(data, sshc->homedir, &protop->path); + if(result) { + sshc->actualcode = result; + state(data, SSH_STOP); + break; + } + + /* Functions from the SCP subsystem cannot handle/return SSH_AGAIN */ + ssh_set_blocking(sshc->ssh_session, 1); + + if(data->state.upload) { + if(data->state.infilesize < 0) { + failf(data, "SCP requires a known file size for upload"); + sshc->actualcode = CURLE_UPLOAD_FAILED; + MOVE_TO_ERROR_STATE(CURLE_UPLOAD_FAILED); + break; + } + + sshc->scp_session = + ssh_scp_new(sshc->ssh_session, SSH_SCP_WRITE, protop->path); + state(data, SSH_SCP_UPLOAD_INIT); + } + else { + sshc->scp_session = + ssh_scp_new(sshc->ssh_session, SSH_SCP_READ, protop->path); + state(data, SSH_SCP_DOWNLOAD_INIT); + } + + if(!sshc->scp_session) { + err_msg = ssh_get_error(sshc->ssh_session); + failf(data, "%s", err_msg); + MOVE_TO_ERROR_STATE(CURLE_UPLOAD_FAILED); + } + + break; + + case SSH_SCP_UPLOAD_INIT: + + rc = ssh_scp_init(sshc->scp_session); + if(rc != SSH_OK) { + err_msg = ssh_get_error(sshc->ssh_session); + failf(data, "%s", err_msg); + MOVE_TO_ERROR_STATE(CURLE_UPLOAD_FAILED); + break; + } + + rc = ssh_scp_push_file(sshc->scp_session, protop->path, + data->state.infilesize, + (int)data->set.new_file_perms); + if(rc != SSH_OK) { + err_msg = ssh_get_error(sshc->ssh_session); + failf(data, "%s", err_msg); + MOVE_TO_ERROR_STATE(CURLE_UPLOAD_FAILED); + break; + } + + /* upload data */ + Curl_xfer_setup(data, -1, data->req.size, FALSE, FIRSTSOCKET); + + /* not set by Curl_xfer_setup to preserve keepon bits */ + conn->sockfd = conn->writesockfd; + + /* store this original bitmask setup to use later on if we can't + figure out a "real" bitmask */ + sshc->orig_waitfor = data->req.keepon; + + /* we want to use the _sending_ function even when the socket turns + out readable as the underlying libssh scp send function will deal + with both accordingly */ + data->state.select_bits = CURL_CSELECT_OUT; + + state(data, SSH_STOP); + + break; + + case SSH_SCP_DOWNLOAD_INIT: + + rc = ssh_scp_init(sshc->scp_session); + if(rc != SSH_OK) { + err_msg = ssh_get_error(sshc->ssh_session); + failf(data, "%s", err_msg); + MOVE_TO_ERROR_STATE(CURLE_COULDNT_CONNECT); + break; + } + state(data, SSH_SCP_DOWNLOAD); + FALLTHROUGH(); + + case SSH_SCP_DOWNLOAD:{ + curl_off_t bytecount; + + rc = ssh_scp_pull_request(sshc->scp_session); + if(rc != SSH_SCP_REQUEST_NEWFILE) { + err_msg = ssh_get_error(sshc->ssh_session); + failf(data, "%s", err_msg); + MOVE_TO_ERROR_STATE(CURLE_REMOTE_FILE_NOT_FOUND); + break; + } + + /* download data */ + bytecount = ssh_scp_request_get_size(sshc->scp_session); + data->req.maxdownload = (curl_off_t) bytecount; + Curl_xfer_setup(data, FIRSTSOCKET, bytecount, FALSE, -1); + + /* not set by Curl_xfer_setup to preserve keepon bits */ + conn->writesockfd = conn->sockfd; + + /* we want to use the _receiving_ function even when the socket turns + out writableable as the underlying libssh recv function will deal + with both accordingly */ + data->state.select_bits = CURL_CSELECT_IN; + + state(data, SSH_STOP); + break; + } + case SSH_SCP_DONE: + if(data->state.upload) + state(data, SSH_SCP_SEND_EOF); + else + state(data, SSH_SCP_CHANNEL_FREE); + break; + + case SSH_SCP_SEND_EOF: + if(sshc->scp_session) { + rc = ssh_scp_close(sshc->scp_session); + if(rc == SSH_AGAIN) { + /* Currently the ssh_scp_close handles waiting for EOF in + * blocking way. + */ + break; + } + if(rc != SSH_OK) { + infof(data, "Failed to close libssh scp channel: %s", + ssh_get_error(sshc->ssh_session)); + } + } + + state(data, SSH_SCP_CHANNEL_FREE); + break; + + case SSH_SCP_CHANNEL_FREE: + if(sshc->scp_session) { + ssh_scp_free(sshc->scp_session); + sshc->scp_session = NULL; + } + DEBUGF(infof(data, "SCP DONE phase complete")); + + ssh_set_blocking(sshc->ssh_session, 0); + + state(data, SSH_SESSION_DISCONNECT); + FALLTHROUGH(); + + case SSH_SESSION_DISCONNECT: + /* during weird times when we've been prematurely aborted, the channel + is still alive when we reach this state and we MUST kill the channel + properly first */ + if(sshc->scp_session) { + ssh_scp_free(sshc->scp_session); + sshc->scp_session = NULL; + } + + ssh_disconnect(sshc->ssh_session); + if(!ssh_version(SSH_VERSION_INT(0, 10, 0))) { + /* conn->sock[FIRSTSOCKET] is closed by ssh_disconnect behind our back, + tell the connection to forget about it. This libssh + bug is fixed in 0.10.0. */ + Curl_conn_forget_socket(data, FIRSTSOCKET); + } + + SSH_STRING_FREE_CHAR(sshc->homedir); + data->state.most_recent_ftp_entrypath = NULL; + + state(data, SSH_SESSION_FREE); + FALLTHROUGH(); + case SSH_SESSION_FREE: + if(sshc->ssh_session) { + ssh_free(sshc->ssh_session); + sshc->ssh_session = NULL; + } + + /* worst-case scenario cleanup */ + + DEBUGASSERT(sshc->ssh_session == NULL); + DEBUGASSERT(sshc->scp_session == NULL); + + if(sshc->readdir_tmp) { + ssh_string_free_char(sshc->readdir_tmp); + sshc->readdir_tmp = NULL; + } + + if(sshc->quote_attrs) + sftp_attributes_free(sshc->quote_attrs); + + if(sshc->readdir_attrs) + sftp_attributes_free(sshc->readdir_attrs); + + if(sshc->readdir_link_attrs) + sftp_attributes_free(sshc->readdir_link_attrs); + + if(sshc->privkey) + ssh_key_free(sshc->privkey); + if(sshc->pubkey) + ssh_key_free(sshc->pubkey); + + Curl_safefree(sshc->rsa_pub); + Curl_safefree(sshc->rsa); + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + Curl_dyn_free(&sshc->readdir_buf); + Curl_safefree(sshc->readdir_linkPath); + SSH_STRING_FREE_CHAR(sshc->homedir); + + /* the code we are about to return */ + result = sshc->actualcode; + + memset(sshc, 0, sizeof(struct ssh_conn)); + + connclose(conn, "SSH session free"); + sshc->state = SSH_SESSION_FREE; /* current */ + sshc->nextstate = SSH_NO_STATE; + state(data, SSH_STOP); + break; + + case SSH_QUIT: + default: + /* internal error */ + sshc->nextstate = SSH_NO_STATE; + state(data, SSH_STOP); + break; + + } + } while(!rc && (sshc->state != SSH_STOP)); + + + if(rc == SSH_AGAIN) { + /* we would block, we need to wait for the socket to be ready (in the + right direction too)! */ + *block = TRUE; + } + + return result; +} + + +/* called by the multi interface to figure out what socket(s) to wait for and + for what actions in the DO_DONE, PERFORM and WAITPERFORM states */ +static int myssh_getsock(struct Curl_easy *data, + struct connectdata *conn, + curl_socket_t *sock) +{ + int bitmap = GETSOCK_BLANK; + (void)data; + sock[0] = conn->sock[FIRSTSOCKET]; + + if(conn->waitfor & KEEP_RECV) + bitmap |= GETSOCK_READSOCK(FIRSTSOCKET); + + if(conn->waitfor & KEEP_SEND) + bitmap |= GETSOCK_WRITESOCK(FIRSTSOCKET); + + if(!conn->waitfor) + bitmap |= GETSOCK_WRITESOCK(FIRSTSOCKET); + + return bitmap; +} + +static void myssh_block2waitfor(struct connectdata *conn, bool block) +{ + struct ssh_conn *sshc = &conn->proto.sshc; + + /* If it didn't block, or nothing was returned by ssh_get_poll_flags + * have the original set */ + conn->waitfor = sshc->orig_waitfor; + + if(block) { + int dir = ssh_get_poll_flags(sshc->ssh_session); + if(dir & SSH_READ_PENDING) { + /* translate the libssh define bits into our own bit defines */ + conn->waitfor = KEEP_RECV; + } + else if(dir & SSH_WRITE_PENDING) { + conn->waitfor = KEEP_SEND; + } + } +} + +/* called repeatedly until done from multi.c */ +static CURLcode myssh_multi_statemach(struct Curl_easy *data, + bool *done) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + bool block; /* we store the status and use that to provide a ssh_getsock() + implementation */ + CURLcode result = myssh_statemach_act(data, &block); + + *done = (sshc->state == SSH_STOP) ? TRUE : FALSE; + myssh_block2waitfor(conn, block); + + return result; +} + +static CURLcode myssh_block_statemach(struct Curl_easy *data, + bool disconnect) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + CURLcode result = CURLE_OK; + + while((sshc->state != SSH_STOP) && !result) { + bool block; + timediff_t left = 1000; + struct curltime now = Curl_now(); + + result = myssh_statemach_act(data, &block); + if(result) + break; + + if(!disconnect) { + if(Curl_pgrsUpdate(data)) + return CURLE_ABORTED_BY_CALLBACK; + + result = Curl_speedcheck(data, now); + if(result) + break; + + left = Curl_timeleft(data, NULL, FALSE); + if(left < 0) { + failf(data, "Operation timed out"); + return CURLE_OPERATION_TIMEDOUT; + } + } + + if(block) { + curl_socket_t fd_read = conn->sock[FIRSTSOCKET]; + /* wait for the socket to become ready */ + (void) Curl_socket_check(fd_read, CURL_SOCKET_BAD, + CURL_SOCKET_BAD, left > 1000 ? 1000 : left); + } + + } + + return result; +} + +/* + * SSH setup connection + */ +static CURLcode myssh_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + struct SSHPROTO *ssh; + struct ssh_conn *sshc = &conn->proto.sshc; + + data->req.p.ssh = ssh = calloc(1, sizeof(struct SSHPROTO)); + if(!ssh) + return CURLE_OUT_OF_MEMORY; + Curl_dyn_init(&sshc->readdir_buf, PATH_MAX * 2); + + return CURLE_OK; +} + +static Curl_recv scp_recv, sftp_recv; +static Curl_send scp_send, sftp_send; + +/* + * Curl_ssh_connect() gets called from Curl_protocol_connect() to allow us to + * do protocol-specific actions at connect-time. + */ +static CURLcode myssh_connect(struct Curl_easy *data, bool *done) +{ + struct ssh_conn *ssh; + CURLcode result; + struct connectdata *conn = data->conn; + curl_socket_t sock = conn->sock[FIRSTSOCKET]; + int rc; + + /* initialize per-handle data if not already */ + if(!data->req.p.ssh) + myssh_setup_connection(data, conn); + + /* We default to persistent connections. We set this already in this connect + function to make the reuse checks properly be able to check this bit. */ + connkeep(conn, "SSH default"); + + if(conn->handler->protocol & CURLPROTO_SCP) { + conn->recv[FIRSTSOCKET] = scp_recv; + conn->send[FIRSTSOCKET] = scp_send; + } + else { + conn->recv[FIRSTSOCKET] = sftp_recv; + conn->send[FIRSTSOCKET] = sftp_send; + } + + ssh = &conn->proto.sshc; + + ssh->ssh_session = ssh_new(); + if(!ssh->ssh_session) { + failf(data, "Failure initialising ssh session"); + return CURLE_FAILED_INIT; + } + + rc = ssh_options_set(ssh->ssh_session, SSH_OPTIONS_HOST, conn->host.name); + if(rc != SSH_OK) { + failf(data, "Could not set remote host"); + return CURLE_FAILED_INIT; + } + + rc = ssh_options_parse_config(ssh->ssh_session, NULL); + if(rc != SSH_OK) { + infof(data, "Could not parse SSH configuration files"); + /* ignore */ + } + + rc = ssh_options_set(ssh->ssh_session, SSH_OPTIONS_FD, &sock); + if(rc != SSH_OK) { + failf(data, "Could not set socket"); + return CURLE_FAILED_INIT; + } + + if(conn->user && conn->user[0] != '\0') { + infof(data, "User: %s", conn->user); + rc = ssh_options_set(ssh->ssh_session, SSH_OPTIONS_USER, conn->user); + if(rc != SSH_OK) { + failf(data, "Could not set user"); + return CURLE_FAILED_INIT; + } + } + + if(data->set.str[STRING_SSH_KNOWNHOSTS]) { + infof(data, "Known hosts: %s", data->set.str[STRING_SSH_KNOWNHOSTS]); + rc = ssh_options_set(ssh->ssh_session, SSH_OPTIONS_KNOWNHOSTS, + data->set.str[STRING_SSH_KNOWNHOSTS]); + if(rc != SSH_OK) { + failf(data, "Could not set known hosts file path"); + return CURLE_FAILED_INIT; + } + } + + if(conn->remote_port) { + rc = ssh_options_set(ssh->ssh_session, SSH_OPTIONS_PORT, + &conn->remote_port); + if(rc != SSH_OK) { + failf(data, "Could not set remote port"); + return CURLE_FAILED_INIT; + } + } + + if(data->set.ssh_compression) { + rc = ssh_options_set(ssh->ssh_session, SSH_OPTIONS_COMPRESSION, + "zlib,zlib@openssh.com,none"); + if(rc != SSH_OK) { + failf(data, "Could not set compression"); + return CURLE_FAILED_INIT; + } + } + + ssh->privkey = NULL; + ssh->pubkey = NULL; + + if(data->set.str[STRING_SSH_PUBLIC_KEY]) { + rc = ssh_pki_import_pubkey_file(data->set.str[STRING_SSH_PUBLIC_KEY], + &ssh->pubkey); + if(rc != SSH_OK) { + failf(data, "Could not load public key file"); + return CURLE_FAILED_INIT; + } + } + + /* we do not verify here, we do it at the state machine, + * after connection */ + + state(data, SSH_INIT); + + result = myssh_multi_statemach(data, done); + + return result; +} + +/* called from multi.c while DOing */ +static CURLcode scp_doing(struct Curl_easy *data, bool *dophase_done) +{ + CURLcode result; + + result = myssh_multi_statemach(data, dophase_done); + + if(*dophase_done) { + DEBUGF(infof(data, "DO phase is complete")); + } + return result; +} + +/* + *********************************************************************** + * + * scp_perform() + * + * This is the actual DO function for SCP. Get a file according to + * the options previously setup. + */ + +static +CURLcode scp_perform(struct Curl_easy *data, + bool *connected, bool *dophase_done) +{ + CURLcode result = CURLE_OK; + + DEBUGF(infof(data, "DO phase starts")); + + *dophase_done = FALSE; /* not done yet */ + + /* start the first command in the DO phase */ + state(data, SSH_SCP_TRANS_INIT); + + result = myssh_multi_statemach(data, dophase_done); + + *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET); + + if(*dophase_done) { + DEBUGF(infof(data, "DO phase is complete")); + } + + return result; +} + +static CURLcode myssh_do_it(struct Curl_easy *data, bool *done) +{ + CURLcode result; + bool connected = 0; + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + + *done = FALSE; /* default to false */ + + data->req.size = -1; /* make sure this is unknown at this point */ + + sshc->actualcode = CURLE_OK; /* reset error code */ + sshc->secondCreateDirs = 0; /* reset the create dir attempt state + variable */ + + Curl_pgrsSetUploadCounter(data, 0); + Curl_pgrsSetDownloadCounter(data, 0); + Curl_pgrsSetUploadSize(data, -1); + Curl_pgrsSetDownloadSize(data, -1); + + if(conn->handler->protocol & CURLPROTO_SCP) + result = scp_perform(data, &connected, done); + else + result = sftp_perform(data, &connected, done); + + return result; +} + +/* BLOCKING, but the function is using the state machine so the only reason + this is still blocking is that the multi interface code has no support for + disconnecting operations that takes a while */ +static CURLcode scp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + CURLcode result = CURLE_OK; + struct ssh_conn *ssh = &conn->proto.sshc; + (void) dead_connection; + + if(ssh->ssh_session) { + /* only if there's a session still around to use! */ + + state(data, SSH_SESSION_DISCONNECT); + + result = myssh_block_statemach(data, TRUE); + } + + return result; +} + +/* generic done function for both SCP and SFTP called from their specific + done functions */ +static CURLcode myssh_done(struct Curl_easy *data, CURLcode status) +{ + CURLcode result = CURLE_OK; + struct SSHPROTO *protop = data->req.p.ssh; + + if(!status) { + /* run the state-machine */ + result = myssh_block_statemach(data, FALSE); + } + else + result = status; + + if(protop) + Curl_safefree(protop->path); + if(Curl_pgrsDone(data)) + return CURLE_ABORTED_BY_CALLBACK; + + data->req.keepon = 0; /* clear all bits */ + return result; +} + + +static CURLcode scp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + (void) premature; /* not used */ + + if(!status) + state(data, SSH_SCP_DONE); + + return myssh_done(data, status); + +} + +static ssize_t scp_send(struct Curl_easy *data, int sockindex, + const void *mem, size_t len, CURLcode *err) +{ + int rc; + struct connectdata *conn = data->conn; + (void) sockindex; /* we only support SCP on the fixed known primary socket */ + (void) err; + + rc = ssh_scp_write(conn->proto.sshc.scp_session, mem, len); + +#if 0 + /* The following code is misleading, mostly added as wishful thinking + * that libssh at some point will implement non-blocking ssh_scp_write/read. + * Currently rc can only be number of bytes read or SSH_ERROR. */ + myssh_block2waitfor(conn, (rc == SSH_AGAIN) ? TRUE : FALSE); + + if(rc == SSH_AGAIN) { + *err = CURLE_AGAIN; + return 0; + } + else +#endif + if(rc != SSH_OK) { + *err = CURLE_SSH; + return -1; + } + + return len; +} + +static ssize_t scp_recv(struct Curl_easy *data, int sockindex, + char *mem, size_t len, CURLcode *err) +{ + ssize_t nread; + struct connectdata *conn = data->conn; + (void) err; + (void) sockindex; /* we only support SCP on the fixed known primary socket */ + + /* libssh returns int */ + nread = ssh_scp_read(conn->proto.sshc.scp_session, mem, len); + +#if 0 + /* The following code is misleading, mostly added as wishful thinking + * that libssh at some point will implement non-blocking ssh_scp_write/read. + * Currently rc can only be SSH_OK or SSH_ERROR. */ + + myssh_block2waitfor(conn, (nread == SSH_AGAIN) ? TRUE : FALSE); + if(nread == SSH_AGAIN) { + *err = CURLE_AGAIN; + nread = -1; + } +#endif + + return nread; +} + +/* + * =============== SFTP =============== + */ + +/* + *********************************************************************** + * + * sftp_perform() + * + * This is the actual DO function for SFTP. Get a file/directory according to + * the options previously setup. + */ + +static +CURLcode sftp_perform(struct Curl_easy *data, + bool *connected, + bool *dophase_done) +{ + CURLcode result = CURLE_OK; + + DEBUGF(infof(data, "DO phase starts")); + + *dophase_done = FALSE; /* not done yet */ + + /* start the first command in the DO phase */ + state(data, SSH_SFTP_QUOTE_INIT); + + /* run the state-machine */ + result = myssh_multi_statemach(data, dophase_done); + + *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET); + + if(*dophase_done) { + DEBUGF(infof(data, "DO phase is complete")); + } + + return result; +} + +/* called from multi.c while DOing */ +static CURLcode sftp_doing(struct Curl_easy *data, + bool *dophase_done) +{ + CURLcode result = myssh_multi_statemach(data, dophase_done); + if(*dophase_done) { + DEBUGF(infof(data, "DO phase is complete")); + } + return result; +} + +/* BLOCKING, but the function is using the state machine so the only reason + this is still blocking is that the multi interface code has no support for + disconnecting operations that takes a while */ +static CURLcode sftp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + CURLcode result = CURLE_OK; + (void) dead_connection; + + DEBUGF(infof(data, "SSH DISCONNECT starts now")); + + if(conn->proto.sshc.ssh_session) { + /* only if there's a session still around to use! */ + state(data, SSH_SFTP_SHUTDOWN); + result = myssh_block_statemach(data, TRUE); + } + + DEBUGF(infof(data, "SSH DISCONNECT is done")); + + return result; + +} + +static CURLcode sftp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + + if(!status) { + /* Post quote commands are executed after the SFTP_CLOSE state to avoid + errors that could happen due to open file handles during POSTQUOTE + operation */ + if(!premature && data->set.postquote && !conn->bits.retry) + sshc->nextstate = SSH_SFTP_POSTQUOTE_INIT; + state(data, SSH_SFTP_CLOSE); + } + return myssh_done(data, status); +} + +/* return number of sent bytes */ +static ssize_t sftp_send(struct Curl_easy *data, int sockindex, + const void *mem, size_t len, CURLcode *err) +{ + ssize_t nwrite; + struct connectdata *conn = data->conn; + (void)sockindex; + + /* limit the writes to the maximum specified in Section 3 of + * https://datatracker.ietf.org/doc/html/draft-ietf-secsh-filexfer-02 + */ + if(len > 32768) + len = 32768; + + nwrite = sftp_write(conn->proto.sshc.sftp_file, mem, len); + + myssh_block2waitfor(conn, FALSE); + +#if 0 /* not returned by libssh on write */ + if(nwrite == SSH_AGAIN) { + *err = CURLE_AGAIN; + nwrite = 0; + } + else +#endif + if(nwrite < 0) { + *err = CURLE_SSH; + nwrite = -1; + } + + return nwrite; +} + +/* + * Return number of received (decrypted) bytes + * or <0 on error + */ +static ssize_t sftp_recv(struct Curl_easy *data, int sockindex, + char *mem, size_t len, CURLcode *err) +{ + ssize_t nread; + struct connectdata *conn = data->conn; + (void)sockindex; + + DEBUGASSERT(len < CURL_MAX_READ_SIZE); + + switch(conn->proto.sshc.sftp_recv_state) { + case 0: + conn->proto.sshc.sftp_file_index = + sftp_async_read_begin(conn->proto.sshc.sftp_file, + (uint32_t)len); + if(conn->proto.sshc.sftp_file_index < 0) { + *err = CURLE_RECV_ERROR; + return -1; + } + + FALLTHROUGH(); + case 1: + conn->proto.sshc.sftp_recv_state = 1; + + nread = sftp_async_read(conn->proto.sshc.sftp_file, + mem, (uint32_t)len, + conn->proto.sshc.sftp_file_index); + + myssh_block2waitfor(conn, (nread == SSH_AGAIN)?TRUE:FALSE); + + if(nread == SSH_AGAIN) { + *err = CURLE_AGAIN; + return -1; + } + else if(nread < 0) { + *err = CURLE_RECV_ERROR; + return -1; + } + + conn->proto.sshc.sftp_recv_state = 0; + return nread; + + default: + /* we never reach here */ + return -1; + } +} + +static void sftp_quote(struct Curl_easy *data) +{ + const char *cp; + struct connectdata *conn = data->conn; + struct SSHPROTO *protop = data->req.p.ssh; + struct ssh_conn *sshc = &conn->proto.sshc; + CURLcode result; + + /* + * Support some of the "FTP" commands + */ + char *cmd = sshc->quote_item->data; + sshc->acceptfail = FALSE; + + /* if a command starts with an asterisk, which a legal SFTP command never + can, the command will be allowed to fail without it causing any + aborts or cancels etc. It will cause libcurl to act as if the command + is successful, whatever the server responds. */ + + if(cmd[0] == '*') { + cmd++; + sshc->acceptfail = TRUE; + } + + if(strcasecompare("pwd", cmd)) { + /* output debug output if that is requested */ + char *tmp = aprintf("257 \"%s\" is current directory.\n", + protop->path); + if(!tmp) { + sshc->actualcode = CURLE_OUT_OF_MEMORY; + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + return; + } + Curl_debug(data, CURLINFO_HEADER_OUT, (char *) "PWD\n", 4); + Curl_debug(data, CURLINFO_HEADER_IN, tmp, strlen(tmp)); + + /* this sends an FTP-like "header" to the header callback so that the + current directory can be read very similar to how it is read when + using ordinary FTP. */ + result = Curl_client_write(data, CLIENTWRITE_HEADER, tmp, strlen(tmp)); + free(tmp); + if(result) { + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + } + else + state(data, SSH_SFTP_NEXT_QUOTE); + return; + } + + /* + * the arguments following the command must be separated from the + * command with a space so we can check for it unconditionally + */ + cp = strchr(cmd, ' '); + if(!cp) { + failf(data, "Syntax error in SFTP command. Supply parameter(s)"); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + return; + } + + /* + * also, every command takes at least one argument so we get that + * first argument right now + */ + result = Curl_get_pathname(&cp, &sshc->quote_path1, sshc->homedir); + if(result) { + if(result == CURLE_OUT_OF_MEMORY) + failf(data, "Out of memory"); + else + failf(data, "Syntax error: Bad first parameter"); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + return; + } + + /* + * SFTP is a binary protocol, so we don't send text commands + * to the server. Instead, we scan for commands used by + * OpenSSH's sftp program and call the appropriate libssh + * functions. + */ + if(strncasecompare(cmd, "chgrp ", 6) || + strncasecompare(cmd, "chmod ", 6) || + strncasecompare(cmd, "chown ", 6) || + strncasecompare(cmd, "atime ", 6) || + strncasecompare(cmd, "mtime ", 6)) { + /* attribute change */ + + /* sshc->quote_path1 contains the mode to set */ + /* get the destination */ + result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); + if(result) { + if(result == CURLE_OUT_OF_MEMORY) + failf(data, "Out of memory"); + else + failf(data, "Syntax error in chgrp/chmod/chown/atime/mtime: " + "Bad second parameter"); + Curl_safefree(sshc->quote_path1); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + return; + } + sshc->quote_attrs = NULL; + state(data, SSH_SFTP_QUOTE_STAT); + return; + } + if(strncasecompare(cmd, "ln ", 3) || + strncasecompare(cmd, "symlink ", 8)) { + /* symbolic linking */ + /* sshc->quote_path1 is the source */ + /* get the destination */ + result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); + if(result) { + if(result == CURLE_OUT_OF_MEMORY) + failf(data, "Out of memory"); + else + failf(data, "Syntax error in ln/symlink: Bad second parameter"); + Curl_safefree(sshc->quote_path1); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + return; + } + state(data, SSH_SFTP_QUOTE_SYMLINK); + return; + } + else if(strncasecompare(cmd, "mkdir ", 6)) { + /* create dir */ + state(data, SSH_SFTP_QUOTE_MKDIR); + return; + } + else if(strncasecompare(cmd, "rename ", 7)) { + /* rename file */ + /* first param is the source path */ + /* second param is the dest. path */ + result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); + if(result) { + if(result == CURLE_OUT_OF_MEMORY) + failf(data, "Out of memory"); + else + failf(data, "Syntax error in rename: Bad second parameter"); + Curl_safefree(sshc->quote_path1); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + return; + } + state(data, SSH_SFTP_QUOTE_RENAME); + return; + } + else if(strncasecompare(cmd, "rmdir ", 6)) { + /* delete dir */ + state(data, SSH_SFTP_QUOTE_RMDIR); + return; + } + else if(strncasecompare(cmd, "rm ", 3)) { + state(data, SSH_SFTP_QUOTE_UNLINK); + return; + } +#ifdef HAS_STATVFS_SUPPORT + else if(strncasecompare(cmd, "statvfs ", 8)) { + state(data, SSH_SFTP_QUOTE_STATVFS); + return; + } +#endif + + failf(data, "Unknown SFTP command"); + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; +} + +static void sftp_quote_stat(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + char *cmd = sshc->quote_item->data; + sshc->acceptfail = FALSE; + + /* if a command starts with an asterisk, which a legal SFTP command never + can, the command will be allowed to fail without it causing any + aborts or cancels etc. It will cause libcurl to act as if the command + is successful, whatever the server responds. */ + + if(cmd[0] == '*') { + cmd++; + sshc->acceptfail = TRUE; + } + + /* We read the file attributes, store them in sshc->quote_attrs + * and modify them accordingly to command. Then we switch to + * QUOTE_SETSTAT state to write new ones. + */ + + if(sshc->quote_attrs) + sftp_attributes_free(sshc->quote_attrs); + sshc->quote_attrs = sftp_stat(sshc->sftp_session, sshc->quote_path2); + if(!sshc->quote_attrs) { + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + failf(data, "Attempt to get SFTP stats failed: %d", + sftp_get_error(sshc->sftp_session)); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + return; + } + + /* Now set the new attributes... */ + if(strncasecompare(cmd, "chgrp", 5)) { + sshc->quote_attrs->gid = (uint32_t)strtoul(sshc->quote_path1, NULL, 10); + if(sshc->quote_attrs->gid == 0 && !ISDIGIT(sshc->quote_path1[0]) && + !sshc->acceptfail) { + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + failf(data, "Syntax error: chgrp gid not a number"); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + return; + } + sshc->quote_attrs->flags |= SSH_FILEXFER_ATTR_UIDGID; + } + else if(strncasecompare(cmd, "chmod", 5)) { + mode_t perms; + perms = (mode_t)strtoul(sshc->quote_path1, NULL, 8); + /* permissions are octal */ + if(perms == 0 && !ISDIGIT(sshc->quote_path1[0])) { + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + failf(data, "Syntax error: chmod permissions not a number"); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + return; + } + sshc->quote_attrs->permissions = perms; + sshc->quote_attrs->flags |= SSH_FILEXFER_ATTR_PERMISSIONS; + } + else if(strncasecompare(cmd, "chown", 5)) { + sshc->quote_attrs->uid = (uint32_t)strtoul(sshc->quote_path1, NULL, 10); + if(sshc->quote_attrs->uid == 0 && !ISDIGIT(sshc->quote_path1[0]) && + !sshc->acceptfail) { + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + failf(data, "Syntax error: chown uid not a number"); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + return; + } + sshc->quote_attrs->flags |= SSH_FILEXFER_ATTR_UIDGID; + } + else if(strncasecompare(cmd, "atime", 5) || + strncasecompare(cmd, "mtime", 5)) { + time_t date = Curl_getdate_capped(sshc->quote_path1); + bool fail = FALSE; + if(date == -1) { + failf(data, "incorrect date format for %.*s", 5, cmd); + fail = TRUE; + } +#if SIZEOF_TIME_T > 4 + else if(date > 0xffffffff) { + failf(data, "date overflow"); + fail = TRUE; /* avoid setting a capped time */ + } +#endif + if(fail) { + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + return; + } + if(strncasecompare(cmd, "atime", 5)) + sshc->quote_attrs->atime = (uint32_t)date; + else /* mtime */ + sshc->quote_attrs->mtime = (uint32_t)date; + + sshc->quote_attrs->flags |= SSH_FILEXFER_ATTR_ACMODTIME; + } + + /* Now send the completed structure... */ + state(data, SSH_SFTP_QUOTE_SETSTAT); + return; +} + +CURLcode Curl_ssh_init(void) +{ + if(ssh_init()) { + DEBUGF(fprintf(stderr, "Error: libssh_init failed\n")); + return CURLE_FAILED_INIT; + } + return CURLE_OK; +} + +void Curl_ssh_cleanup(void) +{ + (void)ssh_finalize(); +} + +void Curl_ssh_version(char *buffer, size_t buflen) +{ + (void)msnprintf(buffer, buflen, "libssh/%s", ssh_version(0)); +} + +#endif /* USE_LIBSSH */ diff --git a/third_party/curl/lib/vssh/libssh2.c b/third_party/curl/lib/vssh/libssh2.c new file mode 100644 index 0000000..abdf42e --- /dev/null +++ b/third_party/curl/lib/vssh/libssh2.c @@ -0,0 +1,3836 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* #define CURL_LIBSSH2_DEBUG */ + +#include "curl_setup.h" + +#ifdef USE_LIBSSH2 + +#include + +#include +#include + +#ifdef HAVE_FCNTL_H +#include +#endif + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef __VMS +#include +#include +#endif + +#include +#include "urldata.h" +#include "sendf.h" +#include "hostip.h" +#include "progress.h" +#include "transfer.h" +#include "escape.h" +#include "http.h" /* for HTTP proxy tunnel stuff */ +#include "ssh.h" +#include "url.h" +#include "speedcheck.h" +#include "getinfo.h" +#include "strdup.h" +#include "strcase.h" +#include "vtls/vtls.h" +#include "cfilters.h" +#include "connect.h" +#include "inet_ntop.h" +#include "parsedate.h" /* for the week day and month names */ +#include "sockaddr.h" /* required for Curl_sockaddr_storage */ +#include "strtoofft.h" +#include "multiif.h" +#include "select.h" +#include "warnless.h" +#include "curl_path.h" + +#include /* for base64 encoding/decoding */ +#include + + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if LIBSSH2_VERSION_NUM >= 0x010206 +/* libssh2_sftp_statvfs and friends were added in 1.2.6 */ +#define HAS_STATVFS_SUPPORT 1 +#endif + +#define sftp_libssh2_realpath(s,p,t,m) \ + libssh2_sftp_symlink_ex((s), (p), curlx_uztoui(strlen(p)), \ + (t), (m), LIBSSH2_SFTP_REALPATH) + +/* Local functions: */ +static const char *sftp_libssh2_strerror(unsigned long err); +static LIBSSH2_ALLOC_FUNC(my_libssh2_malloc); +static LIBSSH2_REALLOC_FUNC(my_libssh2_realloc); +static LIBSSH2_FREE_FUNC(my_libssh2_free); +static CURLcode ssh_force_knownhost_key_type(struct Curl_easy *data); +static CURLcode ssh_connect(struct Curl_easy *data, bool *done); +static CURLcode ssh_multi_statemach(struct Curl_easy *data, bool *done); +static CURLcode ssh_do(struct Curl_easy *data, bool *done); +static CURLcode scp_done(struct Curl_easy *data, CURLcode c, bool premature); +static CURLcode scp_doing(struct Curl_easy *data, bool *dophase_done); +static CURLcode scp_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead_connection); +static CURLcode sftp_done(struct Curl_easy *data, CURLcode, bool premature); +static CURLcode sftp_doing(struct Curl_easy *data, bool *dophase_done); +static CURLcode sftp_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead); +static CURLcode sftp_perform(struct Curl_easy *data, bool *connected, + bool *dophase_done); +static int ssh_getsock(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t *sock); +static CURLcode ssh_setup_connection(struct Curl_easy *data, + struct connectdata *conn); +static void ssh_attach(struct Curl_easy *data, struct connectdata *conn); + +/* + * SCP protocol handler. + */ + +const struct Curl_handler Curl_handler_scp = { + "SCP", /* scheme */ + ssh_setup_connection, /* setup_connection */ + ssh_do, /* do_it */ + scp_done, /* done */ + ZERO_NULL, /* do_more */ + ssh_connect, /* connect_it */ + ssh_multi_statemach, /* connecting */ + scp_doing, /* doing */ + ssh_getsock, /* proto_getsock */ + ssh_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ssh_getsock, /* perform_getsock */ + scp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ssh_attach, /* attach */ + PORT_SSH, /* defport */ + CURLPROTO_SCP, /* protocol */ + CURLPROTO_SCP, /* family */ + PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION + | PROTOPT_NOURLQUERY /* flags */ +}; + + +/* + * SFTP protocol handler. + */ + +const struct Curl_handler Curl_handler_sftp = { + "SFTP", /* scheme */ + ssh_setup_connection, /* setup_connection */ + ssh_do, /* do_it */ + sftp_done, /* done */ + ZERO_NULL, /* do_more */ + ssh_connect, /* connect_it */ + ssh_multi_statemach, /* connecting */ + sftp_doing, /* doing */ + ssh_getsock, /* proto_getsock */ + ssh_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ssh_getsock, /* perform_getsock */ + sftp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ssh_attach, /* attach */ + PORT_SSH, /* defport */ + CURLPROTO_SFTP, /* protocol */ + CURLPROTO_SFTP, /* family */ + PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION + | PROTOPT_NOURLQUERY /* flags */ +}; + +static void +kbd_callback(const char *name, int name_len, const char *instruction, + int instruction_len, int num_prompts, + const LIBSSH2_USERAUTH_KBDINT_PROMPT *prompts, + LIBSSH2_USERAUTH_KBDINT_RESPONSE *responses, + void **abstract) +{ + struct Curl_easy *data = (struct Curl_easy *)*abstract; + +#ifdef CURL_LIBSSH2_DEBUG + fprintf(stderr, "name=%s\n", name); + fprintf(stderr, "name_len=%d\n", name_len); + fprintf(stderr, "instruction=%s\n", instruction); + fprintf(stderr, "instruction_len=%d\n", instruction_len); + fprintf(stderr, "num_prompts=%d\n", num_prompts); +#else + (void)name; + (void)name_len; + (void)instruction; + (void)instruction_len; +#endif /* CURL_LIBSSH2_DEBUG */ + if(num_prompts == 1) { + struct connectdata *conn = data->conn; + responses[0].text = strdup(conn->passwd); + responses[0].length = + responses[0].text == NULL ? 0 : curlx_uztoui(strlen(conn->passwd)); + } + (void)prompts; +} /* kbd_callback */ + +static CURLcode sftp_libssh2_error_to_CURLE(unsigned long err) +{ + switch(err) { + case LIBSSH2_FX_OK: + return CURLE_OK; + + case LIBSSH2_FX_NO_SUCH_FILE: + case LIBSSH2_FX_NO_SUCH_PATH: + return CURLE_REMOTE_FILE_NOT_FOUND; + + case LIBSSH2_FX_PERMISSION_DENIED: + case LIBSSH2_FX_WRITE_PROTECT: + case LIBSSH2_FX_LOCK_CONFlICT: + return CURLE_REMOTE_ACCESS_DENIED; + + case LIBSSH2_FX_NO_SPACE_ON_FILESYSTEM: + case LIBSSH2_FX_QUOTA_EXCEEDED: + return CURLE_REMOTE_DISK_FULL; + + case LIBSSH2_FX_FILE_ALREADY_EXISTS: + return CURLE_REMOTE_FILE_EXISTS; + + case LIBSSH2_FX_DIR_NOT_EMPTY: + return CURLE_QUOTE_ERROR; + + default: + break; + } + + return CURLE_SSH; +} + +static CURLcode libssh2_session_error_to_CURLE(int err) +{ + switch(err) { + /* Ordered by order of appearance in libssh2.h */ + case LIBSSH2_ERROR_NONE: + return CURLE_OK; + + /* This is the error returned by libssh2_scp_recv2 + * on unknown file */ + case LIBSSH2_ERROR_SCP_PROTOCOL: + return CURLE_REMOTE_FILE_NOT_FOUND; + + case LIBSSH2_ERROR_SOCKET_NONE: + return CURLE_COULDNT_CONNECT; + + case LIBSSH2_ERROR_ALLOC: + return CURLE_OUT_OF_MEMORY; + + case LIBSSH2_ERROR_SOCKET_SEND: + return CURLE_SEND_ERROR; + + case LIBSSH2_ERROR_HOSTKEY_INIT: + case LIBSSH2_ERROR_HOSTKEY_SIGN: + case LIBSSH2_ERROR_PUBLICKEY_UNRECOGNIZED: + case LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED: + return CURLE_PEER_FAILED_VERIFICATION; + + case LIBSSH2_ERROR_PASSWORD_EXPIRED: + return CURLE_LOGIN_DENIED; + + case LIBSSH2_ERROR_SOCKET_TIMEOUT: + case LIBSSH2_ERROR_TIMEOUT: + return CURLE_OPERATION_TIMEDOUT; + + case LIBSSH2_ERROR_EAGAIN: + return CURLE_AGAIN; + } + + return CURLE_SSH; +} + +static LIBSSH2_ALLOC_FUNC(my_libssh2_malloc) +{ + (void)abstract; /* arg not used */ + return malloc(count); +} + +static LIBSSH2_REALLOC_FUNC(my_libssh2_realloc) +{ + (void)abstract; /* arg not used */ + return realloc(ptr, count); +} + +static LIBSSH2_FREE_FUNC(my_libssh2_free) +{ + (void)abstract; /* arg not used */ + if(ptr) /* ssh2 agent sometimes call free with null ptr */ + free(ptr); +} + +/* + * SSH State machine related code + */ +/* This is the ONLY way to change SSH state! */ +static void state(struct Curl_easy *data, sshstate nowstate) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + /* for debug purposes */ + static const char * const names[] = { + "SSH_STOP", + "SSH_INIT", + "SSH_S_STARTUP", + "SSH_HOSTKEY", + "SSH_AUTHLIST", + "SSH_AUTH_PKEY_INIT", + "SSH_AUTH_PKEY", + "SSH_AUTH_PASS_INIT", + "SSH_AUTH_PASS", + "SSH_AUTH_AGENT_INIT", + "SSH_AUTH_AGENT_LIST", + "SSH_AUTH_AGENT", + "SSH_AUTH_HOST_INIT", + "SSH_AUTH_HOST", + "SSH_AUTH_KEY_INIT", + "SSH_AUTH_KEY", + "SSH_AUTH_GSSAPI", + "SSH_AUTH_DONE", + "SSH_SFTP_INIT", + "SSH_SFTP_REALPATH", + "SSH_SFTP_QUOTE_INIT", + "SSH_SFTP_POSTQUOTE_INIT", + "SSH_SFTP_QUOTE", + "SSH_SFTP_NEXT_QUOTE", + "SSH_SFTP_QUOTE_STAT", + "SSH_SFTP_QUOTE_SETSTAT", + "SSH_SFTP_QUOTE_SYMLINK", + "SSH_SFTP_QUOTE_MKDIR", + "SSH_SFTP_QUOTE_RENAME", + "SSH_SFTP_QUOTE_RMDIR", + "SSH_SFTP_QUOTE_UNLINK", + "SSH_SFTP_QUOTE_STATVFS", + "SSH_SFTP_GETINFO", + "SSH_SFTP_FILETIME", + "SSH_SFTP_TRANS_INIT", + "SSH_SFTP_UPLOAD_INIT", + "SSH_SFTP_CREATE_DIRS_INIT", + "SSH_SFTP_CREATE_DIRS", + "SSH_SFTP_CREATE_DIRS_MKDIR", + "SSH_SFTP_READDIR_INIT", + "SSH_SFTP_READDIR", + "SSH_SFTP_READDIR_LINK", + "SSH_SFTP_READDIR_BOTTOM", + "SSH_SFTP_READDIR_DONE", + "SSH_SFTP_DOWNLOAD_INIT", + "SSH_SFTP_DOWNLOAD_STAT", + "SSH_SFTP_CLOSE", + "SSH_SFTP_SHUTDOWN", + "SSH_SCP_TRANS_INIT", + "SSH_SCP_UPLOAD_INIT", + "SSH_SCP_DOWNLOAD_INIT", + "SSH_SCP_DOWNLOAD", + "SSH_SCP_DONE", + "SSH_SCP_SEND_EOF", + "SSH_SCP_WAIT_EOF", + "SSH_SCP_WAIT_CLOSE", + "SSH_SCP_CHANNEL_FREE", + "SSH_SESSION_DISCONNECT", + "SSH_SESSION_FREE", + "QUIT" + }; + + /* a precaution to make sure the lists are in sync */ + DEBUGASSERT(sizeof(names)/sizeof(names[0]) == SSH_LAST); + + if(sshc->state != nowstate) { + infof(data, "SFTP %p state change from %s to %s", + (void *)sshc, names[sshc->state], names[nowstate]); + } +#endif + + sshc->state = nowstate; +} + + +#ifdef HAVE_LIBSSH2_KNOWNHOST_API +static int sshkeycallback(struct Curl_easy *easy, + const struct curl_khkey *knownkey, /* known */ + const struct curl_khkey *foundkey, /* found */ + enum curl_khmatch match, + void *clientp) +{ + (void)easy; + (void)knownkey; + (void)foundkey; + (void)clientp; + + /* we only allow perfect matches, and we reject everything else */ + return (match != CURLKHMATCH_OK)?CURLKHSTAT_REJECT:CURLKHSTAT_FINE; +} +#endif + +/* + * Earlier libssh2 versions didn't have the ability to seek to 64bit positions + * with 32bit size_t. + */ +#ifdef HAVE_LIBSSH2_SFTP_SEEK64 +#define SFTP_SEEK(x,y) libssh2_sftp_seek64(x, (libssh2_uint64_t)y) +#else +#define SFTP_SEEK(x,y) libssh2_sftp_seek(x, (size_t)y) +#endif + +/* + * Earlier libssh2 versions didn't do SCP properly beyond 32bit sizes on 32bit + * architectures so we check of the necessary function is present. + */ +#ifndef HAVE_LIBSSH2_SCP_SEND64 +#define SCP_SEND(a,b,c,d) libssh2_scp_send_ex(a, b, (int)(c), (size_t)d, 0, 0) +#else +#define SCP_SEND(a,b,c,d) libssh2_scp_send64(a, b, (int)(c), \ + (libssh2_uint64_t)d, 0, 0) +#endif + +/* + * libssh2 1.2.8 fixed the problem with 32bit ints used for sockets on win64. + */ +#ifdef HAVE_LIBSSH2_SESSION_HANDSHAKE +#define session_startup(x,y) libssh2_session_handshake(x, y) +#else +#define session_startup(x,y) libssh2_session_startup(x, (int)y) +#endif +static int convert_ssh2_keytype(int sshkeytype) +{ + int keytype = CURLKHTYPE_UNKNOWN; + switch(sshkeytype) { + case LIBSSH2_HOSTKEY_TYPE_RSA: + keytype = CURLKHTYPE_RSA; + break; + case LIBSSH2_HOSTKEY_TYPE_DSS: + keytype = CURLKHTYPE_DSS; + break; +#ifdef LIBSSH2_HOSTKEY_TYPE_ECDSA_256 + case LIBSSH2_HOSTKEY_TYPE_ECDSA_256: + keytype = CURLKHTYPE_ECDSA; + break; +#endif +#ifdef LIBSSH2_HOSTKEY_TYPE_ECDSA_384 + case LIBSSH2_HOSTKEY_TYPE_ECDSA_384: + keytype = CURLKHTYPE_ECDSA; + break; +#endif +#ifdef LIBSSH2_HOSTKEY_TYPE_ECDSA_521 + case LIBSSH2_HOSTKEY_TYPE_ECDSA_521: + keytype = CURLKHTYPE_ECDSA; + break; +#endif +#ifdef LIBSSH2_HOSTKEY_TYPE_ED25519 + case LIBSSH2_HOSTKEY_TYPE_ED25519: + keytype = CURLKHTYPE_ED25519; + break; +#endif + } + return keytype; +} + +static CURLcode ssh_knownhost(struct Curl_easy *data) +{ + int sshkeytype = 0; + size_t keylen = 0; + int rc = 0; + CURLcode result = CURLE_OK; + +#ifdef HAVE_LIBSSH2_KNOWNHOST_API + if(data->set.str[STRING_SSH_KNOWNHOSTS]) { + /* we're asked to verify the host against a file */ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + struct libssh2_knownhost *host = NULL; + const char *remotekey = libssh2_session_hostkey(sshc->ssh_session, + &keylen, &sshkeytype); + int keycheck = LIBSSH2_KNOWNHOST_CHECK_FAILURE; + int keybit = 0; + + if(remotekey) { + /* + * A subject to figure out is what host name we need to pass in here. + * What host name does OpenSSH store in its file if an IDN name is + * used? + */ + enum curl_khmatch keymatch; + curl_sshkeycallback func = + data->set.ssh_keyfunc ? data->set.ssh_keyfunc : sshkeycallback; + struct curl_khkey knownkey; + struct curl_khkey *knownkeyp = NULL; + struct curl_khkey foundkey; + + switch(sshkeytype) { + case LIBSSH2_HOSTKEY_TYPE_RSA: + keybit = LIBSSH2_KNOWNHOST_KEY_SSHRSA; + break; + case LIBSSH2_HOSTKEY_TYPE_DSS: + keybit = LIBSSH2_KNOWNHOST_KEY_SSHDSS; + break; +#ifdef LIBSSH2_HOSTKEY_TYPE_ECDSA_256 + case LIBSSH2_HOSTKEY_TYPE_ECDSA_256: + keybit = LIBSSH2_KNOWNHOST_KEY_ECDSA_256; + break; +#endif +#ifdef LIBSSH2_HOSTKEY_TYPE_ECDSA_384 + case LIBSSH2_HOSTKEY_TYPE_ECDSA_384: + keybit = LIBSSH2_KNOWNHOST_KEY_ECDSA_384; + break; +#endif +#ifdef LIBSSH2_HOSTKEY_TYPE_ECDSA_521 + case LIBSSH2_HOSTKEY_TYPE_ECDSA_521: + keybit = LIBSSH2_KNOWNHOST_KEY_ECDSA_521; + break; +#endif +#ifdef LIBSSH2_HOSTKEY_TYPE_ED25519 + case LIBSSH2_HOSTKEY_TYPE_ED25519: + keybit = LIBSSH2_KNOWNHOST_KEY_ED25519; + break; +#endif + default: + infof(data, "unsupported key type, can't check knownhosts"); + keybit = 0; + break; + } + if(!keybit) + /* no check means failure! */ + rc = CURLKHSTAT_REJECT; + else { +#ifdef HAVE_LIBSSH2_KNOWNHOST_CHECKP + keycheck = libssh2_knownhost_checkp(sshc->kh, + conn->host.name, + (conn->remote_port != PORT_SSH)? + conn->remote_port:-1, + remotekey, keylen, + LIBSSH2_KNOWNHOST_TYPE_PLAIN| + LIBSSH2_KNOWNHOST_KEYENC_RAW| + keybit, + &host); +#else + keycheck = libssh2_knownhost_check(sshc->kh, + conn->host.name, + remotekey, keylen, + LIBSSH2_KNOWNHOST_TYPE_PLAIN| + LIBSSH2_KNOWNHOST_KEYENC_RAW| + keybit, + &host); +#endif + + infof(data, "SSH host check: %d, key: %s", keycheck, + (keycheck <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH)? + host->key:""); + + /* setup 'knownkey' */ + if(keycheck <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH) { + knownkey.key = host->key; + knownkey.len = 0; + knownkey.keytype = convert_ssh2_keytype(sshkeytype); + knownkeyp = &knownkey; + } + + /* setup 'foundkey' */ + foundkey.key = remotekey; + foundkey.len = keylen; + foundkey.keytype = convert_ssh2_keytype(sshkeytype); + + /* + * if any of the LIBSSH2_KNOWNHOST_CHECK_* defines and the + * curl_khmatch enum are ever modified, we need to introduce a + * translation table here! + */ + keymatch = (enum curl_khmatch)keycheck; + + /* Ask the callback how to behave */ + Curl_set_in_callback(data, true); + rc = func(data, knownkeyp, /* from the knownhosts file */ + &foundkey, /* from the remote host */ + keymatch, data->set.ssh_keyfunc_userp); + Curl_set_in_callback(data, false); + } + } + else + /* no remotekey means failure! */ + rc = CURLKHSTAT_REJECT; + + switch(rc) { + default: /* unknown return codes will equal reject */ + case CURLKHSTAT_REJECT: + state(data, SSH_SESSION_FREE); + FALLTHROUGH(); + case CURLKHSTAT_DEFER: + /* DEFER means bail out but keep the SSH_HOSTKEY state */ + result = sshc->actualcode = CURLE_PEER_FAILED_VERIFICATION; + break; + case CURLKHSTAT_FINE_REPLACE: + /* remove old host+key that doesn't match */ + if(host) + libssh2_knownhost_del(sshc->kh, host); + FALLTHROUGH(); + case CURLKHSTAT_FINE: + case CURLKHSTAT_FINE_ADD_TO_FILE: + /* proceed */ + if(keycheck != LIBSSH2_KNOWNHOST_CHECK_MATCH) { + /* the found host+key didn't match but has been told to be fine + anyway so we add it in memory */ + int addrc = libssh2_knownhost_add(sshc->kh, + conn->host.name, NULL, + remotekey, keylen, + LIBSSH2_KNOWNHOST_TYPE_PLAIN| + LIBSSH2_KNOWNHOST_KEYENC_RAW| + keybit, NULL); + if(addrc) + infof(data, "WARNING: adding the known host %s failed", + conn->host.name); + else if(rc == CURLKHSTAT_FINE_ADD_TO_FILE || + rc == CURLKHSTAT_FINE_REPLACE) { + /* now we write the entire in-memory list of known hosts to the + known_hosts file */ + int wrc = + libssh2_knownhost_writefile(sshc->kh, + data->set.str[STRING_SSH_KNOWNHOSTS], + LIBSSH2_KNOWNHOST_FILE_OPENSSH); + if(wrc) { + infof(data, "WARNING: writing %s failed", + data->set.str[STRING_SSH_KNOWNHOSTS]); + } + } + } + break; + } + } +#else /* HAVE_LIBSSH2_KNOWNHOST_API */ + (void)data; +#endif + return result; +} + +static CURLcode ssh_check_fingerprint(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + const char *pubkey_md5 = data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5]; + const char *pubkey_sha256 = data->set.str[STRING_SSH_HOST_PUBLIC_KEY_SHA256]; + + infof(data, "SSH MD5 public key: %s", + pubkey_md5 != NULL ? pubkey_md5 : "NULL"); + infof(data, "SSH SHA256 public key: %s", + pubkey_sha256 != NULL ? pubkey_sha256 : "NULL"); + + if(pubkey_sha256) { + const char *fingerprint = NULL; + char *fingerprint_b64 = NULL; + size_t fingerprint_b64_len; + size_t pub_pos = 0; + size_t b64_pos = 0; + +#ifdef LIBSSH2_HOSTKEY_HASH_SHA256 + /* The fingerprint points to static storage (!), don't free() it. */ + fingerprint = libssh2_hostkey_hash(sshc->ssh_session, + LIBSSH2_HOSTKEY_HASH_SHA256); +#else + const char *hostkey; + size_t len = 0; + unsigned char hash[32]; + + hostkey = libssh2_session_hostkey(sshc->ssh_session, &len, NULL); + if(hostkey) { + if(!Curl_sha256it(hash, (const unsigned char *) hostkey, len)) + fingerprint = (char *) hash; + } +#endif + + if(!fingerprint) { + failf(data, + "Denied establishing ssh session: sha256 fingerprint " + "not available"); + state(data, SSH_SESSION_FREE); + sshc->actualcode = CURLE_PEER_FAILED_VERIFICATION; + return sshc->actualcode; + } + + /* The length of fingerprint is 32 bytes for SHA256. + * See libssh2_hostkey_hash documentation. */ + if(Curl_base64_encode(fingerprint, 32, &fingerprint_b64, + &fingerprint_b64_len) != CURLE_OK) { + state(data, SSH_SESSION_FREE); + sshc->actualcode = CURLE_PEER_FAILED_VERIFICATION; + return sshc->actualcode; + } + + if(!fingerprint_b64) { + failf(data, "sha256 fingerprint could not be encoded"); + state(data, SSH_SESSION_FREE); + sshc->actualcode = CURLE_PEER_FAILED_VERIFICATION; + return sshc->actualcode; + } + + infof(data, "SSH SHA256 fingerprint: %s", fingerprint_b64); + + /* Find the position of any = padding characters in the public key */ + while((pubkey_sha256[pub_pos] != '=') && pubkey_sha256[pub_pos]) { + pub_pos++; + } + + /* Find the position of any = padding characters in the base64 coded + * hostkey fingerprint */ + while((fingerprint_b64[b64_pos] != '=') && fingerprint_b64[b64_pos]) { + b64_pos++; + } + + /* Before we authenticate we check the hostkey's sha256 fingerprint + * against a known fingerprint, if available. + */ + if((pub_pos != b64_pos) || + strncmp(fingerprint_b64, pubkey_sha256, pub_pos)) { + failf(data, + "Denied establishing ssh session: mismatch sha256 fingerprint. " + "Remote %s is not equal to %s", fingerprint_b64, pubkey_sha256); + free(fingerprint_b64); + state(data, SSH_SESSION_FREE); + sshc->actualcode = CURLE_PEER_FAILED_VERIFICATION; + return sshc->actualcode; + } + + free(fingerprint_b64); + + infof(data, "SHA256 checksum match"); + } + + if(pubkey_md5) { + char md5buffer[33]; + const char *fingerprint = NULL; + + fingerprint = libssh2_hostkey_hash(sshc->ssh_session, + LIBSSH2_HOSTKEY_HASH_MD5); + + if(fingerprint) { + /* The fingerprint points to static storage (!), don't free() it. */ + int i; + for(i = 0; i < 16; i++) { + msnprintf(&md5buffer[i*2], 3, "%02x", (unsigned char) fingerprint[i]); + } + + infof(data, "SSH MD5 fingerprint: %s", md5buffer); + } + + /* This does NOT verify the length of 'pubkey_md5' separately, which will + make the comparison below fail unless it is exactly 32 characters */ + if(!fingerprint || !strcasecompare(md5buffer, pubkey_md5)) { + if(fingerprint) { + failf(data, + "Denied establishing ssh session: mismatch md5 fingerprint. " + "Remote %s is not equal to %s", md5buffer, pubkey_md5); + } + else { + failf(data, + "Denied establishing ssh session: md5 fingerprint " + "not available"); + } + state(data, SSH_SESSION_FREE); + sshc->actualcode = CURLE_PEER_FAILED_VERIFICATION; + return sshc->actualcode; + } + infof(data, "MD5 checksum match"); + } + + if(!pubkey_md5 && !pubkey_sha256) { + if(data->set.ssh_hostkeyfunc) { + size_t keylen = 0; + int sshkeytype = 0; + int rc = 0; + /* we handle the process to the callback */ + const char *remotekey = libssh2_session_hostkey(sshc->ssh_session, + &keylen, &sshkeytype); + if(remotekey) { + int keytype = convert_ssh2_keytype(sshkeytype); + Curl_set_in_callback(data, true); + rc = data->set.ssh_hostkeyfunc(data->set.ssh_hostkeyfunc_userp, + keytype, remotekey, keylen); + Curl_set_in_callback(data, false); + if(rc!= CURLKHMATCH_OK) { + state(data, SSH_SESSION_FREE); + sshc->actualcode = CURLE_PEER_FAILED_VERIFICATION; + return sshc->actualcode; + } + } + else { + state(data, SSH_SESSION_FREE); + sshc->actualcode = CURLE_PEER_FAILED_VERIFICATION; + return sshc->actualcode; + } + return CURLE_OK; + } + else { + return ssh_knownhost(data); + } + } + else { + /* as we already matched, we skip the check for known hosts */ + return CURLE_OK; + } +} + +/* + * ssh_force_knownhost_key_type() will check the known hosts file and try to + * force a specific public key type from the server if an entry is found. + */ +static CURLcode ssh_force_knownhost_key_type(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + +#ifdef HAVE_LIBSSH2_KNOWNHOST_API + +#ifdef LIBSSH2_KNOWNHOST_KEY_ED25519 + static const char * const hostkey_method_ssh_ed25519 + = "ssh-ed25519"; +#endif +#ifdef LIBSSH2_KNOWNHOST_KEY_ECDSA_521 + static const char * const hostkey_method_ssh_ecdsa_521 + = "ecdsa-sha2-nistp521"; +#endif +#ifdef LIBSSH2_KNOWNHOST_KEY_ECDSA_384 + static const char * const hostkey_method_ssh_ecdsa_384 + = "ecdsa-sha2-nistp384"; +#endif +#ifdef LIBSSH2_KNOWNHOST_KEY_ECDSA_256 + static const char * const hostkey_method_ssh_ecdsa_256 + = "ecdsa-sha2-nistp256"; +#endif + static const char * const hostkey_method_ssh_rsa + = "ssh-rsa"; + static const char * const hostkey_method_ssh_rsa_all + = "rsa-sha2-256,rsa-sha2-512,ssh-rsa"; + static const char * const hostkey_method_ssh_dss + = "ssh-dss"; + + const char *hostkey_method = NULL; + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + struct libssh2_knownhost* store = NULL; + const char *kh_name_end = NULL; + size_t kh_name_size = 0; + int port = 0; + bool found = false; + + if(sshc->kh && !data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5]) { + /* lets try to find our host in the known hosts file */ + while(!libssh2_knownhost_get(sshc->kh, &store, store)) { + /* For non-standard ports, the name will be enclosed in */ + /* square brackets, followed by a colon and the port */ + if(store) { + if(store->name) { + if(store->name[0] == '[') { + kh_name_end = strstr(store->name, "]:"); + if(!kh_name_end) { + infof(data, "Invalid host pattern %s in %s", + store->name, data->set.str[STRING_SSH_KNOWNHOSTS]); + continue; + } + port = atoi(kh_name_end + 2); + if(kh_name_end && (port == conn->remote_port)) { + kh_name_size = strlen(store->name) - 1 - strlen(kh_name_end); + if(strncmp(store->name + 1, + conn->host.name, kh_name_size) == 0) { + found = true; + break; + } + } + } + else if(strcmp(store->name, conn->host.name) == 0) { + found = true; + break; + } + } + else { + found = true; + break; + } + } + } + + if(found) { + int rc; + infof(data, "Found host %s in %s", + conn->host.name, data->set.str[STRING_SSH_KNOWNHOSTS]); + + switch(store->typemask & LIBSSH2_KNOWNHOST_KEY_MASK) { +#ifdef LIBSSH2_KNOWNHOST_KEY_ED25519 + case LIBSSH2_KNOWNHOST_KEY_ED25519: + hostkey_method = hostkey_method_ssh_ed25519; + break; +#endif +#ifdef LIBSSH2_KNOWNHOST_KEY_ECDSA_521 + case LIBSSH2_KNOWNHOST_KEY_ECDSA_521: + hostkey_method = hostkey_method_ssh_ecdsa_521; + break; +#endif +#ifdef LIBSSH2_KNOWNHOST_KEY_ECDSA_384 + case LIBSSH2_KNOWNHOST_KEY_ECDSA_384: + hostkey_method = hostkey_method_ssh_ecdsa_384; + break; +#endif +#ifdef LIBSSH2_KNOWNHOST_KEY_ECDSA_256 + case LIBSSH2_KNOWNHOST_KEY_ECDSA_256: + hostkey_method = hostkey_method_ssh_ecdsa_256; + break; +#endif + case LIBSSH2_KNOWNHOST_KEY_SSHRSA: +#ifdef HAVE_LIBSSH2_VERSION + if(libssh2_version(0x010900)) + /* since 1.9.0 libssh2_session_method_pref() works as expected */ + hostkey_method = hostkey_method_ssh_rsa_all; + else +#endif + /* old libssh2 which cannot correctly remove unsupported methods due + * to bug in src/kex.c or does not support the new methods anyways. + */ + hostkey_method = hostkey_method_ssh_rsa; + break; + case LIBSSH2_KNOWNHOST_KEY_SSHDSS: + hostkey_method = hostkey_method_ssh_dss; + break; + case LIBSSH2_KNOWNHOST_KEY_RSA1: + failf(data, "Found host key type RSA1 which is not supported"); + return CURLE_SSH; + default: + failf(data, "Unknown host key type: %i", + (store->typemask & LIBSSH2_KNOWNHOST_KEY_MASK)); + return CURLE_SSH; + } + + infof(data, "Set \"%s\" as SSH hostkey type", hostkey_method); + rc = libssh2_session_method_pref(sshc->ssh_session, + LIBSSH2_METHOD_HOSTKEY, hostkey_method); + if(rc) { + char *errmsg = NULL; + int errlen; + libssh2_session_last_error(sshc->ssh_session, &errmsg, &errlen, 0); + failf(data, "libssh2: %s", errmsg); + result = libssh2_session_error_to_CURLE(rc); + } + } + else { + infof(data, "Did not find host %s in %s", + conn->host.name, data->set.str[STRING_SSH_KNOWNHOSTS]); + } + } + +#endif /* HAVE_LIBSSH2_KNOWNHOST_API */ + + return result; +} + +/* + * ssh_statemach_act() runs the SSH state machine as far as it can without + * blocking and without reaching the end. The data the pointer 'block' points + * to will be set to TRUE if the libssh2 function returns LIBSSH2_ERROR_EAGAIN + * meaning it wants to be called again when the socket is ready + */ + +static CURLcode ssh_statemach_act(struct Curl_easy *data, bool *block) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct SSHPROTO *sshp = data->req.p.ssh; + struct ssh_conn *sshc = &conn->proto.sshc; + curl_socket_t sock = conn->sock[FIRSTSOCKET]; + int rc = LIBSSH2_ERROR_NONE; + int ssherr; + unsigned long sftperr; + int seekerr = CURL_SEEKFUNC_OK; + size_t readdir_len; + *block = 0; /* we're not blocking by default */ + + do { + switch(sshc->state) { + case SSH_INIT: + sshc->secondCreateDirs = 0; + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_OK; + + /* Set libssh2 to non-blocking, since everything internally is + non-blocking */ + libssh2_session_set_blocking(sshc->ssh_session, 0); + + result = ssh_force_knownhost_key_type(data); + if(result) { + state(data, SSH_SESSION_FREE); + sshc->actualcode = result; + break; + } + + state(data, SSH_S_STARTUP); + FALLTHROUGH(); + + case SSH_S_STARTUP: + rc = session_startup(sshc->ssh_session, sock); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); + failf(data, "Failure establishing ssh session: %d, %s", rc, err_msg); + + state(data, SSH_SESSION_FREE); + sshc->actualcode = CURLE_FAILED_INIT; + break; + } + + state(data, SSH_HOSTKEY); + + FALLTHROUGH(); + case SSH_HOSTKEY: + /* + * Before we authenticate we should check the hostkey's fingerprint + * against our known hosts. How that is handled (reading from file, + * whatever) is up to us. + */ + result = ssh_check_fingerprint(data); + if(!result) + state(data, SSH_AUTHLIST); + /* ssh_check_fingerprint sets state appropriately on error */ + break; + + case SSH_AUTHLIST: + /* + * Figure out authentication methods + * NB: As soon as we have provided a username to an openssh server we + * must never change it later. Thus, always specify the correct username + * here, even though the libssh2 docs kind of indicate that it should be + * possible to get a 'generic' list (not user-specific) of authentication + * methods, presumably with a blank username. That won't work in my + * experience. + * So always specify it here. + */ + sshc->authlist = libssh2_userauth_list(sshc->ssh_session, + conn->user, + curlx_uztoui(strlen(conn->user))); + + if(!sshc->authlist) { + if(libssh2_userauth_authenticated(sshc->ssh_session)) { + sshc->authed = TRUE; + infof(data, "SSH user accepted with no authentication"); + state(data, SSH_AUTH_DONE); + break; + } + ssherr = libssh2_session_last_errno(sshc->ssh_session); + if(ssherr == LIBSSH2_ERROR_EAGAIN) + rc = LIBSSH2_ERROR_EAGAIN; + else { + state(data, SSH_SESSION_FREE); + sshc->actualcode = libssh2_session_error_to_CURLE(ssherr); + } + break; + } + infof(data, "SSH authentication methods available: %s", + sshc->authlist); + + state(data, SSH_AUTH_PKEY_INIT); + break; + + case SSH_AUTH_PKEY_INIT: + /* + * Check the supported auth types in the order I feel is most secure + * with the requested type of authentication + */ + sshc->authed = FALSE; + + if((data->set.ssh_auth_types & CURLSSH_AUTH_PUBLICKEY) && + (strstr(sshc->authlist, "publickey") != NULL)) { + bool out_of_memory = FALSE; + + sshc->rsa_pub = sshc->rsa = NULL; + + if(data->set.str[STRING_SSH_PRIVATE_KEY]) + sshc->rsa = strdup(data->set.str[STRING_SSH_PRIVATE_KEY]); + else { + /* To ponder about: should really the lib be messing about with the + HOME environment variable etc? */ + char *home = curl_getenv("HOME"); + struct_stat sbuf; + + /* If no private key file is specified, try some common paths. */ + if(home) { + /* Try ~/.ssh first. */ + sshc->rsa = aprintf("%s/.ssh/id_rsa", home); + if(!sshc->rsa) + out_of_memory = TRUE; + else if(stat(sshc->rsa, &sbuf)) { + Curl_safefree(sshc->rsa); + sshc->rsa = aprintf("%s/.ssh/id_dsa", home); + if(!sshc->rsa) + out_of_memory = TRUE; + else if(stat(sshc->rsa, &sbuf)) { + Curl_safefree(sshc->rsa); + } + } + free(home); + } + if(!out_of_memory && !sshc->rsa) { + /* Nothing found; try the current dir. */ + sshc->rsa = strdup("id_rsa"); + if(sshc->rsa && stat(sshc->rsa, &sbuf)) { + Curl_safefree(sshc->rsa); + sshc->rsa = strdup("id_dsa"); + if(sshc->rsa && stat(sshc->rsa, &sbuf)) { + Curl_safefree(sshc->rsa); + /* Out of guesses. Set to the empty string to avoid + * surprising info messages. */ + sshc->rsa = strdup(""); + } + } + } + } + + /* + * Unless the user explicitly specifies a public key file, let + * libssh2 extract the public key from the private key file. + * This is done by simply passing sshc->rsa_pub = NULL. + */ + if(data->set.str[STRING_SSH_PUBLIC_KEY] + /* treat empty string the same way as NULL */ + && data->set.str[STRING_SSH_PUBLIC_KEY][0]) { + sshc->rsa_pub = strdup(data->set.str[STRING_SSH_PUBLIC_KEY]); + if(!sshc->rsa_pub) + out_of_memory = TRUE; + } + + if(out_of_memory || !sshc->rsa) { + Curl_safefree(sshc->rsa); + Curl_safefree(sshc->rsa_pub); + state(data, SSH_SESSION_FREE); + sshc->actualcode = CURLE_OUT_OF_MEMORY; + break; + } + + sshc->passphrase = data->set.ssl.key_passwd; + if(!sshc->passphrase) + sshc->passphrase = ""; + + if(sshc->rsa_pub) + infof(data, "Using SSH public key file '%s'", sshc->rsa_pub); + infof(data, "Using SSH private key file '%s'", sshc->rsa); + + state(data, SSH_AUTH_PKEY); + } + else { + state(data, SSH_AUTH_PASS_INIT); + } + break; + + case SSH_AUTH_PKEY: + /* The function below checks if the files exists, no need to stat() here. + */ + rc = libssh2_userauth_publickey_fromfile_ex(sshc->ssh_session, + conn->user, + curlx_uztoui( + strlen(conn->user)), + sshc->rsa_pub, + sshc->rsa, sshc->passphrase); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + + Curl_safefree(sshc->rsa_pub); + Curl_safefree(sshc->rsa); + + if(rc == 0) { + sshc->authed = TRUE; + infof(data, "Initialized SSH public key authentication"); + state(data, SSH_AUTH_DONE); + } + else { + char *err_msg = NULL; + char unknown[] = "Reason unknown (-1)"; + if(rc == -1) { + /* No error message has been set and the last set error message, if + any, is from a previous error so ignore it. #11837 */ + err_msg = unknown; + } + else { + (void)libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0); + } + infof(data, "SSH public key authentication failed: %s", err_msg); + state(data, SSH_AUTH_PASS_INIT); + rc = 0; /* clear rc and continue */ + } + break; + + case SSH_AUTH_PASS_INIT: + if((data->set.ssh_auth_types & CURLSSH_AUTH_PASSWORD) && + (strstr(sshc->authlist, "password") != NULL)) { + state(data, SSH_AUTH_PASS); + } + else { + state(data, SSH_AUTH_HOST_INIT); + rc = 0; /* clear rc and continue */ + } + break; + + case SSH_AUTH_PASS: + rc = libssh2_userauth_password_ex(sshc->ssh_session, conn->user, + curlx_uztoui(strlen(conn->user)), + conn->passwd, + curlx_uztoui(strlen(conn->passwd)), + NULL); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc == 0) { + sshc->authed = TRUE; + infof(data, "Initialized password authentication"); + state(data, SSH_AUTH_DONE); + } + else { + state(data, SSH_AUTH_HOST_INIT); + rc = 0; /* clear rc and continue */ + } + break; + + case SSH_AUTH_HOST_INIT: + if((data->set.ssh_auth_types & CURLSSH_AUTH_HOST) && + (strstr(sshc->authlist, "hostbased") != NULL)) { + state(data, SSH_AUTH_HOST); + } + else { + state(data, SSH_AUTH_AGENT_INIT); + } + break; + + case SSH_AUTH_HOST: + state(data, SSH_AUTH_AGENT_INIT); + break; + + case SSH_AUTH_AGENT_INIT: +#ifdef HAVE_LIBSSH2_AGENT_API + if((data->set.ssh_auth_types & CURLSSH_AUTH_AGENT) + && (strstr(sshc->authlist, "publickey") != NULL)) { + + /* Connect to the ssh-agent */ + /* The agent could be shared by a curl thread i believe + but nothing obvious as keys can be added/removed at any time */ + if(!sshc->ssh_agent) { + sshc->ssh_agent = libssh2_agent_init(sshc->ssh_session); + if(!sshc->ssh_agent) { + infof(data, "Could not create agent object"); + + state(data, SSH_AUTH_KEY_INIT); + break; + } + } + + rc = libssh2_agent_connect(sshc->ssh_agent); + if(rc == LIBSSH2_ERROR_EAGAIN) + break; + if(rc < 0) { + infof(data, "Failure connecting to agent"); + state(data, SSH_AUTH_KEY_INIT); + rc = 0; /* clear rc and continue */ + } + else { + state(data, SSH_AUTH_AGENT_LIST); + } + } + else +#endif /* HAVE_LIBSSH2_AGENT_API */ + state(data, SSH_AUTH_KEY_INIT); + break; + + case SSH_AUTH_AGENT_LIST: +#ifdef HAVE_LIBSSH2_AGENT_API + rc = libssh2_agent_list_identities(sshc->ssh_agent); + + if(rc == LIBSSH2_ERROR_EAGAIN) + break; + if(rc < 0) { + infof(data, "Failure requesting identities to agent"); + state(data, SSH_AUTH_KEY_INIT); + rc = 0; /* clear rc and continue */ + } + else { + state(data, SSH_AUTH_AGENT); + sshc->sshagent_prev_identity = NULL; + } +#endif + break; + + case SSH_AUTH_AGENT: +#ifdef HAVE_LIBSSH2_AGENT_API + /* as prev_identity evolves only after an identity user auth finished we + can safely request it again as long as EAGAIN is returned here or by + libssh2_agent_userauth */ + rc = libssh2_agent_get_identity(sshc->ssh_agent, + &sshc->sshagent_identity, + sshc->sshagent_prev_identity); + if(rc == LIBSSH2_ERROR_EAGAIN) + break; + + if(rc == 0) { + rc = libssh2_agent_userauth(sshc->ssh_agent, conn->user, + sshc->sshagent_identity); + + if(rc < 0) { + if(rc != LIBSSH2_ERROR_EAGAIN) { + /* tried and failed? go to next identity */ + sshc->sshagent_prev_identity = sshc->sshagent_identity; + } + break; + } + } + + if(rc < 0) + infof(data, "Failure requesting identities to agent"); + else if(rc == 1) + infof(data, "No identity would match"); + + if(rc == LIBSSH2_ERROR_NONE) { + sshc->authed = TRUE; + infof(data, "Agent based authentication successful"); + state(data, SSH_AUTH_DONE); + } + else { + state(data, SSH_AUTH_KEY_INIT); + rc = 0; /* clear rc and continue */ + } +#endif + break; + + case SSH_AUTH_KEY_INIT: + if((data->set.ssh_auth_types & CURLSSH_AUTH_KEYBOARD) + && (strstr(sshc->authlist, "keyboard-interactive") != NULL)) { + state(data, SSH_AUTH_KEY); + } + else { + state(data, SSH_AUTH_DONE); + } + break; + + case SSH_AUTH_KEY: + /* Authentication failed. Continue with keyboard-interactive now. */ + rc = libssh2_userauth_keyboard_interactive_ex(sshc->ssh_session, + conn->user, + curlx_uztoui( + strlen(conn->user)), + &kbd_callback); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc == 0) { + sshc->authed = TRUE; + infof(data, "Initialized keyboard interactive authentication"); + } + state(data, SSH_AUTH_DONE); + break; + + case SSH_AUTH_DONE: + if(!sshc->authed) { + failf(data, "Authentication failure"); + state(data, SSH_SESSION_FREE); + sshc->actualcode = CURLE_LOGIN_DENIED; + break; + } + + /* + * At this point we have an authenticated ssh session. + */ + infof(data, "Authentication complete"); + + Curl_pgrsTime(data, TIMER_APPCONNECT); /* SSH is connected */ + + conn->sockfd = sock; + conn->writesockfd = CURL_SOCKET_BAD; + + if(conn->handler->protocol == CURLPROTO_SFTP) { + state(data, SSH_SFTP_INIT); + break; + } + infof(data, "SSH CONNECT phase done"); + state(data, SSH_STOP); + break; + + case SSH_SFTP_INIT: + /* + * Start the libssh2 sftp session + */ + sshc->sftp_session = libssh2_sftp_init(sshc->ssh_session); + if(!sshc->sftp_session) { + char *err_msg = NULL; + if(libssh2_session_last_errno(sshc->ssh_session) == + LIBSSH2_ERROR_EAGAIN) { + rc = LIBSSH2_ERROR_EAGAIN; + break; + } + + (void)libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0); + failf(data, "Failure initializing sftp session: %s", err_msg); + state(data, SSH_SESSION_FREE); + sshc->actualcode = CURLE_FAILED_INIT; + break; + } + state(data, SSH_SFTP_REALPATH); + break; + + case SSH_SFTP_REALPATH: + { + char tempHome[PATH_MAX]; + + /* + * Get the "home" directory + */ + rc = sftp_libssh2_realpath(sshc->sftp_session, ".", + tempHome, PATH_MAX-1); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc > 0) { + /* It seems that this string is not always NULL terminated */ + tempHome[rc] = '\0'; + sshc->homedir = strdup(tempHome); + if(!sshc->homedir) { + state(data, SSH_SFTP_CLOSE); + sshc->actualcode = CURLE_OUT_OF_MEMORY; + break; + } + data->state.most_recent_ftp_entrypath = sshc->homedir; + } + else { + /* Return the error type */ + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + if(sftperr) + result = sftp_libssh2_error_to_CURLE(sftperr); + else + /* in this case, the error wasn't in the SFTP level but for example + a time-out or similar */ + result = CURLE_SSH; + sshc->actualcode = result; + DEBUGF(infof(data, "error = %lu makes libcurl = %d", + sftperr, (int)result)); + state(data, SSH_STOP); + break; + } + } + /* This is the last step in the SFTP connect phase. Do note that while + we get the homedir here, we get the "workingpath" in the DO action + since the homedir will remain the same between request but the + working path will not. */ + DEBUGF(infof(data, "SSH CONNECT phase done")); + state(data, SSH_STOP); + break; + + case SSH_SFTP_QUOTE_INIT: + + result = Curl_getworkingpath(data, sshc->homedir, &sshp->path); + if(result) { + sshc->actualcode = result; + state(data, SSH_STOP); + break; + } + + if(data->set.quote) { + infof(data, "Sending quote commands"); + sshc->quote_item = data->set.quote; + state(data, SSH_SFTP_QUOTE); + } + else { + state(data, SSH_SFTP_GETINFO); + } + break; + + case SSH_SFTP_POSTQUOTE_INIT: + if(data->set.postquote) { + infof(data, "Sending quote commands"); + sshc->quote_item = data->set.postquote; + state(data, SSH_SFTP_QUOTE); + } + else { + state(data, SSH_STOP); + } + break; + + case SSH_SFTP_QUOTE: + /* Send any quote commands */ + { + const char *cp; + + /* + * Support some of the "FTP" commands + * + * 'sshc->quote_item' is already verified to be non-NULL before it + * switched to this state. + */ + char *cmd = sshc->quote_item->data; + sshc->acceptfail = FALSE; + + /* if a command starts with an asterisk, which a legal SFTP command never + can, the command will be allowed to fail without it causing any + aborts or cancels etc. It will cause libcurl to act as if the command + is successful, whatever the server responds. */ + + if(cmd[0] == '*') { + cmd++; + sshc->acceptfail = TRUE; + } + + if(strcasecompare("pwd", cmd)) { + /* output debug output if that is requested */ + char *tmp = aprintf("257 \"%s\" is current directory.\n", + sshp->path); + if(!tmp) { + result = CURLE_OUT_OF_MEMORY; + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + break; + } + Curl_debug(data, CURLINFO_HEADER_OUT, (char *)"PWD\n", 4); + Curl_debug(data, CURLINFO_HEADER_IN, tmp, strlen(tmp)); + + /* this sends an FTP-like "header" to the header callback so that the + current directory can be read very similar to how it is read when + using ordinary FTP. */ + result = Curl_client_write(data, CLIENTWRITE_HEADER, tmp, strlen(tmp)); + free(tmp); + if(result) { + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + } + else + state(data, SSH_SFTP_NEXT_QUOTE); + break; + } + + /* + * the arguments following the command must be separated from the + * command with a space so we can check for it unconditionally + */ + cp = strchr(cmd, ' '); + if(!cp) { + failf(data, "Syntax error command '%s', missing parameter", + cmd); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + + /* + * also, every command takes at least one argument so we get that + * first argument right now + */ + result = Curl_get_pathname(&cp, &sshc->quote_path1, sshc->homedir); + if(result) { + if(result == CURLE_OUT_OF_MEMORY) + failf(data, "Out of memory"); + else + failf(data, "Syntax error: Bad first parameter to '%s'", cmd); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + break; + } + + /* + * SFTP is a binary protocol, so we don't send text commands + * to the server. Instead, we scan for commands used by + * OpenSSH's sftp program and call the appropriate libssh2 + * functions. + */ + if(strncasecompare(cmd, "chgrp ", 6) || + strncasecompare(cmd, "chmod ", 6) || + strncasecompare(cmd, "chown ", 6) || + strncasecompare(cmd, "atime ", 6) || + strncasecompare(cmd, "mtime ", 6)) { + /* attribute change */ + + /* sshc->quote_path1 contains the mode to set */ + /* get the destination */ + result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); + if(result) { + if(result == CURLE_OUT_OF_MEMORY) + failf(data, "Out of memory"); + else + failf(data, "Syntax error in %s: Bad second parameter", cmd); + Curl_safefree(sshc->quote_path1); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + break; + } + memset(&sshp->quote_attrs, 0, sizeof(LIBSSH2_SFTP_ATTRIBUTES)); + state(data, SSH_SFTP_QUOTE_STAT); + break; + } + if(strncasecompare(cmd, "ln ", 3) || + strncasecompare(cmd, "symlink ", 8)) { + /* symbolic linking */ + /* sshc->quote_path1 is the source */ + /* get the destination */ + result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); + if(result) { + if(result == CURLE_OUT_OF_MEMORY) + failf(data, "Out of memory"); + else + failf(data, + "Syntax error in ln/symlink: Bad second parameter"); + Curl_safefree(sshc->quote_path1); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + break; + } + state(data, SSH_SFTP_QUOTE_SYMLINK); + break; + } + else if(strncasecompare(cmd, "mkdir ", 6)) { + /* create dir */ + state(data, SSH_SFTP_QUOTE_MKDIR); + break; + } + else if(strncasecompare(cmd, "rename ", 7)) { + /* rename file */ + /* first param is the source path */ + /* second param is the dest. path */ + result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); + if(result) { + if(result == CURLE_OUT_OF_MEMORY) + failf(data, "Out of memory"); + else + failf(data, "Syntax error in rename: Bad second parameter"); + Curl_safefree(sshc->quote_path1); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + break; + } + state(data, SSH_SFTP_QUOTE_RENAME); + break; + } + else if(strncasecompare(cmd, "rmdir ", 6)) { + /* delete dir */ + state(data, SSH_SFTP_QUOTE_RMDIR); + break; + } + else if(strncasecompare(cmd, "rm ", 3)) { + state(data, SSH_SFTP_QUOTE_UNLINK); + break; + } +#ifdef HAS_STATVFS_SUPPORT + else if(strncasecompare(cmd, "statvfs ", 8)) { + state(data, SSH_SFTP_QUOTE_STATVFS); + break; + } +#endif + + failf(data, "Unknown SFTP command"); + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + + case SSH_SFTP_NEXT_QUOTE: + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + + sshc->quote_item = sshc->quote_item->next; + + if(sshc->quote_item) { + state(data, SSH_SFTP_QUOTE); + } + else { + if(sshc->nextstate != SSH_NO_STATE) { + state(data, sshc->nextstate); + sshc->nextstate = SSH_NO_STATE; + } + else { + state(data, SSH_SFTP_GETINFO); + } + } + break; + + case SSH_SFTP_QUOTE_STAT: + { + char *cmd = sshc->quote_item->data; + sshc->acceptfail = FALSE; + + /* if a command starts with an asterisk, which a legal SFTP command never + can, the command will be allowed to fail without it causing any + aborts or cancels etc. It will cause libcurl to act as if the command + is successful, whatever the server responds. */ + + if(cmd[0] == '*') { + cmd++; + sshc->acceptfail = TRUE; + } + + if(!strncasecompare(cmd, "chmod", 5)) { + /* Since chown and chgrp only set owner OR group but libssh2 wants to + * set them both at once, we need to obtain the current ownership + * first. This takes an extra protocol round trip. + */ + rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshc->quote_path2, + curlx_uztoui(strlen(sshc->quote_path2)), + LIBSSH2_SFTP_STAT, + &sshp->quote_attrs); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc && !sshc->acceptfail) { /* get those attributes */ + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + failf(data, "Attempt to get SFTP stats failed: %s", + sftp_libssh2_strerror(sftperr)); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + } + + /* Now set the new attributes... */ + if(strncasecompare(cmd, "chgrp", 5)) { + sshp->quote_attrs.gid = strtoul(sshc->quote_path1, NULL, 10); + sshp->quote_attrs.flags = LIBSSH2_SFTP_ATTR_UIDGID; + if(sshp->quote_attrs.gid == 0 && !ISDIGIT(sshc->quote_path1[0]) && + !sshc->acceptfail) { + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + failf(data, "Syntax error: chgrp gid not a number"); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + } + else if(strncasecompare(cmd, "chmod", 5)) { + sshp->quote_attrs.permissions = strtoul(sshc->quote_path1, NULL, 8); + sshp->quote_attrs.flags = LIBSSH2_SFTP_ATTR_PERMISSIONS; + /* permissions are octal */ + if(sshp->quote_attrs.permissions == 0 && + !ISDIGIT(sshc->quote_path1[0])) { + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + failf(data, "Syntax error: chmod permissions not a number"); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + } + else if(strncasecompare(cmd, "chown", 5)) { + sshp->quote_attrs.uid = strtoul(sshc->quote_path1, NULL, 10); + sshp->quote_attrs.flags = LIBSSH2_SFTP_ATTR_UIDGID; + if(sshp->quote_attrs.uid == 0 && !ISDIGIT(sshc->quote_path1[0]) && + !sshc->acceptfail) { + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + failf(data, "Syntax error: chown uid not a number"); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + } + else if(strncasecompare(cmd, "atime", 5) || + strncasecompare(cmd, "mtime", 5)) { + time_t date = Curl_getdate_capped(sshc->quote_path1); + bool fail = FALSE; + + if(date == -1) { + failf(data, "incorrect date format for %.*s", 5, cmd); + fail = TRUE; + } +#if SIZEOF_TIME_T > SIZEOF_LONG + if(date > 0xffffffff) { + /* if 'long' can't old >32bit, this date cannot be sent */ + failf(data, "date overflow"); + fail = TRUE; + } +#endif + if(fail) { + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + if(strncasecompare(cmd, "atime", 5)) + sshp->quote_attrs.atime = (unsigned long)date; + else /* mtime */ + sshp->quote_attrs.mtime = (unsigned long)date; + + sshp->quote_attrs.flags = LIBSSH2_SFTP_ATTR_ACMODTIME; + } + + /* Now send the completed structure... */ + state(data, SSH_SFTP_QUOTE_SETSTAT); + break; + } + + case SSH_SFTP_QUOTE_SETSTAT: + rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshc->quote_path2, + curlx_uztoui(strlen(sshc->quote_path2)), + LIBSSH2_SFTP_SETSTAT, + &sshp->quote_attrs); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc && !sshc->acceptfail) { + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + failf(data, "Attempt to set SFTP stats failed: %s", + sftp_libssh2_strerror(sftperr)); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + state(data, SSH_SFTP_NEXT_QUOTE); + break; + + case SSH_SFTP_QUOTE_SYMLINK: + rc = libssh2_sftp_symlink_ex(sshc->sftp_session, sshc->quote_path1, + curlx_uztoui(strlen(sshc->quote_path1)), + sshc->quote_path2, + curlx_uztoui(strlen(sshc->quote_path2)), + LIBSSH2_SFTP_SYMLINK); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc && !sshc->acceptfail) { + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + failf(data, "symlink command failed: %s", + sftp_libssh2_strerror(sftperr)); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + state(data, SSH_SFTP_NEXT_QUOTE); + break; + + case SSH_SFTP_QUOTE_MKDIR: + rc = libssh2_sftp_mkdir_ex(sshc->sftp_session, sshc->quote_path1, + curlx_uztoui(strlen(sshc->quote_path1)), + data->set.new_directory_perms); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc && !sshc->acceptfail) { + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + Curl_safefree(sshc->quote_path1); + failf(data, "mkdir command failed: %s", + sftp_libssh2_strerror(sftperr)); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + state(data, SSH_SFTP_NEXT_QUOTE); + break; + + case SSH_SFTP_QUOTE_RENAME: + rc = libssh2_sftp_rename_ex(sshc->sftp_session, sshc->quote_path1, + curlx_uztoui(strlen(sshc->quote_path1)), + sshc->quote_path2, + curlx_uztoui(strlen(sshc->quote_path2)), + LIBSSH2_SFTP_RENAME_OVERWRITE | + LIBSSH2_SFTP_RENAME_ATOMIC | + LIBSSH2_SFTP_RENAME_NATIVE); + + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc && !sshc->acceptfail) { + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + failf(data, "rename command failed: %s", + sftp_libssh2_strerror(sftperr)); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + state(data, SSH_SFTP_NEXT_QUOTE); + break; + + case SSH_SFTP_QUOTE_RMDIR: + rc = libssh2_sftp_rmdir_ex(sshc->sftp_session, sshc->quote_path1, + curlx_uztoui(strlen(sshc->quote_path1))); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc && !sshc->acceptfail) { + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + Curl_safefree(sshc->quote_path1); + failf(data, "rmdir command failed: %s", + sftp_libssh2_strerror(sftperr)); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + state(data, SSH_SFTP_NEXT_QUOTE); + break; + + case SSH_SFTP_QUOTE_UNLINK: + rc = libssh2_sftp_unlink_ex(sshc->sftp_session, sshc->quote_path1, + curlx_uztoui(strlen(sshc->quote_path1))); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc && !sshc->acceptfail) { + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + Curl_safefree(sshc->quote_path1); + failf(data, "rm command failed: %s", sftp_libssh2_strerror(sftperr)); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + state(data, SSH_SFTP_NEXT_QUOTE); + break; + +#ifdef HAS_STATVFS_SUPPORT + case SSH_SFTP_QUOTE_STATVFS: + { + LIBSSH2_SFTP_STATVFS statvfs; + rc = libssh2_sftp_statvfs(sshc->sftp_session, sshc->quote_path1, + curlx_uztoui(strlen(sshc->quote_path1)), + &statvfs); + + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc && !sshc->acceptfail) { + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + Curl_safefree(sshc->quote_path1); + failf(data, "statvfs command failed: %s", + sftp_libssh2_strerror(sftperr)); + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + else if(rc == 0) { + #ifdef _MSC_VER + #define CURL_LIBSSH2_VFS_SIZE_MASK "I64u" + #else + #define CURL_LIBSSH2_VFS_SIZE_MASK "llu" + #endif + char *tmp = aprintf("statvfs:\n" + "f_bsize: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_frsize: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_blocks: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_bfree: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_bavail: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_files: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_ffree: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_favail: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_fsid: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_flag: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_namemax: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n", + statvfs.f_bsize, statvfs.f_frsize, + statvfs.f_blocks, statvfs.f_bfree, + statvfs.f_bavail, statvfs.f_files, + statvfs.f_ffree, statvfs.f_favail, + statvfs.f_fsid, statvfs.f_flag, + statvfs.f_namemax); + if(!tmp) { + result = CURLE_OUT_OF_MEMORY; + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + break; + } + + result = Curl_client_write(data, CLIENTWRITE_HEADER, tmp, strlen(tmp)); + free(tmp); + if(result) { + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + } + } + state(data, SSH_SFTP_NEXT_QUOTE); + break; + } +#endif + case SSH_SFTP_GETINFO: + { + if(data->set.get_filetime) { + state(data, SSH_SFTP_FILETIME); + } + else { + state(data, SSH_SFTP_TRANS_INIT); + } + break; + } + + case SSH_SFTP_FILETIME: + { + LIBSSH2_SFTP_ATTRIBUTES attrs; + + rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshp->path, + curlx_uztoui(strlen(sshp->path)), + LIBSSH2_SFTP_STAT, &attrs); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc == 0) { + data->info.filetime = attrs.mtime; + } + + state(data, SSH_SFTP_TRANS_INIT); + break; + } + + case SSH_SFTP_TRANS_INIT: + if(data->state.upload) + state(data, SSH_SFTP_UPLOAD_INIT); + else { + if(sshp->path[strlen(sshp->path)-1] == '/') + state(data, SSH_SFTP_READDIR_INIT); + else + state(data, SSH_SFTP_DOWNLOAD_INIT); + } + break; + + case SSH_SFTP_UPLOAD_INIT: + { + unsigned long flags; + /* + * NOTE!!! libssh2 requires that the destination path is a full path + * that includes the destination file and name OR ends in a "/" + * If this is not done the destination file will be named the + * same name as the last directory in the path. + */ + + if(data->state.resume_from) { + LIBSSH2_SFTP_ATTRIBUTES attrs; + if(data->state.resume_from < 0) { + rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshp->path, + curlx_uztoui(strlen(sshp->path)), + LIBSSH2_SFTP_STAT, &attrs); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc) { + data->state.resume_from = 0; + } + else { + curl_off_t size = attrs.filesize; + if(size < 0) { + failf(data, "Bad file size (%" CURL_FORMAT_CURL_OFF_T ")", size); + return CURLE_BAD_DOWNLOAD_RESUME; + } + data->state.resume_from = attrs.filesize; + } + } + } + + if(data->set.remote_append) + /* Try to open for append, but create if nonexisting */ + flags = LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_APPEND; + else if(data->state.resume_from > 0) + /* If we have restart position then open for append */ + flags = LIBSSH2_FXF_WRITE|LIBSSH2_FXF_APPEND; + else + /* Clear file before writing (normal behavior) */ + flags = LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC; + + sshc->sftp_handle = + libssh2_sftp_open_ex(sshc->sftp_session, sshp->path, + curlx_uztoui(strlen(sshp->path)), + flags, data->set.new_file_perms, + LIBSSH2_SFTP_OPENFILE); + + if(!sshc->sftp_handle) { + rc = libssh2_session_last_errno(sshc->ssh_session); + + if(LIBSSH2_ERROR_EAGAIN == rc) + break; + + if(LIBSSH2_ERROR_SFTP_PROTOCOL == rc) + /* only when there was an SFTP protocol error can we extract + the sftp error! */ + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + else + sftperr = LIBSSH2_FX_OK; /* not an sftp error at all */ + + if(sshc->secondCreateDirs) { + state(data, SSH_SFTP_CLOSE); + sshc->actualcode = sftperr != LIBSSH2_FX_OK ? + sftp_libssh2_error_to_CURLE(sftperr):CURLE_SSH; + failf(data, "Creating the dir/file failed: %s", + sftp_libssh2_strerror(sftperr)); + break; + } + if(((sftperr == LIBSSH2_FX_NO_SUCH_FILE) || + (sftperr == LIBSSH2_FX_FAILURE) || + (sftperr == LIBSSH2_FX_NO_SUCH_PATH)) && + (data->set.ftp_create_missing_dirs && + (strlen(sshp->path) > 1))) { + /* try to create the path remotely */ + rc = 0; /* clear rc and continue */ + sshc->secondCreateDirs = 1; + state(data, SSH_SFTP_CREATE_DIRS_INIT); + break; + } + state(data, SSH_SFTP_CLOSE); + sshc->actualcode = sftperr != LIBSSH2_FX_OK ? + sftp_libssh2_error_to_CURLE(sftperr):CURLE_SSH; + if(!sshc->actualcode) { + /* Sometimes, for some reason libssh2_sftp_last_error() returns zero + even though libssh2_sftp_open() failed previously! We need to + work around that! */ + sshc->actualcode = CURLE_SSH; + sftperr = LIBSSH2_FX_OK; + } + failf(data, "Upload failed: %s (%lu/%d)", + sftperr != LIBSSH2_FX_OK ? + sftp_libssh2_strerror(sftperr):"ssh error", + sftperr, rc); + break; + } + + /* If we have a restart point then we need to seek to the correct + position. */ + if(data->state.resume_from > 0) { + /* Let's read off the proper amount of bytes from the input. */ + if(data->set.seek_func) { + Curl_set_in_callback(data, true); + seekerr = data->set.seek_func(data->set.seek_client, + data->state.resume_from, SEEK_SET); + Curl_set_in_callback(data, false); + } + + if(seekerr != CURL_SEEKFUNC_OK) { + curl_off_t passed = 0; + + if(seekerr != CURL_SEEKFUNC_CANTSEEK) { + failf(data, "Could not seek stream"); + return CURLE_FTP_COULDNT_USE_REST; + } + /* seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */ + do { + char scratch[4*1024]; + size_t readthisamountnow = + (data->state.resume_from - passed > + (curl_off_t)sizeof(scratch)) ? + sizeof(scratch) : curlx_sotouz(data->state.resume_from - passed); + + size_t actuallyread; + Curl_set_in_callback(data, true); + actuallyread = data->state.fread_func(scratch, 1, + readthisamountnow, + data->state.in); + Curl_set_in_callback(data, false); + + passed += actuallyread; + if((actuallyread == 0) || (actuallyread > readthisamountnow)) { + /* this checks for greater-than only to make sure that the + CURL_READFUNC_ABORT return code still aborts */ + failf(data, "Failed to read data"); + return CURLE_FTP_COULDNT_USE_REST; + } + } while(passed < data->state.resume_from); + } + + /* now, decrease the size of the read */ + if(data->state.infilesize > 0) { + data->state.infilesize -= data->state.resume_from; + data->req.size = data->state.infilesize; + Curl_pgrsSetUploadSize(data, data->state.infilesize); + } + + SFTP_SEEK(sshc->sftp_handle, data->state.resume_from); + } + if(data->state.infilesize > 0) { + data->req.size = data->state.infilesize; + Curl_pgrsSetUploadSize(data, data->state.infilesize); + } + /* upload data */ + Curl_xfer_setup(data, -1, -1, FALSE, FIRSTSOCKET); + + /* not set by Curl_xfer_setup to preserve keepon bits */ + conn->sockfd = conn->writesockfd; + + if(result) { + state(data, SSH_SFTP_CLOSE); + sshc->actualcode = result; + } + else { + /* store this original bitmask setup to use later on if we can't + figure out a "real" bitmask */ + sshc->orig_waitfor = data->req.keepon; + + /* we want to use the _sending_ function even when the socket turns + out readable as the underlying libssh2 sftp send function will deal + with both accordingly */ + data->state.select_bits = CURL_CSELECT_OUT; + + /* since we don't really wait for anything at this point, we want the + state machine to move on as soon as possible so we set a very short + timeout here */ + Curl_expire(data, 0, EXPIRE_RUN_NOW); + + state(data, SSH_STOP); + } + break; + } + + case SSH_SFTP_CREATE_DIRS_INIT: + if(strlen(sshp->path) > 1) { + sshc->slash_pos = sshp->path + 1; /* ignore the leading '/' */ + state(data, SSH_SFTP_CREATE_DIRS); + } + else { + state(data, SSH_SFTP_UPLOAD_INIT); + } + break; + + case SSH_SFTP_CREATE_DIRS: + sshc->slash_pos = strchr(sshc->slash_pos, '/'); + if(sshc->slash_pos) { + *sshc->slash_pos = 0; + + infof(data, "Creating directory '%s'", sshp->path); + state(data, SSH_SFTP_CREATE_DIRS_MKDIR); + break; + } + state(data, SSH_SFTP_UPLOAD_INIT); + break; + + case SSH_SFTP_CREATE_DIRS_MKDIR: + /* 'mode' - parameter is preliminary - default to 0644 */ + rc = libssh2_sftp_mkdir_ex(sshc->sftp_session, sshp->path, + curlx_uztoui(strlen(sshp->path)), + data->set.new_directory_perms); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + *sshc->slash_pos = '/'; + ++sshc->slash_pos; + if(rc < 0) { + /* + * Abort if failure wasn't that the dir already exists or the + * permission was denied (creation might succeed further down the + * path) - retry on unspecific FAILURE also + */ + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + if((sftperr != LIBSSH2_FX_FILE_ALREADY_EXISTS) && + (sftperr != LIBSSH2_FX_FAILURE) && + (sftperr != LIBSSH2_FX_PERMISSION_DENIED)) { + result = sftp_libssh2_error_to_CURLE(sftperr); + state(data, SSH_SFTP_CLOSE); + sshc->actualcode = result?result:CURLE_SSH; + break; + } + rc = 0; /* clear rc and continue */ + } + state(data, SSH_SFTP_CREATE_DIRS); + break; + + case SSH_SFTP_READDIR_INIT: + Curl_pgrsSetDownloadSize(data, -1); + if(data->req.no_body) { + state(data, SSH_STOP); + break; + } + + /* + * This is a directory that we are trying to get, so produce a directory + * listing + */ + sshc->sftp_handle = libssh2_sftp_open_ex(sshc->sftp_session, + sshp->path, + curlx_uztoui( + strlen(sshp->path)), + 0, 0, LIBSSH2_SFTP_OPENDIR); + if(!sshc->sftp_handle) { + if(libssh2_session_last_errno(sshc->ssh_session) == + LIBSSH2_ERROR_EAGAIN) { + rc = LIBSSH2_ERROR_EAGAIN; + break; + } + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + failf(data, "Could not open directory for reading: %s", + sftp_libssh2_strerror(sftperr)); + state(data, SSH_SFTP_CLOSE); + result = sftp_libssh2_error_to_CURLE(sftperr); + sshc->actualcode = result?result:CURLE_SSH; + break; + } + sshp->readdir_filename = malloc(PATH_MAX + 1); + if(!sshp->readdir_filename) { + state(data, SSH_SFTP_CLOSE); + sshc->actualcode = CURLE_OUT_OF_MEMORY; + break; + } + sshp->readdir_longentry = malloc(PATH_MAX + 1); + if(!sshp->readdir_longentry) { + Curl_safefree(sshp->readdir_filename); + state(data, SSH_SFTP_CLOSE); + sshc->actualcode = CURLE_OUT_OF_MEMORY; + break; + } + Curl_dyn_init(&sshp->readdir, PATH_MAX * 2); + state(data, SSH_SFTP_READDIR); + break; + + case SSH_SFTP_READDIR: + rc = libssh2_sftp_readdir_ex(sshc->sftp_handle, + sshp->readdir_filename, + PATH_MAX, + sshp->readdir_longentry, + PATH_MAX, + &sshp->readdir_attrs); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc > 0) { + readdir_len = (size_t) rc; + sshp->readdir_filename[readdir_len] = '\0'; + + if(data->set.list_only) { + result = Curl_client_write(data, CLIENTWRITE_BODY, + sshp->readdir_filename, + readdir_len); + if(!result) + result = Curl_client_write(data, CLIENTWRITE_BODY, + (char *)"\n", 1); + if(result) { + state(data, SSH_STOP); + break; + } + + } + else { + result = Curl_dyn_add(&sshp->readdir, sshp->readdir_longentry); + + if(!result) { + if((sshp->readdir_attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) && + ((sshp->readdir_attrs.permissions & LIBSSH2_SFTP_S_IFMT) == + LIBSSH2_SFTP_S_IFLNK)) { + Curl_dyn_init(&sshp->readdir_link, PATH_MAX); + result = Curl_dyn_addf(&sshp->readdir_link, "%s%s", sshp->path, + sshp->readdir_filename); + state(data, SSH_SFTP_READDIR_LINK); + if(!result) + break; + } + else { + state(data, SSH_SFTP_READDIR_BOTTOM); + break; + } + } + sshc->actualcode = result; + state(data, SSH_SFTP_CLOSE); + break; + } + } + else if(rc == 0) { + Curl_safefree(sshp->readdir_filename); + Curl_safefree(sshp->readdir_longentry); + state(data, SSH_SFTP_READDIR_DONE); + break; + } + else if(rc < 0) { + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + result = sftp_libssh2_error_to_CURLE(sftperr); + sshc->actualcode = result?result:CURLE_SSH; + failf(data, "Could not open remote file for reading: %s :: %d", + sftp_libssh2_strerror(sftperr), + libssh2_session_last_errno(sshc->ssh_session)); + Curl_safefree(sshp->readdir_filename); + Curl_safefree(sshp->readdir_longentry); + state(data, SSH_SFTP_CLOSE); + break; + } + break; + + case SSH_SFTP_READDIR_LINK: + rc = + libssh2_sftp_symlink_ex(sshc->sftp_session, + Curl_dyn_ptr(&sshp->readdir_link), + (int)Curl_dyn_len(&sshp->readdir_link), + sshp->readdir_filename, + PATH_MAX, LIBSSH2_SFTP_READLINK); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + Curl_dyn_free(&sshp->readdir_link); + + /* append filename and extra output */ + result = Curl_dyn_addf(&sshp->readdir, " -> %s", sshp->readdir_filename); + + if(result) { + Curl_safefree(sshp->readdir_filename); + Curl_safefree(sshp->readdir_longentry); + state(data, SSH_SFTP_CLOSE); + sshc->actualcode = result; + break; + } + + state(data, SSH_SFTP_READDIR_BOTTOM); + break; + + case SSH_SFTP_READDIR_BOTTOM: + result = Curl_dyn_addn(&sshp->readdir, "\n", 1); + if(!result) + result = Curl_client_write(data, CLIENTWRITE_BODY, + Curl_dyn_ptr(&sshp->readdir), + Curl_dyn_len(&sshp->readdir)); + + if(result) { + Curl_dyn_free(&sshp->readdir); + state(data, SSH_STOP); + } + else { + Curl_dyn_reset(&sshp->readdir); + state(data, SSH_SFTP_READDIR); + } + break; + + case SSH_SFTP_READDIR_DONE: + if(libssh2_sftp_closedir(sshc->sftp_handle) == + LIBSSH2_ERROR_EAGAIN) { + rc = LIBSSH2_ERROR_EAGAIN; + break; + } + sshc->sftp_handle = NULL; + Curl_safefree(sshp->readdir_filename); + Curl_safefree(sshp->readdir_longentry); + + /* no data to transfer */ + Curl_xfer_setup(data, -1, -1, FALSE, -1); + state(data, SSH_STOP); + break; + + case SSH_SFTP_DOWNLOAD_INIT: + /* + * Work on getting the specified file + */ + sshc->sftp_handle = + libssh2_sftp_open_ex(sshc->sftp_session, sshp->path, + curlx_uztoui(strlen(sshp->path)), + LIBSSH2_FXF_READ, data->set.new_file_perms, + LIBSSH2_SFTP_OPENFILE); + if(!sshc->sftp_handle) { + if(libssh2_session_last_errno(sshc->ssh_session) == + LIBSSH2_ERROR_EAGAIN) { + rc = LIBSSH2_ERROR_EAGAIN; + break; + } + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + failf(data, "Could not open remote file for reading: %s", + sftp_libssh2_strerror(sftperr)); + state(data, SSH_SFTP_CLOSE); + result = sftp_libssh2_error_to_CURLE(sftperr); + sshc->actualcode = result?result:CURLE_SSH; + break; + } + state(data, SSH_SFTP_DOWNLOAD_STAT); + break; + + case SSH_SFTP_DOWNLOAD_STAT: + { + LIBSSH2_SFTP_ATTRIBUTES attrs; + + rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshp->path, + curlx_uztoui(strlen(sshp->path)), + LIBSSH2_SFTP_STAT, &attrs); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc || + !(attrs.flags & LIBSSH2_SFTP_ATTR_SIZE) || + (attrs.filesize == 0)) { + /* + * libssh2_sftp_open() didn't return an error, so maybe the server + * just doesn't support stat() + * OR the server doesn't return a file size with a stat() + * OR file size is 0 + */ + data->req.size = -1; + data->req.maxdownload = -1; + Curl_pgrsSetDownloadSize(data, -1); + } + else { + curl_off_t size = attrs.filesize; + + if(size < 0) { + failf(data, "Bad file size (%" CURL_FORMAT_CURL_OFF_T ")", size); + return CURLE_BAD_DOWNLOAD_RESUME; + } + if(data->state.use_range) { + curl_off_t from, to; + char *ptr; + char *ptr2; + CURLofft to_t; + CURLofft from_t; + + from_t = curlx_strtoofft(data->state.range, &ptr, 10, &from); + if(from_t == CURL_OFFT_FLOW) + return CURLE_RANGE_ERROR; + while(*ptr && (ISBLANK(*ptr) || (*ptr == '-'))) + ptr++; + to_t = curlx_strtoofft(ptr, &ptr2, 10, &to); + if(to_t == CURL_OFFT_FLOW) + return CURLE_RANGE_ERROR; + if((to_t == CURL_OFFT_INVAL) /* no "to" value given */ + || (to >= size)) { + to = size - 1; + } + if(from_t) { + /* from is relative to end of file */ + from = size - to; + to = size - 1; + } + if(from > size) { + failf(data, "Offset (%" + CURL_FORMAT_CURL_OFF_T ") was beyond file size (%" + CURL_FORMAT_CURL_OFF_T ")", from, + (curl_off_t)attrs.filesize); + return CURLE_BAD_DOWNLOAD_RESUME; + } + if(from > to) { + from = to; + size = 0; + } + else { + if((to - from) == CURL_OFF_T_MAX) + return CURLE_RANGE_ERROR; + size = to - from + 1; + } + + SFTP_SEEK(sshc->sftp_handle, from); + } + data->req.size = size; + data->req.maxdownload = size; + Curl_pgrsSetDownloadSize(data, size); + } + + /* We can resume if we can seek to the resume position */ + if(data->state.resume_from) { + if(data->state.resume_from < 0) { + /* We're supposed to download the last abs(from) bytes */ + if((curl_off_t)attrs.filesize < -data->state.resume_from) { + failf(data, "Offset (%" + CURL_FORMAT_CURL_OFF_T ") was beyond file size (%" + CURL_FORMAT_CURL_OFF_T ")", + data->state.resume_from, (curl_off_t)attrs.filesize); + return CURLE_BAD_DOWNLOAD_RESUME; + } + /* download from where? */ + data->state.resume_from += attrs.filesize; + } + else { + if((curl_off_t)attrs.filesize < data->state.resume_from) { + failf(data, "Offset (%" CURL_FORMAT_CURL_OFF_T + ") was beyond file size (%" CURL_FORMAT_CURL_OFF_T ")", + data->state.resume_from, (curl_off_t)attrs.filesize); + return CURLE_BAD_DOWNLOAD_RESUME; + } + } + /* Now store the number of bytes we are expected to download */ + data->req.size = attrs.filesize - data->state.resume_from; + data->req.maxdownload = attrs.filesize - data->state.resume_from; + Curl_pgrsSetDownloadSize(data, + attrs.filesize - data->state.resume_from); + SFTP_SEEK(sshc->sftp_handle, data->state.resume_from); + } + } + + /* Setup the actual download */ + if(data->req.size == 0) { + /* no data to transfer */ + Curl_xfer_setup(data, -1, -1, FALSE, -1); + infof(data, "File already completely downloaded"); + state(data, SSH_STOP); + break; + } + Curl_xfer_setup(data, FIRSTSOCKET, data->req.size, FALSE, -1); + + /* not set by Curl_xfer_setup to preserve keepon bits */ + conn->writesockfd = conn->sockfd; + + /* we want to use the _receiving_ function even when the socket turns + out writableable as the underlying libssh2 recv function will deal + with both accordingly */ + data->state.select_bits = CURL_CSELECT_IN; + + if(result) { + /* this should never occur; the close state should be entered + at the time the error occurs */ + state(data, SSH_SFTP_CLOSE); + sshc->actualcode = result; + } + else { + state(data, SSH_STOP); + } + break; + + case SSH_SFTP_CLOSE: + if(sshc->sftp_handle) { + rc = libssh2_sftp_close(sshc->sftp_handle); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc < 0) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0); + infof(data, "Failed to close libssh2 file: %d %s", rc, err_msg); + } + sshc->sftp_handle = NULL; + } + + Curl_safefree(sshp->path); + + DEBUGF(infof(data, "SFTP DONE done")); + + /* Check if nextstate is set and move .nextstate could be POSTQUOTE_INIT + After nextstate is executed, the control should come back to + SSH_SFTP_CLOSE to pass the correct result back */ + if(sshc->nextstate != SSH_NO_STATE && + sshc->nextstate != SSH_SFTP_CLOSE) { + state(data, sshc->nextstate); + sshc->nextstate = SSH_SFTP_CLOSE; + } + else { + state(data, SSH_STOP); + result = sshc->actualcode; + } + break; + + case SSH_SFTP_SHUTDOWN: + /* during times we get here due to a broken transfer and then the + sftp_handle might not have been taken down so make sure that is done + before we proceed */ + + if(sshc->sftp_handle) { + rc = libssh2_sftp_close(sshc->sftp_handle); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc < 0) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, + NULL, 0); + infof(data, "Failed to close libssh2 file: %d %s", rc, err_msg); + } + sshc->sftp_handle = NULL; + } + if(sshc->sftp_session) { + rc = libssh2_sftp_shutdown(sshc->sftp_session); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc < 0) { + infof(data, "Failed to stop libssh2 sftp subsystem"); + } + sshc->sftp_session = NULL; + } + + Curl_safefree(sshc->homedir); + data->state.most_recent_ftp_entrypath = NULL; + + state(data, SSH_SESSION_DISCONNECT); + break; + + case SSH_SCP_TRANS_INIT: + result = Curl_getworkingpath(data, sshc->homedir, &sshp->path); + if(result) { + sshc->actualcode = result; + state(data, SSH_STOP); + break; + } + + if(data->state.upload) { + if(data->state.infilesize < 0) { + failf(data, "SCP requires a known file size for upload"); + sshc->actualcode = CURLE_UPLOAD_FAILED; + state(data, SSH_SCP_CHANNEL_FREE); + break; + } + state(data, SSH_SCP_UPLOAD_INIT); + } + else { + state(data, SSH_SCP_DOWNLOAD_INIT); + } + break; + + case SSH_SCP_UPLOAD_INIT: + /* + * libssh2 requires that the destination path is a full path that + * includes the destination file and name OR ends in a "/" . If this is + * not done the destination file will be named the same name as the last + * directory in the path. + */ + sshc->ssh_channel = + SCP_SEND(sshc->ssh_session, sshp->path, data->set.new_file_perms, + data->state.infilesize); + if(!sshc->ssh_channel) { + int ssh_err; + char *err_msg = NULL; + + if(libssh2_session_last_errno(sshc->ssh_session) == + LIBSSH2_ERROR_EAGAIN) { + rc = LIBSSH2_ERROR_EAGAIN; + break; + } + + ssh_err = (int)(libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0)); + failf(data, "%s", err_msg); + state(data, SSH_SCP_CHANNEL_FREE); + sshc->actualcode = libssh2_session_error_to_CURLE(ssh_err); + /* Map generic errors to upload failed */ + if(sshc->actualcode == CURLE_SSH || + sshc->actualcode == CURLE_REMOTE_FILE_NOT_FOUND) + sshc->actualcode = CURLE_UPLOAD_FAILED; + break; + } + + /* upload data */ + data->req.size = data->state.infilesize; + Curl_pgrsSetUploadSize(data, data->state.infilesize); + Curl_xfer_setup(data, -1, -1, FALSE, FIRSTSOCKET); + + /* not set by Curl_xfer_setup to preserve keepon bits */ + conn->sockfd = conn->writesockfd; + + if(result) { + state(data, SSH_SCP_CHANNEL_FREE); + sshc->actualcode = result; + } + else { + /* store this original bitmask setup to use later on if we can't + figure out a "real" bitmask */ + sshc->orig_waitfor = data->req.keepon; + + /* we want to use the _sending_ function even when the socket turns + out readable as the underlying libssh2 scp send function will deal + with both accordingly */ + data->state.select_bits = CURL_CSELECT_OUT; + + state(data, SSH_STOP); + } + break; + + case SSH_SCP_DOWNLOAD_INIT: + { + curl_off_t bytecount; + + /* + * We must check the remote file; if it is a directory no values will + * be set in sb + */ + + /* + * If support for >2GB files exists, use it. + */ + + /* get a fresh new channel from the ssh layer */ +#if LIBSSH2_VERSION_NUM < 0x010700 + struct stat sb; + memset(&sb, 0, sizeof(struct stat)); + sshc->ssh_channel = libssh2_scp_recv(sshc->ssh_session, + sshp->path, &sb); +#else + libssh2_struct_stat sb; + memset(&sb, 0, sizeof(libssh2_struct_stat)); + sshc->ssh_channel = libssh2_scp_recv2(sshc->ssh_session, + sshp->path, &sb); +#endif + + if(!sshc->ssh_channel) { + int ssh_err; + char *err_msg = NULL; + + if(libssh2_session_last_errno(sshc->ssh_session) == + LIBSSH2_ERROR_EAGAIN) { + rc = LIBSSH2_ERROR_EAGAIN; + break; + } + + + ssh_err = (int)(libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0)); + failf(data, "%s", err_msg); + state(data, SSH_SCP_CHANNEL_FREE); + sshc->actualcode = libssh2_session_error_to_CURLE(ssh_err); + break; + } + + /* download data */ + bytecount = (curl_off_t)sb.st_size; + data->req.maxdownload = (curl_off_t)sb.st_size; + Curl_xfer_setup(data, FIRSTSOCKET, bytecount, FALSE, -1); + + /* not set by Curl_xfer_setup to preserve keepon bits */ + conn->writesockfd = conn->sockfd; + + /* we want to use the _receiving_ function even when the socket turns + out writableable as the underlying libssh2 recv function will deal + with both accordingly */ + data->state.select_bits = CURL_CSELECT_IN; + + if(result) { + state(data, SSH_SCP_CHANNEL_FREE); + sshc->actualcode = result; + } + else + state(data, SSH_STOP); + } + break; + + case SSH_SCP_DONE: + if(data->state.upload) + state(data, SSH_SCP_SEND_EOF); + else + state(data, SSH_SCP_CHANNEL_FREE); + break; + + case SSH_SCP_SEND_EOF: + if(sshc->ssh_channel) { + rc = libssh2_channel_send_eof(sshc->ssh_channel); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0); + infof(data, "Failed to send libssh2 channel EOF: %d %s", + rc, err_msg); + } + } + state(data, SSH_SCP_WAIT_EOF); + break; + + case SSH_SCP_WAIT_EOF: + if(sshc->ssh_channel) { + rc = libssh2_channel_wait_eof(sshc->ssh_channel); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0); + infof(data, "Failed to get channel EOF: %d %s", rc, err_msg); + } + } + state(data, SSH_SCP_WAIT_CLOSE); + break; + + case SSH_SCP_WAIT_CLOSE: + if(sshc->ssh_channel) { + rc = libssh2_channel_wait_closed(sshc->ssh_channel); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0); + infof(data, "Channel failed to close: %d %s", rc, err_msg); + } + } + state(data, SSH_SCP_CHANNEL_FREE); + break; + + case SSH_SCP_CHANNEL_FREE: + if(sshc->ssh_channel) { + rc = libssh2_channel_free(sshc->ssh_channel); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc < 0) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0); + infof(data, "Failed to free libssh2 scp subsystem: %d %s", + rc, err_msg); + } + sshc->ssh_channel = NULL; + } + DEBUGF(infof(data, "SCP DONE phase complete")); +#if 0 /* PREV */ + state(data, SSH_SESSION_DISCONNECT); +#endif + state(data, SSH_STOP); + result = sshc->actualcode; + break; + + case SSH_SESSION_DISCONNECT: + /* during weird times when we've been prematurely aborted, the channel + is still alive when we reach this state and we MUST kill the channel + properly first */ + if(sshc->ssh_channel) { + rc = libssh2_channel_free(sshc->ssh_channel); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc < 0) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0); + infof(data, "Failed to free libssh2 scp subsystem: %d %s", + rc, err_msg); + } + sshc->ssh_channel = NULL; + } + + if(sshc->ssh_session) { + rc = libssh2_session_disconnect(sshc->ssh_session, "Shutdown"); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc < 0) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0); + infof(data, "Failed to disconnect libssh2 session: %d %s", + rc, err_msg); + } + } + + Curl_safefree(sshc->homedir); + data->state.most_recent_ftp_entrypath = NULL; + + state(data, SSH_SESSION_FREE); + break; + + case SSH_SESSION_FREE: +#ifdef HAVE_LIBSSH2_KNOWNHOST_API + if(sshc->kh) { + libssh2_knownhost_free(sshc->kh); + sshc->kh = NULL; + } +#endif + +#ifdef HAVE_LIBSSH2_AGENT_API + if(sshc->ssh_agent) { + rc = libssh2_agent_disconnect(sshc->ssh_agent); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc < 0) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0); + infof(data, "Failed to disconnect from libssh2 agent: %d %s", + rc, err_msg); + } + libssh2_agent_free(sshc->ssh_agent); + sshc->ssh_agent = NULL; + + /* NB: there is no need to free identities, they are part of internal + agent stuff */ + sshc->sshagent_identity = NULL; + sshc->sshagent_prev_identity = NULL; + } +#endif + + if(sshc->ssh_session) { + rc = libssh2_session_free(sshc->ssh_session); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc < 0) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0); + infof(data, "Failed to free libssh2 session: %d %s", rc, err_msg); + } + sshc->ssh_session = NULL; + } + + /* worst-case scenario cleanup */ + + DEBUGASSERT(sshc->ssh_session == NULL); + DEBUGASSERT(sshc->ssh_channel == NULL); + DEBUGASSERT(sshc->sftp_session == NULL); + DEBUGASSERT(sshc->sftp_handle == NULL); +#ifdef HAVE_LIBSSH2_KNOWNHOST_API + DEBUGASSERT(sshc->kh == NULL); +#endif +#ifdef HAVE_LIBSSH2_AGENT_API + DEBUGASSERT(sshc->ssh_agent == NULL); +#endif + + Curl_safefree(sshc->rsa_pub); + Curl_safefree(sshc->rsa); + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + Curl_safefree(sshc->homedir); + + /* the code we are about to return */ + result = sshc->actualcode; + + memset(sshc, 0, sizeof(struct ssh_conn)); + + connclose(conn, "SSH session free"); + sshc->state = SSH_SESSION_FREE; /* current */ + sshc->nextstate = SSH_NO_STATE; + state(data, SSH_STOP); + break; + + case SSH_QUIT: + default: + /* internal error */ + sshc->nextstate = SSH_NO_STATE; + state(data, SSH_STOP); + break; + } + + } while(!rc && (sshc->state != SSH_STOP)); + + if(rc == LIBSSH2_ERROR_EAGAIN) { + /* we would block, we need to wait for the socket to be ready (in the + right direction too)! */ + *block = TRUE; + } + + return result; +} + +/* called by the multi interface to figure out what socket(s) to wait for and + for what actions in the DO_DONE, PERFORM and WAITPERFORM states */ +static int ssh_getsock(struct Curl_easy *data, + struct connectdata *conn, + curl_socket_t *sock) +{ + int bitmap = GETSOCK_BLANK; + (void)data; + + sock[0] = conn->sock[FIRSTSOCKET]; + + if(conn->waitfor & KEEP_RECV) + bitmap |= GETSOCK_READSOCK(FIRSTSOCKET); + + if(conn->waitfor & KEEP_SEND) + bitmap |= GETSOCK_WRITESOCK(FIRSTSOCKET); + + return bitmap; +} + +/* + * When one of the libssh2 functions has returned LIBSSH2_ERROR_EAGAIN this + * function is used to figure out in what direction and stores this info so + * that the multi interface can take advantage of it. Make sure to call this + * function in all cases so that when it _doesn't_ return EAGAIN we can + * restore the default wait bits. + */ +static void ssh_block2waitfor(struct Curl_easy *data, bool block) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + int dir = 0; + if(block) { + dir = libssh2_session_block_directions(sshc->ssh_session); + if(dir) { + /* translate the libssh2 define bits into our own bit defines */ + conn->waitfor = ((dir&LIBSSH2_SESSION_BLOCK_INBOUND)?KEEP_RECV:0) | + ((dir&LIBSSH2_SESSION_BLOCK_OUTBOUND)?KEEP_SEND:0); + } + } + if(!dir) + /* It didn't block or libssh2 didn't reveal in which direction, put back + the original set */ + conn->waitfor = sshc->orig_waitfor; +} + +/* called repeatedly until done from multi.c */ +static CURLcode ssh_multi_statemach(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + CURLcode result = CURLE_OK; + bool block; /* we store the status and use that to provide a ssh_getsock() + implementation */ + do { + result = ssh_statemach_act(data, &block); + *done = (sshc->state == SSH_STOP) ? TRUE : FALSE; + /* if there's no error, it isn't done and it didn't EWOULDBLOCK, then + try again */ + } while(!result && !*done && !block); + ssh_block2waitfor(data, block); + + return result; +} + +static CURLcode ssh_block_statemach(struct Curl_easy *data, + struct connectdata *conn, + bool disconnect) +{ + struct ssh_conn *sshc = &conn->proto.sshc; + CURLcode result = CURLE_OK; + struct curltime dis = Curl_now(); + + while((sshc->state != SSH_STOP) && !result) { + bool block; + timediff_t left = 1000; + struct curltime now = Curl_now(); + + result = ssh_statemach_act(data, &block); + if(result) + break; + + if(!disconnect) { + if(Curl_pgrsUpdate(data)) + return CURLE_ABORTED_BY_CALLBACK; + + result = Curl_speedcheck(data, now); + if(result) + break; + + left = Curl_timeleft(data, NULL, FALSE); + if(left < 0) { + failf(data, "Operation timed out"); + return CURLE_OPERATION_TIMEDOUT; + } + } + else if(Curl_timediff(now, dis) > 1000) { + /* disconnect timeout */ + failf(data, "Disconnect timed out"); + result = CURLE_OK; + break; + } + + if(block) { + int dir = libssh2_session_block_directions(sshc->ssh_session); + curl_socket_t sock = conn->sock[FIRSTSOCKET]; + curl_socket_t fd_read = CURL_SOCKET_BAD; + curl_socket_t fd_write = CURL_SOCKET_BAD; + if(LIBSSH2_SESSION_BLOCK_INBOUND & dir) + fd_read = sock; + if(LIBSSH2_SESSION_BLOCK_OUTBOUND & dir) + fd_write = sock; + /* wait for the socket to become ready */ + (void)Curl_socket_check(fd_read, CURL_SOCKET_BAD, fd_write, + left>1000?1000:left); + } + } + + return result; +} + +/* + * SSH setup and connection + */ +static CURLcode ssh_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + struct SSHPROTO *ssh; + (void)conn; + + data->req.p.ssh = ssh = calloc(1, sizeof(struct SSHPROTO)); + if(!ssh) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +static Curl_recv scp_recv, sftp_recv; +static Curl_send scp_send, sftp_send; + +#ifndef CURL_DISABLE_PROXY +static ssize_t ssh_tls_recv(libssh2_socket_t sock, void *buffer, + size_t length, int flags, void **abstract) +{ + struct Curl_easy *data = (struct Curl_easy *)*abstract; + ssize_t nread; + CURLcode result; + struct connectdata *conn = data->conn; + Curl_recv *backup = conn->recv[0]; + struct ssh_conn *ssh = &conn->proto.sshc; + int socknum = Curl_conn_sockindex(data, sock); + (void)flags; + + /* swap in the TLS reader function for this call only, and then swap back + the SSH one again */ + conn->recv[0] = ssh->tls_recv; + result = Curl_conn_recv(data, socknum, buffer, length, &nread); + conn->recv[0] = backup; + if(result == CURLE_AGAIN) + return -EAGAIN; /* magic return code for libssh2 */ + else if(result) + return -1; /* generic error */ + Curl_debug(data, CURLINFO_DATA_IN, (char *)buffer, (size_t)nread); + return nread; +} + +static ssize_t ssh_tls_send(libssh2_socket_t sock, const void *buffer, + size_t length, int flags, void **abstract) +{ + struct Curl_easy *data = (struct Curl_easy *)*abstract; + size_t nwrite; + CURLcode result; + struct connectdata *conn = data->conn; + Curl_send *backup = conn->send[0]; + struct ssh_conn *ssh = &conn->proto.sshc; + int socknum = Curl_conn_sockindex(data, sock); + (void)flags; + + /* swap in the TLS writer function for this call only, and then swap back + the SSH one again */ + conn->send[0] = ssh->tls_send; + result = Curl_conn_send(data, socknum, buffer, length, &nwrite); + conn->send[0] = backup; + if(result == CURLE_AGAIN) + return -EAGAIN; /* magic return code for libssh2 */ + else if(result) + return -1; /* error */ + Curl_debug(data, CURLINFO_DATA_OUT, (char *)buffer, nwrite); + return (ssize_t)nwrite; +} +#endif + +/* + * Curl_ssh_connect() gets called from Curl_protocol_connect() to allow us to + * do protocol-specific actions at connect-time. + */ +static CURLcode ssh_connect(struct Curl_easy *data, bool *done) +{ +#ifdef CURL_LIBSSH2_DEBUG + curl_socket_t sock; +#endif + struct ssh_conn *sshc; + CURLcode result; + struct connectdata *conn = data->conn; + + /* initialize per-handle data if not already */ + if(!data->req.p.ssh) { + result = ssh_setup_connection(data, conn); + if(result) + return result; + } + + /* We default to persistent connections. We set this already in this connect + function to make the reuse checks properly be able to check this bit. */ + connkeep(conn, "SSH default"); + + sshc = &conn->proto.sshc; + +#ifdef CURL_LIBSSH2_DEBUG + if(conn->user) { + infof(data, "User: %s", conn->user); + } + if(conn->passwd) { + infof(data, "Password: %s", conn->passwd); + } + sock = conn->sock[FIRSTSOCKET]; +#endif /* CURL_LIBSSH2_DEBUG */ + + /* libcurl MUST to set custom memory functions so that the kbd_callback + function's memory allocations can be properly freed */ + sshc->ssh_session = libssh2_session_init_ex(my_libssh2_malloc, + my_libssh2_free, + my_libssh2_realloc, data); + + if(!sshc->ssh_session) { + failf(data, "Failure initialising ssh session"); + return CURLE_FAILED_INIT; + } + + /* Set the packet read timeout if the libssh2 version supports it */ +#if LIBSSH2_VERSION_NUM >= 0x010B00 + if(data->set.server_response_timeout > 0) { + libssh2_session_set_read_timeout(sshc->ssh_session, + data->set.server_response_timeout / 1000); + } +#endif + +#ifndef CURL_DISABLE_PROXY + if(conn->http_proxy.proxytype == CURLPROXY_HTTPS) { + /* + Setup libssh2 callbacks to make it read/write TLS from the socket. + + ssize_t + recvcb(libssh2_socket_t sock, void *buffer, size_t length, + int flags, void **abstract); + + ssize_t + sendcb(libssh2_socket_t sock, const void *buffer, size_t length, + int flags, void **abstract); + + */ +#if LIBSSH2_VERSION_NUM >= 0x010b01 + infof(data, "Uses HTTPS proxy"); + libssh2_session_callback_set2(sshc->ssh_session, + LIBSSH2_CALLBACK_RECV, + (libssh2_cb_generic *)ssh_tls_recv); + libssh2_session_callback_set2(sshc->ssh_session, + LIBSSH2_CALLBACK_SEND, + (libssh2_cb_generic *)ssh_tls_send); +#else + /* + * This crazy union dance is here to avoid assigning a void pointer a + * function pointer as it is invalid C. The problem is of course that + * libssh2 has such an API... + */ + union receive { + void *recvp; + ssize_t (*recvptr)(libssh2_socket_t, void *, size_t, int, void **); + }; + union transfer { + void *sendp; + ssize_t (*sendptr)(libssh2_socket_t, const void *, size_t, int, void **); + }; + union receive sshrecv; + union transfer sshsend; + + sshrecv.recvptr = ssh_tls_recv; + sshsend.sendptr = ssh_tls_send; + + infof(data, "Uses HTTPS proxy"); + libssh2_session_callback_set(sshc->ssh_session, + LIBSSH2_CALLBACK_RECV, sshrecv.recvp); + libssh2_session_callback_set(sshc->ssh_session, + LIBSSH2_CALLBACK_SEND, sshsend.sendp); +#endif + + /* Store the underlying TLS recv/send function pointers to be used when + reading from the proxy */ + sshc->tls_recv = conn->recv[FIRSTSOCKET]; + sshc->tls_send = conn->send[FIRSTSOCKET]; + } + +#endif /* CURL_DISABLE_PROXY */ + if(conn->handler->protocol & CURLPROTO_SCP) { + conn->recv[FIRSTSOCKET] = scp_recv; + conn->send[FIRSTSOCKET] = scp_send; + } + else { + conn->recv[FIRSTSOCKET] = sftp_recv; + conn->send[FIRSTSOCKET] = sftp_send; + } + + if(data->set.ssh_compression) { +#if LIBSSH2_VERSION_NUM >= 0x010208 + if(libssh2_session_flag(sshc->ssh_session, LIBSSH2_FLAG_COMPRESS, 1) < 0) +#endif + infof(data, "Failed to enable compression for ssh session"); + } + +#ifdef HAVE_LIBSSH2_KNOWNHOST_API + if(data->set.str[STRING_SSH_KNOWNHOSTS]) { + int rc; + sshc->kh = libssh2_knownhost_init(sshc->ssh_session); + if(!sshc->kh) { + libssh2_session_free(sshc->ssh_session); + sshc->ssh_session = NULL; + return CURLE_FAILED_INIT; + } + + /* read all known hosts from there */ + rc = libssh2_knownhost_readfile(sshc->kh, + data->set.str[STRING_SSH_KNOWNHOSTS], + LIBSSH2_KNOWNHOST_FILE_OPENSSH); + if(rc < 0) + infof(data, "Failed to read known hosts from %s", + data->set.str[STRING_SSH_KNOWNHOSTS]); + } +#endif /* HAVE_LIBSSH2_KNOWNHOST_API */ + +#ifdef CURL_LIBSSH2_DEBUG + libssh2_trace(sshc->ssh_session, ~0); + infof(data, "SSH socket: %d", (int)sock); +#endif /* CURL_LIBSSH2_DEBUG */ + + state(data, SSH_INIT); + + result = ssh_multi_statemach(data, done); + + return result; +} + +/* + *********************************************************************** + * + * scp_perform() + * + * This is the actual DO function for SCP. Get a file according to + * the options previously setup. + */ + +static +CURLcode scp_perform(struct Curl_easy *data, + bool *connected, + bool *dophase_done) +{ + CURLcode result = CURLE_OK; + + DEBUGF(infof(data, "DO phase starts")); + + *dophase_done = FALSE; /* not done yet */ + + /* start the first command in the DO phase */ + state(data, SSH_SCP_TRANS_INIT); + + /* run the state-machine */ + result = ssh_multi_statemach(data, dophase_done); + + *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET); + + if(*dophase_done) { + DEBUGF(infof(data, "DO phase is complete")); + } + + return result; +} + +/* called from multi.c while DOing */ +static CURLcode scp_doing(struct Curl_easy *data, + bool *dophase_done) +{ + CURLcode result; + result = ssh_multi_statemach(data, dophase_done); + + if(*dophase_done) { + DEBUGF(infof(data, "DO phase is complete")); + } + return result; +} + +/* + * The DO function is generic for both protocols. There was previously two + * separate ones but this way means less duplicated code. + */ + +static CURLcode ssh_do(struct Curl_easy *data, bool *done) +{ + CURLcode result; + bool connected = 0; + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + + *done = FALSE; /* default to false */ + + data->req.size = -1; /* make sure this is unknown at this point */ + + sshc->actualcode = CURLE_OK; /* reset error code */ + sshc->secondCreateDirs = 0; /* reset the create dir attempt state + variable */ + + Curl_pgrsSetUploadCounter(data, 0); + Curl_pgrsSetDownloadCounter(data, 0); + Curl_pgrsSetUploadSize(data, -1); + Curl_pgrsSetDownloadSize(data, -1); + + if(conn->handler->protocol & CURLPROTO_SCP) + result = scp_perform(data, &connected, done); + else + result = sftp_perform(data, &connected, done); + + return result; +} + +/* BLOCKING, but the function is using the state machine so the only reason + this is still blocking is that the multi interface code has no support for + disconnecting operations that takes a while */ +static CURLcode scp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + CURLcode result = CURLE_OK; + struct ssh_conn *sshc = &conn->proto.sshc; + (void) dead_connection; + + if(sshc->ssh_session) { + /* only if there's a session still around to use! */ + state(data, SSH_SESSION_DISCONNECT); + result = ssh_block_statemach(data, conn, TRUE); + } + + return result; +} + +/* generic done function for both SCP and SFTP called from their specific + done functions */ +static CURLcode ssh_done(struct Curl_easy *data, CURLcode status) +{ + CURLcode result = CURLE_OK; + struct SSHPROTO *sshp = data->req.p.ssh; + struct connectdata *conn = data->conn; + + if(!status) + /* run the state-machine */ + result = ssh_block_statemach(data, conn, FALSE); + else + result = status; + + Curl_safefree(sshp->path); + Curl_safefree(sshp->readdir_filename); + Curl_safefree(sshp->readdir_longentry); + Curl_dyn_free(&sshp->readdir); + + if(Curl_pgrsDone(data)) + return CURLE_ABORTED_BY_CALLBACK; + + data->req.keepon = 0; /* clear all bits */ + return result; +} + + +static CURLcode scp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + (void)premature; /* not used */ + + if(!status) + state(data, SSH_SCP_DONE); + + return ssh_done(data, status); + +} + +static ssize_t scp_send(struct Curl_easy *data, int sockindex, + const void *mem, size_t len, CURLcode *err) +{ + ssize_t nwrite; + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + (void)sockindex; /* we only support SCP on the fixed known primary socket */ + + /* libssh2_channel_write() returns int! */ + nwrite = (ssize_t) libssh2_channel_write(sshc->ssh_channel, mem, len); + + ssh_block2waitfor(data, (nwrite == LIBSSH2_ERROR_EAGAIN)?TRUE:FALSE); + + if(nwrite == LIBSSH2_ERROR_EAGAIN) { + *err = CURLE_AGAIN; + nwrite = 0; + } + else if(nwrite < LIBSSH2_ERROR_NONE) { + *err = libssh2_session_error_to_CURLE((int)nwrite); + nwrite = -1; + } + + return nwrite; +} + +static ssize_t scp_recv(struct Curl_easy *data, int sockindex, + char *mem, size_t len, CURLcode *err) +{ + ssize_t nread; + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + (void)sockindex; /* we only support SCP on the fixed known primary socket */ + + /* libssh2_channel_read() returns int */ + nread = (ssize_t) libssh2_channel_read(sshc->ssh_channel, mem, len); + + ssh_block2waitfor(data, (nread == LIBSSH2_ERROR_EAGAIN)?TRUE:FALSE); + if(nread == LIBSSH2_ERROR_EAGAIN) { + *err = CURLE_AGAIN; + nread = -1; + } + + return nread; +} + +/* + * =============== SFTP =============== + */ + +/* + *********************************************************************** + * + * sftp_perform() + * + * This is the actual DO function for SFTP. Get a file/directory according to + * the options previously setup. + */ + +static +CURLcode sftp_perform(struct Curl_easy *data, + bool *connected, + bool *dophase_done) +{ + CURLcode result = CURLE_OK; + + DEBUGF(infof(data, "DO phase starts")); + + *dophase_done = FALSE; /* not done yet */ + + /* start the first command in the DO phase */ + state(data, SSH_SFTP_QUOTE_INIT); + + /* run the state-machine */ + result = ssh_multi_statemach(data, dophase_done); + + *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET); + + if(*dophase_done) { + DEBUGF(infof(data, "DO phase is complete")); + } + + return result; +} + +/* called from multi.c while DOing */ +static CURLcode sftp_doing(struct Curl_easy *data, + bool *dophase_done) +{ + CURLcode result = ssh_multi_statemach(data, dophase_done); + + if(*dophase_done) { + DEBUGF(infof(data, "DO phase is complete")); + } + return result; +} + +/* BLOCKING, but the function is using the state machine so the only reason + this is still blocking is that the multi interface code has no support for + disconnecting operations that takes a while */ +static CURLcode sftp_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead_connection) +{ + CURLcode result = CURLE_OK; + struct ssh_conn *sshc = &conn->proto.sshc; + (void) dead_connection; + + DEBUGF(infof(data, "SSH DISCONNECT starts now")); + + if(sshc->ssh_session) { + /* only if there's a session still around to use! */ + state(data, SSH_SFTP_SHUTDOWN); + result = ssh_block_statemach(data, conn, TRUE); + } + + DEBUGF(infof(data, "SSH DISCONNECT is done")); + + return result; + +} + +static CURLcode sftp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + + if(!status) { + /* Post quote commands are executed after the SFTP_CLOSE state to avoid + errors that could happen due to open file handles during POSTQUOTE + operation */ + if(!premature && data->set.postquote && !conn->bits.retry) + sshc->nextstate = SSH_SFTP_POSTQUOTE_INIT; + state(data, SSH_SFTP_CLOSE); + } + return ssh_done(data, status); +} + +/* return number of sent bytes */ +static ssize_t sftp_send(struct Curl_easy *data, int sockindex, + const void *mem, size_t len, CURLcode *err) +{ + ssize_t nwrite; + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + (void)sockindex; + + nwrite = libssh2_sftp_write(sshc->sftp_handle, mem, len); + + ssh_block2waitfor(data, (nwrite == LIBSSH2_ERROR_EAGAIN)?TRUE:FALSE); + + if(nwrite == LIBSSH2_ERROR_EAGAIN) { + *err = CURLE_AGAIN; + nwrite = 0; + } + else if(nwrite < LIBSSH2_ERROR_NONE) { + *err = libssh2_session_error_to_CURLE((int)nwrite); + nwrite = -1; + } + + return nwrite; +} + +/* + * Return number of received (decrypted) bytes + * or <0 on error + */ +static ssize_t sftp_recv(struct Curl_easy *data, int sockindex, + char *mem, size_t len, CURLcode *err) +{ + ssize_t nread; + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + (void)sockindex; + + nread = libssh2_sftp_read(sshc->sftp_handle, mem, len); + + ssh_block2waitfor(data, (nread == LIBSSH2_ERROR_EAGAIN)?TRUE:FALSE); + + if(nread == LIBSSH2_ERROR_EAGAIN) { + *err = CURLE_AGAIN; + nread = -1; + + } + else if(nread < 0) { + *err = libssh2_session_error_to_CURLE((int)nread); + } + return nread; +} + +static const char *sftp_libssh2_strerror(unsigned long err) +{ + switch(err) { + case LIBSSH2_FX_NO_SUCH_FILE: + return "No such file or directory"; + + case LIBSSH2_FX_PERMISSION_DENIED: + return "Permission denied"; + + case LIBSSH2_FX_FAILURE: + return "Operation failed"; + + case LIBSSH2_FX_BAD_MESSAGE: + return "Bad message from SFTP server"; + + case LIBSSH2_FX_NO_CONNECTION: + return "Not connected to SFTP server"; + + case LIBSSH2_FX_CONNECTION_LOST: + return "Connection to SFTP server lost"; + + case LIBSSH2_FX_OP_UNSUPPORTED: + return "Operation not supported by SFTP server"; + + case LIBSSH2_FX_INVALID_HANDLE: + return "Invalid handle"; + + case LIBSSH2_FX_NO_SUCH_PATH: + return "No such file or directory"; + + case LIBSSH2_FX_FILE_ALREADY_EXISTS: + return "File already exists"; + + case LIBSSH2_FX_WRITE_PROTECT: + return "File is write protected"; + + case LIBSSH2_FX_NO_MEDIA: + return "No media"; + + case LIBSSH2_FX_NO_SPACE_ON_FILESYSTEM: + return "Disk full"; + + case LIBSSH2_FX_QUOTA_EXCEEDED: + return "User quota exceeded"; + + case LIBSSH2_FX_UNKNOWN_PRINCIPLE: + return "Unknown principle"; + + case LIBSSH2_FX_LOCK_CONFlICT: + return "File lock conflict"; + + case LIBSSH2_FX_DIR_NOT_EMPTY: + return "Directory not empty"; + + case LIBSSH2_FX_NOT_A_DIRECTORY: + return "Not a directory"; + + case LIBSSH2_FX_INVALID_FILENAME: + return "Invalid filename"; + + case LIBSSH2_FX_LINK_LOOP: + return "Link points to itself"; + } + return "Unknown error in libssh2"; +} + +CURLcode Curl_ssh_init(void) +{ +#ifdef HAVE_LIBSSH2_INIT + if(libssh2_init(0)) { + DEBUGF(fprintf(stderr, "Error: libssh2_init failed\n")); + return CURLE_FAILED_INIT; + } +#endif + return CURLE_OK; +} + +void Curl_ssh_cleanup(void) +{ +#ifdef HAVE_LIBSSH2_EXIT + (void)libssh2_exit(); +#endif +} + +void Curl_ssh_version(char *buffer, size_t buflen) +{ + (void)msnprintf(buffer, buflen, "libssh2/%s", CURL_LIBSSH2_VERSION); +} + +/* The SSH session is associated with the *CONNECTION* but the callback user + * pointer is an easy handle pointer. This function allows us to reassign the + * user pointer to the *CURRENT* (new) easy handle. + */ +static void ssh_attach(struct Curl_easy *data, struct connectdata *conn) +{ + DEBUGASSERT(data); + DEBUGASSERT(conn); + if(conn->handler->protocol & PROTO_FAMILY_SSH) { + struct ssh_conn *sshc = &conn->proto.sshc; + if(sshc->ssh_session) { + /* only re-attach if the session already exists */ + void **abstract = libssh2_session_abstract(sshc->ssh_session); + *abstract = data; + } + } +} +#endif /* USE_LIBSSH2 */ diff --git a/third_party/curl/lib/vssh/ssh.h b/third_party/curl/lib/vssh/ssh.h new file mode 100644 index 0000000..ca0533a --- /dev/null +++ b/third_party/curl/lib/vssh/ssh.h @@ -0,0 +1,273 @@ +#ifndef HEADER_CURL_SSH_H +#define HEADER_CURL_SSH_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_LIBSSH2) +#include +#include +#elif defined(USE_LIBSSH) +#include +#include +#elif defined(USE_WOLFSSH) +#include +#include +#endif + +/**************************************************************************** + * SSH unique setup + ***************************************************************************/ +typedef enum { + SSH_NO_STATE = -1, /* Used for "nextState" so say there is none */ + SSH_STOP = 0, /* do nothing state, stops the state machine */ + + SSH_INIT, /* First state in SSH-CONNECT */ + SSH_S_STARTUP, /* Session startup */ + SSH_HOSTKEY, /* verify hostkey */ + SSH_AUTHLIST, + SSH_AUTH_PKEY_INIT, + SSH_AUTH_PKEY, + SSH_AUTH_PASS_INIT, + SSH_AUTH_PASS, + SSH_AUTH_AGENT_INIT, /* initialize then wait for connection to agent */ + SSH_AUTH_AGENT_LIST, /* ask for list then wait for entire list to come */ + SSH_AUTH_AGENT, /* attempt one key at a time */ + SSH_AUTH_HOST_INIT, + SSH_AUTH_HOST, + SSH_AUTH_KEY_INIT, + SSH_AUTH_KEY, + SSH_AUTH_GSSAPI, + SSH_AUTH_DONE, + SSH_SFTP_INIT, + SSH_SFTP_REALPATH, /* Last state in SSH-CONNECT */ + + SSH_SFTP_QUOTE_INIT, /* First state in SFTP-DO */ + SSH_SFTP_POSTQUOTE_INIT, /* (Possibly) First state in SFTP-DONE */ + SSH_SFTP_QUOTE, + SSH_SFTP_NEXT_QUOTE, + SSH_SFTP_QUOTE_STAT, + SSH_SFTP_QUOTE_SETSTAT, + SSH_SFTP_QUOTE_SYMLINK, + SSH_SFTP_QUOTE_MKDIR, + SSH_SFTP_QUOTE_RENAME, + SSH_SFTP_QUOTE_RMDIR, + SSH_SFTP_QUOTE_UNLINK, + SSH_SFTP_QUOTE_STATVFS, + SSH_SFTP_GETINFO, + SSH_SFTP_FILETIME, + SSH_SFTP_TRANS_INIT, + SSH_SFTP_UPLOAD_INIT, + SSH_SFTP_CREATE_DIRS_INIT, + SSH_SFTP_CREATE_DIRS, + SSH_SFTP_CREATE_DIRS_MKDIR, + SSH_SFTP_READDIR_INIT, + SSH_SFTP_READDIR, + SSH_SFTP_READDIR_LINK, + SSH_SFTP_READDIR_BOTTOM, + SSH_SFTP_READDIR_DONE, + SSH_SFTP_DOWNLOAD_INIT, + SSH_SFTP_DOWNLOAD_STAT, /* Last state in SFTP-DO */ + SSH_SFTP_CLOSE, /* Last state in SFTP-DONE */ + SSH_SFTP_SHUTDOWN, /* First state in SFTP-DISCONNECT */ + SSH_SCP_TRANS_INIT, /* First state in SCP-DO */ + SSH_SCP_UPLOAD_INIT, + SSH_SCP_DOWNLOAD_INIT, + SSH_SCP_DOWNLOAD, + SSH_SCP_DONE, + SSH_SCP_SEND_EOF, + SSH_SCP_WAIT_EOF, + SSH_SCP_WAIT_CLOSE, + SSH_SCP_CHANNEL_FREE, /* Last state in SCP-DONE */ + SSH_SESSION_DISCONNECT, /* First state in SCP-DISCONNECT */ + SSH_SESSION_FREE, /* Last state in SCP/SFTP-DISCONNECT */ + SSH_QUIT, + SSH_LAST /* never used */ +} sshstate; + +/* this struct is used in the HandleData struct which is part of the + Curl_easy, which means this is used on a per-easy handle basis. + Everything that is strictly related to a connection is banned from this + struct. */ +struct SSHPROTO { + char *path; /* the path we operate on */ +#ifdef USE_LIBSSH2 + struct dynbuf readdir_link; + struct dynbuf readdir; + char *readdir_filename; + char *readdir_longentry; + + LIBSSH2_SFTP_ATTRIBUTES quote_attrs; /* used by the SFTP_QUOTE state */ + + /* Here's a set of struct members used by the SFTP_READDIR state */ + LIBSSH2_SFTP_ATTRIBUTES readdir_attrs; +#endif +}; + +/* ssh_conn is used for struct connection-oriented data in the connectdata + struct */ +struct ssh_conn { + const char *authlist; /* List of auth. methods, managed by libssh2 */ + + /* common */ + const char *passphrase; /* pass-phrase to use */ + char *rsa_pub; /* strdup'ed public key file */ + char *rsa; /* strdup'ed private key file */ + bool authed; /* the connection has been authenticated fine */ + bool acceptfail; /* used by the SFTP_QUOTE (continue if + quote command fails) */ + sshstate state; /* always use ssh.c:state() to change state! */ + sshstate nextstate; /* the state to goto after stopping */ + CURLcode actualcode; /* the actual error code */ + struct curl_slist *quote_item; /* for the quote option */ + char *quote_path1; /* two generic pointers for the QUOTE stuff */ + char *quote_path2; + + char *homedir; /* when doing SFTP we figure out home dir in the + connect phase */ + /* end of READDIR stuff */ + + int secondCreateDirs; /* counter use by the code to see if the + second attempt has been made to change + to/create a directory */ + int orig_waitfor; /* default READ/WRITE bits wait for */ + char *slash_pos; /* used by the SFTP_CREATE_DIRS state */ + +#if defined(USE_LIBSSH) + char *readdir_linkPath; + size_t readdir_len; + struct dynbuf readdir_buf; +/* our variables */ + unsigned kbd_state; /* 0 or 1 */ + ssh_key privkey; + ssh_key pubkey; + int auth_methods; + ssh_session ssh_session; + ssh_scp scp_session; + sftp_session sftp_session; + sftp_file sftp_file; + sftp_dir sftp_dir; + + unsigned sftp_recv_state; /* 0 or 1 */ + int sftp_file_index; /* for async read */ + sftp_attributes readdir_attrs; /* used by the SFTP readdir actions */ + sftp_attributes readdir_link_attrs; /* used by the SFTP readdir actions */ + sftp_attributes quote_attrs; /* used by the SFTP_QUOTE state */ + + const char *readdir_filename; /* points within readdir_attrs */ + const char *readdir_longentry; + char *readdir_tmp; +#elif defined(USE_LIBSSH2) + LIBSSH2_SESSION *ssh_session; /* Secure Shell session */ + LIBSSH2_CHANNEL *ssh_channel; /* Secure Shell channel handle */ + LIBSSH2_SFTP *sftp_session; /* SFTP handle */ + LIBSSH2_SFTP_HANDLE *sftp_handle; + +#ifndef CURL_DISABLE_PROXY + /* for HTTPS proxy storage */ + Curl_recv *tls_recv; + Curl_send *tls_send; +#endif + +#ifdef HAVE_LIBSSH2_AGENT_API + LIBSSH2_AGENT *ssh_agent; /* proxy to ssh-agent/pageant */ + struct libssh2_agent_publickey *sshagent_identity, + *sshagent_prev_identity; +#endif + + /* note that HAVE_LIBSSH2_KNOWNHOST_API is a define set in the libssh2.h + header */ +#ifdef HAVE_LIBSSH2_KNOWNHOST_API + LIBSSH2_KNOWNHOSTS *kh; +#endif +#elif defined(USE_WOLFSSH) + WOLFSSH *ssh_session; + WOLFSSH_CTX *ctx; + word32 handleSz; + byte handle[WOLFSSH_MAX_HANDLE]; + curl_off_t offset; +#endif /* USE_LIBSSH */ +}; + +#if defined(USE_LIBSSH2) + +/* Feature detection based on version numbers to better work with + non-configure platforms */ + +#if !defined(LIBSSH2_VERSION_NUM) || (LIBSSH2_VERSION_NUM < 0x001000) +# error "SCP/SFTP protocols require libssh2 0.16 or later" +#endif + +#if LIBSSH2_VERSION_NUM >= 0x010000 +#define HAVE_LIBSSH2_SFTP_SEEK64 1 +#endif + +#if LIBSSH2_VERSION_NUM >= 0x010100 +#define HAVE_LIBSSH2_VERSION 1 +#endif + +#if LIBSSH2_VERSION_NUM >= 0x010205 +#define HAVE_LIBSSH2_INIT 1 +#define HAVE_LIBSSH2_EXIT 1 +#endif + +#if LIBSSH2_VERSION_NUM >= 0x010206 +#define HAVE_LIBSSH2_KNOWNHOST_CHECKP 1 +#define HAVE_LIBSSH2_SCP_SEND64 1 +#endif + +#if LIBSSH2_VERSION_NUM >= 0x010208 +#define HAVE_LIBSSH2_SESSION_HANDSHAKE 1 +#endif + +#ifdef HAVE_LIBSSH2_VERSION +/* get it run-time if possible */ +#define CURL_LIBSSH2_VERSION libssh2_version(0) +#else +/* use build-time if run-time not possible */ +#define CURL_LIBSSH2_VERSION LIBSSH2_VERSION +#endif + +#endif /* USE_LIBSSH2 */ + +#ifdef USE_SSH + +extern const struct Curl_handler Curl_handler_scp; +extern const struct Curl_handler Curl_handler_sftp; + +/* generic SSH backend functions */ +CURLcode Curl_ssh_init(void); +void Curl_ssh_cleanup(void); +void Curl_ssh_version(char *buffer, size_t buflen); +void Curl_ssh_attach(struct Curl_easy *data, + struct connectdata *conn); +#else +/* for non-SSH builds */ +#define Curl_ssh_cleanup() +#define Curl_ssh_attach(x,y) +#define Curl_ssh_init() 0 +#endif + +#endif /* HEADER_CURL_SSH_H */ diff --git a/third_party/curl/lib/vssh/wolfssh.c b/third_party/curl/lib/vssh/wolfssh.c new file mode 100644 index 0000000..6a5aed8 --- /dev/null +++ b/third_party/curl/lib/vssh/wolfssh.c @@ -0,0 +1,1169 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_WOLFSSH + +#include + +#include +#include +#include "urldata.h" +#include "cfilters.h" +#include "connect.h" +#include "sendf.h" +#include "progress.h" +#include "curl_path.h" +#include "strtoofft.h" +#include "transfer.h" +#include "speedcheck.h" +#include "select.h" +#include "multiif.h" +#include "warnless.h" +#include "strdup.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +static CURLcode wssh_connect(struct Curl_easy *data, bool *done); +static CURLcode wssh_multi_statemach(struct Curl_easy *data, bool *done); +static CURLcode wssh_do(struct Curl_easy *data, bool *done); +#if 0 +static CURLcode wscp_done(struct Curl_easy *data, + CURLcode, bool premature); +static CURLcode wscp_doing(struct Curl_easy *data, + bool *dophase_done); +static CURLcode wscp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection); +#endif +static CURLcode wsftp_done(struct Curl_easy *data, + CURLcode, bool premature); +static CURLcode wsftp_doing(struct Curl_easy *data, + bool *dophase_done); +static CURLcode wsftp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead); +static int wssh_getsock(struct Curl_easy *data, + struct connectdata *conn, + curl_socket_t *sock); +static CURLcode wssh_setup_connection(struct Curl_easy *data, + struct connectdata *conn); + +#if 0 +/* + * SCP protocol handler. + */ + +const struct Curl_handler Curl_handler_scp = { + "SCP", /* scheme */ + wssh_setup_connection, /* setup_connection */ + wssh_do, /* do_it */ + wscp_done, /* done */ + ZERO_NULL, /* do_more */ + wssh_connect, /* connect_it */ + wssh_multi_statemach, /* connecting */ + wscp_doing, /* doing */ + wssh_getsock, /* proto_getsock */ + wssh_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + wssh_getsock, /* perform_getsock */ + wscp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_SSH, /* defport */ + CURLPROTO_SCP, /* protocol */ + PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION + | PROTOPT_NOURLQUERY /* flags */ +}; + +#endif + +/* + * SFTP protocol handler. + */ + +const struct Curl_handler Curl_handler_sftp = { + "SFTP", /* scheme */ + wssh_setup_connection, /* setup_connection */ + wssh_do, /* do_it */ + wsftp_done, /* done */ + ZERO_NULL, /* do_more */ + wssh_connect, /* connect_it */ + wssh_multi_statemach, /* connecting */ + wsftp_doing, /* doing */ + wssh_getsock, /* proto_getsock */ + wssh_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + wssh_getsock, /* perform_getsock */ + wsftp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_SSH, /* defport */ + CURLPROTO_SFTP, /* protocol */ + CURLPROTO_SFTP, /* family */ + PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION + | PROTOPT_NOURLQUERY /* flags */ +}; + +/* + * SSH State machine related code + */ +/* This is the ONLY way to change SSH state! */ +static void state(struct Curl_easy *data, sshstate nowstate) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + /* for debug purposes */ + static const char * const names[] = { + "SSH_STOP", + "SSH_INIT", + "SSH_S_STARTUP", + "SSH_HOSTKEY", + "SSH_AUTHLIST", + "SSH_AUTH_PKEY_INIT", + "SSH_AUTH_PKEY", + "SSH_AUTH_PASS_INIT", + "SSH_AUTH_PASS", + "SSH_AUTH_AGENT_INIT", + "SSH_AUTH_AGENT_LIST", + "SSH_AUTH_AGENT", + "SSH_AUTH_HOST_INIT", + "SSH_AUTH_HOST", + "SSH_AUTH_KEY_INIT", + "SSH_AUTH_KEY", + "SSH_AUTH_GSSAPI", + "SSH_AUTH_DONE", + "SSH_SFTP_INIT", + "SSH_SFTP_REALPATH", + "SSH_SFTP_QUOTE_INIT", + "SSH_SFTP_POSTQUOTE_INIT", + "SSH_SFTP_QUOTE", + "SSH_SFTP_NEXT_QUOTE", + "SSH_SFTP_QUOTE_STAT", + "SSH_SFTP_QUOTE_SETSTAT", + "SSH_SFTP_QUOTE_SYMLINK", + "SSH_SFTP_QUOTE_MKDIR", + "SSH_SFTP_QUOTE_RENAME", + "SSH_SFTP_QUOTE_RMDIR", + "SSH_SFTP_QUOTE_UNLINK", + "SSH_SFTP_QUOTE_STATVFS", + "SSH_SFTP_GETINFO", + "SSH_SFTP_FILETIME", + "SSH_SFTP_TRANS_INIT", + "SSH_SFTP_UPLOAD_INIT", + "SSH_SFTP_CREATE_DIRS_INIT", + "SSH_SFTP_CREATE_DIRS", + "SSH_SFTP_CREATE_DIRS_MKDIR", + "SSH_SFTP_READDIR_INIT", + "SSH_SFTP_READDIR", + "SSH_SFTP_READDIR_LINK", + "SSH_SFTP_READDIR_BOTTOM", + "SSH_SFTP_READDIR_DONE", + "SSH_SFTP_DOWNLOAD_INIT", + "SSH_SFTP_DOWNLOAD_STAT", + "SSH_SFTP_CLOSE", + "SSH_SFTP_SHUTDOWN", + "SSH_SCP_TRANS_INIT", + "SSH_SCP_UPLOAD_INIT", + "SSH_SCP_DOWNLOAD_INIT", + "SSH_SCP_DOWNLOAD", + "SSH_SCP_DONE", + "SSH_SCP_SEND_EOF", + "SSH_SCP_WAIT_EOF", + "SSH_SCP_WAIT_CLOSE", + "SSH_SCP_CHANNEL_FREE", + "SSH_SESSION_DISCONNECT", + "SSH_SESSION_FREE", + "QUIT" + }; + + /* a precaution to make sure the lists are in sync */ + DEBUGASSERT(sizeof(names)/sizeof(names[0]) == SSH_LAST); + + if(sshc->state != nowstate) { + infof(data, "wolfssh %p state change from %s to %s", + (void *)sshc, names[sshc->state], names[nowstate]); + } +#endif + + sshc->state = nowstate; +} + +static ssize_t wscp_send(struct Curl_easy *data, int sockindex, + const void *mem, size_t len, CURLcode *err) +{ + ssize_t nwrite = 0; + (void)data; + (void)sockindex; /* we only support SCP on the fixed known primary socket */ + (void)mem; + (void)len; + (void)err; + + return nwrite; +} + +static ssize_t wscp_recv(struct Curl_easy *data, int sockindex, + char *mem, size_t len, CURLcode *err) +{ + ssize_t nread = 0; + (void)data; + (void)sockindex; /* we only support SCP on the fixed known primary socket */ + (void)mem; + (void)len; + (void)err; + + return nread; +} + +/* return number of sent bytes */ +static ssize_t wsftp_send(struct Curl_easy *data, int sockindex, + const void *mem, size_t len, CURLcode *err) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + word32 offset[2]; + int rc; + (void)sockindex; + + offset[0] = (word32)sshc->offset&0xFFFFFFFF; + offset[1] = (word32)(sshc->offset>>32)&0xFFFFFFFF; + + rc = wolfSSH_SFTP_SendWritePacket(sshc->ssh_session, sshc->handle, + sshc->handleSz, + &offset[0], + (byte *)mem, (word32)len); + + if(rc == WS_FATAL_ERROR) + rc = wolfSSH_get_error(sshc->ssh_session); + if(rc == WS_WANT_READ) { + conn->waitfor = KEEP_RECV; + *err = CURLE_AGAIN; + return -1; + } + else if(rc == WS_WANT_WRITE) { + conn->waitfor = KEEP_SEND; + *err = CURLE_AGAIN; + return -1; + } + if(rc < 0) { + failf(data, "wolfSSH_SFTP_SendWritePacket returned %d", rc); + return -1; + } + DEBUGASSERT(rc == (int)len); + infof(data, "sent %zu bytes SFTP from offset %" CURL_FORMAT_CURL_OFF_T, + len, sshc->offset); + sshc->offset += len; + return (ssize_t)rc; +} + +/* + * Return number of received (decrypted) bytes + * or <0 on error + */ +static ssize_t wsftp_recv(struct Curl_easy *data, int sockindex, + char *mem, size_t len, CURLcode *err) +{ + int rc; + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + word32 offset[2]; + (void)sockindex; + + offset[0] = (word32)sshc->offset&0xFFFFFFFF; + offset[1] = (word32)(sshc->offset>>32)&0xFFFFFFFF; + + rc = wolfSSH_SFTP_SendReadPacket(sshc->ssh_session, sshc->handle, + sshc->handleSz, + &offset[0], + (byte *)mem, (word32)len); + if(rc == WS_FATAL_ERROR) + rc = wolfSSH_get_error(sshc->ssh_session); + if(rc == WS_WANT_READ) { + conn->waitfor = KEEP_RECV; + *err = CURLE_AGAIN; + return -1; + } + else if(rc == WS_WANT_WRITE) { + conn->waitfor = KEEP_SEND; + *err = CURLE_AGAIN; + return -1; + } + + DEBUGASSERT(rc <= (int)len); + + if(rc < 0) { + failf(data, "wolfSSH_SFTP_SendReadPacket returned %d", rc); + return -1; + } + sshc->offset += len; + + return (ssize_t)rc; +} + +/* + * SSH setup and connection + */ +static CURLcode wssh_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + struct SSHPROTO *ssh; + (void)conn; + + data->req.p.ssh = ssh = calloc(1, sizeof(struct SSHPROTO)); + if(!ssh) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +static int userauth(byte authtype, + WS_UserAuthData* authdata, + void *ctx) +{ + struct Curl_easy *data = ctx; + DEBUGF(infof(data, "wolfssh callback: type %s", + authtype == WOLFSSH_USERAUTH_PASSWORD ? "PASSWORD" : + "PUBLICCKEY")); + if(authtype == WOLFSSH_USERAUTH_PASSWORD) { + authdata->sf.password.password = (byte *)data->conn->passwd; + authdata->sf.password.passwordSz = (word32) strlen(data->conn->passwd); + } + + return 0; +} + +static CURLcode wssh_connect(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc; + curl_socket_t sock = conn->sock[FIRSTSOCKET]; + int rc; + + /* initialize per-handle data if not already */ + if(!data->req.p.ssh) + wssh_setup_connection(data, conn); + + /* We default to persistent connections. We set this already in this connect + function to make the reuse checks properly be able to check this bit. */ + connkeep(conn, "SSH default"); + + if(conn->handler->protocol & CURLPROTO_SCP) { + conn->recv[FIRSTSOCKET] = wscp_recv; + conn->send[FIRSTSOCKET] = wscp_send; + } + else { + conn->recv[FIRSTSOCKET] = wsftp_recv; + conn->send[FIRSTSOCKET] = wsftp_send; + } + sshc = &conn->proto.sshc; + sshc->ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL); + if(!sshc->ctx) { + failf(data, "No wolfSSH context"); + goto error; + } + + sshc->ssh_session = wolfSSH_new(sshc->ctx); + if(!sshc->ssh_session) { + failf(data, "No wolfSSH session"); + goto error; + } + + rc = wolfSSH_SetUsername(sshc->ssh_session, conn->user); + if(rc != WS_SUCCESS) { + failf(data, "wolfSSH failed to set user name"); + goto error; + } + + /* set callback for authentication */ + wolfSSH_SetUserAuth(sshc->ctx, userauth); + wolfSSH_SetUserAuthCtx(sshc->ssh_session, data); + + rc = wolfSSH_set_fd(sshc->ssh_session, (int)sock); + if(rc) { + failf(data, "wolfSSH failed to set socket"); + goto error; + } + +#if 0 + wolfSSH_Debugging_ON(); +#endif + + *done = TRUE; + if(conn->handler->protocol & CURLPROTO_SCP) + state(data, SSH_INIT); + else + state(data, SSH_SFTP_INIT); + + return wssh_multi_statemach(data, done); +error: + wolfSSH_free(sshc->ssh_session); + wolfSSH_CTX_free(sshc->ctx); + return CURLE_FAILED_INIT; +} + +/* + * wssh_statemach_act() runs the SSH state machine as far as it can without + * blocking and without reaching the end. The data the pointer 'block' points + * to will be set to TRUE if the wolfssh function returns EAGAIN meaning it + * wants to be called again when the socket is ready + */ + +static CURLcode wssh_statemach_act(struct Curl_easy *data, bool *block) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + struct SSHPROTO *sftp_scp = data->req.p.ssh; + WS_SFTPNAME *name; + int rc = 0; + *block = FALSE; /* we're not blocking by default */ + + do { + switch(sshc->state) { + case SSH_INIT: + state(data, SSH_S_STARTUP); + break; + + case SSH_S_STARTUP: + rc = wolfSSH_connect(sshc->ssh_session); + if(rc != WS_SUCCESS) + rc = wolfSSH_get_error(sshc->ssh_session); + if(rc == WS_WANT_READ) { + *block = TRUE; + conn->waitfor = KEEP_RECV; + return CURLE_OK; + } + else if(rc == WS_WANT_WRITE) { + *block = TRUE; + conn->waitfor = KEEP_SEND; + return CURLE_OK; + } + else if(rc != WS_SUCCESS) { + state(data, SSH_STOP); + return CURLE_SSH; + } + infof(data, "wolfssh connected"); + state(data, SSH_STOP); + break; + case SSH_STOP: + break; + + case SSH_SFTP_INIT: + rc = wolfSSH_SFTP_connect(sshc->ssh_session); + if(rc != WS_SUCCESS) + rc = wolfSSH_get_error(sshc->ssh_session); + if(rc == WS_WANT_READ) { + *block = TRUE; + conn->waitfor = KEEP_RECV; + return CURLE_OK; + } + else if(rc == WS_WANT_WRITE) { + *block = TRUE; + conn->waitfor = KEEP_SEND; + return CURLE_OK; + } + else if(rc == WS_SUCCESS) { + infof(data, "wolfssh SFTP connected"); + state(data, SSH_SFTP_REALPATH); + } + else { + failf(data, "wolfssh SFTP connect error %d", rc); + return CURLE_SSH; + } + break; + case SSH_SFTP_REALPATH: + name = wolfSSH_SFTP_RealPath(sshc->ssh_session, (char *)"."); + rc = wolfSSH_get_error(sshc->ssh_session); + if(rc == WS_WANT_READ) { + *block = TRUE; + conn->waitfor = KEEP_RECV; + return CURLE_OK; + } + else if(rc == WS_WANT_WRITE) { + *block = TRUE; + conn->waitfor = KEEP_SEND; + return CURLE_OK; + } + else if(name && (rc == WS_SUCCESS)) { + sshc->homedir = Curl_memdup0(name->fName, name->fSz); + if(!sshc->homedir) + sshc->actualcode = CURLE_OUT_OF_MEMORY; + wolfSSH_SFTPNAME_list_free(name); + state(data, SSH_STOP); + return CURLE_OK; + } + failf(data, "wolfssh SFTP realpath %d", rc); + return CURLE_SSH; + + case SSH_SFTP_QUOTE_INIT: + result = Curl_getworkingpath(data, sshc->homedir, &sftp_scp->path); + if(result) { + sshc->actualcode = result; + state(data, SSH_STOP); + break; + } + + if(data->set.quote) { + infof(data, "Sending quote commands"); + sshc->quote_item = data->set.quote; + state(data, SSH_SFTP_QUOTE); + } + else { + state(data, SSH_SFTP_GETINFO); + } + break; + case SSH_SFTP_GETINFO: + if(data->set.get_filetime) { + state(data, SSH_SFTP_FILETIME); + } + else { + state(data, SSH_SFTP_TRANS_INIT); + } + break; + case SSH_SFTP_TRANS_INIT: + if(data->state.upload) + state(data, SSH_SFTP_UPLOAD_INIT); + else { + if(sftp_scp->path[strlen(sftp_scp->path)-1] == '/') + state(data, SSH_SFTP_READDIR_INIT); + else + state(data, SSH_SFTP_DOWNLOAD_INIT); + } + break; + case SSH_SFTP_UPLOAD_INIT: { + word32 flags; + WS_SFTP_FILEATRB createattrs; + if(data->state.resume_from) { + WS_SFTP_FILEATRB attrs; + if(data->state.resume_from < 0) { + rc = wolfSSH_SFTP_STAT(sshc->ssh_session, sftp_scp->path, + &attrs); + if(rc != WS_SUCCESS) + break; + + if(rc) { + data->state.resume_from = 0; + } + else { + curl_off_t size = ((curl_off_t)attrs.sz[1] << 32) | attrs.sz[0]; + if(size < 0) { + failf(data, "Bad file size (%" CURL_FORMAT_CURL_OFF_T ")", size); + return CURLE_BAD_DOWNLOAD_RESUME; + } + data->state.resume_from = size; + } + } + } + + if(data->set.remote_append) + /* Try to open for append, but create if nonexisting */ + flags = WOLFSSH_FXF_WRITE|WOLFSSH_FXF_CREAT|WOLFSSH_FXF_APPEND; + else if(data->state.resume_from > 0) + /* If we have restart position then open for append */ + flags = WOLFSSH_FXF_WRITE|WOLFSSH_FXF_APPEND; + else + /* Clear file before writing (normal behavior) */ + flags = WOLFSSH_FXF_WRITE|WOLFSSH_FXF_CREAT|WOLFSSH_FXF_TRUNC; + + memset(&createattrs, 0, sizeof(createattrs)); + createattrs.per = (word32)data->set.new_file_perms; + sshc->handleSz = sizeof(sshc->handle); + rc = wolfSSH_SFTP_Open(sshc->ssh_session, sftp_scp->path, + flags, &createattrs, + sshc->handle, &sshc->handleSz); + if(rc == WS_FATAL_ERROR) + rc = wolfSSH_get_error(sshc->ssh_session); + if(rc == WS_WANT_READ) { + *block = TRUE; + conn->waitfor = KEEP_RECV; + return CURLE_OK; + } + else if(rc == WS_WANT_WRITE) { + *block = TRUE; + conn->waitfor = KEEP_SEND; + return CURLE_OK; + } + else if(rc == WS_SUCCESS) { + infof(data, "wolfssh SFTP open succeeded"); + } + else { + failf(data, "wolfssh SFTP upload open failed: %d", rc); + return CURLE_SSH; + } + state(data, SSH_SFTP_DOWNLOAD_STAT); + + /* If we have a restart point then we need to seek to the correct + position. */ + if(data->state.resume_from > 0) { + /* Let's read off the proper amount of bytes from the input. */ + int seekerr = CURL_SEEKFUNC_OK; + if(data->set.seek_func) { + Curl_set_in_callback(data, true); + seekerr = data->set.seek_func(data->set.seek_client, + data->state.resume_from, SEEK_SET); + Curl_set_in_callback(data, false); + } + + if(seekerr != CURL_SEEKFUNC_OK) { + curl_off_t passed = 0; + + if(seekerr != CURL_SEEKFUNC_CANTSEEK) { + failf(data, "Could not seek stream"); + return CURLE_FTP_COULDNT_USE_REST; + } + /* seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */ + do { + char scratch[4*1024]; + size_t readthisamountnow = + (data->state.resume_from - passed > + (curl_off_t)sizeof(scratch)) ? + sizeof(scratch) : curlx_sotouz(data->state.resume_from - passed); + + size_t actuallyread; + Curl_set_in_callback(data, true); + actuallyread = data->state.fread_func(scratch, 1, + readthisamountnow, + data->state.in); + Curl_set_in_callback(data, false); + + passed += actuallyread; + if((actuallyread == 0) || (actuallyread > readthisamountnow)) { + /* this checks for greater-than only to make sure that the + CURL_READFUNC_ABORT return code still aborts */ + failf(data, "Failed to read data"); + return CURLE_FTP_COULDNT_USE_REST; + } + } while(passed < data->state.resume_from); + } + + /* now, decrease the size of the read */ + if(data->state.infilesize > 0) { + data->state.infilesize -= data->state.resume_from; + data->req.size = data->state.infilesize; + Curl_pgrsSetUploadSize(data, data->state.infilesize); + } + + sshc->offset += data->state.resume_from; + } + if(data->state.infilesize > 0) { + data->req.size = data->state.infilesize; + Curl_pgrsSetUploadSize(data, data->state.infilesize); + } + /* upload data */ + Curl_xfer_setup(data, -1, -1, FALSE, FIRSTSOCKET); + + /* not set by Curl_xfer_setup to preserve keepon bits */ + conn->sockfd = conn->writesockfd; + + if(result) { + state(data, SSH_SFTP_CLOSE); + sshc->actualcode = result; + } + else { + /* store this original bitmask setup to use later on if we can't + figure out a "real" bitmask */ + sshc->orig_waitfor = data->req.keepon; + + /* we want to use the _sending_ function even when the socket turns + out readable as the underlying libssh2 sftp send function will deal + with both accordingly */ + data->state.select_bits = CURL_CSELECT_OUT; + + /* since we don't really wait for anything at this point, we want the + state machine to move on as soon as possible so we set a very short + timeout here */ + Curl_expire(data, 0, EXPIRE_RUN_NOW); + + state(data, SSH_STOP); + } + break; + } + case SSH_SFTP_DOWNLOAD_INIT: + sshc->handleSz = sizeof(sshc->handle); + rc = wolfSSH_SFTP_Open(sshc->ssh_session, sftp_scp->path, + WOLFSSH_FXF_READ, NULL, + sshc->handle, &sshc->handleSz); + if(rc == WS_FATAL_ERROR) + rc = wolfSSH_get_error(sshc->ssh_session); + if(rc == WS_WANT_READ) { + *block = TRUE; + conn->waitfor = KEEP_RECV; + return CURLE_OK; + } + else if(rc == WS_WANT_WRITE) { + *block = TRUE; + conn->waitfor = KEEP_SEND; + return CURLE_OK; + } + else if(rc == WS_SUCCESS) { + infof(data, "wolfssh SFTP open succeeded"); + state(data, SSH_SFTP_DOWNLOAD_STAT); + return CURLE_OK; + } + + failf(data, "wolfssh SFTP open failed: %d", rc); + return CURLE_SSH; + + case SSH_SFTP_DOWNLOAD_STAT: { + WS_SFTP_FILEATRB attrs; + curl_off_t size; + + rc = wolfSSH_SFTP_STAT(sshc->ssh_session, sftp_scp->path, &attrs); + if(rc == WS_FATAL_ERROR) + rc = wolfSSH_get_error(sshc->ssh_session); + if(rc == WS_WANT_READ) { + *block = TRUE; + conn->waitfor = KEEP_RECV; + return CURLE_OK; + } + else if(rc == WS_WANT_WRITE) { + *block = TRUE; + conn->waitfor = KEEP_SEND; + return CURLE_OK; + } + else if(rc == WS_SUCCESS) { + infof(data, "wolfssh STAT succeeded"); + } + else { + failf(data, "wolfssh SFTP open failed: %d", rc); + data->req.size = -1; + data->req.maxdownload = -1; + Curl_pgrsSetDownloadSize(data, -1); + return CURLE_SSH; + } + + size = ((curl_off_t)attrs.sz[1] <<32) | attrs.sz[0]; + + data->req.size = size; + data->req.maxdownload = size; + Curl_pgrsSetDownloadSize(data, size); + + infof(data, "SFTP download %" CURL_FORMAT_CURL_OFF_T " bytes", size); + + /* We cannot seek with wolfSSH so resuming and range requests are not + possible */ + if(data->state.use_range || data->state.resume_from) { + infof(data, "wolfSSH cannot do range/seek on SFTP"); + return CURLE_BAD_DOWNLOAD_RESUME; + } + + /* Setup the actual download */ + if(data->req.size == 0) { + /* no data to transfer */ + Curl_xfer_setup(data, -1, -1, FALSE, -1); + infof(data, "File already completely downloaded"); + state(data, SSH_STOP); + break; + } + Curl_xfer_setup(data, FIRSTSOCKET, data->req.size, FALSE, -1); + + /* not set by Curl_xfer_setup to preserve keepon bits */ + conn->writesockfd = conn->sockfd; + + /* we want to use the _receiving_ function even when the socket turns + out writableable as the underlying libssh2 recv function will deal + with both accordingly */ + data->state.select_bits = CURL_CSELECT_IN; + + if(result) { + /* this should never occur; the close state should be entered + at the time the error occurs */ + state(data, SSH_SFTP_CLOSE); + sshc->actualcode = result; + } + else { + state(data, SSH_STOP); + } + break; + } + case SSH_SFTP_CLOSE: + if(sshc->handleSz) + rc = wolfSSH_SFTP_Close(sshc->ssh_session, sshc->handle, + sshc->handleSz); + else + rc = WS_SUCCESS; /* directory listing */ + if(rc == WS_WANT_READ) { + *block = TRUE; + conn->waitfor = KEEP_RECV; + return CURLE_OK; + } + else if(rc == WS_WANT_WRITE) { + *block = TRUE; + conn->waitfor = KEEP_SEND; + return CURLE_OK; + } + else if(rc == WS_SUCCESS) { + state(data, SSH_STOP); + return CURLE_OK; + } + + failf(data, "wolfssh SFTP CLOSE failed: %d", rc); + return CURLE_SSH; + + case SSH_SFTP_READDIR_INIT: + Curl_pgrsSetDownloadSize(data, -1); + if(data->req.no_body) { + state(data, SSH_STOP); + break; + } + state(data, SSH_SFTP_READDIR); + break; + + case SSH_SFTP_READDIR: + name = wolfSSH_SFTP_LS(sshc->ssh_session, sftp_scp->path); + if(!name) + rc = wolfSSH_get_error(sshc->ssh_session); + else + rc = WS_SUCCESS; + + if(rc == WS_WANT_READ) { + *block = TRUE; + conn->waitfor = KEEP_RECV; + return CURLE_OK; + } + else if(rc == WS_WANT_WRITE) { + *block = TRUE; + conn->waitfor = KEEP_SEND; + return CURLE_OK; + } + else if(name && (rc == WS_SUCCESS)) { + WS_SFTPNAME *origname = name; + result = CURLE_OK; + while(name) { + char *line = aprintf("%s\n", + data->set.list_only ? + name->fName : name->lName); + if(!line) { + state(data, SSH_SFTP_CLOSE); + sshc->actualcode = CURLE_OUT_OF_MEMORY; + break; + } + result = Curl_client_write(data, CLIENTWRITE_BODY, + line, strlen(line)); + free(line); + if(result) { + sshc->actualcode = result; + break; + } + name = name->next; + } + wolfSSH_SFTPNAME_list_free(origname); + state(data, SSH_STOP); + return result; + } + failf(data, "wolfssh SFTP ls failed: %d", rc); + return CURLE_SSH; + + case SSH_SFTP_SHUTDOWN: + Curl_safefree(sshc->homedir); + wolfSSH_free(sshc->ssh_session); + wolfSSH_CTX_free(sshc->ctx); + state(data, SSH_STOP); + return CURLE_OK; + default: + break; + } + } while(!rc && (sshc->state != SSH_STOP)); + return result; +} + +/* called repeatedly until done from multi.c */ +static CURLcode wssh_multi_statemach(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + CURLcode result = CURLE_OK; + bool block; /* we store the status and use that to provide a ssh_getsock() + implementation */ + do { + result = wssh_statemach_act(data, &block); + *done = (sshc->state == SSH_STOP) ? TRUE : FALSE; + /* if there's no error, it isn't done and it didn't EWOULDBLOCK, then + try again */ + if(*done) { + DEBUGF(infof(data, "wssh_statemach_act says DONE")); + } + } while(!result && !*done && !block); + + return result; +} + +static +CURLcode wscp_perform(struct Curl_easy *data, + bool *connected, + bool *dophase_done) +{ + (void)data; + (void)connected; + (void)dophase_done; + return CURLE_OK; +} + +static +CURLcode wsftp_perform(struct Curl_easy *data, + bool *connected, + bool *dophase_done) +{ + CURLcode result = CURLE_OK; + + DEBUGF(infof(data, "DO phase starts")); + + *dophase_done = FALSE; /* not done yet */ + + /* start the first command in the DO phase */ + state(data, SSH_SFTP_QUOTE_INIT); + + /* run the state-machine */ + result = wssh_multi_statemach(data, dophase_done); + + *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET); + + if(*dophase_done) { + DEBUGF(infof(data, "DO phase is complete")); + } + + return result; +} + +/* + * The DO function is generic for both protocols. + */ +static CURLcode wssh_do(struct Curl_easy *data, bool *done) +{ + CURLcode result; + bool connected = 0; + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + + *done = FALSE; /* default to false */ + data->req.size = -1; /* make sure this is unknown at this point */ + sshc->actualcode = CURLE_OK; /* reset error code */ + sshc->secondCreateDirs = 0; /* reset the create dir attempt state + variable */ + + Curl_pgrsSetUploadCounter(data, 0); + Curl_pgrsSetDownloadCounter(data, 0); + Curl_pgrsSetUploadSize(data, -1); + Curl_pgrsSetDownloadSize(data, -1); + + if(conn->handler->protocol & CURLPROTO_SCP) + result = wscp_perform(data, &connected, done); + else + result = wsftp_perform(data, &connected, done); + + return result; +} + +static CURLcode wssh_block_statemach(struct Curl_easy *data, + bool disconnect) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + CURLcode result = CURLE_OK; + + while((sshc->state != SSH_STOP) && !result) { + bool block; + timediff_t left = 1000; + struct curltime now = Curl_now(); + + result = wssh_statemach_act(data, &block); + if(result) + break; + + if(!disconnect) { + if(Curl_pgrsUpdate(data)) + return CURLE_ABORTED_BY_CALLBACK; + + result = Curl_speedcheck(data, now); + if(result) + break; + + left = Curl_timeleft(data, NULL, FALSE); + if(left < 0) { + failf(data, "Operation timed out"); + return CURLE_OPERATION_TIMEDOUT; + } + } + + if(!result) { + int dir = conn->waitfor; + curl_socket_t sock = conn->sock[FIRSTSOCKET]; + curl_socket_t fd_read = CURL_SOCKET_BAD; + curl_socket_t fd_write = CURL_SOCKET_BAD; + if(dir == KEEP_RECV) + fd_read = sock; + else if(dir == KEEP_SEND) + fd_write = sock; + + /* wait for the socket to become ready */ + (void)Curl_socket_check(fd_read, CURL_SOCKET_BAD, fd_write, + left>1000?1000:left); /* ignore result */ + } + } + + return result; +} + +/* generic done function for both SCP and SFTP called from their specific + done functions */ +static CURLcode wssh_done(struct Curl_easy *data, CURLcode status) +{ + CURLcode result = CURLE_OK; + struct SSHPROTO *sftp_scp = data->req.p.ssh; + + if(!status) { + /* run the state-machine */ + result = wssh_block_statemach(data, FALSE); + } + else + result = status; + + if(sftp_scp) + Curl_safefree(sftp_scp->path); + if(Curl_pgrsDone(data)) + return CURLE_ABORTED_BY_CALLBACK; + + data->req.keepon = 0; /* clear all bits */ + return result; +} + +#if 0 +static CURLcode wscp_done(struct Curl_easy *data, + CURLcode code, bool premature) +{ + CURLcode result = CURLE_OK; + (void)conn; + (void)code; + (void)premature; + + return result; +} + +static CURLcode wscp_doing(struct Curl_easy *data, + bool *dophase_done) +{ + CURLcode result = CURLE_OK; + (void)conn; + (void)dophase_done; + + return result; +} + +static CURLcode wscp_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead_connection) +{ + CURLcode result = CURLE_OK; + (void)data; + (void)conn; + (void)dead_connection; + + return result; +} +#endif + +static CURLcode wsftp_done(struct Curl_easy *data, + CURLcode code, bool premature) +{ + (void)premature; + state(data, SSH_SFTP_CLOSE); + + return wssh_done(data, code); +} + +static CURLcode wsftp_doing(struct Curl_easy *data, + bool *dophase_done) +{ + CURLcode result = wssh_multi_statemach(data, dophase_done); + + if(*dophase_done) { + DEBUGF(infof(data, "DO phase is complete")); + } + return result; +} + +static CURLcode wsftp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead) +{ + CURLcode result = CURLE_OK; + (void)dead; + + DEBUGF(infof(data, "SSH DISCONNECT starts now")); + + if(conn->proto.sshc.ssh_session) { + /* only if there's a session still around to use! */ + state(data, SSH_SFTP_SHUTDOWN); + result = wssh_block_statemach(data, TRUE); + } + + DEBUGF(infof(data, "SSH DISCONNECT is done")); + return result; +} + +static int wssh_getsock(struct Curl_easy *data, + struct connectdata *conn, + curl_socket_t *sock) +{ + int bitmap = GETSOCK_BLANK; + int dir = conn->waitfor; + (void)data; + sock[0] = conn->sock[FIRSTSOCKET]; + + if(dir == KEEP_RECV) + bitmap |= GETSOCK_READSOCK(FIRSTSOCKET); + else if(dir == KEEP_SEND) + bitmap |= GETSOCK_WRITESOCK(FIRSTSOCKET); + + return bitmap; +} + +void Curl_ssh_version(char *buffer, size_t buflen) +{ + (void)msnprintf(buffer, buflen, "wolfssh/%s", LIBWOLFSSH_VERSION_STRING); +} + +CURLcode Curl_ssh_init(void) +{ + if(WS_SUCCESS != wolfSSH_Init()) { + DEBUGF(fprintf(stderr, "Error: wolfSSH_Init failed\n")); + return CURLE_FAILED_INIT; + } + + return CURLE_OK; +} +void Curl_ssh_cleanup(void) +{ + (void)wolfSSH_Cleanup(); +} + +#endif /* USE_WOLFSSH */ diff --git a/third_party/curl/lib/vtls/bearssl.c b/third_party/curl/lib/vtls/bearssl.c new file mode 100644 index 0000000..a595f54 --- /dev/null +++ b/third_party/curl/lib/vtls/bearssl.c @@ -0,0 +1,1138 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Michael Forney, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_BEARSSL + +#include + +#include "bearssl.h" +#include "cipher_suite.h" +#include "urldata.h" +#include "sendf.h" +#include "inet_pton.h" +#include "vtls.h" +#include "vtls_int.h" +#include "connect.h" +#include "select.h" +#include "multiif.h" +#include "curl_printf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +struct x509_context { + const br_x509_class *vtable; + br_x509_minimal_context minimal; + br_x509_decoder_context decoder; + bool verifyhost; + bool verifypeer; + int cert_num; +}; + +struct bearssl_ssl_backend_data { + br_ssl_client_context ctx; + struct x509_context x509; + unsigned char buf[BR_SSL_BUFSIZE_BIDI]; + br_x509_trust_anchor *anchors; + size_t anchors_len; + const char *protocols[ALPN_ENTRIES_MAX]; + /* SSL client context is active */ + bool active; + /* size of pending write, yet to be flushed */ + size_t pending_write; +}; + +struct cafile_parser { + CURLcode err; + bool in_cert; + br_x509_decoder_context xc; + /* array of trust anchors loaded from CAfile */ + br_x509_trust_anchor *anchors; + size_t anchors_len; + /* buffer for DN data */ + unsigned char dn[1024]; + size_t dn_len; +}; + +#define CAFILE_SOURCE_PATH 1 +#define CAFILE_SOURCE_BLOB 2 +struct cafile_source { + int type; + const char *data; + size_t len; +}; + +static void append_dn(void *ctx, const void *buf, size_t len) +{ + struct cafile_parser *ca = ctx; + + if(ca->err != CURLE_OK || !ca->in_cert) + return; + if(sizeof(ca->dn) - ca->dn_len < len) { + ca->err = CURLE_FAILED_INIT; + return; + } + memcpy(ca->dn + ca->dn_len, buf, len); + ca->dn_len += len; +} + +static void x509_push(void *ctx, const void *buf, size_t len) +{ + struct cafile_parser *ca = ctx; + + if(ca->in_cert) + br_x509_decoder_push(&ca->xc, buf, len); +} + +static CURLcode load_cafile(struct cafile_source *source, + br_x509_trust_anchor **anchors, + size_t *anchors_len) +{ + struct cafile_parser ca; + br_pem_decoder_context pc; + br_x509_trust_anchor *ta; + size_t ta_size; + br_x509_trust_anchor *new_anchors; + size_t new_anchors_len; + br_x509_pkey *pkey; + FILE *fp = 0; + unsigned char buf[BUFSIZ]; + const unsigned char *p = NULL; + const char *name; + size_t n = 0, i, pushed; + + DEBUGASSERT(source->type == CAFILE_SOURCE_PATH + || source->type == CAFILE_SOURCE_BLOB); + + if(source->type == CAFILE_SOURCE_PATH) { + fp = fopen(source->data, "rb"); + if(!fp) + return CURLE_SSL_CACERT_BADFILE; + } + + if(source->type == CAFILE_SOURCE_BLOB && source->len > (size_t)INT_MAX) + return CURLE_SSL_CACERT_BADFILE; + + ca.err = CURLE_OK; + ca.in_cert = FALSE; + ca.anchors = NULL; + ca.anchors_len = 0; + br_pem_decoder_init(&pc); + br_pem_decoder_setdest(&pc, x509_push, &ca); + do { + if(source->type == CAFILE_SOURCE_PATH) { + n = fread(buf, 1, sizeof(buf), fp); + if(n == 0) + break; + p = buf; + } + else if(source->type == CAFILE_SOURCE_BLOB) { + n = source->len; + p = (unsigned char *) source->data; + } + while(n) { + pushed = br_pem_decoder_push(&pc, p, n); + if(ca.err) + goto fail; + p += pushed; + n -= pushed; + + switch(br_pem_decoder_event(&pc)) { + case 0: + break; + case BR_PEM_BEGIN_OBJ: + name = br_pem_decoder_name(&pc); + if(strcmp(name, "CERTIFICATE") && strcmp(name, "X509 CERTIFICATE")) + break; + br_x509_decoder_init(&ca.xc, append_dn, &ca); + ca.in_cert = TRUE; + ca.dn_len = 0; + break; + case BR_PEM_END_OBJ: + if(!ca.in_cert) + break; + ca.in_cert = FALSE; + if(br_x509_decoder_last_error(&ca.xc)) { + ca.err = CURLE_SSL_CACERT_BADFILE; + goto fail; + } + /* add trust anchor */ + if(ca.anchors_len == SIZE_MAX / sizeof(ca.anchors[0])) { + ca.err = CURLE_OUT_OF_MEMORY; + goto fail; + } + new_anchors_len = ca.anchors_len + 1; + new_anchors = realloc(ca.anchors, + new_anchors_len * sizeof(ca.anchors[0])); + if(!new_anchors) { + ca.err = CURLE_OUT_OF_MEMORY; + goto fail; + } + ca.anchors = new_anchors; + ca.anchors_len = new_anchors_len; + ta = &ca.anchors[ca.anchors_len - 1]; + ta->dn.data = NULL; + ta->flags = 0; + if(br_x509_decoder_isCA(&ca.xc)) + ta->flags |= BR_X509_TA_CA; + pkey = br_x509_decoder_get_pkey(&ca.xc); + if(!pkey) { + ca.err = CURLE_SSL_CACERT_BADFILE; + goto fail; + } + ta->pkey = *pkey; + + /* calculate space needed for trust anchor data */ + ta_size = ca.dn_len; + switch(pkey->key_type) { + case BR_KEYTYPE_RSA: + ta_size += pkey->key.rsa.nlen + pkey->key.rsa.elen; + break; + case BR_KEYTYPE_EC: + ta_size += pkey->key.ec.qlen; + break; + default: + ca.err = CURLE_FAILED_INIT; + goto fail; + } + + /* fill in trust anchor DN and public key data */ + ta->dn.data = malloc(ta_size); + if(!ta->dn.data) { + ca.err = CURLE_OUT_OF_MEMORY; + goto fail; + } + memcpy(ta->dn.data, ca.dn, ca.dn_len); + ta->dn.len = ca.dn_len; + switch(pkey->key_type) { + case BR_KEYTYPE_RSA: + ta->pkey.key.rsa.n = ta->dn.data + ta->dn.len; + memcpy(ta->pkey.key.rsa.n, pkey->key.rsa.n, pkey->key.rsa.nlen); + ta->pkey.key.rsa.e = ta->pkey.key.rsa.n + ta->pkey.key.rsa.nlen; + memcpy(ta->pkey.key.rsa.e, pkey->key.rsa.e, pkey->key.rsa.elen); + break; + case BR_KEYTYPE_EC: + ta->pkey.key.ec.q = ta->dn.data + ta->dn.len; + memcpy(ta->pkey.key.ec.q, pkey->key.ec.q, pkey->key.ec.qlen); + break; + } + break; + default: + ca.err = CURLE_SSL_CACERT_BADFILE; + goto fail; + } + } + } while(source->type != CAFILE_SOURCE_BLOB); + if(fp && ferror(fp)) + ca.err = CURLE_READ_ERROR; + else if(ca.in_cert) + ca.err = CURLE_SSL_CACERT_BADFILE; + +fail: + if(fp) + fclose(fp); + if(ca.err == CURLE_OK) { + *anchors = ca.anchors; + *anchors_len = ca.anchors_len; + } + else { + for(i = 0; i < ca.anchors_len; ++i) + free(ca.anchors[i].dn.data); + free(ca.anchors); + } + + return ca.err; +} + +static void x509_start_chain(const br_x509_class **ctx, + const char *server_name) +{ + struct x509_context *x509 = (struct x509_context *)ctx; + + if(!x509->verifypeer) { + x509->cert_num = 0; + return; + } + + if(!x509->verifyhost) + server_name = NULL; + x509->minimal.vtable->start_chain(&x509->minimal.vtable, server_name); +} + +static void x509_start_cert(const br_x509_class **ctx, uint32_t length) +{ + struct x509_context *x509 = (struct x509_context *)ctx; + + if(!x509->verifypeer) { + /* Only decode the first cert in the chain to obtain the public key */ + if(x509->cert_num == 0) + br_x509_decoder_init(&x509->decoder, NULL, NULL); + return; + } + + x509->minimal.vtable->start_cert(&x509->minimal.vtable, length); +} + +static void x509_append(const br_x509_class **ctx, const unsigned char *buf, + size_t len) +{ + struct x509_context *x509 = (struct x509_context *)ctx; + + if(!x509->verifypeer) { + if(x509->cert_num == 0) + br_x509_decoder_push(&x509->decoder, buf, len); + return; + } + + x509->minimal.vtable->append(&x509->minimal.vtable, buf, len); +} + +static void x509_end_cert(const br_x509_class **ctx) +{ + struct x509_context *x509 = (struct x509_context *)ctx; + + if(!x509->verifypeer) { + x509->cert_num++; + return; + } + + x509->minimal.vtable->end_cert(&x509->minimal.vtable); +} + +static unsigned x509_end_chain(const br_x509_class **ctx) +{ + struct x509_context *x509 = (struct x509_context *)ctx; + + if(!x509->verifypeer) { + return br_x509_decoder_last_error(&x509->decoder); + } + + return x509->minimal.vtable->end_chain(&x509->minimal.vtable); +} + +static const br_x509_pkey *x509_get_pkey(const br_x509_class *const *ctx, + unsigned *usages) +{ + struct x509_context *x509 = (struct x509_context *)ctx; + + if(!x509->verifypeer) { + /* Nothing in the chain is verified, just return the public key of the + first certificate and allow its usage for both TLS_RSA_* and + TLS_ECDHE_* */ + if(usages) + *usages = BR_KEYTYPE_KEYX | BR_KEYTYPE_SIGN; + return br_x509_decoder_get_pkey(&x509->decoder); + } + + return x509->minimal.vtable->get_pkey(&x509->minimal.vtable, usages); +} + +static const br_x509_class x509_vtable = { + sizeof(struct x509_context), + x509_start_chain, + x509_start_cert, + x509_append, + x509_end_cert, + x509_end_chain, + x509_get_pkey +}; + +static const uint16_t ciphertable[] = { + /* RFC 2246 TLS 1.0 */ + BR_TLS_RSA_WITH_3DES_EDE_CBC_SHA, /* 0x000A */ + + /* RFC 3268 TLS 1.0 AES */ + BR_TLS_RSA_WITH_AES_128_CBC_SHA, /* 0x002F */ + BR_TLS_RSA_WITH_AES_256_CBC_SHA, /* 0x0035 */ + + /* RFC 5246 TLS 1.2 */ + BR_TLS_RSA_WITH_AES_128_CBC_SHA256, /* 0x003C */ + BR_TLS_RSA_WITH_AES_256_CBC_SHA256, /* 0x003D */ + + /* RFC 5288 TLS 1.2 AES GCM */ + BR_TLS_RSA_WITH_AES_128_GCM_SHA256, /* 0x009C */ + BR_TLS_RSA_WITH_AES_256_GCM_SHA384, /* 0x009D */ + + /* RFC 4492 TLS 1.0 ECC */ + BR_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, /* 0xC003 */ + BR_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, /* 0xC004 */ + BR_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, /* 0xC005 */ + BR_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, /* 0xC008 */ + BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, /* 0xC009 */ + BR_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, /* 0xC00A */ + BR_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, /* 0xC00D */ + BR_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, /* 0xC00E */ + BR_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, /* 0xC00F */ + BR_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, /* 0xC012 */ + BR_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, /* 0xC013 */ + BR_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, /* 0xC014 */ + + /* RFC 5289 TLS 1.2 ECC HMAC SHA256/384 */ + BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, /* 0xC023 */ + BR_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, /* 0xC024 */ + BR_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, /* 0xC025 */ + BR_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, /* 0xC026 */ + BR_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, /* 0xC027 */ + BR_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, /* 0xC028 */ + BR_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, /* 0xC029 */ + BR_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, /* 0xC02A */ + + /* RFC 5289 TLS 1.2 GCM */ + BR_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, /* 0xC02B */ + BR_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, /* 0xC02C */ + BR_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, /* 0xC02D */ + BR_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, /* 0xC02E */ + BR_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, /* 0xC02F */ + BR_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, /* 0xC030 */ + BR_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, /* 0xC031 */ + BR_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, /* 0xC032 */ + +#ifdef BR_TLS_RSA_WITH_AES_128_CCM + /* RFC 6655 TLS 1.2 CCM + Supported since BearSSL 0.6 */ + BR_TLS_RSA_WITH_AES_128_CCM, /* 0xC09C */ + BR_TLS_RSA_WITH_AES_256_CCM, /* 0xC09D */ + BR_TLS_RSA_WITH_AES_128_CCM_8, /* 0xC0A0 */ + BR_TLS_RSA_WITH_AES_256_CCM_8, /* 0xC0A1 */ + + /* RFC 7251 TLS 1.2 ECC CCM + Supported since BearSSL 0.6 */ + BR_TLS_ECDHE_ECDSA_WITH_AES_128_CCM, /* 0xC0AC */ + BR_TLS_ECDHE_ECDSA_WITH_AES_256_CCM, /* 0xC0AD */ + BR_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, /* 0xC0AE */ + BR_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8, /* 0xC0AF */ +#endif + + /* RFC 7905 TLS 1.2 ChaCha20-Poly1305 + Supported since BearSSL 0.2 */ + BR_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCA8 */ + BR_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCA9 */ +}; + +#define NUM_OF_CIPHERS (sizeof(ciphertable) / sizeof(ciphertable[0])) + +static CURLcode bearssl_set_selected_ciphers(struct Curl_easy *data, + br_ssl_engine_context *ssl_eng, + const char *ciphers) +{ + uint16_t selected[NUM_OF_CIPHERS]; + size_t count = 0, i; + const char *ptr, *end; + + for(ptr = ciphers; ptr[0] != '\0' && count < NUM_OF_CIPHERS; ptr = end) { + uint16_t id = Curl_cipher_suite_walk_str(&ptr, &end); + + /* Check if cipher is supported */ + if(id) { + for(i = 0; i < NUM_OF_CIPHERS && ciphertable[i] != id; i++); + if(i == NUM_OF_CIPHERS) + id = 0; + } + if(!id) { + if(ptr[0] != '\0') + infof(data, "BearSSL: unknown cipher in list: \"%.*s\"", + (int) (end - ptr), ptr); + continue; + } + + /* No duplicates allowed */ + for(i = 0; i < count && selected[i] != id; i++); + if(i < count) { + infof(data, "BearSSL: duplicate cipher in list: \"%.*s\"", + (int) (end - ptr), ptr); + continue; + } + + selected[count++] = id; + } + + if(count == 0) { + failf(data, "BearSSL: no supported cipher in list"); + return CURLE_SSL_CIPHER; + } + + br_ssl_engine_set_suites(ssl_eng, selected, count); + return CURLE_OK; +} + +static CURLcode bearssl_connect_step1(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct bearssl_ssl_backend_data *backend = + (struct bearssl_ssl_backend_data *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + const struct curl_blob *ca_info_blob = conn_config->ca_info_blob; + const char * const ssl_cafile = + /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */ + (ca_info_blob ? NULL : conn_config->CAfile); + const char *hostname = connssl->peer.hostname; + const bool verifypeer = conn_config->verifypeer; + const bool verifyhost = conn_config->verifyhost; + CURLcode ret; + unsigned version_min, version_max; + int session_set = 0; + + DEBUGASSERT(backend); + CURL_TRC_CF(data, cf, "connect_step1"); + + switch(conn_config->version) { + case CURL_SSLVERSION_SSLv2: + failf(data, "BearSSL does not support SSLv2"); + return CURLE_SSL_CONNECT_ERROR; + case CURL_SSLVERSION_SSLv3: + failf(data, "BearSSL does not support SSLv3"); + return CURLE_SSL_CONNECT_ERROR; + case CURL_SSLVERSION_TLSv1_0: + version_min = BR_TLS10; + version_max = BR_TLS10; + break; + case CURL_SSLVERSION_TLSv1_1: + version_min = BR_TLS11; + version_max = BR_TLS11; + break; + case CURL_SSLVERSION_TLSv1_2: + version_min = BR_TLS12; + version_max = BR_TLS12; + break; + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1: + version_min = BR_TLS10; + version_max = BR_TLS12; + break; + default: + failf(data, "BearSSL: unknown CURLOPT_SSLVERSION"); + return CURLE_SSL_CONNECT_ERROR; + } + + if(verifypeer) { + if(ca_info_blob) { + struct cafile_source source; + source.type = CAFILE_SOURCE_BLOB; + source.data = ca_info_blob->data; + source.len = ca_info_blob->len; + + CURL_TRC_CF(data, cf, "connect_step1, load ca_info_blob"); + ret = load_cafile(&source, &backend->anchors, &backend->anchors_len); + if(ret != CURLE_OK) { + failf(data, "error importing CA certificate blob"); + return ret; + } + } + + if(ssl_cafile) { + struct cafile_source source; + source.type = CAFILE_SOURCE_PATH; + source.data = ssl_cafile; + source.len = 0; + + CURL_TRC_CF(data, cf, "connect_step1, load cafile"); + ret = load_cafile(&source, &backend->anchors, &backend->anchors_len); + if(ret != CURLE_OK) { + failf(data, "error setting certificate verify locations." + " CAfile: %s", ssl_cafile); + return ret; + } + } + } + + /* initialize SSL context */ + br_ssl_client_init_full(&backend->ctx, &backend->x509.minimal, + backend->anchors, backend->anchors_len); + br_ssl_engine_set_versions(&backend->ctx.eng, version_min, version_max); + br_ssl_engine_set_buffer(&backend->ctx.eng, backend->buf, + sizeof(backend->buf), 1); + + if(conn_config->cipher_list) { + /* Override the ciphers as specified. For the default cipher list see the + BearSSL source code of br_ssl_client_init_full() */ + CURL_TRC_CF(data, cf, "connect_step1, set ciphers"); + ret = bearssl_set_selected_ciphers(data, &backend->ctx.eng, + conn_config->cipher_list); + if(ret) + return ret; + } + + /* initialize X.509 context */ + backend->x509.vtable = &x509_vtable; + backend->x509.verifypeer = verifypeer; + backend->x509.verifyhost = verifyhost; + br_ssl_engine_set_x509(&backend->ctx.eng, &backend->x509.vtable); + + if(ssl_config->primary.sessionid) { + void *session; + + CURL_TRC_CF(data, cf, "connect_step1, check session cache"); + Curl_ssl_sessionid_lock(data); + if(!Curl_ssl_getsessionid(cf, data, &connssl->peer, &session, NULL)) { + br_ssl_engine_set_session_parameters(&backend->ctx.eng, session); + session_set = 1; + infof(data, "BearSSL: reusing session ID"); + } + Curl_ssl_sessionid_unlock(data); + } + + if(connssl->alpn) { + struct alpn_proto_buf proto; + size_t i; + + for(i = 0; i < connssl->alpn->count; ++i) { + backend->protocols[i] = connssl->alpn->entries[i]; + } + br_ssl_engine_set_protocol_names(&backend->ctx.eng, backend->protocols, + connssl->alpn->count); + Curl_alpn_to_proto_str(&proto, connssl->alpn); + infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data); + } + + if(connssl->peer.type != CURL_SSL_PEER_DNS) { + if(verifyhost) { + failf(data, "BearSSL: " + "host verification of IP address is not supported"); + return CURLE_PEER_FAILED_VERIFICATION; + } + hostname = NULL; + } + else { + if(!connssl->peer.sni) { + failf(data, "Failed to set SNI"); + return CURLE_SSL_CONNECT_ERROR; + } + hostname = connssl->peer.sni; + CURL_TRC_CF(data, cf, "connect_step1, SNI set"); + } + + /* give application a chance to interfere with SSL set up. */ + if(data->set.ssl.fsslctx) { + Curl_set_in_callback(data, true); + ret = (*data->set.ssl.fsslctx)(data, &backend->ctx, + data->set.ssl.fsslctxp); + Curl_set_in_callback(data, false); + if(ret) { + failf(data, "BearSSL: error signaled by ssl ctx callback"); + return ret; + } + } + + if(!br_ssl_client_reset(&backend->ctx, hostname, session_set)) + return CURLE_FAILED_INIT; + backend->active = TRUE; + + connssl->connecting_state = ssl_connect_2; + + return CURLE_OK; +} + +static void bearssl_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + if(!cf->connected) { + curl_socket_t sock = Curl_conn_cf_get_socket(cf->next, data); + if(sock != CURL_SOCKET_BAD) { + struct ssl_connect_data *connssl = cf->ctx; + struct bearssl_ssl_backend_data *backend = + (struct bearssl_ssl_backend_data *)connssl->backend; + unsigned state = br_ssl_engine_current_state(&backend->ctx.eng); + + if(state & BR_SSL_SENDREC) { + Curl_pollset_set_out_only(data, ps, sock); + } + else { + Curl_pollset_set_in_only(data, ps, sock); + } + } + } +} + +static CURLcode bearssl_run_until(struct Curl_cfilter *cf, + struct Curl_easy *data, + unsigned target) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct bearssl_ssl_backend_data *backend = + (struct bearssl_ssl_backend_data *)connssl->backend; + unsigned state; + unsigned char *buf; + size_t len; + ssize_t ret; + CURLcode result; + int err; + + DEBUGASSERT(backend); + + for(;;) { + state = br_ssl_engine_current_state(&backend->ctx.eng); + if(state & BR_SSL_CLOSED) { + err = br_ssl_engine_last_error(&backend->ctx.eng); + switch(err) { + case BR_ERR_OK: + /* TLS close notify */ + if(connssl->state != ssl_connection_complete) { + failf(data, "SSL: connection closed during handshake"); + return CURLE_SSL_CONNECT_ERROR; + } + return CURLE_OK; + case BR_ERR_X509_EXPIRED: + failf(data, "SSL: X.509 verification: " + "certificate is expired or not yet valid"); + return CURLE_PEER_FAILED_VERIFICATION; + case BR_ERR_X509_BAD_SERVER_NAME: + failf(data, "SSL: X.509 verification: " + "expected server name was not found in the chain"); + return CURLE_PEER_FAILED_VERIFICATION; + case BR_ERR_X509_NOT_TRUSTED: + failf(data, "SSL: X.509 verification: " + "chain could not be linked to a trust anchor"); + return CURLE_PEER_FAILED_VERIFICATION; + } + /* X.509 errors are documented to have the range 32..63 */ + if(err >= 32 && err < 64) + return CURLE_PEER_FAILED_VERIFICATION; + return CURLE_SSL_CONNECT_ERROR; + } + if(state & target) + return CURLE_OK; + if(state & BR_SSL_SENDREC) { + buf = br_ssl_engine_sendrec_buf(&backend->ctx.eng, &len); + ret = Curl_conn_cf_send(cf->next, data, (char *)buf, len, &result); + CURL_TRC_CF(data, cf, "ssl_send(len=%zu) -> %zd, %d", len, ret, result); + if(ret <= 0) { + return result; + } + br_ssl_engine_sendrec_ack(&backend->ctx.eng, ret); + } + else if(state & BR_SSL_RECVREC) { + buf = br_ssl_engine_recvrec_buf(&backend->ctx.eng, &len); + ret = Curl_conn_cf_recv(cf->next, data, (char *)buf, len, &result); + CURL_TRC_CF(data, cf, "ssl_recv(len=%zu) -> %zd, %d", len, ret, result); + if(ret == 0) { + failf(data, "SSL: EOF without close notify"); + return CURLE_RECV_ERROR; + } + if(ret <= 0) { + return result; + } + br_ssl_engine_recvrec_ack(&backend->ctx.eng, ret); + } + } +} + +static CURLcode bearssl_connect_step2(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct bearssl_ssl_backend_data *backend = + (struct bearssl_ssl_backend_data *)connssl->backend; + br_ssl_session_parameters session; + char cipher_str[64]; + char ver_str[16]; + CURLcode ret; + + DEBUGASSERT(backend); + CURL_TRC_CF(data, cf, "connect_step2"); + + ret = bearssl_run_until(cf, data, BR_SSL_SENDAPP | BR_SSL_RECVAPP); + if(ret == CURLE_AGAIN) + return CURLE_OK; + if(ret == CURLE_OK) { + unsigned int tver; + + if(br_ssl_engine_current_state(&backend->ctx.eng) == BR_SSL_CLOSED) { + failf(data, "SSL: connection closed during handshake"); + return CURLE_SSL_CONNECT_ERROR; + } + connssl->connecting_state = ssl_connect_3; + /* Informational message */ + tver = br_ssl_engine_get_version(&backend->ctx.eng); + if(tver == BR_TLS12) + strcpy(ver_str, "TLSv1.2"); + else if(tver == BR_TLS11) + strcpy(ver_str, "TLSv1.1"); + else if(tver == BR_TLS10) + strcpy(ver_str, "TLSv1.0"); + else { + msnprintf(ver_str, sizeof(ver_str), "TLS 0x%04x", tver); + } + br_ssl_engine_get_session_parameters(&backend->ctx.eng, &session); + Curl_cipher_suite_get_str(session.cipher_suite, cipher_str, + sizeof(cipher_str), true); + infof(data, "BearSSL: %s connection using %s", ver_str, cipher_str); + } + return ret; +} + +static void bearssl_session_free(void *sessionid, size_t idsize) +{ + (void)idsize; + free(sessionid); +} + +static CURLcode bearssl_connect_step3(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct bearssl_ssl_backend_data *backend = + (struct bearssl_ssl_backend_data *)connssl->backend; + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + CURLcode ret; + + DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); + DEBUGASSERT(backend); + CURL_TRC_CF(data, cf, "connect_step3"); + + if(connssl->alpn) { + const char *proto; + + proto = br_ssl_engine_get_selected_protocol(&backend->ctx.eng); + Curl_alpn_set_negotiated(cf, data, (const unsigned char *)proto, + proto? strlen(proto) : 0); + } + + if(ssl_config->primary.sessionid) { + bool incache; + void *oldsession; + br_ssl_session_parameters *session; + + session = malloc(sizeof(*session)); + if(!session) + return CURLE_OUT_OF_MEMORY; + br_ssl_engine_get_session_parameters(&backend->ctx.eng, session); + Curl_ssl_sessionid_lock(data); + incache = !(Curl_ssl_getsessionid(cf, data, &connssl->peer, + &oldsession, NULL)); + if(incache) + Curl_ssl_delsessionid(data, oldsession); + + ret = Curl_ssl_addsessionid(cf, data, &connssl->peer, session, 0, + bearssl_session_free); + Curl_ssl_sessionid_unlock(data); + if(ret) + return ret; + } + + connssl->connecting_state = ssl_connect_done; + + return CURLE_OK; +} + +static ssize_t bearssl_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *buf, size_t len, CURLcode *err) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct bearssl_ssl_backend_data *backend = + (struct bearssl_ssl_backend_data *)connssl->backend; + unsigned char *app; + size_t applen; + + DEBUGASSERT(backend); + + for(;;) { + *err = bearssl_run_until(cf, data, BR_SSL_SENDAPP); + if(*err) + return -1; + app = br_ssl_engine_sendapp_buf(&backend->ctx.eng, &applen); + if(!app) { + failf(data, "SSL: connection closed during write"); + *err = CURLE_SEND_ERROR; + return -1; + } + if(backend->pending_write) { + applen = backend->pending_write; + backend->pending_write = 0; + return applen; + } + if(applen > len) + applen = len; + memcpy(app, buf, applen); + br_ssl_engine_sendapp_ack(&backend->ctx.eng, applen); + br_ssl_engine_flush(&backend->ctx.eng, 0); + backend->pending_write = applen; + } +} + +static ssize_t bearssl_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, CURLcode *err) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct bearssl_ssl_backend_data *backend = + (struct bearssl_ssl_backend_data *)connssl->backend; + unsigned char *app; + size_t applen; + + DEBUGASSERT(backend); + + *err = bearssl_run_until(cf, data, BR_SSL_RECVAPP); + if(*err != CURLE_OK) + return -1; + app = br_ssl_engine_recvapp_buf(&backend->ctx.eng, &applen); + if(!app) + return 0; + if(applen > len) + applen = len; + memcpy(buf, app, applen); + br_ssl_engine_recvapp_ack(&backend->ctx.eng, applen); + + return applen; +} + +static CURLcode bearssl_connect_common(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool nonblocking, + bool *done) +{ + CURLcode ret; + struct ssl_connect_data *connssl = cf->ctx; + curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data); + timediff_t timeout_ms; + int what; + + CURL_TRC_CF(data, cf, "connect_common(blocking=%d)", !nonblocking); + /* check if the connection has already been established */ + if(ssl_connection_complete == connssl->state) { + CURL_TRC_CF(data, cf, "connect_common, connected"); + *done = TRUE; + return CURLE_OK; + } + + if(ssl_connect_1 == connssl->connecting_state) { + ret = bearssl_connect_step1(cf, data); + if(ret) + return ret; + } + + while(ssl_connect_2 == connssl->connecting_state || + ssl_connect_2_reading == connssl->connecting_state || + ssl_connect_2_writing == connssl->connecting_state) { + /* check allowed time left */ + timeout_ms = Curl_timeleft(data, NULL, TRUE); + + if(timeout_ms < 0) { + /* no need to continue if time already is up */ + failf(data, "SSL connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + + /* if ssl is expecting something, check if it's available. */ + if(ssl_connect_2_reading == connssl->connecting_state || + ssl_connect_2_writing == connssl->connecting_state) { + + curl_socket_t writefd = ssl_connect_2_writing == + connssl->connecting_state?sockfd:CURL_SOCKET_BAD; + curl_socket_t readfd = ssl_connect_2_reading == + connssl->connecting_state?sockfd:CURL_SOCKET_BAD; + + CURL_TRC_CF(data, cf, "connect_common, check socket"); + what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, + nonblocking?0:timeout_ms); + CURL_TRC_CF(data, cf, "connect_common, check socket -> %d", what); + if(what < 0) { + /* fatal error */ + failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); + return CURLE_SSL_CONNECT_ERROR; + } + else if(0 == what) { + if(nonblocking) { + *done = FALSE; + return CURLE_OK; + } + else { + /* timeout */ + failf(data, "SSL connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + } + /* socket is readable or writable */ + } + + /* Run transaction, and return to the caller if it failed or if this + * connection is done nonblocking and this loop would execute again. This + * permits the owner of a multi handle to abort a connection attempt + * before step2 has completed while ensuring that a client using select() + * or epoll() will always have a valid fdset to wait on. + */ + ret = bearssl_connect_step2(cf, data); + if(ret || (nonblocking && + (ssl_connect_2 == connssl->connecting_state || + ssl_connect_2_reading == connssl->connecting_state || + ssl_connect_2_writing == connssl->connecting_state))) + return ret; + } + + if(ssl_connect_3 == connssl->connecting_state) { + ret = bearssl_connect_step3(cf, data); + if(ret) + return ret; + } + + if(ssl_connect_done == connssl->connecting_state) { + connssl->state = ssl_connection_complete; + *done = TRUE; + } + else + *done = FALSE; + + /* Reset our connect state machine */ + connssl->connecting_state = ssl_connect_1; + + return CURLE_OK; +} + +static size_t bearssl_version(char *buffer, size_t size) +{ + return msnprintf(buffer, size, "BearSSL"); +} + +static bool bearssl_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct ssl_connect_data *ctx = cf->ctx; + struct bearssl_ssl_backend_data *backend; + + (void)data; + DEBUGASSERT(ctx && ctx->backend); + backend = (struct bearssl_ssl_backend_data *)ctx->backend; + return br_ssl_engine_current_state(&backend->ctx.eng) & BR_SSL_RECVAPP; +} + +static CURLcode bearssl_random(struct Curl_easy *data UNUSED_PARAM, + unsigned char *entropy, size_t length) +{ + static br_hmac_drbg_context ctx; + static bool seeded = FALSE; + + if(!seeded) { + br_prng_seeder seeder; + + br_hmac_drbg_init(&ctx, &br_sha256_vtable, NULL, 0); + seeder = br_prng_seeder_system(NULL); + if(!seeder || !seeder(&ctx.vtable)) + return CURLE_FAILED_INIT; + seeded = TRUE; + } + br_hmac_drbg_generate(&ctx, entropy, length); + + return CURLE_OK; +} + +static CURLcode bearssl_connect(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURLcode ret; + bool done = FALSE; + + ret = bearssl_connect_common(cf, data, FALSE, &done); + if(ret) + return ret; + + DEBUGASSERT(done); + + return CURLE_OK; +} + +static CURLcode bearssl_connect_nonblocking(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + return bearssl_connect_common(cf, data, TRUE, done); +} + +static void *bearssl_get_internals(struct ssl_connect_data *connssl, + CURLINFO info UNUSED_PARAM) +{ + struct bearssl_ssl_backend_data *backend = + (struct bearssl_ssl_backend_data *)connssl->backend; + DEBUGASSERT(backend); + return &backend->ctx; +} + +static void bearssl_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct bearssl_ssl_backend_data *backend = + (struct bearssl_ssl_backend_data *)connssl->backend; + size_t i; + + DEBUGASSERT(backend); + + if(backend->active) { + backend->active = FALSE; + br_ssl_engine_close(&backend->ctx.eng); + (void)bearssl_run_until(cf, data, BR_SSL_CLOSED); + } + if(backend->anchors) { + for(i = 0; i < backend->anchors_len; ++i) + free(backend->anchors[i].dn.data); + Curl_safefree(backend->anchors); + } +} + +static CURLcode bearssl_sha256sum(const unsigned char *input, + size_t inputlen, + unsigned char *sha256sum, + size_t sha256len UNUSED_PARAM) +{ + br_sha256_context ctx; + + br_sha256_init(&ctx); + br_sha256_update(&ctx, input, inputlen); + br_sha256_out(&ctx, sha256sum); + return CURLE_OK; +} + +const struct Curl_ssl Curl_ssl_bearssl = { + { CURLSSLBACKEND_BEARSSL, "bearssl" }, /* info */ + SSLSUPP_CAINFO_BLOB | SSLSUPP_SSL_CTX | SSLSUPP_HTTPS_PROXY, + sizeof(struct bearssl_ssl_backend_data), + + Curl_none_init, /* init */ + Curl_none_cleanup, /* cleanup */ + bearssl_version, /* version */ + Curl_none_check_cxn, /* check_cxn */ + Curl_none_shutdown, /* shutdown */ + bearssl_data_pending, /* data_pending */ + bearssl_random, /* random */ + Curl_none_cert_status_request, /* cert_status_request */ + bearssl_connect, /* connect */ + bearssl_connect_nonblocking, /* connect_nonblocking */ + bearssl_adjust_pollset, /* adjust_pollset */ + bearssl_get_internals, /* get_internals */ + bearssl_close, /* close_one */ + Curl_none_close_all, /* close_all */ + Curl_none_set_engine, /* set_engine */ + Curl_none_set_engine_default, /* set_engine_default */ + Curl_none_engines_list, /* engines_list */ + Curl_none_false_start, /* false_start */ + bearssl_sha256sum, /* sha256sum */ + NULL, /* associate_connection */ + NULL, /* disassociate_connection */ + NULL, /* free_multi_ssl_backend_data */ + bearssl_recv, /* recv decrypted data */ + bearssl_send, /* send data to encrypt */ +}; + +#endif /* USE_BEARSSL */ diff --git a/third_party/curl/lib/vtls/bearssl.h b/third_party/curl/lib/vtls/bearssl.h new file mode 100644 index 0000000..b3651b0 --- /dev/null +++ b/third_party/curl/lib/vtls/bearssl.h @@ -0,0 +1,34 @@ +#ifndef HEADER_CURL_BEARSSL_H +#define HEADER_CURL_BEARSSL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Michael Forney, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_BEARSSL + +extern const struct Curl_ssl Curl_ssl_bearssl; + +#endif /* USE_BEARSSL */ +#endif /* HEADER_CURL_BEARSSL_H */ diff --git a/third_party/curl/lib/vtls/cipher_suite.c b/third_party/curl/lib/vtls/cipher_suite.c new file mode 100644 index 0000000..a78838d --- /dev/null +++ b/third_party/curl/lib/vtls/cipher_suite.c @@ -0,0 +1,716 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Jan Venekamp, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_MBEDTLS) || defined(USE_BEARSSL) +#include "cipher_suite.h" +#include "curl_printf.h" +#include "strcase.h" +#include + +/* + * To support the CURLOPT_SSL_CIPHER_LIST option on SSL backends + * that do not support it natively, but do support setting a list of + * IANA ids, we need a list of all supported cipher suite names + * (openssl and IANA) to be able to look up the IANA ids. + * + * To keep the binary size of this list down we compress each entry + * down to 2 + 6 bytes using the C preprocessor. + */ + +/* + * mbedTLS NOTE: mbedTLS has mbedtls_ssl_get_ciphersuite_id() to + * convert a string representation to an IANA id, we do not use that + * because it does not support "standard" openssl cipher suite + * names, nor IANA names. + */ + +/* NOTE: also see tests/unit/unit3205.c */ + +/* Text for cipher suite parts (max 64 entries), + keep indexes below in sync with this! */ +static const char *cs_txt = + "\0" + "TLS" "\0" + "WITH" "\0" + "128" "\0" + "256" "\0" + "3DES" "\0" + "8" "\0" + "AES" "\0" + "AES128" "\0" + "AES256" "\0" + "CBC" "\0" + "CBC3" "\0" + "CCM" "\0" + "CCM8" "\0" + "CHACHA20" "\0" + "DES" "\0" + "DHE" "\0" + "ECDH" "\0" + "ECDHE" "\0" + "ECDSA" "\0" + "EDE" "\0" + "GCM" "\0" + "MD5" "\0" + "NULL" "\0" + "POLY1305" "\0" + "PSK" "\0" + "RSA" "\0" + "SHA" "\0" + "SHA256" "\0" + "SHA384" "\0" +#if defined(USE_MBEDTLS) + "ARIA" "\0" + "ARIA128" "\0" + "ARIA256" "\0" + "CAMELLIA" "\0" + "CAMELLIA128" "\0" + "CAMELLIA256" "\0" +#endif +; +/* Indexes of above cs_txt */ +enum { + CS_TXT_IDX_, + CS_TXT_IDX_TLS, + CS_TXT_IDX_WITH, + CS_TXT_IDX_128, + CS_TXT_IDX_256, + CS_TXT_IDX_3DES, + CS_TXT_IDX_8, + CS_TXT_IDX_AES, + CS_TXT_IDX_AES128, + CS_TXT_IDX_AES256, + CS_TXT_IDX_CBC, + CS_TXT_IDX_CBC3, + CS_TXT_IDX_CCM, + CS_TXT_IDX_CCM8, + CS_TXT_IDX_CHACHA20, + CS_TXT_IDX_DES, + CS_TXT_IDX_DHE, + CS_TXT_IDX_ECDH, + CS_TXT_IDX_ECDHE, + CS_TXT_IDX_ECDSA, + CS_TXT_IDX_EDE, + CS_TXT_IDX_GCM, + CS_TXT_IDX_MD5, + CS_TXT_IDX_NULL, + CS_TXT_IDX_POLY1305, + CS_TXT_IDX_PSK, + CS_TXT_IDX_RSA, + CS_TXT_IDX_SHA, + CS_TXT_IDX_SHA256, + CS_TXT_IDX_SHA384, +#if defined(USE_MBEDTLS) + CS_TXT_IDX_ARIA, + CS_TXT_IDX_ARIA128, + CS_TXT_IDX_ARIA256, + CS_TXT_IDX_CAMELLIA, + CS_TXT_IDX_CAMELLIA128, + CS_TXT_IDX_CAMELLIA256, +#endif + CS_TXT_LEN, +}; + +#define CS_ZIP_IDX(a, b, c, d, e, f, g, h) \ +{ \ + (uint8_t) ((a) << 2 | ((b) & 0x3F) >> 4), \ + (uint8_t) ((b) << 4 | ((c) & 0x3F) >> 2), \ + (uint8_t) ((c) << 6 | ((d) & 0x3F)), \ + (uint8_t) ((e) << 2 | ((f) & 0x3F) >> 4), \ + (uint8_t) ((f) << 4 | ((g) & 0x3F) >> 2), \ + (uint8_t) ((g) << 6 | ((h) & 0x3F)) \ +} +#define CS_ENTRY(id, a, b, c, d, e, f, g, h) \ +{ \ + id, \ + CS_ZIP_IDX( \ + CS_TXT_IDX_ ## a, CS_TXT_IDX_ ## b, \ + CS_TXT_IDX_ ## c, CS_TXT_IDX_ ## d, \ + CS_TXT_IDX_ ## e, CS_TXT_IDX_ ## f, \ + CS_TXT_IDX_ ## g, CS_TXT_IDX_ ## h \ + ) \ +} + +struct cs_entry { + uint16_t id; + uint8_t zip[6]; +}; + +/* !checksrc! disable COMMANOSPACE all */ +static const struct cs_entry cs_list [] = { + CS_ENTRY(0x002F, TLS,RSA,WITH,AES,128,CBC,SHA,), + CS_ENTRY(0x002F, AES128,SHA,,,,,,), + CS_ENTRY(0x0035, TLS,RSA,WITH,AES,256,CBC,SHA,), + CS_ENTRY(0x0035, AES256,SHA,,,,,,), + CS_ENTRY(0x003C, TLS,RSA,WITH,AES,128,CBC,SHA256,), + CS_ENTRY(0x003C, AES128,SHA256,,,,,,), + CS_ENTRY(0x003D, TLS,RSA,WITH,AES,256,CBC,SHA256,), + CS_ENTRY(0x003D, AES256,SHA256,,,,,,), + CS_ENTRY(0x009C, TLS,RSA,WITH,AES,128,GCM,SHA256,), + CS_ENTRY(0x009C, AES128,GCM,SHA256,,,,,), + CS_ENTRY(0x009D, TLS,RSA,WITH,AES,256,GCM,SHA384,), + CS_ENTRY(0x009D, AES256,GCM,SHA384,,,,,), + CS_ENTRY(0xC004, TLS,ECDH,ECDSA,WITH,AES,128,CBC,SHA), + CS_ENTRY(0xC004, ECDH,ECDSA,AES128,SHA,,,,), + CS_ENTRY(0xC005, TLS,ECDH,ECDSA,WITH,AES,256,CBC,SHA), + CS_ENTRY(0xC005, ECDH,ECDSA,AES256,SHA,,,,), + CS_ENTRY(0xC009, TLS,ECDHE,ECDSA,WITH,AES,128,CBC,SHA), + CS_ENTRY(0xC009, ECDHE,ECDSA,AES128,SHA,,,,), + CS_ENTRY(0xC00A, TLS,ECDHE,ECDSA,WITH,AES,256,CBC,SHA), + CS_ENTRY(0xC00A, ECDHE,ECDSA,AES256,SHA,,,,), + CS_ENTRY(0xC00E, TLS,ECDH,RSA,WITH,AES,128,CBC,SHA), + CS_ENTRY(0xC00E, ECDH,RSA,AES128,SHA,,,,), + CS_ENTRY(0xC00F, TLS,ECDH,RSA,WITH,AES,256,CBC,SHA), + CS_ENTRY(0xC00F, ECDH,RSA,AES256,SHA,,,,), + CS_ENTRY(0xC013, TLS,ECDHE,RSA,WITH,AES,128,CBC,SHA), + CS_ENTRY(0xC013, ECDHE,RSA,AES128,SHA,,,,), + CS_ENTRY(0xC014, TLS,ECDHE,RSA,WITH,AES,256,CBC,SHA), + CS_ENTRY(0xC014, ECDHE,RSA,AES256,SHA,,,,), + CS_ENTRY(0xC023, TLS,ECDHE,ECDSA,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0xC023, ECDHE,ECDSA,AES128,SHA256,,,,), + CS_ENTRY(0xC024, TLS,ECDHE,ECDSA,WITH,AES,256,CBC,SHA384), + CS_ENTRY(0xC024, ECDHE,ECDSA,AES256,SHA384,,,,), + CS_ENTRY(0xC025, TLS,ECDH,ECDSA,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0xC025, ECDH,ECDSA,AES128,SHA256,,,,), + CS_ENTRY(0xC026, TLS,ECDH,ECDSA,WITH,AES,256,CBC,SHA384), + CS_ENTRY(0xC026, ECDH,ECDSA,AES256,SHA384,,,,), + CS_ENTRY(0xC027, TLS,ECDHE,RSA,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0xC027, ECDHE,RSA,AES128,SHA256,,,,), + CS_ENTRY(0xC028, TLS,ECDHE,RSA,WITH,AES,256,CBC,SHA384), + CS_ENTRY(0xC028, ECDHE,RSA,AES256,SHA384,,,,), + CS_ENTRY(0xC029, TLS,ECDH,RSA,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0xC029, ECDH,RSA,AES128,SHA256,,,,), + CS_ENTRY(0xC02A, TLS,ECDH,RSA,WITH,AES,256,CBC,SHA384), + CS_ENTRY(0xC02A, ECDH,RSA,AES256,SHA384,,,,), + CS_ENTRY(0xC02B, TLS,ECDHE,ECDSA,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0xC02B, ECDHE,ECDSA,AES128,GCM,SHA256,,,), + CS_ENTRY(0xC02C, TLS,ECDHE,ECDSA,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0xC02C, ECDHE,ECDSA,AES256,GCM,SHA384,,,), + CS_ENTRY(0xC02D, TLS,ECDH,ECDSA,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0xC02D, ECDH,ECDSA,AES128,GCM,SHA256,,,), + CS_ENTRY(0xC02E, TLS,ECDH,ECDSA,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0xC02E, ECDH,ECDSA,AES256,GCM,SHA384,,,), + CS_ENTRY(0xC02F, TLS,ECDHE,RSA,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0xC02F, ECDHE,RSA,AES128,GCM,SHA256,,,), + CS_ENTRY(0xC030, TLS,ECDHE,RSA,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0xC030, ECDHE,RSA,AES256,GCM,SHA384,,,), + CS_ENTRY(0xC031, TLS,ECDH,RSA,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0xC031, ECDH,RSA,AES128,GCM,SHA256,,,), + CS_ENTRY(0xC032, TLS,ECDH,RSA,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0xC032, ECDH,RSA,AES256,GCM,SHA384,,,), + CS_ENTRY(0xCCA8, TLS,ECDHE,RSA,WITH,CHACHA20,POLY1305,SHA256,), + CS_ENTRY(0xCCA8, ECDHE,RSA,CHACHA20,POLY1305,,,,), + CS_ENTRY(0xCCA9, TLS,ECDHE,ECDSA,WITH,CHACHA20,POLY1305,SHA256,), + CS_ENTRY(0xCCA9, ECDHE,ECDSA,CHACHA20,POLY1305,,,,), +#if defined(USE_MBEDTLS) + CS_ENTRY(0x0001, TLS,RSA,WITH,NULL,MD5,,,), + CS_ENTRY(0x0001, NULL,MD5,,,,,,), + CS_ENTRY(0x0002, TLS,RSA,WITH,NULL,SHA,,,), + CS_ENTRY(0x0002, NULL,SHA,,,,,,), + CS_ENTRY(0x002C, TLS,PSK,WITH,NULL,SHA,,,), + CS_ENTRY(0x002C, PSK,NULL,SHA,,,,,), + CS_ENTRY(0x002D, TLS,DHE,PSK,WITH,NULL,SHA,,), + CS_ENTRY(0x002D, DHE,PSK,NULL,SHA,,,,), + CS_ENTRY(0x002E, TLS,RSA,PSK,WITH,NULL,SHA,,), + CS_ENTRY(0x002E, RSA,PSK,NULL,SHA,,,,), + CS_ENTRY(0x0033, TLS,DHE,RSA,WITH,AES,128,CBC,SHA), + CS_ENTRY(0x0033, DHE,RSA,AES128,SHA,,,,), + CS_ENTRY(0x0039, TLS,DHE,RSA,WITH,AES,256,CBC,SHA), + CS_ENTRY(0x0039, DHE,RSA,AES256,SHA,,,,), + CS_ENTRY(0x003B, TLS,RSA,WITH,NULL,SHA256,,,), + CS_ENTRY(0x003B, NULL,SHA256,,,,,,), + CS_ENTRY(0x0067, TLS,DHE,RSA,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0x0067, DHE,RSA,AES128,SHA256,,,,), + CS_ENTRY(0x006B, TLS,DHE,RSA,WITH,AES,256,CBC,SHA256), + CS_ENTRY(0x006B, DHE,RSA,AES256,SHA256,,,,), + CS_ENTRY(0x008C, TLS,PSK,WITH,AES,128,CBC,SHA,), + CS_ENTRY(0x008C, PSK,AES128,CBC,SHA,,,,), + CS_ENTRY(0x008D, TLS,PSK,WITH,AES,256,CBC,SHA,), + CS_ENTRY(0x008D, PSK,AES256,CBC,SHA,,,,), + CS_ENTRY(0x0090, TLS,DHE,PSK,WITH,AES,128,CBC,SHA), + CS_ENTRY(0x0090, DHE,PSK,AES128,CBC,SHA,,,), + CS_ENTRY(0x0091, TLS,DHE,PSK,WITH,AES,256,CBC,SHA), + CS_ENTRY(0x0091, DHE,PSK,AES256,CBC,SHA,,,), + CS_ENTRY(0x0094, TLS,RSA,PSK,WITH,AES,128,CBC,SHA), + CS_ENTRY(0x0094, RSA,PSK,AES128,CBC,SHA,,,), + CS_ENTRY(0x0095, TLS,RSA,PSK,WITH,AES,256,CBC,SHA), + CS_ENTRY(0x0095, RSA,PSK,AES256,CBC,SHA,,,), + CS_ENTRY(0x009E, TLS,DHE,RSA,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0x009E, DHE,RSA,AES128,GCM,SHA256,,,), + CS_ENTRY(0x009F, TLS,DHE,RSA,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0x009F, DHE,RSA,AES256,GCM,SHA384,,,), + CS_ENTRY(0x00A8, TLS,PSK,WITH,AES,128,GCM,SHA256,), + CS_ENTRY(0x00A8, PSK,AES128,GCM,SHA256,,,,), + CS_ENTRY(0x00A9, TLS,PSK,WITH,AES,256,GCM,SHA384,), + CS_ENTRY(0x00A9, PSK,AES256,GCM,SHA384,,,,), + CS_ENTRY(0x00AA, TLS,DHE,PSK,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0x00AA, DHE,PSK,AES128,GCM,SHA256,,,), + CS_ENTRY(0x00AB, TLS,DHE,PSK,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0x00AB, DHE,PSK,AES256,GCM,SHA384,,,), + CS_ENTRY(0x00AC, TLS,RSA,PSK,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0x00AC, RSA,PSK,AES128,GCM,SHA256,,,), + CS_ENTRY(0x00AD, TLS,RSA,PSK,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0x00AD, RSA,PSK,AES256,GCM,SHA384,,,), + CS_ENTRY(0x00AE, TLS,PSK,WITH,AES,128,CBC,SHA256,), + CS_ENTRY(0x00AE, PSK,AES128,CBC,SHA256,,,,), + CS_ENTRY(0x00AF, TLS,PSK,WITH,AES,256,CBC,SHA384,), + CS_ENTRY(0x00AF, PSK,AES256,CBC,SHA384,,,,), + CS_ENTRY(0x00B0, TLS,PSK,WITH,NULL,SHA256,,,), + CS_ENTRY(0x00B0, PSK,NULL,SHA256,,,,,), + CS_ENTRY(0x00B1, TLS,PSK,WITH,NULL,SHA384,,,), + CS_ENTRY(0x00B1, PSK,NULL,SHA384,,,,,), + CS_ENTRY(0x00B2, TLS,DHE,PSK,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0x00B2, DHE,PSK,AES128,CBC,SHA256,,,), + CS_ENTRY(0x00B3, TLS,DHE,PSK,WITH,AES,256,CBC,SHA384), + CS_ENTRY(0x00B3, DHE,PSK,AES256,CBC,SHA384,,,), + CS_ENTRY(0x00B4, TLS,DHE,PSK,WITH,NULL,SHA256,,), + CS_ENTRY(0x00B4, DHE,PSK,NULL,SHA256,,,,), + CS_ENTRY(0x00B5, TLS,DHE,PSK,WITH,NULL,SHA384,,), + CS_ENTRY(0x00B5, DHE,PSK,NULL,SHA384,,,,), + CS_ENTRY(0x00B6, TLS,RSA,PSK,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0x00B6, RSA,PSK,AES128,CBC,SHA256,,,), + CS_ENTRY(0x00B7, TLS,RSA,PSK,WITH,AES,256,CBC,SHA384), + CS_ENTRY(0x00B7, RSA,PSK,AES256,CBC,SHA384,,,), + CS_ENTRY(0x00B8, TLS,RSA,PSK,WITH,NULL,SHA256,,), + CS_ENTRY(0x00B8, RSA,PSK,NULL,SHA256,,,,), + CS_ENTRY(0x00B9, TLS,RSA,PSK,WITH,NULL,SHA384,,), + CS_ENTRY(0x00B9, RSA,PSK,NULL,SHA384,,,,), + CS_ENTRY(0x1301, TLS,AES,128,GCM,SHA256,,,), + CS_ENTRY(0x1302, TLS,AES,256,GCM,SHA384,,,), + CS_ENTRY(0x1303, TLS,CHACHA20,POLY1305,SHA256,,,,), + CS_ENTRY(0x1304, TLS,AES,128,CCM,SHA256,,,), + CS_ENTRY(0x1305, TLS,AES,128,CCM,8,SHA256,,), + CS_ENTRY(0xC001, TLS,ECDH,ECDSA,WITH,NULL,SHA,,), + CS_ENTRY(0xC001, ECDH,ECDSA,NULL,SHA,,,,), + CS_ENTRY(0xC006, TLS,ECDHE,ECDSA,WITH,NULL,SHA,,), + CS_ENTRY(0xC006, ECDHE,ECDSA,NULL,SHA,,,,), + CS_ENTRY(0xC00B, TLS,ECDH,RSA,WITH,NULL,SHA,,), + CS_ENTRY(0xC00B, ECDH,RSA,NULL,SHA,,,,), + CS_ENTRY(0xC010, TLS,ECDHE,RSA,WITH,NULL,SHA,,), + CS_ENTRY(0xC010, ECDHE,RSA,NULL,SHA,,,,), + CS_ENTRY(0xC035, TLS,ECDHE,PSK,WITH,AES,128,CBC,SHA), + CS_ENTRY(0xC035, ECDHE,PSK,AES128,CBC,SHA,,,), + CS_ENTRY(0xC036, TLS,ECDHE,PSK,WITH,AES,256,CBC,SHA), + CS_ENTRY(0xC036, ECDHE,PSK,AES256,CBC,SHA,,,), + CS_ENTRY(0xCCAB, TLS,PSK,WITH,CHACHA20,POLY1305,SHA256,,), + CS_ENTRY(0xCCAB, PSK,CHACHA20,POLY1305,,,,,), +#endif +#if defined(USE_BEARSSL) + CS_ENTRY(0x000A, TLS,RSA,WITH,3DES,EDE,CBC,SHA,), + CS_ENTRY(0x000A, DES,CBC3,SHA,,,,,), + CS_ENTRY(0xC003, TLS,ECDH,ECDSA,WITH,3DES,EDE,CBC,SHA), + CS_ENTRY(0xC003, ECDH,ECDSA,DES,CBC3,SHA,,,), + CS_ENTRY(0xC008, TLS,ECDHE,ECDSA,WITH,3DES,EDE,CBC,SHA), + CS_ENTRY(0xC008, ECDHE,ECDSA,DES,CBC3,SHA,,,), + CS_ENTRY(0xC00D, TLS,ECDH,RSA,WITH,3DES,EDE,CBC,SHA), + CS_ENTRY(0xC00D, ECDH,RSA,DES,CBC3,SHA,,,), + CS_ENTRY(0xC012, TLS,ECDHE,RSA,WITH,3DES,EDE,CBC,SHA), + CS_ENTRY(0xC012, ECDHE,RSA,DES,CBC3,SHA,,,), +#endif + CS_ENTRY(0xC09C, TLS,RSA,WITH,AES,128,CCM,,), + CS_ENTRY(0xC09C, AES128,CCM,,,,,,), + CS_ENTRY(0xC09D, TLS,RSA,WITH,AES,256,CCM,,), + CS_ENTRY(0xC09D, AES256,CCM,,,,,,), + CS_ENTRY(0xC0A0, TLS,RSA,WITH,AES,128,CCM,8,), + CS_ENTRY(0xC0A0, AES128,CCM8,,,,,,), + CS_ENTRY(0xC0A1, TLS,RSA,WITH,AES,256,CCM,8,), + CS_ENTRY(0xC0A1, AES256,CCM8,,,,,,), + CS_ENTRY(0xC0AC, TLS,ECDHE,ECDSA,WITH,AES,128,CCM,), + CS_ENTRY(0xC0AC, ECDHE,ECDSA,AES128,CCM,,,,), + CS_ENTRY(0xC0AD, TLS,ECDHE,ECDSA,WITH,AES,256,CCM,), + CS_ENTRY(0xC0AD, ECDHE,ECDSA,AES256,CCM,,,,), + CS_ENTRY(0xC0AE, TLS,ECDHE,ECDSA,WITH,AES,128,CCM,8), + CS_ENTRY(0xC0AE, ECDHE,ECDSA,AES128,CCM8,,,,), + CS_ENTRY(0xC0AF, TLS,ECDHE,ECDSA,WITH,AES,256,CCM,8), + CS_ENTRY(0xC0AF, ECDHE,ECDSA,AES256,CCM8,,,,), +#if defined(USE_MBEDTLS) + /* entries marked ns are "non-standard", they are not in openssl */ + CS_ENTRY(0x0041, TLS,RSA,WITH,CAMELLIA,128,CBC,SHA,), + CS_ENTRY(0x0041, CAMELLIA128,SHA,,,,,,), + CS_ENTRY(0x0045, TLS,DHE,RSA,WITH,CAMELLIA,128,CBC,SHA), + CS_ENTRY(0x0045, DHE,RSA,CAMELLIA128,SHA,,,,), + CS_ENTRY(0x0084, TLS,RSA,WITH,CAMELLIA,256,CBC,SHA,), + CS_ENTRY(0x0084, CAMELLIA256,SHA,,,,,,), + CS_ENTRY(0x0088, TLS,DHE,RSA,WITH,CAMELLIA,256,CBC,SHA), + CS_ENTRY(0x0088, DHE,RSA,CAMELLIA256,SHA,,,,), + CS_ENTRY(0x00BA, TLS,RSA,WITH,CAMELLIA,128,CBC,SHA256,), + CS_ENTRY(0x00BA, CAMELLIA128,SHA256,,,,,,), + CS_ENTRY(0x00BE, TLS,DHE,RSA,WITH,CAMELLIA,128,CBC,SHA256), + CS_ENTRY(0x00BE, DHE,RSA,CAMELLIA128,SHA256,,,,), + CS_ENTRY(0x00C0, TLS,RSA,WITH,CAMELLIA,256,CBC,SHA256,), + CS_ENTRY(0x00C0, CAMELLIA256,SHA256,,,,,,), + CS_ENTRY(0x00C4, TLS,DHE,RSA,WITH,CAMELLIA,256,CBC,SHA256), + CS_ENTRY(0x00C4, DHE,RSA,CAMELLIA256,SHA256,,,,), + CS_ENTRY(0xC037, TLS,ECDHE,PSK,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0xC037, ECDHE,PSK,AES128,CBC,SHA256,,,), + CS_ENTRY(0xC038, TLS,ECDHE,PSK,WITH,AES,256,CBC,SHA384), + CS_ENTRY(0xC038, ECDHE,PSK,AES256,CBC,SHA384,,,), + CS_ENTRY(0xC039, TLS,ECDHE,PSK,WITH,NULL,SHA,,), + CS_ENTRY(0xC039, ECDHE,PSK,NULL,SHA,,,,), + CS_ENTRY(0xC03A, TLS,ECDHE,PSK,WITH,NULL,SHA256,,), + CS_ENTRY(0xC03A, ECDHE,PSK,NULL,SHA256,,,,), + CS_ENTRY(0xC03B, TLS,ECDHE,PSK,WITH,NULL,SHA384,,), + CS_ENTRY(0xC03B, ECDHE,PSK,NULL,SHA384,,,,), + CS_ENTRY(0xC03C, TLS,RSA,WITH,ARIA,128,CBC,SHA256,), + CS_ENTRY(0xC03C, ARIA128,SHA256,,,,,,), /* ns */ + CS_ENTRY(0xC03D, TLS,RSA,WITH,ARIA,256,CBC,SHA384,), + CS_ENTRY(0xC03D, ARIA256,SHA384,,,,,,), /* ns */ + CS_ENTRY(0xC044, TLS,DHE,RSA,WITH,ARIA,128,CBC,SHA256), + CS_ENTRY(0xC044, DHE,RSA,ARIA128,SHA256,,,,), /* ns */ + CS_ENTRY(0xC045, TLS,DHE,RSA,WITH,ARIA,256,CBC,SHA384), + CS_ENTRY(0xC045, DHE,RSA,ARIA256,SHA384,,,,), /* ns */ + CS_ENTRY(0xC048, TLS,ECDHE,ECDSA,WITH,ARIA,128,CBC,SHA256), + CS_ENTRY(0xC048, ECDHE,ECDSA,ARIA128,SHA256,,,,), /* ns */ + CS_ENTRY(0xC049, TLS,ECDHE,ECDSA,WITH,ARIA,256,CBC,SHA384), + CS_ENTRY(0xC049, ECDHE,ECDSA,ARIA256,SHA384,,,,), /* ns */ + CS_ENTRY(0xC04A, TLS,ECDH,ECDSA,WITH,ARIA,128,CBC,SHA256), + CS_ENTRY(0xC04A, ECDH,ECDSA,ARIA128,SHA256,,,,), /* ns */ + CS_ENTRY(0xC04B, TLS,ECDH,ECDSA,WITH,ARIA,256,CBC,SHA384), + CS_ENTRY(0xC04B, ECDH,ECDSA,ARIA256,SHA384,,,,), /* ns */ + CS_ENTRY(0xC04C, TLS,ECDHE,RSA,WITH,ARIA,128,CBC,SHA256), + CS_ENTRY(0xC04C, ECDHE,ARIA128,SHA256,,,,,), /* ns */ + CS_ENTRY(0xC04D, TLS,ECDHE,RSA,WITH,ARIA,256,CBC,SHA384), + CS_ENTRY(0xC04D, ECDHE,ARIA256,SHA384,,,,,), /* ns */ + CS_ENTRY(0xC04E, TLS,ECDH,RSA,WITH,ARIA,128,CBC,SHA256), + CS_ENTRY(0xC04E, ECDH,ARIA128,SHA256,,,,,), /* ns */ + CS_ENTRY(0xC04F, TLS,ECDH,RSA,WITH,ARIA,256,CBC,SHA384), + CS_ENTRY(0xC04F, ECDH,ARIA256,SHA384,,,,,), /* ns */ + CS_ENTRY(0xC050, TLS,RSA,WITH,ARIA,128,GCM,SHA256,), + CS_ENTRY(0xC050, ARIA128,GCM,SHA256,,,,,), + CS_ENTRY(0xC051, TLS,RSA,WITH,ARIA,256,GCM,SHA384,), + CS_ENTRY(0xC051, ARIA256,GCM,SHA384,,,,,), + CS_ENTRY(0xC052, TLS,DHE,RSA,WITH,ARIA,128,GCM,SHA256), + CS_ENTRY(0xC052, DHE,RSA,ARIA128,GCM,SHA256,,,), + CS_ENTRY(0xC053, TLS,DHE,RSA,WITH,ARIA,256,GCM,SHA384), + CS_ENTRY(0xC053, DHE,RSA,ARIA256,GCM,SHA384,,,), + CS_ENTRY(0xC05C, TLS,ECDHE,ECDSA,WITH,ARIA,128,GCM,SHA256), + CS_ENTRY(0xC05C, ECDHE,ECDSA,ARIA128,GCM,SHA256,,,), + CS_ENTRY(0xC05D, TLS,ECDHE,ECDSA,WITH,ARIA,256,GCM,SHA384), + CS_ENTRY(0xC05D, ECDHE,ECDSA,ARIA256,GCM,SHA384,,,), + CS_ENTRY(0xC05E, TLS,ECDH,ECDSA,WITH,ARIA,128,GCM,SHA256), + CS_ENTRY(0xC05E, ECDH,ECDSA,ARIA128,GCM,SHA256,,,), /* ns */ + CS_ENTRY(0xC05F, TLS,ECDH,ECDSA,WITH,ARIA,256,GCM,SHA384), + CS_ENTRY(0xC05F, ECDH,ECDSA,ARIA256,GCM,SHA384,,,), /* ns */ + CS_ENTRY(0xC060, TLS,ECDHE,RSA,WITH,ARIA,128,GCM,SHA256), + CS_ENTRY(0xC060, ECDHE,ARIA128,GCM,SHA256,,,,), + CS_ENTRY(0xC061, TLS,ECDHE,RSA,WITH,ARIA,256,GCM,SHA384), + CS_ENTRY(0xC061, ECDHE,ARIA256,GCM,SHA384,,,,), + CS_ENTRY(0xC062, TLS,ECDH,RSA,WITH,ARIA,128,GCM,SHA256), + CS_ENTRY(0xC062, ECDH,ARIA128,GCM,SHA256,,,,), /* ns */ + CS_ENTRY(0xC063, TLS,ECDH,RSA,WITH,ARIA,256,GCM,SHA384), + CS_ENTRY(0xC063, ECDH,ARIA256,GCM,SHA384,,,,), /* ns */ + CS_ENTRY(0xC064, TLS,PSK,WITH,ARIA,128,CBC,SHA256,), + CS_ENTRY(0xC064, PSK,ARIA128,SHA256,,,,,), /* ns */ + CS_ENTRY(0xC065, TLS,PSK,WITH,ARIA,256,CBC,SHA384,), + CS_ENTRY(0xC065, PSK,ARIA256,SHA384,,,,,), /* ns */ + CS_ENTRY(0xC066, TLS,DHE,PSK,WITH,ARIA,128,CBC,SHA256), + CS_ENTRY(0xC066, DHE,PSK,ARIA128,SHA256,,,,), /* ns */ + CS_ENTRY(0xC067, TLS,DHE,PSK,WITH,ARIA,256,CBC,SHA384), + CS_ENTRY(0xC067, DHE,PSK,ARIA256,SHA384,,,,), /* ns */ + CS_ENTRY(0xC068, TLS,RSA,PSK,WITH,ARIA,128,CBC,SHA256), + CS_ENTRY(0xC068, RSA,PSK,ARIA128,SHA256,,,,), /* ns */ + CS_ENTRY(0xC069, TLS,RSA,PSK,WITH,ARIA,256,CBC,SHA384), + CS_ENTRY(0xC069, RSA,PSK,ARIA256,SHA384,,,,), /* ns */ + CS_ENTRY(0xC06A, TLS,PSK,WITH,ARIA,128,GCM,SHA256,), + CS_ENTRY(0xC06A, PSK,ARIA128,GCM,SHA256,,,,), + CS_ENTRY(0xC06B, TLS,PSK,WITH,ARIA,256,GCM,SHA384,), + CS_ENTRY(0xC06B, PSK,ARIA256,GCM,SHA384,,,,), + CS_ENTRY(0xC06C, TLS,DHE,PSK,WITH,ARIA,128,GCM,SHA256), + CS_ENTRY(0xC06C, DHE,PSK,ARIA128,GCM,SHA256,,,), + CS_ENTRY(0xC06D, TLS,DHE,PSK,WITH,ARIA,256,GCM,SHA384), + CS_ENTRY(0xC06D, DHE,PSK,ARIA256,GCM,SHA384,,,), + CS_ENTRY(0xC06E, TLS,RSA,PSK,WITH,ARIA,128,GCM,SHA256), + CS_ENTRY(0xC06E, RSA,PSK,ARIA128,GCM,SHA256,,,), + CS_ENTRY(0xC06F, TLS,RSA,PSK,WITH,ARIA,256,GCM,SHA384), + CS_ENTRY(0xC06F, RSA,PSK,ARIA256,GCM,SHA384,,,), + CS_ENTRY(0xC070, TLS,ECDHE,PSK,WITH,ARIA,128,CBC,SHA256), + CS_ENTRY(0xC070, ECDHE,PSK,ARIA128,SHA256,,,,), /* ns */ + CS_ENTRY(0xC071, TLS,ECDHE,PSK,WITH,ARIA,256,CBC,SHA384), + CS_ENTRY(0xC071, ECDHE,PSK,ARIA256,SHA384,,,,), /* ns */ + CS_ENTRY(0xC072, TLS,ECDHE,ECDSA,WITH,CAMELLIA,128,CBC,SHA256), + CS_ENTRY(0xC072, ECDHE,ECDSA,CAMELLIA128,SHA256,,,,), + CS_ENTRY(0xC073, TLS,ECDHE,ECDSA,WITH,CAMELLIA,256,CBC,SHA384), + CS_ENTRY(0xC073, ECDHE,ECDSA,CAMELLIA256,SHA384,,,,), + CS_ENTRY(0xC074, TLS,ECDH,ECDSA,WITH,CAMELLIA,128,CBC,SHA256), + CS_ENTRY(0xC074, ECDH,ECDSA,CAMELLIA128,SHA256,,,,), /* ns */ + CS_ENTRY(0xC075, TLS,ECDH,ECDSA,WITH,CAMELLIA,256,CBC,SHA384), + CS_ENTRY(0xC075, ECDH,ECDSA,CAMELLIA256,SHA384,,,,), /* ns */ + CS_ENTRY(0xC076, TLS,ECDHE,RSA,WITH,CAMELLIA,128,CBC,SHA256), + CS_ENTRY(0xC076, ECDHE,RSA,CAMELLIA128,SHA256,,,,), + CS_ENTRY(0xC077, TLS,ECDHE,RSA,WITH,CAMELLIA,256,CBC,SHA384), + CS_ENTRY(0xC077, ECDHE,RSA,CAMELLIA256,SHA384,,,,), + CS_ENTRY(0xC078, TLS,ECDH,RSA,WITH,CAMELLIA,128,CBC,SHA256), + CS_ENTRY(0xC078, ECDH,CAMELLIA128,SHA256,,,,,), /* ns */ + CS_ENTRY(0xC079, TLS,ECDH,RSA,WITH,CAMELLIA,256,CBC,SHA384), + CS_ENTRY(0xC079, ECDH,CAMELLIA256,SHA384,,,,,), /* ns */ + CS_ENTRY(0xC07A, TLS,RSA,WITH,CAMELLIA,128,GCM,SHA256,), + CS_ENTRY(0xC07A, CAMELLIA128,GCM,SHA256,,,,,), /* ns */ + CS_ENTRY(0xC07B, TLS,RSA,WITH,CAMELLIA,256,GCM,SHA384,), + CS_ENTRY(0xC07B, CAMELLIA256,GCM,SHA384,,,,,), /* ns */ + CS_ENTRY(0xC07C, TLS,DHE,RSA,WITH,CAMELLIA,128,GCM,SHA256), + CS_ENTRY(0xC07C, DHE,RSA,CAMELLIA128,GCM,SHA256,,,), /* ns */ + CS_ENTRY(0xC07D, TLS,DHE,RSA,WITH,CAMELLIA,256,GCM,SHA384), + CS_ENTRY(0xC07D, DHE,RSA,CAMELLIA256,GCM,SHA384,,,), /* ns */ + CS_ENTRY(0xC086, TLS,ECDHE,ECDSA,WITH,CAMELLIA,128,GCM,SHA256), + CS_ENTRY(0xC086, ECDHE,ECDSA,CAMELLIA128,GCM,SHA256,,,), /* ns */ + CS_ENTRY(0xC087, TLS,ECDHE,ECDSA,WITH,CAMELLIA,256,GCM,SHA384), + CS_ENTRY(0xC087, ECDHE,ECDSA,CAMELLIA256,GCM,SHA384,,,), /* ns */ + CS_ENTRY(0xC088, TLS,ECDH,ECDSA,WITH,CAMELLIA,128,GCM,SHA256), + CS_ENTRY(0xC088, ECDH,ECDSA,CAMELLIA128,GCM,SHA256,,,), /* ns */ + CS_ENTRY(0xC089, TLS,ECDH,ECDSA,WITH,CAMELLIA,256,GCM,SHA384), + CS_ENTRY(0xC089, ECDH,ECDSA,CAMELLIA256,GCM,SHA384,,,), /* ns */ + CS_ENTRY(0xC08A, TLS,ECDHE,RSA,WITH,CAMELLIA,128,GCM,SHA256), + CS_ENTRY(0xC08A, ECDHE,CAMELLIA128,GCM,SHA256,,,,), /* ns */ + CS_ENTRY(0xC08B, TLS,ECDHE,RSA,WITH,CAMELLIA,256,GCM,SHA384), + CS_ENTRY(0xC08B, ECDHE,CAMELLIA256,GCM,SHA384,,,,), /* ns */ + CS_ENTRY(0xC08C, TLS,ECDH,RSA,WITH,CAMELLIA,128,GCM,SHA256), + CS_ENTRY(0xC08C, ECDH,CAMELLIA128,GCM,SHA256,,,,), /* ns */ + CS_ENTRY(0xC08D, TLS,ECDH,RSA,WITH,CAMELLIA,256,GCM,SHA384), + CS_ENTRY(0xC08D, ECDH,CAMELLIA256,GCM,SHA384,,,,), /* ns */ + CS_ENTRY(0xC08E, TLS,PSK,WITH,CAMELLIA,128,GCM,SHA256,), + CS_ENTRY(0xC08E, PSK,CAMELLIA128,GCM,SHA256,,,,), /* ns */ + CS_ENTRY(0xC08F, TLS,PSK,WITH,CAMELLIA,256,GCM,SHA384,), + CS_ENTRY(0xC08F, PSK,CAMELLIA256,GCM,SHA384,,,,), /* ns */ + CS_ENTRY(0xC090, TLS,DHE,PSK,WITH,CAMELLIA,128,GCM,SHA256), + CS_ENTRY(0xC090, DHE,PSK,CAMELLIA128,GCM,SHA256,,,), /* ns */ + CS_ENTRY(0xC091, TLS,DHE,PSK,WITH,CAMELLIA,256,GCM,SHA384), + CS_ENTRY(0xC091, DHE,PSK,CAMELLIA256,GCM,SHA384,,,), /* ns */ + CS_ENTRY(0xC092, TLS,RSA,PSK,WITH,CAMELLIA,128,GCM,SHA256), + CS_ENTRY(0xC092, RSA,PSK,CAMELLIA128,GCM,SHA256,,,), /* ns */ + CS_ENTRY(0xC093, TLS,RSA,PSK,WITH,CAMELLIA,256,GCM,SHA384), + CS_ENTRY(0xC093, RSA,PSK,CAMELLIA256,GCM,SHA384,,,), /* ns */ + CS_ENTRY(0xC094, TLS,PSK,WITH,CAMELLIA,128,CBC,SHA256,), + CS_ENTRY(0xC094, PSK,CAMELLIA128,SHA256,,,,,), + CS_ENTRY(0xC095, TLS,PSK,WITH,CAMELLIA,256,CBC,SHA384,), + CS_ENTRY(0xC095, PSK,CAMELLIA256,SHA384,,,,,), + CS_ENTRY(0xC096, TLS,DHE,PSK,WITH,CAMELLIA,128,CBC,SHA256), + CS_ENTRY(0xC096, DHE,PSK,CAMELLIA128,SHA256,,,,), + CS_ENTRY(0xC097, TLS,DHE,PSK,WITH,CAMELLIA,256,CBC,SHA384), + CS_ENTRY(0xC097, DHE,PSK,CAMELLIA256,SHA384,,,,), + CS_ENTRY(0xC098, TLS,RSA,PSK,WITH,CAMELLIA,128,CBC,SHA256), + CS_ENTRY(0xC098, RSA,PSK,CAMELLIA128,SHA256,,,,), + CS_ENTRY(0xC099, TLS,RSA,PSK,WITH,CAMELLIA,256,CBC,SHA384), + CS_ENTRY(0xC099, RSA,PSK,CAMELLIA256,SHA384,,,,), + CS_ENTRY(0xC09A, TLS,ECDHE,PSK,WITH,CAMELLIA,128,CBC,SHA256), + CS_ENTRY(0xC09A, ECDHE,PSK,CAMELLIA128,SHA256,,,,), + CS_ENTRY(0xC09B, TLS,ECDHE,PSK,WITH,CAMELLIA,256,CBC,SHA384), + CS_ENTRY(0xC09B, ECDHE,PSK,CAMELLIA256,SHA384,,,,), + CS_ENTRY(0xC09E, TLS,DHE,RSA,WITH,AES,128,CCM,), + CS_ENTRY(0xC09E, DHE,RSA,AES128,CCM,,,,), + CS_ENTRY(0xC09F, TLS,DHE,RSA,WITH,AES,256,CCM,), + CS_ENTRY(0xC09F, DHE,RSA,AES256,CCM,,,,), + CS_ENTRY(0xC0A2, TLS,DHE,RSA,WITH,AES,128,CCM,8), + CS_ENTRY(0xC0A2, DHE,RSA,AES128,CCM8,,,,), + CS_ENTRY(0xC0A3, TLS,DHE,RSA,WITH,AES,256,CCM,8), + CS_ENTRY(0xC0A3, DHE,RSA,AES256,CCM8,,,,), + CS_ENTRY(0xC0A4, TLS,PSK,WITH,AES,128,CCM,,), + CS_ENTRY(0xC0A4, PSK,AES128,CCM,,,,,), + CS_ENTRY(0xC0A5, TLS,PSK,WITH,AES,256,CCM,,), + CS_ENTRY(0xC0A5, PSK,AES256,CCM,,,,,), + CS_ENTRY(0xC0A6, TLS,DHE,PSK,WITH,AES,128,CCM,), + CS_ENTRY(0xC0A6, DHE,PSK,AES128,CCM,,,,), + CS_ENTRY(0xC0A7, TLS,DHE,PSK,WITH,AES,256,CCM,), + CS_ENTRY(0xC0A7, DHE,PSK,AES256,CCM,,,,), + CS_ENTRY(0xC0A8, TLS,PSK,WITH,AES,128,CCM,8,), + CS_ENTRY(0xC0A8, PSK,AES128,CCM8,,,,,), + CS_ENTRY(0xC0A9, TLS,PSK,WITH,AES,256,CCM,8,), + CS_ENTRY(0xC0A9, PSK,AES256,CCM8,,,,,), + CS_ENTRY(0xC0AA, TLS,PSK,DHE,WITH,AES,128,CCM,8), + CS_ENTRY(0xC0AA, DHE,PSK,AES128,CCM8,,,,), + CS_ENTRY(0xC0AB, TLS,PSK,DHE,WITH,AES,256,CCM,8), + CS_ENTRY(0xC0AB, DHE,PSK,AES256,CCM8,,,,), + CS_ENTRY(0xCCAA, TLS,DHE,RSA,WITH,CHACHA20,POLY1305,SHA256,), + CS_ENTRY(0xCCAA, DHE,RSA,CHACHA20,POLY1305,,,,), + CS_ENTRY(0xCCAC, TLS,ECDHE,PSK,WITH,CHACHA20,POLY1305,SHA256,), + CS_ENTRY(0xCCAC, ECDHE,PSK,CHACHA20,POLY1305,,,,), + CS_ENTRY(0xCCAD, TLS,DHE,PSK,WITH,CHACHA20,POLY1305,SHA256,), + CS_ENTRY(0xCCAD, DHE,PSK,CHACHA20,POLY1305,,,,), + CS_ENTRY(0xCCAE, TLS,RSA,PSK,WITH,CHACHA20,POLY1305,SHA256,), + CS_ENTRY(0xCCAE, RSA,PSK,CHACHA20,POLY1305,,,,), +#endif +}; +#define CS_LIST_LEN (sizeof(cs_list) / sizeof(cs_list[0])) + +static int cs_str_to_zip(const char *cs_str, size_t cs_len, + uint8_t zip[6]) +{ + uint8_t indexes[8] = {0}; + const char *entry, *cur; + const char *nxt = cs_str; + const char *end = cs_str + cs_len; + char separator = '-'; + int idx, i = 0; + size_t len; + + /* split the cipher string by '-' or '_' */ + if(strncasecompare(cs_str, "TLS", 3)) + separator = '_'; + + do { + if(i == 8) + return -1; + + /* determine the length of the part */ + cur = nxt; + for(; nxt < end && *nxt != '\0' && *nxt != separator; nxt++); + len = nxt - cur; + + /* lookup index for the part (skip empty string at 0) */ + for(idx = 1, entry = cs_txt + 1; idx < CS_TXT_LEN; idx++) { + size_t elen = strlen(entry); + if(elen == len && strncasecompare(entry, cur, len)) + break; + entry += elen + 1; + } + if(idx == CS_TXT_LEN) + return -1; + + indexes[i++] = (uint8_t) idx; + } while(nxt < end && *(nxt++) != '\0'); + + /* zip the 8 indexes into 48 bits */ + zip[0] = (uint8_t) (indexes[0] << 2 | (indexes[1] & 0x3F) >> 4); + zip[1] = (uint8_t) (indexes[1] << 4 | (indexes[2] & 0x3F) >> 2); + zip[2] = (uint8_t) (indexes[2] << 6 | (indexes[3] & 0x3F)); + zip[3] = (uint8_t) (indexes[4] << 2 | (indexes[5] & 0x3F) >> 4); + zip[4] = (uint8_t) (indexes[5] << 4 | (indexes[6] & 0x3F) >> 2); + zip[5] = (uint8_t) (indexes[6] << 6 | (indexes[7] & 0x3F)); + + return 0; +} + +static int cs_zip_to_str(const uint8_t zip[6], + char *buf, size_t buf_size) +{ + uint8_t indexes[8] = {0}; + const char *entry; + char separator = '-'; + int idx, i, r; + size_t len = 0; + + /* unzip the 8 indexes */ + indexes[0] = zip[0] >> 2; + indexes[1] = ((zip[0] << 4) & 0x3F) | zip[1] >> 4; + indexes[2] = ((zip[1] << 2) & 0x3F) | zip[2] >> 6; + indexes[3] = ((zip[2] << 0) & 0x3F); + indexes[4] = zip[3] >> 2; + indexes[5] = ((zip[3] << 4) & 0x3F) | zip[4] >> 4; + indexes[6] = ((zip[4] << 2) & 0x3F) | zip[5] >> 6; + indexes[7] = ((zip[5] << 0) & 0x3F); + + if(indexes[0] == CS_TXT_IDX_TLS) + separator = '_'; + + for(i = 0; i < 8 && indexes[i] != 0 && len < buf_size; i++) { + if(indexes[i] >= CS_TXT_LEN) + return -1; + + /* lookup the part string for the index (skip empty string at 0) */ + for(idx = 1, entry = cs_txt + 1; idx < indexes[i]; idx++) { + size_t elen = strlen(entry); + entry += elen + 1; + } + + /* append the part string to the buffer */ + if(i > 0) + r = msnprintf(&buf[len], buf_size - len, "%c%s", separator, entry); + else + r = msnprintf(&buf[len], buf_size - len, "%s", entry); + + if(r < 0) + return -1; + len += r; + } + + return 0; +} + +uint16_t Curl_cipher_suite_lookup_id(const char *cs_str, size_t cs_len) +{ + size_t i; + uint8_t zip[6]; + + if(cs_len > 0 && cs_str_to_zip(cs_str, cs_len, zip) == 0) { + for(i = 0; i < CS_LIST_LEN; i++) { + if(memcmp(cs_list[i].zip, zip, sizeof(zip)) == 0) + return cs_list[i].id; + } + } + + return 0; +} + +static bool cs_is_separator(char c) +{ + switch(c) { + case ' ': + case '\t': + case ':': + case ',': + case ';': + return true; + default:; + } + return false; +} + +uint16_t Curl_cipher_suite_walk_str(const char **str, const char **end) +{ + /* move string pointer to first non-separator or end of string */ + for(; cs_is_separator(*str[0]); (*str)++); + + /* move end pointer to next separator or end of string */ + for(*end = *str; *end[0] != '\0' && !cs_is_separator(*end[0]); (*end)++); + + return Curl_cipher_suite_lookup_id(*str, *end - *str); +} + +int Curl_cipher_suite_get_str(uint16_t id, char *buf, size_t buf_size, + bool prefer_rfc) +{ + size_t i, j = CS_LIST_LEN; + int r = -1; + + for(i = 0; i < CS_LIST_LEN; i++) { + if(cs_list[i].id != id) + continue; + if((cs_list[i].zip[0] >> 2 != CS_TXT_IDX_TLS) == !prefer_rfc) { + j = i; + break; + } + if(j == CS_LIST_LEN) + j = i; + } + + if(j < CS_LIST_LEN) + r = cs_zip_to_str(cs_list[j].zip, buf, buf_size); + + if(r < 0) + msnprintf(buf, buf_size, "TLS_UNKNOWN_0x%04x", id); + + return r; +} + +#endif /* defined(USE_MBEDTLS) || defined(USE_BEARSSL) */ diff --git a/third_party/curl/lib/vtls/cipher_suite.h b/third_party/curl/lib/vtls/cipher_suite.h new file mode 100644 index 0000000..c139979 --- /dev/null +++ b/third_party/curl/lib/vtls/cipher_suite.h @@ -0,0 +1,46 @@ +#ifndef HEADER_CURL_CIPHER_SUITE_H +#define HEADER_CURL_CIPHER_SUITE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Jan Venekamp, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_MBEDTLS) || defined(USE_BEARSSL) +#include + +/* Lookup IANA id for cipher suite string, returns 0 if not recognized */ +uint16_t Curl_cipher_suite_lookup_id(const char *cs_str, size_t cs_len); + +/* Walk over cipher suite string, update str and end pointers to next + cipher suite in string, returns IANA id of that suite if recognized */ +uint16_t Curl_cipher_suite_walk_str(const char **str, const char **end); + +/* Copy openssl or RFC name for cipher suite in supplied buffer. + Caller is responsible to supply sufficiently large buffer (size + of 64 should suffice), excess bytes are silently truncated. */ +int Curl_cipher_suite_get_str(uint16_t id, char *buf, size_t buf_size, + bool prefer_rfc); + +#endif /* defined(USE_MBEDTLS) || defined(USE_BEARSSL) */ +#endif /* HEADER_CURL_CIPHER_SUITE_H */ diff --git a/third_party/curl/lib/vtls/gtls.c b/third_party/curl/lib/vtls/gtls.c new file mode 100644 index 0000000..5cf3bf9 --- /dev/null +++ b/third_party/curl/lib/vtls/gtls.c @@ -0,0 +1,1864 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Source file for all GnuTLS-specific code for the TLS/SSL layer. No code + * but vtls.c should ever call or use these functions. + * + * Note: don't use the GnuTLS' *_t variable type names in this source code, + * since they were not present in 1.0.X. + */ + +#include "curl_setup.h" + +#ifdef USE_GNUTLS + +#include +#include +#include +#include +#include + +#include "urldata.h" +#include "sendf.h" +#include "inet_pton.h" +#include "keylog.h" +#include "gtls.h" +#include "vtls.h" +#include "vtls_int.h" +#include "vauth/vauth.h" +#include "parsedate.h" +#include "connect.h" /* for the connect timeout */ +#include "select.h" +#include "strcase.h" +#include "warnless.h" +#include "x509asn1.h" +#include "multiif.h" +#include "curl_printf.h" +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + +#ifndef ARRAYSIZE +#define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) +#endif + +#define QUIC_PRIORITY \ + "NORMAL:-VERS-ALL:+VERS-TLS1.3:-CIPHER-ALL:+AES-128-GCM:+AES-256-GCM:" \ + "+CHACHA20-POLY1305:+AES-128-CCM:-GROUP-ALL:+GROUP-SECP256R1:" \ + "+GROUP-X25519:+GROUP-SECP384R1:+GROUP-SECP521R1:" \ + "%DISABLE_TLS13_COMPAT_MODE" + +/* Enable GnuTLS debugging by defining GTLSDEBUG */ +/*#define GTLSDEBUG */ + +#ifdef GTLSDEBUG +static void tls_log_func(int level, const char *str) +{ + fprintf(stderr, "|<%d>| %s", level, str); +} +#endif +static bool gtls_inited = FALSE; + +#if !defined(GNUTLS_VERSION_NUMBER) || (GNUTLS_VERSION_NUMBER < 0x03010a) +#error "too old GnuTLS version" +#endif + +# include + +struct gtls_ssl_backend_data { + struct gtls_ctx gtls; +}; + +static ssize_t gtls_push(void *s, const void *buf, size_t blen) +{ + struct Curl_cfilter *cf = s; + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + ssize_t nwritten; + CURLcode result; + + DEBUGASSERT(data); + nwritten = Curl_conn_cf_send(cf->next, data, buf, blen, &result); + CURL_TRC_CF(data, cf, "gtls_push(len=%zu) -> %zd, err=%d", + blen, nwritten, result); + backend->gtls.io_result = result; + if(nwritten < 0) { + gnutls_transport_set_errno(backend->gtls.session, + (CURLE_AGAIN == result)? EAGAIN : EINVAL); + nwritten = -1; + } + return nwritten; +} + +static ssize_t gtls_pull(void *s, void *buf, size_t blen) +{ + struct Curl_cfilter *cf = s; + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + ssize_t nread; + CURLcode result; + + DEBUGASSERT(data); + if(!backend->gtls.trust_setup) { + result = Curl_gtls_client_trust_setup(cf, data, &backend->gtls); + if(result) { + gnutls_transport_set_errno(backend->gtls.session, EINVAL); + backend->gtls.io_result = result; + return -1; + } + } + + nread = Curl_conn_cf_recv(cf->next, data, buf, blen, &result); + CURL_TRC_CF(data, cf, "glts_pull(len=%zu) -> %zd, err=%d", + blen, nread, result); + backend->gtls.io_result = result; + if(nread < 0) { + gnutls_transport_set_errno(backend->gtls.session, + (CURLE_AGAIN == result)? EAGAIN : EINVAL); + nread = -1; + } + else if(nread == 0) + connssl->peer_closed = TRUE; + return nread; +} + +/* gtls_init() + * + * Global GnuTLS init, called from Curl_ssl_init(). This calls functions that + * are not thread-safe and thus this function itself is not thread-safe and + * must only be called from within curl_global_init() to keep the thread + * situation under control! + */ +static int gtls_init(void) +{ + int ret = 1; + if(!gtls_inited) { + ret = gnutls_global_init()?0:1; +#ifdef GTLSDEBUG + gnutls_global_set_log_function(tls_log_func); + gnutls_global_set_log_level(2); +#endif + gtls_inited = TRUE; + } + return ret; +} + +static void gtls_cleanup(void) +{ + if(gtls_inited) { + gnutls_global_deinit(); + gtls_inited = FALSE; + } +} + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +static void showtime(struct Curl_easy *data, + const char *text, + time_t stamp) +{ + struct tm buffer; + const struct tm *tm = &buffer; + char str[96]; + CURLcode result = Curl_gmtime(stamp, &buffer); + if(result) + return; + + msnprintf(str, + sizeof(str), + " %s: %s, %02d %s %4d %02d:%02d:%02d GMT", + text, + Curl_wkday[tm->tm_wday?tm->tm_wday-1:6], + tm->tm_mday, + Curl_month[tm->tm_mon], + tm->tm_year + 1900, + tm->tm_hour, + tm->tm_min, + tm->tm_sec); + infof(data, "%s", str); +} +#endif + +static gnutls_datum_t load_file(const char *file) +{ + FILE *f; + gnutls_datum_t loaded_file = { NULL, 0 }; + long filelen; + void *ptr; + + f = fopen(file, "rb"); + if(!f) + return loaded_file; + if(fseek(f, 0, SEEK_END) != 0 + || (filelen = ftell(f)) < 0 + || fseek(f, 0, SEEK_SET) != 0 + || !(ptr = malloc((size_t)filelen))) + goto out; + if(fread(ptr, 1, (size_t)filelen, f) < (size_t)filelen) { + free(ptr); + goto out; + } + + loaded_file.data = ptr; + loaded_file.size = (unsigned int)filelen; +out: + fclose(f); + return loaded_file; +} + +static void unload_file(gnutls_datum_t data) +{ + free(data.data); +} + + +/* this function does a SSL/TLS (re-)handshake */ +static CURLcode handshake(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool duringconnect, + bool nonblocking) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + gnutls_session_t session; + curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data); + + DEBUGASSERT(backend); + session = backend->gtls.session; + + for(;;) { + timediff_t timeout_ms; + int rc; + + /* check allowed time left */ + timeout_ms = Curl_timeleft(data, NULL, duringconnect); + + if(timeout_ms < 0) { + /* no need to continue if time already is up */ + failf(data, "SSL connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + + /* if ssl is expecting something, check if it's available. */ + if(connssl->connecting_state == ssl_connect_2_reading + || connssl->connecting_state == ssl_connect_2_writing) { + int what; + curl_socket_t writefd = ssl_connect_2_writing == + connssl->connecting_state?sockfd:CURL_SOCKET_BAD; + curl_socket_t readfd = ssl_connect_2_reading == + connssl->connecting_state?sockfd:CURL_SOCKET_BAD; + + what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, + nonblocking?0: + timeout_ms?timeout_ms:1000); + if(what < 0) { + /* fatal error */ + failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); + return CURLE_SSL_CONNECT_ERROR; + } + else if(0 == what) { + if(nonblocking) + return CURLE_OK; + else if(timeout_ms) { + /* timeout */ + failf(data, "SSL connection timeout at %ld", (long)timeout_ms); + return CURLE_OPERATION_TIMEDOUT; + } + } + /* socket is readable or writable */ + } + + backend->gtls.io_result = CURLE_OK; + rc = gnutls_handshake(session); + + if(!backend->gtls.trust_setup) { + /* After having send off the ClientHello, we prepare the trust + * store to verify the coming certificate from the server */ + CURLcode result = Curl_gtls_client_trust_setup(cf, data, &backend->gtls); + if(result) + return result; + } + + if((rc == GNUTLS_E_AGAIN) || (rc == GNUTLS_E_INTERRUPTED)) { + connssl->connecting_state = + gnutls_record_get_direction(session)? + ssl_connect_2_writing:ssl_connect_2_reading; + continue; + } + else if((rc < 0) && !gnutls_error_is_fatal(rc)) { + const char *strerr = NULL; + + if(rc == GNUTLS_E_WARNING_ALERT_RECEIVED) { + int alert = gnutls_alert_get(session); + strerr = gnutls_alert_get_name(alert); + } + + if(!strerr) + strerr = gnutls_strerror(rc); + + infof(data, "gnutls_handshake() warning: %s", strerr); + continue; + } + else if((rc < 0) && backend->gtls.io_result) { + return backend->gtls.io_result; + } + else if(rc < 0) { + const char *strerr = NULL; + + if(rc == GNUTLS_E_FATAL_ALERT_RECEIVED) { + int alert = gnutls_alert_get(session); + strerr = gnutls_alert_get_name(alert); + } + + if(!strerr) + strerr = gnutls_strerror(rc); + + failf(data, "gnutls_handshake() failed: %s", strerr); + return CURLE_SSL_CONNECT_ERROR; + } + + /* Reset our connect state machine */ + connssl->connecting_state = ssl_connect_1; + return CURLE_OK; + } +} + +static gnutls_x509_crt_fmt_t do_file_type(const char *type) +{ + if(!type || !type[0]) + return GNUTLS_X509_FMT_PEM; + if(strcasecompare(type, "PEM")) + return GNUTLS_X509_FMT_PEM; + if(strcasecompare(type, "DER")) + return GNUTLS_X509_FMT_DER; + return GNUTLS_X509_FMT_PEM; /* default to PEM */ +} + +#define GNUTLS_CIPHERS "NORMAL:-ARCFOUR-128:-CTYPE-ALL:+CTYPE-X509" +/* If GnuTLS was compiled without support for SRP it will error out if SRP is + requested in the priority string, so treat it specially + */ +#define GNUTLS_SRP "+SRP" + +static CURLcode +set_ssl_version_min_max(struct Curl_easy *data, + struct ssl_peer *peer, + struct ssl_primary_config *conn_config, + const char **prioritylist, + const char *tls13support) +{ + long ssl_version = conn_config->version; + long ssl_version_max = conn_config->version_max; + + if(peer->transport == TRNSPRT_QUIC) { + if((ssl_version != CURL_SSLVERSION_DEFAULT) && + (ssl_version < CURL_SSLVERSION_TLSv1_3)) { + failf(data, "QUIC needs at least TLS version 1.3"); + return CURLE_SSL_CONNECT_ERROR; + } + *prioritylist = QUIC_PRIORITY; + return CURLE_OK; + } + + if((ssl_version == CURL_SSLVERSION_DEFAULT) || + (ssl_version == CURL_SSLVERSION_TLSv1)) + ssl_version = CURL_SSLVERSION_TLSv1_0; + if(ssl_version_max == CURL_SSLVERSION_MAX_NONE) + ssl_version_max = CURL_SSLVERSION_MAX_DEFAULT; + if(!tls13support) { + /* If the running GnuTLS doesn't support TLS 1.3, we must not specify a + prioritylist involving that since it will make GnuTLS return an en + error back at us */ + if((ssl_version_max == CURL_SSLVERSION_MAX_TLSv1_3) || + (ssl_version_max == CURL_SSLVERSION_MAX_DEFAULT)) { + ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_2; + } + } + else if(ssl_version_max == CURL_SSLVERSION_MAX_DEFAULT) { + ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_3; + } + + switch(ssl_version | ssl_version_max) { + case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_0: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.0"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_1: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.1:+VERS-TLS1.0"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_2: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.2:+VERS-TLS1.1:+VERS-TLS1.0"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_1 | CURL_SSLVERSION_MAX_TLSv1_1: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.1"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_1 | CURL_SSLVERSION_MAX_TLSv1_2: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.2:+VERS-TLS1.1"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_2 | CURL_SSLVERSION_MAX_TLSv1_2: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.2"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_3 | CURL_SSLVERSION_MAX_TLSv1_3: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.3"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_3: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_1 | CURL_SSLVERSION_MAX_TLSv1_3: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.3:+VERS-TLS1.2:+VERS-TLS1.1"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_2 | CURL_SSLVERSION_MAX_TLSv1_3: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.3:+VERS-TLS1.2"; + return CURLE_OK; + } + + failf(data, "GnuTLS: cannot set ssl protocol"); + return CURLE_SSL_CONNECT_ERROR; +} + +CURLcode Curl_gtls_client_trust_setup(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct gtls_ctx *gtls) +{ + struct ssl_primary_config *config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + int rc; + + CURL_TRC_CF(data, cf, "setup trust anchors and CRLs"); + if(config->verifypeer) { + bool imported_native_ca = false; + + if(ssl_config->native_ca_store) { + rc = gnutls_certificate_set_x509_system_trust(gtls->cred); + if(rc < 0) + infof(data, "error reading native ca store (%s), continuing anyway", + gnutls_strerror(rc)); + else { + infof(data, "found %d certificates in native ca store", rc); + if(rc > 0) + imported_native_ca = true; + } + } + + if(config->CAfile) { + /* set the trusted CA cert bundle file */ + gnutls_certificate_set_verify_flags(gtls->cred, + GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT); + + rc = gnutls_certificate_set_x509_trust_file(gtls->cred, + config->CAfile, + GNUTLS_X509_FMT_PEM); + if(rc < 0) { + infof(data, "error reading ca cert file %s (%s)%s", + config->CAfile, gnutls_strerror(rc), + (imported_native_ca ? ", continuing anyway" : "")); + if(!imported_native_ca) { + ssl_config->certverifyresult = rc; + return CURLE_SSL_CACERT_BADFILE; + } + } + else + infof(data, "found %d certificates in %s", rc, config->CAfile); + } + + if(config->CApath) { + /* set the trusted CA cert directory */ + rc = gnutls_certificate_set_x509_trust_dir(gtls->cred, + config->CApath, + GNUTLS_X509_FMT_PEM); + if(rc < 0) { + infof(data, "error reading ca cert file %s (%s)%s", + config->CApath, gnutls_strerror(rc), + (imported_native_ca ? ", continuing anyway" : "")); + if(!imported_native_ca) { + ssl_config->certverifyresult = rc; + return CURLE_SSL_CACERT_BADFILE; + } + } + else + infof(data, "found %d certificates in %s", rc, config->CApath); + } + } + + if(config->CRLfile) { + /* set the CRL list file */ + rc = gnutls_certificate_set_x509_crl_file(gtls->cred, + config->CRLfile, + GNUTLS_X509_FMT_PEM); + if(rc < 0) { + failf(data, "error reading crl file %s (%s)", + config->CRLfile, gnutls_strerror(rc)); + return CURLE_SSL_CRL_BADFILE; + } + else + infof(data, "found %d CRL in %s", rc, config->CRLfile); + } + + gtls->trust_setup = TRUE; + return CURLE_OK; +} + +static void gtls_sessionid_free(void *sessionid, size_t idsize) +{ + (void)idsize; + free(sessionid); +} + +static CURLcode gtls_update_session_id(struct Curl_cfilter *cf, + struct Curl_easy *data, + gnutls_session_t session) +{ + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + struct ssl_connect_data *connssl = cf->ctx; + CURLcode result = CURLE_OK; + + if(ssl_config->primary.sessionid) { + /* we always unconditionally get the session id here, as even if we + already got it from the cache and asked to use it in the connection, it + might've been rejected and then a new one is in use now and we need to + detect that. */ + void *connect_sessionid; + size_t connect_idsize = 0; + + /* get the session ID data size */ + gnutls_session_get_data(session, NULL, &connect_idsize); + connect_sessionid = malloc(connect_idsize); /* get a buffer for it */ + if(!connect_sessionid) { + return CURLE_OUT_OF_MEMORY; + } + else { + bool incache; + void *ssl_sessionid; + + /* extract session ID to the allocated buffer */ + gnutls_session_get_data(session, connect_sessionid, &connect_idsize); + + DEBUGF(infof(data, "get session id (len=%zu) and store in cache", + connect_idsize)); + Curl_ssl_sessionid_lock(data); + incache = !(Curl_ssl_getsessionid(cf, data, &connssl->peer, + &ssl_sessionid, NULL)); + if(incache) { + /* there was one before in the cache, so instead of risking that the + previous one was rejected, we just kill that and store the new */ + Curl_ssl_delsessionid(data, ssl_sessionid); + } + + /* store this session id, takes ownership */ + result = Curl_ssl_addsessionid(cf, data, &connssl->peer, + connect_sessionid, connect_idsize, + gtls_sessionid_free); + Curl_ssl_sessionid_unlock(data); + } + } + return result; +} + +static int gtls_handshake_cb(gnutls_session_t session, unsigned int htype, + unsigned when, unsigned int incoming, + const gnutls_datum_t *msg) +{ + struct Curl_cfilter *cf = gnutls_session_get_ptr(session); + + (void)msg; + (void)incoming; + if(when) { /* after message has been processed */ + struct Curl_easy *data = CF_DATA_CURRENT(cf); + if(data) { + DEBUGF(infof(data, "handshake: %s message type %d", + incoming? "incoming" : "outgoing", htype)); + switch(htype) { + case GNUTLS_HANDSHAKE_NEW_SESSION_TICKET: { + gtls_update_session_id(cf, data, session); + break; + } + default: + break; + } + } + } + return 0; +} + +static CURLcode gtls_client_init(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + struct gtls_ctx *gtls) +{ + struct ssl_primary_config *config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + unsigned int init_flags; + int rc; + bool sni = TRUE; /* default is SNI enabled */ + const char *prioritylist; + const char *err = NULL; + const char *tls13support; + CURLcode result; + + if(!gtls_inited) + gtls_init(); + + if(config->version == CURL_SSLVERSION_SSLv2) { + failf(data, "GnuTLS does not support SSLv2"); + return CURLE_SSL_CONNECT_ERROR; + } + else if(config->version == CURL_SSLVERSION_SSLv3) + sni = FALSE; /* SSLv3 has no SNI */ + + /* allocate a cred struct */ + rc = gnutls_certificate_allocate_credentials(>ls->cred); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc)); + return CURLE_SSL_CONNECT_ERROR; + } + +#ifdef USE_GNUTLS_SRP + if(config->username && Curl_auth_allowed_to_host(data)) { + infof(data, "Using TLS-SRP username: %s", config->username); + + rc = gnutls_srp_allocate_client_credentials(>ls->srp_client_cred); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "gnutls_srp_allocate_client_cred() failed: %s", + gnutls_strerror(rc)); + return CURLE_OUT_OF_MEMORY; + } + + rc = gnutls_srp_set_client_credentials(gtls->srp_client_cred, + config->username, + config->password); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "gnutls_srp_set_client_cred() failed: %s", + gnutls_strerror(rc)); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + } +#endif + + ssl_config->certverifyresult = 0; + + /* Initialize TLS session as a client */ + init_flags = GNUTLS_CLIENT; + +#if defined(GNUTLS_FORCE_CLIENT_CERT) + init_flags |= GNUTLS_FORCE_CLIENT_CERT; +#endif + +#if defined(GNUTLS_NO_TICKETS) + /* Disable TLS session tickets */ + init_flags |= GNUTLS_NO_TICKETS; +#endif + + rc = gnutls_init(>ls->session, init_flags); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "gnutls_init() failed: %d", rc); + return CURLE_SSL_CONNECT_ERROR; + } + + if(sni && peer->sni) { + if(gnutls_server_name_set(gtls->session, GNUTLS_NAME_DNS, + peer->sni, strlen(peer->sni)) < 0) { + failf(data, "Failed to set SNI"); + return CURLE_SSL_CONNECT_ERROR; + } + } + + /* Use default priorities */ + rc = gnutls_set_default_priority(gtls->session); + if(rc != GNUTLS_E_SUCCESS) + return CURLE_SSL_CONNECT_ERROR; + + /* "In GnuTLS 3.6.5, TLS 1.3 is enabled by default" */ + tls13support = gnutls_check_version("3.6.5"); + + /* Ensure +SRP comes at the *end* of all relevant strings so that it can be + * removed if a run-time error indicates that SRP is not supported by this + * GnuTLS version */ + + if(config->version == CURL_SSLVERSION_SSLv2 || + config->version == CURL_SSLVERSION_SSLv3) { + failf(data, "GnuTLS does not support SSLv2 or SSLv3"); + return CURLE_SSL_CONNECT_ERROR; + } + + if(config->version == CURL_SSLVERSION_TLSv1_3) { + if(!tls13support) { + failf(data, "This GnuTLS installation does not support TLS 1.3"); + return CURLE_SSL_CONNECT_ERROR; + } + } + + /* At this point we know we have a supported TLS version, so set it */ + result = set_ssl_version_min_max(data, peer, + config, &prioritylist, tls13support); + if(result) + return result; + +#ifdef USE_GNUTLS_SRP + /* Only add SRP to the cipher list if SRP is requested. Otherwise + * GnuTLS will disable TLS 1.3 support. */ + if(config->username) { + char *prioritysrp = aprintf("%s:" GNUTLS_SRP, prioritylist); + if(!prioritysrp) + return CURLE_OUT_OF_MEMORY; + rc = gnutls_priority_set_direct(gtls->session, prioritysrp, &err); + free(prioritysrp); + + if((rc == GNUTLS_E_INVALID_REQUEST) && err) { + infof(data, "This GnuTLS does not support SRP"); + } + } + else { +#endif + infof(data, "GnuTLS ciphers: %s", prioritylist); + rc = gnutls_priority_set_direct(gtls->session, prioritylist, &err); +#ifdef USE_GNUTLS_SRP + } +#endif + + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "Error %d setting GnuTLS cipher list starting with %s", + rc, err); + return CURLE_SSL_CONNECT_ERROR; + } + + if(config->clientcert) { + if(!gtls->trust_setup) { + result = Curl_gtls_client_trust_setup(cf, data, gtls); + if(result) + return result; + } + if(ssl_config->key_passwd) { + const unsigned int supported_key_encryption_algorithms = + GNUTLS_PKCS_USE_PKCS12_3DES | GNUTLS_PKCS_USE_PKCS12_ARCFOUR | + GNUTLS_PKCS_USE_PKCS12_RC2_40 | GNUTLS_PKCS_USE_PBES2_3DES | + GNUTLS_PKCS_USE_PBES2_AES_128 | GNUTLS_PKCS_USE_PBES2_AES_192 | + GNUTLS_PKCS_USE_PBES2_AES_256; + rc = gnutls_certificate_set_x509_key_file2( + gtls->cred, + config->clientcert, + ssl_config->key ? ssl_config->key : config->clientcert, + do_file_type(ssl_config->cert_type), + ssl_config->key_passwd, + supported_key_encryption_algorithms); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, + "error reading X.509 potentially-encrypted key file: %s", + gnutls_strerror(rc)); + return CURLE_SSL_CONNECT_ERROR; + } + } + else { + if(gnutls_certificate_set_x509_key_file( + gtls->cred, + config->clientcert, + ssl_config->key ? ssl_config->key : config->clientcert, + do_file_type(ssl_config->cert_type) ) != + GNUTLS_E_SUCCESS) { + failf(data, "error reading X.509 key or certificate file"); + return CURLE_SSL_CONNECT_ERROR; + } + } + } + +#ifdef USE_GNUTLS_SRP + /* put the credentials to the current session */ + if(config->username) { + rc = gnutls_credentials_set(gtls->session, GNUTLS_CRD_SRP, + gtls->srp_client_cred); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc)); + return CURLE_SSL_CONNECT_ERROR; + } + } + else +#endif + { + rc = gnutls_credentials_set(gtls->session, GNUTLS_CRD_CERTIFICATE, + gtls->cred); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc)); + return CURLE_SSL_CONNECT_ERROR; + } + } + + if(config->verifystatus) { + rc = gnutls_ocsp_status_request_enable_client(gtls->session, + NULL, 0, NULL); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "gnutls_ocsp_status_request_enable_client() failed: %d", rc); + return CURLE_SSL_CONNECT_ERROR; + } + } + + return CURLE_OK; +} + +static int keylog_callback(gnutls_session_t session, const char *label, + const gnutls_datum_t *secret) +{ + gnutls_datum_t crandom; + gnutls_datum_t srandom; + + gnutls_session_get_random(session, &crandom, &srandom); + if(crandom.size != 32) { + return -1; + } + + Curl_tls_keylog_write(label, crandom.data, secret->data, secret->size); + return 0; +} + +CURLcode Curl_gtls_ctx_init(struct gtls_ctx *gctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + const unsigned char *alpn, size_t alpn_len, + Curl_gtls_ctx_setup_cb *cb_setup, + void *cb_user_data, + void *ssl_user_data) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + CURLcode result; + + DEBUGASSERT(gctx); + + result = gtls_client_init(cf, data, peer, gctx); + if(result) + return result; + + gnutls_session_set_ptr(gctx->session, ssl_user_data); + + if(cb_setup) { + result = cb_setup(cf, data, cb_user_data); + if(result) + return result; + } + + /* Open the file if a TLS or QUIC backend has not done this before. */ + Curl_tls_keylog_open(); + if(Curl_tls_keylog_enabled()) { + gnutls_session_set_keylog_function(gctx->session, keylog_callback); + } + + /* convert the ALPN string from our arguments to a list of strings + * that gnutls wants and will convert internally back to this very + * string for sending to the server. nice. */ + if(alpn && alpn_len) { + gnutls_datum_t alpns[5]; + size_t i, alen = alpn_len; + unsigned char *s = (unsigned char *)alpn; + unsigned char slen; + for(i = 0; (i < ARRAYSIZE(alpns)) && alen; ++i) { + slen = s[0]; + if(slen >= alen) + return CURLE_FAILED_INIT; + alpns[i].data = s + 1; + alpns[i].size = slen; + s += slen + 1; + alen -= (size_t)slen + 1; + } + if(alen) /* not all alpn chars used, wrong format or too many */ + return CURLE_FAILED_INIT; + if(i && gnutls_alpn_set_protocols(gctx->session, + alpns, (unsigned int)i, + GNUTLS_ALPN_MANDATORY)) { + failf(data, "failed setting ALPN"); + return CURLE_SSL_CONNECT_ERROR; + } + } + + /* This might be a reconnect, so we check for a session ID in the cache + to speed up things */ + if(conn_config->sessionid) { + void *ssl_sessionid; + size_t ssl_idsize; + + Curl_ssl_sessionid_lock(data); + if(!Curl_ssl_getsessionid(cf, data, peer, &ssl_sessionid, &ssl_idsize)) { + /* we got a session id, use it! */ + int rc; + + rc = gnutls_session_set_data(gctx->session, ssl_sessionid, ssl_idsize); + if(rc < 0) + infof(data, "SSL failed to set session ID"); + else + infof(data, "SSL reusing session ID (size=%zu)", ssl_idsize); + } + Curl_ssl_sessionid_unlock(data); + } + return CURLE_OK; +} + +static CURLcode +gtls_connect_step1(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + struct alpn_proto_buf proto; + CURLcode result; + + DEBUGASSERT(backend); + DEBUGASSERT(ssl_connect_1 == connssl->connecting_state); + + if(connssl->state == ssl_connection_complete) + /* to make us tolerant against being called more than once for the + same connection */ + return CURLE_OK; + + memset(&proto, 0, sizeof(proto)); + if(connssl->alpn) { + result = Curl_alpn_to_proto_buf(&proto, connssl->alpn); + if(result) { + failf(data, "Error determining ALPN"); + return CURLE_SSL_CONNECT_ERROR; + } + } + + result = Curl_gtls_ctx_init(&backend->gtls, cf, data, &connssl->peer, + proto.data, proto.len, NULL, NULL, cf); + if(result) + return result; + + gnutls_handshake_set_hook_function(backend->gtls.session, + GNUTLS_HANDSHAKE_ANY, GNUTLS_HOOK_POST, + gtls_handshake_cb); + + /* register callback functions and handle to send and receive data. */ + gnutls_transport_set_ptr(backend->gtls.session, cf); + gnutls_transport_set_push_function(backend->gtls.session, gtls_push); + gnutls_transport_set_pull_function(backend->gtls.session, gtls_pull); + + return CURLE_OK; +} + +static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, + gnutls_x509_crt_t cert, + const char *pinnedpubkey) +{ + /* Scratch */ + size_t len1 = 0, len2 = 0; + unsigned char *buff1 = NULL; + + gnutls_pubkey_t key = NULL; + + /* Result is returned to caller */ + CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; + + /* if a path wasn't specified, don't pin */ + if(!pinnedpubkey) + return CURLE_OK; + + if(!cert) + return result; + + do { + int ret; + + /* Begin Gyrations to get the public key */ + gnutls_pubkey_init(&key); + + ret = gnutls_pubkey_import_x509(key, cert, 0); + if(ret < 0) + break; /* failed */ + + ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, NULL, &len1); + if(ret != GNUTLS_E_SHORT_MEMORY_BUFFER || len1 == 0) + break; /* failed */ + + buff1 = malloc(len1); + if(!buff1) + break; /* failed */ + + len2 = len1; + + ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, buff1, &len2); + if(ret < 0 || len1 != len2) + break; /* failed */ + + /* End Gyrations */ + + /* The one good exit point */ + result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1); + } while(0); + + if(key) + gnutls_pubkey_deinit(key); + + Curl_safefree(buff1); + + return result; +} + +CURLcode +Curl_gtls_verifyserver(struct Curl_easy *data, + gnutls_session_t session, + struct ssl_primary_config *config, + struct ssl_config_data *ssl_config, + struct ssl_peer *peer, + const char *pinned_key) +{ + unsigned int cert_list_size; + const gnutls_datum_t *chainp; + unsigned int verify_status = 0; + gnutls_x509_crt_t x509_cert, x509_issuer; + gnutls_datum_t issuerp; + gnutls_datum_t certfields; + char certname[65] = ""; /* limited to 64 chars by ASN.1 */ + size_t size; + time_t certclock; + int rc; + CURLcode result = CURLE_OK; +#ifndef CURL_DISABLE_VERBOSE_STRINGS + const char *ptr; + unsigned int algo; + unsigned int bits; + gnutls_protocol_t version = gnutls_protocol_get_version(session); +#endif + long * const certverifyresult = &ssl_config->certverifyresult; + +#ifndef CURL_DISABLE_VERBOSE_STRINGS + /* the name of the cipher suite used, e.g. ECDHE_RSA_AES_256_GCM_SHA384. */ + ptr = gnutls_cipher_suite_get_name(gnutls_kx_get(session), + gnutls_cipher_get(session), + gnutls_mac_get(session)); + + infof(data, "SSL connection using %s / %s", + gnutls_protocol_get_name(version), ptr); +#endif + + /* This function will return the peer's raw certificate (chain) as sent by + the peer. These certificates are in raw format (DER encoded for + X.509). In case of a X.509 then a certificate list may be present. The + first certificate in the list is the peer's certificate, following the + issuer's certificate, then the issuer's issuer etc. */ + + chainp = gnutls_certificate_get_peers(session, &cert_list_size); + if(!chainp) { + if(config->verifypeer || + config->verifyhost || + config->issuercert) { +#ifdef USE_GNUTLS_SRP + if(ssl_config->primary.username && !config->verifypeer && + gnutls_cipher_get(session)) { + /* no peer cert, but auth is ok if we have SRP user and cipher and no + peer verify */ + } + else { +#endif + failf(data, "failed to get server cert"); + *certverifyresult = GNUTLS_E_NO_CERTIFICATE_FOUND; + return CURLE_PEER_FAILED_VERIFICATION; +#ifdef USE_GNUTLS_SRP + } +#endif + } + infof(data, " common name: WARNING couldn't obtain"); + } + + if(data->set.ssl.certinfo && chainp) { + unsigned int i; + + result = Curl_ssl_init_certinfo(data, cert_list_size); + if(result) + return result; + + for(i = 0; i < cert_list_size; i++) { + const char *beg = (const char *) chainp[i].data; + const char *end = beg + chainp[i].size; + + result = Curl_extract_certinfo(data, i, beg, end); + if(result) + return result; + } + } + + if(config->verifypeer) { + /* This function will try to verify the peer's certificate and return its + status (trusted, invalid etc.). The value of status should be one or + more of the gnutls_certificate_status_t enumerated elements bitwise + or'd. To avoid denial of service attacks some default upper limits + regarding the certificate key size and chain size are set. To override + them use gnutls_certificate_set_verify_limits(). */ + + rc = gnutls_certificate_verify_peers2(session, &verify_status); + if(rc < 0) { + failf(data, "server cert verify failed: %d", rc); + *certverifyresult = rc; + return CURLE_SSL_CONNECT_ERROR; + } + + *certverifyresult = verify_status; + + /* verify_status is a bitmask of gnutls_certificate_status bits */ + if(verify_status & GNUTLS_CERT_INVALID) { + if(config->verifypeer) { + failf(data, "server certificate verification failed. CAfile: %s " + "CRLfile: %s", config->CAfile ? config->CAfile: + "none", + ssl_config->primary.CRLfile ? + ssl_config->primary.CRLfile : "none"); + return CURLE_PEER_FAILED_VERIFICATION; + } + else + infof(data, " server certificate verification FAILED"); + } + else + infof(data, " server certificate verification OK"); + } + else + infof(data, " server certificate verification SKIPPED"); + + if(config->verifystatus) { + if(gnutls_ocsp_status_request_is_checked(session, 0) == 0) { + gnutls_datum_t status_request; + gnutls_ocsp_resp_t ocsp_resp; + + gnutls_ocsp_cert_status_t status; + gnutls_x509_crl_reason_t reason; + + rc = gnutls_ocsp_status_request_get(session, &status_request); + + infof(data, " server certificate status verification FAILED"); + + if(rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) { + failf(data, "No OCSP response received"); + return CURLE_SSL_INVALIDCERTSTATUS; + } + + if(rc < 0) { + failf(data, "Invalid OCSP response received"); + return CURLE_SSL_INVALIDCERTSTATUS; + } + + gnutls_ocsp_resp_init(&ocsp_resp); + + rc = gnutls_ocsp_resp_import(ocsp_resp, &status_request); + if(rc < 0) { + failf(data, "Invalid OCSP response received"); + return CURLE_SSL_INVALIDCERTSTATUS; + } + + (void)gnutls_ocsp_resp_get_single(ocsp_resp, 0, NULL, NULL, NULL, NULL, + &status, NULL, NULL, NULL, &reason); + + switch(status) { + case GNUTLS_OCSP_CERT_GOOD: + break; + + case GNUTLS_OCSP_CERT_REVOKED: { + const char *crl_reason; + + switch(reason) { + default: + case GNUTLS_X509_CRLREASON_UNSPECIFIED: + crl_reason = "unspecified reason"; + break; + + case GNUTLS_X509_CRLREASON_KEYCOMPROMISE: + crl_reason = "private key compromised"; + break; + + case GNUTLS_X509_CRLREASON_CACOMPROMISE: + crl_reason = "CA compromised"; + break; + + case GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED: + crl_reason = "affiliation has changed"; + break; + + case GNUTLS_X509_CRLREASON_SUPERSEDED: + crl_reason = "certificate superseded"; + break; + + case GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION: + crl_reason = "operation has ceased"; + break; + + case GNUTLS_X509_CRLREASON_CERTIFICATEHOLD: + crl_reason = "certificate is on hold"; + break; + + case GNUTLS_X509_CRLREASON_REMOVEFROMCRL: + crl_reason = "will be removed from delta CRL"; + break; + + case GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN: + crl_reason = "privilege withdrawn"; + break; + + case GNUTLS_X509_CRLREASON_AACOMPROMISE: + crl_reason = "AA compromised"; + break; + } + + failf(data, "Server certificate was revoked: %s", crl_reason); + break; + } + + default: + case GNUTLS_OCSP_CERT_UNKNOWN: + failf(data, "Server certificate status is unknown"); + break; + } + + gnutls_ocsp_resp_deinit(ocsp_resp); + + return CURLE_SSL_INVALIDCERTSTATUS; + } + else + infof(data, " server certificate status verification OK"); + } + else + infof(data, " server certificate status verification SKIPPED"); + + /* initialize an X.509 certificate structure. */ + gnutls_x509_crt_init(&x509_cert); + + if(chainp) + /* convert the given DER or PEM encoded Certificate to the native + gnutls_x509_crt_t format */ + gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER); + + if(config->issuercert) { + gnutls_x509_crt_init(&x509_issuer); + issuerp = load_file(config->issuercert); + gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM); + rc = gnutls_x509_crt_check_issuer(x509_cert, x509_issuer); + gnutls_x509_crt_deinit(x509_issuer); + unload_file(issuerp); + if(rc <= 0) { + failf(data, "server certificate issuer check failed (IssuerCert: %s)", + config->issuercert?config->issuercert:"none"); + gnutls_x509_crt_deinit(x509_cert); + return CURLE_SSL_ISSUER_ERROR; + } + infof(data, " server certificate issuer check OK (Issuer Cert: %s)", + config->issuercert?config->issuercert:"none"); + } + + size = sizeof(certname); + rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME, + 0, /* the first and only one */ + FALSE, + certname, + &size); + if(rc) { + infof(data, "error fetching CN from cert:%s", + gnutls_strerror(rc)); + } + + /* This function will check if the given certificate's subject matches the + given hostname. This is a basic implementation of the matching described + in RFC2818 (HTTPS), which takes into account wildcards, and the subject + alternative name PKIX extension. Returns non zero on success, and zero on + failure. */ + rc = gnutls_x509_crt_check_hostname(x509_cert, peer->hostname); +#if GNUTLS_VERSION_NUMBER < 0x030306 + /* Before 3.3.6, gnutls_x509_crt_check_hostname() didn't check IP + addresses. */ + if(!rc) { +#ifdef USE_IPV6 + #define use_addr in6_addr +#else + #define use_addr in_addr +#endif + unsigned char addrbuf[sizeof(struct use_addr)]; + size_t addrlen = 0; + + if(Curl_inet_pton(AF_INET, peer->hostname, addrbuf) > 0) + addrlen = 4; +#ifdef USE_IPV6 + else if(Curl_inet_pton(AF_INET6, peer->hostname, addrbuf) > 0) + addrlen = 16; +#endif + + if(addrlen) { + unsigned char certaddr[sizeof(struct use_addr)]; + int i; + + for(i = 0; ; i++) { + size_t certaddrlen = sizeof(certaddr); + int ret = gnutls_x509_crt_get_subject_alt_name(x509_cert, i, certaddr, + &certaddrlen, NULL); + /* If this happens, it wasn't an IP address. */ + if(ret == GNUTLS_E_SHORT_MEMORY_BUFFER) + continue; + if(ret < 0) + break; + if(ret != GNUTLS_SAN_IPADDRESS) + continue; + if(certaddrlen == addrlen && !memcmp(addrbuf, certaddr, addrlen)) { + rc = 1; + break; + } + } + } + } +#endif + if(!rc) { + if(config->verifyhost) { + failf(data, "SSL: certificate subject name (%s) does not match " + "target host name '%s'", certname, peer->dispname); + gnutls_x509_crt_deinit(x509_cert); + return CURLE_PEER_FAILED_VERIFICATION; + } + else + infof(data, " common name: %s (does not match '%s')", + certname, peer->dispname); + } + else + infof(data, " common name: %s (matched)", certname); + + /* Check for time-based validity */ + certclock = gnutls_x509_crt_get_expiration_time(x509_cert); + + if(certclock == (time_t)-1) { + if(config->verifypeer) { + failf(data, "server cert expiration date verify failed"); + *certverifyresult = GNUTLS_CERT_EXPIRED; + gnutls_x509_crt_deinit(x509_cert); + return CURLE_SSL_CONNECT_ERROR; + } + else + infof(data, " server certificate expiration date verify FAILED"); + } + else { + if(certclock < time(NULL)) { + if(config->verifypeer) { + failf(data, "server certificate expiration date has passed."); + *certverifyresult = GNUTLS_CERT_EXPIRED; + gnutls_x509_crt_deinit(x509_cert); + return CURLE_PEER_FAILED_VERIFICATION; + } + else + infof(data, " server certificate expiration date FAILED"); + } + else + infof(data, " server certificate expiration date OK"); + } + + certclock = gnutls_x509_crt_get_activation_time(x509_cert); + + if(certclock == (time_t)-1) { + if(config->verifypeer) { + failf(data, "server cert activation date verify failed"); + *certverifyresult = GNUTLS_CERT_NOT_ACTIVATED; + gnutls_x509_crt_deinit(x509_cert); + return CURLE_SSL_CONNECT_ERROR; + } + else + infof(data, " server certificate activation date verify FAILED"); + } + else { + if(certclock > time(NULL)) { + if(config->verifypeer) { + failf(data, "server certificate not activated yet."); + *certverifyresult = GNUTLS_CERT_NOT_ACTIVATED; + gnutls_x509_crt_deinit(x509_cert); + return CURLE_PEER_FAILED_VERIFICATION; + } + else + infof(data, " server certificate activation date FAILED"); + } + else + infof(data, " server certificate activation date OK"); + } + + if(pinned_key) { + result = pkp_pin_peer_pubkey(data, x509_cert, pinned_key); + if(result != CURLE_OK) { + failf(data, "SSL: public key does not match pinned public key"); + gnutls_x509_crt_deinit(x509_cert); + return result; + } + } + + /* Show: + + - subject + - start date + - expire date + - common name + - issuer + + */ + +#ifndef CURL_DISABLE_VERBOSE_STRINGS + /* public key algorithm's parameters */ + algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits); + infof(data, " certificate public key: %s", + gnutls_pk_algorithm_get_name(algo)); + + /* version of the X.509 certificate. */ + infof(data, " certificate version: #%d", + gnutls_x509_crt_get_version(x509_cert)); + + + rc = gnutls_x509_crt_get_dn2(x509_cert, &certfields); + if(rc) + infof(data, "Failed to get certificate name"); + else { + infof(data, " subject: %s", certfields.data); + + certclock = gnutls_x509_crt_get_activation_time(x509_cert); + showtime(data, "start date", certclock); + + certclock = gnutls_x509_crt_get_expiration_time(x509_cert); + showtime(data, "expire date", certclock); + + gnutls_free(certfields.data); + } + + rc = gnutls_x509_crt_get_issuer_dn2(x509_cert, &certfields); + if(rc) + infof(data, "Failed to get certificate issuer"); + else { + infof(data, " issuer: %s", certfields.data); + + gnutls_free(certfields.data); + } +#endif + + gnutls_x509_crt_deinit(x509_cert); + + return result; +} + +static CURLcode gtls_verifyserver(struct Curl_cfilter *cf, + struct Curl_easy *data, + gnutls_session_t session) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); +#ifndef CURL_DISABLE_PROXY + const char *pinned_key = Curl_ssl_cf_is_proxy(cf)? + data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY]: + data->set.str[STRING_SSL_PINNEDPUBLICKEY]; +#else + const char *pinned_key = data->set.str[STRING_SSL_PINNEDPUBLICKEY]; +#endif + CURLcode result; + + result = Curl_gtls_verifyserver(data, session, conn_config, ssl_config, + &connssl->peer, pinned_key); + if(result) + goto out; + + if(connssl->alpn) { + gnutls_datum_t proto; + int rc; + + rc = gnutls_alpn_get_selected_protocol(session, &proto); + if(rc == 0) + Curl_alpn_set_negotiated(cf, data, proto.data, proto.size); + else + Curl_alpn_set_negotiated(cf, data, NULL, 0); + } + + /* Only on TLSv1.2 or lower do we have the session id now. For + * TLSv1.3 we get it via a SESSION_TICKET message that arrives later. */ + if(gnutls_protocol_get_version(session) < GNUTLS_TLS1_3) + result = gtls_update_session_id(cf, data, session); + +out: + return result; +} + +/* + * This function is called after the TCP connect has completed. Setup the TLS + * layer and do all necessary magic. + */ +/* We use connssl->connecting_state to keep track of the connection status; + there are three states: 'ssl_connect_1' (not started yet or complete), + 'ssl_connect_2_reading' (waiting for data from server), and + 'ssl_connect_2_writing' (waiting to be able to write). + */ +static CURLcode +gtls_connect_common(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool nonblocking, + bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + int rc; + CURLcode result = CURLE_OK; + + /* Initiate the connection, if not already done */ + if(ssl_connect_1 == connssl->connecting_state) { + rc = gtls_connect_step1(cf, data); + if(rc) { + result = rc; + goto out; + } + } + + rc = handshake(cf, data, TRUE, nonblocking); + if(rc) { + /* handshake() sets its own error message with failf() */ + result = rc; + goto out; + } + + /* Finish connecting once the handshake is done */ + if(ssl_connect_1 == connssl->connecting_state) { + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + gnutls_session_t session; + DEBUGASSERT(backend); + session = backend->gtls.session; + rc = gtls_verifyserver(cf, data, session); + if(rc) { + result = rc; + goto out; + } + connssl->state = ssl_connection_complete; + } + +out: + *done = ssl_connect_1 == connssl->connecting_state; + + return result; +} + +static CURLcode gtls_connect_nonblocking(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + return gtls_connect_common(cf, data, TRUE, done); +} + +static CURLcode gtls_connect(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURLcode result; + bool done = FALSE; + + result = gtls_connect_common(cf, data, FALSE, &done); + if(result) + return result; + + DEBUGASSERT(done); + + return CURLE_OK; +} + +static bool gtls_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct ssl_connect_data *ctx = cf->ctx; + struct gtls_ssl_backend_data *backend; + + (void)data; + DEBUGASSERT(ctx && ctx->backend); + backend = (struct gtls_ssl_backend_data *)ctx->backend; + if(backend->gtls.session && + 0 != gnutls_record_check_pending(backend->gtls.session)) + return TRUE; + return FALSE; +} + +static ssize_t gtls_send(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *mem, + size_t len, + CURLcode *curlcode) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + ssize_t rc; + + (void)data; + DEBUGASSERT(backend); + backend->gtls.io_result = CURLE_OK; + rc = gnutls_record_send(backend->gtls.session, mem, len); + + if(rc < 0) { + *curlcode = (rc == GNUTLS_E_AGAIN)? + CURLE_AGAIN : + (backend->gtls.io_result? backend->gtls.io_result : CURLE_SEND_ERROR); + + rc = -1; + } + + return rc; +} + +static void gtls_close(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + + (void) data; + DEBUGASSERT(backend); + + if(backend->gtls.session) { + char buf[32]; + /* Maybe the server has already sent a close notify alert. + Read it to avoid an RST on the TCP connection. */ + (void)gnutls_record_recv(backend->gtls.session, buf, sizeof(buf)); + gnutls_bye(backend->gtls.session, GNUTLS_SHUT_WR); + gnutls_deinit(backend->gtls.session); + backend->gtls.session = NULL; + } + if(backend->gtls.cred) { + gnutls_certificate_free_credentials(backend->gtls.cred); + backend->gtls.cred = NULL; + } +#ifdef USE_GNUTLS_SRP + if(backend->gtls.srp_client_cred) { + gnutls_srp_free_client_credentials(backend->gtls.srp_client_cred); + backend->gtls.srp_client_cred = NULL; + } +#endif +} + +/* + * This function is called to shut down the SSL layer but keep the + * socket open (CCC - Clear Command Channel) + */ +static int gtls_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + int retval = 0; + + DEBUGASSERT(backend); + +#ifndef CURL_DISABLE_FTP + /* This has only been tested on the proftpd server, and the mod_tls code + sends a close notify alert without waiting for a close notify alert in + response. Thus we wait for a close notify alert from the server, but + we do not send one. Let's hope other servers do the same... */ + + if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE) + gnutls_bye(backend->gtls.session, GNUTLS_SHUT_WR); +#endif + + if(backend->gtls.session) { + ssize_t result; + bool done = FALSE; + char buf[120]; + + while(!done && !connssl->peer_closed) { + int what = SOCKET_READABLE(Curl_conn_cf_get_socket(cf, data), + SSL_SHUTDOWN_TIMEOUT); + if(what > 0) { + /* Something to read, let's do it and hope that it is the close + notify alert from the server */ + result = gnutls_record_recv(backend->gtls.session, + buf, sizeof(buf)); + switch(result) { + case 0: + /* This is the expected response. There was no data but only + the close notify alert */ + done = TRUE; + break; + case GNUTLS_E_AGAIN: + case GNUTLS_E_INTERRUPTED: + infof(data, "GNUTLS_E_AGAIN || GNUTLS_E_INTERRUPTED"); + break; + default: + retval = -1; + done = TRUE; + break; + } + } + else if(0 == what) { + /* timeout */ + failf(data, "SSL shutdown timeout"); + done = TRUE; + } + else { + /* anything that gets here is fatally bad */ + failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); + retval = -1; + done = TRUE; + } + } + gnutls_deinit(backend->gtls.session); + } + gnutls_certificate_free_credentials(backend->gtls.cred); + +#ifdef USE_GNUTLS_SRP + { + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + if(ssl_config->primary.username) + gnutls_srp_free_client_credentials(backend->gtls.srp_client_cred); + } +#endif + + backend->gtls.cred = NULL; + backend->gtls.session = NULL; + + return retval; +} + +static ssize_t gtls_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, + char *buf, + size_t buffersize, + CURLcode *curlcode) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + ssize_t ret; + + (void)data; + DEBUGASSERT(backend); + + backend->gtls.io_result = CURLE_OK; + ret = gnutls_record_recv(backend->gtls.session, buf, buffersize); + if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) { + *curlcode = CURLE_AGAIN; + ret = -1; + goto out; + } + + if(ret == GNUTLS_E_REHANDSHAKE) { + /* BLOCKING call, this is bad but a work-around for now. Fixing this "the + proper way" takes a whole lot of work. */ + CURLcode result = handshake(cf, data, FALSE, FALSE); + if(result) + /* handshake() writes error message on its own */ + *curlcode = result; + else + *curlcode = CURLE_AGAIN; /* then return as if this was a wouldblock */ + ret = -1; + goto out; + } + + if(ret < 0) { + failf(data, "GnuTLS recv error (%d): %s", + + (int)ret, gnutls_strerror((int)ret)); + *curlcode = backend->gtls.io_result? + backend->gtls.io_result : CURLE_RECV_ERROR; + ret = -1; + goto out; + } + +out: + return ret; +} + +static size_t gtls_version(char *buffer, size_t size) +{ + return msnprintf(buffer, size, "GnuTLS/%s", gnutls_check_version(NULL)); +} + +/* data might be NULL! */ +static CURLcode gtls_random(struct Curl_easy *data, + unsigned char *entropy, size_t length) +{ + int rc; + (void)data; + rc = gnutls_rnd(GNUTLS_RND_RANDOM, entropy, length); + return rc?CURLE_FAILED_INIT:CURLE_OK; +} + +static CURLcode gtls_sha256sum(const unsigned char *tmp, /* input */ + size_t tmplen, + unsigned char *sha256sum, /* output */ + size_t sha256len) +{ + struct sha256_ctx SHA256pw; + sha256_init(&SHA256pw); + sha256_update(&SHA256pw, (unsigned int)tmplen, tmp); + sha256_digest(&SHA256pw, (unsigned int)sha256len, sha256sum); + return CURLE_OK; +} + +static bool gtls_cert_status_request(void) +{ + return TRUE; +} + +static void *gtls_get_internals(struct ssl_connect_data *connssl, + CURLINFO info UNUSED_PARAM) +{ + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + (void)info; + DEBUGASSERT(backend); + return backend->gtls.session; +} + +const struct Curl_ssl Curl_ssl_gnutls = { + { CURLSSLBACKEND_GNUTLS, "gnutls" }, /* info */ + + SSLSUPP_CA_PATH | + SSLSUPP_CERTINFO | + SSLSUPP_PINNEDPUBKEY | + SSLSUPP_HTTPS_PROXY, + + sizeof(struct gtls_ssl_backend_data), + + gtls_init, /* init */ + gtls_cleanup, /* cleanup */ + gtls_version, /* version */ + Curl_none_check_cxn, /* check_cxn */ + gtls_shutdown, /* shutdown */ + gtls_data_pending, /* data_pending */ + gtls_random, /* random */ + gtls_cert_status_request, /* cert_status_request */ + gtls_connect, /* connect */ + gtls_connect_nonblocking, /* connect_nonblocking */ + Curl_ssl_adjust_pollset, /* adjust_pollset */ + gtls_get_internals, /* get_internals */ + gtls_close, /* close_one */ + Curl_none_close_all, /* close_all */ + Curl_none_set_engine, /* set_engine */ + Curl_none_set_engine_default, /* set_engine_default */ + Curl_none_engines_list, /* engines_list */ + Curl_none_false_start, /* false_start */ + gtls_sha256sum, /* sha256sum */ + NULL, /* associate_connection */ + NULL, /* disassociate_connection */ + NULL, /* free_multi_ssl_backend_data */ + gtls_recv, /* recv decrypted data */ + gtls_send, /* send data to encrypt */ +}; + +#endif /* USE_GNUTLS */ diff --git a/third_party/curl/lib/vtls/gtls.h b/third_party/curl/lib/vtls/gtls.h new file mode 100644 index 0000000..f8388b3 --- /dev/null +++ b/third_party/curl/lib/vtls/gtls.h @@ -0,0 +1,85 @@ +#ifndef HEADER_CURL_GTLS_H +#define HEADER_CURL_GTLS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include + +#ifdef USE_GNUTLS + +#include + +#ifdef HAVE_GNUTLS_SRP +/* the function exists */ +#ifdef USE_TLS_SRP +/* the functionality is not disabled */ +#define USE_GNUTLS_SRP +#endif +#endif + +struct Curl_easy; +struct Curl_cfilter; +struct ssl_primary_config; +struct ssl_config_data; +struct ssl_peer; + +struct gtls_ctx { + gnutls_session_t session; + gnutls_certificate_credentials_t cred; +#ifdef USE_GNUTLS_SRP + gnutls_srp_client_credentials_t srp_client_cred; +#endif + CURLcode io_result; /* result of last IO cfilter operation */ + BIT(trust_setup); /* x509 anchors + CRLs have been set up */ +}; + +typedef CURLcode Curl_gtls_ctx_setup_cb(struct Curl_cfilter *cf, + struct Curl_easy *data, + void *user_data); + +CURLcode Curl_gtls_ctx_init(struct gtls_ctx *gctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + const unsigned char *alpn, size_t alpn_len, + Curl_gtls_ctx_setup_cb *cb_setup, + void *cb_user_data, + void *ssl_user_data); + +CURLcode Curl_gtls_client_trust_setup(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct gtls_ctx *gtls); + +CURLcode Curl_gtls_verifyserver(struct Curl_easy *data, + gnutls_session_t session, + struct ssl_primary_config *config, + struct ssl_config_data *ssl_config, + struct ssl_peer *peer, + const char *pinned_key); + +extern const struct Curl_ssl Curl_ssl_gnutls; + +#endif /* USE_GNUTLS */ +#endif /* HEADER_CURL_GTLS_H */ diff --git a/third_party/curl/lib/vtls/hostcheck.c b/third_party/curl/lib/vtls/hostcheck.c new file mode 100644 index 0000000..2726dca --- /dev/null +++ b/third_party/curl/lib/vtls/hostcheck.c @@ -0,0 +1,135 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_OPENSSL) \ + || defined(USE_SCHANNEL) +/* these backends use functions from this file */ + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#include "curl_memrchr.h" + +#include "hostcheck.h" +#include "strcase.h" +#include "hostip.h" + +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + +/* check the two input strings with given length, but do not + assume they end in nul-bytes */ +static bool pmatch(const char *hostname, size_t hostlen, + const char *pattern, size_t patternlen) +{ + if(hostlen != patternlen) + return FALSE; + return strncasecompare(hostname, pattern, hostlen); +} + +/* + * Match a hostname against a wildcard pattern. + * E.g. + * "foo.host.com" matches "*.host.com". + * + * We use the matching rule described in RFC6125, section 6.4.3. + * https://datatracker.ietf.org/doc/html/rfc6125#section-6.4.3 + * + * In addition: ignore trailing dots in the host names and wildcards, so that + * the names are used normalized. This is what the browsers do. + * + * Do not allow wildcard matching on IP numbers. There are apparently + * certificates being used with an IP address in the CN field, thus making no + * apparent distinction between a name and an IP. We need to detect the use of + * an IP address and not wildcard match on such names. + * + * Only match on "*" being used for the leftmost label, not "a*", "a*b" nor + * "*b". + * + * Return TRUE on a match. FALSE if not. + * + * @unittest: 1397 + */ + +static bool hostmatch(const char *hostname, + size_t hostlen, + const char *pattern, + size_t patternlen) +{ + const char *pattern_label_end; + + DEBUGASSERT(pattern); + DEBUGASSERT(patternlen); + DEBUGASSERT(hostname); + DEBUGASSERT(hostlen); + + /* normalize pattern and hostname by stripping off trailing dots */ + if(hostname[hostlen-1]=='.') + hostlen--; + if(pattern[patternlen-1]=='.') + patternlen--; + + if(strncmp(pattern, "*.", 2)) + return pmatch(hostname, hostlen, pattern, patternlen); + + /* detect IP address as hostname and fail the match if so */ + else if(Curl_host_is_ipnum(hostname)) + return FALSE; + + /* We require at least 2 dots in the pattern to avoid too wide wildcard + match. */ + pattern_label_end = memchr(pattern, '.', patternlen); + if(!pattern_label_end || + (memrchr(pattern, '.', patternlen) == pattern_label_end)) + return pmatch(hostname, hostlen, pattern, patternlen); + else { + const char *hostname_label_end = memchr(hostname, '.', hostlen); + if(hostname_label_end) { + size_t skiphost = hostname_label_end - hostname; + size_t skiplen = pattern_label_end - pattern; + return pmatch(hostname_label_end, hostlen - skiphost, + pattern_label_end, patternlen - skiplen); + } + } + return FALSE; +} + +/* + * Curl_cert_hostcheck() returns TRUE if a match and FALSE if not. + */ +bool Curl_cert_hostcheck(const char *match, size_t matchlen, + const char *hostname, size_t hostlen) +{ + if(match && *match && hostname && *hostname) + return hostmatch(hostname, hostlen, match, matchlen); + return FALSE; +} + +#endif /* OPENSSL or SCHANNEL */ diff --git a/third_party/curl/lib/vtls/hostcheck.h b/third_party/curl/lib/vtls/hostcheck.h new file mode 100644 index 0000000..22a1ac2 --- /dev/null +++ b/third_party/curl/lib/vtls/hostcheck.h @@ -0,0 +1,33 @@ +#ifndef HEADER_CURL_HOSTCHECK_H +#define HEADER_CURL_HOSTCHECK_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include + +/* returns TRUE if there's a match */ +bool Curl_cert_hostcheck(const char *match_pattern, size_t matchlen, + const char *hostname, size_t hostlen); + +#endif /* HEADER_CURL_HOSTCHECK_H */ diff --git a/third_party/curl/lib/vtls/keylog.c b/third_party/curl/lib/vtls/keylog.c new file mode 100644 index 0000000..ab7baaa --- /dev/null +++ b/third_party/curl/lib/vtls/keylog.c @@ -0,0 +1,167 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_OPENSSL) || \ + defined(USE_GNUTLS) || \ + defined(USE_WOLFSSL) || \ + (defined(USE_NGTCP2) && defined(USE_NGHTTP3)) || \ + defined(USE_QUICHE) + +#include "keylog.h" +#include + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +#define KEYLOG_LABEL_MAXLEN (sizeof("CLIENT_HANDSHAKE_TRAFFIC_SECRET") - 1) + +#define CLIENT_RANDOM_SIZE 32 + +/* + * The master secret in TLS 1.2 and before is always 48 bytes. In TLS 1.3, the + * secret size depends on the cipher suite's hash function which is 32 bytes + * for SHA-256 and 48 bytes for SHA-384. + */ +#define SECRET_MAXLEN 48 + + +/* The fp for the open SSLKEYLOGFILE, or NULL if not open */ +static FILE *keylog_file_fp; + +void +Curl_tls_keylog_open(void) +{ + char *keylog_file_name; + + if(!keylog_file_fp) { + keylog_file_name = curl_getenv("SSLKEYLOGFILE"); + if(keylog_file_name) { + keylog_file_fp = fopen(keylog_file_name, FOPEN_APPENDTEXT); + if(keylog_file_fp) { +#ifdef _WIN32 + if(setvbuf(keylog_file_fp, NULL, _IONBF, 0)) +#else + if(setvbuf(keylog_file_fp, NULL, _IOLBF, 4096)) +#endif + { + fclose(keylog_file_fp); + keylog_file_fp = NULL; + } + } + Curl_safefree(keylog_file_name); + } + } +} + +void +Curl_tls_keylog_close(void) +{ + if(keylog_file_fp) { + fclose(keylog_file_fp); + keylog_file_fp = NULL; + } +} + +bool +Curl_tls_keylog_enabled(void) +{ + return keylog_file_fp != NULL; +} + +bool +Curl_tls_keylog_write_line(const char *line) +{ + /* The current maximum valid keylog line length LF and NUL is 195. */ + size_t linelen; + char buf[256]; + + if(!keylog_file_fp || !line) { + return false; + } + + linelen = strlen(line); + if(linelen == 0 || linelen > sizeof(buf) - 2) { + /* Empty line or too big to fit in a LF and NUL. */ + return false; + } + + memcpy(buf, line, linelen); + if(line[linelen - 1] != '\n') { + buf[linelen++] = '\n'; + } + buf[linelen] = '\0'; + + /* Using fputs here instead of fprintf since libcurl's fprintf replacement + may not be thread-safe. */ + fputs(buf, keylog_file_fp); + return true; +} + +bool +Curl_tls_keylog_write(const char *label, + const unsigned char client_random[CLIENT_RANDOM_SIZE], + const unsigned char *secret, size_t secretlen) +{ + const char *hex = "0123456789ABCDEF"; + size_t pos, i; + char line[KEYLOG_LABEL_MAXLEN + 1 + 2 * CLIENT_RANDOM_SIZE + 1 + + 2 * SECRET_MAXLEN + 1 + 1]; + + if(!keylog_file_fp) { + return false; + } + + pos = strlen(label); + if(pos > KEYLOG_LABEL_MAXLEN || !secretlen || secretlen > SECRET_MAXLEN) { + /* Should never happen - sanity check anyway. */ + return false; + } + + memcpy(line, label, pos); + line[pos++] = ' '; + + /* Client Random */ + for(i = 0; i < CLIENT_RANDOM_SIZE; i++) { + line[pos++] = hex[client_random[i] >> 4]; + line[pos++] = hex[client_random[i] & 0xF]; + } + line[pos++] = ' '; + + /* Secret */ + for(i = 0; i < secretlen; i++) { + line[pos++] = hex[secret[i] >> 4]; + line[pos++] = hex[secret[i] & 0xF]; + } + line[pos++] = '\n'; + line[pos] = '\0'; + + /* Using fputs here instead of fprintf since libcurl's fprintf replacement + may not be thread-safe. */ + fputs(line, keylog_file_fp); + return true; +} + +#endif /* TLS or QUIC backend */ diff --git a/third_party/curl/lib/vtls/keylog.h b/third_party/curl/lib/vtls/keylog.h new file mode 100644 index 0000000..eff5bf3 --- /dev/null +++ b/third_party/curl/lib/vtls/keylog.h @@ -0,0 +1,58 @@ +#ifndef HEADER_CURL_KEYLOG_H +#define HEADER_CURL_KEYLOG_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* + * Opens the TLS key log file if requested by the user. The SSLKEYLOGFILE + * environment variable specifies the output file. + */ +void Curl_tls_keylog_open(void); + +/* + * Closes the TLS key log file if not already. + */ +void Curl_tls_keylog_close(void); + +/* + * Returns true if the user successfully enabled the TLS key log file. + */ +bool Curl_tls_keylog_enabled(void); + +/* + * Appends a key log file entry. + * Returns true iff the key log file is open and a valid entry was provided. + */ +bool Curl_tls_keylog_write(const char *label, + const unsigned char client_random[32], + const unsigned char *secret, size_t secretlen); + +/* + * Appends a line to the key log file, ensure it is terminated by a LF. + * Returns true iff the key log file is open and a valid line was provided. + */ +bool Curl_tls_keylog_write_line(const char *line); + +#endif /* HEADER_CURL_KEYLOG_H */ diff --git a/third_party/curl/lib/vtls/mbedtls.c b/third_party/curl/lib/vtls/mbedtls.c new file mode 100644 index 0000000..ec0b10d --- /dev/null +++ b/third_party/curl/lib/vtls/mbedtls.c @@ -0,0 +1,1509 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (C) Hoi-Ho Chan, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Source file for all mbedTLS-specific code for the TLS/SSL layer. No code + * but vtls.c should ever call or use these functions. + * + */ + +#include "curl_setup.h" + +#ifdef USE_MBEDTLS + +/* Define this to enable lots of debugging for mbedTLS */ +/* #define MBEDTLS_DEBUG */ + +#ifdef __GNUC__ +#pragma GCC diagnostic push +/* mbedTLS (as of v3.5.1) has a duplicate function declaration + in its public headers. Disable the warning that detects it. */ +#pragma GCC diagnostic ignored "-Wredundant-decls" +#endif + +#include +#if MBEDTLS_VERSION_NUMBER >= 0x02040000 +#include +#else +#include +#endif +#include +#include + +#include +#include +#include +#include + +#if MBEDTLS_VERSION_MAJOR >= 2 +# ifdef MBEDTLS_DEBUG +# include +# endif +#endif + +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + +#include "cipher_suite.h" +#include "strcase.h" +#include "urldata.h" +#include "sendf.h" +#include "inet_pton.h" +#include "mbedtls.h" +#include "vtls.h" +#include "vtls_int.h" +#include "parsedate.h" +#include "connect.h" /* for the connect timeout */ +#include "select.h" +#include "multiif.h" +#include "mbedtls_threadlock.h" +#include "strdup.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* ALPN for http2 */ +#ifdef USE_HTTP2 +# undef HAS_ALPN +# ifdef MBEDTLS_SSL_ALPN +# define HAS_ALPN +# endif +#endif + +struct mbed_ssl_backend_data { + mbedtls_ctr_drbg_context ctr_drbg; + mbedtls_entropy_context entropy; + mbedtls_ssl_context ssl; + mbedtls_x509_crt cacert; + mbedtls_x509_crt clicert; +#ifdef MBEDTLS_X509_CRL_PARSE_C + mbedtls_x509_crl crl; +#endif + mbedtls_pk_context pk; + mbedtls_ssl_config config; +#ifdef HAS_ALPN + const char *protocols[3]; +#endif + int *ciphersuites; +}; + +/* apply threading? */ +#if (defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H)) || \ + defined(_WIN32) +#define THREADING_SUPPORT +#endif + +#ifndef MBEDTLS_ERROR_C +#define mbedtls_strerror(a,b,c) b[0] = 0 +#endif + +#if defined(MBEDTLS_SSL_PROTO_TLS1_3) && MBEDTLS_VERSION_NUMBER >= 0x03060000 +#define TLS13_SUPPORT +#endif + +#if defined(THREADING_SUPPORT) +static mbedtls_entropy_context ts_entropy; + +static int entropy_init_initialized = 0; + +static void entropy_init_mutex(mbedtls_entropy_context *ctx) +{ + /* lock 0 = entropy_init_mutex() */ + Curl_mbedtlsthreadlock_lock_function(0); + if(entropy_init_initialized == 0) { + mbedtls_entropy_init(ctx); + entropy_init_initialized = 1; + } + Curl_mbedtlsthreadlock_unlock_function(0); +} + +static void entropy_cleanup_mutex(mbedtls_entropy_context *ctx) +{ + /* lock 0 = use same lock as init */ + Curl_mbedtlsthreadlock_lock_function(0); + if(entropy_init_initialized == 1) { + mbedtls_entropy_free(ctx); + entropy_init_initialized = 0; + } + Curl_mbedtlsthreadlock_unlock_function(0); +} + +static int entropy_func_mutex(void *data, unsigned char *output, size_t len) +{ + int ret; + /* lock 1 = entropy_func_mutex() */ + Curl_mbedtlsthreadlock_lock_function(1); + ret = mbedtls_entropy_func(data, output, len); + Curl_mbedtlsthreadlock_unlock_function(1); + + return ret; +} + +#endif /* THREADING_SUPPORT */ + +#ifdef MBEDTLS_DEBUG +static void mbed_debug(void *context, int level, const char *f_name, + int line_nb, const char *line) +{ + struct Curl_easy *data = (struct Curl_easy *)context; + (void) level; + (void) line_nb; + (void) f_name; + + if(data) { + size_t len = strlen(line); + if(len && (line[len - 1] == '\n')) + /* discount any trailing newline */ + len--; + infof(data, "%.*s", (int)len, line); + } +} +#endif + +static int mbedtls_bio_cf_write(void *bio, + const unsigned char *buf, size_t blen) +{ + struct Curl_cfilter *cf = bio; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + ssize_t nwritten; + CURLcode result; + + DEBUGASSERT(data); + if(!data) + return 0; + + nwritten = Curl_conn_cf_send(cf->next, data, (char *)buf, blen, &result); + CURL_TRC_CF(data, cf, "mbedtls_bio_cf_out_write(len=%zu) -> %zd, err=%d", + blen, nwritten, result); + if(nwritten < 0 && CURLE_AGAIN == result) { + nwritten = MBEDTLS_ERR_SSL_WANT_WRITE; + } + return (int)nwritten; +} + +static int mbedtls_bio_cf_read(void *bio, unsigned char *buf, size_t blen) +{ + struct Curl_cfilter *cf = bio; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + ssize_t nread; + CURLcode result; + + DEBUGASSERT(data); + if(!data) + return 0; + /* OpenSSL catches this case, so should we. */ + if(!buf) + return 0; + + nread = Curl_conn_cf_recv(cf->next, data, (char *)buf, blen, &result); + CURL_TRC_CF(data, cf, "mbedtls_bio_cf_in_read(len=%zu) -> %zd, err=%d", + blen, nread, result); + if(nread < 0 && CURLE_AGAIN == result) { + nread = MBEDTLS_ERR_SSL_WANT_READ; + } + return (int)nread; +} + +/* + * profile + */ +static const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_fr = +{ + /* Hashes from SHA-1 and above */ + MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA1) | + MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_RIPEMD160) | + MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA224) | + MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256) | + MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384) | + MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512), + 0xFFFFFFF, /* Any PK alg */ + 0xFFFFFFF, /* Any curve */ + 1024, /* RSA min key len */ +}; + +/* See https://tls.mbed.org/discussions/generic/ + howto-determine-exact-buffer-len-for-mbedtls_pk_write_pubkey_der +*/ +#define RSA_PUB_DER_MAX_BYTES (38 + 2 * MBEDTLS_MPI_MAX_SIZE) +#define ECP_PUB_DER_MAX_BYTES (30 + 2 * MBEDTLS_ECP_MAX_BYTES) + +#define PUB_DER_MAX_BYTES (RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \ + RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES) + +#if MBEDTLS_VERSION_NUMBER >= 0x03020000 +static CURLcode mbedtls_version_from_curl( + mbedtls_ssl_protocol_version* mbedver, long version) +{ + switch(version) { + case CURL_SSLVERSION_TLSv1_0: + case CURL_SSLVERSION_TLSv1_1: + case CURL_SSLVERSION_TLSv1_2: + *mbedver = MBEDTLS_SSL_VERSION_TLS1_2; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_3: +#ifdef TLS13_SUPPORT + *mbedver = MBEDTLS_SSL_VERSION_TLS1_3; + return CURLE_OK; +#else + break; +#endif + } + + return CURLE_SSL_CONNECT_ERROR; +} +#else +static CURLcode mbedtls_version_from_curl(int *mbedver, long version) +{ +#if MBEDTLS_VERSION_NUMBER >= 0x03000000 + switch(version) { + case CURL_SSLVERSION_TLSv1_0: + case CURL_SSLVERSION_TLSv1_1: + case CURL_SSLVERSION_TLSv1_2: + *mbedver = MBEDTLS_SSL_MINOR_VERSION_3; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_3: + break; + } +#else + switch(version) { + case CURL_SSLVERSION_TLSv1_0: + *mbedver = MBEDTLS_SSL_MINOR_VERSION_1; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_1: + *mbedver = MBEDTLS_SSL_MINOR_VERSION_2; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_2: + *mbedver = MBEDTLS_SSL_MINOR_VERSION_3; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_3: + break; + } +#endif + + return CURLE_SSL_CONNECT_ERROR; +} +#endif + +static CURLcode +set_ssl_version_min_max(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); +#if MBEDTLS_VERSION_NUMBER >= 0x03020000 + mbedtls_ssl_protocol_version mbedtls_ver_min = MBEDTLS_SSL_VERSION_TLS1_2; +#ifdef TLS13_SUPPORT + mbedtls_ssl_protocol_version mbedtls_ver_max = MBEDTLS_SSL_VERSION_TLS1_3; +#else + mbedtls_ssl_protocol_version mbedtls_ver_max = MBEDTLS_SSL_VERSION_TLS1_2; +#endif +#elif MBEDTLS_VERSION_NUMBER >= 0x03000000 + int mbedtls_ver_min = MBEDTLS_SSL_MINOR_VERSION_3; + int mbedtls_ver_max = MBEDTLS_SSL_MINOR_VERSION_3; +#else + int mbedtls_ver_min = MBEDTLS_SSL_MINOR_VERSION_1; + int mbedtls_ver_max = MBEDTLS_SSL_MINOR_VERSION_1; +#endif + long ssl_version = conn_config->version; + long ssl_version_max = conn_config->version_max; + CURLcode result = CURLE_OK; + + DEBUGASSERT(backend); + + switch(ssl_version) { + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1: + ssl_version = CURL_SSLVERSION_TLSv1_0; + break; + } + + switch(ssl_version_max) { + case CURL_SSLVERSION_MAX_NONE: + case CURL_SSLVERSION_MAX_DEFAULT: +#ifdef TLS13_SUPPORT + ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_3; +#else + ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_2; +#endif + break; + } + + result = mbedtls_version_from_curl(&mbedtls_ver_min, ssl_version); + if(result) { + failf(data, "unsupported min version passed via CURLOPT_SSLVERSION"); + return result; + } + result = mbedtls_version_from_curl(&mbedtls_ver_max, ssl_version_max >> 16); + if(result) { + failf(data, "unsupported max version passed via CURLOPT_SSLVERSION"); + return result; + } + +#if MBEDTLS_VERSION_NUMBER >= 0x03020000 + mbedtls_ssl_conf_min_tls_version(&backend->config, mbedtls_ver_min); + mbedtls_ssl_conf_max_tls_version(&backend->config, mbedtls_ver_max); +#else + mbedtls_ssl_conf_min_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3, + mbedtls_ver_min); + mbedtls_ssl_conf_max_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3, + mbedtls_ver_max); +#endif + +#ifdef TLS13_SUPPORT + if(mbedtls_ver_min == MBEDTLS_SSL_VERSION_TLS1_3) { + mbedtls_ssl_conf_authmode(&backend->config, MBEDTLS_SSL_VERIFY_REQUIRED); + } + else { + mbedtls_ssl_conf_authmode(&backend->config, MBEDTLS_SSL_VERIFY_OPTIONAL); + } +#else + mbedtls_ssl_conf_authmode(&backend->config, MBEDTLS_SSL_VERIFY_OPTIONAL); +#endif + + return result; +} + +/* TLS_ECJPAKE_WITH_AES_128_CCM_8 (0xC0FF) is marked experimental + in mbedTLS. The number is not reserved by IANA nor is the + cipher suite present in other SSL implementations. Provide + provisional support for specifying the cipher suite here. */ +#ifdef MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8 +static int +mbed_cipher_suite_get_str(uint16_t id, char *buf, size_t buf_size, + bool prefer_rfc) +{ + if(id == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8) + msnprintf(buf, buf_size, "%s", "TLS_ECJPAKE_WITH_AES_128_CCM_8"); + else + return Curl_cipher_suite_get_str(id, buf, buf_size, prefer_rfc); + return 0; +} + +static uint16_t +mbed_cipher_suite_walk_str(const char **str, const char **end) +{ + uint16_t id = Curl_cipher_suite_walk_str(str, end); + size_t len = *end - *str; + + if(!id) { + if(strncasecompare("TLS_ECJPAKE_WITH_AES_128_CCM_8", *str, len)) + id = MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8; + } + return id; +} +#else +#define mbed_cipher_suite_get_str Curl_cipher_suite_get_str +#define mbed_cipher_suite_walk_str Curl_cipher_suite_walk_str +#endif + +static CURLcode +mbed_set_selected_ciphers(struct Curl_easy *data, + struct mbed_ssl_backend_data *backend, + const char *ciphers) +{ + const int *supported; + int *selected; + size_t supported_len, count = 0, i; + const char *ptr, *end; + + supported = mbedtls_ssl_list_ciphersuites(); + for(i = 0; supported[i] != 0; i++); + supported_len = i; + + selected = malloc(sizeof(int) * (supported_len + 1)); + if(!selected) + return CURLE_OUT_OF_MEMORY; + + for(ptr = ciphers; ptr[0] != '\0' && count < supported_len; ptr = end) { + uint16_t id = mbed_cipher_suite_walk_str(&ptr, &end); + + /* Check if cipher is supported */ + if(id) { + for(i = 0; i < supported_len && supported[i] != id; i++); + if(i == supported_len) + id = 0; + } + if(!id) { + if(ptr[0] != '\0') + infof(data, "mbedTLS: unknown cipher in list: \"%.*s\"", + (int) (end - ptr), ptr); + continue; + } + + /* No duplicates allowed (so selected cannot overflow) */ + for(i = 0; i < count && selected[i] != id; i++); + if(i < count) { + infof(data, "mbedTLS: duplicate cipher in list: \"%.*s\"", + (int) (end - ptr), ptr); + continue; + } + + selected[count++] = id; + } + + selected[count] = 0; + + if(count == 0) { + free(selected); + failf(data, "mbedTLS: no supported cipher in list"); + return CURLE_SSL_CIPHER; + } + + /* mbedtls_ssl_conf_ciphersuites(): The ciphersuites array is not copied. + It must remain valid for the lifetime of the SSL configuration */ + backend->ciphersuites = selected; + mbedtls_ssl_conf_ciphersuites(&backend->config, backend->ciphersuites); + return CURLE_OK; +} + +static CURLcode +mbed_connect_step1(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + const struct curl_blob *ca_info_blob = conn_config->ca_info_blob; + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + const char * const ssl_cafile = + /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */ + (ca_info_blob ? NULL : conn_config->CAfile); + const bool verifypeer = conn_config->verifypeer; + const char * const ssl_capath = conn_config->CApath; + char * const ssl_cert = ssl_config->primary.clientcert; + const struct curl_blob *ssl_cert_blob = ssl_config->primary.cert_blob; + const char * const ssl_crlfile = ssl_config->primary.CRLfile; + const char *hostname = connssl->peer.hostname; + int ret = -1; + char errorbuf[128]; + + DEBUGASSERT(backend); + + if((conn_config->version == CURL_SSLVERSION_SSLv2) || + (conn_config->version == CURL_SSLVERSION_SSLv3)) { + failf(data, "Not supported SSL version"); + return CURLE_NOT_BUILT_IN; + } + +#ifdef TLS13_SUPPORT + ret = psa_crypto_init(); + if(ret != PSA_SUCCESS) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "mbedTLS psa_crypto_init returned (-0x%04X) %s", + -ret, errorbuf); + return CURLE_SSL_CONNECT_ERROR; + } +#endif /* TLS13_SUPPORT */ + +#ifdef THREADING_SUPPORT + mbedtls_ctr_drbg_init(&backend->ctr_drbg); + + ret = mbedtls_ctr_drbg_seed(&backend->ctr_drbg, entropy_func_mutex, + &ts_entropy, NULL, 0); + if(ret) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "mbedtls_ctr_drbg_seed returned (-0x%04X) %s", + -ret, errorbuf); + return CURLE_FAILED_INIT; + } +#else + mbedtls_entropy_init(&backend->entropy); + mbedtls_ctr_drbg_init(&backend->ctr_drbg); + + ret = mbedtls_ctr_drbg_seed(&backend->ctr_drbg, mbedtls_entropy_func, + &backend->entropy, NULL, 0); + if(ret) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "mbedtls_ctr_drbg_seed returned (-0x%04X) %s", + -ret, errorbuf); + return CURLE_FAILED_INIT; + } +#endif /* THREADING_SUPPORT */ + + /* Load the trusted CA */ + mbedtls_x509_crt_init(&backend->cacert); + + if(ca_info_blob && verifypeer) { + /* Unfortunately, mbedtls_x509_crt_parse() requires the data to be null + terminated even when provided the exact length, forcing us to waste + extra memory here. */ + unsigned char *newblob = Curl_memdup0(ca_info_blob->data, + ca_info_blob->len); + if(!newblob) + return CURLE_OUT_OF_MEMORY; + ret = mbedtls_x509_crt_parse(&backend->cacert, newblob, + ca_info_blob->len + 1); + free(newblob); + if(ret<0) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "Error importing ca cert blob - mbedTLS: (-0x%04X) %s", + -ret, errorbuf); + return CURLE_SSL_CERTPROBLEM; + } + } + + if(ssl_cafile && verifypeer) { +#ifdef MBEDTLS_FS_IO + ret = mbedtls_x509_crt_parse_file(&backend->cacert, ssl_cafile); + + if(ret<0) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "Error reading ca cert file %s - mbedTLS: (-0x%04X) %s", + ssl_cafile, -ret, errorbuf); + return CURLE_SSL_CACERT_BADFILE; + } +#else + failf(data, "mbedtls: functions that use the filesystem not built in"); + return CURLE_NOT_BUILT_IN; +#endif + } + + if(ssl_capath) { +#ifdef MBEDTLS_FS_IO + ret = mbedtls_x509_crt_parse_path(&backend->cacert, ssl_capath); + + if(ret<0) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "Error reading ca cert path %s - mbedTLS: (-0x%04X) %s", + ssl_capath, -ret, errorbuf); + + if(verifypeer) + return CURLE_SSL_CACERT_BADFILE; + } +#else + failf(data, "mbedtls: functions that use the filesystem not built in"); + return CURLE_NOT_BUILT_IN; +#endif + } + + /* Load the client certificate */ + mbedtls_x509_crt_init(&backend->clicert); + + if(ssl_cert) { +#ifdef MBEDTLS_FS_IO + ret = mbedtls_x509_crt_parse_file(&backend->clicert, ssl_cert); + + if(ret) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "Error reading client cert file %s - mbedTLS: (-0x%04X) %s", + ssl_cert, -ret, errorbuf); + + return CURLE_SSL_CERTPROBLEM; + } +#else + failf(data, "mbedtls: functions that use the filesystem not built in"); + return CURLE_NOT_BUILT_IN; +#endif + } + + if(ssl_cert_blob) { + /* Unfortunately, mbedtls_x509_crt_parse() requires the data to be null + terminated even when provided the exact length, forcing us to waste + extra memory here. */ + unsigned char *newblob = Curl_memdup0(ssl_cert_blob->data, + ssl_cert_blob->len); + if(!newblob) + return CURLE_OUT_OF_MEMORY; + ret = mbedtls_x509_crt_parse(&backend->clicert, newblob, + ssl_cert_blob->len + 1); + free(newblob); + + if(ret) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "Error reading private key %s - mbedTLS: (-0x%04X) %s", + ssl_config->key, -ret, errorbuf); + return CURLE_SSL_CERTPROBLEM; + } + } + + /* Load the client private key */ + mbedtls_pk_init(&backend->pk); + + if(ssl_config->key || ssl_config->key_blob) { + if(ssl_config->key) { +#ifdef MBEDTLS_FS_IO +#if MBEDTLS_VERSION_NUMBER >= 0x03000000 + ret = mbedtls_pk_parse_keyfile(&backend->pk, ssl_config->key, + ssl_config->key_passwd, + mbedtls_ctr_drbg_random, + &backend->ctr_drbg); +#else + ret = mbedtls_pk_parse_keyfile(&backend->pk, ssl_config->key, + ssl_config->key_passwd); +#endif + + if(ret) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "Error reading private key %s - mbedTLS: (-0x%04X) %s", + ssl_config->key, -ret, errorbuf); + return CURLE_SSL_CERTPROBLEM; + } +#else + failf(data, "mbedtls: functions that use the filesystem not built in"); + return CURLE_NOT_BUILT_IN; +#endif + } + else { + const struct curl_blob *ssl_key_blob = ssl_config->key_blob; + const unsigned char *key_data = + (const unsigned char *)ssl_key_blob->data; + const char *passwd = ssl_config->key_passwd; +#if MBEDTLS_VERSION_NUMBER >= 0x03000000 + ret = mbedtls_pk_parse_key(&backend->pk, key_data, ssl_key_blob->len, + (const unsigned char *)passwd, + passwd ? strlen(passwd) : 0, + mbedtls_ctr_drbg_random, + &backend->ctr_drbg); +#else + ret = mbedtls_pk_parse_key(&backend->pk, key_data, ssl_key_blob->len, + (const unsigned char *)passwd, + passwd ? strlen(passwd) : 0); +#endif + + if(ret) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "Error parsing private key - mbedTLS: (-0x%04X) %s", + -ret, errorbuf); + return CURLE_SSL_CERTPROBLEM; + } + } + + if(ret == 0 && !(mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_RSA) || + mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_ECKEY))) + ret = MBEDTLS_ERR_PK_TYPE_MISMATCH; + } + + /* Load the CRL */ +#ifdef MBEDTLS_X509_CRL_PARSE_C + mbedtls_x509_crl_init(&backend->crl); + + if(ssl_crlfile) { +#ifdef MBEDTLS_FS_IO + ret = mbedtls_x509_crl_parse_file(&backend->crl, ssl_crlfile); + + if(ret) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "Error reading CRL file %s - mbedTLS: (-0x%04X) %s", + ssl_crlfile, -ret, errorbuf); + + return CURLE_SSL_CRL_BADFILE; + } +#else + failf(data, "mbedtls: functions that use the filesystem not built in"); + return CURLE_NOT_BUILT_IN; +#endif + } +#else + if(ssl_crlfile) { + failf(data, "mbedtls: crl support not built in"); + return CURLE_NOT_BUILT_IN; + } +#endif + + infof(data, "mbedTLS: Connecting to %s:%d", hostname, connssl->peer.port); + + mbedtls_ssl_config_init(&backend->config); + ret = mbedtls_ssl_config_defaults(&backend->config, + MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT); + if(ret) { + failf(data, "mbedTLS: ssl_config failed"); + return CURLE_SSL_CONNECT_ERROR; + } + + mbedtls_ssl_init(&backend->ssl); + + /* new profile with RSA min key len = 1024 ... */ + mbedtls_ssl_conf_cert_profile(&backend->config, + &mbedtls_x509_crt_profile_fr); + + switch(conn_config->version) { + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1: +#if MBEDTLS_VERSION_NUMBER < 0x03000000 + mbedtls_ssl_conf_min_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3, + MBEDTLS_SSL_MINOR_VERSION_1); + infof(data, "mbedTLS: Set min SSL version to TLS 1.0"); + break; +#endif + case CURL_SSLVERSION_TLSv1_0: + case CURL_SSLVERSION_TLSv1_1: + case CURL_SSLVERSION_TLSv1_2: + case CURL_SSLVERSION_TLSv1_3: + { + CURLcode result = set_ssl_version_min_max(cf, data); + if(result != CURLE_OK) + return result; + break; + } + default: + failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); + return CURLE_SSL_CONNECT_ERROR; + } + + mbedtls_ssl_conf_rng(&backend->config, mbedtls_ctr_drbg_random, + &backend->ctr_drbg); + + ret = mbedtls_ssl_setup(&backend->ssl, &backend->config); + if(ret) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "ssl_setup failed - mbedTLS: (-0x%04X) %s", + -ret, errorbuf); + return CURLE_SSL_CONNECT_ERROR; + } + + mbedtls_ssl_set_bio(&backend->ssl, cf, + mbedtls_bio_cf_write, + mbedtls_bio_cf_read, + NULL /* rev_timeout() */); + + if(conn_config->cipher_list) { + ret = mbed_set_selected_ciphers(data, backend, conn_config->cipher_list); + if(ret) { + failf(data, "mbedTLS: failed to set cipher suites"); + return ret; + } + } + else { + mbedtls_ssl_conf_ciphersuites(&backend->config, + mbedtls_ssl_list_ciphersuites()); + } + + +#if defined(MBEDTLS_SSL_RENEGOTIATION) + mbedtls_ssl_conf_renegotiation(&backend->config, + MBEDTLS_SSL_RENEGOTIATION_ENABLED); +#endif + +#if defined(MBEDTLS_SSL_SESSION_TICKETS) + mbedtls_ssl_conf_session_tickets(&backend->config, + MBEDTLS_SSL_SESSION_TICKETS_DISABLED); +#endif + + /* Check if there's a cached ID we can/should use here! */ + if(ssl_config->primary.sessionid) { + void *old_session = NULL; + + Curl_ssl_sessionid_lock(data); + if(!Curl_ssl_getsessionid(cf, data, &connssl->peer, &old_session, NULL)) { + ret = mbedtls_ssl_set_session(&backend->ssl, old_session); + if(ret) { + Curl_ssl_sessionid_unlock(data); + failf(data, "mbedtls_ssl_set_session returned -0x%x", -ret); + return CURLE_SSL_CONNECT_ERROR; + } + infof(data, "mbedTLS reusing session"); + } + Curl_ssl_sessionid_unlock(data); + } + + mbedtls_ssl_conf_ca_chain(&backend->config, + &backend->cacert, +#ifdef MBEDTLS_X509_CRL_PARSE_C + &backend->crl); +#else + NULL); +#endif + + if(ssl_config->key || ssl_config->key_blob) { + mbedtls_ssl_conf_own_cert(&backend->config, + &backend->clicert, &backend->pk); + } + + if(mbedtls_ssl_set_hostname(&backend->ssl, connssl->peer.sni? + connssl->peer.sni : connssl->peer.hostname)) { + /* mbedtls_ssl_set_hostname() sets the name to use in CN/SAN checks and + the name to set in the SNI extension. So even if curl connects to a + host specified as an IP address, this function must be used. */ + failf(data, "Failed to set SNI"); + return CURLE_SSL_CONNECT_ERROR; + } + +#ifdef HAS_ALPN + if(connssl->alpn) { + struct alpn_proto_buf proto; + size_t i; + + for(i = 0; i < connssl->alpn->count; ++i) { + backend->protocols[i] = connssl->alpn->entries[i]; + } + /* this function doesn't clone the protocols array, which is why we need + to keep it around */ + if(mbedtls_ssl_conf_alpn_protocols(&backend->config, + &backend->protocols[0])) { + failf(data, "Failed setting ALPN protocols"); + return CURLE_SSL_CONNECT_ERROR; + } + Curl_alpn_to_proto_str(&proto, connssl->alpn); + infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data); + } +#endif + +#ifdef MBEDTLS_DEBUG + /* In order to make that work in mbedtls MBEDTLS_DEBUG_C must be defined. */ + mbedtls_ssl_conf_dbg(&backend->config, mbed_debug, data); + /* - 0 No debug + * - 1 Error + * - 2 State change + * - 3 Informational + * - 4 Verbose + */ + mbedtls_debug_set_threshold(4); +#endif + + /* give application a chance to interfere with mbedTLS set up. */ + if(data->set.ssl.fsslctx) { + ret = (*data->set.ssl.fsslctx)(data, &backend->config, + data->set.ssl.fsslctxp); + if(ret) { + failf(data, "error signaled by ssl ctx callback"); + return ret; + } + } + + connssl->connecting_state = ssl_connect_2; + + return CURLE_OK; +} + +static CURLcode +mbed_connect_step2(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + int ret; + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + const mbedtls_x509_crt *peercert; + char cipher_str[64]; + uint16_t cipher_id; +#ifndef CURL_DISABLE_PROXY + const char * const pinnedpubkey = Curl_ssl_cf_is_proxy(cf)? + data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY]: + data->set.str[STRING_SSL_PINNEDPUBLICKEY]; +#else + const char * const pinnedpubkey = data->set.str[STRING_SSL_PINNEDPUBLICKEY]; +#endif + + DEBUGASSERT(backend); + + ret = mbedtls_ssl_handshake(&backend->ssl); + + if(ret == MBEDTLS_ERR_SSL_WANT_READ) { + connssl->connecting_state = ssl_connect_2_reading; + return CURLE_OK; + } + else if(ret == MBEDTLS_ERR_SSL_WANT_WRITE) { + connssl->connecting_state = ssl_connect_2_writing; + return CURLE_OK; + } + else if(ret) { + char errorbuf[128]; + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "ssl_handshake returned - mbedTLS: (-0x%04X) %s", + -ret, errorbuf); + return CURLE_SSL_CONNECT_ERROR; + } + + cipher_id = (uint16_t) + mbedtls_ssl_get_ciphersuite_id_from_ssl(&backend->ssl); + mbed_cipher_suite_get_str(cipher_id, cipher_str, sizeof(cipher_str), true); + infof(data, "mbedTLS: Handshake complete, cipher is %s", cipher_str); + + ret = mbedtls_ssl_get_verify_result(&backend->ssl); + + if(!conn_config->verifyhost) + /* Ignore hostname errors if verifyhost is disabled */ + ret &= ~MBEDTLS_X509_BADCERT_CN_MISMATCH; + + if(ret && conn_config->verifypeer) { + if(ret & MBEDTLS_X509_BADCERT_EXPIRED) + failf(data, "Cert verify failed: BADCERT_EXPIRED"); + + else if(ret & MBEDTLS_X509_BADCERT_REVOKED) + failf(data, "Cert verify failed: BADCERT_REVOKED"); + + else if(ret & MBEDTLS_X509_BADCERT_CN_MISMATCH) + failf(data, "Cert verify failed: BADCERT_CN_MISMATCH"); + + else if(ret & MBEDTLS_X509_BADCERT_NOT_TRUSTED) + failf(data, "Cert verify failed: BADCERT_NOT_TRUSTED"); + + else if(ret & MBEDTLS_X509_BADCERT_FUTURE) + failf(data, "Cert verify failed: BADCERT_FUTURE"); + + return CURLE_PEER_FAILED_VERIFICATION; + } + + peercert = mbedtls_ssl_get_peer_cert(&backend->ssl); + + if(peercert && data->set.verbose) { +#ifndef MBEDTLS_X509_REMOVE_INFO + const size_t bufsize = 16384; + char *buffer = malloc(bufsize); + + if(!buffer) + return CURLE_OUT_OF_MEMORY; + + if(mbedtls_x509_crt_info(buffer, bufsize, "* ", peercert) > 0) + infof(data, "Dumping cert info: %s", buffer); + else + infof(data, "Unable to dump certificate information"); + + free(buffer); +#else + infof(data, "Unable to dump certificate information"); +#endif + } + + if(pinnedpubkey) { + int size; + CURLcode result; + mbedtls_x509_crt *p = NULL; + unsigned char *pubkey = NULL; + +#if MBEDTLS_VERSION_NUMBER == 0x03000000 + if(!peercert || !peercert->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(p) || + !peercert->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(len)) { +#else + if(!peercert || !peercert->raw.p || !peercert->raw.len) { +#endif + failf(data, "Failed due to missing peer certificate"); + return CURLE_SSL_PINNEDPUBKEYNOTMATCH; + } + + p = calloc(1, sizeof(*p)); + + if(!p) + return CURLE_OUT_OF_MEMORY; + + pubkey = malloc(PUB_DER_MAX_BYTES); + + if(!pubkey) { + result = CURLE_OUT_OF_MEMORY; + goto pinnedpubkey_error; + } + + mbedtls_x509_crt_init(p); + + /* Make a copy of our const peercert because mbedtls_pk_write_pubkey_der + needs a non-const key, for now. + https://github.com/ARMmbed/mbedtls/issues/396 */ +#if MBEDTLS_VERSION_NUMBER == 0x03000000 + if(mbedtls_x509_crt_parse_der(p, + peercert->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(p), + peercert->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(len))) { +#else + if(mbedtls_x509_crt_parse_der(p, peercert->raw.p, peercert->raw.len)) { +#endif + failf(data, "Failed copying peer certificate"); + result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; + goto pinnedpubkey_error; + } + +#if MBEDTLS_VERSION_NUMBER == 0x03000000 + size = mbedtls_pk_write_pubkey_der(&p->MBEDTLS_PRIVATE(pk), pubkey, + PUB_DER_MAX_BYTES); +#else + size = mbedtls_pk_write_pubkey_der(&p->pk, pubkey, PUB_DER_MAX_BYTES); +#endif + + if(size <= 0) { + failf(data, "Failed copying public key from peer certificate"); + result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; + goto pinnedpubkey_error; + } + + /* mbedtls_pk_write_pubkey_der writes data at the end of the buffer. */ + result = Curl_pin_peer_pubkey(data, + pinnedpubkey, + &pubkey[PUB_DER_MAX_BYTES - size], size); +pinnedpubkey_error: + mbedtls_x509_crt_free(p); + free(p); + free(pubkey); + if(result) { + return result; + } + } + +#ifdef HAS_ALPN + if(connssl->alpn) { + const char *proto = mbedtls_ssl_get_alpn_protocol(&backend->ssl); + + Curl_alpn_set_negotiated(cf, data, (const unsigned char *)proto, + proto? strlen(proto) : 0); + } +#endif + + connssl->connecting_state = ssl_connect_3; + infof(data, "SSL connected"); + + return CURLE_OK; +} + +static void mbedtls_session_free(void *sessionid, size_t idsize) +{ + (void)idsize; + mbedtls_ssl_session_free(sessionid); + free(sessionid); +} + +static CURLcode +mbed_connect_step3(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + CURLcode retcode = CURLE_OK; + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + + DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); + DEBUGASSERT(backend); + + if(ssl_config->primary.sessionid) { + int ret; + mbedtls_ssl_session *our_ssl_sessionid; + void *old_ssl_sessionid = NULL; + + our_ssl_sessionid = malloc(sizeof(mbedtls_ssl_session)); + if(!our_ssl_sessionid) + return CURLE_OUT_OF_MEMORY; + + mbedtls_ssl_session_init(our_ssl_sessionid); + + ret = mbedtls_ssl_get_session(&backend->ssl, our_ssl_sessionid); + if(ret) { + if(ret != MBEDTLS_ERR_SSL_ALLOC_FAILED) + mbedtls_ssl_session_free(our_ssl_sessionid); + free(our_ssl_sessionid); + failf(data, "mbedtls_ssl_get_session returned -0x%x", -ret); + return CURLE_SSL_CONNECT_ERROR; + } + + /* If there's already a matching session in the cache, delete it */ + Curl_ssl_sessionid_lock(data); + if(!Curl_ssl_getsessionid(cf, data, &connssl->peer, + &old_ssl_sessionid, NULL)) + Curl_ssl_delsessionid(data, old_ssl_sessionid); + + retcode = Curl_ssl_addsessionid(cf, data, &connssl->peer, + our_ssl_sessionid, 0, + mbedtls_session_free); + Curl_ssl_sessionid_unlock(data); + if(retcode) + return retcode; + } + + connssl->connecting_state = ssl_connect_done; + + return CURLE_OK; +} + +static ssize_t mbed_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *mem, size_t len, + CURLcode *curlcode) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + int ret = -1; + + (void)data; + DEBUGASSERT(backend); + ret = mbedtls_ssl_write(&backend->ssl, (unsigned char *)mem, len); + + if(ret < 0) { + *curlcode = (ret == MBEDTLS_ERR_SSL_WANT_WRITE) ? + CURLE_AGAIN : CURLE_SEND_ERROR; + ret = -1; + } + + return ret; +} + +static void mbedtls_close_all(struct Curl_easy *data) +{ + (void)data; +} + +static void mbedtls_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + char buf[32]; + + (void)data; + DEBUGASSERT(backend); + + /* Maybe the server has already sent a close notify alert. + Read it to avoid an RST on the TCP connection. */ + (void)mbedtls_ssl_read(&backend->ssl, (unsigned char *)buf, sizeof(buf)); + + mbedtls_pk_free(&backend->pk); + mbedtls_x509_crt_free(&backend->clicert); + mbedtls_x509_crt_free(&backend->cacert); +#ifdef MBEDTLS_X509_CRL_PARSE_C + mbedtls_x509_crl_free(&backend->crl); +#endif + Curl_safefree(backend->ciphersuites); + mbedtls_ssl_config_free(&backend->config); + mbedtls_ssl_free(&backend->ssl); + mbedtls_ctr_drbg_free(&backend->ctr_drbg); +#ifndef THREADING_SUPPORT + mbedtls_entropy_free(&backend->entropy); +#endif /* THREADING_SUPPORT */ +} + +static ssize_t mbed_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t buffersize, + CURLcode *curlcode) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + int ret = -1; + ssize_t len = -1; + + (void)data; + DEBUGASSERT(backend); + + ret = mbedtls_ssl_read(&backend->ssl, (unsigned char *)buf, + buffersize); + + if(ret <= 0) { + if(ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) + return 0; + + *curlcode = ((ret == MBEDTLS_ERR_SSL_WANT_READ) +#ifdef TLS13_SUPPORT + || (ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET) +#endif + ) ? CURLE_AGAIN : CURLE_RECV_ERROR; + return -1; + } + + len = ret; + + return len; +} + +static size_t mbedtls_version(char *buffer, size_t size) +{ +#ifdef MBEDTLS_VERSION_C + /* if mbedtls_version_get_number() is available it is better */ + unsigned int version = mbedtls_version_get_number(); + return msnprintf(buffer, size, "mbedTLS/%u.%u.%u", version>>24, + (version>>16)&0xff, (version>>8)&0xff); +#else + return msnprintf(buffer, size, "mbedTLS/%s", MBEDTLS_VERSION_STRING); +#endif +} + +static CURLcode mbedtls_random(struct Curl_easy *data, + unsigned char *entropy, size_t length) +{ +#if defined(MBEDTLS_CTR_DRBG_C) + int ret = -1; + char errorbuf[128]; + mbedtls_entropy_context ctr_entropy; + mbedtls_ctr_drbg_context ctr_drbg; + mbedtls_entropy_init(&ctr_entropy); + mbedtls_ctr_drbg_init(&ctr_drbg); + + ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, + &ctr_entropy, NULL, 0); + + if(ret) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "mbedtls_ctr_drbg_seed returned (-0x%04X) %s", + -ret, errorbuf); + } + else { + ret = mbedtls_ctr_drbg_random(&ctr_drbg, entropy, length); + + if(ret) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "mbedtls_ctr_drbg_random returned (-0x%04X) %s", + -ret, errorbuf); + } + } + + mbedtls_ctr_drbg_free(&ctr_drbg); + mbedtls_entropy_free(&ctr_entropy); + + return ret == 0 ? CURLE_OK : CURLE_FAILED_INIT; +#elif defined(MBEDTLS_HAVEGE_C) + mbedtls_havege_state hs; + mbedtls_havege_init(&hs); + mbedtls_havege_random(&hs, entropy, length); + mbedtls_havege_free(&hs); + return CURLE_OK; +#else + return CURLE_NOT_BUILT_IN; +#endif +} + +static CURLcode +mbed_connect_common(struct Curl_cfilter *cf, struct Curl_easy *data, + bool nonblocking, + bool *done) +{ + CURLcode retcode; + struct ssl_connect_data *connssl = cf->ctx; + curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data); + timediff_t timeout_ms; + int what; + + /* check if the connection has already been established */ + if(ssl_connection_complete == connssl->state) { + *done = TRUE; + return CURLE_OK; + } + + if(ssl_connect_1 == connssl->connecting_state) { + /* Find out how much more time we're allowed */ + timeout_ms = Curl_timeleft(data, NULL, TRUE); + + if(timeout_ms < 0) { + /* no need to continue if time already is up */ + failf(data, "SSL connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + retcode = mbed_connect_step1(cf, data); + if(retcode) + return retcode; + } + + while(ssl_connect_2 == connssl->connecting_state || + ssl_connect_2_reading == connssl->connecting_state || + ssl_connect_2_writing == connssl->connecting_state) { + + /* check allowed time left */ + timeout_ms = Curl_timeleft(data, NULL, TRUE); + + if(timeout_ms < 0) { + /* no need to continue if time already is up */ + failf(data, "SSL connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + + /* if ssl is expecting something, check if it's available. */ + if(connssl->connecting_state == ssl_connect_2_reading + || connssl->connecting_state == ssl_connect_2_writing) { + + curl_socket_t writefd = ssl_connect_2_writing == + connssl->connecting_state?sockfd:CURL_SOCKET_BAD; + curl_socket_t readfd = ssl_connect_2_reading == + connssl->connecting_state?sockfd:CURL_SOCKET_BAD; + + what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, + nonblocking ? 0 : timeout_ms); + if(what < 0) { + /* fatal error */ + failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); + return CURLE_SSL_CONNECT_ERROR; + } + else if(0 == what) { + if(nonblocking) { + *done = FALSE; + return CURLE_OK; + } + else { + /* timeout */ + failf(data, "SSL connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + } + /* socket is readable or writable */ + } + + /* Run transaction, and return to the caller if it failed or if + * this connection is part of a multi handle and this loop would + * execute again. This permits the owner of a multi handle to + * abort a connection attempt before step2 has completed while + * ensuring that a client using select() or epoll() will always + * have a valid fdset to wait on. + */ + retcode = mbed_connect_step2(cf, data); + if(retcode || (nonblocking && + (ssl_connect_2 == connssl->connecting_state || + ssl_connect_2_reading == connssl->connecting_state || + ssl_connect_2_writing == connssl->connecting_state))) + return retcode; + + } /* repeat step2 until all transactions are done. */ + + if(ssl_connect_3 == connssl->connecting_state) { + retcode = mbed_connect_step3(cf, data); + if(retcode) + return retcode; + } + + if(ssl_connect_done == connssl->connecting_state) { + connssl->state = ssl_connection_complete; + *done = TRUE; + } + else + *done = FALSE; + + /* Reset our connect state machine */ + connssl->connecting_state = ssl_connect_1; + + return CURLE_OK; +} + +static CURLcode mbedtls_connect_nonblocking(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + return mbed_connect_common(cf, data, TRUE, done); +} + + +static CURLcode mbedtls_connect(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURLcode retcode; + bool done = FALSE; + + retcode = mbed_connect_common(cf, data, FALSE, &done); + if(retcode) + return retcode; + + DEBUGASSERT(done); + + return CURLE_OK; +} + +/* + * return 0 error initializing SSL + * return 1 SSL initialized successfully + */ +static int mbedtls_init(void) +{ + if(!Curl_mbedtlsthreadlock_thread_setup()) + return 0; +#ifdef THREADING_SUPPORT + entropy_init_mutex(&ts_entropy); +#endif + return 1; +} + +static void mbedtls_cleanup(void) +{ +#ifdef THREADING_SUPPORT + entropy_cleanup_mutex(&ts_entropy); +#endif + (void)Curl_mbedtlsthreadlock_thread_cleanup(); +} + +static bool mbedtls_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct ssl_connect_data *ctx = cf->ctx; + struct mbed_ssl_backend_data *backend; + + (void)data; + DEBUGASSERT(ctx && ctx->backend); + backend = (struct mbed_ssl_backend_data *)ctx->backend; + return mbedtls_ssl_get_bytes_avail(&backend->ssl) != 0; +} + +static CURLcode mbedtls_sha256sum(const unsigned char *input, + size_t inputlen, + unsigned char *sha256sum, + size_t sha256len UNUSED_PARAM) +{ + /* TODO: explain this for different mbedtls 2.x vs 3 version */ + (void)sha256len; +#if MBEDTLS_VERSION_NUMBER < 0x02070000 + mbedtls_sha256(input, inputlen, sha256sum, 0); +#else + /* returns 0 on success, otherwise failure */ +#if MBEDTLS_VERSION_NUMBER >= 0x03000000 + if(mbedtls_sha256(input, inputlen, sha256sum, 0) != 0) +#else + if(mbedtls_sha256_ret(input, inputlen, sha256sum, 0) != 0) +#endif + return CURLE_BAD_FUNCTION_ARGUMENT; +#endif + return CURLE_OK; +} + +static void *mbedtls_get_internals(struct ssl_connect_data *connssl, + CURLINFO info UNUSED_PARAM) +{ + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + (void)info; + DEBUGASSERT(backend); + return &backend->ssl; +} + +const struct Curl_ssl Curl_ssl_mbedtls = { + { CURLSSLBACKEND_MBEDTLS, "mbedtls" }, /* info */ + + SSLSUPP_CA_PATH | + SSLSUPP_CAINFO_BLOB | + SSLSUPP_PINNEDPUBKEY | + SSLSUPP_SSL_CTX | + SSLSUPP_HTTPS_PROXY, + + sizeof(struct mbed_ssl_backend_data), + + mbedtls_init, /* init */ + mbedtls_cleanup, /* cleanup */ + mbedtls_version, /* version */ + Curl_none_check_cxn, /* check_cxn */ + Curl_none_shutdown, /* shutdown */ + mbedtls_data_pending, /* data_pending */ + mbedtls_random, /* random */ + Curl_none_cert_status_request, /* cert_status_request */ + mbedtls_connect, /* connect */ + mbedtls_connect_nonblocking, /* connect_nonblocking */ + Curl_ssl_adjust_pollset, /* adjust_pollset */ + mbedtls_get_internals, /* get_internals */ + mbedtls_close, /* close_one */ + mbedtls_close_all, /* close_all */ + Curl_none_set_engine, /* set_engine */ + Curl_none_set_engine_default, /* set_engine_default */ + Curl_none_engines_list, /* engines_list */ + Curl_none_false_start, /* false_start */ + mbedtls_sha256sum, /* sha256sum */ + NULL, /* associate_connection */ + NULL, /* disassociate_connection */ + NULL, /* free_multi_ssl_backend_data */ + mbed_recv, /* recv decrypted data */ + mbed_send, /* send data to encrypt */ +}; + +#endif /* USE_MBEDTLS */ diff --git a/third_party/curl/lib/vtls/mbedtls.h b/third_party/curl/lib/vtls/mbedtls.h new file mode 100644 index 0000000..d8a0a06 --- /dev/null +++ b/third_party/curl/lib/vtls/mbedtls.h @@ -0,0 +1,34 @@ +#ifndef HEADER_CURL_MBEDTLS_H +#define HEADER_CURL_MBEDTLS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (C) Hoi-Ho Chan, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_MBEDTLS + +extern const struct Curl_ssl Curl_ssl_mbedtls; + +#endif /* USE_MBEDTLS */ +#endif /* HEADER_CURL_MBEDTLS_H */ diff --git a/third_party/curl/lib/vtls/mbedtls_threadlock.c b/third_party/curl/lib/vtls/mbedtls_threadlock.c new file mode 100644 index 0000000..b96a904 --- /dev/null +++ b/third_party/curl/lib/vtls/mbedtls_threadlock.c @@ -0,0 +1,134 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (C) Hoi-Ho Chan, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_MBEDTLS) && \ + ((defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H)) || \ + defined(_WIN32)) + +#if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) +# include +# define MBEDTLS_MUTEX_T pthread_mutex_t +#elif defined(_WIN32) +# define MBEDTLS_MUTEX_T HANDLE +#endif + +#include "mbedtls_threadlock.h" +#include "curl_printf.h" +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + +/* number of thread locks */ +#define NUMT 2 + +/* This array will store all of the mutexes available to Mbedtls. */ +static MBEDTLS_MUTEX_T *mutex_buf = NULL; + +int Curl_mbedtlsthreadlock_thread_setup(void) +{ + int i; + + mutex_buf = calloc(1, NUMT * sizeof(MBEDTLS_MUTEX_T)); + if(!mutex_buf) + return 0; /* error, no number of threads defined */ + + for(i = 0; i < NUMT; i++) { +#if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) + if(pthread_mutex_init(&mutex_buf[i], NULL)) + return 0; /* pthread_mutex_init failed */ +#elif defined(_WIN32) + mutex_buf[i] = CreateMutex(0, FALSE, 0); + if(mutex_buf[i] == 0) + return 0; /* CreateMutex failed */ +#endif /* USE_THREADS_POSIX && HAVE_PTHREAD_H */ + } + + return 1; /* OK */ +} + +int Curl_mbedtlsthreadlock_thread_cleanup(void) +{ + int i; + + if(!mutex_buf) + return 0; /* error, no threads locks defined */ + + for(i = 0; i < NUMT; i++) { +#if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) + if(pthread_mutex_destroy(&mutex_buf[i])) + return 0; /* pthread_mutex_destroy failed */ +#elif defined(_WIN32) + if(!CloseHandle(mutex_buf[i])) + return 0; /* CloseHandle failed */ +#endif /* USE_THREADS_POSIX && HAVE_PTHREAD_H */ + } + free(mutex_buf); + mutex_buf = NULL; + + return 1; /* OK */ +} + +int Curl_mbedtlsthreadlock_lock_function(int n) +{ + if(n < NUMT) { +#if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) + if(pthread_mutex_lock(&mutex_buf[n])) { + DEBUGF(fprintf(stderr, + "Error: mbedtlsthreadlock_lock_function failed\n")); + return 0; /* pthread_mutex_lock failed */ + } +#elif defined(_WIN32) + if(WaitForSingleObject(mutex_buf[n], INFINITE) == WAIT_FAILED) { + DEBUGF(fprintf(stderr, + "Error: mbedtlsthreadlock_lock_function failed\n")); + return 0; /* pthread_mutex_lock failed */ + } +#endif /* USE_THREADS_POSIX && HAVE_PTHREAD_H */ + } + return 1; /* OK */ +} + +int Curl_mbedtlsthreadlock_unlock_function(int n) +{ + if(n < NUMT) { +#if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) + if(pthread_mutex_unlock(&mutex_buf[n])) { + DEBUGF(fprintf(stderr, + "Error: mbedtlsthreadlock_unlock_function failed\n")); + return 0; /* pthread_mutex_unlock failed */ + } +#elif defined(_WIN32) + if(!ReleaseMutex(mutex_buf[n])) { + DEBUGF(fprintf(stderr, + "Error: mbedtlsthreadlock_unlock_function failed\n")); + return 0; /* pthread_mutex_lock failed */ + } +#endif /* USE_THREADS_POSIX && HAVE_PTHREAD_H */ + } + return 1; /* OK */ +} + +#endif /* USE_MBEDTLS */ diff --git a/third_party/curl/lib/vtls/mbedtls_threadlock.h b/third_party/curl/lib/vtls/mbedtls_threadlock.h new file mode 100644 index 0000000..4846268 --- /dev/null +++ b/third_party/curl/lib/vtls/mbedtls_threadlock.h @@ -0,0 +1,50 @@ +#ifndef HEADER_CURL_MBEDTLS_THREADLOCK_H +#define HEADER_CURL_MBEDTLS_THREADLOCK_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (C) Hoi-Ho Chan, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_MBEDTLS + +#if (defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H)) || \ + defined(_WIN32) + +int Curl_mbedtlsthreadlock_thread_setup(void); +int Curl_mbedtlsthreadlock_thread_cleanup(void); +int Curl_mbedtlsthreadlock_lock_function(int n); +int Curl_mbedtlsthreadlock_unlock_function(int n); + +#else + +#define Curl_mbedtlsthreadlock_thread_setup() 1 +#define Curl_mbedtlsthreadlock_thread_cleanup() 1 +#define Curl_mbedtlsthreadlock_lock_function(x) 1 +#define Curl_mbedtlsthreadlock_unlock_function(x) 1 + +#endif /* (USE_THREADS_POSIX && HAVE_PTHREAD_H) || _WIN32 */ + +#endif /* USE_MBEDTLS */ + +#endif /* HEADER_CURL_MBEDTLS_THREADLOCK_H */ diff --git a/third_party/curl/lib/vtls/openssl.c b/third_party/curl/lib/vtls/openssl.c new file mode 100644 index 0000000..298a488 --- /dev/null +++ b/third_party/curl/lib/vtls/openssl.c @@ -0,0 +1,5301 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Source file for all OpenSSL-specific code for the TLS/SSL layer. No code + * but vtls.c should ever call or use these functions. + */ + +#include "curl_setup.h" + +#if defined(USE_QUICHE) || defined(USE_OPENSSL) + +#include + +/* Wincrypt must be included before anything that could include OpenSSL. */ +#if defined(USE_WIN32_CRYPTO) +#include +/* Undefine wincrypt conflicting symbols for BoringSSL. */ +#undef X509_NAME +#undef X509_EXTENSIONS +#undef PKCS7_ISSUER_AND_SERIAL +#undef PKCS7_SIGNER_INFO +#undef OCSP_REQUEST +#undef OCSP_RESPONSE +#endif + +#include "urldata.h" +#include "sendf.h" +#include "formdata.h" /* for the boundary function */ +#include "url.h" /* for the ssl config check function */ +#include "inet_pton.h" +#include "openssl.h" +#include "connect.h" +#include "slist.h" +#include "select.h" +#include "vtls.h" +#include "vtls_int.h" +#include "vauth/vauth.h" +#include "keylog.h" +#include "strcase.h" +#include "hostcheck.h" +#include "multiif.h" +#include "strerror.h" +#include "curl_printf.h" + +#include +#include +#include +#ifndef OPENSSL_NO_DSA +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef USE_ECH +# ifndef OPENSSL_IS_BORINGSSL +# include +# endif +# include "curl_base64.h" +# define ECH_ENABLED(__data__) \ + (__data__->set.tls_ech && \ + !(__data__->set.tls_ech & CURLECH_DISABLE)\ + ) +#endif /* USE_ECH */ + +#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_OCSP) +#include +#endif + +#if (OPENSSL_VERSION_NUMBER >= 0x0090700fL) && /* 0.9.7 or later */ \ + !defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_UI_CONSOLE) +#define USE_OPENSSL_ENGINE +#include +#endif + +#include "warnless.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +#ifndef ARRAYSIZE +#define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) +#endif + +/* Uncomment the ALLOW_RENEG line to a real #define if you want to allow TLS + renegotiations when built with BoringSSL. Renegotiating is non-compliant + with HTTP/2 and "an extremely dangerous protocol feature". Beware. + +#define ALLOW_RENEG 1 + */ + +#ifndef OPENSSL_VERSION_NUMBER +#error "OPENSSL_VERSION_NUMBER not defined" +#endif + +#ifdef USE_OPENSSL_ENGINE +#include +#endif + +#if OPENSSL_VERSION_NUMBER >= 0x00909000L +#define SSL_METHOD_QUAL const +#else +#define SSL_METHOD_QUAL +#endif + +#if (OPENSSL_VERSION_NUMBER >= 0x10000000L) +#define HAVE_ERR_REMOVE_THREAD_STATE 1 +#endif + +#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && /* OpenSSL 1.1.0+ */ \ + !(defined(LIBRESSL_VERSION_NUMBER) && \ + LIBRESSL_VERSION_NUMBER < 0x20700000L) +#define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER +#define HAVE_X509_GET0_EXTENSIONS 1 /* added in 1.1.0 -pre1 */ +#define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */ +#define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */ +#define CONST_EXTS const +#define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1 + +/* funny typecast define due to difference in API */ +#ifdef LIBRESSL_VERSION_NUMBER +#define ARG2_X509_signature_print (X509_ALGOR *) +#else +#define ARG2_X509_signature_print +#endif + +#else +/* For OpenSSL before 1.1.0 */ +#define ASN1_STRING_get0_data(x) ASN1_STRING_data(x) +#define X509_get0_notBefore(x) X509_get_notBefore(x) +#define X509_get0_notAfter(x) X509_get_notAfter(x) +#define CONST_EXTS /* nope */ +#ifndef LIBRESSL_VERSION_NUMBER +#define OpenSSL_version_num() SSLeay() +#endif +#endif + +#if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* 1.0.2 or later */ \ + !(defined(LIBRESSL_VERSION_NUMBER) && \ + LIBRESSL_VERSION_NUMBER < 0x20700000L) +#define HAVE_X509_GET0_SIGNATURE 1 +#endif + +#if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) /* 1.0.2 or later */ +#define HAVE_SSL_GET_SHUTDOWN 1 +#endif + +#if OPENSSL_VERSION_NUMBER >= 0x10002003L && \ + OPENSSL_VERSION_NUMBER <= 0x10002FFFL && \ + !defined(OPENSSL_NO_COMP) +#define HAVE_SSL_COMP_FREE_COMPRESSION_METHODS 1 +#endif + +#if (OPENSSL_VERSION_NUMBER < 0x0090808fL) +/* not present in older OpenSSL */ +#define OPENSSL_load_builtin_modules(x) +#endif + +#if (OPENSSL_VERSION_NUMBER >= 0x30000000L) +#define HAVE_EVP_PKEY_GET_PARAMS 1 +#endif + +#ifdef HAVE_EVP_PKEY_GET_PARAMS +#include +#define DECLARE_PKEY_PARAM_BIGNUM(name) BIGNUM *name = NULL +#define FREE_PKEY_PARAM_BIGNUM(name) BN_clear_free(name) +#else +#define DECLARE_PKEY_PARAM_BIGNUM(name) const BIGNUM *name +#define FREE_PKEY_PARAM_BIGNUM(name) +#endif + +/* + * Whether SSL_CTX_set_keylog_callback is available. + * OpenSSL: supported since 1.1.1 https://github.com/openssl/openssl/pull/2287 + * BoringSSL: supported since d28f59c27bac (committed 2015-11-19) + * LibreSSL: not supported. 3.5.0+ has a stub function that does nothing. + */ +#if (OPENSSL_VERSION_NUMBER >= 0x10101000L && \ + !defined(LIBRESSL_VERSION_NUMBER)) || \ + defined(OPENSSL_IS_BORINGSSL) +#define HAVE_KEYLOG_CALLBACK +#endif + +/* Whether SSL_CTX_set_ciphersuites is available. + * OpenSSL: supported since 1.1.1 (commit a53b5be6a05) + * BoringSSL: no + * LibreSSL: supported since 3.4.1 (released 2021-10-14) + */ +#if ((OPENSSL_VERSION_NUMBER >= 0x10101000L && \ + !defined(LIBRESSL_VERSION_NUMBER)) || \ + (defined(LIBRESSL_VERSION_NUMBER) && \ + LIBRESSL_VERSION_NUMBER >= 0x3040100fL)) && \ + !defined(OPENSSL_IS_BORINGSSL) + #define HAVE_SSL_CTX_SET_CIPHERSUITES + #if !defined(OPENSSL_IS_AWSLC) + #define HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH + #endif +#endif + +/* + * Whether SSL_CTX_set1_curves_list is available. + * OpenSSL: supported since 1.0.2, see + * https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set1_groups.html + * BoringSSL: supported since 5fd1807d95f7 (committed 2016-09-30) + * LibreSSL: since 2.5.3 (April 12, 2017) + */ +#if (OPENSSL_VERSION_NUMBER >= 0x10002000L) || \ + defined(OPENSSL_IS_BORINGSSL) +#define HAVE_SSL_CTX_SET_EC_CURVES +#endif + +#if defined(LIBRESSL_VERSION_NUMBER) +#define OSSL_PACKAGE "LibreSSL" +#elif defined(OPENSSL_IS_BORINGSSL) +#define OSSL_PACKAGE "BoringSSL" +#elif defined(OPENSSL_IS_AWSLC) +#define OSSL_PACKAGE "AWS-LC" +#else +# if defined(USE_NGTCP2) && defined(USE_NGHTTP3) +# define OSSL_PACKAGE "quictls" +# else +# define OSSL_PACKAGE "OpenSSL" +#endif +#endif + +#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) +/* up2date versions of OpenSSL maintain reasonably secure defaults without + * breaking compatibility, so it is better not to override the defaults in curl + */ +#define DEFAULT_CIPHER_SELECTION NULL +#else +/* ... but it is not the case with old versions of OpenSSL */ +#define DEFAULT_CIPHER_SELECTION \ + "ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH" +#endif + +#ifdef HAVE_OPENSSL_SRP +/* the function exists */ +#ifdef USE_TLS_SRP +/* the functionality is not disabled */ +#define USE_OPENSSL_SRP +#endif +#endif + +#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) +#define HAVE_RANDOM_INIT_BY_DEFAULT 1 +#endif + +#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \ + !(defined(LIBRESSL_VERSION_NUMBER) && \ + LIBRESSL_VERSION_NUMBER < 0x2070100fL) && \ + !defined(OPENSSL_IS_BORINGSSL) && \ + !defined(OPENSSL_IS_AWSLC) +#define HAVE_OPENSSL_VERSION +#endif + +#if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) +typedef uint32_t sslerr_t; +#else +typedef unsigned long sslerr_t; +#endif + +/* + * Whether the OpenSSL version has the API needed to support sharing an + * X509_STORE between connections. The API is: + * * `X509_STORE_up_ref` -- Introduced: OpenSSL 1.1.0. + */ +#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* OpenSSL >= 1.1.0 */ +#define HAVE_SSL_X509_STORE_SHARE +#endif + +/* What API version do we use? */ +#if defined(LIBRESSL_VERSION_NUMBER) +#define USE_PRE_1_1_API (LIBRESSL_VERSION_NUMBER < 0x2070000f) +#else /* !LIBRESSL_VERSION_NUMBER */ +#define USE_PRE_1_1_API (OPENSSL_VERSION_NUMBER < 0x10100000L) +#endif /* !LIBRESSL_VERSION_NUMBER */ + +#if defined(HAVE_SSL_X509_STORE_SHARE) +struct multi_ssl_backend_data { + char *CAfile; /* CAfile path used to generate X509 store */ + X509_STORE *store; /* cached X509 store or NULL if none */ + struct curltime time; /* when the cached store was created */ +}; +#endif /* HAVE_SSL_X509_STORE_SHARE */ + +#define push_certinfo(_label, _num) \ +do { \ + long info_len = BIO_get_mem_data(mem, &ptr); \ + Curl_ssl_push_certinfo_len(data, _num, _label, ptr, info_len); \ + if(1 != BIO_reset(mem)) \ + break; \ +} while(0) + +static void pubkey_show(struct Curl_easy *data, + BIO *mem, + int num, + const char *type, + const char *name, + const BIGNUM *bn) +{ + char *ptr; + char namebuf[32]; + + msnprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name); + + if(bn) + BN_print(mem, bn); + push_certinfo(namebuf, num); +} + +#ifdef HAVE_OPAQUE_RSA_DSA_DH +#define print_pubkey_BN(_type, _name, _num) \ + pubkey_show(data, mem, _num, #_type, #_name, _name) + +#else +#define print_pubkey_BN(_type, _name, _num) \ +do { \ + if(_type->_name) { \ + pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \ + } \ +} while(0) +#endif + +static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len) +{ + int i, ilen; + + ilen = (int)len; + if(ilen < 0) + return 1; /* buffer too big */ + + i = i2t_ASN1_OBJECT(buf, ilen, a); + + if(i >= ilen) + return 1; /* buffer too small */ + + return 0; +} + +static void X509V3_ext(struct Curl_easy *data, + int certnum, + CONST_EXTS STACK_OF(X509_EXTENSION) *exts) +{ + int i; + + if((int)sk_X509_EXTENSION_num(exts) <= 0) + /* no extensions, bail out */ + return; + + for(i = 0; i < (int)sk_X509_EXTENSION_num(exts); i++) { + ASN1_OBJECT *obj; + X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i); + BUF_MEM *biomem; + char namebuf[128]; + BIO *bio_out = BIO_new(BIO_s_mem()); + + if(!bio_out) + return; + + obj = X509_EXTENSION_get_object(ext); + + asn1_object_dump(obj, namebuf, sizeof(namebuf)); + + if(!X509V3_EXT_print(bio_out, ext, 0, 0)) + ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext)); + + BIO_get_mem_ptr(bio_out, &biomem); + Curl_ssl_push_certinfo_len(data, certnum, namebuf, biomem->data, + biomem->length); + BIO_free(bio_out); + } +} + +#if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) +typedef size_t numcert_t; +#else +typedef int numcert_t; +#endif + +CURLcode Curl_ossl_certchain(struct Curl_easy *data, SSL *ssl) +{ + CURLcode result; + STACK_OF(X509) *sk; + int i; + numcert_t numcerts; + BIO *mem; + + DEBUGASSERT(ssl); + + sk = SSL_get_peer_cert_chain(ssl); + if(!sk) { + return CURLE_OUT_OF_MEMORY; + } + + numcerts = sk_X509_num(sk); + + result = Curl_ssl_init_certinfo(data, (int)numcerts); + if(result) { + return result; + } + + mem = BIO_new(BIO_s_mem()); + if(!mem) { + return CURLE_OUT_OF_MEMORY; + } + + for(i = 0; i < (int)numcerts; i++) { + ASN1_INTEGER *num; + X509 *x = sk_X509_value(sk, i); + EVP_PKEY *pubkey = NULL; + int j; + char *ptr; + const ASN1_BIT_STRING *psig = NULL; + + X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE); + push_certinfo("Subject", i); + + X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE); + push_certinfo("Issuer", i); + + BIO_printf(mem, "%lx", X509_get_version(x)); + push_certinfo("Version", i); + + num = X509_get_serialNumber(x); + if(num->type == V_ASN1_NEG_INTEGER) + BIO_puts(mem, "-"); + for(j = 0; j < num->length; j++) + BIO_printf(mem, "%02x", num->data[j]); + push_certinfo("Serial Number", i); + +#if defined(HAVE_X509_GET0_SIGNATURE) && defined(HAVE_X509_GET0_EXTENSIONS) + { + const X509_ALGOR *sigalg = NULL; + X509_PUBKEY *xpubkey = NULL; + ASN1_OBJECT *pubkeyoid = NULL; + + X509_get0_signature(&psig, &sigalg, x); + if(sigalg) { + const ASN1_OBJECT *sigalgoid = NULL; + X509_ALGOR_get0(&sigalgoid, NULL, NULL, sigalg); + i2a_ASN1_OBJECT(mem, sigalgoid); + push_certinfo("Signature Algorithm", i); + } + + xpubkey = X509_get_X509_PUBKEY(x); + if(xpubkey) { + X509_PUBKEY_get0_param(&pubkeyoid, NULL, NULL, NULL, xpubkey); + if(pubkeyoid) { + i2a_ASN1_OBJECT(mem, pubkeyoid); + push_certinfo("Public Key Algorithm", i); + } + } + + X509V3_ext(data, i, X509_get0_extensions(x)); + } +#else + { + /* before OpenSSL 1.0.2 */ + X509_CINF *cinf = x->cert_info; + + i2a_ASN1_OBJECT(mem, cinf->signature->algorithm); + push_certinfo("Signature Algorithm", i); + + i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm); + push_certinfo("Public Key Algorithm", i); + + X509V3_ext(data, i, cinf->extensions); + + psig = x->signature; + } +#endif + + ASN1_TIME_print(mem, X509_get0_notBefore(x)); + push_certinfo("Start date", i); + + ASN1_TIME_print(mem, X509_get0_notAfter(x)); + push_certinfo("Expire date", i); + + pubkey = X509_get_pubkey(x); + if(!pubkey) + infof(data, " Unable to load public key"); + else { + int pktype; +#ifdef HAVE_OPAQUE_EVP_PKEY + pktype = EVP_PKEY_id(pubkey); +#else + pktype = pubkey->type; +#endif + switch(pktype) { + case EVP_PKEY_RSA: + { +#ifndef HAVE_EVP_PKEY_GET_PARAMS + RSA *rsa; +#ifdef HAVE_OPAQUE_EVP_PKEY + rsa = EVP_PKEY_get0_RSA(pubkey); +#else + rsa = pubkey->pkey.rsa; +#endif /* HAVE_OPAQUE_EVP_PKEY */ +#endif /* !HAVE_EVP_PKEY_GET_PARAMS */ + + { +#ifdef HAVE_OPAQUE_RSA_DSA_DH + DECLARE_PKEY_PARAM_BIGNUM(n); + DECLARE_PKEY_PARAM_BIGNUM(e); +#ifdef HAVE_EVP_PKEY_GET_PARAMS + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_RSA_N, &n); + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_RSA_E, &e); +#else + RSA_get0_key(rsa, &n, &e, NULL); +#endif /* HAVE_EVP_PKEY_GET_PARAMS */ + BIO_printf(mem, "%d", n ? BN_num_bits(n) : 0); +#else + BIO_printf(mem, "%d", rsa->n ? BN_num_bits(rsa->n) : 0); +#endif /* HAVE_OPAQUE_RSA_DSA_DH */ + push_certinfo("RSA Public Key", i); + print_pubkey_BN(rsa, n, i); + print_pubkey_BN(rsa, e, i); + FREE_PKEY_PARAM_BIGNUM(n); + FREE_PKEY_PARAM_BIGNUM(e); + } + + break; + } + case EVP_PKEY_DSA: + { +#ifndef OPENSSL_NO_DSA +#ifndef HAVE_EVP_PKEY_GET_PARAMS + DSA *dsa; +#ifdef HAVE_OPAQUE_EVP_PKEY + dsa = EVP_PKEY_get0_DSA(pubkey); +#else + dsa = pubkey->pkey.dsa; +#endif /* HAVE_OPAQUE_EVP_PKEY */ +#endif /* !HAVE_EVP_PKEY_GET_PARAMS */ + { +#ifdef HAVE_OPAQUE_RSA_DSA_DH + DECLARE_PKEY_PARAM_BIGNUM(p); + DECLARE_PKEY_PARAM_BIGNUM(q); + DECLARE_PKEY_PARAM_BIGNUM(g); + DECLARE_PKEY_PARAM_BIGNUM(pub_key); +#ifdef HAVE_EVP_PKEY_GET_PARAMS + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_P, &p); + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_Q, &q); + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_G, &g); + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_PUB_KEY, &pub_key); +#else + DSA_get0_pqg(dsa, &p, &q, &g); + DSA_get0_key(dsa, &pub_key, NULL); +#endif /* HAVE_EVP_PKEY_GET_PARAMS */ +#endif /* HAVE_OPAQUE_RSA_DSA_DH */ + print_pubkey_BN(dsa, p, i); + print_pubkey_BN(dsa, q, i); + print_pubkey_BN(dsa, g, i); + print_pubkey_BN(dsa, pub_key, i); + FREE_PKEY_PARAM_BIGNUM(p); + FREE_PKEY_PARAM_BIGNUM(q); + FREE_PKEY_PARAM_BIGNUM(g); + FREE_PKEY_PARAM_BIGNUM(pub_key); + } +#endif /* !OPENSSL_NO_DSA */ + break; + } + case EVP_PKEY_DH: + { +#ifndef HAVE_EVP_PKEY_GET_PARAMS + DH *dh; +#ifdef HAVE_OPAQUE_EVP_PKEY + dh = EVP_PKEY_get0_DH(pubkey); +#else + dh = pubkey->pkey.dh; +#endif /* HAVE_OPAQUE_EVP_PKEY */ +#endif /* !HAVE_EVP_PKEY_GET_PARAMS */ + { +#ifdef HAVE_OPAQUE_RSA_DSA_DH + DECLARE_PKEY_PARAM_BIGNUM(p); + DECLARE_PKEY_PARAM_BIGNUM(q); + DECLARE_PKEY_PARAM_BIGNUM(g); + DECLARE_PKEY_PARAM_BIGNUM(pub_key); +#ifdef HAVE_EVP_PKEY_GET_PARAMS + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_P, &p); + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_Q, &q); + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_G, &g); + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_PUB_KEY, &pub_key); +#else + DH_get0_pqg(dh, &p, &q, &g); + DH_get0_key(dh, &pub_key, NULL); +#endif /* HAVE_EVP_PKEY_GET_PARAMS */ + print_pubkey_BN(dh, p, i); + print_pubkey_BN(dh, q, i); + print_pubkey_BN(dh, g, i); +#else + print_pubkey_BN(dh, p, i); + print_pubkey_BN(dh, g, i); +#endif /* HAVE_OPAQUE_RSA_DSA_DH */ + print_pubkey_BN(dh, pub_key, i); + FREE_PKEY_PARAM_BIGNUM(p); + FREE_PKEY_PARAM_BIGNUM(q); + FREE_PKEY_PARAM_BIGNUM(g); + FREE_PKEY_PARAM_BIGNUM(pub_key); + } + break; + } + } + EVP_PKEY_free(pubkey); + } + + if(psig) { + for(j = 0; j < psig->length; j++) + BIO_printf(mem, "%02x:", psig->data[j]); + push_certinfo("Signature", i); + } + + PEM_write_bio_X509(mem, x); + push_certinfo("Cert", i); + } + + BIO_free(mem); + + return CURLE_OK; +} + +#endif /* quiche or OpenSSL */ + +#ifdef USE_OPENSSL + +#if USE_PRE_1_1_API +#if !defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER < 0x2070000fL +#define BIO_set_init(x,v) ((x)->init=(v)) +#define BIO_get_data(x) ((x)->ptr) +#define BIO_set_data(x,v) ((x)->ptr=(v)) +#endif +#define BIO_get_shutdown(x) ((x)->shutdown) +#define BIO_set_shutdown(x,v) ((x)->shutdown=(v)) +#endif /* USE_PRE_1_1_API */ + +static int ossl_bio_cf_create(BIO *bio) +{ + BIO_set_shutdown(bio, 1); + BIO_set_init(bio, 1); +#if USE_PRE_1_1_API + bio->num = -1; +#endif + BIO_set_data(bio, NULL); + return 1; +} + +static int ossl_bio_cf_destroy(BIO *bio) +{ + if(!bio) + return 0; + return 1; +} + +static long ossl_bio_cf_ctrl(BIO *bio, int cmd, long num, void *ptr) +{ + struct Curl_cfilter *cf = BIO_get_data(bio); + long ret = 1; + + (void)cf; + (void)ptr; + switch(cmd) { + case BIO_CTRL_GET_CLOSE: + ret = (long)BIO_get_shutdown(bio); + break; + case BIO_CTRL_SET_CLOSE: + BIO_set_shutdown(bio, (int)num); + break; + case BIO_CTRL_FLUSH: + /* we do no delayed writes, but if we ever would, this + * needs to trigger it. */ + ret = 1; + break; + case BIO_CTRL_DUP: + ret = 1; + break; +#ifdef BIO_CTRL_EOF + case BIO_CTRL_EOF: + /* EOF has been reached on input? */ + return (!cf->next || !cf->next->connected); +#endif + default: + ret = 0; + break; + } + return ret; +} + +static int ossl_bio_cf_out_write(BIO *bio, const char *buf, int blen) +{ + struct Curl_cfilter *cf = BIO_get_data(bio); + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + ssize_t nwritten; + CURLcode result = CURLE_SEND_ERROR; + + DEBUGASSERT(data); + nwritten = Curl_conn_cf_send(cf->next, data, buf, blen, &result); + CURL_TRC_CF(data, cf, "ossl_bio_cf_out_write(len=%d) -> %d, err=%d", + blen, (int)nwritten, result); + BIO_clear_retry_flags(bio); + octx->io_result = result; + if(nwritten < 0) { + if(CURLE_AGAIN == result) + BIO_set_retry_write(bio); + } + return (int)nwritten; +} + +static int ossl_bio_cf_in_read(BIO *bio, char *buf, int blen) +{ + struct Curl_cfilter *cf = BIO_get_data(bio); + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + ssize_t nread; + CURLcode result = CURLE_RECV_ERROR; + + DEBUGASSERT(data); + /* OpenSSL catches this case, so should we. */ + if(!buf) + return 0; + + nread = Curl_conn_cf_recv(cf->next, data, buf, blen, &result); + CURL_TRC_CF(data, cf, "ossl_bio_cf_in_read(len=%d) -> %d, err=%d", + blen, (int)nread, result); + BIO_clear_retry_flags(bio); + octx->io_result = result; + if(nread < 0) { + if(CURLE_AGAIN == result) + BIO_set_retry_read(bio); + } + else if(nread == 0) { + connssl->peer_closed = TRUE; + } + + /* Before returning server replies to the SSL instance, we need + * to have setup the x509 store or verification will fail. */ + if(!octx->x509_store_setup) { + result = Curl_ssl_setup_x509_store(cf, data, octx->ssl_ctx); + if(result) { + octx->io_result = result; + return -1; + } + octx->x509_store_setup = TRUE; + } + + return (int)nread; +} + +#if USE_PRE_1_1_API + +static BIO_METHOD ossl_bio_cf_meth_1_0 = { + BIO_TYPE_MEM, + "OpenSSL CF BIO", + ossl_bio_cf_out_write, + ossl_bio_cf_in_read, + NULL, /* puts is never called */ + NULL, /* gets is never called */ + ossl_bio_cf_ctrl, + ossl_bio_cf_create, + ossl_bio_cf_destroy, + NULL +}; + +static BIO_METHOD *ossl_bio_cf_method_create(void) +{ + return &ossl_bio_cf_meth_1_0; +} + +#define ossl_bio_cf_method_free(m) Curl_nop_stmt + +#else + +static BIO_METHOD *ossl_bio_cf_method_create(void) +{ + BIO_METHOD *m = BIO_meth_new(BIO_TYPE_MEM, "OpenSSL CF BIO"); + if(m) { + BIO_meth_set_write(m, &ossl_bio_cf_out_write); + BIO_meth_set_read(m, &ossl_bio_cf_in_read); + BIO_meth_set_ctrl(m, &ossl_bio_cf_ctrl); + BIO_meth_set_create(m, &ossl_bio_cf_create); + BIO_meth_set_destroy(m, &ossl_bio_cf_destroy); + } + return m; +} + +static void ossl_bio_cf_method_free(BIO_METHOD *m) +{ + if(m) + BIO_meth_free(m); +} + +#endif + + +/* + * Number of bytes to read from the random number seed file. This must be + * a finite value (because some entropy "files" like /dev/urandom have + * an infinite length), but must be large enough to provide enough + * entropy to properly seed OpenSSL's PRNG. + */ +#define RAND_LOAD_LENGTH 1024 + +#ifdef HAVE_KEYLOG_CALLBACK +static void ossl_keylog_callback(const SSL *ssl, const char *line) +{ + (void)ssl; + + Curl_tls_keylog_write_line(line); +} +#else +/* + * ossl_log_tls12_secret is called by libcurl to make the CLIENT_RANDOMs if the + * OpenSSL being used doesn't have native support for doing that. + */ +static void +ossl_log_tls12_secret(const SSL *ssl, bool *keylog_done) +{ + const SSL_SESSION *session = SSL_get_session(ssl); + unsigned char client_random[SSL3_RANDOM_SIZE]; + unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH]; + int master_key_length = 0; + + if(!session || *keylog_done) + return; + +#if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ + !(defined(LIBRESSL_VERSION_NUMBER) && \ + LIBRESSL_VERSION_NUMBER < 0x20700000L) + /* ssl->s3 is not checked in openssl 1.1.0-pre6, but let's assume that + * we have a valid SSL context if we have a non-NULL session. */ + SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE); + master_key_length = (int) + SSL_SESSION_get_master_key(session, master_key, SSL_MAX_MASTER_KEY_LENGTH); +#else + if(ssl->s3 && session->master_key_length > 0) { + master_key_length = session->master_key_length; + memcpy(master_key, session->master_key, session->master_key_length); + memcpy(client_random, ssl->s3->client_random, SSL3_RANDOM_SIZE); + } +#endif + + /* The handshake has not progressed sufficiently yet, or this is a TLS 1.3 + * session (when curl was built with older OpenSSL headers and running with + * newer OpenSSL runtime libraries). */ + if(master_key_length <= 0) + return; + + *keylog_done = true; + Curl_tls_keylog_write("CLIENT_RANDOM", client_random, + master_key, master_key_length); +} +#endif /* !HAVE_KEYLOG_CALLBACK */ + +static const char *SSL_ERROR_to_str(int err) +{ + switch(err) { + case SSL_ERROR_NONE: + return "SSL_ERROR_NONE"; + case SSL_ERROR_SSL: + return "SSL_ERROR_SSL"; + case SSL_ERROR_WANT_READ: + return "SSL_ERROR_WANT_READ"; + case SSL_ERROR_WANT_WRITE: + return "SSL_ERROR_WANT_WRITE"; + case SSL_ERROR_WANT_X509_LOOKUP: + return "SSL_ERROR_WANT_X509_LOOKUP"; + case SSL_ERROR_SYSCALL: + return "SSL_ERROR_SYSCALL"; + case SSL_ERROR_ZERO_RETURN: + return "SSL_ERROR_ZERO_RETURN"; + case SSL_ERROR_WANT_CONNECT: + return "SSL_ERROR_WANT_CONNECT"; + case SSL_ERROR_WANT_ACCEPT: + return "SSL_ERROR_WANT_ACCEPT"; +#if defined(SSL_ERROR_WANT_ASYNC) + case SSL_ERROR_WANT_ASYNC: + return "SSL_ERROR_WANT_ASYNC"; +#endif +#if defined(SSL_ERROR_WANT_ASYNC_JOB) + case SSL_ERROR_WANT_ASYNC_JOB: + return "SSL_ERROR_WANT_ASYNC_JOB"; +#endif +#if defined(SSL_ERROR_WANT_EARLY) + case SSL_ERROR_WANT_EARLY: + return "SSL_ERROR_WANT_EARLY"; +#endif + default: + return "SSL_ERROR unknown"; + } +} + +static size_t ossl_version(char *buffer, size_t size); + +/* Return error string for last OpenSSL error + */ +static char *ossl_strerror(unsigned long error, char *buf, size_t size) +{ + size_t len; + DEBUGASSERT(size); + *buf = '\0'; + + len = ossl_version(buf, size); + DEBUGASSERT(len < (size - 2)); + if(len < (size - 2)) { + buf += len; + size -= (len + 2); + *buf++ = ':'; + *buf++ = ' '; + *buf = '\0'; + } + +#if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) + ERR_error_string_n((uint32_t)error, buf, size); +#else + ERR_error_string_n(error, buf, size); +#endif + + if(!*buf) { + const char *msg = error ? "Unknown error" : "No error"; + if(strlen(msg) < size) + strcpy(buf, msg); + } + + return buf; +} + +static int passwd_callback(char *buf, int num, int encrypting, + void *global_passwd) +{ + DEBUGASSERT(0 == encrypting); + + if(!encrypting) { + int klen = curlx_uztosi(strlen((char *)global_passwd)); + if(num > klen) { + memcpy(buf, global_passwd, klen + 1); + return klen; + } + } + return 0; +} + +/* + * rand_enough() returns TRUE if we have seeded the random engine properly. + */ +static bool rand_enough(void) +{ + return (0 != RAND_status()) ? TRUE : FALSE; +} + +static CURLcode ossl_seed(struct Curl_easy *data) +{ + /* This might get called before it has been added to a multi handle */ + if(data->multi && data->multi->ssl_seeded) + return CURLE_OK; + + if(rand_enough()) { + /* OpenSSL 1.1.0+ should return here */ + if(data->multi) + data->multi->ssl_seeded = TRUE; + return CURLE_OK; + } +#ifdef HAVE_RANDOM_INIT_BY_DEFAULT + /* with OpenSSL 1.1.0+, a failed RAND_status is a showstopper */ + failf(data, "Insufficient randomness"); + return CURLE_SSL_CONNECT_ERROR; +#else + +#ifdef RANDOM_FILE + RAND_load_file(RANDOM_FILE, RAND_LOAD_LENGTH); + if(rand_enough()) + return CURLE_OK; +#endif + + /* fallback to a custom seeding of the PRNG using a hash based on a current + time */ + do { + unsigned char randb[64]; + size_t len = sizeof(randb); + size_t i, i_max; + for(i = 0, i_max = len / sizeof(struct curltime); i < i_max; ++i) { + struct curltime tv = Curl_now(); + Curl_wait_ms(1); + tv.tv_sec *= i + 1; + tv.tv_usec *= (unsigned int)i + 2; + tv.tv_sec ^= ((Curl_now().tv_sec + Curl_now().tv_usec) * + (i + 3)) << 8; + tv.tv_usec ^= (unsigned int) ((Curl_now().tv_sec + + Curl_now().tv_usec) * + (i + 4)) << 16; + memcpy(&randb[i * sizeof(struct curltime)], &tv, + sizeof(struct curltime)); + } + RAND_add(randb, (int)len, (double)len/2); + } while(!rand_enough()); + + { + /* generates a default path for the random seed file */ + char fname[256]; + fname[0] = 0; /* blank it first */ + RAND_file_name(fname, sizeof(fname)); + if(fname[0]) { + /* we got a file name to try */ + RAND_load_file(fname, RAND_LOAD_LENGTH); + if(rand_enough()) + return CURLE_OK; + } + } + + infof(data, "libcurl is now using a weak random seed"); + return (rand_enough() ? CURLE_OK : + CURLE_SSL_CONNECT_ERROR /* confusing error code */); +#endif +} + +#ifndef SSL_FILETYPE_ENGINE +#define SSL_FILETYPE_ENGINE 42 +#endif +#ifndef SSL_FILETYPE_PKCS12 +#define SSL_FILETYPE_PKCS12 43 +#endif +static int do_file_type(const char *type) +{ + if(!type || !type[0]) + return SSL_FILETYPE_PEM; + if(strcasecompare(type, "PEM")) + return SSL_FILETYPE_PEM; + if(strcasecompare(type, "DER")) + return SSL_FILETYPE_ASN1; + if(strcasecompare(type, "ENG")) + return SSL_FILETYPE_ENGINE; + if(strcasecompare(type, "P12")) + return SSL_FILETYPE_PKCS12; + return -1; +} + +#ifdef USE_OPENSSL_ENGINE +/* + * Supply default password to the engine user interface conversation. + * The password is passed by OpenSSL engine from ENGINE_load_private_key() + * last argument to the ui and can be obtained by UI_get0_user_data(ui) here. + */ +static int ssl_ui_reader(UI *ui, UI_STRING *uis) +{ + const char *password; + switch(UI_get_string_type(uis)) { + case UIT_PROMPT: + case UIT_VERIFY: + password = (const char *)UI_get0_user_data(ui); + if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) { + UI_set_result(ui, uis, password); + return 1; + } + FALLTHROUGH(); + default: + break; + } + return (UI_method_get_reader(UI_OpenSSL()))(ui, uis); +} + +/* + * Suppress interactive request for a default password if available. + */ +static int ssl_ui_writer(UI *ui, UI_STRING *uis) +{ + switch(UI_get_string_type(uis)) { + case UIT_PROMPT: + case UIT_VERIFY: + if(UI_get0_user_data(ui) && + (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) { + return 1; + } + FALLTHROUGH(); + default: + break; + } + return (UI_method_get_writer(UI_OpenSSL()))(ui, uis); +} + +/* + * Check if a given string is a PKCS#11 URI + */ +static bool is_pkcs11_uri(const char *string) +{ + return (string && strncasecompare(string, "pkcs11:", 7)); +} + +#endif + +static CURLcode ossl_set_engine(struct Curl_easy *data, const char *engine); + +static int +SSL_CTX_use_certificate_blob(SSL_CTX *ctx, const struct curl_blob *blob, + int type, const char *key_passwd) +{ + int ret = 0; + X509 *x = NULL; + /* the typecast of blob->len is fine since it is guaranteed to never be + larger than CURL_MAX_INPUT_LENGTH */ + BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len)); + if(!in) + return CURLE_OUT_OF_MEMORY; + + if(type == SSL_FILETYPE_ASN1) { + /* j = ERR_R_ASN1_LIB; */ + x = d2i_X509_bio(in, NULL); + } + else if(type == SSL_FILETYPE_PEM) { + /* ERR_R_PEM_LIB; */ + x = PEM_read_bio_X509(in, NULL, + passwd_callback, (void *)key_passwd); + } + else { + ret = 0; + goto end; + } + + if(!x) { + ret = 0; + goto end; + } + + ret = SSL_CTX_use_certificate(ctx, x); +end: + X509_free(x); + BIO_free(in); + return ret; +} + +static int +SSL_CTX_use_PrivateKey_blob(SSL_CTX *ctx, const struct curl_blob *blob, + int type, const char *key_passwd) +{ + int ret = 0; + EVP_PKEY *pkey = NULL; + BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len)); + if(!in) + return CURLE_OUT_OF_MEMORY; + + if(type == SSL_FILETYPE_PEM) + pkey = PEM_read_bio_PrivateKey(in, NULL, passwd_callback, + (void *)key_passwd); + else if(type == SSL_FILETYPE_ASN1) + pkey = d2i_PrivateKey_bio(in, NULL); + else { + ret = 0; + goto end; + } + if(!pkey) { + ret = 0; + goto end; + } + ret = SSL_CTX_use_PrivateKey(ctx, pkey); + EVP_PKEY_free(pkey); +end: + BIO_free(in); + return ret; +} + +static int +SSL_CTX_use_certificate_chain_blob(SSL_CTX *ctx, const struct curl_blob *blob, + const char *key_passwd) +{ +/* SSL_CTX_add1_chain_cert introduced in OpenSSL 1.0.2 */ +#if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* OpenSSL 1.0.2 or later */ \ + !(defined(LIBRESSL_VERSION_NUMBER) && \ + (LIBRESSL_VERSION_NUMBER < 0x2090100fL)) /* LibreSSL 2.9.1 or later */ + int ret = 0; + X509 *x = NULL; + void *passwd_callback_userdata = (void *)key_passwd; + BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len)); + if(!in) + return CURLE_OUT_OF_MEMORY; + + ERR_clear_error(); + + x = PEM_read_bio_X509_AUX(in, NULL, + passwd_callback, (void *)key_passwd); + + if(!x) { + ret = 0; + goto end; + } + + ret = SSL_CTX_use_certificate(ctx, x); + + if(ERR_peek_error() != 0) + ret = 0; + + if(ret) { + X509 *ca; + sslerr_t err; + + if(!SSL_CTX_clear_chain_certs(ctx)) { + ret = 0; + goto end; + } + + while((ca = PEM_read_bio_X509(in, NULL, passwd_callback, + passwd_callback_userdata)) + != NULL) { + + if(!SSL_CTX_add0_chain_cert(ctx, ca)) { + X509_free(ca); + ret = 0; + goto end; + } + } + + err = ERR_peek_last_error(); + if((ERR_GET_LIB(err) == ERR_LIB_PEM) && + (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) + ERR_clear_error(); + else + ret = 0; + } + +end: + X509_free(x); + BIO_free(in); + return ret; +#else + (void)ctx; /* unused */ + (void)blob; /* unused */ + (void)key_passwd; /* unused */ + return 0; +#endif +} + +static +int cert_stuff(struct Curl_easy *data, + SSL_CTX* ctx, + char *cert_file, + const struct curl_blob *cert_blob, + const char *cert_type, + char *key_file, + const struct curl_blob *key_blob, + const char *key_type, + char *key_passwd) +{ + char error_buffer[256]; + bool check_privkey = TRUE; + + int file_type = do_file_type(cert_type); + + if(cert_file || cert_blob || (file_type == SSL_FILETYPE_ENGINE)) { + SSL *ssl; + X509 *x509; + int cert_done = 0; + int cert_use_result; + + if(key_passwd) { + /* set the password in the callback userdata */ + SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd); + /* Set passwd callback: */ + SSL_CTX_set_default_passwd_cb(ctx, passwd_callback); + } + + + switch(file_type) { + case SSL_FILETYPE_PEM: + /* SSL_CTX_use_certificate_chain_file() only works on PEM files */ + cert_use_result = cert_blob ? + SSL_CTX_use_certificate_chain_blob(ctx, cert_blob, key_passwd) : + SSL_CTX_use_certificate_chain_file(ctx, cert_file); + if(cert_use_result != 1) { + failf(data, + "could not load PEM client certificate from %s, " OSSL_PACKAGE + " error %s, " + "(no key found, wrong pass phrase, or wrong file format?)", + (cert_blob ? "CURLOPT_SSLCERT_BLOB" : cert_file), + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer)) ); + return 0; + } + break; + + case SSL_FILETYPE_ASN1: + /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but + we use the case above for PEM so this can only be performed with + ASN1 files. */ + + cert_use_result = cert_blob ? + SSL_CTX_use_certificate_blob(ctx, cert_blob, + file_type, key_passwd) : + SSL_CTX_use_certificate_file(ctx, cert_file, file_type); + if(cert_use_result != 1) { + failf(data, + "could not load ASN1 client certificate from %s, " OSSL_PACKAGE + " error %s, " + "(no key found, wrong pass phrase, or wrong file format?)", + (cert_blob ? "CURLOPT_SSLCERT_BLOB" : cert_file), + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer)) ); + return 0; + } + break; + case SSL_FILETYPE_ENGINE: +#if defined(USE_OPENSSL_ENGINE) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME) + { + /* Implicitly use pkcs11 engine if none was provided and the + * cert_file is a PKCS#11 URI */ + if(!data->state.engine) { + if(is_pkcs11_uri(cert_file)) { + if(ossl_set_engine(data, "pkcs11") != CURLE_OK) { + return 0; + } + } + } + + if(data->state.engine) { + const char *cmd_name = "LOAD_CERT_CTRL"; + struct { + const char *cert_id; + X509 *cert; + } params; + + params.cert_id = cert_file; + params.cert = NULL; + + /* Does the engine supports LOAD_CERT_CTRL ? */ + if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME, + 0, (void *)cmd_name, NULL)) { + failf(data, "ssl engine does not support loading certificates"); + return 0; + } + + /* Load the certificate from the engine */ + if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name, + 0, ¶ms, NULL, 1)) { + failf(data, "ssl engine cannot load client cert with id" + " '%s' [%s]", cert_file, + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + return 0; + } + + if(!params.cert) { + failf(data, "ssl engine didn't initialized the certificate " + "properly."); + return 0; + } + + if(SSL_CTX_use_certificate(ctx, params.cert) != 1) { + failf(data, "unable to set client certificate [%s]", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + return 0; + } + X509_free(params.cert); /* we don't need the handle any more... */ + } + else { + failf(data, "crypto engine not set, can't load certificate"); + return 0; + } + } + break; +#else + failf(data, "file type ENG for certificate not implemented"); + return 0; +#endif + + case SSL_FILETYPE_PKCS12: + { + BIO *cert_bio = NULL; + PKCS12 *p12 = NULL; + EVP_PKEY *pri; + STACK_OF(X509) *ca = NULL; + if(cert_blob) { + cert_bio = BIO_new_mem_buf(cert_blob->data, (int)(cert_blob->len)); + if(!cert_bio) { + failf(data, + "BIO_new_mem_buf NULL, " OSSL_PACKAGE + " error %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer)) ); + return 0; + } + } + else { + cert_bio = BIO_new(BIO_s_file()); + if(!cert_bio) { + failf(data, + "BIO_new return NULL, " OSSL_PACKAGE + " error %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer)) ); + return 0; + } + + if(BIO_read_filename(cert_bio, cert_file) <= 0) { + failf(data, "could not open PKCS12 file '%s'", cert_file); + BIO_free(cert_bio); + return 0; + } + } + + p12 = d2i_PKCS12_bio(cert_bio, NULL); + BIO_free(cert_bio); + + if(!p12) { + failf(data, "error reading PKCS12 file '%s'", + cert_blob ? "(memory blob)" : cert_file); + return 0; + } + + PKCS12_PBE_add(); + + if(!PKCS12_parse(p12, key_passwd, &pri, &x509, + &ca)) { + failf(data, + "could not parse PKCS12 file, check password, " OSSL_PACKAGE + " error %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer)) ); + PKCS12_free(p12); + return 0; + } + + PKCS12_free(p12); + + if(SSL_CTX_use_certificate(ctx, x509) != 1) { + failf(data, + "could not load PKCS12 client certificate, " OSSL_PACKAGE + " error %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer)) ); + goto fail; + } + + if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) { + failf(data, "unable to use private key from PKCS12 file '%s'", + cert_file); + goto fail; + } + + if(!SSL_CTX_check_private_key (ctx)) { + failf(data, "private key from PKCS12 file '%s' " + "does not match certificate in same file", cert_file); + goto fail; + } + /* Set Certificate Verification chain */ + if(ca) { + while(sk_X509_num(ca)) { + /* + * Note that sk_X509_pop() is used below to make sure the cert is + * removed from the stack properly before getting passed to + * SSL_CTX_add_extra_chain_cert(), which takes ownership. Previously + * we used sk_X509_value() instead, but then we'd clean it in the + * subsequent sk_X509_pop_free() call. + */ + X509 *x = sk_X509_pop(ca); + if(!SSL_CTX_add_client_CA(ctx, x)) { + X509_free(x); + failf(data, "cannot add certificate to client CA list"); + goto fail; + } + if(!SSL_CTX_add_extra_chain_cert(ctx, x)) { + X509_free(x); + failf(data, "cannot add certificate to certificate chain"); + goto fail; + } + } + } + + cert_done = 1; +fail: + EVP_PKEY_free(pri); + X509_free(x509); + sk_X509_pop_free(ca, X509_free); + if(!cert_done) + return 0; /* failure! */ + break; + } + default: + failf(data, "not supported file type '%s' for certificate", cert_type); + return 0; + } + + if((!key_file) && (!key_blob)) { + key_file = cert_file; + key_blob = cert_blob; + } + else + file_type = do_file_type(key_type); + + switch(file_type) { + case SSL_FILETYPE_PEM: + if(cert_done) + break; + FALLTHROUGH(); + case SSL_FILETYPE_ASN1: + cert_use_result = key_blob ? + SSL_CTX_use_PrivateKey_blob(ctx, key_blob, file_type, key_passwd) : + SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type); + if(cert_use_result != 1) { + failf(data, "unable to set private key file: '%s' type %s", + key_file?key_file:"(memory blob)", key_type?key_type:"PEM"); + return 0; + } + break; + case SSL_FILETYPE_ENGINE: +#ifdef USE_OPENSSL_ENGINE + { + EVP_PKEY *priv_key = NULL; + + /* Implicitly use pkcs11 engine if none was provided and the + * key_file is a PKCS#11 URI */ + if(!data->state.engine) { + if(is_pkcs11_uri(key_file)) { + if(ossl_set_engine(data, "pkcs11") != CURLE_OK) { + return 0; + } + } + } + + if(data->state.engine) { + UI_METHOD *ui_method = + UI_create_method((char *)"curl user interface"); + if(!ui_method) { + failf(data, "unable do create " OSSL_PACKAGE + " user-interface method"); + return 0; + } + UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL())); + UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL())); + UI_method_set_reader(ui_method, ssl_ui_reader); + UI_method_set_writer(ui_method, ssl_ui_writer); + priv_key = ENGINE_load_private_key(data->state.engine, key_file, + ui_method, + key_passwd); + UI_destroy_method(ui_method); + if(!priv_key) { + failf(data, "failed to load private key from crypto engine"); + return 0; + } + if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) { + failf(data, "unable to set private key"); + EVP_PKEY_free(priv_key); + return 0; + } + EVP_PKEY_free(priv_key); /* we don't need the handle any more... */ + } + else { + failf(data, "crypto engine not set, can't load private key"); + return 0; + } + } + break; +#else + failf(data, "file type ENG for private key not supported"); + return 0; +#endif + case SSL_FILETYPE_PKCS12: + if(!cert_done) { + failf(data, "file type P12 for private key not supported"); + return 0; + } + break; + default: + failf(data, "not supported file type for private key"); + return 0; + } + + ssl = SSL_new(ctx); + if(!ssl) { + failf(data, "unable to create an SSL structure"); + return 0; + } + + x509 = SSL_get_certificate(ssl); + + /* This version was provided by Evan Jordan and is supposed to not + leak memory as the previous version: */ + if(x509) { + EVP_PKEY *pktmp = X509_get_pubkey(x509); + EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl)); + EVP_PKEY_free(pktmp); + } + +#if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_IS_BORINGSSL) && \ + !defined(OPENSSL_NO_DEPRECATED_3_0) + { + /* If RSA is used, don't check the private key if its flags indicate + * it doesn't support it. */ + EVP_PKEY *priv_key = SSL_get_privatekey(ssl); + int pktype; +#ifdef HAVE_OPAQUE_EVP_PKEY + pktype = EVP_PKEY_id(priv_key); +#else + pktype = priv_key->type; +#endif + if(pktype == EVP_PKEY_RSA) { + RSA *rsa = EVP_PKEY_get1_RSA(priv_key); + if(RSA_flags(rsa) & RSA_METHOD_FLAG_NO_CHECK) + check_privkey = FALSE; + RSA_free(rsa); /* Decrement reference count */ + } + } +#endif + + SSL_free(ssl); + + /* If we are using DSA, we can copy the parameters from + * the private key */ + + if(check_privkey == TRUE) { + /* Now we know that a key and cert have been set against + * the SSL context */ + if(!SSL_CTX_check_private_key(ctx)) { + failf(data, "Private key does not match the certificate public key"); + return 0; + } + } + } + return 1; +} + +CURLcode Curl_ossl_set_client_cert(struct Curl_easy *data, SSL_CTX *ctx, + char *cert_file, + const struct curl_blob *cert_blob, + const char *cert_type, char *key_file, + const struct curl_blob *key_blob, + const char *key_type, char *key_passwd) +{ + int rv = cert_stuff(data, ctx, cert_file, cert_blob, cert_type, key_file, + key_blob, key_type, key_passwd); + if(rv != 1) { + return CURLE_SSL_CERTPROBLEM; + } + + return CURLE_OK; +} + +/* returns non-zero on failure */ +static int x509_name_oneline(X509_NAME *a, char *buf, size_t size) +{ + BIO *bio_out = BIO_new(BIO_s_mem()); + BUF_MEM *biomem; + int rc; + + if(!bio_out) + return 1; /* alloc failed! */ + + rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC); + BIO_get_mem_ptr(bio_out, &biomem); + + if((size_t)biomem->length < size) + size = biomem->length; + else + size--; /* don't overwrite the buffer end */ + + memcpy(buf, biomem->data, size); + buf[size] = 0; + + BIO_free(bio_out); + + return !rc; +} + +/** + * Global SSL init + * + * @retval 0 error initializing SSL + * @retval 1 SSL initialized successfully + */ +static int ossl_init(void) +{ +#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \ + (!defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER >= 0x2070000fL) + const uint64_t flags = +#ifdef OPENSSL_INIT_ENGINE_ALL_BUILTIN + /* not present in BoringSSL */ + OPENSSL_INIT_ENGINE_ALL_BUILTIN | +#endif +#ifdef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG + OPENSSL_INIT_NO_LOAD_CONFIG | +#else + OPENSSL_INIT_LOAD_CONFIG | +#endif + 0; + OPENSSL_init_ssl(flags, NULL); +#else + OPENSSL_load_builtin_modules(); + +#ifdef USE_OPENSSL_ENGINE + ENGINE_load_builtin_engines(); +#endif + +/* CONF_MFLAGS_DEFAULT_SECTION was introduced some time between 0.9.8b and + 0.9.8e */ +#ifndef CONF_MFLAGS_DEFAULT_SECTION +#define CONF_MFLAGS_DEFAULT_SECTION 0x0 +#endif + +#ifndef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG + CONF_modules_load_file(NULL, NULL, + CONF_MFLAGS_DEFAULT_SECTION| + CONF_MFLAGS_IGNORE_MISSING_FILE); +#endif + + /* Let's get nice error messages */ + SSL_load_error_strings(); + + /* Init the global ciphers and digests */ + if(!SSLeay_add_ssl_algorithms()) + return 0; + + OpenSSL_add_all_algorithms(); +#endif + + Curl_tls_keylog_open(); + + return 1; +} + +/* Global cleanup */ +static void ossl_cleanup(void) +{ +#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \ + (!defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER >= 0x2070000fL) + /* OpenSSL 1.1 deprecates all these cleanup functions and + turns them into no-ops in OpenSSL 1.0 compatibility mode */ +#else + /* Free ciphers and digests lists */ + EVP_cleanup(); + +#ifdef USE_OPENSSL_ENGINE + /* Free engine list */ + ENGINE_cleanup(); +#endif + + /* Free OpenSSL error strings */ + ERR_free_strings(); + + /* Free thread local error state, destroying hash upon zero refcount */ +#ifdef HAVE_ERR_REMOVE_THREAD_STATE + ERR_remove_thread_state(NULL); +#else + ERR_remove_state(0); +#endif + + /* Free all memory allocated by all configuration modules */ + CONF_modules_free(); + +#ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS + SSL_COMP_free_compression_methods(); +#endif +#endif + + Curl_tls_keylog_close(); +} + +/* Selects an OpenSSL crypto engine + */ +static CURLcode ossl_set_engine(struct Curl_easy *data, const char *engine) +{ +#ifdef USE_OPENSSL_ENGINE + ENGINE *e; + +#if OPENSSL_VERSION_NUMBER >= 0x00909000L + e = ENGINE_by_id(engine); +#else + /* avoid memory leak */ + for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) { + const char *e_id = ENGINE_get_id(e); + if(!strcmp(engine, e_id)) + break; + } +#endif + + if(!e) { + failf(data, "SSL Engine '%s' not found", engine); + return CURLE_SSL_ENGINE_NOTFOUND; + } + + if(data->state.engine) { + ENGINE_finish(data->state.engine); + ENGINE_free(data->state.engine); + data->state.engine = NULL; + } + if(!ENGINE_init(e)) { + char buf[256]; + + ENGINE_free(e); + failf(data, "Failed to initialise SSL Engine '%s': %s", + engine, ossl_strerror(ERR_get_error(), buf, sizeof(buf))); + return CURLE_SSL_ENGINE_INITFAILED; + } + data->state.engine = e; + return CURLE_OK; +#else + (void)engine; + failf(data, "SSL Engine not supported"); + return CURLE_SSL_ENGINE_NOTFOUND; +#endif +} + +/* Sets engine as default for all SSL operations + */ +static CURLcode ossl_set_engine_default(struct Curl_easy *data) +{ +#ifdef USE_OPENSSL_ENGINE + if(data->state.engine) { + if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) { + infof(data, "set default crypto engine '%s'", + ENGINE_get_id(data->state.engine)); + } + else { + failf(data, "set default crypto engine '%s' failed", + ENGINE_get_id(data->state.engine)); + return CURLE_SSL_ENGINE_SETFAILED; + } + } +#else + (void) data; +#endif + return CURLE_OK; +} + +/* Return list of OpenSSL crypto engine names. + */ +static struct curl_slist *ossl_engines_list(struct Curl_easy *data) +{ + struct curl_slist *list = NULL; +#ifdef USE_OPENSSL_ENGINE + struct curl_slist *beg; + ENGINE *e; + + for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) { + beg = curl_slist_append(list, ENGINE_get_id(e)); + if(!beg) { + curl_slist_free_all(list); + return NULL; + } + list = beg; + } +#endif + (void) data; + return list; +} + +static void ossl_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + + (void)data; + DEBUGASSERT(octx); + + if(octx->ssl) { + /* Send the TLS shutdown if we are still connected *and* if + * the peer did not already close the connection. */ + if(cf->next && cf->next->connected && !connssl->peer_closed) { + char buf[1024]; + int nread, err; + long sslerr; + + /* Maybe the server has already sent a close notify alert. + Read it to avoid an RST on the TCP connection. */ + ERR_clear_error(); + nread = SSL_read(octx->ssl, buf, (int)sizeof(buf)); + err = SSL_get_error(octx->ssl, nread); + if(!nread && err == SSL_ERROR_ZERO_RETURN) { + CURLcode result; + ssize_t n; + size_t blen = sizeof(buf); + CURL_TRC_CF(data, cf, "peer has shutdown TLS"); + /* SSL_read() will not longer touch the socket, let's receive + * directly from the next filter to see if the underlying + * connection has also been closed. */ + n = Curl_conn_cf_recv(cf->next, data, buf, blen, &result); + if(!n) { + connssl->peer_closed = TRUE; + CURL_TRC_CF(data, cf, "peer closed connection"); + } + } + ERR_clear_error(); + if(connssl->peer_closed) { + /* As the peer closed, we do not expect it to read anything more we + * may send. It may be harmful, leading to TCP RST and delaying + * a lingering close. Just leave. */ + CURL_TRC_CF(data, cf, "not from sending TLS shutdown on " + "connection closed by peer"); + } + else if(SSL_shutdown(octx->ssl) == 1) { + CURL_TRC_CF(data, cf, "SSL shutdown finished"); + } + else { + nread = SSL_read(octx->ssl, buf, (int)sizeof(buf)); + err = SSL_get_error(octx->ssl, nread); + switch(err) { + case SSL_ERROR_NONE: /* this is not an error */ + case SSL_ERROR_ZERO_RETURN: /* no more data */ + CURL_TRC_CF(data, cf, "SSL shutdown, EOF from server"); + break; + case SSL_ERROR_WANT_READ: + /* SSL has send its notify and now wants to read the reply + * from the server. We are not really interested in that. */ + CURL_TRC_CF(data, cf, "SSL shutdown sent"); + break; + case SSL_ERROR_WANT_WRITE: + CURL_TRC_CF(data, cf, "SSL shutdown send blocked"); + break; + default: + sslerr = ERR_get_error(); + CURL_TRC_CF(data, cf, "SSL shutdown, error: '%s', errno %d", + (sslerr ? + ossl_strerror(sslerr, buf, sizeof(buf)) : + SSL_ERROR_to_str(err)), + SOCKERRNO); + break; + } + } + + ERR_clear_error(); + SSL_set_connect_state(octx->ssl); + } + + SSL_free(octx->ssl); + octx->ssl = NULL; + } + if(octx->ssl_ctx) { + SSL_CTX_free(octx->ssl_ctx); + octx->ssl_ctx = NULL; + octx->x509_store_setup = FALSE; + } + if(octx->bio_method) { + ossl_bio_cf_method_free(octx->bio_method); + octx->bio_method = NULL; + } +} + +/* + * This function is called to shut down the SSL layer but keep the + * socket open (CCC - Clear Command Channel) + */ +static int ossl_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + int retval = 0; + struct ssl_connect_data *connssl = cf->ctx; + char buf[256]; /* We will use this for the OpenSSL error buffer, so it has + to be at least 256 bytes long. */ + unsigned long sslerror; + int nread; + int buffsize; + int err; + bool done = FALSE; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + int loop = 10; + + DEBUGASSERT(octx); + +#ifndef CURL_DISABLE_FTP + /* This has only been tested on the proftpd server, and the mod_tls code + sends a close notify alert without waiting for a close notify alert in + response. Thus we wait for a close notify alert from the server, but + we do not send one. Let's hope other servers do the same... */ + + if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE) + (void)SSL_shutdown(octx->ssl); +#endif + + if(octx->ssl) { + buffsize = (int)sizeof(buf); + while(!done && loop--) { + int what = SOCKET_READABLE(Curl_conn_cf_get_socket(cf, data), + SSL_SHUTDOWN_TIMEOUT); + if(what > 0) { + ERR_clear_error(); + + /* Something to read, let's do it and hope that it is the close + notify alert from the server */ + nread = SSL_read(octx->ssl, buf, buffsize); + err = SSL_get_error(octx->ssl, nread); + + switch(err) { + case SSL_ERROR_NONE: /* this is not an error */ + case SSL_ERROR_ZERO_RETURN: /* no more data */ + /* This is the expected response. There was no data but only + the close notify alert */ + done = TRUE; + break; + case SSL_ERROR_WANT_READ: + /* there's data pending, re-invoke SSL_read() */ + infof(data, "SSL_ERROR_WANT_READ"); + break; + case SSL_ERROR_WANT_WRITE: + /* SSL wants a write. Really odd. Let's bail out. */ + infof(data, "SSL_ERROR_WANT_WRITE"); + done = TRUE; + break; + default: + /* openssl/ssl.h says "look at error stack/return value/errno" */ + sslerror = ERR_get_error(); + failf(data, OSSL_PACKAGE " SSL_read on shutdown: %s, errno %d", + (sslerror ? + ossl_strerror(sslerror, buf, sizeof(buf)) : + SSL_ERROR_to_str(err)), + SOCKERRNO); + done = TRUE; + break; + } + } + else if(0 == what) { + /* timeout */ + failf(data, "SSL shutdown timeout"); + done = TRUE; + } + else { + /* anything that gets here is fatally bad */ + failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); + retval = -1; + done = TRUE; + } + } /* while()-loop for the select() */ + + if(data->set.verbose) { +#ifdef HAVE_SSL_GET_SHUTDOWN + switch(SSL_get_shutdown(octx->ssl)) { + case SSL_SENT_SHUTDOWN: + infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN"); + break; + case SSL_RECEIVED_SHUTDOWN: + infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN"); + break; + case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN: + infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|" + "SSL_RECEIVED__SHUTDOWN"); + break; + } +#endif + } + + SSL_free(octx->ssl); + octx->ssl = NULL; + } + return retval; +} + +static void ossl_session_free(void *sessionid, size_t idsize) +{ + /* free the ID */ + (void)idsize; + SSL_SESSION_free(sessionid); +} + +/* + * This function is called when the 'data' struct is going away. Close + * down everything and free all resources! + */ +static void ossl_close_all(struct Curl_easy *data) +{ +#ifdef USE_OPENSSL_ENGINE + if(data->state.engine) { + ENGINE_finish(data->state.engine); + ENGINE_free(data->state.engine); + data->state.engine = NULL; + } +#else + (void)data; +#endif +#if !defined(HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED) && \ + defined(HAVE_ERR_REMOVE_THREAD_STATE) + /* OpenSSL 1.0.1 and 1.0.2 build an error queue that is stored per-thread + so we need to clean it here in case the thread will be killed. All OpenSSL + code should extract the error in association with the error so clearing + this queue here should be harmless at worst. */ + ERR_remove_thread_state(NULL); +#endif +} + +/* ====================================================== */ + +/* + * Match subjectAltName against the host name. + */ +static bool subj_alt_hostcheck(struct Curl_easy *data, + const char *match_pattern, + size_t matchlen, + const char *hostname, + size_t hostlen, + const char *dispname) +{ +#ifdef CURL_DISABLE_VERBOSE_STRINGS + (void)dispname; + (void)data; +#endif + if(Curl_cert_hostcheck(match_pattern, matchlen, hostname, hostlen)) { + infof(data, " subjectAltName: host \"%s\" matched cert's \"%s\"", + dispname, match_pattern); + return TRUE; + } + return FALSE; +} + +/* 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. + + This function is now used from ngtcp2 (QUIC) as well. +*/ +CURLcode Curl_ossl_verifyhost(struct Curl_easy *data, struct connectdata *conn, + struct ssl_peer *peer, X509 *server_cert) +{ + bool matched = FALSE; + int target; /* target type, GEN_DNS or GEN_IPADD */ + size_t addrlen = 0; + STACK_OF(GENERAL_NAME) *altnames; +#ifdef USE_IPV6 + struct in6_addr addr; +#else + struct in_addr addr; +#endif + CURLcode result = CURLE_OK; + bool dNSName = FALSE; /* if a dNSName field exists in the cert */ + bool iPAddress = FALSE; /* if an iPAddress field exists in the cert */ + size_t hostlen; + + (void)conn; + hostlen = strlen(peer->hostname); + switch(peer->type) { + case CURL_SSL_PEER_IPV4: + if(!Curl_inet_pton(AF_INET, peer->hostname, &addr)) + return CURLE_PEER_FAILED_VERIFICATION; + target = GEN_IPADD; + addrlen = sizeof(struct in_addr); + break; +#ifdef USE_IPV6 + case CURL_SSL_PEER_IPV6: + if(!Curl_inet_pton(AF_INET6, peer->hostname, &addr)) + return CURLE_PEER_FAILED_VERIFICATION; + target = GEN_IPADD; + addrlen = sizeof(struct in6_addr); + break; +#endif + case CURL_SSL_PEER_DNS: + target = GEN_DNS; + break; + default: + DEBUGASSERT(0); + failf(data, "unexpected ssl peer type: %d", peer->type); + return CURLE_PEER_FAILED_VERIFICATION; + } + + /* get a "list" of alternative names */ + altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL); + + if(altnames) { +#if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) + size_t numalts; + size_t i; +#else + int numalts; + int i; +#endif + bool dnsmatched = FALSE; + bool ipmatched = FALSE; + + /* get amount of alternatives, RFC2459 claims there MUST be at least + one, but we don't depend on it... */ + numalts = sk_GENERAL_NAME_num(altnames); + + /* loop through all alternatives - until a dnsmatch */ + for(i = 0; (i < numalts) && !dnsmatched; i++) { + /* get a handle to alternative name number i */ + const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i); + + if(check->type == GEN_DNS) + dNSName = TRUE; + else if(check->type == GEN_IPADD) + iPAddress = TRUE; + + /* only check alternatives of the same type the target is */ + if(check->type == target) { + /* get data and length */ + const char *altptr = (char *)ASN1_STRING_get0_data(check->d.ia5); + size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5); + + switch(target) { + case GEN_DNS: /* name/pattern comparison */ + /* The OpenSSL man page explicitly says: "In general it cannot be + assumed that the data returned by ASN1_STRING_data() is null + terminated or does not contain embedded nulls." But also that + "The actual format of the data will depend on the actual string + type itself: for example for an IA5String the data will be ASCII" + + It has been however verified that in 0.9.6 and 0.9.7, IA5String + is always null-terminated. + */ + if((altlen == strlen(altptr)) && + /* if this isn't true, there was an embedded zero in the name + string and we cannot match it. */ + subj_alt_hostcheck(data, altptr, altlen, + peer->hostname, hostlen, + peer->dispname)) { + dnsmatched = TRUE; + } + break; + + case GEN_IPADD: /* IP address comparison */ + /* compare alternative IP address if the data chunk is the same size + our server IP address is */ + if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) { + ipmatched = TRUE; + infof(data, + " subjectAltName: host \"%s\" matched cert's IP address!", + peer->dispname); + } + break; + } + } + } + GENERAL_NAMES_free(altnames); + + if(dnsmatched || ipmatched) + matched = TRUE; + } + + if(matched) + /* an alternative name matched */ + ; + else if(dNSName || iPAddress) { + const char *tname = (peer->type == CURL_SSL_PEER_DNS) ? "host name" : + (peer->type == CURL_SSL_PEER_IPV4) ? + "ipv4 address" : "ipv6 address"; + infof(data, " subjectAltName does not match %s %s", tname, peer->dispname); + failf(data, "SSL: no alternative certificate subject name matches " + "target %s '%s'", tname, peer->dispname); + result = CURLE_PEER_FAILED_VERIFICATION; + } + else { + /* we have to look to the last occurrence of a commonName in the + distinguished one to get the most significant one. */ + int i = -1; + unsigned char *peer_CN = NULL; + int peerlen = 0; + + /* The following is done because of a bug in 0.9.6b */ + X509_NAME *name = X509_get_subject_name(server_cert); + if(name) { + int j; + while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0) + i = j; + } + + /* we have the name entry and we will now convert this to a string + that we can use for comparison. Doing this we support BMPstring, + UTF8, etc. */ + + if(i >= 0) { + ASN1_STRING *tmp = + X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i)); + + /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input + is already UTF-8 encoded. We check for this case and copy the raw + string manually to avoid the problem. This code can be made + conditional in the future when OpenSSL has been fixed. */ + if(tmp) { + if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) { + peerlen = ASN1_STRING_length(tmp); + if(peerlen >= 0) { + peer_CN = OPENSSL_malloc(peerlen + 1); + if(peer_CN) { + memcpy(peer_CN, ASN1_STRING_get0_data(tmp), peerlen); + peer_CN[peerlen] = '\0'; + } + else + result = CURLE_OUT_OF_MEMORY; + } + } + else /* not a UTF8 name */ + peerlen = ASN1_STRING_to_UTF8(&peer_CN, tmp); + + if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != peerlen)) { + /* there was a terminating zero before the end of string, this + cannot match and we return failure! */ + failf(data, "SSL: illegal cert name field"); + result = CURLE_PEER_FAILED_VERIFICATION; + } + } + } + + if(result) + /* error already detected, pass through */ + ; + else if(!peer_CN) { + failf(data, + "SSL: unable to obtain common name from peer certificate"); + result = CURLE_PEER_FAILED_VERIFICATION; + } + else if(!Curl_cert_hostcheck((const char *)peer_CN, + peerlen, peer->hostname, hostlen)) { + failf(data, "SSL: certificate subject name '%s' does not match " + "target host name '%s'", peer_CN, peer->dispname); + result = CURLE_PEER_FAILED_VERIFICATION; + } + else { + infof(data, " common name: %s (matched)", peer_CN); + } + if(peer_CN) + OPENSSL_free(peer_CN); + } + + return result; +} + +#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \ + !defined(OPENSSL_NO_OCSP) +static CURLcode verifystatus(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + int i, ocsp_status; +#if defined(OPENSSL_IS_AWSLC) + const uint8_t *status; +#else + unsigned char *status; +#endif + const unsigned char *p; + CURLcode result = CURLE_OK; + OCSP_RESPONSE *rsp = NULL; + OCSP_BASICRESP *br = NULL; + X509_STORE *st = NULL; + STACK_OF(X509) *ch = NULL; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + X509 *cert; + OCSP_CERTID *id = NULL; + int cert_status, crl_reason; + ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd; + int ret; + long len; + + DEBUGASSERT(octx); + + len = SSL_get_tlsext_status_ocsp_resp(octx->ssl, &status); + + if(!status) { + failf(data, "No OCSP response received"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + p = status; + rsp = d2i_OCSP_RESPONSE(NULL, &p, len); + if(!rsp) { + failf(data, "Invalid OCSP response"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + + ocsp_status = OCSP_response_status(rsp); + if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) { + failf(data, "Invalid OCSP response status: %s (%d)", + OCSP_response_status_str(ocsp_status), ocsp_status); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + + br = OCSP_response_get1_basic(rsp); + if(!br) { + failf(data, "Invalid OCSP response"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + + ch = SSL_get_peer_cert_chain(octx->ssl); + if(!ch) { + failf(data, "Could not get peer certificate chain"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + st = SSL_CTX_get_cert_store(octx->ssl_ctx); + +#if ((OPENSSL_VERSION_NUMBER <= 0x1000201fL) /* Fixed after 1.0.2a */ || \ + (defined(LIBRESSL_VERSION_NUMBER) && \ + LIBRESSL_VERSION_NUMBER <= 0x2040200fL)) + /* The authorized responder cert in the OCSP response MUST be signed by the + peer cert's issuer (see RFC6960 section 4.2.2.2). If that's a root cert, + no problem, but if it's an intermediate cert OpenSSL has a bug where it + expects this issuer to be present in the chain embedded in the OCSP + response. So we add it if necessary. */ + + /* First make sure the peer cert chain includes both a peer and an issuer, + and the OCSP response contains a responder cert. */ + if(sk_X509_num(ch) >= 2 && sk_X509_num(br->certs) >= 1) { + X509 *responder = sk_X509_value(br->certs, sk_X509_num(br->certs) - 1); + + /* Find issuer of responder cert and add it to the OCSP response chain */ + for(i = 0; i < sk_X509_num(ch); i++) { + X509 *issuer = sk_X509_value(ch, i); + if(X509_check_issued(issuer, responder) == X509_V_OK) { + if(!OCSP_basic_add1_cert(br, issuer)) { + failf(data, "Could not add issuer cert to OCSP response"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + } + } + } +#endif + + if(OCSP_basic_verify(br, ch, st, 0) <= 0) { + failf(data, "OCSP response verification failed"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + + /* Compute the certificate's ID */ + cert = SSL_get1_peer_certificate(octx->ssl); + if(!cert) { + failf(data, "Error getting peer certificate"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + + for(i = 0; i < (int)sk_X509_num(ch); i++) { + X509 *issuer = sk_X509_value(ch, i); + if(X509_check_issued(issuer, cert) == X509_V_OK) { + id = OCSP_cert_to_id(EVP_sha1(), cert, issuer); + break; + } + } + X509_free(cert); + + if(!id) { + failf(data, "Error computing OCSP ID"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + + /* Find the single OCSP response corresponding to the certificate ID */ + ret = OCSP_resp_find_status(br, id, &cert_status, &crl_reason, &rev, + &thisupd, &nextupd); + OCSP_CERTID_free(id); + if(ret != 1) { + failf(data, "Could not find certificate ID in OCSP response"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + + /* Validate the corresponding single OCSP response */ + if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) { + failf(data, "OCSP response has expired"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + + infof(data, "SSL certificate status: %s (%d)", + OCSP_cert_status_str(cert_status), cert_status); + + switch(cert_status) { + case V_OCSP_CERTSTATUS_GOOD: + break; + + case V_OCSP_CERTSTATUS_REVOKED: + result = CURLE_SSL_INVALIDCERTSTATUS; + failf(data, "SSL certificate revocation reason: %s (%d)", + OCSP_crl_reason_str(crl_reason), crl_reason); + goto end; + + case V_OCSP_CERTSTATUS_UNKNOWN: + default: + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + +end: + if(br) + OCSP_BASICRESP_free(br); + OCSP_RESPONSE_free(rsp); + + return result; +} +#endif + +#endif /* USE_OPENSSL */ + +/* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions + and thus this cannot be done there. */ +#ifdef SSL_CTRL_SET_MSG_CALLBACK + +static const char *ssl_msg_type(int ssl_ver, int msg) +{ +#ifdef SSL2_VERSION_MAJOR + if(ssl_ver == SSL2_VERSION_MAJOR) { + switch(msg) { + case SSL2_MT_ERROR: + return "Error"; + case SSL2_MT_CLIENT_HELLO: + return "Client hello"; + case SSL2_MT_CLIENT_MASTER_KEY: + return "Client key"; + case SSL2_MT_CLIENT_FINISHED: + return "Client finished"; + case SSL2_MT_SERVER_HELLO: + return "Server hello"; + case SSL2_MT_SERVER_VERIFY: + return "Server verify"; + case SSL2_MT_SERVER_FINISHED: + return "Server finished"; + case SSL2_MT_REQUEST_CERTIFICATE: + return "Request CERT"; + case SSL2_MT_CLIENT_CERTIFICATE: + return "Client CERT"; + } + } + else +#endif + if(ssl_ver == SSL3_VERSION_MAJOR) { + switch(msg) { + case SSL3_MT_HELLO_REQUEST: + return "Hello request"; + case SSL3_MT_CLIENT_HELLO: + return "Client hello"; + case SSL3_MT_SERVER_HELLO: + return "Server hello"; +#ifdef SSL3_MT_NEWSESSION_TICKET + case SSL3_MT_NEWSESSION_TICKET: + return "Newsession Ticket"; +#endif + case SSL3_MT_CERTIFICATE: + return "Certificate"; + case SSL3_MT_SERVER_KEY_EXCHANGE: + return "Server key exchange"; + case SSL3_MT_CLIENT_KEY_EXCHANGE: + return "Client key exchange"; + case SSL3_MT_CERTIFICATE_REQUEST: + return "Request CERT"; + case SSL3_MT_SERVER_DONE: + return "Server finished"; + case SSL3_MT_CERTIFICATE_VERIFY: + return "CERT verify"; + case SSL3_MT_FINISHED: + return "Finished"; +#ifdef SSL3_MT_CERTIFICATE_STATUS + case SSL3_MT_CERTIFICATE_STATUS: + return "Certificate Status"; +#endif +#ifdef SSL3_MT_ENCRYPTED_EXTENSIONS + case SSL3_MT_ENCRYPTED_EXTENSIONS: + return "Encrypted Extensions"; +#endif +#ifdef SSL3_MT_SUPPLEMENTAL_DATA + case SSL3_MT_SUPPLEMENTAL_DATA: + return "Supplemental data"; +#endif +#ifdef SSL3_MT_END_OF_EARLY_DATA + case SSL3_MT_END_OF_EARLY_DATA: + return "End of early data"; +#endif +#ifdef SSL3_MT_KEY_UPDATE + case SSL3_MT_KEY_UPDATE: + return "Key update"; +#endif +#ifdef SSL3_MT_NEXT_PROTO + case SSL3_MT_NEXT_PROTO: + return "Next protocol"; +#endif +#ifdef SSL3_MT_MESSAGE_HASH + case SSL3_MT_MESSAGE_HASH: + return "Message hash"; +#endif + } + } + return "Unknown"; +} + +static const char *tls_rt_type(int type) +{ + switch(type) { +#ifdef SSL3_RT_HEADER + case SSL3_RT_HEADER: + return "TLS header"; +#endif + case SSL3_RT_CHANGE_CIPHER_SPEC: + return "TLS change cipher"; + case SSL3_RT_ALERT: + return "TLS alert"; + case SSL3_RT_HANDSHAKE: + return "TLS handshake"; + case SSL3_RT_APPLICATION_DATA: + return "TLS app data"; + default: + return "TLS Unknown"; + } +} + +/* + * Our callback from the SSL/TLS layers. + */ +static void ossl_trace(int direction, int ssl_ver, int content_type, + const void *buf, size_t len, SSL *ssl, + void *userp) +{ + const char *verstr = "???"; + struct Curl_cfilter *cf = userp; + struct Curl_easy *data = NULL; + char unknown[32]; + + if(!cf) + return; + data = CF_DATA_CURRENT(cf); + if(!data || !data->set.fdebug || (direction && direction != 1)) + return; + + switch(ssl_ver) { +#ifdef SSL2_VERSION /* removed in recent versions */ + case SSL2_VERSION: + verstr = "SSLv2"; + break; +#endif +#ifdef SSL3_VERSION + case SSL3_VERSION: + verstr = "SSLv3"; + break; +#endif + case TLS1_VERSION: + verstr = "TLSv1.0"; + break; +#ifdef TLS1_1_VERSION + case TLS1_1_VERSION: + verstr = "TLSv1.1"; + break; +#endif +#ifdef TLS1_2_VERSION + case TLS1_2_VERSION: + verstr = "TLSv1.2"; + break; +#endif +#ifdef TLS1_3_VERSION + case TLS1_3_VERSION: + verstr = "TLSv1.3"; + break; +#endif + case 0: + break; + default: + msnprintf(unknown, sizeof(unknown), "(%x)", ssl_ver); + verstr = unknown; + break; + } + + /* Log progress for interesting records only (like Handshake or Alert), skip + * all raw record headers (content_type == SSL3_RT_HEADER or ssl_ver == 0). + * For TLS 1.3, skip notification of the decrypted inner Content-Type. + */ + if(ssl_ver +#ifdef SSL3_RT_HEADER + && content_type != SSL3_RT_HEADER +#endif +#ifdef SSL3_RT_INNER_CONTENT_TYPE + && content_type != SSL3_RT_INNER_CONTENT_TYPE +#endif + ) { + const char *msg_name, *tls_rt_name; + char ssl_buf[1024]; + int msg_type, txt_len; + + /* the info given when the version is zero is not that useful for us */ + + ssl_ver >>= 8; /* check the upper 8 bits only below */ + + /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL + * always pass-up content-type as 0. But the interesting message-type + * is at 'buf[0]'. + */ + if(ssl_ver == SSL3_VERSION_MAJOR && content_type) + tls_rt_name = tls_rt_type(content_type); + else + tls_rt_name = ""; + + if(content_type == SSL3_RT_CHANGE_CIPHER_SPEC) { + msg_type = *(char *)buf; + msg_name = "Change cipher spec"; + } + else if(content_type == SSL3_RT_ALERT) { + msg_type = (((char *)buf)[0] << 8) + ((char *)buf)[1]; + msg_name = SSL_alert_desc_string_long(msg_type); + } + else { + msg_type = *(char *)buf; + msg_name = ssl_msg_type(ssl_ver, msg_type); + } + + txt_len = msnprintf(ssl_buf, sizeof(ssl_buf), + "%s (%s), %s, %s (%d):\n", + verstr, direction?"OUT":"IN", + tls_rt_name, msg_name, msg_type); + if(0 <= txt_len && (unsigned)txt_len < sizeof(ssl_buf)) { + Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len); + } + } + + Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT : + CURLINFO_SSL_DATA_IN, (char *)buf, len); + (void) ssl; +} +#endif + +#ifdef USE_OPENSSL +/* ====================================================== */ + +/* Check for OpenSSL 1.0.2 which has ALPN support. */ +#undef HAS_ALPN +#if OPENSSL_VERSION_NUMBER >= 0x10002000L \ + && !defined(OPENSSL_NO_TLSEXT) +# define HAS_ALPN 1 +#endif + +#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* 1.1.0 */ +static CURLcode +ossl_set_ssl_version_min_max(struct Curl_cfilter *cf, SSL_CTX *ctx) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + /* first, TLS min version... */ + long curl_ssl_version_min = conn_config->version; + long curl_ssl_version_max; + + /* convert curl min SSL version option to OpenSSL constant */ +#if (defined(OPENSSL_IS_BORINGSSL) || \ + defined(OPENSSL_IS_AWSLC) || \ + defined(LIBRESSL_VERSION_NUMBER)) + uint16_t ossl_ssl_version_min = 0; + uint16_t ossl_ssl_version_max = 0; +#else + long ossl_ssl_version_min = 0; + long ossl_ssl_version_max = 0; +#endif + switch(curl_ssl_version_min) { + case CURL_SSLVERSION_TLSv1: /* TLS 1.x */ + case CURL_SSLVERSION_TLSv1_0: + ossl_ssl_version_min = TLS1_VERSION; + break; + case CURL_SSLVERSION_TLSv1_1: + ossl_ssl_version_min = TLS1_1_VERSION; + break; + case CURL_SSLVERSION_TLSv1_2: + ossl_ssl_version_min = TLS1_2_VERSION; + break; + case CURL_SSLVERSION_TLSv1_3: +#ifdef TLS1_3_VERSION + ossl_ssl_version_min = TLS1_3_VERSION; + break; +#else + return CURLE_NOT_BUILT_IN; +#endif + } + + /* CURL_SSLVERSION_DEFAULT means that no option was selected. + We don't want to pass 0 to SSL_CTX_set_min_proto_version as + it would enable all versions down to the lowest supported by + the library. + So we skip this, and stay with the library default + */ + if(curl_ssl_version_min != CURL_SSLVERSION_DEFAULT) { + if(!SSL_CTX_set_min_proto_version(ctx, ossl_ssl_version_min)) { + return CURLE_SSL_CONNECT_ERROR; + } + } + + /* ... then, TLS max version */ + curl_ssl_version_max = conn_config->version_max; + + /* convert curl max SSL version option to OpenSSL constant */ + switch(curl_ssl_version_max) { + case CURL_SSLVERSION_MAX_TLSv1_0: + ossl_ssl_version_max = TLS1_VERSION; + break; + case CURL_SSLVERSION_MAX_TLSv1_1: + ossl_ssl_version_max = TLS1_1_VERSION; + break; + case CURL_SSLVERSION_MAX_TLSv1_2: + ossl_ssl_version_max = TLS1_2_VERSION; + break; +#ifdef TLS1_3_VERSION + case CURL_SSLVERSION_MAX_TLSv1_3: + ossl_ssl_version_max = TLS1_3_VERSION; + break; +#endif + case CURL_SSLVERSION_MAX_NONE: /* none selected */ + case CURL_SSLVERSION_MAX_DEFAULT: /* max selected */ + default: + /* SSL_CTX_set_max_proto_version states that: + setting the maximum to 0 will enable + protocol versions up to the highest version + supported by the library */ + ossl_ssl_version_max = 0; + break; + } + + if(!SSL_CTX_set_max_proto_version(ctx, ossl_ssl_version_max)) { + return CURLE_SSL_CONNECT_ERROR; + } + + return CURLE_OK; +} +#endif + +#if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) +typedef uint32_t ctx_option_t; +#elif OPENSSL_VERSION_NUMBER >= 0x30000000L +typedef uint64_t ctx_option_t; +#else +typedef long ctx_option_t; +#endif + +#if (OPENSSL_VERSION_NUMBER < 0x10100000L) /* 1.1.0 */ +static CURLcode +ossl_set_ssl_version_min_max_legacy(ctx_option_t *ctx_options, + struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + long ssl_version = conn_config->version; + long ssl_version_max = conn_config->version_max; + + (void) data; /* In case it's unused. */ + + switch(ssl_version) { + case CURL_SSLVERSION_TLSv1_3: +#ifdef TLS1_3_VERSION + { + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + DEBUGASSERT(octx); + SSL_CTX_set_max_proto_version(octx->ssl_ctx, TLS1_3_VERSION); + *ctx_options |= SSL_OP_NO_TLSv1_2; + } +#else + (void)ctx_options; + failf(data, OSSL_PACKAGE " was built without TLS 1.3 support"); + return CURLE_NOT_BUILT_IN; +#endif + FALLTHROUGH(); + case CURL_SSLVERSION_TLSv1_2: +#if OPENSSL_VERSION_NUMBER >= 0x1000100FL + *ctx_options |= SSL_OP_NO_TLSv1_1; +#else + failf(data, OSSL_PACKAGE " was built without TLS 1.2 support"); + return CURLE_NOT_BUILT_IN; +#endif + FALLTHROUGH(); + case CURL_SSLVERSION_TLSv1_1: +#if OPENSSL_VERSION_NUMBER >= 0x1000100FL + *ctx_options |= SSL_OP_NO_TLSv1; +#else + failf(data, OSSL_PACKAGE " was built without TLS 1.1 support"); + return CURLE_NOT_BUILT_IN; +#endif + FALLTHROUGH(); + case CURL_SSLVERSION_TLSv1_0: + case CURL_SSLVERSION_TLSv1: + break; + } + + switch(ssl_version_max) { + case CURL_SSLVERSION_MAX_TLSv1_0: +#if OPENSSL_VERSION_NUMBER >= 0x1000100FL + *ctx_options |= SSL_OP_NO_TLSv1_1; +#endif + FALLTHROUGH(); + case CURL_SSLVERSION_MAX_TLSv1_1: +#if OPENSSL_VERSION_NUMBER >= 0x1000100FL + *ctx_options |= SSL_OP_NO_TLSv1_2; +#endif + FALLTHROUGH(); + case CURL_SSLVERSION_MAX_TLSv1_2: +#ifdef TLS1_3_VERSION + *ctx_options |= SSL_OP_NO_TLSv1_3; +#endif + break; + case CURL_SSLVERSION_MAX_TLSv1_3: +#ifdef TLS1_3_VERSION + break; +#else + failf(data, OSSL_PACKAGE " was built without TLS 1.3 support"); + return CURLE_NOT_BUILT_IN; +#endif + } + return CURLE_OK; +} +#endif + +CURLcode Curl_ossl_add_session(struct Curl_cfilter *cf, + struct Curl_easy *data, + const struct ssl_peer *peer, + SSL_SESSION *session) +{ + const struct ssl_config_data *config; + bool isproxy; + bool added = FALSE; + + if(!cf || !data) + goto out; + + isproxy = Curl_ssl_cf_is_proxy(cf); + + config = Curl_ssl_cf_get_config(cf, data); + if(config->primary.sessionid) { + bool incache; + void *old_session = NULL; + + Curl_ssl_sessionid_lock(data); + if(isproxy) + incache = FALSE; + else + incache = !(Curl_ssl_getsessionid(cf, data, peer, + &old_session, NULL)); + if(incache && (old_session != session)) { + infof(data, "old SSL session ID is stale, removing"); + Curl_ssl_delsessionid(data, old_session); + incache = FALSE; + } + + if(!incache) { + added = TRUE; + Curl_ssl_addsessionid(cf, data, peer, session, 0, ossl_session_free); + } + Curl_ssl_sessionid_unlock(data); + } + +out: + if(!added) + ossl_session_free(session, 0); + return CURLE_OK; +} + +/* The "new session" callback must return zero if the session can be removed + * or non-zero if the session has been put into the session cache. + */ +static int ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid) +{ + struct Curl_cfilter *cf; + struct Curl_easy *data; + struct ssl_connect_data *connssl; + + cf = (struct Curl_cfilter*) SSL_get_app_data(ssl); + connssl = cf? cf->ctx : NULL; + data = connssl? CF_DATA_CURRENT(cf) : NULL; + Curl_ossl_add_session(cf, data, &connssl->peer, ssl_sessionid); + return 1; +} + +static CURLcode load_cacert_from_memory(X509_STORE *store, + const struct curl_blob *ca_info_blob) +{ + /* these need to be freed at the end */ + BIO *cbio = NULL; + STACK_OF(X509_INFO) *inf = NULL; + + /* everything else is just a reference */ + int i, count = 0; + X509_INFO *itmp = NULL; + + if(ca_info_blob->len > (size_t)INT_MAX) + return CURLE_SSL_CACERT_BADFILE; + + cbio = BIO_new_mem_buf(ca_info_blob->data, (int)ca_info_blob->len); + if(!cbio) + return CURLE_OUT_OF_MEMORY; + + inf = PEM_X509_INFO_read_bio(cbio, NULL, NULL, NULL); + if(!inf) { + BIO_free(cbio); + return CURLE_SSL_CACERT_BADFILE; + } + + /* add each entry from PEM file to x509_store */ + for(i = 0; i < (int)sk_X509_INFO_num(inf); ++i) { + itmp = sk_X509_INFO_value(inf, i); + if(itmp->x509) { + if(X509_STORE_add_cert(store, itmp->x509)) { + ++count; + } + else { + /* set count to 0 to return an error */ + count = 0; + break; + } + } + if(itmp->crl) { + if(X509_STORE_add_crl(store, itmp->crl)) { + ++count; + } + else { + /* set count to 0 to return an error */ + count = 0; + break; + } + } + } + + sk_X509_INFO_pop_free(inf, X509_INFO_free); + BIO_free(cbio); + + /* if we didn't end up importing anything, treat that as an error */ + return (count > 0) ? CURLE_OK : CURLE_SSL_CACERT_BADFILE; +} + +#if defined(USE_WIN32_CRYPTO) +static CURLcode import_windows_cert_store(struct Curl_easy *data, + const char *name, + X509_STORE *store, + bool *imported) +{ + CURLcode result = CURLE_OK; + HCERTSTORE hStore; + + *imported = false; + + hStore = CertOpenSystemStoreA(0, name); + if(hStore) { + PCCERT_CONTEXT pContext = NULL; + /* The array of enhanced key usage OIDs will vary per certificate and + is declared outside of the loop so that rather than malloc/free each + iteration we can grow it with realloc, when necessary. */ + CERT_ENHKEY_USAGE *enhkey_usage = NULL; + DWORD enhkey_usage_size = 0; + + /* This loop makes a best effort to import all valid certificates from + the MS root store. If a certificate cannot be imported it is + skipped. 'result' is used to store only hard-fail conditions (such + as out of memory) that cause an early break. */ + result = CURLE_OK; + for(;;) { + X509 *x509; + FILETIME now; + BYTE key_usage[2]; + DWORD req_size; + const unsigned char *encoded_cert; +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + char cert_name[256]; +#endif + + pContext = CertEnumCertificatesInStore(hStore, pContext); + if(!pContext) + break; + +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + if(!CertGetNameStringA(pContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, + NULL, cert_name, sizeof(cert_name))) { + strcpy(cert_name, "Unknown"); + } + infof(data, "SSL: Checking cert \"%s\"", cert_name); +#endif + encoded_cert = (const unsigned char *)pContext->pbCertEncoded; + if(!encoded_cert) + continue; + + GetSystemTimeAsFileTime(&now); + if(CompareFileTime(&pContext->pCertInfo->NotBefore, &now) > 0 || + CompareFileTime(&now, &pContext->pCertInfo->NotAfter) > 0) + continue; + + /* If key usage exists check for signing attribute */ + if(CertGetIntendedKeyUsage(pContext->dwCertEncodingType, + pContext->pCertInfo, + key_usage, sizeof(key_usage))) { + if(!(key_usage[0] & CERT_KEY_CERT_SIGN_KEY_USAGE)) + continue; + } + else if(GetLastError()) + continue; + + /* If enhanced key usage exists check for server auth attribute. + * + * Note "In a Microsoft environment, a certificate might also have + * EKU extended properties that specify valid uses for the + * certificate." The call below checks both, and behavior varies + * depending on what is found. For more details see + * CertGetEnhancedKeyUsage doc. + */ + if(CertGetEnhancedKeyUsage(pContext, 0, NULL, &req_size)) { + if(req_size && req_size > enhkey_usage_size) { + void *tmp = realloc(enhkey_usage, req_size); + + if(!tmp) { + failf(data, "SSL: Out of memory allocating for OID list"); + result = CURLE_OUT_OF_MEMORY; + break; + } + + enhkey_usage = (CERT_ENHKEY_USAGE *)tmp; + enhkey_usage_size = req_size; + } + + if(CertGetEnhancedKeyUsage(pContext, 0, enhkey_usage, &req_size)) { + if(!enhkey_usage->cUsageIdentifier) { + /* "If GetLastError returns CRYPT_E_NOT_FOUND, the certificate + is good for all uses. If it returns zero, the certificate + has no valid uses." */ + if((HRESULT)GetLastError() != CRYPT_E_NOT_FOUND) + continue; + } + else { + DWORD i; + bool found = false; + + for(i = 0; i < enhkey_usage->cUsageIdentifier; ++i) { + if(!strcmp("1.3.6.1.5.5.7.3.1" /* OID server auth */, + enhkey_usage->rgpszUsageIdentifier[i])) { + found = true; + break; + } + } + + if(!found) + continue; + } + } + else + continue; + } + else + continue; + + x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded); + if(!x509) + continue; + + /* Try to import the certificate. This may fail for legitimate + reasons such as duplicate certificate, which is allowed by MS but + not OpenSSL. */ + if(X509_STORE_add_cert(store, x509) == 1) { +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + infof(data, "SSL: Imported cert \"%s\"", cert_name); +#endif + *imported = true; + } + X509_free(x509); + } + + free(enhkey_usage); + CertFreeCertificateContext(pContext); + CertCloseStore(hStore, 0); + + if(result) + return result; + } + + return result; +} +#endif + +static CURLcode populate_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + X509_STORE *store) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + CURLcode result = CURLE_OK; + X509_LOOKUP *lookup = NULL; + const struct curl_blob *ca_info_blob = conn_config->ca_info_blob; + const char * const ssl_cafile = + /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */ + (ca_info_blob ? NULL : conn_config->CAfile); + const char * const ssl_capath = conn_config->CApath; + const char * const ssl_crlfile = ssl_config->primary.CRLfile; + const bool verifypeer = conn_config->verifypeer; + bool imported_native_ca = false; + bool imported_ca_info_blob = false; + + CURL_TRC_CF(data, cf, "populate_x509_store, path=%s, blob=%d", + ssl_cafile? ssl_cafile : "none", !!ca_info_blob); + if(!store) + return CURLE_OUT_OF_MEMORY; + + if(verifypeer) { +#if defined(USE_WIN32_CRYPTO) + /* Import certificates from the Windows root certificate store if + requested. + https://stackoverflow.com/questions/9507184/ + https://github.com/d3x0r/SACK/blob/master/src/netlib/ssl_layer.c#L1037 + https://datatracker.ietf.org/doc/html/rfc5280 */ + if(ssl_config->native_ca_store) { + const char *storeNames[] = { + "ROOT", /* Trusted Root Certification Authorities */ + "CA" /* Intermediate Certification Authorities */ + }; + size_t i; + for(i = 0; i < ARRAYSIZE(storeNames); ++i) { + bool imported = false; + result = import_windows_cert_store(data, storeNames[i], store, + &imported); + if(result) + return result; + if(imported) { + infof(data, "successfully imported Windows %s store", storeNames[i]); + imported_native_ca = true; + } + else + infof(data, "error importing Windows %s store, continuing anyway", + storeNames[i]); + } + } +#endif + if(ca_info_blob) { + result = load_cacert_from_memory(store, ca_info_blob); + if(result) { + failf(data, "error importing CA certificate blob"); + return result; + } + else { + imported_ca_info_blob = true; + infof(data, "successfully imported CA certificate blob"); + } + } + + if(ssl_cafile || ssl_capath) { +#if (OPENSSL_VERSION_NUMBER >= 0x30000000L) + /* OpenSSL 3.0.0 has deprecated SSL_CTX_load_verify_locations */ + if(ssl_cafile && !X509_STORE_load_file(store, ssl_cafile)) { + if(!imported_native_ca && !imported_ca_info_blob) { + /* Fail if we insist on successfully verifying the server. */ + failf(data, "error setting certificate file: %s", ssl_cafile); + return CURLE_SSL_CACERT_BADFILE; + } + else + infof(data, "error setting certificate file, continuing anyway"); + } + if(ssl_capath && !X509_STORE_load_path(store, ssl_capath)) { + if(!imported_native_ca && !imported_ca_info_blob) { + /* Fail if we insist on successfully verifying the server. */ + failf(data, "error setting certificate path: %s", ssl_capath); + return CURLE_SSL_CACERT_BADFILE; + } + else + infof(data, "error setting certificate path, continuing anyway"); + } +#else + /* tell OpenSSL where to find CA certificates that are used to verify the + server's certificate. */ + if(!X509_STORE_load_locations(store, ssl_cafile, ssl_capath)) { + if(!imported_native_ca && !imported_ca_info_blob) { + /* Fail if we insist on successfully verifying the server. */ + failf(data, "error setting certificate verify locations:" + " CAfile: %s CApath: %s", + ssl_cafile ? ssl_cafile : "none", + ssl_capath ? ssl_capath : "none"); + return CURLE_SSL_CACERT_BADFILE; + } + else { + infof(data, "error setting certificate verify locations," + " continuing anyway"); + } + } +#endif + infof(data, " CAfile: %s", ssl_cafile ? ssl_cafile : "none"); + infof(data, " CApath: %s", ssl_capath ? ssl_capath : "none"); + } + +#ifdef CURL_CA_FALLBACK + if(!ssl_cafile && !ssl_capath && + !imported_native_ca && !imported_ca_info_blob) { + /* verifying the peer without any CA certificates won't + work so use openssl's built-in default as fallback */ + X509_STORE_set_default_paths(store); + } +#endif + } + + if(ssl_crlfile) { + /* tell OpenSSL where to find CRL file that is used to check certificate + * revocation */ + lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); + if(!lookup || + (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) { + failf(data, "error loading CRL file: %s", ssl_crlfile); + return CURLE_SSL_CRL_BADFILE; + } + /* Everything is fine. */ + infof(data, "successfully loaded CRL file:"); + X509_STORE_set_flags(store, + X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL); + + infof(data, " CRLfile: %s", ssl_crlfile); + } + + if(verifypeer) { + /* Try building a chain using issuers in the trusted store first to avoid + problems with server-sent legacy intermediates. Newer versions of + OpenSSL do alternate chain checking by default but we do not know how to + determine that in a reliable manner. + https://rt.openssl.org/Ticket/Display.html?id=3621&user=guest&pass=guest + */ +#if defined(X509_V_FLAG_TRUSTED_FIRST) + X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST); +#endif +#ifdef X509_V_FLAG_PARTIAL_CHAIN + if(!ssl_config->no_partialchain && !ssl_crlfile) { + /* Have intermediate certificates in the trust store be treated as + trust-anchors, in the same way as self-signed root CA certificates + are. This allows users to verify servers using the intermediate cert + only, instead of needing the whole chain. + + Due to OpenSSL bug https://github.com/openssl/openssl/issues/5081 we + cannot do partial chains with a CRL check. + */ + X509_STORE_set_flags(store, X509_V_FLAG_PARTIAL_CHAIN); + } +#endif + } + + return result; +} + +#if defined(HAVE_SSL_X509_STORE_SHARE) +static bool cached_x509_store_expired(const struct Curl_easy *data, + const struct multi_ssl_backend_data *mb) +{ + const struct ssl_general_config *cfg = &data->set.general_ssl; + struct curltime now = Curl_now(); + timediff_t elapsed_ms = Curl_timediff(now, mb->time); + timediff_t timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000; + + if(timeout_ms < 0) + return false; + + return elapsed_ms >= timeout_ms; +} + +static bool cached_x509_store_different( + struct Curl_cfilter *cf, + const struct multi_ssl_backend_data *mb) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + if(!mb->CAfile || !conn_config->CAfile) + return mb->CAfile != conn_config->CAfile; + + return strcmp(mb->CAfile, conn_config->CAfile); +} + +static X509_STORE *get_cached_x509_store(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct Curl_multi *multi = data->multi; + X509_STORE *store = NULL; + + DEBUGASSERT(multi); + if(multi && + multi->ssl_backend_data && + multi->ssl_backend_data->store && + !cached_x509_store_expired(data, multi->ssl_backend_data) && + !cached_x509_store_different(cf, multi->ssl_backend_data)) { + store = multi->ssl_backend_data->store; + } + + return store; +} + +static void set_cached_x509_store(struct Curl_cfilter *cf, + const struct Curl_easy *data, + X509_STORE *store) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct Curl_multi *multi = data->multi; + struct multi_ssl_backend_data *mbackend; + + DEBUGASSERT(multi); + if(!multi) + return; + + if(!multi->ssl_backend_data) { + multi->ssl_backend_data = calloc(1, sizeof(struct multi_ssl_backend_data)); + if(!multi->ssl_backend_data) + return; + } + + mbackend = multi->ssl_backend_data; + + if(X509_STORE_up_ref(store)) { + char *CAfile = NULL; + + if(conn_config->CAfile) { + CAfile = strdup(conn_config->CAfile); + if(!CAfile) { + X509_STORE_free(store); + return; + } + } + + if(mbackend->store) { + X509_STORE_free(mbackend->store); + free(mbackend->CAfile); + } + + mbackend->time = Curl_now(); + mbackend->store = store; + mbackend->CAfile = CAfile; + } +} + +CURLcode Curl_ssl_setup_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + SSL_CTX *ssl_ctx) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + CURLcode result = CURLE_OK; + X509_STORE *cached_store; + bool cache_criteria_met; + + /* Consider the X509 store cacheable if it comes exclusively from a CAfile, + or no source is provided and we are falling back to openssl's built-in + default. */ + cache_criteria_met = (data->set.general_ssl.ca_cache_timeout != 0) && + conn_config->verifypeer && + !conn_config->CApath && + !conn_config->ca_info_blob && + !ssl_config->primary.CRLfile && + !ssl_config->native_ca_store; + + cached_store = get_cached_x509_store(cf, data); + if(cached_store && cache_criteria_met && X509_STORE_up_ref(cached_store)) { + SSL_CTX_set_cert_store(ssl_ctx, cached_store); + } + else { + X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx); + + result = populate_x509_store(cf, data, store); + if(result == CURLE_OK && cache_criteria_met) { + set_cached_x509_store(cf, data, store); + } + } + + return result; +} +#else /* HAVE_SSL_X509_STORE_SHARE */ +CURLcode Curl_ssl_setup_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + SSL_CTX *ssl_ctx) +{ + X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx); + + return populate_x509_store(cf, data, store); +} +#endif /* HAVE_SSL_X509_STORE_SHARE */ + +CURLcode Curl_ossl_ctx_init(struct ossl_ctx *octx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + int transport, /* TCP or QUIC */ + const unsigned char *alpn, size_t alpn_len, + Curl_ossl_ctx_setup_cb *cb_setup, + void *cb_user_data, + Curl_ossl_new_session_cb *cb_new_session, + void *ssl_user_data) +{ + CURLcode result = CURLE_OK; + const char *ciphers; + SSL_METHOD_QUAL SSL_METHOD *req_method = NULL; + ctx_option_t ctx_options = 0; + void *ssl_sessionid = NULL; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + const long int ssl_version = conn_config->version; + char * const ssl_cert = ssl_config->primary.clientcert; + const struct curl_blob *ssl_cert_blob = ssl_config->primary.cert_blob; + const char * const ssl_cert_type = ssl_config->cert_type; + const bool verifypeer = conn_config->verifypeer; + char error_buffer[256]; +#ifdef USE_ECH + struct ssl_connect_data *connssl = cf->ctx; +#endif + + /* Make funny stuff to get random input */ + result = ossl_seed(data); + if(result) + return result; + + ssl_config->certverifyresult = !X509_V_OK; + + switch(transport) { + case TRNSPRT_TCP: + /* check to see if we've been told to use an explicit SSL/TLS version */ + switch(ssl_version) { + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1: + case CURL_SSLVERSION_TLSv1_0: + case CURL_SSLVERSION_TLSv1_1: + case CURL_SSLVERSION_TLSv1_2: + case CURL_SSLVERSION_TLSv1_3: + /* it will be handled later with the context options */ + #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) + req_method = TLS_client_method(); + #else + req_method = SSLv23_client_method(); + #endif + break; + case CURL_SSLVERSION_SSLv2: + failf(data, "No SSLv2 support"); + return CURLE_NOT_BUILT_IN; + case CURL_SSLVERSION_SSLv3: + failf(data, "No SSLv3 support"); + return CURLE_NOT_BUILT_IN; + default: + failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); + return CURLE_SSL_CONNECT_ERROR; + } + break; + case TRNSPRT_QUIC: + if((ssl_version != CURL_SSLVERSION_DEFAULT) && + (ssl_version < CURL_SSLVERSION_TLSv1_3)) { + failf(data, "QUIC needs at least TLS version 1.3"); + return CURLE_SSL_CONNECT_ERROR; + } +#ifdef USE_OPENSSL_QUIC + req_method = OSSL_QUIC_client_method(); +#elif (OPENSSL_VERSION_NUMBER >= 0x10100000L) + req_method = TLS_method(); +#else + req_method = SSLv23_client_method(); +#endif + break; + default: + failf(data, "unsupported transport %d in SSL init", transport); + return CURLE_SSL_CONNECT_ERROR; + } + + + DEBUGASSERT(!octx->ssl_ctx); + octx->ssl_ctx = SSL_CTX_new(req_method); + + if(!octx->ssl_ctx) { + failf(data, "SSL: couldn't create a context: %s", + ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer))); + return CURLE_OUT_OF_MEMORY; + } + + if(cb_setup) { + result = cb_setup(cf, data, cb_user_data); + if(result) + return result; + } + +#ifdef SSL_CTRL_SET_MSG_CALLBACK + if(data->set.fdebug && data->set.verbose) { + /* the SSL trace callback is only used for verbose logging */ + SSL_CTX_set_msg_callback(octx->ssl_ctx, ossl_trace); + SSL_CTX_set_msg_callback_arg(octx->ssl_ctx, cf); + } +#endif + + /* OpenSSL contains code to work around lots of bugs and flaws in various + SSL-implementations. SSL_CTX_set_options() is used to enabled those + work-arounds. The man page for this option states that SSL_OP_ALL enables + all the work-arounds and that "It is usually safe to use SSL_OP_ALL to + enable the bug workaround options if compatibility with somewhat broken + implementations is desired." + + The "-no_ticket" option was introduced in OpenSSL 0.9.8j. It's a flag to + disable "rfc4507bis session ticket support". rfc4507bis was later turned + into the proper RFC5077: https://datatracker.ietf.org/doc/html/rfc5077 + + The enabled extension concerns the session management. I wonder how often + libcurl stops a connection and then resumes a TLS session. Also, sending + the session data is some overhead. I suggest that you just use your + proposed patch (which explicitly disables TICKET). + + If someone writes an application with libcurl and OpenSSL who wants to + enable the feature, one can do this in the SSL callback. + + SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper + interoperability with web server Netscape Enterprise Server 2.0.1 which + was released back in 1996. + + Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has + become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate + CVE-2010-4180 when using previous OpenSSL versions we no longer enable + this option regardless of OpenSSL version and SSL_OP_ALL definition. + + OpenSSL added a work-around for a SSL 3.0/TLS 1.0 CBC vulnerability + (https://www.openssl.org/~bodo/tls-cbc.txt). In 0.9.6e they added a bit to + SSL_OP_ALL that _disables_ that work-around despite the fact that + SSL_OP_ALL is documented to do "rather harmless" workarounds. In order to + keep the secure work-around, the SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit + must not be set. + */ + + ctx_options = SSL_OP_ALL; + +#ifdef SSL_OP_NO_TICKET + ctx_options |= SSL_OP_NO_TICKET; +#endif + +#ifdef SSL_OP_NO_COMPRESSION + ctx_options |= SSL_OP_NO_COMPRESSION; +#endif + +#ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG + /* mitigate CVE-2010-4180 */ + ctx_options &= ~SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG; +#endif + +#ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS + /* unless the user explicitly asks to allow the protocol vulnerability we + use the work-around */ + if(!ssl_config->enable_beast) + ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; +#endif + + switch(ssl_version) { + case CURL_SSLVERSION_SSLv2: + case CURL_SSLVERSION_SSLv3: + return CURLE_NOT_BUILT_IN; + + /* "--tlsv" options mean TLS >= version */ + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1: /* TLS >= version 1.0 */ + case CURL_SSLVERSION_TLSv1_0: /* TLS >= version 1.0 */ + case CURL_SSLVERSION_TLSv1_1: /* TLS >= version 1.1 */ + case CURL_SSLVERSION_TLSv1_2: /* TLS >= version 1.2 */ + case CURL_SSLVERSION_TLSv1_3: /* TLS >= version 1.3 */ + /* asking for any TLS version as the minimum, means no SSL versions + allowed */ + ctx_options |= SSL_OP_NO_SSLv2; + ctx_options |= SSL_OP_NO_SSLv3; + +#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* 1.1.0 */ + result = ossl_set_ssl_version_min_max(cf, octx->ssl_ctx); +#else + result = ossl_set_ssl_version_min_max_legacy(&ctx_options, cf, data); +#endif + if(result != CURLE_OK) + return result; + break; + + default: + failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); + return CURLE_SSL_CONNECT_ERROR; + } + + SSL_CTX_set_options(octx->ssl_ctx, ctx_options); + +#ifdef HAS_ALPN + if(alpn && alpn_len) { + if(SSL_CTX_set_alpn_protos(octx->ssl_ctx, alpn, (int)alpn_len)) { + failf(data, "Error setting ALPN"); + return CURLE_SSL_CONNECT_ERROR; + } + } +#endif + + if(ssl_cert || ssl_cert_blob || ssl_cert_type) { + if(!result && + !cert_stuff(data, octx->ssl_ctx, + ssl_cert, ssl_cert_blob, ssl_cert_type, + ssl_config->key, ssl_config->key_blob, + ssl_config->key_type, ssl_config->key_passwd)) + result = CURLE_SSL_CERTPROBLEM; + if(result) + /* failf() is already done in cert_stuff() */ + return result; + } + + ciphers = conn_config->cipher_list; + if(!ciphers && (peer->transport != TRNSPRT_QUIC)) + ciphers = DEFAULT_CIPHER_SELECTION; + if(ciphers) { + if(!SSL_CTX_set_cipher_list(octx->ssl_ctx, ciphers)) { + failf(data, "failed setting cipher list: %s", ciphers); + return CURLE_SSL_CIPHER; + } + infof(data, "Cipher selection: %s", ciphers); + } + +#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES + { + const char *ciphers13 = conn_config->cipher_list13; + if(ciphers13) { + if(!SSL_CTX_set_ciphersuites(octx->ssl_ctx, ciphers13)) { + failf(data, "failed setting TLS 1.3 cipher suite: %s", ciphers13); + return CURLE_SSL_CIPHER; + } + infof(data, "TLS 1.3 cipher selection: %s", ciphers13); + } + } +#endif + +#ifdef HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH + /* OpenSSL 1.1.1 requires clients to opt-in for PHA */ + SSL_CTX_set_post_handshake_auth(octx->ssl_ctx, 1); +#endif + +#ifdef HAVE_SSL_CTX_SET_EC_CURVES + { + const char *curves = conn_config->curves; + if(curves) { + if(!SSL_CTX_set1_curves_list(octx->ssl_ctx, curves)) { + failf(data, "failed setting curves list: '%s'", curves); + return CURLE_SSL_CIPHER; + } + } + } +#endif + +#ifdef USE_OPENSSL_SRP + if(ssl_config->primary.username && Curl_auth_allowed_to_host(data)) { + char * const ssl_username = ssl_config->primary.username; + char * const ssl_password = ssl_config->primary.password; + infof(data, "Using TLS-SRP username: %s", ssl_username); + + if(!SSL_CTX_set_srp_username(octx->ssl_ctx, ssl_username)) { + failf(data, "Unable to set SRP user name"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + if(!SSL_CTX_set_srp_password(octx->ssl_ctx, ssl_password)) { + failf(data, "failed setting SRP password"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + if(!conn_config->cipher_list) { + infof(data, "Setting cipher list SRP"); + + if(!SSL_CTX_set_cipher_list(octx->ssl_ctx, "SRP")) { + failf(data, "failed setting SRP cipher list"); + return CURLE_SSL_CIPHER; + } + } + } +#endif + + /* OpenSSL always tries to verify the peer, this only says whether it should + * fail to connect if the verification fails, or if it should continue + * anyway. In the latter case the result of the verification is checked with + * SSL_get_verify_result() below. */ + SSL_CTX_set_verify(octx->ssl_ctx, + verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL); + + /* Enable logging of secrets to the file specified in env SSLKEYLOGFILE. */ +#ifdef HAVE_KEYLOG_CALLBACK + if(Curl_tls_keylog_enabled()) { + SSL_CTX_set_keylog_callback(octx->ssl_ctx, ossl_keylog_callback); + } +#endif + + if(cb_new_session) { + /* Enable the session cache because it's a prerequisite for the + * "new session" callback. Use the "external storage" mode to prevent + * OpenSSL from creating an internal session cache. + */ + SSL_CTX_set_session_cache_mode(octx->ssl_ctx, + SSL_SESS_CACHE_CLIENT | + SSL_SESS_CACHE_NO_INTERNAL); + SSL_CTX_sess_set_new_cb(octx->ssl_ctx, cb_new_session); + } + + /* give application a chance to interfere with SSL set up. */ + if(data->set.ssl.fsslctx) { + /* When a user callback is installed to modify the SSL_CTX, + * we need to do the full initialization before calling it. + * See: #11800 */ + if(!octx->x509_store_setup) { + result = Curl_ssl_setup_x509_store(cf, data, octx->ssl_ctx); + if(result) + return result; + octx->x509_store_setup = TRUE; + } + Curl_set_in_callback(data, true); + result = (*data->set.ssl.fsslctx)(data, octx->ssl_ctx, + data->set.ssl.fsslctxp); + Curl_set_in_callback(data, false); + if(result) { + failf(data, "error signaled by ssl ctx callback"); + return result; + } + } + + /* Let's make an SSL structure */ + if(octx->ssl) + SSL_free(octx->ssl); + octx->ssl = SSL_new(octx->ssl_ctx); + if(!octx->ssl) { + failf(data, "SSL: couldn't create a context (handle)"); + return CURLE_OUT_OF_MEMORY; + } + + SSL_set_app_data(octx->ssl, ssl_user_data); + +#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \ + !defined(OPENSSL_NO_OCSP) + if(conn_config->verifystatus) + SSL_set_tlsext_status_type(octx->ssl, TLSEXT_STATUSTYPE_ocsp); +#endif + +#if (defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC)) && \ + defined(ALLOW_RENEG) + SSL_set_renegotiate_mode(octx->ssl, ssl_renegotiate_freely); +#endif + + SSL_set_connect_state(octx->ssl); + + octx->server_cert = 0x0; +#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME + if(peer->sni) { + if(!SSL_set_tlsext_host_name(octx->ssl, peer->sni)) { + failf(data, "Failed set SNI"); + return CURLE_SSL_CONNECT_ERROR; + } + } + +#ifdef USE_ECH + if(ECH_ENABLED(data)) { + unsigned char *ech_config = NULL; + size_t ech_config_len = 0; + char *outername = data->set.str[STRING_ECH_PUBLIC]; + int trying_ech_now = 0; + + if(data->set.tls_ech & CURLECH_GREASE) { + infof(data, "ECH: will GREASE ClientHello"); +# ifdef OPENSSL_IS_BORINGSSL + SSL_set_enable_ech_grease(octx->ssl, 1); +# else + SSL_set_options(octx->ssl, SSL_OP_ECH_GREASE); +# endif + } + else if(data->set.tls_ech & CURLECH_CLA_CFG) { +# ifdef OPENSSL_IS_BORINGSSL + /* have to do base64 decode here for boring */ + const char *b64 = data->set.str[STRING_ECH_CONFIG]; + + if(!b64) { + infof(data, "ECH: ECHConfig from command line empty"); + return CURLE_SSL_CONNECT_ERROR; + } + ech_config_len = 2 * strlen(b64); + result = Curl_base64_decode(b64, &ech_config, &ech_config_len); + if(result || !ech_config) { + infof(data, "ECH: can't base64 decode ECHConfig from command line"); + if(data->set.tls_ech & CURLECH_HARD) + return result; + } + if(SSL_set1_ech_config_list(octx->ssl, ech_config, + ech_config_len) != 1) { + infof(data, "ECH: SSL_ECH_set1_echconfig failed"); + if(data->set.tls_ech & CURLECH_HARD) { + free(ech_config); + return CURLE_SSL_CONNECT_ERROR; + } + } + free(ech_config); + trying_ech_now = 1; +# else + ech_config = (unsigned char *) data->set.str[STRING_ECH_CONFIG]; + if(!ech_config) { + infof(data, "ECH: ECHConfig from command line empty"); + return CURLE_SSL_CONNECT_ERROR; + } + ech_config_len = strlen(data->set.str[STRING_ECH_CONFIG]); + if(SSL_ech_set1_echconfig(octx->ssl, ech_config, ech_config_len) != 1) { + infof(data, "ECH: SSL_ECH_set1_echconfig failed"); + if(data->set.tls_ech & CURLECH_HARD) + return CURLE_SSL_CONNECT_ERROR; + } + else + trying_ech_now = 1; +# endif + infof(data, "ECH: ECHConfig from command line"); + } + else { + struct Curl_dns_entry *dns = NULL; + + dns = Curl_fetch_addr(data, connssl->peer.hostname, connssl->peer.port); + if(!dns) { + infof(data, "ECH: requested but no DNS info available"); + if(data->set.tls_ech & CURLECH_HARD) + return CURLE_SSL_CONNECT_ERROR; + } + else { + struct Curl_https_rrinfo *rinfo = NULL; + + rinfo = dns->hinfo; + if(rinfo && rinfo->echconfiglist) { + unsigned char *ecl = rinfo->echconfiglist; + size_t elen = rinfo->echconfiglist_len; + + infof(data, "ECH: ECHConfig from DoH HTTPS RR"); +# ifndef OPENSSL_IS_BORINGSSL + if(SSL_ech_set1_echconfig(octx->ssl, ecl, elen) != 1) { + infof(data, "ECH: SSL_ECH_set1_echconfig failed"); + if(data->set.tls_ech & CURLECH_HARD) + return CURLE_SSL_CONNECT_ERROR; + } +# else + if(SSL_set1_ech_config_list(octx->ssl, ecl, elen) != 1) { + infof(data, "ECH: SSL_set1_ech_config_list failed (boring)"); + if(data->set.tls_ech & CURLECH_HARD) + return CURLE_SSL_CONNECT_ERROR; + } +# endif + else { + trying_ech_now = 1; + infof(data, "ECH: imported ECHConfigList of length %ld", elen); + } + } + else { + infof(data, "ECH: requested but no ECHConfig available"); + if(data->set.tls_ech & CURLECH_HARD) + return CURLE_SSL_CONNECT_ERROR; + } + Curl_resolv_unlock(data, dns); + } + } +# ifdef OPENSSL_IS_BORINGSSL + if(trying_ech_now && outername) { + infof(data, "ECH: setting public_name not supported with boringssl"); + return CURLE_SSL_CONNECT_ERROR; + } +# else + if(trying_ech_now && outername) { + infof(data, "ECH: inner: '%s', outer: '%s'", + connssl->peer.hostname, outername); + result = SSL_ech_set_server_names(octx->ssl, + connssl->peer.hostname, outername, + 0 /* do send outer */); + if(result != 1) { + infof(data, "ECH: rv failed to set server name(s) %d [ERROR]", result); + return CURLE_SSL_CONNECT_ERROR; + } + } +# endif /* not BORING */ + if(trying_ech_now + && SSL_set_min_proto_version(octx->ssl, TLS1_3_VERSION) != 1) { + infof(data, "ECH: Can't force TLSv1.3 [ERROR]"); + return CURLE_SSL_CONNECT_ERROR; + } + } +#endif /* USE_ECH */ + +#endif + + octx->reused_session = FALSE; + if(ssl_config->primary.sessionid && transport == TRNSPRT_TCP) { + Curl_ssl_sessionid_lock(data); + if(!Curl_ssl_getsessionid(cf, data, peer, &ssl_sessionid, NULL)) { + /* we got a session id, use it! */ + if(!SSL_set_session(octx->ssl, ssl_sessionid)) { + Curl_ssl_sessionid_unlock(data); + failf(data, "SSL: SSL_set_session failed: %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + return CURLE_SSL_CONNECT_ERROR; + } + /* Informational message */ + infof(data, "SSL reusing session ID"); + octx->reused_session = TRUE; + } + Curl_ssl_sessionid_unlock(data); + } + + return CURLE_OK; +} + +static CURLcode ossl_connect_step1(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + struct alpn_proto_buf proto; + BIO *bio; + CURLcode result; + + DEBUGASSERT(ssl_connect_1 == connssl->connecting_state); + DEBUGASSERT(octx); + memset(&proto, 0, sizeof(proto)); +#ifdef HAS_ALPN + if(connssl->alpn) { + result = Curl_alpn_to_proto_buf(&proto, connssl->alpn); + if(result) { + failf(data, "Error determining ALPN"); + return CURLE_SSL_CONNECT_ERROR; + } + } +#endif + + result = Curl_ossl_ctx_init(octx, cf, data, &connssl->peer, TRNSPRT_TCP, + proto.data, proto.len, NULL, NULL, + ossl_new_session_cb, cf); + if(result) + return result; + + octx->bio_method = ossl_bio_cf_method_create(); + if(!octx->bio_method) + return CURLE_OUT_OF_MEMORY; + bio = BIO_new(octx->bio_method); + if(!bio) + return CURLE_OUT_OF_MEMORY; + + BIO_set_data(bio, cf); +#ifdef HAVE_SSL_SET0_WBIO + /* with OpenSSL v1.1.1 we get an alternative to SSL_set_bio() that works + * without backward compat quirks. Every call takes one reference, so we + * up it and pass. SSL* then owns it and will free. + * We check on the function in configure, since libressl and friends + * each have their own versions to add support for this. */ + BIO_up_ref(bio); + SSL_set0_rbio(octx->ssl, bio); + SSL_set0_wbio(octx->ssl, bio); +#else + SSL_set_bio(octx->ssl, bio, bio); +#endif + +#ifdef HAS_ALPN + if(connssl->alpn) { + Curl_alpn_to_proto_str(&proto, connssl->alpn); + infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data); + } +#endif + connssl->connecting_state = ssl_connect_2; + return CURLE_OK; +} + +#ifdef USE_ECH +/* If we have retry configs, then trace those out */ +static void ossl_trace_ech_retry_configs(struct Curl_easy *data, SSL* ssl, + int reason) +{ + CURLcode result = CURLE_OK; + size_t rcl = 0; + int rv = 1; +# ifndef OPENSSL_IS_BORINGSSL + char *inner = NULL; + unsigned char *rcs = NULL; + char *outer = NULL; +# else + const char *inner = NULL; + const uint8_t *rcs = NULL; + const char *outer = NULL; + size_t out_name_len = 0; + int servername_type = 0; +# endif + + /* nothing to trace if not doing ECH */ + if(!ECH_ENABLED(data)) + return; +# ifndef OPENSSL_IS_BORINGSSL + rv = SSL_ech_get_retry_config(ssl, &rcs, &rcl); +# else + SSL_get0_ech_retry_configs(ssl, &rcs, &rcl); + rv = (int)rcl; +# endif + + if(rv && rcs) { +# define HEXSTR_MAX 800 + char *b64str = NULL; + size_t blen = 0; + + result = Curl_base64_encode((const char *)rcs, rcl, + &b64str, &blen); + if(!result && b64str) + infof(data, "ECH: retry_configs %s", b64str); + free(b64str); +# ifndef OPENSSL_IS_BORINGSSL + rv = SSL_ech_get_status(ssl, &inner, &outer); + infof(data, "ECH: retry_configs for %s from %s, %d %d", + inner ? inner : "NULL", outer ? outer : "NULL", reason, rv); +#else + rv = SSL_ech_accepted(ssl); + servername_type = SSL_get_servername_type(ssl); + inner = SSL_get_servername(ssl, servername_type); + SSL_get0_ech_name_override(ssl, &outer, &out_name_len); + /* TODO: get the inner from boring */ + infof(data, "ECH: retry_configs for %s from %s, %d %d", + inner ? inner : "NULL", outer ? outer : "NULL", reason, rv); +#endif + } + else + infof(data, "ECH: no retry_configs (rv = %d)", rv); +# ifndef OPENSSL_IS_BORINGSSL + OPENSSL_free((void *)rcs); +# endif + return; +} + +#endif + +static CURLcode ossl_connect_step2(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + int err; + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + DEBUGASSERT(ssl_connect_2 == connssl->connecting_state + || ssl_connect_2_reading == connssl->connecting_state + || ssl_connect_2_writing == connssl->connecting_state); + DEBUGASSERT(octx); + + ERR_clear_error(); + + err = SSL_connect(octx->ssl); + + if(!octx->x509_store_setup) { + /* After having send off the ClientHello, we prepare the x509 + * store to verify the coming certificate from the server */ + CURLcode result = Curl_ssl_setup_x509_store(cf, data, octx->ssl_ctx); + if(result) + return result; + octx->x509_store_setup = TRUE; + } + +#ifndef HAVE_KEYLOG_CALLBACK + if(Curl_tls_keylog_enabled()) { + /* If key logging is enabled, wait for the handshake to complete and then + * proceed with logging secrets (for TLS 1.2 or older). + */ + bool done = FALSE; + ossl_log_tls12_secret(octx->ssl, &done); + octx->keylog_done = done; + } +#endif + + /* 1 is fine + 0 is "not successful but was shut down controlled" + <0 is "handshake was not successful, because a fatal error occurred" */ + if(1 != err) { + int detail = SSL_get_error(octx->ssl, err); + + if(SSL_ERROR_WANT_READ == detail) { + connssl->connecting_state = ssl_connect_2_reading; + return CURLE_OK; + } + if(SSL_ERROR_WANT_WRITE == detail) { + connssl->connecting_state = ssl_connect_2_writing; + return CURLE_OK; + } +#ifdef SSL_ERROR_WANT_ASYNC + if(SSL_ERROR_WANT_ASYNC == detail) { + connssl->connecting_state = ssl_connect_2; + return CURLE_OK; + } +#endif +#ifdef SSL_ERROR_WANT_RETRY_VERIFY + if(SSL_ERROR_WANT_RETRY_VERIFY == detail) { + connssl->connecting_state = ssl_connect_2; + return CURLE_OK; + } +#endif + if(octx->io_result == CURLE_AGAIN) { + return CURLE_OK; + } + else { + /* untreated error */ + sslerr_t errdetail; + char error_buffer[256]=""; + CURLcode result; + long lerr; + int lib; + int reason; + + /* the connection failed, we're not waiting for anything else. */ + connssl->connecting_state = ssl_connect_2; + + /* Get the earliest error code from the thread's error queue and remove + the entry. */ + errdetail = ERR_get_error(); + + /* Extract which lib and reason */ + lib = ERR_GET_LIB(errdetail); + reason = ERR_GET_REASON(errdetail); + + if((lib == ERR_LIB_SSL) && + ((reason == SSL_R_CERTIFICATE_VERIFY_FAILED) || + (reason == SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED))) { + result = CURLE_PEER_FAILED_VERIFICATION; + + lerr = SSL_get_verify_result(octx->ssl); + if(lerr != X509_V_OK) { + ssl_config->certverifyresult = lerr; + msnprintf(error_buffer, sizeof(error_buffer), + "SSL certificate problem: %s", + X509_verify_cert_error_string(lerr)); + } + else + /* strcpy() is fine here as long as the string fits within + error_buffer */ + strcpy(error_buffer, "SSL certificate verification failed"); + } +#if defined(SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED) + /* SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED is only available on + OpenSSL version above v1.1.1, not LibreSSL, BoringSSL, or AWS-LC */ + else if((lib == ERR_LIB_SSL) && + (reason == SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED)) { + /* If client certificate is required, communicate the + error to client */ + result = CURLE_SSL_CLIENTCERT; + ossl_strerror(errdetail, error_buffer, sizeof(error_buffer)); + } +#endif +#ifdef USE_ECH + else if((lib == ERR_LIB_SSL) && +# ifndef OPENSSL_IS_BORINGSSL + (reason == SSL_R_ECH_REQUIRED)) { +# else + (reason == SSL_R_ECH_REJECTED)) { +# endif + + /* trace retry_configs if we got some */ + ossl_trace_ech_retry_configs(data, octx->ssl, reason); + + result = CURLE_ECH_REQUIRED; + ossl_strerror(errdetail, error_buffer, sizeof(error_buffer)); + } +#endif + else { + result = CURLE_SSL_CONNECT_ERROR; + ossl_strerror(errdetail, error_buffer, sizeof(error_buffer)); + } + + /* detail is already set to the SSL error above */ + + /* If we e.g. use SSLv2 request-method and the server doesn't like us + * (RST connection, etc.), OpenSSL gives no explanation whatsoever and + * the SO_ERROR is also lost. + */ + if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) { + char extramsg[80]=""; + int sockerr = SOCKERRNO; + + if(sockerr && detail == SSL_ERROR_SYSCALL) + Curl_strerror(sockerr, extramsg, sizeof(extramsg)); + failf(data, OSSL_PACKAGE " SSL_connect: %s in connection to %s:%d ", + extramsg[0] ? extramsg : SSL_ERROR_to_str(detail), + connssl->peer.hostname, connssl->peer.port); + return result; + } + + /* Could be a CERT problem */ + failf(data, "%s", error_buffer); + + return result; + } + } + else { + int psigtype_nid = NID_undef; + const char *negotiated_group_name = NULL; + + /* we connected fine, we're not waiting for anything else. */ + connssl->connecting_state = ssl_connect_3; + +#if (OPENSSL_VERSION_NUMBER >= 0x30000000L) + SSL_get_peer_signature_type_nid(octx->ssl, &psigtype_nid); +#if (OPENSSL_VERSION_NUMBER >= 0x30200000L) + negotiated_group_name = SSL_get0_group_name(octx->ssl); +#else + negotiated_group_name = + OBJ_nid2sn(SSL_get_negotiated_group(octx->ssl) & 0x0000FFFF); +#endif +#endif + + /* Informational message */ + infof(data, "SSL connection using %s / %s / %s / %s", + SSL_get_version(octx->ssl), + SSL_get_cipher(octx->ssl), + negotiated_group_name? negotiated_group_name : "[blank]", + OBJ_nid2sn(psigtype_nid)); + +#ifdef USE_ECH +# ifndef OPENSSL_IS_BORINGSSL + if(ECH_ENABLED(data)) { + char *inner = NULL, *outer = NULL; + const char *status = NULL; + int rv; + + rv = SSL_ech_get_status(octx->ssl, &inner, &outer); + switch(rv) { + case SSL_ECH_STATUS_SUCCESS: + status = "succeeded"; + break; + case SSL_ECH_STATUS_GREASE_ECH: + status = "sent GREASE, got retry-configs"; + break; + case SSL_ECH_STATUS_GREASE: + status = "sent GREASE"; + break; + case SSL_ECH_STATUS_NOT_TRIED: + status = "not attempted"; + break; + case SSL_ECH_STATUS_NOT_CONFIGURED: + status = "not configured"; + break; + case SSL_ECH_STATUS_BACKEND: + status = "backend (unexpected)"; + break; + case SSL_ECH_STATUS_FAILED: + status = "failed"; + break; + case SSL_ECH_STATUS_BAD_CALL: + status = "bad call (unexpected)"; + break; + case SSL_ECH_STATUS_BAD_NAME: + status = "bad name (unexpected)"; + break; + default: + status = "unexpected status"; + infof(data, "ECH: unexpected status %d",rv); + } + infof(data, "ECH: result: status is %s, inner is %s, outer is %s", + (status?status:"NULL"), + (inner?inner:"NULL"), + (outer?outer:"NULL")); + OPENSSL_free(inner); + OPENSSL_free(outer); + if(rv == SSL_ECH_STATUS_GREASE_ECH) { + /* trace retry_configs if we got some */ + ossl_trace_ech_retry_configs(data, octx->ssl, 0); + } + if(rv != SSL_ECH_STATUS_SUCCESS + && data->set.tls_ech & CURLECH_HARD) { + infof(data, "ECH: ech-hard failed"); + return CURLE_SSL_CONNECT_ERROR; + } + } + else { + infof(data, "ECH: result: status is not attempted"); + } +# endif /* BORING */ +#endif /* USE_ECH */ + +#ifdef HAS_ALPN + /* Sets data and len to negotiated protocol, len is 0 if no protocol was + * negotiated + */ + if(connssl->alpn) { + const unsigned char *neg_protocol; + unsigned int len; + SSL_get0_alpn_selected(octx->ssl, &neg_protocol, &len); + + return Curl_alpn_set_negotiated(cf, data, neg_protocol, len); + } +#endif + + return CURLE_OK; + } +} + +/* + * Heavily modified from: + * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL + */ +static CURLcode ossl_pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert, + const char *pinnedpubkey) +{ + /* Scratch */ + int len1 = 0, len2 = 0; + unsigned char *buff1 = NULL, *temp = NULL; + + /* Result is returned to caller */ + CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; + + /* if a path wasn't specified, don't pin */ + if(!pinnedpubkey) + return CURLE_OK; + + if(!cert) + return result; + + do { + /* Begin Gyrations to get the subjectPublicKeyInfo */ + /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */ + + /* https://groups.google.com/group/mailing.openssl.users/browse_thread + /thread/d61858dae102c6c7 */ + len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL); + if(len1 < 1) + break; /* failed */ + + buff1 = temp = malloc(len1); + if(!buff1) + break; /* failed */ + + /* https://www.openssl.org/docs/crypto/d2i_X509.html */ + len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp); + + /* + * These checks are verifying we got back the same values as when we + * sized the buffer. It's pretty weak since they should always be the + * same. But it gives us something to test. + */ + if((len1 != len2) || !temp || ((temp - buff1) != len1)) + break; /* failed */ + + /* End Gyrations */ + + /* The one good exit point */ + result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1); + } while(0); + + if(buff1) + free(buff1); + + return result; +} + +#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \ + !(defined(LIBRESSL_VERSION_NUMBER) && \ + LIBRESSL_VERSION_NUMBER < 0x3060000fL) && \ + !defined(OPENSSL_IS_BORINGSSL) && \ + !defined(OPENSSL_IS_AWSLC) && \ + !defined(CURL_DISABLE_VERBOSE_STRINGS) +static void infof_certstack(struct Curl_easy *data, const SSL *ssl) +{ + STACK_OF(X509) *certstack; + long verify_result; + int num_cert_levels; + int cert_level; + + verify_result = SSL_get_verify_result(ssl); + if(verify_result != X509_V_OK) + certstack = SSL_get_peer_cert_chain(ssl); + else + certstack = SSL_get0_verified_chain(ssl); + num_cert_levels = sk_X509_num(certstack); + + for(cert_level = 0; cert_level < num_cert_levels; cert_level++) { + char cert_algorithm[80] = ""; + char group_name_final[80] = ""; + const X509_ALGOR *palg_cert = NULL; + const ASN1_OBJECT *paobj_cert = NULL; + X509 *current_cert; + EVP_PKEY *current_pkey; + int key_bits; + int key_sec_bits; + int get_group_name; + const char *type_name; + + current_cert = sk_X509_value(certstack, cert_level); + + X509_get0_signature(NULL, &palg_cert, current_cert); + X509_ALGOR_get0(&paobj_cert, NULL, NULL, palg_cert); + OBJ_obj2txt(cert_algorithm, sizeof(cert_algorithm), paobj_cert, 0); + + current_pkey = X509_get0_pubkey(current_cert); + key_bits = EVP_PKEY_bits(current_pkey); +#if (OPENSSL_VERSION_NUMBER < 0x30000000L) +#define EVP_PKEY_get_security_bits EVP_PKEY_security_bits +#endif + key_sec_bits = EVP_PKEY_get_security_bits(current_pkey); +#if (OPENSSL_VERSION_NUMBER >= 0x30000000L) + { + char group_name[80] = ""; + get_group_name = EVP_PKEY_get_group_name(current_pkey, group_name, + sizeof(group_name), NULL); + msnprintf(group_name_final, sizeof(group_name_final), "/%s", group_name); + } + type_name = EVP_PKEY_get0_type_name(current_pkey); +#else + get_group_name = 0; + type_name = NULL; +#endif + + infof(data, + " Certificate level %d: " + "Public key type %s%s (%d/%d Bits/secBits), signed using %s", + cert_level, type_name ? type_name : "?", + get_group_name == 0 ? "" : group_name_final, + key_bits, key_sec_bits, cert_algorithm); + } +} +#else +#define infof_certstack(data, ssl) +#endif + +CURLcode Curl_oss_check_peer_cert(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ossl_ctx *octx, + struct ssl_peer *peer) +{ + struct connectdata *conn = cf->conn; + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + CURLcode result = CURLE_OK; + int rc; + long lerr; + X509 *issuer; + BIO *fp = NULL; + char error_buffer[256]=""; + char buffer[2048]; + const char *ptr; + BIO *mem = BIO_new(BIO_s_mem()); + bool strict = (conn_config->verifypeer || conn_config->verifyhost); + + DEBUGASSERT(octx); + + if(!mem) { + failf(data, + "BIO_new return NULL, " OSSL_PACKAGE + " error %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer)) ); + return CURLE_OUT_OF_MEMORY; + } + + if(data->set.ssl.certinfo) + /* asked to gather certificate info */ + (void)Curl_ossl_certchain(data, octx->ssl); + + octx->server_cert = SSL_get1_peer_certificate(octx->ssl); + if(!octx->server_cert) { + BIO_free(mem); + if(!strict) + return CURLE_OK; + + failf(data, "SSL: couldn't get peer certificate"); + return CURLE_PEER_FAILED_VERIFICATION; + } + + infof(data, "%s certificate:", + Curl_ssl_cf_is_proxy(cf)? "Proxy" : "Server"); + + rc = x509_name_oneline(X509_get_subject_name(octx->server_cert), + buffer, sizeof(buffer)); + infof(data, " subject: %s", rc?"[NONE]":buffer); + +#ifndef CURL_DISABLE_VERBOSE_STRINGS + { + long len; + ASN1_TIME_print(mem, X509_get0_notBefore(octx->server_cert)); + len = BIO_get_mem_data(mem, (char **) &ptr); + infof(data, " start date: %.*s", (int)len, ptr); + (void)BIO_reset(mem); + + ASN1_TIME_print(mem, X509_get0_notAfter(octx->server_cert)); + len = BIO_get_mem_data(mem, (char **) &ptr); + infof(data, " expire date: %.*s", (int)len, ptr); + (void)BIO_reset(mem); + } +#endif + + BIO_free(mem); + + if(conn_config->verifyhost) { + result = Curl_ossl_verifyhost(data, conn, peer, octx->server_cert); + if(result) { + X509_free(octx->server_cert); + octx->server_cert = NULL; + return result; + } + } + + rc = x509_name_oneline(X509_get_issuer_name(octx->server_cert), + buffer, sizeof(buffer)); + if(rc) { + if(strict) + failf(data, "SSL: couldn't get X509-issuer name"); + result = CURLE_PEER_FAILED_VERIFICATION; + } + else { + infof(data, " issuer: %s", buffer); + + /* We could do all sorts of certificate verification stuff here before + deallocating the certificate. */ + + /* e.g. match issuer name with provided issuer certificate */ + if(conn_config->issuercert || conn_config->issuercert_blob) { + if(conn_config->issuercert_blob) { + fp = BIO_new_mem_buf(conn_config->issuercert_blob->data, + (int)conn_config->issuercert_blob->len); + if(!fp) { + failf(data, + "BIO_new_mem_buf NULL, " OSSL_PACKAGE + " error %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer)) ); + X509_free(octx->server_cert); + octx->server_cert = NULL; + return CURLE_OUT_OF_MEMORY; + } + } + else { + fp = BIO_new(BIO_s_file()); + if(!fp) { + failf(data, + "BIO_new return NULL, " OSSL_PACKAGE + " error %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer)) ); + X509_free(octx->server_cert); + octx->server_cert = NULL; + return CURLE_OUT_OF_MEMORY; + } + + if(BIO_read_filename(fp, conn_config->issuercert) <= 0) { + if(strict) + failf(data, "SSL: Unable to open issuer cert (%s)", + conn_config->issuercert); + BIO_free(fp); + X509_free(octx->server_cert); + octx->server_cert = NULL; + return CURLE_SSL_ISSUER_ERROR; + } + } + + issuer = PEM_read_bio_X509(fp, NULL, ZERO_NULL, NULL); + if(!issuer) { + if(strict) + failf(data, "SSL: Unable to read issuer cert (%s)", + conn_config->issuercert); + BIO_free(fp); + X509_free(issuer); + X509_free(octx->server_cert); + octx->server_cert = NULL; + return CURLE_SSL_ISSUER_ERROR; + } + + if(X509_check_issued(issuer, octx->server_cert) != X509_V_OK) { + if(strict) + failf(data, "SSL: Certificate issuer check failed (%s)", + conn_config->issuercert); + BIO_free(fp); + X509_free(issuer); + X509_free(octx->server_cert); + octx->server_cert = NULL; + return CURLE_SSL_ISSUER_ERROR; + } + + infof(data, " SSL certificate issuer check ok (%s)", + conn_config->issuercert); + BIO_free(fp); + X509_free(issuer); + } + + lerr = SSL_get_verify_result(octx->ssl); + ssl_config->certverifyresult = lerr; + if(lerr != X509_V_OK) { + if(conn_config->verifypeer) { + /* We probably never reach this, because SSL_connect() will fail + and we return earlier if verifypeer is set? */ + if(strict) + failf(data, "SSL certificate verify result: %s (%ld)", + X509_verify_cert_error_string(lerr), lerr); + result = CURLE_PEER_FAILED_VERIFICATION; + } + else + infof(data, " SSL certificate verify result: %s (%ld)," + " continuing anyway.", + X509_verify_cert_error_string(lerr), lerr); + } + else + infof(data, " SSL certificate verify ok."); + } + + infof_certstack(data, octx->ssl); + +#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \ + !defined(OPENSSL_NO_OCSP) + if(conn_config->verifystatus && !octx->reused_session) { + /* don't do this after Session ID reuse */ + result = verifystatus(cf, data); + if(result) { + /* when verifystatus failed, remove the session id from the cache again + if present */ + if(!Curl_ssl_cf_is_proxy(cf)) { + void *old_ssl_sessionid = NULL; + bool incache; + Curl_ssl_sessionid_lock(data); + incache = !(Curl_ssl_getsessionid(cf, data, peer, + &old_ssl_sessionid, NULL)); + if(incache) { + infof(data, "Remove session ID again from cache"); + Curl_ssl_delsessionid(data, old_ssl_sessionid); + } + Curl_ssl_sessionid_unlock(data); + } + + X509_free(octx->server_cert); + octx->server_cert = NULL; + return result; + } + } +#endif + + if(!strict) + /* when not strict, we don't bother about the verify cert problems */ + result = CURLE_OK; + +#ifndef CURL_DISABLE_PROXY + ptr = Curl_ssl_cf_is_proxy(cf)? + data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY]: + data->set.str[STRING_SSL_PINNEDPUBLICKEY]; +#else + ptr = data->set.str[STRING_SSL_PINNEDPUBLICKEY]; +#endif + if(!result && ptr) { + result = ossl_pkp_pin_peer_pubkey(data, octx->server_cert, ptr); + if(result) + failf(data, "SSL: public key does not match pinned public key"); + } + + X509_free(octx->server_cert); + octx->server_cert = NULL; + + return result; +} + +static CURLcode ossl_connect_step3(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + + DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); + + /* + * We check certificates to authenticate the server; otherwise we risk + * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to + * verify the peer, ignore faults and failures from the server cert + * operations. + */ + + result = Curl_oss_check_peer_cert(cf, data, octx, &connssl->peer); + if(!result) + connssl->connecting_state = ssl_connect_done; + + return result; +} + +static CURLcode ossl_connect_common(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool nonblocking, + bool *done) +{ + CURLcode result = CURLE_OK; + struct ssl_connect_data *connssl = cf->ctx; + curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data); + int what; + + /* check if the connection has already been established */ + if(ssl_connection_complete == connssl->state) { + *done = TRUE; + return CURLE_OK; + } + + if(ssl_connect_1 == connssl->connecting_state) { + /* Find out how much more time we're allowed */ + const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE); + + if(timeout_ms < 0) { + /* no need to continue if time is already up */ + failf(data, "SSL connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + + result = ossl_connect_step1(cf, data); + if(result) + goto out; + } + + while(ssl_connect_2 == connssl->connecting_state || + ssl_connect_2_reading == connssl->connecting_state || + ssl_connect_2_writing == connssl->connecting_state) { + + /* check allowed time left */ + const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE); + + if(timeout_ms < 0) { + /* no need to continue if time already is up */ + failf(data, "SSL connection timeout"); + result = CURLE_OPERATION_TIMEDOUT; + goto out; + } + + /* if ssl is expecting something, check if it's available. */ + if(!nonblocking && + (connssl->connecting_state == ssl_connect_2_reading || + connssl->connecting_state == ssl_connect_2_writing)) { + + curl_socket_t writefd = ssl_connect_2_writing == + connssl->connecting_state?sockfd:CURL_SOCKET_BAD; + curl_socket_t readfd = ssl_connect_2_reading == + connssl->connecting_state?sockfd:CURL_SOCKET_BAD; + + what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, + timeout_ms); + if(what < 0) { + /* fatal error */ + failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + if(0 == what) { + /* timeout */ + failf(data, "SSL connection timeout"); + result = CURLE_OPERATION_TIMEDOUT; + goto out; + } + /* socket is readable or writable */ + } + + /* Run transaction, and return to the caller if it failed or if this + * connection is done nonblocking and this loop would execute again. This + * permits the owner of a multi handle to abort a connection attempt + * before step2 has completed while ensuring that a client using select() + * or epoll() will always have a valid fdset to wait on. + */ + result = ossl_connect_step2(cf, data); + if(result || (nonblocking && + (ssl_connect_2 == connssl->connecting_state || + ssl_connect_2_reading == connssl->connecting_state || + ssl_connect_2_writing == connssl->connecting_state))) + goto out; + + } /* repeat step2 until all transactions are done. */ + + if(ssl_connect_3 == connssl->connecting_state) { + result = ossl_connect_step3(cf, data); + if(result) + goto out; + } + + if(ssl_connect_done == connssl->connecting_state) { + connssl->state = ssl_connection_complete; + *done = TRUE; + } + else + *done = FALSE; + + /* Reset our connect state machine */ + connssl->connecting_state = ssl_connect_1; + +out: + return result; +} + +static CURLcode ossl_connect_nonblocking(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + return ossl_connect_common(cf, data, TRUE, done); +} + +static CURLcode ossl_connect(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURLcode result; + bool done = FALSE; + + result = ossl_connect_common(cf, data, FALSE, &done); + if(result) + return result; + + DEBUGASSERT(done); + + return CURLE_OK; +} + +static bool ossl_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + + (void)data; + DEBUGASSERT(connssl && octx); + if(octx->ssl && SSL_pending(octx->ssl)) + return TRUE; + return FALSE; +} + +static ssize_t ossl_send(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *mem, + size_t len, + CURLcode *curlcode) +{ + /* SSL_write() is said to return 'int' while write() and send() returns + 'size_t' */ + int err; + char error_buffer[256]; + sslerr_t sslerror; + int memlen; + int rc; + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + + (void)data; + DEBUGASSERT(octx); + + ERR_clear_error(); + + memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len; + rc = SSL_write(octx->ssl, mem, memlen); + + if(rc <= 0) { + err = SSL_get_error(octx->ssl, rc); + + switch(err) { + case SSL_ERROR_WANT_READ: + case SSL_ERROR_WANT_WRITE: + /* The operation did not complete; the same TLS/SSL I/O function + should be called again later. This is basically an EWOULDBLOCK + equivalent. */ + *curlcode = CURLE_AGAIN; + rc = -1; + goto out; + case SSL_ERROR_SYSCALL: + { + int sockerr = SOCKERRNO; + + if(octx->io_result == CURLE_AGAIN) { + *curlcode = CURLE_AGAIN; + rc = -1; + goto out; + } + sslerror = ERR_get_error(); + if(sslerror) + ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)); + else if(sockerr) + Curl_strerror(sockerr, error_buffer, sizeof(error_buffer)); + else + msnprintf(error_buffer, sizeof(error_buffer), "%s", + SSL_ERROR_to_str(err)); + + failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d", + error_buffer, sockerr); + *curlcode = CURLE_SEND_ERROR; + rc = -1; + goto out; + } + case SSL_ERROR_SSL: { + /* A failure in the SSL library occurred, usually a protocol error. + The OpenSSL error queue contains more information on the error. */ + sslerror = ERR_get_error(); + failf(data, "SSL_write() error: %s", + ossl_strerror(sslerror, error_buffer, sizeof(error_buffer))); + *curlcode = CURLE_SEND_ERROR; + rc = -1; + goto out; + } + default: + /* a true error */ + failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d", + SSL_ERROR_to_str(err), SOCKERRNO); + *curlcode = CURLE_SEND_ERROR; + rc = -1; + goto out; + } + } + *curlcode = CURLE_OK; + +out: + return (ssize_t)rc; /* number of bytes */ +} + +static ssize_t ossl_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, /* transfer */ + char *buf, /* store read data here */ + size_t buffersize, /* max amount to read */ + CURLcode *curlcode) +{ + char error_buffer[256]; + unsigned long sslerror; + ssize_t nread; + int buffsize; + struct connectdata *conn = cf->conn; + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + + (void)data; + DEBUGASSERT(octx); + + ERR_clear_error(); + + buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize; + nread = (ssize_t)SSL_read(octx->ssl, buf, buffsize); + + if(nread <= 0) { + /* failed SSL_read */ + int err = SSL_get_error(octx->ssl, (int)nread); + + switch(err) { + case SSL_ERROR_NONE: /* this is not an error */ + break; + case SSL_ERROR_ZERO_RETURN: /* no more data */ + /* close_notify alert */ + if(cf->sockindex == FIRSTSOCKET) + /* mark the connection for close if it is indeed the control + connection */ + connclose(conn, "TLS close_notify"); + break; + case SSL_ERROR_WANT_READ: + case SSL_ERROR_WANT_WRITE: + /* there's data pending, re-invoke SSL_read() */ + *curlcode = CURLE_AGAIN; + nread = -1; + goto out; + default: + /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return + value/errno" */ + /* https://www.openssl.org/docs/crypto/ERR_get_error.html */ + if(octx->io_result == CURLE_AGAIN) { + *curlcode = CURLE_AGAIN; + nread = -1; + goto out; + } + sslerror = ERR_get_error(); + if((nread < 0) || sslerror) { + /* If the return code was negative or there actually is an error in the + queue */ + int sockerr = SOCKERRNO; + if(sslerror) + ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)); + else if(sockerr && err == SSL_ERROR_SYSCALL) + Curl_strerror(sockerr, error_buffer, sizeof(error_buffer)); + else + msnprintf(error_buffer, sizeof(error_buffer), "%s", + SSL_ERROR_to_str(err)); + failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d", + error_buffer, sockerr); + *curlcode = CURLE_RECV_ERROR; + nread = -1; + goto out; + } + /* For debug builds be a little stricter and error on any + SSL_ERROR_SYSCALL. For example a server may have closed the connection + abruptly without a close_notify alert. For compatibility with older + peers we don't do this by default. #4624 + + We can use this to gauge how many users may be affected, and + if it goes ok eventually transition to allow in dev and release with + the newest OpenSSL: #if (OPENSSL_VERSION_NUMBER >= 0x10101000L) */ +#ifdef DEBUGBUILD + if(err == SSL_ERROR_SYSCALL) { + int sockerr = SOCKERRNO; + if(sockerr) + Curl_strerror(sockerr, error_buffer, sizeof(error_buffer)); + else { + msnprintf(error_buffer, sizeof(error_buffer), + "Connection closed abruptly"); + } + failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d" + " (Fatal because this is a curl debug build)", + error_buffer, sockerr); + *curlcode = CURLE_RECV_ERROR; + nread = -1; + goto out; + } +#endif + } + } + +out: + return nread; +} + +static size_t ossl_version(char *buffer, size_t size) +{ +#ifdef LIBRESSL_VERSION_NUMBER +#ifdef HAVE_OPENSSL_VERSION + char *p; + int count; + const char *ver = OpenSSL_version(OPENSSL_VERSION); + const char expected[] = OSSL_PACKAGE " "; /* ie "LibreSSL " */ + if(strncasecompare(ver, expected, sizeof(expected) - 1)) { + ver += sizeof(expected) - 1; + } + count = msnprintf(buffer, size, "%s/%s", OSSL_PACKAGE, ver); + for(p = buffer; *p; ++p) { + if(ISBLANK(*p)) + *p = '_'; + } + return count; +#else + return msnprintf(buffer, size, "%s/%lx.%lx.%lx", + OSSL_PACKAGE, + (LIBRESSL_VERSION_NUMBER>>28)&0xf, + (LIBRESSL_VERSION_NUMBER>>20)&0xff, + (LIBRESSL_VERSION_NUMBER>>12)&0xff); +#endif +#elif defined(OPENSSL_IS_BORINGSSL) +#ifdef CURL_BORINGSSL_VERSION + return msnprintf(buffer, size, "%s/%s", + OSSL_PACKAGE, + CURL_BORINGSSL_VERSION); +#else + return msnprintf(buffer, size, OSSL_PACKAGE); +#endif +#elif defined(OPENSSL_IS_AWSLC) + return msnprintf(buffer, size, "%s/%s", + OSSL_PACKAGE, + AWSLC_VERSION_NUMBER_STRING); +#elif defined(HAVE_OPENSSL_VERSION) && defined(OPENSSL_VERSION_STRING) + return msnprintf(buffer, size, "%s/%s", + OSSL_PACKAGE, OpenSSL_version(OPENSSL_VERSION_STRING)); +#else + /* not LibreSSL, BoringSSL and not using OpenSSL_version */ + + char sub[3]; + unsigned long ssleay_value; + sub[2]='\0'; + sub[1]='\0'; + ssleay_value = OpenSSL_version_num(); + if(ssleay_value < 0x906000) { + ssleay_value = SSLEAY_VERSION_NUMBER; + sub[0]='\0'; + } + else { + if(ssleay_value&0xff0) { + int minor_ver = (ssleay_value >> 4) & 0xff; + if(minor_ver > 26) { + /* handle extended version introduced for 0.9.8za */ + sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1); + sub[0] = 'z'; + } + else { + sub[0] = (char) (minor_ver + 'a' - 1); + } + } + else + sub[0]='\0'; + } + + return msnprintf(buffer, size, "%s/%lx.%lx.%lx%s" +#ifdef OPENSSL_FIPS + "-fips" +#endif + , + OSSL_PACKAGE, + (ssleay_value>>28)&0xf, + (ssleay_value>>20)&0xff, + (ssleay_value>>12)&0xff, + sub); +#endif /* OPENSSL_IS_BORINGSSL */ +} + +/* can be called with data == NULL */ +static CURLcode ossl_random(struct Curl_easy *data, + unsigned char *entropy, size_t length) +{ + int rc; + if(data) { + if(ossl_seed(data)) /* Initiate the seed if not already done */ + return CURLE_FAILED_INIT; /* couldn't seed for some reason */ + } + else { + if(!rand_enough()) + return CURLE_FAILED_INIT; + } + /* RAND_bytes() returns 1 on success, 0 otherwise. */ + rc = RAND_bytes(entropy, curlx_uztosi(length)); + return (rc == 1 ? CURLE_OK : CURLE_FAILED_INIT); +} + +#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256) +static CURLcode ossl_sha256sum(const unsigned char *tmp, /* input */ + size_t tmplen, + unsigned char *sha256sum /* output */, + size_t unused) +{ + EVP_MD_CTX *mdctx; + unsigned int len = 0; + (void) unused; + + mdctx = EVP_MD_CTX_create(); + if(!mdctx) + return CURLE_OUT_OF_MEMORY; + if(!EVP_DigestInit(mdctx, EVP_sha256())) { + EVP_MD_CTX_destroy(mdctx); + return CURLE_FAILED_INIT; + } + EVP_DigestUpdate(mdctx, tmp, tmplen); + EVP_DigestFinal_ex(mdctx, sha256sum, &len); + EVP_MD_CTX_destroy(mdctx); + return CURLE_OK; +} +#endif + +static bool ossl_cert_status_request(void) +{ +#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \ + !defined(OPENSSL_NO_OCSP) + return TRUE; +#else + return FALSE; +#endif +} + +static void *ossl_get_internals(struct ssl_connect_data *connssl, + CURLINFO info) +{ + /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */ + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + DEBUGASSERT(octx); + return info == CURLINFO_TLS_SESSION ? + (void *)octx->ssl_ctx : (void *)octx->ssl; +} + +static void ossl_free_multi_ssl_backend_data( + struct multi_ssl_backend_data *mbackend) +{ +#if defined(HAVE_SSL_X509_STORE_SHARE) + if(mbackend->store) { + X509_STORE_free(mbackend->store); + } + free(mbackend->CAfile); + free(mbackend); +#else /* HAVE_SSL_X509_STORE_SHARE */ + (void)mbackend; +#endif /* HAVE_SSL_X509_STORE_SHARE */ +} + +const struct Curl_ssl Curl_ssl_openssl = { + { CURLSSLBACKEND_OPENSSL, "openssl" }, /* info */ + + SSLSUPP_CA_PATH | + SSLSUPP_CAINFO_BLOB | + SSLSUPP_CERTINFO | + SSLSUPP_PINNEDPUBKEY | + SSLSUPP_SSL_CTX | +#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES + SSLSUPP_TLS13_CIPHERSUITES | +#endif +#ifdef USE_ECH + SSLSUPP_ECH | +#endif + SSLSUPP_HTTPS_PROXY, + + sizeof(struct ossl_ctx), + + ossl_init, /* init */ + ossl_cleanup, /* cleanup */ + ossl_version, /* version */ + Curl_none_check_cxn, /* check_cxn */ + ossl_shutdown, /* shutdown */ + ossl_data_pending, /* data_pending */ + ossl_random, /* random */ + ossl_cert_status_request, /* cert_status_request */ + ossl_connect, /* connect */ + ossl_connect_nonblocking, /* connect_nonblocking */ + Curl_ssl_adjust_pollset, /* adjust_pollset */ + ossl_get_internals, /* get_internals */ + ossl_close, /* close_one */ + ossl_close_all, /* close_all */ + ossl_set_engine, /* set_engine */ + ossl_set_engine_default, /* set_engine_default */ + ossl_engines_list, /* engines_list */ + Curl_none_false_start, /* false_start */ +#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256) + ossl_sha256sum, /* sha256sum */ +#else + NULL, /* sha256sum */ +#endif + NULL, /* use of data in this connection */ + NULL, /* remote of data from this connection */ + ossl_free_multi_ssl_backend_data, /* free_multi_ssl_backend_data */ + ossl_recv, /* recv decrypted data */ + ossl_send, /* send data to encrypt */ +}; + +#endif /* USE_OPENSSL */ diff --git a/third_party/curl/lib/vtls/openssl.h b/third_party/curl/lib/vtls/openssl.h new file mode 100644 index 0000000..55e06bd --- /dev/null +++ b/third_party/curl/lib/vtls/openssl.h @@ -0,0 +1,121 @@ +#ifndef HEADER_CURL_SSLUSE_H +#define HEADER_CURL_SSLUSE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_OPENSSL +/* + * This header should only be needed to get included by vtls.c, openssl.c + * and ngtcp2.c + */ +#include +#include + +#include "urldata.h" + +/* Struct to hold a Curl OpenSSL instance */ +struct ossl_ctx { + /* these ones requires specific SSL-types */ + SSL_CTX* ssl_ctx; + SSL* ssl; + X509* server_cert; + BIO_METHOD *bio_method; + CURLcode io_result; /* result of last BIO cfilter operation */ +#ifndef HAVE_KEYLOG_CALLBACK + /* Set to true once a valid keylog entry has been created to avoid dupes. */ + BIT(keylog_done); +#endif + BIT(x509_store_setup); /* x509 store has been set up */ + BIT(reused_session); /* session-ID was reused for this */ +}; + +typedef CURLcode Curl_ossl_ctx_setup_cb(struct Curl_cfilter *cf, + struct Curl_easy *data, + void *user_data); + +typedef int Curl_ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid); + +CURLcode Curl_ossl_ctx_init(struct ossl_ctx *octx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + int transport, /* TCP or QUIC */ + const unsigned char *alpn, size_t alpn_len, + Curl_ossl_ctx_setup_cb *cb_setup, + void *cb_user_data, + Curl_ossl_new_session_cb *cb_new_session, + void *ssl_user_data); + +#if (OPENSSL_VERSION_NUMBER < 0x30000000L) +#define SSL_get1_peer_certificate SSL_get_peer_certificate +#endif + +CURLcode Curl_ossl_verifyhost(struct Curl_easy *data, struct connectdata *conn, + struct ssl_peer *peer, X509 *server_cert); +extern const struct Curl_ssl Curl_ssl_openssl; + +CURLcode Curl_ossl_set_client_cert(struct Curl_easy *data, + SSL_CTX *ctx, char *cert_file, + const struct curl_blob *cert_blob, + const char *cert_type, char *key_file, + const struct curl_blob *key_blob, + const char *key_type, char *key_passwd); + +CURLcode Curl_ossl_certchain(struct Curl_easy *data, SSL *ssl); + +/** + * Setup the OpenSSL X509_STORE in `ssl_ctx` for the cfilter `cf` and + * easy handle `data`. Will allow reuse of a shared cache if suitable + * and configured. + */ +CURLcode Curl_ssl_setup_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + SSL_CTX *ssl_ctx); + +CURLcode Curl_ossl_ctx_configure(struct Curl_cfilter *cf, + struct Curl_easy *data, + SSL_CTX *ssl_ctx); + +/* + * Add a new session to the cache. Takes ownership of the session. + */ +CURLcode Curl_ossl_add_session(struct Curl_cfilter *cf, + struct Curl_easy *data, + const struct ssl_peer *peer, + SSL_SESSION *ssl_sessionid); + +/* + * Get the server cert, verify it and show it, etc., only call failf() if + * ssl config verifypeer or -host is set. Otherwise all this is for + * informational purposes only! + */ +CURLcode Curl_oss_check_peer_cert(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ossl_ctx *octx, + struct ssl_peer *peer); + +#endif /* USE_OPENSSL */ +#endif /* HEADER_CURL_SSLUSE_H */ diff --git a/third_party/curl/lib/vtls/rustls.c b/third_party/curl/lib/vtls/rustls.c new file mode 100644 index 0000000..8b6588a --- /dev/null +++ b/third_party/curl/lib/vtls/rustls.c @@ -0,0 +1,791 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Jacob Hoffman-Andrews, + * + * Copyright (C) kpcyrd, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_RUSTLS + +#include "curl_printf.h" + +#include +#include + +#include "inet_pton.h" +#include "urldata.h" +#include "sendf.h" +#include "vtls.h" +#include "vtls_int.h" +#include "select.h" +#include "strerror.h" +#include "multiif.h" +#include "connect.h" /* for the connect timeout */ + +struct rustls_ssl_backend_data +{ + const struct rustls_client_config *config; + struct rustls_connection *conn; + size_t plain_out_buffered; + BIT(data_in_pending); +}; + +/* For a given rustls_result error code, return the best-matching CURLcode. */ +static CURLcode map_error(rustls_result r) +{ + if(rustls_result_is_cert_error(r)) { + return CURLE_PEER_FAILED_VERIFICATION; + } + switch(r) { + case RUSTLS_RESULT_OK: + return CURLE_OK; + case RUSTLS_RESULT_NULL_PARAMETER: + return CURLE_BAD_FUNCTION_ARGUMENT; + default: + return CURLE_RECV_ERROR; + } +} + +static bool +cr_data_pending(struct Curl_cfilter *cf, const struct Curl_easy *data) +{ + struct ssl_connect_data *ctx = cf->ctx; + struct rustls_ssl_backend_data *backend; + + (void)data; + DEBUGASSERT(ctx && ctx->backend); + backend = (struct rustls_ssl_backend_data *)ctx->backend; + return backend->data_in_pending; +} + +struct io_ctx { + struct Curl_cfilter *cf; + struct Curl_easy *data; +}; + +static int +read_cb(void *userdata, uint8_t *buf, uintptr_t len, uintptr_t *out_n) +{ + struct io_ctx *io_ctx = userdata; + struct ssl_connect_data *const connssl = io_ctx->cf->ctx; + CURLcode result; + int ret = 0; + ssize_t nread = Curl_conn_cf_recv(io_ctx->cf->next, io_ctx->data, + (char *)buf, len, &result); + if(nread < 0) { + nread = 0; + if(CURLE_AGAIN == result) + ret = EAGAIN; + else + ret = EINVAL; + } + else if(nread == 0) + connssl->peer_closed = TRUE; + *out_n = (int)nread; + CURL_TRC_CF(io_ctx->data, io_ctx->cf, "cf->next recv(len=%zu) -> %zd, %d", + len, nread, result); + return ret; +} + +static int +write_cb(void *userdata, const uint8_t *buf, uintptr_t len, uintptr_t *out_n) +{ + struct io_ctx *io_ctx = userdata; + CURLcode result; + int ret = 0; + ssize_t nwritten = Curl_conn_cf_send(io_ctx->cf->next, io_ctx->data, + (const char *)buf, len, &result); + if(nwritten < 0) { + nwritten = 0; + if(CURLE_AGAIN == result) + ret = EAGAIN; + else + ret = EINVAL; + } + *out_n = (int)nwritten; + CURL_TRC_CF(io_ctx->data, io_ctx->cf, "cf->next send(len=%zu) -> %zd, %d", + len, nwritten, result); + return ret; +} + +static ssize_t tls_recv_more(struct Curl_cfilter *cf, + struct Curl_easy *data, CURLcode *err) +{ + struct ssl_connect_data *const connssl = cf->ctx; + struct rustls_ssl_backend_data *const backend = + (struct rustls_ssl_backend_data *)connssl->backend; + struct io_ctx io_ctx; + size_t tls_bytes_read = 0; + rustls_io_result io_error; + rustls_result rresult = 0; + + io_ctx.cf = cf; + io_ctx.data = data; + io_error = rustls_connection_read_tls(backend->conn, read_cb, &io_ctx, + &tls_bytes_read); + if(io_error == EAGAIN || io_error == EWOULDBLOCK) { + *err = CURLE_AGAIN; + return -1; + } + else if(io_error) { + char buffer[STRERROR_LEN]; + failf(data, "reading from socket: %s", + Curl_strerror(io_error, buffer, sizeof(buffer))); + *err = CURLE_RECV_ERROR; + return -1; + } + + rresult = rustls_connection_process_new_packets(backend->conn); + if(rresult != RUSTLS_RESULT_OK) { + char errorbuf[255]; + size_t errorlen; + rustls_error(rresult, errorbuf, sizeof(errorbuf), &errorlen); + failf(data, "rustls_connection_process_new_packets: %.*s", + (int)errorlen, errorbuf); + *err = map_error(rresult); + return -1; + } + + backend->data_in_pending = TRUE; + *err = CURLE_OK; + return (ssize_t)tls_bytes_read; +} + +/* + * On each run: + * - Read a chunk of bytes from the socket into rustls' TLS input buffer. + * - Tell rustls to process any new packets. + * - Read out as many plaintext bytes from rustls as possible, until hitting + * error, EOF, or EAGAIN/EWOULDBLOCK, or plainbuf/plainlen is filled up. + * + * It's okay to call this function with plainbuf == NULL and plainlen == 0. + * In that case, it will copy bytes from the socket into rustls' TLS input + * buffer, and process packets, but won't consume bytes from rustls' plaintext + * output buffer. + */ +static ssize_t +cr_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *plainbuf, size_t plainlen, CURLcode *err) +{ + struct ssl_connect_data *const connssl = cf->ctx; + struct rustls_ssl_backend_data *const backend = + (struct rustls_ssl_backend_data *)connssl->backend; + struct rustls_connection *rconn = NULL; + size_t n = 0; + size_t plain_bytes_copied = 0; + rustls_result rresult = 0; + ssize_t nread; + bool eof = FALSE; + + DEBUGASSERT(backend); + rconn = backend->conn; + + while(plain_bytes_copied < plainlen) { + if(!backend->data_in_pending) { + if(tls_recv_more(cf, data, err) < 0) { + if(*err != CURLE_AGAIN) { + nread = -1; + goto out; + } + break; + } + } + + rresult = rustls_connection_read(rconn, + (uint8_t *)plainbuf + plain_bytes_copied, + plainlen - plain_bytes_copied, + &n); + if(rresult == RUSTLS_RESULT_PLAINTEXT_EMPTY) { + backend->data_in_pending = FALSE; + } + else if(rresult == RUSTLS_RESULT_UNEXPECTED_EOF) { + failf(data, "rustls: peer closed TCP connection " + "without first closing TLS connection"); + *err = CURLE_RECV_ERROR; + nread = -1; + goto out; + } + else if(rresult != RUSTLS_RESULT_OK) { + /* n always equals 0 in this case, don't need to check it */ + char errorbuf[255]; + size_t errorlen; + rustls_error(rresult, errorbuf, sizeof(errorbuf), &errorlen); + failf(data, "rustls_connection_read: %.*s", (int)errorlen, errorbuf); + *err = CURLE_RECV_ERROR; + nread = -1; + goto out; + } + else if(n == 0) { + /* n == 0 indicates clean EOF, but we may have read some other + plaintext bytes before we reached this. Break out of the loop + so we can figure out whether to return success or EOF. */ + eof = TRUE; + break; + } + else { + plain_bytes_copied += n; + } + } + + if(plain_bytes_copied) { + *err = CURLE_OK; + nread = (ssize_t)plain_bytes_copied; + } + else if(eof) { + *err = CURLE_OK; + nread = 0; + } + else { + *err = CURLE_AGAIN; + nread = -1; + } + +out: + CURL_TRC_CF(data, cf, "cf_recv(len=%zu) -> %zd, %d", + plainlen, nread, *err); + return nread; +} + +static CURLcode cr_flush_out(struct Curl_cfilter *cf, struct Curl_easy *data, + struct rustls_connection *rconn) +{ + struct io_ctx io_ctx; + rustls_io_result io_error; + size_t tlswritten = 0; + size_t tlswritten_total = 0; + CURLcode result = CURLE_OK; + + io_ctx.cf = cf; + io_ctx.data = data; + + while(rustls_connection_wants_write(rconn)) { + io_error = rustls_connection_write_tls(rconn, write_cb, &io_ctx, + &tlswritten); + if(io_error == EAGAIN || io_error == EWOULDBLOCK) { + CURL_TRC_CF(data, cf, "cf_send: EAGAIN after %zu bytes", + tlswritten_total); + return CURLE_AGAIN; + } + else if(io_error) { + char buffer[STRERROR_LEN]; + failf(data, "writing to socket: %s", + Curl_strerror(io_error, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + if(tlswritten == 0) { + failf(data, "EOF in swrite"); + return CURLE_SEND_ERROR; + } + CURL_TRC_CF(data, cf, "cf_send: wrote %zu TLS bytes", tlswritten); + tlswritten_total += tlswritten; + } + return result; +} + +/* + * On each call: + * - Copy `plainlen` bytes into rustls' plaintext input buffer (if > 0). + * - Fully drain rustls' plaintext output buffer into the socket until + * we get either an error or EAGAIN/EWOULDBLOCK. + * + * It's okay to call this function with plainbuf == NULL and plainlen == 0. + * In that case, it won't read anything into rustls' plaintext input buffer. + * It will only drain rustls' plaintext output buffer into the socket. + */ +static ssize_t +cr_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *plainbuf, size_t plainlen, CURLcode *err) +{ + struct ssl_connect_data *const connssl = cf->ctx; + struct rustls_ssl_backend_data *const backend = + (struct rustls_ssl_backend_data *)connssl->backend; + struct rustls_connection *rconn = NULL; + size_t plainwritten = 0; + rustls_result rresult; + char errorbuf[256]; + size_t errorlen; + const unsigned char *buf = plainbuf; + size_t blen = plainlen; + ssize_t nwritten = 0; + + DEBUGASSERT(backend); + rconn = backend->conn; + DEBUGASSERT(rconn); + + CURL_TRC_CF(data, cf, "cf_send(len=%zu)", plainlen); + + /* If a previous send blocked, we already added its plain bytes + * to rustsls and must not do that again. Flush the TLS bytes and, + * if successful, deduct the previous plain bytes from the current + * send. */ + if(backend->plain_out_buffered) { + *err = cr_flush_out(cf, data, rconn); + CURL_TRC_CF(data, cf, "cf_send: flushing %zu previously added bytes -> %d", + backend->plain_out_buffered, *err); + if(*err) + return -1; + if(blen > backend->plain_out_buffered) { + blen -= backend->plain_out_buffered; + buf += backend->plain_out_buffered; + } + else + blen = 0; + nwritten += (ssize_t)backend->plain_out_buffered; + backend->plain_out_buffered = 0; + } + + if(blen > 0) { + CURL_TRC_CF(data, cf, "cf_send: adding %zu plain bytes to rustls", blen); + rresult = rustls_connection_write(rconn, buf, blen, &plainwritten); + if(rresult != RUSTLS_RESULT_OK) { + rustls_error(rresult, errorbuf, sizeof(errorbuf), &errorlen); + failf(data, "rustls_connection_write: %.*s", (int)errorlen, errorbuf); + *err = CURLE_WRITE_ERROR; + return -1; + } + else if(plainwritten == 0) { + failf(data, "rustls_connection_write: EOF"); + *err = CURLE_WRITE_ERROR; + return -1; + } + } + + *err = cr_flush_out(cf, data, rconn); + if(*err) { + if(CURLE_AGAIN == *err) { + /* The TLS bytes may have been partially written, but we fail the + * complete send() and remember how much we already added to rustls. */ + CURL_TRC_CF(data, cf, "cf_send: EAGAIN, remember we added %zu plain" + " bytes already to rustls", blen); + backend->plain_out_buffered = plainwritten; + if(nwritten) { + *err = CURLE_OK; + return (ssize_t)nwritten; + } + } + return -1; + } + else + nwritten += (ssize_t)plainwritten; + + CURL_TRC_CF(data, cf, "cf_send(len=%zu) -> %d, %zd", + plainlen, *err, nwritten); + return nwritten; +} + +/* A server certificate verify callback for rustls that always returns + RUSTLS_RESULT_OK, or in other words disable certificate verification. */ +static uint32_t +cr_verify_none(void *userdata UNUSED_PARAM, + const rustls_verify_server_cert_params *params UNUSED_PARAM) +{ + return RUSTLS_RESULT_OK; +} + +static bool +cr_hostname_is_ip(const char *hostname) +{ + struct in_addr in; +#ifdef USE_IPV6 + struct in6_addr in6; + if(Curl_inet_pton(AF_INET6, hostname, &in6) > 0) { + return true; + } +#endif /* USE_IPV6 */ + if(Curl_inet_pton(AF_INET, hostname, &in) > 0) { + return true; + } + return false; +} + +static CURLcode +cr_init_backend(struct Curl_cfilter *cf, struct Curl_easy *data, + struct rustls_ssl_backend_data *const backend) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct rustls_connection *rconn = NULL; + struct rustls_client_config_builder *config_builder = NULL; + const struct rustls_root_cert_store *roots = NULL; + struct rustls_root_cert_store_builder *roots_builder = NULL; + struct rustls_web_pki_server_cert_verifier_builder *verifier_builder = NULL; + struct rustls_server_cert_verifier *server_cert_verifier = NULL; + const struct curl_blob *ca_info_blob = conn_config->ca_info_blob; + const char * const ssl_cafile = + /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */ + (ca_info_blob ? NULL : conn_config->CAfile); + const bool verifypeer = conn_config->verifypeer; + const char *hostname = connssl->peer.hostname; + char errorbuf[256]; + size_t errorlen; + int result; + + DEBUGASSERT(backend); + rconn = backend->conn; + + config_builder = rustls_client_config_builder_new(); + if(connssl->alpn) { + struct alpn_proto_buf proto; + rustls_slice_bytes alpn[ALPN_ENTRIES_MAX]; + size_t i; + + for(i = 0; i < connssl->alpn->count; ++i) { + alpn[i].data = (const uint8_t *)connssl->alpn->entries[i]; + alpn[i].len = strlen(connssl->alpn->entries[i]); + } + rustls_client_config_builder_set_alpn_protocols(config_builder, alpn, + connssl->alpn->count); + Curl_alpn_to_proto_str(&proto, connssl->alpn); + infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data); + } + if(!verifypeer) { + rustls_client_config_builder_dangerous_set_certificate_verifier( + config_builder, cr_verify_none); + /* rustls doesn't support IP addresses (as of 0.19.0), and will reject + * connections created with an IP address, even when certificate + * verification is turned off. Set a placeholder hostname and disable + * SNI. */ + if(cr_hostname_is_ip(hostname)) { + rustls_client_config_builder_set_enable_sni(config_builder, false); + hostname = "example.invalid"; + } + } + else if(ca_info_blob || ssl_cafile) { + roots_builder = rustls_root_cert_store_builder_new(); + + if(ca_info_blob) { + /* Enable strict parsing only if verification isn't disabled. */ + result = rustls_root_cert_store_builder_add_pem(roots_builder, + ca_info_blob->data, + ca_info_blob->len, + verifypeer); + if(result != RUSTLS_RESULT_OK) { + failf(data, "rustls: failed to parse trusted certificates from blob"); + rustls_root_cert_store_builder_free(roots_builder); + rustls_client_config_free( + rustls_client_config_builder_build(config_builder)); + return CURLE_SSL_CACERT_BADFILE; + } + } + else if(ssl_cafile) { + /* Enable strict parsing only if verification isn't disabled. */ + result = rustls_root_cert_store_builder_load_roots_from_file( + roots_builder, ssl_cafile, verifypeer); + if(result != RUSTLS_RESULT_OK) { + failf(data, "rustls: failed to load trusted certificates"); + rustls_root_cert_store_builder_free(roots_builder); + rustls_client_config_free( + rustls_client_config_builder_build(config_builder)); + return CURLE_SSL_CACERT_BADFILE; + } + } + + result = rustls_root_cert_store_builder_build(roots_builder, &roots); + rustls_root_cert_store_builder_free(roots_builder); + if(result != RUSTLS_RESULT_OK) { + failf(data, "rustls: failed to load trusted certificates"); + rustls_client_config_free( + rustls_client_config_builder_build(config_builder)); + return CURLE_SSL_CACERT_BADFILE; + } + + verifier_builder = rustls_web_pki_server_cert_verifier_builder_new(roots); + + result = rustls_web_pki_server_cert_verifier_builder_build( + verifier_builder, &server_cert_verifier); + rustls_web_pki_server_cert_verifier_builder_free(verifier_builder); + if(result != RUSTLS_RESULT_OK) { + failf(data, "rustls: failed to load trusted certificates"); + rustls_server_cert_verifier_free(server_cert_verifier); + rustls_client_config_free( + rustls_client_config_builder_build(config_builder)); + return CURLE_SSL_CACERT_BADFILE; + } + + rustls_client_config_builder_set_server_verifier(config_builder, + server_cert_verifier); + } + + backend->config = rustls_client_config_builder_build(config_builder); + DEBUGASSERT(rconn == NULL); + result = rustls_client_connection_new(backend->config, + connssl->peer.hostname, &rconn); + if(result != RUSTLS_RESULT_OK) { + rustls_error(result, errorbuf, sizeof(errorbuf), &errorlen); + failf(data, "rustls_client_connection_new: %.*s", (int)errorlen, errorbuf); + return CURLE_COULDNT_CONNECT; + } + DEBUGASSERT(rconn); + rustls_connection_set_userdata(rconn, backend); + backend->conn = rconn; + return CURLE_OK; +} + +static void +cr_set_negotiated_alpn(struct Curl_cfilter *cf, struct Curl_easy *data, + const struct rustls_connection *rconn) +{ + const uint8_t *protocol = NULL; + size_t len = 0; + + rustls_connection_get_alpn_protocol(rconn, &protocol, &len); + Curl_alpn_set_negotiated(cf, data, protocol, len); +} + +/* Given an established network connection, do a TLS handshake. + * + * If `blocking` is true, this function will block until the handshake is + * complete. Otherwise it will return as soon as I/O would block. + * + * For the non-blocking I/O case, this function will set `*done` to true + * once the handshake is complete. This function never reads the value of + * `*done*`. + */ +static CURLcode +cr_connect_common(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, + bool *done) +{ + struct ssl_connect_data *const connssl = cf->ctx; + curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data); + struct rustls_ssl_backend_data *const backend = + (struct rustls_ssl_backend_data *)connssl->backend; + struct rustls_connection *rconn = NULL; + CURLcode tmperr = CURLE_OK; + int result; + int what; + bool wants_read; + bool wants_write; + curl_socket_t writefd; + curl_socket_t readfd; + timediff_t timeout_ms; + timediff_t socket_check_timeout; + + DEBUGASSERT(backend); + + CURL_TRC_CF(data, cf, "cr_connect_common, state=%d", connssl->state); + *done = FALSE; + if(!backend->conn) { + result = cr_init_backend(cf, data, + (struct rustls_ssl_backend_data *)connssl->backend); + CURL_TRC_CF(data, cf, "cr_connect_common, init backend -> %d", result); + if(result != CURLE_OK) { + return result; + } + connssl->state = ssl_connection_negotiating; + } + + rconn = backend->conn; + + /* Read/write data until the handshake is done or the socket would block. */ + for(;;) { + /* + * Connection has been established according to rustls. Set send/recv + * handlers, and update the state machine. + */ + if(!rustls_connection_is_handshaking(rconn)) { + infof(data, "Done handshaking"); + /* rustls claims it is no longer handshaking *before* it has + * send its FINISHED message off. We attempt to let it write + * one more time. Oh my. + */ + cr_set_negotiated_alpn(cf, data, rconn); + cr_send(cf, data, NULL, 0, &tmperr); + if(tmperr == CURLE_AGAIN) { + connssl->connecting_state = ssl_connect_2_writing; + return CURLE_OK; + } + else if(tmperr != CURLE_OK) { + return tmperr; + } + /* REALLY Done with the handshake. */ + connssl->state = ssl_connection_complete; + *done = TRUE; + return CURLE_OK; + } + + wants_read = rustls_connection_wants_read(rconn); + wants_write = rustls_connection_wants_write(rconn) || + backend->plain_out_buffered; + DEBUGASSERT(wants_read || wants_write); + writefd = wants_write?sockfd:CURL_SOCKET_BAD; + readfd = wants_read?sockfd:CURL_SOCKET_BAD; + + connssl->connecting_state = wants_write? + ssl_connect_2_writing : ssl_connect_2_reading; + /* check allowed time left */ + timeout_ms = Curl_timeleft(data, NULL, TRUE); + + if(timeout_ms < 0) { + /* no need to continue if time already is up */ + failf(data, "rustls: operation timed out before socket check"); + return CURLE_OPERATION_TIMEDOUT; + } + + socket_check_timeout = blocking?timeout_ms:0; + + what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, + socket_check_timeout); + if(what < 0) { + /* fatal error */ + failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); + return CURLE_SSL_CONNECT_ERROR; + } + if(blocking && 0 == what) { + failf(data, "rustls connection timeout after %" + CURL_FORMAT_TIMEDIFF_T " ms", socket_check_timeout); + return CURLE_OPERATION_TIMEDOUT; + } + if(0 == what) { + CURL_TRC_CF(data, cf, "Curl_socket_check: %s would block", + wants_read&&wants_write ? "writing and reading" : + wants_write ? "writing" : "reading"); + return CURLE_OK; + } + /* socket is readable or writable */ + + if(wants_write) { + CURL_TRC_CF(data, cf, "rustls_connection wants us to write_tls."); + cr_send(cf, data, NULL, 0, &tmperr); + if(tmperr == CURLE_AGAIN) { + CURL_TRC_CF(data, cf, "writing would block"); + /* fall through */ + } + else if(tmperr != CURLE_OK) { + return tmperr; + } + } + + if(wants_read) { + CURL_TRC_CF(data, cf, "rustls_connection wants us to read_tls."); + if(tls_recv_more(cf, data, &tmperr) < 0) { + if(tmperr == CURLE_AGAIN) { + CURL_TRC_CF(data, cf, "reading would block"); + /* fall through */ + } + else if(tmperr == CURLE_RECV_ERROR) { + return CURLE_SSL_CONNECT_ERROR; + } + else { + return tmperr; + } + } + } + } + + /* We should never fall through the loop. We should return either because + the handshake is done or because we can't read/write without blocking. */ + DEBUGASSERT(false); +} + +static CURLcode +cr_connect_nonblocking(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done) +{ + return cr_connect_common(cf, data, false, done); +} + +static CURLcode +cr_connect_blocking(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + bool done; /* unused */ + return cr_connect_common(cf, data, true, &done); +} + +static void * +cr_get_internals(struct ssl_connect_data *connssl, + CURLINFO info UNUSED_PARAM) +{ + struct rustls_ssl_backend_data *backend = + (struct rustls_ssl_backend_data *)connssl->backend; + DEBUGASSERT(backend); + return &backend->conn; +} + +static void +cr_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct rustls_ssl_backend_data *backend = + (struct rustls_ssl_backend_data *)connssl->backend; + CURLcode tmperr = CURLE_OK; + ssize_t n = 0; + + DEBUGASSERT(backend); + if(backend->conn && !connssl->peer_closed) { + CURL_TRC_CF(data, cf, "closing connection, send notify"); + rustls_connection_send_close_notify(backend->conn); + n = cr_send(cf, data, NULL, 0, &tmperr); + if(n < 0) { + failf(data, "rustls: error sending close_notify: %d", tmperr); + } + + rustls_connection_free(backend->conn); + backend->conn = NULL; + } + if(backend->config) { + rustls_client_config_free(backend->config); + backend->config = NULL; + } +} + +static size_t cr_version(char *buffer, size_t size) +{ + struct rustls_str ver = rustls_version(); + return msnprintf(buffer, size, "%.*s", (int)ver.len, ver.data); +} + +const struct Curl_ssl Curl_ssl_rustls = { + { CURLSSLBACKEND_RUSTLS, "rustls" }, + SSLSUPP_CAINFO_BLOB | /* supports */ + SSLSUPP_HTTPS_PROXY, + sizeof(struct rustls_ssl_backend_data), + + Curl_none_init, /* init */ + Curl_none_cleanup, /* cleanup */ + cr_version, /* version */ + Curl_none_check_cxn, /* check_cxn */ + Curl_none_shutdown, /* shutdown */ + cr_data_pending, /* data_pending */ + Curl_none_random, /* random */ + Curl_none_cert_status_request, /* cert_status_request */ + cr_connect_blocking, /* connect */ + cr_connect_nonblocking, /* connect_nonblocking */ + Curl_ssl_adjust_pollset, /* adjust_pollset */ + cr_get_internals, /* get_internals */ + cr_close, /* close_one */ + Curl_none_close_all, /* close_all */ + Curl_none_set_engine, /* set_engine */ + Curl_none_set_engine_default, /* set_engine_default */ + Curl_none_engines_list, /* engines_list */ + Curl_none_false_start, /* false_start */ + NULL, /* sha256sum */ + NULL, /* associate_connection */ + NULL, /* disassociate_connection */ + NULL, /* free_multi_ssl_backend_data */ + cr_recv, /* recv decrypted data */ + cr_send, /* send data to encrypt */ +}; + +#endif /* USE_RUSTLS */ diff --git a/third_party/curl/lib/vtls/rustls.h b/third_party/curl/lib/vtls/rustls.h new file mode 100644 index 0000000..bfbe23d --- /dev/null +++ b/third_party/curl/lib/vtls/rustls.h @@ -0,0 +1,35 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Jacob Hoffman-Andrews, + * + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifndef HEADER_CURL_RUSTLS_H +#define HEADER_CURL_RUSTLS_H + +#include "curl_setup.h" + +#ifdef USE_RUSTLS + +extern const struct Curl_ssl Curl_ssl_rustls; + +#endif /* USE_RUSTLS */ +#endif /* HEADER_CURL_RUSTLS_H */ diff --git a/third_party/curl/lib/vtls/schannel.c b/third_party/curl/lib/vtls/schannel.c new file mode 100644 index 0000000..19cdc4b --- /dev/null +++ b/third_party/curl/lib/vtls/schannel.c @@ -0,0 +1,2933 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (C) Marc Hoersken, + * Copyright (C) Mark Salisbury, + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Source file for all Schannel-specific code for the TLS/SSL layer. No code + * but vtls.c should ever call or use these functions. + */ + +#include "curl_setup.h" + +#ifdef USE_SCHANNEL + +#ifndef USE_WINDOWS_SSPI +# error "Can't compile SCHANNEL support without SSPI." +#endif + +#include "schannel.h" +#include "schannel_int.h" +#include "vtls.h" +#include "vtls_int.h" +#include "strcase.h" +#include "sendf.h" +#include "connect.h" /* for the connect timeout */ +#include "strerror.h" +#include "select.h" /* for the socket readiness */ +#include "inet_pton.h" /* for IP addr SNI check */ +#include "curl_multibyte.h" +#include "warnless.h" +#include "x509asn1.h" +#include "curl_printf.h" +#include "multiif.h" +#include "version_win32.h" +#include "rand.h" + +/* The last #include file should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* ALPN requires version 8.1 of the Windows SDK, which was + shipped with Visual Studio 2013, aka _MSC_VER 1800: + + https://technet.microsoft.com/en-us/library/hh831771%28v=ws.11%29.aspx +*/ +#if defined(_MSC_VER) && (_MSC_VER >= 1800) && !defined(_USING_V110_SDK71_) +# define HAS_ALPN 1 +#endif + +#ifndef BCRYPT_CHACHA20_POLY1305_ALGORITHM +#define BCRYPT_CHACHA20_POLY1305_ALGORITHM L"CHACHA20_POLY1305" +#endif + +#ifndef BCRYPT_CHAIN_MODE_CCM +#define BCRYPT_CHAIN_MODE_CCM L"ChainingModeCCM" +#endif + +#ifndef BCRYPT_CHAIN_MODE_GCM +#define BCRYPT_CHAIN_MODE_GCM L"ChainingModeGCM" +#endif + +#ifndef BCRYPT_AES_ALGORITHM +#define BCRYPT_AES_ALGORITHM L"AES" +#endif + +#ifndef BCRYPT_SHA256_ALGORITHM +#define BCRYPT_SHA256_ALGORITHM L"SHA256" +#endif + +#ifndef BCRYPT_SHA384_ALGORITHM +#define BCRYPT_SHA384_ALGORITHM L"SHA384" +#endif + +#ifdef HAS_CLIENT_CERT_PATH +#ifdef UNICODE +#define CURL_CERT_STORE_PROV_SYSTEM CERT_STORE_PROV_SYSTEM_W +#else +#define CURL_CERT_STORE_PROV_SYSTEM CERT_STORE_PROV_SYSTEM_A +#endif +#endif + +#ifndef SP_PROT_TLS1_0_CLIENT +#define SP_PROT_TLS1_0_CLIENT SP_PROT_TLS1_CLIENT +#endif + +#ifndef SP_PROT_TLS1_1_CLIENT +#define SP_PROT_TLS1_1_CLIENT 0x00000200 +#endif + +#ifndef SP_PROT_TLS1_2_CLIENT +#define SP_PROT_TLS1_2_CLIENT 0x00000800 +#endif + +#ifndef SP_PROT_TLS1_3_CLIENT +#define SP_PROT_TLS1_3_CLIENT 0x00002000 +#endif + +#ifndef SCH_USE_STRONG_CRYPTO +#define SCH_USE_STRONG_CRYPTO 0x00400000 +#endif + +#ifndef SECBUFFER_ALERT +#define SECBUFFER_ALERT 17 +#endif + +/* Both schannel buffer sizes must be > 0 */ +#define CURL_SCHANNEL_BUFFER_INIT_SIZE 4096 +#define CURL_SCHANNEL_BUFFER_FREE_SIZE 1024 + +#define CERT_THUMBPRINT_STR_LEN 40 +#define CERT_THUMBPRINT_DATA_LEN 20 + +/* Uncomment to force verbose output + * #define infof(x, y, ...) printf(y, __VA_ARGS__) + * #define failf(x, y, ...) printf(y, __VA_ARGS__) + */ + +#ifndef CALG_SHA_256 +# define CALG_SHA_256 0x0000800c +#endif + +#ifndef PKCS12_NO_PERSIST_KEY +#define PKCS12_NO_PERSIST_KEY 0x00008000 +#endif + +static CURLcode schannel_pkp_pin_peer_pubkey(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *pinnedpubkey); + +static void InitSecBuffer(SecBuffer *buffer, unsigned long BufType, + void *BufDataPtr, unsigned long BufByteSize) +{ + buffer->cbBuffer = BufByteSize; + buffer->BufferType = BufType; + buffer->pvBuffer = BufDataPtr; +} + +static void InitSecBufferDesc(SecBufferDesc *desc, SecBuffer *BufArr, + unsigned long NumArrElem) +{ + desc->ulVersion = SECBUFFER_VERSION; + desc->pBuffers = BufArr; + desc->cBuffers = NumArrElem; +} + +static CURLcode +schannel_set_ssl_version_min_max(DWORD *enabled_protocols, + struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + long ssl_version = conn_config->version; + long ssl_version_max = conn_config->version_max; + long i = ssl_version; + + switch(ssl_version_max) { + case CURL_SSLVERSION_MAX_NONE: + case CURL_SSLVERSION_MAX_DEFAULT: + + /* Windows Server 2022 and newer (including Windows 11) support TLS 1.3 + built-in. Previous builds of Windows 10 had broken TLS 1.3 + implementations that could be enabled via registry. + */ + if(curlx_verify_windows_version(10, 0, 20348, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) { + ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_3; + } + else /* Windows 10 and older */ + ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_2; + + break; + } + + for(; i <= (ssl_version_max >> 16); ++i) { + switch(i) { + case CURL_SSLVERSION_TLSv1_0: + (*enabled_protocols) |= SP_PROT_TLS1_0_CLIENT; + break; + case CURL_SSLVERSION_TLSv1_1: + (*enabled_protocols) |= SP_PROT_TLS1_1_CLIENT; + break; + case CURL_SSLVERSION_TLSv1_2: + (*enabled_protocols) |= SP_PROT_TLS1_2_CLIENT; + break; + case CURL_SSLVERSION_TLSv1_3: + + /* Windows Server 2022 and newer */ + if(curlx_verify_windows_version(10, 0, 20348, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) { + (*enabled_protocols) |= SP_PROT_TLS1_3_CLIENT; + break; + } + else { /* Windows 10 and older */ + failf(data, "schannel: TLS 1.3 not supported on Windows prior to 11"); + return CURLE_SSL_CONNECT_ERROR; + } + } + } + return CURLE_OK; +} + +/* longest is 26, buffer is slightly bigger */ +#define LONGEST_ALG_ID 32 +#define CIPHEROPTION(x) {#x, x} + +struct algo { + const char *name; + int id; +}; + +static const struct algo algs[]= { + CIPHEROPTION(CALG_MD2), + CIPHEROPTION(CALG_MD4), + CIPHEROPTION(CALG_MD5), + CIPHEROPTION(CALG_SHA), + CIPHEROPTION(CALG_SHA1), + CIPHEROPTION(CALG_MAC), + CIPHEROPTION(CALG_RSA_SIGN), + CIPHEROPTION(CALG_DSS_SIGN), +/* ifdefs for the options that are defined conditionally in wincrypt.h */ +#ifdef CALG_NO_SIGN + CIPHEROPTION(CALG_NO_SIGN), +#endif + CIPHEROPTION(CALG_RSA_KEYX), + CIPHEROPTION(CALG_DES), +#ifdef CALG_3DES_112 + CIPHEROPTION(CALG_3DES_112), +#endif + CIPHEROPTION(CALG_3DES), + CIPHEROPTION(CALG_DESX), + CIPHEROPTION(CALG_RC2), + CIPHEROPTION(CALG_RC4), + CIPHEROPTION(CALG_SEAL), +#ifdef CALG_DH_SF + CIPHEROPTION(CALG_DH_SF), +#endif + CIPHEROPTION(CALG_DH_EPHEM), +#ifdef CALG_AGREEDKEY_ANY + CIPHEROPTION(CALG_AGREEDKEY_ANY), +#endif +#ifdef CALG_HUGHES_MD5 + CIPHEROPTION(CALG_HUGHES_MD5), +#endif + CIPHEROPTION(CALG_SKIPJACK), +#ifdef CALG_TEK + CIPHEROPTION(CALG_TEK), +#endif + CIPHEROPTION(CALG_CYLINK_MEK), + CIPHEROPTION(CALG_SSL3_SHAMD5), +#ifdef CALG_SSL3_MASTER + CIPHEROPTION(CALG_SSL3_MASTER), +#endif +#ifdef CALG_SCHANNEL_MASTER_HASH + CIPHEROPTION(CALG_SCHANNEL_MASTER_HASH), +#endif +#ifdef CALG_SCHANNEL_MAC_KEY + CIPHEROPTION(CALG_SCHANNEL_MAC_KEY), +#endif +#ifdef CALG_SCHANNEL_ENC_KEY + CIPHEROPTION(CALG_SCHANNEL_ENC_KEY), +#endif +#ifdef CALG_PCT1_MASTER + CIPHEROPTION(CALG_PCT1_MASTER), +#endif +#ifdef CALG_SSL2_MASTER + CIPHEROPTION(CALG_SSL2_MASTER), +#endif +#ifdef CALG_TLS1_MASTER + CIPHEROPTION(CALG_TLS1_MASTER), +#endif +#ifdef CALG_RC5 + CIPHEROPTION(CALG_RC5), +#endif +#ifdef CALG_HMAC + CIPHEROPTION(CALG_HMAC), +#endif +#ifdef CALG_TLS1PRF + CIPHEROPTION(CALG_TLS1PRF), +#endif +#ifdef CALG_HASH_REPLACE_OWF + CIPHEROPTION(CALG_HASH_REPLACE_OWF), +#endif +#ifdef CALG_AES_128 + CIPHEROPTION(CALG_AES_128), +#endif +#ifdef CALG_AES_192 + CIPHEROPTION(CALG_AES_192), +#endif +#ifdef CALG_AES_256 + CIPHEROPTION(CALG_AES_256), +#endif +#ifdef CALG_AES + CIPHEROPTION(CALG_AES), +#endif +#ifdef CALG_SHA_256 + CIPHEROPTION(CALG_SHA_256), +#endif +#ifdef CALG_SHA_384 + CIPHEROPTION(CALG_SHA_384), +#endif +#ifdef CALG_SHA_512 + CIPHEROPTION(CALG_SHA_512), +#endif +#ifdef CALG_ECDH + CIPHEROPTION(CALG_ECDH), +#endif +#ifdef CALG_ECMQV + CIPHEROPTION(CALG_ECMQV), +#endif +#ifdef CALG_ECDSA + CIPHEROPTION(CALG_ECDSA), +#endif +#ifdef CALG_ECDH_EPHEM + CIPHEROPTION(CALG_ECDH_EPHEM), +#endif + {NULL, 0}, +}; + +static int +get_alg_id_by_name(char *name) +{ + char *nameEnd = strchr(name, ':'); + size_t n = nameEnd ? (size_t)(nameEnd - name) : strlen(name); + int i; + + for(i = 0; algs[i].name; i++) { + if((n == strlen(algs[i].name) && !strncmp(algs[i].name, name, n))) + return algs[i].id; + } + return 0; /* not found */ +} + +#define NUM_CIPHERS 47 /* There are 47 options listed above */ + +static CURLcode +set_ssl_ciphers(SCHANNEL_CRED *schannel_cred, char *ciphers, + ALG_ID *algIds) +{ + char *startCur = ciphers; + int algCount = 0; + while(startCur && (0 != *startCur) && (algCount < NUM_CIPHERS)) { + long alg = strtol(startCur, 0, 0); + if(!alg) + alg = get_alg_id_by_name(startCur); + if(alg) + algIds[algCount++] = alg; + else if(!strncmp(startCur, "USE_STRONG_CRYPTO", + sizeof("USE_STRONG_CRYPTO") - 1) || + !strncmp(startCur, "SCH_USE_STRONG_CRYPTO", + sizeof("SCH_USE_STRONG_CRYPTO") - 1)) + schannel_cred->dwFlags |= SCH_USE_STRONG_CRYPTO; + else + return CURLE_SSL_CIPHER; + startCur = strchr(startCur, ':'); + if(startCur) + startCur++; + } + schannel_cred->palgSupportedAlgs = algIds; + schannel_cred->cSupportedAlgs = algCount; + return CURLE_OK; +} + +#ifdef HAS_CLIENT_CERT_PATH + +/* Function allocates memory for store_path only if CURLE_OK is returned */ +static CURLcode +get_cert_location(TCHAR *path, DWORD *store_name, TCHAR **store_path, + TCHAR **thumbprint) +{ + TCHAR *sep; + TCHAR *store_path_start; + size_t store_name_len; + + sep = _tcschr(path, TEXT('\\')); + if(!sep) + return CURLE_SSL_CERTPROBLEM; + + store_name_len = sep - path; + + if(_tcsncmp(path, TEXT("CurrentUser"), store_name_len) == 0) + *store_name = CERT_SYSTEM_STORE_CURRENT_USER; + else if(_tcsncmp(path, TEXT("LocalMachine"), store_name_len) == 0) + *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE; + else if(_tcsncmp(path, TEXT("CurrentService"), store_name_len) == 0) + *store_name = CERT_SYSTEM_STORE_CURRENT_SERVICE; + else if(_tcsncmp(path, TEXT("Services"), store_name_len) == 0) + *store_name = CERT_SYSTEM_STORE_SERVICES; + else if(_tcsncmp(path, TEXT("Users"), store_name_len) == 0) + *store_name = CERT_SYSTEM_STORE_USERS; + else if(_tcsncmp(path, TEXT("CurrentUserGroupPolicy"), + store_name_len) == 0) + *store_name = CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY; + else if(_tcsncmp(path, TEXT("LocalMachineGroupPolicy"), + store_name_len) == 0) + *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY; + else if(_tcsncmp(path, TEXT("LocalMachineEnterprise"), + store_name_len) == 0) + *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE; + else + return CURLE_SSL_CERTPROBLEM; + + store_path_start = sep + 1; + + sep = _tcschr(store_path_start, TEXT('\\')); + if(!sep) + return CURLE_SSL_CERTPROBLEM; + + *thumbprint = sep + 1; + if(_tcslen(*thumbprint) != CERT_THUMBPRINT_STR_LEN) + return CURLE_SSL_CERTPROBLEM; + + *sep = TEXT('\0'); + *store_path = _tcsdup(store_path_start); + *sep = TEXT('\\'); + if(!*store_path) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} +#endif + +static bool algo(const char *check, char *namep, size_t nlen) +{ + return (strlen(check) == nlen) && !strncmp(check, namep, nlen); +} + +static CURLcode +schannel_acquire_credential_handle(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + +#ifdef HAS_CLIENT_CERT_PATH + PCCERT_CONTEXT client_certs[1] = { NULL }; + HCERTSTORE client_cert_store = NULL; +#endif + SECURITY_STATUS sspi_status = SEC_E_OK; + CURLcode result; + + /* setup Schannel API options */ + DWORD flags = 0; + DWORD enabled_protocols = 0; + + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)(connssl->backend); + + DEBUGASSERT(backend); + + if(conn_config->verifypeer) { +#ifdef HAS_MANUAL_VERIFY_API + if(backend->use_manual_cred_validation) + flags = SCH_CRED_MANUAL_CRED_VALIDATION; + else +#endif + flags = SCH_CRED_AUTO_CRED_VALIDATION; + + if(ssl_config->no_revoke) { + flags |= SCH_CRED_IGNORE_NO_REVOCATION_CHECK | + SCH_CRED_IGNORE_REVOCATION_OFFLINE; + + DEBUGF(infof(data, "schannel: disabled server certificate revocation " + "checks")); + } + else if(ssl_config->revoke_best_effort) { + flags |= SCH_CRED_IGNORE_NO_REVOCATION_CHECK | + SCH_CRED_IGNORE_REVOCATION_OFFLINE | SCH_CRED_REVOCATION_CHECK_CHAIN; + + DEBUGF(infof(data, "schannel: ignore revocation offline errors")); + } + else { + flags |= SCH_CRED_REVOCATION_CHECK_CHAIN; + + DEBUGF(infof(data, + "schannel: checking server certificate revocation")); + } + } + else { + flags = SCH_CRED_MANUAL_CRED_VALIDATION | + SCH_CRED_IGNORE_NO_REVOCATION_CHECK | + SCH_CRED_IGNORE_REVOCATION_OFFLINE; + DEBUGF(infof(data, + "schannel: disabled server cert revocation checks")); + } + + if(!conn_config->verifyhost) { + flags |= SCH_CRED_NO_SERVERNAME_CHECK; + DEBUGF(infof(data, "schannel: verifyhost setting prevents Schannel from " + "comparing the supplied target name with the subject " + "names in server certificates.")); + } + + if(!ssl_config->auto_client_cert) { + flags &= ~SCH_CRED_USE_DEFAULT_CREDS; + flags |= SCH_CRED_NO_DEFAULT_CREDS; + infof(data, "schannel: disabled automatic use of client certificate"); + } + else + infof(data, "schannel: enabled automatic use of client certificate"); + + switch(conn_config->version) { + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1: + case CURL_SSLVERSION_TLSv1_0: + case CURL_SSLVERSION_TLSv1_1: + case CURL_SSLVERSION_TLSv1_2: + case CURL_SSLVERSION_TLSv1_3: + { + result = schannel_set_ssl_version_min_max(&enabled_protocols, cf, data); + if(result != CURLE_OK) + return result; + break; + } + case CURL_SSLVERSION_SSLv3: + case CURL_SSLVERSION_SSLv2: + failf(data, "SSL versions not supported"); + return CURLE_NOT_BUILT_IN; + default: + failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); + return CURLE_SSL_CONNECT_ERROR; + } + +#ifdef HAS_CLIENT_CERT_PATH + /* client certificate */ + if(data->set.ssl.primary.clientcert || data->set.ssl.primary.cert_blob) { + DWORD cert_store_name = 0; + TCHAR *cert_store_path = NULL; + TCHAR *cert_thumbprint_str = NULL; + CRYPT_HASH_BLOB cert_thumbprint; + BYTE cert_thumbprint_data[CERT_THUMBPRINT_DATA_LEN]; + HCERTSTORE cert_store = NULL; + FILE *fInCert = NULL; + void *certdata = NULL; + size_t certsize = 0; + bool blob = data->set.ssl.primary.cert_blob != NULL; + TCHAR *cert_path = NULL; + if(blob) { + certdata = data->set.ssl.primary.cert_blob->data; + certsize = data->set.ssl.primary.cert_blob->len; + } + else { + cert_path = curlx_convert_UTF8_to_tchar( + data->set.ssl.primary.clientcert); + if(!cert_path) + return CURLE_OUT_OF_MEMORY; + + result = get_cert_location(cert_path, &cert_store_name, + &cert_store_path, &cert_thumbprint_str); + + if(result && (data->set.ssl.primary.clientcert[0]!='\0')) + fInCert = fopen(data->set.ssl.primary.clientcert, "rb"); + + if(result && !fInCert) { + failf(data, "schannel: Failed to get certificate location" + " or file for %s", + data->set.ssl.primary.clientcert); + curlx_unicodefree(cert_path); + return result; + } + } + + if((fInCert || blob) && (data->set.ssl.cert_type) && + (!strcasecompare(data->set.ssl.cert_type, "P12"))) { + failf(data, "schannel: certificate format compatibility error " + " for %s", + blob ? "(memory blob)" : data->set.ssl.primary.clientcert); + curlx_unicodefree(cert_path); + return CURLE_SSL_CERTPROBLEM; + } + + if(fInCert || blob) { + /* Reading a .P12 or .pfx file, like the example at bottom of + https://social.msdn.microsoft.com/Forums/windowsdesktop/ + en-US/3e7bc95f-b21a-4bcd-bd2c-7f996718cae5 + */ + CRYPT_DATA_BLOB datablob; + WCHAR* pszPassword; + size_t pwd_len = 0; + int str_w_len = 0; + const char *cert_showfilename_error = blob ? + "(memory blob)" : data->set.ssl.primary.clientcert; + curlx_unicodefree(cert_path); + if(fInCert) { + long cert_tell = 0; + bool continue_reading = fseek(fInCert, 0, SEEK_END) == 0; + if(continue_reading) + cert_tell = ftell(fInCert); + if(cert_tell < 0) + continue_reading = FALSE; + else + certsize = (size_t)cert_tell; + if(continue_reading) + continue_reading = fseek(fInCert, 0, SEEK_SET) == 0; + if(continue_reading) + certdata = malloc(certsize + 1); + if((!certdata) || + ((int) fread(certdata, certsize, 1, fInCert) != 1)) + continue_reading = FALSE; + fclose(fInCert); + if(!continue_reading) { + failf(data, "schannel: Failed to read cert file %s", + data->set.ssl.primary.clientcert); + free(certdata); + return CURLE_SSL_CERTPROBLEM; + } + } + + /* Convert key-pair data to the in-memory certificate store */ + datablob.pbData = (BYTE*)certdata; + datablob.cbData = (DWORD)certsize; + + if(data->set.ssl.key_passwd) + pwd_len = strlen(data->set.ssl.key_passwd); + pszPassword = (WCHAR*)malloc(sizeof(WCHAR)*(pwd_len + 1)); + if(pszPassword) { + if(pwd_len > 0) + str_w_len = MultiByteToWideChar(CP_UTF8, + MB_ERR_INVALID_CHARS, + data->set.ssl.key_passwd, + (int)pwd_len, + pszPassword, (int)(pwd_len + 1)); + + if((str_w_len >= 0) && (str_w_len <= (int)pwd_len)) + pszPassword[str_w_len] = 0; + else + pszPassword[0] = 0; + + if(curlx_verify_windows_version(6, 0, 0, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) + cert_store = PFXImportCertStore(&datablob, pszPassword, + PKCS12_NO_PERSIST_KEY); + else + cert_store = PFXImportCertStore(&datablob, pszPassword, 0); + + free(pszPassword); + } + if(!blob) + free(certdata); + if(!cert_store) { + DWORD errorcode = GetLastError(); + if(errorcode == ERROR_INVALID_PASSWORD) + failf(data, "schannel: Failed to import cert file %s, " + "password is bad", + cert_showfilename_error); + else + failf(data, "schannel: Failed to import cert file %s, " + "last error is 0x%lx", + cert_showfilename_error, errorcode); + return CURLE_SSL_CERTPROBLEM; + } + + client_certs[0] = CertFindCertificateInStore( + cert_store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, + CERT_FIND_ANY, NULL, NULL); + + if(!client_certs[0]) { + failf(data, "schannel: Failed to get certificate from file %s" + ", last error is 0x%lx", + cert_showfilename_error, GetLastError()); + CertCloseStore(cert_store, 0); + return CURLE_SSL_CERTPROBLEM; + } + } + else { + cert_store = + CertOpenStore(CURL_CERT_STORE_PROV_SYSTEM, 0, + (HCRYPTPROV)NULL, + CERT_STORE_OPEN_EXISTING_FLAG | cert_store_name, + cert_store_path); + if(!cert_store) { + char *path_utf8 = + curlx_convert_tchar_to_UTF8(cert_store_path); + failf(data, "schannel: Failed to open cert store %lx %s, " + "last error is 0x%lx", + cert_store_name, + (path_utf8 ? path_utf8 : "(unknown)"), + GetLastError()); + free(cert_store_path); + curlx_unicodefree(path_utf8); + curlx_unicodefree(cert_path); + return CURLE_SSL_CERTPROBLEM; + } + free(cert_store_path); + + cert_thumbprint.pbData = cert_thumbprint_data; + cert_thumbprint.cbData = CERT_THUMBPRINT_DATA_LEN; + + if(!CryptStringToBinary(cert_thumbprint_str, + CERT_THUMBPRINT_STR_LEN, + CRYPT_STRING_HEX, + cert_thumbprint_data, + &cert_thumbprint.cbData, + NULL, NULL)) { + curlx_unicodefree(cert_path); + CertCloseStore(cert_store, 0); + return CURLE_SSL_CERTPROBLEM; + } + + client_certs[0] = CertFindCertificateInStore( + cert_store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, + CERT_FIND_HASH, &cert_thumbprint, NULL); + + curlx_unicodefree(cert_path); + + if(!client_certs[0]) { + /* CRYPT_E_NOT_FOUND / E_INVALIDARG */ + CertCloseStore(cert_store, 0); + return CURLE_SSL_CERTPROBLEM; + } + } + client_cert_store = cert_store; + } +#else + if(data->set.ssl.primary.clientcert || data->set.ssl.primary.cert_blob) { + failf(data, "schannel: client cert support not built in"); + return CURLE_NOT_BUILT_IN; + } +#endif + + /* allocate memory for the reusable credential handle */ + backend->cred = (struct Curl_schannel_cred *) + calloc(1, sizeof(struct Curl_schannel_cred)); + if(!backend->cred) { + failf(data, "schannel: unable to allocate memory"); + +#ifdef HAS_CLIENT_CERT_PATH + if(client_certs[0]) + CertFreeCertificateContext(client_certs[0]); + if(client_cert_store) + CertCloseStore(client_cert_store, 0); +#endif + + return CURLE_OUT_OF_MEMORY; + } + backend->cred->refcount = 1; + +#ifdef HAS_CLIENT_CERT_PATH + /* Since we did not persist the key, we need to extend the store's + * lifetime until the end of the connection + */ + backend->cred->client_cert_store = client_cert_store; +#endif + + /* We support TLS 1.3 starting in Windows 10 version 1809 (OS build 17763) as + long as the user did not set a legacy algorithm list + (CURLOPT_SSL_CIPHER_LIST). */ + if(!conn_config->cipher_list && + curlx_verify_windows_version(10, 0, 17763, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) { + + char *ciphers13 = 0; + + bool disable_aes_gcm_sha384 = FALSE; + bool disable_aes_gcm_sha256 = FALSE; + bool disable_chacha_poly = FALSE; + bool disable_aes_ccm_8_sha256 = FALSE; + bool disable_aes_ccm_sha256 = FALSE; + + SCH_CREDENTIALS credentials = { 0 }; + TLS_PARAMETERS tls_parameters = { 0 }; + CRYPTO_SETTINGS crypto_settings[4] = { { 0 } }; + UNICODE_STRING blocked_ccm_modes[1] = { { 0 } }; + UNICODE_STRING blocked_gcm_modes[1] = { { 0 } }; + + int crypto_settings_idx = 0; + + + /* If TLS 1.3 ciphers are explicitly listed, then + * disable all the ciphers and re-enable which + * ciphers the user has provided. + */ + ciphers13 = conn_config->cipher_list13; + if(ciphers13) { + const int remaining_ciphers = 5; + + /* detect which remaining ciphers to enable + and then disable everything else. + */ + + char *startCur = ciphers13; + int algCount = 0; + char *nameEnd; + + disable_aes_gcm_sha384 = TRUE; + disable_aes_gcm_sha256 = TRUE; + disable_chacha_poly = TRUE; + disable_aes_ccm_8_sha256 = TRUE; + disable_aes_ccm_sha256 = TRUE; + + while(startCur && (0 != *startCur) && (algCount < remaining_ciphers)) { + size_t n; + char *namep; + nameEnd = strchr(startCur, ':'); + n = nameEnd ? (size_t)(nameEnd - startCur) : strlen(startCur); + namep = startCur; + + if(disable_aes_gcm_sha384 && + algo("TLS_AES_256_GCM_SHA384", namep, n)) { + disable_aes_gcm_sha384 = FALSE; + } + else if(disable_aes_gcm_sha256 + && algo("TLS_AES_128_GCM_SHA256", namep, n)) { + disable_aes_gcm_sha256 = FALSE; + } + else if(disable_chacha_poly + && algo("TLS_CHACHA20_POLY1305_SHA256", namep, n)) { + disable_chacha_poly = FALSE; + } + else if(disable_aes_ccm_8_sha256 + && algo("TLS_AES_128_CCM_8_SHA256", namep, n)) { + disable_aes_ccm_8_sha256 = FALSE; + } + else if(disable_aes_ccm_sha256 + && algo("TLS_AES_128_CCM_SHA256", namep, n)) { + disable_aes_ccm_sha256 = FALSE; + } + else { + failf(data, "schannel: Unknown TLS 1.3 cipher: %.*s", (int)n, namep); + return CURLE_SSL_CIPHER; + } + + startCur = nameEnd; + if(startCur) + startCur++; + + algCount++; + } + } + + if(disable_aes_gcm_sha384 && disable_aes_gcm_sha256 + && disable_chacha_poly && disable_aes_ccm_8_sha256 + && disable_aes_ccm_sha256) { + failf(data, "schannel: All available TLS 1.3 ciphers were disabled"); + return CURLE_SSL_CIPHER; + } + + /* Disable TLS_AES_128_CCM_8_SHA256 and/or TLS_AES_128_CCM_SHA256 */ + if(disable_aes_ccm_8_sha256 || disable_aes_ccm_sha256) { + /* + Disallow AES_CCM algorithm. + */ + blocked_ccm_modes[0].Length = sizeof(BCRYPT_CHAIN_MODE_CCM); + blocked_ccm_modes[0].MaximumLength = sizeof(BCRYPT_CHAIN_MODE_CCM); + blocked_ccm_modes[0].Buffer = (PWSTR)BCRYPT_CHAIN_MODE_CCM; + + crypto_settings[crypto_settings_idx].eAlgorithmUsage = + TlsParametersCngAlgUsageCipher; + crypto_settings[crypto_settings_idx].rgstrChainingModes = + blocked_ccm_modes; + crypto_settings[crypto_settings_idx].cChainingModes = + ARRAYSIZE(blocked_ccm_modes); + crypto_settings[crypto_settings_idx].strCngAlgId.Length = + sizeof(BCRYPT_AES_ALGORITHM); + crypto_settings[crypto_settings_idx].strCngAlgId.MaximumLength = + sizeof(BCRYPT_AES_ALGORITHM); + crypto_settings[crypto_settings_idx].strCngAlgId.Buffer = + (PWSTR)BCRYPT_AES_ALGORITHM; + + /* only disabling one of the CCM modes */ + if(disable_aes_ccm_8_sha256 != disable_aes_ccm_sha256) { + if(disable_aes_ccm_8_sha256) + crypto_settings[crypto_settings_idx].dwMinBitLength = 128; + else /* disable_aes_ccm_sha256 */ + crypto_settings[crypto_settings_idx].dwMaxBitLength = 64; + } + + crypto_settings_idx++; + } + + /* Disable TLS_AES_256_GCM_SHA384 and/or TLS_AES_128_GCM_SHA256 */ + if(disable_aes_gcm_sha384 || disable_aes_gcm_sha256) { + + /* + Disallow AES_GCM algorithm + */ + blocked_gcm_modes[0].Length = sizeof(BCRYPT_CHAIN_MODE_GCM); + blocked_gcm_modes[0].MaximumLength = sizeof(BCRYPT_CHAIN_MODE_GCM); + blocked_gcm_modes[0].Buffer = (PWSTR)BCRYPT_CHAIN_MODE_GCM; + + /* if only one is disabled, then explicitly disable the + digest cipher suite (sha384 or sha256) */ + if(disable_aes_gcm_sha384 != disable_aes_gcm_sha256) { + crypto_settings[crypto_settings_idx].eAlgorithmUsage = + TlsParametersCngAlgUsageDigest; + crypto_settings[crypto_settings_idx].strCngAlgId.Length = + sizeof(disable_aes_gcm_sha384 ? + BCRYPT_SHA384_ALGORITHM : BCRYPT_SHA256_ALGORITHM); + crypto_settings[crypto_settings_idx].strCngAlgId.MaximumLength = + sizeof(disable_aes_gcm_sha384 ? + BCRYPT_SHA384_ALGORITHM : BCRYPT_SHA256_ALGORITHM); + crypto_settings[crypto_settings_idx].strCngAlgId.Buffer = + (PWSTR)(disable_aes_gcm_sha384 ? + BCRYPT_SHA384_ALGORITHM : BCRYPT_SHA256_ALGORITHM); + } + else { /* Disable both AES_GCM ciphers */ + crypto_settings[crypto_settings_idx].eAlgorithmUsage = + TlsParametersCngAlgUsageCipher; + crypto_settings[crypto_settings_idx].strCngAlgId.Length = + sizeof(BCRYPT_AES_ALGORITHM); + crypto_settings[crypto_settings_idx].strCngAlgId.MaximumLength = + sizeof(BCRYPT_AES_ALGORITHM); + crypto_settings[crypto_settings_idx].strCngAlgId.Buffer = + (PWSTR)BCRYPT_AES_ALGORITHM; + } + + crypto_settings[crypto_settings_idx].rgstrChainingModes = + blocked_gcm_modes; + crypto_settings[crypto_settings_idx].cChainingModes = 1; + + crypto_settings_idx++; + } + + /* + Disable ChaCha20-Poly1305. + */ + if(disable_chacha_poly) { + crypto_settings[crypto_settings_idx].eAlgorithmUsage = + TlsParametersCngAlgUsageCipher; + crypto_settings[crypto_settings_idx].strCngAlgId.Length = + sizeof(BCRYPT_CHACHA20_POLY1305_ALGORITHM); + crypto_settings[crypto_settings_idx].strCngAlgId.MaximumLength = + sizeof(BCRYPT_CHACHA20_POLY1305_ALGORITHM); + crypto_settings[crypto_settings_idx].strCngAlgId.Buffer = + (PWSTR)BCRYPT_CHACHA20_POLY1305_ALGORITHM; + crypto_settings_idx++; + } + + tls_parameters.pDisabledCrypto = crypto_settings; + + /* The number of blocked suites */ + tls_parameters.cDisabledCrypto = crypto_settings_idx; + credentials.pTlsParameters = &tls_parameters; + credentials.cTlsParameters = 1; + + credentials.dwVersion = SCH_CREDENTIALS_VERSION; + credentials.dwFlags = flags | SCH_USE_STRONG_CRYPTO; + + credentials.pTlsParameters->grbitDisabledProtocols = + (DWORD)~enabled_protocols; + +#ifdef HAS_CLIENT_CERT_PATH + if(client_certs[0]) { + credentials.cCreds = 1; + credentials.paCred = client_certs; + } +#endif + + sspi_status = + s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR*)UNISP_NAME, + SECPKG_CRED_OUTBOUND, NULL, + &credentials, NULL, NULL, + &backend->cred->cred_handle, + &backend->cred->time_stamp); + } + else { + /* Pre-Windows 10 1809 or the user set a legacy algorithm list. Although MS + doesn't document it, currently Schannel will not negotiate TLS 1.3 when + SCHANNEL_CRED is used. */ + ALG_ID algIds[NUM_CIPHERS]; + char *ciphers = conn_config->cipher_list; + SCHANNEL_CRED schannel_cred = { 0 }; + schannel_cred.dwVersion = SCHANNEL_CRED_VERSION; + schannel_cred.dwFlags = flags; + schannel_cred.grbitEnabledProtocols = enabled_protocols; + + if(ciphers) { + if((enabled_protocols & SP_PROT_TLS1_3_CLIENT)) { + infof(data, "schannel: WARNING: This version of Schannel may " + "negotiate a less-secure TLS version than TLS 1.3 because the " + "user set an algorithm cipher list."); + } + if(conn_config->cipher_list13) { + failf(data, "schannel: This version of Schannel does not support " + "setting an algorithm cipher list and TLS 1.3 cipher list at " + "the same time"); + return CURLE_SSL_CIPHER; + } + result = set_ssl_ciphers(&schannel_cred, ciphers, algIds); + if(CURLE_OK != result) { + failf(data, "schannel: Failed setting algorithm cipher list"); + return result; + } + } + else { + schannel_cred.dwFlags = flags | SCH_USE_STRONG_CRYPTO; + } + +#ifdef HAS_CLIENT_CERT_PATH + if(client_certs[0]) { + schannel_cred.cCreds = 1; + schannel_cred.paCred = client_certs; + } +#endif + + sspi_status = + s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR*)UNISP_NAME, + SECPKG_CRED_OUTBOUND, NULL, + &schannel_cred, NULL, NULL, + &backend->cred->cred_handle, + &backend->cred->time_stamp); + } + +#ifdef HAS_CLIENT_CERT_PATH + if(client_certs[0]) + CertFreeCertificateContext(client_certs[0]); +#endif + + if(sspi_status != SEC_E_OK) { + char buffer[STRERROR_LEN]; + failf(data, "schannel: AcquireCredentialsHandle failed: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + Curl_safefree(backend->cred); + switch(sspi_status) { + case SEC_E_INSUFFICIENT_MEMORY: + return CURLE_OUT_OF_MEMORY; + case SEC_E_NO_CREDENTIALS: + case SEC_E_SECPKG_NOT_FOUND: + case SEC_E_NOT_OWNER: + case SEC_E_UNKNOWN_CREDENTIALS: + case SEC_E_INTERNAL_ERROR: + default: + return CURLE_SSL_CONNECT_ERROR; + } + } + + return CURLE_OK; +} + +static CURLcode +schannel_connect_step1(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + ssize_t written = -1; + struct ssl_connect_data *connssl = cf->ctx; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + SecBuffer outbuf; + SecBufferDesc outbuf_desc; + SecBuffer inbuf; + SecBufferDesc inbuf_desc; +#ifdef HAS_ALPN + unsigned char alpn_buffer[128]; +#endif + SECURITY_STATUS sspi_status = SEC_E_OK; + struct Curl_schannel_cred *old_cred = NULL; + CURLcode result; + + DEBUGASSERT(backend); + DEBUGF(infof(data, + "schannel: SSL/TLS connection with %s port %d (step 1/3)", + connssl->peer.hostname, connssl->peer.port)); + + if(curlx_verify_windows_version(5, 1, 0, PLATFORM_WINNT, + VERSION_LESS_THAN_EQUAL)) { + /* Schannel in Windows XP (OS version 5.1) uses legacy handshakes and + algorithms that may not be supported by all servers. */ + infof(data, "schannel: Windows version is old and may not be able to " + "connect to some servers due to lack of SNI, algorithms, etc."); + } + +#ifdef HAS_ALPN + /* ALPN is only supported on Windows 8.1 / Server 2012 R2 and above. + Also it doesn't seem to be supported for Wine, see curl bug #983. */ + backend->use_alpn = connssl->alpn && + !GetProcAddress(GetModuleHandle(TEXT("ntdll")), + "wine_get_version") && + curlx_verify_windows_version(6, 3, 0, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL); +#else + backend->use_alpn = false; +#endif + +#ifdef _WIN32_WCE +#ifdef HAS_MANUAL_VERIFY_API + /* certificate validation on CE doesn't seem to work right; we'll + * do it following a more manual process. */ + backend->use_manual_cred_validation = true; +#else +#error "compiler too old to support requisite manual cert verify for Win CE" +#endif +#else +#ifdef HAS_MANUAL_VERIFY_API + if(conn_config->CAfile || conn_config->ca_info_blob) { + if(curlx_verify_windows_version(6, 1, 0, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) { + backend->use_manual_cred_validation = true; + } + else { + failf(data, "schannel: this version of Windows is too old to support " + "certificate verification via CA bundle file."); + return CURLE_SSL_CACERT_BADFILE; + } + } + else + backend->use_manual_cred_validation = false; +#else + if(conn_config->CAfile || conn_config->ca_info_blob) { + failf(data, "schannel: CA cert support not built in"); + return CURLE_NOT_BUILT_IN; + } +#endif +#endif + + backend->cred = NULL; + + /* check for an existing reusable credential handle */ + if(ssl_config->primary.sessionid) { + Curl_ssl_sessionid_lock(data); + if(!Curl_ssl_getsessionid(cf, data, &connssl->peer, + (void **)&old_cred, NULL)) { + backend->cred = old_cred; + DEBUGF(infof(data, "schannel: reusing existing credential handle")); + + /* increment the reference counter of the credential/session handle */ + backend->cred->refcount++; + DEBUGF(infof(data, + "schannel: incremented credential handle refcount = %d", + backend->cred->refcount)); + } + Curl_ssl_sessionid_unlock(data); + } + + if(!backend->cred) { + char *snihost; + result = schannel_acquire_credential_handle(cf, data); + if(result) + return result; + /* schannel_acquire_credential_handle() sets backend->cred accordingly or + it returns error otherwise. */ + + /* A hostname associated with the credential is needed by + InitializeSecurityContext for SNI and other reasons. */ + snihost = connssl->peer.sni? connssl->peer.sni : connssl->peer.hostname; + backend->cred->sni_hostname = curlx_convert_UTF8_to_tchar(snihost); + if(!backend->cred->sni_hostname) + return CURLE_OUT_OF_MEMORY; + } + + /* Warn if SNI is disabled due to use of an IP address */ + if(connssl->peer.type != CURL_SSL_PEER_DNS) { + infof(data, "schannel: using IP address, SNI is not supported by OS."); + } + +#ifdef HAS_ALPN + if(backend->use_alpn) { + int cur = 0; + int list_start_index = 0; + unsigned int *extension_len = NULL; + unsigned short* list_len = NULL; + struct alpn_proto_buf proto; + + /* The first four bytes will be an unsigned int indicating number + of bytes of data in the rest of the buffer. */ + extension_len = (unsigned int *)(void *)(&alpn_buffer[cur]); + cur += (int)sizeof(unsigned int); + + /* The next four bytes are an indicator that this buffer will contain + ALPN data, as opposed to NPN, for example. */ + *(unsigned int *)(void *)&alpn_buffer[cur] = + SecApplicationProtocolNegotiationExt_ALPN; + cur += (int)sizeof(unsigned int); + + /* The next two bytes will be an unsigned short indicating the number + of bytes used to list the preferred protocols. */ + list_len = (unsigned short*)(void *)(&alpn_buffer[cur]); + cur += (int)sizeof(unsigned short); + + list_start_index = cur; + + result = Curl_alpn_to_proto_buf(&proto, connssl->alpn); + if(result) { + failf(data, "Error setting ALPN"); + return CURLE_SSL_CONNECT_ERROR; + } + memcpy(&alpn_buffer[cur], proto.data, proto.len); + cur += proto.len; + + *list_len = curlx_uitous(cur - list_start_index); + *extension_len = (unsigned int)(*list_len + + sizeof(unsigned int) + sizeof(unsigned short)); + + InitSecBuffer(&inbuf, SECBUFFER_APPLICATION_PROTOCOLS, alpn_buffer, cur); + InitSecBufferDesc(&inbuf_desc, &inbuf, 1); + + Curl_alpn_to_proto_str(&proto, connssl->alpn); + infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data); + } + else { + InitSecBuffer(&inbuf, SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&inbuf_desc, &inbuf, 1); + } +#else /* HAS_ALPN */ + InitSecBuffer(&inbuf, SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&inbuf_desc, &inbuf, 1); +#endif + + /* setup output buffer */ + InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&outbuf_desc, &outbuf, 1); + + /* security request flags */ + backend->req_flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | + ISC_REQ_CONFIDENTIALITY | ISC_REQ_ALLOCATE_MEMORY | + ISC_REQ_STREAM; + + if(!ssl_config->auto_client_cert) { + backend->req_flags |= ISC_REQ_USE_SUPPLIED_CREDS; + } + + /* allocate memory for the security context handle */ + backend->ctxt = (struct Curl_schannel_ctxt *) + calloc(1, sizeof(struct Curl_schannel_ctxt)); + if(!backend->ctxt) { + failf(data, "schannel: unable to allocate memory"); + return CURLE_OUT_OF_MEMORY; + } + + /* Schannel InitializeSecurityContext: + https://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx + + At the moment we don't pass inbuf unless we're using ALPN since we only + use it for that, and Wine (for which we currently disable ALPN) is giving + us problems with inbuf regardless. https://github.com/curl/curl/issues/983 + */ + sspi_status = s_pSecFn->InitializeSecurityContext( + &backend->cred->cred_handle, NULL, backend->cred->sni_hostname, + backend->req_flags, 0, 0, + (backend->use_alpn ? &inbuf_desc : NULL), + 0, &backend->ctxt->ctxt_handle, + &outbuf_desc, &backend->ret_flags, &backend->ctxt->time_stamp); + + if(sspi_status != SEC_I_CONTINUE_NEEDED) { + char buffer[STRERROR_LEN]; + Curl_safefree(backend->ctxt); + switch(sspi_status) { + case SEC_E_INSUFFICIENT_MEMORY: + failf(data, "schannel: initial InitializeSecurityContext failed: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + return CURLE_OUT_OF_MEMORY; + case SEC_E_WRONG_PRINCIPAL: + failf(data, "schannel: SNI or certificate check failed: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + return CURLE_PEER_FAILED_VERIFICATION; + /* + case SEC_E_INVALID_HANDLE: + case SEC_E_INVALID_TOKEN: + case SEC_E_LOGON_DENIED: + case SEC_E_TARGET_UNKNOWN: + case SEC_E_NO_AUTHENTICATING_AUTHORITY: + case SEC_E_INTERNAL_ERROR: + case SEC_E_NO_CREDENTIALS: + case SEC_E_UNSUPPORTED_FUNCTION: + case SEC_E_APPLICATION_PROTOCOL_MISMATCH: + */ + default: + failf(data, "schannel: initial InitializeSecurityContext failed: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + return CURLE_SSL_CONNECT_ERROR; + } + } + + DEBUGF(infof(data, "schannel: sending initial handshake data: " + "sending %lu bytes.", outbuf.cbBuffer)); + + /* send initial handshake data which is now stored in output buffer */ + written = Curl_conn_cf_send(cf->next, data, + outbuf.pvBuffer, outbuf.cbBuffer, + &result); + s_pSecFn->FreeContextBuffer(outbuf.pvBuffer); + if((result != CURLE_OK) || (outbuf.cbBuffer != (size_t) written)) { + failf(data, "schannel: failed to send initial handshake data: " + "sent %zd of %lu bytes", written, outbuf.cbBuffer); + return CURLE_SSL_CONNECT_ERROR; + } + + DEBUGF(infof(data, "schannel: sent initial handshake data: " + "sent %zd bytes", written)); + + backend->recv_unrecoverable_err = CURLE_OK; + backend->recv_sspi_close_notify = false; + backend->recv_connection_closed = false; + backend->recv_renegotiating = false; + backend->encdata_is_incomplete = false; + + /* continue to second handshake step */ + connssl->connecting_state = ssl_connect_2; + + return CURLE_OK; +} + +static CURLcode +schannel_connect_step2(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + int i; + ssize_t nread = -1, written = -1; + unsigned char *reallocated_buffer; + SecBuffer outbuf[3]; + SecBufferDesc outbuf_desc; + SecBuffer inbuf[2]; + SecBufferDesc inbuf_desc; + SECURITY_STATUS sspi_status = SEC_E_OK; + CURLcode result; + bool doread; + const char *pubkey_ptr; + + DEBUGASSERT(backend); + + doread = (connssl->connecting_state != ssl_connect_2_writing) ? TRUE : FALSE; + + DEBUGF(infof(data, + "schannel: SSL/TLS connection with %s port %d (step 2/3)", + connssl->peer.hostname, connssl->peer.port)); + + if(!backend->cred || !backend->ctxt) + return CURLE_SSL_CONNECT_ERROR; + + /* buffer to store previously received and decrypted data */ + if(!backend->decdata_buffer) { + backend->decdata_offset = 0; + backend->decdata_length = CURL_SCHANNEL_BUFFER_INIT_SIZE; + backend->decdata_buffer = malloc(backend->decdata_length); + if(!backend->decdata_buffer) { + failf(data, "schannel: unable to allocate memory"); + return CURLE_OUT_OF_MEMORY; + } + } + + /* buffer to store previously received and encrypted data */ + if(!backend->encdata_buffer) { + backend->encdata_is_incomplete = false; + backend->encdata_offset = 0; + backend->encdata_length = CURL_SCHANNEL_BUFFER_INIT_SIZE; + backend->encdata_buffer = malloc(backend->encdata_length); + if(!backend->encdata_buffer) { + failf(data, "schannel: unable to allocate memory"); + return CURLE_OUT_OF_MEMORY; + } + } + + /* if we need a bigger buffer to read a full message, increase buffer now */ + if(backend->encdata_length - backend->encdata_offset < + CURL_SCHANNEL_BUFFER_FREE_SIZE) { + /* increase internal encrypted data buffer */ + size_t reallocated_length = backend->encdata_offset + + CURL_SCHANNEL_BUFFER_FREE_SIZE; + reallocated_buffer = realloc(backend->encdata_buffer, + reallocated_length); + + if(!reallocated_buffer) { + failf(data, "schannel: unable to re-allocate memory"); + return CURLE_OUT_OF_MEMORY; + } + else { + backend->encdata_buffer = reallocated_buffer; + backend->encdata_length = reallocated_length; + } + } + + for(;;) { + if(doread) { + /* read encrypted handshake data from socket */ + nread = Curl_conn_cf_recv(cf->next, data, + (char *) (backend->encdata_buffer + + backend->encdata_offset), + backend->encdata_length - + backend->encdata_offset, + &result); + if(result == CURLE_AGAIN) { + if(connssl->connecting_state != ssl_connect_2_writing) + connssl->connecting_state = ssl_connect_2_reading; + DEBUGF(infof(data, "schannel: failed to receive handshake, " + "need more data")); + return CURLE_OK; + } + else if((result != CURLE_OK) || (nread == 0)) { + failf(data, "schannel: failed to receive handshake, " + "SSL/TLS connection failed"); + return CURLE_SSL_CONNECT_ERROR; + } + + /* increase encrypted data buffer offset */ + backend->encdata_offset += nread; + backend->encdata_is_incomplete = false; + DEBUGF(infof(data, "schannel: encrypted data got %zd", nread)); + } + + DEBUGF(infof(data, + "schannel: encrypted data buffer: offset %zu length %zu", + backend->encdata_offset, backend->encdata_length)); + + /* setup input buffers */ + InitSecBuffer(&inbuf[0], SECBUFFER_TOKEN, malloc(backend->encdata_offset), + curlx_uztoul(backend->encdata_offset)); + InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&inbuf_desc, inbuf, 2); + + /* setup output buffers */ + InitSecBuffer(&outbuf[0], SECBUFFER_TOKEN, NULL, 0); + InitSecBuffer(&outbuf[1], SECBUFFER_ALERT, NULL, 0); + InitSecBuffer(&outbuf[2], SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&outbuf_desc, outbuf, 3); + + if(!inbuf[0].pvBuffer) { + failf(data, "schannel: unable to allocate memory"); + return CURLE_OUT_OF_MEMORY; + } + + /* copy received handshake data into input buffer */ + memcpy(inbuf[0].pvBuffer, backend->encdata_buffer, + backend->encdata_offset); + + sspi_status = s_pSecFn->InitializeSecurityContext( + &backend->cred->cred_handle, &backend->ctxt->ctxt_handle, + backend->cred->sni_hostname, backend->req_flags, + 0, 0, &inbuf_desc, 0, NULL, + &outbuf_desc, &backend->ret_flags, &backend->ctxt->time_stamp); + + /* free buffer for received handshake data */ + Curl_safefree(inbuf[0].pvBuffer); + + /* check if the handshake was incomplete */ + if(sspi_status == SEC_E_INCOMPLETE_MESSAGE) { + backend->encdata_is_incomplete = true; + connssl->connecting_state = ssl_connect_2_reading; + DEBUGF(infof(data, + "schannel: received incomplete message, need more data")); + return CURLE_OK; + } + + /* If the server has requested a client certificate, attempt to continue + the handshake without one. This will allow connections to servers which + request a client certificate but do not require it. */ + if(sspi_status == SEC_I_INCOMPLETE_CREDENTIALS && + !(backend->req_flags & ISC_REQ_USE_SUPPLIED_CREDS)) { + backend->req_flags |= ISC_REQ_USE_SUPPLIED_CREDS; + connssl->connecting_state = ssl_connect_2_writing; + DEBUGF(infof(data, + "schannel: a client certificate has been requested")); + return CURLE_OK; + } + + /* check if the handshake needs to be continued */ + if(sspi_status == SEC_I_CONTINUE_NEEDED || sspi_status == SEC_E_OK) { + for(i = 0; i < 3; i++) { + /* search for handshake tokens that need to be send */ + if(outbuf[i].BufferType == SECBUFFER_TOKEN && outbuf[i].cbBuffer > 0) { + DEBUGF(infof(data, "schannel: sending next handshake data: " + "sending %lu bytes.", outbuf[i].cbBuffer)); + + /* send handshake token to server */ + written = Curl_conn_cf_send(cf->next, data, + outbuf[i].pvBuffer, outbuf[i].cbBuffer, + &result); + if((result != CURLE_OK) || + (outbuf[i].cbBuffer != (size_t) written)) { + failf(data, "schannel: failed to send next handshake data: " + "sent %zd of %lu bytes", written, outbuf[i].cbBuffer); + return CURLE_SSL_CONNECT_ERROR; + } + } + + /* free obsolete buffer */ + if(outbuf[i].pvBuffer) { + s_pSecFn->FreeContextBuffer(outbuf[i].pvBuffer); + } + } + } + else { + char buffer[STRERROR_LEN]; + switch(sspi_status) { + case SEC_E_INSUFFICIENT_MEMORY: + failf(data, "schannel: next InitializeSecurityContext failed: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + return CURLE_OUT_OF_MEMORY; + case SEC_E_WRONG_PRINCIPAL: + failf(data, "schannel: SNI or certificate check failed: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + return CURLE_PEER_FAILED_VERIFICATION; + case SEC_E_UNTRUSTED_ROOT: + failf(data, "schannel: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + return CURLE_PEER_FAILED_VERIFICATION; + /* + case SEC_E_INVALID_HANDLE: + case SEC_E_INVALID_TOKEN: + case SEC_E_LOGON_DENIED: + case SEC_E_TARGET_UNKNOWN: + case SEC_E_NO_AUTHENTICATING_AUTHORITY: + case SEC_E_INTERNAL_ERROR: + case SEC_E_NO_CREDENTIALS: + case SEC_E_UNSUPPORTED_FUNCTION: + case SEC_E_APPLICATION_PROTOCOL_MISMATCH: + */ + default: + failf(data, "schannel: next InitializeSecurityContext failed: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + return CURLE_SSL_CONNECT_ERROR; + } + } + + /* check if there was additional remaining encrypted data */ + if(inbuf[1].BufferType == SECBUFFER_EXTRA && inbuf[1].cbBuffer > 0) { + DEBUGF(infof(data, "schannel: encrypted data length: %lu", + inbuf[1].cbBuffer)); + /* + There are two cases where we could be getting extra data here: + 1) If we're renegotiating a connection and the handshake is already + complete (from the server perspective), it can encrypted app data + (not handshake data) in an extra buffer at this point. + 2) (sspi_status == SEC_I_CONTINUE_NEEDED) We are negotiating a + connection and this extra data is part of the handshake. + We should process the data immediately; waiting for the socket to + be ready may fail since the server is done sending handshake data. + */ + /* check if the remaining data is less than the total amount + and therefore begins after the already processed data */ + if(backend->encdata_offset > inbuf[1].cbBuffer) { + memmove(backend->encdata_buffer, + (backend->encdata_buffer + backend->encdata_offset) - + inbuf[1].cbBuffer, inbuf[1].cbBuffer); + backend->encdata_offset = inbuf[1].cbBuffer; + if(sspi_status == SEC_I_CONTINUE_NEEDED) { + doread = FALSE; + continue; + } + } + } + else { + backend->encdata_offset = 0; + } + break; + } + + /* check if the handshake needs to be continued */ + if(sspi_status == SEC_I_CONTINUE_NEEDED) { + connssl->connecting_state = ssl_connect_2_reading; + return CURLE_OK; + } + + /* check if the handshake is complete */ + if(sspi_status == SEC_E_OK) { + connssl->connecting_state = ssl_connect_3; + DEBUGF(infof(data, "schannel: SSL/TLS handshake complete")); + } + +#ifndef CURL_DISABLE_PROXY + pubkey_ptr = Curl_ssl_cf_is_proxy(cf)? + data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY]: + data->set.str[STRING_SSL_PINNEDPUBLICKEY]; +#else + pubkey_ptr = data->set.str[STRING_SSL_PINNEDPUBLICKEY]; +#endif + if(pubkey_ptr) { + result = schannel_pkp_pin_peer_pubkey(cf, data, pubkey_ptr); + if(result) { + failf(data, "SSL: public key does not match pinned public key"); + return result; + } + } + +#ifdef HAS_MANUAL_VERIFY_API + if(conn_config->verifypeer && backend->use_manual_cred_validation) { + /* Certificate verification also verifies the hostname if verifyhost */ + return Curl_verify_certificate(cf, data); + } +#endif + + /* Verify the hostname manually when certificate verification is disabled, + because in that case Schannel won't verify it. */ + if(!conn_config->verifypeer && conn_config->verifyhost) + return Curl_verify_host(cf, data); + + return CURLE_OK; +} + +static bool +valid_cert_encoding(const CERT_CONTEXT *cert_context) +{ + return (cert_context != NULL) && + ((cert_context->dwCertEncodingType & X509_ASN_ENCODING) != 0) && + (cert_context->pbCertEncoded != NULL) && + (cert_context->cbCertEncoded > 0); +} + +typedef bool(*Read_crt_func)(const CERT_CONTEXT *ccert_context, + bool reverse_order, void *arg); + +static void +traverse_cert_store(const CERT_CONTEXT *context, Read_crt_func func, + void *arg) +{ + const CERT_CONTEXT *current_context = NULL; + bool should_continue = true; + bool first = true; + bool reverse_order = false; + while(should_continue && + (current_context = CertEnumCertificatesInStore( + context->hCertStore, + current_context)) != NULL) { + /* Windows 11 22H2 OS Build 22621.674 or higher enumerates certificates in + leaf-to-root order while all previous versions of Windows enumerate + certificates in root-to-leaf order. Determine the order of enumeration + by comparing SECPKG_ATTR_REMOTE_CERT_CONTEXT's pbCertContext with the + first certificate's pbCertContext. */ + if(first && context->pbCertEncoded != current_context->pbCertEncoded) + reverse_order = true; + should_continue = func(current_context, reverse_order, arg); + first = false; + } + + if(current_context) + CertFreeCertificateContext(current_context); +} + +static bool +cert_counter_callback(const CERT_CONTEXT *ccert_context, bool reverse_order, + void *certs_count) +{ + (void)reverse_order; /* unused */ + if(valid_cert_encoding(ccert_context)) + (*(int *)certs_count)++; + return true; +} + +struct Adder_args +{ + struct Curl_easy *data; + CURLcode result; + int idx; + int certs_count; +}; + +static bool +add_cert_to_certinfo(const CERT_CONTEXT *ccert_context, bool reverse_order, + void *raw_arg) +{ + struct Adder_args *args = (struct Adder_args*)raw_arg; + args->result = CURLE_OK; + if(valid_cert_encoding(ccert_context)) { + const char *beg = (const char *) ccert_context->pbCertEncoded; + const char *end = beg + ccert_context->cbCertEncoded; + int insert_index = reverse_order ? (args->certs_count - 1) - args->idx : + args->idx; + args->result = Curl_extract_certinfo(args->data, insert_index, + beg, end); + args->idx++; + } + return args->result == CURLE_OK; +} + +static void schannel_session_free(void *sessionid, size_t idsize) +{ + /* this is expected to be called under sessionid lock */ + struct Curl_schannel_cred *cred = sessionid; + + (void)idsize; + if(cred) { + cred->refcount--; + if(cred->refcount == 0) { + s_pSecFn->FreeCredentialsHandle(&cred->cred_handle); + curlx_unicodefree(cred->sni_hostname); +#ifdef HAS_CLIENT_CERT_PATH + if(cred->client_cert_store) { + CertCloseStore(cred->client_cert_store, 0); + cred->client_cert_store = NULL; + } +#endif + Curl_safefree(cred); + } + } +} + +static CURLcode +schannel_connect_step3(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + CURLcode result = CURLE_OK; + SECURITY_STATUS sspi_status = SEC_E_OK; + CERT_CONTEXT *ccert_context = NULL; +#ifdef HAS_ALPN + SecPkgContext_ApplicationProtocol alpn_result; +#endif + + DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); + DEBUGASSERT(backend); + + DEBUGF(infof(data, + "schannel: SSL/TLS connection with %s port %d (step 3/3)", + connssl->peer.hostname, connssl->peer.port)); + + if(!backend->cred) + return CURLE_SSL_CONNECT_ERROR; + + /* check if the required context attributes are met */ + if(backend->ret_flags != backend->req_flags) { + if(!(backend->ret_flags & ISC_RET_SEQUENCE_DETECT)) + failf(data, "schannel: failed to setup sequence detection"); + if(!(backend->ret_flags & ISC_RET_REPLAY_DETECT)) + failf(data, "schannel: failed to setup replay detection"); + if(!(backend->ret_flags & ISC_RET_CONFIDENTIALITY)) + failf(data, "schannel: failed to setup confidentiality"); + if(!(backend->ret_flags & ISC_RET_ALLOCATED_MEMORY)) + failf(data, "schannel: failed to setup memory allocation"); + if(!(backend->ret_flags & ISC_RET_STREAM)) + failf(data, "schannel: failed to setup stream orientation"); + return CURLE_SSL_CONNECT_ERROR; + } + +#ifdef HAS_ALPN + if(backend->use_alpn) { + sspi_status = + s_pSecFn->QueryContextAttributes(&backend->ctxt->ctxt_handle, + SECPKG_ATTR_APPLICATION_PROTOCOL, + &alpn_result); + + if(sspi_status != SEC_E_OK) { + failf(data, "schannel: failed to retrieve ALPN result"); + return CURLE_SSL_CONNECT_ERROR; + } + + if(alpn_result.ProtoNegoStatus == + SecApplicationProtocolNegotiationStatus_Success) { + unsigned char prev_alpn = cf->conn->alpn; + + Curl_alpn_set_negotiated(cf, data, alpn_result.ProtocolId, + alpn_result.ProtocolIdSize); + if(backend->recv_renegotiating) { + if(prev_alpn != cf->conn->alpn && + prev_alpn != CURL_HTTP_VERSION_NONE) { + /* Renegotiation selected a different protocol now, we cannot + * deal with this */ + failf(data, "schannel: server selected an ALPN protocol too late"); + return CURLE_SSL_CONNECT_ERROR; + } + } + } + else { + if(!backend->recv_renegotiating) + Curl_alpn_set_negotiated(cf, data, NULL, 0); + } + } +#endif + + /* save the current session data for possible reuse */ + if(ssl_config->primary.sessionid) { + bool incache; + struct Curl_schannel_cred *old_cred = NULL; + + Curl_ssl_sessionid_lock(data); + incache = !(Curl_ssl_getsessionid(cf, data, &connssl->peer, + (void **)&old_cred, NULL)); + if(incache) { + if(old_cred != backend->cred) { + DEBUGF(infof(data, + "schannel: old credential handle is stale, removing")); + /* we're not taking old_cred ownership here, no refcount++ is needed */ + Curl_ssl_delsessionid(data, (void *)old_cred); + incache = FALSE; + } + } + if(!incache) { + /* Up ref count since call takes ownership */ + backend->cred->refcount++; + result = Curl_ssl_addsessionid(cf, data, &connssl->peer, backend->cred, + sizeof(struct Curl_schannel_cred), + schannel_session_free); + if(result) { + Curl_ssl_sessionid_unlock(data); + return result; + } + } + Curl_ssl_sessionid_unlock(data); + } + + if(data->set.ssl.certinfo) { + int certs_count = 0; + sspi_status = + s_pSecFn->QueryContextAttributes(&backend->ctxt->ctxt_handle, + SECPKG_ATTR_REMOTE_CERT_CONTEXT, + &ccert_context); + + if((sspi_status != SEC_E_OK) || !ccert_context) { + failf(data, "schannel: failed to retrieve remote cert context"); + return CURLE_PEER_FAILED_VERIFICATION; + } + + traverse_cert_store(ccert_context, cert_counter_callback, &certs_count); + + result = Curl_ssl_init_certinfo(data, certs_count); + if(!result) { + struct Adder_args args; + args.data = data; + args.idx = 0; + args.certs_count = certs_count; + traverse_cert_store(ccert_context, add_cert_to_certinfo, &args); + result = args.result; + } + CertFreeCertificateContext(ccert_context); + if(result) + return result; + } + + connssl->connecting_state = ssl_connect_done; + + return CURLE_OK; +} + +static CURLcode +schannel_connect_common(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool nonblocking, bool *done) +{ + CURLcode result; + struct ssl_connect_data *connssl = cf->ctx; + curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data); + timediff_t timeout_ms; + int what; + + /* check if the connection has already been established */ + if(ssl_connection_complete == connssl->state) { + *done = TRUE; + return CURLE_OK; + } + + if(ssl_connect_1 == connssl->connecting_state) { + /* check out how much more time we're allowed */ + timeout_ms = Curl_timeleft(data, NULL, TRUE); + + if(timeout_ms < 0) { + /* no need to continue if time already is up */ + failf(data, "SSL/TLS connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + + result = schannel_connect_step1(cf, data); + if(result) + return result; + } + + while(ssl_connect_2 == connssl->connecting_state || + ssl_connect_2_reading == connssl->connecting_state || + ssl_connect_2_writing == connssl->connecting_state) { + + /* check out how much more time we're allowed */ + timeout_ms = Curl_timeleft(data, NULL, TRUE); + + if(timeout_ms < 0) { + /* no need to continue if time already is up */ + failf(data, "SSL/TLS connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + + /* if ssl is expecting something, check if it's available. */ + if(connssl->connecting_state == ssl_connect_2_reading + || connssl->connecting_state == ssl_connect_2_writing) { + + curl_socket_t writefd = ssl_connect_2_writing == + connssl->connecting_state ? sockfd : CURL_SOCKET_BAD; + curl_socket_t readfd = ssl_connect_2_reading == + connssl->connecting_state ? sockfd : CURL_SOCKET_BAD; + + what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, + nonblocking ? 0 : timeout_ms); + if(what < 0) { + /* fatal error */ + failf(data, "select/poll on SSL/TLS socket, errno: %d", SOCKERRNO); + return CURLE_SSL_CONNECT_ERROR; + } + else if(0 == what) { + if(nonblocking) { + *done = FALSE; + return CURLE_OK; + } + else { + /* timeout */ + failf(data, "SSL/TLS connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + } + /* socket is readable or writable */ + } + + /* Run transaction, and return to the caller if it failed or if + * this connection is part of a multi handle and this loop would + * execute again. This permits the owner of a multi handle to + * abort a connection attempt before step2 has completed while + * ensuring that a client using select() or epoll() will always + * have a valid fdset to wait on. + */ + result = schannel_connect_step2(cf, data); + if(result || (nonblocking && + (ssl_connect_2 == connssl->connecting_state || + ssl_connect_2_reading == connssl->connecting_state || + ssl_connect_2_writing == connssl->connecting_state))) + return result; + + } /* repeat step2 until all transactions are done. */ + + if(ssl_connect_3 == connssl->connecting_state) { + result = schannel_connect_step3(cf, data); + if(result) + return result; + } + + if(ssl_connect_done == connssl->connecting_state) { + connssl->state = ssl_connection_complete; + +#ifdef SECPKG_ATTR_ENDPOINT_BINDINGS + /* When SSPI is used in combination with Schannel + * we need the Schannel context to create the Schannel + * binding to pass the IIS extended protection checks. + * Available on Windows 7 or later. + */ + { + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + DEBUGASSERT(backend); + cf->conn->sslContext = &backend->ctxt->ctxt_handle; + } +#endif + + *done = TRUE; + } + else + *done = FALSE; + + /* reset our connection state machine */ + connssl->connecting_state = ssl_connect_1; + + return CURLE_OK; +} + +static ssize_t +schannel_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *buf, size_t len, CURLcode *err) +{ + ssize_t written = -1; + size_t data_len = 0; + unsigned char *ptr = NULL; + struct ssl_connect_data *connssl = cf->ctx; + SecBuffer outbuf[4]; + SecBufferDesc outbuf_desc; + SECURITY_STATUS sspi_status = SEC_E_OK; + CURLcode result; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + + DEBUGASSERT(backend); + + /* check if the maximum stream sizes were queried */ + if(backend->stream_sizes.cbMaximumMessage == 0) { + sspi_status = s_pSecFn->QueryContextAttributes( + &backend->ctxt->ctxt_handle, + SECPKG_ATTR_STREAM_SIZES, + &backend->stream_sizes); + if(sspi_status != SEC_E_OK) { + *err = CURLE_SEND_ERROR; + return -1; + } + } + + /* check if the buffer is longer than the maximum message length */ + if(len > backend->stream_sizes.cbMaximumMessage) { + len = backend->stream_sizes.cbMaximumMessage; + } + + /* calculate the complete message length and allocate a buffer for it */ + data_len = backend->stream_sizes.cbHeader + len + + backend->stream_sizes.cbTrailer; + ptr = (unsigned char *) malloc(data_len); + if(!ptr) { + *err = CURLE_OUT_OF_MEMORY; + return -1; + } + + /* setup output buffers (header, data, trailer, empty) */ + InitSecBuffer(&outbuf[0], SECBUFFER_STREAM_HEADER, + ptr, backend->stream_sizes.cbHeader); + InitSecBuffer(&outbuf[1], SECBUFFER_DATA, + ptr + backend->stream_sizes.cbHeader, curlx_uztoul(len)); + InitSecBuffer(&outbuf[2], SECBUFFER_STREAM_TRAILER, + ptr + backend->stream_sizes.cbHeader + len, + backend->stream_sizes.cbTrailer); + InitSecBuffer(&outbuf[3], SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&outbuf_desc, outbuf, 4); + + /* copy data into output buffer */ + memcpy(outbuf[1].pvBuffer, buf, len); + + /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375390.aspx */ + sspi_status = s_pSecFn->EncryptMessage(&backend->ctxt->ctxt_handle, 0, + &outbuf_desc, 0); + + /* check if the message was encrypted */ + if(sspi_status == SEC_E_OK) { + written = 0; + + /* send the encrypted message including header, data and trailer */ + len = outbuf[0].cbBuffer + outbuf[1].cbBuffer + outbuf[2].cbBuffer; + + /* + It's important to send the full message which includes the header, + encrypted payload, and trailer. Until the client receives all the + data a coherent message has not been delivered and the client + can't read any of it. + + If we wanted to buffer the unwritten encrypted bytes, we would + tell the client that all data it has requested to be sent has been + sent. The unwritten encrypted bytes would be the first bytes to + send on the next invocation. + Here's the catch with this - if we tell the client that all the + bytes have been sent, will the client call this method again to + send the buffered data? Looking at who calls this function, it + seems the answer is NO. + */ + + /* send entire message or fail */ + while(len > (size_t)written) { + ssize_t this_write = 0; + int what; + timediff_t timeout_ms = Curl_timeleft(data, NULL, FALSE); + if(timeout_ms < 0) { + /* we already got the timeout */ + failf(data, "schannel: timed out sending data " + "(bytes sent: %zd)", written); + *err = CURLE_OPERATION_TIMEDOUT; + written = -1; + break; + } + else if(!timeout_ms) + timeout_ms = TIMEDIFF_T_MAX; + what = SOCKET_WRITABLE(Curl_conn_cf_get_socket(cf, data), timeout_ms); + if(what < 0) { + /* fatal error */ + failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); + *err = CURLE_SEND_ERROR; + written = -1; + break; + } + else if(0 == what) { + failf(data, "schannel: timed out sending data " + "(bytes sent: %zd)", written); + *err = CURLE_OPERATION_TIMEDOUT; + written = -1; + break; + } + /* socket is writable */ + + this_write = Curl_conn_cf_send(cf->next, data, + ptr + written, len - written, + &result); + if(result == CURLE_AGAIN) + continue; + else if(result != CURLE_OK) { + *err = result; + written = -1; + break; + } + + written += this_write; + } + } + else if(sspi_status == SEC_E_INSUFFICIENT_MEMORY) { + *err = CURLE_OUT_OF_MEMORY; + } + else{ + *err = CURLE_SEND_ERROR; + } + + Curl_safefree(ptr); + + if(len == (size_t)written) + /* Encrypted message including header, data and trailer entirely sent. + The return value is the number of unencrypted bytes that were sent. */ + written = outbuf[1].cbBuffer; + + return written; +} + +static ssize_t +schannel_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, CURLcode *err) +{ + size_t size = 0; + ssize_t nread = -1; + struct ssl_connect_data *connssl = cf->ctx; + unsigned char *reallocated_buffer; + size_t reallocated_length; + bool done = FALSE; + SecBuffer inbuf[4]; + SecBufferDesc inbuf_desc; + SECURITY_STATUS sspi_status = SEC_E_OK; + /* we want the length of the encrypted buffer to be at least large enough + that it can hold all the bytes requested and some TLS record overhead. */ + size_t min_encdata_length = len + CURL_SCHANNEL_BUFFER_FREE_SIZE; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + + DEBUGASSERT(backend); + + /**************************************************************************** + * Don't return or set backend->recv_unrecoverable_err unless in the cleanup. + * The pattern for return error is set *err, optional infof, goto cleanup. + * + * Our priority is to always return as much decrypted data to the caller as + * possible, even if an error occurs. The state of the decrypted buffer must + * always be valid. Transfer of decrypted data to the caller's buffer is + * handled in the cleanup. + */ + + DEBUGF(infof(data, "schannel: client wants to read %zu bytes", len)); + *err = CURLE_OK; + + if(len && len <= backend->decdata_offset) { + infof(data, "schannel: enough decrypted data is already available"); + goto cleanup; + } + else if(backend->recv_unrecoverable_err) { + *err = backend->recv_unrecoverable_err; + infof(data, "schannel: an unrecoverable error occurred in a prior call"); + goto cleanup; + } + else if(backend->recv_sspi_close_notify) { + /* once a server has indicated shutdown there is no more encrypted data */ + infof(data, "schannel: server indicated shutdown in a prior call"); + goto cleanup; + } + /* It's debatable what to return when !len. Regardless we can't return + immediately because there may be data to decrypt (in the case we want to + decrypt all encrypted cached data) so handle !len later in cleanup. + */ + else if(len && !backend->recv_connection_closed) { + /* increase enc buffer in order to fit the requested amount of data */ + size = backend->encdata_length - backend->encdata_offset; + if(size < CURL_SCHANNEL_BUFFER_FREE_SIZE || + backend->encdata_length < min_encdata_length) { + reallocated_length = backend->encdata_offset + + CURL_SCHANNEL_BUFFER_FREE_SIZE; + if(reallocated_length < min_encdata_length) { + reallocated_length = min_encdata_length; + } + reallocated_buffer = realloc(backend->encdata_buffer, + reallocated_length); + if(!reallocated_buffer) { + *err = CURLE_OUT_OF_MEMORY; + failf(data, "schannel: unable to re-allocate memory"); + goto cleanup; + } + + backend->encdata_buffer = reallocated_buffer; + backend->encdata_length = reallocated_length; + size = backend->encdata_length - backend->encdata_offset; + DEBUGF(infof(data, "schannel: encdata_buffer resized %zu", + backend->encdata_length)); + } + + DEBUGF(infof(data, + "schannel: encrypted data buffer: offset %zu length %zu", + backend->encdata_offset, backend->encdata_length)); + + /* read encrypted data from socket */ + nread = Curl_conn_cf_recv(cf->next, data, + (char *)(backend->encdata_buffer + + backend->encdata_offset), + size, err); + if(*err) { + nread = -1; + if(*err == CURLE_AGAIN) + DEBUGF(infof(data, + "schannel: recv returned CURLE_AGAIN")); + else if(*err == CURLE_RECV_ERROR) + infof(data, "schannel: recv returned CURLE_RECV_ERROR"); + else + infof(data, "schannel: recv returned error %d", *err); + } + else if(nread == 0) { + backend->recv_connection_closed = true; + DEBUGF(infof(data, "schannel: server closed the connection")); + } + else if(nread > 0) { + backend->encdata_offset += (size_t)nread; + backend->encdata_is_incomplete = false; + DEBUGF(infof(data, "schannel: encrypted data got %zd", nread)); + } + } + + DEBUGF(infof(data, + "schannel: encrypted data buffer: offset %zu length %zu", + backend->encdata_offset, backend->encdata_length)); + + /* decrypt loop */ + while(backend->encdata_offset > 0 && sspi_status == SEC_E_OK && + (!len || backend->decdata_offset < len || + backend->recv_connection_closed)) { + /* prepare data buffer for DecryptMessage call */ + InitSecBuffer(&inbuf[0], SECBUFFER_DATA, backend->encdata_buffer, + curlx_uztoul(backend->encdata_offset)); + + /* we need 3 more empty input buffers for possible output */ + InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0); + InitSecBuffer(&inbuf[2], SECBUFFER_EMPTY, NULL, 0); + InitSecBuffer(&inbuf[3], SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&inbuf_desc, inbuf, 4); + + /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375348.aspx + */ + sspi_status = s_pSecFn->DecryptMessage(&backend->ctxt->ctxt_handle, + &inbuf_desc, 0, NULL); + + /* check if everything went fine (server may want to renegotiate + or shutdown the connection context) */ + if(sspi_status == SEC_E_OK || sspi_status == SEC_I_RENEGOTIATE || + sspi_status == SEC_I_CONTEXT_EXPIRED) { + /* check for successfully decrypted data, even before actual + renegotiation or shutdown of the connection context */ + if(inbuf[1].BufferType == SECBUFFER_DATA) { + DEBUGF(infof(data, "schannel: decrypted data length: %lu", + inbuf[1].cbBuffer)); + + /* increase buffer in order to fit the received amount of data */ + size = inbuf[1].cbBuffer > CURL_SCHANNEL_BUFFER_FREE_SIZE ? + inbuf[1].cbBuffer : CURL_SCHANNEL_BUFFER_FREE_SIZE; + if(backend->decdata_length - backend->decdata_offset < size || + backend->decdata_length < len) { + /* increase internal decrypted data buffer */ + reallocated_length = backend->decdata_offset + size; + /* make sure that the requested amount of data fits */ + if(reallocated_length < len) { + reallocated_length = len; + } + reallocated_buffer = realloc(backend->decdata_buffer, + reallocated_length); + if(!reallocated_buffer) { + *err = CURLE_OUT_OF_MEMORY; + failf(data, "schannel: unable to re-allocate memory"); + goto cleanup; + } + backend->decdata_buffer = reallocated_buffer; + backend->decdata_length = reallocated_length; + } + + /* copy decrypted data to internal buffer */ + size = inbuf[1].cbBuffer; + if(size) { + memcpy(backend->decdata_buffer + backend->decdata_offset, + inbuf[1].pvBuffer, size); + backend->decdata_offset += size; + } + + DEBUGF(infof(data, "schannel: decrypted data added: %zu", size)); + DEBUGF(infof(data, + "schannel: decrypted cached: offset %zu length %zu", + backend->decdata_offset, backend->decdata_length)); + } + + /* check for remaining encrypted data */ + if(inbuf[3].BufferType == SECBUFFER_EXTRA && inbuf[3].cbBuffer > 0) { + DEBUGF(infof(data, "schannel: encrypted data length: %lu", + inbuf[3].cbBuffer)); + + /* check if the remaining data is less than the total amount + * and therefore begins after the already processed data + */ + if(backend->encdata_offset > inbuf[3].cbBuffer) { + /* move remaining encrypted data forward to the beginning of + buffer */ + memmove(backend->encdata_buffer, + (backend->encdata_buffer + backend->encdata_offset) - + inbuf[3].cbBuffer, inbuf[3].cbBuffer); + backend->encdata_offset = inbuf[3].cbBuffer; + } + + DEBUGF(infof(data, + "schannel: encrypted cached: offset %zu length %zu", + backend->encdata_offset, backend->encdata_length)); + } + else { + /* reset encrypted buffer offset, because there is no data remaining */ + backend->encdata_offset = 0; + } + + /* check if server wants to renegotiate the connection context */ + if(sspi_status == SEC_I_RENEGOTIATE) { + infof(data, "schannel: remote party requests renegotiation"); + if(*err && *err != CURLE_AGAIN) { + infof(data, "schannel: can't renegotiate, an error is pending"); + goto cleanup; + } + + /* begin renegotiation */ + infof(data, "schannel: renegotiating SSL/TLS connection"); + connssl->state = ssl_connection_negotiating; + connssl->connecting_state = ssl_connect_2_writing; + backend->recv_renegotiating = true; + *err = schannel_connect_common(cf, data, FALSE, &done); + backend->recv_renegotiating = false; + if(*err) { + infof(data, "schannel: renegotiation failed"); + goto cleanup; + } + /* now retry receiving data */ + sspi_status = SEC_E_OK; + infof(data, "schannel: SSL/TLS connection renegotiated"); + continue; + } + /* check if the server closed the connection */ + else if(sspi_status == SEC_I_CONTEXT_EXPIRED) { + /* In Windows 2000 SEC_I_CONTEXT_EXPIRED (close_notify) is not + returned so we have to work around that in cleanup. */ + backend->recv_sspi_close_notify = true; + if(!backend->recv_connection_closed) + backend->recv_connection_closed = true; + infof(data, + "schannel: server close notification received (close_notify)"); + goto cleanup; + } + } + else if(sspi_status == SEC_E_INCOMPLETE_MESSAGE) { + backend->encdata_is_incomplete = true; + if(!*err) + *err = CURLE_AGAIN; + infof(data, "schannel: failed to decrypt data, need more data"); + goto cleanup; + } + else { +#ifndef CURL_DISABLE_VERBOSE_STRINGS + char buffer[STRERROR_LEN]; + infof(data, "schannel: failed to read data from server: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); +#endif + *err = CURLE_RECV_ERROR; + goto cleanup; + } + } + + DEBUGF(infof(data, + "schannel: encrypted data buffer: offset %zu length %zu", + backend->encdata_offset, backend->encdata_length)); + + DEBUGF(infof(data, + "schannel: decrypted data buffer: offset %zu length %zu", + backend->decdata_offset, backend->decdata_length)); + +cleanup: + /* Warning- there is no guarantee the encdata state is valid at this point */ + DEBUGF(infof(data, "schannel: schannel_recv cleanup")); + + /* Error if the connection has closed without a close_notify. + + The behavior here is a matter of debate. We don't want to be vulnerable + to a truncation attack however there's some browser precedent for + ignoring the close_notify for compatibility reasons. + + Additionally, Windows 2000 (v5.0) is a special case since it seems it + doesn't return close_notify. In that case if the connection was closed we + assume it was graceful (close_notify) since there doesn't seem to be a + way to tell. + */ + if(len && !backend->decdata_offset && backend->recv_connection_closed && + !backend->recv_sspi_close_notify) { + bool isWin2k = curlx_verify_windows_version(5, 0, 0, PLATFORM_WINNT, + VERSION_EQUAL); + + if(isWin2k && sspi_status == SEC_E_OK) + backend->recv_sspi_close_notify = true; + else { + *err = CURLE_RECV_ERROR; + infof(data, "schannel: server closed abruptly (missing close_notify)"); + } + } + + /* Any error other than CURLE_AGAIN is an unrecoverable error. */ + if(*err && *err != CURLE_AGAIN) + backend->recv_unrecoverable_err = *err; + + size = len < backend->decdata_offset ? len : backend->decdata_offset; + if(size) { + memcpy(buf, backend->decdata_buffer, size); + memmove(backend->decdata_buffer, backend->decdata_buffer + size, + backend->decdata_offset - size); + backend->decdata_offset -= size; + DEBUGF(infof(data, "schannel: decrypted data returned %zu", size)); + DEBUGF(infof(data, + "schannel: decrypted data buffer: offset %zu length %zu", + backend->decdata_offset, backend->decdata_length)); + *err = CURLE_OK; + return (ssize_t)size; + } + + if(!*err && !backend->recv_connection_closed) + *err = CURLE_AGAIN; + + /* It's debatable what to return when !len. We could return whatever error + we got from decryption but instead we override here so the return is + consistent. + */ + if(!len) + *err = CURLE_OK; + + return *err ? -1 : 0; +} + +static CURLcode schannel_connect_nonblocking(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + return schannel_connect_common(cf, data, TRUE, done); +} + +static CURLcode schannel_connect(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURLcode result; + bool done = FALSE; + + result = schannel_connect_common(cf, data, FALSE, &done); + if(result) + return result; + + DEBUGASSERT(done); + + return CURLE_OK; +} + +static bool schannel_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + const struct ssl_connect_data *connssl = cf->ctx; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + + (void)data; + DEBUGASSERT(backend); + + if(backend->ctxt) /* SSL/TLS is in use */ + return (backend->decdata_offset > 0 || + (backend->encdata_offset > 0 && !backend->encdata_is_incomplete) || + backend->recv_connection_closed || + backend->recv_sspi_close_notify || + backend->recv_unrecoverable_err); + else + return FALSE; +} + +/* shut down the SSL connection and clean up related memory. + this function can be called multiple times on the same connection including + if the SSL connection failed (eg connection made but failed handshake). */ +static int schannel_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + /* See https://msdn.microsoft.com/en-us/library/windows/desktop/aa380138.aspx + * Shutting Down an Schannel Connection + */ + struct ssl_connect_data *connssl = cf->ctx; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + + DEBUGASSERT(data); + DEBUGASSERT(backend); + + if(backend->ctxt) { + infof(data, "schannel: shutting down SSL/TLS connection with %s port %d", + connssl->peer.hostname, connssl->peer.port); + } + + if(backend->cred && backend->ctxt) { + SecBufferDesc BuffDesc; + SecBuffer Buffer; + SECURITY_STATUS sspi_status; + SecBuffer outbuf; + SecBufferDesc outbuf_desc; + CURLcode result; + DWORD dwshut = SCHANNEL_SHUTDOWN; + + InitSecBuffer(&Buffer, SECBUFFER_TOKEN, &dwshut, sizeof(dwshut)); + InitSecBufferDesc(&BuffDesc, &Buffer, 1); + + sspi_status = s_pSecFn->ApplyControlToken(&backend->ctxt->ctxt_handle, + &BuffDesc); + + if(sspi_status != SEC_E_OK) { + char buffer[STRERROR_LEN]; + failf(data, "schannel: ApplyControlToken failure: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + } + + /* setup output buffer */ + InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&outbuf_desc, &outbuf, 1); + + sspi_status = s_pSecFn->InitializeSecurityContext( + &backend->cred->cred_handle, + &backend->ctxt->ctxt_handle, + backend->cred->sni_hostname, + backend->req_flags, + 0, + 0, + NULL, + 0, + &backend->ctxt->ctxt_handle, + &outbuf_desc, + &backend->ret_flags, + &backend->ctxt->time_stamp); + + if((sspi_status == SEC_E_OK) || (sspi_status == SEC_I_CONTEXT_EXPIRED)) { + /* send close message which is in output buffer */ + ssize_t written = Curl_conn_cf_send(cf->next, data, + outbuf.pvBuffer, outbuf.cbBuffer, + &result); + s_pSecFn->FreeContextBuffer(outbuf.pvBuffer); + if((result != CURLE_OK) || (outbuf.cbBuffer != (size_t) written)) { + infof(data, "schannel: failed to send close msg: %s" + " (bytes written: %zd)", curl_easy_strerror(result), written); + } + } + } + + /* free SSPI Schannel API security context handle */ + if(backend->ctxt) { + DEBUGF(infof(data, "schannel: clear security context handle")); + s_pSecFn->DeleteSecurityContext(&backend->ctxt->ctxt_handle); + Curl_safefree(backend->ctxt); + } + + /* free SSPI Schannel API credential handle */ + if(backend->cred) { + Curl_ssl_sessionid_lock(data); + schannel_session_free(backend->cred, 0); + Curl_ssl_sessionid_unlock(data); + backend->cred = NULL; + } + + /* free internal buffer for received encrypted data */ + if(backend->encdata_buffer) { + Curl_safefree(backend->encdata_buffer); + backend->encdata_length = 0; + backend->encdata_offset = 0; + backend->encdata_is_incomplete = false; + } + + /* free internal buffer for received decrypted data */ + if(backend->decdata_buffer) { + Curl_safefree(backend->decdata_buffer); + backend->decdata_length = 0; + backend->decdata_offset = 0; + } + + return CURLE_OK; +} + +static void schannel_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + schannel_shutdown(cf, data); +} + +static int schannel_init(void) +{ + return (Curl_sspi_global_init() == CURLE_OK ? 1 : 0); +} + +static void schannel_cleanup(void) +{ + Curl_sspi_global_cleanup(); +} + +static size_t schannel_version(char *buffer, size_t size) +{ + size = msnprintf(buffer, size, "Schannel"); + + return size; +} + +static CURLcode schannel_random(struct Curl_easy *data UNUSED_PARAM, + unsigned char *entropy, size_t length) +{ + (void)data; + + return Curl_win32_random(entropy, length); +} + +static CURLcode schannel_pkp_pin_peer_pubkey(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *pinnedpubkey) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + CERT_CONTEXT *pCertContextServer = NULL; + + /* Result is returned to caller */ + CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; + + DEBUGASSERT(backend); + + /* if a path wasn't specified, don't pin */ + if(!pinnedpubkey) + return CURLE_OK; + + do { + SECURITY_STATUS sspi_status; + const char *x509_der; + DWORD x509_der_len; + struct Curl_X509certificate x509_parsed; + struct Curl_asn1Element *pubkey; + + sspi_status = + s_pSecFn->QueryContextAttributes(&backend->ctxt->ctxt_handle, + SECPKG_ATTR_REMOTE_CERT_CONTEXT, + &pCertContextServer); + + if((sspi_status != SEC_E_OK) || !pCertContextServer) { + char buffer[STRERROR_LEN]; + failf(data, "schannel: Failed to read remote certificate context: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + break; /* failed */ + } + + + if(!(((pCertContextServer->dwCertEncodingType & X509_ASN_ENCODING) != 0) && + (pCertContextServer->cbCertEncoded > 0))) + break; + + x509_der = (const char *)pCertContextServer->pbCertEncoded; + x509_der_len = pCertContextServer->cbCertEncoded; + memset(&x509_parsed, 0, sizeof(x509_parsed)); + if(Curl_parseX509(&x509_parsed, x509_der, x509_der + x509_der_len)) + break; + + pubkey = &x509_parsed.subjectPublicKeyInfo; + if(!pubkey->header || pubkey->end <= pubkey->header) { + failf(data, "SSL: failed retrieving public key from server certificate"); + break; + } + + result = Curl_pin_peer_pubkey(data, + pinnedpubkey, + (const unsigned char *)pubkey->header, + (size_t)(pubkey->end - pubkey->header)); + if(result) { + failf(data, "SSL: public key does not match pinned public key"); + } + } while(0); + + if(pCertContextServer) + CertFreeCertificateContext(pCertContextServer); + + return result; +} + +static void schannel_checksum(const unsigned char *input, + size_t inputlen, + unsigned char *checksum, + size_t checksumlen, + DWORD provType, + const unsigned int algId) +{ + HCRYPTPROV hProv = 0; + HCRYPTHASH hHash = 0; + DWORD cbHashSize = 0; + DWORD dwHashSizeLen = (DWORD)sizeof(cbHashSize); + DWORD dwChecksumLen = (DWORD)checksumlen; + + /* since this can fail in multiple ways, zero memory first so we never + * return old data + */ + memset(checksum, 0, checksumlen); + + if(!CryptAcquireContext(&hProv, NULL, NULL, provType, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + return; /* failed */ + + do { + if(!CryptCreateHash(hProv, algId, 0, 0, &hHash)) + break; /* failed */ + + if(!CryptHashData(hHash, input, (DWORD)inputlen, 0)) + break; /* failed */ + + /* get hash size */ + if(!CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE *)&cbHashSize, + &dwHashSizeLen, 0)) + break; /* failed */ + + /* check hash size */ + if(checksumlen < cbHashSize) + break; /* failed */ + + if(CryptGetHashParam(hHash, HP_HASHVAL, checksum, &dwChecksumLen, 0)) + break; /* failed */ + } while(0); + + if(hHash) + CryptDestroyHash(hHash); + + if(hProv) + CryptReleaseContext(hProv, 0); +} + +static CURLcode schannel_sha256sum(const unsigned char *input, + size_t inputlen, + unsigned char *sha256sum, + size_t sha256len) +{ + schannel_checksum(input, inputlen, sha256sum, sha256len, + PROV_RSA_AES, CALG_SHA_256); + return CURLE_OK; +} + +static void *schannel_get_internals(struct ssl_connect_data *connssl, + CURLINFO info UNUSED_PARAM) +{ + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + (void)info; + DEBUGASSERT(backend); + return &backend->ctxt->ctxt_handle; +} + +HCERTSTORE Curl_schannel_get_cached_cert_store(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct Curl_multi *multi = data->multi; + const struct curl_blob *ca_info_blob = conn_config->ca_info_blob; + struct schannel_multi_ssl_backend_data *mbackend; + const struct ssl_general_config *cfg = &data->set.general_ssl; + timediff_t timeout_ms; + timediff_t elapsed_ms; + struct curltime now; + unsigned char info_blob_digest[CURL_SHA256_DIGEST_LENGTH]; + + DEBUGASSERT(multi); + + if(!multi || !multi->ssl_backend_data) { + return NULL; + } + + mbackend = (struct schannel_multi_ssl_backend_data *)multi->ssl_backend_data; + if(!mbackend->cert_store) { + return NULL; + } + + /* zero ca_cache_timeout completely disables caching */ + if(!cfg->ca_cache_timeout) { + return NULL; + } + + /* check for cache timeout by using the cached_x509_store_expired timediff + calculation pattern from openssl.c. + negative timeout means retain forever. */ + timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000; + if(timeout_ms >= 0) { + now = Curl_now(); + elapsed_ms = Curl_timediff(now, mbackend->time); + if(elapsed_ms >= timeout_ms) { + return NULL; + } + } + + if(ca_info_blob) { + if(!mbackend->CAinfo_blob_digest) { + return NULL; + } + if(mbackend->CAinfo_blob_size != ca_info_blob->len) { + return NULL; + } + schannel_sha256sum((const unsigned char *)ca_info_blob->data, + ca_info_blob->len, + info_blob_digest, + CURL_SHA256_DIGEST_LENGTH); + if(memcmp(mbackend->CAinfo_blob_digest, + info_blob_digest, + CURL_SHA256_DIGEST_LENGTH)) { + return NULL; + } + } + else { + if(!conn_config->CAfile || !mbackend->CAfile || + strcmp(mbackend->CAfile, conn_config->CAfile)) { + return NULL; + } + } + + return mbackend->cert_store; +} + +bool Curl_schannel_set_cached_cert_store(struct Curl_cfilter *cf, + const struct Curl_easy *data, + HCERTSTORE cert_store) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct Curl_multi *multi = data->multi; + const struct curl_blob *ca_info_blob = conn_config->ca_info_blob; + struct schannel_multi_ssl_backend_data *mbackend; + unsigned char *CAinfo_blob_digest = NULL; + size_t CAinfo_blob_size = 0; + char *CAfile = NULL; + + DEBUGASSERT(multi); + + if(!multi) { + return false; + } + + if(!multi->ssl_backend_data) { + multi->ssl_backend_data = + calloc(1, sizeof(struct schannel_multi_ssl_backend_data)); + if(!multi->ssl_backend_data) { + return false; + } + } + + mbackend = (struct schannel_multi_ssl_backend_data *)multi->ssl_backend_data; + + + if(ca_info_blob) { + CAinfo_blob_digest = malloc(CURL_SHA256_DIGEST_LENGTH); + if(!CAinfo_blob_digest) { + return false; + } + schannel_sha256sum((const unsigned char *)ca_info_blob->data, + ca_info_blob->len, + CAinfo_blob_digest, + CURL_SHA256_DIGEST_LENGTH); + CAinfo_blob_size = ca_info_blob->len; + } + else { + if(conn_config->CAfile) { + CAfile = strdup(conn_config->CAfile); + if(!CAfile) { + return false; + } + } + } + + /* free old cache data */ + if(mbackend->cert_store) { + CertCloseStore(mbackend->cert_store, 0); + } + free(mbackend->CAinfo_blob_digest); + free(mbackend->CAfile); + + mbackend->time = Curl_now(); + mbackend->cert_store = cert_store; + mbackend->CAinfo_blob_digest = CAinfo_blob_digest; + mbackend->CAinfo_blob_size = CAinfo_blob_size; + mbackend->CAfile = CAfile; + return true; +} + +static void schannel_free_multi_ssl_backend_data( + struct multi_ssl_backend_data *msbd) +{ + struct schannel_multi_ssl_backend_data *mbackend = + (struct schannel_multi_ssl_backend_data*)msbd; + if(mbackend->cert_store) { + CertCloseStore(mbackend->cert_store, 0); + } + free(mbackend->CAinfo_blob_digest); + free(mbackend->CAfile); + free(mbackend); +} + +const struct Curl_ssl Curl_ssl_schannel = { + { CURLSSLBACKEND_SCHANNEL, "schannel" }, /* info */ + + SSLSUPP_CERTINFO | +#ifdef HAS_MANUAL_VERIFY_API + SSLSUPP_CAINFO_BLOB | +#endif + SSLSUPP_PINNEDPUBKEY | + SSLSUPP_TLS13_CIPHERSUITES | + SSLSUPP_HTTPS_PROXY, + + sizeof(struct schannel_ssl_backend_data), + + schannel_init, /* init */ + schannel_cleanup, /* cleanup */ + schannel_version, /* version */ + Curl_none_check_cxn, /* check_cxn */ + schannel_shutdown, /* shutdown */ + schannel_data_pending, /* data_pending */ + schannel_random, /* random */ + Curl_none_cert_status_request, /* cert_status_request */ + schannel_connect, /* connect */ + schannel_connect_nonblocking, /* connect_nonblocking */ + Curl_ssl_adjust_pollset, /* adjust_pollset */ + schannel_get_internals, /* get_internals */ + schannel_close, /* close_one */ + Curl_none_close_all, /* close_all */ + Curl_none_set_engine, /* set_engine */ + Curl_none_set_engine_default, /* set_engine_default */ + Curl_none_engines_list, /* engines_list */ + Curl_none_false_start, /* false_start */ + schannel_sha256sum, /* sha256sum */ + NULL, /* associate_connection */ + NULL, /* disassociate_connection */ + schannel_free_multi_ssl_backend_data, /* free_multi_ssl_backend_data */ + schannel_recv, /* recv decrypted data */ + schannel_send, /* send data to encrypt */ +}; + +#endif /* USE_SCHANNEL */ diff --git a/third_party/curl/lib/vtls/schannel.h b/third_party/curl/lib/vtls/schannel.h new file mode 100644 index 0000000..b26334b --- /dev/null +++ b/third_party/curl/lib/vtls/schannel.h @@ -0,0 +1,86 @@ +#ifndef HEADER_CURL_SCHANNEL_H +#define HEADER_CURL_SCHANNEL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Marc Hoersken, , et al. + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_SCHANNEL + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4201) +#endif +#include +#ifdef _MSC_VER +#pragma warning(pop) +#endif +/* Wincrypt must be included before anything that could include OpenSSL. */ +#if defined(USE_WIN32_CRYPTO) +#include +/* Undefine wincrypt conflicting symbols for BoringSSL. */ +#undef X509_NAME +#undef X509_EXTENSIONS +#undef PKCS7_ISSUER_AND_SERIAL +#undef PKCS7_SIGNER_INFO +#undef OCSP_REQUEST +#undef OCSP_RESPONSE +#endif + +#include +#include +#include "curl_sspi.h" + +#include "cfilters.h" +#include "urldata.h" + +/* has been included via the above . + * Or in case of ldap.c, it was included via . + * And since has this: + * #define X509_NAME ((LPCSTR) 7) + * + * And in BoringSSL's there is: + * typedef struct X509_name_st X509_NAME; + * etc. + * + * this will cause all kinds of C-preprocessing paste errors in + * BoringSSL's : So just undefine those defines here + * (and only here). + */ +#if defined(OPENSSL_IS_BORINGSSL) +# undef X509_NAME +# undef X509_CERT_PAIR +# undef X509_EXTENSIONS +#endif + +extern const struct Curl_ssl Curl_ssl_schannel; + +CURLcode Curl_verify_host(struct Curl_cfilter *cf, + struct Curl_easy *data); + +CURLcode Curl_verify_certificate(struct Curl_cfilter *cf, + struct Curl_easy *data); + +#endif /* USE_SCHANNEL */ +#endif /* HEADER_CURL_SCHANNEL_H */ diff --git a/third_party/curl/lib/vtls/schannel_int.h b/third_party/curl/lib/vtls/schannel_int.h new file mode 100644 index 0000000..5e233a9 --- /dev/null +++ b/third_party/curl/lib/vtls/schannel_int.h @@ -0,0 +1,180 @@ +#ifndef HEADER_CURL_SCHANNEL_INT_H +#define HEADER_CURL_SCHANNEL_INT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Marc Hoersken, , et al. + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_SCHANNEL + +#if defined(__MINGW32__) || defined(CERT_CHAIN_REVOCATION_CHECK_CHAIN) +#define HAS_MANUAL_VERIFY_API +#endif + +#if defined(CryptStringToBinary) && defined(CRYPT_STRING_HEX) \ + && !defined(DISABLE_SCHANNEL_CLIENT_CERT) +#define HAS_CLIENT_CERT_PATH +#endif + +#ifndef CRYPT_DECODE_NOCOPY_FLAG +#define CRYPT_DECODE_NOCOPY_FLAG 0x1 +#endif + +#ifndef CRYPT_DECODE_ALLOC_FLAG +#define CRYPT_DECODE_ALLOC_FLAG 0x8000 +#endif + +#ifndef CERT_ALT_NAME_DNS_NAME +#define CERT_ALT_NAME_DNS_NAME 3 +#endif + +#ifndef CERT_ALT_NAME_IP_ADDRESS +#define CERT_ALT_NAME_IP_ADDRESS 8 +#endif + +#if defined(_MSC_VER) && (_MSC_VER <= 1600) +/* Workaround for warning: + 'type cast' : conversion from 'int' to 'LPCSTR' of greater size */ +#undef CERT_STORE_PROV_MEMORY +#undef CERT_STORE_PROV_SYSTEM_A +#undef CERT_STORE_PROV_SYSTEM_W +#define CERT_STORE_PROV_MEMORY ((LPCSTR)(size_t)2) +#define CERT_STORE_PROV_SYSTEM_A ((LPCSTR)(size_t)9) +#define CERT_STORE_PROV_SYSTEM_W ((LPCSTR)(size_t)10) +#endif + +#ifndef SCH_CREDENTIALS_VERSION + +#define SCH_CREDENTIALS_VERSION 0x00000005 + +typedef enum _eTlsAlgorithmUsage +{ + TlsParametersCngAlgUsageKeyExchange, + TlsParametersCngAlgUsageSignature, + TlsParametersCngAlgUsageCipher, + TlsParametersCngAlgUsageDigest, + TlsParametersCngAlgUsageCertSig +} eTlsAlgorithmUsage; + +typedef struct _CRYPTO_SETTINGS +{ + eTlsAlgorithmUsage eAlgorithmUsage; + UNICODE_STRING strCngAlgId; + DWORD cChainingModes; + PUNICODE_STRING rgstrChainingModes; + DWORD dwMinBitLength; + DWORD dwMaxBitLength; +} CRYPTO_SETTINGS, * PCRYPTO_SETTINGS; + +typedef struct _TLS_PARAMETERS +{ + DWORD cAlpnIds; + PUNICODE_STRING rgstrAlpnIds; + DWORD grbitDisabledProtocols; + DWORD cDisabledCrypto; + PCRYPTO_SETTINGS pDisabledCrypto; + DWORD dwFlags; +} TLS_PARAMETERS, * PTLS_PARAMETERS; + +typedef struct _SCH_CREDENTIALS +{ + DWORD dwVersion; + DWORD dwCredFormat; + DWORD cCreds; + PCCERT_CONTEXT* paCred; + HCERTSTORE hRootStore; + + DWORD cMappers; + struct _HMAPPER **aphMappers; + + DWORD dwSessionLifespan; + DWORD dwFlags; + DWORD cTlsParameters; + PTLS_PARAMETERS pTlsParameters; +} SCH_CREDENTIALS, * PSCH_CREDENTIALS; + +#define SCH_CRED_MAX_SUPPORTED_PARAMETERS 16 +#define SCH_CRED_MAX_SUPPORTED_ALPN_IDS 16 +#define SCH_CRED_MAX_SUPPORTED_CRYPTO_SETTINGS 16 +#define SCH_CRED_MAX_SUPPORTED_CHAINING_MODES 16 + +#endif /* SCH_CREDENTIALS_VERSION */ + +struct Curl_schannel_cred { + CredHandle cred_handle; + TimeStamp time_stamp; + TCHAR *sni_hostname; +#ifdef HAS_CLIENT_CERT_PATH + HCERTSTORE client_cert_store; +#endif + int refcount; +}; + +struct Curl_schannel_ctxt { + CtxtHandle ctxt_handle; + TimeStamp time_stamp; +}; + +struct schannel_ssl_backend_data { + struct Curl_schannel_cred *cred; + struct Curl_schannel_ctxt *ctxt; + SecPkgContext_StreamSizes stream_sizes; + size_t encdata_length, decdata_length; + size_t encdata_offset, decdata_offset; + unsigned char *encdata_buffer, *decdata_buffer; + /* encdata_is_incomplete: if encdata contains only a partial record that + can't be decrypted without another recv() (that is, status is + SEC_E_INCOMPLETE_MESSAGE) then set this true. after an recv() adds + more bytes into encdata then set this back to false. */ + bool encdata_is_incomplete; + unsigned long req_flags, ret_flags; + CURLcode recv_unrecoverable_err; /* schannel_recv had an unrecoverable err */ + bool recv_sspi_close_notify; /* true if connection closed by close_notify */ + bool recv_connection_closed; /* true if connection closed, regardless how */ + bool recv_renegotiating; /* true if recv is doing renegotiation */ + bool use_alpn; /* true if ALPN is used for this connection */ +#ifdef HAS_MANUAL_VERIFY_API + bool use_manual_cred_validation; /* true if manual cred validation is used */ +#endif +}; + +struct schannel_multi_ssl_backend_data { + unsigned char *CAinfo_blob_digest; /* CA info blob digest */ + size_t CAinfo_blob_size; /* CA info blob size */ + char *CAfile; /* CAfile path used to generate + certificate store */ + HCERTSTORE cert_store; /* cached certificate store or + NULL if none */ + struct curltime time; /* when the cached store was created */ +}; + +HCERTSTORE Curl_schannel_get_cached_cert_store(struct Curl_cfilter *cf, + const struct Curl_easy *data); + +bool Curl_schannel_set_cached_cert_store(struct Curl_cfilter *cf, + const struct Curl_easy *data, + HCERTSTORE cert_store); + +#endif /* USE_SCHANNEL */ +#endif /* HEADER_CURL_SCHANNEL_INT_H */ diff --git a/third_party/curl/lib/vtls/schannel_verify.c b/third_party/curl/lib/vtls/schannel_verify.c new file mode 100644 index 0000000..24146d0 --- /dev/null +++ b/third_party/curl/lib/vtls/schannel_verify.c @@ -0,0 +1,787 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Marc Hoersken, + * Copyright (C) Mark Salisbury, + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Source file for Schannel-specific certificate verification. This code should + * only be invoked by code in schannel.c. + */ + +#include "curl_setup.h" + +#ifdef USE_SCHANNEL +#ifndef USE_WINDOWS_SSPI +# error "Can't compile SCHANNEL support without SSPI." +#endif + +#include "schannel.h" +#include "schannel_int.h" + +#include "vtls.h" +#include "vtls_int.h" +#include "sendf.h" +#include "strerror.h" +#include "curl_multibyte.h" +#include "curl_printf.h" +#include "hostcheck.h" +#include "version_win32.h" + +/* The last #include file should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +#define BACKEND ((struct schannel_ssl_backend_data *)connssl->backend) + + +#ifdef HAS_MANUAL_VERIFY_API + +#define MAX_CAFILE_SIZE 1048576 /* 1 MiB */ +#define BEGIN_CERT "-----BEGIN CERTIFICATE-----" +#define END_CERT "\n-----END CERTIFICATE-----" + +struct cert_chain_engine_config_win7 { + DWORD cbSize; + HCERTSTORE hRestrictedRoot; + HCERTSTORE hRestrictedTrust; + HCERTSTORE hRestrictedOther; + DWORD cAdditionalStore; + HCERTSTORE *rghAdditionalStore; + DWORD dwFlags; + DWORD dwUrlRetrievalTimeout; + DWORD MaximumCachedCertificates; + DWORD CycleDetectionModulus; + HCERTSTORE hExclusiveRoot; + HCERTSTORE hExclusiveTrustedPeople; +}; + +static int is_cr_or_lf(char c) +{ + return c == '\r' || c == '\n'; +} + +/* Search the substring needle,needlelen into string haystack,haystacklen + * Strings don't need to be terminated by a '\0'. + * Similar of OSX/Linux memmem (not available on Visual Studio). + * Return position of beginning of first occurrence or NULL if not found + */ +static const char *c_memmem(const void *haystack, size_t haystacklen, + const void *needle, size_t needlelen) +{ + const char *p; + char first; + const char *str_limit = (const char *)haystack + haystacklen; + if(!needlelen || needlelen > haystacklen) + return NULL; + first = *(const char *)needle; + for(p = (const char *)haystack; p <= (str_limit - needlelen); p++) + if(((*p) == first) && (memcmp(p, needle, needlelen) == 0)) + return p; + + return NULL; +} + +static CURLcode add_certs_data_to_store(HCERTSTORE trust_store, + const char *ca_buffer, + size_t ca_buffer_size, + const char *ca_file_text, + struct Curl_easy *data) +{ + const size_t begin_cert_len = strlen(BEGIN_CERT); + const size_t end_cert_len = strlen(END_CERT); + CURLcode result = CURLE_OK; + int num_certs = 0; + bool more_certs = 1; + const char *current_ca_file_ptr = ca_buffer; + const char *ca_buffer_limit = ca_buffer + ca_buffer_size; + + while(more_certs && (current_ca_file_ptr MAX_CAFILE_SIZE) { + failf(data, + "schannel: CA file exceeds max size of %u bytes", + MAX_CAFILE_SIZE); + result = CURLE_SSL_CACERT_BADFILE; + goto cleanup; + } + + ca_file_bufsize = (size_t)file_size.QuadPart; + ca_file_buffer = (char *)malloc(ca_file_bufsize + 1); + if(!ca_file_buffer) { + result = CURLE_OUT_OF_MEMORY; + goto cleanup; + } + + while(total_bytes_read < ca_file_bufsize) { + DWORD bytes_to_read = (DWORD)(ca_file_bufsize - total_bytes_read); + DWORD bytes_read = 0; + + if(!ReadFile(ca_file_handle, ca_file_buffer + total_bytes_read, + bytes_to_read, &bytes_read, NULL)) { + char buffer[STRERROR_LEN]; + failf(data, + "schannel: failed to read from CA file '%s': %s", + ca_file, + Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer))); + result = CURLE_SSL_CACERT_BADFILE; + goto cleanup; + } + if(bytes_read == 0) { + /* Premature EOF -- adjust the bufsize to the new value */ + ca_file_bufsize = total_bytes_read; + } + else { + total_bytes_read += bytes_read; + } + } + + /* Null terminate the buffer */ + ca_file_buffer[ca_file_bufsize] = '\0'; + + result = add_certs_data_to_store(trust_store, + ca_file_buffer, ca_file_bufsize, + ca_file, + data); + +cleanup: + if(ca_file_handle != INVALID_HANDLE_VALUE) { + CloseHandle(ca_file_handle); + } + Curl_safefree(ca_file_buffer); + curlx_unicodefree(ca_file_tstr); + + return result; +} + +#endif /* HAS_MANUAL_VERIFY_API */ + +/* + * Returns the number of characters necessary to populate all the host_names. + * If host_names is not NULL, populate it with all the host names. Each string + * in the host_names is null-terminated and the last string is double + * null-terminated. If no DNS names are found, a single null-terminated empty + * string is returned. + */ +static DWORD cert_get_name_string(struct Curl_easy *data, + CERT_CONTEXT *cert_context, + LPTSTR host_names, + DWORD length) +{ + DWORD actual_length = 0; + BOOL compute_content = FALSE; + CERT_INFO *cert_info = NULL; + CERT_EXTENSION *extension = NULL; + CRYPT_DECODE_PARA decode_para = {0, 0, 0}; + CERT_ALT_NAME_INFO *alt_name_info = NULL; + DWORD alt_name_info_size = 0; + BOOL ret_val = FALSE; + LPTSTR current_pos = NULL; + DWORD i; + +#ifdef CERT_NAME_SEARCH_ALL_NAMES_FLAG + /* CERT_NAME_SEARCH_ALL_NAMES_FLAG is available from Windows 8 onwards. */ + if(curlx_verify_windows_version(6, 2, 0, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) { + /* CertGetNameString will provide the 8-bit character string without + * any decoding */ + DWORD name_flags = + CERT_NAME_DISABLE_IE4_UTF8_FLAG | CERT_NAME_SEARCH_ALL_NAMES_FLAG; + actual_length = CertGetNameString(cert_context, + CERT_NAME_DNS_TYPE, + name_flags, + NULL, + host_names, + length); + return actual_length; + } +#endif + + compute_content = host_names != NULL && length != 0; + + /* Initialize default return values. */ + actual_length = 1; + if(compute_content) { + *host_names = '\0'; + } + + if(!cert_context) { + failf(data, "schannel: Null certificate context."); + return actual_length; + } + + cert_info = cert_context->pCertInfo; + if(!cert_info) { + failf(data, "schannel: Null certificate info."); + return actual_length; + } + + extension = CertFindExtension(szOID_SUBJECT_ALT_NAME2, + cert_info->cExtension, + cert_info->rgExtension); + if(!extension) { + failf(data, "schannel: CertFindExtension() returned no extension."); + return actual_length; + } + + decode_para.cbSize = sizeof(CRYPT_DECODE_PARA); + + ret_val = + CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, + szOID_SUBJECT_ALT_NAME2, + extension->Value.pbData, + extension->Value.cbData, + CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, + &decode_para, + &alt_name_info, + &alt_name_info_size); + if(!ret_val) { + failf(data, + "schannel: CryptDecodeObjectEx() returned no alternate name " + "information."); + return actual_length; + } + + current_pos = host_names; + + /* Iterate over the alternate names and populate host_names. */ + for(i = 0; i < alt_name_info->cAltEntry; i++) { + const CERT_ALT_NAME_ENTRY *entry = &alt_name_info->rgAltEntry[i]; + wchar_t *dns_w = NULL; + size_t current_length = 0; + + if(entry->dwAltNameChoice != CERT_ALT_NAME_DNS_NAME) { + continue; + } + if(!entry->pwszDNSName) { + infof(data, "schannel: Empty DNS name."); + continue; + } + current_length = wcslen(entry->pwszDNSName) + 1; + if(!compute_content) { + actual_length += (DWORD)current_length; + continue; + } + /* Sanity check to prevent buffer overrun. */ + if((actual_length + current_length) > length) { + failf(data, "schannel: Not enough memory to list all host names."); + break; + } + dns_w = entry->pwszDNSName; + /* pwszDNSName is in ia5 string format and hence doesn't contain any + * non-ascii characters. */ + while(*dns_w != '\0') { + *current_pos++ = (char)(*dns_w++); + } + *current_pos++ = '\0'; + actual_length += (DWORD)current_length; + } + if(compute_content) { + /* Last string has double null-terminator. */ + *current_pos = '\0'; + } + return actual_length; +} + +/* Verify the server's hostname */ +CURLcode Curl_verify_host(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + SECURITY_STATUS sspi_status; + CURLcode result = CURLE_PEER_FAILED_VERIFICATION; + CERT_CONTEXT *pCertContextServer = NULL; + TCHAR *cert_hostname_buff = NULL; + size_t cert_hostname_buff_index = 0; + const char *conn_hostname = connssl->peer.hostname; + size_t hostlen = strlen(conn_hostname); + DWORD len = 0; + DWORD actual_len = 0; + + sspi_status = + s_pSecFn->QueryContextAttributes(&BACKEND->ctxt->ctxt_handle, + SECPKG_ATTR_REMOTE_CERT_CONTEXT, + &pCertContextServer); + + if((sspi_status != SEC_E_OK) || !pCertContextServer) { + char buffer[STRERROR_LEN]; + failf(data, "schannel: Failed to read remote certificate context: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + result = CURLE_PEER_FAILED_VERIFICATION; + goto cleanup; + } + + /* Determine the size of the string needed for the cert hostname */ + len = cert_get_name_string(data, pCertContextServer, NULL, 0); + if(len == 0) { + failf(data, + "schannel: CertGetNameString() returned no " + "certificate name information"); + result = CURLE_PEER_FAILED_VERIFICATION; + goto cleanup; + } + + /* CertGetNameString guarantees that the returned name will not contain + * embedded null bytes. This appears to be undocumented behavior. + */ + cert_hostname_buff = (LPTSTR)malloc(len * sizeof(TCHAR)); + if(!cert_hostname_buff) { + result = CURLE_OUT_OF_MEMORY; + goto cleanup; + } + actual_len = cert_get_name_string( + data, pCertContextServer, (LPTSTR)cert_hostname_buff, len); + + /* Sanity check */ + if(actual_len != len) { + failf(data, + "schannel: CertGetNameString() returned certificate " + "name information of unexpected size"); + result = CURLE_PEER_FAILED_VERIFICATION; + goto cleanup; + } + + /* cert_hostname_buff contains all DNS names, where each name is + * null-terminated and the last DNS name is double null-terminated. Due to + * this encoding, use the length of the buffer to iterate over all names. + */ + result = CURLE_PEER_FAILED_VERIFICATION; + while(cert_hostname_buff_index < len && + cert_hostname_buff[cert_hostname_buff_index] != TEXT('\0') && + result == CURLE_PEER_FAILED_VERIFICATION) { + + char *cert_hostname; + + /* Comparing the cert name and the connection hostname encoded as UTF-8 + * is acceptable since both values are assumed to use ASCII + * (or some equivalent) encoding + */ + cert_hostname = curlx_convert_tchar_to_UTF8( + &cert_hostname_buff[cert_hostname_buff_index]); + if(!cert_hostname) { + result = CURLE_OUT_OF_MEMORY; + } + else { + if(Curl_cert_hostcheck(cert_hostname, strlen(cert_hostname), + conn_hostname, hostlen)) { + infof(data, + "schannel: connection hostname (%s) validated " + "against certificate name (%s)", + conn_hostname, cert_hostname); + result = CURLE_OK; + } + else { + size_t cert_hostname_len; + + infof(data, + "schannel: connection hostname (%s) did not match " + "against certificate name (%s)", + conn_hostname, cert_hostname); + + cert_hostname_len = + _tcslen(&cert_hostname_buff[cert_hostname_buff_index]); + + /* Move on to next cert name */ + cert_hostname_buff_index += cert_hostname_len + 1; + + result = CURLE_PEER_FAILED_VERIFICATION; + } + curlx_unicodefree(cert_hostname); + } + } + + if(result == CURLE_PEER_FAILED_VERIFICATION) { + failf(data, + "schannel: CertGetNameString() failed to match " + "connection hostname (%s) against server certificate names", + conn_hostname); + } + else if(result != CURLE_OK) + failf(data, "schannel: server certificate name verification failed"); + +cleanup: + Curl_safefree(cert_hostname_buff); + + if(pCertContextServer) + CertFreeCertificateContext(pCertContextServer); + + return result; +} + + +#ifdef HAS_MANUAL_VERIFY_API +/* Verify the server's certificate and hostname */ +CURLcode Curl_verify_certificate(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + SECURITY_STATUS sspi_status; + CURLcode result = CURLE_OK; + CERT_CONTEXT *pCertContextServer = NULL; + const CERT_CHAIN_CONTEXT *pChainContext = NULL; + HCERTCHAINENGINE cert_chain_engine = NULL; + HCERTSTORE trust_store = NULL; + HCERTSTORE own_trust_store = NULL; + + DEBUGASSERT(BACKEND); + + sspi_status = + s_pSecFn->QueryContextAttributes(&BACKEND->ctxt->ctxt_handle, + SECPKG_ATTR_REMOTE_CERT_CONTEXT, + &pCertContextServer); + + if((sspi_status != SEC_E_OK) || !pCertContextServer) { + char buffer[STRERROR_LEN]; + failf(data, "schannel: Failed to read remote certificate context: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + result = CURLE_PEER_FAILED_VERIFICATION; + } + + if(result == CURLE_OK && + (conn_config->CAfile || conn_config->ca_info_blob) && + BACKEND->use_manual_cred_validation) { + /* + * Create a chain engine that uses the certificates in the CA file as + * trusted certificates. This is only supported on Windows 7+. + */ + + if(curlx_verify_windows_version(6, 1, 0, PLATFORM_WINNT, + VERSION_LESS_THAN)) { + failf(data, "schannel: this version of Windows is too old to support " + "certificate verification via CA bundle file."); + result = CURLE_SSL_CACERT_BADFILE; + } + else { + /* try cache */ + trust_store = Curl_schannel_get_cached_cert_store(cf, data); + + if(trust_store) { + infof(data, "schannel: reusing certificate store from cache"); + } + else { + /* Open the certificate store */ + trust_store = CertOpenStore(CERT_STORE_PROV_MEMORY, + 0, + (HCRYPTPROV)NULL, + CERT_STORE_CREATE_NEW_FLAG, + NULL); + if(!trust_store) { + char buffer[STRERROR_LEN]; + failf(data, "schannel: failed to create certificate store: %s", + Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer))); + result = CURLE_SSL_CACERT_BADFILE; + } + else { + const struct curl_blob *ca_info_blob = conn_config->ca_info_blob; + own_trust_store = trust_store; + + if(ca_info_blob) { + result = add_certs_data_to_store(trust_store, + (const char *)ca_info_blob->data, + ca_info_blob->len, + "(memory blob)", + data); + } + else { + result = add_certs_file_to_store(trust_store, + conn_config->CAfile, + data); + } + if(result == CURLE_OK) { + if(Curl_schannel_set_cached_cert_store(cf, data, trust_store)) { + own_trust_store = NULL; + } + } + } + } + } + + if(result == CURLE_OK) { + struct cert_chain_engine_config_win7 engine_config; + BOOL create_engine_result; + + memset(&engine_config, 0, sizeof(engine_config)); + engine_config.cbSize = sizeof(engine_config); + engine_config.hExclusiveRoot = trust_store; + + /* CertCreateCertificateChainEngine will check the expected size of the + * CERT_CHAIN_ENGINE_CONFIG structure and fail if the specified size + * does not match the expected size. When this occurs, it indicates that + * CAINFO is not supported on the version of Windows in use. + */ + create_engine_result = + CertCreateCertificateChainEngine( + (CERT_CHAIN_ENGINE_CONFIG *)&engine_config, &cert_chain_engine); + if(!create_engine_result) { + char buffer[STRERROR_LEN]; + failf(data, + "schannel: failed to create certificate chain engine: %s", + Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer))); + result = CURLE_SSL_CACERT_BADFILE; + } + } + } + + if(result == CURLE_OK) { + CERT_CHAIN_PARA ChainPara; + + memset(&ChainPara, 0, sizeof(ChainPara)); + ChainPara.cbSize = sizeof(ChainPara); + + if(!CertGetCertificateChain(cert_chain_engine, + pCertContextServer, + NULL, + pCertContextServer->hCertStore, + &ChainPara, + (ssl_config->no_revoke ? 0 : + CERT_CHAIN_REVOCATION_CHECK_CHAIN), + NULL, + &pChainContext)) { + char buffer[STRERROR_LEN]; + failf(data, "schannel: CertGetCertificateChain failed: %s", + Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer))); + pChainContext = NULL; + result = CURLE_PEER_FAILED_VERIFICATION; + } + + if(result == CURLE_OK) { + CERT_SIMPLE_CHAIN *pSimpleChain = pChainContext->rgpChain[0]; + DWORD dwTrustErrorMask = ~(DWORD)(CERT_TRUST_IS_NOT_TIME_NESTED); + dwTrustErrorMask &= pSimpleChain->TrustStatus.dwErrorStatus; + + if(data->set.ssl.revoke_best_effort) { + /* Ignore errors when root certificates are missing the revocation + * list URL, or when the list could not be downloaded because the + * server is currently unreachable. */ + dwTrustErrorMask &= ~(DWORD)(CERT_TRUST_REVOCATION_STATUS_UNKNOWN | + CERT_TRUST_IS_OFFLINE_REVOCATION); + } + + if(dwTrustErrorMask) { + if(dwTrustErrorMask & CERT_TRUST_IS_REVOKED) + failf(data, "schannel: CertGetCertificateChain trust error" + " CERT_TRUST_IS_REVOKED"); + else if(dwTrustErrorMask & CERT_TRUST_IS_PARTIAL_CHAIN) + failf(data, "schannel: CertGetCertificateChain trust error" + " CERT_TRUST_IS_PARTIAL_CHAIN"); + else if(dwTrustErrorMask & CERT_TRUST_IS_UNTRUSTED_ROOT) + failf(data, "schannel: CertGetCertificateChain trust error" + " CERT_TRUST_IS_UNTRUSTED_ROOT"); + else if(dwTrustErrorMask & CERT_TRUST_IS_NOT_TIME_VALID) + failf(data, "schannel: CertGetCertificateChain trust error" + " CERT_TRUST_IS_NOT_TIME_VALID"); + else if(dwTrustErrorMask & CERT_TRUST_REVOCATION_STATUS_UNKNOWN) + failf(data, "schannel: CertGetCertificateChain trust error" + " CERT_TRUST_REVOCATION_STATUS_UNKNOWN"); + else + failf(data, "schannel: CertGetCertificateChain error mask: 0x%08lx", + dwTrustErrorMask); + result = CURLE_PEER_FAILED_VERIFICATION; + } + } + } + + if(result == CURLE_OK) { + if(conn_config->verifyhost) { + result = Curl_verify_host(cf, data); + } + } + + if(cert_chain_engine) { + CertFreeCertificateChainEngine(cert_chain_engine); + } + + if(own_trust_store) { + CertCloseStore(own_trust_store, 0); + } + + if(pChainContext) + CertFreeCertificateChain(pChainContext); + + if(pCertContextServer) + CertFreeCertificateContext(pCertContextServer); + + return result; +} + +#endif /* HAS_MANUAL_VERIFY_API */ +#endif /* USE_SCHANNEL */ diff --git a/third_party/curl/lib/vtls/sectransp.c b/third_party/curl/lib/vtls/sectransp.c new file mode 100644 index 0000000..f49db64 --- /dev/null +++ b/third_party/curl/lib/vtls/sectransp.c @@ -0,0 +1,3492 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (C) Nick Zitzmann, . + * + * 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Source file for all iOS and macOS SecureTransport-specific code for the + * TLS/SSL layer. No code but vtls.c should ever call or use these functions. + */ + +#include "curl_setup.h" + +#include "urldata.h" /* for the Curl_easy definition */ +#include "curl_base64.h" +#include "strtok.h" +#include "multiif.h" +#include "strcase.h" +#include "x509asn1.h" +#include "strerror.h" + +#ifdef USE_SECTRANSP + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wtautological-pointer-compare" +#endif /* __clang__ */ + +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Waddress" +#pragma GCC diagnostic ignored "-Wundef" +#pragma GCC diagnostic ignored "-Wunreachable-code" +#endif + +#include + +#include +/* For some reason, when building for iOS, the omnibus header above does + * not include SecureTransport.h as of iOS SDK 5.1. */ +#include +#include +#include + +/* The Security framework has changed greatly between iOS and different macOS + versions, and we will try to support as many of them as we can (back to + Leopard and iOS 5) by using macros and weak-linking. + + In general, you want to build this using the most recent OS SDK, since some + features require curl to be built against the latest SDK. TLS 1.1 and 1.2 + support, for instance, require the macOS 10.8 SDK or later. TLS 1.3 + requires the macOS 10.13 or iOS 11 SDK or later. */ +#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) + +#if MAC_OS_X_VERSION_MAX_ALLOWED < 1050 +#error "The Secure Transport back-end requires Leopard or later." +#endif /* MAC_OS_X_VERSION_MAX_ALLOWED < 1050 */ + +#define CURL_BUILD_IOS 0 +#define CURL_BUILD_IOS_7 0 +#define CURL_BUILD_IOS_9 0 +#define CURL_BUILD_IOS_11 0 +#define CURL_BUILD_IOS_13 0 +#define CURL_BUILD_MAC 1 +/* This is the maximum API level we are allowed to use when building: */ +#define CURL_BUILD_MAC_10_5 MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 +#define CURL_BUILD_MAC_10_6 MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 +#define CURL_BUILD_MAC_10_7 MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 +#define CURL_BUILD_MAC_10_8 MAC_OS_X_VERSION_MAX_ALLOWED >= 1080 +#define CURL_BUILD_MAC_10_9 MAC_OS_X_VERSION_MAX_ALLOWED >= 1090 +#define CURL_BUILD_MAC_10_11 MAC_OS_X_VERSION_MAX_ALLOWED >= 101100 +#define CURL_BUILD_MAC_10_13 MAC_OS_X_VERSION_MAX_ALLOWED >= 101300 +#define CURL_BUILD_MAC_10_15 MAC_OS_X_VERSION_MAX_ALLOWED >= 101500 +/* These macros mean "the following code is present to allow runtime backward + compatibility with at least this cat or earlier": + (You set this at build-time using the compiler command line option + "-mmacosx-version-min.") */ +#define CURL_SUPPORT_MAC_10_5 MAC_OS_X_VERSION_MIN_REQUIRED <= 1050 +#define CURL_SUPPORT_MAC_10_6 MAC_OS_X_VERSION_MIN_REQUIRED <= 1060 +#define CURL_SUPPORT_MAC_10_7 MAC_OS_X_VERSION_MIN_REQUIRED <= 1070 +#define CURL_SUPPORT_MAC_10_8 MAC_OS_X_VERSION_MIN_REQUIRED <= 1080 +#define CURL_SUPPORT_MAC_10_9 MAC_OS_X_VERSION_MIN_REQUIRED <= 1090 + +#elif TARGET_OS_EMBEDDED || TARGET_OS_IPHONE +#define CURL_BUILD_IOS 1 +#define CURL_BUILD_IOS_7 __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 +#define CURL_BUILD_IOS_9 __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000 +#define CURL_BUILD_IOS_11 __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 +#define CURL_BUILD_IOS_13 __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 +#define CURL_BUILD_MAC 0 +#define CURL_BUILD_MAC_10_5 0 +#define CURL_BUILD_MAC_10_6 0 +#define CURL_BUILD_MAC_10_7 0 +#define CURL_BUILD_MAC_10_8 0 +#define CURL_BUILD_MAC_10_9 0 +#define CURL_BUILD_MAC_10_11 0 +#define CURL_BUILD_MAC_10_13 0 +#define CURL_BUILD_MAC_10_15 0 +#define CURL_SUPPORT_MAC_10_5 0 +#define CURL_SUPPORT_MAC_10_6 0 +#define CURL_SUPPORT_MAC_10_7 0 +#define CURL_SUPPORT_MAC_10_8 0 +#define CURL_SUPPORT_MAC_10_9 0 + +#else +#error "The Secure Transport back-end requires iOS or macOS." +#endif /* (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) */ + +#if CURL_BUILD_MAC +#include +#endif /* CURL_BUILD_MAC */ + +#include "sendf.h" +#include "inet_pton.h" +#include "connect.h" +#include "select.h" +#include "vtls.h" +#include "vtls_int.h" +#include "sectransp.h" +#include "curl_printf.h" +#include "strdup.h" + +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + + +/* From MacTypes.h (which we can't include because it isn't present in iOS: */ +#define ioErr -36 +#define paramErr -50 + +struct st_ssl_backend_data { + SSLContextRef ssl_ctx; + bool ssl_direction; /* true if writing, false if reading */ + size_t ssl_write_buffered_length; +}; + +struct st_cipher { + const char *name; /* Cipher suite IANA name. It starts with "TLS_" prefix */ + const char *alias_name; /* Alias name is the same as OpenSSL cipher name */ + SSLCipherSuite num; /* Cipher suite code/number defined in IANA registry */ + bool weak; /* Flag to mark cipher as weak based on previous implementation + of Secure Transport back-end by CURL */ +}; + +/* Macro to initialize st_cipher data structure: stringify id to name, cipher + number/id, 'weak' suite flag + */ +#define CIPHER_DEF(num, alias, weak) \ + { #num, alias, num, weak } + +/* + Macro to initialize st_cipher data structure with name, code (IANA cipher + number/id value), and 'weak' suite flag. The first 28 cipher suite numbers + have the same IANA code for both SSL and TLS standards: numbers 0x0000 to + 0x001B. They have different names though. The first 4 letters of the cipher + suite name are the protocol name: "SSL_" or "TLS_", rest of the IANA name is + the same for both SSL and TLS cipher suite name. + The second part of the problem is that macOS/iOS SDKs don't define all TLS + codes but only 12 of them. The SDK defines all SSL codes though, i.e. SSL_NUM + constant is always defined for those 28 ciphers while TLS_NUM is defined only + for 12 of the first 28 ciphers. Those 12 TLS cipher codes match to + corresponding SSL enum value and represent the same cipher suite. Therefore + we'll use the SSL enum value for those cipher suites because it is defined + for all 28 of them. + We make internal data consistent and based on TLS names, i.e. all st_cipher + item names start with the "TLS_" prefix. + Summarizing all the above, those 28 first ciphers are presented in our table + with both TLS and SSL names. Their cipher numbers are assigned based on the + SDK enum value for the SSL cipher, which matches to IANA TLS number. + */ +#define CIPHER_DEF_SSLTLS(num_wo_prefix, alias, weak) \ + { "TLS_" #num_wo_prefix, alias, SSL_##num_wo_prefix, weak } + +/* + Cipher suites were marked as weak based on the following: + RC4 encryption - rfc7465, the document contains a list of deprecated ciphers. + Marked in the code below as weak. + RC2 encryption - many mentions, was found vulnerable to a relatively easy + attack https://link.springer.com/chapter/10.1007%2F3-540-69710-1_14 + Marked in the code below as weak. + DES and IDEA encryption - rfc5469, has a list of deprecated ciphers. + Marked in the code below as weak. + Anonymous Diffie-Hellman authentication and anonymous elliptic curve + Diffie-Hellman - vulnerable to a man-in-the-middle attack. Deprecated by + RFC 4346 aka TLS 1.1 (section A.5, page 60) + Null bulk encryption suites - not encrypted communication + Export ciphers, i.e. ciphers with restrictions to be used outside the US for + software exported to some countries, they were excluded from TLS 1.1 + version. More precisely, they were noted as ciphers which MUST NOT be + negotiated in RFC 4346 aka TLS 1.1 (section A.5, pages 60 and 61). + All of those filters were considered weak because they contain a weak + algorithm like DES, RC2 or RC4, and already considered weak by other + criteria. + 3DES - NIST deprecated it and is going to retire it by 2023 + https://csrc.nist.gov/News/2017/Update-to-Current-Use-and-Deprecation-of-TDEA + OpenSSL https://www.openssl.org/blog/blog/2016/08/24/sweet32/ also + deprecated those ciphers. Some other libraries also consider it + vulnerable or at least not strong enough. + + CBC ciphers are vulnerable with SSL3.0 and TLS1.0: + https://www.cisco.com/c/en/us/support/docs/security/email-security-appliance + /118518-technote-esa-00.html + We don't take care of this issue because it is resolved by later TLS + versions and for us, it requires more complicated checks, we need to + check a protocol version also. Vulnerability doesn't look very critical + and we do not filter out those cipher suites. + */ + +#define CIPHER_WEAK_NOT_ENCRYPTED TRUE +#define CIPHER_WEAK_RC_ENCRYPTION TRUE +#define CIPHER_WEAK_DES_ENCRYPTION TRUE +#define CIPHER_WEAK_IDEA_ENCRYPTION TRUE +#define CIPHER_WEAK_ANON_AUTH TRUE +#define CIPHER_WEAK_3DES_ENCRYPTION TRUE +#define CIPHER_STRONG_ENOUGH FALSE + +/* Please do not change the order of the first ciphers available for SSL. + Do not insert and do not delete any of them. Code below + depends on their order and continuity. + If you add a new cipher, please maintain order by number, i.e. + insert in between existing items to appropriate place based on + cipher suite IANA number +*/ +static const struct st_cipher ciphertable[] = { + /* SSL version 3.0 and initial TLS 1.0 cipher suites. + Defined since SDK 10.2.8 */ + CIPHER_DEF_SSLTLS(NULL_WITH_NULL_NULL, /* 0x0000 */ + NULL, + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF_SSLTLS(RSA_WITH_NULL_MD5, /* 0x0001 */ + "NULL-MD5", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF_SSLTLS(RSA_WITH_NULL_SHA, /* 0x0002 */ + "NULL-SHA", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF_SSLTLS(RSA_EXPORT_WITH_RC4_40_MD5, /* 0x0003 */ + "EXP-RC4-MD5", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF_SSLTLS(RSA_WITH_RC4_128_MD5, /* 0x0004 */ + "RC4-MD5", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF_SSLTLS(RSA_WITH_RC4_128_SHA, /* 0x0005 */ + "RC4-SHA", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF_SSLTLS(RSA_EXPORT_WITH_RC2_CBC_40_MD5, /* 0x0006 */ + "EXP-RC2-CBC-MD5", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF_SSLTLS(RSA_WITH_IDEA_CBC_SHA, /* 0x0007 */ + "IDEA-CBC-SHA", + CIPHER_WEAK_IDEA_ENCRYPTION), + CIPHER_DEF_SSLTLS(RSA_EXPORT_WITH_DES40_CBC_SHA, /* 0x0008 */ + "EXP-DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(RSA_WITH_DES_CBC_SHA, /* 0x0009 */ + "DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(RSA_WITH_3DES_EDE_CBC_SHA, /* 0x000A */ + "DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DH_DSS_EXPORT_WITH_DES40_CBC_SHA, /* 0x000B */ + "EXP-DH-DSS-DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DH_DSS_WITH_DES_CBC_SHA, /* 0x000C */ + "DH-DSS-DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DH_DSS_WITH_3DES_EDE_CBC_SHA, /* 0x000D */ + "DH-DSS-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DH_RSA_EXPORT_WITH_DES40_CBC_SHA, /* 0x000E */ + "EXP-DH-RSA-DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DH_RSA_WITH_DES_CBC_SHA, /* 0x000F */ + "DH-RSA-DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DH_RSA_WITH_3DES_EDE_CBC_SHA, /* 0x0010 */ + "DH-RSA-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, /* 0x0011 */ + "EXP-EDH-DSS-DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DHE_DSS_WITH_DES_CBC_SHA, /* 0x0012 */ + "EDH-DSS-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DHE_DSS_WITH_3DES_EDE_CBC_SHA, /* 0x0013 */ + "DHE-DSS-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, /* 0x0014 */ + "EXP-EDH-RSA-DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DHE_RSA_WITH_DES_CBC_SHA, /* 0x0015 */ + "EDH-RSA-DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DHE_RSA_WITH_3DES_EDE_CBC_SHA, /* 0x0016 */ + "DHE-RSA-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DH_anon_EXPORT_WITH_RC4_40_MD5, /* 0x0017 */ + "EXP-ADH-RC4-MD5", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF_SSLTLS(DH_anon_WITH_RC4_128_MD5, /* 0x0018 */ + "ADH-RC4-MD5", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF_SSLTLS(DH_anon_EXPORT_WITH_DES40_CBC_SHA, /* 0x0019 */ + "EXP-ADH-DES-CBC-SHA", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF_SSLTLS(DH_anon_WITH_DES_CBC_SHA, /* 0x001A */ + "ADH-DES-CBC-SHA", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF_SSLTLS(DH_anon_WITH_3DES_EDE_CBC_SHA, /* 0x001B */ + "ADH-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(SSL_FORTEZZA_DMS_WITH_NULL_SHA, /* 0x001C */ + NULL, + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA, /* 0x001D */ + NULL, + CIPHER_STRONG_ENOUGH), + +#if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 + /* RFC 4785 - Pre-Shared Key (PSK) Ciphersuites with NULL Encryption */ + CIPHER_DEF(TLS_PSK_WITH_NULL_SHA, /* 0x002C */ + "PSK-NULL-SHA", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_DHE_PSK_WITH_NULL_SHA, /* 0x002D */ + "DHE-PSK-NULL-SHA", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_RSA_PSK_WITH_NULL_SHA, /* 0x002E */ + "RSA-PSK-NULL-SHA", + CIPHER_WEAK_NOT_ENCRYPTED), +#endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */ + + /* TLS addenda using AES, per RFC 3268. Defined since SDK 10.4u */ + CIPHER_DEF(TLS_RSA_WITH_AES_128_CBC_SHA, /* 0x002F */ + "AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_DSS_WITH_AES_128_CBC_SHA, /* 0x0030 */ + "DH-DSS-AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_RSA_WITH_AES_128_CBC_SHA, /* 0x0031 */ + "DH-RSA-AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_DSS_WITH_AES_128_CBC_SHA, /* 0x0032 */ + "DHE-DSS-AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_RSA_WITH_AES_128_CBC_SHA, /* 0x0033 */ + "DHE-RSA-AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_anon_WITH_AES_128_CBC_SHA, /* 0x0034 */ + "ADH-AES128-SHA", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF(TLS_RSA_WITH_AES_256_CBC_SHA, /* 0x0035 */ + "AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_DSS_WITH_AES_256_CBC_SHA, /* 0x0036 */ + "DH-DSS-AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_RSA_WITH_AES_256_CBC_SHA, /* 0x0037 */ + "DH-RSA-AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_DSS_WITH_AES_256_CBC_SHA, /* 0x0038 */ + "DHE-DSS-AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_RSA_WITH_AES_256_CBC_SHA, /* 0x0039 */ + "DHE-RSA-AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_anon_WITH_AES_256_CBC_SHA, /* 0x003A */ + "ADH-AES256-SHA", + CIPHER_WEAK_ANON_AUTH), + +#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS + /* TLS 1.2 addenda, RFC 5246 */ + /* Server provided RSA certificate for key exchange. */ + CIPHER_DEF(TLS_RSA_WITH_NULL_SHA256, /* 0x003B */ + "NULL-SHA256", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_RSA_WITH_AES_128_CBC_SHA256, /* 0x003C */ + "AES128-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_RSA_WITH_AES_256_CBC_SHA256, /* 0x003D */ + "AES256-SHA256", + CIPHER_STRONG_ENOUGH), + /* Server-authenticated (and optionally client-authenticated) + Diffie-Hellman. */ + CIPHER_DEF(TLS_DH_DSS_WITH_AES_128_CBC_SHA256, /* 0x003E */ + "DH-DSS-AES128-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_RSA_WITH_AES_128_CBC_SHA256, /* 0x003F */ + "DH-RSA-AES128-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, /* 0x0040 */ + "DHE-DSS-AES128-SHA256", + CIPHER_STRONG_ENOUGH), + + /* TLS 1.2 addenda, RFC 5246 */ + CIPHER_DEF(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, /* 0x0067 */ + "DHE-RSA-AES128-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_DSS_WITH_AES_256_CBC_SHA256, /* 0x0068 */ + "DH-DSS-AES256-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_RSA_WITH_AES_256_CBC_SHA256, /* 0x0069 */ + "DH-RSA-AES256-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, /* 0x006A */ + "DHE-DSS-AES256-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, /* 0x006B */ + "DHE-RSA-AES256-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_anon_WITH_AES_128_CBC_SHA256, /* 0x006C */ + "ADH-AES128-SHA256", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF(TLS_DH_anon_WITH_AES_256_CBC_SHA256, /* 0x006D */ + "ADH-AES256-SHA256", + CIPHER_WEAK_ANON_AUTH), +#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ + +#if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 + /* Addendum from RFC 4279, TLS PSK */ + CIPHER_DEF(TLS_PSK_WITH_RC4_128_SHA, /* 0x008A */ + "PSK-RC4-SHA", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF(TLS_PSK_WITH_3DES_EDE_CBC_SHA, /* 0x008B */ + "PSK-3DES-EDE-CBC-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(TLS_PSK_WITH_AES_128_CBC_SHA, /* 0x008C */ + "PSK-AES128-CBC-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_PSK_WITH_AES_256_CBC_SHA, /* 0x008D */ + "PSK-AES256-CBC-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_PSK_WITH_RC4_128_SHA, /* 0x008E */ + "DHE-PSK-RC4-SHA", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF(TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA, /* 0x008F */ + "DHE-PSK-3DES-EDE-CBC-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(TLS_DHE_PSK_WITH_AES_128_CBC_SHA, /* 0x0090 */ + "DHE-PSK-AES128-CBC-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_PSK_WITH_AES_256_CBC_SHA, /* 0x0091 */ + "DHE-PSK-AES256-CBC-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_RSA_PSK_WITH_RC4_128_SHA, /* 0x0092 */ + "RSA-PSK-RC4-SHA", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF(TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, /* 0x0093 */ + "RSA-PSK-3DES-EDE-CBC-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(TLS_RSA_PSK_WITH_AES_128_CBC_SHA, /* 0x0094 */ + "RSA-PSK-AES128-CBC-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_RSA_PSK_WITH_AES_256_CBC_SHA, /* 0x0095 */ + "RSA-PSK-AES256-CBC-SHA", + CIPHER_STRONG_ENOUGH), +#endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */ + +#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS + /* Addenda from rfc 5288 AES Galois Counter Mode (GCM) Cipher Suites + for TLS. */ + CIPHER_DEF(TLS_RSA_WITH_AES_128_GCM_SHA256, /* 0x009C */ + "AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_RSA_WITH_AES_256_GCM_SHA384, /* 0x009D */ + "AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, /* 0x009E */ + "DHE-RSA-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, /* 0x009F */ + "DHE-RSA-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_RSA_WITH_AES_128_GCM_SHA256, /* 0x00A0 */ + "DH-RSA-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_RSA_WITH_AES_256_GCM_SHA384, /* 0x00A1 */ + "DH-RSA-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, /* 0x00A2 */ + "DHE-DSS-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, /* 0x00A3 */ + "DHE-DSS-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_DSS_WITH_AES_128_GCM_SHA256, /* 0x00A4 */ + "DH-DSS-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_DSS_WITH_AES_256_GCM_SHA384, /* 0x00A5 */ + "DH-DSS-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_anon_WITH_AES_128_GCM_SHA256, /* 0x00A6 */ + "ADH-AES128-GCM-SHA256", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF(TLS_DH_anon_WITH_AES_256_GCM_SHA384, /* 0x00A7 */ + "ADH-AES256-GCM-SHA384", + CIPHER_WEAK_ANON_AUTH), +#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ + +#if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 + /* RFC 5487 - PSK with SHA-256/384 and AES GCM */ + CIPHER_DEF(TLS_PSK_WITH_AES_128_GCM_SHA256, /* 0x00A8 */ + "PSK-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_PSK_WITH_AES_256_GCM_SHA384, /* 0x00A9 */ + "PSK-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_PSK_WITH_AES_128_GCM_SHA256, /* 0x00AA */ + "DHE-PSK-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_PSK_WITH_AES_256_GCM_SHA384, /* 0x00AB */ + "DHE-PSK-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_RSA_PSK_WITH_AES_128_GCM_SHA256, /* 0x00AC */ + "RSA-PSK-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_RSA_PSK_WITH_AES_256_GCM_SHA384, /* 0x00AD */ + "RSA-PSK-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_PSK_WITH_AES_128_CBC_SHA256, /* 0x00AE */ + "PSK-AES128-CBC-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_PSK_WITH_AES_256_CBC_SHA384, /* 0x00AF */ + "PSK-AES256-CBC-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_PSK_WITH_NULL_SHA256, /* 0x00B0 */ + "PSK-NULL-SHA256", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_PSK_WITH_NULL_SHA384, /* 0x00B1 */ + "PSK-NULL-SHA384", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_DHE_PSK_WITH_AES_128_CBC_SHA256, /* 0x00B2 */ + "DHE-PSK-AES128-CBC-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, /* 0x00B3 */ + "DHE-PSK-AES256-CBC-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_PSK_WITH_NULL_SHA256, /* 0x00B4 */ + "DHE-PSK-NULL-SHA256", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_DHE_PSK_WITH_NULL_SHA384, /* 0x00B5 */ + "DHE-PSK-NULL-SHA384", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, /* 0x00B6 */ + "RSA-PSK-AES128-CBC-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, /* 0x00B7 */ + "RSA-PSK-AES256-CBC-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_RSA_PSK_WITH_NULL_SHA256, /* 0x00B8 */ + "RSA-PSK-NULL-SHA256", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_RSA_PSK_WITH_NULL_SHA384, /* 0x00B9 */ + "RSA-PSK-NULL-SHA384", + CIPHER_WEAK_NOT_ENCRYPTED), +#endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */ + + /* RFC 5746 - Secure Renegotiation. This is not a real suite, + it is a response to initiate negotiation again */ + CIPHER_DEF(TLS_EMPTY_RENEGOTIATION_INFO_SCSV, /* 0x00FF */ + NULL, + CIPHER_STRONG_ENOUGH), + +#if CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 + /* TLS 1.3 standard cipher suites for ChaCha20+Poly1305. + Note: TLS 1.3 ciphersuites do not specify the key exchange + algorithm -- they only specify the symmetric ciphers. + Cipher alias name matches to OpenSSL cipher name, and for + TLS 1.3 ciphers */ + CIPHER_DEF(TLS_AES_128_GCM_SHA256, /* 0x1301 */ + NULL, /* The OpenSSL cipher name matches to the IANA name */ + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_AES_256_GCM_SHA384, /* 0x1302 */ + NULL, /* The OpenSSL cipher name matches to the IANA name */ + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_CHACHA20_POLY1305_SHA256, /* 0x1303 */ + NULL, /* The OpenSSL cipher name matches to the IANA name */ + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_AES_128_CCM_SHA256, /* 0x1304 */ + NULL, /* The OpenSSL cipher name matches to the IANA name */ + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_AES_128_CCM_8_SHA256, /* 0x1305 */ + NULL, /* The OpenSSL cipher name matches to the IANA name */ + CIPHER_STRONG_ENOUGH), +#endif /* CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 */ + +#if CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS + /* ECDSA addenda, RFC 4492 */ + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_NULL_SHA, /* 0xC001 */ + "ECDH-ECDSA-NULL-SHA", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_RC4_128_SHA, /* 0xC002 */ + "ECDH-ECDSA-RC4-SHA", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, /* 0xC003 */ + "ECDH-ECDSA-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, /* 0xC004 */ + "ECDH-ECDSA-AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, /* 0xC005 */ + "ECDH-ECDSA-AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_NULL_SHA, /* 0xC006 */ + "ECDHE-ECDSA-NULL-SHA", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, /* 0xC007 */ + "ECDHE-ECDSA-RC4-SHA", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, /* 0xC008 */ + "ECDHE-ECDSA-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, /* 0xC009 */ + "ECDHE-ECDSA-AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, /* 0xC00A */ + "ECDHE-ECDSA-AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_RSA_WITH_NULL_SHA, /* 0xC00B */ + "ECDH-RSA-NULL-SHA", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_ECDH_RSA_WITH_RC4_128_SHA, /* 0xC00C */ + "ECDH-RSA-RC4-SHA", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF(TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, /* 0xC00D */ + "ECDH-RSA-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, /* 0xC00E */ + "ECDH-RSA-AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, /* 0xC00F */ + "ECDH-RSA-AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_NULL_SHA, /* 0xC010 */ + "ECDHE-RSA-NULL-SHA", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_RC4_128_SHA, /* 0xC011 */ + "ECDHE-RSA-RC4-SHA", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, /* 0xC012 */ + "ECDHE-RSA-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, /* 0xC013 */ + "ECDHE-RSA-AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, /* 0xC014 */ + "ECDHE-RSA-AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_anon_WITH_NULL_SHA, /* 0xC015 */ + "AECDH-NULL-SHA", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF(TLS_ECDH_anon_WITH_RC4_128_SHA, /* 0xC016 */ + "AECDH-RC4-SHA", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF(TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, /* 0xC017 */ + "AECDH-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(TLS_ECDH_anon_WITH_AES_128_CBC_SHA, /* 0xC018 */ + "AECDH-AES128-SHA", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF(TLS_ECDH_anon_WITH_AES_256_CBC_SHA, /* 0xC019 */ + "AECDH-AES256-SHA", + CIPHER_WEAK_ANON_AUTH), +#endif /* CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS */ + +#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS + /* Addenda from rfc 5289 Elliptic Curve Cipher Suites with + HMAC SHA-256/384. */ + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, /* 0xC023 */ + "ECDHE-ECDSA-AES128-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, /* 0xC024 */ + "ECDHE-ECDSA-AES256-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, /* 0xC025 */ + "ECDH-ECDSA-AES128-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, /* 0xC026 */ + "ECDH-ECDSA-AES256-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, /* 0xC027 */ + "ECDHE-RSA-AES128-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, /* 0xC028 */ + "ECDHE-RSA-AES256-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, /* 0xC029 */ + "ECDH-RSA-AES128-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, /* 0xC02A */ + "ECDH-RSA-AES256-SHA384", + CIPHER_STRONG_ENOUGH), + /* Addenda from rfc 5289 Elliptic Curve Cipher Suites with + SHA-256/384 and AES Galois Counter Mode (GCM) */ + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, /* 0xC02B */ + "ECDHE-ECDSA-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, /* 0xC02C */ + "ECDHE-ECDSA-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, /* 0xC02D */ + "ECDH-ECDSA-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, /* 0xC02E */ + "ECDH-ECDSA-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, /* 0xC02F */ + "ECDHE-RSA-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, /* 0xC030 */ + "ECDHE-RSA-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, /* 0xC031 */ + "ECDH-RSA-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, /* 0xC032 */ + "ECDH-RSA-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), +#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ + +#if CURL_BUILD_MAC_10_15 || CURL_BUILD_IOS_13 + /* ECDHE_PSK Cipher Suites for Transport Layer Security (TLS), RFC 5489 */ + CIPHER_DEF(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA, /* 0xC035 */ + "ECDHE-PSK-AES128-CBC-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA, /* 0xC036 */ + "ECDHE-PSK-AES256-CBC-SHA", + CIPHER_STRONG_ENOUGH), +#endif /* CURL_BUILD_MAC_10_15 || CURL_BUILD_IOS_13 */ + +#if CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 + /* Addenda from rfc 7905 ChaCha20-Poly1305 Cipher Suites for + Transport Layer Security (TLS). */ + CIPHER_DEF(TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCA8 */ + "ECDHE-RSA-CHACHA20-POLY1305", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCA9 */ + "ECDHE-ECDSA-CHACHA20-POLY1305", + CIPHER_STRONG_ENOUGH), +#endif /* CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 */ + +#if CURL_BUILD_MAC_10_15 || CURL_BUILD_IOS_13 + /* ChaCha20-Poly1305 Cipher Suites for Transport Layer Security (TLS), + RFC 7905 */ + CIPHER_DEF(TLS_PSK_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCAB */ + "PSK-CHACHA20-POLY1305", + CIPHER_STRONG_ENOUGH), +#endif /* CURL_BUILD_MAC_10_15 || CURL_BUILD_IOS_13 */ + + /* Tags for SSL 2 cipher kinds which are not specified for SSL 3. + Defined since SDK 10.2.8 */ + CIPHER_DEF(SSL_RSA_WITH_RC2_CBC_MD5, /* 0xFF80 */ + NULL, + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF(SSL_RSA_WITH_IDEA_CBC_MD5, /* 0xFF81 */ + NULL, + CIPHER_WEAK_IDEA_ENCRYPTION), + CIPHER_DEF(SSL_RSA_WITH_DES_CBC_MD5, /* 0xFF82 */ + NULL, + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF(SSL_RSA_WITH_3DES_EDE_CBC_MD5, /* 0xFF83 */ + NULL, + CIPHER_WEAK_3DES_ENCRYPTION), +}; + +#define NUM_OF_CIPHERS sizeof(ciphertable)/sizeof(ciphertable[0]) + + +/* pinned public key support tests */ + +/* version 1 supports macOS 10.12+ and iOS 10+ */ +#if ((TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000) || \ + (!TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200)) +#define SECTRANSP_PINNEDPUBKEY_V1 1 +#endif + +/* version 2 supports MacOSX 10.7+ */ +#if (!TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070) +#define SECTRANSP_PINNEDPUBKEY_V2 1 +#endif + +#if defined(SECTRANSP_PINNEDPUBKEY_V1) || defined(SECTRANSP_PINNEDPUBKEY_V2) +/* this backend supports CURLOPT_PINNEDPUBLICKEY */ +#define SECTRANSP_PINNEDPUBKEY 1 +#endif /* SECTRANSP_PINNEDPUBKEY */ + +#ifdef SECTRANSP_PINNEDPUBKEY +/* both new and old APIs return rsa keys missing the spki header (not DER) */ +static const unsigned char rsa4096SpkiHeader[] = { + 0x30, 0x82, 0x02, 0x22, 0x30, 0x0d, + 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, + 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, + 0x00, 0x03, 0x82, 0x02, 0x0f, 0x00}; + +static const unsigned char rsa2048SpkiHeader[] = { + 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, + 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, + 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, + 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00}; +#ifdef SECTRANSP_PINNEDPUBKEY_V1 +/* the *new* version doesn't return DER encoded ecdsa certs like the old... */ +static const unsigned char ecDsaSecp256r1SpkiHeader[] = { + 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, + 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, + 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, + 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, + 0x42, 0x00}; + +static const unsigned char ecDsaSecp384r1SpkiHeader[] = { + 0x30, 0x76, 0x30, 0x10, 0x06, 0x07, + 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, + 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, + 0x00, 0x22, 0x03, 0x62, 0x00}; +#endif /* SECTRANSP_PINNEDPUBKEY_V1 */ +#endif /* SECTRANSP_PINNEDPUBKEY */ + +static OSStatus sectransp_bio_cf_in_read(SSLConnectionRef connection, + void *buf, + size_t *dataLength) /* IN/OUT */ +{ + struct Curl_cfilter *cf = (struct Curl_cfilter *)connection; + struct ssl_connect_data *connssl = cf->ctx; + struct st_ssl_backend_data *backend = + (struct st_ssl_backend_data *)connssl->backend; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + ssize_t nread; + CURLcode result; + OSStatus rtn = noErr; + + DEBUGASSERT(data); + nread = Curl_conn_cf_recv(cf->next, data, buf, *dataLength, &result); + CURL_TRC_CF(data, cf, "bio_read(len=%zu) -> %zd, result=%d", + *dataLength, nread, result); + if(nread < 0) { + switch(result) { + case CURLE_OK: + case CURLE_AGAIN: + rtn = errSSLWouldBlock; + backend->ssl_direction = false; + break; + default: + rtn = ioErr; + break; + } + nread = 0; + } + else if(nread == 0) { + rtn = errSSLClosedGraceful; + } + else if((size_t)nread < *dataLength) { + rtn = errSSLWouldBlock; + } + *dataLength = nread; + return rtn; +} + +static OSStatus sectransp_bio_cf_out_write(SSLConnectionRef connection, + const void *buf, + size_t *dataLength) /* IN/OUT */ +{ + struct Curl_cfilter *cf = (struct Curl_cfilter *)connection; + struct ssl_connect_data *connssl = cf->ctx; + struct st_ssl_backend_data *backend = + (struct st_ssl_backend_data *)connssl->backend; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + ssize_t nwritten; + CURLcode result; + OSStatus rtn = noErr; + + DEBUGASSERT(data); + nwritten = Curl_conn_cf_send(cf->next, data, buf, *dataLength, &result); + CURL_TRC_CF(data, cf, "bio_send(len=%zu) -> %zd, result=%d", + *dataLength, nwritten, result); + if(nwritten <= 0) { + if(result == CURLE_AGAIN) { + rtn = errSSLWouldBlock; + backend->ssl_direction = true; + } + else { + rtn = ioErr; + } + nwritten = 0; + } + else if((size_t)nwritten < *dataLength) { + rtn = errSSLWouldBlock; + } + *dataLength = nwritten; + return rtn; +} + +CF_INLINE const char *TLSCipherNameForNumber(SSLCipherSuite cipher) +{ + /* The first ciphers in the ciphertable are continuous. Here we do small + optimization and instead of loop directly get SSL name by cipher number. + */ + size_t i; + if(cipher <= SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA) { + return ciphertable[cipher].name; + } + /* Iterate through the rest of the ciphers */ + for(i = SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA + 1; i < NUM_OF_CIPHERS; + ++i) { + if(ciphertable[i].num == cipher) { + return ciphertable[i].name; + } + } + return ciphertable[SSL_NULL_WITH_NULL_NULL].name; +} + +#if CURL_BUILD_MAC +CF_INLINE void GetDarwinVersionNumber(int *major, int *minor) +{ + int mib[2]; + char *os_version; + size_t os_version_len; + char *os_version_major, *os_version_minor; + char *tok_buf; + + /* Get the Darwin kernel version from the kernel using sysctl(): */ + mib[0] = CTL_KERN; + mib[1] = KERN_OSRELEASE; + if(sysctl(mib, 2, NULL, &os_version_len, NULL, 0) == -1) + return; + os_version = malloc(os_version_len*sizeof(char)); + if(!os_version) + return; + if(sysctl(mib, 2, os_version, &os_version_len, NULL, 0) == -1) { + free(os_version); + return; + } + + /* Parse the version: */ + os_version_major = strtok_r(os_version, ".", &tok_buf); + os_version_minor = strtok_r(NULL, ".", &tok_buf); + *major = atoi(os_version_major); + *minor = atoi(os_version_minor); + free(os_version); +} +#endif /* CURL_BUILD_MAC */ + +/* Apple provides a myriad of ways of getting information about a certificate + into a string. Some aren't available under iOS or newer cats. So here's + a unified function for getting a string describing the certificate that + ought to work in all cats starting with Leopard. */ +CF_INLINE CFStringRef getsubject(SecCertificateRef cert) +{ + CFStringRef server_cert_summary = CFSTR("(null)"); + +#if CURL_BUILD_IOS + /* iOS: There's only one way to do this. */ + server_cert_summary = SecCertificateCopySubjectSummary(cert); +#else +#if CURL_BUILD_MAC_10_7 + /* Lion & later: Get the long description if we can. */ + if(SecCertificateCopyLongDescription) + server_cert_summary = + SecCertificateCopyLongDescription(NULL, cert, NULL); + else +#endif /* CURL_BUILD_MAC_10_7 */ +#if CURL_BUILD_MAC_10_6 + /* Snow Leopard: Get the certificate summary. */ + if(SecCertificateCopySubjectSummary) + server_cert_summary = SecCertificateCopySubjectSummary(cert); + else +#endif /* CURL_BUILD_MAC_10_6 */ + /* Leopard is as far back as we go... */ + (void)SecCertificateCopyCommonName(cert, &server_cert_summary); +#endif /* CURL_BUILD_IOS */ + return server_cert_summary; +} + +static CURLcode CopyCertSubject(struct Curl_easy *data, + SecCertificateRef cert, char **certp) +{ + CFStringRef c = getsubject(cert); + CURLcode result = CURLE_OK; + const char *direct; + char *cbuf = NULL; + *certp = NULL; + + if(!c) { + failf(data, "SSL: invalid CA certificate subject"); + return CURLE_PEER_FAILED_VERIFICATION; + } + + /* If the subject is already available as UTF-8 encoded (ie 'direct') then + use that, else convert it. */ + direct = CFStringGetCStringPtr(c, kCFStringEncodingUTF8); + if(direct) { + *certp = strdup(direct); + if(!*certp) { + failf(data, "SSL: out of memory"); + result = CURLE_OUT_OF_MEMORY; + } + } + else { + size_t cbuf_size = ((size_t)CFStringGetLength(c) * 4) + 1; + cbuf = calloc(1, cbuf_size); + if(cbuf) { + if(!CFStringGetCString(c, cbuf, cbuf_size, + kCFStringEncodingUTF8)) { + failf(data, "SSL: invalid CA certificate subject"); + result = CURLE_PEER_FAILED_VERIFICATION; + } + else + /* pass back the buffer */ + *certp = cbuf; + } + else { + failf(data, "SSL: couldn't allocate %zu bytes of memory", cbuf_size); + result = CURLE_OUT_OF_MEMORY; + } + } + if(result) + free(cbuf); + CFRelease(c); + return result; +} + +#if CURL_SUPPORT_MAC_10_6 +/* The SecKeychainSearch API was deprecated in Lion, and using it will raise + deprecation warnings, so let's not compile this unless it's necessary: */ +static OSStatus CopyIdentityWithLabelOldSchool(char *label, + SecIdentityRef *out_c_a_k) +{ + OSStatus status = errSecItemNotFound; + SecKeychainAttributeList attr_list; + SecKeychainAttribute attr; + SecKeychainSearchRef search = NULL; + SecCertificateRef cert = NULL; + + /* Set up the attribute list: */ + attr_list.count = 1L; + attr_list.attr = &attr; + + /* Set up our lone search criterion: */ + attr.tag = kSecLabelItemAttr; + attr.data = label; + attr.length = (UInt32)strlen(label); + + /* Start searching: */ + status = SecKeychainSearchCreateFromAttributes(NULL, + kSecCertificateItemClass, + &attr_list, + &search); + if(status == noErr) { + status = SecKeychainSearchCopyNext(search, + (SecKeychainItemRef *)&cert); + if(status == noErr && cert) { + /* If we found a certificate, does it have a private key? */ + status = SecIdentityCreateWithCertificate(NULL, cert, out_c_a_k); + CFRelease(cert); + } + } + + if(search) + CFRelease(search); + return status; +} +#endif /* CURL_SUPPORT_MAC_10_6 */ + +static OSStatus CopyIdentityWithLabel(char *label, + SecIdentityRef *out_cert_and_key) +{ + OSStatus status = errSecItemNotFound; + +#if CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS + CFArrayRef keys_list; + CFIndex keys_list_count; + CFIndex i; + + /* SecItemCopyMatching() was introduced in iOS and Snow Leopard. + kSecClassIdentity was introduced in Lion. If both exist, let's use them + to find the certificate. */ + if(SecItemCopyMatching && kSecClassIdentity) { + CFTypeRef keys[5]; + CFTypeRef values[5]; + CFDictionaryRef query_dict; + CFStringRef label_cf = CFStringCreateWithCString(NULL, label, + kCFStringEncodingUTF8); + + /* Set up our search criteria and expected results: */ + values[0] = kSecClassIdentity; /* we want a certificate and a key */ + keys[0] = kSecClass; + values[1] = kCFBooleanTrue; /* we want a reference */ + keys[1] = kSecReturnRef; + values[2] = kSecMatchLimitAll; /* kSecMatchLimitOne would be better if the + * label matching below worked correctly */ + keys[2] = kSecMatchLimit; + /* identity searches need a SecPolicyRef in order to work */ + values[3] = SecPolicyCreateSSL(false, NULL); + keys[3] = kSecMatchPolicy; + /* match the name of the certificate (doesn't work in macOS 10.12.1) */ + values[4] = label_cf; + keys[4] = kSecAttrLabel; + query_dict = CFDictionaryCreate(NULL, (const void **)keys, + (const void **)values, 5L, + &kCFCopyStringDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + CFRelease(values[3]); + + /* Do we have a match? */ + status = SecItemCopyMatching(query_dict, (CFTypeRef *) &keys_list); + + /* Because kSecAttrLabel matching doesn't work with kSecClassIdentity, + * we need to find the correct identity ourselves */ + if(status == noErr) { + keys_list_count = CFArrayGetCount(keys_list); + *out_cert_and_key = NULL; + status = 1; + for(i = 0; idata, blob->len); + status = (pkcs_data != NULL) ? errSecSuccess : errSecAllocate; + resource_imported = (pkcs_data != NULL); + } + else { + pkcs_url = + CFURLCreateFromFileSystemRepresentation(NULL, + (const UInt8 *)cPath, + strlen(cPath), false); + resource_imported = + CFURLCreateDataAndPropertiesFromResource(NULL, + pkcs_url, &pkcs_data, + NULL, NULL, &status); + } + + if(resource_imported) { + CFArrayRef items = NULL; + + /* On iOS SecPKCS12Import will never add the client certificate to the + * Keychain. + * + * It gives us back a SecIdentityRef that we can use directly. */ +#if CURL_BUILD_IOS + const void *cKeys[] = {kSecImportExportPassphrase}; + const void *cValues[] = {password}; + CFDictionaryRef options = CFDictionaryCreate(NULL, cKeys, cValues, + password ? 1L : 0L, NULL, NULL); + + if(options) { + status = SecPKCS12Import(pkcs_data, options, &items); + CFRelease(options); + } + + + /* On macOS SecPKCS12Import will always add the client certificate to + * the Keychain. + * + * As this doesn't match iOS, and apps may not want to see their client + * certificate saved in the user's keychain, we use SecItemImport + * with a NULL keychain to avoid importing it. + * + * This returns a SecCertificateRef from which we can construct a + * SecIdentityRef. + */ +#elif CURL_BUILD_MAC_10_7 + SecItemImportExportKeyParameters keyParams; + SecExternalFormat inputFormat = kSecFormatPKCS12; + SecExternalItemType inputType = kSecItemTypeCertificate; + + memset(&keyParams, 0x00, sizeof(keyParams)); + keyParams.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION; + keyParams.passphrase = password; + + status = SecItemImport(pkcs_data, NULL, &inputFormat, &inputType, + 0, &keyParams, NULL, &items); +#endif + + + /* Extract the SecIdentityRef */ + if(status == errSecSuccess && items && CFArrayGetCount(items)) { + CFIndex i, count; + count = CFArrayGetCount(items); + + for(i = 0; i < count; i++) { + CFTypeRef item = (CFTypeRef) CFArrayGetValueAtIndex(items, i); + CFTypeID itemID = CFGetTypeID(item); + + if(itemID == CFDictionaryGetTypeID()) { + CFTypeRef identity = (CFTypeRef) CFDictionaryGetValue( + (CFDictionaryRef) item, + kSecImportItemIdentity); + CFRetain(identity); + *out_cert_and_key = (SecIdentityRef) identity; + break; + } +#if CURL_BUILD_MAC_10_7 + else if(itemID == SecCertificateGetTypeID()) { + status = SecIdentityCreateWithCertificate(NULL, + (SecCertificateRef) item, + out_cert_and_key); + break; + } +#endif + } + } + + if(items) + CFRelease(items); + CFRelease(pkcs_data); + } +#endif /* CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS */ + if(password) + CFRelease(password); + if(pkcs_url) + CFRelease(pkcs_url); + return status; +} + +/* This code was borrowed from nss.c, with some modifications: + * Determine whether the nickname passed in is a filename that needs to + * be loaded as a PEM or a nickname. + * + * returns 1 for a file + * returns 0 for not a file + */ +CF_INLINE bool is_file(const char *filename) +{ + struct_stat st; + + if(!filename) + return false; + + if(stat(filename, &st) == 0) + return S_ISREG(st.st_mode); + return false; +} + +#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS +static CURLcode sectransp_version_from_curl(SSLProtocol *darwinver, + long ssl_version) +{ + switch(ssl_version) { + case CURL_SSLVERSION_TLSv1_0: + *darwinver = kTLSProtocol1; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_1: + *darwinver = kTLSProtocol11; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_2: + *darwinver = kTLSProtocol12; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_3: + /* TLS 1.3 support first appeared in iOS 11 and macOS 10.13 */ +#if (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1 + if(__builtin_available(macOS 10.13, iOS 11.0, *)) { + *darwinver = kTLSProtocol13; + return CURLE_OK; + } +#endif /* (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && + HAVE_BUILTIN_AVAILABLE == 1 */ + break; + } + return CURLE_SSL_CONNECT_ERROR; +} +#endif + +static CURLcode set_ssl_version_min_max(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct st_ssl_backend_data *backend = + (struct st_ssl_backend_data *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + long ssl_version = conn_config->version; + long ssl_version_max = conn_config->version_max; + long max_supported_version_by_os; + + DEBUGASSERT(backend); + + /* macOS 10.5-10.7 supported TLS 1.0 only. + macOS 10.8 and later, and iOS 5 and later, added TLS 1.1 and 1.2. + macOS 10.13 and later, and iOS 11 and later, added TLS 1.3. */ +#if (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1 + if(__builtin_available(macOS 10.13, iOS 11.0, *)) { + max_supported_version_by_os = CURL_SSLVERSION_MAX_TLSv1_3; + } + else { + max_supported_version_by_os = CURL_SSLVERSION_MAX_TLSv1_2; + } +#else + max_supported_version_by_os = CURL_SSLVERSION_MAX_TLSv1_2; +#endif /* (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && + HAVE_BUILTIN_AVAILABLE == 1 */ + + switch(ssl_version) { + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1: + ssl_version = CURL_SSLVERSION_TLSv1_0; + break; + } + + switch(ssl_version_max) { + case CURL_SSLVERSION_MAX_NONE: + case CURL_SSLVERSION_MAX_DEFAULT: + ssl_version_max = max_supported_version_by_os; + break; + } + +#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS + if(SSLSetProtocolVersionMax) { + SSLProtocol darwin_ver_min = kTLSProtocol1; + SSLProtocol darwin_ver_max = kTLSProtocol1; + CURLcode result = sectransp_version_from_curl(&darwin_ver_min, + ssl_version); + if(result) { + failf(data, "unsupported min version passed via CURLOPT_SSLVERSION"); + return result; + } + result = sectransp_version_from_curl(&darwin_ver_max, + ssl_version_max >> 16); + if(result) { + failf(data, "unsupported max version passed via CURLOPT_SSLVERSION"); + return result; + } + + (void)SSLSetProtocolVersionMin(backend->ssl_ctx, darwin_ver_min); + (void)SSLSetProtocolVersionMax(backend->ssl_ctx, darwin_ver_max); + return result; + } + else { +#if CURL_SUPPORT_MAC_10_8 + long i = ssl_version; + (void)SSLSetProtocolVersionEnabled(backend->ssl_ctx, + kSSLProtocolAll, + false); + for(; i <= (ssl_version_max >> 16); i++) { + switch(i) { + case CURL_SSLVERSION_TLSv1_0: + (void)SSLSetProtocolVersionEnabled(backend->ssl_ctx, + kTLSProtocol1, + true); + break; + case CURL_SSLVERSION_TLSv1_1: + (void)SSLSetProtocolVersionEnabled(backend->ssl_ctx, + kTLSProtocol11, + true); + break; + case CURL_SSLVERSION_TLSv1_2: + (void)SSLSetProtocolVersionEnabled(backend->ssl_ctx, + kTLSProtocol12, + true); + break; + case CURL_SSLVERSION_TLSv1_3: + failf(data, "Your version of the OS does not support TLSv1.3"); + return CURLE_SSL_CONNECT_ERROR; + } + } + return CURLE_OK; +#endif /* CURL_SUPPORT_MAC_10_8 */ + } +#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ + failf(data, "Secure Transport: cannot set SSL protocol"); + return CURLE_SSL_CONNECT_ERROR; +} + +static bool is_cipher_suite_strong(SSLCipherSuite suite_num) +{ + size_t i; + for(i = 0; i < NUM_OF_CIPHERS; ++i) { + if(ciphertable[i].num == suite_num) { + return !ciphertable[i].weak; + } + } + /* If the cipher is not in our list, assume it is a new one + and therefore strong. Previous implementation was the same, + if cipher suite is not in the list, it was considered strong enough */ + return true; +} + +static bool sectransp_is_separator(char c) +{ + /* Return whether character is a cipher list separator. */ + switch(c) { + case ' ': + case '\t': + case ':': + case ',': + case ';': + return true; + } + return false; +} + +static CURLcode sectransp_set_default_ciphers(struct Curl_easy *data, + SSLContextRef ssl_ctx) +{ + size_t all_ciphers_count = 0UL, allowed_ciphers_count = 0UL, i; + SSLCipherSuite *all_ciphers = NULL, *allowed_ciphers = NULL; + OSStatus err = noErr; + +#if CURL_BUILD_MAC + int darwinver_maj = 0, darwinver_min = 0; + + GetDarwinVersionNumber(&darwinver_maj, &darwinver_min); +#endif /* CURL_BUILD_MAC */ + + /* Disable cipher suites that ST supports but are not safe. These ciphers + are unlikely to be used in any case since ST gives other ciphers a much + higher priority, but it's probably better that we not connect at all than + to give the user a false sense of security if the server only supports + insecure ciphers. (Note: We don't care about SSLv2-only ciphers.) */ + err = SSLGetNumberSupportedCiphers(ssl_ctx, &all_ciphers_count); + if(err != noErr) { + failf(data, "SSL: SSLGetNumberSupportedCiphers() failed: OSStatus %d", + err); + return CURLE_SSL_CIPHER; + } + all_ciphers = malloc(all_ciphers_count*sizeof(SSLCipherSuite)); + if(!all_ciphers) { + failf(data, "SSL: Failed to allocate memory for all ciphers"); + return CURLE_OUT_OF_MEMORY; + } + allowed_ciphers = malloc(all_ciphers_count*sizeof(SSLCipherSuite)); + if(!allowed_ciphers) { + Curl_safefree(all_ciphers); + failf(data, "SSL: Failed to allocate memory for allowed ciphers"); + return CURLE_OUT_OF_MEMORY; + } + err = SSLGetSupportedCiphers(ssl_ctx, all_ciphers, + &all_ciphers_count); + if(err != noErr) { + Curl_safefree(all_ciphers); + Curl_safefree(allowed_ciphers); + return CURLE_SSL_CIPHER; + } + for(i = 0UL ; i < all_ciphers_count ; i++) { +#if CURL_BUILD_MAC + /* There's a known bug in early versions of Mountain Lion where ST's ECC + ciphers (cipher suite 0xC001 through 0xC032) simply do not work. + Work around the problem here by disabling those ciphers if we are + running in an affected version of OS X. */ + if(darwinver_maj == 12 && darwinver_min <= 3 && + all_ciphers[i] >= 0xC001 && all_ciphers[i] <= 0xC032) { + continue; + } +#endif /* CURL_BUILD_MAC */ + if(is_cipher_suite_strong(all_ciphers[i])) { + allowed_ciphers[allowed_ciphers_count++] = all_ciphers[i]; + } + } + err = SSLSetEnabledCiphers(ssl_ctx, allowed_ciphers, + allowed_ciphers_count); + Curl_safefree(all_ciphers); + Curl_safefree(allowed_ciphers); + if(err != noErr) { + failf(data, "SSL: SSLSetEnabledCiphers() failed: OSStatus %d", err); + return CURLE_SSL_CIPHER; + } + return CURLE_OK; +} + +static CURLcode sectransp_set_selected_ciphers(struct Curl_easy *data, + SSLContextRef ssl_ctx, + const char *ciphers) +{ + size_t ciphers_count = 0; + const char *cipher_start = ciphers; + OSStatus err = noErr; + SSLCipherSuite selected_ciphers[NUM_OF_CIPHERS]; + + if(!ciphers) + return CURLE_OK; + + while(sectransp_is_separator(*ciphers)) /* Skip initial separators. */ + ciphers++; + if(!*ciphers) + return CURLE_OK; + + cipher_start = ciphers; + while(*cipher_start && ciphers_count < NUM_OF_CIPHERS) { + bool cipher_found = FALSE; + size_t cipher_len = 0; + const char *cipher_end = NULL; + bool tls_name = FALSE; + size_t i; + + /* Skip separators */ + while(sectransp_is_separator(*cipher_start)) + cipher_start++; + if(*cipher_start == '\0') { + break; + } + /* Find last position of a cipher in the ciphers string */ + cipher_end = cipher_start; + while(*cipher_end != '\0' && !sectransp_is_separator(*cipher_end)) { + ++cipher_end; + } + + /* IANA cipher names start with the TLS_ or SSL_ prefix. + If the 4th symbol of the cipher is '_' we look for a cipher in the + table by its (TLS) name. + Otherwise, we try to match cipher by an alias. */ + if(cipher_start[3] == '_') { + tls_name = TRUE; + } + /* Iterate through the cipher table and look for the cipher, starting + the cipher number 0x01 because the 0x00 is not the real cipher */ + cipher_len = cipher_end - cipher_start; + for(i = 1; i < NUM_OF_CIPHERS; ++i) { + const char *table_cipher_name = NULL; + if(tls_name) { + table_cipher_name = ciphertable[i].name; + } + else if(ciphertable[i].alias_name) { + table_cipher_name = ciphertable[i].alias_name; + } + else { + continue; + } + /* Compare a part of the string between separators with a cipher name + in the table and make sure we matched the whole cipher name */ + if(strncmp(cipher_start, table_cipher_name, cipher_len) == 0 + && table_cipher_name[cipher_len] == '\0') { + selected_ciphers[ciphers_count] = ciphertable[i].num; + ++ciphers_count; + cipher_found = TRUE; + break; + } + } + if(!cipher_found) { + /* It would be more human-readable if we print the wrong cipher name + but we don't want to allocate any additional memory and copy the name + into it, then add it into logs. + Also, we do not modify an original cipher list string. We just point + to positions where cipher starts and ends in the cipher list string. + The message is a bit cryptic and longer than necessary but can be + understood by humans. */ + failf(data, "SSL: cipher string \"%s\" contains unsupported cipher name" + " starting position %zd and ending position %zd", + ciphers, + cipher_start - ciphers, + cipher_end - ciphers); + return CURLE_SSL_CIPHER; + } + if(*cipher_end) { + cipher_start = cipher_end + 1; + } + else { + break; + } + } + /* All cipher suites in the list are found. Report to logs as-is */ + infof(data, "SSL: Setting cipher suites list \"%s\"", ciphers); + + err = SSLSetEnabledCiphers(ssl_ctx, selected_ciphers, ciphers_count); + if(err != noErr) { + failf(data, "SSL: SSLSetEnabledCiphers() failed: OSStatus %d", err); + return CURLE_SSL_CIPHER; + } + return CURLE_OK; +} + +static void sectransp_session_free(void *sessionid, size_t idsize) +{ + /* ST, as of iOS 5 and Mountain Lion, has no public method of deleting a + cached session ID inside the Security framework. There is a private + function that does this, but I don't want to have to explain to you why I + got your application rejected from the App Store due to the use of a + private API, so the best we can do is free up our own char array that we + created way back in sectransp_connect_step1... */ + (void)idsize; + Curl_safefree(sessionid); +} + +static CURLcode sectransp_connect_step1(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct st_ssl_backend_data *backend = + (struct st_ssl_backend_data *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + const struct curl_blob *ssl_cablob = conn_config->ca_info_blob; + const char * const ssl_cafile = + /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */ + (ssl_cablob ? NULL : conn_config->CAfile); + const bool verifypeer = conn_config->verifypeer; + char * const ssl_cert = ssl_config->primary.clientcert; + const struct curl_blob *ssl_cert_blob = ssl_config->primary.cert_blob; + char *ciphers; + OSStatus err = noErr; +#if CURL_BUILD_MAC + int darwinver_maj = 0, darwinver_min = 0; + + DEBUGASSERT(backend); + + CURL_TRC_CF(data, cf, "connect_step1"); + GetDarwinVersionNumber(&darwinver_maj, &darwinver_min); +#endif /* CURL_BUILD_MAC */ + +#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS + if(SSLCreateContext) { /* use the newer API if available */ + if(backend->ssl_ctx) + CFRelease(backend->ssl_ctx); + backend->ssl_ctx = SSLCreateContext(NULL, kSSLClientSide, kSSLStreamType); + if(!backend->ssl_ctx) { + failf(data, "SSL: couldn't create a context"); + return CURLE_OUT_OF_MEMORY; + } + } + else { + /* The old ST API does not exist under iOS, so don't compile it: */ +#if CURL_SUPPORT_MAC_10_8 + if(backend->ssl_ctx) + (void)SSLDisposeContext(backend->ssl_ctx); + err = SSLNewContext(false, &(backend->ssl_ctx)); + if(err != noErr) { + failf(data, "SSL: couldn't create a context: OSStatus %d", err); + return CURLE_OUT_OF_MEMORY; + } +#endif /* CURL_SUPPORT_MAC_10_8 */ + } +#else + if(backend->ssl_ctx) + (void)SSLDisposeContext(backend->ssl_ctx); + err = SSLNewContext(false, &(backend->ssl_ctx)); + if(err != noErr) { + failf(data, "SSL: couldn't create a context: OSStatus %d", err); + return CURLE_OUT_OF_MEMORY; + } +#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ + backend->ssl_write_buffered_length = 0UL; /* reset buffered write length */ + + /* check to see if we've been told to use an explicit SSL/TLS version */ +#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS + if(SSLSetProtocolVersionMax) { + switch(conn_config->version) { + case CURL_SSLVERSION_TLSv1: + (void)SSLSetProtocolVersionMin(backend->ssl_ctx, kTLSProtocol1); +#if (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1 + if(__builtin_available(macOS 10.13, iOS 11.0, *)) { + (void)SSLSetProtocolVersionMax(backend->ssl_ctx, kTLSProtocol13); + } + else { + (void)SSLSetProtocolVersionMax(backend->ssl_ctx, kTLSProtocol12); + } +#else + (void)SSLSetProtocolVersionMax(backend->ssl_ctx, kTLSProtocol12); +#endif /* (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && + HAVE_BUILTIN_AVAILABLE == 1 */ + break; + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1_0: + case CURL_SSLVERSION_TLSv1_1: + case CURL_SSLVERSION_TLSv1_2: + case CURL_SSLVERSION_TLSv1_3: + { + CURLcode result = set_ssl_version_min_max(cf, data); + if(result != CURLE_OK) + return result; + break; + } + case CURL_SSLVERSION_SSLv3: + case CURL_SSLVERSION_SSLv2: + failf(data, "SSL versions not supported"); + return CURLE_NOT_BUILT_IN; + default: + failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); + return CURLE_SSL_CONNECT_ERROR; + } + } + else { +#if CURL_SUPPORT_MAC_10_8 + (void)SSLSetProtocolVersionEnabled(backend->ssl_ctx, + kSSLProtocolAll, + false); + switch(conn_config->version) { + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1: + (void)SSLSetProtocolVersionEnabled(backend->ssl_ctx, + kTLSProtocol1, + true); + (void)SSLSetProtocolVersionEnabled(backend->ssl_ctx, + kTLSProtocol11, + true); + (void)SSLSetProtocolVersionEnabled(backend->ssl_ctx, + kTLSProtocol12, + true); + break; + case CURL_SSLVERSION_TLSv1_0: + case CURL_SSLVERSION_TLSv1_1: + case CURL_SSLVERSION_TLSv1_2: + case CURL_SSLVERSION_TLSv1_3: + { + CURLcode result = set_ssl_version_min_max(cf, data); + if(result != CURLE_OK) + return result; + break; + } + case CURL_SSLVERSION_SSLv3: + case CURL_SSLVERSION_SSLv2: + failf(data, "SSL versions not supported"); + return CURLE_NOT_BUILT_IN; + default: + failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); + return CURLE_SSL_CONNECT_ERROR; + } +#endif /* CURL_SUPPORT_MAC_10_8 */ + } +#else + if(conn_config->version_max != CURL_SSLVERSION_MAX_NONE) { + failf(data, "Your version of the OS does not support to set maximum" + " SSL/TLS version"); + return CURLE_SSL_CONNECT_ERROR; + } + (void)SSLSetProtocolVersionEnabled(backend->ssl_ctx, kSSLProtocolAll, false); + switch(conn_config->version) { + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1: + case CURL_SSLVERSION_TLSv1_0: + (void)SSLSetProtocolVersionEnabled(backend->ssl_ctx, + kTLSProtocol1, + true); + break; + case CURL_SSLVERSION_TLSv1_1: + failf(data, "Your version of the OS does not support TLSv1.1"); + return CURLE_SSL_CONNECT_ERROR; + case CURL_SSLVERSION_TLSv1_2: + failf(data, "Your version of the OS does not support TLSv1.2"); + return CURLE_SSL_CONNECT_ERROR; + case CURL_SSLVERSION_TLSv1_3: + failf(data, "Your version of the OS does not support TLSv1.3"); + return CURLE_SSL_CONNECT_ERROR; + case CURL_SSLVERSION_SSLv2: + case CURL_SSLVERSION_SSLv3: + failf(data, "SSL versions not supported"); + return CURLE_NOT_BUILT_IN; + default: + failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); + return CURLE_SSL_CONNECT_ERROR; + } +#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ + +#if (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1 + if(connssl->alpn) { + if(__builtin_available(macOS 10.13.4, iOS 11, tvOS 11, *)) { + struct alpn_proto_buf proto; + size_t i; + CFStringRef cstr; + CFMutableArrayRef alpnArr = CFArrayCreateMutable(NULL, 0, + &kCFTypeArrayCallBacks); + for(i = 0; i < connssl->alpn->count; ++i) { + cstr = CFStringCreateWithCString(NULL, connssl->alpn->entries[i], + kCFStringEncodingUTF8); + if(!cstr) + return CURLE_OUT_OF_MEMORY; + CFArrayAppendValue(alpnArr, cstr); + CFRelease(cstr); + } + err = SSLSetALPNProtocols(backend->ssl_ctx, alpnArr); + if(err != noErr) + infof(data, "WARNING: failed to set ALPN protocols; OSStatus %d", + err); + CFRelease(alpnArr); + Curl_alpn_to_proto_str(&proto, connssl->alpn); + infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data); + } + } +#endif + + if(ssl_config->key) { + infof(data, "WARNING: SSL: CURLOPT_SSLKEY is ignored by Secure " + "Transport. The private key must be in the Keychain."); + } + + if(ssl_cert || ssl_cert_blob) { + bool is_cert_data = ssl_cert_blob != NULL; + bool is_cert_file = (!is_cert_data) && is_file(ssl_cert); + SecIdentityRef cert_and_key = NULL; + + /* User wants to authenticate with a client cert. Look for it. Assume that + the user wants to use an identity loaded from the Keychain. If not, try + it as a file on disk */ + + if(!is_cert_data) + err = CopyIdentityWithLabel(ssl_cert, &cert_and_key); + else + err = !noErr; + if((err != noErr) && (is_cert_file || is_cert_data)) { + if(!ssl_config->cert_type) + infof(data, "SSL: Certificate type not set, assuming " + "PKCS#12 format."); + else if(!strcasecompare(ssl_config->cert_type, "P12")) { + failf(data, "SSL: The Security framework only supports " + "loading identities that are in PKCS#12 format."); + return CURLE_SSL_CERTPROBLEM; + } + + err = CopyIdentityFromPKCS12File(ssl_cert, ssl_cert_blob, + ssl_config->key_passwd, + &cert_and_key); + } + + if(err == noErr && cert_and_key) { + SecCertificateRef cert = NULL; + CFTypeRef certs_c[1]; + CFArrayRef certs; + + /* If we found one, print it out: */ + err = SecIdentityCopyCertificate(cert_and_key, &cert); + if(err == noErr) { + char *certp; + CURLcode result = CopyCertSubject(data, cert, &certp); + if(!result) { + infof(data, "Client certificate: %s", certp); + free(certp); + } + + CFRelease(cert); + if(result == CURLE_PEER_FAILED_VERIFICATION) + return CURLE_SSL_CERTPROBLEM; + if(result) + return result; + } + certs_c[0] = cert_and_key; + certs = CFArrayCreate(NULL, (const void **)certs_c, 1L, + &kCFTypeArrayCallBacks); + err = SSLSetCertificate(backend->ssl_ctx, certs); + if(certs) + CFRelease(certs); + if(err != noErr) { + failf(data, "SSL: SSLSetCertificate() failed: OSStatus %d", err); + return CURLE_SSL_CERTPROBLEM; + } + CFRelease(cert_and_key); + } + else { + const char *cert_showfilename_error = + is_cert_data ? "(memory blob)" : ssl_cert; + + switch(err) { + case errSecAuthFailed: case -25264: /* errSecPkcs12VerifyFailure */ + failf(data, "SSL: Incorrect password for the certificate \"%s\" " + "and its private key.", cert_showfilename_error); + break; + case -26275: /* errSecDecode */ case -25257: /* errSecUnknownFormat */ + failf(data, "SSL: Couldn't make sense of the data in the " + "certificate \"%s\" and its private key.", + cert_showfilename_error); + break; + case -25260: /* errSecPassphraseRequired */ + failf(data, "SSL The certificate \"%s\" requires a password.", + cert_showfilename_error); + break; + case errSecItemNotFound: + failf(data, "SSL: Can't find the certificate \"%s\" and its private " + "key in the Keychain.", cert_showfilename_error); + break; + default: + failf(data, "SSL: Can't load the certificate \"%s\" and its private " + "key: OSStatus %d", cert_showfilename_error, err); + break; + } + return CURLE_SSL_CERTPROBLEM; + } + } + + /* SSL always tries to verify the peer, this only says whether it should + * fail to connect if the verification fails, or if it should continue + * anyway. In the latter case the result of the verification is checked with + * SSL_get_verify_result() below. */ +#if CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS + /* Snow Leopard introduced the SSLSetSessionOption() function, but due to + a library bug with the way the kSSLSessionOptionBreakOnServerAuth flag + works, it doesn't work as expected under Snow Leopard, Lion or + Mountain Lion. + So we need to call SSLSetEnableCertVerify() on those older cats in order + to disable certificate validation if the user turned that off. + (SecureTransport will always validate the certificate chain by + default.) + Note: + Darwin 11.x.x is Lion (10.7) + Darwin 12.x.x is Mountain Lion (10.8) + Darwin 13.x.x is Mavericks (10.9) + Darwin 14.x.x is Yosemite (10.10) + Darwin 15.x.x is El Capitan (10.11) + */ +#if CURL_BUILD_MAC + if(SSLSetSessionOption && darwinver_maj >= 13) { +#else + if(SSLSetSessionOption) { +#endif /* CURL_BUILD_MAC */ + bool break_on_auth = !conn_config->verifypeer || + ssl_cafile || ssl_cablob; + err = SSLSetSessionOption(backend->ssl_ctx, + kSSLSessionOptionBreakOnServerAuth, + break_on_auth); + if(err != noErr) { + failf(data, "SSL: SSLSetSessionOption() failed: OSStatus %d", err); + return CURLE_SSL_CONNECT_ERROR; + } + } + else { +#if CURL_SUPPORT_MAC_10_8 + err = SSLSetEnableCertVerify(backend->ssl_ctx, + conn_config->verifypeer?true:false); + if(err != noErr) { + failf(data, "SSL: SSLSetEnableCertVerify() failed: OSStatus %d", err); + return CURLE_SSL_CONNECT_ERROR; + } +#endif /* CURL_SUPPORT_MAC_10_8 */ + } +#else + err = SSLSetEnableCertVerify(backend->ssl_ctx, + conn_config->verifypeer?true:false); + if(err != noErr) { + failf(data, "SSL: SSLSetEnableCertVerify() failed: OSStatus %d", err); + return CURLE_SSL_CONNECT_ERROR; + } +#endif /* CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS */ + + if((ssl_cafile || ssl_cablob) && verifypeer) { + bool is_cert_data = ssl_cablob != NULL; + bool is_cert_file = (!is_cert_data) && is_file(ssl_cafile); + + if(!(is_cert_file || is_cert_data)) { + failf(data, "SSL: can't load CA certificate file %s", + ssl_cafile ? ssl_cafile : "(blob memory)"); + return CURLE_SSL_CACERT_BADFILE; + } + } + + /* Configure hostname check. SNI is used if available. + * Both hostname check and SNI require SSLSetPeerDomainName(). + * Also: the verifyhost setting influences SNI usage */ + if(conn_config->verifyhost) { + char *server = connssl->peer.sni? + connssl->peer.sni : connssl->peer.hostname; + err = SSLSetPeerDomainName(backend->ssl_ctx, server, strlen(server)); + + if(err != noErr) { + failf(data, "SSL: SSLSetPeerDomainName() failed: OSStatus %d", + err); + return CURLE_SSL_CONNECT_ERROR; + } + + if(connssl->peer.type != CURL_SSL_PEER_DNS) { + infof(data, "WARNING: using IP address, SNI is being disabled by " + "the OS."); + } + } + else { + infof(data, "WARNING: disabling hostname validation also disables SNI."); + } + + ciphers = conn_config->cipher_list; + if(ciphers) { + err = sectransp_set_selected_ciphers(data, backend->ssl_ctx, ciphers); + } + else { + err = sectransp_set_default_ciphers(data, backend->ssl_ctx); + } + if(err != noErr) { + failf(data, "SSL: Unable to set ciphers for SSL/TLS handshake. " + "Error code: %d", err); + return CURLE_SSL_CIPHER; + } + +#if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 + /* We want to enable 1/n-1 when using a CBC cipher unless the user + specifically doesn't want us doing that: */ + if(SSLSetSessionOption) { + SSLSetSessionOption(backend->ssl_ctx, kSSLSessionOptionSendOneByteRecord, + !ssl_config->enable_beast); + SSLSetSessionOption(backend->ssl_ctx, kSSLSessionOptionFalseStart, + ssl_config->falsestart); /* false start support */ + } +#endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */ + + /* Check if there's a cached ID we can/should use here! */ + if(ssl_config->primary.sessionid) { + char *ssl_sessionid; + size_t ssl_sessionid_len; + + Curl_ssl_sessionid_lock(data); + if(!Curl_ssl_getsessionid(cf, data, &connssl->peer, + (void **)&ssl_sessionid, &ssl_sessionid_len)) { + /* we got a session id, use it! */ + err = SSLSetPeerID(backend->ssl_ctx, ssl_sessionid, ssl_sessionid_len); + Curl_ssl_sessionid_unlock(data); + if(err != noErr) { + failf(data, "SSL: SSLSetPeerID() failed: OSStatus %d", err); + return CURLE_SSL_CONNECT_ERROR; + } + /* Informational message */ + infof(data, "SSL reusing session ID"); + } + /* If there isn't one, then let's make one up! This has to be done prior + to starting the handshake. */ + else { + CURLcode result; + ssl_sessionid = + aprintf("%s:%d:%d:%s:%d", + ssl_cafile ? ssl_cafile : "(blob memory)", + verifypeer, conn_config->verifyhost, connssl->peer.hostname, + connssl->peer.port); + ssl_sessionid_len = strlen(ssl_sessionid); + + err = SSLSetPeerID(backend->ssl_ctx, ssl_sessionid, ssl_sessionid_len); + if(err != noErr) { + Curl_ssl_sessionid_unlock(data); + failf(data, "SSL: SSLSetPeerID() failed: OSStatus %d", err); + return CURLE_SSL_CONNECT_ERROR; + } + + result = Curl_ssl_addsessionid(cf, data, &connssl->peer, ssl_sessionid, + ssl_sessionid_len, + sectransp_session_free); + Curl_ssl_sessionid_unlock(data); + if(result) + return result; + } + } + + err = SSLSetIOFuncs(backend->ssl_ctx, + sectransp_bio_cf_in_read, + sectransp_bio_cf_out_write); + if(err != noErr) { + failf(data, "SSL: SSLSetIOFuncs() failed: OSStatus %d", err); + return CURLE_SSL_CONNECT_ERROR; + } + + err = SSLSetConnection(backend->ssl_ctx, cf); + if(err != noErr) { + failf(data, "SSL: SSLSetConnection() failed: %d", err); + return CURLE_SSL_CONNECT_ERROR; + } + + connssl->connecting_state = ssl_connect_2; + return CURLE_OK; +} + +static long pem_to_der(const char *in, unsigned char **out, size_t *outlen) +{ + char *sep_start, *sep_end, *cert_start, *cert_end; + size_t i, j, err; + size_t len; + unsigned char *b64; + + /* Jump through the separators at the beginning of the certificate. */ + sep_start = strstr(in, "-----"); + if(!sep_start) + return 0; + cert_start = strstr(sep_start + 1, "-----"); + if(!cert_start) + return -1; + + cert_start += 5; + + /* Find separator after the end of the certificate. */ + cert_end = strstr(cert_start, "-----"); + if(!cert_end) + return -1; + + sep_end = strstr(cert_end + 1, "-----"); + if(!sep_end) + return -1; + sep_end += 5; + + len = cert_end - cert_start; + b64 = malloc(len + 1); + if(!b64) + return -1; + + /* Create base64 string without linefeeds. */ + for(i = 0, j = 0; i < len; i++) { + if(cert_start[i] != '\r' && cert_start[i] != '\n') + b64[j++] = cert_start[i]; + } + b64[j] = '\0'; + + err = Curl_base64_decode((const char *)b64, out, outlen); + free(b64); + if(err) { + free(*out); + return -1; + } + + return sep_end - in; +} + +#define MAX_CERTS_SIZE (50*1024*1024) /* arbitrary - to catch mistakes */ + +static int read_cert(const char *file, unsigned char **out, size_t *outlen) +{ + int fd; + ssize_t n; + unsigned char buf[512]; + struct dynbuf certs; + + Curl_dyn_init(&certs, MAX_CERTS_SIZE); + + fd = open(file, 0); + if(fd < 0) + return -1; + + for(;;) { + n = read(fd, buf, sizeof(buf)); + if(!n) + break; + if(n < 0) { + close(fd); + Curl_dyn_free(&certs); + return -1; + } + if(Curl_dyn_addn(&certs, buf, n)) { + close(fd); + return -1; + } + } + close(fd); + + *out = Curl_dyn_uptr(&certs); + *outlen = Curl_dyn_len(&certs); + + return 0; +} + +static int append_cert_to_array(struct Curl_easy *data, + const unsigned char *buf, size_t buflen, + CFMutableArrayRef array) +{ + char *certp; + CURLcode result; + SecCertificateRef cacert; + CFDataRef certdata; + + certdata = CFDataCreate(kCFAllocatorDefault, buf, buflen); + if(!certdata) { + failf(data, "SSL: failed to allocate array for CA certificate"); + return CURLE_OUT_OF_MEMORY; + } + + cacert = SecCertificateCreateWithData(kCFAllocatorDefault, certdata); + CFRelease(certdata); + if(!cacert) { + failf(data, "SSL: failed to create SecCertificate from CA certificate"); + return CURLE_SSL_CACERT_BADFILE; + } + + /* Check if cacert is valid. */ + result = CopyCertSubject(data, cacert, &certp); + switch(result) { + case CURLE_OK: + break; + case CURLE_PEER_FAILED_VERIFICATION: + return CURLE_SSL_CACERT_BADFILE; + case CURLE_OUT_OF_MEMORY: + default: + return result; + } + free(certp); + + CFArrayAppendValue(array, cacert); + CFRelease(cacert); + + return CURLE_OK; +} + +static CURLcode verify_cert_buf(struct Curl_cfilter *cf, + struct Curl_easy *data, + const unsigned char *certbuf, size_t buflen, + SSLContextRef ctx) +{ + int n = 0, rc; + long res; + unsigned char *der; + size_t derlen, offset = 0; + OSStatus ret; + SecTrustResultType trust_eval; + CFMutableArrayRef array = NULL; + SecTrustRef trust = NULL; + CURLcode result = CURLE_PEER_FAILED_VERIFICATION; + (void)cf; + /* + * Certbuf now contains the contents of the certificate file, which can be + * - a single DER certificate, + * - a single PEM certificate or + * - a bunch of PEM certificates (certificate bundle). + * + * Go through certbuf, and convert any PEM certificate in it into DER + * format. + */ + array = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); + if(!array) { + failf(data, "SSL: out of memory creating CA certificate array"); + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + while(offset < buflen) { + n++; + + /* + * Check if the certificate is in PEM format, and convert it to DER. If + * this fails, we assume the certificate is in DER format. + */ + res = pem_to_der((const char *)certbuf + offset, &der, &derlen); + if(res < 0) { + failf(data, "SSL: invalid CA certificate #%d (offset %zu) in bundle", + n, offset); + result = CURLE_SSL_CACERT_BADFILE; + goto out; + } + offset += res; + + if(res == 0 && offset == 0) { + /* This is not a PEM file, probably a certificate in DER format. */ + rc = append_cert_to_array(data, certbuf, buflen, array); + if(rc != CURLE_OK) { + CURL_TRC_CF(data, cf, "append_cert for CA failed"); + result = rc; + goto out; + } + break; + } + else if(res == 0) { + /* No more certificates in the bundle. */ + break; + } + + rc = append_cert_to_array(data, der, derlen, array); + free(der); + if(rc != CURLE_OK) { + CURL_TRC_CF(data, cf, "append_cert for CA failed"); + result = rc; + goto out; + } + } + + ret = SSLCopyPeerTrust(ctx, &trust); + if(!trust) { + failf(data, "SSL: error getting certificate chain"); + goto out; + } + else if(ret != noErr) { + failf(data, "SSLCopyPeerTrust() returned error %d", ret); + goto out; + } + + CURL_TRC_CF(data, cf, "setting %d trust anchors", n); + ret = SecTrustSetAnchorCertificates(trust, array); + if(ret != noErr) { + failf(data, "SecTrustSetAnchorCertificates() returned error %d", ret); + goto out; + } + ret = SecTrustSetAnchorCertificatesOnly(trust, true); + if(ret != noErr) { + failf(data, "SecTrustSetAnchorCertificatesOnly() returned error %d", ret); + goto out; + } + + trust_eval = 0; + ret = SecTrustEvaluate(trust, &trust_eval); + if(ret != noErr) { + failf(data, "SecTrustEvaluate() returned error %d", ret); + goto out; + } + + switch(trust_eval) { + case kSecTrustResultUnspecified: + /* what does this really mean? */ + CURL_TRC_CF(data, cf, "trust result: Unspecified"); + result = CURLE_OK; + goto out; + case kSecTrustResultProceed: + CURL_TRC_CF(data, cf, "trust result: Proceed"); + result = CURLE_OK; + goto out; + + case kSecTrustResultRecoverableTrustFailure: + failf(data, "SSL: peer not verified: RecoverableTrustFailure"); + goto out; + case kSecTrustResultDeny: + failf(data, "SSL: peer not verified: Deny"); + goto out; + default: + failf(data, "SSL: perr not verified: result=%d", trust_eval); + goto out; + } + +out: + if(trust) + CFRelease(trust); + if(array) + CFRelease(array); + return result; +} + +static CURLcode verify_cert(struct Curl_cfilter *cf, + struct Curl_easy *data, const char *cafile, + const struct curl_blob *ca_info_blob, + SSLContextRef ctx) +{ + CURLcode result; + unsigned char *certbuf; + size_t buflen; + bool free_certbuf = FALSE; + + if(ca_info_blob) { + CURL_TRC_CF(data, cf, "verify_peer, CA from config blob"); + certbuf = ca_info_blob->data; + buflen = ca_info_blob->len; + } + else if(cafile) { + CURL_TRC_CF(data, cf, "verify_peer, CA from file '%s'", cafile); + if(read_cert(cafile, &certbuf, &buflen) < 0) { + failf(data, "SSL: failed to read or invalid CA certificate"); + return CURLE_SSL_CACERT_BADFILE; + } + free_certbuf = TRUE; + } + else + return CURLE_SSL_CACERT_BADFILE; + + result = verify_cert_buf(cf, data, certbuf, buflen, ctx); + if(free_certbuf) + free(certbuf); + return result; +} + + +#ifdef SECTRANSP_PINNEDPUBKEY +static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, + SSLContextRef ctx, + const char *pinnedpubkey) +{ /* Scratch */ + size_t pubkeylen, realpubkeylen, spkiHeaderLength = 24; + unsigned char *pubkey = NULL, *realpubkey = NULL; + const unsigned char *spkiHeader = NULL; + CFDataRef publicKeyBits = NULL; + + /* Result is returned to caller */ + CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; + + /* if a path wasn't specified, don't pin */ + if(!pinnedpubkey) + return CURLE_OK; + + + if(!ctx) + return result; + + do { + SecTrustRef trust; + OSStatus ret; + SecKeyRef keyRef; + + ret = SSLCopyPeerTrust(ctx, &trust); + if(ret != noErr || !trust) + break; + + keyRef = SecTrustCopyPublicKey(trust); + CFRelease(trust); + if(!keyRef) + break; + +#ifdef SECTRANSP_PINNEDPUBKEY_V1 + + publicKeyBits = SecKeyCopyExternalRepresentation(keyRef, NULL); + CFRelease(keyRef); + if(!publicKeyBits) + break; + +#elif SECTRANSP_PINNEDPUBKEY_V2 + + { + OSStatus success; + success = SecItemExport(keyRef, kSecFormatOpenSSL, 0, NULL, + &publicKeyBits); + CFRelease(keyRef); + if(success != errSecSuccess || !publicKeyBits) + break; + } + +#endif /* SECTRANSP_PINNEDPUBKEY_V2 */ + + pubkeylen = CFDataGetLength(publicKeyBits); + pubkey = (unsigned char *)CFDataGetBytePtr(publicKeyBits); + + switch(pubkeylen) { + case 526: + /* 4096 bit RSA pubkeylen == 526 */ + spkiHeader = rsa4096SpkiHeader; + break; + case 270: + /* 2048 bit RSA pubkeylen == 270 */ + spkiHeader = rsa2048SpkiHeader; + break; +#ifdef SECTRANSP_PINNEDPUBKEY_V1 + case 65: + /* ecDSA secp256r1 pubkeylen == 65 */ + spkiHeader = ecDsaSecp256r1SpkiHeader; + spkiHeaderLength = 26; + break; + case 97: + /* ecDSA secp384r1 pubkeylen == 97 */ + spkiHeader = ecDsaSecp384r1SpkiHeader; + spkiHeaderLength = 23; + break; + default: + infof(data, "SSL: unhandled public key length: %zu", pubkeylen); +#elif SECTRANSP_PINNEDPUBKEY_V2 + default: + /* ecDSA secp256r1 pubkeylen == 91 header already included? + * ecDSA secp384r1 header already included too + * we assume rest of algorithms do same, so do nothing + */ + result = Curl_pin_peer_pubkey(data, pinnedpubkey, pubkey, + pubkeylen); +#endif /* SECTRANSP_PINNEDPUBKEY_V2 */ + continue; /* break from loop */ + } + + realpubkeylen = pubkeylen + spkiHeaderLength; + realpubkey = malloc(realpubkeylen); + if(!realpubkey) + break; + + memcpy(realpubkey, spkiHeader, spkiHeaderLength); + memcpy(realpubkey + spkiHeaderLength, pubkey, pubkeylen); + + result = Curl_pin_peer_pubkey(data, pinnedpubkey, realpubkey, + realpubkeylen); + + } while(0); + + Curl_safefree(realpubkey); + if(publicKeyBits) + CFRelease(publicKeyBits); + + return result; +} +#endif /* SECTRANSP_PINNEDPUBKEY */ + +static CURLcode sectransp_connect_step2(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct st_ssl_backend_data *backend = + (struct st_ssl_backend_data *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + OSStatus err; + SSLCipherSuite cipher; + SSLProtocol protocol = 0; + + DEBUGASSERT(ssl_connect_2 == connssl->connecting_state + || ssl_connect_2_reading == connssl->connecting_state + || ssl_connect_2_writing == connssl->connecting_state); + DEBUGASSERT(backend); + CURL_TRC_CF(data, cf, "connect_step2"); + + /* Here goes nothing: */ +check_handshake: + err = SSLHandshake(backend->ssl_ctx); + + if(err != noErr) { + switch(err) { + case errSSLWouldBlock: /* they're not done with us yet */ + connssl->connecting_state = backend->ssl_direction ? + ssl_connect_2_writing : ssl_connect_2_reading; + return CURLE_OK; + + /* The below is errSSLServerAuthCompleted; it's not defined in + Leopard's headers */ + case -9841: + if((conn_config->CAfile || conn_config->ca_info_blob) && + conn_config->verifypeer) { + CURLcode result = verify_cert(cf, data, conn_config->CAfile, + conn_config->ca_info_blob, + backend->ssl_ctx); + if(result) + return result; + } + /* the documentation says we need to call SSLHandshake() again */ + goto check_handshake; + + /* Problem with encrypt / decrypt */ + case errSSLPeerDecodeError: + failf(data, "Decode failed"); + break; + case errSSLDecryptionFail: + case errSSLPeerDecryptionFail: + failf(data, "Decryption failed"); + break; + case errSSLPeerDecryptError: + failf(data, "A decryption error occurred"); + break; + case errSSLBadCipherSuite: + failf(data, "A bad SSL cipher suite was encountered"); + break; + case errSSLCrypto: + failf(data, "An underlying cryptographic error was encountered"); + break; +#if CURL_BUILD_MAC_10_11 || CURL_BUILD_IOS_9 + case errSSLWeakPeerEphemeralDHKey: + failf(data, "Indicates a weak ephemeral Diffie-Hellman key"); + break; +#endif + + /* Problem with the message record validation */ + case errSSLBadRecordMac: + case errSSLPeerBadRecordMac: + failf(data, "A record with a bad message authentication code (MAC) " + "was encountered"); + break; + case errSSLRecordOverflow: + case errSSLPeerRecordOverflow: + failf(data, "A record overflow occurred"); + break; + + /* Problem with zlib decompression */ + case errSSLPeerDecompressFail: + failf(data, "Decompression failed"); + break; + + /* Problem with access */ + case errSSLPeerAccessDenied: + failf(data, "Access was denied"); + break; + case errSSLPeerInsufficientSecurity: + failf(data, "There is insufficient security for this operation"); + break; + + /* These are all certificate problems with the server: */ + case errSSLXCertChainInvalid: + failf(data, "SSL certificate problem: Invalid certificate chain"); + return CURLE_PEER_FAILED_VERIFICATION; + case errSSLUnknownRootCert: + failf(data, "SSL certificate problem: Untrusted root certificate"); + return CURLE_PEER_FAILED_VERIFICATION; + case errSSLNoRootCert: + failf(data, "SSL certificate problem: No root certificate"); + return CURLE_PEER_FAILED_VERIFICATION; + case errSSLCertNotYetValid: + failf(data, "SSL certificate problem: The certificate chain had a " + "certificate that is not yet valid"); + return CURLE_PEER_FAILED_VERIFICATION; + case errSSLCertExpired: + case errSSLPeerCertExpired: + failf(data, "SSL certificate problem: Certificate chain had an " + "expired certificate"); + return CURLE_PEER_FAILED_VERIFICATION; + case errSSLBadCert: + case errSSLPeerBadCert: + failf(data, "SSL certificate problem: Couldn't understand the server " + "certificate format"); + return CURLE_PEER_FAILED_VERIFICATION; + case errSSLPeerUnsupportedCert: + failf(data, "SSL certificate problem: An unsupported certificate " + "format was encountered"); + return CURLE_PEER_FAILED_VERIFICATION; + case errSSLPeerCertRevoked: + failf(data, "SSL certificate problem: The certificate was revoked"); + return CURLE_PEER_FAILED_VERIFICATION; + case errSSLPeerCertUnknown: + failf(data, "SSL certificate problem: The certificate is unknown"); + return CURLE_PEER_FAILED_VERIFICATION; + + /* These are all certificate problems with the client: */ + case errSecAuthFailed: + failf(data, "SSL authentication failed"); + break; + case errSSLPeerHandshakeFail: + failf(data, "SSL peer handshake failed, the server most likely " + "requires a client certificate to connect"); + break; + case errSSLPeerUnknownCA: + failf(data, "SSL server rejected the client certificate due to " + "the certificate being signed by an unknown certificate " + "authority"); + break; + + /* This error is raised if the server's cert didn't match the server's + host name: */ + case errSSLHostNameMismatch: + failf(data, "SSL certificate peer verification failed, the " + "certificate did not match \"%s\"\n", connssl->peer.dispname); + return CURLE_PEER_FAILED_VERIFICATION; + + /* Problem with SSL / TLS negotiation */ + case errSSLNegotiation: + failf(data, "Could not negotiate an SSL cipher suite with the server"); + break; + case errSSLBadConfiguration: + failf(data, "A configuration error occurred"); + break; + case errSSLProtocol: + failf(data, "SSL protocol error"); + break; + case errSSLPeerProtocolVersion: + failf(data, "A bad protocol version was encountered"); + break; + case errSSLPeerNoRenegotiation: + failf(data, "No renegotiation is allowed"); + break; + + /* Generic handshake errors: */ + case errSSLConnectionRefused: + failf(data, "Server dropped the connection during the SSL handshake"); + break; + case errSSLClosedAbort: + failf(data, "Server aborted the SSL handshake"); + break; + case errSSLClosedGraceful: + failf(data, "The connection closed gracefully"); + break; + case errSSLClosedNoNotify: + failf(data, "The server closed the session with no notification"); + break; + /* Sometimes paramErr happens with buggy ciphers: */ + case paramErr: + case errSSLInternal: + case errSSLPeerInternalError: + failf(data, "Internal SSL engine error encountered during the " + "SSL handshake"); + break; + case errSSLFatalAlert: + failf(data, "Fatal SSL engine error encountered during the SSL " + "handshake"); + break; + /* Unclassified error */ + case errSSLBufferOverflow: + failf(data, "An insufficient buffer was provided"); + break; + case errSSLIllegalParam: + failf(data, "An illegal parameter was encountered"); + break; + case errSSLModuleAttach: + failf(data, "Module attach failure"); + break; + case errSSLSessionNotFound: + failf(data, "An attempt to restore an unknown session failed"); + break; + case errSSLPeerExportRestriction: + failf(data, "An export restriction occurred"); + break; + case errSSLPeerUserCancelled: + failf(data, "The user canceled the operation"); + break; + case errSSLPeerUnexpectedMsg: + failf(data, "Peer rejected unexpected message"); + break; +#if CURL_BUILD_MAC_10_11 || CURL_BUILD_IOS_9 + /* Treating non-fatal error as fatal like before */ + case errSSLClientHelloReceived: + failf(data, "A non-fatal result for providing a server name " + "indication"); + break; +#endif + + /* Error codes defined in the enum but should never be returned. + We list them here just in case. */ +#if CURL_BUILD_MAC_10_6 + /* Only returned when kSSLSessionOptionBreakOnCertRequested is set */ + case errSSLClientCertRequested: + failf(data, "Server requested a client certificate during the " + "handshake"); + return CURLE_SSL_CLIENTCERT; +#endif +#if CURL_BUILD_MAC_10_9 + /* Alias for errSSLLast, end of error range */ + case errSSLUnexpectedRecord: + failf(data, "Unexpected (skipped) record in DTLS"); + break; +#endif + default: + /* May also return codes listed in Security Framework Result Codes */ + failf(data, "Unknown SSL protocol error in connection to %s:%d", + connssl->peer.hostname, err); + break; + } + return CURLE_SSL_CONNECT_ERROR; + } + else { + /* we have been connected fine, we're not waiting for anything else. */ + connssl->connecting_state = ssl_connect_3; + +#ifdef SECTRANSP_PINNEDPUBKEY + if(data->set.str[STRING_SSL_PINNEDPUBLICKEY]) { + CURLcode result = + pkp_pin_peer_pubkey(data, backend->ssl_ctx, + data->set.str[STRING_SSL_PINNEDPUBLICKEY]); + if(result) { + failf(data, "SSL: public key does not match pinned public key"); + return result; + } + } +#endif /* SECTRANSP_PINNEDPUBKEY */ + + /* Informational message */ + (void)SSLGetNegotiatedCipher(backend->ssl_ctx, &cipher); + (void)SSLGetNegotiatedProtocolVersion(backend->ssl_ctx, &protocol); + switch(protocol) { + case kSSLProtocol2: + infof(data, "SSL 2.0 connection using %s", + TLSCipherNameForNumber(cipher)); + break; + case kSSLProtocol3: + infof(data, "SSL 3.0 connection using %s", + TLSCipherNameForNumber(cipher)); + break; + case kTLSProtocol1: + infof(data, "TLS 1.0 connection using %s", + TLSCipherNameForNumber(cipher)); + break; +#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS + case kTLSProtocol11: + infof(data, "TLS 1.1 connection using %s", + TLSCipherNameForNumber(cipher)); + break; + case kTLSProtocol12: + infof(data, "TLS 1.2 connection using %s", + TLSCipherNameForNumber(cipher)); + break; +#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ +#if CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 + case kTLSProtocol13: + infof(data, "TLS 1.3 connection using %s", + TLSCipherNameForNumber(cipher)); + break; +#endif /* CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 */ + default: + infof(data, "Unknown protocol connection"); + break; + } + +#if(CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1 + if(connssl->alpn) { + if(__builtin_available(macOS 10.13.4, iOS 11, tvOS 11, *)) { + CFArrayRef alpnArr = NULL; + CFStringRef chosenProtocol = NULL; + err = SSLCopyALPNProtocols(backend->ssl_ctx, &alpnArr); + + if(err == noErr && alpnArr && CFArrayGetCount(alpnArr) >= 1) + chosenProtocol = CFArrayGetValueAtIndex(alpnArr, 0); + +#ifdef USE_HTTP2 + if(chosenProtocol && + !CFStringCompare(chosenProtocol, CFSTR(ALPN_H2), 0)) { + cf->conn->alpn = CURL_HTTP_VERSION_2; + } + else +#endif + if(chosenProtocol && + !CFStringCompare(chosenProtocol, CFSTR(ALPN_HTTP_1_1), 0)) { + cf->conn->alpn = CURL_HTTP_VERSION_1_1; + } + else + infof(data, VTLS_INFOF_NO_ALPN); + + Curl_multiuse_state(data, cf->conn->alpn == CURL_HTTP_VERSION_2 ? + BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE); + + /* chosenProtocol is a reference to the string within alpnArr + and doesn't need to be freed separately */ + if(alpnArr) + CFRelease(alpnArr); + } + } +#endif + + return CURLE_OK; + } +} + +static CURLcode +add_cert_to_certinfo(struct Curl_easy *data, + SecCertificateRef server_cert, + int idx) +{ + CURLcode result = CURLE_OK; + const char *beg; + const char *end; + CFDataRef cert_data = SecCertificateCopyData(server_cert); + + if(!cert_data) + return CURLE_PEER_FAILED_VERIFICATION; + + beg = (const char *)CFDataGetBytePtr(cert_data); + end = beg + CFDataGetLength(cert_data); + result = Curl_extract_certinfo(data, idx, beg, end); + CFRelease(cert_data); + return result; +} + +static CURLcode +collect_server_cert_single(struct Curl_cfilter *cf, struct Curl_easy *data, + SecCertificateRef server_cert, + CFIndex idx) +{ + CURLcode result = CURLE_OK; + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); +#ifndef CURL_DISABLE_VERBOSE_STRINGS + if(data->set.verbose) { + char *certp; + result = CopyCertSubject(data, server_cert, &certp); + if(!result) { + infof(data, "Server certificate: %s", certp); + free(certp); + } + } +#endif + if(ssl_config->certinfo) + result = add_cert_to_certinfo(data, server_cert, (int)idx); + return result; +} + +/* This should be called during step3 of the connection at the earliest */ +static CURLcode collect_server_cert(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ +#ifndef CURL_DISABLE_VERBOSE_STRINGS + const bool show_verbose_server_cert = data->set.verbose; +#else + const bool show_verbose_server_cert = false; +#endif + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + CURLcode result = ssl_config->certinfo ? + CURLE_PEER_FAILED_VERIFICATION : CURLE_OK; + struct ssl_connect_data *connssl = cf->ctx; + struct st_ssl_backend_data *backend = + (struct st_ssl_backend_data *)connssl->backend; + CFArrayRef server_certs = NULL; + SecCertificateRef server_cert; + OSStatus err; + CFIndex i, count; + SecTrustRef trust = NULL; + + DEBUGASSERT(backend); + + if(!show_verbose_server_cert && !ssl_config->certinfo) + return CURLE_OK; + + if(!backend->ssl_ctx) + return result; + +#if CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS +#if CURL_BUILD_IOS +#pragma unused(server_certs) + err = SSLCopyPeerTrust(backend->ssl_ctx, &trust); + /* For some reason, SSLCopyPeerTrust() can return noErr and yet return + a null trust, so be on guard for that: */ + if(err == noErr && trust) { + count = SecTrustGetCertificateCount(trust); + if(ssl_config->certinfo) + result = Curl_ssl_init_certinfo(data, (int)count); + for(i = 0L ; !result && (i < count) ; i++) { + server_cert = SecTrustGetCertificateAtIndex(trust, i); + result = collect_server_cert_single(cf, data, server_cert, i); + } + CFRelease(trust); + } +#else + /* SSLCopyPeerCertificates() is deprecated as of Mountain Lion. + The function SecTrustGetCertificateAtIndex() is officially present + in Lion, but it is unfortunately also present in Snow Leopard as + private API and doesn't work as expected. So we have to look for + a different symbol to make sure this code is only executed under + Lion or later. */ + if(SecTrustCopyPublicKey) { +#pragma unused(server_certs) + err = SSLCopyPeerTrust(backend->ssl_ctx, &trust); + /* For some reason, SSLCopyPeerTrust() can return noErr and yet return + a null trust, so be on guard for that: */ + if(err == noErr && trust) { + count = SecTrustGetCertificateCount(trust); + if(ssl_config->certinfo) + result = Curl_ssl_init_certinfo(data, (int)count); + for(i = 0L ; !result && (i < count) ; i++) { + server_cert = SecTrustGetCertificateAtIndex(trust, i); + result = collect_server_cert_single(cf, data, server_cert, i); + } + CFRelease(trust); + } + } + else { +#if CURL_SUPPORT_MAC_10_8 + err = SSLCopyPeerCertificates(backend->ssl_ctx, &server_certs); + /* Just in case SSLCopyPeerCertificates() returns null too... */ + if(err == noErr && server_certs) { + count = CFArrayGetCount(server_certs); + if(ssl_config->certinfo) + result = Curl_ssl_init_certinfo(data, (int)count); + for(i = 0L ; !result && (i < count) ; i++) { + server_cert = (SecCertificateRef)CFArrayGetValueAtIndex(server_certs, + i); + result = collect_server_cert_single(cf, data, server_cert, i); + } + CFRelease(server_certs); + } +#endif /* CURL_SUPPORT_MAC_10_8 */ + } +#endif /* CURL_BUILD_IOS */ +#else +#pragma unused(trust) + err = SSLCopyPeerCertificates(backend->ssl_ctx, &server_certs); + if(err == noErr) { + count = CFArrayGetCount(server_certs); + if(ssl_config->certinfo) + result = Curl_ssl_init_certinfo(data, (int)count); + for(i = 0L ; !result && (i < count) ; i++) { + server_cert = (SecCertificateRef)CFArrayGetValueAtIndex(server_certs, i); + result = collect_server_cert_single(cf, data, server_cert, i); + } + CFRelease(server_certs); + } +#endif /* CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS */ + return result; +} + +static CURLcode sectransp_connect_step3(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + CURLcode result; + + CURL_TRC_CF(data, cf, "connect_step3"); + /* There is no step 3! + * Well, okay, let's collect server certificates, and if verbose mode is on, + * let's print the details of the server certificates. */ + result = collect_server_cert(cf, data); + if(result) + return result; + + connssl->connecting_state = ssl_connect_done; + return CURLE_OK; +} + +static CURLcode +sectransp_connect_common(struct Curl_cfilter *cf, struct Curl_easy *data, + bool nonblocking, + bool *done) +{ + CURLcode result; + struct ssl_connect_data *connssl = cf->ctx; + curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data); + int what; + + /* check if the connection has already been established */ + if(ssl_connection_complete == connssl->state) { + *done = TRUE; + return CURLE_OK; + } + + if(ssl_connect_1 == connssl->connecting_state) { + /* Find out how much more time we're allowed */ + const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE); + + if(timeout_ms < 0) { + /* no need to continue if time already is up */ + failf(data, "SSL connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + + result = sectransp_connect_step1(cf, data); + if(result) + return result; + } + + while(ssl_connect_2 == connssl->connecting_state || + ssl_connect_2_reading == connssl->connecting_state || + ssl_connect_2_writing == connssl->connecting_state) { + + /* check allowed time left */ + const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE); + + if(timeout_ms < 0) { + /* no need to continue if time already is up */ + failf(data, "SSL connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + + /* if ssl is expecting something, check if it's available. */ + if(connssl->connecting_state == ssl_connect_2_reading || + connssl->connecting_state == ssl_connect_2_writing) { + + curl_socket_t writefd = ssl_connect_2_writing == + connssl->connecting_state?sockfd:CURL_SOCKET_BAD; + curl_socket_t readfd = ssl_connect_2_reading == + connssl->connecting_state?sockfd:CURL_SOCKET_BAD; + + what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, + nonblocking ? 0 : timeout_ms); + if(what < 0) { + /* fatal error */ + failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); + return CURLE_SSL_CONNECT_ERROR; + } + else if(0 == what) { + if(nonblocking) { + *done = FALSE; + return CURLE_OK; + } + else { + /* timeout */ + failf(data, "SSL connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + } + /* socket is readable or writable */ + } + + /* Run transaction, and return to the caller if it failed or if this + * connection is done nonblocking and this loop would execute again. This + * permits the owner of a multi handle to abort a connection attempt + * before step2 has completed while ensuring that a client using select() + * or epoll() will always have a valid fdset to wait on. + */ + result = sectransp_connect_step2(cf, data); + if(result || (nonblocking && + (ssl_connect_2 == connssl->connecting_state || + ssl_connect_2_reading == connssl->connecting_state || + ssl_connect_2_writing == connssl->connecting_state))) + return result; + + } /* repeat step2 until all transactions are done. */ + + + if(ssl_connect_3 == connssl->connecting_state) { + result = sectransp_connect_step3(cf, data); + if(result) + return result; + } + + if(ssl_connect_done == connssl->connecting_state) { + CURL_TRC_CF(data, cf, "connected"); + connssl->state = ssl_connection_complete; + *done = TRUE; + } + else + *done = FALSE; + + /* Reset our connect state machine */ + connssl->connecting_state = ssl_connect_1; + + return CURLE_OK; +} + +static CURLcode sectransp_connect_nonblocking(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + return sectransp_connect_common(cf, data, TRUE, done); +} + +static CURLcode sectransp_connect(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURLcode result; + bool done = FALSE; + + result = sectransp_connect_common(cf, data, FALSE, &done); + + if(result) + return result; + + DEBUGASSERT(done); + + return CURLE_OK; +} + +static void sectransp_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct st_ssl_backend_data *backend = + (struct st_ssl_backend_data *)connssl->backend; + + (void) data; + + DEBUGASSERT(backend); + + if(backend->ssl_ctx) { + CURL_TRC_CF(data, cf, "close"); + (void)SSLClose(backend->ssl_ctx); +#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS + if(SSLCreateContext) + CFRelease(backend->ssl_ctx); +#if CURL_SUPPORT_MAC_10_8 + else + (void)SSLDisposeContext(backend->ssl_ctx); +#endif /* CURL_SUPPORT_MAC_10_8 */ +#else + (void)SSLDisposeContext(backend->ssl_ctx); +#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ + backend->ssl_ctx = NULL; + } +} + +static int sectransp_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct st_ssl_backend_data *backend = + (struct st_ssl_backend_data *)connssl->backend; + ssize_t nread; + int what; + int rc; + char buf[120]; + int loop = 10; /* avoid getting stuck */ + CURLcode result; + + DEBUGASSERT(backend); + + if(!backend->ssl_ctx) + return 0; + +#ifndef CURL_DISABLE_FTP + if(data->set.ftp_ccc != CURLFTPSSL_CCC_ACTIVE) + return 0; +#endif + + sectransp_close(cf, data); + + rc = 0; + + what = SOCKET_READABLE(Curl_conn_cf_get_socket(cf, data), + SSL_SHUTDOWN_TIMEOUT); + + CURL_TRC_CF(data, cf, "shutdown"); + while(loop--) { + if(what < 0) { + /* anything that gets here is fatally bad */ + failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); + rc = -1; + break; + } + + if(!what) { /* timeout */ + failf(data, "SSL shutdown timeout"); + break; + } + + /* Something to read, let's do it and hope that it is the close + notify alert from the server. No way to SSL_Read now, so use read(). */ + + nread = Curl_conn_cf_recv(cf->next, data, buf, sizeof(buf), &result); + + if(nread < 0) { + failf(data, "read: %s", curl_easy_strerror(result)); + rc = -1; + } + + if(nread <= 0) + break; + + what = SOCKET_READABLE(Curl_conn_cf_get_socket(cf, data), 0); + } + + return rc; +} + +static size_t sectransp_version(char *buffer, size_t size) +{ + return msnprintf(buffer, size, "SecureTransport"); +} + +static bool sectransp_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + const struct ssl_connect_data *connssl = cf->ctx; + struct st_ssl_backend_data *backend = + (struct st_ssl_backend_data *)connssl->backend; + OSStatus err; + size_t buffer; + + (void)data; + DEBUGASSERT(backend); + + if(backend->ssl_ctx) { /* SSL is in use */ + CURL_TRC_CF((struct Curl_easy *)data, cf, "data_pending"); + err = SSLGetBufferedReadSize(backend->ssl_ctx, &buffer); + if(err == noErr) + return buffer > 0UL; + return false; + } + else + return false; +} + +static CURLcode sectransp_random(struct Curl_easy *data UNUSED_PARAM, + unsigned char *entropy, size_t length) +{ + /* arc4random_buf() isn't available on cats older than Lion, so let's + do this manually for the benefit of the older cats. */ + size_t i; + u_int32_t random_number = 0; + + (void)data; + + for(i = 0 ; i < length ; i++) { + if(i % sizeof(u_int32_t) == 0) + random_number = arc4random(); + entropy[i] = random_number & 0xFF; + random_number >>= 8; + } + i = random_number = 0; + return CURLE_OK; +} + +static CURLcode sectransp_sha256sum(const unsigned char *tmp, /* input */ + size_t tmplen, + unsigned char *sha256sum, /* output */ + size_t sha256len) +{ + (void)sha256len; + assert(sha256len >= CURL_SHA256_DIGEST_LENGTH); + (void)CC_SHA256(tmp, (CC_LONG)tmplen, sha256sum); + return CURLE_OK; +} + +static bool sectransp_false_start(void) +{ +#if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 + if(SSLSetSessionOption) + return TRUE; +#endif + return FALSE; +} + +static ssize_t sectransp_send(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *mem, + size_t len, + CURLcode *curlcode) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct st_ssl_backend_data *backend = + (struct st_ssl_backend_data *)connssl->backend; + size_t processed = 0UL; + OSStatus err; + + DEBUGASSERT(backend); + + /* The SSLWrite() function works a little differently than expected. The + fourth argument (processed) is currently documented in Apple's + documentation as: "On return, the length, in bytes, of the data actually + written." + + Now, one could interpret that as "written to the socket," but actually, + it returns the amount of data that was written to a buffer internal to + the SSLContextRef instead. So it's possible for SSLWrite() to return + errSSLWouldBlock and a number of bytes "written" because those bytes were + encrypted and written to a buffer, not to the socket. + + So if this happens, then we need to keep calling SSLWrite() over and + over again with no new data until it quits returning errSSLWouldBlock. */ + + /* Do we have buffered data to write from the last time we were called? */ + if(backend->ssl_write_buffered_length) { + /* Write the buffered data: */ + err = SSLWrite(backend->ssl_ctx, NULL, 0UL, &processed); + switch(err) { + case noErr: + /* processed is always going to be 0 because we didn't write to + the buffer, so return how much was written to the socket */ + processed = backend->ssl_write_buffered_length; + backend->ssl_write_buffered_length = 0UL; + break; + case errSSLWouldBlock: /* argh, try again */ + *curlcode = CURLE_AGAIN; + return -1L; + default: + failf(data, "SSLWrite() returned error %d", err); + *curlcode = CURLE_SEND_ERROR; + return -1L; + } + } + else { + /* We've got new data to write: */ + err = SSLWrite(backend->ssl_ctx, mem, len, &processed); + if(err != noErr) { + switch(err) { + case errSSLWouldBlock: + /* Data was buffered but not sent, we have to tell the caller + to try sending again, and remember how much was buffered */ + backend->ssl_write_buffered_length = len; + *curlcode = CURLE_AGAIN; + return -1L; + default: + failf(data, "SSLWrite() returned error %d", err); + *curlcode = CURLE_SEND_ERROR; + return -1L; + } + } + } + return (ssize_t)processed; +} + +static ssize_t sectransp_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, + char *buf, + size_t buffersize, + CURLcode *curlcode) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct st_ssl_backend_data *backend = + (struct st_ssl_backend_data *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + size_t processed = 0UL; + OSStatus err; + + DEBUGASSERT(backend); + +again: + *curlcode = CURLE_OK; + err = SSLRead(backend->ssl_ctx, buf, buffersize, &processed); + + if(err != noErr) { + switch(err) { + case errSSLWouldBlock: /* return how much we read (if anything) */ + if(processed) { + return (ssize_t)processed; + } + *curlcode = CURLE_AGAIN; + return -1L; + + /* errSSLClosedGraceful - server gracefully shut down the SSL session + errSSLClosedNoNotify - server hung up on us instead of sending a + closure alert notice, read() is returning 0 + Either way, inform the caller that the server disconnected. */ + case errSSLClosedGraceful: + case errSSLClosedNoNotify: + *curlcode = CURLE_OK; + return 0; + + /* The below is errSSLPeerAuthCompleted; it's not defined in + Leopard's headers */ + case -9841: + if((conn_config->CAfile || conn_config->ca_info_blob) && + conn_config->verifypeer) { + CURLcode result = verify_cert(cf, data, conn_config->CAfile, + conn_config->ca_info_blob, + backend->ssl_ctx); + if(result) { + *curlcode = result; + return -1; + } + } + goto again; + default: + failf(data, "SSLRead() return error %d", err); + *curlcode = CURLE_RECV_ERROR; + return -1L; + } + } + return (ssize_t)processed; +} + +static void *sectransp_get_internals(struct ssl_connect_data *connssl, + CURLINFO info UNUSED_PARAM) +{ + struct st_ssl_backend_data *backend = + (struct st_ssl_backend_data *)connssl->backend; + (void)info; + DEBUGASSERT(backend); + return backend->ssl_ctx; +} + +const struct Curl_ssl Curl_ssl_sectransp = { + { CURLSSLBACKEND_SECURETRANSPORT, "secure-transport" }, /* info */ + + SSLSUPP_CAINFO_BLOB | + SSLSUPP_CERTINFO | +#ifdef SECTRANSP_PINNEDPUBKEY + SSLSUPP_PINNEDPUBKEY | +#endif /* SECTRANSP_PINNEDPUBKEY */ + SSLSUPP_HTTPS_PROXY, + + sizeof(struct st_ssl_backend_data), + + Curl_none_init, /* init */ + Curl_none_cleanup, /* cleanup */ + sectransp_version, /* version */ + Curl_none_check_cxn, /* check_cxn */ + sectransp_shutdown, /* shutdown */ + sectransp_data_pending, /* data_pending */ + sectransp_random, /* random */ + Curl_none_cert_status_request, /* cert_status_request */ + sectransp_connect, /* connect */ + sectransp_connect_nonblocking, /* connect_nonblocking */ + Curl_ssl_adjust_pollset, /* adjust_pollset */ + sectransp_get_internals, /* get_internals */ + sectransp_close, /* close_one */ + Curl_none_close_all, /* close_all */ + Curl_none_set_engine, /* set_engine */ + Curl_none_set_engine_default, /* set_engine_default */ + Curl_none_engines_list, /* engines_list */ + sectransp_false_start, /* false_start */ + sectransp_sha256sum, /* sha256sum */ + NULL, /* associate_connection */ + NULL, /* disassociate_connection */ + NULL, /* free_multi_ssl_backend_data */ + sectransp_recv, /* recv decrypted data */ + sectransp_send, /* send data to encrypt */ +}; + +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#endif /* USE_SECTRANSP */ diff --git a/third_party/curl/lib/vtls/sectransp.h b/third_party/curl/lib/vtls/sectransp.h new file mode 100644 index 0000000..0f1085a --- /dev/null +++ b/third_party/curl/lib/vtls/sectransp.h @@ -0,0 +1,34 @@ +#ifndef HEADER_CURL_SECTRANSP_H +#define HEADER_CURL_SECTRANSP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Nick Zitzmann, . + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_SECTRANSP + +extern const struct Curl_ssl Curl_ssl_sectransp; + +#endif /* USE_SECTRANSP */ +#endif /* HEADER_CURL_SECTRANSP_H */ diff --git a/third_party/curl/lib/vtls/vtls.c b/third_party/curl/lib/vtls/vtls.c new file mode 100644 index 0000000..570a10d --- /dev/null +++ b/third_party/curl/lib/vtls/vtls.c @@ -0,0 +1,2172 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* This file is for implementing all "generic" SSL functions that all libcurl + internals should use. It is then responsible for calling the proper + "backend" function. + + SSL-functions in libcurl should call functions in this source file, and not + to any specific SSL-layer. + + Curl_ssl_ - prefix for generic ones + + Note that this source code uses the functions of the configured SSL + backend via the global Curl_ssl instance. + + "SSL/TLS Strong Encryption: An Introduction" + https://httpd.apache.org/docs/2.0/ssl/ssl_intro.html +*/ + +#include "curl_setup.h" + +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_STAT_H +#include +#endif +#ifdef HAVE_FCNTL_H +#include +#endif + +#include "urldata.h" +#include "cfilters.h" + +#include "vtls.h" /* generic SSL protos etc */ +#include "vtls_int.h" +#include "slist.h" +#include "sendf.h" +#include "strcase.h" +#include "url.h" +#include "progress.h" +#include "share.h" +#include "multiif.h" +#include "timeval.h" +#include "curl_md5.h" +#include "warnless.h" +#include "curl_base64.h" +#include "curl_printf.h" +#include "inet_pton.h" +#include "strdup.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + + +/* convenience macro to check if this handle is using a shared SSL session */ +#define SSLSESSION_SHARED(data) (data->share && \ + (data->share->specifier & \ + (1<var) { \ + dest->var = strdup(source->var); \ + if(!dest->var) \ + return FALSE; \ + } \ + else \ + dest->var = NULL; \ + } while(0) + +#define CLONE_BLOB(var) \ + do { \ + if(blobdup(&dest->var, source->var)) \ + return FALSE; \ + } while(0) + +static CURLcode blobdup(struct curl_blob **dest, + struct curl_blob *src) +{ + DEBUGASSERT(dest); + DEBUGASSERT(!*dest); + if(src) { + /* only if there's data to dupe! */ + struct curl_blob *d; + d = malloc(sizeof(struct curl_blob) + src->len); + if(!d) + return CURLE_OUT_OF_MEMORY; + d->len = src->len; + /* Always duplicate because the connection may survive longer than the + handle that passed in the blob. */ + d->flags = CURL_BLOB_COPY; + d->data = (void *)((char *)d + sizeof(struct curl_blob)); + memcpy(d->data, src->data, src->len); + *dest = d; + } + return CURLE_OK; +} + +/* returns TRUE if the blobs are identical */ +static bool blobcmp(struct curl_blob *first, struct curl_blob *second) +{ + if(!first && !second) /* both are NULL */ + return TRUE; + if(!first || !second) /* one is NULL */ + return FALSE; + if(first->len != second->len) /* different sizes */ + return FALSE; + return !memcmp(first->data, second->data, first->len); /* same data */ +} + +#ifdef USE_SSL +static const struct alpn_spec ALPN_SPEC_H11 = { + { ALPN_HTTP_1_1 }, 1 +}; +#ifdef USE_HTTP2 +static const struct alpn_spec ALPN_SPEC_H2_H11 = { + { ALPN_H2, ALPN_HTTP_1_1 }, 2 +}; +#endif + +static const struct alpn_spec *alpn_get_spec(int httpwant, bool use_alpn) +{ + if(!use_alpn) + return NULL; +#ifdef USE_HTTP2 + if(httpwant >= CURL_HTTP_VERSION_2) + return &ALPN_SPEC_H2_H11; +#else + (void)httpwant; +#endif + /* Use the ALPN protocol "http/1.1" for HTTP/1.x. + Avoid "http/1.0" because some servers don't support it. */ + return &ALPN_SPEC_H11; +} +#endif /* USE_SSL */ + + +void Curl_ssl_easy_config_init(struct Curl_easy *data) +{ + /* + * libcurl 7.10 introduced SSL verification *by default*! This needs to be + * switched off unless wanted. + */ + data->set.ssl.primary.verifypeer = TRUE; + data->set.ssl.primary.verifyhost = TRUE; + data->set.ssl.primary.sessionid = TRUE; /* session ID caching by default */ +#ifndef CURL_DISABLE_PROXY + data->set.proxy_ssl = data->set.ssl; +#endif +} + +static bool +match_ssl_primary_config(struct Curl_easy *data, + struct ssl_primary_config *c1, + struct ssl_primary_config *c2) +{ + (void)data; + if((c1->version == c2->version) && + (c1->version_max == c2->version_max) && + (c1->ssl_options == c2->ssl_options) && + (c1->verifypeer == c2->verifypeer) && + (c1->verifyhost == c2->verifyhost) && + (c1->verifystatus == c2->verifystatus) && + blobcmp(c1->cert_blob, c2->cert_blob) && + blobcmp(c1->ca_info_blob, c2->ca_info_blob) && + blobcmp(c1->issuercert_blob, c2->issuercert_blob) && + Curl_safecmp(c1->CApath, c2->CApath) && + Curl_safecmp(c1->CAfile, c2->CAfile) && + Curl_safecmp(c1->issuercert, c2->issuercert) && + Curl_safecmp(c1->clientcert, c2->clientcert) && +#ifdef USE_TLS_SRP + !Curl_timestrcmp(c1->username, c2->username) && + !Curl_timestrcmp(c1->password, c2->password) && +#endif + strcasecompare(c1->cipher_list, c2->cipher_list) && + strcasecompare(c1->cipher_list13, c2->cipher_list13) && + strcasecompare(c1->curves, c2->curves) && + strcasecompare(c1->CRLfile, c2->CRLfile) && + strcasecompare(c1->pinned_key, c2->pinned_key)) + return TRUE; + + return FALSE; +} + +bool Curl_ssl_conn_config_match(struct Curl_easy *data, + struct connectdata *candidate, + bool proxy) +{ +#ifndef CURL_DISABLE_PROXY + if(proxy) + return match_ssl_primary_config(data, &data->set.proxy_ssl.primary, + &candidate->proxy_ssl_config); +#else + (void)proxy; +#endif + return match_ssl_primary_config(data, &data->set.ssl.primary, + &candidate->ssl_config); +} + +static bool clone_ssl_primary_config(struct ssl_primary_config *source, + struct ssl_primary_config *dest) +{ + dest->version = source->version; + dest->version_max = source->version_max; + dest->verifypeer = source->verifypeer; + dest->verifyhost = source->verifyhost; + dest->verifystatus = source->verifystatus; + dest->sessionid = source->sessionid; + dest->ssl_options = source->ssl_options; + + CLONE_BLOB(cert_blob); + CLONE_BLOB(ca_info_blob); + CLONE_BLOB(issuercert_blob); + CLONE_STRING(CApath); + CLONE_STRING(CAfile); + CLONE_STRING(issuercert); + CLONE_STRING(clientcert); + CLONE_STRING(cipher_list); + CLONE_STRING(cipher_list13); + CLONE_STRING(pinned_key); + CLONE_STRING(curves); + CLONE_STRING(CRLfile); +#ifdef USE_TLS_SRP + CLONE_STRING(username); + CLONE_STRING(password); +#endif + + return TRUE; +} + +static void Curl_free_primary_ssl_config(struct ssl_primary_config *sslc) +{ + Curl_safefree(sslc->CApath); + Curl_safefree(sslc->CAfile); + Curl_safefree(sslc->issuercert); + Curl_safefree(sslc->clientcert); + Curl_safefree(sslc->cipher_list); + Curl_safefree(sslc->cipher_list13); + Curl_safefree(sslc->pinned_key); + Curl_safefree(sslc->cert_blob); + Curl_safefree(sslc->ca_info_blob); + Curl_safefree(sslc->issuercert_blob); + Curl_safefree(sslc->curves); + Curl_safefree(sslc->CRLfile); +#ifdef USE_TLS_SRP + Curl_safefree(sslc->username); + Curl_safefree(sslc->password); +#endif +} + +CURLcode Curl_ssl_easy_config_complete(struct Curl_easy *data) +{ + data->set.ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH]; + data->set.ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE]; + data->set.ssl.primary.CRLfile = data->set.str[STRING_SSL_CRLFILE]; + data->set.ssl.primary.issuercert = data->set.str[STRING_SSL_ISSUERCERT]; + data->set.ssl.primary.issuercert_blob = data->set.blobs[BLOB_SSL_ISSUERCERT]; + data->set.ssl.primary.cipher_list = + data->set.str[STRING_SSL_CIPHER_LIST]; + data->set.ssl.primary.cipher_list13 = + data->set.str[STRING_SSL_CIPHER13_LIST]; + data->set.ssl.primary.pinned_key = + data->set.str[STRING_SSL_PINNEDPUBLICKEY]; + data->set.ssl.primary.cert_blob = data->set.blobs[BLOB_CERT]; + data->set.ssl.primary.ca_info_blob = data->set.blobs[BLOB_CAINFO]; + data->set.ssl.primary.curves = data->set.str[STRING_SSL_EC_CURVES]; +#ifdef USE_TLS_SRP + data->set.ssl.primary.username = data->set.str[STRING_TLSAUTH_USERNAME]; + data->set.ssl.primary.password = data->set.str[STRING_TLSAUTH_PASSWORD]; +#endif + data->set.ssl.cert_type = data->set.str[STRING_CERT_TYPE]; + data->set.ssl.key = data->set.str[STRING_KEY]; + data->set.ssl.key_type = data->set.str[STRING_KEY_TYPE]; + data->set.ssl.key_passwd = data->set.str[STRING_KEY_PASSWD]; + data->set.ssl.primary.clientcert = data->set.str[STRING_CERT]; + data->set.ssl.key_blob = data->set.blobs[BLOB_KEY]; + +#ifndef CURL_DISABLE_PROXY + data->set.proxy_ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_PROXY]; + data->set.proxy_ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_PROXY]; + data->set.proxy_ssl.primary.cipher_list = + data->set.str[STRING_SSL_CIPHER_LIST_PROXY]; + data->set.proxy_ssl.primary.cipher_list13 = + data->set.str[STRING_SSL_CIPHER13_LIST_PROXY]; + data->set.proxy_ssl.primary.pinned_key = + data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY]; + data->set.proxy_ssl.primary.cert_blob = data->set.blobs[BLOB_CERT_PROXY]; + data->set.proxy_ssl.primary.ca_info_blob = + data->set.blobs[BLOB_CAINFO_PROXY]; + data->set.proxy_ssl.primary.issuercert = + data->set.str[STRING_SSL_ISSUERCERT_PROXY]; + data->set.proxy_ssl.primary.issuercert_blob = + data->set.blobs[BLOB_SSL_ISSUERCERT_PROXY]; + data->set.proxy_ssl.primary.CRLfile = + data->set.str[STRING_SSL_CRLFILE_PROXY]; + data->set.proxy_ssl.cert_type = data->set.str[STRING_CERT_TYPE_PROXY]; + data->set.proxy_ssl.key = data->set.str[STRING_KEY_PROXY]; + data->set.proxy_ssl.key_type = data->set.str[STRING_KEY_TYPE_PROXY]; + data->set.proxy_ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_PROXY]; + data->set.proxy_ssl.primary.clientcert = data->set.str[STRING_CERT_PROXY]; + data->set.proxy_ssl.key_blob = data->set.blobs[BLOB_KEY_PROXY]; +#ifdef USE_TLS_SRP + data->set.proxy_ssl.primary.username = + data->set.str[STRING_TLSAUTH_USERNAME_PROXY]; + data->set.proxy_ssl.primary.password = + data->set.str[STRING_TLSAUTH_PASSWORD_PROXY]; +#endif +#endif /* CURL_DISABLE_PROXY */ + + return CURLE_OK; +} + +CURLcode Curl_ssl_conn_config_init(struct Curl_easy *data, + struct connectdata *conn) +{ + /* Clone "primary" SSL configurations from the esay handle to + * the connection. They are used for connection cache matching and + * probably outlive the easy handle */ + if(!clone_ssl_primary_config(&data->set.ssl.primary, &conn->ssl_config)) + return CURLE_OUT_OF_MEMORY; +#ifndef CURL_DISABLE_PROXY + if(!clone_ssl_primary_config(&data->set.proxy_ssl.primary, + &conn->proxy_ssl_config)) + return CURLE_OUT_OF_MEMORY; +#endif + return CURLE_OK; +} + +void Curl_ssl_conn_config_cleanup(struct connectdata *conn) +{ + Curl_free_primary_ssl_config(&conn->ssl_config); +#ifndef CURL_DISABLE_PROXY + Curl_free_primary_ssl_config(&conn->proxy_ssl_config); +#endif +} + +void Curl_ssl_conn_config_update(struct Curl_easy *data, bool for_proxy) +{ + /* May be called on an easy that has no connection yet */ + if(data->conn) { + struct ssl_primary_config *src, *dest; +#ifndef CURL_DISABLE_PROXY + src = for_proxy? &data->set.proxy_ssl.primary : &data->set.ssl.primary; + dest = for_proxy? &data->conn->proxy_ssl_config : &data->conn->ssl_config; +#else + (void)for_proxy; + src = &data->set.ssl.primary; + dest = &data->conn->ssl_config; +#endif + dest->verifyhost = src->verifyhost; + dest->verifypeer = src->verifypeer; + dest->verifystatus = src->verifystatus; + } +} + +#ifdef USE_SSL +static int multissl_setup(const struct Curl_ssl *backend); +#endif + +curl_sslbackend Curl_ssl_backend(void) +{ +#ifdef USE_SSL + multissl_setup(NULL); + return Curl_ssl->info.id; +#else + return CURLSSLBACKEND_NONE; +#endif +} + +#ifdef USE_SSL + +/* "global" init done? */ +static bool init_ssl = FALSE; + +/** + * Global SSL init + * + * @retval 0 error initializing SSL + * @retval 1 SSL initialized successfully + */ +int Curl_ssl_init(void) +{ + /* make sure this is only done once */ + if(init_ssl) + return 1; + init_ssl = TRUE; /* never again */ + + return Curl_ssl->init(); +} + +#if defined(CURL_WITH_MULTI_SSL) +static const struct Curl_ssl Curl_ssl_multi; +#endif + +/* Global cleanup */ +void Curl_ssl_cleanup(void) +{ + if(init_ssl) { + /* only cleanup if we did a previous init */ + Curl_ssl->cleanup(); +#if defined(CURL_WITH_MULTI_SSL) + Curl_ssl = &Curl_ssl_multi; +#endif + init_ssl = FALSE; + } +} + +static bool ssl_prefs_check(struct Curl_easy *data) +{ + /* check for CURLOPT_SSLVERSION invalid parameter value */ + const unsigned char sslver = data->set.ssl.primary.version; + if(sslver >= CURL_SSLVERSION_LAST) { + failf(data, "Unrecognized parameter value passed via CURLOPT_SSLVERSION"); + return FALSE; + } + + switch(data->set.ssl.primary.version_max) { + case CURL_SSLVERSION_MAX_NONE: + case CURL_SSLVERSION_MAX_DEFAULT: + break; + + default: + if((data->set.ssl.primary.version_max >> 16) < sslver) { + failf(data, "CURL_SSLVERSION_MAX incompatible with CURL_SSLVERSION"); + return FALSE; + } + } + + return TRUE; +} + +static struct ssl_connect_data *cf_ctx_new(struct Curl_easy *data, + const struct alpn_spec *alpn) +{ + struct ssl_connect_data *ctx; + + (void)data; + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) + return NULL; + + ctx->alpn = alpn; + ctx->backend = calloc(1, Curl_ssl->sizeof_ssl_backend_data); + if(!ctx->backend) { + free(ctx); + return NULL; + } + return ctx; +} + +static void cf_ctx_free(struct ssl_connect_data *ctx) +{ + if(ctx) { + free(ctx->backend); + free(ctx); + } +} + +static CURLcode ssl_connect(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + CURLcode result; + + if(!ssl_prefs_check(data)) + return CURLE_SSL_CONNECT_ERROR; + + /* mark this is being ssl-enabled from here on. */ + connssl->state = ssl_connection_negotiating; + + result = Curl_ssl->connect_blocking(cf, data); + + if(!result) { + DEBUGASSERT(connssl->state == ssl_connection_complete); + } + + return result; +} + +static CURLcode +ssl_connect_nonblocking(struct Curl_cfilter *cf, struct Curl_easy *data, + bool *done) +{ + if(!ssl_prefs_check(data)) + return CURLE_SSL_CONNECT_ERROR; + + /* mark this is being ssl requested from here on. */ + return Curl_ssl->connect_nonblocking(cf, data, done); +} + +/* + * Lock shared SSL session data + */ +void Curl_ssl_sessionid_lock(struct Curl_easy *data) +{ + if(SSLSESSION_SHARED(data)) + Curl_share_lock(data, CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE); +} + +/* + * Unlock shared SSL session data + */ +void Curl_ssl_sessionid_unlock(struct Curl_easy *data) +{ + if(SSLSESSION_SHARED(data)) + Curl_share_unlock(data, CURL_LOCK_DATA_SSL_SESSION); +} + +/* + * Check if there's a session ID for the given connection in the cache, and if + * there's one suitable, it is provided. Returns TRUE when no entry matched. + */ +bool Curl_ssl_getsessionid(struct Curl_cfilter *cf, + struct Curl_easy *data, + const struct ssl_peer *peer, + void **ssl_sessionid, + size_t *idsize) /* set 0 if unknown */ +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + struct Curl_ssl_session *check; + size_t i; + long *general_age; + bool no_match = TRUE; + + *ssl_sessionid = NULL; + if(!ssl_config) + return TRUE; + + DEBUGASSERT(ssl_config->primary.sessionid); + + if(!ssl_config->primary.sessionid || !data->state.session) + /* session ID reuse is disabled or the session cache has not been + setup */ + return TRUE; + + /* Lock if shared */ + if(SSLSESSION_SHARED(data)) + general_age = &data->share->sessionage; + else + general_age = &data->state.sessionage; + + for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) { + check = &data->state.session[i]; + if(!check->sessionid) + /* not session ID means blank entry */ + continue; + if(strcasecompare(peer->hostname, check->name) && + ((!cf->conn->bits.conn_to_host && !check->conn_to_host) || + (cf->conn->bits.conn_to_host && check->conn_to_host && + strcasecompare(cf->conn->conn_to_host.name, check->conn_to_host))) && + ((!cf->conn->bits.conn_to_port && check->conn_to_port == -1) || + (cf->conn->bits.conn_to_port && check->conn_to_port != -1 && + cf->conn->conn_to_port == check->conn_to_port)) && + (peer->port == check->remote_port) && + (peer->transport == check->transport) && + strcasecompare(cf->conn->handler->scheme, check->scheme) && + match_ssl_primary_config(data, conn_config, &check->ssl_config)) { + /* yes, we have a session ID! */ + (*general_age)++; /* increase general age */ + check->age = *general_age; /* set this as used in this age */ + *ssl_sessionid = check->sessionid; + if(idsize) + *idsize = check->idsize; + no_match = FALSE; + break; + } + } + + DEBUGF(infof(data, "%s Session ID in cache for %s %s://%s:%d", + no_match? "Didn't find": "Found", + Curl_ssl_cf_is_proxy(cf) ? "proxy" : "host", + cf->conn->handler->scheme, peer->hostname, peer->port)); + return no_match; +} + +/* + * Kill a single session ID entry in the cache. + */ +void Curl_ssl_kill_session(struct Curl_ssl_session *session) +{ + if(session->sessionid) { + /* defensive check */ + + /* free the ID the SSL-layer specific way */ + session->sessionid_free(session->sessionid, session->idsize); + + session->sessionid = NULL; + session->sessionid_free = NULL; + session->age = 0; /* fresh */ + + Curl_free_primary_ssl_config(&session->ssl_config); + + Curl_safefree(session->name); + Curl_safefree(session->conn_to_host); + } +} + +/* + * Delete the given session ID from the cache. + */ +void Curl_ssl_delsessionid(struct Curl_easy *data, void *ssl_sessionid) +{ + size_t i; + + for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) { + struct Curl_ssl_session *check = &data->state.session[i]; + + if(check->sessionid == ssl_sessionid) { + Curl_ssl_kill_session(check); + break; + } + } +} + +/* + * Store session id in the session cache. The ID passed on to this function + * must already have been extracted and allocated the proper way for the SSL + * layer. Curl_XXXX_session_free() will be called to free/kill the session ID + * later on. + */ +CURLcode Curl_ssl_addsessionid(struct Curl_cfilter *cf, + struct Curl_easy *data, + const struct ssl_peer *peer, + void *ssl_sessionid, + size_t idsize, + Curl_ssl_sessionid_dtor *sessionid_free_cb) +{ + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + size_t i; + struct Curl_ssl_session *store; + long oldest_age; + char *clone_host = NULL; + char *clone_conn_to_host = NULL; + int conn_to_port; + long *general_age; + CURLcode result = CURLE_OUT_OF_MEMORY; + + DEBUGASSERT(ssl_sessionid); + DEBUGASSERT(sessionid_free_cb); + + if(!data->state.session) { + sessionid_free_cb(ssl_sessionid, idsize); + return CURLE_OK; + } + + store = &data->state.session[0]; + oldest_age = data->state.session[0].age; /* zero if unused */ + DEBUGASSERT(ssl_config->primary.sessionid); + (void)ssl_config; + + clone_host = strdup(peer->hostname); + if(!clone_host) + goto out; + + if(cf->conn->bits.conn_to_host) { + clone_conn_to_host = strdup(cf->conn->conn_to_host.name); + if(!clone_conn_to_host) + goto out; + } + + if(cf->conn->bits.conn_to_port) + conn_to_port = cf->conn->conn_to_port; + else + conn_to_port = -1; + + /* Now we should add the session ID and the host name to the cache, (remove + the oldest if necessary) */ + + /* If using shared SSL session, lock! */ + if(SSLSESSION_SHARED(data)) { + general_age = &data->share->sessionage; + } + else { + general_age = &data->state.sessionage; + } + + /* find an empty slot for us, or find the oldest */ + for(i = 1; (i < data->set.general_ssl.max_ssl_sessions) && + data->state.session[i].sessionid; i++) { + if(data->state.session[i].age < oldest_age) { + oldest_age = data->state.session[i].age; + store = &data->state.session[i]; + } + } + if(i == data->set.general_ssl.max_ssl_sessions) + /* cache is full, we must "kill" the oldest entry! */ + Curl_ssl_kill_session(store); + else + store = &data->state.session[i]; /* use this slot */ + + /* now init the session struct wisely */ + if(!clone_ssl_primary_config(conn_config, &store->ssl_config)) { + Curl_free_primary_ssl_config(&store->ssl_config); + store->sessionid = NULL; /* let caller free sessionid */ + goto out; + } + store->sessionid = ssl_sessionid; + store->idsize = idsize; + store->sessionid_free = sessionid_free_cb; + store->age = *general_age; /* set current age */ + /* free it if there's one already present */ + free(store->name); + free(store->conn_to_host); + store->name = clone_host; /* clone host name */ + clone_host = NULL; + store->conn_to_host = clone_conn_to_host; /* clone connect to host name */ + clone_conn_to_host = NULL; + store->conn_to_port = conn_to_port; /* connect to port number */ + /* port number */ + store->remote_port = peer->port; + store->scheme = cf->conn->handler->scheme; + store->transport = peer->transport; + + result = CURLE_OK; + +out: + free(clone_host); + free(clone_conn_to_host); + if(result) { + failf(data, "Failed to add Session ID to cache for %s://%s:%d [%s]", + store->scheme, store->name, store->remote_port, + Curl_ssl_cf_is_proxy(cf) ? "PROXY" : "server"); + sessionid_free_cb(ssl_sessionid, idsize); + return result; + } + CURL_TRC_CF(data, cf, "Added Session ID to cache for %s://%s:%d [%s]", + store->scheme, store->name, store->remote_port, + Curl_ssl_cf_is_proxy(cf) ? "PROXY" : "server"); + return CURLE_OK; +} + +void Curl_free_multi_ssl_backend_data(struct multi_ssl_backend_data *mbackend) +{ + if(Curl_ssl->free_multi_ssl_backend_data && mbackend) + Curl_ssl->free_multi_ssl_backend_data(mbackend); +} + +void Curl_ssl_close_all(struct Curl_easy *data) +{ + /* kill the session ID cache if not shared */ + if(data->state.session && !SSLSESSION_SHARED(data)) { + size_t i; + for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) + /* the single-killer function handles empty table slots */ + Curl_ssl_kill_session(&data->state.session[i]); + + /* free the cache data */ + Curl_safefree(data->state.session); + } + + Curl_ssl->close_all(data); +} + +void Curl_ssl_adjust_pollset(struct Curl_cfilter *cf, struct Curl_easy *data, + struct easy_pollset *ps) +{ + if(!cf->connected) { + struct ssl_connect_data *connssl = cf->ctx; + curl_socket_t sock = Curl_conn_cf_get_socket(cf->next, data); + if(sock != CURL_SOCKET_BAD) { + if(connssl->connecting_state == ssl_connect_2_writing) { + Curl_pollset_set_out_only(data, ps, sock); + CURL_TRC_CF(data, cf, "adjust_pollset, POLLOUT fd=%" + CURL_FORMAT_SOCKET_T, sock); + } + else { + Curl_pollset_set_in_only(data, ps, sock); + CURL_TRC_CF(data, cf, "adjust_pollset, POLLIN fd=%" + CURL_FORMAT_SOCKET_T, sock); + } + } + } +} + +/* Selects an SSL crypto engine + */ +CURLcode Curl_ssl_set_engine(struct Curl_easy *data, const char *engine) +{ + return Curl_ssl->set_engine(data, engine); +} + +/* Selects the default SSL crypto engine + */ +CURLcode Curl_ssl_set_engine_default(struct Curl_easy *data) +{ + return Curl_ssl->set_engine_default(data); +} + +/* Return list of OpenSSL crypto engine names. */ +struct curl_slist *Curl_ssl_engines_list(struct Curl_easy *data) +{ + return Curl_ssl->engines_list(data); +} + +/* + * This sets up a session ID cache to the specified size. Make sure this code + * is agnostic to what underlying SSL technology we use. + */ +CURLcode Curl_ssl_initsessions(struct Curl_easy *data, size_t amount) +{ + struct Curl_ssl_session *session; + + if(data->state.session) + /* this is just a precaution to prevent multiple inits */ + return CURLE_OK; + + session = calloc(amount, sizeof(struct Curl_ssl_session)); + if(!session) + return CURLE_OUT_OF_MEMORY; + + /* store the info in the SSL section */ + data->set.general_ssl.max_ssl_sessions = amount; + data->state.session = session; + data->state.sessionage = 1; /* this is brand new */ + return CURLE_OK; +} + +static size_t multissl_version(char *buffer, size_t size); + +void Curl_ssl_version(char *buffer, size_t size) +{ +#ifdef CURL_WITH_MULTI_SSL + (void)multissl_version(buffer, size); +#else + (void)Curl_ssl->version(buffer, size); +#endif +} + +void Curl_ssl_free_certinfo(struct Curl_easy *data) +{ + struct curl_certinfo *ci = &data->info.certs; + + if(ci->num_of_certs) { + /* free all individual lists used */ + int i; + for(i = 0; inum_of_certs; i++) { + curl_slist_free_all(ci->certinfo[i]); + ci->certinfo[i] = NULL; + } + + free(ci->certinfo); /* free the actual array too */ + ci->certinfo = NULL; + ci->num_of_certs = 0; + } +} + +CURLcode Curl_ssl_init_certinfo(struct Curl_easy *data, int num) +{ + struct curl_certinfo *ci = &data->info.certs; + struct curl_slist **table; + + /* Free any previous certificate information structures */ + Curl_ssl_free_certinfo(data); + + /* Allocate the required certificate information structures */ + table = calloc((size_t) num, sizeof(struct curl_slist *)); + if(!table) + return CURLE_OUT_OF_MEMORY; + + ci->num_of_certs = num; + ci->certinfo = table; + + return CURLE_OK; +} + +/* + * 'value' is NOT a null-terminated string + */ +CURLcode Curl_ssl_push_certinfo_len(struct Curl_easy *data, + int certnum, + const char *label, + const char *value, + size_t valuelen) +{ + struct curl_certinfo *ci = &data->info.certs; + struct curl_slist *nl; + CURLcode result = CURLE_OK; + struct dynbuf build; + + Curl_dyn_init(&build, 10000); + + if(Curl_dyn_add(&build, label) || + Curl_dyn_addn(&build, ":", 1) || + Curl_dyn_addn(&build, value, valuelen)) + return CURLE_OUT_OF_MEMORY; + + nl = Curl_slist_append_nodup(ci->certinfo[certnum], + Curl_dyn_ptr(&build)); + if(!nl) { + Curl_dyn_free(&build); + curl_slist_free_all(ci->certinfo[certnum]); + result = CURLE_OUT_OF_MEMORY; + } + + ci->certinfo[certnum] = nl; + return result; +} + +CURLcode Curl_ssl_random(struct Curl_easy *data, + unsigned char *entropy, + size_t length) +{ + return Curl_ssl->random(data, entropy, length); +} + +/* + * Public key pem to der conversion + */ + +static CURLcode pubkey_pem_to_der(const char *pem, + unsigned char **der, size_t *der_len) +{ + char *stripped_pem, *begin_pos, *end_pos; + size_t pem_count, stripped_pem_count = 0, pem_len; + CURLcode result; + + /* if no pem, exit. */ + if(!pem) + return CURLE_BAD_CONTENT_ENCODING; + + begin_pos = strstr(pem, "-----BEGIN PUBLIC KEY-----"); + if(!begin_pos) + return CURLE_BAD_CONTENT_ENCODING; + + pem_count = begin_pos - pem; + /* Invalid if not at beginning AND not directly following \n */ + if(0 != pem_count && '\n' != pem[pem_count - 1]) + return CURLE_BAD_CONTENT_ENCODING; + + /* 26 is length of "-----BEGIN PUBLIC KEY-----" */ + pem_count += 26; + + /* Invalid if not directly following \n */ + end_pos = strstr(pem + pem_count, "\n-----END PUBLIC KEY-----"); + if(!end_pos) + return CURLE_BAD_CONTENT_ENCODING; + + pem_len = end_pos - pem; + + stripped_pem = malloc(pem_len - pem_count + 1); + if(!stripped_pem) + return CURLE_OUT_OF_MEMORY; + + /* + * Here we loop through the pem array one character at a time between the + * correct indices, and place each character that is not '\n' or '\r' + * into the stripped_pem array, which should represent the raw base64 string + */ + while(pem_count < pem_len) { + if('\n' != pem[pem_count] && '\r' != pem[pem_count]) + stripped_pem[stripped_pem_count++] = pem[pem_count]; + ++pem_count; + } + /* Place the null terminator in the correct place */ + stripped_pem[stripped_pem_count] = '\0'; + + result = Curl_base64_decode(stripped_pem, der, der_len); + + Curl_safefree(stripped_pem); + + return result; +} + +/* + * Generic pinned public key check. + */ + +CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data, + const char *pinnedpubkey, + const unsigned char *pubkey, size_t pubkeylen) +{ + FILE *fp; + unsigned char *buf = NULL, *pem_ptr = NULL; + CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; +#ifdef CURL_DISABLE_VERBOSE_STRINGS + (void)data; +#endif + + /* if a path wasn't specified, don't pin */ + if(!pinnedpubkey) + return CURLE_OK; + if(!pubkey || !pubkeylen) + return result; + + /* only do this if pinnedpubkey starts with "sha256//", length 8 */ + if(strncmp(pinnedpubkey, "sha256//", 8) == 0) { + CURLcode encode; + size_t encodedlen = 0; + char *encoded = NULL, *pinkeycopy, *begin_pos, *end_pos; + unsigned char *sha256sumdigest; + + if(!Curl_ssl->sha256sum) { + /* without sha256 support, this cannot match */ + return result; + } + + /* compute sha256sum of public key */ + sha256sumdigest = malloc(CURL_SHA256_DIGEST_LENGTH); + if(!sha256sumdigest) + return CURLE_OUT_OF_MEMORY; + encode = Curl_ssl->sha256sum(pubkey, pubkeylen, + sha256sumdigest, CURL_SHA256_DIGEST_LENGTH); + + if(!encode) + encode = Curl_base64_encode((char *)sha256sumdigest, + CURL_SHA256_DIGEST_LENGTH, &encoded, + &encodedlen); + Curl_safefree(sha256sumdigest); + + if(encode) + return encode; + + infof(data, " public key hash: sha256//%s", encoded); + + /* it starts with sha256//, copy so we can modify it */ + pinkeycopy = strdup(pinnedpubkey); + if(!pinkeycopy) { + Curl_safefree(encoded); + return CURLE_OUT_OF_MEMORY; + } + /* point begin_pos to the copy, and start extracting keys */ + begin_pos = pinkeycopy; + do { + end_pos = strstr(begin_pos, ";sha256//"); + /* + * if there is an end_pos, null terminate, + * otherwise it'll go to the end of the original string + */ + if(end_pos) + end_pos[0] = '\0'; + + /* compare base64 sha256 digests, 8 is the length of "sha256//" */ + if(encodedlen == strlen(begin_pos + 8) && + !memcmp(encoded, begin_pos + 8, encodedlen)) { + result = CURLE_OK; + break; + } + + /* + * change back the null-terminator we changed earlier, + * and look for next begin + */ + if(end_pos) { + end_pos[0] = ';'; + begin_pos = strstr(end_pos, "sha256//"); + } + } while(end_pos && begin_pos); + Curl_safefree(encoded); + Curl_safefree(pinkeycopy); + return result; + } + + fp = fopen(pinnedpubkey, "rb"); + if(!fp) + return result; + + do { + long filesize; + size_t size, pem_len; + CURLcode pem_read; + + /* Determine the file's size */ + if(fseek(fp, 0, SEEK_END)) + break; + filesize = ftell(fp); + if(fseek(fp, 0, SEEK_SET)) + break; + if(filesize < 0 || filesize > MAX_PINNED_PUBKEY_SIZE) + break; + + /* + * if the size of our certificate is bigger than the file + * size then it can't match + */ + size = curlx_sotouz((curl_off_t) filesize); + if(pubkeylen > size) + break; + + /* + * Allocate buffer for the pinned key + * With 1 additional byte for null terminator in case of PEM key + */ + buf = malloc(size + 1); + if(!buf) + break; + + /* Returns number of elements read, which should be 1 */ + if((int) fread(buf, size, 1, fp) != 1) + break; + + /* If the sizes are the same, it can't be base64 encoded, must be der */ + if(pubkeylen == size) { + if(!memcmp(pubkey, buf, pubkeylen)) + result = CURLE_OK; + break; + } + + /* + * Otherwise we will assume it's PEM and try to decode it + * after placing null terminator + */ + buf[size] = '\0'; + pem_read = pubkey_pem_to_der((const char *)buf, &pem_ptr, &pem_len); + /* if it wasn't read successfully, exit */ + if(pem_read) + break; + + /* + * if the size of our certificate doesn't match the size of + * the decoded file, they can't be the same, otherwise compare + */ + if(pubkeylen == pem_len && !memcmp(pubkey, pem_ptr, pubkeylen)) + result = CURLE_OK; + } while(0); + + Curl_safefree(buf); + Curl_safefree(pem_ptr); + fclose(fp); + + return result; +} + +/* + * Check whether the SSL backend supports the status_request extension. + */ +bool Curl_ssl_cert_status_request(void) +{ + return Curl_ssl->cert_status_request(); +} + +/* + * Check whether the SSL backend supports false start. + */ +bool Curl_ssl_false_start(struct Curl_easy *data) +{ + (void)data; + return Curl_ssl->false_start(); +} + +/* + * Default implementations for unsupported functions. + */ + +int Curl_none_init(void) +{ + return 1; +} + +void Curl_none_cleanup(void) +{ } + +int Curl_none_shutdown(struct Curl_cfilter *cf UNUSED_PARAM, + struct Curl_easy *data UNUSED_PARAM) +{ + (void)data; + (void)cf; + return 0; +} + +int Curl_none_check_cxn(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + (void)cf; + (void)data; + return -1; +} + +CURLcode Curl_none_random(struct Curl_easy *data UNUSED_PARAM, + unsigned char *entropy UNUSED_PARAM, + size_t length UNUSED_PARAM) +{ + (void)data; + (void)entropy; + (void)length; + return CURLE_NOT_BUILT_IN; +} + +void Curl_none_close_all(struct Curl_easy *data UNUSED_PARAM) +{ + (void)data; +} + +void Curl_none_session_free(void *ptr UNUSED_PARAM) +{ + (void)ptr; +} + +bool Curl_none_data_pending(struct Curl_cfilter *cf UNUSED_PARAM, + const struct Curl_easy *data UNUSED_PARAM) +{ + (void)cf; + (void)data; + return 0; +} + +bool Curl_none_cert_status_request(void) +{ + return FALSE; +} + +CURLcode Curl_none_set_engine(struct Curl_easy *data UNUSED_PARAM, + const char *engine UNUSED_PARAM) +{ + (void)data; + (void)engine; + return CURLE_NOT_BUILT_IN; +} + +CURLcode Curl_none_set_engine_default(struct Curl_easy *data UNUSED_PARAM) +{ + (void)data; + return CURLE_NOT_BUILT_IN; +} + +struct curl_slist *Curl_none_engines_list(struct Curl_easy *data UNUSED_PARAM) +{ + (void)data; + return (struct curl_slist *)NULL; +} + +bool Curl_none_false_start(void) +{ + return FALSE; +} + +static int multissl_init(void) +{ + if(multissl_setup(NULL)) + return 1; + return Curl_ssl->init(); +} + +static CURLcode multissl_connect(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + if(multissl_setup(NULL)) + return CURLE_FAILED_INIT; + return Curl_ssl->connect_blocking(cf, data); +} + +static CURLcode multissl_connect_nonblocking(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + if(multissl_setup(NULL)) + return CURLE_FAILED_INIT; + return Curl_ssl->connect_nonblocking(cf, data, done); +} + +static void multissl_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + if(multissl_setup(NULL)) + return; + Curl_ssl->adjust_pollset(cf, data, ps); +} + +static void *multissl_get_internals(struct ssl_connect_data *connssl, + CURLINFO info) +{ + if(multissl_setup(NULL)) + return NULL; + return Curl_ssl->get_internals(connssl, info); +} + +static void multissl_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + if(multissl_setup(NULL)) + return; + Curl_ssl->close(cf, data); +} + +static ssize_t multissl_recv_plain(struct Curl_cfilter *cf, + struct Curl_easy *data, + char *buf, size_t len, CURLcode *code) +{ + if(multissl_setup(NULL)) + return CURLE_FAILED_INIT; + return Curl_ssl->recv_plain(cf, data, buf, len, code); +} + +static ssize_t multissl_send_plain(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *mem, size_t len, + CURLcode *code) +{ + if(multissl_setup(NULL)) + return CURLE_FAILED_INIT; + return Curl_ssl->send_plain(cf, data, mem, len, code); +} + +static const struct Curl_ssl Curl_ssl_multi = { + { CURLSSLBACKEND_NONE, "multi" }, /* info */ + 0, /* supports nothing */ + (size_t)-1, /* something insanely large to be on the safe side */ + + multissl_init, /* init */ + Curl_none_cleanup, /* cleanup */ + multissl_version, /* version */ + Curl_none_check_cxn, /* check_cxn */ + Curl_none_shutdown, /* shutdown */ + Curl_none_data_pending, /* data_pending */ + Curl_none_random, /* random */ + Curl_none_cert_status_request, /* cert_status_request */ + multissl_connect, /* connect */ + multissl_connect_nonblocking, /* connect_nonblocking */ + multissl_adjust_pollset, /* adjust_pollset */ + multissl_get_internals, /* get_internals */ + multissl_close, /* close_one */ + Curl_none_close_all, /* close_all */ + Curl_none_set_engine, /* set_engine */ + Curl_none_set_engine_default, /* set_engine_default */ + Curl_none_engines_list, /* engines_list */ + Curl_none_false_start, /* false_start */ + NULL, /* sha256sum */ + NULL, /* associate_connection */ + NULL, /* disassociate_connection */ + NULL, /* free_multi_ssl_backend_data */ + multissl_recv_plain, /* recv decrypted data */ + multissl_send_plain, /* send data to encrypt */ +}; + +const struct Curl_ssl *Curl_ssl = +#if defined(CURL_WITH_MULTI_SSL) + &Curl_ssl_multi; +#elif defined(USE_WOLFSSL) + &Curl_ssl_wolfssl; +#elif defined(USE_SECTRANSP) + &Curl_ssl_sectransp; +#elif defined(USE_GNUTLS) + &Curl_ssl_gnutls; +#elif defined(USE_MBEDTLS) + &Curl_ssl_mbedtls; +#elif defined(USE_RUSTLS) + &Curl_ssl_rustls; +#elif defined(USE_OPENSSL) + &Curl_ssl_openssl; +#elif defined(USE_SCHANNEL) + &Curl_ssl_schannel; +#elif defined(USE_BEARSSL) + &Curl_ssl_bearssl; +#else +#error "Missing struct Curl_ssl for selected SSL backend" +#endif + +static const struct Curl_ssl *available_backends[] = { +#if defined(USE_WOLFSSL) + &Curl_ssl_wolfssl, +#endif +#if defined(USE_SECTRANSP) + &Curl_ssl_sectransp, +#endif +#if defined(USE_GNUTLS) + &Curl_ssl_gnutls, +#endif +#if defined(USE_MBEDTLS) + &Curl_ssl_mbedtls, +#endif +#if defined(USE_OPENSSL) + &Curl_ssl_openssl, +#endif +#if defined(USE_SCHANNEL) + &Curl_ssl_schannel, +#endif +#if defined(USE_BEARSSL) + &Curl_ssl_bearssl, +#endif +#if defined(USE_RUSTLS) + &Curl_ssl_rustls, +#endif + NULL +}; + +static size_t multissl_version(char *buffer, size_t size) +{ + static const struct Curl_ssl *selected; + static char backends[200]; + static size_t backends_len; + const struct Curl_ssl *current; + + current = Curl_ssl == &Curl_ssl_multi ? available_backends[0] : Curl_ssl; + + if(current != selected) { + char *p = backends; + char *end = backends + sizeof(backends); + int i; + + selected = current; + + backends[0] = '\0'; + + for(i = 0; available_backends[i]; ++i) { + char vb[200]; + bool paren = (selected != available_backends[i]); + + if(available_backends[i]->version(vb, sizeof(vb))) { + p += msnprintf(p, end - p, "%s%s%s%s", (p != backends ? " " : ""), + (paren ? "(" : ""), vb, (paren ? ")" : "")); + } + } + + backends_len = p - backends; + } + + if(size) { + if(backends_len < size) + strcpy(buffer, backends); + else + *buffer = 0; /* did not fit */ + } + return 0; +} + +static int multissl_setup(const struct Curl_ssl *backend) +{ + const char *env; + char *env_tmp; + + if(Curl_ssl != &Curl_ssl_multi) + return 1; + + if(backend) { + Curl_ssl = backend; + return 0; + } + + if(!available_backends[0]) + return 1; + + env = env_tmp = curl_getenv("CURL_SSL_BACKEND"); +#ifdef CURL_DEFAULT_SSL_BACKEND + if(!env) + env = CURL_DEFAULT_SSL_BACKEND; +#endif + if(env) { + int i; + for(i = 0; available_backends[i]; i++) { + if(strcasecompare(env, available_backends[i]->info.name)) { + Curl_ssl = available_backends[i]; + free(env_tmp); + return 0; + } + } + } + + /* Fall back to first available backend */ + Curl_ssl = available_backends[0]; + free(env_tmp); + return 0; +} + +/* This function is used to select the SSL backend to use. It is called by + curl_global_sslset (easy.c) which uses the global init lock. */ +CURLsslset Curl_init_sslset_nolock(curl_sslbackend id, const char *name, + const curl_ssl_backend ***avail) +{ + int i; + + if(avail) + *avail = (const curl_ssl_backend **)&available_backends; + + if(Curl_ssl != &Curl_ssl_multi) + return id == Curl_ssl->info.id || + (name && strcasecompare(name, Curl_ssl->info.name)) ? + CURLSSLSET_OK : +#if defined(CURL_WITH_MULTI_SSL) + CURLSSLSET_TOO_LATE; +#else + CURLSSLSET_UNKNOWN_BACKEND; +#endif + + for(i = 0; available_backends[i]; i++) { + if(available_backends[i]->info.id == id || + (name && strcasecompare(available_backends[i]->info.name, name))) { + multissl_setup(available_backends[i]); + return CURLSSLSET_OK; + } + } + + return CURLSSLSET_UNKNOWN_BACKEND; +} + +#else /* USE_SSL */ +CURLsslset Curl_init_sslset_nolock(curl_sslbackend id, const char *name, + const curl_ssl_backend ***avail) +{ + (void)id; + (void)name; + (void)avail; + return CURLSSLSET_NO_BACKENDS; +} + +#endif /* !USE_SSL */ + +#ifdef USE_SSL + +void Curl_ssl_peer_cleanup(struct ssl_peer *peer) +{ + if(peer->dispname != peer->hostname) + free(peer->dispname); + free(peer->sni); + free(peer->hostname); + peer->hostname = peer->sni = peer->dispname = NULL; + peer->type = CURL_SSL_PEER_DNS; +} + +static void cf_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + if(connssl) { + Curl_ssl->close(cf, data); + connssl->state = ssl_connection_none; + Curl_ssl_peer_cleanup(&connssl->peer); + } + cf->connected = FALSE; +} + +static ssl_peer_type get_peer_type(const char *hostname) +{ + if(hostname && hostname[0]) { +#ifdef USE_IPV6 + struct in6_addr addr; +#else + struct in_addr addr; +#endif + if(Curl_inet_pton(AF_INET, hostname, &addr)) + return CURL_SSL_PEER_IPV4; +#ifdef USE_IPV6 + else if(Curl_inet_pton(AF_INET6, hostname, &addr)) { + return CURL_SSL_PEER_IPV6; + } +#endif + } + return CURL_SSL_PEER_DNS; +} + +CURLcode Curl_ssl_peer_init(struct ssl_peer *peer, struct Curl_cfilter *cf, + int transport) +{ + const char *ehostname, *edispname; + int eport; + + /* We need the hostname for SNI negotiation. Once handshaked, this + * remains the SNI hostname for the TLS connection. But when the + * connection is reused, the settings in cf->conn might change. + * So we keep a copy of the hostname we use for SNI. + */ +#ifndef CURL_DISABLE_PROXY + if(Curl_ssl_cf_is_proxy(cf)) { + ehostname = cf->conn->http_proxy.host.name; + edispname = cf->conn->http_proxy.host.dispname; + eport = cf->conn->http_proxy.port; + } + else +#endif + { + ehostname = cf->conn->host.name; + edispname = cf->conn->host.dispname; + eport = cf->conn->remote_port; + } + + /* change if ehostname changed */ + DEBUGASSERT(!ehostname || ehostname[0]); + if(ehostname && (!peer->hostname + || strcmp(ehostname, peer->hostname))) { + Curl_ssl_peer_cleanup(peer); + peer->hostname = strdup(ehostname); + if(!peer->hostname) { + Curl_ssl_peer_cleanup(peer); + return CURLE_OUT_OF_MEMORY; + } + if(!edispname || !strcmp(ehostname, edispname)) + peer->dispname = peer->hostname; + else { + peer->dispname = strdup(edispname); + if(!peer->dispname) { + Curl_ssl_peer_cleanup(peer); + return CURLE_OUT_OF_MEMORY; + } + } + + peer->type = get_peer_type(peer->hostname); + if(peer->type == CURL_SSL_PEER_DNS && peer->hostname[0]) { + /* not an IP address, normalize according to RCC 6066 ch. 3, + * max len of SNI is 2^16-1, no trailing dot */ + size_t len = strlen(peer->hostname); + if(len && (peer->hostname[len-1] == '.')) + len--; + if(len < USHRT_MAX) { + peer->sni = calloc(1, len + 1); + if(!peer->sni) { + Curl_ssl_peer_cleanup(peer); + return CURLE_OUT_OF_MEMORY; + } + Curl_strntolower(peer->sni, peer->hostname, len); + peer->sni[len] = 0; + } + } + + } + peer->port = eport; + peer->transport = transport; + return CURLE_OK; +} + +static void ssl_cf_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + cf_close(cf, data); + CF_DATA_RESTORE(cf, save); + cf_ctx_free(cf->ctx); + cf->ctx = NULL; +} + +static void ssl_cf_close(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + cf_close(cf, data); + if(cf->next) + cf->next->cft->do_close(cf->next, data); + CF_DATA_RESTORE(cf, save); +} + +static CURLcode ssl_cf_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct cf_call_data save; + CURLcode result; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + CF_DATA_SAVE(save, cf, data); + CURL_TRC_CF(data, cf, "cf_connect()"); + (void)connssl; + DEBUGASSERT(data->conn); + DEBUGASSERT(data->conn == cf->conn); + DEBUGASSERT(connssl); + DEBUGASSERT(cf->conn->host.name); + + result = cf->next->cft->do_connect(cf->next, data, blocking, done); + if(result || !*done) + goto out; + + *done = FALSE; + result = Curl_ssl_peer_init(&connssl->peer, cf, TRNSPRT_TCP); + if(result) + goto out; + + if(blocking) { + result = ssl_connect(cf, data); + *done = (result == CURLE_OK); + } + else { + result = ssl_connect_nonblocking(cf, data, done); + } + + if(!result && *done) { + cf->connected = TRUE; + connssl->handshake_done = Curl_now(); + DEBUGASSERT(connssl->state == ssl_connection_complete); + } +out: + CURL_TRC_CF(data, cf, "cf_connect() -> %d, done=%d", result, *done); + CF_DATA_RESTORE(cf, save); + return result; +} + +static bool ssl_cf_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct cf_call_data save; + bool result; + + CF_DATA_SAVE(save, cf, data); + if(Curl_ssl->data_pending(cf, data)) + result = TRUE; + else + result = cf->next->cft->has_data_pending(cf->next, data); + CF_DATA_RESTORE(cf, save); + return result; +} + +static ssize_t ssl_cf_send(struct Curl_cfilter *cf, + struct Curl_easy *data, const void *buf, size_t len, + CURLcode *err) +{ + struct cf_call_data save; + ssize_t nwritten; + + CF_DATA_SAVE(save, cf, data); + *err = CURLE_OK; + nwritten = Curl_ssl->send_plain(cf, data, buf, len, err); + CF_DATA_RESTORE(cf, save); + return nwritten; +} + +static ssize_t ssl_cf_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, char *buf, size_t len, + CURLcode *err) +{ + struct cf_call_data save; + ssize_t nread; + + CF_DATA_SAVE(save, cf, data); + *err = CURLE_OK; + nread = Curl_ssl->recv_plain(cf, data, buf, len, err); + if(nread > 0) { + DEBUGASSERT((size_t)nread <= len); + } + else if(nread == 0) { + /* eof */ + *err = CURLE_OK; + } + CURL_TRC_CF(data, cf, "cf_recv(len=%zu) -> %zd, %d", len, + nread, *err); + CF_DATA_RESTORE(cf, save); + return nread; +} + +static void ssl_cf_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_call_data save; + + if(!cf->connected) { + CF_DATA_SAVE(save, cf, data); + Curl_ssl->adjust_pollset(cf, data, ps); + CF_DATA_RESTORE(cf, save); + } +} + +static CURLcode ssl_cf_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + struct cf_call_data save; + + (void)arg1; + (void)arg2; + switch(event) { + case CF_CTRL_DATA_ATTACH: + if(Curl_ssl->attach_data) { + CF_DATA_SAVE(save, cf, data); + Curl_ssl->attach_data(cf, data); + CF_DATA_RESTORE(cf, save); + } + break; + case CF_CTRL_DATA_DETACH: + if(Curl_ssl->detach_data) { + CF_DATA_SAVE(save, cf, data); + Curl_ssl->detach_data(cf, data); + CF_DATA_RESTORE(cf, save); + } + break; + default: + break; + } + return CURLE_OK; +} + +static CURLcode ssl_cf_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct ssl_connect_data *connssl = cf->ctx; + + switch(query) { + case CF_QUERY_TIMER_APPCONNECT: { + struct curltime *when = pres2; + if(cf->connected && !Curl_ssl_cf_is_proxy(cf)) + *when = connssl->handshake_done; + return CURLE_OK; + } + default: + break; + } + return cf->next? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +static bool cf_ssl_is_alive(struct Curl_cfilter *cf, struct Curl_easy *data, + bool *input_pending) +{ + struct cf_call_data save; + int result; + /* + * This function tries to determine connection status. + * + * Return codes: + * 1 means the connection is still in place + * 0 means the connection has been closed + * -1 means the connection status is unknown + */ + CF_DATA_SAVE(save, cf, data); + result = Curl_ssl->check_cxn(cf, data); + CF_DATA_RESTORE(cf, save); + if(result > 0) { + *input_pending = TRUE; + return TRUE; + } + if(result == 0) { + *input_pending = FALSE; + return FALSE; + } + /* ssl backend does not know */ + return cf->next? + cf->next->cft->is_alive(cf->next, data, input_pending) : + FALSE; /* pessimistic in absence of data */ +} + +struct Curl_cftype Curl_cft_ssl = { + "SSL", + CF_TYPE_SSL, + CURL_LOG_LVL_NONE, + ssl_cf_destroy, + ssl_cf_connect, + ssl_cf_close, + Curl_cf_def_get_host, + ssl_cf_adjust_pollset, + ssl_cf_data_pending, + ssl_cf_send, + ssl_cf_recv, + ssl_cf_cntrl, + cf_ssl_is_alive, + Curl_cf_def_conn_keep_alive, + ssl_cf_query, +}; + +#ifndef CURL_DISABLE_PROXY + +struct Curl_cftype Curl_cft_ssl_proxy = { + "SSL-PROXY", + CF_TYPE_SSL|CF_TYPE_PROXY, + CURL_LOG_LVL_NONE, + ssl_cf_destroy, + ssl_cf_connect, + ssl_cf_close, + Curl_cf_def_get_host, + ssl_cf_adjust_pollset, + ssl_cf_data_pending, + ssl_cf_send, + ssl_cf_recv, + ssl_cf_cntrl, + cf_ssl_is_alive, + Curl_cf_def_conn_keep_alive, + Curl_cf_def_query, +}; + +#endif /* !CURL_DISABLE_PROXY */ + +static CURLcode cf_ssl_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn) +{ + struct Curl_cfilter *cf = NULL; + struct ssl_connect_data *ctx; + CURLcode result; + + DEBUGASSERT(data->conn); + + ctx = cf_ctx_new(data, alpn_get_spec(data->state.httpwant, + conn->bits.tls_enable_alpn)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + result = Curl_cf_create(&cf, &Curl_cft_ssl, ctx); + +out: + if(result) + cf_ctx_free(ctx); + *pcf = result? NULL : cf; + return result; +} + +CURLcode Curl_ssl_cfilter_add(struct Curl_easy *data, + struct connectdata *conn, + int sockindex) +{ + struct Curl_cfilter *cf; + CURLcode result; + + result = cf_ssl_create(&cf, data, conn); + if(!result) + Curl_conn_cf_add(data, conn, sockindex, cf); + return result; +} + +CURLcode Curl_cf_ssl_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data) +{ + struct Curl_cfilter *cf; + CURLcode result; + + result = cf_ssl_create(&cf, data, cf_at->conn); + if(!result) + Curl_conn_cf_insert_after(cf_at, cf); + return result; +} + +#ifndef CURL_DISABLE_PROXY + +static CURLcode cf_ssl_proxy_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn) +{ + struct Curl_cfilter *cf = NULL; + struct ssl_connect_data *ctx; + CURLcode result; + bool use_alpn = conn->bits.tls_enable_alpn; + int httpwant = CURL_HTTP_VERSION_1_1; + +#ifdef USE_HTTP2 + if(conn->http_proxy.proxytype == CURLPROXY_HTTPS2) { + use_alpn = TRUE; + httpwant = CURL_HTTP_VERSION_2; + } +#endif + + ctx = cf_ctx_new(data, alpn_get_spec(httpwant, use_alpn)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + result = Curl_cf_create(&cf, &Curl_cft_ssl_proxy, ctx); + +out: + if(result) + cf_ctx_free(ctx); + *pcf = result? NULL : cf; + return result; +} + +CURLcode Curl_cf_ssl_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data) +{ + struct Curl_cfilter *cf; + CURLcode result; + + result = cf_ssl_proxy_create(&cf, data, cf_at->conn); + if(!result) + Curl_conn_cf_insert_after(cf_at, cf); + return result; +} + +#endif /* !CURL_DISABLE_PROXY */ + +bool Curl_ssl_supports(struct Curl_easy *data, int option) +{ + (void)data; + return (Curl_ssl->supports & option)? TRUE : FALSE; +} + +static struct Curl_cfilter *get_ssl_filter(struct Curl_cfilter *cf) +{ + for(; cf; cf = cf->next) { + if(cf->cft == &Curl_cft_ssl) + return cf; +#ifndef CURL_DISABLE_PROXY + if(cf->cft == &Curl_cft_ssl_proxy) + return cf; +#endif + } + return NULL; +} + + +void *Curl_ssl_get_internals(struct Curl_easy *data, int sockindex, + CURLINFO info, int n) +{ + void *result = NULL; + (void)n; + if(data->conn) { + struct Curl_cfilter *cf; + /* get first SSL filter in chain, if any is present */ + cf = get_ssl_filter(data->conn->cfilter[sockindex]); + if(cf) { + struct cf_call_data save; + CF_DATA_SAVE(save, cf, data); + result = Curl_ssl->get_internals(cf->ctx, info); + CF_DATA_RESTORE(cf, save); + } + } + return result; +} + +CURLcode Curl_ssl_cfilter_remove(struct Curl_easy *data, + int sockindex) +{ + struct Curl_cfilter *cf, *head; + CURLcode result = CURLE_OK; + + (void)data; + head = data->conn? data->conn->cfilter[sockindex] : NULL; + for(cf = head; cf; cf = cf->next) { + if(cf->cft == &Curl_cft_ssl) { + if(Curl_ssl->shut_down(cf, data)) + result = CURLE_SSL_SHUTDOWN_FAILED; + Curl_conn_cf_discard_sub(head, cf, data, FALSE); + break; + } + } + return result; +} + +bool Curl_ssl_cf_is_proxy(struct Curl_cfilter *cf) +{ + return (cf->cft->flags & CF_TYPE_SSL) && (cf->cft->flags & CF_TYPE_PROXY); +} + +struct ssl_config_data * +Curl_ssl_cf_get_config(struct Curl_cfilter *cf, struct Curl_easy *data) +{ +#ifdef CURL_DISABLE_PROXY + (void)cf; + return &data->set.ssl; +#else + return Curl_ssl_cf_is_proxy(cf)? &data->set.proxy_ssl : &data->set.ssl; +#endif +} + +struct ssl_primary_config * +Curl_ssl_cf_get_primary_config(struct Curl_cfilter *cf) +{ +#ifdef CURL_DISABLE_PROXY + return &cf->conn->ssl_config; +#else + return Curl_ssl_cf_is_proxy(cf)? + &cf->conn->proxy_ssl_config : &cf->conn->ssl_config; +#endif +} + +CURLcode Curl_alpn_to_proto_buf(struct alpn_proto_buf *buf, + const struct alpn_spec *spec) +{ + size_t i, len; + int off = 0; + unsigned char blen; + + memset(buf, 0, sizeof(*buf)); + for(i = 0; spec && i < spec->count; ++i) { + len = strlen(spec->entries[i]); + if(len >= ALPN_NAME_MAX) + return CURLE_FAILED_INIT; + blen = (unsigned char)len; + if(off + blen + 1 >= (int)sizeof(buf->data)) + return CURLE_FAILED_INIT; + buf->data[off++] = blen; + memcpy(buf->data + off, spec->entries[i], blen); + off += blen; + } + buf->len = off; + return CURLE_OK; +} + +CURLcode Curl_alpn_to_proto_str(struct alpn_proto_buf *buf, + const struct alpn_spec *spec) +{ + size_t i, len; + size_t off = 0; + + memset(buf, 0, sizeof(*buf)); + for(i = 0; spec && i < spec->count; ++i) { + len = strlen(spec->entries[i]); + if(len >= ALPN_NAME_MAX) + return CURLE_FAILED_INIT; + if(off + len + 2 >= sizeof(buf->data)) + return CURLE_FAILED_INIT; + if(off) + buf->data[off++] = ','; + memcpy(buf->data + off, spec->entries[i], len); + off += len; + } + buf->data[off] = '\0'; + buf->len = (int)off; + return CURLE_OK; +} + +CURLcode Curl_alpn_set_negotiated(struct Curl_cfilter *cf, + struct Curl_easy *data, + const unsigned char *proto, + size_t proto_len) +{ + int can_multi = 0; + unsigned char *palpn = +#ifndef CURL_DISABLE_PROXY + (cf->conn->bits.tunnel_proxy && Curl_ssl_cf_is_proxy(cf))? + &cf->conn->proxy_alpn : &cf->conn->alpn +#else + &cf->conn->alpn +#endif + ; + + if(proto && proto_len) { + if(proto_len == ALPN_HTTP_1_1_LENGTH && + !memcmp(ALPN_HTTP_1_1, proto, ALPN_HTTP_1_1_LENGTH)) { + *palpn = CURL_HTTP_VERSION_1_1; + } +#ifdef USE_HTTP2 + else if(proto_len == ALPN_H2_LENGTH && + !memcmp(ALPN_H2, proto, ALPN_H2_LENGTH)) { + *palpn = CURL_HTTP_VERSION_2; + can_multi = 1; + } +#endif +#ifdef USE_HTTP3 + else if(proto_len == ALPN_H3_LENGTH && + !memcmp(ALPN_H3, proto, ALPN_H3_LENGTH)) { + *palpn = CURL_HTTP_VERSION_3; + can_multi = 1; + } +#endif + else { + *palpn = CURL_HTTP_VERSION_NONE; + failf(data, "unsupported ALPN protocol: '%.*s'", (int)proto_len, proto); + /* TODO: do we want to fail this? Previous code just ignored it and + * some vtls backends even ignore the return code of this function. */ + /* return CURLE_NOT_BUILT_IN; */ + goto out; + } + infof(data, VTLS_INFOF_ALPN_ACCEPTED_LEN_1STR, (int)proto_len, proto); + } + else { + *palpn = CURL_HTTP_VERSION_NONE; + infof(data, VTLS_INFOF_NO_ALPN); + } + +out: + if(!Curl_ssl_cf_is_proxy(cf)) + Curl_multiuse_state(data, can_multi? + BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE); + return CURLE_OK; +} + +#endif /* USE_SSL */ diff --git a/third_party/curl/lib/vtls/vtls.h b/third_party/curl/lib/vtls/vtls.h new file mode 100644 index 0000000..c40ff26 --- /dev/null +++ b/third_party/curl/lib/vtls/vtls.h @@ -0,0 +1,260 @@ +#ifndef HEADER_CURL_VTLS_H +#define HEADER_CURL_VTLS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +struct connectdata; +struct ssl_config_data; +struct ssl_primary_config; +struct Curl_ssl_session; + +#define SSLSUPP_CA_PATH (1<<0) /* supports CAPATH */ +#define SSLSUPP_CERTINFO (1<<1) /* supports CURLOPT_CERTINFO */ +#define SSLSUPP_PINNEDPUBKEY (1<<2) /* supports CURLOPT_PINNEDPUBLICKEY */ +#define SSLSUPP_SSL_CTX (1<<3) /* supports CURLOPT_SSL_CTX */ +#define SSLSUPP_HTTPS_PROXY (1<<4) /* supports access via HTTPS proxies */ +#define SSLSUPP_TLS13_CIPHERSUITES (1<<5) /* supports TLS 1.3 ciphersuites */ +#define SSLSUPP_CAINFO_BLOB (1<<6) +#define SSLSUPP_ECH (1<<7) + +#define ALPN_ACCEPTED "ALPN: server accepted " + +#define VTLS_INFOF_NO_ALPN \ + "ALPN: server did not agree on a protocol. Uses default." +#define VTLS_INFOF_ALPN_OFFER_1STR \ + "ALPN: curl offers %s" +#define VTLS_INFOF_ALPN_ACCEPTED_1STR \ + ALPN_ACCEPTED "%s" +#define VTLS_INFOF_ALPN_ACCEPTED_LEN_1STR \ + ALPN_ACCEPTED "%.*s" + +/* Curl_multi SSL backend-specific data; declared differently by each SSL + backend */ +struct multi_ssl_backend_data; +struct Curl_cfilter; + +CURLsslset Curl_init_sslset_nolock(curl_sslbackend id, const char *name, + const curl_ssl_backend ***avail); + +#ifndef MAX_PINNED_PUBKEY_SIZE +#define MAX_PINNED_PUBKEY_SIZE 1048576 /* 1MB */ +#endif + +#ifndef CURL_SHA256_DIGEST_LENGTH +#define CURL_SHA256_DIGEST_LENGTH 32 /* fixed size */ +#endif + +curl_sslbackend Curl_ssl_backend(void); + +/** + * Init ssl config for a new easy handle. + */ +void Curl_ssl_easy_config_init(struct Curl_easy *data); + +/** + * Init the `data->set.ssl` and `data->set.proxy_ssl` for + * connection matching use. + */ +CURLcode Curl_ssl_easy_config_complete(struct Curl_easy *data); + +/** + * Init SSL configs (main + proxy) for a new connection from the easy handle. + */ +CURLcode Curl_ssl_conn_config_init(struct Curl_easy *data, + struct connectdata *conn); + +/** + * Free allocated resources in SSL configs (main + proxy) for + * the given connection. + */ +void Curl_ssl_conn_config_cleanup(struct connectdata *conn); + +/** + * Return TRUE iff SSL configuration from `conn` is functionally the + * same as the one on `candidate`. + * @param proxy match the proxy SSL config or the main one + */ +bool Curl_ssl_conn_config_match(struct Curl_easy *data, + struct connectdata *candidate, + bool proxy); + +/* Update certain connection SSL config flags after they have + * been changed on the easy handle. Will work for `verifypeer`, + * `verifyhost` and `verifystatus`. */ +void Curl_ssl_conn_config_update(struct Curl_easy *data, bool for_proxy); + +/** + * Init SSL peer information for filter. Can be called repeatedly. + */ +CURLcode Curl_ssl_peer_init(struct ssl_peer *peer, + struct Curl_cfilter *cf, int transport); +/** + * Free all allocated data and reset peer information. + */ +void Curl_ssl_peer_cleanup(struct ssl_peer *peer); + +#ifdef USE_SSL +int Curl_ssl_init(void); +void Curl_ssl_cleanup(void); +/* tell the SSL stuff to close down all open information regarding + connections (and thus session ID caching etc) */ +void Curl_ssl_close_all(struct Curl_easy *data); +CURLcode Curl_ssl_set_engine(struct Curl_easy *data, const char *engine); +/* Sets engine as default for all SSL operations */ +CURLcode Curl_ssl_set_engine_default(struct Curl_easy *data); +struct curl_slist *Curl_ssl_engines_list(struct Curl_easy *data); + +/* init the SSL session ID cache */ +CURLcode Curl_ssl_initsessions(struct Curl_easy *, size_t); +void Curl_ssl_version(char *buffer, size_t size); + +/* Certificate information list handling. */ + +void Curl_ssl_free_certinfo(struct Curl_easy *data); +CURLcode Curl_ssl_init_certinfo(struct Curl_easy *data, int num); +CURLcode Curl_ssl_push_certinfo_len(struct Curl_easy *data, int certnum, + const char *label, const char *value, + size_t valuelen); +CURLcode Curl_ssl_push_certinfo(struct Curl_easy *data, int certnum, + const char *label, const char *value); + +/* Functions to be used by SSL library adaptation functions */ + +/* Lock session cache mutex. + * Call this before calling other Curl_ssl_*session* functions + * Caller should unlock this mutex as soon as possible, as it may block + * other SSL connection from making progress. + * The purpose of explicitly locking SSL session cache data is to allow + * individual SSL engines to manage session lifetime in their specific way. + */ +void Curl_ssl_sessionid_lock(struct Curl_easy *data); + +/* Unlock session cache mutex */ +void Curl_ssl_sessionid_unlock(struct Curl_easy *data); + +/* Kill a single session ID entry in the cache + * Sessionid mutex must be locked (see Curl_ssl_sessionid_lock). + * This will call engine-specific curlssl_session_free function, which must + * take sessionid object ownership from sessionid cache + * (e.g. decrement refcount). + */ +void Curl_ssl_kill_session(struct Curl_ssl_session *session); +/* delete a session from the cache + * Sessionid mutex must be locked (see Curl_ssl_sessionid_lock). + * This will call engine-specific curlssl_session_free function, which must + * take sessionid object ownership from sessionid cache + * (e.g. decrement refcount). + */ +void Curl_ssl_delsessionid(struct Curl_easy *data, void *ssl_sessionid); + +/* get N random bytes into the buffer */ +CURLcode Curl_ssl_random(struct Curl_easy *data, unsigned char *buffer, + size_t length); +/* Check pinned public key. */ +CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data, + const char *pinnedpubkey, + const unsigned char *pubkey, size_t pubkeylen); + +bool Curl_ssl_cert_status_request(void); + +bool Curl_ssl_false_start(struct Curl_easy *data); + +void Curl_free_multi_ssl_backend_data(struct multi_ssl_backend_data *mbackend); + +#define SSL_SHUTDOWN_TIMEOUT 10000 /* ms */ + +CURLcode Curl_ssl_cfilter_add(struct Curl_easy *data, + struct connectdata *conn, + int sockindex); + +CURLcode Curl_cf_ssl_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data); + +CURLcode Curl_ssl_cfilter_remove(struct Curl_easy *data, + int sockindex); + +#ifndef CURL_DISABLE_PROXY +CURLcode Curl_cf_ssl_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data); +#endif /* !CURL_DISABLE_PROXY */ + +/** + * True iff the underlying SSL implementation supports the option. + * Option is one of the defined SSLSUPP_* values. + * `data` maybe NULL for the features of the default implementation. + */ +bool Curl_ssl_supports(struct Curl_easy *data, int ssl_option); + +/** + * Get the internal ssl instance (like OpenSSL's SSL*) from the filter + * chain at `sockindex` of type specified by `info`. + * For `n` == 0, the first active (top down) instance is returned. + * 1 gives the second active, etc. + * NULL is returned when no active SSL filter is present. + */ +void *Curl_ssl_get_internals(struct Curl_easy *data, int sockindex, + CURLINFO info, int n); + +/** + * Get the ssl_config_data in `data` that is relevant for cfilter `cf`. + */ +struct ssl_config_data *Curl_ssl_cf_get_config(struct Curl_cfilter *cf, + struct Curl_easy *data); + +/** + * Get the primary config relevant for the filter from its connection. + */ +struct ssl_primary_config * + Curl_ssl_cf_get_primary_config(struct Curl_cfilter *cf); + +extern struct Curl_cftype Curl_cft_ssl; +#ifndef CURL_DISABLE_PROXY +extern struct Curl_cftype Curl_cft_ssl_proxy; +#endif + +#else /* if not USE_SSL */ + +/* When SSL support is not present, just define away these function calls */ +#define Curl_ssl_init() 1 +#define Curl_ssl_cleanup() Curl_nop_stmt +#define Curl_ssl_close_all(x) Curl_nop_stmt +#define Curl_ssl_set_engine(x,y) CURLE_NOT_BUILT_IN +#define Curl_ssl_set_engine_default(x) CURLE_NOT_BUILT_IN +#define Curl_ssl_engines_list(x) NULL +#define Curl_ssl_initsessions(x,y) CURLE_OK +#define Curl_ssl_free_certinfo(x) Curl_nop_stmt +#define Curl_ssl_kill_session(x) Curl_nop_stmt +#define Curl_ssl_random(x,y,z) ((void)x, CURLE_NOT_BUILT_IN) +#define Curl_ssl_cert_status_request() FALSE +#define Curl_ssl_false_start(a) FALSE +#define Curl_ssl_get_internals(a,b,c,d) NULL +#define Curl_ssl_supports(a,b) FALSE +#define Curl_ssl_cfilter_add(a,b,c) CURLE_NOT_BUILT_IN +#define Curl_ssl_cfilter_remove(a,b) CURLE_OK +#define Curl_ssl_cf_get_config(a,b) NULL +#define Curl_ssl_cf_get_primary_config(a) NULL +#endif + +#endif /* HEADER_CURL_VTLS_H */ diff --git a/third_party/curl/lib/vtls/vtls_int.h b/third_party/curl/lib/vtls/vtls_int.h new file mode 100644 index 0000000..5259bab --- /dev/null +++ b/third_party/curl/lib/vtls/vtls_int.h @@ -0,0 +1,209 @@ +#ifndef HEADER_CURL_VTLS_INT_H +#define HEADER_CURL_VTLS_INT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "cfilters.h" +#include "urldata.h" + +#ifdef USE_SSL + +/* see https://www.iana.org/assignments/tls-extensiontype-values/ */ +#define ALPN_HTTP_1_1_LENGTH 8 +#define ALPN_HTTP_1_1 "http/1.1" +#define ALPN_H2_LENGTH 2 +#define ALPN_H2 "h2" +#define ALPN_H3_LENGTH 2 +#define ALPN_H3 "h3" + +/* conservative sizes on the ALPN entries and count we are handling, + * we can increase these if we ever feel the need or have to accommodate + * ALPN strings from the "outside". */ +#define ALPN_NAME_MAX 10 +#define ALPN_ENTRIES_MAX 3 +#define ALPN_PROTO_BUF_MAX (ALPN_ENTRIES_MAX * (ALPN_NAME_MAX + 1)) + +struct alpn_spec { + const char entries[ALPN_ENTRIES_MAX][ALPN_NAME_MAX]; + size_t count; /* number of entries */ +}; + +struct alpn_proto_buf { + unsigned char data[ALPN_PROTO_BUF_MAX]; + int len; +}; + +CURLcode Curl_alpn_to_proto_buf(struct alpn_proto_buf *buf, + const struct alpn_spec *spec); +CURLcode Curl_alpn_to_proto_str(struct alpn_proto_buf *buf, + const struct alpn_spec *spec); + +CURLcode Curl_alpn_set_negotiated(struct Curl_cfilter *cf, + struct Curl_easy *data, + const unsigned char *proto, + size_t proto_len); + +/* Information in each SSL cfilter context: cf->ctx */ +struct ssl_connect_data { + ssl_connection_state state; + ssl_connect_state connecting_state; + struct ssl_peer peer; + const struct alpn_spec *alpn; /* ALPN to use or NULL for none */ + void *backend; /* vtls backend specific props */ + struct cf_call_data call_data; /* data handle used in current call */ + struct curltime handshake_done; /* time when handshake finished */ + BIT(use_alpn); /* if ALPN shall be used in handshake */ + BIT(peer_closed); /* peer has closed connection */ +}; + + +#undef CF_CTX_CALL_DATA +#define CF_CTX_CALL_DATA(cf) \ + ((struct ssl_connect_data *)(cf)->ctx)->call_data + + +/* Definitions for SSL Implementations */ + +struct Curl_ssl { + /* + * This *must* be the first entry to allow returning the list of available + * backends in curl_global_sslset(). + */ + curl_ssl_backend info; + unsigned int supports; /* bitfield, see above */ + size_t sizeof_ssl_backend_data; + + int (*init)(void); + void (*cleanup)(void); + + size_t (*version)(char *buffer, size_t size); + int (*check_cxn)(struct Curl_cfilter *cf, struct Curl_easy *data); + int (*shut_down)(struct Curl_cfilter *cf, + struct Curl_easy *data); + bool (*data_pending)(struct Curl_cfilter *cf, + const struct Curl_easy *data); + + /* return 0 if a find random is filled in */ + CURLcode (*random)(struct Curl_easy *data, unsigned char *entropy, + size_t length); + bool (*cert_status_request)(void); + + CURLcode (*connect_blocking)(struct Curl_cfilter *cf, + struct Curl_easy *data); + CURLcode (*connect_nonblocking)(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done); + + /* During handshake, adjust the pollset to include the socket + * for POLLOUT or POLLIN as needed. + * Mandatory. */ + void (*adjust_pollset)(struct Curl_cfilter *cf, struct Curl_easy *data, + struct easy_pollset *ps); + void *(*get_internals)(struct ssl_connect_data *connssl, CURLINFO info); + void (*close)(struct Curl_cfilter *cf, struct Curl_easy *data); + void (*close_all)(struct Curl_easy *data); + + CURLcode (*set_engine)(struct Curl_easy *data, const char *engine); + CURLcode (*set_engine_default)(struct Curl_easy *data); + struct curl_slist *(*engines_list)(struct Curl_easy *data); + + bool (*false_start)(void); + CURLcode (*sha256sum)(const unsigned char *input, size_t inputlen, + unsigned char *sha256sum, size_t sha256sumlen); + + bool (*attach_data)(struct Curl_cfilter *cf, struct Curl_easy *data); + void (*detach_data)(struct Curl_cfilter *cf, struct Curl_easy *data); + + void (*free_multi_ssl_backend_data)(struct multi_ssl_backend_data *mbackend); + + ssize_t (*recv_plain)(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, CURLcode *code); + ssize_t (*send_plain)(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *mem, size_t len, CURLcode *code); + +}; + +extern const struct Curl_ssl *Curl_ssl; + + +int Curl_none_init(void); +void Curl_none_cleanup(void); +int Curl_none_shutdown(struct Curl_cfilter *cf, struct Curl_easy *data); +int Curl_none_check_cxn(struct Curl_cfilter *cf, struct Curl_easy *data); +CURLcode Curl_none_random(struct Curl_easy *data, unsigned char *entropy, + size_t length); +void Curl_none_close_all(struct Curl_easy *data); +void Curl_none_session_free(void *ptr); +bool Curl_none_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data); +bool Curl_none_cert_status_request(void); +CURLcode Curl_none_set_engine(struct Curl_easy *data, const char *engine); +CURLcode Curl_none_set_engine_default(struct Curl_easy *data); +struct curl_slist *Curl_none_engines_list(struct Curl_easy *data); +bool Curl_none_false_start(void); +void Curl_ssl_adjust_pollset(struct Curl_cfilter *cf, struct Curl_easy *data, + struct easy_pollset *ps); + +/** + * Get the SSL filter below the given one or NULL if there is none. + */ +bool Curl_ssl_cf_is_proxy(struct Curl_cfilter *cf); + +/* extract a session ID + * Sessionid mutex must be locked (see Curl_ssl_sessionid_lock). + * Caller must make sure that the ownership of returned sessionid object + * is properly taken (e.g. its refcount is incremented + * under sessionid mutex). + */ +bool Curl_ssl_getsessionid(struct Curl_cfilter *cf, + struct Curl_easy *data, + const struct ssl_peer *peer, + void **ssl_sessionid, + size_t *idsize); /* set 0 if unknown */ +/* add a new session ID + * Sessionid mutex must be locked (see Curl_ssl_sessionid_lock). + * Caller must ensure that it has properly shared ownership of this sessionid + * object with cache (e.g. incrementing refcount on success) + * Call takes ownership of `ssl_sessionid`, using `sessionid_free_cb` + * to destroy it in case of failure or later removal. + */ +CURLcode Curl_ssl_addsessionid(struct Curl_cfilter *cf, + struct Curl_easy *data, + const struct ssl_peer *peer, + void *ssl_sessionid, + size_t idsize, + Curl_ssl_sessionid_dtor *sessionid_free_cb); + +#include "openssl.h" /* OpenSSL versions */ +#include "gtls.h" /* GnuTLS versions */ +#include "wolfssl.h" /* wolfSSL versions */ +#include "schannel.h" /* Schannel SSPI version */ +#include "sectransp.h" /* SecureTransport (Darwin) version */ +#include "mbedtls.h" /* mbedTLS versions */ +#include "bearssl.h" /* BearSSL versions */ +#include "rustls.h" /* rustls versions */ + +#endif /* USE_SSL */ + +#endif /* HEADER_CURL_VTLS_INT_H */ diff --git a/third_party/curl/lib/vtls/wolfssl.c b/third_party/curl/lib/vtls/wolfssl.c new file mode 100644 index 0000000..2c92f56 --- /dev/null +++ b/third_party/curl/lib/vtls/wolfssl.c @@ -0,0 +1,1526 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Source file for all wolfSSL specific code for the TLS/SSL layer. No code + * but vtls.c should ever call or use these functions. + * + */ + +#include "curl_setup.h" + +#ifdef USE_WOLFSSL + +#define WOLFSSL_OPTIONS_IGNORE_SYS +#include +#include + +/* To determine what functions are available we rely on one or both of: + - the user's options.h generated by wolfSSL + - the symbols detected by curl's configure + Since they are markedly different from one another, and one or the other may + not be available, we do some checking below to bring things in sync. */ + +/* HAVE_ALPN is wolfSSL's build time symbol for enabling ALPN in options.h. */ +#ifndef HAVE_ALPN +#ifdef HAVE_WOLFSSL_USEALPN +#define HAVE_ALPN +#endif +#endif + +#include + +#include "urldata.h" +#include "sendf.h" +#include "inet_pton.h" +#include "vtls.h" +#include "vtls_int.h" +#include "keylog.h" +#include "parsedate.h" +#include "connect.h" /* for the connect timeout */ +#include "select.h" +#include "strcase.h" +#include "x509asn1.h" +#include "curl_printf.h" +#include "multiif.h" + +#include +#include +#include +#include "wolfssl.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +#ifdef USE_ECH +# include "curl_base64.h" +# define ECH_ENABLED(__data__) \ + (__data__->set.tls_ech && \ + !(__data__->set.tls_ech & CURLECH_DISABLE)\ + ) +#endif /* USE_ECH */ + +/* KEEP_PEER_CERT is a product of the presence of build time symbol + OPENSSL_EXTRA without NO_CERTS, depending on the version. KEEP_PEER_CERT is + in wolfSSL's settings.h, and the latter two are build time symbols in + options.h. */ +#ifndef KEEP_PEER_CERT +#if defined(HAVE_WOLFSSL_GET_PEER_CERTIFICATE) || \ + (defined(OPENSSL_EXTRA) && !defined(NO_CERTS)) +#define KEEP_PEER_CERT +#endif +#endif + +#if defined(HAVE_WOLFSSL_FULL_BIO) && HAVE_WOLFSSL_FULL_BIO +#define USE_BIO_CHAIN +#else +#undef USE_BIO_CHAIN +#endif + +struct wolfssl_ssl_backend_data { + WOLFSSL_CTX *ctx; + WOLFSSL *handle; + CURLcode io_result; /* result of last BIO cfilter operation */ +}; + +#ifdef OPENSSL_EXTRA +/* + * Availability note: + * The TLS 1.3 secret callback (wolfSSL_set_tls13_secret_cb) was added in + * WolfSSL 4.4.0, but requires the -DHAVE_SECRET_CALLBACK build option. If that + * option is not set, then TLS 1.3 will not be logged. + * For TLS 1.2 and before, we use wolfSSL_get_keys(). + * SSL_get_client_random and wolfSSL_get_keys require OPENSSL_EXTRA + * (--enable-opensslextra or --enable-all). + */ +#if defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13) +static int +wolfssl_tls13_secret_callback(SSL *ssl, int id, const unsigned char *secret, + int secretSz, void *ctx) +{ + const char *label; + unsigned char client_random[SSL3_RANDOM_SIZE]; + (void)ctx; + + if(!ssl || !Curl_tls_keylog_enabled()) { + return 0; + } + + switch(id) { + case CLIENT_EARLY_TRAFFIC_SECRET: + label = "CLIENT_EARLY_TRAFFIC_SECRET"; + break; + case CLIENT_HANDSHAKE_TRAFFIC_SECRET: + label = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"; + break; + case SERVER_HANDSHAKE_TRAFFIC_SECRET: + label = "SERVER_HANDSHAKE_TRAFFIC_SECRET"; + break; + case CLIENT_TRAFFIC_SECRET: + label = "CLIENT_TRAFFIC_SECRET_0"; + break; + case SERVER_TRAFFIC_SECRET: + label = "SERVER_TRAFFIC_SECRET_0"; + break; + case EARLY_EXPORTER_SECRET: + label = "EARLY_EXPORTER_SECRET"; + break; + case EXPORTER_SECRET: + label = "EXPORTER_SECRET"; + break; + default: + return 0; + } + + if(SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE) == 0) { + /* Should never happen as wolfSSL_KeepArrays() was called before. */ + return 0; + } + + Curl_tls_keylog_write(label, client_random, secret, secretSz); + return 0; +} +#endif /* defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13) */ + +static void +wolfssl_log_tls12_secret(SSL *ssl) +{ + unsigned char *ms, *sr, *cr; + unsigned int msLen, srLen, crLen, i, x = 0; + +#if LIBWOLFSSL_VERSION_HEX >= 0x0300d000 /* >= 3.13.0 */ + /* wolfSSL_GetVersion is available since 3.13, we use it instead of + * SSL_version since the latter relies on OPENSSL_ALL (--enable-opensslall or + * --enable-all). Failing to perform this check could result in an unusable + * key log line when TLS 1.3 is actually negotiated. */ + switch(wolfSSL_GetVersion(ssl)) { + case WOLFSSL_SSLV3: + case WOLFSSL_TLSV1: + case WOLFSSL_TLSV1_1: + case WOLFSSL_TLSV1_2: + break; + default: + /* TLS 1.3 does not use this mechanism, the "master secret" returned below + * is not directly usable. */ + return; + } +#endif + + if(wolfSSL_get_keys(ssl, &ms, &msLen, &sr, &srLen, &cr, &crLen) != + SSL_SUCCESS) { + return; + } + + /* Check for a missing master secret and skip logging. That can happen if + * curl rejects the server certificate and aborts the handshake. + */ + for(i = 0; i < msLen; i++) { + x |= ms[i]; + } + if(x == 0) { + return; + } + + Curl_tls_keylog_write("CLIENT_RANDOM", cr, ms, msLen); +} +#endif /* OPENSSL_EXTRA */ + +static int do_file_type(const char *type) +{ + if(!type || !type[0]) + return SSL_FILETYPE_PEM; + if(strcasecompare(type, "PEM")) + return SSL_FILETYPE_PEM; + if(strcasecompare(type, "DER")) + return SSL_FILETYPE_ASN1; + return -1; +} + +#ifdef HAVE_LIBOQS +struct group_name_map { + const word16 group; + const char *name; +}; + +static const struct group_name_map gnm[] = { + { WOLFSSL_KYBER_LEVEL1, "KYBER_LEVEL1" }, + { WOLFSSL_KYBER_LEVEL3, "KYBER_LEVEL3" }, + { WOLFSSL_KYBER_LEVEL5, "KYBER_LEVEL5" }, + { WOLFSSL_P256_KYBER_LEVEL1, "P256_KYBER_LEVEL1" }, + { WOLFSSL_P384_KYBER_LEVEL3, "P384_KYBER_LEVEL3" }, + { WOLFSSL_P521_KYBER_LEVEL5, "P521_KYBER_LEVEL5" }, + { 0, NULL } +}; +#endif + +#ifdef USE_BIO_CHAIN + +static int wolfssl_bio_cf_create(WOLFSSL_BIO *bio) +{ + wolfSSL_BIO_set_shutdown(bio, 1); + wolfSSL_BIO_set_data(bio, NULL); + return 1; +} + +static int wolfssl_bio_cf_destroy(WOLFSSL_BIO *bio) +{ + if(!bio) + return 0; + return 1; +} + +static long wolfssl_bio_cf_ctrl(WOLFSSL_BIO *bio, int cmd, long num, void *ptr) +{ + struct Curl_cfilter *cf = BIO_get_data(bio); + long ret = 1; + + (void)cf; + (void)ptr; + switch(cmd) { + case BIO_CTRL_GET_CLOSE: + ret = (long)wolfSSL_BIO_get_shutdown(bio); + break; + case BIO_CTRL_SET_CLOSE: + wolfSSL_BIO_set_shutdown(bio, (int)num); + break; + case BIO_CTRL_FLUSH: + /* we do no delayed writes, but if we ever would, this + * needs to trigger it. */ + ret = 1; + break; + case BIO_CTRL_DUP: + ret = 1; + break; +#ifdef BIO_CTRL_EOF + case BIO_CTRL_EOF: + /* EOF has been reached on input? */ + return (!cf->next || !cf->next->connected); +#endif + default: + ret = 0; + break; + } + return ret; +} + +static int wolfssl_bio_cf_out_write(WOLFSSL_BIO *bio, + const char *buf, int blen) +{ + struct Curl_cfilter *cf = wolfSSL_BIO_get_data(bio); + struct ssl_connect_data *connssl = cf->ctx; + struct wolfssl_ssl_backend_data *backend = + (struct wolfssl_ssl_backend_data *)connssl->backend; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + ssize_t nwritten; + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + nwritten = Curl_conn_cf_send(cf->next, data, buf, blen, &result); + backend->io_result = result; + CURL_TRC_CF(data, cf, "bio_write(len=%d) -> %zd, %d", + blen, nwritten, result); + wolfSSL_BIO_clear_retry_flags(bio); + if(nwritten < 0 && CURLE_AGAIN == result) + BIO_set_retry_write(bio); + return (int)nwritten; +} + +static int wolfssl_bio_cf_in_read(WOLFSSL_BIO *bio, char *buf, int blen) +{ + struct Curl_cfilter *cf = wolfSSL_BIO_get_data(bio); + struct ssl_connect_data *connssl = cf->ctx; + struct wolfssl_ssl_backend_data *backend = + (struct wolfssl_ssl_backend_data *)connssl->backend; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + ssize_t nread; + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + /* OpenSSL catches this case, so should we. */ + if(!buf) + return 0; + + nread = Curl_conn_cf_recv(cf->next, data, buf, blen, &result); + backend->io_result = result; + CURL_TRC_CF(data, cf, "bio_read(len=%d) -> %zd, %d", blen, nread, result); + wolfSSL_BIO_clear_retry_flags(bio); + if(nread < 0 && CURLE_AGAIN == result) + BIO_set_retry_read(bio); + else if(nread == 0) + connssl->peer_closed = TRUE; + return (int)nread; +} + +static WOLFSSL_BIO_METHOD *wolfssl_bio_cf_method = NULL; + +static void wolfssl_bio_cf_init_methods(void) +{ + wolfssl_bio_cf_method = wolfSSL_BIO_meth_new(BIO_TYPE_MEM, "wolfSSL CF BIO"); + wolfSSL_BIO_meth_set_write(wolfssl_bio_cf_method, &wolfssl_bio_cf_out_write); + wolfSSL_BIO_meth_set_read(wolfssl_bio_cf_method, &wolfssl_bio_cf_in_read); + wolfSSL_BIO_meth_set_ctrl(wolfssl_bio_cf_method, &wolfssl_bio_cf_ctrl); + wolfSSL_BIO_meth_set_create(wolfssl_bio_cf_method, &wolfssl_bio_cf_create); + wolfSSL_BIO_meth_set_destroy(wolfssl_bio_cf_method, &wolfssl_bio_cf_destroy); +} + +static void wolfssl_bio_cf_free_methods(void) +{ + wolfSSL_BIO_meth_free(wolfssl_bio_cf_method); +} + +#else /* USE_BIO_CHAIN */ + +#define wolfssl_bio_cf_init_methods() Curl_nop_stmt +#define wolfssl_bio_cf_free_methods() Curl_nop_stmt + +#endif /* !USE_BIO_CHAIN */ + +/* + * This function loads all the client/CA certificates and CRLs. Setup the TLS + * layer and do all necessary magic. + */ +static CURLcode +wolfssl_connect_step1(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + char *ciphers, *curves; + struct ssl_connect_data *connssl = cf->ctx; + struct wolfssl_ssl_backend_data *backend = + (struct wolfssl_ssl_backend_data *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + const struct curl_blob *ca_info_blob = conn_config->ca_info_blob; + const struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + const char * const ssl_cafile = + /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */ + (ca_info_blob ? NULL : conn_config->CAfile); + const char * const ssl_capath = conn_config->CApath; + WOLFSSL_METHOD* req_method = NULL; +#ifdef HAVE_LIBOQS + word16 oqsAlg = 0; + size_t idx = 0; +#endif +#ifdef HAVE_SNI + bool sni = FALSE; +#define use_sni(x) sni = (x) +#else +#define use_sni(x) Curl_nop_stmt +#endif + bool imported_native_ca = false; + bool imported_ca_info_blob = false; + + DEBUGASSERT(backend); + + if(connssl->state == ssl_connection_complete) + return CURLE_OK; + + if(conn_config->version_max != CURL_SSLVERSION_MAX_NONE) { + failf(data, "wolfSSL does not support to set maximum SSL/TLS version"); + return CURLE_SSL_CONNECT_ERROR; + } + + /* check to see if we've been told to use an explicit SSL/TLS version */ + switch(conn_config->version) { + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1: +#if LIBWOLFSSL_VERSION_HEX >= 0x03003000 /* >= 3.3.0 */ + /* minimum protocol version is set later after the CTX object is created */ + req_method = SSLv23_client_method(); +#else + infof(data, "wolfSSL <3.3.0 cannot be configured to use TLS 1.0-1.2, " + "TLS 1.0 is used exclusively"); + req_method = TLSv1_client_method(); +#endif + use_sni(TRUE); + break; + case CURL_SSLVERSION_TLSv1_0: +#if defined(WOLFSSL_ALLOW_TLSV10) && !defined(NO_OLD_TLS) + req_method = TLSv1_client_method(); + use_sni(TRUE); + break; +#else + failf(data, "wolfSSL does not support TLS 1.0"); + return CURLE_NOT_BUILT_IN; +#endif + case CURL_SSLVERSION_TLSv1_1: +#ifndef NO_OLD_TLS + req_method = TLSv1_1_client_method(); + use_sni(TRUE); +#else + failf(data, "wolfSSL does not support TLS 1.1"); + return CURLE_NOT_BUILT_IN; +#endif + break; + case CURL_SSLVERSION_TLSv1_2: +#ifndef WOLFSSL_NO_TLS12 + req_method = TLSv1_2_client_method(); + use_sni(TRUE); +#else + failf(data, "wolfSSL does not support TLS 1.2"); + return CURLE_NOT_BUILT_IN; +#endif + break; + case CURL_SSLVERSION_TLSv1_3: +#ifdef WOLFSSL_TLS13 + req_method = wolfTLSv1_3_client_method(); + use_sni(TRUE); + break; +#else + failf(data, "wolfSSL: TLS 1.3 is not yet supported"); + return CURLE_SSL_CONNECT_ERROR; +#endif + default: + failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); + return CURLE_SSL_CONNECT_ERROR; + } + + if(!req_method) { + failf(data, "SSL: couldn't create a method"); + return CURLE_OUT_OF_MEMORY; + } + + if(backend->ctx) + wolfSSL_CTX_free(backend->ctx); + backend->ctx = wolfSSL_CTX_new(req_method); + + if(!backend->ctx) { + failf(data, "SSL: couldn't create a context"); + return CURLE_OUT_OF_MEMORY; + } + + switch(conn_config->version) { + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1: +#if LIBWOLFSSL_VERSION_HEX > 0x03004006 /* > 3.4.6 */ + /* Versions 3.3.0 to 3.4.6 we know the minimum protocol version is + * whatever minimum version of TLS was built in and at least TLS 1.0. For + * later library versions that could change (eg TLS 1.0 built in but + * defaults to TLS 1.1) so we have this short circuit evaluation to find + * the minimum supported TLS version. + */ + if((wolfSSL_CTX_SetMinVersion(backend->ctx, WOLFSSL_TLSV1) != 1) && + (wolfSSL_CTX_SetMinVersion(backend->ctx, WOLFSSL_TLSV1_1) != 1) && + (wolfSSL_CTX_SetMinVersion(backend->ctx, WOLFSSL_TLSV1_2) != 1) +#ifdef WOLFSSL_TLS13 + && (wolfSSL_CTX_SetMinVersion(backend->ctx, WOLFSSL_TLSV1_3) != 1) +#endif + ) { + failf(data, "SSL: couldn't set the minimum protocol version"); + return CURLE_SSL_CONNECT_ERROR; + } +#endif + FALLTHROUGH(); + default: + break; + } + + ciphers = conn_config->cipher_list; + if(ciphers) { + if(!SSL_CTX_set_cipher_list(backend->ctx, ciphers)) { + failf(data, "failed setting cipher list: %s", ciphers); + return CURLE_SSL_CIPHER; + } + infof(data, "Cipher selection: %s", ciphers); + } + + curves = conn_config->curves; + if(curves) { + +#ifdef HAVE_LIBOQS + for(idx = 0; gnm[idx].name != NULL; idx++) { + if(strncmp(curves, gnm[idx].name, strlen(gnm[idx].name)) == 0) { + oqsAlg = gnm[idx].group; + break; + } + } + + if(oqsAlg == 0) +#endif + { + if(!SSL_CTX_set1_curves_list(backend->ctx, curves)) { + failf(data, "failed setting curves list: '%s'", curves); + return CURLE_SSL_CIPHER; + } + } + } + +#if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SYS_CA_CERTS) + /* load native CA certificates */ + if(ssl_config->native_ca_store) { + if(wolfSSL_CTX_load_system_CA_certs(backend->ctx) != WOLFSSL_SUCCESS) { + infof(data, "error importing native CA store, continuing anyway"); + } + else { + imported_native_ca = true; + infof(data, "successfully imported native CA store"); + } + } +#endif /* !NO_FILESYSTEM */ + + /* load certificate blob */ + if(ca_info_blob) { + if(wolfSSL_CTX_load_verify_buffer(backend->ctx, ca_info_blob->data, + ca_info_blob->len, + SSL_FILETYPE_PEM) != SSL_SUCCESS) { + if(imported_native_ca) { + infof(data, "error importing CA certificate blob, continuing anyway"); + } + else { + failf(data, "error importing CA certificate blob"); + return CURLE_SSL_CACERT_BADFILE; + } + } + else { + imported_ca_info_blob = true; + infof(data, "successfully imported CA certificate blob"); + } + } + +#ifndef NO_FILESYSTEM + /* load trusted cacert from file if not blob */ + if(ssl_cafile || ssl_capath) { + int rc = + wolfSSL_CTX_load_verify_locations_ex(backend->ctx, + ssl_cafile, + ssl_capath, + WOLFSSL_LOAD_FLAG_IGNORE_ERR); + if(SSL_SUCCESS != rc) { + if(conn_config->verifypeer && !imported_ca_info_blob && + !imported_native_ca) { + /* Fail if we insist on successfully verifying the server. */ + failf(data, "error setting certificate verify locations:" + " CAfile: %s CApath: %s", + ssl_cafile ? ssl_cafile : "none", + ssl_capath ? ssl_capath : "none"); + return CURLE_SSL_CACERT_BADFILE; + } + else { + /* Just continue with a warning if no strict certificate + verification is required. */ + infof(data, "error setting certificate verify locations," + " continuing anyway:"); + } + } + else { + /* Everything is fine. */ + infof(data, "successfully set certificate verify locations:"); + } + infof(data, " CAfile: %s", ssl_cafile ? ssl_cafile : "none"); + infof(data, " CApath: %s", ssl_capath ? ssl_capath : "none"); + } + + /* Load the client certificate, and private key */ + if(ssl_config->primary.clientcert && ssl_config->key) { + int file_type = do_file_type(ssl_config->cert_type); + + if(file_type == WOLFSSL_FILETYPE_PEM) { + if(wolfSSL_CTX_use_certificate_chain_file(backend->ctx, + ssl_config->primary.clientcert) + != 1) { + failf(data, "unable to use client certificate"); + return CURLE_SSL_CONNECT_ERROR; + } + } + else if(file_type == WOLFSSL_FILETYPE_ASN1) { + if(wolfSSL_CTX_use_certificate_file(backend->ctx, + ssl_config->primary.clientcert, + file_type) != 1) { + failf(data, "unable to use client certificate"); + return CURLE_SSL_CONNECT_ERROR; + } + } + else { + failf(data, "unknown cert type"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + file_type = do_file_type(ssl_config->key_type); + if(wolfSSL_CTX_use_PrivateKey_file(backend->ctx, ssl_config->key, + file_type) != 1) { + failf(data, "unable to set private key"); + return CURLE_SSL_CONNECT_ERROR; + } + } +#endif /* !NO_FILESYSTEM */ + + /* SSL always tries to verify the peer, this only says whether it should + * fail to connect if the verification fails, or if it should continue + * anyway. In the latter case the result of the verification is checked with + * SSL_get_verify_result() below. */ + wolfSSL_CTX_set_verify(backend->ctx, + conn_config->verifypeer?SSL_VERIFY_PEER: + SSL_VERIFY_NONE, NULL); + +#ifdef HAVE_SNI + if(sni && connssl->peer.sni) { + size_t sni_len = strlen(connssl->peer.sni); + if((sni_len < USHRT_MAX)) { + if(wolfSSL_CTX_UseSNI(backend->ctx, WOLFSSL_SNI_HOST_NAME, + connssl->peer.sni, + (unsigned short)sni_len) != 1) { + failf(data, "Failed to set SNI"); + return CURLE_SSL_CONNECT_ERROR; + } + } + } +#endif + + /* give application a chance to interfere with SSL set up. */ + if(data->set.ssl.fsslctx) { + CURLcode result = (*data->set.ssl.fsslctx)(data, backend->ctx, + data->set.ssl.fsslctxp); + if(result) { + failf(data, "error signaled by ssl ctx callback"); + return result; + } + } +#ifdef NO_FILESYSTEM + else if(conn_config->verifypeer) { + failf(data, "SSL: Certificates can't be loaded because wolfSSL was built" + " with \"no filesystem\". Either disable peer verification" + " (insecure) or if you are building an application with libcurl you" + " can load certificates via CURLOPT_SSL_CTX_FUNCTION."); + return CURLE_SSL_CONNECT_ERROR; + } +#endif + + /* Let's make an SSL structure */ + if(backend->handle) + wolfSSL_free(backend->handle); + backend->handle = wolfSSL_new(backend->ctx); + if(!backend->handle) { + failf(data, "SSL: couldn't create a handle"); + return CURLE_OUT_OF_MEMORY; + } + +#ifdef HAVE_LIBOQS + if(oqsAlg) { + if(wolfSSL_UseKeyShare(backend->handle, oqsAlg) != WOLFSSL_SUCCESS) { + failf(data, "unable to use oqs KEM"); + } + } +#endif + +#ifdef HAVE_ALPN + if(connssl->alpn) { + struct alpn_proto_buf proto; + CURLcode result; + + result = Curl_alpn_to_proto_str(&proto, connssl->alpn); + if(result || + wolfSSL_UseALPN(backend->handle, (char *)proto.data, proto.len, + WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) != SSL_SUCCESS) { + failf(data, "SSL: failed setting ALPN protocols"); + return CURLE_SSL_CONNECT_ERROR; + } + infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data); + } +#endif /* HAVE_ALPN */ + +#ifdef OPENSSL_EXTRA + if(Curl_tls_keylog_enabled()) { + /* Ensure the Client Random is preserved. */ + wolfSSL_KeepArrays(backend->handle); +#if defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13) + wolfSSL_set_tls13_secret_cb(backend->handle, + wolfssl_tls13_secret_callback, NULL); +#endif + } +#endif /* OPENSSL_EXTRA */ + +#ifdef HAVE_SECURE_RENEGOTIATION + if(wolfSSL_UseSecureRenegotiation(backend->handle) != SSL_SUCCESS) { + failf(data, "SSL: failed setting secure renegotiation"); + return CURLE_SSL_CONNECT_ERROR; + } +#endif /* HAVE_SECURE_RENEGOTIATION */ + + /* Check if there's a cached ID we can/should use here! */ + if(ssl_config->primary.sessionid) { + void *ssl_sessionid = NULL; + + Curl_ssl_sessionid_lock(data); + if(!Curl_ssl_getsessionid(cf, data, &connssl->peer, + &ssl_sessionid, NULL)) { + /* we got a session id, use it! */ + if(!SSL_set_session(backend->handle, ssl_sessionid)) { + Curl_ssl_delsessionid(data, ssl_sessionid); + infof(data, "Can't use session ID, going on without"); + } + else + infof(data, "SSL reusing session ID"); + } + Curl_ssl_sessionid_unlock(data); + } + +#ifdef USE_ECH + if(ECH_ENABLED(data)) { + int trying_ech_now = 0; + + if(data->set.str[STRING_ECH_PUBLIC]) { + infof(data, "ECH: outername not (yet) supported with WolfSSL"); + return CURLE_SSL_CONNECT_ERROR; + } + if(data->set.tls_ech == CURLECH_GREASE) { + infof(data, "ECH: GREASE'd ECH not yet supported for wolfSSL"); + return CURLE_SSL_CONNECT_ERROR; + } + if(data->set.tls_ech & CURLECH_CLA_CFG + && data->set.str[STRING_ECH_CONFIG]) { + char *b64val = data->set.str[STRING_ECH_CONFIG]; + word32 b64len = 0; + + b64len = (word32) strlen(b64val); + if(b64len + && wolfSSL_SetEchConfigsBase64(backend->handle, b64val, b64len) + != WOLFSSL_SUCCESS) { + if(data->set.tls_ech & CURLECH_HARD) + return CURLE_SSL_CONNECT_ERROR; + } + else { + trying_ech_now = 1; + infof(data, "ECH: ECHConfig from command line"); + } + } + else { + struct Curl_dns_entry *dns = NULL; + + dns = Curl_fetch_addr(data, connssl->peer.hostname, connssl->peer.port); + if(!dns) { + infof(data, "ECH: requested but no DNS info available"); + if(data->set.tls_ech & CURLECH_HARD) + return CURLE_SSL_CONNECT_ERROR; + } + else { + struct Curl_https_rrinfo *rinfo = NULL; + + rinfo = dns->hinfo; + if(rinfo && rinfo->echconfiglist) { + unsigned char *ecl = rinfo->echconfiglist; + size_t elen = rinfo->echconfiglist_len; + + infof(data, "ECH: ECHConfig from DoH HTTPS RR"); + if(wolfSSL_SetEchConfigs(backend->handle, ecl, (word32) elen) != + WOLFSSL_SUCCESS) { + infof(data, "ECH: wolfSSL_SetEchConfigs failed"); + if(data->set.tls_ech & CURLECH_HARD) + return CURLE_SSL_CONNECT_ERROR; + } + else { + trying_ech_now = 1; + infof(data, "ECH: imported ECHConfigList of length %ld", elen); + } + } + else { + infof(data, "ECH: requested but no ECHConfig available"); + if(data->set.tls_ech & CURLECH_HARD) + return CURLE_SSL_CONNECT_ERROR; + } + Curl_resolv_unlock(data, dns); + } + } + + if(trying_ech_now + && SSL_set_min_proto_version(backend->handle, TLS1_3_VERSION) != 1) { + infof(data, "ECH: Can't force TLSv1.3 [ERROR]"); + return CURLE_SSL_CONNECT_ERROR; + } + + } +#endif /* USE_ECH */ + +#ifdef USE_BIO_CHAIN + { + WOLFSSL_BIO *bio; + + bio = BIO_new(wolfssl_bio_cf_method); + if(!bio) + return CURLE_OUT_OF_MEMORY; + + wolfSSL_BIO_set_data(bio, cf); + wolfSSL_set_bio(backend->handle, bio, bio); + } +#else /* USE_BIO_CHAIN */ + /* pass the raw socket into the SSL layer */ + if(!wolfSSL_set_fd(backend->handle, + (int)Curl_conn_cf_get_socket(cf, data))) { + failf(data, "SSL: SSL_set_fd failed"); + return CURLE_SSL_CONNECT_ERROR; + } +#endif /* !USE_BIO_CHAIN */ + + connssl->connecting_state = ssl_connect_2; + return CURLE_OK; +} + + +static CURLcode +wolfssl_connect_step2(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + int ret = -1; + struct ssl_connect_data *connssl = cf->ctx; + struct wolfssl_ssl_backend_data *backend = + (struct wolfssl_ssl_backend_data *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); +#ifndef CURL_DISABLE_PROXY + const char * const pinnedpubkey = Curl_ssl_cf_is_proxy(cf)? + data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY]: + data->set.str[STRING_SSL_PINNEDPUBLICKEY]; +#else + const char * const pinnedpubkey = data->set.str[STRING_SSL_PINNEDPUBLICKEY]; +#endif + + DEBUGASSERT(backend); + + wolfSSL_ERR_clear_error(); + + /* Enable RFC2818 checks */ + if(conn_config->verifyhost) { + char *snihost = connssl->peer.sni? + connssl->peer.sni : connssl->peer.hostname; + if(wolfSSL_check_domain_name(backend->handle, snihost) == SSL_FAILURE) + return CURLE_SSL_CONNECT_ERROR; + } + + ret = wolfSSL_connect(backend->handle); + +#ifdef OPENSSL_EXTRA + if(Curl_tls_keylog_enabled()) { + /* If key logging is enabled, wait for the handshake to complete and then + * proceed with logging secrets (for TLS 1.2 or older). + * + * During the handshake (ret==-1), wolfSSL_want_read() is true as it waits + * for the server response. At that point the master secret is not yet + * available, so we must not try to read it. + * To log the secret on completion with a handshake failure, detect + * completion via the observation that there is nothing to read or write. + * Note that OpenSSL SSL_want_read() is always true here. If wolfSSL ever + * changes, the worst case is that no key is logged on error. + */ + if(ret == SSL_SUCCESS || + (!wolfSSL_want_read(backend->handle) && + !wolfSSL_want_write(backend->handle))) { + wolfssl_log_tls12_secret(backend->handle); + /* Client Random and master secrets are no longer needed, erase these. + * Ignored while the handshake is still in progress. */ + wolfSSL_FreeArrays(backend->handle); + } + } +#endif /* OPENSSL_EXTRA */ + + if(ret != 1) { + char error_buffer[WOLFSSL_MAX_ERROR_SZ]; + int detail = wolfSSL_get_error(backend->handle, ret); + + if(SSL_ERROR_WANT_READ == detail) { + connssl->connecting_state = ssl_connect_2_reading; + return CURLE_OK; + } + else if(SSL_ERROR_WANT_WRITE == detail) { + connssl->connecting_state = ssl_connect_2_writing; + return CURLE_OK; + } + /* There is no easy way to override only the CN matching. + * This will enable the override of both mismatching SubjectAltNames + * as also mismatching CN fields */ + else if(DOMAIN_NAME_MISMATCH == detail) { +#if 1 + failf(data, " subject alt name(s) or common name do not match \"%s\"", + connssl->peer.dispname); + return CURLE_PEER_FAILED_VERIFICATION; +#else + /* When the wolfssl_check_domain_name() is used and you desire to + * continue on a DOMAIN_NAME_MISMATCH, i.e. 'ssl_config.verifyhost + * == 0', CyaSSL version 2.4.0 will fail with an INCOMPLETE_DATA + * error. The only way to do this is currently to switch the + * Wolfssl_check_domain_name() in and out based on the + * 'ssl_config.verifyhost' value. */ + if(conn_config->verifyhost) { + failf(data, + " subject alt name(s) or common name do not match \"%s\"\n", + connssl->dispname); + return CURLE_PEER_FAILED_VERIFICATION; + } + else { + infof(data, + " subject alt name(s) and/or common name do not match \"%s\"", + connssl->dispname); + return CURLE_OK; + } +#endif + } +#if LIBWOLFSSL_VERSION_HEX >= 0x02007000 /* 2.7.0 */ + else if(ASN_NO_SIGNER_E == detail) { + if(conn_config->verifypeer) { + failf(data, " CA signer not available for verification"); + return CURLE_SSL_CACERT_BADFILE; + } + else { + /* Just continue with a warning if no strict certificate + verification is required. */ + infof(data, "CA signer not available for verification, " + "continuing anyway"); + } + } +#endif +#ifdef USE_ECH + else if(-1 == detail) { + /* try access a retry_config ECHConfigList for tracing */ + byte echConfigs[1000]; + word32 echConfigsLen = 1000; + int rv = 0; + + /* this currently doesn't produce the retry_configs */ + rv = wolfSSL_GetEchConfigs(backend->handle, echConfigs, + &echConfigsLen); + if(rv != WOLFSSL_SUCCESS) { + infof(data, "Failed to get ECHConfigs"); + } + else { + char *b64str = NULL; + size_t blen = 0; + + rv = Curl_base64_encode((const char *)echConfigs, echConfigsLen, + &b64str, &blen); + if(!rv && b64str) + infof(data, "ECH: (not yet) retry_configs %s", b64str); + free(b64str); + } + } +#endif + else if(backend->io_result == CURLE_AGAIN) { + return CURLE_OK; + } + else { + failf(data, "SSL_connect failed with error %d: %s", detail, + wolfSSL_ERR_error_string(detail, error_buffer)); + return CURLE_SSL_CONNECT_ERROR; + } + } + + if(pinnedpubkey) { +#ifdef KEEP_PEER_CERT + X509 *x509; + const char *x509_der; + int x509_der_len; + struct Curl_X509certificate x509_parsed; + struct Curl_asn1Element *pubkey; + CURLcode result; + + x509 = wolfSSL_get_peer_certificate(backend->handle); + if(!x509) { + failf(data, "SSL: failed retrieving server certificate"); + return CURLE_SSL_PINNEDPUBKEYNOTMATCH; + } + + x509_der = (const char *)wolfSSL_X509_get_der(x509, &x509_der_len); + if(!x509_der) { + failf(data, "SSL: failed retrieving ASN.1 server certificate"); + return CURLE_SSL_PINNEDPUBKEYNOTMATCH; + } + + memset(&x509_parsed, 0, sizeof(x509_parsed)); + if(Curl_parseX509(&x509_parsed, x509_der, x509_der + x509_der_len)) + return CURLE_SSL_PINNEDPUBKEYNOTMATCH; + + pubkey = &x509_parsed.subjectPublicKeyInfo; + if(!pubkey->header || pubkey->end <= pubkey->header) { + failf(data, "SSL: failed retrieving public key from server certificate"); + return CURLE_SSL_PINNEDPUBKEYNOTMATCH; + } + + result = Curl_pin_peer_pubkey(data, + pinnedpubkey, + (const unsigned char *)pubkey->header, + (size_t)(pubkey->end - pubkey->header)); + wolfSSL_FreeX509(x509); + if(result) { + failf(data, "SSL: public key does not match pinned public key"); + return result; + } +#else + failf(data, "Library lacks pinning support built-in"); + return CURLE_NOT_BUILT_IN; +#endif + } + +#ifdef HAVE_ALPN + if(connssl->alpn) { + int rc; + char *protocol = NULL; + unsigned short protocol_len = 0; + + rc = wolfSSL_ALPN_GetProtocol(backend->handle, &protocol, &protocol_len); + + if(rc == SSL_SUCCESS) { + Curl_alpn_set_negotiated(cf, data, (const unsigned char *)protocol, + protocol_len); + } + else if(rc == SSL_ALPN_NOT_FOUND) + Curl_alpn_set_negotiated(cf, data, NULL, 0); + else { + failf(data, "ALPN, failure getting protocol, error %d", rc); + return CURLE_SSL_CONNECT_ERROR; + } + } +#endif /* HAVE_ALPN */ + + connssl->connecting_state = ssl_connect_3; +#if (LIBWOLFSSL_VERSION_HEX >= 0x03009010) + infof(data, "SSL connection using %s / %s", + wolfSSL_get_version(backend->handle), + wolfSSL_get_cipher_name(backend->handle)); +#else + infof(data, "SSL connected"); +#endif + + return CURLE_OK; +} + + +static void wolfssl_session_free(void *sessionid, size_t idsize) +{ + (void)idsize; + wolfSSL_SESSION_free(sessionid); +} + + +static CURLcode +wolfssl_connect_step3(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct ssl_connect_data *connssl = cf->ctx; + struct wolfssl_ssl_backend_data *backend = + (struct wolfssl_ssl_backend_data *)connssl->backend; + const struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + + DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); + DEBUGASSERT(backend); + + if(ssl_config->primary.sessionid) { + /* wolfSSL_get1_session allocates memory that has to be freed. */ + WOLFSSL_SESSION *our_ssl_sessionid = wolfSSL_get1_session(backend->handle); + + if(our_ssl_sessionid) { + void *old_ssl_sessionid = NULL; + bool incache; + Curl_ssl_sessionid_lock(data); + incache = !(Curl_ssl_getsessionid(cf, data, &connssl->peer, + &old_ssl_sessionid, NULL)); + if(incache) { + Curl_ssl_delsessionid(data, old_ssl_sessionid); + } + + /* call takes ownership of `our_ssl_sessionid` */ + result = Curl_ssl_addsessionid(cf, data, &connssl->peer, + our_ssl_sessionid, 0, + wolfssl_session_free); + Curl_ssl_sessionid_unlock(data); + if(result) { + failf(data, "failed to store ssl session"); + return result; + } + } + } + + connssl->connecting_state = ssl_connect_done; + + return result; +} + + +static ssize_t wolfssl_send(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *mem, + size_t len, + CURLcode *curlcode) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct wolfssl_ssl_backend_data *backend = + (struct wolfssl_ssl_backend_data *)connssl->backend; + char error_buffer[WOLFSSL_MAX_ERROR_SZ]; + int memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len; + int rc; + + DEBUGASSERT(backend); + + wolfSSL_ERR_clear_error(); + + rc = wolfSSL_write(backend->handle, mem, memlen); + if(rc <= 0) { + int err = wolfSSL_get_error(backend->handle, rc); + + switch(err) { + case SSL_ERROR_WANT_READ: + case SSL_ERROR_WANT_WRITE: + /* there's data pending, re-invoke SSL_write() */ + CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> AGAIN", len); + *curlcode = CURLE_AGAIN; + return -1; + default: + if(backend->io_result == CURLE_AGAIN) { + CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> AGAIN", len); + *curlcode = CURLE_AGAIN; + return -1; + } + CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> %d, %d", len, rc, err); + failf(data, "SSL write: %s, errno %d", + wolfSSL_ERR_error_string(err, error_buffer), + SOCKERRNO); + *curlcode = CURLE_SEND_ERROR; + return -1; + } + } + CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> %d", len, rc); + return rc; +} + +static void wolfssl_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct wolfssl_ssl_backend_data *backend = + (struct wolfssl_ssl_backend_data *)connssl->backend; + + (void) data; + + DEBUGASSERT(backend); + + if(backend->handle) { + char buf[32]; + /* Maybe the server has already sent a close notify alert. + Read it to avoid an RST on the TCP connection. */ + (void)wolfSSL_read(backend->handle, buf, (int)sizeof(buf)); + if(!connssl->peer_closed) + (void)wolfSSL_shutdown(backend->handle); + wolfSSL_free(backend->handle); + backend->handle = NULL; + } + if(backend->ctx) { + wolfSSL_CTX_free(backend->ctx); + backend->ctx = NULL; + } +} + +static ssize_t wolfssl_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, + char *buf, size_t blen, + CURLcode *curlcode) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct wolfssl_ssl_backend_data *backend = + (struct wolfssl_ssl_backend_data *)connssl->backend; + char error_buffer[WOLFSSL_MAX_ERROR_SZ]; + int buffsize = (blen > (size_t)INT_MAX) ? INT_MAX : (int)blen; + int nread; + + DEBUGASSERT(backend); + + wolfSSL_ERR_clear_error(); + *curlcode = CURLE_OK; + + nread = wolfSSL_read(backend->handle, buf, buffsize); + + if(nread <= 0) { + int err = wolfSSL_get_error(backend->handle, nread); + + switch(err) { + case SSL_ERROR_ZERO_RETURN: /* no more data */ + CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> CLOSED", blen); + *curlcode = CURLE_OK; + return 0; + case SSL_ERROR_NONE: + case SSL_ERROR_WANT_READ: + case SSL_ERROR_WANT_WRITE: + /* there's data pending, re-invoke wolfSSL_read() */ + CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> AGAIN", blen); + *curlcode = CURLE_AGAIN; + return -1; + default: + if(backend->io_result == CURLE_AGAIN) { + CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> AGAIN", blen); + *curlcode = CURLE_AGAIN; + return -1; + } + failf(data, "SSL read: %s, errno %d", + wolfSSL_ERR_error_string(err, error_buffer), SOCKERRNO); + *curlcode = CURLE_RECV_ERROR; + return -1; + } + } + CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> %d", blen, nread); + return nread; +} + + +static size_t wolfssl_version(char *buffer, size_t size) +{ +#if LIBWOLFSSL_VERSION_HEX >= 0x03006000 + return msnprintf(buffer, size, "wolfSSL/%s", wolfSSL_lib_version()); +#elif defined(WOLFSSL_VERSION) + return msnprintf(buffer, size, "wolfSSL/%s", WOLFSSL_VERSION); +#endif +} + + +static int wolfssl_init(void) +{ + int ret; + +#ifdef OPENSSL_EXTRA + Curl_tls_keylog_open(); +#endif + ret = (wolfSSL_Init() == SSL_SUCCESS); + wolfssl_bio_cf_init_methods(); + return ret; +} + + +static void wolfssl_cleanup(void) +{ + wolfssl_bio_cf_free_methods(); + wolfSSL_Cleanup(); +#ifdef OPENSSL_EXTRA + Curl_tls_keylog_close(); +#endif +} + + +static bool wolfssl_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct ssl_connect_data *ctx = cf->ctx; + struct wolfssl_ssl_backend_data *backend; + + (void)data; + DEBUGASSERT(ctx && ctx->backend); + + backend = (struct wolfssl_ssl_backend_data *)ctx->backend; + if(backend->handle) /* SSL is in use */ + return (0 != wolfSSL_pending(backend->handle)) ? TRUE : FALSE; + else + return FALSE; +} + + +/* + * This function is called to shut down the SSL layer but keep the + * socket open (CCC - Clear Command Channel) + */ +static int wolfssl_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *ctx = cf->ctx; + struct wolfssl_ssl_backend_data *backend; + int retval = 0; + + (void)data; + DEBUGASSERT(ctx && ctx->backend); + + backend = (struct wolfssl_ssl_backend_data *)ctx->backend; + if(backend->handle) { + wolfSSL_ERR_clear_error(); + wolfSSL_free(backend->handle); + backend->handle = NULL; + } + return retval; +} + + +static CURLcode +wolfssl_connect_common(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool nonblocking, + bool *done) +{ + CURLcode result; + struct ssl_connect_data *connssl = cf->ctx; + curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data); + int what; + + /* check if the connection has already been established */ + if(ssl_connection_complete == connssl->state) { + *done = TRUE; + return CURLE_OK; + } + + if(ssl_connect_1 == connssl->connecting_state) { + /* Find out how much more time we're allowed */ + const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE); + + if(timeout_ms < 0) { + /* no need to continue if time already is up */ + failf(data, "SSL connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + + result = wolfssl_connect_step1(cf, data); + if(result) + return result; + } + + while(ssl_connect_2 == connssl->connecting_state || + ssl_connect_2_reading == connssl->connecting_state || + ssl_connect_2_writing == connssl->connecting_state) { + + /* check allowed time left */ + const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE); + + if(timeout_ms < 0) { + /* no need to continue if time already is up */ + failf(data, "SSL connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + + /* if ssl is expecting something, check if it's available. */ + if(connssl->connecting_state == ssl_connect_2_reading + || connssl->connecting_state == ssl_connect_2_writing) { + + curl_socket_t writefd = ssl_connect_2_writing == + connssl->connecting_state?sockfd:CURL_SOCKET_BAD; + curl_socket_t readfd = ssl_connect_2_reading == + connssl->connecting_state?sockfd:CURL_SOCKET_BAD; + + what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, + nonblocking?0:timeout_ms); + if(what < 0) { + /* fatal error */ + failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); + return CURLE_SSL_CONNECT_ERROR; + } + else if(0 == what) { + if(nonblocking) { + *done = FALSE; + return CURLE_OK; + } + else { + /* timeout */ + failf(data, "SSL connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + } + /* socket is readable or writable */ + } + + /* Run transaction, and return to the caller if it failed or if + * this connection is part of a multi handle and this loop would + * execute again. This permits the owner of a multi handle to + * abort a connection attempt before step2 has completed while + * ensuring that a client using select() or epoll() will always + * have a valid fdset to wait on. + */ + result = wolfssl_connect_step2(cf, data); + if(result || (nonblocking && + (ssl_connect_2 == connssl->connecting_state || + ssl_connect_2_reading == connssl->connecting_state || + ssl_connect_2_writing == connssl->connecting_state))) + return result; + } /* repeat step2 until all transactions are done. */ + + if(ssl_connect_3 == connssl->connecting_state) { + result = wolfssl_connect_step3(cf, data); + if(result) + return result; + } + + if(ssl_connect_done == connssl->connecting_state) { + connssl->state = ssl_connection_complete; + *done = TRUE; + } + else + *done = FALSE; + + /* Reset our connect state machine */ + connssl->connecting_state = ssl_connect_1; + + return CURLE_OK; +} + + +static CURLcode wolfssl_connect_nonblocking(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + return wolfssl_connect_common(cf, data, TRUE, done); +} + + +static CURLcode wolfssl_connect(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURLcode result; + bool done = FALSE; + + result = wolfssl_connect_common(cf, data, FALSE, &done); + if(result) + return result; + + DEBUGASSERT(done); + + return CURLE_OK; +} + +static CURLcode wolfssl_random(struct Curl_easy *data, + unsigned char *entropy, size_t length) +{ + WC_RNG rng; + (void)data; + if(wc_InitRng(&rng)) + return CURLE_FAILED_INIT; + if(length > UINT_MAX) + return CURLE_FAILED_INIT; + if(wc_RNG_GenerateBlock(&rng, entropy, (unsigned)length)) + return CURLE_FAILED_INIT; + if(wc_FreeRng(&rng)) + return CURLE_FAILED_INIT; + return CURLE_OK; +} + +static CURLcode wolfssl_sha256sum(const unsigned char *tmp, /* input */ + size_t tmplen, + unsigned char *sha256sum /* output */, + size_t unused) +{ + wc_Sha256 SHA256pw; + (void)unused; + if(wc_InitSha256(&SHA256pw)) + return CURLE_FAILED_INIT; + wc_Sha256Update(&SHA256pw, tmp, (word32)tmplen); + wc_Sha256Final(&SHA256pw, sha256sum); + return CURLE_OK; +} + +static void *wolfssl_get_internals(struct ssl_connect_data *connssl, + CURLINFO info UNUSED_PARAM) +{ + struct wolfssl_ssl_backend_data *backend = + (struct wolfssl_ssl_backend_data *)connssl->backend; + (void)info; + DEBUGASSERT(backend); + return backend->handle; +} + +const struct Curl_ssl Curl_ssl_wolfssl = { + { CURLSSLBACKEND_WOLFSSL, "WolfSSL" }, /* info */ + +#ifdef KEEP_PEER_CERT + SSLSUPP_PINNEDPUBKEY | +#endif +#ifdef USE_BIO_CHAIN + SSLSUPP_HTTPS_PROXY | +#endif + SSLSUPP_CA_PATH | + SSLSUPP_CAINFO_BLOB | +#ifdef USE_ECH + SSLSUPP_ECH | +#endif + SSLSUPP_SSL_CTX, + + sizeof(struct wolfssl_ssl_backend_data), + + wolfssl_init, /* init */ + wolfssl_cleanup, /* cleanup */ + wolfssl_version, /* version */ + Curl_none_check_cxn, /* check_cxn */ + wolfssl_shutdown, /* shutdown */ + wolfssl_data_pending, /* data_pending */ + wolfssl_random, /* random */ + Curl_none_cert_status_request, /* cert_status_request */ + wolfssl_connect, /* connect */ + wolfssl_connect_nonblocking, /* connect_nonblocking */ + Curl_ssl_adjust_pollset, /* adjust_pollset */ + wolfssl_get_internals, /* get_internals */ + wolfssl_close, /* close_one */ + Curl_none_close_all, /* close_all */ + Curl_none_set_engine, /* set_engine */ + Curl_none_set_engine_default, /* set_engine_default */ + Curl_none_engines_list, /* engines_list */ + Curl_none_false_start, /* false_start */ + wolfssl_sha256sum, /* sha256sum */ + NULL, /* associate_connection */ + NULL, /* disassociate_connection */ + NULL, /* free_multi_ssl_backend_data */ + wolfssl_recv, /* recv decrypted data */ + wolfssl_send, /* send data to encrypt */ +}; + +#endif diff --git a/third_party/curl/lib/vtls/wolfssl.h b/third_party/curl/lib/vtls/wolfssl.h new file mode 100644 index 0000000..a5ed848 --- /dev/null +++ b/third_party/curl/lib/vtls/wolfssl.h @@ -0,0 +1,33 @@ +#ifndef HEADER_CURL_WOLFSSL_H +#define HEADER_CURL_WOLFSSL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_WOLFSSL + +extern const struct Curl_ssl Curl_ssl_wolfssl; + +#endif /* USE_WOLFSSL */ +#endif /* HEADER_CURL_WOLFSSL_H */ diff --git a/third_party/curl/lib/vtls/x509asn1.c b/third_party/curl/lib/vtls/x509asn1.c new file mode 100644 index 0000000..4564ea9 --- /dev/null +++ b/third_party/curl/lib/vtls/x509asn1.c @@ -0,0 +1,1232 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_GNUTLS) || defined(USE_WOLFSSL) || \ + defined(USE_SCHANNEL) || defined(USE_SECTRANSP) + +#if defined(USE_WOLFSSL) || defined(USE_SCHANNEL) +#define WANT_PARSEX509 /* uses Curl_parseX509() */ +#endif + +#if defined(USE_GNUTLS) || defined(USE_SCHANNEL) || defined(USE_SECTRANSP) +#define WANT_EXTRACT_CERTINFO /* uses Curl_extract_certinfo() */ +#define WANT_PARSEX509 /* ... uses Curl_parseX509() */ +#endif + +#include +#include "urldata.h" +#include "strcase.h" +#include "curl_ctype.h" +#include "hostcheck.h" +#include "vtls/vtls.h" +#include "vtls/vtls_int.h" +#include "sendf.h" +#include "inet_pton.h" +#include "curl_base64.h" +#include "x509asn1.h" +#include "dynbuf.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Constants. + */ + +/* Largest supported ASN.1 structure. */ +#define CURL_ASN1_MAX ((size_t) 0x40000) /* 256K */ + +/* ASN.1 classes. */ +#define CURL_ASN1_UNIVERSAL 0 +#define CURL_ASN1_APPLICATION 1 +#define CURL_ASN1_CONTEXT_SPECIFIC 2 +#define CURL_ASN1_PRIVATE 3 + +/* ASN.1 types. */ +#define CURL_ASN1_BOOLEAN 1 +#define CURL_ASN1_INTEGER 2 +#define CURL_ASN1_BIT_STRING 3 +#define CURL_ASN1_OCTET_STRING 4 +#define CURL_ASN1_NULL 5 +#define CURL_ASN1_OBJECT_IDENTIFIER 6 +#define CURL_ASN1_OBJECT_DESCRIPTOR 7 +#define CURL_ASN1_INSTANCE_OF 8 +#define CURL_ASN1_REAL 9 +#define CURL_ASN1_ENUMERATED 10 +#define CURL_ASN1_EMBEDDED 11 +#define CURL_ASN1_UTF8_STRING 12 +#define CURL_ASN1_RELATIVE_OID 13 +#define CURL_ASN1_SEQUENCE 16 +#define CURL_ASN1_SET 17 +#define CURL_ASN1_NUMERIC_STRING 18 +#define CURL_ASN1_PRINTABLE_STRING 19 +#define CURL_ASN1_TELETEX_STRING 20 +#define CURL_ASN1_VIDEOTEX_STRING 21 +#define CURL_ASN1_IA5_STRING 22 +#define CURL_ASN1_UTC_TIME 23 +#define CURL_ASN1_GENERALIZED_TIME 24 +#define CURL_ASN1_GRAPHIC_STRING 25 +#define CURL_ASN1_VISIBLE_STRING 26 +#define CURL_ASN1_GENERAL_STRING 27 +#define CURL_ASN1_UNIVERSAL_STRING 28 +#define CURL_ASN1_CHARACTER_STRING 29 +#define CURL_ASN1_BMP_STRING 30 + +/* Max sixes */ + +#define MAX_X509_STR 10000 +#define MAX_X509_CERT 100000 + +#ifdef WANT_EXTRACT_CERTINFO +/* ASN.1 OID table entry. */ +struct Curl_OID { + const char *numoid; /* Dotted-numeric OID. */ + const char *textoid; /* OID name. */ +}; + +/* ASN.1 OIDs. */ +static const char cnOID[] = "2.5.4.3"; /* Common name. */ +static const char sanOID[] = "2.5.29.17"; /* Subject alternative name. */ + +static const struct Curl_OID OIDtable[] = { + { "1.2.840.10040.4.1", "dsa" }, + { "1.2.840.10040.4.3", "dsa-with-sha1" }, + { "1.2.840.10045.2.1", "ecPublicKey" }, + { "1.2.840.10045.3.0.1", "c2pnb163v1" }, + { "1.2.840.10045.4.1", "ecdsa-with-SHA1" }, + { "1.2.840.10046.2.1", "dhpublicnumber" }, + { "1.2.840.113549.1.1.1", "rsaEncryption" }, + { "1.2.840.113549.1.1.2", "md2WithRSAEncryption" }, + { "1.2.840.113549.1.1.4", "md5WithRSAEncryption" }, + { "1.2.840.113549.1.1.5", "sha1WithRSAEncryption" }, + { "1.2.840.113549.1.1.10", "RSASSA-PSS" }, + { "1.2.840.113549.1.1.14", "sha224WithRSAEncryption" }, + { "1.2.840.113549.1.1.11", "sha256WithRSAEncryption" }, + { "1.2.840.113549.1.1.12", "sha384WithRSAEncryption" }, + { "1.2.840.113549.1.1.13", "sha512WithRSAEncryption" }, + { "1.2.840.113549.2.2", "md2" }, + { "1.2.840.113549.2.5", "md5" }, + { "1.3.14.3.2.26", "sha1" }, + { cnOID, "CN" }, + { "2.5.4.4", "SN" }, + { "2.5.4.5", "serialNumber" }, + { "2.5.4.6", "C" }, + { "2.5.4.7", "L" }, + { "2.5.4.8", "ST" }, + { "2.5.4.9", "streetAddress" }, + { "2.5.4.10", "O" }, + { "2.5.4.11", "OU" }, + { "2.5.4.12", "title" }, + { "2.5.4.13", "description" }, + { "2.5.4.17", "postalCode" }, + { "2.5.4.41", "name" }, + { "2.5.4.42", "givenName" }, + { "2.5.4.43", "initials" }, + { "2.5.4.44", "generationQualifier" }, + { "2.5.4.45", "X500UniqueIdentifier" }, + { "2.5.4.46", "dnQualifier" }, + { "2.5.4.65", "pseudonym" }, + { "1.2.840.113549.1.9.1", "emailAddress" }, + { "2.5.4.72", "role" }, + { sanOID, "subjectAltName" }, + { "2.5.29.18", "issuerAltName" }, + { "2.5.29.19", "basicConstraints" }, + { "2.16.840.1.101.3.4.2.4", "sha224" }, + { "2.16.840.1.101.3.4.2.1", "sha256" }, + { "2.16.840.1.101.3.4.2.2", "sha384" }, + { "2.16.840.1.101.3.4.2.3", "sha512" }, + { "1.2.840.113549.1.9.2", "unstructuredName" }, + { (const char *) NULL, (const char *) NULL } +}; + +#endif /* WANT_EXTRACT_CERTINFO */ + +/* + * Lightweight ASN.1 parser. + * In particular, it does not check for syntactic/lexical errors. + * It is intended to support certificate information gathering for SSL backends + * that offer a mean to get certificates as a whole, but do not supply + * entry points to get particular certificate sub-fields. + * Please note there is no pretension here to rewrite a full SSL library. + */ + +static const char *getASN1Element(struct Curl_asn1Element *elem, + const char *beg, const char *end) + WARN_UNUSED_RESULT; + +static const char *getASN1Element(struct Curl_asn1Element *elem, + const char *beg, const char *end) +{ + unsigned char b; + size_t len; + struct Curl_asn1Element lelem; + + /* Get a single ASN.1 element into `elem', parse ASN.1 string at `beg' + ending at `end'. + Returns a pointer in source string after the parsed element, or NULL + if an error occurs. */ + if(!beg || !end || beg >= end || !*beg || + (size_t)(end - beg) > CURL_ASN1_MAX) + return NULL; + + /* Process header byte. */ + elem->header = beg; + b = (unsigned char) *beg++; + elem->constructed = (b & 0x20) != 0; + elem->class = (b >> 6) & 3; + b &= 0x1F; + if(b == 0x1F) + return NULL; /* Long tag values not supported here. */ + elem->tag = b; + + /* Process length. */ + if(beg >= end) + return NULL; + b = (unsigned char) *beg++; + if(!(b & 0x80)) + len = b; + else if(!(b &= 0x7F)) { + /* Unspecified length. Since we have all the data, we can determine the + effective length by skipping element until an end element is found. */ + if(!elem->constructed) + return NULL; + elem->beg = beg; + while(beg < end && *beg) { + beg = getASN1Element(&lelem, beg, end); + if(!beg) + return NULL; + } + if(beg >= end) + return NULL; + elem->end = beg; + return beg + 1; + } + else if((unsigned)b > (size_t)(end - beg)) + return NULL; /* Does not fit in source. */ + else { + /* Get long length. */ + len = 0; + do { + if(len & 0xFF000000L) + return NULL; /* Lengths > 32 bits are not supported. */ + len = (len << 8) | (unsigned char) *beg++; + } while(--b); + } + if(len > (size_t)(end - beg)) + return NULL; /* Element data does not fit in source. */ + elem->beg = beg; + elem->end = beg + len; + return elem->end; +} + +#ifdef WANT_EXTRACT_CERTINFO + +/* + * Search the null terminated OID or OID identifier in local table. + * Return the table entry pointer or NULL if not found. + */ +static const struct Curl_OID *searchOID(const char *oid) +{ + const struct Curl_OID *op; + for(op = OIDtable; op->numoid; op++) + if(!strcmp(op->numoid, oid) || strcasecompare(op->textoid, oid)) + return op; + + return NULL; +} + +/* + * Convert an ASN.1 Boolean value into its string representation. + * + * Return error code. + */ + +static CURLcode bool2str(struct dynbuf *store, + const char *beg, const char *end) +{ + if(end - beg != 1) + return CURLE_BAD_FUNCTION_ARGUMENT; + return Curl_dyn_add(store, *beg? "TRUE": "FALSE"); +} + +/* + * Convert an ASN.1 octet string to a printable string. + * + * Return error code. + */ +static CURLcode octet2str(struct dynbuf *store, + const char *beg, const char *end) +{ + CURLcode result = CURLE_OK; + + while(!result && beg < end) + result = Curl_dyn_addf(store, "%02x:", (unsigned char) *beg++); + + return result; +} + +static CURLcode bit2str(struct dynbuf *store, + const char *beg, const char *end) +{ + /* Convert an ASN.1 bit string to a printable string. */ + + if(++beg > end) + return CURLE_BAD_FUNCTION_ARGUMENT; + return octet2str(store, beg, end); +} + +/* + * Convert an ASN.1 integer value into its string representation. + * + * Returns error. + */ +static CURLcode int2str(struct dynbuf *store, + const char *beg, const char *end) +{ + unsigned int val = 0; + size_t n = end - beg; + + if(!n) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(n > 4) + return octet2str(store, beg, end); + + /* Represent integers <= 32-bit as a single value. */ + if(*beg & 0x80) + val = ~val; + + do + val = (val << 8) | *(const unsigned char *) beg++; + while(beg < end); + return Curl_dyn_addf(store, "%s%x", val >= 10? "0x": "", val); +} + +/* + * Convert from an ASN.1 typed string to UTF8. + * + * The result is stored in a dynbuf that is inited by the user of this + * function. + * + * Returns error. + */ +static CURLcode +utf8asn1str(struct dynbuf *to, int type, const char *from, const char *end) +{ + size_t inlength = end - from; + int size = 1; + CURLcode result = CURLE_OK; + + switch(type) { + case CURL_ASN1_BMP_STRING: + size = 2; + break; + case CURL_ASN1_UNIVERSAL_STRING: + size = 4; + break; + case CURL_ASN1_NUMERIC_STRING: + case CURL_ASN1_PRINTABLE_STRING: + case CURL_ASN1_TELETEX_STRING: + case CURL_ASN1_IA5_STRING: + case CURL_ASN1_VISIBLE_STRING: + case CURL_ASN1_UTF8_STRING: + break; + default: + return CURLE_BAD_FUNCTION_ARGUMENT; /* Conversion not supported. */ + } + + if(inlength % size) + /* Length inconsistent with character size. */ + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(type == CURL_ASN1_UTF8_STRING) { + /* Just copy. */ + if(inlength) + result = Curl_dyn_addn(to, from, inlength); + } + else { + while(!result && (from < end)) { + char buf[4]; /* decode buffer */ + int charsize = 1; + unsigned int wc = 0; + + switch(size) { + case 4: + wc = (wc << 8) | *(const unsigned char *) from++; + wc = (wc << 8) | *(const unsigned char *) from++; + FALLTHROUGH(); + case 2: + wc = (wc << 8) | *(const unsigned char *) from++; + FALLTHROUGH(); + default: /* case 1: */ + wc = (wc << 8) | *(const unsigned char *) from++; + } + if(wc >= 0x00000080) { + if(wc >= 0x00000800) { + if(wc >= 0x00010000) { + if(wc >= 0x00200000) { + free(buf); + /* Invalid char. size for target encoding. */ + return CURLE_WEIRD_SERVER_REPLY; + } + buf[3] = (char) (0x80 | (wc & 0x3F)); + wc = (wc >> 6) | 0x00010000; + charsize++; + } + buf[2] = (char) (0x80 | (wc & 0x3F)); + wc = (wc >> 6) | 0x00000800; + charsize++; + } + buf[1] = (char) (0x80 | (wc & 0x3F)); + wc = (wc >> 6) | 0x000000C0; + charsize++; + } + buf[0] = (char) wc; + result = Curl_dyn_addn(to, buf, charsize); + } + } + return result; +} + +/* + * Convert an ASN.1 OID into its dotted string representation. + * + * Return error code. + */ +static CURLcode encodeOID(struct dynbuf *store, + const char *beg, const char *end) +{ + unsigned int x; + unsigned int y; + CURLcode result = CURLE_OK; + + /* Process the first two numbers. */ + y = *(const unsigned char *) beg++; + x = y / 40; + y -= x * 40; + + result = Curl_dyn_addf(store, "%u.%u", x, y); + if(result) + return result; + + /* Process the trailing numbers. */ + while(beg < end) { + x = 0; + do { + if(x & 0xFF000000) + return 0; + y = *(const unsigned char *) beg++; + x = (x << 7) | (y & 0x7F); + } while(y & 0x80); + result = Curl_dyn_addf(store, ".%u", x); + } + return result; +} + +/* + * Convert an ASN.1 OID into its dotted or symbolic string representation. + * + * Return error code. + */ + +static CURLcode OID2str(struct dynbuf *store, + const char *beg, const char *end, bool symbolic) +{ + CURLcode result = CURLE_OK; + if(beg < end) { + if(symbolic) { + struct dynbuf buf; + Curl_dyn_init(&buf, MAX_X509_STR); + result = encodeOID(&buf, beg, end); + + if(!result) { + const struct Curl_OID *op = searchOID(Curl_dyn_ptr(&buf)); + if(op) + result = Curl_dyn_add(store, op->textoid); + else + result = CURLE_BAD_FUNCTION_ARGUMENT; + Curl_dyn_free(&buf); + } + } + else + result = encodeOID(store, beg, end); + } + return result; +} + +static CURLcode GTime2str(struct dynbuf *store, + const char *beg, const char *end) +{ + const char *tzp; + const char *fracp; + char sec1, sec2; + size_t fracl; + size_t tzl; + const char *sep = ""; + + /* Convert an ASN.1 Generalized time to a printable string. + Return the dynamically allocated string, or NULL if an error occurs. */ + + for(fracp = beg; fracp < end && *fracp >= '0' && *fracp <= '9'; fracp++) + ; + + /* Get seconds digits. */ + sec1 = '0'; + switch(fracp - beg - 12) { + case 0: + sec2 = '0'; + break; + case 2: + sec1 = fracp[-2]; + FALLTHROUGH(); + case 1: + sec2 = fracp[-1]; + break; + default: + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + /* Scan for timezone, measure fractional seconds. */ + tzp = fracp; + fracl = 0; + if(fracp < end && (*fracp == '.' || *fracp == ',')) { + fracp++; + do + tzp++; + while(tzp < end && *tzp >= '0' && *tzp <= '9'); + /* Strip leading zeroes in fractional seconds. */ + for(fracl = tzp - fracp - 1; fracl && fracp[fracl - 1] == '0'; fracl--) + ; + } + + /* Process timezone. */ + if(tzp >= end) + ; /* Nothing to do. */ + else if(*tzp == 'Z') { + tzp = " GMT"; + end = tzp + 4; + } + else { + sep = " "; + tzp++; + } + + tzl = end - tzp; + return Curl_dyn_addf(store, + "%.4s-%.2s-%.2s %.2s:%.2s:%c%c%s%.*s%s%.*s", + beg, beg + 4, beg + 6, + beg + 8, beg + 10, sec1, sec2, + fracl? ".": "", (int)fracl, fracp, + sep, (int)tzl, tzp); +} + +/* + * Convert an ASN.1 UTC time to a printable string. + * + * Return error code. + */ +static CURLcode UTime2str(struct dynbuf *store, + const char *beg, const char *end) +{ + const char *tzp; + size_t tzl; + const char *sec; + + for(tzp = beg; tzp < end && *tzp >= '0' && *tzp <= '9'; tzp++) + ; + /* Get the seconds. */ + sec = beg + 10; + switch(tzp - sec) { + case 0: + sec = "00"; + FALLTHROUGH(); + case 2: + break; + default: + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + /* Process timezone. */ + if(tzp >= end) + return CURLE_BAD_FUNCTION_ARGUMENT; + if(*tzp == 'Z') { + tzp = "GMT"; + end = tzp + 3; + } + else + tzp++; + + tzl = end - tzp; + return Curl_dyn_addf(store, "%u%.2s-%.2s-%.2s %.2s:%.2s:%.2s %.*s", + 20 - (*beg >= '5'), beg, beg + 2, beg + 4, + beg + 6, beg + 8, sec, + (int)tzl, tzp); +} + +/* + * Convert an ASN.1 element to a printable string. + * + * Return error + */ +static CURLcode ASN1tostr(struct dynbuf *store, + struct Curl_asn1Element *elem, int type) +{ + CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT; + if(elem->constructed) + return CURLE_OK; /* No conversion of structured elements. */ + + if(!type) + type = elem->tag; /* Type not forced: use element tag as type. */ + + switch(type) { + case CURL_ASN1_BOOLEAN: + result = bool2str(store, elem->beg, elem->end); + break; + case CURL_ASN1_INTEGER: + case CURL_ASN1_ENUMERATED: + result = int2str(store, elem->beg, elem->end); + break; + case CURL_ASN1_BIT_STRING: + result = bit2str(store, elem->beg, elem->end); + break; + case CURL_ASN1_OCTET_STRING: + result = octet2str(store, elem->beg, elem->end); + break; + case CURL_ASN1_NULL: + result = Curl_dyn_addn(store, "", 1); + break; + case CURL_ASN1_OBJECT_IDENTIFIER: + result = OID2str(store, elem->beg, elem->end, TRUE); + break; + case CURL_ASN1_UTC_TIME: + result = UTime2str(store, elem->beg, elem->end); + break; + case CURL_ASN1_GENERALIZED_TIME: + result = GTime2str(store, elem->beg, elem->end); + break; + case CURL_ASN1_UTF8_STRING: + case CURL_ASN1_NUMERIC_STRING: + case CURL_ASN1_PRINTABLE_STRING: + case CURL_ASN1_TELETEX_STRING: + case CURL_ASN1_IA5_STRING: + case CURL_ASN1_VISIBLE_STRING: + case CURL_ASN1_UNIVERSAL_STRING: + case CURL_ASN1_BMP_STRING: + result = utf8asn1str(store, type, elem->beg, elem->end); + break; + } + + return result; +} + +/* + * ASCII encode distinguished name at `dn' into the store dynbuf. + * + * Returns error. + */ +static CURLcode encodeDN(struct dynbuf *store, struct Curl_asn1Element *dn) +{ + struct Curl_asn1Element rdn; + struct Curl_asn1Element atv; + struct Curl_asn1Element oid; + struct Curl_asn1Element value; + const char *p1; + const char *p2; + const char *p3; + const char *str; + CURLcode result = CURLE_OK; + bool added = FALSE; + struct dynbuf temp; + Curl_dyn_init(&temp, MAX_X509_STR); + + for(p1 = dn->beg; p1 < dn->end;) { + p1 = getASN1Element(&rdn, p1, dn->end); + if(!p1) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto error; + } + for(p2 = rdn.beg; p2 < rdn.end;) { + p2 = getASN1Element(&atv, p2, rdn.end); + if(!p2) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto error; + } + p3 = getASN1Element(&oid, atv.beg, atv.end); + if(!p3) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto error; + } + if(!getASN1Element(&value, p3, atv.end)) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto error; + } + Curl_dyn_reset(&temp); + result = ASN1tostr(&temp, &oid, 0); + if(result) + goto error; + + str = Curl_dyn_ptr(&temp); + + /* Encode delimiter. + If attribute has a short uppercase name, delimiter is ", ". */ + for(p3 = str; ISUPPER(*p3); p3++) + ; + if(added) { + if(p3 - str > 2) + result = Curl_dyn_addn(store, "/", 1); + else + result = Curl_dyn_addn(store, ", ", 2); + if(result) + goto error; + } + + /* Encode attribute name. */ + result = Curl_dyn_add(store, str); + if(result) + goto error; + + /* Generate equal sign. */ + result = Curl_dyn_addn(store, "=", 1); + if(result) + goto error; + + /* Generate value. */ + result = ASN1tostr(store, &value, 0); + if(result) + goto error; + Curl_dyn_reset(&temp); + added = TRUE; /* use separator for next */ + } + } +error: + Curl_dyn_free(&temp); + + return result; +} + +#endif /* WANT_EXTRACT_CERTINFO */ + +#ifdef WANT_PARSEX509 +/* + * ASN.1 parse an X509 certificate into structure subfields. + * Syntax is assumed to have already been checked by the SSL backend. + * See RFC 5280. + */ +int Curl_parseX509(struct Curl_X509certificate *cert, + const char *beg, const char *end) +{ + struct Curl_asn1Element elem; + struct Curl_asn1Element tbsCertificate; + const char *ccp; + static const char defaultVersion = 0; /* v1. */ + + cert->certificate.header = NULL; + cert->certificate.beg = beg; + cert->certificate.end = end; + + /* Get the sequence content. */ + if(!getASN1Element(&elem, beg, end)) + return -1; /* Invalid bounds/size. */ + beg = elem.beg; + end = elem.end; + + /* Get tbsCertificate. */ + beg = getASN1Element(&tbsCertificate, beg, end); + if(!beg) + return -1; + /* Skip the signatureAlgorithm. */ + beg = getASN1Element(&cert->signatureAlgorithm, beg, end); + if(!beg) + return -1; + /* Get the signatureValue. */ + if(!getASN1Element(&cert->signature, beg, end)) + return -1; + + /* Parse TBSCertificate. */ + beg = tbsCertificate.beg; + end = tbsCertificate.end; + /* Get optional version, get serialNumber. */ + cert->version.header = NULL; + cert->version.beg = &defaultVersion; + cert->version.end = &defaultVersion + sizeof(defaultVersion); + beg = getASN1Element(&elem, beg, end); + if(!beg) + return -1; + if(elem.tag == 0) { + if(!getASN1Element(&cert->version, elem.beg, elem.end)) + return -1; + beg = getASN1Element(&elem, beg, end); + if(!beg) + return -1; + } + cert->serialNumber = elem; + /* Get signature algorithm. */ + beg = getASN1Element(&cert->signatureAlgorithm, beg, end); + /* Get issuer. */ + beg = getASN1Element(&cert->issuer, beg, end); + if(!beg) + return -1; + /* Get notBefore and notAfter. */ + beg = getASN1Element(&elem, beg, end); + if(!beg) + return -1; + ccp = getASN1Element(&cert->notBefore, elem.beg, elem.end); + if(!ccp) + return -1; + if(!getASN1Element(&cert->notAfter, ccp, elem.end)) + return -1; + /* Get subject. */ + beg = getASN1Element(&cert->subject, beg, end); + if(!beg) + return -1; + /* Get subjectPublicKeyAlgorithm and subjectPublicKey. */ + beg = getASN1Element(&cert->subjectPublicKeyInfo, beg, end); + if(!beg) + return -1; + ccp = getASN1Element(&cert->subjectPublicKeyAlgorithm, + cert->subjectPublicKeyInfo.beg, + cert->subjectPublicKeyInfo.end); + if(!ccp) + return -1; + if(!getASN1Element(&cert->subjectPublicKey, ccp, + cert->subjectPublicKeyInfo.end)) + return -1; + /* Get optional issuerUiqueID, subjectUniqueID and extensions. */ + cert->issuerUniqueID.tag = cert->subjectUniqueID.tag = 0; + cert->extensions.tag = elem.tag = 0; + cert->issuerUniqueID.header = cert->subjectUniqueID.header = NULL; + cert->issuerUniqueID.beg = cert->issuerUniqueID.end = ""; + cert->subjectUniqueID.beg = cert->subjectUniqueID.end = ""; + cert->extensions.header = NULL; + cert->extensions.beg = cert->extensions.end = ""; + if(beg < end) { + beg = getASN1Element(&elem, beg, end); + if(!beg) + return -1; + } + if(elem.tag == 1) { + cert->issuerUniqueID = elem; + if(beg < end) { + beg = getASN1Element(&elem, beg, end); + if(!beg) + return -1; + } + } + if(elem.tag == 2) { + cert->subjectUniqueID = elem; + if(beg < end) { + beg = getASN1Element(&elem, beg, end); + if(!beg) + return -1; + } + } + if(elem.tag == 3) + if(!getASN1Element(&cert->extensions, elem.beg, elem.end)) + return -1; + return 0; +} + +#endif /* WANT_PARSEX509 */ + +#ifdef WANT_EXTRACT_CERTINFO + +static CURLcode dumpAlgo(struct dynbuf *store, + struct Curl_asn1Element *param, + const char *beg, const char *end) +{ + struct Curl_asn1Element oid; + + /* Get algorithm parameters and return algorithm name. */ + + beg = getASN1Element(&oid, beg, end); + if(!beg) + return CURLE_BAD_FUNCTION_ARGUMENT; + param->header = NULL; + param->tag = 0; + param->beg = param->end = end; + if(beg < end) { + const char *p = getASN1Element(param, beg, end); + if(!p) + return CURLE_BAD_FUNCTION_ARGUMENT; + } + return OID2str(store, oid.beg, oid.end, TRUE); +} + +/* + * This is a convenience function for push_certinfo_len that takes a zero + * terminated value. + */ +static CURLcode ssl_push_certinfo(struct Curl_easy *data, + int certnum, + const char *label, + const char *value) +{ + size_t valuelen = strlen(value); + + return Curl_ssl_push_certinfo_len(data, certnum, label, value, valuelen); +} + +/* + * This is a convenience function for push_certinfo_len that takes a + * dynbuf value. + * + * It also does the verbose output if !certnum. + */ +static CURLcode ssl_push_certinfo_dyn(struct Curl_easy *data, + int certnum, + const char *label, + struct dynbuf *ptr) +{ + size_t valuelen = Curl_dyn_len(ptr); + char *value = Curl_dyn_ptr(ptr); + + CURLcode result = Curl_ssl_push_certinfo_len(data, certnum, label, + value, valuelen); + + if(!certnum && !result) + infof(data, " %s: %s", label, value); + + return result; +} + +static CURLcode do_pubkey_field(struct Curl_easy *data, int certnum, + const char *label, + struct Curl_asn1Element *elem) +{ + CURLcode result; + struct dynbuf out; + + Curl_dyn_init(&out, MAX_X509_STR); + + /* Generate a certificate information record for the public key. */ + + result = ASN1tostr(&out, elem, 0); + if(!result) { + if(data->set.ssl.certinfo) + result = ssl_push_certinfo_dyn(data, certnum, label, &out); + Curl_dyn_free(&out); + } + return result; +} + +/* return 0 on success, 1 on error */ +static int do_pubkey(struct Curl_easy *data, int certnum, + const char *algo, struct Curl_asn1Element *param, + struct Curl_asn1Element *pubkey) +{ + struct Curl_asn1Element elem; + struct Curl_asn1Element pk; + const char *p; + + /* Generate all information records for the public key. */ + + if(strcasecompare(algo, "ecPublicKey")) { + /* + * ECC public key is all the data, a value of type BIT STRING mapped to + * OCTET STRING and should not be parsed as an ASN.1 value. + */ + const size_t len = ((pubkey->end - pubkey->beg - 2) * 4); + if(!certnum) + infof(data, " ECC Public Key (%zu bits)", len); + if(data->set.ssl.certinfo) { + char q[sizeof(len) * 8 / 3 + 1]; + (void)msnprintf(q, sizeof(q), "%zu", len); + if(ssl_push_certinfo(data, certnum, "ECC Public Key", q)) + return 1; + } + return do_pubkey_field(data, certnum, "ecPublicKey", pubkey); + } + + /* Get the public key (single element). */ + if(!getASN1Element(&pk, pubkey->beg + 1, pubkey->end)) + return 1; + + if(strcasecompare(algo, "rsaEncryption")) { + const char *q; + size_t len; + + p = getASN1Element(&elem, pk.beg, pk.end); + if(!p) + return 1; + + /* Compute key length. */ + for(q = elem.beg; !*q && q < elem.end; q++) + ; + len = ((elem.end - q) * 8); + if(len) { + unsigned int i; + for(i = *(unsigned char *) q; !(i & 0x80); i <<= 1) + len--; + } + if(len > 32) + elem.beg = q; /* Strip leading zero bytes. */ + if(!certnum) + infof(data, " RSA Public Key (%zu bits)", len); + if(data->set.ssl.certinfo) { + char r[sizeof(len) * 8 / 3 + 1]; + msnprintf(r, sizeof(r), "%zu", len); + if(ssl_push_certinfo(data, certnum, "RSA Public Key", r)) + return 1; + } + /* Generate coefficients. */ + if(do_pubkey_field(data, certnum, "rsa(n)", &elem)) + return 1; + if(!getASN1Element(&elem, p, pk.end)) + return 1; + if(do_pubkey_field(data, certnum, "rsa(e)", &elem)) + return 1; + } + else if(strcasecompare(algo, "dsa")) { + p = getASN1Element(&elem, param->beg, param->end); + if(p) { + if(do_pubkey_field(data, certnum, "dsa(p)", &elem)) + return 1; + p = getASN1Element(&elem, p, param->end); + if(p) { + if(do_pubkey_field(data, certnum, "dsa(q)", &elem)) + return 1; + if(getASN1Element(&elem, p, param->end)) { + if(do_pubkey_field(data, certnum, "dsa(g)", &elem)) + return 1; + if(do_pubkey_field(data, certnum, "dsa(pub_key)", &pk)) + return 1; + } + } + } + } + else if(strcasecompare(algo, "dhpublicnumber")) { + p = getASN1Element(&elem, param->beg, param->end); + if(p) { + if(do_pubkey_field(data, certnum, "dh(p)", &elem)) + return 1; + if(getASN1Element(&elem, param->beg, param->end)) { + if(do_pubkey_field(data, certnum, "dh(g)", &elem)) + return 1; + if(do_pubkey_field(data, certnum, "dh(pub_key)", &pk)) + return 1; + } + } + } + return 0; +} + +/* + * Convert an ASN.1 distinguished name into a printable string. + * Return error. + */ +static CURLcode DNtostr(struct dynbuf *store, + struct Curl_asn1Element *dn) +{ + return encodeDN(store, dn); +} + +CURLcode Curl_extract_certinfo(struct Curl_easy *data, + int certnum, + const char *beg, + const char *end) +{ + struct Curl_X509certificate cert; + struct Curl_asn1Element param; + char *certptr; + size_t clen; + struct dynbuf out; + CURLcode result = CURLE_OK; + unsigned int version; + const char *ptr; + int rc; + + if(!data->set.ssl.certinfo) + if(certnum) + return CURLE_OK; + + Curl_dyn_init(&out, MAX_X509_STR); + /* Prepare the certificate information for curl_easy_getinfo(). */ + + /* Extract the certificate ASN.1 elements. */ + if(Curl_parseX509(&cert, beg, end)) + return CURLE_PEER_FAILED_VERIFICATION; + + /* Subject. */ + result = DNtostr(&out, &cert.subject); + if(result) + goto done; + if(data->set.ssl.certinfo) { + result = ssl_push_certinfo_dyn(data, certnum, "Subject", &out); + if(result) + goto done; + } + Curl_dyn_reset(&out); + + /* Issuer. */ + result = DNtostr(&out, &cert.issuer); + if(result) + goto done; + if(data->set.ssl.certinfo) { + result = ssl_push_certinfo_dyn(data, certnum, "Issuer", &out); + if(result) + goto done; + } + Curl_dyn_reset(&out); + + /* Version (always fits in less than 32 bits). */ + version = 0; + for(ptr = cert.version.beg; ptr < cert.version.end; ptr++) + version = (version << 8) | *(const unsigned char *) ptr; + if(data->set.ssl.certinfo) { + result = Curl_dyn_addf(&out, "%x", version); + if(result) + goto done; + result = ssl_push_certinfo_dyn(data, certnum, "Version", &out); + if(result) + goto done; + Curl_dyn_reset(&out); + } + + /* Serial number. */ + result = ASN1tostr(&out, &cert.serialNumber, 0); + if(result) + goto done; + if(data->set.ssl.certinfo) { + result = ssl_push_certinfo_dyn(data, certnum, "Serial Number", &out); + if(result) + goto done; + } + Curl_dyn_reset(&out); + + /* Signature algorithm .*/ + result = dumpAlgo(&out, ¶m, cert.signatureAlgorithm.beg, + cert.signatureAlgorithm.end); + if(result) + goto done; + if(data->set.ssl.certinfo) { + result = ssl_push_certinfo_dyn(data, certnum, "Signature Algorithm", + &out); + if(result) + goto done; + } + Curl_dyn_reset(&out); + + /* Start Date. */ + result = ASN1tostr(&out, &cert.notBefore, 0); + if(result) + goto done; + if(data->set.ssl.certinfo) { + result = ssl_push_certinfo_dyn(data, certnum, "Start Date", &out); + if(result) + goto done; + } + Curl_dyn_reset(&out); + + /* Expire Date. */ + result = ASN1tostr(&out, &cert.notAfter, 0); + if(result) + goto done; + if(data->set.ssl.certinfo) { + result = ssl_push_certinfo_dyn(data, certnum, "Expire Date", &out); + if(result) + goto done; + } + Curl_dyn_reset(&out); + + /* Public Key Algorithm. */ + result = dumpAlgo(&out, ¶m, cert.subjectPublicKeyAlgorithm.beg, + cert.subjectPublicKeyAlgorithm.end); + if(result) + goto done; + if(data->set.ssl.certinfo) { + result = ssl_push_certinfo_dyn(data, certnum, "Public Key Algorithm", + &out); + if(result) + goto done; + } + + rc = do_pubkey(data, certnum, Curl_dyn_ptr(&out), + ¶m, &cert.subjectPublicKey); + if(rc) { + result = CURLE_OUT_OF_MEMORY; /* the most likely error */ + goto done; + } + Curl_dyn_reset(&out); + + /* Signature. */ + result = ASN1tostr(&out, &cert.signature, 0); + if(result) + goto done; + if(data->set.ssl.certinfo) { + result = ssl_push_certinfo_dyn(data, certnum, "Signature", &out); + if(result) + goto done; + } + Curl_dyn_reset(&out); + + /* Generate PEM certificate. */ + result = Curl_base64_encode(cert.certificate.beg, + cert.certificate.end - cert.certificate.beg, + &certptr, &clen); + if(result) + goto done; + + /* Generate the final output certificate string. Format is: + -----BEGIN CERTIFICATE-----\n + \n + . + . + . + -----END CERTIFICATE-----\n + */ + + Curl_dyn_reset(&out); + + /* Build the certificate string. */ + result = Curl_dyn_add(&out, "-----BEGIN CERTIFICATE-----\n"); + if(!result) { + size_t j = 0; + + while(!result && (j < clen)) { + size_t chunksize = (clen - j) > 64 ? 64 : (clen - j); + result = Curl_dyn_addn(&out, &certptr[j], chunksize); + if(!result) + result = Curl_dyn_addn(&out, "\n", 1); + j += chunksize; + } + if(!result) + result = Curl_dyn_add(&out, "-----END CERTIFICATE-----\n"); + } + free(certptr); + if(!result) + if(data->set.ssl.certinfo) + result = ssl_push_certinfo_dyn(data, certnum, "Cert", &out); + +done: + Curl_dyn_free(&out); + return result; +} + +#endif /* WANT_EXTRACT_CERTINFO */ + +#endif /* USE_GNUTLS or USE_WOLFSSL or USE_SCHANNEL or USE_SECTRANSP */ diff --git a/third_party/curl/lib/vtls/x509asn1.h b/third_party/curl/lib/vtls/x509asn1.h new file mode 100644 index 0000000..23a67b8 --- /dev/null +++ b/third_party/curl/lib/vtls/x509asn1.h @@ -0,0 +1,80 @@ +#ifndef HEADER_CURL_X509ASN1_H +#define HEADER_CURL_X509ASN1_H + +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_GNUTLS) || defined(USE_WOLFSSL) || \ + defined(USE_SCHANNEL) || defined(USE_SECTRANSP) + +#include "cfilters.h" +#include "urldata.h" + +/* + * Types. + */ + +/* ASN.1 parsed element. */ +struct Curl_asn1Element { + const char *header; /* Pointer to header byte. */ + const char *beg; /* Pointer to element data. */ + const char *end; /* Pointer to 1st byte after element. */ + unsigned char class; /* ASN.1 element class. */ + unsigned char tag; /* ASN.1 element tag. */ + bool constructed; /* Element is constructed. */ +}; + +/* X509 certificate: RFC 5280. */ +struct Curl_X509certificate { + struct Curl_asn1Element certificate; + struct Curl_asn1Element version; + struct Curl_asn1Element serialNumber; + struct Curl_asn1Element signatureAlgorithm; + struct Curl_asn1Element signature; + struct Curl_asn1Element issuer; + struct Curl_asn1Element notBefore; + struct Curl_asn1Element notAfter; + struct Curl_asn1Element subject; + struct Curl_asn1Element subjectPublicKeyInfo; + struct Curl_asn1Element subjectPublicKeyAlgorithm; + struct Curl_asn1Element subjectPublicKey; + struct Curl_asn1Element issuerUniqueID; + struct Curl_asn1Element subjectUniqueID; + struct Curl_asn1Element extensions; +}; + +/* + * Prototypes. + */ + +int Curl_parseX509(struct Curl_X509certificate *cert, + const char *beg, const char *end); +CURLcode Curl_extract_certinfo(struct Curl_easy *data, int certnum, + const char *beg, const char *end); +CURLcode Curl_verifyhost(struct Curl_cfilter *cf, struct Curl_easy *data, + const char *beg, const char *end); +#endif /* USE_GNUTLS or USE_WOLFSSL or USE_SCHANNEL or USE_SECTRANSP */ +#endif /* HEADER_CURL_X509ASN1_H */ diff --git a/third_party/curl/lib/warnless.c b/third_party/curl/lib/warnless.c new file mode 100644 index 0000000..c80937b --- /dev/null +++ b/third_party/curl/lib/warnless.c @@ -0,0 +1,386 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(__INTEL_COMPILER) && defined(__unix__) + +#ifdef HAVE_NETINET_IN_H +# include +#endif +#ifdef HAVE_ARPA_INET_H +# include +#endif + +#endif /* __INTEL_COMPILER && __unix__ */ + +#include "warnless.h" + +#ifdef _WIN32 +#undef read +#undef write +#endif + +#include + +#define CURL_MASK_UCHAR ((unsigned char)~0) +#define CURL_MASK_SCHAR (CURL_MASK_UCHAR >> 1) + +#define CURL_MASK_USHORT ((unsigned short)~0) +#define CURL_MASK_SSHORT (CURL_MASK_USHORT >> 1) + +#define CURL_MASK_UINT ((unsigned int)~0) +#define CURL_MASK_SINT (CURL_MASK_UINT >> 1) + +#define CURL_MASK_ULONG ((unsigned long)~0) +#define CURL_MASK_SLONG (CURL_MASK_ULONG >> 1) + +#define CURL_MASK_UCOFFT ((unsigned CURL_TYPEOF_CURL_OFF_T)~0) +#define CURL_MASK_SCOFFT (CURL_MASK_UCOFFT >> 1) + +#define CURL_MASK_USIZE_T ((size_t)~0) +#define CURL_MASK_SSIZE_T (CURL_MASK_USIZE_T >> 1) + +/* +** unsigned long to unsigned short +*/ + +unsigned short curlx_ultous(unsigned long ulnum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(ulnum <= (unsigned long) CURL_MASK_USHORT); + return (unsigned short)(ulnum & (unsigned long) CURL_MASK_USHORT); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif +} + +/* +** unsigned long to unsigned char +*/ + +unsigned char curlx_ultouc(unsigned long ulnum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(ulnum <= (unsigned long) CURL_MASK_UCHAR); + return (unsigned char)(ulnum & (unsigned long) CURL_MASK_UCHAR); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif +} + +/* +** unsigned size_t to signed curl_off_t +*/ + +curl_off_t curlx_uztoso(size_t uznum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#elif defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable:4310) /* cast truncates constant value */ +#endif + + DEBUGASSERT(uznum <= (size_t) CURL_MASK_SCOFFT); + return (curl_off_t)(uznum & (size_t) CURL_MASK_SCOFFT); + +#if defined(__INTEL_COMPILER) || defined(_MSC_VER) +# pragma warning(pop) +#endif +} + +/* +** unsigned size_t to signed int +*/ + +int curlx_uztosi(size_t uznum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(uznum <= (size_t) CURL_MASK_SINT); + return (int)(uznum & (size_t) CURL_MASK_SINT); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif +} + +/* +** unsigned size_t to unsigned long +*/ + +unsigned long curlx_uztoul(size_t uznum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + +#if ULONG_MAX < SIZE_T_MAX + DEBUGASSERT(uznum <= (size_t) CURL_MASK_ULONG); +#endif + return (unsigned long)(uznum & (size_t) CURL_MASK_ULONG); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif +} + +/* +** unsigned size_t to unsigned int +*/ + +unsigned int curlx_uztoui(size_t uznum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + +#if UINT_MAX < SIZE_T_MAX + DEBUGASSERT(uznum <= (size_t) CURL_MASK_UINT); +#endif + return (unsigned int)(uznum & (size_t) CURL_MASK_UINT); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif +} + +/* +** signed long to signed int +*/ + +int curlx_sltosi(long slnum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(slnum >= 0); +#if INT_MAX < LONG_MAX + DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_SINT); +#endif + return (int)(slnum & (long) CURL_MASK_SINT); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif +} + +/* +** signed long to unsigned int +*/ + +unsigned int curlx_sltoui(long slnum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(slnum >= 0); +#if UINT_MAX < LONG_MAX + DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_UINT); +#endif + return (unsigned int)(slnum & (long) CURL_MASK_UINT); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif +} + +/* +** signed long to unsigned short +*/ + +unsigned short curlx_sltous(long slnum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(slnum >= 0); + DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_USHORT); + return (unsigned short)(slnum & (long) CURL_MASK_USHORT); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif +} + +/* +** unsigned size_t to signed ssize_t +*/ + +ssize_t curlx_uztosz(size_t uznum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(uznum <= (size_t) CURL_MASK_SSIZE_T); + return (ssize_t)(uznum & (size_t) CURL_MASK_SSIZE_T); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif +} + +/* +** signed curl_off_t to unsigned size_t +*/ + +size_t curlx_sotouz(curl_off_t sonum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(sonum >= 0); + return (size_t)(sonum & (curl_off_t) CURL_MASK_USIZE_T); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif +} + +/* +** signed ssize_t to signed int +*/ + +int curlx_sztosi(ssize_t sznum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(sznum >= 0); +#if INT_MAX < SSIZE_T_MAX + DEBUGASSERT((size_t) sznum <= (size_t) CURL_MASK_SINT); +#endif + return (int)(sznum & (ssize_t) CURL_MASK_SINT); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif +} + +/* +** unsigned int to unsigned short +*/ + +unsigned short curlx_uitous(unsigned int uinum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(uinum <= (unsigned int) CURL_MASK_USHORT); + return (unsigned short) (uinum & (unsigned int) CURL_MASK_USHORT); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif +} + +/* +** signed int to unsigned size_t +*/ + +size_t curlx_sitouz(int sinum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(sinum >= 0); + return (size_t) sinum; + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif +} + +#ifdef USE_WINSOCK + +/* +** curl_socket_t to signed int +*/ + +int curlx_sktosi(curl_socket_t s) +{ + return (int)((ssize_t) s); +} + +/* +** signed int to curl_socket_t +*/ + +curl_socket_t curlx_sitosk(int i) +{ + return (curl_socket_t)((ssize_t) i); +} + +#endif /* USE_WINSOCK */ + +#if defined(_WIN32) + +ssize_t curlx_read(int fd, void *buf, size_t count) +{ + return (ssize_t)read(fd, buf, curlx_uztoui(count)); +} + +ssize_t curlx_write(int fd, const void *buf, size_t count) +{ + return (ssize_t)write(fd, buf, curlx_uztoui(count)); +} + +#endif /* _WIN32 */ + +/* Ensure that warnless.h redefinitions continue to have an effect + in "unity" builds. */ +#undef HEADER_CURL_WARNLESS_H_REDEFS diff --git a/third_party/curl/lib/warnless.h b/third_party/curl/lib/warnless.h new file mode 100644 index 0000000..6adf63a --- /dev/null +++ b/third_party/curl/lib/warnless.h @@ -0,0 +1,92 @@ +#ifndef HEADER_CURL_WARNLESS_H +#define HEADER_CURL_WARNLESS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_WINSOCK +#include /* for curl_socket_t */ +#endif + +#define CURLX_FUNCTION_CAST(target_type, func) \ + (target_type)(void (*) (void))(func) + +unsigned short curlx_ultous(unsigned long ulnum); + +unsigned char curlx_ultouc(unsigned long ulnum); + +int curlx_uztosi(size_t uznum); + +curl_off_t curlx_uztoso(size_t uznum); + +unsigned long curlx_uztoul(size_t uznum); + +unsigned int curlx_uztoui(size_t uznum); + +int curlx_sltosi(long slnum); + +unsigned int curlx_sltoui(long slnum); + +unsigned short curlx_sltous(long slnum); + +ssize_t curlx_uztosz(size_t uznum); + +size_t curlx_sotouz(curl_off_t sonum); + +int curlx_sztosi(ssize_t sznum); + +unsigned short curlx_uitous(unsigned int uinum); + +size_t curlx_sitouz(int sinum); + +#ifdef USE_WINSOCK + +int curlx_sktosi(curl_socket_t s); + +curl_socket_t curlx_sitosk(int i); + +#endif /* USE_WINSOCK */ + +#if defined(_WIN32) + +ssize_t curlx_read(int fd, void *buf, size_t count); + +ssize_t curlx_write(int fd, const void *buf, size_t count); + +#endif /* _WIN32 */ + +#endif /* HEADER_CURL_WARNLESS_H */ + +#ifndef HEADER_CURL_WARNLESS_H_REDEFS +#define HEADER_CURL_WARNLESS_H_REDEFS + +#if defined(_WIN32) +#undef read +#define read(fd, buf, count) curlx_read(fd, buf, count) +#undef write +#define write(fd, buf, count) curlx_write(fd, buf, count) +#endif + +#endif /* HEADER_CURL_WARNLESS_H_REDEFS */ diff --git a/third_party/curl/lib/ws.c b/third_party/curl/lib/ws.c new file mode 100644 index 0000000..6ccf9e6 --- /dev/null +++ b/third_party/curl/lib/ws.c @@ -0,0 +1,1271 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include + +#if defined(USE_WEBSOCKETS) && !defined(CURL_DISABLE_HTTP) + +#include "urldata.h" +#include "bufq.h" +#include "dynbuf.h" +#include "rand.h" +#include "curl_base64.h" +#include "connect.h" +#include "sendf.h" +#include "multiif.h" +#include "ws.h" +#include "easyif.h" +#include "transfer.h" +#include "nonblock.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +#define WSBIT_FIN 0x80 +#define WSBIT_OPCODE_CONT 0 +#define WSBIT_OPCODE_TEXT (1) +#define WSBIT_OPCODE_BIN (2) +#define WSBIT_OPCODE_CLOSE (8) +#define WSBIT_OPCODE_PING (9) +#define WSBIT_OPCODE_PONG (0xa) +#define WSBIT_OPCODE_MASK (0xf) + +#define WSBIT_MASK 0x80 + +/* buffer dimensioning */ +#define WS_CHUNK_SIZE 65535 +#define WS_CHUNK_COUNT 2 + +struct ws_frame_meta { + char proto_opcode; + int flags; + const char *name; +}; + +static struct ws_frame_meta WS_FRAMES[] = { + { WSBIT_OPCODE_CONT, CURLWS_CONT, "CONT" }, + { WSBIT_OPCODE_TEXT, CURLWS_TEXT, "TEXT" }, + { WSBIT_OPCODE_BIN, CURLWS_BINARY, "BIN" }, + { WSBIT_OPCODE_CLOSE, CURLWS_CLOSE, "CLOSE" }, + { WSBIT_OPCODE_PING, CURLWS_PING, "PING" }, + { WSBIT_OPCODE_PONG, CURLWS_PONG, "PONG" }, +}; + +static const char *ws_frame_name_of_op(unsigned char proto_opcode) +{ + unsigned char opcode = proto_opcode & WSBIT_OPCODE_MASK; + size_t i; + for(i = 0; i < sizeof(WS_FRAMES)/sizeof(WS_FRAMES[0]); ++i) { + if(WS_FRAMES[i].proto_opcode == opcode) + return WS_FRAMES[i].name; + } + return "???"; +} + +static int ws_frame_op2flags(unsigned char proto_opcode) +{ + unsigned char opcode = proto_opcode & WSBIT_OPCODE_MASK; + size_t i; + for(i = 0; i < sizeof(WS_FRAMES)/sizeof(WS_FRAMES[0]); ++i) { + if(WS_FRAMES[i].proto_opcode == opcode) + return WS_FRAMES[i].flags; + } + return 0; +} + +static unsigned char ws_frame_flags2op(int flags) +{ + size_t i; + for(i = 0; i < sizeof(WS_FRAMES)/sizeof(WS_FRAMES[0]); ++i) { + if(WS_FRAMES[i].flags & flags) + return WS_FRAMES[i].proto_opcode; + } + return 0; +} + +static void ws_dec_info(struct ws_decoder *dec, struct Curl_easy *data, + const char *msg) +{ + switch(dec->head_len) { + case 0: + break; + case 1: + CURL_TRC_WRITE(data, "websocket, decoded %s [%s%s]", msg, + ws_frame_name_of_op(dec->head[0]), + (dec->head[0] & WSBIT_FIN)? "" : " NON-FINAL"); + break; + default: + if(dec->head_len < dec->head_total) { + CURL_TRC_WRITE(data, "websocket, decoded %s [%s%s](%d/%d)", msg, + ws_frame_name_of_op(dec->head[0]), + (dec->head[0] & WSBIT_FIN)? "" : " NON-FINAL", + dec->head_len, dec->head_total); + } + else { + CURL_TRC_WRITE(data, "websocket, decoded %s [%s%s payload=%" + CURL_FORMAT_CURL_OFF_T "/%" CURL_FORMAT_CURL_OFF_T "]", + msg, ws_frame_name_of_op(dec->head[0]), + (dec->head[0] & WSBIT_FIN)? "" : " NON-FINAL", + dec->payload_offset, dec->payload_len); + } + break; + } +} + +typedef ssize_t ws_write_payload(const unsigned char *buf, size_t buflen, + int frame_age, int frame_flags, + curl_off_t payload_offset, + curl_off_t payload_len, + void *userp, + CURLcode *err); + + +static void ws_dec_reset(struct ws_decoder *dec) +{ + dec->frame_age = 0; + dec->frame_flags = 0; + dec->payload_offset = 0; + dec->payload_len = 0; + dec->head_len = dec->head_total = 0; + dec->state = WS_DEC_INIT; +} + +static void ws_dec_init(struct ws_decoder *dec) +{ + ws_dec_reset(dec); +} + +static CURLcode ws_dec_read_head(struct ws_decoder *dec, + struct Curl_easy *data, + struct bufq *inraw) +{ + const unsigned char *inbuf; + size_t inlen; + + while(Curl_bufq_peek(inraw, &inbuf, &inlen)) { + if(dec->head_len == 0) { + dec->head[0] = *inbuf; + Curl_bufq_skip(inraw, 1); + + dec->frame_flags = ws_frame_op2flags(dec->head[0]); + if(!dec->frame_flags) { + failf(data, "WS: unknown opcode: %x", dec->head[0]); + ws_dec_reset(dec); + return CURLE_RECV_ERROR; + } + dec->head_len = 1; + /* ws_dec_info(dec, data, "seeing opcode"); */ + continue; + } + else if(dec->head_len == 1) { + dec->head[1] = *inbuf; + Curl_bufq_skip(inraw, 1); + dec->head_len = 2; + + if(dec->head[1] & WSBIT_MASK) { + /* A client MUST close a connection if it detects a masked frame. */ + failf(data, "WS: masked input frame"); + ws_dec_reset(dec); + return CURLE_RECV_ERROR; + } + /* How long is the frame head? */ + if(dec->head[1] == 126) { + dec->head_total = 4; + continue; + } + else if(dec->head[1] == 127) { + dec->head_total = 10; + continue; + } + else { + dec->head_total = 2; + } + } + + if(dec->head_len < dec->head_total) { + dec->head[dec->head_len] = *inbuf; + Curl_bufq_skip(inraw, 1); + ++dec->head_len; + if(dec->head_len < dec->head_total) { + /* ws_dec_info(dec, data, "decoding head"); */ + continue; + } + } + /* got the complete frame head */ + DEBUGASSERT(dec->head_len == dec->head_total); + switch(dec->head_total) { + case 2: + dec->payload_len = dec->head[1]; + break; + case 4: + dec->payload_len = (dec->head[2] << 8) | dec->head[3]; + break; + case 10: + if(dec->head[2] > 127) { + failf(data, "WS: frame length longer than 64 signed not supported"); + return CURLE_RECV_ERROR; + } + dec->payload_len = ((curl_off_t)dec->head[2] << 56) | + (curl_off_t)dec->head[3] << 48 | + (curl_off_t)dec->head[4] << 40 | + (curl_off_t)dec->head[5] << 32 | + (curl_off_t)dec->head[6] << 24 | + (curl_off_t)dec->head[7] << 16 | + (curl_off_t)dec->head[8] << 8 | + dec->head[9]; + break; + default: + /* this should never happen */ + DEBUGASSERT(0); + failf(data, "WS: unexpected frame header length"); + return CURLE_RECV_ERROR; + } + + dec->frame_age = 0; + dec->payload_offset = 0; + ws_dec_info(dec, data, "decoded"); + return CURLE_OK; + } + return CURLE_AGAIN; +} + +static CURLcode ws_dec_pass_payload(struct ws_decoder *dec, + struct Curl_easy *data, + struct bufq *inraw, + ws_write_payload *write_payload, + void *write_ctx) +{ + const unsigned char *inbuf; + size_t inlen; + ssize_t nwritten; + CURLcode result; + curl_off_t remain = dec->payload_len - dec->payload_offset; + + (void)data; + while(remain && Curl_bufq_peek(inraw, &inbuf, &inlen)) { + if((curl_off_t)inlen > remain) + inlen = (size_t)remain; + nwritten = write_payload(inbuf, inlen, dec->frame_age, dec->frame_flags, + dec->payload_offset, dec->payload_len, + write_ctx, &result); + if(nwritten < 0) + return result; + Curl_bufq_skip(inraw, (size_t)nwritten); + dec->payload_offset += (curl_off_t)nwritten; + remain = dec->payload_len - dec->payload_offset; + CURL_TRC_WRITE(data, "websocket, passed %zd bytes payload, %" + CURL_FORMAT_CURL_OFF_T " remain", nwritten, remain); + } + + return remain? CURLE_AGAIN : CURLE_OK; +} + +static CURLcode ws_dec_pass(struct ws_decoder *dec, + struct Curl_easy *data, + struct bufq *inraw, + ws_write_payload *write_payload, + void *write_ctx) +{ + CURLcode result; + + if(Curl_bufq_is_empty(inraw)) + return CURLE_AGAIN; + + switch(dec->state) { + case WS_DEC_INIT: + ws_dec_reset(dec); + dec->state = WS_DEC_HEAD; + FALLTHROUGH(); + case WS_DEC_HEAD: + result = ws_dec_read_head(dec, data, inraw); + if(result) { + if(result != CURLE_AGAIN) { + infof(data, "WS: decode error %d", (int)result); + break; /* real error */ + } + /* incomplete ws frame head */ + DEBUGASSERT(Curl_bufq_is_empty(inraw)); + break; + } + /* head parsing done */ + dec->state = WS_DEC_PAYLOAD; + if(dec->payload_len == 0) { + ssize_t nwritten; + const unsigned char tmp = '\0'; + /* special case of a 0 length frame, need to write once */ + nwritten = write_payload(&tmp, 0, dec->frame_age, dec->frame_flags, + 0, 0, write_ctx, &result); + if(nwritten < 0) + return result; + dec->state = WS_DEC_INIT; + break; + } + FALLTHROUGH(); + case WS_DEC_PAYLOAD: + result = ws_dec_pass_payload(dec, data, inraw, write_payload, write_ctx); + ws_dec_info(dec, data, "passing"); + if(result) + return result; + /* paylod parsing done */ + dec->state = WS_DEC_INIT; + break; + default: + /* we covered all enums above, but some code analyzers are whimps */ + result = CURLE_FAILED_INIT; + } + return result; +} + +static void update_meta(struct websocket *ws, + int frame_age, int frame_flags, + curl_off_t payload_offset, + curl_off_t payload_len, + size_t cur_len) +{ + ws->frame.age = frame_age; + ws->frame.flags = frame_flags; + ws->frame.offset = payload_offset; + ws->frame.len = cur_len; + ws->frame.bytesleft = (payload_len - payload_offset - cur_len); +} + +/* WebSockets decoding client writer */ +struct ws_cw_ctx { + struct Curl_cwriter super; + struct bufq buf; +}; + +static CURLcode ws_cw_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct ws_cw_ctx *ctx = writer->ctx; + (void)data; + Curl_bufq_init2(&ctx->buf, WS_CHUNK_SIZE, 1, BUFQ_OPT_SOFT_LIMIT); + return CURLE_OK; +} + +static void ws_cw_close(struct Curl_easy *data, struct Curl_cwriter *writer) +{ + struct ws_cw_ctx *ctx = writer->ctx; + (void) data; + Curl_bufq_free(&ctx->buf); +} + +struct ws_cw_dec_ctx { + struct Curl_easy *data; + struct websocket *ws; + struct Curl_cwriter *next_writer; + int cw_type; +}; + +static ssize_t ws_cw_dec_next(const unsigned char *buf, size_t buflen, + int frame_age, int frame_flags, + curl_off_t payload_offset, + curl_off_t payload_len, + void *user_data, + CURLcode *err) +{ + struct ws_cw_dec_ctx *ctx = user_data; + struct Curl_easy *data = ctx->data; + struct websocket *ws = ctx->ws; + curl_off_t remain = (payload_len - (payload_offset + buflen)); + + (void)frame_age; + if((frame_flags & CURLWS_PING) && !remain) { + /* auto-respond to PINGs, only works for single-frame payloads atm */ + size_t bytes; + infof(data, "WS: auto-respond to PING with a PONG"); + /* send back the exact same content as a PONG */ + *err = curl_ws_send(data, buf, buflen, &bytes, 0, CURLWS_PONG); + if(*err) + return -1; + } + else if(buflen || !remain) { + /* forward the decoded frame to the next client writer. */ + update_meta(ws, frame_age, frame_flags, payload_offset, + payload_len, buflen); + + *err = Curl_cwriter_write(data, ctx->next_writer, ctx->cw_type, + (const char *)buf, buflen); + if(*err) + return -1; + } + *err = CURLE_OK; + return (ssize_t)buflen; +} + +static CURLcode ws_cw_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + struct ws_cw_ctx *ctx = writer->ctx; + struct websocket *ws; + CURLcode result; + + if(!(type & CLIENTWRITE_BODY) || data->set.ws_raw_mode) + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); + + ws = data->conn->proto.ws; + if(!ws) { + failf(data, "WS: not a websocket transfer"); + return CURLE_FAILED_INIT; + } + + if(nbytes) { + ssize_t nwritten; + nwritten = Curl_bufq_write(&ctx->buf, (const unsigned char *)buf, + nbytes, &result); + if(nwritten < 0) { + infof(data, "WS: error adding data to buffer %d", result); + return result; + } + } + + while(!Curl_bufq_is_empty(&ctx->buf)) { + struct ws_cw_dec_ctx pass_ctx; + pass_ctx.data = data; + pass_ctx.ws = ws; + pass_ctx.next_writer = writer->next; + pass_ctx.cw_type = type; + result = ws_dec_pass(&ws->dec, data, &ctx->buf, + ws_cw_dec_next, &pass_ctx); + if(result == CURLE_AGAIN) { + /* insufficient amount of data, keep it for later. + * we pretend to have written all since we have a copy */ + CURL_TRC_WRITE(data, "websocket, buffered incomplete frame head"); + return CURLE_OK; + } + else if(result) { + infof(data, "WS: decode error %d", (int)result); + return result; + } + } + + if((type & CLIENTWRITE_EOS) && !Curl_bufq_is_empty(&ctx->buf)) { + infof(data, "WS: decode ending with %zd frame bytes remaining", + Curl_bufq_len(&ctx->buf)); + return CURLE_RECV_ERROR; + } + + return CURLE_OK; +} + +/* WebSocket payload decoding client writer. */ +static const struct Curl_cwtype ws_cw_decode = { + "ws-decode", + NULL, + ws_cw_init, + ws_cw_write, + ws_cw_close, + sizeof(struct ws_cw_ctx) +}; + + +static void ws_enc_info(struct ws_encoder *enc, struct Curl_easy *data, + const char *msg) +{ + infof(data, "WS-ENC: %s [%s%s%s payload=%" CURL_FORMAT_CURL_OFF_T + "/%" CURL_FORMAT_CURL_OFF_T "]", + msg, ws_frame_name_of_op(enc->firstbyte), + (enc->firstbyte & WSBIT_OPCODE_MASK) == WSBIT_OPCODE_CONT ? + " CONT" : "", + (enc->firstbyte & WSBIT_FIN)? "" : " NON-FIN", + enc->payload_len - enc->payload_remain, enc->payload_len); +} + +static void ws_enc_reset(struct ws_encoder *enc) +{ + enc->payload_remain = 0; + enc->xori = 0; + enc->contfragment = FALSE; +} + +static void ws_enc_init(struct ws_encoder *enc) +{ + ws_enc_reset(enc); +} + +/*** + RFC 6455 Section 5.2 + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-------+-+-------------+-------------------------------+ + |F|R|R|R| opcode|M| Payload len | Extended payload length | + |I|S|S|S| (4) |A| (7) | (16/64) | + |N|V|V|V| |S| | (if payload len==126/127) | + | |1|2|3| |K| | | + +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + + | Extended payload length continued, if payload len == 127 | + + - - - - - - - - - - - - - - - +-------------------------------+ + | |Masking-key, if MASK set to 1 | + +-------------------------------+-------------------------------+ + | Masking-key (continued) | Payload Data | + +-------------------------------- - - - - - - - - - - - - - - - + + : Payload Data continued ... : + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + | Payload Data continued ... | + +---------------------------------------------------------------+ +*/ + +static ssize_t ws_enc_write_head(struct Curl_easy *data, + struct ws_encoder *enc, + unsigned int flags, + curl_off_t payload_len, + struct bufq *out, + CURLcode *err) +{ + unsigned char firstbyte = 0; + unsigned char opcode; + unsigned char head[14]; + size_t hlen; + ssize_t n; + + if(payload_len < 0) { + failf(data, "WS: starting new frame with negative payload length %" + CURL_FORMAT_CURL_OFF_T, payload_len); + *err = CURLE_SEND_ERROR; + return -1; + } + + if(enc->payload_remain > 0) { + /* trying to write a new frame before the previous one is finished */ + failf(data, "WS: starting new frame with %zd bytes from last one" + "remaining to be sent", (ssize_t)enc->payload_remain); + *err = CURLE_SEND_ERROR; + return -1; + } + + opcode = ws_frame_flags2op(flags); + if(!opcode) { + failf(data, "WS: provided flags not recognized '%x'", flags); + *err = CURLE_SEND_ERROR; + return -1; + } + + if(!(flags & CURLWS_CONT)) { + if(!enc->contfragment) + /* not marked as continuing, this is the final fragment */ + firstbyte |= WSBIT_FIN | opcode; + else + /* marked as continuing, this is the final fragment; set CONT + opcode and FIN bit */ + firstbyte |= WSBIT_FIN | WSBIT_OPCODE_CONT; + + enc->contfragment = FALSE; + } + else if(enc->contfragment) { + /* the previous fragment was not a final one and this isn't either, keep a + CONT opcode and no FIN bit */ + firstbyte |= WSBIT_OPCODE_CONT; + } + else { + firstbyte = opcode; + enc->contfragment = TRUE; + } + + head[0] = enc->firstbyte = firstbyte; + if(payload_len > 65535) { + head[1] = 127 | WSBIT_MASK; + head[2] = (unsigned char)((payload_len >> 56) & 0xff); + head[3] = (unsigned char)((payload_len >> 48) & 0xff); + head[4] = (unsigned char)((payload_len >> 40) & 0xff); + head[5] = (unsigned char)((payload_len >> 32) & 0xff); + head[6] = (unsigned char)((payload_len >> 24) & 0xff); + head[7] = (unsigned char)((payload_len >> 16) & 0xff); + head[8] = (unsigned char)((payload_len >> 8) & 0xff); + head[9] = (unsigned char)(payload_len & 0xff); + hlen = 10; + } + else if(payload_len >= 126) { + head[1] = 126 | WSBIT_MASK; + head[2] = (unsigned char)((payload_len >> 8) & 0xff); + head[3] = (unsigned char)(payload_len & 0xff); + hlen = 4; + } + else { + head[1] = (unsigned char)payload_len | WSBIT_MASK; + hlen = 2; + } + + enc->payload_remain = enc->payload_len = payload_len; + ws_enc_info(enc, data, "sending"); + + /* add 4 bytes mask */ + memcpy(&head[hlen], &enc->mask, 4); + hlen += 4; + /* reset for payload to come */ + enc->xori = 0; + + n = Curl_bufq_write(out, head, hlen, err); + if(n < 0) + return -1; + if((size_t)n != hlen) { + /* We use a bufq with SOFT_LIMIT, writing should always succeed */ + DEBUGASSERT(0); + *err = CURLE_SEND_ERROR; + return -1; + } + return n; +} + +static ssize_t ws_enc_write_payload(struct ws_encoder *enc, + struct Curl_easy *data, + const unsigned char *buf, size_t buflen, + struct bufq *out, CURLcode *err) +{ + ssize_t n; + size_t i, len; + + if(Curl_bufq_is_full(out)) { + *err = CURLE_AGAIN; + return -1; + } + + /* not the most performant way to do this */ + len = buflen; + if((curl_off_t)len > enc->payload_remain) + len = (size_t)enc->payload_remain; + + for(i = 0; i < len; ++i) { + unsigned char c = buf[i] ^ enc->mask[enc->xori]; + n = Curl_bufq_write(out, &c, 1, err); + if(n < 0) { + if((*err != CURLE_AGAIN) || !i) + return -1; + break; + } + enc->xori++; + enc->xori &= 3; + } + enc->payload_remain -= (curl_off_t)i; + ws_enc_info(enc, data, "buffered"); + return (ssize_t)i; +} + + +struct wsfield { + const char *name; + const char *val; +}; + +CURLcode Curl_ws_request(struct Curl_easy *data, REQTYPE *req) +{ + unsigned int i; + CURLcode result = CURLE_OK; + unsigned char rand[16]; + char *randstr; + size_t randlen; + char keyval[40]; + struct SingleRequest *k = &data->req; + struct wsfield heads[]= { + { + /* The request MUST contain an |Upgrade| header field whose value + MUST include the "websocket" keyword. */ + "Upgrade:", "websocket" + }, + { + /* The request MUST contain a |Connection| header field whose value + MUST include the "Upgrade" token. */ + "Connection:", "Upgrade", + }, + { + /* The request MUST include a header field with the name + |Sec-WebSocket-Version|. The value of this header field MUST be + 13. */ + "Sec-WebSocket-Version:", "13", + }, + { + /* The request MUST include a header field with the name + |Sec-WebSocket-Key|. The value of this header field MUST be a nonce + consisting of a randomly selected 16-byte value that has been + base64-encoded (see Section 4 of [RFC4648]). The nonce MUST be + selected randomly for each connection. */ + "Sec-WebSocket-Key:", NULL, + } + }; + heads[3].val = &keyval[0]; + + /* 16 bytes random */ + result = Curl_rand(data, (unsigned char *)rand, sizeof(rand)); + if(result) + return result; + result = Curl_base64_encode((char *)rand, sizeof(rand), &randstr, &randlen); + if(result) + return result; + DEBUGASSERT(randlen < sizeof(keyval)); + if(randlen >= sizeof(keyval)) { + free(randstr); + return CURLE_FAILED_INIT; + } + strcpy(keyval, randstr); + free(randstr); + for(i = 0; !result && (i < sizeof(heads)/sizeof(heads[0])); i++) { + if(!Curl_checkheaders(data, STRCONST(heads[i].name))) { +#ifdef USE_HYPER + char field[128]; + msnprintf(field, sizeof(field), "%s %s", heads[i].name, + heads[i].val); + result = Curl_hyper_header(data, req, field); +#else + (void)data; + result = Curl_dyn_addf(req, "%s %s\r\n", heads[i].name, + heads[i].val); +#endif + } + } + k->upgr101 = UPGR101_WS; + return result; +} + +/* + * 'nread' is number of bytes of websocket data already in the buffer at + * 'mem'. + */ +CURLcode Curl_ws_accept(struct Curl_easy *data, + const char *mem, size_t nread) +{ + struct SingleRequest *k = &data->req; + struct websocket *ws; + struct Curl_cwriter *ws_dec_writer; + CURLcode result; + + DEBUGASSERT(data->conn); + ws = data->conn->proto.ws; + if(!ws) { + size_t chunk_size = WS_CHUNK_SIZE; + ws = calloc(1, sizeof(*ws)); + if(!ws) + return CURLE_OUT_OF_MEMORY; + data->conn->proto.ws = ws; +#ifdef DEBUGBUILD + { + char *p = getenv("CURL_WS_CHUNK_SIZE"); + if(p) { + long l = strtol(p, NULL, 10); + if(l > 0 && l <= (1*1024*1024)) { + chunk_size = (size_t)l; + } + } + } +#endif + DEBUGF(infof(data, "WS, using chunk size %zu", chunk_size)); + Curl_bufq_init2(&ws->recvbuf, chunk_size, WS_CHUNK_COUNT, + BUFQ_OPT_SOFT_LIMIT); + Curl_bufq_init2(&ws->sendbuf, chunk_size, WS_CHUNK_COUNT, + BUFQ_OPT_SOFT_LIMIT); + ws_dec_init(&ws->dec); + ws_enc_init(&ws->enc); + } + else { + Curl_bufq_reset(&ws->recvbuf); + ws_dec_reset(&ws->dec); + ws_enc_reset(&ws->enc); + } + /* Verify the Sec-WebSocket-Accept response. + + The sent value is the base64 encoded version of a SHA-1 hash done on the + |Sec-WebSocket-Key| header field concatenated with + the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11". + */ + + /* If the response includes a |Sec-WebSocket-Extensions| header field and + this header field indicates the use of an extension that was not present + in the client's handshake (the server has indicated an extension not + requested by the client), the client MUST Fail the WebSocket Connection. + */ + + /* If the response includes a |Sec-WebSocket-Protocol| header field + and this header field indicates the use of a subprotocol that was + not present in the client's handshake (the server has indicated a + subprotocol not requested by the client), the client MUST Fail + the WebSocket Connection. */ + + /* 4 bytes random */ + + result = Curl_rand(data, (unsigned char *)&ws->enc.mask, + sizeof(ws->enc.mask)); + if(result) + return result; + infof(data, "Received 101, switch to WebSocket; mask %02x%02x%02x%02x", + ws->enc.mask[0], ws->enc.mask[1], ws->enc.mask[2], ws->enc.mask[3]); + + /* Install our client writer that decodes WS frames payload */ + result = Curl_cwriter_create(&ws_dec_writer, data, &ws_cw_decode, + CURL_CW_CONTENT_DECODE); + if(result) + return result; + + result = Curl_cwriter_add(data, ws_dec_writer); + if(result) { + Curl_cwriter_free(data, ws_dec_writer); + return result; + } + + if(data->set.connect_only) { + ssize_t nwritten; + /* In CONNECT_ONLY setup, the payloads from `mem` need to be received + * when using `curl_ws_recv` later on after this transfer is already + * marked as DONE. */ + nwritten = Curl_bufq_write(&ws->recvbuf, (const unsigned char *)mem, + nread, &result); + if(nwritten < 0) + return result; + infof(data, "%zu bytes websocket payload", nread); + } + else { /* !connect_only */ + /* And pass any additional data to the writers */ + if(nread) { + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)mem, nread); + } + } + k->upgr101 = UPGR101_RECEIVED; + + return result; +} + +struct ws_collect { + struct Curl_easy *data; + unsigned char *buffer; + size_t buflen; + size_t bufidx; + int frame_age; + int frame_flags; + curl_off_t payload_offset; + curl_off_t payload_len; + bool written; +}; + +static ssize_t ws_client_collect(const unsigned char *buf, size_t buflen, + int frame_age, int frame_flags, + curl_off_t payload_offset, + curl_off_t payload_len, + void *userp, + CURLcode *err) +{ + struct ws_collect *ctx = userp; + size_t nwritten; + curl_off_t remain = (payload_len - (payload_offset + buflen)); + + if(!ctx->bufidx) { + /* first write */ + ctx->frame_age = frame_age; + ctx->frame_flags = frame_flags; + ctx->payload_offset = payload_offset; + ctx->payload_len = payload_len; + } + + if((frame_flags & CURLWS_PING) && !remain) { + /* auto-respond to PINGs, only works for single-frame payloads atm */ + size_t bytes; + infof(ctx->data, "WS: auto-respond to PING with a PONG"); + /* send back the exact same content as a PONG */ + *err = curl_ws_send(ctx->data, buf, buflen, &bytes, 0, CURLWS_PONG); + if(*err) + return -1; + nwritten = bytes; + } + else { + ctx->written = TRUE; + DEBUGASSERT(ctx->buflen >= ctx->bufidx); + nwritten = CURLMIN(buflen, ctx->buflen - ctx->bufidx); + if(!nwritten) { + if(!buflen) { /* 0 length write, we accept that */ + *err = CURLE_OK; + return 0; + } + *err = CURLE_AGAIN; /* no more space */ + return -1; + } + *err = CURLE_OK; + memcpy(ctx->buffer + ctx->bufidx, buf, nwritten); + ctx->bufidx += nwritten; + } + return nwritten; +} + +static ssize_t nw_in_recv(void *reader_ctx, + unsigned char *buf, size_t buflen, + CURLcode *err) +{ + struct Curl_easy *data = reader_ctx; + size_t nread; + + *err = curl_easy_recv(data, buf, buflen, &nread); + if(*err) + return -1; + return (ssize_t)nread; +} + +CURL_EXTERN CURLcode curl_ws_recv(struct Curl_easy *data, void *buffer, + size_t buflen, size_t *nread, + const struct curl_ws_frame **metap) +{ + struct connectdata *conn = data->conn; + struct websocket *ws; + bool done = FALSE; /* not filled passed buffer yet */ + struct ws_collect ctx; + CURLcode result; + + if(!conn) { + /* Unhappy hack with lifetimes of transfers and connection */ + if(!data->set.connect_only) { + failf(data, "CONNECT_ONLY is required"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + + Curl_getconnectinfo(data, &conn); + if(!conn) { + failf(data, "connection not found"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + } + ws = conn->proto.ws; + if(!ws) { + failf(data, "connection is not setup for websocket"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + *nread = 0; + *metap = NULL; + + memset(&ctx, 0, sizeof(ctx)); + ctx.data = data; + ctx.buffer = buffer; + ctx.buflen = buflen; + + while(!done) { + /* receive more when our buffer is empty */ + if(Curl_bufq_is_empty(&ws->recvbuf)) { + ssize_t n = Curl_bufq_slurp(&ws->recvbuf, nw_in_recv, data, &result); + if(n < 0) { + return result; + } + else if(n == 0) { + /* connection closed */ + infof(data, "connection expectedly closed?"); + return CURLE_GOT_NOTHING; + } + DEBUGF(infof(data, "curl_ws_recv, added %zu bytes from network", + Curl_bufq_len(&ws->recvbuf))); + } + + result = ws_dec_pass(&ws->dec, data, &ws->recvbuf, + ws_client_collect, &ctx); + if(result == CURLE_AGAIN) { + if(!ctx.written) { + ws_dec_info(&ws->dec, data, "need more input"); + continue; /* nothing written, try more input */ + } + done = TRUE; + break; + } + else if(result) { + return result; + } + else if(ctx.written) { + /* The decoded frame is passed back to our caller. + * There are frames like PING were we auto-respond to and + * that we do not return. For these `ctx.written` is not set. */ + done = TRUE; + break; + } + } + + /* update frame information to be passed back */ + update_meta(ws, ctx.frame_age, ctx.frame_flags, ctx.payload_offset, + ctx.payload_len, ctx.bufidx); + *metap = &ws->frame; + *nread = ws->frame.len; + /* infof(data, "curl_ws_recv(len=%zu) -> %zu bytes (frame at %" + CURL_FORMAT_CURL_OFF_T ", %" CURL_FORMAT_CURL_OFF_T " left)", + buflen, *nread, ws->frame.offset, ws->frame.bytesleft); */ + return CURLE_OK; +} + +static CURLcode ws_flush(struct Curl_easy *data, struct websocket *ws, + bool complete) +{ + if(!Curl_bufq_is_empty(&ws->sendbuf)) { + CURLcode result; + const unsigned char *out; + size_t outlen, n; + + while(Curl_bufq_peek(&ws->sendbuf, &out, &outlen)) { + if(data->set.connect_only) + result = Curl_senddata(data, out, outlen, &n); + else { + result = Curl_xfer_send(data, out, outlen, &n); + if(!result && !n && outlen) + result = CURLE_AGAIN; + } + + if(result) { + if(result == CURLE_AGAIN) { + if(!complete) { + infof(data, "WS: flush EAGAIN, %zu bytes remain in buffer", + Curl_bufq_len(&ws->sendbuf)); + return result; + } + /* TODO: the current design does not allow for buffered writes. + * We need to flush the buffer now. There is no ws_flush() later */ + n = 0; + continue; + } + else if(result) { + failf(data, "WS: flush, write error %d", result); + return result; + } + } + else { + infof(data, "WS: flushed %zu bytes", n); + Curl_bufq_skip(&ws->sendbuf, n); + } + } + } + return CURLE_OK; +} + +CURL_EXTERN CURLcode curl_ws_send(CURL *data, const void *buffer, + size_t buflen, size_t *sent, + curl_off_t fragsize, + unsigned int flags) +{ + struct websocket *ws; + ssize_t n; + size_t nwritten, space; + CURLcode result; + + *sent = 0; + if(!data->conn && data->set.connect_only) { + result = Curl_connect_only_attach(data); + if(result) + return result; + } + if(!data->conn) { + failf(data, "No associated connection"); + return CURLE_SEND_ERROR; + } + if(!data->conn->proto.ws) { + failf(data, "Not a websocket transfer"); + return CURLE_SEND_ERROR; + } + ws = data->conn->proto.ws; + + if(data->set.ws_raw_mode) { + if(fragsize || flags) { + DEBUGF(infof(data, "ws_send: " + "fragsize and flags cannot be non-zero in raw mode")); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + if(!buflen) + /* nothing to do */ + return CURLE_OK; + /* raw mode sends exactly what was requested, and this is from within + the write callback */ + if(Curl_is_in_callback(data)) { + result = Curl_xfer_send(data, buffer, buflen, &nwritten); + } + else + result = Curl_senddata(data, buffer, buflen, &nwritten); + + infof(data, "WS: wanted to send %zu bytes, sent %zu bytes", + buflen, nwritten); + *sent = nwritten; + return result; + } + + /* Not RAW mode, buf we do the frame encoding */ + result = ws_flush(data, ws, FALSE); + if(result) + return result; + + /* TODO: the current design does not allow partial writes, afaict. + * It is not clear how the application is supposed to react. */ + space = Curl_bufq_space(&ws->sendbuf); + DEBUGF(infof(data, "curl_ws_send(len=%zu), sendbuf len=%zu space %zu", + buflen, Curl_bufq_len(&ws->sendbuf), space)); + if(space < 14) + return CURLE_AGAIN; + + if(flags & CURLWS_OFFSET) { + if(fragsize) { + /* a frame series 'fragsize' bytes big, this is the first */ + n = ws_enc_write_head(data, &ws->enc, flags, fragsize, + &ws->sendbuf, &result); + if(n < 0) + return result; + } + else { + if((curl_off_t)buflen > ws->enc.payload_remain) { + infof(data, "WS: unaligned frame size (sending %zu instead of %" + CURL_FORMAT_CURL_OFF_T ")", + buflen, ws->enc.payload_remain); + } + } + } + else if(!ws->enc.payload_remain) { + n = ws_enc_write_head(data, &ws->enc, flags, (curl_off_t)buflen, + &ws->sendbuf, &result); + if(n < 0) + return result; + } + + n = ws_enc_write_payload(&ws->enc, data, + buffer, buflen, &ws->sendbuf, &result); + if(n < 0) + return result; + + *sent = (size_t)n; + return ws_flush(data, ws, TRUE); +} + +static void ws_free(struct connectdata *conn) +{ + if(conn && conn->proto.ws) { + Curl_bufq_free(&conn->proto.ws->recvbuf); + Curl_bufq_free(&conn->proto.ws->sendbuf); + Curl_safefree(conn->proto.ws); + } +} + +static CURLcode ws_setup_conn(struct Curl_easy *data, + struct connectdata *conn) +{ + /* websockets is 1.1 only (for now) */ + data->state.httpwant = CURL_HTTP_VERSION_1_1; + return Curl_http_setup_conn(data, conn); +} + + +static CURLcode ws_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + (void)data; + (void)dead_connection; + ws_free(conn); + return CURLE_OK; +} + +CURL_EXTERN const struct curl_ws_frame *curl_ws_meta(struct Curl_easy *data) +{ + /* we only return something for websocket, called from within the callback + when not using raw mode */ + if(GOOD_EASY_HANDLE(data) && Curl_is_in_callback(data) && data->conn && + data->conn->proto.ws && !data->set.ws_raw_mode) + return &data->conn->proto.ws->frame; + return NULL; +} + +const struct Curl_handler Curl_handler_ws = { + "WS", /* scheme */ + ws_setup_conn, /* setup_connection */ + Curl_http, /* do_it */ + Curl_http_done, /* done */ + ZERO_NULL, /* do_more */ + Curl_http_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + Curl_http_getsock_do, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ws_disconnect, /* disconnect */ + Curl_http_write_resp, /* write_resp */ + Curl_http_write_resp_hd, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_HTTP, /* defport */ + CURLPROTO_WS, /* protocol */ + CURLPROTO_HTTP, /* family */ + PROTOPT_CREDSPERREQUEST | /* flags */ + PROTOPT_USERPWDCTRL +}; + +#ifdef USE_SSL +const struct Curl_handler Curl_handler_wss = { + "WSS", /* scheme */ + ws_setup_conn, /* setup_connection */ + Curl_http, /* do_it */ + Curl_http_done, /* done */ + ZERO_NULL, /* do_more */ + Curl_http_connect, /* connect_it */ + NULL, /* connecting */ + ZERO_NULL, /* doing */ + NULL, /* proto_getsock */ + Curl_http_getsock_do, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ws_disconnect, /* disconnect */ + Curl_http_write_resp, /* write_resp */ + Curl_http_write_resp_hd, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_HTTPS, /* defport */ + CURLPROTO_WSS, /* protocol */ + CURLPROTO_HTTP, /* family */ + PROTOPT_SSL | PROTOPT_CREDSPERREQUEST | /* flags */ + PROTOPT_USERPWDCTRL +}; +#endif + + +#else + +CURL_EXTERN CURLcode curl_ws_recv(CURL *curl, void *buffer, size_t buflen, + size_t *nread, + const struct curl_ws_frame **metap) +{ + (void)curl; + (void)buffer; + (void)buflen; + (void)nread; + (void)metap; + return CURLE_NOT_BUILT_IN; +} + +CURL_EXTERN CURLcode curl_ws_send(CURL *curl, const void *buffer, + size_t buflen, size_t *sent, + curl_off_t fragsize, + unsigned int flags) +{ + (void)curl; + (void)buffer; + (void)buflen; + (void)sent; + (void)fragsize; + (void)flags; + return CURLE_NOT_BUILT_IN; +} + +CURL_EXTERN const struct curl_ws_frame *curl_ws_meta(struct Curl_easy *data) +{ + (void)data; + return NULL; +} +#endif /* USE_WEBSOCKETS */ diff --git a/third_party/curl/lib/ws.h b/third_party/curl/lib/ws.h new file mode 100644 index 0000000..baa77b4 --- /dev/null +++ b/third_party/curl/lib/ws.h @@ -0,0 +1,90 @@ +#ifndef HEADER_CURL_WS_H +#define HEADER_CURL_WS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_WEBSOCKETS) && !defined(CURL_DISABLE_HTTP) + +#ifdef USE_HYPER +#define REQTYPE void +#else +#define REQTYPE struct dynbuf +#endif + +/* a client-side WS frame decoder, parsing frame headers and + * payload, keeping track of current position and stats */ +enum ws_dec_state { + WS_DEC_INIT, + WS_DEC_HEAD, + WS_DEC_PAYLOAD +}; + +struct ws_decoder { + int frame_age; /* zero */ + int frame_flags; /* See the CURLWS_* defines */ + curl_off_t payload_offset; /* the offset parsing is at */ + curl_off_t payload_len; + unsigned char head[10]; + int head_len, head_total; + enum ws_dec_state state; +}; + +/* a client-side WS frame encoder, generating frame headers and + * converting payloads, tracking remaining data in current frame */ +struct ws_encoder { + curl_off_t payload_len; /* payload length of current frame */ + curl_off_t payload_remain; /* remaining payload of current */ + unsigned int xori; /* xor index */ + unsigned char mask[4]; /* 32 bit mask for this connection */ + unsigned char firstbyte; /* first byte of frame we encode */ + bool contfragment; /* set TRUE if the previous fragment sent was not final */ +}; + +/* A websocket connection with en- and decoder that treat frames + * and keep track of boundaries. */ +struct websocket { + struct Curl_easy *data; /* used for write callback handling */ + struct ws_decoder dec; /* decode of we frames */ + struct ws_encoder enc; /* decode of we frames */ + struct bufq recvbuf; /* raw data from the server */ + struct bufq sendbuf; /* raw data to be sent to the server */ + struct curl_ws_frame frame; /* the current WS FRAME received */ +}; + +CURLcode Curl_ws_request(struct Curl_easy *data, REQTYPE *req); +CURLcode Curl_ws_accept(struct Curl_easy *data, const char *mem, size_t len); + +extern const struct Curl_handler Curl_handler_ws; +#ifdef USE_SSL +extern const struct Curl_handler Curl_handler_wss; +#endif + + +#else +#define Curl_ws_request(x,y) CURLE_OK +#define Curl_ws_free(x) Curl_nop_stmt +#endif + +#endif /* HEADER_CURL_WS_H */ diff --git a/third_party/curl/libcurl.def b/third_party/curl/libcurl.def new file mode 100644 index 0000000..9bf9fcc --- /dev/null +++ b/third_party/curl/libcurl.def @@ -0,0 +1,95 @@ +EXPORTS +curl_easy_cleanup +curl_easy_duphandle +curl_easy_escape +curl_easy_getinfo +curl_easy_header +curl_easy_init +curl_easy_nextheader +curl_easy_option_by_id +curl_easy_option_by_name +curl_easy_option_next +curl_easy_pause +curl_easy_perform +curl_easy_recv +curl_easy_reset +curl_easy_send +curl_easy_setopt +curl_easy_strerror +curl_easy_unescape +curl_easy_upkeep +curl_escape +curl_formadd +curl_formfree +curl_formget +curl_free +curl_getdate +curl_getenv +curl_global_cleanup +curl_global_init +curl_global_init_mem +curl_global_sslset +curl_global_trace +curl_maprintf +curl_mfprintf +curl_mime_addpart +curl_mime_data +curl_mime_data_cb +curl_mime_encoder +curl_mime_filedata +curl_mime_filename +curl_mime_free +curl_mime_headers +curl_mime_init +curl_mime_name +curl_mime_subparts +curl_mime_type +curl_mprintf +curl_msnprintf +curl_msprintf +curl_multi_add_handle +curl_multi_assign +curl_multi_cleanup +curl_multi_fdset +curl_multi_get_handles +curl_multi_info_read +curl_multi_init +curl_multi_perform +curl_multi_poll +curl_multi_remove_handle +curl_multi_setopt +curl_multi_socket +curl_multi_socket_action +curl_multi_socket_all +curl_multi_strerror +curl_multi_timeout +curl_multi_wait +curl_multi_waitfds +curl_multi_wakeup +curl_mvaprintf +curl_mvfprintf +curl_mvprintf +curl_mvsnprintf +curl_mvsprintf +curl_pushheader_byname +curl_pushheader_bynum +curl_share_cleanup +curl_share_init +curl_share_setopt +curl_share_strerror +curl_slist_append +curl_slist_free_all +curl_strequal +curl_strnequal +curl_unescape +curl_url +curl_url_cleanup +curl_url_dup +curl_url_get +curl_url_set +curl_url_strerror +curl_version +curl_version_info +curl_ws_meta +curl_ws_recv +curl_ws_send diff --git a/third_party/curl/libcurl.pc.in b/third_party/curl/libcurl.pc.in new file mode 100644 index 0000000..9db6b0f --- /dev/null +++ b/third_party/curl/libcurl.pc.in @@ -0,0 +1,41 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +# This should most probably benefit from getting a "Requires:" field added +# dynamically by configure. +# +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ +supported_protocols="@SUPPORT_PROTOCOLS@" +supported_features="@SUPPORT_FEATURES@" + +Name: libcurl +URL: https://curl.se/ +Description: Library to transfer files with ftp, http, etc. +Version: @CURLVERSION@ +Libs: -L${libdir} -lcurl @LIBCURL_NO_SHARED@ +Libs.private: @LIBCURL_LIBS@ +Cflags: -I${includedir} @CPPFLAG_CURL_STATICLIB@ diff --git a/third_party/curl/ltmain.sh b/third_party/curl/ltmain.sh new file mode 100755 index 0000000..9b12fbb --- /dev/null +++ b/third_party/curl/ltmain.sh @@ -0,0 +1,11448 @@ +#! /usr/bin/env sh +## DO NOT EDIT - This file generated from ./build-aux/ltmain.in +## by inline-source v2019-02-19.15 + +# libtool (GNU libtool) 2.4.7 +# Provide generalized library-building support services. +# Written by Gordon Matzigkeit , 1996 + +# Copyright (C) 1996-2019, 2021-2022 Free Software Foundation, Inc. +# This is free software; see the source for copying conditions. There is NO +# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +# GNU Libtool is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# As a special exception to the GNU General Public License, +# if you distribute this file as part of a program or library that +# is built using GNU Libtool, you may include this file under the +# same distribution terms that you use for the rest of that program. +# +# GNU Libtool is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + + +PROGRAM=libtool +PACKAGE=libtool +VERSION="2.4.7 Debian-2.4.7-5" +package_revision=2.4.7 + + +## ------ ## +## Usage. ## +## ------ ## + +# Run './libtool --help' for help with using this script from the +# command line. + + +## ------------------------------- ## +## User overridable command paths. ## +## ------------------------------- ## + +# After configure completes, it has a better idea of some of the +# shell tools we need than the defaults used by the functions shared +# with bootstrap, so set those here where they can still be over- +# ridden by the user, but otherwise take precedence. + +: ${AUTOCONF="autoconf"} +: ${AUTOMAKE="automake"} + + +## -------------------------- ## +## Source external libraries. ## +## -------------------------- ## + +# Much of our low-level functionality needs to be sourced from external +# libraries, which are installed to $pkgauxdir. + +# Set a version string for this script. +scriptversion=2019-02-19.15; # UTC + +# General shell script boiler plate, and helper functions. +# Written by Gary V. Vaughan, 2004 + +# This is free software. There is NO warranty; not even for +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# +# Copyright (C) 2004-2019, 2021 Bootstrap Authors +# +# This file is dual licensed under the terms of the MIT license +# , and GPL version 2 or later +# . You must apply one of +# these licenses when using or redistributing this software or any of +# the files within it. See the URLs above, or the file `LICENSE` +# included in the Bootstrap distribution for the full license texts. + +# Please report bugs or propose patches to: +# + + +## ------ ## +## Usage. ## +## ------ ## + +# Evaluate this file near the top of your script to gain access to +# the functions and variables defined here: +# +# . `echo "$0" | ${SED-sed} 's|[^/]*$||'`/build-aux/funclib.sh +# +# If you need to override any of the default environment variable +# settings, do that before evaluating this file. + + +## -------------------- ## +## Shell normalisation. ## +## -------------------- ## + +# Some shells need a little help to be as Bourne compatible as possible. +# Before doing anything else, make sure all that help has been provided! + +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac +fi + +# NLS nuisances: We save the old values in case they are required later. +_G_user_locale= +_G_safe_locale= +for _G_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES +do + eval "if test set = \"\${$_G_var+set}\"; then + save_$_G_var=\$$_G_var + $_G_var=C + export $_G_var + _G_user_locale=\"$_G_var=\\\$save_\$_G_var; \$_G_user_locale\" + _G_safe_locale=\"$_G_var=C; \$_G_safe_locale\" + fi" +done +# These NLS vars are set unconditionally (bootstrap issue #24). Unset those +# in case the environment reset is needed later and the $save_* variant is not +# defined (see the code above). +LC_ALL=C +LANGUAGE=C +export LANGUAGE LC_ALL + +# Make sure IFS has a sensible default +sp=' ' +nl=' +' +IFS="$sp $nl" + +# There are apparently some retarded systems that use ';' as a PATH separator! +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + +# func_unset VAR +# -------------- +# Portably unset VAR. +# In some shells, an 'unset VAR' statement leaves a non-zero return +# status if VAR is already unset, which might be problematic if the +# statement is used at the end of a function (thus poisoning its return +# value) or when 'set -e' is active (causing even a spurious abort of +# the script in this case). +func_unset () +{ + { eval $1=; (eval unset $1) >/dev/null 2>&1 && eval unset $1 || : ; } +} + + +# Make sure CDPATH doesn't cause `cd` commands to output the target dir. +func_unset CDPATH + +# Make sure ${,E,F}GREP behave sanely. +func_unset GREP_OPTIONS + + +## ------------------------- ## +## Locate command utilities. ## +## ------------------------- ## + + +# func_executable_p FILE +# ---------------------- +# Check that FILE is an executable regular file. +func_executable_p () +{ + test -f "$1" && test -x "$1" +} + + +# func_path_progs PROGS_LIST CHECK_FUNC [PATH] +# -------------------------------------------- +# Search for either a program that responds to --version with output +# containing "GNU", or else returned by CHECK_FUNC otherwise, by +# trying all the directories in PATH with each of the elements of +# PROGS_LIST. +# +# CHECK_FUNC should accept the path to a candidate program, and +# set $func_check_prog_result if it truncates its output less than +# $_G_path_prog_max characters. +func_path_progs () +{ + _G_progs_list=$1 + _G_check_func=$2 + _G_PATH=${3-"$PATH"} + + _G_path_prog_max=0 + _G_path_prog_found=false + _G_save_IFS=$IFS; IFS=${PATH_SEPARATOR-:} + for _G_dir in $_G_PATH; do + IFS=$_G_save_IFS + test -z "$_G_dir" && _G_dir=. + for _G_prog_name in $_G_progs_list; do + for _exeext in '' .EXE; do + _G_path_prog=$_G_dir/$_G_prog_name$_exeext + func_executable_p "$_G_path_prog" || continue + case `"$_G_path_prog" --version 2>&1` in + *GNU*) func_path_progs_result=$_G_path_prog _G_path_prog_found=: ;; + *) $_G_check_func $_G_path_prog + func_path_progs_result=$func_check_prog_result + ;; + esac + $_G_path_prog_found && break 3 + done + done + done + IFS=$_G_save_IFS + test -z "$func_path_progs_result" && { + echo "no acceptable sed could be found in \$PATH" >&2 + exit 1 + } +} + + +# We want to be able to use the functions in this file before configure +# has figured out where the best binaries are kept, which means we have +# to search for them ourselves - except when the results are already set +# where we skip the searches. + +# Unless the user overrides by setting SED, search the path for either GNU +# sed, or the sed that truncates its output the least. +test -z "$SED" && { + _G_sed_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ + for _G_i in 1 2 3 4 5 6 7; do + _G_sed_script=$_G_sed_script$nl$_G_sed_script + done + echo "$_G_sed_script" 2>/dev/null | sed 99q >conftest.sed + _G_sed_script= + + func_check_prog_sed () + { + _G_path_prog=$1 + + _G_count=0 + printf 0123456789 >conftest.in + while : + do + cat conftest.in conftest.in >conftest.tmp + mv conftest.tmp conftest.in + cp conftest.in conftest.nl + echo '' >> conftest.nl + "$_G_path_prog" -f conftest.sed conftest.out 2>/dev/null || break + diff conftest.out conftest.nl >/dev/null 2>&1 || break + _G_count=`expr $_G_count + 1` + if test "$_G_count" -gt "$_G_path_prog_max"; then + # Best one so far, save it but keep looking for a better one + func_check_prog_result=$_G_path_prog + _G_path_prog_max=$_G_count + fi + # 10*(2^10) chars as input seems more than enough + test 10 -lt "$_G_count" && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out + } + + func_path_progs "sed gsed" func_check_prog_sed "$PATH:/usr/xpg4/bin" + rm -f conftest.sed + SED=$func_path_progs_result +} + + +# Unless the user overrides by setting GREP, search the path for either GNU +# grep, or the grep that truncates its output the least. +test -z "$GREP" && { + func_check_prog_grep () + { + _G_path_prog=$1 + + _G_count=0 + _G_path_prog_max=0 + printf 0123456789 >conftest.in + while : + do + cat conftest.in conftest.in >conftest.tmp + mv conftest.tmp conftest.in + cp conftest.in conftest.nl + echo 'GREP' >> conftest.nl + "$_G_path_prog" -e 'GREP$' -e '-(cannot match)-' conftest.out 2>/dev/null || break + diff conftest.out conftest.nl >/dev/null 2>&1 || break + _G_count=`expr $_G_count + 1` + if test "$_G_count" -gt "$_G_path_prog_max"; then + # Best one so far, save it but keep looking for a better one + func_check_prog_result=$_G_path_prog + _G_path_prog_max=$_G_count + fi + # 10*(2^10) chars as input seems more than enough + test 10 -lt "$_G_count" && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out + } + + func_path_progs "grep ggrep" func_check_prog_grep "$PATH:/usr/xpg4/bin" + GREP=$func_path_progs_result +} + + +## ------------------------------- ## +## User overridable command paths. ## +## ------------------------------- ## + +# All uppercase variable names are used for environment variables. These +# variables can be overridden by the user before calling a script that +# uses them if a suitable command of that name is not already available +# in the command search PATH. + +: ${CP="cp -f"} +: ${ECHO="printf %s\n"} +: ${EGREP="$GREP -E"} +: ${FGREP="$GREP -F"} +: ${LN_S="ln -s"} +: ${MAKE="make"} +: ${MKDIR="mkdir"} +: ${MV="mv -f"} +: ${RM="rm -f"} +: ${SHELL="${CONFIG_SHELL-/bin/sh}"} + + +## -------------------- ## +## Useful sed snippets. ## +## -------------------- ## + +sed_dirname='s|/[^/]*$||' +sed_basename='s|^.*/||' + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +sed_quote_subst='s|\([`"$\\]\)|\\\1|g' + +# Same as above, but do not quote variable references. +sed_double_quote_subst='s/\(["`\\]\)/\\\1/g' + +# Sed substitution that turns a string into a regex matching for the +# string literally. +sed_make_literal_regex='s|[].[^$\\*\/]|\\&|g' + +# Sed substitution that converts a w32 file name or path +# that contains forward slashes, into one that contains +# (escaped) backslashes. A very naive implementation. +sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' + +# Re-'\' parameter expansions in output of sed_double_quote_subst that +# were '\'-ed in input to the same. If an odd number of '\' preceded a +# '$' in input to sed_double_quote_subst, that '$' was protected from +# expansion. Since each input '\' is now two '\'s, look for any number +# of runs of four '\'s followed by two '\'s and then a '$'. '\' that '$'. +_G_bs='\\' +_G_bs2='\\\\' +_G_bs4='\\\\\\\\' +_G_dollar='\$' +sed_double_backslash="\ + s/$_G_bs4/&\\ +/g + s/^$_G_bs2$_G_dollar/$_G_bs&/ + s/\\([^$_G_bs]\\)$_G_bs2$_G_dollar/\\1$_G_bs2$_G_bs$_G_dollar/g + s/\n//g" + +# require_check_ifs_backslash +# --------------------------- +# Check if we can use backslash as IFS='\' separator, and set +# $check_ifs_backshlash_broken to ':' or 'false'. +require_check_ifs_backslash=func_require_check_ifs_backslash +func_require_check_ifs_backslash () +{ + _G_save_IFS=$IFS + IFS='\' + _G_check_ifs_backshlash='a\\b' + for _G_i in $_G_check_ifs_backshlash + do + case $_G_i in + a) + check_ifs_backshlash_broken=false + ;; + '') + break + ;; + *) + check_ifs_backshlash_broken=: + break + ;; + esac + done + IFS=$_G_save_IFS + require_check_ifs_backslash=: +} + + +## ----------------- ## +## Global variables. ## +## ----------------- ## + +# Except for the global variables explicitly listed below, the following +# functions in the '^func_' namespace, and the '^require_' namespace +# variables initialised in the 'Resource management' section, sourcing +# this file will not pollute your global namespace with anything +# else. There's no portable way to scope variables in Bourne shell +# though, so actually running these functions will sometimes place +# results into a variable named after the function, and often use +# temporary variables in the '^_G_' namespace. If you are careful to +# avoid using those namespaces casually in your sourcing script, things +# should continue to work as you expect. And, of course, you can freely +# overwrite any of the functions or variables defined here before +# calling anything to customize them. + +EXIT_SUCCESS=0 +EXIT_FAILURE=1 +EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. +EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. + +# Allow overriding, eg assuming that you follow the convention of +# putting '$debug_cmd' at the start of all your functions, you can get +# bash to show function call trace with: +# +# debug_cmd='echo "${FUNCNAME[0]} $*" >&2' bash your-script-name +debug_cmd=${debug_cmd-":"} +exit_cmd=: + +# By convention, finish your script with: +# +# exit $exit_status +# +# so that you can set exit_status to non-zero if you want to indicate +# something went wrong during execution without actually bailing out at +# the point of failure. +exit_status=$EXIT_SUCCESS + +# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh +# is ksh but when the shell is invoked as "sh" and the current value of +# the _XPG environment variable is not equal to 1 (one), the special +# positional parameter $0, within a function call, is the name of the +# function. +progpath=$0 + +# The name of this program. +progname=`$ECHO "$progpath" |$SED "$sed_basename"` + +# Make sure we have an absolute progpath for reexecution: +case $progpath in + [\\/]*|[A-Za-z]:\\*) ;; + *[\\/]*) + progdir=`$ECHO "$progpath" |$SED "$sed_dirname"` + progdir=`cd "$progdir" && pwd` + progpath=$progdir/$progname + ;; + *) + _G_IFS=$IFS + IFS=${PATH_SEPARATOR-:} + for progdir in $PATH; do + IFS=$_G_IFS + test -x "$progdir/$progname" && break + done + IFS=$_G_IFS + test -n "$progdir" || progdir=`pwd` + progpath=$progdir/$progname + ;; +esac + + +## ----------------- ## +## Standard options. ## +## ----------------- ## + +# The following options affect the operation of the functions defined +# below, and should be set appropriately depending on run-time para- +# meters passed on the command line. + +opt_dry_run=false +opt_quiet=false +opt_verbose=false + +# Categories 'all' and 'none' are always available. Append any others +# you will pass as the first argument to func_warning from your own +# code. +warning_categories= + +# By default, display warnings according to 'opt_warning_types'. Set +# 'warning_func' to ':' to elide all warnings, or func_fatal_error to +# treat the next displayed warning as a fatal error. +warning_func=func_warn_and_continue + +# Set to 'all' to display all warnings, 'none' to suppress all +# warnings, or a space delimited list of some subset of +# 'warning_categories' to display only the listed warnings. +opt_warning_types=all + + +## -------------------- ## +## Resource management. ## +## -------------------- ## + +# This section contains definitions for functions that each ensure a +# particular resource (a file, or a non-empty configuration variable for +# example) is available, and if appropriate to extract default values +# from pertinent package files. Call them using their associated +# 'require_*' variable to ensure that they are executed, at most, once. +# +# It's entirely deliberate that calling these functions can set +# variables that don't obey the namespace limitations obeyed by the rest +# of this file, in order that that they be as useful as possible to +# callers. + + +# require_term_colors +# ------------------- +# Allow display of bold text on terminals that support it. +require_term_colors=func_require_term_colors +func_require_term_colors () +{ + $debug_cmd + + test -t 1 && { + # COLORTERM and USE_ANSI_COLORS environment variables take + # precedence, because most terminfo databases neglect to describe + # whether color sequences are supported. + test -n "${COLORTERM+set}" && : ${USE_ANSI_COLORS="1"} + + if test 1 = "$USE_ANSI_COLORS"; then + # Standard ANSI escape sequences + tc_reset='' + tc_bold=''; tc_standout='' + tc_red=''; tc_green='' + tc_blue=''; tc_cyan='' + else + # Otherwise trust the terminfo database after all. + test -n "`tput sgr0 2>/dev/null`" && { + tc_reset=`tput sgr0` + test -n "`tput bold 2>/dev/null`" && tc_bold=`tput bold` + tc_standout=$tc_bold + test -n "`tput smso 2>/dev/null`" && tc_standout=`tput smso` + test -n "`tput setaf 1 2>/dev/null`" && tc_red=`tput setaf 1` + test -n "`tput setaf 2 2>/dev/null`" && tc_green=`tput setaf 2` + test -n "`tput setaf 4 2>/dev/null`" && tc_blue=`tput setaf 4` + test -n "`tput setaf 5 2>/dev/null`" && tc_cyan=`tput setaf 5` + } + fi + } + + require_term_colors=: +} + + +## ----------------- ## +## Function library. ## +## ----------------- ## + +# This section contains a variety of useful functions to call in your +# scripts. Take note of the portable wrappers for features provided by +# some modern shells, which will fall back to slower equivalents on +# less featureful shells. + + +# func_append VAR VALUE +# --------------------- +# Append VALUE onto the existing contents of VAR. + + # We should try to minimise forks, especially on Windows where they are + # unreasonably slow, so skip the feature probes when bash or zsh are + # being used: + if test set = "${BASH_VERSION+set}${ZSH_VERSION+set}"; then + : ${_G_HAVE_ARITH_OP="yes"} + : ${_G_HAVE_XSI_OPS="yes"} + # The += operator was introduced in bash 3.1 + case $BASH_VERSION in + [12].* | 3.0 | 3.0*) ;; + *) + : ${_G_HAVE_PLUSEQ_OP="yes"} + ;; + esac + fi + + # _G_HAVE_PLUSEQ_OP + # Can be empty, in which case the shell is probed, "yes" if += is + # useable or anything else if it does not work. + test -z "$_G_HAVE_PLUSEQ_OP" \ + && (eval 'x=a; x+=" b"; test "a b" = "$x"') 2>/dev/null \ + && _G_HAVE_PLUSEQ_OP=yes + +if test yes = "$_G_HAVE_PLUSEQ_OP" +then + # This is an XSI compatible shell, allowing a faster implementation... + eval 'func_append () + { + $debug_cmd + + eval "$1+=\$2" + }' +else + # ...otherwise fall back to using expr, which is often a shell builtin. + func_append () + { + $debug_cmd + + eval "$1=\$$1\$2" + } +fi + + +# func_append_quoted VAR VALUE +# ---------------------------- +# Quote VALUE and append to the end of shell variable VAR, separated +# by a space. +if test yes = "$_G_HAVE_PLUSEQ_OP"; then + eval 'func_append_quoted () + { + $debug_cmd + + func_quote_arg pretty "$2" + eval "$1+=\\ \$func_quote_arg_result" + }' +else + func_append_quoted () + { + $debug_cmd + + func_quote_arg pretty "$2" + eval "$1=\$$1\\ \$func_quote_arg_result" + } +fi + + +# func_append_uniq VAR VALUE +# -------------------------- +# Append unique VALUE onto the existing contents of VAR, assuming +# entries are delimited by the first character of VALUE. For example: +# +# func_append_uniq options " --another-option option-argument" +# +# will only append to $options if " --another-option option-argument " +# is not already present somewhere in $options already (note spaces at +# each end implied by leading space in second argument). +func_append_uniq () +{ + $debug_cmd + + eval _G_current_value='`$ECHO $'$1'`' + _G_delim=`expr "$2" : '\(.\)'` + + case $_G_delim$_G_current_value$_G_delim in + *"$2$_G_delim"*) ;; + *) func_append "$@" ;; + esac +} + + +# func_arith TERM... +# ------------------ +# Set func_arith_result to the result of evaluating TERMs. + test -z "$_G_HAVE_ARITH_OP" \ + && (eval 'test 2 = $(( 1 + 1 ))') 2>/dev/null \ + && _G_HAVE_ARITH_OP=yes + +if test yes = "$_G_HAVE_ARITH_OP"; then + eval 'func_arith () + { + $debug_cmd + + func_arith_result=$(( $* )) + }' +else + func_arith () + { + $debug_cmd + + func_arith_result=`expr "$@"` + } +fi + + +# func_basename FILE +# ------------------ +# Set func_basename_result to FILE with everything up to and including +# the last / stripped. +if test yes = "$_G_HAVE_XSI_OPS"; then + # If this shell supports suffix pattern removal, then use it to avoid + # forking. Hide the definitions single quotes in case the shell chokes + # on unsupported syntax... + _b='func_basename_result=${1##*/}' + _d='case $1 in + */*) func_dirname_result=${1%/*}$2 ;; + * ) func_dirname_result=$3 ;; + esac' + +else + # ...otherwise fall back to using sed. + _b='func_basename_result=`$ECHO "$1" |$SED "$sed_basename"`' + _d='func_dirname_result=`$ECHO "$1" |$SED "$sed_dirname"` + if test "X$func_dirname_result" = "X$1"; then + func_dirname_result=$3 + else + func_append func_dirname_result "$2" + fi' +fi + +eval 'func_basename () +{ + $debug_cmd + + '"$_b"' +}' + + +# func_dirname FILE APPEND NONDIR_REPLACEMENT +# ------------------------------------------- +# Compute the dirname of FILE. If nonempty, add APPEND to the result, +# otherwise set result to NONDIR_REPLACEMENT. +eval 'func_dirname () +{ + $debug_cmd + + '"$_d"' +}' + + +# func_dirname_and_basename FILE APPEND NONDIR_REPLACEMENT +# -------------------------------------------------------- +# Perform func_basename and func_dirname in a single function +# call: +# dirname: Compute the dirname of FILE. If nonempty, +# add APPEND to the result, otherwise set result +# to NONDIR_REPLACEMENT. +# value returned in "$func_dirname_result" +# basename: Compute filename of FILE. +# value retuned in "$func_basename_result" +# For efficiency, we do not delegate to the functions above but instead +# duplicate the functionality here. +eval 'func_dirname_and_basename () +{ + $debug_cmd + + '"$_b"' + '"$_d"' +}' + + +# func_echo ARG... +# ---------------- +# Echo program name prefixed message. +func_echo () +{ + $debug_cmd + + _G_message=$* + + func_echo_IFS=$IFS + IFS=$nl + for _G_line in $_G_message; do + IFS=$func_echo_IFS + $ECHO "$progname: $_G_line" + done + IFS=$func_echo_IFS +} + + +# func_echo_all ARG... +# -------------------- +# Invoke $ECHO with all args, space-separated. +func_echo_all () +{ + $ECHO "$*" +} + + +# func_echo_infix_1 INFIX ARG... +# ------------------------------ +# Echo program name, followed by INFIX on the first line, with any +# additional lines not showing INFIX. +func_echo_infix_1 () +{ + $debug_cmd + + $require_term_colors + + _G_infix=$1; shift + _G_indent=$_G_infix + _G_prefix="$progname: $_G_infix: " + _G_message=$* + + # Strip color escape sequences before counting printable length + for _G_tc in "$tc_reset" "$tc_bold" "$tc_standout" "$tc_red" "$tc_green" "$tc_blue" "$tc_cyan" + do + test -n "$_G_tc" && { + _G_esc_tc=`$ECHO "$_G_tc" | $SED "$sed_make_literal_regex"` + _G_indent=`$ECHO "$_G_indent" | $SED "s|$_G_esc_tc||g"` + } + done + _G_indent="$progname: "`echo "$_G_indent" | $SED 's|.| |g'`" " ## exclude from sc_prohibit_nested_quotes + + func_echo_infix_1_IFS=$IFS + IFS=$nl + for _G_line in $_G_message; do + IFS=$func_echo_infix_1_IFS + $ECHO "$_G_prefix$tc_bold$_G_line$tc_reset" >&2 + _G_prefix=$_G_indent + done + IFS=$func_echo_infix_1_IFS +} + + +# func_error ARG... +# ----------------- +# Echo program name prefixed message to standard error. +func_error () +{ + $debug_cmd + + $require_term_colors + + func_echo_infix_1 " $tc_standout${tc_red}error$tc_reset" "$*" >&2 +} + + +# func_fatal_error ARG... +# ----------------------- +# Echo program name prefixed message to standard error, and exit. +func_fatal_error () +{ + $debug_cmd + + func_error "$*" + exit $EXIT_FAILURE +} + + +# func_grep EXPRESSION FILENAME +# ----------------------------- +# Check whether EXPRESSION matches any line of FILENAME, without output. +func_grep () +{ + $debug_cmd + + $GREP "$1" "$2" >/dev/null 2>&1 +} + + +# func_len STRING +# --------------- +# Set func_len_result to the length of STRING. STRING may not +# start with a hyphen. + test -z "$_G_HAVE_XSI_OPS" \ + && (eval 'x=a/b/c; + test 5aa/bb/cc = "${#x}${x%%/*}${x%/*}${x#*/}${x##*/}"') 2>/dev/null \ + && _G_HAVE_XSI_OPS=yes + +if test yes = "$_G_HAVE_XSI_OPS"; then + eval 'func_len () + { + $debug_cmd + + func_len_result=${#1} + }' +else + func_len () + { + $debug_cmd + + func_len_result=`expr "$1" : ".*" 2>/dev/null || echo $max_cmd_len` + } +fi + + +# func_mkdir_p DIRECTORY-PATH +# --------------------------- +# Make sure the entire path to DIRECTORY-PATH is available. +func_mkdir_p () +{ + $debug_cmd + + _G_directory_path=$1 + _G_dir_list= + + if test -n "$_G_directory_path" && test : != "$opt_dry_run"; then + + # Protect directory names starting with '-' + case $_G_directory_path in + -*) _G_directory_path=./$_G_directory_path ;; + esac + + # While some portion of DIR does not yet exist... + while test ! -d "$_G_directory_path"; do + # ...make a list in topmost first order. Use a colon delimited + # list incase some portion of path contains whitespace. + _G_dir_list=$_G_directory_path:$_G_dir_list + + # If the last portion added has no slash in it, the list is done + case $_G_directory_path in */*) ;; *) break ;; esac + + # ...otherwise throw away the child directory and loop + _G_directory_path=`$ECHO "$_G_directory_path" | $SED -e "$sed_dirname"` + done + _G_dir_list=`$ECHO "$_G_dir_list" | $SED 's|:*$||'` + + func_mkdir_p_IFS=$IFS; IFS=: + for _G_dir in $_G_dir_list; do + IFS=$func_mkdir_p_IFS + # mkdir can fail with a 'File exist' error if two processes + # try to create one of the directories concurrently. Don't + # stop in that case! + $MKDIR "$_G_dir" 2>/dev/null || : + done + IFS=$func_mkdir_p_IFS + + # Bail out if we (or some other process) failed to create a directory. + test -d "$_G_directory_path" || \ + func_fatal_error "Failed to create '$1'" + fi +} + + +# func_mktempdir [BASENAME] +# ------------------------- +# Make a temporary directory that won't clash with other running +# libtool processes, and avoids race conditions if possible. If +# given, BASENAME is the basename for that directory. +func_mktempdir () +{ + $debug_cmd + + _G_template=${TMPDIR-/tmp}/${1-$progname} + + if test : = "$opt_dry_run"; then + # Return a directory name, but don't create it in dry-run mode + _G_tmpdir=$_G_template-$$ + else + + # If mktemp works, use that first and foremost + _G_tmpdir=`mktemp -d "$_G_template-XXXXXXXX" 2>/dev/null` + + if test ! -d "$_G_tmpdir"; then + # Failing that, at least try and use $RANDOM to avoid a race + _G_tmpdir=$_G_template-${RANDOM-0}$$ + + func_mktempdir_umask=`umask` + umask 0077 + $MKDIR "$_G_tmpdir" + umask $func_mktempdir_umask + fi + + # If we're not in dry-run mode, bomb out on failure + test -d "$_G_tmpdir" || \ + func_fatal_error "cannot create temporary directory '$_G_tmpdir'" + fi + + $ECHO "$_G_tmpdir" +} + + +# func_normal_abspath PATH +# ------------------------ +# Remove doubled-up and trailing slashes, "." path components, +# and cancel out any ".." path components in PATH after making +# it an absolute path. +func_normal_abspath () +{ + $debug_cmd + + # These SED scripts presuppose an absolute path with a trailing slash. + _G_pathcar='s|^/\([^/]*\).*$|\1|' + _G_pathcdr='s|^/[^/]*||' + _G_removedotparts=':dotsl + s|/\./|/|g + t dotsl + s|/\.$|/|' + _G_collapseslashes='s|/\{1,\}|/|g' + _G_finalslash='s|/*$|/|' + + # Start from root dir and reassemble the path. + func_normal_abspath_result= + func_normal_abspath_tpath=$1 + func_normal_abspath_altnamespace= + case $func_normal_abspath_tpath in + "") + # Empty path, that just means $cwd. + func_stripname '' '/' "`pwd`" + func_normal_abspath_result=$func_stripname_result + return + ;; + # The next three entries are used to spot a run of precisely + # two leading slashes without using negated character classes; + # we take advantage of case's first-match behaviour. + ///*) + # Unusual form of absolute path, do nothing. + ;; + //*) + # Not necessarily an ordinary path; POSIX reserves leading '//' + # and for example Cygwin uses it to access remote file shares + # over CIFS/SMB, so we conserve a leading double slash if found. + func_normal_abspath_altnamespace=/ + ;; + /*) + # Absolute path, do nothing. + ;; + *) + # Relative path, prepend $cwd. + func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath + ;; + esac + + # Cancel out all the simple stuff to save iterations. We also want + # the path to end with a slash for ease of parsing, so make sure + # there is one (and only one) here. + func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ + -e "$_G_removedotparts" -e "$_G_collapseslashes" -e "$_G_finalslash"` + while :; do + # Processed it all yet? + if test / = "$func_normal_abspath_tpath"; then + # If we ascended to the root using ".." the result may be empty now. + if test -z "$func_normal_abspath_result"; then + func_normal_abspath_result=/ + fi + break + fi + func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \ + -e "$_G_pathcar"` + func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ + -e "$_G_pathcdr"` + # Figure out what to do with it + case $func_normal_abspath_tcomponent in + "") + # Trailing empty path component, ignore it. + ;; + ..) + # Parent dir; strip last assembled component from result. + func_dirname "$func_normal_abspath_result" + func_normal_abspath_result=$func_dirname_result + ;; + *) + # Actual path component, append it. + func_append func_normal_abspath_result "/$func_normal_abspath_tcomponent" + ;; + esac + done + # Restore leading double-slash if one was found on entry. + func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result +} + + +# func_notquiet ARG... +# -------------------- +# Echo program name prefixed message only when not in quiet mode. +func_notquiet () +{ + $debug_cmd + + $opt_quiet || func_echo ${1+"$@"} + + # A bug in bash halts the script if the last line of a function + # fails when set -e is in force, so we need another command to + # work around that: + : +} + + +# func_relative_path SRCDIR DSTDIR +# -------------------------------- +# Set func_relative_path_result to the relative path from SRCDIR to DSTDIR. +func_relative_path () +{ + $debug_cmd + + func_relative_path_result= + func_normal_abspath "$1" + func_relative_path_tlibdir=$func_normal_abspath_result + func_normal_abspath "$2" + func_relative_path_tbindir=$func_normal_abspath_result + + # Ascend the tree starting from libdir + while :; do + # check if we have found a prefix of bindir + case $func_relative_path_tbindir in + $func_relative_path_tlibdir) + # found an exact match + func_relative_path_tcancelled= + break + ;; + $func_relative_path_tlibdir*) + # found a matching prefix + func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir" + func_relative_path_tcancelled=$func_stripname_result + if test -z "$func_relative_path_result"; then + func_relative_path_result=. + fi + break + ;; + *) + func_dirname $func_relative_path_tlibdir + func_relative_path_tlibdir=$func_dirname_result + if test -z "$func_relative_path_tlibdir"; then + # Have to descend all the way to the root! + func_relative_path_result=../$func_relative_path_result + func_relative_path_tcancelled=$func_relative_path_tbindir + break + fi + func_relative_path_result=../$func_relative_path_result + ;; + esac + done + + # Now calculate path; take care to avoid doubling-up slashes. + func_stripname '' '/' "$func_relative_path_result" + func_relative_path_result=$func_stripname_result + func_stripname '/' '/' "$func_relative_path_tcancelled" + if test -n "$func_stripname_result"; then + func_append func_relative_path_result "/$func_stripname_result" + fi + + # Normalisation. If bindir is libdir, return '.' else relative path. + if test -n "$func_relative_path_result"; then + func_stripname './' '' "$func_relative_path_result" + func_relative_path_result=$func_stripname_result + fi + + test -n "$func_relative_path_result" || func_relative_path_result=. + + : +} + + +# func_quote_portable EVAL ARG +# ---------------------------- +# Internal function to portably implement func_quote_arg. Note that we still +# keep attention to performance here so we as much as possible try to avoid +# calling sed binary (so far O(N) complexity as long as func_append is O(1)). +func_quote_portable () +{ + $debug_cmd + + $require_check_ifs_backslash + + func_quote_portable_result=$2 + + # one-time-loop (easy break) + while true + do + if $1; then + func_quote_portable_result=`$ECHO "$2" | $SED \ + -e "$sed_double_quote_subst" -e "$sed_double_backslash"` + break + fi + + # Quote for eval. + case $func_quote_portable_result in + *[\\\`\"\$]*) + # Fallback to sed for $func_check_bs_ifs_broken=:, or when the string + # contains the shell wildcard characters. + case $check_ifs_backshlash_broken$func_quote_portable_result in + :*|*[\[\*\?]*) + func_quote_portable_result=`$ECHO "$func_quote_portable_result" \ + | $SED "$sed_quote_subst"` + break + ;; + esac + + func_quote_portable_old_IFS=$IFS + for _G_char in '\' '`' '"' '$' + do + # STATE($1) PREV($2) SEPARATOR($3) + set start "" "" + func_quote_portable_result=dummy"$_G_char$func_quote_portable_result$_G_char"dummy + IFS=$_G_char + for _G_part in $func_quote_portable_result + do + case $1 in + quote) + func_append func_quote_portable_result "$3$2" + set quote "$_G_part" "\\$_G_char" + ;; + start) + set first "" "" + func_quote_portable_result= + ;; + first) + set quote "$_G_part" "" + ;; + esac + done + done + IFS=$func_quote_portable_old_IFS + ;; + *) ;; + esac + break + done + + func_quote_portable_unquoted_result=$func_quote_portable_result + case $func_quote_portable_result in + # double-quote args containing shell metacharacters to delay + # word splitting, command substitution and variable expansion + # for a subsequent eval. + # many bourne shells cannot handle close brackets correctly + # in scan sets, so we specify it separately. + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + func_quote_portable_result=\"$func_quote_portable_result\" + ;; + esac +} + + +# func_quotefast_eval ARG +# ----------------------- +# Quote one ARG (internal). This is equivalent to 'func_quote_arg eval ARG', +# but optimized for speed. Result is stored in $func_quotefast_eval. +if test xyes = `(x=; printf -v x %q yes; echo x"$x") 2>/dev/null`; then + printf -v _GL_test_printf_tilde %q '~' + if test '\~' = "$_GL_test_printf_tilde"; then + func_quotefast_eval () + { + printf -v func_quotefast_eval_result %q "$1" + } + else + # Broken older Bash implementations. Make those faster too if possible. + func_quotefast_eval () + { + case $1 in + '~'*) + func_quote_portable false "$1" + func_quotefast_eval_result=$func_quote_portable_result + ;; + *) + printf -v func_quotefast_eval_result %q "$1" + ;; + esac + } + fi +else + func_quotefast_eval () + { + func_quote_portable false "$1" + func_quotefast_eval_result=$func_quote_portable_result + } +fi + + +# func_quote_arg MODEs ARG +# ------------------------ +# Quote one ARG to be evaled later. MODEs argument may contain zero or more +# specifiers listed below separated by ',' character. This function returns two +# values: +# i) func_quote_arg_result +# double-quoted (when needed), suitable for a subsequent eval +# ii) func_quote_arg_unquoted_result +# has all characters that are still active within double +# quotes backslashified. Available only if 'unquoted' is specified. +# +# Available modes: +# ---------------- +# 'eval' (default) +# - escape shell special characters +# 'expand' +# - the same as 'eval'; but do not quote variable references +# 'pretty' +# - request aesthetic output, i.e. '"a b"' instead of 'a\ b'. This might +# be used later in func_quote to get output like: 'echo "a b"' instead +# of 'echo a\ b'. This is slower than default on some shells. +# 'unquoted' +# - produce also $func_quote_arg_unquoted_result which does not contain +# wrapping double-quotes. +# +# Examples for 'func_quote_arg pretty,unquoted string': +# +# string | *_result | *_unquoted_result +# ------------+-----------------------+------------------- +# " | \" | \" +# a b | "a b" | a b +# "a b" | "\"a b\"" | \"a b\" +# * | "*" | * +# z="${x-$y}" | "z=\"\${x-\$y}\"" | z=\"\${x-\$y}\" +# +# Examples for 'func_quote_arg pretty,unquoted,expand string': +# +# string | *_result | *_unquoted_result +# --------------+---------------------+-------------------- +# z="${x-$y}" | "z=\"${x-$y}\"" | z=\"${x-$y}\" +func_quote_arg () +{ + _G_quote_expand=false + case ,$1, in + *,expand,*) + _G_quote_expand=: + ;; + esac + + case ,$1, in + *,pretty,*|*,expand,*|*,unquoted,*) + func_quote_portable $_G_quote_expand "$2" + func_quote_arg_result=$func_quote_portable_result + func_quote_arg_unquoted_result=$func_quote_portable_unquoted_result + ;; + *) + # Faster quote-for-eval for some shells. + func_quotefast_eval "$2" + func_quote_arg_result=$func_quotefast_eval_result + ;; + esac +} + + +# func_quote MODEs ARGs... +# ------------------------ +# Quote all ARGs to be evaled later and join them into single command. See +# func_quote_arg's description for more info. +func_quote () +{ + $debug_cmd + _G_func_quote_mode=$1 ; shift + func_quote_result= + while test 0 -lt $#; do + func_quote_arg "$_G_func_quote_mode" "$1" + if test -n "$func_quote_result"; then + func_append func_quote_result " $func_quote_arg_result" + else + func_append func_quote_result "$func_quote_arg_result" + fi + shift + done +} + + +# func_stripname PREFIX SUFFIX NAME +# --------------------------------- +# strip PREFIX and SUFFIX from NAME, and store in func_stripname_result. +# PREFIX and SUFFIX must not contain globbing or regex special +# characters, hashes, percent signs, but SUFFIX may contain a leading +# dot (in which case that matches only a dot). +if test yes = "$_G_HAVE_XSI_OPS"; then + eval 'func_stripname () + { + $debug_cmd + + # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are + # positional parameters, so assign one to ordinary variable first. + func_stripname_result=$3 + func_stripname_result=${func_stripname_result#"$1"} + func_stripname_result=${func_stripname_result%"$2"} + }' +else + func_stripname () + { + $debug_cmd + + case $2 in + .*) func_stripname_result=`$ECHO "$3" | $SED -e "s%^$1%%" -e "s%\\\\$2\$%%"`;; + *) func_stripname_result=`$ECHO "$3" | $SED -e "s%^$1%%" -e "s%$2\$%%"`;; + esac + } +fi + + +# func_show_eval CMD [FAIL_EXP] +# ----------------------------- +# Unless opt_quiet is true, then output CMD. Then, if opt_dryrun is +# not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP +# is given, then evaluate it. +func_show_eval () +{ + $debug_cmd + + _G_cmd=$1 + _G_fail_exp=${2-':'} + + func_quote_arg pretty,expand "$_G_cmd" + eval "func_notquiet $func_quote_arg_result" + + $opt_dry_run || { + eval "$_G_cmd" + _G_status=$? + if test 0 -ne "$_G_status"; then + eval "(exit $_G_status); $_G_fail_exp" + fi + } +} + + +# func_show_eval_locale CMD [FAIL_EXP] +# ------------------------------------ +# Unless opt_quiet is true, then output CMD. Then, if opt_dryrun is +# not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP +# is given, then evaluate it. Use the saved locale for evaluation. +func_show_eval_locale () +{ + $debug_cmd + + _G_cmd=$1 + _G_fail_exp=${2-':'} + + $opt_quiet || { + func_quote_arg expand,pretty "$_G_cmd" + eval "func_echo $func_quote_arg_result" + } + + $opt_dry_run || { + eval "$_G_user_locale + $_G_cmd" + _G_status=$? + eval "$_G_safe_locale" + if test 0 -ne "$_G_status"; then + eval "(exit $_G_status); $_G_fail_exp" + fi + } +} + + +# func_tr_sh +# ---------- +# Turn $1 into a string suitable for a shell variable name. +# Result is stored in $func_tr_sh_result. All characters +# not in the set a-zA-Z0-9_ are replaced with '_'. Further, +# if $1 begins with a digit, a '_' is prepended as well. +func_tr_sh () +{ + $debug_cmd + + case $1 in + [0-9]* | *[!a-zA-Z0-9_]*) + func_tr_sh_result=`$ECHO "$1" | $SED -e 's/^\([0-9]\)/_\1/' -e 's/[^a-zA-Z0-9_]/_/g'` + ;; + * ) + func_tr_sh_result=$1 + ;; + esac +} + + +# func_verbose ARG... +# ------------------- +# Echo program name prefixed message in verbose mode only. +func_verbose () +{ + $debug_cmd + + $opt_verbose && func_echo "$*" + + : +} + + +# func_warn_and_continue ARG... +# ----------------------------- +# Echo program name prefixed warning message to standard error. +func_warn_and_continue () +{ + $debug_cmd + + $require_term_colors + + func_echo_infix_1 "${tc_red}warning$tc_reset" "$*" >&2 +} + + +# func_warning CATEGORY ARG... +# ---------------------------- +# Echo program name prefixed warning message to standard error. Warning +# messages can be filtered according to CATEGORY, where this function +# elides messages where CATEGORY is not listed in the global variable +# 'opt_warning_types'. +func_warning () +{ + $debug_cmd + + # CATEGORY must be in the warning_categories list! + case " $warning_categories " in + *" $1 "*) ;; + *) func_internal_error "invalid warning category '$1'" ;; + esac + + _G_category=$1 + shift + + case " $opt_warning_types " in + *" $_G_category "*) $warning_func ${1+"$@"} ;; + esac +} + + +# func_sort_ver VER1 VER2 +# ----------------------- +# 'sort -V' is not generally available. +# Note this deviates from the version comparison in automake +# in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a +# but this should suffice as we won't be specifying old +# version formats or redundant trailing .0 in bootstrap.conf. +# If we did want full compatibility then we should probably +# use m4_version_compare from autoconf. +func_sort_ver () +{ + $debug_cmd + + printf '%s\n%s\n' "$1" "$2" \ + | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n -k 5,5n -k 6,6n -k 7,7n -k 8,8n -k 9,9n +} + +# func_lt_ver PREV CURR +# --------------------- +# Return true if PREV and CURR are in the correct order according to +# func_sort_ver, otherwise false. Use it like this: +# +# func_lt_ver "$prev_ver" "$proposed_ver" || func_fatal_error "..." +func_lt_ver () +{ + $debug_cmd + + test "x$1" = x`func_sort_ver "$1" "$2" | $SED 1q` +} + + +# Local variables: +# mode: shell-script +# sh-indentation: 2 +# eval: (add-hook 'before-save-hook 'time-stamp) +# time-stamp-pattern: "10/scriptversion=%:y-%02m-%02d.%02H; # UTC" +# time-stamp-time-zone: "UTC" +# End: +#! /bin/sh + +# A portable, pluggable option parser for Bourne shell. +# Written by Gary V. Vaughan, 2010 + +# This is free software. There is NO warranty; not even for +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# +# Copyright (C) 2010-2019, 2021 Bootstrap Authors +# +# This file is dual licensed under the terms of the MIT license +# , and GPL version 2 or later +# . You must apply one of +# these licenses when using or redistributing this software or any of +# the files within it. See the URLs above, or the file `LICENSE` +# included in the Bootstrap distribution for the full license texts. + +# Please report bugs or propose patches to: +# + +# Set a version string for this script. +scriptversion=2019-02-19.15; # UTC + + +## ------ ## +## Usage. ## +## ------ ## + +# This file is a library for parsing options in your shell scripts along +# with assorted other useful supporting features that you can make use +# of too. +# +# For the simplest scripts you might need only: +# +# #!/bin/sh +# . relative/path/to/funclib.sh +# . relative/path/to/options-parser +# scriptversion=1.0 +# func_options ${1+"$@"} +# eval set dummy "$func_options_result"; shift +# ...rest of your script... +# +# In order for the '--version' option to work, you will need to have a +# suitably formatted comment like the one at the top of this file +# starting with '# Written by ' and ending with '# Copyright'. +# +# For '-h' and '--help' to work, you will also need a one line +# description of your script's purpose in a comment directly above the +# '# Written by ' line, like the one at the top of this file. +# +# The default options also support '--debug', which will turn on shell +# execution tracing (see the comment above debug_cmd below for another +# use), and '--verbose' and the func_verbose function to allow your script +# to display verbose messages only when your user has specified +# '--verbose'. +# +# After sourcing this file, you can plug in processing for additional +# options by amending the variables from the 'Configuration' section +# below, and following the instructions in the 'Option parsing' +# section further down. + +## -------------- ## +## Configuration. ## +## -------------- ## + +# You should override these variables in your script after sourcing this +# file so that they reflect the customisations you have added to the +# option parser. + +# The usage line for option parsing errors and the start of '-h' and +# '--help' output messages. You can embed shell variables for delayed +# expansion at the time the message is displayed, but you will need to +# quote other shell meta-characters carefully to prevent them being +# expanded when the contents are evaled. +usage='$progpath [OPTION]...' + +# Short help message in response to '-h' and '--help'. Add to this or +# override it after sourcing this library to reflect the full set of +# options your script accepts. +usage_message="\ + --debug enable verbose shell tracing + -W, --warnings=CATEGORY + report the warnings falling in CATEGORY [all] + -v, --verbose verbosely report processing + --version print version information and exit + -h, --help print short or long help message and exit +" + +# Additional text appended to 'usage_message' in response to '--help'. +long_help_message=" +Warning categories include: + 'all' show all warnings + 'none' turn off all the warnings + 'error' warnings are treated as fatal errors" + +# Help message printed before fatal option parsing errors. +fatal_help="Try '\$progname --help' for more information." + + + +## ------------------------- ## +## Hook function management. ## +## ------------------------- ## + +# This section contains functions for adding, removing, and running hooks +# in the main code. A hook is just a list of function names that can be +# run in order later on. + +# func_hookable FUNC_NAME +# ----------------------- +# Declare that FUNC_NAME will run hooks added with +# 'func_add_hook FUNC_NAME ...'. +func_hookable () +{ + $debug_cmd + + func_append hookable_fns " $1" +} + + +# func_add_hook FUNC_NAME HOOK_FUNC +# --------------------------------- +# Request that FUNC_NAME call HOOK_FUNC before it returns. FUNC_NAME must +# first have been declared "hookable" by a call to 'func_hookable'. +func_add_hook () +{ + $debug_cmd + + case " $hookable_fns " in + *" $1 "*) ;; + *) func_fatal_error "'$1' does not accept hook functions." ;; + esac + + eval func_append ${1}_hooks '" $2"' +} + + +# func_remove_hook FUNC_NAME HOOK_FUNC +# ------------------------------------ +# Remove HOOK_FUNC from the list of hook functions to be called by +# FUNC_NAME. +func_remove_hook () +{ + $debug_cmd + + eval ${1}_hooks='`$ECHO "\$'$1'_hooks" |$SED "s| '$2'||"`' +} + + +# func_propagate_result FUNC_NAME_A FUNC_NAME_B +# --------------------------------------------- +# If the *_result variable of FUNC_NAME_A _is set_, assign its value to +# *_result variable of FUNC_NAME_B. +func_propagate_result () +{ + $debug_cmd + + func_propagate_result_result=: + if eval "test \"\${${1}_result+set}\" = set" + then + eval "${2}_result=\$${1}_result" + else + func_propagate_result_result=false + fi +} + + +# func_run_hooks FUNC_NAME [ARG]... +# --------------------------------- +# Run all hook functions registered to FUNC_NAME. +# It's assumed that the list of hook functions contains nothing more +# than a whitespace-delimited list of legal shell function names, and +# no effort is wasted trying to catch shell meta-characters or preserve +# whitespace. +func_run_hooks () +{ + $debug_cmd + + _G_rc_run_hooks=false + + case " $hookable_fns " in + *" $1 "*) ;; + *) func_fatal_error "'$1' does not support hook functions." ;; + esac + + eval _G_hook_fns=\$$1_hooks; shift + + for _G_hook in $_G_hook_fns; do + func_unset "${_G_hook}_result" + eval $_G_hook '${1+"$@"}' + func_propagate_result $_G_hook func_run_hooks + if $func_propagate_result_result; then + eval set dummy "$func_run_hooks_result"; shift + fi + done +} + + + +## --------------- ## +## Option parsing. ## +## --------------- ## + +# In order to add your own option parsing hooks, you must accept the +# full positional parameter list from your hook function. You may remove +# or edit any options that you action, and then pass back the remaining +# unprocessed options in '_result', escaped +# suitably for 'eval'. +# +# The '_result' variable is automatically unset +# before your hook gets called; for best performance, only set the +# *_result variable when necessary (i.e. don't call the 'func_quote' +# function unnecessarily because it can be an expensive operation on some +# machines). +# +# Like this: +# +# my_options_prep () +# { +# $debug_cmd +# +# # Extend the existing usage message. +# usage_message=$usage_message' +# -s, --silent don'\''t print informational messages +# ' +# # No change in '$@' (ignored completely by this hook). Leave +# # my_options_prep_result variable intact. +# } +# func_add_hook func_options_prep my_options_prep +# +# +# my_silent_option () +# { +# $debug_cmd +# +# args_changed=false +# +# # Note that, for efficiency, we parse as many options as we can +# # recognise in a loop before passing the remainder back to the +# # caller on the first unrecognised argument we encounter. +# while test $# -gt 0; do +# opt=$1; shift +# case $opt in +# --silent|-s) opt_silent=: +# args_changed=: +# ;; +# # Separate non-argument short options: +# -s*) func_split_short_opt "$_G_opt" +# set dummy "$func_split_short_opt_name" \ +# "-$func_split_short_opt_arg" ${1+"$@"} +# shift +# args_changed=: +# ;; +# *) # Make sure the first unrecognised option "$_G_opt" +# # is added back to "$@" in case we need it later, +# # if $args_changed was set to 'true'. +# set dummy "$_G_opt" ${1+"$@"}; shift; break ;; +# esac +# done +# +# # Only call 'func_quote' here if we processed at least one argument. +# if $args_changed; then +# func_quote eval ${1+"$@"} +# my_silent_option_result=$func_quote_result +# fi +# } +# func_add_hook func_parse_options my_silent_option +# +# +# my_option_validation () +# { +# $debug_cmd +# +# $opt_silent && $opt_verbose && func_fatal_help "\ +# '--silent' and '--verbose' options are mutually exclusive." +# } +# func_add_hook func_validate_options my_option_validation +# +# You'll also need to manually amend $usage_message to reflect the extra +# options you parse. It's preferable to append if you can, so that +# multiple option parsing hooks can be added safely. + + +# func_options_finish [ARG]... +# ---------------------------- +# Finishing the option parse loop (call 'func_options' hooks ATM). +func_options_finish () +{ + $debug_cmd + + func_run_hooks func_options ${1+"$@"} + func_propagate_result func_run_hooks func_options_finish +} + + +# func_options [ARG]... +# --------------------- +# All the functions called inside func_options are hookable. See the +# individual implementations for details. +func_hookable func_options +func_options () +{ + $debug_cmd + + _G_options_quoted=false + + for my_func in options_prep parse_options validate_options options_finish + do + func_unset func_${my_func}_result + func_unset func_run_hooks_result + eval func_$my_func '${1+"$@"}' + func_propagate_result func_$my_func func_options + if $func_propagate_result_result; then + eval set dummy "$func_options_result"; shift + _G_options_quoted=: + fi + done + + $_G_options_quoted || { + # As we (func_options) are top-level options-parser function and + # nobody quoted "$@" for us yet, we need to do it explicitly for + # caller. + func_quote eval ${1+"$@"} + func_options_result=$func_quote_result + } +} + + +# func_options_prep [ARG]... +# -------------------------- +# All initialisations required before starting the option parse loop. +# Note that when calling hook functions, we pass through the list of +# positional parameters. If a hook function modifies that list, and +# needs to propagate that back to rest of this script, then the complete +# modified list must be put in 'func_run_hooks_result' before returning. +func_hookable func_options_prep +func_options_prep () +{ + $debug_cmd + + # Option defaults: + opt_verbose=false + opt_warning_types= + + func_run_hooks func_options_prep ${1+"$@"} + func_propagate_result func_run_hooks func_options_prep +} + + +# func_parse_options [ARG]... +# --------------------------- +# The main option parsing loop. +func_hookable func_parse_options +func_parse_options () +{ + $debug_cmd + + _G_parse_options_requote=false + # this just eases exit handling + while test $# -gt 0; do + # Defer to hook functions for initial option parsing, so they + # get priority in the event of reusing an option name. + func_run_hooks func_parse_options ${1+"$@"} + func_propagate_result func_run_hooks func_parse_options + if $func_propagate_result_result; then + eval set dummy "$func_parse_options_result"; shift + # Even though we may have changed "$@", we passed the "$@" array + # down into the hook and it quoted it for us (because we are in + # this if-branch). No need to quote it again. + _G_parse_options_requote=false + fi + + # Break out of the loop if we already parsed every option. + test $# -gt 0 || break + + # We expect that one of the options parsed in this function matches + # and thus we remove _G_opt from "$@" and need to re-quote. + _G_match_parse_options=: + _G_opt=$1 + shift + case $_G_opt in + --debug|-x) debug_cmd='set -x' + func_echo "enabling shell trace mode" >&2 + $debug_cmd + ;; + + --no-warnings|--no-warning|--no-warn) + set dummy --warnings none ${1+"$@"} + shift + ;; + + --warnings|--warning|-W) + if test $# = 0 && func_missing_arg $_G_opt; then + _G_parse_options_requote=: + break + fi + case " $warning_categories $1" in + *" $1 "*) + # trailing space prevents matching last $1 above + func_append_uniq opt_warning_types " $1" + ;; + *all) + opt_warning_types=$warning_categories + ;; + *none) + opt_warning_types=none + warning_func=: + ;; + *error) + opt_warning_types=$warning_categories + warning_func=func_fatal_error + ;; + *) + func_fatal_error \ + "unsupported warning category: '$1'" + ;; + esac + shift + ;; + + --verbose|-v) opt_verbose=: ;; + --version) func_version ;; + -\?|-h) func_usage ;; + --help) func_help ;; + + # Separate optargs to long options (plugins may need this): + --*=*) func_split_equals "$_G_opt" + set dummy "$func_split_equals_lhs" \ + "$func_split_equals_rhs" ${1+"$@"} + shift + ;; + + # Separate optargs to short options: + -W*) + func_split_short_opt "$_G_opt" + set dummy "$func_split_short_opt_name" \ + "$func_split_short_opt_arg" ${1+"$@"} + shift + ;; + + # Separate non-argument short options: + -\?*|-h*|-v*|-x*) + func_split_short_opt "$_G_opt" + set dummy "$func_split_short_opt_name" \ + "-$func_split_short_opt_arg" ${1+"$@"} + shift + ;; + + --) _G_parse_options_requote=: ; break ;; + -*) func_fatal_help "unrecognised option: '$_G_opt'" ;; + *) set dummy "$_G_opt" ${1+"$@"}; shift + _G_match_parse_options=false + break + ;; + esac + + if $_G_match_parse_options; then + _G_parse_options_requote=: + fi + done + + if $_G_parse_options_requote; then + # save modified positional parameters for caller + func_quote eval ${1+"$@"} + func_parse_options_result=$func_quote_result + fi +} + + +# func_validate_options [ARG]... +# ------------------------------ +# Perform any sanity checks on option settings and/or unconsumed +# arguments. +func_hookable func_validate_options +func_validate_options () +{ + $debug_cmd + + # Display all warnings if -W was not given. + test -n "$opt_warning_types" || opt_warning_types=" $warning_categories" + + func_run_hooks func_validate_options ${1+"$@"} + func_propagate_result func_run_hooks func_validate_options + + # Bail if the options were screwed! + $exit_cmd $EXIT_FAILURE +} + + + +## ----------------- ## +## Helper functions. ## +## ----------------- ## + +# This section contains the helper functions used by the rest of the +# hookable option parser framework in ascii-betical order. + + +# func_fatal_help ARG... +# ---------------------- +# Echo program name prefixed message to standard error, followed by +# a help hint, and exit. +func_fatal_help () +{ + $debug_cmd + + eval \$ECHO \""Usage: $usage"\" + eval \$ECHO \""$fatal_help"\" + func_error ${1+"$@"} + exit $EXIT_FAILURE +} + + +# func_help +# --------- +# Echo long help message to standard output and exit. +func_help () +{ + $debug_cmd + + func_usage_message + $ECHO "$long_help_message" + exit 0 +} + + +# func_missing_arg ARGNAME +# ------------------------ +# Echo program name prefixed message to standard error and set global +# exit_cmd. +func_missing_arg () +{ + $debug_cmd + + func_error "Missing argument for '$1'." + exit_cmd=exit +} + + +# func_split_equals STRING +# ------------------------ +# Set func_split_equals_lhs and func_split_equals_rhs shell variables +# after splitting STRING at the '=' sign. +test -z "$_G_HAVE_XSI_OPS" \ + && (eval 'x=a/b/c; + test 5aa/bb/cc = "${#x}${x%%/*}${x%/*}${x#*/}${x##*/}"') 2>/dev/null \ + && _G_HAVE_XSI_OPS=yes + +if test yes = "$_G_HAVE_XSI_OPS" +then + # This is an XSI compatible shell, allowing a faster implementation... + eval 'func_split_equals () + { + $debug_cmd + + func_split_equals_lhs=${1%%=*} + func_split_equals_rhs=${1#*=} + if test "x$func_split_equals_lhs" = "x$1"; then + func_split_equals_rhs= + fi + }' +else + # ...otherwise fall back to using expr, which is often a shell builtin. + func_split_equals () + { + $debug_cmd + + func_split_equals_lhs=`expr "x$1" : 'x\([^=]*\)'` + func_split_equals_rhs= + test "x$func_split_equals_lhs=" = "x$1" \ + || func_split_equals_rhs=`expr "x$1" : 'x[^=]*=\(.*\)$'` + } +fi #func_split_equals + + +# func_split_short_opt SHORTOPT +# ----------------------------- +# Set func_split_short_opt_name and func_split_short_opt_arg shell +# variables after splitting SHORTOPT after the 2nd character. +if test yes = "$_G_HAVE_XSI_OPS" +then + # This is an XSI compatible shell, allowing a faster implementation... + eval 'func_split_short_opt () + { + $debug_cmd + + func_split_short_opt_arg=${1#??} + func_split_short_opt_name=${1%"$func_split_short_opt_arg"} + }' +else + # ...otherwise fall back to using expr, which is often a shell builtin. + func_split_short_opt () + { + $debug_cmd + + func_split_short_opt_name=`expr "x$1" : 'x\(-.\)'` + func_split_short_opt_arg=`expr "x$1" : 'x-.\(.*\)$'` + } +fi #func_split_short_opt + + +# func_usage +# ---------- +# Echo short help message to standard output and exit. +func_usage () +{ + $debug_cmd + + func_usage_message + $ECHO "Run '$progname --help |${PAGER-more}' for full usage" + exit 0 +} + + +# func_usage_message +# ------------------ +# Echo short help message to standard output. +func_usage_message () +{ + $debug_cmd + + eval \$ECHO \""Usage: $usage"\" + echo + $SED -n 's|^# || + /^Written by/{ + x;p;x + } + h + /^Written by/q' < "$progpath" + echo + eval \$ECHO \""$usage_message"\" +} + + +# func_version +# ------------ +# Echo version message to standard output and exit. +# The version message is extracted from the calling file's header +# comments, with leading '# ' stripped: +# 1. First display the progname and version +# 2. Followed by the header comment line matching /^# Written by / +# 3. Then a blank line followed by the first following line matching +# /^# Copyright / +# 4. Immediately followed by any lines between the previous matches, +# except lines preceding the intervening completely blank line. +# For example, see the header comments of this file. +func_version () +{ + $debug_cmd + + printf '%s\n' "$progname $scriptversion" + $SED -n ' + /^# Written by /!b + s|^# ||; p; n + + :fwd2blnk + /./ { + n + b fwd2blnk + } + p; n + + :holdwrnt + s|^# || + s|^# *$|| + /^Copyright /!{ + /./H + n + b holdwrnt + } + + s|\((C)\)[ 0-9,-]*[ ,-]\([1-9][0-9]* \)|\1 \2| + G + s|\(\n\)\n*|\1|g + p; q' < "$progpath" + + exit $? +} + + +# Local variables: +# mode: shell-script +# sh-indentation: 2 +# eval: (add-hook 'before-save-hook 'time-stamp) +# time-stamp-pattern: "30/scriptversion=%:y-%02m-%02d.%02H; # UTC" +# time-stamp-time-zone: "UTC" +# End: + +# Set a version string. +scriptversion='(GNU libtool) 2.4.7' + + +# func_echo ARG... +# ---------------- +# Libtool also displays the current mode in messages, so override +# funclib.sh func_echo with this custom definition. +func_echo () +{ + $debug_cmd + + _G_message=$* + + func_echo_IFS=$IFS + IFS=$nl + for _G_line in $_G_message; do + IFS=$func_echo_IFS + $ECHO "$progname${opt_mode+: $opt_mode}: $_G_line" + done + IFS=$func_echo_IFS +} + + +# func_warning ARG... +# ------------------- +# Libtool warnings are not categorized, so override funclib.sh +# func_warning with this simpler definition. +func_warning () +{ + $debug_cmd + + $warning_func ${1+"$@"} +} + + +## ---------------- ## +## Options parsing. ## +## ---------------- ## + +# Hook in the functions to make sure our own options are parsed during +# the option parsing loop. + +usage='$progpath [OPTION]... [MODE-ARG]...' + +# Short help message in response to '-h'. +usage_message="Options: + --config show all configuration variables + --debug enable verbose shell tracing + -n, --dry-run display commands without modifying any files + --features display basic configuration information and exit + --mode=MODE use operation mode MODE + --no-warnings equivalent to '-Wnone' + --preserve-dup-deps don't remove duplicate dependency libraries + --quiet, --silent don't print informational messages + --tag=TAG use configuration variables from tag TAG + -v, --verbose print more informational messages than default + --version print version information + -W, --warnings=CATEGORY report the warnings falling in CATEGORY [all] + -h, --help, --help-all print short, long, or detailed help message +" + +# Additional text appended to 'usage_message' in response to '--help'. +func_help () +{ + $debug_cmd + + func_usage_message + $ECHO "$long_help_message + +MODE must be one of the following: + + clean remove files from the build directory + compile compile a source file into a libtool object + execute automatically set library path, then run a program + finish complete the installation of libtool libraries + install install libraries or executables + link create a library or an executable + uninstall remove libraries from an installed directory + +MODE-ARGS vary depending on the MODE. When passed as first option, +'--mode=MODE' may be abbreviated as 'MODE' or a unique abbreviation of that. +Try '$progname --help --mode=MODE' for a more detailed description of MODE. + +When reporting a bug, please describe a test case to reproduce it and +include the following information: + + host-triplet: $host + shell: $SHELL + compiler: $LTCC + compiler flags: $LTCFLAGS + linker: $LD (gnu? $with_gnu_ld) + version: $progname $scriptversion Debian-2.4.7-5 + automake: `($AUTOMAKE --version) 2>/dev/null |$SED 1q` + autoconf: `($AUTOCONF --version) 2>/dev/null |$SED 1q` + +Report bugs to . +GNU libtool home page: . +General help using GNU software: ." + exit 0 +} + + +# func_lo2o OBJECT-NAME +# --------------------- +# Transform OBJECT-NAME from a '.lo' suffix to the platform specific +# object suffix. + +lo2o=s/\\.lo\$/.$objext/ +o2lo=s/\\.$objext\$/.lo/ + +if test yes = "$_G_HAVE_XSI_OPS"; then + eval 'func_lo2o () + { + case $1 in + *.lo) func_lo2o_result=${1%.lo}.$objext ;; + * ) func_lo2o_result=$1 ;; + esac + }' + + # func_xform LIBOBJ-OR-SOURCE + # --------------------------- + # Transform LIBOBJ-OR-SOURCE from a '.o' or '.c' (or otherwise) + # suffix to a '.lo' libtool-object suffix. + eval 'func_xform () + { + func_xform_result=${1%.*}.lo + }' +else + # ...otherwise fall back to using sed. + func_lo2o () + { + func_lo2o_result=`$ECHO "$1" | $SED "$lo2o"` + } + + func_xform () + { + func_xform_result=`$ECHO "$1" | $SED 's|\.[^.]*$|.lo|'` + } +fi + + +# func_fatal_configuration ARG... +# ------------------------------- +# Echo program name prefixed message to standard error, followed by +# a configuration failure hint, and exit. +func_fatal_configuration () +{ + func_fatal_error ${1+"$@"} \ + "See the $PACKAGE documentation for more information." \ + "Fatal configuration error." +} + + +# func_config +# ----------- +# Display the configuration for all the tags in this script. +func_config () +{ + re_begincf='^# ### BEGIN LIBTOOL' + re_endcf='^# ### END LIBTOOL' + + # Default configuration. + $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath" + + # Now print the configurations for the tags. + for tagname in $taglist; do + $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath" + done + + exit $? +} + + +# func_features +# ------------- +# Display the features supported by this script. +func_features () +{ + echo "host: $host" + if test yes = "$build_libtool_libs"; then + echo "enable shared libraries" + else + echo "disable shared libraries" + fi + if test yes = "$build_old_libs"; then + echo "enable static libraries" + else + echo "disable static libraries" + fi + + exit $? +} + + +# func_enable_tag TAGNAME +# ----------------------- +# Verify that TAGNAME is valid, and either flag an error and exit, or +# enable the TAGNAME tag. We also add TAGNAME to the global $taglist +# variable here. +func_enable_tag () +{ + # Global variable: + tagname=$1 + + re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$" + re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$" + sed_extractcf=/$re_begincf/,/$re_endcf/p + + # Validate tagname. + case $tagname in + *[!-_A-Za-z0-9,/]*) + func_fatal_error "invalid tag name: $tagname" + ;; + esac + + # Don't test for the "default" C tag, as we know it's + # there but not specially marked. + case $tagname in + CC) ;; + *) + if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then + taglist="$taglist $tagname" + + # Evaluate the configuration. Be careful to quote the path + # and the sed script, to avoid splitting on whitespace, but + # also don't use non-portable quotes within backquotes within + # quotes we have to do it in 2 steps: + extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` + eval "$extractedcf" + else + func_error "ignoring unknown tag $tagname" + fi + ;; + esac +} + + +# func_check_version_match +# ------------------------ +# Ensure that we are using m4 macros, and libtool script from the same +# release of libtool. +func_check_version_match () +{ + if test "$package_revision" != "$macro_revision"; then + if test "$VERSION" != "$macro_version"; then + if test -z "$macro_version"; then + cat >&2 <<_LT_EOF +$progname: Version mismatch error. This is $PACKAGE $VERSION, but the +$progname: definition of this LT_INIT comes from an older release. +$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION +$progname: and run autoconf again. +_LT_EOF + else + cat >&2 <<_LT_EOF +$progname: Version mismatch error. This is $PACKAGE $VERSION, but the +$progname: definition of this LT_INIT comes from $PACKAGE $macro_version. +$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION +$progname: and run autoconf again. +_LT_EOF + fi + else + cat >&2 <<_LT_EOF +$progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, +$progname: but the definition of this LT_INIT comes from revision $macro_revision. +$progname: You should recreate aclocal.m4 with macros from revision $package_revision +$progname: of $PACKAGE $VERSION and run autoconf again. +_LT_EOF + fi + + exit $EXIT_MISMATCH + fi +} + + +# libtool_options_prep [ARG]... +# ----------------------------- +# Preparation for options parsed by libtool. +libtool_options_prep () +{ + $debug_mode + + # Option defaults: + opt_config=false + opt_dlopen= + opt_dry_run=false + opt_help=false + opt_mode= + opt_preserve_dup_deps=false + opt_quiet=false + + nonopt= + preserve_args= + + _G_rc_lt_options_prep=: + + _G_rc_lt_options_prep=: + + # Shorthand for --mode=foo, only valid as the first argument + case $1 in + clean|clea|cle|cl) + shift; set dummy --mode clean ${1+"$@"}; shift + ;; + compile|compil|compi|comp|com|co|c) + shift; set dummy --mode compile ${1+"$@"}; shift + ;; + execute|execut|execu|exec|exe|ex|e) + shift; set dummy --mode execute ${1+"$@"}; shift + ;; + finish|finis|fini|fin|fi|f) + shift; set dummy --mode finish ${1+"$@"}; shift + ;; + install|instal|insta|inst|ins|in|i) + shift; set dummy --mode install ${1+"$@"}; shift + ;; + link|lin|li|l) + shift; set dummy --mode link ${1+"$@"}; shift + ;; + uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) + shift; set dummy --mode uninstall ${1+"$@"}; shift + ;; + *) + _G_rc_lt_options_prep=false + ;; + esac + + if $_G_rc_lt_options_prep; then + # Pass back the list of options. + func_quote eval ${1+"$@"} + libtool_options_prep_result=$func_quote_result + fi +} +func_add_hook func_options_prep libtool_options_prep + + +# libtool_parse_options [ARG]... +# --------------------------------- +# Provide handling for libtool specific options. +libtool_parse_options () +{ + $debug_cmd + + _G_rc_lt_parse_options=false + + # Perform our own loop to consume as many options as possible in + # each iteration. + while test $# -gt 0; do + _G_match_lt_parse_options=: + _G_opt=$1 + shift + case $_G_opt in + --dry-run|--dryrun|-n) + opt_dry_run=: + ;; + + --config) func_config ;; + + --dlopen|-dlopen) + opt_dlopen="${opt_dlopen+$opt_dlopen +}$1" + shift + ;; + + --preserve-dup-deps) + opt_preserve_dup_deps=: ;; + + --features) func_features ;; + + --finish) set dummy --mode finish ${1+"$@"}; shift ;; + + --help) opt_help=: ;; + + --help-all) opt_help=': help-all' ;; + + --mode) test $# = 0 && func_missing_arg $_G_opt && break + opt_mode=$1 + case $1 in + # Valid mode arguments: + clean|compile|execute|finish|install|link|relink|uninstall) ;; + + # Catch anything else as an error + *) func_error "invalid argument for $_G_opt" + exit_cmd=exit + break + ;; + esac + shift + ;; + + --no-silent|--no-quiet) + opt_quiet=false + func_append preserve_args " $_G_opt" + ;; + + --no-warnings|--no-warning|--no-warn) + opt_warning=false + func_append preserve_args " $_G_opt" + ;; + + --no-verbose) + opt_verbose=false + func_append preserve_args " $_G_opt" + ;; + + --silent|--quiet) + opt_quiet=: + opt_verbose=false + func_append preserve_args " $_G_opt" + ;; + + --tag) test $# = 0 && func_missing_arg $_G_opt && break + opt_tag=$1 + func_append preserve_args " $_G_opt $1" + func_enable_tag "$1" + shift + ;; + + --verbose|-v) opt_quiet=false + opt_verbose=: + func_append preserve_args " $_G_opt" + ;; + + # An option not handled by this hook function: + *) set dummy "$_G_opt" ${1+"$@"} ; shift + _G_match_lt_parse_options=false + break + ;; + esac + $_G_match_lt_parse_options && _G_rc_lt_parse_options=: + done + + if $_G_rc_lt_parse_options; then + # save modified positional parameters for caller + func_quote eval ${1+"$@"} + libtool_parse_options_result=$func_quote_result + fi +} +func_add_hook func_parse_options libtool_parse_options + + + +# libtool_validate_options [ARG]... +# --------------------------------- +# Perform any sanity checks on option settings and/or unconsumed +# arguments. +libtool_validate_options () +{ + # save first non-option argument + if test 0 -lt $#; then + nonopt=$1 + shift + fi + + # preserve --debug + test : = "$debug_cmd" || func_append preserve_args " --debug" + + case $host in + # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452 + # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788 + *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*) + # don't eliminate duplications in $postdeps and $predeps + opt_duplicate_compiler_generated_deps=: + ;; + *) + opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps + ;; + esac + + $opt_help || { + # Sanity checks first: + func_check_version_match + + test yes != "$build_libtool_libs" \ + && test yes != "$build_old_libs" \ + && func_fatal_configuration "not configured to build any kind of library" + + # Darwin sucks + eval std_shrext=\"$shrext_cmds\" + + # Only execute mode is allowed to have -dlopen flags. + if test -n "$opt_dlopen" && test execute != "$opt_mode"; then + func_error "unrecognized option '-dlopen'" + $ECHO "$help" 1>&2 + exit $EXIT_FAILURE + fi + + # Change the help message to a mode-specific one. + generic_help=$help + help="Try '$progname --help --mode=$opt_mode' for more information." + } + + # Pass back the unparsed argument list + func_quote eval ${1+"$@"} + libtool_validate_options_result=$func_quote_result +} +func_add_hook func_validate_options libtool_validate_options + + +# Process options as early as possible so that --help and --version +# can return quickly. +func_options ${1+"$@"} +eval set dummy "$func_options_result"; shift + + + +## ----------- ## +## Main. ## +## ----------- ## + +magic='%%%MAGIC variable%%%' +magic_exe='%%%MAGIC EXE variable%%%' + +# Global variables. +extracted_archives= +extracted_serial=0 + +# If this variable is set in any of the actions, the command in it +# will be execed at the end. This prevents here-documents from being +# left over by shells. +exec_cmd= + + +# A function that is used when there is no print builtin or printf. +func_fallback_echo () +{ + eval 'cat <<_LTECHO_EOF +$1 +_LTECHO_EOF' +} + +# func_generated_by_libtool +# True iff stdin has been generated by Libtool. This function is only +# a basic sanity check; it will hardly flush out determined imposters. +func_generated_by_libtool_p () +{ + $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 +} + +# func_lalib_p file +# True iff FILE is a libtool '.la' library or '.lo' object file. +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_lalib_p () +{ + test -f "$1" && + $SED -e 4q "$1" 2>/dev/null | func_generated_by_libtool_p +} + +# func_lalib_unsafe_p file +# True iff FILE is a libtool '.la' library or '.lo' object file. +# This function implements the same check as func_lalib_p without +# resorting to external programs. To this end, it redirects stdin and +# closes it afterwards, without saving the original file descriptor. +# As a safety measure, use it only where a negative result would be +# fatal anyway. Works if 'file' does not exist. +func_lalib_unsafe_p () +{ + lalib_p=no + if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then + for lalib_p_l in 1 2 3 4 + do + read lalib_p_line + case $lalib_p_line in + \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; + esac + done + exec 0<&5 5<&- + fi + test yes = "$lalib_p" +} + +# func_ltwrapper_script_p file +# True iff FILE is a libtool wrapper script +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_ltwrapper_script_p () +{ + test -f "$1" && + $lt_truncate_bin < "$1" 2>/dev/null | func_generated_by_libtool_p +} + +# func_ltwrapper_executable_p file +# True iff FILE is a libtool wrapper executable +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_ltwrapper_executable_p () +{ + func_ltwrapper_exec_suffix= + case $1 in + *.exe) ;; + *) func_ltwrapper_exec_suffix=.exe ;; + esac + $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 +} + +# func_ltwrapper_scriptname file +# Assumes file is an ltwrapper_executable +# uses $file to determine the appropriate filename for a +# temporary ltwrapper_script. +func_ltwrapper_scriptname () +{ + func_dirname_and_basename "$1" "" "." + func_stripname '' '.exe' "$func_basename_result" + func_ltwrapper_scriptname_result=$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper +} + +# func_ltwrapper_p file +# True iff FILE is a libtool wrapper script or wrapper executable +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_ltwrapper_p () +{ + func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" +} + + +# func_execute_cmds commands fail_cmd +# Execute tilde-delimited COMMANDS. +# If FAIL_CMD is given, eval that upon failure. +# FAIL_CMD may read-access the current command in variable CMD! +func_execute_cmds () +{ + $debug_cmd + + save_ifs=$IFS; IFS='~' + for cmd in $1; do + IFS=$sp$nl + eval cmd=\"$cmd\" + IFS=$save_ifs + func_show_eval "$cmd" "${2-:}" + done + IFS=$save_ifs +} + + +# func_source file +# Source FILE, adding directory component if necessary. +# Note that it is not necessary on cygwin/mingw to append a dot to +# FILE even if both FILE and FILE.exe exist: automatic-append-.exe +# behavior happens only for exec(3), not for open(2)! Also, sourcing +# 'FILE.' does not work on cygwin managed mounts. +func_source () +{ + $debug_cmd + + case $1 in + */* | *\\*) . "$1" ;; + *) . "./$1" ;; + esac +} + + +# func_resolve_sysroot PATH +# Replace a leading = in PATH with a sysroot. Store the result into +# func_resolve_sysroot_result +func_resolve_sysroot () +{ + func_resolve_sysroot_result=$1 + case $func_resolve_sysroot_result in + =*) + func_stripname '=' '' "$func_resolve_sysroot_result" + func_resolve_sysroot_result=$lt_sysroot$func_stripname_result + ;; + esac +} + +# func_replace_sysroot PATH +# If PATH begins with the sysroot, replace it with = and +# store the result into func_replace_sysroot_result. +func_replace_sysroot () +{ + case $lt_sysroot:$1 in + ?*:"$lt_sysroot"*) + func_stripname "$lt_sysroot" '' "$1" + func_replace_sysroot_result='='$func_stripname_result + ;; + *) + # Including no sysroot. + func_replace_sysroot_result=$1 + ;; + esac +} + +# func_infer_tag arg +# Infer tagged configuration to use if any are available and +# if one wasn't chosen via the "--tag" command line option. +# Only attempt this if the compiler in the base compile +# command doesn't match the default compiler. +# arg is usually of the form 'gcc ...' +func_infer_tag () +{ + $debug_cmd + + if test -n "$available_tags" && test -z "$tagname"; then + CC_quoted= + for arg in $CC; do + func_append_quoted CC_quoted "$arg" + done + CC_expanded=`func_echo_all $CC` + CC_quoted_expanded=`func_echo_all $CC_quoted` + case $@ in + # Blanks in the command may have been stripped by the calling shell, + # but not from the CC environment variable when configure was run. + " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ + " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;; + # Blanks at the start of $base_compile will cause this to fail + # if we don't check for them as well. + *) + for z in $available_tags; do + if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then + # Evaluate the configuration. + eval "`$SED -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" + CC_quoted= + for arg in $CC; do + # Double-quote args containing other shell metacharacters. + func_append_quoted CC_quoted "$arg" + done + CC_expanded=`func_echo_all $CC` + CC_quoted_expanded=`func_echo_all $CC_quoted` + case "$@ " in + " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ + " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) + # The compiler in the base compile command matches + # the one in the tagged configuration. + # Assume this is the tagged configuration we want. + tagname=$z + break + ;; + esac + fi + done + # If $tagname still isn't set, then no tagged configuration + # was found and let the user know that the "--tag" command + # line option must be used. + if test -z "$tagname"; then + func_echo "unable to infer tagged configuration" + func_fatal_error "specify a tag with '--tag'" +# else +# func_verbose "using $tagname tagged configuration" + fi + ;; + esac + fi +} + + + +# func_write_libtool_object output_name pic_name nonpic_name +# Create a libtool object file (analogous to a ".la" file), +# but don't create it if we're doing a dry run. +func_write_libtool_object () +{ + write_libobj=$1 + if test yes = "$build_libtool_libs"; then + write_lobj=\'$2\' + else + write_lobj=none + fi + + if test yes = "$build_old_libs"; then + write_oldobj=\'$3\' + else + write_oldobj=none + fi + + $opt_dry_run || { + cat >${write_libobj}T </dev/null` + if test "$?" -eq 0 && test -n "$func_convert_core_file_wine_to_w32_tmp"; then + func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" | + $SED -e "$sed_naive_backslashify"` + else + func_convert_core_file_wine_to_w32_result= + fi + fi +} +# end: func_convert_core_file_wine_to_w32 + + +# func_convert_core_path_wine_to_w32 ARG +# Helper function used by path conversion functions when $build is *nix, and +# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly +# configured wine environment available, with the winepath program in $build's +# $PATH. Assumes ARG has no leading or trailing path separator characters. +# +# ARG is path to be converted from $build format to win32. +# Result is available in $func_convert_core_path_wine_to_w32_result. +# Unconvertible file (directory) names in ARG are skipped; if no directory names +# are convertible, then the result may be empty. +func_convert_core_path_wine_to_w32 () +{ + $debug_cmd + + # unfortunately, winepath doesn't convert paths, only file names + func_convert_core_path_wine_to_w32_result= + if test -n "$1"; then + oldIFS=$IFS + IFS=: + for func_convert_core_path_wine_to_w32_f in $1; do + IFS=$oldIFS + func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f" + if test -n "$func_convert_core_file_wine_to_w32_result"; then + if test -z "$func_convert_core_path_wine_to_w32_result"; then + func_convert_core_path_wine_to_w32_result=$func_convert_core_file_wine_to_w32_result + else + func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result" + fi + fi + done + IFS=$oldIFS + fi +} +# end: func_convert_core_path_wine_to_w32 + + +# func_cygpath ARGS... +# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when +# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2) +# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or +# (2), returns the Cygwin file name or path in func_cygpath_result (input +# file name or path is assumed to be in w32 format, as previously converted +# from $build's *nix or MSYS format). In case (3), returns the w32 file name +# or path in func_cygpath_result (input file name or path is assumed to be in +# Cygwin format). Returns an empty string on error. +# +# ARGS are passed to cygpath, with the last one being the file name or path to +# be converted. +# +# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH +# environment variable; do not put it in $PATH. +func_cygpath () +{ + $debug_cmd + + if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then + func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null` + if test "$?" -ne 0; then + # on failure, ensure result is empty + func_cygpath_result= + fi + else + func_cygpath_result= + func_error "LT_CYGPATH is empty or specifies non-existent file: '$LT_CYGPATH'" + fi +} +#end: func_cygpath + + +# func_convert_core_msys_to_w32 ARG +# Convert file name or path ARG from MSYS format to w32 format. Return +# result in func_convert_core_msys_to_w32_result. +func_convert_core_msys_to_w32 () +{ + $debug_cmd + + # awkward: cmd appends spaces to result + func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null | + $SED -e 's/[ ]*$//' -e "$sed_naive_backslashify"` +} +#end: func_convert_core_msys_to_w32 + + +# func_convert_file_check ARG1 ARG2 +# Verify that ARG1 (a file name in $build format) was converted to $host +# format in ARG2. Otherwise, emit an error message, but continue (resetting +# func_to_host_file_result to ARG1). +func_convert_file_check () +{ + $debug_cmd + + if test -z "$2" && test -n "$1"; then + func_error "Could not determine host file name corresponding to" + func_error " '$1'" + func_error "Continuing, but uninstalled executables may not work." + # Fallback: + func_to_host_file_result=$1 + fi +} +# end func_convert_file_check + + +# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH +# Verify that FROM_PATH (a path in $build format) was converted to $host +# format in TO_PATH. Otherwise, emit an error message, but continue, resetting +# func_to_host_file_result to a simplistic fallback value (see below). +func_convert_path_check () +{ + $debug_cmd + + if test -z "$4" && test -n "$3"; then + func_error "Could not determine the host path corresponding to" + func_error " '$3'" + func_error "Continuing, but uninstalled executables may not work." + # Fallback. This is a deliberately simplistic "conversion" and + # should not be "improved". See libtool.info. + if test "x$1" != "x$2"; then + lt_replace_pathsep_chars="s|$1|$2|g" + func_to_host_path_result=`echo "$3" | + $SED -e "$lt_replace_pathsep_chars"` + else + func_to_host_path_result=$3 + fi + fi +} +# end func_convert_path_check + + +# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG +# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT +# and appending REPL if ORIG matches BACKPAT. +func_convert_path_front_back_pathsep () +{ + $debug_cmd + + case $4 in + $1 ) func_to_host_path_result=$3$func_to_host_path_result + ;; + esac + case $4 in + $2 ) func_append func_to_host_path_result "$3" + ;; + esac +} +# end func_convert_path_front_back_pathsep + + +################################################## +# $build to $host FILE NAME CONVERSION FUNCTIONS # +################################################## +# invoked via '$to_host_file_cmd ARG' +# +# In each case, ARG is the path to be converted from $build to $host format. +# Result will be available in $func_to_host_file_result. + + +# func_to_host_file ARG +# Converts the file name ARG from $build format to $host format. Return result +# in func_to_host_file_result. +func_to_host_file () +{ + $debug_cmd + + $to_host_file_cmd "$1" +} +# end func_to_host_file + + +# func_to_tool_file ARG LAZY +# converts the file name ARG from $build format to toolchain format. Return +# result in func_to_tool_file_result. If the conversion in use is listed +# in (the comma separated) LAZY, no conversion takes place. +func_to_tool_file () +{ + $debug_cmd + + case ,$2, in + *,"$to_tool_file_cmd",*) + func_to_tool_file_result=$1 + ;; + *) + $to_tool_file_cmd "$1" + func_to_tool_file_result=$func_to_host_file_result + ;; + esac +} +# end func_to_tool_file + + +# func_convert_file_noop ARG +# Copy ARG to func_to_host_file_result. +func_convert_file_noop () +{ + func_to_host_file_result=$1 +} +# end func_convert_file_noop + + +# func_convert_file_msys_to_w32 ARG +# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic +# conversion to w32 is not available inside the cwrapper. Returns result in +# func_to_host_file_result. +func_convert_file_msys_to_w32 () +{ + $debug_cmd + + func_to_host_file_result=$1 + if test -n "$1"; then + func_convert_core_msys_to_w32 "$1" + func_to_host_file_result=$func_convert_core_msys_to_w32_result + fi + func_convert_file_check "$1" "$func_to_host_file_result" +} +# end func_convert_file_msys_to_w32 + + +# func_convert_file_cygwin_to_w32 ARG +# Convert file name ARG from Cygwin to w32 format. Returns result in +# func_to_host_file_result. +func_convert_file_cygwin_to_w32 () +{ + $debug_cmd + + func_to_host_file_result=$1 + if test -n "$1"; then + # because $build is cygwin, we call "the" cygpath in $PATH; no need to use + # LT_CYGPATH in this case. + func_to_host_file_result=`cygpath -m "$1"` + fi + func_convert_file_check "$1" "$func_to_host_file_result" +} +# end func_convert_file_cygwin_to_w32 + + +# func_convert_file_nix_to_w32 ARG +# Convert file name ARG from *nix to w32 format. Requires a wine environment +# and a working winepath. Returns result in func_to_host_file_result. +func_convert_file_nix_to_w32 () +{ + $debug_cmd + + func_to_host_file_result=$1 + if test -n "$1"; then + func_convert_core_file_wine_to_w32 "$1" + func_to_host_file_result=$func_convert_core_file_wine_to_w32_result + fi + func_convert_file_check "$1" "$func_to_host_file_result" +} +# end func_convert_file_nix_to_w32 + + +# func_convert_file_msys_to_cygwin ARG +# Convert file name ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. +# Returns result in func_to_host_file_result. +func_convert_file_msys_to_cygwin () +{ + $debug_cmd + + func_to_host_file_result=$1 + if test -n "$1"; then + func_convert_core_msys_to_w32 "$1" + func_cygpath -u "$func_convert_core_msys_to_w32_result" + func_to_host_file_result=$func_cygpath_result + fi + func_convert_file_check "$1" "$func_to_host_file_result" +} +# end func_convert_file_msys_to_cygwin + + +# func_convert_file_nix_to_cygwin ARG +# Convert file name ARG from *nix to Cygwin format. Requires Cygwin installed +# in a wine environment, working winepath, and LT_CYGPATH set. Returns result +# in func_to_host_file_result. +func_convert_file_nix_to_cygwin () +{ + $debug_cmd + + func_to_host_file_result=$1 + if test -n "$1"; then + # convert from *nix to w32, then use cygpath to convert from w32 to cygwin. + func_convert_core_file_wine_to_w32 "$1" + func_cygpath -u "$func_convert_core_file_wine_to_w32_result" + func_to_host_file_result=$func_cygpath_result + fi + func_convert_file_check "$1" "$func_to_host_file_result" +} +# end func_convert_file_nix_to_cygwin + + +############################################# +# $build to $host PATH CONVERSION FUNCTIONS # +############################################# +# invoked via '$to_host_path_cmd ARG' +# +# In each case, ARG is the path to be converted from $build to $host format. +# The result will be available in $func_to_host_path_result. +# +# Path separators are also converted from $build format to $host format. If +# ARG begins or ends with a path separator character, it is preserved (but +# converted to $host format) on output. +# +# All path conversion functions are named using the following convention: +# file name conversion function : func_convert_file_X_to_Y () +# path conversion function : func_convert_path_X_to_Y () +# where, for any given $build/$host combination the 'X_to_Y' value is the +# same. If conversion functions are added for new $build/$host combinations, +# the two new functions must follow this pattern, or func_init_to_host_path_cmd +# will break. + + +# func_init_to_host_path_cmd +# Ensures that function "pointer" variable $to_host_path_cmd is set to the +# appropriate value, based on the value of $to_host_file_cmd. +to_host_path_cmd= +func_init_to_host_path_cmd () +{ + $debug_cmd + + if test -z "$to_host_path_cmd"; then + func_stripname 'func_convert_file_' '' "$to_host_file_cmd" + to_host_path_cmd=func_convert_path_$func_stripname_result + fi +} + + +# func_to_host_path ARG +# Converts the path ARG from $build format to $host format. Return result +# in func_to_host_path_result. +func_to_host_path () +{ + $debug_cmd + + func_init_to_host_path_cmd + $to_host_path_cmd "$1" +} +# end func_to_host_path + + +# func_convert_path_noop ARG +# Copy ARG to func_to_host_path_result. +func_convert_path_noop () +{ + func_to_host_path_result=$1 +} +# end func_convert_path_noop + + +# func_convert_path_msys_to_w32 ARG +# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic +# conversion to w32 is not available inside the cwrapper. Returns result in +# func_to_host_path_result. +func_convert_path_msys_to_w32 () +{ + $debug_cmd + + func_to_host_path_result=$1 + if test -n "$1"; then + # Remove leading and trailing path separator characters from ARG. MSYS + # behavior is inconsistent here; cygpath turns them into '.;' and ';.'; + # and winepath ignores them completely. + func_stripname : : "$1" + func_to_host_path_tmp1=$func_stripname_result + func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" + func_to_host_path_result=$func_convert_core_msys_to_w32_result + func_convert_path_check : ";" \ + "$func_to_host_path_tmp1" "$func_to_host_path_result" + func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" + fi +} +# end func_convert_path_msys_to_w32 + + +# func_convert_path_cygwin_to_w32 ARG +# Convert path ARG from Cygwin to w32 format. Returns result in +# func_to_host_file_result. +func_convert_path_cygwin_to_w32 () +{ + $debug_cmd + + func_to_host_path_result=$1 + if test -n "$1"; then + # See func_convert_path_msys_to_w32: + func_stripname : : "$1" + func_to_host_path_tmp1=$func_stripname_result + func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"` + func_convert_path_check : ";" \ + "$func_to_host_path_tmp1" "$func_to_host_path_result" + func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" + fi +} +# end func_convert_path_cygwin_to_w32 + + +# func_convert_path_nix_to_w32 ARG +# Convert path ARG from *nix to w32 format. Requires a wine environment and +# a working winepath. Returns result in func_to_host_file_result. +func_convert_path_nix_to_w32 () +{ + $debug_cmd + + func_to_host_path_result=$1 + if test -n "$1"; then + # See func_convert_path_msys_to_w32: + func_stripname : : "$1" + func_to_host_path_tmp1=$func_stripname_result + func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" + func_to_host_path_result=$func_convert_core_path_wine_to_w32_result + func_convert_path_check : ";" \ + "$func_to_host_path_tmp1" "$func_to_host_path_result" + func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" + fi +} +# end func_convert_path_nix_to_w32 + + +# func_convert_path_msys_to_cygwin ARG +# Convert path ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. +# Returns result in func_to_host_file_result. +func_convert_path_msys_to_cygwin () +{ + $debug_cmd + + func_to_host_path_result=$1 + if test -n "$1"; then + # See func_convert_path_msys_to_w32: + func_stripname : : "$1" + func_to_host_path_tmp1=$func_stripname_result + func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" + func_cygpath -u -p "$func_convert_core_msys_to_w32_result" + func_to_host_path_result=$func_cygpath_result + func_convert_path_check : : \ + "$func_to_host_path_tmp1" "$func_to_host_path_result" + func_convert_path_front_back_pathsep ":*" "*:" : "$1" + fi +} +# end func_convert_path_msys_to_cygwin + + +# func_convert_path_nix_to_cygwin ARG +# Convert path ARG from *nix to Cygwin format. Requires Cygwin installed in a +# a wine environment, working winepath, and LT_CYGPATH set. Returns result in +# func_to_host_file_result. +func_convert_path_nix_to_cygwin () +{ + $debug_cmd + + func_to_host_path_result=$1 + if test -n "$1"; then + # Remove leading and trailing path separator characters from + # ARG. msys behavior is inconsistent here, cygpath turns them + # into '.;' and ';.', and winepath ignores them completely. + func_stripname : : "$1" + func_to_host_path_tmp1=$func_stripname_result + func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" + func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result" + func_to_host_path_result=$func_cygpath_result + func_convert_path_check : : \ + "$func_to_host_path_tmp1" "$func_to_host_path_result" + func_convert_path_front_back_pathsep ":*" "*:" : "$1" + fi +} +# end func_convert_path_nix_to_cygwin + + +# func_dll_def_p FILE +# True iff FILE is a Windows DLL '.def' file. +# Keep in sync with _LT_DLL_DEF_P in libtool.m4 +func_dll_def_p () +{ + $debug_cmd + + func_dll_def_p_tmp=`$SED -n \ + -e 's/^[ ]*//' \ + -e '/^\(;.*\)*$/d' \ + -e 's/^\(EXPORTS\|LIBRARY\)\([ ].*\)*$/DEF/p' \ + -e q \ + "$1"` + test DEF = "$func_dll_def_p_tmp" +} + + +# func_mode_compile arg... +func_mode_compile () +{ + $debug_cmd + + # Get the compilation command and the source file. + base_compile= + srcfile=$nonopt # always keep a non-empty value in "srcfile" + suppress_opt=yes + suppress_output= + arg_mode=normal + libobj= + later= + pie_flag= + + for arg + do + case $arg_mode in + arg ) + # do not "continue". Instead, add this to base_compile + lastarg=$arg + arg_mode=normal + ;; + + target ) + libobj=$arg + arg_mode=normal + continue + ;; + + normal ) + # Accept any command-line options. + case $arg in + -o) + test -n "$libobj" && \ + func_fatal_error "you cannot specify '-o' more than once" + arg_mode=target + continue + ;; + + -pie | -fpie | -fPIE) + func_append pie_flag " $arg" + continue + ;; + + -shared | -static | -prefer-pic | -prefer-non-pic) + func_append later " $arg" + continue + ;; + + -no-suppress) + suppress_opt=no + continue + ;; + + -Xcompiler) + arg_mode=arg # the next one goes into the "base_compile" arg list + continue # The current "srcfile" will either be retained or + ;; # replaced later. I would guess that would be a bug. + + -Wc,*) + func_stripname '-Wc,' '' "$arg" + args=$func_stripname_result + lastarg= + save_ifs=$IFS; IFS=, + for arg in $args; do + IFS=$save_ifs + func_append_quoted lastarg "$arg" + done + IFS=$save_ifs + func_stripname ' ' '' "$lastarg" + lastarg=$func_stripname_result + + # Add the arguments to base_compile. + func_append base_compile " $lastarg" + continue + ;; + + *) + # Accept the current argument as the source file. + # The previous "srcfile" becomes the current argument. + # + lastarg=$srcfile + srcfile=$arg + ;; + esac # case $arg + ;; + esac # case $arg_mode + + # Aesthetically quote the previous argument. + func_append_quoted base_compile "$lastarg" + done # for arg + + case $arg_mode in + arg) + func_fatal_error "you must specify an argument for -Xcompile" + ;; + target) + func_fatal_error "you must specify a target with '-o'" + ;; + *) + # Get the name of the library object. + test -z "$libobj" && { + func_basename "$srcfile" + libobj=$func_basename_result + } + ;; + esac + + # Recognize several different file suffixes. + # If the user specifies -o file.o, it is replaced with file.lo + case $libobj in + *.[cCFSifmso] | \ + *.ada | *.adb | *.ads | *.asm | \ + *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \ + *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup) + func_xform "$libobj" + libobj=$func_xform_result + ;; + esac + + case $libobj in + *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;; + *) + func_fatal_error "cannot determine name of library object from '$libobj'" + ;; + esac + + func_infer_tag $base_compile + + for arg in $later; do + case $arg in + -shared) + test yes = "$build_libtool_libs" \ + || func_fatal_configuration "cannot build a shared library" + build_old_libs=no + continue + ;; + + -static) + build_libtool_libs=no + build_old_libs=yes + continue + ;; + + -prefer-pic) + pic_mode=yes + continue + ;; + + -prefer-non-pic) + pic_mode=no + continue + ;; + esac + done + + func_quote_arg pretty "$libobj" + test "X$libobj" != "X$func_quote_arg_result" \ + && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"' &()|`$[]' \ + && func_warning "libobj name '$libobj' may not contain shell special characters." + func_dirname_and_basename "$obj" "/" "" + objname=$func_basename_result + xdir=$func_dirname_result + lobj=$xdir$objdir/$objname + + test -z "$base_compile" && \ + func_fatal_help "you must specify a compilation command" + + # Delete any leftover library objects. + if test yes = "$build_old_libs"; then + removelist="$obj $lobj $libobj ${libobj}T" + else + removelist="$lobj $libobj ${libobj}T" + fi + + # On Cygwin there's no "real" PIC flag so we must build both object types + case $host_os in + cygwin* | mingw* | pw32* | os2* | cegcc*) + pic_mode=default + ;; + esac + if test no = "$pic_mode" && test pass_all != "$deplibs_check_method"; then + # non-PIC code in shared libraries is not supported + pic_mode=default + fi + + # Calculate the filename of the output object if compiler does + # not support -o with -c + if test no = "$compiler_c_o"; then + output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.$objext + lockfile=$output_obj.lock + else + output_obj= + need_locks=no + lockfile= + fi + + # Lock this critical section if it is needed + # We use this script file to make the link, it avoids creating a new file + if test yes = "$need_locks"; then + until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do + func_echo "Waiting for $lockfile to be removed" + sleep 2 + done + elif test warn = "$need_locks"; then + if test -f "$lockfile"; then + $ECHO "\ +*** ERROR, $lockfile exists and contains: +`cat $lockfile 2>/dev/null` + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support '-c' and '-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $opt_dry_run || $RM $removelist + exit $EXIT_FAILURE + fi + func_append removelist " $output_obj" + $ECHO "$srcfile" > "$lockfile" + fi + + $opt_dry_run || $RM $removelist + func_append removelist " $lockfile" + trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 + + func_to_tool_file "$srcfile" func_convert_file_msys_to_w32 + srcfile=$func_to_tool_file_result + func_quote_arg pretty "$srcfile" + qsrcfile=$func_quote_arg_result + + # Only build a PIC object if we are building libtool libraries. + if test yes = "$build_libtool_libs"; then + # Without this assignment, base_compile gets emptied. + fbsd_hideous_sh_bug=$base_compile + + if test no != "$pic_mode"; then + command="$base_compile $qsrcfile $pic_flag" + else + # Don't build PIC code + command="$base_compile $qsrcfile" + fi + + func_mkdir_p "$xdir$objdir" + + if test -z "$output_obj"; then + # Place PIC objects in $objdir + func_append command " -o $lobj" + fi + + func_show_eval_locale "$command" \ + 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' + + if test warn = "$need_locks" && + test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then + $ECHO "\ +*** ERROR, $lockfile contains: +`cat $lockfile 2>/dev/null` + +but it should contain: +$srcfile + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support '-c' and '-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $opt_dry_run || $RM $removelist + exit $EXIT_FAILURE + fi + + # Just move the object if needed, then go on to compile the next one + if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then + func_show_eval '$MV "$output_obj" "$lobj"' \ + 'error=$?; $opt_dry_run || $RM $removelist; exit $error' + fi + + # Allow error messages only from the first compilation. + if test yes = "$suppress_opt"; then + suppress_output=' >/dev/null 2>&1' + fi + fi + + # Only build a position-dependent object if we build old libraries. + if test yes = "$build_old_libs"; then + if test yes != "$pic_mode"; then + # Don't build PIC code + command="$base_compile $qsrcfile$pie_flag" + else + command="$base_compile $qsrcfile $pic_flag" + fi + if test yes = "$compiler_c_o"; then + func_append command " -o $obj" + fi + + # Suppress compiler output if we already did a PIC compilation. + func_append command "$suppress_output" + func_show_eval_locale "$command" \ + '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' + + if test warn = "$need_locks" && + test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then + $ECHO "\ +*** ERROR, $lockfile contains: +`cat $lockfile 2>/dev/null` + +but it should contain: +$srcfile + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support '-c' and '-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $opt_dry_run || $RM $removelist + exit $EXIT_FAILURE + fi + + # Just move the object if needed + if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then + func_show_eval '$MV "$output_obj" "$obj"' \ + 'error=$?; $opt_dry_run || $RM $removelist; exit $error' + fi + fi + + $opt_dry_run || { + func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" + + # Unlock the critical section if it was locked + if test no != "$need_locks"; then + removelist=$lockfile + $RM "$lockfile" + fi + } + + exit $EXIT_SUCCESS +} + +$opt_help || { + test compile = "$opt_mode" && func_mode_compile ${1+"$@"} +} + +func_mode_help () +{ + # We need to display help for each of the modes. + case $opt_mode in + "") + # Generic help is extracted from the usage comments + # at the start of this file. + func_help + ;; + + clean) + $ECHO \ +"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... + +Remove files from the build directory. + +RM is the name of the program to use to delete files associated with each FILE +(typically '/bin/rm'). RM-OPTIONS are options (such as '-f') to be passed +to RM. + +If FILE is a libtool library, object or program, all the files associated +with it are deleted. Otherwise, only FILE itself is deleted using RM." + ;; + + compile) + $ECHO \ +"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE + +Compile a source file into a libtool library object. + +This mode accepts the following additional options: + + -o OUTPUT-FILE set the output file name to OUTPUT-FILE + -no-suppress do not suppress compiler output for multiple passes + -prefer-pic try to build PIC objects only + -prefer-non-pic try to build non-PIC objects only + -shared do not build a '.o' file suitable for static linking + -static only build a '.o' file suitable for static linking + -Wc,FLAG + -Xcompiler FLAG pass FLAG directly to the compiler + +COMPILE-COMMAND is a command to be used in creating a 'standard' object file +from the given SOURCEFILE. + +The output file name is determined by removing the directory component from +SOURCEFILE, then substituting the C source code suffix '.c' with the +library object suffix, '.lo'." + ;; + + execute) + $ECHO \ +"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... + +Automatically set library path, then run a program. + +This mode accepts the following additional options: + + -dlopen FILE add the directory containing FILE to the library path + +This mode sets the library path environment variable according to '-dlopen' +flags. + +If any of the ARGS are libtool executable wrappers, then they are translated +into their corresponding uninstalled binary, and any of their required library +directories are added to the library path. + +Then, COMMAND is executed, with ARGS as arguments." + ;; + + finish) + $ECHO \ +"Usage: $progname [OPTION]... --mode=finish [LIBDIR]... + +Complete the installation of libtool libraries. + +Each LIBDIR is a directory that contains libtool libraries. + +The commands that this mode executes may require superuser privileges. Use +the '--dry-run' option if you just want to see what would be executed." + ;; + + install) + $ECHO \ +"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... + +Install executables or libraries. + +INSTALL-COMMAND is the installation command. The first component should be +either the 'install' or 'cp' program. + +The following components of INSTALL-COMMAND are treated specially: + + -inst-prefix-dir PREFIX-DIR Use PREFIX-DIR as a staging area for installation + +The rest of the components are interpreted as arguments to that command (only +BSD-compatible install options are recognized)." + ;; + + link) + $ECHO \ +"Usage: $progname [OPTION]... --mode=link LINK-COMMAND... + +Link object files or libraries together to form another library, or to +create an executable program. + +LINK-COMMAND is a command using the C compiler that you would use to create +a program from several object files. + +The following components of LINK-COMMAND are treated specially: + + -all-static do not do any dynamic linking at all + -avoid-version do not add a version suffix if possible + -bindir BINDIR specify path to binaries directory (for systems where + libraries must be found in the PATH setting at runtime) + -dlopen FILE '-dlpreopen' FILE if it cannot be dlopened at runtime + -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols + -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) + -export-symbols SYMFILE + try to export only the symbols listed in SYMFILE + -export-symbols-regex REGEX + try to export only the symbols matching REGEX + -LLIBDIR search LIBDIR for required installed libraries + -lNAME OUTPUT-FILE requires the installed library libNAME + -module build a library that can dlopened + -no-fast-install disable the fast-install mode + -no-install link a not-installable executable + -no-undefined declare that a library does not refer to external symbols + -o OUTPUT-FILE create OUTPUT-FILE from the specified objects + -objectlist FILE use a list of object files found in FILE to specify objects + -os2dllname NAME force a short DLL name on OS/2 (no effect on other OSes) + -precious-files-regex REGEX + don't remove output files matching REGEX + -release RELEASE specify package release information + -rpath LIBDIR the created library will eventually be installed in LIBDIR + -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries + -shared only do dynamic linking of libtool libraries + -shrext SUFFIX override the standard shared library file extension + -static do not do any dynamic linking of uninstalled libtool libraries + -static-libtool-libs + do not do any dynamic linking of libtool libraries + -version-info CURRENT[:REVISION[:AGE]] + specify library version info [each variable defaults to 0] + -weak LIBNAME declare that the target provides the LIBNAME interface + -Wc,FLAG + -Xcompiler FLAG pass linker-specific FLAG directly to the compiler + -Wa,FLAG + -Xassembler FLAG pass linker-specific FLAG directly to the assembler + -Wl,FLAG + -Xlinker FLAG pass linker-specific FLAG directly to the linker + -XCClinker FLAG pass link-specific FLAG to the compiler driver (CC) + +All other options (arguments beginning with '-') are ignored. + +Every other argument is treated as a filename. Files ending in '.la' are +treated as uninstalled libtool libraries, other files are standard or library +object files. + +If the OUTPUT-FILE ends in '.la', then a libtool library is created, +only library objects ('.lo' files) may be specified, and '-rpath' is +required, except when creating a convenience library. + +If OUTPUT-FILE ends in '.a' or '.lib', then a standard library is created +using 'ar' and 'ranlib', or on Windows using 'lib'. + +If OUTPUT-FILE ends in '.lo' or '.$objext', then a reloadable object file +is created, otherwise an executable program is created." + ;; + + uninstall) + $ECHO \ +"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... + +Remove libraries from an installation directory. + +RM is the name of the program to use to delete files associated with each FILE +(typically '/bin/rm'). RM-OPTIONS are options (such as '-f') to be passed +to RM. + +If FILE is a libtool library, all the files associated with it are deleted. +Otherwise, only FILE itself is deleted using RM." + ;; + + *) + func_fatal_help "invalid operation mode '$opt_mode'" + ;; + esac + + echo + $ECHO "Try '$progname --help' for more information about other modes." +} + +# Now that we've collected a possible --mode arg, show help if necessary +if $opt_help; then + if test : = "$opt_help"; then + func_mode_help + else + { + func_help noexit + for opt_mode in compile link execute install finish uninstall clean; do + func_mode_help + done + } | $SED -n '1p; 2,$s/^Usage:/ or: /p' + { + func_help noexit + for opt_mode in compile link execute install finish uninstall clean; do + echo + func_mode_help + done + } | + $SED '1d + /^When reporting/,/^Report/{ + H + d + } + $x + /information about other modes/d + /more detailed .*MODE/d + s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/' + fi + exit $? +fi + + +# func_mode_execute arg... +func_mode_execute () +{ + $debug_cmd + + # The first argument is the command name. + cmd=$nonopt + test -z "$cmd" && \ + func_fatal_help "you must specify a COMMAND" + + # Handle -dlopen flags immediately. + for file in $opt_dlopen; do + test -f "$file" \ + || func_fatal_help "'$file' is not a file" + + dir= + case $file in + *.la) + func_resolve_sysroot "$file" + file=$func_resolve_sysroot_result + + # Check to see that this really is a libtool archive. + func_lalib_unsafe_p "$file" \ + || func_fatal_help "'$lib' is not a valid libtool archive" + + # Read the libtool library. + dlname= + library_names= + func_source "$file" + + # Skip this library if it cannot be dlopened. + if test -z "$dlname"; then + # Warn if it was a shared library. + test -n "$library_names" && \ + func_warning "'$file' was not linked with '-export-dynamic'" + continue + fi + + func_dirname "$file" "" "." + dir=$func_dirname_result + + if test -f "$dir/$objdir/$dlname"; then + func_append dir "/$objdir" + else + if test ! -f "$dir/$dlname"; then + func_fatal_error "cannot find '$dlname' in '$dir' or '$dir/$objdir'" + fi + fi + ;; + + *.lo) + # Just add the directory containing the .lo file. + func_dirname "$file" "" "." + dir=$func_dirname_result + ;; + + *) + func_warning "'-dlopen' is ignored for non-libtool libraries and objects" + continue + ;; + esac + + # Get the absolute pathname. + absdir=`cd "$dir" && pwd` + test -n "$absdir" && dir=$absdir + + # Now add the directory to shlibpath_var. + if eval "test -z \"\$$shlibpath_var\""; then + eval "$shlibpath_var=\"\$dir\"" + else + eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" + fi + done + + # This variable tells wrapper scripts just to set shlibpath_var + # rather than running their programs. + libtool_execute_magic=$magic + + # Check if any of the arguments is a wrapper script. + args= + for file + do + case $file in + -* | *.la | *.lo ) ;; + *) + # Do a test to see if this is really a libtool program. + if func_ltwrapper_script_p "$file"; then + func_source "$file" + # Transform arg to wrapped name. + file=$progdir/$program + elif func_ltwrapper_executable_p "$file"; then + func_ltwrapper_scriptname "$file" + func_source "$func_ltwrapper_scriptname_result" + # Transform arg to wrapped name. + file=$progdir/$program + fi + ;; + esac + # Quote arguments (to preserve shell metacharacters). + func_append_quoted args "$file" + done + + if $opt_dry_run; then + # Display what would be done. + if test -n "$shlibpath_var"; then + eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" + echo "export $shlibpath_var" + fi + $ECHO "$cmd$args" + exit $EXIT_SUCCESS + else + if test -n "$shlibpath_var"; then + # Export the shlibpath_var. + eval "export $shlibpath_var" + fi + + # Restore saved environment variables + for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES + do + eval "if test \"\${save_$lt_var+set}\" = set; then + $lt_var=\$save_$lt_var; export $lt_var + else + $lt_unset $lt_var + fi" + done + + # Now prepare to actually exec the command. + exec_cmd=\$cmd$args + fi +} + +test execute = "$opt_mode" && func_mode_execute ${1+"$@"} + + +# func_mode_finish arg... +func_mode_finish () +{ + $debug_cmd + + libs= + libdirs= + admincmds= + + for opt in "$nonopt" ${1+"$@"} + do + if test -d "$opt"; then + func_append libdirs " $opt" + + elif test -f "$opt"; then + if func_lalib_unsafe_p "$opt"; then + func_append libs " $opt" + else + func_warning "'$opt' is not a valid libtool archive" + fi + + else + func_fatal_error "invalid argument '$opt'" + fi + done + + if test -n "$libs"; then + if test -n "$lt_sysroot"; then + sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"` + sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;" + else + sysroot_cmd= + fi + + # Remove sysroot references + if $opt_dry_run; then + for lib in $libs; do + echo "removing references to $lt_sysroot and '=' prefixes from $lib" + done + else + tmpdir=`func_mktempdir` + for lib in $libs; do + $SED -e "$sysroot_cmd s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \ + > $tmpdir/tmp-la + mv -f $tmpdir/tmp-la $lib + done + ${RM}r "$tmpdir" + fi + fi + + if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then + for libdir in $libdirs; do + if test -n "$finish_cmds"; then + # Do each command in the finish commands. + func_execute_cmds "$finish_cmds" 'admincmds="$admincmds +'"$cmd"'"' + fi + if test -n "$finish_eval"; then + # Do the single finish_eval. + eval cmds=\"$finish_eval\" + $opt_dry_run || eval "$cmds" || func_append admincmds " + $cmds" + fi + done + fi + + # Exit here if they wanted silent mode. + $opt_quiet && exit $EXIT_SUCCESS + + if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then + echo "----------------------------------------------------------------------" + echo "Libraries have been installed in:" + for libdir in $libdirs; do + $ECHO " $libdir" + done + echo + echo "If you ever happen to want to link against installed libraries" + echo "in a given directory, LIBDIR, you must either use libtool, and" + echo "specify the full pathname of the library, or use the '-LLIBDIR'" + echo "flag during linking and do at least one of the following:" + if test -n "$shlibpath_var"; then + echo " - add LIBDIR to the '$shlibpath_var' environment variable" + echo " during execution" + fi + if test -n "$runpath_var"; then + echo " - add LIBDIR to the '$runpath_var' environment variable" + echo " during linking" + fi + if test -n "$hardcode_libdir_flag_spec"; then + libdir=LIBDIR + eval flag=\"$hardcode_libdir_flag_spec\" + + $ECHO " - use the '$flag' linker flag" + fi + if test -n "$admincmds"; then + $ECHO " - have your system administrator run these commands:$admincmds" + fi + if test -f /etc/ld.so.conf; then + echo " - have your system administrator add LIBDIR to '/etc/ld.so.conf'" + fi + echo + + echo "See any operating system documentation about shared libraries for" + case $host in + solaris2.[6789]|solaris2.1[0-9]) + echo "more information, such as the ld(1), crle(1) and ld.so(8) manual" + echo "pages." + ;; + *) + echo "more information, such as the ld(1) and ld.so(8) manual pages." + ;; + esac + echo "----------------------------------------------------------------------" + fi + exit $EXIT_SUCCESS +} + +test finish = "$opt_mode" && func_mode_finish ${1+"$@"} + + +# func_mode_install arg... +func_mode_install () +{ + $debug_cmd + + # There may be an optional sh(1) argument at the beginning of + # install_prog (especially on Windows NT). + if test "$SHELL" = "$nonopt" || test /bin/sh = "$nonopt" || + # Allow the use of GNU shtool's install command. + case $nonopt in *shtool*) :;; *) false;; esac + then + # Aesthetically quote it. + func_quote_arg pretty "$nonopt" + install_prog="$func_quote_arg_result " + arg=$1 + shift + else + install_prog= + arg=$nonopt + fi + + # The real first argument should be the name of the installation program. + # Aesthetically quote it. + func_quote_arg pretty "$arg" + func_append install_prog "$func_quote_arg_result" + install_shared_prog=$install_prog + case " $install_prog " in + *[\\\ /]cp\ *) install_cp=: ;; + *) install_cp=false ;; + esac + + # We need to accept at least all the BSD install flags. + dest= + files= + opts= + prev= + install_type= + isdir=false + stripme= + no_mode=: + for arg + do + arg2= + if test -n "$dest"; then + func_append files " $dest" + dest=$arg + continue + fi + + case $arg in + -d) isdir=: ;; + -f) + if $install_cp; then :; else + prev=$arg + fi + ;; + -g | -m | -o) + prev=$arg + ;; + -s) + stripme=" -s" + continue + ;; + -*) + ;; + *) + # If the previous option needed an argument, then skip it. + if test -n "$prev"; then + if test X-m = "X$prev" && test -n "$install_override_mode"; then + arg2=$install_override_mode + no_mode=false + fi + prev= + else + dest=$arg + continue + fi + ;; + esac + + # Aesthetically quote the argument. + func_quote_arg pretty "$arg" + func_append install_prog " $func_quote_arg_result" + if test -n "$arg2"; then + func_quote_arg pretty "$arg2" + fi + func_append install_shared_prog " $func_quote_arg_result" + done + + test -z "$install_prog" && \ + func_fatal_help "you must specify an install program" + + test -n "$prev" && \ + func_fatal_help "the '$prev' option requires an argument" + + if test -n "$install_override_mode" && $no_mode; then + if $install_cp; then :; else + func_quote_arg pretty "$install_override_mode" + func_append install_shared_prog " -m $func_quote_arg_result" + fi + fi + + if test -z "$files"; then + if test -z "$dest"; then + func_fatal_help "no file or destination specified" + else + func_fatal_help "you must specify a destination" + fi + fi + + # Strip any trailing slash from the destination. + func_stripname '' '/' "$dest" + dest=$func_stripname_result + + # Check to see that the destination is a directory. + test -d "$dest" && isdir=: + if $isdir; then + destdir=$dest + destname= + else + func_dirname_and_basename "$dest" "" "." + destdir=$func_dirname_result + destname=$func_basename_result + + # Not a directory, so check to see that there is only one file specified. + set dummy $files; shift + test "$#" -gt 1 && \ + func_fatal_help "'$dest' is not a directory" + fi + case $destdir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + for file in $files; do + case $file in + *.lo) ;; + *) + func_fatal_help "'$destdir' must be an absolute directory name" + ;; + esac + done + ;; + esac + + # This variable tells wrapper scripts just to set variables rather + # than running their programs. + libtool_install_magic=$magic + + staticlibs= + future_libdirs= + current_libdirs= + for file in $files; do + + # Do each installation. + case $file in + *.$libext) + # Do the static libraries later. + func_append staticlibs " $file" + ;; + + *.la) + func_resolve_sysroot "$file" + file=$func_resolve_sysroot_result + + # Check to see that this really is a libtool archive. + func_lalib_unsafe_p "$file" \ + || func_fatal_help "'$file' is not a valid libtool archive" + + library_names= + old_library= + relink_command= + func_source "$file" + + # Add the libdir to current_libdirs if it is the destination. + if test "X$destdir" = "X$libdir"; then + case "$current_libdirs " in + *" $libdir "*) ;; + *) func_append current_libdirs " $libdir" ;; + esac + else + # Note the libdir as a future libdir. + case "$future_libdirs " in + *" $libdir "*) ;; + *) func_append future_libdirs " $libdir" ;; + esac + fi + + func_dirname "$file" "/" "" + dir=$func_dirname_result + func_append dir "$objdir" + + if test -n "$relink_command"; then + # Determine the prefix the user has applied to our future dir. + inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"` + + # Don't allow the user to place us outside of our expected + # location b/c this prevents finding dependent libraries that + # are installed to the same prefix. + # At present, this check doesn't affect windows .dll's that + # are installed into $libdir/../bin (currently, that works fine) + # but it's something to keep an eye on. + test "$inst_prefix_dir" = "$destdir" && \ + func_fatal_error "error: cannot install '$file' to a directory not ending in $libdir" + + if test -n "$inst_prefix_dir"; then + # Stick the inst_prefix_dir data into the link command. + relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` + else + relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"` + fi + + func_warning "relinking '$file'" + func_show_eval "$relink_command" \ + 'func_fatal_error "error: relink '\''$file'\'' with the above command before installing it"' + fi + + # See the names of the shared library. + set dummy $library_names; shift + if test -n "$1"; then + realname=$1 + shift + + srcname=$realname + test -n "$relink_command" && srcname=${realname}T + + # Install the shared library and build the symlinks. + func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \ + 'exit $?' + tstripme=$stripme + case $host_os in + cygwin* | mingw* | pw32* | cegcc*) + case $realname in + *.dll.a) + tstripme= + ;; + esac + ;; + os2*) + case $realname in + *_dll.a) + tstripme= + ;; + esac + ;; + esac + if test -n "$tstripme" && test -n "$striplib"; then + func_show_eval "$striplib $destdir/$realname" 'exit $?' + fi + + if test "$#" -gt 0; then + # Delete the old symlinks, and create new ones. + # Try 'ln -sf' first, because the 'ln' binary might depend on + # the symlink we replace! Solaris /bin/ln does not understand -f, + # so we also need to try rm && ln -s. + for linkname + do + test "$linkname" != "$realname" \ + && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" + done + fi + + # Do each command in the postinstall commands. + lib=$destdir/$realname + func_execute_cmds "$postinstall_cmds" 'exit $?' + fi + + # Install the pseudo-library for information purposes. + func_basename "$file" + name=$func_basename_result + instname=$dir/${name}i + func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' + + # Maybe install the static library, too. + test -n "$old_library" && func_append staticlibs " $dir/$old_library" + ;; + + *.lo) + # Install (i.e. copy) a libtool object. + + # Figure out destination file name, if it wasn't already specified. + if test -n "$destname"; then + destfile=$destdir/$destname + else + func_basename "$file" + destfile=$func_basename_result + destfile=$destdir/$destfile + fi + + # Deduce the name of the destination old-style object file. + case $destfile in + *.lo) + func_lo2o "$destfile" + staticdest=$func_lo2o_result + ;; + *.$objext) + staticdest=$destfile + destfile= + ;; + *) + func_fatal_help "cannot copy a libtool object to '$destfile'" + ;; + esac + + # Install the libtool object if requested. + test -n "$destfile" && \ + func_show_eval "$install_prog $file $destfile" 'exit $?' + + # Install the old object if enabled. + if test yes = "$build_old_libs"; then + # Deduce the name of the old-style object file. + func_lo2o "$file" + staticobj=$func_lo2o_result + func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' + fi + exit $EXIT_SUCCESS + ;; + + *) + # Figure out destination file name, if it wasn't already specified. + if test -n "$destname"; then + destfile=$destdir/$destname + else + func_basename "$file" + destfile=$func_basename_result + destfile=$destdir/$destfile + fi + + # If the file is missing, and there is a .exe on the end, strip it + # because it is most likely a libtool script we actually want to + # install + stripped_ext= + case $file in + *.exe) + if test ! -f "$file"; then + func_stripname '' '.exe' "$file" + file=$func_stripname_result + stripped_ext=.exe + fi + ;; + esac + + # Do a test to see if this is really a libtool program. + case $host in + *cygwin* | *mingw*) + if func_ltwrapper_executable_p "$file"; then + func_ltwrapper_scriptname "$file" + wrapper=$func_ltwrapper_scriptname_result + else + func_stripname '' '.exe' "$file" + wrapper=$func_stripname_result + fi + ;; + *) + wrapper=$file + ;; + esac + if func_ltwrapper_script_p "$wrapper"; then + notinst_deplibs= + relink_command= + + func_source "$wrapper" + + # Check the variables that should have been set. + test -z "$generated_by_libtool_version" && \ + func_fatal_error "invalid libtool wrapper script '$wrapper'" + + finalize=: + for lib in $notinst_deplibs; do + # Check to see that each library is installed. + libdir= + if test -f "$lib"; then + func_source "$lib" + fi + libfile=$libdir/`$ECHO "$lib" | $SED 's%^.*/%%g'` + if test -n "$libdir" && test ! -f "$libfile"; then + func_warning "'$lib' has not been installed in '$libdir'" + finalize=false + fi + done + + relink_command= + func_source "$wrapper" + + outputname= + if test no = "$fast_install" && test -n "$relink_command"; then + $opt_dry_run || { + if $finalize; then + tmpdir=`func_mktempdir` + func_basename "$file$stripped_ext" + file=$func_basename_result + outputname=$tmpdir/$file + # Replace the output file specification. + relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'` + + $opt_quiet || { + func_quote_arg expand,pretty "$relink_command" + eval "func_echo $func_quote_arg_result" + } + if eval "$relink_command"; then : + else + func_error "error: relink '$file' with the above command before installing it" + $opt_dry_run || ${RM}r "$tmpdir" + continue + fi + file=$outputname + else + func_warning "cannot relink '$file'" + fi + } + else + # Install the binary that we compiled earlier. + file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"` + fi + fi + + # remove .exe since cygwin /usr/bin/install will append another + # one anyway + case $install_prog,$host in + */usr/bin/install*,*cygwin*) + case $file:$destfile in + *.exe:*.exe) + # this is ok + ;; + *.exe:*) + destfile=$destfile.exe + ;; + *:*.exe) + func_stripname '' '.exe' "$destfile" + destfile=$func_stripname_result + ;; + esac + ;; + esac + func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' + $opt_dry_run || if test -n "$outputname"; then + ${RM}r "$tmpdir" + fi + ;; + esac + done + + for file in $staticlibs; do + func_basename "$file" + name=$func_basename_result + + # Set up the ranlib parameters. + oldlib=$destdir/$name + func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 + tool_oldlib=$func_to_tool_file_result + + func_show_eval "$install_prog \$file \$oldlib" 'exit $?' + + if test -n "$stripme" && test -n "$old_striplib"; then + func_show_eval "$old_striplib $tool_oldlib" 'exit $?' + fi + + # Do each command in the postinstall commands. + func_execute_cmds "$old_postinstall_cmds" 'exit $?' + done + + test -n "$future_libdirs" && \ + func_warning "remember to run '$progname --finish$future_libdirs'" + + if test -n "$current_libdirs"; then + # Maybe just do a dry run. + $opt_dry_run && current_libdirs=" -n$current_libdirs" + exec_cmd='$SHELL "$progpath" $preserve_args --finish$current_libdirs' + else + exit $EXIT_SUCCESS + fi +} + +test install = "$opt_mode" && func_mode_install ${1+"$@"} + + +# func_generate_dlsyms outputname originator pic_p +# Extract symbols from dlprefiles and create ${outputname}S.o with +# a dlpreopen symbol table. +func_generate_dlsyms () +{ + $debug_cmd + + my_outputname=$1 + my_originator=$2 + my_pic_p=${3-false} + my_prefix=`$ECHO "$my_originator" | $SED 's%[^a-zA-Z0-9]%_%g'` + my_dlsyms= + + if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then + if test -n "$NM" && test -n "$global_symbol_pipe"; then + my_dlsyms=${my_outputname}S.c + else + func_error "not configured to extract global symbols from dlpreopened files" + fi + fi + + if test -n "$my_dlsyms"; then + case $my_dlsyms in + "") ;; + *.c) + # Discover the nlist of each of the dlfiles. + nlist=$output_objdir/$my_outputname.nm + + func_show_eval "$RM $nlist ${nlist}S ${nlist}T" + + # Parse the name list into a source file. + func_verbose "creating $output_objdir/$my_dlsyms" + + $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ +/* $my_dlsyms - symbol resolution table for '$my_outputname' dlsym emulation. */ +/* Generated by $PROGRAM (GNU $PACKAGE) $VERSION */ + +#ifdef __cplusplus +extern \"C\" { +#endif + +#if defined __GNUC__ && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4)) +#pragma GCC diagnostic ignored \"-Wstrict-prototypes\" +#endif + +/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ +#if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE +/* DATA imports from DLLs on WIN32 can't be const, because runtime + relocations are performed -- see ld's documentation on pseudo-relocs. */ +# define LT_DLSYM_CONST +#elif defined __osf__ +/* This system does not cope well with relocations in const data. */ +# define LT_DLSYM_CONST +#else +# define LT_DLSYM_CONST const +#endif + +#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0) + +/* External symbol declarations for the compiler. */\ +" + + if test yes = "$dlself"; then + func_verbose "generating symbol list for '$output'" + + $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" + + # Add our own program objects to the symbol list. + progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP` + for progfile in $progfiles; do + func_to_tool_file "$progfile" func_convert_file_msys_to_w32 + func_verbose "extracting global C symbols from '$func_to_tool_file_result'" + $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'" + done + + if test -n "$exclude_expsyms"; then + $opt_dry_run || { + eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' + eval '$MV "$nlist"T "$nlist"' + } + fi + + if test -n "$export_symbols_regex"; then + $opt_dry_run || { + eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' + eval '$MV "$nlist"T "$nlist"' + } + fi + + # Prepare the list of exported symbols + if test -z "$export_symbols"; then + export_symbols=$output_objdir/$outputname.exp + $opt_dry_run || { + $RM $export_symbols + eval "$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' + case $host in + *cygwin* | *mingw* | *cegcc* ) + eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' + eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' + ;; + esac + } + else + $opt_dry_run || { + eval "$SED -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' + eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' + eval '$MV "$nlist"T "$nlist"' + case $host in + *cygwin* | *mingw* | *cegcc* ) + eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' + eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' + ;; + esac + } + fi + fi + + for dlprefile in $dlprefiles; do + func_verbose "extracting global C symbols from '$dlprefile'" + func_basename "$dlprefile" + name=$func_basename_result + case $host in + *cygwin* | *mingw* | *cegcc* ) + # if an import library, we need to obtain dlname + if func_win32_import_lib_p "$dlprefile"; then + func_tr_sh "$dlprefile" + eval "curr_lafile=\$libfile_$func_tr_sh_result" + dlprefile_dlbasename= + if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then + # Use subshell, to avoid clobbering current variable values + dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"` + if test -n "$dlprefile_dlname"; then + func_basename "$dlprefile_dlname" + dlprefile_dlbasename=$func_basename_result + else + # no lafile. user explicitly requested -dlpreopen . + $sharedlib_from_linklib_cmd "$dlprefile" + dlprefile_dlbasename=$sharedlib_from_linklib_result + fi + fi + $opt_dry_run || { + if test -n "$dlprefile_dlbasename"; then + eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"' + else + func_warning "Could not compute DLL name from $name" + eval '$ECHO ": $name " >> "$nlist"' + fi + func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 + eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | + $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" + } + else # not an import lib + $opt_dry_run || { + eval '$ECHO ": $name " >> "$nlist"' + func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 + eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" + } + fi + ;; + *) + $opt_dry_run || { + eval '$ECHO ": $name " >> "$nlist"' + func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 + eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" + } + ;; + esac + done + + $opt_dry_run || { + # Make sure we have at least an empty file. + test -f "$nlist" || : > "$nlist" + + if test -n "$exclude_expsyms"; then + $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T + $MV "$nlist"T "$nlist" + fi + + # Try sorting and uniquifying the output. + if $GREP -v "^: " < "$nlist" | + if sort -k 3 /dev/null 2>&1; then + sort -k 3 + else + sort +2 + fi | + uniq > "$nlist"S; then + : + else + $GREP -v "^: " < "$nlist" > "$nlist"S + fi + + if test -f "$nlist"S; then + eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' + else + echo '/* NONE */' >> "$output_objdir/$my_dlsyms" + fi + + func_show_eval '$RM "${nlist}I"' + if test -n "$global_symbol_to_import"; then + eval "$global_symbol_to_import"' < "$nlist"S > "$nlist"I' + fi + + echo >> "$output_objdir/$my_dlsyms" "\ + +/* The mapping between symbol names and symbols. */ +typedef struct { + const char *name; + void *address; +} lt_dlsymlist; +extern LT_DLSYM_CONST lt_dlsymlist +lt_${my_prefix}_LTX_preloaded_symbols[];\ +" + + if test -s "$nlist"I; then + echo >> "$output_objdir/$my_dlsyms" "\ +static void lt_syminit(void) +{ + LT_DLSYM_CONST lt_dlsymlist *symbol = lt_${my_prefix}_LTX_preloaded_symbols; + for (; symbol->name; ++symbol) + {" + $SED 's/.*/ if (STREQ (symbol->name, \"&\")) symbol->address = (void *) \&&;/' < "$nlist"I >> "$output_objdir/$my_dlsyms" + echo >> "$output_objdir/$my_dlsyms" "\ + } +}" + fi + echo >> "$output_objdir/$my_dlsyms" "\ +LT_DLSYM_CONST lt_dlsymlist +lt_${my_prefix}_LTX_preloaded_symbols[] = +{ {\"$my_originator\", (void *) 0}," + + if test -s "$nlist"I; then + echo >> "$output_objdir/$my_dlsyms" "\ + {\"@INIT@\", (void *) <_syminit}," + fi + + case $need_lib_prefix in + no) + eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" + ;; + *) + eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" + ;; + esac + echo >> "$output_objdir/$my_dlsyms" "\ + {0, (void *) 0} +}; + +/* This works around a problem in FreeBSD linker */ +#ifdef FREEBSD_WORKAROUND +static const void *lt_preloaded_setup() { + return lt_${my_prefix}_LTX_preloaded_symbols; +} +#endif + +#ifdef __cplusplus +} +#endif\ +" + } # !$opt_dry_run + + pic_flag_for_symtable= + case "$compile_command " in + *" -static "*) ;; + *) + case $host in + # compiling the symbol table file with pic_flag works around + # a FreeBSD bug that causes programs to crash when -lm is + # linked before any other PIC object. But we must not use + # pic_flag when linking with -static. The problem exists in + # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. + *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) + pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; + *-*-hpux*) + pic_flag_for_symtable=" $pic_flag" ;; + *) + $my_pic_p && pic_flag_for_symtable=" $pic_flag" + ;; + esac + ;; + esac + symtab_cflags= + for arg in $LTCFLAGS; do + case $arg in + -pie | -fpie | -fPIE) ;; + *) func_append symtab_cflags " $arg" ;; + esac + done + + # Now compile the dynamic symbol file. + func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' + + # Clean up the generated files. + func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T" "${nlist}I"' + + # Transform the symbol file into the correct name. + symfileobj=$output_objdir/${my_outputname}S.$objext + case $host in + *cygwin* | *mingw* | *cegcc* ) + if test -f "$output_objdir/$my_outputname.def"; then + compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` + finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` + else + compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` + finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` + fi + ;; + *) + compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` + finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` + ;; + esac + ;; + *) + func_fatal_error "unknown suffix for '$my_dlsyms'" + ;; + esac + else + # We keep going just in case the user didn't refer to + # lt_preloaded_symbols. The linker will fail if global_symbol_pipe + # really was required. + + # Nullify the symbol file. + compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"` + finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"` + fi +} + +# func_cygming_gnu_implib_p ARG +# This predicate returns with zero status (TRUE) if +# ARG is a GNU/binutils-style import library. Returns +# with nonzero status (FALSE) otherwise. +func_cygming_gnu_implib_p () +{ + $debug_cmd + + func_to_tool_file "$1" func_convert_file_msys_to_w32 + func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'` + test -n "$func_cygming_gnu_implib_tmp" +} + +# func_cygming_ms_implib_p ARG +# This predicate returns with zero status (TRUE) if +# ARG is an MS-style import library. Returns +# with nonzero status (FALSE) otherwise. +func_cygming_ms_implib_p () +{ + $debug_cmd + + func_to_tool_file "$1" func_convert_file_msys_to_w32 + func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'` + test -n "$func_cygming_ms_implib_tmp" +} + +# func_win32_libid arg +# return the library type of file 'arg' +# +# Need a lot of goo to handle *both* DLLs and import libs +# Has to be a shell function in order to 'eat' the argument +# that is supplied when $file_magic_command is called. +# Despite the name, also deal with 64 bit binaries. +func_win32_libid () +{ + $debug_cmd + + win32_libid_type=unknown + win32_fileres=`file -L $1 2>/dev/null` + case $win32_fileres in + *ar\ archive\ import\ library*) # definitely import + win32_libid_type="x86 archive import" + ;; + *ar\ archive*) # could be an import, or static + # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD. + if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | + $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then + case $nm_interface in + "MS dumpbin") + if func_cygming_ms_implib_p "$1" || + func_cygming_gnu_implib_p "$1" + then + win32_nmres=import + else + win32_nmres= + fi + ;; + *) + func_to_tool_file "$1" func_convert_file_msys_to_w32 + win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" | + $SED -n -e ' + 1,100{ + / I /{ + s|.*|import| + p + q + } + }'` + ;; + esac + case $win32_nmres in + import*) win32_libid_type="x86 archive import";; + *) win32_libid_type="x86 archive static";; + esac + fi + ;; + *DLL*) + win32_libid_type="x86 DLL" + ;; + *executable*) # but shell scripts are "executable" too... + case $win32_fileres in + *MS\ Windows\ PE\ Intel*) + win32_libid_type="x86 DLL" + ;; + esac + ;; + esac + $ECHO "$win32_libid_type" +} + +# func_cygming_dll_for_implib ARG +# +# Platform-specific function to extract the +# name of the DLL associated with the specified +# import library ARG. +# Invoked by eval'ing the libtool variable +# $sharedlib_from_linklib_cmd +# Result is available in the variable +# $sharedlib_from_linklib_result +func_cygming_dll_for_implib () +{ + $debug_cmd + + sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"` +} + +# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs +# +# The is the core of a fallback implementation of a +# platform-specific function to extract the name of the +# DLL associated with the specified import library LIBNAME. +# +# SECTION_NAME is either .idata$6 or .idata$7, depending +# on the platform and compiler that created the implib. +# +# Echos the name of the DLL associated with the +# specified import library. +func_cygming_dll_for_implib_fallback_core () +{ + $debug_cmd + + match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"` + $OBJDUMP -s --section "$1" "$2" 2>/dev/null | + $SED '/^Contents of section '"$match_literal"':/{ + # Place marker at beginning of archive member dllname section + s/.*/====MARK====/ + p + d + } + # These lines can sometimes be longer than 43 characters, but + # are always uninteresting + /:[ ]*file format pe[i]\{,1\}-/d + /^In archive [^:]*:/d + # Ensure marker is printed + /^====MARK====/p + # Remove all lines with less than 43 characters + /^.\{43\}/!d + # From remaining lines, remove first 43 characters + s/^.\{43\}//' | + $SED -n ' + # Join marker and all lines until next marker into a single line + /^====MARK====/ b para + H + $ b para + b + :para + x + s/\n//g + # Remove the marker + s/^====MARK====// + # Remove trailing dots and whitespace + s/[\. \t]*$// + # Print + /./p' | + # we now have a list, one entry per line, of the stringified + # contents of the appropriate section of all members of the + # archive that possess that section. Heuristic: eliminate + # all those that have a first or second character that is + # a '.' (that is, objdump's representation of an unprintable + # character.) This should work for all archives with less than + # 0x302f exports -- but will fail for DLLs whose name actually + # begins with a literal '.' or a single character followed by + # a '.'. + # + # Of those that remain, print the first one. + $SED -e '/^\./d;/^.\./d;q' +} + +# func_cygming_dll_for_implib_fallback ARG +# Platform-specific function to extract the +# name of the DLL associated with the specified +# import library ARG. +# +# This fallback implementation is for use when $DLLTOOL +# does not support the --identify-strict option. +# Invoked by eval'ing the libtool variable +# $sharedlib_from_linklib_cmd +# Result is available in the variable +# $sharedlib_from_linklib_result +func_cygming_dll_for_implib_fallback () +{ + $debug_cmd + + if func_cygming_gnu_implib_p "$1"; then + # binutils import library + sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"` + elif func_cygming_ms_implib_p "$1"; then + # ms-generated import library + sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"` + else + # unknown + sharedlib_from_linklib_result= + fi +} + + +# func_extract_an_archive dir oldlib +func_extract_an_archive () +{ + $debug_cmd + + f_ex_an_ar_dir=$1; shift + f_ex_an_ar_oldlib=$1 + if test yes = "$lock_old_archive_extraction"; then + lockfile=$f_ex_an_ar_oldlib.lock + until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do + func_echo "Waiting for $lockfile to be removed" + sleep 2 + done + fi + func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \ + 'stat=$?; rm -f "$lockfile"; exit $stat' + if test yes = "$lock_old_archive_extraction"; then + $opt_dry_run || rm -f "$lockfile" + fi + if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then + : + else + func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" + fi +} + + +# func_extract_archives gentop oldlib ... +func_extract_archives () +{ + $debug_cmd + + my_gentop=$1; shift + my_oldlibs=${1+"$@"} + my_oldobjs= + my_xlib= + my_xabs= + my_xdir= + + for my_xlib in $my_oldlibs; do + # Extract the objects. + case $my_xlib in + [\\/]* | [A-Za-z]:[\\/]*) my_xabs=$my_xlib ;; + *) my_xabs=`pwd`"/$my_xlib" ;; + esac + func_basename "$my_xlib" + my_xlib=$func_basename_result + my_xlib_u=$my_xlib + while :; do + case " $extracted_archives " in + *" $my_xlib_u "*) + func_arith $extracted_serial + 1 + extracted_serial=$func_arith_result + my_xlib_u=lt$extracted_serial-$my_xlib ;; + *) break ;; + esac + done + extracted_archives="$extracted_archives $my_xlib_u" + my_xdir=$my_gentop/$my_xlib_u + + func_mkdir_p "$my_xdir" + + case $host in + *-darwin*) + func_verbose "Extracting $my_xabs" + # Do not bother doing anything if just a dry run + $opt_dry_run || { + darwin_orig_dir=`pwd` + cd $my_xdir || exit $? + darwin_archive=$my_xabs + darwin_curdir=`pwd` + func_basename "$darwin_archive" + darwin_base_archive=$func_basename_result + darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` + if test -n "$darwin_arches"; then + darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` + darwin_arch= + func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" + for darwin_arch in $darwin_arches; do + func_mkdir_p "unfat-$$/$darwin_base_archive-$darwin_arch" + $LIPO -thin $darwin_arch -output "unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive" "$darwin_archive" + cd "unfat-$$/$darwin_base_archive-$darwin_arch" + func_extract_an_archive "`pwd`" "$darwin_base_archive" + cd "$darwin_curdir" + $RM "unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive" + done # $darwin_arches + ## Okay now we've a bunch of thin objects, gotta fatten them up :) + darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$sed_basename" | sort -u` + darwin_file= + darwin_files= + for darwin_file in $darwin_filelist; do + darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP` + $LIPO -create -output "$darwin_file" $darwin_files + done # $darwin_filelist + $RM -rf unfat-$$ + cd "$darwin_orig_dir" + else + cd $darwin_orig_dir + func_extract_an_archive "$my_xdir" "$my_xabs" + fi # $darwin_arches + } # !$opt_dry_run + ;; + *) + func_extract_an_archive "$my_xdir" "$my_xabs" + ;; + esac + my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP` + done + + func_extract_archives_result=$my_oldobjs +} + + +# func_emit_wrapper [arg=no] +# +# Emit a libtool wrapper script on stdout. +# Don't directly open a file because we may want to +# incorporate the script contents within a cygwin/mingw +# wrapper executable. Must ONLY be called from within +# func_mode_link because it depends on a number of variables +# set therein. +# +# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR +# variable will take. If 'yes', then the emitted script +# will assume that the directory where it is stored is +# the $objdir directory. This is a cygwin/mingw-specific +# behavior. +func_emit_wrapper () +{ + func_emit_wrapper_arg1=${1-no} + + $ECHO "\ +#! $SHELL + +# $output - temporary wrapper script for $objdir/$outputname +# Generated by $PROGRAM (GNU $PACKAGE) $VERSION +# +# The $output program cannot be directly executed until all the libtool +# libraries that it depends on are installed. +# +# This wrapper script should never be moved out of the build directory. +# If it is, it will not operate correctly. + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +sed_quote_subst='$sed_quote_subst' + +# Be Bourne compatible +if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST +else + case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac +fi +BIN_SH=xpg4; export BIN_SH # for Tru64 +DUALCASE=1; export DUALCASE # for MKS sh + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +relink_command=\"$relink_command\" + +# This environment variable determines our operation mode. +if test \"\$libtool_install_magic\" = \"$magic\"; then + # install mode needs the following variables: + generated_by_libtool_version='$macro_version' + notinst_deplibs='$notinst_deplibs' +else + # When we are sourced in execute mode, \$file and \$ECHO are already set. + if test \"\$libtool_execute_magic\" != \"$magic\"; then + file=\"\$0\"" + + func_quote_arg pretty "$ECHO" + qECHO=$func_quote_arg_result + $ECHO "\ + +# A function that is used when there is no print builtin or printf. +func_fallback_echo () +{ + eval 'cat <<_LTECHO_EOF +\$1 +_LTECHO_EOF' +} + ECHO=$qECHO + fi + +# Very basic option parsing. These options are (a) specific to +# the libtool wrapper, (b) are identical between the wrapper +# /script/ and the wrapper /executable/ that is used only on +# windows platforms, and (c) all begin with the string "--lt-" +# (application programs are unlikely to have options that match +# this pattern). +# +# There are only two supported options: --lt-debug and +# --lt-dump-script. There is, deliberately, no --lt-help. +# +# The first argument to this parsing function should be the +# script's $0 value, followed by "$@". +lt_option_debug= +func_parse_lt_options () +{ + lt_script_arg0=\$0 + shift + for lt_opt + do + case \"\$lt_opt\" in + --lt-debug) lt_option_debug=1 ;; + --lt-dump-script) + lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\` + test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=. + lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\` + cat \"\$lt_dump_D/\$lt_dump_F\" + exit 0 + ;; + --lt-*) + \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2 + exit 1 + ;; + esac + done + + # Print the debug banner immediately: + if test -n \"\$lt_option_debug\"; then + echo \"$outputname:$output:\$LINENO: libtool wrapper (GNU $PACKAGE) $VERSION\" 1>&2 + fi +} + +# Used when --lt-debug. Prints its arguments to stdout +# (redirection is the responsibility of the caller) +func_lt_dump_args () +{ + lt_dump_args_N=1; + for lt_arg + do + \$ECHO \"$outputname:$output:\$LINENO: newargv[\$lt_dump_args_N]: \$lt_arg\" + lt_dump_args_N=\`expr \$lt_dump_args_N + 1\` + done +} + +# Core function for launching the target application +func_exec_program_core () +{ +" + case $host in + # Backslashes separate directories on plain windows + *-*-mingw | *-*-os2* | *-cegcc*) + $ECHO "\ + if test -n \"\$lt_option_debug\"; then + \$ECHO \"$outputname:$output:\$LINENO: newargv[0]: \$progdir\\\\\$program\" 1>&2 + func_lt_dump_args \${1+\"\$@\"} 1>&2 + fi + exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} +" + ;; + + *) + $ECHO "\ + if test -n \"\$lt_option_debug\"; then + \$ECHO \"$outputname:$output:\$LINENO: newargv[0]: \$progdir/\$program\" 1>&2 + func_lt_dump_args \${1+\"\$@\"} 1>&2 + fi + exec \"\$progdir/\$program\" \${1+\"\$@\"} +" + ;; + esac + $ECHO "\ + \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 + exit 1 +} + +# A function to encapsulate launching the target application +# Strips options in the --lt-* namespace from \$@ and +# launches target application with the remaining arguments. +func_exec_program () +{ + case \" \$* \" in + *\\ --lt-*) + for lt_wr_arg + do + case \$lt_wr_arg in + --lt-*) ;; + *) set x \"\$@\" \"\$lt_wr_arg\"; shift;; + esac + shift + done ;; + esac + func_exec_program_core \${1+\"\$@\"} +} + + # Parse options + func_parse_lt_options \"\$0\" \${1+\"\$@\"} + + # Find the directory that this script lives in. + thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\` + test \"x\$thisdir\" = \"x\$file\" && thisdir=. + + # Follow symbolic links until we get to the real thisdir. + file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\` + while test -n \"\$file\"; do + destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\` + + # If there was a directory component, then change thisdir. + if test \"x\$destdir\" != \"x\$file\"; then + case \"\$destdir\" in + [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; + *) thisdir=\"\$thisdir/\$destdir\" ;; + esac + fi + + file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\` + file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\` + done + + # Usually 'no', except on cygwin/mingw when embedded into + # the cwrapper. + WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1 + if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then + # special case for '.' + if test \"\$thisdir\" = \".\"; then + thisdir=\`pwd\` + fi + # remove .libs from thisdir + case \"\$thisdir\" in + *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;; + $objdir ) thisdir=. ;; + esac + fi + + # Try to get the absolute directory name. + absdir=\`cd \"\$thisdir\" && pwd\` + test -n \"\$absdir\" && thisdir=\"\$absdir\" +" + + if test yes = "$fast_install"; then + $ECHO "\ + program=lt-'$outputname'$exeext + progdir=\"\$thisdir/$objdir\" + + if test ! -f \"\$progdir/\$program\" || + { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | $SED 1q\`; \\ + test \"X\$file\" != \"X\$progdir/\$program\"; }; then + + file=\"\$\$-\$program\" + + if test ! -d \"\$progdir\"; then + $MKDIR \"\$progdir\" + else + $RM \"\$progdir/\$file\" + fi" + + $ECHO "\ + + # relink executable if necessary + if test -n \"\$relink_command\"; then + if relink_command_output=\`eval \$relink_command 2>&1\`; then : + else + \$ECHO \"\$relink_command_output\" >&2 + $RM \"\$progdir/\$file\" + exit 1 + fi + fi + + $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || + { $RM \"\$progdir/\$program\"; + $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } + $RM \"\$progdir/\$file\" + fi" + else + $ECHO "\ + program='$outputname' + progdir=\"\$thisdir/$objdir\" +" + fi + + $ECHO "\ + + if test -f \"\$progdir/\$program\"; then" + + # fixup the dll searchpath if we need to. + # + # Fix the DLL searchpath if we need to. Do this before prepending + # to shlibpath, because on Windows, both are PATH and uninstalled + # libraries must come first. + if test -n "$dllsearchpath"; then + $ECHO "\ + # Add the dll search path components to the executable PATH + PATH=$dllsearchpath:\$PATH +" + fi + + # Export our shlibpath_var if we have one. + if test yes = "$shlibpath_overrides_runpath" && test -n "$shlibpath_var" && test -n "$temp_rpath"; then + $ECHO "\ + # Add our own library path to $shlibpath_var + $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" + + # Some systems cannot cope with colon-terminated $shlibpath_var + # The second colon is a workaround for a bug in BeOS R4 sed + $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\` + + export $shlibpath_var +" + fi + + $ECHO "\ + if test \"\$libtool_execute_magic\" != \"$magic\"; then + # Run the actual program with our arguments. + func_exec_program \${1+\"\$@\"} + fi + else + # The program doesn't exist. + \$ECHO \"\$0: error: '\$progdir/\$program' does not exist\" 1>&2 + \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 + \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 + exit 1 + fi +fi\ +" +} + + +# func_emit_cwrapperexe_src +# emit the source code for a wrapper executable on stdout +# Must ONLY be called from within func_mode_link because +# it depends on a number of variable set therein. +func_emit_cwrapperexe_src () +{ + cat < +#include +#ifdef _MSC_VER +# include +# include +# include +#else +# include +# include +# ifdef __CYGWIN__ +# include +# endif +#endif +#include +#include +#include +#include +#include +#include +#include +#include + +#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0) + +/* declarations of non-ANSI functions */ +#if defined __MINGW32__ +# ifdef __STRICT_ANSI__ +int _putenv (const char *); +# endif +#elif defined __CYGWIN__ +# ifdef __STRICT_ANSI__ +char *realpath (const char *, char *); +int putenv (char *); +int setenv (const char *, const char *, int); +# endif +/* #elif defined other_platform || defined ... */ +#endif + +/* portability defines, excluding path handling macros */ +#if defined _MSC_VER +# define setmode _setmode +# define stat _stat +# define chmod _chmod +# define getcwd _getcwd +# define putenv _putenv +# define S_IXUSR _S_IEXEC +#elif defined __MINGW32__ +# define setmode _setmode +# define stat _stat +# define chmod _chmod +# define getcwd _getcwd +# define putenv _putenv +#elif defined __CYGWIN__ +# define HAVE_SETENV +# define FOPEN_WB "wb" +/* #elif defined other platforms ... */ +#endif + +#if defined PATH_MAX +# define LT_PATHMAX PATH_MAX +#elif defined MAXPATHLEN +# define LT_PATHMAX MAXPATHLEN +#else +# define LT_PATHMAX 1024 +#endif + +#ifndef S_IXOTH +# define S_IXOTH 0 +#endif +#ifndef S_IXGRP +# define S_IXGRP 0 +#endif + +/* path handling portability macros */ +#ifndef DIR_SEPARATOR +# define DIR_SEPARATOR '/' +# define PATH_SEPARATOR ':' +#endif + +#if defined _WIN32 || defined __MSDOS__ || defined __DJGPP__ || \ + defined __OS2__ +# define HAVE_DOS_BASED_FILE_SYSTEM +# define FOPEN_WB "wb" +# ifndef DIR_SEPARATOR_2 +# define DIR_SEPARATOR_2 '\\' +# endif +# ifndef PATH_SEPARATOR_2 +# define PATH_SEPARATOR_2 ';' +# endif +#endif + +#ifndef DIR_SEPARATOR_2 +# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) +#else /* DIR_SEPARATOR_2 */ +# define IS_DIR_SEPARATOR(ch) \ + (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) +#endif /* DIR_SEPARATOR_2 */ + +#ifndef PATH_SEPARATOR_2 +# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) +#else /* PATH_SEPARATOR_2 */ +# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) +#endif /* PATH_SEPARATOR_2 */ + +#ifndef FOPEN_WB +# define FOPEN_WB "w" +#endif +#ifndef _O_BINARY +# define _O_BINARY 0 +#endif + +#define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) +#define XFREE(stale) do { \ + if (stale) { free (stale); stale = 0; } \ +} while (0) + +#if defined LT_DEBUGWRAPPER +static int lt_debug = 1; +#else +static int lt_debug = 0; +#endif + +const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */ + +void *xmalloc (size_t num); +char *xstrdup (const char *string); +const char *base_name (const char *name); +char *find_executable (const char *wrapper); +char *chase_symlinks (const char *pathspec); +int make_executable (const char *path); +int check_executable (const char *path); +char *strendzap (char *str, const char *pat); +void lt_debugprintf (const char *file, int line, const char *fmt, ...); +void lt_fatal (const char *file, int line, const char *message, ...); +static const char *nonnull (const char *s); +static const char *nonempty (const char *s); +void lt_setenv (const char *name, const char *value); +char *lt_extend_str (const char *orig_value, const char *add, int to_end); +void lt_update_exe_path (const char *name, const char *value); +void lt_update_lib_path (const char *name, const char *value); +char **prepare_spawn (char **argv); +void lt_dump_script (FILE *f); +EOF + + cat <= 0) + && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) + return 1; + else + return 0; +} + +int +make_executable (const char *path) +{ + int rval = 0; + struct stat st; + + lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n", + nonempty (path)); + if ((!path) || (!*path)) + return 0; + + if (stat (path, &st) >= 0) + { + rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); + } + return rval; +} + +/* Searches for the full path of the wrapper. Returns + newly allocated full path name if found, NULL otherwise + Does not chase symlinks, even on platforms that support them. +*/ +char * +find_executable (const char *wrapper) +{ + int has_slash = 0; + const char *p; + const char *p_next; + /* static buffer for getcwd */ + char tmp[LT_PATHMAX + 1]; + size_t tmp_len; + char *concat_name; + + lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n", + nonempty (wrapper)); + + if ((wrapper == NULL) || (*wrapper == '\0')) + return NULL; + + /* Absolute path? */ +#if defined HAVE_DOS_BASED_FILE_SYSTEM + if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') + { + concat_name = xstrdup (wrapper); + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + } + else + { +#endif + if (IS_DIR_SEPARATOR (wrapper[0])) + { + concat_name = xstrdup (wrapper); + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + } +#if defined HAVE_DOS_BASED_FILE_SYSTEM + } +#endif + + for (p = wrapper; *p; p++) + if (*p == '/') + { + has_slash = 1; + break; + } + if (!has_slash) + { + /* no slashes; search PATH */ + const char *path = getenv ("PATH"); + if (path != NULL) + { + for (p = path; *p; p = p_next) + { + const char *q; + size_t p_len; + for (q = p; *q; q++) + if (IS_PATH_SEPARATOR (*q)) + break; + p_len = (size_t) (q - p); + p_next = (*q == '\0' ? q : q + 1); + if (p_len == 0) + { + /* empty path: current directory */ + if (getcwd (tmp, LT_PATHMAX) == NULL) + lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", + nonnull (strerror (errno))); + tmp_len = strlen (tmp); + concat_name = + XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); + memcpy (concat_name, tmp, tmp_len); + concat_name[tmp_len] = '/'; + strcpy (concat_name + tmp_len + 1, wrapper); + } + else + { + concat_name = + XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); + memcpy (concat_name, p, p_len); + concat_name[p_len] = '/'; + strcpy (concat_name + p_len + 1, wrapper); + } + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + } + } + /* not found in PATH; assume curdir */ + } + /* Relative path | not found in path: prepend cwd */ + if (getcwd (tmp, LT_PATHMAX) == NULL) + lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", + nonnull (strerror (errno))); + tmp_len = strlen (tmp); + concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); + memcpy (concat_name, tmp, tmp_len); + concat_name[tmp_len] = '/'; + strcpy (concat_name + tmp_len + 1, wrapper); + + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + return NULL; +} + +char * +chase_symlinks (const char *pathspec) +{ +#ifndef S_ISLNK + return xstrdup (pathspec); +#else + char buf[LT_PATHMAX]; + struct stat s; + char *tmp_pathspec = xstrdup (pathspec); + char *p; + int has_symlinks = 0; + while (strlen (tmp_pathspec) && !has_symlinks) + { + lt_debugprintf (__FILE__, __LINE__, + "checking path component for symlinks: %s\n", + tmp_pathspec); + if (lstat (tmp_pathspec, &s) == 0) + { + if (S_ISLNK (s.st_mode) != 0) + { + has_symlinks = 1; + break; + } + + /* search backwards for last DIR_SEPARATOR */ + p = tmp_pathspec + strlen (tmp_pathspec) - 1; + while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) + p--; + if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) + { + /* no more DIR_SEPARATORS left */ + break; + } + *p = '\0'; + } + else + { + lt_fatal (__FILE__, __LINE__, + "error accessing file \"%s\": %s", + tmp_pathspec, nonnull (strerror (errno))); + } + } + XFREE (tmp_pathspec); + + if (!has_symlinks) + { + return xstrdup (pathspec); + } + + tmp_pathspec = realpath (pathspec, buf); + if (tmp_pathspec == 0) + { + lt_fatal (__FILE__, __LINE__, + "could not follow symlinks for %s", pathspec); + } + return xstrdup (tmp_pathspec); +#endif +} + +char * +strendzap (char *str, const char *pat) +{ + size_t len, patlen; + + assert (str != NULL); + assert (pat != NULL); + + len = strlen (str); + patlen = strlen (pat); + + if (patlen <= len) + { + str += len - patlen; + if (STREQ (str, pat)) + *str = '\0'; + } + return str; +} + +void +lt_debugprintf (const char *file, int line, const char *fmt, ...) +{ + va_list args; + if (lt_debug) + { + (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line); + va_start (args, fmt); + (void) vfprintf (stderr, fmt, args); + va_end (args); + } +} + +static void +lt_error_core (int exit_status, const char *file, + int line, const char *mode, + const char *message, va_list ap) +{ + fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode); + vfprintf (stderr, message, ap); + fprintf (stderr, ".\n"); + + if (exit_status >= 0) + exit (exit_status); +} + +void +lt_fatal (const char *file, int line, const char *message, ...) +{ + va_list ap; + va_start (ap, message); + lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap); + va_end (ap); +} + +static const char * +nonnull (const char *s) +{ + return s ? s : "(null)"; +} + +static const char * +nonempty (const char *s) +{ + return (s && !*s) ? "(empty)" : nonnull (s); +} + +void +lt_setenv (const char *name, const char *value) +{ + lt_debugprintf (__FILE__, __LINE__, + "(lt_setenv) setting '%s' to '%s'\n", + nonnull (name), nonnull (value)); + { +#ifdef HAVE_SETENV + /* always make a copy, for consistency with !HAVE_SETENV */ + char *str = xstrdup (value); + setenv (name, str, 1); +#else + size_t len = strlen (name) + 1 + strlen (value) + 1; + char *str = XMALLOC (char, len); + sprintf (str, "%s=%s", name, value); + if (putenv (str) != EXIT_SUCCESS) + { + XFREE (str); + } +#endif + } +} + +char * +lt_extend_str (const char *orig_value, const char *add, int to_end) +{ + char *new_value; + if (orig_value && *orig_value) + { + size_t orig_value_len = strlen (orig_value); + size_t add_len = strlen (add); + new_value = XMALLOC (char, add_len + orig_value_len + 1); + if (to_end) + { + strcpy (new_value, orig_value); + strcpy (new_value + orig_value_len, add); + } + else + { + strcpy (new_value, add); + strcpy (new_value + add_len, orig_value); + } + } + else + { + new_value = xstrdup (add); + } + return new_value; +} + +void +lt_update_exe_path (const char *name, const char *value) +{ + lt_debugprintf (__FILE__, __LINE__, + "(lt_update_exe_path) modifying '%s' by prepending '%s'\n", + nonnull (name), nonnull (value)); + + if (name && *name && value && *value) + { + char *new_value = lt_extend_str (getenv (name), value, 0); + /* some systems can't cope with a ':'-terminated path #' */ + size_t len = strlen (new_value); + while ((len > 0) && IS_PATH_SEPARATOR (new_value[len-1])) + { + new_value[--len] = '\0'; + } + lt_setenv (name, new_value); + XFREE (new_value); + } +} + +void +lt_update_lib_path (const char *name, const char *value) +{ + lt_debugprintf (__FILE__, __LINE__, + "(lt_update_lib_path) modifying '%s' by prepending '%s'\n", + nonnull (name), nonnull (value)); + + if (name && *name && value && *value) + { + char *new_value = lt_extend_str (getenv (name), value, 0); + lt_setenv (name, new_value); + XFREE (new_value); + } +} + +EOF + case $host_os in + mingw*) + cat <<"EOF" + +/* Prepares an argument vector before calling spawn(). + Note that spawn() does not by itself call the command interpreter + (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") : + ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + GetVersionEx(&v); + v.dwPlatformId == VER_PLATFORM_WIN32_NT; + }) ? "cmd.exe" : "command.com"). + Instead it simply concatenates the arguments, separated by ' ', and calls + CreateProcess(). We must quote the arguments since Win32 CreateProcess() + interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a + special way: + - Space and tab are interpreted as delimiters. They are not treated as + delimiters if they are surrounded by double quotes: "...". + - Unescaped double quotes are removed from the input. Their only effect is + that within double quotes, space and tab are treated like normal + characters. + - Backslashes not followed by double quotes are not special. + - But 2*n+1 backslashes followed by a double quote become + n backslashes followed by a double quote (n >= 0): + \" -> " + \\\" -> \" + \\\\\" -> \\" + */ +#define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" +#define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" +char ** +prepare_spawn (char **argv) +{ + size_t argc; + char **new_argv; + size_t i; + + /* Count number of arguments. */ + for (argc = 0; argv[argc] != NULL; argc++) + ; + + /* Allocate new argument vector. */ + new_argv = XMALLOC (char *, argc + 1); + + /* Put quoted arguments into the new argument vector. */ + for (i = 0; i < argc; i++) + { + const char *string = argv[i]; + + if (string[0] == '\0') + new_argv[i] = xstrdup ("\"\""); + else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL) + { + int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL); + size_t length; + unsigned int backslashes; + const char *s; + char *quoted_string; + char *p; + + length = 0; + backslashes = 0; + if (quote_around) + length++; + for (s = string; *s != '\0'; s++) + { + char c = *s; + if (c == '"') + length += backslashes + 1; + length++; + if (c == '\\') + backslashes++; + else + backslashes = 0; + } + if (quote_around) + length += backslashes + 1; + + quoted_string = XMALLOC (char, length + 1); + + p = quoted_string; + backslashes = 0; + if (quote_around) + *p++ = '"'; + for (s = string; *s != '\0'; s++) + { + char c = *s; + if (c == '"') + { + unsigned int j; + for (j = backslashes + 1; j > 0; j--) + *p++ = '\\'; + } + *p++ = c; + if (c == '\\') + backslashes++; + else + backslashes = 0; + } + if (quote_around) + { + unsigned int j; + for (j = backslashes; j > 0; j--) + *p++ = '\\'; + *p++ = '"'; + } + *p = '\0'; + + new_argv[i] = quoted_string; + } + else + new_argv[i] = (char *) string; + } + new_argv[argc] = NULL; + + return new_argv; +} +EOF + ;; + esac + + cat <<"EOF" +void lt_dump_script (FILE* f) +{ +EOF + func_emit_wrapper yes | + $SED -n -e ' +s/^\(.\{79\}\)\(..*\)/\1\ +\2/ +h +s/\([\\"]\)/\\\1/g +s/$/\\n/ +s/\([^\n]*\).*/ fputs ("\1", f);/p +g +D' + cat <<"EOF" +} +EOF +} +# end: func_emit_cwrapperexe_src + +# func_win32_import_lib_p ARG +# True if ARG is an import lib, as indicated by $file_magic_cmd +func_win32_import_lib_p () +{ + $debug_cmd + + case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in + *import*) : ;; + *) false ;; + esac +} + +# func_suncc_cstd_abi +# !!ONLY CALL THIS FOR SUN CC AFTER $compile_command IS FULLY EXPANDED!! +# Several compiler flags select an ABI that is incompatible with the +# Cstd library. Avoid specifying it if any are in CXXFLAGS. +func_suncc_cstd_abi () +{ + $debug_cmd + + case " $compile_command " in + *" -compat=g "*|*\ -std=c++[0-9][0-9]\ *|*" -library=stdcxx4 "*|*" -library=stlport4 "*) + suncc_use_cstd_abi=no + ;; + *) + suncc_use_cstd_abi=yes + ;; + esac +} + +# func_mode_link arg... +func_mode_link () +{ + $debug_cmd + + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + # It is impossible to link a dll without this setting, and + # we shouldn't force the makefile maintainer to figure out + # what system we are compiling for in order to pass an extra + # flag for every libtool invocation. + # allow_undefined=no + + # FIXME: Unfortunately, there are problems with the above when trying + # to make a dll that has undefined symbols, in which case not + # even a static library is built. For now, we need to specify + # -no-undefined on the libtool link line when we can be certain + # that all symbols are satisfied, otherwise we get a static library. + allow_undefined=yes + ;; + *) + allow_undefined=yes + ;; + esac + libtool_args=$nonopt + base_compile="$nonopt $@" + compile_command=$nonopt + finalize_command=$nonopt + + compile_rpath= + finalize_rpath= + compile_shlibpath= + finalize_shlibpath= + convenience= + old_convenience= + deplibs= + old_deplibs= + compiler_flags= + linker_flags= + dllsearchpath= + lib_search_path=`pwd` + inst_prefix_dir= + new_inherited_linker_flags= + + avoid_version=no + bindir= + dlfiles= + dlprefiles= + dlself=no + export_dynamic=no + export_symbols= + export_symbols_regex= + generated= + libobjs= + ltlibs= + module=no + no_install=no + objs= + os2dllname= + non_pic_objects= + precious_files_regex= + prefer_static_libs=no + preload=false + prev= + prevarg= + release= + rpath= + xrpath= + perm_rpath= + temp_rpath= + thread_safe=no + vinfo= + vinfo_number=no + weak_libs= + single_module=$wl-single_module + func_infer_tag $base_compile + + # We need to know -static, to get the right output filenames. + for arg + do + case $arg in + -shared) + test yes != "$build_libtool_libs" \ + && func_fatal_configuration "cannot build a shared library" + build_old_libs=no + break + ;; + -all-static | -static | -static-libtool-libs) + case $arg in + -all-static) + if test yes = "$build_libtool_libs" && test -z "$link_static_flag"; then + func_warning "complete static linking is impossible in this configuration" + fi + if test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + prefer_static_libs=yes + ;; + -static) + if test -z "$pic_flag" && test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + prefer_static_libs=built + ;; + -static-libtool-libs) + if test -z "$pic_flag" && test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + prefer_static_libs=yes + ;; + esac + build_libtool_libs=no + build_old_libs=yes + break + ;; + esac + done + + # See if our shared archives depend on static archives. + test -n "$old_archive_from_new_cmds" && build_old_libs=yes + + # Go through the arguments, transforming them on the way. + while test "$#" -gt 0; do + arg=$1 + shift + func_quote_arg pretty,unquoted "$arg" + qarg=$func_quote_arg_unquoted_result + func_append libtool_args " $func_quote_arg_result" + + # If the previous option needs an argument, assign it. + if test -n "$prev"; then + case $prev in + output) + func_append compile_command " @OUTPUT@" + func_append finalize_command " @OUTPUT@" + ;; + esac + + case $prev in + bindir) + bindir=$arg + prev= + continue + ;; + dlfiles|dlprefiles) + $preload || { + # Add the symbol object into the linking commands. + func_append compile_command " @SYMFILE@" + func_append finalize_command " @SYMFILE@" + preload=: + } + case $arg in + *.la | *.lo) ;; # We handle these cases below. + force) + if test no = "$dlself"; then + dlself=needless + export_dynamic=yes + fi + prev= + continue + ;; + self) + if test dlprefiles = "$prev"; then + dlself=yes + elif test dlfiles = "$prev" && test yes != "$dlopen_self"; then + dlself=yes + else + dlself=needless + export_dynamic=yes + fi + prev= + continue + ;; + *) + if test dlfiles = "$prev"; then + func_append dlfiles " $arg" + else + func_append dlprefiles " $arg" + fi + prev= + continue + ;; + esac + ;; + expsyms) + export_symbols=$arg + test -f "$arg" \ + || func_fatal_error "symbol file '$arg' does not exist" + prev= + continue + ;; + expsyms_regex) + export_symbols_regex=$arg + prev= + continue + ;; + framework) + case $host in + *-*-darwin*) + case "$deplibs " in + *" $qarg.ltframework "*) ;; + *) func_append deplibs " $qarg.ltframework" # this is fixed later + ;; + esac + ;; + esac + prev= + continue + ;; + inst_prefix) + inst_prefix_dir=$arg + prev= + continue + ;; + mllvm) + # Clang does not use LLVM to link, so we can simply discard any + # '-mllvm $arg' options when doing the link step. + prev= + continue + ;; + objectlist) + if test -f "$arg"; then + save_arg=$arg + moreargs= + for fil in `cat "$save_arg"` + do +# func_append moreargs " $fil" + arg=$fil + # A libtool-controlled object. + + # Check to see that this really is a libtool object. + if func_lalib_unsafe_p "$arg"; then + pic_object= + non_pic_object= + + # Read the .lo file + func_source "$arg" + + if test -z "$pic_object" || + test -z "$non_pic_object" || + test none = "$pic_object" && + test none = "$non_pic_object"; then + func_fatal_error "cannot find name of object for '$arg'" + fi + + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir=$func_dirname_result + + if test none != "$pic_object"; then + # Prepend the subdirectory the object is found in. + pic_object=$xdir$pic_object + + if test dlfiles = "$prev"; then + if test yes = "$build_libtool_libs" && test yes = "$dlopen_support"; then + func_append dlfiles " $pic_object" + prev= + continue + else + # If libtool objects are unsupported, then we need to preload. + prev=dlprefiles + fi + fi + + # CHECK ME: I think I busted this. -Ossama + if test dlprefiles = "$prev"; then + # Preload the old-style object. + func_append dlprefiles " $pic_object" + prev= + fi + + # A PIC object. + func_append libobjs " $pic_object" + arg=$pic_object + fi + + # Non-PIC object. + if test none != "$non_pic_object"; then + # Prepend the subdirectory the object is found in. + non_pic_object=$xdir$non_pic_object + + # A standard non-PIC object + func_append non_pic_objects " $non_pic_object" + if test -z "$pic_object" || test none = "$pic_object"; then + arg=$non_pic_object + fi + else + # If the PIC object exists, use it instead. + # $xdir was prepended to $pic_object above. + non_pic_object=$pic_object + func_append non_pic_objects " $non_pic_object" + fi + else + # Only an error if not doing a dry-run. + if $opt_dry_run; then + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir=$func_dirname_result + + func_lo2o "$arg" + pic_object=$xdir$objdir/$func_lo2o_result + non_pic_object=$xdir$func_lo2o_result + func_append libobjs " $pic_object" + func_append non_pic_objects " $non_pic_object" + else + func_fatal_error "'$arg' is not a valid libtool object" + fi + fi + done + else + func_fatal_error "link input file '$arg' does not exist" + fi + arg=$save_arg + prev= + continue + ;; + os2dllname) + os2dllname=$arg + prev= + continue + ;; + precious_regex) + precious_files_regex=$arg + prev= + continue + ;; + release) + release=-$arg + prev= + continue + ;; + rpath | xrpath) + # We need an absolute path. + case $arg in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + func_fatal_error "only absolute run-paths are allowed" + ;; + esac + if test rpath = "$prev"; then + case "$rpath " in + *" $arg "*) ;; + *) func_append rpath " $arg" ;; + esac + else + case "$xrpath " in + *" $arg "*) ;; + *) func_append xrpath " $arg" ;; + esac + fi + prev= + continue + ;; + shrext) + shrext_cmds=$arg + prev= + continue + ;; + weak) + func_append weak_libs " $arg" + prev= + continue + ;; + xassembler) + func_append compiler_flags " -Xassembler $qarg" + prev= + func_append compile_command " -Xassembler $qarg" + func_append finalize_command " -Xassembler $qarg" + continue + ;; + xcclinker) + func_append linker_flags " $qarg" + func_append compiler_flags " $qarg" + prev= + func_append compile_command " $qarg" + func_append finalize_command " $qarg" + continue + ;; + xcompiler) + func_append compiler_flags " $qarg" + prev= + func_append compile_command " $qarg" + func_append finalize_command " $qarg" + continue + ;; + xlinker) + func_append linker_flags " $qarg" + func_append compiler_flags " $wl$qarg" + prev= + func_append compile_command " $wl$qarg" + func_append finalize_command " $wl$qarg" + continue + ;; + *) + eval "$prev=\"\$arg\"" + prev= + continue + ;; + esac + fi # test -n "$prev" + + prevarg=$arg + + case $arg in + -all-static) + if test -n "$link_static_flag"; then + # See comment for -static flag below, for more details. + func_append compile_command " $link_static_flag" + func_append finalize_command " $link_static_flag" + fi + continue + ;; + + -allow-undefined) + # FIXME: remove this flag sometime in the future. + func_fatal_error "'-allow-undefined' must not be used because it is the default" + ;; + + -avoid-version) + avoid_version=yes + continue + ;; + + -bindir) + prev=bindir + continue + ;; + + -dlopen) + prev=dlfiles + continue + ;; + + -dlpreopen) + prev=dlprefiles + continue + ;; + + -export-dynamic) + export_dynamic=yes + continue + ;; + + -export-symbols | -export-symbols-regex) + if test -n "$export_symbols" || test -n "$export_symbols_regex"; then + func_fatal_error "more than one -exported-symbols argument is not allowed" + fi + if test X-export-symbols = "X$arg"; then + prev=expsyms + else + prev=expsyms_regex + fi + continue + ;; + + -framework) + prev=framework + continue + ;; + + -inst-prefix-dir) + prev=inst_prefix + continue + ;; + + # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* + # so, if we see these flags be careful not to treat them like -L + -L[A-Z][A-Z]*:*) + case $with_gcc/$host in + no/*-*-irix* | /*-*-irix*) + func_append compile_command " $arg" + func_append finalize_command " $arg" + ;; + esac + continue + ;; + + -L*) + func_stripname "-L" '' "$arg" + if test -z "$func_stripname_result"; then + if test "$#" -gt 0; then + func_fatal_error "require no space between '-L' and '$1'" + else + func_fatal_error "need path for '-L' option" + fi + fi + func_resolve_sysroot "$func_stripname_result" + dir=$func_resolve_sysroot_result + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + absdir=`cd "$dir" && pwd` + test -z "$absdir" && \ + func_fatal_error "cannot determine absolute directory name of '$dir'" + dir=$absdir + ;; + esac + case "$deplibs " in + *" -L$dir "* | *" $arg "*) + # Will only happen for absolute or sysroot arguments + ;; + *) + # Preserve sysroot, but never include relative directories + case $dir in + [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;; + *) func_append deplibs " -L$dir" ;; + esac + func_append lib_search_path " $dir" + ;; + esac + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'` + case :$dllsearchpath: in + *":$dir:"*) ;; + ::) dllsearchpath=$dir;; + *) func_append dllsearchpath ":$dir";; + esac + case :$dllsearchpath: in + *":$testbindir:"*) ;; + ::) dllsearchpath=$testbindir;; + *) func_append dllsearchpath ":$testbindir";; + esac + ;; + esac + continue + ;; + + -l*) + if test X-lc = "X$arg" || test X-lm = "X$arg"; then + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) + # These systems don't actually have a C or math library (as such) + continue + ;; + *-*-os2*) + # These systems don't actually have a C library (as such) + test X-lc = "X$arg" && continue + ;; + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig* | *-*-midnightbsd*) + # Do not include libc due to us having libc/libc_r. + test X-lc = "X$arg" && continue + ;; + *-*-rhapsody* | *-*-darwin1.[012]) + # Rhapsody C and math libraries are in the System framework + func_append deplibs " System.ltframework" + continue + ;; + *-*-sco3.2v5* | *-*-sco5v6*) + # Causes problems with __ctype + test X-lc = "X$arg" && continue + ;; + *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) + # Compiler inserts libc in the correct place for threads to work + test X-lc = "X$arg" && continue + ;; + esac + elif test X-lc_r = "X$arg"; then + case $host in + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig* | *-*-midnightbsd*) + # Do not include libc_r directly, use -pthread flag. + continue + ;; + esac + fi + func_append deplibs " $arg" + continue + ;; + + -mllvm) + prev=mllvm + continue + ;; + + -module) + module=yes + continue + ;; + + # Tru64 UNIX uses -model [arg] to determine the layout of C++ + # classes, name mangling, and exception handling. + # Darwin uses the -arch flag to determine output architecture. + -model|-arch|-isysroot|--sysroot) + func_append compiler_flags " $arg" + func_append compile_command " $arg" + func_append finalize_command " $arg" + prev=xcompiler + continue + ;; + # Solaris ld rejects as of 11.4. Refer to Oracle bug 22985199. + -pthread) + case $host in + *solaris2*) ;; + *) + case "$new_inherited_linker_flags " in + *" $arg "*) ;; + * ) func_append new_inherited_linker_flags " $arg" ;; + esac + ;; + esac + continue + ;; + -mt|-mthreads|-kthread|-Kthread|-pthreads|--thread-safe \ + |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) + func_append compiler_flags " $arg" + func_append compile_command " $arg" + func_append finalize_command " $arg" + case "$new_inherited_linker_flags " in + *" $arg "*) ;; + * ) func_append new_inherited_linker_flags " $arg" ;; + esac + continue + ;; + + -multi_module) + single_module=$wl-multi_module + continue + ;; + + -no-fast-install) + fast_install=no + continue + ;; + + -no-install) + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) + # The PATH hackery in wrapper scripts is required on Windows + # and Darwin in order for the loader to find any dlls it needs. + func_warning "'-no-install' is ignored for $host" + func_warning "assuming '-no-fast-install' instead" + fast_install=no + ;; + *) no_install=yes ;; + esac + continue + ;; + + -no-undefined) + allow_undefined=no + continue + ;; + + -objectlist) + prev=objectlist + continue + ;; + + -os2dllname) + prev=os2dllname + continue + ;; + + -o) prev=output ;; + + -precious-files-regex) + prev=precious_regex + continue + ;; + + -release) + prev=release + continue + ;; + + -rpath) + prev=rpath + continue + ;; + + -R) + prev=xrpath + continue + ;; + + -R*) + func_stripname '-R' '' "$arg" + dir=$func_stripname_result + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + =*) + func_stripname '=' '' "$dir" + dir=$lt_sysroot$func_stripname_result + ;; + *) + func_fatal_error "only absolute run-paths are allowed" + ;; + esac + case "$xrpath " in + *" $dir "*) ;; + *) func_append xrpath " $dir" ;; + esac + continue + ;; + + -shared) + # The effects of -shared are defined in a previous loop. + continue + ;; + + -shrext) + prev=shrext + continue + ;; + + -static | -static-libtool-libs) + # The effects of -static are defined in a previous loop. + # We used to do the same as -all-static on platforms that + # didn't have a PIC flag, but the assumption that the effects + # would be equivalent was wrong. It would break on at least + # Digital Unix and AIX. + continue + ;; + + -thread-safe) + thread_safe=yes + continue + ;; + + -version-info) + prev=vinfo + continue + ;; + + -version-number) + prev=vinfo + vinfo_number=yes + continue + ;; + + -weak) + prev=weak + continue + ;; + + -Wc,*) + func_stripname '-Wc,' '' "$arg" + args=$func_stripname_result + arg= + save_ifs=$IFS; IFS=, + for flag in $args; do + IFS=$save_ifs + func_quote_arg pretty "$flag" + func_append arg " $func_quote_arg_result" + func_append compiler_flags " $func_quote_arg_result" + done + IFS=$save_ifs + func_stripname ' ' '' "$arg" + arg=$func_stripname_result + ;; + + -Wl,*) + func_stripname '-Wl,' '' "$arg" + args=$func_stripname_result + arg= + save_ifs=$IFS; IFS=, + for flag in $args; do + IFS=$save_ifs + func_quote_arg pretty "$flag" + func_append arg " $wl$func_quote_arg_result" + func_append compiler_flags " $wl$func_quote_arg_result" + func_append linker_flags " $func_quote_arg_result" + done + IFS=$save_ifs + func_stripname ' ' '' "$arg" + arg=$func_stripname_result + ;; + + -Xassembler) + prev=xassembler + continue + ;; + + -Xcompiler) + prev=xcompiler + continue + ;; + + -Xlinker) + prev=xlinker + continue + ;; + + -XCClinker) + prev=xcclinker + continue + ;; + + # -msg_* for osf cc + -msg_*) + func_quote_arg pretty "$arg" + arg=$func_quote_arg_result + ;; + + # Flags to be passed through unchanged, with rationale: + # -64, -mips[0-9] enable 64-bit mode for the SGI compiler + # -r[0-9][0-9]* specify processor for the SGI compiler + # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler + # +DA*, +DD* enable 64-bit mode for the HP compiler + # -q* compiler args for the IBM compiler + # -m*, -t[45]*, -txscale* architecture-specific flags for GCC + # -F/path path to uninstalled frameworks, gcc on darwin + # -p, -pg, --coverage, -fprofile-* profiling flags for GCC + # -fstack-protector* stack protector flags for GCC + # @file GCC response files + # -tp=* Portland pgcc target processor selection + # --sysroot=* for sysroot support + # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization + # -specs=* GCC specs files + # -stdlib=* select c++ std lib with clang + # -fsanitize=* Clang/GCC memory and address sanitizer + # -fuse-ld=* Linker select flags for GCC + # -static-* direct GCC to link specific libraries statically + # -fcilkplus Cilk Plus language extension features for C/C++ + # -Wa,* Pass flags directly to the assembler + -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ + -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \ + -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*| \ + -specs=*|-fsanitize=*|-fuse-ld=*|-static-*|-fcilkplus|-Wa,*) + func_quote_arg pretty "$arg" + arg=$func_quote_arg_result + func_append compile_command " $arg" + func_append finalize_command " $arg" + func_append compiler_flags " $arg" + continue + ;; + + -Z*) + if test os2 = "`expr $host : '.*\(os2\)'`"; then + # OS/2 uses -Zxxx to specify OS/2-specific options + compiler_flags="$compiler_flags $arg" + func_append compile_command " $arg" + func_append finalize_command " $arg" + case $arg in + -Zlinker | -Zstack) + prev=xcompiler + ;; + esac + continue + else + # Otherwise treat like 'Some other compiler flag' below + func_quote_arg pretty "$arg" + arg=$func_quote_arg_result + fi + ;; + + # Some other compiler flag. + -* | +*) + func_quote_arg pretty "$arg" + arg=$func_quote_arg_result + ;; + + *.$objext) + # A standard object. + func_append objs " $arg" + ;; + + *.lo) + # A libtool-controlled object. + + # Check to see that this really is a libtool object. + if func_lalib_unsafe_p "$arg"; then + pic_object= + non_pic_object= + + # Read the .lo file + func_source "$arg" + + if test -z "$pic_object" || + test -z "$non_pic_object" || + test none = "$pic_object" && + test none = "$non_pic_object"; then + func_fatal_error "cannot find name of object for '$arg'" + fi + + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir=$func_dirname_result + + test none = "$pic_object" || { + # Prepend the subdirectory the object is found in. + pic_object=$xdir$pic_object + + if test dlfiles = "$prev"; then + if test yes = "$build_libtool_libs" && test yes = "$dlopen_support"; then + func_append dlfiles " $pic_object" + prev= + continue + else + # If libtool objects are unsupported, then we need to preload. + prev=dlprefiles + fi + fi + + # CHECK ME: I think I busted this. -Ossama + if test dlprefiles = "$prev"; then + # Preload the old-style object. + func_append dlprefiles " $pic_object" + prev= + fi + + # A PIC object. + func_append libobjs " $pic_object" + arg=$pic_object + } + + # Non-PIC object. + if test none != "$non_pic_object"; then + # Prepend the subdirectory the object is found in. + non_pic_object=$xdir$non_pic_object + + # A standard non-PIC object + func_append non_pic_objects " $non_pic_object" + if test -z "$pic_object" || test none = "$pic_object"; then + arg=$non_pic_object + fi + else + # If the PIC object exists, use it instead. + # $xdir was prepended to $pic_object above. + non_pic_object=$pic_object + func_append non_pic_objects " $non_pic_object" + fi + else + # Only an error if not doing a dry-run. + if $opt_dry_run; then + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir=$func_dirname_result + + func_lo2o "$arg" + pic_object=$xdir$objdir/$func_lo2o_result + non_pic_object=$xdir$func_lo2o_result + func_append libobjs " $pic_object" + func_append non_pic_objects " $non_pic_object" + else + func_fatal_error "'$arg' is not a valid libtool object" + fi + fi + ;; + + *.$libext) + # An archive. + func_append deplibs " $arg" + func_append old_deplibs " $arg" + continue + ;; + + *.la) + # A libtool-controlled library. + + func_resolve_sysroot "$arg" + if test dlfiles = "$prev"; then + # This library was specified with -dlopen. + func_append dlfiles " $func_resolve_sysroot_result" + prev= + elif test dlprefiles = "$prev"; then + # The library was specified with -dlpreopen. + func_append dlprefiles " $func_resolve_sysroot_result" + prev= + else + func_append deplibs " $func_resolve_sysroot_result" + fi + continue + ;; + + # Some other compiler argument. + *) + # Unknown arguments in both finalize_command and compile_command need + # to be aesthetically quoted because they are evaled later. + func_quote_arg pretty "$arg" + arg=$func_quote_arg_result + ;; + esac # arg + + # Now actually substitute the argument into the commands. + if test -n "$arg"; then + func_append compile_command " $arg" + func_append finalize_command " $arg" + fi + done # argument parsing loop + + test -n "$prev" && \ + func_fatal_help "the '$prevarg' option requires an argument" + + if test yes = "$export_dynamic" && test -n "$export_dynamic_flag_spec"; then + eval arg=\"$export_dynamic_flag_spec\" + func_append compile_command " $arg" + func_append finalize_command " $arg" + fi + + oldlibs= + # calculate the name of the file, without its directory + func_basename "$output" + outputname=$func_basename_result + libobjs_save=$libobjs + + if test -n "$shlibpath_var"; then + # get the directories listed in $shlibpath_var + eval shlib_search_path=\`\$ECHO \"\$$shlibpath_var\" \| \$SED \'s/:/ /g\'\` + else + shlib_search_path= + fi + eval sys_lib_search_path=\"$sys_lib_search_path_spec\" + eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" + + # Definition is injected by LT_CONFIG during libtool generation. + func_munge_path_list sys_lib_dlsearch_path "$LT_SYS_LIBRARY_PATH" + + func_dirname "$output" "/" "" + output_objdir=$func_dirname_result$objdir + func_to_tool_file "$output_objdir/" + tool_output_objdir=$func_to_tool_file_result + # Create the object directory. + func_mkdir_p "$output_objdir" + + # Determine the type of output + case $output in + "") + func_fatal_help "you must specify an output file" + ;; + *.$libext) linkmode=oldlib ;; + *.lo | *.$objext) linkmode=obj ;; + *.la) linkmode=lib ;; + *) linkmode=prog ;; # Anything else should be a program. + esac + + specialdeplibs= + + libs= + # Find all interdependent deplibs by searching for libraries + # that are linked more than once (e.g. -la -lb -la) + for deplib in $deplibs; do + if $opt_preserve_dup_deps; then + case "$libs " in + *" $deplib "*) func_append specialdeplibs " $deplib" ;; + esac + fi + func_append libs " $deplib" + done + + if test lib = "$linkmode"; then + libs="$predeps $libs $compiler_lib_search_path $postdeps" + + # Compute libraries that are listed more than once in $predeps + # $postdeps and mark them as special (i.e., whose duplicates are + # not to be eliminated). + pre_post_deps= + if $opt_duplicate_compiler_generated_deps; then + for pre_post_dep in $predeps $postdeps; do + case "$pre_post_deps " in + *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;; + esac + func_append pre_post_deps " $pre_post_dep" + done + fi + pre_post_deps= + fi + + deplibs= + newdependency_libs= + newlib_search_path= + need_relink=no # whether we're linking any uninstalled libtool libraries + notinst_deplibs= # not-installed libtool libraries + notinst_path= # paths that contain not-installed libtool libraries + + case $linkmode in + lib) + passes="conv dlpreopen link" + for file in $dlfiles $dlprefiles; do + case $file in + *.la) ;; + *) + func_fatal_help "libraries can '-dlopen' only libtool libraries: $file" + ;; + esac + done + ;; + prog) + compile_deplibs= + finalize_deplibs= + alldeplibs=false + newdlfiles= + newdlprefiles= + passes="conv scan dlopen dlpreopen link" + ;; + *) passes="conv" + ;; + esac + + for pass in $passes; do + # The preopen pass in lib mode reverses $deplibs; put it back here + # so that -L comes before libs that need it for instance... + if test lib,link = "$linkmode,$pass"; then + ## FIXME: Find the place where the list is rebuilt in the wrong + ## order, and fix it there properly + tmp_deplibs= + for deplib in $deplibs; do + tmp_deplibs="$deplib $tmp_deplibs" + done + deplibs=$tmp_deplibs + fi + + if test lib,link = "$linkmode,$pass" || + test prog,scan = "$linkmode,$pass"; then + libs=$deplibs + deplibs= + fi + if test prog = "$linkmode"; then + case $pass in + dlopen) libs=$dlfiles ;; + dlpreopen) libs=$dlprefiles ;; + link) + libs="$deplibs %DEPLIBS%" + test "X$link_all_deplibs" != Xno && libs="$libs $dependency_libs" + ;; + esac + fi + if test lib,dlpreopen = "$linkmode,$pass"; then + # Collect and forward deplibs of preopened libtool libs + for lib in $dlprefiles; do + # Ignore non-libtool-libs + dependency_libs= + func_resolve_sysroot "$lib" + case $lib in + *.la) func_source "$func_resolve_sysroot_result" ;; + esac + + # Collect preopened libtool deplibs, except any this library + # has declared as weak libs + for deplib in $dependency_libs; do + func_basename "$deplib" + deplib_base=$func_basename_result + case " $weak_libs " in + *" $deplib_base "*) ;; + *) func_append deplibs " $deplib" ;; + esac + done + done + libs=$dlprefiles + fi + if test dlopen = "$pass"; then + # Collect dlpreopened libraries + save_deplibs=$deplibs + deplibs= + fi + + for deplib in $libs; do + lib= + found=false + case $deplib in + -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ + |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) + if test prog,link = "$linkmode,$pass"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + func_append compiler_flags " $deplib" + if test lib = "$linkmode"; then + case "$new_inherited_linker_flags " in + *" $deplib "*) ;; + * ) func_append new_inherited_linker_flags " $deplib" ;; + esac + fi + fi + continue + ;; + -l*) + if test lib != "$linkmode" && test prog != "$linkmode"; then + func_warning "'-l' is ignored for archives/objects" + continue + fi + func_stripname '-l' '' "$deplib" + name=$func_stripname_result + if test lib = "$linkmode"; then + searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" + else + searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" + fi + for searchdir in $searchdirs; do + for search_ext in .la $std_shrext .so .a; do + # Search the libtool library + lib=$searchdir/lib$name$search_ext + if test -f "$lib"; then + if test .la = "$search_ext"; then + found=: + else + found=false + fi + break 2 + fi + done + done + if $found; then + # deplib is a libtool library + # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, + # We need to do some special things here, and not later. + if test yes = "$allow_libtool_libs_with_static_runtimes"; then + case " $predeps $postdeps " in + *" $deplib "*) + if func_lalib_p "$lib"; then + library_names= + old_library= + func_source "$lib" + for l in $old_library $library_names; do + ll=$l + done + if test "X$ll" = "X$old_library"; then # only static version available + found=false + func_dirname "$lib" "" "." + ladir=$func_dirname_result + lib=$ladir/$old_library + if test prog,link = "$linkmode,$pass"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + test lib = "$linkmode" && newdependency_libs="$deplib $newdependency_libs" + fi + continue + fi + fi + ;; + *) ;; + esac + fi + else + # deplib doesn't seem to be a libtool library + if test prog,link = "$linkmode,$pass"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + test lib = "$linkmode" && newdependency_libs="$deplib $newdependency_libs" + fi + continue + fi + ;; # -l + *.ltframework) + if test prog,link = "$linkmode,$pass"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + if test lib = "$linkmode"; then + case "$new_inherited_linker_flags " in + *" $deplib "*) ;; + * ) func_append new_inherited_linker_flags " $deplib" ;; + esac + fi + fi + continue + ;; + -L*) + case $linkmode in + lib) + deplibs="$deplib $deplibs" + test conv = "$pass" && continue + newdependency_libs="$deplib $newdependency_libs" + func_stripname '-L' '' "$deplib" + func_resolve_sysroot "$func_stripname_result" + func_append newlib_search_path " $func_resolve_sysroot_result" + ;; + prog) + if test conv = "$pass"; then + deplibs="$deplib $deplibs" + continue + fi + if test scan = "$pass"; then + deplibs="$deplib $deplibs" + else + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + fi + func_stripname '-L' '' "$deplib" + func_resolve_sysroot "$func_stripname_result" + func_append newlib_search_path " $func_resolve_sysroot_result" + ;; + *) + func_warning "'-L' is ignored for archives/objects" + ;; + esac # linkmode + continue + ;; # -L + -R*) + if test link = "$pass"; then + func_stripname '-R' '' "$deplib" + func_resolve_sysroot "$func_stripname_result" + dir=$func_resolve_sysroot_result + # Make sure the xrpath contains only unique directories. + case "$xrpath " in + *" $dir "*) ;; + *) func_append xrpath " $dir" ;; + esac + fi + deplibs="$deplib $deplibs" + continue + ;; + *.la) + func_resolve_sysroot "$deplib" + lib=$func_resolve_sysroot_result + ;; + *.$libext) + if test conv = "$pass"; then + deplibs="$deplib $deplibs" + continue + fi + case $linkmode in + lib) + # Linking convenience modules into shared libraries is allowed, + # but linking other static libraries is non-portable. + case " $dlpreconveniencelibs " in + *" $deplib "*) ;; + *) + valid_a_lib=false + case $deplibs_check_method in + match_pattern*) + set dummy $deplibs_check_method; shift + match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` + if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \ + | $EGREP "$match_pattern_regex" > /dev/null; then + valid_a_lib=: + fi + ;; + pass_all) + valid_a_lib=: + ;; + esac + if $valid_a_lib; then + echo + $ECHO "*** Warning: Linking the shared library $output against the" + $ECHO "*** static library $deplib is not portable!" + deplibs="$deplib $deplibs" + else + echo + $ECHO "*** Warning: Trying to link with static lib archive $deplib." + echo "*** I have the capability to make that library automatically link in when" + echo "*** you link to this library. But I can only do this if you have a" + echo "*** shared version of the library, which you do not appear to have" + echo "*** because the file extensions .$libext of this argument makes me believe" + echo "*** that it is just a static archive that I should not use here." + fi + ;; + esac + continue + ;; + prog) + if test link != "$pass"; then + deplibs="$deplib $deplibs" + else + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + fi + continue + ;; + esac # linkmode + ;; # *.$libext + *.lo | *.$objext) + if test conv = "$pass"; then + deplibs="$deplib $deplibs" + elif test prog = "$linkmode"; then + if test dlpreopen = "$pass" || test yes != "$dlopen_support" || test no = "$build_libtool_libs"; then + # If there is no dlopen support or we're linking statically, + # we need to preload. + func_append newdlprefiles " $deplib" + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + func_append newdlfiles " $deplib" + fi + fi + continue + ;; + %DEPLIBS%) + alldeplibs=: + continue + ;; + esac # case $deplib + + $found || test -f "$lib" \ + || func_fatal_error "cannot find the library '$lib' or unhandled argument '$deplib'" + + # Check to see that this really is a libtool archive. + func_lalib_unsafe_p "$lib" \ + || func_fatal_error "'$lib' is not a valid libtool archive" + + func_dirname "$lib" "" "." + ladir=$func_dirname_result + + dlname= + dlopen= + dlpreopen= + libdir= + library_names= + old_library= + inherited_linker_flags= + # If the library was installed with an old release of libtool, + # it will not redefine variables installed, or shouldnotlink + installed=yes + shouldnotlink=no + avoidtemprpath= + + + # Read the .la file + func_source "$lib" + + # Convert "-framework foo" to "foo.ltframework" + if test -n "$inherited_linker_flags"; then + tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'` + for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do + case " $new_inherited_linker_flags " in + *" $tmp_inherited_linker_flag "*) ;; + *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";; + esac + done + fi + dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + if test lib,link = "$linkmode,$pass" || + test prog,scan = "$linkmode,$pass" || + { test prog != "$linkmode" && test lib != "$linkmode"; }; then + test -n "$dlopen" && func_append dlfiles " $dlopen" + test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen" + fi + + if test conv = "$pass"; then + # Only check for convenience libraries + deplibs="$lib $deplibs" + if test -z "$libdir"; then + if test -z "$old_library"; then + func_fatal_error "cannot find name of link library for '$lib'" + fi + # It is a libtool convenience library, so add in its objects. + func_append convenience " $ladir/$objdir/$old_library" + func_append old_convenience " $ladir/$objdir/$old_library" + tmp_libs= + for deplib in $dependency_libs; do + deplibs="$deplib $deplibs" + if $opt_preserve_dup_deps; then + case "$tmp_libs " in + *" $deplib "*) func_append specialdeplibs " $deplib" ;; + esac + fi + func_append tmp_libs " $deplib" + done + elif test prog != "$linkmode" && test lib != "$linkmode"; then + func_fatal_error "'$lib' is not a convenience library" + fi + continue + fi # $pass = conv + + + # Get the name of the library we link against. + linklib= + if test -n "$old_library" && + { test yes = "$prefer_static_libs" || + test built,no = "$prefer_static_libs,$installed"; }; then + linklib=$old_library + else + for l in $old_library $library_names; do + linklib=$l + done + fi + if test -z "$linklib"; then + func_fatal_error "cannot find name of link library for '$lib'" + fi + + # This library was specified with -dlopen. + if test dlopen = "$pass"; then + test -z "$libdir" \ + && func_fatal_error "cannot -dlopen a convenience library: '$lib'" + if test -z "$dlname" || + test yes != "$dlopen_support" || + test no = "$build_libtool_libs" + then + # If there is no dlname, no dlopen support or we're linking + # statically, we need to preload. We also need to preload any + # dependent libraries so libltdl's deplib preloader doesn't + # bomb out in the load deplibs phase. + func_append dlprefiles " $lib $dependency_libs" + else + func_append newdlfiles " $lib" + fi + continue + fi # $pass = dlopen + + # We need an absolute path. + case $ladir in + [\\/]* | [A-Za-z]:[\\/]*) abs_ladir=$ladir ;; + *) + abs_ladir=`cd "$ladir" && pwd` + if test -z "$abs_ladir"; then + func_warning "cannot determine absolute directory name of '$ladir'" + func_warning "passing it literally to the linker, although it might fail" + abs_ladir=$ladir + fi + ;; + esac + func_basename "$lib" + laname=$func_basename_result + + # Find the relevant object directory and library name. + if test yes = "$installed"; then + if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then + func_warning "library '$lib' was moved." + dir=$ladir + absdir=$abs_ladir + libdir=$abs_ladir + else + dir=$lt_sysroot$libdir + absdir=$lt_sysroot$libdir + fi + test yes = "$hardcode_automatic" && avoidtemprpath=yes + else + if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then + dir=$ladir + absdir=$abs_ladir + # Remove this search path later + func_append notinst_path " $abs_ladir" + else + dir=$ladir/$objdir + absdir=$abs_ladir/$objdir + # Remove this search path later + func_append notinst_path " $abs_ladir" + fi + fi # $installed = yes + func_stripname 'lib' '.la' "$laname" + name=$func_stripname_result + + # This library was specified with -dlpreopen. + if test dlpreopen = "$pass"; then + if test -z "$libdir" && test prog = "$linkmode"; then + func_fatal_error "only libraries may -dlpreopen a convenience library: '$lib'" + fi + case $host in + # special handling for platforms with PE-DLLs. + *cygwin* | *mingw* | *cegcc* ) + # Linker will automatically link against shared library if both + # static and shared are present. Therefore, ensure we extract + # symbols from the import library if a shared library is present + # (otherwise, the dlopen module name will be incorrect). We do + # this by putting the import library name into $newdlprefiles. + # We recover the dlopen module name by 'saving' the la file + # name in a special purpose variable, and (later) extracting the + # dlname from the la file. + if test -n "$dlname"; then + func_tr_sh "$dir/$linklib" + eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname" + func_append newdlprefiles " $dir/$linklib" + else + func_append newdlprefiles " $dir/$old_library" + # Keep a list of preopened convenience libraries to check + # that they are being used correctly in the link pass. + test -z "$libdir" && \ + func_append dlpreconveniencelibs " $dir/$old_library" + fi + ;; + * ) + # Prefer using a static library (so that no silly _DYNAMIC symbols + # are required to link). + if test -n "$old_library"; then + func_append newdlprefiles " $dir/$old_library" + # Keep a list of preopened convenience libraries to check + # that they are being used correctly in the link pass. + test -z "$libdir" && \ + func_append dlpreconveniencelibs " $dir/$old_library" + # Otherwise, use the dlname, so that lt_dlopen finds it. + elif test -n "$dlname"; then + func_append newdlprefiles " $dir/$dlname" + else + func_append newdlprefiles " $dir/$linklib" + fi + ;; + esac + fi # $pass = dlpreopen + + if test -z "$libdir"; then + # Link the convenience library + if test lib = "$linkmode"; then + deplibs="$dir/$old_library $deplibs" + elif test prog,link = "$linkmode,$pass"; then + compile_deplibs="$dir/$old_library $compile_deplibs" + finalize_deplibs="$dir/$old_library $finalize_deplibs" + else + deplibs="$lib $deplibs" # used for prog,scan pass + fi + continue + fi + + + if test prog = "$linkmode" && test link != "$pass"; then + func_append newlib_search_path " $ladir" + deplibs="$lib $deplibs" + + linkalldeplibs=false + if test no != "$link_all_deplibs" || test -z "$library_names" || + test no = "$build_libtool_libs"; then + linkalldeplibs=: + fi + + tmp_libs= + for deplib in $dependency_libs; do + case $deplib in + -L*) func_stripname '-L' '' "$deplib" + func_resolve_sysroot "$func_stripname_result" + func_append newlib_search_path " $func_resolve_sysroot_result" + ;; + esac + # Need to link against all dependency_libs? + if $linkalldeplibs; then + deplibs="$deplib $deplibs" + else + # Need to hardcode shared library paths + # or/and link against static libraries + newdependency_libs="$deplib $newdependency_libs" + fi + if $opt_preserve_dup_deps; then + case "$tmp_libs " in + *" $deplib "*) func_append specialdeplibs " $deplib" ;; + esac + fi + func_append tmp_libs " $deplib" + done # for deplib + continue + fi # $linkmode = prog... + + if test prog,link = "$linkmode,$pass"; then + if test -n "$library_names" && + { { test no = "$prefer_static_libs" || + test built,yes = "$prefer_static_libs,$installed"; } || + test -z "$old_library"; }; then + # We need to hardcode the library path + if test -n "$shlibpath_var" && test -z "$avoidtemprpath"; then + # Make sure the rpath contains only unique directories. + case $temp_rpath: in + *"$absdir:"*) ;; + *) func_append temp_rpath "$absdir:" ;; + esac + fi + + # Hardcode the library path. + # Skip directories that are in the system default run-time + # search path. + case " $sys_lib_dlsearch_path " in + *" $absdir "*) ;; + *) + case "$compile_rpath " in + *" $absdir "*) ;; + *) func_append compile_rpath " $absdir" ;; + esac + ;; + esac + case " $sys_lib_dlsearch_path " in + *" $libdir "*) ;; + *) + case "$finalize_rpath " in + *" $libdir "*) ;; + *) func_append finalize_rpath " $libdir" ;; + esac + ;; + esac + fi # $linkmode,$pass = prog,link... + + if $alldeplibs && + { test pass_all = "$deplibs_check_method" || + { test yes = "$build_libtool_libs" && + test -n "$library_names"; }; }; then + # We only need to search for static libraries + continue + fi + fi + + link_static=no # Whether the deplib will be linked statically + use_static_libs=$prefer_static_libs + if test built = "$use_static_libs" && test yes = "$installed"; then + use_static_libs=no + fi + if test -n "$library_names" && + { test no = "$use_static_libs" || test -z "$old_library"; }; then + case $host in + *cygwin* | *mingw* | *cegcc* | *os2*) + # No point in relinking DLLs because paths are not encoded + func_append notinst_deplibs " $lib" + need_relink=no + ;; + *) + if test no = "$installed"; then + func_append notinst_deplibs " $lib" + need_relink=yes + fi + ;; + esac + # This is a shared library + + # Warn about portability, can't link against -module's on some + # systems (darwin). Don't bleat about dlopened modules though! + dlopenmodule= + for dlpremoduletest in $dlprefiles; do + if test "X$dlpremoduletest" = "X$lib"; then + dlopenmodule=$dlpremoduletest + break + fi + done + if test -z "$dlopenmodule" && test yes = "$shouldnotlink" && test link = "$pass"; then + echo + if test prog = "$linkmode"; then + $ECHO "*** Warning: Linking the executable $output against the loadable module" + else + $ECHO "*** Warning: Linking the shared library $output against the loadable module" + fi + $ECHO "*** $linklib is not portable!" + fi + if test lib = "$linkmode" && + test yes = "$hardcode_into_libs"; then + # Hardcode the library path. + # Skip directories that are in the system default run-time + # search path. + case " $sys_lib_dlsearch_path " in + *" $absdir "*) ;; + *) + case "$compile_rpath " in + *" $absdir "*) ;; + *) func_append compile_rpath " $absdir" ;; + esac + ;; + esac + case " $sys_lib_dlsearch_path " in + *" $libdir "*) ;; + *) + case "$finalize_rpath " in + *" $libdir "*) ;; + *) func_append finalize_rpath " $libdir" ;; + esac + ;; + esac + fi + + if test -n "$old_archive_from_expsyms_cmds"; then + # figure out the soname + set dummy $library_names + shift + realname=$1 + shift + libname=`eval "\\$ECHO \"$libname_spec\""` + # use dlname if we got it. it's perfectly good, no? + if test -n "$dlname"; then + soname=$dlname + elif test -n "$soname_spec"; then + # bleh windows + case $host in + *cygwin* | mingw* | *cegcc* | *os2*) + func_arith $current - $age + major=$func_arith_result + versuffix=-$major + ;; + esac + eval soname=\"$soname_spec\" + else + soname=$realname + fi + + # Make a new name for the extract_expsyms_cmds to use + soroot=$soname + func_basename "$soroot" + soname=$func_basename_result + func_stripname 'lib' '.dll' "$soname" + newlib=libimp-$func_stripname_result.a + + # If the library has no export list, then create one now + if test -f "$output_objdir/$soname-def"; then : + else + func_verbose "extracting exported symbol list from '$soname'" + func_execute_cmds "$extract_expsyms_cmds" 'exit $?' + fi + + # Create $newlib + if test -f "$output_objdir/$newlib"; then :; else + func_verbose "generating import library for '$soname'" + func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' + fi + # make sure the library variables are pointing to the new library + dir=$output_objdir + linklib=$newlib + fi # test -n "$old_archive_from_expsyms_cmds" + + if test prog = "$linkmode" || test relink != "$opt_mode"; then + add_shlibpath= + add_dir= + add= + lib_linked=yes + case $hardcode_action in + immediate | unsupported) + if test no = "$hardcode_direct"; then + add=$dir/$linklib + case $host in + *-*-sco3.2v5.0.[024]*) add_dir=-L$dir ;; + *-*-sysv4*uw2*) add_dir=-L$dir ;; + *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ + *-*-unixware7*) add_dir=-L$dir ;; + *-*-darwin* ) + # if the lib is a (non-dlopened) module then we cannot + # link against it, someone is ignoring the earlier warnings + if /usr/bin/file -L $add 2> /dev/null | + $GREP ": [^:]* bundle" >/dev/null; then + if test "X$dlopenmodule" != "X$lib"; then + $ECHO "*** Warning: lib $linklib is a module, not a shared library" + if test -z "$old_library"; then + echo + echo "*** And there doesn't seem to be a static archive available" + echo "*** The link will probably fail, sorry" + else + add=$dir/$old_library + fi + elif test -n "$old_library"; then + add=$dir/$old_library + fi + fi + esac + elif test no = "$hardcode_minus_L"; then + case $host in + *-*-sunos*) add_shlibpath=$dir ;; + esac + add_dir=-L$dir + add=-l$name + elif test no = "$hardcode_shlibpath_var"; then + add_shlibpath=$dir + add=-l$name + else + lib_linked=no + fi + ;; + relink) + if test yes = "$hardcode_direct" && + test no = "$hardcode_direct_absolute"; then + add=$dir/$linklib + elif test yes = "$hardcode_minus_L"; then + add_dir=-L$absdir + # Try looking first in the location we're being installed to. + if test -n "$inst_prefix_dir"; then + case $libdir in + [\\/]*) + func_append add_dir " -L$inst_prefix_dir$libdir" + ;; + esac + fi + add=-l$name + elif test yes = "$hardcode_shlibpath_var"; then + add_shlibpath=$dir + add=-l$name + else + lib_linked=no + fi + ;; + *) lib_linked=no ;; + esac + + if test yes != "$lib_linked"; then + func_fatal_configuration "unsupported hardcode properties" + fi + + if test -n "$add_shlibpath"; then + case :$compile_shlibpath: in + *":$add_shlibpath:"*) ;; + *) func_append compile_shlibpath "$add_shlibpath:" ;; + esac + fi + if test prog = "$linkmode"; then + test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" + test -n "$add" && compile_deplibs="$add $compile_deplibs" + else + test -n "$add_dir" && deplibs="$add_dir $deplibs" + test -n "$add" && deplibs="$add $deplibs" + if test yes != "$hardcode_direct" && + test yes != "$hardcode_minus_L" && + test yes = "$hardcode_shlibpath_var"; then + case :$finalize_shlibpath: in + *":$libdir:"*) ;; + *) func_append finalize_shlibpath "$libdir:" ;; + esac + fi + fi + fi + + if test prog = "$linkmode" || test relink = "$opt_mode"; then + add_shlibpath= + add_dir= + add= + # Finalize command for both is simple: just hardcode it. + if test yes = "$hardcode_direct" && + test no = "$hardcode_direct_absolute"; then + add=$libdir/$linklib + elif test yes = "$hardcode_minus_L"; then + add_dir=-L$libdir + add=-l$name + elif test yes = "$hardcode_shlibpath_var"; then + case :$finalize_shlibpath: in + *":$libdir:"*) ;; + *) func_append finalize_shlibpath "$libdir:" ;; + esac + add=-l$name + elif test yes = "$hardcode_automatic"; then + if test -n "$inst_prefix_dir" && + test -f "$inst_prefix_dir$libdir/$linklib"; then + add=$inst_prefix_dir$libdir/$linklib + else + add=$libdir/$linklib + fi + else + # We cannot seem to hardcode it, guess we'll fake it. + add_dir=-L$libdir + # Try looking first in the location we're being installed to. + if test -n "$inst_prefix_dir"; then + case $libdir in + [\\/]*) + func_append add_dir " -L$inst_prefix_dir$libdir" + ;; + esac + fi + add=-l$name + fi + + if test prog = "$linkmode"; then + test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" + test -n "$add" && finalize_deplibs="$add $finalize_deplibs" + else + test -n "$add_dir" && deplibs="$add_dir $deplibs" + test -n "$add" && deplibs="$add $deplibs" + fi + fi + elif test prog = "$linkmode"; then + # Here we assume that one of hardcode_direct or hardcode_minus_L + # is not unsupported. This is valid on all known static and + # shared platforms. + if test unsupported != "$hardcode_direct"; then + test -n "$old_library" && linklib=$old_library + compile_deplibs="$dir/$linklib $compile_deplibs" + finalize_deplibs="$dir/$linklib $finalize_deplibs" + else + compile_deplibs="-l$name -L$dir $compile_deplibs" + finalize_deplibs="-l$name -L$dir $finalize_deplibs" + fi + elif test yes = "$build_libtool_libs"; then + # Not a shared library + if test pass_all != "$deplibs_check_method"; then + # We're trying link a shared library against a static one + # but the system doesn't support it. + + # Just print a warning and add the library to dependency_libs so + # that the program can be linked against the static library. + echo + $ECHO "*** Warning: This system cannot link to static lib archive $lib." + echo "*** I have the capability to make that library automatically link in when" + echo "*** you link to this library. But I can only do this if you have a" + echo "*** shared version of the library, which you do not appear to have." + if test yes = "$module"; then + echo "*** But as you try to build a module library, libtool will still create " + echo "*** a static module, that should work as long as the dlopening application" + echo "*** is linked with the -dlopen flag to resolve symbols at runtime." + if test -z "$global_symbol_pipe"; then + echo + echo "*** However, this would only work if libtool was able to extract symbol" + echo "*** lists from a program, using 'nm' or equivalent, but libtool could" + echo "*** not find such a program. So, this module is probably useless." + echo "*** 'nm' from GNU binutils and a full rebuild may help." + fi + if test no = "$build_old_libs"; then + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + fi + else + deplibs="$dir/$old_library $deplibs" + link_static=yes + fi + fi # link shared/static library? + + if test lib = "$linkmode"; then + if test -n "$dependency_libs" && + { test yes != "$hardcode_into_libs" || + test yes = "$build_old_libs" || + test yes = "$link_static"; }; then + # Extract -R from dependency_libs + temp_deplibs= + for libdir in $dependency_libs; do + case $libdir in + -R*) func_stripname '-R' '' "$libdir" + temp_xrpath=$func_stripname_result + case " $xrpath " in + *" $temp_xrpath "*) ;; + *) func_append xrpath " $temp_xrpath";; + esac;; + *) func_append temp_deplibs " $libdir";; + esac + done + dependency_libs=$temp_deplibs + fi + + func_append newlib_search_path " $absdir" + # Link against this library + test no = "$link_static" && newdependency_libs="$abs_ladir/$laname $newdependency_libs" + # ... and its dependency_libs + tmp_libs= + for deplib in $dependency_libs; do + newdependency_libs="$deplib $newdependency_libs" + case $deplib in + -L*) func_stripname '-L' '' "$deplib" + func_resolve_sysroot "$func_stripname_result";; + *) func_resolve_sysroot "$deplib" ;; + esac + if $opt_preserve_dup_deps; then + case "$tmp_libs " in + *" $func_resolve_sysroot_result "*) + func_append specialdeplibs " $func_resolve_sysroot_result" ;; + esac + fi + func_append tmp_libs " $func_resolve_sysroot_result" + done + + if test no != "$link_all_deplibs"; then + # Add the search paths of all dependency libraries + for deplib in $dependency_libs; do + path= + case $deplib in + -L*) path=$deplib ;; + *.la) + func_resolve_sysroot "$deplib" + deplib=$func_resolve_sysroot_result + func_dirname "$deplib" "" "." + dir=$func_dirname_result + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) absdir=$dir ;; + *) + absdir=`cd "$dir" && pwd` + if test -z "$absdir"; then + func_warning "cannot determine absolute directory name of '$dir'" + absdir=$dir + fi + ;; + esac + if $GREP "^installed=no" $deplib > /dev/null; then + case $host in + *-*-darwin*) + depdepl= + eval deplibrary_names=`$SED -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` + if test -n "$deplibrary_names"; then + for tmp in $deplibrary_names; do + depdepl=$tmp + done + if test -f "$absdir/$objdir/$depdepl"; then + depdepl=$absdir/$objdir/$depdepl + darwin_install_name=`$OTOOL -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` + if test -z "$darwin_install_name"; then + darwin_install_name=`$OTOOL64 -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` + fi + func_append compiler_flags " $wl-dylib_file $wl$darwin_install_name:$depdepl" + func_append linker_flags " -dylib_file $darwin_install_name:$depdepl" + path= + fi + fi + ;; + *) + path=-L$absdir/$objdir + ;; + esac + else + eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` + test -z "$libdir" && \ + func_fatal_error "'$deplib' is not a valid libtool archive" + test "$absdir" != "$libdir" && \ + func_warning "'$deplib' seems to be moved" + + path=-L$absdir + fi + ;; + esac + case " $deplibs " in + *" $path "*) ;; + *) deplibs="$path $deplibs" ;; + esac + done + fi # link_all_deplibs != no + fi # linkmode = lib + done # for deplib in $libs + if test link = "$pass"; then + if test prog = "$linkmode"; then + compile_deplibs="$new_inherited_linker_flags $compile_deplibs" + finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" + else + compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + fi + fi + dependency_libs=$newdependency_libs + if test dlpreopen = "$pass"; then + # Link the dlpreopened libraries before other libraries + for deplib in $save_deplibs; do + deplibs="$deplib $deplibs" + done + fi + if test dlopen != "$pass"; then + test conv = "$pass" || { + # Make sure lib_search_path contains only unique directories. + lib_search_path= + for dir in $newlib_search_path; do + case "$lib_search_path " in + *" $dir "*) ;; + *) func_append lib_search_path " $dir" ;; + esac + done + newlib_search_path= + } + + if test prog,link = "$linkmode,$pass"; then + vars="compile_deplibs finalize_deplibs" + else + vars=deplibs + fi + for var in $vars dependency_libs; do + # Add libraries to $var in reverse order + eval tmp_libs=\"\$$var\" + new_libs= + for deplib in $tmp_libs; do + # FIXME: Pedantically, this is the right thing to do, so + # that some nasty dependency loop isn't accidentally + # broken: + #new_libs="$deplib $new_libs" + # Pragmatically, this seems to cause very few problems in + # practice: + case $deplib in + -L*) new_libs="$deplib $new_libs" ;; + -R*) ;; + *) + # And here is the reason: when a library appears more + # than once as an explicit dependence of a library, or + # is implicitly linked in more than once by the + # compiler, it is considered special, and multiple + # occurrences thereof are not removed. Compare this + # with having the same library being listed as a + # dependency of multiple other libraries: in this case, + # we know (pedantically, we assume) the library does not + # need to be listed more than once, so we keep only the + # last copy. This is not always right, but it is rare + # enough that we require users that really mean to play + # such unportable linking tricks to link the library + # using -Wl,-lname, so that libtool does not consider it + # for duplicate removal. + case " $specialdeplibs " in + *" $deplib "*) new_libs="$deplib $new_libs" ;; + *) + case " $new_libs " in + *" $deplib "*) ;; + *) new_libs="$deplib $new_libs" ;; + esac + ;; + esac + ;; + esac + done + tmp_libs= + for deplib in $new_libs; do + case $deplib in + -L*) + case " $tmp_libs " in + *" $deplib "*) ;; + *) func_append tmp_libs " $deplib" ;; + esac + ;; + *) func_append tmp_libs " $deplib" ;; + esac + done + eval $var=\"$tmp_libs\" + done # for var + fi + + # Add Sun CC postdeps if required: + test CXX = "$tagname" && { + case $host_os in + linux*) + case `$CC -V 2>&1 | $SED 5q` in + *Sun\ C*) # Sun C++ 5.9 + func_suncc_cstd_abi + + if test no != "$suncc_use_cstd_abi"; then + func_append postdeps ' -library=Cstd -library=Crun' + fi + ;; + esac + ;; + + solaris*) + func_cc_basename "$CC" + case $func_cc_basename_result in + CC* | sunCC*) + func_suncc_cstd_abi + + if test no != "$suncc_use_cstd_abi"; then + func_append postdeps ' -library=Cstd -library=Crun' + fi + ;; + esac + ;; + esac + } + + # Last step: remove runtime libs from dependency_libs + # (they stay in deplibs) + tmp_libs= + for i in $dependency_libs; do + case " $predeps $postdeps $compiler_lib_search_path " in + *" $i "*) + i= + ;; + esac + if test -n "$i"; then + func_append tmp_libs " $i" + fi + done + dependency_libs=$tmp_libs + done # for pass + if test prog = "$linkmode"; then + dlfiles=$newdlfiles + fi + if test prog = "$linkmode" || test lib = "$linkmode"; then + dlprefiles=$newdlprefiles + fi + + case $linkmode in + oldlib) + if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then + func_warning "'-dlopen' is ignored for archives" + fi + + case " $deplibs" in + *\ -l* | *\ -L*) + func_warning "'-l' and '-L' are ignored for archives" ;; + esac + + test -n "$rpath" && \ + func_warning "'-rpath' is ignored for archives" + + test -n "$xrpath" && \ + func_warning "'-R' is ignored for archives" + + test -n "$vinfo" && \ + func_warning "'-version-info/-version-number' is ignored for archives" + + test -n "$release" && \ + func_warning "'-release' is ignored for archives" + + test -n "$export_symbols$export_symbols_regex" && \ + func_warning "'-export-symbols' is ignored for archives" + + # Now set the variables for building old libraries. + build_libtool_libs=no + oldlibs=$output + func_append objs "$old_deplibs" + ;; + + lib) + # Make sure we only generate libraries of the form 'libNAME.la'. + case $outputname in + lib*) + func_stripname 'lib' '.la' "$outputname" + name=$func_stripname_result + eval shared_ext=\"$shrext_cmds\" + eval libname=\"$libname_spec\" + ;; + *) + test no = "$module" \ + && func_fatal_help "libtool library '$output' must begin with 'lib'" + + if test no != "$need_lib_prefix"; then + # Add the "lib" prefix for modules if required + func_stripname '' '.la' "$outputname" + name=$func_stripname_result + eval shared_ext=\"$shrext_cmds\" + eval libname=\"$libname_spec\" + else + func_stripname '' '.la' "$outputname" + libname=$func_stripname_result + fi + ;; + esac + + if test -n "$objs"; then + if test pass_all != "$deplibs_check_method"; then + func_fatal_error "cannot build libtool library '$output' from non-libtool objects on this host:$objs" + else + echo + $ECHO "*** Warning: Linking the shared library $output against the non-libtool" + $ECHO "*** objects $objs is not portable!" + func_append libobjs " $objs" + fi + fi + + test no = "$dlself" \ + || func_warning "'-dlopen self' is ignored for libtool libraries" + + set dummy $rpath + shift + test 1 -lt "$#" \ + && func_warning "ignoring multiple '-rpath's for a libtool library" + + install_libdir=$1 + + oldlibs= + if test -z "$rpath"; then + if test yes = "$build_libtool_libs"; then + # Building a libtool convenience library. + # Some compilers have problems with a '.al' extension so + # convenience libraries should have the same extension an + # archive normally would. + oldlibs="$output_objdir/$libname.$libext $oldlibs" + build_libtool_libs=convenience + build_old_libs=yes + fi + + test -n "$vinfo" && \ + func_warning "'-version-info/-version-number' is ignored for convenience libraries" + + test -n "$release" && \ + func_warning "'-release' is ignored for convenience libraries" + else + + # Parse the version information argument. + save_ifs=$IFS; IFS=: + set dummy $vinfo 0 0 0 + shift + IFS=$save_ifs + + test -n "$7" && \ + func_fatal_help "too many parameters to '-version-info'" + + # convert absolute version numbers to libtool ages + # this retains compatibility with .la files and attempts + # to make the code below a bit more comprehensible + + case $vinfo_number in + yes) + number_major=$1 + number_minor=$2 + number_revision=$3 + # + # There are really only two kinds -- those that + # use the current revision as the major version + # and those that subtract age and use age as + # a minor version. But, then there is irix + # that has an extra 1 added just for fun + # + case $version_type in + # correct linux to gnu/linux during the next big refactor + darwin|freebsd-elf|linux|midnightbsd-elf|osf|windows|none) + func_arith $number_major + $number_minor + current=$func_arith_result + age=$number_minor + revision=$number_revision + ;; + freebsd-aout|qnx|sunos) + current=$number_major + revision=$number_minor + age=0 + ;; + irix|nonstopux) + func_arith $number_major + $number_minor + current=$func_arith_result + age=$number_minor + revision=$number_minor + lt_irix_increment=no + ;; + *) + func_fatal_configuration "$modename: unknown library version type '$version_type'" + ;; + esac + ;; + no) + current=$1 + revision=$2 + age=$3 + ;; + esac + + # Check that each of the things are valid numbers. + case $current in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + func_error "CURRENT '$current' must be a nonnegative integer" + func_fatal_error "'$vinfo' is not valid version information" + ;; + esac + + case $revision in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + func_error "REVISION '$revision' must be a nonnegative integer" + func_fatal_error "'$vinfo' is not valid version information" + ;; + esac + + case $age in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + func_error "AGE '$age' must be a nonnegative integer" + func_fatal_error "'$vinfo' is not valid version information" + ;; + esac + + if test "$age" -gt "$current"; then + func_error "AGE '$age' is greater than the current interface number '$current'" + func_fatal_error "'$vinfo' is not valid version information" + fi + + # Calculate the version variables. + major= + versuffix= + verstring= + case $version_type in + none) ;; + + darwin) + # Like Linux, but with the current version available in + # verstring for coding it into the library header + func_arith $current - $age + major=.$func_arith_result + versuffix=$major.$age.$revision + # Darwin ld doesn't like 0 for these options... + func_arith $current + 1 + minor_current=$func_arith_result + xlcverstring="$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision" + verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" + # On Darwin other compilers + case $CC in + nagfor*) + verstring="$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision" + ;; + *) + verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" + ;; + esac + ;; + + freebsd-aout) + major=.$current + versuffix=.$current.$revision + ;; + + freebsd-elf | midnightbsd-elf) + func_arith $current - $age + major=.$func_arith_result + versuffix=$major.$age.$revision + ;; + + irix | nonstopux) + if test no = "$lt_irix_increment"; then + func_arith $current - $age + else + func_arith $current - $age + 1 + fi + major=$func_arith_result + + case $version_type in + nonstopux) verstring_prefix=nonstopux ;; + *) verstring_prefix=sgi ;; + esac + verstring=$verstring_prefix$major.$revision + + # Add in all the interfaces that we are compatible with. + loop=$revision + while test 0 -ne "$loop"; do + func_arith $revision - $loop + iface=$func_arith_result + func_arith $loop - 1 + loop=$func_arith_result + verstring=$verstring_prefix$major.$iface:$verstring + done + + # Before this point, $major must not contain '.'. + major=.$major + versuffix=$major.$revision + ;; + + linux) # correct to gnu/linux during the next big refactor + func_arith $current - $age + major=.$func_arith_result + versuffix=$major.$age.$revision + ;; + + osf) + func_arith $current - $age + major=.$func_arith_result + versuffix=.$current.$age.$revision + verstring=$current.$age.$revision + + # Add in all the interfaces that we are compatible with. + loop=$age + while test 0 -ne "$loop"; do + func_arith $current - $loop + iface=$func_arith_result + func_arith $loop - 1 + loop=$func_arith_result + verstring=$verstring:$iface.0 + done + + # Make executables depend on our current version. + func_append verstring ":$current.0" + ;; + + qnx) + major=.$current + versuffix=.$current + ;; + + sco) + major=.$current + versuffix=.$current + ;; + + sunos) + major=.$current + versuffix=.$current.$revision + ;; + + windows) + # Use '-' rather than '.', since we only want one + # extension on DOS 8.3 file systems. + func_arith $current - $age + major=$func_arith_result + versuffix=-$major + ;; + + *) + func_fatal_configuration "unknown library version type '$version_type'" + ;; + esac + + # Clear the version info if we defaulted, and they specified a release. + if test -z "$vinfo" && test -n "$release"; then + major= + case $version_type in + darwin) + # we can't check for "0.0" in archive_cmds due to quoting + # problems, so we reset it completely + verstring= + ;; + *) + verstring=0.0 + ;; + esac + if test no = "$need_version"; then + versuffix= + else + versuffix=.0.0 + fi + fi + + # Remove version info from name if versioning should be avoided + if test yes,no = "$avoid_version,$need_version"; then + major= + versuffix= + verstring= + fi + + # Check to see if the archive will have undefined symbols. + if test yes = "$allow_undefined"; then + if test unsupported = "$allow_undefined_flag"; then + if test yes = "$build_old_libs"; then + func_warning "undefined symbols not allowed in $host shared libraries; building static only" + build_libtool_libs=no + else + func_fatal_error "can't build $host shared library unless -no-undefined is specified" + fi + fi + else + # Don't allow undefined symbols. + allow_undefined_flag=$no_undefined_flag + fi + + fi + + func_generate_dlsyms "$libname" "$libname" : + func_append libobjs " $symfileobj" + test " " = "$libobjs" && libobjs= + + if test relink != "$opt_mode"; then + # Remove our outputs, but don't remove object files since they + # may have been created when compiling PIC objects. + removelist= + tempremovelist=`$ECHO "$output_objdir/*"` + for p in $tempremovelist; do + case $p in + *.$objext | *.gcno) + ;; + $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/$libname$release.*) + if test -n "$precious_files_regex"; then + if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 + then + continue + fi + fi + func_append removelist " $p" + ;; + *) ;; + esac + done + test -n "$removelist" && \ + func_show_eval "${RM}r \$removelist" + fi + + # Now set the variables for building old libraries. + if test yes = "$build_old_libs" && test convenience != "$build_libtool_libs"; then + func_append oldlibs " $output_objdir/$libname.$libext" + + # Transform .lo files to .o files. + oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.$libext$/d; $lo2o" | $NL2SP` + fi + + # Eliminate all temporary directories. + #for path in $notinst_path; do + # lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"` + # deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"` + # dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"` + #done + + if test -n "$xrpath"; then + # If the user specified any rpath flags, then add them. + temp_xrpath= + for libdir in $xrpath; do + func_replace_sysroot "$libdir" + func_append temp_xrpath " -R$func_replace_sysroot_result" + case "$finalize_rpath " in + *" $libdir "*) ;; + *) func_append finalize_rpath " $libdir" ;; + esac + done + if test yes != "$hardcode_into_libs" || test yes = "$build_old_libs"; then + dependency_libs="$temp_xrpath $dependency_libs" + fi + fi + + # Make sure dlfiles contains only unique files that won't be dlpreopened + old_dlfiles=$dlfiles + dlfiles= + for lib in $old_dlfiles; do + case " $dlprefiles $dlfiles " in + *" $lib "*) ;; + *) func_append dlfiles " $lib" ;; + esac + done + + # Make sure dlprefiles contains only unique files + old_dlprefiles=$dlprefiles + dlprefiles= + for lib in $old_dlprefiles; do + case "$dlprefiles " in + *" $lib "*) ;; + *) func_append dlprefiles " $lib" ;; + esac + done + + if test yes = "$build_libtool_libs"; then + if test -n "$rpath"; then + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*) + # these systems don't actually have a c library (as such)! + ;; + *-*-rhapsody* | *-*-darwin1.[012]) + # Rhapsody C library is in the System framework + func_append deplibs " System.ltframework" + ;; + *-*-netbsd*) + # Don't link with libc until the a.out ld.so is fixed. + ;; + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-midnightbsd*) + # Do not include libc due to us having libc/libc_r. + ;; + *-*-sco3.2v5* | *-*-sco5v6*) + # Causes problems with __ctype + ;; + *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) + # Compiler inserts libc in the correct place for threads to work + ;; + *) + # Add libc to deplibs on all other systems if necessary. + if test yes = "$build_libtool_need_lc"; then + func_append deplibs " -lc" + fi + ;; + esac + fi + + # Transform deplibs into only deplibs that can be linked in shared. + name_save=$name + libname_save=$libname + release_save=$release + versuffix_save=$versuffix + major_save=$major + # I'm not sure if I'm treating the release correctly. I think + # release should show up in the -l (ie -lgmp5) so we don't want to + # add it in twice. Is that correct? + release= + versuffix= + major= + newdeplibs= + droppeddeps=no + case $deplibs_check_method in + pass_all) + # Don't check for shared/static. Everything works. + # This might be a little naive. We might want to check + # whether the library exists or not. But this is on + # osf3 & osf4 and I'm not really sure... Just + # implementing what was already the behavior. + newdeplibs=$deplibs + ;; + test_compile) + # This code stresses the "libraries are programs" paradigm to its + # limits. Maybe even breaks it. We compile a program, linking it + # against the deplibs as a proxy for the library. Then we can check + # whether they linked in statically or dynamically with ldd. + $opt_dry_run || $RM conftest.c + cat > conftest.c </dev/null` + $nocaseglob + else + potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null` + fi + for potent_lib in $potential_libs; do + # Follow soft links. + if ls -lLd "$potent_lib" 2>/dev/null | + $GREP " -> " >/dev/null; then + continue + fi + # The statement above tries to avoid entering an + # endless loop below, in case of cyclic links. + # We might still enter an endless loop, since a link + # loop can be closed while we follow links, + # but so what? + potlib=$potent_lib + while test -h "$potlib" 2>/dev/null; do + potliblink=`ls -ld $potlib | $SED 's/.* -> //'` + case $potliblink in + [\\/]* | [A-Za-z]:[\\/]*) potlib=$potliblink;; + *) potlib=`$ECHO "$potlib" | $SED 's|[^/]*$||'`"$potliblink";; + esac + done + if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | + $SED -e 10q | + $EGREP "$file_magic_regex" > /dev/null; then + func_append newdeplibs " $a_deplib" + a_deplib= + break 2 + fi + done + done + fi + if test -n "$a_deplib"; then + droppeddeps=yes + echo + $ECHO "*** Warning: linker path does not have real file for library $a_deplib." + echo "*** I have the capability to make that library automatically link in when" + echo "*** you link to this library. But I can only do this if you have a" + echo "*** shared version of the library, which you do not appear to have" + echo "*** because I did check the linker path looking for a file starting" + if test -z "$potlib"; then + $ECHO "*** with $libname but no candidates were found. (...for file magic test)" + else + $ECHO "*** with $libname and none of the candidates passed a file format test" + $ECHO "*** using a file magic. Last file checked: $potlib" + fi + fi + ;; + *) + # Add a -L argument. + func_append newdeplibs " $a_deplib" + ;; + esac + done # Gone through all deplibs. + ;; + match_pattern*) + set dummy $deplibs_check_method; shift + match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` + for a_deplib in $deplibs; do + case $a_deplib in + -l*) + func_stripname -l '' "$a_deplib" + name=$func_stripname_result + if test yes = "$allow_libtool_libs_with_static_runtimes"; then + case " $predeps $postdeps " in + *" $a_deplib "*) + func_append newdeplibs " $a_deplib" + a_deplib= + ;; + esac + fi + if test -n "$a_deplib"; then + libname=`eval "\\$ECHO \"$libname_spec\""` + for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do + potential_libs=`ls $i/$libname[.-]* 2>/dev/null` + for potent_lib in $potential_libs; do + potlib=$potent_lib # see symlink-check above in file_magic test + if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \ + $EGREP "$match_pattern_regex" > /dev/null; then + func_append newdeplibs " $a_deplib" + a_deplib= + break 2 + fi + done + done + fi + if test -n "$a_deplib"; then + droppeddeps=yes + echo + $ECHO "*** Warning: linker path does not have real file for library $a_deplib." + echo "*** I have the capability to make that library automatically link in when" + echo "*** you link to this library. But I can only do this if you have a" + echo "*** shared version of the library, which you do not appear to have" + echo "*** because I did check the linker path looking for a file starting" + if test -z "$potlib"; then + $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" + else + $ECHO "*** with $libname and none of the candidates passed a file format test" + $ECHO "*** using a regex pattern. Last file checked: $potlib" + fi + fi + ;; + *) + # Add a -L argument. + func_append newdeplibs " $a_deplib" + ;; + esac + done # Gone through all deplibs. + ;; + none | unknown | *) + newdeplibs= + tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'` + if test yes = "$allow_libtool_libs_with_static_runtimes"; then + for i in $predeps $postdeps; do + # can't use Xsed below, because $i might contain '/' + tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s|$i||"` + done + fi + case $tmp_deplibs in + *[!\ \ ]*) + echo + if test none = "$deplibs_check_method"; then + echo "*** Warning: inter-library dependencies are not supported in this platform." + else + echo "*** Warning: inter-library dependencies are not known to be supported." + fi + echo "*** All declared inter-library dependencies are being dropped." + droppeddeps=yes + ;; + esac + ;; + esac + versuffix=$versuffix_save + major=$major_save + release=$release_save + libname=$libname_save + name=$name_save + + case $host in + *-*-rhapsody* | *-*-darwin1.[012]) + # On Rhapsody replace the C library with the System framework + newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'` + ;; + esac + + if test yes = "$droppeddeps"; then + if test yes = "$module"; then + echo + echo "*** Warning: libtool could not satisfy all declared inter-library" + $ECHO "*** dependencies of module $libname. Therefore, libtool will create" + echo "*** a static module, that should work as long as the dlopening" + echo "*** application is linked with the -dlopen flag." + if test -z "$global_symbol_pipe"; then + echo + echo "*** However, this would only work if libtool was able to extract symbol" + echo "*** lists from a program, using 'nm' or equivalent, but libtool could" + echo "*** not find such a program. So, this module is probably useless." + echo "*** 'nm' from GNU binutils and a full rebuild may help." + fi + if test no = "$build_old_libs"; then + oldlibs=$output_objdir/$libname.$libext + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + else + echo "*** The inter-library dependencies that have been dropped here will be" + echo "*** automatically added whenever a program is linked with this library" + echo "*** or is declared to -dlopen it." + + if test no = "$allow_undefined"; then + echo + echo "*** Since this library must not contain undefined symbols," + echo "*** because either the platform does not support them or" + echo "*** it was explicitly requested with -no-undefined," + echo "*** libtool will only create a static version of it." + if test no = "$build_old_libs"; then + oldlibs=$output_objdir/$libname.$libext + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + fi + fi + fi + # Done checking deplibs! + deplibs=$newdeplibs + fi + # Time to change all our "foo.ltframework" stuff back to "-framework foo" + case $host in + *-*-darwin*) + newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + ;; + esac + + # move library search paths that coincide with paths to not yet + # installed libraries to the beginning of the library search list + new_libs= + for path in $notinst_path; do + case " $new_libs " in + *" -L$path/$objdir "*) ;; + *) + case " $deplibs " in + *" -L$path/$objdir "*) + func_append new_libs " -L$path/$objdir" ;; + esac + ;; + esac + done + for deplib in $deplibs; do + case $deplib in + -L*) + case " $new_libs " in + *" $deplib "*) ;; + *) func_append new_libs " $deplib" ;; + esac + ;; + *) func_append new_libs " $deplib" ;; + esac + done + deplibs=$new_libs + + # All the library-specific variables (install_libdir is set above). + library_names= + old_library= + dlname= + + # Test again, we may have decided not to build it any more + if test yes = "$build_libtool_libs"; then + # Remove $wl instances when linking with ld. + # FIXME: should test the right _cmds variable. + case $archive_cmds in + *\$LD\ *) wl= ;; + esac + if test yes = "$hardcode_into_libs"; then + # Hardcode the library paths + hardcode_libdirs= + dep_rpath= + rpath=$finalize_rpath + test relink = "$opt_mode" || rpath=$compile_rpath$rpath + for libdir in $rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + func_replace_sysroot "$libdir" + libdir=$func_replace_sysroot_result + if test -z "$hardcode_libdirs"; then + hardcode_libdirs=$libdir + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + func_append dep_rpath " $flag" + fi + elif test -n "$runpath_var"; then + case "$perm_rpath " in + *" $libdir "*) ;; + *) func_append perm_rpath " $libdir" ;; + esac + fi + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir=$hardcode_libdirs + eval "dep_rpath=\"$hardcode_libdir_flag_spec\"" + fi + if test -n "$runpath_var" && test -n "$perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $perm_rpath; do + func_append rpath "$dir:" + done + eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" + fi + test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" + fi + + shlibpath=$finalize_shlibpath + test relink = "$opt_mode" || shlibpath=$compile_shlibpath$shlibpath + if test -n "$shlibpath"; then + eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" + fi + + # Get the real and link names of the library. + eval shared_ext=\"$shrext_cmds\" + eval library_names=\"$library_names_spec\" + set dummy $library_names + shift + realname=$1 + shift + + if test -n "$soname_spec"; then + eval soname=\"$soname_spec\" + else + soname=$realname + fi + if test -z "$dlname"; then + dlname=$soname + fi + + lib=$output_objdir/$realname + linknames= + for link + do + func_append linknames " $link" + done + + # Use standard objects if they are pic + test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP` + test "X$libobjs" = "X " && libobjs= + + delfiles= + if test -n "$export_symbols" && test -n "$include_expsyms"; then + $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" + export_symbols=$output_objdir/$libname.uexp + func_append delfiles " $export_symbols" + fi + + orig_export_symbols= + case $host_os in + cygwin* | mingw* | cegcc*) + if test -n "$export_symbols" && test -z "$export_symbols_regex"; then + # exporting using user supplied symfile + func_dll_def_p "$export_symbols" || { + # and it's NOT already a .def file. Must figure out + # which of the given symbols are data symbols and tag + # them as such. So, trigger use of export_symbols_cmds. + # export_symbols gets reassigned inside the "prepare + # the list of exported symbols" if statement, so the + # include_expsyms logic still works. + orig_export_symbols=$export_symbols + export_symbols= + always_export_symbols=yes + } + fi + ;; + esac + + # Prepare the list of exported symbols + if test -z "$export_symbols"; then + if test yes = "$always_export_symbols" || test -n "$export_symbols_regex"; then + func_verbose "generating symbol list for '$libname.la'" + export_symbols=$output_objdir/$libname.exp + $opt_dry_run || $RM $export_symbols + cmds=$export_symbols_cmds + save_ifs=$IFS; IFS='~' + for cmd1 in $cmds; do + IFS=$save_ifs + # Take the normal branch if the nm_file_list_spec branch + # doesn't work or if tool conversion is not needed. + case $nm_file_list_spec~$to_tool_file_cmd in + *~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*) + try_normal_branch=yes + eval cmd=\"$cmd1\" + func_len " $cmd" + len=$func_len_result + ;; + *) + try_normal_branch=no + ;; + esac + if test yes = "$try_normal_branch" \ + && { test "$len" -lt "$max_cmd_len" \ + || test "$max_cmd_len" -le -1; } + then + func_show_eval "$cmd" 'exit $?' + skipped_export=false + elif test -n "$nm_file_list_spec"; then + func_basename "$output" + output_la=$func_basename_result + save_libobjs=$libobjs + save_output=$output + output=$output_objdir/$output_la.nm + func_to_tool_file "$output" + libobjs=$nm_file_list_spec$func_to_tool_file_result + func_append delfiles " $output" + func_verbose "creating $NM input file list: $output" + for obj in $save_libobjs; do + func_to_tool_file "$obj" + $ECHO "$func_to_tool_file_result" + done > "$output" + eval cmd=\"$cmd1\" + func_show_eval "$cmd" 'exit $?' + output=$save_output + libobjs=$save_libobjs + skipped_export=false + else + # The command line is too long to execute in one step. + func_verbose "using reloadable object file for export list..." + skipped_export=: + # Break out early, otherwise skipped_export may be + # set to false by a later but shorter cmd. + break + fi + done + IFS=$save_ifs + if test -n "$export_symbols_regex" && test : != "$skipped_export"; then + func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' + func_show_eval '$MV "${export_symbols}T" "$export_symbols"' + fi + fi + fi + + if test -n "$export_symbols" && test -n "$include_expsyms"; then + tmp_export_symbols=$export_symbols + test -n "$orig_export_symbols" && tmp_export_symbols=$orig_export_symbols + $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' + fi + + if test : != "$skipped_export" && test -n "$orig_export_symbols"; then + # The given exports_symbols file has to be filtered, so filter it. + func_verbose "filter symbol list for '$libname.la' to tag DATA exports" + # FIXME: $output_objdir/$libname.filter potentially contains lots of + # 's' commands, which not all seds can handle. GNU sed should be fine + # though. Also, the filter scales superlinearly with the number of + # global variables. join(1) would be nice here, but unfortunately + # isn't a blessed tool. + $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter + func_append delfiles " $export_symbols $output_objdir/$libname.filter" + export_symbols=$output_objdir/$libname.def + $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols + fi + + tmp_deplibs= + for test_deplib in $deplibs; do + case " $convenience " in + *" $test_deplib "*) ;; + *) + func_append tmp_deplibs " $test_deplib" + ;; + esac + done + deplibs=$tmp_deplibs + + if test -n "$convenience"; then + if test -n "$whole_archive_flag_spec" && + test yes = "$compiler_needs_object" && + test -z "$libobjs"; then + # extract the archives, so we have objects to list. + # TODO: could optimize this to just extract one archive. + whole_archive_flag_spec= + fi + if test -n "$whole_archive_flag_spec"; then + save_libobjs=$libobjs + eval libobjs=\"\$libobjs $whole_archive_flag_spec\" + test "X$libobjs" = "X " && libobjs= + else + gentop=$output_objdir/${outputname}x + func_append generated " $gentop" + + func_extract_archives $gentop $convenience + func_append libobjs " $func_extract_archives_result" + test "X$libobjs" = "X " && libobjs= + fi + fi + + if test yes = "$thread_safe" && test -n "$thread_safe_flag_spec"; then + eval flag=\"$thread_safe_flag_spec\" + func_append linker_flags " $flag" + fi + + # Make a backup of the uninstalled library when relinking + if test relink = "$opt_mode"; then + $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? + fi + + # Do each of the archive commands. + if test yes = "$module" && test -n "$module_cmds"; then + if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then + eval test_cmds=\"$module_expsym_cmds\" + cmds=$module_expsym_cmds + else + eval test_cmds=\"$module_cmds\" + cmds=$module_cmds + fi + else + if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then + eval test_cmds=\"$archive_expsym_cmds\" + cmds=$archive_expsym_cmds + else + eval test_cmds=\"$archive_cmds\" + cmds=$archive_cmds + fi + fi + + if test : != "$skipped_export" && + func_len " $test_cmds" && + len=$func_len_result && + test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then + : + else + # The command line is too long to link in one step, link piecewise + # or, if using GNU ld and skipped_export is not :, use a linker + # script. + + # Save the value of $output and $libobjs because we want to + # use them later. If we have whole_archive_flag_spec, we + # want to use save_libobjs as it was before + # whole_archive_flag_spec was expanded, because we can't + # assume the linker understands whole_archive_flag_spec. + # This may have to be revisited, in case too many + # convenience libraries get linked in and end up exceeding + # the spec. + if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then + save_libobjs=$libobjs + fi + save_output=$output + func_basename "$output" + output_la=$func_basename_result + + # Clear the reloadable object creation command queue and + # initialize k to one. + test_cmds= + concat_cmds= + objlist= + last_robj= + k=1 + + if test -n "$save_libobjs" && test : != "$skipped_export" && test yes = "$with_gnu_ld"; then + output=$output_objdir/$output_la.lnkscript + func_verbose "creating GNU ld script: $output" + echo 'INPUT (' > $output + for obj in $save_libobjs + do + func_to_tool_file "$obj" + $ECHO "$func_to_tool_file_result" >> $output + done + echo ')' >> $output + func_append delfiles " $output" + func_to_tool_file "$output" + output=$func_to_tool_file_result + elif test -n "$save_libobjs" && test : != "$skipped_export" && test -n "$file_list_spec"; then + output=$output_objdir/$output_la.lnk + func_verbose "creating linker input file list: $output" + : > $output + set x $save_libobjs + shift + firstobj= + if test yes = "$compiler_needs_object"; then + firstobj="$1 " + shift + fi + for obj + do + func_to_tool_file "$obj" + $ECHO "$func_to_tool_file_result" >> $output + done + func_append delfiles " $output" + func_to_tool_file "$output" + output=$firstobj\"$file_list_spec$func_to_tool_file_result\" + else + if test -n "$save_libobjs"; then + func_verbose "creating reloadable object files..." + output=$output_objdir/$output_la-$k.$objext + eval test_cmds=\"$reload_cmds\" + func_len " $test_cmds" + len0=$func_len_result + len=$len0 + + # Loop over the list of objects to be linked. + for obj in $save_libobjs + do + func_len " $obj" + func_arith $len + $func_len_result + len=$func_arith_result + if test -z "$objlist" || + test "$len" -lt "$max_cmd_len"; then + func_append objlist " $obj" + else + # The command $test_cmds is almost too long, add a + # command to the queue. + if test 1 -eq "$k"; then + # The first file doesn't have a previous command to add. + reload_objs=$objlist + eval concat_cmds=\"$reload_cmds\" + else + # All subsequent reloadable object files will link in + # the last one created. + reload_objs="$objlist $last_robj" + eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\" + fi + last_robj=$output_objdir/$output_la-$k.$objext + func_arith $k + 1 + k=$func_arith_result + output=$output_objdir/$output_la-$k.$objext + objlist=" $obj" + func_len " $last_robj" + func_arith $len0 + $func_len_result + len=$func_arith_result + fi + done + # Handle the remaining objects by creating one last + # reloadable object file. All subsequent reloadable object + # files will link in the last one created. + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + reload_objs="$objlist $last_robj" + eval concat_cmds=\"\$concat_cmds$reload_cmds\" + if test -n "$last_robj"; then + eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" + fi + func_append delfiles " $output" + + else + output= + fi + + ${skipped_export-false} && { + func_verbose "generating symbol list for '$libname.la'" + export_symbols=$output_objdir/$libname.exp + $opt_dry_run || $RM $export_symbols + libobjs=$output + # Append the command to create the export file. + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" + if test -n "$last_robj"; then + eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" + fi + } + + test -n "$save_libobjs" && + func_verbose "creating a temporary reloadable object file: $output" + + # Loop through the commands generated above and execute them. + save_ifs=$IFS; IFS='~' + for cmd in $concat_cmds; do + IFS=$save_ifs + $opt_quiet || { + func_quote_arg expand,pretty "$cmd" + eval "func_echo $func_quote_arg_result" + } + $opt_dry_run || eval "$cmd" || { + lt_exit=$? + + # Restore the uninstalled library and exit + if test relink = "$opt_mode"; then + ( cd "$output_objdir" && \ + $RM "${realname}T" && \ + $MV "${realname}U" "$realname" ) + fi + + exit $lt_exit + } + done + IFS=$save_ifs + + if test -n "$export_symbols_regex" && ${skipped_export-false}; then + func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' + func_show_eval '$MV "${export_symbols}T" "$export_symbols"' + fi + fi + + ${skipped_export-false} && { + if test -n "$export_symbols" && test -n "$include_expsyms"; then + tmp_export_symbols=$export_symbols + test -n "$orig_export_symbols" && tmp_export_symbols=$orig_export_symbols + $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' + fi + + if test -n "$orig_export_symbols"; then + # The given exports_symbols file has to be filtered, so filter it. + func_verbose "filter symbol list for '$libname.la' to tag DATA exports" + # FIXME: $output_objdir/$libname.filter potentially contains lots of + # 's' commands, which not all seds can handle. GNU sed should be fine + # though. Also, the filter scales superlinearly with the number of + # global variables. join(1) would be nice here, but unfortunately + # isn't a blessed tool. + $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter + func_append delfiles " $export_symbols $output_objdir/$libname.filter" + export_symbols=$output_objdir/$libname.def + $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols + fi + } + + libobjs=$output + # Restore the value of output. + output=$save_output + + if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then + eval libobjs=\"\$libobjs $whole_archive_flag_spec\" + test "X$libobjs" = "X " && libobjs= + fi + # Expand the library linking commands again to reset the + # value of $libobjs for piecewise linking. + + # Do each of the archive commands. + if test yes = "$module" && test -n "$module_cmds"; then + if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then + cmds=$module_expsym_cmds + else + cmds=$module_cmds + fi + else + if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then + cmds=$archive_expsym_cmds + else + cmds=$archive_cmds + fi + fi + fi + + if test -n "$delfiles"; then + # Append the command to remove temporary files to $cmds. + eval cmds=\"\$cmds~\$RM $delfiles\" + fi + + # Add any objects from preloaded convenience libraries + if test -n "$dlprefiles"; then + gentop=$output_objdir/${outputname}x + func_append generated " $gentop" + + func_extract_archives $gentop $dlprefiles + func_append libobjs " $func_extract_archives_result" + test "X$libobjs" = "X " && libobjs= + fi + + save_ifs=$IFS; IFS='~' + for cmd in $cmds; do + IFS=$sp$nl + eval cmd=\"$cmd\" + IFS=$save_ifs + $opt_quiet || { + func_quote_arg expand,pretty "$cmd" + eval "func_echo $func_quote_arg_result" + } + $opt_dry_run || eval "$cmd" || { + lt_exit=$? + + # Restore the uninstalled library and exit + if test relink = "$opt_mode"; then + ( cd "$output_objdir" && \ + $RM "${realname}T" && \ + $MV "${realname}U" "$realname" ) + fi + + exit $lt_exit + } + done + IFS=$save_ifs + + # Restore the uninstalled library and exit + if test relink = "$opt_mode"; then + $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? + + if test -n "$convenience"; then + if test -z "$whole_archive_flag_spec"; then + func_show_eval '${RM}r "$gentop"' + fi + fi + + exit $EXIT_SUCCESS + fi + + # Create links to the real library. + for linkname in $linknames; do + if test "$realname" != "$linkname"; then + func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' + fi + done + + # If -module or -export-dynamic was specified, set the dlname. + if test yes = "$module" || test yes = "$export_dynamic"; then + # On all known operating systems, these are identical. + dlname=$soname + fi + fi + ;; + + obj) + if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then + func_warning "'-dlopen' is ignored for objects" + fi + + case " $deplibs" in + *\ -l* | *\ -L*) + func_warning "'-l' and '-L' are ignored for objects" ;; + esac + + test -n "$rpath" && \ + func_warning "'-rpath' is ignored for objects" + + test -n "$xrpath" && \ + func_warning "'-R' is ignored for objects" + + test -n "$vinfo" && \ + func_warning "'-version-info' is ignored for objects" + + test -n "$release" && \ + func_warning "'-release' is ignored for objects" + + case $output in + *.lo) + test -n "$objs$old_deplibs" && \ + func_fatal_error "cannot build library object '$output' from non-libtool objects" + + libobj=$output + func_lo2o "$libobj" + obj=$func_lo2o_result + ;; + *) + libobj= + obj=$output + ;; + esac + + # Delete the old objects. + $opt_dry_run || $RM $obj $libobj + + # Objects from convenience libraries. This assumes + # single-version convenience libraries. Whenever we create + # different ones for PIC/non-PIC, this we'll have to duplicate + # the extraction. + reload_conv_objs= + gentop= + # if reload_cmds runs $LD directly, get rid of -Wl from + # whole_archive_flag_spec and hope we can get by with turning comma + # into space. + case $reload_cmds in + *\$LD[\ \$]*) wl= ;; + esac + if test -n "$convenience"; then + if test -n "$whole_archive_flag_spec"; then + eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" + test -n "$wl" || tmp_whole_archive_flags=`$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'` + reload_conv_objs=$reload_objs\ $tmp_whole_archive_flags + else + gentop=$output_objdir/${obj}x + func_append generated " $gentop" + + func_extract_archives $gentop $convenience + reload_conv_objs="$reload_objs $func_extract_archives_result" + fi + fi + + # If we're not building shared, we need to use non_pic_objs + test yes = "$build_libtool_libs" || libobjs=$non_pic_objects + + # Create the old-style object. + reload_objs=$objs$old_deplibs' '`$ECHO "$libobjs" | $SP2NL | $SED "/\.$libext$/d; /\.lib$/d; $lo2o" | $NL2SP`' '$reload_conv_objs + + output=$obj + func_execute_cmds "$reload_cmds" 'exit $?' + + # Exit if we aren't doing a library object file. + if test -z "$libobj"; then + if test -n "$gentop"; then + func_show_eval '${RM}r "$gentop"' + fi + + exit $EXIT_SUCCESS + fi + + test yes = "$build_libtool_libs" || { + if test -n "$gentop"; then + func_show_eval '${RM}r "$gentop"' + fi + + # Create an invalid libtool object if no PIC, so that we don't + # accidentally link it into a program. + # $show "echo timestamp > $libobj" + # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? + exit $EXIT_SUCCESS + } + + if test -n "$pic_flag" || test default != "$pic_mode"; then + # Only do commands if we really have different PIC objects. + reload_objs="$libobjs $reload_conv_objs" + output=$libobj + func_execute_cmds "$reload_cmds" 'exit $?' + fi + + if test -n "$gentop"; then + func_show_eval '${RM}r "$gentop"' + fi + + exit $EXIT_SUCCESS + ;; + + prog) + case $host in + *cygwin*) func_stripname '' '.exe' "$output" + output=$func_stripname_result.exe;; + esac + test -n "$vinfo" && \ + func_warning "'-version-info' is ignored for programs" + + test -n "$release" && \ + func_warning "'-release' is ignored for programs" + + $preload \ + && test unknown,unknown,unknown = "$dlopen_support,$dlopen_self,$dlopen_self_static" \ + && func_warning "'LT_INIT([dlopen])' not used. Assuming no dlopen support." + + case $host in + *-*-rhapsody* | *-*-darwin1.[012]) + # On Rhapsody replace the C library is the System framework + compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'` + finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'` + ;; + esac + + case $host in + *-*-darwin*) + # Don't allow lazy linking, it breaks C++ global constructors + # But is supposedly fixed on 10.4 or later (yay!). + if test CXX = "$tagname"; then + case ${MACOSX_DEPLOYMENT_TARGET-10.0} in + 10.[0123]) + func_append compile_command " $wl-bind_at_load" + func_append finalize_command " $wl-bind_at_load" + ;; + esac + fi + # Time to change all our "foo.ltframework" stuff back to "-framework foo" + compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + ;; + esac + + + # move library search paths that coincide with paths to not yet + # installed libraries to the beginning of the library search list + new_libs= + for path in $notinst_path; do + case " $new_libs " in + *" -L$path/$objdir "*) ;; + *) + case " $compile_deplibs " in + *" -L$path/$objdir "*) + func_append new_libs " -L$path/$objdir" ;; + esac + ;; + esac + done + for deplib in $compile_deplibs; do + case $deplib in + -L*) + case " $new_libs " in + *" $deplib "*) ;; + *) func_append new_libs " $deplib" ;; + esac + ;; + *) func_append new_libs " $deplib" ;; + esac + done + compile_deplibs=$new_libs + + + func_append compile_command " $compile_deplibs" + func_append finalize_command " $finalize_deplibs" + + if test -n "$rpath$xrpath"; then + # If the user specified any rpath flags, then add them. + for libdir in $rpath $xrpath; do + # This is the magic to use -rpath. + case "$finalize_rpath " in + *" $libdir "*) ;; + *) func_append finalize_rpath " $libdir" ;; + esac + done + fi + + # Now hardcode the library paths + rpath= + hardcode_libdirs= + for libdir in $compile_rpath $finalize_rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs=$libdir + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + func_append rpath " $flag" + fi + elif test -n "$runpath_var"; then + case "$perm_rpath " in + *" $libdir "*) ;; + *) func_append perm_rpath " $libdir" ;; + esac + fi + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + testbindir=`$ECHO "$libdir" | $SED -e 's*/lib$*/bin*'` + case :$dllsearchpath: in + *":$libdir:"*) ;; + ::) dllsearchpath=$libdir;; + *) func_append dllsearchpath ":$libdir";; + esac + case :$dllsearchpath: in + *":$testbindir:"*) ;; + ::) dllsearchpath=$testbindir;; + *) func_append dllsearchpath ":$testbindir";; + esac + ;; + esac + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir=$hardcode_libdirs + eval rpath=\" $hardcode_libdir_flag_spec\" + fi + compile_rpath=$rpath + + rpath= + hardcode_libdirs= + for libdir in $finalize_rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs=$libdir + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + func_append rpath " $flag" + fi + elif test -n "$runpath_var"; then + case "$finalize_perm_rpath " in + *" $libdir "*) ;; + *) func_append finalize_perm_rpath " $libdir" ;; + esac + fi + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir=$hardcode_libdirs + eval rpath=\" $hardcode_libdir_flag_spec\" + fi + finalize_rpath=$rpath + + if test -n "$libobjs" && test yes = "$build_old_libs"; then + # Transform all the library objects into standard objects. + compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP` + finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP` + fi + + func_generate_dlsyms "$outputname" "@PROGRAM@" false + + # template prelinking step + if test -n "$prelink_cmds"; then + func_execute_cmds "$prelink_cmds" 'exit $?' + fi + + wrappers_required=: + case $host in + *cegcc* | *mingw32ce*) + # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway. + wrappers_required=false + ;; + *cygwin* | *mingw* ) + test yes = "$build_libtool_libs" || wrappers_required=false + ;; + *) + if test no = "$need_relink" || test yes != "$build_libtool_libs"; then + wrappers_required=false + fi + ;; + esac + $wrappers_required || { + # Replace the output file specification. + compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'` + link_command=$compile_command$compile_rpath + + # We have no uninstalled library dependencies, so finalize right now. + exit_status=0 + func_show_eval "$link_command" 'exit_status=$?' + + if test -n "$postlink_cmds"; then + func_to_tool_file "$output" + postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` + func_execute_cmds "$postlink_cmds" 'exit $?' + fi + + # Delete the generated files. + if test -f "$output_objdir/${outputname}S.$objext"; then + func_show_eval '$RM "$output_objdir/${outputname}S.$objext"' + fi + + exit $exit_status + } + + if test -n "$compile_shlibpath$finalize_shlibpath"; then + compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" + fi + if test -n "$finalize_shlibpath"; then + finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" + fi + + compile_var= + finalize_var= + if test -n "$runpath_var"; then + if test -n "$perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $perm_rpath; do + func_append rpath "$dir:" + done + compile_var="$runpath_var=\"$rpath\$$runpath_var\" " + fi + if test -n "$finalize_perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $finalize_perm_rpath; do + func_append rpath "$dir:" + done + finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " + fi + fi + + if test yes = "$no_install"; then + # We don't need to create a wrapper script. + link_command=$compile_var$compile_command$compile_rpath + # Replace the output file specification. + link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'` + # Delete the old output file. + $opt_dry_run || $RM $output + # Link the executable and exit + func_show_eval "$link_command" 'exit $?' + + if test -n "$postlink_cmds"; then + func_to_tool_file "$output" + postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` + func_execute_cmds "$postlink_cmds" 'exit $?' + fi + + exit $EXIT_SUCCESS + fi + + case $hardcode_action,$fast_install in + relink,*) + # Fast installation is not supported + link_command=$compile_var$compile_command$compile_rpath + relink_command=$finalize_var$finalize_command$finalize_rpath + + func_warning "this platform does not like uninstalled shared libraries" + func_warning "'$output' will be relinked during installation" + ;; + *,yes) + link_command=$finalize_var$compile_command$finalize_rpath + relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'` + ;; + *,no) + link_command=$compile_var$compile_command$compile_rpath + relink_command=$finalize_var$finalize_command$finalize_rpath + ;; + *,needless) + link_command=$finalize_var$compile_command$finalize_rpath + relink_command= + ;; + esac + + # Replace the output file specification. + link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` + + # Delete the old output files. + $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname + + func_show_eval "$link_command" 'exit $?' + + if test -n "$postlink_cmds"; then + func_to_tool_file "$output_objdir/$outputname" + postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` + func_execute_cmds "$postlink_cmds" 'exit $?' + fi + + # Now create the wrapper script. + func_verbose "creating $output" + + # Quote the relink command for shipping. + if test -n "$relink_command"; then + # Preserve any variables that may affect compiler behavior + for var in $variables_saved_for_relink; do + if eval test -z \"\${$var+set}\"; then + relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" + elif eval var_value=\$$var; test -z "$var_value"; then + relink_command="$var=; export $var; $relink_command" + else + func_quote_arg pretty "$var_value" + relink_command="$var=$func_quote_arg_result; export $var; $relink_command" + fi + done + func_quote eval cd "`pwd`" + func_quote_arg pretty,unquoted "($func_quote_result; $relink_command)" + relink_command=$func_quote_arg_unquoted_result + fi + + # Only actually do things if not in dry run mode. + $opt_dry_run || { + # win32 will think the script is a binary if it has + # a .exe suffix, so we strip it off here. + case $output in + *.exe) func_stripname '' '.exe' "$output" + output=$func_stripname_result ;; + esac + # test for cygwin because mv fails w/o .exe extensions + case $host in + *cygwin*) + exeext=.exe + func_stripname '' '.exe' "$outputname" + outputname=$func_stripname_result ;; + *) exeext= ;; + esac + case $host in + *cygwin* | *mingw* ) + func_dirname_and_basename "$output" "" "." + output_name=$func_basename_result + output_path=$func_dirname_result + cwrappersource=$output_path/$objdir/lt-$output_name.c + cwrapper=$output_path/$output_name.exe + $RM $cwrappersource $cwrapper + trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 + + func_emit_cwrapperexe_src > $cwrappersource + + # The wrapper executable is built using the $host compiler, + # because it contains $host paths and files. If cross- + # compiling, it, like the target executable, must be + # executed on the $host or under an emulation environment. + $opt_dry_run || { + $LTCC $LTCFLAGS -o $cwrapper $cwrappersource + $STRIP $cwrapper + } + + # Now, create the wrapper script for func_source use: + func_ltwrapper_scriptname $cwrapper + $RM $func_ltwrapper_scriptname_result + trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 + $opt_dry_run || { + # note: this script will not be executed, so do not chmod. + if test "x$build" = "x$host"; then + $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result + else + func_emit_wrapper no > $func_ltwrapper_scriptname_result + fi + } + ;; + * ) + $RM $output + trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 + + func_emit_wrapper no > $output + chmod +x $output + ;; + esac + } + exit $EXIT_SUCCESS + ;; + esac + + # See if we need to build an old-fashioned archive. + for oldlib in $oldlibs; do + + case $build_libtool_libs in + convenience) + oldobjs="$libobjs_save $symfileobj" + addlibs=$convenience + build_libtool_libs=no + ;; + module) + oldobjs=$libobjs_save + addlibs=$old_convenience + build_libtool_libs=no + ;; + *) + oldobjs="$old_deplibs $non_pic_objects" + $preload && test -f "$symfileobj" \ + && func_append oldobjs " $symfileobj" + addlibs=$old_convenience + ;; + esac + + if test -n "$addlibs"; then + gentop=$output_objdir/${outputname}x + func_append generated " $gentop" + + func_extract_archives $gentop $addlibs + func_append oldobjs " $func_extract_archives_result" + fi + + # Do each command in the archive commands. + if test -n "$old_archive_from_new_cmds" && test yes = "$build_libtool_libs"; then + cmds=$old_archive_from_new_cmds + else + + # Add any objects from preloaded convenience libraries + if test -n "$dlprefiles"; then + gentop=$output_objdir/${outputname}x + func_append generated " $gentop" + + func_extract_archives $gentop $dlprefiles + func_append oldobjs " $func_extract_archives_result" + fi + + # POSIX demands no paths to be encoded in archives. We have + # to avoid creating archives with duplicate basenames if we + # might have to extract them afterwards, e.g., when creating a + # static archive out of a convenience library, or when linking + # the entirety of a libtool archive into another (currently + # not supported by libtool). + if (for obj in $oldobjs + do + func_basename "$obj" + $ECHO "$func_basename_result" + done | sort | sort -uc >/dev/null 2>&1); then + : + else + echo "copying selected object files to avoid basename conflicts..." + gentop=$output_objdir/${outputname}x + func_append generated " $gentop" + func_mkdir_p "$gentop" + save_oldobjs=$oldobjs + oldobjs= + counter=1 + for obj in $save_oldobjs + do + func_basename "$obj" + objbase=$func_basename_result + case " $oldobjs " in + " ") oldobjs=$obj ;; + *[\ /]"$objbase "*) + while :; do + # Make sure we don't pick an alternate name that also + # overlaps. + newobj=lt$counter-$objbase + func_arith $counter + 1 + counter=$func_arith_result + case " $oldobjs " in + *[\ /]"$newobj "*) ;; + *) if test ! -f "$gentop/$newobj"; then break; fi ;; + esac + done + func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" + func_append oldobjs " $gentop/$newobj" + ;; + *) func_append oldobjs " $obj" ;; + esac + done + fi + func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 + tool_oldlib=$func_to_tool_file_result + eval cmds=\"$old_archive_cmds\" + + func_len " $cmds" + len=$func_len_result + if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then + cmds=$old_archive_cmds + elif test -n "$archiver_list_spec"; then + func_verbose "using command file archive linking..." + for obj in $oldobjs + do + func_to_tool_file "$obj" + $ECHO "$func_to_tool_file_result" + done > $output_objdir/$libname.libcmd + func_to_tool_file "$output_objdir/$libname.libcmd" + oldobjs=" $archiver_list_spec$func_to_tool_file_result" + cmds=$old_archive_cmds + else + # the command line is too long to link in one step, link in parts + func_verbose "using piecewise archive linking..." + save_RANLIB=$RANLIB + RANLIB=: + objlist= + concat_cmds= + save_oldobjs=$oldobjs + oldobjs= + # Is there a better way of finding the last object in the list? + for obj in $save_oldobjs + do + last_oldobj=$obj + done + eval test_cmds=\"$old_archive_cmds\" + func_len " $test_cmds" + len0=$func_len_result + len=$len0 + for obj in $save_oldobjs + do + func_len " $obj" + func_arith $len + $func_len_result + len=$func_arith_result + func_append objlist " $obj" + if test "$len" -lt "$max_cmd_len"; then + : + else + # the above command should be used before it gets too long + oldobjs=$objlist + if test "$obj" = "$last_oldobj"; then + RANLIB=$save_RANLIB + fi + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + eval concat_cmds=\"\$concat_cmds$old_archive_cmds\" + objlist= + len=$len0 + fi + done + RANLIB=$save_RANLIB + oldobjs=$objlist + if test -z "$oldobjs"; then + eval cmds=\"\$concat_cmds\" + else + eval cmds=\"\$concat_cmds~\$old_archive_cmds\" + fi + fi + fi + func_execute_cmds "$cmds" 'exit $?' + done + + test -n "$generated" && \ + func_show_eval "${RM}r$generated" + + # Now create the libtool archive. + case $output in + *.la) + old_library= + test yes = "$build_old_libs" && old_library=$libname.$libext + func_verbose "creating $output" + + # Preserve any variables that may affect compiler behavior + for var in $variables_saved_for_relink; do + if eval test -z \"\${$var+set}\"; then + relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" + elif eval var_value=\$$var; test -z "$var_value"; then + relink_command="$var=; export $var; $relink_command" + else + func_quote_arg pretty,unquoted "$var_value" + relink_command="$var=$func_quote_arg_unquoted_result; export $var; $relink_command" + fi + done + # Quote the link command for shipping. + func_quote eval cd "`pwd`" + relink_command="($func_quote_result; $SHELL \"$progpath\" $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" + func_quote_arg pretty,unquoted "$relink_command" + relink_command=$func_quote_arg_unquoted_result + if test yes = "$hardcode_automatic"; then + relink_command= + fi + + # Only create the output if not a dry run. + $opt_dry_run || { + for installed in no yes; do + if test yes = "$installed"; then + if test -z "$install_libdir"; then + break + fi + output=$output_objdir/${outputname}i + # Replace all uninstalled libtool libraries with the installed ones + newdependency_libs= + for deplib in $dependency_libs; do + case $deplib in + *.la) + func_basename "$deplib" + name=$func_basename_result + func_resolve_sysroot "$deplib" + eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result` + test -z "$libdir" && \ + func_fatal_error "'$deplib' is not a valid libtool archive" + func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name" + ;; + -L*) + func_stripname -L '' "$deplib" + func_replace_sysroot "$func_stripname_result" + func_append newdependency_libs " -L$func_replace_sysroot_result" + ;; + -R*) + func_stripname -R '' "$deplib" + func_replace_sysroot "$func_stripname_result" + func_append newdependency_libs " -R$func_replace_sysroot_result" + ;; + *) func_append newdependency_libs " $deplib" ;; + esac + done + dependency_libs=$newdependency_libs + newdlfiles= + + for lib in $dlfiles; do + case $lib in + *.la) + func_basename "$lib" + name=$func_basename_result + eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $lib` + test -z "$libdir" && \ + func_fatal_error "'$lib' is not a valid libtool archive" + func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name" + ;; + *) func_append newdlfiles " $lib" ;; + esac + done + dlfiles=$newdlfiles + newdlprefiles= + for lib in $dlprefiles; do + case $lib in + *.la) + # Only pass preopened files to the pseudo-archive (for + # eventual linking with the app. that links it) if we + # didn't already link the preopened objects directly into + # the library: + func_basename "$lib" + name=$func_basename_result + eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $lib` + test -z "$libdir" && \ + func_fatal_error "'$lib' is not a valid libtool archive" + func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name" + ;; + esac + done + dlprefiles=$newdlprefiles + else + newdlfiles= + for lib in $dlfiles; do + case $lib in + [\\/]* | [A-Za-z]:[\\/]*) abs=$lib ;; + *) abs=`pwd`"/$lib" ;; + esac + func_append newdlfiles " $abs" + done + dlfiles=$newdlfiles + newdlprefiles= + for lib in $dlprefiles; do + case $lib in + [\\/]* | [A-Za-z]:[\\/]*) abs=$lib ;; + *) abs=`pwd`"/$lib" ;; + esac + func_append newdlprefiles " $abs" + done + dlprefiles=$newdlprefiles + fi + $RM $output + # place dlname in correct position for cygwin + # In fact, it would be nice if we could use this code for all target + # systems that can't hard-code library paths into their executables + # and that have no shared library path variable independent of PATH, + # but it turns out we can't easily determine that from inspecting + # libtool variables, so we have to hard-code the OSs to which it + # applies here; at the moment, that means platforms that use the PE + # object format with DLL files. See the long comment at the top of + # tests/bindir.at for full details. + tdlname=$dlname + case $host,$output,$installed,$module,$dlname in + *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) + # If a -bindir argument was supplied, place the dll there. + if test -n "$bindir"; then + func_relative_path "$install_libdir" "$bindir" + tdlname=$func_relative_path_result/$dlname + else + # Otherwise fall back on heuristic. + tdlname=../bin/$dlname + fi + ;; + esac + $ECHO > $output "\ +# $outputname - a libtool library file +# Generated by $PROGRAM (GNU $PACKAGE) $VERSION +# +# Please DO NOT delete this file! +# It is necessary for linking the library. + +# The name that we can dlopen(3). +dlname='$tdlname' + +# Names of this library. +library_names='$library_names' + +# The name of the static archive. +old_library='$old_library' + +# Linker flags that cannot go in dependency_libs. +inherited_linker_flags='$new_inherited_linker_flags' + +# Libraries that this one depends upon. +dependency_libs='$dependency_libs' + +# Names of additional weak libraries provided by this library +weak_library_names='$weak_libs' + +# Version information for $libname. +current=$current +age=$age +revision=$revision + +# Is this an already installed library? +installed=$installed + +# Should we warn about portability when linking against -modules? +shouldnotlink=$module + +# Files to dlopen/dlpreopen +dlopen='$dlfiles' +dlpreopen='$dlprefiles' + +# Directory that this library needs to be installed in: +libdir='$install_libdir'" + if test no,yes = "$installed,$need_relink"; then + $ECHO >> $output "\ +relink_command=\"$relink_command\"" + fi + done + } + + # Do a symbolic link so that the libtool archive can be found in + # LD_LIBRARY_PATH before the program is installed. + func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' + ;; + esac + exit $EXIT_SUCCESS +} + +if test link = "$opt_mode" || test relink = "$opt_mode"; then + func_mode_link ${1+"$@"} +fi + + +# func_mode_uninstall arg... +func_mode_uninstall () +{ + $debug_cmd + + RM=$nonopt + files= + rmforce=false + exit_status=0 + + # This variable tells wrapper scripts just to set variables rather + # than running their programs. + libtool_install_magic=$magic + + for arg + do + case $arg in + -f) func_append RM " $arg"; rmforce=: ;; + -*) func_append RM " $arg" ;; + *) func_append files " $arg" ;; + esac + done + + test -z "$RM" && \ + func_fatal_help "you must specify an RM program" + + rmdirs= + + for file in $files; do + func_dirname "$file" "" "." + dir=$func_dirname_result + if test . = "$dir"; then + odir=$objdir + else + odir=$dir/$objdir + fi + func_basename "$file" + name=$func_basename_result + test uninstall = "$opt_mode" && odir=$dir + + # Remember odir for removal later, being careful to avoid duplicates + if test clean = "$opt_mode"; then + case " $rmdirs " in + *" $odir "*) ;; + *) func_append rmdirs " $odir" ;; + esac + fi + + # Don't error if the file doesn't exist and rm -f was used. + if { test -L "$file"; } >/dev/null 2>&1 || + { test -h "$file"; } >/dev/null 2>&1 || + test -f "$file"; then + : + elif test -d "$file"; then + exit_status=1 + continue + elif $rmforce; then + continue + fi + + rmfiles=$file + + case $name in + *.la) + # Possibly a libtool archive, so verify it. + if func_lalib_p "$file"; then + func_source $dir/$name + + # Delete the libtool libraries and symlinks. + for n in $library_names; do + func_append rmfiles " $odir/$n" + done + test -n "$old_library" && func_append rmfiles " $odir/$old_library" + + case $opt_mode in + clean) + case " $library_names " in + *" $dlname "*) ;; + *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;; + esac + test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i" + ;; + uninstall) + if test -n "$library_names"; then + # Do each command in the postuninstall commands. + func_execute_cmds "$postuninstall_cmds" '$rmforce || exit_status=1' + fi + + if test -n "$old_library"; then + # Do each command in the old_postuninstall commands. + func_execute_cmds "$old_postuninstall_cmds" '$rmforce || exit_status=1' + fi + # FIXME: should reinstall the best remaining shared library. + ;; + esac + fi + ;; + + *.lo) + # Possibly a libtool object, so verify it. + if func_lalib_p "$file"; then + + # Read the .lo file + func_source $dir/$name + + # Add PIC object to the list of files to remove. + if test -n "$pic_object" && test none != "$pic_object"; then + func_append rmfiles " $dir/$pic_object" + fi + + # Add non-PIC object to the list of files to remove. + if test -n "$non_pic_object" && test none != "$non_pic_object"; then + func_append rmfiles " $dir/$non_pic_object" + fi + fi + ;; + + *) + if test clean = "$opt_mode"; then + noexename=$name + case $file in + *.exe) + func_stripname '' '.exe' "$file" + file=$func_stripname_result + func_stripname '' '.exe' "$name" + noexename=$func_stripname_result + # $file with .exe has already been added to rmfiles, + # add $file without .exe + func_append rmfiles " $file" + ;; + esac + # Do a test to see if this is a libtool program. + if func_ltwrapper_p "$file"; then + if func_ltwrapper_executable_p "$file"; then + func_ltwrapper_scriptname "$file" + relink_command= + func_source $func_ltwrapper_scriptname_result + func_append rmfiles " $func_ltwrapper_scriptname_result" + else + relink_command= + func_source $dir/$noexename + fi + + # note $name still contains .exe if it was in $file originally + # as does the version of $file that was added into $rmfiles + func_append rmfiles " $odir/$name $odir/${name}S.$objext" + if test yes = "$fast_install" && test -n "$relink_command"; then + func_append rmfiles " $odir/lt-$name" + fi + if test "X$noexename" != "X$name"; then + func_append rmfiles " $odir/lt-$noexename.c" + fi + fi + fi + ;; + esac + func_show_eval "$RM $rmfiles" 'exit_status=1' + done + + # Try to remove the $objdir's in the directories where we deleted files + for dir in $rmdirs; do + if test -d "$dir"; then + func_show_eval "rmdir $dir >/dev/null 2>&1" + fi + done + + exit $exit_status +} + +if test uninstall = "$opt_mode" || test clean = "$opt_mode"; then + func_mode_uninstall ${1+"$@"} +fi + +test -z "$opt_mode" && { + help=$generic_help + func_fatal_help "you must specify a MODE" +} + +test -z "$exec_cmd" && \ + func_fatal_help "invalid operation mode '$opt_mode'" + +if test -n "$exec_cmd"; then + eval exec "$exec_cmd" + exit $EXIT_FAILURE +fi + +exit $exit_status + + +# The TAGs below are defined such that we never get into a situation +# where we disable both kinds of libraries. Given conflicting +# choices, we go for a static library, that is the most portable, +# since we can't tell whether shared libraries were disabled because +# the user asked for that or because the platform doesn't support +# them. This is particularly important on AIX, because we don't +# support having both static and shared libraries enabled at the same +# time on that platform, so we default to a shared-only configuration. +# If a disable-shared tag is given, we'll fallback to a static-only +# configuration. But we'll never go from static-only to shared-only. + +# ### BEGIN LIBTOOL TAG CONFIG: disable-shared +build_libtool_libs=no +build_old_libs=yes +# ### END LIBTOOL TAG CONFIG: disable-shared + +# ### BEGIN LIBTOOL TAG CONFIG: disable-static +build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` +# ### END LIBTOOL TAG CONFIG: disable-static + +# Local Variables: +# mode:shell-script +# sh-indentation:2 +# End: diff --git a/third_party/curl/m4/curl-amissl.m4 b/third_party/curl/m4/curl-amissl.m4 new file mode 100644 index 0000000..48067e7 --- /dev/null +++ b/third_party/curl/m4/curl-amissl.m4 @@ -0,0 +1,69 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +AC_DEFUN([CURL_WITH_AMISSL], [ +AC_MSG_CHECKING([whether to enable Amiga native SSL/TLS (AmiSSL v5)]) +if test "$HAVE_PROTO_BSDSOCKET_H" = "1"; then + if test "x$OPT_AMISSL" != xno; then + ssl_msg= + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + #include + #include + ]],[[ + #if defined(AMISSL_CURRENT_VERSION) && defined(AMISSL_V3xx) && \ + (OPENSSL_VERSION_NUMBER >= 0x30000000L) && \ + defined(PROTO_AMISSL_H) + return 0; + #else + #error not AmiSSL v5 / OpenSSL 3 + #endif + ]]) + ],[ + AC_MSG_RESULT([yes]) + ssl_msg="AmiSSL" + test amissl != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + AMISSL_ENABLED=1 + OPENSSL_ENABLED=1 + # Use AmiSSL's built-in ca bundle + check_for_ca_bundle=1 + with_ca_fallback=yes + LIBS="-lamisslstubs -lamisslauto $LIBS" + AC_DEFINE(USE_AMISSL, 1, [if AmiSSL is in use]) + AC_DEFINE(USE_OPENSSL, 1, [if OpenSSL is in use]) + AC_DEFINE_UNQUOTED(HAVE_OPENSSL3, 1, [Define to 1 if using OpenSSL 3 or later.]) + AC_CHECK_HEADERS(openssl/x509.h openssl/rsa.h openssl/crypto.h \ + openssl/pem.h openssl/ssl.h openssl/err.h) + ],[ + AC_MSG_RESULT([no]) + ]) + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" + else + AC_MSG_RESULT(no) + fi +else + AC_MSG_RESULT(no) +fi + +]) diff --git a/third_party/curl/m4/curl-bearssl.m4 b/third_party/curl/m4/curl-bearssl.m4 new file mode 100644 index 0000000..f2d661d --- /dev/null +++ b/third_party/curl/m4/curl-bearssl.m4 @@ -0,0 +1,110 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +AC_DEFUN([CURL_WITH_BEARSSL], [ +dnl ---------------------------------------------------- +dnl check for BearSSL +dnl ---------------------------------------------------- + +if test "x$OPT_BEARSSL" != xno; then + _cppflags=$CPPFLAGS + _ldflags=$LDFLAGS + ssl_msg= + + if test X"$OPT_BEARSSL" != Xno; then + + if test "$OPT_BEARSSL" = "yes"; then + OPT_BEARSSL="" + fi + + if test -z "$OPT_BEARSSL" ; then + dnl check for lib first without setting any new path + + AC_CHECK_LIB(bearssl, br_ssl_client_init_full, + dnl libbearssl found, set the variable + [ + AC_DEFINE(USE_BEARSSL, 1, [if BearSSL is enabled]) + AC_SUBST(USE_BEARSSL, [1]) + BEARSSL_ENABLED=1 + USE_BEARSSL="yes" + ssl_msg="BearSSL" + test bearssl != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + ], [], -lbearssl) + fi + + addld="" + addlib="" + addcflags="" + bearssllib="" + + if test "x$USE_BEARSSL" != "xyes"; then + dnl add the path and test again + addld=-L$OPT_BEARSSL/lib$libsuff + addcflags=-I$OPT_BEARSSL/include + bearssllib=$OPT_BEARSSL/lib$libsuff + + LDFLAGS="$LDFLAGS $addld" + if test "$addcflags" != "-I/usr/include"; then + CPPFLAGS="$CPPFLAGS $addcflags" + fi + + AC_CHECK_LIB(bearssl, br_ssl_client_init_full, + [ + AC_DEFINE(USE_BEARSSL, 1, [if BearSSL is enabled]) + AC_SUBST(USE_BEARSSL, [1]) + BEARSSL_ENABLED=1 + USE_BEARSSL="yes" + ssl_msg="BearSSL" + test bearssl != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + ], + [ + CPPFLAGS=$_cppflags + LDFLAGS=$_ldflags + ], -lbearssl) + fi + + if test "x$USE_BEARSSL" = "xyes"; then + AC_MSG_NOTICE([detected BearSSL]) + check_for_ca_bundle=1 + + LIBS="-lbearssl $LIBS" + + if test -n "$bearssllib"; then + dnl when shared libs were found in a path that the run-time + dnl linker doesn't search through, we need to add it to + dnl CURL_LIBRARY_PATH to prevent further configure tests to fail + dnl due to this + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$bearssllib" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $bearssllib to CURL_LIBRARY_PATH]) + fi + fi + fi + + fi dnl BearSSL not disabled + + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" +fi +]) diff --git a/third_party/curl/m4/curl-compilers.m4 b/third_party/curl/m4/curl-compilers.m4 new file mode 100644 index 0000000..06e335d --- /dev/null +++ b/third_party/curl/m4/curl-compilers.m4 @@ -0,0 +1,1631 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +# File version for 'aclocal' use. Keep it a single number. +# serial 67 + + +dnl CURL_CHECK_COMPILER +dnl ------------------------------------------------- +dnl Verify if the C compiler being used is known. + +AC_DEFUN([CURL_CHECK_COMPILER], [ + # + compiler_id="unknown" + compiler_num="0" + # + flags_dbg_yes="unknown" + flags_opt_all="unknown" + flags_opt_yes="unknown" + flags_opt_off="unknown" + # + flags_prefer_cppflags="no" + # + CURL_CHECK_COMPILER_DEC_C + CURL_CHECK_COMPILER_HPUX_C + CURL_CHECK_COMPILER_IBM_C + CURL_CHECK_COMPILER_INTEL_C + CURL_CHECK_COMPILER_CLANG + CURL_CHECK_COMPILER_GNU_C + case $host in + mips-sgi-irix*) + CURL_CHECK_COMPILER_SGI_MIPSPRO_C + CURL_CHECK_COMPILER_SGI_MIPS_C + ;; + esac + CURL_CHECK_COMPILER_SUNPRO_C + CURL_CHECK_COMPILER_TINY_C + # + if test "$compiler_id" = "unknown"; then + cat <<_EOF 1>&2 +*** +*** Warning: This configure script does not have information about the +*** compiler you are using, relative to the flags required to enable or +*** disable generation of debug info, optimization options or warnings. +*** +*** Whatever settings are present in CFLAGS will be used for this run. +*** +*** If you wish to help the curl project to better support your compiler +*** you can report this and the required info on the libcurl development +*** mailing list: https://lists.haxx.selistinfo/curl-library/ +*** +_EOF + fi +]) + + +dnl CURL_CHECK_COMPILER_CLANG +dnl ------------------------------------------------- +dnl Verify if compiler being used is clang. + +AC_DEFUN([CURL_CHECK_COMPILER_CLANG], [ + AC_BEFORE([$0],[CURL_CHECK_COMPILER_GNU_C])dnl + AC_MSG_CHECKING([if compiler is clang]) + CURL_CHECK_DEF([__clang__], [], [silent]) + if test "$curl_cv_have_def___clang__" = "yes"; then + AC_MSG_RESULT([yes]) + AC_MSG_CHECKING([if compiler is xlclang]) + CURL_CHECK_DEF([__ibmxl__], [], [silent]) + if test "$curl_cv_have_def___ibmxl__" = "yes" ; then + dnl IBM's almost-compatible clang version + AC_MSG_RESULT([yes]) + compiler_id="XLCLANG" + else + AC_MSG_RESULT([no]) + compiler_id="CLANG" + fi + AC_MSG_CHECKING([compiler version]) + fullclangver=`$CC -v 2>&1 | grep version` + if echo $fullclangver | grep 'Apple' >/dev/null; then + appleclang=1 + else + appleclang=0 + fi + clangver=`echo $fullclangver | grep "based on LLVM " | "$SED" 's/.*(based on LLVM \(@<:@0-9@:>@*\.@<:@0-9@:>@*\).*)/\1/'` + if test -z "$clangver"; then + clangver=`echo $fullclangver | "$SED" 's/.*version \(@<:@0-9@:>@*\.@<:@0-9@:>@*\).*/\1/'` + oldapple=0 + else + oldapple=1 + fi + clangvhi=`echo $clangver | cut -d . -f1` + clangvlo=`echo $clangver | cut -d . -f2` + compiler_num=`(expr $clangvhi "*" 100 + $clangvlo) 2>/dev/null` + if test "$appleclang" = '1' && test "$oldapple" = '0'; then + dnl Starting with Xcode 7 / clang 3.7, Apple clang won't tell its upstream version + if test "$compiler_num" -ge '1300'; then compiler_num='1200' + elif test "$compiler_num" -ge '1205'; then compiler_num='1101' + elif test "$compiler_num" -ge '1204'; then compiler_num='1000' + elif test "$compiler_num" -ge '1107'; then compiler_num='900' + elif test "$compiler_num" -ge '1103'; then compiler_num='800' + elif test "$compiler_num" -ge '1003'; then compiler_num='700' + elif test "$compiler_num" -ge '1001'; then compiler_num='600' + elif test "$compiler_num" -ge '904'; then compiler_num='500' + elif test "$compiler_num" -ge '902'; then compiler_num='400' + elif test "$compiler_num" -ge '803'; then compiler_num='309' + elif test "$compiler_num" -ge '703'; then compiler_num='308' + else compiler_num='307' + fi + fi + AC_MSG_RESULT([clang '$compiler_num' (raw: '$fullclangver' / '$clangver')]) + flags_dbg_yes="-g" + flags_opt_all="-O -O0 -O1 -O2 -Os -O3 -O4" + flags_opt_yes="-O2" + flags_opt_off="-O0" + else + AC_MSG_RESULT([no]) + fi +]) + + +dnl CURL_CHECK_COMPILER_DEC_C +dnl ------------------------------------------------- +dnl Verify if compiler being used is DEC C. + +AC_DEFUN([CURL_CHECK_COMPILER_DEC_C], [ + AC_MSG_CHECKING([if compiler is DEC/Compaq/HP C]) + CURL_CHECK_DEF([__DECC], [], [silent]) + CURL_CHECK_DEF([__DECC_VER], [], [silent]) + if test "$curl_cv_have_def___DECC" = "yes" && + test "$curl_cv_have_def___DECC_VER" = "yes"; then + AC_MSG_RESULT([yes]) + compiler_id="DEC_C" + flags_dbg_yes="-g2" + flags_opt_all="-O -O0 -O1 -O2 -O3 -O4" + flags_opt_yes="-O1" + flags_opt_off="-O0" + else + AC_MSG_RESULT([no]) + fi +]) + + +dnl CURL_CHECK_COMPILER_GNU_C +dnl ------------------------------------------------- +dnl Verify if compiler being used is GNU C +dnl +dnl $compiler_num will be set to MAJOR * 100 + MINOR for gcc less than version +dnl 7 and just $MAJOR * 100 for gcc version 7 and later. +dnl +dnl Examples: +dnl Version 1.2.3 => 102 +dnl Version 2.95 => 295 +dnl Version 4.7 => 407 +dnl Version 9.2.1 => 900 +dnl +AC_DEFUN([CURL_CHECK_COMPILER_GNU_C], [ + AC_REQUIRE([CURL_CHECK_COMPILER_INTEL_C])dnl + AC_REQUIRE([CURL_CHECK_COMPILER_CLANG])dnl + AC_MSG_CHECKING([if compiler is GNU C]) + CURL_CHECK_DEF([__GNUC__], [], [silent]) + if test "$curl_cv_have_def___GNUC__" = "yes" && + test "$compiler_id" = "unknown"; then + AC_MSG_RESULT([yes]) + compiler_id="GNU_C" + AC_MSG_CHECKING([compiler version]) + # strip '-suffix' parts, e.g. Ubuntu Windows cross-gcc returns '10-win32' + gccver=`$CC -dumpversion | sed -E 's/-.+$//'` + gccvhi=`echo $gccver | cut -d . -f1` + if echo $gccver | grep -F '.' >/dev/null; then + gccvlo=`echo $gccver | cut -d . -f2` + else + gccvlo="0" + fi + compiler_num=`(expr $gccvhi "*" 100 + $gccvlo) 2>/dev/null` + AC_MSG_RESULT([gcc '$compiler_num' (raw: '$gccver')]) + flags_dbg_yes="-g" + flags_opt_all="-O -O0 -O1 -O2 -O3 -Os -Og -Ofast" + flags_opt_yes="-O2" + flags_opt_off="-O0" + else + AC_MSG_RESULT([no]) + fi +]) + + +dnl CURL_CHECK_COMPILER_HPUX_C +dnl ------------------------------------------------- +dnl Verify if compiler being used is HP-UX C. + +AC_DEFUN([CURL_CHECK_COMPILER_HPUX_C], [ + AC_MSG_CHECKING([if compiler is HP-UX C]) + CURL_CHECK_DEF([__HP_cc], [], [silent]) + if test "$curl_cv_have_def___HP_cc" = "yes"; then + AC_MSG_RESULT([yes]) + compiler_id="HP_UX_C" + flags_dbg_yes="-g" + flags_opt_all="-O +O0 +O1 +O2 +O3 +O4" + flags_opt_yes="+O2" + flags_opt_off="+O0" + else + AC_MSG_RESULT([no]) + fi +]) + + +dnl CURL_CHECK_COMPILER_IBM_C +dnl ------------------------------------------------- +dnl Verify if compiler being used is IBM C. + +AC_DEFUN([CURL_CHECK_COMPILER_IBM_C], [ + AC_MSG_CHECKING([if compiler is IBM C]) + CURL_CHECK_DEF([__IBMC__], [], [silent]) + if test "$curl_cv_have_def___IBMC__" = "yes"; then + AC_MSG_RESULT([yes]) + compiler_id="IBM_C" + flags_dbg_yes="-g" + flags_opt_all="-O -O0 -O1 -O2 -O3 -O4 -O5" + flags_opt_all="$flags_opt_all -qnooptimize" + flags_opt_all="$flags_opt_all -qoptimize=0" + flags_opt_all="$flags_opt_all -qoptimize=1" + flags_opt_all="$flags_opt_all -qoptimize=2" + flags_opt_all="$flags_opt_all -qoptimize=3" + flags_opt_all="$flags_opt_all -qoptimize=4" + flags_opt_all="$flags_opt_all -qoptimize=5" + flags_opt_yes="-O2" + flags_opt_off="-qnooptimize" + flags_prefer_cppflags="yes" + else + AC_MSG_RESULT([no]) + fi +]) + + +dnl CURL_CHECK_COMPILER_INTEL_C +dnl ------------------------------------------------- +dnl Verify if compiler being used is Intel C. + +AC_DEFUN([CURL_CHECK_COMPILER_INTEL_C], [ + AC_BEFORE([$0],[CURL_CHECK_COMPILER_GNU_C])dnl + AC_MSG_CHECKING([if compiler is Intel C]) + CURL_CHECK_DEF([__INTEL_COMPILER], [], [silent]) + if test "$curl_cv_have_def___INTEL_COMPILER" = "yes"; then + AC_MSG_RESULT([yes]) + AC_MSG_CHECKING([compiler version]) + compiler_num="$curl_cv_def___INTEL_COMPILER" + AC_MSG_RESULT([Intel C '$compiler_num']) + CURL_CHECK_DEF([__unix__], [], [silent]) + if test "$curl_cv_have_def___unix__" = "yes"; then + compiler_id="INTEL_UNIX_C" + flags_dbg_yes="-g" + flags_opt_all="-O -O0 -O1 -O2 -O3 -Os" + flags_opt_yes="-O2" + flags_opt_off="-O0" + else + compiler_id="INTEL_WINDOWS_C" + flags_dbg_yes="/Zi /Oy-" + flags_opt_all="/O /O0 /O1 /O2 /O3 /Od /Og /Og- /Oi /Oi-" + flags_opt_yes="/O2" + flags_opt_off="/Od" + fi + else + AC_MSG_RESULT([no]) + fi +]) + + +dnl CURL_CHECK_COMPILER_SGI_MIPS_C +dnl ------------------------------------------------- +dnl Verify if compiler being used is SGI MIPS C. + +AC_DEFUN([CURL_CHECK_COMPILER_SGI_MIPS_C], [ + AC_REQUIRE([CURL_CHECK_COMPILER_SGI_MIPSPRO_C])dnl + AC_MSG_CHECKING([if compiler is SGI MIPS C]) + CURL_CHECK_DEF([__GNUC__], [], [silent]) + CURL_CHECK_DEF([__sgi], [], [silent]) + if test "$curl_cv_have_def___GNUC__" = "no" && + test "$curl_cv_have_def___sgi" = "yes" && + test "$compiler_id" = "unknown"; then + AC_MSG_RESULT([yes]) + compiler_id="SGI_MIPS_C" + flags_dbg_yes="-g" + flags_opt_all="-O -O0 -O1 -O2 -O3 -Ofast" + flags_opt_yes="-O2" + flags_opt_off="-O0" + else + AC_MSG_RESULT([no]) + fi +]) + + +dnl CURL_CHECK_COMPILER_SGI_MIPSPRO_C +dnl ------------------------------------------------- +dnl Verify if compiler being used is SGI MIPSpro C. + +AC_DEFUN([CURL_CHECK_COMPILER_SGI_MIPSPRO_C], [ + AC_BEFORE([$0],[CURL_CHECK_COMPILER_SGI_MIPS_C])dnl + AC_MSG_CHECKING([if compiler is SGI MIPSpro C]) + CURL_CHECK_DEF([__GNUC__], [], [silent]) + CURL_CHECK_DEF([_COMPILER_VERSION], [], [silent]) + CURL_CHECK_DEF([_SGI_COMPILER_VERSION], [], [silent]) + if test "$curl_cv_have_def___GNUC__" = "no" && + (test "$curl_cv_have_def__SGI_COMPILER_VERSION" = "yes" || + test "$curl_cv_have_def__COMPILER_VERSION" = "yes"); then + AC_MSG_RESULT([yes]) + compiler_id="SGI_MIPSPRO_C" + flags_dbg_yes="-g" + flags_opt_all="-O -O0 -O1 -O2 -O3 -Ofast" + flags_opt_yes="-O2" + flags_opt_off="-O0" + else + AC_MSG_RESULT([no]) + fi +]) + + +dnl CURL_CHECK_COMPILER_SUNPRO_C +dnl ------------------------------------------------- +dnl Verify if compiler being used is SunPro C. + +AC_DEFUN([CURL_CHECK_COMPILER_SUNPRO_C], [ + AC_MSG_CHECKING([if compiler is SunPro C]) + CURL_CHECK_DEF([__SUNPRO_C], [], [silent]) + if test "$curl_cv_have_def___SUNPRO_C" = "yes"; then + AC_MSG_RESULT([yes]) + compiler_id="SUNPRO_C" + flags_dbg_yes="-g" + flags_opt_all="-O -xO -xO1 -xO2 -xO3 -xO4 -xO5" + flags_opt_yes="-xO2" + flags_opt_off="" + else + AC_MSG_RESULT([no]) + fi +]) + + +dnl CURL_CHECK_COMPILER_TINY_C +dnl ------------------------------------------------- +dnl Verify if compiler being used is Tiny C. + +AC_DEFUN([CURL_CHECK_COMPILER_TINY_C], [ + AC_MSG_CHECKING([if compiler is Tiny C]) + CURL_CHECK_DEF([__TINYC__], [], [silent]) + if test "$curl_cv_have_def___TINYC__" = "yes"; then + AC_MSG_RESULT([yes]) + compiler_id="TINY_C" + flags_dbg_yes="-g" + flags_opt_all="" + flags_opt_yes="" + flags_opt_off="" + else + AC_MSG_RESULT([no]) + fi +]) + +dnl CURL_CONVERT_INCLUDE_TO_ISYSTEM +dnl ------------------------------------------------- +dnl Changes standard include paths present in CFLAGS +dnl and CPPFLAGS into isystem include paths. This is +dnl done to prevent GNUC from generating warnings on +dnl headers from these locations, although on ancient +dnl GNUC versions these warnings are not silenced. + +AC_DEFUN([CURL_CONVERT_INCLUDE_TO_ISYSTEM], [ + AC_REQUIRE([CURL_SHFUNC_SQUEEZE])dnl + AC_REQUIRE([CURL_CHECK_COMPILER])dnl + AC_MSG_CHECKING([convert -I options to -isystem]) + if test "$compiler_id" = "GNU_C" || + test "$compiler_id" = "CLANG"; then + AC_MSG_RESULT([yes]) + tmp_has_include="no" + tmp_chg_FLAGS="$CFLAGS" + for word1 in $tmp_chg_FLAGS; do + case "$word1" in + -I*) + tmp_has_include="yes" + ;; + esac + done + if test "$tmp_has_include" = "yes"; then + tmp_chg_FLAGS=`echo "$tmp_chg_FLAGS" | "$SED" 's/^-I/ -isystem /g'` + tmp_chg_FLAGS=`echo "$tmp_chg_FLAGS" | "$SED" 's/ -I/ -isystem /g'` + CFLAGS="$tmp_chg_FLAGS" + squeeze CFLAGS + fi + tmp_has_include="no" + tmp_chg_FLAGS="$CPPFLAGS" + for word1 in $tmp_chg_FLAGS; do + case "$word1" in + -I*) + tmp_has_include="yes" + ;; + esac + done + if test "$tmp_has_include" = "yes"; then + tmp_chg_FLAGS=`echo "$tmp_chg_FLAGS" | "$SED" 's/^-I/ -isystem /g'` + tmp_chg_FLAGS=`echo "$tmp_chg_FLAGS" | "$SED" 's/ -I/ -isystem /g'` + CPPFLAGS="$tmp_chg_FLAGS" + squeeze CPPFLAGS + fi + else + AC_MSG_RESULT([no]) + fi +]) + + +dnl CURL_COMPILER_WORKS_IFELSE ([ACTION-IF-WORKS], [ACTION-IF-NOT-WORKS]) +dnl ------------------------------------------------- +dnl Verify if the C compiler seems to work with the +dnl settings that are 'active' at the time the test +dnl is performed. + +AC_DEFUN([CURL_COMPILER_WORKS_IFELSE], [ + dnl compilation capability verification + tmp_compiler_works="unknown" + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + ]],[[ + int i = 1; + return i; + ]]) + ],[ + tmp_compiler_works="yes" + ],[ + tmp_compiler_works="no" + echo " " >&6 + sed 's/^/cc-fail: /' conftest.err >&6 + echo " " >&6 + ]) + dnl linking capability verification + if test "$tmp_compiler_works" = "yes"; then + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + ]],[[ + int i = 1; + return i; + ]]) + ],[ + tmp_compiler_works="yes" + ],[ + tmp_compiler_works="no" + echo " " >&6 + sed 's/^/link-fail: /' conftest.err >&6 + echo " " >&6 + ]) + fi + dnl only do runtime verification when not cross-compiling + if test "x$cross_compiling" != "xyes" && + test "$tmp_compiler_works" = "yes"; then + CURL_RUN_IFELSE([ + AC_LANG_PROGRAM([[ +# ifdef __STDC__ +# include +# endif + ]],[[ + int i = 0; + exit(i); + ]]) + ],[ + tmp_compiler_works="yes" + ],[ + tmp_compiler_works="no" + echo " " >&6 + echo "run-fail: test program exited with status $ac_status" >&6 + echo " " >&6 + ]) + fi + dnl branch upon test result + if test "$tmp_compiler_works" = "yes"; then + ifelse($1,,:,[$1]) + ifelse($2,,,[else + $2]) + fi +]) + + +dnl CURL_SET_COMPILER_BASIC_OPTS +dnl ------------------------------------------------- +dnl Sets compiler specific options/flags which do not +dnl depend on configure's debug, optimize or warnings +dnl options. + +AC_DEFUN([CURL_SET_COMPILER_BASIC_OPTS], [ + AC_REQUIRE([CURL_CHECK_COMPILER])dnl + AC_REQUIRE([CURL_SHFUNC_SQUEEZE])dnl + # + if test "$compiler_id" != "unknown"; then + # + tmp_save_CPPFLAGS="$CPPFLAGS" + tmp_save_CFLAGS="$CFLAGS" + tmp_CPPFLAGS="" + tmp_CFLAGS="" + # + case "$compiler_id" in + # + CLANG) + # + dnl Disable warnings for unused arguments, otherwise clang will + dnl warn about compile-time arguments used during link-time, like + dnl -O and -g and -pedantic. + tmp_CFLAGS="$tmp_CFLAGS -Qunused-arguments" + ;; + # + DEC_C) + # + dnl Select strict ANSI C compiler mode + tmp_CFLAGS="$tmp_CFLAGS -std1" + dnl Turn off optimizer ANSI C aliasing rules + tmp_CFLAGS="$tmp_CFLAGS -noansi_alias" + dnl Generate warnings for missing function prototypes + tmp_CFLAGS="$tmp_CFLAGS -warnprotos" + dnl Change some warnings into fatal errors + tmp_CFLAGS="$tmp_CFLAGS -msg_fatal toofewargs,toomanyargs" + ;; + # + GNU_C) + # + dnl turn implicit-function-declaration warning into error, + dnl at least gcc 2.95 and later support this + if test "$compiler_num" -ge "295"; then + tmp_CFLAGS="$tmp_CFLAGS -Werror-implicit-function-declaration" + fi + ;; + # + HP_UX_C) + # + dnl Disallow run-time dereferencing of null pointers + tmp_CFLAGS="$tmp_CFLAGS -z" + dnl Disable some remarks + dnl #4227: padding struct with n bytes to align member + dnl #4255: padding size of struct with n bytes to alignment boundary + tmp_CFLAGS="$tmp_CFLAGS +W 4227,4255" + ;; + # + IBM_C) + # + dnl Ensure that compiler optimizations are always thread-safe. + tmp_CPPFLAGS="$tmp_CPPFLAGS -qthreaded" + dnl Disable type based strict aliasing optimizations, using worst + dnl case aliasing assumptions when compiling. Type based aliasing + dnl would restrict the lvalues that could be safely used to access + dnl a data object. + tmp_CPPFLAGS="$tmp_CPPFLAGS -qnoansialias" + dnl Force compiler to stop after the compilation phase, without + dnl generating an object code file when compilation has errors. + tmp_CPPFLAGS="$tmp_CPPFLAGS -qhalt=e" + ;; + # + INTEL_UNIX_C) + # + dnl On unix this compiler uses gcc's header files, so + dnl we select ANSI C89 dialect plus GNU extensions. + tmp_CFLAGS="$tmp_CFLAGS -std=gnu89" + dnl Change some warnings into errors + dnl #140: too many arguments in function call + dnl #147: declaration is incompatible with 'previous one' + dnl #165: too few arguments in function call + dnl #266: function declared implicitly + tmp_CPPFLAGS="$tmp_CPPFLAGS -diag-error 140,147,165,266" + dnl Disable some remarks + dnl #279: controlling expression is constant + dnl #981: operands are evaluated in unspecified order + dnl #1025: zero extending result of unary operation + dnl #1469: "cc" clobber ignored + dnl #2259: non-pointer conversion from X to Y may lose significant bits + tmp_CPPFLAGS="$tmp_CPPFLAGS -diag-disable 279,981,1025,1469,2259" + ;; + # + INTEL_WINDOWS_C) + # + dnl Placeholder + tmp_CFLAGS="$tmp_CFLAGS" + ;; + # + SGI_MIPS_C) + # + dnl Placeholder + tmp_CFLAGS="$tmp_CFLAGS" + ;; + # + SGI_MIPSPRO_C) + # + dnl Placeholder + tmp_CFLAGS="$tmp_CFLAGS" + ;; + # + SUNPRO_C) + # + dnl Placeholder + tmp_CFLAGS="$tmp_CFLAGS" + ;; + # + TINY_C) + # + dnl Placeholder + tmp_CFLAGS="$tmp_CFLAGS" + ;; + # + esac + # + squeeze tmp_CPPFLAGS + squeeze tmp_CFLAGS + # + if test ! -z "$tmp_CFLAGS" || test ! -z "$tmp_CPPFLAGS"; then + AC_MSG_CHECKING([if compiler accepts some basic options]) + CPPFLAGS="$tmp_save_CPPFLAGS $tmp_CPPFLAGS" + CFLAGS="$tmp_save_CFLAGS $tmp_CFLAGS" + squeeze CPPFLAGS + squeeze CFLAGS + CURL_COMPILER_WORKS_IFELSE([ + AC_MSG_RESULT([yes]) + AC_MSG_NOTICE([compiler options added: $tmp_CFLAGS $tmp_CPPFLAGS]) + ],[ + AC_MSG_RESULT([no]) + AC_MSG_WARN([compiler options rejected: $tmp_CFLAGS $tmp_CPPFLAGS]) + dnl restore initial settings + CPPFLAGS="$tmp_save_CPPFLAGS" + CFLAGS="$tmp_save_CFLAGS" + ]) + fi + # + fi +]) + + +dnl CURL_SET_COMPILER_DEBUG_OPTS +dnl ------------------------------------------------- +dnl Sets compiler specific options/flags which depend +dnl on configure's debug option. + +AC_DEFUN([CURL_SET_COMPILER_DEBUG_OPTS], [ + AC_REQUIRE([CURL_CHECK_OPTION_DEBUG])dnl + AC_REQUIRE([CURL_CHECK_COMPILER])dnl + AC_REQUIRE([CURL_SHFUNC_SQUEEZE])dnl + # + if test "$compiler_id" != "unknown"; then + # + tmp_save_CFLAGS="$CFLAGS" + tmp_save_CPPFLAGS="$CPPFLAGS" + # + tmp_options="" + tmp_CFLAGS="$CFLAGS" + tmp_CPPFLAGS="$CPPFLAGS" + # + if test "$want_debug" = "yes"; then + AC_MSG_CHECKING([if compiler accepts debug enabling options]) + tmp_options="$flags_dbg_yes" + fi + # + if test "$flags_prefer_cppflags" = "yes"; then + CPPFLAGS="$tmp_CPPFLAGS $tmp_options" + CFLAGS="$tmp_CFLAGS" + else + CPPFLAGS="$tmp_CPPFLAGS" + CFLAGS="$tmp_CFLAGS $tmp_options" + fi + squeeze CPPFLAGS + squeeze CFLAGS + fi +]) + + +dnl CURL_SET_COMPILER_OPTIMIZE_OPTS +dnl ------------------------------------------------- +dnl Sets compiler specific options/flags which depend +dnl on configure's optimize option. + +AC_DEFUN([CURL_SET_COMPILER_OPTIMIZE_OPTS], [ + AC_REQUIRE([CURL_CHECK_OPTION_OPTIMIZE])dnl + AC_REQUIRE([CURL_CHECK_COMPILER])dnl + AC_REQUIRE([CURL_SHFUNC_SQUEEZE])dnl + # + if test "$compiler_id" != "unknown"; then + # + tmp_save_CFLAGS="$CFLAGS" + tmp_save_CPPFLAGS="$CPPFLAGS" + # + tmp_options="" + tmp_CFLAGS="$CFLAGS" + tmp_CPPFLAGS="$CPPFLAGS" + honor_optimize_option="yes" + # + dnl If optimization request setting has not been explicitly specified, + dnl it has been derived from the debug setting and initially assumed. + dnl This initially assumed optimizer setting will finally be ignored + dnl if CFLAGS or CPPFLAGS already hold optimizer flags. This implies + dnl that an initially assumed optimizer setting might not be honored. + # + if test "$want_optimize" = "assume_no" || + test "$want_optimize" = "assume_yes"; then + AC_MSG_CHECKING([if compiler optimizer assumed setting might be used]) + CURL_VAR_MATCH_IFELSE([tmp_CFLAGS],[$flags_opt_all],[ + honor_optimize_option="no" + ]) + CURL_VAR_MATCH_IFELSE([tmp_CPPFLAGS],[$flags_opt_all],[ + honor_optimize_option="no" + ]) + AC_MSG_RESULT([$honor_optimize_option]) + if test "$honor_optimize_option" = "yes"; then + if test "$want_optimize" = "assume_yes"; then + want_optimize="yes" + fi + if test "$want_optimize" = "assume_no"; then + want_optimize="no" + fi + fi + fi + # + if test "$honor_optimize_option" = "yes"; then + CURL_VAR_STRIP([tmp_CFLAGS],[$flags_opt_all]) + CURL_VAR_STRIP([tmp_CPPFLAGS],[$flags_opt_all]) + if test "$want_optimize" = "yes"; then + AC_MSG_CHECKING([if compiler accepts optimizer enabling options]) + tmp_options="$flags_opt_yes" + fi + if test "$want_optimize" = "no"; then + AC_MSG_CHECKING([if compiler accepts optimizer disabling options]) + tmp_options="$flags_opt_off" + fi + if test "$flags_prefer_cppflags" = "yes"; then + CPPFLAGS="$tmp_CPPFLAGS $tmp_options" + CFLAGS="$tmp_CFLAGS" + else + CPPFLAGS="$tmp_CPPFLAGS" + CFLAGS="$tmp_CFLAGS $tmp_options" + fi + squeeze CPPFLAGS + squeeze CFLAGS + CURL_COMPILER_WORKS_IFELSE([ + AC_MSG_RESULT([yes]) + AC_MSG_NOTICE([compiler options added: $tmp_options]) + ],[ + AC_MSG_RESULT([no]) + AC_MSG_WARN([compiler options rejected: $tmp_options]) + dnl restore initial settings + CPPFLAGS="$tmp_save_CPPFLAGS" + CFLAGS="$tmp_save_CFLAGS" + ]) + fi + # + fi +]) + + +dnl CURL_SET_COMPILER_WARNING_OPTS +dnl ------------------------------------------------- +dnl Sets compiler options/flags which depend on +dnl configure's warnings given option. + +AC_DEFUN([CURL_SET_COMPILER_WARNING_OPTS], [ + AC_REQUIRE([CURL_CHECK_OPTION_WARNINGS])dnl + AC_REQUIRE([CURL_CHECK_COMPILER])dnl + AC_REQUIRE([CURL_SHFUNC_SQUEEZE])dnl + # + if test "$compiler_id" != "unknown"; then + # + tmp_save_CPPFLAGS="$CPPFLAGS" + tmp_save_CFLAGS="$CFLAGS" + tmp_CPPFLAGS="" + tmp_CFLAGS="" + # + case "$compiler_id" in + # + CLANG) + # + if test "$want_warnings" = "yes"; then + tmp_CFLAGS="$tmp_CFLAGS -pedantic" + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [all extra]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [pointer-arith write-strings]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [shadow]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [inline nested-externs]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [missing-declarations]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [missing-prototypes]) + tmp_CFLAGS="$tmp_CFLAGS -Wno-long-long" + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [float-equal]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [sign-compare]) + tmp_CFLAGS="$tmp_CFLAGS -Wno-multichar" + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [undef]) + tmp_CFLAGS="$tmp_CFLAGS -Wno-format-nonliteral" + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [endif-labels strict-prototypes]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [declaration-after-statement]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [cast-align]) + tmp_CFLAGS="$tmp_CFLAGS -Wno-system-headers" + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [shorten-64-to-32]) + # + dnl Only clang 1.1 or later + if test "$compiler_num" -ge "101"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [unused]) + fi + # + dnl Only clang 2.7 or later + if test "$compiler_num" -ge "207"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [address]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [attributes]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [bad-function-cast]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [conversion]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [div-by-zero format-security]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [empty-body]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [missing-field-initializers]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [missing-noreturn]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [old-style-definition]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [redundant-decls]) + # CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [switch-enum]) # Not used because this basically disallows default case + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [type-limits]) + # CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [unused-macros]) # Not practical + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [unreachable-code unused-parameter]) + fi + # + dnl Only clang 2.8 or later + if test "$compiler_num" -ge "208"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [ignored-qualifiers]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [vla]) + fi + # + dnl Only clang 2.9 or later + if test "$compiler_num" -ge "209"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [sign-conversion]) + tmp_CFLAGS="$tmp_CFLAGS -Wno-error=sign-conversion" # FIXME + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [shift-sign-overflow]) + # CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [padded]) # Not used because we cannot change public structs + fi + # + dnl Only clang 3.0 or later + if test "$compiler_num" -ge "300"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [language-extension-token]) + tmp_CFLAGS="$tmp_CFLAGS -Wformat=2" + fi + # + dnl Only clang 3.2 or later + if test "$compiler_num" -ge "302"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [enum-conversion]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [sometimes-uninitialized]) + case $host_os in + cygwin* | mingw*) + dnl skip missing-variable-declarations warnings for cygwin and + dnl mingw because the libtool wrapper executable causes them + ;; + *) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [missing-variable-declarations]) + ;; + esac + fi + # + dnl Only clang 3.4 or later + if test "$compiler_num" -ge "304"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [header-guard]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [unused-const-variable]) + fi + # + dnl Only clang 3.5 or later + if test "$compiler_num" -ge "305"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [pragmas]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [unreachable-code-break]) + fi + # + dnl Only clang 3.6 or later + if test "$compiler_num" -ge "306"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [double-promotion]) + fi + # + dnl Only clang 3.9 or later + if test "$compiler_num" -ge "309"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [comma]) + # avoid the varargs warning, fixed in 4.0 + # https://bugs.llvm.org/show_bug.cgi?id=29140 + if test "$compiler_num" -lt "400"; then + tmp_CFLAGS="$tmp_CFLAGS -Wno-varargs" + fi + fi + dnl clang 7 or later + if test "$compiler_num" -ge "700"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [assign-enum]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [extra-semi-stmt]) + fi + dnl clang 10 or later + if test "$compiler_num" -ge "1000"; then + tmp_CFLAGS="$tmp_CFLAGS -Wimplicit-fallthrough" # we have silencing markup for clang 10.0 and above only + fi + fi + dnl Disable pointer to bool conversion warnings since they cause + dnl lib/securetransp.c cause several warnings for checks we want. + dnl This option should be placed after -Wconversion. + tmp_CFLAGS="$tmp_CFLAGS -Wno-pointer-bool-conversion" + ;; + # + DEC_C) + # + if test "$want_warnings" = "yes"; then + dnl Select a higher warning level than default level2 + tmp_CFLAGS="$tmp_CFLAGS -msg_enable level3" + fi + ;; + # + GNU_C) + # + if test "$want_warnings" = "yes"; then + # + dnl Do not enable -pedantic when cross-compiling with a gcc older + dnl than 3.0, to avoid warnings from third party system headers. + if test "x$cross_compiling" != "xyes" || + test "$compiler_num" -ge "300"; then + tmp_CFLAGS="$tmp_CFLAGS -pedantic" + fi + # + dnl Set of options we believe *ALL* gcc versions support: + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [all]) + tmp_CFLAGS="$tmp_CFLAGS -W" + # + dnl Only gcc 1.4 or later + if test "$compiler_num" -ge "104"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [pointer-arith write-strings]) + dnl If not cross-compiling with a gcc older than 3.0 + if test "x$cross_compiling" != "xyes" || + test "$compiler_num" -ge "300"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [unused shadow]) + fi + fi + # + dnl Only gcc 2.7 or later + if test "$compiler_num" -ge "207"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [inline nested-externs]) + dnl If not cross-compiling with a gcc older than 3.0 + if test "x$cross_compiling" != "xyes" || + test "$compiler_num" -ge "300"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [missing-declarations]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [missing-prototypes]) + fi + fi + # + dnl Only gcc 2.95 or later + if test "$compiler_num" -ge "295"; then + tmp_CFLAGS="$tmp_CFLAGS -Wno-long-long" + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [bad-function-cast]) + fi + # + dnl Only gcc 2.96 or later + if test "$compiler_num" -ge "296"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [float-equal]) + tmp_CFLAGS="$tmp_CFLAGS -Wno-multichar" + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [sign-compare]) + dnl -Wundef used only if gcc is 2.96 or later since we get + dnl lots of "`_POSIX_C_SOURCE' is not defined" in system + dnl headers with gcc 2.95.4 on FreeBSD 4.9 + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [undef]) + fi + # + dnl Only gcc 2.97 or later + if test "$compiler_num" -ge "297"; then + tmp_CFLAGS="$tmp_CFLAGS -Wno-format-nonliteral" + fi + # + dnl Only gcc 3.0 or later + if test "$compiler_num" -ge "300"; then + dnl -Wunreachable-code seems totally unreliable on my gcc 3.3.2 on + dnl on i686-Linux as it gives us heaps with false positives. + dnl Also, on gcc 4.0.X it is totally unbearable and complains all + dnl over making it unusable for generic purposes. Let's not use it. + tmp_CFLAGS="$tmp_CFLAGS" + fi + # + dnl Only gcc 3.3 or later + if test "$compiler_num" -ge "303"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [endif-labels strict-prototypes]) + fi + # + dnl Only gcc 3.4 or later + if test "$compiler_num" -ge "304"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [declaration-after-statement]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [old-style-definition]) + fi + # + dnl Only gcc 4.0 or later + if test "$compiler_num" -ge "400"; then + tmp_CFLAGS="$tmp_CFLAGS -Wstrict-aliasing=3" + fi + # + dnl Only gcc 4.1 or later + if test "$compiler_num" -ge "401"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [attributes]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [div-by-zero format-security]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [missing-field-initializers]) + case $host in + *-*-msys*) + ;; + *) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [missing-noreturn]) # Seen to clash with libtool-generated stub code + ;; + esac + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [unreachable-code unused-parameter]) + # CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [padded]) # Not used because we cannot change public structs + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [pragmas]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [redundant-decls]) + # CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [switch-enum]) # Not used because this basically disallows default case + # CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [unused-macros]) # Not practical + fi + # + dnl Only gcc 4.2 or later + if test "$compiler_num" -ge "402"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [cast-align]) + fi + # + dnl Only gcc 4.3 or later + if test "$compiler_num" -ge "403"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [address]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [type-limits old-style-declaration]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [missing-parameter-type empty-body]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [clobbered ignored-qualifiers]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [conversion trampolines]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [sign-conversion]) + tmp_CFLAGS="$tmp_CFLAGS -Wno-error=sign-conversion" # FIXME + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [vla]) + dnl required for -Warray-bounds, included in -Wall + tmp_CFLAGS="$tmp_CFLAGS -ftree-vrp" + fi + # + dnl Only gcc 4.5 or later + if test "$compiler_num" -ge "405"; then + dnl Only windows targets + if test "$curl_cv_native_windows" = "yes"; then + tmp_CFLAGS="$tmp_CFLAGS -Wno-pedantic-ms-format" + fi + fi + # + dnl Only gcc 4.6 or later + if test "$compiler_num" -ge "406"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [double-promotion]) + fi + # + dnl only gcc 4.8 or later + if test "$compiler_num" -ge "408"; then + tmp_CFLAGS="$tmp_CFLAGS -Wformat=2" + fi + # + dnl Only gcc 5 or later + if test "$compiler_num" -ge "500"; then + tmp_CFLAGS="$tmp_CFLAGS -Warray-bounds=2" + fi + # + dnl Only gcc 6 or later + if test "$compiler_num" -ge "600"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [shift-negative-value]) + tmp_CFLAGS="$tmp_CFLAGS -Wshift-overflow=2" + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [null-dereference]) + tmp_CFLAGS="$tmp_CFLAGS -fdelete-null-pointer-checks" + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [duplicated-cond]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [unused-const-variable]) + fi + # + dnl Only gcc 7 or later + if test "$compiler_num" -ge "700"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [duplicated-branches]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [restrict]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [alloc-zero]) + tmp_CFLAGS="$tmp_CFLAGS -Wformat-overflow=2" + tmp_CFLAGS="$tmp_CFLAGS -Wformat-truncation=2" + tmp_CFLAGS="$tmp_CFLAGS -Wimplicit-fallthrough" + fi + # + dnl Only gcc 10 or later + if test "$compiler_num" -ge "1000"; then + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [arith-conversion]) + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [enum-conversion]) + fi + # + fi + # + dnl Do not issue warnings for code in system include paths. + if test "$compiler_num" -ge "300"; then + tmp_CFLAGS="$tmp_CFLAGS -Wno-system-headers" + else + dnl When cross-compiling with a gcc older than 3.0, disable + dnl some warnings triggered on third party system headers. + if test "x$cross_compiling" = "xyes"; then + if test "$compiler_num" -ge "104"; then + dnl gcc 1.4 or later + tmp_CFLAGS="$tmp_CFLAGS -Wno-unused -Wno-shadow" + fi + if test "$compiler_num" -ge "207"; then + dnl gcc 2.7 or later + tmp_CFLAGS="$tmp_CFLAGS -Wno-missing-declarations" + tmp_CFLAGS="$tmp_CFLAGS -Wno-missing-prototypes" + fi + fi + fi + ;; + # + HP_UX_C) + # + if test "$want_warnings" = "yes"; then + dnl Issue all warnings + tmp_CFLAGS="$tmp_CFLAGS +w1" + fi + ;; + # + IBM_C) + # + dnl Placeholder + tmp_CFLAGS="$tmp_CFLAGS" + ;; + # + INTEL_UNIX_C) + # + if test "$want_warnings" = "yes"; then + if test "$compiler_num" -gt "600"; then + dnl Show errors, warnings, and remarks + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wall -w2" + dnl Perform extra compile-time code checking + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wcheck" + dnl Warn on nested comments + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wcomment" + dnl Show warnings relative to deprecated features + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wdeprecated" + dnl Enable warnings for missing prototypes + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wmissing-prototypes" + dnl Enable warnings for 64-bit portability issues + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wp64" + dnl Enable warnings for questionable pointer arithmetic + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wpointer-arith" + dnl Check for function return typw issues + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wreturn-type" + dnl Warn on variable declarations hiding a previous one + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wshadow" + dnl Warn when a variable is used before initialized + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wuninitialized" + dnl Warn if a declared function is not used + tmp_CPPFLAGS="$tmp_CPPFLAGS -Wunused-function" + fi + fi + dnl Disable using EBP register in optimizations + tmp_CFLAGS="$tmp_CFLAGS -fno-omit-frame-pointer" + dnl Disable use of ANSI C aliasing rules in optimizations + tmp_CFLAGS="$tmp_CFLAGS -fno-strict-aliasing" + dnl Value-safe optimizations on floating-point data + tmp_CFLAGS="$tmp_CFLAGS -fp-model precise" + ;; + # + INTEL_WINDOWS_C) + # + dnl Placeholder + tmp_CFLAGS="$tmp_CFLAGS" + ;; + # + SGI_MIPS_C) + # + if test "$want_warnings" = "yes"; then + dnl Perform stricter semantic and lint-like checks + tmp_CFLAGS="$tmp_CFLAGS -fullwarn" + fi + ;; + # + SGI_MIPSPRO_C) + # + if test "$want_warnings" = "yes"; then + dnl Perform stricter semantic and lint-like checks + tmp_CFLAGS="$tmp_CFLAGS -fullwarn" + dnl Disable some remarks + dnl #1209: controlling expression is constant + tmp_CFLAGS="$tmp_CFLAGS -woff 1209" + fi + ;; + # + SUNPRO_C) + # + if test "$want_warnings" = "yes"; then + dnl Perform stricter semantic and lint-like checks + tmp_CFLAGS="$tmp_CFLAGS -v" + fi + ;; + # + TINY_C) + # + if test "$want_warnings" = "yes"; then + dnl Activate all warnings + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [all]) + dnl Make string constants be of type const char * + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [write-strings]) + dnl Warn use of unsupported GCC features ignored by TCC + CURL_ADD_COMPILER_WARNINGS([tmp_CFLAGS], [unsupported]) + fi + ;; + # + esac + # + squeeze tmp_CPPFLAGS + squeeze tmp_CFLAGS + # + if test ! -z "$tmp_CFLAGS" || test ! -z "$tmp_CPPFLAGS"; then + AC_MSG_CHECKING([if compiler accepts strict warning options]) + CPPFLAGS="$tmp_save_CPPFLAGS $tmp_CPPFLAGS" + CFLAGS="$tmp_save_CFLAGS $tmp_CFLAGS" + squeeze CPPFLAGS + squeeze CFLAGS + CURL_COMPILER_WORKS_IFELSE([ + AC_MSG_RESULT([yes]) + AC_MSG_NOTICE([compiler options added: $tmp_CFLAGS $tmp_CPPFLAGS]) + ],[ + AC_MSG_RESULT([no]) + AC_MSG_WARN([compiler options rejected: $tmp_CFLAGS $tmp_CPPFLAGS]) + dnl restore initial settings + CPPFLAGS="$tmp_save_CPPFLAGS" + CFLAGS="$tmp_save_CFLAGS" + ]) + fi + # + fi +]) + + +dnl CURL_SHFUNC_SQUEEZE +dnl ------------------------------------------------- +dnl Declares a shell function squeeze() which removes +dnl redundant whitespace out of a shell variable. + +AC_DEFUN([CURL_SHFUNC_SQUEEZE], [ +squeeze() { + _sqz_result="" + eval _sqz_input=\[$][$]1 + for _sqz_token in $_sqz_input; do + if test -z "$_sqz_result"; then + _sqz_result="$_sqz_token" + else + _sqz_result="$_sqz_result $_sqz_token" + fi + done + eval [$]1=\$_sqz_result + return 0 +} +]) + + +dnl CURL_CHECK_CURLDEBUG +dnl ------------------------------------------------- +dnl Settings which depend on configure's curldebug given +dnl option, and other additional configure pre-requisites. +dnl Actually the curl debug memory tracking feature can +dnl only be used/enabled when libcurl is built as a static +dnl library or as a shared one on those systems on which +dnl shared libraries support undefined symbols. + +AC_DEFUN([CURL_CHECK_CURLDEBUG], [ + AC_REQUIRE([XC_LIBTOOL])dnl + AC_REQUIRE([CURL_SHFUNC_SQUEEZE])dnl + supports_curldebug="unknown" + if test "$want_curldebug" = "yes"; then + if test "x$enable_shared" != "xno" && + test "x$enable_shared" != "xyes"; then + AC_MSG_WARN([unknown enable_shared setting.]) + supports_curldebug="no" + fi + if test "x$enable_static" != "xno" && + test "x$enable_static" != "xyes"; then + AC_MSG_WARN([unknown enable_static setting.]) + supports_curldebug="no" + fi + if test "$supports_curldebug" != "no"; then + if test "$enable_shared" = "yes" && + test "x$xc_lt_shlib_use_no_undefined" = 'xyes'; then + supports_curldebug="no" + AC_MSG_WARN([shared library does not support undefined symbols.]) + fi + fi + fi + # + if test "$want_curldebug" = "yes"; then + AC_MSG_CHECKING([if curl debug memory tracking can be enabled]) + test "$supports_curldebug" = "no" || supports_curldebug="yes" + AC_MSG_RESULT([$supports_curldebug]) + if test "$supports_curldebug" = "no"; then + AC_MSG_WARN([cannot enable curl debug memory tracking.]) + want_curldebug="no" + fi + fi +]) + + + +dnl CURL_CHECK_COMPILER_HALT_ON_ERROR +dnl ------------------------------------------------- +dnl Verifies if the compiler actually halts after the +dnl compilation phase without generating any object +dnl code file, when the source compiles with errors. + +AC_DEFUN([CURL_CHECK_COMPILER_HALT_ON_ERROR], [ + AC_MSG_CHECKING([if compiler halts on compilation errors]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + ]],[[ + force compilation error + ]]) + ],[ + AC_MSG_RESULT([no]) + AC_MSG_ERROR([compiler does not halt on compilation errors.]) + ],[ + AC_MSG_RESULT([yes]) + ]) +]) + + +dnl CURL_CHECK_COMPILER_ARRAY_SIZE_NEGATIVE +dnl ------------------------------------------------- +dnl Verifies if the compiler actually halts after the +dnl compilation phase without generating any object +dnl code file, when the source code tries to define a +dnl type for a constant array with negative dimension. + +AC_DEFUN([CURL_CHECK_COMPILER_ARRAY_SIZE_NEGATIVE], [ + AC_REQUIRE([CURL_CHECK_COMPILER_HALT_ON_ERROR])dnl + AC_MSG_CHECKING([if compiler halts on negative sized arrays]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + typedef char bad_t[sizeof(char) == sizeof(int) ? -1 : -1 ]; + ]],[[ + bad_t dummy; + ]]) + ],[ + AC_MSG_RESULT([no]) + AC_MSG_ERROR([compiler does not halt on negative sized arrays.]) + ],[ + AC_MSG_RESULT([yes]) + ]) +]) + + +dnl CURL_CHECK_COMPILER_STRUCT_MEMBER_SIZE +dnl ------------------------------------------------- +dnl Verifies if the compiler is capable of handling the +dnl size of a struct member, struct which is a function +dnl result, as a compilation-time condition inside the +dnl type definition of a constant array. + +AC_DEFUN([CURL_CHECK_COMPILER_STRUCT_MEMBER_SIZE], [ + AC_REQUIRE([CURL_CHECK_COMPILER_ARRAY_SIZE_NEGATIVE])dnl + AC_MSG_CHECKING([if compiler struct member size checking works]) + tst_compiler_check_one_works="unknown" + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + struct mystruct { + int mi; + char mc; + struct mystruct *next; + }; + struct mystruct myfunc(); + typedef char good_t1[sizeof(myfunc().mi) == sizeof(int) ? 1 : -1 ]; + typedef char good_t2[sizeof(myfunc().mc) == sizeof(char) ? 1 : -1 ]; + ]],[[ + good_t1 dummy1; + good_t2 dummy2; + ]]) + ],[ + tst_compiler_check_one_works="yes" + ],[ + tst_compiler_check_one_works="no" + sed 's/^/cc-src: /' conftest.$ac_ext >&6 + sed 's/^/cc-err: /' conftest.err >&6 + ]) + tst_compiler_check_two_works="unknown" + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + struct mystruct { + int mi; + char mc; + struct mystruct *next; + }; + struct mystruct myfunc(); + typedef char bad_t1[sizeof(myfunc().mi) != sizeof(int) ? 1 : -1 ]; + typedef char bad_t2[sizeof(myfunc().mc) != sizeof(char) ? 1 : -1 ]; + ]],[[ + bad_t1 dummy1; + bad_t2 dummy2; + ]]) + ],[ + tst_compiler_check_two_works="no" + ],[ + tst_compiler_check_two_works="yes" + ]) + if test "$tst_compiler_check_one_works" = "yes" && + test "$tst_compiler_check_two_works" = "yes"; then + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + AC_MSG_ERROR([compiler fails struct member size checking.]) + fi +]) + + +dnl CURL_CHECK_COMPILER_SYMBOL_HIDING +dnl ------------------------------------------------- +dnl Verify if compiler supports hiding library internal symbols, setting +dnl shell variable supports_symbol_hiding value as appropriate, as well as +dnl variables symbol_hiding_CFLAGS and symbol_hiding_EXTERN when supported. + +AC_DEFUN([CURL_CHECK_COMPILER_SYMBOL_HIDING], [ + AC_REQUIRE([CURL_CHECK_COMPILER])dnl + AC_BEFORE([$0],[CURL_CONFIGURE_SYMBOL_HIDING])dnl + AC_MSG_CHECKING([if compiler supports hiding library internal symbols]) + supports_symbol_hiding="no" + symbol_hiding_CFLAGS="" + symbol_hiding_EXTERN="" + tmp_CFLAGS="" + tmp_EXTERN="" + case "$compiler_id" in + CLANG) + dnl All versions of clang support -fvisibility= + tmp_EXTERN="__attribute__ ((__visibility__ (\"default\")))" + tmp_CFLAGS="-fvisibility=hidden" + supports_symbol_hiding="yes" + ;; + GNU_C) + dnl Only gcc 3.4 or later + if test "$compiler_num" -ge "304"; then + if $CC --help --verbose 2>/dev/null | grep fvisibility= >/dev/null ; then + tmp_EXTERN="__attribute__ ((__visibility__ (\"default\")))" + tmp_CFLAGS="-fvisibility=hidden" + supports_symbol_hiding="yes" + fi + fi + ;; + INTEL_UNIX_C) + dnl Only icc 9.0 or later + if test "$compiler_num" -ge "900"; then + if $CC --help --verbose 2>&1 | grep fvisibility= > /dev/null ; then + tmp_save_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS -fvisibility=hidden" + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ +# include + ]],[[ + printf("icc fvisibility bug test"); + ]]) + ],[ + tmp_EXTERN="__attribute__ ((__visibility__ (\"default\")))" + tmp_CFLAGS="-fvisibility=hidden" + supports_symbol_hiding="yes" + ]) + CFLAGS="$tmp_save_CFLAGS" + fi + fi + ;; + SUNPRO_C) + if $CC 2>&1 | grep flags >/dev/null && $CC -flags | grep xldscope= >/dev/null ; then + tmp_EXTERN="__global" + tmp_CFLAGS="-xldscope=hidden" + supports_symbol_hiding="yes" + fi + ;; + esac + if test "$supports_symbol_hiding" = "yes"; then + tmp_save_CFLAGS="$CFLAGS" + CFLAGS="$tmp_save_CFLAGS $tmp_CFLAGS" + squeeze CFLAGS + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $tmp_EXTERN char *dummy(char *buff); + char *dummy(char *buff) + { + if(buff) + return ++buff; + else + return buff; + } + ]],[[ + char b[16]; + char *r = dummy(&b[0]); + if(r) + return (int)*r; + ]]) + ],[ + supports_symbol_hiding="yes" + if test -f conftest.err; then + grep 'visibility' conftest.err >/dev/null + if test "$?" -eq "0"; then + supports_symbol_hiding="no" + fi + fi + ],[ + supports_symbol_hiding="no" + echo " " >&6 + sed 's/^/cc-src: /' conftest.$ac_ext >&6 + sed 's/^/cc-err: /' conftest.err >&6 + echo " " >&6 + ]) + CFLAGS="$tmp_save_CFLAGS" + fi + if test "$supports_symbol_hiding" = "yes"; then + AC_MSG_RESULT([yes]) + symbol_hiding_CFLAGS="$tmp_CFLAGS" + symbol_hiding_EXTERN="$tmp_EXTERN" + else + AC_MSG_RESULT([no]) + fi +]) + + +dnl CURL_CHECK_COMPILER_PROTOTYPE_MISMATCH +dnl ------------------------------------------------- +dnl Verifies if the compiler actually halts after the +dnl compilation phase without generating any object +dnl code file, when the source code tries to redefine +dnl a prototype which does not match previous one. + +AC_DEFUN([CURL_CHECK_COMPILER_PROTOTYPE_MISMATCH], [ + AC_REQUIRE([CURL_CHECK_COMPILER_HALT_ON_ERROR])dnl + AC_MSG_CHECKING([if compiler halts on function prototype mismatch]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +# include + int rand(int n); + int rand(int n) + { + if(n) + return ++n; + else + return n; + } + ]],[[ + int i[2]={0,0}; + int j = rand(i[0]); + if(j) + return j; + ]]) + ],[ + AC_MSG_RESULT([no]) + AC_MSG_ERROR([compiler does not halt on function prototype mismatch.]) + ],[ + AC_MSG_RESULT([yes]) + ]) +]) + + +dnl CURL_VAR_MATCH (VARNAME, VALUE) +dnl ------------------------------------------------- +dnl Verifies if shell variable VARNAME contains VALUE. +dnl Contents of variable VARNAME and VALUE are handled +dnl as whitespace separated lists of words. If at least +dnl one word of VALUE is present in VARNAME the match +dnl is considered positive, otherwise false. + +AC_DEFUN([CURL_VAR_MATCH], [ + ac_var_match_word="no" + for word1 in $[$1]; do + for word2 in [$2]; do + if test "$word1" = "$word2"; then + ac_var_match_word="yes" + fi + done + done +]) + + +dnl CURL_VAR_MATCH_IFELSE (VARNAME, VALUE, +dnl [ACTION-IF-MATCH], [ACTION-IF-NOT-MATCH]) +dnl ------------------------------------------------- +dnl This performs a CURL_VAR_MATCH check and executes +dnl first branch if the match is positive, otherwise +dnl the second branch is executed. + +AC_DEFUN([CURL_VAR_MATCH_IFELSE], [ + CURL_VAR_MATCH([$1],[$2]) + if test "$ac_var_match_word" = "yes"; then + ifelse($3,,:,[$3]) + ifelse($4,,,[else + $4]) + fi +]) + + +dnl CURL_VAR_STRIP (VARNAME, VALUE) +dnl ------------------------------------------------- +dnl Contents of variable VARNAME and VALUE are handled +dnl as whitespace separated lists of words. Each word +dnl from VALUE is removed from VARNAME when present. + +AC_DEFUN([CURL_VAR_STRIP], [ + AC_REQUIRE([CURL_SHFUNC_SQUEEZE])dnl + ac_var_stripped="" + for word1 in $[$1]; do + ac_var_strip_word="no" + for word2 in [$2]; do + if test "$word1" = "$word2"; then + ac_var_strip_word="yes" + fi + done + if test "$ac_var_strip_word" = "no"; then + ac_var_stripped="$ac_var_stripped $word1" + fi + done + dnl squeeze whitespace out of result + [$1]="$ac_var_stripped" + squeeze [$1] +]) + +dnl CURL_ADD_COMPILER_WARNINGS (WARNING-LIST, NEW-WARNINGS) +dnl ------------------------------------------------------- +dnl Contents of variable WARNING-LIST and NEW-WARNINGS are +dnl handled as whitespace separated lists of words. +dnl Add each compiler warning from NEW-WARNINGS that has not +dnl been disabled via CFLAGS to WARNING-LIST. + +AC_DEFUN([CURL_ADD_COMPILER_WARNINGS], [ + AC_REQUIRE([CURL_SHFUNC_SQUEEZE])dnl + ac_var_added_warnings="" + for warning in [$2]; do + CURL_VAR_MATCH(CFLAGS, [-Wno-$warning -W$warning]) + if test "$ac_var_match_word" = "no"; then + ac_var_added_warnings="$ac_var_added_warnings -W$warning" + fi + done + dnl squeeze whitespace out of result + [$1]="$[$1] $ac_var_added_warnings" + squeeze [$1] +]) diff --git a/third_party/curl/m4/curl-confopts.m4 b/third_party/curl/m4/curl-confopts.m4 new file mode 100644 index 0000000..5c307fc --- /dev/null +++ b/third_party/curl/m4/curl-confopts.m4 @@ -0,0 +1,705 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +# File version for 'aclocal' use. Keep it a single number. +# serial 19 + +dnl CURL_CHECK_OPTION_THREADED_RESOLVER +dnl ------------------------------------------------- +dnl Verify if configure has been invoked with option +dnl --enable-threaded-resolver or --disable-threaded-resolver, and +dnl set shell variable want_thres as appropriate. + +AC_DEFUN([CURL_CHECK_OPTION_THREADED_RESOLVER], [ + AC_MSG_CHECKING([whether to enable the threaded resolver]) + OPT_THRES="default" + AC_ARG_ENABLE(threaded_resolver, +AS_HELP_STRING([--enable-threaded-resolver],[Enable threaded resolver]) +AS_HELP_STRING([--disable-threaded-resolver],[Disable threaded resolver]), + OPT_THRES=$enableval) + case "$OPT_THRES" in + no) + dnl --disable-threaded-resolver option used + want_thres="no" + ;; + *) + dnl configure option not specified + want_thres="yes" + ;; + esac + AC_MSG_RESULT([$want_thres]) +]) + +dnl CURL_CHECK_OPTION_ARES +dnl ------------------------------------------------- +dnl Verify if configure has been invoked with option +dnl --enable-ares or --disable-ares, and +dnl set shell variable want_ares as appropriate. + +AC_DEFUN([CURL_CHECK_OPTION_ARES], [ +dnl AC_BEFORE([$0],[CURL_CHECK_OPTION_THREADS])dnl + AC_BEFORE([$0],[CURL_CHECK_LIB_ARES])dnl + AC_MSG_CHECKING([whether to enable c-ares for DNS lookups]) + OPT_ARES="default" + AC_ARG_ENABLE(ares, +AS_HELP_STRING([--enable-ares@<:@=PATH@:>@],[Enable c-ares for DNS lookups]) +AS_HELP_STRING([--disable-ares],[Disable c-ares for DNS lookups]), + OPT_ARES=$enableval) + case "$OPT_ARES" in + no) + dnl --disable-ares option used + want_ares="no" + ;; + default) + dnl configure option not specified + want_ares="no" + ;; + *) + dnl --enable-ares option used + want_ares="yes" + if test -n "$enableval" && test "$enableval" != "yes"; then + want_ares_path="$enableval" + fi + ;; + esac + AC_MSG_RESULT([$want_ares]) +]) + + +dnl CURL_CHECK_OPTION_CURLDEBUG +dnl ------------------------------------------------- +dnl Verify if configure has been invoked with option +dnl --enable-curldebug or --disable-curldebug, and set +dnl shell variable want_curldebug value as appropriate. + +AC_DEFUN([CURL_CHECK_OPTION_CURLDEBUG], [ + AC_BEFORE([$0],[CURL_CHECK_CURLDEBUG])dnl + AC_MSG_CHECKING([whether to enable curl debug memory tracking]) + OPT_CURLDEBUG_BUILD="default" + AC_ARG_ENABLE(curldebug, +AS_HELP_STRING([--enable-curldebug],[Enable curl debug memory tracking]) +AS_HELP_STRING([--disable-curldebug],[Disable curl debug memory tracking]), + OPT_CURLDEBUG_BUILD=$enableval) + case "$OPT_CURLDEBUG_BUILD" in + no) + dnl --disable-curldebug option used + want_curldebug="no" + AC_MSG_RESULT([no]) + ;; + default) + dnl configure's curldebug option not specified. Initially we will + dnl handle this as a request to use the same setting as option + dnl --enable-debug. IOW, initially, for debug-enabled builds + dnl this will be handled as a request to enable curldebug if + dnl possible, and for debug-disabled builds this will be handled + dnl as a request to disable curldebug. + if test "$want_debug" = "yes"; then + AC_MSG_RESULT([(assumed) yes]) + AC_DEFINE(CURLDEBUG, 1, [to enable curl debug memory tracking]) + else + AC_MSG_RESULT([no]) + fi + want_curldebug_assumed="yes" + want_curldebug="$want_debug" + ;; + *) + dnl --enable-curldebug option used. + dnl The use of this option value is a request to enable curl's + dnl debug memory tracking for the libcurl library. This can only + dnl be done when some requisites are simultaneously satisfied. + dnl Later on, these requisites are verified and if they are not + dnl fully satisfied the option will be ignored and act as if + dnl --disable-curldebug had been given setting shell variable + dnl want_curldebug to 'no'. + want_curldebug="yes" + AC_DEFINE(CURLDEBUG, 1, [to enable curl debug memory tracking]) + AC_MSG_RESULT([yes]) + ;; + esac +]) + + +dnl CURL_CHECK_OPTION_DEBUG +dnl ------------------------------------------------- +dnl Verify if configure has been invoked with option +dnl --enable-debug or --disable-debug, and set shell +dnl variable want_debug value as appropriate. + +AC_DEFUN([CURL_CHECK_OPTION_DEBUG], [ + AC_BEFORE([$0],[CURL_CHECK_OPTION_WARNINGS])dnl + AC_BEFORE([$0],[CURL_CHECK_OPTION_CURLDEBUG])dnl + AC_BEFORE([$0],[XC_CHECK_PROG_CC])dnl + AC_MSG_CHECKING([whether to enable debug build options]) + OPT_DEBUG_BUILD="default" + AC_ARG_ENABLE(debug, +AS_HELP_STRING([--enable-debug],[Enable debug build options]) +AS_HELP_STRING([--disable-debug],[Disable debug build options]), + OPT_DEBUG_BUILD=$enableval) + case "$OPT_DEBUG_BUILD" in + no) + dnl --disable-debug option used + want_debug="no" + ;; + default) + dnl configure option not specified + want_debug="no" + ;; + *) + dnl --enable-debug option used + want_debug="yes" + AC_DEFINE(DEBUGBUILD, 1, [enable debug build options]) + ;; + esac + AC_MSG_RESULT([$want_debug]) +]) + +dnl CURL_CHECK_OPTION_OPTIMIZE +dnl ------------------------------------------------- +dnl Verify if configure has been invoked with option +dnl --enable-optimize or --disable-optimize, and set +dnl shell variable want_optimize value as appropriate. + +AC_DEFUN([CURL_CHECK_OPTION_OPTIMIZE], [ + AC_REQUIRE([CURL_CHECK_OPTION_DEBUG])dnl + AC_BEFORE([$0],[XC_CHECK_PROG_CC])dnl + AC_MSG_CHECKING([whether to enable compiler optimizer]) + OPT_COMPILER_OPTIMIZE="default" + AC_ARG_ENABLE(optimize, +AS_HELP_STRING([--enable-optimize],[Enable compiler optimizations]) +AS_HELP_STRING([--disable-optimize],[Disable compiler optimizations]), + OPT_COMPILER_OPTIMIZE=$enableval) + case "$OPT_COMPILER_OPTIMIZE" in + no) + dnl --disable-optimize option used. We will handle this as + dnl a request to disable compiler optimizations if possible. + dnl If the compiler is known CFLAGS and CPPFLAGS will be + dnl overridden, otherwise this can not be honored. + want_optimize="no" + AC_MSG_RESULT([no]) + ;; + default) + dnl configure's optimize option not specified. Initially we will + dnl handle this as a request contrary to configure's setting + dnl for --enable-debug. IOW, initially, for debug-enabled builds + dnl this will be handled as a request to disable optimizations if + dnl possible, and for debug-disabled builds this will be handled + dnl initially as a request to enable optimizations if possible. + dnl Finally, if the compiler is known and CFLAGS and CPPFLAGS do + dnl not have any optimizer flag the request will be honored, in + dnl any other case the request can not be honored. + dnl IOW, existing optimizer flags defined in CFLAGS or CPPFLAGS + dnl will always take precedence over any initial assumption. + if test "$want_debug" = "yes"; then + want_optimize="assume_no" + AC_MSG_RESULT([(assumed) no]) + else + want_optimize="assume_yes" + AC_MSG_RESULT([(assumed) yes]) + fi + ;; + *) + dnl --enable-optimize option used. We will handle this as + dnl a request to enable compiler optimizations if possible. + dnl If the compiler is known CFLAGS and CPPFLAGS will be + dnl overridden, otherwise this can not be honored. + want_optimize="yes" + AC_MSG_RESULT([yes]) + ;; + esac +]) + + +dnl CURL_CHECK_OPTION_SYMBOL_HIDING +dnl ------------------------------------------------- +dnl Verify if configure has been invoked with option +dnl --enable-symbol-hiding or --disable-symbol-hiding, +dnl setting shell variable want_symbol_hiding value. + +AC_DEFUN([CURL_CHECK_OPTION_SYMBOL_HIDING], [ + AC_BEFORE([$0],[CURL_CHECK_COMPILER_SYMBOL_HIDING])dnl + AC_MSG_CHECKING([whether to enable hiding of library internal symbols]) + OPT_SYMBOL_HIDING="default" + AC_ARG_ENABLE(symbol-hiding, +AS_HELP_STRING([--enable-symbol-hiding],[Enable hiding of library internal symbols]) +AS_HELP_STRING([--disable-symbol-hiding],[Disable hiding of library internal symbols]), + OPT_SYMBOL_HIDING=$enableval) + case "$OPT_SYMBOL_HIDING" in + no) + dnl --disable-symbol-hiding option used. + dnl This is an indication to not attempt hiding of library internal + dnl symbols. Default symbol visibility will be used, which normally + dnl exposes all library internal symbols. + want_symbol_hiding="no" + AC_MSG_RESULT([no]) + ;; + default) + dnl configure's symbol-hiding option not specified. + dnl Handle this as if --enable-symbol-hiding option was given. + want_symbol_hiding="yes" + AC_MSG_RESULT([yes]) + ;; + *) + dnl --enable-symbol-hiding option used. + dnl This is an indication to attempt hiding of library internal + dnl symbols. This is only supported on some compilers/linkers. + want_symbol_hiding="yes" + AC_MSG_RESULT([yes]) + ;; + esac +]) + + +dnl CURL_CHECK_OPTION_THREADS +dnl ------------------------------------------------- +dnl Verify if configure has been invoked with option +dnl --enable-threads or --disable-threads, and +dnl set shell variable want_threads as appropriate. + +dnl AC_DEFUN([CURL_CHECK_OPTION_THREADS], [ +dnl AC_BEFORE([$0],[CURL_CHECK_LIB_THREADS])dnl +dnl AC_MSG_CHECKING([whether to enable threads for DNS lookups]) +dnl OPT_THREADS="default" +dnl AC_ARG_ENABLE(threads, +dnl AS_HELP_STRING([--enable-threads@<:@=PATH@:>@],[Enable threads for DNS lookups]) +dnl AS_HELP_STRING([--disable-threads],[Disable threads for DNS lookups]), +dnl OPT_THREADS=$enableval) +dnl case "$OPT_THREADS" in +dnl no) +dnl dnl --disable-threads option used +dnl want_threads="no" +dnl AC_MSG_RESULT([no]) +dnl ;; +dnl default) +dnl dnl configure option not specified +dnl want_threads="no" +dnl AC_MSG_RESULT([(assumed) no]) +dnl ;; +dnl *) +dnl dnl --enable-threads option used +dnl want_threads="yes" +dnl want_threads_path="$enableval" +dnl AC_MSG_RESULT([yes]) +dnl ;; +dnl esac +dnl # +dnl if test "$want_ares" = "assume_yes"; then +dnl if test "$want_threads" = "yes"; then +dnl AC_MSG_CHECKING([whether to ignore c-ares enabling assumed setting]) +dnl AC_MSG_RESULT([yes]) +dnl want_ares="no" +dnl else +dnl want_ares="yes" +dnl fi +dnl fi +dnl if test "$want_threads" = "yes" && test "$want_ares" = "yes"; then +dnl AC_MSG_ERROR([options --enable-ares and --enable-threads are mutually exclusive, at most one may be enabled.]) +dnl fi +dnl ]) + +dnl CURL_CHECK_OPTION_RT +dnl ------------------------------------------------- +dnl Verify if configure has been invoked with option +dnl --disable-rt and set shell variable dontwant_rt +dnl as appropriate. + +AC_DEFUN([CURL_CHECK_OPTION_RT], [ + AC_BEFORE([$0], [CURL_CHECK_LIB_THREADS])dnl + AC_MSG_CHECKING([whether to disable dependency on -lrt]) + OPT_RT="default" + AC_ARG_ENABLE(rt, + AS_HELP_STRING([--disable-rt],[disable dependency on -lrt]), + OPT_RT=$enableval) + case "$OPT_RT" in + no) + dnl --disable-rt used (reverse logic) + dontwant_rt="yes" + AC_MSG_RESULT([yes]) + ;; + default) + dnl configure option not specified (so not disabled) + dontwant_rt="no" + AC_MSG_RESULT([(assumed no)]) + ;; + *) + dnl --enable-rt option used (reverse logic) + dontwant_rt="no" + AC_MSG_RESULT([no]) + ;; + esac +]) + +dnl CURL_CHECK_OPTION_WARNINGS +dnl ------------------------------------------------- +dnl Verify if configure has been invoked with option +dnl --enable-warnings or --disable-warnings, and set +dnl shell variable want_warnings as appropriate. + +AC_DEFUN([CURL_CHECK_OPTION_WARNINGS], [ + AC_REQUIRE([CURL_CHECK_OPTION_DEBUG])dnl + AC_BEFORE([$0],[CURL_CHECK_OPTION_WERROR])dnl + AC_BEFORE([$0],[XC_CHECK_PROG_CC])dnl + AC_MSG_CHECKING([whether to enable strict compiler warnings]) + OPT_COMPILER_WARNINGS="default" + AC_ARG_ENABLE(warnings, +AS_HELP_STRING([--enable-warnings],[Enable strict compiler warnings]) +AS_HELP_STRING([--disable-warnings],[Disable strict compiler warnings]), + OPT_COMPILER_WARNINGS=$enableval) + case "$OPT_COMPILER_WARNINGS" in + no) + dnl --disable-warnings option used + want_warnings="no" + ;; + default) + dnl configure option not specified, so + dnl use same setting as --enable-debug + want_warnings="$want_debug" + ;; + *) + dnl --enable-warnings option used + want_warnings="yes" + ;; + esac + AC_MSG_RESULT([$want_warnings]) +]) + +dnl CURL_CHECK_OPTION_WERROR +dnl ------------------------------------------------- +dnl Verify if configure has been invoked with option +dnl --enable-werror or --disable-werror, and set +dnl shell variable want_werror as appropriate. + +AC_DEFUN([CURL_CHECK_OPTION_WERROR], [ + AC_BEFORE([$0],[CURL_CHECK_COMPILER])dnl + AC_MSG_CHECKING([whether to enable compiler warnings as errors]) + OPT_COMPILER_WERROR="default" + AC_ARG_ENABLE(werror, +AS_HELP_STRING([--enable-werror],[Enable compiler warnings as errors]) +AS_HELP_STRING([--disable-werror],[Disable compiler warnings as errors]), + OPT_COMPILER_WERROR=$enableval) + case "$OPT_COMPILER_WERROR" in + no) + dnl --disable-werror option used + want_werror="no" + ;; + default) + dnl configure option not specified + want_werror="no" + ;; + *) + dnl --enable-werror option used + want_werror="yes" + ;; + esac + AC_MSG_RESULT([$want_werror]) +]) + + +dnl CURL_CHECK_NONBLOCKING_SOCKET +dnl ------------------------------------------------- +dnl Check for how to set a socket into non-blocking state. + +AC_DEFUN([CURL_CHECK_NONBLOCKING_SOCKET], [ + AC_REQUIRE([CURL_CHECK_FUNC_FCNTL])dnl + AC_REQUIRE([CURL_CHECK_FUNC_IOCTLSOCKET])dnl + AC_REQUIRE([CURL_CHECK_FUNC_IOCTLSOCKET_CAMEL])dnl + # + tst_method="unknown" + + AC_MSG_CHECKING([how to set a socket into non-blocking mode]) + if test "x$curl_cv_func_fcntl_o_nonblock" = "xyes"; then + tst_method="fcntl O_NONBLOCK" + elif test "x$curl_cv_func_ioctl_fionbio" = "xyes"; then + tst_method="ioctl FIONBIO" + elif test "x$curl_cv_func_ioctlsocket_fionbio" = "xyes"; then + tst_method="ioctlsocket FIONBIO" + elif test "x$curl_cv_func_ioctlsocket_camel_fionbio" = "xyes"; then + tst_method="IoctlSocket FIONBIO" + elif test "x$curl_cv_func_setsockopt_so_nonblock" = "xyes"; then + tst_method="setsockopt SO_NONBLOCK" + fi + AC_MSG_RESULT([$tst_method]) + if test "$tst_method" = "unknown"; then + AC_MSG_WARN([cannot determine non-blocking socket method.]) + fi +]) + + +dnl CURL_CONFIGURE_SYMBOL_HIDING +dnl ------------------------------------------------- +dnl Depending on --enable-symbol-hiding or --disable-symbol-hiding +dnl configure option, and compiler capability to actually honor such +dnl option, this will modify compiler flags as appropriate and also +dnl provide needed definitions for configuration and Makefile.am files. +dnl This macro should not be used until all compilation tests have +dnl been done to prevent interferences on other tests. + +AC_DEFUN([CURL_CONFIGURE_SYMBOL_HIDING], [ + AC_MSG_CHECKING([whether hiding of library internal symbols will actually happen]) + CFLAG_CURL_SYMBOL_HIDING="" + doing_symbol_hiding="no" + if test "$want_symbol_hiding" = "yes" && + test "$supports_symbol_hiding" = "yes"; then + doing_symbol_hiding="yes" + CFLAG_CURL_SYMBOL_HIDING="$symbol_hiding_CFLAGS" + AC_DEFINE_UNQUOTED(CURL_EXTERN_SYMBOL, $symbol_hiding_EXTERN, + [Definition to make a library symbol externally visible.]) + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + fi + AM_CONDITIONAL(DOING_CURL_SYMBOL_HIDING, test x$doing_symbol_hiding = xyes) + AC_SUBST(CFLAG_CURL_SYMBOL_HIDING) +]) + + +dnl CURL_CHECK_LIB_ARES +dnl ------------------------------------------------- +dnl When c-ares library support has been requested, performs necessary checks +dnl and adjustments needed to enable support of this library. + +AC_DEFUN([CURL_CHECK_LIB_ARES], [ + # + if test "$want_ares" = "yes"; then + dnl c-ares library support has been requested + clean_CPPFLAGS="$CPPFLAGS" + clean_LDFLAGS="$LDFLAGS" + clean_LIBS="$LIBS" + configure_runpath=`pwd` + if test -n "$want_ares_path"; then + dnl c-ares library path has been specified + ARES_PCDIR="$want_ares_path/lib/pkgconfig" + CURL_CHECK_PKGCONFIG(libcares, [$ARES_PCDIR]) + if test "$PKGCONFIG" != "no" ; then + ares_LIBS=`CURL_EXPORT_PCDIR([$ARES_PCDIR]) + $PKGCONFIG --libs-only-l libcares` + ares_LDFLAGS=`CURL_EXPORT_PCDIR([$ARES_PCDIR]) + $PKGCONFIG --libs-only-L libcares` + ares_CPPFLAGS=`CURL_EXPORT_PCDIR([$ARES_PCDIR]) + $PKGCONFIG --cflags-only-I libcares` + AC_MSG_NOTICE([pkg-config: ares LIBS: "$ares_LIBS"]) + AC_MSG_NOTICE([pkg-config: ares LDFLAGS: "$ares_LDFLAGS"]) + AC_MSG_NOTICE([pkg-config: ares CPPFLAGS: "$ares_CPPFLAGS"]) + else + dnl ... path without pkg-config + ares_CPPFLAGS="-I$want_ares_path/include" + ares_LDFLAGS="-L$want_ares_path/lib" + ares_LIBS="-lcares" + fi + else + dnl c-ares path not specified, use defaults + CURL_CHECK_PKGCONFIG(libcares) + if test "$PKGCONFIG" != "no" ; then + ares_LIBS=`$PKGCONFIG --libs-only-l libcares` + ares_LDFLAGS=`$PKGCONFIG --libs-only-L libcares` + ares_CPPFLAGS=`$PKGCONFIG --cflags-only-I libcares` + AC_MSG_NOTICE([pkg-config: ares_LIBS: "$ares_LIBS"]) + AC_MSG_NOTICE([pkg-config: ares_LDFLAGS: "$ares_LDFLAGS"]) + AC_MSG_NOTICE([pkg-config: ares_CPPFLAGS: "$ares_CPPFLAGS"]) + else + ares_CPPFLAGS="" + ares_LDFLAGS="" + ares_LIBS="-lcares" + fi + fi + # + CPPFLAGS="$clean_CPPFLAGS $ares_CPPFLAGS" + LDFLAGS="$clean_LDFLAGS $ares_LDFLAGS" + LIBS="$ares_LIBS $clean_LIBS" + # + + dnl check if c-ares new enough + AC_MSG_CHECKING([that c-ares is good and recent enough]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ +#include + /* set of dummy functions in case c-ares was built with debug */ + void curl_dofree() { } + void curl_sclose() { } + void curl_domalloc() { } + void curl_docalloc() { } + void curl_socket() { } + ]],[[ + ares_channel channel; + ares_cancel(channel); /* added in 1.2.0 */ + ares_process_fd(channel, 0, 0); /* added in 1.4.0 */ + ares_dup(&channel, channel); /* added in 1.6.0 */ + ]]) + ],[ + AC_MSG_RESULT([yes]) + ],[ + AC_MSG_RESULT([no]) + AC_MSG_ERROR([c-ares library defective or too old]) + dnl restore initial settings + CPPFLAGS="$clean_CPPFLAGS" + LDFLAGS="$clean_LDFLAGS" + LIBS="$clean_LIBS" + # prevent usage + want_ares="no" + ]) + + if test "$want_ares" = "yes"; then + dnl finally c-ares will be used + AC_DEFINE(USE_ARES, 1, [Define to enable c-ares support]) + AC_DEFINE(CARES_NO_DEPRECATED, 1, [Ignore c-ares deprecation warnings]) + AC_SUBST([USE_ARES], [1]) + curl_res_msg="c-ares" + fi + fi +]) + +dnl CURL_CHECK_OPTION_NTLM_WB +dnl ------------------------------------------------- +dnl Verify if configure has been invoked with option +dnl --enable-ntlm-wb or --disable-ntlm-wb, and set +dnl shell variable want_ntlm_wb and want_ntlm_wb_file +dnl as appropriate. + +AC_DEFUN([CURL_CHECK_OPTION_NTLM_WB], [ + AC_BEFORE([$0],[CURL_CHECK_NTLM_WB])dnl + OPT_NTLM_WB="default" + AC_ARG_ENABLE(ntlm-wb, +AS_HELP_STRING([--enable-ntlm-wb@<:@=FILE@:>@],[Enable NTLM delegation to winbind's ntlm_auth helper, where FILE is ntlm_auth's absolute filename (default: /usr/bin/ntlm_auth)]) +AS_HELP_STRING([--disable-ntlm-wb],[Disable NTLM delegation to winbind's ntlm_auth helper]), + OPT_NTLM_WB=$enableval) + want_ntlm_wb_file="/usr/bin/ntlm_auth" + case "$OPT_NTLM_WB" in + no) + dnl --disable-ntlm-wb option used + want_ntlm_wb="no" + ;; + default) + dnl configure option not specified + want_ntlm_wb="yes" + ;; + *) + dnl --enable-ntlm-wb option used + want_ntlm_wb="yes" + if test -n "$enableval" && test "$enableval" != "yes"; then + want_ntlm_wb_file="$enableval" + fi + ;; + esac +]) + + +dnl CURL_CHECK_NTLM_WB +dnl ------------------------------------------------- +dnl Check if support for NTLM delegation to winbind's +dnl ntlm_auth helper will finally be enabled depending +dnl on given configure options and target platform. + +AC_DEFUN([CURL_CHECK_NTLM_WB], [ + AC_REQUIRE([CURL_CHECK_OPTION_NTLM_WB])dnl + AC_REQUIRE([CURL_CHECK_NATIVE_WINDOWS])dnl + AC_MSG_CHECKING([whether to enable NTLM delegation to winbind's helper]) + if test "$curl_cv_native_windows" = "yes" || + test "x$SSL_ENABLED" = "x"; then + want_ntlm_wb_file="" + want_ntlm_wb="no" + elif test "x$ac_cv_func_fork" != "xyes"; then + dnl ntlm_wb requires fork + want_ntlm_wb="no" + fi + AC_MSG_RESULT([$want_ntlm_wb]) + if test "$want_ntlm_wb" = "yes"; then + AC_DEFINE(NTLM_WB_ENABLED, 1, + [Define to enable NTLM delegation to winbind's ntlm_auth helper.]) + AC_DEFINE_UNQUOTED(NTLM_WB_FILE, "$want_ntlm_wb_file", + [Define absolute filename for winbind's ntlm_auth helper.]) + NTLM_WB_ENABLED=1 + fi +]) + +dnl CURL_CHECK_OPTION_HTTPSRR +dnl ----------------------------------------------------- +dnl Verify whether configure has been invoked with option +dnl --enable-httpsrr or --disable-httpsrr, and set +dnl shell variable want_httpsrr as appropriate. + +AC_DEFUN([CURL_CHECK_OPTION_HTTPSRR], [ + AC_MSG_CHECKING([whether to enable HTTPSRR support]) + OPT_HTTPSRR="default" + AC_ARG_ENABLE(httpsrr, +AS_HELP_STRING([--enable-httpsrr],[Enable HTTPSRR support]) +AS_HELP_STRING([--disable-httpsrr],[Disable HTTPSRR support]), + OPT_HTTPSRR=$enableval) + case "$OPT_HTTPSRR" in + no) + dnl --disable-httpsrr option used + want_httpsrr="no" + curl_httpsrr_msg="no (--enable-httpsrr)" + AC_MSG_RESULT([no]) + ;; + default) + dnl configure option not specified + want_httpsrr="no" + curl_httpsrr_msg="no (--enable-httpsrr)" + AC_MSG_RESULT([no]) + ;; + *) + dnl --enable-httpsrr option used + want_httpsrr="yes" + curl_httpsrr_msg="enabled (--disable-httpsrr)" + experimental="httpsrr" + AC_MSG_RESULT([yes]) + ;; + esac +]) + +dnl CURL_CHECK_OPTION_ECH +dnl ----------------------------------------------------- +dnl Verify whether configure has been invoked with option +dnl --enable-ech or --disable-ech, and set +dnl shell variable want_ech as appropriate. + +AC_DEFUN([CURL_CHECK_OPTION_ECH], [ + AC_MSG_CHECKING([whether to enable ECH support]) + OPT_ECH="default" + AC_ARG_ENABLE(ech, +AS_HELP_STRING([--enable-ech],[Enable ECH support]) +AS_HELP_STRING([--disable-ech],[Disable ECH support]), + OPT_ECH=$enableval) + case "$OPT_ECH" in + no) + dnl --disable-ech option used + want_ech="no" + curl_ech_msg="no (--enable-ech)" + AC_MSG_RESULT([no]) + ;; + default) + dnl configure option not specified + want_ech="no" + curl_ech_msg="no (--enable-ech)" + AC_MSG_RESULT([no]) + ;; + *) + dnl --enable-ech option used + want_ech="yes" + curl_ech_msg="enabled (--disable-ech)" + experimental="ech" + AC_MSG_RESULT([yes]) + ;; + esac +]) +]) diff --git a/third_party/curl/m4/curl-functions.m4 b/third_party/curl/m4/curl-functions.m4 new file mode 100644 index 0000000..f0860dd --- /dev/null +++ b/third_party/curl/m4/curl-functions.m4 @@ -0,0 +1,5012 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +# File version for 'aclocal' use. Keep it a single number. +# serial 73 + + +dnl CURL_INCLUDES_ARPA_INET +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when arpa/inet.h is to be included. + +AC_DEFUN([CURL_INCLUDES_ARPA_INET], [ +curl_includes_arpa_inet="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_SOCKET_H +# include +#endif +#ifdef HAVE_NETINET_IN_H +# include +#endif +#ifdef HAVE_ARPA_INET_H +# include +#endif +#ifdef _WIN32 +#include +#include +#endif +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h sys/socket.h netinet/in.h arpa/inet.h, + [], [], [$curl_includes_arpa_inet]) +]) + + +dnl CURL_INCLUDES_FCNTL +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when fcntl.h is to be included. + +AC_DEFUN([CURL_INCLUDES_FCNTL], [ +curl_includes_fcntl="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif +#ifdef HAVE_FCNTL_H +# include +#endif +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h unistd.h fcntl.h, + [], [], [$curl_includes_fcntl]) +]) + + +dnl CURL_INCLUDES_IFADDRS +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when ifaddrs.h is to be included. + +AC_DEFUN([CURL_INCLUDES_IFADDRS], [ +curl_includes_ifaddrs="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_SOCKET_H +# include +#endif +#ifdef HAVE_NETINET_IN_H +# include +#endif +#ifdef HAVE_IFADDRS_H +# include +#endif +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h sys/socket.h netinet/in.h ifaddrs.h, + [], [], [$curl_includes_ifaddrs]) +]) + + +dnl CURL_INCLUDES_LIBGEN +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when libgen.h is to be included. + +AC_DEFUN([CURL_INCLUDES_LIBGEN], [ +curl_includes_libgen="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_LIBGEN_H +# include +#endif +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h libgen.h, + [], [], [$curl_includes_libgen]) +]) + + +dnl CURL_INCLUDES_NETDB +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when netdb.h is to be included. + +AC_DEFUN([CURL_INCLUDES_NETDB], [ +curl_includes_netdb="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_NETDB_H +# include +#endif +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h netdb.h, + [], [], [$curl_includes_netdb]) +]) + + +dnl CURL_INCLUDES_POLL +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when poll.h is to be included. + +AC_DEFUN([CURL_INCLUDES_POLL], [ +curl_includes_poll="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_POLL_H +# include +#endif +#ifdef HAVE_SYS_POLL_H +# include +#endif +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h poll.h sys/poll.h, + [], [], [$curl_includes_poll]) +]) + + +dnl CURL_INCLUDES_SETJMP +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when setjmp.h is to be included. + +AC_DEFUN([CURL_INCLUDES_SETJMP], [ +curl_includes_setjmp="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#include +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h, + [], [], [$curl_includes_setjmp]) +]) + + +dnl CURL_INCLUDES_SIGNAL +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when signal.h is to be included. + +AC_DEFUN([CURL_INCLUDES_SIGNAL], [ +curl_includes_signal="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#include +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h, + [], [], [$curl_includes_signal]) +]) + + +dnl CURL_INCLUDES_SOCKET +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when socket.h is to be included. + +AC_DEFUN([CURL_INCLUDES_SOCKET], [ +curl_includes_socket="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SOCKET_H +# include +#endif +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h socket.h, + [], [], [$curl_includes_socket]) +]) + + +dnl CURL_INCLUDES_STDLIB +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when stdlib.h is to be included. + +AC_DEFUN([CURL_INCLUDES_STDLIB], [ +curl_includes_stdlib="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#include +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h, + [], [], [$curl_includes_stdlib]) +]) + + +dnl CURL_INCLUDES_STRING +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when string(s).h is to be included. + +AC_DEFUN([CURL_INCLUDES_STRING], [ +curl_includes_string="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#include +#ifdef HAVE_STRINGS_H +# include +#endif +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h strings.h, + [], [], [$curl_includes_string]) +]) + + +dnl CURL_INCLUDES_STROPTS +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when stropts.h is to be included. + +AC_DEFUN([CURL_INCLUDES_STROPTS], [ +curl_includes_stropts="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif +#ifdef HAVE_SYS_SOCKET_H +# include +#endif +#ifdef HAVE_SYS_IOCTL_H +# include +#endif +#ifdef HAVE_STROPTS_H +# include +#endif +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h unistd.h sys/socket.h sys/ioctl.h stropts.h, + [], [], [$curl_includes_stropts]) +]) + + +dnl CURL_INCLUDES_SYS_SOCKET +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when sys/socket.h is to be included. + +AC_DEFUN([CURL_INCLUDES_SYS_SOCKET], [ +curl_includes_sys_socket="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_SOCKET_H +# include +#endif +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h sys/socket.h, + [], [], [$curl_includes_sys_socket]) +]) + + +dnl CURL_INCLUDES_SYS_TYPES +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when sys/types.h is to be included. + +AC_DEFUN([CURL_INCLUDES_SYS_TYPES], [ +curl_includes_sys_types="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h, + [], [], [$curl_includes_sys_types]) +]) + + +dnl CURL_INCLUDES_SYS_XATTR +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when sys/xattr.h is to be included. + +AC_DEFUN([CURL_INCLUDES_SYS_XATTR], [ +curl_includes_sys_xattr="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_XATTR_H +# include +#endif +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h sys/xattr.h, + [], [], [$curl_includes_sys_xattr]) +]) + +dnl CURL_INCLUDES_TIME +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when time.h is to be included. + +AC_DEFUN([CURL_INCLUDES_TIME], [ +curl_includes_time="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_TIME_H +# include +#endif +#include +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h sys/time.h, + [], [], [$curl_includes_time]) +]) + + +dnl CURL_INCLUDES_UNISTD +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when unistd.h is to be included. + +AC_DEFUN([CURL_INCLUDES_UNISTD], [ +curl_includes_unistd="\ +/* includes start */ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif +/* includes end */" + AC_CHECK_HEADERS( + sys/types.h unistd.h, + [], [], [$curl_includes_unistd]) +]) + + +dnl CURL_INCLUDES_WINSOCK2 +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when winsock2.h is to be included. + +AC_DEFUN([CURL_INCLUDES_WINSOCK2], [ +curl_includes_winsock2="\ +/* includes start */ +#ifdef _WIN32 +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +#endif +/* includes end */" + CURL_CHECK_NATIVE_WINDOWS +]) + + +dnl CURL_INCLUDES_WS2TCPIP +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when ws2tcpip.h is to be included. + +AC_DEFUN([CURL_INCLUDES_WS2TCPIP], [ +curl_includes_ws2tcpip="\ +/* includes start */ +#ifdef _WIN32 +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +# include +#endif +/* includes end */" + CURL_CHECK_NATIVE_WINDOWS +]) + + +dnl CURL_INCLUDES_BSDSOCKET +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when bsdsocket.h is to be included. + +AC_DEFUN([CURL_INCLUDES_BSDSOCKET], [ +curl_includes_bsdsocket="\ +/* includes start */ +#if defined(HAVE_PROTO_BSDSOCKET_H) +# define __NO_NET_API +# define __USE_INLINE__ +# include +# ifdef HAVE_SYS_IOCTL_H +# include +# endif +# ifdef __amigaos4__ +struct SocketIFace *ISocket = NULL; +# else +struct Library *SocketBase = NULL; +# endif +# define select(a,b,c,d,e) WaitSelect(a,b,c,d,e,0) +#endif +/* includes end */" + AC_CHECK_HEADERS( + proto/bsdsocket.h, + [], [], [$curl_includes_bsdsocket]) +]) + +dnl CURL_INCLUDES_NETIF +dnl ------------------------------------------------- +dnl Set up variable with list of headers that must be +dnl included when net/if.h is to be included. + +AC_DEFUN([CURL_INCLUDES_NETIF], [ +curl_includes_netif="\ +/* includes start */ +#ifdef HAVE_NET_IF_H +# include +#endif +/* includes end */" + AC_CHECK_HEADERS( + net/if.h, + [], [], [$curl_includes_netif]) +]) + + +dnl CURL_PREPROCESS_CALLCONV +dnl ------------------------------------------------- +dnl Set up variable with a preprocessor block which +dnl defines function calling convention. + +AC_DEFUN([CURL_PREPROCESS_CALLCONV], [ +curl_preprocess_callconv="\ +/* preprocess start */ +#ifdef _WIN32 +# define FUNCALLCONV __stdcall +#else +# define FUNCALLCONV +#endif +/* preprocess end */" +]) + + +dnl CURL_CHECK_FUNC_ALARM +dnl ------------------------------------------------- +dnl Verify if alarm is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_alarm, then +dnl HAVE_ALARM will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_ALARM], [ + AC_REQUIRE([CURL_INCLUDES_UNISTD])dnl + # + tst_links_alarm="unknown" + tst_proto_alarm="unknown" + tst_compi_alarm="unknown" + tst_allow_alarm="unknown" + # + AC_MSG_CHECKING([if alarm can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([alarm]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_alarm="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_alarm="no" + ]) + # + if test "$tst_links_alarm" = "yes"; then + AC_MSG_CHECKING([if alarm is prototyped]) + AC_EGREP_CPP([alarm],[ + $curl_includes_unistd + ],[ + AC_MSG_RESULT([yes]) + tst_proto_alarm="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_alarm="no" + ]) + fi + # + if test "$tst_proto_alarm" = "yes"; then + AC_MSG_CHECKING([if alarm is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_unistd + ]],[[ + if(0 != alarm(0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_alarm="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_alarm="no" + ]) + fi + # + if test "$tst_compi_alarm" = "yes"; then + AC_MSG_CHECKING([if alarm usage allowed]) + if test "x$curl_disallow_alarm" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_alarm="yes" + else + AC_MSG_RESULT([no]) + tst_allow_alarm="no" + fi + fi + # + AC_MSG_CHECKING([if alarm might be used]) + if test "$tst_links_alarm" = "yes" && + test "$tst_proto_alarm" = "yes" && + test "$tst_compi_alarm" = "yes" && + test "$tst_allow_alarm" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_ALARM, 1, + [Define to 1 if you have the alarm function.]) + curl_cv_func_alarm="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_alarm="no" + fi +]) + + +dnl CURL_CHECK_FUNC_BASENAME +dnl ------------------------------------------------- +dnl Verify if basename is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_basename, then +dnl HAVE_BASENAME will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_BASENAME], [ + AC_REQUIRE([CURL_INCLUDES_STRING])dnl + AC_REQUIRE([CURL_INCLUDES_LIBGEN])dnl + AC_REQUIRE([CURL_INCLUDES_UNISTD])dnl + # + tst_links_basename="unknown" + tst_proto_basename="unknown" + tst_compi_basename="unknown" + tst_allow_basename="unknown" + # + AC_MSG_CHECKING([if basename can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([basename]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_basename="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_basename="no" + ]) + # + if test "$tst_links_basename" = "yes"; then + AC_MSG_CHECKING([if basename is prototyped]) + AC_EGREP_CPP([basename],[ + $curl_includes_string + $curl_includes_libgen + $curl_includes_unistd + ],[ + AC_MSG_RESULT([yes]) + tst_proto_basename="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_basename="no" + ]) + fi + # + if test "$tst_proto_basename" = "yes"; then + AC_MSG_CHECKING([if basename is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_string + $curl_includes_libgen + $curl_includes_unistd + ]],[[ + if(0 != basename(0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_basename="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_basename="no" + ]) + fi + # + if test "$tst_compi_basename" = "yes"; then + AC_MSG_CHECKING([if basename usage allowed]) + if test "x$curl_disallow_basename" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_basename="yes" + else + AC_MSG_RESULT([no]) + tst_allow_basename="no" + fi + fi + # + AC_MSG_CHECKING([if basename might be used]) + if test "$tst_links_basename" = "yes" && + test "$tst_proto_basename" = "yes" && + test "$tst_compi_basename" = "yes" && + test "$tst_allow_basename" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_BASENAME, 1, + [Define to 1 if you have the basename function.]) + curl_cv_func_basename="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_basename="no" + fi +]) + + +dnl CURL_CHECK_FUNC_CLOSESOCKET +dnl ------------------------------------------------- +dnl Verify if closesocket is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_closesocket, then +dnl HAVE_CLOSESOCKET will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_CLOSESOCKET], [ + AC_REQUIRE([CURL_INCLUDES_WINSOCK2])dnl + AC_REQUIRE([CURL_INCLUDES_SOCKET])dnl + # + tst_links_closesocket="unknown" + tst_proto_closesocket="unknown" + tst_compi_closesocket="unknown" + tst_allow_closesocket="unknown" + # + AC_MSG_CHECKING([if closesocket can be linked]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_socket + ]],[[ + if(0 != closesocket(0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_closesocket="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_closesocket="no" + ]) + # + if test "$tst_links_closesocket" = "yes"; then + AC_MSG_CHECKING([if closesocket is prototyped]) + AC_EGREP_CPP([closesocket],[ + $curl_includes_winsock2 + $curl_includes_socket + ],[ + AC_MSG_RESULT([yes]) + tst_proto_closesocket="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_closesocket="no" + ]) + fi + # + if test "$tst_proto_closesocket" = "yes"; then + AC_MSG_CHECKING([if closesocket is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_socket + ]],[[ + if(0 != closesocket(0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_closesocket="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_closesocket="no" + ]) + fi + # + if test "$tst_compi_closesocket" = "yes"; then + AC_MSG_CHECKING([if closesocket usage allowed]) + if test "x$curl_disallow_closesocket" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_closesocket="yes" + else + AC_MSG_RESULT([no]) + tst_allow_closesocket="no" + fi + fi + # + AC_MSG_CHECKING([if closesocket might be used]) + if test "$tst_links_closesocket" = "yes" && + test "$tst_proto_closesocket" = "yes" && + test "$tst_compi_closesocket" = "yes" && + test "$tst_allow_closesocket" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_CLOSESOCKET, 1, + [Define to 1 if you have the closesocket function.]) + curl_cv_func_closesocket="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_closesocket="no" + fi +]) + + +dnl CURL_CHECK_FUNC_CLOSESOCKET_CAMEL +dnl ------------------------------------------------- +dnl Verify if CloseSocket is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_closesocket_camel, +dnl then HAVE_CLOSESOCKET_CAMEL will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_CLOSESOCKET_CAMEL], [ + AC_REQUIRE([CURL_INCLUDES_SYS_SOCKET])dnl + AC_REQUIRE([CURL_INCLUDES_BSDSOCKET])dnl + # + tst_links_closesocket_camel="unknown" + tst_proto_closesocket_camel="unknown" + tst_compi_closesocket_camel="unknown" + tst_allow_closesocket_camel="unknown" + # + AC_MSG_CHECKING([if CloseSocket can be linked]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_bsdsocket + $curl_includes_sys_socket + ]],[[ + if(0 != CloseSocket(0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_closesocket_camel="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_closesocket_camel="no" + ]) + # + if test "$tst_links_closesocket_camel" = "yes"; then + AC_MSG_CHECKING([if CloseSocket is prototyped]) + AC_EGREP_CPP([CloseSocket],[ + $curl_includes_bsdsocket + $curl_includes_sys_socket + ],[ + AC_MSG_RESULT([yes]) + tst_proto_closesocket_camel="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_closesocket_camel="no" + ]) + fi + # + if test "$tst_proto_closesocket_camel" = "yes"; then + AC_MSG_CHECKING([if CloseSocket is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_bsdsocket + $curl_includes_sys_socket + ]],[[ + if(0 != CloseSocket(0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_closesocket_camel="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_closesocket_camel="no" + ]) + fi + # + if test "$tst_compi_closesocket_camel" = "yes"; then + AC_MSG_CHECKING([if CloseSocket usage allowed]) + if test "x$curl_disallow_closesocket_camel" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_closesocket_camel="yes" + else + AC_MSG_RESULT([no]) + tst_allow_closesocket_camel="no" + fi + fi + # + AC_MSG_CHECKING([if CloseSocket might be used]) + if test "$tst_links_closesocket_camel" = "yes" && + test "$tst_proto_closesocket_camel" = "yes" && + test "$tst_compi_closesocket_camel" = "yes" && + test "$tst_allow_closesocket_camel" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_CLOSESOCKET_CAMEL, 1, + [Define to 1 if you have the CloseSocket camel case function.]) + curl_cv_func_closesocket_camel="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_closesocket_camel="no" + fi +]) + +dnl CURL_CHECK_FUNC_FCNTL +dnl ------------------------------------------------- +dnl Verify if fcntl is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_fcntl, then +dnl HAVE_FCNTL will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_FCNTL], [ + AC_REQUIRE([CURL_INCLUDES_FCNTL])dnl + # + tst_links_fcntl="unknown" + tst_proto_fcntl="unknown" + tst_compi_fcntl="unknown" + tst_allow_fcntl="unknown" + # + AC_MSG_CHECKING([if fcntl can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([fcntl]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_fcntl="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_fcntl="no" + ]) + # + if test "$tst_links_fcntl" = "yes"; then + AC_MSG_CHECKING([if fcntl is prototyped]) + AC_EGREP_CPP([fcntl],[ + $curl_includes_fcntl + ],[ + AC_MSG_RESULT([yes]) + tst_proto_fcntl="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_fcntl="no" + ]) + fi + # + if test "$tst_proto_fcntl" = "yes"; then + AC_MSG_CHECKING([if fcntl is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_fcntl + ]],[[ + if(0 != fcntl(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_fcntl="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_fcntl="no" + ]) + fi + # + if test "$tst_compi_fcntl" = "yes"; then + AC_MSG_CHECKING([if fcntl usage allowed]) + if test "x$curl_disallow_fcntl" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_fcntl="yes" + else + AC_MSG_RESULT([no]) + tst_allow_fcntl="no" + fi + fi + # + AC_MSG_CHECKING([if fcntl might be used]) + if test "$tst_links_fcntl" = "yes" && + test "$tst_proto_fcntl" = "yes" && + test "$tst_compi_fcntl" = "yes" && + test "$tst_allow_fcntl" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_FCNTL, 1, + [Define to 1 if you have the fcntl function.]) + curl_cv_func_fcntl="yes" + CURL_CHECK_FUNC_FCNTL_O_NONBLOCK + else + AC_MSG_RESULT([no]) + curl_cv_func_fcntl="no" + fi +]) + + +dnl CURL_CHECK_FUNC_FCNTL_O_NONBLOCK +dnl ------------------------------------------------- +dnl Verify if fcntl with status flag O_NONBLOCK is +dnl available, can be compiled, and seems to work. If +dnl all of these are true, then HAVE_FCNTL_O_NONBLOCK +dnl will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_FCNTL_O_NONBLOCK], [ + # + tst_compi_fcntl_o_nonblock="unknown" + tst_allow_fcntl_o_nonblock="unknown" + # + case $host_os in + sunos4* | aix3*) + dnl O_NONBLOCK does not work on these platforms + curl_disallow_fcntl_o_nonblock="yes" + ;; + esac + # + if test "$curl_cv_func_fcntl" = "yes"; then + AC_MSG_CHECKING([if fcntl O_NONBLOCK is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_fcntl + ]],[[ + int flags = 0; + if(0 != fcntl(0, F_SETFL, flags | O_NONBLOCK)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_fcntl_o_nonblock="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_fcntl_o_nonblock="no" + ]) + fi + # + if test "$tst_compi_fcntl_o_nonblock" = "yes"; then + AC_MSG_CHECKING([if fcntl O_NONBLOCK usage allowed]) + if test "x$curl_disallow_fcntl_o_nonblock" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_fcntl_o_nonblock="yes" + else + AC_MSG_RESULT([no]) + tst_allow_fcntl_o_nonblock="no" + fi + fi + # + AC_MSG_CHECKING([if fcntl O_NONBLOCK might be used]) + if test "$tst_compi_fcntl_o_nonblock" = "yes" && + test "$tst_allow_fcntl_o_nonblock" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_FCNTL_O_NONBLOCK, 1, + [Define to 1 if you have a working fcntl O_NONBLOCK function.]) + curl_cv_func_fcntl_o_nonblock="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_fcntl_o_nonblock="no" + fi +]) + + +dnl CURL_CHECK_FUNC_FREEADDRINFO +dnl ------------------------------------------------- +dnl Verify if freeaddrinfo is available, prototyped, +dnl and can be compiled. If all of these are true, +dnl and usage has not been previously disallowed with +dnl shell variable curl_disallow_freeaddrinfo, then +dnl HAVE_FREEADDRINFO will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_FREEADDRINFO], [ + AC_REQUIRE([CURL_INCLUDES_WS2TCPIP])dnl + AC_REQUIRE([CURL_INCLUDES_SYS_SOCKET])dnl + AC_REQUIRE([CURL_INCLUDES_NETDB])dnl + # + tst_links_freeaddrinfo="unknown" + tst_proto_freeaddrinfo="unknown" + tst_compi_freeaddrinfo="unknown" + tst_allow_freeaddrinfo="unknown" + # + AC_MSG_CHECKING([if freeaddrinfo can be linked]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_ws2tcpip + $curl_includes_sys_socket + $curl_includes_netdb + ]],[[ + freeaddrinfo(0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_freeaddrinfo="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_freeaddrinfo="no" + ]) + # + if test "$tst_links_freeaddrinfo" = "yes"; then + AC_MSG_CHECKING([if freeaddrinfo is prototyped]) + AC_EGREP_CPP([freeaddrinfo],[ + $curl_includes_ws2tcpip + $curl_includes_sys_socket + $curl_includes_netdb + ],[ + AC_MSG_RESULT([yes]) + tst_proto_freeaddrinfo="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_freeaddrinfo="no" + ]) + fi + # + if test "$tst_proto_freeaddrinfo" = "yes"; then + AC_MSG_CHECKING([if freeaddrinfo is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_ws2tcpip + $curl_includes_sys_socket + $curl_includes_netdb + ]],[[ + freeaddrinfo(0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_freeaddrinfo="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_freeaddrinfo="no" + ]) + fi + # + if test "$tst_compi_freeaddrinfo" = "yes"; then + AC_MSG_CHECKING([if freeaddrinfo usage allowed]) + if test "x$curl_disallow_freeaddrinfo" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_freeaddrinfo="yes" + else + AC_MSG_RESULT([no]) + tst_allow_freeaddrinfo="no" + fi + fi + # + AC_MSG_CHECKING([if freeaddrinfo might be used]) + if test "$tst_links_freeaddrinfo" = "yes" && + test "$tst_proto_freeaddrinfo" = "yes" && + test "$tst_compi_freeaddrinfo" = "yes" && + test "$tst_allow_freeaddrinfo" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_FREEADDRINFO, 1, + [Define to 1 if you have the freeaddrinfo function.]) + curl_cv_func_freeaddrinfo="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_freeaddrinfo="no" + fi +]) + + +dnl CURL_CHECK_FUNC_FSETXATTR +dnl ------------------------------------------------- +dnl Verify if fsetxattr is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_fsetxattr, then +dnl HAVE_FSETXATTR will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_FSETXATTR], [ + AC_REQUIRE([CURL_INCLUDES_SYS_XATTR])dnl + # + tst_links_fsetxattr="unknown" + tst_proto_fsetxattr="unknown" + tst_compi_fsetxattr="unknown" + tst_allow_fsetxattr="unknown" + tst_nargs_fsetxattr="unknown" + # + AC_MSG_CHECKING([if fsetxattr can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([fsetxattr]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_fsetxattr="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_fsetxattr="no" + ]) + # + if test "$tst_links_fsetxattr" = "yes"; then + AC_MSG_CHECKING([if fsetxattr is prototyped]) + AC_EGREP_CPP([fsetxattr],[ + $curl_includes_sys_xattr + ],[ + AC_MSG_RESULT([yes]) + tst_proto_fsetxattr="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_fsetxattr="no" + ]) + fi + # + if test "$tst_proto_fsetxattr" = "yes"; then + if test "$tst_nargs_fsetxattr" = "unknown"; then + AC_MSG_CHECKING([if fsetxattr takes 5 args.]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_sys_xattr + ]],[[ + if(0 != fsetxattr(0, 0, 0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_fsetxattr="yes" + tst_nargs_fsetxattr="5" + ],[ + AC_MSG_RESULT([no]) + tst_compi_fsetxattr="no" + ]) + fi + if test "$tst_nargs_fsetxattr" = "unknown"; then + AC_MSG_CHECKING([if fsetxattr takes 6 args.]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_sys_xattr + ]],[[ + if(0 != fsetxattr(0, 0, 0, 0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_fsetxattr="yes" + tst_nargs_fsetxattr="6" + ],[ + AC_MSG_RESULT([no]) + tst_compi_fsetxattr="no" + ]) + fi + AC_MSG_CHECKING([if fsetxattr is compilable]) + if test "$tst_compi_fsetxattr" = "yes"; then + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + fi + fi + # + if test "$tst_compi_fsetxattr" = "yes"; then + AC_MSG_CHECKING([if fsetxattr usage allowed]) + if test "x$curl_disallow_fsetxattr" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_fsetxattr="yes" + else + AC_MSG_RESULT([no]) + tst_allow_fsetxattr="no" + fi + fi + # + AC_MSG_CHECKING([if fsetxattr might be used]) + if test "$tst_links_fsetxattr" = "yes" && + test "$tst_proto_fsetxattr" = "yes" && + test "$tst_compi_fsetxattr" = "yes" && + test "$tst_allow_fsetxattr" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_FSETXATTR, 1, + [Define to 1 if you have the fsetxattr function.]) + dnl AC_DEFINE_UNQUOTED(FSETXATTR_ARGS, $tst_nargs_fsetxattr, + dnl [Specifies the number of arguments to fsetxattr]) + # + if test "$tst_nargs_fsetxattr" -eq "5"; then + AC_DEFINE(HAVE_FSETXATTR_5, 1, [fsetxattr() takes 5 args]) + elif test "$tst_nargs_fsetxattr" -eq "6"; then + AC_DEFINE(HAVE_FSETXATTR_6, 1, [fsetxattr() takes 6 args]) + fi + # + curl_cv_func_fsetxattr="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_fsetxattr="no" + fi +]) + + +dnl CURL_CHECK_FUNC_FTRUNCATE +dnl ------------------------------------------------- +dnl Verify if ftruncate is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_ftruncate, then +dnl HAVE_FTRUNCATE will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_FTRUNCATE], [ + AC_REQUIRE([CURL_INCLUDES_UNISTD])dnl + # + tst_links_ftruncate="unknown" + tst_proto_ftruncate="unknown" + tst_compi_ftruncate="unknown" + tst_allow_ftruncate="unknown" + # + AC_MSG_CHECKING([if ftruncate can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([ftruncate]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_ftruncate="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_ftruncate="no" + ]) + # + if test "$tst_links_ftruncate" = "yes"; then + AC_MSG_CHECKING([if ftruncate is prototyped]) + AC_EGREP_CPP([ftruncate],[ + $curl_includes_unistd + ],[ + AC_MSG_RESULT([yes]) + tst_proto_ftruncate="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_ftruncate="no" + ]) + fi + # + if test "$tst_proto_ftruncate" = "yes"; then + AC_MSG_CHECKING([if ftruncate is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_unistd + ]],[[ + if(0 != ftruncate(0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_ftruncate="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_ftruncate="no" + ]) + fi + # + if test "$tst_compi_ftruncate" = "yes"; then + AC_MSG_CHECKING([if ftruncate usage allowed]) + if test "x$curl_disallow_ftruncate" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_ftruncate="yes" + else + AC_MSG_RESULT([no]) + tst_allow_ftruncate="no" + fi + fi + # + AC_MSG_CHECKING([if ftruncate might be used]) + if test "$tst_links_ftruncate" = "yes" && + test "$tst_proto_ftruncate" = "yes" && + test "$tst_compi_ftruncate" = "yes" && + test "$tst_allow_ftruncate" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_FTRUNCATE, 1, + [Define to 1 if you have the ftruncate function.]) + curl_cv_func_ftruncate="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_ftruncate="no" + fi +]) + + +dnl CURL_CHECK_FUNC_GETADDRINFO +dnl ------------------------------------------------- +dnl Verify if getaddrinfo is available, prototyped, can +dnl be compiled and seems to work. If all of these are +dnl true, and usage has not been previously disallowed +dnl with shell variable curl_disallow_getaddrinfo, then +dnl HAVE_GETADDRINFO will be defined. Additionally when +dnl HAVE_GETADDRINFO gets defined this will also attempt +dnl to find out if getaddrinfo happens to be threadsafe, +dnl defining HAVE_GETADDRINFO_THREADSAFE when true. + +AC_DEFUN([CURL_CHECK_FUNC_GETADDRINFO], [ + AC_REQUIRE([CURL_INCLUDES_WS2TCPIP])dnl + AC_REQUIRE([CURL_INCLUDES_STDLIB])dnl + AC_REQUIRE([CURL_INCLUDES_STRING])dnl + AC_REQUIRE([CURL_INCLUDES_SYS_SOCKET])dnl + AC_REQUIRE([CURL_INCLUDES_NETDB])dnl + AC_REQUIRE([CURL_CHECK_NATIVE_WINDOWS])dnl + # + tst_links_getaddrinfo="unknown" + tst_proto_getaddrinfo="unknown" + tst_compi_getaddrinfo="unknown" + tst_works_getaddrinfo="unknown" + tst_allow_getaddrinfo="unknown" + tst_tsafe_getaddrinfo="unknown" + # + AC_MSG_CHECKING([if getaddrinfo can be linked]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_ws2tcpip + $curl_includes_sys_socket + $curl_includes_netdb + ]],[[ + if(0 != getaddrinfo(0, 0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_getaddrinfo="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_getaddrinfo="no" + ]) + # + if test "$tst_links_getaddrinfo" = "yes"; then + AC_MSG_CHECKING([if getaddrinfo is prototyped]) + AC_EGREP_CPP([getaddrinfo],[ + $curl_includes_ws2tcpip + $curl_includes_sys_socket + $curl_includes_netdb + ],[ + AC_MSG_RESULT([yes]) + tst_proto_getaddrinfo="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_getaddrinfo="no" + ]) + fi + # + if test "$tst_proto_getaddrinfo" = "yes"; then + AC_MSG_CHECKING([if getaddrinfo is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_ws2tcpip + $curl_includes_sys_socket + $curl_includes_netdb + ]],[[ + if(0 != getaddrinfo(0, 0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_getaddrinfo="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_getaddrinfo="no" + ]) + fi + # + dnl only do runtime verification when not cross-compiling + if test "x$cross_compiling" != "xyes" && + test "$tst_compi_getaddrinfo" = "yes"; then + AC_MSG_CHECKING([if getaddrinfo seems to work]) + CURL_RUN_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_ws2tcpip + $curl_includes_stdlib + $curl_includes_string + $curl_includes_sys_socket + $curl_includes_netdb + ]],[[ + struct addrinfo hints; + struct addrinfo *ai = 0; + int error; + + #ifdef _WIN32 + WSADATA wsa; + if(WSAStartup(MAKEWORD(2, 2), &wsa)) + exit(2); + #endif + + memset(&hints, 0, sizeof(hints)); + hints.ai_flags = AI_NUMERICHOST; + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + error = getaddrinfo("127.0.0.1", 0, &hints, &ai); + if(error || !ai) + exit(1); /* fail */ + else + exit(0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_works_getaddrinfo="yes" + ],[ + AC_MSG_RESULT([no]) + tst_works_getaddrinfo="no" + ]) + fi + # + if test "$tst_compi_getaddrinfo" = "yes" && + test "$tst_works_getaddrinfo" != "no"; then + AC_MSG_CHECKING([if getaddrinfo usage allowed]) + if test "x$curl_disallow_getaddrinfo" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_getaddrinfo="yes" + else + AC_MSG_RESULT([no]) + tst_allow_getaddrinfo="no" + fi + fi + # + AC_MSG_CHECKING([if getaddrinfo might be used]) + if test "$tst_links_getaddrinfo" = "yes" && + test "$tst_proto_getaddrinfo" = "yes" && + test "$tst_compi_getaddrinfo" = "yes" && + test "$tst_allow_getaddrinfo" = "yes" && + test "$tst_works_getaddrinfo" != "no"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_GETADDRINFO, 1, + [Define to 1 if you have a working getaddrinfo function.]) + curl_cv_func_getaddrinfo="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_getaddrinfo="no" + curl_cv_func_getaddrinfo_threadsafe="no" + fi + # + if test "$curl_cv_func_getaddrinfo" = "yes"; then + AC_MSG_CHECKING([if getaddrinfo is threadsafe]) + case $host_os in + aix[[1234]].* | aix5.[[01]].*) + dnl aix 5.1 and older + tst_tsafe_getaddrinfo="no" + ;; + aix*) + dnl aix 5.2 and newer + tst_tsafe_getaddrinfo="yes" + ;; + darwin[[12345]].*) + dnl darwin 5.0 and mac os x 10.1.X and older + tst_tsafe_getaddrinfo="no" + ;; + darwin*) + dnl darwin 6.0 and mac os x 10.2.X and newer + tst_tsafe_getaddrinfo="yes" + ;; + freebsd[[1234]].* | freebsd5.[[1234]]*) + dnl freebsd 5.4 and older + tst_tsafe_getaddrinfo="no" + ;; + freebsd*) + dnl freebsd 5.5 and newer + tst_tsafe_getaddrinfo="yes" + ;; + hpux[[123456789]].* | hpux10.* | hpux11.0* | hpux11.10*) + dnl hpux 11.10 and older + tst_tsafe_getaddrinfo="no" + ;; + hpux*) + dnl hpux 11.11 and newer + tst_tsafe_getaddrinfo="yes" + ;; + midnightbsd*) + dnl all MidnightBSD versions + tst_tsafe_getaddrinfo="yes" + ;; + netbsd[[123]].*) + dnl netbsd 3.X and older + tst_tsafe_getaddrinfo="no" + ;; + netbsd*) + dnl netbsd 4.X and newer + tst_tsafe_getaddrinfo="yes" + ;; + *bsd*) + dnl All other bsd's + tst_tsafe_getaddrinfo="no" + ;; + solaris2*) + dnl solaris which have it + tst_tsafe_getaddrinfo="yes" + ;; + esac + if test "$tst_tsafe_getaddrinfo" = "unknown" && + test "$curl_cv_native_windows" = "yes"; then + tst_tsafe_getaddrinfo="yes" + fi + if test "$tst_tsafe_getaddrinfo" = "unknown"; then + CURL_CHECK_DEF_CC([h_errno], [ + $curl_includes_sys_socket + $curl_includes_netdb + ], [silent]) + if test "$curl_cv_have_def_h_errno" = "yes"; then + tst_h_errno_macro="yes" + else + tst_h_errno_macro="no" + fi + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_sys_socket + $curl_includes_netdb + ]],[[ + h_errno = 2; + if(0 != h_errno) + return 1; + ]]) + ],[ + tst_h_errno_modifiable_lvalue="yes" + ],[ + tst_h_errno_modifiable_lvalue="no" + ]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + ]],[[ +#if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200809L) + return 0; +#elif defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE >= 700) + return 0; +#else + force compilation error +#endif + ]]) + ],[ + tst_h_errno_sbs_issue_7="yes" + ],[ + tst_h_errno_sbs_issue_7="no" + ]) + if test "$tst_h_errno_macro" = "no" && + test "$tst_h_errno_modifiable_lvalue" = "no" && + test "$tst_h_errno_sbs_issue_7" = "no"; then + tst_tsafe_getaddrinfo="no" + else + tst_tsafe_getaddrinfo="yes" + fi + fi + AC_MSG_RESULT([$tst_tsafe_getaddrinfo]) + if test "$tst_tsafe_getaddrinfo" = "yes"; then + AC_DEFINE_UNQUOTED(HAVE_GETADDRINFO_THREADSAFE, 1, + [Define to 1 if the getaddrinfo function is threadsafe.]) + curl_cv_func_getaddrinfo_threadsafe="yes" + else + curl_cv_func_getaddrinfo_threadsafe="no" + fi + fi +]) + + +dnl CURL_CHECK_FUNC_GETHOSTBYNAME +dnl ------------------------------------------------- +dnl Verify if gethostbyname is available, prototyped, +dnl and can be compiled. If all of these are true, +dnl and usage has not been previously disallowed with +dnl shell variable curl_disallow_gethostbyname, then +dnl HAVE_GETHOSTBYNAME will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_GETHOSTBYNAME], [ + AC_REQUIRE([CURL_INCLUDES_WINSOCK2])dnl + AC_REQUIRE([CURL_INCLUDES_NETDB])dnl + # + tst_links_gethostbyname="unknown" + tst_proto_gethostbyname="unknown" + tst_compi_gethostbyname="unknown" + tst_allow_gethostbyname="unknown" + # + AC_MSG_CHECKING([if gethostbyname can be linked]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_netdb + ]],[[ + if(0 != gethostbyname(0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_gethostbyname="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_gethostbyname="no" + ]) + # + if test "$tst_links_gethostbyname" = "yes"; then + AC_MSG_CHECKING([if gethostbyname is prototyped]) + AC_EGREP_CPP([gethostbyname],[ + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_netdb + ],[ + AC_MSG_RESULT([yes]) + tst_proto_gethostbyname="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_gethostbyname="no" + ]) + fi + # + if test "$tst_proto_gethostbyname" = "yes"; then + AC_MSG_CHECKING([if gethostbyname is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_netdb + ]],[[ + if(0 != gethostbyname(0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_gethostbyname="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_gethostbyname="no" + ]) + fi + # + if test "$tst_compi_gethostbyname" = "yes"; then + AC_MSG_CHECKING([if gethostbyname usage allowed]) + if test "x$curl_disallow_gethostbyname" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_gethostbyname="yes" + else + AC_MSG_RESULT([no]) + tst_allow_gethostbyname="no" + fi + fi + # + AC_MSG_CHECKING([if gethostbyname might be used]) + if test "$tst_links_gethostbyname" = "yes" && + test "$tst_proto_gethostbyname" = "yes" && + test "$tst_compi_gethostbyname" = "yes" && + test "$tst_allow_gethostbyname" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_GETHOSTBYNAME, 1, + [Define to 1 if you have the gethostbyname function.]) + curl_cv_func_gethostbyname="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_gethostbyname="no" + fi +]) + + +dnl CURL_CHECK_FUNC_GETHOSTBYNAME_R +dnl ------------------------------------------------- +dnl Verify if gethostbyname_r is available, prototyped, +dnl and can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_gethostbyname_r, then +dnl HAVE_GETHOSTBYNAME_R will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_GETHOSTBYNAME_R], [ + AC_REQUIRE([CURL_INCLUDES_NETDB])dnl + # + tst_links_gethostbyname_r="unknown" + tst_proto_gethostbyname_r="unknown" + tst_compi_gethostbyname_r="unknown" + tst_allow_gethostbyname_r="unknown" + tst_nargs_gethostbyname_r="unknown" + # + AC_MSG_CHECKING([if gethostbyname_r can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([gethostbyname_r]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_gethostbyname_r="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_gethostbyname_r="no" + ]) + # + if test "$tst_links_gethostbyname_r" = "yes"; then + AC_MSG_CHECKING([if gethostbyname_r is prototyped]) + AC_EGREP_CPP([gethostbyname_r],[ + $curl_includes_netdb + ],[ + AC_MSG_RESULT([yes]) + tst_proto_gethostbyname_r="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_gethostbyname_r="no" + ]) + fi + # + if test "$tst_proto_gethostbyname_r" = "yes"; then + if test "$tst_nargs_gethostbyname_r" = "unknown"; then + AC_MSG_CHECKING([if gethostbyname_r takes 3 args.]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_netdb + $curl_includes_bsdsocket + ]],[[ + if(0 != gethostbyname_r(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_gethostbyname_r="yes" + tst_nargs_gethostbyname_r="3" + ],[ + AC_MSG_RESULT([no]) + tst_compi_gethostbyname_r="no" + ]) + fi + if test "$tst_nargs_gethostbyname_r" = "unknown"; then + AC_MSG_CHECKING([if gethostbyname_r takes 5 args.]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_netdb + $curl_includes_bsdsocket + ]],[[ + if(0 != gethostbyname_r(0, 0, 0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_gethostbyname_r="yes" + tst_nargs_gethostbyname_r="5" + ],[ + AC_MSG_RESULT([no]) + tst_compi_gethostbyname_r="no" + ]) + fi + if test "$tst_nargs_gethostbyname_r" = "unknown"; then + AC_MSG_CHECKING([if gethostbyname_r takes 6 args.]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_netdb + $curl_includes_bsdsocket + ]],[[ + if(0 != gethostbyname_r(0, 0, 0, 0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_gethostbyname_r="yes" + tst_nargs_gethostbyname_r="6" + ],[ + AC_MSG_RESULT([no]) + tst_compi_gethostbyname_r="no" + ]) + fi + AC_MSG_CHECKING([if gethostbyname_r is compilable]) + if test "$tst_compi_gethostbyname_r" = "yes"; then + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + fi + fi + # + if test "$tst_compi_gethostbyname_r" = "yes"; then + AC_MSG_CHECKING([if gethostbyname_r usage allowed]) + if test "x$curl_disallow_gethostbyname_r" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_gethostbyname_r="yes" + else + AC_MSG_RESULT([no]) + tst_allow_gethostbyname_r="no" + fi + fi + # + AC_MSG_CHECKING([if gethostbyname_r might be used]) + if test "$tst_links_gethostbyname_r" = "yes" && + test "$tst_proto_gethostbyname_r" = "yes" && + test "$tst_compi_gethostbyname_r" = "yes" && + test "$tst_allow_gethostbyname_r" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_GETHOSTBYNAME_R, 1, + [Define to 1 if you have the gethostbyname_r function.]) + dnl AC_DEFINE_UNQUOTED(GETHOSTBYNAME_R_ARGS, $tst_nargs_gethostbyname_r, + dnl [Specifies the number of arguments to gethostbyname_r]) + # + if test "$tst_nargs_gethostbyname_r" -eq "3"; then + AC_DEFINE(HAVE_GETHOSTBYNAME_R_3, 1, [gethostbyname_r() takes 3 args]) + elif test "$tst_nargs_gethostbyname_r" -eq "5"; then + AC_DEFINE(HAVE_GETHOSTBYNAME_R_5, 1, [gethostbyname_r() takes 5 args]) + elif test "$tst_nargs_gethostbyname_r" -eq "6"; then + AC_DEFINE(HAVE_GETHOSTBYNAME_R_6, 1, [gethostbyname_r() takes 6 args]) + fi + # + curl_cv_func_gethostbyname_r="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_gethostbyname_r="no" + fi +]) + + +dnl CURL_CHECK_FUNC_GETHOSTNAME +dnl ------------------------------------------------- +dnl Verify if gethostname is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_gethostname, then +dnl HAVE_GETHOSTNAME will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_GETHOSTNAME], [ + AC_REQUIRE([CURL_INCLUDES_WINSOCK2])dnl + AC_REQUIRE([CURL_INCLUDES_BSDSOCKET])dnl + AC_REQUIRE([CURL_INCLUDES_UNISTD])dnl + AC_REQUIRE([CURL_PREPROCESS_CALLCONV])dnl + # + tst_links_gethostname="unknown" + tst_proto_gethostname="unknown" + tst_compi_gethostname="unknown" + tst_allow_gethostname="unknown" + # + AC_MSG_CHECKING([if gethostname can be linked]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_unistd + $curl_includes_bsdsocket + ]],[[ + if(0 != gethostname(0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_gethostname="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_gethostname="no" + ]) + # + if test "$tst_links_gethostname" = "yes"; then + AC_MSG_CHECKING([if gethostname is prototyped]) + AC_EGREP_CPP([gethostname],[ + $curl_includes_winsock2 + $curl_includes_unistd + $curl_includes_bsdsocket + ],[ + AC_MSG_RESULT([yes]) + tst_proto_gethostname="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_gethostname="no" + ]) + fi + # + if test "$tst_proto_gethostname" = "yes"; then + AC_MSG_CHECKING([if gethostname is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_unistd + $curl_includes_bsdsocket + ]],[[ + if(0 != gethostname(0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_gethostname="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_gethostname="no" + ]) + fi + # + if test "$tst_compi_gethostname" = "yes"; then + AC_MSG_CHECKING([for gethostname arg 2 data type]) + tst_gethostname_type_arg2="unknown" + for tst_arg1 in 'char *' 'unsigned char *' 'void *'; do + for tst_arg2 in 'int' 'unsigned int' 'size_t'; do + if test "$tst_gethostname_type_arg2" = "unknown"; then + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_unistd + $curl_includes_bsdsocket + $curl_preprocess_callconv + extern int FUNCALLCONV gethostname($tst_arg1, $tst_arg2); + ]],[[ + if(0 != gethostname(0, 0)) + return 1; + ]]) + ],[ + tst_gethostname_type_arg2="$tst_arg2" + ]) + fi + done + done + AC_MSG_RESULT([$tst_gethostname_type_arg2]) + if test "$tst_gethostname_type_arg2" != "unknown"; then + AC_DEFINE_UNQUOTED(GETHOSTNAME_TYPE_ARG2, $tst_gethostname_type_arg2, + [Define to the type of arg 2 for gethostname.]) + fi + fi + # + if test "$tst_compi_gethostname" = "yes"; then + AC_MSG_CHECKING([if gethostname usage allowed]) + if test "x$curl_disallow_gethostname" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_gethostname="yes" + else + AC_MSG_RESULT([no]) + tst_allow_gethostname="no" + fi + fi + # + AC_MSG_CHECKING([if gethostname might be used]) + if test "$tst_links_gethostname" = "yes" && + test "$tst_proto_gethostname" = "yes" && + test "$tst_compi_gethostname" = "yes" && + test "$tst_allow_gethostname" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_GETHOSTNAME, 1, + [Define to 1 if you have the gethostname function.]) + curl_cv_func_gethostname="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_gethostname="no" + fi +]) + +dnl CURL_CHECK_FUNC_GETPEERNAME +dnl ------------------------------------------------- +dnl Verify if getpeername is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_getpeername, then +dnl HAVE_GETPEERNAME will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_GETPEERNAME], [ + AC_REQUIRE([CURL_INCLUDES_WINSOCK2])dnl + AC_REQUIRE([CURL_INCLUDES_UNISTD])dnl + AC_REQUIRE([CURL_PREPROCESS_CALLCONV])dnl + AC_REQUIRE([CURL_INCLUDES_BSDSOCKET])dnl + # + tst_links_getpeername="unknown" + tst_proto_getpeername="unknown" + tst_compi_getpeername="unknown" + tst_allow_getpeername="unknown" + # + AC_MSG_CHECKING([if getpeername can be linked]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + ]],[[ + if(0 != getpeername(0, (void *)0, (void *)0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_getpeername="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_getpeername="no" + ]) + # + if test "$tst_links_getpeername" = "yes"; then + AC_MSG_CHECKING([if getpeername is prototyped]) + AC_EGREP_CPP([getpeername],[ + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + ],[ + AC_MSG_RESULT([yes]) + tst_proto_getpeername="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_getpeername="no" + ]) + fi + # + if test "$tst_proto_getpeername" = "yes"; then + AC_MSG_CHECKING([if getpeername is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + ]],[[ + if(0 != getpeername(0, (void *)0, (void *)0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_getpeername="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_getpeername="no" + ]) + fi + # + if test "$tst_compi_getpeername" = "yes"; then + AC_MSG_CHECKING([if getpeername usage allowed]) + if test "x$curl_disallow_getpeername" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_getpeername="yes" + else + AC_MSG_RESULT([no]) + tst_allow_getpeername="no" + fi + fi + # + AC_MSG_CHECKING([if getpeername might be used]) + if test "$tst_links_getpeername" = "yes" && + test "$tst_proto_getpeername" = "yes" && + test "$tst_compi_getpeername" = "yes" && + test "$tst_allow_getpeername" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_GETPEERNAME, 1, + [Define to 1 if you have the getpeername function.]) + curl_cv_func_getpeername="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_getpeername="no" + fi +]) + +dnl CURL_CHECK_FUNC_GETSOCKNAME +dnl ------------------------------------------------- +dnl Verify if getsockname is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_getsockname, then +dnl HAVE_GETSOCKNAME will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_GETSOCKNAME], [ + AC_REQUIRE([CURL_INCLUDES_WINSOCK2])dnl + AC_REQUIRE([CURL_INCLUDES_UNISTD])dnl + AC_REQUIRE([CURL_PREPROCESS_CALLCONV])dnl + AC_REQUIRE([CURL_INCLUDES_BSDSOCKET])dnl + # + tst_links_getsockname="unknown" + tst_proto_getsockname="unknown" + tst_compi_getsockname="unknown" + tst_allow_getsockname="unknown" + # + AC_MSG_CHECKING([if getsockname can be linked]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + ]],[[ + if(0 != getsockname(0, (void *)0, (void *)0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_getsockname="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_getsockname="no" + ]) + # + if test "$tst_links_getsockname" = "yes"; then + AC_MSG_CHECKING([if getsockname is prototyped]) + AC_EGREP_CPP([getsockname],[ + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + ],[ + AC_MSG_RESULT([yes]) + tst_proto_getsockname="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_getsockname="no" + ]) + fi + # + if test "$tst_proto_getsockname" = "yes"; then + AC_MSG_CHECKING([if getsockname is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + ]],[[ + if(0 != getsockname(0, (void *)0, (void *)0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_getsockname="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_getsockname="no" + ]) + fi + # + if test "$tst_compi_getsockname" = "yes"; then + AC_MSG_CHECKING([if getsockname usage allowed]) + if test "x$curl_disallow_getsockname" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_getsockname="yes" + else + AC_MSG_RESULT([no]) + tst_allow_getsockname="no" + fi + fi + # + AC_MSG_CHECKING([if getsockname might be used]) + if test "$tst_links_getsockname" = "yes" && + test "$tst_proto_getsockname" = "yes" && + test "$tst_compi_getsockname" = "yes" && + test "$tst_allow_getsockname" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_GETSOCKNAME, 1, + [Define to 1 if you have the getsockname function.]) + curl_cv_func_getsockname="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_getsockname="no" + fi +]) + +dnl CURL_CHECK_FUNC_IF_NAMETOINDEX +dnl ------------------------------------------------- +dnl Verify if if_nametoindex is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_if_nametoindex, then +dnl HAVE_IF_NAMETOINDEX will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_IF_NAMETOINDEX], [ + AC_REQUIRE([CURL_INCLUDES_WINSOCK2])dnl + AC_REQUIRE([CURL_INCLUDES_NETIF])dnl + AC_REQUIRE([CURL_PREPROCESS_CALLCONV])dnl + # + tst_links_if_nametoindex="unknown" + tst_proto_if_nametoindex="unknown" + tst_compi_if_nametoindex="unknown" + tst_allow_if_nametoindex="unknown" + # + AC_MSG_CHECKING([if if_nametoindex can be linked]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_bsdsocket + #include + ]],[[ + if(0 != if_nametoindex("")) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_if_nametoindex="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_if_nametoindex="no" + ]) + # + if test "$tst_links_if_nametoindex" = "yes"; then + AC_MSG_CHECKING([if if_nametoindex is prototyped]) + AC_EGREP_CPP([if_nametoindex],[ + $curl_includes_winsock2 + $curl_includes_netif + ],[ + AC_MSG_RESULT([yes]) + tst_proto_if_nametoindex="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_if_nametoindex="no" + ]) + fi + # + if test "$tst_proto_if_nametoindex" = "yes"; then + AC_MSG_CHECKING([if if_nametoindex is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_netif + ]],[[ + if(0 != if_nametoindex("")) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_if_nametoindex="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_if_nametoindex="no" + ]) + fi + # + if test "$tst_compi_if_nametoindex" = "yes"; then + AC_MSG_CHECKING([if if_nametoindex usage allowed]) + if test "x$curl_disallow_if_nametoindex" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_if_nametoindex="yes" + else + AC_MSG_RESULT([no]) + tst_allow_if_nametoindex="no" + fi + fi + # + AC_MSG_CHECKING([if if_nametoindex might be used]) + if test "$tst_links_if_nametoindex" = "yes" && + test "$tst_proto_if_nametoindex" = "yes" && + test "$tst_compi_if_nametoindex" = "yes" && + test "$tst_allow_if_nametoindex" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_IF_NAMETOINDEX, 1, + [Define to 1 if you have the if_nametoindex function.]) + curl_cv_func_if_nametoindex="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_if_nametoindex="no" + fi +]) + + +dnl CURL_CHECK_FUNC_GETIFADDRS +dnl ------------------------------------------------- +dnl Verify if getifaddrs is available, prototyped, can +dnl be compiled and seems to work. If all of these are +dnl true, and usage has not been previously disallowed +dnl with shell variable curl_disallow_getifaddrs, then +dnl HAVE_GETIFADDRS will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_GETIFADDRS], [ + AC_REQUIRE([CURL_INCLUDES_STDLIB])dnl + AC_REQUIRE([CURL_INCLUDES_IFADDRS])dnl + # + tst_links_getifaddrs="unknown" + tst_proto_getifaddrs="unknown" + tst_compi_getifaddrs="unknown" + tst_works_getifaddrs="unknown" + tst_allow_getifaddrs="unknown" + # + AC_MSG_CHECKING([if getifaddrs can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([getifaddrs]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_getifaddrs="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_getifaddrs="no" + ]) + # + if test "$tst_links_getifaddrs" = "yes"; then + AC_MSG_CHECKING([if getifaddrs is prototyped]) + AC_EGREP_CPP([getifaddrs],[ + $curl_includes_ifaddrs + ],[ + AC_MSG_RESULT([yes]) + tst_proto_getifaddrs="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_getifaddrs="no" + ]) + fi + # + if test "$tst_proto_getifaddrs" = "yes"; then + AC_MSG_CHECKING([if getifaddrs is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_ifaddrs + ]],[[ + if(0 != getifaddrs(0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_getifaddrs="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_getifaddrs="no" + ]) + fi + # + dnl only do runtime verification when not cross-compiling + if test "x$cross_compiling" != "xyes" && + test "$tst_compi_getifaddrs" = "yes"; then + AC_MSG_CHECKING([if getifaddrs seems to work]) + CURL_RUN_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_stdlib + $curl_includes_ifaddrs + ]],[[ + struct ifaddrs *ifa = 0; + int error; + + error = getifaddrs(&ifa); + if(error || !ifa) + exit(1); /* fail */ + else + exit(0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_works_getifaddrs="yes" + ],[ + AC_MSG_RESULT([no]) + tst_works_getifaddrs="no" + ]) + fi + # + if test "$tst_compi_getifaddrs" = "yes" && + test "$tst_works_getifaddrs" != "no"; then + AC_MSG_CHECKING([if getifaddrs usage allowed]) + if test "x$curl_disallow_getifaddrs" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_getifaddrs="yes" + else + AC_MSG_RESULT([no]) + tst_allow_getifaddrs="no" + fi + fi + # + AC_MSG_CHECKING([if getifaddrs might be used]) + if test "$tst_links_getifaddrs" = "yes" && + test "$tst_proto_getifaddrs" = "yes" && + test "$tst_compi_getifaddrs" = "yes" && + test "$tst_allow_getifaddrs" = "yes" && + test "$tst_works_getifaddrs" != "no"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_GETIFADDRS, 1, + [Define to 1 if you have a working getifaddrs function.]) + curl_cv_func_getifaddrs="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_getifaddrs="no" + fi +]) + + +dnl CURL_CHECK_FUNC_GMTIME_R +dnl ------------------------------------------------- +dnl Verify if gmtime_r is available, prototyped, can +dnl be compiled and seems to work. If all of these are +dnl true, and usage has not been previously disallowed +dnl with shell variable curl_disallow_gmtime_r, then +dnl HAVE_GMTIME_R will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_GMTIME_R], [ + AC_REQUIRE([CURL_INCLUDES_STDLIB])dnl + AC_REQUIRE([CURL_INCLUDES_TIME])dnl + # + tst_links_gmtime_r="unknown" + tst_proto_gmtime_r="unknown" + tst_compi_gmtime_r="unknown" + tst_works_gmtime_r="unknown" + tst_allow_gmtime_r="unknown" + # + AC_MSG_CHECKING([if gmtime_r can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([gmtime_r]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_gmtime_r="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_gmtime_r="no" + ]) + # + if test "$tst_links_gmtime_r" = "yes"; then + AC_MSG_CHECKING([if gmtime_r is prototyped]) + AC_EGREP_CPP([gmtime_r],[ + $curl_includes_time + ],[ + AC_MSG_RESULT([yes]) + tst_proto_gmtime_r="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_gmtime_r="no" + ]) + fi + # + if test "$tst_proto_gmtime_r" = "yes"; then + AC_MSG_CHECKING([if gmtime_r is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_time + ]],[[ + if(0 != gmtime_r(0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_gmtime_r="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_gmtime_r="no" + ]) + fi + # + dnl only do runtime verification when not cross-compiling + if test "x$cross_compiling" != "xyes" && + test "$tst_compi_gmtime_r" = "yes"; then + AC_MSG_CHECKING([if gmtime_r seems to work]) + CURL_RUN_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_stdlib + $curl_includes_time + ]],[[ + time_t local = 1170352587; + struct tm *gmt = 0; + struct tm result; + gmt = gmtime_r(&local, &result); + if(gmt) + exit(0); + else + exit(1); + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_works_gmtime_r="yes" + ],[ + AC_MSG_RESULT([no]) + tst_works_gmtime_r="no" + ]) + fi + # + if test "$tst_compi_gmtime_r" = "yes" && + test "$tst_works_gmtime_r" != "no"; then + AC_MSG_CHECKING([if gmtime_r usage allowed]) + if test "x$curl_disallow_gmtime_r" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_gmtime_r="yes" + else + AC_MSG_RESULT([no]) + tst_allow_gmtime_r="no" + fi + fi + # + AC_MSG_CHECKING([if gmtime_r might be used]) + if test "$tst_links_gmtime_r" = "yes" && + test "$tst_proto_gmtime_r" = "yes" && + test "$tst_compi_gmtime_r" = "yes" && + test "$tst_allow_gmtime_r" = "yes" && + test "$tst_works_gmtime_r" != "no"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_GMTIME_R, 1, + [Define to 1 if you have a working gmtime_r function.]) + curl_cv_func_gmtime_r="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_gmtime_r="no" + fi +]) + + +dnl CURL_CHECK_FUNC_INET_NTOP +dnl ------------------------------------------------- +dnl Verify if inet_ntop is available, prototyped, can +dnl be compiled and seems to work. If all of these are +dnl true, and usage has not been previously disallowed +dnl with shell variable curl_disallow_inet_ntop, then +dnl HAVE_INET_NTOP will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_INET_NTOP], [ + AC_REQUIRE([CURL_INCLUDES_STDLIB])dnl + AC_REQUIRE([CURL_INCLUDES_ARPA_INET])dnl + AC_REQUIRE([CURL_INCLUDES_STRING])dnl + # + tst_links_inet_ntop="unknown" + tst_proto_inet_ntop="unknown" + tst_compi_inet_ntop="unknown" + tst_works_inet_ntop="unknown" + tst_allow_inet_ntop="unknown" + # + AC_MSG_CHECKING([if inet_ntop can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([inet_ntop]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_inet_ntop="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_inet_ntop="no" + ]) + # + if test "$tst_links_inet_ntop" = "yes"; then + AC_MSG_CHECKING([if inet_ntop is prototyped]) + AC_EGREP_CPP([inet_ntop],[ + $curl_includes_arpa_inet + ],[ + AC_MSG_RESULT([yes]) + tst_proto_inet_ntop="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_inet_ntop="no" + ]) + fi + # + if test "$tst_proto_inet_ntop" = "yes"; then + AC_MSG_CHECKING([if inet_ntop is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_arpa_inet + ]],[[ + if(0 != inet_ntop(0, 0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_inet_ntop="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_inet_ntop="no" + ]) + fi + # + dnl only do runtime verification when not cross-compiling + if test "x$cross_compiling" != "xyes" && + test "$tst_compi_inet_ntop" = "yes"; then + AC_MSG_CHECKING([if inet_ntop seems to work]) + CURL_RUN_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_stdlib + $curl_includes_arpa_inet + $curl_includes_string + ]],[[ + char ipv6res[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")]; + char ipv4res[sizeof "255.255.255.255"]; + unsigned char ipv6a[26]; + unsigned char ipv4a[5]; + char *ipv6ptr = 0; + char *ipv4ptr = 0; + /* - */ + ipv4res[0] = '\0'; + ipv4a[0] = 0xc0; + ipv4a[1] = 0xa8; + ipv4a[2] = 0x64; + ipv4a[3] = 0x01; + ipv4a[4] = 0x01; + /* - */ + ipv4ptr = inet_ntop(AF_INET, ipv4a, ipv4res, sizeof(ipv4res)); + if(!ipv4ptr) + exit(1); /* fail */ + if(ipv4ptr != ipv4res) + exit(1); /* fail */ + if(!ipv4ptr[0]) + exit(1); /* fail */ + if(memcmp(ipv4res, "192.168.100.1", 13) != 0) + exit(1); /* fail */ + /* - */ + ipv6res[0] = '\0'; + memset(ipv6a, 0, sizeof(ipv6a)); + ipv6a[0] = 0xfe; + ipv6a[1] = 0x80; + ipv6a[8] = 0x02; + ipv6a[9] = 0x14; + ipv6a[10] = 0x4f; + ipv6a[11] = 0xff; + ipv6a[12] = 0xfe; + ipv6a[13] = 0x0b; + ipv6a[14] = 0x76; + ipv6a[15] = 0xc8; + ipv6a[25] = 0x01; + /* - */ + ipv6ptr = inet_ntop(AF_INET6, ipv6a, ipv6res, sizeof(ipv6res)); + if(!ipv6ptr) + exit(1); /* fail */ + if(ipv6ptr != ipv6res) + exit(1); /* fail */ + if(!ipv6ptr[0]) + exit(1); /* fail */ + if(memcmp(ipv6res, "fe80::214:4fff:fe0b:76c8", 24) != 0) + exit(1); /* fail */ + /* - */ + exit(0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_works_inet_ntop="yes" + ],[ + AC_MSG_RESULT([no]) + tst_works_inet_ntop="no" + ]) + fi + # + if test "$tst_compi_inet_ntop" = "yes" && + test "$tst_works_inet_ntop" != "no"; then + AC_MSG_CHECKING([if inet_ntop usage allowed]) + if test "x$curl_disallow_inet_ntop" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_inet_ntop="yes" + else + AC_MSG_RESULT([no]) + tst_allow_inet_ntop="no" + fi + fi + # + AC_MSG_CHECKING([if inet_ntop might be used]) + if test "$tst_links_inet_ntop" = "yes" && + test "$tst_proto_inet_ntop" = "yes" && + test "$tst_compi_inet_ntop" = "yes" && + test "$tst_allow_inet_ntop" = "yes" && + test "$tst_works_inet_ntop" != "no"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_INET_NTOP, 1, + [Define to 1 if you have a IPv6 capable working inet_ntop function.]) + curl_cv_func_inet_ntop="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_inet_ntop="no" + fi +]) + + +dnl CURL_CHECK_FUNC_INET_PTON +dnl ------------------------------------------------- +dnl Verify if inet_pton is available, prototyped, can +dnl be compiled and seems to work. If all of these are +dnl true, and usage has not been previously disallowed +dnl with shell variable curl_disallow_inet_pton, then +dnl HAVE_INET_PTON will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_INET_PTON], [ + AC_REQUIRE([CURL_INCLUDES_STDLIB])dnl + AC_REQUIRE([CURL_INCLUDES_ARPA_INET])dnl + AC_REQUIRE([CURL_INCLUDES_STRING])dnl + # + tst_links_inet_pton="unknown" + tst_proto_inet_pton="unknown" + tst_compi_inet_pton="unknown" + tst_works_inet_pton="unknown" + tst_allow_inet_pton="unknown" + # + AC_MSG_CHECKING([if inet_pton can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([inet_pton]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_inet_pton="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_inet_pton="no" + ]) + # + if test "$tst_links_inet_pton" = "yes"; then + AC_MSG_CHECKING([if inet_pton is prototyped]) + AC_EGREP_CPP([inet_pton],[ + $curl_includes_arpa_inet + ],[ + AC_MSG_RESULT([yes]) + tst_proto_inet_pton="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_inet_pton="no" + ]) + fi + # + if test "$tst_proto_inet_pton" = "yes"; then + AC_MSG_CHECKING([if inet_pton is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_arpa_inet + ]],[[ + if(0 != inet_pton(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_inet_pton="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_inet_pton="no" + ]) + fi + # + dnl only do runtime verification when not cross-compiling + if test "x$cross_compiling" != "xyes" && + test "$tst_compi_inet_pton" = "yes"; then + AC_MSG_CHECKING([if inet_pton seems to work]) + CURL_RUN_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_stdlib + $curl_includes_arpa_inet + $curl_includes_string + ]],[[ + unsigned char ipv6a[16+1]; + unsigned char ipv4a[4+1]; + const char *ipv6src = "fe80::214:4fff:fe0b:76c8"; + const char *ipv4src = "192.168.100.1"; + /* - */ + memset(ipv4a, 1, sizeof(ipv4a)); + if(1 != inet_pton(AF_INET, ipv4src, ipv4a)) + exit(1); /* fail */ + /* - */ + if( (ipv4a[0] != 0xc0) || + (ipv4a[1] != 0xa8) || + (ipv4a[2] != 0x64) || + (ipv4a[3] != 0x01) || + (ipv4a[4] != 0x01) ) + exit(1); /* fail */ + /* - */ + memset(ipv6a, 1, sizeof(ipv6a)); + if(1 != inet_pton(AF_INET6, ipv6src, ipv6a)) + exit(1); /* fail */ + /* - */ + if( (ipv6a[0] != 0xfe) || + (ipv6a[1] != 0x80) || + (ipv6a[8] != 0x02) || + (ipv6a[9] != 0x14) || + (ipv6a[10] != 0x4f) || + (ipv6a[11] != 0xff) || + (ipv6a[12] != 0xfe) || + (ipv6a[13] != 0x0b) || + (ipv6a[14] != 0x76) || + (ipv6a[15] != 0xc8) || + (ipv6a[16] != 0x01) ) + exit(1); /* fail */ + /* - */ + if( (ipv6a[2] != 0x0) || + (ipv6a[3] != 0x0) || + (ipv6a[4] != 0x0) || + (ipv6a[5] != 0x0) || + (ipv6a[6] != 0x0) || + (ipv6a[7] != 0x0) ) + exit(1); /* fail */ + /* - */ + exit(0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_works_inet_pton="yes" + ],[ + AC_MSG_RESULT([no]) + tst_works_inet_pton="no" + ]) + fi + # + if test "$tst_compi_inet_pton" = "yes" && + test "$tst_works_inet_pton" != "no"; then + AC_MSG_CHECKING([if inet_pton usage allowed]) + if test "x$curl_disallow_inet_pton" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_inet_pton="yes" + else + AC_MSG_RESULT([no]) + tst_allow_inet_pton="no" + fi + fi + # + AC_MSG_CHECKING([if inet_pton might be used]) + if test "$tst_links_inet_pton" = "yes" && + test "$tst_proto_inet_pton" = "yes" && + test "$tst_compi_inet_pton" = "yes" && + test "$tst_allow_inet_pton" = "yes" && + test "$tst_works_inet_pton" != "no"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_INET_PTON, 1, + [Define to 1 if you have a IPv6 capable working inet_pton function.]) + curl_cv_func_inet_pton="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_inet_pton="no" + fi +]) + + +dnl CURL_CHECK_FUNC_IOCTL +dnl ------------------------------------------------- +dnl Verify if ioctl is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_ioctl, then +dnl HAVE_IOCTL will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_IOCTL], [ + AC_REQUIRE([CURL_INCLUDES_STROPTS])dnl + # + tst_links_ioctl="unknown" + tst_proto_ioctl="unknown" + tst_compi_ioctl="unknown" + tst_allow_ioctl="unknown" + # + AC_MSG_CHECKING([if ioctl can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([ioctl]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_ioctl="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_ioctl="no" + ]) + # + if test "$tst_links_ioctl" = "yes"; then + AC_MSG_CHECKING([if ioctl is prototyped]) + AC_EGREP_CPP([ioctl],[ + $curl_includes_stropts + ],[ + AC_MSG_RESULT([yes]) + tst_proto_ioctl="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_ioctl="no" + ]) + fi + # + if test "$tst_proto_ioctl" = "yes"; then + AC_MSG_CHECKING([if ioctl is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_stropts + ]],[[ + if(0 != ioctl(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_ioctl="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_ioctl="no" + ]) + fi + # + if test "$tst_compi_ioctl" = "yes"; then + AC_MSG_CHECKING([if ioctl usage allowed]) + if test "x$curl_disallow_ioctl" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_ioctl="yes" + else + AC_MSG_RESULT([no]) + tst_allow_ioctl="no" + fi + fi + # + AC_MSG_CHECKING([if ioctl might be used]) + if test "$tst_links_ioctl" = "yes" && + test "$tst_proto_ioctl" = "yes" && + test "$tst_compi_ioctl" = "yes" && + test "$tst_allow_ioctl" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_IOCTL, 1, + [Define to 1 if you have the ioctl function.]) + curl_cv_func_ioctl="yes" + CURL_CHECK_FUNC_IOCTL_FIONBIO + CURL_CHECK_FUNC_IOCTL_SIOCGIFADDR + else + AC_MSG_RESULT([no]) + curl_cv_func_ioctl="no" + fi +]) + + +dnl CURL_CHECK_FUNC_IOCTL_FIONBIO +dnl ------------------------------------------------- +dnl Verify if ioctl with the FIONBIO command is +dnl available, can be compiled, and seems to work. If +dnl all of these are true, then HAVE_IOCTL_FIONBIO +dnl will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_IOCTL_FIONBIO], [ + # + tst_compi_ioctl_fionbio="unknown" + tst_allow_ioctl_fionbio="unknown" + # + if test "$curl_cv_func_ioctl" = "yes"; then + AC_MSG_CHECKING([if ioctl FIONBIO is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_stropts + ]],[[ + int flags = 0; + if(0 != ioctl(0, FIONBIO, &flags)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_ioctl_fionbio="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_ioctl_fionbio="no" + ]) + fi + # + if test "$tst_compi_ioctl_fionbio" = "yes"; then + AC_MSG_CHECKING([if ioctl FIONBIO usage allowed]) + if test "x$curl_disallow_ioctl_fionbio" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_ioctl_fionbio="yes" + else + AC_MSG_RESULT([no]) + tst_allow_ioctl_fionbio="no" + fi + fi + # + AC_MSG_CHECKING([if ioctl FIONBIO might be used]) + if test "$tst_compi_ioctl_fionbio" = "yes" && + test "$tst_allow_ioctl_fionbio" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_IOCTL_FIONBIO, 1, + [Define to 1 if you have a working ioctl FIONBIO function.]) + curl_cv_func_ioctl_fionbio="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_ioctl_fionbio="no" + fi +]) + + +dnl CURL_CHECK_FUNC_IOCTL_SIOCGIFADDR +dnl ------------------------------------------------- +dnl Verify if ioctl with the SIOCGIFADDR command is available, +dnl struct ifreq is defined, they can be compiled, and seem to +dnl work. If all of these are true, then HAVE_IOCTL_SIOCGIFADDR +dnl will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_IOCTL_SIOCGIFADDR], [ + # + tst_compi_ioctl_siocgifaddr="unknown" + tst_allow_ioctl_siocgifaddr="unknown" + # + if test "$curl_cv_func_ioctl" = "yes"; then + AC_MSG_CHECKING([if ioctl SIOCGIFADDR is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_stropts + #include + ]],[[ + struct ifreq ifr; + if(0 != ioctl(0, SIOCGIFADDR, &ifr)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_ioctl_siocgifaddr="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_ioctl_siocgifaddr="no" + ]) + fi + # + if test "$tst_compi_ioctl_siocgifaddr" = "yes"; then + AC_MSG_CHECKING([if ioctl SIOCGIFADDR usage allowed]) + if test "x$curl_disallow_ioctl_siocgifaddr" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_ioctl_siocgifaddr="yes" + else + AC_MSG_RESULT([no]) + tst_allow_ioctl_siocgifaddr="no" + fi + fi + # + AC_MSG_CHECKING([if ioctl SIOCGIFADDR might be used]) + if test "$tst_compi_ioctl_siocgifaddr" = "yes" && + test "$tst_allow_ioctl_siocgifaddr" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_IOCTL_SIOCGIFADDR, 1, + [Define to 1 if you have a working ioctl SIOCGIFADDR function.]) + curl_cv_func_ioctl_siocgifaddr="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_ioctl_siocgifaddr="no" + fi +]) + + +dnl CURL_CHECK_FUNC_IOCTLSOCKET +dnl ------------------------------------------------- +dnl Verify if ioctlsocket is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_ioctlsocket, then +dnl HAVE_IOCTLSOCKET will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_IOCTLSOCKET], [ + AC_REQUIRE([CURL_INCLUDES_WINSOCK2])dnl + # + tst_links_ioctlsocket="unknown" + tst_proto_ioctlsocket="unknown" + tst_compi_ioctlsocket="unknown" + tst_allow_ioctlsocket="unknown" + # + AC_MSG_CHECKING([if ioctlsocket can be linked]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + ]],[[ + if(0 != ioctlsocket(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_ioctlsocket="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_ioctlsocket="no" + ]) + # + if test "$tst_links_ioctlsocket" = "yes"; then + AC_MSG_CHECKING([if ioctlsocket is prototyped]) + AC_EGREP_CPP([ioctlsocket],[ + $curl_includes_winsock2 + ],[ + AC_MSG_RESULT([yes]) + tst_proto_ioctlsocket="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_ioctlsocket="no" + ]) + fi + # + if test "$tst_proto_ioctlsocket" = "yes"; then + AC_MSG_CHECKING([if ioctlsocket is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + ]],[[ + if(0 != ioctlsocket(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_ioctlsocket="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_ioctlsocket="no" + ]) + fi + # + if test "$tst_compi_ioctlsocket" = "yes"; then + AC_MSG_CHECKING([if ioctlsocket usage allowed]) + if test "x$curl_disallow_ioctlsocket" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_ioctlsocket="yes" + else + AC_MSG_RESULT([no]) + tst_allow_ioctlsocket="no" + fi + fi + # + AC_MSG_CHECKING([if ioctlsocket might be used]) + if test "$tst_links_ioctlsocket" = "yes" && + test "$tst_proto_ioctlsocket" = "yes" && + test "$tst_compi_ioctlsocket" = "yes" && + test "$tst_allow_ioctlsocket" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_IOCTLSOCKET, 1, + [Define to 1 if you have the ioctlsocket function.]) + curl_cv_func_ioctlsocket="yes" + CURL_CHECK_FUNC_IOCTLSOCKET_FIONBIO + else + AC_MSG_RESULT([no]) + curl_cv_func_ioctlsocket="no" + fi +]) + + +dnl CURL_CHECK_FUNC_IOCTLSOCKET_FIONBIO +dnl ------------------------------------------------- +dnl Verify if ioctlsocket with the FIONBIO command is +dnl available, can be compiled, and seems to work. If +dnl all of these are true, then HAVE_IOCTLSOCKET_FIONBIO +dnl will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_IOCTLSOCKET_FIONBIO], [ + # + tst_compi_ioctlsocket_fionbio="unknown" + tst_allow_ioctlsocket_fionbio="unknown" + # + if test "$curl_cv_func_ioctlsocket" = "yes"; then + AC_MSG_CHECKING([if ioctlsocket FIONBIO is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + ]],[[ + unsigned long flags = 0; + if(0 != ioctlsocket(0, FIONBIO, &flags)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_ioctlsocket_fionbio="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_ioctlsocket_fionbio="no" + ]) + fi + # + if test "$tst_compi_ioctlsocket_fionbio" = "yes"; then + AC_MSG_CHECKING([if ioctlsocket FIONBIO usage allowed]) + if test "x$curl_disallow_ioctlsocket_fionbio" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_ioctlsocket_fionbio="yes" + else + AC_MSG_RESULT([no]) + tst_allow_ioctlsocket_fionbio="no" + fi + fi + # + AC_MSG_CHECKING([if ioctlsocket FIONBIO might be used]) + if test "$tst_compi_ioctlsocket_fionbio" = "yes" && + test "$tst_allow_ioctlsocket_fionbio" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_IOCTLSOCKET_FIONBIO, 1, + [Define to 1 if you have a working ioctlsocket FIONBIO function.]) + curl_cv_func_ioctlsocket_fionbio="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_ioctlsocket_fionbio="no" + fi +]) + + +dnl CURL_CHECK_FUNC_IOCTLSOCKET_CAMEL +dnl ------------------------------------------------- +dnl Verify if IoctlSocket is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_ioctlsocket_camel, +dnl then HAVE_IOCTLSOCKET_CAMEL will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_IOCTLSOCKET_CAMEL], [ + AC_REQUIRE([CURL_INCLUDES_BSDSOCKET])dnl + # + tst_links_ioctlsocket_camel="unknown" + tst_proto_ioctlsocket_camel="unknown" + tst_compi_ioctlsocket_camel="unknown" + tst_allow_ioctlsocket_camel="unknown" + # + AC_MSG_CHECKING([if IoctlSocket can be linked]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_bsdsocket + ]],[[ + IoctlSocket(0, 0, 0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_ioctlsocket_camel="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_ioctlsocket_camel="no" + ]) + # + if test "$tst_links_ioctlsocket_camel" = "yes"; then + AC_MSG_CHECKING([if IoctlSocket is prototyped]) + AC_EGREP_CPP([IoctlSocket],[ + $curl_includes_bsdsocket + ],[ + AC_MSG_RESULT([yes]) + tst_proto_ioctlsocket_camel="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_ioctlsocket_camel="no" + ]) + fi + # + if test "$tst_proto_ioctlsocket_camel" = "yes"; then + AC_MSG_CHECKING([if IoctlSocket is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_bsdsocket + ]],[[ + if(0 != IoctlSocket(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_ioctlsocket_camel="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_ioctlsocket_camel="no" + ]) + fi + # + if test "$tst_compi_ioctlsocket_camel" = "yes"; then + AC_MSG_CHECKING([if IoctlSocket usage allowed]) + if test "x$curl_disallow_ioctlsocket_camel" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_ioctlsocket_camel="yes" + else + AC_MSG_RESULT([no]) + tst_allow_ioctlsocket_camel="no" + fi + fi + # + AC_MSG_CHECKING([if IoctlSocket might be used]) + if test "$tst_links_ioctlsocket_camel" = "yes" && + test "$tst_proto_ioctlsocket_camel" = "yes" && + test "$tst_compi_ioctlsocket_camel" = "yes" && + test "$tst_allow_ioctlsocket_camel" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_IOCTLSOCKET_CAMEL, 1, + [Define to 1 if you have the IoctlSocket camel case function.]) + curl_cv_func_ioctlsocket_camel="yes" + CURL_CHECK_FUNC_IOCTLSOCKET_CAMEL_FIONBIO + else + AC_MSG_RESULT([no]) + curl_cv_func_ioctlsocket_camel="no" + fi +]) + + +dnl CURL_CHECK_FUNC_IOCTLSOCKET_CAMEL_FIONBIO +dnl ------------------------------------------------- +dnl Verify if IoctlSocket with FIONBIO command is available, +dnl can be compiled, and seems to work. If all of these are +dnl true, then HAVE_IOCTLSOCKET_CAMEL_FIONBIO will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_IOCTLSOCKET_CAMEL_FIONBIO], [ + AC_REQUIRE([CURL_INCLUDES_BSDSOCKET])dnl + # + tst_compi_ioctlsocket_camel_fionbio="unknown" + tst_allow_ioctlsocket_camel_fionbio="unknown" + # + if test "$curl_cv_func_ioctlsocket_camel" = "yes"; then + AC_MSG_CHECKING([if IoctlSocket FIONBIO is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_bsdsocket + ]],[[ + long flags = 0; + if(0 != IoctlSocket(0, FIONBIO, &flags)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_ioctlsocket_camel_fionbio="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_ioctlsocket_camel_fionbio="no" + ]) + fi + # + if test "$tst_compi_ioctlsocket_camel_fionbio" = "yes"; then + AC_MSG_CHECKING([if IoctlSocket FIONBIO usage allowed]) + if test "x$curl_disallow_ioctlsocket_camel_fionbio" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_ioctlsocket_camel_fionbio="yes" + else + AC_MSG_RESULT([no]) + tst_allow_ioctlsocket_camel_fionbio="no" + fi + fi + # + AC_MSG_CHECKING([if IoctlSocket FIONBIO might be used]) + if test "$tst_compi_ioctlsocket_camel_fionbio" = "yes" && + test "$tst_allow_ioctlsocket_camel_fionbio" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_IOCTLSOCKET_CAMEL_FIONBIO, 1, + [Define to 1 if you have a working IoctlSocket camel case FIONBIO function.]) + curl_cv_func_ioctlsocket_camel_fionbio="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_ioctlsocket_camel_fionbio="no" + fi +]) + + +dnl CURL_CHECK_FUNC_MEMRCHR +dnl ------------------------------------------------- +dnl Verify if memrchr is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_memrchr, then +dnl HAVE_MEMRCHR will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_MEMRCHR], [ + AC_REQUIRE([CURL_INCLUDES_STRING])dnl + # + tst_links_memrchr="unknown" + tst_macro_memrchr="unknown" + tst_proto_memrchr="unknown" + tst_compi_memrchr="unknown" + tst_allow_memrchr="unknown" + # + AC_MSG_CHECKING([if memrchr can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([memrchr]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_memrchr="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_memrchr="no" + ]) + # + if test "$tst_links_memrchr" = "no"; then + AC_MSG_CHECKING([if memrchr seems a macro]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_string + ]],[[ + if(0 != memrchr(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_macro_memrchr="yes" + ],[ + AC_MSG_RESULT([no]) + tst_macro_memrchr="no" + ]) + fi + # + if test "$tst_links_memrchr" = "yes"; then + AC_MSG_CHECKING([if memrchr is prototyped]) + AC_EGREP_CPP([memrchr],[ + $curl_includes_string + ],[ + AC_MSG_RESULT([yes]) + tst_proto_memrchr="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_memrchr="no" + ]) + fi + # + if test "$tst_proto_memrchr" = "yes" || + test "$tst_macro_memrchr" = "yes"; then + AC_MSG_CHECKING([if memrchr is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_string + ]],[[ + if(0 != memrchr(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_memrchr="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_memrchr="no" + ]) + fi + # + if test "$tst_compi_memrchr" = "yes"; then + AC_MSG_CHECKING([if memrchr usage allowed]) + if test "x$curl_disallow_memrchr" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_memrchr="yes" + else + AC_MSG_RESULT([no]) + tst_allow_memrchr="no" + fi + fi + # + AC_MSG_CHECKING([if memrchr might be used]) + if (test "$tst_proto_memrchr" = "yes" || + test "$tst_macro_memrchr" = "yes") && + test "$tst_compi_memrchr" = "yes" && + test "$tst_allow_memrchr" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_MEMRCHR, 1, + [Define to 1 if you have the memrchr function or macro.]) + curl_cv_func_memrchr="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_memrchr="no" + fi +]) + + +dnl CURL_CHECK_FUNC_POLL +dnl ------------------------------------------------- +dnl Verify if poll is available, prototyped, can +dnl be compiled and seems to work. + +AC_DEFUN([CURL_CHECK_FUNC_POLL], [ + AC_REQUIRE([CURL_INCLUDES_STDLIB])dnl + AC_REQUIRE([CURL_INCLUDES_POLL])dnl + # + tst_links_poll="unknown" + tst_proto_poll="unknown" + tst_compi_poll="unknown" + tst_works_poll="unknown" + tst_allow_poll="unknown" + # + case $host_os in + darwin*|interix*) + dnl poll() does not work on these platforms + dnl Interix: "does provide poll(), but the implementing developer must + dnl have been in a bad mood, because poll() only works on the /proc + dnl filesystem here" + dnl macOS: poll() first didn't exist, then was broken until fixed in 10.9 + dnl only to break again in 10.12. + curl_disallow_poll="yes" + tst_compi_poll="no" + ;; + esac + # + AC_MSG_CHECKING([if poll can be linked]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_poll + ]],[[ + if(0 != poll(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_poll="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_poll="no" + ]) + # + if test "$tst_links_poll" = "yes"; then + AC_MSG_CHECKING([if poll is prototyped]) + AC_EGREP_CPP([poll],[ + $curl_includes_poll + ],[ + AC_MSG_RESULT([yes]) + tst_proto_poll="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_poll="no" + ]) + fi + # + if test "$tst_proto_poll" = "yes"; then + AC_MSG_CHECKING([if poll is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_poll + ]],[[ + if(0 != poll(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_poll="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_poll="no" + ]) + fi + # + dnl only do runtime verification when not cross-compiling + if test "x$cross_compiling" != "xyes" && + test "$tst_compi_poll" = "yes"; then + AC_MSG_CHECKING([if poll seems to work]) + CURL_RUN_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_stdlib + $curl_includes_poll + $curl_includes_time + ]],[[ + /* detect the original poll() breakage */ + if(0 != poll(0, 0, 10)) + exit(1); /* fail */ + else { + /* detect the 10.12 poll() breakage */ + struct timeval before, after; + int rc; + size_t us; + + gettimeofday(&before, NULL); + rc = poll(NULL, 0, 500); + gettimeofday(&after, NULL); + + us = (after.tv_sec - before.tv_sec) * 1000000 + + (after.tv_usec - before.tv_usec); + + if(us < 400000) + exit(1); + } + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_works_poll="yes" + ],[ + AC_MSG_RESULT([no]) + tst_works_poll="no" + ]) + fi + # + if test "$tst_compi_poll" = "yes" && + test "$tst_works_poll" != "no"; then + AC_MSG_CHECKING([if poll usage allowed]) + if test "x$curl_disallow_poll" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_poll="yes" + else + AC_MSG_RESULT([no]) + tst_allow_poll="no" + fi + fi + # + AC_MSG_CHECKING([if poll might be used]) + if test "$tst_links_poll" = "yes" && + test "$tst_proto_poll" = "yes" && + test "$tst_compi_poll" = "yes" && + test "$tst_allow_poll" = "yes" && + test "$tst_works_poll" != "no"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_POLL_FINE, 1, + [If you have a fine poll]) + curl_cv_func_poll="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_poll="no" + fi +]) + + + fi +]) + + +dnl CURL_CHECK_FUNC_SIGACTION +dnl ------------------------------------------------- +dnl Verify if sigaction is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_sigaction, then +dnl HAVE_SIGACTION will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_SIGACTION], [ + AC_REQUIRE([CURL_INCLUDES_SIGNAL])dnl + # + tst_links_sigaction="unknown" + tst_proto_sigaction="unknown" + tst_compi_sigaction="unknown" + tst_allow_sigaction="unknown" + # + AC_MSG_CHECKING([if sigaction can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([sigaction]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_sigaction="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_sigaction="no" + ]) + # + if test "$tst_links_sigaction" = "yes"; then + AC_MSG_CHECKING([if sigaction is prototyped]) + AC_EGREP_CPP([sigaction],[ + $curl_includes_signal + ],[ + AC_MSG_RESULT([yes]) + tst_proto_sigaction="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_sigaction="no" + ]) + fi + # + if test "$tst_proto_sigaction" = "yes"; then + AC_MSG_CHECKING([if sigaction is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_signal + ]],[[ + if(0 != sigaction(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_sigaction="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_sigaction="no" + ]) + fi + # + if test "$tst_compi_sigaction" = "yes"; then + AC_MSG_CHECKING([if sigaction usage allowed]) + if test "x$curl_disallow_sigaction" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_sigaction="yes" + else + AC_MSG_RESULT([no]) + tst_allow_sigaction="no" + fi + fi + # + AC_MSG_CHECKING([if sigaction might be used]) + if test "$tst_links_sigaction" = "yes" && + test "$tst_proto_sigaction" = "yes" && + test "$tst_compi_sigaction" = "yes" && + test "$tst_allow_sigaction" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_SIGACTION, 1, + [Define to 1 if you have the sigaction function.]) + curl_cv_func_sigaction="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_sigaction="no" + fi +]) + + +dnl CURL_CHECK_FUNC_SIGINTERRUPT +dnl ------------------------------------------------- +dnl Verify if siginterrupt is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_siginterrupt, then +dnl HAVE_SIGINTERRUPT will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_SIGINTERRUPT], [ + AC_REQUIRE([CURL_INCLUDES_SIGNAL])dnl + # + tst_links_siginterrupt="unknown" + tst_proto_siginterrupt="unknown" + tst_compi_siginterrupt="unknown" + tst_allow_siginterrupt="unknown" + # + AC_MSG_CHECKING([if siginterrupt can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([siginterrupt]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_siginterrupt="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_siginterrupt="no" + ]) + # + if test "$tst_links_siginterrupt" = "yes"; then + AC_MSG_CHECKING([if siginterrupt is prototyped]) + AC_EGREP_CPP([siginterrupt],[ + $curl_includes_signal + ],[ + AC_MSG_RESULT([yes]) + tst_proto_siginterrupt="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_siginterrupt="no" + ]) + fi + # + if test "$tst_proto_siginterrupt" = "yes"; then + AC_MSG_CHECKING([if siginterrupt is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_signal + ]],[[ + if(0 != siginterrupt(0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_siginterrupt="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_siginterrupt="no" + ]) + fi + # + if test "$tst_compi_siginterrupt" = "yes"; then + AC_MSG_CHECKING([if siginterrupt usage allowed]) + if test "x$curl_disallow_siginterrupt" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_siginterrupt="yes" + else + AC_MSG_RESULT([no]) + tst_allow_siginterrupt="no" + fi + fi + # + AC_MSG_CHECKING([if siginterrupt might be used]) + if test "$tst_links_siginterrupt" = "yes" && + test "$tst_proto_siginterrupt" = "yes" && + test "$tst_compi_siginterrupt" = "yes" && + test "$tst_allow_siginterrupt" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_SIGINTERRUPT, 1, + [Define to 1 if you have the siginterrupt function.]) + curl_cv_func_siginterrupt="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_siginterrupt="no" + fi +]) + + +dnl CURL_CHECK_FUNC_SIGNAL +dnl ------------------------------------------------- +dnl Verify if signal is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_signal, then +dnl HAVE_SIGNAL will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_SIGNAL], [ + AC_REQUIRE([CURL_INCLUDES_SIGNAL])dnl + # + tst_links_signal="unknown" + tst_proto_signal="unknown" + tst_compi_signal="unknown" + tst_allow_signal="unknown" + # + AC_MSG_CHECKING([if signal can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([signal]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_signal="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_signal="no" + ]) + # + if test "$tst_links_signal" = "yes"; then + AC_MSG_CHECKING([if signal is prototyped]) + AC_EGREP_CPP([signal],[ + $curl_includes_signal + ],[ + AC_MSG_RESULT([yes]) + tst_proto_signal="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_signal="no" + ]) + fi + # + if test "$tst_proto_signal" = "yes"; then + AC_MSG_CHECKING([if signal is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_signal + ]],[[ + if(0 != signal(0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_signal="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_signal="no" + ]) + fi + # + if test "$tst_compi_signal" = "yes"; then + AC_MSG_CHECKING([if signal usage allowed]) + if test "x$curl_disallow_signal" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_signal="yes" + else + AC_MSG_RESULT([no]) + tst_allow_signal="no" + fi + fi + # + AC_MSG_CHECKING([if signal might be used]) + if test "$tst_links_signal" = "yes" && + test "$tst_proto_signal" = "yes" && + test "$tst_compi_signal" = "yes" && + test "$tst_allow_signal" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_SIGNAL, 1, + [Define to 1 if you have the signal function.]) + curl_cv_func_signal="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_signal="no" + fi +]) + + +dnl CURL_CHECK_FUNC_SIGSETJMP +dnl ------------------------------------------------- +dnl Verify if sigsetjmp is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_sigsetjmp, then +dnl HAVE_SIGSETJMP will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_SIGSETJMP], [ + AC_REQUIRE([CURL_INCLUDES_SETJMP])dnl + # + tst_links_sigsetjmp="unknown" + tst_macro_sigsetjmp="unknown" + tst_proto_sigsetjmp="unknown" + tst_compi_sigsetjmp="unknown" + tst_allow_sigsetjmp="unknown" + # + AC_MSG_CHECKING([if sigsetjmp can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([sigsetjmp]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_sigsetjmp="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_sigsetjmp="no" + ]) + # + if test "$tst_links_sigsetjmp" = "no"; then + AC_MSG_CHECKING([if sigsetjmp seems a macro]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_setjmp + ]],[[ + sigjmp_buf env; + if(0 != sigsetjmp(env, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_macro_sigsetjmp="yes" + ],[ + AC_MSG_RESULT([no]) + tst_macro_sigsetjmp="no" + ]) + fi + # + if test "$tst_links_sigsetjmp" = "yes"; then + AC_MSG_CHECKING([if sigsetjmp is prototyped]) + AC_EGREP_CPP([sigsetjmp],[ + $curl_includes_setjmp + ],[ + AC_MSG_RESULT([yes]) + tst_proto_sigsetjmp="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_sigsetjmp="no" + ]) + fi + # + if test "$tst_proto_sigsetjmp" = "yes" || + test "$tst_macro_sigsetjmp" = "yes"; then + AC_MSG_CHECKING([if sigsetjmp is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_setjmp + ]],[[ + sigjmp_buf env; + if(0 != sigsetjmp(env, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_sigsetjmp="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_sigsetjmp="no" + ]) + fi + # + if test "$tst_compi_sigsetjmp" = "yes"; then + AC_MSG_CHECKING([if sigsetjmp usage allowed]) + if test "x$curl_disallow_sigsetjmp" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_sigsetjmp="yes" + else + AC_MSG_RESULT([no]) + tst_allow_sigsetjmp="no" + fi + fi + # + AC_MSG_CHECKING([if sigsetjmp might be used]) + if (test "$tst_proto_sigsetjmp" = "yes" || + test "$tst_macro_sigsetjmp" = "yes") && + test "$tst_compi_sigsetjmp" = "yes" && + test "$tst_allow_sigsetjmp" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_SIGSETJMP, 1, + [Define to 1 if you have the sigsetjmp function or macro.]) + curl_cv_func_sigsetjmp="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_sigsetjmp="no" + fi +]) + + +dnl CURL_CHECK_FUNC_SOCKET +dnl ------------------------------------------------- +dnl Verify if socket is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_socket, then +dnl HAVE_SOCKET will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_SOCKET], [ + AC_REQUIRE([CURL_INCLUDES_WINSOCK2])dnl + AC_REQUIRE([CURL_INCLUDES_SYS_SOCKET])dnl + AC_REQUIRE([CURL_INCLUDES_SOCKET])dnl + # + tst_links_socket="unknown" + tst_proto_socket="unknown" + tst_compi_socket="unknown" + tst_allow_socket="unknown" + # + AC_MSG_CHECKING([if socket can be linked]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + $curl_includes_socket + ]],[[ + if(0 != socket(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_socket="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_socket="no" + ]) + # + if test "$tst_links_socket" = "yes"; then + AC_MSG_CHECKING([if socket is prototyped]) + AC_EGREP_CPP([socket],[ + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + $curl_includes_socket + ],[ + AC_MSG_RESULT([yes]) + tst_proto_socket="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_socket="no" + ]) + fi + # + if test "$tst_proto_socket" = "yes"; then + AC_MSG_CHECKING([if socket is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_bsdsocket + $curl_includes_sys_socket + $curl_includes_socket + ]],[[ + if(0 != socket(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_socket="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_socket="no" + ]) + fi + # + if test "$tst_compi_socket" = "yes"; then + AC_MSG_CHECKING([if socket usage allowed]) + if test "x$curl_disallow_socket" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_socket="yes" + else + AC_MSG_RESULT([no]) + tst_allow_socket="no" + fi + fi + # + AC_MSG_CHECKING([if socket might be used]) + if test "$tst_links_socket" = "yes" && + test "$tst_proto_socket" = "yes" && + test "$tst_compi_socket" = "yes" && + test "$tst_allow_socket" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_SOCKET, 1, + [Define to 1 if you have the socket function.]) + curl_cv_func_socket="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_socket="no" + fi +]) + + +dnl CURL_CHECK_FUNC_SOCKETPAIR +dnl ------------------------------------------------- +dnl Verify if socketpair is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_socketpair, then +dnl HAVE_SOCKETPAIR will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_SOCKETPAIR], [ + AC_REQUIRE([CURL_INCLUDES_SYS_SOCKET])dnl + AC_REQUIRE([CURL_INCLUDES_SOCKET])dnl + # + tst_links_socketpair="unknown" + tst_proto_socketpair="unknown" + tst_compi_socketpair="unknown" + tst_allow_socketpair="unknown" + # + AC_MSG_CHECKING([if socketpair can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([socketpair]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_socketpair="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_socketpair="no" + ]) + # + if test "$tst_links_socketpair" = "yes"; then + AC_MSG_CHECKING([if socketpair is prototyped]) + AC_EGREP_CPP([socketpair],[ + $curl_includes_sys_socket + $curl_includes_socket + ],[ + AC_MSG_RESULT([yes]) + tst_proto_socketpair="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_socketpair="no" + ]) + fi + # + if test "$tst_proto_socketpair" = "yes"; then + AC_MSG_CHECKING([if socketpair is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_sys_socket + $curl_includes_socket + ]],[[ + int sv[2]; + if(0 != socketpair(0, 0, 0, sv)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_socketpair="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_socketpair="no" + ]) + fi + # + if test "$tst_compi_socketpair" = "yes"; then + AC_MSG_CHECKING([if socketpair usage allowed]) + if test "x$curl_disallow_socketpair" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_socketpair="yes" + else + AC_MSG_RESULT([no]) + tst_allow_socketpair="no" + fi + fi + # + AC_MSG_CHECKING([if socketpair might be used]) + if test "$tst_links_socketpair" = "yes" && + test "$tst_proto_socketpair" = "yes" && + test "$tst_compi_socketpair" = "yes" && + test "$tst_allow_socketpair" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_SOCKETPAIR, 1, + [Define to 1 if you have the socketpair function.]) + curl_cv_func_socketpair="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_socketpair="no" + fi +]) + + +dnl CURL_CHECK_FUNC_STRCASECMP +dnl ------------------------------------------------- +dnl Verify if strcasecmp is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_strcasecmp, then +dnl HAVE_STRCASECMP will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_STRCASECMP], [ + AC_REQUIRE([CURL_INCLUDES_STRING])dnl + # + tst_links_strcasecmp="unknown" + tst_proto_strcasecmp="unknown" + tst_compi_strcasecmp="unknown" + tst_allow_strcasecmp="unknown" + # + AC_MSG_CHECKING([if strcasecmp can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([strcasecmp]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_strcasecmp="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_strcasecmp="no" + ]) + # + if test "$tst_links_strcasecmp" = "yes"; then + AC_MSG_CHECKING([if strcasecmp is prototyped]) + AC_EGREP_CPP([strcasecmp],[ + $curl_includes_string + ],[ + AC_MSG_RESULT([yes]) + tst_proto_strcasecmp="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_strcasecmp="no" + ]) + fi + # + if test "$tst_proto_strcasecmp" = "yes"; then + AC_MSG_CHECKING([if strcasecmp is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_string + ]],[[ + if(0 != strcasecmp(0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_strcasecmp="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_strcasecmp="no" + ]) + fi + # + if test "$tst_compi_strcasecmp" = "yes"; then + AC_MSG_CHECKING([if strcasecmp usage allowed]) + if test "x$curl_disallow_strcasecmp" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_strcasecmp="yes" + else + AC_MSG_RESULT([no]) + tst_allow_strcasecmp="no" + fi + fi + # + AC_MSG_CHECKING([if strcasecmp might be used]) + if test "$tst_links_strcasecmp" = "yes" && + test "$tst_proto_strcasecmp" = "yes" && + test "$tst_compi_strcasecmp" = "yes" && + test "$tst_allow_strcasecmp" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_STRCASECMP, 1, + [Define to 1 if you have the strcasecmp function.]) + curl_cv_func_strcasecmp="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_strcasecmp="no" + fi +]) + +dnl CURL_CHECK_FUNC_STRCMPI +dnl ------------------------------------------------- +dnl Verify if strcmpi is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_strcmpi, then +dnl HAVE_STRCMPI will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_STRCMPI], [ + AC_REQUIRE([CURL_INCLUDES_STRING])dnl + # + tst_links_strcmpi="unknown" + tst_proto_strcmpi="unknown" + tst_compi_strcmpi="unknown" + tst_allow_strcmpi="unknown" + # + AC_MSG_CHECKING([if strcmpi can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([strcmpi]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_strcmpi="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_strcmpi="no" + ]) + # + if test "$tst_links_strcmpi" = "yes"; then + AC_MSG_CHECKING([if strcmpi is prototyped]) + AC_EGREP_CPP([strcmpi],[ + $curl_includes_string + ],[ + AC_MSG_RESULT([yes]) + tst_proto_strcmpi="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_strcmpi="no" + ]) + fi + # + if test "$tst_proto_strcmpi" = "yes"; then + AC_MSG_CHECKING([if strcmpi is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_string + ]],[[ + if(0 != strcmpi(0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_strcmpi="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_strcmpi="no" + ]) + fi + # + if test "$tst_compi_strcmpi" = "yes"; then + AC_MSG_CHECKING([if strcmpi usage allowed]) + if test "x$curl_disallow_strcmpi" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_strcmpi="yes" + else + AC_MSG_RESULT([no]) + tst_allow_strcmpi="no" + fi + fi + # + AC_MSG_CHECKING([if strcmpi might be used]) + if test "$tst_links_strcmpi" = "yes" && + test "$tst_proto_strcmpi" = "yes" && + test "$tst_compi_strcmpi" = "yes" && + test "$tst_allow_strcmpi" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_STRCMPI, 1, + [Define to 1 if you have the strcmpi function.]) + curl_cv_func_strcmpi="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_strcmpi="no" + fi +]) + + +dnl CURL_CHECK_FUNC_STRDUP +dnl ------------------------------------------------- +dnl Verify if strdup is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_strdup, then +dnl HAVE_STRDUP will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_STRDUP], [ + AC_REQUIRE([CURL_INCLUDES_STRING])dnl + # + tst_links_strdup="unknown" + tst_proto_strdup="unknown" + tst_compi_strdup="unknown" + tst_allow_strdup="unknown" + # + AC_MSG_CHECKING([if strdup can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([strdup]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_strdup="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_strdup="no" + ]) + # + if test "$tst_links_strdup" = "yes"; then + AC_MSG_CHECKING([if strdup is prototyped]) + AC_EGREP_CPP([strdup],[ + $curl_includes_string + ],[ + AC_MSG_RESULT([yes]) + tst_proto_strdup="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_strdup="no" + ]) + fi + # + if test "$tst_proto_strdup" = "yes"; then + AC_MSG_CHECKING([if strdup is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_string + ]],[[ + if(0 != strdup(0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_strdup="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_strdup="no" + ]) + fi + # + if test "$tst_compi_strdup" = "yes"; then + AC_MSG_CHECKING([if strdup usage allowed]) + if test "x$curl_disallow_strdup" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_strdup="yes" + else + AC_MSG_RESULT([no]) + tst_allow_strdup="no" + fi + fi + # + AC_MSG_CHECKING([if strdup might be used]) + if test "$tst_links_strdup" = "yes" && + test "$tst_proto_strdup" = "yes" && + test "$tst_compi_strdup" = "yes" && + test "$tst_allow_strdup" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_STRDUP, 1, + [Define to 1 if you have the strdup function.]) + curl_cv_func_strdup="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_strdup="no" + fi +]) + + +dnl CURL_CHECK_FUNC_STRERROR_R +dnl ------------------------------------------------- +dnl Verify if strerror_r is available, prototyped, can be compiled and +dnl seems to work. If all of these are true, and usage has not been +dnl previously disallowed with shell variable curl_disallow_strerror_r, +dnl then HAVE_STRERROR_R will be defined, as well as one of +dnl HAVE_GLIBC_STRERROR_R or HAVE_POSIX_STRERROR_R. +dnl +dnl glibc-style strerror_r: +dnl +dnl char *strerror_r(int errnum, char *workbuf, size_t bufsize); +dnl +dnl glibc-style strerror_r returns a pointer to the error string, +dnl and might use the provided workbuf as a scratch area if needed. A +dnl quick test on a few systems shows that it's usually not used at all. +dnl +dnl POSIX-style strerror_r: +dnl +dnl int strerror_r(int errnum, char *resultbuf, size_t bufsize); +dnl +dnl POSIX-style strerror_r returns 0 upon successful completion and the +dnl error string in the provided resultbuf. +dnl + +AC_DEFUN([CURL_CHECK_FUNC_STRERROR_R], [ + AC_REQUIRE([CURL_INCLUDES_STDLIB])dnl + AC_REQUIRE([CURL_INCLUDES_STRING])dnl + # + tst_links_strerror_r="unknown" + tst_proto_strerror_r="unknown" + tst_compi_strerror_r="unknown" + tst_glibc_strerror_r="unknown" + tst_posix_strerror_r="unknown" + tst_allow_strerror_r="unknown" + tst_works_glibc_strerror_r="unknown" + tst_works_posix_strerror_r="unknown" + tst_glibc_strerror_r_type_arg3="unknown" + tst_posix_strerror_r_type_arg3="unknown" + # + AC_MSG_CHECKING([if strerror_r can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([strerror_r]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_strerror_r="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_strerror_r="no" + ]) + # + if test "$tst_links_strerror_r" = "yes"; then + AC_MSG_CHECKING([if strerror_r is prototyped]) + AC_EGREP_CPP([strerror_r],[ + $curl_includes_string + ],[ + AC_MSG_RESULT([yes]) + tst_proto_strerror_r="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_strerror_r="no" + ]) + fi + # + if test "$tst_proto_strerror_r" = "yes"; then + AC_MSG_CHECKING([if strerror_r is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_string + ]],[[ + if(0 != strerror_r(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_strerror_r="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_strerror_r="no" + ]) + fi + # + if test "$tst_compi_strerror_r" = "yes"; then + AC_MSG_CHECKING([if strerror_r is glibc like]) + tst_glibc_strerror_r_type_arg3="unknown" + for arg3 in 'size_t' 'int' 'unsigned int'; do + if test "$tst_glibc_strerror_r_type_arg3" = "unknown"; then + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_string + char *strerror_r(int errnum, char *workbuf, $arg3 bufsize); + ]],[[ + if(0 != strerror_r(0, 0, 0)) + return 1; + ]]) + ],[ + tst_glibc_strerror_r_type_arg3="$arg3" + ]) + fi + done + case "$tst_glibc_strerror_r_type_arg3" in + unknown) + AC_MSG_RESULT([no]) + tst_glibc_strerror_r="no" + ;; + *) + AC_MSG_RESULT([yes]) + tst_glibc_strerror_r="yes" + ;; + esac + fi + # + dnl only do runtime verification when not cross-compiling + if test "x$cross_compiling" != "xyes" && + test "$tst_glibc_strerror_r" = "yes"; then + AC_MSG_CHECKING([if strerror_r seems to work]) + CURL_RUN_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_stdlib + $curl_includes_string +# include + ]],[[ + char buffer[1024]; + char *string = 0; + buffer[0] = '\0'; + string = strerror_r(EACCES, buffer, sizeof(buffer)); + if(!string) + exit(1); /* fail */ + if(!string[0]) + exit(1); /* fail */ + else + exit(0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_works_glibc_strerror_r="yes" + ],[ + AC_MSG_RESULT([no]) + tst_works_glibc_strerror_r="no" + ]) + fi + # + if test "$tst_compi_strerror_r" = "yes" && + test "$tst_works_glibc_strerror_r" != "yes"; then + AC_MSG_CHECKING([if strerror_r is POSIX like]) + tst_posix_strerror_r_type_arg3="unknown" + for arg3 in 'size_t' 'int' 'unsigned int'; do + if test "$tst_posix_strerror_r_type_arg3" = "unknown"; then + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_string + int strerror_r(int errnum, char *resultbuf, $arg3 bufsize); + ]],[[ + if(0 != strerror_r(0, 0, 0)) + return 1; + ]]) + ],[ + tst_posix_strerror_r_type_arg3="$arg3" + ]) + fi + done + case "$tst_posix_strerror_r_type_arg3" in + unknown) + AC_MSG_RESULT([no]) + tst_posix_strerror_r="no" + ;; + *) + AC_MSG_RESULT([yes]) + tst_posix_strerror_r="yes" + ;; + esac + fi + # + dnl only do runtime verification when not cross-compiling + if test "x$cross_compiling" != "xyes" && + test "$tst_posix_strerror_r" = "yes"; then + AC_MSG_CHECKING([if strerror_r seems to work]) + CURL_RUN_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_stdlib + $curl_includes_string +# include + ]],[[ + char buffer[1024]; + int error = 1; + buffer[0] = '\0'; + error = strerror_r(EACCES, buffer, sizeof(buffer)); + if(error) + exit(1); /* fail */ + if(buffer[0] == '\0') + exit(1); /* fail */ + else + exit(0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_works_posix_strerror_r="yes" + ],[ + AC_MSG_RESULT([no]) + tst_works_posix_strerror_r="no" + ]) + fi + # + if test "$tst_works_glibc_strerror_r" = "yes"; then + tst_posix_strerror_r="no" + fi + if test "$tst_works_posix_strerror_r" = "yes"; then + tst_glibc_strerror_r="no" + fi + if test "$tst_glibc_strerror_r" = "yes" && + test "$tst_works_glibc_strerror_r" != "no" && + test "$tst_posix_strerror_r" != "yes"; then + tst_allow_strerror_r="check" + fi + if test "$tst_posix_strerror_r" = "yes" && + test "$tst_works_posix_strerror_r" != "no" && + test "$tst_glibc_strerror_r" != "yes"; then + tst_allow_strerror_r="check" + fi + if test "$tst_allow_strerror_r" = "check"; then + AC_MSG_CHECKING([if strerror_r usage allowed]) + if test "x$curl_disallow_strerror_r" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_strerror_r="yes" + else + AC_MSG_RESULT([no]) + tst_allow_strerror_r="no" + fi + fi + # + AC_MSG_CHECKING([if strerror_r might be used]) + if test "$tst_links_strerror_r" = "yes" && + test "$tst_proto_strerror_r" = "yes" && + test "$tst_compi_strerror_r" = "yes" && + test "$tst_allow_strerror_r" = "yes"; then + AC_MSG_RESULT([yes]) + if test "$tst_glibc_strerror_r" = "yes"; then + AC_DEFINE_UNQUOTED(HAVE_STRERROR_R, 1, + [Define to 1 if you have the strerror_r function.]) + AC_DEFINE_UNQUOTED(HAVE_GLIBC_STRERROR_R, 1, + [Define to 1 if you have a working glibc-style strerror_r function.]) + fi + if test "$tst_posix_strerror_r" = "yes"; then + AC_DEFINE_UNQUOTED(HAVE_STRERROR_R, 1, + [Define to 1 if you have the strerror_r function.]) + AC_DEFINE_UNQUOTED(HAVE_POSIX_STRERROR_R, 1, + [Define to 1 if you have a working POSIX-style strerror_r function.]) + fi + curl_cv_func_strerror_r="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_strerror_r="no" + fi + # + if test "$tst_compi_strerror_r" = "yes" && + test "$tst_allow_strerror_r" = "unknown"; then + AC_MSG_WARN([cannot determine strerror_r() style: edit lib/curl_config.h manually.]) + fi + # +]) + + +dnl CURL_CHECK_FUNC_STRICMP +dnl ------------------------------------------------- +dnl Verify if stricmp is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_stricmp, then +dnl HAVE_STRICMP will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_STRICMP], [ + AC_REQUIRE([CURL_INCLUDES_STRING])dnl + # + tst_links_stricmp="unknown" + tst_proto_stricmp="unknown" + tst_compi_stricmp="unknown" + tst_allow_stricmp="unknown" + # + AC_MSG_CHECKING([if stricmp can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([stricmp]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_stricmp="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_stricmp="no" + ]) + # + if test "$tst_links_stricmp" = "yes"; then + AC_MSG_CHECKING([if stricmp is prototyped]) + AC_EGREP_CPP([stricmp],[ + $curl_includes_string + ],[ + AC_MSG_RESULT([yes]) + tst_proto_stricmp="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_stricmp="no" + ]) + fi + # + if test "$tst_proto_stricmp" = "yes"; then + AC_MSG_CHECKING([if stricmp is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_string + ]],[[ + if(0 != stricmp(0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_stricmp="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_stricmp="no" + ]) + fi + # + if test "$tst_compi_stricmp" = "yes"; then + AC_MSG_CHECKING([if stricmp usage allowed]) + if test "x$curl_disallow_stricmp" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_stricmp="yes" + else + AC_MSG_RESULT([no]) + tst_allow_stricmp="no" + fi + fi + # + AC_MSG_CHECKING([if stricmp might be used]) + if test "$tst_links_stricmp" = "yes" && + test "$tst_proto_stricmp" = "yes" && + test "$tst_compi_stricmp" = "yes" && + test "$tst_allow_stricmp" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_STRICMP, 1, + [Define to 1 if you have the stricmp function.]) + curl_cv_func_stricmp="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_stricmp="no" + fi +]) + + +dnl CURL_CHECK_FUNC_STRTOK_R +dnl ------------------------------------------------- +dnl Verify if strtok_r is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_strtok_r, then +dnl HAVE_STRTOK_R will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_STRTOK_R], [ + AC_REQUIRE([CURL_INCLUDES_STRING])dnl + # + tst_links_strtok_r="unknown" + tst_proto_strtok_r="unknown" + tst_compi_strtok_r="unknown" + tst_allow_strtok_r="unknown" + # + AC_MSG_CHECKING([if strtok_r can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([strtok_r]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_strtok_r="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_strtok_r="no" + ]) + # + if test "$tst_links_strtok_r" = "yes"; then + AC_MSG_CHECKING([if strtok_r is prototyped]) + AC_EGREP_CPP([strtok_r],[ + $curl_includes_string + ],[ + AC_MSG_RESULT([yes]) + tst_proto_strtok_r="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_strtok_r="no" + ]) + fi + # + if test "$tst_proto_strtok_r" = "yes"; then + AC_MSG_CHECKING([if strtok_r is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_string + ]],[[ + if(0 != strtok_r(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_strtok_r="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_strtok_r="no" + ]) + fi + # + if test "$tst_compi_strtok_r" = "yes"; then + AC_MSG_CHECKING([if strtok_r usage allowed]) + if test "x$curl_disallow_strtok_r" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_strtok_r="yes" + else + AC_MSG_RESULT([no]) + tst_allow_strtok_r="no" + fi + fi + # + AC_MSG_CHECKING([if strtok_r might be used]) + if test "$tst_links_strtok_r" = "yes" && + test "$tst_proto_strtok_r" = "yes" && + test "$tst_compi_strtok_r" = "yes" && + test "$tst_allow_strtok_r" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_STRTOK_R, 1, + [Define to 1 if you have the strtok_r function.]) + curl_cv_func_strtok_r="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_strtok_r="no" + fi +]) + + +dnl CURL_CHECK_FUNC_STRTOLL +dnl ------------------------------------------------- +dnl Verify if strtoll is available, prototyped, and +dnl can be compiled. If all of these are true, and +dnl usage has not been previously disallowed with +dnl shell variable curl_disallow_strtoll, then +dnl HAVE_STRTOLL will be defined. + +AC_DEFUN([CURL_CHECK_FUNC_STRTOLL], [ + AC_REQUIRE([CURL_INCLUDES_STDLIB])dnl + # + tst_links_strtoll="unknown" + tst_proto_strtoll="unknown" + tst_compi_strtoll="unknown" + tst_allow_strtoll="unknown" + # + AC_MSG_CHECKING([if strtoll can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([strtoll]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_strtoll="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_strtoll="no" + ]) + # + if test "$tst_links_strtoll" = "yes"; then + AC_MSG_CHECKING([if strtoll is prototyped]) + AC_EGREP_CPP([strtoll],[ + $curl_includes_stdlib + ],[ + AC_MSG_RESULT([yes]) + tst_proto_strtoll="yes" + ],[ + AC_MSG_RESULT([no]) + tst_proto_strtoll="no" + ]) + fi + # + if test "$tst_proto_strtoll" = "yes"; then + AC_MSG_CHECKING([if strtoll is compilable]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_stdlib + ]],[[ + if(0 != strtoll(0, 0, 0)) + return 1; + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_compi_strtoll="yes" + ],[ + AC_MSG_RESULT([no]) + tst_compi_strtoll="no" + ]) + fi + # + if test "$tst_compi_strtoll" = "yes"; then + AC_MSG_CHECKING([if strtoll usage allowed]) + if test "x$curl_disallow_strtoll" != "xyes"; then + AC_MSG_RESULT([yes]) + tst_allow_strtoll="yes" + else + AC_MSG_RESULT([no]) + tst_allow_strtoll="no" + fi + fi + # + AC_MSG_CHECKING([if strtoll might be used]) + if test "$tst_links_strtoll" = "yes" && + test "$tst_proto_strtoll" = "yes" && + test "$tst_compi_strtoll" = "yes" && + test "$tst_allow_strtoll" = "yes"; then + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_STRTOLL, 1, + [Define to 1 if you have the strtoll function.]) + curl_cv_func_strtoll="yes" + else + AC_MSG_RESULT([no]) + curl_cv_func_strtoll="no" + fi +]) + +dnl CURL_RUN_IFELSE +dnl ------------------------------------------------- +dnl Wrapper macro to use instead of AC_RUN_IFELSE. It +dnl sets LD_LIBRARY_PATH locally for this run only, from the +dnl CURL_LIBRARY_PATH variable. It keeps the LD_LIBRARY_PATH +dnl changes contained within this macro. + +AC_DEFUN([CURL_RUN_IFELSE], [ + case $host_os in + darwin*) + AC_RUN_IFELSE([AC_LANG_SOURCE([$1])], $2, $3, $4) + ;; + *) + oldcc=$CC + old=$LD_LIBRARY_PATH + CC="sh ./run-compiler" + LD_LIBRARY_PATH=$CURL_LIBRARY_PATH:$old + export LD_LIBRARY_PATH + AC_RUN_IFELSE([AC_LANG_SOURCE([$1])], $2, $3, $4) + LD_LIBRARY_PATH=$old # restore + CC=$oldcc + ;; + esac +]) + +dnl CURL_COVERAGE +dnl -------------------------------------------------- +dnl Switch on options and libs to build with gcc's code coverage. +dnl + +AC_DEFUN([CURL_COVERAGE],[ + AC_REQUIRE([AC_PROG_SED]) + AC_REQUIRE([AC_ARG_ENABLE]) + AC_MSG_CHECKING([for code coverage support]) + coverage="no" + curl_coverage_msg="disabled" + + dnl check if enabled by argument + AC_ARG_ENABLE(code-coverage, + AS_HELP_STRING([--enable-code-coverage], [Provide code coverage]), + coverage="$enableval") + + dnl if not gcc switch off again + AS_IF([ test "$GCC" != "yes" ], coverage="no" ) + AC_MSG_RESULT($coverage) + + if test "x$coverage" = "xyes"; then + curl_coverage_msg="enabled" + + AC_CHECK_TOOL([GCOV], [gcov], [gcov]) + if test -z "$GCOV"; then + AC_MSG_ERROR([needs gcov for code coverage]) + fi + AC_CHECK_PROG([LCOV], [lcov], [lcov]) + if test -z "$LCOV"; then + AC_MSG_ERROR([needs lcov for code coverage]) + fi + + CPPFLAGS="$CPPFLAGS -DNDEBUG" + CFLAGS="$CFLAGS -O0 -g -fprofile-arcs -ftest-coverage" + LIBS="$LIBS -lgcov" + fi +]) + +dnl CURL_ATOMIC +dnl ------------------------------------------------------------- +dnl Check if _Atomic works. But only check if stdatomic.h exists. +dnl +AC_DEFUN([CURL_ATOMIC],[ + AC_CHECK_HEADERS(stdatomic.h, [ + AC_MSG_CHECKING([if _Atomic is available]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_unistd + ]],[[ + _Atomic int i = 0; + i = 4; // Force an atomic-write operation. + ]]) + ],[ + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_ATOMIC, 1, + [Define to 1 if you have _Atomic support.]) + tst_atomic="yes" + ],[ + AC_MSG_RESULT([no]) + tst_atomic="no" + ]) + ]) +]) + +# Rewrite inspired by the functionality once provided by +# AX_COMPILE_CHECK_SIZEOF. Uses the switch() "trick" to find the size of the +# given type. +# +# This code fails to compile: +# +# switch() { case 0: case 0: } +# +# By making the second case number a boolean check, it fails to compile the +# test code when the boolean is false and thus creating a zero, making it a +# duplicated case label. If the boolean equals true, it becomes a one, the +# code compiles and we know it was a match. +# +# The check iterates over all possible sizes and stops as soon it compiles +# error-free. +# +# Usage: +# +# CURL_SIZEOF(TYPE, [HEADERS]) +# + +AC_DEFUN([CURL_SIZEOF], [ + dnl The #define name to make autoheader put the name in curl_config.h.in + define(TYPE, translit(sizeof_$1, [a-z *], [A-Z_P]))dnl + + AC_MSG_CHECKING(size of $1) + r=0 + dnl Check the sizes in a reasonable order + for typesize in 8 4 2 16 1; do + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ +#include +$2 +]], + [switch(0) { + case 0: + case (sizeof($1) == $typesize):; + } + ]) ], + [ + r=$typesize], + [ + r=0]) + dnl get out of the loop once matched + if test $r -gt 0; then + break; + fi + done + if test $r -eq 0; then + AC_MSG_ERROR([Failed to find size of $1]) + fi + AC_MSG_RESULT($r) + dnl lowercase and underscore instead of space + tname=$(echo "ac_cv_sizeof_$1" | tr A-Z a-z | tr " " "_") + eval "$tname=$r" + + AC_DEFINE_UNQUOTED(TYPE, [$r], [Size of $1 in number of bytes]) + +]) diff --git a/third_party/curl/m4/curl-gnutls.m4 b/third_party/curl/m4/curl-gnutls.m4 new file mode 100644 index 0000000..d4f553d --- /dev/null +++ b/third_party/curl/m4/curl-gnutls.m4 @@ -0,0 +1,168 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +dnl ---------------------------------------------------- +dnl check for GnuTLS +dnl ---------------------------------------------------- + +AC_DEFUN([CURL_WITH_GNUTLS], [ +if test "x$OPT_GNUTLS" != xno; then + ssl_msg= + + if test X"$OPT_GNUTLS" != Xno; then + + addld="" + addlib="" + gtlslib="" + version="" + addcflags="" + + if test "x$OPT_GNUTLS" = "xyes"; then + dnl this is with no particular path given + CURL_CHECK_PKGCONFIG(gnutls) + + if test "$PKGCONFIG" != "no" ; then + addlib=`$PKGCONFIG --libs-only-l gnutls` + addld=`$PKGCONFIG --libs-only-L gnutls` + addcflags=`$PKGCONFIG --cflags-only-I gnutls` + version=`$PKGCONFIG --modversion gnutls` + gtlslib=`echo $addld | $SED -e 's/^-L//'` + else + dnl without pkg-config, we try libgnutls-config as that was how it + dnl used to be done + check=`libgnutls-config --version 2>/dev/null` + if test -n "$check"; then + addlib=`libgnutls-config --libs` + addcflags=`libgnutls-config --cflags` + version=`libgnutls-config --version` + gtlslib=`libgnutls-config --prefix`/lib$libsuff + fi + fi + else + dnl this is with a given path, first check if there's a libgnutls-config + dnl there and if not, make an educated guess + cfg=$OPT_GNUTLS/bin/libgnutls-config + check=`$cfg --version 2>/dev/null` + if test -n "$check"; then + addlib=`$cfg --libs` + addcflags=`$cfg --cflags` + version=`$cfg --version` + gtlslib=`$cfg --prefix`/lib$libsuff + else + dnl without pkg-config and libgnutls-config, we guess a lot! + addlib=-lgnutls + addld=-L$OPT_GNUTLS/lib$libsuff + addcflags=-I$OPT_GNUTLS/include + version="" # we just don't know + gtlslib=$OPT_GNUTLS/lib$libsuff + fi + fi + + if test -z "$version"; then + dnl lots of efforts, still no go + version="unknown" + fi + + if test -n "$addlib"; then + + CLEANLIBS="$LIBS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLDFLAGS="$LDFLAGS" + + LIBS="$addlib $LIBS" + LDFLAGS="$LDFLAGS $addld" + if test "$addcflags" != "-I/usr/include"; then + CPPFLAGS="$CPPFLAGS $addcflags" + fi + + dnl this function is selected since it was introduced in 3.1.10 + AC_CHECK_LIB(gnutls, gnutls_x509_crt_get_dn2, + [ + AC_DEFINE(USE_GNUTLS, 1, [if GnuTLS is enabled]) + AC_SUBST(USE_GNUTLS, [1]) + GNUTLS_ENABLED=1 + USE_GNUTLS="yes" + ssl_msg="GnuTLS" + QUIC_ENABLED=yes + test gnutls != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + ], + [ + LIBS="$CLEANLIBS" + CPPFLAGS="$CLEANCPPFLAGS" + ]) + + if test "x$USE_GNUTLS" = "xyes"; then + AC_MSG_NOTICE([detected GnuTLS version $version]) + check_for_ca_bundle=1 + if test -n "$gtlslib"; then + dnl when shared libs were found in a path that the run-time + dnl linker doesn't search through, we need to add it to + dnl CURL_LIBRARY_PATH to prevent further configure tests to fail + dnl due to this + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$gtlslib" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $gtlslib to CURL_LIBRARY_PATH]) + fi + fi + fi + + fi + + fi dnl GNUTLS not disabled + + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" +fi + +dnl --- +dnl Check which crypto backend GnuTLS uses +dnl --- + +if test "$GNUTLS_ENABLED" = "1"; then + USE_GNUTLS_NETTLE= + # First check if we can detect either crypto library via transitive linking + AC_CHECK_LIB(gnutls, nettle_MD5Init, [ USE_GNUTLS_NETTLE=1 ]) + + # If not, try linking directly to both of them to see if they are available + if test "$USE_GNUTLS_NETTLE" = ""; then + AC_CHECK_LIB(nettle, nettle_MD5Init, [ USE_GNUTLS_NETTLE=1 ]) + fi + if test "$USE_GNUTLS_NETTLE" = ""; then + AC_MSG_ERROR([GnuTLS found, but nettle was not found]) + fi + LIBS="-lnettle $LIBS" +fi + +dnl --- +dnl We require GnuTLS with SRP support. +dnl --- +if test "$GNUTLS_ENABLED" = "1"; then + AC_CHECK_LIB(gnutls, gnutls_srp_verifier, + [ + AC_DEFINE(HAVE_GNUTLS_SRP, 1, [if you have the function gnutls_srp_verifier]) + AC_SUBST(HAVE_GNUTLS_SRP, [1]) + ]) +fi + +]) diff --git a/third_party/curl/m4/curl-mbedtls.m4 b/third_party/curl/m4/curl-mbedtls.m4 new file mode 100644 index 0000000..64116e7 --- /dev/null +++ b/third_party/curl/m4/curl-mbedtls.m4 @@ -0,0 +1,111 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +dnl ---------------------------------------------------- +dnl check for mbedTLS +dnl ---------------------------------------------------- +AC_DEFUN([CURL_WITH_MBEDTLS], [ + +if test "x$OPT_MBEDTLS" != xno; then + _cppflags=$CPPFLAGS + _ldflags=$LDFLAGS + ssl_msg= + + if test X"$OPT_MBEDTLS" != Xno; then + + if test "$OPT_MBEDTLS" = "yes"; then + OPT_MBEDTLS="" + fi + + if test -z "$OPT_MBEDTLS" ; then + dnl check for lib first without setting any new path + + AC_CHECK_LIB(mbedtls, mbedtls_havege_init, + dnl libmbedtls found, set the variable + [ + AC_DEFINE(USE_MBEDTLS, 1, [if mbedTLS is enabled]) + AC_SUBST(USE_MBEDTLS, [1]) + MBEDTLS_ENABLED=1 + USE_MBEDTLS="yes" + ssl_msg="mbedTLS" + test mbedtls != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + ], [], -lmbedx509 -lmbedcrypto) + fi + + addld="" + addlib="" + addcflags="" + mbedtlslib="" + + if test "x$USE_MBEDTLS" != "xyes"; then + dnl add the path and test again + addld=-L$OPT_MBEDTLS/lib$libsuff + addcflags=-I$OPT_MBEDTLS/include + mbedtlslib=$OPT_MBEDTLS/lib$libsuff + + LDFLAGS="$LDFLAGS $addld" + if test "$addcflags" != "-I/usr/include"; then + CPPFLAGS="$CPPFLAGS $addcflags" + fi + + AC_CHECK_LIB(mbedtls, mbedtls_ssl_init, + [ + AC_DEFINE(USE_MBEDTLS, 1, [if mbedTLS is enabled]) + AC_SUBST(USE_MBEDTLS, [1]) + MBEDTLS_ENABLED=1 + USE_MBEDTLS="yes" + ssl_msg="mbedTLS" + test mbedtls != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + ], + [ + CPPFLAGS=$_cppflags + LDFLAGS=$_ldflags + ], -lmbedx509 -lmbedcrypto) + fi + + if test "x$USE_MBEDTLS" = "xyes"; then + AC_MSG_NOTICE([detected mbedTLS]) + check_for_ca_bundle=1 + + LIBS="-lmbedtls -lmbedx509 -lmbedcrypto $LIBS" + + if test -n "$mbedtlslib"; then + dnl when shared libs were found in a path that the run-time + dnl linker doesn't search through, we need to add it to + dnl CURL_LIBRARY_PATH to prevent further configure tests to fail + dnl due to this + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$mbedtlslib" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $mbedtlslib to CURL_LIBRARY_PATH]) + fi + fi + fi + + fi dnl mbedTLS not disabled + + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" +fi + +]) diff --git a/third_party/curl/m4/curl-openssl.m4 b/third_party/curl/m4/curl-openssl.m4 new file mode 100644 index 0000000..2fb2abe --- /dev/null +++ b/third_party/curl/m4/curl-openssl.m4 @@ -0,0 +1,446 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +# File version for 'aclocal' use. Keep it a single number. +# serial 5 + +dnl ********************************************************************** +dnl Check for OpenSSL libraries and headers +dnl ********************************************************************** + +AC_DEFUN([CURL_WITH_OPENSSL], [ +if test "x$OPT_OPENSSL" != xno; then + ssl_msg= + + dnl backup the pre-ssl variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + dnl This is for Msys/Mingw + case $host in + *-*-msys* | *-*-mingw*) + AC_MSG_CHECKING([for gdi32]) + my_ac_save_LIBS=$LIBS + LIBS="-lgdi32 $LIBS" + AC_LINK_IFELSE([ AC_LANG_PROGRAM([[ + #include + #include + ]], + [[ + GdiFlush(); + ]])], + [ dnl worked! + AC_MSG_RESULT([yes])], + [ dnl failed, restore LIBS + LIBS=$my_ac_save_LIBS + AC_MSG_RESULT(no)] + ) + ;; + esac + + case "$OPT_OPENSSL" in + yes) + dnl --with-openssl (without path) used + PKGTEST="yes" + PREFIX_OPENSSL= + ;; + *) + dnl check the given --with-openssl spot + PKGTEST="no" + PREFIX_OPENSSL=$OPT_OPENSSL + + dnl Try pkg-config even when cross-compiling. Since we + dnl specify PKG_CONFIG_LIBDIR we're only looking where + dnl the user told us to look + OPENSSL_PCDIR="$OPT_OPENSSL/lib/pkgconfig" + if test -f "$OPENSSL_PCDIR/openssl.pc"; then + AC_MSG_NOTICE([PKG_CONFIG_LIBDIR will be set to "$OPENSSL_PCDIR"]) + PKGTEST="yes" + fi + + if test "$PKGTEST" != "yes"; then + # try lib64 instead + OPENSSL_PCDIR="$OPT_OPENSSL/lib64/pkgconfig" + if test -f "$OPENSSL_PCDIR/openssl.pc"; then + AC_MSG_NOTICE([PKG_CONFIG_LIBDIR will be set to "$OPENSSL_PCDIR"]) + PKGTEST="yes" + fi + fi + + if test "$PKGTEST" != "yes"; then + if test ! -f "$PREFIX_OPENSSL/include/openssl/ssl.h"; then + AC_MSG_ERROR([$PREFIX_OPENSSL is a bad --with-openssl prefix!]) + fi + fi + + dnl in case pkg-config comes up empty, use what we got + dnl via --with-openssl + LIB_OPENSSL="$PREFIX_OPENSSL/lib$libsuff" + if test "$PREFIX_OPENSSL" != "/usr" ; then + SSL_LDFLAGS="-L$LIB_OPENSSL" + SSL_CPPFLAGS="-I$PREFIX_OPENSSL/include" + fi + ;; + esac + + if test "$PKGTEST" = "yes"; then + + CURL_CHECK_PKGCONFIG(openssl, [$OPENSSL_PCDIR]) + + if test "$PKGCONFIG" != "no" ; then + SSL_LIBS=`CURL_EXPORT_PCDIR([$OPENSSL_PCDIR]) dnl + $PKGCONFIG --libs-only-l --libs-only-other openssl 2>/dev/null` + + SSL_LDFLAGS=`CURL_EXPORT_PCDIR([$OPENSSL_PCDIR]) dnl + $PKGCONFIG --libs-only-L openssl 2>/dev/null` + + SSL_CPPFLAGS=`CURL_EXPORT_PCDIR([$OPENSSL_PCDIR]) dnl + $PKGCONFIG --cflags-only-I openssl 2>/dev/null` + + AC_SUBST(SSL_LIBS) + AC_MSG_NOTICE([pkg-config: SSL_LIBS: "$SSL_LIBS"]) + AC_MSG_NOTICE([pkg-config: SSL_LDFLAGS: "$SSL_LDFLAGS"]) + AC_MSG_NOTICE([pkg-config: SSL_CPPFLAGS: "$SSL_CPPFLAGS"]) + + LIB_OPENSSL=`echo $SSL_LDFLAGS | sed -e 's/^-L//'` + + dnl use the values pkg-config reported. This is here + dnl instead of below with CPPFLAGS and LDFLAGS because we only + dnl learn about this via pkg-config. If we only have + dnl the argument to --with-openssl we don't know what + dnl additional libs may be necessary. Hope that we + dnl don't need any. + LIBS="$SSL_LIBS $LIBS" + fi + fi + + dnl finally, set flags to use SSL + CPPFLAGS="$CPPFLAGS $SSL_CPPFLAGS" + LDFLAGS="$LDFLAGS $SSL_LDFLAGS" + + AC_CHECK_LIB(crypto, HMAC_Update,[ + HAVECRYPTO="yes" + LIBS="-lcrypto $LIBS" + ],[ + if test -n "$LIB_OPENSSL" ; then + LDFLAGS="$CLEANLDFLAGS -L$LIB_OPENSSL" + fi + if test "$PKGCONFIG" = "no" -a -n "$PREFIX_OPENSSL" ; then + # only set this if pkg-config wasn't used + CPPFLAGS="$CLEANCPPFLAGS -I$PREFIX_OPENSSL/include" + fi + # Linking previously failed, try extra paths from --with-openssl or + # pkg-config. Use a different function name to avoid reusing the earlier + # cached result. + AC_CHECK_LIB(crypto, HMAC_Init_ex,[ + HAVECRYPTO="yes" + LIBS="-lcrypto $LIBS"], [ + + dnl still no, but what about with -ldl? + AC_MSG_CHECKING([OpenSSL linking with -ldl]) + LIBS="-lcrypto $CLEANLIBS -ldl" + AC_LINK_IFELSE([ AC_LANG_PROGRAM([[ + #include + ]], [[ + ERR_clear_error(); + ]]) ], + [ + AC_MSG_RESULT(yes) + HAVECRYPTO="yes" + ], + [ + AC_MSG_RESULT(no) + dnl ok, so what about both -ldl and -lpthread? + dnl This may be necessary for static libraries. + + AC_MSG_CHECKING([OpenSSL linking with -ldl and -lpthread]) + LIBS="-lcrypto $CLEANLIBS -ldl -lpthread" + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + #include + ]], [[ + ERR_clear_error(); + ]])], + [ + AC_MSG_RESULT(yes) + HAVECRYPTO="yes" + ], + [ + AC_MSG_RESULT(no) + LDFLAGS="$CLEANLDFLAGS" + CPPFLAGS="$CLEANCPPFLAGS" + LIBS="$CLEANLIBS" + + ]) + + ]) + + ]) + ]) + + if test X"$HAVECRYPTO" = X"yes"; then + dnl This is only reasonable to do if crypto actually is there: check for + dnl SSL libs NOTE: it is important to do this AFTER the crypto lib + + AC_CHECK_LIB(ssl, SSL_connect) + + if test "$ac_cv_lib_ssl_SSL_connect" != yes; then + dnl we didn't find the SSL lib, try the RSAglue/rsaref stuff + AC_MSG_CHECKING(for ssl with RSAglue/rsaref libs in use); + OLIBS=$LIBS + LIBS="-lRSAglue -lrsaref $LIBS" + AC_CHECK_LIB(ssl, SSL_connect) + if test "$ac_cv_lib_ssl_SSL_connect" != yes; then + dnl still no SSL_connect + AC_MSG_RESULT(no) + LIBS=$OLIBS + else + AC_MSG_RESULT(yes) + fi + + else + + dnl Have the libraries--check for OpenSSL headers + AC_CHECK_HEADERS(openssl/x509.h openssl/rsa.h openssl/crypto.h \ + openssl/pem.h openssl/ssl.h openssl/err.h, + ssl_msg="OpenSSL" + test openssl != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + OPENSSL_ENABLED=1 + AC_DEFINE(USE_OPENSSL, 1, [if OpenSSL is in use])) + + if test $ac_cv_header_openssl_x509_h = no; then + dnl we don't use the "action" part of the AC_CHECK_HEADERS macro + dnl since 'err.h' might in fact find a krb4 header with the same + dnl name + AC_CHECK_HEADERS(x509.h rsa.h crypto.h pem.h ssl.h err.h) + + if test $ac_cv_header_x509_h = yes && + test $ac_cv_header_crypto_h = yes && + test $ac_cv_header_ssl_h = yes; then + dnl three matches + ssl_msg="OpenSSL" + OPENSSL_ENABLED=1 + fi + fi + fi + + if test X"$OPENSSL_ENABLED" != X"1"; then + LIBS="$CLEANLIBS" + fi + + if test X"$OPT_OPENSSL" != Xoff && + test "$OPENSSL_ENABLED" != "1"; then + AC_MSG_ERROR([OpenSSL libs and/or directories were not found where specified!]) + fi + fi + + if test X"$OPENSSL_ENABLED" = X"1"; then + dnl These can only exist if OpenSSL exists + + AC_MSG_CHECKING([for BoringSSL]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + #include + ]],[[ + #ifndef OPENSSL_IS_BORINGSSL + #error not boringssl + #endif + ]]) + ],[ + AC_MSG_RESULT([yes]) + ssl_msg="BoringSSL" + OPENSSL_IS_BORINGSSL=1 + ],[ + AC_MSG_RESULT([no]) + ]) + + AC_MSG_CHECKING([for AWS-LC]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + #include + ]],[[ + #ifndef OPENSSL_IS_AWSLC + #error not AWS-LC + #endif + ]]) + ],[ + AC_MSG_RESULT([yes]) + ssl_msg="AWS-LC" + OPENSSL_IS_BORINGSSL=1 + ],[ + AC_MSG_RESULT([no]) + ]) + + AC_MSG_CHECKING([for libressl]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#include + ]],[[ + int dummy = LIBRESSL_VERSION_NUMBER; + ]]) + ],[ + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_LIBRESSL, 1, + [Define to 1 if using libressl.]) + ssl_msg="libressl" + ],[ + AC_MSG_RESULT([no]) + ]) + + AC_MSG_CHECKING([for OpenSSL >= v3]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#include + ]],[[ + #if (OPENSSL_VERSION_NUMBER >= 0x30000000L) + return 0; + #else + #error older than 3 + #endif + ]]) + ],[ + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_OPENSSL3, 1, + [Define to 1 if using OpenSSL 3 or later.]) + ssl_msg="OpenSSL v3+" + ],[ + AC_MSG_RESULT([no]) + ]) + fi + + dnl is this OpenSSL (fork) providing the original QUIC API? + AC_CHECK_FUNCS([SSL_set_quic_use_legacy_codepoint], + [QUIC_ENABLED=yes]) + if test "$QUIC_ENABLED" = "yes"; then + AC_MSG_NOTICE([OpenSSL fork speaks QUIC API]) + else + AC_MSG_NOTICE([OpenSSL version does not speak QUIC API]) + fi + + if test "$OPENSSL_ENABLED" = "1"; then + if test -n "$LIB_OPENSSL"; then + dnl when the ssl shared libs were found in a path that the run-time + dnl linker doesn't search through, we need to add it to CURL_LIBRARY_PATH + dnl to prevent further configure tests to fail due to this + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$LIB_OPENSSL" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $LIB_OPENSSL to CURL_LIBRARY_PATH]) + fi + fi + check_for_ca_bundle=1 + fi + + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" +fi + +if test X"$OPT_OPENSSL" != Xno && + test "$OPENSSL_ENABLED" != "1"; then + AC_MSG_NOTICE([OPT_OPENSSL: $OPT_OPENSSL]) + AC_MSG_NOTICE([OPENSSL_ENABLED: $OPENSSL_ENABLED]) + AC_MSG_ERROR([--with-openssl was given but OpenSSL could not be detected]) +fi + +dnl ********************************************************************** +dnl Check for the random seed preferences +dnl ********************************************************************** + +if test X"$OPENSSL_ENABLED" = X"1"; then + dnl Check for user-specified random device + AC_ARG_WITH(random, + AS_HELP_STRING([--with-random=FILE], + [read randomness from FILE (default=/dev/urandom)]), + [ RANDOM_FILE="$withval" ], + [ + if test x$cross_compiling != xyes; then + dnl Check for random device + AC_CHECK_FILE("/dev/urandom", [ RANDOM_FILE="/dev/urandom"] ) + else + AC_MSG_WARN([skipped the /dev/urandom detection when cross-compiling]) + fi + ] + ) + if test -n "$RANDOM_FILE" && test X"$RANDOM_FILE" != Xno ; then + AC_SUBST(RANDOM_FILE) + AC_DEFINE_UNQUOTED(RANDOM_FILE, "$RANDOM_FILE", + [a suitable file to read random data from]) + fi +fi + +dnl --- +dnl We require OpenSSL with SRP support. +dnl --- +if test "$OPENSSL_ENABLED" = "1"; then + AC_MSG_CHECKING([for SRP support in OpenSSL]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ +#include + ]],[[ + SSL_CTX_set_srp_username(NULL, ""); + SSL_CTX_set_srp_password(NULL, ""); + ]]) + ],[ + AC_MSG_RESULT([yes]) + AC_DEFINE(HAVE_OPENSSL_SRP, 1, [if you have the functions SSL_CTX_set_srp_username and SSL_CTX_set_srp_password]) + AC_SUBST(HAVE_OPENSSL_SRP, [1]) + ],[ + AC_MSG_RESULT([no]) + ]) +fi + +dnl --- +dnl Whether the OpenSSL configuration will be loaded automatically +dnl --- +if test X"$OPENSSL_ENABLED" = X"1"; then +AC_ARG_ENABLE(openssl-auto-load-config, +AS_HELP_STRING([--enable-openssl-auto-load-config],[Enable automatic loading of OpenSSL configuration]) +AS_HELP_STRING([--disable-openssl-auto-load-config],[Disable automatic loading of OpenSSL configuration]), +[ if test X"$enableval" = X"no"; then + AC_MSG_NOTICE([automatic loading of OpenSSL configuration disabled]) + AC_DEFINE(CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG, 1, [if the OpenSSL configuration won't be loaded automatically]) + fi +]) +fi + +dnl --- +dnl We may use OpenSSL QUIC. +dnl --- +if test "$OPENSSL_ENABLED" = "1"; then + AC_MSG_CHECKING([for QUIC support in OpenSSL]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ +#include + ]],[[ + OSSL_QUIC_client_method(); + ]]) + ],[ + AC_MSG_RESULT([yes]) + AC_DEFINE(HAVE_OPENSSL_QUIC, 1, [if you have the functions OSSL_QUIC_client_method]) + AC_SUBST(HAVE_OPENSSL_QUIC, [1]) + ],[ + AC_MSG_RESULT([no]) + ]) +fi +]) diff --git a/third_party/curl/m4/curl-override.m4 b/third_party/curl/m4/curl-override.m4 new file mode 100644 index 0000000..b4a8df9 --- /dev/null +++ b/third_party/curl/m4/curl-override.m4 @@ -0,0 +1,98 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +#*************************************************************************** +#*************************************************************************** + +# File version for 'aclocal' use. Keep it a single number. +# serial 7 + +dnl CURL_OVERRIDE_AUTOCONF +dnl ------------------------------------------------- +dnl Placing a call to this macro in configure.ac after +dnl the one to AC_INIT will make macros in this file +dnl visible to the rest of the compilation overriding +dnl those from Autoconf. + +AC_DEFUN([CURL_OVERRIDE_AUTOCONF], [ +AC_BEFORE([$0],[AC_PROG_LIBTOOL]) +# using curl-override.m4 +]) + +dnl Override Autoconf's AC_LANG_PROGRAM (C) +dnl ------------------------------------------------- +dnl This is done to prevent compiler warning +dnl 'function declaration isn't a prototype' +dnl in function main. This requires at least +dnl a c89 compiler and does not support K&R. + +m4_define([AC_LANG_PROGRAM(C)], +[$1 +int main (void) +{ +$2 + ; + return 0; +}]) + +dnl Override Autoconf's AC_LANG_CALL (C) +dnl ------------------------------------------------- +dnl This is a backport of Autoconf's 2.60 with the +dnl embedded comments that hit the resulting script +dnl removed. This is done to reduce configure size +dnl and use fixed macro across Autoconf versions. + +m4_define([AC_LANG_CALL(C)], +[AC_LANG_PROGRAM([$1 +m4_if([$2], [main], , +[ +#ifdef __cplusplus +extern "C" +#endif +char $2 ();])], [return $2 ();])]) + +dnl Override Autoconf's AC_LANG_FUNC_LINK_TRY (C) +dnl ------------------------------------------------- +dnl This is a backport of Autoconf's 2.60 with the +dnl embedded comments that hit the resulting script +dnl removed. This is done to reduce configure size +dnl and use fixed macro across Autoconf versions. + +m4_define([AC_LANG_FUNC_LINK_TRY(C)], +[AC_LANG_PROGRAM( +[ +#define $1 innocuous_$1 +#ifdef __STDC__ +# include +#else +# include +#endif +#undef $1 +#ifdef __cplusplus +extern "C" +#endif +char $1 (); +#if defined __stub_$1 || defined __stub___$1 +choke me +#endif +], [return $1 ();])]) diff --git a/third_party/curl/m4/curl-reentrant.m4 b/third_party/curl/m4/curl-reentrant.m4 new file mode 100644 index 0000000..c1f3339 --- /dev/null +++ b/third_party/curl/m4/curl-reentrant.m4 @@ -0,0 +1,506 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +# File version for 'aclocal' use. Keep it a single number. +# serial 10 + +dnl Note 1 +dnl ------ +dnl None of the CURL_CHECK_NEED_REENTRANT_* macros shall use HAVE_FOO_H to +dnl conditionally include header files. These macros are used early in the +dnl configure process much before header file availability is known. + + +dnl CURL_CHECK_NEED_REENTRANT_ERRNO +dnl ------------------------------------------------- +dnl Checks if the preprocessor _REENTRANT definition +dnl makes errno available as a preprocessor macro. + +AC_DEFUN([CURL_CHECK_NEED_REENTRANT_ERRNO], [ + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#include + ]],[[ + if(0 != errno) + return 1; + ]]) + ],[ + tmp_errno="yes" + ],[ + tmp_errno="no" + ]) + if test "$tmp_errno" = "yes"; then + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#include + ]],[[ +#ifdef errno + int dummy=1; +#else + force compilation error +#endif + ]]) + ],[ + tmp_errno="errno_macro_defined" + ],[ + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#define _REENTRANT +#include + ]],[[ +#ifdef errno + int dummy=1; +#else + force compilation error +#endif + ]]) + ],[ + tmp_errno="errno_macro_needs_reentrant" + tmp_need_reentrant="yes" + ]) + ]) + fi +]) + + +dnl CURL_CHECK_NEED_REENTRANT_GMTIME_R +dnl ------------------------------------------------- +dnl Checks if the preprocessor _REENTRANT definition +dnl makes function gmtime_r compiler visible. + +AC_DEFUN([CURL_CHECK_NEED_REENTRANT_GMTIME_R], [ + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([gmtime_r]) + ],[ + tmp_gmtime_r="yes" + ],[ + tmp_gmtime_r="no" + ]) + if test "$tmp_gmtime_r" = "yes"; then + AC_EGREP_CPP([gmtime_r],[ +#include +#include + ],[ + tmp_gmtime_r="proto_declared" + ],[ + AC_EGREP_CPP([gmtime_r],[ +#define _REENTRANT +#include +#include + ],[ + tmp_gmtime_r="proto_needs_reentrant" + tmp_need_reentrant="yes" + ]) + ]) + fi +]) + + +dnl CURL_CHECK_NEED_REENTRANT_LOCALTIME_R +dnl ------------------------------------------------- +dnl Checks if the preprocessor _REENTRANT definition +dnl makes function localtime_r compiler visible. + +AC_DEFUN([CURL_CHECK_NEED_REENTRANT_LOCALTIME_R], [ + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([localtime_r]) + ],[ + tmp_localtime_r="yes" + ],[ + tmp_localtime_r="no" + ]) + if test "$tmp_localtime_r" = "yes"; then + AC_EGREP_CPP([localtime_r],[ +#include +#include + ],[ + tmp_localtime_r="proto_declared" + ],[ + AC_EGREP_CPP([localtime_r],[ +#define _REENTRANT +#include +#include + ],[ + tmp_localtime_r="proto_needs_reentrant" + tmp_need_reentrant="yes" + ]) + ]) + fi +]) + + +dnl CURL_CHECK_NEED_REENTRANT_STRERROR_R +dnl ------------------------------------------------- +dnl Checks if the preprocessor _REENTRANT definition +dnl makes function strerror_r compiler visible. + +AC_DEFUN([CURL_CHECK_NEED_REENTRANT_STRERROR_R], [ + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([strerror_r]) + ],[ + tmp_strerror_r="yes" + ],[ + tmp_strerror_r="no" + ]) + if test "$tmp_strerror_r" = "yes"; then + AC_EGREP_CPP([strerror_r],[ +#include +#include + ],[ + tmp_strerror_r="proto_declared" + ],[ + AC_EGREP_CPP([strerror_r],[ +#define _REENTRANT +#include +#include + ],[ + tmp_strerror_r="proto_needs_reentrant" + tmp_need_reentrant="yes" + ]) + ]) + fi +]) + + +dnl CURL_CHECK_NEED_REENTRANT_STRTOK_R +dnl ------------------------------------------------- +dnl Checks if the preprocessor _REENTRANT definition +dnl makes function strtok_r compiler visible. + +AC_DEFUN([CURL_CHECK_NEED_REENTRANT_STRTOK_R], [ + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([strtok_r]) + ],[ + tmp_strtok_r="yes" + ],[ + tmp_strtok_r="no" + ]) + if test "$tmp_strtok_r" = "yes"; then + AC_EGREP_CPP([strtok_r],[ +#include +#include + ],[ + tmp_strtok_r="proto_declared" + ],[ + AC_EGREP_CPP([strtok_r],[ +#define _REENTRANT +#include +#include + ],[ + tmp_strtok_r="proto_needs_reentrant" + tmp_need_reentrant="yes" + ]) + ]) + fi +]) + + +dnl CURL_CHECK_NEED_REENTRANT_GETHOSTBYNAME_R +dnl ------------------------------------------------- +dnl Checks if the preprocessor _REENTRANT definition +dnl makes function gethostbyname_r compiler visible. + +AC_DEFUN([CURL_CHECK_NEED_REENTRANT_GETHOSTBYNAME_R], [ + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([gethostbyname_r]) + ],[ + tmp_gethostbyname_r="yes" + ],[ + tmp_gethostbyname_r="no" + ]) + if test "$tmp_gethostbyname_r" = "yes"; then + AC_EGREP_CPP([gethostbyname_r],[ +#include +#include + ],[ + tmp_gethostbyname_r="proto_declared" + ],[ + AC_EGREP_CPP([gethostbyname_r],[ +#define _REENTRANT +#include +#include + ],[ + tmp_gethostbyname_r="proto_needs_reentrant" + tmp_need_reentrant="yes" + ]) + ]) + fi +]) + + +dnl CURL_CHECK_NEED_REENTRANT_GETPROTOBYNAME_R +dnl ------------------------------------------------- +dnl Checks if the preprocessor _REENTRANT definition +dnl makes function getprotobyname_r compiler visible. + +AC_DEFUN([CURL_CHECK_NEED_REENTRANT_GETPROTOBYNAME_R], [ + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([getprotobyname_r]) + ],[ + tmp_getprotobyname_r="yes" + ],[ + tmp_getprotobyname_r="no" + ]) + if test "$tmp_getprotobyname_r" = "yes"; then + AC_EGREP_CPP([getprotobyname_r],[ +#include +#include + ],[ + tmp_getprotobyname_r="proto_declared" + ],[ + AC_EGREP_CPP([getprotobyname_r],[ +#define _REENTRANT +#include +#include + ],[ + tmp_getprotobyname_r="proto_needs_reentrant" + tmp_need_reentrant="yes" + ]) + ]) + fi +]) + + +dnl CURL_CHECK_NEED_REENTRANT_FUNCTIONS_R +dnl ------------------------------------------------- +dnl Checks if the preprocessor _REENTRANT definition +dnl makes several _r functions compiler visible. +dnl Internal macro for CURL_CONFIGURE_REENTRANT. + +AC_DEFUN([CURL_CHECK_NEED_REENTRANT_FUNCTIONS_R], [ + if test "$tmp_need_reentrant" = "no"; then + CURL_CHECK_NEED_REENTRANT_GMTIME_R + fi + if test "$tmp_need_reentrant" = "no"; then + CURL_CHECK_NEED_REENTRANT_LOCALTIME_R + fi + if test "$tmp_need_reentrant" = "no"; then + CURL_CHECK_NEED_REENTRANT_STRERROR_R + fi + if test "$tmp_need_reentrant" = "no"; then + CURL_CHECK_NEED_REENTRANT_STRTOK_R + fi + if test "$tmp_need_reentrant" = "no"; then + CURL_CHECK_NEED_REENTRANT_GETHOSTBYNAME_R + fi + if test "$tmp_need_reentrant" = "no"; then + CURL_CHECK_NEED_REENTRANT_GETPROTOBYNAME_R + fi +]) + + +dnl CURL_CHECK_NEED_REENTRANT_SYSTEM +dnl ------------------------------------------------- +dnl Checks if the preprocessor _REENTRANT definition +dnl must be unconditionally done for this platform. +dnl Internal macro for CURL_CONFIGURE_REENTRANT. + +AC_DEFUN([CURL_CHECK_NEED_REENTRANT_SYSTEM], [ + case $host_os in + solaris*) + tmp_need_reentrant="yes" + ;; + *) + tmp_need_reentrant="no" + ;; + esac +]) + + +dnl CURL_CHECK_NEED_THREAD_SAFE_SYSTEM +dnl ------------------------------------------------- +dnl Checks if the preprocessor _THREAD_SAFE definition +dnl must be unconditionally done for this platform. +dnl Internal macro for CURL_CONFIGURE_THREAD_SAFE. + +AC_DEFUN([CURL_CHECK_NEED_THREAD_SAFE_SYSTEM], [ + case $host_os in + aix[[123]].* | aix4.[[012]].*) + dnl aix 4.2 and older + tmp_need_thread_safe="no" + ;; + aix*) + dnl AIX 4.3 and newer + tmp_need_thread_safe="yes" + ;; + *) + tmp_need_thread_safe="no" + ;; + esac +]) + + +dnl CURL_CONFIGURE_FROM_NOW_ON_WITH_REENTRANT +dnl ------------------------------------------------- +dnl This macro ensures that configuration tests done +dnl after this will execute with preprocessor symbol +dnl _REENTRANT defined. This macro also ensures that +dnl the generated config file defines NEED_REENTRANT +dnl and that in turn curl_setup.h will define _REENTRANT. +dnl Internal macro for CURL_CONFIGURE_REENTRANT. + +AC_DEFUN([CURL_CONFIGURE_FROM_NOW_ON_WITH_REENTRANT], [ +AC_DEFINE(NEED_REENTRANT, 1, + [Define to 1 if _REENTRANT preprocessor symbol must be defined.]) +cat >>confdefs.h <<_EOF +#ifndef _REENTRANT +# define _REENTRANT +#endif +_EOF +]) + + +dnl CURL_CONFIGURE_FROM_NOW_ON_WITH_THREAD_SAFE +dnl ------------------------------------------------- +dnl This macro ensures that configuration tests done +dnl after this will execute with preprocessor symbol +dnl _THREAD_SAFE defined. This macro also ensures that +dnl the generated config file defines NEED_THREAD_SAFE +dnl and that in turn curl_setup.h will define _THREAD_SAFE. +dnl Internal macro for CURL_CONFIGURE_THREAD_SAFE. + +AC_DEFUN([CURL_CONFIGURE_FROM_NOW_ON_WITH_THREAD_SAFE], [ +AC_DEFINE(NEED_THREAD_SAFE, 1, + [Define to 1 if _THREAD_SAFE preprocessor symbol must be defined.]) +cat >>confdefs.h <<_EOF +#ifndef _THREAD_SAFE +# define _THREAD_SAFE +#endif +_EOF +]) + + +dnl CURL_CONFIGURE_REENTRANT +dnl ------------------------------------------------- +dnl This first checks if the preprocessor _REENTRANT +dnl symbol is already defined. If it isn't currently +dnl defined a set of checks are performed to verify +dnl if its definition is required to make visible to +dnl the compiler a set of *_r functions. Finally, if +dnl _REENTRANT is already defined or needed it takes +dnl care of making adjustments necessary to ensure +dnl that it is defined equally for further configure +dnl tests and generated config file. + +AC_DEFUN([CURL_CONFIGURE_REENTRANT], [ + AC_PREREQ([2.50])dnl + # + AC_MSG_CHECKING([if _REENTRANT is already defined]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + ]],[[ +#ifdef _REENTRANT + int dummy=1; +#else + force compilation error +#endif + ]]) + ],[ + AC_MSG_RESULT([yes]) + tmp_reentrant_initially_defined="yes" + ],[ + AC_MSG_RESULT([no]) + tmp_reentrant_initially_defined="no" + ]) + # + if test "$tmp_reentrant_initially_defined" = "no"; then + AC_MSG_CHECKING([if _REENTRANT is actually needed]) + CURL_CHECK_NEED_REENTRANT_SYSTEM + if test "$tmp_need_reentrant" = "no"; then + CURL_CHECK_NEED_REENTRANT_ERRNO + fi + if test "$tmp_need_reentrant" = "no"; then + CURL_CHECK_NEED_REENTRANT_FUNCTIONS_R + fi + if test "$tmp_need_reentrant" = "yes"; then + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + fi + fi + # + AC_MSG_CHECKING([if _REENTRANT is onwards defined]) + if test "$tmp_reentrant_initially_defined" = "yes" || + test "$tmp_need_reentrant" = "yes"; then + CURL_CONFIGURE_FROM_NOW_ON_WITH_REENTRANT + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + fi + # +]) + + +dnl CURL_CONFIGURE_THREAD_SAFE +dnl ------------------------------------------------- +dnl This first checks if the preprocessor _THREAD_SAFE +dnl symbol is already defined. If it isn't currently +dnl defined a set of checks are performed to verify +dnl if its definition is required. Finally, if +dnl _THREAD_SAFE is already defined or needed it takes +dnl care of making adjustments necessary to ensure +dnl that it is defined equally for further configure +dnl tests and generated config file. + +AC_DEFUN([CURL_CONFIGURE_THREAD_SAFE], [ + AC_PREREQ([2.50])dnl + # + AC_MSG_CHECKING([if _THREAD_SAFE is already defined]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + ]],[[ +#ifdef _THREAD_SAFE + int dummy=1; +#else + force compilation error +#endif + ]]) + ],[ + AC_MSG_RESULT([yes]) + tmp_thread_safe_initially_defined="yes" + ],[ + AC_MSG_RESULT([no]) + tmp_thread_safe_initially_defined="no" + ]) + # + if test "$tmp_thread_safe_initially_defined" = "no"; then + AC_MSG_CHECKING([if _THREAD_SAFE is actually needed]) + CURL_CHECK_NEED_THREAD_SAFE_SYSTEM + if test "$tmp_need_thread_safe" = "yes"; then + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + fi + fi + # + AC_MSG_CHECKING([if _THREAD_SAFE is onwards defined]) + if test "$tmp_thread_safe_initially_defined" = "yes" || + test "$tmp_need_thread_safe" = "yes"; then + CURL_CONFIGURE_FROM_NOW_ON_WITH_THREAD_SAFE + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + fi + # +]) diff --git a/third_party/curl/m4/curl-rustls.m4 b/third_party/curl/m4/curl-rustls.m4 new file mode 100644 index 0000000..ef8d7dd --- /dev/null +++ b/third_party/curl/m4/curl-rustls.m4 @@ -0,0 +1,189 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +AC_DEFUN([CURL_WITH_RUSTLS], [ +dnl ---------------------------------------------------- +dnl check for rustls +dnl ---------------------------------------------------- + +if test "x$OPT_RUSTLS" != xno; then + ssl_msg= + + dnl backup the pre-ssl variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + + case $host_os in + darwin*) + LDFLAGS="$LDFLAGS -framework Security" + ;; + *) + ;; + esac + ## NEW CODE + + dnl use pkg-config unless we have been given a path + dnl even then, try pkg-config first + + case "$OPT_RUSTLS" in + yes) + dnl --with-rustls (without path) used + PKGTEST="yes" + PREFIX_RUSTLS= + ;; + *) + dnl check the provided --with-rustls path + PKGTEST="no" + PREFIX_RUSTLS=$OPT_RUSTLS + + dnl Try pkg-config even when cross-compiling. Since we + dnl specify PKG_CONFIG_LIBDIR we are only looking where + dnl the user told us to look + + RUSTLS_PCDIR="$PREFIX_RUSTLS/lib/pkgconfig" + if test -f "$RUSTLS_PCDIR/rustls.pc"; then + AC_MSG_NOTICE([PKG_CONFIG_LIBDIR will be set to "$RUSTLS_PCDIR"]) + PKGTEST="yes" + fi + + if test "$PKGTEST" != "yes"; then + # try lib64 instead + RUSTLS_PCDIR="$PREFIX_RUSTLS/lib64/pkgconfig" + if test -f "$RUSTLS_PCDIR/rustls.pc"; then + AC_MSG_NOTICE([PKG_CONFIG_LIBDIR will be set to "$RUSTLS_PCDIR"]) + PKGTEST="yes" + fi + fi + + if test "$PKGTEST" != "yes"; then + dnl pkg-config came up empty, use what we got + dnl via --with-rustls + + addld=-L$PREFIX_RUSTLS/lib$libsuff + addcflags=-I$PREFIX_RUSTLS/include + + LDFLAGS="$LDFLAGS $addld" + if test "$addcflags" != "-I/usr/include"; then + CPPFLAGS="$CPPFLAGS $addcflags" + fi + + AC_CHECK_LIB(rustls, rustls_connection_read, + [ + AC_DEFINE(USE_RUSTLS, 1, [if rustls is enabled]) + AC_SUBST(USE_RUSTLS, [1]) + RUSTLS_ENABLED=1 + USE_RUSTLS="yes" + ssl_msg="rustls" + test rustls != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + ], + AC_MSG_ERROR([--with-rustls was specified but could not find rustls.]), + -lpthread -ldl -lm) + + LIB_RUSTLS="$PREFIX_RUSTLS/lib$libsuff" + if test "$PREFIX_RUSTLS" != "/usr" ; then + SSL_LDFLAGS="-L$LIB_RUSTLS" + SSL_CPPFLAGS="-I$PREFIX_RUSTLS/include" + fi + fi + ;; + esac + + if test "$PKGTEST" = "yes"; then + + CURL_CHECK_PKGCONFIG(rustls, [$RUSTLS_PCDIR]) + + if test "$PKGCONFIG" != "no" ; then + SSL_LIBS=`CURL_EXPORT_PCDIR([$RUSTLS_PCDIR]) dnl + $PKGCONFIG --libs-only-l --libs-only-other rustls 2>/dev/null` + + SSL_LDFLAGS=`CURL_EXPORT_PCDIR([$RUSTLS_PCDIR]) dnl + $PKGCONFIG --libs-only-L rustls 2>/dev/null` + + SSL_CPPFLAGS=`CURL_EXPORT_PCDIR([$RUSTLS_PCDIR]) dnl + $PKGCONFIG --cflags-only-I rustls 2>/dev/null` + + AC_SUBST(SSL_LIBS) + AC_MSG_NOTICE([pkg-config: SSL_LIBS: "$SSL_LIBS"]) + AC_MSG_NOTICE([pkg-config: SSL_LDFLAGS: "$SSL_LDFLAGS"]) + AC_MSG_NOTICE([pkg-config: SSL_CPPFLAGS: "$SSL_CPPFLAGS"]) + + LIB_RUSTLS=`echo $SSL_LDFLAGS | sed -e 's/^-L//'` + + dnl use the values pkg-config reported. This is here + dnl instead of below with CPPFLAGS and LDFLAGS because we only + dnl learn about this via pkg-config. If we only have + dnl the argument to --with-rustls we don't know what + dnl additional libs may be necessary. Hope that we + dnl don't need any. + LIBS="$SSL_LIBS $LIBS" + ssl_msg="rustls" + AC_DEFINE(USE_RUSTLS, 1, [if rustls is enabled]) + AC_SUBST(USE_RUSTLS, [1]) + USE_RUSTLS="yes" + RUSTLS_ENABLED=1 + test rustls != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + else + AC_MSG_ERROR([pkg-config: Could not find rustls]) + fi + + else + dnl we did not use pkg-config, so we need to add the + dnl rustls lib to LIBS + LIBS="-lrustls -lpthread -ldl -lm $LIBS" + fi + + dnl finally, set flags to use this TLS backend + CPPFLAGS="$CLEAN_CPPFLAGS $SSL_CPPFLAGS" + LDFLAGS="$CLAN_LDFLAGS $SSL_LDFLAGS" + + if test "x$USE_RUSTLS" = "xyes"; then + AC_MSG_NOTICE([detected rustls]) + check_for_ca_bundle=1 + + if test -n "$LIB_RUSTLS"; then + dnl when shared libs were found in a path that the run-time + dnl linker does not search through, we need to add it to + dnl CURL_LIBRARY_PATH so that further configure tests do not + dnl fail due to this + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$LIB_RUSTLS" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $LIB_RUSTLS to CURL_LIBRARY_PATH]) + fi + fi + fi + + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" + + if test X"$OPT_RUSTLS" != Xno && + test "$RUSTLS_ENABLED" != "1"; then + AC_MSG_NOTICE([OPT_RUSTLS: $OPT_RUSTLS]) + AC_MSG_NOTICE([RUSTLS_ENABLED: $RUSTLS_ENABLED]) + AC_MSG_ERROR([--with-rustls was given but Rustls could not be detected]) + fi +fi +]) + + +RUSTLS_ENABLED diff --git a/third_party/curl/m4/curl-schannel.m4 b/third_party/curl/m4/curl-schannel.m4 new file mode 100644 index 0000000..016bfd4 --- /dev/null +++ b/third_party/curl/m4/curl-schannel.m4 @@ -0,0 +1,48 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +AC_DEFUN([CURL_WITH_SCHANNEL], [ +AC_MSG_CHECKING([whether to enable Windows native SSL/TLS]) +if test "x$OPT_SCHANNEL" != xno; then + ssl_msg= + if test "x$OPT_SCHANNEL" != "xno" && + test "x$curl_cv_native_windows" = "xyes"; then + AC_MSG_RESULT(yes) + AC_DEFINE(USE_SCHANNEL, 1, [to enable Windows native SSL/TLS support]) + AC_SUBST(USE_SCHANNEL, [1]) + ssl_msg="Schannel" + test schannel != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + SCHANNEL_ENABLED=1 + # --with-schannel implies --enable-sspi + AC_DEFINE(USE_WINDOWS_SSPI, 1, [to enable SSPI support]) + AC_SUBST(USE_WINDOWS_SSPI, [1]) + curl_sspi_msg="enabled" + else + AC_MSG_RESULT(no) + fi + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" +else + AC_MSG_RESULT(no) +fi +]) diff --git a/third_party/curl/m4/curl-sectransp.m4 b/third_party/curl/m4/curl-sectransp.m4 new file mode 100644 index 0000000..77b37be --- /dev/null +++ b/third_party/curl/m4/curl-sectransp.m4 @@ -0,0 +1,45 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +AC_DEFUN([CURL_WITH_SECURETRANSPORT], [ +AC_MSG_CHECKING([whether to enable Secure Transport]) +if test "x$OPT_SECURETRANSPORT" != xno; then + if test "x$OPT_SECURETRANSPORT" != "xno" && + (test "x$cross_compiling" != "xno" || test -d "/System/Library/Frameworks/Security.framework"); then + AC_MSG_RESULT(yes) + AC_DEFINE(USE_SECTRANSP, 1, [enable Secure Transport]) + AC_SUBST(USE_SECTRANSP, [1]) + ssl_msg="Secure Transport" + test secure-transport != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + SECURETRANSPORT_ENABLED=1 + LDFLAGS="$LDFLAGS -framework CoreFoundation -framework CoreServices -framework Security" + else + AC_MSG_RESULT(no) + fi + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" +else + AC_MSG_RESULT(no) +fi + +]) diff --git a/third_party/curl/m4/curl-sysconfig.m4 b/third_party/curl/m4/curl-sysconfig.m4 new file mode 100644 index 0000000..9b287bc --- /dev/null +++ b/third_party/curl/m4/curl-sysconfig.m4 @@ -0,0 +1,54 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +AC_DEFUN([CURL_DARWIN_SYSTEMCONFIGURATION], [ +AC_MSG_CHECKING([whether to link macOS CoreFoundation, CoreServices, and SystemConfiguration frameworks]) +case $host_os in + darwin*) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ +#include + ]],[[ +#if TARGET_OS_MAC && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) + return 0; +#else +#error Not macOS +#endif + ]]) + ],[ + build_for_macos="yes" + ],[ + build_for_macos="no" + ]) + if test "x$build_for_macos" != xno; then + AC_MSG_RESULT(yes) + LDFLAGS="$LDFLAGS -framework CoreFoundation -framework CoreServices -framework SystemConfiguration" + else + AC_MSG_RESULT(no) + fi + ;; + *) + AC_MSG_RESULT(no) +esac +]) diff --git a/third_party/curl/m4/curl-wolfssl.m4 b/third_party/curl/m4/curl-wolfssl.m4 new file mode 100644 index 0000000..1da47a9 --- /dev/null +++ b/third_party/curl/m4/curl-wolfssl.m4 @@ -0,0 +1,176 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +AC_DEFUN([CURL_WITH_WOLFSSL], [ +dnl ---------------------------------------------------- +dnl check for wolfSSL +dnl ---------------------------------------------------- + +case "$OPT_WOLFSSL" in + yes|no) + wolfpkg="" + ;; + *) + wolfpkg="$withval/lib/pkgconfig" + ;; +esac + +if test "x$OPT_WOLFSSL" != xno; then + _cppflags=$CPPFLAGS + _ldflags=$LDFLAGS + + ssl_msg= + + if test X"$OPT_WOLFSSL" != Xno; then + + if test "$OPT_WOLFSSL" = "yes"; then + OPT_WOLFSSL="" + fi + + dnl try pkg-config magic + CURL_CHECK_PKGCONFIG(wolfssl, [$wolfpkg]) + AC_MSG_NOTICE([Check dir $wolfpkg]) + + addld="" + addlib="" + addcflags="" + if test "$PKGCONFIG" != "no" ; then + addlib=`CURL_EXPORT_PCDIR([$wolfpkg]) + $PKGCONFIG --libs-only-l wolfssl` + addld=`CURL_EXPORT_PCDIR([$wolfpkg]) + $PKGCONFIG --libs-only-L wolfssl` + addcflags=`CURL_EXPORT_PCDIR([$wolfpkg]) + $PKGCONFIG --cflags-only-I wolfssl` + version=`CURL_EXPORT_PCDIR([$wolfpkg]) + $PKGCONFIG --modversion wolfssl` + wolfssllibpath=`echo $addld | $SED -e 's/^-L//'` + else + addlib=-lwolfssl + dnl use system defaults if user does not supply a path + if test -n "$OPT_WOLFSSL"; then + addld=-L$OPT_WOLFSSL/lib$libsuff + addcflags=-I$OPT_WOLFSSL/include + wolfssllibpath=$OPT_WOLFSSL/lib$libsuff + fi + fi + + if test "x$USE_WOLFSSL" != "xyes"; then + + LDFLAGS="$LDFLAGS $addld" + AC_MSG_NOTICE([Add $addld to LDFLAGS]) + if test "$addcflags" != "-I/usr/include"; then + CPPFLAGS="$CPPFLAGS $addcflags" + AC_MSG_NOTICE([Add $addcflags to CPPFLAGS]) + fi + + my_ac_save_LIBS="$LIBS" + LIBS="$addlib $LIBS" + AC_MSG_NOTICE([Add $addlib to LIBS]) + + AC_MSG_CHECKING([for wolfSSL_Init in -lwolfssl]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ +/* These aren't needed for detection and confuse WolfSSL. + They are set up properly later if it is detected. */ +#undef SIZEOF_LONG +#undef SIZEOF_LONG_LONG +#include +#include + ]],[[ + return wolfSSL_Init(); + ]]) + ],[ + AC_MSG_RESULT(yes) + AC_DEFINE(USE_WOLFSSL, 1, [if wolfSSL is enabled]) + AC_SUBST(USE_WOLFSSL, [1]) + WOLFSSL_ENABLED=1 + USE_WOLFSSL="yes" + ssl_msg="WolfSSL" + QUIC_ENABLED=yes + test wolfssl != "$DEFAULT_SSL_BACKEND" || VALID_DEFAULT_SSL_BACKEND=yes + ], + [ + AC_MSG_RESULT(no) + CPPFLAGS=$_cppflags + LDFLAGS=$_ldflags + wolfssllibpath="" + ]) + LIBS="$my_ac_save_LIBS" + fi + + if test "x$USE_WOLFSSL" = "xyes"; then + AC_MSG_NOTICE([detected wolfSSL]) + check_for_ca_bundle=1 + + dnl wolfssl/ctaocrypt/types.h needs SIZEOF_LONG_LONG defined! + CURL_SIZEOF(long long) + + LIBS="$addlib -lm $LIBS" + + dnl WolfSSL needs configure --enable-opensslextra to have *get_peer* + dnl DES* is needed for NTLM support and lives in the OpenSSL compatibility + dnl layer + AC_CHECK_FUNCS(wolfSSL_get_peer_certificate \ + wolfSSL_UseALPN ) + + dnl if this symbol is present, we want the include path to include the + dnl OpenSSL API root as well + AC_CHECK_FUNC(wolfSSL_DES_ecb_encrypt, + [ + AC_DEFINE(HAVE_WOLFSSL_DES_ECB_ENCRYPT, 1, + [if you have wolfSSL_DES_ecb_encrypt]) + WOLFSSL_NTLM=1 + ] + ) + + dnl if this symbol is present, we can make use of BIO filter chains + AC_CHECK_FUNC(wolfSSL_BIO_set_shutdown, + [ + AC_DEFINE(HAVE_WOLFSSL_FULL_BIO, 1, + [if you have wolfSSL_BIO_set_shutdown]) + WOLFSSL_FULL_BIO=1 + ] + ) + + if test -n "$wolfssllibpath"; then + dnl when shared libs were found in a path that the run-time + dnl linker doesn't search through, we need to add it to + dnl CURL_LIBRARY_PATH to prevent further configure tests to fail + dnl due to this + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$wolfssllibpath" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $wolfssllibpath to CURL_LIBRARY_PATH]) + fi + fi + else + AC_MSG_ERROR([--with-wolfssl but wolfSSL was not found or doesn't work]) + fi + + fi dnl wolfSSL not disabled + + test -z "$ssl_msg" || ssl_backends="${ssl_backends:+$ssl_backends, }$ssl_msg" +fi + +]) diff --git a/third_party/curl/m4/libtool.m4 b/third_party/curl/m4/libtool.m4 new file mode 100644 index 0000000..e7b6833 --- /dev/null +++ b/third_party/curl/m4/libtool.m4 @@ -0,0 +1,8427 @@ +# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*- +# +# Copyright (C) 1996-2001, 2003-2019, 2021-2022 Free Software +# Foundation, Inc. +# Written by Gordon Matzigkeit, 1996 +# +# This file is free software; the Free Software Foundation gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. + +m4_define([_LT_COPYING], [dnl +# Copyright (C) 2014 Free Software Foundation, Inc. +# This is free software; see the source for copying conditions. There is NO +# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +# GNU Libtool is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of of the License, or +# (at your option) any later version. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program or library that is built +# using GNU Libtool, you may include this file under the same +# distribution terms that you use for the rest of that program. +# +# GNU Libtool is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +]) + +# serial 59 LT_INIT + + +# LT_PREREQ(VERSION) +# ------------------ +# Complain and exit if this libtool version is less that VERSION. +m4_defun([LT_PREREQ], +[m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1, + [m4_default([$3], + [m4_fatal([Libtool version $1 or higher is required], + 63)])], + [$2])]) + + +# _LT_CHECK_BUILDDIR +# ------------------ +# Complain if the absolute build directory name contains unusual characters +m4_defun([_LT_CHECK_BUILDDIR], +[case `pwd` in + *\ * | *\ *) + AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;; +esac +]) + + +# LT_INIT([OPTIONS]) +# ------------------ +AC_DEFUN([LT_INIT], +[AC_PREREQ([2.62])dnl We use AC_PATH_PROGS_FEATURE_CHECK +AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl +AC_BEFORE([$0], [LT_LANG])dnl +AC_BEFORE([$0], [LT_OUTPUT])dnl +AC_BEFORE([$0], [LTDL_INIT])dnl +m4_require([_LT_CHECK_BUILDDIR])dnl + +dnl Autoconf doesn't catch unexpanded LT_ macros by default: +m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl +m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl +dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4 +dnl unless we require an AC_DEFUNed macro: +AC_REQUIRE([LTOPTIONS_VERSION])dnl +AC_REQUIRE([LTSUGAR_VERSION])dnl +AC_REQUIRE([LTVERSION_VERSION])dnl +AC_REQUIRE([LTOBSOLETE_VERSION])dnl +m4_require([_LT_PROG_LTMAIN])dnl + +_LT_SHELL_INIT([SHELL=${CONFIG_SHELL-/bin/sh}]) + +dnl Parse OPTIONS +_LT_SET_OPTIONS([$0], [$1]) + +# This can be used to rebuild libtool when needed +LIBTOOL_DEPS=$ltmain + +# Always use our own libtool. +LIBTOOL='$(SHELL) $(top_builddir)/libtool' +AC_SUBST(LIBTOOL)dnl + +_LT_SETUP + +# Only expand once: +m4_define([LT_INIT]) +])# LT_INIT + +# Old names: +AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT]) +AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_PROG_LIBTOOL], []) +dnl AC_DEFUN([AM_PROG_LIBTOOL], []) + + +# _LT_PREPARE_CC_BASENAME +# ----------------------- +m4_defun([_LT_PREPARE_CC_BASENAME], [ +# Calculate cc_basename. Skip known compiler wrappers and cross-prefix. +func_cc_basename () +{ + for cc_temp in @S|@*""; do + case $cc_temp in + compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;; + distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;; + \-*) ;; + *) break;; + esac + done + func_cc_basename_result=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` +} +])# _LT_PREPARE_CC_BASENAME + + +# _LT_CC_BASENAME(CC) +# ------------------- +# It would be clearer to call AC_REQUIREs from _LT_PREPARE_CC_BASENAME, +# but that macro is also expanded into generated libtool script, which +# arranges for $SED and $ECHO to be set by different means. +m4_defun([_LT_CC_BASENAME], +[m4_require([_LT_PREPARE_CC_BASENAME])dnl +AC_REQUIRE([_LT_DECL_SED])dnl +AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl +func_cc_basename $1 +cc_basename=$func_cc_basename_result +]) + + +# _LT_FILEUTILS_DEFAULTS +# ---------------------- +# It is okay to use these file commands and assume they have been set +# sensibly after 'm4_require([_LT_FILEUTILS_DEFAULTS])'. +m4_defun([_LT_FILEUTILS_DEFAULTS], +[: ${CP="cp -f"} +: ${MV="mv -f"} +: ${RM="rm -f"} +])# _LT_FILEUTILS_DEFAULTS + + +# _LT_SETUP +# --------- +m4_defun([_LT_SETUP], +[AC_REQUIRE([AC_CANONICAL_HOST])dnl +AC_REQUIRE([AC_CANONICAL_BUILD])dnl +AC_REQUIRE([_LT_PREPARE_SED_QUOTE_VARS])dnl +AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl + +_LT_DECL([], [PATH_SEPARATOR], [1], [The PATH separator for the build system])dnl +dnl +_LT_DECL([], [host_alias], [0], [The host system])dnl +_LT_DECL([], [host], [0])dnl +_LT_DECL([], [host_os], [0])dnl +dnl +_LT_DECL([], [build_alias], [0], [The build system])dnl +_LT_DECL([], [build], [0])dnl +_LT_DECL([], [build_os], [0])dnl +dnl +AC_REQUIRE([AC_PROG_CC])dnl +AC_REQUIRE([LT_PATH_LD])dnl +AC_REQUIRE([LT_PATH_NM])dnl +dnl +AC_REQUIRE([AC_PROG_LN_S])dnl +test -z "$LN_S" && LN_S="ln -s" +_LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl +dnl +AC_REQUIRE([LT_CMD_MAX_LEN])dnl +_LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl +_LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl +dnl +m4_require([_LT_FILEUTILS_DEFAULTS])dnl +m4_require([_LT_CHECK_SHELL_FEATURES])dnl +m4_require([_LT_PATH_CONVERSION_FUNCTIONS])dnl +m4_require([_LT_CMD_RELOAD])dnl +m4_require([_LT_DECL_FILECMD])dnl +m4_require([_LT_CHECK_MAGIC_METHOD])dnl +m4_require([_LT_CHECK_SHAREDLIB_FROM_LINKLIB])dnl +m4_require([_LT_CMD_OLD_ARCHIVE])dnl +m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl +m4_require([_LT_WITH_SYSROOT])dnl +m4_require([_LT_CMD_TRUNCATE])dnl + +_LT_CONFIG_LIBTOOL_INIT([ +# See if we are running on zsh, and set the options that allow our +# commands through without removal of \ escapes INIT. +if test -n "\${ZSH_VERSION+set}"; then + setopt NO_GLOB_SUBST +fi +]) +if test -n "${ZSH_VERSION+set}"; then + setopt NO_GLOB_SUBST +fi + +_LT_CHECK_OBJDIR + +m4_require([_LT_TAG_COMPILER])dnl + +case $host_os in +aix3*) + # AIX sometimes has problems with the GCC collect2 program. For some + # reason, if we set the COLLECT_NAMES environment variable, the problems + # vanish in a puff of smoke. + if test set != "${COLLECT_NAMES+set}"; then + COLLECT_NAMES= + export COLLECT_NAMES + fi + ;; +esac + +# Global variables: +ofile=libtool +can_build_shared=yes + +# All known linkers require a '.a' archive for static linking (except MSVC and +# ICC, which need '.lib'). +libext=a + +with_gnu_ld=$lt_cv_prog_gnu_ld + +old_CC=$CC +old_CFLAGS=$CFLAGS + +# Set sane defaults for various variables +test -z "$CC" && CC=cc +test -z "$LTCC" && LTCC=$CC +test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS +test -z "$LD" && LD=ld +test -z "$ac_objext" && ac_objext=o + +_LT_CC_BASENAME([$compiler]) + +# Only perform the check for file, if the check method requires it +test -z "$MAGIC_CMD" && MAGIC_CMD=file +case $deplibs_check_method in +file_magic*) + if test "$file_magic_cmd" = '$MAGIC_CMD'; then + _LT_PATH_MAGIC + fi + ;; +esac + +# Use C for the default configuration in the libtool script +LT_SUPPORTED_TAG([CC]) +_LT_LANG_C_CONFIG +_LT_LANG_DEFAULT_CONFIG +_LT_CONFIG_COMMANDS +])# _LT_SETUP + + +# _LT_PREPARE_SED_QUOTE_VARS +# -------------------------- +# Define a few sed substitution that help us do robust quoting. +m4_defun([_LT_PREPARE_SED_QUOTE_VARS], +[# Backslashify metacharacters that are still active within +# double-quoted strings. +sed_quote_subst='s/\([["`$\\]]\)/\\\1/g' + +# Same as above, but do not quote variable references. +double_quote_subst='s/\([["`\\]]\)/\\\1/g' + +# Sed substitution to delay expansion of an escaped shell variable in a +# double_quote_subst'ed string. +delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' + +# Sed substitution to delay expansion of an escaped single quote. +delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' + +# Sed substitution to avoid accidental globbing in evaled expressions +no_glob_subst='s/\*/\\\*/g' +]) + +# _LT_PROG_LTMAIN +# --------------- +# Note that this code is called both from 'configure', and 'config.status' +# now that we use AC_CONFIG_COMMANDS to generate libtool. Notably, +# 'config.status' has no value for ac_aux_dir unless we are using Automake, +# so we pass a copy along to make sure it has a sensible value anyway. +m4_defun([_LT_PROG_LTMAIN], +[m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl +_LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir']) +ltmain=$ac_aux_dir/ltmain.sh +])# _LT_PROG_LTMAIN + + +## ------------------------------------- ## +## Accumulate code for creating libtool. ## +## ------------------------------------- ## + +# So that we can recreate a full libtool script including additional +# tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS +# in macros and then make a single call at the end using the 'libtool' +# label. + + +# _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS]) +# ---------------------------------------- +# Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later. +m4_define([_LT_CONFIG_LIBTOOL_INIT], +[m4_ifval([$1], + [m4_append([_LT_OUTPUT_LIBTOOL_INIT], + [$1 +])])]) + +# Initialize. +m4_define([_LT_OUTPUT_LIBTOOL_INIT]) + + +# _LT_CONFIG_LIBTOOL([COMMANDS]) +# ------------------------------ +# Register COMMANDS to be passed to AC_CONFIG_COMMANDS later. +m4_define([_LT_CONFIG_LIBTOOL], +[m4_ifval([$1], + [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS], + [$1 +])])]) + +# Initialize. +m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS]) + + +# _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS]) +# ----------------------------------------------------- +m4_defun([_LT_CONFIG_SAVE_COMMANDS], +[_LT_CONFIG_LIBTOOL([$1]) +_LT_CONFIG_LIBTOOL_INIT([$2]) +]) + + +# _LT_FORMAT_COMMENT([COMMENT]) +# ----------------------------- +# Add leading comment marks to the start of each line, and a trailing +# full-stop to the whole comment if one is not present already. +m4_define([_LT_FORMAT_COMMENT], +[m4_ifval([$1], [ +m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])], + [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.]) +)]) + + + +## ------------------------ ## +## FIXME: Eliminate VARNAME ## +## ------------------------ ## + + +# _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?]) +# ------------------------------------------------------------------- +# CONFIGNAME is the name given to the value in the libtool script. +# VARNAME is the (base) name used in the configure script. +# VALUE may be 0, 1 or 2 for a computed quote escaped value based on +# VARNAME. Any other value will be used directly. +m4_define([_LT_DECL], +[lt_if_append_uniq([lt_decl_varnames], [$2], [, ], + [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name], + [m4_ifval([$1], [$1], [$2])]) + lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3]) + m4_ifval([$4], + [lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])]) + lt_dict_add_subkey([lt_decl_dict], [$2], + [tagged?], [m4_ifval([$5], [yes], [no])])]) +]) + + +# _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION]) +# -------------------------------------------------------- +m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])]) + + +# lt_decl_tag_varnames([SEPARATOR], [VARNAME1...]) +# ------------------------------------------------ +m4_define([lt_decl_tag_varnames], +[_lt_decl_filter([tagged?], [yes], $@)]) + + +# _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..]) +# --------------------------------------------------------- +m4_define([_lt_decl_filter], +[m4_case([$#], + [0], [m4_fatal([$0: too few arguments: $#])], + [1], [m4_fatal([$0: too few arguments: $#: $1])], + [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)], + [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)], + [lt_dict_filter([lt_decl_dict], $@)])[]dnl +]) + + +# lt_decl_quote_varnames([SEPARATOR], [VARNAME1...]) +# -------------------------------------------------- +m4_define([lt_decl_quote_varnames], +[_lt_decl_filter([value], [1], $@)]) + + +# lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...]) +# --------------------------------------------------- +m4_define([lt_decl_dquote_varnames], +[_lt_decl_filter([value], [2], $@)]) + + +# lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...]) +# --------------------------------------------------- +m4_define([lt_decl_varnames_tagged], +[m4_assert([$# <= 2])dnl +_$0(m4_quote(m4_default([$1], [[, ]])), + m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]), + m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))]) +m4_define([_lt_decl_varnames_tagged], +[m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])]) + + +# lt_decl_all_varnames([SEPARATOR], [VARNAME1...]) +# ------------------------------------------------ +m4_define([lt_decl_all_varnames], +[_$0(m4_quote(m4_default([$1], [[, ]])), + m4_if([$2], [], + m4_quote(lt_decl_varnames), + m4_quote(m4_shift($@))))[]dnl +]) +m4_define([_lt_decl_all_varnames], +[lt_join($@, lt_decl_varnames_tagged([$1], + lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl +]) + + +# _LT_CONFIG_STATUS_DECLARE([VARNAME]) +# ------------------------------------ +# Quote a variable value, and forward it to 'config.status' so that its +# declaration there will have the same value as in 'configure'. VARNAME +# must have a single quote delimited value for this to work. +m4_define([_LT_CONFIG_STATUS_DECLARE], +[$1='`$ECHO "$][$1" | $SED "$delay_single_quote_subst"`']) + + +# _LT_CONFIG_STATUS_DECLARATIONS +# ------------------------------ +# We delimit libtool config variables with single quotes, so when +# we write them to config.status, we have to be sure to quote all +# embedded single quotes properly. In configure, this macro expands +# each variable declared with _LT_DECL (and _LT_TAGDECL) into: +# +# ='`$ECHO "$" | $SED "$delay_single_quote_subst"`' +m4_defun([_LT_CONFIG_STATUS_DECLARATIONS], +[m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames), + [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])]) + + +# _LT_LIBTOOL_TAGS +# ---------------- +# Output comment and list of tags supported by the script +m4_defun([_LT_LIBTOOL_TAGS], +[_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl +available_tags='_LT_TAGS'dnl +]) + + +# _LT_LIBTOOL_DECLARE(VARNAME, [TAG]) +# ----------------------------------- +# Extract the dictionary values for VARNAME (optionally with TAG) and +# expand to a commented shell variable setting: +# +# # Some comment about what VAR is for. +# visible_name=$lt_internal_name +m4_define([_LT_LIBTOOL_DECLARE], +[_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], + [description])))[]dnl +m4_pushdef([_libtool_name], + m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl +m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])), + [0], [_libtool_name=[$]$1], + [1], [_libtool_name=$lt_[]$1], + [2], [_libtool_name=$lt_[]$1], + [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl +m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl +]) + + +# _LT_LIBTOOL_CONFIG_VARS +# ----------------------- +# Produce commented declarations of non-tagged libtool config variables +# suitable for insertion in the LIBTOOL CONFIG section of the 'libtool' +# script. Tagged libtool config variables (even for the LIBTOOL CONFIG +# section) are produced by _LT_LIBTOOL_TAG_VARS. +m4_defun([_LT_LIBTOOL_CONFIG_VARS], +[m4_foreach([_lt_var], + m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)), + [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])]) + + +# _LT_LIBTOOL_TAG_VARS(TAG) +# ------------------------- +m4_define([_LT_LIBTOOL_TAG_VARS], +[m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames), + [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])]) + + +# _LT_TAGVAR(VARNAME, [TAGNAME]) +# ------------------------------ +m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])]) + + +# _LT_CONFIG_COMMANDS +# ------------------- +# Send accumulated output to $CONFIG_STATUS. Thanks to the lists of +# variables for single and double quote escaping we saved from calls +# to _LT_DECL, we can put quote escaped variables declarations +# into 'config.status', and then the shell code to quote escape them in +# for loops in 'config.status'. Finally, any additional code accumulated +# from calls to _LT_CONFIG_LIBTOOL_INIT is expanded. +m4_defun([_LT_CONFIG_COMMANDS], +[AC_PROVIDE_IFELSE([LT_OUTPUT], + dnl If the libtool generation code has been placed in $CONFIG_LT, + dnl instead of duplicating it all over again into config.status, + dnl then we will have config.status run $CONFIG_LT later, so it + dnl needs to know what name is stored there: + [AC_CONFIG_COMMANDS([libtool], + [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])], + dnl If the libtool generation code is destined for config.status, + dnl expand the accumulated commands and init code now: + [AC_CONFIG_COMMANDS([libtool], + [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])]) +])#_LT_CONFIG_COMMANDS + + +# Initialize. +m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT], +[ + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +sed_quote_subst='$sed_quote_subst' +double_quote_subst='$double_quote_subst' +delay_variable_subst='$delay_variable_subst' +_LT_CONFIG_STATUS_DECLARATIONS +LTCC='$LTCC' +LTCFLAGS='$LTCFLAGS' +compiler='$compiler_DEFAULT' + +# A function that is used when there is no print builtin or printf. +func_fallback_echo () +{ + eval 'cat <<_LTECHO_EOF +\$[]1 +_LTECHO_EOF' +} + +# Quote evaled strings. +for var in lt_decl_all_varnames([[ \ +]], lt_decl_quote_varnames); do + case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in + *[[\\\\\\\`\\"\\\$]]*) + eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ## exclude from sc_prohibit_nested_quotes + ;; + *) + eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" + ;; + esac +done + +# Double-quote double-evaled strings. +for var in lt_decl_all_varnames([[ \ +]], lt_decl_dquote_varnames); do + case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in + *[[\\\\\\\`\\"\\\$]]*) + eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ## exclude from sc_prohibit_nested_quotes + ;; + *) + eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" + ;; + esac +done + +_LT_OUTPUT_LIBTOOL_INIT +]) + +# _LT_GENERATED_FILE_INIT(FILE, [COMMENT]) +# ------------------------------------ +# Generate a child script FILE with all initialization necessary to +# reuse the environment learned by the parent script, and make the +# file executable. If COMMENT is supplied, it is inserted after the +# '#!' sequence but before initialization text begins. After this +# macro, additional text can be appended to FILE to form the body of +# the child script. The macro ends with non-zero status if the +# file could not be fully written (such as if the disk is full). +m4_ifdef([AS_INIT_GENERATED], +[m4_defun([_LT_GENERATED_FILE_INIT],[AS_INIT_GENERATED($@)])], +[m4_defun([_LT_GENERATED_FILE_INIT], +[m4_require([AS_PREPARE])]dnl +[m4_pushdef([AS_MESSAGE_LOG_FD])]dnl +[lt_write_fail=0 +cat >$1 <<_ASEOF || lt_write_fail=1 +#! $SHELL +# Generated by $as_me. +$2 +SHELL=\${CONFIG_SHELL-$SHELL} +export SHELL +_ASEOF +cat >>$1 <<\_ASEOF || lt_write_fail=1 +AS_SHELL_SANITIZE +_AS_PREPARE +exec AS_MESSAGE_FD>&1 +_ASEOF +test 0 = "$lt_write_fail" && chmod +x $1[]dnl +m4_popdef([AS_MESSAGE_LOG_FD])])])# _LT_GENERATED_FILE_INIT + +# LT_OUTPUT +# --------- +# This macro allows early generation of the libtool script (before +# AC_OUTPUT is called), incase it is used in configure for compilation +# tests. +AC_DEFUN([LT_OUTPUT], +[: ${CONFIG_LT=./config.lt} +AC_MSG_NOTICE([creating $CONFIG_LT]) +_LT_GENERATED_FILE_INIT(["$CONFIG_LT"], +[# Run this file to recreate a libtool stub with the current configuration.]) + +cat >>"$CONFIG_LT" <<\_LTEOF +lt_cl_silent=false +exec AS_MESSAGE_LOG_FD>>config.log +{ + echo + AS_BOX([Running $as_me.]) +} >&AS_MESSAGE_LOG_FD + +lt_cl_help="\ +'$as_me' creates a local libtool stub from the current configuration, +for use in further configure time tests before the real libtool is +generated. + +Usage: $[0] [[OPTIONS]] + + -h, --help print this help, then exit + -V, --version print version number, then exit + -q, --quiet do not print progress messages + -d, --debug don't remove temporary files + +Report bugs to ." + +lt_cl_version="\ +m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl +m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION]) +configured by $[0], generated by m4_PACKAGE_STRING. + +Copyright (C) 2011 Free Software Foundation, Inc. +This config.lt script is free software; the Free Software Foundation +gives unlimited permision to copy, distribute and modify it." + +while test 0 != $[#] +do + case $[1] in + --version | --v* | -V ) + echo "$lt_cl_version"; exit 0 ;; + --help | --h* | -h ) + echo "$lt_cl_help"; exit 0 ;; + --debug | --d* | -d ) + debug=: ;; + --quiet | --q* | --silent | --s* | -q ) + lt_cl_silent=: ;; + + -*) AC_MSG_ERROR([unrecognized option: $[1] +Try '$[0] --help' for more information.]) ;; + + *) AC_MSG_ERROR([unrecognized argument: $[1] +Try '$[0] --help' for more information.]) ;; + esac + shift +done + +if $lt_cl_silent; then + exec AS_MESSAGE_FD>/dev/null +fi +_LTEOF + +cat >>"$CONFIG_LT" <<_LTEOF +_LT_OUTPUT_LIBTOOL_COMMANDS_INIT +_LTEOF + +cat >>"$CONFIG_LT" <<\_LTEOF +AC_MSG_NOTICE([creating $ofile]) +_LT_OUTPUT_LIBTOOL_COMMANDS +AS_EXIT(0) +_LTEOF +chmod +x "$CONFIG_LT" + +# configure is writing to config.log, but config.lt does its own redirection, +# appending to config.log, which fails on DOS, as config.log is still kept +# open by configure. Here we exec the FD to /dev/null, effectively closing +# config.log, so it can be properly (re)opened and appended to by config.lt. +lt_cl_success=: +test yes = "$silent" && + lt_config_lt_args="$lt_config_lt_args --quiet" +exec AS_MESSAGE_LOG_FD>/dev/null +$SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false +exec AS_MESSAGE_LOG_FD>>config.log +$lt_cl_success || AS_EXIT(1) +])# LT_OUTPUT + + +# _LT_CONFIG(TAG) +# --------------- +# If TAG is the built-in tag, create an initial libtool script with a +# default configuration from the untagged config vars. Otherwise add code +# to config.status for appending the configuration named by TAG from the +# matching tagged config vars. +m4_defun([_LT_CONFIG], +[m4_require([_LT_FILEUTILS_DEFAULTS])dnl +_LT_CONFIG_SAVE_COMMANDS([ + m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl + m4_if(_LT_TAG, [C], [ + # See if we are running on zsh, and set the options that allow our + # commands through without removal of \ escapes. + if test -n "${ZSH_VERSION+set}"; then + setopt NO_GLOB_SUBST + fi + + cfgfile=${ofile}T + trap "$RM \"$cfgfile\"; exit 1" 1 2 15 + $RM "$cfgfile" + + cat <<_LT_EOF >> "$cfgfile" +#! $SHELL +# Generated automatically by $as_me ($PACKAGE) $VERSION +# NOTE: Changes made to this file will be lost: look at ltmain.sh. + +# Provide generalized library-building support services. +# Written by Gordon Matzigkeit, 1996 + +_LT_COPYING +_LT_LIBTOOL_TAGS + +# Configured defaults for sys_lib_dlsearch_path munging. +: \${LT_SYS_LIBRARY_PATH="$configure_time_lt_sys_library_path"} + +# ### BEGIN LIBTOOL CONFIG +_LT_LIBTOOL_CONFIG_VARS +_LT_LIBTOOL_TAG_VARS +# ### END LIBTOOL CONFIG + +_LT_EOF + + cat <<'_LT_EOF' >> "$cfgfile" + +# ### BEGIN FUNCTIONS SHARED WITH CONFIGURE + +_LT_PREPARE_MUNGE_PATH_LIST +_LT_PREPARE_CC_BASENAME + +# ### END FUNCTIONS SHARED WITH CONFIGURE + +_LT_EOF + + case $host_os in + aix3*) + cat <<\_LT_EOF >> "$cfgfile" +# AIX sometimes has problems with the GCC collect2 program. For some +# reason, if we set the COLLECT_NAMES environment variable, the problems +# vanish in a puff of smoke. +if test set != "${COLLECT_NAMES+set}"; then + COLLECT_NAMES= + export COLLECT_NAMES +fi +_LT_EOF + ;; + esac + + _LT_PROG_LTMAIN + + # We use sed instead of cat because bash on DJGPP gets confused if + # if finds mixed CR/LF and LF-only lines. Since sed operates in + # text mode, it properly converts lines to CR/LF. This bash problem + # is reportedly fixed, but why not run on old versions too? + $SED '$q' "$ltmain" >> "$cfgfile" \ + || (rm -f "$cfgfile"; exit 1) + + mv -f "$cfgfile" "$ofile" || + (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") + chmod +x "$ofile" +], +[cat <<_LT_EOF >> "$ofile" + +dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded +dnl in a comment (ie after a #). +# ### BEGIN LIBTOOL TAG CONFIG: $1 +_LT_LIBTOOL_TAG_VARS(_LT_TAG) +# ### END LIBTOOL TAG CONFIG: $1 +_LT_EOF +])dnl /m4_if +], +[m4_if([$1], [], [ + PACKAGE='$PACKAGE' + VERSION='$VERSION' + RM='$RM' + ofile='$ofile'], []) +])dnl /_LT_CONFIG_SAVE_COMMANDS +])# _LT_CONFIG + + +# LT_SUPPORTED_TAG(TAG) +# --------------------- +# Trace this macro to discover what tags are supported by the libtool +# --tag option, using: +# autoconf --trace 'LT_SUPPORTED_TAG:$1' +AC_DEFUN([LT_SUPPORTED_TAG], []) + + +# C support is built-in for now +m4_define([_LT_LANG_C_enabled], []) +m4_define([_LT_TAGS], []) + + +# LT_LANG(LANG) +# ------------- +# Enable libtool support for the given language if not already enabled. +AC_DEFUN([LT_LANG], +[AC_BEFORE([$0], [LT_OUTPUT])dnl +m4_case([$1], + [C], [_LT_LANG(C)], + [C++], [_LT_LANG(CXX)], + [Go], [_LT_LANG(GO)], + [Java], [_LT_LANG(GCJ)], + [Fortran 77], [_LT_LANG(F77)], + [Fortran], [_LT_LANG(FC)], + [Windows Resource], [_LT_LANG(RC)], + [m4_ifdef([_LT_LANG_]$1[_CONFIG], + [_LT_LANG($1)], + [m4_fatal([$0: unsupported language: "$1"])])])dnl +])# LT_LANG + + +# _LT_LANG(LANGNAME) +# ------------------ +m4_defun([_LT_LANG], +[m4_ifdef([_LT_LANG_]$1[_enabled], [], + [LT_SUPPORTED_TAG([$1])dnl + m4_append([_LT_TAGS], [$1 ])dnl + m4_define([_LT_LANG_]$1[_enabled], [])dnl + _LT_LANG_$1_CONFIG($1)])dnl +])# _LT_LANG + + +m4_ifndef([AC_PROG_GO], [ +############################################################ +# NOTE: This macro has been submitted for inclusion into # +# GNU Autoconf as AC_PROG_GO. When it is available in # +# a released version of Autoconf we should remove this # +# macro and use it instead. # +############################################################ +m4_defun([AC_PROG_GO], +[AC_LANG_PUSH(Go)dnl +AC_ARG_VAR([GOC], [Go compiler command])dnl +AC_ARG_VAR([GOFLAGS], [Go compiler flags])dnl +_AC_ARG_VAR_LDFLAGS()dnl +AC_CHECK_TOOL(GOC, gccgo) +if test -z "$GOC"; then + if test -n "$ac_tool_prefix"; then + AC_CHECK_PROG(GOC, [${ac_tool_prefix}gccgo], [${ac_tool_prefix}gccgo]) + fi +fi +if test -z "$GOC"; then + AC_CHECK_PROG(GOC, gccgo, gccgo, false) +fi +])#m4_defun +])#m4_ifndef + + +# _LT_LANG_DEFAULT_CONFIG +# ----------------------- +m4_defun([_LT_LANG_DEFAULT_CONFIG], +[AC_PROVIDE_IFELSE([AC_PROG_CXX], + [LT_LANG(CXX)], + [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])]) + +AC_PROVIDE_IFELSE([AC_PROG_F77], + [LT_LANG(F77)], + [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])]) + +AC_PROVIDE_IFELSE([AC_PROG_FC], + [LT_LANG(FC)], + [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])]) + +dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal +dnl pulling things in needlessly. +AC_PROVIDE_IFELSE([AC_PROG_GCJ], + [LT_LANG(GCJ)], + [AC_PROVIDE_IFELSE([A][M_PROG_GCJ], + [LT_LANG(GCJ)], + [AC_PROVIDE_IFELSE([LT_PROG_GCJ], + [LT_LANG(GCJ)], + [m4_ifdef([AC_PROG_GCJ], + [m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])]) + m4_ifdef([A][M_PROG_GCJ], + [m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])]) + m4_ifdef([LT_PROG_GCJ], + [m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])]) + +AC_PROVIDE_IFELSE([AC_PROG_GO], + [LT_LANG(GO)], + [m4_define([AC_PROG_GO], defn([AC_PROG_GO])[LT_LANG(GO)])]) + +AC_PROVIDE_IFELSE([LT_PROG_RC], + [LT_LANG(RC)], + [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])]) +])# _LT_LANG_DEFAULT_CONFIG + +# Obsolete macros: +AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)]) +AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)]) +AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)]) +AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)]) +AU_DEFUN([AC_LIBTOOL_RC], [LT_LANG(Windows Resource)]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_LIBTOOL_CXX], []) +dnl AC_DEFUN([AC_LIBTOOL_F77], []) +dnl AC_DEFUN([AC_LIBTOOL_FC], []) +dnl AC_DEFUN([AC_LIBTOOL_GCJ], []) +dnl AC_DEFUN([AC_LIBTOOL_RC], []) + + +# _LT_TAG_COMPILER +# ---------------- +m4_defun([_LT_TAG_COMPILER], +[AC_REQUIRE([AC_PROG_CC])dnl + +_LT_DECL([LTCC], [CC], [1], [A C compiler])dnl +_LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl +_LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl +_LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} + +# Allow CC to be a program name with arguments. +compiler=$CC +])# _LT_TAG_COMPILER + + +# _LT_COMPILER_BOILERPLATE +# ------------------------ +# Check for compiler boilerplate output or warnings with +# the simple compiler test code. +m4_defun([_LT_COMPILER_BOILERPLATE], +[m4_require([_LT_DECL_SED])dnl +ac_outfile=conftest.$ac_objext +echo "$lt_simple_compile_test_code" >conftest.$ac_ext +eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_compiler_boilerplate=`cat conftest.err` +$RM conftest* +])# _LT_COMPILER_BOILERPLATE + + +# _LT_LINKER_BOILERPLATE +# ---------------------- +# Check for linker boilerplate output or warnings with +# the simple link test code. +m4_defun([_LT_LINKER_BOILERPLATE], +[m4_require([_LT_DECL_SED])dnl +ac_outfile=conftest.$ac_objext +echo "$lt_simple_link_test_code" >conftest.$ac_ext +eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_linker_boilerplate=`cat conftest.err` +$RM -r conftest* +])# _LT_LINKER_BOILERPLATE + +# _LT_REQUIRED_DARWIN_CHECKS +# ------------------------- +m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[ + case $host_os in + rhapsody* | darwin*) + AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:]) + AC_CHECK_TOOL([NMEDIT], [nmedit], [:]) + AC_CHECK_TOOL([LIPO], [lipo], [:]) + AC_CHECK_TOOL([OTOOL], [otool], [:]) + AC_CHECK_TOOL([OTOOL64], [otool64], [:]) + _LT_DECL([], [DSYMUTIL], [1], + [Tool to manipulate archived DWARF debug symbol files on Mac OS X]) + _LT_DECL([], [NMEDIT], [1], + [Tool to change global to local symbols on Mac OS X]) + _LT_DECL([], [LIPO], [1], + [Tool to manipulate fat objects and archives on Mac OS X]) + _LT_DECL([], [OTOOL], [1], + [ldd/readelf like tool for Mach-O binaries on Mac OS X]) + _LT_DECL([], [OTOOL64], [1], + [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4]) + + AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod], + [lt_cv_apple_cc_single_mod=no + if test -z "$LT_MULTI_MODULE"; then + # By default we will add the -single_module flag. You can override + # by either setting the environment variable LT_MULTI_MODULE + # non-empty at configure time, or by adding -multi_module to the + # link flags. + rm -rf libconftest.dylib* + echo "int foo(void){return 1;}" > conftest.c + echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ +-dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD + $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ + -dynamiclib -Wl,-single_module conftest.c 2>conftest.err + _lt_result=$? + # If there is a non-empty error log, and "single_module" + # appears in it, assume the flag caused a linker warning + if test -s conftest.err && $GREP single_module conftest.err; then + cat conftest.err >&AS_MESSAGE_LOG_FD + # Otherwise, if the output was created with a 0 exit code from + # the compiler, it worked. + elif test -f libconftest.dylib && test 0 = "$_lt_result"; then + lt_cv_apple_cc_single_mod=yes + else + cat conftest.err >&AS_MESSAGE_LOG_FD + fi + rm -rf libconftest.dylib* + rm -f conftest.* + fi]) + + AC_CACHE_CHECK([for -exported_symbols_list linker flag], + [lt_cv_ld_exported_symbols_list], + [lt_cv_ld_exported_symbols_list=no + save_LDFLAGS=$LDFLAGS + echo "_main" > conftest.sym + LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" + AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], + [lt_cv_ld_exported_symbols_list=yes], + [lt_cv_ld_exported_symbols_list=no]) + LDFLAGS=$save_LDFLAGS + ]) + + AC_CACHE_CHECK([for -force_load linker flag],[lt_cv_ld_force_load], + [lt_cv_ld_force_load=no + cat > conftest.c << _LT_EOF +int forced_loaded() { return 2;} +_LT_EOF + echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&AS_MESSAGE_LOG_FD + $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&AS_MESSAGE_LOG_FD + echo "$AR $AR_FLAGS libconftest.a conftest.o" >&AS_MESSAGE_LOG_FD + $AR $AR_FLAGS libconftest.a conftest.o 2>&AS_MESSAGE_LOG_FD + echo "$RANLIB libconftest.a" >&AS_MESSAGE_LOG_FD + $RANLIB libconftest.a 2>&AS_MESSAGE_LOG_FD + cat > conftest.c << _LT_EOF +int main() { return 0;} +_LT_EOF + echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&AS_MESSAGE_LOG_FD + $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err + _lt_result=$? + if test -s conftest.err && $GREP force_load conftest.err; then + cat conftest.err >&AS_MESSAGE_LOG_FD + elif test -f conftest && test 0 = "$_lt_result" && $GREP forced_load conftest >/dev/null 2>&1; then + lt_cv_ld_force_load=yes + else + cat conftest.err >&AS_MESSAGE_LOG_FD + fi + rm -f conftest.err libconftest.a conftest conftest.c + rm -rf conftest.dSYM + ]) + case $host_os in + rhapsody* | darwin1.[[012]]) + _lt_dar_allow_undefined='$wl-undefined ${wl}suppress' ;; + darwin1.*) + _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;; + darwin*) + case $MACOSX_DEPLOYMENT_TARGET,$host in + 10.[[012]],*|,*powerpc*-darwin[[5-8]]*) + _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;; + *) + _lt_dar_allow_undefined='$wl-undefined ${wl}dynamic_lookup' ;; + esac + ;; + esac + if test yes = "$lt_cv_apple_cc_single_mod"; then + _lt_dar_single_mod='$single_module' + fi + if test yes = "$lt_cv_ld_exported_symbols_list"; then + _lt_dar_export_syms=' $wl-exported_symbols_list,$output_objdir/$libname-symbols.expsym' + else + _lt_dar_export_syms='~$NMEDIT -s $output_objdir/$libname-symbols.expsym $lib' + fi + if test : != "$DSYMUTIL" && test no = "$lt_cv_ld_force_load"; then + _lt_dsymutil='~$DSYMUTIL $lib || :' + else + _lt_dsymutil= + fi + ;; + esac +]) + + +# _LT_DARWIN_LINKER_FEATURES([TAG]) +# --------------------------------- +# Checks for linker and compiler features on darwin +m4_defun([_LT_DARWIN_LINKER_FEATURES], +[ + m4_require([_LT_REQUIRED_DARWIN_CHECKS]) + _LT_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_TAGVAR(hardcode_direct, $1)=no + _LT_TAGVAR(hardcode_automatic, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported + if test yes = "$lt_cv_ld_force_load"; then + _LT_TAGVAR(whole_archive_flag_spec, $1)='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience $wl-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' + m4_case([$1], [F77], [_LT_TAGVAR(compiler_needs_object, $1)=yes], + [FC], [_LT_TAGVAR(compiler_needs_object, $1)=yes]) + else + _LT_TAGVAR(whole_archive_flag_spec, $1)='' + fi + _LT_TAGVAR(link_all_deplibs, $1)=yes + _LT_TAGVAR(allow_undefined_flag, $1)=$_lt_dar_allow_undefined + case $cc_basename in + ifort*|nagfor*) _lt_dar_can_shared=yes ;; + *) _lt_dar_can_shared=$GCC ;; + esac + if test yes = "$_lt_dar_can_shared"; then + output_verbose_link_cmd=func_echo_all + _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dsymutil" + _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dsymutil" + _LT_TAGVAR(archive_expsym_cmds, $1)="$SED 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dar_export_syms$_lt_dsymutil" + _LT_TAGVAR(module_expsym_cmds, $1)="$SED -e 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dar_export_syms$_lt_dsymutil" + m4_if([$1], [CXX], +[ if test yes != "$lt_cv_apple_cc_single_mod"; then + _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \$lib-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$lib-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring$_lt_dsymutil" + _LT_TAGVAR(archive_expsym_cmds, $1)="$SED 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \$lib-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$lib-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring$_lt_dar_export_syms$_lt_dsymutil" + fi +],[]) + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi +]) + +# _LT_SYS_MODULE_PATH_AIX([TAGNAME]) +# ---------------------------------- +# Links a minimal program and checks the executable +# for the system default hardcoded library path. In most cases, +# this is /usr/lib:/lib, but when the MPI compilers are used +# the location of the communication and MPI libs are included too. +# If we don't find anything, use the default library path according +# to the aix ld manual. +# Store the results from the different compilers for each TAGNAME. +# Allow to override them for all tags through lt_cv_aix_libpath. +m4_defun([_LT_SYS_MODULE_PATH_AIX], +[m4_require([_LT_DECL_SED])dnl +if test set = "${lt_cv_aix_libpath+set}"; then + aix_libpath=$lt_cv_aix_libpath +else + AC_CACHE_VAL([_LT_TAGVAR([lt_cv_aix_libpath_], [$1])], + [AC_LINK_IFELSE([AC_LANG_PROGRAM],[ + lt_aix_libpath_sed='[ + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\([^ ]*\) *$/\1/ + p + } + }]' + _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` + # Check for a 64-bit object if we didn't find anything. + if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then + _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` + fi],[]) + if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then + _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=/usr/lib:/lib + fi + ]) + aix_libpath=$_LT_TAGVAR([lt_cv_aix_libpath_], [$1]) +fi +])# _LT_SYS_MODULE_PATH_AIX + + +# _LT_SHELL_INIT(ARG) +# ------------------- +m4_define([_LT_SHELL_INIT], +[m4_divert_text([M4SH-INIT], [$1 +])])# _LT_SHELL_INIT + + + +# _LT_PROG_ECHO_BACKSLASH +# ----------------------- +# Find how we can fake an echo command that does not interpret backslash. +# In particular, with Autoconf 2.60 or later we add some code to the start +# of the generated configure script that will find a shell with a builtin +# printf (that we can use as an echo command). +m4_defun([_LT_PROG_ECHO_BACKSLASH], +[ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO +ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO + +AC_MSG_CHECKING([how to print strings]) +# Test print first, because it will be a builtin if present. +if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ + test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then + ECHO='print -r --' +elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then + ECHO='printf %s\n' +else + # Use this function as a fallback that always works. + func_fallback_echo () + { + eval 'cat <<_LTECHO_EOF +$[]1 +_LTECHO_EOF' + } + ECHO='func_fallback_echo' +fi + +# func_echo_all arg... +# Invoke $ECHO with all args, space-separated. +func_echo_all () +{ + $ECHO "$*" +} + +case $ECHO in + printf*) AC_MSG_RESULT([printf]) ;; + print*) AC_MSG_RESULT([print -r]) ;; + *) AC_MSG_RESULT([cat]) ;; +esac + +m4_ifdef([_AS_DETECT_SUGGESTED], +[_AS_DETECT_SUGGESTED([ + test -n "${ZSH_VERSION+set}${BASH_VERSION+set}" || ( + ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' + ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO + ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO + PATH=/empty FPATH=/empty; export PATH FPATH + test "X`printf %s $ECHO`" = "X$ECHO" \ + || test "X`print -r -- $ECHO`" = "X$ECHO" )])]) + +_LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts]) +_LT_DECL([], [ECHO], [1], [An echo program that protects backslashes]) +])# _LT_PROG_ECHO_BACKSLASH + + +# _LT_WITH_SYSROOT +# ---------------- +AC_DEFUN([_LT_WITH_SYSROOT], +[m4_require([_LT_DECL_SED])dnl +AC_MSG_CHECKING([for sysroot]) +AC_ARG_WITH([sysroot], +[AS_HELP_STRING([--with-sysroot@<:@=DIR@:>@], + [Search for dependent libraries within DIR (or the compiler's sysroot + if not specified).])], +[], [with_sysroot=no]) + +dnl lt_sysroot will always be passed unquoted. We quote it here +dnl in case the user passed a directory name. +lt_sysroot= +case $with_sysroot in #( + yes) + if test yes = "$GCC"; then + lt_sysroot=`$CC --print-sysroot 2>/dev/null` + fi + ;; #( + /*) + lt_sysroot=`echo "$with_sysroot" | $SED -e "$sed_quote_subst"` + ;; #( + no|'') + ;; #( + *) + AC_MSG_RESULT([$with_sysroot]) + AC_MSG_ERROR([The sysroot must be an absolute path.]) + ;; +esac + + AC_MSG_RESULT([${lt_sysroot:-no}]) +_LT_DECL([], [lt_sysroot], [0], [The root where to search for ]dnl +[dependent libraries, and where our libraries should be installed.])]) + +# _LT_ENABLE_LOCK +# --------------- +m4_defun([_LT_ENABLE_LOCK], +[AC_ARG_ENABLE([libtool-lock], + [AS_HELP_STRING([--disable-libtool-lock], + [avoid locking (might break parallel builds)])]) +test no = "$enable_libtool_lock" || enable_libtool_lock=yes + +# Some flags need to be propagated to the compiler or linker for good +# libtool support. +case $host in +ia64-*-hpux*) + # Find out what ABI is being produced by ac_compile, and set mode + # options accordingly. + echo 'int i;' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + case `$FILECMD conftest.$ac_objext` in + *ELF-32*) + HPUX_IA64_MODE=32 + ;; + *ELF-64*) + HPUX_IA64_MODE=64 + ;; + esac + fi + rm -rf conftest* + ;; +*-*-irix6*) + # Find out what ABI is being produced by ac_compile, and set linker + # options accordingly. + echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + if test yes = "$lt_cv_prog_gnu_ld"; then + case `$FILECMD conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -melf32bsmip" + ;; + *N32*) + LD="${LD-ld} -melf32bmipn32" + ;; + *64-bit*) + LD="${LD-ld} -melf64bmip" + ;; + esac + else + case `$FILECMD conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -32" + ;; + *N32*) + LD="${LD-ld} -n32" + ;; + *64-bit*) + LD="${LD-ld} -64" + ;; + esac + fi + fi + rm -rf conftest* + ;; + +mips64*-*linux*) + # Find out what ABI is being produced by ac_compile, and set linker + # options accordingly. + echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + emul=elf + case `$FILECMD conftest.$ac_objext` in + *32-bit*) + emul="${emul}32" + ;; + *64-bit*) + emul="${emul}64" + ;; + esac + case `$FILECMD conftest.$ac_objext` in + *MSB*) + emul="${emul}btsmip" + ;; + *LSB*) + emul="${emul}ltsmip" + ;; + esac + case `$FILECMD conftest.$ac_objext` in + *N32*) + emul="${emul}n32" + ;; + esac + LD="${LD-ld} -m $emul" + fi + rm -rf conftest* + ;; + +x86_64-*kfreebsd*-gnu|x86_64-*linux*|powerpc*-*linux*| \ +s390*-*linux*|s390*-*tpf*|sparc*-*linux*) + # Find out what ABI is being produced by ac_compile, and set linker + # options accordingly. Note that the listed cases only cover the + # situations where additional linker options are needed (such as when + # doing 32-bit compilation for a host where ld defaults to 64-bit, or + # vice versa); the common cases where no linker options are needed do + # not appear in the list. + echo 'int i;' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + case `$FILECMD conftest.o` in + *32-bit*) + case $host in + x86_64-*kfreebsd*-gnu) + LD="${LD-ld} -m elf_i386_fbsd" + ;; + x86_64-*linux*) + case `$FILECMD conftest.o` in + *x86-64*) + LD="${LD-ld} -m elf32_x86_64" + ;; + *) + LD="${LD-ld} -m elf_i386" + ;; + esac + ;; + powerpc64le-*linux*) + LD="${LD-ld} -m elf32lppclinux" + ;; + powerpc64-*linux*) + LD="${LD-ld} -m elf32ppclinux" + ;; + s390x-*linux*) + LD="${LD-ld} -m elf_s390" + ;; + sparc64-*linux*) + LD="${LD-ld} -m elf32_sparc" + ;; + esac + ;; + *64-bit*) + case $host in + x86_64-*kfreebsd*-gnu) + LD="${LD-ld} -m elf_x86_64_fbsd" + ;; + x86_64-*linux*) + LD="${LD-ld} -m elf_x86_64" + ;; + powerpcle-*linux*) + LD="${LD-ld} -m elf64lppc" + ;; + powerpc-*linux*) + LD="${LD-ld} -m elf64ppc" + ;; + s390*-*linux*|s390*-*tpf*) + LD="${LD-ld} -m elf64_s390" + ;; + sparc*-*linux*) + LD="${LD-ld} -m elf64_sparc" + ;; + esac + ;; + esac + fi + rm -rf conftest* + ;; + +*-*-sco3.2v5*) + # On SCO OpenServer 5, we need -belf to get full-featured binaries. + SAVE_CFLAGS=$CFLAGS + CFLAGS="$CFLAGS -belf" + AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf, + [AC_LANG_PUSH(C) + AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no]) + AC_LANG_POP]) + if test yes != "$lt_cv_cc_needs_belf"; then + # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf + CFLAGS=$SAVE_CFLAGS + fi + ;; +*-*solaris*) + # Find out what ABI is being produced by ac_compile, and set linker + # options accordingly. + echo 'int i;' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + case `$FILECMD conftest.o` in + *64-bit*) + case $lt_cv_prog_gnu_ld in + yes*) + case $host in + i?86-*-solaris*|x86_64-*-solaris*) + LD="${LD-ld} -m elf_x86_64" + ;; + sparc*-*-solaris*) + LD="${LD-ld} -m elf64_sparc" + ;; + esac + # GNU ld 2.21 introduced _sol2 emulations. Use them if available. + if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then + LD=${LD-ld}_sol2 + fi + ;; + *) + if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then + LD="${LD-ld} -64" + fi + ;; + esac + ;; + esac + fi + rm -rf conftest* + ;; +esac + +need_locks=$enable_libtool_lock +])# _LT_ENABLE_LOCK + + +# _LT_PROG_AR +# ----------- +m4_defun([_LT_PROG_AR], +[AC_CHECK_TOOLS(AR, [ar], false) +: ${AR=ar} +_LT_DECL([], [AR], [1], [The archiver]) + +# Use ARFLAGS variable as AR's operation code to sync the variable naming with +# Automake. If both AR_FLAGS and ARFLAGS are specified, AR_FLAGS should have +# higher priority because thats what people were doing historically (setting +# ARFLAGS for automake and AR_FLAGS for libtool). FIXME: Make the AR_FLAGS +# variable obsoleted/removed. + +test ${AR_FLAGS+y} || AR_FLAGS=${ARFLAGS-cr} +lt_ar_flags=$AR_FLAGS +_LT_DECL([], [lt_ar_flags], [0], [Flags to create an archive (by configure)]) + +# Make AR_FLAGS overridable by 'make ARFLAGS='. Don't try to run-time override +# by AR_FLAGS because that was never working and AR_FLAGS is about to die. +_LT_DECL([], [AR_FLAGS], [\@S|@{ARFLAGS-"\@S|@lt_ar_flags"}], + [Flags to create an archive]) + +AC_CACHE_CHECK([for archiver @FILE support], [lt_cv_ar_at_file], + [lt_cv_ar_at_file=no + AC_COMPILE_IFELSE([AC_LANG_PROGRAM], + [echo conftest.$ac_objext > conftest.lst + lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&AS_MESSAGE_LOG_FD' + AC_TRY_EVAL([lt_ar_try]) + if test 0 -eq "$ac_status"; then + # Ensure the archiver fails upon bogus file names. + rm -f conftest.$ac_objext libconftest.a + AC_TRY_EVAL([lt_ar_try]) + if test 0 -ne "$ac_status"; then + lt_cv_ar_at_file=@ + fi + fi + rm -f conftest.* libconftest.a + ]) + ]) + +if test no = "$lt_cv_ar_at_file"; then + archiver_list_spec= +else + archiver_list_spec=$lt_cv_ar_at_file +fi +_LT_DECL([], [archiver_list_spec], [1], + [How to feed a file listing to the archiver]) +])# _LT_PROG_AR + + +# _LT_CMD_OLD_ARCHIVE +# ------------------- +m4_defun([_LT_CMD_OLD_ARCHIVE], +[_LT_PROG_AR + +AC_CHECK_TOOL(STRIP, strip, :) +test -z "$STRIP" && STRIP=: +_LT_DECL([], [STRIP], [1], [A symbol stripping program]) + +AC_CHECK_TOOL(RANLIB, ranlib, :) +test -z "$RANLIB" && RANLIB=: +_LT_DECL([], [RANLIB], [1], + [Commands used to install an old-style archive]) + +# Determine commands to create old-style static archives. +old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' +old_postinstall_cmds='chmod 644 $oldlib' +old_postuninstall_cmds= + +if test -n "$RANLIB"; then + case $host_os in + bitrig* | openbsd*) + old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" + ;; + *) + old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" + ;; + esac + old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" +fi + +case $host_os in + darwin*) + lock_old_archive_extraction=yes ;; + *) + lock_old_archive_extraction=no ;; +esac +_LT_DECL([], [old_postinstall_cmds], [2]) +_LT_DECL([], [old_postuninstall_cmds], [2]) +_LT_TAGDECL([], [old_archive_cmds], [2], + [Commands used to build an old-style archive]) +_LT_DECL([], [lock_old_archive_extraction], [0], + [Whether to use a lock for old archive extraction]) +])# _LT_CMD_OLD_ARCHIVE + + +# _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, +# [OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE]) +# ---------------------------------------------------------------- +# Check whether the given compiler option works +AC_DEFUN([_LT_COMPILER_OPTION], +[m4_require([_LT_FILEUTILS_DEFAULTS])dnl +m4_require([_LT_DECL_SED])dnl +AC_CACHE_CHECK([$1], [$2], + [$2=no + m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4]) + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$3" ## exclude from sc_useless_quotes_in_assignment + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&AS_MESSAGE_LOG_FD + echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + $2=yes + fi + fi + $RM conftest* +]) + +if test yes = "[$]$2"; then + m4_if([$5], , :, [$5]) +else + m4_if([$6], , :, [$6]) +fi +])# _LT_COMPILER_OPTION + +# Old name: +AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], []) + + +# _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, +# [ACTION-SUCCESS], [ACTION-FAILURE]) +# ---------------------------------------------------- +# Check whether the given linker option works +AC_DEFUN([_LT_LINKER_OPTION], +[m4_require([_LT_FILEUTILS_DEFAULTS])dnl +m4_require([_LT_DECL_SED])dnl +AC_CACHE_CHECK([$1], [$2], + [$2=no + save_LDFLAGS=$LDFLAGS + LDFLAGS="$LDFLAGS $3" + echo "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The linker can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&AS_MESSAGE_LOG_FD + $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if diff conftest.exp conftest.er2 >/dev/null; then + $2=yes + fi + else + $2=yes + fi + fi + $RM -r conftest* + LDFLAGS=$save_LDFLAGS +]) + +if test yes = "[$]$2"; then + m4_if([$4], , :, [$4]) +else + m4_if([$5], , :, [$5]) +fi +])# _LT_LINKER_OPTION + +# Old name: +AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], []) + + +# LT_CMD_MAX_LEN +#--------------- +AC_DEFUN([LT_CMD_MAX_LEN], +[AC_REQUIRE([AC_CANONICAL_HOST])dnl +# find the maximum length of command line arguments +AC_MSG_CHECKING([the maximum length of command line arguments]) +AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl + i=0 + teststring=ABCD + + case $build_os in + msdosdjgpp*) + # On DJGPP, this test can blow up pretty badly due to problems in libc + # (any single argument exceeding 2000 bytes causes a buffer overrun + # during glob expansion). Even if it were fixed, the result of this + # check would be larger than it should be. + lt_cv_sys_max_cmd_len=12288; # 12K is about right + ;; + + gnu*) + # Under GNU Hurd, this test is not required because there is + # no limit to the length of command line arguments. + # Libtool will interpret -1 as no limit whatsoever + lt_cv_sys_max_cmd_len=-1; + ;; + + cygwin* | mingw* | cegcc*) + # On Win9x/ME, this test blows up -- it succeeds, but takes + # about 5 minutes as the teststring grows exponentially. + # Worse, since 9x/ME are not pre-emptively multitasking, + # you end up with a "frozen" computer, even though with patience + # the test eventually succeeds (with a max line length of 256k). + # Instead, let's just punt: use the minimum linelength reported by + # all of the supported platforms: 8192 (on NT/2K/XP). + lt_cv_sys_max_cmd_len=8192; + ;; + + mint*) + # On MiNT this can take a long time and run out of memory. + lt_cv_sys_max_cmd_len=8192; + ;; + + amigaos*) + # On AmigaOS with pdksh, this test takes hours, literally. + # So we just punt and use a minimum line length of 8192. + lt_cv_sys_max_cmd_len=8192; + ;; + + bitrig* | darwin* | dragonfly* | freebsd* | midnightbsd* | netbsd* | openbsd*) + # This has been around since 386BSD, at least. Likely further. + if test -x /sbin/sysctl; then + lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` + elif test -x /usr/sbin/sysctl; then + lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` + else + lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs + fi + # And add a safety zone + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` + ;; + + interix*) + # We know the value 262144 and hardcode it with a safety zone (like BSD) + lt_cv_sys_max_cmd_len=196608 + ;; + + os2*) + # The test takes a long time on OS/2. + lt_cv_sys_max_cmd_len=8192 + ;; + + osf*) + # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure + # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not + # nice to cause kernel panics so lets avoid the loop below. + # First set a reasonable default. + lt_cv_sys_max_cmd_len=16384 + # + if test -x /sbin/sysconfig; then + case `/sbin/sysconfig -q proc exec_disable_arg_limit` in + *1*) lt_cv_sys_max_cmd_len=-1 ;; + esac + fi + ;; + sco3.2v5*) + lt_cv_sys_max_cmd_len=102400 + ;; + sysv5* | sco5v6* | sysv4.2uw2*) + kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` + if test -n "$kargmax"; then + lt_cv_sys_max_cmd_len=`echo $kargmax | $SED 's/.*[[ ]]//'` + else + lt_cv_sys_max_cmd_len=32768 + fi + ;; + *) + lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` + if test -n "$lt_cv_sys_max_cmd_len" && \ + test undefined != "$lt_cv_sys_max_cmd_len"; then + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` + else + # Make teststring a little bigger before we do anything with it. + # a 1K string should be a reasonable start. + for i in 1 2 3 4 5 6 7 8; do + teststring=$teststring$teststring + done + SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} + # If test is not a shell built-in, we'll probably end up computing a + # maximum length that is only half of the actual maximum length, but + # we can't tell. + while { test X`env echo "$teststring$teststring" 2>/dev/null` \ + = "X$teststring$teststring"; } >/dev/null 2>&1 && + test 17 != "$i" # 1/2 MB should be enough + do + i=`expr $i + 1` + teststring=$teststring$teststring + done + # Only check the string length outside the loop. + lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` + teststring= + # Add a significant safety factor because C++ compilers can tack on + # massive amounts of additional arguments before passing them to the + # linker. It appears as though 1/2 is a usable value. + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` + fi + ;; + esac +]) +if test -n "$lt_cv_sys_max_cmd_len"; then + AC_MSG_RESULT($lt_cv_sys_max_cmd_len) +else + AC_MSG_RESULT(none) +fi +max_cmd_len=$lt_cv_sys_max_cmd_len +_LT_DECL([], [max_cmd_len], [0], + [What is the maximum length of a command?]) +])# LT_CMD_MAX_LEN + +# Old name: +AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], []) + + +# _LT_HEADER_DLFCN +# ---------------- +m4_defun([_LT_HEADER_DLFCN], +[AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl +])# _LT_HEADER_DLFCN + + +# _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE, +# ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING) +# ---------------------------------------------------------------- +m4_defun([_LT_TRY_DLOPEN_SELF], +[m4_require([_LT_HEADER_DLFCN])dnl +if test yes = "$cross_compiling"; then : + [$4] +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext <<_LT_EOF +[#line $LINENO "configure" +#include "confdefs.h" + +#if HAVE_DLFCN_H +#include +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +/* When -fvisibility=hidden is used, assume the code has been annotated + correspondingly for the symbols needed. */ +#if defined __GNUC__ && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) +int fnord () __attribute__((visibility("default"))); +#endif + +int fnord () { return 42; } +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else + { + if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + else puts (dlerror ()); + } + /* dlclose (self); */ + } + else + puts (dlerror ()); + + return status; +}] +_LT_EOF + if AC_TRY_EVAL(ac_link) && test -s "conftest$ac_exeext" 2>/dev/null; then + (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) $1 ;; + x$lt_dlneed_uscore) $2 ;; + x$lt_dlunknown|x*) $3 ;; + esac + else : + # compilation failed + $3 + fi +fi +rm -fr conftest* +])# _LT_TRY_DLOPEN_SELF + + +# LT_SYS_DLOPEN_SELF +# ------------------ +AC_DEFUN([LT_SYS_DLOPEN_SELF], +[m4_require([_LT_HEADER_DLFCN])dnl +if test yes != "$enable_dlopen"; then + enable_dlopen=unknown + enable_dlopen_self=unknown + enable_dlopen_self_static=unknown +else + lt_cv_dlopen=no + lt_cv_dlopen_libs= + + case $host_os in + beos*) + lt_cv_dlopen=load_add_on + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + ;; + + mingw* | pw32* | cegcc*) + lt_cv_dlopen=LoadLibrary + lt_cv_dlopen_libs= + ;; + + cygwin*) + lt_cv_dlopen=dlopen + lt_cv_dlopen_libs= + ;; + + darwin*) + # if libdl is installed we need to link against it + AC_CHECK_LIB([dl], [dlopen], + [lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl],[ + lt_cv_dlopen=dyld + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + ]) + ;; + + tpf*) + # Don't try to run any link tests for TPF. We know it's impossible + # because TPF is a cross-compiler, and we know how we open DSOs. + lt_cv_dlopen=dlopen + lt_cv_dlopen_libs= + lt_cv_dlopen_self=no + ;; + + *) + AC_CHECK_FUNC([shl_load], + [lt_cv_dlopen=shl_load], + [AC_CHECK_LIB([dld], [shl_load], + [lt_cv_dlopen=shl_load lt_cv_dlopen_libs=-ldld], + [AC_CHECK_FUNC([dlopen], + [lt_cv_dlopen=dlopen], + [AC_CHECK_LIB([dl], [dlopen], + [lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl], + [AC_CHECK_LIB([svld], [dlopen], + [lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-lsvld], + [AC_CHECK_LIB([dld], [dld_link], + [lt_cv_dlopen=dld_link lt_cv_dlopen_libs=-ldld]) + ]) + ]) + ]) + ]) + ]) + ;; + esac + + if test no = "$lt_cv_dlopen"; then + enable_dlopen=no + else + enable_dlopen=yes + fi + + case $lt_cv_dlopen in + dlopen) + save_CPPFLAGS=$CPPFLAGS + test yes = "$ac_cv_header_dlfcn_h" && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" + + save_LDFLAGS=$LDFLAGS + wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" + + save_LIBS=$LIBS + LIBS="$lt_cv_dlopen_libs $LIBS" + + AC_CACHE_CHECK([whether a program can dlopen itself], + lt_cv_dlopen_self, [dnl + _LT_TRY_DLOPEN_SELF( + lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes, + lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross) + ]) + + if test yes = "$lt_cv_dlopen_self"; then + wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" + AC_CACHE_CHECK([whether a statically linked program can dlopen itself], + lt_cv_dlopen_self_static, [dnl + _LT_TRY_DLOPEN_SELF( + lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes, + lt_cv_dlopen_self_static=no, lt_cv_dlopen_self_static=cross) + ]) + fi + + CPPFLAGS=$save_CPPFLAGS + LDFLAGS=$save_LDFLAGS + LIBS=$save_LIBS + ;; + esac + + case $lt_cv_dlopen_self in + yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; + *) enable_dlopen_self=unknown ;; + esac + + case $lt_cv_dlopen_self_static in + yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; + *) enable_dlopen_self_static=unknown ;; + esac +fi +_LT_DECL([dlopen_support], [enable_dlopen], [0], + [Whether dlopen is supported]) +_LT_DECL([dlopen_self], [enable_dlopen_self], [0], + [Whether dlopen of programs is supported]) +_LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0], + [Whether dlopen of statically linked programs is supported]) +])# LT_SYS_DLOPEN_SELF + +# Old name: +AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], []) + + +# _LT_COMPILER_C_O([TAGNAME]) +# --------------------------- +# Check to see if options -c and -o are simultaneously supported by compiler. +# This macro does not hard code the compiler like AC_PROG_CC_C_O. +m4_defun([_LT_COMPILER_C_O], +[m4_require([_LT_DECL_SED])dnl +m4_require([_LT_FILEUTILS_DEFAULTS])dnl +m4_require([_LT_TAG_COMPILER])dnl +AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext], + [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)], + [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no + $RM -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&AS_MESSAGE_LOG_FD + echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp + $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 + if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then + _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes + fi + fi + chmod u+w . 2>&AS_MESSAGE_LOG_FD + $RM conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files + $RM out/* && rmdir out + cd .. + $RM -r conftest + $RM conftest* +]) +_LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1], + [Does compiler simultaneously support -c and -o options?]) +])# _LT_COMPILER_C_O + + +# _LT_COMPILER_FILE_LOCKS([TAGNAME]) +# ---------------------------------- +# Check to see if we can do hard links to lock some files if needed +m4_defun([_LT_COMPILER_FILE_LOCKS], +[m4_require([_LT_ENABLE_LOCK])dnl +m4_require([_LT_FILEUTILS_DEFAULTS])dnl +_LT_COMPILER_C_O([$1]) + +hard_links=nottested +if test no = "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" && test no != "$need_locks"; then + # do not overwrite the value of need_locks provided by the user + AC_MSG_CHECKING([if we can lock with hard links]) + hard_links=yes + $RM conftest* + ln conftest.a conftest.b 2>/dev/null && hard_links=no + touch conftest.a + ln conftest.a conftest.b 2>&5 || hard_links=no + ln conftest.a conftest.b 2>/dev/null && hard_links=no + AC_MSG_RESULT([$hard_links]) + if test no = "$hard_links"; then + AC_MSG_WARN(['$CC' does not support '-c -o', so 'make -j' may be unsafe]) + need_locks=warn + fi +else + need_locks=no +fi +_LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?]) +])# _LT_COMPILER_FILE_LOCKS + + +# _LT_CHECK_OBJDIR +# ---------------- +m4_defun([_LT_CHECK_OBJDIR], +[AC_CACHE_CHECK([for objdir], [lt_cv_objdir], +[rm -f .libs 2>/dev/null +mkdir .libs 2>/dev/null +if test -d .libs; then + lt_cv_objdir=.libs +else + # MS-DOS does not allow filenames that begin with a dot. + lt_cv_objdir=_libs +fi +rmdir .libs 2>/dev/null]) +objdir=$lt_cv_objdir +_LT_DECL([], [objdir], [0], + [The name of the directory that contains temporary libtool files])dnl +m4_pattern_allow([LT_OBJDIR])dnl +AC_DEFINE_UNQUOTED([LT_OBJDIR], "$lt_cv_objdir/", + [Define to the sub-directory where libtool stores uninstalled libraries.]) +])# _LT_CHECK_OBJDIR + + +# _LT_LINKER_HARDCODE_LIBPATH([TAGNAME]) +# -------------------------------------- +# Check hardcoding attributes. +m4_defun([_LT_LINKER_HARDCODE_LIBPATH], +[AC_MSG_CHECKING([how to hardcode library paths into programs]) +_LT_TAGVAR(hardcode_action, $1)= +if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" || + test -n "$_LT_TAGVAR(runpath_var, $1)" || + test yes = "$_LT_TAGVAR(hardcode_automatic, $1)"; then + + # We can hardcode non-existent directories. + if test no != "$_LT_TAGVAR(hardcode_direct, $1)" && + # If the only mechanism to avoid hardcoding is shlibpath_var, we + # have to relink, otherwise we might link with an installed library + # when we should be linking with a yet-to-be-installed one + ## test no != "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" && + test no != "$_LT_TAGVAR(hardcode_minus_L, $1)"; then + # Linking always hardcodes the temporary library directory. + _LT_TAGVAR(hardcode_action, $1)=relink + else + # We can link without hardcoding, and we can hardcode nonexisting dirs. + _LT_TAGVAR(hardcode_action, $1)=immediate + fi +else + # We cannot hardcode anything, or else we can only hardcode existing + # directories. + _LT_TAGVAR(hardcode_action, $1)=unsupported +fi +AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)]) + +if test relink = "$_LT_TAGVAR(hardcode_action, $1)" || + test yes = "$_LT_TAGVAR(inherit_rpath, $1)"; then + # Fast installation is not supported + enable_fast_install=no +elif test yes = "$shlibpath_overrides_runpath" || + test no = "$enable_shared"; then + # Fast installation is not necessary + enable_fast_install=needless +fi +_LT_TAGDECL([], [hardcode_action], [0], + [How to hardcode a shared library path into an executable]) +])# _LT_LINKER_HARDCODE_LIBPATH + + +# _LT_CMD_STRIPLIB +# ---------------- +m4_defun([_LT_CMD_STRIPLIB], +[m4_require([_LT_DECL_EGREP]) +striplib= +old_striplib= +AC_MSG_CHECKING([whether stripping libraries is possible]) +if test -z "$STRIP"; then + AC_MSG_RESULT([no]) +else + if $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then + old_striplib="$STRIP --strip-debug" + striplib="$STRIP --strip-unneeded" + AC_MSG_RESULT([yes]) + else + case $host_os in + darwin*) + # FIXME - insert some real tests, host_os isn't really good enough + striplib="$STRIP -x" + old_striplib="$STRIP -S" + AC_MSG_RESULT([yes]) + ;; + freebsd*) + if $STRIP -V 2>&1 | $GREP "elftoolchain" >/dev/null; then + old_striplib="$STRIP --strip-debug" + striplib="$STRIP --strip-unneeded" + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + fi + ;; + *) + AC_MSG_RESULT([no]) + ;; + esac + fi +fi +_LT_DECL([], [old_striplib], [1], [Commands to strip libraries]) +_LT_DECL([], [striplib], [1]) +])# _LT_CMD_STRIPLIB + + +# _LT_PREPARE_MUNGE_PATH_LIST +# --------------------------- +# Make sure func_munge_path_list() is defined correctly. +m4_defun([_LT_PREPARE_MUNGE_PATH_LIST], +[[# func_munge_path_list VARIABLE PATH +# ----------------------------------- +# VARIABLE is name of variable containing _space_ separated list of +# directories to be munged by the contents of PATH, which is string +# having a format: +# "DIR[:DIR]:" +# string "DIR[ DIR]" will be prepended to VARIABLE +# ":DIR[:DIR]" +# string "DIR[ DIR]" will be appended to VARIABLE +# "DIRP[:DIRP]::[DIRA:]DIRA" +# string "DIRP[ DIRP]" will be prepended to VARIABLE and string +# "DIRA[ DIRA]" will be appended to VARIABLE +# "DIR[:DIR]" +# VARIABLE will be replaced by "DIR[ DIR]" +func_munge_path_list () +{ + case x@S|@2 in + x) + ;; + *:) + eval @S|@1=\"`$ECHO @S|@2 | $SED 's/:/ /g'` \@S|@@S|@1\" + ;; + x:*) + eval @S|@1=\"\@S|@@S|@1 `$ECHO @S|@2 | $SED 's/:/ /g'`\" + ;; + *::*) + eval @S|@1=\"\@S|@@S|@1\ `$ECHO @S|@2 | $SED -e 's/.*:://' -e 's/:/ /g'`\" + eval @S|@1=\"`$ECHO @S|@2 | $SED -e 's/::.*//' -e 's/:/ /g'`\ \@S|@@S|@1\" + ;; + *) + eval @S|@1=\"`$ECHO @S|@2 | $SED 's/:/ /g'`\" + ;; + esac +} +]])# _LT_PREPARE_PATH_LIST + + +# _LT_SYS_DYNAMIC_LINKER([TAG]) +# ----------------------------- +# PORTME Fill in your ld.so characteristics +m4_defun([_LT_SYS_DYNAMIC_LINKER], +[AC_REQUIRE([AC_CANONICAL_HOST])dnl +m4_require([_LT_DECL_EGREP])dnl +m4_require([_LT_FILEUTILS_DEFAULTS])dnl +m4_require([_LT_DECL_OBJDUMP])dnl +m4_require([_LT_DECL_SED])dnl +m4_require([_LT_CHECK_SHELL_FEATURES])dnl +m4_require([_LT_PREPARE_MUNGE_PATH_LIST])dnl +AC_MSG_CHECKING([dynamic linker characteristics]) +m4_if([$1], + [], [ +if test yes = "$GCC"; then + case $host_os in + darwin*) lt_awk_arg='/^libraries:/,/LR/' ;; + *) lt_awk_arg='/^libraries:/' ;; + esac + case $host_os in + mingw* | cegcc*) lt_sed_strip_eq='s|=\([[A-Za-z]]:\)|\1|g' ;; + *) lt_sed_strip_eq='s|=/|/|g' ;; + esac + lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` + case $lt_search_path_spec in + *\;*) + # if the path contains ";" then we assume it to be the separator + # otherwise default to the standard path separator (i.e. ":") - it is + # assumed that no part of a normal pathname contains ";" but that should + # okay in the real world where ";" in dirpaths is itself problematic. + lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'` + ;; + *) + lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"` + ;; + esac + # Ok, now we have the path, separated by spaces, we can step through it + # and add multilib dir if necessary... + lt_tmp_lt_search_path_spec= + lt_multi_os_dir=/`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` + # ...but if some path component already ends with the multilib dir we assume + # that all is fine and trust -print-search-dirs as is (GCC 4.2? or newer). + case "$lt_multi_os_dir; $lt_search_path_spec " in + "/; "* | "/.; "* | "/./; "* | *"$lt_multi_os_dir "* | *"$lt_multi_os_dir/ "*) + lt_multi_os_dir= + ;; + esac + for lt_sys_path in $lt_search_path_spec; do + if test -d "$lt_sys_path$lt_multi_os_dir"; then + lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path$lt_multi_os_dir" + elif test -n "$lt_multi_os_dir"; then + test -d "$lt_sys_path" && \ + lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" + fi + done + lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk ' +BEGIN {RS = " "; FS = "/|\n";} { + lt_foo = ""; + lt_count = 0; + for (lt_i = NF; lt_i > 0; lt_i--) { + if ($lt_i != "" && $lt_i != ".") { + if ($lt_i == "..") { + lt_count++; + } else { + if (lt_count == 0) { + lt_foo = "/" $lt_i lt_foo; + } else { + lt_count--; + } + } + } + } + if (lt_foo != "") { lt_freq[[lt_foo]]++; } + if (lt_freq[[lt_foo]] == 1) { print lt_foo; } +}'` + # AWK program above erroneously prepends '/' to C:/dos/paths + # for these hosts. + case $host_os in + mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ + $SED 's|/\([[A-Za-z]]:\)|\1|g'` ;; + esac + sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` +else + sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" +fi]) +library_names_spec= +libname_spec='lib$name' +soname_spec= +shrext_cmds=.so +postinstall_cmds= +postuninstall_cmds= +finish_cmds= +finish_eval= +shlibpath_var= +shlibpath_overrides_runpath=unknown +version_type=none +dynamic_linker="$host_os ld.so" +sys_lib_dlsearch_path_spec="/lib /usr/lib" +need_lib_prefix=unknown +hardcode_into_libs=no + +# when you set need_version to no, make sure it does not cause -set_version +# flags to be left without arguments +need_version=unknown + +AC_ARG_VAR([LT_SYS_LIBRARY_PATH], +[User-defined run-time library search path.]) + +case $host_os in +aix3*) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='$libname$release$shared_ext$versuffix $libname.a' + shlibpath_var=LIBPATH + + # AIX 3 has no versioning support, so we append a major version to the name. + soname_spec='$libname$release$shared_ext$major' + ;; + +aix[[4-9]]*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + hardcode_into_libs=yes + if test ia64 = "$host_cpu"; then + # AIX 5 supports IA64 + library_names_spec='$libname$release$shared_ext$major $libname$release$shared_ext$versuffix $libname$shared_ext' + shlibpath_var=LD_LIBRARY_PATH + else + # With GCC up to 2.95.x, collect2 would create an import file + # for dependence libraries. The import file would start with + # the line '#! .'. This would cause the generated library to + # depend on '.', always an invalid library. This was fixed in + # development snapshots of GCC prior to 3.0. + case $host_os in + aix4 | aix4.[[01]] | aix4.[[01]].*) + if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' + echo ' yes ' + echo '#endif'; } | $CC -E - | $GREP yes > /dev/null; then + : + else + can_build_shared=no + fi + ;; + esac + # Using Import Files as archive members, it is possible to support + # filename-based versioning of shared library archives on AIX. While + # this would work for both with and without runtime linking, it will + # prevent static linking of such archives. So we do filename-based + # shared library versioning with .so extension only, which is used + # when both runtime linking and shared linking is enabled. + # Unfortunately, runtime linking may impact performance, so we do + # not want this to be the default eventually. Also, we use the + # versioned .so libs for executables only if there is the -brtl + # linker flag in LDFLAGS as well, or --with-aix-soname=svr4 only. + # To allow for filename-based versioning support, we need to create + # libNAME.so.V as an archive file, containing: + # *) an Import File, referring to the versioned filename of the + # archive as well as the shared archive member, telling the + # bitwidth (32 or 64) of that shared object, and providing the + # list of exported symbols of that shared object, eventually + # decorated with the 'weak' keyword + # *) the shared object with the F_LOADONLY flag set, to really avoid + # it being seen by the linker. + # At run time we better use the real file rather than another symlink, + # but for link time we create the symlink libNAME.so -> libNAME.so.V + + case $with_aix_soname,$aix_use_runtimelinking in + # AIX (on Power*) has no versioning support, so currently we cannot hardcode correct + # soname into executable. Probably we can add versioning support to + # collect2, so additional links can be useful in future. + aix,yes) # traditional libtool + dynamic_linker='AIX unversionable lib.so' + # If using run time linking (on AIX 4.2 or later) use lib.so + # instead of lib.a to let people know that these are not + # typical AIX shared libraries. + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + ;; + aix,no) # traditional AIX only + dynamic_linker='AIX lib.a[(]lib.so.V[)]' + # We preserve .a as extension for shared libraries through AIX4.2 + # and later when we are not doing run time linking. + library_names_spec='$libname$release.a $libname.a' + soname_spec='$libname$release$shared_ext$major' + ;; + svr4,*) # full svr4 only + dynamic_linker="AIX lib.so.V[(]$shared_archive_member_spec.o[)]" + library_names_spec='$libname$release$shared_ext$major $libname$shared_ext' + # We do not specify a path in Import Files, so LIBPATH fires. + shlibpath_overrides_runpath=yes + ;; + *,yes) # both, prefer svr4 + dynamic_linker="AIX lib.so.V[(]$shared_archive_member_spec.o[)], lib.a[(]lib.so.V[)]" + library_names_spec='$libname$release$shared_ext$major $libname$shared_ext' + # unpreferred sharedlib libNAME.a needs extra handling + postinstall_cmds='test -n "$linkname" || linkname="$realname"~func_stripname "" ".so" "$linkname"~$install_shared_prog "$dir/$func_stripname_result.$libext" "$destdir/$func_stripname_result.$libext"~test -z "$tstripme" || test -z "$striplib" || $striplib "$destdir/$func_stripname_result.$libext"' + postuninstall_cmds='for n in $library_names $old_library; do :; done~func_stripname "" ".so" "$n"~test "$func_stripname_result" = "$n" || func_append rmfiles " $odir/$func_stripname_result.$libext"' + # We do not specify a path in Import Files, so LIBPATH fires. + shlibpath_overrides_runpath=yes + ;; + *,no) # both, prefer aix + dynamic_linker="AIX lib.a[(]lib.so.V[)], lib.so.V[(]$shared_archive_member_spec.o[)]" + library_names_spec='$libname$release.a $libname.a' + soname_spec='$libname$release$shared_ext$major' + # unpreferred sharedlib libNAME.so.V and symlink libNAME.so need extra handling + postinstall_cmds='test -z "$dlname" || $install_shared_prog $dir/$dlname $destdir/$dlname~test -z "$tstripme" || test -z "$striplib" || $striplib $destdir/$dlname~test -n "$linkname" || linkname=$realname~func_stripname "" ".a" "$linkname"~(cd "$destdir" && $LN_S -f $dlname $func_stripname_result.so)' + postuninstall_cmds='test -z "$dlname" || func_append rmfiles " $odir/$dlname"~for n in $old_library $library_names; do :; done~func_stripname "" ".a" "$n"~func_append rmfiles " $odir/$func_stripname_result.so"' + ;; + esac + shlibpath_var=LIBPATH + fi + ;; + +amigaos*) + case $host_cpu in + powerpc) + # Since July 2007 AmigaOS4 officially supports .so libraries. + # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + ;; + m68k) + library_names_spec='$libname.ixlibrary $libname.a' + # Create ${libname}_ixlibrary.a entries in /sys/libs. + finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' + ;; + esac + ;; + +beos*) + library_names_spec='$libname$shared_ext' + dynamic_linker="$host_os ld.so" + shlibpath_var=LIBRARY_PATH + ;; + +bsdi[[45]]*) + version_type=linux # correct to gnu/linux during the next big refactor + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" + sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" + # the default ld.so.conf also contains /usr/contrib/lib and + # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow + # libtool to hard-code these into programs + ;; + +cygwin* | mingw* | pw32* | cegcc*) + version_type=windows + shrext_cmds=.dll + need_version=no + need_lib_prefix=no + + case $GCC,$cc_basename in + yes,*) + # gcc + library_names_spec='$libname.dll.a' + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \$file`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname~ + chmod a+x \$dldir/$dlname~ + if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then + eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; + fi' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $RM \$dlpath' + shlibpath_overrides_runpath=yes + + case $host_os in + cygwin*) + # Cygwin DLLs use 'cyg' prefix rather than 'lib' + soname_spec='`echo $libname | $SED -e 's/^lib/cyg/'``echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext' +m4_if([$1], [],[ + sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"]) + ;; + mingw* | cegcc*) + # MinGW DLLs use traditional 'lib' prefix + soname_spec='$libname`echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext' + ;; + pw32*) + # pw32 DLLs use 'pw' prefix rather than 'lib' + library_names_spec='`echo $libname | $SED -e 's/^lib/pw/'``echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext' + ;; + esac + dynamic_linker='Win32 ld.exe' + ;; + + *,cl* | *,icl*) + # Native MSVC or ICC + libname_spec='$name' + soname_spec='$libname`echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext' + library_names_spec='$libname.dll.lib' + + case $build_os in + mingw*) + sys_lib_search_path_spec= + lt_save_ifs=$IFS + IFS=';' + for lt_path in $LIB + do + IFS=$lt_save_ifs + # Let DOS variable expansion print the short 8.3 style file name. + lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` + sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" + done + IFS=$lt_save_ifs + # Convert to MSYS style. + sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's|\\\\|/|g' -e 's| \\([[a-zA-Z]]\\):| /\\1|g' -e 's|^ ||'` + ;; + cygwin*) + # Convert to unix form, then to dos form, then back to unix form + # but this time dos style (no spaces!) so that the unix form looks + # like /cygdrive/c/PROGRA~1:/cygdr... + sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` + sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` + sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + ;; + *) + sys_lib_search_path_spec=$LIB + if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then + # It is most probably a Windows format PATH. + sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + # FIXME: find the short name or the path components, as spaces are + # common. (e.g. "Program Files" -> "PROGRA~1") + ;; + esac + + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \$file`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $RM \$dlpath' + shlibpath_overrides_runpath=yes + dynamic_linker='Win32 link.exe' + ;; + + *) + # Assume MSVC and ICC wrapper + library_names_spec='$libname`echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext $libname.lib' + dynamic_linker='Win32 ld.exe' + ;; + esac + # FIXME: first we should search . and the directory the executable is in + shlibpath_var=PATH + ;; + +darwin* | rhapsody*) + dynamic_linker="$host_os dyld" + version_type=darwin + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$major$shared_ext $libname$shared_ext' + soname_spec='$libname$release$major$shared_ext' + shlibpath_overrides_runpath=yes + shlibpath_var=DYLD_LIBRARY_PATH + shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' +m4_if([$1], [],[ + sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"]) + sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' + ;; + +dgux*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +freebsd* | dragonfly* | midnightbsd*) + # DragonFly does not have aout. When/if they implement a new + # versioning mechanism, adjust this. + if test -x /usr/bin/objformat; then + objformat=`/usr/bin/objformat` + else + case $host_os in + freebsd[[23]].*) objformat=aout ;; + *) objformat=elf ;; + esac + fi + version_type=freebsd-$objformat + case $version_type in + freebsd-elf*) + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + need_version=no + need_lib_prefix=no + ;; + freebsd-*) + library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' + need_version=yes + ;; + esac + shlibpath_var=LD_LIBRARY_PATH + case $host_os in + freebsd2.*) + shlibpath_overrides_runpath=yes + ;; + freebsd3.[[01]]* | freebsdelf3.[[01]]*) + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \ + freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1) + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + *) # from 4.6 on, and DragonFly + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + esac + ;; + +haiku*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + dynamic_linker="$host_os runtime_loader" + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LIBRARY_PATH + shlibpath_overrides_runpath=no + sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' + hardcode_into_libs=yes + ;; + +hpux9* | hpux10* | hpux11*) + # Give a soname corresponding to the major version so that dld.sl refuses to + # link against other versions. + version_type=sunos + need_lib_prefix=no + need_version=no + case $host_cpu in + ia64*) + shrext_cmds='.so' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.so" + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + if test 32 = "$HPUX_IA64_MODE"; then + sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" + sys_lib_dlsearch_path_spec=/usr/lib/hpux32 + else + sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" + sys_lib_dlsearch_path_spec=/usr/lib/hpux64 + fi + ;; + hppa*64*) + shrext_cmds='.sl' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.sl" + shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + *) + shrext_cmds='.sl' + dynamic_linker="$host_os dld.sl" + shlibpath_var=SHLIB_PATH + shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + ;; + esac + # HP-UX runs *really* slowly unless shared libraries are mode 555, ... + postinstall_cmds='chmod 555 $lib' + # or fails outright, so override atomically: + install_override_mode=555 + ;; + +interix[[3-9]]*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +irix5* | irix6* | nonstopux*) + case $host_os in + nonstopux*) version_type=nonstopux ;; + *) + if test yes = "$lt_cv_prog_gnu_ld"; then + version_type=linux # correct to gnu/linux during the next big refactor + else + version_type=irix + fi ;; + esac + need_lib_prefix=no + need_version=no + soname_spec='$libname$release$shared_ext$major' + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$release$shared_ext $libname$shared_ext' + case $host_os in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in # libtool.m4 will add one of these switches to LD + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") + libsuff= shlibsuff= libmagic=32-bit;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") + libsuff=32 shlibsuff=N32 libmagic=N32;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") + libsuff=64 shlibsuff=64 libmagic=64-bit;; + *) libsuff= shlibsuff= libmagic=never-match;; + esac + ;; + esac + shlibpath_var=LD_LIBRARY${shlibsuff}_PATH + shlibpath_overrides_runpath=no + sys_lib_search_path_spec="/usr/lib$libsuff /lib$libsuff /usr/local/lib$libsuff" + sys_lib_dlsearch_path_spec="/usr/lib$libsuff /lib$libsuff" + hardcode_into_libs=yes + ;; + +# No shared lib support for Linux oldld, aout, or coff. +linux*oldld* | linux*aout* | linux*coff*) + dynamic_linker=no + ;; + +linux*android*) + version_type=none # Android doesn't support versioned libraries. + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext' + soname_spec='$libname$release$shared_ext' + finish_cmds= + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + + dynamic_linker='Android linker' + # Don't embed -rpath directories since the linker doesn't support them. + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + ;; + +# This must be glibc/ELF. +linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + + # Some binutils ld are patched to set DT_RUNPATH + AC_CACHE_VAL([lt_cv_shlibpath_overrides_runpath], + [lt_cv_shlibpath_overrides_runpath=no + save_LDFLAGS=$LDFLAGS + save_libdir=$libdir + eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \ + LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\"" + AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], + [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null], + [lt_cv_shlibpath_overrides_runpath=yes])]) + LDFLAGS=$save_LDFLAGS + libdir=$save_libdir + ]) + shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath + + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + + # Ideally, we could use ldconfig to report *all* directores which are + # searched for libraries, however this is still not possible. Aside from not + # being certain /sbin/ldconfig is available, command + # 'ldconfig -N -X -v | grep ^/' on 64bit Fedora does not report /usr/lib64, + # even though it is searched at run-time. Try to do the best guess by + # appending ld.so.conf contents (and includes) to the search path. + if test -f /etc/ld.so.conf; then + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" + fi + + # We used to test for /lib/ld.so.1 and disable shared libraries on + # powerpc, because MkLinux only supported shared libraries with the + # GNU dynamic linker. Since this was broken with cross compilers, + # most powerpc-linux boxes support dynamic linking these days and + # people can always --disable-shared, the test was removed, and we + # assume the GNU/Linux dynamic linker is in use. + dynamic_linker='GNU/Linux ld.so' + ;; + +netbsdelf*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='NetBSD ld.elf_so' + ;; + +netbsd*) + version_type=sunos + need_lib_prefix=no + need_version=no + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + dynamic_linker='NetBSD (a.out) ld.so' + else + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + dynamic_linker='NetBSD ld.elf_so' + fi + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + +newsos6) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +*nto* | *qnx*) + version_type=qnx + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='ldqnx.so' + ;; + +openbsd* | bitrig*) + version_type=sunos + sys_lib_dlsearch_path_spec=/usr/lib + need_lib_prefix=no + if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then + need_version=no + else + need_version=yes + fi + library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +os2*) + libname_spec='$name' + version_type=windows + shrext_cmds=.dll + need_version=no + need_lib_prefix=no + # OS/2 can only load a DLL with a base name of 8 characters or less. + soname_spec='`test -n "$os2dllname" && libname="$os2dllname"; + v=$($ECHO $release$versuffix | tr -d .-); + n=$($ECHO $libname | cut -b -$((8 - ${#v})) | tr . _); + $ECHO $n$v`$shared_ext' + library_names_spec='${libname}_dll.$libext' + dynamic_linker='OS/2 ld.exe' + shlibpath_var=BEGINLIBPATH + sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + postinstall_cmds='base_file=`basename \$file`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; $ECHO \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname~ + chmod a+x \$dldir/$dlname~ + if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then + eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; + fi' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; $ECHO \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $RM \$dlpath' + ;; + +osf3* | osf4* | osf5*) + version_type=osf + need_lib_prefix=no + need_version=no + soname_spec='$libname$release$shared_ext$major' + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + +rdos*) + dynamic_linker=no + ;; + +solaris*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + # ldd complains unless libraries are executable + postinstall_cmds='chmod +x $lib' + ;; + +sunos4*) + version_type=sunos + library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' + finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + if test yes = "$with_gnu_ld"; then + need_lib_prefix=no + fi + need_version=yes + ;; + +sysv4 | sysv4.3*) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + case $host_vendor in + sni) + shlibpath_overrides_runpath=no + need_lib_prefix=no + runpath_var=LD_RUN_PATH + ;; + siemens) + need_lib_prefix=no + ;; + motorola) + need_lib_prefix=no + need_version=no + shlibpath_overrides_runpath=no + sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' + ;; + esac + ;; + +sysv4*MP*) + if test -d /usr/nec; then + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='$libname$shared_ext.$versuffix $libname$shared_ext.$major $libname$shared_ext' + soname_spec='$libname$shared_ext.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + version_type=sco + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + if test yes = "$with_gnu_ld"; then + sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' + else + sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' + case $host_os in + sco3.2v5*) + sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" + ;; + esac + fi + sys_lib_dlsearch_path_spec='/usr/lib' + ;; + +tpf*) + # TPF is a cross-target only. Preferred cross-host = GNU/Linux. + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +uts4*) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +*) + dynamic_linker=no + ;; +esac +AC_MSG_RESULT([$dynamic_linker]) +test no = "$dynamic_linker" && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test yes = "$GCC"; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi + +if test set = "${lt_cv_sys_lib_search_path_spec+set}"; then + sys_lib_search_path_spec=$lt_cv_sys_lib_search_path_spec +fi + +if test set = "${lt_cv_sys_lib_dlsearch_path_spec+set}"; then + sys_lib_dlsearch_path_spec=$lt_cv_sys_lib_dlsearch_path_spec +fi + +# remember unaugmented sys_lib_dlsearch_path content for libtool script decls... +configure_time_dlsearch_path=$sys_lib_dlsearch_path_spec + +# ... but it needs LT_SYS_LIBRARY_PATH munging for other configure-time code +func_munge_path_list sys_lib_dlsearch_path_spec "$LT_SYS_LIBRARY_PATH" + +# to be used as default LT_SYS_LIBRARY_PATH value in generated libtool +configure_time_lt_sys_library_path=$LT_SYS_LIBRARY_PATH + +_LT_DECL([], [variables_saved_for_relink], [1], + [Variables whose values should be saved in libtool wrapper scripts and + restored at link time]) +_LT_DECL([], [need_lib_prefix], [0], + [Do we need the "lib" prefix for modules?]) +_LT_DECL([], [need_version], [0], [Do we need a version for libraries?]) +_LT_DECL([], [version_type], [0], [Library versioning type]) +_LT_DECL([], [runpath_var], [0], [Shared library runtime path variable]) +_LT_DECL([], [shlibpath_var], [0],[Shared library path variable]) +_LT_DECL([], [shlibpath_overrides_runpath], [0], + [Is shlibpath searched before the hard-coded library search path?]) +_LT_DECL([], [libname_spec], [1], [Format of library name prefix]) +_LT_DECL([], [library_names_spec], [1], + [[List of archive names. First name is the real one, the rest are links. + The last name is the one that the linker finds with -lNAME]]) +_LT_DECL([], [soname_spec], [1], + [[The coded name of the library, if different from the real name]]) +_LT_DECL([], [install_override_mode], [1], + [Permission mode override for installation of shared libraries]) +_LT_DECL([], [postinstall_cmds], [2], + [Command to use after installation of a shared archive]) +_LT_DECL([], [postuninstall_cmds], [2], + [Command to use after uninstallation of a shared archive]) +_LT_DECL([], [finish_cmds], [2], + [Commands used to finish a libtool library installation in a directory]) +_LT_DECL([], [finish_eval], [1], + [[As "finish_cmds", except a single script fragment to be evaled but + not shown]]) +_LT_DECL([], [hardcode_into_libs], [0], + [Whether we should hardcode library paths into libraries]) +_LT_DECL([], [sys_lib_search_path_spec], [2], + [Compile-time system search path for libraries]) +_LT_DECL([sys_lib_dlsearch_path_spec], [configure_time_dlsearch_path], [2], + [Detected run-time system search path for libraries]) +_LT_DECL([], [configure_time_lt_sys_library_path], [2], + [Explicit LT_SYS_LIBRARY_PATH set during ./configure time]) +])# _LT_SYS_DYNAMIC_LINKER + + +# _LT_PATH_TOOL_PREFIX(TOOL) +# -------------------------- +# find a file program that can recognize shared library +AC_DEFUN([_LT_PATH_TOOL_PREFIX], +[m4_require([_LT_DECL_EGREP])dnl +AC_MSG_CHECKING([for $1]) +AC_CACHE_VAL(lt_cv_path_MAGIC_CMD, +[case $MAGIC_CMD in +[[\\/*] | ?:[\\/]*]) + lt_cv_path_MAGIC_CMD=$MAGIC_CMD # Let the user override the test with a path. + ;; +*) + lt_save_MAGIC_CMD=$MAGIC_CMD + lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR +dnl $ac_dummy forces splitting on constant user-supplied paths. +dnl POSIX.2 word splitting is done only on the output of word expansions, +dnl not every word. This closes a longstanding sh security hole. + ac_dummy="m4_if([$2], , $PATH, [$2])" + for ac_dir in $ac_dummy; do + IFS=$lt_save_ifs + test -z "$ac_dir" && ac_dir=. + if test -f "$ac_dir/$1"; then + lt_cv_path_MAGIC_CMD=$ac_dir/"$1" + if test -n "$file_magic_test_file"; then + case $deplibs_check_method in + "file_magic "*) + file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` + MAGIC_CMD=$lt_cv_path_MAGIC_CMD + if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | + $EGREP "$file_magic_regex" > /dev/null; then + : + else + cat <<_LT_EOF 1>&2 + +*** Warning: the command libtool uses to detect shared libraries, +*** $file_magic_cmd, produces output that libtool cannot recognize. +*** The result is that libtool may fail to recognize shared libraries +*** as such. This will affect the creation of libtool libraries that +*** depend on shared libraries, but programs linked with such libtool +*** libraries will work regardless of this problem. Nevertheless, you +*** may want to report the problem to your system manager and/or to +*** bug-libtool@gnu.org + +_LT_EOF + fi ;; + esac + fi + break + fi + done + IFS=$lt_save_ifs + MAGIC_CMD=$lt_save_MAGIC_CMD + ;; +esac]) +MAGIC_CMD=$lt_cv_path_MAGIC_CMD +if test -n "$MAGIC_CMD"; then + AC_MSG_RESULT($MAGIC_CMD) +else + AC_MSG_RESULT(no) +fi +_LT_DECL([], [MAGIC_CMD], [0], + [Used to examine libraries when file_magic_cmd begins with "file"])dnl +])# _LT_PATH_TOOL_PREFIX + +# Old name: +AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], []) + + +# _LT_PATH_MAGIC +# -------------- +# find a file program that can recognize a shared library +m4_defun([_LT_PATH_MAGIC], +[_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH) +if test -z "$lt_cv_path_MAGIC_CMD"; then + if test -n "$ac_tool_prefix"; then + _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH) + else + MAGIC_CMD=: + fi +fi +])# _LT_PATH_MAGIC + + +# LT_PATH_LD +# ---------- +# find the pathname to the GNU or non-GNU linker +AC_DEFUN([LT_PATH_LD], +[AC_REQUIRE([AC_PROG_CC])dnl +AC_REQUIRE([AC_CANONICAL_HOST])dnl +AC_REQUIRE([AC_CANONICAL_BUILD])dnl +m4_require([_LT_DECL_SED])dnl +m4_require([_LT_DECL_EGREP])dnl +m4_require([_LT_PROG_ECHO_BACKSLASH])dnl + +AC_ARG_WITH([gnu-ld], + [AS_HELP_STRING([--with-gnu-ld], + [assume the C compiler uses GNU ld @<:@default=no@:>@])], + [test no = "$withval" || with_gnu_ld=yes], + [with_gnu_ld=no])dnl + +ac_prog=ld +if test yes = "$GCC"; then + # Check if gcc -print-prog-name=ld gives a path. + AC_MSG_CHECKING([for ld used by $CC]) + case $host in + *-*-mingw*) + # gcc leaves a trailing carriage return, which upsets mingw + ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; + *) + ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; + esac + case $ac_prog in + # Accept absolute paths. + [[\\/]]* | ?:[[\\/]]*) + re_direlt='/[[^/]][[^/]]*/\.\./' + # Canonicalize the pathname of ld + ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` + while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do + ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` + done + test -z "$LD" && LD=$ac_prog + ;; + "") + # If it fails, then pretend we aren't using GCC. + ac_prog=ld + ;; + *) + # If it is relative, then search for the first ld in PATH. + with_gnu_ld=unknown + ;; + esac +elif test yes = "$with_gnu_ld"; then + AC_MSG_CHECKING([for GNU ld]) +else + AC_MSG_CHECKING([for non-GNU ld]) +fi +AC_CACHE_VAL(lt_cv_path_LD, +[if test -z "$LD"; then + lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR + for ac_dir in $PATH; do + IFS=$lt_save_ifs + test -z "$ac_dir" && ac_dir=. + if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then + lt_cv_path_LD=$ac_dir/$ac_prog + # Check to see if the program is GNU ld. I'd rather use --version, + # but apparently some variants of GNU ld only accept -v. + # Break only if it was the GNU/non-GNU ld that we prefer. + case `"$lt_cv_path_LD" -v 2>&1 &1 conftest.i +cat conftest.i conftest.i >conftest2.i +: ${lt_DD:=$DD} +AC_PATH_PROGS_FEATURE_CHECK([lt_DD], [dd], +[if "$ac_path_lt_DD" bs=32 count=1 conftest.out 2>/dev/null; then + cmp -s conftest.i conftest.out \ + && ac_cv_path_lt_DD="$ac_path_lt_DD" ac_path_lt_DD_found=: +fi]) +rm -f conftest.i conftest2.i conftest.out]) +])# _LT_PATH_DD + + +# _LT_CMD_TRUNCATE +# ---------------- +# find command to truncate a binary pipe +m4_defun([_LT_CMD_TRUNCATE], +[m4_require([_LT_PATH_DD]) +AC_CACHE_CHECK([how to truncate binary pipes], [lt_cv_truncate_bin], +[printf 0123456789abcdef0123456789abcdef >conftest.i +cat conftest.i conftest.i >conftest2.i +lt_cv_truncate_bin= +if "$ac_cv_path_lt_DD" bs=32 count=1 conftest.out 2>/dev/null; then + cmp -s conftest.i conftest.out \ + && lt_cv_truncate_bin="$ac_cv_path_lt_DD bs=4096 count=1" +fi +rm -f conftest.i conftest2.i conftest.out +test -z "$lt_cv_truncate_bin" && lt_cv_truncate_bin="$SED -e 4q"]) +_LT_DECL([lt_truncate_bin], [lt_cv_truncate_bin], [1], + [Command to truncate a binary pipe]) +])# _LT_CMD_TRUNCATE + + +# _LT_CHECK_MAGIC_METHOD +# ---------------------- +# how to check for library dependencies +# -- PORTME fill in with the dynamic library characteristics +m4_defun([_LT_CHECK_MAGIC_METHOD], +[m4_require([_LT_DECL_EGREP]) +m4_require([_LT_DECL_OBJDUMP]) +AC_CACHE_CHECK([how to recognize dependent libraries], +lt_cv_deplibs_check_method, +[lt_cv_file_magic_cmd='$MAGIC_CMD' +lt_cv_file_magic_test_file= +lt_cv_deplibs_check_method='unknown' +# Need to set the preceding variable on all platforms that support +# interlibrary dependencies. +# 'none' -- dependencies not supported. +# 'unknown' -- same as none, but documents that we really don't know. +# 'pass_all' -- all dependencies passed with no checks. +# 'test_compile' -- check by making test program. +# 'file_magic [[regex]]' -- check by looking for files in library path +# that responds to the $file_magic_cmd with a given extended regex. +# If you have 'file' or equivalent on your system and you're not sure +# whether 'pass_all' will *always* work, you probably want this one. + +case $host_os in +aix[[4-9]]*) + lt_cv_deplibs_check_method=pass_all + ;; + +beos*) + lt_cv_deplibs_check_method=pass_all + ;; + +bsdi[[45]]*) + lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib)' + lt_cv_file_magic_cmd='$FILECMD -L' + lt_cv_file_magic_test_file=/shlib/libc.so + ;; + +cygwin*) + # func_win32_libid is a shell function defined in ltmain.sh + lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' + lt_cv_file_magic_cmd='func_win32_libid' + ;; + +mingw* | pw32*) + # Base MSYS/MinGW do not provide the 'file' command needed by + # func_win32_libid shell function, so use a weaker test based on 'objdump', + # unless we find 'file', for example because we are cross-compiling. + if ( file / ) >/dev/null 2>&1; then + lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' + lt_cv_file_magic_cmd='func_win32_libid' + else + # Keep this pattern in sync with the one in func_win32_libid. + lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' + lt_cv_file_magic_cmd='$OBJDUMP -f' + fi + ;; + +cegcc*) + # use the weaker test based on 'objdump'. See mingw*. + lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' + lt_cv_file_magic_cmd='$OBJDUMP -f' + ;; + +darwin* | rhapsody*) + lt_cv_deplibs_check_method=pass_all + ;; + +freebsd* | dragonfly* | midnightbsd*) + if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then + case $host_cpu in + i*86 ) + # Not sure whether the presence of OpenBSD here was a mistake. + # Let's accept both of them until this is cleared up. + lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library' + lt_cv_file_magic_cmd=$FILECMD + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` + ;; + esac + else + lt_cv_deplibs_check_method=pass_all + fi + ;; + +haiku*) + lt_cv_deplibs_check_method=pass_all + ;; + +hpux10.20* | hpux11*) + lt_cv_file_magic_cmd=$FILECMD + case $host_cpu in + ia64*) + lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64' + lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so + ;; + hppa*64*) + [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]'] + lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl + ;; + *) + lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]]\.[[0-9]]) shared library' + lt_cv_file_magic_test_file=/usr/lib/libc.sl + ;; + esac + ;; + +interix[[3-9]]*) + # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$' + ;; + +irix5* | irix6* | nonstopux*) + case $LD in + *-32|*"-32 ") libmagic=32-bit;; + *-n32|*"-n32 ") libmagic=N32;; + *-64|*"-64 ") libmagic=64-bit;; + *) libmagic=never-match;; + esac + lt_cv_deplibs_check_method=pass_all + ;; + +# This must be glibc/ELF. +linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) + lt_cv_deplibs_check_method=pass_all + ;; + +netbsd* | netbsdelf*-gnu) + if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' + else + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$' + fi + ;; + +newos6*) + lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)' + lt_cv_file_magic_cmd=$FILECMD + lt_cv_file_magic_test_file=/usr/lib/libnls.so + ;; + +*nto* | *qnx*) + lt_cv_deplibs_check_method=pass_all + ;; + +openbsd* | bitrig*) + if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$' + else + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' + fi + ;; + +osf3* | osf4* | osf5*) + lt_cv_deplibs_check_method=pass_all + ;; + +rdos*) + lt_cv_deplibs_check_method=pass_all + ;; + +solaris*) + lt_cv_deplibs_check_method=pass_all + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + lt_cv_deplibs_check_method=pass_all + ;; + +sysv4 | sysv4.3*) + case $host_vendor in + motorola) + lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]' + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` + ;; + ncr) + lt_cv_deplibs_check_method=pass_all + ;; + sequent) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )' + ;; + sni) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib" + lt_cv_file_magic_test_file=/lib/libc.so + ;; + siemens) + lt_cv_deplibs_check_method=pass_all + ;; + pc) + lt_cv_deplibs_check_method=pass_all + ;; + esac + ;; + +tpf*) + lt_cv_deplibs_check_method=pass_all + ;; +os2*) + lt_cv_deplibs_check_method=pass_all + ;; +esac +]) + +file_magic_glob= +want_nocaseglob=no +if test "$build" = "$host"; then + case $host_os in + mingw* | pw32*) + if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then + want_nocaseglob=yes + else + file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[[\1]]\/[[\1]]\/g;/g"` + fi + ;; + esac +fi + +file_magic_cmd=$lt_cv_file_magic_cmd +deplibs_check_method=$lt_cv_deplibs_check_method +test -z "$deplibs_check_method" && deplibs_check_method=unknown + +_LT_DECL([], [deplibs_check_method], [1], + [Method to check whether dependent libraries are shared objects]) +_LT_DECL([], [file_magic_cmd], [1], + [Command to use when deplibs_check_method = "file_magic"]) +_LT_DECL([], [file_magic_glob], [1], + [How to find potential files when deplibs_check_method = "file_magic"]) +_LT_DECL([], [want_nocaseglob], [1], + [Find potential files using nocaseglob when deplibs_check_method = "file_magic"]) +])# _LT_CHECK_MAGIC_METHOD + + +# LT_PATH_NM +# ---------- +# find the pathname to a BSD- or MS-compatible name lister +AC_DEFUN([LT_PATH_NM], +[AC_REQUIRE([AC_PROG_CC])dnl +AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM, +[if test -n "$NM"; then + # Let the user override the test. + lt_cv_path_NM=$NM +else + lt_nm_to_check=${ac_tool_prefix}nm + if test -n "$ac_tool_prefix" && test "$build" = "$host"; then + lt_nm_to_check="$lt_nm_to_check nm" + fi + for lt_tmp_nm in $lt_nm_to_check; do + lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR + for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do + IFS=$lt_save_ifs + test -z "$ac_dir" && ac_dir=. + tmp_nm=$ac_dir/$lt_tmp_nm + if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext"; then + # Check to see if the nm accepts a BSD-compat flag. + # Adding the 'sed 1q' prevents false positives on HP-UX, which says: + # nm: unknown option "B" ignored + # Tru64's nm complains that /dev/null is an invalid object file + # MSYS converts /dev/null to NUL, MinGW nm treats NUL as empty + case $build_os in + mingw*) lt_bad_file=conftest.nm/nofile ;; + *) lt_bad_file=/dev/null ;; + esac + case `"$tmp_nm" -B $lt_bad_file 2>&1 | $SED '1q'` in + *$lt_bad_file* | *'Invalid file or object type'*) + lt_cv_path_NM="$tmp_nm -B" + break 2 + ;; + *) + case `"$tmp_nm" -p /dev/null 2>&1 | $SED '1q'` in + */dev/null*) + lt_cv_path_NM="$tmp_nm -p" + break 2 + ;; + *) + lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but + continue # so that we can try to find one that supports BSD flags + ;; + esac + ;; + esac + fi + done + IFS=$lt_save_ifs + done + : ${lt_cv_path_NM=no} +fi]) +if test no != "$lt_cv_path_NM"; then + NM=$lt_cv_path_NM +else + # Didn't find any BSD compatible name lister, look for dumpbin. + if test -n "$DUMPBIN"; then : + # Let the user override the test. + else + AC_CHECK_TOOLS(DUMPBIN, [dumpbin "link -dump"], :) + case `$DUMPBIN -symbols -headers /dev/null 2>&1 | $SED '1q'` in + *COFF*) + DUMPBIN="$DUMPBIN -symbols -headers" + ;; + *) + DUMPBIN=: + ;; + esac + fi + AC_SUBST([DUMPBIN]) + if test : != "$DUMPBIN"; then + NM=$DUMPBIN + fi +fi +test -z "$NM" && NM=nm +AC_SUBST([NM]) +_LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl + +AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface], + [lt_cv_nm_interface="BSD nm" + echo "int some_variable = 0;" > conftest.$ac_ext + (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&AS_MESSAGE_LOG_FD) + (eval "$ac_compile" 2>conftest.err) + cat conftest.err >&AS_MESSAGE_LOG_FD + (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD) + (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) + cat conftest.err >&AS_MESSAGE_LOG_FD + (eval echo "\"\$as_me:$LINENO: output\"" >&AS_MESSAGE_LOG_FD) + cat conftest.out >&AS_MESSAGE_LOG_FD + if $GREP 'External.*some_variable' conftest.out > /dev/null; then + lt_cv_nm_interface="MS dumpbin" + fi + rm -f conftest*]) +])# LT_PATH_NM + +# Old names: +AU_ALIAS([AM_PROG_NM], [LT_PATH_NM]) +AU_ALIAS([AC_PROG_NM], [LT_PATH_NM]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AM_PROG_NM], []) +dnl AC_DEFUN([AC_PROG_NM], []) + +# _LT_CHECK_SHAREDLIB_FROM_LINKLIB +# -------------------------------- +# how to determine the name of the shared library +# associated with a specific link library. +# -- PORTME fill in with the dynamic library characteristics +m4_defun([_LT_CHECK_SHAREDLIB_FROM_LINKLIB], +[m4_require([_LT_DECL_EGREP]) +m4_require([_LT_DECL_OBJDUMP]) +m4_require([_LT_DECL_DLLTOOL]) +AC_CACHE_CHECK([how to associate runtime and link libraries], +lt_cv_sharedlib_from_linklib_cmd, +[lt_cv_sharedlib_from_linklib_cmd='unknown' + +case $host_os in +cygwin* | mingw* | pw32* | cegcc*) + # two different shell functions defined in ltmain.sh; + # decide which one to use based on capabilities of $DLLTOOL + case `$DLLTOOL --help 2>&1` in + *--identify-strict*) + lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib + ;; + *) + lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback + ;; + esac + ;; +*) + # fallback: assume linklib IS sharedlib + lt_cv_sharedlib_from_linklib_cmd=$ECHO + ;; +esac +]) +sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd +test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO + +_LT_DECL([], [sharedlib_from_linklib_cmd], [1], + [Command to associate shared and link libraries]) +])# _LT_CHECK_SHAREDLIB_FROM_LINKLIB + + +# _LT_PATH_MANIFEST_TOOL +# ---------------------- +# locate the manifest tool +m4_defun([_LT_PATH_MANIFEST_TOOL], +[AC_CHECK_TOOL(MANIFEST_TOOL, mt, :) +test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt +AC_CACHE_CHECK([if $MANIFEST_TOOL is a manifest tool], [lt_cv_path_mainfest_tool], + [lt_cv_path_mainfest_tool=no + echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&AS_MESSAGE_LOG_FD + $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out + cat conftest.err >&AS_MESSAGE_LOG_FD + if $GREP 'Manifest Tool' conftest.out > /dev/null; then + lt_cv_path_mainfest_tool=yes + fi + rm -f conftest*]) +if test yes != "$lt_cv_path_mainfest_tool"; then + MANIFEST_TOOL=: +fi +_LT_DECL([], [MANIFEST_TOOL], [1], [Manifest tool])dnl +])# _LT_PATH_MANIFEST_TOOL + + +# _LT_DLL_DEF_P([FILE]) +# --------------------- +# True iff FILE is a Windows DLL '.def' file. +# Keep in sync with func_dll_def_p in the libtool script +AC_DEFUN([_LT_DLL_DEF_P], +[dnl + test DEF = "`$SED -n dnl + -e '\''s/^[[ ]]*//'\'' dnl Strip leading whitespace + -e '\''/^\(;.*\)*$/d'\'' dnl Delete empty lines and comments + -e '\''s/^\(EXPORTS\|LIBRARY\)\([[ ]].*\)*$/DEF/p'\'' dnl + -e q dnl Only consider the first "real" line + $1`" dnl +])# _LT_DLL_DEF_P + + +# LT_LIB_M +# -------- +# check for math library +AC_DEFUN([LT_LIB_M], +[AC_REQUIRE([AC_CANONICAL_HOST])dnl +LIBM= +case $host in +*-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-pw32* | *-*-darwin*) + # These system don't have libm, or don't need it + ;; +*-ncr-sysv4.3*) + AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM=-lmw) + AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm") + ;; +*) + AC_CHECK_LIB(m, cos, LIBM=-lm) + ;; +esac +AC_SUBST([LIBM]) +])# LT_LIB_M + +# Old name: +AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_CHECK_LIBM], []) + + +# _LT_COMPILER_NO_RTTI([TAGNAME]) +# ------------------------------- +m4_defun([_LT_COMPILER_NO_RTTI], +[m4_require([_LT_TAG_COMPILER])dnl + +_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= + +if test yes = "$GCC"; then + case $cc_basename in + nvcc*) + _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -Xcompiler -fno-builtin' ;; + *) + _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' ;; + esac + + _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions], + lt_cv_prog_compiler_rtti_exceptions, + [-fno-rtti -fno-exceptions], [], + [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"]) +fi +_LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1], + [Compiler flag to turn off builtin functions]) +])# _LT_COMPILER_NO_RTTI + + +# _LT_CMD_GLOBAL_SYMBOLS +# ---------------------- +m4_defun([_LT_CMD_GLOBAL_SYMBOLS], +[AC_REQUIRE([AC_CANONICAL_HOST])dnl +AC_REQUIRE([AC_PROG_CC])dnl +AC_REQUIRE([AC_PROG_AWK])dnl +AC_REQUIRE([LT_PATH_NM])dnl +AC_REQUIRE([LT_PATH_LD])dnl +m4_require([_LT_DECL_SED])dnl +m4_require([_LT_DECL_EGREP])dnl +m4_require([_LT_TAG_COMPILER])dnl + +# Check for command to grab the raw symbol name followed by C symbol from nm. +AC_MSG_CHECKING([command to parse $NM output from $compiler object]) +AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe], +[ +# These are sane defaults that work on at least a few old systems. +# [They come from Ultrix. What could be older than Ultrix?!! ;)] + +# Character class describing NM global symbol codes. +symcode='[[BCDEGRST]]' + +# Regexp to match symbols that can be accessed directly from C. +sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)' + +# Define system-specific variables. +case $host_os in +aix*) + symcode='[[BCDT]]' + ;; +cygwin* | mingw* | pw32* | cegcc*) + symcode='[[ABCDGISTW]]' + ;; +hpux*) + if test ia64 = "$host_cpu"; then + symcode='[[ABCDEGRST]]' + fi + ;; +irix* | nonstopux*) + symcode='[[BCDEGRST]]' + ;; +osf*) + symcode='[[BCDEGQRST]]' + ;; +solaris*) + symcode='[[BDRT]]' + ;; +sco3.2v5*) + symcode='[[DT]]' + ;; +sysv4.2uw2*) + symcode='[[DT]]' + ;; +sysv5* | sco5v6* | unixware* | OpenUNIX*) + symcode='[[ABDT]]' + ;; +sysv4) + symcode='[[DFNSTU]]' + ;; +esac + +# If we're using GNU nm, then use its standard symbol codes. +case `$NM -V 2>&1` in +*GNU* | *'with BFD'*) + symcode='[[ABCDGIRSTW]]' ;; +esac + +if test "$lt_cv_nm_interface" = "MS dumpbin"; then + # Gets list of data symbols to import. + lt_cv_sys_global_symbol_to_import="$SED -n -e 's/^I .* \(.*\)$/\1/p'" + # Adjust the below global symbol transforms to fixup imported variables. + lt_cdecl_hook=" -e 's/^I .* \(.*\)$/extern __declspec(dllimport) char \1;/p'" + lt_c_name_hook=" -e 's/^I .* \(.*\)$/ {\"\1\", (void *) 0},/p'" + lt_c_name_lib_hook="\ + -e 's/^I .* \(lib.*\)$/ {\"\1\", (void *) 0},/p'\ + -e 's/^I .* \(.*\)$/ {\"lib\1\", (void *) 0},/p'" +else + # Disable hooks by default. + lt_cv_sys_global_symbol_to_import= + lt_cdecl_hook= + lt_c_name_hook= + lt_c_name_lib_hook= +fi + +# Transform an extracted symbol line into a proper C declaration. +# Some systems (esp. on ia64) link data and code symbols differently, +# so use this general approach. +lt_cv_sys_global_symbol_to_cdecl="$SED -n"\ +$lt_cdecl_hook\ +" -e 's/^T .* \(.*\)$/extern int \1();/p'"\ +" -e 's/^$symcode$symcode* .* \(.*\)$/extern char \1;/p'" + +# Transform an extracted symbol line into symbol name and symbol address +lt_cv_sys_global_symbol_to_c_name_address="$SED -n"\ +$lt_c_name_hook\ +" -e 's/^: \(.*\) .*$/ {\"\1\", (void *) 0},/p'"\ +" -e 's/^$symcode$symcode* .* \(.*\)$/ {\"\1\", (void *) \&\1},/p'" + +# Transform an extracted symbol line into symbol name with lib prefix and +# symbol address. +lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="$SED -n"\ +$lt_c_name_lib_hook\ +" -e 's/^: \(.*\) .*$/ {\"\1\", (void *) 0},/p'"\ +" -e 's/^$symcode$symcode* .* \(lib.*\)$/ {\"\1\", (void *) \&\1},/p'"\ +" -e 's/^$symcode$symcode* .* \(.*\)$/ {\"lib\1\", (void *) \&\1},/p'" + +# Handle CRLF in mingw tool chain +opt_cr= +case $build_os in +mingw*) + opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp + ;; +esac + +# Try without a prefix underscore, then with it. +for ac_symprfx in "" "_"; do + + # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. + symxfrm="\\1 $ac_symprfx\\2 \\2" + + # Write the raw and C identifiers. + if test "$lt_cv_nm_interface" = "MS dumpbin"; then + # Fake it for dumpbin and say T for any non-static function, + # D for any global variable and I for any imported variable. + # Also find C++ and __fastcall symbols from MSVC++ or ICC, + # which start with @ or ?. + lt_cv_sys_global_symbol_pipe="$AWK ['"\ +" {last_section=section; section=\$ 3};"\ +" /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\ +" /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ +" /^ *Symbol name *: /{split(\$ 0,sn,\":\"); si=substr(sn[2],2)};"\ +" /^ *Type *: code/{print \"T\",si,substr(si,length(prfx))};"\ +" /^ *Type *: data/{print \"I\",si,substr(si,length(prfx))};"\ +" \$ 0!~/External *\|/{next};"\ +" / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ +" {if(hide[section]) next};"\ +" {f=\"D\"}; \$ 0~/\(\).*\|/{f=\"T\"};"\ +" {split(\$ 0,a,/\||\r/); split(a[2],s)};"\ +" s[1]~/^[@?]/{print f,s[1],s[1]; next};"\ +" s[1]~prfx {split(s[1],t,\"@\"); print f,t[1],substr(t[1],length(prfx))}"\ +" ' prfx=^$ac_symprfx]" + else + lt_cv_sys_global_symbol_pipe="$SED -n -e 's/^.*[[ ]]\($symcode$symcode*\)[[ ]][[ ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" + fi + lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | $SED '/ __gnu_lto/d'" + + # Check to see that the pipe works correctly. + pipe_works=no + + rm -f conftest* + cat > conftest.$ac_ext <<_LT_EOF +#ifdef __cplusplus +extern "C" { +#endif +char nm_test_var; +void nm_test_func(void); +void nm_test_func(void){} +#ifdef __cplusplus +} +#endif +int main(){nm_test_var='a';nm_test_func();return(0);} +_LT_EOF + + if AC_TRY_EVAL(ac_compile); then + # Now try to grab the symbols. + nlist=conftest.nm + $ECHO "$as_me:$LINENO: $NM conftest.$ac_objext | $lt_cv_sys_global_symbol_pipe > $nlist" >&AS_MESSAGE_LOG_FD + if eval "$NM" conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist 2>&AS_MESSAGE_LOG_FD && test -s "$nlist"; then + # Try sorting and uniquifying the output. + if sort "$nlist" | uniq > "$nlist"T; then + mv -f "$nlist"T "$nlist" + else + rm -f "$nlist"T + fi + + # Make sure that we snagged all the symbols we need. + if $GREP ' nm_test_var$' "$nlist" >/dev/null; then + if $GREP ' nm_test_func$' "$nlist" >/dev/null; then + cat <<_LT_EOF > conftest.$ac_ext +/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ +#if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE +/* DATA imports from DLLs on WIN32 can't be const, because runtime + relocations are performed -- see ld's documentation on pseudo-relocs. */ +# define LT@&t@_DLSYM_CONST +#elif defined __osf__ +/* This system does not cope well with relocations in const data. */ +# define LT@&t@_DLSYM_CONST +#else +# define LT@&t@_DLSYM_CONST const +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +_LT_EOF + # Now generate the symbol file. + eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' + + cat <<_LT_EOF >> conftest.$ac_ext + +/* The mapping between symbol names and symbols. */ +LT@&t@_DLSYM_CONST struct { + const char *name; + void *address; +} +lt__PROGRAM__LTX_preloaded_symbols[[]] = +{ + { "@PROGRAM@", (void *) 0 }, +_LT_EOF + $SED "s/^$symcode$symcode* .* \(.*\)$/ {\"\1\", (void *) \&\1},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext + cat <<\_LT_EOF >> conftest.$ac_ext + {0, (void *) 0} +}; + +/* This works around a problem in FreeBSD linker */ +#ifdef FREEBSD_WORKAROUND +static const void *lt_preloaded_setup() { + return lt__PROGRAM__LTX_preloaded_symbols; +} +#endif + +#ifdef __cplusplus +} +#endif +_LT_EOF + # Now try linking the two files. + mv conftest.$ac_objext conftstm.$ac_objext + lt_globsym_save_LIBS=$LIBS + lt_globsym_save_CFLAGS=$CFLAGS + LIBS=conftstm.$ac_objext + CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)" + if AC_TRY_EVAL(ac_link) && test -s conftest$ac_exeext; then + pipe_works=yes + fi + LIBS=$lt_globsym_save_LIBS + CFLAGS=$lt_globsym_save_CFLAGS + else + echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD + fi + else + echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD + fi + else + echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD + fi + else + echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD + cat conftest.$ac_ext >&5 + fi + rm -rf conftest* conftst* + + # Do not use the global_symbol_pipe unless it works. + if test yes = "$pipe_works"; then + break + else + lt_cv_sys_global_symbol_pipe= + fi +done +]) +if test -z "$lt_cv_sys_global_symbol_pipe"; then + lt_cv_sys_global_symbol_to_cdecl= +fi +if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then + AC_MSG_RESULT(failed) +else + AC_MSG_RESULT(ok) +fi + +# Response file support. +if test "$lt_cv_nm_interface" = "MS dumpbin"; then + nm_file_list_spec='@' +elif $NM --help 2>/dev/null | grep '[[@]]FILE' >/dev/null; then + nm_file_list_spec='@' +fi + +_LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1], + [Take the output of nm and produce a listing of raw symbols and C names]) +_LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1], + [Transform the output of nm in a proper C declaration]) +_LT_DECL([global_symbol_to_import], [lt_cv_sys_global_symbol_to_import], [1], + [Transform the output of nm into a list of symbols to manually relocate]) +_LT_DECL([global_symbol_to_c_name_address], + [lt_cv_sys_global_symbol_to_c_name_address], [1], + [Transform the output of nm in a C name address pair]) +_LT_DECL([global_symbol_to_c_name_address_lib_prefix], + [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1], + [Transform the output of nm in a C name address pair when lib prefix is needed]) +_LT_DECL([nm_interface], [lt_cv_nm_interface], [1], + [The name lister interface]) +_LT_DECL([], [nm_file_list_spec], [1], + [Specify filename containing input files for $NM]) +]) # _LT_CMD_GLOBAL_SYMBOLS + + +# _LT_COMPILER_PIC([TAGNAME]) +# --------------------------- +m4_defun([_LT_COMPILER_PIC], +[m4_require([_LT_TAG_COMPILER])dnl +_LT_TAGVAR(lt_prog_compiler_wl, $1)= +_LT_TAGVAR(lt_prog_compiler_pic, $1)= +_LT_TAGVAR(lt_prog_compiler_static, $1)= + +m4_if([$1], [CXX], [ + # C++ specific cases for pic, static, wl, etc. + if test yes = "$GXX"; then + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test ia64 = "$host_cpu"; then + # AIX 5 now supports IA64 processor + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + fi + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + m68k) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the '-m68020' flag to GCC prevents building anything better, + # like '-m68040'. + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' + ;; + esac + ;; + + beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + mingw* | cygwin* | os2* | pw32* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + # Although the cygwin gcc ignores -fPIC, still need this for old-style + # (--disable-auto-import) libraries + m4_if([$1], [GCJ], [], + [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) + case $host_os in + os2*) + _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-static' + ;; + esac + ;; + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' + ;; + *djgpp*) + # DJGPP does not support shared libraries at all + _LT_TAGVAR(lt_prog_compiler_pic, $1)= + ;; + haiku*) + # PIC is the default for Haiku. + # The "-static" flag exists, but is broken. + _LT_TAGVAR(lt_prog_compiler_static, $1)= + ;; + interix[[3-9]]*) + # Interix 3.x gcc -fpic/-fPIC options generate broken code. + # Instead, we relocate shared libraries at runtime. + ;; + sysv4*MP*) + if test -d /usr/nec; then + _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic + fi + ;; + hpux*) + # PIC is the default for 64-bit PA HP-UX, but not for 32-bit + # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag + # sets the default TLS model and affects inlining. + case $host_cpu in + hppa*64*) + ;; + *) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + esac + ;; + *qnx* | *nto*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' + ;; + *) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + esac + else + case $host_os in + aix[[4-9]]*) + # All AIX code is PIC. + if test ia64 = "$host_cpu"; then + # AIX 5 now supports IA64 processor + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + else + _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' + fi + ;; + chorus*) + case $cc_basename in + cxch68*) + # Green Hills C++ Compiler + # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" + ;; + esac + ;; + mingw* | cygwin* | os2* | pw32* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + m4_if([$1], [GCJ], [], + [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) + ;; + dgux*) + case $cc_basename in + ec++*) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + ;; + ghcx*) + # Green Hills C++ Compiler + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + ;; + *) + ;; + esac + ;; + freebsd* | dragonfly* | midnightbsd*) + # FreeBSD uses GNU C++ + ;; + hpux9* | hpux10* | hpux11*) + case $cc_basename in + CC*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-a ${wl}archive' + if test ia64 != "$host_cpu"; then + _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' + fi + ;; + aCC*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-a ${wl}archive' + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' + ;; + esac + ;; + *) + ;; + esac + ;; + interix*) + # This is c89, which is MS Visual C++ (no shared libs) + # Anyone wants to do a port? + ;; + irix5* | irix6* | nonstopux*) + case $cc_basename in + CC*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + # CC pic flag -KPIC is the default. + ;; + *) + ;; + esac + ;; + linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) + case $cc_basename in + KCC*) + # KAI C++ Compiler + _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + ecpc* ) + # old Intel C++ for x86_64, which still supported -KPIC. + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; + icpc* ) + # Intel C++, used to be incompatible with GCC. + # ICC 10 doesn't accept -KPIC any more. + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; + pgCC* | pgcpp*) + # Portland Group C++ compiler + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + cxx*) + # Compaq C++ + # Make sure the PIC flag is empty. It appears that all Alpha + # Linux and Compaq Tru64 Unix objects are PIC. + _LT_TAGVAR(lt_prog_compiler_pic, $1)= + _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + xlc* | xlC* | bgxl[[cC]]* | mpixl[[cC]]*) + # IBM XL 8.0, 9.0 on PPC and BlueGene + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' + ;; + *) + case `$CC -V 2>&1 | $SED 5q` in + *Sun\ C*) + # Sun C++ 5.9 + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' + ;; + esac + ;; + esac + ;; + lynxos*) + ;; + m88k*) + ;; + mvs*) + case $cc_basename in + cxx*) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall' + ;; + *) + ;; + esac + ;; + netbsd* | netbsdelf*-gnu) + ;; + *qnx* | *nto*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' + ;; + osf3* | osf4* | osf5*) + case $cc_basename in + KCC*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' + ;; + RCC*) + # Rational C++ 2.4.1 + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + ;; + cxx*) + # Digital/Compaq C++ + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # Make sure the PIC flag is empty. It appears that all Alpha + # Linux and Compaq Tru64 Unix objects are PIC. + _LT_TAGVAR(lt_prog_compiler_pic, $1)= + _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + *) + ;; + esac + ;; + psos*) + ;; + solaris*) + case $cc_basename in + CC* | sunCC*) + # Sun C++ 4.2, 5.x and Centerline C++ + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' + ;; + gcx*) + # Green Hills C++ Compiler + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' + ;; + *) + ;; + esac + ;; + sunos4*) + case $cc_basename in + CC*) + # Sun C++ 4.x + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + lcc*) + # Lucid + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + ;; + *) + ;; + esac + ;; + sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) + case $cc_basename in + CC*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + esac + ;; + tandem*) + case $cc_basename in + NCC*) + # NonStop-UX NCC 3.20 + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + ;; + *) + ;; + esac + ;; + vxworks*) + ;; + *) + _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no + ;; + esac + fi +], +[ + if test yes = "$GCC"; then + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test ia64 = "$host_cpu"; then + # AIX 5 now supports IA64 processor + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + fi + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + m68k) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the '-m68020' flag to GCC prevents building anything better, + # like '-m68040'. + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' + ;; + esac + ;; + + beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + + mingw* | cygwin* | pw32* | os2* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + # Although the cygwin gcc ignores -fPIC, still need this for old-style + # (--disable-auto-import) libraries + m4_if([$1], [GCJ], [], + [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) + case $host_os in + os2*) + _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-static' + ;; + esac + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' + ;; + + haiku*) + # PIC is the default for Haiku. + # The "-static" flag exists, but is broken. + _LT_TAGVAR(lt_prog_compiler_static, $1)= + ;; + + hpux*) + # PIC is the default for 64-bit PA HP-UX, but not for 32-bit + # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag + # sets the default TLS model and affects inlining. + case $host_cpu in + hppa*64*) + # +Z the default + ;; + *) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + esac + ;; + + interix[[3-9]]*) + # Interix 3.x gcc -fpic/-fPIC options generate broken code. + # Instead, we relocate shared libraries at runtime. + ;; + + msdosdjgpp*) + # Just because we use GCC doesn't mean we suddenly get shared libraries + # on systems that don't support them. + _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no + enable_shared=no + ;; + + *nto* | *qnx*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic + fi + ;; + + *) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + esac + + case $cc_basename in + nvcc*) # Cuda Compiler Driver 2.2 + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Xlinker ' + if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then + _LT_TAGVAR(lt_prog_compiler_pic, $1)="-Xcompiler $_LT_TAGVAR(lt_prog_compiler_pic, $1)" + fi + ;; + esac + else + # PORTME Check for flag to pass linker flags through the system compiler. + case $host_os in + aix*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + if test ia64 = "$host_cpu"; then + # AIX 5 now supports IA64 processor + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + else + _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' + fi + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' + case $cc_basename in + nagfor*) + # NAG Fortran compiler + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + esac + ;; + + mingw* | cygwin* | pw32* | os2* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + m4_if([$1], [GCJ], [], + [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) + case $host_os in + os2*) + _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-static' + ;; + esac + ;; + + hpux9* | hpux10* | hpux11*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' + ;; + esac + # Is there a better lt_prog_compiler_static that works with the bundled CC? + _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-a ${wl}archive' + ;; + + irix5* | irix6* | nonstopux*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # PIC (with -KPIC) is the default. + _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + + linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) + case $cc_basename in + # old Intel for x86_64, which still supported -KPIC. + ecc*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; + # flang / f18. f95 an alias for gfortran or flang on Debian + flang* | f18* | f95*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; + # icc used to be incompatible with GCC. + # ICC 10 doesn't accept -KPIC any more. + icc* | ifort*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; + # Lahey Fortran 8.1. + lf95*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared' + _LT_TAGVAR(lt_prog_compiler_static, $1)='--static' + ;; + nagfor*) + # NAG Fortran compiler + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + tcc*) + # Fabrice Bellard et al's Tiny C Compiler + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; + pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) + # Portland Group compilers (*not* the Pentium gcc compiler, + # which looks to be a dead project) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + ccc*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # All Alpha code is PIC. + _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + xl* | bgxl* | bgf* | mpixl*) + # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' + ;; + *) + case `$CC -V 2>&1 | $SED 5q` in + *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [[1-7]].* | *Sun*Fortran*\ 8.[[0-3]]*) + # Sun Fortran 8.3 passes all unrecognized flags to the linker + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + _LT_TAGVAR(lt_prog_compiler_wl, $1)='' + ;; + *Sun\ F* | *Sun*Fortran*) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' + ;; + *Sun\ C*) + # Sun C 5.9 + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + ;; + *Intel*\ [[CF]]*Compiler*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; + *Portland\ Group*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + esac + ;; + esac + ;; + + newsos6) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + *nto* | *qnx*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' + ;; + + osf3* | osf4* | osf5*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # All OSF/1 code is PIC. + _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + + rdos*) + _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + + solaris*) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + case $cc_basename in + f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';; + *) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';; + esac + ;; + + sunos4*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + sysv4 | sysv4.2uw2* | sysv4.3*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + fi + ;; + + sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + unicos*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no + ;; + + uts4*) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + *) + _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no + ;; + esac + fi +]) +case $host_os in + # For platforms that do not support PIC, -DPIC is meaningless: + *djgpp*) + _LT_TAGVAR(lt_prog_compiler_pic, $1)= + ;; + *) + _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])" + ;; +esac + +AC_CACHE_CHECK([for $compiler option to produce PIC], + [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)], + [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_prog_compiler_pic, $1)]) +_LT_TAGVAR(lt_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_cv_prog_compiler_pic, $1) + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then + _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works], + [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)], + [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [], + [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in + "" | " "*) ;; + *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;; + esac], + [_LT_TAGVAR(lt_prog_compiler_pic, $1)= + _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no]) +fi +_LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1], + [Additional compiler flags for building library objects]) + +_LT_TAGDECL([wl], [lt_prog_compiler_wl], [1], + [How to pass a linker flag through the compiler]) +# +# Check to make sure the static flag actually works. +# +wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\" +_LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works], + _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1), + $lt_tmp_static_flag, + [], + [_LT_TAGVAR(lt_prog_compiler_static, $1)=]) +_LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1], + [Compiler flag to prevent dynamic linking]) +])# _LT_COMPILER_PIC + + +# _LT_LINKER_SHLIBS([TAGNAME]) +# ---------------------------- +# See if the linker supports building shared libraries. +m4_defun([_LT_LINKER_SHLIBS], +[AC_REQUIRE([LT_PATH_LD])dnl +AC_REQUIRE([LT_PATH_NM])dnl +m4_require([_LT_PATH_MANIFEST_TOOL])dnl +m4_require([_LT_FILEUTILS_DEFAULTS])dnl +m4_require([_LT_DECL_EGREP])dnl +m4_require([_LT_DECL_SED])dnl +m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl +m4_require([_LT_TAG_COMPILER])dnl +AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) +m4_if([$1], [CXX], [ + _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] + case $host_os in + aix[[4-9]]*) + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to GNU nm, but means don't demangle to AIX nm. + # Without the "-l" option, or with the "-B" option, AIX nm treats + # weak defined symbols like other global defined symbols, whereas + # GNU nm marks them as "W". + # While the 'weak' keyword is ignored in the Export File, we need + # it in the Import File for the 'aix-soname' feature, so we have + # to replace the "-B" option with "-P" for AIX nm. + if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then + _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { if (\$ 2 == "W") { print \$ 3 " weak" } else { print \$ 3 } } }'\'' | sort -u > $export_symbols' + else + _LT_TAGVAR(export_symbols_cmds, $1)='`func_echo_all $NM | $SED -e '\''s/B\([[^B]]*\)$/P\1/'\''` -PCpgl $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "L") || (\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) && ([substr](\$ 1,1,1) != ".")) { if ((\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) { print \$ 1 " weak" } else { print \$ 1 } } }'\'' | sort -u > $export_symbols' + fi + ;; + pw32*) + _LT_TAGVAR(export_symbols_cmds, $1)=$ltdll_cmds + ;; + cygwin* | mingw* | cegcc*) + case $cc_basename in + cl* | icl*) + _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' + ;; + *) + _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' + _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'] + ;; + esac + ;; + linux* | k*bsd*-gnu | gnu*) + _LT_TAGVAR(link_all_deplibs, $1)=no + ;; + *) + _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + ;; + esac +], [ + runpath_var= + _LT_TAGVAR(allow_undefined_flag, $1)= + _LT_TAGVAR(always_export_symbols, $1)=no + _LT_TAGVAR(archive_cmds, $1)= + _LT_TAGVAR(archive_expsym_cmds, $1)= + _LT_TAGVAR(compiler_needs_object, $1)=no + _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no + _LT_TAGVAR(export_dynamic_flag_spec, $1)= + _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + _LT_TAGVAR(hardcode_automatic, $1)=no + _LT_TAGVAR(hardcode_direct, $1)=no + _LT_TAGVAR(hardcode_direct_absolute, $1)=no + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= + _LT_TAGVAR(hardcode_libdir_separator, $1)= + _LT_TAGVAR(hardcode_minus_L, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported + _LT_TAGVAR(inherit_rpath, $1)=no + _LT_TAGVAR(link_all_deplibs, $1)=unknown + _LT_TAGVAR(module_cmds, $1)= + _LT_TAGVAR(module_expsym_cmds, $1)= + _LT_TAGVAR(old_archive_from_new_cmds, $1)= + _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)= + _LT_TAGVAR(thread_safe_flag_spec, $1)= + _LT_TAGVAR(whole_archive_flag_spec, $1)= + # include_expsyms should be a list of space-separated symbols to be *always* + # included in the symbol list + _LT_TAGVAR(include_expsyms, $1)= + # exclude_expsyms can be an extended regexp of symbols to exclude + # it will be wrapped by ' (' and ')$', so one must not match beginning or + # end of line. Example: 'a|bc|.*d.*' will exclude the symbols 'a' and 'bc', + # as well as any symbol that contains 'd'. + _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] + # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out + # platforms (ab)use it in PIC code, but their linkers get confused if + # the symbol is explicitly referenced. Since portable code cannot + # rely on this symbol name, it's probably fine to never include it in + # preloaded symbol tables. + # Exclude shared library initialization/finalization symbols. +dnl Note also adjust exclude_expsyms for C++ above. + extract_expsyms_cmds= + + case $host_os in + cygwin* | mingw* | pw32* | cegcc*) + # FIXME: the MSVC++ and ICC port hasn't been tested in a loooong time + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++ or Intel C++ Compiler. + if test yes != "$GCC"; then + with_gnu_ld=no + fi + ;; + interix*) + # we just hope/assume this is gcc and not c89 (= MSVC++ or ICC) + with_gnu_ld=yes + ;; + openbsd* | bitrig*) + with_gnu_ld=no + ;; + linux* | k*bsd*-gnu | gnu*) + _LT_TAGVAR(link_all_deplibs, $1)=no + ;; + esac + + _LT_TAGVAR(ld_shlibs, $1)=yes + + # On some targets, GNU ld is compatible enough with the native linker + # that we're better off using the native interface for both. + lt_use_gnu_ld_interface=no + if test yes = "$with_gnu_ld"; then + case $host_os in + aix*) + # The AIX port of GNU ld has always aspired to compatibility + # with the native linker. However, as the warning in the GNU ld + # block says, versions before 2.19.5* couldn't really create working + # shared libraries, regardless of the interface used. + case `$LD -v 2>&1` in + *\ \(GNU\ Binutils\)\ 2.19.5*) ;; + *\ \(GNU\ Binutils\)\ 2.[[2-9]]*) ;; + *\ \(GNU\ Binutils\)\ [[3-9]]*) ;; + *) + lt_use_gnu_ld_interface=yes + ;; + esac + ;; + *) + lt_use_gnu_ld_interface=yes + ;; + esac + fi + + if test yes = "$lt_use_gnu_ld_interface"; then + # If archive_cmds runs LD, not CC, wlarc should be empty + wlarc='$wl' + + # Set some defaults for GNU ld with shared library support. These + # are reset later if shared libraries are not supported. Putting them + # here allows them to be overridden if necessary. + runpath_var=LD_RUN_PATH + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' + # ancient GNU ld didn't support --whole-archive et. al. + if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then + _LT_TAGVAR(whole_archive_flag_spec, $1)=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive' + else + _LT_TAGVAR(whole_archive_flag_spec, $1)= + fi + supports_anon_versioning=no + case `$LD -v | $SED -e 's/([[^)]]\+)\s\+//' 2>&1` in + *GNU\ gold*) supports_anon_versioning=yes ;; + *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11 + *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... + *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... + *\ 2.11.*) ;; # other 2.11 versions + *) supports_anon_versioning=yes ;; + esac + + # See if GNU ld supports shared libraries. + case $host_os in + aix[[3-9]]*) + # On AIX/PPC, the GNU linker is very broken + if test ia64 != "$host_cpu"; then + _LT_TAGVAR(ld_shlibs, $1)=no + cat <<_LT_EOF 1>&2 + +*** Warning: the GNU linker, at least up to release 2.19, is reported +*** to be unable to reliably create shared libraries on AIX. +*** Therefore, libtool is disabling shared libraries support. If you +*** really care for shared libraries, you may want to install binutils +*** 2.20 or above, or modify your PATH so that a non-GNU linker is found. +*** You will then need to restart the configuration process. + +_LT_EOF + fi + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='' + ;; + m68k) + _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_minus_L, $1)=yes + ;; + esac + ;; + + beos*) + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + cygwin* | mingw* | pw32* | cegcc*) + # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, + # as there is no search path for DLLs. + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-all-symbols' + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_TAGVAR(always_export_symbols, $1)=no + _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' + _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'] + + if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + # If the export-symbols file already is a .def file, use it as + # is; otherwise, prepend EXPORTS... + _LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + haiku*) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + _LT_TAGVAR(link_all_deplibs, $1)=yes + ;; + + os2*) + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_minus_L, $1)=yes + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + shrext_cmds=.dll + _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ + $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ + $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ + $ECHO EXPORTS >> $output_objdir/$libname.def~ + emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~ + $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ + emximp -o $lib $output_objdir/$libname.def' + _LT_TAGVAR(archive_expsym_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ + $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ + $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ + $ECHO EXPORTS >> $output_objdir/$libname.def~ + prefix_cmds="$SED"~ + if test EXPORTS = "`$SED 1q $export_symbols`"; then + prefix_cmds="$prefix_cmds -e 1d"; + fi~ + prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~ + cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ + $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ + emximp -o $lib $output_objdir/$libname.def' + _LT_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' + _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + _LT_TAGVAR(file_list_spec, $1)='@' + ;; + + interix[[3-9]]*) + _LT_TAGVAR(hardcode_direct, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' + # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. + # Instead, shared libraries are loaded at an image base (0x10000000 by + # default) and relocated if they conflict, which is a slow very memory + # consuming and fragmenting process. To avoid this, we pick a random, + # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link + # time. Moving up from 0x10000000 also allows more sbrk(2) space. + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$SED "s|^|_|" $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--retain-symbols-file,$output_objdir/$soname.expsym $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + ;; + + gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu) + tmp_diet=no + if test linux-dietlibc = "$host_os"; then + case $cc_basename in + diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) + esac + fi + if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ + && test no = "$tmp_diet" + then + tmp_addflag=' $pic_flag' + tmp_sharedflag='-shared' + case $cc_basename,$host_cpu in + pgcc*) # Portland Group C compiler + _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' + tmp_addflag=' $pic_flag' + ;; + pgf77* | pgf90* | pgf95* | pgfortran*) + # Portland Group f77 and f90 compilers + _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' + tmp_addflag=' $pic_flag -Mnomain' ;; + ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 + tmp_addflag=' -i_dynamic' ;; + efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 + tmp_addflag=' -i_dynamic -nofor_main' ;; + ifc* | ifort*) # Intel Fortran compiler + tmp_addflag=' -nofor_main' ;; + lf95*) # Lahey Fortran 8.1 + _LT_TAGVAR(whole_archive_flag_spec, $1)= + tmp_sharedflag='--shared' ;; + nagfor*) # NAGFOR 5.3 + tmp_sharedflag='-Wl,-shared' ;; + xl[[cC]]* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL C 8.0 on PPC (deal with xlf below) + tmp_sharedflag='-qmkshrobj' + tmp_addflag= ;; + nvcc*) # Cuda Compiler Driver 2.2 + _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' + _LT_TAGVAR(compiler_needs_object, $1)=yes + ;; + esac + case `$CC -V 2>&1 | $SED 5q` in + *Sun\ C*) # Sun C 5.9 + _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' + _LT_TAGVAR(compiler_needs_object, $1)=yes + tmp_sharedflag='-G' ;; + *Sun\ F*) # Sun Fortran 8.3 + tmp_sharedflag='-G' ;; + esac + _LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + + if test yes = "$supports_anon_versioning"; then + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + echo "local: *; };" >> $output_objdir/$libname.ver~ + $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-version-script $wl$output_objdir/$libname.ver -o $lib' + fi + + case $cc_basename in + tcc*) + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='-rdynamic' + ;; + xlf* | bgf* | bgxlf* | mpixlf*) + # IBM XL Fortran 10.1 on PPC cannot create shared libs itself + _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' + _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib' + if test yes = "$supports_anon_versioning"; then + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + echo "local: *; };" >> $output_objdir/$libname.ver~ + $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' + fi + ;; + esac + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + netbsd* | netbsdelf*-gnu) + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' + wlarc= + else + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' + fi + ;; + + solaris*) + if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then + _LT_TAGVAR(ld_shlibs, $1)=no + cat <<_LT_EOF 1>&2 + +*** Warning: The releases 2.8.* of the GNU linker cannot reliably +*** create shared libraries on Solaris systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.9.1 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +_LT_EOF + elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) + case `$LD -v 2>&1` in + *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*) + _LT_TAGVAR(ld_shlibs, $1)=no + cat <<_LT_EOF 1>&2 + +*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 cannot +*** reliably create shared libraries on SCO systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.16.91.0.3 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +_LT_EOF + ;; + *) + # For security reasons, it is highly recommended that you always + # use absolute paths for naming shared libraries, and exclude the + # DT_RUNPATH tag from executables and libraries. But doing so + # requires that you compile everything twice, which is a pain. + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + + sunos4*) + _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' + wlarc= + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + *) + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + + if test no = "$_LT_TAGVAR(ld_shlibs, $1)"; then + runpath_var= + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= + _LT_TAGVAR(export_dynamic_flag_spec, $1)= + _LT_TAGVAR(whole_archive_flag_spec, $1)= + fi + else + # PORTME fill in a description of your system's linker (not GNU ld) + case $host_os in + aix3*) + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_TAGVAR(always_export_symbols, $1)=yes + _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' + # Note: this linker hardcodes the directories in LIBPATH if there + # are no directories specified by -L. + _LT_TAGVAR(hardcode_minus_L, $1)=yes + if test yes = "$GCC" && test -z "$lt_prog_compiler_static"; then + # Neither direct hardcoding nor static linking is supported with a + # broken collect2. + _LT_TAGVAR(hardcode_direct, $1)=unsupported + fi + ;; + + aix[[4-9]]*) + if test ia64 = "$host_cpu"; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag= + else + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to GNU nm, but means don't demangle to AIX nm. + # Without the "-l" option, or with the "-B" option, AIX nm treats + # weak defined symbols like other global defined symbols, whereas + # GNU nm marks them as "W". + # While the 'weak' keyword is ignored in the Export File, we need + # it in the Import File for the 'aix-soname' feature, so we have + # to replace the "-B" option with "-P" for AIX nm. + if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then + _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { if (\$ 2 == "W") { print \$ 3 " weak" } else { print \$ 3 } } }'\'' | sort -u > $export_symbols' + else + _LT_TAGVAR(export_symbols_cmds, $1)='`func_echo_all $NM | $SED -e '\''s/B\([[^B]]*\)$/P\1/'\''` -PCpgl $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "L") || (\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) && ([substr](\$ 1,1,1) != ".")) { if ((\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) { print \$ 1 " weak" } else { print \$ 1 } } }'\'' | sort -u > $export_symbols' + fi + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # have runtime linking enabled, and use it for executables. + # For shared libraries, we enable/disable runtime linking + # depending on the kind of the shared library created - + # when "with_aix_soname,aix_use_runtimelinking" is: + # "aix,no" lib.a(lib.so.V) shared, rtl:no, for executables + # "aix,yes" lib.so shared, rtl:yes, for executables + # lib.a static archive + # "both,no" lib.so.V(shr.o) shared, rtl:yes + # lib.a(lib.so.V) shared, rtl:no, for executables + # "both,yes" lib.so.V(shr.o) shared, rtl:yes, for executables + # lib.a(lib.so.V) shared, rtl:no + # "svr4,*" lib.so.V(shr.o) shared, rtl:yes, for executables + # lib.a static archive + case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) + for ld_flag in $LDFLAGS; do + if (test x-brtl = "x$ld_flag" || test x-Wl,-brtl = "x$ld_flag"); then + aix_use_runtimelinking=yes + break + fi + done + if test svr4,no = "$with_aix_soname,$aix_use_runtimelinking"; then + # With aix-soname=svr4, we create the lib.so.V shared archives only, + # so we don't have lib.a shared libs to link our executables. + # We have to force runtime linking in this case. + aix_use_runtimelinking=yes + LDFLAGS="$LDFLAGS -Wl,-brtl" + fi + ;; + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + _LT_TAGVAR(archive_cmds, $1)='' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_direct_absolute, $1)=yes + _LT_TAGVAR(hardcode_libdir_separator, $1)=':' + _LT_TAGVAR(link_all_deplibs, $1)=yes + _LT_TAGVAR(file_list_spec, $1)='$wl-f,' + case $with_aix_soname,$aix_use_runtimelinking in + aix,*) ;; # traditional, no import file + svr4,* | *,yes) # use import file + # The Import File defines what to hardcode. + _LT_TAGVAR(hardcode_direct, $1)=no + _LT_TAGVAR(hardcode_direct_absolute, $1)=no + ;; + esac + + if test yes = "$GCC"; then + case $host_os in aix4.[[012]]|aix4.[[012]].*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`$CC -print-prog-name=collect2` + if test -f "$collect2name" && + strings "$collect2name" | $GREP resolve_lib_name >/dev/null + then + # We have reworked collect2 + : + else + # We have old collect2 + _LT_TAGVAR(hardcode_direct, $1)=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + _LT_TAGVAR(hardcode_minus_L, $1)=yes + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)= + fi + ;; + esac + shared_flag='-shared' + if test yes = "$aix_use_runtimelinking"; then + shared_flag="$shared_flag "'$wl-G' + fi + # Need to ensure runtime linking is disabled for the traditional + # shared library, or the linker may eventually find shared libraries + # /with/ Import File - we do not want to mix them. + shared_flag_aix='-shared' + shared_flag_svr4='-shared $wl-G' + else + # not using gcc + if test ia64 = "$host_cpu"; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test yes = "$aix_use_runtimelinking"; then + shared_flag='$wl-G' + else + shared_flag='$wl-bM:SRE' + fi + shared_flag_aix='$wl-bM:SRE' + shared_flag_svr4='$wl-G' + fi + fi + + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-bexpall' + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + _LT_TAGVAR(always_export_symbols, $1)=yes + if test aix,yes = "$with_aix_soname,$aix_use_runtimelinking"; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + _LT_TAGVAR(allow_undefined_flag, $1)='-berok' + # Determine the default libpath from the value encoded in an + # empty executable. + _LT_SYS_MODULE_PATH_AIX([$1]) + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-blibpath:$libdir:'"$aix_libpath" + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs $wl'$no_entry_flag' $compiler_flags `if test -n "$allow_undefined_flag"; then func_echo_all "$wl$allow_undefined_flag"; else :; fi` $wl'$exp_sym_flag:\$export_symbols' '$shared_flag + else + if test ia64 = "$host_cpu"; then + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R $libdir:/usr/lib:/lib' + _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" + _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\$wl$no_entry_flag"' $compiler_flags $wl$allow_undefined_flag '"\$wl$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an + # empty executable. + _LT_SYS_MODULE_PATH_AIX([$1]) + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + _LT_TAGVAR(no_undefined_flag, $1)=' $wl-bernotok' + _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-berok' + if test yes = "$with_gnu_ld"; then + # We only use this code for GNU lds that support --whole-archive. + _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive$convenience $wl--no-whole-archive' + else + # Exported symbols can be pulled into shared objects from archives + _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' + fi + _LT_TAGVAR(archive_cmds_need_lc, $1)=yes + _LT_TAGVAR(archive_expsym_cmds, $1)='$RM -r $output_objdir/$realname.d~$MKDIR $output_objdir/$realname.d' + # -brtl affects multiple linker settings, -berok does not and is overridden later + compiler_flags_filtered='`func_echo_all "$compiler_flags " | $SED -e "s%-brtl\\([[, ]]\\)%-berok\\1%g"`' + if test svr4 != "$with_aix_soname"; then + # This is similar to how AIX traditionally builds its shared libraries. + _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$CC '$shared_flag_aix' -o $output_objdir/$realname.d/$soname $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$realname.d/$soname' + fi + if test aix != "$with_aix_soname"; then + _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$CC '$shared_flag_svr4' -o $output_objdir/$realname.d/$shared_archive_member_spec.o $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$STRIP -e $output_objdir/$realname.d/$shared_archive_member_spec.o~( func_echo_all "#! $soname($shared_archive_member_spec.o)"; if test shr_64 = "$shared_archive_member_spec"; then func_echo_all "# 64"; else func_echo_all "# 32"; fi; cat $export_symbols ) > $output_objdir/$realname.d/$shared_archive_member_spec.imp~$AR $AR_FLAGS $output_objdir/$soname $output_objdir/$realname.d/$shared_archive_member_spec.o $output_objdir/$realname.d/$shared_archive_member_spec.imp' + else + # used by -dlpreopen to get the symbols + _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$MV $output_objdir/$realname.d/$soname $output_objdir' + fi + _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$RM -r $output_objdir/$realname.d' + fi + fi + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='' + ;; + m68k) + _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_minus_L, $1)=yes + ;; + esac + ;; + + bsdi[[45]]*) + _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic + ;; + + cygwin* | mingw* | pw32* | cegcc*) + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++ or Intel C++ Compiler. + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + case $cc_basename in + cl* | icl*) + # Native MSVC or ICC + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_TAGVAR(always_export_symbols, $1)=yes + _LT_TAGVAR(file_list_spec, $1)='@' + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=.dll + # FIXME: Setting linknames here is a bad hack. + _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~linknames=' + _LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then + cp "$export_symbols" "$output_objdir/$soname.def"; + echo "$tool_output_objdir$soname.def" > "$output_objdir/$soname.exp"; + else + $SED -e '\''s/^/-link -EXPORT:/'\'' < $export_symbols > $output_objdir/$soname.exp; + fi~ + $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ + linknames=' + # The linker will not automatically build a static lib if we build a DLL. + # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' + _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' + _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1,DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols' + # Don't use ranlib + _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib' + _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~ + lt_tool_outputfile="@TOOL_OUTPUT@"~ + case $lt_outputfile in + *.exe|*.EXE) ;; + *) + lt_outputfile=$lt_outputfile.exe + lt_tool_outputfile=$lt_tool_outputfile.exe + ;; + esac~ + if test : != "$MANIFEST_TOOL" && test -f "$lt_outputfile.manifest"; then + $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; + $RM "$lt_outputfile.manifest"; + fi' + ;; + *) + # Assume MSVC and ICC wrapper + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=.dll + # FIXME: Setting linknames here is a bad hack. + _LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=' + # The linker will automatically build a .lib file if we build a DLL. + _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' + # FIXME: Should let the user specify the lib program. + _LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs' + _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + ;; + esac + ;; + + darwin* | rhapsody*) + _LT_DARWIN_LINKER_FEATURES($1) + ;; + + dgux*) + _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor + # support. Future versions do this automatically, but an explicit c++rt0.o + # does not break anything, and helps significantly (at the cost of a little + # extra space). + freebsd2.2*) + _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + # Unfortunately, older versions of FreeBSD 2 do not have this feature. + freebsd2.*) + _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_minus_L, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + # FreeBSD 3 and greater uses gcc -shared to do shared libraries. + freebsd* | dragonfly* | midnightbsd*) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + hpux9*) + if test yes = "$GCC"; then + _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared $pic_flag $wl+b $wl$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' + else + _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' + fi + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_TAGVAR(hardcode_direct, $1)=yes + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + _LT_TAGVAR(hardcode_minus_L, $1)=yes + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' + ;; + + hpux10*) + if test yes,no = "$GCC,$with_gnu_ld"; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + else + _LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' + fi + if test no = "$with_gnu_ld"; then + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_direct_absolute, $1)=yes + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + _LT_TAGVAR(hardcode_minus_L, $1)=yes + fi + ;; + + hpux11*) + if test yes,no = "$GCC,$with_gnu_ld"; then + case $host_cpu in + hppa*64*) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl+h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $wl+h $wl$soname $wl+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + else + case $host_cpu in + hppa*64*) + _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + m4_if($1, [], [ + # Older versions of the 11.00 compiler do not understand -b yet + # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does) + _LT_LINKER_OPTION([if $CC understands -b], + _LT_TAGVAR(lt_cv_prog_compiler__b, $1), [-b], + [_LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags'], + [_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'])], + [_LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags']) + ;; + esac + fi + if test no = "$with_gnu_ld"; then + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + + case $host_cpu in + hppa*64*|ia64*) + _LT_TAGVAR(hardcode_direct, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + *) + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_direct_absolute, $1)=yes + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + _LT_TAGVAR(hardcode_minus_L, $1)=yes + ;; + esac + fi + ;; + + irix5* | irix6* | nonstopux*) + if test yes = "$GCC"; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' + # Try to use the -exported_symbol ld option, if it does not + # work, assume that -exports_file does not work either and + # implicitly export all symbols. + # This should be the same for all languages, so no per-tag cache variable. + AC_CACHE_CHECK([whether the $host_os linker accepts -exported_symbol], + [lt_cv_irix_exported_symbol], + [save_LDFLAGS=$LDFLAGS + LDFLAGS="$LDFLAGS -shared $wl-exported_symbol ${wl}foo $wl-update_registry $wl/dev/null" + AC_LINK_IFELSE( + [AC_LANG_SOURCE( + [AC_LANG_CASE([C], [[int foo (void) { return 0; }]], + [C++], [[int foo (void) { return 0; }]], + [Fortran 77], [[ + subroutine foo + end]], + [Fortran], [[ + subroutine foo + end]])])], + [lt_cv_irix_exported_symbol=yes], + [lt_cv_irix_exported_symbol=no]) + LDFLAGS=$save_LDFLAGS]) + if test yes = "$lt_cv_irix_exported_symbol"; then + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations $wl-exports_file $wl$export_symbols -o $lib' + fi + _LT_TAGVAR(link_all_deplibs, $1)=no + else + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -exports_file $export_symbols -o $lib' + fi + _LT_TAGVAR(archive_cmds_need_lc, $1)='no' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_TAGVAR(inherit_rpath, $1)=yes + _LT_TAGVAR(link_all_deplibs, $1)=yes + ;; + + linux*) + case $cc_basename in + tcc*) + # Fabrice Bellard et al's Tiny C Compiler + _LT_TAGVAR(ld_shlibs, $1)=yes + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' + ;; + esac + ;; + + netbsd* | netbsdelf*-gnu) + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out + else + _LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF + fi + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + newsos6) + _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + *nto* | *qnx*) + ;; + + openbsd* | bitrig*) + if test -f /usr/libexec/ld.so; then + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_TAGVAR(hardcode_direct_absolute, $1)=yes + if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags $wl-retain-symbols-file,$export_symbols' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' + else + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' + fi + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + os2*) + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_minus_L, $1)=yes + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + shrext_cmds=.dll + _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ + $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ + $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ + $ECHO EXPORTS >> $output_objdir/$libname.def~ + emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~ + $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ + emximp -o $lib $output_objdir/$libname.def' + _LT_TAGVAR(archive_expsym_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ + $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ + $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ + $ECHO EXPORTS >> $output_objdir/$libname.def~ + prefix_cmds="$SED"~ + if test EXPORTS = "`$SED 1q $export_symbols`"; then + prefix_cmds="$prefix_cmds -e 1d"; + fi~ + prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~ + cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ + $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ + emximp -o $lib $output_objdir/$libname.def' + _LT_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' + _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + _LT_TAGVAR(file_list_spec, $1)='@' + ;; + + osf3*) + if test yes = "$GCC"; then + _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-expect_unresolved $wl\*' + _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' + else + _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' + _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' + fi + _LT_TAGVAR(archive_cmds_need_lc, $1)='no' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + ;; + + osf4* | osf5*) # as osf3* with the addition of -msym flag + if test yes = "$GCC"; then + _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-expect_unresolved $wl\*' + _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $pic_flag $libobjs $deplibs $compiler_flags $wl-msym $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' + else + _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' + _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ + $CC -shared$allow_undefined_flag $wl-input $wl$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib~$RM $lib.exp' + + # Both c and cxx compiler support -rpath directly + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' + fi + _LT_TAGVAR(archive_cmds_need_lc, $1)='no' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + ;; + + solaris*) + _LT_TAGVAR(no_undefined_flag, $1)=' -z defs' + if test yes = "$GCC"; then + wlarc='$wl' + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $wl-z ${wl}text $wl-h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -shared $pic_flag $wl-z ${wl}text $wl-M $wl$lib.exp $wl-h $wl$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' + else + case `$CC -V 2>&1` in + *"Compilers 5.0"*) + wlarc='' + _LT_TAGVAR(archive_cmds, $1)='$LD -G$allow_undefined_flag -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $LD -G$allow_undefined_flag -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' + ;; + *) + wlarc='$wl' + _LT_TAGVAR(archive_cmds, $1)='$CC -G$allow_undefined_flag -h $soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -G$allow_undefined_flag -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' + ;; + esac + fi + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + case $host_os in + solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; + *) + # The compiler driver will combine and reorder linker options, + # but understands '-z linker_flag'. GCC discards it without '$wl', + # but is careful enough not to reorder. + # Supported since Solaris 2.6 (maybe 2.5.1?) + if test yes = "$GCC"; then + _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl-z ${wl}allextract$convenience $wl-z ${wl}defaultextract' + else + _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' + fi + ;; + esac + _LT_TAGVAR(link_all_deplibs, $1)=yes + ;; + + sunos4*) + if test sequent = "$host_vendor"; then + # Use $CC to link under sequent, because it throws in some extra .o + # files that make .init and .fini sections work. + _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h $soname -o $lib $libobjs $deplibs $compiler_flags' + else + _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' + fi + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_minus_L, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + sysv4) + case $host_vendor in + sni) + _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true??? + ;; + siemens) + ## LD is ld it makes a PLAMLIB + ## CC just makes a GrossModule. + _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs' + _LT_TAGVAR(hardcode_direct, $1)=no + ;; + motorola) + _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie + ;; + esac + runpath_var='LD_RUN_PATH' + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + sysv4.3*) + _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + _LT_TAGVAR(ld_shlibs, $1)=yes + fi + ;; + + sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) + _LT_TAGVAR(no_undefined_flag, $1)='$wl-z,text' + _LT_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + runpath_var='LD_RUN_PATH' + + if test yes = "$GCC"; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + else + _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + sysv5* | sco3.2v5* | sco5v6*) + # Note: We CANNOT use -z defs as we might desire, because we do not + # link with -lc, and that would cause any symbols used from libc to + # always be unresolved, which means just about no library would + # ever link correctly. If we're not using GNU ld we use -z text + # though, which does catch some bad symbols but isn't as heavy-handed + # as -z defs. + _LT_TAGVAR(no_undefined_flag, $1)='$wl-z,text' + _LT_TAGVAR(allow_undefined_flag, $1)='$wl-z,nodefs' + _LT_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R,$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=':' + _LT_TAGVAR(link_all_deplibs, $1)=yes + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-Bexport' + runpath_var='LD_RUN_PATH' + + if test yes = "$GCC"; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + else + _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + uts4*) + _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + *) + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + esac + + if test sni = "$host_vendor"; then + case $host in + sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-Blargedynsym' + ;; + esac + fi + fi +]) +AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) +test no = "$_LT_TAGVAR(ld_shlibs, $1)" && can_build_shared=no + +_LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld + +_LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl +_LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl +_LT_DECL([], [extract_expsyms_cmds], [2], + [The commands to extract the exported symbol list from a shared archive]) + +# +# Do we need to explicitly link libc? +# +case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in +x|xyes) + # Assume -lc should be added + _LT_TAGVAR(archive_cmds_need_lc, $1)=yes + + if test yes,yes = "$GCC,$enable_shared"; then + case $_LT_TAGVAR(archive_cmds, $1) in + *'~'*) + # FIXME: we may have to deal with multi-command sequences. + ;; + '$CC '*) + # Test whether the compiler implicitly links with -lc since on some + # systems, -lgcc has to come before -lc. If gcc already passes -lc + # to ld, don't add -lc before -lgcc. + AC_CACHE_CHECK([whether -lc should be explicitly linked in], + [lt_cv_]_LT_TAGVAR(archive_cmds_need_lc, $1), + [$RM conftest* + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + if AC_TRY_EVAL(ac_compile) 2>conftest.err; then + soname=conftest + lib=conftest + libobjs=conftest.$ac_objext + deplibs= + wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) + pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1) + compiler_flags=-v + linker_flags=-v + verstring= + output_objdir=. + libname=conftest + lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1) + _LT_TAGVAR(allow_undefined_flag, $1)= + if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) + then + lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=no + else + lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=yes + fi + _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag + else + cat conftest.err 1>&5 + fi + $RM conftest* + ]) + _LT_TAGVAR(archive_cmds_need_lc, $1)=$lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1) + ;; + esac + fi + ;; +esac + +_LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0], + [Whether or not to add -lc for building shared libraries]) +_LT_TAGDECL([allow_libtool_libs_with_static_runtimes], + [enable_shared_with_static_runtimes], [0], + [Whether or not to disallow shared libs when runtime libs are static]) +_LT_TAGDECL([], [export_dynamic_flag_spec], [1], + [Compiler flag to allow reflexive dlopens]) +_LT_TAGDECL([], [whole_archive_flag_spec], [1], + [Compiler flag to generate shared objects directly from archives]) +_LT_TAGDECL([], [compiler_needs_object], [1], + [Whether the compiler copes with passing no objects directly]) +_LT_TAGDECL([], [old_archive_from_new_cmds], [2], + [Create an old-style archive from a shared archive]) +_LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2], + [Create a temporary old-style archive to link instead of a shared archive]) +_LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive]) +_LT_TAGDECL([], [archive_expsym_cmds], [2]) +_LT_TAGDECL([], [module_cmds], [2], + [Commands used to build a loadable module if different from building + a shared archive.]) +_LT_TAGDECL([], [module_expsym_cmds], [2]) +_LT_TAGDECL([], [with_gnu_ld], [1], + [Whether we are building with GNU ld or not]) +_LT_TAGDECL([], [allow_undefined_flag], [1], + [Flag that allows shared libraries with undefined symbols to be built]) +_LT_TAGDECL([], [no_undefined_flag], [1], + [Flag that enforces no undefined symbols]) +_LT_TAGDECL([], [hardcode_libdir_flag_spec], [1], + [Flag to hardcode $libdir into a binary during linking. + This must work even if $libdir does not exist]) +_LT_TAGDECL([], [hardcode_libdir_separator], [1], + [Whether we need a single "-rpath" flag with a separated argument]) +_LT_TAGDECL([], [hardcode_direct], [0], + [Set to "yes" if using DIR/libNAME$shared_ext during linking hardcodes + DIR into the resulting binary]) +_LT_TAGDECL([], [hardcode_direct_absolute], [0], + [Set to "yes" if using DIR/libNAME$shared_ext during linking hardcodes + DIR into the resulting binary and the resulting library dependency is + "absolute", i.e impossible to change by setting $shlibpath_var if the + library is relocated]) +_LT_TAGDECL([], [hardcode_minus_L], [0], + [Set to "yes" if using the -LDIR flag during linking hardcodes DIR + into the resulting binary]) +_LT_TAGDECL([], [hardcode_shlibpath_var], [0], + [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR + into the resulting binary]) +_LT_TAGDECL([], [hardcode_automatic], [0], + [Set to "yes" if building a shared library automatically hardcodes DIR + into the library and all subsequent libraries and executables linked + against it]) +_LT_TAGDECL([], [inherit_rpath], [0], + [Set to yes if linker adds runtime paths of dependent libraries + to runtime path list]) +_LT_TAGDECL([], [link_all_deplibs], [0], + [Whether libtool must link a program against all its dependency libraries]) +_LT_TAGDECL([], [always_export_symbols], [0], + [Set to "yes" if exported symbols are required]) +_LT_TAGDECL([], [export_symbols_cmds], [2], + [The commands to list exported symbols]) +_LT_TAGDECL([], [exclude_expsyms], [1], + [Symbols that should not be listed in the preloaded symbols]) +_LT_TAGDECL([], [include_expsyms], [1], + [Symbols that must always be exported]) +_LT_TAGDECL([], [prelink_cmds], [2], + [Commands necessary for linking programs (against libraries) with templates]) +_LT_TAGDECL([], [postlink_cmds], [2], + [Commands necessary for finishing linking programs]) +_LT_TAGDECL([], [file_list_spec], [1], + [Specify filename containing input files]) +dnl FIXME: Not yet implemented +dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1], +dnl [Compiler flag to generate thread safe objects]) +])# _LT_LINKER_SHLIBS + + +# _LT_LANG_C_CONFIG([TAG]) +# ------------------------ +# Ensure that the configuration variables for a C compiler are suitably +# defined. These variables are subsequently used by _LT_CONFIG to write +# the compiler configuration to 'libtool'. +m4_defun([_LT_LANG_C_CONFIG], +[m4_require([_LT_DECL_EGREP])dnl +lt_save_CC=$CC +AC_LANG_PUSH(C) + +# Source file extension for C test sources. +ac_ext=c + +# Object file extension for compiled C test sources. +objext=o +_LT_TAGVAR(objext, $1)=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="int some_variable = 0;" + +# Code to be used in simple link tests +lt_simple_link_test_code='int main(){return(0);}' + +_LT_TAG_COMPILER +# Save the default compiler, since it gets overwritten when the other +# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. +compiler_DEFAULT=$CC + +# save warnings/boilerplate of simple test code +_LT_COMPILER_BOILERPLATE +_LT_LINKER_BOILERPLATE + +## CAVEAT EMPTOR: +## There is no encapsulation within the following macros, do not change +## the running order or otherwise move them around unless you know exactly +## what you are doing... +if test -n "$compiler"; then + _LT_COMPILER_NO_RTTI($1) + _LT_COMPILER_PIC($1) + _LT_COMPILER_C_O($1) + _LT_COMPILER_FILE_LOCKS($1) + _LT_LINKER_SHLIBS($1) + _LT_SYS_DYNAMIC_LINKER($1) + _LT_LINKER_HARDCODE_LIBPATH($1) + LT_SYS_DLOPEN_SELF + _LT_CMD_STRIPLIB + + # Report what library types will actually be built + AC_MSG_CHECKING([if libtool supports shared libraries]) + AC_MSG_RESULT([$can_build_shared]) + + AC_MSG_CHECKING([whether to build shared libraries]) + test no = "$can_build_shared" && enable_shared=no + + # On AIX, shared libraries and static libraries use the same namespace, and + # are all built from PIC. + case $host_os in + aix3*) + test yes = "$enable_shared" && enable_static=no + if test -n "$RANLIB"; then + archive_cmds="$archive_cmds~\$RANLIB \$lib" + postinstall_cmds='$RANLIB $lib' + fi + ;; + + aix[[4-9]]*) + if test ia64 != "$host_cpu"; then + case $enable_shared,$with_aix_soname,$aix_use_runtimelinking in + yes,aix,yes) ;; # shared object as lib.so file only + yes,svr4,*) ;; # shared object as lib.so archive member only + yes,*) enable_static=no ;; # shared object in lib.a archive as well + esac + fi + ;; + esac + AC_MSG_RESULT([$enable_shared]) + + AC_MSG_CHECKING([whether to build static libraries]) + # Make sure either enable_shared or enable_static is yes. + test yes = "$enable_shared" || enable_static=yes + AC_MSG_RESULT([$enable_static]) + + _LT_CONFIG($1) +fi +AC_LANG_POP +CC=$lt_save_CC +])# _LT_LANG_C_CONFIG + + +# _LT_LANG_CXX_CONFIG([TAG]) +# -------------------------- +# Ensure that the configuration variables for a C++ compiler are suitably +# defined. These variables are subsequently used by _LT_CONFIG to write +# the compiler configuration to 'libtool'. +m4_defun([_LT_LANG_CXX_CONFIG], +[m4_require([_LT_FILEUTILS_DEFAULTS])dnl +m4_require([_LT_DECL_EGREP])dnl +m4_require([_LT_PATH_MANIFEST_TOOL])dnl +if test -n "$CXX" && ( test no != "$CXX" && + ( (test g++ = "$CXX" && `g++ -v >/dev/null 2>&1` ) || + (test g++ != "$CXX"))); then + AC_PROG_CXXCPP +else + _lt_caught_CXX_error=yes +fi + +AC_LANG_PUSH(C++) +_LT_TAGVAR(archive_cmds_need_lc, $1)=no +_LT_TAGVAR(allow_undefined_flag, $1)= +_LT_TAGVAR(always_export_symbols, $1)=no +_LT_TAGVAR(archive_expsym_cmds, $1)= +_LT_TAGVAR(compiler_needs_object, $1)=no +_LT_TAGVAR(export_dynamic_flag_spec, $1)= +_LT_TAGVAR(hardcode_direct, $1)=no +_LT_TAGVAR(hardcode_direct_absolute, $1)=no +_LT_TAGVAR(hardcode_libdir_flag_spec, $1)= +_LT_TAGVAR(hardcode_libdir_separator, $1)= +_LT_TAGVAR(hardcode_minus_L, $1)=no +_LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported +_LT_TAGVAR(hardcode_automatic, $1)=no +_LT_TAGVAR(inherit_rpath, $1)=no +_LT_TAGVAR(module_cmds, $1)= +_LT_TAGVAR(module_expsym_cmds, $1)= +_LT_TAGVAR(link_all_deplibs, $1)=unknown +_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds +_LT_TAGVAR(reload_flag, $1)=$reload_flag +_LT_TAGVAR(reload_cmds, $1)=$reload_cmds +_LT_TAGVAR(no_undefined_flag, $1)= +_LT_TAGVAR(whole_archive_flag_spec, $1)= +_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no + +# Source file extension for C++ test sources. +ac_ext=cpp + +# Object file extension for compiled C++ test sources. +objext=o +_LT_TAGVAR(objext, $1)=$objext + +# No sense in running all these tests if we already determined that +# the CXX compiler isn't working. Some variables (like enable_shared) +# are currently assumed to apply to all compilers on this platform, +# and will be corrupted by setting them based on a non-working compiler. +if test yes != "$_lt_caught_CXX_error"; then + # Code to be used in simple compile tests + lt_simple_compile_test_code="int some_variable = 0;" + + # Code to be used in simple link tests + lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }' + + # ltmain only uses $CC for tagged configurations so make sure $CC is set. + _LT_TAG_COMPILER + + # save warnings/boilerplate of simple test code + _LT_COMPILER_BOILERPLATE + _LT_LINKER_BOILERPLATE + + # Allow CC to be a program name with arguments. + lt_save_CC=$CC + lt_save_CFLAGS=$CFLAGS + lt_save_LD=$LD + lt_save_GCC=$GCC + GCC=$GXX + lt_save_with_gnu_ld=$with_gnu_ld + lt_save_path_LD=$lt_cv_path_LD + if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then + lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx + else + $as_unset lt_cv_prog_gnu_ld + fi + if test -n "${lt_cv_path_LDCXX+set}"; then + lt_cv_path_LD=$lt_cv_path_LDCXX + else + $as_unset lt_cv_path_LD + fi + test -z "${LDCXX+set}" || LD=$LDCXX + CC=${CXX-"c++"} + CFLAGS=$CXXFLAGS + compiler=$CC + _LT_TAGVAR(compiler, $1)=$CC + _LT_CC_BASENAME([$compiler]) + + if test -n "$compiler"; then + # We don't want -fno-exception when compiling C++ code, so set the + # no_builtin_flag separately + if test yes = "$GXX"; then + _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' + else + _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= + fi + + if test yes = "$GXX"; then + # Set up default GNU C++ configuration + + LT_PATH_LD + + # Check if GNU C++ uses GNU ld as the underlying linker, since the + # archiving commands below assume that GNU ld is being used. + if test yes = "$with_gnu_ld"; then + _LT_TAGVAR(archive_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' + + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' + + # If archive_cmds runs LD, not CC, wlarc should be empty + # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to + # investigate it a little bit more. (MM) + wlarc='$wl' + + # ancient GNU ld didn't support --whole-archive et. al. + if eval "`$CC -print-prog-name=ld` --help 2>&1" | + $GREP 'no-whole-archive' > /dev/null; then + _LT_TAGVAR(whole_archive_flag_spec, $1)=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive' + else + _LT_TAGVAR(whole_archive_flag_spec, $1)= + fi + else + with_gnu_ld=no + wlarc= + + # A generic and very simple default shared library creation + # command for GNU C++ for the case where it uses the native + # linker, instead of GNU ld. If possible, this setting should + # overridden to take advantage of the native linker features on + # the platform it is being used on. + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' + fi + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " \-L"' + + else + GXX=no + with_gnu_ld=no + wlarc= + fi + + # PORTME: fill in a description of your system's C++ link characteristics + AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) + _LT_TAGVAR(ld_shlibs, $1)=yes + case $host_os in + aix3*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + aix[[4-9]]*) + if test ia64 = "$host_cpu"; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag= + else + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # have runtime linking enabled, and use it for executables. + # For shared libraries, we enable/disable runtime linking + # depending on the kind of the shared library created - + # when "with_aix_soname,aix_use_runtimelinking" is: + # "aix,no" lib.a(lib.so.V) shared, rtl:no, for executables + # "aix,yes" lib.so shared, rtl:yes, for executables + # lib.a static archive + # "both,no" lib.so.V(shr.o) shared, rtl:yes + # lib.a(lib.so.V) shared, rtl:no, for executables + # "both,yes" lib.so.V(shr.o) shared, rtl:yes, for executables + # lib.a(lib.so.V) shared, rtl:no + # "svr4,*" lib.so.V(shr.o) shared, rtl:yes, for executables + # lib.a static archive + case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) + for ld_flag in $LDFLAGS; do + case $ld_flag in + *-brtl*) + aix_use_runtimelinking=yes + break + ;; + esac + done + if test svr4,no = "$with_aix_soname,$aix_use_runtimelinking"; then + # With aix-soname=svr4, we create the lib.so.V shared archives only, + # so we don't have lib.a shared libs to link our executables. + # We have to force runtime linking in this case. + aix_use_runtimelinking=yes + LDFLAGS="$LDFLAGS -Wl,-brtl" + fi + ;; + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + _LT_TAGVAR(archive_cmds, $1)='' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_direct_absolute, $1)=yes + _LT_TAGVAR(hardcode_libdir_separator, $1)=':' + _LT_TAGVAR(link_all_deplibs, $1)=yes + _LT_TAGVAR(file_list_spec, $1)='$wl-f,' + case $with_aix_soname,$aix_use_runtimelinking in + aix,*) ;; # no import file + svr4,* | *,yes) # use import file + # The Import File defines what to hardcode. + _LT_TAGVAR(hardcode_direct, $1)=no + _LT_TAGVAR(hardcode_direct_absolute, $1)=no + ;; + esac + + if test yes = "$GXX"; then + case $host_os in aix4.[[012]]|aix4.[[012]].*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`$CC -print-prog-name=collect2` + if test -f "$collect2name" && + strings "$collect2name" | $GREP resolve_lib_name >/dev/null + then + # We have reworked collect2 + : + else + # We have old collect2 + _LT_TAGVAR(hardcode_direct, $1)=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + _LT_TAGVAR(hardcode_minus_L, $1)=yes + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)= + fi + esac + shared_flag='-shared' + if test yes = "$aix_use_runtimelinking"; then + shared_flag=$shared_flag' $wl-G' + fi + # Need to ensure runtime linking is disabled for the traditional + # shared library, or the linker may eventually find shared libraries + # /with/ Import File - we do not want to mix them. + shared_flag_aix='-shared' + shared_flag_svr4='-shared $wl-G' + else + # not using gcc + if test ia64 = "$host_cpu"; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test yes = "$aix_use_runtimelinking"; then + shared_flag='$wl-G' + else + shared_flag='$wl-bM:SRE' + fi + shared_flag_aix='$wl-bM:SRE' + shared_flag_svr4='$wl-G' + fi + fi + + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-bexpall' + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to + # export. + _LT_TAGVAR(always_export_symbols, $1)=yes + if test aix,yes = "$with_aix_soname,$aix_use_runtimelinking"; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + # The "-G" linker flag allows undefined symbols. + _LT_TAGVAR(no_undefined_flag, $1)='-bernotok' + # Determine the default libpath from the value encoded in an empty + # executable. + _LT_SYS_MODULE_PATH_AIX([$1]) + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-blibpath:$libdir:'"$aix_libpath" + + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs $wl'$no_entry_flag' $compiler_flags `if test -n "$allow_undefined_flag"; then func_echo_all "$wl$allow_undefined_flag"; else :; fi` $wl'$exp_sym_flag:\$export_symbols' '$shared_flag + else + if test ia64 = "$host_cpu"; then + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R $libdir:/usr/lib:/lib' + _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" + _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\$wl$no_entry_flag"' $compiler_flags $wl$allow_undefined_flag '"\$wl$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an + # empty executable. + _LT_SYS_MODULE_PATH_AIX([$1]) + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + _LT_TAGVAR(no_undefined_flag, $1)=' $wl-bernotok' + _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-berok' + if test yes = "$with_gnu_ld"; then + # We only use this code for GNU lds that support --whole-archive. + _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive$convenience $wl--no-whole-archive' + else + # Exported symbols can be pulled into shared objects from archives + _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' + fi + _LT_TAGVAR(archive_cmds_need_lc, $1)=yes + _LT_TAGVAR(archive_expsym_cmds, $1)='$RM -r $output_objdir/$realname.d~$MKDIR $output_objdir/$realname.d' + # -brtl affects multiple linker settings, -berok does not and is overridden later + compiler_flags_filtered='`func_echo_all "$compiler_flags " | $SED -e "s%-brtl\\([[, ]]\\)%-berok\\1%g"`' + if test svr4 != "$with_aix_soname"; then + # This is similar to how AIX traditionally builds its shared + # libraries. Need -bnortl late, we may have -brtl in LDFLAGS. + _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$CC '$shared_flag_aix' -o $output_objdir/$realname.d/$soname $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$realname.d/$soname' + fi + if test aix != "$with_aix_soname"; then + _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$CC '$shared_flag_svr4' -o $output_objdir/$realname.d/$shared_archive_member_spec.o $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$STRIP -e $output_objdir/$realname.d/$shared_archive_member_spec.o~( func_echo_all "#! $soname($shared_archive_member_spec.o)"; if test shr_64 = "$shared_archive_member_spec"; then func_echo_all "# 64"; else func_echo_all "# 32"; fi; cat $export_symbols ) > $output_objdir/$realname.d/$shared_archive_member_spec.imp~$AR $AR_FLAGS $output_objdir/$soname $output_objdir/$realname.d/$shared_archive_member_spec.o $output_objdir/$realname.d/$shared_archive_member_spec.imp' + else + # used by -dlpreopen to get the symbols + _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$MV $output_objdir/$realname.d/$soname $output_objdir' + fi + _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$RM -r $output_objdir/$realname.d' + fi + fi + ;; + + beos*) + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + chorus*) + case $cc_basename in + *) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + + cygwin* | mingw* | pw32* | cegcc*) + case $GXX,$cc_basename in + ,cl* | no,cl* | ,icl* | no,icl*) + # Native MSVC or ICC + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_TAGVAR(always_export_symbols, $1)=yes + _LT_TAGVAR(file_list_spec, $1)='@' + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=.dll + # FIXME: Setting linknames here is a bad hack. + _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~linknames=' + _LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then + cp "$export_symbols" "$output_objdir/$soname.def"; + echo "$tool_output_objdir$soname.def" > "$output_objdir/$soname.exp"; + else + $SED -e '\''s/^/-link -EXPORT:/'\'' < $export_symbols > $output_objdir/$soname.exp; + fi~ + $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ + linknames=' + # The linker will not automatically build a static lib if we build a DLL. + # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' + _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + # Don't use ranlib + _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib' + _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~ + lt_tool_outputfile="@TOOL_OUTPUT@"~ + case $lt_outputfile in + *.exe|*.EXE) ;; + *) + lt_outputfile=$lt_outputfile.exe + lt_tool_outputfile=$lt_tool_outputfile.exe + ;; + esac~ + func_to_tool_file "$lt_outputfile"~ + if test : != "$MANIFEST_TOOL" && test -f "$lt_outputfile.manifest"; then + $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; + $RM "$lt_outputfile.manifest"; + fi' + ;; + *) + # g++ + # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, + # as there is no search path for DLLs. + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-all-symbols' + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_TAGVAR(always_export_symbols, $1)=no + _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + + if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + # If the export-symbols file already is a .def file, use it as + # is; otherwise, prepend EXPORTS... + _LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + darwin* | rhapsody*) + _LT_DARWIN_LINKER_FEATURES($1) + ;; + + os2*) + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_minus_L, $1)=yes + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + shrext_cmds=.dll + _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ + $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ + $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ + $ECHO EXPORTS >> $output_objdir/$libname.def~ + emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~ + $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ + emximp -o $lib $output_objdir/$libname.def' + _LT_TAGVAR(archive_expsym_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ + $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ + $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ + $ECHO EXPORTS >> $output_objdir/$libname.def~ + prefix_cmds="$SED"~ + if test EXPORTS = "`$SED 1q $export_symbols`"; then + prefix_cmds="$prefix_cmds -e 1d"; + fi~ + prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~ + cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ + $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ + emximp -o $lib $output_objdir/$libname.def' + _LT_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' + _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + _LT_TAGVAR(file_list_spec, $1)='@' + ;; + + dgux*) + case $cc_basename in + ec++*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + ghcx*) + # Green Hills C++ Compiler + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + + freebsd2.*) + # C++ shared libraries reported to be fairly broken before + # switch to ELF + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + + freebsd-elf*) + _LT_TAGVAR(archive_cmds_need_lc, $1)=no + ;; + + freebsd* | dragonfly* | midnightbsd*) + # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF + # conventions + _LT_TAGVAR(ld_shlibs, $1)=yes + ;; + + haiku*) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + _LT_TAGVAR(link_all_deplibs, $1)=yes + ;; + + hpux9*) + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, + # but as the default + # location of the library. + + case $cc_basename in + CC*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + aCC*) + _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b $wl+b $wl$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP " \-L"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' + ;; + *) + if test yes = "$GXX"; then + _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag $wl+b $wl$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' + else + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + + hpux10*|hpux11*) + if test no = "$with_gnu_ld"; then + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + + case $host_cpu in + hppa*64*|ia64*) + ;; + *) + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' + ;; + esac + fi + case $host_cpu in + hppa*64*|ia64*) + _LT_TAGVAR(hardcode_direct, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + *) + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_direct_absolute, $1)=yes + _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, + # but as the default + # location of the library. + ;; + esac + + case $cc_basename in + CC*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + aCC*) + case $host_cpu in + hppa*64*) + _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + ia64*) + _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + *) + _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + esac + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP " \-L"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' + ;; + *) + if test yes = "$GXX"; then + if test no = "$with_gnu_ld"; then + case $host_cpu in + hppa*64*) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC $wl+h $wl$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + ia64*) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag $wl+h $wl$soname $wl+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + *) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + esac + fi + else + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + + interix[[3-9]]*) + _LT_TAGVAR(hardcode_direct, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' + # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. + # Instead, shared libraries are loaded at an image base (0x10000000 by + # default) and relocated if they conflict, which is a slow very memory + # consuming and fragmenting process. To avoid this, we pick a random, + # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link + # time. Moving up from 0x10000000 also allows more sbrk(2) space. + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$SED "s|^|_|" $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--retain-symbols-file,$output_objdir/$soname.expsym $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + ;; + irix5* | irix6*) + case $cc_basename in + CC*) + # SGI C++ + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' + + # Archives containing C++ object files must be created using + # "CC -ar", where "CC" is the IRIX C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs' + ;; + *) + if test yes = "$GXX"; then + if test no = "$with_gnu_ld"; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' + else + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` -o $lib' + fi + fi + _LT_TAGVAR(link_all_deplibs, $1)=yes + ;; + esac + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_TAGVAR(inherit_rpath, $1)=yes + ;; + + linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) + case $cc_basename in + KCC*) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\$tempext\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\$tempext\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib $wl-retain-symbols-file,$export_symbols; mv \$templib $lib' + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' + + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' + + # Archives containing C++ object files must be created using + # "CC -Bstatic", where "CC" is the KAI C++ compiler. + _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' + ;; + icpc* | ecpc* ) + # Intel C++ + with_gnu_ld=yes + # version 8.0 and above of icpc choke on multiply defined symbols + # if we add $predep_objects and $postdep_objects, however 7.1 and + # earlier do not add the objects themselves. + case `$CC -V 2>&1` in + *"Version 7."*) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' + ;; + *) # Version 8.0 or newer + tmp_idyn= + case $host_cpu in + ia64*) tmp_idyn=' -i_dynamic';; + esac + _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' + ;; + esac + _LT_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' + _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive$convenience $wl--no-whole-archive' + ;; + pgCC* | pgcpp*) + # Portland Group C++ compiler + case `$CC -V` in + *pgCC\ [[1-5]].* | *pgcpp\ [[1-5]].*) + _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~ + rm -rf $tpldir~ + $CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~ + compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"' + _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~ + rm -rf $tpldir~ + $CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~ + $AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~ + $RANLIB $oldlib' + _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~ + rm -rf $tpldir~ + $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ + $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~ + rm -rf $tpldir~ + $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ + $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' + ;; + *) # Version 6 and above use weak symbols + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' + ;; + esac + + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl--rpath $wl$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' + _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' + ;; + cxx*) + # Compaq C++ + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib $wl-retain-symbols-file $wl$export_symbols' + + runpath_var=LD_RUN_PATH + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed' + ;; + xl* | mpixl* | bgxl*) + # IBM XL 8.0 on PPC, with GNU ld + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' + _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + if test yes = "$supports_anon_versioning"; then + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + echo "local: *; };" >> $output_objdir/$libname.ver~ + $CC -qmkshrobj $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-version-script $wl$output_objdir/$libname.ver -o $lib' + fi + ;; + *) + case `$CC -V 2>&1 | $SED 5q` in + *Sun\ C*) + # Sun C++ 5.9 + _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' + _LT_TAGVAR(archive_cmds, $1)='$CC -G$allow_undefined_flag -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G$allow_undefined_flag -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-retain-symbols-file $wl$export_symbols' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' + _LT_TAGVAR(compiler_needs_object, $1)=yes + + # Not sure whether something based on + # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 + # would be better. + output_verbose_link_cmd='func_echo_all' + + # Archives containing C++ object files must be created using + # "CC -xar", where "CC" is the Sun C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' + ;; + esac + ;; + esac + ;; + + lynxos*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + + m88k*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + + mvs*) + case $cc_basename in + cxx*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + + netbsd*) + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' + wlarc= + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + fi + # Workaround some broken pre-1.5 toolchains + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' + ;; + + *nto* | *qnx*) + _LT_TAGVAR(ld_shlibs, $1)=yes + ;; + + openbsd* | bitrig*) + if test -f /usr/libexec/ld.so; then + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_TAGVAR(hardcode_direct_absolute, $1)=yes + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`"; then + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-retain-symbols-file,$export_symbols -o $lib' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' + _LT_TAGVAR(whole_archive_flag_spec, $1)=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive' + fi + output_verbose_link_cmd=func_echo_all + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + osf3* | osf4* | osf5*) + case $cc_basename in + KCC*) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\$tempext\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + + # Archives containing C++ object files must be created using + # the KAI C++ compiler. + case $host in + osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;; + *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;; + esac + ;; + RCC*) + # Rational C++ 2.4.1 + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + cxx*) + case $host in + osf3*) + _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-expect_unresolved $wl\*' + _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $soname `test -n "$verstring" && func_echo_all "$wl-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' + ;; + *) + _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' + _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ + echo "-hidden">> $lib.exp~ + $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname $wl-input $wl$lib.exp `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib~ + $RM $lib.exp' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' + ;; + esac + + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' + ;; + *) + if test yes,no = "$GXX,$with_gnu_ld"; then + _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-expect_unresolved $wl\*' + case $host in + osf3*) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' + ;; + *) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-msym $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' + ;; + esac + + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " \-L"' + + else + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + + psos*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + + sunos4*) + case $cc_basename in + CC*) + # Sun C++ 4.x + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + lcc*) + # Lucid + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + + solaris*) + case $cc_basename in + CC* | sunCC*) + # Sun C++ 4.2, 5.x and Centerline C++ + _LT_TAGVAR(archive_cmds_need_lc,$1)=yes + _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' + _LT_TAGVAR(archive_cmds, $1)='$CC -G$allow_undefined_flag -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -G$allow_undefined_flag $wl-M $wl$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' + + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + case $host_os in + solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; + *) + # The compiler driver will combine and reorder linker options, + # but understands '-z linker_flag'. + # Supported since Solaris 2.6 (maybe 2.5.1?) + _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' + ;; + esac + _LT_TAGVAR(link_all_deplibs, $1)=yes + + output_verbose_link_cmd='func_echo_all' + + # Archives containing C++ object files must be created using + # "CC -xar", where "CC" is the Sun C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' + ;; + gcx*) + # Green Hills C++ Compiler + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-h $wl$soname -o $lib' + + # The C++ compiler must be used to create the archive. + _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs' + ;; + *) + # GNU C++ compiler with Solaris linker + if test yes,no = "$GXX,$with_gnu_ld"; then + _LT_TAGVAR(no_undefined_flag, $1)=' $wl-z ${wl}defs' + if $CC --version | $GREP -v '^2\.7' > /dev/null; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-h $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -shared $pic_flag -nostdlib $wl-M $wl$lib.exp $wl-h $wl$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " \-L"' + else + # g++ 2.7 appears to require '-G' NOT '-shared' on this + # platform. + _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-h $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -G -nostdlib $wl-M $wl$lib.exp $wl-h $wl$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " \-L"' + fi + + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R $wl$libdir' + case $host_os in + solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; + *) + _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl-z ${wl}allextract$convenience $wl-z ${wl}defaultextract' + ;; + esac + fi + ;; + esac + ;; + + sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) + _LT_TAGVAR(no_undefined_flag, $1)='$wl-z,text' + _LT_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + runpath_var='LD_RUN_PATH' + + case $cc_basename in + CC*) + _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + ;; + + sysv5* | sco3.2v5* | sco5v6*) + # Note: We CANNOT use -z defs as we might desire, because we do not + # link with -lc, and that would cause any symbols used from libc to + # always be unresolved, which means just about no library would + # ever link correctly. If we're not using GNU ld we use -z text + # though, which does catch some bad symbols but isn't as heavy-handed + # as -z defs. + _LT_TAGVAR(no_undefined_flag, $1)='$wl-z,text' + _LT_TAGVAR(allow_undefined_flag, $1)='$wl-z,nodefs' + _LT_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R,$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=':' + _LT_TAGVAR(link_all_deplibs, $1)=yes + _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-Bexport' + runpath_var='LD_RUN_PATH' + + case $cc_basename in + CC*) + _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(old_archive_cmds, $1)='$CC -Tprelink_objects $oldobjs~ + '"$_LT_TAGVAR(old_archive_cmds, $1)" + _LT_TAGVAR(reload_cmds, $1)='$CC -Tprelink_objects $reload_objs~ + '"$_LT_TAGVAR(reload_cmds, $1)" + ;; + *) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + ;; + + tandem*) + case $cc_basename in + NCC*) + # NonStop-UX NCC 3.20 + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + + vxworks*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + + *) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + esac + + AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) + test no = "$_LT_TAGVAR(ld_shlibs, $1)" && can_build_shared=no + + _LT_TAGVAR(GCC, $1)=$GXX + _LT_TAGVAR(LD, $1)=$LD + + ## CAVEAT EMPTOR: + ## There is no encapsulation within the following macros, do not change + ## the running order or otherwise move them around unless you know exactly + ## what you are doing... + _LT_SYS_HIDDEN_LIBDEPS($1) + _LT_COMPILER_PIC($1) + _LT_COMPILER_C_O($1) + _LT_COMPILER_FILE_LOCKS($1) + _LT_LINKER_SHLIBS($1) + _LT_SYS_DYNAMIC_LINKER($1) + _LT_LINKER_HARDCODE_LIBPATH($1) + + _LT_CONFIG($1) + fi # test -n "$compiler" + + CC=$lt_save_CC + CFLAGS=$lt_save_CFLAGS + LDCXX=$LD + LD=$lt_save_LD + GCC=$lt_save_GCC + with_gnu_ld=$lt_save_with_gnu_ld + lt_cv_path_LDCXX=$lt_cv_path_LD + lt_cv_path_LD=$lt_save_path_LD + lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld + lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld +fi # test yes != "$_lt_caught_CXX_error" + +AC_LANG_POP +])# _LT_LANG_CXX_CONFIG + + +# _LT_FUNC_STRIPNAME_CNF +# ---------------------- +# func_stripname_cnf prefix suffix name +# strip PREFIX and SUFFIX off of NAME. +# PREFIX and SUFFIX must not contain globbing or regex special +# characters, hashes, percent signs, but SUFFIX may contain a leading +# dot (in which case that matches only a dot). +# +# This function is identical to the (non-XSI) version of func_stripname, +# except this one can be used by m4 code that may be executed by configure, +# rather than the libtool script. +m4_defun([_LT_FUNC_STRIPNAME_CNF],[dnl +AC_REQUIRE([_LT_DECL_SED]) +AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH]) +func_stripname_cnf () +{ + case @S|@2 in + .*) func_stripname_result=`$ECHO "@S|@3" | $SED "s%^@S|@1%%; s%\\\\@S|@2\$%%"`;; + *) func_stripname_result=`$ECHO "@S|@3" | $SED "s%^@S|@1%%; s%@S|@2\$%%"`;; + esac +} # func_stripname_cnf +])# _LT_FUNC_STRIPNAME_CNF + + +# _LT_SYS_HIDDEN_LIBDEPS([TAGNAME]) +# --------------------------------- +# Figure out "hidden" library dependencies from verbose +# compiler output when linking a shared library. +# Parse the compiler output and extract the necessary +# objects, libraries and library flags. +m4_defun([_LT_SYS_HIDDEN_LIBDEPS], +[m4_require([_LT_FILEUTILS_DEFAULTS])dnl +AC_REQUIRE([_LT_FUNC_STRIPNAME_CNF])dnl +# Dependencies to place before and after the object being linked: +_LT_TAGVAR(predep_objects, $1)= +_LT_TAGVAR(postdep_objects, $1)= +_LT_TAGVAR(predeps, $1)= +_LT_TAGVAR(postdeps, $1)= +_LT_TAGVAR(compiler_lib_search_path, $1)= + +dnl we can't use the lt_simple_compile_test_code here, +dnl because it contains code intended for an executable, +dnl not a library. It's possible we should let each +dnl tag define a new lt_????_link_test_code variable, +dnl but it's only used here... +m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF +int a; +void foo (void) { a = 0; } +_LT_EOF +], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF +class Foo +{ +public: + Foo (void) { a = 0; } +private: + int a; +}; +_LT_EOF +], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF + subroutine foo + implicit none + integer*4 a + a=0 + return + end +_LT_EOF +], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF + subroutine foo + implicit none + integer a + a=0 + return + end +_LT_EOF +], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF +public class foo { + private int a; + public void bar (void) { + a = 0; + } +}; +_LT_EOF +], [$1], [GO], [cat > conftest.$ac_ext <<_LT_EOF +package foo +func foo() { +} +_LT_EOF +]) + +_lt_libdeps_save_CFLAGS=$CFLAGS +case "$CC $CFLAGS " in #( +*\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;; +*\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;; +*\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;; +esac + +dnl Parse the compiler output and extract the necessary +dnl objects, libraries and library flags. +if AC_TRY_EVAL(ac_compile); then + # Parse the compiler output and extract the necessary + # objects, libraries and library flags. + + # Sentinel used to keep track of whether or not we are before + # the conftest object file. + pre_test_object_deps_done=no + + for p in `eval "$output_verbose_link_cmd"`; do + case $prev$p in + + -L* | -R* | -l*) + # Some compilers place space between "-{L,R}" and the path. + # Remove the space. + if test x-L = "$p" || + test x-R = "$p"; then + prev=$p + continue + fi + + # Expand the sysroot to ease extracting the directories later. + if test -z "$prev"; then + case $p in + -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;; + -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;; + -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;; + esac + fi + case $p in + =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;; + esac + if test no = "$pre_test_object_deps_done"; then + case $prev in + -L | -R) + # Internal compiler library paths should come after those + # provided the user. The postdeps already come after the + # user supplied libs so there is no need to process them. + if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then + _LT_TAGVAR(compiler_lib_search_path, $1)=$prev$p + else + _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} $prev$p" + fi + ;; + # The "-l" case would never come before the object being + # linked, so don't bother handling this case. + esac + else + if test -z "$_LT_TAGVAR(postdeps, $1)"; then + _LT_TAGVAR(postdeps, $1)=$prev$p + else + _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} $prev$p" + fi + fi + prev= + ;; + + *.lto.$objext) ;; # Ignore GCC LTO objects + *.$objext) + # This assumes that the test object file only shows up + # once in the compiler output. + if test "$p" = "conftest.$objext"; then + pre_test_object_deps_done=yes + continue + fi + + if test no = "$pre_test_object_deps_done"; then + if test -z "$_LT_TAGVAR(predep_objects, $1)"; then + _LT_TAGVAR(predep_objects, $1)=$p + else + _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p" + fi + else + if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then + _LT_TAGVAR(postdep_objects, $1)=$p + else + _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p" + fi + fi + ;; + + *) ;; # Ignore the rest. + + esac + done + + # Clean up. + rm -f a.out a.exe +else + echo "libtool.m4: error: problem compiling $1 test program" +fi + +$RM -f confest.$objext +CFLAGS=$_lt_libdeps_save_CFLAGS + +# PORTME: override above test on systems where it is broken +m4_if([$1], [CXX], +[case $host_os in +interix[[3-9]]*) + # Interix 3.5 installs completely hosed .la files for C++, so rather than + # hack all around it, let's just trust "g++" to DTRT. + _LT_TAGVAR(predep_objects,$1)= + _LT_TAGVAR(postdep_objects,$1)= + _LT_TAGVAR(postdeps,$1)= + ;; +esac +]) + +case " $_LT_TAGVAR(postdeps, $1) " in +*" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;; +esac + _LT_TAGVAR(compiler_lib_search_dirs, $1)= +if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then + _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | $SED -e 's! -L! !g' -e 's!^ !!'` +fi +_LT_TAGDECL([], [compiler_lib_search_dirs], [1], + [The directories searched by this compiler when creating a shared library]) +_LT_TAGDECL([], [predep_objects], [1], + [Dependencies to place before and after the objects being linked to + create a shared library]) +_LT_TAGDECL([], [postdep_objects], [1]) +_LT_TAGDECL([], [predeps], [1]) +_LT_TAGDECL([], [postdeps], [1]) +_LT_TAGDECL([], [compiler_lib_search_path], [1], + [The library search path used internally by the compiler when linking + a shared library]) +])# _LT_SYS_HIDDEN_LIBDEPS + + +# _LT_LANG_F77_CONFIG([TAG]) +# -------------------------- +# Ensure that the configuration variables for a Fortran 77 compiler are +# suitably defined. These variables are subsequently used by _LT_CONFIG +# to write the compiler configuration to 'libtool'. +m4_defun([_LT_LANG_F77_CONFIG], +[AC_LANG_PUSH(Fortran 77) +if test -z "$F77" || test no = "$F77"; then + _lt_disable_F77=yes +fi + +_LT_TAGVAR(archive_cmds_need_lc, $1)=no +_LT_TAGVAR(allow_undefined_flag, $1)= +_LT_TAGVAR(always_export_symbols, $1)=no +_LT_TAGVAR(archive_expsym_cmds, $1)= +_LT_TAGVAR(export_dynamic_flag_spec, $1)= +_LT_TAGVAR(hardcode_direct, $1)=no +_LT_TAGVAR(hardcode_direct_absolute, $1)=no +_LT_TAGVAR(hardcode_libdir_flag_spec, $1)= +_LT_TAGVAR(hardcode_libdir_separator, $1)= +_LT_TAGVAR(hardcode_minus_L, $1)=no +_LT_TAGVAR(hardcode_automatic, $1)=no +_LT_TAGVAR(inherit_rpath, $1)=no +_LT_TAGVAR(module_cmds, $1)= +_LT_TAGVAR(module_expsym_cmds, $1)= +_LT_TAGVAR(link_all_deplibs, $1)=unknown +_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds +_LT_TAGVAR(reload_flag, $1)=$reload_flag +_LT_TAGVAR(reload_cmds, $1)=$reload_cmds +_LT_TAGVAR(no_undefined_flag, $1)= +_LT_TAGVAR(whole_archive_flag_spec, $1)= +_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no + +# Source file extension for f77 test sources. +ac_ext=f + +# Object file extension for compiled f77 test sources. +objext=o +_LT_TAGVAR(objext, $1)=$objext + +# No sense in running all these tests if we already determined that +# the F77 compiler isn't working. Some variables (like enable_shared) +# are currently assumed to apply to all compilers on this platform, +# and will be corrupted by setting them based on a non-working compiler. +if test yes != "$_lt_disable_F77"; then + # Code to be used in simple compile tests + lt_simple_compile_test_code="\ + subroutine t + return + end +" + + # Code to be used in simple link tests + lt_simple_link_test_code="\ + program t + end +" + + # ltmain only uses $CC for tagged configurations so make sure $CC is set. + _LT_TAG_COMPILER + + # save warnings/boilerplate of simple test code + _LT_COMPILER_BOILERPLATE + _LT_LINKER_BOILERPLATE + + # Allow CC to be a program name with arguments. + lt_save_CC=$CC + lt_save_GCC=$GCC + lt_save_CFLAGS=$CFLAGS + CC=${F77-"f77"} + CFLAGS=$FFLAGS + compiler=$CC + _LT_TAGVAR(compiler, $1)=$CC + _LT_CC_BASENAME([$compiler]) + GCC=$G77 + if test -n "$compiler"; then + AC_MSG_CHECKING([if libtool supports shared libraries]) + AC_MSG_RESULT([$can_build_shared]) + + AC_MSG_CHECKING([whether to build shared libraries]) + test no = "$can_build_shared" && enable_shared=no + + # On AIX, shared libraries and static libraries use the same namespace, and + # are all built from PIC. + case $host_os in + aix3*) + test yes = "$enable_shared" && enable_static=no + if test -n "$RANLIB"; then + archive_cmds="$archive_cmds~\$RANLIB \$lib" + postinstall_cmds='$RANLIB $lib' + fi + ;; + aix[[4-9]]*) + if test ia64 != "$host_cpu"; then + case $enable_shared,$with_aix_soname,$aix_use_runtimelinking in + yes,aix,yes) ;; # shared object as lib.so file only + yes,svr4,*) ;; # shared object as lib.so archive member only + yes,*) enable_static=no ;; # shared object in lib.a archive as well + esac + fi + ;; + esac + AC_MSG_RESULT([$enable_shared]) + + AC_MSG_CHECKING([whether to build static libraries]) + # Make sure either enable_shared or enable_static is yes. + test yes = "$enable_shared" || enable_static=yes + AC_MSG_RESULT([$enable_static]) + + _LT_TAGVAR(GCC, $1)=$G77 + _LT_TAGVAR(LD, $1)=$LD + + ## CAVEAT EMPTOR: + ## There is no encapsulation within the following macros, do not change + ## the running order or otherwise move them around unless you know exactly + ## what you are doing... + _LT_COMPILER_PIC($1) + _LT_COMPILER_C_O($1) + _LT_COMPILER_FILE_LOCKS($1) + _LT_LINKER_SHLIBS($1) + _LT_SYS_DYNAMIC_LINKER($1) + _LT_LINKER_HARDCODE_LIBPATH($1) + + _LT_CONFIG($1) + fi # test -n "$compiler" + + GCC=$lt_save_GCC + CC=$lt_save_CC + CFLAGS=$lt_save_CFLAGS +fi # test yes != "$_lt_disable_F77" + +AC_LANG_POP +])# _LT_LANG_F77_CONFIG + + +# _LT_LANG_FC_CONFIG([TAG]) +# ------------------------- +# Ensure that the configuration variables for a Fortran compiler are +# suitably defined. These variables are subsequently used by _LT_CONFIG +# to write the compiler configuration to 'libtool'. +m4_defun([_LT_LANG_FC_CONFIG], +[AC_LANG_PUSH(Fortran) + +if test -z "$FC" || test no = "$FC"; then + _lt_disable_FC=yes +fi + +_LT_TAGVAR(archive_cmds_need_lc, $1)=no +_LT_TAGVAR(allow_undefined_flag, $1)= +_LT_TAGVAR(always_export_symbols, $1)=no +_LT_TAGVAR(archive_expsym_cmds, $1)= +_LT_TAGVAR(export_dynamic_flag_spec, $1)= +_LT_TAGVAR(hardcode_direct, $1)=no +_LT_TAGVAR(hardcode_direct_absolute, $1)=no +_LT_TAGVAR(hardcode_libdir_flag_spec, $1)= +_LT_TAGVAR(hardcode_libdir_separator, $1)= +_LT_TAGVAR(hardcode_minus_L, $1)=no +_LT_TAGVAR(hardcode_automatic, $1)=no +_LT_TAGVAR(inherit_rpath, $1)=no +_LT_TAGVAR(module_cmds, $1)= +_LT_TAGVAR(module_expsym_cmds, $1)= +_LT_TAGVAR(link_all_deplibs, $1)=unknown +_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds +_LT_TAGVAR(reload_flag, $1)=$reload_flag +_LT_TAGVAR(reload_cmds, $1)=$reload_cmds +_LT_TAGVAR(no_undefined_flag, $1)= +_LT_TAGVAR(whole_archive_flag_spec, $1)= +_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no + +# Source file extension for fc test sources. +ac_ext=${ac_fc_srcext-f} + +# Object file extension for compiled fc test sources. +objext=o +_LT_TAGVAR(objext, $1)=$objext + +# No sense in running all these tests if we already determined that +# the FC compiler isn't working. Some variables (like enable_shared) +# are currently assumed to apply to all compilers on this platform, +# and will be corrupted by setting them based on a non-working compiler. +if test yes != "$_lt_disable_FC"; then + # Code to be used in simple compile tests + lt_simple_compile_test_code="\ + subroutine t + return + end +" + + # Code to be used in simple link tests + lt_simple_link_test_code="\ + program t + end +" + + # ltmain only uses $CC for tagged configurations so make sure $CC is set. + _LT_TAG_COMPILER + + # save warnings/boilerplate of simple test code + _LT_COMPILER_BOILERPLATE + _LT_LINKER_BOILERPLATE + + # Allow CC to be a program name with arguments. + lt_save_CC=$CC + lt_save_GCC=$GCC + lt_save_CFLAGS=$CFLAGS + CC=${FC-"f95"} + CFLAGS=$FCFLAGS + compiler=$CC + GCC=$ac_cv_fc_compiler_gnu + + _LT_TAGVAR(compiler, $1)=$CC + _LT_CC_BASENAME([$compiler]) + + if test -n "$compiler"; then + AC_MSG_CHECKING([if libtool supports shared libraries]) + AC_MSG_RESULT([$can_build_shared]) + + AC_MSG_CHECKING([whether to build shared libraries]) + test no = "$can_build_shared" && enable_shared=no + + # On AIX, shared libraries and static libraries use the same namespace, and + # are all built from PIC. + case $host_os in + aix3*) + test yes = "$enable_shared" && enable_static=no + if test -n "$RANLIB"; then + archive_cmds="$archive_cmds~\$RANLIB \$lib" + postinstall_cmds='$RANLIB $lib' + fi + ;; + aix[[4-9]]*) + if test ia64 != "$host_cpu"; then + case $enable_shared,$with_aix_soname,$aix_use_runtimelinking in + yes,aix,yes) ;; # shared object as lib.so file only + yes,svr4,*) ;; # shared object as lib.so archive member only + yes,*) enable_static=no ;; # shared object in lib.a archive as well + esac + fi + ;; + esac + AC_MSG_RESULT([$enable_shared]) + + AC_MSG_CHECKING([whether to build static libraries]) + # Make sure either enable_shared or enable_static is yes. + test yes = "$enable_shared" || enable_static=yes + AC_MSG_RESULT([$enable_static]) + + _LT_TAGVAR(GCC, $1)=$ac_cv_fc_compiler_gnu + _LT_TAGVAR(LD, $1)=$LD + + ## CAVEAT EMPTOR: + ## There is no encapsulation within the following macros, do not change + ## the running order or otherwise move them around unless you know exactly + ## what you are doing... + _LT_SYS_HIDDEN_LIBDEPS($1) + _LT_COMPILER_PIC($1) + _LT_COMPILER_C_O($1) + _LT_COMPILER_FILE_LOCKS($1) + _LT_LINKER_SHLIBS($1) + _LT_SYS_DYNAMIC_LINKER($1) + _LT_LINKER_HARDCODE_LIBPATH($1) + + _LT_CONFIG($1) + fi # test -n "$compiler" + + GCC=$lt_save_GCC + CC=$lt_save_CC + CFLAGS=$lt_save_CFLAGS +fi # test yes != "$_lt_disable_FC" + +AC_LANG_POP +])# _LT_LANG_FC_CONFIG + + +# _LT_LANG_GCJ_CONFIG([TAG]) +# -------------------------- +# Ensure that the configuration variables for the GNU Java Compiler compiler +# are suitably defined. These variables are subsequently used by _LT_CONFIG +# to write the compiler configuration to 'libtool'. +m4_defun([_LT_LANG_GCJ_CONFIG], +[AC_REQUIRE([LT_PROG_GCJ])dnl +AC_LANG_SAVE + +# Source file extension for Java test sources. +ac_ext=java + +# Object file extension for compiled Java test sources. +objext=o +_LT_TAGVAR(objext, $1)=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="class foo {}" + +# Code to be used in simple link tests +lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }' + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. +_LT_TAG_COMPILER + +# save warnings/boilerplate of simple test code +_LT_COMPILER_BOILERPLATE +_LT_LINKER_BOILERPLATE + +# Allow CC to be a program name with arguments. +lt_save_CC=$CC +lt_save_CFLAGS=$CFLAGS +lt_save_GCC=$GCC +GCC=yes +CC=${GCJ-"gcj"} +CFLAGS=$GCJFLAGS +compiler=$CC +_LT_TAGVAR(compiler, $1)=$CC +_LT_TAGVAR(LD, $1)=$LD +_LT_CC_BASENAME([$compiler]) + +# GCJ did not exist at the time GCC didn't implicitly link libc in. +_LT_TAGVAR(archive_cmds_need_lc, $1)=no + +_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds +_LT_TAGVAR(reload_flag, $1)=$reload_flag +_LT_TAGVAR(reload_cmds, $1)=$reload_cmds + +## CAVEAT EMPTOR: +## There is no encapsulation within the following macros, do not change +## the running order or otherwise move them around unless you know exactly +## what you are doing... +if test -n "$compiler"; then + _LT_COMPILER_NO_RTTI($1) + _LT_COMPILER_PIC($1) + _LT_COMPILER_C_O($1) + _LT_COMPILER_FILE_LOCKS($1) + _LT_LINKER_SHLIBS($1) + _LT_LINKER_HARDCODE_LIBPATH($1) + + _LT_CONFIG($1) +fi + +AC_LANG_RESTORE + +GCC=$lt_save_GCC +CC=$lt_save_CC +CFLAGS=$lt_save_CFLAGS +])# _LT_LANG_GCJ_CONFIG + + +# _LT_LANG_GO_CONFIG([TAG]) +# -------------------------- +# Ensure that the configuration variables for the GNU Go compiler +# are suitably defined. These variables are subsequently used by _LT_CONFIG +# to write the compiler configuration to 'libtool'. +m4_defun([_LT_LANG_GO_CONFIG], +[AC_REQUIRE([LT_PROG_GO])dnl +AC_LANG_SAVE + +# Source file extension for Go test sources. +ac_ext=go + +# Object file extension for compiled Go test sources. +objext=o +_LT_TAGVAR(objext, $1)=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="package main; func main() { }" + +# Code to be used in simple link tests +lt_simple_link_test_code='package main; func main() { }' + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. +_LT_TAG_COMPILER + +# save warnings/boilerplate of simple test code +_LT_COMPILER_BOILERPLATE +_LT_LINKER_BOILERPLATE + +# Allow CC to be a program name with arguments. +lt_save_CC=$CC +lt_save_CFLAGS=$CFLAGS +lt_save_GCC=$GCC +GCC=yes +CC=${GOC-"gccgo"} +CFLAGS=$GOFLAGS +compiler=$CC +_LT_TAGVAR(compiler, $1)=$CC +_LT_TAGVAR(LD, $1)=$LD +_LT_CC_BASENAME([$compiler]) + +# Go did not exist at the time GCC didn't implicitly link libc in. +_LT_TAGVAR(archive_cmds_need_lc, $1)=no + +_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds +_LT_TAGVAR(reload_flag, $1)=$reload_flag +_LT_TAGVAR(reload_cmds, $1)=$reload_cmds + +## CAVEAT EMPTOR: +## There is no encapsulation within the following macros, do not change +## the running order or otherwise move them around unless you know exactly +## what you are doing... +if test -n "$compiler"; then + _LT_COMPILER_NO_RTTI($1) + _LT_COMPILER_PIC($1) + _LT_COMPILER_C_O($1) + _LT_COMPILER_FILE_LOCKS($1) + _LT_LINKER_SHLIBS($1) + _LT_LINKER_HARDCODE_LIBPATH($1) + + _LT_CONFIG($1) +fi + +AC_LANG_RESTORE + +GCC=$lt_save_GCC +CC=$lt_save_CC +CFLAGS=$lt_save_CFLAGS +])# _LT_LANG_GO_CONFIG + + +# _LT_LANG_RC_CONFIG([TAG]) +# ------------------------- +# Ensure that the configuration variables for the Windows resource compiler +# are suitably defined. These variables are subsequently used by _LT_CONFIG +# to write the compiler configuration to 'libtool'. +m4_defun([_LT_LANG_RC_CONFIG], +[AC_REQUIRE([LT_PROG_RC])dnl +AC_LANG_SAVE + +# Source file extension for RC test sources. +ac_ext=rc + +# Object file extension for compiled RC test sources. +objext=o +_LT_TAGVAR(objext, $1)=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }' + +# Code to be used in simple link tests +lt_simple_link_test_code=$lt_simple_compile_test_code + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. +_LT_TAG_COMPILER + +# save warnings/boilerplate of simple test code +_LT_COMPILER_BOILERPLATE +_LT_LINKER_BOILERPLATE + +# Allow CC to be a program name with arguments. +lt_save_CC=$CC +lt_save_CFLAGS=$CFLAGS +lt_save_GCC=$GCC +GCC= +CC=${RC-"windres"} +CFLAGS= +compiler=$CC +_LT_TAGVAR(compiler, $1)=$CC +_LT_CC_BASENAME([$compiler]) +_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes + +if test -n "$compiler"; then + : + _LT_CONFIG($1) +fi + +GCC=$lt_save_GCC +AC_LANG_RESTORE +CC=$lt_save_CC +CFLAGS=$lt_save_CFLAGS +])# _LT_LANG_RC_CONFIG + + +# LT_PROG_GCJ +# ----------- +AC_DEFUN([LT_PROG_GCJ], +[m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ], + [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ], + [AC_CHECK_TOOL(GCJ, gcj,) + test set = "${GCJFLAGS+set}" || GCJFLAGS="-g -O2" + AC_SUBST(GCJFLAGS)])])[]dnl +]) + +# Old name: +AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([LT_AC_PROG_GCJ], []) + + +# LT_PROG_GO +# ---------- +AC_DEFUN([LT_PROG_GO], +[AC_CHECK_TOOL(GOC, gccgo,) +]) + + +# LT_PROG_RC +# ---------- +AC_DEFUN([LT_PROG_RC], +[AC_CHECK_TOOL(RC, windres,) +]) + +# Old name: +AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([LT_AC_PROG_RC], []) + + +# _LT_DECL_EGREP +# -------------- +# If we don't have a new enough Autoconf to choose the best grep +# available, choose the one first in the user's PATH. +m4_defun([_LT_DECL_EGREP], +[AC_REQUIRE([AC_PROG_EGREP])dnl +AC_REQUIRE([AC_PROG_FGREP])dnl +test -z "$GREP" && GREP=grep +_LT_DECL([], [GREP], [1], [A grep program that handles long lines]) +_LT_DECL([], [EGREP], [1], [An ERE matcher]) +_LT_DECL([], [FGREP], [1], [A literal string matcher]) +dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too +AC_SUBST([GREP]) +]) + + +# _LT_DECL_OBJDUMP +# -------------- +# If we don't have a new enough Autoconf to choose the best objdump +# available, choose the one first in the user's PATH. +m4_defun([_LT_DECL_OBJDUMP], +[AC_CHECK_TOOL(OBJDUMP, objdump, false) +test -z "$OBJDUMP" && OBJDUMP=objdump +_LT_DECL([], [OBJDUMP], [1], [An object symbol dumper]) +AC_SUBST([OBJDUMP]) +]) + +# _LT_DECL_DLLTOOL +# ---------------- +# Ensure DLLTOOL variable is set. +m4_defun([_LT_DECL_DLLTOOL], +[AC_CHECK_TOOL(DLLTOOL, dlltool, false) +test -z "$DLLTOOL" && DLLTOOL=dlltool +_LT_DECL([], [DLLTOOL], [1], [DLL creation program]) +AC_SUBST([DLLTOOL]) +]) + +# _LT_DECL_FILECMD +# ---------------- +# Check for a file(cmd) program that can be used to detect file type and magic +m4_defun([_LT_DECL_FILECMD], +[AC_CHECK_TOOL([FILECMD], [file], [:]) +_LT_DECL([], [FILECMD], [1], [A file(cmd) program that detects file types]) +])# _LD_DECL_FILECMD + +# _LT_DECL_SED +# ------------ +# Check for a fully-functional sed program, that truncates +# as few characters as possible. Prefer GNU sed if found. +m4_defun([_LT_DECL_SED], +[AC_PROG_SED +test -z "$SED" && SED=sed +Xsed="$SED -e 1s/^X//" +_LT_DECL([], [SED], [1], [A sed program that does not truncate output]) +_LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"], + [Sed that helps us avoid accidentally triggering echo(1) options like -n]) +])# _LT_DECL_SED + +m4_ifndef([AC_PROG_SED], [ +############################################################ +# NOTE: This macro has been submitted for inclusion into # +# GNU Autoconf as AC_PROG_SED. When it is available in # +# a released version of Autoconf we should remove this # +# macro and use it instead. # +############################################################ + +m4_defun([AC_PROG_SED], +[AC_MSG_CHECKING([for a sed that does not truncate output]) +AC_CACHE_VAL(lt_cv_path_SED, +[# Loop through the user's path and test for sed and gsed. +# Then use that list of sed's as ones to test for truncation. +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for lt_ac_prog in sed gsed; do + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then + lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext" + fi + done + done +done +IFS=$as_save_IFS +lt_ac_max=0 +lt_ac_count=0 +# Add /usr/xpg4/bin/sed as it is typically found on Solaris +# along with /bin/sed that truncates output. +for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do + test ! -f "$lt_ac_sed" && continue + cat /dev/null > conftest.in + lt_ac_count=0 + echo $ECHO_N "0123456789$ECHO_C" >conftest.in + # Check for GNU sed and select it if it is found. + if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then + lt_cv_path_SED=$lt_ac_sed + break + fi + while true; do + cat conftest.in conftest.in >conftest.tmp + mv conftest.tmp conftest.in + cp conftest.in conftest.nl + echo >>conftest.nl + $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break + cmp -s conftest.out conftest.nl || break + # 10000 chars as input seems more than enough + test 10 -lt "$lt_ac_count" && break + lt_ac_count=`expr $lt_ac_count + 1` + if test "$lt_ac_count" -gt "$lt_ac_max"; then + lt_ac_max=$lt_ac_count + lt_cv_path_SED=$lt_ac_sed + fi + done +done +]) +SED=$lt_cv_path_SED +AC_SUBST([SED]) +AC_MSG_RESULT([$SED]) +])#AC_PROG_SED +])#m4_ifndef + +# Old name: +AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([LT_AC_PROG_SED], []) + + +# _LT_CHECK_SHELL_FEATURES +# ------------------------ +# Find out whether the shell is Bourne or XSI compatible, +# or has some other useful features. +m4_defun([_LT_CHECK_SHELL_FEATURES], +[if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then + lt_unset=unset +else + lt_unset=false +fi +_LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl + +# test EBCDIC or ASCII +case `echo X|tr X '\101'` in + A) # ASCII based system + # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr + lt_SP2NL='tr \040 \012' + lt_NL2SP='tr \015\012 \040\040' + ;; + *) # EBCDIC based system + lt_SP2NL='tr \100 \n' + lt_NL2SP='tr \r\n \100\100' + ;; +esac +_LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl +_LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl +])# _LT_CHECK_SHELL_FEATURES + + +# _LT_PATH_CONVERSION_FUNCTIONS +# ----------------------------- +# Determine what file name conversion functions should be used by +# func_to_host_file (and, implicitly, by func_to_host_path). These are needed +# for certain cross-compile configurations and native mingw. +m4_defun([_LT_PATH_CONVERSION_FUNCTIONS], +[AC_REQUIRE([AC_CANONICAL_HOST])dnl +AC_REQUIRE([AC_CANONICAL_BUILD])dnl +AC_MSG_CHECKING([how to convert $build file names to $host format]) +AC_CACHE_VAL(lt_cv_to_host_file_cmd, +[case $host in + *-*-mingw* ) + case $build in + *-*-mingw* ) # actually msys + lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 + ;; + *-*-cygwin* ) + lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32 + ;; + * ) # otherwise, assume *nix + lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32 + ;; + esac + ;; + *-*-cygwin* ) + case $build in + *-*-mingw* ) # actually msys + lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin + ;; + *-*-cygwin* ) + lt_cv_to_host_file_cmd=func_convert_file_noop + ;; + * ) # otherwise, assume *nix + lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin + ;; + esac + ;; + * ) # unhandled hosts (and "normal" native builds) + lt_cv_to_host_file_cmd=func_convert_file_noop + ;; +esac +]) +to_host_file_cmd=$lt_cv_to_host_file_cmd +AC_MSG_RESULT([$lt_cv_to_host_file_cmd]) +_LT_DECL([to_host_file_cmd], [lt_cv_to_host_file_cmd], + [0], [convert $build file names to $host format])dnl + +AC_MSG_CHECKING([how to convert $build file names to toolchain format]) +AC_CACHE_VAL(lt_cv_to_tool_file_cmd, +[#assume ordinary cross tools, or native build. +lt_cv_to_tool_file_cmd=func_convert_file_noop +case $host in + *-*-mingw* ) + case $build in + *-*-mingw* ) # actually msys + lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 + ;; + esac + ;; +esac +]) +to_tool_file_cmd=$lt_cv_to_tool_file_cmd +AC_MSG_RESULT([$lt_cv_to_tool_file_cmd]) +_LT_DECL([to_tool_file_cmd], [lt_cv_to_tool_file_cmd], + [0], [convert $build files to toolchain format])dnl +])# _LT_PATH_CONVERSION_FUNCTIONS diff --git a/third_party/curl/m4/ltoptions.m4 b/third_party/curl/m4/ltoptions.m4 new file mode 100644 index 0000000..b0b5e9c --- /dev/null +++ b/third_party/curl/m4/ltoptions.m4 @@ -0,0 +1,437 @@ +# Helper functions for option handling. -*- Autoconf -*- +# +# Copyright (C) 2004-2005, 2007-2009, 2011-2019, 2021-2022 Free +# Software Foundation, Inc. +# Written by Gary V. Vaughan, 2004 +# +# This file is free software; the Free Software Foundation gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. + +# serial 8 ltoptions.m4 + +# This is to help aclocal find these macros, as it can't see m4_define. +AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])]) + + +# _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME) +# ------------------------------------------ +m4_define([_LT_MANGLE_OPTION], +[[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])]) + + +# _LT_SET_OPTION(MACRO-NAME, OPTION-NAME) +# --------------------------------------- +# Set option OPTION-NAME for macro MACRO-NAME, and if there is a +# matching handler defined, dispatch to it. Other OPTION-NAMEs are +# saved as a flag. +m4_define([_LT_SET_OPTION], +[m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl +m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]), + _LT_MANGLE_DEFUN([$1], [$2]), + [m4_warning([Unknown $1 option '$2'])])[]dnl +]) + + +# _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET]) +# ------------------------------------------------------------ +# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. +m4_define([_LT_IF_OPTION], +[m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])]) + + +# _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET) +# ------------------------------------------------------- +# Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME +# are set. +m4_define([_LT_UNLESS_OPTIONS], +[m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), + [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option), + [m4_define([$0_found])])])[]dnl +m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3 +])[]dnl +]) + + +# _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST) +# ---------------------------------------- +# OPTION-LIST is a space-separated list of Libtool options associated +# with MACRO-NAME. If any OPTION has a matching handler declared with +# LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about +# the unknown option and exit. +m4_defun([_LT_SET_OPTIONS], +[# Set options +m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), + [_LT_SET_OPTION([$1], _LT_Option)]) + +m4_if([$1],[LT_INIT],[ + dnl + dnl Simply set some default values (i.e off) if boolean options were not + dnl specified: + _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no + ]) + _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no + ]) + dnl + dnl If no reference was made to various pairs of opposing options, then + dnl we run the default mode handler for the pair. For example, if neither + dnl 'shared' nor 'disable-shared' was passed, we enable building of shared + dnl archives by default: + _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED]) + _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC]) + _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC]) + _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install], + [_LT_ENABLE_FAST_INSTALL]) + _LT_UNLESS_OPTIONS([LT_INIT], [aix-soname=aix aix-soname=both aix-soname=svr4], + [_LT_WITH_AIX_SONAME([aix])]) + ]) +])# _LT_SET_OPTIONS + + +## --------------------------------- ## +## Macros to handle LT_INIT options. ## +## --------------------------------- ## + +# _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME) +# ----------------------------------------- +m4_define([_LT_MANGLE_DEFUN], +[[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])]) + + +# LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE) +# ----------------------------------------------- +m4_define([LT_OPTION_DEFINE], +[m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl +])# LT_OPTION_DEFINE + + +# dlopen +# ------ +LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes +]) + +AU_DEFUN([AC_LIBTOOL_DLOPEN], +[_LT_SET_OPTION([LT_INIT], [dlopen]) +AC_DIAGNOSE([obsolete], +[$0: Remove this warning and the call to _LT_SET_OPTION when you +put the 'dlopen' option into LT_INIT's first parameter.]) +]) + +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], []) + + +# win32-dll +# --------- +# Declare package support for building win32 dll's. +LT_OPTION_DEFINE([LT_INIT], [win32-dll], +[enable_win32_dll=yes + +case $host in +*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*) + AC_CHECK_TOOL(AS, as, false) + AC_CHECK_TOOL(DLLTOOL, dlltool, false) + AC_CHECK_TOOL(OBJDUMP, objdump, false) + ;; +esac + +test -z "$AS" && AS=as +_LT_DECL([], [AS], [1], [Assembler program])dnl + +test -z "$DLLTOOL" && DLLTOOL=dlltool +_LT_DECL([], [DLLTOOL], [1], [DLL creation program])dnl + +test -z "$OBJDUMP" && OBJDUMP=objdump +_LT_DECL([], [OBJDUMP], [1], [Object dumper program])dnl +])# win32-dll + +AU_DEFUN([AC_LIBTOOL_WIN32_DLL], +[AC_REQUIRE([AC_CANONICAL_HOST])dnl +_LT_SET_OPTION([LT_INIT], [win32-dll]) +AC_DIAGNOSE([obsolete], +[$0: Remove this warning and the call to _LT_SET_OPTION when you +put the 'win32-dll' option into LT_INIT's first parameter.]) +]) + +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], []) + + +# _LT_ENABLE_SHARED([DEFAULT]) +# ---------------------------- +# implement the --enable-shared flag, and supports the 'shared' and +# 'disable-shared' LT_INIT options. +# DEFAULT is either 'yes' or 'no'. If omitted, it defaults to 'yes'. +m4_define([_LT_ENABLE_SHARED], +[m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl +AC_ARG_ENABLE([shared], + [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@], + [build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])], + [p=${PACKAGE-default} + case $enableval in + yes) enable_shared=yes ;; + no) enable_shared=no ;; + *) + enable_shared=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, + for pkg in $enableval; do + IFS=$lt_save_ifs + if test "X$pkg" = "X$p"; then + enable_shared=yes + fi + done + IFS=$lt_save_ifs + ;; + esac], + [enable_shared=]_LT_ENABLE_SHARED_DEFAULT) + + _LT_DECL([build_libtool_libs], [enable_shared], [0], + [Whether or not to build shared libraries]) +])# _LT_ENABLE_SHARED + +LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])]) +LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])]) + +# Old names: +AC_DEFUN([AC_ENABLE_SHARED], +[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared]) +]) + +AC_DEFUN([AC_DISABLE_SHARED], +[_LT_SET_OPTION([LT_INIT], [disable-shared]) +]) + +AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)]) +AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)]) + +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AM_ENABLE_SHARED], []) +dnl AC_DEFUN([AM_DISABLE_SHARED], []) + + + +# _LT_ENABLE_STATIC([DEFAULT]) +# ---------------------------- +# implement the --enable-static flag, and support the 'static' and +# 'disable-static' LT_INIT options. +# DEFAULT is either 'yes' or 'no'. If omitted, it defaults to 'yes'. +m4_define([_LT_ENABLE_STATIC], +[m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl +AC_ARG_ENABLE([static], + [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@], + [build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])], + [p=${PACKAGE-default} + case $enableval in + yes) enable_static=yes ;; + no) enable_static=no ;; + *) + enable_static=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, + for pkg in $enableval; do + IFS=$lt_save_ifs + if test "X$pkg" = "X$p"; then + enable_static=yes + fi + done + IFS=$lt_save_ifs + ;; + esac], + [enable_static=]_LT_ENABLE_STATIC_DEFAULT) + + _LT_DECL([build_old_libs], [enable_static], [0], + [Whether or not to build static libraries]) +])# _LT_ENABLE_STATIC + +LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])]) +LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])]) + +# Old names: +AC_DEFUN([AC_ENABLE_STATIC], +[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static]) +]) + +AC_DEFUN([AC_DISABLE_STATIC], +[_LT_SET_OPTION([LT_INIT], [disable-static]) +]) + +AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)]) +AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)]) + +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AM_ENABLE_STATIC], []) +dnl AC_DEFUN([AM_DISABLE_STATIC], []) + + + +# _LT_ENABLE_FAST_INSTALL([DEFAULT]) +# ---------------------------------- +# implement the --enable-fast-install flag, and support the 'fast-install' +# and 'disable-fast-install' LT_INIT options. +# DEFAULT is either 'yes' or 'no'. If omitted, it defaults to 'yes'. +m4_define([_LT_ENABLE_FAST_INSTALL], +[m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl +AC_ARG_ENABLE([fast-install], + [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@], + [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])], + [p=${PACKAGE-default} + case $enableval in + yes) enable_fast_install=yes ;; + no) enable_fast_install=no ;; + *) + enable_fast_install=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, + for pkg in $enableval; do + IFS=$lt_save_ifs + if test "X$pkg" = "X$p"; then + enable_fast_install=yes + fi + done + IFS=$lt_save_ifs + ;; + esac], + [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT) + +_LT_DECL([fast_install], [enable_fast_install], [0], + [Whether or not to optimize for fast installation])dnl +])# _LT_ENABLE_FAST_INSTALL + +LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])]) +LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])]) + +# Old names: +AU_DEFUN([AC_ENABLE_FAST_INSTALL], +[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install]) +AC_DIAGNOSE([obsolete], +[$0: Remove this warning and the call to _LT_SET_OPTION when you put +the 'fast-install' option into LT_INIT's first parameter.]) +]) + +AU_DEFUN([AC_DISABLE_FAST_INSTALL], +[_LT_SET_OPTION([LT_INIT], [disable-fast-install]) +AC_DIAGNOSE([obsolete], +[$0: Remove this warning and the call to _LT_SET_OPTION when you put +the 'disable-fast-install' option into LT_INIT's first parameter.]) +]) + +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], []) +dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], []) + + +# _LT_WITH_AIX_SONAME([DEFAULT]) +# ---------------------------------- +# implement the --with-aix-soname flag, and support the `aix-soname=aix' +# and `aix-soname=both' and `aix-soname=svr4' LT_INIT options. DEFAULT +# is either `aix', `both' or `svr4'. If omitted, it defaults to `aix'. +m4_define([_LT_WITH_AIX_SONAME], +[m4_define([_LT_WITH_AIX_SONAME_DEFAULT], [m4_if($1, svr4, svr4, m4_if($1, both, both, aix))])dnl +shared_archive_member_spec= +case $host,$enable_shared in +power*-*-aix[[5-9]]*,yes) + AC_MSG_CHECKING([which variant of shared library versioning to provide]) + AC_ARG_WITH([aix-soname], + [AS_HELP_STRING([--with-aix-soname=aix|svr4|both], + [shared library versioning (aka "SONAME") variant to provide on AIX, @<:@default=]_LT_WITH_AIX_SONAME_DEFAULT[@:>@.])], + [case $withval in + aix|svr4|both) + ;; + *) + AC_MSG_ERROR([Unknown argument to --with-aix-soname]) + ;; + esac + lt_cv_with_aix_soname=$with_aix_soname], + [AC_CACHE_VAL([lt_cv_with_aix_soname], + [lt_cv_with_aix_soname=]_LT_WITH_AIX_SONAME_DEFAULT) + with_aix_soname=$lt_cv_with_aix_soname]) + AC_MSG_RESULT([$with_aix_soname]) + if test aix != "$with_aix_soname"; then + # For the AIX way of multilib, we name the shared archive member + # based on the bitwidth used, traditionally 'shr.o' or 'shr_64.o', + # and 'shr.imp' or 'shr_64.imp', respectively, for the Import File. + # Even when GNU compilers ignore OBJECT_MODE but need '-maix64' flag, + # the AIX toolchain works better with OBJECT_MODE set (default 32). + if test 64 = "${OBJECT_MODE-32}"; then + shared_archive_member_spec=shr_64 + else + shared_archive_member_spec=shr + fi + fi + ;; +*) + with_aix_soname=aix + ;; +esac + +_LT_DECL([], [shared_archive_member_spec], [0], + [Shared archive member basename, for filename based shared library versioning on AIX])dnl +])# _LT_WITH_AIX_SONAME + +LT_OPTION_DEFINE([LT_INIT], [aix-soname=aix], [_LT_WITH_AIX_SONAME([aix])]) +LT_OPTION_DEFINE([LT_INIT], [aix-soname=both], [_LT_WITH_AIX_SONAME([both])]) +LT_OPTION_DEFINE([LT_INIT], [aix-soname=svr4], [_LT_WITH_AIX_SONAME([svr4])]) + + +# _LT_WITH_PIC([MODE]) +# -------------------- +# implement the --with-pic flag, and support the 'pic-only' and 'no-pic' +# LT_INIT options. +# MODE is either 'yes' or 'no'. If omitted, it defaults to 'both'. +m4_define([_LT_WITH_PIC], +[AC_ARG_WITH([pic], + [AS_HELP_STRING([--with-pic@<:@=PKGS@:>@], + [try to use only PIC/non-PIC objects @<:@default=use both@:>@])], + [lt_p=${PACKAGE-default} + case $withval in + yes|no) pic_mode=$withval ;; + *) + pic_mode=default + # Look at the argument we got. We use all the common list separators. + lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, + for lt_pkg in $withval; do + IFS=$lt_save_ifs + if test "X$lt_pkg" = "X$lt_p"; then + pic_mode=yes + fi + done + IFS=$lt_save_ifs + ;; + esac], + [pic_mode=m4_default([$1], [default])]) + +_LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl +])# _LT_WITH_PIC + +LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])]) +LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])]) + +# Old name: +AU_DEFUN([AC_LIBTOOL_PICMODE], +[_LT_SET_OPTION([LT_INIT], [pic-only]) +AC_DIAGNOSE([obsolete], +[$0: Remove this warning and the call to _LT_SET_OPTION when you +put the 'pic-only' option into LT_INIT's first parameter.]) +]) + +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_LIBTOOL_PICMODE], []) + +## ----------------- ## +## LTDL_INIT Options ## +## ----------------- ## + +m4_define([_LTDL_MODE], []) +LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive], + [m4_define([_LTDL_MODE], [nonrecursive])]) +LT_OPTION_DEFINE([LTDL_INIT], [recursive], + [m4_define([_LTDL_MODE], [recursive])]) +LT_OPTION_DEFINE([LTDL_INIT], [subproject], + [m4_define([_LTDL_MODE], [subproject])]) + +m4_define([_LTDL_TYPE], []) +LT_OPTION_DEFINE([LTDL_INIT], [installable], + [m4_define([_LTDL_TYPE], [installable])]) +LT_OPTION_DEFINE([LTDL_INIT], [convenience], + [m4_define([_LTDL_TYPE], [convenience])]) diff --git a/third_party/curl/m4/ltsugar.m4 b/third_party/curl/m4/ltsugar.m4 new file mode 100644 index 0000000..902508b --- /dev/null +++ b/third_party/curl/m4/ltsugar.m4 @@ -0,0 +1,124 @@ +# ltsugar.m4 -- libtool m4 base layer. -*-Autoconf-*- +# +# Copyright (C) 2004-2005, 2007-2008, 2011-2019, 2021-2022 Free Software +# Foundation, Inc. +# Written by Gary V. Vaughan, 2004 +# +# This file is free software; the Free Software Foundation gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. + +# serial 6 ltsugar.m4 + +# This is to help aclocal find these macros, as it can't see m4_define. +AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])]) + + +# lt_join(SEP, ARG1, [ARG2...]) +# ----------------------------- +# Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their +# associated separator. +# Needed until we can rely on m4_join from Autoconf 2.62, since all earlier +# versions in m4sugar had bugs. +m4_define([lt_join], +[m4_if([$#], [1], [], + [$#], [2], [[$2]], + [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])]) +m4_define([_lt_join], +[m4_if([$#$2], [2], [], + [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])]) + + +# lt_car(LIST) +# lt_cdr(LIST) +# ------------ +# Manipulate m4 lists. +# These macros are necessary as long as will still need to support +# Autoconf-2.59, which quotes differently. +m4_define([lt_car], [[$1]]) +m4_define([lt_cdr], +[m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])], + [$#], 1, [], + [m4_dquote(m4_shift($@))])]) +m4_define([lt_unquote], $1) + + +# lt_append(MACRO-NAME, STRING, [SEPARATOR]) +# ------------------------------------------ +# Redefine MACRO-NAME to hold its former content plus 'SEPARATOR''STRING'. +# Note that neither SEPARATOR nor STRING are expanded; they are appended +# to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked). +# No SEPARATOR is output if MACRO-NAME was previously undefined (different +# than defined and empty). +# +# This macro is needed until we can rely on Autoconf 2.62, since earlier +# versions of m4sugar mistakenly expanded SEPARATOR but not STRING. +m4_define([lt_append], +[m4_define([$1], + m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])]) + + + +# lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...]) +# ---------------------------------------------------------- +# Produce a SEP delimited list of all paired combinations of elements of +# PREFIX-LIST with SUFFIX1 through SUFFIXn. Each element of the list +# has the form PREFIXmINFIXSUFFIXn. +# Needed until we can rely on m4_combine added in Autoconf 2.62. +m4_define([lt_combine], +[m4_if(m4_eval([$# > 3]), [1], + [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl +[[m4_foreach([_Lt_prefix], [$2], + [m4_foreach([_Lt_suffix], + ]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[, + [_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])]) + + +# lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ]) +# ----------------------------------------------------------------------- +# Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited +# by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ. +m4_define([lt_if_append_uniq], +[m4_ifdef([$1], + [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1], + [lt_append([$1], [$2], [$3])$4], + [$5])], + [lt_append([$1], [$2], [$3])$4])]) + + +# lt_dict_add(DICT, KEY, VALUE) +# ----------------------------- +m4_define([lt_dict_add], +[m4_define([$1($2)], [$3])]) + + +# lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE) +# -------------------------------------------- +m4_define([lt_dict_add_subkey], +[m4_define([$1($2:$3)], [$4])]) + + +# lt_dict_fetch(DICT, KEY, [SUBKEY]) +# ---------------------------------- +m4_define([lt_dict_fetch], +[m4_ifval([$3], + m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]), + m4_ifdef([$1($2)], [m4_defn([$1($2)])]))]) + + +# lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE]) +# ----------------------------------------------------------------- +m4_define([lt_if_dict_fetch], +[m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4], + [$5], + [$6])]) + + +# lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...]) +# -------------------------------------------------------------- +m4_define([lt_dict_filter], +[m4_if([$5], [], [], + [lt_join(m4_quote(m4_default([$4], [[, ]])), + lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]), + [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl +]) diff --git a/third_party/curl/m4/ltversion.m4 b/third_party/curl/m4/ltversion.m4 new file mode 100644 index 0000000..b155d0a --- /dev/null +++ b/third_party/curl/m4/ltversion.m4 @@ -0,0 +1,24 @@ +# ltversion.m4 -- version numbers -*- Autoconf -*- +# +# Copyright (C) 2004, 2011-2019, 2021-2022 Free Software Foundation, +# Inc. +# Written by Scott James Remnant, 2004 +# +# This file is free software; the Free Software Foundation gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. + +# @configure_input@ + +# serial 4245 ltversion.m4 +# This file is part of GNU Libtool + +m4_define([LT_PACKAGE_VERSION], [2.4.7]) +m4_define([LT_PACKAGE_REVISION], [2.4.7]) + +AC_DEFUN([LTVERSION_VERSION], +[macro_version='2.4.7' +macro_revision='2.4.7' +_LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?]) +_LT_DECL(, macro_revision, 0) +]) diff --git a/third_party/curl/m4/lt~obsolete.m4 b/third_party/curl/m4/lt~obsolete.m4 new file mode 100644 index 0000000..0f7a875 --- /dev/null +++ b/third_party/curl/m4/lt~obsolete.m4 @@ -0,0 +1,99 @@ +# lt~obsolete.m4 -- aclocal satisfying obsolete definitions. -*-Autoconf-*- +# +# Copyright (C) 2004-2005, 2007, 2009, 2011-2019, 2021-2022 Free +# Software Foundation, Inc. +# Written by Scott James Remnant, 2004. +# +# This file is free software; the Free Software Foundation gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. + +# serial 5 lt~obsolete.m4 + +# These exist entirely to fool aclocal when bootstrapping libtool. +# +# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN), +# which have later been changed to m4_define as they aren't part of the +# exported API, or moved to Autoconf or Automake where they belong. +# +# The trouble is, aclocal is a bit thick. It'll see the old AC_DEFUN +# in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us +# using a macro with the same name in our local m4/libtool.m4 it'll +# pull the old libtool.m4 in (it doesn't see our shiny new m4_define +# and doesn't know about Autoconf macros at all.) +# +# So we provide this file, which has a silly filename so it's always +# included after everything else. This provides aclocal with the +# AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything +# because those macros already exist, or will be overwritten later. +# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. +# +# Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here. +# Yes, that means every name once taken will need to remain here until +# we give up compatibility with versions before 1.7, at which point +# we need to keep only those names which we still refer to. + +# This is to help aclocal find these macros, as it can't see m4_define. +AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])]) + +m4_ifndef([AC_LIBTOOL_LINKER_OPTION], [AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])]) +m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP])]) +m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])]) +m4_ifndef([_LT_AC_SHELL_INIT], [AC_DEFUN([_LT_AC_SHELL_INIT])]) +m4_ifndef([_LT_AC_SYS_LIBPATH_AIX], [AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])]) +m4_ifndef([_LT_PROG_LTMAIN], [AC_DEFUN([_LT_PROG_LTMAIN])]) +m4_ifndef([_LT_AC_TAGVAR], [AC_DEFUN([_LT_AC_TAGVAR])]) +m4_ifndef([AC_LTDL_ENABLE_INSTALL], [AC_DEFUN([AC_LTDL_ENABLE_INSTALL])]) +m4_ifndef([AC_LTDL_PREOPEN], [AC_DEFUN([AC_LTDL_PREOPEN])]) +m4_ifndef([_LT_AC_SYS_COMPILER], [AC_DEFUN([_LT_AC_SYS_COMPILER])]) +m4_ifndef([_LT_AC_LOCK], [AC_DEFUN([_LT_AC_LOCK])]) +m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE], [AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])]) +m4_ifndef([_LT_AC_TRY_DLOPEN_SELF], [AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])]) +m4_ifndef([AC_LIBTOOL_PROG_CC_C_O], [AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])]) +m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])]) +m4_ifndef([AC_LIBTOOL_OBJDIR], [AC_DEFUN([AC_LIBTOOL_OBJDIR])]) +m4_ifndef([AC_LTDL_OBJDIR], [AC_DEFUN([AC_LTDL_OBJDIR])]) +m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])]) +m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP], [AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])]) +m4_ifndef([AC_PATH_MAGIC], [AC_DEFUN([AC_PATH_MAGIC])]) +m4_ifndef([AC_PROG_LD_GNU], [AC_DEFUN([AC_PROG_LD_GNU])]) +m4_ifndef([AC_PROG_LD_RELOAD_FLAG], [AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])]) +m4_ifndef([AC_DEPLIBS_CHECK_METHOD], [AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])]) +m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])]) +m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])]) +m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])]) +m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS], [AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])]) +m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP], [AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])]) +m4_ifndef([LT_AC_PROG_EGREP], [AC_DEFUN([LT_AC_PROG_EGREP])]) +m4_ifndef([LT_AC_PROG_SED], [AC_DEFUN([LT_AC_PROG_SED])]) +m4_ifndef([_LT_CC_BASENAME], [AC_DEFUN([_LT_CC_BASENAME])]) +m4_ifndef([_LT_COMPILER_BOILERPLATE], [AC_DEFUN([_LT_COMPILER_BOILERPLATE])]) +m4_ifndef([_LT_LINKER_BOILERPLATE], [AC_DEFUN([_LT_LINKER_BOILERPLATE])]) +m4_ifndef([_AC_PROG_LIBTOOL], [AC_DEFUN([_AC_PROG_LIBTOOL])]) +m4_ifndef([AC_LIBTOOL_SETUP], [AC_DEFUN([AC_LIBTOOL_SETUP])]) +m4_ifndef([_LT_AC_CHECK_DLFCN], [AC_DEFUN([_LT_AC_CHECK_DLFCN])]) +m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER], [AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])]) +m4_ifndef([_LT_AC_TAGCONFIG], [AC_DEFUN([_LT_AC_TAGCONFIG])]) +m4_ifndef([AC_DISABLE_FAST_INSTALL], [AC_DEFUN([AC_DISABLE_FAST_INSTALL])]) +m4_ifndef([_LT_AC_LANG_CXX], [AC_DEFUN([_LT_AC_LANG_CXX])]) +m4_ifndef([_LT_AC_LANG_F77], [AC_DEFUN([_LT_AC_LANG_F77])]) +m4_ifndef([_LT_AC_LANG_GCJ], [AC_DEFUN([_LT_AC_LANG_GCJ])]) +m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])]) +m4_ifndef([_LT_AC_LANG_C_CONFIG], [AC_DEFUN([_LT_AC_LANG_C_CONFIG])]) +m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])]) +m4_ifndef([_LT_AC_LANG_CXX_CONFIG], [AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])]) +m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])]) +m4_ifndef([_LT_AC_LANG_F77_CONFIG], [AC_DEFUN([_LT_AC_LANG_F77_CONFIG])]) +m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])]) +m4_ifndef([_LT_AC_LANG_GCJ_CONFIG], [AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])]) +m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])]) +m4_ifndef([_LT_AC_LANG_RC_CONFIG], [AC_DEFUN([_LT_AC_LANG_RC_CONFIG])]) +m4_ifndef([AC_LIBTOOL_CONFIG], [AC_DEFUN([AC_LIBTOOL_CONFIG])]) +m4_ifndef([_LT_AC_FILE_LTDLL_C], [AC_DEFUN([_LT_AC_FILE_LTDLL_C])]) +m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS], [AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])]) +m4_ifndef([_LT_AC_PROG_CXXCPP], [AC_DEFUN([_LT_AC_PROG_CXXCPP])]) +m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS], [AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])]) +m4_ifndef([_LT_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])]) +m4_ifndef([_LT_PROG_F77], [AC_DEFUN([_LT_PROG_F77])]) +m4_ifndef([_LT_PROG_FC], [AC_DEFUN([_LT_PROG_FC])]) +m4_ifndef([_LT_PROG_CXX], [AC_DEFUN([_LT_PROG_CXX])]) diff --git a/third_party/curl/m4/xc-am-iface.m4 b/third_party/curl/m4/xc-am-iface.m4 new file mode 100644 index 0000000..c035f58 --- /dev/null +++ b/third_party/curl/m4/xc-am-iface.m4 @@ -0,0 +1,85 @@ +#--------------------------------------------------------------------------- +# +# xc-am-iface.m4 +# +# Copyright (C) Daniel Stenberg +# +# Permission to use, copy, modify, and distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# +# SPDX-License-Identifier: ISC +# +#--------------------------------------------------------------------------- + +# serial 1 + + +dnl _XC_AUTOMAKE_BODY +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl This macro performs embedding of automake initialization +dnl code into configure script. When automake version 1.14 or +dnl newer is used at configure script generation time, this +dnl results in 'subdir-objects' automake option being used. +dnl When using automake versions older than 1.14 this option +dnl is not used when generating configure script. +dnl +dnl Existence of automake _AM_PROG_CC_C_O m4 private macro +dnl is used to differentiate automake version 1.14 from older +dnl ones which lack this macro. + +m4_define([_XC_AUTOMAKE_BODY], +[dnl +## --------------------------------------- ## +## Start of automake initialization code ## +## --------------------------------------- ## +m4_ifdef([_AM_PROG_CC_C_O], +[ +AM_INIT_AUTOMAKE([subdir-objects]) +],[ +AM_INIT_AUTOMAKE +])dnl +## ------------------------------------- ## +## End of automake initialization code ## +## ------------------------------------- ## +dnl +m4_define([$0], [])[]dnl +]) + + +dnl XC_AUTOMAKE +dnl ------------------------------------------------- +dnl Public macro. +dnl +dnl This macro embeds automake machinery into configure +dnl script regardless of automake version used in order +dnl to generate configure script. +dnl +dnl When using automake version 1.14 or newer, automake +dnl initialization option 'subdir-objects' is used to +dnl generate the configure script, otherwise this option +dnl is not used. + +AC_DEFUN([XC_AUTOMAKE], +[dnl +AC_PREREQ([2.50])dnl +dnl +AC_BEFORE([$0],[AM_INIT_AUTOMAKE])dnl +dnl +_XC_AUTOMAKE_BODY +dnl +m4_ifdef([AM_INIT_AUTOMAKE], + [m4_undefine([AM_INIT_AUTOMAKE])])dnl +dnl +m4_define([$0], [])[]dnl +]) diff --git a/third_party/curl/m4/xc-cc-check.m4 b/third_party/curl/m4/xc-cc-check.m4 new file mode 100644 index 0000000..a6cfb07 --- /dev/null +++ b/third_party/curl/m4/xc-cc-check.m4 @@ -0,0 +1,97 @@ +#--------------------------------------------------------------------------- +# +# xc-cc-check.m4 +# +# Copyright (C), Daniel Stenberg +# +# Permission to use, copy, modify, and distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# +# SPDX-License-Identifier: ISC +# +#--------------------------------------------------------------------------- + +# serial 1 + + +dnl _XC_PROG_CC_PREAMBLE +dnl ------------------------------------------------- +dnl Private macro. + +AC_DEFUN([_XC_PROG_CC_PREAMBLE], [ + xc_prog_cc_prev_IFS=$IFS + xc_prog_cc_prev_LIBS=$LIBS + xc_prog_cc_prev_CFLAGS=$CFLAGS + xc_prog_cc_prev_LDFLAGS=$LDFLAGS + xc_prog_cc_prev_CPPFLAGS=$CPPFLAGS +]) + + +dnl _XC_PROG_CC_POSTLUDE +dnl ------------------------------------------------- +dnl Private macro. + +AC_DEFUN([_XC_PROG_CC_POSTLUDE], [ + IFS=$xc_prog_cc_prev_IFS + LIBS=$xc_prog_cc_prev_LIBS + CFLAGS=$xc_prog_cc_prev_CFLAGS + LDFLAGS=$xc_prog_cc_prev_LDFLAGS + CPPFLAGS=$xc_prog_cc_prev_CPPFLAGS + AC_SUBST([CC])dnl + AC_SUBST([CPP])dnl + AC_SUBST([LIBS])dnl + AC_SUBST([CFLAGS])dnl + AC_SUBST([LDFLAGS])dnl + AC_SUBST([CPPFLAGS])dnl +]) + + +dnl _XC_PROG_CC +dnl ------------------------------------------------- +dnl Private macro. + +AC_DEFUN([_XC_PROG_CC], [ + AC_REQUIRE([_XC_PROG_CC_PREAMBLE])dnl + AC_REQUIRE([XC_CHECK_BUILD_FLAGS])dnl + AC_REQUIRE([AC_PROG_INSTALL])dnl + AC_REQUIRE([AC_PROG_CC])dnl + AC_REQUIRE([AM_PROG_CC_C_O])dnl + AC_REQUIRE([AC_PROG_CPP])dnl + AC_REQUIRE([_XC_PROG_CC_POSTLUDE])dnl +]) + + +dnl XC_CHECK_PROG_CC +dnl ------------------------------------------------- +dnl Public macro. +dnl +dnl Checks for C compiler and C preprocessor programs, +dnl while doing some previous sanity validation on user +dnl provided LIBS, LDFLAGS, CPPFLAGS and CFLAGS values +dnl that must succeed in order to continue execution. +dnl +dnl This sets variables CC and CPP, while preventing +dnl LIBS, LDFLAGS, CFLAGS, CPPFLAGS and IFS from being +dnl unexpectedly changed by underlying macros. + +AC_DEFUN([XC_CHECK_PROG_CC], [ + AC_PREREQ([2.50])dnl + AC_BEFORE([$0],[_XC_PROG_CC_PREAMBLE])dnl + AC_BEFORE([$0],[AC_PROG_INSTALL])dnl + AC_BEFORE([$0],[AC_PROG_CC])dnl + AC_BEFORE([$0],[AM_PROG_CC_C_O])dnl + AC_BEFORE([$0],[AC_PROG_CPP])dnl + AC_BEFORE([$0],[AC_PROG_LIBTOOL])dnl + AC_BEFORE([$0],[AM_INIT_AUTOMAKE])dnl + AC_BEFORE([$0],[_XC_PROG_CC_POSTLUDE])dnl + AC_REQUIRE([_XC_PROG_CC])dnl +]) diff --git a/third_party/curl/m4/xc-lt-iface.m4 b/third_party/curl/m4/xc-lt-iface.m4 new file mode 100644 index 0000000..d5e437f --- /dev/null +++ b/third_party/curl/m4/xc-lt-iface.m4 @@ -0,0 +1,466 @@ +#--------------------------------------------------------------------------- +# +# xc-lt-iface.m4 +# +# Copyright (C), Daniel Stenberg +# +# Permission to use, copy, modify, and distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# +# SPDX-License-Identifier: ISC +# +#--------------------------------------------------------------------------- + +# serial 1 + + +dnl _XC_LIBTOOL_PREAMBLE +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Checks some configure script options related with +dnl libtool and customizes its default behavior before +dnl libtool code is actually used in script. + +m4_define([_XC_LIBTOOL_PREAMBLE], +[dnl +# ------------------------------------ # +# Determine libtool default behavior # +# ------------------------------------ # + +# +# Default behavior is to enable shared and static libraries on systems +# where libtool knows how to build both library versions, and does not +# require separate configuration and build runs for each flavor. +# + +xc_lt_want_enable_shared='yes' +xc_lt_want_enable_static='yes' + +# +# User may have disabled shared or static libraries. +# +case "x$enable_shared" in @%:@ ( + xno) + xc_lt_want_enable_shared='no' + ;; +esac +case "x$enable_static" in @%:@ ( + xno) + xc_lt_want_enable_static='no' + ;; +esac +if test "x$xc_lt_want_enable_shared" = 'xno' && + test "x$xc_lt_want_enable_static" = 'xno'; then + AC_MSG_ERROR([can not disable shared and static libraries simultaneously]) +fi + +# +# Default behavior on systems that require independent configuration +# and build runs for shared and static is to enable shared libraries +# and disable static ones. On these systems option '--disable-shared' +# must be used in order to build a proper static library. +# + +if test "x$xc_lt_want_enable_shared" = 'xyes' && + test "x$xc_lt_want_enable_static" = 'xyes'; then + case $host_os in @%:@ ( + pw32* | cegcc* | os2* | aix*) + xc_lt_want_enable_static='no' + ;; + esac +fi + +# +# Make libtool aware of current shared and static library preferences +# taking in account that, depending on host characteristics, libtool +# may modify these option preferences later in this configure script. +# + +enable_shared=$xc_lt_want_enable_shared +enable_static=$xc_lt_want_enable_static + +# +# Default behavior is to build PIC objects for shared libraries and +# non-PIC objects for static libraries. +# + +xc_lt_want_with_pic='default' + +# +# User may have specified PIC preference. +# + +case "x$with_pic" in @%:@ (( + xno) + xc_lt_want_with_pic='no' + ;; + xyes) + xc_lt_want_with_pic='yes' + ;; +esac + +# +# Default behavior on some systems where building a shared library out +# of non-PIC compiled objects will fail with following linker error +# "relocation R_X86_64_32 can not be used when making a shared object" +# is to build PIC objects even for static libraries. This behavior may +# be overridden using 'configure --disable-shared --without-pic'. +# + +if test "x$xc_lt_want_with_pic" = 'xdefault'; then + case $host_cpu in @%:@ ( + x86_64 | amd64 | ia64) + case $host_os in @%:@ ( + linux* | freebsd* | midnightbsd*) + xc_lt_want_with_pic='yes' + ;; + esac + ;; + esac +fi + +# +# Make libtool aware of current PIC preference taking in account that, +# depending on host characteristics, libtool may modify PIC default +# behavior to fit host system idiosyncrasies later in this script. +# + +with_pic=$xc_lt_want_with_pic +dnl +m4_define([$0],[])dnl +]) + + +dnl _XC_LIBTOOL_BODY +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl This macro performs embedding of libtool code into +dnl configure script, regardless of libtool version in +dnl use when generating configure script. + +m4_define([_XC_LIBTOOL_BODY], +[dnl +## ----------------------- ## +## Start of libtool code ## +## ----------------------- ## +m4_ifdef([LT_INIT], +[dnl +LT_INIT([win32-dll]) +],[dnl +AC_LIBTOOL_WIN32_DLL +AC_PROG_LIBTOOL +])dnl +## --------------------- ## +## End of libtool code ## +## --------------------- ## +dnl +m4_define([$0], [])[]dnl +]) + + +dnl _XC_CHECK_LT_BUILD_LIBRARIES +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Checks whether libtool shared and static libraries +dnl are finally built depending on user input, default +dnl behavior and knowledge that libtool has about host +dnl characteristics. +dnl Results stored in following shell variables: +dnl xc_lt_build_shared +dnl xc_lt_build_static + +m4_define([_XC_CHECK_LT_BUILD_LIBRARIES], +[dnl +# +# Verify if finally libtool shared libraries will be built +# + +case "x$enable_shared" in @%:@ (( + xyes | xno) + xc_lt_build_shared=$enable_shared + ;; + *) + AC_MSG_ERROR([unexpected libtool enable_shared value: $enable_shared]) + ;; +esac + +# +# Verify if finally libtool static libraries will be built +# + +case "x$enable_static" in @%:@ (( + xyes | xno) + xc_lt_build_static=$enable_static + ;; + *) + AC_MSG_ERROR([unexpected libtool enable_static value: $enable_static]) + ;; +esac +dnl +m4_define([$0],[])dnl +]) + + +dnl _XC_CHECK_LT_SHLIB_USE_VERSION_INFO +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Checks if the -version-info linker flag must be +dnl provided when building libtool shared libraries. +dnl Result stored in xc_lt_shlib_use_version_info. + +m4_define([_XC_CHECK_LT_SHLIB_USE_VERSION_INFO], +[dnl +# +# Verify if libtool shared libraries should be linked using flag -version-info +# + +AC_MSG_CHECKING([whether to build shared libraries with -version-info]) +xc_lt_shlib_use_version_info='yes' +if test "x$version_type" = 'xnone'; then + xc_lt_shlib_use_version_info='no' +fi +case $host_os in @%:@ ( + amigaos*) + xc_lt_shlib_use_version_info='yes' + ;; +esac +AC_MSG_RESULT([$xc_lt_shlib_use_version_info]) +dnl +m4_define([$0], [])[]dnl +]) + + +dnl _XC_CHECK_LT_SHLIB_USE_NO_UNDEFINED +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Checks if the -no-undefined linker flag must be +dnl provided when building libtool shared libraries. +dnl Result stored in xc_lt_shlib_use_no_undefined. + +m4_define([_XC_CHECK_LT_SHLIB_USE_NO_UNDEFINED], +[dnl +# +# Verify if libtool shared libraries should be linked using flag -no-undefined +# + +AC_MSG_CHECKING([whether to build shared libraries with -no-undefined]) +xc_lt_shlib_use_no_undefined='no' +if test "x$allow_undefined" = 'xno'; then + xc_lt_shlib_use_no_undefined='yes' +elif test "x$allow_undefined_flag" = 'xunsupported'; then + xc_lt_shlib_use_no_undefined='yes' +fi +case $host_os in @%:@ ( + cygwin* | mingw* | pw32* | cegcc* | os2* | aix*) + xc_lt_shlib_use_no_undefined='yes' + ;; +esac +AC_MSG_RESULT([$xc_lt_shlib_use_no_undefined]) +dnl +m4_define([$0], [])[]dnl +]) + + +dnl _XC_CHECK_LT_SHLIB_USE_MIMPURE_TEXT +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Checks if the -mimpure-text linker flag must be +dnl provided when building libtool shared libraries. +dnl Result stored in xc_lt_shlib_use_mimpure_text. + +m4_define([_XC_CHECK_LT_SHLIB_USE_MIMPURE_TEXT], +[dnl +# +# Verify if libtool shared libraries should be linked using flag -mimpure-text +# + +AC_MSG_CHECKING([whether to build shared libraries with -mimpure-text]) +xc_lt_shlib_use_mimpure_text='no' +case $host_os in @%:@ ( + solaris2*) + if test "x$GCC" = 'xyes'; then + xc_lt_shlib_use_mimpure_text='yes' + fi + ;; +esac +AC_MSG_RESULT([$xc_lt_shlib_use_mimpure_text]) +dnl +m4_define([$0], [])[]dnl +]) + + +dnl _XC_CHECK_LT_BUILD_WITH_PIC +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Checks whether libtool shared and static libraries +dnl would be built with PIC depending on user input, +dnl default behavior and knowledge that libtool has +dnl about host characteristics. +dnl Results stored in following shell variables: +dnl xc_lt_build_shared_with_pic +dnl xc_lt_build_static_with_pic + +m4_define([_XC_CHECK_LT_BUILD_WITH_PIC], +[dnl +# +# Find out whether libtool libraries would be built with PIC +# + +case "x$pic_mode" in @%:@ (((( + xdefault) + xc_lt_build_shared_with_pic='yes' + xc_lt_build_static_with_pic='no' + ;; + xyes) + xc_lt_build_shared_with_pic='yes' + xc_lt_build_static_with_pic='yes' + ;; + xno) + xc_lt_build_shared_with_pic='no' + xc_lt_build_static_with_pic='no' + ;; + *) + xc_lt_build_shared_with_pic='unknown' + xc_lt_build_static_with_pic='unknown' + AC_MSG_WARN([unexpected libtool pic_mode value: $pic_mode]) + ;; +esac +AC_MSG_CHECKING([whether to build shared libraries with PIC]) +AC_MSG_RESULT([$xc_lt_build_shared_with_pic]) +AC_MSG_CHECKING([whether to build static libraries with PIC]) +AC_MSG_RESULT([$xc_lt_build_static_with_pic]) +dnl +m4_define([$0],[])dnl +]) + + +dnl _XC_CHECK_LT_BUILD_SINGLE_VERSION +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Checks whether a libtool shared or static library +dnl is finally built exclusively without the other. +dnl Results stored in following shell variables: +dnl xc_lt_build_shared_only +dnl xc_lt_build_static_only + +m4_define([_XC_CHECK_LT_BUILD_SINGLE_VERSION], +[dnl +# +# Verify if libtool shared libraries will be built while static not built +# + +AC_MSG_CHECKING([whether to build shared libraries only]) +if test "$xc_lt_build_shared" = 'yes' && + test "$xc_lt_build_static" = 'no'; then + xc_lt_build_shared_only='yes' +else + xc_lt_build_shared_only='no' +fi +AC_MSG_RESULT([$xc_lt_build_shared_only]) + +# +# Verify if libtool static libraries will be built while shared not built +# + +AC_MSG_CHECKING([whether to build static libraries only]) +if test "$xc_lt_build_static" = 'yes' && + test "$xc_lt_build_shared" = 'no'; then + xc_lt_build_static_only='yes' +else + xc_lt_build_static_only='no' +fi +AC_MSG_RESULT([$xc_lt_build_static_only]) +dnl +m4_define([$0],[])dnl +]) + + +dnl _XC_LIBTOOL_POSTLUDE +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Performs several checks related with libtool that +dnl can not be done unless libtool code has already +dnl been executed. See individual check descriptions +dnl for further info. + +m4_define([_XC_LIBTOOL_POSTLUDE], +[dnl +_XC_CHECK_LT_BUILD_LIBRARIES +_XC_CHECK_LT_SHLIB_USE_VERSION_INFO +_XC_CHECK_LT_SHLIB_USE_NO_UNDEFINED +_XC_CHECK_LT_SHLIB_USE_MIMPURE_TEXT +_XC_CHECK_LT_BUILD_WITH_PIC +_XC_CHECK_LT_BUILD_SINGLE_VERSION +dnl +m4_define([$0],[])dnl +]) + + +dnl XC_LIBTOOL +dnl ------------------------------------------------- +dnl Public macro. +dnl +dnl This macro embeds libtool machinery into configure +dnl script, regardless of libtool version, and performs +dnl several additional checks whose results can be used +dnl later on. +dnl +dnl Usage of this macro ensures that generated configure +dnl script uses equivalent logic irrespective of autoconf +dnl or libtool version being used to generate configure +dnl script. +dnl +dnl Results stored in following shell variables: +dnl xc_lt_build_shared +dnl xc_lt_build_static +dnl xc_lt_shlib_use_version_info +dnl xc_lt_shlib_use_no_undefined +dnl xc_lt_shlib_use_mimpure_text +dnl xc_lt_build_shared_with_pic +dnl xc_lt_build_static_with_pic +dnl xc_lt_build_shared_only +dnl xc_lt_build_static_only + +AC_DEFUN([XC_LIBTOOL], +[dnl +AC_PREREQ([2.50])dnl +dnl +AC_BEFORE([$0],[LT_INIT])dnl +AC_BEFORE([$0],[AC_PROG_LIBTOOL])dnl +AC_BEFORE([$0],[AC_LIBTOOL_WIN32_DLL])dnl +dnl +AC_REQUIRE([XC_CHECK_PATH_SEPARATOR])dnl +AC_REQUIRE([AC_CANONICAL_HOST])dnl +AC_REQUIRE([AC_PROG_CC])dnl +dnl +_XC_LIBTOOL_PREAMBLE +_XC_LIBTOOL_BODY +_XC_LIBTOOL_POSTLUDE +dnl +m4_ifdef([AC_LIBTOOL_WIN32_DLL], + [m4_undefine([AC_LIBTOOL_WIN32_DLL])])dnl +m4_ifdef([AC_PROG_LIBTOOL], + [m4_undefine([AC_PROG_LIBTOOL])])dnl +m4_ifdef([LT_INIT], + [m4_undefine([LT_INIT])])dnl +dnl +m4_define([$0],[])dnl +]) diff --git a/third_party/curl/m4/xc-translit.m4 b/third_party/curl/m4/xc-translit.m4 new file mode 100644 index 0000000..6d66771 --- /dev/null +++ b/third_party/curl/m4/xc-translit.m4 @@ -0,0 +1,165 @@ +#--------------------------------------------------------------------------- +# +# xc-translit.m4 +# +# Copyright (C), Daniel Stenberg +# +# Permission to use, copy, modify, and distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# +# SPDX-License-Identifier: ISC +# +#--------------------------------------------------------------------------- + +# File version for 'aclocal' use. Keep it a single number. +# serial 2 + + +dnl XC_SH_TR_SH (expression) +dnl ------------------------------------------------- +dnl Shell execution time transliteration of 'expression' +dnl argument, where all non-alfanumeric characters are +dnl converted to the underscore '_' character. +dnl Normal shell expansion and substitution takes place +dnl for given 'expression' at shell execution time before +dnl transliteration is applied to it. + +AC_DEFUN([XC_SH_TR_SH], +[`echo "$1" | sed 's/[[^a-zA-Z0-9_]]/_/g'`]) + + +dnl XC_SH_TR_SH_EX (expression, [extra]) +dnl ------------------------------------------------- +dnl Like XC_SH_TR_SH but transliterating characters +dnl given in 'extra' argument to lowercase 'p'. For +dnl example [*+], [*], and [+] are valid 'extra' args. + +AC_DEFUN([XC_SH_TR_SH_EX], +[ifelse([$2], [], + [XC_SH_TR_SH([$1])], + [`echo "$1" | sed 's/[[$2]]/p/g' | sed 's/[[^a-zA-Z0-9_]]/_/g'`])]) + + +dnl XC_M4_TR_SH (expression) +dnl ------------------------------------------------- +dnl m4 execution time transliteration of 'expression' +dnl argument, where all non-alfanumeric characters are +dnl converted to the underscore '_' character. + +AC_DEFUN([XC_M4_TR_SH], +[patsubst(XC_QPATSUBST(XC_QUOTE($1), + [[^a-zA-Z0-9_]], [_]), + [\(_\(.*\)_\)], [\2])]) + + +dnl XC_M4_TR_SH_EX (expression, [extra]) +dnl ------------------------------------------------- +dnl Like XC_M4_TR_SH but transliterating characters +dnl given in 'extra' argument to lowercase 'p'. For +dnl example [*+], [*], and [+] are valid 'extra' args. + +AC_DEFUN([XC_M4_TR_SH_EX], +[ifelse([$2], [], + [XC_M4_TR_SH([$1])], + [patsubst(XC_QPATSUBST(XC_QPATSUBST(XC_QUOTE($1), + [[$2]], + [p]), + [[^a-zA-Z0-9_]], [_]), + [\(_\(.*\)_\)], [\2])])]) + + +dnl XC_SH_TR_CPP (expression) +dnl ------------------------------------------------- +dnl Shell execution time transliteration of 'expression' +dnl argument, where all non-alfanumeric characters are +dnl converted to the underscore '_' character and alnum +dnl characters are converted to uppercase. +dnl Normal shell expansion and substitution takes place +dnl for given 'expression' at shell execution time before +dnl transliteration is applied to it. + +AC_DEFUN([XC_SH_TR_CPP], +[`echo "$1" | dnl +sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/' | dnl +sed 's/[[^A-Z0-9_]]/_/g'`]) + + +dnl XC_SH_TR_CPP_EX (expression, [extra]) +dnl ------------------------------------------------- +dnl Like XC_SH_TR_CPP but transliterating characters +dnl given in 'extra' argument to uppercase 'P'. For +dnl example [*+], [*], and [+] are valid 'extra' args. + +AC_DEFUN([XC_SH_TR_CPP_EX], +[ifelse([$2], [], + [XC_SH_TR_CPP([$1])], + [`echo "$1" | dnl +sed 's/[[$2]]/P/g' | dnl +sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/' | dnl +sed 's/[[^A-Z0-9_]]/_/g'`])]) + + +dnl XC_M4_TR_CPP (expression) +dnl ------------------------------------------------- +dnl m4 execution time transliteration of 'expression' +dnl argument, where all non-alfanumeric characters are +dnl converted to the underscore '_' character and alnum +dnl characters are converted to uppercase. + +AC_DEFUN([XC_M4_TR_CPP], +[patsubst(XC_QPATSUBST(XC_QTRANSLIT(XC_QUOTE($1), + [abcdefghijklmnopqrstuvwxyz], + [ABCDEFGHIJKLMNOPQRSTUVWXYZ]), + [[^A-Z0-9_]], [_]), + [\(_\(.*\)_\)], [\2])]) + + +dnl XC_M4_TR_CPP_EX (expression, [extra]) +dnl ------------------------------------------------- +dnl Like XC_M4_TR_CPP but transliterating characters +dnl given in 'extra' argument to uppercase 'P'. For +dnl example [*+], [*], and [+] are valid 'extra' args. + +AC_DEFUN([XC_M4_TR_CPP_EX], +[ifelse([$2], [], + [XC_M4_TR_CPP([$1])], + [patsubst(XC_QPATSUBST(XC_QTRANSLIT(XC_QPATSUBST(XC_QUOTE($1), + [[$2]], + [P]), + [abcdefghijklmnopqrstuvwxyz], + [ABCDEFGHIJKLMNOPQRSTUVWXYZ]), + [[^A-Z0-9_]], [_]), + [\(_\(.*\)_\)], [\2])])]) + + +dnl XC_QUOTE (expression) +dnl ------------------------------------------------- +dnl Expands to quoted result of 'expression' expansion. + +AC_DEFUN([XC_QUOTE], +[[$@]]) + + +dnl XC_QPATSUBST (string, regexp[, repl]) +dnl ------------------------------------------------- +dnl Expands to quoted result of 'patsubst' expansion. + +AC_DEFUN([XC_QPATSUBST], +[XC_QUOTE(patsubst([$1], [$2], [$3]))]) + + +dnl XC_QTRANSLIT (string, chars, repl) +dnl ------------------------------------------------- +dnl Expands to quoted result of 'translit' expansion. + +AC_DEFUN([XC_QTRANSLIT], +[XC_QUOTE(translit([$1], [$2], [$3]))]) diff --git a/third_party/curl/m4/xc-val-flgs.m4 b/third_party/curl/m4/xc-val-flgs.m4 new file mode 100644 index 0000000..c8f7796 --- /dev/null +++ b/third_party/curl/m4/xc-val-flgs.m4 @@ -0,0 +1,244 @@ +#--------------------------------------------------------------------------- +# +# xc-val-flgs.m4 +# +# Copyright (C), Daniel Stenberg +# +# Permission to use, copy, modify, and distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# +# SPDX-License-Identifier: ISC +# +#--------------------------------------------------------------------------- + +# serial 1 + + +dnl _XC_CHECK_VAR_LIBS +dnl ------------------------------------------------- +dnl Private macro. + +AC_DEFUN([_XC_CHECK_VAR_LIBS], [ + xc_bad_var_libs=no + for xc_word in $LIBS; do + case "$xc_word" in + -l* | --library=*) + : + ;; + *) + xc_bad_var_libs=yes + ;; + esac + done + if test $xc_bad_var_libs = yes; then + AC_MSG_NOTICE([using LIBS: $LIBS]) + AC_MSG_NOTICE([LIBS note: LIBS should only be used to specify libraries (-lname).]) + fi +]) + + +dnl _XC_CHECK_VAR_LDFLAGS +dnl ------------------------------------------------- +dnl Private macro. + +AC_DEFUN([_XC_CHECK_VAR_LDFLAGS], [ + xc_bad_var_ldflags=no + for xc_word in $LDFLAGS; do + case "$xc_word" in + -D*) + xc_bad_var_ldflags=yes + ;; + -U*) + xc_bad_var_ldflags=yes + ;; + -I*) + xc_bad_var_ldflags=yes + ;; + -l* | --library=*) + xc_bad_var_ldflags=yes + ;; + esac + done + if test $xc_bad_var_ldflags = yes; then + AC_MSG_NOTICE([using LDFLAGS: $LDFLAGS]) + xc_bad_var_msg="LDFLAGS note: LDFLAGS should only be used to specify linker flags, not" + for xc_word in $LDFLAGS; do + case "$xc_word" in + -D*) + AC_MSG_NOTICE([$xc_bad_var_msg macro definitions. Use CPPFLAGS for: $xc_word]) + ;; + -U*) + AC_MSG_NOTICE([$xc_bad_var_msg macro suppressions. Use CPPFLAGS for: $xc_word]) + ;; + -I*) + AC_MSG_NOTICE([$xc_bad_var_msg include directories. Use CPPFLAGS for: $xc_word]) + ;; + -l* | --library=*) + AC_MSG_NOTICE([$xc_bad_var_msg libraries. Use LIBS for: $xc_word]) + ;; + esac + done + fi +]) + + +dnl _XC_CHECK_VAR_CPPFLAGS +dnl ------------------------------------------------- +dnl Private macro. + +AC_DEFUN([_XC_CHECK_VAR_CPPFLAGS], [ + xc_bad_var_cppflags=no + for xc_word in $CPPFLAGS; do + case "$xc_word" in + -rpath*) + xc_bad_var_cppflags=yes + ;; + -L* | --library-path=*) + xc_bad_var_cppflags=yes + ;; + -l* | --library=*) + xc_bad_var_cppflags=yes + ;; + esac + done + if test $xc_bad_var_cppflags = yes; then + AC_MSG_NOTICE([using CPPFLAGS: $CPPFLAGS]) + xc_bad_var_msg="CPPFLAGS note: CPPFLAGS should only be used to specify C preprocessor flags, not" + for xc_word in $CPPFLAGS; do + case "$xc_word" in + -rpath*) + AC_MSG_NOTICE([$xc_bad_var_msg library runtime directories. Use LDFLAGS for: $xc_word]) + ;; + -L* | --library-path=*) + AC_MSG_NOTICE([$xc_bad_var_msg library directories. Use LDFLAGS for: $xc_word]) + ;; + -l* | --library=*) + AC_MSG_NOTICE([$xc_bad_var_msg libraries. Use LIBS for: $xc_word]) + ;; + esac + done + fi +]) + + +dnl _XC_CHECK_VAR_CFLAGS +dnl ------------------------------------------------- +dnl Private macro. + +AC_DEFUN([_XC_CHECK_VAR_CFLAGS], [ + xc_bad_var_cflags=no + for xc_word in $CFLAGS; do + case "$xc_word" in + -D*) + xc_bad_var_cflags=yes + ;; + -U*) + xc_bad_var_cflags=yes + ;; + -I*) + xc_bad_var_cflags=yes + ;; + -rpath*) + xc_bad_var_cflags=yes + ;; + -L* | --library-path=*) + xc_bad_var_cflags=yes + ;; + -l* | --library=*) + xc_bad_var_cflags=yes + ;; + esac + done + if test $xc_bad_var_cflags = yes; then + AC_MSG_NOTICE([using CFLAGS: $CFLAGS]) + xc_bad_var_msg="CFLAGS note: CFLAGS should only be used to specify C compiler flags, not" + for xc_word in $CFLAGS; do + case "$xc_word" in + -D*) + AC_MSG_NOTICE([$xc_bad_var_msg macro definitions. Use CPPFLAGS for: $xc_word]) + ;; + -U*) + AC_MSG_NOTICE([$xc_bad_var_msg macro suppressions. Use CPPFLAGS for: $xc_word]) + ;; + -I*) + AC_MSG_NOTICE([$xc_bad_var_msg include directories. Use CPPFLAGS for: $xc_word]) + ;; + -rpath*) + AC_MSG_NOTICE([$xc_bad_var_msg library runtime directories. Use LDFLAGS for: $xc_word]) + ;; + -L* | --library-path=*) + AC_MSG_NOTICE([$xc_bad_var_msg library directories. Use LDFLAGS for: $xc_word]) + ;; + -l* | --library=*) + AC_MSG_NOTICE([$xc_bad_var_msg libraries. Use LIBS for: $xc_word]) + ;; + esac + done + fi +]) + + +dnl XC_CHECK_USER_FLAGS +dnl ------------------------------------------------- +dnl Public macro. +dnl +dnl Performs some sanity checks for LIBS, LDFLAGS, +dnl CPPFLAGS and CFLAGS values that the user might +dnl have set. When checks fails, user is noticed +dnl about errors detected in all of them and script +dnl execution is halted. +dnl +dnl Intended to be used early in configure script. + +AC_DEFUN([XC_CHECK_USER_FLAGS], [ + AC_PREREQ([2.50])dnl + AC_BEFORE([$0],[XC_CHECK_PROG_CC])dnl + dnl check order below matters + _XC_CHECK_VAR_LIBS + _XC_CHECK_VAR_LDFLAGS + _XC_CHECK_VAR_CPPFLAGS + _XC_CHECK_VAR_CFLAGS + if test $xc_bad_var_libs = yes || + test $xc_bad_var_cflags = yes || + test $xc_bad_var_ldflags = yes || + test $xc_bad_var_cppflags = yes; then + AC_MSG_ERROR([Can not continue. Fix errors mentioned immediately above this line.]) + fi +]) + + +dnl XC_CHECK_BUILD_FLAGS +dnl ------------------------------------------------- +dnl Public macro. +dnl +dnl Performs some sanity checks for LIBS, LDFLAGS, +dnl CPPFLAGS and CFLAGS values that the configure +dnl script might have set. When checks fails, user +dnl is noticed about errors detected in all of them +dnl but script continues execution. +dnl +dnl Intended to be used very late in configure script. + +AC_DEFUN([XC_CHECK_BUILD_FLAGS], [ + AC_PREREQ([2.50])dnl + dnl check order below matters + _XC_CHECK_VAR_LIBS + _XC_CHECK_VAR_LDFLAGS + _XC_CHECK_VAR_CPPFLAGS + _XC_CHECK_VAR_CFLAGS + if test $xc_bad_var_libs = yes || + test $xc_bad_var_cflags = yes || + test $xc_bad_var_ldflags = yes || + test $xc_bad_var_cppflags = yes; then + AC_MSG_WARN([Continuing even with errors mentioned immediately above this line.]) + fi +]) diff --git a/third_party/curl/m4/zz40-xc-ovr.m4 b/third_party/curl/m4/zz40-xc-ovr.m4 new file mode 100644 index 0000000..fa45787 --- /dev/null +++ b/third_party/curl/m4/zz40-xc-ovr.m4 @@ -0,0 +1,667 @@ +#--------------------------------------------------------------------------- +# +# zz40-xc-ovr.m4 +# +# Copyright (C) Daniel Stenberg +# +# Permission to use, copy, modify, and distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# +# SPDX-License-Identifier: ISC +# +#--------------------------------------------------------------------------- + +dnl The funny name of this file is intentional in order to make it +dnl sort alphabetically after any libtool, autoconf or automake +dnl provided .m4 macro file that might get copied into this same +dnl subdirectory. This allows that macro (re)definitions from this +dnl file may override those provided in other files. + + +dnl Version macros +dnl ------------------------------------------------- +dnl Public macros. + +m4_define([XC_CONFIGURE_PREAMBLE_VER_MAJOR],[1])dnl +m4_define([XC_CONFIGURE_PREAMBLE_VER_MINOR],[0])dnl + + +dnl _XC_CFG_PRE_PREAMBLE +dnl ------------------------------------------------- +dnl Private macro. + +AC_DEFUN([_XC_CFG_PRE_PREAMBLE], +[ +## -------------------------------- ## +@%:@@%:@ [XC_CONFIGURE_PREAMBLE] ver: []dnl +XC_CONFIGURE_PREAMBLE_VER_MAJOR.[]dnl +XC_CONFIGURE_PREAMBLE_VER_MINOR ## +## -------------------------------- ## + +xc_configure_preamble_ver_major='XC_CONFIGURE_PREAMBLE_VER_MAJOR' +xc_configure_preamble_ver_minor='XC_CONFIGURE_PREAMBLE_VER_MINOR' + +# +# Set IFS to space, tab and newline. +# + +xc_space=' ' +xc_tab=' ' +xc_newline=' +' +IFS="$xc_space$xc_tab$xc_newline" + +# +# Set internationalization behavior variables. +# + +LANG='C' +LC_ALL='C' +LANGUAGE='C' +export LANG +export LC_ALL +export LANGUAGE + +# +# Some useful variables. +# + +xc_msg_warn='configure: WARNING:' +xc_msg_abrt='Can not continue.' +xc_msg_err='configure: error:' +]) + + +dnl _XC_CFG_PRE_BASIC_CHK_CMD_ECHO +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Emits shell code that verifies that 'echo' command +dnl is available, otherwise aborts execution. + +AC_DEFUN([_XC_CFG_PRE_BASIC_CHK_CMD_ECHO], +[dnl +AC_REQUIRE([_XC_CFG_PRE_PREAMBLE])dnl +# +# Verify that 'echo' command is available, otherwise abort. +# + +xc_tst_str='unknown' +(`echo "$xc_tst_str" >/dev/null 2>&1`) && xc_tst_str='success' +case "x$xc_tst_str" in @%:@ (( + xsuccess) + : + ;; + *) + # Try built-in echo, and fail. + echo "$xc_msg_err 'echo' command not found. $xc_msg_abrt" >&2 + exit 1 + ;; +esac +]) + + +dnl _XC_CFG_PRE_BASIC_CHK_CMD_TEST +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Emits shell code that verifies that 'test' command +dnl is available, otherwise aborts execution. + +AC_DEFUN([_XC_CFG_PRE_BASIC_CHK_CMD_TEST], +[dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_CMD_ECHO])dnl +# +# Verify that 'test' command is available, otherwise abort. +# + +xc_tst_str='unknown' +(`test -n "$xc_tst_str" >/dev/null 2>&1`) && xc_tst_str='success' +case "x$xc_tst_str" in @%:@ (( + xsuccess) + : + ;; + *) + echo "$xc_msg_err 'test' command not found. $xc_msg_abrt" >&2 + exit 1 + ;; +esac +]) + + +dnl _XC_CFG_PRE_BASIC_CHK_VAR_PATH +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Emits shell code that verifies that 'PATH' variable +dnl is set, otherwise aborts execution. + +AC_DEFUN([_XC_CFG_PRE_BASIC_CHK_VAR_PATH], +[dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_CMD_TEST])dnl +# +# Verify that 'PATH' variable is set, otherwise abort. +# + +xc_tst_str='unknown' +(`test -n "$PATH" >/dev/null 2>&1`) && xc_tst_str='success' +case "x$xc_tst_str" in @%:@ (( + xsuccess) + : + ;; + *) + echo "$xc_msg_err 'PATH' variable not set. $xc_msg_abrt" >&2 + exit 1 + ;; +esac +]) + + +dnl _XC_CFG_PRE_BASIC_CHK_CMD_EXPR +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Emits shell code that verifies that 'expr' command +dnl is available, otherwise aborts execution. + +AC_DEFUN([_XC_CFG_PRE_BASIC_CHK_CMD_EXPR], +[dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_VAR_PATH])dnl +# +# Verify that 'expr' command is available, otherwise abort. +# + +xc_tst_str='unknown' +xc_tst_str=`expr "$xc_tst_str" : '.*' 2>/dev/null` +case "x$xc_tst_str" in @%:@ (( + x7) + : + ;; + *) + echo "$xc_msg_err 'expr' command not found. $xc_msg_abrt" >&2 + exit 1 + ;; +esac +]) + + +dnl _XC_CFG_PRE_BASIC_CHK_UTIL_SED +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Emits shell code that verifies that 'sed' utility +dnl is found within 'PATH', otherwise aborts execution. +dnl +dnl This 'sed' is required in order to allow configure +dnl script bootstrapping itself. No fancy testing for a +dnl proper 'sed' this early, that should be done later. + +AC_DEFUN([_XC_CFG_PRE_BASIC_CHK_UTIL_SED], +[dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_VAR_PATH])dnl +# +# Verify that 'sed' utility is found within 'PATH', otherwise abort. +# + +xc_tst_str='unknown' +xc_tst_str=`echo "$xc_tst_str" 2>/dev/null \ + | sed -e 's:unknown:success:' 2>/dev/null` +case "x$xc_tst_str" in @%:@ (( + xsuccess) + : + ;; + *) + echo "$xc_msg_err 'sed' utility not found in 'PATH'. $xc_msg_abrt" >&2 + exit 1 + ;; +esac +]) + + +dnl _XC_CFG_PRE_BASIC_CHK_UTIL_GREP +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Emits shell code that verifies that 'grep' utility +dnl is found within 'PATH', otherwise aborts execution. +dnl +dnl This 'grep' is required in order to allow configure +dnl script bootstrapping itself. No fancy testing for a +dnl proper 'grep' this early, that should be done later. + +AC_DEFUN([_XC_CFG_PRE_BASIC_CHK_UTIL_GREP], +[dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_VAR_PATH])dnl +# +# Verify that 'grep' utility is found within 'PATH', otherwise abort. +# + +xc_tst_str='unknown' +(`echo "$xc_tst_str" 2>/dev/null \ + | grep 'unknown' >/dev/null 2>&1`) && xc_tst_str='success' +case "x$xc_tst_str" in @%:@ (( + xsuccess) + : + ;; + *) + echo "$xc_msg_err 'grep' utility not found in 'PATH'. $xc_msg_abrt" >&2 + exit 1 + ;; +esac +]) + + +dnl _XC_CFG_PRE_BASIC_CHK_UTIL_TR +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Emits shell code that verifies that 'tr' utility +dnl is found within 'PATH', otherwise aborts execution. + +AC_DEFUN([_XC_CFG_PRE_BASIC_CHK_UTIL_TR], +[dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_VAR_PATH])dnl +# +# Verify that 'tr' utility is found within 'PATH', otherwise abort. +# + +xc_tst_str="${xc_tab}98s7u6c5c4e3s2s10" +xc_tst_str=`echo "$xc_tst_str" 2>/dev/null \ + | tr -d "0123456789$xc_tab" 2>/dev/null` +case "x$xc_tst_str" in @%:@ (( + xsuccess) + : + ;; + *) + echo "$xc_msg_err 'tr' utility not found in 'PATH'. $xc_msg_abrt" >&2 + exit 1 + ;; +esac +]) + + +dnl _XC_CFG_PRE_BASIC_CHK_UTIL_WC +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Emits shell code that verifies that 'wc' utility +dnl is found within 'PATH', otherwise aborts execution. + +AC_DEFUN([_XC_CFG_PRE_BASIC_CHK_UTIL_WC], +[dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_UTIL_TR])dnl +# +# Verify that 'wc' utility is found within 'PATH', otherwise abort. +# + +xc_tst_str='unknown unknown unknown unknown' +xc_tst_str=`echo "$xc_tst_str" 2>/dev/null \ + | wc -w 2>/dev/null | tr -d "$xc_space$xc_tab" 2>/dev/null` +case "x$xc_tst_str" in @%:@ (( + x4) + : + ;; + *) + echo "$xc_msg_err 'wc' utility not found in 'PATH'. $xc_msg_abrt" >&2 + exit 1 + ;; +esac +]) + + +dnl _XC_CFG_PRE_BASIC_CHK_UTIL_CAT +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Emits shell code that verifies that 'cat' utility +dnl is found within 'PATH', otherwise aborts execution. + +AC_DEFUN([_XC_CFG_PRE_BASIC_CHK_UTIL_CAT], +[dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_UTIL_WC])dnl +# +# Verify that 'cat' utility is found within 'PATH', otherwise abort. +# + +xc_tst_str='unknown' +xc_tst_str=`cat <<_EOT 2>/dev/null \ + | wc -l 2>/dev/null | tr -d "$xc_space$xc_tab" 2>/dev/null +unknown +unknown +unknown +_EOT` +case "x$xc_tst_str" in @%:@ (( + x3) + : + ;; + *) + echo "$xc_msg_err 'cat' utility not found in 'PATH'. $xc_msg_abrt" >&2 + exit 1 + ;; +esac +]) + + +dnl _XC_CFG_PRE_CHECK_PATH_SEPARATOR +dnl ------------------------------------------------- +dnl Private macro. +dnl +dnl Emits shell code that computes the path separator +dnl and stores the result in 'PATH_SEPARATOR', unless +dnl the user has already set it with a non-empty value. +dnl +dnl This path separator is the symbol used to separate +dnl or differentiate paths inside the 'PATH' environment +dnl variable. +dnl +dnl Non-empty user provided 'PATH_SEPARATOR' always +dnl overrides the auto-detected one. + +AC_DEFUN([_XC_CFG_PRE_CHECK_PATH_SEPARATOR], +[dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_CMD_EXPR])dnl +# +# Auto-detect and set 'PATH_SEPARATOR', unless it is already non-empty set. +# + +# Directory count in 'PATH' when using a colon separator. +xc_tst_dirs_col='x' +xc_tst_prev_IFS=$IFS; IFS=':' +for xc_tst_dir in $PATH; do + IFS=$xc_tst_prev_IFS + xc_tst_dirs_col="x$xc_tst_dirs_col" +done +IFS=$xc_tst_prev_IFS +xc_tst_dirs_col=`expr "$xc_tst_dirs_col" : '.*'` + +# Directory count in 'PATH' when using a semicolon separator. +xc_tst_dirs_sem='x' +xc_tst_prev_IFS=$IFS; IFS=';' +for xc_tst_dir in $PATH; do + IFS=$xc_tst_prev_IFS + xc_tst_dirs_sem="x$xc_tst_dirs_sem" +done +IFS=$xc_tst_prev_IFS +xc_tst_dirs_sem=`expr "$xc_tst_dirs_sem" : '.*'` + +if test $xc_tst_dirs_sem -eq $xc_tst_dirs_col; then + # When both counting methods give the same result we do not want to + # chose one over the other, and consider auto-detection not possible. + if test -z "$PATH_SEPARATOR"; then + # User should provide the correct 'PATH_SEPARATOR' definition. + # Until then, guess that it is colon! + echo "$xc_msg_warn path separator not determined, guessing colon" >&2 + PATH_SEPARATOR=':' + fi +else + # Separator with the greater directory count is the auto-detected one. + if test $xc_tst_dirs_sem -gt $xc_tst_dirs_col; then + xc_tst_auto_separator=';' + else + xc_tst_auto_separator=':' + fi + if test -z "$PATH_SEPARATOR"; then + # Simply use the auto-detected one when not already set. + PATH_SEPARATOR=$xc_tst_auto_separator + elif test "x$PATH_SEPARATOR" != "x$xc_tst_auto_separator"; then + echo "$xc_msg_warn 'PATH_SEPARATOR' does not match auto-detected one." >&2 + fi +fi +xc_PATH_SEPARATOR=$PATH_SEPARATOR +AC_SUBST([PATH_SEPARATOR])dnl +]) + + +dnl _XC_CFG_PRE_POSTLUDE +dnl ------------------------------------------------- +dnl Private macro. + +AC_DEFUN([_XC_CFG_PRE_POSTLUDE], +[dnl +AC_REQUIRE([_XC_CFG_PRE_PREAMBLE])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_CMD_ECHO])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_CMD_TEST])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_VAR_PATH])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_CMD_EXPR])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_UTIL_SED])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_UTIL_GREP])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_UTIL_TR])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_UTIL_WC])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_UTIL_CAT])dnl +AC_REQUIRE([_XC_CFG_PRE_CHECK_PATH_SEPARATOR])dnl +dnl +xc_configure_preamble_result='yes' +]) + + +dnl XC_CONFIGURE_PREAMBLE +dnl ------------------------------------------------- +dnl Public macro. +dnl +dnl This macro emits shell code which does some +dnl very basic checks related with the availability +dnl of some commands and utilities needed to allow +dnl configure script bootstrapping itself when using +dnl these to figure out other settings. Also emits +dnl code that performs PATH_SEPARATOR auto-detection +dnl and sets its value unless it is already set with +dnl a non-empty value. +dnl +dnl These basic checks are intended to be placed and +dnl executed as early as possible in the resulting +dnl configure script, and as such these must be pure +dnl and portable shell code. +dnl +dnl This macro may be used directly, or indirectly +dnl when using other macros that AC_REQUIRE it such +dnl as XC_CHECK_PATH_SEPARATOR. +dnl +dnl Currently the mechanism used to ensure that this +dnl macro expands early enough in generated configure +dnl script is making it override autoconf and libtool +dnl PATH_SEPARATOR check. + +AC_DEFUN([XC_CONFIGURE_PREAMBLE], +[dnl +AC_PREREQ([2.50])dnl +dnl +AC_BEFORE([$0],[_XC_CFG_PRE_PREAMBLE])dnl +AC_BEFORE([$0],[_XC_CFG_PRE_BASIC_CHK_CMD_ECHO])dnl +AC_BEFORE([$0],[_XC_CFG_PRE_BASIC_CHK_CMD_TEST])dnl +AC_BEFORE([$0],[_XC_CFG_PRE_BASIC_CHK_VAR_PATH])dnl +AC_BEFORE([$0],[_XC_CFG_PRE_BASIC_CHK_CMD_EXPR])dnl +AC_BEFORE([$0],[_XC_CFG_PRE_BASIC_CHK_UTIL_SED])dnl +AC_BEFORE([$0],[_XC_CFG_PRE_BASIC_CHK_UTIL_GREP])dnl +AC_BEFORE([$0],[_XC_CFG_PRE_BASIC_CHK_UTIL_TR])dnl +AC_BEFORE([$0],[_XC_CFG_PRE_BASIC_CHK_UTIL_WC])dnl +AC_BEFORE([$0],[_XC_CFG_PRE_BASIC_CHK_UTIL_CAT])dnl +AC_BEFORE([$0],[_XC_CFG_PRE_CHECK_PATH_SEPARATOR])dnl +AC_BEFORE([$0],[_XC_CFG_PRE_POSTLUDE])dnl +dnl +AC_BEFORE([$0],[AC_CHECK_TOOL])dnl +AC_BEFORE([$0],[AC_CHECK_PROG])dnl +AC_BEFORE([$0],[AC_CHECK_TOOLS])dnl +AC_BEFORE([$0],[AC_CHECK_PROGS])dnl +dnl +AC_BEFORE([$0],[AC_PATH_TOOL])dnl +AC_BEFORE([$0],[AC_PATH_PROG])dnl +AC_BEFORE([$0],[AC_PATH_PROGS])dnl +dnl +AC_BEFORE([$0],[AC_PROG_SED])dnl +AC_BEFORE([$0],[AC_PROG_GREP])dnl +AC_BEFORE([$0],[AC_PROG_LN_S])dnl +AC_BEFORE([$0],[AC_PROG_MKDIR_P])dnl +AC_BEFORE([$0],[AC_PROG_INSTALL])dnl +AC_BEFORE([$0],[AC_PROG_MAKE_SET])dnl +AC_BEFORE([$0],[AC_PROG_LIBTOOL])dnl +dnl +AC_BEFORE([$0],[LT_INIT])dnl +AC_BEFORE([$0],[AM_INIT_AUTOMAKE])dnl +AC_BEFORE([$0],[AC_LIBTOOL_WIN32_DLL])dnl +dnl +AC_REQUIRE([_XC_CFG_PRE_PREAMBLE])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_CMD_ECHO])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_CMD_TEST])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_VAR_PATH])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_CMD_EXPR])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_UTIL_SED])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_UTIL_GREP])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_UTIL_TR])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_UTIL_WC])dnl +AC_REQUIRE([_XC_CFG_PRE_BASIC_CHK_UTIL_CAT])dnl +AC_REQUIRE([_XC_CFG_PRE_CHECK_PATH_SEPARATOR])dnl +AC_REQUIRE([_XC_CFG_PRE_POSTLUDE])dnl +dnl +m4_pattern_forbid([^_*XC])dnl +m4_define([$0],[])dnl +]) + + +dnl Override autoconf and libtool PATH_SEPARATOR check +dnl ------------------------------------------------- +dnl Macros overriding. +dnl +dnl This is done to ensure that the same check is +dnl used across different autoconf versions and to +dnl allow expansion of XC_CONFIGURE_PREAMBLE macro +dnl early enough in the generated configure script. + +dnl +dnl Override when using autoconf 2.53 and newer. +dnl + +m4_ifdef([_AS_PATH_SEPARATOR_PREPARE], +[dnl +m4_undefine([_AS_PATH_SEPARATOR_PREPARE])dnl +m4_defun([_AS_PATH_SEPARATOR_PREPARE], +[dnl +AC_REQUIRE([XC_CONFIGURE_PREAMBLE])dnl +m4_define([$0],[])dnl +])dnl +]) + +dnl +dnl Override when using autoconf 2.50 to 2.52 +dnl + +m4_ifdef([_AC_INIT_PREPARE_FS_SEPARATORS], +[dnl +m4_undefine([_AC_INIT_PREPARE_FS_SEPARATORS])dnl +m4_defun([_AC_INIT_PREPARE_FS_SEPARATORS], +[dnl +AC_REQUIRE([XC_CONFIGURE_PREAMBLE])dnl +ac_path_separator=$PATH_SEPARATOR +m4_define([$0],[])dnl +])dnl +]) + +dnl +dnl Override when using libtool 1.4.2 +dnl + +m4_ifdef([_LT_AC_LIBTOOL_SYS_PATH_SEPARATOR], +[dnl +m4_undefine([_LT_AC_LIBTOOL_SYS_PATH_SEPARATOR])dnl +m4_defun([_LT_AC_LIBTOOL_SYS_PATH_SEPARATOR], +[dnl +AC_REQUIRE([XC_CONFIGURE_PREAMBLE])dnl +lt_cv_sys_path_separator=$PATH_SEPARATOR +m4_define([$0],[])dnl +])dnl +]) + + +dnl XC_CHECK_PATH_SEPARATOR +dnl ------------------------------------------------- +dnl Public macro. +dnl +dnl Usage of this macro ensures that generated configure +dnl script uses the same PATH_SEPARATOR check irrespective +dnl of autoconf or libtool version being used to generate +dnl configure script. +dnl +dnl Emits shell code that computes the path separator +dnl and stores the result in 'PATH_SEPARATOR', unless +dnl the user has already set it with a non-empty value. +dnl +dnl This path separator is the symbol used to separate +dnl or differentiate paths inside the 'PATH' environment +dnl variable. +dnl +dnl Non-empty user provided 'PATH_SEPARATOR' always +dnl overrides the auto-detected one. +dnl +dnl Strictly speaking the check is done in two steps. The +dnl first, which does the actual check, takes place in +dnl XC_CONFIGURE_PREAMBLE macro and happens very early in +dnl generated configure script. The second one shows and +dnl logs the result of the check into config.log at a later +dnl configure stage. Placement of this second stage in +dnl generated configure script will be done where first +dnl direct or indirect usage of this macro happens. + +AC_DEFUN([XC_CHECK_PATH_SEPARATOR], +[dnl +AC_PREREQ([2.50])dnl +dnl +AC_BEFORE([$0],[AC_CHECK_TOOL])dnl +AC_BEFORE([$0],[AC_CHECK_PROG])dnl +AC_BEFORE([$0],[AC_CHECK_TOOLS])dnl +AC_BEFORE([$0],[AC_CHECK_PROGS])dnl +dnl +AC_BEFORE([$0],[AC_PATH_TOOL])dnl +AC_BEFORE([$0],[AC_PATH_PROG])dnl +AC_BEFORE([$0],[AC_PATH_PROGS])dnl +dnl +AC_BEFORE([$0],[AC_PROG_SED])dnl +AC_BEFORE([$0],[AC_PROG_GREP])dnl +AC_BEFORE([$0],[AC_PROG_LN_S])dnl +AC_BEFORE([$0],[AC_PROG_MKDIR_P])dnl +AC_BEFORE([$0],[AC_PROG_INSTALL])dnl +AC_BEFORE([$0],[AC_PROG_MAKE_SET])dnl +AC_BEFORE([$0],[AC_PROG_LIBTOOL])dnl +dnl +AC_BEFORE([$0],[LT_INIT])dnl +AC_BEFORE([$0],[AM_INIT_AUTOMAKE])dnl +AC_BEFORE([$0],[AC_LIBTOOL_WIN32_DLL])dnl +dnl +AC_REQUIRE([XC_CONFIGURE_PREAMBLE])dnl +dnl +# +# Check that 'XC_CONFIGURE_PREAMBLE' has already run. +# + +if test -z "$xc_configure_preamble_result"; then + AC_MSG_ERROR([xc_configure_preamble_result not set (internal problem)]) +fi + +# +# Check that 'PATH_SEPARATOR' has already been set. +# + +if test -z "$xc_PATH_SEPARATOR"; then + AC_MSG_ERROR([xc_PATH_SEPARATOR not set (internal problem)]) +fi +if test -z "$PATH_SEPARATOR"; then + AC_MSG_ERROR([PATH_SEPARATOR not set (internal or config.site problem)]) +fi +AC_MSG_CHECKING([for path separator]) +AC_MSG_RESULT([$PATH_SEPARATOR]) +if test "x$PATH_SEPARATOR" != "x$xc_PATH_SEPARATOR"; then + AC_MSG_CHECKING([for initial path separator]) + AC_MSG_RESULT([$xc_PATH_SEPARATOR]) + AC_MSG_ERROR([path separator mismatch (internal or config.site problem)]) +fi +dnl +m4_pattern_forbid([^_*XC])dnl +m4_define([$0],[])dnl +]) diff --git a/third_party/curl/m4/zz50-xc-ovr.m4 b/third_party/curl/m4/zz50-xc-ovr.m4 new file mode 100644 index 0000000..18c1f0a --- /dev/null +++ b/third_party/curl/m4/zz50-xc-ovr.m4 @@ -0,0 +1,61 @@ +#--------------------------------------------------------------------------- +# +# zz50-xc-ovr.m4 +# +# Copyright (C), Daniel Stenberg +# +# Permission to use, copy, modify, and distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# +# SPDX-License-Identifier: ISC +# +#--------------------------------------------------------------------------- + +# serial 1 + + +dnl The funny name of this file is intentional in order to make it +dnl sort alphabetically after any libtool, autoconf or automake +dnl provided .m4 macro file that might get copied into this same +dnl subdirectory. This allows that macro (re)definitions from this +dnl file may override those provided in other files. + + +dnl Override some language related macros +dnl ------------------------------------------------- +dnl This is done to prevent Libtool 1.5.X from doing +dnl unnecessary C++, Fortran and Java tests when only +dnl using C language and reduce resulting configure +dnl script by nearly 300 Kb. + +m4_ifdef([AC_LIBTOOL_LANG_CXX_CONFIG], + [m4_undefine([AC_LIBTOOL_LANG_CXX_CONFIG])]) +m4_define([AC_LIBTOOL_LANG_CXX_CONFIG],[:]) + +m4_ifdef([AC_LIBTOOL_LANG_F77_CONFIG], + [m4_undefine([AC_LIBTOOL_LANG_F77_CONFIG])]) +m4_define([AC_LIBTOOL_LANG_F77_CONFIG],[:]) + +m4_ifdef([AC_LIBTOOL_LANG_GCJ_CONFIG], + [m4_undefine([AC_LIBTOOL_LANG_GCJ_CONFIG])]) +m4_define([AC_LIBTOOL_LANG_GCJ_CONFIG],[:]) + + +dnl XC_OVR_ZZ50 +dnl ------------------------------------------------- +dnl Placing a call to this macro in configure.ac will +dnl make macros in this file visible to other macros +dnl used for same configure script, overriding those +dnl provided elsewhere. + +AC_DEFUN([XC_OVR_ZZ50], + [AC_BEFORE([$0],[AC_PROG_LIBTOOL])]) diff --git a/third_party/curl/m4/zz60-xc-ovr.m4 b/third_party/curl/m4/zz60-xc-ovr.m4 new file mode 100644 index 0000000..5316686 --- /dev/null +++ b/third_party/curl/m4/zz60-xc-ovr.m4 @@ -0,0 +1,65 @@ +#--------------------------------------------------------------------------- +# +# zz60-xc-ovr.m4 +# +# Copyright (C), Daniel Stenberg +# +# Permission to use, copy, modify, and distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# +# SPDX-License-Identifier: ISC +# +#--------------------------------------------------------------------------- + +# serial 1 + + +dnl The funny name of this file is intentional in order to make it +dnl sort alphabetically after any libtool, autoconf or automake +dnl provided .m4 macro file that might get copied into this same +dnl subdirectory. This allows that macro (re)definitions from this +dnl file may override those provided in other files. + + +dnl Override an autoconf provided macro +dnl ------------------------------------------------- +dnl This macro overrides the one provided by autoconf +dnl 2.58 or newer, and provides macro definition for +dnl autoconf 2.57 or older which lack it. This allows +dnl using libtool 2.2 or newer, which requires that +dnl this macro is used in configure.ac, with autoconf +dnl 2.57 or older. + +m4_ifdef([AC_CONFIG_MACRO_DIR], +[dnl +m4_undefine([AC_CONFIG_MACRO_DIR])dnl +]) +m4_define([AC_CONFIG_MACRO_DIR],[]) + + +dnl XC_OVR_ZZ60 +dnl ------------------------------------------------- +dnl Placing a call to this macro in configure.ac will +dnl make macros in this file visible to other macros +dnl used for same configure script, overriding those +dnl provided elsewhere. + +AC_DEFUN([XC_OVR_ZZ60], +[dnl +AC_BEFORE([$0],[LT_INIT])dnl +AC_BEFORE([$0],[AM_INIT_AUTOMAKE])dnl +AC_BEFORE([$0],[AC_LIBTOOL_WIN32_DLL])dnl +AC_BEFORE([$0],[AC_PROG_LIBTOOL])dnl +dnl +AC_BEFORE([$0],[AC_CONFIG_MACRO_DIR])dnl +AC_BEFORE([$0],[AC_CONFIG_MACRO_DIRS])dnl +]) diff --git a/third_party/curl/maketgz b/third_party/curl/maketgz new file mode 100755 index 0000000..0492371 --- /dev/null +++ b/third_party/curl/maketgz @@ -0,0 +1,235 @@ +#!/bin/sh +# Script to build release-archives with. Note that this requires a checkout +# from git and you should first run ./buildconf and build curl once. +# +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +set -eu + +export LC_ALL=C +export TZ=UTC + +version="${1:-}" + +if [ -z "$version" ]; then + echo "Specify a version number!" + exit +fi + +if [ "only" = "${2:-}" ]; then + echo "Setup version number only!" + only=1 +else + only= +fi + +libversion="$version" + +# we make curl the same version as libcurl +curlversion="$libversion" + +major=$(echo "$libversion" | cut -d. -f1 | sed -e "s/[^0-9]//g") +minor=$(echo "$libversion" | cut -d. -f2 | sed -e "s/[^0-9]//g") +patch=$(echo "$libversion" | cut -d. -f3 | cut -d- -f1 | sed -e "s/[^0-9]//g") + +if test -z "$patch"; then + echo "invalid version number? needs to be z.y.z" + exit +fi + +# +# As a precaution, remove all *.dist files that may be lying around, to reduce +# the risk of old leftovers getting shipped. The root 'Makefile.dist' is the +# exception. +echo "removing all old *.dist files" +find . -name "*.dist" -a ! -name Makefile.dist -exec rm {} \; + +numeric="$(printf "%02x%02x%02x\n" "$major" "$minor" "$patch")" + +HEADER=include/curl/curlver.h +CHEADER=src/tool_version.h + +if test -z "$only"; then + ext=".dist" + # when not setting up version numbers locally + for a in $HEADER $CHEADER; do + cp "$a" "$a$ext" + done + HEADER="$HEADER$ext" + CHEADER="$CHEADER$ext" +fi + +# requires a date command that knows + for format and -d for date input +timestamp=${SOURCE_DATE_EPOCH:-$(date +"%s")} +datestamp=$(date -d "@$timestamp" +"%F") +filestamp=$(date -d "@$timestamp" +"%Y%m%d%H%M.%S") + +# Replace version number in header file: +sed -i.bak \ + -e "s/^#define LIBCURL_VERSION .*/#define LIBCURL_VERSION \"$libversion\"/g" \ + -e "s/^#define LIBCURL_VERSION_NUM .*/#define LIBCURL_VERSION_NUM 0x$numeric/g" \ + -e "s/^#define LIBCURL_VERSION_MAJOR .*/#define LIBCURL_VERSION_MAJOR $major/g" \ + -e "s/^#define LIBCURL_VERSION_MINOR .*/#define LIBCURL_VERSION_MINOR $minor/g" \ + -e "s/^#define LIBCURL_VERSION_PATCH .*/#define LIBCURL_VERSION_PATCH $patch/g" \ + -e "s/^#define LIBCURL_TIMESTAMP .*/#define LIBCURL_TIMESTAMP \"$datestamp\"/g" \ + "$HEADER" +rm -f "$HEADER.bak" + +# Replace version number in header file: +sed -i.bak "s/#define CURL_VERSION .*/#define CURL_VERSION \"$curlversion\"/g" "$CHEADER" +rm -f "$CHEADER.bak" + +if test -n "$only"; then + # done! + exit +fi + +echo "curl version $curlversion" +echo "libcurl version $libversion" +echo "libcurl numerical $numeric" +echo "datestamp $datestamp" + +findprog() { + file="$1" + for part in $(echo "$PATH" | tr ':' ' '); do + path="$part/$file" + if [ -x "$path" ]; then + # there it is! + return 1 + fi + done + + # no such executable + return 0 +} + +############################################################################ +# +# Enforce a rerun of configure (updates the VERSION) +# + +echo "Re-running config.status" +./config.status --recheck >/dev/null + +############################################################################ +# +# automake is needed to run to make a non-GNU Makefile.in if Makefile.am has +# been modified. +# + +if { findprog automake >/dev/null 2>/dev/null; } then + echo "- Could not find or run automake, I hope you know what you are doing!" +else + echo "Runs automake --include-deps" + automake --include-deps Makefile >/dev/null +fi + +echo "produce CHANGES" +git log --pretty=fuller --no-color --date=short --decorate=full -1000 | ./scripts/log2changes.pl > CHANGES.dist + +echo "produce RELEASE-TOOLS.md" +./scripts/release-tools.sh "$timestamp" "$version" > docs/RELEASE-TOOLS.md.dist + +############################################################################ +# +# Now run make dist to generate a tar.gz archive +# + +echo "make dist" +targz="curl-$version.tar.gz" +make -sj dist "VERSION=$version" +res=$? + +if test "$res" != 0; then + echo "make dist failed" + exit 2 +fi + +retar() { + tempdir=$1 + rm -rf "$tempdir" + mkdir "$tempdir" + cd "$tempdir" + gzip -dc "../$targz" | tar -xf - + find curl-* -depth -exec touch -c -t "$filestamp" '{}' + + tar --create --format=ustar --owner=0 --group=0 --numeric-owner --sort=name curl-* | gzip --best --no-name > out.tar.gz + mv out.tar.gz ../ + cd .. + rm -rf "$tempdir" +} + +retar ".tarbuild" +echo "replace $targz with out.tar.gz" +mv out.tar.gz "$targz" + +############################################################################ +# +# Now make a bz2 archive from the tar.gz original +# + +bzip2="curl-$version.tar.bz2" +echo "Generating $bzip2" +gzip -dc "$targz" | bzip2 --best > "$bzip2" + +############################################################################ +# +# Now make an xz archive from the tar.gz original +# + +xz="curl-$version.tar.xz" +echo "Generating $xz" +gzip -dc "$targz" | xz -6e - > "$xz" + +############################################################################ +# +# Now make a zip archive from the tar.gz original +# +makezip() { + rm -rf "$tempdir" + mkdir "$tempdir" + cd "$tempdir" + gzip -dc "../$targz" | tar -xf - + find . | sort | zip -9 -X "$zip" -@ >/dev/null + mv "$zip" ../ + cd .. + rm -rf "$tempdir" +} + +zip="curl-$version.zip" +echo "Generating $zip" +tempdir=".builddir" +makezip + +# Set deterministic timestamp +touch -c -t "$filestamp" "$targz" "$bzip2" "$xz" "$zip" + +echo "------------------" +echo "maketgz report:" +echo "" +ls -l "$targz" "$bzip2" "$xz" "$zip" +sha256sum "$targz" "$bzip2" "$xz" "$zip" + +echo "Run this:" +echo "gpg -b -a '$targz' && gpg -b -a '$bzip2' && gpg -b -a '$xz' && gpg -b -a '$zip'" diff --git a/third_party/curl/missing b/third_party/curl/missing new file mode 100755 index 0000000..1fe1611 --- /dev/null +++ b/third_party/curl/missing @@ -0,0 +1,215 @@ +#! /bin/sh +# Common wrapper for a few potentially missing GNU programs. + +scriptversion=2018-03-07.03; # UTC + +# Copyright (C) 1996-2021 Free Software Foundation, Inc. +# Originally written by Fran,cois Pinard , 1996. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +if test $# -eq 0; then + echo 1>&2 "Try '$0 --help' for more information" + exit 1 +fi + +case $1 in + + --is-lightweight) + # Used by our autoconf macros to check whether the available missing + # script is modern enough. + exit 0 + ;; + + --run) + # Back-compat with the calling convention used by older automake. + shift + ;; + + -h|--h|--he|--hel|--help) + echo "\ +$0 [OPTION]... PROGRAM [ARGUMENT]... + +Run 'PROGRAM [ARGUMENT]...', returning a proper advice when this fails due +to PROGRAM being missing or too old. + +Options: + -h, --help display this help and exit + -v, --version output version information and exit + +Supported PROGRAM values: + aclocal autoconf autoheader autom4te automake makeinfo + bison yacc flex lex help2man + +Version suffixes to PROGRAM as well as the prefixes 'gnu-', 'gnu', and +'g' are ignored when checking the name. + +Send bug reports to ." + exit $? + ;; + + -v|--v|--ve|--ver|--vers|--versi|--versio|--version) + echo "missing $scriptversion (GNU Automake)" + exit $? + ;; + + -*) + echo 1>&2 "$0: unknown '$1' option" + echo 1>&2 "Try '$0 --help' for more information" + exit 1 + ;; + +esac + +# Run the given program, remember its exit status. +"$@"; st=$? + +# If it succeeded, we are done. +test $st -eq 0 && exit 0 + +# Also exit now if we it failed (or wasn't found), and '--version' was +# passed; such an option is passed most likely to detect whether the +# program is present and works. +case $2 in --version|--help) exit $st;; esac + +# Exit code 63 means version mismatch. This often happens when the user +# tries to use an ancient version of a tool on a file that requires a +# minimum version. +if test $st -eq 63; then + msg="probably too old" +elif test $st -eq 127; then + # Program was missing. + msg="missing on your system" +else + # Program was found and executed, but failed. Give up. + exit $st +fi + +perl_URL=https://www.perl.org/ +flex_URL=https://github.com/westes/flex +gnu_software_URL=https://www.gnu.org/software + +program_details () +{ + case $1 in + aclocal|automake) + echo "The '$1' program is part of the GNU Automake package:" + echo "<$gnu_software_URL/automake>" + echo "It also requires GNU Autoconf, GNU m4 and Perl in order to run:" + echo "<$gnu_software_URL/autoconf>" + echo "<$gnu_software_URL/m4/>" + echo "<$perl_URL>" + ;; + autoconf|autom4te|autoheader) + echo "The '$1' program is part of the GNU Autoconf package:" + echo "<$gnu_software_URL/autoconf/>" + echo "It also requires GNU m4 and Perl in order to run:" + echo "<$gnu_software_URL/m4/>" + echo "<$perl_URL>" + ;; + esac +} + +give_advice () +{ + # Normalize program name to check for. + normalized_program=`echo "$1" | sed ' + s/^gnu-//; t + s/^gnu//; t + s/^g//; t'` + + printf '%s\n' "'$1' is $msg." + + configure_deps="'configure.ac' or m4 files included by 'configure.ac'" + case $normalized_program in + autoconf*) + echo "You should only need it if you modified 'configure.ac'," + echo "or m4 files included by it." + program_details 'autoconf' + ;; + autoheader*) + echo "You should only need it if you modified 'acconfig.h' or" + echo "$configure_deps." + program_details 'autoheader' + ;; + automake*) + echo "You should only need it if you modified 'Makefile.am' or" + echo "$configure_deps." + program_details 'automake' + ;; + aclocal*) + echo "You should only need it if you modified 'acinclude.m4' or" + echo "$configure_deps." + program_details 'aclocal' + ;; + autom4te*) + echo "You might have modified some maintainer files that require" + echo "the 'autom4te' program to be rebuilt." + program_details 'autom4te' + ;; + bison*|yacc*) + echo "You should only need it if you modified a '.y' file." + echo "You may want to install the GNU Bison package:" + echo "<$gnu_software_URL/bison/>" + ;; + lex*|flex*) + echo "You should only need it if you modified a '.l' file." + echo "You may want to install the Fast Lexical Analyzer package:" + echo "<$flex_URL>" + ;; + help2man*) + echo "You should only need it if you modified a dependency" \ + "of a man page." + echo "You may want to install the GNU Help2man package:" + echo "<$gnu_software_URL/help2man/>" + ;; + makeinfo*) + echo "You should only need it if you modified a '.texi' file, or" + echo "any other file indirectly affecting the aspect of the manual." + echo "You might want to install the Texinfo package:" + echo "<$gnu_software_URL/texinfo/>" + echo "The spurious makeinfo call might also be the consequence of" + echo "using a buggy 'make' (AIX, DU, IRIX), in which case you might" + echo "want to install GNU make:" + echo "<$gnu_software_URL/make/>" + ;; + *) + echo "You might have modified some files without having the proper" + echo "tools for further handling them. Check the 'README' file, it" + echo "often tells you about the needed prerequisites for installing" + echo "this package. You may also peek at any GNU archive site, in" + echo "case some other package contains this missing '$1' program." + ;; + esac +} + +give_advice "$1" | sed -e '1s/^/WARNING: /' \ + -e '2,$s/^/ /' >&2 + +# Propagate the correct exit status (expected to be 127 for a program +# not found, 63 for a program that failed due to version mismatch). +exit $st + +# Local variables: +# eval: (add-hook 'before-save-hook 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-time-zone: "UTC0" +# time-stamp-end: "; # UTC" +# End: diff --git a/third_party/curl/packages/Makefile.am b/third_party/curl/packages/Makefile.am new file mode 100644 index 0000000..b7bf1e5 --- /dev/null +++ b/third_party/curl/packages/Makefile.am @@ -0,0 +1,51 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +SUBDIRS = vms + +EXTRA_DIST = README.md \ + OS400/README.OS400 \ + OS400/rpg-examples \ + OS400/ccsidcurl.c \ + OS400/ccsidcurl.h \ + OS400/curlcl.c \ + OS400/curlmain.c \ + OS400/curl.inc.in \ + OS400/initscript.sh \ + OS400/config400.default \ + OS400/make-include.sh \ + OS400/make-lib.sh \ + OS400/make-src.sh \ + OS400/make-tests.sh \ + OS400/makefile.sh \ + OS400/os400sys.c \ + OS400/os400sys.h \ + OS400/curl.cmd + +CHECKSRC = $(CS_$(V)) +CS_0 = @echo " RUN " $@; +CS_1 = +CS_ = $(CS_0) + +checksrc: + $(CHECKSRC)(@PERL@ $(top_srcdir)/scripts/checksrc.pl -D$(srcdir) $(srcdir)/OS400/*.[ch]) diff --git a/third_party/curl/packages/Makefile.in b/third_party/curl/packages/Makefile.in new file mode 100644 index 0000000..842469e --- /dev/null +++ b/third_party/curl/packages/Makefile.in @@ -0,0 +1,796 @@ +# Makefile.in generated by automake 1.16.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994-2021 Free Software Foundation, Inc. + +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ +VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = packages +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4/curl-amissl.m4 \ + $(top_srcdir)/m4/curl-bearssl.m4 \ + $(top_srcdir)/m4/curl-compilers.m4 \ + $(top_srcdir)/m4/curl-confopts.m4 \ + $(top_srcdir)/m4/curl-functions.m4 \ + $(top_srcdir)/m4/curl-gnutls.m4 \ + $(top_srcdir)/m4/curl-mbedtls.m4 \ + $(top_srcdir)/m4/curl-openssl.m4 \ + $(top_srcdir)/m4/curl-override.m4 \ + $(top_srcdir)/m4/curl-reentrant.m4 \ + $(top_srcdir)/m4/curl-rustls.m4 \ + $(top_srcdir)/m4/curl-schannel.m4 \ + $(top_srcdir)/m4/curl-sectransp.m4 \ + $(top_srcdir)/m4/curl-sysconfig.m4 \ + $(top_srcdir)/m4/curl-wolfssl.m4 $(top_srcdir)/m4/libtool.m4 \ + $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ + $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ + $(top_srcdir)/m4/xc-am-iface.m4 \ + $(top_srcdir)/m4/xc-cc-check.m4 \ + $(top_srcdir)/m4/xc-lt-iface.m4 \ + $(top_srcdir)/m4/xc-translit.m4 \ + $(top_srcdir)/m4/xc-val-flgs.m4 \ + $(top_srcdir)/m4/zz40-xc-ovr.m4 \ + $(top_srcdir)/m4/zz50-xc-ovr.m4 \ + $(top_srcdir)/m4/zz60-xc-ovr.m4 $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/lib/curl_config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ + ctags-recursive dvi-recursive html-recursive info-recursive \ + install-data-recursive install-dvi-recursive \ + install-exec-recursive install-html-recursive \ + install-info-recursive install-pdf-recursive \ + install-ps-recursive install-recursive installcheck-recursive \ + installdirs-recursive pdf-recursive ps-recursive \ + tags-recursive uninstall-recursive +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +am__recursive_targets = \ + $(RECURSIVE_TARGETS) \ + $(RECURSIVE_CLEAN_TARGETS) \ + $(am__extra_recursive_targets) +AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ + distdir distdir-am +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` +DIST_SUBDIRS = $(SUBDIRS) +am__DIST_COMMON = $(srcdir)/Makefile.in README.md +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +APACHECTL = @APACHECTL@ +APXS = @APXS@ +AR = @AR@ +AR_FLAGS = @AR_FLAGS@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +BLANK_AT_MAKETIME = @BLANK_AT_MAKETIME@ +CADDY = @CADDY@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CFLAG_CURL_SYMBOL_HIDING = @CFLAG_CURL_SYMBOL_HIDING@ +CONFIGURE_OPTIONS = @CONFIGURE_OPTIONS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CPPFLAG_CURL_STATICLIB = @CPPFLAG_CURL_STATICLIB@ +CSCOPE = @CSCOPE@ +CTAGS = @CTAGS@ +CURLVERSION = @CURLVERSION@ +CURL_CA_BUNDLE = @CURL_CA_BUNDLE@ +CURL_CFLAG_EXTRAS = @CURL_CFLAG_EXTRAS@ +CURL_DISABLE_DICT = @CURL_DISABLE_DICT@ +CURL_DISABLE_FILE = @CURL_DISABLE_FILE@ +CURL_DISABLE_FTP = @CURL_DISABLE_FTP@ +CURL_DISABLE_GOPHER = @CURL_DISABLE_GOPHER@ +CURL_DISABLE_HTTP = @CURL_DISABLE_HTTP@ +CURL_DISABLE_IMAP = @CURL_DISABLE_IMAP@ +CURL_DISABLE_LDAP = @CURL_DISABLE_LDAP@ +CURL_DISABLE_LDAPS = @CURL_DISABLE_LDAPS@ +CURL_DISABLE_MQTT = @CURL_DISABLE_MQTT@ +CURL_DISABLE_POP3 = @CURL_DISABLE_POP3@ +CURL_DISABLE_PROXY = @CURL_DISABLE_PROXY@ +CURL_DISABLE_RTSP = @CURL_DISABLE_RTSP@ +CURL_DISABLE_SMB = @CURL_DISABLE_SMB@ +CURL_DISABLE_SMTP = @CURL_DISABLE_SMTP@ +CURL_DISABLE_TELNET = @CURL_DISABLE_TELNET@ +CURL_DISABLE_TFTP = @CURL_DISABLE_TFTP@ +CURL_LT_SHLIB_VERSIONED_FLAVOUR = @CURL_LT_SHLIB_VERSIONED_FLAVOUR@ +CURL_NETWORK_AND_TIME_LIBS = @CURL_NETWORK_AND_TIME_LIBS@ +CURL_NETWORK_LIBS = @CURL_NETWORK_LIBS@ +CURL_WITH_MULTI_SSL = @CURL_WITH_MULTI_SSL@ +CYGPATH_W = @CYGPATH_W@ +DEFAULT_SSL_BACKEND = @DEFAULT_SSL_BACKEND@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +ENABLE_SHARED = @ENABLE_SHARED@ +ENABLE_STATIC = @ENABLE_STATIC@ +ETAGS = @ETAGS@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +FILECMD = @FILECMD@ +FISH_FUNCTIONS_DIR = @FISH_FUNCTIONS_DIR@ +GCOV = @GCOV@ +GREP = @GREP@ +HAVE_BROTLI = @HAVE_BROTLI@ +HAVE_GNUTLS_SRP = @HAVE_GNUTLS_SRP@ +HAVE_LDAP_SSL = @HAVE_LDAP_SSL@ +HAVE_LIBZ = @HAVE_LIBZ@ +HAVE_OPENSSL_QUIC = @HAVE_OPENSSL_QUIC@ +HAVE_OPENSSL_SRP = @HAVE_OPENSSL_SRP@ +HAVE_PROTO_BSDSOCKET_H = @HAVE_PROTO_BSDSOCKET_H@ +HAVE_ZSTD = @HAVE_ZSTD@ +HTTPD = @HTTPD@ +HTTPD_NGHTTPX = @HTTPD_NGHTTPX@ +IDN_ENABLED = @IDN_ENABLED@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +IPV6_ENABLED = @IPV6_ENABLED@ +LCOV = @LCOV@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBCURL_LIBS = @LIBCURL_LIBS@ +LIBCURL_NO_SHARED = @LIBCURL_NO_SHARED@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ +MAINT = @MAINT@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PERL = @PERL@ +PKGADD_NAME = @PKGADD_NAME@ +PKGADD_PKG = @PKGADD_PKG@ +PKGADD_VENDOR = @PKGADD_VENDOR@ +PKGCONFIG = @PKGCONFIG@ +RANDOM_FILE = @RANDOM_FILE@ +RANLIB = @RANLIB@ +RC = @RC@ +REQUIRE_LIB_DEPS = @REQUIRE_LIB_DEPS@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SSL_BACKENDS = @SSL_BACKENDS@ +SSL_ENABLED = @SSL_ENABLED@ +SSL_LIBS = @SSL_LIBS@ +STRIP = @STRIP@ +SUPPORT_FEATURES = @SUPPORT_FEATURES@ +SUPPORT_PROTOCOLS = @SUPPORT_PROTOCOLS@ +TEST_NGHTTPX = @TEST_NGHTTPX@ +USE_ARES = @USE_ARES@ +USE_BEARSSL = @USE_BEARSSL@ +USE_GNUTLS = @USE_GNUTLS@ +USE_HYPER = @USE_HYPER@ +USE_LIBPSL = @USE_LIBPSL@ +USE_LIBRTMP = @USE_LIBRTMP@ +USE_LIBSSH = @USE_LIBSSH@ +USE_LIBSSH2 = @USE_LIBSSH2@ +USE_MBEDTLS = @USE_MBEDTLS@ +USE_MSH3 = @USE_MSH3@ +USE_NGHTTP2 = @USE_NGHTTP2@ +USE_NGHTTP3 = @USE_NGHTTP3@ +USE_NGTCP2 = @USE_NGTCP2@ +USE_NGTCP2_CRYPTO_BORINGSSL = @USE_NGTCP2_CRYPTO_BORINGSSL@ +USE_NGTCP2_CRYPTO_GNUTLS = @USE_NGTCP2_CRYPTO_GNUTLS@ +USE_NGTCP2_CRYPTO_QUICTLS = @USE_NGTCP2_CRYPTO_QUICTLS@ +USE_NGTCP2_CRYPTO_WOLFSSL = @USE_NGTCP2_CRYPTO_WOLFSSL@ +USE_NGTCP2_H3 = @USE_NGTCP2_H3@ +USE_OPENLDAP = @USE_OPENLDAP@ +USE_OPENSSL_H3 = @USE_OPENSSL_H3@ +USE_OPENSSL_QUIC = @USE_OPENSSL_QUIC@ +USE_QUICHE = @USE_QUICHE@ +USE_RUSTLS = @USE_RUSTLS@ +USE_SCHANNEL = @USE_SCHANNEL@ +USE_SECTRANSP = @USE_SECTRANSP@ +USE_UNIX_SOCKETS = @USE_UNIX_SOCKETS@ +USE_WIN32_CRYPTO = @USE_WIN32_CRYPTO@ +USE_WIN32_LARGE_FILES = @USE_WIN32_LARGE_FILES@ +USE_WIN32_SMALL_FILES = @USE_WIN32_SMALL_FILES@ +USE_WINDOWS_SSPI = @USE_WINDOWS_SSPI@ +USE_WOLFSSH = @USE_WOLFSSH@ +USE_WOLFSSL = @USE_WOLFSSL@ +VERSION = @VERSION@ +VERSIONNUM = @VERSIONNUM@ +VSFTPD = @VSFTPD@ +ZLIB_LIBS = @ZLIB_LIBS@ +ZSH_FUNCTIONS_DIR = @ZSH_FUNCTIONS_DIR@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +libext = @libext@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +runstatedir = @runstatedir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ + +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +SUBDIRS = vms +EXTRA_DIST = README.md \ + OS400/README.OS400 \ + OS400/rpg-examples \ + OS400/ccsidcurl.c \ + OS400/ccsidcurl.h \ + OS400/curlcl.c \ + OS400/curlmain.c \ + OS400/curl.inc.in \ + OS400/initscript.sh \ + OS400/config400.default \ + OS400/make-include.sh \ + OS400/make-lib.sh \ + OS400/make-src.sh \ + OS400/make-tests.sh \ + OS400/makefile.sh \ + OS400/os400sys.c \ + OS400/os400sys.h \ + OS400/curl.cmd + +CHECKSRC = $(CS_$(V)) +CS_0 = @echo " RUN " $@; +CS_1 = +CS_ = $(CS_0) +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu packages/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --gnu packages/Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +# This directory's subdirectories are mostly independent; you can cd +# into them and run 'make' without going through this Makefile. +# To change the values of 'make' variables: instead of editing Makefiles, +# (1) if the variable is set in 'config.status', edit 'config.status' +# (which will cause the Makefiles to be regenerated when you run 'make'); +# (2) otherwise, pass the desired values on the 'make' command line. +$(am__recursive_targets): + @fail=; \ + if $(am__make_keepgoing); then \ + failcom='fail=yes'; \ + else \ + failcom='exit 1'; \ + fi; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-recursive +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: ctags-recursive + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-recursive + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags +distdir: $(BUILT_SOURCES) + $(MAKE) $(AM_MAKEFLAGS) distdir-am + +distdir-am: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + $(am__make_dryrun) \ + || test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ + distdir) \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-recursive +all-am: Makefile +installdirs: installdirs-recursive +installdirs-am: +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: + +install-dvi: install-dvi-recursive + +install-dvi-am: + +install-exec-am: + +install-html: install-html-recursive + +install-html-am: + +install-info: install-info-recursive + +install-info-am: + +install-man: + +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: + +.MAKE: $(am__recursive_targets) install-am install-strip + +.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ + check-am clean clean-generic clean-libtool cscopelist-am ctags \ + ctags-am distclean distclean-generic distclean-libtool \ + distclean-tags distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + installdirs-am maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \ + ps ps-am tags tags-am uninstall uninstall-am + +.PRECIOUS: Makefile + + +checksrc: + $(CHECKSRC)(@PERL@ $(top_srcdir)/scripts/checksrc.pl -D$(srcdir) $(srcdir)/OS400/*.[ch]) + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/third_party/curl/packages/OS400/README.OS400 b/third_party/curl/packages/OS400/README.OS400 new file mode 100644 index 0000000..38b2c7f --- /dev/null +++ b/third_party/curl/packages/OS400/README.OS400 @@ -0,0 +1,391 @@ + +Implementation notes: + + This is a true OS/400 ILE implementation, not a PASE implementation (for +PASE, use AIX implementation). + + The biggest problem with OS/400 is EBCDIC. Libcurl implements an internal +conversion mechanism, but it has been designed for computers that have a +single native character set. OS/400 default native character set varies +depending on the country for which it has been localized. And more, a job +may dynamically alter its "native" character set. + Several characters that do not have fixed code in EBCDIC variants are +used in libcurl strings. As a consequence, using the existing conversion +mechanism would have lead in a localized binary library - not portable across +countries. + For this reason, and because libcurl was originally designed for ASCII based +operating systems, the current OS/400 implementation uses ASCII as internal +character set. This has been accomplished using the QADRT library and +include files, a C and system procedures ASCII wrapper library. See IBM QADRT +description for more information. + This then results in libcurl being an ASCII library: any function string +argument is taken/returned in ASCII and a C/C++ calling program built around +QADRT may use libcurl functions as on any other platform. + QADRT does not define ASCII wrappers for all C/system procedures: the +OS/400 configuration header file and an additional module (os400sys.c) define +some more of them, that are used by libcurl and that QADRT left out. + To support all the different variants of EBCDIC, non-standard wrapper +procedures have been added to libcurl on OS/400: they provide an additional +CCSID (numeric Coded Character Set ID specific to OS/400) parameter for each +string argument. Callback procedures arguments giving access to strings are +NOT converted, so text gathered this way is (probably !) ASCII. + + Another OS/400 problem comes from the fact that the last fixed argument of a +vararg procedure may not be of type char, unsigned char, short or unsigned +short. Enums that are internally implemented by the C compiler as one of these +types are also forbidden. Libcurl uses enums as vararg procedure tagfields... +Happily, there is a pragma forcing enums to type "int". The original libcurl +header files are thus altered during build process to use this pragma, in +order to force libcurl enums of being type int (the pragma disposition in use +before inclusion is restored before resuming the including unit compilation). + + Non-standard EBCDIC wrapper prototypes are defined in an additional header +file: ccsidcurl.h. These should be self-explanatory to an OS/400-aware +designer. CCSID 0 can be used to select the current job's CCSID. + Wrapper procedures with variable arguments are described below: + +_ curl_easy_setopt_ccsid() + Variable arguments are a string pointer and a CCSID (unsigned int) for +options: + CURLOPT_ABSTRACT_UNIX_SOCKET + CURLOPT_ACCEPT_ENCODING + CURLOPT_ALTSVC + CURLOPT_AWS_SIGV4 + CURLOPT_CAINFO + CURLOPT_CAPATH + CURLOPT_COOKIE + CURLOPT_COOKIEFILE + CURLOPT_COOKIEJAR + CURLOPT_COOKIELIST + CURLOPT_CRLFILE + CURLOPT_CUSTOMREQUEST + CURLOPT_DEFAULT_PROTOCOL + CURLOPT_DNS_INTERFACE + CURLOPT_DNS_LOCAL_IP4 + CURLOPT_DNS_LOCAL_IP6 + CURLOPT_DNS_SERVERS + CURLOPT_DOH_URL + CURLOPT_EGDSOCKET + CURLOPT_FTPPORT + CURLOPT_FTP_ACCOUNT + CURLOPT_FTP_ALTERNATIVE_TO_USER + CURLOPT_HAPROXY_CLIENT_IP + CURLOPT_HSTS + CURLOPT_INTERFACE + CURLOPT_ISSUERCERT + CURLOPT_KEYPASSWD + CURLOPT_KRBLEVEL + CURLOPT_LOGIN_OPTIONS + CURLOPT_MAIL_AUTH + CURLOPT_MAIL_FROM + CURLOPT_NETRC_FILE + CURLOPT_NOPROXY + CURLOPT_PASSWORD + CURLOPT_PINNEDPUBLICKEY + CURLOPT_PRE_PROXY + CURLOPT_PROTOCOLS_STR + CURLOPT_PROXY + CURLOPT_PROXYPASSWORD + CURLOPT_PROXYUSERNAME + CURLOPT_PROXYUSERPWD + CURLOPT_PROXY_CAINFO + CURLOPT_PROXY_CAPATH + CURLOPT_PROXY_CRLFILE + CURLOPT_PROXY_ISSUERCERT + CURLOPT_PROXY_KEYPASSWD + CURLOPT_PROXY_PINNEDPUBLICKEY + CURLOPT_PROXY_SERVICE_NAME + CURLOPT_PROXY_SSLCERT + CURLOPT_PROXY_SSLCERTTYPE + CURLOPT_PROXY_SSLKEY + CURLOPT_PROXY_SSLKEYTYPE + CURLOPT_PROXY_SSL_CIPHER_LIST + CURLOPT_PROXY_TLS13_CIPHERS + CURLOPT_PROXY_TLSAUTH_PASSWORD + CURLOPT_PROXY_TLSAUTH_TYPE + CURLOPT_PROXY_TLSAUTH_USERNAME + CURLOPT_RANDOM_FILE + CURLOPT_RANGE + CURLOPT_REDIR_PROTOCOLS_STR + CURLOPT_REFERER + CURLOPT_REQUEST_TARGET + CURLOPT_RTSP_SESSION_ID + CURLOPT_RTSP_STREAM_URI + CURLOPT_RTSP_TRANSPORT + CURLOPT_SASL_AUTHZID + CURLOPT_SERVICE_NAME + CURLOPT_SOCKS5_GSSAPI_SERVICE + CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 + CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 + CURLOPT_SSH_KNOWNHOSTS + CURLOPT_SSH_PRIVATE_KEYFILE + CURLOPT_SSH_PUBLIC_KEYFILE + CURLOPT_SSLCERT + CURLOPT_SSLCERTTYPE + CURLOPT_SSLENGINE + CURLOPT_SSLKEY + CURLOPT_SSLKEYTYPE + CURLOPT_SSL_CIPHER_LIST + CURLOPT_SSL_EC_CURVES + CURLOPT_TLS13_CIPHERS + CURLOPT_TLSAUTH_PASSWORD + CURLOPT_TLSAUTH_TYPE + CURLOPT_TLSAUTH_USERNAME + CURLOPT_UNIX_SOCKET_PATH + CURLOPT_URL + CURLOPT_USERAGENT + CURLOPT_USERNAME + CURLOPT_USERPWD + CURLOPT_XOAUTH2_BEARER + All blob options are also supported. + In all other cases, it ignores the ccsid parameter and behaves as +curl_easy_setopt(). + Note that CURLOPT_ERRORBUFFER is not in the list above, since it gives the +address of an (empty) character buffer, not the address of a string. +CURLOPT_POSTFIELDS stores the address of static binary data (of type void *) +and thus is not converted. If CURLOPT_COPYPOSTFIELDS is issued after +CURLOPT_POSTFIELDSIZE != -1, the data size is adjusted according to the +CCSID conversion result length. + +_ curl_formadd_ccsid() + In the variable argument list, string pointers should be followed by a (long) +CCSID for the following options: + CURLFORM_BUFFER + CURLFORM_CONTENTTYPE + CURLFORM_COPYCONTENTS + CURLFORM_COPYNAME + CURLFORM_FILE + CURLFORM_FILECONTENT + CURLFORM_FILENAME + CURLFORM_PTRNAME + If taken from an argument array, an additional array entry must follow each +entry containing one of the above option. This additional entry holds the CCSID +in its value field, and the option field is meaningless. + It is not possible to have a string pointer and its CCSID across a function +parameter/array boundary. + Please note that CURLFORM_PTRCONTENTS and CURLFORM_BUFFERPTR are considered +unconvertible strings and thus are NOT followed by a CCSID. + +_ curl_easy_getinfo_ccsid() + The following options are followed by a 'char * *' and a CCSID. Unlike +curl_easy_getinfo(), the value returned in the pointer should be released with +curl_free() after use: + CURLINFO_CONTENT_TYPE + CURLINFO_EFFECTIVE_URL + CURLINFO_FTP_ENTRY_PATH + CURLINFO_LOCAL_IP + CURLINFO_PRIMARY_IP + CURLINFO_REDIRECT_URL + CURLINFO_REFERER + CURLINFO_RTSP_SESSION_ID + CURLINFO_SCHEME + Likewise, the following options are followed by a struct curl_slist * * and a +CCSID. + CURLINFO_COOKIELIST + CURLINFO_SSL_ENGINES +Lists returned should be released with curl_slist_free_all() after use. + Option CURLINFO_CERTINFO is followed by a struct curl_certinfo * * and a +CCSID. Returned structures should be freed with curl_certinfo_free_all() +after use. + Other options are processed like in curl_easy_getinfo(). + +_ curl_easy_strerror_ccsid(), curl_multi_strerror_ccsid(), +curl_share_strerror_ccsid() and curl_url_strerror_ccsid() work as their +non-ccsid version and return a string encoded in the additional ccsid +parameter. These strings belong to libcurl and may not be freed by the caller. +A subsequent call to the same procedure in the same thread invalidates the +previous result. + +_ curl_pushheader_bynum_cssid() and curl_pushheader_byname_ccsid() + Although the prototypes are self-explanatory, the returned string pointer +should be released with curl_free() after use, as opposite to the non-ccsid +versions of these procedures. + Please note that HTTP2 is not (yet) implemented on OS/400, thus these +functions will always return NULL. + +_ curl_easy_option_by_name_ccsid() returns a pointer to an untranslated option +metadata structure. As each curl_easyoption structure holds the option name in +ASCII, the curl_easy_option_get_name_ccsid() function allows getting it in any +supported ccsid. However the caller should release the returned pointer with +curl_free() after use. + +_ curl_easy_header_ccsid() works as its non-CCSID counterpart but requires an +additional ccsid parameter specifying the name parameter encoding. The output +hout parameter is kept in libcurl's encoding and should not be altered. + +_ curl_from_ccsid() and curl_to_ccsid() are string encoding conversion +functions between ASCII (latin1) and the given CCSID. The first parameter is +the source string, the second is the CCSID and the returned value is a pointer +to the dynamically allocated string. These functions do not impact on Curl's +behavior and are only provided for user convenience. After use, returned values +must be released with curl_free(). + + + Standard compilation environment does support neither autotools nor make; +in fact, very few common utilities are available. As a consequence, the +config-os400.h has been coded manually and the compilation scripts are +a set of shell scripts stored in subdirectory packages/OS400. + + The "curl" command and the test environment are currently not supported on +OS/400. + + +Protocols currently implemented on OS/400: +_ DICT +_ FILE +_ FTP +_ FTPS +_ FTP with secure transmission +_ GOPHER +_ HTTP +_ HTTPS +_ IMAP +_ IMAPS +_ IMAP with secure transmission +_ LDAP +_ POP3 +_ POP3S +_ POP3 with secure transmission +_ RTSP +_ SCP if libssh2 is enabled +_ SFTP if libssh2 is enabled +_ SMTP +_ SMTPS +_ SMTP with secure transmission +_ TELNET +_ TFTP + + + +Compiling on OS/400: + + These instructions targets people who knows about OS/400, compiling, IFS and +archive extraction. Do not ask questions about these subjects if you're not +familiar with. + +_ As a prerequisite, QADRT development environment must be installed. + For more information on downloading and installing the QADRT development kit, + please see https://www.ibm.com/support/pages/node/6258183 +_ If data compression has to be supported, ZLIB development environment must + be installed. +_ Likewise, if SCP and SFTP protocols have to be compiled in, LIBSSH2 + developent environment must be installed. +_ Install the curl source directory in IFS. Do NOT install it in the + installation target directory (which defaults to /curl). +_ Enter Qshell (QSH, not PASE) +_ Change current directory to the curl installation directory +_ Change current directory to ./packages/OS400 +- If you want to change the default configuration parameters like debug info + generation, optimization level, listing option, target library, ZLIB/LIBSSH2 + availability and location, etc., copy file config400.default to + config400.override and edit the latter. Do not edit the original default file + as it might be overwritten by a subsequent source installation. +_ Copy any file in the current directory to makelog (i.e.: + cp initscript.sh makelog): this is intended to create the makelog file with + an ASCII CCSID! +_ Enter the command "sh makefile.sh > makelog 2>&1" +_ Examine the makelog file to check for compilation errors. CZM0383 warnings on + C or system standard API come from QADRT inlining and can safely be ignored. + + Without configuration parameters override, this will produce the following +OS/400 objects: +_ Library CURL. All other objects will be stored in this library. +_ Modules for all libcurl units. +_ Binding directory CURL_A, to be used at calling program link time for + statically binding the modules (specify BNDSRVPGM(QADRTTS QGLDCLNT QGLDBRDR) + when creating a program using CURL_A). +_ Service program CURL., where is extracted from the + lib/Makefile.am VERSION variable. To be used at calling program run-time + when this program has dynamically bound curl at link time. +_ Binding directory CURL. To be used to dynamically bind libcurl when linking a + calling program. +- CLI tool bound program CURL. +- CLI command CURL. +_ Source file H. It contains all the include members needed to compile a C/C++ + module using libcurl, and an ILE/RPG /copy member for support in this + language. +_ Standard C/C++ libcurl include members in file H. +_ CCSIDCURL member in file H. This defines the non-standard EBCDIC wrappers for + C and C++. +_ CURL.INC member in file H. This defines everything needed by an ILE/RPG + program using libcurl. +_ IFS directory /curl/include/curl containing the C header files for IFS source + C/C++ compilation and curl.inc.rpgle for IFS source ILE/RPG compilation. +- IFS link /curl/bin/curl to CLI tool program. + + +Special programming consideration: + +QADRT being used, the following points must be considered: +_ If static binding is used, service program QADRTTS must be linked too. +_ The EBCDIC CCSID used by QADRT is 37 by default, NOT THE JOB'S CCSID. If + another EBCDIC CCSID is required, it must be set via a locale through a call + to setlocale_a (QADRT's setlocale() ASCII wrapper) with category LC_ALL or + LC_CTYPE, or by setting environment variable QADRT_ENV_LOCALE to the locale + object path before executing the program. +_ Do not use original source include files unless you know what you are doing. + Use the installed members instead (in /QSYS.LIB/CURL.LIB/H.FILE and + /curl/include/curl). + + + +ILE/RPG support: + + Since most of the ILE OS/400 programmers use ILE/RPG exclusively, a +definition /INCLUDE member is provided for this language. To include all +libcurl definitions in an ILE/RPG module, line + + h bnddir('CURL/CURL') + +must figure in the program header, and line + + d/include curl/h,curl.inc + +in the global data section of the module's source code. + + No vararg procedure support exists in ILE/RPG: for this reason, the following +considerations apply: +_ Procedures curl_easy_setopt_long(), curl_easy_setopt_object(), + curl_easy_setopt_function(), curl_easy_setopt_offset() and + curl_easy_setopt_blob() are all alias prototypes to curl_easy_setopt(), but + with different parameter lists. +_ Procedures curl_easy_getinfo_string(), curl_easy_getinfo_long(), + curl_easy_getinfo_double(), curl_easy_getinfo_slist(), + curl_easy_getinfo_ptr(), curl_easy_getinfo_socket() and + curl_easy_getinfo_off_t() are all alias prototypes to curl_easy_getinfo(), + but with different parameter lists. +_ Procedures curl_multi_setopt_long(), curl_multi_setopt_object(), + curl_multi_setopt_function() and curl_multi_setopt_offset() are all alias + prototypes to curl_multi_setopt(), but with different parameter lists. +_ Procedures curl_share_setopt_int(), curl_share_setopt_ptr() and + curl_share_setopt_proc() are all alias prototypes to curl_share_setopt, + but with different parameter lists. +_ Procedure curl_easy_setopt_blob_ccsid() is an alias of + curl_easy_setopt_ccsid() supporting blob encoding conversion. +_ The prototype of procedure curl_formadd() allows specifying a pointer option + and the CURLFORM_END option. This makes possible to use an option array + without any additional definition. If some specific incompatible argument + list is used in the ILE/RPG program, the latter must define a specialised + alias. The same applies to curl_formadd_ccsid() too. +_ Since V7R4M0, procedure overloading is used to emulate limited "vararg-like" + definitions of curl_easy_setopt(), curl_multi_setopt(), curl_share_setopt() + and curl_easy_getinfo(). Blob and CCSID alternatives are NOT included in + overloading. + + Since RPG cannot cast a long to a pointer, procedure curl_form_long_value() +is provided for that purpose: this allows storing a long value in the +curl_forms array. Please note the form API is deprecated and the MIME API +should be used instead. + + +CLI tool: + + The build system provides it as a bound program, an IFS link to it and a +simple CL command. The latter however is not able to provide a different +parameter for each option since there are too many of those; instead, +parameters are entered in a single field subject to quoting and escaping, in +the same form as expected by the standard CLI program. + Care must be taken about the program output encoding: by default, it is sent +to the standard output and is thus subject to transcoding. It is therefore +recommended to use option "--output" to redirect output to a specific IFS file. +Similar problems may occur about the standard input encoding. diff --git a/third_party/curl/packages/OS400/ccsidcurl.c b/third_party/curl/packages/OS400/ccsidcurl.c new file mode 100644 index 0000000..60a10d7 --- /dev/null +++ b/third_party/curl/packages/OS400/ccsidcurl.c @@ -0,0 +1,1529 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * + ***************************************************************************/ + +/* CCSID API wrappers for OS/400. */ + +#include +#include +#include +#include +#include +#include + +#pragma enum(int) + +#include "curl.h" +#include "mprintf.h" +#include "slist.h" +#include "urldata.h" +#include "url.h" +#include "setopt.h" +#include "getinfo.h" +#include "ccsidcurl.h" + +#include "os400sys.h" + +#ifndef SIZE_MAX +#define SIZE_MAX ((size_t) ~0) /* Is unsigned on OS/400. */ +#endif + + +#define ASCII_CCSID 819 /* Use ISO-8859-1 as ASCII. */ +#define NOCONV_CCSID 65535 /* No conversion. */ +#define ICONV_ID_SIZE 32 /* Size of iconv_open() code identifier. */ +#define ICONV_OPEN_ERROR(t) ((t).return_value == -1) + +#define ALLOC_GRANULE 8 /* Alloc. granule for curl_formadd_ccsid(). */ + + +static void +makeOS400IconvCode(char buf[ICONV_ID_SIZE], unsigned int ccsid) +{ + /** + *** Convert a CCSID to the corresponding IBM iconv_open() character + *** code identifier. + *** This code is specific to the OS400 implementation of the iconv library. + *** CCSID 65535 (no conversion) is replaced by the ASCII CCSID. + *** CCSID 0 is interpreted by the OS400 as the job's CCSID. + **/ + + ccsid &= 0xFFFF; + + if(ccsid == NOCONV_CCSID) + ccsid = ASCII_CCSID; + + memset(buf, 0, ICONV_ID_SIZE); + curl_msprintf(buf, "IBMCCSID%05u0000000", ccsid); +} + + +static iconv_t +iconv_open_CCSID(unsigned int ccsidout, unsigned int ccsidin, + unsigned int cstr) +{ + char fromcode[ICONV_ID_SIZE]; + char tocode[ICONV_ID_SIZE]; + + /** + *** Like iconv_open(), but character codes are given as CCSIDs. + *** If `cstr' is non-zero, conversion is set up to stop whenever a + *** null character is encountered. + *** See iconv_open() IBM description in "National Language Support API". + **/ + + makeOS400IconvCode(fromcode, ccsidin); + makeOS400IconvCode(tocode, ccsidout); + memset(tocode + 13, 0, sizeof(tocode) - 13); /* Dest. code id format. */ + + if(cstr) + fromcode[18] = '1'; /* Set null-terminator flag. */ + + return iconv_open(tocode, fromcode); +} + + +static int +convert(char *d, size_t dlen, int dccsid, + const char *s, int slen, int sccsid) +{ + int i; + iconv_t cd; + size_t lslen; + + /** + *** Convert `sccsid'-coded `slen'-data bytes at `s' into `dccsid'-coded + *** data stored in the `dlen'-byte buffer at `d'. + *** If `slen' < 0, source string is null-terminated. + *** CCSID 65535 (no conversion) is replaced by the ASCII CCSID. + *** Return the converted destination byte count, or -1 if error. + **/ + + if(sccsid == 65535) + sccsid = ASCII_CCSID; + + if(dccsid == 65535) + dccsid = ASCII_CCSID; + + if(sccsid == dccsid) { + lslen = slen >= 0? slen: strlen(s) + 1; + i = lslen < dlen? lslen: dlen; + + if(s != d && i > 0) + memcpy(d, s, i); + + return i; + } + + if(slen < 0) { + lslen = 0; + cd = iconv_open_CCSID(dccsid, sccsid, 1); + } + else { + lslen = (size_t) slen; + cd = iconv_open_CCSID(dccsid, sccsid, 0); + } + + if(ICONV_OPEN_ERROR(cd)) + return -1; + + i = dlen; + + if((int) iconv(cd, (char * *) &s, &lslen, &d, &dlen) < 0) + i = -1; + else + i -= dlen; + + iconv_close(cd); + return i; +} + + +static char *dynconvert(int dccsid, const char *s, int slen, int sccsid) +{ + char *d; + char *cp; + size_t dlen; + int l; + static const char nullbyte = 0; + + /* Like convert, but the destination is allocated and returned. */ + + dlen = (size_t) (slen < 0? strlen(s): slen) + 1; + dlen *= MAX_CONV_EXPANSION; /* Allow some expansion. */ + d = malloc(dlen); + + if(!d) + return (char *) NULL; + + l = convert(d, dlen, dccsid, s, slen, sccsid); + + if(l < 0) { + free(d); + return (char *) NULL; + } + + if(slen < 0) { + /* Need to null-terminate even when source length is given. + Since destination code size is unknown, use a conversion to generate + terminator. */ + + int l2 = convert(d + l, dlen - l, dccsid, &nullbyte, -1, ASCII_CCSID); + + if(l2 < 0) { + free(d); + return (char *) NULL; + } + + l += l2; + } + + if((size_t) l < dlen) { + cp = realloc(d, l); /* Shorten to minimum needed. */ + + if(cp) + d = cp; + } + + return d; +} + + +static struct curl_slist * +slist_convert(int dccsid, struct curl_slist *from, int sccsid) +{ + struct curl_slist *to = (struct curl_slist *) NULL; + + for(; from; from = from->next) { + struct curl_slist *nl; + char *cp = dynconvert(dccsid, from->data, -1, sccsid); + + if(!cp) { + curl_slist_free_all(to); + return (struct curl_slist *) NULL; + } + nl = Curl_slist_append_nodup(to, cp); + if(!nl) { + curl_slist_free_all(to); + free(cp); + return NULL; + } + to = nl; + } + return to; +} + + +static char * +keyed_string(localkey_t key, const char *ascii, unsigned int ccsid) +{ + int i; + char *ebcdic; + + if(!ascii) + return (char *) NULL; + + i = MAX_CONV_EXPANSION * (strlen(ascii) + 1); + + ebcdic = Curl_thread_buffer(key, i); + if(!ebcdic) + return ebcdic; + + if(convert(ebcdic, i, ccsid, ascii, -1, ASCII_CCSID) < 0) + return (char *) NULL; + + return ebcdic; +} + + +const char * +curl_to_ccsid(const char *s, unsigned int ccsid) +{ + if(s) + s = dynconvert(ccsid, s, -1, ASCII_CCSID); + return s; +} + + +const char * +curl_from_ccsid(const char *s, unsigned int ccsid) +{ + if(s) + s = dynconvert(ASCII_CCSID, s, -1, ccsid); + return s; +} + + +char * +curl_version_ccsid(unsigned int ccsid) +{ + return keyed_string(LK_CURL_VERSION, curl_version(), ccsid); +} + + +char * +curl_easy_escape_ccsid(CURL *handle, const char *string, int length, + unsigned int sccsid, unsigned int dccsid) +{ + char *s; + char *d; + + if(!string) { + errno = EINVAL; + return (char *) NULL; + } + + s = dynconvert(ASCII_CCSID, string, length? length: -1, sccsid); + + if(!s) + return (char *) NULL; + + d = curl_easy_escape(handle, s, 0); + free(s); + + if(!d) + return (char *) NULL; + + s = dynconvert(dccsid, d, -1, ASCII_CCSID); + free(d); + return s; +} + + +char * +curl_easy_unescape_ccsid(CURL *handle, const char *string, int length, + int *outlength, + unsigned int sccsid, unsigned int dccsid) +{ + char *s; + char *d; + + if(!string) { + errno = EINVAL; + return (char *) NULL; + } + + s = dynconvert(ASCII_CCSID, string, length? length: -1, sccsid); + + if(!s) + return (char *) NULL; + + d = curl_easy_unescape(handle, s, 0, outlength); + free(s); + + if(!d) + return (char *) NULL; + + s = dynconvert(dccsid, d, -1, ASCII_CCSID); + free(d); + + if(s && outlength) + *outlength = strlen(s); + + return s; +} + + +struct curl_slist * +curl_slist_append_ccsid(struct curl_slist *list, + const char *data, unsigned int ccsid) +{ + char *s; + + s = (char *) NULL; + + if(!data) + return curl_slist_append(list, data); + + s = dynconvert(ASCII_CCSID, data, -1, ccsid); + + if(!s) + return (struct curl_slist *) NULL; + + list = curl_slist_append(list, s); + free(s); + return list; +} + + +time_t +curl_getdate_ccsid(const char *p, const time_t *unused, unsigned int ccsid) +{ + char *s; + time_t t; + + if(!p) + return curl_getdate(p, unused); + + s = dynconvert(ASCII_CCSID, p, -1, ccsid); + + if(!s) + return (time_t) -1; + + t = curl_getdate(s, unused); + free(s); + return t; +} + + +static int +convert_version_info_string(const char **stringp, + char **bufp, int *left, unsigned int ccsid) +{ + /* Helper for curl_version_info_ccsid(): convert a string if defined. + Result is stored in the `*left'-byte buffer at `*bufp'. + `*bufp' and `*left' are updated accordingly. + Return 0 if ok, else -1. */ + + if(*stringp) { + int l = convert(*bufp, *left, ccsid, *stringp, -1, ASCII_CCSID); + + if(l <= 0) + return -1; + + *stringp = *bufp; + *bufp += l; + *left -= l; + } + + return 0; +} + + +curl_version_info_data * +curl_version_info_ccsid(CURLversion stamp, unsigned int ccsid) +{ + curl_version_info_data *p; + char *cp; + int n; + int nproto; + curl_version_info_data *id; + int i; + const char **cpp; + static const size_t charfields[] = { + offsetof(curl_version_info_data, version), + offsetof(curl_version_info_data, host), + offsetof(curl_version_info_data, ssl_version), + offsetof(curl_version_info_data, libz_version), + offsetof(curl_version_info_data, ares), + offsetof(curl_version_info_data, libidn), + offsetof(curl_version_info_data, libssh_version), + offsetof(curl_version_info_data, brotli_version), + offsetof(curl_version_info_data, nghttp2_version), + offsetof(curl_version_info_data, quic_version), + offsetof(curl_version_info_data, cainfo), + offsetof(curl_version_info_data, capath), + offsetof(curl_version_info_data, zstd_version), + offsetof(curl_version_info_data, hyper_version), + offsetof(curl_version_info_data, gsasl_version), + offsetof(curl_version_info_data, feature_names), + offsetof(curl_version_info_data, rtmp_version) + }; + + /* The assertion below is possible, because although the second operand + is an enum member, the first is a #define. In that case, the OS/400 C + compiler seems to compare string values after substitution. */ + +#if CURLVERSION_NOW != CURLVERSION_ELEVENTH +#error curl_version_info_data structure has changed: upgrade this procedure. +#endif + + /* If caller has been compiled with a newer version, error. */ + + if(stamp > CURLVERSION_NOW) + return (curl_version_info_data *) NULL; + + p = curl_version_info(stamp); + + if(!p) + return p; + + /* Measure thread space needed. */ + + n = 0; + nproto = 0; + + if(p->protocols) { + while(p->protocols[nproto]) + n += strlen(p->protocols[nproto++]); + + n += nproto++; + } + + for(i = 0; i < sizeof(charfields) / sizeof(charfields[0]); i++) { + cpp = (const char **) ((char *) p + charfields[i]); + if(*cpp) + n += strlen(*cpp) + 1; + } + + /* Allocate thread space. */ + + n *= MAX_CONV_EXPANSION; + + if(nproto) + n += nproto * sizeof(const char *); + + cp = Curl_thread_buffer(LK_VERSION_INFO_DATA, n); + id = (curl_version_info_data *) Curl_thread_buffer(LK_VERSION_INFO, + sizeof(*id)); + + if(!id || !cp) + return (curl_version_info_data *) NULL; + + /* Copy data and convert strings. */ + + memcpy((char *) id, (char *) p, sizeof(*p)); + + if(id->protocols) { + i = nproto * sizeof(id->protocols[0]); + + id->protocols = (const char * const *) cp; + memcpy(cp, (char *) p->protocols, i); + cp += i; + n -= i; + + for(i = 0; id->protocols[i]; i++) + if(convert_version_info_string(((const char * *) id->protocols) + i, + &cp, &n, ccsid)) + return (curl_version_info_data *) NULL; + } + + for(i = 0; i < sizeof(charfields) / sizeof(charfields[0]); i++) { + cpp = (const char **) ((char *) p + charfields[i]); + if(*cpp && convert_version_info_string(cpp, &cp, &n, ccsid)) + return (curl_version_info_data *) NULL; + } + + return id; +} + + +const char * +curl_easy_strerror_ccsid(CURLcode error, unsigned int ccsid) +{ + return keyed_string(LK_EASY_STRERROR, curl_easy_strerror(error), ccsid); +} + + +const char * +curl_share_strerror_ccsid(CURLSHcode error, unsigned int ccsid) +{ + return keyed_string(LK_SHARE_STRERROR, curl_share_strerror(error), ccsid); +} + + +const char * +curl_multi_strerror_ccsid(CURLMcode error, unsigned int ccsid) +{ + return keyed_string(LK_MULTI_STRERROR, curl_multi_strerror(error), ccsid); +} + + +const char * +curl_url_strerror_ccsid(CURLUcode error, unsigned int ccsid) +{ + return keyed_string(LK_URL_STRERROR, curl_url_strerror(error), ccsid); +} + + +void +curl_certinfo_free_all(struct curl_certinfo *info) +{ + /* Free all memory used by certificate info. */ + if(info) { + if(info->certinfo) { + int i; + + for(i = 0; i < info->num_of_certs; i++) + curl_slist_free_all(info->certinfo[i]); + free((char *) info->certinfo); + } + free((char *) info); + } +} + + +CURLcode +curl_easy_getinfo_ccsid(CURL *curl, CURLINFO info, ...) +{ + va_list arg; + void *paramp; + CURLcode ret; + struct Curl_easy *data; + + /* WARNING: unlike curl_easy_getinfo(), the strings returned by this + procedure have to be free'ed. */ + + data = (struct Curl_easy *) curl; + va_start(arg, info); + paramp = va_arg(arg, void *); + ret = Curl_getinfo(data, info, paramp); + + if(ret == CURLE_OK) { + unsigned int ccsid; + char **cpp; + struct curl_slist **slp; + struct curl_certinfo *cipf; + struct curl_certinfo *cipt; + + switch((int) info & CURLINFO_TYPEMASK) { + + case CURLINFO_STRING: + ccsid = va_arg(arg, unsigned int); + cpp = (char * *) paramp; + + if(*cpp) { + *cpp = dynconvert(ccsid, *cpp, -1, ASCII_CCSID); + + if(!*cpp) + ret = CURLE_OUT_OF_MEMORY; + } + + break; + + case CURLINFO_SLIST: + ccsid = va_arg(arg, unsigned int); + switch(info) { + case CURLINFO_CERTINFO: + cipf = *(struct curl_certinfo * *) paramp; + if(cipf) { + cipt = (struct curl_certinfo *) malloc(sizeof(*cipt)); + if(!cipt) + ret = CURLE_OUT_OF_MEMORY; + else { + cipt->certinfo = (struct curl_slist **) + calloc(cipf->num_of_certs + + 1, sizeof(struct curl_slist *)); + if(!cipt->certinfo) + ret = CURLE_OUT_OF_MEMORY; + else { + int i; + + cipt->num_of_certs = cipf->num_of_certs; + for(i = 0; i < cipf->num_of_certs; i++) + if(cipf->certinfo[i]) + if(!(cipt->certinfo[i] = slist_convert(ccsid, + cipf->certinfo[i], + ASCII_CCSID))) { + ret = CURLE_OUT_OF_MEMORY; + break; + } + } + } + + if(ret != CURLE_OK) { + curl_certinfo_free_all(cipt); + cipt = (struct curl_certinfo *) NULL; + } + + *(struct curl_certinfo * *) paramp = cipt; + } + + break; + + case CURLINFO_TLS_SESSION: + case CURLINFO_TLS_SSL_PTR: + case CURLINFO_SOCKET: + break; + + default: + slp = (struct curl_slist **) paramp; + if(*slp) { + *slp = slist_convert(ccsid, *slp, ASCII_CCSID); + if(!*slp) + ret = CURLE_OUT_OF_MEMORY; + } + break; + } + } + } + + va_end(arg); + return ret; +} + + +static int +Curl_is_formadd_string(CURLformoption option) +{ + switch(option) { + + case CURLFORM_FILENAME: + case CURLFORM_CONTENTTYPE: + case CURLFORM_BUFFER: + case CURLFORM_FILE: + case CURLFORM_FILECONTENT: + case CURLFORM_COPYCONTENTS: + case CURLFORM_COPYNAME: + return 1; + } + + return 0; +} + + +static void +Curl_formadd_release_local(struct curl_forms *forms, int nargs, int skip) +{ + while(nargs--) + if(nargs != skip) + if(Curl_is_formadd_string(forms[nargs].option)) + if(forms[nargs].value) + free((char *) forms[nargs].value); + + free((char *) forms); +} + + +static int +Curl_formadd_convert(struct curl_forms *forms, + int formx, int lengthx, unsigned int ccsid) +{ + int l; + char *cp; + char *cp2; + + if(formx < 0 || !forms[formx].value) + return 0; + + if(lengthx >= 0) + l = (int) forms[lengthx].value; + else + l = strlen(forms[formx].value) + 1; + + cp = malloc(MAX_CONV_EXPANSION * l); + + if(!cp) + return -1; + + l = convert(cp, MAX_CONV_EXPANSION * l, ASCII_CCSID, + forms[formx].value, l, ccsid); + + if(l < 0) { + free(cp); + return -1; + } + + cp2 = realloc(cp, l); /* Shorten buffer to the string size. */ + + if(cp2) + cp = cp2; + + forms[formx].value = cp; + + if(lengthx >= 0) + forms[lengthx].value = (char *) l; /* Update length after conversion. */ + + return l; +} + + +CURLFORMcode +curl_formadd_ccsid(struct curl_httppost **httppost, + struct curl_httppost **last_post, ...) +{ + va_list arg; + CURLformoption option; + CURLFORMcode result; + struct curl_forms *forms; + struct curl_forms *lforms; + struct curl_forms *tforms; + unsigned int lformlen; + const char *value; + unsigned int ccsid; + int nargs; + int namex; + int namelengthx; + int contentx; + int lengthx; + unsigned int contentccsid; + unsigned int nameccsid; + + /* A single curl_formadd() call cannot be split in several calls to deal + with all parameters: the original parameters are thus copied to a local + curl_forms array and converted to ASCII when needed. + CURLFORM_PTRNAME is processed as if it were CURLFORM_COPYNAME. + CURLFORM_COPYNAME and CURLFORM_NAMELENGTH occurrence order in + parameters is not defined; for this reason, the actual conversion is + delayed to the end of parameter processing. The same applies to + CURLFORM_COPYCONTENTS/CURLFORM_CONTENTSLENGTH, but these may appear + several times in the parameter list; the problem resides here in knowing + which CURLFORM_CONTENTSLENGTH applies to which CURLFORM_COPYCONTENTS and + when we can be sure to have both info for conversion: end of parameter + list is such a point, but CURLFORM_CONTENTTYPE is also used here as a + natural separator between content data definitions; this seems to be + in accordance with FormAdd() behavior. */ + + /* Allocate the local curl_forms array. */ + + lformlen = ALLOC_GRANULE; + lforms = malloc(lformlen * sizeof(*lforms)); + + if(!lforms) + return CURL_FORMADD_MEMORY; + + /* Process the arguments, copying them into local array, latching conversion + indexes and converting when needed. */ + + result = CURL_FORMADD_OK; + nargs = 0; + contentx = -1; + lengthx = -1; + namex = -1; + namelengthx = -1; + forms = (struct curl_forms *) NULL; + va_start(arg, last_post); + + for(;;) { + /* Make sure there is still room for an item in local array. */ + + if(nargs >= lformlen) { + lformlen += ALLOC_GRANULE; + tforms = realloc(lforms, lformlen * sizeof(*lforms)); + + if(!tforms) { + result = CURL_FORMADD_MEMORY; + break; + } + + lforms = tforms; + } + + /* Get next option. */ + + if(forms) { + /* Get option from array. */ + + option = forms->option; + value = forms->value; + forms++; + } + else { + /* Get option from arguments. */ + + option = va_arg(arg, CURLformoption); + + if(option == CURLFORM_END) + break; + } + + /* Dispatch by option. */ + + switch(option) { + + case CURLFORM_END: + forms = (struct curl_forms *) NULL; /* Leave array mode. */ + continue; + + case CURLFORM_ARRAY: + if(!forms) { + forms = va_arg(arg, struct curl_forms *); + continue; + } + + result = CURL_FORMADD_ILLEGAL_ARRAY; + break; + + case CURLFORM_COPYNAME: + option = CURLFORM_PTRNAME; /* Static for now. */ + + case CURLFORM_PTRNAME: + if(namex >= 0) + result = CURL_FORMADD_OPTION_TWICE; + + namex = nargs; + + if(!forms) { + value = va_arg(arg, char *); + nameccsid = (unsigned int) va_arg(arg, long); + } + else { + nameccsid = (unsigned int) forms->value; + forms++; + } + + break; + + case CURLFORM_COPYCONTENTS: + if(contentx >= 0) + result = CURL_FORMADD_OPTION_TWICE; + + contentx = nargs; + + if(!forms) { + value = va_arg(arg, char *); + contentccsid = (unsigned int) va_arg(arg, long); + } + else { + contentccsid = (unsigned int) forms->value; + forms++; + } + + break; + + case CURLFORM_PTRCONTENTS: + case CURLFORM_BUFFERPTR: + if(!forms) + value = va_arg(arg, char *); /* No conversion. */ + + break; + + case CURLFORM_CONTENTSLENGTH: + lengthx = nargs; + + if(!forms) + value = (char *) va_arg(arg, long); + + break; + + case CURLFORM_CONTENTLEN: + lengthx = nargs; + + if(!forms) + value = (char *) va_arg(arg, curl_off_t); + + break; + + case CURLFORM_NAMELENGTH: + namelengthx = nargs; + + if(!forms) + value = (char *) va_arg(arg, long); + + break; + + case CURLFORM_BUFFERLENGTH: + if(!forms) + value = (char *) va_arg(arg, long); + + break; + + case CURLFORM_CONTENTHEADER: + if(!forms) + value = (char *) va_arg(arg, struct curl_slist *); + + break; + + case CURLFORM_STREAM: + if(!forms) + value = (char *) va_arg(arg, void *); + + break; + + case CURLFORM_CONTENTTYPE: + /* If a previous content has been encountered, convert it now. */ + + if(Curl_formadd_convert(lforms, contentx, lengthx, contentccsid) < 0) { + result = CURL_FORMADD_MEMORY; + break; + } + + contentx = -1; + lengthx = -1; + /* Fall into default. */ + + default: + /* Must be a convertible string. */ + + if(!Curl_is_formadd_string(option)) { + result = CURL_FORMADD_UNKNOWN_OPTION; + break; + } + + if(!forms) { + value = va_arg(arg, char *); + ccsid = (unsigned int) va_arg(arg, long); + } + else { + ccsid = (unsigned int) forms->value; + forms++; + } + + /* Do the conversion. */ + + lforms[nargs].value = value; + + if(Curl_formadd_convert(lforms, nargs, -1, ccsid) < 0) { + result = CURL_FORMADD_MEMORY; + break; + } + + value = lforms[nargs].value; + } + + if(result != CURL_FORMADD_OK) + break; + + lforms[nargs].value = value; + lforms[nargs++].option = option; + } + + va_end(arg); + + /* Convert the name and the last content, now that we know their lengths. */ + + if(result == CURL_FORMADD_OK && namex >= 0) { + if(Curl_formadd_convert(lforms, namex, namelengthx, nameccsid) < 0) + result = CURL_FORMADD_MEMORY; + else + lforms[namex].option = CURLFORM_COPYNAME; /* Force copy. */ + } + + if(result == CURL_FORMADD_OK) { + if(Curl_formadd_convert(lforms, contentx, lengthx, contentccsid) < 0) + result = CURL_FORMADD_MEMORY; + else + contentx = -1; + } + + /* Do the formadd with our converted parameters. */ + + if(result == CURL_FORMADD_OK) { + lforms[nargs].option = CURLFORM_END; + result = curl_formadd(httppost, last_post, + CURLFORM_ARRAY, lforms, CURLFORM_END); + } + + /* Terminate. */ + + Curl_formadd_release_local(lforms, nargs, contentx); + return result; +} + + +struct cfcdata { + curl_formget_callback append; + void * arg; + unsigned int ccsid; +}; + + +static size_t +Curl_formget_callback_ccsid(void *arg, const char *buf, size_t len) +{ + struct cfcdata *p; + char *b; + int l; + size_t ret; + + p = (struct cfcdata *) arg; + + if((long) len <= 0) + return (*p->append)(p->arg, buf, len); + + b = malloc(MAX_CONV_EXPANSION * len); + + if(!b) + return (size_t) -1; + + l = convert(b, MAX_CONV_EXPANSION * len, p->ccsid, buf, len, ASCII_CCSID); + + if(l < 0) { + free(b); + return (size_t) -1; + } + + ret = (*p->append)(p->arg, b, l); + free(b); + return ret == l? len: -1; +} + + +int +curl_formget_ccsid(struct curl_httppost *form, void *arg, + curl_formget_callback append, unsigned int ccsid) +{ + struct cfcdata lcfc; + + lcfc.append = append; + lcfc.arg = arg; + lcfc.ccsid = ccsid; + return curl_formget(form, (void *) &lcfc, Curl_formget_callback_ccsid); +} + + +CURLcode +curl_easy_setopt_ccsid(CURL *easy, CURLoption tag, ...) +{ + CURLcode result; + va_list arg; + char *s; + char *cp = NULL; + unsigned int ccsid; + curl_off_t pfsize; + + va_start(arg, tag); + + switch(tag) { + + /* BEGIN TRANSLATABLE STRING OPTIONS */ + /* Keep option symbols in alphanumeric order and retain the BEGIN/END + armor comments. */ + case CURLOPT_ABSTRACT_UNIX_SOCKET: + case CURLOPT_ACCEPT_ENCODING: + case CURLOPT_ALTSVC: + case CURLOPT_AWS_SIGV4: + case CURLOPT_CAINFO: + case CURLOPT_CAPATH: + case CURLOPT_COOKIE: + case CURLOPT_COOKIEFILE: + case CURLOPT_COOKIEJAR: + case CURLOPT_COOKIELIST: + case CURLOPT_CRLFILE: + case CURLOPT_CUSTOMREQUEST: + case CURLOPT_DEFAULT_PROTOCOL: + case CURLOPT_DNS_INTERFACE: + case CURLOPT_DNS_LOCAL_IP4: + case CURLOPT_DNS_LOCAL_IP6: + case CURLOPT_DNS_SERVERS: + case CURLOPT_DOH_URL: + case CURLOPT_ECH: + case CURLOPT_EGDSOCKET: + case CURLOPT_FTPPORT: + case CURLOPT_FTP_ACCOUNT: + case CURLOPT_FTP_ALTERNATIVE_TO_USER: + case CURLOPT_HAPROXY_CLIENT_IP: + case CURLOPT_HSTS: + case CURLOPT_INTERFACE: + case CURLOPT_ISSUERCERT: + case CURLOPT_KEYPASSWD: + case CURLOPT_KRBLEVEL: + case CURLOPT_LOGIN_OPTIONS: + case CURLOPT_MAIL_AUTH: + case CURLOPT_MAIL_FROM: + case CURLOPT_NETRC_FILE: + case CURLOPT_NOPROXY: + case CURLOPT_PASSWORD: + case CURLOPT_PINNEDPUBLICKEY: + case CURLOPT_PRE_PROXY: + case CURLOPT_PROTOCOLS_STR: + case CURLOPT_PROXY: + case CURLOPT_PROXYPASSWORD: + case CURLOPT_PROXYUSERNAME: + case CURLOPT_PROXYUSERPWD: + case CURLOPT_PROXY_CAINFO: + case CURLOPT_PROXY_CAPATH: + case CURLOPT_PROXY_CRLFILE: + case CURLOPT_PROXY_ISSUERCERT: + case CURLOPT_PROXY_KEYPASSWD: + case CURLOPT_PROXY_PINNEDPUBLICKEY: + case CURLOPT_PROXY_SERVICE_NAME: + case CURLOPT_PROXY_SSLCERT: + case CURLOPT_PROXY_SSLCERTTYPE: + case CURLOPT_PROXY_SSLKEY: + case CURLOPT_PROXY_SSLKEYTYPE: + case CURLOPT_PROXY_SSL_CIPHER_LIST: + case CURLOPT_PROXY_TLS13_CIPHERS: + case CURLOPT_PROXY_TLSAUTH_PASSWORD: + case CURLOPT_PROXY_TLSAUTH_TYPE: + case CURLOPT_PROXY_TLSAUTH_USERNAME: + case CURLOPT_RANDOM_FILE: + case CURLOPT_RANGE: + case CURLOPT_REDIR_PROTOCOLS_STR: + case CURLOPT_REFERER: + case CURLOPT_REQUEST_TARGET: + case CURLOPT_RTSP_SESSION_ID: + case CURLOPT_RTSP_STREAM_URI: + case CURLOPT_RTSP_TRANSPORT: + case CURLOPT_SASL_AUTHZID: + case CURLOPT_SERVICE_NAME: + case CURLOPT_SOCKS5_GSSAPI_SERVICE: + case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5: + case CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256: + case CURLOPT_SSH_KNOWNHOSTS: + case CURLOPT_SSH_PRIVATE_KEYFILE: + case CURLOPT_SSH_PUBLIC_KEYFILE: + case CURLOPT_SSLCERT: + case CURLOPT_SSLCERTTYPE: + case CURLOPT_SSLENGINE: + case CURLOPT_SSLKEY: + case CURLOPT_SSLKEYTYPE: + case CURLOPT_SSL_CIPHER_LIST: + case CURLOPT_SSL_EC_CURVES: + case CURLOPT_TLS13_CIPHERS: + case CURLOPT_TLSAUTH_PASSWORD: + case CURLOPT_TLSAUTH_TYPE: + case CURLOPT_TLSAUTH_USERNAME: + case CURLOPT_UNIX_SOCKET_PATH: + case CURLOPT_URL: + case CURLOPT_USERAGENT: + case CURLOPT_USERNAME: + case CURLOPT_USERPWD: + case CURLOPT_XOAUTH2_BEARER: + /* END TRANSLATABLE STRING OPTIONS */ + s = va_arg(arg, char *); + ccsid = va_arg(arg, unsigned int); + + if(s) { + s = dynconvert(ASCII_CCSID, s, -1, ccsid); + + if(!s) { + result = CURLE_OUT_OF_MEMORY; + break; + } + } + + result = curl_easy_setopt(easy, tag, s); + free(s); + break; + + case CURLOPT_COPYPOSTFIELDS: + /* Special case: byte count may have been given by CURLOPT_POSTFIELDSIZE + prior to this call. In this case, convert the given byte count and + replace the length according to the conversion result. */ + s = va_arg(arg, char *); + ccsid = va_arg(arg, unsigned int); + + pfsize = easy->set.postfieldsize; + + if(!s || !pfsize || ccsid == NOCONV_CCSID || ccsid == ASCII_CCSID) { + result = curl_easy_setopt(easy, CURLOPT_COPYPOSTFIELDS, s); + break; + } + + if(pfsize == -1) { + /* Data is null-terminated. */ + s = dynconvert(ASCII_CCSID, s, -1, ccsid); + + if(!s) { + result = CURLE_OUT_OF_MEMORY; + break; + } + } + else { + /* Data length specified. */ + size_t len; + + if(pfsize < 0 || pfsize > SIZE_MAX) { + result = CURLE_OUT_OF_MEMORY; + break; + } + + len = pfsize; + pfsize = len * MAX_CONV_EXPANSION; + + if(pfsize > SIZE_MAX) + pfsize = SIZE_MAX; + + cp = malloc(pfsize); + + if(!cp) { + result = CURLE_OUT_OF_MEMORY; + break; + } + + pfsize = convert(cp, pfsize, ASCII_CCSID, s, len, ccsid); + + if(pfsize < 0) { + result = CURLE_OUT_OF_MEMORY; + break; + } + + easy->set.postfieldsize = pfsize; /* Replace data size. */ + s = cp; + } + + result = curl_easy_setopt(easy, CURLOPT_POSTFIELDS, s); + easy->set.str[STRING_COPYPOSTFIELDS] = s; /* Give to library. */ + break; + + default: + if(tag / 10000 == CURLOPTTYPE_BLOB) { + struct curl_blob *bp = va_arg(arg, struct curl_blob *); + struct curl_blob blob; + + ccsid = va_arg(arg, unsigned int); + + if(bp && bp->data && bp->len && + ccsid != NOCONV_CCSID && ccsid != ASCII_CCSID) { + pfsize = (curl_off_t) bp->len * MAX_CONV_EXPANSION; + + if(pfsize > SIZE_MAX) + pfsize = SIZE_MAX; + + cp = malloc(pfsize); + + if(!cp) { + result = CURLE_OUT_OF_MEMORY; + break; + } + + pfsize = convert(cp, pfsize, ASCII_CCSID, bp->data, bp->len, ccsid); + + if(pfsize < 0) { + result = CURLE_OUT_OF_MEMORY; + break; + } + + blob.data = cp; + blob.len = pfsize; + blob.flags = bp->flags | CURL_BLOB_COPY; + bp = &blob; + } + result = curl_easy_setopt(easy, tag, &blob); + break; + } + FALLTHROUGH(); + case CURLOPT_ERRORBUFFER: /* This is an output buffer. */ + result = Curl_vsetopt(easy, tag, arg); + break; + } + + va_end(arg); + free(cp); + return result; +} + + +/* ILE/RPG helper functions. */ + +char * +curl_form_long_value(long value) +{ + /* ILE/RPG cannot cast an integer to a pointer. This procedure does it. */ + + return (char *) value; +} + + +CURLcode +curl_easy_setopt_RPGnum_(CURL *easy, CURLoption tag, curl_off_t arg) +{ + /* ILE/RPG procedure overloading cannot discriminate between different + size and/or signedness of format arguments. This provides a generic + wrapper that adapts size to the given tag expectation. + This procedure is not intended to be explicitly called from user code. */ + if(tag / 10000 != CURLOPTTYPE_OFF_T) + return curl_easy_setopt(easy, tag, (long) arg); + return curl_easy_setopt(easy, tag, arg); +} + + +CURLcode +curl_multi_setopt_RPGnum_(CURLM *multi, CURLMoption tag, curl_off_t arg) +{ + /* Likewise, for multi handle. */ + if(tag / 10000 != CURLOPTTYPE_OFF_T) + return curl_multi_setopt(multi, tag, (long) arg); + return curl_multi_setopt(multi, tag, arg); +} + + +char * +curl_pushheader_bynum_cssid(struct curl_pushheaders *h, + size_t num, unsigned int ccsid) +{ + char *d = (char *) NULL; + char *s = curl_pushheader_bynum(h, num); + + if(s) + d = dynconvert(ccsid, s, -1, ASCII_CCSID); + + return d; +} + + +char * +curl_pushheader_byname_ccsid(struct curl_pushheaders *h, const char *header, + unsigned int ccsidin, unsigned int ccsidout) +{ + char *d = (char *) NULL; + + if(header) { + header = dynconvert(ASCII_CCSID, header, -1, ccsidin); + + if(header) { + char *s = curl_pushheader_byname(h, header); + free((char *) header); + + if(s) + d = dynconvert(ccsidout, s, -1, ASCII_CCSID); + } + } + + return d; +} + +static CURLcode +mime_string_call(curl_mimepart *part, const char *string, unsigned int ccsid, + CURLcode (*mimefunc)(curl_mimepart *part, const char *string)) +{ + char *s = (char *) NULL; + CURLcode result; + + if(!string) + return mimefunc(part, string); + s = dynconvert(ASCII_CCSID, string, -1, ccsid); + if(!s) + return CURLE_OUT_OF_MEMORY; + + result = mimefunc(part, s); + free(s); + return result; +} + +CURLcode +curl_mime_name_ccsid(curl_mimepart *part, const char *name, unsigned int ccsid) +{ + return mime_string_call(part, name, ccsid, curl_mime_name); +} + +CURLcode +curl_mime_filename_ccsid(curl_mimepart *part, + const char *filename, unsigned int ccsid) +{ + return mime_string_call(part, filename, ccsid, curl_mime_filename); +} + +CURLcode +curl_mime_type_ccsid(curl_mimepart *part, + const char *mimetype, unsigned int ccsid) +{ + return mime_string_call(part, mimetype, ccsid, curl_mime_type); +} + +CURLcode +curl_mime_encoder_ccsid(curl_mimepart *part, + const char *encoding, unsigned int ccsid) +{ + return mime_string_call(part, encoding, ccsid, curl_mime_encoder); +} + +CURLcode +curl_mime_filedata_ccsid(curl_mimepart *part, + const char *filename, unsigned int ccsid) +{ + return mime_string_call(part, filename, ccsid, curl_mime_filedata); +} + +CURLcode +curl_mime_data_ccsid(curl_mimepart *part, + const char *data, size_t datasize, unsigned int ccsid) +{ + char *s = (char *) NULL; + CURLcode result; + + if(!data) + return curl_mime_data(part, data, datasize); + s = dynconvert(ASCII_CCSID, data, datasize, ccsid); + if(!s) + return CURLE_OUT_OF_MEMORY; + + result = curl_mime_data(part, s, datasize); + free(s); + return result; +} + +CURLUcode +curl_url_get_ccsid(CURLU *handle, CURLUPart what, char **part, + unsigned int flags, unsigned int ccsid) +{ + char *s = (char *)NULL; + CURLUcode result; + + if(!part) + return CURLUE_BAD_PARTPOINTER; + + *part = (char *)NULL; + result = curl_url_get(handle, what, &s, flags); + if(result == CURLUE_OK) { + if(s) { + *part = dynconvert(ccsid, s, -1, ASCII_CCSID); + if(!*part) + result = CURLUE_OUT_OF_MEMORY; + } + } + if(s) + free(s); + return result; +} + +CURLUcode +curl_url_set_ccsid(CURLU *handle, CURLUPart what, const char *part, + unsigned int flags, unsigned int ccsid) +{ + char *s = (char *)NULL; + CURLUcode result; + + if(part) { + s = dynconvert(ASCII_CCSID, part, -1, ccsid); + if(!s) + return CURLUE_OUT_OF_MEMORY; + } + result = curl_url_set(handle, what, s, flags); + if(s) + free(s); + return result; +} + +const struct curl_easyoption * +curl_easy_option_by_name_ccsid(const char *name, unsigned int ccsid) +{ + const struct curl_easyoption *option = NULL; + + if(name) { + char *s = dynconvert(ASCII_CCSID, name, -1, ccsid); + + if(s) { + option = curl_easy_option_by_name(s); + free(s); + } + } + + return option; +} + +/* Return option name in the given ccsid. */ +const char * +curl_easy_option_get_name_ccsid(const struct curl_easyoption *option, + unsigned int ccsid) +{ + char *name = NULL; + + if(option && option->name) + name = dynconvert(ccsid, option->name, -1, ASCII_CCSID); + + return (const char *) name; +} + +/* Header API CCSID support. */ +CURLHcode +curl_easy_header_ccsid(CURL *easy, const char *name, size_t index, + unsigned int origin, int request, + struct curl_header **hout, unsigned int ccsid) +{ + CURLHcode result = CURLHE_BAD_ARGUMENT; + + if(name) { + char *s = dynconvert(ASCII_CCSID, name, -1, ccsid); + + result = CURLHE_OUT_OF_MEMORY; + if(s) { + result = curl_easy_header(easy, s, index, origin, request, hout); + free(s); + } + } + + return result; +} diff --git a/third_party/curl/packages/OS400/ccsidcurl.h b/third_party/curl/packages/OS400/ccsidcurl.h new file mode 100644 index 0000000..ab01d32 --- /dev/null +++ b/third_party/curl/packages/OS400/ccsidcurl.h @@ -0,0 +1,113 @@ +#ifndef CURLINC_CCSIDCURL_H +#define CURLINC_CCSIDCURL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * + ***************************************************************************/ +#include "curl.h" +#include "easy.h" +#include "multi.h" + + +CURL_EXTERN char *curl_version_ccsid(unsigned int ccsid); +CURL_EXTERN char *curl_easy_escape_ccsid(CURL *handle, + const char *string, int length, + unsigned int sccsid, + unsigned int dccsid); +CURL_EXTERN char *curl_easy_unescape_ccsid(CURL *handle, const char *string, + int length, int *outlength, + unsigned int sccsid, + unsigned int dccsid); +CURL_EXTERN struct curl_slist *curl_slist_append_ccsid(struct curl_slist *l, + const char *data, + unsigned int ccsid); +CURL_EXTERN time_t curl_getdate_ccsid(const char *p, const time_t *unused, + unsigned int ccsid); +CURL_EXTERN curl_version_info_data *curl_version_info_ccsid(CURLversion stamp, + unsigned int cid); +CURL_EXTERN const char *curl_easy_strerror_ccsid(CURLcode error, + unsigned int ccsid); +CURL_EXTERN const char *curl_share_strerror_ccsid(CURLSHcode error, + unsigned int ccsid); +CURL_EXTERN const char *curl_multi_strerror_ccsid(CURLMcode error, + unsigned int ccsid); +CURL_EXTERN CURLcode curl_easy_getinfo_ccsid(CURL *curl, CURLINFO info, ...); +CURL_EXTERN CURLFORMcode curl_formadd_ccsid(struct curl_httppost **httppost, + struct curl_httppost **last_post, + ...); +CURL_EXTERN char *curl_form_long_value(long value); +CURL_EXTERN int curl_formget_ccsid(struct curl_httppost *form, void *arg, + curl_formget_callback append, + unsigned int ccsid); +CURL_EXTERN CURLcode curl_easy_setopt_ccsid(CURL *curl, CURLoption tag, ...); +CURL_EXTERN void curl_certinfo_free_all(struct curl_certinfo *info); +CURL_EXTERN char *curl_pushheader_bynum_cssid(struct curl_pushheaders *h, + size_t num, unsigned int ccsid); +CURL_EXTERN char *curl_pushheader_byname_ccsid(struct curl_pushheaders *h, + const char *header, + unsigned int ccsidin, + unsigned int ccsidout); +CURL_EXTERN CURLcode curl_mime_name_ccsid(curl_mimepart *part, + const char *name, + unsigned int ccsid); +CURL_EXTERN CURLcode curl_mime_filename_ccsid(curl_mimepart *part, + const char *filename, + unsigned int ccsid); +CURL_EXTERN CURLcode curl_mime_type_ccsid(curl_mimepart *part, + const char *mimetype, + unsigned int ccsid); +CURL_EXTERN CURLcode curl_mime_encoder_ccsid(curl_mimepart *part, + const char *encoding, + unsigned int ccsid); +CURL_EXTERN CURLcode curl_mime_filedata_ccsid(curl_mimepart *part, + const char *filename, + unsigned int ccsid); +CURL_EXTERN CURLcode curl_mime_data_ccsid(curl_mimepart *part, + const char *data, size_t datasize, + unsigned int ccsid); +CURL_EXTERN CURLUcode curl_url_get_ccsid(CURLU *handle, CURLUPart what, + char **part, unsigned int flags, + unsigned int ccsid); +CURL_EXTERN CURLUcode curl_url_set_ccsid(CURLU *handle, CURLUPart what, + const char *part, unsigned int flags, + unsigned int ccsid); +CURL_EXTERN const struct curl_easyoption *curl_easy_option_by_name_ccsid( + const char *name, unsigned int ccsid); +CURL_EXTERN const char *curl_easy_option_get_name_ccsid( + const struct curl_easyoption *option, + unsigned int ccsid); +CURL_EXTERN const char *curl_url_strerror_ccsid(CURLUcode error, + unsigned int ccsid); +CURL_EXTERN CURLHcode curl_easy_header_ccsid(CURL *easy, const char *name, + size_t index, unsigned int origin, + int request, + struct curl_header **hout, + unsigned int ccsid); +CURL_EXTERN const char *curl_from_ccsid(const char *s, unsigned int ccsid); +CURL_EXTERN const char *curl_to_ccsid(const char *s, unsigned int ccsid); +CURL_EXTERN CURLcode curl_easy_setopt_RPGnum_(CURL *easy, + CURLoption tag, curl_off_t arg); +CURL_EXTERN CURLcode curl_multi_setopt_RPGnum_(CURLM *multi, CURLMoption tag, + curl_off_t arg); + +#endif diff --git a/third_party/curl/packages/OS400/config400.default b/third_party/curl/packages/OS400/config400.default new file mode 100644 index 0000000..91a8277 --- /dev/null +++ b/third_party/curl/packages/OS400/config400.default @@ -0,0 +1,55 @@ +#!/bin/sh +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +# Tunable configuration parameters. + +setenv TARGETLIB 'CURL' # Target OS/400 program library. +setenv STATBNDDIR 'CURL_A' # Static binding directory. +setenv DYNBNDDIR 'CURL' # Dynamic binding directory. +setenv SRVPGM "CURL.${SONAME}" # Service program. +setenv CURLPGM 'CURL' # CLI tool bound program. +setenv CURLCMD 'CURL' # CL command name. +setenv CURLCLI 'CURLCL' # CL interface program. +setenv TGTCCSID '500' # Target CCSID of objects. +setenv DEBUG '*ALL' # Debug level. +setenv OPTIMIZE '10' # Optimization level +setenv OUTPUT '*NONE' # Compilation output option. +setenv TGTRLS '*CURRENT' # Target OS release. +setenv IFSDIR '/curl' # Installation IFS directory. +setenv QADRTDIR '/QIBM/ProdData/qadrt' # QADRT IFS directory. + +# Define ZLIB availability and locations. + +setenv WITH_ZLIB 0 # Define to 1 to enable. +setenv ZLIB_INCLUDE '/zlib/include' # ZLIB include IFS directory. +setenv ZLIB_LIB 'ZLIB' # ZLIB library. +setenv ZLIB_BNDDIR 'ZLIB_A' # ZLIB binding directory. + +# Define LIBSSH2 availability and locations. + +setenv WITH_LIBSSH2 0 # Define to 1 to enable. +setenv LIBSSH2_INCLUDE '/libssh2/include' # LIBSSH2 include IFS directory. +setenv LIBSSH2_LIB 'LIBSSH2' # LIBSSH2 library. +setenv LIBSSH2_BNDDIR 'LIBSSH2_A' # LIBSSH2 binding directory. diff --git a/third_party/curl/packages/OS400/curl.cmd b/third_party/curl/packages/OS400/curl.cmd new file mode 100644 index 0000000..822f4db --- /dev/null +++ b/third_party/curl/packages/OS400/curl.cmd @@ -0,0 +1,32 @@ +/*****************************************************************************/ +/* _ _ ____ _ */ +/* Project ___| | | | _ \| | */ +/* / __| | | | |_) | | */ +/* | (__| |_| | _ <| |___ */ +/* \___|\___/|_| \_\_____| */ +/* */ +/* Copyright (C) Daniel Stenberg, , 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. */ +/* */ +/* SPDX-License-Identifier: curl */ +/* */ +/* */ +/*****************************************************************************/ + +/* Use program CURLCL as interface to the curl command line tool */ + + CMD PROMPT('File transfer utility') + + PARM KWD(CMDARGS) TYPE(*CHAR) LEN(5000) VARY(*YES *INT2) + + CASE(*MIXED) EXPR(*YES) MIN(1) + + PROMPT('Curl command arguments') diff --git a/third_party/curl/packages/OS400/curl.inc.in b/third_party/curl/packages/OS400/curl.inc.in new file mode 100644 index 0000000..915ece6 --- /dev/null +++ b/third_party/curl/packages/OS400/curl.inc.in @@ -0,0 +1,3444 @@ + ************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * + ************************************************************************** + * + /if not defined(CURL_CURL_INC_) + /define CURL_CURL_INC_ + * + * WARNING: this file should be kept in sync with C include files. + * + ************************************************************************** + * Constants + ************************************************************************** + * + d LIBCURL_VERSION... + d c '@LIBCURL_VERSION@' + d LIBCURL_VERSION_MAJOR... + d c @LIBCURL_VERSION_MAJOR@ + d LIBCURL_VERSION_MINOR... + d c @LIBCURL_VERSION_MINOR@ + d LIBCURL_VERSION_PATCH... + d c @LIBCURL_VERSION_PATCH@ + d LIBCURL_VERSION_NUM... + d c X'00@LIBCURL_VERSION_NUM@' + d LIBCURL_TIMESTAMP... + d c '@LIBCURL_TIMESTAMP@' + * + d CURL_SOCKET_BAD... + d c -1 + d CURL_SOCKET_TIMEOUT... + d c -1 + * + /if not defined(CURL_MAX_WRITE_SIZE) + /define CURL_MAX_WRITE_SIZE + d CURL_MAX_WRITE_SIZE... + d c 16384 + /endif + * + /if not defined(CURL_MAX_HTTP_HEADER) + /define CURL_MAX_HTTP_HEADER + d CURL_MAX_HTTP_HEADER... + d c 102400 + /endif + * + d CURLINFO_STRING... + d c X'00100000' + d CURLINFO_LONG c X'00200000' + d CURLINFO_DOUBLE... + d c X'00300000' + d CURLINFO_SLIST c X'00400000' + d CURLINFO_PTR c X'00400000' + d CURLINFO_SOCKET... + d c X'00500000' + d CURLINFO_OFF_T... + d c X'00600000' + d CURLINFO_MASK c X'000FFFFF' + d CURLINFO_TYPEMASK... + d c X'00F00000' + * + d CURL_GLOBAL_SSL... + d c X'00000001' + d CURL_GLOBAL_WIN32... + d c X'00000002' + d CURL_GLOBAL_ALL... + d c X'00000003' + d CURL_GLOBAL_NOTHING... + d c X'00000000' + d CURL_GLOBAL_DEFAULT... + d c X'00000003' + d CURL_GLOBAL_ACK_EINTR... + d c X'00000004' + * + d CURL_VERSION_IPV6... + d c X'00000001' + d CURL_VERSION_KERBEROS4... + d c X'00000002' + d CURL_VERSION_SSL... + d c X'00000004' + d CURL_VERSION_LIBZ... + d c X'00000008' + d CURL_VERSION_NTLM... + d c X'00000010' + d CURL_VERSION_GSSNEGOTIATE... + d c X'00000020' Deprecated + d CURL_VERSION_DEBUG... + d c X'00000040' + d CURL_VERSION_ASYNCHDNS... + d c X'00000080' + d CURL_VERSION_SPNEGO... + d c X'00000100' + d CURL_VERSION_LARGEFILE... + d c X'00000200' + d CURL_VERSION_IDN... + d c X'00000400' + d CURL_VERSION_SSPI... + d c X'00000800' + d CURL_VERSION_CONV... + d c X'00001000' + d CURL_VERSION_CURLDEBUG... + d c X'00002000' + d CURL_VERSION_TLSAUTH_SRP... + d c X'00004000' + d CURL_VERSION_NTLM_WB... + d c X'00008000' + d CURL_VERSION_HTTP2... + d c X'00010000' + d CURL_VERSION_GSSAPI... + d c X'00020000' + d CURL_VERSION_KERBEROS5... + d c X'00040000' + d CURL_VERSION_UNIX_SOCKETS... + d c X'00080000' + d CURL_VERSION_PSL... + d c X'00100000' + d CURL_VERSION_HTTPS_PROXY... + d c X'00200000' + d CURL_VERSION_MULTI_SSL... + d c X'00400000' + d CURL_VERSION_BROTLI... + d c X'00800000' + d CURL_VERSION_ALTSVC... + d c X'01000000' + d CURL_VERSION_HTTP3... + d c X'02000000' + d CURL_VERSION_ZSTD... + d c X'04000000' + d CURL_VERSION_UNICODE... + d c X'08000000' + d CURL_VERSION_HSTS... + d c X'10000000' + d CURL_VERSION_GSASL... + d c X'20000000' + d CURL_VERSION_THREADSAFE... + d c X'40000000' + * + d CURL_HTTPPOST_FILENAME... + d c X'00000001' + d CURL_HTTPPOST_READFILE... + d c X'00000002' + d CURL_HTTPPOST_PTRNAME... + d c X'00000004' + d CURL_HTTPPOST_PTRCONTENTS... + d c X'00000008' + d CURL_HTTPPOST_BUFFER... + d c X'00000010' + d CURL_HTTPPOST_PTRBUFFER... + d c X'00000020' + d CURL_HTTPPOST_CALLBACK... + d c X'00000040' + d CURL_HTTPPOST_LARGE... + d c X'00000080' + * + d CURL_SEEKFUNC_OK... + d c 0 + d CURL_SEEKFUNC_FAIL... + d c 1 + d CURL_SEEKFUNC_CANTSEEK... + d c 2 + * + d CURL_READFUNC_ABORT... + d c X'10000000' + d CURL_READFUNC_PAUSE... + d c X'10000001' + * + d CURL_WRITEFUNC_PAUSE... + d c X'10000001' + d CURL_WRITEFUNC_ERROR... + d c X'FFFFFFFF' + * + d CURL_TRAILERFUNC_OK... + d c 0 + d CURL_TRAILERFUNC_ABORT... + d c 1 + * + d CURL_PREREQFUNC_OK... + d c 0 + d CURL_PREREQFUNC_ABORT... + d c 1 + * + d CURLAUTH_NONE c X'00000000' + d CURLAUTH_BASIC c X'00000001' + d CURLAUTH_DIGEST... + d c X'00000002' + d CURLAUTH_NEGOTIATE... + d c X'00000004' + d CURLAUTH_NTLM c X'00000008' + d CURLAUTH_DIGEST_IE... + d c X'00000010' + /if not defined(CURL_NO_OLDIES) + d CURLAUTH_NTLM_WB... + d c X'00000020' + /endif + d CURLAUTH_BEARER... + d c X'00000040' + d CURLAUTH_AWS_SIGV4... + d c X'00000080' + d CURLAUTH_ONLY... + d c X'80000000' + d CURLAUTH_ANY c X'7FFFFFEF' + d CURLAUTH_ANYSAFE... + d c X'7FFFFFEE' + * + d CURLSSH_AUTH_ANY... + d c X'7FFFFFFF' + d CURLSSH_AUTH_NONE... + d c X'00000000' + d CURLSSH_AUTH_PUBLICKEY... + d c X'00000001' + d CURLSSH_AUTH_PASSWORD... + d c X'00000002' + d CURLSSH_AUTH_HOST... + d c X'00000004' + d CURLSSH_AUTH_KEYBOARD... + d c X'00000008' + d CURLSSH_AUTH_AGENT... + d c X'00000010' + d CURLSSH_AUTH_DEFAULT... + d c X'7FFFFFFF' CURLSSH_AUTH_ANY + * + d CURLGSSAPI_DELEGATION_NONE... + d c 0 + d CURLGSSAPI_DELEGATION_POLICY_FLAG... + d c X'00000001' + d CURLGSSAPI_DELEGATION_FLAG... + d c X'00000002' + * + d CURL_ERROR_SIZE... + d c 256 + * + d CURLOPTTYPE_LONG... + d c 0 + d CURLOPTTYPE_VALUES... + d c 0 + d CURLOPTTYPE_OBJECTPOINT... + d c 10000 + d CURLOPTTYPE_STRINGPOINT... + d c 10000 + d CURLOPTTYPE_SLISTPOINT... + d c 10000 + d CURLOPTTYPE_CBPOINT... + d c 10000 + d CURLOPTTYPE_FUNCTIONPOINT... + d c 20000 + d CURLOPTTYPE_OFF_T... + d c 30000 + d CURLOPTTYPE_BLOB... + d c 40000 + * + d CURL_IPRESOLVE_WHATEVER... + d c 0 + d CURL_IPRESOLVE_V4... + d c 1 + d CURL_IPRESOLVE_V6... + d c 2 + * + d CURL_HTTP_VERSION_NONE... + d c 0 + d CURL_HTTP_VERSION_1_0... + d c 1 + d CURL_HTTP_VERSION_1_1... + d c 2 + d CURL_HTTP_VERSION_2_0... + d c 3 + d CURL_HTTP_VERSION_2... + d c 3 + d CURL_HTTP_VERSION_2TLS... + d c 4 + d CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE... + d c 5 + d CURL_HTTP_VERSION_3... + d c 30 + d CURL_HTTP_VERSION_3ONLY... + d c 31 + * + d CURL_NETRC_IGNORED... + d c 0 + d CURL_NETRC_OPTIONAL... + d c 1 + d CURL_NETRC_REQUIRED... + d c 2 + * + d CURL_SSLVERSION_DEFAULT... + d c 0 + d CURL_SSLVERSION_TLSv1... + d c 1 + d CURL_SSLVERSION_SSLv2... + d c 2 + d CURL_SSLVERSION_SSLv3... + d c 3 + d CURL_SSLVERSION_TLSv1_0... + d c 4 + d CURL_SSLVERSION_TLSv1_1... + d c 5 + d CURL_SSLVERSION_TLSv1_2... + d c 6 + d CURL_SSLVERSION_TLSv1_3... + d c 7 + d CURL_SSLVERSION_MAX_DEFAULT... + d c X'00010000' + d CURL_SSLVERSION_MAX_TLSv1_0... + d c X'00040000' + d CURL_SSLVERSION_MAX_TLSv1_1... + d c X'00050000' + d CURL_SSLVERSION_MAX_TLSv1_2... + d c X'00060000' + d CURL_SSLVERSION_MAX_TLSv1_3... + d c X'00070000' + * + d CURL_TLSAUTH_NONE... + d c 0 + d CURL_TLSAUTH_SRP... + d c 1 + * + d CURL_REDIR_GET_ALL... + d c 0 + d CURL_REDIR_POST_301... + d c 1 + d CURL_REDIR_POST_302... + d c 2 + d CURL_REDIR_POST_303... + d c 4 + d CURL_REDIR_POST_ALL... + d c 7 + * + d CURL_ZERO_TERMINATED... + d c X'FFFFFFFF' + * + d CURL_POLL_NONE c 0 + d CURL_POLL_IN c 1 + d CURL_POLL_OUT c 2 + d CURL_POLL_INOUT... + d c 3 + d CURL_POLL_REMOVE... + d c 4 + * + d CURL_BLOB_NOCOPY... + d c 0 + d CURL_BLOB_COPY c 1 + * + d CURL_CSELECT_IN... + d c X'00000001' + d CURL_CSELECT_OUT... + d c X'00000002' + d CURL_CSELECT_ERR... + d c X'00000004' + * + d CURL_PUSH_OK c 0 + d CURL_PUSH_DENY c 1 + * + d CURLPAUSE_RECV c X'00000001' + d CURLPAUSE_RECV_CONT... + d c X'00000000' + d CURLPAUSE_SEND c X'00000004' + d CURLPAUSE_SEND_CONT... + d c X'00000000' + d CURLPAUSE_ALL c X'00000005' + d CURLPAUSE_CONT c X'00000000' + * + d CURLINFOFLAG_KNOWN_FILENAME... + d c X'00000001' + d CURLINFOFLAG_KNOWN_FILETYPE... + d c X'00000002' + d CURLINFOFLAG_KNOWN_TIME... + d c X'00000004' + d CURLINFOFLAG_KNOWN_PERM... + d c X'00000008' + d CURLINFOFLAG_KNOWN_UID... + d c X'00000010' + d CURLINFOFLAG_KNOWN_GID... + d c X'00000020' + d CURLINFOFLAG_KNOWN_SIZE... + d c X'00000040' + d CURLINFOFLAG_KNOWN_HLINKCOUNT... + d c X'00000080' + * + d CURL_CHUNK_BGN_FUNC_OK... + d c 0 + d CURL_CHUNK_BGN_FUNC_FAIL... + d c 1 + d CURL_CHUNK_BGN_FUNC_SKIP... + d c 2 + * + d CURL_CHUNK_END_FUNC_OK... + d c 0 + d CURL_CHUNK_END_FUNC_FAIL... + d c 1 + * + d CURL_FNMATCHFUNC_MATCH... + d c 0 + d CURL_FNMATCHFUNC_NOMATCH... + d c 1 + d CURL_FNMATCHFUNC_FAIL... + d c 2 + * + d CURL_WAIT_POLLIN... + d c X'0001' + d CURL_WAIT_POLLPRI... + d c X'0002' + d CURL_WAIT_POLLOUT... + d c X'0004' + * + d CURLU_DEFAULT_PORT... + d c X'00000001' + d CURLU_NO_DEFAULT_PORT... + d c X'00000002' + d CURLU_DEFAULT_SCHEME... + d c X'00000004' + d CURLU_NON_SUPPORT_SCHEME... + d c X'00000008' + d CURLU_PATH_AS_IS... + d c X'00000010' + d CURLU_DISALLOW_USER... + d c X'00000020' + d CURLU_URLDECODE... + d c X'00000040' + d CURLU_URLENCODE... + d c X'00000080' + d CURLU_APPENDQUERY... + d c X'00000100' + d CURLU_GUESS_SCHEME... + d c X'00000200' + d CURLU_NO_AUTHORITY... + d c X'00000400' + d CURLU_ALLOW_SPACE... + d c X'00000800' + d CURLU_PUNYCODE... + d c X'00001000' + * + d CURLOT_FLAG_ALIAS... + d c X'00000001' + * + d CURLH_HEADER c X'00000001' + d CURLH_TRAILER c X'00000002' + d CURLH_CONNECT c X'00000004' + d CURLH_1XX c X'00000008' + d CURLH_PSEUDO c X'00000010' + * + d CURLWS_TEXT c X'00000001' + d CURLWS_BINARY c X'00000002' + d CURLWS_CONT c X'00000004' + d CURLWS_CLOSE c X'00000008' + d CURLWS_PING c X'00000010' + d CURLWS_OFFSET c X'00000020' + d CURLWS_PONG c X'00000040' + * + d CURLWS_RAW_MODE... + d c X'00000001' + * + ************************************************************************** + * Types + ************************************************************************** + * + d curl_socket_t s 10i 0 based(######ptr######) + * + d curl_off_t s 20i 0 based(######ptr######) + * + d CURLcode s 10i 0 based(######ptr######) Enum + d CURLE_OK c 0 + d CURLE_UNSUPPORTED_PROTOCOL... + d c 1 + d CURLE_FAILED_INIT... + d c 2 + d CURLE_URL_MALFORMAT... + d c 3 + d CURLE_NOT_BUILT_IN... + d c 4 + d CURLE_COULDNT_RESOLVE_PROXY... + d c 5 + d CURLE_COULDNT_RESOLVE_HOST... + d c 6 + d CURLE_COULDNT_CONNECT... + d c 7 + d CURLE_WEIRD_SERVER_REPLY... + d c 8 + d CURLE_REMOTE_ACCESS_DENIED... + d c 9 + d CURLE_FTP_ACCEPT_FAILED... + d c 10 + d CURLE_FTP_WEIRD_PASS_REPLY... + d c 11 + d CURLE_FTP_ACCEPT_TIMEOUT... + d c 12 + d CURLE_FTP_WEIRD_PASV_REPLY... + d c 13 + d CURLE_FTP_WEIRD_227_FORMAT... + d c 14 + d CURLE_FTP_CANT_GET_HOST... + d c 15 + d CURLE_HTTP2 c 16 + d CURLE_FTP_COULDNT_SET_TYPE... + d c 17 + d CURLE_PARTIAL_FILE... + d c 18 + d CURLE_FTP_COULDNT_RETR_FILE... + d c 19 + d CURLE_OBSOLETE20... + d c 20 + d CURLE_QUOTE_ERROR... + d c 21 + d CURLE_HTTP_RETURNED_ERROR... + d c 22 + d CURLE_WRITE_ERROR... + d c 23 + d CURLE_OBSOLETE24... + d c 24 + d CURLE_UPLOAD_FAILED... + d c 25 + d CURLE_READ_ERROR... + d c 26 + d CURLE_OUT_OF_MEMORY... + d c 27 + d CURLE_OPERATION_TIMEDOUT... + d c 28 + d CURLE_OBSOLETE29... + d c 29 + d CURLE_FTP_PORT_FAILED... + d c 30 + d CURLE_FTP_COULDNT_USE_REST... + d c 31 + d CURLE_OBSOLETE32... + d c 32 + d CURLE_RANGE_ERROR... + d c 33 + d CURLE_HTTP_POST_ERROR... + d c 34 + d CURLE_SSL_CONNECT_ERROR... + d c 35 + d CURLE_BAD_DOWNLOAD_RESUME... + d c 36 + d CURLE_FILE_COULDNT_READ_FILE... + d c 37 + d CURLE_LDAP_CANNOT_BIND... + d c 38 + d CURLE_LDAP_SEARCH_FAILED... + d c 39 + d CURLE_OBSOLETE40... + d c 40 + d CURLE_FUNCTION_NOT_FOUND... + d c 41 + d CURLE_ABORTED_BY_CALLBACK... + d c 42 + d CURLE_BAD_FUNCTION_ARGUMENT... + d c 43 + d CURLE_OBSOLETE44... + d c 44 + d CURLE_INTERFACE_FAILED... + d c 45 + d CURLE_OBSOLETE46... + d c 46 + d CURLE_TOO_MANY_REDIRECTS... + d c 47 + d CURLE_UNKNOWN_OPTION... + d c 48 + d CURLE_SETOPT_OPTION_SYNTAX... + d c 49 + d CURLE_OBSOLETE50... + d c 50 + d CURLE_OBSOLETE51... + d c 51 + d CURLE_GOT_NOTHING... + d c 52 + d CURLE_SSL_ENGINE_NOTFOUND... + d c 53 + d CURLE_SSL_ENGINE_SETFAILED... + d c 54 + d CURLE_SEND_ERROR... + d c 55 + d CURLE_RECV_ERROR... + d c 56 + d CURLE_OBSOLETE57... + d c 57 + d CURLE_SSL_CERTPROBLEM... + d c 58 + d CURLE_SSL_CIPHER... + d c 59 + d CURLE_PEER_FAILED_VERIFICATION... + d c 60 + d CURLE_BAD_CONTENT_ENCODING... + d c 61 + d CURLE_OBSOLETE62... + d c 62 + d CURLE_FILESIZE_EXCEEDED... + d c 63 + d CURLE_USE_SSL_FAILED... + d c 64 + d CURLE_SEND_FAIL_REWIND... + d c 65 + d CURLE_SSL_ENGINE_INITFAILED... + d c 66 + d CURLE_LOGIN_DENIED... + d c 67 + d CURLE_TFTP_NOTFOUND... + d c 68 + d CURLE_TFTP_PERM... + d c 69 + d CURLE_REMOTE_DISK_FULL... + d c 70 + d CURLE_TFTP_ILLEGAL... + d c 71 + d CURLE_TFTP_UNKNOWNID... + d c 72 + d CURLE_REMOTE_FILE_EXISTS... + d c 73 + d CURLE_TFTP_NOSUCHUSER... + d c 74 + d CURLE_OBSOLETE75... + d c 75 + d CURLE_OBSOLETE76... + d c 76 + d CURLE_SSL_CACERT_BADFILE... + d c 77 + d CURLE_REMOTE_FILE_NOT_FOUND... + d c 78 + d CURLE_SSH c 79 + d CURLE_SSL_SHUTDOWN_FAILED... + d c 80 + d CURLE_AGAIN c 81 + d CURLE_SSL_CRL_BADFILE... + d c 82 + d CURLE_SSL_ISSUER_ERROR... + d c 83 + d CURLE_FTP_PRET_FAILED... + d c 84 + d CURLE_RTSP_CSEQ_ERROR... + d c 85 + d CURLE_RTSP_SESSION_ERROR... + d c 86 + d CURLE_FTP_BAD_FILE_LIST... + d c 87 + d CURLE_CHUNK_FAILED... + d c 88 + d CURLE_NO_CONNECTION_AVAILABLE... + d c 89 + d CURLE_SSL_PINNEDPUBKEYNOTMATCH... + d c 90 + d CURLE_SSL_INVALIDCERTSTATUS... + d c 91 + d CURLE_HTTP2_STREAM... + d c 92 + d CURLE_RECURSIVE_API_CALL... + d c 93 + d CURLE_AUTH_ERROR... + d c 94 + d CURLE_HTTP3 c 95 + d CURLE_QUIC_CONNECT_ERROR... + d c 96 + d CURLE_PROXY c 97 + d CURLE_SSL_CLIENTCERT... + d c 98 + d CURLE_UNRECOVERABLE_POLL... + d c 99 + d CURLE_TOO_LARGE... + d c 100 + d CURLE_ECH_REQUIRED... + d c 101 + * + /if not defined(CURL_NO_OLDIES) + d CURLE_URL_MALFORMAT_USER... + d c 4 + d CURLE_FTP_WEIRD_SERVER_REPLY... + d c 8 + d CURLE_FTP_ACCESS_DENIED... + d c 9 + d CURLE_FTP_USER_PASSWORD_INCORRECT... + d c 10 + d CURLE_FTP_WEIRD_USER_REPLY... + d c 12 + d CURLE_FTP_CANT_RECONNECT... + d c 16 + d CURLE_FTP_COULDNT_SET_BINARY... + d c 17 + d CURLE_FTP_PARTIAL_FILE... + d c 18 + d CURLE_FTP_WRITE_ERROR... + d c 20 + d CURLE_FTP_QUOTE_ERROR... + d c 21 + d CURLE_HTTP_NOT_FOUND... + d c 22 + d CURLE_MALFORMAT_USER... + d c 24 + d CURLE_FTP_COULDNT_STOR_FILE... + d c 25 + d CURLE_OPERATION_TIMEOUTED... + d c 28 + d CURLE_FTP_COULDNT_SET_ASCII... + d c 29 + d CURLE_FTP_COULDNT_GET_SIZE... + d c 32 + d CURLE_HTTP_RANGE_ERROR... + d c 33 + d CURLE_FTP_BAD_DOWNLOAD_RESUME... + d c 36 + d CURLE_LIBRARY_NOT_FOUND... + d c 40 + d CURLE_BAD_CALLING_ORDER... + d c 44 + d CURLE_HTTP_PORT_FAILED... + d c 45 + d CURLE_BAD_PASSWORD_ENTERED... + d c 46 + d CURLE_UNKNOWN_TELNET_OPTION... + d c 48 + d CURLE_TELNET_OPTION_SYNTAX... + d c 49 + d CURLE_OBSOLETE... + d c 50 + d CURLE_SHARE_IN_USE... + d c 57 + d CURLE_SSL_CACERT... + d c 60 + d CURLE_SSL_PEER_CERTIFICATE... + d c 60 + d CURLE_LDAP_INVALID_URL... + d c 62 + d CURLE_FTP_SSL_FAILED... + d c 64 + d CURLE_TFTP_DISKFULL... + d c 70 + d CURLE_TFTP_EXISTS... + d c 73 + d CURLE_CONV_FAILED... + d c 75 + d CURLE_CONV_REQD... + d c 76 + d CURLE_ALREADY_COMPLETE... + d c 99999 + /endif + * + d CURLproxycode s 10i 0 based(######ptr######) Enum + d CURLPX_OK c 0 + d CURLPX_BAD_ADDRESS_TYPE... + d c 1 + d CURLPX_BAD_VERSION... + d c 2 + d CURLPX_CLOSED... + d c 3 + d CURLPX_GSSAPI... + d c 4 + d CURLPX_GSSAPI_PERMSG... + d c 5 + d CURLPX_GSSAPI_PROTECTION... + d c 6 + d CURLPX_IDENTD... + d c 7 + d CURLPX_IDENTD_DIFFER... + d c 8 + d CURLPX_LONG_HOSTNAME... + d c 9 + d CURLPX_LONG_PASSWD... + d c 10 + d CURLPX_LONG_USER... + d c 11 + d CURLPX_NO_AUTH... + d c 12 + d CURLPX_RECV_ADDRESS... + d c 13 + d CURLPX_RECV_AUTH... + d c 14 + d CURLPX_RECV_CONNECT... + d c 15 + d CURLPX_RECV_REQACK... + d c 16 + d CURLPX_REPLY_ADDRESS_TYPE_NOT_SUPPORTED... + d c 17 + d CURLPX_REPLY_COMMAND_NOT_SUPPORTED... + d c 18 + d CURLPX_REPLY_CONNECTION_REFUSED... + d c 10 + d CURLPX_REPLY_GENERAL_SERVER_FAILURE... + d c 20 + d CURLPX_REPLY_HOST_UNREACHABLE... + d c 21 + d CURLPX_REPLY_NETWORK_UNREACHABLE... + d c 22 + d CURLPX_REPLY_NOT_ALLOWED... + d c 23 + d CURLPX_REPLY_TTL_EXPIRED... + d c 24 + d CURLPX_REPLY_UNASSIGNED... + d c 25 + d CURLPX_REQUEST_FAILED... + d c 26 + d CURLPX_RESOLVE_HOST... + d c 27 + d CURLPX_SEND_AUTH... + d c 28 + d CURLPX_SEND_CONNECT... + d c 29 + d CURLPX_SEND_REQUEST... + d c 30 + d CURLPX_UNKNOWN_FAIL... + d c 31 + d CURLPX_UNKNOWN_MODE... + d c 32 + d CURLPX_USER_REJECTED... + d c 33 + * + d curlioerr s 10i 0 based(######ptr######) Enum + d CURLIOE_OK c 0 + d CURLIOE_UNKNOWNCMD... + d c 1 + d CURLIOE_FAILRESTART... + d c 2 + * + d curlfiletype s 10i 0 based(######ptr######) Enum + d CURLFILETYPE_FILE... + d c 0 + d CURLFILETYPE_DIRECTORY... + d c 1 + d CURLFILETYPE_SYMLINK... + d c 2 + d CURLFILETYPE_DEVICE_BLOCK... + d c 3 + d CURLFILETYPE_DEVICE_CHAR... + d c 4 + d CURLFILETYPE_NAMEDPIPE... + d c 5 + d CURLFILETYPE_SOCKET... + d c 6 + d CURLFILETYPE_DOOR... + d c 7 + * + d curliocmd s 10i 0 based(######ptr######) Enum + d CURLIOCMD_NOP c 0 + d CURLIOCMD_RESTARTREAD... + d c 1 + * + d curl_infotype s 10i 0 based(######ptr######) Enum + d CURLINFO_TEXT... + d c 0 + d CURLINFO_HEADER_IN... + d c 1 + d CURLINFO_HEADER_OUT... + d c 2 + d CURLINFO_DATA_IN... + d c 3 + d CURLINFO_DATA_OUT... + d c 4 + d CURLINFO_SSL_DATA_IN... + d c 5 + d CURLINFO_SSL_DATA_OUT... + d c 6 + d CURLINFO_END... + d c 7 + * + d curl_proxytype s 10i 0 based(######ptr######) Enum + d CURLPROXY_HTTP... + d c 0 + d CURLPROXY_HTTP_1_0... + d c 1 + d CURLPROXY_HTTPS... + d c 2 + d CURLPROXY_HTTPS2... + d c 3 + d CURLPROXY_SOCKS4... + d c 4 + d CURLPROXY_SOCKS5... + d c 5 + d CURLPROXY_SOCKS4A... + d c 6 + d CURLPROXY_SOCKS5_HOSTNAME... + d c 7 + * + d curl_khstat s 10i 0 based(######ptr######) Enum + d CURLKHSTAT_FINE_ADD_TO_FILE... + d c 0 + d CURLKHSTAT_FINE... + d c 1 + d CURLKHSTAT_REJECT... + d c 2 + d CURLKHSTAT_DEFER... + d c 3 + d CURLKHSTAT_FINE_REPLACE... + d c 4 + d CURLKHSTAT_LAST... + d c 5 + * + d curl_khmatch s 10i 0 based(######ptr######) Enum + d CURLKHMATCH_OK... + d c 0 + d CURLKHMATCH_MISMATCH... + d c 1 + d CURLKHMATCH_MISSING... + d c 2 + d CURLKHMATCH_LAST... + d c 3 + * + d curl_usessl s 10i 0 based(######ptr######) Enum + d CURLUSESSL_NONE... + d c 0 + d CURLUSESSL_TRY... + d c 1 + d CURLUSESSL_CONTROL... + d c 2 + d CURLUSESSL_ALL... + d c 3 + * + d CURLSSLOPT_ALLOW_BEAST... + d c X'0001' + d CURLSSLOPT_NO_REVOKE... + d c X'0002' + d CURLSSLOPT_NO_PARTIALCHAIN... + d c X'0004' + d CURLSSLOPT_REVOKE_BEST_EFFORT... + d c X'0008' + d CURLSSLOPT_NATIVE_CA... + d c X'0010' + d CURLSSLOPT_AUTO_CLIENT_CERT... + d c X'0020' + * + d CURL_HET_DEFAULT... + d c 200 + * + d CURL_UPKEEP_INTERVAL_DEFAULT... + d c 60000 + * + /if not defined(CURL_NO_OLDIES) + d curl_ftpssl s like(curl_usessl) + d based(######ptr######) + d CURLFTPSSL_NONE... + d c 0 + d CURLFTPSSL_TRY... + d c 1 + d CURLFTPSSL_CONTROL... + d c 2 + d CURLFTPSSL_ALL... + d c 3 + /endif + * + d curl_ftpccc s 10i 0 based(######ptr######) Enum + d CURLFTPSSL_CCC_NONE... + d c 0 + d CURLFTPSSL_CCC_PASSIVE... + d c 1 + d CURLFTPSSL_CCC_ACTIVE... + d c 2 + * + d curl_ftpauth s 10i 0 based(######ptr######) Enum + d CURLFTPAUTH_DEFAULT... + d c 0 + d CURLFTPAUTH_SSL... + d c 1 + d CURLFTPAUTH_TLS... + d c 2 + * + d curl_ftpcreatedir... + d s 10i 0 based(######ptr######) Enum + d CURLFTP_CREATE_DIR_NONE... + d c 0 + d CURLFTP_CREATE_DIR... + d c 1 + d CURLFTP_CREATE_DIR_RETRY... + d c 2 + * + d curl_ftpmethod s 10i 0 based(######ptr######) Enum + d CURLFTPMETHOD_DEFAULT... + d c 0 + d CURLFTPMETHOD_MULTICWD... + d c 1 + d CURLFTPMETHOD_NOCWD... + d c 2 + d CURLFTPMETHOD_SINGLECWD... + d c 3 + * + d CURLHEADER_UNIFIED... + d c X'00000000' + d CURLHEADER_SEPARATE... + d c X'00000001' + * + d CURLALTSVC_READONLYFILE... + d c X'00000004' + d CURLALTSVC_H1... + d c X'00000008' + d CURLALTSVC_H2... + d c X'00000010' + d CURLALTSVC_H3... + d c X'00000020' + * + d CURLHSTS_ENABLE... + d c X'00000001' + d CURLHSTS_READONLYFILE... + d c X'00000002' + * + d CURLPROTO_HTTP... + d c X'00000001' + d CURLPROTO_HTTPS... + d c X'00000002' + d CURLPROTO_FTP... + d c X'00000004' + d CURLPROTO_FTPS... + d c X'00000008' + d CURLPROTO_SCP... + d c X'00000010' + d CURLPROTO_SFTP... + d c X'00000020' + d CURLPROTO_TELNET... + d c X'00000040' + d CURLPROTO_LDAP... + d c X'00000080' + d CURLPROTO_LDAPS... + d c X'00000100' + d CURLPROTO_DICT... + d c X'00000200' + d CURLPROTO_FILE... + d c X'00000400' + d CURLPROTO_TFTP... + d c X'00000800' + d CURLPROTO_IMAP... + d c X'00001000' + d CURLPROTO_IMAPS... + d c X'00002000' + d CURLPROTO_POP3... + d c X'00004000' + d CURLPROTO_POP3S... + d c X'00008000' + d CURLPROTO_SMTP... + d c X'00010000' + d CURLPROTO_SMTPS... + d c X'00020000' + d CURLPROTO_RTSP... + d c X'00040000' + d CURLPROTO_RTMP... + d c X'00080000' + d CURLPROTO_RTMPT... + d c X'00100000' + d CURLPROTO_RTMPTE... + d c X'00200000' + d CURLPROTO_RTMPE... + d c X'00400000' + d CURLPROTO_RTMPS... + d c X'00800000' + d CURLPROTO_RTMPTS... + d c X'01000000' + d CURLPROTO_GOPHER... + d c X'02000000' + d CURLPROTO_SMB... + d c X'04000000' + d CURLPROTO_SMBS... + d c X'08000000' + d CURLPROTO_MQTT... + d c X'10000000' + d CURLPROTO_GOPHERS... + d c X'20000000' + * + d CURLoption s 10i 0 based(######ptr######) Enum + d CURLOPT_WRITEDATA... + d c 10001 + d CURLOPT_URL c 10002 + d CURLOPT_PORT c 00003 + d CURLOPT_PROXY c 10004 + d CURLOPT_USERPWD... + d c 10005 + d CURLOPT_PROXYUSERPWD... + d c 10006 + d CURLOPT_RANGE c 10007 + d CURLOPT_READDATA... + d c 10009 + d CURLOPT_ERRORBUFFER... + d c 10010 + d CURLOPT_WRITEFUNCTION... + d c 20011 + d CURLOPT_READFUNCTION... + d c 20012 + d CURLOPT_TIMEOUT... + d c 00013 + d CURLOPT_INFILESIZE... + d c 00014 + d CURLOPT_POSTFIELDS... + d c 10015 + d CURLOPT_REFERER... + d c 10016 + d CURLOPT_FTPPORT... + d c 10017 + d CURLOPT_USERAGENT... + d c 10018 + d CURLOPT_LOW_SPEED_LIMIT... + d c 00019 + d CURLOPT_LOW_SPEED_TIME... + d c 00020 + d CURLOPT_RESUME_FROM... + d c 00021 + d CURLOPT_COOKIE... + d c 10022 + d CURLOPT_HTTPHEADER... + d c 10023 + d CURLOPT_RTSPHEADER... + d c 10023 + d CURLOPT_HTTPPOST... + d c 10024 + d CURLOPT_SSLCERT... + d c 10025 + d CURLOPT_KEYPASSWD... + d c 10026 + d CURLOPT_CRLF c 00027 + d CURLOPT_QUOTE c 10028 + d CURLOPT_HEADERDATA... + d c 10029 + d CURLOPT_COOKIEFILE... + d c 10031 + d CURLOPT_SSLVERSION... + d c 00032 + d CURLOPT_TIMECONDITION... + d c 00033 + d CURLOPT_TIMEVALUE... + d c 00034 + d CURLOPT_CUSTOMREQUEST... + d c 10036 + d CURLOPT_STDERR... + d c 10037 + d CURLOPT_POSTQUOTE... + d c 10039 + d CURLOPT_VERBOSE... + d c 00041 + d CURLOPT_HEADER... + d c 00042 + d CURLOPT_NOPROGRESS... + d c 00043 + d CURLOPT_NOBODY... + d c 00044 + d CURLOPT_FAILONERROR... + d c 00045 + d CURLOPT_UPLOAD... + d c 00046 + d CURLOPT_POST c 00047 + d CURLOPT_DIRLISTONLY... + d c 00048 + d CURLOPT_APPEND... + d c 00050 + d CURLOPT_NETRC c 00051 + d CURLOPT_FOLLOWLOCATION... + d c 00052 + d CURLOPT_TRANSFERTEXT... + d c 00053 + d CURLOPT_PUT c 00054 + d CURLOPT_PROGRESSFUNCTION... + d c 20056 + d CURLOPT_PROGRESSDATA... + d c 10057 + d CURLOPT_XFERINFODATA... + d c 10057 PROGRESSDATA alias + d CURLOPT_AUTOREFERER... + d c 00058 + d CURLOPT_PROXYPORT... + d c 00059 + d CURLOPT_POSTFIELDSIZE... + d c 00060 + d CURLOPT_HTTPPROXYTUNNEL... + d c 00061 + d CURLOPT_INTERFACE... + d c 10062 + d CURLOPT_KRBLEVEL... + d c 10063 + d CURLOPT_SSL_VERIFYPEER... + d c 00064 + d CURLOPT_CAINFO... + d c 10065 + d CURLOPT_MAXREDIRS... + d c 00068 + d CURLOPT_FILETIME... + d c 00069 + d CURLOPT_TELNETOPTIONS... + d c 10070 + d CURLOPT_MAXCONNECTS... + d c 00071 + d CURLOPT_FRESH_CONNECT... + d c 00074 + d CURLOPT_FORBID_REUSE... + d c 00075 + d CURLOPT_RANDOM_FILE... + d c 10076 + d CURLOPT_EGDSOCKET... + d c 10077 + d CURLOPT_CONNECTTIMEOUT... + d c 00078 + d CURLOPT_HEADERFUNCTION... + d c 20079 + d CURLOPT_HTTPGET... + d c 00080 + d CURLOPT_SSL_VERIFYHOST... + d c 00081 + d CURLOPT_COOKIEJAR... + d c 10082 + d CURLOPT_SSL_CIPHER_LIST... + d c 10083 + d CURLOPT_HTTP_VERSION... + d c 00084 + d CURLOPT_FTP_USE_EPSV... + d c 00085 + d CURLOPT_SSLCERTTYPE... + d c 10086 + d CURLOPT_SSLKEY... + d c 10087 + d CURLOPT_SSLKEYTYPE... + d c 10088 + d CURLOPT_SSLENGINE... + d c 10089 + d CURLOPT_SSLENGINE_DEFAULT... + d c 00090 + d CURLOPT_DNS_USE_GLOBAL_CACHE... + d c 00091 + d CURLOPT_DNS_CACHE_TIMEOUT... + d c 00092 + d CURLOPT_PREQUOTE... + d c 10093 + d CURLOPT_DEBUGFUNCTION... + d c 20094 + d CURLOPT_DEBUGDATA... + d c 10095 + d CURLOPT_COOKIESESSION... + d c 00096 + d CURLOPT_CAPATH... + d c 10097 + d CURLOPT_BUFFERSIZE... + d c 00098 + d CURLOPT_NOSIGNAL... + d c 00099 + d CURLOPT_SHARE c 10100 + d CURLOPT_PROXYTYPE... + d c 00101 + d CURLOPT_ACCEPT_ENCODING... + d c 10102 + d CURLOPT_PRIVATE... + d c 10103 + d CURLOPT_HTTP200ALIASES... + d c 10104 + d CURLOPT_UNRESTRICTED_AUTH... + d c 00105 + d CURLOPT_FTP_USE_EPRT... + d c 00106 + d CURLOPT_HTTPAUTH... + d c 00107 + d CURLOPT_SSL_CTX_FUNCTION... + d c 20108 + d CURLOPT_SSL_CTX_DATA... + d c 10109 + d CURLOPT_FTP_CREATE_MISSING_DIRS... + d c 00110 + d CURLOPT_PROXYAUTH... + d c 00111 + d CURLOPT_SERVER_RESPONSE_TIMEOUT... + d c 00112 + d CURLOPT_IPRESOLVE... + d c 00113 + d CURLOPT_MAXFILESIZE... + d c 00114 + d CURLOPT_INFILESIZE_LARGE... + d c 30115 + d CURLOPT_RESUME_FROM_LARGE... + d c 30116 + d CURLOPT_MAXFILESIZE_LARGE... + d c 30117 + d CURLOPT_NETRC_FILE... + d c 10118 + d CURLOPT_USE_SSL... + d c 00119 + d CURLOPT_POSTFIELDSIZE_LARGE... + d c 30120 + d CURLOPT_TCP_NODELAY... + d c 00121 + d CURLOPT_FTPSSLAUTH... + d c 00129 + d CURLOPT_IOCTLFUNCTION... + d c 20130 + d CURLOPT_IOCTLDATA... + d c 10131 + d CURLOPT_FTP_ACCOUNT... + d c 10134 + d CURLOPT_COOKIELIST... + d c 10135 + d CURLOPT_IGNORE_CONTENT_LENGTH... + d c 00136 + d CURLOPT_FTP_SKIP_PASV_IP... + d c 00137 + d CURLOPT_FTP_FILEMETHOD... + d c 00138 + d CURLOPT_LOCALPORT... + d c 00139 + d CURLOPT_LOCALPORTRANGE... + d c 00140 + d CURLOPT_CONNECT_ONLY... + d c 00141 + d CURLOPT_CONV_FROM_NETWORK_FUNCTION... + d c 20142 + d CURLOPT_CONV_TO_NETWORK_FUNCTION... + d c 20143 + d CURLOPT_CONV_FROM_UTF8_FUNCTION... + d c 20144 + d CURLOPT_MAX_SEND_SPEED_LARGE... + d c 30145 + d CURLOPT_MAX_RECV_SPEED_LARGE... + d c 30146 + d CURLOPT_FTP_ALTERNATIVE_TO_USER... + d c 10147 + d CURLOPT_SOCKOPTFUNCTION... + d c 20148 + d CURLOPT_SOCKOPTDATA... + d c 10149 + d CURLOPT_SSL_SESSIONID_CACHE... + d c 00150 + d CURLOPT_SSH_AUTH_TYPES... + d c 00151 + d CURLOPT_SSH_PUBLIC_KEYFILE... + d c 10152 + d CURLOPT_SSH_PRIVATE_KEYFILE... + d c 10153 + d CURLOPT_FTP_SSL_CCC... + d c 00154 + d CURLOPT_TIMEOUT_MS... + d c 00155 + d CURLOPT_CONNECTTIMEOUT_MS... + d c 00156 + d CURLOPT_HTTP_TRANSFER_DECODING... + d c 00157 + d CURLOPT_HTTP_CONTENT_DECODING... + d c 00158 + d CURLOPT_NEW_FILE_PERMS... + d c 00159 + d CURLOPT_NEW_DIRECTORY_PERMS... + d c 00160 + d CURLOPT_POSTREDIR... + d c 00161 + d CURLOPT_SSH_HOST_PUBLIC_KEY_MD5... + d c 10162 + d CURLOPT_OPENSOCKETFUNCTION... + d c 20163 + d CURLOPT_OPENSOCKETDATA... + d c 10164 + d CURLOPT_COPYPOSTFIELDS... + d c 10165 + d CURLOPT_PROXY_TRANSFER_MODE... + d c 00166 + d CURLOPT_SEEKFUNCTION... + d c 20167 + d CURLOPT_SEEKDATA... + d c 10168 + d CURLOPT_CRLFILE... + d c 10169 + d CURLOPT_ISSUERCERT... + d c 10170 + d CURLOPT_ADDRESS_SCOPE... + d c 00171 + d CURLOPT_CERTINFO... + d c 00172 + d CURLOPT_USERNAME... + d c 10173 + d CURLOPT_PASSWORD... + d c 10174 + d CURLOPT_PROXYUSERNAME... + d c 10175 + d CURLOPT_PROXYPASSWORD... + d c 10176 + d CURLOPT_NOPROXY... + d c 10177 + d CURLOPT_TFTP_BLKSIZE... + d c 00178 + d CURLOPT_SOCKS5_GSSAPI_SERVICE... + d c 10179 + d CURLOPT_SOCKS5_GSSAPI_NEC... + d c 00180 + d CURLOPT_PROTOCOLS... + d c 00181 + d CURLOPT_REDIR_PROTOCOLS... + d c 00182 + d CURLOPT_SSH_KNOWNHOSTS... + d c 10183 + d CURLOPT_SSH_KEYFUNCTION... + d c 20184 + d CURLOPT_SSH_KEYDATA... + d c 10185 + d CURLOPT_MAIL_FROM... + d c 10186 + d CURLOPT_MAIL_RCPT... + d c 10187 + d CURLOPT_FTP_USE_PRET... + d c 00188 + d CURLOPT_RTSP_REQUEST... + d c 00189 + d CURLOPT_RTSP_SESSION_ID... + d c 10190 + d CURLOPT_RTSP_STREAM_URI... + d c 10191 + d CURLOPT_RTSP_TRANSPORT... + d c 10192 + d CURLOPT_RTSP_CLIENT_CSEQ... + d c 00193 + d CURLOPT_RTSP_SERVER_CSEQ... + d c 00194 + d CURLOPT_INTERLEAVEDATA... + d c 10195 + d CURLOPT_INTERLEAVEFUNCTION... + d c 20196 + d CURLOPT_WILDCARDMATCH... + d c 00197 + d CURLOPT_CHUNK_BGN_FUNCTION... + d c 20198 + d CURLOPT_CHUNK_END_FUNCTION... + d c 20199 + d CURLOPT_FNMATCH_FUNCTION... + d c 20200 + d CURLOPT_CHUNK_DATA... + d c 10201 + d CURLOPT_FNMATCH_DATA... + d c 10202 + d CURLOPT_RESOLVE... + d c 10203 + d CURLOPT_TLSAUTH_USERNAME... + d c 10204 + d CURLOPT_TLSAUTH_PASSWORD... + d c 10205 + d CURLOPT_TLSAUTH_TYPE... + d c 10206 + d CURLOPT_TRANSFER_ENCODING... + d c 00207 + d CURLOPT_CLOSESOCKETFUNCTION... + d c 20208 + d CURLOPT_CLOSESOCKETDATA... + d c 10209 + d CURLOPT_GSSAPI_DELEGATION... + d c 00210 + d CURLOPT_DNS_SERVERS... + d c 10211 + d CURLOPT_ACCEPTTIMEOUT_MS... + d c 00212 + d CURLOPT_TCP_KEEPALIVE... + d c 00213 + d CURLOPT_TCP_KEEPIDLE... + d c 00214 + d CURLOPT_TCP_KEEPINTVL... + d c 00215 + d CURLOPT_SSL_OPTIONS... + d c 00216 + d CURLOPT_MAIL_AUTH... + d c 10217 + d CURLOPT_SASL_IR... + d c 00218 + d CURLOPT_XFERINFOFUNCTION... + d c 20219 + d CURLOPT_XOAUTH2_BEARER... + d c 10220 + d CURLOPT_DNS_INTERFACE... + d c 10221 + d CURLOPT_DNS_LOCAL_IP4... + d c 10222 + d CURLOPT_DNS_LOCAL_IP6... + d c 10223 + d CURLOPT_LOGIN_OPTIONS... + d c 10224 + d CURLOPT_SSL_ENABLE_NPN... + d c 00225 + d CURLOPT_SSL_ENABLE_ALPN... + d c 00226 + d CURLOPT_EXPECT_100_TIMEOUT_MS... + d c 00227 + d CURLOPT_PROXYHEADER... + d c 10228 + d CURLOPT_HEADEROPT... + d c 00229 + d CURLOPT_PINNEDPUBLICKEY... + d c 10230 + d CURLOPT_UNIX_SOCKET_PATH... + d c 10231 + d CURLOPT_SSL_VERIFYSTATUS... + d c 00232 + d CURLOPT_SSL_FALSESTART... + d c 00233 + d CURLOPT_PATH_AS_IS... + d c 00234 + d CURLOPT_PROXY_SERVICE_NAME... + d c 10235 + d CURLOPT_SERVICE_NAME... + d c 10236 + d CURLOPT_PIPEWAIT... + d c 00237 + d CURLOPT_DEFAULT_PROTOCOL... + d c 10238 + d CURLOPT_STREAM_WEIGHT... + d c 00239 + d CURLOPT_STREAM_DEPENDS... + d c 10240 + d CURLOPT_STREAM_DEPENDS_E... + d c 10241 + d CURLOPT_TFTP_NO_OPTIONS... + d c 00242 + d CURLOPT_CONNECT_TO... + d c 10243 + d CURLOPT_TCP_FASTOPEN... + d c 00244 + d CURLOPT_KEEP_SENDING_ON_ERROR... + d c 00245 + d CURLOPT_PROXY_CAINFO... + d c 10246 + d CURLOPT_PROXY_CAPATH... + d c 10247 + d CURLOPT_PROXY_SSL_VERIFYPEER... + d c 00248 + d CURLOPT_PROXY_SSL_VERIFYHOST... + d c 00249 + d CURLOPT_PROXY_SSLVERSION... + d c 00250 + d CURLOPT_PROXY_TLSAUTH_USERNAME... + d c 10251 + d CURLOPT_PROXY_TLSAUTH_PASSWORD... + d c 10252 + d CURLOPT_PROXY_TLSAUTH_TYPE... + d c 10253 + d CURLOPT_PROXY_SSLCERT... + d c 10254 + d CURLOPT_PROXY_SSLCERTTYPE... + d c 10255 + d CURLOPT_PROXY_SSLKEY... + d c 10256 + d CURLOPT_PROXY_SSLKEYTYPE... + d c 10257 + d CURLOPT_PROXY_KEYPASSWD... + d c 10258 + d CURLOPT_PROXY_SSL_CIPHER_LIST... + d c 10259 + d CURLOPT_PROXY_CRLFILE... + d c 10260 + d CURLOPT_PROXY_SSL_OPTIONS... + d c 00261 + d CURLOPT_PRE_PROXY... + d c 10262 + d CURLOPT_PROXY_PINNEDPUBLICKEY... + d c 10263 + d CURLOPT_ABSTRACT_UNIX_SOCKET... + d c 10264 + d CURLOPT_SUPPRESS_CONNECT_HEADERS... + d c 00265 + d CURLOPT_REQUEST_TARGET... + d c 10266 + d CURLOPT_SOCKS5_AUTH... + d c 00267 + d CURLOPT_SSH_COMPRESSION... + d c 00268 + d CURLOPT_MIMEPOST... + d c 10269 + d CURLOPT_TIMEVALUE_LARGE... + d c 30270 + d CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS... + d c 00271 + d CURLOPT_RESOLVER_START_FUNCTION... + d c 20272 + d CURLOPT_RESOLVER_START_DATA... + d c 10273 + d CURLOPT_HAPROXYPROTOCOL... + d c 00274 + d CURLOPT_DNS_SHUFFLE_ADDRESSES... + d c 00275 + d CURLOPT_TLS13_CIPHERS... + d c 10276 + d CURLOPT_PROXY_TLS13_CIPHERS... + d c 10277 + d CURLOPT_DISALLOW_USERNAME_IN_URL... + d c 00278 + d CURLOPT_DOH_URL... + d c 10279 + d CURLOPT_UPLOAD_BUFFERSIZE... + d c 00280 + d CURLOPT_UPKEEP_INTERVAL_MS... + d c 00281 + d CURLOPT_CURLU c 10282 + d CURLOPT_TRAILERFUNCTION... + d c 20283 + d CURLOPT_TRAILERDATA... + d c 10284 + d CURLOPT_HTTP09_ALLOWED... + d c 00285 + d CURLOPT_ALTSVC_CTRL... + d c 00286 + d CURLOPT_ALTSVC... + d c 10287 + d CURLOPT_MAXAGE_CONN... + d c 00288 + d CURLOPT_SASL_AUTHZID... + d c 10289 + d CURLOPT_MAIL_RCPT_ALLOWFAILS... + d c 00290 + d CURLOPT_SSLCERT_BLOB... + d c 40291 + d CURLOPT_SSLKEY_BLOB... + d c 40292 + d CURLOPT_PROXY_SSLCERT_BLOB... + d c 40293 + d CURLOPT_PROXY_SSLKEY_BLOB... + d c 40294 + d CURLOPT_ISSUERCERT_BLOB... + d c 40295 + d CURLOPT_PROXY_ISSUERCERT... + d c 10296 + d CURLOPT_PROXY_ISSUERCERT_BLOB... + d c 40297 + d CURLOPT_SSL_EC_CURVES... + d c 10298 + d CURLOPT_HSTS_CTRL... + d c 00299 + d CURLOPT_HSTS... + d c 10300 + d CURLOPT_HSTSREADFUNCTION... + d c 20301 + d CURLOPT_HSTSREADDATA... + d c 10302 + d CURLOPT_HSTSWRITEFUNCTION... + d c 20303 + d CURLOPT_HSTSWRITEDATA... + d c 10304 + d CURLOPT_AWS_SIG4... + d c 10305 + d CURLOPT_DOH_SSL_VERIFYPEER... + d c 00306 + d CURLOPT_DOH_SSL_VERIFYHOST... + d c 00307 + d CURLOPT_DOH_SSL_VERIFYSTATUS... + d c 00308 + d CURLOPT_CAINFO_BLOB... + d c 40309 + d CURLOPT_PROXY_CAINFO_BLOB... + d c 40310 + d CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256... + d c 10311 + d CURLOPT_PREREQFUNCTION... + d c 20312 + d CURLOPT_PREREQDATA... + d c 10313 + d CURLOPT_MAXLIFETIME_CONN... + d c 00314 + d CURLOPT_MIME_OPTIONS... + d c 00315 + d CURLOPT_SSH_HOSTKEYFUNCTION... + d c 20316 + d CURLOPT_SSH_HOSTKEYDATA... + d c 10317 + d CURLOPT_PROTOCOLS_STR... + d c 10318 + d CURLOPT_REDIR_PROTOCOLS_STR... + d c 10319 + d CURLOPT_WS_OPTIONS... + d c 00320 + d CURLOPT_CA_CACHE_TIMEOUT... + d c 00321 + d CURLOPT_QUICK_EXIT... + d c 00322 + d CURLOPT_HAPROXY_CLIENT_IP... + d c 10323 + d CURLOPT_SERVER_RESPONSE_TIMEOUT_MS... + d c 00324 + d CURLOPT_ECH c 10325 + * + /if not defined(CURL_NO_OLDIES) + d CURLOPT_FILE c 10001 + d CURLOPT_INFILE... + d c 10009 + d CURLOPT_SSLKEYPASSWD... + d c 10026 + d CURLOPT_SSLCERTPASSWD... + d c 10026 + d CURLOPT_WRITEHEADER... + d c 10029 + d CURLOPT_WRITEINFO... + d c 10040 + d CURLOPT_FTPLISTONLY... + d c 00048 + d CURLOPT_FTPAPPEND... + d c 00050 + d CURLOPT_CLOSEPOLICY... + d c 00072 + d CURLOPT_KRB4LEVEL... + d c 10063 + d CURLOPT_ENCODING... + d c 10102 + d CURLOPT_FTP_SSL... + d c 00119 + d CURLOPT_POST301... + d c 00161 + d CURLOPT_FTP_RESPONSE_TIMEOUT... + d c 00112 + /endif + * + d CURLFORMcode s 10i 0 based(######ptr######) Enum + d CURL_FORMADD_OK... + d c 0 + d CURL_FORMADD_MEMORY... + d c 1 + d CURL_FORMADD_OPTION_TWICE... + d c 2 + d CURL_FORMADD_NULL... + d c 3 + d CURL_FORMADD_UNKNOWN_OPTION... + d c 4 + d CURL_FORMADD_INCOMPLETE... + d c 5 + d CURL_FORMADD_ILLEGAL_ARRAY... + d c 6 + d CURL_FORMADD_DISABLED... + d c 7 + * + d CURLformoption s 10i 0 based(######ptr######) Enum + d CURLFORM_NOTHING... + d c 0 + d CURLFORM_COPYNAME... + d c 1 + d CURLFORM_PTRNAME... + d c 2 + d CURLFORM_NAMELENGTH... + d c 3 + d CURLFORM_COPYCONTENTS... + d c 4 + d CURLFORM_PTRCONTENTS... + d c 5 + d CURLFORM_CONTENTSLENGTH... + d c 6 + d CURLFORM_FILECONTENT... + d c 7 + d CURLFORM_ARRAY... + d c 8 + d CURLFORM_OBSOLETE... + d c 9 + d CURLFORM_FILE... + d c 10 + d CURLFORM_BUFFER... + d c 11 + d CURLFORM_BUFFERPTR... + d c 12 + d CURLFORM_BUFFERLENGTH... + d c 13 + d CURLFORM_CONTENTTYPE... + d c 14 + d CURLFORM_CONTENTHEADER... + d c 15 + d CURLFORM_FILENAME... + d c 16 + d CURLFORM_END... + d c 17 + d CURLFORM_OBSOLETE2... + d c 18 + d CURLFORM_STREAM... + d c 19 + d CURLFORM_CONTENTLEN... + d c 20 + * + d CURLMIMEOPT_FORMESCAPE... + d c X'00000001' + * + d CURLINFO s 10i 0 based(######ptr######) Enum + d CURLINFO_EFFECTIVE_URL... CURLINFO_STRING + 1 + d c X'00100001' + d CURLINFO_RESPONSE_CODE... CURLINFO_LONG + 2 + d c X'00200002' + d CURLINFO_TOTAL_TIME... CURLINFO_DOUBLE + 3 + d c X'00300003' + d CURLINFO_NAMELOOKUP_TIME... CURLINFO_DOUBLE + 4 + d c X'00300004' + d CURLINFO_CONNECT_TIME... CURLINFO_DOUBLE + 5 + d c X'00300005' + d CURLINFO_PRETRANSFER_TIME... CURLINFO_DOUBLE + 6 + d c X'00300006' + d CURLINFO_SIZE_UPLOAD... CURLINFO_DOUBLE + 7 + d c X'00300007' + d CURLINFO_SIZE_UPLOAD_T... CURLINFO_OFF_T + 7 + d c X'00600007' + d CURLINFO_SIZE_DOWNLOAD... CURLINFO_DOUBLE + 8 + d c X'00300008' + d CURLINFO_SIZE_DOWNLOAD_T... CURLINFO_OFF_T + 8 + d c X'00600008' + d CURLINFO_SPEED_DOWNLOAD... CURLINFO_DOUBLE + 9 + d c X'00300009' + d CURLINFO_SPEED_DOWNLOAD_T... CURLINFO_OFF_T + 9 + d c X'00600009' + d CURLINFO_SPEED_UPLOAD... CURLINFO_DOUBLE + 10 + d c X'0030000A' + d CURLINFO_SPEED_UPLOAD_T... CURLINFO_OFF_T + 10 + d c X'0060000A' + d CURLINFO_HEADER_SIZE... CURLINFO_LONG + 11 + d c X'0020000B' + d CURLINFO_REQUEST_SIZE... CURLINFO_LONG + 12 + d c X'0020000C' + d CURLINFO_SSL_VERIFYRESULT... CURLINFO_LONG + 13 + d c X'0020000D' + d CURLINFO_FILETIME... CURLINFO_LONG + 14 + d c X'0020000E' + d CURLINFO_FILETIME_T... CURLINFO_OFF_T + 14 + d c X'0060000E' + d CURLINFO_CONTENT_LENGTH_DOWNLOAD... CURLINFO_DOUBLE + 15 + d c X'0030000F' + d CURLINFO_CONTENT_LENGTH_DOWNLOAD_T... CURLINFO_OFF_T + 15 + d c X'0060000F' + d CURLINFO_CONTENT_LENGTH_UPLOAD... CURLINFO_DOUBLE + 16 + d c X'00300010' + d CURLINFO_CONTENT_LENGTH_UPLOAD_T... CURLINFO_OFF_T + 16 + d c X'00600010' + d CURLINFO_STARTTRANSFER_TIME... CURLINFO_DOUBLE + 17 + d c X'00300011' + d CURLINFO_CONTENT_TYPE... CURLINFO_STRING + 18 + d c X'00100012' + d CURLINFO_REDIRECT_TIME... CURLINFO_DOUBLE + 19 + d c X'00300013' + d CURLINFO_REDIRECT_COUNT... CURLINFO_LONG + 20 + d c X'00200014' + d CURLINFO_PRIVATE... CURLINFO_STRING + 21 + d c X'00100015' + d CURLINFO_HTTP_CONNECTCODE... CURLINFO_LONG + 22 + d c X'00200016' + d CURLINFO_HTTPAUTH_AVAIL... CURLINFO_LONG + 23 + d c X'00200017' + d CURLINFO_PROXYAUTH_AVAIL... CURLINFO_LONG + 24 + d c X'00200018' + d CURLINFO_OS_ERRNO... CURLINFO_LONG + 25 + d c X'00200019' + d CURLINFO_NUM_CONNECTS... CURLINFO_LONG + 26 + d c X'0020001A' + d CURLINFO_SSL_ENGINES... CURLINFO_SLIST + 27 + d c X'0040001B' + d CURLINFO_COOKIELIST... CURLINFO_SLIST + 28 + d c X'0040001C' + d CURLINFO_LASTSOCKET... CURLINFO_LONG + 29 + d c X'0020001D' + d CURLINFO_FTP_ENTRY_PATH... CURLINFO_STRING + 30 + d c X'0010001E' + d CURLINFO_REDIRECT_URL... CURLINFO_STRING + 31 + d c X'0010001F' + d CURLINFO_PRIMARY_IP... CURLINFO_STRING + 32 + d c X'00100020' + d CURLINFO_APPCONNECT_TIME... CURLINFO_DOUBLE + 33 + d c X'00300021' + d CURLINFO_CERTINFO... CURLINFO_SLIST + 34 + d c X'00400022' + d CURLINFO_CONDITION_UNMET... CURLINFO_LONG + 35 + d c X'00200023' + d CURLINFO_RTSP_SESSION_ID... CURLINFO_STRING + 36 + d c X'00100024' + d CURLINFO_RTSP_CLIENT_CSEQ... CURLINFO_LONG + 37 + d c X'00200025' + d CURLINFO_RTSP_SERVER_CSEQ... CURLINFO_LONG + 38 + d c X'00200026' + d CURLINFO_RTSP_CSEQ_RECV... CURLINFO_LONG + 39 + d c X'00200027' + d CURLINFO_PRIMARY_PORT... CURLINFO_LONG + 40 + d c X'00200028' + d CURLINFO_LOCAL_IP... CURLINFO_STRING + 41 + d c X'00100029' + d CURLINFO_LOCAL_PORT... CURLINFO_LONG + 42 + d c X'0020002A' + d CURLINFO_TLS_SESSION... CURLINFO_SLIST + 43 + d c X'0040002B' + d CURLINFO_ACTIVESOCKET... CURLINFO_SOCKET + 44 + d c X'0050002C' + d CURLINFO_TLS_SSL_PTR... CURLINFO_SLIST + 45 + d c X'0040002D' + d CURLINFO_HTTP_VERSION... CURLINFO_LONG + 46 + d c X'0020002E' + d CURLINFO_PROXY_SSL_VERIFYRESULT... CURLINFO_LONG + 47 + d c X'0020002F' + d CURLINFO_PROTOCOL... CURLINFO_LONG + 48 + d c X'00200030' + d CURLINFO_SCHEME... CURLINFO_STRING + 49 + d c X'00100031' + d CURLINFO_TOTAL_TIME_T... CURLINFO_OFF_T + 50 + d c X'00600032' + d CURLINFO_NAMELOOKUP_TIME_T... CURLINFO_OFF_T + 51 + d c X'00600033' + d CURLINFO_CONNECT_TIME_T... CURLINFO_OFF_T + 52 + d c X'00600034' + d CURLINFO_PRETRANSFER_TIME_T... CURLINFO_OFF_T + 53 + d c X'00600035' + d CURLINFO_STARTTRANSFER_TIME_T... CURLINFO_OFF_T + 54 + d c X'00600036' + d CURLINFO_REDIRECT_TIME_T... CURLINFO_OFF_T + 55 + d c X'00600037' + d CURLINFO_APPCONNECT_TIME_T... CURLINFO_OFF_T + 56 + d c X'00600038' + d CURLINFO_RETRY_AFTER... CURLINFO_OFF_T + 57 + d c X'00600039' + d CURLINFO_EFFECTIVE_METHOD... CURLINFO_STRING + 58 + d c X'0010003A' + d CURLINFO_PROXY_ERROR... CURLINFO_LONG + 59 + d c X'0020003B' + d CURLINFO_REFERER... CURLINFO_STRING + 60 + d c X'0010003C' + d CURLINFO_CAINFO... CURLINFO_STRING + 61 + d c X'0010003D' + d CURLINFO_CAPATH... CURLINFO_STRING + 62 + d c X'0010003E' + d CURLINFO_XFER_ID... CURLINFO_OFF_T + 63 + d c X'0060003F' + d CURLINFO_CONN_ID... CURLINFO_OFF_T + 64 + d c X'00600040' + d CURLINFO_QUEUE_TIME_T... CURLINFO_OFF_T + 65 + d c X'00600041' + d CURLINFO_USED_PROXY... CURLINFO_LONG + 66 + d c X'00200042' + * + d CURLINFO_HTTP_CODE... Old ...RESPONSE_CODE + d c X'00200002' + * + d curl_sslbackend... + d s 10i 0 based(######ptr######) Enum + d CURLSSLBACKEND_NONE... + d c 0 + d CURLSSLBACKEND_OPENSSL... + d c 1 + d CURLSSLBACKEND_GNUTLS... + d c 2 + d CURLSSLBACKEND_NSS... + d c 3 + d CURLSSLBACKEND_OBSOLETE4... + d c 4 + d CURLSSLBACKEND_GSKIT... + d c 5 + d CURLSSLBACKEND_POLARSSL... + d c 6 + d CURLSSLBACKEND_CYASSL... + d c 7 + d CURLSSLBACKEND_SCHANNEL... + d c 8 + d CURLSSLBACKEND_DARWINSSL... + d c 9 + d CURLSSLBACKEND_AXTLS... + d c 10 + d CURLSSLBACKEND_MBEDTLS... + d c 11 + d CURLSSLBACKEND_MESALINK... + d c 12 + d CURLSSLBACKEND_BEARSSL... + d c 13 + d CURLSSLBACKEND_RUSTLS... + d c 14 + * Aliases for clones. + d CURLSSLBACKEND_AWSLC... + d c 1 + d CURLSSLBACKEND_BORINGSSL... + d c 1 + d CURLSSLBACKEND_LIBRESSL... + d c 1 + d CURLSSLBACKEND_WOLFSSL... + d c 6 + * + d curl_closepolicy... + d s 10i 0 based(######ptr######) Enum + d CURLCLOSEPOLICY_OLDEST... + d c 1 + d CURLCLOSEPOLICY_LEAST_RECENTLY_USED... + d c 2 + d CURLCLOSEPOLICY_LEAST_TRAFFIC... + d c 3 + d CURLCLOSEPOLICY_SLOWEST... + d c 4 + d CURLCLOSEPOLICY_CALLBACK... + d c 5 + * + d curl_lock_data... + d s 10i 0 based(######ptr######) Enum + d CURL_LOCK_DATA_NONE... + d c 0 + d CURL_LOCK_DATA_SHARE... + d c 1 + d CURL_LOCK_DATA_COOKIE... + d c 2 + d CURL_LOCK_DATA_DNS... + d c 3 + d CURL_LOCK_DATA_SSL_SESSION... + d c 4 + d CURL_LOCK_DATA_CONNECT... + d c 5 + d CURL_LOCK_DATA_PSL... + d c 6 + d CURL_LOCK_DATA_HSTS... + d c 7 + d CURL_LOCK_DATA_LAST... + d c 8 + * + d curl_lock_access... + d s 10i 0 based(######ptr######) Enum + d CURL_LOCK_ACCESS_NONE... + d c 0 + d CURL_LOCK_ACCESS_SHARED... + d c 1 + d CURL_LOCK_ACCESS_SINGLE... + d c 2 + * + d curl_TimeCond s 10i 0 based(######ptr######) Enum + d CURL_TIMECOND_NONE... + d c 0 + d CURL_TIMECOND_IFMODSINCE... + d c 1 + d CURL_TIMECOND_LASTMOD... + d c 2 + d CURL_TIMECOND_LAST... + d c 3 + * + d curl_easytype s 10i 0 based(######ptr######) Enum + d CURLOT_LONG c 0 + d CURLOT_VALUES... + d c 1 + d CURLOT_OFF_T c 2 + d CURLOT_OBJECT... + d c 3 + d CURLOT_STRING... + d c 4 + d CURLOT_SLIST c 5 + d CURLOT_CBPTR c 6 + d CURLOT_BLOB c 7 + d CURLOT_FUNCTION... + d c 8 + * + d CURLSHcode s 10i 0 based(######ptr######) Enum + d CURLSHE_OK c 0 + d CURLSHE_BAD_OPTION... + d c 1 + d CURLSHE_IN_USE... + d c 2 + d CURLSHE_INVALID... + d c 3 + d CURLSHE_NOMEM... + d c 4 + d CURLSHE_NOT_BUILT_IN... + d c 5 + * + d CURLSHoption... + d s 10i 0 based(######ptr######) Enum + d CURLSHOPT_SHARE... + d c 1 + d CURLSHOPT_UNSHARE... + d c 2 + d CURLSHOPT_LOCKFUNC... + d c 3 + d CURLSHOPT_UNLOCKFUNC... + d c 4 + d CURLSHOPT_USERDATA... + d c 5 + * + d CURLversion s 10i 0 based(######ptr######) Enum + d CURLVERSION_FIRST... + d c 0 + d CURLVERSION_SECOND... + d c 1 + d CURLVERSION_THIRD... + d c 2 + d CURLVERSION_FOURTH... + d c 3 + d CURLVERSION_FIFTH... + d c 4 + d CURLVERSION_SIXTH... + d c 5 + d CURLVERSION_SEVENTH... + d c 6 + d CURLVERSION_EIGHTH... + d c 7 + d CURLVERSION_NINTH... + d c 8 + d CURLVERSION_TENTH... + d c 9 + d CURLVERSION_ELEVENTH... + d c 10 + d CURLVERSION_TWELFTH... + d c 11 + d CURLVERSION_NOW... + d c 11 CURLVERSION_ELEVENTH + * + d CURLHcode s 10i 0 based(######ptr######) Enum + d CURLHE_OK c 0 + d CURLHE_BADINDEX... + d c 1 + d CURLHE_MISSING... + d c 2 + d CURLHE_NOHEADERS... + d c 3 + d CURLHE_NOREQUEST... + d c 4 + d CURLHE_OUT_OF_MEMORY... + d c 5 + d CURLHE_BAD_ARGUMENT... + d c 6 + d CURLHE_NOT_BUILT_IN... + d c 7 + * + d curlsocktype s 10i 0 based(######ptr######) Enum + d CURLSOCKTYPE_IPCXN... + d c 0 + d CURLSOCKTYPE_ACCEPT... + d c 1 + * + d CURL_SOCKOPT_OK... + d c 0 + d CURL_SOCKOPT_ERROR... + d c 1 + d CURL_SOCKOPT_ALREADY_CONNECTED... + d c 2 + * + d CURLMcode s 10i 0 based(######ptr######) Enum + d CURLM_CALL_MULTI_PERFORM... + d c -1 + d CURLM_CALL_MULTI_SOCKET... + d c -1 + d CURLM_OK c 0 + d CURLM_BAD_HANDLE... + d c 1 + d CURLM_BAD_EASY_HANDLE... + d c 2 + d CURLM_OUT_OF_MEMORY... + d c 3 + d CURLM_INTERNAL_ERROR... + d c 4 + d CURLM_BAD_SOCKET... + d c 5 + d CURLM_UNKNOWN_OPTION... + d c 6 + d CURLM_ADDED_ALREADY... + d c 7 + d CURLM_RECURSIVE_API_CALL... + d c 8 + d CURLM_WAKEUP_FAILURE... + d c 9 + d CURLM_BAD_FUNCTION_ARGUMENT... + d c 10 + d CURLM_LAST c 11 + * + d CURLMSG s 10i 0 based(######ptr######) Enum + d CURLMSG_NONE c 0 + d CURLMSG_DONE c 1 + * + d CURLMoption s 10i 0 based(######ptr######) Enum + d CURLMOPT_SOCKETFUNCTION... + d c 20001 + d CURLMOPT_SOCKETDATA... + d c 10002 + d CURLMOPT_PIPELINING... + d c 00003 + d CURLMOPT_TIMERFUNCTION... + d c 20004 + d CURLMOPT_TIMERDATA... + d c 10005 + d CURLMOPT_MAXCONNECTS... + d c 00006 + d CURLMOPT_MAX_HOST_CONNECTIONS... + d c 00007 + d CURLMOPT_MAX_PIPELINE_LENGTH... + d c 00008 + d CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE... + d c 30009 + d CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE... + d c 30010 + d CURLMOPT_PIPELINING_SITE_BL... + d c 10011 + d CURLMOPT_PIPELINING_SERVER_BL... + d c 10012 + d CURLMOPT_MAX_TOTAL_CONNECTIONS... + d c 00013 + d CURLMOPT_PUSHFUNCTION... + d c 20014 + d CURLMOPT_PUSHDATA... + d c 10015 + d CURLMOPT_MAX_CONCURRENT_STREAMS... + d c 10016 + * + * Bitmask bits for CURLMOPT_PIPELING. + * + d CURLPIPE_NOTHING... + d c x'00000000' + d CURLPIPE_HTTP1 c x'00000001' + d CURLPIPE_MULTIPLEX... + d c x'00000002' + * + * Public API enums for RTSP requests. + * + d CURLRTSPREQ_NONE... + d c 0 + d CURL_RTSPREQ_OPTIONS... + d c 1 + d CURL_RTSPREQ_DESCRIBE... + d c 2 + d CURL_RTSPREQ_ANNOUNCE... + d c 3 + d CURL_RTSPREQ_SETUP... + d c 4 + d CURL_RTSPREQ_PLAY... + d c 5 + d CURL_RTSPREQ_PAUSE... + d c 6 + d CURL_RTSPREQ_TEARDOWN... + d c 7 + d CURL_RTSPREQ_GET_PARAMETER... + d c 8 + d CURL_RTSPREQ_SET_PARAMETER... + d c 9 + d CURL_RTSPREQ_RECORD... + d c 10 + d CURL_RTSPREQ_RECEIVE... + d c 12 + d CURL_RTSPREQ_LAST... + d c 13 + * + d CURLUcode s 10i 0 based(######ptr######) Enum + d CURLUE_OK c 0 + d CURLUE_BAD_HANDLE... + d c 1 + d CURLUE_BAD_PARTPOINTER... + d c 2 + d CURLUE_MALFORMED_INPUT... + d c 3 + d CURLUE_BAD_PORT_NUMBER... + d c 4 + d CURLUE_UNSUPPORTED_SCHEME... + d c 5 + d CURLUE_URLDECODE... + d c 6 + d CURLUE_OUT_OF_MEMORY... + d c 7 + d CURLUE_USER_NOT_ALLOWED... + d c 8 + d CURLUE_UNKNOWN_PART... + d c 9 + d CURLUE_NO_SCHEME... + d c 10 + d CURLUE_NO_USER... + d c 11 + d CURLUE_NO_PASSWORD... + d c 12 + d CURLUE_NO_OPTIONS... + d c 13 + d CURLUE_NO_HOST... + d c 14 + d CURLUE_NO_PORT... + d c 15 + d CURLUE_NO_QUERY... + d c 16 + d CURLUE_NO_FRAGMENT... + d c 17 + d CURLUE_NO_ZONEID... + d c 18 + d CURLUE_BAD_FILE_URL... + d c 19 + d CURLUE_BAD_FRAGMENT... + d c 20 + d CURLUE_BAD_HOSTNAME... + d c 21 + d CURLUE_BAD_IPV6... + d c 22 + d CURLUE_BAD_LOGIN... + d c 23 + d CURLUE_BAD_PASSWORD... + d c 24 + d CURLUE_BAD_PATH... + d c 25 + d CURLUE_BAD_QUERY... + d c 26 + d CURLUE_BAD_SCHEME... + d c 27 + d CURLUE_BAD_SLASHES... + d c 28 + d CURLUE_BAD_USER... + d c 29 + d CURLUE_LACKS_IDN... + d c 30 + d CURLUE_TOO_LARGE... + d c 31 + * + d CURLUPart s 10i 0 based(######ptr######) Enum + d CURLUPART_URL c 0 + d CURLUPART_SCHEME... + d c 1 + d CURLUPART_USER... + d c 2 + d CURLUPART_PASSWORD... + d c 3 + d CURLUPART_OPTIONS... + d c 4 + d CURLUPART_HOST... + d c 5 + d CURLUPART_PORT... + d c 6 + d CURLUPART_PATH... + d c 7 + d CURLUPART_QUERY... + d c 8 + d CURLUPART_FRAGMENT... + d c 9 + d CURLUPART_ZONEID... + d c 10 + * + * + d CURLSTScode s 10i 0 based(######ptr######) Enum + d CURLSTS_OK c 0 + d CURLSTS_DONE c 1 + d CURLSTS_FAIL c 2 + * + * Renaming CURLMsg to CURL_Msg to avoid case-insensitivity name clash. + * + d CURL_Msg ds based(######ptr######) + d qualified + d msg like(CURLMSG) + d easy_handle * CURL * + d data * + d whatever * overlay(data) void * + d result overlay(data) like(CURLcode) + * + d curl_waitfd... + d ds based(######ptr######) + d qualified + d fd like(curl_socket_t) + d events 5i 0 + d revents 5i 0 + * + d curl_http_post... + d ds based(######ptr######) + d qualified + d next * curl_httppost * + d name * char * + d namelength 10i 0 long + d contents * char * + d contentslength... + d 10i 0 long + d buffer * char * + d bufferlength... + d 10i 0 long + d contenttype * char * + d contentheader... + d * curl_slist * + d more * curl_httppost * + d flags 10i 0 long + d showfilename * char * + d userp * void * + * + d curl_sockaddr ds based(######ptr######) + d qualified + d family 10i 0 + d socktype 10i 0 + d protocol 10i 0 + d addrlen 10u 0 + d addr 16 struct sockaddr + * + d curl_khtype s 10i 0 based(######ptr######) enum + d CURLKHTYPE_UNKNOWN... + d c 0 + d CURLKHTYPE_RSA1... + d c 1 + d CURLKHTYPE_RSA... + d c 2 + d CURLKHTYPE_DSS... + d c 3 + * + d curl_khkey ds based(######ptr######) + d qualified + d key * const char * + d len 10u 0 + d keytype like(curl_khtype) + * + d curl_forms ds based(######ptr######) + d qualified + d option like(CURLformoption) + d value * const char * + d value_ptr * overlay(value) + d value_procptr... + d * overlay(value) procptr + d value_num overlay(value: 8) like(curl_off_t) + * + d curl_slist ds based(######ptr######) + d qualified + d data * char * + d next * struct curl_slist * + * + d curl_version_info_data... + d ds based(######ptr######) + d qualified + d age like(CURLversion) + d version * const char * + d version_num 10u 0 + d host * const char * + d features 10i 0 + d ssl_version * const char * + d ssl_version_num... + d 10i 0 long + d libz_version * const char * + d protocols * const char * const * + d ares * const char * + d ares_num 10i 0 + d libidn * const char * + d iconv_ver_num... + d 10i 0 + d libssh_version... + d * const char * + d brotli_ver_num... + d 10u 0 + d brotli_version... + d * const char * + d nghttp2_ver_num... + d 10u 0 + d nghttp2_version... + d * const char * + d quic_version... + d * const char * + d cainfo... + d * const char * + d capath... + d * const char * + d zstd_ver_num... + d 10u 0 + d zstd_version... + d * const char * + d hyper_version... + d * const char * + d gsasl_version... + d * const char * + d feature_names... + d * const char * + d rtmp_version... + d * const char * + * + d curl_certinfo ds based(######ptr######) + d qualified + d num_of_certs 10i 0 + d certinfo * struct curl_slist ** + * + d curl_fistrgs ds based(######ptr######) + d qualified + d time * char * + d perm * char * + d user * char * + d group * char * + d target * char * + * + d curl_tlssessioninfo... + d ds based(######ptr######) + d qualified + d backend like(curl_sslbackend) + d internals * void * + * + d curl_fileinfo ds based(######ptr######) + d qualified + d filename * char * + d filetype like(curlfiletype) + d time 10i 0 time_t + d perm 10u 0 + d uid 10i 0 + d gid 10i 0 + d size like(curl_off_t) + d hardlinks 10i 0 + d strings likeds(curl_fistrgs) + d flags 10u 0 + d b_data * char * + d b_size 10u 0 size_t + d b_used 10u 0 size_t + * + d curl_easyoption... + d ds based(######ptr######) + d qualified + d name * const char * + d id like(CURLoption) + d type like(curl_easytype) + d flags 10u 0 + * + d curl_hstsentry... + d ds based(######ptr######) + d qualified + d name * char * + d namelen 10u 0 size_t + d includeSubDomain... + d 10u 0 Bit field: 1 + d expire 10 + * + d curl_index ds based(######ptr######) + d qualified + d index 10u 0 size_t + d total 10u 0 size_t + * + d curl_header ds based(######ptr######) + d qualified + d name * char * + d value * char * + d amount 10u 0 size_t + d index 10u 0 size_t + d origin 10u 0 + d anchor * void * + * + d curl_blob ds based(######ptr######) + d qualified + d data * void * + d len 10u 0 size_t + d flags 10u 0 + * + d curl_ws_frame ds based(######ptr######) + d qualified + d age 10i 0 + d flags 10i 0 + d offset like(curl_off_t) + d bytesleft like(curl_off_t) + d len 10u 0 size_t + * + d curl_formget_callback... + d s * based(######ptr######) procptr + * + d curl_malloc_callback... + d s * based(######ptr######) procptr + * + d curl_free_callback... + d s * based(######ptr######) procptr + * + d curl_realloc_callback... + d s * based(######ptr######) procptr + * + d curl_strdup_callback... + d s * based(######ptr######) procptr + * + d curl_calloc_callback... + d s * based(######ptr######) procptr + * + d curl_lock_function... + d s * based(######ptr######) procptr + * + d curl_unlock_function... + d s * based(######ptr######) procptr + * + d curl_progress_callback... + d s * based(######ptr######) procptr + * + d curl_xferinfo_callback... + d s * based(######ptr######) procptr + * + d curl_read_callback... + d s * based(######ptr######) procptr + * + d curl_trailer_callback... + d s * based(######ptr######) procptr + * + d curl_write_callback... + d s * based(######ptr######) procptr + * + d curl_seek_callback... + d s * based(######ptr######) procptr + * + d curl_sockopt_callback... + d s * based(######ptr######) procptr + * + d curl_ioctl_callback... + d s * based(######ptr######) procptr + * + d curl_debug_callback... + d s * based(######ptr######) procptr + * + d curl_conv_callback... + d s * based(######ptr######) procptr + * + d curl_ssl_ctx_callback... + d s * based(######ptr######) procptr + * + d curl_socket_callback... + d s * based(######ptr######) procptr + * + d curl_multi_timer_callback... + d s * based(######ptr######) procptr + * + d curl_push_callback... + d s * based(######ptr######) procptr + * + d curl_opensocket_callback... + d s * based(######ptr######) procptr + * + d curl_sshkeycallback... + d s * based(######ptr######) procptr + * + d curl_chunk_bgn_callback... + d s * based(######ptr######) procptr + * + d curl_chunk_end_callback... + d s * based(######ptr######) procptr + * + d curl_fnmatch_callback... + d s * based(######ptr######) procptr + * + d curl_closesocket_callback... + d s * based(######ptr######) procptr + * + d curl_resolver_start_callback... + d s * based(######ptr######) procptr + * + d curl_hstsread_callback... + d s * based(######ptr######) procptr + * + d curl_hstswrite_callback... + d s * based(######ptr######) procptr + * + d curl_prereq_callback... + d s * based(######ptr######) procptr + * + d curl_sshhostkeycallback... + d s * based(######ptr######) procptr + * + d curl_ws_write_callback... + d s * based(######ptr######) procptr + * + ************************************************************************** + * Prototypes + ************************************************************************** + * + d curl_mime_init pr * extproc('curl_mime_init') curl_mime * + d easy * value CURL * + * + d curl_mime_free pr extproc('curl_mime_free') + d mime * value curl_mime * + * + d curl_mime_addpart... + d pr * extproc('curl_mime_addpart') curl_mimepart * + d mime * value curl_mime * + * + d curl_mime_name pr extproc('curl_mime_name') + d like(CURLcode) + d part * value curl_mimepart * + d name * value options(*string) + * + d curl_mime_filename... + d pr extproc('curl_mime_filename') + d like(CURLcode) + d part * value curl_mimepart * + d filename * value options(*string) + * + d curl_mime_type pr extproc('curl_mime_type') + d like(CURLcode) + d part * value curl_mimepart * + d mimetype * value options(*string) + * + d curl_mime_encoder... + d pr extproc('curl_mime_encoder') + d like(CURLcode) + d part * value curl_mimepart * + d encoding * value options(*string) + * + d curl_mime_data pr extproc('curl_mime_data') + d like(CURLcode) + d part * value curl_mimepart * + d data * value options(*string) + d datasize 10u 0 value size_t + * + d curl_mime_filedata... + d pr extproc('curl_mime_filedata') + d like(CURLcode) + d part * value curl_mimepart * + d filename * value options(*string) + * + d curl_mime_data_cb... + d pr extproc('curl_mime_data_cb') + d like(CURLcode) + d part * value curl_mimepart * + d datasize value like(curl_off_t) + d readfunc value like(curl_read_callback) + d seekfunc value like(curl_seek_callback) + d freefunc value like(curl_free_callback) + d arg * value void * + * + d curl_mime_subparts... + d pr extproc('curl_mime_subparts') + d like(CURLcode) + d part * value curl_mimepart * + d subparts * value curl_mime * + * + d curl_mime_headers... + d pr extproc('curl_mime_headers') + d like(CURLcode) + d part * value curl_mimepart * + d headers * value curl_slist * + d take_ownership... + d 10i 0 value + * + * This procedure as a variable parameter list. + * This prototype allows use of an option array, or a single "object" + * option. Other argument lists may be implemented by alias procedure + * prototype definitions. + * + d curl_formadd pr extproc('curl_formadd') + d like(CURLFORMcode) + d httppost * curl_httppost * + d lastpost * curl_httppost * + d option1 value like(CURLFORMoption) CURLFORM_ARRAY + d options(*nopass) + d object1 * value options(*string: *nopass) + d option2 value like(CURLFORMoption) CURLFORM_END + d options(*nopass) + * + * + d curl_strequal pr 10i 0 extproc('curl_strequal') + d s1 * value options(*string) + d s2 * value options(*string) + * + d curl_strnequal pr 10i 0 extproc('curl_strnequal') + d s1 * value options(*string) + d s2 * value options(*string) + d n 10u 0 value + * + d curl_formget pr 10i 0 extproc('curl_formget') + d form * value curl_httppost * + d arg * value + d append value like(curl_formget_callback) + * + d curl_formfree pr extproc('curl_formfree') + d form * value curl_httppost * + * + d curl_getenv pr * extproc('curl_getenv') + d variable * value options(*string) + * + d curl_version pr * extproc('curl_version') + * + d curl_easy_escape... + d pr * extproc('curl_easy_escape') char * + d handle * value CURL * + d string * value options(*string) + d length 10i 0 value + * + d curl_escape pr * extproc('curl_escape') char * + d string * value options(*string) + d length 10i 0 value + * + d curl_easy_unescape... + d pr * extproc('curl_easy_unescape') char * + d handle * value CURL * + d string * value options(*string) + d length 10i 0 value + d outlength 10i 0 options(*omit) + * + d curl_unescape pr * extproc('curl_unescape') char * + d string * value options(*string) + d length 10i 0 value + * + d curl_free pr extproc('curl_free') + d p * value + * + d curl_global_init... + d pr extproc('curl_global_init') + d like(CURLcode) + d flags 10i 0 value + * + d curl_global_init_mem... + d pr extproc('curl_global_init_mem') + d like(CURLcode) + d m value like(curl_malloc_callback) + d f value like(curl_free_callback) + d r value like(curl_realloc_callback) + d s value like(curl_strdup_callback) + d c value like(curl_calloc_callback) + * + d curl_global_cleanup... + d pr extproc('curl_global_cleanup') + * + d curl_slist_append... + d pr * extproc('curl_slist_append') struct curl_slist * + d list * value struct curl_slist * + d data * value options(*string) const char * + * + d curl_slist_free_all... + d pr extproc('curl_slist_free_all') + d list * value struct curl_slist * + * + d curl_getdate pr 10i 0 extproc('curl_getdate') time_t + d p * value options(*string) const char * + d unused 10i 0 const options(*omit) time_t + * + d curl_share_init... + d pr * extproc('curl_share_init') CURLSH * (= void *) + * + * Variable argument type procedure. + * Multiply prototyped to support all possible types. + * + d curl_share_setopt_int... + d pr extproc('curl_share_setopt') + d like(CURLSHcode) + d share * value CURLSH * (= void *) + d option value like(CURLSHoption) + d intarg 10i 0 value options(*nopass) + * + d curl_share_setopt_ptr... + d pr extproc('curl_share_setopt') + d like(CURLSHcode) + d share * value CURLSH * (= void *) + d option value like(CURLSHoption) + d ptrarg * value options(*nopass) + * + d curl_share_setopt_proc... + d pr extproc('curl_share_setopt') + d like(CURLSHcode) + d share * value CURLSH * (= void *) + d option value like(CURLSHoption) + d procarg * value procptr options(*nopass) + * + d curl_share_cleanup... + d pr extproc('curl_share_cleanup') + d like(CURLSHcode) + d share * value CURLSH * (= void *) + * + d curl_version_info... + d pr * extproc('curl_version_info') c_i_version_data * + d version value like(CURLversion) + * + d curl_easy_strerror... + d pr * extproc('curl_easy_strerror') const char * + d code value like(CURLcode) + * + d curl_share_strerror... + d pr * extproc('curl_share_strerror') const char * + d code value like(CURLSHcode) + * + d curl_easy_init pr * extproc('curl_easy_init') CURL * + * + * Multiple prototypes for vararg procedure curl_easy_setopt. + * + d curl_easy_setopt_long... + d pr extproc('curl_easy_setopt') + d like(CURLcode) + d curl * value CURL * + d option value like(CURLoption) + d longarg 10i 0 value options(*nopass) + * + d curl_easy_setopt_object... + d pr extproc('curl_easy_setopt') + d like(CURLcode) + d curl * value CURL * + d option value like(CURLoption) + d objectarg * value options(*string: *nopass) + * + d curl_easy_setopt_function... + d pr extproc('curl_easy_setopt') + d like(CURLcode) + d curl * value CURL * + d option value like(CURLoption) + d functionarg * value procptr options(*nopass) + * + d curl_easy_setopt_offset... + d pr extproc('curl_easy_setopt') + d like(CURLcode) + d curl * value CURL * + d option value like(CURLoption) + d offsetarg value like(curl_off_t) + d options(*nopass) + * + d curl_easy_setopt_blob... + d pr extproc('curl_easy_setopt') + d like(CURLcode) + d curl * value CURL * + d option value like(CURLoption) + d blob const likeds(curl_blob) + d options(*nopass) + * + * + d curl_easy_perform... + d pr extproc('curl_easy_perform') + d like(CURLcode) + d curl * value CURL * + * + d curl_easy_cleanup... + d pr extproc('curl_easy_cleanup') + d curl * value CURL * + * + * Multiple prototypes for vararg procedure curl_easy_getinfo. + * + d curl_easy_getinfo_string... + d pr extproc('curl_easy_getinfo') + d like(CURLcode) + d curl * value CURL * + d info value like(CURLINFO) + d stringarg * options(*nopass) char * + * + d curl_easy_getinfo_long... + d pr extproc('curl_easy_getinfo') + d like(CURLcode) + d curl * value CURL * + d info value like(CURLINFO) + d longarg 10i 0 options(*nopass) + * + d curl_easy_getinfo_double... + d pr extproc('curl_easy_getinfo') + d like(CURLcode) + d curl * value CURL * + d info value like(CURLINFO) + d doublearg 8f options(*nopass) + * + d curl_easy_getinfo_slist... + d pr extproc('curl_easy_getinfo') + d like(CURLcode) + d curl * value CURL * + d info value like(CURLINFO) + d slistarg * options(*nopass) struct curl_slist * + * + d curl_easy_getinfo_ptr... + d pr extproc('curl_easy_getinfo') + d like(CURLcode) + d curl * value CURL * + d info value like(CURLINFO) + d ptrarg * options(*nopass) void * + * + d curl_easy_getinfo_socket... + d pr extproc('curl_easy_getinfo') + d like(CURLcode) + d curl * value CURL * + d info value like(CURLINFO) + d socketarg like(curl_socket_t) options(*nopass) + * + d curl_easy_getinfo_off_t... + d pr extproc('curl_easy_getinfo') + d like(CURLcode) + d curl * value CURL * + d info value like(CURLINFO) + d offsetarg like(curl_off_t) options(*nopass) + * + * + d curl_easy_duphandle... + d pr * extproc('curl_easy_duphandle') CURL * + d curl * value CURL * + * + d curl_easy_reset... + d pr extproc('curl_easy_reset') + d curl * value CURL * + * + d curl_easy_recv... + d pr extproc('curl_easy_recv') + d like(CURLcode) + d curl * value CURL * + d buffer * value void * + d buflen 10u 0 value size_t + d n 10u 0 size_t * + * + d curl_easy_send... + d pr extproc('curl_easy_send') + d like(CURLcode) + d curl * value CURL * + d buffer * value const void * + d buflen 10u 0 value size_t + d n 10u 0 size_t * + * + d curl_easy_pause... + d pr extproc('curl_easy_pause') + d like(CURLcode) + d curl * value CURL * + d bitmask 10i 0 value + * + d curl_easy_upkeep... + d pr extproc('curl_easy_upkeep') + d like(CURLcode) + d curl * value CURL * + * + d curl_multi_init... + d pr * extproc('curl_multi_init') CURLM * + * + d curl_multi_add_handle... + d pr extproc('curl_multi_add_handle') + d like(CURLMcode) + d multi_handle * value CURLM * + d curl_handle * value CURL * + * + d curl_multi_remove_handle... + d pr extproc('curl_multi_remove_handle') + d like(CURLMcode) + d multi_handle * value CURLM * + d curl_handle * value CURL * + * + d curl_multi_fdset... + d pr extproc('curl_multi_fdset') + d like(CURLMcode) + d multi_handle * value CURLM * + d read_fd_set 65535 options(*varsize) fd_set + d write_fd_set 65535 options(*varsize) fd_set + d exc_fd_set 65535 options(*varsize) fd_set + d max_fd 10i 0 + * + d curl_multi_wait... + d pr extproc('curl_multi_wait') + d like(CURLMcode) + d multi_handle * value CURLM * + d extra_fds * value curl_waitfd * + d extra_nfds 10u 0 value + d timeout_ms 10i 0 value + d ret 10i 0 options(*omit) + * + d curl_multi_perform... + d pr extproc('curl_multi_perform') + d like(CURLMcode) + d multi_handle * value CURLM * + d running_handles... + d 10i 0 + * + d curl_multi_cleanup... + d pr extproc('curl_multi_cleanup') + d like(CURLMcode) + d multi_handle * value CURLM * + * + d curl_multi_info_read... + d pr * extproc('curl_multi_info_read') CURL_Msg * + d multi_handle * value CURLM * + d msgs_in_queue 10i 0 + * + d curl_multi_strerror... + d pr * extproc('curl_multi_strerror') char * + d code value like(CURLMcode) + * + d curl_pushheader_bynum... + d pr * extproc('curl_pushheader_bynum') char * + d h * value curl_pushheaders * + d num 10u 0 value + * + d curl_pushheader_byname... + d pr * extproc('curl_pushheader_byname') char * + d h * value curl_pushheaders * + d header * value options(*string) const char * + * + d curl_multi_socket... + d pr extproc('curl_multi_socket') + d like(CURLMcode) + d multi_handle * value CURLM * + d s value like(curl_socket_t) + d running_handles... + d 10i 0 + * + d curl_multi_waitfds... + d pr extproc('curl_multi_waitfds') + d like(CURLMcode) + d multi * value CURLM * + d ufds * value curl_waitfd * + d size 10u 0 value + d fd_count 10u 0 + * + d curl_multi_socket_action... + d pr extproc('curl_multi_socket_action') + d like(CURLMcode) + d multi_handle * value CURLM * + d s value like(curl_socket_t) + d ev_bitmask 10i 0 value + d running_handles... + d 10i 0 + * + d curl_multi_socket_all... + d pr extproc('curl_multi_socket_all') + d like(CURLMcode) + d multi_handle * value CURLM * + d running_handles... + d 10i 0 + * + d curl_multi_timeout... + d pr extproc('curl_multi_timeout') + d like(CURLMcode) + d multi_handle * value CURLM * + d milliseconds 10i 0 + * + * Multiple prototypes for vararg procedure curl_multi_setopt. + * + d curl_multi_setopt_long... + d pr extproc('curl_multi_setopt') + d like(CURLMcode) + d multi_handle * value CURLM * + d option value like(CURLMoption) + d longarg 10i 0 value options(*nopass) + * + d curl_multi_setopt_object... + d pr extproc('curl_multi_setopt') + d like(CURLMcode) + d multi_handle * value CURLM * + d option value like(CURLMoption) + d objectarg * value options(*string: *nopass) + * + d curl_multi_setopt_function... + d pr extproc('curl_multi_setopt') + d like(CURLMcode) + d multi_handle * value CURLM * + d option value like(CURLMoption) + d functionarg * value procptr options(*nopass) + * + d curl_multi_setopt_offset... + d pr extproc('curl_multi_setopt') + d like(CURLMcode) + d multi_handle * value CURLM * + d option value like(CURLMoption) + d offsetarg value like(curl_off_t) + d options(*nopass) + * + * + d curl_multi_assign... + d pr extproc('curl_multi_assign') + d like(CURLMcode) + d multi_handle * value CURLM * + d sockfd value like(curl_socket_t) + d sockp * value void * + * + d curl_multi_get_handles... + d pr * extproc('curl_multi_get_handles') CURL ** + d multi_handle * value CURLM * + * + d curl_url pr * extproc('curl_url') CURLU * + * + d curl_url_cleanup... + d pr extproc('curl_url_cleanup') + d handle * value CURLU * + * + d curl_url_dup pr * extproc('curl_url_dup') CURLU * + d in * value CURLU * + * + d curl_url_get pr extproc('curl_url_get') + d like(CURLUcode) + d handle * value CURLU * + d what value like(CURLUPart) + d part * char ** + d flags 10u 0 value + * + d curl_url_set pr extproc('curl_url_set') + d like(CURLUcode) + d handle * value CURLU * + d what value like(CURLUPart) + d part * value options(*string) + d flags 10u 0 value + * + d curl_url_strerror... + d pr * extproc('curl_url_strerror') const char * + d code value like(CURLUcode) + * + d curl_easy_option_by_name... + d pr * extproc('curl_easy_option_by_name') curl_easyoption * + d name * value options(*string) + * + d curl_easy_option_by_id... + d pr * extproc('curl_easy_option_by_id') curl_easyoption * + d id value like(CURLoption) + * + d curl_easy_option_next... + d pr * extproc('curl_easy_next') curl_easyoption * + d prev * value curl_easyoption * + * + d curl_ws_recv pr extproc('curl_ws_recv') + d like(CURLcode) + d curl * value CURL * + d buffer * value void * + d buflen 10u 0 value size_t + d recv 10u 0 size_t * + d metap likeds(curl_ws_frame) + * + d curl_ws_send pr extproc('curl_ws_send') + d like(CURLcode) + d curl * value CURL * + d buffer * value const void * + d buflen 10u 0 value size_t + d sent 10u 0 size_t * + d framesize like(curl_off_t) + d sendflags 10u 0 value + * + d curl_ws_meta pr * extproc('curl_ws_meta') curl_ws_frame * + d curl * value CURL * + * + d curl_easy_header... + d pr extproc('curl_easy_header') curl_header * + d like(CURLHcode) + d curl * value CURL * + d name * value options(*string) const char * + d index 10u 0 value size_t + d origin 10u 0 value + d request 10i 0 value + d hout * curl_header ** + * + d curl_easy_nextheader... + d pr * extproc('curl_easy_nextheader') curl_header * + d curl * value CURL * + d origin 10u 0 value + d request 10i 0 value + d prev * value curl_header * + * + ************************************************************************** + * CCSID wrapper procedure prototypes + ************************************************************************** + * + d curl_version_ccsid... + d pr * extproc('curl_version_ccsid') + d ccsid 10u 0 value + * + d curl_easy_escape_ccsid... + d pr * extproc('curl_easy_escape_ccsid') char * + d handle * value CURL * + d string * value options(*string) + d length 10i 0 value + d ccsid 10u 0 value + * + d curl_easy_unescape_ccsid... + d pr * extproc('curl_easy_unescape_ccsid') char * + d handle * value CURL * + d string * value options(*string) + d length 10i 0 value + d outlength 10i 0 options(*omit) + d ccsid 10u 0 value + * + d curl_slist_append_ccsid... + d pr * extproc('curl_slist_append_ccsid') struct curl_slist * + d list * value struct curl_slist * + d data * value options(*string) const char * + d ccsid 10u 0 value + * + d curl_getdate_ccsid... + d pr 10i 0 extproc('curl_getdate_ccsid') time_t + d p * value options(*string) const char * + d unused 10i 0 const options(*omit) time_t + d ccsid 10u 0 value + * + d curl_version_info_ccsid... + d pr * extproc('curl_version_info_ccsid') c_i_version_data * + d version value like(CURLversion) + d ccsid 10u 0 value + * + d curl_easy_strerror_ccsid... + d pr * extproc('curl_easy_strerror_ccsid') const char * + d code value like(CURLcode) + d ccsid 10u 0 value + * + d curl_share_strerror_ccsid... + d pr * extproc('curl_share_strerror_ccsid') const char * + d code value like(CURLSHcode) + d ccsid 10u 0 value + * + d curl_multi_strerror_ccsid... + d pr * extproc('curl_multi_strerror_ccsid') char * + d code value like(CURLMcode) + d ccsid 10u 0 value + * + * May be used for strings and structures. + d curl_easy_getinfo_ccsid... + d pr extproc('curl_easy_getinfo_ccsid') + d like(CURLcode) + d curl * value CURL * + d info value like(CURLINFO) + d ptrarg * options(*nopass) char * + d ccsid 10u 0 value options(*nopass) + * + d curl_certinfo_free_all... + d pr extproc('curl_certinfo_free_all') + d info * value + * + d curl_formadd_ccsid... + d pr extproc('curl_formadd_ccsid') + d like(CURLFORMcode) + d httppost * curl_httppost * + d lastpost * curl_httppost * + d option1 value like(CURLFORMoption) CURLFORM_ARRAY + d options(*nopass) + d object1 * value options(*string: *nopass) + d option2 value like(CURLFORMoption) CURLFORM_END + d options(*nopass) + * + d curl_formget_ccsid... + d pr 10i 0 extproc('curl_formget_ccsid') + d form * value curl_httppost * + d arg * value + d append value like(curl_formget_callback) + d ccsid 10u 0 value + * + d curl_form_long_value... + d pr * extproc('curl_form_long_value') + d value 10i 0 value curl_httppost * + * + d curl_easy_setopt_ccsid... + d pr extproc('curl_easy_setopt_ccsid') + d like(CURLcode) + d curl * value CURL * + d option value like(CURLoption) + d objectarg * value options(*string: *nopass) + d ccsid 10u 0 value options(*nopass) + * + d curl_easy_setopt_blob_ccsid... + d pr extproc('curl_easy_setopt_ccsid') + d like(CURLcode) + d curl * value CURL * + d option value like(CURLoption) + d blob const likeds(curl_blob) + d options(*nopass) + d ccsid 10u 0 value options(*nopass) + * + d curl_pushheader_bynum_ccsid... + d pr * extproc( char * + d 'curl_pushheader_bynum_ccsid') + d h * value curl_pushheaders * + d num 10u 0 value + d ccsid 10u 0 value + * + d curl_pushheader_byname_ccsid... + d pr * extproc( char * + d 'curl_pushheader_byname_ccsid') + d h * value curl_pushheaders * + d header * value options(*string) const char * + d ccsidin 10u 0 value + d ccsidout 10u 0 value + * + d curl_mime_name_ccsid... + d pr extproc('curl_mime_name_ccsid') + d like(CURLcode) + d part * value curl_mimepart * + d name * value options(*string) + d ccsid 10u 0 value + * + d curl_mime_filename_ccsid... + d pr extproc('curl_mime_filename_ccsid') + d like(CURLcode) + d part * value curl_mimepart * + d filename * value options(*string) + d ccsid 10u 0 value + * + d curl_mime_type_ccsid... + d pr extproc('curl_mime_type_ccsid') + d like(CURLcode) + d part * value curl_mimepart * + d mimetype * value options(*string) + d ccsid 10u 0 value + * + d curl_mime_encoder_ccsid... + d pr extproc('curl_mime_encoder_ccsid') + d like(CURLcode) + d part * value curl_mimepart * + d encoding * value options(*string) + d ccsid 10u 0 value + * + d curl_mime_data_ccsid... + d pr extproc('curl_mime_data_ccsid') + d like(CURLcode) + d part * value curl_mimepart * + d data * value options(*string) + d datasize 10u 0 value size_t + d ccsid 10u 0 value + * + d curl_mime_filedata_ccsid... + d pr extproc('curl_mime_filedata_ccsid') + d like(CURLcode) + d part * value curl_mimepart * + d filename * value options(*string) + d ccsid 10u 0 value + * + d curl_url_get_ccsid... + d pr extproc('curl_url_get_ccsid') + d like(CURLUcode) + d handle * value CURLU * + d what value like(CURLUPart) + d part * char ** + d flags 10u 0 value + d ccsid 10u 0 value + * + d curl_url_set_ccsid... + d pr extproc('curl_url_set_ccsid') + d like(CURLUcode) + d handle * value CURLU * + d what value like(CURLUPart) + d part * value options(*string) + d flags 10u 0 value + d ccsid 10u 0 value + * + d curl_url_strerror_ccsid... + d pr * extproc('curl_url_strerror_ccsid') const char * + d code value like(CURLUcode) + d ccsid 10u 0 value + * + d curl_easy_option_by_name_ccsid... + d pr * extproc( curl_easyoption * + d 'curl_easy_option_by_name_ccsid') + d name * value options(*string) + d ccsid 10u 0 value + * + d curl_easy_option_get_name_ccsid... + d pr * extproc( const char * + d 'curl_easy_option_get_name_ccsid') + d option * value curl_easyoption * + d ccsid 10u 0 value + * + d curl_easy_header_ccsid... + d pr extproc('curl_easy_header_ccsid') curl_header * + d like(CURLHcode) + d curl * value CURL * + d name * value options(*string) const char * + d index 10u 0 value size_t + d origin 10u 0 value + d request 10i 0 value + d hout * curl_header ** + d ccsid 10u 0 value + * + d curl_from_ccsid... + d pr * extproc('curl_from_ccsid') const char * + d s * value options(*string) const char * + d ccsid 10u 0 value + * + d curl_to_ccsid... + d pr * extproc('curl_to_ccsid') const char * + d s * value options(*string) const char * + d ccsid 10u 0 value + * + ************************************************************************** + * Procedure overloading + ************************************************************************** + * + /if defined(*V7R4M0) + d curl_easy_setopt_RPGnum_... + d pr extproc('curl_easy_setopt_RPGnum_') + d like(CURLcode) + d curl * value CURL * + d option value like(CURLoption) + d numarg 20i 0 value + * + d curl_easy_setopt... + d pr like(CURLcode) + d overload(curl_easy_setopt_RPGnum_: + d curl_easy_setopt_object: + d curl_easy_setopt_function) + * + d curl_multi_setopt_RPGnum_... + d pr extproc('curl_multi_setopt_RPGnum_') + d like(CURLcode) + d curl * value CURLM * + d option value like(CURLMoption) + d numarg 20i 0 value + * + d curl_multi_setopt... + d pr like(CURLcode) + d overload(curl_multi_setopt_RPGnum_: + d curl_multi_setopt_object: + d curl_multi_setopt_function) + * + d curl_share_setopt... + d pr like(CURLcode) + d overload(curl_share_setopt_int: + d curl_share_setopt_ptr: + d curl_share_setopt_proc) + * + d curl_easy_getinfo... + d pr like(CURLcode) + d overload(curl_easy_getinfo_long: + d curl_easy_getinfo_off_t: + d curl_easy_getinfo_double: + d curl_easy_getinfo_ptr) + /endif + * + /endif diff --git a/third_party/curl/packages/OS400/curlcl.c b/third_party/curl/packages/OS400/curlcl.c new file mode 100644 index 0000000..02edcd6 --- /dev/null +++ b/third_party/curl/packages/OS400/curlcl.c @@ -0,0 +1,177 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * + ***************************************************************************/ + +/* CL interface program to curl cli tool. */ + +#include +#include + +#include +#include +#include + +#ifndef CURLPGM +#define CURLPGM "CURL" +#endif + +/* Variable-length string, with 16-bit length. */ +struct vary2 { + short len; + char string[5000]; +}; + +/* Arguments from CL command. */ +struct arguments { + char *pgm; /* Program name. */ + struct vary2 *cmdargs; /* Command line arguments. */ +}; + +static int +is_ifs(char c) +{ + return c == ' ' || c == '\t' || c == '\r' || c == '\n'; +} + +static int +parse_command_line(const char *cmdargs, size_t len, + size_t *argc, char **argv, + size_t *argsize, char *argbuf) +{ + const char *endline = cmdargs + len; + char quote = '\0'; + int inarg = 0; + + *argc = 0; + *argsize = 0; + + while(cmdargs < endline) { + char c = *cmdargs++; + + if(!inarg) { + /* Skip argument separator. */ + if(is_ifs(c)) + continue; + + /* Start a new argument. */ + ++*argc; + if(argv) + *argv++ = argbuf; + inarg = 1; + } + + /* Check for quoting end. */ + if(quote && quote == c) { + quote = '\0'; + continue; + } + + /* Check for backslash-escaping. */ + if(quote != '\'' && c == '\\') { + if(cmdargs >= endline) { + fputs("Trailing backslash in command\n", stderr); + return -1; + } + c = *cmdargs++; + } + else if(!quote && is_ifs(c)) { /* Check for end of argument. */ + inarg = 0; + c = '\0'; /* Will store a string terminator. */ + } + + /* Store argument character and count it. */ + if(argbuf) + *argbuf++ = c; + ++*argsize; + } + + if(quote) { + fprintf(stderr, "Unterminated quote: %c\n", quote); + return -1; + } + + /* Terminate last argument. */ + if(inarg) { + if(argbuf) + *argbuf = '\0'; + ++*argsize; + } + + /* Terminate argument list. */ + if(argv) + *argv = NULL; + + return 0; +} + + +int +main(int argsc, struct arguments *args) +{ + size_t argc; + char **argv; + size_t argsize; + int i; + int exitcode; + char library[11]; + + /* Extract current program library name. */ + for(i = 0; i < 10; i++) { + char c = args->pgm[i]; + + if(!c || c == '/') + break; + + library[i] = c; + } + library[i] = '\0'; + + /* Measure arguments size. */ + exitcode = parse_command_line(args->cmdargs->string, args->cmdargs->len, + &argc, NULL, &argsize, NULL); + + if(!exitcode) { + /* Allocate space for parsed arguments. */ + argv = (char **) malloc((argc + 1) * sizeof(*argv) + argsize); + if(!argv) { + fputs("Memory allocation error\n", stderr); + exitcode = -2; + } + else { + _SYSPTR pgmptr = rslvsp(WLI_PGM, (char *) CURLPGM, library, _AUTH_NONE); + _LU_Work_Area_T *luwrka = (_LU_Work_Area_T *) _LUWRKA(); + + parse_command_line(args->cmdargs->string, args->cmdargs->len, + &argc, argv, &argsize, (char *) (argv + argc + 1)); + + /* Call program. */ + _CALLPGMV((void *) &pgmptr, argv, argc); + exitcode = luwrka->LU_RC; + + free(argv); + } + } + + return exitcode; +} diff --git a/third_party/curl/packages/OS400/curlmain.c b/third_party/curl/packages/OS400/curlmain.c new file mode 100644 index 0000000..1b030b7 --- /dev/null +++ b/third_party/curl/packages/OS400/curlmain.c @@ -0,0 +1,121 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * + ***************************************************************************/ + +/* + * QADRT/QADRTMAIN2 substitution program. + * This is needed because the IBM-provided QADRTMAIN2 does not + * properly translate arguments by default or if no locale is provided. + */ + +#include +#include +#include +#include +#include + +/* Do not use qadrt.h since it defines unneeded static procedures. */ +extern void QadrtInit(void); +extern int QadrtFreeConversionTable(void); +extern int QadrtFreeEnviron(void); +extern char * setlocale_a(int, const char *); + + +/* The ASCII main program. */ +extern int main_a(int argc, char * * argv); + +/* Global values of original EBCDIC arguments. */ +int ebcdic_argc; +char ** ebcdic_argv; + + +int main(int argc, char **argv) +{ + int i; + int j; + iconv_t cd; + size_t bytecount = 0; + char *inbuf; + char *outbuf; + size_t inbytesleft; + size_t outbytesleft; + char dummybuf[128]; + char tocode[32]; + char fromcode[32]; + + ebcdic_argc = argc; + ebcdic_argv = argv; + + /* Build the encoding converter. */ + strncpy(tocode, "IBMCCSID01208", sizeof(tocode)); /* Use UTF-8. */ + strncpy(fromcode, "IBMCCSID000000000010", sizeof(fromcode)); + cd = iconv_open(tocode, fromcode); + + /* Measure the arguments. */ + for(i = 0; i < argc; i++) { + inbuf = argv[i]; + do { + inbytesleft = 0; + outbuf = dummybuf; + outbytesleft = sizeof(dummybuf); + j = iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft); + bytecount += outbuf - dummybuf; + } while(j == -1 && errno == E2BIG); + + /* Reset the shift state. */ + iconv(cd, NULL, &inbytesleft, &outbuf, &outbytesleft); + } + + /* Allocate memory for the ASCII arguments and vector. */ + argv = (char **) malloc((argc + 1) * sizeof(*argv) + bytecount); + + /* Build the vector and convert argument encoding. */ + outbuf = (char *) (argv + argc + 1); + outbytesleft = bytecount; + + for(i = 0; i < argc; i++) { + argv[i] = outbuf; + inbuf = ebcdic_argv[i]; + inbytesleft = 0; + iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft); + iconv(cd, NULL, &inbytesleft, &outbuf, &outbytesleft); + } + + iconv_close(cd); + argv[argc] = NULL; + + /* Try setting the locale regardless of QADRT_ENV_LOCALE. */ + setlocale_a(LC_ALL, ""); + + /* Call the program. */ + i = main_a(argc, argv); + + /* Clean-up allocated items. */ + free((char *) argv); + QadrtFreeConversionTable(); + QadrtFreeEnviron(); + + /* Terminate. */ + return i; +} diff --git a/third_party/curl/packages/OS400/initscript.sh b/third_party/curl/packages/OS400/initscript.sh new file mode 100755 index 0000000..cdb8fab --- /dev/null +++ b/third_party/curl/packages/OS400/initscript.sh @@ -0,0 +1,292 @@ +#!/bin/sh +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +CLcommand() +{ + /usr/bin/system "${@}" || exit 1 +} + +setenv() + +{ + # Define and export. + + eval "${1}=${2}" + export "${1?}" +} + + +case "${SCRIPTDIR}" in +/*) ;; +*) SCRIPTDIR="$(pwd)/${SCRIPTDIR}" +esac + +while true +do case "${SCRIPTDIR}" in + */.) SCRIPTDIR="${SCRIPTDIR%/.}";; + *) break;; + esac +done + +# The script directory is supposed to be in $TOPDIR/packages/os400. + +TOPDIR=$(dirname "${SCRIPTDIR}") +TOPDIR=$(dirname "${TOPDIR}") +export SCRIPTDIR TOPDIR + +# Extract the SONAME from the library makefile. + +SONAME="$(sed -e '/^VERSIONCHANGE=/!d;s/^.*=\([0-9]*\).*/\1/' \ + < "${TOPDIR}/lib/Makefile.soname")" +export SONAME + +# Get OS/400 configuration parameters. + +. "${SCRIPTDIR}/config400.default" +if [ -f "${SCRIPTDIR}/config400.override" ] +then . "${SCRIPTDIR}/config400.override" +fi + +# Need to get the version definitions. + +LIBCURL_VERSION=$(grep '^#define *LIBCURL_VERSION ' \ + "${TOPDIR}/include/curl/curlver.h" | + sed 's/.*"\(.*\)".*/\1/') +LIBCURL_VERSION_MAJOR=$(grep '^#define *LIBCURL_VERSION_MAJOR ' \ + "${TOPDIR}/include/curl/curlver.h" | + sed 's/^#define *LIBCURL_VERSION_MAJOR *\([^ ]*\).*/\1/') +LIBCURL_VERSION_MINOR=$(grep '^#define *LIBCURL_VERSION_MINOR ' \ + "${TOPDIR}/include/curl/curlver.h" | + sed 's/^#define *LIBCURL_VERSION_MINOR *\([^ ]*\).*/\1/') +LIBCURL_VERSION_PATCH=$(grep '^#define *LIBCURL_VERSION_PATCH ' \ + "${TOPDIR}/include/curl/curlver.h" | + sed 's/^#define *LIBCURL_VERSION_PATCH *\([^ ]*\).*/\1/') +LIBCURL_VERSION_NUM=$(grep '^#define *LIBCURL_VERSION_NUM ' \ + "${TOPDIR}/include/curl/curlver.h" | + sed 's/^#define *LIBCURL_VERSION_NUM *0x\([^ ]*\).*/\1/') +LIBCURL_TIMESTAMP=$(grep '^#define *LIBCURL_TIMESTAMP ' \ + "${TOPDIR}/include/curl/curlver.h" | + sed 's/.*"\(.*\)".*/\1/') +export LIBCURL_VERSION +export LIBCURL_VERSION_MAJOR LIBCURL_VERSION_MINOR LIBCURL_VERSION_PATCH +export LIBCURL_VERSION_NUM LIBCURL_TIMESTAMP + +################################################################################ +# +# OS/400 specific definitions. +# +################################################################################ + +LIBIFSNAME="/QSYS.LIB/${TARGETLIB}.LIB" + + +################################################################################ +# +# Procedures. +# +################################################################################ + +# action_needed dest [src] +# +# dest is an object to build +# if specified, src is an object on which dest depends. +# +# exit 0 (succeeds) if some action has to be taken, else 1. + +action_needed() + +{ + [ ! -e "${1}" ] && return 0 + [ -n "${2}" ] || return 1 + # shellcheck disable=SC3013 + [ "${1}" -ot "${2}" ] && return 0 + return 1 +} + + +# canonicalize_path path +# +# Return canonicalized path as: +# - Absolute +# - No . or .. component. + +canonicalize_path() + +{ + if expr "${1}" : '^/' > /dev/null + then P="${1}" + else P="$(pwd)/${1}" + fi + + R= + IFSSAVE="${IFS}" + IFS="/" + + for C in ${P} + do IFS="${IFSSAVE}" + case "${C}" in + .) ;; + ..) R="$(expr "${R}" : '^\(.*/\)..*')" + ;; + ?*) R="${R}${C}/" + ;; + *) ;; + esac + done + + IFS="${IFSSAVE}" + echo "/$(expr "${R}" : '^\(.*\)/')" +} + + +# make_module module_name source_name [additional_definitions] +# +# Compile source name into ASCII module if needed. +# As side effect, append the module name to variable MODULES. +# Set LINK to "YES" if the module has been compiled. + +make_module() + +{ + MODULES="${MODULES} ${1}" + MODIFSNAME="${LIBIFSNAME}/${1}.MODULE" + action_needed "${MODIFSNAME}" "${2}" || return 0; + SRCDIR="$(dirname "$(canonicalize_path "${2}")")" + + # #pragma convert has to be in the source file itself, i.e. + # putting it in an include file makes it only active + # for that include file. + # Thus we build a temporary file with the pragma prepended to + # the source file and we compile that temporary file. + + { + echo "#line 1 \"${2}\"" + echo "#pragma convert(819)" + echo "#line 1" + cat "${2}" + } > __tmpsrcf.c + CMD="CRTCMOD MODULE(${TARGETLIB}/${1}) SRCSTMF('__tmpsrcf.c')" + CMD="${CMD} SYSIFCOPT(*IFS64IO *ASYNCSIGNAL)" +# CMD="${CMD} OPTION(*INCDIRFIRST *SHOWINC *SHOWSYS)" + CMD="${CMD} OPTION(*INCDIRFIRST)" + CMD="${CMD} LOCALETYPE(*LOCALE) FLAG(10)" + CMD="${CMD} INCDIR('${QADRTDIR}/include'" + CMD="${CMD} '${TOPDIR}/include/curl' '${TOPDIR}/include' '${SRCDIR}'" + CMD="${CMD} '${TOPDIR}/packages/OS400'" + + if [ "${WITH_ZLIB}" != "0" ] + then CMD="${CMD} '${ZLIB_INCLUDE}'" + fi + + if [ "${WITH_LIBSSH2}" != "0" ] + then CMD="${CMD} '${LIBSSH2_INCLUDE}'" + fi + + CMD="${CMD} ${INCLUDES})" + CMD="${CMD} TGTCCSID(${TGTCCSID}) TGTRLS(${TGTRLS})" + CMD="${CMD} OUTPUT(${OUTPUT})" + CMD="${CMD} OPTIMIZE(${OPTIMIZE})" + CMD="${CMD} DBGVIEW(${DEBUG})" + + DEFINES="${3} 'qadrt_use_inline'" + + if [ "${WITH_ZLIB}" != "0" ] + then DEFINES="${DEFINES} HAVE_LIBZ" + fi + + if [ "${WITH_LIBSSH2}" != "0" ] + then DEFINES="${DEFINES} USE_LIBSSH2" + fi + + if [ -n "${DEFINES}" ] + then CMD="${CMD} DEFINE(${DEFINES})" + fi + + CLcommand "${CMD}" + rm -f __tmpsrcf.c + # shellcheck disable=SC2034 + LINK=YES +} + + +# Determine DB2 object name from IFS name. + +db2_name() + +{ + if [ "${2}" = 'nomangle' ] + then basename "${1}" | + tr 'a-z-' 'A-Z_' | + sed -e 's/\..*//' \ + -e 's/^\(.\).*\(.........\)$/\1\2/' + else basename "${1}" | + tr 'a-z-' 'A-Z_' | + sed -e 's/\..*//' \ + -e 's/^CURL_*/C/' \ + -e 's/^TOOL_*/T/' \ + -e 's/^\(.\).*\(.........\)$/\1\2/' + fi +} + + +# Copy IFS file replacing version info. + +versioned_copy() + +{ + sed -e "s/@LIBCURL_VERSION@/${LIBCURL_VERSION}/g" \ + -e "s/@LIBCURL_VERSION_MAJOR@/${LIBCURL_VERSION_MAJOR}/g" \ + -e "s/@LIBCURL_VERSION_MINOR@/${LIBCURL_VERSION_MINOR}/g" \ + -e "s/@LIBCURL_VERSION_PATCH@/${LIBCURL_VERSION_PATCH}/g" \ + -e "s/@LIBCURL_VERSION_NUM@/${LIBCURL_VERSION_NUM}/g" \ + -e "s/@LIBCURL_TIMESTAMP@/${LIBCURL_TIMESTAMP}/g" \ + < "${1}" > "${2}" +} + + +# Get definitions from a make file. +# The `sed' statement works as follows: +# - Join \nl-separated lines. +# - Retain only lines that begins with "identifier =". +# - Replace @...@ substitutions by shell variable references. +# - Turn these lines into shell variable assignments. + +get_make_vars() + +{ + eval "$(sed -e ': begin' \ + -e '/\\$/{' \ + -e 'N' \ + -e 's/\\\n/ /' \ + -e 'b begin' \ + -e '}' \ + -e 's/[[:space:]][[:space:]]*/ /g' \ + -e '/^[A-Za-z_][A-Za-z0-9_]* *=/!d' \ + -e 's/@\([A-Za-z0-9_]*\)@/${\1}/g' \ + -e 's/ *= */=/' \ + -e 's/=\(.*[^ ]\) *$/="\1"/' \ + -e 's/\$(\([^)]*\))/${\1}/g' \ + < "${1}")" +} diff --git a/third_party/curl/packages/OS400/make-include.sh b/third_party/curl/packages/OS400/make-include.sh new file mode 100755 index 0000000..e30e950 --- /dev/null +++ b/third_party/curl/packages/OS400/make-include.sh @@ -0,0 +1,106 @@ +#!/bin/sh +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +# Installation of the header files in the OS/400 library. +# + +SCRIPTDIR=$(dirname "${0}") +. "${SCRIPTDIR}/initscript.sh" +cd "${TOPDIR}/include" || exit 1 + + +# Create the OS/400 source program file for the header files. + +SRCPF="${LIBIFSNAME}/H.FILE" + +if action_needed "${SRCPF}" +then CMD="CRTSRCPF FILE(${TARGETLIB}/H) RCDLEN(112)" + CMD="${CMD} CCSID(${TGTCCSID}) TEXT('curl: Header files')" + CLcommand "${CMD}" +fi + + +# Create the IFS directory for the header files. + +IFSINCLUDE="${IFSDIR}/include/curl" + +if action_needed "${IFSINCLUDE}" +then mkdir -p "${IFSINCLUDE}" +fi + + +# Enumeration values are used as va_arg tagfields, so they MUST be +# integers. + +copy_hfile() + +{ + destfile="${1}" + srcfile="${2}" + shift + shift + sed -e '1i\ +#pragma enum(int)\ +' "${@}" -e '$a\ +#pragma enum(pop)\ +' < "${srcfile}" > "${destfile}" +} + +# Copy the header files. + +for HFILE in curl/*.h ${SCRIPTDIR}/ccsidcurl.h +do case "$(basename "${HFILE}" .h)" in + stdcheaders|typecheck-gcc) + continue;; + esac + + DEST="${SRCPF}/$(db2_name "${HFILE}" nomangle).MBR" + + if action_needed "${DEST}" "${HFILE}" + then copy_hfile "${DEST}" "${HFILE}" + IFSDEST="${IFSINCLUDE}/$(basename "${HFILE}")" + rm -f "${IFSDEST}" + ln -s "${DEST}" "${IFSDEST}" + fi +done + + +# Copy the ILE/RPG header file, setting-up version number. + +versioned_copy "${SCRIPTDIR}/curl.inc.in" "${SRCPF}/CURL.INC.MBR" +rm -f "${IFSINCLUDE}/curl.inc.rpgle" +ln -s "${SRCPF}/CURL.INC.MBR" "${IFSINCLUDE}/curl.inc.rpgle" + + +# Duplicate file H as CURL to support more include path forms. + +if action_needed "${LIBIFSNAME}/CURL.FILE" +then : +else CLcommand "DLTF FILE(${TARGETLIB}/CURL)" +fi + +CMD="CRTDUPOBJ OBJ(H) FROMLIB(${TARGETLIB}) OBJTYPE(*FILE) TOLIB(*FROMLIB)" +CMD="${CMD} NEWOBJ(CURL) DATA(*YES)" +CLcommand "${CMD}" diff --git a/third_party/curl/packages/OS400/make-lib.sh b/third_party/curl/packages/OS400/make-lib.sh new file mode 100755 index 0000000..e7b5b51 --- /dev/null +++ b/third_party/curl/packages/OS400/make-lib.sh @@ -0,0 +1,181 @@ +#!/bin/sh +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +# libcurl compilation script for the OS/400. +# + +SCRIPTDIR=$(dirname "${0}") +. "${SCRIPTDIR}/initscript.sh" +cd "${TOPDIR}/lib" || exit 1 + +# Need to have IFS access to the mih/cipher header file. + +if action_needed cipher.mih '/QSYS.LIB/QSYSINC.LIB/MIH.FILE/CIPHER.MBR' +then rm -f cipher.mih + ln -s '/QSYS.LIB/QSYSINC.LIB/MIH.FILE/CIPHER.MBR' cipher.mih +fi + + +# Create and compile the identification source file. + +{ + echo '#pragma comment(user, "libcurl version '"${LIBCURL_VERSION}"'")' + echo '#pragma comment(user, __DATE__)' + echo '#pragma comment(user, __TIME__)' + echo '#pragma comment(copyright, "Copyright (C) Daniel Stenberg et al. OS/400 version by P. Monnerat")' +} > os400.c +make_module OS400 os400.c BUILDING_LIBCURL +LINK= # No need to rebuild service program yet. +MODULES= + + +# Get source list (CSOURCES variable). + +get_make_vars Makefile.inc + + +# Compile the sources into modules. + +# shellcheck disable=SC2034 +INCLUDES="'$(pwd)'" + +make_module OS400SYS "${SCRIPTDIR}/os400sys.c" BUILDING_LIBCURL +make_module CCSIDCURL "${SCRIPTDIR}/ccsidcurl.c" BUILDING_LIBCURL + +for SRC in ${CSOURCES} +do MODULE=$(db2_name "${SRC}") + make_module "${MODULE}" "${SRC}" BUILDING_LIBCURL +done + + +# If needed, (re)create the static binding directory. + +if action_needed "${LIBIFSNAME}/${STATBNDDIR}.BNDDIR" +then LINK=YES +fi + +if [ -n "${LINK}" ] +then rm -rf "${LIBIFSNAME}/${STATBNDDIR}.BNDDIR" + CMD="CRTBNDDIR BNDDIR(${TARGETLIB}/${STATBNDDIR})" + CMD="${CMD} TEXT('LibCurl API static binding directory')" + CLcommand "${CMD}" + + for MODULE in ${MODULES} + do CMD="ADDBNDDIRE BNDDIR(${TARGETLIB}/${STATBNDDIR})" + CMD="${CMD} OBJ((${TARGETLIB}/${MODULE} *MODULE))" + CLcommand "${CMD}" + done +fi + + +# The exportation file for service program creation must be in a DB2 +# source file, so make sure it exists. + +if action_needed "${LIBIFSNAME}/TOOLS.FILE" +then CMD="CRTSRCPF FILE(${TARGETLIB}/TOOLS) RCDLEN(112)" + CMD="${CMD} TEXT('curl: build tools')" + CLcommand "${CMD}" +fi + + +# Gather the list of symbols to export. +# - Unfold lines from the header files so that they contain a semicolon. +# - Keep only CURL_EXTERN definitions. +# - Remove the CURL_DEPRECATED and CURL_TEMP_PRINTF macro calls. +# - Drop the parenthesized function arguments and what follows. +# - Keep the trailing function name only. + +EXPORTS=$(cat "${TOPDIR}"/include/curl/*.h "${SCRIPTDIR}/ccsidcurl.h" | + sed -e 'H;s/.*//;x;s/\n//;s/.*/& /' \ + -e '/^CURL_EXTERN[[:space:]]/!d' \ + -e '/\;/!{x;d;}' \ + -e 's/ CURL_DEPRECATED([^)]*)//g' \ + -e 's/ CURL_TEMP_PRINTF([^)]*)//g' \ + -e 's/[[:space:]]*(.*$//' \ + -e 's/^.*[^A-Za-z0-9_]\([A-Za-z0-9_]*\)$/\1/') + + +# Create the service program exportation file in DB2 member if needed. + +BSF="${LIBIFSNAME}/TOOLS.FILE/BNDSRC.MBR" + +if action_needed "${BSF}" Makefile.am +then LINK=YES +fi + +if [ -n "${LINK}" ] +then echo " STRPGMEXP PGMLVL(*CURRENT) SIGNATURE('LIBCURL_${SONAME}')" \ + > "${BSF}" + for EXPORT in ${EXPORTS} + do echo ' EXPORT SYMBOL("'"${EXPORT}"'")' >> "${BSF}" + done + + echo ' ENDPGMEXP' >> "${BSF}" +fi + + +# Build the service program if needed. + +if action_needed "${LIBIFSNAME}/${SRVPGM}.SRVPGM" +then LINK=YES +fi + +if [ -n "${LINK}" ] +then CMD="CRTSRVPGM SRVPGM(${TARGETLIB}/${SRVPGM})" + CMD="${CMD} SRCFILE(${TARGETLIB}/TOOLS) SRCMBR(BNDSRC)" + CMD="${CMD} MODULE(${TARGETLIB}/OS400)" + CMD="${CMD} BNDDIR(${TARGETLIB}/${STATBNDDIR}" + if [ "${WITH_ZLIB}" != 0 ] + then CMD="${CMD} ${ZLIB_LIB}/${ZLIB_BNDDIR}" + liblist -a "${ZLIB_LIB}" + fi + if [ "${WITH_LIBSSH2}" != 0 ] + then CMD="${CMD} ${LIBSSH2_LIB}/${LIBSSH2_BNDDIR}" + liblist -a "${LIBSSH2_LIB}" + fi + CMD="${CMD})" + CMD="${CMD} BNDSRVPGM(QADRTTS QGLDCLNT QGLDBRDR)" + CMD="${CMD} TEXT('curl API library')" + CMD="${CMD} TGTRLS(${TGTRLS})" + CLcommand "${CMD}" + LINK=YES +fi + + +# If needed, (re)create the dynamic binding directory. + +if action_needed "${LIBIFSNAME}/${DYNBNDDIR}.BNDDIR" +then LINK=YES +fi + +if [ -n "${LINK}" ] +then rm -rf "${LIBIFSNAME}/${DYNBNDDIR}.BNDDIR" + CMD="CRTBNDDIR BNDDIR(${TARGETLIB}/${DYNBNDDIR})" + CMD="${CMD} TEXT('LibCurl API dynamic binding directory')" + CLcommand "${CMD}" + CMD="ADDBNDDIRE BNDDIR(${TARGETLIB}/${DYNBNDDIR})" + CMD="${CMD} OBJ((*LIBL/${SRVPGM} *SRVPGM))" + CLcommand "${CMD}" +fi diff --git a/third_party/curl/packages/OS400/make-src.sh b/third_party/curl/packages/OS400/make-src.sh new file mode 100755 index 0000000..6775f98 --- /dev/null +++ b/third_party/curl/packages/OS400/make-src.sh @@ -0,0 +1,101 @@ +#!/bin/sh +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +# Command line interface tool compilation script for the OS/400. + +SCRIPTDIR=$(dirname "${0}") +. "${SCRIPTDIR}/initscript.sh" +cd "${TOPDIR}/src" || exit 1 + + +# Get source lists. +# CURL_CFILES are in the current directory. +# CURLX_CFILES are in the lib directory and need to be recompiled because +# some function names change using macros. + +get_make_vars Makefile.inc + + +# Compile the sources into modules. + +# shellcheck disable=SC2034 +LINK= +MODULES= +# shellcheck disable=SC2034 +INCLUDES="'${TOPDIR}/lib'" + +for SRC in ${CURLX_CFILES} +do MODULE=$(db2_name "${SRC}") + MODULE=$(db2_name "X${MODULE}") + make_module "${MODULE}" "${SRC}" +done + +for SRC in ${CURL_CFILES} +do MODULE=$(db2_name "${SRC}") + make_module "${MODULE}" "${SRC}" +done + + +# Link modules into program. + +MODULES="$(echo "${MODULES}" | sed "s/[^ ][^ ]*/${TARGETLIB}\/&/g")" +CMD="CRTPGM PGM(${TARGETLIB}/${CURLPGM})" +CMD="${CMD} ENTMOD(${TARGETLIB}/CURLMAIN)" +CMD="${CMD} MODULE(${MODULES})" +CMD="${CMD} BNDSRVPGM(${TARGETLIB}/${SRVPGM} QADRTTS)" +CMD="${CMD} TGTRLS(${TGTRLS})" +CLcommand "${CMD}" + + +# Create the IFS command. + +IFSBIN="${IFSDIR}/bin" + +if action_needed "${IFSBIN}" +then mkdir -p "${IFSBIN}" +fi + +rm -f "${IFSBIN}/curl" +ln -s "/QSYS.LIB/${TARGETLIB}.LIB/${CURLPGM}.PGM" "${IFSBIN}/curl" + + +# Create the CL interface program. + +if action_needed "${LIBIFSNAME}/CURLCL.PGM" "${SCRIPTDIR}/curlcl.c" +then CMD="CRTBNDC PGM(${TARGETLIB}/${CURLCLI})" + CMD="${CMD} SRCSTMF('${SCRIPTDIR}/curlcl.c')" + CMD="${CMD} DEFINE('CURLPGM=\"${CURLPGM}\"')" + CMD="${CMD} TGTCCSID(${TGTCCSID})" + CLcommand "${CMD}" +fi + + +# Create the CL command. + +if action_needed "${LIBIFSNAME}/${CURLCMD}.CMD" "${SCRIPTDIR}/curl.cmd" +then CMD="CRTCMD CMD(${TARGETLIB}/${CURLCMD}) PGM(${TARGETLIB}/${CURLCLI})" + CMD="${CMD} SRCSTMF('${SCRIPTDIR}/curl.cmd')" + CLcommand "${CMD}" +fi diff --git a/third_party/curl/packages/OS400/make-tests.sh b/third_party/curl/packages/OS400/make-tests.sh new file mode 100755 index 0000000..8ff64d2 --- /dev/null +++ b/third_party/curl/packages/OS400/make-tests.sh @@ -0,0 +1,151 @@ +#!/bin/sh +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +# tests compilation script for the OS/400. +# + + +SCRIPTDIR=$(dirname "${0}") +. "${SCRIPTDIR}/initscript.sh" +cd "${TOPDIR}/tests" || exit 1 + + +# Build programs in a directory. + +build_all_programs() + +{ + # Compile all programs. + # The list is found in variable "noinst_PROGRAMS" + + # shellcheck disable=SC2034 + INCLUDES="'$(pwd)' '${TOPDIR}/lib' '${TOPDIR}/src'" + MODS="${1}" + SRVPGMS="${2}" + + # shellcheck disable=SC2154 + for PGM in ${noinst_PROGRAMS} + do DB2PGM=$(db2_name "${PGM}") + PGMIFSNAME="${LIBIFSNAME}/${DB2PGM}.PGM" + + # Extract preprocessor symbol definitions from + # compilation options for the program. + + PGMCFLAGS="$(eval echo "\${${PGM}_CFLAGS}")" + PGMDFNS= + + for FLAG in ${PGMCFLAGS} + do case "${FLAG}" in + -D?*) # shellcheck disable=SC2001 + DEFINE="$(echo "${FLAG}" | sed 's/^..//')" + PGMDFNS="${PGMDFNS} '${DEFINE}'" + ;; + esac + done + + # Compile all C sources for the program into modules. + + PGMSOURCES="$(eval echo "\${${PGM}_SOURCES}")" + LINK= + MODULES= + + for SOURCE in ${PGMSOURCES} + do case "${SOURCE}" in + *.c) # Special processing for libxxx.c files: + # their module name is determined + # by the target PROGRAM name. + + case "${SOURCE}" in + lib*.c) MODULE="${DB2PGM}" + ;; + *) MODULE=$(db2_name "${SOURCE}") + ;; + esac + + # If source is in a sibling directory, + # prefix module name with 'X'. + + case "${SOURCE}" in + ../*) MODULE=$(db2_name "X${MODULE}") + ;; + esac + + make_module "${MODULE}" "${SOURCE}" "${PGMDFNS}" + if action_needed "${PGMIFSNAME}" "${MODIFSNAME}" + then LINK=yes + fi + ;; + esac + done + + # Link program if needed. + + if [ -n "${LINK}" ] + then PGMLDADD="$(eval echo "\${${PGM}_LDADD}")" + for M in ${PGMLDADD} + do case "${M}" in + -*) ;; # Ignore non-module. + *) MODULES="${MODULES} $(db2_name "${M}")" + ;; + esac + done + MODULES="$(echo "${MODULES}" | + sed "s/[^ ][^ ]*/${TARGETLIB}\/&/g")" + CMD="CRTPGM PGM(${TARGETLIB}/${DB2PGM})" + CMD="${CMD} ENTMOD(${TARGETLIB}/CURLMAIN)" + CMD="${CMD} MODULE(${MODULES} ${MODS})" + CMD="${CMD} BNDSRVPGM(${SRVPGMS} QADRTTS)" + CMD="${CMD} TGTRLS(${TGTRLS})" + CLcommand "${CMD}" + fi + done +} + + +# Build programs in the server directory. + +( + cd server || exit 1 + get_make_vars Makefile.inc + build_all_programs "${TARGETLIB}/OS400SYS" +) + + +# Build all programs in the libtest subdirectory. + +( + cd libtest || exit 1 + get_make_vars Makefile.inc + + # Special case: redefine chkhostname compilation parameters. + + # shellcheck disable=SC2034 + chkhostname_SOURCES=chkhostname.c + # shellcheck disable=SC2034 + chkhostname_LDADD=curl_gethostname.o + + # shellcheck disable=SC2153 + build_all_programs "" "${TARGETLIB}/${SRVPGM}" +) diff --git a/third_party/curl/packages/OS400/makefile.sh b/third_party/curl/packages/OS400/makefile.sh new file mode 100755 index 0000000..e58b835 --- /dev/null +++ b/third_party/curl/packages/OS400/makefile.sh @@ -0,0 +1,123 @@ +#!/bin/sh +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +# curl compilation script for the OS/400. +# +# +# This is a shell script since make is not a standard component of OS/400. + +SCRIPTDIR=$(dirname "${0}") +. "${SCRIPTDIR}/initscript.sh" +cd "${TOPDIR}" || exit 1 + + +# Create the OS/400 library if it does not exist. + +if action_needed "${LIBIFSNAME}" +then CMD="CRTLIB LIB(${TARGETLIB}) TEXT('curl: multiprotocol support API')" + CLcommand "${CMD}" +fi + + +# Create the DOCS source file if it does not exist. + +if action_needed "${LIBIFSNAME}/DOCS.FILE" +then CMD="CRTSRCPF FILE(${TARGETLIB}/DOCS) RCDLEN(240)" + CMD="${CMD} CCSID(${TGTCCSID}) TEXT('Documentation texts')" + CLcommand "${CMD}" +fi + + +# Copy some documentation files if needed. + +for TEXT in "${TOPDIR}/COPYING" "${SCRIPTDIR}/README.OS400" \ + "${TOPDIR}/CHANGES" "${TOPDIR}/docs/THANKS" "${TOPDIR}/docs/FAQ" \ + "${TOPDIR}/docs/FEATURES" "${TOPDIR}/docs/SSLCERTS.md" \ + "${TOPDIR}/docs/RESOURCES" "${TOPDIR}/docs/VERSIONS.md" \ + "${TOPDIR}/docs/HISTORY.md" +do MEMBER="$(basename "${TEXT}" .OS400)" + MEMBER="$(basename "${MEMBER}" .md)" + MEMBER="${LIBIFSNAME}/DOCS.FILE/$(db2_name "${MEMBER}").MBR" + + [ -e "${TEXT}" ] || continue + + if action_needed "${MEMBER}" "${TEXT}" + then CMD="CPY OBJ('${TEXT}') TOOBJ('${MEMBER}') TOCCSID(${TGTCCSID})" + CMD="${CMD} DTAFMT(*TEXT) REPLACE(*YES)" + CLcommand "${CMD}" + fi +done + + +# Create the RPGXAMPLES source file if it does not exist. + +if action_needed "${LIBIFSNAME}/RPGXAMPLES.FILE" +then CMD="CRTSRCPF FILE(${TARGETLIB}/RPGXAMPLES) RCDLEN(240)" + CMD="${CMD} CCSID(${TGTCCSID}) TEXT('ILE/RPG examples')" + CLcommand "${CMD}" +fi + + +# Copy RPG examples if needed. + +for EXAMPLE in "${SCRIPTDIR}/rpg-examples"/* +do MEMBER="$(basename "${EXAMPLE}")" + IFSMEMBER="${LIBIFSNAME}/RPGXAMPLES.FILE/$(db2_name "${MEMBER}").MBR" + + [ -e "${EXAMPLE}" ] || continue + + if action_needed "${IFSMEMBER}" "${EXAMPLE}" + then CMD="CPY OBJ('${EXAMPLE}') TOOBJ('${IFSMEMBER}')" + CMD="${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)" + CLcommand "${CMD}" + MBRTEXT=$(sed -e '1!d;/^ \*/!d;s/^ *\* *//' \ + -e 's/ *$//;s/'"'"'/&&/g' < "${EXAMPLE}") + CMD="CHGPFM FILE(${TARGETLIB}/RPGXAMPLES) MBR(${MEMBER})" + CMD="${CMD} SRCTYPE(RPGLE) TEXT('${MBRTEXT}')" + CLcommand "${CMD}" + fi +done + + +# Compile the QADRTMAIN2 replacement module. + +if action_needed "${LIBIFSNAME}/CURLMAIN.MODULE" "${SCRIPTDIR}/curlmain.c" +then CMD="CRTCMOD MODULE(${TARGETLIB}/CURLMAIN)" + CMD="${CMD} SRCSTMF('${SCRIPTDIR}/curlmain.c')" + CMD="${CMD} SYSIFCOPT(*IFS64IO) LOCALETYPE(*LOCALE) FLAG(10)" + CMD="${CMD} TGTCCSID(${TGTCCSID}) TGTRLS(${TGTRLS})" + CMD="${CMD} OUTPUT(${OUTPUT})" + CMD="${CMD} OPTIMIZE(${OPTIMIZE})" + CMD="${CMD} DBGVIEW(${DEBUG})" + CLcommand "${CMD}" +fi + + +# Build in each directory. + +# for SUBDIR in include lib src tests +for SUBDIR in include lib src +do "${SCRIPTDIR}/make-${SUBDIR}.sh" +done diff --git a/third_party/curl/packages/OS400/os400sys.c b/third_party/curl/packages/OS400/os400sys.c new file mode 100644 index 0000000..510c1c4 --- /dev/null +++ b/third_party/curl/packages/OS400/os400sys.c @@ -0,0 +1,1040 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * + ***************************************************************************/ + +/* OS/400 additional support. */ + +#include +#include "config-os400.h" /* Not curl_setup.h: we only need some defines. */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifdef HAVE_LIBZ +#include +#endif + +#ifdef HAVE_GSSAPI +#include +#endif + +#ifndef CURL_DISABLE_LDAP +#include +#endif + +#include +#include + +#include "os400sys.h" + +/** +*** QADRT OS/400 ASCII runtime defines only the most used procedures, but a +*** lot of them are not supported. This module implements ASCII wrappers for +*** those that are used by libcurl, but not defined by QADRT. +**/ + +#pragma convert(0) /* Restore EBCDIC. */ + +#define MIN_BYTE_GAIN 1024 /* Minimum gain when shortening a buffer. */ + +struct buffer_t { + unsigned long size; /* Buffer size. */ + char *buf; /* Buffer address. */ +}; + + +static char *buffer_undef(localkey_t key, long size); +static char *buffer_threaded(localkey_t key, long size); +static char *buffer_unthreaded(localkey_t key, long size); + +static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; +static pthread_key_t thdkey; +static struct buffer_t *locbufs; + +char *(*Curl_thread_buffer)(localkey_t key, long size) = buffer_undef; + +static void thdbufdestroy(void *private) +{ + if(private) { + struct buffer_t *p = (struct buffer_t *) private; + localkey_t i; + + for(i = (localkey_t) 0; i < LK_LAST; i++) { + free(p->buf); + p++; + } + + free(private); + } +} + + +static void +terminate(void) +{ + if(Curl_thread_buffer == buffer_threaded) { + locbufs = pthread_getspecific(thdkey); + pthread_setspecific(thdkey, (void *) NULL); + pthread_key_delete(thdkey); + } + + if(Curl_thread_buffer != buffer_undef) { + thdbufdestroy((void *) locbufs); + locbufs = (struct buffer_t *) NULL; + } + + Curl_thread_buffer = buffer_undef; +} + + +static char * +get_buffer(struct buffer_t *buf, long size) +{ + char *cp; + + /* If `size' >= 0, make sure buffer at `buf' is at least `size'-byte long. + Return the buffer address. */ + + if(size < 0) + return buf->buf; + + if(!buf->buf) { + buf->buf = malloc(size); + if(buf->buf) + buf->size = size; + + return buf->buf; + } + + if((unsigned long) size <= buf->size) { + /* Shorten the buffer only if it frees a significant byte count. This + avoids some realloc() overhead. */ + + if(buf->size - size < MIN_BYTE_GAIN) + return buf->buf; + } + + /* Resize the buffer. */ + + cp = realloc(buf->buf, size); + if(cp) { + buf->buf = cp; + buf->size = size; + } + else if(size <= buf->size) + cp = buf->buf; + + return cp; +} + + +static char * +buffer_unthreaded(localkey_t key, long size) +{ + return get_buffer(locbufs + key, size); +} + + +static char * +buffer_threaded(localkey_t key, long size) +{ + struct buffer_t *bufs; + + /* Get the buffer for the given local key in the current thread, and + make sure it is at least `size'-byte long. Set `size' to < 0 to get + its address only. */ + + bufs = (struct buffer_t *) pthread_getspecific(thdkey); + + if(!bufs) { + if(size < 0) + return (char *) NULL; /* No buffer yet. */ + + /* Allocate buffer descriptors for the current thread. */ + + bufs = calloc((size_t) LK_LAST, sizeof(*bufs)); + if(!bufs) + return (char *) NULL; + + if(pthread_setspecific(thdkey, (void *) bufs)) { + free(bufs); + return (char *) NULL; + } + } + + return get_buffer(bufs + key, size); +} + + +static char * +buffer_undef(localkey_t key, long size) +{ + /* Define the buffer system, get the buffer for the given local key in + the current thread, and make sure it is at least `size'-byte long. + Set `size' to < 0 to get its address only. */ + + pthread_mutex_lock(&mutex); + + /* Determine if we can use pthread-specific data. */ + + if(Curl_thread_buffer == buffer_undef) { /* If unchanged during lock. */ + if(!pthread_key_create(&thdkey, thdbufdestroy)) + Curl_thread_buffer = buffer_threaded; + else { + locbufs = calloc((size_t) LK_LAST, sizeof(*locbufs)); + if(!locbufs) { + pthread_mutex_unlock(&mutex); + return (char *) NULL; + } + else + Curl_thread_buffer = buffer_unthreaded; + } + + atexit(terminate); + } + + pthread_mutex_unlock(&mutex); + return Curl_thread_buffer(key, size); +} + + +static char * +set_thread_string(localkey_t key, const char *s) +{ + int i; + char *cp; + + if(!s) + return (char *) NULL; + + i = strlen(s) + 1; + cp = Curl_thread_buffer(key, MAX_CONV_EXPANSION * i + 1); + + if(cp) { + i = QadrtConvertE2A(cp, s, MAX_CONV_EXPANSION * i, i); + cp[i] = '\0'; + } + + return cp; +} + + +int +Curl_getnameinfo_a(const struct sockaddr *sa, socklen_t salen, + char *nodename, socklen_t nodenamelen, + char *servname, socklen_t servnamelen, + int flags) +{ + char *enodename = NULL; + char *eservname = NULL; + int status; + + if(nodename && nodenamelen) { + enodename = malloc(nodenamelen); + if(!enodename) + return EAI_MEMORY; + } + + if(servname && servnamelen) { + eservname = malloc(servnamelen); + if(!eservname) { + free(enodename); + return EAI_MEMORY; + } + } + + status = getnameinfo(sa, salen, enodename, nodenamelen, + eservname, servnamelen, flags); + + if(!status) { + int i; + if(enodename) { + i = QadrtConvertE2A(nodename, enodename, + nodenamelen - 1, strlen(enodename)); + nodename[i] = '\0'; + } + + if(eservname) { + i = QadrtConvertE2A(servname, eservname, + servnamelen - 1, strlen(eservname)); + servname[i] = '\0'; + } + } + + free(enodename); + free(eservname); + return status; +} + +int +Curl_getaddrinfo_a(const char *nodename, const char *servname, + const struct addrinfo *hints, + struct addrinfo **res) +{ + char *enodename; + char *eservname; + int status; + int i; + + enodename = (char *) NULL; + eservname = (char *) NULL; + + if(nodename) { + i = strlen(nodename); + + enodename = malloc(i + 1); + if(!enodename) + return EAI_MEMORY; + + i = QadrtConvertA2E(enodename, nodename, i, i); + enodename[i] = '\0'; + } + + if(servname) { + i = strlen(servname); + + eservname = malloc(i + 1); + if(!eservname) { + free(enodename); + return EAI_MEMORY; + } + + QadrtConvertA2E(eservname, servname, i, i); + eservname[i] = '\0'; + } + + status = getaddrinfo(enodename, eservname, hints, res); + free(enodename); + free(eservname); + return status; +} + +#ifdef HAVE_GSSAPI + +/* ASCII wrappers for the GSSAPI procedures. */ + +static int +Curl_gss_convert_in_place(OM_uint32 *minor_status, gss_buffer_t buf) +{ + unsigned int i = buf->length; + + /* Convert `buf' in place, from EBCDIC to ASCII. + If error, release the buffer and return -1. Else return 0. */ + + if(i) { + char *t = malloc(i); + if(!t) { + gss_release_buffer(minor_status, buf); + + if(minor_status) + *minor_status = ENOMEM; + + return -1; + } + + QadrtConvertE2A(t, buf->value, i, i); + memcpy(buf->value, t, i); + free(t); + } + + return 0; +} + + +OM_uint32 +Curl_gss_import_name_a(OM_uint32 *minor_status, gss_buffer_t in_name, + gss_OID in_name_type, gss_name_t *out_name) +{ + OM_uint32 rc; + unsigned int i; + gss_buffer_desc in; + + if(!in_name || !in_name->value || !in_name->length) + return gss_import_name(minor_status, in_name, in_name_type, out_name); + + memcpy((char *) &in, (char *) in_name, sizeof(in)); + i = in.length; + + in.value = malloc(i + 1); + if(!in.value) { + if(minor_status) + *minor_status = ENOMEM; + + return GSS_S_FAILURE; + } + + QadrtConvertA2E(in.value, in_name->value, i, i); + ((char *) in.value)[i] = '\0'; + rc = gss_import_name(minor_status, &in, in_name_type, out_name); + free(in.value); + return rc; +} + +OM_uint32 +Curl_gss_display_status_a(OM_uint32 *minor_status, OM_uint32 status_value, + int status_type, gss_OID mech_type, + gss_msg_ctx_t *message_context, + gss_buffer_t status_string) +{ + int rc; + + rc = gss_display_status(minor_status, status_value, status_type, + mech_type, message_context, status_string); + + if(rc != GSS_S_COMPLETE || !status_string || + !status_string->length || !status_string->value) + return rc; + + /* No way to allocate a buffer here, because it will be released by + gss_release_buffer(). The solution is to overwrite the EBCDIC buffer + with ASCII to return it. */ + + if(Curl_gss_convert_in_place(minor_status, status_string)) + return GSS_S_FAILURE; + + return rc; +} + +OM_uint32 +Curl_gss_init_sec_context_a(OM_uint32 *minor_status, + gss_cred_id_t cred_handle, + gss_ctx_id_t *context_handle, + gss_name_t target_name, gss_OID mech_type, + gss_flags_t req_flags, OM_uint32 time_req, + gss_channel_bindings_t input_chan_bindings, + gss_buffer_t input_token, + gss_OID *actual_mech_type, + gss_buffer_t output_token, gss_flags_t *ret_flags, + OM_uint32 *time_rec) +{ + int rc; + gss_buffer_desc in; + gss_buffer_t inp; + + in.value = NULL; + inp = input_token; + + if(inp) { + if(inp->length && inp->value) { + unsigned int i = inp->length; + + in.value = malloc(i + 1); + if(!in.value) { + if(minor_status) + *minor_status = ENOMEM; + + return GSS_S_FAILURE; + } + + QadrtConvertA2E(in.value, input_token->value, i, i); + ((char *) in.value)[i] = '\0'; + in.length = i; + inp = ∈ + } + } + + rc = gss_init_sec_context(minor_status, cred_handle, context_handle, + target_name, mech_type, req_flags, time_req, + input_chan_bindings, inp, actual_mech_type, + output_token, ret_flags, time_rec); + free(in.value); + + if(rc != GSS_S_COMPLETE || !output_token || + !output_token->length || !output_token->value) + return rc; + + /* No way to allocate a buffer here, because it will be released by + gss_release_buffer(). The solution is to overwrite the EBCDIC buffer + with ASCII to return it. */ + + if(Curl_gss_convert_in_place(minor_status, output_token)) + return GSS_S_FAILURE; + + return rc; +} + + +OM_uint32 +Curl_gss_delete_sec_context_a(OM_uint32 *minor_status, + gss_ctx_id_t *context_handle, + gss_buffer_t output_token) +{ + OM_uint32 rc; + + rc = gss_delete_sec_context(minor_status, context_handle, output_token); + + if(rc != GSS_S_COMPLETE || !output_token || + !output_token->length || !output_token->value) + return rc; + + /* No way to allocate a buffer here, because it will be released by + gss_release_buffer(). The solution is to overwrite the EBCDIC buffer + with ASCII to return it. */ + + if(Curl_gss_convert_in_place(minor_status, output_token)) + return GSS_S_FAILURE; + + return rc; +} + +#endif /* HAVE_GSSAPI */ + +#ifndef CURL_DISABLE_LDAP + +/* ASCII wrappers for the LDAP procedures. */ + +void * +Curl_ldap_init_a(char *host, int port) +{ + size_t i; + char *ehost; + void *result; + + if(!host) + return (void *) ldap_init(host, port); + + i = strlen(host); + + ehost = malloc(i + 1); + if(!ehost) + return (void *) NULL; + + QadrtConvertA2E(ehost, host, i, i); + ehost[i] = '\0'; + result = (void *) ldap_init(ehost, port); + free(ehost); + return result; +} + +int +Curl_ldap_simple_bind_s_a(void *ld, char *dn, char *passwd) +{ + int i; + char *edn; + char *epasswd; + + edn = (char *) NULL; + epasswd = (char *) NULL; + + if(dn) { + i = strlen(dn); + + edn = malloc(i + 1); + if(!edn) + return LDAP_NO_MEMORY; + + QadrtConvertA2E(edn, dn, i, i); + edn[i] = '\0'; + } + + if(passwd) { + i = strlen(passwd); + + epasswd = malloc(i + 1); + if(!epasswd) { + free(edn); + return LDAP_NO_MEMORY; + } + + QadrtConvertA2E(epasswd, passwd, i, i); + epasswd[i] = '\0'; + } + + i = ldap_simple_bind_s(ld, edn, epasswd); + free(epasswd); + free(edn); + return i; +} + +int +Curl_ldap_search_s_a(void *ld, char *base, int scope, char *filter, + char **attrs, int attrsonly, LDAPMessage **res) +{ + int i; + int j; + char *ebase; + char *efilter; + char **eattrs; + int status; + + ebase = (char *) NULL; + efilter = (char *) NULL; + eattrs = (char **) NULL; + status = LDAP_SUCCESS; + + if(base) { + i = strlen(base); + + ebase = malloc(i + 1); + if(!ebase) + status = LDAP_NO_MEMORY; + else { + QadrtConvertA2E(ebase, base, i, i); + ebase[i] = '\0'; + } + } + + if(filter && status == LDAP_SUCCESS) { + i = strlen(filter); + + efilter = malloc(i + 1); + if(!efilter) + status = LDAP_NO_MEMORY; + else { + QadrtConvertA2E(efilter, filter, i, i); + efilter[i] = '\0'; + } + } + + if(attrs && status == LDAP_SUCCESS) { + for(i = 0; attrs[i++];) + ; + + eattrs = calloc(i, sizeof(*eattrs)); + if(!eattrs) + status = LDAP_NO_MEMORY; + else { + for(j = 0; attrs[j]; j++) { + i = strlen(attrs[j]); + + eattrs[j] = malloc(i + 1); + if(!eattrs[j]) { + status = LDAP_NO_MEMORY; + break; + } + + QadrtConvertA2E(eattrs[j], attrs[j], i, i); + eattrs[j][i] = '\0'; + } + } + } + + if(status == LDAP_SUCCESS) + status = ldap_search_s(ld, ebase? ebase: "", scope, + efilter? efilter: "(objectclass=*)", + eattrs, attrsonly, res); + + if(eattrs) { + for(j = 0; eattrs[j]; j++) + free(eattrs[j]); + + free(eattrs); + } + + free(efilter); + free(ebase); + return status; +} + + +struct berval ** +Curl_ldap_get_values_len_a(void *ld, LDAPMessage *entry, const char *attr) +{ + char *cp; + struct berval **result; + + cp = (char *) NULL; + + if(attr) { + int i = strlen(attr); + + cp = malloc(i + 1); + if(!cp) { + ldap_set_lderrno(ld, LDAP_NO_MEMORY, NULL, + ldap_err2string(LDAP_NO_MEMORY)); + return (struct berval **) NULL; + } + + QadrtConvertA2E(cp, attr, i, i); + cp[i] = '\0'; + } + + result = ldap_get_values_len(ld, entry, cp); + free(cp); + + /* Result data are binary in nature, so they haven't been + converted to EBCDIC. Therefore do not convert. */ + + return result; +} + +char * +Curl_ldap_err2string_a(int error) +{ + return set_thread_string(LK_LDAP_ERROR, ldap_err2string(error)); +} + +char * +Curl_ldap_get_dn_a(void *ld, LDAPMessage *entry) +{ + int i; + char *cp; + char *cp2; + + cp = ldap_get_dn(ld, entry); + + if(!cp) + return cp; + + i = strlen(cp); + + cp2 = malloc(i + 1); + if(!cp2) + return cp2; + + QadrtConvertE2A(cp2, cp, i, i); + cp2[i] = '\0'; + + /* No way to allocate a buffer here, because it will be released by + ldap_memfree() and ldap_memalloc() does not exist. The solution is to + overwrite the EBCDIC buffer with ASCII to return it. */ + + strcpy(cp, cp2); + free(cp2); + return cp; +} + +char * +Curl_ldap_first_attribute_a(void *ld, + LDAPMessage *entry, BerElement **berptr) +{ + int i; + char *cp; + char *cp2; + + cp = ldap_first_attribute(ld, entry, berptr); + + if(!cp) + return cp; + + i = strlen(cp); + + cp2 = malloc(i + 1); + if(!cp2) + return cp2; + + QadrtConvertE2A(cp2, cp, i, i); + cp2[i] = '\0'; + + /* No way to allocate a buffer here, because it will be released by + ldap_memfree() and ldap_memalloc() does not exist. The solution is to + overwrite the EBCDIC buffer with ASCII to return it. */ + + strcpy(cp, cp2); + free(cp2); + return cp; +} + +char * +Curl_ldap_next_attribute_a(void *ld, + LDAPMessage *entry, BerElement *berptr) +{ + int i; + char *cp; + char *cp2; + + cp = ldap_next_attribute(ld, entry, berptr); + + if(!cp) + return cp; + + i = strlen(cp); + + cp2 = malloc(i + 1); + if(!cp2) + return cp2; + + QadrtConvertE2A(cp2, cp, i, i); + cp2[i] = '\0'; + + /* No way to allocate a buffer here, because it will be released by + ldap_memfree() and ldap_memalloc() does not exist. The solution is to + overwrite the EBCDIC buffer with ASCII to return it. */ + + strcpy(cp, cp2); + free(cp2); + return cp; +} + +#endif /* CURL_DISABLE_LDAP */ + +static int +sockaddr2ebcdic(struct sockaddr_storage *dstaddr, + const struct sockaddr *srcaddr, int srclen) +{ + const struct sockaddr_un *srcu; + struct sockaddr_un *dstu; + unsigned int i; + unsigned int dstsize; + + /* Convert a socket address to job CCSID, if needed. */ + + if(!srcaddr || srclen < offsetof(struct sockaddr, sa_family) + + sizeof(srcaddr->sa_family) || srclen > sizeof(*dstaddr)) { + errno = EINVAL; + return -1; + } + + memcpy((char *) dstaddr, (char *) srcaddr, srclen); + + switch(srcaddr->sa_family) { + + case AF_UNIX: + srcu = (const struct sockaddr_un *) srcaddr; + dstu = (struct sockaddr_un *) dstaddr; + dstsize = sizeof(*dstaddr) - offsetof(struct sockaddr_un, sun_path); + srclen -= offsetof(struct sockaddr_un, sun_path); + i = QadrtConvertA2E(dstu->sun_path, srcu->sun_path, dstsize - 1, srclen); + dstu->sun_path[i] = '\0'; + srclen = i + offsetof(struct sockaddr_un, sun_path); + } + + return srclen; +} + + +static int +sockaddr2ascii(struct sockaddr *dstaddr, int dstlen, + const struct sockaddr_storage *srcaddr, int srclen) +{ + const struct sockaddr_un *srcu; + struct sockaddr_un *dstu; + unsigned int dstsize; + + /* Convert a socket address to ASCII, if needed. */ + + if(!srclen) + return 0; + if(srclen > dstlen) + srclen = dstlen; + if(!srcaddr || srclen < 0) { + errno = EINVAL; + return -1; + } + + memcpy((char *) dstaddr, (char *) srcaddr, srclen); + + if(srclen >= offsetof(struct sockaddr_storage, ss_family) + + sizeof(srcaddr->ss_family)) { + switch(srcaddr->ss_family) { + + case AF_UNIX: + srcu = (const struct sockaddr_un *) srcaddr; + dstu = (struct sockaddr_un *) dstaddr; + dstsize = dstlen - offsetof(struct sockaddr_un, sun_path); + srclen -= offsetof(struct sockaddr_un, sun_path); + if(dstsize > 0 && srclen > 0) { + srclen = QadrtConvertE2A(dstu->sun_path, srcu->sun_path, + dstsize - 1, srclen); + dstu->sun_path[srclen] = '\0'; + } + srclen += offsetof(struct sockaddr_un, sun_path); + } + } + + return srclen; +} + +int +Curl_os400_connect(int sd, struct sockaddr *destaddr, int addrlen) +{ + int i; + struct sockaddr_storage laddr; + + i = sockaddr2ebcdic(&laddr, destaddr, addrlen); + + if(i < 0) + return -1; + + return connect(sd, (struct sockaddr *) &laddr, i); +} + +int +Curl_os400_bind(int sd, struct sockaddr *localaddr, int addrlen) +{ + int i; + struct sockaddr_storage laddr; + + i = sockaddr2ebcdic(&laddr, localaddr, addrlen); + + if(i < 0) + return -1; + + return bind(sd, (struct sockaddr *) &laddr, i); +} + +int +Curl_os400_sendto(int sd, char *buffer, int buflen, int flags, + const struct sockaddr *dstaddr, int addrlen) +{ + int i; + struct sockaddr_storage laddr; + + i = sockaddr2ebcdic(&laddr, dstaddr, addrlen); + + if(i < 0) + return -1; + + return sendto(sd, buffer, buflen, flags, (struct sockaddr *) &laddr, i); +} + +int +Curl_os400_recvfrom(int sd, char *buffer, int buflen, int flags, + struct sockaddr *fromaddr, int *addrlen) +{ + int rcvlen; + struct sockaddr_storage laddr; + int laddrlen = sizeof(laddr); + + if(!fromaddr || !addrlen || *addrlen <= 0) + return recvfrom(sd, buffer, buflen, flags, fromaddr, addrlen); + + laddr.ss_family = AF_UNSPEC; /* To detect if unused. */ + rcvlen = recvfrom(sd, buffer, buflen, flags, + (struct sockaddr *) &laddr, &laddrlen); + + if(rcvlen < 0) + return rcvlen; + + if(laddr.ss_family == AF_UNSPEC) + laddrlen = 0; + else { + laddrlen = sockaddr2ascii(fromaddr, *addrlen, &laddr, laddrlen); + if(laddrlen < 0) + return laddrlen; + } + *addrlen = laddrlen; + return rcvlen; +} + +int +Curl_os400_getpeername(int sd, struct sockaddr *addr, int *addrlen) +{ + struct sockaddr_storage laddr; + int laddrlen = sizeof(laddr); + int retcode = getpeername(sd, (struct sockaddr *) &laddr, &laddrlen); + + if(!retcode) { + laddrlen = sockaddr2ascii(addr, *addrlen, &laddr, laddrlen); + if(laddrlen < 0) + return laddrlen; + *addrlen = laddrlen; + } + + return retcode; +} + +int +Curl_os400_getsockname(int sd, struct sockaddr *addr, int *addrlen) +{ + struct sockaddr_storage laddr; + int laddrlen = sizeof(laddr); + int retcode = getsockname(sd, (struct sockaddr *) &laddr, &laddrlen); + + if(!retcode) { + laddrlen = sockaddr2ascii(addr, *addrlen, &laddr, laddrlen); + if(laddrlen < 0) + return laddrlen; + *addrlen = laddrlen; + } + + return retcode; +} + + +#ifdef HAVE_LIBZ +const char * +Curl_os400_zlibVersion(void) +{ + return set_thread_string(LK_ZLIB_VERSION, zlibVersion()); +} + + +int +Curl_os400_inflateInit_(z_streamp strm, const char *version, int stream_size) +{ + z_const char *msgb4 = strm->msg; + int ret; + + ret = inflateInit(strm); + + if(strm->msg != msgb4) + strm->msg = set_thread_string(LK_ZLIB_MSG, strm->msg); + + return ret; +} + +int +Curl_os400_inflateInit2_(z_streamp strm, int windowBits, + const char *version, int stream_size) +{ + z_const char *msgb4 = strm->msg; + int ret; + + ret = inflateInit2(strm, windowBits); + + if(strm->msg != msgb4) + strm->msg = set_thread_string(LK_ZLIB_MSG, strm->msg); + + return ret; +} + +int +Curl_os400_inflate(z_streamp strm, int flush) +{ + z_const char *msgb4 = strm->msg; + int ret; + + ret = inflate(strm, flush); + + if(strm->msg != msgb4) + strm->msg = set_thread_string(LK_ZLIB_MSG, strm->msg); + + return ret; +} + +int +Curl_os400_inflateEnd(z_streamp strm) +{ + z_const char *msgb4 = strm->msg; + int ret; + + ret = inflateEnd(strm); + + if(strm->msg != msgb4) + strm->msg = set_thread_string(LK_ZLIB_MSG, strm->msg); + + return ret; +} + +#endif diff --git a/third_party/curl/packages/OS400/os400sys.h b/third_party/curl/packages/OS400/os400sys.h new file mode 100644 index 0000000..d5ff412 --- /dev/null +++ b/third_party/curl/packages/OS400/os400sys.h @@ -0,0 +1,57 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + * + ***************************************************************************/ + +/* OS/400 additional definitions. */ + +#ifndef __OS400_SYS_ +#define __OS400_SYS_ + + +/* Per-thread item identifiers. */ + +typedef enum { + LK_GSK_ERROR, + LK_LDAP_ERROR, + LK_CURL_VERSION, + LK_VERSION_INFO, + LK_VERSION_INFO_DATA, + LK_EASY_STRERROR, + LK_SHARE_STRERROR, + LK_MULTI_STRERROR, + LK_URL_STRERROR, + LK_ZLIB_VERSION, + LK_ZLIB_MSG, + LK_LAST +} localkey_t; + + +extern char * (* Curl_thread_buffer)(localkey_t key, long size); + + +/* Maximum string expansion factor due to character code conversion. */ + +#define MAX_CONV_EXPANSION 4 /* Can deal with UTF-8. */ + +#endif diff --git a/third_party/curl/packages/OS400/rpg-examples/HEADERAPI b/third_party/curl/packages/OS400/rpg-examples/HEADERAPI new file mode 100644 index 0000000..2c2407e --- /dev/null +++ b/third_party/curl/packages/OS400/rpg-examples/HEADERAPI @@ -0,0 +1,146 @@ + * Curl header API: extract headers post transfer + * + h DFTACTGRP(*NO) ACTGRP(*NEW) + h OPTION(*NOSHOWCPY) + h BNDDIR('CURL') + * + ************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ************************************************************************** + * + /include H,CURL.INC + * + * Extract headers post transfer with the header API. + * + d pi + d url 120 + * + d urllen s 10u 0 URL length + * + ************************************************************************** + + urllen = trimmed_length(url: %len(url)); + + // Do the curl stuff. + + curl_global_init(CURL_GLOBAL_ALL); + main(); + curl_global_cleanup(); + *inlr = *on; // Exit + * + ************************************************************************** + * Main procedure: do the curl job. + ************************************************************************** + * + p main b + d main pi + * + d h s * Easy handle + d result s like(CURLcode) Curl return code + d inz(CURLE_OUT_OF_MEMORY) + d header ds likeds(curl_header) based(hp) + d strp1 s * Work string pointer + d strp2 s * Work string pointer + d inout s 52 For error display + + // Create and fill curl handle. + + h = curl_easy_init(); + if h <> *NULL; + curl_easy_setopt_ccsid(h: CURLOPT_URL: %subst(url: 1: urllen): 0); + curl_easy_setopt(h: CURLOPT_FOLLOWLOCATION: 1); + curl_easy_setopt(h: CURLOPT_WRITEFUNCTION: %paddr(in_data_cb)); // Ignore input data + + // Perform the request. + + result = curl_easy_perform(h); + endif; + + // Check for error and report if some. + + if result <> CURLE_OK; + inout = %str(curl_easy_strerror_ccsid(result: 0)); + dsply '' '*EXT' inout; + else; + if curl_easy_header_ccsid(h: 'Content-Type': 0: CURLH_HEADER: -1: + hp: 0) = CURLHE_OK; + strp2 = curl_to_ccsid(header.value: 0); + inout = 'Content-Type: ' + %str(strp2); + dsply inout; + curl_free(strp2); + endif; + dsply ' All server headers:'; + hp = *NULL; + dow *on; + hp = curl_easy_nextheader(h: CURLH_HEADER: -1: hp); + if hp = *NULL; + leave; + endif; + strp1 = curl_to_ccsid(header.name: 0); + strp2 = curl_to_ccsid(header.value: 0); + inout = %str(strp1) + ': ' + %str(strp2) + + ' (' + %char(header.amount) + ')'; + curl_free(strp2); + curl_free(strp1); + dsply inout; + enddo; + inout = 'Done'; + dsply '' '*EXT' inout; + curl_easy_cleanup(h); // Release handle + endif; + p main e + * + ************************************************************************** + * Dummy data input callback procedure. + ************************************************************************** + * + p in_data_cb b + d in_data_cb pi 10u 0 + d ptr * value Input data pointer + d size 10u 0 value Data element size + d nmemb 10u 0 value Data element count + d userdata * value User data pointer + * + return size * nmemb; + p in_data_cb e + * + ************************************************************************** + * Get the length of right-trimmed string + ************************************************************************** + * + p trimmed_length b + d trimmed_length pi 10u 0 + d string 999999 const options(*varsize) + d length 10u 0 value + * + d len s 10u 0 + * + len = %scan(X'00': string: 1: length); // Limit to zero-terminated string + if len = 0; + len = length + 1; + endif; + if len <= 1; + return 0; + endif; + return %checkr(' ': string: len - 1); // Trim right + p trimmed_length e diff --git a/third_party/curl/packages/OS400/rpg-examples/HTTPPOST b/third_party/curl/packages/OS400/rpg-examples/HTTPPOST new file mode 100644 index 0000000..21202eb --- /dev/null +++ b/third_party/curl/packages/OS400/rpg-examples/HTTPPOST @@ -0,0 +1,129 @@ + * Curl MIME post data and display response + * + h DFTACTGRP(*NO) ACTGRP(*NEW) + h OPTION(*NOSHOWCPY) + h BNDDIR('CURL') + * + ************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ************************************************************************** + * + /include H,CURL.INC + * + * Example to HTTP POST data using the MIME API. Displays the response. + * + d pi + d userinput 120 User data to post + * + d url c 'http://httpbin.org/anything' + * + * + d inputlen s 10u 0 User input length + ************************************************************************** + + inputlen = trimmed_length(userinput: %len(userinput)); + + // Do the curl stuff. + + curl_global_init(CURL_GLOBAL_ALL); + main(); + curl_global_cleanup(); + *inlr = *on; // Exit + * + ************************************************************************** + * Main procedure: do the curl job. + ************************************************************************** + * + p main b + d main pi + * + d h s * Easy handle + d result s like(CURLcode) Curl return code + d inz(CURLE_OUT_OF_MEMORY) + d errmsgp s * Error string pointer + d response s 52 For error display + d mime s * MIME handle + d mimepart s * MIME part handle + d parthdrs s * inz(*NULL) Part headers + + // Create and fill curl handle. + + h = curl_easy_init(); + if h <> *NULL; + curl_easy_setopt_ccsid(h: CURLOPT_URL: url: 0); + curl_easy_setopt(h: CURLOPT_FOLLOWLOCATION: 1); + mime = curl_mime_init(h); + mimepart = curl_mime_addpart(mime); + curl_mime_name_ccsid(mimepart: 'autofield': 0); + curl_mime_data_ccsid(mimepart: 'program-generated value': + CURL_ZERO_TERMINATED: 0); + mimepart = curl_mime_addpart(mime); + curl_mime_name_ccsid(mimepart: 'userfield': 0); + curl_mime_data_ccsid(mimepart: %subst(userinput: 1: inputlen): + CURL_ZERO_TERMINATED: 0); + mimepart = curl_mime_addpart(mime); + curl_mime_name_ccsid(mimepart: 'ebcdicfield': 0); + curl_mime_data(mimepart: %subst(userinput: 1: inputlen): inputlen); + curl_mime_encoder_ccsid(mimepart: 'base64': 0); + // Avoid server to convert base64 to text. + parthdrs = curl_slist_append_ccsid(parthdrs: + 'Content-Transfer-Encoding: bit': 0); + curl_mime_headers(mimepart: parthdrs: 1); + curl_easy_setopt(h: CURLOPT_MIMEPOST: mime); + + // Perform the request. + + result = curl_easy_perform(h); + curl_mime_free(mime); + curl_easy_cleanup(h); // Release handle + endif; + + // Check for error and report if some. + + if result <> CURLE_OK; + errmsgp = curl_easy_strerror_ccsid(result: 0); + response = %str(errmsgp); + dsply '' '*EXT' response; + endif; + p main e + * + ************************************************************************** + * Get the length of right-trimmed string + ************************************************************************** + * + p trimmed_length b + d trimmed_length pi 10u 0 + d string 999999 const options(*varsize) + d length 10u 0 value + * + d len s 10u 0 + * + len = %scan(X'00': string: 1: length); // Limit to zero-terminated string + if len = 0; + len = length + 1; + endif; + if len <= 1; + return 0; + endif; + return %checkr(' ': string: len - 1); // Trim right + p trimmed_length e diff --git a/third_party/curl/packages/OS400/rpg-examples/INMEMORY b/third_party/curl/packages/OS400/rpg-examples/INMEMORY new file mode 100644 index 0000000..e6f43ab --- /dev/null +++ b/third_party/curl/packages/OS400/rpg-examples/INMEMORY @@ -0,0 +1,159 @@ + * Curl get in memory and count HTML tags + * + h DFTACTGRP(*NO) ACTGRP(*NEW) + h OPTION(*NOSHOWCPY) + h BNDDIR('CURL') + * + ************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ************************************************************************** + * + /include H,CURL.INC + * + * Example to request the URL given as command line parameter and count + * HTML tags in its response. + * + d pi + d url 120 + * + d countdata ds qualified based(###dummyptr) User data type + d tagcount 10u 0 Tag counter + d tagopen n Possible opening tag + * + d urllen s 10u 0 URL length + * + ************************************************************************** + + urllen = trimmed_length(url: %len(url)); + + // Do the curl stuff. + + curl_global_init(CURL_GLOBAL_ALL); + main(); + curl_global_cleanup(); + *inlr = *on; // Exit + * + ************************************************************************** + * Main procedure: do the curl job. + ************************************************************************** + * + p main b + d main pi + * + d h s * Easy handle + d result s like(CURLcode) Curl return code + d inz(CURLE_OUT_OF_MEMORY) + d errmsgp s * Error string pointer + d response s 52 For error display + d counter ds likeds(countdata) HTML tag counter + + counter.tagcount = 0; + counter.tagopen = *off; + + // Create and fill curl handle. + + h = curl_easy_init(); + if h <> *NULL; + curl_easy_setopt_ccsid(h: CURLOPT_URL: %subst(url: 1: urllen): 0); + curl_easy_setopt(h: CURLOPT_FOLLOWLOCATION: 1); + curl_easy_setopt(h: CURLOPT_WRITEFUNCTION: %paddr(in_data_cb)); + curl_easy_setopt(h: CURLOPT_WRITEDATA: %addr(counter)); + + // Perform the request. + + result = curl_easy_perform(h); + curl_easy_cleanup(h); // Release handle + endif; + + // Check for error and report if some. + + if result <> CURLE_OK; + errmsgp = curl_easy_strerror_ccsid(result: 0); + response = %str(errmsgp); + dsply '' '*EXT' response; + else; + // Display the tag count. + + response = 'Tag count: ' + %char(counter.tagcount); + dsply '' '*EXT' response; + endif; + p main e + * + ************************************************************************** + * Data input callback procedure. + ************************************************************************** + * + p in_data_cb b + d in_data_cb pi 10u 0 + d ptr * value Input data pointer + d size 10u 0 value Data element size + d nmemb 10u 0 value Data element count + d userdata * value User data pointer + * + d counter ds likeds(countdata) based(userdata) HTML tag counter + d ebcdata s * EBCDIC data pointer + d chars s 1 based(ebcdata) dim(1000000) + d i s 10u 0 Character position + * + size = size * nmemb; // The size in bytes. + ebcdata = curl_to_ccsid(%str(ptr: size): 0); // Convert to EBCDIC. + i = 1; + dow i <= size; + if counter.tagopen; // Did we see '<' ? + counter.tagopen = *off; + if chars(i) <> '/'; // Reject closing tag. + counter.tagcount = counter.tagcount + 1; // Count this tag. + endif; + else; + i = %scan('<': %str(ebcdata): i); // Search next possible tag. + if i = 0; + leave; + endif; + counter.tagopen = *on; // Found one: flag it. + endif; + i = i + 1; + enddo; + curl_free(ebcdata); + return size; + p in_data_cb e + * + ************************************************************************** + * Get the length of right-trimmed string + ************************************************************************** + * + p trimmed_length b + d trimmed_length pi 10u 0 + d string 999999 const options(*varsize) + d length 10u 0 value + * + d len s 10u 0 + * + len = %scan(X'00': string: 1: length); // Limit to zero-terminated string + if len = 0; + len = length + 1; + endif; + if len <= 1; + return 0; + endif; + return %checkr(' ': string: len - 1); // Trim right + p trimmed_length e diff --git a/third_party/curl/packages/OS400/rpg-examples/SIMPLE1 b/third_party/curl/packages/OS400/rpg-examples/SIMPLE1 new file mode 100644 index 0000000..52c0c93 --- /dev/null +++ b/third_party/curl/packages/OS400/rpg-examples/SIMPLE1 @@ -0,0 +1,108 @@ + * Curl simple URL request + * + h DFTACTGRP(*NO) ACTGRP(*NEW) + h OPTION(*NOSHOWCPY) + h BNDDIR('CURL') + * + ************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ************************************************************************** + * + /include H,CURL.INC + * + * Simple example to request the URL given as command line parameter and + * output its response. + * + d pi + d url 120 + * + d urllen s 10u 0 URL length + * + ************************************************************************** + * + c eval urllen = trimmed_length(url: %len(url)) + * + * Do the curl stuff. + * + c callp curl_global_init(CURL_GLOBAL_ALL) + c callp main + c callp curl_global_cleanup() + c seton lr Exit + * + ************************************************************************** + * Main procedure: do the curl job. + ************************************************************************** + * + p main b + d main pi + * + d h s * Easy handle + d result s like(CURLcode) Curl return code + d inz(CURLE_OUT_OF_MEMORY) + d errmsgp s * Error string pointer + d response s 52 For error display + * + * Create and fill curl handle. + * + c eval h = curl_easy_init() + c if h <> *NULL + c callp curl_easy_setopt_ccsid(h: CURLOPT_URL: + c %subst(url: 1: urllen): 0) + c callp curl_easy_setopt_long(h: + c CURLOPT_FOLLOWLOCATION: 1) + * + * Perform the request. + * + c eval result = curl_easy_perform(h) + c callp curl_easy_cleanup(h) Release handle + c endif + * + * Check for error and report if some. + * + c if result <> CURLE_OK + c eval errmsgp = curl_easy_strerror_ccsid(result: 0) + c eval response = %str(errmsgp) + c dsply response + c endif + p main e + * + ************************************************************************** + * Get the length of right-trimmed string + ************************************************************************** + * + p trimmed_length b + d trimmed_length pi 10u 0 + d string 999999 const options(*varsize) + d length 10u 0 value + * + d len s 10u 0 + * + c eval len = %scan(X'00': string: 1: length) Limit 0-terminated + c if len = 0 + c eval len = length + 1 + c endif + c if len <= 1 + c return 0 + c endif + c return %checkr(' ': string: len - 1) Trim right + p trimmed_length e diff --git a/third_party/curl/packages/OS400/rpg-examples/SIMPLE2 b/third_party/curl/packages/OS400/rpg-examples/SIMPLE2 new file mode 100644 index 0000000..493c91e --- /dev/null +++ b/third_party/curl/packages/OS400/rpg-examples/SIMPLE2 @@ -0,0 +1,108 @@ + * Curl simple URL request (free-format RPG) + * + ctl-opt dftactgrp(*NO) actgrp(*NEW) + option(*NOSHOWCPY) + bnddir('CURL'); + * + ************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ************************************************************************** + + /include H,CURL.INC + + * Simple free-format RPG program to request the URL given as command line + * parameter and output its response. + + dcl-pi *N; + url char(120); + end-pi; + + dcl-s urllen int(10); // URL length + + ************************************************************************** + + urllen = trimmed_length(url: %len(url)); + + // Do the curl stuff. + + curl_global_init(CURL_GLOBAL_ALL); + main(); + curl_global_cleanup(); + *inlr = *on; // Exit + + ************************************************************************** + * Main procedure: do the curl job. + ************************************************************************** + + dcl-proc main; + dcl-pi *N end-pi; + + dcl-s h pointer; // Easy handle + dcl-s result like(CURLcode) inz(CURLE_OUT_OF_MEMORY); // Curl return code + dcl-s errmsgp pointer; // Error string pointer + dcl-s response char(52); // For error display + + // Create and fill curl handle. + + h = curl_easy_init(); + if h <> *NULL; + curl_easy_setopt_ccsid(h: CURLOPT_URL: %subst(url: 1: urllen): + 0); + curl_easy_setopt(h: CURLOPT_FOLLOWLOCATION: 1); + + // Perform the request. + + result = curl_easy_perform(h); + curl_easy_cleanup(h); // Release handle + endif; + + // Check for error and report if some. + + if result <> CURLE_OK; + errmsgp = curl_easy_strerror_ccsid(result: 0); + response = %str(errmsgp); + dsply '' '*EXT' response; + endif; + end-proc; + * + ************************************************************************** + * Get the length of right-trimmed string + ************************************************************************** + * + dcl-proc trimmed_length; + dcl-pi *N uns(10); + string char(9999999) const options(*varsize); + length uns(10) value; + end-pi; + + dcl-s len uns(10); + + len = %scan(X'00': string: 1: length); // Limit to zero-terminated string + if len = 0; + len = length + 1; + endif; + if len <= 1; + return 0; + endif; + return %checkr(' ': string: len - 1); // Trim right + end-proc; diff --git a/third_party/curl/packages/OS400/rpg-examples/SMTPSRCMBR b/third_party/curl/packages/OS400/rpg-examples/SMTPSRCMBR new file mode 100644 index 0000000..88f4fd2 --- /dev/null +++ b/third_party/curl/packages/OS400/rpg-examples/SMTPSRCMBR @@ -0,0 +1,239 @@ + * Curl SMTP send source member as attachment + * + h DFTACTGRP(*NO) ACTGRP(*NEW) + h OPTION(*NOSHOWCPY) + h BNDDIR('CURL') + * + ************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ************************************************************************** + * + /include H,CURL.INC + * + * Example to SMTP send source member as attachment via SMTP. + * + fRPGXAMPLESif e disk extmbr(program_name) + f rename(RPGXAMPLES: record) + d pi + d url 60 SMTP server URL + d recipient_mail 40 Recipient mail addr + * + d program_name c 'SMTPSRCMBR' Member name to send + d sender_name c 'Curl' Sender name + d sender_mail c 'curl@example.com' Sender e-mail + d recipient_name c 'WIMC' Recipient name + d crlf c X'0D25' + * + d urllen s 10u 0 URL length + d rcptmlen s 10u 0 Recipient mail len + * + ************************************************************************** + + urllen = trimmed_length(url: %len(url)); + rcptmlen = trimmed_length(recipient_mail: %len(recipient_mail)); + + // Do the curl stuff. + + curl_global_init(CURL_GLOBAL_ALL); + main(); + curl_global_cleanup(); + *inlr = *on; // Exit + * + ************************************************************************** + * Main procedure: do the curl job. + ************************************************************************** + * + p main b + d main pi + * + d h s * Easy handle + d result s like(CURLcode) Curl return code + d inz(CURLE_OUT_OF_MEMORY) + d errmsgp s * Error string pointer + d response s 52 For error display + d headers s * inz(*NULL) Mail headers + d rcpts s * inz(*NULL) List of recipients + d mime s * Mail MIME structure + d mimepart s * Mail part + + // Create and fill curl handle. + + h = curl_easy_init(); + if h <> *NULL; + rcpts = curl_slist_append_ccsid(rcpts: + %subst(recipient_mail: 1: rcptmlen): 0); + headers = curl_slist_append_ccsid(headers: 'From: ' + sender_name + + ' <' + sender_mail + '>': + 0); + headers = curl_slist_append_ccsid(headers: 'To: ' + recipient_name + + ' <' + %subst(recipient_mail: 1: rcptmlen) + '>': 0); + headers = curl_slist_append_ccsid(headers: 'Subject: An ILE/RPG ' + + 'source program': 0); + headers = curl_slist_append_ccsid(headers: 'Date: ' + mail_date(): + 0); + curl_easy_setopt_ccsid(h: CURLOPT_URL: %subst(url: 1: urllen): 0); + curl_easy_setopt_ccsid(h: CURLOPT_MAIL_FROM: sender_mail: 0); + curl_easy_setopt(h: CURLOPT_MAIL_RCPT: rcpts); + curl_easy_setopt(h: CURLOPT_HTTPHEADER: headers); + mime = curl_mime_init(h); + mimepart = curl_mime_addpart(mime); + curl_mime_data_ccsid(mimepart: 'Please find the ILE/RPG program ' + + program_name + ' source code in ' + + 'attachment.' + crlf: + CURL_ZERO_TERMINATED: 0); + mimepart = curl_mime_addpart(mime); + curl_mime_data_cb(mimepart: -1: %paddr(out_data_cb): *NULL: *NULL: + *NULL); + curl_mime_filename_ccsid(mimepart: program_name: 0); + curl_mime_encoder_ccsid(mimepart: 'quoted-printable': 0); + curl_easy_setopt(h: CURLOPT_MIMEPOST: mime); + + // Perform the request. + + setll *start RPGXAMPLES; + result = curl_easy_perform(h); + + // Cleanup. + + curl_mime_free(mime); + curl_slist_free_all(headers); + curl_slist_free_all(rcpts); + curl_easy_cleanup(h); // Release handle + endif; + + // Check for error and report if some. + + if result <> CURLE_OK; + errmsgp = curl_easy_strerror_ccsid(result: 0); + response = %str(errmsgp); + dsply '' '*EXT' response; + else; + response = 'Mail sent'; + dsply '' '*EXT' response; + endif; + p main e + * + ************************************************************************** + * Attachment data callback procedure. + ************************************************************************** + * + p out_data_cb b + d out_data_cb pi 10u 0 + d ptr * value Output data pointer + d size 10u 0 value Data element size + d nmemb 10u 0 value Data element count + d userdata * value User data pointer + * + d buffer s 9999999 based(ptr) Output buffer + d line s 9999999 based(lineptr) ASCII line pointer + d linelen s 10u 0 + d i s 10u 0 Buffer position + * + size = size * nmemb; // The size in bytes. + i = 0; + dow size - i >= %len(SRCDTA) + %len(crlf) and not %eof(RPGXAMPLES); + read record; + lineptr = curl_from_ccsid(%trimr(SRCDTA) + crlf: 0); + linelen = %scan(X'00': line) - 1; + %subst(buffer: i + 1: linelen) = %str(lineptr); + curl_free(lineptr); + i = i + linelen; + enddo; + return i; + p out_data_cb e + * + ************************************************************************** + * Mail-formatted date procedure. + ************************************************************************** + * + p mail_date b + d mail_date pi 50 varying + * + d sysval ds qualified To retrieve timezone + d numsysval 10u 0 + d offset 10u 0 + d 100 + * + d get_sysval pr extpgm('QWCRSVAL') + d outdata likeds(sysval) + d outsize 10u 0 const + d numsysval 10u 0 const + d name 10 const + d errcode 10000 options(*varsize) + * + d now ds qualified + d ts z + d year 4s 0 overlay(ts: 1) + d month 2s 0 overlay(ts: 6) + d day 2s 0 overlay(ts: 9) + d hour 2s 0 overlay(ts: 12) + d minute 2 overlay(ts: 15) + d second 2 overlay(ts: 18) + * + d sysvalinfo ds qualified based(sysvalinfoptr) + d name 10 + d type 1 + d status 1 + d length 10u 0 + d value 99999 + * + d qusec ds qualified + d 10u 0 inz(0) + * + d weekday s 10u 0 + * + now.ts = %timestamp(*SYS); + get_sysval(sysval: %len(sysval): 1: 'QUTCOFFSET': qusec); + sysvalinfoptr = %addr(sysval) + sysval.offset; + weekday = %rem(%diff(now.ts: %timestamp('2001-01-01-00.00.00.000000'): + *DAYS): 7); + return %subst('MonTueWedThuFriSatSun': 3 * weekday + 1: 3) + ', ' + + %char(now.day) + ' ' + + %subst('JanFebMarAprMayJunJulAugSepOctNovDec': + 3 * now.month - 2: 3) + ' ' + + %char(now.year) + ' ' + + %char(now.hour) + ':' + now.minute + ':' + now.second + ' ' + + %subst(sysvalinfo.value: 1: sysvalinfo.length); + p mail_date e + * + ************************************************************************** + * Get the length of right-trimmed string + ************************************************************************** + * + p trimmed_length b + d trimmed_length pi 10u 0 + d string 999999 const options(*varsize) + d length 10u 0 value + * + d addrdiff s 10i 0 + d len s 10u 0 + * + len = %scan(X'00': string: 1: length); // Limit to zero-terminated string + if len = 0; + len = length + 1; + endif; + if len <= 1; + return 0; + endif; + return %checkr(' ': string: len - 1); // Trim right + p trimmed_length e diff --git a/third_party/curl/packages/README.md b/third_party/curl/packages/README.md new file mode 100644 index 0000000..f52f8e4 --- /dev/null +++ b/third_party/curl/packages/README.md @@ -0,0 +1,12 @@ + + +# Packages + + This directory and all its subdirectories are for special package +information, templates, scripts and docs. The files herein should be of use +for those of you who want to package curl in a binary or source format for +these platforms. diff --git a/third_party/curl/packages/vms/Makefile.am b/third_party/curl/packages/vms/Makefile.am new file mode 100644 index 0000000..e869a89 --- /dev/null +++ b/third_party/curl/packages/vms/Makefile.am @@ -0,0 +1,59 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +EXTRA_DIST = \ + backup_gnv_curl_src.com \ + build_curl-config_script.com \ + build_gnv_curl.com \ + build_gnv_curl_pcsi_desc.com \ + build_gnv_curl_pcsi_text.com \ + build_gnv_curl_release_notes.com \ + build_libcurl_pc.com \ + build_vms.com \ + clean_gnv_curl.com \ + compare_curl_source.com \ + config_h.com \ + curl_crtl_init.c \ + curl_gnv_build_steps.txt \ + curl_release_note_start.txt \ + curl_startup.com \ + curlmsg.h \ + curlmsg.msg \ + curlmsg.sdl \ + curlmsg_vms.h \ + generate_config_vms_h_curl.com \ + generate_vax_transfer.com \ + gnv_conftest.c_first \ + gnv_curl_configure.sh \ + gnv_libcurl_symbols.opt \ + gnv_link_curl.com \ + macro32_exactcase.patch \ + make_gnv_curl_install.sh \ + make_pcsi_curl_kit_name.com \ + pcsi_gnv_curl_file_list.txt \ + pcsi_product_gnv_curl.com \ + readme \ + report_openssl_version.c \ + setup_gnv_curl_build.com \ + stage_curl_install.com \ + vms_eco_level.h diff --git a/third_party/curl/packages/vms/Makefile.in b/third_party/curl/packages/vms/Makefile.in new file mode 100644 index 0000000..9ecd712 --- /dev/null +++ b/third_party/curl/packages/vms/Makefile.in @@ -0,0 +1,628 @@ +# Makefile.in generated by automake 1.16.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994-2021 Free Software Foundation, Inc. + +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ +VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = packages/vms +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4/curl-amissl.m4 \ + $(top_srcdir)/m4/curl-bearssl.m4 \ + $(top_srcdir)/m4/curl-compilers.m4 \ + $(top_srcdir)/m4/curl-confopts.m4 \ + $(top_srcdir)/m4/curl-functions.m4 \ + $(top_srcdir)/m4/curl-gnutls.m4 \ + $(top_srcdir)/m4/curl-mbedtls.m4 \ + $(top_srcdir)/m4/curl-openssl.m4 \ + $(top_srcdir)/m4/curl-override.m4 \ + $(top_srcdir)/m4/curl-reentrant.m4 \ + $(top_srcdir)/m4/curl-rustls.m4 \ + $(top_srcdir)/m4/curl-schannel.m4 \ + $(top_srcdir)/m4/curl-sectransp.m4 \ + $(top_srcdir)/m4/curl-sysconfig.m4 \ + $(top_srcdir)/m4/curl-wolfssl.m4 $(top_srcdir)/m4/libtool.m4 \ + $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ + $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ + $(top_srcdir)/m4/xc-am-iface.m4 \ + $(top_srcdir)/m4/xc-cc-check.m4 \ + $(top_srcdir)/m4/xc-lt-iface.m4 \ + $(top_srcdir)/m4/xc-translit.m4 \ + $(top_srcdir)/m4/xc-val-flgs.m4 \ + $(top_srcdir)/m4/zz40-xc-ovr.m4 \ + $(top_srcdir)/m4/zz50-xc-ovr.m4 \ + $(top_srcdir)/m4/zz60-xc-ovr.m4 $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/lib/curl_config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +SOURCES = +DIST_SOURCES = +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +am__DIST_COMMON = $(srcdir)/Makefile.in +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +APACHECTL = @APACHECTL@ +APXS = @APXS@ +AR = @AR@ +AR_FLAGS = @AR_FLAGS@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +BLANK_AT_MAKETIME = @BLANK_AT_MAKETIME@ +CADDY = @CADDY@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CFLAG_CURL_SYMBOL_HIDING = @CFLAG_CURL_SYMBOL_HIDING@ +CONFIGURE_OPTIONS = @CONFIGURE_OPTIONS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CPPFLAG_CURL_STATICLIB = @CPPFLAG_CURL_STATICLIB@ +CSCOPE = @CSCOPE@ +CTAGS = @CTAGS@ +CURLVERSION = @CURLVERSION@ +CURL_CA_BUNDLE = @CURL_CA_BUNDLE@ +CURL_CFLAG_EXTRAS = @CURL_CFLAG_EXTRAS@ +CURL_DISABLE_DICT = @CURL_DISABLE_DICT@ +CURL_DISABLE_FILE = @CURL_DISABLE_FILE@ +CURL_DISABLE_FTP = @CURL_DISABLE_FTP@ +CURL_DISABLE_GOPHER = @CURL_DISABLE_GOPHER@ +CURL_DISABLE_HTTP = @CURL_DISABLE_HTTP@ +CURL_DISABLE_IMAP = @CURL_DISABLE_IMAP@ +CURL_DISABLE_LDAP = @CURL_DISABLE_LDAP@ +CURL_DISABLE_LDAPS = @CURL_DISABLE_LDAPS@ +CURL_DISABLE_MQTT = @CURL_DISABLE_MQTT@ +CURL_DISABLE_POP3 = @CURL_DISABLE_POP3@ +CURL_DISABLE_PROXY = @CURL_DISABLE_PROXY@ +CURL_DISABLE_RTSP = @CURL_DISABLE_RTSP@ +CURL_DISABLE_SMB = @CURL_DISABLE_SMB@ +CURL_DISABLE_SMTP = @CURL_DISABLE_SMTP@ +CURL_DISABLE_TELNET = @CURL_DISABLE_TELNET@ +CURL_DISABLE_TFTP = @CURL_DISABLE_TFTP@ +CURL_LT_SHLIB_VERSIONED_FLAVOUR = @CURL_LT_SHLIB_VERSIONED_FLAVOUR@ +CURL_NETWORK_AND_TIME_LIBS = @CURL_NETWORK_AND_TIME_LIBS@ +CURL_NETWORK_LIBS = @CURL_NETWORK_LIBS@ +CURL_WITH_MULTI_SSL = @CURL_WITH_MULTI_SSL@ +CYGPATH_W = @CYGPATH_W@ +DEFAULT_SSL_BACKEND = @DEFAULT_SSL_BACKEND@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +ENABLE_SHARED = @ENABLE_SHARED@ +ENABLE_STATIC = @ENABLE_STATIC@ +ETAGS = @ETAGS@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +FILECMD = @FILECMD@ +FISH_FUNCTIONS_DIR = @FISH_FUNCTIONS_DIR@ +GCOV = @GCOV@ +GREP = @GREP@ +HAVE_BROTLI = @HAVE_BROTLI@ +HAVE_GNUTLS_SRP = @HAVE_GNUTLS_SRP@ +HAVE_LDAP_SSL = @HAVE_LDAP_SSL@ +HAVE_LIBZ = @HAVE_LIBZ@ +HAVE_OPENSSL_QUIC = @HAVE_OPENSSL_QUIC@ +HAVE_OPENSSL_SRP = @HAVE_OPENSSL_SRP@ +HAVE_PROTO_BSDSOCKET_H = @HAVE_PROTO_BSDSOCKET_H@ +HAVE_ZSTD = @HAVE_ZSTD@ +HTTPD = @HTTPD@ +HTTPD_NGHTTPX = @HTTPD_NGHTTPX@ +IDN_ENABLED = @IDN_ENABLED@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +IPV6_ENABLED = @IPV6_ENABLED@ +LCOV = @LCOV@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBCURL_LIBS = @LIBCURL_LIBS@ +LIBCURL_NO_SHARED = @LIBCURL_NO_SHARED@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ +MAINT = @MAINT@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PERL = @PERL@ +PKGADD_NAME = @PKGADD_NAME@ +PKGADD_PKG = @PKGADD_PKG@ +PKGADD_VENDOR = @PKGADD_VENDOR@ +PKGCONFIG = @PKGCONFIG@ +RANDOM_FILE = @RANDOM_FILE@ +RANLIB = @RANLIB@ +RC = @RC@ +REQUIRE_LIB_DEPS = @REQUIRE_LIB_DEPS@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SSL_BACKENDS = @SSL_BACKENDS@ +SSL_ENABLED = @SSL_ENABLED@ +SSL_LIBS = @SSL_LIBS@ +STRIP = @STRIP@ +SUPPORT_FEATURES = @SUPPORT_FEATURES@ +SUPPORT_PROTOCOLS = @SUPPORT_PROTOCOLS@ +TEST_NGHTTPX = @TEST_NGHTTPX@ +USE_ARES = @USE_ARES@ +USE_BEARSSL = @USE_BEARSSL@ +USE_GNUTLS = @USE_GNUTLS@ +USE_HYPER = @USE_HYPER@ +USE_LIBPSL = @USE_LIBPSL@ +USE_LIBRTMP = @USE_LIBRTMP@ +USE_LIBSSH = @USE_LIBSSH@ +USE_LIBSSH2 = @USE_LIBSSH2@ +USE_MBEDTLS = @USE_MBEDTLS@ +USE_MSH3 = @USE_MSH3@ +USE_NGHTTP2 = @USE_NGHTTP2@ +USE_NGHTTP3 = @USE_NGHTTP3@ +USE_NGTCP2 = @USE_NGTCP2@ +USE_NGTCP2_CRYPTO_BORINGSSL = @USE_NGTCP2_CRYPTO_BORINGSSL@ +USE_NGTCP2_CRYPTO_GNUTLS = @USE_NGTCP2_CRYPTO_GNUTLS@ +USE_NGTCP2_CRYPTO_QUICTLS = @USE_NGTCP2_CRYPTO_QUICTLS@ +USE_NGTCP2_CRYPTO_WOLFSSL = @USE_NGTCP2_CRYPTO_WOLFSSL@ +USE_NGTCP2_H3 = @USE_NGTCP2_H3@ +USE_OPENLDAP = @USE_OPENLDAP@ +USE_OPENSSL_H3 = @USE_OPENSSL_H3@ +USE_OPENSSL_QUIC = @USE_OPENSSL_QUIC@ +USE_QUICHE = @USE_QUICHE@ +USE_RUSTLS = @USE_RUSTLS@ +USE_SCHANNEL = @USE_SCHANNEL@ +USE_SECTRANSP = @USE_SECTRANSP@ +USE_UNIX_SOCKETS = @USE_UNIX_SOCKETS@ +USE_WIN32_CRYPTO = @USE_WIN32_CRYPTO@ +USE_WIN32_LARGE_FILES = @USE_WIN32_LARGE_FILES@ +USE_WIN32_SMALL_FILES = @USE_WIN32_SMALL_FILES@ +USE_WINDOWS_SSPI = @USE_WINDOWS_SSPI@ +USE_WOLFSSH = @USE_WOLFSSH@ +USE_WOLFSSL = @USE_WOLFSSL@ +VERSION = @VERSION@ +VERSIONNUM = @VERSIONNUM@ +VSFTPD = @VSFTPD@ +ZLIB_LIBS = @ZLIB_LIBS@ +ZSH_FUNCTIONS_DIR = @ZSH_FUNCTIONS_DIR@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +libext = @libext@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +runstatedir = @runstatedir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ + +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +EXTRA_DIST = \ + backup_gnv_curl_src.com \ + build_curl-config_script.com \ + build_gnv_curl.com \ + build_gnv_curl_pcsi_desc.com \ + build_gnv_curl_pcsi_text.com \ + build_gnv_curl_release_notes.com \ + build_libcurl_pc.com \ + build_vms.com \ + clean_gnv_curl.com \ + compare_curl_source.com \ + config_h.com \ + curl_crtl_init.c \ + curl_gnv_build_steps.txt \ + curl_release_note_start.txt \ + curl_startup.com \ + curlmsg.h \ + curlmsg.msg \ + curlmsg.sdl \ + curlmsg_vms.h \ + generate_config_vms_h_curl.com \ + generate_vax_transfer.com \ + gnv_conftest.c_first \ + gnv_curl_configure.sh \ + gnv_libcurl_symbols.opt \ + gnv_link_curl.com \ + macro32_exactcase.patch \ + make_gnv_curl_install.sh \ + make_pcsi_curl_kit_name.com \ + pcsi_gnv_curl_file_list.txt \ + pcsi_product_gnv_curl.com \ + readme \ + report_openssl_version.c \ + setup_gnv_curl_build.com \ + stage_curl_install.com \ + vms_eco_level.h + +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu packages/vms/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --gnu packages/vms/Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +tags TAGS: + +ctags CTAGS: + +cscope cscopelist: + +distdir: $(BUILT_SOURCES) + $(MAKE) $(AM_MAKEFLAGS) distdir-am + +distdir-am: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile +installdirs: +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: + +.MAKE: install-am install-strip + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + cscopelist-am ctags-am distclean distclean-generic \ + distclean-libtool distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + tags-am uninstall uninstall-am + +.PRECIOUS: Makefile + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/third_party/curl/packages/vms/backup_gnv_curl_src.com b/third_party/curl/packages/vms/backup_gnv_curl_src.com new file mode 100644 index 0000000..298f11f --- /dev/null +++ b/third_party/curl/packages/vms/backup_gnv_curl_src.com @@ -0,0 +1,130 @@ +$! File: Backup_gnv_curl_src.com +$! +$! Procedure to create backup save sets for installing in a PCSI kit. +$! +$! To comply with most Open Source licenses, the source used for building +$! a kit will be packaged with the distribution kit for the binary. +$! +$! Backup save sets are the only storage format that I can expect a +$! VMS system to be able to extract ODS-5 filenames and directories. +$! +$! The make_pcsi_kit_name.com needs to be run before this procedure to +$! properly name the files that will be created. +$! +$! This file is created from a template file for the purpose of making it +$! easier to port Unix code, particularly open source code to VMS. +$! Therefore permission is freely granted for any use. +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!=========================================================================== +$! +$! Save default +$ default_dir = f$environment("DEFAULT") +$! +$ arch_type = f$getsyi("ARCH_NAME") +$ arch_code = f$extract(0, 1, arch_type) +$! +$ if arch_code .nes. "V" +$ then +$ set proc/parse=extended +$ endif +$! +$ ss_abort = 44 +$ status = ss_abort +$! +$ kit_name = f$trnlnm("GNV_PCSI_KITNAME") +$ if kit_name .eqs. "" +$ then +$ write sys$output "@MAKE_PCSI_CURL_KIT_NAME.COM has not been run." +$ goto all_exit +$ endif +$ producer = f$trnlnm("GNV_PCSI_PRODUCER") +$ if producer .eqs. "" +$ then +$ write sys$output "@MAKE_PCSI_CURL_KIT_NAME.COM has not been run." +$ goto all_exit +$ endif +$ filename_base = f$trnlnm("GNV_PCSI_FILENAME_BASE") +$ if filename_base .eqs. "" +$ then +$ write sys$output "@MAKE_PCSI_CURL_KIT_NAME.COM has not been run." +$ goto all_exit +$ endif +$! +$ node_swvers = f$getsyi("NODE_SWVERS") +$ node_swvers_type = f$extract(0, 1, node_swvers) +$ node_swvers_vers = f$extract(1, f$length(node_swvers), node_swvers) +$ swvers_maj = f$element(0, ".", node_swvers_vers) +$ node_swvers_min_update = f$element(1, ".", node_swvers_vers) +$ swvers_min = f$element(0, "-", node_swvers_min_update) +$ swvers_update = f$element(1, "-", node_swvers_min_update) +$! +$ if swvers_update .eqs. "-" then swvers_update = "" +$! +$ vms_vers = f$fao("!2ZB!2ZB!AS", 'swvers_maj', 'swvers_min', swvers_update) +$! +$! +$! +$! If available make an interchange save set +$!------------------------------------------- +$ interchange = "" +$ if arch_code .eqs. "V" +$ then +$ interchange = "/interchange" +$ endif +$ if (swvers_maj .ges. "8") .and. (swvers_min .ges. 4) +$ then +$ interchange = "/interchange/noconvert" +$ endif +$! +$! +$! Move to the base directories +$ set def [--] +$! +$! Put things back on error. +$ on warning then goto all_exit +$! +$ current_default = f$environment("DEFAULT") +$ my_dir = f$parse(current_default,,,"DIRECTORY") - "[" - "<" - ">" - "]" +$! +$ src_root = "src_root:" +$ if f$trnlnm("src_root1") .nes. "" then src_root = "src_root1:" +$ backup'interchange' 'src_root'[curl...]*.*;0 - + 'filename_base'_original_src.bck/sav +$ status = $status +$! +$! There may be a VMS specific source kit +$!----------------------------------------- +$ vms_root = "vms_root:" +$ if f$trnlnm("vms_root1") .nes. "" then vms_root = "vms_root1:" +$ files_found = 0 +$ define/user sys$error nl: +$ define/user sys$output nl: +$ directory 'vms_root'[...]*.*;*/exc=*.dir +$ if '$severity' .eq. 1 then files_found = 1 +$! +$ if files_found .eq. 1 +$ then +$ backup'interchange' 'vms_root'[curl...]*.*;0 - + 'filename_base'_vms_src.bck/sav +$ status = $status +$ endif +$! +$all_exit: +$ set def 'default_dir' +$ exit diff --git a/third_party/curl/packages/vms/build_curl-config_script.com b/third_party/curl/packages/vms/build_curl-config_script.com new file mode 100644 index 0000000..1667d07 --- /dev/null +++ b/third_party/curl/packages/vms/build_curl-config_script.com @@ -0,0 +1,153 @@ +$! build_curl-config_script.com +$! +$! This generates the curl-config. script from the curl-config.in file. +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!=========================================================================== +$! +$! Skip this if the curl-config. already exists. +$ if f$search("[--]curl-config.") .nes. "" then goto all_exit +$! +$ if (f$getsyi("HW_MODEL") .lt. 1024) +$ then +$ arch_name = "VAX" +$ else +$ arch_name = "" +$ arch_name = arch_name + f$edit(f$getsyi("ARCH_NAME"), "UPCASE") +$ if (arch_name .eqs. "") then arch_name = "UNK" +$ endif +$! +$ x_prefix = "/usr" +$ x_exec_prefix = "/usr" +$ x_includedir = "${prefix}/include" +$ x_cppflag_curl_staticlib = "-DCURL_STATICLIB" +$ x_enabled_shared = "no" +$ x_curl_ca_bundle = "" +$ x_cc = "cc" +$ x_support_features = "SSL IPv6 libz NTLM" +$ x_support_protocols1 = "DICT FILE FTP FTPS GOPHER HTTP HTTPS IMAP IMAPS LDAP" +$ x_support_protocols2 = " LDAPS POP3 POP3S RTSP SMTP SMTPS TELNET TFTP" +$ x_support_protocols = x_support_protocols1 + x_support_protocols2 +$ x_curlversion = "0.0.0.0" +$ x_versionnum = "" +$ x_libdir = "${prefix}/lib" +$ x_require_lib_deps = "" +$ x_enable_static = "" +$ x_ldflags = "" +$ part1 = "-L/usr/lib -L/SSL_LIB -lssl -lcrypto -lz" +$ if arch_name .eqs. "VAX" +$ then +$ x_libcurl_libs = part1 +$ else +$ x_libcurl_libs = part1 + " -lgssapi" +$ endif +$ x_libext = "a" +$! +$! Get the version number +$!----------------------- +$ i = 0 +$ open/read/error=version_loop_end vhf [--.include.curl]curlver.h +$ version_loop: +$ read/end=version_loop_end vhf line_in +$ if line_in .eqs. "" then goto version_loop +$ if f$locate("#define LIBCURL_VERSION ", line_in) .eq. 0 +$ then +$ x_curlversion = f$element(2," ", line_in) - """" - """" +$ i = i + 1 +$ endif +$ if f$locate("#define LIBCURL_VERSION_NUM ", line_in) .eq. 0 +$ then +$ x_versionnum = f$element(2," ", line_in) - """" - """" +$ i = i + 1 +$ endif +$ if i .lt 2 then goto version_loop +$ version_loop_end: +$ close vhf +$! +$ kit_type = "V" +$ if f$locate("-", x_curlversion) .lt. f$length(x_curlversion) +$ then +$ kit_type = "D" +$ x_prefix = "/beta" +$ x_exec_prefix = "/beta" +$ endif +$! +$ if kit_type .nes. "D" +$ then +$ part1 = " echo "" '--prefix=/usr' '--exec-prefix=/usr' " +$ else +$ part1 = " echo "" '--prefix=/beta' '--exec_prefix=/beta' " +$ endif +$ if arch_name .eqs. "VAX" +$ then +$ part3 = "" +$ else +$ part3 = "'--with-gssapi' " +$ endif +$ part2 = "'--disable-dependency-tracking' '--disable-libtool-lock' " +$ part4 = "'--disable-ntlm-wb' '--with-ca-path=gnv$curl_ca_path'""" +$! +$ x_configure_options = part1 + part2 + part3 + part4 +$! +$! +$ open/read/error=read_loop_end c_c_in sys$disk:[--]curl-config.in +$ create sys$disk:[--]curl-config. +$ open/append c_c_out sys$disk:[--]curl-config. +$read_loop: +$ read/end=read_loop_end c_c_in line_in +$ line_in_len = f$length(line_in) +$ if f$locate("@", line_in) .ge. line_in_len +$ then +$ write c_c_out line_in +$ goto read_loop +$ endif +$ i = 0 +$ line_out = "" +$sub_loop: +$ ! Replace between pairs of @ by alternating the elements. +$ ! If mis-matched pairs, do not substitute anything. +$ section1 = f$element(i, "@", line_in) +$ if section1 .eqs. "@" +$ then +$ goto sub_loop_end +$ endif +$ i = i + 1 +$ section2 = f$element(i, "@", line_in) +$ if section2 .eqs. "@" +$ then +$ goto sub_loop_end +$ endif +$ i = i + 1 +$ section3 = f$element(i, "@", line_in) +$ if section3 .eqs. "@" +$ then +$ if line_out .eqs. "" then line_out = line_in +$ goto sub_loop_end +$ endif +$ line_out = line_out + section1 +$ if f$type(x_'section2') .eqs. "STRING" +$ then +$ line_out = line_out + x_'section2' +$ endif +$ goto sub_loop +$sub_loop_end: +$ write c_c_out line_out +$ goto read_loop +$read_loop_end: +$ close c_c_in +$ close c_c_out diff --git a/third_party/curl/packages/vms/build_gnv_curl.com b/third_party/curl/packages/vms/build_gnv_curl.com new file mode 100644 index 0000000..36e7281 --- /dev/null +++ b/third_party/curl/packages/vms/build_gnv_curl.com @@ -0,0 +1,36 @@ +$! File: build_gnv_curl.com +$! +$! All in one build procedure +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!----------------------------------------------------------------------- +$! +$ @setup_gnv_curl_build.com +$! +$ bash gnv_curl_configure.sh +$! +$ @clean_gnv_curl.com +$! +$ bash make_gnv_curl_install.sh +$! +$ @gnv_link_curl.com +$! +$ purge new_gnu:[*...]/log +$! +$! +$exit diff --git a/third_party/curl/packages/vms/build_gnv_curl_pcsi_desc.com b/third_party/curl/packages/vms/build_gnv_curl_pcsi_desc.com new file mode 100644 index 0000000..8567426 --- /dev/null +++ b/third_party/curl/packages/vms/build_gnv_curl_pcsi_desc.com @@ -0,0 +1,489 @@ +$! File: Build_GNV_CURL_PCSI_DESC.COM +$! +$! Build the *.pcsi$text file in the following sections: +$! Required software dependencies. +$! install/upgrade/postinstall steps. +$! 1. Duplicate filenames need an alias procedure. (N/A for curl) +$! 2. ODS-5 filenames need an alias procedure. (N/A for curl) +$! 3. Special alias links for executables (curl. -> curl.exe) +$! if a lot, then an alias procedure is needed. +$! 4. Rename the files to lowercase. +$! Move Release Notes to destination +$! Source kit option +$! Create directory lines +$! Add file lines for curl. +$! Add Link alias procedure file (N/A for curl) +$! Add [.SYS$STARTUP]curl_startup file +$! Add Release notes file. +$! +$! The file PCSI_GNV_CURL_FILE_LIST.TXT is read in to get the files other +$! than the release notes file and the source backup file. +$! +$! The PCSI system can really only handle ODS-2 format filenames and +$! assumes that there is only one source directory. It also assumes that +$! all destination files with the same name come from the same source file. +$! Fortunately CURL does not trip most of these issues, so those steps +$! above are marked N/A. +$! +$! A rename action section is needed to make sure that the files are +$! created in the GNV$GNU: in the correct case, and to create the alias +$! link [usr.bin]curl. for [usr.bin]curl.exe. +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!=========================================================================== +$! +$ kit_name = f$trnlnm("GNV_PCSI_KITNAME") +$ if kit_name .eqs. "" +$ then +$ write sys$output "@MAKE_PCSI_CURL_KIT_NAME.COM has not been run." +$ goto all_exit +$ endif +$ producer = f$trnlnm("GNV_PCSI_PRODUCER") +$ if producer .eqs. "" +$ then +$ write sys$output "@MAKE_PCSI_CURL_KIT_NAME.COM has not been run." +$ goto all_exit +$ endif +$ filename_base = f$trnlnm("GNV_PCSI_FILENAME_BASE") +$ if filename_base .eqs. "" +$ then +$ write sys$output "@MAKE_PCSI_CURL_KIT_NAME.COM has not been run." +$ goto all_exit +$ endif +$! +$! +$! Parse the kit name into components. +$!--------------------------------------- +$ producer = f$element(0, "-", kit_name) +$ base = f$element(1, "-", kit_name) +$ product = f$element(2, "-", kit_name) +$ mmversion = f$element(3, "-", kit_name) +$ majorver = f$extract(0, 3, mmversion) +$ minorver = f$extract(3, 2, mmversion) +$ updatepatch = f$element(4, "-", kit_name) +$ if updatepatch .eqs. "-" then updatepatch = "" +$! +$! kit type of "D" means a daily build +$ kit_type = f$edit(f$extract(0, 1, majorver), "upcase") +$! +$! +$ product_line = "product ''producer' ''base' ''product'" +$ if updatepatch .eqs. "" +$ then +$ product_name = " ''majorver'.''minorver'" +$ else +$ product_name = " ''majorver'.''minorver'-''updatepatch'" +$ endif +$ product_line = product_line + " ''product_name' full;" +$!write sys$output product_line +$! +$! +$! +$! Create the file as a VMS text file. +$!---------------------------------------- +$ base_file = kit_name +$ create 'base_file'.pcsi$desc +$! +$! +$! Start building file. +$!---------------------- +$ open/append pdsc 'base_file'.pcsi$desc +$! +$ write pdsc product_line +$! +$! Required product dependencies. +$!---------------------------------- +$ vmsprd = "DEC" +$ if base .eqs. "I64VMS" then vmsprd = "HP" +$ vsiprd = "VSI" +$! +$ write pdsc " software ''vmsprd' ''base' VMS ;" +$ arch_type = f$getsyi("ARCH_NAME") +$ node_swvers = f$getsyi("node_swvers") +$ vernum = f$extract(1, f$length(node_swvers), node_swvers) +$ majver = f$element(0, ".", vernum) +$ minverdash = f$element(1, ".", vernum) +$ minver = f$element(0, "-", minverdash) +$ dashver = f$element(1, "-", minverdash) +$ if dashver .eqs. "-" then dashver = "" +$ vmstag = majver + minver + dashver +$ code = f$extract(0, 1, arch_type) +$ arch_code = f$extract(0, 1, arch_type) +$ line_out = - + " if ((not ) and" + - + " (not ));" +$ write pdsc line_out +$ write pdsc " error NEED_VMS''vmstag';" +$ write pdsc " end if;" +$! +$write pdsc " software VMSPORTS ''base' ZLIB ;" +$write pdsc - + " if (not ) ;" +$write pdsc " error NEED_ZLIB;" +$write pdsc " end if;" +$! +$! +$! +$! install/upgrade/postinstall steps. +$!----------------------------------- +$! 1. Duplicate filenames need an alias procedure. (N/A for curl) +$! 2. ODS-5 filenames need an alias procedure. (N/A for curl) +$! 3. Special alias links for executables (curl. -> curl.exe) +$! if a lot, then an alias procedure is needed. +$! 4. Rename the files to lowercase. +$! +$! +$! Alias links needed. +$!------------------------- +$ add_alias_lines = "" +$ rem_alias_lines = "" +$ line_out = "" +$! +$! Read through the file list to set up aliases and rename commands. +$!--------------------------------------------------------------------- +$ open/read flst pcsi_gnv_curl_file_list.txt +$! +$inst_alias_loop: +$ read/end=inst_alias_loop_end flst line_in +$ line_in = f$edit(line_in,"compress,trim,uncomment") +$ if line_in .eqs. "" then goto inst_alias_loop +$ pathname = f$element(0, " ", line_in) +$ linkflag = f$element(1, " ", line_in) + +$ if linkflag .nes. "->" then goto inst_alias_write +$! +$ linktarget = f$element(2, " ", line_in) +$ if kit_type .eqs. "D" +$ then +$ old_start = f$locate("[gnv.usr", pathname) +$ if old_start .lt. f$length(pathname) +$ then +$ pathname = "[gnv.beta" + pathname - "[gnv.usr" +$ linktarget = "[gnv.beta" + linktarget - "[gnv.usr" +$ endif +$ endif +$ nlink = "pcsi$destination:" + pathname +$ ntarg = "pcsi$destination:" + linktarget +$ new_add_alias_line = - + """if f$search(""""''nlink'"""") .eqs. """""""" then" + - + " set file/enter=''nlink' ''ntarg'""" +$ if add_alias_lines .nes. "" +$ then +$ add_alias_lines = add_alias_lines + "," + new_add_alias_line +$ else +$ add_alias_lines = new_add_alias_line +$ endif +$! +$ new_rem_alias_line = - + """if f$search(""""''nlink'"""") .nes. """""""" then" + - + " set file/remove ''nlink';""" +$ if rem_alias_lines .nes. "" +$ then +$ rem_alias_lines = rem_alias_lines + "," + new_rem_alias_line +$ else +$ rem_alias_lines = new_rem_alias_line +$ endif +$! +$ goto inst_alias_loop +$! +$inst_alias_write: +$! +$! execute install / remove +$ write pdsc " execute install (" +$! add aliases +$ i = 0 +$ex_ins_loop: +$ line = f$element(i, ",", add_alias_lines) +$ i = i + 1 +$ if line .eqs. "" then goto ex_ins_loop +$ if line .eqs. "," then goto ex_ins_loop_end +$ if line_out .nes. "" then write pdsc line_out,"," +$ line_out = line +$ goto ex_ins_loop +$ex_ins_loop_end: +$ write pdsc line_out +$ line_out = "" +$ write pdsc " )" +$ write pdsc " remove (" +$! remove aliases +$ i = 0 +$ex_rem_loop: +$ line = f$element(i, ",", rem_alias_lines) +$ i = i + 1 +$ if line .eqs. "" then goto ex_rem_loop +$ if line .eqs. "," then goto ex_rem_loop_end +$ if line_out .nes. "" then write pdsc line_out,"," +$ line_out = line +$ goto ex_rem_loop +$ex_rem_loop_end: +$ write pdsc line_out +$ line_out = "" +$ write pdsc " ) ;" +$! +$! execute upgrade +$ write pdsc " execute upgrade (" +$ i = 0 +$ex_upg_loop: +$ line = f$element(i, ",", rem_alias_lines) +$ i = i + 1 +$ if line .eqs. "" then goto ex_upg_loop +$ if line .eqs. "," then goto ex_upg_loop_end +$ if line_out .nes. "" then write pdsc line_out,"," +$ line_out = line +$ goto ex_upg_loop +$ex_upg_loop_end: +$ write pdsc line_out +$ line_out = "" +$! remove aliases +$ write pdsc " ) ;" +$! +$! execute postinstall +$ write pdsc " execute postinstall (" +$ if arch_code .nes. "V" +$ then +$ line_out = " ""set process/parse=extended""" +$ endif +$ i = 0 +$ex_pins_loop: +$ line = f$element(i, ",", add_alias_lines) +$ i = i + 1 +$ if line .eqs. "" then goto ex_pins_loop +$ if line .eqs. "," then goto ex_pins_loop_end +$ if line_out .nes. "" then write pdsc line_out,"," +$ line_out = line +$ goto ex_pins_loop +$ex_pins_loop_end: +$ if line_out .eqs. "" then line_out = " ""continue""" +$! write pdsc line_out +$! line_out = "" +$! add aliases and follow with renames. +$! +$goto inst_dir +$! +$inst_dir_loop: +$ read/end=inst_alias_loop_end flst line_in +$ line_in = f$edit(line_in,"compress,trim,uncomment") +$ if line_in .eqs. "" then goto inst_dir_loop +$inst_dir: +$ pathname = f$element(0, " ", line_in) +$ if kit_type .eqs. "D" +$ then +$ if pathname .eqs. "[gnv]usr.dir" +$ then +$ pathname = "[gnv]beta.dir" +$ else +$ old_start = f$locate("[gnv.usr", pathname) +$ if old_start .lt. f$length(pathname) +$ then +$ pathname = "[gnv.beta" + pathname - "[gnv.usr" +$ endif +$ endif +$ endif +$! +$! Ignore the directory entries for now. +$!----------------------------------------- +$ filedir = f$parse(pathname,,,"DIRECTORY") +$ if pathname .eqs. filedir then goto inst_dir_loop +$! +$! process .dir extensions for rename +$! If this is not a directory then start processing files. +$!------------------------- +$ filetype = f$parse(pathname,,,"TYPE") +$ filetype_u = f$edit(filetype, "upcase") +$ filename = f$parse(pathname,,,"NAME") +$ if filetype_u .nes. ".DIR" then goto inst_file +$! +$! process directory lines for rename. +$!-------------------------------------- +$ if line_out .nes. "" +$ then +$ write pdsc line_out,"," +$ line_out = "" +$ endif +$ if arch_code .nes. "V" +$ then +$ if line_out .nes. "" then write pdsc line_out,"," +$ line_out = " ""rename pcsi$destination:''pathname' ''filename'.DIR""" +$ else +$ if line_out .nes. "" then write pdsc line_out +$ line_out = "" +$ endif +$ goto inst_dir_loop +$! +$! +$! process file lines for rename +$!--------------------------------- +$inst_file_loop: +$ read/end=inst_alias_loop_end flst line_in +$ line_in = f$edit(line_in,"compress,trim,uncomment") +$ if line_in .eqs. "" then goto inst_dir_loop +$ pathname = f$element(0, " ", line_in) +$ if kit_type .eqs. "D" +$ then +$ if pathname .eqs. "[gnv]usr.dir" +$ then +$ pathname = "[gnv]beta.dir" +$ else +$ old_start = f$locate("[gnv.usr", pathname) +$ if old_start .lt. f$length(pathname) +$ then +$ pathname = "[gnv.beta" + pathname - "[gnv.usr" +$ endif +$ endif +$ endif +$! +$! Filenames with $ in them are VMS special and do not need to be lowercase. +$! -------------------------------------------------------------------------- +$ if f$locate("$", pathname) .lt. f$length(pathname) then goto inst_file_loop +$! +$ filetype = f$parse(pathname,,,"TYPE") +$ filename = f$parse(pathname,,,"NAME") + filetype +$inst_file: +$ if arch_code .nes. "V" +$ then +$ if line_out .nes. "" then write pdsc line_out,"," +$ filetype = f$parse(pathname,,,"TYPE") +$ filename = f$parse(pathname,,,"NAME") + filetype +$ line_out = " ""rename pcsi$destination:''pathname' ''filename'""" +$ else +$ if line_out .nes. "" then write pdsc line_out +$ line_out = "" +$ endif +$ goto inst_file_loop +$! +$inst_alias_loop_end: +$! +$write pdsc line_out +$write pdsc " ) ;" +$close flst +$! +$! Move Release Notes to destination +$!------------------------------------- +$write pdsc " information RELEASE_NOTES phase after ;" +$! +$! Source kit option +$!--------------------- +$write pdsc " option SOURCE default 0;" +$write pdsc " directory ""[gnv.common_src]"" PROTECTION PUBLIC ;" +$write pdsc - + " file ""[gnv.common_src]''filename_base'_original_src.bck""" +$write pdsc - + " source [common_src]''filename_base'_original_src.bck ;" +$if f$search("gnv$gnu:[vms_src]''filename_base'_vms_src.bck") .nes. "" +$then +$ write pdsc " directory ""[gnv.vms_src]"" PROTECTION PUBLIC ;" +$ write pdsc " file ""[gnv.vms_src]''filename_base'_vms_src.bck""" +$ write pdsc " source [vms_src]''filename_base'_vms_src.bck ;" +$endif +$write pdsc " end option;" +$! +$! +$! Read through the file list again. +$!---------------------------------- +$open/read flst pcsi_gnv_curl_file_list.txt +$! +$! +$! Create directory lines +$!------------------------- +$flst_dir_loop: +$ read/end=flst_loop_end flst line_in +$ line_in = f$edit(line_in,"compress,trim,uncomment") +$ if line_in .eqs. "" then goto flst_dir_loop +$! +$ filename = f$element(0, " ", line_in) +$ linkflag = f$element(1, " ", line_in) +$ if linkflag .eqs. "->" then goto flst_dir_loop +$! +$! Ignore .dir extensions +$!------------------------- +$ filetype = f$edit(f$parse(filename,,,"TYPE"), "upcase") +$ if filetype .eqs. ".DIR" then goto flst_dir_loop +$! +$ destname = filename +$ if kit_type .eqs. "D" +$ then +$ old_start = f$locate("[gnv.usr", destname) +$ if old_start .lt. f$length(destname) +$ then +$ destname = "[gnv.beta" + destname - "[gnv.usr" +$ endif +$ endif +$! +$! It should be just a directory then. +$!------------------------------------- +$ filedir = f$edit(f$parse(filename,,,"DIRECTORY"), "lowercase") +$! If this is not a directory then start processing files. +$!--------------------------------------------------------- +$ if filename .nes. filedir then goto flst_file +$! +$ write pdsc " directory ""''destname'"" PROTECTION PUBLIC ;" +$ goto flst_dir_loop +$! +$! +$! Add file lines for curl. +$!--------------------------- +$flst_file_loop: +$ read/end=flst_loop_end flst line_in +$ line_in = f$edit(line_in,"compress,trim,uncomment") +$ if line_in .eqs. "" then goto inst_file_loop +$ filename = f$element(0, " ", line_in) +$ destname = filename +$ if kit_type .eqs. "D" +$ then +$ old_start = f$locate("[gnv.usr", destname) +$ if old_start .lt. f$length(destname) +$ then +$ destname = "[gnv.beta" + destname - "[gnv.usr" +$ endif +$ endif +$flst_file: +$ srcfile = filename - "gnv." +$ write pdsc " file ""''destname'"" " +$ write pdsc " source ""''srcfile'"" ;" +$ goto flst_file_loop +$! +$flst_loop_end: +$ close flst +$! +$! Add Link alias procedure file (N/A for curl) +$!------------------------------------------------ +$! +$! Add [.SYS$STARTUP]curl_startup file +$!--------------------------------------- +$ if kit_type .eqs. "D" +$ then +$ write pdsc " file ""[sys$startup]curl_daily_startup.com""" +$ else +$ write pdsc " file ""[sys$startup]curl_startup.com""" +$ endif +$ write pdsc " source [usr.lib]curl_startup.com ;" +$! +$! Add Release notes file. +$!------------------------------ +$ write pdsc - + " file ""[SYSHLP]''filename_base'.release_notes"" release notes ;" +$! +$! Close the product file +$!------------------------ +$ write pdsc "end product;" +$! +$close pdsc +$! +$all_exit: +$ exit diff --git a/third_party/curl/packages/vms/build_gnv_curl_pcsi_text.com b/third_party/curl/packages/vms/build_gnv_curl_pcsi_text.com new file mode 100644 index 0000000..8f109c1 --- /dev/null +++ b/third_party/curl/packages/vms/build_gnv_curl_pcsi_text.com @@ -0,0 +1,195 @@ +$! File: Build_GNV_curl_pcsi_text.com +$! +$! Build the *.pcsi$text file from the four components: +$! 1. Generated =product header section +$! 2. [--]readme. file from the Curl distribution, modified to fit +$! a pcsi$text file format. +$! 3. [--]copying file from the Curl distribution, modified to fit +$! a pcsi$text file format. +$! 4. Generated Producer section. +$! +$! Set the name of the release notes from the GNV_PCSI_FILENAME_BASE +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!=========================================================================== +$! +$ kit_name = f$trnlnm("GNV_PCSI_KITNAME") +$ if kit_name .eqs. "" +$ then +$ write sys$output "@MAKE_PCSI_CURL_KIT_NAME.COM has not been run." +$ goto all_exit +$ endif +$ producer = f$trnlnm("GNV_PCSI_PRODUCER") +$ if producer .eqs. "" +$ then +$ write sys$output "@MAKE_PCSI_CURL_KIT_NAME.COM has not been run." +$ goto all_exit +$ endif +$ producer_full_name = f$trnlnm("GNV_PCSI_PRODUCER_FULL_NAME") +$ if producer_full_name .eqs. "" +$ then +$ write sys$output "@MAKE_PCSI_CURL_KIT_NAME.COM has not been run." +$ goto all_exit +$ endif +$! +$! +$! Parse the kit name into components. +$!--------------------------------------- +$ producer = f$element(0, "-", kit_name) +$ base = f$element(1, "-", kit_name) +$ product = f$element(2, "-", kit_name) +$ mmversion = f$element(3, "-", kit_name) +$ majorver = f$extract(0, 3, mmversion) +$ minorver = f$extract(3, 2, mmversion) +$ updatepatch = f$element(4, "-", kit_name) +$ if updatepatch .eqs. "-" then updatepatch = "" +$! +$! +$ product_line = "=product ''producer' ''base' ''product'" +$ if updatepatch .eqs. "" +$ then +$ product_name = " ''majorver'.''minorver'" +$ else +$ product_name = " ''majorver'.''minorver'-''updatepatch'" +$ endif +$ product_line = product_line + " ''product_name' full" +$! +$! +$! If this is VAX and the file is on NFS, the names may be mangled. +$!----------------------------------------------------------------- +$ readme_file = "" +$ if f$search("[--]readme.") .nes. "" +$ then +$ readme_file = "[--]readme." +$ else +$ if f$search("[--]$README.") .nes. "" +$ then +$ readme_file = "[--]$README." +$ else +$ write sys$output "Can not find readme file." +$ goto all_exit +$ endif +$ endif +$ copying_file = "" +$ if f$search("[--]copying.") .nes. "" +$ then +$ copying_file = "[--]copying." +$ else +$ if f$search("[--]$COPYING.") .nes. "" +$ then +$ copying_file = "[--]$COPYING." +$ else +$ write sys$output "Can not find copying file." +$ goto all_exit +$ endif +$ endif +$! +$! Create the file as a VMS text file. +$!---------------------------------------- +$ base_file = kit_name +$ create 'base_file'.pcsi$text +$! +$! +$! Start building file. +$!---------------------- +$ open/append ptxt 'base_file'.pcsi$text +$ write ptxt product_line +$! +$! +$! First insert the Readme file. +$! +$ open/read rf 'readme_file' +$! +$ write ptxt "1 'PRODUCT" +$ write ptxt "=prompt ''producter' ''product' for OpenVMS" +$! +$rf_loop: +$ read/end=rf_loop_end rf line_in +$ if line_in .nes. "" +$ then +$! PCSI files use the first character in for their purposes. +$!-------------------------------------------------------------- +$ first_char = f$extract(0, 1, line_in) +$ if first_char .nes. " " then line_in = " " + line_in +$ endif +$ write ptxt line_in +$ goto rf_loop +$rf_loop_end: +$ close rf +$! +$! +$! Now add in the copying file +$!-------------------------------- +$ write ptxt "" +$ write ptxt "1 'NOTICE" +$ write ptxt "" +$! +$ open/read cf 'copying_file' +$! +$cf_loop: +$ read/end=cf_loop_end cf line_in +$ if line_in .nes. "" +$ then +$! PCSI files use the first character in for their purposes. +$!-------------------------------------------------------------- +$ first_char = f$extract(0, 1, line_in) +$ if first_char .nes. " " then line_in = " " + line_in +$ endif +$ write ptxt line_in +$ goto cf_loop +$cf_loop_end: +$ close cf +$! +$! Now we need the rest of the boiler plate. +$!-------------------------------------------- +$ write ptxt "" +$ write ptxt "1 'PRODUCER" +$ write ptxt "=prompt ''producer_full_name'" +$ write ptxt - + "This software product is provided by ''producer_full_name' with no warranty." +$! +$ arch_type = f$getsyi("ARCH_NAME") +$ node_swvers = f$getsyi("node_swvers") +$ vernum = f$extract(1, f$length(node_swvers), node_swvers) +$ majver = f$element(0, ".", vernum) +$ minverdash = f$element(1, ".", vernum) +$ minver = f$element(0, "-", minverdash) +$ dashver = f$element(1, "-", minverdash) +$ if dashver .eqs. "-" then dashver = "" +$ vmstag = majver + minver + dashver +$ code = f$extract(0, 1, arch_type) +$! +$ write ptxt "1 NEED_VMS''vmstag'" +$ write ptxt - + "=prompt OpenVMS ''vernum' or later is not installed on your system." +$ write ptxt "This product requires OpenVMS ''vernum' or later to function." +$ write ptxt "1 NEED_ZLIB" +$ write ptxt "=prompt ZLIB 1.2-8 or later is not installed on your system." +$ write ptxt "This product requires ZLIB 1.2-8 or later to function." +$ write ptxt "1 SOURCE" +$ write ptxt "=prompt Source modules for ''product'" +$ write ptxt "The Source modules for ''product' will be installed." +$ write ptxt "1 RELEASE_NOTES" +$ write ptxt "=prompt Release notes are available in the [SYSHLP] directory." +$! +$ close ptxt +$! +$! +$! +$all_exit: +$ exit diff --git a/third_party/curl/packages/vms/build_gnv_curl_release_notes.com b/third_party/curl/packages/vms/build_gnv_curl_release_notes.com new file mode 100644 index 0000000..0da9445 --- /dev/null +++ b/third_party/curl/packages/vms/build_gnv_curl_release_notes.com @@ -0,0 +1,100 @@ +$! File: Build_GNV_curl_release_notes.com +$! +$! Build the release note file from the four components: +$! 1. The curl_release_note_start.txt +$! 2. The hp_ssl_release_info.txt +$! 3. [--]readme. file from the Curl distribution. +$! 4. The Curl_gnv-build_steps.txt. +$! +$! Set the name of the release notes from the GNV_PCSI_FILENAME_BASE +$! logical name. +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!=========================================================================== +$! +$ base_file = f$trnlnm("GNV_PCSI_FILENAME_BASE") +$ if base_file .eqs. "" +$ then +$ write sys$output "@MAKE_PCSI_CURL_KIT_NAME.COM has not been run." +$ goto all_exit +$ endif +$! +$! +$ curl_readme = f$search("sys$disk:[--]readme.") +$ if curl_readme .eqs. "" +$ then +$ curl_readme = f$search("sys$disk:[--]$README.") +$ endif +$ if curl_readme .eqs. "" +$ then +$ write sys$output "Can not find Curl readme file." +$ goto all_exit +$ endif +$! +$ curl_copying = f$search("sys$disk:[--]copying.") +$ if curl_copying .eqs. "" +$ then +$ curl_copying = f$search("sys$disk:[--]$COPYING.") +$ endif +$ if curl_copying .eqs. "" +$ then +$ write sys$output "Can not find Curl copying file." +$ goto all_exit +$ endif +$! +$ vms_readme = f$search("sys$disk:[]readme.") +$ if vms_readme .eqs. "" +$ then +$ vms_readme = f$search("sys$disk:[]$README.") +$ endif +$ if vms_readme .eqs. "" +$ then +$ write sys$output "Can not find VMS specific Curl readme file." +$ goto all_exit +$ endif +$! +$ curl_release_notes = f$search("sys$disk:[--]release-notes.") +$ if curl_release_notes .eqs. "" +$ then +$ curl_release_notes = f$search("sys$disk:[--]$RELEASE-NOTES.") +$ endif +$ if curl_release_notes .eqs. "" +$ then +$ write sys$output "Can not find Curl release-notes file." +$ goto all_exit +$ endif +$! +$ if f$search("sys$disk:[]hp_ssl_release_info.txt") .eqs. "" +$ then +$ write sys$output "GNV_LINK_CURL.COM has not been run!" +$ goto all_exit +$ endif +$! +$ type/noheader 'curl_readme', 'vms_readme', - + 'curl_release_notes', - + sys$disk:[]curl_release_note_start.txt, - + sys$disk:[]hp_ssl_release_info.txt, - + 'curl_copying', - + sys$disk:[]curl_gnv_build_steps.txt - + /out='base_file'.release_notes +$! +$ purge 'base_file'.release_notes +$ rename 'base_file.release_notes ;1 +$! +$all_exit: +$ exit diff --git a/third_party/curl/packages/vms/build_libcurl_pc.com b/third_party/curl/packages/vms/build_libcurl_pc.com new file mode 100644 index 0000000..294ae08 --- /dev/null +++ b/third_party/curl/packages/vms/build_libcurl_pc.com @@ -0,0 +1,202 @@ +$! File: build_libcurl_pc.com +$! +$! Build the libcurl.pc file from the libcurl.pc.in file +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!=========================================================================== +$! +$! Skip this if the libcurl.pc already exists. +$ if f$search("[--]libcurl.pc") .nes. "" then goto all_exit +$! +$! Need to know the kit type. +$ kit_name = f$trnlnm("GNV_PCSI_KITNAME") +$ if kit_name .eqs. "" +$ then +$ write sys$output "@MAKE_PCSI_CURL_KIT_NAME.COM has not been run." +$ goto all_exit +$ endif +$! +$! +$! Parse the kit name into components. +$!--------------------------------------- +$ producer = f$element(0, "-", kit_name) +$ base = f$element(1, "-", kit_name) +$ product = f$element(2, "-", kit_name) +$ mmversion = f$element(3, "-", kit_name) +$ majorver = f$extract(0, 3, mmversion) +$ minorver = f$extract(3, 2, mmversion) +$ updatepatch = f$element(4, "-", kit_name) +$ if updatepatch .eqs. "-" then updatepatch = "" +$! +$! kit type of "D" means a daily build +$ kit_type = f$edit(f$extract(0, 1, majorver), "upcase") +$! +$ pc_file_in = "[--]libcurl^.pc.in" +$! +$ if f$search(pc_file_in) .eqs. "" +$ then +$ pc_file_in = "[--]libcurl.pc$5nin" +$ if f$search(pc_file_in) .eqs. "" +$ then +$ pc_file_in = "[--]libcurl.pc_in" +$ if f$search(pc_file_in) .eqs. "" +$ then +$ write sys$output "Can not find libcurl.pc.in." +$ goto all_exit +$ endif +$ endif +$ endif +$! +$ if (f$getsyi("HW_MODEL") .lt. 1024) +$ then +$ arch_name = "VAX" +$ else +$ arch_name = "" +$ arch_name = arch_name + f$edit(f$getsyi("ARCH_NAME"), "UPCASE") +$ if (arch_name .eqs. "") then arch_name = "UNK" +$ endif +$! +$! +$ curl_version = "0.0.0" +$ open/read vf [--.src]tool_version.h +$version_loop: +$ read vf/end=version_loop_end line_in +$ if line_in .eqs. "" then goto version_loop +$ key = f$element(0, " ", line_in) +$ if key .nes. "#define" then goto version_loop +$ name = f$element(1, " ", line_in) +$ if name .eqs. "VERSION" +$ then +$ curl_version = f$element(2, " ", line_in) - """" - """" +$ else +$ goto version_loop +$ endif +$version_loop_end: +$ close vf +$! +$! +$ create [--]libcurl.pc +$ open/append pco [--]libcurl.pc +$ open/read pci 'pc_file_in' +$pc_file_loop: +$ read pci/end=pc_file_loop_end line_in +$! +$! blank lines +$ if line_in .eqs. "" +$ then +$ write pco "" +$ goto pc_file_loop +$ endif +$! +$! comment lines +$ key = f$extract(0, 1, line_in) +$ if key .eqs. "#" +$ then +$ write pco line_in +$ goto pc_file_loop +$ endif +$! +$! Special handling for libs. +$ if f$locate("Libs:", line_in) .eq. 0 +$ then +$ write pco "#",line_in +$ goto pc_file_loop +$ endif +$! No substitution line +$ line_in_len = f$length(line_in) +$ if f$locate("@", line_in) .ge. line_in_len +$ then +$ write pco line_in +$ goto pc_file_loop +$ endif +$! +$ if f$locate("@prefix@", line_in) .lt line_in_len +$ then +$ if kit_type .nes. "D" +$ then +$ write pco "prefix=/usr" +$ else +$ write pco "prefix=/beta" +$ endif +$ goto pc_file_loop +$ endif +$ if f$locate("@exec_prefix@", line_in) .lt line_in_len +$ then +$ if kit_type .nes. "D" +$ then +$ write pco "exec_prefix=/usr" +$ else +$ write pco "exec_prefix=/beta" +$ endif +$ goto pc_file_loop +$ endif +$ if f$locate("@libdir@", line_in) .lt line_in_len +$ then +$ write pco "libdir=$(exec_prefix}/lib" +$ goto pc_file_loop +$ endif +$ if f$locate("@includedir@", line_in) .lt line_in_len +$ then +$ write pco "includedir=$(prefix}/include" +$ goto pc_file_loop +$ endif +$ if f$locate("@SUPPORT_PROTOCOLS@", line_in) .lt line_in_len +$ then +$ proto1 = "DICT FILE FTP FTPS GOPHER HTTP HTTPS IMAP IMAPS" +$ proto2 = " LDAP LDAPS POP3 POP3S RTSP SMTP SMTPS TELNET TFTP" +$ proto = proto1 + proto2 +$ write pco "supported_protocols=""" + proto + """" +$ goto pc_file_loop +$ endif +$ if f$locate("@SUPPORT_FEATURES@", line_in) .lt line_in_len +$ then +$ if arch_name .eqs. "VAX" +$ then +$ write pco "supported_features=""SSL libz NTLM""" +$ else +$ write pco "supported_features=""SSL IPv6 libz NTLM""" +$ endif +$ goto pc_file_loop +$ endif +$ if f$locate("@CURLVERSION@", line_in) .lt line_in_len +$ then +$ write pco "Version: ''curl_version'" +$ goto pc_file_loop +$ endif +$ if f$locate("@LIBCURL_LIBS@", line_in) .lt line_in_len +$ then +$ if arch_name .eqs. "VAX" +$ then +$ write pco "Libs.private: -lssl -lcrypto -lz" +$ else +$ write pco "Libs.private: -lssl -lcrypto -lgssapi -lz" +$ endif +$ goto pc_file_loop +$ endif +$ if f$locate("@CPPFLAG_CURL_STATICLIB@", line_in) .lt line_in_len +$ then +$ write pco "Cflags: -I${includedir} -DCURL_STATICLIB" +$ goto pc_file_loop +$ endif +$! +$pc_file_loop_end: +$ close pco +$ close pci +$! +$all_exit: +$ exit diff --git a/third_party/curl/packages/vms/build_vms.com b/third_party/curl/packages/vms/build_vms.com new file mode 100644 index 0000000..1b02364 --- /dev/null +++ b/third_party/curl/packages/vms/build_vms.com @@ -0,0 +1,1038 @@ +$! BUILD_VMS.COM +$! +$! I've taken the original build_vms.com, supplied by Nico Baggus, if +$! memory serves me correctly, and made some modifications. +$! +$! SSL support is controlled by logical names. If SSL$INCLUDE is +$! defined, then it is assumed that HP's SSL product has been installed. +$! If OPENSSL is defined, but SSL$INCLUDE is not, then OpenSSL will be +$! used. If neither logical name is defined, then SSL support will not +$! be compiled/linked in. Command-line options NOHPSSL and NOSSL can be +$! specified to override the automatic SSL selection. +$! +$! Command-line Options: +$! +$! CLEAN Delete product files for this host architecture. (No +$! build done.) +$! CLEAN_ALL Delete product files for all host architectures. (No +$! build done.) +$! +$! 64 Compile with 64-bit pointers. +$! Note, you must match the pointer size that the OpenSSL +$! shared image expects. +$! Currently curl is not building properly with 64 bit pointers +$! on VMS because it is trying to cast pointers to 32 bit +$! integers and some OpenVMS library routines called by curl +$! do not yet support 64 bit pointers. +$! CCQUAL=x Add "x" to the C compiler qualifiers. +$! Default qualifiers are: +$! /standard=relaxed +$! /names=(as_is, shortened) +$! /repository=[.'arch'] +$! /nested_include_directory=none +$! /define=(_LARGEFILE=1,_USE_STD_STAT=1) (non-vax) +$! /float=ieee/ieee_mode=denorm_results (non-vax) +$! DEBUG Compile debug and nooptimize +$! Alpha/IA64 always compiles /debug. +$! Always link a debug image. +$! NOIEEE Do not use IEEE floating point. (Alpha/I64) +$! VAX must always use DFLOAT +$! NOLARGE Disable large-file support if large file support available. +$! (Non-VAX, VMS >= V7.2.) +$! NOLDAP Disable LDAP support if LDAP is available. +$! NOKERBEROS Disable Kerberos support if Kerberos is available. +$! LIST Create C compiler listings and linker maps. +$! /list/show=(expan,includ)/machine +$! FULLLIST Full detailed listing. +$! /list/show=(all, nomessages)/machine +$! NOHPSSL Don't use HP SSL, even if available. +$! Note, you must match the pointer size that the OpenSSL +$! shared image expects. This procedure will select the +$! correct HP OpenSSL image. +$! NOSSL Don't use any SSL, even if available. +$! OSSLOLB Use OpenSSL object libraries (.OLB), even if shared +$! images (.EXE) are available. +$! NOZLIB Don't use GNV$ZLIB shared image even if available. +$! REALCLEAN Delete product files for all host architectures. (No +$! build done.) Alias for CLEAN_ALL +$! +$! DCL Symbols: +$! +$! CURL_CCDEFS="c_macro_1=value1 [, c_macro_2=value2 [...]]" +$! Compile with these additional C macros defined. +$! +$! Revisions: +$! +$! 2-DEC-2003, MSK, the "original" version. +$! It works for me. Your mileage may vary. +$! 13-JAN-2004, MSK, moved this procedure to the [.packages.vms] directory +$! and updated it to do hardware dependent builds. +$! 29-JAN-2004, MSK, moved logical defines into defines.com +$! 6-FEB-2004, MSK, put in various SSL support bits +$! 9-MAR-2004, MSK, the config-vms.h* files are now copied to the lib and +$! src directories as curl_config.h. +$! 15-MAR-2004, MSK, All of the curlmsg*.* files have also been moved to +$! this build directory. They will be copied to the src +$! directory before build. The .msg file will be compiled +$! to get the .obj for messages, but the .h and .sdl files +$! are not automatically created since they partly rely on +$! the freeware SDL tool. +$! 8-FEB-2005, MSK, merged the two config-vms.h* files into one that uses +$! USE_SSLEAY to define if the target has SSL support built +$! in. Changed the cc/define parameter accordingly. +$! 11-FEB-2005, MSK, If [--.LIB]AMIGAOS.C and NWLIB.C are there, rename them +$! 23-MAR-2005, MSK, relocated cc_qual define so that DEBUG option would work +$! 25-APR-2007, STL, allow compilation in 64-bit mode. +$! 13-DEC-2009. SMS, Changed to skip unwanted source files without +$! renaming the original files. +$! Eliminated needless, persistent logical names. +$! Added CURL_CCDEFS DCL symbol for user-specified C +$! macro definitions. +$! Added CLEAN and CLEAN_ALL options. +$! Added CCQUAL option for user-specified C compiler +$! qualifiers. +$! Added IEEE option for IEEE floating point (Alpha). +$! Added LARGE option for large-file support. +$! Added OSSLOLB option, and support for OpenSSL +$! shared images. +$! Changed to put listing and map files into lisdir:. +$! Changed to avoid case confusion on ODS5 disks. +$! Added more default dev:[dir] save+restore. +$! Moved remaining "defines.com" code (back) into +$! here, eliminating the hard-coded OpenSSL nonsense. +$! Changed to use F$GETSYI("ARCH_NAME") (or +$! equivalent) to name architecture-specific product +$! file destination directory, and to create the +$! directory if needed (obviating inclusion of these +$! directories and dummy files in the distribution +$! kit). +$! Changed the "compile" subroutine to break the CC +$! command across multiple lines to avoid DCL +$! line-too-long problems. +$! Changed "vo_c" messages to show the CC qualifiers +$! once, not with every compile command. +$! 01-Jan-2013 J. Malmberg +$! VMS build procedures need to be able to work with +$! the default set to a search list, with created or +$! modified files only in the first member of the search +$! list. +$! Whitespace change to be more compatible with current +$! practices. +$! One pass option parsing instead of loop. +$! GNV ZLIB shared image support. +$! KERBEROS support where available. +$! LDAP default to on where available +$! LARGEFILE default to on where available +$! IEEE float default to on where available. +$! Generate the curl_config.h file from system inspection. +$! Linker finds ldap with out option file. +$! 13-Mar-2013, Tom Grace +$! Added missing slash in cc_full_list. +$! Removed unwanted extra quotes inside symbol tool_main +$! for non-VAX architectures that triggered link failure. +$! Replaced curl_sys_inc with sys_inc. +$! 19-Mar-2013, John Malmberg +$! symbol tool_main needs to be quoted when parse style is +$! set to extended in versions of VMS greater than 7.3-1. +$! Remove curlbuild.h generation as it should be pre-built +$! in the curl release or daily tarball. +$! 12-Jul-2013, John Malmberg +$! Adjust to find and use ZLIB from the Jean-Francois +$! Pieronne shared image and newer GNV ZLIB kit that +$! is upward compatible with Jean-Francois's kit. +$! Remove tabs from file. +$! Fixed DCL formatting as follows: +$! * Labels have no space after leading $. +$! * 1 space after $ for first level. +$! * 3 spaces after $ for second level. Line start + 4. +$! * 7 spaces after $ for third level. Line start + 8. +$! * Each level after that indents 4 characters. +$! * then/else/endif same indentation as if statement. +$! 17-Nov-2014, Michael Steve +$! Modified build to handle new location of the VTLS lib +$! source within zip archive. Not a pretty fix. +$! +$!=========================================================================== +$! +$! +$! Save the original default dev:[dir], and arrange for its restoration +$! at exit. +$!------------------------------------------------------------------------ +$ curl = "" +$ orig_def = f$environment("DEFAULT") +$ on error then goto Common_Exit +$ on control_y then goto Common_Exit +$! +$ ctrl_y = 1556 +$ proc = f$environment("PROCEDURE") +$ proc_fid = f$file_attributes(proc, "FID") +$ proc_dev = f$parse(proc, , , "DEVICE") +$ proc_dir = f$parse(proc, , , "DIRECTORY") +$ proc_name = f$parse(proc, , , "NAME") +$ proc_type = f$parse(proc, , , "TYPE") +$ proc_dev_dir = proc_dev + proc_dir +$! +$! Have to manually parse the device for a search list. +$! Can not use the f$parse() as it will return the first name +$! in the search list. +$! +$ orig_def_dev = f$element(0, ":", orig_def) + ":" +$ if orig_def_dev .eqs. "::" then orig_def_dev = "sys$disk:" +$ test_proc = orig_def_dev + proc_dir + proc_name + proc_type +$! +$! If we can find this file using the default directory +$! then we know that we should use the original device from the +$! default directory which could be a search list. +$! +$ test_proc_fid = f$file_attributes(test_proc, "FID") +$! +$ if (test_proc_fid .eq. proc_fid) +$ then +$ proc_dev_dir = orig_def_dev + proc_dir +$ endif +$! +$! +$! Verbose output message stuff. Define symbol to "write sys$output" or "!". +$! vo_c - verbose output for compile +$! vo_l - link +$! vo_o - object check +$! +$ vo_c := "write sys$output" +$ vo_l := "write sys$output" +$ vo_o := "!" +$! +$! Determine the main distribution directory ("[--]") in an +$! ODS5-tolerant (case-insensitive) way. (We do assume that the only +$! "]" or ">" is the one at the end.) +$! +$! Some non-US VMS installations report ">" for the directory delimiter +$! so do not assume that it is "]". +$! +$ orig_def_len = f$length(orig_def) +$ delim = f$extract(orig_def_len - 1, 1, orig_def) +$! +$ set default 'proc_dev_dir' +$ set default [--] +$ base_dev_dir = f$environment("default") +$ top_dev_dir = base_dev_dir - delim +$! +$! +$! +$! Define the architecture-specific product file destination directory +$! name(s). +$! +$ parse_style = "TRADITIONAL" +$ if (f$getsyi("HW_MODEL") .lt. 1024) +$ then +$ arch_name = "VAX" +$ else +$ arch_name = "" +$ arch_name = arch_name + f$edit(f$getsyi("ARCH_NAME"), "UPCASE") +$ if (arch_name .eqs. "") then arch_name = "UNK" +$! +$! Extended parsing option starts with VMS 7.3-1. +$! There is no 7.4, so that simplifies the parse a bit. +$! +$ node_swvers = f$getsyi("node_swvers") +$ version_patch = f$extract(1, f$length(node_swvers), node_swvers) +$ maj_ver = f$element(0, ".", version_patch) +$ min_ver_patch = f$element(1, ".", version_patch) +$ min_ver = f$element(0, "-", min_ver_patch) +$ patch = f$element(1, "-", min_ver_patch) +$ if patch .eqs. "-" then patch = "" +$ parse_x = 0 +$ if maj_ver .ges. "8" +$ then +$ parse_x = 1 +$ else +$ if maj_ver .eqs. "7" .and. min_ver .ges. "3" .and. patch .nes. "" +$ then +$ parse_x = 1 +$ endif +$ endif +$ if parse_x +$ then +$ parse_style = f$getjpi("", "parse_style_perm") +$ endif +$ endif +$! +$ exedir = proc_dev_dir - delim + ".''arch_name'" + delim +$ lisdir = exedir +$ objdir = exedir +$! +$! When building on a search list, need to do a create to make sure that +$! the output directory exists, since the clean procedure tries to delete +$! it. +$ create/dir 'exedir'/prot=o:rwed +$! +$! Interpret command-line options. +$! +$ hpssl = 0 +$ ldap = 1 +$ list = 0 +$ full_list = 0 +$ nohpssl = 0 +$ nossl = 0 +$ openssl = 0 +$ osslolb = 0 +$ nozlib = 0 +$ nokerberos = 0 +$ cc_names = "/names=(shortened, as_is)/repository='exedir' +$ cc_defs = "HAVE_CONFIG_H=1" +$ cc_list = "/list='objdir'/show=(expan, includ)/machine +$ cc_full_list = "/list='objdir'/show=(all, nomessages)/machine +$ link_qual = "" +$ if arch_name .eqs. "VAX" +$ then +$ cc_debug = "/nodebug/optimize" +$ !cc_defs = cc_defs + "" +$ cc_float = "" +$ cc_large = "" +$ else +$ cc_debug = "/debug/optimize" +$ cc_defs = cc_defs + ",_USE_STD_STAT" +$ cc_float = "/float=ieee/ieee_mode=denorm_results" +$ cc_large = ",_LARGEFILE" +$ endif +$ cc_qual1 = "" +$ cc_qual2 = "" +$ if (f$type(CURL_CCDEFS) .nes. "") +$ then +$ CURL_CCDEFS = f$edit(CURL_CCDEFS, "TRIM") +$ cc_defs = cc_defs + ", " + CURL_CCDEFS +$ endif +$ msg_qual = "/object = ''objdir'" +$ ssl_opt = "" +$! +$! Allow arguments to be grouped together with comma or separated by spaces +$! Do no know if we will need more than 8. +$ args = "," + p1 + "," + p2 + "," + p3 + "," + p4 + "," +$ args = args + p5 + "," + p6 + "," + p7 + "," + p8 + "," +$! +$! Provide lower case version to simplify parsing. +$ args_lower = f$edit(args, "LOWERCASE,COLLAPSE") +$! +$ args_len = f$length(args) +$ args_lower_len = f$length(args_lower) +$! +$ clean = 0 +$ if f$locate(",clean,", args_lower) .lt. args_lower_len +$ then +$ clean = 1 +$ endif +$ clean_all = 0 +$ if f$locate(",clean_all,", args_lower) .lt. args_lower_len +$ then +$ clean = 1 +$ clean_all = 1 +$ endif +$ if f$locate(",realclean,", args_lower) .lt. args_lower_len +$ then +$ clean = 1 +$ clean_all = 1 +$ endif +$! +$ if clean .ne. 0 +$ then +$ prods = "''exedir'*.*;*" +$ if (f$search(prods) .nes. "") then delete /log 'prods' +$ prods = proc_dev_dir + arch_name + ".DIR;1" +$ if (f$search(prods) .nes. "") then set prot=o:rwed 'prods' +$ if (f$search(prods) .nes. "") then delete /log 'prods' +$ file = "[]config_vms.h" +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[]config.h" +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[]curl-config." +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[]libcurl.pc" +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[.lib.cxx_repository]cxx$demangler_db." +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[.src.cxx_repository]cxx$demangler_db." +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[.lib]config_vms.h" +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[...]curl_crtl_init" +$ if f$search("''file'.lis") .nes. "" then delete/log 'file'.lis;* +$ if f$search("''file'.obj") .nes. "" then delete/log 'file'.obj;* +$ file = "[...]gnv$curlmsg" +$ if f$search("''file'.lis") .nes. "" then delete/log 'file'.lis;* +$ if f$search("''file'.obj") .nes. "" then delete/log 'file'.obj;* +$ if f$search("''file'.exe") .nes. "" then delete/log 'file'.exe;* +$ file = "[...]curlmsg" +$ if f$search("''file'.lis") .nes. "" then delete/log 'file'.lis;* +$ if f$search("''file'.obj") .nes. "" then delete/log 'file'.obj;* +$ if f$search("''file'.exe") .nes. "" then delete/log 'file'.exe;* +$ file = "[...]report_openssl_version" +$ if f$search("''file'.lis") .nes. "" then delete/log 'file'.lis;* +$ if f$search("''file'.obj") .nes. "" then delete/log 'file'.obj;* +$ if f$search("''file'.exe") .nes. "" then delete/log 'file'.exe;* +$ file = "[...]hp_ssl_release_info.txt" +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[...]gnv_libcurl_xfer.mar_exact" +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[...]gnv_libcurl_xfer" +$ if f$search("''file'.lis") .nes. "" then delete/log 'file'.lis;* +$ if f$search("''file'.obj") .nes. "" then delete/log 'file'.obj;* +$ if f$search("''file'.opt") .nes. "" then delete/log 'file'.opt;* +$ file = "[...]curl-*_original_src.bck" +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[...]curl_d-*_original_src.bck" +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[...]curl-*_vms_src.bck" +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[...]curl_d-*_vms_src.bck" +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[...]curl-*.release_notes" +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[...]curl_d-*.release_notes" +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[...]*curl*.pcsi$desc" +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[...]*curl_d*.pcsi$desc" +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[...]*curl*.pcsi$text" +$ if f$search(file) .nes. "" then delete/log 'file';* +$ file = "[...]*curl_d*.pcsi$text" +$ if f$search(file) .nes. "" then delete/log 'file';* +$! +$ if clean_all .eq. 0 then goto Common_Exit +$ endif +$! +$! +$ if clean_all .ne. 0 +$ then +$ file = "[...]gnv$libcurl" +$ if f$search("''file'.exe") .nes. "" then delete/log 'file'.exe;* +$ if f$search("''file'.map") .nes. "" then delete/log 'file'.map;* +$ if f$search("''file'.dsf") .nes. "" then delete/log 'file'.dsf;* +$ file = "[.src]curl" +$ if f$search("''file'.exe") .nes. "" then delete/log 'file'.exe;* +$ if f$search("''file'.map") .nes. "" then delete/log 'file'.map;* +$ if f$search("''file'.dsf") .nes. "" then delete/log 'file'.dsf;* +$ prods = proc_dev_dir - delim + ".ALPHA" + delim + "*.*;*" +$ if (f$search(prods) .nes. "") then delete /log 'prods' +$ prods = proc_dev_dir + "ALPHA" + ".DIR;1" +$ if (f$search(prods) .nes. "") then set prot=o:rwed 'prods' +$ if (f$search(prods) .nes. "") then delete /log 'prods' +$ prods = proc_dev_dir - delim + ".IA64" + delim + "*.*;*" +$ if (f$search(prods) .nes. "") then delete /log 'prods' +$ prods = proc_dev_dir + "IA64" + ".DIR;1" +$ if (f$search(prods) .nes. "") then set prot=o:rwed 'prods' +$ if (f$search(prods) .nes. "") then delete /log 'prods' +$ prods = proc_dev_dir - delim + ".VAX" + delim + "*.*;*" +$ if (f$search(prods) .nes. "") then delete /log 'prods' +$ prods = proc_dev_dir + "VAX"+ ".DIR;1" +$ if (f$search(prods) .nes. "") then set prot=o:rwed 'prods' +$ if (f$search(prods) .nes. "") then delete /log 'prods' +$ file = "[...]macro32_exactcase" +$ if f$search("''file'.exe") .nes. "" then delete/log 'file'.exe;* +$ if f$search("''file'.jnl") .nes. "" then delete/log 'file'.jnl;* +$ goto Common_Exit +$ endif +$! +$ build_64 = 0 +$ if f$locate(",64,", args_lower) .lt. args_lower_len +$ then +$ cc_qual1 = cc_qual1 + " /POINTER = 64" +$ build_64 = 1 +$ endif +$! +$ args_loc = f$locate(",ccqual=", args_lower) +$ if args_loc .lt. args_lower_len +$ then +$ arg = f$extract(args_loc + 1, args_lower_len, args_lower) +$ arg_val = f$element(0, ",", arg) +$ cc_qual2 = f$element(1, "=", arg_val); +$ endif +$! +$! On Alpha/IA64 no size penalty for compiling /debug/optimize +$! by default. +$ if f$locate(",debug,", args_lower) .lt. args_lower_len +$ then +$ cc_debug = "/debug/nooptimize" +$ endif +$! +$! We normally want IEEE float if it is available. Programs that are +$! calling libcurl will typically prefer IEEE behavior, unless on the +$! VAX where we have no choice. +$! +$ if f$locate(",noieee,", args_lower) .lt. args_lower_len +$ then +$ cc_float = "" +$ endif +$! +$! Normally we want large file if it is available. +$ if f$locate(",nolarge,", args_lower) .lt. args_lower_len +$ then +$ write sys$output "Handling of large files disabled." +$ cc_large = "" +$ endif +$ if cc_large .nes. "" +$ then +$ cc_defs = cc_defs + cc_large +$ endif +$! +$ if f$locate(",noldap,", args_lower) .lt. args_lower_len +$ then +$ ldap = 0 +$ endif +$! +$ if f$locate(",list,", args_lower) .lt. args_lower_len +$ then +$ list = 1 +$ endif +$ if f$locate(",fulllist,", args_lower) .lt. args_lower_len +$ then +$ list = 1 +$ full_list = 1 +$ endif +$! +$ if f$locate(",nohpssl,", args_lower) .lt. args_lower_len +$ then +$ nohpssl = 1 +$ endif +$! +$ if f$locate(",nossl,", args_lower) .lt. args_lower_len +$ then +$ nossl = 1 +$ endif +$! +$ if f$locate(",osslolb,", args_lower) .lt. args_lower_len +$ then +$ osslolb = 1 +$ endif +$! +$ if f$locate(",nozlib,", args_lower) .lt. args_lower_len +$ then +$ nozlib = 1 +$ endif +$! +$ if f$locate(",nokerberos,", args_lower) .lt. args_lower_len +$ then +$ nokerberos = 1 +$ endif +$! +$! +$! CC /LIST, LINK /MAP, and MESSAGE /LIST are defaults in batch mode, +$! so be explicit when they're not desired. +$! +$ +$ if list .eq. 0 +$ then +$ cc_qual1 = cc_qual1 + "/nolist" +$ msg_qual = msg_qual + "/nolist" +$ else +$ msg_qual = msg_qual + "/list='objdir'" +$ if (full_list .ne. 0) +$ then +$ cc_qual1 = cc_qual1 + cc_full_list +$ else +$ cc_qual1 = cc_qual1 + cc_list +$ endif +$ endif +$ cc_qual1 = cc_qual1 + cc_names + cc_float + cc_debug +$! +$! Create product directory, if needed. +$! +$ if (f$search(proc_dev_dir + arch_name + ".DIR;1") .eqs. "") +$ then +$ create /directory 'exedir' +$ endif +$! +$! Detect available (but not prohibited) SSL software. +$! +$ libsslshr_line = "" +$ libcryptoshr_line = "" +$ if (.not. nossl) +$ then +$ if (f$trnlnm("OPENSSL") .nes. "") +$ then +$! cc_defs = cc_defs + ", USE_OPENSSL=1" +$ if ((f$trnlnm("SSL$INCLUDE") .nes. "") .and. (.not. nohpssl)) +$ then +$! Use HP SSL. +$ hpssl = 1 +$! +$! Older SSL only has lib*_shr32 images +$!----------------------------------------------- +$ libsslshr = "sys$share:ssl$libssl_shr" +$ if (f$search("''libsslshr'.exe") .eqs. "") .or. (.not. build_64) +$ then +$ libsslshr = libsslshr + "32" +$ endif +$ libcryptoshr = "sys$share:ssl$libcrypto_shr" +$ if (f$search("''libcryptoshr'.exe") .eqs. "") .or. (.not. build_64) +$ then +$ libcryptoshr = libcryptoshr + "32" +$ endif +$ libsslshr_line = "''libsslshr'.exe/share" +$ libcryptoshr_line = "''libcryptoshr'.exe/share" +$ else +$! Use OpenSSL. Assume object libraries, unless shared images +$! are found (and not prohibited). +$! TODO: We do not know how to automatically choose based on the +$! pointer size. +$! +$ openssl = 1 +$ libsslshr_line = "ssllib:libssl.olb/lib" +$ libcryptoshr_line = "ssllib:libcrypto.olb/lib" +$ ssl_opt = ", ssllib:libssl.olb /library" + - + ", ssllib:libcrypto.olb /library" +$ if (osslolb .eq. 0) +$ then + if ((f$search("ssllib:ssl_libcrypto.exe") .nes. "") .and. - + (f$search("ssllib:ssl_libssl.exe") .nes. "")) +$ then +$! OpenSSL shared images with "SSL_xxx.EXE names. +$ openssl = 2 +$ libsslshr_line = "ssllib:ssl_libssl_shr.exe/share" +$ libcryptoshr_line = "ssllib:ssl_libcrypto_shr.exe/share" +$ else +$ if ((f$search("ssllib:libcrypto.exe") .nes. "") .and. - + (f$search("ssllib:libssl.exe") .nes. "")) +$ then +$! OpenSSL shared images with "xxx.EXE names. +$ openssl = 3 +$ libsslshr_line = "ssllib:libssl_shr.exe/share" +$ libcryptoshr_line = "ssllib:libcrypto_shr.exe/share" +$ endif +$ endif +$ endif +$ endif +$ endif +$ endif +$! +$! LDAP. +$! +$ if f$search("SYS$SHARE:LDAP$SHR.EXE") .eqs. "" +$ then +$ ldap = 0 +$ endif +$ if (ldap .eq. 0) +$ then +$! cc_defs = cc_defs + ", CURL_DISABLE_LDAP=1" +$ else +$ 'vo_c' "%CURL-I-BLDHPLDAP, building with HP LDAP support" +$ endif +$! +$! KERBEROS +$ gssrtlshr_line = "" +$ try_shr = "sys$share:gss$rtl" +$ if f$search("''try_shr'.exe") .eqs. "" +$ then +$ nokerberos = 1 +$ endif +$ curl_sys_krbinc = "" +$ if nokerberos .eq. 0 +$ then +$ 'vo_c' "%CURL-I-BLDHPKERBEROS, building with HP KERBEROS support" +$ curl_sys_krbinc = "sys$sysroot:[kerberos.include]" +$ gssrtlshr_line = "''try_shr'/share" +$ endif +$! +$! +$! LIBZ +$ libzshr_line = "" +$ try_shr = "gnv$libzshr" +$ if build_64 +$ then +$! First look for 64 bit +$ if f$search("''try_shr'64") .eqs. "" +$ then +$! Second look for the J.F. Pieronne 64 bit shared image +$ try_shr = "LIBZ_SHR64" +$ if f$search(try_shr) .eqs. "" then nozlib = 1 +$ endif +$ else +$! First look for 32 bit +$ if f$search("''try_shr'32") .eqs. "" +$ then +$! Second look for old 32 bit image +$ if f$search(try_shr) .eqs. "" +$ then +$! Third look for the J.F. Pieronne 32 bit shared image +$ try_shr = "LIBZ_SHR32" +$ if f$search(try_shr) .eqs. "" then nozlib = 1 +$ endif +$ endif +$ endif +$ if f$search(try_shr) .eqs. "" +$ then +$ nozlib = 1 +$ endif +$ curl_sys_zlibinc = "" +$ if nozlib .eq. 0 +$ then +$ libzshr_line = "''try_shr'/share" +$ if f$locate("LIBZ", try_shr) .eq. 0 +$ then +$ 'vo_c' "%CURL-I-BLDJFPLIBZ, building with JFP LIBZ support" +$ curl_sys_zlibinc = "LIBZ:" +$ else +$ 'vo_c' "%CURL-I-BLDGNVLIBZ, building with GNV LIBZ support" +$ curl_sys_zlibinc = "GNV$ZLIB_INCLUDE:" +$ endif +$ endif +$! +$! Form CC qualifiers. +$! +$ cc_defs = "/define = (''cc_defs')" +$ cc_qual2 = cc_qual2 + " /object = ''objdir'" +$ cc_qual2 = cc_qual2 + "/nested_include_directory=none" +$! +$ 'vo_c' "CC opts:", - + " ''cc_defs'", - + " ''cc_qual1'", - + " ''cc_qual2'" +$! +$! Inform the victim of our plans. +$! +$ if (hpssl) +$ then +$ 'vo_c' "%CURL-I-BLDHPSSL, building with HP SSL support" +$ else +$ if (openssl .ne. 0) +$ then +$ if (openssl .eq. 1) +$ then +$ 'vo_c' - + "%CURL-I-BLDOSSL_OLB, building with OpenSSL (object library) support" +$ else +$ 'vo_c' - + "%CURL-I-BLDOSSL_EXE, building with OpenSSL (shared image) support" +$ endif +$ else +$ 'vo_c' "%CURL-I-BLDNOSSL, building with NO SSL support" +$ endif +$ endif +$! +$! Announce destination and SSL directories. +$! +$ 'vo_c' " OBJDIR = ''objdir'" +$ 'vo_c' " EXEDIR = ''exedir'" +$! +$ if (openssl .ne. 0) +$ then +$ ssllib = f$trnlnm("ssllib") +$ if (ssllib .eqs. "") +$ then +$ ssllib = "(undefined)" +$ endif +$ 'vo_c' " SSLLIB = ''ssllib'" +$! +$! TODO: Why are we translating the logical name? +$! The logical aname used to find the shared image should just be used +$! as translating it could result in the wrong location at run time. +$ if (openssl .eq. 1) +$ then +$ ossl_lib1 = f$trnlnm("ssllib")+ "LIBSSL.OLB" +$ ossl_lib2 = f$trnlnm("ssllib")+ "LIBCRYPTO.OLB" +$ msg = "object libraries" +$ else +$ if (openssl .eq. 2) +$ then +$ ossl_lib1 = f$trnlnm("ssllib")+ "SSL_LIBSSL.EXE" +$ ossl_lib2 = f$trnlnm("ssllib")+ "SSL_LIBCRYPTO.EXE" +$ else +$ ossl_lib1 = f$trnlnm("ssllib")+ "LIBSSL.EXE" +$ ossl_lib2 = f$trnlnm("ssllib")+ "LIBCRYPTO.EXE" +$ endif +$ msg = "shared images" +$ endif +$ if ((f$search(ossl_lib1) .eqs. "") .or. - + (f$search(ossl_lib2) .eqs. "")) +$ then +$ write sys$output "Can't find OpenSSL ''msg':" +$ write sys$output " ''ossl_lib1'" +$ write sys$output " ''ossl_lib2'" +$ goto Common_Exit +$ endif +$ endif +$! +$! Define the "curl" (process) logical name for "#include ". +$! +$ curl = f$trnlnm("curl", "LNM$PROCESS") +$ if (curl .nes. "") +$ then +$ write sys$output "" +$ write sys$output - + "Process logical name ""curl"" is already defined, but this procedure" +$ write sys$output - + "would override that definition. Use a command like" +$ write sys$output - + " deassign /process curl" +$ write sys$output - + "to cancel that logical name definition, and then and re-run this procedure." +$ write sys$output "" +$ goto Common_Exit +$ endif +$ curl_logical = top_dev_dir + ".include.curl" + delim +$ curl_sys_inc2 = curl_logical +$ curl_sys_inc1 = top_dev_dir + ".include" + delim +$! define curl 'top_dev_dir'.include.curl'delim' +$! +$! Generate config file into the product directory. +$! +$! call MoveIfDiff [.lib]config-vms.h 'objdir'curl_config.h +$! +$ conf_params = "" +$ if nossl .ne. 0 then conf_params = conf_params + ",nossl" +$ if nohpssl .ne. 0 then conf_params = conf_params + ",nohpssl," +$ if ldap .eq. 0 then conf_params = conf_params + ",noldap," +$ if nozlib .ne. 0 then conf_params = conf_params + ",nozlib," +$ if nokerberos .ne. 0 then conf_params = conf_params + ",nokerberos" +$ conf_params = conf_params - "," +$! +$! +$ new_conf = f$search("''objdir'curl_config.h") +$ if new_conf .eqs. "" +$ then +$! set ver +$ write sys$output "Generating curl custom config_vms.h" +$ @'proc_dev_dir'generate_config_vms_h_curl.com ''conf_params' +$! +$ write sys$output "Generating curl_config.h" +$ conf_in = f$search("[.lib]curl_config*.*in") +$ if conf_in .eqs. "" +$ then +$ write sys$output "Can not find [.lib]curl_config*.*in file!" +$ goto common_exit +$ endif +$ @'proc_dev_dir'config_h.com 'conf_in' +$ copy config.h 'objdir'curl_config.h +$ delete config.h; +$! set nover +$ endif +$! +$! +$ on control_y then goto Common_Exit +$! +$ set default 'proc_dev_dir' +$ sys_inc = "''curl_sys_inc1', ''curl_sys_inc2', ''curl_logical'" +$ if curl_sys_krbinc .nes. "" +$ then +$ sys_inc = sys_inc + ",''curl_sys_krbinc'" +$ endif +$ if curl_sys_zlibinc .nes. "" +$ then +$ sys_inc = sys_inc + ",''curl_sys_zlibinc'" +$ endif +$! Build LIB +$ cc_include = "/include=([-.lib],[-.lib.vtls],[-.packages.vms]" +$ cc_include = cc_include + ",[-.packages.vms.''arch_name'])" +$ call build "[--.lib]" "*.c" "''objdir'CURLLIB.OLB" "amigaos, nwlib, nwos" +$ if ($status .eq. ctrl_y) then goto Common_Exit +$! Build VTLS +$ cc_include = "/include=([--.lib.vtls],[--.lib],[--.src]" +$ cc_include = cc_include + ",[--.packages.vms],[--.packages.vms.''arch_name'])" +$ call build "[--.lib.vtls]" "*.c" "''objdir'CURLLIB.OLB" "amigaos, nwlib, nwos" +$! Build SRC +$ cc_include = "/include=([-.src],[-.lib],[-.lib.vtls]" +$ cc_include = cc_include + ",[-.packages.vms],[-.packages.vms.''arch_name'])" +$ call build "[--.src]" "*.c" "''objdir'CURLSRC.OLB" +$ if ($status .eq. ctrl_y) then goto Common_Exit +$! Build MSG +$ call build "[]" "*.msg" "''objdir'CURLSRC.OLB" +$ if ($status .eq. ctrl_y) then goto Common_Exit +$! +$! +$ if (openssl .ne. 0) +$ then +$ if (openssl .eq. 1) +$ then +$ 'vo_l' "%CURL-I-LINK_OSSL, linking with OpenSSL (object library)" +$ else +$ 'vo_l' "%CURL-I-LINK_HPSSL, linking with OpenSSL (shared image)" +$ endif +$ else +$ if (hpssl) +$ then +$ 'vo_l' "%CURL-I-LINK_HPSSL, linking with HP SSL" +$ else +$ 'vo_l' "%CURL-I-LINK_NOSSL, linking with NO SSL support" +$ endif +$ endif +$! +$! +$! GNV helper files for building the test curl binary. +$!----------------------------------------------- +$ create 'exedir'gnv$curl.opt +$ open/append opt 'exedir'gnv$curl.opt +$ if libzshr_line .nes. "" then write opt libzshr_line +$ if gssrtlshr_line .nes. "" then write opt gssrtlshr_line +$ if libcryptoshr_line .nes. "" then write opt libcryptoshr_line +$ if libsslshr_line .nes. "" then write opt libsslshr_line +$ close opt +$! +$! +$! Create the libcurl +$!------------------------------------------------------ +$ create 'exedir'gnv_libcurl_linker.opt +$ open/append opt 'exedir'gnv_libcurl_linker.opt +$ if libzshr_line .nes. "" then write opt libzshr_line +$ if gssrtlshr_line .nes. "" then write opt gssrtlshr_line +$ if libcryptoshr_line .nes. "" then write opt libcryptoshr_line +$ if libsslshr_line .nes. "" then write opt libsslshr_line +$ close opt +$! +$! +$! If we are not on VAX, then we want the debug symbol table in +$! a separate file. +$! VAX needs the tool_main unquoted in uppercase, +$! Alpha and IA64 need tool_main quoted in exact case when parse style is +$! extended. +$ link_dsf1 = "" +$ link_dsf2 = "" +$ tool_main = "tool_main" +$ if arch_name .nes. "VAX" +$ then +$ if parse_style .eqs. "EXTENDED" +$ then +$ tool_main = """tool_main""" +$ endif +$ link_dsf1 = "/dsf=" + exedir + "CURL.DSF" +$ link_dsf2 = "/dsf=" + exedir + "CURL_DEBUG.DSF" +$ endif +$ if (list .eq. 0) +$ then +$ link_map1 = "/nomap" +$ link_map2 = "/nomap" +$ else +$ link_map1 = "/map=" + exedir + "CURL.MAP" +$ link_map2 = "/map=" + exedir + "CURL_DEBUG.MAP" +$ endif +$! +$! +$! Make a normal image. +$ set ver +$ link 'link_map1' 'link_dsf1' /executable = 'exedir'CURL.EXE - + 'objdir'curlsrc.olb /library /include = ('tool_main', curlmsg), - + 'objdir'curllib.olb /library, - + 'exedir'gnv$curl.opt/opt +$! +$! Also make a debug copy. +$ link/debug 'link_map2' 'link_dsf2' /executable = 'exedir'CURL_DEBUG.EXE - + 'objdir'curlsrc.olb /library /include = ('tool_main', curlmsg), - + 'objdir'curllib.olb /library, - + 'exedir'gnv$curl.opt/opt +$ set nover +$! +$ goto Common_Exit +$! +$! Subroutine to build everything with a filetype passed in via P2 in +$! the directory passed in via P1 and put it in the object library named +$! via P3. Exclude items in P4. +$! +$build: subroutine +$ build_def = f$environment("default") +$ on control_y then goto EndLoop ! SS$_CONTROLY +$ sts = 1 ! SS$_NORMAL. +$! set noon +$ set default 'p1' +$ search = "sys$disk:" + p2 +$ reset = f$search("reset") +$ if f$search( p3) .eqs. "" +$ then +$ librarian /create /object 'p3' +$ endif +$ reject_list__ = "," + f$edit(p4, "COLLAPSE, UPCASE") + "," +$ reject_list___len = f$length(reject_list__) +$ reset = f$search( "reset", 1) +$Loop: +$ file = f$search( search, 1) +$ if file .eqs. "" then goto EndLoop +$! Skip a name if it's in the P4 exclusion list. +$ if (p4 .nes. "") +$ then +$ name__ = "," + - + f$edit(f$parse(file, , , "NAME", "SYNTAX_ONLY"), "UPCASE") + - + "," +$ if (f$locate(name__, reject_list__) .lt. reject_list___len) +$ then +$ goto Loop +$ endif +$ endif +$ objfile = f$parse("''objdir'.OBJ;", file) +$ obj = f$search(objfile, 2) +$ if (obj .nes. "") +$ then +$ if (f$cvtime(f$file(file,"rdt")) .gts. f$cvtime(f$file(obj,"rdt"))) +$ then +$ call compile 'file' +$ sts = $status +$ if .not. sts +$ then +$ goto EndLoop +$ endif +$ librarian /object 'p3' 'objfile' +$ else +$ 'vo_o' "%CURL-I-OBJUTD, ", objfile, " is up to date" +$ endif +$ else +$ 'vo_o' "%CURL-I-OBJDNE, ", file, " does not exist" +$ call compile 'file' +$ sts = $status +$ if .not. sts +$ then +$ goto EndLoop +$ endif +$ librarian /object 'p3' 'objfile' +$ endif +$ goto Loop +$EndLoop: +$!!! purge +$ set default 'build_def' +$ exit 'sts' +$ endsubroutine ! Build +$! +$! Based on the file TYPE, do the right compile command. +$! Only C and MSG supported. +$! +$compile: subroutine +$ on control_y then return ctrl_y ! SS$_CONTROLY +$! set noon +$ file = p1 +$ qual = p2+ p3+ p4+ p5+ p6+ p7+ p8 +$ typ = f$edit(f$parse(file, , , "TYPE"), "UPCASE") - "." +$ if (typ .eqs. "C") +$ then +$ 'vo_c' "CC (opts) ", file +$ define/user curl 'curl_logical' +$ if curl_sys_krbinc .nes. "" then define/user gssapi 'curl_sys_krbinc' +$ define/user decc$system_include 'sys_inc' +$ CC 'cc_defs' - + 'cc_qual1' - + 'cc_qual2' - + 'cc_include' - + 'file' +$ else +$ cmd_msg = "MESSAGE " + msg_qual +$ x = cmd_'typ' +$ 'vo_c' x, " ", file +$ 'x' 'file' +$ endif +$ ENDSUBROUTINE ! Compile +$! +$! Do a diff of the file specified in P1 with that in P2. If different +$! copy P1 to P2. This also covers if P2 doesn't exist, but not if P2 +$! is an invalid filespec. +$! +$MoveIfDiff: subroutine +$ set NoOn +$ define /user_mode sys$error nl: +$ define /user_mode sys$output nl: +$ differences 'p1' 'p2' +$ status = $status +$ if (status .ne. %X006C8009) ! if status is not "no diff" +$ then +$ copy 'p1' 'p2' +$ purge /nolog 'p2' +$ endif +$ on control_y then return ctrl_y ! SS$_CONTROLY +$ ENDSUBROUTINE ! MoveIfDiff +$! +$Common_Exit: +$ set default 'orig_def' +$ exit diff --git a/third_party/curl/packages/vms/clean_gnv_curl.com b/third_party/curl/packages/vms/clean_gnv_curl.com new file mode 100644 index 0000000..1a9a0eb --- /dev/null +++ b/third_party/curl/packages/vms/clean_gnv_curl.com @@ -0,0 +1,239 @@ +$! File: clean_gnv_curl.COM +$! +$! The GNV environment leaves behind some during the configure and build +$! procedure that need to be cleaned up. +$! +$! The default is to remove all the left over stuff from running the +$! configure script and to remove all intermediate binary files. +$! +$! This should be run with no parameters after the gnv_curl_configure.sh +$! script is run. +$! +$! Parameter P1: REALCLEAN +$! This removes all build products and brings the environment back to +$! the point where the gnv_curl_configure.sh procedure needs to be run again. +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!============================================================================ +$! +$! Save this so we can get back. +$ default_dir = f$environment("default") +$! +$! +$! Move to where the base directory is. +$ set def [--] +$! +$! +$ file = "sys$login:sh*." +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "sys$login:make*." +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[]confdefs.h" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[]conftest.dsf" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[]conftest.lis" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[]conftest.sym" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$! +$ file = "lcl_root:[.conf*...]*.*" +$ if f$search(file) .nes. "" then delete 'file';* +$ file = "lcl_root:[]conf*.dir +$ if f$search(file) .nes. "" then delete 'file';* +$! +$! +$ file = "lcl_root:[.lib]*.out" +$ if f$search(file) .nes. "" then delete 'file';* +$ file = "lcl_root:[.lib]*.o" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$! +$ file = "lcl_root:[.lib]*.lis" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.src]*.lis" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.src]cc_temp*." +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.src]*.dsf" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.src]*.o" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.lib]ar*." +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.lib]cc_temp*." +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[...]*.lo" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[...]*.a" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[...]*.la" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[...]*.lai" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.packages.vms]curl-*_original_src.bck" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.packages.vms]curl_d-*_original_src.bck" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.packages.vms]curl-*_vms_src.bck" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.packages.vms]curl_d-*_vms_src.bck" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.packages.vms]curl-*.release_notes" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.packages.vms]curl_d-*.release_notes" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.packages.vms]*-curl-*.pcsi$desc" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.packages.vms]*-curl_d-*.pcsi$desc" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.packages.vms]*-curl-*.pcsi$text" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.packages.vms]*-curl_d-*.pcsi$text" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$!====================================================================== +$! +$ if p1 .nes. "REALCLEAN" then goto all_exit +$! +$ file = "lcl_root:[...]*.obj" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[...]Makefile." +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[...]libtool." +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[...]*.lis" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[...]POTFILES." +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[]libcurl.pc" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[]curl-config." +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[]config.h" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.src]config.h" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.src]curl." +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.tests]configurehelp.pm" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.lib]config.h" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.lib]curl_config.h" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.lib]libcurl.vers" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[]ca-bundle.h" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[]config.log" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[]config.status" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[]conftest.dangle" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[]CXX$DEMANGLER_DB." +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[]stamp-h1." +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[...]stamp-h1." +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[...]stamp-h2." +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[...]stamp-h3." +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.lib]*.a" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[...]*.spec" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[...]gnv$*.*" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[...]gnv*.opt" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.packages.vms]macro32_exactcase.exe" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.packages.vms]report_openssl_version.exe" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.packages.vms]hp_ssl_release_info.txt" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$ file = "lcl_root:[.src]curl.exe" +$ if f$search(file) .nes. "" then delete 'file';* +$! +$all_exit: +$! +$! Put the default back. +$!----------------------- +$ set def 'default_dir' +$! +$ exit diff --git a/third_party/curl/packages/vms/compare_curl_source.com b/third_party/curl/packages/vms/compare_curl_source.com new file mode 100644 index 0000000..3f7542d --- /dev/null +++ b/third_party/curl/packages/vms/compare_curl_source.com @@ -0,0 +1,363 @@ +$! Compare_curl_source.com +$! +$! This procedure compares the files in two directories and reports the +$! differences. It is customized for the vmsports repository layout. +$! +$! It needs to be customized to the local site directories. +$! +$! This is used by me for these purposes: +$! 1. Compare the original source of a project with an existing +$! VMS port. +$! 2. Compare the checked out repository of a project with the +$! the local working copy to make sure they are in sync. +$! 3. Keep a copy directory up to date. The third is needed by +$! me because VMS Backup can create a saveset of files from a +$! NFS mounted volume. +$! +$! First the files in the original source directory which is assumed to be +$! under source code control are compared with the copy directory. +$! +$! Then the files are are only in the copy directory are listed. +$! +$! The result will five diagnostics about of files: +$! 1. Files that are not generation 1. +$! 2. Files missing in the copy directory. +$! 3. Files in the copy directory not in the source directory. +$! 4. Files different from the source directory. +$! 5. Files that VMS DIFF can not process. +$! +$! This needs to be run on an ODS-5 volume. +$! +$! If UPDATE is given as a second parameter, files missing or different in the +$! copy directory will be updated. +$! +$! By default: +$! The directory src_root:[project_name] will be translated to something like +$! DISK:[dir.dir.reference.project_name] and this will be used +$! to calculate DISK:[dir.dir.vms_source.project_name] for the VMS specific +$! source directory. +$! +$! The copy directory is vms_root:[project_name] +$! The UPDATE parameter is ignored. +$! +$! This setting is used to make sure that the working vms directory +$! and the repository checkout directory have the same contents. +$! +$! If P1 is "SRCBCK" then this +$! The source directory tree is: src_root:[project_name] +$! The copy directory is src_root1:[project_name] +$! +$! src_root1:[project_name] is used by me to work around that VMS backup will +$! not use NFS as a source directory so I need to make a copy. +$! +$! This is to make sure that the backup save set for the unmodified +$! source is up to date. +$! +$! If your repository checkout is not on an NFS mounted volume, you do not +$! need to use this option or have the logical name src_root1 defined. +$! +$! If P1 is "VMSBCK" then this changes the two directories: +$! The source directory is vms_root:[project_name] +$! The copy directory is vms_root1:[project_name] +$! +$! vms_root:[project_name] is where I do the VMS specific edits. +$! vms_root1:[project_name] is used by me to work around that VMS backup will +$! not use NFS as a source directory so I need to make a copy. +$! +$! This is to make sure that the backup save set for the unmodified +$! source is up to date. +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!========================================================================== +$! +$! Update missing/changed files. +$ update_file = 0 +$ if (p2 .eqs. "UPDATE") +$ then +$ update_file = 1 +$ endif +$! +$ myproc = f$environment("PROCEDURE") +$ myprocdir = f$parse(myproc,,,"DIRECTORY") - "[" - "]" - "<" - ">" +$ myprocdir = f$edit(myprocdir, "LOWERCASE") +$ mydefault = f$environment("DEFAULT") +$ mydir = f$parse(mydefault,,,"DIRECTORY") +$ mydir = f$edit(mydir, "LOWERCASE") +$ odelim = f$extract(0, 1, mydir) +$ mydir = mydir - "[" - "]" - "<" - ">" +$ mydev = f$parse(mydefault,,,"DEVICE") +$! +$ ref = "" +$ if P1 .eqs. "" +$ then +$ ref_base_dir = myprocdir +$ wrk_base_dir = mydir +$ update_file = 0 +$ resultd = f$parse("src_root:",,,,"NO_CONCEAL") +$ resultd = f$edit(resultd, "LOWERCASE") +$ resultd = resultd - "][" - "><" - ".;" - ".." +$ resultd_len = f$length(resultd) - 1 +$ delim = f$extract(resultd_len, 1, resultd) +$ ref_root_base = mydir + delim +$ resultd = resultd - ref_root_base - "reference." + "vms_source." +$ ref = resultd + ref_base_dir +$ wrk = "VMS_ROOT:" + odelim + wrk_base_dir +$ resultd_len = f$length(resultd) - 1 +$ resultd = f$extract(0, resultd_len, resultd) + delim +$ ref_root_dir = f$parse(resultd,,,"DIRECTORY") +$ ref_root_dir = f$edit(ref_root_dir, "LOWERCASE") +$ ref_root_dir = ref_root_dir - "[" - "]" +$ ref_base_dir = ref_root_dir + "." + ref_base_dir +$ endif +$! +$ if p1 .eqs. "SRCBCK" +$ then +$ ref_base_dir = "curl" +$ wrk_base_dir = "curl" +$ ref = "src_root:[" + ref_base_dir +$ wrk = "src_root1:[" + wrk_base_dir +$ if update_file +$ then +$ if f$search("src_root1:[000000]curl.dir") .eqs. "" +$ then +$ create/dir/prot=o:rwed src_root1:[curl] +$ endif +$ endif +$ endif +$! +$! +$ if p1 .eqs. "VMSBCK" +$ then +$ ref_base_dir = "curl" +$ wrk_base_dir = "curl" +$ ref = "vms_root:[" + ref_base_dir +$ wrk = "vms_root1:[" + wrk_base_dir +$ if update_file +$ then +$ if f$search("vms_root1:[000000]curl.dir") .eqs. "" +$ then +$ create/dir/prot=o:rwed vms_root1:[curl] +$ endif +$ endif +$ endif +$! +$! +$ if ref .eqs. "" +$ then +$ write sys$output "Unknown compare type specified!" +$ exit 44 +$ endif +$! +$! +$! Future - check the device types involved for the +$! the syntax to check. +$ ODS2_SYNTAX = 0 +$ NFS_MANGLE = 0 +$ PWRK_MANGLE = 0 +$! +$ vax = f$getsyi("HW_MODEL") .lt. 1024 +$ if vax +$ then +$ ODS2_SYNTAX = 1 +$ endif +$! +$ report_missing = 1 +$! +$ if .not. ODS2_SYNTAX +$ then +$ set proc/parse=extended +$ endif +$! +$loop: +$ ref_spec = f$search("''ref'...]*.*;",1) +$ if ref_spec .eqs. "" then goto loop_end +$! +$ ref_dev = f$parse(ref_spec,,,"DEVICE") +$ ref_dir = f$parse(ref_spec,,,"DIRECTORY") +$ ref_dir = f$edit(ref_dir, "LOWERCASE") +$ ref_name = f$parse(ref_spec,,,"NAME") +$ ref_type = f$parse(ref_spec,,,"TYPE") +$! +$! +$ rel_path = ref_dir - "[" - ref_base_dir +$! rel_path_len = f$length(rel_path) - 1 +$! delim = f$extract(rel_path_len, 1, rel_path) +$! rel_path = rel_path - ".]" - ".>" - "]" - ">" +$! rel_path = rel_path + delim +$! +$ if ODS2_SYNTAX +$ then +$! if rel_path .eqs. ".examples.scripts^.noah]" +$! then +$! rel_path = ".examples.scripts_noah]" +$! endif +$! if rel_path .eqs. ".examples.scripts^.v2]" +$! then +$! rel_path = ".examples.scripts_v2]" +$! endif +$ endif +$! +$ wrk_path = wrk + rel_path +$! +$ ref_name_type = ref_name + ref_type +$! +$ if ODS2_SYNTAX +$ then +$ endif +$! +$ wrk_spec = wrk_path + ref_name_type +$! +$! +$ wrk_chk = f$search(wrk_spec, 0) +$ if wrk_chk .eqs. "" +$ then +$ if report_missing +$ then +$ write sys$output "''wrk_spec' is missing" +$ endif +$ if update_file +$ then +$ copy/log 'ref_spec' 'wrk_spec' +$ endif +$ goto loop +$ endif +$! +$ wrk_name = f$parse(wrk_spec,,,"NAME") +$ wrk_type = f$parse(wrk_spec,,,"TYPE") +$ wrk_fname = wrk_name + wrk_type" +$ ref_fname = ref_name + ref_type +$! +$ if ref_fname .nes. wrk_fname +$ then +$ write sys$output "''wrk_spc' wrong name, should be ""''ref_fname'""" +$ endif +$! +$ ref_type = f$edit(ref_type, "UPCASE") +$ if ref_type .eqs. ".DIR" then goto loop +$! +$ if ODS2_SYNTAX +$ then +$ ref_fname = f$edit(ref_fname, "LOWERCASE") +$ endif +$! +$! These files are in the wrong format for VMS diff, and we don't change them. +$ ref_skip = 0 +$ if ref_type .eqs. ".PDF" then ref_skip = 1 +$ if ref_type .eqs. ".HTML" then ref_skip = 1 +$ if ref_type .eqs. ".P12" then ref_skip = 1 +$ if ref_type .eqs. "." +$ then +$ if f$locate("test", ref_fname) .eq. 0 then ref_skip = 1 +$ if ref_fname .eqs. "configure." then ref_skip = 1 +$ endif +$! +$! +$ if ref_skip .ne. 0 +$ then +$ if report_missing +$ then +$ write sys$output "Skipping diff of ''ref_fname'" +$ endif +$ goto loop +$ endif +$! +$! +$ wrk_ver = f$parse(wrk_chk,,,"VERSION") +$ if wrk_ver .nes. ";1" +$ then +$ write sys$output "Version for ''wrk_spec' is not 1" +$ endif +$ set noon +$ diff/out=nl: 'wrk_spec' 'ref_spec' +$ if $severity .nes. "1" +$ then +$ write sys$output "''wrk_spec' is different from ''ref_spec'" +$ if update_file +$ then +$ delete 'wrk_spec';* +$ copy/log 'ref_spec' 'wrk_spec' +$ endif +$ endif +$ set on +$ +$! +$ goto loop +$loop_end: +$! +$! +$missing_loop: +$! For missing loop, check the latest generation. +$ ref_spec = f$search("''wrk'...]*.*;") +$ if ref_spec .eqs. "" then goto missing_loop_end +$! +$ ref_dev = f$parse(ref_spec,,,"DEVICE") +$ ref_dir = f$parse(ref_spec,,,"DIRECTORY") +$ ref_dir = f$edit(ref_dir, "LOWERCASE") +$ ref_name = f$parse(ref_spec,,,"NAME") +$ ref_type = f$parse(ref_spec,,,"TYPE") +$ ref_name_type = ref_name + ref_type +$! +$ rel_path = ref_dir - "[" - wrk_base_dir +$! +$! +$ wrk_path = ref + rel_path +$ wrk_spec = wrk_path + ref_name + ref_type +$ wrk_name = f$parse(wrk_spec,,,"NAME") +$ wrk_type = f$parse(wrk_spec,,,"TYPE") +$! +$ wrk_fname = wrk_name + wrk_type" +$ ref_fname = ref_name + ref_type +$! +$ wrk_skip = 0 +$ ref_utype = f$edit(ref_type,"UPCASE") +$ ref_ufname = f$edit(ref_fname,"UPCASE") +$! +$ if wrk_skip .eq. 0 +$ then +$ wrk_chk = f$search(wrk_spec, 0) +$ if wrk_chk .eqs. "" +$ then +$ if report_missing +$ then +$ write sys$output "''wrk_spec' is missing" +$ endif +$ goto missing_loop +$ endif +$ else +$ goto missing_loop +$ endif +$! +$ if ref_fname .nes. wrk_fname +$ then +$ write sys$output "''wrk_spc' wrong name, should be ""''ref_fname'""" +$ endif +$! +$ if ref_utype .eqs. ".DIR" then goto missing_loop +$! +$ wrk_ver = f$parse(wrk_chk,,,"VERSION") +$ if wrk_ver .nes. ";1" +$ then +$ write sys$output "Version for ''wrk_spec' is not 1" +$ endif +$! +$ goto missing_loop +$! +$! +$missing_loop_end: +$! +$exit diff --git a/third_party/curl/packages/vms/config_h.com b/third_party/curl/packages/vms/config_h.com new file mode 100644 index 0000000..44cb067 --- /dev/null +++ b/third_party/curl/packages/vms/config_h.com @@ -0,0 +1,1972 @@ +$! File: config_h.com +$! +$! This procedure attempts to figure out how to build a config.h file +$! for the current project. +$! +$! P1 specifies the config.h.in file or equivalent. If it is not specified +$! then this procedure will search for several common names of the file. +$! +$! The CONFIGURE shell script will be examined for hints and a few symbols +$! but most of the tests will not produce valid results on OpenVMS. Some +$! will produce false positives and some will produce false negatives. +$! +$! It is easier to just read the config.h_in file and make up tests based +$! on what is in it! +$! +$! This file will create an empty config_vms.h file if one does not exist. +$! The config_vms.h is intended for manual edits to handle things that +$! this procedure can not. +$! +$! The config_vms.h will be invoked by the resulting config.h file. +$! +$! This procedure knows about the DEC C RTL on the system it is on. +$! Future versions may be handle the GNV, the OpenVMS porting library, +$! and others. +$! +$! This procedure may not guess the options correctly for all architectures, +$! and is a work in progress. +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!============================================================================ +$! +$ss_normal = 1 +$ss_abort = 44 +$ss_control_y = 1556 +$status = ss_normal +$on control_y then goto control_y +$on warning then goto general_error +$!on warning then set ver +$! +$! Some information for writing timestamps to created files +$!---------------------------------------------------------- +$my_proc = f$environment("PROCEDURE") +$my_proc_file = f$parse(my_proc,,,"NAME") + f$parse(my_proc,,,"TYPE") +$tab[0,8] = 9 +$datetime = f$element(0,".",f$cvtime(,"ABSOLUTE","DATETIME")) +$username = f$edit(f$getjpi("","USERNAME"),"TRIM") +$! +$pid = f$getjpi("","PID") +$tfile1 = "SYS$SCRATCH:config_h_temp1_''pid'.TEMP" +$dchfile = "SYS$SCRATCH:config_h_decc_''pid'.TEMP" +$starhfile = "SYS$SCRATCH:config_h_starlet_''pid'.TEMP" +$configure_script = "SYS$SCRATCH:configure_script_''pid'.TEMP" +$! +$! Get the system type +$!---------------------- +$arch_type = f$getsyi("arch_type") +$! +$! Does config_vms.h exist? +$!------------------------- +$update_config_vms = 0 +$file = f$search("sys$disk:[]config_vms.h") +$if file .nes. "" +$then +$ write sys$output "Found existing custom file ''file'." +$else +$ update_config_vms = 1 +$ write sys$output "Creating new sys$disk:[]config_vms.h for you." +$ gosub write_config_vms +$endif +$! +$! +$! On some platforms, DCL search has problems with searching a file +$! on a NFS mounted volume. So copy it to sys$scratch: +$! +$if f$search(configure_script) .nes. "" then delete 'configure_script';* +$copy sys$disk:[]configure 'configure_script' +$! +$ssl_header_dir = "OPENSSL:" +$if f$trnlnm("OPENSSL") .eqs. "" +$then +$ ssl_header_dir = "SSL$INCLUDE:" +$endif +$! +$! +$! Write out the header +$!---------------------- +$gosub write_config_h_header +$! +$! +$! +$! config.h.in could have at least five different names depending +$! on how it was transferred to OpenVMS +$!------------------------------------------------------------------ +$if p1 .nes. "" +$then +$ cfile = p1 +$else +$ cfile = f$search("sys$disk:[]config.h.in") +$ if cfile .eqs. "" +$ then +$ cfile = f$search("sys$disk:[]config.h_in") +$ if cfile .eqs. "" +$ then +$ cfile = f$search("sys$disk:[]configh.in") +$ if cfile .eqs. "" +$ then +$ cfile = f$search("sys$disk:[]config__2eh.in") +$ if cfile .eqs. "" +$ then +$ cfile = f$search("sys$disk:[]config.h__2ein") +$ endif +$ endif +$ endif +$ endif +$endif +$if f$trnlnm("PRJ_INCLUDE") .nes. "" +$then +$ cfile = f$search("PRJ_INCLUDE:config.h.in") +$ if cfile .eqs. "" +$ then +$ cfile = f$search("PRJ_INCLUDE:config.h_in") +$ if cfile .eqs. "" +$ then +$ cfile = f$search("PRJ_INCLUDE:config__2eh.in") +$ if cfile .eqs. "" +$ then +$ cfile = f$search("PRJ_INCLUDE:config__2eh.in") +$ if cfile .eqs. "" +$ then +$ cfile = f$search("PRJ_INCLUDE:config.h__2ein") +$ endif +$ endif +$ endif +$ endif +$endif +$if cfile .eqs. "" +$then +$ write sys$output "Can not find sys$disk:config.h.in" +$ line_out = "Looked for config.h.in, config.h_in, configh.in, " +$ line_out = line_out + "config__2eh.in, config.h__2ein" +$ write/symbol sys$output line_out +$ if f$trnlnm("PRJ_INCLUDE") .nes. "" +$ then +$ write sys$output "Also looked in PRJ_INCLUDE: for these files." +$ endif +$! +$ write tf "" +$ write tf - + " /* Could not find sys$disk:config.h.in */" +$ write tf - + " /* Looked also for config.h_in, configh.in, config__2eh.in, */" +$ write tf - + " /* config.h__2ein */" +$ if f$trnlnm("PRJ_INCLUDE") .nes. "" +$ then +$ write tf - + " /* Also looked in PRJ_INCLUDE: for these files. */" +$ endif +$ write tf - + "/*--------------------------------------------------------------*/ +$ write tf "" +$ goto write_tail +$endif +$! +$! +$! Locate the DECC libraries in use +$!----------------------------------- +$decc_rtldef = f$parse("decc$rtldef","sys$library:.tlb;0") +$decc_starletdef = f$parse("sys$starlet_c","sys$library:.tlb;0") +$decc_shr = f$parse("decc$shr","sys$share:.exe;0") +$! +$! Dump the DECC header names into a file +$!---------------------------------------- +$if f$search(dchfile) .nes. "" then delete 'dchfile';* +$if f$search(tfile1) .nes. "" then delete 'tfile1';* +$define/user sys$output 'tfile1' +$library/list 'decc_rtldef' +$open/read/error=rtldef_loop1_end tf1 'tfile1' +$open/write/error=rtldef_loop1_end tf2 'dchfile' +$rtldef_loop1: +$ read/end=rtldef_loop1_end tf1 line_in +$ line_in = f$edit(line_in,"TRIM,COMPRESS") +$ key1 = f$element(0," ",line_in) +$ key2 = f$element(1," ",line_in) +$ if key1 .eqs. " " .or. key1 .eqs. "" then goto rtldef_loop1 +$ if key2 .nes. " " .and. key2 .nes. "" then goto rtldef_loop1 +$ write tf2 "|",key1,"|" +$ goto rtldef_loop1 +$rtldef_loop1_end: +$if f$trnlnm("tf1","lnm$process",,"SUPERVISOR") .nes. "" then close tf1 +$if f$trnlnm("tf2","lnm$process",,"SUPERVISOR") .nes. "" then close tf2 +$if f$search(tfile1) .nes. "" then delete 'tfile1';* +$! +$! Dump the STARLET header names into a file +$!---------------------------------------- +$if f$search(starhfile) .nes. "" then delete 'starhfile';* +$if f$search(tfile1) .nes. "" then delete 'tfile1';* +$define/user sys$output 'tfile1' +$library/list 'decc_starletdef' +$open/read/error=stardef_loop1_end tf1 'tfile1' +$open/write/error=stardef_loop1_end tf2 'starhfile' +$stardef_loop1: +$ read/end=stardef_loop1_end tf1 line_in +$ line_in = f$edit(line_in,"TRIM,COMPRESS") +$ key1 = f$element(0," ",line_in) +$ key2 = f$element(1," ",line_in) +$ if key1 .eqs. " " .or. key1 .eqs. "" then goto stardef_loop1 +$ if key2 .nes. " " .and. key2 .nes. "" then goto stardef_loop1 +$ write tf2 "|",key1,"|" +$ goto stardef_loop1 +$stardef_loop1_end: +$if f$trnlnm("tf1","lnm$process",,"SUPERVISOR") .nes. "" then close tf1 +$if f$trnlnm("tf2","lnm$process",,"SUPERVISOR") .nes. "" then close tf2 +$if f$search(tfile1) .nes. "" then delete 'tfile1';* +$! +$! +$! Now calculate what should be in the file from reading +$! config.h.in and CONFIGURE. +$!--------------------------------------------------------------- +$open/read inf 'cfile' +$do_comment = 0 +$if_block = 0 +$cfgh_in_loop1: +$!set nover +$ read/end=cfgh_in_loop1_end inf line_in +$ xline = f$edit(line_in,"TRIM,COMPRESS") +$! +$! Blank line handling +$!--------------------- +$ if xline .eqs. "" +$ then +$ write tf "" +$ goto cfgh_in_loop1 +$ endif +$ xlen = f$length(xline) +$ key = f$extract(0,2,xline) +$! +$! deal with comments by copying exactly +$!----------------------------------------- +$ if (do_comment .eq. 1) .or. (key .eqs. "/*") +$ then +$ do_comment = 1 +$ write tf line_in +$ key = f$extract(xlen - 2, 2, xline) +$ if key .eqs. "*/" then do_comment = 0 +$ goto cfgh_in_loop1 +$ endif +$! +$! Some quick parsing +$!---------------------- +$ keyif = f$extract(0,3,xline) +$ key1 = f$element(0," ",xline) +$ key2 = f$element(1," ",xline) +$ key2a = f$element(0,"_",key2) +$ key2b = f$element(1,"_",key2) +$ key2_len = f$length(key2) +$ key2_h = f$extract(key2_len - 2, 2, key2) +$ key2_t = f$extract(key2_len - 5, 5, key2) +$ if key2_t .eqs. "_TYPE" then key2_h = "_T" +$ key64 = 0 +$ if f$locate("64", xline) .lt. xlen then key64 = 1 +$! +$!write sys$output "xline = ''xline'" +$! +$! Comment out this section of the ifblock +$!----------------------------------------- +$ if if_block .ge. 3 +$ then +$ write tf "/* ", xline, " */" +$ if keyif .eqs. "#en" then if_block = 0 +$ goto cfgh_in_loop1 +$ endif +$! +$! Handle the end of an ifblock +$!------------------------------- +$ if keyif .eqs. "#en" +$ then +$ write tf xline +$ if_block = 0 +$ goto cfgh_in_loop1 +$ endif +$! +$ if key1 .eqs. "#ifndef" +$ then +$! Manual check for _ALL_SOURCE on AIX error +$!----------------------------------------------- +$ if key2 .eqs. "_ALL_SOURCE" +$ then +$ write tf "/* ", xline, " */" +$! +$! Ignore the rest of the block +$!-------------------------------------- +$ if_block = 3 +$ goto cfgh_in_loop1 +$ endif +$ endif +$! +$! +$! Default action for an #if/#else/#endif +$!------------------------------------------ +$ if keyif .eqs. "#if" .or. keyif .eqs. "#el" +$ then +$ if_block = 1 +$ write tf xline +$ goto cfgh_in_loop1 +$ endif +$! +$! +$! Process "normal?" stuff +$!--------------------------- +$ if key1 .eqs. "#undef" +$ then +$ key2c = f$element(2, "_", key2) +$ if (key2c .eqs. "_") .or. (key2c .eqs. "H") then key2c = "" +$ key2d = f$element(3, "_", key2) +$ if (key2d .eqs. "_") .or. (key2d .eqs. "H") then key2d = "" +$ key2e = f$element(4, "_", key2) +$ if (key2e .eqs. "_") .or. (key2e .eqs. "H") then key2e = "" +$ if key2d .eqs. "T" +$ then +$ if key2e .eqs. "TYPE" +$ then +$ key2_h = "_T" +$ key2d = "" +$ endif +$ endif +$! +$ double_under = 0 +$! +$! Process FCNTL directives +$!------------------------------------- +$ if (key2b .eqs. "FCNTL") .and. (key2c .eqs. "O") .and. - + (key2d .eqs. "NONBLOCK") +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$! Process GETADDRINFO directives +$!------------------------------------- +$ if key2 .eqs. "GETADDRINFO_THREADSAFE" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$! Process IOCTL directives +$!------------------------------------- +$ if (key2b .eqs. "IOCTL") .and. (key2c .nes. "") +$ then +$ if (key2c .eqs. "FIONBIO") .or. (key2c .eqs. "SIOCGIFADDR") +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ endif +$! +$! +$! Manual check for LL on +$!----------------------------------------------- +$ if key2 .eqs. "LL" +$ then +$ write tf "#ifndef __VAX +$ write tf "#define HAVE_''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "bool_t" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' short" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "bits16_t" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' short" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "u_bits16_t" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' unsigned short" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "bits32_t" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' int" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "u_bits32_t" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' unsigned int" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "intmax_t" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#ifdef __VAX" +$ write tf "#define ''key2' long" +$ write tf "#else" +$ write tf "#define ''key2' long long" +$ write tf "#endif" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "uintmax_t" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#ifdef __VAX" +$ write tf "#define ''key2' unsigned long" +$ write tf "#else" +$ write tf "#define ''key2' unsigned long long" +$ write tf "#endif" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "socklen_t" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' int" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "GETGROUPS_T" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' gid_t" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_DECL_SYS_SIGLIST" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 0" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_SYS_ERRLIST" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_STRUCT_DIRENT_D_INO" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_STRUCT_TIMEVAL" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$! ! The header files have this information, however +$! ! The ioctl() call only works on sockets. +$! if key2 .eqs. "FIONREAD_IN_SYS_IOCTL" +$! then +$! write tf "#ifndef ''key2'" +$! write tf "#define ''key2' 1" +$! write tf "#endif" +$! goto cfgh_in_loop1 +$! endif +$! +$! ! The header files have this information, however +$! ! The ioctl() call only works on sockets. +$! if key2 .eqs. "GWINSZ_IN_SYS_IOCTL" +$! then +$! write tf "#ifndef ''key2'" +$! write tf "#define ''key2' 1" +$! write tf "#endif" +$! goto cfgh_in_loop1 +$! endif +$! +$! ! The header files have this information, however +$! ! The ioctl() call only works on sockets. +$! if key2 .eqs. "STRUCT_WINSIZE_IN_SYS_IOCTL" +$! then +$! write tf "#ifndef ''key2'" +$! write tf "#define ''key2' 0" +$! write tf "#endif" +$! goto cfgh_in_loop1 +$! endif +$! +$ if key2 .eqs. "HAVE_STRUCT_TM_TM_ZONE" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_TM_ZONE" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_TIMEVAL" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "WEXITSTATUS_OFFSET" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 2" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_GETPW_DECLS" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_DECL_CONFSTR" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_DECL_PRINTF" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_DECL_SBRK" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_DECL_STRSIGNAL" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 0" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2a .eqs. "HAVE_DECL_STRTOLD" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 0" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_DECL_STRTOIMAX" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 0" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_DECL_STRTOL" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_DECL_STRTOLL" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_DECL_STRTOUL" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_DECL_STRTOULL" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_DECL_STRTOUMAX" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 0" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "GETPGRP_VOID" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "NAMED_PIPES_MISSING" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "OPENDIR_NOT_ROBUST" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "PGRP_PIPE" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "CAN_REDEFINE_GETENV" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_PRINTF_A_FORMAT" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "CTYPE_NON_ASCII" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_LANGINFO_CODESET" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 0" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$! This wants execve() to do this automagically to pass. +$! if key2 .eqs. "HAVE_HASH_BANG_EXEC" +$! then +$! write tf "#ifndef ''key2'" +$! write tf "#define ''key2' 1" +$! write tf "#endif" +$! goto cfgh_in_loop1 +$! endif +$! +$ if key2 .eqs. "ICONV_CONST" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2'" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "VOID_SIGHANDLER" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_POSIX_SIGNALS" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "UNUSABLE_RT_SIGNALS" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2a .eqs. "HAVE_DECL_FPURGE" +$ then +$ write tf "#ifndef ''key2a'" +$ write tf "#define ''key2a' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_DECL_SETREGID" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "HAVE_POSIX_SIGSETJMP" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2b .eqs. "RAND" .and. key2c .nes. "" .and. key2d .eqs. "" +$ then +$ if (key2c .eqs. "EGD") .or. - + (key2c .eqs. "STATUS") .or. - + (key2c .eqs. "SCREEN") +$ then +$ if f$search("''ssl_header_dir'rand.h") .nes. "" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ else +$ write tf "/* #undef ''key2' */" +$ endif +$ endif +$ endif +$! +$ if key2 .eqs. "STRCOLL_BROKEN" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2 .eqs. "DUP_BROKEN" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$! This is for a test that getcwd(0,0) works. +$! It does not on VMS. +$!-------------------------- +$ if key2 .eqs. "GETCWD_BROKEN" +$ then +$ write sys$output "" +$ write sys$output - + "%CONFIG_H-I-NONPORT, ''key2' being tested for!" +$ write sys$output - + "-CONFIG_H-I-GETCWD, GETCWD(0,0) does not work on VMS." +$ write sys$output - + "-CONFIG_H-I-GETCWD2, Work around hack probably required." +$ write sys$output - + "-CONFIG_H-I-REVIEW, Manual Code review required!" +$ if update_config_vms +$ then +$ open/append tfcv sys$disk:[]config_vms.h +$ write tfcv "" +$ write tfcv - + "/* Check config.h for use of ''key2' settings */" +$ write tfcv "" +$ close tfcv +$ endif +$ +$ goto cfgh_in_loop1 +$ endif +$! +$ if (key2a .eqs. "HAVE") .or. (key2a .eqs. "STAT") .or. - + (key2 .eqs. "USE_IPV6") .or. (key2b .eqs. "LDAP") +$ then +$! +$! Process extra underscores +$!------------------------------------ +$ if f$locate("HAVE___", key2) .lt. key2_len +$ then +$ key2b = "__" + key2d +$ key2d = "" +$ double_under = 1 +$ else +$ if f$locate("HAVE__", key2) .lt. key2_len +$ then +$ key2b = "_" + key2c +$ key2c = "" +$ double_under = 1 +$ endif +$ endif +$! +$ if (key2_h .eqs. "_H") .or. (key2 .eqs. "USE_IPV6") .or. - + (key2b .eqs. "LDAP") +$ then +$! +$! Looking for a header file +$!--------------------------------------- +$ headf = key2b +$ if key2c .nes. "" then headf = headf + "_" + key2c +$ if key2d .nes. "" then headf = headf + "_" + key2d +$! +$! (key2b .eqs. "READLINE") +$! +$! Some special parsing +$!------------------------------------------ +$ if (key2b .eqs. "SYS") .or. (key2b .eqs. "ARPA") .or. - + (key2b .eqs. "NET") .or. (key2b .eqs. "NETINET") +$ then +$ if key2c .nes. "" +$ then +$ headf = key2c +$ if key2d .nes. "" then headf = key2c + "_" + key2d +$ endif +$ endif +$! +$! And of course what's life with out some special cases +$!-------------------------------------------------------------------- +$ if key2 .eqs. "USE_IPV6" +$ then +$ headf = "in6" +$ endif +$! +$ if key2b .eqs. "LDAP" +$ then +$ if (key2 .eqs. "HAVE_LDAP_SSL") .or. - + (key2 .eqs. "HAVE_LDAP_URL_PARSE") +$ then +$ headf = "ldap" +$ endif +$ endif +$! +$! +$ if key2b .eqs. "FILE" +$ then +$ write sys$output "" +$ write sys$output - + "%CONFIG_H-I-NONPORT, ''key2' being asked for!" +$ write sys$output - + "-CONFIG_H-I-FILE_OLD, file.h will not be configured as is obsolete!" +$ write sys$output - + "-CONFIG_H_I-FCNTL_NEW, "Expecting fcntl.h to be configured instead!" +$ write sys$output - + "-CONFIG_H_I-FCNTL_CHK, "Unable to verify at this time!" +$ write sys$output - + "-CONFIG_H-I-REVIEW, Manual Code review required!" +$! +$ if update_config_vms +$ then +$ open/append tfcv sys$disk:[]config_vms.h +$ write tfcv "" +$ write tfcv - + "/* Check config.h for use of fcntl.h instead of file.h */" +$ write tfcv "" +$ close tfcv +$ endif +$ endif +$! +$! Now look it up in the DEC C RTL +$!--------------------------------------------- +$ define/user sys$output nl: +$ define/user sys$error nl: +$ search/output=nl: 'dchfile' |'headf'|/exact +$ if '$severity' .eq. 1 +$ then +$ if key64 then write tf "#ifndef __VAX" +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$if p2 .nes. "" then write sys$output "''dchfile' - #define ''key2' 1" +$ write tf "#endif" +$ if key64 then write tf "#endif" +$set nover +$ goto cfgh_in_loop1 +$ endif +$! +$! +$! Now look it up in the DEC C STARLET_C +$!--------------------------------------------- +$ define/user sys$output nl: +$ define/user sys$error nl: +$ search/output=nl: 'starhfile' |'headf'|/exact +$ if '$severity' .eq. 1 +$ then +$ if key64 then write tf "#ifndef __VAX" +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$if p2 .nes. "" then write sys$output "''starfile' - #define ''key2' 1" +$ write tf "#endif" +$ if key64 then write tf "#endif" +$set nover +$ goto cfgh_in_loop1 +$ endif +$! +$! Now look for OPENSSL headers +$!--------------------------------------------------------- +$ if key2b .eqs. "OPENSSL" +$ then +$ headf = headf - "OPENSSL_" +$ header = f$search("''ssl_header_dir'''headf'.h") +$ if header .nes. "" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$set nover +$ goto cfgh_in_loop1 +$ endif +$ endif +$! +$! Now look for Kerberos +$!------------------------------------------------------------ +$ if key2b .eqs. "GSSAPI" +$ then +$ header_dir = "sys$sysroot:[kerberos.include]" +$ headf = headf - "GSSAPI_" +$ header = f$search("''header_dir'''headf'.h") +$ if header .nes. "" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$set nover +$ goto cfgh_in_loop1 +$ endif +$ endif +$! +$set nover +$ else +$! +$! Looking for a routine or a symbol +$!------------------------------------------------ +$ if key2c .eqs. "MACRO" +$ then +$ if (key2b .eqs. "FILE") .or. (key2b .eqs. "DATE") - + .or. (key2b .eqs. "LINE") .or. (key2b .eqs. "TIME") +$ then +$ write tf "#ifndef HAVE_''key2b'" +$ write tf "#define HAVE_''key2b' 1" +$ write tf "#endif" +$ endif +$ goto cfgh_in_loop1 +$ endif +$! +$! Special false tests +$!------------------------------------- +$ if double_under +$ then +$ if key2b .eqs. "_FCNTL" .or. key2b .eqs. "__FCNTL" +$ then +$ write tf "/* #undef HAVE_''key2b' */" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2b .eqs. "_STAT" .or. key2b .eqs. "__STAT" +$ then +$ write tf "/* #undef HAVE_''key2b' */" +$ goto cfgh_in_loop1 +$ endif +$! +$ if key2b .eqs. "_READ" .or. key2b .eqs. "__READ" +$ then +$ write tf "/* #undef HAVE_''key2b' */" +$ goto cfgh_in_loop1 +$ endif +$ endif +$! +$ keysym = key2b +$ if key2c .nes. "" then keysym = keysym + "_" + key2c +$ if key2d .nes. "" then keysym = keysym + "_" + key2d +$ if key2e .nes. "" then keysym = keysym + "_" + key2e +$! +$! +$! Stat structure members +$!------------------------------------- +$ if key2b .eqs. "STRUCT" +$ then +$ if key2c .eqs. "STAT" .and (key2d .nes. "") +$ then +$ key2b = key2b + "_" + key2c + "_" + key2d +$ key2c = key2e +$ key2d = "" +$ key2e = "" +$ endif +$ endif +$ if (key2b .eqs. "ST") .or. (key2b .eqs. "STRUCT_STAT_ST") +$ then +$ keysym = "ST" + "_" + key2c +$ keysym = f$edit(keysym,"LOWERCASE") +$ endif +$ if key2a .eqs. "STAT" +$ then +$ if (f$locate("STATVFS", key2b) .eq. 0) .and. key2c .eqs. "" +$ then +$ keysym = f$edit(key2b, "LOWERCASE") +$ endif +$!$ if (key2b .eqs. "STATVFS" .or. key2b .eqs. "STATFS2" - +$! .or. key2b .eqs. "STATFS3") .and. key2c .nes. "" +$! +$ if (key2b .eqs. "STATVFS") .and. key2c .nes. "" +$ then +$! Should really verify that the structure +$! named by key2b actually exists first. +$!------------------------------------------------------------ +$! +$! Statvfs structure members +$!------------------------------------------------- +$ keysym = "f_" + f$edit(key2c,"LOWERCASE") +$ endif +$ endif +$! +$! UTMPX structure members +$!-------------------------------------- +$ if key2b .eqs. "UT" .and. key2c .eqs. "UT" +$ then +$ keysym = "ut_" + f$edit(key2d,"LOWERCASE") +$ endif +$! +$ if f$locate("MMAP",key2) .lt. key2_len +$ then +$ write sys$output "" +$ write sys$output - + "%CONFIG_H-I-NONPORT, ''key2' being asked for!" +$ write sys$output - + "-CONFIG_H-I-MMAP, MMAP operations only work on STREAM and BINARY files!" +$ write sys$output - + "-CONFIG_H-I-REVIEW, Manual Code review required!" +$ if update_config_vms +$ then +$ open/append tfcv sys$disk:[]config_vms.h +$ write tfcv "" +$ write tfcv - + "/* Check config.h for use of ''key2' settings */" +$ write tfcv "" +$ close tfcv +$ endif +$ endif +$! +$! +$ if keysym .eqs. "CRYPT" +$ then +$ write sys$output "" +$ write sys$output - + "%CONFIG_H-I-NONPORT, ''key2' being asked for!" +$ write sys$output - + "-CONFIG_H-I-CRYPT, CRYPT operations on the VMS SYSUAF may not work!" +$ write sys$output - + "-CONFIG_H-I-REVIEW, Manual Code review required!" +$ if update_config_vms +$ then +$ open/append tfcv sys$disk:[]config_vms.h +$ write tfcv "" +$ write tfcv - + "/* Check config.h for use of ''keysym' */" +$ write tfcv "" +$ close tfcv +$ endif +$ endif +$! +$! +$ if keysym .eqs. "EXECL" +$ then +$ write sys$output "" +$ write sys$output - + "%CONFIG_H-I-NONPORT, ''key2' being asked for!" +$ write sys$output - + "-CONFIG_H-I-EXCEL, EXECL configured, Will probably not work." +$ write sys$output - + "-CONFIG_H-I-REVIEW, Manual Code review required!" +$ if update_config_vms +$ then +$ open/append tfcv sys$disk:[]config_vms.h +$ write tfcv "" +$ write tfcv - + "/* Check config.h for use of ''keysym' */" +$ write tfcv "" +$ close tfcv +$ endif +$ endif +$! +$! +$! Process if cpp supports ANSI-C stringizing '#' operator +$!----------------------------------------------------------------------- +$ if keysym .eqs. "STRINGIZE" +$ then +$ write tf "#ifndef HAVE_STRINGIZE" +$ write tf "#define HAVE_STRINGSIZE 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if keysym .eqs. "VOLATILE" +$ then +$ write tf "#ifndef HAVE_VOLATILE" +$ write tf "#define HAVE_VOLATILE 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if keysym .eqs. "ALLOCA" +$ then +$ write tf "#ifndef HAVE_ALLOCA" +$ write tf "#define HAVE_ALLOCA 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if keysym .eqs. "ERRNO_DECL" +$ then +$ write tf "#ifndef HAVE_ERRNO_DECL" +$ write tf "#define HAVE_ERRNO_DECL 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if keysym .eqs. "LONGLONG" +$ then +$ write tf "#ifndef __VAX" +$ write tf "#pragma message disable longlongtype" +$ write tf "#ifndef HAVE_LONGLONG" +$ write tf "#define HAVE_LONGLONG 1" +$ write tf "#endif" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$! May need to test compiler version +$!----------------------------------------------- +$ if keysym .eqs. "LONG_LONG" +$ then +$ write tf "#ifndef __VAX" +$ write tf "#pragma message disable longlongtype" +$ write tf "#ifndef HAVE_LONG_LONG" +$ write tf "#define HAVE_LONG_LONG 1" +$ write tf "#endif" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$! May need to test compiler version +$!----------------------------------------------- +$ if keysym .eqs. "UNSIGNED_LONG_LONG" +$ then +$ write tf "#ifndef __VAX" +$ write tf "#pragma message disable longlongtype" +$ write tf "#ifndef HAVE_UNSIGNED_LONG_LONG" +$ write tf "#define HAVE_UNSIGNED_LONG_LONG 1" +$ write tf "#endif" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$! May need to test compiler version +$!----------------------------------------------- +$ if keysym .eqs. "UNSIGNED_LONG_LONG_INT" +$ then +$ write tf "#ifndef __VAX" +$ write tf "#pragma message disable longlongtype" +$ write tf "#ifndef HAVE_UNSIGNED_LONG_LONG_INT" +$ write tf "#define HAVE_UNSIGNED_LONG_LONG_INT 1" +$ write tf "#endif" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$! May need to test compiler version +$!----------------------------------------------- +$ if keysym .eqs. "LONG_DOUBLE" +$ then +$ write tf "#ifndef __VAX" +$ write tf "#pragma message disable longlongtype" +$ write tf "#ifndef HAVE_LONG_DOUBLE" +$ write tf "#define HAVE_LONG_DOUBLE 1" +$ write tf "#endif" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$ if keysym .eqs. "FCNTL_LOCK" +$ then +$ write sys$output - + "%CONFIG_H-I-NONPORT, ''key2' being asked for! +$ write sys$output - + "-CONFIG_H-I-REVIEW, Manual Code review required!" +$ goto cfgh_in_loop1 +$ endif +$! +$! +$! These libraries are provided by the DEC C RTL +$!------------------------------------------------------------- +$ if keysym .eqs. "LIBINET" .or. keysym .eqs. "LIBSOCKET" +$ then +$ write tf "#ifndef HAVE_''keysym'" +$ write tf "#define HAVE_''keysym' 1" +$if p2 .nes. "" then write sys$output "''decc_shr' #define ''keysym' 1" +$ write tf "#endif +$ goto cfgh_in_loop1 +$ endif +$! +$ if keysym .eqs. "HERRNO" then keysym = "h_errno" +$ if keysym .eqs. "UTIMBUF" then keysym = "utimbuf" +$ if key2c .eqs. "STRUCT" +$ then +$ keysym = f$edit(key2d,"LOWERCASE") +$ else +$ if key2_h .eqs. "_T" +$ then +$ if key2_t .eqs. "_TYPE" +$ then +$ keysym = f$extract(0, key2_len - 5, key2) - "HAVE_" +$ endif +$ keysym = f$edit(keysym,"LOWERCASE") +$ endif +$ endif +$! +$! Check the DEC C RTL shared image first +$!------------------------------------------------------ +$ if f$search(tfile1) .nes. "" then delete 'tfile1';* +$ define/user sys$output nl: +$ define/user sys$error nl: +$ search/format=nonull/out='tfile1' 'decc_shr' 'keysym' +$ if '$severity' .eq. 1 +$ then +$! +$! Not documented, but from observation +$!------------------------------------------------------ +$ define/user sys$output nl: +$ define/user sys$error nl: +$ if arch_type .eq. 3 +$ then +$ keyterm = "''keysym'" +$ else +$ if arch_type .eq. 2 +$ then +$ keyterm = "''keysym'" +$ else +$ keyterm = "''keysym'" +$ endif +$ endif +$ search/out=nl: 'tfile1' - + "$''keyterm'","$g''keyterm'","$__utc_''keyterm'",- + "$__utctz_''keyterm'","$__bsd44_''keyterm'","$bsd_''keyterm'",- + "$''keysym'decc$","$G''keysym'decc$","$GX''keyterm'" +$ severity = '$severity' +$! +$! +$! Of course the 64 bit stuff is different +$!--------------------------------------------------------- +$ if severity .ne. 1 .and. key64 +$ then +$ define/user sys$output nl: +$ define/user sys$error nl: +$ search/out=nl: 'tfile1' "$_''keyterm'" +$! search/out 'tfile1' "$_''keyterm'" +$ severity = '$severity' +$ endif +$! +$! Unix compatibility routines +$!--------------------------------------------- +$ if severity .ne. 1 +$ then +$ define/user sys$output nl: +$ define/user sys$error nl: +$ search/out=nl: 'tfile1' - + "$__unix_''keyterm'","$__vms_''keyterm'","$_posix_''keyterm'" +$ severity = '$severity' +$ endif +$! +$! Show the result of the search +$!------------------------------------------------ +$ if 'severity' .eq. 1 +$ then +$ if key64 then write tf "#ifndef __VAX" +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$if p2 .nes. "" then write sys$output "''decc_shr' #define ''key2' 1" +$ write tf "#endif" +$ if key64 then write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ endif +$ if f$search(tfile1) .nes. "" then delete 'tfile1';* +$! +$! Check the DECC Header files next +$!---------------------------------------------- +$ define/user sys$output nl: +$ define/user sys$error nl: +$ search/out=nl: 'decc_rtldef' - + "''keysym';", "''keysym'[", "struct ''keysym'"/exact +$ severity = '$severity' +$ if severity .eq. 1 +$ then +$ if key64 then write tf "#ifndef __VAX" +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$if p2 .nes. "" then write sys$output "''decc_rtldef' #define ''key2' 1" +$ write tf "#endif" +$ if key64 then write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$! Check kerberos +$!-------------------------------------------- +$ if f$search("SYS$SYSROOT:[kerberos]include.dir") .nes. "" +$ then +$ test_mit = "SYS$SYSROOT:[kerberos.include]gssapi_krb5.h" +$ if (key2 .eqs. "HAVE_GSSAPI") +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ endif +$! +$ endif +$ write tf "/* ", xline, " */" +$ goto cfgh_in_loop1 +$ endif +$! +$! +$! Process SIZEOF directives found in SAMBA and others +$!---------------------------------------------------------- +$ if key2a .eqs. "SIZEOF" +$ then +$ if key2b .eqs. "INO" .and. key2_h .eqs. "_T" +$ then +$ write tf "#ifndef SIZEOF_INO_T" +$ write tf "#if !__USING_STD_STAT +$ write tf "#define SIZEOF_INO_T 6" +$ write tf "#else +$ write tf "#define SIZEOF_INO_T 8" +$ write tf "#endif +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2b .eqs. "INTMAX" .and. key2_h .eqs. "_T" +$ then +$ write tf "#ifndef SIZEOF_INTMAX_T" +$ write tf "#ifdef __VAX" +$ write tf "#define SIZEOF_INTMAX_T 4" +$ write tf "#else" +$ write tf "#define SIZEOF_INTMAX_T 8" +$ write tf "#endif" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2b .eqs. "OFF" .and. key2_h .eqs. "_T" +$ then +$ write tf "#ifndef SIZEOF_OFF_T" +$ write tf "#if __USE_OFF64_T" +$ write tf "#define SIZEOF_OFF_T 8" +$ write tf "#else" +$ write tf "#define SIZEOF_OFF_T 4" +$ write tf "#endif" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2b .eqs. "CHAR" .and. key2_h .eqs. "_P" +$ then +$ write tf "#ifndef SIZEOF_CHAR_P" +$ write tf "#if __INITIAL_POINTER_SIZE == 64" +$ write tf "#define SIZEOF_CHAR_P 8" +$ write tf "#else" +$ write tf "#define SIZEOF_CHAR_P 4" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2b .eqs. "VOIDP" +$ then +$ write tf "#ifndef SIZEOF_VOIDP" +$ write tf "#if __INITIAL_POINTER_SIZE == 64" +$ write tf "#define SIZEOF_VOIDP 8" +$ write tf "#else" +$ write tf "#define SIZEOF_VOIDP 4" +$ write tf "#endif" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2b .eqs. "INT" +$ then +$ write tf "#ifndef SIZEOF_INT" +$ write tf "#define SIZEOF_INT 4" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2b .eqs. "SIZE" .and. key2_h .eqs. "_T" +$ then +$ write tf "#ifndef SIZEOF_SIZE_T" +$ write tf "#define SIZEOF_SIZE_T 4" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2b .eqs. "TIME" .and. key2_h .eqs. "_T" +$ then +$ write tf "#ifndef SIZEOF_TIME_T" +$ write tf "#define SIZEOF_TIME_T 4" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2b .eqs. "DOUBLE" +$ then +$ write tf "#ifndef SIZEOF_DOUBLE" +$ write tf "#define SIZEOF_DOUBLE 8" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2b .eqs. "LONG" +$ then +$ if key2c .eqs. "" +$ then +$ write tf "#ifndef SIZEOF_LONG" +$ write tf "#define SIZEOF_LONG 4" +$ write tf "#endif" +$ else +$ write tf "#ifndef SIZEOF_LONG_LONG" +$ write tf "#ifndef __VAX" +$ write tf "#define SIZEOF_LONG_LONG 8" +$ write tf "#endif" +$ write tf "#endif" +$ endif +$ goto cfgh_in_loop1 +$ endif +$ write tf "/* ", xline, " */" +$ goto cfgh_in_loop1 +$ endif +$! +$! Process NEED directives +$!------------------------------- +$ if key2a .eqs. "NEED" +$ then +$ if key2b .eqs. "STRINGS" .and. key2_h .eqs. "_H" +$ then +$ write tf "#ifndef NEED_STRINGS_H" +$ write tf "#define NEED_STRINGS_H 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ write tf "/* ", xline, " */" +$ goto cfgh_in_loop1 +$ endif +$! +$! Process GETHOSTNAME directives +$!------------------------------------- +$ if key2 .eqs. "GETHOSTNAME_TYPE_ARG2" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#ifdef _DECC_V4_SOURCE" +$ write tf "#define ''key2' int" +$ write tf "#else" +$ write tf "#define ''key2' size_t" +$ write tf "#endif" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$! Process GETNAMEINFO directives +$!------------------------------------- +$ if key2a .eqs. "GETNAMEINFO" +$ then +$ if key2 .eqs. "GETNAMEINFO_QUAL_ARG1" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' const" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2 .eqs. "GETNAMEINFO_TYPE_ARG1" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' struct sockaddr *" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2 .eqs. "GETNAMEINFO_TYPE_ARG2" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' size_t" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2 .eqs. "GETNAMEINFO_TYPE_ARG46" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' size_t" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2 .eqs. "GETNAMEINFO_TYPE_ARG7" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' int" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ endif +$! +$! Process RECV directives +$!------------------------------------- +$ if key2a .eqs. "RECV" +$ then +$ if key2 .eqs. "RECV_TYPE_ARG1" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' int" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2 .eqs. "RECV_TYPE_ARG2" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' void *" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2 .eqs. "RECV_TYPE_ARG3" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' size_t" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2 .eqs. "RECV_TYPE_ARG4" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' int" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2 .eqs. "RECV_TYPE_RETV" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' int" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ endif +$! +$! Process SEND directives +$!------------------------------------- +$ if key2a .eqs. "SEND" +$ then +$ if key2 .eqs. "SEND_QUAL_ARG2" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' const" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2 .eqs. "SEND_TYPE_ARG1" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' int" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2 .eqs. "SEND_TYPE_ARG2" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' void *" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2 .eqs. "SEND_TYPE_ARG3" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' size_t" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2 .eqs. "SEND_TYPE_ARG4" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' int" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ if key2 .eqs. "SEND_TYPE_RETV" +$ then +$ write tf "#ifndef ''key2'" +$ write tf "#define ''key2' int" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$ endif +$! +$! +$! Process STATFS directives +$!------------------------------- +$! if key2a .eqs. "STATFS" +$! then +$! write tf "/* ", xline, " */" +$! goto cfgh_in_loop1 +$! endif +$! +$! Process inline directive +$!------------------------------ +$ if key2 .eqs. "inline" +$ then +$ write tf "#ifndef inline" +$ write tf "#define inline __inline" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$! Process restrict directive +$!-------------------------------- +$ if key2 .eqs. "restrict" +$ then +$ write tf "#ifndef restrict" +$ write tf "#define restrict __restrict" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$! Process STDC_HEADERS (SAMBA!) +$!--------------------------- +$ if key2 .eqs. "STDC_HEADERS" +$ then +$ write tf "#ifndef STDC_HEADERS" +$ write tf "#define STDC_HEADERS 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$! Process PROTOTYPES directive +$!------------------------------------- +$ if key2 .eqs. "PROTOTYPES" +$ then +$ write tf "#ifndef PROTOTYPES" +$ write tf "#define PROTOTYPES 1" +$ write tf "#endif" +$ goto cfgh_in_loop1 +$ endif +$! +$! Special for SEEKDIR_RETURNS_VOID +$!--------------------------------------- +$ if key2 .eqs. "SEEKDIR_RETURNS_VOID" +$ then +$ write tf "#ifndef SEEKDIR_RETURNS_VOID" +$ write tf "#define SEEKDIR_RETURNS_VOID 1" +$ write tf "#endif" +$ endif +$! +$! Unknown - See if CONFIGURE can give a clue for this +$!---------------------------------------------------------- +$ pflag = 0 +$ set_flag = 0 +$! gproj_name = proj_name - "_VMS" - "-VMS" +$ if f$search(tfile1) .nes. "" then delete 'tfile1';* +$ define/user sys$output nl: +$ define/user sys$error nl: +$! if f$locate("FILE", key2) .lt. key2_len then pflag = 1 +$! if f$locate("DIR", key2) .eq. key2_len - 3 then pflag = 1 +$! if f$locate("PATH", key2) .eq. key2_len - 4 then pflag = 1 +$! +$ search/out='tfile1' 'configure_script' "''key2'="/exact +$ search_sev = '$severity' +$ if 'search_sev' .eq. 1 +$ then +$ open/read/err=unknown_cf_rd_error sf 'tfile1' +$search_file_rd_loop: +$ read/end=unknown_cf_rd_err sf line_in +$ line_in = f$edit(line_in, "TRIM") +$ skey1 = f$element(0,"=",line_in) +$ if skey1 .eqs. key2 +$ then +$ skey2 = f$element(1,"=",line_in) +$ skey2a = f$extract(0,2,skey2) +$! +$! +$! We can not handle assignment to shell symbols. +$! For now skip them. +$!------------------------------------------------------------ +$ if f$locate("$", skey2) .lt. f$length(skey2) +$ then +$ write tf "/* ", xline, " */" +$ set_flag = 1 +$ goto found_in_configure +$ endif +$! +$! Keep these two cases separate to make it easier to add +$! more future intelligence to this routine +$!---------------------------------------------------------------------- +$ if skey2a .eqs. """`" +$ then +$! if pflag .eq. 1 +$! then +$! write tf "#ifndef ''key2'" +$! write tf "#define ",key2," """,gproj_name,"_",key2,"""" +$! write tf "#endif" +$! else +$! Ignore this for now +$!------------------------------------------ +$ write tf "/* ", xline, " */" +$! endif +$ set_flag = 1 +$ goto found_in_configure +$ endif +$ if skey2a .eqs. """$" +$ then +$! if pflag .eq. 1 +$! then +$! write tf "#ifndef ''key2'" +$! write tf "#define ",key2," """,gproj_name,"_",key2,"""" +$! write tf "#endif" +$! else +$! Ignore this for now +$!------------------------------------------- +$ write tf "/* ", xline, " */" +$! endif +$ set_flag = 1 +$ goto found_in_configure +$ endif +$! +$! Remove multiple layers of quotes if present +$!---------------------------------------------------------- +$ if f$extract(0, 1, skey2) .eqs. "'" +$ then +$ skey2 = skey2 - "'" - "'" - "'" - "'" +$ endif +$ if f$extract(0, 1, skey2) .eqs. """" +$ then +$ skey2 = skey2 - """" - """" - """" - """" +$ endif +$ write tf "#ifndef ''key2'" +$ if skey2 .eqs. "" +$ then +$ write tf "#define ",key2 +$ else +$! Only quote non-numbers +$!---------------------------------------- +$ if f$string(skey2+0) .eqs. skey2 +$ then +$ write tf "#define ",key2," ",skey2 +$ else +$ write tf "#define ",key2," """,skey2,"""" +$ endif +$ endif +$ write tf "#endif" +$ set_flag = 1 +$ else +$ goto search_file_rd_loop +$! if pflag .eq. 1 +$! then +$! write tf "#ifndef ''key2'" +$! write tf "#define ",key2," """,gproj_name,"_",key2,"""" +$! write tf "#endif" +$! set_flag = 1 +$! endif +$ endif +$found_in_configure: +$unknown_cf_rd_err: +$ if f$trnlnm("sf","lnm$process",,"SUPERVISOR") .nes. "" +$ then +$ close sf +$ endif +$ if f$search(tfile1) .nes. "" then delete 'tfile1';* +$ if set_flag .eq. 1 then goto cfgh_in_loop1 +$ endif +$ endif +$! +$! +$! +$! If it falls through everything else, comment it out +$!----------------------------------------------------- +$ write tf "/* ", xline, " */" +$ goto cfgh_in_loop1 +$cfgh_in_loop1_end: +$close inf +$! +$! +$! Write out the tail +$!-------------------- +$write_tail: +$gosub write_config_h_tail +$! +$! Exit and clean up +$!-------------------- +$general_error: +$status = '$status' +$all_exit: +$set noon +$if f$trnlnm("sf","lnm$process",,"SUPERVISOR") .nes. "" then close sf +$if f$trnlnm("tf","lnm$process",,"SUPERVISOR") .nes. "" then close tf +$if f$trnlnm("inf","lnm$process",,"SUPERVISOR") .nes. "" then close inf +$if f$trnlnm("tf1","lnm$process",,"SUPERVISOR") .nes. "" then close tf1 +$if f$trnlnm("tf2","lnm$process",,"SUPERVISOR") .nes. "" then close tf2 +$if f$trnlnm("tfcv","lnm$process",,"SUPERVISOR") .nes. "" then close tfcv +$if f$type(tfile1) .eqs. "STRING" +$then +$ if f$search(tfile1) .nes. "" then delete 'tfile1';* +$endif +$if f$type(dchfile) .eqs. "STRING" +$then +$ if f$search(dchfile) .nes. "" then delete 'dchfile';* +$endif +$if f$type(starhfile) .eqs. "STRING" +$then +$ if f$search(starhfile) .nes. "" then delete 'starhfile';* +$endif +$if f$type(configure_script) .eqs. "STRING" +$then +$ if f$search(configure_script) .nes. "" then delete 'configure_script';* +$endif +$exit 'status' +$! +$! +$control_y: +$ status = ss_control_y +$ goto all_exit +$! +$! +$! +$! Gosub to write a new config_vms.h +$!----------------------------------- +$write_config_vms: +$outfile = "sys$disk:[]config_vms.h" +$create 'outfile' +$open/append tf 'outfile' +$write tf "/* File: config_vms.h" +$write tf "**" +$write tf "** This file contains the manual edits needed for porting" +$!write tf "** the ''proj_name' package to OpenVMS. +$write tf "**" +$write tf "** Edit this file as needed. The procedure that automatically" +$write tf "** generated this header stub will not overwrite or make any" +$write tf "** changes to this file." +$write tf "**" +$write tf - + "** ", datetime, tab, username, tab, "Generated by ''my_proc_file'" +$write tf "**" +$write tf - + "**========================================================================*/" +$write tf "" +$close tf +$return +$! +$! gosub to write out a documentation header for config.h +$!---------------------------------------------------------------- +$write_config_h_header: +$outfile = "sys$disk:[]config.h" +$create 'outfile' +$open/append tf 'outfile' +$write tf "#ifndef CONFIG_H" +$write tf "#define CONFIG_H" +$write tf "/* File: config.h" +$write tf "**" +$write tf - + "** This file contains the options needed for porting " +$write tf "** the project on a VMS system." +$write tf "**" +$write tf "** Try not to make any edits to this file, as it is" +$write tf "** automagically generated." +$write tf "**" +$write tf "** Manual edits should be made to the config_vms.h file." +$write tf "**" +$write tf - + "** ", datetime, tab, username, tab, "Generated by ''my_proc_file'" +$write tf "**" +$write tf - + "**========================================================================*/" +$write tf "" +$write tf "#if (__CRTL_VER >= 70200000) && !defined (__VAX)" +$write tf "#define _LARGEFILE 1" +$write tf "#endif" +$write tf "" +$write tf "#ifndef __VAX" +$write tf "#ifdef __CRTL_VER" +$write tf "#if __CRTL_VER >= 80200000" +$write tf "#define _USE_STD_STAT 1" +$write tf "#endif" +$write tf "#endif" +$write tf "#endif" +$write tf "" +$! +$write tf " /* Allow compiler builtins */" +$write tf "/*-------------------------*/" +$write tf "#ifdef __DECC_VER" +$write tf "#include " +$write tf "#endif" +$! +$write tf "" +$return +$! +$! gosub to write out the tail for config.h and close it +$!--------------------------------------------------------- +$write_config_h_tail: +$write tf "" +$write tf " /* Include the hand customized settings */" +$write tf "/*--------------------------------------*/" +$write tf "#include ""config_vms.h""" +$write tf "" +$write tf "#endif /* CONFIG_H */" +$close tf +$return +$! diff --git a/third_party/curl/packages/vms/curl_crtl_init.c b/third_party/curl/packages/vms/curl_crtl_init.c new file mode 100644 index 0000000..6ae7e8c --- /dev/null +++ b/third_party/curl/packages/vms/curl_crtl_init.c @@ -0,0 +1,333 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* File: curl_crtl_init.c + * + * This file makes sure that the DECC Unix settings are correct for + * the mode the program is run in. + * + * The CRTL has not been initialized at the time that these routines + * are called, so many routines can not be called. + * + * This is a module that provides a LIB$INITIALIZE routine that + * will turn on some CRTL features that are not enabled by default. + * + * The CRTL features can also be turned on via logical names, but that + * impacts all programs and some aren't ready, willing, or able to handle + * those settings. + * + * On VMS versions that are too old to use the feature setting API, this + * module falls back to using logical names. + * + * Copyright (C) John Malmberg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +/* Unix headers */ +#include +#include + +/* VMS specific headers */ +#include +#include +#include + +#pragma member_alignment save +#pragma nomember_alignment longword +#pragma message save +#pragma message disable misalgndmem +struct itmlst_3 { + unsigned short int buflen; + unsigned short int itmcode; + void *bufadr; + unsigned short int *retlen; +}; +#pragma message restore +#pragma member_alignment restore + +#ifdef __VAX +#define ENABLE "ENABLE" +#define DISABLE "DISABLE" +#else + +#define ENABLE TRUE +#define DISABLE 0 +int decc$feature_get_index (const char *name); +int decc$feature_set_value (int index, int mode, int value); +#endif + +int SYS$TRNLNM( + const unsigned long * attr, + const struct dsc$descriptor_s * table_dsc, + struct dsc$descriptor_s * name_dsc, + const unsigned char * acmode, + const struct itmlst_3 * item_list); +int SYS$CRELNM( + const unsigned long * attr, + const struct dsc$descriptor_s * table_dsc, + const struct dsc$descriptor_s * name_dsc, + const unsigned char * acmode, + const struct itmlst_3 * item_list); + + +/* Take all the fun out of simply looking up a logical name */ +static int sys_trnlnm + (const char * logname, + char * value, + int value_len) +{ + const $DESCRIPTOR(table_dsc, "LNM$FILE_DEV"); + const unsigned long attr = LNM$M_CASE_BLIND; + struct dsc$descriptor_s name_dsc; + int status; + unsigned short result; + struct itmlst_3 itlst[2]; + + itlst[0].buflen = value_len; + itlst[0].itmcode = LNM$_STRING; + itlst[0].bufadr = value; + itlst[0].retlen = &result; + + itlst[1].buflen = 0; + itlst[1].itmcode = 0; + + name_dsc.dsc$w_length = strlen(logname); + name_dsc.dsc$a_pointer = (char *)logname; + name_dsc.dsc$b_dtype = DSC$K_DTYPE_T; + name_dsc.dsc$b_class = DSC$K_CLASS_S; + + status = SYS$TRNLNM(&attr, &table_dsc, &name_dsc, 0, itlst); + + if($VMS_STATUS_SUCCESS(status)) { + + /* Null terminate and return the string */ + /*--------------------------------------*/ + value[result] = '\0'; + } + + return status; +} + +/* How to simply create a logical name */ +static int sys_crelnm + (const char * logname, + const char * value) +{ + int ret_val; + const char * proc_table = "LNM$PROCESS_TABLE"; + struct dsc$descriptor_s proc_table_dsc; + struct dsc$descriptor_s logname_dsc; + struct itmlst_3 item_list[2]; + + proc_table_dsc.dsc$a_pointer = (char *) proc_table; + proc_table_dsc.dsc$w_length = strlen(proc_table); + proc_table_dsc.dsc$b_dtype = DSC$K_DTYPE_T; + proc_table_dsc.dsc$b_class = DSC$K_CLASS_S; + + logname_dsc.dsc$a_pointer = (char *) logname; + logname_dsc.dsc$w_length = strlen(logname); + logname_dsc.dsc$b_dtype = DSC$K_DTYPE_T; + logname_dsc.dsc$b_class = DSC$K_CLASS_S; + + item_list[0].buflen = strlen(value); + item_list[0].itmcode = LNM$_STRING; + item_list[0].bufadr = (char *)value; + item_list[0].retlen = NULL; + + item_list[1].buflen = 0; + item_list[1].itmcode = 0; + + ret_val = SYS$CRELNM(NULL, &proc_table_dsc, &logname_dsc, NULL, item_list); + + return ret_val; +} + + + /* Start of DECC RTL Feature handling */ + +/* +** Sets default value for a feature +*/ +#ifdef __VAX +static void set_feature_default(const char *name, const char *value) +{ + sys_crelnm(name, value); +} +#else +static void set_feature_default(const char *name, int value) +{ + int index; + + index = decc$feature_get_index(name); + + if(index > 0) + decc$feature_set_value (index, 0, value); +} +#endif + +static void set_features(void) +{ + int status; + char unix_shell_name[255]; + int use_unix_settings = 1; + + status = sys_trnlnm("GNV$UNIX_SHELL", + unix_shell_name, sizeof unix_shell_name -1); + if(!$VMS_STATUS_SUCCESS(status)) { + use_unix_settings = 0; + } + + /* ACCESS should check ACLs or it is lying. */ + set_feature_default("DECC$ACL_ACCESS_CHECK", ENABLE); + + /* We always want the new parse style */ + set_feature_default ("DECC$ARGV_PARSE_STYLE" , ENABLE); + + + /* Unless we are in POSIX compliant mode, we want the old POSIX root + * enabled. + */ + set_feature_default("DECC$DISABLE_POSIX_ROOT", DISABLE); + + /* EFS charset, means UTF-8 support */ + /* VTF-7 support is controlled by a feature setting called UTF8 */ + set_feature_default ("DECC$EFS_CHARSET", ENABLE); + set_feature_default ("DECC$EFS_CASE_PRESERVE", ENABLE); + + /* Support timestamps when available */ + set_feature_default ("DECC$EFS_FILE_TIMESTAMPS", ENABLE); + + /* Cache environment variables - performance improvements */ + set_feature_default ("DECC$ENABLE_GETENV_CACHE", ENABLE); + + /* Start out with new file attribute inheritance */ +#ifdef __VAX + set_feature_default ("DECC$EXEC_FILEATTR_INHERITANCE", "2"); +#else + set_feature_default ("DECC$EXEC_FILEATTR_INHERITANCE", 2); +#endif + + /* Don't display trailing dot after files without type */ + set_feature_default ("DECC$READDIR_DROPDOTNOTYPE", ENABLE); + + /* For standard output channels buffer output until terminator */ + /* Gets rid of output logs with single character lines in them. */ + set_feature_default ("DECC$STDIO_CTX_EOL", ENABLE); + + /* Fix mv aa.bb aa */ + set_feature_default ("DECC$RENAME_NO_INHERIT", ENABLE); + + if(use_unix_settings) { + + /* POSIX requires that open files be able to be removed */ + set_feature_default ("DECC$ALLOW_REMOVE_OPEN_FILES", ENABLE); + + /* Default to outputting Unix filenames in VMS routines */ + set_feature_default ("DECC$FILENAME_UNIX_ONLY", ENABLE); + /* FILENAME_UNIX_ONLY Implicitly sets */ + /* decc$disable_to_vms_logname_translation */ + + set_feature_default ("DECC$FILE_PERMISSION_UNIX", ENABLE); + + set_feature_default ("DECC$FILE_SHARING", ENABLE); + + set_feature_default ("DECC$FILE_OWNER_UNIX", ENABLE); + set_feature_default ("DECC$POSIX_SEEK_STREAM_FILE", ENABLE); + + } else { + set_feature_default("DECC$FILENAME_UNIX_REPORT", ENABLE); + } + + /* When reporting Unix filenames, glob the same way */ + set_feature_default ("DECC$GLOB_UNIX_STYLE", ENABLE); + + /* The VMS version numbers on Unix filenames is incompatible with most */ + /* ported packages. */ + set_feature_default("DECC$FILENAME_UNIX_NO_VERSION", ENABLE); + + /* The VMS version numbers on Unix filenames is incompatible with most */ + /* ported packages. */ + set_feature_default("DECC$UNIX_PATH_BEFORE_LOGNAME", ENABLE); + + /* Set strtol to proper behavior */ + set_feature_default("DECC$STRTOL_ERANGE", ENABLE); + + /* Commented here to prevent future bugs: A program or user should */ + /* never ever enable DECC$POSIX_STYLE_UID. */ + /* It will probably break all code that accesses UIDs */ + /* do_not_set_default ("DECC$POSIX_STYLE_UID", TRUE); */ +} + + +/* Some boilerplate to force this to be a proper LIB$INITIALIZE section */ + +#pragma nostandard +#pragma extern_model save +#ifdef __VAX +#pragma extern_model strict_refdef "LIB$INITIALIZE" nowrt, long, nopic +#else +#pragma extern_model strict_refdef "LIB$INITIALIZE" nowrt, long +# if __INITIAL_POINTER_SIZE +# pragma __pointer_size __save +# pragma __pointer_size 32 +# else +# pragma __required_pointer_size __save +# pragma __required_pointer_size 32 +# endif +#endif +/* Set our contribution to the LIB$INITIALIZE array */ +void (* const iniarray[])(void) = {set_features, } ; +#ifndef __VAX +# if __INITIAL_POINTER_SIZE +# pragma __pointer_size __restore +# else +# pragma __required_pointer_size __restore +# endif +#endif + + +/* +** Force a reference to LIB$INITIALIZE to ensure it +** exists in the image. +*/ +int LIB$INITIALIZE(void); +#ifdef __DECC +#pragma extern_model strict_refdef +#endif + int lib_init_ref = (int) LIB$INITIALIZE; +#ifdef __DECC +#pragma extern_model restore +#pragma standard +#endif diff --git a/third_party/curl/packages/vms/curl_gnv_build_steps.txt b/third_party/curl/packages/vms/curl_gnv_build_steps.txt new file mode 100644 index 0000000..b7ea952 --- /dev/null +++ b/third_party/curl/packages/vms/curl_gnv_build_steps.txt @@ -0,0 +1,290 @@ +From File: curl_gnv_build_steps.txt + + Copyright (C) John Malmberg + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + SPDX-License-Identifier: ISC + +Currently building Curl using GNV takes longer than building Curl via DCL. +The GNV procedure actually uses the same configure and makefiles that +Unix builds use. + +Building CURL on OpenVMS using GNV requires GNV V2.1-2 or the updated +images that are available via anonymous FTP at encompasserve.org in the gnv +directory. It also requires the GNV Bash 4.2.45 kit as an update from the +same location or from the sourceforge.net GNV project. + +The HP C 7.x compiler was used for building the GNV version. + +The source kits are provided in backup savesets inside of the PCSI install kit. + +Backup save sets are currently the only distribution medium that I can be +sure is installed on a target VMS system that will correctly unpack files +with extended character sets in them. You may need to adjust the ownership +of the restored files, since /Interchange/noconvert was not available at the +time that this document was written. + +[gnv.common_src]curl_*_original_src.bck is the original source of the curl kit +as provided by the curl project. [gnv.vms_src]curl-*_vms_src.bck, if present, +has the OpenVMS specific files that are used for building that are not yet in +the curl source kits for that release distributed https://curl.se + +These backup savesets should be restored to different directory trees on +an ODS-5 volume(s) which are referenced by concealed rooted logical names. + +SRC_ROOT: is for the source files common to all platforms. +VMS_ROOT: is for the source files that are specific to OpenVMS. + Note, you should create the VMS_ROOT: directory tree even if it is + initially empty. This is where you should put edits if you are + making changes. +LCL_ROOT: is manually created to have the same base and sub-directories as + SRC_ROOT: and VMS_ROOT: + +The logical name REF_ROOT: may be defined to be a search list for +VMS_ROOT:,SRC_ROOT: + +The logical name PRJ_ROOT: is defined to be a search list for +LCL_ROOT:,VMS_ROOT:,SRC_ROOT: + +For the make install process to work, it must have write access to the +directories referenced by the GNU: logical name. + +In future releases of GNV, and with GNV Bash 4.3.30 installed, this name +should be GNV$GNU: + +As directly updating those directories would probably be disruptive to other +users of the system and require elevated privilege, this can be handled by +creating a separate directory tree to install into which can be referenced +by the concealed rooted logical name new_gnu:. A concealed logical name of +OLD_GNU: can be set up to reference the real GNV directory tree. + +Then a local copy of the GNU/GNV$GNU logical names can be set up as a search +list such as NEW_GNU:,OLD_GNU: + +The directory NEW_GNU:[usr] should be created. The make install phase should +create all the other directories. + +The make install process may abort if curl is already because it can not +uninstall the older version of curl because it does not have permission. + +The file stage_curl_install.com is used set up a new_gnu: directory tree +for testing. The PCSI kitting procedure uses these files as input. + +These files do not create the directories in the VMS_ROOT and LCL_ROOT +directory trees. You can create them with commands similar to: + + $ create/dir lcl_root:[curl]/prot=w:re + $ copy src_root:[curl...]*.dir - + lcl_root:[curl...]/prot=(o:rwed,w:re) + $ create/dir vms_root:[curl]/prot=w:re + $ copy src_root:[curl...]*.dir - + vms_root:[curl...]/prot=(o:rwed,w:re) + +One of the ways with to protect the source from being modified is to have +the directories under src_root: owned by a user or resource where the build +username only has read access to it. + + +Note to builders: + +GNV currently has a bug where configure scripts take a long time to run. +Some of the configure steps take a while to complete, and on a 600 Mhz +DS10 with IDE disks, taking an hour to run the CURL configure is normal. + +The following messages can be ignored and may get fixed in a future version +of GNV. The GNV$*.OPT files are used to find the libraries as many have +different names on VMS than on Unix. The Bash environment variable +GNV_CC_QUALIFIERS can override all other settings for the C Compiler. + +? cc: No support for switch -warnprotos +? cc: Unrecognized file toomanyargs +? cc: Warning: library "ssl" not found +? cc: Warning: library "crypto" not found +? cc: Warning: library "gssapi" not found +? cc: Warning: library "z" not found +u unimplemented switch - ignored + + +With these search lists set up and the properly, curl can be built by +setting your default to PRJ_ROOT:[curl.packages.vms] and then issuing +either the command: + + $ @pcsi_product_gnv_curl.com + +or + + $ @build_gnv_curl.com. + +The GNV configure procedure takes considerably longer than the DCL build +procedure takes. It is of use for testing the GNV build environment, and +may not have been kept up to date. + +The pcsi_product_gnv_curl.com needs the following logical names which +are described in the section below: + + gnv_pcsi_producer + gnv_pcsi_producer_full_name + stage_root + vms_root1 (Optional if vms_root is on a NFS volume) + src_root1 (Optional if src_root is on a NFS volume) + +The pcsi_product_gnv_curl.com is described in more detail below. It does +the following steps. The build steps are only done if they are needed to +allow using either DCL or GNV based building procedures. + + $ @build_vms list + + $ @gnv_link_curl.com + + $ @build_gnv_curl_release_notes.com + + $ @backup_gnv_curl_src.com + + $ @build_gnv_curl_pcsi_desc.com + + $ @build_gnv_curl_pcsi_text.com + + $ @stage_curl_install remove + $ @stage_curl_install + + Then builds the kit. + +The build_gnv_curl.com command procedure does the following: + + $ @setup_gnv_curl_build.com + + $ bash gnv_curl_configure.sh + + $ @clean_gnv_curl.com + + $ bash make_gnv_curl_install.sh + + $ @gnv_link_curl.com + + $ @stage_curl_install.com + + $ purge new_gnu:[*...]/log + +To clean up after a GNV based build to start over, the following commands are +used: + + $ bash + bash$ cd ../.. + bash$ make clean + bash$ exit + +Then run the @clean_gnv_curl.com. Use the parameter "realclean" if you are +going to run the setup_gnv_curl_build.com and configure script again. + + $ @clean_gnv_curl.com realclean + +If new public symbols have been added, adjust the file gnv_libcurl_symbols.opt +to have the new symbols. If the symbols are longer than 32 characters, +then they will need to have the original be exact case CRC shortened and +an alias in upper case with CRC shortened, in addition to having an exact +case truncated alias and an uppercase truncated alias. + +The *.EXE files are not moved to the new_gnu: directory. + +After you are satisfied with the results of your build, you can move the +files from new_gnu: to old_gnu: at your convenience. + +Building a PCSI kit for an architecture takes the following steps after +making sure that you have a working build environment. + +Note that it requires manually creating two logical names as described +below. It is intentional that they be manually set. This is for +branding the PCSI kit based on who is making the kit. + + 1. Make sure that you have a staging directory that can be referenced + by the path STAGE_ROOT:[KIT] + + 2. Edit the file curl_release_note_start.txt or other text files to + reflect any changes. + + 3. Define the logical name GNV_PCSI_PRODUCER to indicate who is making + the distribution. For making updates to an existing open source + kit you may need to keep the producer the same. + + 4. Define the logical name GNV_PCSI_PRODUCER_FULL_NAME to be your full + name or full name of your company. + + 5. If you are producing an update kit, then update the file + vms_eco_level.h by changing the value for the VMS_ECO_LEVEL macro. + This file is currently only used in building the PCSI kit. + + 6. Edit the file PCSI_GNV_CURL_FILE_LIST.TXT if there are new files added + to the kit. These files should all be ODS-2 legal filenames and + directories. + + A limitation of the PCSI kitting procedure is that when selecting files, + it tends to ignore the directory structure and assumes that all files + with the same name are the same file, so every file placed in the kit + must have a unique name. Then a procedure needs to be added to the kit + to create an alias link on install and remove the link on remove. + + Since at this time curl does not need this alias procedure, the steps + to automatically build it are not included here. + + While newer versions of PCSI can support ODS-5 filenames, not all versions + of PCSI on systems that have ODS-5 filenames do. So as a post install + step, the PCSI kit built by these steps does a rename to the correct + case as a post install step. + + 7. Edit the build_curl_pcsi_desc.com and build_curl_pcsi_text.com if you + have changed the version of ZLIB that curl is built against. + + 8. Prepare to backup the files for building the kit. + + Note that if src_root: or vms_root: are NFS mounted disks, the + step of backing up the source files will probably hang or fail. + + You need to copy the source files to VMS mounted disks and create + logical names SRC_ROOT1 and VMS_ROOT1 to work around this to + reference local disks. Make sure src_root1:[000000] and + vms_root1:[000000] exist and can be written to. + + The command procedure compare_curl_source can be used to check + those directories and keep them up to date. + + @compare_curl_source.com SRCBCK UPDATE + + This compares the reference project source with the backup + staging directory for it and updates with any changes. + + @compare_curl_source.com VMSBCK UPDATE + + This compares the VMS specific source with the backup + staging directory for it and updates with any changes. + + Leave off "UPDATE" to just check without doing any changes. + + If you are not using NFS mounted disks and do not want to have a + separate directory for staging the sources for backup make sure + that src_root1: and vms_root1: do not exist. + + 9. Build the PCSI kit with @pcsi_product_gnv_curl.com + + The following message is normal: + %PCSI-I-CANNOTVAL, cannot validate + EAGLE$DQA0:[stage_root.][kit]VMSPORTS-AXPVMS-CURL-V0731-0-1.PCSI;1 + -PCSI-I-NOTSIGNED, product kit is not signed and therefore has + no manifest file + + This will result in an uncompressed kit for the target platform. + On Alpha and Integrity, the pcsi_product_gnv_curl.com can be used with + the "COMPRESSED" parameter to build both a compressed and uncompressed + kits. + +Good Luck. diff --git a/third_party/curl/packages/vms/curl_release_note_start.txt b/third_party/curl/packages/vms/curl_release_note_start.txt new file mode 100644 index 0000000..62b2836 --- /dev/null +++ b/third_party/curl/packages/vms/curl_release_note_start.txt @@ -0,0 +1,77 @@ +From file: CURL_RELEASE_NOTE_START.TXT + +Note: These kits are produced by a hobbyist and are providing any support +or any commitment to supply bug fixes or future releases. This code is +as-is with no warranties. + +The testing of this build of curl was minimal and involved building some of +the sample and test programs, accessing a public HTTPS: website, doing a +form post of some VMS test files, and FTP upload of some text files. + +Due to the way that PCSI identifies packages, if you install a package from +one producer and then want to upgrade it from another producer, you will +probably need to uninstall the previous package first. + +OpenVMS specific building and kitting instructions are after the standard +curl readme file. + +This product may be available for your platform in a PCSI kit. The source kit +contains files for building CURL using GNV or with a DCL procedure. + +The GNV based build creates a libcurl share imaged which is supplied in the +PCSI kit. + +This version of CURL will return VMS compatible status codes when run from +DCL and Unix compatible exit codes and messages when run with the SHELL +environment variable set. + +This port of Curl uses the OpenSSL, Ldap, and Kerberos V5 that are bundled +with OpenVMS or supplied as updates by HP. Ldap and Kerberos are not available +on the VAX platform. See section below for a special note about HP OpenSSL +on Alpha and IA64. + +The supplied CURL_STARTUP.COM procedure that is installed in +[VMS$COMMON.SYS$STARTUP] can be put in your VMS startup procedure to install +the GNV$LIBCURL shared image and create logical names GNV$LIBCURL to reference +it. It will create the GNV$CURL_INCLUDE logical name for build procedures +to access the header files. + +Normally to use curl from DCL, just create a foreign command as: + curl :== $gnv$gnu:[usr.bin]gnv$curl.exe + +If you need to work around having the older HP SSL kit installed, then +for DCL create this command procedure: + + $ create/dir gnv$gnu:[vms_bin]/prot=w:re + $ create gnv$gnu:[vms_bin]curl.com + $ curl := $gnv$gnu:[usr.bin]gnv$curl.exe + $ define/user ssl$libcrypto_shr32 gnv$curl_ssl_libcryptoshr32 + $ curl "''p1'" "''p2'" "''p3'" "''p4'" "''p5'" "''p6'" "''p7'" "''p8'" + ^Z + +Then you can use: curl :== @gnv$gnu:[vms_bin]curl.com to run curl. + +For the HP SSL work around to work for GNV do the following: + $ create/dir gnv$gnu:[usr.local.bin]/prot=w:re + $ create gnv$gnu:[usr.local.bin]curl. + #! /bin/sh + dcl @gnv\$gnu:[vms_bin]curl.com $* + ^Z + +Similar workarounds will be needed for any program linked with GNV$LIBCURL +until the HP OpenSSL is upgraded to the current 1.4 version or later. + +If you are installing a "daily" build instead of a release build of Curl, some +things have been changed so that it can be installed at the same time as +a production build without conflicts. + + The CURL_DAILY_STARTUP.COM will be supplied instead of CURL_STARTUP.COM. + This file is actually not used with the daily package and is provided as + a preview of what the next CURL_STARTUP.COM will be for the next release. + Do not run it. + + The files that are normally installed in [VMS$COMMON.GNV.usr], for the + daily build are installed in [VMS$COMMON.GNV.beta] directory. + + To use the daily GNV$LIBCURL image, you will need to define the logical + name GNV$LIBCURL to the image. diff --git a/third_party/curl/packages/vms/curl_startup.com b/third_party/curl/packages/vms/curl_startup.com new file mode 100644 index 0000000..e90bbec --- /dev/null +++ b/third_party/curl/packages/vms/curl_startup.com @@ -0,0 +1,98 @@ +$! File: curl_Startup.com +$! +$! Procedure to setup the CURL libraries for use by programs from the +$! VMS SYSTARTUP*.COM procedure. +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!======================================================================== +$! +$! +$! GNV$GNU if needed. +$ if f$trnlnm("GNV$GNU") .eqs. "" +$ then +$ x = f$trnlnm("GNU","LNM$SYSTEM_TABLE") +$ if x .eqs. "" +$ then +$ write sys$output "GNV must be started up before this procedure. +$ exit 44 +$ endif +$ define/system/exec/trans=conc GNV$GNU 'x' +$ endif +$! +$! +$ myproc = f$environment("procedure") +$! +$! ZLIB needed. +$ if f$trnlnm("GNV$LIBZSHR32") .eqs. "" +$ then +$ zlib_startup = f$parse("gnv$zlib_startup.com;0", myproc,,,) +$ if f$search(zlib_startup) .nes. "" +$ then +$ @'zlib_startup +$ else +$ write sys$output "ZLIB package not found and is required." +$ exit 44 +$ endif +$ endif +$! +$! +$ curl_ssl_libcrypto32 = "" +$ curl_ssl_libssl32 = "" +$ gnv_ssl_libcrypto32 = "gnv$gnu:[lib]ssl$libcrypto_shr32.exe" +$ gnv_ssl_libssl32 = "gnv$gnu:[lib]ssl$libssl_shr32.exe" +$ if f$search(gnv_ssl_libcrypto32) .nes. "" +$ then +$ curl_ssl_libcrypto32 = gnv_ssl_libcrypto32 +$ curl_ssl_libssl32 = gnv_ssl_libssl32 +$ else +$ hp_ssl_libcrypto32 = "sys$share:ssl$libcrypto_shr32.exe" +$ hp_ssl_libssl32 = "sys$share:ssl$libssl_shr32.exe" +$ if f$search(hp_ssl_libcrypto32) .nes. "" +$ then +$ curl_ssl_libcrypto32 = hp_ssl_libcrypto32 +$ curl_ssl_libssl32 = hp_ssl_libssl32 +$ else +$ write sys$output "HP SSL package not found and is required." +$ endif +$ endif +$! +$ define/system/exec gnv$curl_ssl_libcryptoshr32 'curl_ssl_libcrypto32' +$ define/system/exec gnv$curl_ssl_libsslshr32 'curl_ssl_libssl32' +$! +$! +$! CURL setup +$ define/system/exec gnv$libcurl gnv$gnu:[usr.lib]GNV$LIBCURL.EXE +$ define/system/exec gnv$curl_include gnv$gnu:[usr.include.curl] +$ if .not. f$file_attributes("gnv$libcurl", "known") +$ then +$ install ADD gnv$libcurl/OPEN/SHARE/HEADER +$ else +$ install REPLACE gnv$libcurl/OPEN/SHARE/HEADER +$ endif +$! +$! +$ curl_exe = "gnv$gnu:[usr.bin]gnv$curl.exe" +$ if .not. f$file_attributes(curl_exe, "known") +$ then +$ install ADD 'curl_exe'/OPEN/SHARE/HEADER +$ else +$ install REPLACE 'curl_exe'/OPEN/SHARE/HEADER +$ endif +$! +$all_exit: +$ exit diff --git a/third_party/curl/packages/vms/curlmsg.h b/third_party/curl/packages/vms/curlmsg.h new file mode 100644 index 0000000..9b5c4c7 --- /dev/null +++ b/third_party/curl/packages/vms/curlmsg.h @@ -0,0 +1,143 @@ +#ifndef HEADER_CURLMSG_H +#define HEADER_CURLMSG_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#pragma __member_alignment __save +#pragma __nomember_alignment + +/* */ +/* CURLMSG.H */ +/* */ +/* SDL File Generated by VAX-11 Message V04-00 on 3-SEP-2008 13:33:54.09 */ +/* */ +/* THESE VMS ERROR CODES ARE GENERATED BY TAKING APART THE CURL.H */ +/* FILE AND PUTTING ALL THE CURLE_* ENUM STUFF INTO THIS FILE, */ +/* CURLMSG.MSG. AN .SDL FILE IS CREATED FROM THIS FILE WITH */ +/* MESSAGE/SDL. THE .H FILE IS CREATED USING THE FREEWARE SDL TOOL */ +/* AGAINST THE .SDL FILE WITH SDL/ALPHA/LANG=CC COMMAND. */ +/* */ +/* WITH THE EXCEPTION OF CURLE_OK, ALL OF THE MESSAGES ARE AT */ +/* THE ERROR SEVERITY LEVEL. WITH THE EXCEPTION OF */ +/* PEER_FAILED_VERIF, WHICH IS A SHORTENED FORM OF */ +/* PEER_FAILED_VERIFICATION, THESE ARE THE SAME NAMES AS THE */ +/* CURLE_ ONES IN INCLUDE/CURL.H. THE MESSAGE UTILITY MANUAL STATES */ +/* "THE COMBINED LENGTH OF THE PREFIX AND THE MESSAGE SYMBOL NAME CANNOT */ +/* EXCEED 31 CHARACTERS." WITH A PREFIX OF FIVE THAT LEAVES US WITH 26 */ +/* FOR THE MESSAGE NAME. */ +/* */ +/* IF YOU UPDATE THIS FILE, UPDATE CURLMSG_VMS.H SO THAT THEY ARE IN SYNC */ +/* */ + +#define CURL_FACILITY 3841 +#define CURL_OK 251756553 +#define CURL_UNSUPPORTED_PROTOCOL 251756562 +#define CURL_FAILED_INIT 251756570 +#define CURL_URL_MALFORMAT 251756578 +#define CURL_OBSOLETE4 251756586 +#define CURL_COULDNT_RESOLVE_PROXY 251756594 +#define CURL_COULDNT_RESOLVE_HOST 251756602 +#define CURL_COULDNT_CONNECT 251756610 +#define CURL_WEIRD_SERVER_REPLY 251756618 +#define CURL_FTP_WEIRD_SERVER_REPLY CURL_WEIRD_SERVER_REPLY +#define CURL_FTP_ACCESS_DENIED 251756626 +#define CURL_OBSOLETE10 251756634 +#define CURL_FTP_WEIRD_PASS_REPLY 251756642 +#define CURL_OBSOLETE12 251756650 +#define CURL_FTP_WEIRD_PASV_REPLY 251756658 +#define CURL_FTP_WEIRD_227_FORMAT 251756666 +#define CURL_FTP_CANT_GET_HOST 251756674 +#define CURL_OBSOLETE16 251756682 +#define CURL_FTP_COULDNT_SET_TYPE 251756690 +#define CURL_PARTIAL_FILE 251756698 +#define CURL_FTP_COULDNT_RETR_FILE 251756706 +#define CURL_OBSOLETE20 251756714 +#define CURL_QUOTE_ERROR 251756722 +#define CURL_HTTP_RETURNED_ERROR 251756730 +#define CURL_WRITE_ERROR 251756738 +#define CURL_OBSOLETE24 251756746 +#define CURL_UPLOAD_FAILED 251756754 +#define CURL_READ_ERROR 251756762 +#define CURL_OUT_OF_MEMORY 251756770 +#define CURL_OPERATION_TIMEOUTED 251756778 +#define CURL_OBSOLETE29 251756786 +#define CURL_FTP_PORT_FAILED 251756794 +#define CURL_FTP_COULDNT_USE_REST 251756802 +#define CURL_OBSOLETE32 251756810 +#define CURL_RANGE_ERROR 251756818 +#define CURL_HTTP_POST_ERROR 251756826 +#define CURL_SSL_CONNECT_ERROR 251756834 +#define CURL_BAD_DOWNLOAD_RESUME 251756842 +#define CURL_FILE_COULDNT_READ_FILE 251756850 +#define CURL_LDAP_CANNOT_BIND 251756858 +#define CURL_LDAP_SEARCH_FAILED 251756866 +#define CURL_OBSOLETE40 251756874 +#define CURL_FUNCTION_NOT_FOUND 251756882 +#define CURL_ABORTED_BY_CALLBACK 251756890 +#define CURL_BAD_FUNCTION_ARGUMENT 251756898 +#define CURL_OBSOLETE44 251756906 +#define CURL_INTERFACE_FAILED 251756914 +#define CURL_OBSOLETE46 251756922 +#define CURL_TOO_MANY_REDIRECTS 251756930 +#define CURL_UNKNOWN_TELNET_OPTION 251756938 +#define CURL_TELNET_OPTION_SYNTAX 251756946 +#define CURL_OBSOLETE50 251756954 +#define CURL_PEER_FAILED_VERIF 251756962 +#define CURL_GOT_NOTHING 251756970 +#define CURL_SSL_ENGINE_NOTFOUND 251756978 +#define CURL_SSL_ENGINE_SETFAILED 251756986 +#define CURL_SEND_ERROR 251756994 +#define CURL_RECV_ERROR 251757002 +#define CURL_OBSOLETE57 251757010 +#define CURL_SSL_CERTPROBLEM 251757018 +#define CURL_SSL_CIPHER 251757026 +#define CURL_SSL_CACERT 251757034 +#define CURL_BAD_CONTENT_ENCODING 251757042 +#define CURL_LDAP_INVALID_URL 251757050 +#define CURL_FILESIZE_EXCEEDED 251757058 +#define CURL_USE_SSL_FAILED 251757066 +#define CURL_SEND_FAIL_REWIND 251757074 +#define CURL_SSL_ENGINE_INITFAILED 251757082 +#define CURL_LOGIN_DENIED 251757090 +#define CURL_TFTP_NOTFOUND 251757098 +#define CURL_TFTP_PERM 251757106 +#define CURL_REMOTE_DISK_FULL 251757114 +#define CURL_TFTP_ILLEGAL 251757122 +#define CURL_TFTP_UNKNOWNID 251757130 +#define CURL_REMOTE_FILE_EXISTS 251757138 +#define CURL_TFTP_NOSUCHUSER 251757146 +#define CURL_CONV_FAILED 251757154 +#define CURL_CONV_REQD 251757162 +#define CURL_SSL_CACERT_BADFILE 251757170 +#define CURL_REMOTE_FILE_NOT_FOUND 251757178 +#define CURL_SSH 251757186 +#define CURL_SSL_SHUTDOWN_FAILED 251757194 +#define CURL_AGAIN 251757202 +#define CURL_SSL_CRL_BADFILE 251757210 +#define CURL_SSL_ISSUER_ERROR 251757218 +#define CURL_CURL_LAST 251757226 + +#pragma __member_alignment __restore + +#endif /* HEADER_CURLMSG_H */ diff --git a/third_party/curl/packages/vms/curlmsg.msg b/third_party/curl/packages/vms/curlmsg.msg new file mode 100644 index 0000000..ac2d508 --- /dev/null +++ b/third_party/curl/packages/vms/curlmsg.msg @@ -0,0 +1,134 @@ +!*************************************************************************** +! _ _ ____ _ +! Project ___| | | | _ \| | +! / __| | | | |_) | | +! | (__| |_| | _ <| |___ +! \___|\___/|_| \_\_____| +! +! Copyright (C) Daniel Stenberg, , 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. +! +! SPDX-License-Identifier: curl +! +!########################################################################## +! +! These VMS error codes are generated by taking apart the curl.h +! file and putting all the CURLE_* enum stuff into this file, +! CURLMSG.MSG. An .SDL file is created from this file with +! MESSAGE/SDL. The .H file is created using the freeware SDL tool +! against the .SDL file with SDL/ALPHA/LANG=CC command. +! +! With the exception of CURLE_OK, all of the messages are at +! the error severity level. With the exception of +! PEER_FAILED_VERIF, which is a shortened form of +! PEER_FAILED_VERIFICATION, these are the same names as the +! CURLE_ ones in include/curl.h. The Message Utility manual states +! "The combined length of the prefix and the message symbol name cannot +! exceed 31 characters." With a prefix of five that leaves us with 26 +! for the message name. +! +! If you update this file also update curlmsg_vms.h so that they are in sync +! +.TITLE CURLMSG Message files +.FACILITY CURL,1793 /PREFIX=CURL_ +.BASE 1 +.SEVERITY SUCCESS +OK + +.SEVERITY ERROR +UNSUPPORTED_PROTOCOL +FAILED_INIT +URL_MALFORMAT +OBSOLETE4 +COULDNT_RESOLVE_PROXY +COULDNT_RESOLVE_HOST +COULDNT_CONNECT +WEIRD_SERVER_REPLY +FTP_ACCESS_DENIED +OBSOLETE10 +FTP_WEIRD_PASS_REPLY +OBSOLETE12 +FTP_WEIRD_PASV_REPLY +FTP_WEIRD_227_FORMAT +FTP_CANT_GET_HOST +OBSOLETE16 +FTP_COULDNT_SET_TYPE +PARTIAL_FILE +FTP_COULDNT_RETR_FILE +OBSOLETE20 +QUOTE_ERROR +HTTP_RETURNED_ERROR +WRITE_ERROR +OBSOLETE24 +UPLOAD_FAILED +READ_ERROR +OUT_OF_MEMORY +OPERATION_TIMEOUTED +OBSOLETE29 +FTP_PORT_FAILED +FTP_COULDNT_USE_REST +OBSOLETE32 +RANGE_ERROR +HTTP_POST_ERROR +SSL_CONNECT_ERROR +BAD_DOWNLOAD_RESUME +FILE_COULDNT_READ_FILE +LDAP_CANNOT_BIND +LDAP_SEARCH_FAILED +OBSOLETE40 +FUNCTION_NOT_FOUND +ABORTED_BY_CALLBACK +BAD_FUNCTION_ARGUMENT +OBSOLETE44 +INTERFACE_FAILED +OBSOLETE46 +TOO_MANY_REDIRECTS +UNKNOWN_TELNET_OPTION +TELNET_OPTION_SYNTAX +OBSOLETE50 +PEER_FAILED_VERIF +GOT_NOTHING +SSL_ENGINE_NOTFOUND +SSL_ENGINE_SETFAILED +SEND_ERROR +RECV_ERROR +OBSOLETE57 +SSL_CERTPROBLEM +SSL_CIPHER +SSL_CACERT +BAD_CONTENT_ENCODING +LDAP_INVALID_URL +FILESIZE_EXCEEDED +USE_SSL_FAILED +SEND_FAIL_REWIND +SSL_ENGINE_INITFAILED +LOGIN_DENIED +TFTP_NOTFOUND +TFTP_PERM +REMOTE_DISK_FULL +TFTP_ILLEGAL +TFTP_UNKNOWNID +REMOTE_FILE_EXISTS +TFTP_NOSUCHUSER +CONV_FAILED +CONV_REQD +SSL_CACERT_BADFILE +REMOTE_FILE_NOT_FOUND +SSH +SSL_SHUTDOWN_FAILED +AGAIN +SSL_CRL_BADFILE +SSL_ISSUER_ERROR +CURL_LAST + +.END diff --git a/third_party/curl/packages/vms/curlmsg.sdl b/third_party/curl/packages/vms/curlmsg.sdl new file mode 100644 index 0000000..db5baad --- /dev/null +++ b/third_party/curl/packages/vms/curlmsg.sdl @@ -0,0 +1,116 @@ + + + MODULE $CURDEF; + +/* +/* This SDL File Generated by VAX-11 Message V04-00 on 3-SEP-2008 13:33:54.09 +/* +/* $ID: CURLMSG.MSG,V 1.7 2008-05-30 23:51:09 CURLVMS EXP $ +/* +/* THESE VMS ERROR CODES ARE GENERATED BY TAKING APART THE CURL.H +/* FILE AND PUTTING ALL THE CURLE_* ENUM STUFF INTO THIS FILE, +/* CURLMSG.MSG. AN .SDL FILE IS CREATED FROM THIS FILE WITH +/* MESSAGE/SDL. THE .H FILE IS CREATED USING THE FREEWARE SDL TOOL +/* AGAINST THE .SDL FILE WITH SDL/ALPHA/LANG=CC COMMAND. +/* +/* WITH THE EXCEPTION OF CURLE_OK, ALL OF THE MESSAGES ARE AT +/* THE ERROR SEVERITY LEVEL. WITH THE EXCEPTION OF +/* PEER_FAILED_VERIF, WHICH IS A SHORTENED FORM OF +/* PEER_FAILED_VERIFICATION, THESE ARE THE SAME NAMES AS THE +/* CURLE_ ONES IN INCLUDE/CURL.H. THE MESSAGE UTILITY MANUAL STATES +/* "THE COMBINED LENGTH OF THE PREFIX AND THE MESSAGE SYMBOL NAME CANNOT +/* EXCEED 31 CHARACTERS." WITH A PREFIX OF FIVE THAT LEAVES US WITH 26 +/* FOR THE MESSAGE NAME. +/* +/* IF YOU UPDATE THIS FILE ALSO UPDATE CURLMSG_VMS.H SO THAT THEY ARE IN SYNC +/* + CONSTANT + "FACILITY" EQUALS 3841 PREFIX "CURL" TAG "" + ,"OK" EQUALS %X0F018009 PREFIX "CURL" TAG "" + ,"UNSUPPORTED_PROTOCOL" EQUALS %X0F018012 PREFIX "CURL" TAG "" + ,"FAILED_INIT" EQUALS %X0F01801A PREFIX "CURL" TAG "" + ,"URL_MALFORMAT" EQUALS %X0F018022 PREFIX "CURL" TAG "" + ,"OBSOLETE4" EQUALS %X0F01802A PREFIX "CURL" TAG "" + ,"COULDNT_RESOLVE_PROXY" EQUALS %X0F018032 PREFIX "CURL" TAG "" + ,"COULDNT_RESOLVE_HOST" EQUALS %X0F01803A PREFIX "CURL" TAG "" + ,"COULDNT_CONNECT" EQUALS %X0F018042 PREFIX "CURL" TAG "" + ,"WEIRD_SERVER_REPLY" EQUALS %X0F01804A PREFIX "CURL" TAG "" + ,"FTP_WEIRD_SERVER_REPLY" EQUALS %X0F01804A PREFIX "CURL" TAG "" + ,"FTP_ACCESS_DENIED" EQUALS %X0F018052 PREFIX "CURL" TAG "" + ,"OBSOLETE10" EQUALS %X0F01805A PREFIX "CURL" TAG "" + ,"FTP_WEIRD_PASS_REPLY" EQUALS %X0F018062 PREFIX "CURL" TAG "" + ,"OBSOLETE12" EQUALS %X0F01806A PREFIX "CURL" TAG "" + ,"FTP_WEIRD_PASV_REPLY" EQUALS %X0F018072 PREFIX "CURL" TAG "" + ,"FTP_WEIRD_227_FORMAT" EQUALS %X0F01807A PREFIX "CURL" TAG "" + ,"FTP_CANT_GET_HOST" EQUALS %X0F018082 PREFIX "CURL" TAG "" + ,"OBSOLETE16" EQUALS %X0F01808A PREFIX "CURL" TAG "" + ,"FTP_COULDNT_SET_TYPE" EQUALS %X0F018092 PREFIX "CURL" TAG "" + ,"PARTIAL_FILE" EQUALS %X0F01809A PREFIX "CURL" TAG "" + ,"FTP_COULDNT_RETR_FILE" EQUALS %X0F0180A2 PREFIX "CURL" TAG "" + ,"OBSOLETE20" EQUALS %X0F0180AA PREFIX "CURL" TAG "" + ,"QUOTE_ERROR" EQUALS %X0F0180B2 PREFIX "CURL" TAG "" + ,"HTTP_RETURNED_ERROR" EQUALS %X0F0180BA PREFIX "CURL" TAG "" + ,"WRITE_ERROR" EQUALS %X0F0180C2 PREFIX "CURL" TAG "" + ,"OBSOLETE24" EQUALS %X0F0180CA PREFIX "CURL" TAG "" + ,"UPLOAD_FAILED" EQUALS %X0F0180D2 PREFIX "CURL" TAG "" + ,"READ_ERROR" EQUALS %X0F0180DA PREFIX "CURL" TAG "" + ,"OUT_OF_MEMORY" EQUALS %X0F0180E2 PREFIX "CURL" TAG "" + ,"OPERATION_TIMEOUTED" EQUALS %X0F0180EA PREFIX "CURL" TAG "" + ,"OBSOLETE29" EQUALS %X0F0180F2 PREFIX "CURL" TAG "" + ,"FTP_PORT_FAILED" EQUALS %X0F0180FA PREFIX "CURL" TAG "" + ,"FTP_COULDNT_USE_REST" EQUALS %X0F018102 PREFIX "CURL" TAG "" + ,"OBSOLETE32" EQUALS %X0F01810A PREFIX "CURL" TAG "" + ,"RANGE_ERROR" EQUALS %X0F018112 PREFIX "CURL" TAG "" + ,"HTTP_POST_ERROR" EQUALS %X0F01811A PREFIX "CURL" TAG "" + ,"SSL_CONNECT_ERROR" EQUALS %X0F018122 PREFIX "CURL" TAG "" + ,"BAD_DOWNLOAD_RESUME" EQUALS %X0F01812A PREFIX "CURL" TAG "" + ,"FILE_COULDNT_READ_FILE" EQUALS %X0F018132 PREFIX "CURL" TAG "" + ,"LDAP_CANNOT_BIND" EQUALS %X0F01813A PREFIX "CURL" TAG "" + ,"LDAP_SEARCH_FAILED" EQUALS %X0F018142 PREFIX "CURL" TAG "" + ,"OBSOLETE40" EQUALS %X0F01814A PREFIX "CURL" TAG "" + ,"FUNCTION_NOT_FOUND" EQUALS %X0F018152 PREFIX "CURL" TAG "" + ,"ABORTED_BY_CALLBACK" EQUALS %X0F01815A PREFIX "CURL" TAG "" + ,"BAD_FUNCTION_ARGUMENT" EQUALS %X0F018162 PREFIX "CURL" TAG "" + ,"OBSOLETE44" EQUALS %X0F01816A PREFIX "CURL" TAG "" + ,"INTERFACE_FAILED" EQUALS %X0F018172 PREFIX "CURL" TAG "" + ,"OBSOLETE46" EQUALS %X0F01817A PREFIX "CURL" TAG "" + ,"TOO_MANY_REDIRECTS" EQUALS %X0F018182 PREFIX "CURL" TAG "" + ,"UNKNOWN_TELNET_OPTION" EQUALS %X0F01818A PREFIX "CURL" TAG "" + ,"TELNET_OPTION_SYNTAX" EQUALS %X0F018192 PREFIX "CURL" TAG "" + ,"OBSOLETE50" EQUALS %X0F01819A PREFIX "CURL" TAG "" + ,"PEER_FAILED_VERIF" EQUALS %X0F0181A2 PREFIX "CURL" TAG "" + ,"GOT_NOTHING" EQUALS %X0F0181AA PREFIX "CURL" TAG "" + ,"SSL_ENGINE_NOTFOUND" EQUALS %X0F0181B2 PREFIX "CURL" TAG "" + ,"SSL_ENGINE_SETFAILED" EQUALS %X0F0181BA PREFIX "CURL" TAG "" + ,"SEND_ERROR" EQUALS %X0F0181C2 PREFIX "CURL" TAG "" + ,"RECV_ERROR" EQUALS %X0F0181CA PREFIX "CURL" TAG "" + ,"OBSOLETE57" EQUALS %X0F0181D2 PREFIX "CURL" TAG "" + ,"SSL_CERTPROBLEM" EQUALS %X0F0181DA PREFIX "CURL" TAG "" + ,"SSL_CIPHER" EQUALS %X0F0181E2 PREFIX "CURL" TAG "" + ,"SSL_CACERT" EQUALS %X0F0181EA PREFIX "CURL" TAG "" + ,"BAD_CONTENT_ENCODING" EQUALS %X0F0181F2 PREFIX "CURL" TAG "" + ,"LDAP_INVALID_URL" EQUALS %X0F0181FA PREFIX "CURL" TAG "" + ,"FILESIZE_EXCEEDED" EQUALS %X0F018202 PREFIX "CURL" TAG "" + ,"USE_SSL_FAILED" EQUALS %X0F01820A PREFIX "CURL" TAG "" + ,"SEND_FAIL_REWIND" EQUALS %X0F018212 PREFIX "CURL" TAG "" + ,"SSL_ENGINE_INITFAILED" EQUALS %X0F01821A PREFIX "CURL" TAG "" + ,"LOGIN_DENIED" EQUALS %X0F018222 PREFIX "CURL" TAG "" + ,"TFTP_NOTFOUND" EQUALS %X0F01822A PREFIX "CURL" TAG "" + ,"TFTP_PERM" EQUALS %X0F018232 PREFIX "CURL" TAG "" + ,"REMOTE_DISK_FULL" EQUALS %X0F01823A PREFIX "CURL" TAG "" + ,"TFTP_ILLEGAL" EQUALS %X0F018242 PREFIX "CURL" TAG "" + ,"TFTP_UNKNOWNID" EQUALS %X0F01824A PREFIX "CURL" TAG "" + ,"REMOTE_FILE_EXISTS" EQUALS %X0F018252 PREFIX "CURL" TAG "" + ,"TFTP_NOSUCHUSER" EQUALS %X0F01825A PREFIX "CURL" TAG "" + ,"CONV_FAILED" EQUALS %X0F018262 PREFIX "CURL" TAG "" + ,"CONV_REQD" EQUALS %X0F01826A PREFIX "CURL" TAG "" + ,"SSL_CACERT_BADFILE" EQUALS %X0F018272 PREFIX "CURL" TAG "" + ,"REMOTE_FILE_NOT_FOUND" EQUALS %X0F01827A PREFIX "CURL" TAG "" + ,"SSH" EQUALS %X0F018282 PREFIX "CURL" TAG "" + ,"SSL_SHUTDOWN_FAILED" EQUALS %X0F01828A PREFIX "CURL" TAG "" + ,"AGAIN" EQUALS %X0F018292 PREFIX "CURL" TAG "" + ,"SSL_CRL_BADFILE" EQUALS %X0F01829A PREFIX "CURL" TAG "" + ,"SSL_ISSUER_ERROR" EQUALS %X0F0182A2 PREFIX "CURL" TAG "" + ,"CURL_LAST" EQUALS %X0F0182AA PREFIX "CURL" TAG "" + ; + END_MODULE; diff --git a/third_party/curl/packages/vms/curlmsg_vms.h b/third_party/curl/packages/vms/curlmsg_vms.h new file mode 100644 index 0000000..bb64702 --- /dev/null +++ b/third_party/curl/packages/vms/curlmsg_vms.h @@ -0,0 +1,143 @@ +#ifndef HEADER_CURLMSG_VMS_H +#define HEADER_CURLMSG_VMS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* */ +/* CURLMSG_VMS.H */ +/* */ +/* This defines the necessary bits to change CURLE_* error codes to VMS */ +/* style error codes. CURLMSG.H is built from CURLMSG.SDL which is built */ +/* from CURLMSG.MSG. The vms_cond array is used to return VMS errors by */ +/* putting the VMS error codes into the array offset based on CURLE_* code. */ +/* */ +/* If you update CURLMSG.MSG make sure to update this file to match. */ +/* */ + +#include "curlmsg.h" + +/* +#define FAC_CURL 0xC01 +#define FAC_SYSTEM 0 +#define MSG_NORMAL 0 +*/ + +/* +#define SEV_WARNING 0 +#define SEV_SUCCESS 1 +#define SEV_ERROR 2 +#define SEV_INFO 3 +#define SEV_FATAL 4 +*/ + +static const long vms_cond[] = + { + CURL_OK, + CURL_UNSUPPORTED_PROTOCOL, + CURL_FAILED_INIT, + CURL_URL_MALFORMAT, + CURL_OBSOLETE4, + CURL_COULDNT_RESOLVE_PROXY, + CURL_COULDNT_RESOLVE_HOST, + CURL_COULDNT_CONNECT, + CURL_WEIRD_SERVER_REPLY, + CURL_FTP_ACCESS_DENIED, + CURL_OBSOLETE10, + CURL_FTP_WEIRD_PASS_REPLY, + CURL_OBSOLETE12, + CURL_FTP_WEIRD_PASV_REPLY, + CURL_FTP_WEIRD_227_FORMAT, + CURL_FTP_CANT_GET_HOST, + CURL_OBSOLETE16, + CURL_FTP_COULDNT_SET_TYPE, + CURL_PARTIAL_FILE, + CURL_FTP_COULDNT_RETR_FILE, + CURL_OBSOLETE20, + CURL_QUOTE_ERROR, + CURL_HTTP_RETURNED_ERROR, + CURL_WRITE_ERROR, + CURL_OBSOLETE24, + CURL_UPLOAD_FAILED, + CURL_READ_ERROR, + CURL_OUT_OF_MEMORY, + CURL_OPERATION_TIMEOUTED, + CURL_OBSOLETE29, + CURL_FTP_PORT_FAILED, + CURL_FTP_COULDNT_USE_REST, + CURL_OBSOLETE32, + CURL_RANGE_ERROR, + CURL_HTTP_POST_ERROR, + CURL_SSL_CONNECT_ERROR, + CURL_BAD_DOWNLOAD_RESUME, + CURL_FILE_COULDNT_READ_FILE, + CURL_LDAP_CANNOT_BIND, + CURL_LDAP_SEARCH_FAILED, + CURL_OBSOLETE40, + CURL_FUNCTION_NOT_FOUND, + CURL_ABORTED_BY_CALLBACK, + CURL_BAD_FUNCTION_ARGUMENT, + CURL_OBSOLETE44, + CURL_INTERFACE_FAILED, + CURL_OBSOLETE46, + CURL_TOO_MANY_REDIRECTS, + CURL_UNKNOWN_TELNET_OPTION, + CURL_TELNET_OPTION_SYNTAX, + CURL_OBSOLETE50, + CURL_PEER_FAILED_VERIF, + CURL_GOT_NOTHING, + CURL_SSL_ENGINE_NOTFOUND, + CURL_SSL_ENGINE_SETFAILED, + CURL_SEND_ERROR, + CURL_RECV_ERROR, + CURL_OBSOLETE57, + CURL_SSL_CERTPROBLEM, + CURL_SSL_CIPHER, + CURL_SSL_CACERT, + CURL_BAD_CONTENT_ENCODING, + CURL_LDAP_INVALID_URL, + CURL_FILESIZE_EXCEEDED, + CURL_USE_SSL_FAILED, + CURL_SEND_FAIL_REWIND, + CURL_SSL_ENGINE_INITFAILED, + CURL_LOGIN_DENIED, + CURL_TFTP_NOTFOUND, + CURL_TFTP_PERM, + CURL_REMOTE_DISK_FULL, + CURL_TFTP_ILLEGAL, + CURL_TFTP_UNKNOWNID, + CURL_REMOTE_FILE_EXISTS, + CURL_TFTP_NOSUCHUSER, + CURL_CONV_FAILED, + CURL_CONV_REQD, + CURL_SSL_CACERT_BADFILE, + CURL_REMOTE_FILE_NOT_FOUND, + CURL_SSH, + CURL_SSL_SHUTDOWN_FAILED, + CURL_AGAIN, + CURLE_SSL_CRL_BADFILE, + CURLE_SSL_ISSUER_ERROR, + CURL_CURL_LAST + }; + +#endif /* HEADER_CURLMSG_VMS_H */ diff --git a/third_party/curl/packages/vms/generate_config_vms_h_curl.com b/third_party/curl/packages/vms/generate_config_vms_h_curl.com new file mode 100644 index 0000000..99a39c8 --- /dev/null +++ b/third_party/curl/packages/vms/generate_config_vms_h_curl.com @@ -0,0 +1,450 @@ +$! File: GENERATE_CONFIG_H_CURL.COM +$! +$! Curl like most open source products uses a variant of a config.h file. +$! Depending on the curl version, this could be config.h or curl_config.h. +$! +$! For GNV based builds, the configure script is run and that produces +$! a [curl_]config.h file. Configure scripts on VMS generally do not +$! know how to do everything, so there is also a [-.lib]config-vms.h file +$! that has VMS specific code that compensates for bugs in some of the +$! VMS shared images. +$! +$! This generates a [curl_]config.h file and also a config_vms.h file, +$! which is used to supplement that file. Note that the config_vms.h file +$! and the [.lib]config-vms.h file do two different tasks and that the +$! filenames are slightly different. +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!========================================================================= +$! +$! Allow arguments to be grouped together with comma or separated by spaces +$! Do no know if we will need more than 8. +$args = "," + p1 + "," + p2 + "," + p3 + "," + p4 + "," +$args = args + p5 + "," + p6 + "," + p7 + "," + p8 + "," +$! +$! Provide lower case version to simplify parsing. +$args_lower = f$edit(args, "LOWERCASE") +$! +$args_len = f$length(args) +$! +$if (f$getsyi("HW_MODEL") .lt. 1024) +$then +$ arch_name = "VAX" +$else +$ arch_name = "" +$ arch_name = arch_name + f$edit(f$getsyi("ARCH_NAME"), "UPCASE") +$ if (arch_name .eqs. "") then arch_name = "UNK" +$endif +$! +$! +$nossl = 0 +$nohpssl = 1 +$hpssl = 0 +$libidn = 0 +$libssh2 = 0 +$noldap = 0 +$nozlib = 0 +$nokerberos = 0 +$! +$! First check to see if SSL is disabled. +$!--------------------------------------- +$if f$locate(",nossl,", args_lower) .lt. args_len then nossl = 1 +$if .not. nossl +$then +$! +$! ssl$* logicals means HP ssl is present +$!---------------------------------------- +$ if f$trnlnm("ssl$root") .nes. "" +$ then +$ nohpssl = 0 +$ hpssl = 1 +$ endif +$! +$! HP defines OPENSSL as SSL$INCLUDE as a convenience for linking. +$! As it is a violation of VMS standards for this to be provided, +$! some sites may have removed it, but if present, assume that +$! it indicates which OpenSSL to use. +$!------------------------------------ +$ openssl_lnm = f$trnlnm("OPENSSL") +$ if (openssl_lnm .nes. "SYS$INCLUDE") +$ then +$! Non HP SSL is installed, default to use it. +$ nohpssl = 1 +$ hpssl = 0 +$ endif +$! +$! Now check to see if hpssl has been specifically disabled +$!---------------------------------------------------------- +$ if f$locate(",nohpssl,", args_lower) .lt. args_len +$ then +$ nohpssl = 1 +$ hpssl = 0 +$ endif +$! +$! Finally check to see if hp ssl has been specifically included. +$!---------------------------------------------------------------- +$ if f$locate(",nohpssl,", args_lower) .lt. args_len +$ then +$ nohpssl = 1 +$ hpssl = 0 +$ endif +$endif +$! +$! Did someone port LIBIDN in the GNV compatible way? +$!------------------------------------------------------ +$if f$trnlnm("GNV$LIBIDNSHR") .nes. "" +$then +$ write sys$output "NOTICE: A LIBIDN port has been detected." +$ write sys$output " This port of curl for VMS has not been tested with it." +$ if f$locate(",libidn,", args_lower) .lt. args_len +$ then +$ libidn = 1 +$ endif +$ if .not. libidn +$ then +$ write sys$output " LIBIDN support is not enabled." +$ write sys$output "Run with the ""libidn"" parameter to attempt to use." +$ else +$ write sys$output " Untested LIBIDN support requested." +$ endif +$endif +$! +$! Did someone port LIBSSH2 in the GNV compatible way? +$!------------------------------------------------------ +$if f$trnlnm("GNV$LIBSSH2SHR") .nes. "" +$then +$ write sys$output "NOTICE: A LIBSSH2 port has been detected." +$ write sys$output " This port of curl for VMS has not been tested with it." +$ if f$locate(",libssh2,", args_lower) .lt. args_len +$ then +$ libssh2 = 1 +$ endif +$ if .not. libssh2 +$ then +$ write sys$output " LIBSSH2 support is not enabled." +$ write sys$output "Run with the ""libssh2"" parameter to attempt to use." +$ else +$ write sys$output " Untested LIBSSH2 support requested." +$ endif +$endif +$! +$! LDAP suppressed? +$if f$locate(",noldap,", args_lower) .lt. args_len +$then +$ noldap = 1 +$endif +$if f$search("SYS$SHARE:LDAP$SHR.EXE") .eqs. "" +$then +$ noldap = 1 +$endif +$! +$if f$locate(",nokerberos,", args_lower) .lt. args_len then nokerberos = 1 +$if .not. nokerberos +$then +$! If kerberos is installed: sys$share:gss$rtl.exe exists. +$ if f$search("sys$shsare:gss$rtl.exe") .eqs. "" +$ then +$ nokerberos = 1 +$ endif +$endif +$! +$! +$! Is GNV compatible LIBZ present? +$!------------------------------------------------------ +$if f$trnlnm("GNV$LIBZSHR") .nes. "" +$then +$ if f$locate(",nozlib,", args_lower) .lt. args_len +$ then +$ nozlib = 1 +$ endif +$! if .not. nozlib +$! then +$! write sys$output " GNV$LIBZSHR support is enabled." +$! else +$! write sys$output " GNV$LIBZSHR support is disabled by nozlib." +$! endif +$else +$ nozlib = 1 +$endif +$! +$! +$! Start the configuration file. +$! Need to do a create and then an append to make the file have the +$! typical file attributes of a VMS text file. +$create sys$disk:[curl.lib]config_vms.h +$open/append cvh sys$disk:[curl.lib]config_vms.h +$! +$! Write the defines to prevent multiple includes. +$! These are probably not needed in this case, +$! but are best practice to put on all header files. +$write cvh "#ifndef __CONFIG_VMS_H__" +$write cvh "#define __CONFIG_VMS_H__" +$write cvh "" +$write cvh "/* Define cpu-machine-OS */" +$! +$! Curl uses an OS macro to set the build environment. +$!---------------------------------------------------- +$! Now the DCL builds usually say xxx-HP-VMS and configure scripts +$! may put DEC or COMPAQ or HP for the middle part. +$! +$write cvh "#if defined(__alpha)" +$write cvh "#define OS ""ALPHA-HP-VMS""" +$write cvh "#elif defined(__vax)" +$write cvh "#define OS ""VAX-HP-VMS""" +$write cvh "#elif defined(__ia64)" +$write cvh "#define OS ""IA64-HP-VMS"" +$write cvh "#else" +$write cvh "#define OS ""UNKNOWN-HP-VMS"" +$write cvh "#endif" +$write cvh "" +$! +$! We are now setting this on the GNV build, so also do this +$! for compatibility. +$write cvh "/* Location of default ca path */" +$write cvh "#define curl_ca_path ""gnv$curl_ca_path""" +$! +$! NTLM_WB_ENABLED requires fork() but configure does not know this +$! We have to disable this in the configure command line. +$! config_h.com finds that configure defaults to it being enabled so +$! reports it. So we need to turn it off here. +$! +$write cvh "#ifdef NTLM_WB_ENABLED" +$write cvh "#undef NTLM_WB_ENABLED" +$write cvh "#endif" +$! +$! The config_h.com finds a bunch of default disable commands in +$! configure and will incorrectly disable these options. The config_h.com +$! is a generic procedure and it would break more things to try to fix it +$! to special case it for curl. So we will fix it here. +$! +$! We do them all here, even the ones that config_h.com currently gets correct. +$! +$write cvh "#ifdef CURL_DISABLE_COOKIES" +$write cvh "#undef CURL_DISABLE_COOKIES" +$write cvh "#endif" +$write cvh "#ifdef CURL_DISABLE_DICT" +$write cvh "#undef CURL_DISABLE_DICT" +$write cvh "#endif" +$write cvh "#ifdef CURL_DISABLE_FILE" +$write cvh "#undef CURL_DISABLE_FILE" +$write cvh "#endif" +$write cvh "#ifdef CURL_DISABLE_FTP" +$write cvh "#undef CURL_DISABLE_FTP" +$write cvh "#endif" +$write cvh "#ifdef CURL_DISABLE_GOPHER" +$write cvh "#undef CURL_DISABLE_GOPHER" +$write cvh "#endif" +$write cvh "#ifdef CURL_DISABLE_HTTP" +$write cvh "#undef CURL_DISABLE_HTTP" +$write cvh "#endif" +$write cvh "#ifdef CURL_DISABLE_IMAP" +$write cvh "#undef CURL_DISABLE_IMAP" +$write cvh "#endif" +$if .not. noldap +$then +$ write cvh "#ifdef CURL_DISABLE_LDAP" +$ write cvh "#undef CURL_DISABLE_LDAP" +$ write cvh "#endif" +$ if .not. nossl +$ then +$ write cvh "#ifdef CURL_DISABLE_LDAPS" +$ write cvh "#undef CURL_DISABLE_LDAPS" +$ write cvh "#endif" +$ endif +$endif +$write cvh "#ifdef CURL_DISABLE_LIBCURL_OPTION" +$write cvh "#undef CURL_DISABLE_LIBCURL_OPTION" +$write cvh "#endif" +$write cvh "#ifndef __VAX" +$write cvh "#ifdef CURL_DISABLE_NTLM" +$write cvh "#undef CURL_DISABLE_NTLM" +$write cvh "#endif" +$write cvh "#else" +$! NTLM needs long long or int64 support, missing from DECC C. +$write cvh "#ifdef __DECC +$write cvh "#ifndef CURL_DISABLE_NTLM" +$write cvh "#define CURL_DISABLE_NTLM 1" +$write cvh "#endif" +$write cvh "#endif" +$write cvh "#endif" +$write cvh "#ifdef CURL_DISABLE_POP3" +$write cvh "#undef CURL_DISABLE_POP3" +$write cvh "#endif" +$write cvh "#ifdef CURL_DISABLE_PROXY" +$write cvh "#undef CURL_DISABLE_PROXY" +$write cvh "#endif" +$write cvh "#ifdef CURL_DISABLE_RTSP" +$write cvh "#undef CURL_DISABLE_RTSP" +$write cvh "#endif" +$write cvh "#ifdef CURL_DISABLE_SMTP" +$write cvh "#undef CURL_DISABLE_SMTP" +$write cvh "#endif" +$write cvh "#ifdef CURL_DISABLE_TELNET" +$write cvh "#undef CURL_DISABLE_TELNET" +$write cvh "#endif" +$write cvh "#ifdef CURL_DISABLE_TFTP" +$write cvh "#undef CURL_DISABLE_TFTP" +$write cvh "#endif" +$write cvh "#ifdef CURL_DISABLE_POP3" +$write cvh "#undef CURL_DISABLE_POP3" +$write cvh "#endif" +$if .not. nossl +$then +$ write cvh "#ifdef CURL_DISABLE_TLS_SRP" +$ write cvh "#undef CURL_DISABLE_TLS_SRP" +$ write cvh "#endif" +$! +$endif +$write cvh "#ifdef CURL_DISABLE_VERBOSE_STRINGS" +$write cvh "#undef CURL_DISABLE_VERBOSE_STRINGS" +$write cvh "#endif" +$! +$! configure defaults to USE_*, a real configure on VMS chooses different. +$write cvh "#ifdef USE_ARES" +$write cvh "#undef USE_ARES" +$write cvh "#endif" +$write cvh "#ifdef USE_WOLFSSL" +$write cvh "#undef USE_WOLFSSL" +$write cvh "#endif" +$write cvh "#ifdef USE_GNUTLS" +$write cvh "#undef USE_GNUTLS" +$write cvh "#endif" +$write cvh "#ifdef USE_LIBRTMP" +$write cvh "#undef USE_LIBRTMP" +$write cvh "#endif" +$write cvh "#ifdef USE_MANUAL" +$write cvh "#undef USE_MANUAL" +$write cvh "#endif" +$write cvh "#ifdef USE_NGHTTP2" +$write cvh "#undef USE_NGHTTP2" +$write cvh "#endif" +$write cvh "#ifdef USE_OPENLDAP" +$write cvh "#undef USE_OPENLDAP" +$write cvh "#endif" +$write cvh "#ifdef USE_THREADS_POSIX" +$write cvh "#undef USE_THREADS_POSIX" +$write cvh "#endif" +$write cvh "#ifdef USE_TLS_SRP" +$write cvh "#undef USE_TLS_SRP" +$write cvh "#endif" +$write cvh "#ifdef USE_UNIX_SOCKETS" +$write cvh "#undef USE_UNIX_SOCKETS" +$write cvh "#endif" +$! +$write cvh "#ifndef HAVE_OLD_GSSMIT" +$write cvh "#define gss_nt_service_name GSS_C_NT_HOSTBASED_SERVICE" +$write cvh "#endif" +$! +$! +$! Note: +$! The CURL_EXTERN_SYMBOL is used for platforms that need the compiler +$! to know about universal symbols. VMS does not need this support so +$! we do not set it here. +$! +$! +$! I can not figure out where the C compiler is finding the ALLOCA.H file +$! in the text libraries, so CONFIG_H.COM can not find it either. +$! Usually the header file name is the module name in the text library. +$! It does not appear to hurt anything to not find header file, so we +$! are not overriding it here. +$! +$! +$! Check to see if OpenSSL is present. +$!---------------------------------- +$ssl_include = f$trnlnm("OPENSSL") +$if ssl_include .eqs. "" +$then +$ ssl_include = f$trnlnm("ssl$include") +$endif +$if ssl_include .eqs. "" then nossl = 1 +$! +$if .not. nossl +$then +$! +$ write cvh "#ifndef USE_OPENSSL" +$ write cvh "#define USE_OPENSSL 1" +$ write cvh "#endif" +$ if arch_name .eqs. "VAX" +$ then +$ old_mes = f$environment("message") +$ set message/notext/nofaci/noseve/noident +$ search/output=nla0: ssl$include:*.h CONF_MFLAGS_IGNORE_MISSING_FILE +$ status = $severity +$ set message'old_mes' +$ if status .nes. "1" +$ then +$ write cvh "#define VMS_OLD_SSL 1" +$ endif +$ endif +$endif +$! +$! +$! LibIDN not ported to VMS at this time. +$! This is for international domain name support. +$! Allow explicit experimentation. +$if libidn +$then +$ write cvh "#define HAVE_IDNA_STRERROR 1" +$ write cvh "#define HAVE_IDNA_FREE 1" +$ write cvh "#define HAVE_IDNA_FREE_H 1" +$ write cvh "#define HAVE_LIBIDN 1" +$else +$ write cvh "#ifdef HAVE_LIBIDN" +$ write cvh "#undef HAVE_LIBIDN" +$ write cvh "#endif" +$endif +$! +$! +$! LibSSH2 not ported to VMS at this time. +$! Allow explicit experimentation. +$if libssh2 +$then +$ write cvh "#define HAVE_LIBSSH2_EXIT 1" +$ write cvh "#define HAVE_LIBSSH2_INIT 1" +$ write cvh "#define HAVE_LIBSSH2_SCP_SEND64 1" +$ write cvh "#define HAVE_LIBSSH2_SESSION_HANDSHAKE 1" +$ write cvh "#define HAVE_LIBSSH2_VERSION 1 +$! +$ write cvh "#ifndef USE_LIBSSH2" +$ write cvh "#define USE_LIBSSH2 1" +$ write cvh "#endif" +$else +$ write cvh "#ifdef USE_LIBSSH2" +$ write cvh "#undef USE_LIBSSH2" +$ write cvh "#endif" +$endif +$! +$! +$! +$if .not. nozlib +$then +$ write cvh "#define HAVE_LIBZ 1" +$endif +$! +$! +$! Suppress a message in curl_gssapi.c compile. +$write cvh "#pragma message disable notconstqual" +$! +$! Close out the file +$! +$write cvh "" +$write cvh "#endif /* __CONFIG_VMS_H__ */" +$close cvh +$! +$all_exit: +$exit diff --git a/third_party/curl/packages/vms/generate_vax_transfer.com b/third_party/curl/packages/vms/generate_vax_transfer.com new file mode 100644 index 0000000..3ed49cb --- /dev/null +++ b/third_party/curl/packages/vms/generate_vax_transfer.com @@ -0,0 +1,273 @@ +$! File: generate_vax_transfer.com +$! +$! File to generate and compile the VAX transfer vectors from reading in the +$! Alpha/Itanium gnv_libcurl_symbols.opt file. +$! +$! This procedure patches the VAX Macro32 assembler to be case sensitive +$! and then compiles the generated +$! +$! The output of this procedure is: +$! gnv_libcurl_xfer.mar_exact +$! gnv_libcurl_xfer.obj +$! gnv_libcurl_xfer.opt +$! macro32_exactcase.exe +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!============================================================================ +$! +$! Save this so we can get back. +$ default_dir = f$environment("default") +$! +$ on warning then goto all_exit +$! +$! Want hard tabs in the generated file. +$ tab[0,8] = 9 +$! +$! This procedure is used on VAX only +$ if (f$getsyi("HW_MODEL") .ge. 1024) +$ then +$ write sys$output "This procedure is only used on VAX." +$ goto all_exit +$ endif +$! +$! +$! Get the libcurl version to generate the ident string. +$! ident string is max of 31 characters. +$! +$ ident_string = "unknown" +$ open/read cver [-.-.include.curl]curlver.h +$cver_loop: +$ read/end=cver_loop_end cver line_in +$ line_in = f$edit(line_in, "COMPRESS,TRIM") +$ if line_in .eqs. "" then goto cver_loop +$ code = f$extract(0, 1, line_in) +$ if code .nes. "#" then goto cver_loop +$ directive = f$element(0, " ", line_in) +$ if directive .nes. "#define" then goto cver_loop +$ name = f$element(1, " ", line_in) +$ if name .nes. "LIBCURL_VERSION" then goto cver_loop +$ ident_string = f$element(2, " ", line_in) - "" - "" +$cver_loop_end: +$ close cver +$! +$ open/read aopt gnv_libcurl_symbols.opt +$! +$! Write out the header +$ gosub do_header +$! +$ open/append vopt gnv_libcurl_xfer.mar_exact +$ write vopt tab,".IDENT /", ident_string, "/" +$! +$ write vopt tab, ".PSECT LIBCURL_XFERVECTORS -" +$ write vopt tab,tab,tab, "PIC,USR,CON,REL,GBL,SHR,EXE,RD,NOWRT,QUAD" +$ write vopt "" +$ write vopt tab, "SPARE", tab, "; never delete this spare" +$ write vopt ";" +$ write vopt ";", tab, "Exact case and upper case transfer vectors" +$! +$ alias_count = 0 +$vector_loop: +$! +$! Read in symbol_vector +$! +$ read/end=vector_loop_end aopt line_in +$ line = f$edit(line_in, "UNCOMMENT,COMPRESS,TRIM") +$ if line .eqs. "" then goto vector_loop +$! +$ line_u = f$edit(line, "UPCASE") +$ key = f$element(0, "=", line_u) +$ if (key .eqs. "SYMBOL_VECTOR") +$ then +$ symbol_string = f$element(1, "=", line) - "(" +$ symbol_type = f$element(2, "=", line_u) - ")" +$ symbol_name = f$element(1, "/", symbol_string) +$ if symbol_type .nes. "PROCEDURE" +$ then +$ write sys$output "%CURLBUILD-W-NOTPROC, " + - +$ "This procedure can only handle procedure vectors" +$ write sys$output - +"Data vectors require manual construction for which this procedure or" +$ write sys$output - +"the shared library needs to be updated to resolve." +$ write sys$output - +"the preferred solution is to have a procedure return the address of the " +$ write sys$output - +"the variable instead of having a variable, as if the size of the variable " + write sys$output - +"changes, the symbol vector is no longer backwards compatible." +$ endif +$ if (symbol_name .eqs. "/") +$ then +$ symbol_name = symbol_string +$ write vopt tab, symbol_type, tab, symbol_name +$ else +$ alias_count = alias_count + 1 +$ symbol_alias = f$element(0, "/", symbol_string) +$ write vopt - + tab, "''symbol_type_U", tab, symbol_name, tab, symbol_alias +$ endif +$ endif +$ goto vector_loop +$vector_loop_end: +$! +$! End of pass one, second pass needed if aliases exist +$ close aopt +$! +$ if alias_count .eq. 0 then goto finish_file +$! +$! Start pass 2, write stub routine header +$! +$ open/read aopt gnv_libcurl_symbols.opt +$! +$alias_loop: +$! +$! Read in symbol_vector +$! +$ read/end=alias_loop_end aopt line_in +$ line = f$edit(line_in, "UNCOMMENT,COMPRESS,TRIM") +$ if line .eqs. "" then goto alias_loop +$! +$ line_u = f$edit(line, "UPCASE") +$ key = f$element(0, "=", line_u) +$ if (key .eqs. "SYMBOL_VECTOR") +$ then +$ symbol_string = f$element(1, "=", line) - "(" +$ symbol_type = f$element(2, "=", line_u) - ")" +$ symbol_name = f$element(1, "/", symbol_string) +$ if (symbol_name .eqs. "/") +$ then +$ symbol_name = symbol_string +$ else +$ alias_count = alias_count + 1 +$ symbol_alias = f$element(0, "/", symbol_string) +$ write vopt tab, ".ENTRY", tab, symbol_alias, ", ^M<>" +$ endif +$ endif +$ goto alias_loop +$! read in symbol_vector +$! if not alias, then loop +$! write out subroutine name +$! +$alias_loop_end: +$! +$ write vopt tab, "MOVL #1, R0" +$ write vopt tab, "RET" +$! +$finish_file: +$! +$ write vopt "" +$ write vopt tab, ".END" +$! +$ close aopt +$ close vopt +$! +$! Patch the Macro32 compiler +$!---------------------------- +$ patched_macro = "sys$disk:[]macro32_exactcase.exe" +$ if f$search(patched_macro) .eqs. "" +$ then +$ copy sys$system:macro32.exe 'patched_macro' +$ patch @macro32_exactcase.patch +$ endif +$ define/user macro32 'patched_macro' +$ macro/object=gnv_libcurl_xfer.obj gnv_libcurl_xfer.mar_exact +$! +$! Create the option file for linking the shared image. +$ create gnv_libcurl_xfer.opt +$ open/append lco gnv_libcurl_xfer.opt +$ write lco "gsmatch=lequal,1,1" +$ write lco "cluster=transfer_vector,,,''default_dir'gnv_libcurl_xfer" +$ write lco "collect=libcurl_global, libcurl_xfervectors" +$ close lco +$! +$! +$ goto all_exit +$! +$! Process the header +$do_header: +$! +$! Force the mode of the file to same as text editor generated. +$ create gnv_libcurl_xfer.mar_exact +$deck +; File: gnv_libcurl_xfer.mar_exact +; +; VAX transfer vectors +; +; This needs to be compiled with a specialized patch on Macro32 to make it +; preserve the case of symbols instead of converting it to uppercase. +; +; This patched Macro32 requires all directives to be in upper case. +; +; There are three sets of symbols for transfer vectors here. +; +; The first for upper case which matches the tradition method of generating +; VAX transfer vectors. +; +; The second is the exact case for compatibility with open source C programs +; that expect exact case symbols in images. These are separated because a +; previous kit had only upper case symbols. +; +; The third is the routine stub that is used to resolve part of the upper +; case transfer vectors, with exact case entry symbols. +; +; When you add routines, you need to add them after the second set of transfer +; vectors for both upper and exact case, and then additional entry points +; in upper case added to stub routines. +; +;************************************************************************* + + .TITLE libcurl_xfer - Transfer vector for libcurl + .DISABLE GLOBAL + +; +; Macro to generate a transfer vector entry +; + .MACRO PROCEDURE NAME + .EXTRN 'NAME + .ALIGN QUAD + .TRANSFER 'NAME + .MASK 'NAME + JMP 'NAME+2 + .ENDM + + .MACRO PROCEDUREU NAME NAMEU + .EXTRN 'NAME + .ALIGN QUAD + .TRANSFER 'NAMEU + .MASK 'NAME + JMP 'NAME+2 + + .ENDM +; +; +; Macro to reserve a spare entry. +; + .MACRO SPARE + .ALIGN QUAD + .ALIGN QUAD + .QUAD 0 + .ENDM + +$EOD +$! +$! +$ return +$! +$all_exit: +$set def 'default_dir' +$exit '$status' diff --git a/third_party/curl/packages/vms/gnv_conftest.c_first b/third_party/curl/packages/vms/gnv_conftest.c_first new file mode 100644 index 0000000..317b1ab --- /dev/null +++ b/third_party/curl/packages/vms/gnv_conftest.c_first @@ -0,0 +1,58 @@ +/* File: GNV$CONFTEST.C_FIRST + * + * Copyright (C) John Malmberg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * SPDX-License-Identifier: ISC + * + */ + +/* This is needed for Configure tests to get the correct exit status */ +void __posix_exit(int __status); +#define exit(__p1) __posix_exit(__p1) + +/* Fake pass the test to find a standard ldap routine that we know is */ +/* present on VMS, but with the wrong case for the symbol */ +char ldap_url_parse(void) {return 0;} + +/* These are to pass the test that does not use headers */ +/* Because configure does an #undef which keeps us from using #define */ +/* char CRYPTO_add_lock(void) {return 0;} */ +char SSL_connect(void) {return 0;} +char ENGINE_init(void) {return 0;} +char RAND_status(void) {return 0;} +/* char RAND_screen(void) {return 0;} In headers, but not present */ +char CRYPTO_cleanup_all_ex_data(void) {return 0;} +char SSL_get_shutdown(void) {return 0;} +char ENGINE_load_builtin_engines (void) {return 0;} + +/* And these are to pass the test that uses headers. */ +/* Because the HP OpenSSL transfer vectors are currently in Upper case only */ +#pragma message disable macroredef +#define CRYPTO_add_lock CRYPTO_ADD_LOCK +#define SSL_connect SSL_CONNECT +#define ENGINE_init ENGINE_INIT +#define RAND_status RAND_STATUS +/* #define RAND_screen RAND_SCREEN */ +#define CRYPTO_cleanup_all_ex_data CRYPTO_CLEANUP_ALL_EX_DATA +#define SSL_get_shutdown SSL_GET_SHUTDOWN +#define ENGINE_load_builtin_engines ENGINE_LOAD_BUILTIN_ENGINES + +/* Can not use the #define macro to fix the case on CRYPTO_lock because */ +/* there is a macro CRYPTO_LOCK that is a number */ + +/* After all the work to get configure to pass the CRYPTO_LOCK tests, + * it turns out that VMS does not have the CRYPTO_LOCK symbol in the + * transfer vector, even though it is in the header file. + */ diff --git a/third_party/curl/packages/vms/gnv_curl_configure.sh b/third_party/curl/packages/vms/gnv_curl_configure.sh new file mode 100755 index 0000000..2155800 --- /dev/null +++ b/third_party/curl/packages/vms/gnv_curl_configure.sh @@ -0,0 +1,44 @@ +# File: gnv_curl_configure.sh +# +# Set up and run the configure script for Curl so that it can find the +# proper options for VMS. +# +# Copyright (C) John Malmberg +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# +# SPDX-License-Identifier: ISC +# +#========================================================================== +# +# POSIX exit mode is needed for Unix shells. +export GNV_CC_MAIN_POSIX_EXIT=1 +# +# Where to look for the helper files. +export GNV_OPT_DIR=. +# +# How to find the SSL library files. +export LIB_OPENSSL=/SSL_LIB +# +# Override configure adding -std1 which is too strict for what curl +# actually wants. +export GNV_CC_QUALIFIERS=/STANDARD=RELAXED +# +# Set the directory to where the Configure script actually is. +cd ../.. +# +# +./configure --prefix=/usr --exec-prefix=/usr --disable-dependency-tracking \ + --disable-libtool-lock --with-gssapi --disable-ntlm-wb \ + --with-ca-path=gnv\$curl_ca_path +# diff --git a/third_party/curl/packages/vms/gnv_libcurl_symbols.opt b/third_party/curl/packages/vms/gnv_libcurl_symbols.opt new file mode 100644 index 0000000..5bc2a85 --- /dev/null +++ b/third_party/curl/packages/vms/gnv_libcurl_symbols.opt @@ -0,0 +1,181 @@ +! File GNV$LIBCURL_SYMBOLS.OPT +! +! This file must be manually maintained to allow upward compatibility +! The SYMBOL_VECTORs are set up so that applications can be compiled +! with either case sensitive symbol names or the default of uppercase. +! This is because many of the Open Source applications that would call +! the LIBCURL library need to be built with case sensitive names. +! +! Automatic generation is currently not practical because the order of +! the entries are important for upward compatibility. +! +! The GSMATCH is manually set to the major version of 1, with the minor +! version being the next two sections multiplied by a power of 10 to +! become the minor version. +! So LIBCURL 7.18.1 becomes 1,718010. +! And a future LIBCURL of 7.18.2 would be 1,718020 if new routines were added. +! +! This leaves some spare digits for minor patches. +! +! Note that the GSMATCH does not need to have any real relationship to the +! actual package version number. +! +! New SYMBOL_VECTORs must be added to the end of this list, and added +! in pairs for both exact and with an uppercase alias. +! If the public symbol is more than 31 characters long, then a special +! shortened symbol will be exported, and three aliases should be created, +! The aliases will be the special shortened uppercase alias, and both +! upper and lowercase versions of a truncated name (preferred) or a +! modified manually shortened name if a truncated name will not be +! unique. +! +! Routines can not be removed, the functionality must be maintained. +! If a new routine is supplied where the arguments are incompatible with +! the older version, both versions are needed to be maintained. +! The old version can be given a different name, but must be in the same +! SYMBOL_VECTOR positions in this file. +! +! Changing the number of parameters for an existing routine does not require +! maintaining multiple versions as long as the routine can be called with +! the old number of parameters. +! +! Copyright (C) John Malmberg +! +! Permission to use, copy, modify, and/or distribute this software for any +! purpose with or without fee is hereby granted, provided that the above +! copyright notice and this permission notice appear in all copies. +! +! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +! +! SPDX-License-Identifier: ISC +!============================================================================ +GSMATCH=LEQUAL,1,719050 +CASE_SENSITIVE=YES +SYMBOL_VECTOR=(curl_strequal=PROCEDURE) +SYMBOL_VECTOR=(CURL_STREQUAL/curl_strequal=PROCEDURE) +SYMBOL_VECTOR=(curl_strnequal=PROCEDURE) +SYMBOL_VECTOR=(CURL_STRNEQUAL/curl_strnequal=PROCEDURE) +SYMBOL_VECTOR=(curl_formadd=PROCEDURE) +SYMBOL_VECTOR=(CURL_FORMADD/curl_formadd=PROCEDURE) +SYMBOL_VECTOR=(curl_formget=PROCEDURE) +SYMBOL_VECTOR=(CURL_FORMGET/curl_formget=PROCEDURE) +SYMBOL_VECTOR=(curl_formfree=PROCEDURE) +SYMBOL_VECTOR=(CURL_FORMFREE/curl_formfree=PROCEDURE) +SYMBOL_VECTOR=(curl_getenv=PROCEDURE) +SYMBOL_VECTOR=(CURL_GETENV/curl_getenv=PROCEDURE) +SYMBOL_VECTOR=(curl_version=PROCEDURE) +SYMBOL_VECTOR=(CURL_VERSION/curl_version=PROCEDURE) +SYMBOL_VECTOR=(curl_easy_escape=PROCEDURE) +SYMBOL_VECTOR=(CURL_EASY_ESCAPE/curl_easy_escape=PROCEDURE) +SYMBOL_VECTOR=(curl_escape=PROCEDURE) +SYMBOL_VECTOR=(CURL_ESCAPE/curl_escape=PROCEDURE) +SYMBOL_VECTOR=(curl_easy_unescape=PROCEDURE) +SYMBOL_VECTOR=(CURL_EASY_UNESCAPE/curl_easy_unescape=PROCEDURE) +SYMBOL_VECTOR=(curl_unescape=PROCEDURE) +SYMBOL_VECTOR=(CURL_UNESCAPE/curl_unescape=PROCEDURE) +SYMBOL_VECTOR=(curl_free=PROCEDURE) +SYMBOL_VECTOR=(CURL_FREE/curl_free=PROCEDURE) +SYMBOL_VECTOR=(curl_global_init=PROCEDURE) +SYMBOL_VECTOR=(CURL_GLOBAL_INIT/curl_global_init=PROCEDURE) +SYMBOL_VECTOR=(curl_global_init_mem=PROCEDURE) +SYMBOL_VECTOR=(CURL_GLOBAL_INIT_MEM/curl_global_init_mem=PROCEDURE) +SYMBOL_VECTOR=(curl_global_cleanup=PROCEDURE) +SYMBOL_VECTOR=(CURL_GLOBAL_CLEANUP/curl_global_cleanup=PROCEDURE) +SYMBOL_VECTOR=(curl_slist_append=PROCEDURE) +SYMBOL_VECTOR=(CURL_SLIST_APPEND/curl_slist_append=PROCEDURE) +SYMBOL_VECTOR=(curl_slist_free_all=PROCEDURE) +SYMBOL_VECTOR=(CURL_SLIST_FREE_ALL/curl_slist_free_all=PROCEDURE) +SYMBOL_VECTOR=(curl_getdate=PROCEDURE) +SYMBOL_VECTOR=(CURL_GETDATE/curl_getdate=PROCEDURE) +SYMBOL_VECTOR=(curl_share_init=PROCEDURE) +SYMBOL_VECTOR=(CURL_SHARE_INIT/curl_share_init=PROCEDURE) +SYMBOL_VECTOR=(curl_share_setopt=PROCEDURE) +SYMBOL_VECTOR=(CURL_SHARE_SETOPT/curl_share_setopt=PROCEDURE) +SYMBOL_VECTOR=(curl_share_cleanup=PROCEDURE) +SYMBOL_VECTOR=(CURL_SHARE_CLEANUP/curl_share_cleanup=PROCEDURE) +SYMBOL_VECTOR=(curl_version_info=PROCEDURE) +SYMBOL_VECTOR=(CURL_VERSION_INFO/curl_version_info=PROCEDURE) +SYMBOL_VECTOR=(curl_easy_strerror=PROCEDURE) +SYMBOL_VECTOR=(CURL_EASY_STRERROR/curl_easy_strerror=PROCEDURE) +SYMBOL_VECTOR=(curl_share_strerror=PROCEDURE) +SYMBOL_VECTOR=(CURL_SHARE_STRERROR/curl_share_strerror=PROCEDURE) +SYMBOL_VECTOR=(curl_easy_pause=PROCEDURE) +SYMBOL_VECTOR=(CURL_EASY_PAUSE/curl_easy_pause=PROCEDURE) +! +! easy.h +SYMBOL_VECTOR=(curl_easy_init=PROCEDURE) +SYMBOL_VECTOR=(CURL_EASY_INIT/curl_easy_init=PROCEDURE) +SYMBOL_VECTOR=(curl_easy_setopt=PROCEDURE) +SYMBOL_VECTOR=(CURL_EASY_SETOPT/curl_easy_setopt=PROCEDURE) +SYMBOL_VECTOR=(curl_easy_perform=PROCEDURE) +SYMBOL_VECTOR=(CURL_EASY_PERFORM/curl_easy_perform=PROCEDURE) +SYMBOL_VECTOR=(curl_easy_cleanup=PROCEDURE) +SYMBOL_VECTOR=(CURL_EASY_CLEANUP/curl_easy_cleanup=PROCEDURE) +SYMBOL_VECTOR=(curl_easy_getinfo=PROCEDURE) +SYMBOL_VECTOR=(CURL_EASY_GETINFO/curl_easy_getinfo=PROCEDURE) +SYMBOL_VECTOR=(curl_easy_duphandle=PROCEDURE) +SYMBOL_VECTOR=(CURL_EASY_DUPHANDLE/curl_easy_duphandle=PROCEDURE) +SYMBOL_VECTOR=(curl_easy_reset=PROCEDURE) +SYMBOL_VECTOR=(CURL_EASY_RESET/curl_easy_reset=PROCEDURE) +SYMBOL_VECTOR=(curl_easy_recv=PROCEDURE) +SYMBOL_VECTOR=(CURL_EASY_RECV/curl_easy_recv=PROCEDURE) +SYMBOL_VECTOR=(curl_easy_send=PROCEDURE) +SYMBOL_VECTOR=(CURL_EASY_SEND/curl_easy_send=PROCEDURE) +! +! multi.h +SYMBOL_VECTOR=(curl_multi_init=PROCEDURE) +SYMBOL_VECTOR=(CURL_MULTI_INIT/curl_multi_init=PROCEDURE) +SYMBOL_VECTOR=(curl_multi_add_handle=PROCEDURE) +SYMBOL_VECTOR=(CURL_MULTI_ADD_HANDLE/curl_multi_add_handle=PROCEDURE) +SYMBOL_VECTOR=(curl_multi_remove_handle=PROCEDURE) +SYMBOL_VECTOR=(CURL_MULTI_REMOVE_HANDLE/curl_multi_remove_handle=PROCEDURE) +SYMBOL_VECTOR=(curl_multi_fdset=PROCEDURE) +SYMBOL_VECTOR=(CURL_MULTI_FDSET/curl_multi_fdset=PROCEDURE) +SYMBOL_VECTOR=(curl_multi_perform=PROCEDURE) +SYMBOL_VECTOR=(CURL_MULTI_PERFORM/curl_multi_perform=PROCEDURE) +SYMBOL_VECTOR=(curl_multi_cleanup=PROCEDURE) +SYMBOL_VECTOR=(CURL_MULTI_CLEANUP/curl_multi_cleanup=PROCEDURE) +SYMBOL_VECTOR=(curl_multi_info_read=PROCEDURE) +SYMBOL_VECTOR=(CURL_MULTI_INFO_READ/curl_multi_info_read=PROCEDURE) +SYMBOL_VECTOR=(curl_multi_strerror=PROCEDURE) +SYMBOL_VECTOR=(CURL_MULTI_STRERROR/curl_multi_strerror=PROCEDURE) +SYMBOL_VECTOR=(curl_multi_socket=PROCEDURE) +SYMBOL_VECTOR=(CURL_MULTI_SOCKET/curl_multi_socket=PROCEDURE) +SYMBOL_VECTOR=(curl_multi_socket_action=PROCEDURE) +SYMBOL_VECTOR=(CURL_MULTI_SOCKET_ACTION/curl_multi_socket_action=PROCEDURE) +SYMBOL_VECTOR=(curl_multi_socket_all=PROCEDURE) +SYMBOL_VECTOR=(CURL_MULTI_SOCKET_ALL/curl_multi_socket_all=PROCEDURE) +SYMBOL_VECTOR=(curl_multi_timeout=PROCEDURE) +SYMBOL_VECTOR=(CURL_MULTI_TIMEOUT/curl_multi_timeout=PROCEDURE) +SYMBOL_VECTOR=(curl_multi_setopt=PROCEDURE) +SYMBOL_VECTOR=(CURL_MULTI_SETOPT/curl_multi_setopt=PROCEDURE) +SYMBOL_VECTOR=(curl_multi_assign=PROCEDURE) +SYMBOL_VECTOR=(CURL_MULTI_ASSIGN/curl_multi_assign=PROCEDURE) +! +! mprintf.h +SYMBOL_VECTOR=(curl_mprintf=PROCEDURE) +SYMBOL_VECTOR=(CURL_MPRINTF/curl_mprintf=PROCEDURE) +SYMBOL_VECTOR=(curl_mfprintf=PROCEDURE) +SYMBOL_VECTOR=(CURL_MFPRINTF/curl_mfprintf=PROCEDURE) +SYMBOL_VECTOR=(curl_msprintf=PROCEDURE) +SYMBOL_VECTOR=(CURL_MSPRINTF/curl_msprintf=PROCEDURE) +SYMBOL_VECTOR=(curl_msnprintf=PROCEDURE) +SYMBOL_VECTOR=(CURL_MSNPRINTF/curl_msnprintf=PROCEDURE) +SYMBOL_VECTOR=(curl_mvprintf=PROCEDURE) +SYMBOL_VECTOR=(CURL_MVPRINTF/curl_mvprintf=PROCEDURE) +SYMBOL_VECTOR=(curl_mvfprintf=PROCEDURE) +SYMBOL_VECTOR=(CURL_MVFPRINTF/curl_mvfprintf=PROCEDURE) +SYMBOL_VECTOR=(curl_mvsprintf=PROCEDURE) +SYMBOL_VECTOR=(CURL_MVSPRINTF/curl_mvsprintf=PROCEDURE) +SYMBOL_VECTOR=(curl_mvsnprintf=PROCEDURE) +SYMBOL_VECTOR=(CURL_MVSNPRINTF/curl_mvsnprintf=PROCEDURE) +SYMBOL_VECTOR=(curl_maprintf=PROCEDURE) +SYMBOL_VECTOR=(CURL_MAPRINTF/curl_maprintf=PROCEDURE) +SYMBOL_VECTOR=(curl_mvaprintf=PROCEDURE) +SYMBOL_VECTOR=(CURL_MVAPRINTF/curl_mvaprintf=PROCEDURE) diff --git a/third_party/curl/packages/vms/gnv_link_curl.com b/third_party/curl/packages/vms/gnv_link_curl.com new file mode 100644 index 0000000..247987a --- /dev/null +++ b/third_party/curl/packages/vms/gnv_link_curl.com @@ -0,0 +1,851 @@ +$! File: gnv_link_curl.com +$! +$! File to build images using gnv$libcurl.exe +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!============================================================================ +$! +$! Save this so we can get back. +$ default_dir = f$environment("default") +$ define/job gnv_packages_vms 'default_dir' +$! +$ on warning then goto all_exit +$! +$! On VAX, we need to generate a Macro transfer vector. +$ parse_style = "TRADITIONAL" +$ if (f$getsyi("HW_MODEL") .lt. 1024) +$ then +$ @generate_vax_transfer.com +$ arch_name = "VAX" +$ else +$ arch_name = "" +$ arch_name = arch_name + f$edit(f$getsyi("ARCH_NAME"), "UPCASE") +$ if (arch_name .eqs. "") then arch_name = "UNK" +$! +$! Extended parsing option starts with VMS 7.3-1. +$! There is no 7.4, so that simplifies the parse a bit. +$! +$ node_swvers = f$getsyi("node_swvers") +$ version_patch = f$extract(1, f$length(node_swvers), node_swvers) +$ maj_ver = f$element(0, ".", version_patch) +$ min_ver_patch = f$element(1, ".", version_patch) +$ min_ver = f$element(0, "-", min_ver_patch) +$ patch = f$element(1, "-", min_ver_patch) +$ if patch .eqs. "-" then patch = "" +$ parse_x = 0 +$ if maj_ver .ges. "8" +$ then +$ parse_x = 1 +$ else +$ if maj_ver .eqs. "7" .and. min_ver .ges. "3" .and. patch .nes. "" +$ then +$ parse_x = 1 +$ endif +$ endif +$ if parse_x +$ then +$ parse_style = f$getjpi("", "parse_style_perm") +$ endif +$ endif +$! +$! +$! Move to where the base directories. +$ set def [--] +$! +$! +$! Build the Message file. +$!-------------------------- +$ if f$search("[.packages.vms]curlmsg.obj") .eqs. "" +$ then +$ message [.packages.vms]curlmsg.msg/object=[.packages.vms] +$ endif +$ if f$search("gnv$curlmsg.exe") .eqs. "" +$ then +$ link/share=gnv$curlmsg.exe [.packages.vms]curlmsg.obj +$ endif +$! +$! +$! Need to build the common init module. +$!------------------------------------------- +$ cflags = "/list/show=(expan,includ)" +$ init_obj = "[.packages.vms]curl_crtl_init.obj" +$ if f$search(init_obj) .eqs. "" +$ then +$ cc'cflags' 'default_dir'curl_crtl_init.c/obj='init_obj' +$ endif +$ purge 'init_obj' +$ rename 'init_obj' ;1 +$! +$! +$! Need to build the module to test the HP OpenSSL version +$!-------------------------------------------------------- +$ if arch_name .nes. "VAX" +$ then +$ rpt_obj = "[.packages.vms]report_openssl_version.obj +$ if f$search(rpt_obj) .eqs. "" +$ then +$ cc'cflags' 'default_dir'report_openssl_version.c/obj='rpt_obj' +$ endif +$ purge 'rpt_obj' +$ rename 'rpt_obj' ;1 +$! +$ link/exe='default_dir'report_openssl_version.exe 'rpt_obj' +$ report_openssl_version := $'default_dir'report_openssl_version.exe +$ endif +$! +$! +$ base_link_opt_file = "[.packages.vms.''arch_name']gnv_libcurl_linker.opt" +$ share_link_opt_file = "[.packages.vms.''arch_name']gnv_ssl_libcurl_linker.opt" +$ if f$search(base_link_opt_file) .eqs. "" +$ then +$ base_link_opt_file = "[.packages.vms]gnv_libcurl_linker.opt" +$ share_link_opt_file = "[.packages.vms]gnv_ssl_libcurl_linker.opt" +$ if f$search(base_link_opt_file) .eqs. "" +$ then +$ write sys$output "Can not find base library option file!" +$ goto all_exit +$ endif +$ endif +$! +$! Create the a new option file with special fixup for HP SSL +$! For a shared image, we always want ZLIB and 32 bit HPSSL +$! +$ if f$search("gnv$libzshr32") .eqs. "" +$ then +$ write sys$output "VMSPORTS/GNV LIBZ Shared image not found!" +$ goto all_exit +$ endif +$! +$! +$! Need to check the version of the HP SSL shared image. +$! +$! VAX platform can not be checked this way, it appears symbol lookup +$! was disabled. VAX has not been updated in a while. +$ if arch_name .eqs. "VAX" +$ then +$ hp_ssl_libcrypto32 = "sys$common:[syslib]ssl$libcrypto_shr32.exe" +$ hp_ssl_libssl32 = "sys$common:[syslib]ssl$libssl_shr32.exe" +$ if f$search(hp_ssl_libcrypto32) .nes. "" +$ then +$ use_hp_ssl = 1 +$ curl_ssl_libcrypto32 = hp_ssl_libcrypto32 +$ curl_ssl_libssl32 = hp_ssl_libssl32 +$ curl_ssl_version = "OpenSSL/0.9.6g" +$ else +$ write sys$output "HP OpenSSL Shared images not found!" +$ goto all_exit +$ endif +$ else +$! +$! Minimum HP version we can use reports: +$! "OpenSSL 0.9.8w 23 Apr 2012" +$! +$ use_hp_ssl = 0 +$ hp_ssl_libcrypto32 = "sys$share:ssl$libcrypto_shr32.exe" +$ hp_ssl_libssl32 = "sys$share:ssl$libssl_shr32.exe" +$ if f$search(hp_ssl_libcrypto32) .nes. "" +$ then +$ curl_ssl_libcrypto32 = hp_ssl_libcrypto32 +$ curl_ssl_libssl32 = hp_ssl_libssl32 +$ report_openssl_version 'hp_ssl_libcrypto32' hp_ssl_version +$ endif +$! +$ if f$type(hp_ssl_version) .eqs. "STRING" +$ then +$ curl_ssl_version = hp_ssl_version +$ full_version = f$element(1, " ", hp_ssl_version) +$ ver_maj = f$element(0, ".", full_version) +$ ver_min = f$element(1, ".", full_version) +$ ver_patch = f$element(2, ".", full_version) +$! ! ver_patch is typically both a number and some letters +$ ver_patch_len = f$length(ver_patch) +$ ver_patchltr = "" +$ver_patch_loop: +$ ver_patchltr_c = f$extract(ver_patch_len - 1, 1, ver_patch) +$ if ver_patchltr_c .les. "9" then goto ver_patch_loop_end +$ ver_patchltr = ver_patchltr_c + ver_patchltr +$ ver_patch_len = ver_patch_len - 1 +$ goto ver_patch_loop +$ver_patch_loop_end: +$ ver_patchnum = ver_patch - ver_patchltr +$ if 'ver_maj' .ge. 0 +$ then +$ if 'ver_min' .ge. 9 +$ then +$ if 'ver_patchnum' .ge. 8 +$ then +$ if ver_patchltr .ges. "w" then use_hp_ssl = 1 +$ endif +$ endif +$ endif +$set nover +$ if use_hp_ssl .eq. 0 +$ then +$ write sys$output - + " HP OpenSSL version of ""''hp_ssl_version'"" is too old for shared libcurl!" +$ endif +$ else +$ write sys$output "Unable to get version of HP OpenSSL" +$ endif +$! +$ gnv_ssl_libcrypto32 = "gnv$gnu:[lib]ssl$libcrypto_shr32.exe" +$ gnv_ssl_libssl32 = "gnv$gnu:[lib]ssl$libssl_shr32.exe" +$ if f$search(gnv_ssl_libcrypto32) .nes. "" +$ then +$ report_openssl_version 'gnv_ssl_libcrypto32' gnv_ssl_version +$ endif +$! +$ use_gnv_ssl = 0 +$ if f$type(gnv_ssl_version) .eqs. "STRING" +$ then +$ gnv_full_version = f$element(1, " ", gnv_ssl_version) +$ gnv_ver_maj = f$element(0, ".", gnv_full_version) +$ gnv_ver_min = f$element(1, ".", gnv_full_version) +$ gnv_ver_patch = f$element(2, ".", gnv_full_version) +$ gnv_ver_patch_len = f$length(gnv_ver_patch) +$ gnv_ver_patchnum = f$extract(0, gnv_ver_patch_len - 1, gnv_ver_patch) +$ gnv_ver_patchltr = f$extract(gnv_ver_patch_len - 1, 1, gnv_ver_patch) +$ if 'gnv_ver_maj' .ge. 0 +$ then +$ if 'gnv_ver_min' .ge. 9 +$ then +$ if 'gnv_ver_patchnum' .ge. 8 +$ then +$ if gnv_ver_patchltr .ges. "w" then use_gnv_ssl = 1 +$ endif +$ endif +$ endif +$ if use_gnv_ssl .eq. 0 +$ then +$ write sys$output - + "GNV OpenSSL version of ""''gnv_ssl_version'" is too old for shared libcurl!" +$ endif +$! +$! Prefer to break the tie with the lowest supported version +$! For simplicity, if the GNV image is present, it will be used. +$! Version tuple is not a simple compare. +$! +$ if use_gnv_ssl .eq. 1 then +$ curl_ssl_libcrypto32 = gnv_ssl_libcrypto32 +$ curl_ssl_libssl32 = gnv_ssl_libssl32 +$ curl_ssl_version = gnv_ssl_version +$ use_hp_ssl = 0 +$ endif +!$! +$ else +$ write sys$output "Unable to get version of GNV OpenSSL" +$ endif +$! +$! Need to write a release note section about HP OpenSSL +$! +$create 'default_dir'hp_ssl_release_info.txt +$deck +This package is built on with the OpenSSL version listed below and requires +the shared images from the HP OpenSSL product that is kitted with that +version or a compatible later version. + +For Alpha and IA64 platforms, see the url below to register to get the +download URL. The kit will be HP 1.4-467 or later. + https://h41379.www4.hpe.com/openvms/products/ssl/ssl.html + +For VAX, use the same registration, but remove the kit name from any of the +download URLs provided and put in CPQ-VAXVMS-SSL-V0101-B-1.PCSI-DCX_VAXEXE + +If your system can not be upgraded to a compatible version of OpenSSL, then +you can extract the two shared images from the kit and place them in the +[vms$common.gnv.lib]directory of the volume that you are installing GNV and +or GNV compatible components like Curl. + +If GNV is installed, you must run the GNV startup procedure before these steps +and before installing Curl. + + + 1. make sure that [vms$common.gnv.lib] exists by using the following + commands. We want the directory to be in lowercase except on VAX. + + $SET PROCESS/PARSE=extend !If not VAX. + $CREATE/DIR device:[vms$common.gnv.lib]/prot=w:re + + 2. Extract the ssl$crypto_shr32.exe and ssl$libssl_shr32.exe images. + + $PRODUCT EXTRACT FILE - + /select=(ssl$libcrypto_shr32.exe,ssl$libssl_shr32.exe)- + /source=device:[dir] - + /options=noconfirm - + /destination=device:[vms$common.gnv.lib] SSL + +The [vms$common.sys$startup}curl_startup.com procedure will then configure +libcurl to use these shared images instead of the system ones. + +When you upgrade SSL on VMS to the newer version of HP SSL, then these copies +should be deleted. + +$eod +$! +$ open/append sslr 'default_dir'hp_ssl_release_info.txt +$ write sslr "OpenSSL version used for building this kit: ",curl_ssl_version +$ write sslr "" +$ close sslr +$! +$! +$! LIBZ +$ libzshr_line = "" +$ try_shr = "gnv$libzshr32" +$ if f$search(try_shr) .nes. "" +$ then +$ libzshr_line = "''try_shr'/share" +$ else +$ write sys$output "''try_shr' image not found!" +$ goto all_exit +$ endif +$! +$! +$ gssrtlshr_line = "" +$ if arch_name .nes. "VAX" +$ then +$ try_shr = "sys$share:gss$rtl" +$ if f$search("''try_shr'.exe") .nes. "" +$ then +$ gssrtlshr_line = "''try_shr'/share" +$ else +$ write sys$output "''try_shr' image not found!" +$ goto all_exit +$ endif +$ endif +$! +$! +$! +$ if f$search(share_link_opt_file) .eqs. "" +$ then +$ create 'share_link_opt_file' +$ open/append slopt 'share_link_opt_file' +$ if libzshr_line .nes. "" then write slopt libzshr_line +$ if gssrtlshr_line .nes. "" then write slopt gssrtlshr_line +$ write slopt "gnv$curl_ssl_libcryptoshr32/share" +$ write slopt "gnv$curl_ssl_libsslshr32/share" +$ close slopt +$ endif +$! +$! DCL build puts curllib in architecture directory +$! GNV build uses the makefile. +$ libfile = "[.packages.vms.''arch_name']curllib.olb" +$ if f$search(libfile) .nes. "" +$ then +$ olb_file = libfile +$ else +$ ! GNV based build +$ libfile = "[.lib.^.libs]libcurl.a" +$ if f$search(libfile) .nes. "" +$ then +$ olb_file = libfile +$ else +$ write sys$output - + "Can not build shared image, libcurl object library not found!" +$ goto all_exit +$ endif +$ endif +$! +$gnv_libcurl_share = "''default_dir'gnv$libcurl.exe" +$! +$ if f$search(gnv_libcurl_share) .eqs. "" +$ then +$ if arch_name .nes. "VAX" +$ then +$ define/user gnv$curl_ssl_libcryptoshr32 'curl_ssl_libcrypto32' +$ define/user gnv$curl_ssl_libsslshr32 'curl_ssl_libssl32' +$ link/dsf='default_dir'gnv$libcurl.dsf/share='gnv_libcurl_share' - + /map='default_dir'gnv$libcurl.map - + gnv_packages_vms:gnv_libcurl_symbols.opt/opt,- + 'olb_file'/lib,- + 'share_link_opt_file'/opt +$ else +$! VAX will not allow the logical name hack for the +$! SSL libcryto library, it is pulling it in twice if I try it. +$ link/share='gnv_libcurl_share'/map='default_dir'gnv$libcurl.map - + gnv_packages_vms:gnv_libcurl_xfer.opt/opt,- + 'olb_file'/lib,- + 'base_link_opt_file'/opt +$ endif +$ endif +$! +$! +$ if f$search("[.src]curl-tool_main.o") .nes. "" +$ then +$! From src/makefile.inc: +$! # libcurl has sources that provide functions named curlx_* that aren't +$! # part of the official API, but we reuse the code here to avoid +$! # duplication. +$! +$! +$ if f$search("[.src]curl.exe") .eqs. "" +$ then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.src]curl.exe/dsf=[.src]curl.dsf - + [.src]curl-tool_main.o, [.src]curl-tool_binmode.o, - + [.src]curl-tool_bname.o, [.src]curl-tool_cb_dbg.o, - + [.src]curl-tool_cb_hdr.o, [.src]curl-tool_cb_prg.o, - + [.src]curl-tool_cb_rea.o, [.src]curl-tool_cb_see.o, - + [.src]curl-tool_cb_wrt.o, [.src]curl-tool_cfgable.o, - + [.src]curl-tool_convert.o, [.src]curl-tool_dirhie.o, - + [.src]curl-tool_doswin.o, [.src]curl-tool_easysrc.o, - + [.src]curl-tool_formparse.o, [.src]curl-tool_getparam.o, - + [.src]curl-tool_getpass.o, [.src]curl-tool_help.o, - + [.src]curl-tool_helpers.o, [.src]curl-tool_homedir.o, - + [.src]curl-tool_hugehelp.o, [.src]curl-tool_libinfo.o, - + [.src]curl-tool_mfiles.o, - + [.src]curl-tool_msgs.o, [.src]curl-tool_operate.o, - + [.src]curl-tool_operhlp.o, - + [.src]curl-tool_paramhlp.o, [.src]curl-tool_parsecfg.o, - + [.src]curl-tool_setopt.o, [.src]curl-tool_sleep.o, - + [.src]curl-tool_urlglob.o, [.src]curl-tool_util.o, - + [.src]curl-tool_vms.o, [.src]curl-tool_writeenv.o, - + [.src]curl-tool_writeout.o, [.src]curl-tool_xattr.o, - + [.src]curl-strtoofft.o, [.src]curl-strdup.o, [.src]curl-strcase.o, - + [.src]curl-nonblock.o, gnv_packages_vms:curlmsg.obj,- + sys$input:/opt +gnv$libcurl/share +gnv_packages_vms:curl_crtl_init.obj +$ endif +$ else +$ curl_exe = "[.src]curl.exe" +$ curl_dsf = "[.src]curl.dsf" +$ curl_main = "[.packages.vms.''arch_name']tool_main.obj" +$ curl_src = "[.packages.vms.''arch_name']curlsrc.olb" +$ curl_lib = "[.packages.vms.''arch_name']curllib.olb" +$ strcase = "strcase" +$ nonblock = "nonblock" +$ warnless = "warnless" +$! +$! Extended parse style requires special quoting +$! +$ if (arch_name .nes. "VAX") .and. (parse_style .eqs. "EXTENDED") +$ then +$ strcase = """strcase""" +$ nonblock = """nonblock""" +$ warnless = """warnless""" +$ endif +$ if f$search(curl_exe) .eqs. "" +$ then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe='curl_exe'/dsf='curl_dsf' - + 'curl_main','curl_src'/lib, - + 'curl_lib'/library/include=- + ('strcase','nonblock','warnless'),- + gnv_packages_vms:curlmsg.obj,- + sys$input:/opt +gnv$libcurl/share +gnv_packages_vms:curl_crtl_init.obj +$ endif +$ endif +$! +$! +$! +$! in6addr_missing so skip building: +$! [.server]sws.o +$! [.server]sockfilt.o +$! [.server]tftpd.o +$! +$! +$ target = "10-at-a-time" +$ if f$search("[.docs.examples]''target'.o") .eqs. "" +$ then +$ write sys$output "examples not built" +$ goto all_exit +$ endif +$ if f$search("[.docs.examples]''target'.exe") .eqs. "" +$ then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$ endif +$! +$! +$ target = "anyauthput" +$ if f$search("[.docs.examples]''target'.exe") .eqs. "" +$ then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$ endif +$! +$! +$ target = "certinfo" +$ if f$search("[.docs.examples]''target'.exe") .eqs. "" +$ then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$ endif +$! +$! +$ target = "cookie_interface" +$ if f$search("[.docs.examples]''target'.exe") .eqs. "" +$ then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$ endif +$! +$! +$ target = "debug" +$ if f$search("[.docs.examples]''target'.exe") .eqs. "" +$ then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$ endif +$! +$! +$ target = "fileupload" +$ if f$search("[.docs.examples]''target'.exe") .eqs. "" +$ then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$ endif +$! +$! +$ target = "fopen" +$ if f$search("[.docs.examples]''target'.exe") .eqs. "" +$ then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$ endif +$! +$! +$target = "ftpget" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "ftpgetresp" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "ftpupload" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "getinfo" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "getinmemory" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "http-post" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "httpcustomheader" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "httpput" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "https" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "multi-app" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "multi-debugcallback" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "multi-double" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "multi-post" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "multi-single" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "persistent" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "post-callback" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "postit2" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "sendrecv" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "sepheaders" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "simple" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "simplepost" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! +$target = "simplessl" +$if f$search("[.docs.examples]''target'.exe") .eqs. "" +$then +$ define/user gnv$libcurl 'gnv_libcurl_share' +$ link'ldebug'/exe=[.docs.examples]'target'.exe- + /dsf=[.docs.examples]'target'.dsf - + [.docs.examples]'target'.o,- + gnv$'target'.opt/opt,- + sys$input:/opt +gnv$libcurl/share +$endif +$! +$! =============== End of docs/examples ========================= +$! +$! +$all_exit: +$set def 'default_dir' +$exit '$status' +$! diff --git a/third_party/curl/packages/vms/macro32_exactcase.patch b/third_party/curl/packages/vms/macro32_exactcase.patch new file mode 100644 index 0000000..eda5cac --- /dev/null +++ b/third_party/curl/packages/vms/macro32_exactcase.patch @@ -0,0 +1,11 @@ +macro32_exactcase.exe +SE EC +^X00000001 +RE /I +^X00012B1D +'BICB2 #^X00000020,R3' +EXIT +'BICB2 #^X00000000,R3' +EXI +U +EXI diff --git a/third_party/curl/packages/vms/make_gnv_curl_install.sh b/third_party/curl/packages/vms/make_gnv_curl_install.sh new file mode 100755 index 0000000..b85ef0c --- /dev/null +++ b/third_party/curl/packages/vms/make_gnv_curl_install.sh @@ -0,0 +1,44 @@ +# File: make_gnv_curl_install.sh +# +# Set up and run the make script for Curl. +# +# This makes the library, the curl binary and attempts an install. +# A search list should be set up for GNU (GNV$GNU). +# +# Copyright (C) John Malmberg +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# +# SPDX-License-Identifier: ISC +# +#========================================================================== +# +# +# Needed VMS build setups for GNV. +export GNV_OPT_DIR=. +export GNV_CC_QUALIFIERS=/DEBUG/OPTIMIZE/STANDARD=RELAXED\ +/float=ieee_float/ieee_mode=denorm_results +export GNV_CXX_QUALIFIERS=/DEBUG/OPTIMIZE/float=ieee/ieee_mode=denorm_results +export GNV_CC_NO_INC_PRIMARY=1 +# +# +# POSIX exit mode is needed for Unix shells. +export GNV_CC_MAIN_POSIX_EXIT=1 +make +cd ../.. +# adjust the libcurl.pc file, GNV currently ignores the Lib: line. +# but is noisy about it, so we just remove it. +sed -e 's/^Libs:/#Libs:/g' libcurl.pc > libcurl.pc_new +rm libcurl.pc +mv libcurl.pc_new libcurl.pc +make install diff --git a/third_party/curl/packages/vms/make_pcsi_curl_kit_name.com b/third_party/curl/packages/vms/make_pcsi_curl_kit_name.com new file mode 100644 index 0000000..956f7c1 --- /dev/null +++ b/third_party/curl/packages/vms/make_pcsi_curl_kit_name.com @@ -0,0 +1,188 @@ +$! File: MAKE_PCSI_CURL_KIT_NAME.COM +$! +$! Calculates the PCSI kit name for use in building an installation kit. +$! PCSI is HP's PolyCenter Software Installation Utility. +$! +$! The results are stored in as logical names so that other procedures +$! can use them. +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!======================================================================== +$! +$! Save default +$ default_dir = f$environment("DEFAULT") +$! +$! Move to the base directories +$ set def [--] +$! +$! Put things back on error. +$ on warning then goto all_exit +$! +$! The producer is the name or common abbreviation for the entity that is +$! making the kit. It must be set as a logical name before running this +$! procedure. +$! +$! HP documents the producer as the legal owner of the software, but for +$! open source work, it should document who is creating the package for +$! distribution. +$! +$ producer = f$trnlnm("GNV_PCSI_PRODUCER") +$ if producer .eqs. "" +$ then +$ write sys$output "The logical name GNV_PCSI_PRODUCER needs to be defined." +$ write sys$output "This should be set to the common abbreviation or name of" +$ write sys$output "the entity creating this kit. If you are an individual" +$ write sys$output "then use your initials." +$ goto all_exit +$ endif +$ producer_full_name = f$trnlnm("GNV_PCSI_PRODUCER_FULL_NAME") +$ if producer_full_name .eqs. "" +$ then +$ write sys$output "The logical name GNV_PCSI_PRODUCER_FULL_NAME needs to" +$ write sys$output "be defined. This should be set to the full name of" +$ write sys$output "the entity creating this kit. If you are an individual" +$ write sys$output "then use your name." +$ write sys$output "EX: DEFINE GNV_PCSI_PRODUCER_FULL_NAME ""First M. Last""" +$ goto all_exit +$ endif +$! +$ write sys$output "*****" +$ write sys$output "***** Producer = ''producer'" +$ write sys$output "*****" +$! +$! +$! Base is one of 'VMS', 'AXPVMS', 'I64VMS', 'VAXVMS' and indicates what +$! binaries are in the kit. A kit with just 'VMS' can be installed on all +$! architectures. +$! +$ base = "VMS" +$ arch_type = f$getsyi("ARCH_NAME") +$ code = f$extract(0, 1, arch_type) +$ if (code .eqs. "I") then base = "I64VMS" +$ if (code .eqs. "V") then base = "VAXVMS" +$ if (code .eqs. "A") then base = "AXPVMS" +$! +$! +$ product = "curl" +$! +$! +$! We need to get the version from curlver_h. It will have a line like +$! #define LIBCURL_VERSION "7.31.0" +$! or +$! #define LIBCURL_VERSION "7.32.0-20130731". +$! +$! The dash indicates that this is a daily pre-release. +$! +$! +$ open/read/error=version_loop_end vhf [.include.curl]curlver.h +$ version_loop: +$ read vhf line_in +$ if line_in .eqs. "" then goto version_loop +$ if f$locate("#define LIBCURL_VERSION ", line_in) .ne. 0 +$ then +$ goto version_loop +$ endif +$ raw_version = f$element(2," ", line_in) - """" - """" +$ version_loop_end: +$ close vhf +$! +$! +$ eco_level = "" +$ if f$search("''default_dir'vms_eco_level.h") .nes. "" +$ then +$ open/read ef 'default_dir'vms_eco_level.h +$ecolevel_loop: +$ read/end=ecolevel_loop_end ef line_in +$ prefix = f$element(0, " ", line_in) +$ if prefix .nes. "#define" then goto ecolevel_loop +$ key = f$element(1, " ", line_in) +$ value = f$element(2, " ", line_in) - """" - """" +$ if key .eqs. "VMS_ECO_LEVEL" +$ then +$ eco_level = "''value'" +$ if eco_level .eqs. "0" +$ then +$ eco_level = "" +$ else +$ eco_level = "E" + eco_level +$ endif +$ goto ecolevel_loop_end +$ endif +$ goto ecolevel_loop +$ecolevel_loop_end: +$ close ef +$ endif +$! +$! +$! This translates to V0732-0 or D0732-0 +$! We encode the snapshot date into the version as an ECO since a daily +$! can never have an ECO. +$! +$! version_type = 'V' for a production release, and 'D' for a build from a +$! daiy snapshot of the curl source. +$ majorver = f$element(0, ".", raw_version) +$ minorver = f$element(1, ".", raw_version) +$ raw_update = f$element(2, ".", raw_version) +$ update = f$element(0, "-", raw_update) +$ if update .eqs. "0" then update = "" +$ daily_tag = f$element(1, "-", raw_update) +$ vtype = "V" +$ patch = "" +$ if daily_tag .nes. "-" +$ then +$ vtype = "D" +$ daily_tag_len = f$length(daily_tag) +$ daily_tag = f$extract(4, daily_tag_len - 4, daily_tag) +$ patch = vtype + daily_tag +$ product = product + "_d" +$ else +$ daily_tag = "" +$ if eco_level .nes. "" then patch = eco_level +$ endif +$! +$! +$ version_fao = "!2ZB!2ZB" +$ mmversion = f$fao(version_fao, 'majorver', 'minorver') +$ version = vtype + "''mmversion'" +$ if update .nes. "" .or. patch .nes. "" +$ then +$! The presence of a patch implies an update +$ if update .eqs. "" .and. patch .nes. "" then update = "0" +$ version = version + "-" + update + patch +$ fversion = version +$ else +$ fversion = version +$ version = version + "-" +$ endif +$! +$! Kit type 1 is complete kit, the only type that this procedure will make. +$ kittype = 1 +$! +$! Write out a logical name for the resulting base kit name. +$ name = "''producer'-''base'-''product'-''version'-''kittype'" +$ define GNV_PCSI_KITNAME "''name'" +$ fname = "''product'-''fversion'" +$ define GNV_PCSI_FILENAME_BASE "''fname'" +$ write sys$output "*****" +$ write sys$output "***** GNV_PCSI_KITNAME = ''name'." +$ write sys$output "***** GNV_PCSI_FILENAME_BASE = ''fname'." +$ write sys$output "*****" +$! +$all_exit: +$ set def 'default_dir' +$ exit '$status' diff --git a/third_party/curl/packages/vms/pcsi_gnv_curl_file_list.txt b/third_party/curl/packages/vms/pcsi_gnv_curl_file_list.txt new file mode 100644 index 0000000..586f7e7 --- /dev/null +++ b/third_party/curl/packages/vms/pcsi_gnv_curl_file_list.txt @@ -0,0 +1,125 @@ +! File: PCSI_GNV_CURL_FILE_LIST.TXT +! +! File list for building a PCSI kit. +! Very simple format so that the parsing logic can be simple. +! links first, directory second, and files third. +! +! link -> file tells procedure to create/remove a link on install/uninstall +! If more than one link, consider using an alias file. +! +! [xxx.yyy]foo.dir is a directory file for the rename phase. +! [xxx.yyy.foo] is a directory file for the create phase. +! Each subdirectory needs to be on its own pair of lines. +! +! [xxx.yyy]file.ext is a file for the rename and add phases. +! +! Copyright (C) John Malmberg +! +! Permission to use, copy, modify, and/or distribute this software for any +! purpose with or without fee is hereby granted, provided that the above +! copyright notice and this permission notice appear in all copies. +! +! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +! +! SPDX-License-Identifier: ISC +! +!============================================================================ +[gnv.usr.bin]curl. -> [gnv.usr.bin]gnv$curl.exe +[gnv.usr.bin]curl.exe -> [gnv.usr.bin]gnv$curl.exe +[gnv] +[000000]gnv.dir +[gnv.usr] +[gnv]usr.dir +[gnv.usr]bin.dir +[gnv.usr.bin] +[gnv.usr]include.dir +[gnv.usr.include] +[gnv.usr.include]curl.dir +[gnv.usr.include.curl] +[gnv.usr]lib.dir +[gnv.usr.lib] +[gnv.usr.lib]pkgconfig.dir +[gnv.usr.lib.pkgconfig] +[gnv.usr]share.dir +[gnv.usr.share] +[gnv.usr.share]man.dir +[gnv.usr.share.man] +[gnv.usr.share.man]man1.dir +[gnv.usr.share.man.man1] +[gnv.usr.share.man]man3.dir +[gnv.usr.share.man.man3] +[gnv.usr.bin]curl-config. +[gnv.usr.bin]gnv$curl.exe +[gnv.usr.include.curl]curl.h +[gnv.usr.include.curl]system.h +[gnv.usr.include.curl]curlver.h +[gnv.usr.include.curl]easy.h +[gnv.usr.include.curl]mprintf.h +[gnv.usr.include.curl]multi.h +[gnv.usr.include.curl]stdcheaders.h +[gnv.usr.include.curl]typecheck-gcc.h +[gnv.usr.lib]gnv$libcurl.exe +[gnv.usr.lib]gnv$curlmsg.exe +[gnv.usr.lib.pkgconfig]libcurl.pc +[gnv.usr.share.man.man1]curl-config.1 +[gnv.usr.share.man.man1]curl.1 +[gnv.usr.share.man.man3]curl_easy_cleanup.3 +[gnv.usr.share.man.man3]curl_easy_duphandle.3 +[gnv.usr.share.man.man3]curl_easy_escape.3 +[gnv.usr.share.man.man3]curl_easy_getinfo.3 +[gnv.usr.share.man.man3]curl_easy_init.3 +[gnv.usr.share.man.man3]curl_easy_pause.3 +[gnv.usr.share.man.man3]curl_easy_perform.3 +[gnv.usr.share.man.man3]curl_easy_recv.3 +[gnv.usr.share.man.man3]curl_easy_reset.3 +[gnv.usr.share.man.man3]curl_easy_send.3 +[gnv.usr.share.man.man3]curl_easy_setopt.3 +[gnv.usr.share.man.man3]curl_easy_strerror.3 +[gnv.usr.share.man.man3]curl_easy_unescape.3 +[gnv.usr.share.man.man3]curl_escape.3 +[gnv.usr.share.man.man3]curl_formadd.3 +[gnv.usr.share.man.man3]curl_formfree.3 +[gnv.usr.share.man.man3]curl_formget.3 +[gnv.usr.share.man.man3]curl_free.3 +[gnv.usr.share.man.man3]curl_getdate.3 +[gnv.usr.share.man.man3]curl_getenv.3 +[gnv.usr.share.man.man3]curl_global_cleanup.3 +[gnv.usr.share.man.man3]curl_global_init.3 +[gnv.usr.share.man.man3]curl_global_init_mem.3 +[gnv.usr.share.man.man3]curl_mprintf.3 +[gnv.usr.share.man.man3]curl_multi_add_handle.3 +[gnv.usr.share.man.man3]curl_multi_assign.3 +[gnv.usr.share.man.man3]curl_multi_cleanup.3 +[gnv.usr.share.man.man3]curl_multi_fdset.3 +[gnv.usr.share.man.man3]curl_multi_info_read.3 +[gnv.usr.share.man.man3]curl_multi_init.3 +[gnv.usr.share.man.man3]curl_multi_perform.3 +[gnv.usr.share.man.man3]curl_multi_remove_handle.3 +[gnv.usr.share.man.man3]curl_multi_setopt.3 +[gnv.usr.share.man.man3]curl_multi_socket.3 +[gnv.usr.share.man.man3]curl_multi_socket_action.3 +[gnv.usr.share.man.man3]curl_multi_strerror.3 +[gnv.usr.share.man.man3]curl_multi_timeout.3 +[gnv.usr.share.man.man3]curl_multi_wait.3 +[gnv.usr.share.man.man3]curl_share_cleanup.3 +[gnv.usr.share.man.man3]curl_share_init.3 +[gnv.usr.share.man.man3]curl_share_setopt.3 +[gnv.usr.share.man.man3]curl_share_strerror.3 +[gnv.usr.share.man.man3]curl_slist_append.3 +[gnv.usr.share.man.man3]curl_slist_free_all.3 +[gnv.usr.share.man.man3]curl_strequal.3 +[gnv.usr.share.man.man3]curl_unescape.3 +[gnv.usr.share.man.man3]curl_version.3 +[gnv.usr.share.man.man3]curl_version_info.3 +[gnv.usr.share.man.man3]libcurl-easy.3 +[gnv.usr.share.man.man3]libcurl-errors.3 +[gnv.usr.share.man.man3]libcurl-multi.3 +[gnv.usr.share.man.man3]libcurl-share.3 +[gnv.usr.share.man.man3]libcurl-tutorial.3 +[gnv.usr.share.man.man3]libcurl.3 diff --git a/third_party/curl/packages/vms/pcsi_product_gnv_curl.com b/third_party/curl/packages/vms/pcsi_product_gnv_curl.com new file mode 100644 index 0000000..83d8fa3 --- /dev/null +++ b/third_party/curl/packages/vms/pcsi_product_gnv_curl.com @@ -0,0 +1,197 @@ +$! File: PCSI_PRODUCT_GNV_CURL.COM +$! +$! This command file packages up the product CURL into a sequential +$! format kit +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!========================================================================= +$! +$! Save default +$ default_dir = f$environment("DEFAULT") +$! +$! Put things back on error. +$ on warning then goto all_exit +$! +$! +$ can_build = 1 +$ producer = f$trnlnm("GNV_PCSI_PRODUCER") +$ if producer .eqs. "" +$ then +$ write sys$output "GNV_PCSI_PRODUCER logical name has not been set." +$ can_build = 0 +$ endif +$ producer_full_name = f$trnlnm("GNV_PCSI_PRODUCER_FULL_NAME") +$ if producer_full_name .eqs. "" +$ then +$ write sys$output - + "GNV_PCSI_PRODUCER_FULL_NAME logical name has not been set." +$ can_build = 0 +$ endif +$ stage_root_name = f$trnlnm("STAGE_ROOT") +$ if stage_root_name .eqs. "" +$ then +$ write sys$output "STAGE_ROOT logical name has not been set." +$ can_build = 0 +$ endif +$! +$ if (can_build .eq. 0) +$ then +$ write sys$output "Not able to build a kit." +$ goto all_exit +$ endif +$! +$! Make sure that the kit name is up to date for this build +$!---------------------------------------------------------- +$ @MAKE_PCSI_CURL_KIT_NAME.COM +$! +$! +$! Make sure that the image is built +$!---------------------------------- +$ arch_name = f$edit(f$getsyi("arch_name"),"UPCASE") +$ if f$search("[--.src]curl.exe") .eqs. "" +$ then +$ build_it = 1 +$ libfile = "[.packages.vms.''arch_name']curllib.olb" +$ if f$search(libfile) .nes. "" +$ then +$ build_it = 0 +$ else +$ ! GNV based build +$ libfile = "[.lib.^.libs]libcurl.a" +$ if f$search(libfile) .nes. "" +$ then +$ build_it = 0; +$ endif +$ endif +$ if build_it .eq. 1 +$ then +$ @build_vms list +$ endif +$ @gnv_link_curl.com +$ endif +$! +$! Make sure that the release note file name is up to date +$!--------------------------------------------------------- +$ @BUILD_GNV_CURL_RELEASE_NOTES.COM +$! +$! +$! Make sure that the source has been backed up. +$!---------------------------------------------- +$ arch_type = f$getsyi("ARCH_NAME") +$ arch_code = f$extract(0, 1, arch_type) +$ @backup_gnv_curl_src.com +$! +$! Regenerate the PCSI description file. +$!-------------------------------------- +$ @BUILD_GNV_CURL_PCSI_DESC.COM +$! +$! Regenerate the PCSI Text file. +$!--------------------------------- +$ @BUILD_GNV_CURL_PCSI_TEXT.COM +$! +$! +$! Parse the kit name into components. +$!--------------------------------------- +$ kit_name = f$trnlnm("GNV_PCSI_KITNAME") +$ if kit_name .eqs. "" +$ then +$ write sys$output "@MAKE_PCSI_CURL_KIT_NAME.COM has not been run." +$ goto all_exit +$ endif +$ producer = f$element(0, "-", kit_name) +$ base = f$element(1, "-", kit_name) +$ product_name = f$element(2, "-", kit_name) +$ mmversion = f$element(3, "-", kit_name) +$ majorver = f$extract(0, 3, mmversion) +$ minorver = f$extract(3, 2, mmversion) +$ updatepatch = f$element(4, "-", kit_name) +$ if updatepatch .eqs. "" then updatepatch = "" +$! +$ version_fao = "!AS.!AS" +$ mmversion = f$fao(version_fao, "''majorver'", "''minorver'") +$ if updatepatch .nes. "" +$ then +$ version = "''mmversion'" + "-" + updatepatch +$ else +$ version = "''mmversion'" +$ endif +$! +$ @stage_curl_install remove +$ @stage_curl_install +$! +$! Move to the base directories +$ set def [--] +$ current_default = f$environment("DEFAULT") +$ my_dir = f$parse(current_default,,,"DIRECTORY") - "[" - "<" - ">" - "]" +$! +$! +$! +$ source = "''default_dir'" +$ src1 = "new_gnu:[usr.bin]," +$ src2 = "new_gnu:[usr.include.curl]," +$ src3 = "new_gnu:[usr.lib]," +$ src4 = "new_gnu:[usr.lib.pkgconfig]," +$ src5 = "new_gnu:[usr.share.man.man1]," +$ src6 = "new_gnu:[usr.share.man.man3]," +$ src7 = "new_gnu:[vms_src]," +$ src8 = "new_gnu:[common_src]," +$ src9 = "prj_root:[''my_dir'],prj_root:[''my_dir'.src]" +$ gnu_src = src1 + src2 + src3 + src4 + src5 + src6 + src7 + src8 + src9 +$! +$! +$ base = "" +$ if arch_name .eqs. "ALPHA" then base = "AXPVMS" +$ if arch_name .eqs. "IA64" then base = "I64VMS" +$ if arch_name .eqs. "VAX" then base = "VAXVMS" +$! +$ if base .eqs. "" then exit 44 +$! +$ pcsi_option = "/option=noconfirm" +$ if arch_code .eqs. "V" +$ then +$ pcsi_option = "" +$ endif +$! +$! +$product package 'product_name' - + /base='base' - + /producer='producer' - + /source='source' - + /destination=STAGE_ROOT:[KIT] - + /material=('gnu_src','source') - + /format=sequential 'pcsi_option' +$! +$! +$! VAX can not do a compressed kit. +$! ZIP -9 "-V" does a better job, so no reason to normally build a compressed +$! kit. +$!---------------------------------- +$if p1 .eqs. "COMPRESSED" +$then +$ if arch_code .nes. "V" +$ then +$ product copy /options=(novalidate, noconfirm) /format=compressed - + 'product_name' - + /source=stage_root:[kit]/dest=stage_root:[kit] - + /version='version'/base='base' +$ endif +$endif +$! +$all_exit: +$ set def 'default_dir' +$ exit diff --git a/third_party/curl/packages/vms/readme b/third_party/curl/packages/vms/readme new file mode 100644 index 0000000..0bb6166 --- /dev/null +++ b/third_party/curl/packages/vms/readme @@ -0,0 +1,228 @@ + _ _ ____ _ + ___| | | | _ \| | + / __| | | | |_) | | + ( (__| |_| | _ <| |___ + \___|\___/|_| \_\_____| + for OpenVMS + +History: + + 9-MAR-2004, Created this readme. file. Marty Kuhrt (MSK). +15-MAR-2004, MSK, Updated to reflect the new files in this directory. +14-FEB-2005, MSK, removed config-vms.h_with* file comments +10-FEB-2010, SMS. General update. +14-Jul-2013, JEM, General Update, add GNV build information. + + +The release notes installed by the PCSI kit consist of this file and the +curl_gnv_build_steps.txt and other useful information. + +Prerequisites: + +OpenVMS V7.0 or later (any platform) +DECC V6.5 or later +OpenSSL or hp SSL, if you want SSL support + +What is Here: + +This directory contains the following files for a DCL based build. + +backup_gnv_curl_src.com This procedure backs up the source modules for + creating a PCSI kit. + +build_curl-config_script.com + Procedure to create the curl-config script. + +build_gnv_curl.com This procedure does a build of curl using the + GNV utilities and then uses DCL tools to build + the libcurl shared image. The setup_gnv_curl_build.com + procedure must be run first. + +build_gnv_curl_pcsi_desc.com + This procedure builds the pcsi$desc file for + creating a PCSI based package. + +build_gnv_curl_pcsi_text.com + This procedure builds the pcsi$text file for + creating a PCSI based package. + +build_gnv_curl_release_notes.com + This procedure creates the release notes for + a PCSI kit based on curl_release_note_start.txt, + this readme file, and the curl_gnv_build_steps.txt + +build_libcurl_pc.com Procedure to create a libcurl.pc file. + +build_vms.com DCL based build procedure. + +clean_gnv_curl.com This procedure cleans up the files generated by + a GNV based build. + +config_h.com DCL based procedure used by build_vms.com + to run generate the curl_config.h file. + This is a generic procedure that does most + of the work for generating config.h files. + +compare_curl_source.com Procedure to compare the working directory + with a repository directory or a backup staging + directory. + +curl_crtl_init.c A special pre-initialization routine to for + programs to behave more Unix like when run + under GNV. + +curl_gnv_build_steps.txt + Detailed instructions on how to built curl using + GNV and how to build the libcurl shared image and + PCSI kit. + +curl_release_note_start.txt + The first part of the curl release notes. + +curl_startup.com A procedure run at VMS startup to install the + libcurl shared image and to set up the needed + logical names. + +curlmsg.h C header defining curl status code macros. + +curlmsg.msg Error message source for curlmsg.h and curlmsg.sdl. + +curlmsg.sdl SDL source defining curl status code constants. + +curlmsg_vms.h Mapping of curl status codes to VMS-form codes. + +generate_config_vms_h_curl.com + DCL procedure to generate the curl specific + definitions for curl_config.h that config_h.com + can not properly generate. + +generate_vax_transfer.com + DCL procedure to read an Alpha/IA64 symbol vector + linker option file and generate the VAX transfer + vector modules. + +gnv_conftest.c_first A helper file for the configure script. + +gnv_curl_configure.sh A script to run the configure script with the + options needed for VMS. + +gnv_libcurl_symbols.opt The symbol vectors needed for Alpha and IA64 + libcurl shared image. + +gnv_link_curl.com Links the libcurl shared image and then links a curl + image to use the libcurl. + +macro32_exactcase.patch The patch file needed to modify VAX Macro32 to be + case sensitive and case preserving. + +Makefile.am curl kit file list for this directory. + +Makefile.in curl kit makefile source for this directory. + +make_gnv_curl_install.sh + Script to do a make install using GNV after running + the configure script. + +make_pcsi_curl_kit_name.com + This generates the name of the PCSI kit based on + the version of curl being built. + +pcsi_gnv_curl_file_list.txt + This is a text file describing what files should + be included in a PCSI kit. + +pcsi_product_gnv_curl.com + This generates the PCSI kit after the libcurl + shared image has been made. + +readme. This file. + +report_openssl_version.c + Program to check that the openssl version is new + enough for building a shared libcurl image. + +setup_gnv_curl_build.com + This procedure sets up symbols and logical names + for a GNV build environment and also copies some + helper files. + +stage_curl_install.com This procedure sets up new_gnu: directory tree to + for testing the install and building the PCSI kit. + It takes a "remove" option to remove all the staged + files. + +vms_eco_level.h This sets the ECO level for the PCSI kit name. + + +How to Build: + +The GNV based build and the DCL based build procedures are not compatible +and you must make sure that none of the build files are present before +running a different type of build. Use the "REALCLEAN" option for +BUILD_VMS.COM and the "REALCLEAN" option for clean_gnv_curl.com. + +The (brute-force) DCL based builder is [.packages.vms]build_vms.com. +Comments in this procedure describe various optional parameters which +enable or disable optional program features, or which control the build +in other ways. Product files (.EXE, .H, .LIS, .MAP, .OBJ, .OLB, ...) +should be produced in an architecture-specific subdirectory under this +directory ([.ALPHA], [.IA64], [.VAX]). + +The file curl_gnv_build_steps.txt contains information on building using +the GNV tool kit, building a shared libcurl, and producing a PCSI kit for +distribution. The curl_gnv_build_steps.text is included in the release +notes file of the PCSI kit. + +The building with 64 bit pointers does not currently work. + +The build procedure will detect if HP OpenSSL, LDAP, and Kerberos are +installed and default to building with them. + +The build procedure will also detect if a compatible ZLIB shared image +is installed from a PCSI kit and default to using it. + + Example build commands: + + @ [.packages.vms]build_vms.com CLEAN + @ [.packages.vms]build_vms.com LARGE LDAP + submit /noprint [.packages.vms]build_vms.com /param = (LARGE, LDAP) + +The build_vms.com procedure does not build the shared image file or the PCSI +kit. If you have built a curl with ZLIB and HPSSL support as well as if +LDAP and Kerberos installed, you can use the GNV_LINK_CURL.COM file. + +The GNV_LINK_CURL.COM contains information on how to link and run with a newer +version of HP SSL than what may be install on an Alpha or IA64 based system. + +To build the PCSI kit, follow the instructions in the file +curl_gnv_build_steps.txt. + +Other Notes: + +This release fixes known bugs #22, and #57 in the [curl.docs]known_bugs. +file. + +The libcurl formdata.c module and Curl tools post form now have some +understanding of VMS file types. Files will be posted in STREAM_LF format. + +The Curl tool now has some understanding of VMS file types and will upload the +files in STREAM_LF format. + +When CURL is uploading a VARIABLE format VMS file, it is less efficient as in +order to get the file size, it will first read the entire file once, and then +read the file again for the actual upload. + +The Curl tool will now always download files into STREAM_LF format. Even if a +file by that name with a different format already exists. This is needed to +allow interrupted downloads to be continued. + + +The libcurl file module still does not understand VMS file types and requires +the input files to be in STREAM_LF to work property. + +The test suites are not supported as of 7.11.0. + +The curlmsg.sdl and curlmsg.h files are generated from curlmsg.msg. +This is not done automatically, since the .MSG file is a hand edit +of the relevant stuff from the curl.h file. If you want to do this +yourself you'll need the SDL package from the freeware collection. diff --git a/third_party/curl/packages/vms/report_openssl_version.c b/third_party/curl/packages/vms/report_openssl_version.c new file mode 100644 index 0000000..64e1ee0 --- /dev/null +++ b/third_party/curl/packages/vms/report_openssl_version.c @@ -0,0 +1,100 @@ +/* File: report_openssl_version.c + * + * This file dynamically loads the openssl shared image to report the + * version string. + * + * It will optionally place that version string in a DCL symbol. + * + * Usage: report_openssl_version [] + * + * Copyright (C) John Malmberg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * SPDX-License-Identifier: ISC + * + */ + +#include +#include +#include + +#include +#include +#include +#include +#include + +unsigned long LIB$SET_SYMBOL( + const struct dsc$descriptor_s * symbol, + const struct dsc$descriptor_s * value, + const unsigned long * table_type); + +int main(int argc, char ** argv) { + + +void * libptr; +const char * (*ssl_version)(int t); +const char * version; + + if(argc < 1) { + puts("report_openssl_version filename"); + exit(1); + } + + libptr = dlopen(argv[1], 0); + + ssl_version = (const char * (*)(int))dlsym(libptr, "SSLeay_version"); + if(ssl_version == NULL) { + ssl_version = (const char * (*)(int))dlsym(libptr, "ssleay_version"); + if(ssl_version == NULL) { + ssl_version = (const char * (*)(int))dlsym(libptr, "SSLEAY_VERSION"); + } + } + + dlclose(libptr); + + if(ssl_version == NULL) { + puts("Unable to lookup version of OpenSSL"); + exit(1); + } + + version = ssl_version(SSLEAY_VERSION); + + puts(version); + + /* Was a symbol argument given? */ + if(argc > 1) { + int status; + struct dsc$descriptor_s symbol_dsc; + struct dsc$descriptor_s value_dsc; + const unsigned long table_type = LIB$K_CLI_LOCAL_SYM; + + symbol_dsc.dsc$a_pointer = argv[2]; + symbol_dsc.dsc$w_length = strlen(argv[2]); + symbol_dsc.dsc$b_dtype = DSC$K_DTYPE_T; + symbol_dsc.dsc$b_class = DSC$K_CLASS_S; + + value_dsc.dsc$a_pointer = (char *)version; /* Cast ok */ + value_dsc.dsc$w_length = strlen(version); + value_dsc.dsc$b_dtype = DSC$K_DTYPE_T; + value_dsc.dsc$b_class = DSC$K_CLASS_S; + + status = LIB$SET_SYMBOL(&symbol_dsc, &value_dsc, &table_type); + if(!$VMS_STATUS_SUCCESS(status)) { + exit(status); + } + } + + exit(0); +} diff --git a/third_party/curl/packages/vms/setup_gnv_curl_build.com b/third_party/curl/packages/vms/setup_gnv_curl_build.com new file mode 100644 index 0000000..1685b6a --- /dev/null +++ b/third_party/curl/packages/vms/setup_gnv_curl_build.com @@ -0,0 +1,286 @@ +$! File: setup_gnv_curl_build.com +$! +$! Set up build environment for building Curl under GNV on VMS. +$! +$! GNV needs some files moved into the other directories to help with +$! the configure script and the build. +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!======================================================================= +$! +$! Save this so we can get back. +$ default_dir = f$environment("default") +$! +$! Move to where the Configure script is. +$ set def [--] +$! +$! Get the path to where the Configure script is. +$ base_dir = f$environment("default") +$! +$! Allow arguments to be grouped together with comma or separated by spaces +$! Do no know if we will need more than 8. +$ args = "," + p1 + "," + p2 + "," + p3 + "," + p4 + "," +$ args = args + p5 + "," + p6 + "," + p7 + "," + p8 + "," +$! +$! Provide lower case version to simplify parsing. +$ args_lower = f$edit(args, "LOWERCASE,COLLAPSE") +$! +$ args_len = f$length(args) +$ args_lower_len = f$length(args_lower) +$! +$ tests = 0 +$ if f$locate(",test", args_lower) .lt. args_lower_len +$ then +$ tests = 1 +$ endif +$! +$ examples = 0 +$ if f$locate(",exam", args_lower) .lt. args_lower_len +$ then +$ examples = 1 +$ endif +$! +$! We want detailed build logs. +$ clist = "/list/show=(expan,includ)" +$! +$! We want full symbol names in exact case. Need a common +$! repository for all directories. +$ cnames = "/names=(shortened,as_is)/repository=''base_dir'" +$! +$! Set the compiler options for GNV CC wrapper to inherit. +$ cc :== cc'clist''cnames'/nested_include_directory=none +$ cxx :== cxx'clist''cnames'/nested_include_directory=none +$ pointer_size = "32" +$! Note 64 bit pointers requires all libraries to either have +$! 64 bit pointers or have #pragma directives. +$! Currently building curl on VMS with 64 bit pointers does not work. +$! +$! A logical name to make it easier to find some of the hacks. +$ define/job gnv_hacks 'base_dir' +$! +$! A logical name to find the [.packages.vms] directory where we started. +$ define/job gnv_packages_vms 'default_dir' +$! +$! Kerberos headers: +$ if f$trnlnm("gssapi") .eqs. "" +$ then +$ if f$search("sys$sysroot:[kerberos]include.dir") .nes. "" +$ then +$ define/job gssapi sys$sysroot:[kerberos.include] +$ endif +$ endif +$! +$! OpenSSL headers +$ if f$trnlnm("openssl") .eqs. "" +$ then +$ if f$trnlnm("ssl$include") .nes. "" +$ then +$ define/job openssl ssl$include: +$ endif +$ endif +$! +$! C compiler include path. +$ define/job decc$system_include prj_root:[.include.curl],- + [-.packages.vms],- + ssl$include:,gnv$gnu:[usr.include],- + gnv$gnu:[usr.include.libz],gnv$gnu:[include],- + gnv$zlib_include:,- + sys$sysroot:[kerberos.include] +$! +$! Set up an include list for the compiler to find all the header files +$! that they need. +$! +$ define/job decc$user_include src_root:[.include.curl] +$ define ssl_lib sys$library: +$! +$! Calculate what is needed in the option files +$ libzshr_line = "" +$ try_shr = "gnv$libzshr''pointer_size'" +$ if f$search(try_shr) .nes. "" then libzshr_line = "''try_shr'/share" +$ if (libzshr_line .eqs. "") +$ then +$ try_shr = "sys$share:" + try_shr +$ if f$search("''try_shr'.exe") .nes. "" +$ then +$ libzshr_line = "''try_shr'/share" +$ endif +$ endif +$! +$! Kerberos +$ gssrtlshr_line = "" +$ try_shr = "sys$share:gss$rtl" +$ if f$search("''try_shr'.exe") .nes. "" +$ then +$ gssrtlshr_line = "''try_shr'/share" +$ endif +$! +$! HP OpenSSL +$ libcryptoshr_line = "" +$ try_shr = "sys$share:ssl$libcrypto_shr''pointer_size'" +$ if f$search("''try_shr'.exe") .nes. "" +$ then +$ libcryptoshr_line = "''try_shr'/share" +$ endif +$! +$ libsslshr_line = "" +$ try_shr = "sys$share:ssl$libssl_shr''pointer_size'" +$ if f$search("''try_shr'.exe") .nes. "" +$ then +$ libsslshr_line = "''try_shr'/share" +$ endif +$! +$! +$! Copy over the gnv$conftest* files to base directory. +$!----------------------------------------------------- +$ copy 'default_dir'gnv_conftest.c_first 'base_dir'gnv$conftest.c_first +$ create 'base_dir'gnv$conftest.opt +$ open/append opt 'base_dir'gnv$conftest.opt +$ if libzshr_line .nes. "" then write opt libzshr_line +$ if libcryptoshr_line .nes. "" then write opt libcryptoshr_line +$ if libsslshr_line .nes. "" then write opt libsslshr_line +$ close opt +$ purge 'base_dir'gnv$conftest.* +$ rename 'base_dir'gnv$conftest.* ;1 +$! +$! +$! +$! GNV helper files for building the test curl binary. +$!----------------------------------------------- +$ create [.src]gnv$curl.opt +$ open/append opt [.src]gnv$curl.opt +$ write opt "gnv_packages_vms:curlmsg.obj" +$ if libzshr_line .nes. "" then write opt libzshr_line +$ if gssrtlshr_line .nes. "" then write opt gssrtlshr_line +$ if libcryptoshr_line .nes. "" then write opt libcryptoshr_line +$ if libsslshr_line .nes. "" then write opt libsslshr_line +$ close opt +$ purge [.src]gnv$*.* +$ rename [.src]gnv$*.* ;1 +$! +$! +$! Create the libcurl +$!------------------------------------------------------ +$ create 'default_dir'gnv_libcurl_linker.opt +$ open/append opt 'default_dir'gnv_libcurl_linker.opt +$ if libzshr_line .nes. "" then write opt libzshr_line +$ if gssrtlshr_line .nes. "" then write opt gssrtlshr_line +$ if libcryptoshr_line .nes. "" then write opt libcryptoshr_line +$ if libsslshr_line .nes. "" then write opt libsslshr_line +$ close opt +$! +$! +$! Create the template linker file +$!--------------------------------- +$ create 'default_dir'gnv_template_linker.opt +$ open/append opt 'default_dir'gnv_template_linker.opt +$ write opt "gnv_vms_common:vms_curl_init_unix.obj" +$ if libzshr_line .nes. "" then write opt libzshr_line +$ if gssrtlshr_line .nes. "" then write opt gssrtlshr_line +$ if libcryptoshr_line .nes. "" then write opt libcryptoshr_line +$ if libsslshr_line .nes. "" then write opt libsslshr_line +$ close opt +$! +$! Copy over the gnv$*.opt files for [.docs.examples] +$!---------------------------------------------------- +$ if examples .ne. 0 +$ then +$ example_apps = "10-at-a-time,anyauthput,certinfo,cookie_interface,debug" +$ example_apps = example_apps + ",fileupload,fopen,ftpget,ftpgetresp" +$ example_apps = example_apps + ",ftpupload,getinfo,getinmemory" +$ example_apps = example_apps + ",http-post,httpcustomheader,httpput" +$ example_apps = example_apps + ",https,multi-app,multi-debugcallback" +$ example_apps = example_apps + ",multi-double,multi-post,multi-single" +$ example_apps = example_apps + ",persistent,post-callback,postit2" +$ example_apps = example_apps + ",sendrecv,sepheaders,simple,simplepost" +$ example_apps = example_apps + ",simplessl" +$! +$ i = 0 +$example_loop: +$ ap_name = f$element(i, ",", example_apps) +$ if ap_name .eqs. "," then goto example_loop_end +$ if ap_name .eqs. "" then goto example_loop_end +$ copy 'default_dir'gnv_template_linker.opt - + [.docs.examples]gnv$'ap_name'.opt +$ i = i + 1 +$ goto example_loop +$example_loop_end: +$! +$! clean up the copy. +$ purge [.docs.examples]gnv$*.opt +$ rename [.docs.examples]gnv$*.opt ;1 +$ endif +$! +$! +$ if tests .ne. 0 +$ then +$ libtest_apps = "lib500,lib501,lib502,lib503,lib504,lib505,lib506,lib507" +$ libtest_apps = libtest_apps + ",lib508,lib510,lib511,lib512,lib513,lib514" +$ libtest_apps = libtest_apps + ",lib515,lib516,lib517,lib518,lib519,lib520" +$ libtest_apps = libtest_apps + ",lib521,lib523,lib524,lib525,lib526,lib527" +$ libtest_apps = libtest_apps + ",lib529,lib530,lib532,lib533,lib536,lib537" +$ libtest_apps = libtest_apps + ",lib539,lib540,lib541,lib542,lib543,lib544" +$ libtest_apps = libtest_apps + ",lib545,lib547,lib548,lib549,lib552,lib553" +$ libtest_apps = libtest_apps + ",lib554,lib555,lib556,lib557,lib558,lib559" +$ libtest_apps = libtest_apps + ",lib560,lib562,lib564" +$ i = 0 +$libtest_loop: +$ ap_name = f$element(i, ",", libtest_apps) +$ if ap_name .eqs. "," then goto libtest_loop_end +$ if ap_name .eqs. "" then goto libtest_loop_end +$ copy 'default_dir'gnv_template_linker.opt - + [.tests.libtest]gnv$'ap_name'.opt +$ i = i + 1 +$ goto libtest_loop +$libtest_loop_end: +$! +$! clean up the copy. +$ purge [.tests.libtest]gnv$*.opt +$ rename [.tests.libtest]gnv$*.opt ;1 +$ endif +$! +$! +$! Build the Message file. +$!-------------------------- +$ if f$search("[.packages.vms]curlmsg.obj") .eqs. "" +$ then +$ message [.packages.vms]curlmsg.msg/object=[.packages.vms] +$ endif +$ if f$search("gnv$curlmsg.exe") .eqs. "" +$ then +$ link/share=gnv$curlmsg.exe [.packages.vms]curlmsg.obj +$ endif +$! +$! +$! +$! Need to build the common init module. +$!------------------------------------------- +$ init_obj = "[.packages.vms]curl_crtl_init.obj" +$ if f$search(init_obj) .eqs. "" +$ then +$ cc'cflags' 'default_dir'curl_crtl_init.c/obj='init_obj' +$ purge 'init_obj' +$ rename 'init_obj' ;1 +$ endif +$! +$all_exit: +$! +$ set def 'default_dir' +$! +$! Verify can break things in bash, especially in Configure scripts. +$ set nover +$ exit diff --git a/third_party/curl/packages/vms/stage_curl_install.com b/third_party/curl/packages/vms/stage_curl_install.com new file mode 100644 index 0000000..10ae17a --- /dev/null +++ b/third_party/curl/packages/vms/stage_curl_install.com @@ -0,0 +1,170 @@ +$! File: stage_curl_install.com +$! +$! This updates or removes the GNV$CURL.EXE and related files for the +$! new_gnu:[*...] directory tree for running the self tests. +$! +$! The files installed/removed are: +$! [usr.bin]gnv$curl.exe +$! [usr.bin]curl-config. +$! [usr.lib]gnv$libcurl.exe +$! [usr.bin]curl. hard link for [usr.bin]gnv$curl.exe +$! [usr.include.curl]curl.h +$! [usr.include.curl]curlver.h +$! [usr.include.curl]easy.h +$! [usr.include.curl]mprintf.h +$! [usr.include.curl]multi.h +$! [usr.include.curl]stdcheaders.h +$! [usr.include.curl]typecheck-gcc.h +$! [usr.lib.pkgconfig]libcurl.pc +$! [usr.share.man.man1]curl-config.1 +$! [usr.share.man.man1]curl.1 +$! [usr.share.man.man3]curl*.3 +$! [usr.share.man.man3]libcurl*.3 +$! Future: A symbolic link to the release notes? +$! +$! Copyright (C) John Malmberg +$! +$! Permission to use, copy, modify, and/or distribute this software for any +$! purpose with or without fee is hereby granted, provided that the above +$! copyright notice and this permission notice appear in all copies. +$! +$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +$! +$! SPDX-License-Identifier: ISC +$! +$!=========================================================================== +$! +$ arch_type = f$getsyi("ARCH_NAME") +$ arch_code = f$extract(0, 1, arch_type) +$! +$ if arch_code .nes. "V" +$ then +$ set proc/parse=extended +$ endif +$! +$! +$! If the first parameter begins with "r" or "R" then this is to +$! remove the files instead of installing them. +$ remove_filesq = f$edit(p1, "upcase,trim") +$ remove_filesq = f$extract(0, 1, remove_filesq) +$ remove_files = 0 +$ if remove_filesq .eqs. "R" then remove_files = 1 +$! +$! +$! If we are staging files, make sure that the libcurl.pc and curl-config +$! files are present. +$ if remove_files .eq. 0 +$ then +$ if f$search("[--]libcurl.pc") .eqs. "" +$ then +$ @build_libcurl_pc.com +$ endif +$ if f$search("[--]curl-config") .eqs. "" +$ then +$ @build_curl-config_script.com +$ endif +$ endif +$! +$! +$! Dest dirs +$!------------------ +$ dest_dirs1 = "[usr],[usr.bin],[usr.include],[usr.include.curl]" +$ dest_dirs2 = ",[usr.bin],[usr.lib.pkgconfig],[usr.share]" +$ dest_dirs3 = ",[usr.share.man],[usr.share.man.man1],[usr.share.man.man3]" +$ dest_dirs = dest_dirs1 + dest_dirs2 + dest_dirs3 +$! +$! +$! Alias links needed. +$!------------------------- +$ source_curl = "gnv$curl.exe" +$ dest_curl = "[bin]gnv$curl.exe" +$ curl_links = "[bin]curl." +$ new_gnu = "new_gnu:" +$! +$! +$! Create the directories if they do not exist +$!--------------------------------------------- +$ i = 0 +$curl_dir_loop: +$ this_dir = f$element(i, ",", dest_dirs) +$ i = i + 1 +$ if this_dir .eqs. "" then goto curl_dir_loop +$ if this_dir .eqs. "," then goto curl_dir_loop_end +$! Just create the directories, do not delete them. +$! -------------------------------------------------- +$ if remove_files .eq. 0 +$ then +$ create/dir 'new_gnu''this_dir'/prot=(o:rwed) +$ endif +$ goto curl_dir_loop +$curl_dir_loop_end: +$! +$! +$! Need to add in the executable file +$!----------------------------------- +$ if remove_files .eq. 0 +$ then +$ copy [--.src]curl.exe 'new_gnu'[usr.bin]gnv$curl.exe/prot=w:re +$ copy [--]curl-config. 'new_gnu'[usr.bin]curl-config./prot=w:re +$ copy sys$disk:[]gnv$libcurl.exe 'new_gnu'[usr.lib]gnv$libcurl.exe/prot=w:re +$ endif +$! +$ if remove_files .eq. 0 +$ then +$ set file/enter='new_gnu'[bin]curl. 'new_gnu'[usr.bin]gnv$curl.exe +$ else +$ file = "''new_gnu'[bin]curl." +$ if f$search(file) .nes. "" then set file/remove 'file';* +$ endif +$! +$! +$ if remove_files .eq. 0 +$ then +$ copy [--.include.curl]curl.h 'new_gnu'[usr.include.curl]curl.h +$ copy [--.include.curl]system.h - + 'new_gnu'[usr.include.curl]system.h +$ copy [--.include.curl]curlver.h - + 'new_gnu'[usr.include.curl]curlver.h +$ copy [--.include.curl]easy.h - + 'new_gnu'[usr.include.curl]easy.h +$ copy [--.include.curl]mprintf.h - + 'new_gnu'[usr.include.curl]mprintf.h +$ copy [--.include.curl]multi.h - + 'new_gnu'[usr.include.curl]multi.h +$ copy [--.include.curl]stdcheaders.h - + 'new_gnu'[usr.include.curl]stdcheaders.h +$ copy [--.include.curl]typecheck-gcc.h - + 'new_gnu'[usr.include.curl]typecheck-gcc.h +$ copy [--]libcurl.pc 'new_gnu'[usr.lib.pkgconfig]libcurl.pc +$! +$ copy [--.docs]curl-config.1 'new_gnu'[usr.share.man.man1]curl-config.1 +$ copy [--.docs]curl.1 'new_gnu'[usr.share.man.man1]curl.1 +$! +$ copy [--.docs.libcurl]*.3 - + 'new_gnu'[usr.share.man.man3]*.3 +$! +$ else +$ file = "''new_gnu'[usr.bin]curl-config." +$ if f$search(file) .nes. "" then delete 'file';* +$ file = "''new_gnu'[usr.bin]gnv$curl.exe" +$ if f$search(file) .nes. "" then delete 'file';* +$ file = "''new_gnu'[usr.lib]gnv$libcurl.exe" +$ if f$search(file) .nes. "" then delete 'file';* +$ file = "''new_gnu'[usr.include.curl]*.h" +$ if f$search(file) .nes. "" then delete 'file';* +$ file = "''new_gnu'[usr.share.man.man1]curl-config.1" +$ if f$search(file) .nes. "" then delete 'file';* +$ file = "''new_gnu'[usr.share.man.man1]curl.1" +$ if f$search(file) .nes. "" then delete 'file';* +$ file = "''new_gnu'[usr.share.man.man3]curl*.3" +$ if f$search(file) .nes. "" then delete 'file';* +$ file = "''new_gnu'[usr.share.man.man3]libcurl*.3" +$ if f$search(file) .nes. "" then delete 'file';* +$ endif +$! diff --git a/third_party/curl/packages/vms/vms_eco_level.h b/third_party/curl/packages/vms/vms_eco_level.h new file mode 100644 index 0000000..89f1dfd --- /dev/null +++ b/third_party/curl/packages/vms/vms_eco_level.h @@ -0,0 +1,30 @@ +/* File: vms_eco_level.h + * + * Copyright (C) John Malmberg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * SPDX-License-Identifier: ISC + * + */ + +/* This file should be incremented for each ECO that is kit */ +/* for a specific curl x.y-z release. */ +/* When any part of x.y-z is incremented, the ECO should be set back to 0 */ + +#ifndef _VMS_ECO_LEVEL_H +#define _VMS_ECO_LEVEL_H + +#define VMS_ECO_LEVEL "0" + +#endif diff --git a/third_party/curl/plan9/README b/third_party/curl/plan9/README new file mode 100644 index 0000000..6df23d3 --- /dev/null +++ b/third_party/curl/plan9/README @@ -0,0 +1,55 @@ +Prerequirement +============== +This document describes how to compile, build and install curl and libcurl +from sources using mk. To build it, you will require to install latest +9legacy patches into Plan 9. Also Plan 9 still have no configuration option so +both zlib and libopenssl are required too. + +The zlib that is available on Plan 9 can be downloaded from: + + https://github.com/madler/zlib/pull/398 + +LibreSSL Portable can be downloaded from: + + https://github.com/libressl-portable/portable/pull/510 + +Instruction +=========== +First, you should construct namespace as like described below: + +% bind -ac ../lib lib +% bind -ac ../src src +% bind -ac ../include include +% bind -ac .. . + +Then you will see as shown below (excerpt): + + curl.git/ + |_plan9 + | |_BUILD.PLAN9.txt + | |_CHANGES + | |_CMake + | | : + | |_mkfile + | |_mkfile.proto + | |_include + | | |_Makefile.am + | | | : + | | |_mkfile + | |_lib + | | |_CMakeLists.txt + | | | : + | | |_mkfile + | | |_mkfile.inc + | |_src + | | |_CMakeLists.txt + | | | : + | | |_mkfile + | | |_mkfile.inc + |_lib + |_src + +After constructing namespace, you can run mk on plan9 directory. + +% mk +% mk install diff --git a/third_party/curl/plan9/include/mkfile b/third_party/curl/plan9/include/mkfile new file mode 100644 index 0000000..a0970e9 --- /dev/null +++ b/third_party/curl/plan9/include/mkfile @@ -0,0 +1,36 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +DIR=/sys/include/ape/curl +HFILES=`{ls curl/*.h} + +all:V: $HFILES + +install:V: all + mkdir -p $DIR + cp curl/*.h $DIR/ + +clean:V: $HFILES # do nothing + +nuke:V: clean diff --git a/third_party/curl/plan9/lib/mkfile b/third_party/curl/plan9/lib/mkfile new file mode 100644 index 0000000..04b54a8 --- /dev/null +++ b/third_party/curl/plan9/lib/mkfile @@ -0,0 +1,41 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +<../mkfile.proto +<|mkfile.inc + +CFLAGS=$CFLAGS -I../include -I. -c + +OFILES=${CSOURCES:%.c=%.$O} +HFILES=$HHEADERS +LIB=/$objtype/lib/ape/libcurl.a + +CLEANFILES=\ + ${LIB_VAUTH_CFILES:%.c=%.$O}\ + ${LIB_VTLS_CFILES:%.c=%.$O}\ + +, 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +# rename $(VAR) -> $VAR +sed 's/\$\(([A-Z_]+)\)/$\1/g' Makefile.inc diff --git a/third_party/curl/plan9/mkfile b/third_party/curl/plan9/mkfile new file mode 100644 index 0000000..2133a49 --- /dev/null +++ b/third_party/curl/plan9/mkfile @@ -0,0 +1,38 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +, 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +, 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +<../mkfile.proto +<|mkfile.inc + +CFLAGS=$CFLAGS -I../include -I../lib -c + +OFILES=${CURL_CFILES:%.c=%.$O} +HFILES=$CURL_HFILES + +LIB=\ + /$objtype/lib/ape/libcurl.a\ + /$objtype/lib/ape/libssl.a\ + /$objtype/lib/ape/libcrypto.a\ + /$objtype/lib/ape/libz.a\ + +BIN=/$objtype/bin +TARG=curl + +CLEANFILES=tool_hugehelp.c + +$target diff --git a/third_party/curl/plan9/src/mkfile.inc b/third_party/curl/plan9/src/mkfile.inc new file mode 100755 index 0000000..5c2cc12 --- /dev/null +++ b/third_party/curl/plan9/src/mkfile.inc @@ -0,0 +1,27 @@ +#!/bin/rc +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +# rename $(VAR) -> $VAR +sed 's/\$\(([A-Z_]+)\)/$\1/g' Makefile.inc diff --git a/third_party/curl/projects/README.md b/third_party/curl/projects/README.md new file mode 100644 index 0000000..4c4ea6e --- /dev/null +++ b/third_party/curl/projects/README.md @@ -0,0 +1,160 @@ + + +Building via IDE Project Files +============================== + +This document describes how to compile, build and install curl and libcurl +from sources using legacy versions of Visual Studio 2010 - 2013. + +You will need to generate the project files before using them. Please run +"generate -help" for usage details. + +To generate project files for recent versions of Visual Studio instead, use +cmake. Refer to INSTALL-CMAKE in the docs directory. + +## Directory Structure + +The following directory structure is used for the legacy project files: + + somedirectory\ + |_curl + |_projects + |_ + |_ + |_lib + |_src + +This structure allows for side-by-side compilation of curl on the same machine +using different versions of a given compiler (for example VC10 and VC12) and +allows for your own application or product to be compiled against those +variants of libcurl for example. + +Note: Typically this side-by-side compilation is generally only required when +a library is being compiled against dynamic runtime libraries. + +## Dependencies + +The projects files also support build configurations that require third party +dependencies such as OpenSSL, wolfSSL and libssh2. If you wish to support +these, you will also need to download and compile those libraries as well. + +To support compilation of these libraries using different versions of +compilers, the following directory structure has been used for both the output +of curl and libcurl as well as these dependencies. + + somedirectory\ + |_curl + | |_ build + | |_ + | |_ + | |_ + | |_lib + | |_src + | + |_openssl + | |_ build + | |_ + | |_VC + | |_ + | + |_libssh2 + |_ build + |_ + |_VC + |_ + +As OpenSSL and wolfSSL don't support side-by-side compilation when using +different versions of Visual Studio, build helper batch files have been +provided to assist with this. Please run `build-openssl -help` and/or +`build-wolfssl -help` for usage details. + +## Building with Visual C++ + +To build with VC++, you will of course have to first install VC++ which is +part of Visual Studio. + +Once you have VC++ installed you should launch the application and open one of +the solution or workspace files. The VC directory names are based on the +version of Visual C++ that you will be using. Each version of Visual Studio +has a default version of Visual C++. We offer these versions: + + - VC10 (Visual Studio 2010 Version 10.0) + - VC11 (Visual Studio 2012 Version 11.0) + - VC12 (Visual Studio 2013 Version 12.0) + +Separate solutions are provided for both libcurl and the curl command line +tool as well as a solution that includes both projects. libcurl.sln, curl.sln +and curl-all.sln, respectively. We recommend using curl-all.sln to build both +projects. + +For example, if you are using Visual Studio 2010 then you should be able to +use `VC10\curl-all.sln` to build curl and libcurl. + +## Running DLL based configurations + +If you are a developer and plan to run the curl tool from Visual Studio with +any third-party libraries (such as OpenSSL, wolfSSL or LibSSH2) then you will +need to add the search path of these DLLs to the configuration's PATH +environment. To do that: + + 1. Open the 'curl-all.sln' or 'curl.sln' solutions + 2. Right-click on the 'curl' project and select Properties + 3. Navigate to 'Configuration Properties > Debugging > Environment' + 4. Add `PATH='Path to DLL';C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem` + +... where 'Path to DLL` is the configuration specific path. For example the +following configurations in Visual Studio 2010 might be: + +DLL Debug - DLL OpenSSL (Win32): + + PATH=..\..\..\..\..\openssl\build\Win32\VC10\DLL Debug;C:\Windows\system32; + C:\Windows;C:\Windows\System32\Wbem + +DLL Debug - DLL OpenSSL (x64): + + PATH=..\..\..\..\..\openssl\build\Win64\VC10\DLL Debug;C:\Windows\system32; + C:\Windows;C:\Windows\System32\Wbem + +DLL Debug - DLL wolfSSL (Win32): + + PATH=..\..\..\..\..\wolfssl\build\Win32\VC10\DLL Debug;C:\Windows\system32; + C:\Windows;C:\Windows\System32\Wbem + +DLL Debug - DLL wolfSSL (x64): + + PATH=..\..\..\..\..\wolfssl\build\Win64\VC10\DLL Debug;C:\Windows\system32; + C:\Windows;C:\Windows\System32\Wbem + +If you are using a configuration that uses multiple third-party library DLLs +(such as DLL Debug - DLL OpenSSL - DLL LibSSH2) then 'Path to DLL' will need +to contain the path to both of these. + +## Notes + +The following keywords have been used in the directory hierarchy: + + - `` - The platform (For example: Windows) + - `` - The IDE (For example: VC10) + - `` - The platform architecture (For example: Win32, Win64) + - `` - The target configuration (For example: DLL Debug, LIB + Release - LIB OpenSSL) + +Should you wish to help out with some of the items on the TODO list, or find +bugs in the project files that need correcting, and would like to submit +updated files back then please note that, whilst the solution files can be +edited directly, the templates for the project files (which are stored in the +git repository) will need to be modified rather than the generated project +files that Visual Studio uses. + +## Legacy Windows and SSL + +Some of the project configurations allow the use of Schannel, the native SSL +library in Windows which forms part of Windows SSPI. However, Schannel in +Windows <= XP is unable to connect to servers that no longer support the +legacy handshakes and algorithms used by those versions. If you will be using +curl in one of those earlier versions of Windows you should choose another SSL +backend such as OpenSSL. diff --git a/third_party/curl/projects/build-openssl.bat b/third_party/curl/projects/build-openssl.bat new file mode 100644 index 0000000..0ded764 --- /dev/null +++ b/third_party/curl/projects/build-openssl.bat @@ -0,0 +1,739 @@ +@echo off +rem *************************************************************************** +rem * _ _ ____ _ +rem * Project ___| | | | _ \| | +rem * / __| | | | |_) | | +rem * | (__| |_| | _ <| |___ +rem * \___|\___/|_| \_\_____| +rem * +rem * Copyright (C) Steve Holme, . +rem * +rem * This software is licensed as described in the file COPYING, which +rem * you should have received as part of this distribution. The terms +rem * are also available at https://curl.se/docs/copyright.html. +rem * +rem * You may opt to use, copy, modify, merge, publish, distribute and/or sell +rem * copies of the Software, and permit persons to whom the Software is +rem * furnished to do so, under the terms of the COPYING file. +rem * +rem * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +rem * KIND, either express or implied. +rem * +rem * SPDX-License-Identifier: curl +rem * +rem *************************************************************************** + +:begin + rem Check we are running on a Windows NT derived OS + if not "%OS%" == "Windows_NT" goto nodos + + rem Set our variables + setlocal ENABLEDELAYEDEXPANSION + set BUILD_CONFIG= + set BUILD_PLATFORM= + set SAVED_PATH= + set SOURCE_PATH= + set TMP_BUILD_PATH= + set TMP_INSTALL_PATH= + set VC_VER= + + rem Ensure we have the required arguments + if /i "%~1" == "" goto syntax + + rem Calculate the program files directory + if defined PROGRAMFILES ( + set "PF=%PROGRAMFILES%" + set OS_PLATFORM=x86 + ) + if defined PROGRAMFILES(x86) ( + rem Visual Studio was x86-only prior to 14.3 + if /i "%~1" == "vc14.3" ( + set "PF=%PROGRAMFILES%" + ) else ( + set "PF=%PROGRAMFILES(x86)%" + ) + set OS_PLATFORM=x64 + ) + +:parseArgs + if not "%~1" == "" ( + if /i "%~1" == "vc10" ( + set VC_VER=10.0 + set VC_DESC=VC10 + set "VC_PATH=Microsoft Visual Studio 10.0\VC" + ) else if /i "%~1" == "vc11" ( + set VC_VER=11.0 + set VC_DESC=VC11 + set "VC_PATH=Microsoft Visual Studio 11.0\VC" + ) else if /i "%~1" == "vc12" ( + set VC_VER=12.0 + set VC_DESC=VC12 + set "VC_PATH=Microsoft Visual Studio 12.0\VC" + ) else if /i "%~1" == "vc14" ( + set VC_VER=14.0 + set VC_DESC=VC14 + set "VC_PATH=Microsoft Visual Studio 14.0\VC" + ) else if /i "%~1" == "vc14.1" ( + set VC_VER=14.1 + set VC_DESC=VC14.10 + + rem Determine the VC14.1 path based on the installed edition in descending + rem order (Enterprise, then Professional and finally Community) + if exist "%PF%\Microsoft Visual Studio\2017\Enterprise\VC" ( + set "VC_PATH=Microsoft Visual Studio\2017\Enterprise\VC" + ) else if exist "%PF%\Microsoft Visual Studio\2017\Professional\VC" ( + set "VC_PATH=Microsoft Visual Studio\2017\Professional\VC" + ) else ( + set "VC_PATH=Microsoft Visual Studio\2017\Community\VC" + ) + ) else if /i "%~1" == "vc14.2" ( + set VC_VER=14.2 + set VC_DESC=VC14.20 + + rem Determine the VC14.2 path based on the installed edition in descending + rem order (Enterprise, then Professional and finally Community) + if exist "%PF%\Microsoft Visual Studio\2019\Enterprise\VC" ( + set "VC_PATH=Microsoft Visual Studio\2019\Enterprise\VC" + ) else if exist "%PF%\Microsoft Visual Studio\2019\Professional\VC" ( + set "VC_PATH=Microsoft Visual Studio\2019\Professional\VC" + ) else ( + set "VC_PATH=Microsoft Visual Studio\2019\Community\VC" + ) + ) else if /i "%~1" == "vc14.3" ( + set VC_VER=14.3 + set VC_DESC=VC14.30 + + rem Determine the VC14.3 path based on the installed edition in descending + rem order (Enterprise, then Professional and finally Community) + if exist "%PF%\Microsoft Visual Studio\2022\Enterprise\VC" ( + set "VC_PATH=Microsoft Visual Studio\2022\Enterprise\VC" + ) else if exist "%PF%\Microsoft Visual Studio\2022\Professional\VC" ( + set "VC_PATH=Microsoft Visual Studio\2022\Professional\VC" + ) else ( + set "VC_PATH=Microsoft Visual Studio\2022\Community\VC" + ) + ) else if /i "%~1%" == "x86" ( + set BUILD_PLATFORM=x86 + ) else if /i "%~1%" == "x64" ( + set BUILD_PLATFORM=x64 + ) else if /i "%~1%" == "debug" ( + set BUILD_CONFIG=debug + ) else if /i "%~1%" == "release" ( + set BUILD_CONFIG=release + ) else if /i "%~1" == "-?" ( + goto syntax + ) else if /i "%~1" == "-h" ( + goto syntax + ) else if /i "%~1" == "-help" ( + goto syntax + ) else if /i "%~1" == "-VSpath" ( + if "%~2" == "" ( + echo. + echo Error. Please provide VS Path. + goto error + ) else ( + set "ABS_VC_PATH=%~2\VC" + shift + ) + ) else if /i "%~1" == "-perlpath" ( + if "%~2" == "" ( + echo. + echo Error. Please provide Perl root Path. + goto error + ) else ( + set "PERL_PATH=%~2" + shift + ) + ) else ( + if not defined START_DIR ( + set "START_DIR=%~1%" + ) else ( + goto unknown + ) + ) + + shift & goto parseArgs + ) + +:prerequisites + rem Compiler is a required parameter + if not defined VC_VER goto syntax + + rem Default the start directory if one isn't specified + if not defined START_DIR set START_DIR=..\..\openssl + + if not defined ABS_VC_PATH ( + rem Check we have a program files directory + if not defined PF goto nopf + set "ABS_VC_PATH=%PF%\%VC_PATH%" + ) + + rem Check we have Visual Studio installed + if not exist "%ABS_VC_PATH%" goto novc + + if not defined PERL_PATH ( + rem Check we have Perl in our path + perl --version NUL 2>&1 + if errorlevel 1 ( + rem It isn't so check we have it installed and set the path if it is + if exist "%SystemDrive%\Perl" ( + set "PATH=%SystemDrive%\Perl\bin;%PATH%" + ) else ( + if exist "%SystemDrive%\Perl64" ( + set "PATH=%SystemDrive%\Perl64\bin;%PATH%" + ) else ( + goto noperl + ) + ) + ) + ) else ( + set "PATH=%PERL_PATH%\Perl\bin;%PATH%" + ) + + rem Check the start directory exists + if not exist "%START_DIR%" goto noopenssl + +:setup + if "%BUILD_PLATFORM%" == "" ( + if "%VC_VER%" == "6.0" ( + set BUILD_PLATFORM=x86 + ) else if "%VC_VER%" == "7.0" ( + set BUILD_PLATFORM=x86 + ) else if "%VC_VER%" == "7.1" ( + set BUILD_PLATFORM=x86 + ) else ( + set BUILD_PLATFORM=%OS_PLATFORM% + ) + ) + + if "%BUILD_PLATFORM%" == "x86" ( + set VCVARS_PLATFORM=x86 + ) else if "%BUILD_PLATFORM%" == "x64" ( + if "%VC_VER%" == "10.0" set VCVARS_PLATFORM=%BUILD_PLATFORM% + if "%VC_VER%" == "11.0" set VCVARS_PLATFORM=amd64 + if "%VC_VER%" == "12.0" set VCVARS_PLATFORM=amd64 + if "%VC_VER%" == "14.0" set VCVARS_PLATFORM=amd64 + if "%VC_VER%" == "14.1" set VCVARS_PLATFORM=amd64 + if "%VC_VER%" == "14.2" set VCVARS_PLATFORM=amd64 + if "%VC_VER%" == "14.3" set VCVARS_PLATFORM=amd64 + ) + + if exist "%START_DIR%\ms\do_ms.bat" ( + set LEGACY_BUILD=TRUE + ) else ( + set LEGACY_BUILD=FALSE + ) + +:start + echo. + set "SAVED_PATH=%CD%" + + if "%VC_VER%" == "14.1" ( + call "%ABS_VC_PATH%\Auxiliary\Build\vcvarsall" %VCVARS_PLATFORM% + ) else if "%VC_VER%" == "14.2" ( + call "%ABS_VC_PATH%\Auxiliary\Build\vcvarsall" %VCVARS_PLATFORM% + ) else if "%VC_VER%" == "14.3" ( + call "%ABS_VC_PATH%\Auxiliary\Build\vcvarsall" %VCVARS_PLATFORM% + ) else ( + call "%ABS_VC_PATH%\vcvarsall" %VCVARS_PLATFORM% + ) + + echo. + + cd /d "%START_DIR%" || (echo Error: Failed cd start & exit /B 1) + rem Save the full path of the openssl source dir + set "SOURCE_PATH=%CD%" + + rem Set temporary paths for building and installing OpenSSL. If a temporary + rem path is not the same as the source path then it is *removed* after the + rem installation is completed. + rem + rem For legacy OpenSSL the temporary build path must be the source path. + rem + rem For OpenSSL 1.1.x the temporary paths must be separate not a descendant + rem of the other, otherwise pdb files will be lost between builds. + rem https://github.com/openssl/openssl/issues/10005 + rem + if "%LEGACY_BUILD%" == "TRUE" ( + set "TMP_BUILD_PATH=%SOURCE_PATH%" + set "TMP_INSTALL_PATH=%SOURCE_PATH%" + ) else ( + set "TMP_BUILD_PATH=%SOURCE_PATH%\build\tmp_build" + set "TMP_INSTALL_PATH=%SOURCE_PATH%\build\tmp_install" + ) + + goto %BUILD_PLATFORM% + +:x64 + rem Calculate our output directory + set OUTDIR=build\Win64\%VC_DESC% + if not exist %OUTDIR% md %OUTDIR% + + if not "%BUILD_CONFIG%" == "release" ( + rem Configuring 64-bit Static Library Debug Build + call :configure x64 debug static %LEGACY_BUILD% + + rem Perform the build + call :build x64 static %LEGACY_BUILD% + + rem Perform the install + call :install debug static %LEGACY_BUILD% + + rem Configuring 64-bit Shared Library Debug Build + call :configure x64 debug shared %LEGACY_BUILD% + + rem Perform the build + call :build x64 shared %LEGACY_BUILD% + + rem Perform the install + call :install debug shared %LEGACY_BUILD% + ) + + if not "%BUILD_CONFIG%" == "debug" ( + rem Configuring 64-bit Static Library Release Build + call :configure x64 release static %LEGACY_BUILD% + + rem Perform the build + call :build x64 static %LEGACY_BUILD% + + rem Perform the install + call :install release static %LEGACY_BUILD% + + rem Configuring 64-bit Shared Library Release Build + call :configure x64 release shared %LEGACY_BUILD% + + rem Perform the build + call :build x64 shared %LEGACY_BUILD% + + rem Perform the install + call :install release shared %LEGACY_BUILD% + ) + + goto success + +:x86 + rem Calculate our output directory + set OUTDIR=build\Win32\%VC_DESC% + if not exist %OUTDIR% md %OUTDIR% + + if not "%BUILD_CONFIG%" == "release" ( + rem Configuring 32-bit Static Library Debug Build + call :configure x86 debug static %LEGACY_BUILD% + + rem Perform the build + call :build x86 static %LEGACY_BUILD% + + rem Perform the install + call :install debug static %LEGACY_BUILD% + + rem Configuring 32-bit Shared Library Debug Build + call :configure x86 debug shared %LEGACY_BUILD% + + rem Perform the build + call :build x86 shared %LEGACY_BUILD% + + rem Perform the install + call :install debug shared %LEGACY_BUILD% + ) + + if not "%BUILD_CONFIG%" == "debug" ( + rem Configuring 32-bit Static Library Release Build + call :configure x86 release static %LEGACY_BUILD% + + rem Perform the build + call :build x86 static %LEGACY_BUILD% + + rem Perform the install + call :install release static %LEGACY_BUILD% + + rem Configuring 32-bit Shared Library Release Build + call :configure x86 release shared %LEGACY_BUILD% + + rem Perform the build + call :build x86 shared %LEGACY_BUILD% + + rem Perform the install + call :install release shared %LEGACY_BUILD% + ) + + goto success + +rem Function to configure the build. +rem +rem %1 - Platform (x86 or x64) +rem %2 - Configuration (release or debug) +rem %3 - Build Type (static or shared) +rem %4 - Build type (TRUE for legacy aka pre v1.1.0; otherwise FALSE) +rem +:configure + setlocal + + if "%1" == "" exit /B 1 + if "%2" == "" exit /B 1 + if "%3" == "" exit /B 1 + if "%4" == "" exit /B 1 + + if not exist "%TMP_BUILD_PATH%" mkdir "%TMP_BUILD_PATH%" + cd /d "%TMP_BUILD_PATH%" || (echo Error: Failed cd build & exit /B 1) + + if "%4" == "TRUE" ( + rem Calculate the configure options + if "%1" == "x86" ( + if "%2" == "debug" ( + set options=debug-VC-WIN32 + ) else if "%2" == "release" ( + set options=VC-WIN32 + ) else ( + exit /B 1 + ) + + set options=!options! no-asm + ) else if "%1" == "x64" ( + if "%2" == "debug" ( + set options=debug-VC-WIN64A + ) else if "%2" == "release" ( + set options=VC-WIN64A + ) else ( + exit /B 1 + ) + ) else ( + exit /B 1 + ) + ) else if "%4" == "FALSE" ( + rem Has configure already been ran? + if exist makefile ( + rem Clean up the previous build + nmake clean + + rem Remove the old makefile + del makefile 1>nul + ) + + rem Calculate the configure options + if "%1" == "x86" ( + set options=VC-WIN32 + ) else if "%1" == "x64" ( + set options=VC-WIN64A + ) else ( + exit /B 1 + ) + + if "%2" == "debug" ( + set options=!options! --debug + ) else if "%2" == "release" ( + set options=!options! --release + ) else ( + exit /B 1 + ) + + if "%3" == "static" ( + set options=!options! no-shared + ) else if not "%3" == "shared" ( + exit /B 1 + ) + + set options=!options! no-asm + ) else ( + exit /B 1 + ) + + rem Run the configure + perl "%SOURCE_PATH%\Configure" %options% "--prefix=%TMP_INSTALL_PATH%" + + exit /B %ERRORLEVEL% + +rem Main build function. +rem +rem %1 - Platform (x86 or x64) +rem %2 - Build Type (static or shared) +rem %3 - Build type (TRUE for legacy aka pre v1.1.0; otherwise FALSE) +rem +:build + setlocal + + if "%1" == "" exit /B 1 + if "%2" == "" exit /B 1 + if "%3" == "" exit /B 1 + + cd /d "%TMP_BUILD_PATH%" || (echo Error: Failed cd build & exit /B 1) + + if "%3" == "TRUE" ( + if "%1" == "x86" ( + call ms\do_ms.bat + ) else if "%1" == "x64" ( + call ms\do_win64a.bat + ) else ( + exit /B 1 + ) + + if "%2" == "static" ( + nmake -f ms\nt.mak + ) else if "%2" == "shared" ( + nmake -f ms\ntdll.mak + ) else ( + exit /B 1 + ) + ) else if "%3" == "FALSE" ( + nmake + ) else ( + exit /B 1 + ) + + exit /B 0 + +rem Main installation function. +rem +rem %1 - Configuration (release or debug) +rem %2 - Build Type (static or shared) +rem %3 - Build type (TRUE for legacy aka pre v1.1.0; otherwise FALSE) +rem +:install + setlocal + + if "%1" == "" exit /B 1 + if "%2" == "" exit /B 1 + if "%3" == "" exit /B 1 + + rem Copy the generated files to our directory structure + if "%3" == "TRUE" ( + rem There's no actual installation for legacy OpenSSL, the files are copied + rem from the build dir (for legacy this is same as source dir) to the final + rem location. + cd /d "%SOURCE_PATH%" || (echo Error: Failed cd source & exit /B 1) + if "%1" == "debug" ( + if "%2" == "static" ( + rem Move the output directories + if exist "%OUTDIR%\LIB Debug" ( + copy /y out32.dbg\* "%OUTDIR%\LIB Debug" 1>nul + rd out32.dbg /s /q + ) else ( + move out32.dbg "%OUTDIR%\LIB Debug" 1>nul + ) + + rem Move the PDB files + move tmp32.dbg\lib.pdb "%OUTDIR%\LIB Debug" 1>nul + + rem Remove the intermediate directories + rd tmp32.dbg /s /q + ) else if "%2" == "shared" ( + if exist "%OUTDIR%\DLL Debug" ( + copy /y out32dll.dbg\* "%OUTDIR%\DLL Debug" 1>nul + rd out32dll.dbg /s /q + ) else ( + move out32dll.dbg "%OUTDIR%\DLL Debug" 1>nul + ) + + rem Move the PDB files + move tmp32dll.dbg\lib.pdb "%OUTDIR%\DLL Debug" 1>nul + + rem Remove the intermediate directories + rd tmp32dll.dbg /s /q + ) else ( + exit /B 1 + ) + ) else if "%1" == "release" ( + if "%2" == "static" ( + rem Move the output directories + if exist "%OUTDIR%\LIB Release" ( + copy /y out32\* "%OUTDIR%\LIB Release" 1>nul + rd out32 /s /q + ) else ( + move out32 "%OUTDIR%\LIB Release" 1>nul + ) + + rem Move the PDB files + move tmp32\lib.pdb "%OUTDIR%\LIB Release" 1>nul + + rem Remove the intermediate directories + rd tmp32 /s /q + ) else if "%2" == "shared" ( + if exist "%OUTDIR%\DLL Release" ( + copy /y out32dll\* "%OUTDIR%\DLL Release" 1>nul + rd out32dll /s /q + ) else ( + move out32dll "%OUTDIR%\DLL Release" 1>nul + ) + + rem Move the PDB files + move tmp32dll\lib.pdb "%OUTDIR%\DLL Release" 1>nul + + rem Remove the intermediate directories + rd tmp32dll /s /q + ) else ( + exit /B 1 + ) + ) + ) else if "%3" == "FALSE" ( + cd /d "%TMP_BUILD_PATH%" || (echo Error: Failed cd build & exit /B 1) + + rem Perform the installation + nmake install_sw + + cd /d "%SOURCE_PATH%" || (echo Error: Failed cd source & exit /B 1) + + rem Move the output directories + if "%1" == "debug" ( + if "%2" == "static" ( + if not exist "%OUTDIR%\LIB Debug" ( + mkdir "%OUTDIR%\LIB Debug" 1>nul + ) + + move "%TMP_INSTALL_PATH%\lib\*.lib" "%OUTDIR%\LIB Debug" 1>nul + move "%TMP_INSTALL_PATH%\lib\*.pdb" "%OUTDIR%\LIB Debug" 1>nul + move "%TMP_INSTALL_PATH%\bin\*.exe" "%OUTDIR%\LIB Debug" 1>nul + move "%TMP_INSTALL_PATH%\bin\*.pdb" "%OUTDIR%\LIB Debug" 1>nul + xcopy /E /I /Y "%TMP_INSTALL_PATH%\include" "%OUTDIR%\LIB Debug\include" 1>nul + ) else if "%2" == "shared" ( + if not exist "%OUTDIR%\DLL Debug" ( + mkdir "%OUTDIR%\DLL Debug" 1>nul + ) + + move "%TMP_INSTALL_PATH%\lib\*.lib" "%OUTDIR%\DLL Debug" 1>nul + if exist "%TMP_INSTALL_PATH%\lib\engines-3" ( + move "%TMP_INSTALL_PATH%\lib\engines-3\*.dll" "%OUTDIR%\DLL Debug" 1>nul + move "%TMP_INSTALL_PATH%\lib\engines-3\*.pdb" "%OUTDIR%\DLL Debug" 1>nul + ) else if exist "%TMP_INSTALL_PATH%\lib\engines-1_1" ( + move "%TMP_INSTALL_PATH%\lib\engines-1_1\*.dll" "%OUTDIR%\DLL Debug" 1>nul + move "%TMP_INSTALL_PATH%\lib\engines-1_1\*.pdb" "%OUTDIR%\DLL Debug" 1>nul + ) + move "%TMP_INSTALL_PATH%\bin\*.dll" "%OUTDIR%\DLL Debug" 1>nul + move "%TMP_INSTALL_PATH%\bin\*.exe" "%OUTDIR%\DLL Debug" 1>nul + move "%TMP_INSTALL_PATH%\bin\*.pdb" "%OUTDIR%\DLL Debug" 1>nul + xcopy /E /I /Y "%TMP_INSTALL_PATH%\include" "%OUTDIR%\DLL Debug\include" 1>nul + ) else ( + exit /B 1 + ) + ) else if "%1" == "release" ( + if "%2" == "static" ( + if not exist "%OUTDIR%\LIB Release" ( + mkdir "%OUTDIR%\LIB Release" 1>nul + ) + + move "%TMP_INSTALL_PATH%\lib\*.lib" "%OUTDIR%\LIB Release" 1>nul + move "%TMP_INSTALL_PATH%\lib\*.pdb" "%OUTDIR%\LIB Release" 1>nul + move "%TMP_INSTALL_PATH%\bin\*.exe" "%OUTDIR%\LIB Release" 1>nul + move "%TMP_INSTALL_PATH%\bin\*.pdb" "%OUTDIR%\LIB Release" 1>nul + xcopy /E /I /Y "%TMP_INSTALL_PATH%\include" "%OUTDIR%\LIB Release\include" 1>nul + ) else if "%2" == "shared" ( + if not exist "%OUTDIR%\DLL Release" ( + mkdir "%OUTDIR%\DLL Release" 1>nul + ) + + move "%TMP_INSTALL_PATH%\lib\*.lib" "%OUTDIR%\DLL Release" 1>nul + if exist "%TMP_INSTALL_PATH%\lib\engines-3" ( + move "%TMP_INSTALL_PATH%\lib\engines-3\*.dll" "%OUTDIR%\DLL Release" 1>nul + move "%TMP_INSTALL_PATH%\lib\engines-3\*.pdb" "%OUTDIR%\DLL Release" 1>nul + ) else if exist "%TMP_INSTALL_PATH%\lib\engines-1_1" ( + move "%TMP_INSTALL_PATH%\lib\engines-1_1\*.dll" "%OUTDIR%\DLL Release" 1>nul + move "%TMP_INSTALL_PATH%\lib\engines-1_1\*.pdb" "%OUTDIR%\DLL Release" 1>nul + ) + move "%TMP_INSTALL_PATH%\bin\*.dll" "%OUTDIR%\DLL Release" 1>nul + move "%TMP_INSTALL_PATH%\bin\*.exe" "%OUTDIR%\DLL Release" 1>nul + move "%TMP_INSTALL_PATH%\bin\*.pdb" "%OUTDIR%\DLL Release" 1>nul + xcopy /E /I /Y "%TMP_INSTALL_PATH%\include" "%OUTDIR%\DLL Release\include" 1>nul + ) else ( + exit /B 1 + ) + ) else ( + exit /B 1 + ) + + rem Remove the output directories + if not "%SOURCE_PATH%" == "%TMP_BUILD_PATH%" ( + rd "%TMP_BUILD_PATH%" /s /q + ) + if not "%SOURCE_PATH%" == "%TMP_INSTALL_PATH%" ( + rd "%TMP_INSTALL_PATH%" /s /q + ) + ) else ( + exit /B 1 + ) + + exit /B 0 + +:syntax + rem Display the help + echo. + echo Usage: build-openssl ^ [platform] [configuration] [directory] [-VSpath] ["VSpath"] [-perlpath] ["perlpath"] + echo. + echo Compiler: + echo. + echo vc10 - Use Visual Studio 2010 + echo vc11 - Use Visual Studio 2012 + echo vc12 - Use Visual Studio 2013 + echo vc14 - Use Visual Studio 2015 + echo vc14.1 - Use Visual Studio 2017 + echo vc14.2 - Use Visual Studio 2019 + echo vc14.3 - Use Visual Studio 2022 + echo. + echo Platform: + echo. + echo x86 - Perform a 32-bit build + echo x64 - Perform a 64-bit build + echo. + echo Configuration: + echo. + echo debug - Perform a debug build + echo release - Perform a release build + echo. + echo Other: + echo. + echo directory - Specifies the OpenSSL source directory + echo. + echo -VSpath - Specify the custom VS path if Visual Studio is not located at + echo "C:\\Microsoft Visual Studio " + echo For e.g. -VSpath "C:\apps\MVS14" + echo. + echo -perlpath - Specify the custom perl root path if perl is not located at + echo "C:\Perl" and it is a portable copy of perl and not + echo installed on the win system. + echo For e.g. -perlpath "D:\strawberry-perl-5.24.3.1-64bit-portable" + goto error + +:unknown + echo. + echo Error: Unknown argument '%1' + goto error + +:nodos + echo. + echo Error: Only a Windows NT based Operating System is supported + goto error + +:nopf + echo. + echo Error: Cannot obtain the directory for Program Files + goto error + +:novc + echo. + echo Error: %VC_DESC% is not installed + echo Error: Please check whether Visual compiler is installed at the path "%ABS_VC_PATH%" + echo Error: Please provide proper VS Path by using -VSpath + goto error + +:noperl + echo. + echo Error: Perl is not installed + echo Error: Please check whether Perl is installed or it is at location "C:\Perl" + echo Error: If Perl is portable please provide perl root path by using -perlpath + goto error + +:nox64 + echo. + echo Error: %VC_DESC% does not support 64-bit builds + goto error + +:noopenssl + echo. + echo Error: Cannot locate OpenSSL source directory + goto error + +:error + if "%OS%" == "Windows_NT" endlocal + exit /B 1 + +:success + cd /d "%SAVED_PATH%" + endlocal + exit /B 0 diff --git a/third_party/curl/projects/build-wolfssl.bat b/third_party/curl/projects/build-wolfssl.bat new file mode 100644 index 0000000..1ceaa62 --- /dev/null +++ b/third_party/curl/projects/build-wolfssl.bat @@ -0,0 +1,429 @@ +@echo off +rem *************************************************************************** +rem * _ _ ____ _ +rem * Project ___| | | | _ \| | +rem * / __| | | | |_) | | +rem * | (__| |_| | _ <| |___ +rem * \___|\___/|_| \_\_____| +rem * +rem * Copyright (C) Steve Holme, . +rem * Copyright (C) Jay Satiro, . +rem * +rem * This software is licensed as described in the file COPYING, which +rem * you should have received as part of this distribution. The terms +rem * are also available at https://curl.se/docs/copyright.html. +rem * +rem * You may opt to use, copy, modify, merge, publish, distribute and/or sell +rem * copies of the Software, and permit persons to whom the Software is +rem * furnished to do so, under the terms of the COPYING file. +rem * +rem * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +rem * KIND, either express or implied. +rem * +rem * SPDX-License-Identifier: curl +rem * +rem *************************************************************************** + +:begin + rem Check we are running on a Windows NT derived OS + if not "%OS%" == "Windows_NT" goto nodos + + rem Set our variables + setlocal + set SUCCESSFUL_BUILDS= + set VC_VER= + set BUILD_PLATFORM= + set DEFAULT_START_DIR=..\..\wolfssl + + rem Calculate the program files directory + if defined PROGRAMFILES ( + set "PF=%PROGRAMFILES%" + set OS_PLATFORM=x86 + ) + if defined PROGRAMFILES(x86) ( + rem Visual Studio was x86-only prior to 14.3 + if /i "%~1" == "vc14.3" ( + set "PF=%PROGRAMFILES%" + ) else ( + set "PF=%PROGRAMFILES(x86)%" + ) + set OS_PLATFORM=x64 + ) + + rem Ensure we have the required arguments + if /i "%~1" == "" goto syntax + +:parseArgs + if "%~1" == "" goto prerequisites + + if /i "%~1" == "vc10" ( + set VC_VER=10.0 + set VC_DESC=VC10 + set VC_TOOLSET=v100 + set "VC_PATH=Microsoft Visual Studio 10.0\VC" + ) else if /i "%~1" == "vc11" ( + set VC_VER=11.0 + set VC_DESC=VC11 + set VC_TOOLSET=v110 + set "VC_PATH=Microsoft Visual Studio 11.0\VC" + ) else if /i "%~1" == "vc12" ( + set VC_VER=12.0 + set VC_DESC=VC12 + set VC_TOOLSET=v120 + set "VC_PATH=Microsoft Visual Studio 12.0\VC" + ) else if /i "%~1" == "vc14" ( + set VC_VER=14.0 + set VC_DESC=VC14 + set VC_TOOLSET=v140 + set "VC_PATH=Microsoft Visual Studio 14.0\VC" + ) else if /i "%~1" == "vc14.1" ( + set VC_VER=14.1 + set VC_DESC=VC14.10 + set VC_TOOLSET=v141 + + rem Determine the VC14.1 path based on the installed edition in descending + rem order (Enterprise, then Professional and finally Community) + if exist "%PF%\Microsoft Visual Studio\2017\Enterprise\VC" ( + set "VC_PATH=Microsoft Visual Studio\2017\Enterprise\VC" + ) else if exist "%PF%\Microsoft Visual Studio\2017\Professional\VC" ( + set "VC_PATH=Microsoft Visual Studio\2017\Professional\VC" + ) else ( + set "VC_PATH=Microsoft Visual Studio\2017\Community\VC" + ) + ) else if /i "%~1" == "vc14.2" ( + set VC_VER=14.2 + set VC_DESC=VC14.20 + set VC_TOOLSET=v142 + + rem Determine the VC14.2 path based on the installed edition in descending + rem order (Enterprise, then Professional and finally Community) + if exist "%PF%\Microsoft Visual Studio\2019\Enterprise\VC" ( + set "VC_PATH=Microsoft Visual Studio\2019\Enterprise\VC" + ) else if exist "%PF%\Microsoft Visual Studio\2019\Professional\VC" ( + set "VC_PATH=Microsoft Visual Studio\2019\Professional\VC" + ) else ( + set "VC_PATH=Microsoft Visual Studio\2019\Community\VC" + ) + ) else if /i "%~1" == "vc14.3" ( + set VC_VER=14.3 + set VC_DESC=VC14.30 + set VC_TOOLSET=v143 + + rem Determine the VC14.3 path based on the installed edition in descending + rem order (Enterprise, then Professional and finally Community) + if exist "%PF%\Microsoft Visual Studio\2022\Enterprise\VC" ( + set "VC_PATH=Microsoft Visual Studio\2022\Enterprise\VC" + ) else if exist "%PF%\Microsoft Visual Studio\2022\Professional\VC" ( + set "VC_PATH=Microsoft Visual Studio\2022\Professional\VC" + ) else ( + set "VC_PATH=Microsoft Visual Studio\2022\Community\VC" + ) + ) else if /i "%~1" == "x86" ( + set BUILD_PLATFORM=x86 + ) else if /i "%~1" == "x64" ( + set BUILD_PLATFORM=x64 + ) else if /i "%~1" == "debug" ( + set BUILD_CONFIG=debug + ) else if /i "%~1" == "release" ( + set BUILD_CONFIG=release + ) else if /i "%~1" == "-?" ( + goto syntax + ) else if /i "%~1" == "-h" ( + goto syntax + ) else if /i "%~1" == "-help" ( + goto syntax + ) else ( + if not defined START_DIR ( + set START_DIR=%~1 + ) else ( + goto unknown + ) + ) + + shift & goto parseArgs + +:prerequisites + rem Compiler is a required parameter + if not defined VC_VER goto syntax + + rem Default the start directory if one isn't specified + if not defined START_DIR set "START_DIR=%DEFAULT_START_DIR%" + + rem Check we have a program files directory + if not defined PF goto nopf + + rem Check we have Visual Studio installed + if not exist "%PF%\%VC_PATH%" goto novc + + rem Check the start directory exists + if not exist "%START_DIR%" goto nowolfssl + +:configure + if "%BUILD_PLATFORM%" == "" set BUILD_PLATFORM=%OS_PLATFORM% + + if "%BUILD_PLATFORM%" == "x86" ( + set VCVARS_PLATFORM=x86 + ) else if "%BUILD_PLATFORM%" == "x64" ( + if "%VC_VER%" == "10.0" set VCVARS_PLATFORM=%BUILD_PLATFORM% + if "%VC_VER%" == "11.0" set VCVARS_PLATFORM=amd64 + if "%VC_VER%" == "12.0" set VCVARS_PLATFORM=amd64 + if "%VC_VER%" == "14.0" set VCVARS_PLATFORM=amd64 + if "%VC_VER%" == "14.1" set VCVARS_PLATFORM=amd64 + if "%VC_VER%" == "14.2" set VCVARS_PLATFORM=amd64 + if "%VC_VER%" == "14.3" set VCVARS_PLATFORM=amd64 + ) + +:start + echo. + set SAVED_PATH=%CD% + + if "%VC_VER%" == "14.1" ( + call "%PF%\%VC_PATH%\Auxiliary\Build\vcvarsall" %VCVARS_PLATFORM% + ) else if "%VC_VER%" == "14.2" ( + call "%PF%\%VC_PATH%\Auxiliary\Build\vcvarsall" %VCVARS_PLATFORM% + ) else if "%VC_VER%" == "14.3" ( + call "%PF%\%VC_PATH%\Auxiliary\Build\vcvarsall" %VCVARS_PLATFORM% + ) else ( + call "%PF%\%VC_PATH%\vcvarsall" %VCVARS_PLATFORM% + ) + + echo. + cd /d %SAVED_PATH% + if defined START_DIR cd /d %START_DIR% + goto %BUILD_PLATFORM% + +:x64 + rem Calculate our output directory + set OUTDIR=build\Win64\%VC_DESC% + if not exist %OUTDIR% md %OUTDIR% + + if "%BUILD_CONFIG%" == "release" goto x64release + +:x64debug + rem Perform 64-bit Debug Build + + call :build Debug x64 + if errorlevel 1 goto error + + call :build "DLL Debug" x64 + if errorlevel 1 goto error + + if "%BUILD_CONFIG%" == "debug" goto success + +:x64release + rem Perform 64-bit Release Build + + call :build Release x64 + if errorlevel 1 goto error + + call :build "DLL Release" x64 + if errorlevel 1 goto error + + goto success + +:x86 + rem Calculate our output directory + set OUTDIR=build\Win32\%VC_DESC% + if not exist %OUTDIR% md %OUTDIR% + + if "%BUILD_CONFIG%" == "release" goto x86release + +:x86debug + rem Perform 32-bit Debug Build + + call :build Debug Win32 + if errorlevel 1 goto error + + call :build "DLL Debug" Win32 + if errorlevel 1 goto error + + if "%BUILD_CONFIG%" == "debug" goto success + +:x86release + rem Perform 32-bit Release Build + + call :build Release Win32 + if errorlevel 1 goto error + + call :build "DLL Release" Win32 + if errorlevel 1 goto error + + goto success + +:build + rem This function builds wolfSSL. + rem Usage: CALL :build + rem The current directory must be the wolfSSL directory. + rem VS Configuration: Debug, Release, DLL Debug or DLL Release. + rem VS Platform: Win32 or x64. + rem Returns: 1 on fail, 0 on success. + rem An informational message should be shown before any return. + setlocal + set MSBUILD_CONFIG=%~1 + set MSBUILD_PLATFORM=%~2 + + if not exist wolfssl64.sln ( + echo. + echo Error: build: wolfssl64.sln not found in "%CD%" + exit /b 1 + ) + + rem OUTDIR isn't a full path, only relative. MSBUILD_OUTDIR must be full and + rem not have trailing backslashes, which are handled later. + if "%MSBUILD_CONFIG%" == "Debug" ( + set "MSBUILD_OUTDIR=%CD%\%OUTDIR%\LIB Debug" + ) else if "%MSBUILD_CONFIG%" == "Release" ( + set "MSBUILD_OUTDIR=%CD%\%OUTDIR%\LIB Release" + ) else if "%MSBUILD_CONFIG%" == "DLL Debug" ( + set "MSBUILD_OUTDIR=%CD%\%OUTDIR%\DLL Debug" + ) else if "%MSBUILD_CONFIG%" == "DLL Release" ( + set "MSBUILD_OUTDIR=%CD%\%OUTDIR%\DLL Release" + ) else ( + echo. + echo Error: build: Configuration not recognized. + exit /b 1 + ) + + if not "%MSBUILD_PLATFORM%" == "Win32" if not "%MSBUILD_PLATFORM%" == "x64" ( + echo. + echo Error: build: Platform not recognized. + exit /b 1 + ) + + copy /v /y "%~dp0\wolfssl_options.h" .\cyassl\options.h + if %ERRORLEVEL% neq 0 ( + echo. + echo Error: build: Couldn't replace .\cyassl\options.h + exit /b 1 + ) + + copy /v /y "%~dp0\wolfssl_options.h" .\wolfssl\options.h + if %ERRORLEVEL% neq 0 ( + echo. + echo Error: build: Couldn't replace .\wolfssl\options.h + exit /b 1 + ) + + rem Extra trailing \ in Dirs because otherwise it thinks a quote is escaped + msbuild wolfssl64.sln ^ + -p:CustomAfterMicrosoftCommonTargets="%~dp0\wolfssl_override.props" ^ + -p:Configuration="%MSBUILD_CONFIG%" ^ + -p:Platform="%MSBUILD_PLATFORM%" ^ + -p:PlatformToolset="%VC_TOOLSET%" ^ + -p:OutDir="%MSBUILD_OUTDIR%\\" ^ + -p:IntDir="%MSBUILD_OUTDIR%\obj\\" + + if %ERRORLEVEL% neq 0 ( + echo. + echo Error: Failed building wolfSSL %MSBUILD_CONFIG%^|%MSBUILD_PLATFORM%. + exit /b 1 + ) + + rem For tests to run properly the wolfSSL directory must remain the current. + set "PATH=%MSBUILD_OUTDIR%;%PATH%" + "%MSBUILD_OUTDIR%\testsuite.exe" + + if %ERRORLEVEL% neq 0 ( + echo. + echo Error: Failed testing wolfSSL %MSBUILD_CONFIG%^|%MSBUILD_PLATFORM%. + exit /b 1 + ) + + echo. + echo Success: Built and tested wolfSSL %MSBUILD_CONFIG%^|%MSBUILD_PLATFORM%. + echo. + echo. + rem This is necessary to export our local variables back to the caller. + endlocal & set SUCCESSFUL_BUILDS="%MSBUILD_CONFIG%|%MSBUILD_PLATFORM%" ^ + %SUCCESSFUL_BUILDS% + exit /b 0 + +:syntax + rem Display the help + echo. + echo Usage: build-wolfssl ^ [platform] [configuration] [directory] + echo. + echo. + echo Compiler: + echo. + echo vc10 - Use Visual Studio 2010 + echo vc11 - Use Visual Studio 2012 + echo vc12 - Use Visual Studio 2013 + echo vc14 - Use Visual Studio 2015 + echo vc14.1 - Use Visual Studio 2017 + echo vc14.2 - Use Visual Studio 2019 + echo vc14.3 - Use Visual Studio 2022 + echo. + echo. + echo Platform: + echo. + echo x86 - Perform a 32-bit build + echo x64 - Perform a 64-bit build + echo. + echo If this parameter is unset the OS platform is used ^(%OS_PLATFORM%^). + echo. + echo. + echo Configuration: + echo. + echo debug - Perform a debug build + echo release - Perform a release build + echo. + echo If this parameter is unset both configurations are built. + echo. + echo. + echo Other: + echo. + echo directory - Specifies the wolfSSL source directory + echo. + echo If this parameter is unset the directory used is "%DEFAULT_START_DIR%". + echo. + goto error + +:unknown + echo. + echo Error: Unknown argument '%1' + goto error + +:nodos + echo. + echo Error: Only a Windows NT based Operating System is supported + goto error + +:nopf + echo. + echo Error: Cannot obtain the directory for Program Files + goto error + +:novc + echo. + echo Error: %VC_DESC% is not installed + goto error + +:nox64 + echo. + echo Error: %VC_DESC% does not support 64-bit builds + goto error + +:nowolfssl + echo. + echo Error: Cannot locate wolfSSL source directory, expected "%START_DIR%" + goto error + +:error + if "%OS%" == "Windows_NT" endlocal + exit /B 1 + +:success + if defined SUCCESSFUL_BUILDS ( + echo. + echo. + echo Build complete. + echo. + echo The following configurations were built and tested successfully: + echo. + echo %SUCCESSFUL_BUILDS% + echo. + ) + cd /d %SAVED_PATH% + endlocal + exit /B 0 diff --git a/third_party/curl/projects/checksrc.bat b/third_party/curl/projects/checksrc.bat new file mode 100644 index 0000000..af0ff1e --- /dev/null +++ b/third_party/curl/projects/checksrc.bat @@ -0,0 +1,225 @@ +@echo off +rem *************************************************************************** +rem * _ _ ____ _ +rem * Project ___| | | | _ \| | +rem * / __| | | | |_) | | +rem * | (__| |_| | _ <| |___ +rem * \___|\___/|_| \_\_____| +rem * +rem * Copyright (C) Steve Holme, . +rem * +rem * This software is licensed as described in the file COPYING, which +rem * you should have received as part of this distribution. The terms +rem * are also available at https://curl.se/docs/copyright.html. +rem * +rem * You may opt to use, copy, modify, merge, publish, distribute and/or sell +rem * copies of the Software, and permit persons to whom the Software is +rem * furnished to do so, under the terms of the COPYING file. +rem * +rem * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +rem * KIND, either express or implied. +rem * +rem * SPDX-License-Identifier: curl +rem * +rem *************************************************************************** + +:begin + rem Check we are running on a Windows NT derived OS + if not "%OS%" == "Windows_NT" goto nodos + + rem Set our variables + setlocal + set CHECK_LIB=TRUE + set CHECK_SRC=TRUE + set CHECK_TESTS=TRUE + set CHECK_EXAMPLES=TRUE + set SRC_DIR= + set CUR_DIR=%cd% + set ARG0_DIR=%~dp0 + +:parseArgs + if "%~1" == "" goto prerequisites + + if /i "%~1" == "-?" ( + goto syntax + ) else if /i "%~1" == "-h" ( + goto syntax + ) else if /i "%~1" == "-help" ( + goto syntax + ) else if /i "%~1" == "lib" ( + set CHECK_LIB=TRUE + set CHECK_SRC=FALSE + set CHECK_TESTS=FALSE + set CHECK_EXAMPLES=FALSE + ) else if /i "%~1" == "src" ( + set CHECK_LIB=FALSE + set CHECK_SRC=TRUE + set CHECK_TESTS=FALSE + set CHECK_EXAMPLES=FALSE + ) else if /i "%~1" == "tests" ( + set CHECK_LIB=FALSE + set CHECK_SRC=FALSE + set CHECK_TESTS=TRUE + set CHECK_EXAMPLES=FALSE + ) else if /i "%~1" == "examples" ( + set CHECK_LIB=FALSE + set CHECK_SRC=FALSE + set CHECK_TESTS=FALSE + set CHECK_EXAMPLES=TRUE + ) else ( + if not defined SRC_DIR ( + set SRC_DIR=%~1% + ) else ( + goto unknown + ) + ) + + shift & goto parseArgs + +:prerequisites + rem Check we have Perl in our path + perl --version NUL 2>&1 + if errorlevel 1 ( + rem It isn't so check we have it installed and set the path if it is + if exist "%SystemDrive%\Perl" ( + set "PATH=%SystemDrive%\Perl\bin;%PATH%" + ) else ( + if exist "%SystemDrive%\Perl64" ( + set "PATH=%SystemDrive%\Perl64\bin;%PATH%" + ) else ( + goto noperl + ) + ) + ) + +:configure + if "%SRC_DIR%" == "" ( + rem Are we being executed from the "projects" or main directory? + if "%CUR_DIR%\" == "%ARG0_DIR%" ( + set SRC_DIR=.. + ) else if exist projects ( + if exist docs ( + if exist lib ( + if exist src ( + if exist tests ( + set SRC_DIR=. + ) + ) + ) + ) + ) + ) + if not exist "%SRC_DIR%" goto nosrc + +:start + if "%CHECK_SRC%" == "TRUE" ( + rem Check the src directory + if exist %SRC_DIR%\src ( + for /f "delims=" %%i in ('dir "%SRC_DIR%\src\*.c.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\src" -Wtool_hugehelp.c "%%i" + for /f "delims=" %%i in ('dir "%SRC_DIR%\src\*.h.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\src" "%%i" + ) + ) + + if "%CHECK_LIB%" == "TRUE" ( + rem Check the lib directory + if exist %SRC_DIR%\lib ( + for /f "delims=" %%i in ('dir "%SRC_DIR%\lib\*.c.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\lib" "%%i" + for /f "delims=" %%i in ('dir "%SRC_DIR%\lib\*.h.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\lib" -Wcurl_config.h.cmake -Wcurl_config.h.in -Wcurl_config.h "%%i" + ) + + rem Check the lib\vauth directory + if exist %SRC_DIR%\lib\vauth ( + for /f "delims=" %%i in ('dir "%SRC_DIR%\lib\vauth\*.c.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\lib\vauth" "%%i" + for /f "delims=" %%i in ('dir "%SRC_DIR%\lib\vauth\*.h.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\lib\vauth" "%%i" + ) + + rem Check the lib\vquic directory + if exist %SRC_DIR%\lib\vquic ( + for /f "delims=" %%i in ('dir "%SRC_DIR%\lib\vquic\*.c.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\lib\vquic" "%%i" + for /f "delims=" %%i in ('dir "%SRC_DIR%\lib\vquic\*.h.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\lib\vquic" "%%i" + ) + + rem Check the lib\vssh directory + if exist %SRC_DIR%\lib\vssh ( + for /f "delims=" %%i in ('dir "%SRC_DIR%\lib\vssh\*.c.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\lib\vssh" "%%i" + for /f "delims=" %%i in ('dir "%SRC_DIR%\lib\vssh\*.h.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\lib\vssh" "%%i" + ) + + rem Check the lib\vtls directory + if exist %SRC_DIR%\lib\vtls ( + for /f "delims=" %%i in ('dir "%SRC_DIR%\lib\vtls\*.c.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\lib\vtls" "%%i" + for /f "delims=" %%i in ('dir "%SRC_DIR%\lib\vtls\*.h.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\lib\vtls" "%%i" + ) + ) + + if "%CHECK_TESTS%" == "TRUE" ( + rem Check the tests\libtest directory + if exist %SRC_DIR%\tests\libtest ( + for /f "delims=" %%i in ('dir "%SRC_DIR%\tests\libtest\*.c.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\tests\libtest" "%%i" + for /f "delims=" %%i in ('dir "%SRC_DIR%\tests\libtest\*.h.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\tests\libtest" "%%i" + ) + + rem Check the tests\unit directory + if exist %SRC_DIR%\tests\unit ( + for /f "delims=" %%i in ('dir "%SRC_DIR%\tests\unit\*.c.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\tests\unit" "%%i" + for /f "delims=" %%i in ('dir "%SRC_DIR%\tests\unit\*.h.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\tests\unit" "%%i" + ) + + rem Check the tests\server directory + if exist %SRC_DIR%\tests\server ( + for /f "delims=" %%i in ('dir "%SRC_DIR%\tests\server\*.c.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\tests\server" "%%i" + for /f "delims=" %%i in ('dir "%SRC_DIR%\tests\server\*.h.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\tests\server" "%%i" + ) + ) + + if "%CHECK_EXAMPLES%" == "TRUE" ( + rem Check the docs\examples directory + if exist %SRC_DIR%\docs\examples ( + for /f "delims=" %%i in ('dir "%SRC_DIR%\docs\examples\*.c.*" /b 2^>NUL') do @perl "%SRC_DIR%\scripts\checksrc.pl" "-D%SRC_DIR%\docs\examples" -ASNPRINTF "%%i" + ) + ) + + goto success + +:syntax + rem Display the help + echo. + echo Usage: checksrc [what] [directory] + echo. + echo What to scan: + echo. + echo lib - Scan the libcurl source + echo src - Scan the command-line tool source + echo tests - Scan the library tests and unit tests + echo examples - Scan the examples + echo. + echo directory - Specifies the curl source directory + goto success + +:unknown + echo. + echo Error: Unknown argument '%1' + goto error + +:nodos + echo. + echo Error: Only a Windows NT based Operating System is supported + goto error + +:noperl + echo. + echo Error: Perl is not installed + goto error + +:nosrc + echo. + echo Error: "%SRC_DIR%" does not exist + goto error + +:error + if "%OS%" == "Windows_NT" endlocal + exit /B 1 + +:success + endlocal + exit /B 0 diff --git a/third_party/curl/projects/generate.bat b/third_party/curl/projects/generate.bat new file mode 100644 index 0000000..7022eed --- /dev/null +++ b/third_party/curl/projects/generate.bat @@ -0,0 +1,357 @@ +@echo off +rem *************************************************************************** +rem * _ _ ____ _ +rem * Project ___| | | | _ \| | +rem * / __| | | | |_) | | +rem * | (__| |_| | _ <| |___ +rem * \___|\___/|_| \_\_____| +rem * +rem * Copyright (C) Steve Holme, . +rem * +rem * This software is licensed as described in the file COPYING, which +rem * you should have received as part of this distribution. The terms +rem * are also available at https://curl.se/docs/copyright.html. +rem * +rem * You may opt to use, copy, modify, merge, publish, distribute and/or sell +rem * copies of the Software, and permit persons to whom the Software is +rem * furnished to do so, under the terms of the COPYING file. +rem * +rem * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +rem * KIND, either express or implied. +rem * +rem * SPDX-License-Identifier: curl +rem * +rem *************************************************************************** + +:begin + rem Check we are running on a Windows NT derived OS + if not "%OS%" == "Windows_NT" goto nodos + + rem Set our variables + setlocal ENABLEEXTENSIONS + set VERSION=ALL + set MODE=GENERATE + + rem Check we are not running on a network drive + if "%~d0."=="\\." goto nonetdrv + + rem Switch to this batch file's directory + cd /d "%~0\.." 1>NUL 2>&1 + + rem Check we are running from a curl git repository + if not exist ..\GIT-INFO.md goto norepo + +:parseArgs + if "%~1" == "" goto start + + if /i "%~1" == "pre" ( + set VERSION=PRE + ) else if /i "%~1" == "vc10" ( + set VERSION=VC10 + ) else if /i "%~1" == "vc11" ( + set VERSION=VC11 + ) else if /i "%~1" == "vc12" ( + set VERSION=VC12 + ) else if /i "%~1" == "-clean" ( + set MODE=CLEAN + ) else if /i "%~1" == "-?" ( + goto syntax + ) else if /i "%~1" == "/?" ( + goto syntax + ) else if /i "%~1" == "-h" ( + goto syntax + ) else if /i "%~1" == "-help" ( + goto syntax + ) else if /i "%~1" == "--help" ( + goto syntax + ) else ( + goto unknown + ) + + shift & goto parseArgs + +:start + if exist ..\buildconf.bat ( + if "%MODE%" == "GENERATE" ( + call ..\buildconf + ) else if "%VERSION%" == "PRE" ( + call ..\buildconf -clean + ) else if "%VERSION%" == "ALL" ( + call ..\buildconf -clean + ) + ) + if "%VERSION%" == "PRE" goto success + if "%VERSION%" == "VC10" goto vc10 + if "%VERSION%" == "VC11" goto vc11 + if "%VERSION%" == "VC12" goto vc12 + +:vc10 + echo. + + if "%MODE%" == "GENERATE" ( + echo Generating VC10 project files + call :generate vcxproj Windows\VC10\src\curl.tmpl Windows\VC10\src\curl.vcxproj + call :generate vcxproj Windows\VC10\lib\libcurl.tmpl Windows\VC10\lib\libcurl.vcxproj + ) else ( + echo Removing VC10 project files + call :clean Windows\VC10\src\curl.vcxproj + call :clean Windows\VC10\lib\libcurl.vcxproj + ) + + if not "%VERSION%" == "ALL" goto success + +:vc11 + echo. + + if "%MODE%" == "GENERATE" ( + echo Generating VC11 project files + call :generate vcxproj Windows\VC11\src\curl.tmpl Windows\VC11\src\curl.vcxproj + call :generate vcxproj Windows\VC11\lib\libcurl.tmpl Windows\VC11\lib\libcurl.vcxproj + ) else ( + echo Removing VC11 project files + call :clean Windows\VC11\src\curl.vcxproj + call :clean Windows\VC11\lib\libcurl.vcxproj + ) + + if not "%VERSION%" == "ALL" goto success + +:vc12 + echo. + + if "%MODE%" == "GENERATE" ( + echo Generating VC12 project files + call :generate vcxproj Windows\VC12\src\curl.tmpl Windows\VC12\src\curl.vcxproj + call :generate vcxproj Windows\VC12\lib\libcurl.tmpl Windows\VC12\lib\libcurl.vcxproj + ) else ( + echo Removing VC12 project files + call :clean Windows\VC12\src\curl.vcxproj + call :clean Windows\VC12\lib\libcurl.vcxproj + ) + + goto success + +rem Main generate function. +rem +rem %1 - Project Type (vcxproj for VC10, VC11, VC12, VC14, VC14.10, VC14.20 and VC14.30) +rem %2 - Input template file +rem %3 - Output project file +rem +:generate + if not exist %2 ( + echo. + echo Error: Cannot open %2 + exit /B + ) + + if exist %3 ( + del %3 + ) + + echo * %CD%\%3 + for /f "usebackq delims=" %%i in (`"findstr /n ^^ %2"`) do ( + set "var=%%i" + setlocal enabledelayedexpansion + set "var=!var:*:=!" + + if "!var!" == "CURL_SRC_C_FILES" ( + for /f "delims=" %%c in ('dir /b ..\src\*.c') do call :element %1 src "%%c" %3 + ) else if "!var!" == "CURL_SRC_H_FILES" ( + for /f "delims=" %%h in ('dir /b ..\src\*.h') do call :element %1 src "%%h" %3 + ) else if "!var!" == "CURL_SRC_RC_FILES" ( + for /f "delims=" %%r in ('dir /b ..\src\*.rc') do call :element %1 src "%%r" %3 + ) else if "!var!" == "CURL_SRC_X_C_FILES" ( + call :element %1 lib "strtoofft.c" %3 + call :element %1 lib "timediff.c" %3 + call :element %1 lib "nonblock.c" %3 + call :element %1 lib "warnless.c" %3 + call :element %1 lib "curl_multibyte.c" %3 + call :element %1 lib "version_win32.c" %3 + call :element %1 lib "dynbuf.c" %3 + call :element %1 lib "base64.c" %3 + ) else if "!var!" == "CURL_SRC_X_H_FILES" ( + call :element %1 lib "config-win32.h" %3 + call :element %1 lib "curl_setup.h" %3 + call :element %1 lib "strtoofft.h" %3 + call :element %1 lib "timediff.h" %3 + call :element %1 lib "nonblock.h" %3 + call :element %1 lib "warnless.h" %3 + call :element %1 lib "curl_ctype.h" %3 + call :element %1 lib "curl_multibyte.h" %3 + call :element %1 lib "version_win32.h" %3 + call :element %1 lib "dynbuf.h" %3 + call :element %1 lib "curl_base64.h" %3 + ) else if "!var!" == "CURL_LIB_C_FILES" ( + for /f "delims=" %%c in ('dir /b ..\lib\*.c') do call :element %1 lib "%%c" %3 + ) else if "!var!" == "CURL_LIB_H_FILES" ( + for /f "delims=" %%h in ('dir /b ..\include\curl\*.h') do call :element %1 include\curl "%%h" %3 + for /f "delims=" %%h in ('dir /b ..\lib\*.h') do call :element %1 lib "%%h" %3 + ) else if "!var!" == "CURL_LIB_RC_FILES" ( + for /f "delims=" %%r in ('dir /b ..\lib\*.rc') do call :element %1 lib "%%r" %3 + ) else if "!var!" == "CURL_LIB_VAUTH_C_FILES" ( + for /f "delims=" %%c in ('dir /b ..\lib\vauth\*.c') do call :element %1 lib\vauth "%%c" %3 + ) else if "!var!" == "CURL_LIB_VAUTH_H_FILES" ( + for /f "delims=" %%h in ('dir /b ..\lib\vauth\*.h') do call :element %1 lib\vauth "%%h" %3 + ) else if "!var!" == "CURL_LIB_VQUIC_C_FILES" ( + for /f "delims=" %%c in ('dir /b ..\lib\vquic\*.c') do call :element %1 lib\vquic "%%c" %3 + ) else if "!var!" == "CURL_LIB_VQUIC_H_FILES" ( + for /f "delims=" %%h in ('dir /b ..\lib\vquic\*.h') do call :element %1 lib\vquic "%%h" %3 + ) else if "!var!" == "CURL_LIB_VSSH_C_FILES" ( + for /f "delims=" %%c in ('dir /b ..\lib\vssh\*.c') do call :element %1 lib\vssh "%%c" %3 + ) else if "!var!" == "CURL_LIB_VSSH_H_FILES" ( + for /f "delims=" %%h in ('dir /b ..\lib\vssh\*.h') do call :element %1 lib\vssh "%%h" %3 + ) else if "!var!" == "CURL_LIB_VTLS_C_FILES" ( + for /f "delims=" %%c in ('dir /b ..\lib\vtls\*.c') do call :element %1 lib\vtls "%%c" %3 + ) else if "!var!" == "CURL_LIB_VTLS_H_FILES" ( + for /f "delims=" %%h in ('dir /b ..\lib\vtls\*.h') do call :element %1 lib\vtls "%%h" %3 + ) else ( + echo.!var!>> %3 + ) + + endlocal + ) + exit /B + +rem Generates a single file xml element. +rem +rem %1 - Project Type (vcxproj for VC10, VC11, VC12, VC14, VC14.10, VC14.20 and VC14.30) +rem %2 - Directory (src, lib, lib\vauth, lib\vquic, lib\vssh, lib\vtls) +rem %3 - Source filename +rem %4 - Output project file +rem +:element + set "SPACES= " + if "%2" == "lib\vauth" ( + set "TABS= " + ) else if "%2" == "lib\vquic" ( + set "TABS= " + ) else if "%2" == "lib\vssh" ( + set "TABS= " + ) else if "%2" == "lib\vtls" ( + set "TABS= " + ) else ( + set "TABS= " + ) + + call :extension %3 ext + + if "%1" == "dsp" ( + echo # Begin Source File>> %4 + echo.>> %4 + echo SOURCE=..\..\..\..\%2\%~3>> %4 + echo # End Source File>> %4 + ) else if "%1" == "vcproj1" ( + echo %TABS%^> %4 + echo %TABS% RelativePath="..\..\..\..\%2\%~3"^>>> %4 + echo %TABS%^>> %4 + ) else if "%1" == "vcproj2" ( + echo %TABS%^> %4 + echo %TABS% RelativePath="..\..\..\..\%2\%~3">> %4 + echo %TABS%^>>> %4 + echo %TABS%^>> %4 + ) else if "%1" == "vcxproj" ( + if "%ext%" == "c" ( + echo %SPACES%^>> %4 + ) else if "%ext%" == "h" ( + echo %SPACES%^>> %4 + ) else if "%ext%" == "rc" ( + echo %SPACES%^>> %4 + ) + ) + + exit /B + +rem Returns the extension for a given filename. +rem +rem %1 - The filename +rem %2 - The return value +rem +:extension + set fname=%~1 + set ename= +:loop1 + if "%fname%"=="" ( + set %2= + exit /B + ) + + if not "%fname:~-1%"=="." ( + set ename=%fname:~-1%%ename% + set fname=%fname:~0,-1% + goto loop1 + ) + + set %2=%ename% + exit /B + +rem Removes the given project file. +rem +rem %1 - The filename +rem +:clean + echo * %CD%\%1 + + if exist %1 ( + del %1 + ) + + exit /B + +:syntax + rem Display the help + echo. + echo Usage: generate [what] [-clean] + echo. + echo What to generate: + echo. + echo pre - Prerequisites only + echo vc10 - Use Visual Studio 2010 + echo vc11 - Use Visual Studio 2012 + echo vc12 - Use Visual Studio 2013 + echo. + echo Only legacy Visual Studio project files can be generated. + echo. + echo To generate recent versions of Visual Studio project files use cmake. + echo Refer to INSTALL-CMAKE in the docs directory. + echo. + echo -clean - Removes the project files + goto error + +:unknown + echo. + echo Error: Unknown argument '%1' + goto error + +:nodos + echo. + echo Error: Only a Windows NT based Operating System is supported + goto error + +:nonetdrv + echo. + echo Error: This batch file cannot run from a network drive + goto error + +:norepo + echo. + echo Error: This batch file should only be used from a curl git repository + goto error + +:seterr + rem Set the caller's errorlevel. + rem %1[opt]: Errorlevel as integer. + rem If %1 is empty the errorlevel will be set to 0. + rem If %1 is not empty and not an integer the errorlevel will be set to 1. + setlocal + set EXITCODE=%~1 + if not defined EXITCODE set EXITCODE=0 + echo %EXITCODE%|findstr /r "[^0-9\-]" 1>NUL 2>&1 + if %ERRORLEVEL% EQU 0 set EXITCODE=1 + exit /b %EXITCODE% + +:error + if "%OS%" == "Windows_NT" endlocal + exit /B 1 + +:success + endlocal + exit /B 0 diff --git a/third_party/curl/projects/wolfssl_options.h b/third_party/curl/projects/wolfssl_options.h new file mode 100644 index 0000000..3ef23fb --- /dev/null +++ b/third_party/curl/projects/wolfssl_options.h @@ -0,0 +1,308 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , 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. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* +By default wolfSSL has a very conservative configuration that can result in +connections to servers failing due to certificate or algorithm problems. +To remedy this issue for libcurl I've generated this options file that +build-wolfssl will copy to the wolfSSL include directories and will result in +maximum compatibility. + +These are the configure options that were used to build wolfSSL v5.1.1 in +mingw and generate the options in this file: + +C_EXTRA_FLAGS="\ + -Wno-attributes \ + -Wno-unused-but-set-variable \ + -DFP_MAX_BITS=16384 \ + -DHAVE_SECRET_CALLBACK \ + -DTFM_TIMING_RESISTANT \ + -DUSE_WOLF_STRTOK \ + -DWOLFSSL_DES_ECB \ + -DWOLFSSL_STATIC_DH \ + -DWOLFSSL_STATIC_RSA \ + " \ +./configure --prefix=/usr/local \ + --disable-jobserver \ + --enable-aesgcm \ + --enable-alpn \ + --enable-altcertchains \ + --enable-certgen \ + --enable-des3 \ + --enable-dh \ + --enable-dsa \ + --enable-ecc \ + --enable-eccshamir \ + --enable-fastmath \ + --enable-opensslextra \ + --enable-ripemd \ + --enable-sessioncerts \ + --enable-sha512 \ + --enable-sni \ + --enable-tlsv10 \ + --enable-supportedcurves \ + --enable-tls13 \ + --enable-testcert \ + > config.out 2>&1 + +Two generated options HAVE_THREAD_LS and _POSIX_THREADS were removed since they +are inapplicable for our Visual Studio build. Currently thread local storage is +only used by the Fixed Point cache ECC which we're not enabling. However even +if we later may decide to enable the cache it will fallback on mutexes when +thread local storage is not available. wolfSSL is using __declspec(thread) to +create the thread local storage and that could be a problem for LoadLibrary. + +Regarding the options that were added via C_EXTRA_FLAGS: + +FP_MAX_BITS=16384 +https://www.yassl.com/forums/topic423-cacertorgs-ca-cert-verify-failed-but-withdisablefastmath-it-works.html +"Since root.crt uses a 4096-bit RSA key, you'll need to increase the fastmath +buffer size. You can do this using the define: +FP_MAX_BITS and setting it to 8192." + +HAVE_SECRET_CALLBACK +Build wolfSSL with wolfSSL_set_tls13_secret_cb which allows saving TLS 1.3 +secrets to SSLKEYLOGFILE. + +TFM_TIMING_RESISTANT +https://wolfssl.com/wolfSSL/Docs-wolfssl-manual-2-building-wolfssl.html +From section 2.4.5 Increasing Performance, USE_FAST_MATH: +"Because the stack memory usage can be larger when using fastmath, we recommend +defining TFM_TIMING_RESISTANT as well when using this option." + +USE_WOLF_STRTOK +Build wolfSSL to always use its internal strtok instead of C runtime strtok. + +WOLFSSL_DES_ECB +Build wolfSSL with wolfSSL_DES_ecb_encrypt which is needed by libcurl for NTLM. + +WOLFSSL_STATIC_DH: Allow TLS_ECDH_ ciphers +WOLFSSL_STATIC_RSA: Allow TLS_RSA_ ciphers +https://github.com/wolfSSL/wolfssl/blob/v3.6.6/README.md#note-1 +Static key cipher suites are deprecated and disabled by default since v3.6.6. +*/ + +/* wolfssl options.h + * generated from configure options + * + * Copyright (C) 2006-2022 wolfSSL Inc. + * + * This file is part of wolfSSL. (formerly known as CyaSSL) + * + */ + +#ifndef WOLFSSL_OPTIONS_H +#define WOLFSSL_OPTIONS_H + + +#ifdef __cplusplus +extern "C" { +#endif + +#undef FP_MAX_BITS +#define FP_MAX_BITS 16384 + +#undef HAVE_SECRET_CALLBACK +#define HAVE_SECRET_CALLBACK + +#undef TFM_TIMING_RESISTANT +#define TFM_TIMING_RESISTANT + +#undef USE_WOLF_STRTOK +#define USE_WOLF_STRTOK + +#undef WOLFSSL_DES_ECB +#define WOLFSSL_DES_ECB + +#undef WOLFSSL_STATIC_DH +#define WOLFSSL_STATIC_DH + +#undef WOLFSSL_STATIC_RSA +#define WOLFSSL_STATIC_RSA + +#undef TFM_TIMING_RESISTANT +#define TFM_TIMING_RESISTANT + +#undef ECC_TIMING_RESISTANT +#define ECC_TIMING_RESISTANT + +#undef WC_RSA_BLINDING +#define WC_RSA_BLINDING + +#undef WOLFSSL_USE_ALIGN +#define WOLFSSL_USE_ALIGN + +#undef WOLFSSL_RIPEMD +#define WOLFSSL_RIPEMD + +#undef WOLFSSL_SHA512 +#define WOLFSSL_SHA512 + +#undef WOLFSSL_SHA384 +#define WOLFSSL_SHA384 + +#undef SESSION_CERTS +#define SESSION_CERTS + +#undef HAVE_HKDF +#define HAVE_HKDF + +#undef HAVE_ECC +#define HAVE_ECC + +#undef TFM_ECC256 +#define TFM_ECC256 + +#undef ECC_SHAMIR +#define ECC_SHAMIR + +#undef WOLFSSL_ALLOW_TLSV10 +#define WOLFSSL_ALLOW_TLSV10 + +#undef WC_RSA_PSS +#define WC_RSA_PSS + +#undef NO_HC128 +#define NO_HC128 + +#undef NO_RABBIT +#define NO_RABBIT + +#undef HAVE_POLY1305 +#define HAVE_POLY1305 + +#undef HAVE_ONE_TIME_AUTH +#define HAVE_ONE_TIME_AUTH + +#undef HAVE_CHACHA +#define HAVE_CHACHA + +#undef HAVE_HASHDRBG +#define HAVE_HASHDRBG + +#undef HAVE_TLS_EXTENSIONS +#define HAVE_TLS_EXTENSIONS + +#undef HAVE_SNI +#define HAVE_SNI + +#undef HAVE_TLS_EXTENSIONS +#define HAVE_TLS_EXTENSIONS + +#undef HAVE_ALPN +#define HAVE_ALPN + +#undef HAVE_TLS_EXTENSIONS +#define HAVE_TLS_EXTENSIONS + +#undef HAVE_SUPPORTED_CURVES +#define HAVE_SUPPORTED_CURVES + +#undef HAVE_FFDHE_2048 +#define HAVE_FFDHE_2048 + +#undef HAVE_SUPPORTED_CURVES +#define HAVE_SUPPORTED_CURVES + +#undef WOLFSSL_TLS13 +#define WOLFSSL_TLS13 + +#undef HAVE_TLS_EXTENSIONS +#define HAVE_TLS_EXTENSIONS + +#undef HAVE_EXTENDED_MASTER +#define HAVE_EXTENDED_MASTER + +#undef WOLFSSL_ALT_CERT_CHAINS +#define WOLFSSL_ALT_CERT_CHAINS + +#undef WOLFSSL_TEST_CERT +#define WOLFSSL_TEST_CERT + +#undef NO_RC4 +#define NO_RC4 + +#undef HAVE_ENCRYPT_THEN_MAC +#define HAVE_ENCRYPT_THEN_MAC + +#undef NO_PSK +#define NO_PSK + +#undef NO_MD4 +#define NO_MD4 + +#undef WOLFSSL_ENCRYPTED_KEYS +#define WOLFSSL_ENCRYPTED_KEYS + +#undef USE_FAST_MATH +#define USE_FAST_MATH + +#undef WC_NO_ASYNC_THREADING +#define WC_NO_ASYNC_THREADING + +#undef HAVE_DH_DEFAULT_PARAMS +#define HAVE_DH_DEFAULT_PARAMS + +#undef WOLFSSL_CERT_GEN +#define WOLFSSL_CERT_GEN + +#undef OPENSSL_EXTRA +#define OPENSSL_EXTRA + +#undef WOLFSSL_ALWAYS_VERIFY_CB +#define WOLFSSL_ALWAYS_VERIFY_CB + +#undef WOLFSSL_VERIFY_CB_ALL_CERTS +#define WOLFSSL_VERIFY_CB_ALL_CERTS + +#undef WOLFSSL_EXTRA_ALERTS +#define WOLFSSL_EXTRA_ALERTS + +#undef HAVE_EXT_CACHE +#define HAVE_EXT_CACHE + +#undef WOLFSSL_FORCE_CACHE_ON_TICKET +#define WOLFSSL_FORCE_CACHE_ON_TICKET + +#undef WOLFSSL_AKID_NAME +#define WOLFSSL_AKID_NAME + +#undef HAVE_CTS +#define HAVE_CTS + +#undef GCM_TABLE_4BIT +#define GCM_TABLE_4BIT + +#undef HAVE_AESGCM +#define HAVE_AESGCM + +#undef HAVE_WC_INTROSPECTION +#define HAVE_WC_INTROSPECTION + + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + + +#endif /* WOLFSSL_OPTIONS_H */ diff --git a/third_party/curl/projects/wolfssl_override.props b/third_party/curl/projects/wolfssl_override.props new file mode 100644 index 0000000..fab60f3 --- /dev/null +++ b/third_party/curl/projects/wolfssl_override.props @@ -0,0 +1,40 @@ + + + + + + %(PreprocessorDefinitions); + + $(SolutionDir)\wolfssl\options.h;%(ForcedIncludeFiles); + + _UNICODE;UNICODE;WOLFSSL_USER_SETTINGS;CYASSL_USER_SETTINGS;%(UndefinePreprocessorDefinitions); + + + _UNICODE;UNICODE;%(UndefinePreprocessorDefinitions); + + + + + + + + + + diff --git a/third_party/curl/scripts/Makefile.am b/third_party/curl/scripts/Makefile.am new file mode 100644 index 0000000..772c7bd --- /dev/null +++ b/third_party/curl/scripts/Makefile.am @@ -0,0 +1,83 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +EXTRA_DIST = coverage.sh completion.pl firefox-db2pem.sh checksrc.pl \ + mk-ca-bundle.pl schemetable.c cd2nroff nroff2cd cdall cd2cd managen \ + dmaketgz + +ZSH_FUNCTIONS_DIR = @ZSH_FUNCTIONS_DIR@ +FISH_FUNCTIONS_DIR = @FISH_FUNCTIONS_DIR@ +PERL = @PERL@ + +if USE_ZSH_COMPLETION +ZSH_COMPLETION_FUNCTION_FILENAME = _curl +endif +if USE_FISH_COMPLETION +FISH_COMPLETION_FUNCTION_FILENAME = curl.fish +endif + +CLEANFILES = $(ZSH_COMPLETION_FUNCTION_FILENAME) $(FISH_COMPLETION_FUNCTION_FILENAME) + +all-local: $(ZSH_COMPLETION_FUNCTION_FILENAME) $(FISH_COMPLETION_FUNCTION_FILENAME) + +if USE_ZSH_COMPLETION +$(ZSH_COMPLETION_FUNCTION_FILENAME): completion.pl +if CROSSCOMPILING + @echo "NOTICE: we can't generate zsh completion when cross-compiling!" +else # if not cross-compiling: + if test -z "$(PERL)"; then echo "No perl: can't install completion script"; else \ + $(PERL) $(srcdir)/completion.pl --curl $(top_builddir)/src/curl$(EXEEXT) --shell zsh > $@ ; fi +endif +endif + +if USE_FISH_COMPLETION +$(FISH_COMPLETION_FUNCTION_FILENAME): completion.pl +if CROSSCOMPILING + @echo "NOTICE: we can't generate fish completion when cross-compiling!" +else # if not cross-compiling: + if test -z "$(PERL)"; then echo "No perl: can't install completion script"; else \ + $(PERL) $(srcdir)/completion.pl --curl $(top_builddir)/src/curl$(EXEEXT) --shell fish > $@ ; fi +endif +endif + +install-data-local: +if CROSSCOMPILING + @echo "NOTICE: we can't install completion scripts when cross-compiling!" +else # if not cross-compiling: +if USE_ZSH_COMPLETION + if test -n "$(PERL)"; then \ + $(MKDIR_P) $(DESTDIR)$(ZSH_FUNCTIONS_DIR); \ + $(INSTALL_DATA) $(ZSH_COMPLETION_FUNCTION_FILENAME) $(DESTDIR)$(ZSH_FUNCTIONS_DIR)/$(ZSH_COMPLETION_FUNCTION_FILENAME) ; \ + fi +endif +if USE_FISH_COMPLETION + if test -n "$(PERL)"; then \ + $(MKDIR_P) $(DESTDIR)$(FISH_FUNCTIONS_DIR); \ + $(INSTALL_DATA) $(FISH_COMPLETION_FUNCTION_FILENAME) $(DESTDIR)$(FISH_FUNCTIONS_DIR)/$(FISH_COMPLETION_FUNCTION_FILENAME) ; \ + fi +endif +endif + +distclean: + rm -f $(CLEANFILES) diff --git a/third_party/curl/scripts/Makefile.in b/third_party/curl/scripts/Makefile.in new file mode 100644 index 0000000..347030a --- /dev/null +++ b/third_party/curl/scripts/Makefile.in @@ -0,0 +1,624 @@ +# Makefile.in generated by automake 1.16.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994-2021 Free Software Foundation, Inc. + +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### +VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = scripts +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4/curl-amissl.m4 \ + $(top_srcdir)/m4/curl-bearssl.m4 \ + $(top_srcdir)/m4/curl-compilers.m4 \ + $(top_srcdir)/m4/curl-confopts.m4 \ + $(top_srcdir)/m4/curl-functions.m4 \ + $(top_srcdir)/m4/curl-gnutls.m4 \ + $(top_srcdir)/m4/curl-mbedtls.m4 \ + $(top_srcdir)/m4/curl-openssl.m4 \ + $(top_srcdir)/m4/curl-override.m4 \ + $(top_srcdir)/m4/curl-reentrant.m4 \ + $(top_srcdir)/m4/curl-rustls.m4 \ + $(top_srcdir)/m4/curl-schannel.m4 \ + $(top_srcdir)/m4/curl-sectransp.m4 \ + $(top_srcdir)/m4/curl-sysconfig.m4 \ + $(top_srcdir)/m4/curl-wolfssl.m4 $(top_srcdir)/m4/libtool.m4 \ + $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ + $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ + $(top_srcdir)/m4/xc-am-iface.m4 \ + $(top_srcdir)/m4/xc-cc-check.m4 \ + $(top_srcdir)/m4/xc-lt-iface.m4 \ + $(top_srcdir)/m4/xc-translit.m4 \ + $(top_srcdir)/m4/xc-val-flgs.m4 \ + $(top_srcdir)/m4/zz40-xc-ovr.m4 \ + $(top_srcdir)/m4/zz50-xc-ovr.m4 \ + $(top_srcdir)/m4/zz60-xc-ovr.m4 $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/lib/curl_config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +SOURCES = +DIST_SOURCES = +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +am__DIST_COMMON = $(srcdir)/Makefile.in +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +APACHECTL = @APACHECTL@ +APXS = @APXS@ +AR = @AR@ +AR_FLAGS = @AR_FLAGS@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +BLANK_AT_MAKETIME = @BLANK_AT_MAKETIME@ +CADDY = @CADDY@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CFLAG_CURL_SYMBOL_HIDING = @CFLAG_CURL_SYMBOL_HIDING@ +CONFIGURE_OPTIONS = @CONFIGURE_OPTIONS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CPPFLAG_CURL_STATICLIB = @CPPFLAG_CURL_STATICLIB@ +CSCOPE = @CSCOPE@ +CTAGS = @CTAGS@ +CURLVERSION = @CURLVERSION@ +CURL_CA_BUNDLE = @CURL_CA_BUNDLE@ +CURL_CFLAG_EXTRAS = @CURL_CFLAG_EXTRAS@ +CURL_DISABLE_DICT = @CURL_DISABLE_DICT@ +CURL_DISABLE_FILE = @CURL_DISABLE_FILE@ +CURL_DISABLE_FTP = @CURL_DISABLE_FTP@ +CURL_DISABLE_GOPHER = @CURL_DISABLE_GOPHER@ +CURL_DISABLE_HTTP = @CURL_DISABLE_HTTP@ +CURL_DISABLE_IMAP = @CURL_DISABLE_IMAP@ +CURL_DISABLE_LDAP = @CURL_DISABLE_LDAP@ +CURL_DISABLE_LDAPS = @CURL_DISABLE_LDAPS@ +CURL_DISABLE_MQTT = @CURL_DISABLE_MQTT@ +CURL_DISABLE_POP3 = @CURL_DISABLE_POP3@ +CURL_DISABLE_PROXY = @CURL_DISABLE_PROXY@ +CURL_DISABLE_RTSP = @CURL_DISABLE_RTSP@ +CURL_DISABLE_SMB = @CURL_DISABLE_SMB@ +CURL_DISABLE_SMTP = @CURL_DISABLE_SMTP@ +CURL_DISABLE_TELNET = @CURL_DISABLE_TELNET@ +CURL_DISABLE_TFTP = @CURL_DISABLE_TFTP@ +CURL_LT_SHLIB_VERSIONED_FLAVOUR = @CURL_LT_SHLIB_VERSIONED_FLAVOUR@ +CURL_NETWORK_AND_TIME_LIBS = @CURL_NETWORK_AND_TIME_LIBS@ +CURL_NETWORK_LIBS = @CURL_NETWORK_LIBS@ +CURL_WITH_MULTI_SSL = @CURL_WITH_MULTI_SSL@ +CYGPATH_W = @CYGPATH_W@ +DEFAULT_SSL_BACKEND = @DEFAULT_SSL_BACKEND@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +ENABLE_SHARED = @ENABLE_SHARED@ +ENABLE_STATIC = @ENABLE_STATIC@ +ETAGS = @ETAGS@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +FILECMD = @FILECMD@ +FISH_FUNCTIONS_DIR = @FISH_FUNCTIONS_DIR@ +GCOV = @GCOV@ +GREP = @GREP@ +HAVE_BROTLI = @HAVE_BROTLI@ +HAVE_GNUTLS_SRP = @HAVE_GNUTLS_SRP@ +HAVE_LDAP_SSL = @HAVE_LDAP_SSL@ +HAVE_LIBZ = @HAVE_LIBZ@ +HAVE_OPENSSL_QUIC = @HAVE_OPENSSL_QUIC@ +HAVE_OPENSSL_SRP = @HAVE_OPENSSL_SRP@ +HAVE_PROTO_BSDSOCKET_H = @HAVE_PROTO_BSDSOCKET_H@ +HAVE_ZSTD = @HAVE_ZSTD@ +HTTPD = @HTTPD@ +HTTPD_NGHTTPX = @HTTPD_NGHTTPX@ +IDN_ENABLED = @IDN_ENABLED@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +IPV6_ENABLED = @IPV6_ENABLED@ +LCOV = @LCOV@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBCURL_LIBS = @LIBCURL_LIBS@ +LIBCURL_NO_SHARED = @LIBCURL_NO_SHARED@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ +MAINT = @MAINT@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PERL = @PERL@ +PKGADD_NAME = @PKGADD_NAME@ +PKGADD_PKG = @PKGADD_PKG@ +PKGADD_VENDOR = @PKGADD_VENDOR@ +PKGCONFIG = @PKGCONFIG@ +RANDOM_FILE = @RANDOM_FILE@ +RANLIB = @RANLIB@ +RC = @RC@ +REQUIRE_LIB_DEPS = @REQUIRE_LIB_DEPS@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SSL_BACKENDS = @SSL_BACKENDS@ +SSL_ENABLED = @SSL_ENABLED@ +SSL_LIBS = @SSL_LIBS@ +STRIP = @STRIP@ +SUPPORT_FEATURES = @SUPPORT_FEATURES@ +SUPPORT_PROTOCOLS = @SUPPORT_PROTOCOLS@ +TEST_NGHTTPX = @TEST_NGHTTPX@ +USE_ARES = @USE_ARES@ +USE_BEARSSL = @USE_BEARSSL@ +USE_GNUTLS = @USE_GNUTLS@ +USE_HYPER = @USE_HYPER@ +USE_LIBPSL = @USE_LIBPSL@ +USE_LIBRTMP = @USE_LIBRTMP@ +USE_LIBSSH = @USE_LIBSSH@ +USE_LIBSSH2 = @USE_LIBSSH2@ +USE_MBEDTLS = @USE_MBEDTLS@ +USE_MSH3 = @USE_MSH3@ +USE_NGHTTP2 = @USE_NGHTTP2@ +USE_NGHTTP3 = @USE_NGHTTP3@ +USE_NGTCP2 = @USE_NGTCP2@ +USE_NGTCP2_CRYPTO_BORINGSSL = @USE_NGTCP2_CRYPTO_BORINGSSL@ +USE_NGTCP2_CRYPTO_GNUTLS = @USE_NGTCP2_CRYPTO_GNUTLS@ +USE_NGTCP2_CRYPTO_QUICTLS = @USE_NGTCP2_CRYPTO_QUICTLS@ +USE_NGTCP2_CRYPTO_WOLFSSL = @USE_NGTCP2_CRYPTO_WOLFSSL@ +USE_NGTCP2_H3 = @USE_NGTCP2_H3@ +USE_OPENLDAP = @USE_OPENLDAP@ +USE_OPENSSL_H3 = @USE_OPENSSL_H3@ +USE_OPENSSL_QUIC = @USE_OPENSSL_QUIC@ +USE_QUICHE = @USE_QUICHE@ +USE_RUSTLS = @USE_RUSTLS@ +USE_SCHANNEL = @USE_SCHANNEL@ +USE_SECTRANSP = @USE_SECTRANSP@ +USE_UNIX_SOCKETS = @USE_UNIX_SOCKETS@ +USE_WIN32_CRYPTO = @USE_WIN32_CRYPTO@ +USE_WIN32_LARGE_FILES = @USE_WIN32_LARGE_FILES@ +USE_WIN32_SMALL_FILES = @USE_WIN32_SMALL_FILES@ +USE_WINDOWS_SSPI = @USE_WINDOWS_SSPI@ +USE_WOLFSSH = @USE_WOLFSSH@ +USE_WOLFSSL = @USE_WOLFSSL@ +VERSION = @VERSION@ +VERSIONNUM = @VERSIONNUM@ +VSFTPD = @VSFTPD@ +ZLIB_LIBS = @ZLIB_LIBS@ +ZSH_FUNCTIONS_DIR = @ZSH_FUNCTIONS_DIR@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +libext = @libext@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +runstatedir = @runstatedir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +EXTRA_DIST = coverage.sh completion.pl firefox-db2pem.sh checksrc.pl \ + mk-ca-bundle.pl schemetable.c cd2nroff nroff2cd cdall cd2cd managen \ + dmaketgz + +@USE_ZSH_COMPLETION_TRUE@ZSH_COMPLETION_FUNCTION_FILENAME = _curl +@USE_FISH_COMPLETION_TRUE@FISH_COMPLETION_FUNCTION_FILENAME = curl.fish +CLEANFILES = $(ZSH_COMPLETION_FUNCTION_FILENAME) $(FISH_COMPLETION_FUNCTION_FILENAME) +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu scripts/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --gnu scripts/Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +tags TAGS: + +ctags CTAGS: + +cscope cscopelist: + +distdir: $(BUILT_SOURCES) + $(MAKE) $(AM_MAKEFLAGS) distdir-am + +distdir-am: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile all-local +installdirs: +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean-am: clean-am distclean-generic + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-data-local + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: + +.MAKE: install-am install-strip + +.PHONY: all all-am all-local check check-am clean clean-generic \ + clean-libtool cscopelist-am ctags-am distclean \ + distclean-generic distclean-libtool distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-data-local install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-man install-pdf \ + install-pdf-am install-ps install-ps-am install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am tags-am uninstall \ + uninstall-am + +.PRECIOUS: Makefile + + +all-local: $(ZSH_COMPLETION_FUNCTION_FILENAME) $(FISH_COMPLETION_FUNCTION_FILENAME) + +@USE_ZSH_COMPLETION_TRUE@$(ZSH_COMPLETION_FUNCTION_FILENAME): completion.pl +@CROSSCOMPILING_TRUE@@USE_ZSH_COMPLETION_TRUE@ @echo "NOTICE: we can't generate zsh completion when cross-compiling!" +@CROSSCOMPILING_FALSE@@USE_ZSH_COMPLETION_TRUE@ if test -z "$(PERL)"; then echo "No perl: can't install completion script"; else \ +@CROSSCOMPILING_FALSE@@USE_ZSH_COMPLETION_TRUE@ $(PERL) $(srcdir)/completion.pl --curl $(top_builddir)/src/curl$(EXEEXT) --shell zsh > $@ ; fi + +@USE_FISH_COMPLETION_TRUE@$(FISH_COMPLETION_FUNCTION_FILENAME): completion.pl +@CROSSCOMPILING_TRUE@@USE_FISH_COMPLETION_TRUE@ @echo "NOTICE: we can't generate fish completion when cross-compiling!" +@CROSSCOMPILING_FALSE@@USE_FISH_COMPLETION_TRUE@ if test -z "$(PERL)"; then echo "No perl: can't install completion script"; else \ +@CROSSCOMPILING_FALSE@@USE_FISH_COMPLETION_TRUE@ $(PERL) $(srcdir)/completion.pl --curl $(top_builddir)/src/curl$(EXEEXT) --shell fish > $@ ; fi + +install-data-local: +@CROSSCOMPILING_TRUE@ @echo "NOTICE: we can't install completion scripts when cross-compiling!" +@CROSSCOMPILING_FALSE@@USE_ZSH_COMPLETION_TRUE@ if test -n "$(PERL)"; then \ +@CROSSCOMPILING_FALSE@@USE_ZSH_COMPLETION_TRUE@ $(MKDIR_P) $(DESTDIR)$(ZSH_FUNCTIONS_DIR); \ +@CROSSCOMPILING_FALSE@@USE_ZSH_COMPLETION_TRUE@ $(INSTALL_DATA) $(ZSH_COMPLETION_FUNCTION_FILENAME) $(DESTDIR)$(ZSH_FUNCTIONS_DIR)/$(ZSH_COMPLETION_FUNCTION_FILENAME) ; \ +@CROSSCOMPILING_FALSE@@USE_ZSH_COMPLETION_TRUE@ fi +@CROSSCOMPILING_FALSE@@USE_FISH_COMPLETION_TRUE@ if test -n "$(PERL)"; then \ +@CROSSCOMPILING_FALSE@@USE_FISH_COMPLETION_TRUE@ $(MKDIR_P) $(DESTDIR)$(FISH_FUNCTIONS_DIR); \ +@CROSSCOMPILING_FALSE@@USE_FISH_COMPLETION_TRUE@ $(INSTALL_DATA) $(FISH_COMPLETION_FUNCTION_FILENAME) $(DESTDIR)$(FISH_FUNCTIONS_DIR)/$(FISH_COMPLETION_FUNCTION_FILENAME) ; \ +@CROSSCOMPILING_FALSE@@USE_FISH_COMPLETION_TRUE@ fi + +distclean: + rm -f $(CLEANFILES) + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/third_party/curl/scripts/cd2cd b/third_party/curl/scripts/cd2cd new file mode 100755 index 0000000..a4de2f8 --- /dev/null +++ b/third_party/curl/scripts/cd2cd @@ -0,0 +1,226 @@ +#!/usr/bin/env perl +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +=begin comment + +This script updates a curldown file to current/better curldown. + +Example: cd2cd [--in-place] > + +--in-place: if used, it replaces the original file with the cleaned up + version. When this is used, cd2cd accepts multiple files to work + on and it ignores errors on single files. + +=end comment +=cut + +my $cd2cd = "0.1"; # to keep check +my $dir; +my $extension; +my $inplace = 0; + +while(1) { + if($ARGV[0] eq "--in-place") { + shift @ARGV; + $inplace = 1; + } + else { + last; + } +} + + +use POSIX qw(strftime); +my @ts; +if (defined($ENV{SOURCE_DATE_EPOCH})) { + @ts = localtime($ENV{SOURCE_DATE_EPOCH}); +} else { + @ts = localtime; +} +my $date = strftime "%B %d %Y", @ts; + +sub outseealso { + my (@sa) = @_; + my $comma = 0; + my @o; + push @o, ".SH SEE ALSO\n"; + for my $s (sort @sa) { + push @o, sprintf "%s.BR $s", $comma ? ",\n": ""; + $comma = 1; + } + push @o, "\n"; + return @o; +} + +sub single { + my @head; + my @seealso; + my ($f)=@_; + my $title; + my $section; + my $source; + my $start = 0; + my $d; + my $line = 0; + open(F, "<:crlf", "$f") || + return 1; + while() { + $line++; + $d = $_; + if(!$start) { + if(/^---/) { + # header starts here + $start = 1; + push @head, $d; + } + next; + } + if(/^Title: *(.*)/i) { + $title=$1; + } + elsif(/^Section: *(.*)/i) { + $section=$1; + } + elsif(/^Source: *(.*)/i) { + $source=$1; + } + elsif(/^See-also: +(.*)/i) { + $salist = 0; + push @seealso, $1; + } + elsif(/^See-also: */i) { + if($seealso[0]) { + print STDERR "$f:$line:1:ERROR: bad See-Also, needs list\n"; + return 2; + } + $salist = 1; + } + elsif(/^ +- (.*)/i) { + # the only list we support is the see-also + if($salist) { + push @seealso, $1; + } + } + # REUSE-IgnoreStart + elsif(/^C: (.*)/i) { + $copyright=$1; + } + elsif(/^SPDX-License-Identifier: (.*)/i) { + $spdx=$1; + } + # REUSE-IgnoreEnd + elsif(/^---/) { + # end of the header section + if(!$title) { + print STDERR "ERROR: no 'Title:' in $f\n"; + return 1; + } + if(!$section) { + print STDERR "ERROR: no 'Section:' in $f\n"; + return 2; + } + if(!$seealso[0]) { + print STDERR "$f:$line:1:ERROR: no 'See-also:' present\n"; + return 2; + } + if(!$copyright) { + print STDERR "$f:$line:1:ERROR: no 'C:' field present\n"; + return 2; + } + if(!$spdx) { + print STDERR "$f:$line:1:ERROR: no 'SPDX-License-Identifier:' field present\n"; + return 2; + } + last; + } + else { + chomp; + print STDERR "WARN: unrecognized line in $f, ignoring:\n:'$_';" + } + } + + if(!$start) { + print STDERR "$f:$line:1:ERROR: no header present\n"; + return 2; + } + + my @desc; + + push @desc, sprintf <, et al. +SPDX-License-Identifier: curl +Title: $title +Section: $section +Source: $source +HEAD + ; + push @desc, "See-also:\n"; + for my $s (sort @seealso) { + push @desc, " - $s\n" if($s); + } + push @desc, "---\n"; + + my $blankline = 0; + while() { + $d = $_; + $line++; + if($d =~ /^[ \t]*\n/) { + $blankline++; + } + else { + $blankline = 0; + } + # *italics* for curl symbol links get the asterisks removed + $d =~ s/\*((lib|)curl[^ ]*\(3\))\*/$1/gi; + + if(length($d) > 90) { + print STDERR "$f:$line:1:WARN: excessive line length\n"; + } + + push @desc, $d if($blankline < 2); + } + close(F); + + if($inplace) { + open(O, ">$f") || return 1; + print O @desc; + close(O); + } + else { + print @desc; + } + return 0; +} + +if($inplace) { + for my $a (@ARGV) { + # this ignores errors + single($a); + } +} +else { + exit single($ARGV[0]); +} diff --git a/third_party/curl/scripts/cd2nroff b/third_party/curl/scripts/cd2nroff new file mode 100755 index 0000000..647a289 --- /dev/null +++ b/third_party/curl/scripts/cd2nroff @@ -0,0 +1,526 @@ +#!/usr/bin/env perl +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +=begin comment + +Converts a curldown file to nroff (man page). + +=end comment +=cut + +use strict; +use warnings; + +my $cd2nroff = "0.1"; # to keep check +my $dir; +my $extension; +my $keepfilename; + +while(@ARGV) { + if($ARGV[0] eq "-d") { + shift @ARGV; + $dir = shift @ARGV; + } + elsif($ARGV[0] eq "-e") { + shift @ARGV; + $extension = shift @ARGV; + } + elsif($ARGV[0] eq "-k") { + shift @ARGV; + $keepfilename = 1; + } + elsif($ARGV[0] eq "-h") { + print < Write the output to the file name from the meta-data in the + specified directory, instead of writing to stdout +-e If -d is used, this option can provide an added "extension", arbitrary + text really, to append to the file name. +-h This help text, +-v Show version then exit +HELP + ; + exit 0; + } + elsif($ARGV[0] eq "-v") { + print "cd2nroff version $cd2nroff\n"; + exit 0; + } + else { + last; + } +} + +use POSIX qw(strftime); +my @ts; +if (defined($ENV{SOURCE_DATE_EPOCH})) { + @ts = gmtime($ENV{SOURCE_DATE_EPOCH}); +} else { + @ts = localtime; +} +my $date = strftime "%Y-%m-%d", @ts; + +sub outseealso { + my (@sa) = @_; + my $comma = 0; + my @o; + push @o, ".SH SEE ALSO\n"; + for my $s (sort @sa) { + push @o, sprintf "%s.BR $s", $comma ? ",\n": ""; + $comma = 1; + } + push @o, "\n"; + return @o; +} + +sub outprotocols { + my (@p) = @_; + my $comma = 0; + my @o; + push @o, ".SH PROTOCOLS\n"; + + if($p[0] eq "TLS") { + push @o, "All TLS based protocols: HTTPS, FTPS, IMAPS, POP3S, SMTPS etc."; + } + else { + my @s = sort @p; + for my $e (sort @s) { + push @o, sprintf "%s$e", + $comma ? (($e eq $s[-1]) ? " and " : ", "): ""; + $comma = 1; + } + } + push @o, "\n"; + return @o; +} + +sub outtls { + my (@t) = @_; + my $comma = 0; + my @o; + if($t[0] eq "All") { + push @o, "\nAll TLS backends support this option."; + } + else { + push @o, "\nThis option works only with the following TLS backends:\n"; + my @s = sort @t; + for my $e (@s) { + push @o, sprintf "%s$e", + $comma ? (($e eq $s[-1]) ? " and " : ", "): ""; + $comma = 1; + } + } + push @o, "\n"; + return @o; +} + +my %knownprotos = ( + 'DICT' => 1, + 'FILE' => 1, + 'FTP' => 1, + 'FTPS' => 1, + 'GOPHER' => 1, + 'GOPHERS' => 1, + 'HTTP' => 1, + 'HTTPS' => 1, + 'IMAP' => 1, + 'IMAPS' => 1, + 'LDAP' => 1, + 'LDAPS' => 1, + 'MQTT' => 1, + 'POP3' => 1, + 'POP3S' => 1, + 'RTMP' => 1, + 'RTMPS' => 1, + 'RTSP' => 1, + 'SCP' => 1, + 'SFTP' => 1, + 'SMB' => 1, + 'SMBS' => 1, + 'SMTP' => 1, + 'SMTPS' => 1, + 'TELNET' => 1, + 'TFTP' => 1, + 'WS' => 1, + 'WSS' => 1, + 'TLS' => 1, + 'TCP' => 1, + 'All' => 1 + ); + +my %knowntls = ( + 'BearSSL' => 1, + 'GnuTLS' => 1, + 'mbedTLS' => 1, + 'OpenSSL' => 1, + 'rustls' => 1, + 'Schannel' => 1, + 'Secure Transport' => 1, + 'wolfSSL' => 1, + 'All' => 1, + ); + +sub single { + my @seealso; + my @proto; + my @tls; + my $d; + my ($f)=@_; + my $copyright; + my $errors = 0; + my $fh; + my $line; + my $list; + my $tlslist; + my $section; + my $source; + my $spdx; + my $start = 0; + my $title; + + if(defined($f)) { + if(!open($fh, "<:crlf", "$f")) { + print STDERR "cd2nroff failed to open '$f' for reading: $!\n"; + return 1; + } + } + else { + $f = "STDIN"; + $fh = \*STDIN; + binmode($fh, ":crlf"); + } + while(<$fh>) { + $line++; + if(!$start) { + if(/^---/) { + # header starts here + $start = 1; + } + next; + } + if(/^Title: *(.*)/i) { + $title=$1; + } + elsif(/^Section: *(.*)/i) { + $section=$1; + } + elsif(/^Source: *(.*)/i) { + $source=$1; + } + elsif(/^See-also: +(.*)/i) { + $list = 1; # 1 for see-also + push @seealso, $1; + } + elsif(/^See-also: */i) { + if($seealso[0]) { + print STDERR "$f:$line:1:ERROR: bad See-Also, needs list\n"; + return 2; + } + $list = 1; # 1 for see-also + } + elsif(/^Protocol:/i) { + $list = 2; # 2 for protocol + } + elsif(/^TLS-backend:/i) { + $list = 3; # 3 for TLS backend + } + elsif(/^ +- (.*)/i) { + # the only lists we support are see-also and protocol + if($list == 1) { + push @seealso, $1; + } + elsif($list == 2) { + push @proto, $1; + } + elsif($list == 3) { + push @tls, $1; + } + else { + print STDERR "$f:$line:1:ERROR: list item without owner?\n"; + return 2; + } + } + # REUSE-IgnoreStart + elsif(/^C: (.*)/i) { + $copyright=$1; + } + elsif(/^SPDX-License-Identifier: (.*)/i) { + $spdx=$1; + } + # REUSE-IgnoreEnd + elsif(/^---/) { + # end of the header section + if(!$title) { + print STDERR "ERROR: no 'Title:' in $f\n"; + return 1; + } + if(!$section) { + print STDERR "ERROR: no 'Section:' in $f\n"; + return 2; + } + if(!$seealso[0]) { + print STDERR "$f:$line:1:ERROR: no 'See-also:' present\n"; + return 2; + } + if(!$copyright) { + print STDERR "$f:$line:1:ERROR: no 'C:' field present\n"; + return 2; + } + if(!$spdx) { + print STDERR "$f:$line:1:ERROR: no 'SPDX-License-Identifier:' field present\n"; + return 2; + } + if($section == 3) { + if(!$proto[0]) { + printf STDERR "$f:$line:1:ERROR: missing Protocol:\n"; + exit 2; + } + my $tls = 0; + for my $p (@proto) { + if($p eq "TLS") { + $tls = 1; + } + if(!$knownprotos{$p}) { + printf STDERR "$f:$line:1:ERROR: invalid protocol used: $p:\n"; + exit 2; + } + } + # This is for TLS, require TLS-backend: + if($tls) { + if(!$tls[0]) { + printf STDERR "$f:$line:1:ERROR: missing TLS-backend:\n"; + exit 2; + } + for my $t (@tls) { + if(!$knowntls{$t}) { + printf STDERR "$f:$line:1:ERROR: invalid TLS backend: $t:\n"; + exit 2; + } + } + } + } + last; + } + else { + chomp; + print STDERR "WARN: unrecognized line in $f, ignoring:\n:'$_';" + } + } + + if(!$start) { + print STDERR "$f:$line:1:ERROR: no header present\n"; + return 2; + } + + my @desc; + my $quote = 0; + my $blankline = 0; + my $header = 0; + + # cut off the leading path from the file name, if any + $f =~ s/^(.*[\\\/])//; + + push @desc, ".\\\" generated by cd2nroff $cd2nroff from $f\n"; + push @desc, ".TH $title $section \"$date\" $source\n"; + while(<$fh>) { + $line++; + + $d = $_; + + if($quote) { + if($quote == 4) { + # remove the indentation + if($d =~ /^ (.*)/) { + push @desc, "$1\n"; + next; + } + else { + # end of quote + $quote = 0; + push @desc, ".fi\n"; + next; + } + } + if(/^~~~/) { + # end of quote + $quote = 0; + push @desc, ".fi\n"; + next; + } + # convert single backslahes to doubles + $d =~ s/\\/\\\\/g; + # lines starting with a period needs it escaped + $d =~ s/^\./\\&./; + push @desc, $d; + next; + } + + # remove single line HTML comments + $d =~ s///g; + + # **bold** + $d =~ s/\*\*(\S.*?)\*\*/\\fB$1\\fP/g; + # *italics* + $d =~ s/\*(\S.*?)\*/\\fI$1\\fP/g; + + if($d =~ /[^\\][\<\>]/) { + print STDERR "$f:$line:1:WARN: un-escaped < or > used\n"; + } + # convert backslash-'<' or '> to just the second character + $d =~ s/\\([<>])/$1/g; + + # mentions of curl symbols with man pages use italics by default + $d =~ s/((lib|)curl([^ ]*\(3\)))/\\fI$1\\fP/gi; + + # backticked becomes italics + $d =~ s/\`(.*?)\`/\\fI$1\\fP/g; + + if(/^## (.*)/) { + my $word = $1; + # if there are enclosing quotes, remove them first + $word =~ s/[\"\'\`](.*)[\"\'\`]\z/$1/; + + # enclose in double quotes if there is a space present + if($word =~ / /) { + push @desc, ".IP \"$word\"\n"; + } + else { + push @desc, ".IP $word\n"; + } + $header = 1; + } + elsif(/^# (.*)/) { + my $word = $1; + # if there are enclosing quotes, remove them first + $word =~ s/[\"\'](.*)[\"\']\z/$1/; + + if($word eq "PROTOCOLS") { + print STDERR "$f:$line:1:WARN: PROTOCOLS section in source file\n"; + } + elsif($word eq "EXAMPLE") { + # insert the generated PROTOCOLS section before EXAMPLE + push @desc, outprotocols(@proto); + + if($proto[0] eq "TLS") { + push @desc, outtls(@tls); + } + } + push @desc, ".SH $word\n"; + $header = 1; + } + elsif(/^~~~c/) { + # start of a code section, not indented + $quote = 1; + push @desc, "\n" if($blankline && !$header); + $header = 0; + push @desc, ".nf\n"; + } + elsif(/^~~~/) { + # start of a quote section; not code, not indented + $quote = 1; + push @desc, "\n" if($blankline && !$header); + $header = 0; + push @desc, ".nf\n"; + } + elsif(/^ (.*)/) { + # quoted, indented by 4 space + $quote = 4; + push @desc, "\n" if($blankline && !$header); + $header = 0; + push @desc, ".nf\n$1\n"; + } + elsif(/^[ \t]*\n/) { + # count and ignore blank lines + $blankline++; + } + else { + # don't output newlines if this is the first content after a + # header + push @desc, "\n" if($blankline && !$header); + $blankline = 0; + $header = 0; + + # quote minuses in the output + $d =~ s/([^\\])-/$1\\-/g; + # replace single quotes + $d =~ s/\'/\\(aq/g; + # handle double quotes first on the line + $d =~ s/^(\s*)\"/$1\\&\"/; + + # lines starting with a period needs it escaped + $d =~ s/^\./\\&./; + + if($d =~ /^(.*) /) { + printf STDERR "$f:$line:%d:ERROR: 2 spaces detected\n", + length($1); + $errors++; + } + if($d =~ /^[ \t]*\n/) { + # replaced away all contents + $blankline= 1; + } + else { + push @desc, $d; + } + } + } + if($fh != \*STDIN) { + close($fh); + } + push @desc, outseealso(@seealso); + if($dir) { + if($keepfilename) { + $title = $f; + $title =~ s/\.[^.]*$//; + } + my $outfile = "$dir/$title.$section"; + if(defined($extension)) { + $outfile .= $extension; + } + if(!open(O, ">", $outfile)) { + print STDERR "Failed to open $outfile : $!\n"; + return 1; + } + print O @desc; + close(O); + } + else { + print @desc; + } + return $errors; +} + +if(@ARGV) { + for my $f (@ARGV) { + my $r = single($f); + if($r) { + exit $r; + } + } +} +else { + exit single(); +} diff --git a/third_party/curl/scripts/cdall b/third_party/curl/scripts/cdall new file mode 100755 index 0000000..507ccc6 --- /dev/null +++ b/third_party/curl/scripts/cdall @@ -0,0 +1,44 @@ +#!/usr/bin/env perl +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +# provide all dir names to scan on the cmdline + +sub convert { + my ($dir)=@_; + opendir(my $dh, $dir) || die "could not open $dir"; + my @cd = grep { /\.md\z/ && -f "$dir/$_" } readdir($dh); + closedir $dh; + + for my $cd (@cd) { + my $nroff = "$cd"; + $nroff =~ s/\.md\z/.3/; + print "$dir/$cd = $dir/$nroff\n"; + system("./scripts/cd2nroff -d $dir $dir/$cd"); + } +} + +for my $d (sort @ARGV) { + convert($d); +} diff --git a/third_party/curl/scripts/checksrc.pl b/third_party/curl/scripts/checksrc.pl new file mode 100755 index 0000000..75f68fb --- /dev/null +++ b/third_party/curl/scripts/checksrc.pl @@ -0,0 +1,990 @@ +#!/usr/bin/env perl +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +use strict; +use warnings; + +my $max_column = 79; +my $indent = 2; + +my $warnings = 0; +my $swarnings = 0; +my $errors = 0; +my $serrors = 0; +my $suppressed; # skipped problems +my $file; +my $dir="."; +my $wlist=""; +my @alist; +my $windows_os = $^O eq 'MSWin32' || $^O eq 'cygwin' || $^O eq 'msys'; +my $verbose; +my %skiplist; + +my %ignore; +my %ignore_set; +my %ignore_used; +my @ignore_line; + +my %warnings_extended = ( + 'COPYRIGHTYEAR' => 'copyright year incorrect', + 'STRERROR', => 'strerror() detected', + 'STDERR', => 'stderr detected', + ); + +my %warnings = ( + 'ASSIGNWITHINCONDITION' => 'assignment within conditional expression', + 'ASTERISKNOSPACE' => 'pointer declared without space before asterisk', + 'ASTERISKSPACE' => 'pointer declared with space after asterisk', + 'BADCOMMAND' => 'bad !checksrc! instruction', + 'BANNEDFUNC' => 'a banned function was used', + 'BANNEDPREPROC' => 'a banned symbol was used on a preprocessor line', + 'BRACEELSE' => '} else on the same line', + 'BRACEPOS' => 'wrong position for an open brace', + 'BRACEWHILE' => 'A single space between open brace and while', + 'COMMANOSPACE' => 'comma without following space', + 'COMMENTNOSPACEEND' => 'no space before */', + 'COMMENTNOSPACESTART' => 'no space following /*', + 'COPYRIGHT' => 'file missing a copyright statement', + 'CPPCOMMENTS' => '// comment detected', + 'DOBRACE' => 'A single space between do and open brace', + 'EMPTYLINEBRACE' => 'Empty line before the open brace', + 'EQUALSNOSPACE' => 'equals sign without following space', + 'EQUALSNULL' => 'if/while comparison with == NULL', + 'EXCLAMATIONSPACE' => 'Whitespace after exclamation mark in expression', + 'FOPENMODE' => 'fopen needs a macro for the mode string', + 'INCLUDEDUP', => 'same file is included again', + 'INDENTATION' => 'wrong start column for code', + 'LONGLINE' => "Line longer than $max_column", + 'SPACEBEFORELABEL' => 'labels not at the start of the line', + 'MULTISPACE' => 'multiple spaces used when not suitable', + 'NOSPACEEQUALS' => 'equals sign without preceding space', + 'NOTEQUALSZERO', => 'if/while comparison with != 0', + 'ONELINECONDITION' => 'conditional block on the same line as the if()', + 'OPENCOMMENT' => 'file ended with a /* comment still "open"', + 'PARENBRACE' => '){ without sufficient space', + 'RETURNNOSPACE' => 'return without space', + 'SEMINOSPACE' => 'semicolon without following space', + 'SIZEOFNOPAREN' => 'use of sizeof without parentheses', + 'SNPRINTF' => 'use of snprintf', + 'SPACEAFTERPAREN' => 'space after open parenthesis', + 'SPACEBEFORECLOSE' => 'space before a close parenthesis', + 'SPACEBEFORECOMMA' => 'space before a comma', + 'SPACEBEFOREPAREN' => 'space before an open parenthesis', + 'SPACESEMICOLON' => 'space before semicolon', + 'SPACESWITCHCOLON' => 'space before colon of switch label', + 'TABS' => 'TAB characters not allowed', + 'TRAILINGSPACE' => 'Trailing whitespace on the line', + 'TYPEDEFSTRUCT' => 'typedefed struct', + 'UNUSEDIGNORE' => 'a warning ignore was not used', + ); + +sub readskiplist { + open(my $W, '<', "$dir/checksrc.skip") or return; + my @all=<$W>; + for(@all) { + $windows_os ? $_ =~ s/\r?\n$// : chomp; + $skiplist{$_}=1; + } + close($W); +} + +# Reads the .checksrc in $dir for any extended warnings to enable locally. +# Currently there is no support for disabling warnings from the standard set, +# and since that's already handled via !checksrc! commands there is probably +# little use to add it. +sub readlocalfile { + my $i = 0; + + open(my $rcfile, "<", "$dir/.checksrc") or return; + + while(<$rcfile>) { + $windows_os ? $_ =~ s/\r?\n$// : chomp; + $i++; + + # Lines starting with '#' are considered comments + if (/^\s*(#.*)/) { + next; + } + elsif (/^\s*enable ([A-Z]+)$/) { + if(!defined($warnings_extended{$1})) { + print STDERR "invalid warning specified in .checksrc: \"$1\"\n"; + next; + } + $warnings{$1} = $warnings_extended{$1}; + } + elsif (/^\s*disable ([A-Z]+)$/) { + if(!defined($warnings{$1})) { + print STDERR "invalid warning specified in .checksrc: \"$1\"\n"; + next; + } + # Accept-list + push @alist, $1; + } + else { + die "Invalid format in $dir/.checksrc on line $i\n"; + } + } + close($rcfile); +} + +sub checkwarn { + my ($name, $num, $col, $file, $line, $msg, $error) = @_; + + my $w=$error?"error":"warning"; + my $nowarn=0; + + #if(!$warnings{$name}) { + # print STDERR "Dev! there's no description for $name!\n"; + #} + + # checksrc.skip + if($skiplist{$line}) { + $nowarn = 1; + } + # !checksrc! controlled + elsif($ignore{$name}) { + $ignore{$name}--; + $ignore_used{$name}++; + $nowarn = 1; + if(!$ignore{$name}) { + # reached zero, enable again + enable_warn($name, $num, $file, $line); + } + } + + if($nowarn) { + $suppressed++; + if($w) { + $swarnings++; + } + else { + $serrors++; + } + return; + } + + if($w) { + $warnings++; + } + else { + $errors++; + } + + $col++; + print "$file:$num:$col: $w: $msg ($name)\n"; + print " $line\n"; + + if($col < 80) { + my $pref = (' ' x $col); + print "${pref}^\n"; + } +} + +$file = shift @ARGV; + +while(defined $file) { + + if($file =~ /-D(.*)/) { + $dir = $1; + $file = shift @ARGV; + next; + } + elsif($file =~ /-W(.*)/) { + $wlist .= " $1 "; + $file = shift @ARGV; + next; + } + elsif($file =~ /-A(.+)/) { + push @alist, $1; + $file = shift @ARGV; + next; + } + elsif($file =~ /-i([1-9])/) { + $indent = $1 + 0; + $file = shift @ARGV; + next; + } + elsif($file =~ /-m([0-9]+)/) { + $max_column = $1 + 0; + $file = shift @ARGV; + next; + } + elsif($file =~ /^(-h|--help)/) { + undef $file; + last; + } + + last; +} + +if(!$file) { + print "checksrc.pl [option] [file2] ...\n"; + print " Options:\n"; + print " -A[rule] Accept this violation, can be used multiple times\n"; + print " -D[DIR] Directory to prepend file names\n"; + print " -h Show help output\n"; + print " -W[file] Skip the given file - ignore all its flaws\n"; + print " -i Indent spaces. Default: 2\n"; + print " -m Maximum line length. Default: 79\n"; + print "\nDetects and warns for these problems:\n"; + my @allw = keys %warnings; + push @allw, keys %warnings_extended; + for my $w (sort @allw) { + if($warnings{$w}) { + printf (" %-18s: %s\n", $w, $warnings{$w}); + } + else { + printf (" %-18s: %s[*]\n", $w, $warnings_extended{$w}); + } + } + print " [*] = disabled by default\n"; + exit; +} + +readskiplist(); +readlocalfile(); + +do { + if("$wlist" !~ / $file /) { + my $fullname = $file; + $fullname = "$dir/$file" if ($fullname !~ '^\.?\.?/'); + scanfile($fullname); + } + $file = shift @ARGV; + +} while($file); + +sub accept_violations { + for my $r (@alist) { + if(!$warnings{$r}) { + print "'$r' is not a warning to accept!\n"; + exit; + } + $ignore{$r}=999999; + $ignore_used{$r}=0; + } +} + +sub checksrc_clear { + undef %ignore; + undef %ignore_set; + undef @ignore_line; +} + +sub checksrc_endoffile { + my ($file) = @_; + for(keys %ignore_set) { + if($ignore_set{$_} && !$ignore_used{$_}) { + checkwarn("UNUSEDIGNORE", $ignore_set{$_}, + length($_)+11, $file, + $ignore_line[$ignore_set{$_}], + "Unused ignore: $_"); + } + } +} + +sub enable_warn { + my ($what, $line, $file, $l) = @_; + + # switch it back on, but warn if not triggered! + if(!$ignore_used{$what}) { + checkwarn("UNUSEDIGNORE", + $line, length($what) + 11, $file, $l, + "No warning was inhibited!"); + } + $ignore_set{$what}=0; + $ignore_used{$what}=0; + $ignore{$what}=0; +} +sub checksrc { + my ($cmd, $line, $file, $l) = @_; + if($cmd =~ / *([^ ]*) *(.*)/) { + my ($enable, $what) = ($1, $2); + $what =~ s: *\*/$::; # cut off end of C comment + # print "ENABLE $enable WHAT $what\n"; + if($enable eq "disable") { + my ($warn, $scope)=($1, $2); + if($what =~ /([^ ]*) +(.*)/) { + ($warn, $scope)=($1, $2); + } + else { + $warn = $what; + $scope = 1; + } + # print "IGNORE $warn for SCOPE $scope\n"; + if($scope eq "all") { + $scope=999999; + } + + # Comparing for a literal zero rather than the scalar value zero + # covers the case where $scope contains the ending '*' from the + # comment. If we use a scalar comparison (==) we induce warnings + # on non-scalar contents. + if($scope eq "0") { + checkwarn("BADCOMMAND", + $line, 0, $file, $l, + "Disable zero not supported, did you mean to enable?"); + } + elsif($ignore_set{$warn}) { + checkwarn("BADCOMMAND", + $line, 0, $file, $l, + "$warn already disabled from line $ignore_set{$warn}"); + } + else { + $ignore{$warn}=$scope; + $ignore_set{$warn}=$line; + $ignore_line[$line]=$l; + } + } + elsif($enable eq "enable") { + enable_warn($what, $line, $file, $l); + } + else { + checkwarn("BADCOMMAND", + $line, 0, $file, $l, + "Illegal !checksrc! command"); + } + } +} + +sub nostrings { + my ($str) = @_; + $str =~ s/\".*\"//g; + return $str; +} + +sub scanfile { + my ($file) = @_; + + my $line = 1; + my $prevl=""; + my $prevpl=""; + my $l = ""; + my $prep = 0; + my $prevp = 0; + open(my $R, '<', $file) || die "failed to open $file"; + + my $incomment=0; + my @copyright=(); + my %includes; + checksrc_clear(); # for file based ignores + accept_violations(); + + while(<$R>) { + $windows_os ? $_ =~ s/\r?\n$// : chomp; + my $l = $_; + my $ol = $l; # keep the unmodified line for error reporting + my $column = 0; + + # check for !checksrc! commands + if($l =~ /\!checksrc\! (.*)/) { + my $cmd = $1; + checksrc($cmd, $line, $file, $l) + } + + if($l =~ /^#line (\d+) \"([^\"]*)\"/) { + # a #line instruction + $file = $2; + $line = $1; + next; + } + + # check for a copyright statement and save the years + if($l =~ /\* +copyright .* (\d\d\d\d|)/i) { + my $count = 0; + while($l =~ /([\d]{4})/g) { + push @copyright, { + year => $1, + line => $line, + col => index($l, $1), + code => $l + }; + $count++; + } + if(!$count) { + # year-less + push @copyright, { + year => -1, + line => $line, + col => index($l, $1), + code => $l + }; + } + } + + # detect long lines + if(length($l) > $max_column) { + checkwarn("LONGLINE", $line, length($l), $file, $l, + "Longer than $max_column columns"); + } + # detect TAB characters + if($l =~ /^(.*)\t/) { + checkwarn("TABS", + $line, length($1), $file, $l, "Contains TAB character", 1); + } + # detect trailing whitespace + if($l =~ /^(.*)[ \t]+\z/) { + checkwarn("TRAILINGSPACE", + $line, length($1), $file, $l, "Trailing whitespace"); + } + + # no space after comment start + if($l =~ /^(.*)\/\*\w/) { + checkwarn("COMMENTNOSPACESTART", + $line, length($1) + 2, $file, $l, + "Missing space after comment start"); + } + # no space at comment end + if($l =~ /^(.*)\w\*\//) { + checkwarn("COMMENTNOSPACEEND", + $line, length($1) + 1, $file, $l, + "Missing space end comment end"); + } + # ------------------------------------------------------------ + # Above this marker, the checks were done on lines *including* + # comments + # ------------------------------------------------------------ + + # strip off C89 comments + + comment: + if(!$incomment) { + if($l =~ s/\/\*.*\*\// /g) { + # full /* comments */ were removed! + } + if($l =~ s/\/\*.*//) { + # start of /* comment was removed + $incomment = 1; + } + } + else { + if($l =~ s/.*\*\///) { + # end of comment */ was removed + $incomment = 0; + goto comment; + } + else { + # still within a comment + $l=""; + } + } + + # ------------------------------------------------------------ + # Below this marker, the checks were done on lines *without* + # comments + # ------------------------------------------------------------ + + # prev line was a preprocessor **and** ended with a backslash + if($prep && ($prevpl =~ /\\ *\z/)) { + # this is still a preprocessor line + $prep = 1; + goto preproc; + } + $prep = 0; + + # crude attempt to detect // comments without too many false + # positives + if($l =~ /^(([^"\*]*)[^:"]|)\/\//) { + checkwarn("CPPCOMMENTS", + $line, length($1), $file, $l, "\/\/ comment"); + } + + if($l =~ /^(\#\s*include\s+)([\">].*[>}"])/) { + my ($pre, $path) = ($1, $2); + if($includes{$path}) { + checkwarn("INCLUDEDUP", + $line, length($1), $file, $l, "duplicated include"); + } + $includes{$path} = $l; + } + + # detect and strip preprocessor directives + if($l =~ /^[ \t]*\#/) { + # preprocessor line + $prep = 1; + goto preproc; + } + + my $nostr = nostrings($l); + # check spaces after for/if/while/function call + if($nostr =~ /^(.*)(for|if|while|switch| ([a-zA-Z0-9_]+)) \((.)/) { + my ($leading, $word, $extra, $first)=($1,$2,$3,$4); + if($1 =~ / *\#/) { + # this is a #if, treat it differently + } + elsif(defined $3 && $3 eq "return") { + # return must have a space + } + elsif(defined $3 && $3 eq "case") { + # case must have a space + } + elsif(($first eq "*") && ($word !~ /(for|if|while|switch)/)) { + # A "(*" beginning makes the space OK because it wants to + # allow function pointer declared + } + elsif($1 =~ / *typedef/) { + # typedefs can use space-paren + } + else { + checkwarn("SPACEBEFOREPAREN", $line, length($leading)+length($word), $file, $l, + "$word with space"); + } + } + # check for '== NULL' in if/while conditions but not if the thing on + # the left of it is a function call + if($nostr =~ /^(.*)(if|while)(\(.*?)([!=]= NULL|NULL [!=]=)/) { + checkwarn("EQUALSNULL", $line, + length($1) + length($2) + length($3), + $file, $l, "we prefer !variable instead of \"== NULL\" comparisons"); + } + + # check for '!= 0' in if/while conditions but not if the thing on + # the left of it is a function call + if($nostr =~ /^(.*)(if|while)(\(.*[^)]) != 0[^x]/) { + checkwarn("NOTEQUALSZERO", $line, + length($1) + length($2) + length($3), + $file, $l, "we prefer if(rc) instead of \"rc != 0\" comparisons"); + } + + # check spaces in 'do {' + if($nostr =~ /^( *)do( *)\{/ && length($2) != 1) { + checkwarn("DOBRACE", $line, length($1) + 2, $file, $l, "one space after do before brace"); + } + # check spaces in 'do {' + elsif($nostr =~ /^( *)\}( *)while/ && length($2) != 1) { + checkwarn("BRACEWHILE", $line, length($1) + 2, $file, $l, "one space between brace and while"); + } + if($nostr =~ /^((.*\s)(if) *\()(.*)\)(.*)/) { + my $pos = length($1); + my $postparen = $5; + my $cond = $4; + if($cond =~ / = /) { + checkwarn("ASSIGNWITHINCONDITION", + $line, $pos+1, $file, $l, + "assignment within conditional expression"); + } + my $temp = $cond; + $temp =~ s/\(//g; # remove open parens + my $openc = length($cond) - length($temp); + + $temp = $cond; + $temp =~ s/\)//g; # remove close parens + my $closec = length($cond) - length($temp); + my $even = $openc == $closec; + + if($l =~ / *\#/) { + # this is a #if, treat it differently + } + elsif($even && $postparen && + ($postparen !~ /^ *$/) && ($postparen !~ /^ *[,{&|\\]+/)) { + checkwarn("ONELINECONDITION", + $line, length($l)-length($postparen), $file, $l, + "conditional block on the same line"); + } + } + # check spaces after open parentheses + if($l =~ /^(.*[a-z])\( /i) { + checkwarn("SPACEAFTERPAREN", + $line, length($1)+1, $file, $l, + "space after open parenthesis"); + } + + # check spaces before close parentheses, unless it was a space or a + # close parenthesis! + if($l =~ /(.*[^\) ]) \)/) { + checkwarn("SPACEBEFORECLOSE", + $line, length($1)+1, $file, $l, + "space before close parenthesis"); + } + + # check spaces before comma! + if($l =~ /(.*[^ ]) ,/) { + checkwarn("SPACEBEFORECOMMA", + $line, length($1)+1, $file, $l, + "space before comma"); + } + + # check for "return(" without space + if($l =~ /^(.*)return\(/) { + if($1 =~ / *\#/) { + # this is a #if, treat it differently + } + else { + checkwarn("RETURNNOSPACE", $line, length($1)+6, $file, $l, + "return without space before paren"); + } + } + + # check for "sizeof" without parenthesis + if(($l =~ /^(.*)sizeof *([ (])/) && ($2 ne "(")) { + if($1 =~ / *\#/) { + # this is a #if, treat it differently + } + else { + checkwarn("SIZEOFNOPAREN", $line, length($1)+6, $file, $l, + "sizeof without parenthesis"); + } + } + + # check for comma without space + if($l =~ /^(.*),[^ \n]/) { + my $pref=$1; + my $ign=0; + if($pref =~ / *\#/) { + # this is a #if, treat it differently + $ign=1; + } + elsif($pref =~ /\/\*/) { + # this is a comment + $ign=1; + } + elsif($pref =~ /[\"\']/) { + $ign = 1; + # There is a quote here, figure out whether the comma is + # within a string or '' or not. + if($pref =~ /\"/) { + # within a string + } + elsif($pref =~ /\'$/) { + # a single letter + } + else { + $ign = 0; + } + } + if(!$ign) { + checkwarn("COMMANOSPACE", $line, length($pref)+1, $file, $l, + "comma without following space"); + } + } + + # check for "} else" + if($l =~ /^(.*)\} *else/) { + checkwarn("BRACEELSE", + $line, length($1), $file, $l, "else after closing brace on same line"); + } + # check for "){" + if($l =~ /^(.*)\)\{/) { + checkwarn("PARENBRACE", + $line, length($1)+1, $file, $l, "missing space after close paren"); + } + # check for "^{" with an empty line before it + if(($l =~ /^\{/) && ($prevl =~ /^[ \t]*\z/)) { + checkwarn("EMPTYLINEBRACE", + $line, 0, $file, $l, "empty line before open brace"); + } + + # check for space before the semicolon last in a line + if($l =~ /^(.*[^ ].*) ;$/) { + checkwarn("SPACESEMICOLON", + $line, length($1), $file, $ol, "no space before semicolon"); + } + + # check for space before the colon in a switch label + if($l =~ /^( *(case .+|default)) :/) { + checkwarn("SPACESWITCHCOLON", + $line, length($1), $file, $ol, "no space before colon of switch label"); + } + + if($prevl !~ /\?\z/ && $l =~ /^ +([A-Za-z_][A-Za-z0-9_]*):$/ && $1 ne 'default') { + checkwarn("SPACEBEFORELABEL", + $line, length($1), $file, $ol, "no space before label"); + } + + # scan for use of banned functions + if($l =~ /^(.*\W) + (gmtime|localtime| + gets| + strtok| + v?sprintf| + (str|_mbs|_tcs|_wcs)n?cat| + LoadLibrary(Ex)?(A|W)?| + _?w?access) + \s*\( + /x) { + checkwarn("BANNEDFUNC", + $line, length($1), $file, $ol, + "use of $2 is banned"); + } + if($warnings{"STRERROR"}) { + # scan for use of banned strerror. This is not a BANNEDFUNC to + # allow for individual enable/disable of this warning. + if($l =~ /^(.*\W)(strerror)\s*\(/x) { + if($1 !~ /^ *\#/) { + # skip preprocessor lines + checkwarn("STRERROR", + $line, length($1), $file, $ol, + "use of $2 is banned"); + } + } + } + if($warnings{"STDERR"}) { + # scan for use of banned stderr. This is not a BANNEDFUNC to + # allow for individual enable/disable of this warning. + if($l =~ /^([^\"-]*\W)(stderr)[^\"_]/x) { + if($1 !~ /^ *\#/) { + # skip preprocessor lines + checkwarn("STDERR", + $line, length($1), $file, $ol, + "use of $2 is banned (use tool_stderr instead)"); + } + } + } + # scan for use of snprintf for curl-internals reasons + if($l =~ /^(.*\W)(v?snprintf)\s*\(/x) { + checkwarn("SNPRINTF", + $line, length($1), $file, $ol, + "use of $2 is banned"); + } + + # scan for use of non-binary fopen without the macro + if($l =~ /^(.*\W)fopen\s*\([^,]*, *\"([^"]*)/) { + my $mode = $2; + if($mode !~ /b/) { + checkwarn("FOPENMODE", + $line, length($1), $file, $ol, + "use of non-binary fopen without FOPEN_* macro: $mode"); + } + } + + # check for open brace first on line but not first column only alert + # if previous line ended with a close paren and it wasn't a cpp line + if(($prevl =~ /\)\z/) && ($l =~ /^( +)\{/) && !$prevp) { + checkwarn("BRACEPOS", + $line, length($1), $file, $ol, "badly placed open brace"); + } + + # if the previous line starts with if/while/for AND ends with an open + # brace, or an else statement, check that this line is indented $indent + # more steps, if not a cpp line + if(!$prevp && ($prevl =~ /^( *)((if|while|for)\(.*\{|else)\z/)) { + my $first = length($1); + # this line has some character besides spaces + if($l =~ /^( *)[^ ]/) { + my $second = length($1); + my $expect = $first+$indent; + if($expect != $second) { + my $diff = $second - $first; + checkwarn("INDENTATION", $line, length($1), $file, $ol, + "not indented $indent steps (uses $diff)"); + + } + } + } + + # if the previous line starts with if/while/for AND ends with a closed + # parenthesis and there's an equal number of open and closed + # parentheses, check that this line is indented $indent more steps, if + # not a cpp line + elsif(!$prevp && ($prevl =~ /^( *)(if|while|for)(\(.*\))\z/)) { + my $first = length($1); + my $op = $3; + my $cl = $3; + + $op =~ s/[^(]//g; + $cl =~ s/[^)]//g; + + if(length($op) == length($cl)) { + # this line has some character besides spaces + if($l =~ /^( *)[^ ]/) { + my $second = length($1); + my $expect = $first+$indent; + if($expect != $second) { + my $diff = $second - $first; + checkwarn("INDENTATION", $line, length($1), $file, $ol, + "not indented $indent steps (uses $diff)"); + } + } + } + } + + # check for 'char * name' + if(($l =~ /(^.*(char|int|long|void|CURL|CURLM|CURLMsg|[cC]url_[A-Za-z_]+|struct [a-zA-Z_]+) *(\*+)) (\w+)/) && ($4 !~ /^(const|volatile)$/)) { + checkwarn("ASTERISKSPACE", + $line, length($1), $file, $ol, + "space after declarative asterisk"); + } + # check for 'char*' + if(($l =~ /(^.*(char|int|long|void|curl_slist|CURL|CURLM|CURLMsg|curl_httppost|sockaddr_in|FILE)\*)/)) { + checkwarn("ASTERISKNOSPACE", + $line, length($1)-1, $file, $ol, + "no space before asterisk"); + } + + # check for 'void func() {', but avoid false positives by requiring + # both an open and closed parentheses before the open brace + if($l =~ /^((\w).*)\{\z/) { + my $k = $1; + $k =~ s/const *//; + $k =~ s/static *//; + if($k =~ /\(.*\)/) { + checkwarn("BRACEPOS", + $line, length($l)-1, $file, $ol, + "wrongly placed open brace"); + } + } + + # check for equals sign without spaces next to it + if($nostr =~ /(.*)\=[a-z0-9]/i) { + checkwarn("EQUALSNOSPACE", + $line, length($1)+1, $file, $ol, + "no space after equals sign"); + } + # check for equals sign without spaces before it + elsif($nostr =~ /(.*)[a-z0-9]\=/i) { + checkwarn("NOSPACEEQUALS", + $line, length($1)+1, $file, $ol, + "no space before equals sign"); + } + + # check for plus signs without spaces next to it + if($nostr =~ /(.*)[^+]\+[a-z0-9]/i) { + checkwarn("PLUSNOSPACE", + $line, length($1)+1, $file, $ol, + "no space after plus sign"); + } + # check for plus sign without spaces before it + elsif($nostr =~ /(.*)[a-z0-9]\+[^+]/i) { + checkwarn("NOSPACEPLUS", + $line, length($1)+1, $file, $ol, + "no space before plus sign"); + } + + # check for semicolons without space next to it + if($nostr =~ /(.*)\;[a-z0-9]/i) { + checkwarn("SEMINOSPACE", + $line, length($1)+1, $file, $ol, + "no space after semicolon"); + } + + # typedef struct ... { + if($nostr =~ /^(.*)typedef struct.*{/) { + checkwarn("TYPEDEFSTRUCT", + $line, length($1)+1, $file, $ol, + "typedef'ed struct"); + } + + if($nostr =~ /(.*)! +(\w|\()/) { + checkwarn("EXCLAMATIONSPACE", + $line, length($1)+1, $file, $ol, + "space after exclamation mark"); + } + + # check for more than one consecutive space before open brace or + # question mark. Skip lines containing strings since they make it hard + # due to artificially getting multiple spaces + if(($l eq $nostr) && + $nostr =~ /^(.*(\S)) + [{?]/i) { + checkwarn("MULTISPACE", + $line, length($1)+1, $file, $ol, + "multiple spaces"); + } + preproc: + if($prep) { + # scan for use of banned symbols on a preprocessor line + if($l =~ /^(^|.*\W) + (WIN32) + (\W|$) + /x) { + checkwarn("BANNEDPREPROC", + $line, length($1), $file, $ol, + "use of $2 is banned from preprocessor lines" . + (($2 eq "WIN32") ? ", use _WIN32 instead" : "")); + } + } + $line++; + $prevp = $prep; + $prevl = $ol if(!$prep); + $prevpl = $ol if($prep); + } + + if(!scalar(@copyright)) { + checkwarn("COPYRIGHT", 1, 0, $file, "", "Missing copyright statement", 1); + } + + # COPYRIGHTYEAR is an extended warning so we must first see if it has been + # enabled in .checksrc + if(defined($warnings{"COPYRIGHTYEAR"})) { + # The check for updated copyrightyear is overly complicated in order to + # not punish current hacking for past sins. The copyright years are + # right now a bit behind, so enforcing copyright year checking on all + # files would cause hundreds of errors. Instead we only look at files + # which are tracked in the Git repo and edited in the workdir, or + # committed locally on the branch without being in upstream master. + # + # The simple and naive test is to simply check for the current year, + # but updating the year even without an edit is against project policy + # (and it would fail every file on January 1st). + # + # A rather more interesting, and correct, check would be to not test + # only locally committed files but inspect all files wrt the year of + # their last commit. Removing the `git rev-list origin/master..HEAD` + # condition below will enforce copyright year checks against the year + # the file was last committed (and thus edited to some degree). + my $commityear = undef; + @copyright = sort {$$b{year} cmp $$a{year}} @copyright; + + # if the file is modified, assume commit year this year + if(`git status -s -- "$file"` =~ /^ [MARCU]/) { + $commityear = (localtime(time))[5] + 1900; + } + else { + # min-parents=1 to ignore wrong initial commit in truncated repos + my $grl = `git rev-list --max-count=1 --min-parents=1 --timestamp HEAD -- "$file"`; + if($grl) { + chomp $grl; + $commityear = (localtime((split(/ /, $grl))[0]))[5] + 1900; + } + } + + if(defined($commityear) && scalar(@copyright) && + $copyright[0]{year} != $commityear) { + checkwarn("COPYRIGHTYEAR", $copyright[0]{line}, $copyright[0]{col}, + $file, $copyright[0]{code}, + "Copyright year out of date, should be $commityear, " . + "is $copyright[0]{year}", 1); + } + } + + if($incomment) { + checkwarn("OPENCOMMENT", 1, 0, $file, "", "Missing closing comment", 1); + } + + checksrc_endoffile($file); + + close($R); + +} + + +if($errors || $warnings || $verbose) { + printf "checksrc: %d errors and %d warnings\n", $errors, $warnings; + if($suppressed) { + printf "checksrc: %d errors and %d warnings suppressed\n", + $serrors, + $swarnings; + } + exit 5; # return failure +} diff --git a/third_party/curl/scripts/completion.pl b/third_party/curl/scripts/completion.pl new file mode 100755 index 0000000..00c7368 --- /dev/null +++ b/third_party/curl/scripts/completion.pl @@ -0,0 +1,166 @@ +#!/usr/bin/env perl +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +use strict; +use warnings; +use Getopt::Long(); +use Pod::Usage(); + +my $curl = 'curl'; +my $shell = 'zsh'; +my $help = 0; +Getopt::Long::GetOptions( + 'curl=s' => \$curl, + 'shell=s' => \$shell, + 'help' => \$help, +) or Pod::Usage::pod2usage(); +Pod::Usage::pod2usage() if $help; + +my $regex = '\s+(?:(-[^\s]+),\s)?(--[^\s]+)\s*(\<.+?\>)?\s+(.*)'; +my @opts = parse_main_opts('--help all', $regex); + +if ($shell eq 'fish') { + print "# curl fish completion\n\n"; + print qq{$_ \n} foreach (@opts); +} elsif ($shell eq 'zsh') { + my $opts_str; + + $opts_str .= qq{ $_ \\\n} foreach (@opts); + chomp $opts_str; + +my $tmpl = <<"EOS"; +#compdef curl + +# curl zsh completion + +local curcontext="\$curcontext" state state_descr line +typeset -A opt_args + +local rc=1 + +_arguments -C -S \\ +$opts_str + '*:URL:_urls' && rc=0 + +return rc +EOS + + print $tmpl; +} else { + die("Unsupported shell: $shell"); +} + +sub parse_main_opts { + my ($cmd, $regex) = @_; + + my @list; + my @lines = call_curl($cmd); + + foreach my $line (@lines) { + my ($short, $long, $arg, $desc) = ($line =~ /^$regex/) or next; + + my $option = ''; + + $arg =~ s/\:/\\\:/g if defined $arg; + + $desc =~ s/'/'\\''/g if defined $desc; + $desc =~ s/\[/\\\[/g if defined $desc; + $desc =~ s/\]/\\\]/g if defined $desc; + $desc =~ s/\:/\\\:/g if defined $desc; + + if ($shell eq 'fish') { + $option .= "complete --command curl"; + $option .= " --short-option '" . strip_dash(trim($short)) . "'" + if defined $short; + $option .= " --long-option '" . strip_dash(trim($long)) . "'" + if defined $long; + $option .= " --description '" . strip_dash(trim($desc)) . "'" + if defined $desc; + } elsif ($shell eq 'zsh') { + $option .= '{' . trim($short) . ',' if defined $short; + $option .= trim($long) if defined $long; + $option .= '}' if defined $short; + $option .= '\'[' . trim($desc) . ']\'' if defined $desc; + + if (defined $arg) { + $option .= ":'$arg'"; + if ($arg =~ /|/) { + $option .= ':_files'; + } elsif ($arg =~ //) { + $option .= ":'_path_files -/'"; + } elsif ($arg =~ //i) { + $option .= ':_urls'; + } elsif ($long =~ /ftp/ && $arg =~ //) { + $option .= ":'(multicwd nocwd singlecwd)'"; + } elsif ($arg =~ //) { + $option .= ":'(DELETE GET HEAD POST PUT)'"; + } + } + } + + push @list, $option; + } + + # Sort longest first, because zsh won't complete an option listed + # after one that's a prefix of it. + @list = sort { + $a =~ /([^=]*)/; my $ma = $1; + $b =~ /([^=]*)/; my $mb = $1; + + length($mb) <=> length($ma) + } @list if $shell eq 'zsh'; + + return @list; +} + +sub trim { my $s = shift; $s =~ s/^\s+|\s+$//g; return $s }; +sub strip_dash { my $s = shift; $s =~ s/^-+//g; return $s }; + +sub call_curl { + my ($cmd) = @_; + my $output = `"$curl" $cmd`; + if ($? == -1) { + die "Could not run curl: $!"; + } elsif ((my $exit_code = $? >> 8) != 0) { + die "curl returned $exit_code with output:\n$output"; + } + return split /\n/, $output; +} + +__END__ + +=head1 NAME + +completion.pl - Generates tab-completion files for various shells + +=head1 SYNOPSIS + +completion.pl [options...] + + --curl path to curl executable + --shell zsh/fish + --help prints this help + +=cut diff --git a/third_party/curl/scripts/coverage.sh b/third_party/curl/scripts/coverage.sh new file mode 100755 index 0000000..b554056 --- /dev/null +++ b/third_party/curl/scripts/coverage.sh @@ -0,0 +1,41 @@ +#!/bin/sh +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +set -eu + +autoreconf -fi +mkdir -p cvr +cd cvr +../configure --disable-shared --enable-debug --enable-maintainer-mode --enable-code-coverage +make -sj +# the regular test run +make TFLAGS=-n test-nonflaky +# make all allocs/file operations fail +#make TFLAGS=-n test-torture +# do everything event-based +make TFLAGS=-n test-event +lcov -d . -c -o cov.lcov +genhtml cov.lcov --output-directory coverage --title "curl code coverage" +tar -cjf curl-coverage.tar.bz2 coverage diff --git a/third_party/curl/scripts/dmaketgz b/third_party/curl/scripts/dmaketgz new file mode 100755 index 0000000..2587479 --- /dev/null +++ b/third_party/curl/scripts/dmaketgz @@ -0,0 +1,52 @@ +#!/bin/sh +# docker-maketgz +# +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +set -eu + +version="${1:-}" + +if [ -z "$version" ]; then + echo "Specify a version number!" + exit +fi + +timestamp="${2:-$(date -u +%s)}" + +make distclean +docker build \ + --build-arg SOURCE_DATE_EPOCH="$timestamp" \ + --build-arg UID="$(id -u)" \ + --build-arg GID="$(id -g)" \ + -t curl/curl . + +docker run --rm -it -u "$(id -u):$(id -g)" \ + -v "$(pwd):/usr/src" -w /usr/src curl/curl sh -c " + set -e + autoreconf -fi + ./configure --without-ssl --without-libpsl + make -sj8 + ./maketgz $version" diff --git a/third_party/curl/scripts/firefox-db2pem.sh b/third_party/curl/scripts/firefox-db2pem.sh new file mode 100755 index 0000000..a45a881 --- /dev/null +++ b/third_party/curl/scripts/firefox-db2pem.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# *************************************************************************** +# * _ _ ____ _ +# * Project ___| | | | _ \| | +# * / __| | | | |_) | | +# * | (__| |_| | _ <| |___ +# * \___|\___/|_| \_\_____| +# * +# * Copyright (C) Daniel Stenberg, , 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. +# * +# * SPDX-License-Identifier: curl +# * +# *************************************************************************** +# This shell script creates a fresh ca-bundle.crt file for use with libcurl. +# It extracts all ca certs it finds in the local Firefox database and converts +# them all into PEM format. +# + +set -eu + +db=$(ls -1d "$HOME"/.mozilla/firefox/*default*) +out="${1:-}" + +if test -z "$out"; then + out="ca-bundle.crt" # use a sensible default +fi + +currentdate=$(date) + +cat > "$out" <> "$out" diff --git a/third_party/curl/scripts/managen b/third_party/curl/scripts/managen new file mode 100755 index 0000000..8f16783 --- /dev/null +++ b/third_party/curl/scripts/managen @@ -0,0 +1,1143 @@ +#!/usr/bin/env perl +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , 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. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +=begin comment + +This script generates the manpage. + +Example: managen [files] > curl.1 + +Dev notes: + +We open *input* files in :crlf translation (a no-op on many platforms) in +case we have CRLF line endings in Windows but a perl that defaults to LF. +Unfortunately it seems some perls like msysgit cannot handle a global input-only +:crlf so it has to be specified on each file open for text input. + +=end comment +=cut + +my %optshort; +my %optlong; +my %helplong; +my %arglong; +my %redirlong; +my %protolong; +my %catlong; + +use POSIX qw(strftime); +my @ts; +if (defined($ENV{SOURCE_DATE_EPOCH})) { + @ts = gmtime($ENV{SOURCE_DATE_EPOCH}); +} else { + @ts = localtime; +} +my $date = strftime "%Y-%m-%d", @ts; +my $year = strftime "%Y", @ts; +my $version = "unknown"; +my $globals; + +# get the long name version, return the man page string +sub manpageify { + my ($k)=@_; + my $l; + my $trail; + # the matching pattern might include a trailing dot that cannot be part of + # the option name + if($k =~ s/\.$//) { + # cut off trailing dot + $trail = "."; + } + my $klong = $k; + # quote "bare" minuses in the long name + $klong =~ s/-/\\-/g; + if($optlong{$k}) { + # both short + long + $l = "\\fI-".$optlong{$k}.", \\-\\-$klong\\fP$trail"; + } + else { + # only long + $l = "\\fI\\-\\-$klong\\fP$trail"; + } + return $l; +} + + +my $colwidth=78; # max number of columns + +sub justline { + my ($lvl, @line) = @_; + my $w = -1; + my $spaces = -1; + my $width = $colwidth - ($lvl * 4); + for(@line) { + $w += length($_); + $w++; + $spaces++; + } + my $inject = $width - $w; + my $ratio = 0; # stay at zero if no spaces at all + if($spaces) { + $ratio = $inject / $spaces; + } + my $spare = 0; + print ' ' x ($lvl * 4); + my $prev; + for(@line) { + while($spare >= 0.90) { + print " "; + $spare--; + } + printf "%s%s", $prev?" ":"", $_; + $prev = 1; + $spare += $ratio; + } + print "\n"; +} + +sub lastline { + my ($lvl, @line) = @_; + print ' ' x ($lvl * 4); + my $prev = 0; + for(@line) { + printf "%s%s", $prev?" ":"", $_; + $prev = 1; + } + print "\n"; +} + +sub outputpara { + my ($lvl, $f) = @_; + $f =~ s/\n/ /g; + + my $w = 0; + my @words = split(/ */, $f); + my $width = $colwidth - ($lvl * 4); + + my @line; + for my $e (@words) { + my $l = length($e); + my $spaces = scalar(@line); + if(($w + $l + $spaces) >= $width) { + justline($lvl, @line); + undef @line; + $w = 0; + } + + push @line, $e; + $w += $l; # new width + } + if($w) { + lastline($lvl, @line); + print "\n"; + } +} + +sub printdesc { + my ($manpage, $baselvl, @desc) = @_; + + if($manpage) { + for my $d (@desc) { + print $d; + } + } + else { + my $p = -1; + my $para; + for my $l (@desc) { + my $lvl; + if($l !~ /^[\n\r]+/) { + # get the indent level off the string + $l =~ s/^\[([0-9q]*)\]//; + $lvl = $1; + } + if(($p =~ /q/) && ($lvl !~ /q/)) { + # the previous was quoted, this is not + print "\n"; + } + if($lvl != $p) { + outputpara($baselvl + $p, $para); + $para = ""; + } + if($lvl =~ /q/) { + # quoted, do not right-justify + chomp $l; + lastline($baselvl + $lvl + 1, $l); + } + else { + $para .= $l; + } + + $p = $lvl; + } + outputpara($baselvl + $p, $para); + } +} + +sub seealso { + my($standalone, $data)=@_; + if($standalone) { + return sprintf + ".SH \"SEE ALSO\"\n$data\n"; + } + else { + return "See also $data. "; + } +} + +sub overrides { + my ($standalone, $data)=@_; + if($standalone) { + return ".SH \"OVERRIDES\"\n$data\n"; + } + else { + return $data; + } +} + +sub protocols { + my ($manpage, $standalone, $data)=@_; + if($standalone) { + return ".SH \"PROTOCOLS\"\n$data\n"; + } + else { + return "($data) " if($manpage); + return "[1]($data) " if(!$manpage); + } +} + +sub too_old { + my ($version)=@_; + my $a = 999999; + if($version =~ /^(\d+)\.(\d+)\.(\d+)/) { + $a = $1 * 1000 + $2 * 10 + $3; + } + elsif($version =~ /^(\d+)\.(\d+)/) { + $a = $1 * 1000 + $2 * 10; + } + if($a < 7500) { + # we consider everything before 7.50.0 to be too old to mention + # specific changes for + return 1; + } + return 0; +} + +sub added { + my ($standalone, $data)=@_; + if(too_old($data)) { + # do not mention ancient additions + return ""; + } + if($standalone) { + return ".SH \"ADDED\"\nAdded in curl version $data\n"; + } + else { + return "Added in $data. "; + } +} + +sub render { + my ($manpage, $fh, $f, $line) = @_; + my @desc; + my $tablemode = 0; + my $header = 0; + # if $top is TRUE, it means a top-level page and not a command line option + my $top = ($line == 1); + my $quote; + my $level; + $start = 0; + + while(<$fh>) { + my $d = $_; + $line++; + if($d =~ /^\.(SH|BR|IP|B)/) { + print STDERR "$f:$line:1:ERROR: nroff instruction in input: \".$1\"\n"; + return 4; + } + if(/^ * + +# Building curl with Visual C++ + + This document describes how to compile, build and install curl and libcurl + from sources using the Visual C++ build tool. To build with VC++, you will of + course have to first install VC++. The minimum required version of VC is 6 + (part of Visual Studio 6). However using a more recent version is strongly + recommended. + + VC++ is also part of the Windows Platform SDK. You do not have to install the + full Visual Studio or Visual C++ if all you want is to build curl. + + The latest Platform SDK can be downloaded freely from [Windows SDK and + emulator + archive](https://developer.microsoft.com/en-us/windows/downloads/sdk-archive) + +## Prerequisites + + If you wish to support zlib, OpenSSL, c-ares, ssh2, you will have to download + them separately and copy them to the `deps` directory as shown below: + + somedirectory\ + |_curl-src + | |_winbuild + | + |_deps + |_ lib + |_ include + |_ bin + + It is also possible to create the `deps` directory in some other random places + and tell the `Makefile` its location using the `WITH_DEVEL` option. + +## Building straight from git + + When you check out code git and build it, as opposed from a released source + code archive, you need to first run the `buildconf.bat` batch file (present + in the source code root directory) to set things up. + +## Open a command prompt + +Open a Visual Studio Command prompt: + + Using the **'Developer Command Prompt for VS [version]'** menu entry: where + [version} is the Visual Studio version. The developer prompt at default uses + the x86 mode. It is required to call `Vcvarsall.bat` to setup the prompt for + the machine type you want. This type of command prompt may not exist in all + Visual Studio versions. + + See also: [Developer Command Prompt for Visual + Studio](https://docs.microsoft.com/en-us/dotnet/framework/tools/developer-command-prompt-for-vs) + and [How to: Enable a 64-Bit, x64 hosted MSVC toolset on the command + line](https://docs.microsoft.com/en-us/cpp/build/how-to-enable-a-64-bit-visual-cpp-toolset-on-the-command-line) + + Using the **'VS [version] [platform] [type] Command Prompt'** menu entry: + where [version] is the Visual Studio version, [platform] is e.g. x64 and + [type] Native of Cross platform build. This type of command prompt may not + exist in all Visual Studio versions. + + See also: [Set the Path and Environment Variables for Command-Line Builds](https://docs.microsoft.com/en-us/cpp/build/building-on-the-command-line) + +## Build in the console + + Once you are in the console, go to the winbuild directory in the Curl + sources: + + cd curl-src\winbuild + + Then you can call `nmake /f Makefile.vc` with the desired options (see + below). The builds will be in the top src directory, `builds\` directory, in + a directory named using the options given to the nmake call. + + nmake /f Makefile.vc mode= + +where `` is one or many of: + + - `VC=` - VC version. 6 or later. + - `WITH_DEVEL=` - Paths for the development files (SSL, zlib, etc.) + Defaults to sibling directory: `../deps` + - `WITH_SSL=` - Enable OpenSSL support, DLL or static + - `WITH_NGHTTP2=` - Enable HTTP/2 support, DLL or static + - `WITH_MSH3=` - Enable (experimental) HTTP/3 support, DLL or static + - `WITH_MBEDTLS=` - Enable mbedTLS support, DLL or static + - `WITH_CARES=` - Enable c-ares support, DLL or static + - `WITH_ZLIB=` - Enable zlib support, DLL or static + - `WITH_SSH=` - Enable libSSH support, DLL or static + - `WITH_SSH2=` - Enable libSSH2 support, DLL or static + - `WITH_PREFIX=` - Where to install the build + - `ENABLE_SSPI=` - Enable SSPI support, defaults to yes + - `ENABLE_IPV6=` - Enable IPv6, defaults to yes + - `ENABLE_IDN=` - Enable use of Windows IDN APIs, defaults to yes + Requires Windows Vista or later + - `ENABLE_SCHANNEL=` - Enable native Windows SSL support, defaults + to yes if SSPI and no other SSL library + - `ENABLE_OPENSSL_AUTO_LOAD_CONFIG=` + - Enable loading OpenSSL configuration + automatically, defaults to yes + - `ENABLE_UNICODE=` - Enable UNICODE support, defaults to no + - `ENABLE_WEBSOCKETS=` - Enable Web Socket support, defaults to no + - `GEN_PDB=` - Generate External Program Database + (debug symbols for release build) + - `DEBUG=` - Debug builds + - `MACHINE=` - Target architecture (default is x86) + - `CARES_PATH=` - Custom path for c-ares + - `MBEDTLS_PATH=` - Custom path for mbedTLS + - `NGHTTP2_PATH=` - Custom path for nghttp2 + - `MSH3_PATH=` - Custom path for msh3 + - `SSH2_PATH=` - Custom path for libSSH2 + - `SSL_PATH=` - Custom path for OpenSSL + - `ZLIB_PATH=` - Custom path for zlib + +## Static linking of Microsoft's C runtime (CRT): + + If you are using mode=static nmake will create and link to the static build + of libcurl but *not* the static CRT. If you must you can force nmake to link + in the static CRT by passing `RTLIBCFG=static`. Typically you shouldn't use + that option, and nmake will default to the DLL CRT. `RTLIBCFG` is rarely used + and therefore rarely tested. When passing `RTLIBCFG` for a configuration that + was already built but not with that option, or if the option was specified + differently, you must destroy the build directory containing the + configuration so that nmake can build it from scratch. + + This option is not recommended unless you have enough development experience + to know how to match the runtime library for linking (that is, the CRT). If + `RTLIBCFG=static` then release builds use `/MT` and debug builds use `/MTd`. + +## Building your own application with libcurl (Visual Studio example) + + When you build curl and libcurl, nmake will show the relative path where the + output directory is. The output directory is named from the options nmake used + when building. You may also see temp directories of the same name but with + suffixes -obj-curl and -obj-lib. + + For example let's say you've built curl.exe and libcurl.dll from the Visual + Studio 2010 x64 Win64 Command Prompt: + + nmake /f Makefile.vc mode=dll VC=10 + + The output directory will have a name similar to + `..\builds\libcurl-vc10-x64-release-dll-ipv6-sspi-schannel`. + + The output directory contains subdirectories bin, lib and include. Those are + the directories to set in your Visual Studio project. You can either copy the + output directory to your project or leave it in place. Following the example, + let's assume you leave it in place and your curl top source directory is + `C:\curl-7.82.0`. You would set these options for configurations using the + x64 platform: + +~~~ + - Configuration Properties > Debugging > Environment + PATH=C:\curl-7.82.0\builds\libcurl-vc10-x64-release-dll-ipv6-sspi-schannel\bin;%PATH% + + - C/C++ > General > Additional Include Directories + C:\curl-7.82.0\builds\libcurl-vc10-x64-release-dll-ipv6-sspi-schannel\include; + + - Linker > General > Additional Library Directories + C:\curl-7.82.0\builds\libcurl-vc10-x64-release-dll-ipv6-sspi-schannel\lib; + + - Linker > Input > Additional Dependencies + libcurl.lib; +~~~ + + For configurations using the x86 platform (aka Win32 platform) you would + need to make a separate x86 build of libcurl. + + If you build libcurl static (`mode=static`) or debug (`DEBUG=yes`) then the + library name will vary and separate builds may be necessary for separate + configurations of your project within the same platform. This is discussed in + the next section. + +## Building your own application with a static libcurl + + When building an application that uses the static libcurl library on Windows, + you must define `CURL_STATICLIB`. Otherwise the linker will look for dynamic + import symbols. + + The static library name has an `_a` suffix in the basename and the debug + library name has a `_debug` suffix in the basename. For example, + `libcurl_a_debug.lib` is a static debug build of libcurl. + + You may need a separate build of libcurl for each VC configuration combination + (for example: Debug|Win32, Debug|x64, Release|Win32, Release|x64). + + You must specify any additional dependencies needed by your build of static + libcurl (for example: + `advapi32.lib;crypt32.lib;normaliz.lib;ws2_32.lib;wldap32.lib`). + +## Legacy Windows and SSL + + When you build curl using the build files in this directory the default SSL + backend will be Schannel (Windows SSPI), the native SSL library that comes + with the Windows OS. Schannel in Windows <= XP is not able to connect to + servers that no longer support the legacy handshakes and algorithms used by + those versions. If you will be using curl in one of those earlier versions of + Windows you should choose another SSL backend like OpenSSL. diff --git a/third_party/curl/winbuild/gen_resp_file.bat b/third_party/curl/winbuild/gen_resp_file.bat new file mode 100755 index 0000000..6286fd0 --- /dev/null +++ b/third_party/curl/winbuild/gen_resp_file.bat @@ -0,0 +1,34 @@ +@echo off +rem *************************************************************************** +rem * _ _ ____ _ +rem * Project ___| | | | _ \| | +rem * / __| | | | |_) | | +rem * | (__| |_| | _ <| |___ +rem * \___|\___/|_| \_\_____| +rem * +rem * Copyright (C) Daniel Stenberg, , et al. +rem * +rem * This software is licensed as described in the file COPYING, which +rem * you should have received as part of this distribution. The terms +rem * are also available at https://curl.se/docs/copyright.html. +rem * +rem * You may opt to use, copy, modify, merge, publish, distribute and/or sell +rem * copies of the Software, and permit persons to whom the Software is +rem * furnished to do so, under the terms of the COPYING file. +rem * +rem * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +rem * KIND, either express or implied. +rem * +rem * SPDX-License-Identifier: curl +rem * +rem *************************************************************************** + +if exist %OUTFILE% ( + del %OUTFILE% +) + +echo %MACRO_NAME% = \> %OUTFILE% +for %%i in (%*) do echo %DIROBJ%/%%i \>> %OUTFILE% +echo. >> %OUTFILE% + +:END diff --git a/third_party/curl/winbuild/makedebug.cmd b/third_party/curl/winbuild/makedebug.cmd new file mode 100644 index 0000000..dada9c6 --- /dev/null +++ b/third_party/curl/winbuild/makedebug.cmd @@ -0,0 +1,36 @@ +@echo off +rem *************************************************************************** +rem * _ _ ____ _ +rem * Project ___| | | | _ \| | +rem * / __| | | | |_) | | +rem * | (__| |_| | _ <| |___ +rem * \___|\___/|_| \_\_____| +rem * +rem * Copyright (C) Daniel Stenberg, , et al. +rem * +rem * This software is licensed as described in the file COPYING, which +rem * you should have received as part of this distribution. The terms +rem * are also available at https://curl.se/docs/copyright.html. +rem * +rem * You may opt to use, copy, modify, merge, publish, distribute and/or sell +rem * copies of the Software, and permit persons to whom the Software is +rem * furnished to do so, under the terms of the COPYING file. +rem * +rem * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +rem * KIND, either express or implied. +rem * +rem * SPDX-License-Identifier: curl +rem * +rem *************************************************************************** + +where.exe nmake.exe >nul 2>&1 + +IF %ERRORLEVEL% == 1 ( + ECHO Error: Can't find `nmake.exe` - be sure to run this script from within a Developer Command-Prompt + ECHO. +) ELSE ( + nmake /f Makefile.vc mode=static DEBUG=yes GEN_PDB=yes + IF %ERRORLEVEL% NEQ 0 ( + ECHO "Error: Build Failed" + ) +) diff --git a/third_party/date/.gitignore b/third_party/date/.gitignore new file mode 100644 index 0000000..e88e3be --- /dev/null +++ b/third_party/date/.gitignore @@ -0,0 +1,194 @@ +#ignore thumbnails created by windows +Thumbs.db +#Ignore files build by Visual Studio +*.obj +*.exe +*.pdb +*.user +*.aps +*.pch +*.vspscc +*_i.c +*_p.c +*.ncb +*.suo +*.tlb +*.tlh +*.bak +*.cache +*.ilk +*.log +[Bb]in +[Dd]ebug*/ +*.lib +*.sbr +obj/ +[Rr]elease*/ +_ReSharper*/ +[Tt]est[Rr]esult* +.idea/ +*.opensdf +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates +# User-specific folders +*.sln.ide/ +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +build/ +bld/ +[Bb]in/ +[Oo]bj/ +# Roslyn cache directories +*.ide/ +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* +#NUNIT +*.VisualState.xml +TestResult.xml +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc +# Chutzpah Test files +_Chutzpah* +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile +# Visual Studio profiler +*.psess +*.vsp +*.vspx +# TFS 2012 Local Workspace +$tf/ +# Guidance Automation Toolkit +*.gpState +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user +# JustCode is a .NET coding addin-in +.JustCode +# TeamCity is a build add-in +_TeamCity* +# DotCover is a Code Coverage Tool +*.dotCover +# NCrunch +_NCrunch_* +.*crunch*.local.xml +# MightyMoose +*.mm.* +AutoTest.Net/ +# Web workbench (sass) +.sass-cache/ +# Installshield output folder +[Ee]xpress/ +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html +# Click-Once directory +publish/ +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# If using the old MSBuild-Integrated Package Restore, uncomment this: +#!**/packages/repositories.config +# Windows Azure Build Output +csx/ +*.build.csdef +# Windows Store app package directory +AppPackages/ +# Others +sql/ +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +bower_components/ +# RIA/Silverlight projects +Generated_Code/ +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +# SQL Server files +*.mdf +*.ldf +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +# Microsoft Fakes +FakesAssemblies/ +*.suo +*.vcxproj.filters +*.npp +CMakeFiles/* +nbproject/* +*.cd +*.cd +a.out +cmake-build-debug/* diff --git a/third_party/date/.travis.yml b/third_party/date/.travis.yml new file mode 100644 index 0000000..ca8991a --- /dev/null +++ b/third_party/date/.travis.yml @@ -0,0 +1,147 @@ +language: cpp + +env: + global: + - CMAKE_EXTRA_CONF="-DCOMPILE_WITH_C_LOCALE=ON" + - CTEST_OUTPUT_ON_FAILURE=1 + +matrix: + include: + + - name: "Ubuntu 16.04 LTS (Xenial Xerus) GCC 7" + os: linux + dist: xenial + addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-7 + env: + - MATRIX_EVAL="CC=gcc-7 && CXX=g++-7" + + - name: "Ubuntu 16.04 LTS (Xenial Xerus) GCC 8" + os: linux + dist: xenial + addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-8 + env: + - MATRIX_EVAL="CC=gcc-8 && CXX=g++-8" + + - name: "Ubuntu 16.04 LTS (Xenial Xerus) GCC 9" + os: linux + dist: xenial + addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-9 + env: + - MATRIX_EVAL="CC=gcc-9 && CXX=g++-9" + + - name: "Ubuntu 18.04 LTS (Bionic Beaver) GCC 7" + os: linux + dist: bionic + addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-7 + env: + - MATRIX_EVAL="CC=gcc-7 && CXX=g++-7" + + - name: "Ubuntu 18.04 LTS (Bionic Beaver) GCC 8" + os: linux + dist: bionic + addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-8 + env: + - MATRIX_EVAL="CC=gcc-8 && CXX=g++-8" + + - name: "Ubuntu 18.04 LTS (Bionic Beaver) Clang 6" + os: linux + dist: bionic + addons: + apt: + sources: + - llvm-toolchain-bionic-6.0 + packages: + - clang-6.0 + env: + - MATRIX_EVAL="CC=clang-6.0 && CXX=clang++-6.0" + + - name: "Ubuntu 18.04 LTS (Bionic Beaver) Clang 7" + os: linux + dist: bionic + addons: + apt: + sources: + - llvm-toolchain-bionic-7 + packages: + - clang-7 + env: + - MATRIX_EVAL="CC=clang-7 && CXX=clang++-7" + + - name: "Ubuntu 18.04 LTS (Bionic Beaver) Clang 8" + os: linux + dist: bionic + addons: + apt: + sources: + - llvm-toolchain-bionic-8 + packages: + - clang-8 + env: + - MATRIX_EVAL="CC=clang-8 && CXX=clang++-8" + + - &macos + name: xcode10 + os: osx + osx_image: xcode10.2 + env: + - CMAKE_EXTRA_CONF="" + addons: + homebrew: + packages: + - bash + - ninja + + - <<: *macos + name: xcode9 + # xcode 9 only works if we tell it to use c++14 explicitly + env: + - CMAKE_EXTRA_CONF="-DCMAKE_CXX_STANDARD=14" + osx_image: xcode9.4 + + - <<: *macos + osx_image: xcode11 + name: xcode11 + +before_install: + - eval "${MATRIX_EVAL}" + - ci/install_cmake.sh 3.15.2 + - export OPENSSL_ROOT=$(brew --prefix openssl@1.1) + - if [ "$(uname)" = "Darwin" ] ; then export PATH="$HOME/cmake/CMake.app/Contents/bin:${PATH}"; fi + - if [ "$(uname)" = "Linux" ] ; then export PATH="$HOME/cmake/bin:${PATH}"; fi + +cache: + directories: + - $HOME/cmake + +script: + - mkdir -p build + - cd build + - eval cmake -DENABLE_DATE_TESTING=ON -DBUILD_SHARED_LIBS=ON ${CMAKE_EXTRA_CONF} .. + - cmake --build . --parallel + - cmake --build . --parallel --target testit + diff --git a/third_party/date/CMakeLists.txt b/third_party/date/CMakeLists.txt new file mode 100644 index 0000000..e3c6994 --- /dev/null +++ b/third_party/date/CMakeLists.txt @@ -0,0 +1,277 @@ +#[===================================================================[ + date library by Howard Hinnant + + CMake projects that wish to use this library should consider + something like the following : + + include( FetchContent ) + FetchContent_Declare( date_src + GIT_REPOSITORY https://github.com/HowardHinnant/date.git + GIT_TAG v3.0.0 # adjust tag/branch/commit as needed + ) + FetchContent_MakeAvailable(date_src) + ... + target_link_libraries (my_target PRIVATE date::date) + +#]===================================================================] + +cmake_minimum_required( VERSION 3.7 ) + +project( date VERSION 3.0.0 ) +set(ABI_VERSION 3) # used as SOVERSION, increment when ABI changes + +include( GNUInstallDirs ) + +get_directory_property( has_parent PARENT_DIRECTORY ) + +# Override by setting on CMake command line. +set( CMAKE_CXX_STANDARD 11 CACHE STRING "The C++ standard whose features are requested." ) + +option( USE_SYSTEM_TZ_DB "Use the operating system's timezone database" ON ) +option( MANUAL_TZ_DB "User will set TZ DB manually by invoking set_install in their code" OFF ) +option( USE_TZ_DB_IN_DOT "Save the timezone database in the current folder" OFF ) +option( BUILD_SHARED_LIBS "Build a shared version of library" OFF ) +option( ENABLE_DATE_TESTING "Enable unit tests" OFF ) +option( DISABLE_STRING_VIEW "Disable string view" ON ) +option( COMPILE_WITH_C_LOCALE "define ONLY_C_LOCALE=1" OFF ) +option( BUILD_TZ_LIB "build/install of TZ library" ON ) + +if( ENABLE_DATE_TESTING AND NOT BUILD_TZ_LIB ) + message(WARNING "Testing requested, bug BUILD_TZ_LIB not ON - forcing the latter") + set (BUILD_TZ_LIB ON CACHE BOOL "required for testing" FORCE) +endif( ) + +function( print_option OPT ) + if ( NOT DEFINED PRINT_OPTION_CURR_${OPT} OR ( NOT PRINT_OPTION_CURR_${OPT} STREQUAL ${OPT} ) ) + set( PRINT_OPTION_CURR_${OPT} ${${OPT}} CACHE BOOL "" ) + mark_as_advanced(PRINT_OPTION_CURR_${OPT}) + message( "# date: ${OPT} ${${OPT}}" ) + endif( ) +endfunction( ) + +print_option( USE_SYSTEM_TZ_DB ) +print_option( MANUAL_TZ_DB ) +print_option( USE_TZ_DB_IN_DOT ) +print_option( BUILD_SHARED_LIBS ) +print_option( ENABLE_DATE_TESTING ) +print_option( DISABLE_STRING_VIEW ) + +#[===================================================================[ + date (header only) library +#]===================================================================] +add_library( date INTERFACE ) +add_library( date::date ALIAS date ) +target_include_directories( date INTERFACE + $ + $ ) +# adding header sources just helps IDEs +target_sources( date INTERFACE + $$/date/date.h + # the rest of these are not currently part of the public interface of the library: + $ + $ + $ + $ +) +if (CMAKE_VERSION VERSION_GREATER_EQUAL 3.15) + # public headers will get installed: + set_target_properties( date PROPERTIES PUBLIC_HEADER include/date/date.h ) +endif () + +# These used to be set with generator expressions, +# +# ONLY_C_LOCALE=$,1,0> +# +# which expand in the output target file to, e.g. +# +# ONLY_C_LOCALE=$,1,0> +# +# This string is then (somtimes?) not correctly interpreted. +if ( COMPILE_WITH_C_LOCALE ) + # To workaround libstdc++ issue https://github.com/HowardHinnant/date/issues/388 + target_compile_definitions( date INTERFACE ONLY_C_LOCALE=1 ) +else() + target_compile_definitions( date INTERFACE ONLY_C_LOCALE=0 ) +endif() +if ( DISABLE_STRING_VIEW ) + target_compile_definitions( date INTERFACE HAS_STRING_VIEW=0 -DHAS_DEDUCTION_GUIDES=0 ) +endif() + +#[===================================================================[ + tz (compiled) library +#]===================================================================] +if( BUILD_TZ_LIB ) + add_library( date-tz ) + target_sources( date-tz + PUBLIC + $$/date/tz.h + PRIVATE + include/date/tz_private.h + src/tz.cpp ) + if ( IOS ) + target_sources( date-tz + PUBLIC + $$/date/ios.h + PRIVATE + src/ios.mm ) + endif() + add_library( date::date-tz ALIAS date-tz ) + target_link_libraries( date-tz PUBLIC date ) + target_include_directories( date-tz PUBLIC + $ + $ ) + + if ( USE_SYSTEM_TZ_DB OR MANUAL_TZ_DB ) + target_compile_definitions( date-tz PRIVATE AUTO_DOWNLOAD=0 HAS_REMOTE_API=0 ) + else() + target_compile_definitions( date-tz PRIVATE AUTO_DOWNLOAD=1 HAS_REMOTE_API=1 ) + endif() + + if ( USE_SYSTEM_TZ_DB AND NOT WIN32 AND NOT MANUAL_TZ_DB ) + target_compile_definitions( date-tz PRIVATE INSTALL=. PUBLIC USE_OS_TZDB=1 ) + else() + target_compile_definitions( date-tz PUBLIC USE_OS_TZDB=0 ) + endif() + + if ( WIN32 AND BUILD_SHARED_LIBS ) + target_compile_definitions( date-tz PUBLIC DATE_BUILD_DLL=1 ) + endif() + + set(TZ_HEADERS include/date/tz.h) + + if( IOS ) + list(APPEND TZ_HEADERS include/date/ios.h) + endif( ) + set_target_properties( date-tz PROPERTIES + POSITION_INDEPENDENT_CODE ON + PUBLIC_HEADER "${TZ_HEADERS}" + VERSION "${PROJECT_VERSION}" + SOVERSION "${ABI_VERSION}" ) + if( NOT MSVC ) + find_package( Threads ) + target_link_libraries( date-tz PUBLIC Threads::Threads ) + endif( ) + if( NOT USE_SYSTEM_TZ_DB AND NOT MANUAL_TZ_DB ) + find_package( CURL REQUIRED ) + target_include_directories( date-tz SYSTEM PRIVATE ${CURL_INCLUDE_DIRS} ) + target_link_libraries( date-tz PRIVATE ${CURL_LIBRARIES} ) + endif( ) +endif( ) + +#[===================================================================[ + installation +#]===================================================================] +set( version_config "${CMAKE_CURRENT_BINARY_DIR}/dateConfigVersion.cmake" ) + +include( CMakePackageConfigHelpers ) +write_basic_package_version_file( "${version_config}" + VERSION ${PROJECT_VERSION} + COMPATIBILITY SameMajorVersion ) + +install( TARGETS date + EXPORT dateConfig + PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/date ) +export( TARGETS date NAMESPACE date:: FILE dateTargets.cmake ) +if (CMAKE_VERSION VERSION_LESS 3.15) + install( + FILES include/date/date.h + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/date ) +endif () + +if( BUILD_TZ_LIB ) + install( TARGETS date-tz + EXPORT dateConfig + PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/date + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} ) # This is for Windows + export( TARGETS date-tz NAMESPACE date:: APPEND FILE dateTargets.cmake ) +endif( ) + +if( WIN32 AND NOT CYGWIN) + set( CONFIG_LOC CMake ) +else( ) + set( CONFIG_LOC "${CMAKE_INSTALL_LIBDIR}/cmake/date" ) +endif( ) +install( EXPORT dateConfig + FILE dateTargets.cmake + NAMESPACE date:: + DESTINATION ${CONFIG_LOC} ) +install ( + FILES cmake/dateConfig.cmake "${version_config}" + DESTINATION ${CONFIG_LOC}) + +#[===================================================================[ + testing +#]===================================================================] +if( ENABLE_DATE_TESTING ) + enable_testing( ) + + add_custom_target( testit COMMAND ${CMAKE_CTEST_COMMAND} ) + add_dependencies( testit date-tz ) + + function( add_pass_tests TEST_GLOB TEST_PREFIX ) + file( GLOB_RECURSE FILENAMES ${TEST_GLOB} ) + + foreach( TEST_FILE ${FILENAMES} ) + get_filename_component( TEST_NAME ${TEST_FILE} NAME_WE ) + get_filename_component( TEST_EXT ${TEST_FILE} EXT ) + if( NOT ${TEST_EXT} STREQUAL ".fail.cpp" ) + set( PREFIX "${TEST_PREFIX}_pass_${TEST_NAME}" ) + set( BIN_NAME ${PREFIX}_bin ) + set( TST_NAME ${PREFIX}_test ) + add_executable( ${BIN_NAME} EXCLUDE_FROM_ALL ${TEST_FILE} ) + add_test( ${TST_NAME} ${BIN_NAME} ) + target_link_libraries( ${BIN_NAME} date-tz ) + # HACK: because the test files don't use FQ includes: + target_include_directories( ${BIN_NAME} PRIVATE include/date ) + add_dependencies( testit ${BIN_NAME} ) + endif( ) + endforeach( ) + endfunction( ) + + function( add_fail_tests TEST_GLOB TEST_PREFIX ) + file( GLOB_RECURSE FILENAMES ${TEST_GLOB} ) + + foreach( TEST_FILE ${FILENAMES} ) + get_filename_component( TEST_NAME ${TEST_FILE} NAME_WE ) + get_filename_component( TEST_EXT ${TEST_FILE} EXT ) + + set( TEST_TYPE "_fail" ) + + set( PREFIX "${TEST_PREFIX}_fail_${TEST_NAME}" ) + set( BIN_NAME ${PREFIX}_bin ) + set( TST_NAME ${PREFIX}_test ) + + set( TEST_BIN_NAME ${CMAKE_BINARY_DIR}/${BIN_NAME} ) + add_custom_target( ${BIN_NAME} + COMMAND + ${PROJECT_SOURCE_DIR}/compile_fail.sh + ${TEST_BIN_NAME} + ${CMAKE_CXX_COMPILER} + -std=c++14 + -L${CMAKE_BINARY_DIR}/ + -ldate-tz + -I${PROJECT_SOURCE_DIR}/include + -I${PROJECT_SOURCE_DIR}/include/date + -o ${BIN_NAME} + ${TEST_FILE} + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + COMMENT ${TST_NAME} ) + add_test( ${TST_NAME} "${PROJECT_SOURCE_DIR}/test_fail.sh" ${CMAKE_BINARY_DIR}/${BIN_NAME} WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}/" ) + #set_tests_properties( ${TST_NAME} PROPERTIES WILL_FAIL TRUE) + add_dependencies( testit ${BIN_NAME} ) + endforeach( ) + endfunction( ) + + file( GLOB children RELATIVE "${PROJECT_SOURCE_DIR}/test" "${PROJECT_SOURCE_DIR}/test/*" ) + foreach( child ${children} ) + if( IS_DIRECTORY "${PROJECT_SOURCE_DIR}/test/${child}" ) + set( CUR_FOLDER "${PROJECT_SOURCE_DIR}/test/${child}" ) + add_pass_tests( "${CUR_FOLDER}/*.cpp" ${child} ) + if( NOT WIN32 ) + add_fail_tests( "${CUR_FOLDER}/*.fail.cpp" ${child} ) + endif( ) + endif( ) + endforeach( ) +endif( ) diff --git a/third_party/date/LICENSE.txt b/third_party/date/LICENSE.txt new file mode 100644 index 0000000..79ea069 --- /dev/null +++ b/third_party/date/LICENSE.txt @@ -0,0 +1,31 @@ +The source code in this project is released using the MIT License. There is no +global license for the project because each file is licensed individually with +different author names and/or dates. + +If you contribute to this project, please add your name to the license of each +file you modify. If you have already contributed to this project and forgot to +add your name to the license, please feel free to submit a new P/R to add your +name to the license in each file you modified. + +For convenience, here is a copy of the MIT license found in each file except +without author names or dates: + +The MIT License (MIT) + +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. diff --git a/third_party/date/README.md b/third_party/date/README.md new file mode 100644 index 0000000..7ef280f --- /dev/null +++ b/third_party/date/README.md @@ -0,0 +1,84 @@ +# Date + +[![Build Status](https://travis-ci.org/HowardHinnant/date.svg?branch=master)](https://travis-ci.org/HowardHinnant/date) +[![Join the chat at https://gitter.im/HowardHinnant/date](https://badges.gitter.im/HowardHinnant/date.svg)](https://gitter.im/HowardHinnant/date?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +--- + +**[Try it out on wandbox!](https://wandbox.org/permlink/oyXjibyF680HHoyS)** + +## Summary + +This is actually several separate C++11/C++14/C++17 libraries: + +1. `"date.h"` is a header-only library which builds upon ``. It adds some new `duration` types, and new `time_point` types. It also adds "field" types such as `year_month_day` which is a struct `{year, month, day}`. And it provides convenient means to convert between the "field" types and the `time_point` types. + + * Documentation: http://howardhinnant.github.io/date/date.html + * Video: https://www.youtube.com/watch?v=tzyGjOm8AKo + * Slides: http://schd.ws/hosted_files/cppcon2015/43/hinnant_dates.pdf + +1. `"tz.h"` / `"tz.cpp"` are a timezone library built on top of the `"date.h"` library. This timezone library is a complete parser of the IANA timezone database. It provides for an easy way to access all of the data in this database, using the types from `"date.h"` and ``. The IANA database also includes data on leap seconds, and this library provides utilities to compute with that information as well. + + * Documentation: http://howardhinnant.github.io/date/tz.html + * Video: https://www.youtube.com/watch?v=Vwd3pduVGKY + * Slides: http://schd.ws/hosted_files/cppcon2016/0f/Welcome%20To%20The%20Time%20Zone%20-%20Howard%20Hinnant%20-%20CppCon%202016.pdf + +1. `"iso_week.h"` is a header-only library built on top of the `"date.h"` library which implements the ISO week date calendar. + + * Documentation: http://howardhinnant.github.io/date/iso_week.html + +1. `"julian.h"` is a header-only library built on top of the `"date.h"` library which implements a proleptic Julian calendar which is fully interoperable with everything above. + + * Documentation: http://howardhinnant.github.io/date/julian.html + +1. `"islamic.h"` is a header-only library built on top of the `"date.h"` library which implements a proleptic Islamic calendar which is fully interoperable with everything above. + + * Documentation: http://howardhinnant.github.io/date/islamic.html + +## Standardization + +Slightly modified versions of `"date.h"` and `"tz.h"` were voted into the C++20 working draft at the Jacksonville FL meeting on 2018-03-17: + +* http://howardhinnant.github.io/date/d0355r7.html + +## Build & Test + +The recommended way to use any of these libraries besides `"tz.h"` is to just include it. These are header-only libraries (except `"tz.h"`). + +To use `"tz.h"`, there is a single source file (`src/tz.cpp`) that needs to be compiled. Here are the recommended directions: https://howardhinnant.github.io/date/tz.html#Installation. + +One can run tests by cd'ing into the `test` subdirectory and running `testit`. There are known failures on all platforms except for macOS. And even on macOS if C++11 is used. If any of these failures present problems for you, there exist workarounds. + +Additionally there is _unsupported_ support for [vcpkg](https://github.com/Microsoft/vcpkg) and [CMake](https://cmake.org/). I don't personally use or maintain these systems as for me they cause more problems than they solve (for this small project). If you would like to contribute to these build systems please feel free to file a PR. + +You can download and install Date using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager: + + git clone https://github.com/Microsoft/vcpkg.git + cd vcpkg + ./bootstrap-vcpkg.sh + ./vcpkg integrate install + vcpkg install date + +The Date port in vcpkg is updated by Microsoft team members and community contributors. If the version falls behind, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. + +You can optionally build using [CMake](https://cmake.org/). Here is a guide of how to build and test using the CMake Makefile generator. + +```bash +mkdir build +cd build +cmake -DENABLE_DATE_TESTING=ON -DBUILD_TZ_LIB=ON ../ +cmake --build . --target testit # Consider '-- -j4' for multithreading +``` +## Projects using this library + +* www.safe.com +* www.webtoolkit.eu/wt +* https://github.com/ViewTouch/viewtouch +* https://routinghub.com +* https://github.com/valhalla +* https://github.com/siodb/siodb +* https://github.com/KomodoPlatform/atomicDEX-Pro +* https://github.com/Kotlin/kotlinx-datetime +* https://github.com/royalbee/jewish_date + +If you would like your project (or product) on this list, just let me know. diff --git a/third_party/date/ci/install_cmake.sh b/third_party/date/ci/install_cmake.sh new file mode 100755 index 0000000..2c9fa10 --- /dev/null +++ b/third_party/date/ci/install_cmake.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +set -e + +IFS=. read cm_maj cm_min cm_rel <<<"$1" +: ${cm_rel:-0} +CMAKE_ROOT=${2:-"${HOME}/cmake"} + +function cmake_version () +{ + if [[ -d ${CMAKE_ROOT} ]] ; then + local perms=$(test $(uname) = "Linux" && echo "/111" || echo "+111") + local installed=$(find ${CMAKE_ROOT} -perm ${perms} -type f -name cmake) + if [[ "${installed}" != "" ]] ; then + echo "$(${installed} --version | head -1)" + fi + fi +} + +installed=$(cmake_version) +if [[ "${installed}" != "" && ${installed} =~ ${cm_maj}.${cm_min}.${cm_rel} ]] ; then + echo "cmake already installed: ${installed}" + exit +fi + +pkgname="cmake-${cm_maj}.${cm_min}.${cm_rel}-$(uname)-x86_64.tar.gz" +tmppkg="/tmp/cmake.tar.gz" +wget --quiet https://cmake.org/files/v${cm_maj}.${cm_min}/${pkgname} -O ${tmppkg} +mkdir -p ${CMAKE_ROOT} +cd ${CMAKE_ROOT} +tar --strip-components 1 -xf ${tmppkg} +rm -f ${tmppkg} +echo "installed: $(cmake_version)" + + diff --git a/third_party/date/cmake/dateConfig.cmake b/third_party/date/cmake/dateConfig.cmake new file mode 100644 index 0000000..2198ad1 --- /dev/null +++ b/third_party/date/cmake/dateConfig.cmake @@ -0,0 +1,11 @@ +include( CMakeFindDependencyMacro ) +include( "${CMAKE_CURRENT_LIST_DIR}/dateTargets.cmake" ) +if( NOT MSVC AND TARGET date::date-tz ) + find_dependency( Threads REQUIRED) + get_target_property( _tzill date::date-tz INTERFACE_LINK_LIBRARIES ) + if( _tzill AND "${_tzill}" MATCHES "libcurl" ) + find_dependency( CURL ) + endif( ) +endif( ) + + diff --git a/third_party/date/compile_fail.sh b/third_party/date/compile_fail.sh new file mode 100755 index 0000000..60cf6b9 --- /dev/null +++ b/third_party/date/compile_fail.sh @@ -0,0 +1,16 @@ +#!/bin/bash +export TEST_BIN_NAME=$1 +#echo "Building ${TEST_BIN_NAME}" +shift 1 +export BUILD_COMMAND=$@ +#echo "Build command: ${BUILD_COMMAND}" +eval ${BUILD_COMMAND} >/dev/null 2>/dev/null + +if [ $? -eq 0 ]; then + echo -ne "#!/bin/bash\nexit 1;" > ${TEST_BIN_NAME} +else + echo -ne "#!/bin/bash\nexit 0;" > ${TEST_BIN_NAME} +fi +chmod u+x ${TEST_BIN_NAME} +exit 0; + diff --git a/third_party/date/include/date/chrono_io.h b/third_party/date/include/date/chrono_io.h new file mode 100644 index 0000000..21be404 --- /dev/null +++ b/third_party/date/include/date/chrono_io.h @@ -0,0 +1,34 @@ +#ifndef CHRONO_IO_H +#define CHRONO_IO_H + +// The MIT License (MIT) +// +// Copyright (c) 2016, 2017 Howard Hinnant +// +// 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. +// +// Our apologies. When the previous paragraph was written, lowercase had not yet +// been invented (that would involve another several millennia of evolution). +// We did not mean to shout. + +// This functionality has moved to "date.h" + +#include "date.h" + +#endif // CHRONO_IO_H diff --git a/third_party/date/include/date/date.h b/third_party/date/include/date/date.h new file mode 100644 index 0000000..7b6b4e4 --- /dev/null +++ b/third_party/date/include/date/date.h @@ -0,0 +1,8200 @@ +#ifndef DATE_H +#define DATE_H + +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016, 2017 Howard Hinnant +// Copyright (c) 2016 Adrian Colomitchi +// Copyright (c) 2017 Florian Dang +// Copyright (c) 2017 Paul Thompson +// Copyright (c) 2018, 2019 Tomasz KamiÅ„ski +// Copyright (c) 2019 Jiangang Zhuang +// +// 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. +// +// Our apologies. When the previous paragraph was written, lowercase had not yet +// been invented (that would involve another several millennia of evolution). +// We did not mean to shout. + +#ifndef HAS_STRING_VIEW +# if __cplusplus >= 201703 || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) +# define HAS_STRING_VIEW 1 +# else +# define HAS_STRING_VIEW 0 +# endif +#endif // HAS_STRING_VIEW + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if HAS_STRING_VIEW +# include +#endif +#include +#include + +#ifdef __GNUC__ +# pragma GCC diagnostic push +# if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 7) +# pragma GCC diagnostic ignored "-Wpedantic" +# endif +# if __GNUC__ < 5 + // GCC 4.9 Bug 61489 Wrong warning with -Wmissing-field-initializers +# pragma GCC diagnostic ignored "-Wmissing-field-initializers" +# endif +#endif + +#ifdef _MSC_VER +# pragma warning(push) +// warning C4127: conditional expression is constant +# pragma warning(disable : 4127) +#endif + +namespace date +{ + +//---------------+ +// Configuration | +//---------------+ + +#ifndef ONLY_C_LOCALE +# define ONLY_C_LOCALE 0 +#endif + +#if defined(_MSC_VER) && (!defined(__clang__) || (_MSC_VER < 1910)) +// MSVC +# ifndef _SILENCE_CXX17_UNCAUGHT_EXCEPTION_DEPRECATION_WARNING +# define _SILENCE_CXX17_UNCAUGHT_EXCEPTION_DEPRECATION_WARNING +# endif +# if _MSC_VER < 1910 +// before VS2017 +# define CONSTDATA const +# define CONSTCD11 +# define CONSTCD14 +# define NOEXCEPT _NOEXCEPT +# else +// VS2017 and later +# define CONSTDATA constexpr const +# define CONSTCD11 constexpr +# define CONSTCD14 constexpr +# define NOEXCEPT noexcept +# endif + +#elif defined(__SUNPRO_CC) && __SUNPRO_CC <= 0x5150 +// Oracle Developer Studio 12.6 and earlier +# define CONSTDATA constexpr const +# define CONSTCD11 constexpr +# define CONSTCD14 +# define NOEXCEPT noexcept + +#elif __cplusplus >= 201402 +// C++14 +# define CONSTDATA constexpr const +# define CONSTCD11 constexpr +# define CONSTCD14 constexpr +# define NOEXCEPT noexcept +#else +// C++11 +# define CONSTDATA constexpr const +# define CONSTCD11 constexpr +# define CONSTCD14 +# define NOEXCEPT noexcept +#endif + +#ifndef HAS_UNCAUGHT_EXCEPTIONS +# if __cplusplus >= 201703 || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) +# define HAS_UNCAUGHT_EXCEPTIONS 1 +# else +# define HAS_UNCAUGHT_EXCEPTIONS 0 +# endif +#endif // HAS_UNCAUGHT_EXCEPTIONS + +#ifndef HAS_VOID_T +# if __cplusplus >= 201703 || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) +# define HAS_VOID_T 1 +# else +# define HAS_VOID_T 0 +# endif +#endif // HAS_VOID_T + +// Protect from Oracle sun macro +#ifdef sun +# undef sun +#endif + +// Work around for a NVCC compiler bug which causes it to fail +// to compile std::ratio_{multiply,divide} when used directly +// in the std::chrono::duration template instantiations below +namespace detail { +template +using ratio_multiply = decltype(std::ratio_multiply{}); + +template +using ratio_divide = decltype(std::ratio_divide{}); +} // namespace detail + +//-----------+ +// Interface | +//-----------+ + +// durations + +using days = std::chrono::duration + , std::chrono::hours::period>>; + +using weeks = std::chrono::duration + , days::period>>; + +using years = std::chrono::duration + , days::period>>; + +using months = std::chrono::duration + >>; + +// time_point + +template + using sys_time = std::chrono::time_point; + +using sys_days = sys_time; +using sys_seconds = sys_time; + +struct local_t {}; + +template + using local_time = std::chrono::time_point; + +using local_seconds = local_time; +using local_days = local_time; + +// types + +struct last_spec +{ + explicit last_spec() = default; +}; + +class day; +class month; +class year; + +class weekday; +class weekday_indexed; +class weekday_last; + +class month_day; +class month_day_last; +class month_weekday; +class month_weekday_last; + +class year_month; + +class year_month_day; +class year_month_day_last; +class year_month_weekday; +class year_month_weekday_last; + +// date composition operators + +CONSTCD11 year_month operator/(const year& y, const month& m) NOEXCEPT; +CONSTCD11 year_month operator/(const year& y, int m) NOEXCEPT; + +CONSTCD11 month_day operator/(const day& d, const month& m) NOEXCEPT; +CONSTCD11 month_day operator/(const day& d, int m) NOEXCEPT; +CONSTCD11 month_day operator/(const month& m, const day& d) NOEXCEPT; +CONSTCD11 month_day operator/(const month& m, int d) NOEXCEPT; +CONSTCD11 month_day operator/(int m, const day& d) NOEXCEPT; + +CONSTCD11 month_day_last operator/(const month& m, last_spec) NOEXCEPT; +CONSTCD11 month_day_last operator/(int m, last_spec) NOEXCEPT; +CONSTCD11 month_day_last operator/(last_spec, const month& m) NOEXCEPT; +CONSTCD11 month_day_last operator/(last_spec, int m) NOEXCEPT; + +CONSTCD11 month_weekday operator/(const month& m, const weekday_indexed& wdi) NOEXCEPT; +CONSTCD11 month_weekday operator/(int m, const weekday_indexed& wdi) NOEXCEPT; +CONSTCD11 month_weekday operator/(const weekday_indexed& wdi, const month& m) NOEXCEPT; +CONSTCD11 month_weekday operator/(const weekday_indexed& wdi, int m) NOEXCEPT; + +CONSTCD11 month_weekday_last operator/(const month& m, const weekday_last& wdl) NOEXCEPT; +CONSTCD11 month_weekday_last operator/(int m, const weekday_last& wdl) NOEXCEPT; +CONSTCD11 month_weekday_last operator/(const weekday_last& wdl, const month& m) NOEXCEPT; +CONSTCD11 month_weekday_last operator/(const weekday_last& wdl, int m) NOEXCEPT; + +CONSTCD11 year_month_day operator/(const year_month& ym, const day& d) NOEXCEPT; +CONSTCD11 year_month_day operator/(const year_month& ym, int d) NOEXCEPT; +CONSTCD11 year_month_day operator/(const year& y, const month_day& md) NOEXCEPT; +CONSTCD11 year_month_day operator/(int y, const month_day& md) NOEXCEPT; +CONSTCD11 year_month_day operator/(const month_day& md, const year& y) NOEXCEPT; +CONSTCD11 year_month_day operator/(const month_day& md, int y) NOEXCEPT; + +CONSTCD11 + year_month_day_last operator/(const year_month& ym, last_spec) NOEXCEPT; +CONSTCD11 + year_month_day_last operator/(const year& y, const month_day_last& mdl) NOEXCEPT; +CONSTCD11 + year_month_day_last operator/(int y, const month_day_last& mdl) NOEXCEPT; +CONSTCD11 + year_month_day_last operator/(const month_day_last& mdl, const year& y) NOEXCEPT; +CONSTCD11 + year_month_day_last operator/(const month_day_last& mdl, int y) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(const year_month& ym, const weekday_indexed& wdi) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(const year& y, const month_weekday& mwd) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(int y, const month_weekday& mwd) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(const month_weekday& mwd, const year& y) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(const month_weekday& mwd, int y) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(const year_month& ym, const weekday_last& wdl) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(const year& y, const month_weekday_last& mwdl) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(int y, const month_weekday_last& mwdl) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(const month_weekday_last& mwdl, const year& y) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(const month_weekday_last& mwdl, int y) NOEXCEPT; + +// Detailed interface + +// day + +class day +{ + unsigned char d_; + +public: + day() = default; + explicit CONSTCD11 day(unsigned d) NOEXCEPT; + + CONSTCD14 day& operator++() NOEXCEPT; + CONSTCD14 day operator++(int) NOEXCEPT; + CONSTCD14 day& operator--() NOEXCEPT; + CONSTCD14 day operator--(int) NOEXCEPT; + + CONSTCD14 day& operator+=(const days& d) NOEXCEPT; + CONSTCD14 day& operator-=(const days& d) NOEXCEPT; + + CONSTCD11 explicit operator unsigned() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator!=(const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator< (const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator> (const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator<=(const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator>=(const day& x, const day& y) NOEXCEPT; + +CONSTCD11 day operator+(const day& x, const days& y) NOEXCEPT; +CONSTCD11 day operator+(const days& x, const day& y) NOEXCEPT; +CONSTCD11 day operator-(const day& x, const days& y) NOEXCEPT; +CONSTCD11 days operator-(const day& x, const day& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const day& d); + +// month + +class month +{ + unsigned char m_; + +public: + month() = default; + explicit CONSTCD11 month(unsigned m) NOEXCEPT; + + CONSTCD14 month& operator++() NOEXCEPT; + CONSTCD14 month operator++(int) NOEXCEPT; + CONSTCD14 month& operator--() NOEXCEPT; + CONSTCD14 month operator--(int) NOEXCEPT; + + CONSTCD14 month& operator+=(const months& m) NOEXCEPT; + CONSTCD14 month& operator-=(const months& m) NOEXCEPT; + + CONSTCD11 explicit operator unsigned() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator!=(const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator< (const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator> (const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator<=(const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator>=(const month& x, const month& y) NOEXCEPT; + +CONSTCD14 month operator+(const month& x, const months& y) NOEXCEPT; +CONSTCD14 month operator+(const months& x, const month& y) NOEXCEPT; +CONSTCD14 month operator-(const month& x, const months& y) NOEXCEPT; +CONSTCD14 months operator-(const month& x, const month& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month& m); + +// year + +class year +{ + short y_; + +public: + year() = default; + explicit CONSTCD11 year(int y) NOEXCEPT; + + CONSTCD14 year& operator++() NOEXCEPT; + CONSTCD14 year operator++(int) NOEXCEPT; + CONSTCD14 year& operator--() NOEXCEPT; + CONSTCD14 year operator--(int) NOEXCEPT; + + CONSTCD14 year& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 year operator-() const NOEXCEPT; + CONSTCD11 year operator+() const NOEXCEPT; + + CONSTCD11 bool is_leap() const NOEXCEPT; + + CONSTCD11 explicit operator int() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; + + static CONSTCD11 year min() NOEXCEPT { return year{-32767}; } + static CONSTCD11 year max() NOEXCEPT { return year{32767}; } +}; + +CONSTCD11 bool operator==(const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator< (const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator> (const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year& x, const year& y) NOEXCEPT; + +CONSTCD11 year operator+(const year& x, const years& y) NOEXCEPT; +CONSTCD11 year operator+(const years& x, const year& y) NOEXCEPT; +CONSTCD11 year operator-(const year& x, const years& y) NOEXCEPT; +CONSTCD11 years operator-(const year& x, const year& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year& y); + +// weekday + +class weekday +{ + unsigned char wd_; +public: + weekday() = default; + explicit CONSTCD11 weekday(unsigned wd) NOEXCEPT; + CONSTCD14 weekday(const sys_days& dp) NOEXCEPT; + CONSTCD14 explicit weekday(const local_days& dp) NOEXCEPT; + + CONSTCD14 weekday& operator++() NOEXCEPT; + CONSTCD14 weekday operator++(int) NOEXCEPT; + CONSTCD14 weekday& operator--() NOEXCEPT; + CONSTCD14 weekday operator--(int) NOEXCEPT; + + CONSTCD14 weekday& operator+=(const days& d) NOEXCEPT; + CONSTCD14 weekday& operator-=(const days& d) NOEXCEPT; + + CONSTCD11 bool ok() const NOEXCEPT; + + CONSTCD11 unsigned c_encoding() const NOEXCEPT; + CONSTCD11 unsigned iso_encoding() const NOEXCEPT; + + CONSTCD11 weekday_indexed operator[](unsigned index) const NOEXCEPT; + CONSTCD11 weekday_last operator[](last_spec) const NOEXCEPT; + +private: + static CONSTCD14 unsigned char weekday_from_days(int z) NOEXCEPT; + + friend CONSTCD11 bool operator==(const weekday& x, const weekday& y) NOEXCEPT; + friend CONSTCD14 days operator-(const weekday& x, const weekday& y) NOEXCEPT; + friend CONSTCD14 weekday operator+(const weekday& x, const days& y) NOEXCEPT; + template + friend std::basic_ostream& + operator<<(std::basic_ostream& os, const weekday& wd); + friend class weekday_indexed; +}; + +CONSTCD11 bool operator==(const weekday& x, const weekday& y) NOEXCEPT; +CONSTCD11 bool operator!=(const weekday& x, const weekday& y) NOEXCEPT; + +CONSTCD14 weekday operator+(const weekday& x, const days& y) NOEXCEPT; +CONSTCD14 weekday operator+(const days& x, const weekday& y) NOEXCEPT; +CONSTCD14 weekday operator-(const weekday& x, const days& y) NOEXCEPT; +CONSTCD14 days operator-(const weekday& x, const weekday& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday& wd); + +// weekday_indexed + +class weekday_indexed +{ + unsigned char wd_ : 4; + unsigned char index_ : 4; + +public: + weekday_indexed() = default; + CONSTCD11 weekday_indexed(const date::weekday& wd, unsigned index) NOEXCEPT; + + CONSTCD11 date::weekday weekday() const NOEXCEPT; + CONSTCD11 unsigned index() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT; +CONSTCD11 bool operator!=(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday_indexed& wdi); + +// weekday_last + +class weekday_last +{ + date::weekday wd_; + +public: + explicit CONSTCD11 weekday_last(const date::weekday& wd) NOEXCEPT; + + CONSTCD11 date::weekday weekday() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const weekday_last& x, const weekday_last& y) NOEXCEPT; +CONSTCD11 bool operator!=(const weekday_last& x, const weekday_last& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday_last& wdl); + +namespace detail +{ + +struct unspecified_month_disambiguator {}; + +} // namespace detail + +// year_month + +class year_month +{ + date::year y_; + date::month m_; + +public: + year_month() = default; + CONSTCD11 year_month(const date::year& y, const date::month& m) NOEXCEPT; + + CONSTCD11 date::year year() const NOEXCEPT; + CONSTCD11 date::month month() const NOEXCEPT; + + template + CONSTCD14 year_month& operator+=(const months& dm) NOEXCEPT; + template + CONSTCD14 year_month& operator-=(const months& dm) NOEXCEPT; + CONSTCD14 year_month& operator+=(const years& dy) NOEXCEPT; + CONSTCD14 year_month& operator-=(const years& dy) NOEXCEPT; + + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator< (const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator> (const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year_month& x, const year_month& y) NOEXCEPT; + +template +CONSTCD14 year_month operator+(const year_month& ym, const months& dm) NOEXCEPT; +template +CONSTCD14 year_month operator+(const months& dm, const year_month& ym) NOEXCEPT; +template +CONSTCD14 year_month operator-(const year_month& ym, const months& dm) NOEXCEPT; + +CONSTCD11 months operator-(const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 year_month operator+(const year_month& ym, const years& dy) NOEXCEPT; +CONSTCD11 year_month operator+(const years& dy, const year_month& ym) NOEXCEPT; +CONSTCD11 year_month operator-(const year_month& ym, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month& ym); + +// month_day + +class month_day +{ + date::month m_; + date::day d_; + +public: + month_day() = default; + CONSTCD11 month_day(const date::month& m, const date::day& d) NOEXCEPT; + + CONSTCD11 date::month month() const NOEXCEPT; + CONSTCD11 date::day day() const NOEXCEPT; + + CONSTCD14 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator!=(const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator< (const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator> (const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator<=(const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator>=(const month_day& x, const month_day& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_day& md); + +// month_day_last + +class month_day_last +{ + date::month m_; + +public: + CONSTCD11 explicit month_day_last(const date::month& m) NOEXCEPT; + + CONSTCD11 date::month month() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator!=(const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator< (const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator> (const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator<=(const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator>=(const month_day_last& x, const month_day_last& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_day_last& mdl); + +// month_weekday + +class month_weekday +{ + date::month m_; + date::weekday_indexed wdi_; +public: + CONSTCD11 month_weekday(const date::month& m, + const date::weekday_indexed& wdi) NOEXCEPT; + + CONSTCD11 date::month month() const NOEXCEPT; + CONSTCD11 date::weekday_indexed weekday_indexed() const NOEXCEPT; + + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const month_weekday& x, const month_weekday& y) NOEXCEPT; +CONSTCD11 bool operator!=(const month_weekday& x, const month_weekday& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_weekday& mwd); + +// month_weekday_last + +class month_weekday_last +{ + date::month m_; + date::weekday_last wdl_; + +public: + CONSTCD11 month_weekday_last(const date::month& m, + const date::weekday_last& wd) NOEXCEPT; + + CONSTCD11 date::month month() const NOEXCEPT; + CONSTCD11 date::weekday_last weekday_last() const NOEXCEPT; + + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 + bool operator==(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT; +CONSTCD11 + bool operator!=(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_weekday_last& mwdl); + +// class year_month_day + +class year_month_day +{ + date::year y_; + date::month m_; + date::day d_; + +public: + year_month_day() = default; + CONSTCD11 year_month_day(const date::year& y, const date::month& m, + const date::day& d) NOEXCEPT; + CONSTCD14 year_month_day(const year_month_day_last& ymdl) NOEXCEPT; + + CONSTCD14 year_month_day(sys_days dp) NOEXCEPT; + CONSTCD14 explicit year_month_day(local_days dp) NOEXCEPT; + + template + CONSTCD14 year_month_day& operator+=(const months& m) NOEXCEPT; + template + CONSTCD14 year_month_day& operator-=(const months& m) NOEXCEPT; + CONSTCD14 year_month_day& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year_month_day& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 date::year year() const NOEXCEPT; + CONSTCD11 date::month month() const NOEXCEPT; + CONSTCD11 date::day day() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD14 bool ok() const NOEXCEPT; + +private: + static CONSTCD14 year_month_day from_days(days dp) NOEXCEPT; + CONSTCD14 days to_days() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator< (const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator> (const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year_month_day& x, const year_month_day& y) NOEXCEPT; + +template +CONSTCD14 year_month_day operator+(const year_month_day& ymd, const months& dm) NOEXCEPT; +template +CONSTCD14 year_month_day operator+(const months& dm, const year_month_day& ymd) NOEXCEPT; +template +CONSTCD14 year_month_day operator-(const year_month_day& ymd, const months& dm) NOEXCEPT; +CONSTCD11 year_month_day operator+(const year_month_day& ymd, const years& dy) NOEXCEPT; +CONSTCD11 year_month_day operator+(const years& dy, const year_month_day& ymd) NOEXCEPT; +CONSTCD11 year_month_day operator-(const year_month_day& ymd, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_day& ymd); + +// year_month_day_last + +class year_month_day_last +{ + date::year y_; + date::month_day_last mdl_; + +public: + CONSTCD11 year_month_day_last(const date::year& y, + const date::month_day_last& mdl) NOEXCEPT; + + template + CONSTCD14 year_month_day_last& operator+=(const months& m) NOEXCEPT; + template + CONSTCD14 year_month_day_last& operator-=(const months& m) NOEXCEPT; + CONSTCD14 year_month_day_last& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year_month_day_last& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 date::year year() const NOEXCEPT; + CONSTCD11 date::month month() const NOEXCEPT; + CONSTCD11 date::month_day_last month_day_last() const NOEXCEPT; + CONSTCD14 date::day day() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 + bool operator==(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator!=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator< (const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator> (const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator<=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator>=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; + +template +CONSTCD14 +year_month_day_last +operator+(const year_month_day_last& ymdl, const months& dm) NOEXCEPT; + +template +CONSTCD14 +year_month_day_last +operator+(const months& dm, const year_month_day_last& ymdl) NOEXCEPT; + +CONSTCD11 +year_month_day_last +operator+(const year_month_day_last& ymdl, const years& dy) NOEXCEPT; + +CONSTCD11 +year_month_day_last +operator+(const years& dy, const year_month_day_last& ymdl) NOEXCEPT; + +template +CONSTCD14 +year_month_day_last +operator-(const year_month_day_last& ymdl, const months& dm) NOEXCEPT; + +CONSTCD11 +year_month_day_last +operator-(const year_month_day_last& ymdl, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_day_last& ymdl); + +// year_month_weekday + +class year_month_weekday +{ + date::year y_; + date::month m_; + date::weekday_indexed wdi_; + +public: + year_month_weekday() = default; + CONSTCD11 year_month_weekday(const date::year& y, const date::month& m, + const date::weekday_indexed& wdi) NOEXCEPT; + CONSTCD14 year_month_weekday(const sys_days& dp) NOEXCEPT; + CONSTCD14 explicit year_month_weekday(const local_days& dp) NOEXCEPT; + + template + CONSTCD14 year_month_weekday& operator+=(const months& m) NOEXCEPT; + template + CONSTCD14 year_month_weekday& operator-=(const months& m) NOEXCEPT; + CONSTCD14 year_month_weekday& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year_month_weekday& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 date::year year() const NOEXCEPT; + CONSTCD11 date::month month() const NOEXCEPT; + CONSTCD11 date::weekday weekday() const NOEXCEPT; + CONSTCD11 unsigned index() const NOEXCEPT; + CONSTCD11 date::weekday_indexed weekday_indexed() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD14 bool ok() const NOEXCEPT; + +private: + static CONSTCD14 year_month_weekday from_days(days dp) NOEXCEPT; + CONSTCD14 days to_days() const NOEXCEPT; +}; + +CONSTCD11 + bool operator==(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT; +CONSTCD11 + bool operator!=(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT; + +template +CONSTCD14 +year_month_weekday +operator+(const year_month_weekday& ymwd, const months& dm) NOEXCEPT; + +template +CONSTCD14 +year_month_weekday +operator+(const months& dm, const year_month_weekday& ymwd) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator+(const year_month_weekday& ymwd, const years& dy) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator+(const years& dy, const year_month_weekday& ymwd) NOEXCEPT; + +template +CONSTCD14 +year_month_weekday +operator-(const year_month_weekday& ymwd, const months& dm) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator-(const year_month_weekday& ymwd, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_weekday& ymwdi); + +// year_month_weekday_last + +class year_month_weekday_last +{ + date::year y_; + date::month m_; + date::weekday_last wdl_; + +public: + CONSTCD11 year_month_weekday_last(const date::year& y, const date::month& m, + const date::weekday_last& wdl) NOEXCEPT; + + template + CONSTCD14 year_month_weekday_last& operator+=(const months& m) NOEXCEPT; + template + CONSTCD14 year_month_weekday_last& operator-=(const months& m) NOEXCEPT; + CONSTCD14 year_month_weekday_last& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year_month_weekday_last& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 date::year year() const NOEXCEPT; + CONSTCD11 date::month month() const NOEXCEPT; + CONSTCD11 date::weekday weekday() const NOEXCEPT; + CONSTCD11 date::weekday_last weekday_last() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; + +private: + CONSTCD14 days to_days() const NOEXCEPT; +}; + +CONSTCD11 +bool +operator==(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT; + +CONSTCD11 +bool +operator!=(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT; + +template +CONSTCD14 +year_month_weekday_last +operator+(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT; + +template +CONSTCD14 +year_month_weekday_last +operator+(const months& dm, const year_month_weekday_last& ymwdl) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator+(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator+(const years& dy, const year_month_weekday_last& ymwdl) NOEXCEPT; + +template +CONSTCD14 +year_month_weekday_last +operator-(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator-(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_weekday_last& ymwdl); + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) +inline namespace literals +{ + +CONSTCD11 date::day operator "" _d(unsigned long long d) NOEXCEPT; +CONSTCD11 date::year operator "" _y(unsigned long long y) NOEXCEPT; + +} // inline namespace literals +#endif // !defined(_MSC_VER) || (_MSC_VER >= 1900) + +// CONSTDATA date::month January{1}; +// CONSTDATA date::month February{2}; +// CONSTDATA date::month March{3}; +// CONSTDATA date::month April{4}; +// CONSTDATA date::month May{5}; +// CONSTDATA date::month June{6}; +// CONSTDATA date::month July{7}; +// CONSTDATA date::month August{8}; +// CONSTDATA date::month September{9}; +// CONSTDATA date::month October{10}; +// CONSTDATA date::month November{11}; +// CONSTDATA date::month December{12}; +// +// CONSTDATA date::weekday Sunday{0u}; +// CONSTDATA date::weekday Monday{1u}; +// CONSTDATA date::weekday Tuesday{2u}; +// CONSTDATA date::weekday Wednesday{3u}; +// CONSTDATA date::weekday Thursday{4u}; +// CONSTDATA date::weekday Friday{5u}; +// CONSTDATA date::weekday Saturday{6u}; + +#if HAS_VOID_T + +template > +struct is_clock + : std::false_type +{}; + +template +struct is_clock> + : std::true_type +{}; + +template inline constexpr bool is_clock_v = is_clock::value; + +#endif // HAS_VOID_T + +//----------------+ +// Implementation | +//----------------+ + +// utilities +namespace detail { + +template> +class save_istream +{ +protected: + std::basic_ios& is_; + CharT fill_; + std::ios::fmtflags flags_; + std::streamsize precision_; + std::streamsize width_; + std::basic_ostream* tie_; + std::locale loc_; + +public: + ~save_istream() + { + is_.fill(fill_); + is_.flags(flags_); + is_.precision(precision_); + is_.width(width_); + is_.imbue(loc_); + is_.tie(tie_); + } + + save_istream(const save_istream&) = delete; + save_istream& operator=(const save_istream&) = delete; + + explicit save_istream(std::basic_ios& is) + : is_(is) + , fill_(is.fill()) + , flags_(is.flags()) + , precision_(is.precision()) + , width_(is.width(0)) + , tie_(is.tie(nullptr)) + , loc_(is.getloc()) + { + if (tie_ != nullptr) + tie_->flush(); + } +}; + +template> +class save_ostream + : private save_istream +{ +public: + ~save_ostream() + { + if ((this->flags_ & std::ios::unitbuf) && +#if HAS_UNCAUGHT_EXCEPTIONS + std::uncaught_exceptions() == 0 && +#else + !std::uncaught_exception() && +#endif + this->is_.good()) + this->is_.rdbuf()->pubsync(); + } + + save_ostream(const save_ostream&) = delete; + save_ostream& operator=(const save_ostream&) = delete; + + explicit save_ostream(std::basic_ios& os) + : save_istream(os) + { + } +}; + +template +struct choose_trunc_type +{ + static const int digits = std::numeric_limits::digits; + using type = typename std::conditional + < + digits < 32, + std::int32_t, + typename std::conditional + < + digits < 64, + std::int64_t, +#ifdef __SIZEOF_INT128__ + __int128 +#else + std::int64_t +#endif + >::type + >::type; +}; + +template +CONSTCD11 +inline +typename std::enable_if +< + !std::chrono::treat_as_floating_point::value, + T +>::type +trunc(T t) NOEXCEPT +{ + return t; +} + +template +CONSTCD14 +inline +typename std::enable_if +< + std::chrono::treat_as_floating_point::value, + T +>::type +trunc(T t) NOEXCEPT +{ + using std::numeric_limits; + using I = typename choose_trunc_type::type; + CONSTDATA auto digits = numeric_limits::digits; + static_assert(digits < numeric_limits::digits, ""); + CONSTDATA auto max = I{1} << (digits-1); + CONSTDATA auto min = -max; + const auto negative = t < T{0}; + if (min <= t && t <= max && t != 0 && t == t) + { + t = static_cast(static_cast(t)); + if (t == 0 && negative) + t = -t; + } + return t; +} + +template +struct static_gcd +{ + static const std::intmax_t value = static_gcd::value; +}; + +template +struct static_gcd +{ + static const std::intmax_t value = Xp; +}; + +template <> +struct static_gcd<0, 0> +{ + static const std::intmax_t value = 1; +}; + +template +struct no_overflow +{ +private: + static const std::intmax_t gcd_n1_n2 = static_gcd::value; + static const std::intmax_t gcd_d1_d2 = static_gcd::value; + static const std::intmax_t n1 = R1::num / gcd_n1_n2; + static const std::intmax_t d1 = R1::den / gcd_d1_d2; + static const std::intmax_t n2 = R2::num / gcd_n1_n2; + static const std::intmax_t d2 = R2::den / gcd_d1_d2; +#ifdef __cpp_constexpr + static const std::intmax_t max = std::numeric_limits::max(); +#else + static const std::intmax_t max = LLONG_MAX; +#endif + + template + struct mul // overflow == false + { + static const std::intmax_t value = Xp * Yp; + }; + + template + struct mul + { + static const std::intmax_t value = 1; + }; + +public: + static const bool value = (n1 <= max / d2) && (n2 <= max / d1); + typedef std::ratio::value, + mul::value> type; +}; + +} // detail + +// trunc towards zero +template +CONSTCD11 +inline +typename std::enable_if +< + detail::no_overflow::value, + To +>::type +trunc(const std::chrono::duration& d) +{ + return To{detail::trunc(std::chrono::duration_cast(d).count())}; +} + +template +CONSTCD11 +inline +typename std::enable_if +< + !detail::no_overflow::value, + To +>::type +trunc(const std::chrono::duration& d) +{ + using std::chrono::duration_cast; + using std::chrono::duration; + using rep = typename std::common_type::type; + return To{detail::trunc(duration_cast(duration_cast>(d)).count())}; +} + +#ifndef HAS_CHRONO_ROUNDING +# if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 190023918 || (_MSC_FULL_VER >= 190000000 && defined (__clang__))) +# define HAS_CHRONO_ROUNDING 1 +# elif defined(__cpp_lib_chrono) && __cplusplus > 201402 && __cpp_lib_chrono >= 201510 +# define HAS_CHRONO_ROUNDING 1 +# elif defined(_LIBCPP_VERSION) && __cplusplus > 201402 && _LIBCPP_VERSION >= 3800 +# define HAS_CHRONO_ROUNDING 1 +# else +# define HAS_CHRONO_ROUNDING 0 +# endif +#endif // HAS_CHRONO_ROUNDING + +#if HAS_CHRONO_ROUNDING == 0 + +// round down +template +CONSTCD14 +inline +typename std::enable_if +< + detail::no_overflow::value, + To +>::type +floor(const std::chrono::duration& d) +{ + auto t = trunc(d); + if (t > d) + return t - To{1}; + return t; +} + +template +CONSTCD14 +inline +typename std::enable_if +< + !detail::no_overflow::value, + To +>::type +floor(const std::chrono::duration& d) +{ + using rep = typename std::common_type::type; + return floor(floor>(d)); +} + +// round to nearest, to even on tie +template +CONSTCD14 +inline +To +round(const std::chrono::duration& d) +{ + auto t0 = floor(d); + auto t1 = t0 + To{1}; + if (t1 == To{0} && t0 < To{0}) + t1 = -t1; + auto diff0 = d - t0; + auto diff1 = t1 - d; + if (diff0 == diff1) + { + if (t0 - trunc(t0/2)*2 == To{0}) + return t0; + return t1; + } + if (diff0 < diff1) + return t0; + return t1; +} + +// round up +template +CONSTCD14 +inline +To +ceil(const std::chrono::duration& d) +{ + auto t = trunc(d); + if (t < d) + return t + To{1}; + return t; +} + +template ::is_signed + >::type> +CONSTCD11 +std::chrono::duration +abs(std::chrono::duration d) +{ + return d >= d.zero() ? d : -d; +} + +// round down +template +CONSTCD11 +inline +std::chrono::time_point +floor(const std::chrono::time_point& tp) +{ + using std::chrono::time_point; + return time_point{date::floor(tp.time_since_epoch())}; +} + +// round to nearest, to even on tie +template +CONSTCD11 +inline +std::chrono::time_point +round(const std::chrono::time_point& tp) +{ + using std::chrono::time_point; + return time_point{round(tp.time_since_epoch())}; +} + +// round up +template +CONSTCD11 +inline +std::chrono::time_point +ceil(const std::chrono::time_point& tp) +{ + using std::chrono::time_point; + return time_point{ceil(tp.time_since_epoch())}; +} + +#else // HAS_CHRONO_ROUNDING == 1 + +using std::chrono::floor; +using std::chrono::ceil; +using std::chrono::round; +using std::chrono::abs; + +#endif // HAS_CHRONO_ROUNDING + +namespace detail +{ + +template +CONSTCD14 +inline +typename std::enable_if +< + !std::chrono::treat_as_floating_point::value, + To +>::type +round_i(const std::chrono::duration& d) +{ + return round(d); +} + +template +CONSTCD14 +inline +typename std::enable_if +< + std::chrono::treat_as_floating_point::value, + To +>::type +round_i(const std::chrono::duration& d) +{ + return d; +} + +template +CONSTCD11 +inline +std::chrono::time_point +round_i(const std::chrono::time_point& tp) +{ + using std::chrono::time_point; + return time_point{round_i(tp.time_since_epoch())}; +} + +} // detail + +// trunc towards zero +template +CONSTCD11 +inline +std::chrono::time_point +trunc(const std::chrono::time_point& tp) +{ + using std::chrono::time_point; + return time_point{trunc(tp.time_since_epoch())}; +} + +// day + +CONSTCD11 inline day::day(unsigned d) NOEXCEPT : d_(static_cast(d)) {} +CONSTCD14 inline day& day::operator++() NOEXCEPT {++d_; return *this;} +CONSTCD14 inline day day::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +CONSTCD14 inline day& day::operator--() NOEXCEPT {--d_; return *this;} +CONSTCD14 inline day day::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} +CONSTCD14 inline day& day::operator+=(const days& d) NOEXCEPT {*this = *this + d; return *this;} +CONSTCD14 inline day& day::operator-=(const days& d) NOEXCEPT {*this = *this - d; return *this;} +CONSTCD11 inline day::operator unsigned() const NOEXCEPT {return d_;} +CONSTCD11 inline bool day::ok() const NOEXCEPT {return 1 <= d_ && d_ <= 31;} + +CONSTCD11 +inline +bool +operator==(const day& x, const day& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const day& x, const day& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const day& x, const day& y) NOEXCEPT +{ + return static_cast(x) < static_cast(y); +} + +CONSTCD11 +inline +bool +operator>(const day& x, const day& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const day& x, const day& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const day& x, const day& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD11 +inline +days +operator-(const day& x, const day& y) NOEXCEPT +{ + return days{static_cast(static_cast(x) + - static_cast(y))}; +} + +CONSTCD11 +inline +day +operator+(const day& x, const days& y) NOEXCEPT +{ + return day{static_cast(x) + static_cast(y.count())}; +} + +CONSTCD11 +inline +day +operator+(const days& x, const day& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD11 +inline +day +operator-(const day& x, const days& y) NOEXCEPT +{ + return x + -y; +} + +namespace detail +{ + +template +std::basic_ostream& +low_level_fmt(std::basic_ostream& os, const day& d) +{ + detail::save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::right); + os.width(2); + os << static_cast(d); + return os; +} + +} // namespace detail + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const day& d) +{ + detail::low_level_fmt(os, d); + if (!d.ok()) + os << " is not a valid day"; + return os; +} + +// month + +CONSTCD11 inline month::month(unsigned m) NOEXCEPT : m_(static_cast(m)) {} +CONSTCD14 inline month& month::operator++() NOEXCEPT {*this += months{1}; return *this;} +CONSTCD14 inline month month::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +CONSTCD14 inline month& month::operator--() NOEXCEPT {*this -= months{1}; return *this;} +CONSTCD14 inline month month::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} + +CONSTCD14 +inline +month& +month::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +CONSTCD14 +inline +month& +month::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD11 inline month::operator unsigned() const NOEXCEPT {return m_;} +CONSTCD11 inline bool month::ok() const NOEXCEPT {return 1 <= m_ && m_ <= 12;} + +CONSTCD11 +inline +bool +operator==(const month& x, const month& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const month& x, const month& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const month& x, const month& y) NOEXCEPT +{ + return static_cast(x) < static_cast(y); +} + +CONSTCD11 +inline +bool +operator>(const month& x, const month& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const month& x, const month& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const month& x, const month& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD14 +inline +months +operator-(const month& x, const month& y) NOEXCEPT +{ + auto const d = static_cast(x) - static_cast(y); + return months(d <= 11 ? d : d + 12); +} + +CONSTCD14 +inline +month +operator+(const month& x, const months& y) NOEXCEPT +{ + auto const mu = static_cast(static_cast(x)) + y.count() - 1; + auto const yr = (mu >= 0 ? mu : mu-11) / 12; + return month{static_cast(mu - yr * 12 + 1)}; +} + +CONSTCD14 +inline +month +operator+(const months& x, const month& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD14 +inline +month +operator-(const month& x, const months& y) NOEXCEPT +{ + return x + -y; +} + +namespace detail +{ + +template +std::basic_ostream& +low_level_fmt(std::basic_ostream& os, const month& m) +{ + if (m.ok()) + { + CharT fmt[] = {'%', 'b', 0}; + os << format(os.getloc(), fmt, m); + } + else + os << static_cast(m); + return os; +} + +} // namespace detail + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month& m) +{ + detail::low_level_fmt(os, m); + if (!m.ok()) + os << " is not a valid month"; + return os; +} + +// year + +CONSTCD11 inline year::year(int y) NOEXCEPT : y_(static_cast(y)) {} +CONSTCD14 inline year& year::operator++() NOEXCEPT {++y_; return *this;} +CONSTCD14 inline year year::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +CONSTCD14 inline year& year::operator--() NOEXCEPT {--y_; return *this;} +CONSTCD14 inline year year::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} +CONSTCD14 inline year& year::operator+=(const years& y) NOEXCEPT {*this = *this + y; return *this;} +CONSTCD14 inline year& year::operator-=(const years& y) NOEXCEPT {*this = *this - y; return *this;} +CONSTCD11 inline year year::operator-() const NOEXCEPT {return year{-y_};} +CONSTCD11 inline year year::operator+() const NOEXCEPT {return *this;} + +CONSTCD11 +inline +bool +year::is_leap() const NOEXCEPT +{ + return y_ % 4 == 0 && (y_ % 100 != 0 || y_ % 400 == 0); +} + +CONSTCD11 inline year::operator int() const NOEXCEPT {return y_;} + +CONSTCD11 +inline +bool +year::ok() const NOEXCEPT +{ + return y_ != std::numeric_limits::min(); +} + +CONSTCD11 +inline +bool +operator==(const year& x, const year& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const year& x, const year& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year& x, const year& y) NOEXCEPT +{ + return static_cast(x) < static_cast(y); +} + +CONSTCD11 +inline +bool +operator>(const year& x, const year& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year& x, const year& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year& x, const year& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD11 +inline +years +operator-(const year& x, const year& y) NOEXCEPT +{ + return years{static_cast(x) - static_cast(y)}; +} + +CONSTCD11 +inline +year +operator+(const year& x, const years& y) NOEXCEPT +{ + return year{static_cast(x) + y.count()}; +} + +CONSTCD11 +inline +year +operator+(const years& x, const year& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD11 +inline +year +operator-(const year& x, const years& y) NOEXCEPT +{ + return year{static_cast(x) - y.count()}; +} + +namespace detail +{ + +template +std::basic_ostream& +low_level_fmt(std::basic_ostream& os, const year& y) +{ + detail::save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::internal); + os.width(4 + (y < year{0})); + os.imbue(std::locale::classic()); + os << static_cast(y); + return os; +} + +} // namespace detail + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year& y) +{ + detail::low_level_fmt(os, y); + if (!y.ok()) + os << " is not a valid year"; + return os; +} + +// weekday + +CONSTCD14 +inline +unsigned char +weekday::weekday_from_days(int z) NOEXCEPT +{ + auto u = static_cast(z); + return static_cast(z >= -4 ? (u+4) % 7 : u % 7); +} + +CONSTCD11 +inline +weekday::weekday(unsigned wd) NOEXCEPT + : wd_(static_cast(wd != 7 ? wd : 0)) + {} + +CONSTCD14 +inline +weekday::weekday(const sys_days& dp) NOEXCEPT + : wd_(weekday_from_days(dp.time_since_epoch().count())) + {} + +CONSTCD14 +inline +weekday::weekday(const local_days& dp) NOEXCEPT + : wd_(weekday_from_days(dp.time_since_epoch().count())) + {} + +CONSTCD14 inline weekday& weekday::operator++() NOEXCEPT {*this += days{1}; return *this;} +CONSTCD14 inline weekday weekday::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +CONSTCD14 inline weekday& weekday::operator--() NOEXCEPT {*this -= days{1}; return *this;} +CONSTCD14 inline weekday weekday::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} + +CONSTCD14 +inline +weekday& +weekday::operator+=(const days& d) NOEXCEPT +{ + *this = *this + d; + return *this; +} + +CONSTCD14 +inline +weekday& +weekday::operator-=(const days& d) NOEXCEPT +{ + *this = *this - d; + return *this; +} + +CONSTCD11 inline bool weekday::ok() const NOEXCEPT {return wd_ <= 6;} + +CONSTCD11 +inline +unsigned weekday::c_encoding() const NOEXCEPT +{ + return unsigned{wd_}; +} + +CONSTCD11 +inline +unsigned weekday::iso_encoding() const NOEXCEPT +{ + return unsigned{((wd_ == 0u) ? 7u : wd_)}; +} + +CONSTCD11 +inline +bool +operator==(const weekday& x, const weekday& y) NOEXCEPT +{ + return x.wd_ == y.wd_; +} + +CONSTCD11 +inline +bool +operator!=(const weekday& x, const weekday& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD14 +inline +days +operator-(const weekday& x, const weekday& y) NOEXCEPT +{ + auto const wdu = x.wd_ - y.wd_; + auto const wk = (wdu >= 0 ? wdu : wdu-6) / 7; + return days{wdu - wk * 7}; +} + +CONSTCD14 +inline +weekday +operator+(const weekday& x, const days& y) NOEXCEPT +{ + auto const wdu = static_cast(static_cast(x.wd_)) + y.count(); + auto const wk = (wdu >= 0 ? wdu : wdu-6) / 7; + return weekday{static_cast(wdu - wk * 7)}; +} + +CONSTCD14 +inline +weekday +operator+(const days& x, const weekday& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD14 +inline +weekday +operator-(const weekday& x, const days& y) NOEXCEPT +{ + return x + -y; +} + +namespace detail +{ + +template +std::basic_ostream& +low_level_fmt(std::basic_ostream& os, const weekday& wd) +{ + if (wd.ok()) + { + CharT fmt[] = {'%', 'a', 0}; + os << format(fmt, wd); + } + else + os << wd.c_encoding(); + return os; +} + +} // namespace detail + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday& wd) +{ + detail::low_level_fmt(os, wd); + if (!wd.ok()) + os << " is not a valid weekday"; + return os; +} + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) +inline namespace literals +{ + +CONSTCD11 +inline +date::day +operator "" _d(unsigned long long d) NOEXCEPT +{ + return date::day{static_cast(d)}; +} + +CONSTCD11 +inline +date::year +operator "" _y(unsigned long long y) NOEXCEPT +{ + return date::year(static_cast(y)); +} +#endif // !defined(_MSC_VER) || (_MSC_VER >= 1900) + +CONSTDATA date::last_spec last{}; + +CONSTDATA date::month jan{1}; +CONSTDATA date::month feb{2}; +CONSTDATA date::month mar{3}; +CONSTDATA date::month apr{4}; +CONSTDATA date::month may{5}; +CONSTDATA date::month jun{6}; +CONSTDATA date::month jul{7}; +CONSTDATA date::month aug{8}; +CONSTDATA date::month sep{9}; +CONSTDATA date::month oct{10}; +CONSTDATA date::month nov{11}; +CONSTDATA date::month dec{12}; + +CONSTDATA date::weekday sun{0u}; +CONSTDATA date::weekday mon{1u}; +CONSTDATA date::weekday tue{2u}; +CONSTDATA date::weekday wed{3u}; +CONSTDATA date::weekday thu{4u}; +CONSTDATA date::weekday fri{5u}; +CONSTDATA date::weekday sat{6u}; + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) +} // inline namespace literals +#endif + +CONSTDATA date::month January{1}; +CONSTDATA date::month February{2}; +CONSTDATA date::month March{3}; +CONSTDATA date::month April{4}; +CONSTDATA date::month May{5}; +CONSTDATA date::month June{6}; +CONSTDATA date::month July{7}; +CONSTDATA date::month August{8}; +CONSTDATA date::month September{9}; +CONSTDATA date::month October{10}; +CONSTDATA date::month November{11}; +CONSTDATA date::month December{12}; + +CONSTDATA date::weekday Monday{1}; +CONSTDATA date::weekday Tuesday{2}; +CONSTDATA date::weekday Wednesday{3}; +CONSTDATA date::weekday Thursday{4}; +CONSTDATA date::weekday Friday{5}; +CONSTDATA date::weekday Saturday{6}; +CONSTDATA date::weekday Sunday{7}; + +// weekday_indexed + +CONSTCD11 +inline +weekday +weekday_indexed::weekday() const NOEXCEPT +{ + return date::weekday{static_cast(wd_)}; +} + +CONSTCD11 inline unsigned weekday_indexed::index() const NOEXCEPT {return index_;} + +CONSTCD11 +inline +bool +weekday_indexed::ok() const NOEXCEPT +{ + return weekday().ok() && 1 <= index_ && index_ <= 5; +} + +#ifdef __GNUC__ +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wconversion" +#endif // __GNUC__ + +CONSTCD11 +inline +weekday_indexed::weekday_indexed(const date::weekday& wd, unsigned index) NOEXCEPT + : wd_(static_cast(static_cast(wd.wd_))) + , index_(static_cast(index)) + {} + +#ifdef __GNUC__ +# pragma GCC diagnostic pop +#endif // __GNUC__ + +namespace detail +{ + +template +std::basic_ostream& +low_level_fmt(std::basic_ostream& os, const weekday_indexed& wdi) +{ + return low_level_fmt(os, wdi.weekday()) << '[' << wdi.index() << ']'; +} + +} // namespace detail + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday_indexed& wdi) +{ + detail::low_level_fmt(os, wdi); + if (!wdi.ok()) + os << " is not a valid weekday_indexed"; + return os; +} + +CONSTCD11 +inline +weekday_indexed +weekday::operator[](unsigned index) const NOEXCEPT +{ + return {*this, index}; +} + +CONSTCD11 +inline +bool +operator==(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT +{ + return x.weekday() == y.weekday() && x.index() == y.index(); +} + +CONSTCD11 +inline +bool +operator!=(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT +{ + return !(x == y); +} + +// weekday_last + +CONSTCD11 inline date::weekday weekday_last::weekday() const NOEXCEPT {return wd_;} +CONSTCD11 inline bool weekday_last::ok() const NOEXCEPT {return wd_.ok();} +CONSTCD11 inline weekday_last::weekday_last(const date::weekday& wd) NOEXCEPT : wd_(wd) {} + +CONSTCD11 +inline +bool +operator==(const weekday_last& x, const weekday_last& y) NOEXCEPT +{ + return x.weekday() == y.weekday(); +} + +CONSTCD11 +inline +bool +operator!=(const weekday_last& x, const weekday_last& y) NOEXCEPT +{ + return !(x == y); +} + +namespace detail +{ + +template +std::basic_ostream& +low_level_fmt(std::basic_ostream& os, const weekday_last& wdl) +{ + return low_level_fmt(os, wdl.weekday()) << "[last]"; +} + +} // namespace detail + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday_last& wdl) +{ + detail::low_level_fmt(os, wdl); + if (!wdl.ok()) + os << " is not a valid weekday_last"; + return os; +} + +CONSTCD11 +inline +weekday_last +weekday::operator[](last_spec) const NOEXCEPT +{ + return weekday_last{*this}; +} + +// year_month + +CONSTCD11 +inline +year_month::year_month(const date::year& y, const date::month& m) NOEXCEPT + : y_(y) + , m_(m) + {} + +CONSTCD11 inline year year_month::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month::month() const NOEXCEPT {return m_;} +CONSTCD11 inline bool year_month::ok() const NOEXCEPT {return y_.ok() && m_.ok();} + +template +CONSTCD14 +inline +year_month& +year_month::operator+=(const months& dm) NOEXCEPT +{ + *this = *this + dm; + return *this; +} + +template +CONSTCD14 +inline +year_month& +year_month::operator-=(const months& dm) NOEXCEPT +{ + *this = *this - dm; + return *this; +} + +CONSTCD14 +inline +year_month& +year_month::operator+=(const years& dy) NOEXCEPT +{ + *this = *this + dy; + return *this; +} + +CONSTCD14 +inline +year_month& +year_month::operator-=(const years& dy) NOEXCEPT +{ + *this = *this - dy; + return *this; +} + +CONSTCD11 +inline +bool +operator==(const year_month& x, const year_month& y) NOEXCEPT +{ + return x.year() == y.year() && x.month() == y.month(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month& x, const year_month& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year_month& x, const year_month& y) NOEXCEPT +{ + return x.year() < y.year() ? true + : (x.year() > y.year() ? false + : (x.month() < y.month())); +} + +CONSTCD11 +inline +bool +operator>(const year_month& x, const year_month& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year_month& x, const year_month& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year_month& x, const year_month& y) NOEXCEPT +{ + return !(x < y); +} + +template +CONSTCD14 +inline +year_month +operator+(const year_month& ym, const months& dm) NOEXCEPT +{ + auto dmi = static_cast(static_cast(ym.month())) - 1 + dm.count(); + auto dy = (dmi >= 0 ? dmi : dmi-11) / 12; + dmi = dmi - dy * 12 + 1; + return (ym.year() + years(dy)) / month(static_cast(dmi)); +} + +template +CONSTCD14 +inline +year_month +operator+(const months& dm, const year_month& ym) NOEXCEPT +{ + return ym + dm; +} + +template +CONSTCD14 +inline +year_month +operator-(const year_month& ym, const months& dm) NOEXCEPT +{ + return ym + -dm; +} + +CONSTCD11 +inline +months +operator-(const year_month& x, const year_month& y) NOEXCEPT +{ + return (x.year() - y.year()) + + months(static_cast(x.month()) - static_cast(y.month())); +} + +CONSTCD11 +inline +year_month +operator+(const year_month& ym, const years& dy) NOEXCEPT +{ + return (ym.year() + dy) / ym.month(); +} + +CONSTCD11 +inline +year_month +operator+(const years& dy, const year_month& ym) NOEXCEPT +{ + return ym + dy; +} + +CONSTCD11 +inline +year_month +operator-(const year_month& ym, const years& dy) NOEXCEPT +{ + return ym + -dy; +} + +namespace detail +{ + +template +std::basic_ostream& +low_level_fmt(std::basic_ostream& os, const year_month& ym) +{ + low_level_fmt(os, ym.year()) << '/'; + return low_level_fmt(os, ym.month()); +} + +} // namespace detail + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month& ym) +{ + detail::low_level_fmt(os, ym); + if (!ym.ok()) + os << " is not a valid year_month"; + return os; +} + +// month_day + +CONSTCD11 +inline +month_day::month_day(const date::month& m, const date::day& d) NOEXCEPT + : m_(m) + , d_(d) + {} + +CONSTCD11 inline date::month month_day::month() const NOEXCEPT {return m_;} +CONSTCD11 inline date::day month_day::day() const NOEXCEPT {return d_;} + +CONSTCD14 +inline +bool +month_day::ok() const NOEXCEPT +{ + CONSTDATA date::day d[] = + { + date::day(31), date::day(29), date::day(31), + date::day(30), date::day(31), date::day(30), + date::day(31), date::day(31), date::day(30), + date::day(31), date::day(30), date::day(31) + }; + return m_.ok() && date::day{1} <= d_ && d_ <= d[static_cast(m_)-1]; +} + +CONSTCD11 +inline +bool +operator==(const month_day& x, const month_day& y) NOEXCEPT +{ + return x.month() == y.month() && x.day() == y.day(); +} + +CONSTCD11 +inline +bool +operator!=(const month_day& x, const month_day& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const month_day& x, const month_day& y) NOEXCEPT +{ + return x.month() < y.month() ? true + : (x.month() > y.month() ? false + : (x.day() < y.day())); +} + +CONSTCD11 +inline +bool +operator>(const month_day& x, const month_day& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const month_day& x, const month_day& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const month_day& x, const month_day& y) NOEXCEPT +{ + return !(x < y); +} + +namespace detail +{ + +template +std::basic_ostream& +low_level_fmt(std::basic_ostream& os, const month_day& md) +{ + low_level_fmt(os, md.month()) << '/'; + return low_level_fmt(os, md.day()); +} + +} // namespace detail + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_day& md) +{ + detail::low_level_fmt(os, md); + if (!md.ok()) + os << " is not a valid month_day"; + return os; +} + +// month_day_last + +CONSTCD11 inline month month_day_last::month() const NOEXCEPT {return m_;} +CONSTCD11 inline bool month_day_last::ok() const NOEXCEPT {return m_.ok();} +CONSTCD11 inline month_day_last::month_day_last(const date::month& m) NOEXCEPT : m_(m) {} + +CONSTCD11 +inline +bool +operator==(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return x.month() == y.month(); +} + +CONSTCD11 +inline +bool +operator!=(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return x.month() < y.month(); +} + +CONSTCD11 +inline +bool +operator>(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return !(x < y); +} + +namespace detail +{ + +template +std::basic_ostream& +low_level_fmt(std::basic_ostream& os, const month_day_last& mdl) +{ + return low_level_fmt(os, mdl.month()) << "/last"; +} + +} // namespace detail + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_day_last& mdl) +{ + detail::low_level_fmt(os, mdl); + if (!mdl.ok()) + os << " is not a valid month_day_last"; + return os; +} + +// month_weekday + +CONSTCD11 +inline +month_weekday::month_weekday(const date::month& m, + const date::weekday_indexed& wdi) NOEXCEPT + : m_(m) + , wdi_(wdi) + {} + +CONSTCD11 inline month month_weekday::month() const NOEXCEPT {return m_;} + +CONSTCD11 +inline +weekday_indexed +month_weekday::weekday_indexed() const NOEXCEPT +{ + return wdi_; +} + +CONSTCD11 +inline +bool +month_weekday::ok() const NOEXCEPT +{ + return m_.ok() && wdi_.ok(); +} + +CONSTCD11 +inline +bool +operator==(const month_weekday& x, const month_weekday& y) NOEXCEPT +{ + return x.month() == y.month() && x.weekday_indexed() == y.weekday_indexed(); +} + +CONSTCD11 +inline +bool +operator!=(const month_weekday& x, const month_weekday& y) NOEXCEPT +{ + return !(x == y); +} + +namespace detail +{ + +template +std::basic_ostream& +low_level_fmt(std::basic_ostream& os, const month_weekday& mwd) +{ + low_level_fmt(os, mwd.month()) << '/'; + return low_level_fmt(os, mwd.weekday_indexed()); +} + +} // namespace detail + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_weekday& mwd) +{ + detail::low_level_fmt(os, mwd); + if (!mwd.ok()) + os << " is not a valid month_weekday"; + return os; +} + +// month_weekday_last + +CONSTCD11 +inline +month_weekday_last::month_weekday_last(const date::month& m, + const date::weekday_last& wdl) NOEXCEPT + : m_(m) + , wdl_(wdl) + {} + +CONSTCD11 inline month month_weekday_last::month() const NOEXCEPT {return m_;} + +CONSTCD11 +inline +weekday_last +month_weekday_last::weekday_last() const NOEXCEPT +{ + return wdl_; +} + +CONSTCD11 +inline +bool +month_weekday_last::ok() const NOEXCEPT +{ + return m_.ok() && wdl_.ok(); +} + +CONSTCD11 +inline +bool +operator==(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT +{ + return x.month() == y.month() && x.weekday_last() == y.weekday_last(); +} + +CONSTCD11 +inline +bool +operator!=(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT +{ + return !(x == y); +} + +namespace detail +{ + +template +std::basic_ostream& +low_level_fmt(std::basic_ostream& os, const month_weekday_last& mwdl) +{ + low_level_fmt(os, mwdl.month()) << '/'; + return low_level_fmt(os, mwdl.weekday_last()); +} + +} // namespace detail + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_weekday_last& mwdl) +{ + detail::low_level_fmt(os, mwdl); + if (!mwdl.ok()) + os << " is not a valid month_weekday_last"; + return os; +} + +// year_month_day_last + +CONSTCD11 +inline +year_month_day_last::year_month_day_last(const date::year& y, + const date::month_day_last& mdl) NOEXCEPT + : y_(y) + , mdl_(mdl) + {} + +template +CONSTCD14 +inline +year_month_day_last& +year_month_day_last::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +template +CONSTCD14 +inline +year_month_day_last& +year_month_day_last::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD14 +inline +year_month_day_last& +year_month_day_last::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +CONSTCD14 +inline +year_month_day_last& +year_month_day_last::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD11 inline year year_month_day_last::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month_day_last::month() const NOEXCEPT {return mdl_.month();} + +CONSTCD11 +inline +month_day_last +year_month_day_last::month_day_last() const NOEXCEPT +{ + return mdl_; +} + +CONSTCD14 +inline +day +year_month_day_last::day() const NOEXCEPT +{ + CONSTDATA date::day d[] = + { + date::day(31), date::day(28), date::day(31), + date::day(30), date::day(31), date::day(30), + date::day(31), date::day(31), date::day(30), + date::day(31), date::day(30), date::day(31) + }; + return (month() != February || !y_.is_leap()) && mdl_.ok() ? + d[static_cast(month()) - 1] : date::day{29}; +} + +CONSTCD14 +inline +year_month_day_last::operator sys_days() const NOEXCEPT +{ + return sys_days(year()/month()/day()); +} + +CONSTCD14 +inline +year_month_day_last::operator local_days() const NOEXCEPT +{ + return local_days(year()/month()/day()); +} + +CONSTCD11 +inline +bool +year_month_day_last::ok() const NOEXCEPT +{ + return y_.ok() && mdl_.ok(); +} + +CONSTCD11 +inline +bool +operator==(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return x.year() == y.year() && x.month_day_last() == y.month_day_last(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return x.year() < y.year() ? true + : (x.year() > y.year() ? false + : (x.month_day_last() < y.month_day_last())); +} + +CONSTCD11 +inline +bool +operator>(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return !(x < y); +} + +namespace detail +{ + +template +std::basic_ostream& +low_level_fmt(std::basic_ostream& os, const year_month_day_last& ymdl) +{ + low_level_fmt(os, ymdl.year()) << '/'; + return low_level_fmt(os, ymdl.month_day_last()); +} + +} // namespace detail + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_day_last& ymdl) +{ + detail::low_level_fmt(os, ymdl); + if (!ymdl.ok()) + os << " is not a valid year_month_day_last"; + return os; +} + +template +CONSTCD14 +inline +year_month_day_last +operator+(const year_month_day_last& ymdl, const months& dm) NOEXCEPT +{ + return (ymdl.year() / ymdl.month() + dm) / last; +} + +template +CONSTCD14 +inline +year_month_day_last +operator+(const months& dm, const year_month_day_last& ymdl) NOEXCEPT +{ + return ymdl + dm; +} + +template +CONSTCD14 +inline +year_month_day_last +operator-(const year_month_day_last& ymdl, const months& dm) NOEXCEPT +{ + return ymdl + (-dm); +} + +CONSTCD11 +inline +year_month_day_last +operator+(const year_month_day_last& ymdl, const years& dy) NOEXCEPT +{ + return {ymdl.year()+dy, ymdl.month_day_last()}; +} + +CONSTCD11 +inline +year_month_day_last +operator+(const years& dy, const year_month_day_last& ymdl) NOEXCEPT +{ + return ymdl + dy; +} + +CONSTCD11 +inline +year_month_day_last +operator-(const year_month_day_last& ymdl, const years& dy) NOEXCEPT +{ + return ymdl + (-dy); +} + +// year_month_day + +CONSTCD11 +inline +year_month_day::year_month_day(const date::year& y, const date::month& m, + const date::day& d) NOEXCEPT + : y_(y) + , m_(m) + , d_(d) + {} + +CONSTCD14 +inline +year_month_day::year_month_day(const year_month_day_last& ymdl) NOEXCEPT + : y_(ymdl.year()) + , m_(ymdl.month()) + , d_(ymdl.day()) + {} + +CONSTCD14 +inline +year_month_day::year_month_day(sys_days dp) NOEXCEPT + : year_month_day(from_days(dp.time_since_epoch())) + {} + +CONSTCD14 +inline +year_month_day::year_month_day(local_days dp) NOEXCEPT + : year_month_day(from_days(dp.time_since_epoch())) + {} + +CONSTCD11 inline year year_month_day::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month_day::month() const NOEXCEPT {return m_;} +CONSTCD11 inline day year_month_day::day() const NOEXCEPT {return d_;} + +template +CONSTCD14 +inline +year_month_day& +year_month_day::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +template +CONSTCD14 +inline +year_month_day& +year_month_day::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD14 +inline +year_month_day& +year_month_day::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +CONSTCD14 +inline +year_month_day& +year_month_day::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD14 +inline +days +year_month_day::to_days() const NOEXCEPT +{ + static_assert(std::numeric_limits::digits >= 18, + "This algorithm has not been ported to a 16 bit unsigned integer"); + static_assert(std::numeric_limits::digits >= 20, + "This algorithm has not been ported to a 16 bit signed integer"); + auto const y = static_cast(y_) - (m_ <= February); + auto const m = static_cast(m_); + auto const d = static_cast(d_); + auto const era = (y >= 0 ? y : y-399) / 400; + auto const yoe = static_cast(y - era * 400); // [0, 399] + auto const doy = (153*(m > 2 ? m-3 : m+9) + 2)/5 + d-1; // [0, 365] + auto const doe = yoe * 365 + yoe/4 - yoe/100 + doy; // [0, 146096] + return days{era * 146097 + static_cast(doe) - 719468}; +} + +CONSTCD14 +inline +year_month_day::operator sys_days() const NOEXCEPT +{ + return sys_days{to_days()}; +} + +CONSTCD14 +inline +year_month_day::operator local_days() const NOEXCEPT +{ + return local_days{to_days()}; +} + +CONSTCD14 +inline +bool +year_month_day::ok() const NOEXCEPT +{ + if (!(y_.ok() && m_.ok())) + return false; + return date::day{1} <= d_ && d_ <= (y_ / m_ / last).day(); +} + +CONSTCD11 +inline +bool +operator==(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return x.year() == y.year() && x.month() == y.month() && x.day() == y.day(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return x.year() < y.year() ? true + : (x.year() > y.year() ? false + : (x.month() < y.month() ? true + : (x.month() > y.month() ? false + : (x.day() < y.day())))); +} + +CONSTCD11 +inline +bool +operator>(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return !(x < y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_day& ymd) +{ + detail::save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::right); + os.imbue(std::locale::classic()); + os << static_cast(ymd.year()) << '-'; + os.width(2); + os << static_cast(ymd.month()) << '-'; + os.width(2); + os << static_cast(ymd.day()); + if (!ymd.ok()) + os << " is not a valid year_month_day"; + return os; +} + +CONSTCD14 +inline +year_month_day +year_month_day::from_days(days dp) NOEXCEPT +{ + static_assert(std::numeric_limits::digits >= 18, + "This algorithm has not been ported to a 16 bit unsigned integer"); + static_assert(std::numeric_limits::digits >= 20, + "This algorithm has not been ported to a 16 bit signed integer"); + auto const z = dp.count() + 719468; + auto const era = (z >= 0 ? z : z - 146096) / 146097; + auto const doe = static_cast(z - era * 146097); // [0, 146096] + auto const yoe = (doe - doe/1460 + doe/36524 - doe/146096) / 365; // [0, 399] + auto const y = static_cast(yoe) + era * 400; + auto const doy = doe - (365*yoe + yoe/4 - yoe/100); // [0, 365] + auto const mp = (5*doy + 2)/153; // [0, 11] + auto const d = doy - (153*mp+2)/5 + 1; // [1, 31] + auto const m = mp < 10 ? mp+3 : mp-9; // [1, 12] + return year_month_day{date::year{y + (m <= 2)}, date::month(m), date::day(d)}; +} + +template +CONSTCD14 +inline +year_month_day +operator+(const year_month_day& ymd, const months& dm) NOEXCEPT +{ + return (ymd.year() / ymd.month() + dm) / ymd.day(); +} + +template +CONSTCD14 +inline +year_month_day +operator+(const months& dm, const year_month_day& ymd) NOEXCEPT +{ + return ymd + dm; +} + +template +CONSTCD14 +inline +year_month_day +operator-(const year_month_day& ymd, const months& dm) NOEXCEPT +{ + return ymd + (-dm); +} + +CONSTCD11 +inline +year_month_day +operator+(const year_month_day& ymd, const years& dy) NOEXCEPT +{ + return (ymd.year() + dy) / ymd.month() / ymd.day(); +} + +CONSTCD11 +inline +year_month_day +operator+(const years& dy, const year_month_day& ymd) NOEXCEPT +{ + return ymd + dy; +} + +CONSTCD11 +inline +year_month_day +operator-(const year_month_day& ymd, const years& dy) NOEXCEPT +{ + return ymd + (-dy); +} + +// year_month_weekday + +CONSTCD11 +inline +year_month_weekday::year_month_weekday(const date::year& y, const date::month& m, + const date::weekday_indexed& wdi) + NOEXCEPT + : y_(y) + , m_(m) + , wdi_(wdi) + {} + +CONSTCD14 +inline +year_month_weekday::year_month_weekday(const sys_days& dp) NOEXCEPT + : year_month_weekday(from_days(dp.time_since_epoch())) + {} + +CONSTCD14 +inline +year_month_weekday::year_month_weekday(const local_days& dp) NOEXCEPT + : year_month_weekday(from_days(dp.time_since_epoch())) + {} + +template +CONSTCD14 +inline +year_month_weekday& +year_month_weekday::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +template +CONSTCD14 +inline +year_month_weekday& +year_month_weekday::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD14 +inline +year_month_weekday& +year_month_weekday::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +CONSTCD14 +inline +year_month_weekday& +year_month_weekday::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD11 inline year year_month_weekday::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month_weekday::month() const NOEXCEPT {return m_;} + +CONSTCD11 +inline +weekday +year_month_weekday::weekday() const NOEXCEPT +{ + return wdi_.weekday(); +} + +CONSTCD11 +inline +unsigned +year_month_weekday::index() const NOEXCEPT +{ + return wdi_.index(); +} + +CONSTCD11 +inline +weekday_indexed +year_month_weekday::weekday_indexed() const NOEXCEPT +{ + return wdi_; +} + +CONSTCD14 +inline +year_month_weekday::operator sys_days() const NOEXCEPT +{ + return sys_days{to_days()}; +} + +CONSTCD14 +inline +year_month_weekday::operator local_days() const NOEXCEPT +{ + return local_days{to_days()}; +} + +CONSTCD14 +inline +bool +year_month_weekday::ok() const NOEXCEPT +{ + if (!y_.ok() || !m_.ok() || !wdi_.weekday().ok() || wdi_.index() < 1) + return false; + if (wdi_.index() <= 4) + return true; + auto d2 = wdi_.weekday() - date::weekday(static_cast(y_/m_/1)) + + days((wdi_.index()-1)*7 + 1); + return static_cast(d2.count()) <= static_cast((y_/m_/last).day()); +} + +CONSTCD14 +inline +year_month_weekday +year_month_weekday::from_days(days d) NOEXCEPT +{ + sys_days dp{d}; + auto const wd = date::weekday(dp); + auto const ymd = year_month_day(dp); + return {ymd.year(), ymd.month(), wd[(static_cast(ymd.day())-1)/7+1]}; +} + +CONSTCD14 +inline +days +year_month_weekday::to_days() const NOEXCEPT +{ + auto d = sys_days(y_/m_/1); + return (d + (wdi_.weekday() - date::weekday(d) + days{(wdi_.index()-1)*7}) + ).time_since_epoch(); +} + +CONSTCD11 +inline +bool +operator==(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT +{ + return x.year() == y.year() && x.month() == y.month() && + x.weekday_indexed() == y.weekday_indexed(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_weekday& ymwdi) +{ + detail::low_level_fmt(os, ymwdi.year()) << '/'; + detail::low_level_fmt(os, ymwdi.month()) << '/'; + detail::low_level_fmt(os, ymwdi.weekday_indexed()); + if (!ymwdi.ok()) + os << " is not a valid year_month_weekday"; + return os; +} + +template +CONSTCD14 +inline +year_month_weekday +operator+(const year_month_weekday& ymwd, const months& dm) NOEXCEPT +{ + return (ymwd.year() / ymwd.month() + dm) / ymwd.weekday_indexed(); +} + +template +CONSTCD14 +inline +year_month_weekday +operator+(const months& dm, const year_month_weekday& ymwd) NOEXCEPT +{ + return ymwd + dm; +} + +template +CONSTCD14 +inline +year_month_weekday +operator-(const year_month_weekday& ymwd, const months& dm) NOEXCEPT +{ + return ymwd + (-dm); +} + +CONSTCD11 +inline +year_month_weekday +operator+(const year_month_weekday& ymwd, const years& dy) NOEXCEPT +{ + return {ymwd.year()+dy, ymwd.month(), ymwd.weekday_indexed()}; +} + +CONSTCD11 +inline +year_month_weekday +operator+(const years& dy, const year_month_weekday& ymwd) NOEXCEPT +{ + return ymwd + dy; +} + +CONSTCD11 +inline +year_month_weekday +operator-(const year_month_weekday& ymwd, const years& dy) NOEXCEPT +{ + return ymwd + (-dy); +} + +// year_month_weekday_last + +CONSTCD11 +inline +year_month_weekday_last::year_month_weekday_last(const date::year& y, + const date::month& m, + const date::weekday_last& wdl) NOEXCEPT + : y_(y) + , m_(m) + , wdl_(wdl) + {} + +template +CONSTCD14 +inline +year_month_weekday_last& +year_month_weekday_last::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +template +CONSTCD14 +inline +year_month_weekday_last& +year_month_weekday_last::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD14 +inline +year_month_weekday_last& +year_month_weekday_last::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +CONSTCD14 +inline +year_month_weekday_last& +year_month_weekday_last::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD11 inline year year_month_weekday_last::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month_weekday_last::month() const NOEXCEPT {return m_;} + +CONSTCD11 +inline +weekday +year_month_weekday_last::weekday() const NOEXCEPT +{ + return wdl_.weekday(); +} + +CONSTCD11 +inline +weekday_last +year_month_weekday_last::weekday_last() const NOEXCEPT +{ + return wdl_; +} + +CONSTCD14 +inline +year_month_weekday_last::operator sys_days() const NOEXCEPT +{ + return sys_days{to_days()}; +} + +CONSTCD14 +inline +year_month_weekday_last::operator local_days() const NOEXCEPT +{ + return local_days{to_days()}; +} + +CONSTCD11 +inline +bool +year_month_weekday_last::ok() const NOEXCEPT +{ + return y_.ok() && m_.ok() && wdl_.ok(); +} + +CONSTCD14 +inline +days +year_month_weekday_last::to_days() const NOEXCEPT +{ + auto const d = sys_days(y_/m_/last); + return (d - (date::weekday{d} - wdl_.weekday())).time_since_epoch(); +} + +CONSTCD11 +inline +bool +operator==(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT +{ + return x.year() == y.year() && x.month() == y.month() && + x.weekday_last() == y.weekday_last(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_weekday_last& ymwdl) +{ + detail::low_level_fmt(os, ymwdl.year()) << '/'; + detail::low_level_fmt(os, ymwdl.month()) << '/'; + detail::low_level_fmt(os, ymwdl.weekday_last()); + if (!ymwdl.ok()) + os << " is not a valid year_month_weekday_last"; + return os; +} + +template +CONSTCD14 +inline +year_month_weekday_last +operator+(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT +{ + return (ymwdl.year() / ymwdl.month() + dm) / ymwdl.weekday_last(); +} + +template +CONSTCD14 +inline +year_month_weekday_last +operator+(const months& dm, const year_month_weekday_last& ymwdl) NOEXCEPT +{ + return ymwdl + dm; +} + +template +CONSTCD14 +inline +year_month_weekday_last +operator-(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT +{ + return ymwdl + (-dm); +} + +CONSTCD11 +inline +year_month_weekday_last +operator+(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT +{ + return {ymwdl.year()+dy, ymwdl.month(), ymwdl.weekday_last()}; +} + +CONSTCD11 +inline +year_month_weekday_last +operator+(const years& dy, const year_month_weekday_last& ymwdl) NOEXCEPT +{ + return ymwdl + dy; +} + +CONSTCD11 +inline +year_month_weekday_last +operator-(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT +{ + return ymwdl + (-dy); +} + +// year_month from operator/() + +CONSTCD11 +inline +year_month +operator/(const year& y, const month& m) NOEXCEPT +{ + return {y, m}; +} + +CONSTCD11 +inline +year_month +operator/(const year& y, int m) NOEXCEPT +{ + return y / month(static_cast(m)); +} + +// month_day from operator/() + +CONSTCD11 +inline +month_day +operator/(const month& m, const day& d) NOEXCEPT +{ + return {m, d}; +} + +CONSTCD11 +inline +month_day +operator/(const day& d, const month& m) NOEXCEPT +{ + return m / d; +} + +CONSTCD11 +inline +month_day +operator/(const month& m, int d) NOEXCEPT +{ + return m / day(static_cast(d)); +} + +CONSTCD11 +inline +month_day +operator/(int m, const day& d) NOEXCEPT +{ + return month(static_cast(m)) / d; +} + +CONSTCD11 inline month_day operator/(const day& d, int m) NOEXCEPT {return m / d;} + +// month_day_last from operator/() + +CONSTCD11 +inline +month_day_last +operator/(const month& m, last_spec) NOEXCEPT +{ + return month_day_last{m}; +} + +CONSTCD11 +inline +month_day_last +operator/(last_spec, const month& m) NOEXCEPT +{ + return m/last; +} + +CONSTCD11 +inline +month_day_last +operator/(int m, last_spec) NOEXCEPT +{ + return month(static_cast(m))/last; +} + +CONSTCD11 +inline +month_day_last +operator/(last_spec, int m) NOEXCEPT +{ + return m/last; +} + +// month_weekday from operator/() + +CONSTCD11 +inline +month_weekday +operator/(const month& m, const weekday_indexed& wdi) NOEXCEPT +{ + return {m, wdi}; +} + +CONSTCD11 +inline +month_weekday +operator/(const weekday_indexed& wdi, const month& m) NOEXCEPT +{ + return m / wdi; +} + +CONSTCD11 +inline +month_weekday +operator/(int m, const weekday_indexed& wdi) NOEXCEPT +{ + return month(static_cast(m)) / wdi; +} + +CONSTCD11 +inline +month_weekday +operator/(const weekday_indexed& wdi, int m) NOEXCEPT +{ + return m / wdi; +} + +// month_weekday_last from operator/() + +CONSTCD11 +inline +month_weekday_last +operator/(const month& m, const weekday_last& wdl) NOEXCEPT +{ + return {m, wdl}; +} + +CONSTCD11 +inline +month_weekday_last +operator/(const weekday_last& wdl, const month& m) NOEXCEPT +{ + return m / wdl; +} + +CONSTCD11 +inline +month_weekday_last +operator/(int m, const weekday_last& wdl) NOEXCEPT +{ + return month(static_cast(m)) / wdl; +} + +CONSTCD11 +inline +month_weekday_last +operator/(const weekday_last& wdl, int m) NOEXCEPT +{ + return m / wdl; +} + +// year_month_day from operator/() + +CONSTCD11 +inline +year_month_day +operator/(const year_month& ym, const day& d) NOEXCEPT +{ + return {ym.year(), ym.month(), d}; +} + +CONSTCD11 +inline +year_month_day +operator/(const year_month& ym, int d) NOEXCEPT +{ + return ym / day(static_cast(d)); +} + +CONSTCD11 +inline +year_month_day +operator/(const year& y, const month_day& md) NOEXCEPT +{ + return y / md.month() / md.day(); +} + +CONSTCD11 +inline +year_month_day +operator/(int y, const month_day& md) NOEXCEPT +{ + return year(y) / md; +} + +CONSTCD11 +inline +year_month_day +operator/(const month_day& md, const year& y) NOEXCEPT +{ + return y / md; +} + +CONSTCD11 +inline +year_month_day +operator/(const month_day& md, int y) NOEXCEPT +{ + return year(y) / md; +} + +// year_month_day_last from operator/() + +CONSTCD11 +inline +year_month_day_last +operator/(const year_month& ym, last_spec) NOEXCEPT +{ + return {ym.year(), month_day_last{ym.month()}}; +} + +CONSTCD11 +inline +year_month_day_last +operator/(const year& y, const month_day_last& mdl) NOEXCEPT +{ + return {y, mdl}; +} + +CONSTCD11 +inline +year_month_day_last +operator/(int y, const month_day_last& mdl) NOEXCEPT +{ + return year(y) / mdl; +} + +CONSTCD11 +inline +year_month_day_last +operator/(const month_day_last& mdl, const year& y) NOEXCEPT +{ + return y / mdl; +} + +CONSTCD11 +inline +year_month_day_last +operator/(const month_day_last& mdl, int y) NOEXCEPT +{ + return year(y) / mdl; +} + +// year_month_weekday from operator/() + +CONSTCD11 +inline +year_month_weekday +operator/(const year_month& ym, const weekday_indexed& wdi) NOEXCEPT +{ + return {ym.year(), ym.month(), wdi}; +} + +CONSTCD11 +inline +year_month_weekday +operator/(const year& y, const month_weekday& mwd) NOEXCEPT +{ + return {y, mwd.month(), mwd.weekday_indexed()}; +} + +CONSTCD11 +inline +year_month_weekday +operator/(int y, const month_weekday& mwd) NOEXCEPT +{ + return year(y) / mwd; +} + +CONSTCD11 +inline +year_month_weekday +operator/(const month_weekday& mwd, const year& y) NOEXCEPT +{ + return y / mwd; +} + +CONSTCD11 +inline +year_month_weekday +operator/(const month_weekday& mwd, int y) NOEXCEPT +{ + return year(y) / mwd; +} + +// year_month_weekday_last from operator/() + +CONSTCD11 +inline +year_month_weekday_last +operator/(const year_month& ym, const weekday_last& wdl) NOEXCEPT +{ + return {ym.year(), ym.month(), wdl}; +} + +CONSTCD11 +inline +year_month_weekday_last +operator/(const year& y, const month_weekday_last& mwdl) NOEXCEPT +{ + return {y, mwdl.month(), mwdl.weekday_last()}; +} + +CONSTCD11 +inline +year_month_weekday_last +operator/(int y, const month_weekday_last& mwdl) NOEXCEPT +{ + return year(y) / mwdl; +} + +CONSTCD11 +inline +year_month_weekday_last +operator/(const month_weekday_last& mwdl, const year& y) NOEXCEPT +{ + return y / mwdl; +} + +CONSTCD11 +inline +year_month_weekday_last +operator/(const month_weekday_last& mwdl, int y) NOEXCEPT +{ + return year(y) / mwdl; +} + +template +struct fields; + +template +std::basic_ostream& +to_stream(std::basic_ostream& os, const CharT* fmt, + const fields& fds, const std::string* abbrev = nullptr, + const std::chrono::seconds* offset_sec = nullptr); + +template +std::basic_istream& +from_stream(std::basic_istream& is, const CharT* fmt, + fields& fds, std::basic_string* abbrev = nullptr, + std::chrono::minutes* offset = nullptr); + +// hh_mm_ss + +namespace detail +{ + +struct undocumented {explicit undocumented() = default;}; + +// width::value is the number of fractional decimal digits in 1/n +// width<0>::value and width<1>::value are defined to be 0 +// If 1/n takes more than 18 fractional decimal digits, +// the result is truncated to 19. +// Example: width<2>::value == 1 +// Example: width<3>::value == 19 +// Example: width<4>::value == 2 +// Example: width<10>::value == 1 +// Example: width<1000>::value == 3 +template +struct width +{ + static_assert(d > 0, "width called with zero denominator"); + static CONSTDATA unsigned value = 1 + width::value; +}; + +template +struct width +{ + static CONSTDATA unsigned value = 0; +}; + +template +struct static_pow10 +{ +private: + static CONSTDATA std::uint64_t h = static_pow10::value; +public: + static CONSTDATA std::uint64_t value = h * h * (exp % 2 ? 10 : 1); +}; + +template <> +struct static_pow10<0> +{ + static CONSTDATA std::uint64_t value = 1; +}; + +template +class decimal_format_seconds +{ + using CT = typename std::common_type::type; + using rep = typename CT::rep; + static unsigned CONSTDATA trial_width = + detail::width::value; +public: + static unsigned CONSTDATA width = trial_width < 19 ? trial_width : 6u; + using precision = std::chrono::duration::value>>; + +private: + std::chrono::seconds s_; + precision sub_s_; + +public: + CONSTCD11 decimal_format_seconds() + : s_() + , sub_s_() + {} + + CONSTCD11 explicit decimal_format_seconds(const Duration& d) NOEXCEPT + : s_(std::chrono::duration_cast(d)) + , sub_s_(std::chrono::duration_cast(d - s_)) + {} + + CONSTCD14 std::chrono::seconds& seconds() NOEXCEPT {return s_;} + CONSTCD11 std::chrono::seconds seconds() const NOEXCEPT {return s_;} + CONSTCD11 precision subseconds() const NOEXCEPT {return sub_s_;} + + CONSTCD14 precision to_duration() const NOEXCEPT + { + return s_ + sub_s_; + } + + CONSTCD11 bool in_conventional_range() const NOEXCEPT + { + return sub_s_ < std::chrono::seconds{1} && s_ < std::chrono::minutes{1}; + } + + template + friend + std::basic_ostream& + operator<<(std::basic_ostream& os, const decimal_format_seconds& x) + { + return x.print(os, std::chrono::treat_as_floating_point{}); + } + + template + std::basic_ostream& + print(std::basic_ostream& os, std::true_type) const + { + date::detail::save_ostream _(os); + std::chrono::duration d = s_ + sub_s_; + if (d < std::chrono::seconds{10}) + os << '0'; + os.precision(width+6); + os << std::fixed << d.count(); + return os; + } + + template + std::basic_ostream& + print(std::basic_ostream& os, std::false_type) const + { + date::detail::save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::right); + os.width(2); + os << s_.count(); + if (width > 0) + { +#if !ONLY_C_LOCALE + os << std::use_facet>(os.getloc()).decimal_point(); +#else + os << '.'; +#endif + date::detail::save_ostream _s(os); + os.imbue(std::locale::classic()); + os.width(width); + os << sub_s_.count(); + } + return os; + } +}; + +template +inline +CONSTCD11 +typename std::enable_if + < + std::numeric_limits::is_signed, + std::chrono::duration + >::type +abs(std::chrono::duration d) +{ + return d >= d.zero() ? +d : -d; +} + +template +inline +CONSTCD11 +typename std::enable_if + < + !std::numeric_limits::is_signed, + std::chrono::duration + >::type +abs(std::chrono::duration d) +{ + return d; +} + +} // namespace detail + +template +class hh_mm_ss +{ + using dfs = detail::decimal_format_seconds::type>; + + std::chrono::hours h_; + std::chrono::minutes m_; + dfs s_; + bool neg_; + +public: + static unsigned CONSTDATA fractional_width = dfs::width; + using precision = typename dfs::precision; + + CONSTCD11 hh_mm_ss() NOEXCEPT + : hh_mm_ss(Duration::zero()) + {} + + CONSTCD11 explicit hh_mm_ss(Duration d) NOEXCEPT + : h_(std::chrono::duration_cast(detail::abs(d))) + , m_(std::chrono::duration_cast(detail::abs(d)) - h_) + , s_(detail::abs(d) - h_ - m_) + , neg_(d < Duration::zero()) + {} + + CONSTCD11 std::chrono::hours hours() const NOEXCEPT {return h_;} + CONSTCD11 std::chrono::minutes minutes() const NOEXCEPT {return m_;} + CONSTCD11 std::chrono::seconds seconds() const NOEXCEPT {return s_.seconds();} + CONSTCD14 std::chrono::seconds& + seconds(detail::undocumented) NOEXCEPT {return s_.seconds();} + CONSTCD11 precision subseconds() const NOEXCEPT {return s_.subseconds();} + CONSTCD11 bool is_negative() const NOEXCEPT {return neg_;} + + CONSTCD11 explicit operator precision() const NOEXCEPT {return to_duration();} + CONSTCD11 precision to_duration() const NOEXCEPT + {return (s_.to_duration() + m_ + h_) * (1-2*neg_);} + + CONSTCD11 bool in_conventional_range() const NOEXCEPT + { + return !neg_ && h_ < days{1} && m_ < std::chrono::hours{1} && + s_.in_conventional_range(); + } + +private: + + template + friend + std::basic_ostream& + operator<<(std::basic_ostream& os, hh_mm_ss const& tod) + { + if (tod.is_negative()) + os << '-'; + if (tod.h_ < std::chrono::hours{10}) + os << '0'; + os << tod.h_.count() << ':'; + if (tod.m_ < std::chrono::minutes{10}) + os << '0'; + os << tod.m_.count() << ':' << tod.s_; + return os; + } + + template + friend + std::basic_ostream& + date::to_stream(std::basic_ostream& os, const CharT* fmt, + const fields& fds, const std::string* abbrev, + const std::chrono::seconds* offset_sec); + + template + friend + std::basic_istream& + date::from_stream(std::basic_istream& is, const CharT* fmt, + fields& fds, + std::basic_string* abbrev, std::chrono::minutes* offset); +}; + +inline +CONSTCD14 +bool +is_am(std::chrono::hours const& h) NOEXCEPT +{ + using std::chrono::hours; + return hours{0} <= h && h < hours{12}; +} + +inline +CONSTCD14 +bool +is_pm(std::chrono::hours const& h) NOEXCEPT +{ + using std::chrono::hours; + return hours{12} <= h && h < hours{24}; +} + +inline +CONSTCD14 +std::chrono::hours +make12(std::chrono::hours h) NOEXCEPT +{ + using std::chrono::hours; + if (h < hours{12}) + { + if (h == hours{0}) + h = hours{12}; + } + else + { + if (h != hours{12}) + h = h - hours{12}; + } + return h; +} + +inline +CONSTCD14 +std::chrono::hours +make24(std::chrono::hours h, bool is_pm) NOEXCEPT +{ + using std::chrono::hours; + if (is_pm) + { + if (h != hours{12}) + h = h + hours{12}; + } + else if (h == hours{12}) + h = hours{0}; + return h; +} + +template +using time_of_day = hh_mm_ss; + +template +CONSTCD11 +inline +hh_mm_ss> +make_time(const std::chrono::duration& d) +{ + return hh_mm_ss>(d); +} + +template +inline +typename std::enable_if +< + std::ratio_less::value + , std::basic_ostream& +>::type +operator<<(std::basic_ostream& os, const sys_time& tp) +{ + auto const dp = date::floor(tp); + return os << year_month_day(dp) << ' ' << make_time(tp-dp); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const sys_days& dp) +{ + return os << year_month_day(dp); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const local_time& ut) +{ + return (os << sys_time{ut.time_since_epoch()}); +} + +namespace detail +{ + +template +class string_literal; + +template +inline +CONSTCD14 +string_literal::type, + N1 + N2 - 1> +operator+(const string_literal& x, const string_literal& y) NOEXCEPT; + +template +class string_literal +{ + CharT p_[N]; + + CONSTCD11 string_literal() NOEXCEPT + : p_{} + {} + +public: + using const_iterator = const CharT*; + + string_literal(string_literal const&) = default; + string_literal& operator=(string_literal const&) = delete; + + template ::type> + CONSTCD11 string_literal(CharT c) NOEXCEPT + : p_{c} + { + } + + template ::type> + CONSTCD11 string_literal(CharT c1, CharT c2) NOEXCEPT + : p_{c1, c2} + { + } + + template ::type> + CONSTCD11 string_literal(CharT c1, CharT c2, CharT c3) NOEXCEPT + : p_{c1, c2, c3} + { + } + + CONSTCD14 string_literal(const CharT(&a)[N]) NOEXCEPT + : p_{} + { + for (std::size_t i = 0; i < N; ++i) + p_[i] = a[i]; + } + + template ::type> + CONSTCD14 string_literal(const char(&a)[N]) NOEXCEPT + : p_{} + { + for (std::size_t i = 0; i < N; ++i) + p_[i] = a[i]; + } + + template ::value>::type> + CONSTCD14 string_literal(string_literal const& a) NOEXCEPT + : p_{} + { + for (std::size_t i = 0; i < N; ++i) + p_[i] = a[i]; + } + + CONSTCD11 const CharT* data() const NOEXCEPT {return p_;} + CONSTCD11 std::size_t size() const NOEXCEPT {return N-1;} + + CONSTCD11 const_iterator begin() const NOEXCEPT {return p_;} + CONSTCD11 const_iterator end() const NOEXCEPT {return p_ + N-1;} + + CONSTCD11 CharT const& operator[](std::size_t n) const NOEXCEPT + { + return p_[n]; + } + + template + friend + std::basic_ostream& + operator<<(std::basic_ostream& os, const string_literal& s) + { + return os << s.p_; + } + + template + friend + CONSTCD14 + string_literal::type, + N1 + N2 - 1> + operator+(const string_literal& x, const string_literal& y) NOEXCEPT; +}; + +template +CONSTCD11 +inline +string_literal +operator+(const string_literal& x, const string_literal& y) NOEXCEPT +{ + return string_literal(x[0], y[0]); +} + +template +CONSTCD11 +inline +string_literal +operator+(const string_literal& x, const string_literal& y) NOEXCEPT +{ + return string_literal(x[0], x[1], y[0]); +} + +template +CONSTCD14 +inline +string_literal::type, + N1 + N2 - 1> +operator+(const string_literal& x, const string_literal& y) NOEXCEPT +{ + using CT = typename std::conditional::type; + + string_literal r; + std::size_t i = 0; + for (; i < N1-1; ++i) + r.p_[i] = CT(x.p_[i]); + for (std::size_t j = 0; j < N2; ++j, ++i) + r.p_[i] = CT(y.p_[j]); + + return r; +} + + +template +inline +std::basic_string +operator+(std::basic_string x, const string_literal& y) +{ + x.append(y.data(), y.size()); + return x; +} + +#if __cplusplus >= 201402 && (!defined(__EDG_VERSION__) || __EDG_VERSION__ > 411) \ + && (!defined(__SUNPRO_CC) || __SUNPRO_CC > 0x5150) + +template ::value || + std::is_same::value || + std::is_same::value || + std::is_same::value>> +CONSTCD14 +inline +string_literal +msl(CharT c) NOEXCEPT +{ + return string_literal{c}; +} + +CONSTCD14 +inline +std::size_t +to_string_len(std::intmax_t i) +{ + std::size_t r = 0; + do + { + i /= 10; + ++r; + } while (i > 0); + return r; +} + +template +CONSTCD14 +inline +std::enable_if_t +< + N < 10, + string_literal +> +msl() NOEXCEPT +{ + return msl(char(N % 10 + '0')); +} + +template +CONSTCD14 +inline +std::enable_if_t +< + 10 <= N, + string_literal +> +msl() NOEXCEPT +{ + return msl() + msl(char(N % 10 + '0')); +} + +template +CONSTCD14 +inline +std::enable_if_t +< + std::ratio::type::den != 1, + string_literal::type::num) + + to_string_len(std::ratio::type::den) + 4> +> +msl(std::ratio) NOEXCEPT +{ + using R = typename std::ratio::type; + return msl(CharT{'['}) + msl() + msl(CharT{'/'}) + + msl() + msl(CharT{']'}); +} + +template +CONSTCD14 +inline +std::enable_if_t +< + std::ratio::type::den == 1, + string_literal::type::num) + 3> +> +msl(std::ratio) NOEXCEPT +{ + using R = typename std::ratio::type; + return msl(CharT{'['}) + msl() + msl(CharT{']'}); +} + + +#else // __cplusplus < 201402 || (defined(__EDG_VERSION__) && __EDG_VERSION__ <= 411) + +inline +std::string +to_string(std::uint64_t x) +{ + return std::to_string(x); +} + +template +inline +std::basic_string +to_string(std::uint64_t x) +{ + auto y = std::to_string(x); + return std::basic_string(y.begin(), y.end()); +} + +template +inline +typename std::enable_if +< + std::ratio::type::den != 1, + std::basic_string +>::type +msl(std::ratio) +{ + using R = typename std::ratio::type; + return std::basic_string(1, '[') + to_string(R::num) + CharT{'/'} + + to_string(R::den) + CharT{']'}; +} + +template +inline +typename std::enable_if +< + std::ratio::type::den == 1, + std::basic_string +>::type +msl(std::ratio) +{ + using R = typename std::ratio::type; + return std::basic_string(1, '[') + to_string(R::num) + CharT{']'}; +} + +#endif // __cplusplus < 201402 || (defined(__EDG_VERSION__) && __EDG_VERSION__ <= 411) + +template +CONSTCD11 +inline +string_literal +msl(std::atto) NOEXCEPT +{ + return string_literal{'a'}; +} + +template +CONSTCD11 +inline +string_literal +msl(std::femto) NOEXCEPT +{ + return string_literal{'f'}; +} + +template +CONSTCD11 +inline +string_literal +msl(std::pico) NOEXCEPT +{ + return string_literal{'p'}; +} + +template +CONSTCD11 +inline +string_literal +msl(std::nano) NOEXCEPT +{ + return string_literal{'n'}; +} + +template +CONSTCD11 +inline +typename std::enable_if +< + std::is_same::value, + string_literal +>::type +msl(std::micro) NOEXCEPT +{ + return string_literal{'\xC2', '\xB5'}; +} + +template +CONSTCD11 +inline +typename std::enable_if +< + !std::is_same::value, + string_literal +>::type +msl(std::micro) NOEXCEPT +{ + return string_literal{CharT{static_cast('\xB5')}}; +} + +template +CONSTCD11 +inline +string_literal +msl(std::milli) NOEXCEPT +{ + return string_literal{'m'}; +} + +template +CONSTCD11 +inline +string_literal +msl(std::centi) NOEXCEPT +{ + return string_literal{'c'}; +} + +template +CONSTCD11 +inline +string_literal +msl(std::deca) NOEXCEPT +{ + return string_literal{'d', 'a'}; +} + +template +CONSTCD11 +inline +string_literal +msl(std::deci) NOEXCEPT +{ + return string_literal{'d'}; +} + +template +CONSTCD11 +inline +string_literal +msl(std::hecto) NOEXCEPT +{ + return string_literal{'h'}; +} + +template +CONSTCD11 +inline +string_literal +msl(std::kilo) NOEXCEPT +{ + return string_literal{'k'}; +} + +template +CONSTCD11 +inline +string_literal +msl(std::mega) NOEXCEPT +{ + return string_literal{'M'}; +} + +template +CONSTCD11 +inline +string_literal +msl(std::giga) NOEXCEPT +{ + return string_literal{'G'}; +} + +template +CONSTCD11 +inline +string_literal +msl(std::tera) NOEXCEPT +{ + return string_literal{'T'}; +} + +template +CONSTCD11 +inline +string_literal +msl(std::peta) NOEXCEPT +{ + return string_literal{'P'}; +} + +template +CONSTCD11 +inline +string_literal +msl(std::exa) NOEXCEPT +{ + return string_literal{'E'}; +} + +template +CONSTCD11 +inline +auto +get_units(Period p) + -> decltype(msl(p) + string_literal{'s'}) +{ + return msl(p) + string_literal{'s'}; +} + +template +CONSTCD11 +inline +string_literal +get_units(std::ratio<1>) +{ + return string_literal{'s'}; +} + +template +CONSTCD11 +inline +string_literal +get_units(std::ratio<3600>) +{ + return string_literal{'h'}; +} + +template +CONSTCD11 +inline +string_literal +get_units(std::ratio<60>) +{ + return string_literal{'m', 'i', 'n'}; +} + +template +CONSTCD11 +inline +string_literal +get_units(std::ratio<86400>) +{ + return string_literal{'d'}; +} + +template > +struct make_string; + +template <> +struct make_string +{ + template + static + std::string + from(Rep n) + { + return std::to_string(n); + } +}; + +template +struct make_string +{ + template + static + std::basic_string + from(Rep n) + { + auto s = std::to_string(n); + return std::basic_string(s.begin(), s.end()); + } +}; + +template <> +struct make_string +{ + template + static + std::wstring + from(Rep n) + { + return std::to_wstring(n); + } +}; + +template +struct make_string +{ + template + static + std::basic_string + from(Rep n) + { + auto s = std::to_wstring(n); + return std::basic_string(s.begin(), s.end()); + } +}; + +} // namespace detail + +// to_stream + +CONSTDATA year nanyear{-32768}; + +template +struct fields +{ + year_month_day ymd{nanyear/0/0}; + weekday wd{8u}; + hh_mm_ss tod{}; + bool has_tod = false; + + fields() = default; + + fields(year_month_day ymd_) : ymd(ymd_) {} + fields(weekday wd_) : wd(wd_) {} + fields(hh_mm_ss tod_) : tod(tod_), has_tod(true) {} + + fields(year_month_day ymd_, weekday wd_) : ymd(ymd_), wd(wd_) {} + fields(year_month_day ymd_, hh_mm_ss tod_) : ymd(ymd_), tod(tod_), + has_tod(true) {} + + fields(weekday wd_, hh_mm_ss tod_) : wd(wd_), tod(tod_), has_tod(true) {} + + fields(year_month_day ymd_, weekday wd_, hh_mm_ss tod_) + : ymd(ymd_) + , wd(wd_) + , tod(tod_) + , has_tod(true) + {} +}; + +namespace detail +{ + +template +unsigned +extract_weekday(std::basic_ostream& os, const fields& fds) +{ + if (!fds.ymd.ok() && !fds.wd.ok()) + { + // fds does not contain a valid weekday + os.setstate(std::ios::failbit); + return 8; + } + weekday wd; + if (fds.ymd.ok()) + { + wd = weekday{sys_days(fds.ymd)}; + if (fds.wd.ok() && wd != fds.wd) + { + // fds.ymd and fds.wd are inconsistent + os.setstate(std::ios::failbit); + return 8; + } + } + else + wd = fds.wd; + return static_cast((wd - Sunday).count()); +} + +template +unsigned +extract_month(std::basic_ostream& os, const fields& fds) +{ + if (!fds.ymd.month().ok()) + { + // fds does not contain a valid month + os.setstate(std::ios::failbit); + return 0; + } + return static_cast(fds.ymd.month()); +} + +} // namespace detail + +#if ONLY_C_LOCALE + +namespace detail +{ + +inline +std::pair +weekday_names() +{ + static const std::string nm[] = + { + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sun", + "Mon", + "Tue", + "Wed", + "Thu", + "Fri", + "Sat" + }; + return std::make_pair(nm, nm+sizeof(nm)/sizeof(nm[0])); +} + +inline +std::pair +month_names() +{ + static const std::string nm[] = + { + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" + }; + return std::make_pair(nm, nm+sizeof(nm)/sizeof(nm[0])); +} + +inline +std::pair +ampm_names() +{ + static const std::string nm[] = + { + "AM", + "PM" + }; + return std::make_pair(nm, nm+sizeof(nm)/sizeof(nm[0])); +} + +template +FwdIter +scan_keyword(std::basic_istream& is, FwdIter kb, FwdIter ke) +{ + size_t nkw = static_cast(std::distance(kb, ke)); + const unsigned char doesnt_match = '\0'; + const unsigned char might_match = '\1'; + const unsigned char does_match = '\2'; + unsigned char statbuf[100]; + unsigned char* status = statbuf; + std::unique_ptr stat_hold(0, free); + if (nkw > sizeof(statbuf)) + { + status = (unsigned char*)std::malloc(nkw); + if (status == nullptr) + throw std::bad_alloc(); + stat_hold.reset(status); + } + size_t n_might_match = nkw; // At this point, any keyword might match + size_t n_does_match = 0; // but none of them definitely do + // Initialize all statuses to might_match, except for "" keywords are does_match + unsigned char* st = status; + for (auto ky = kb; ky != ke; ++ky, ++st) + { + if (!ky->empty()) + *st = might_match; + else + { + *st = does_match; + --n_might_match; + ++n_does_match; + } + } + // While there might be a match, test keywords against the next CharT + for (size_t indx = 0; is && n_might_match > 0; ++indx) + { + // Peek at the next CharT but don't consume it + auto ic = is.peek(); + if (ic == EOF) + { + is.setstate(std::ios::eofbit); + break; + } + auto c = static_cast(toupper(static_cast(ic))); + bool consume = false; + // For each keyword which might match, see if the indx character is c + // If a match if found, consume c + // If a match is found, and that is the last character in the keyword, + // then that keyword matches. + // If the keyword doesn't match this character, then change the keyword + // to doesn't match + st = status; + for (auto ky = kb; ky != ke; ++ky, ++st) + { + if (*st == might_match) + { + if (c == static_cast(toupper(static_cast((*ky)[indx])))) + { + consume = true; + if (ky->size() == indx+1) + { + *st = does_match; + --n_might_match; + ++n_does_match; + } + } + else + { + *st = doesnt_match; + --n_might_match; + } + } + } + // consume if we matched a character + if (consume) + { + (void)is.get(); + // If we consumed a character and there might be a matched keyword that + // was marked matched on a previous iteration, then such keywords + // are now marked as not matching. + if (n_might_match + n_does_match > 1) + { + st = status; + for (auto ky = kb; ky != ke; ++ky, ++st) + { + if (*st == does_match && ky->size() != indx+1) + { + *st = doesnt_match; + --n_does_match; + } + } + } + } + } + // We've exited the loop because we hit eof and/or we have no more "might matches". + // Return the first matching result + for (st = status; kb != ke; ++kb, ++st) + if (*st == does_match) + break; + if (kb == ke) + is.setstate(std::ios::failbit); + return kb; +} + +} // namespace detail + +#endif // ONLY_C_LOCALE + +template +std::basic_ostream& +to_stream(std::basic_ostream& os, const CharT* fmt, + const fields& fds, const std::string* abbrev, + const std::chrono::seconds* offset_sec) +{ +#if ONLY_C_LOCALE + using detail::weekday_names; + using detail::month_names; + using detail::ampm_names; +#endif + using detail::save_ostream; + using detail::get_units; + using detail::extract_weekday; + using detail::extract_month; + using std::ios; + using std::chrono::duration_cast; + using std::chrono::seconds; + using std::chrono::minutes; + using std::chrono::hours; + date::detail::save_ostream ss(os); + os.fill(' '); + os.flags(std::ios::skipws | std::ios::dec); + os.width(0); + tm tm{}; + bool insert_negative = fds.has_tod && fds.tod.to_duration() < Duration::zero(); +#if !ONLY_C_LOCALE + auto& facet = std::use_facet>(os.getloc()); +#endif + const CharT* command = nullptr; + CharT modified = CharT{}; + for (; *fmt; ++fmt) + { + switch (*fmt) + { + case 'a': + case 'A': + if (command) + { + if (modified == CharT{}) + { + tm.tm_wday = static_cast(extract_weekday(os, fds)); + if (os.fail()) + return os; +#if !ONLY_C_LOCALE + const CharT f[] = {'%', *fmt}; + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); +#else // ONLY_C_LOCALE + os << weekday_names().first[tm.tm_wday+7*(*fmt == 'a')]; +#endif // ONLY_C_LOCALE + } + else + { + os << CharT{'%'} << modified << *fmt; + modified = CharT{}; + } + command = nullptr; + } + else + os << *fmt; + break; + case 'b': + case 'B': + case 'h': + if (command) + { + if (modified == CharT{}) + { + tm.tm_mon = static_cast(extract_month(os, fds)) - 1; +#if !ONLY_C_LOCALE + const CharT f[] = {'%', *fmt}; + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); +#else // ONLY_C_LOCALE + os << month_names().first[tm.tm_mon+12*(*fmt != 'B')]; +#endif // ONLY_C_LOCALE + } + else + { + os << CharT{'%'} << modified << *fmt; + modified = CharT{}; + } + command = nullptr; + } + else + os << *fmt; + break; + case 'c': + case 'x': + if (command) + { + if (modified == CharT{'O'}) + os << CharT{'%'} << modified << *fmt; + else + { + if (!fds.ymd.ok()) + os.setstate(std::ios::failbit); + if (*fmt == 'c' && !fds.has_tod) + os.setstate(std::ios::failbit); +#if !ONLY_C_LOCALE + tm = std::tm{}; + auto const& ymd = fds.ymd; + auto ld = local_days(ymd); + if (*fmt == 'c') + { + tm.tm_sec = static_cast(fds.tod.seconds().count()); + tm.tm_min = static_cast(fds.tod.minutes().count()); + tm.tm_hour = static_cast(fds.tod.hours().count()); + } + tm.tm_mday = static_cast(static_cast(ymd.day())); + tm.tm_mon = static_cast(extract_month(os, fds) - 1); + tm.tm_year = static_cast(ymd.year()) - 1900; + tm.tm_wday = static_cast(extract_weekday(os, fds)); + if (os.fail()) + return os; + tm.tm_yday = static_cast((ld - local_days(ymd.year()/1/1)).count()); + CharT f[3] = {'%'}; + auto fe = std::begin(f) + 1; + if (modified == CharT{'E'}) + *fe++ = modified; + *fe++ = *fmt; + facet.put(os, os, os.fill(), &tm, std::begin(f), fe); +#else // ONLY_C_LOCALE + if (*fmt == 'c') + { + auto wd = static_cast(extract_weekday(os, fds)); + os << weekday_names().first[static_cast(wd)+7] + << ' '; + os << month_names().first[extract_month(os, fds)-1+12] << ' '; + auto d = static_cast(static_cast(fds.ymd.day())); + if (d < 10) + os << ' '; + os << d << ' ' + << make_time(duration_cast(fds.tod.to_duration())) + << ' ' << fds.ymd.year(); + + } + else // *fmt == 'x' + { + auto const& ymd = fds.ymd; + save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::right); + os.width(2); + os << static_cast(ymd.month()) << CharT{'/'}; + os.width(2); + os << static_cast(ymd.day()) << CharT{'/'}; + os.width(2); + os << static_cast(ymd.year()) % 100; + } +#endif // ONLY_C_LOCALE + } + command = nullptr; + modified = CharT{}; + } + else + os << *fmt; + break; + case 'C': + if (command) + { + if (modified == CharT{'O'}) + os << CharT{'%'} << modified << *fmt; + else + { + if (!fds.ymd.year().ok()) + os.setstate(std::ios::failbit); + auto y = static_cast(fds.ymd.year()); +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#endif + { + save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::right); + if (y >= 0) + { + os.width(2); + os << y/100; + } + else + { + os << CharT{'-'}; + os.width(2); + os << -(y-99)/100; + } + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'E'}) + { + tm.tm_year = y - 1900; + CharT f[3] = {'%', 'E', 'C'}; + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); + } +#endif + } + command = nullptr; + modified = CharT{}; + } + else + os << *fmt; + break; + case 'd': + case 'e': + if (command) + { + if (modified == CharT{'E'}) + os << CharT{'%'} << modified << *fmt; + else + { + if (!fds.ymd.day().ok()) + os.setstate(std::ios::failbit); + auto d = static_cast(static_cast(fds.ymd.day())); +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#endif + { + save_ostream _(os); + if (*fmt == CharT{'d'}) + os.fill('0'); + else + os.fill(' '); + os.flags(std::ios::dec | std::ios::right); + os.width(2); + os << d; + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'O'}) + { + tm.tm_mday = d; + CharT f[3] = {'%', 'O', *fmt}; + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); + } +#endif + } + command = nullptr; + modified = CharT{}; + } + else + os << *fmt; + break; + case 'D': + if (command) + { + if (modified == CharT{}) + { + if (!fds.ymd.ok()) + os.setstate(std::ios::failbit); + auto const& ymd = fds.ymd; + save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::right); + os.width(2); + os << static_cast(ymd.month()) << CharT{'/'}; + os.width(2); + os << static_cast(ymd.day()) << CharT{'/'}; + os.width(2); + os << static_cast(ymd.year()) % 100; + } + else + { + os << CharT{'%'} << modified << *fmt; + modified = CharT{}; + } + command = nullptr; + } + else + os << *fmt; + break; + case 'F': + if (command) + { + if (modified == CharT{}) + { + if (!fds.ymd.ok()) + os.setstate(std::ios::failbit); + auto const& ymd = fds.ymd; + save_ostream _(os); + os.imbue(std::locale::classic()); + os.fill('0'); + os.flags(std::ios::dec | std::ios::right); + os.width(4); + os << static_cast(ymd.year()) << CharT{'-'}; + os.width(2); + os << static_cast(ymd.month()) << CharT{'-'}; + os.width(2); + os << static_cast(ymd.day()); + } + else + { + os << CharT{'%'} << modified << *fmt; + modified = CharT{}; + } + command = nullptr; + } + else + os << *fmt; + break; + case 'g': + case 'G': + if (command) + { + if (modified == CharT{}) + { + if (!fds.ymd.ok()) + os.setstate(std::ios::failbit); + auto ld = local_days(fds.ymd); + auto y = year_month_day{ld + days{3}}.year(); + auto start = local_days((y-years{1})/December/Thursday[last]) + + (Monday-Thursday); + if (ld < start) + --y; + if (*fmt == CharT{'G'}) + os << y; + else + { + save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::right); + os.width(2); + os << std::abs(static_cast(y)) % 100; + } + } + else + { + os << CharT{'%'} << modified << *fmt; + modified = CharT{}; + } + command = nullptr; + } + else + os << *fmt; + break; + case 'H': + case 'I': + if (command) + { + if (modified == CharT{'E'}) + os << CharT{'%'} << modified << *fmt; + else + { + if (!fds.has_tod) + os.setstate(std::ios::failbit); + if (insert_negative) + { + os << '-'; + insert_negative = false; + } + auto hms = fds.tod; +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#endif + { + auto h = *fmt == CharT{'I'} ? date::make12(hms.hours()) : hms.hours(); + if (h < hours{10}) + os << CharT{'0'}; + os << h.count(); + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'O'}) + { + const CharT f[] = {'%', modified, *fmt}; + tm.tm_hour = static_cast(hms.hours().count()); + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); + } +#endif + } + modified = CharT{}; + command = nullptr; + } + else + os << *fmt; + break; + case 'j': + if (command) + { + if (modified == CharT{}) + { + if (fds.ymd.ok() || fds.has_tod) + { + days doy; + if (fds.ymd.ok()) + { + auto ld = local_days(fds.ymd); + auto y = fds.ymd.year(); + doy = ld - local_days(y/January/1) + days{1}; + } + else + { + doy = duration_cast(fds.tod.to_duration()); + } + save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::right); + os.width(3); + os << doy.count(); + } + else + { + os.setstate(std::ios::failbit); + } + } + else + { + os << CharT{'%'} << modified << *fmt; + modified = CharT{}; + } + command = nullptr; + } + else + os << *fmt; + break; + case 'm': + if (command) + { + if (modified == CharT{'E'}) + os << CharT{'%'} << modified << *fmt; + else + { + if (!fds.ymd.month().ok()) + os.setstate(std::ios::failbit); + auto m = static_cast(fds.ymd.month()); +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#endif + { + if (m < 10) + os << CharT{'0'}; + os << m; + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'O'}) + { + const CharT f[] = {'%', modified, *fmt}; + tm.tm_mon = static_cast(m-1); + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); + } +#endif + } + modified = CharT{}; + command = nullptr; + } + else + os << *fmt; + break; + case 'M': + if (command) + { + if (modified == CharT{'E'}) + os << CharT{'%'} << modified << *fmt; + else + { + if (!fds.has_tod) + os.setstate(std::ios::failbit); + if (insert_negative) + { + os << '-'; + insert_negative = false; + } +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#endif + { + if (fds.tod.minutes() < minutes{10}) + os << CharT{'0'}; + os << fds.tod.minutes().count(); + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'O'}) + { + const CharT f[] = {'%', modified, *fmt}; + tm.tm_min = static_cast(fds.tod.minutes().count()); + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); + } +#endif + } + modified = CharT{}; + command = nullptr; + } + else + os << *fmt; + break; + case 'n': + if (command) + { + if (modified == CharT{}) + os << CharT{'\n'}; + else + { + os << CharT{'%'} << modified << *fmt; + modified = CharT{}; + } + command = nullptr; + } + else + os << *fmt; + break; + case 'p': + if (command) + { + if (modified == CharT{}) + { + if (!fds.has_tod) + os.setstate(std::ios::failbit); +#if !ONLY_C_LOCALE + const CharT f[] = {'%', *fmt}; + tm.tm_hour = static_cast(fds.tod.hours().count()); + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); +#else + if (date::is_am(fds.tod.hours())) + os << ampm_names().first[0]; + else + os << ampm_names().first[1]; +#endif + } + else + { + os << CharT{'%'} << modified << *fmt; + } + modified = CharT{}; + command = nullptr; + } + else + os << *fmt; + break; + case 'Q': + case 'q': + if (command) + { + if (modified == CharT{}) + { + if (!fds.has_tod) + os.setstate(std::ios::failbit); + auto d = fds.tod.to_duration(); + if (*fmt == 'q') + os << get_units(typename decltype(d)::period::type{}); + else + os << d.count(); + } + else + { + os << CharT{'%'} << modified << *fmt; + } + modified = CharT{}; + command = nullptr; + } + else + os << *fmt; + break; + case 'r': + if (command) + { + if (modified == CharT{}) + { + if (!fds.has_tod) + os.setstate(std::ios::failbit); +#if !ONLY_C_LOCALE + const CharT f[] = {'%', *fmt}; + tm.tm_hour = static_cast(fds.tod.hours().count()); + tm.tm_min = static_cast(fds.tod.minutes().count()); + tm.tm_sec = static_cast(fds.tod.seconds().count()); + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); +#else + hh_mm_ss tod(duration_cast(fds.tod.to_duration())); + save_ostream _(os); + os.fill('0'); + os.width(2); + os << date::make12(tod.hours()).count() << CharT{':'}; + os.width(2); + os << tod.minutes().count() << CharT{':'}; + os.width(2); + os << tod.seconds().count() << CharT{' '}; + if (date::is_am(tod.hours())) + os << ampm_names().first[0]; + else + os << ampm_names().first[1]; +#endif + } + else + { + os << CharT{'%'} << modified << *fmt; + } + modified = CharT{}; + command = nullptr; + } + else + os << *fmt; + break; + case 'R': + if (command) + { + if (modified == CharT{}) + { + if (!fds.has_tod) + os.setstate(std::ios::failbit); + if (fds.tod.hours() < hours{10}) + os << CharT{'0'}; + os << fds.tod.hours().count() << CharT{':'}; + if (fds.tod.minutes() < minutes{10}) + os << CharT{'0'}; + os << fds.tod.minutes().count(); + } + else + { + os << CharT{'%'} << modified << *fmt; + modified = CharT{}; + } + command = nullptr; + } + else + os << *fmt; + break; + case 'S': + if (command) + { + if (modified == CharT{'E'}) + os << CharT{'%'} << modified << *fmt; + else + { + if (!fds.has_tod) + os.setstate(std::ios::failbit); + if (insert_negative) + { + os << '-'; + insert_negative = false; + } +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#endif + { + os << fds.tod.s_; + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'O'}) + { + const CharT f[] = {'%', modified, *fmt}; + tm.tm_sec = static_cast(fds.tod.s_.seconds().count()); + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); + } +#endif + } + modified = CharT{}; + command = nullptr; + } + else + os << *fmt; + break; + case 't': + if (command) + { + if (modified == CharT{}) + os << CharT{'\t'}; + else + { + os << CharT{'%'} << modified << *fmt; + modified = CharT{}; + } + command = nullptr; + } + else + os << *fmt; + break; + case 'T': + if (command) + { + if (modified == CharT{}) + { + if (!fds.has_tod) + os.setstate(std::ios::failbit); + os << fds.tod; + } + else + { + os << CharT{'%'} << modified << *fmt; + modified = CharT{}; + } + command = nullptr; + } + else + os << *fmt; + break; + case 'u': + if (command) + { + if (modified == CharT{'E'}) + os << CharT{'%'} << modified << *fmt; + else + { + auto wd = extract_weekday(os, fds); +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#endif + { + os << (wd != 0 ? wd : 7u); + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'O'}) + { + const CharT f[] = {'%', modified, *fmt}; + tm.tm_wday = static_cast(wd); + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); + } +#endif + } + modified = CharT{}; + command = nullptr; + } + else + os << *fmt; + break; + case 'U': + if (command) + { + if (modified == CharT{'E'}) + os << CharT{'%'} << modified << *fmt; + else + { + auto const& ymd = fds.ymd; + if (!ymd.ok()) + os.setstate(std::ios::failbit); + auto ld = local_days(ymd); +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#endif + { + auto st = local_days(Sunday[1]/January/ymd.year()); + if (ld < st) + os << CharT{'0'} << CharT{'0'}; + else + { + auto wn = duration_cast(ld - st).count() + 1; + if (wn < 10) + os << CharT{'0'}; + os << wn; + } + } + #if !ONLY_C_LOCALE + else if (modified == CharT{'O'}) + { + const CharT f[] = {'%', modified, *fmt}; + tm.tm_year = static_cast(ymd.year()) - 1900; + tm.tm_wday = static_cast(extract_weekday(os, fds)); + if (os.fail()) + return os; + tm.tm_yday = static_cast((ld - local_days(ymd.year()/1/1)).count()); + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); + } +#endif + } + modified = CharT{}; + command = nullptr; + } + else + os << *fmt; + break; + case 'V': + if (command) + { + if (modified == CharT{'E'}) + os << CharT{'%'} << modified << *fmt; + else + { + if (!fds.ymd.ok()) + os.setstate(std::ios::failbit); + auto ld = local_days(fds.ymd); +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#endif + { + auto y = year_month_day{ld + days{3}}.year(); + auto st = local_days((y-years{1})/12/Thursday[last]) + + (Monday-Thursday); + if (ld < st) + { + --y; + st = local_days((y - years{1})/12/Thursday[last]) + + (Monday-Thursday); + } + auto wn = duration_cast(ld - st).count() + 1; + if (wn < 10) + os << CharT{'0'}; + os << wn; + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'O'}) + { + const CharT f[] = {'%', modified, *fmt}; + auto const& ymd = fds.ymd; + tm.tm_year = static_cast(ymd.year()) - 1900; + tm.tm_wday = static_cast(extract_weekday(os, fds)); + if (os.fail()) + return os; + tm.tm_yday = static_cast((ld - local_days(ymd.year()/1/1)).count()); + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); + } +#endif + } + modified = CharT{}; + command = nullptr; + } + else + os << *fmt; + break; + case 'w': + if (command) + { + auto wd = extract_weekday(os, fds); + if (os.fail()) + return os; +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#else + if (modified != CharT{'E'}) +#endif + { + os << wd; + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'O'}) + { + const CharT f[] = {'%', modified, *fmt}; + tm.tm_wday = static_cast(wd); + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); + } +#endif + else + { + os << CharT{'%'} << modified << *fmt; + } + modified = CharT{}; + command = nullptr; + } + else + os << *fmt; + break; + case 'W': + if (command) + { + if (modified == CharT{'E'}) + os << CharT{'%'} << modified << *fmt; + else + { + auto const& ymd = fds.ymd; + if (!ymd.ok()) + os.setstate(std::ios::failbit); + auto ld = local_days(ymd); +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#endif + { + auto st = local_days(Monday[1]/January/ymd.year()); + if (ld < st) + os << CharT{'0'} << CharT{'0'}; + else + { + auto wn = duration_cast(ld - st).count() + 1; + if (wn < 10) + os << CharT{'0'}; + os << wn; + } + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'O'}) + { + const CharT f[] = {'%', modified, *fmt}; + tm.tm_year = static_cast(ymd.year()) - 1900; + tm.tm_wday = static_cast(extract_weekday(os, fds)); + if (os.fail()) + return os; + tm.tm_yday = static_cast((ld - local_days(ymd.year()/1/1)).count()); + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); + } +#endif + } + modified = CharT{}; + command = nullptr; + } + else + os << *fmt; + break; + case 'X': + if (command) + { + if (modified == CharT{'O'}) + os << CharT{'%'} << modified << *fmt; + else + { + if (!fds.has_tod) + os.setstate(std::ios::failbit); +#if !ONLY_C_LOCALE + tm = std::tm{}; + tm.tm_sec = static_cast(fds.tod.seconds().count()); + tm.tm_min = static_cast(fds.tod.minutes().count()); + tm.tm_hour = static_cast(fds.tod.hours().count()); + CharT f[3] = {'%'}; + auto fe = std::begin(f) + 1; + if (modified == CharT{'E'}) + *fe++ = modified; + *fe++ = *fmt; + facet.put(os, os, os.fill(), &tm, std::begin(f), fe); +#else + os << fds.tod; +#endif + } + command = nullptr; + modified = CharT{}; + } + else + os << *fmt; + break; + case 'y': + if (command) + { + if (!fds.ymd.year().ok()) + os.setstate(std::ios::failbit); + auto y = static_cast(fds.ymd.year()); +#if !ONLY_C_LOCALE + if (modified == CharT{}) + { +#endif + y = std::abs(y) % 100; + if (y < 10) + os << CharT{'0'}; + os << y; +#if !ONLY_C_LOCALE + } + else + { + const CharT f[] = {'%', modified, *fmt}; + tm.tm_year = y - 1900; + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); + } +#endif + modified = CharT{}; + command = nullptr; + } + else + os << *fmt; + break; + case 'Y': + if (command) + { + if (modified == CharT{'O'}) + os << CharT{'%'} << modified << *fmt; + else + { + if (!fds.ymd.year().ok()) + os.setstate(std::ios::failbit); + auto y = fds.ymd.year(); +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#endif + { + save_ostream _(os); + os.imbue(std::locale::classic()); + os << y; + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'E'}) + { + const CharT f[] = {'%', modified, *fmt}; + tm.tm_year = static_cast(y) - 1900; + facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); + } +#endif + } + modified = CharT{}; + command = nullptr; + } + else + os << *fmt; + break; + case 'z': + if (command) + { + if (offset_sec == nullptr) + { + // Can not format %z with unknown offset + os.setstate(ios::failbit); + return os; + } + auto m = duration_cast(*offset_sec); + auto neg = m < minutes{0}; + m = date::abs(m); + auto h = duration_cast(m); + m -= h; + if (neg) + os << CharT{'-'}; + else + os << CharT{'+'}; + if (h < hours{10}) + os << CharT{'0'}; + os << h.count(); + if (modified != CharT{}) + os << CharT{':'}; + if (m < minutes{10}) + os << CharT{'0'}; + os << m.count(); + command = nullptr; + modified = CharT{}; + } + else + os << *fmt; + break; + case 'Z': + if (command) + { + if (modified == CharT{}) + { + if (abbrev == nullptr) + { + // Can not format %Z with unknown time_zone + os.setstate(ios::failbit); + return os; + } + for (auto c : *abbrev) + os << CharT(c); + } + else + { + os << CharT{'%'} << modified << *fmt; + modified = CharT{}; + } + command = nullptr; + } + else + os << *fmt; + break; + case 'E': + case 'O': + if (command) + { + if (modified == CharT{}) + { + modified = *fmt; + } + else + { + os << CharT{'%'} << modified << *fmt; + command = nullptr; + modified = CharT{}; + } + } + else + os << *fmt; + break; + case '%': + if (command) + { + if (modified == CharT{}) + { + os << CharT{'%'}; + command = nullptr; + } + else + { + os << CharT{'%'} << modified << CharT{'%'}; + command = nullptr; + modified = CharT{}; + } + } + else + command = fmt; + break; + default: + if (command) + { + os << CharT{'%'}; + command = nullptr; + } + if (modified != CharT{}) + { + os << modified; + modified = CharT{}; + } + os << *fmt; + break; + } + } + if (command) + os << CharT{'%'}; + if (modified != CharT{}) + os << modified; + return os; +} + +template +inline +std::basic_ostream& +to_stream(std::basic_ostream& os, const CharT* fmt, const year& y) +{ + using CT = std::chrono::seconds; + fields fds{y/0/0}; + return to_stream(os, fmt, fds); +} + +template +inline +std::basic_ostream& +to_stream(std::basic_ostream& os, const CharT* fmt, const month& m) +{ + using CT = std::chrono::seconds; + fields fds{m/0/nanyear}; + return to_stream(os, fmt, fds); +} + +template +inline +std::basic_ostream& +to_stream(std::basic_ostream& os, const CharT* fmt, const day& d) +{ + using CT = std::chrono::seconds; + fields fds{d/0/nanyear}; + return to_stream(os, fmt, fds); +} + +template +inline +std::basic_ostream& +to_stream(std::basic_ostream& os, const CharT* fmt, const weekday& wd) +{ + using CT = std::chrono::seconds; + fields fds{wd}; + return to_stream(os, fmt, fds); +} + +template +inline +std::basic_ostream& +to_stream(std::basic_ostream& os, const CharT* fmt, const year_month& ym) +{ + using CT = std::chrono::seconds; + fields fds{ym/0}; + return to_stream(os, fmt, fds); +} + +template +inline +std::basic_ostream& +to_stream(std::basic_ostream& os, const CharT* fmt, const month_day& md) +{ + using CT = std::chrono::seconds; + fields fds{md/nanyear}; + return to_stream(os, fmt, fds); +} + +template +inline +std::basic_ostream& +to_stream(std::basic_ostream& os, const CharT* fmt, + const year_month_day& ymd) +{ + using CT = std::chrono::seconds; + fields fds{ymd}; + return to_stream(os, fmt, fds); +} + +template +inline +std::basic_ostream& +to_stream(std::basic_ostream& os, const CharT* fmt, + const std::chrono::duration& d) +{ + using Duration = std::chrono::duration; + using CT = typename std::common_type::type; + fields fds{hh_mm_ss{d}}; + return to_stream(os, fmt, fds); +} + +template +std::basic_ostream& +to_stream(std::basic_ostream& os, const CharT* fmt, + const local_time& tp, const std::string* abbrev = nullptr, + const std::chrono::seconds* offset_sec = nullptr) +{ + using CT = typename std::common_type::type; + auto ld = floor(tp); + fields fds{year_month_day{ld}, hh_mm_ss{tp-local_seconds{ld}}}; + return to_stream(os, fmt, fds, abbrev, offset_sec); +} + +template +std::basic_ostream& +to_stream(std::basic_ostream& os, const CharT* fmt, + const sys_time& tp) +{ + using std::chrono::seconds; + using CT = typename std::common_type::type; + const std::string abbrev("UTC"); + CONSTDATA seconds offset{0}; + auto sd = floor(tp); + fields fds{year_month_day{sd}, hh_mm_ss{tp-sys_seconds{sd}}}; + return to_stream(os, fmt, fds, &abbrev, &offset); +} + +// format + +template +auto +format(const std::locale& loc, const CharT* fmt, const Streamable& tp) + -> decltype(to_stream(std::declval&>(), fmt, tp), + std::basic_string{}) +{ + std::basic_ostringstream os; + os.exceptions(std::ios::failbit | std::ios::badbit); + os.imbue(loc); + to_stream(os, fmt, tp); + return os.str(); +} + +template +auto +format(const CharT* fmt, const Streamable& tp) + -> decltype(to_stream(std::declval&>(), fmt, tp), + std::basic_string{}) +{ + std::basic_ostringstream os; + os.exceptions(std::ios::failbit | std::ios::badbit); + to_stream(os, fmt, tp); + return os.str(); +} + +template +auto +format(const std::locale& loc, const std::basic_string& fmt, + const Streamable& tp) + -> decltype(to_stream(std::declval&>(), fmt.c_str(), tp), + std::basic_string{}) +{ + std::basic_ostringstream os; + os.exceptions(std::ios::failbit | std::ios::badbit); + os.imbue(loc); + to_stream(os, fmt.c_str(), tp); + return os.str(); +} + +template +auto +format(const std::basic_string& fmt, const Streamable& tp) + -> decltype(to_stream(std::declval&>(), fmt.c_str(), tp), + std::basic_string{}) +{ + std::basic_ostringstream os; + os.exceptions(std::ios::failbit | std::ios::badbit); + to_stream(os, fmt.c_str(), tp); + return os.str(); +} + +// parse + +namespace detail +{ + +template +bool +read_char(std::basic_istream& is, CharT fmt, std::ios::iostate& err) +{ + auto ic = is.get(); + if (Traits::eq_int_type(ic, Traits::eof()) || + !Traits::eq(Traits::to_char_type(ic), fmt)) + { + err |= std::ios::failbit; + is.setstate(std::ios::failbit); + return false; + } + return true; +} + +template +unsigned +read_unsigned(std::basic_istream& is, unsigned m = 1, unsigned M = 10) +{ + unsigned x = 0; + unsigned count = 0; + while (true) + { + auto ic = is.peek(); + if (Traits::eq_int_type(ic, Traits::eof())) + break; + auto c = static_cast(Traits::to_char_type(ic)); + if (!('0' <= c && c <= '9')) + break; + (void)is.get(); + ++count; + x = 10*x + static_cast(c - '0'); + if (count == M) + break; + } + if (count < m) + is.setstate(std::ios::failbit); + return x; +} + +template +int +read_signed(std::basic_istream& is, unsigned m = 1, unsigned M = 10) +{ + auto ic = is.peek(); + if (!Traits::eq_int_type(ic, Traits::eof())) + { + auto c = static_cast(Traits::to_char_type(ic)); + if (('0' <= c && c <= '9') || c == '-' || c == '+') + { + if (c == '-' || c == '+') + (void)is.get(); + auto x = static_cast(read_unsigned(is, std::max(m, 1u), M)); + if (!is.fail()) + { + if (c == '-') + x = -x; + return x; + } + } + } + if (m > 0) + is.setstate(std::ios::failbit); + return 0; +} + +template +long double +read_long_double(std::basic_istream& is, unsigned m = 1, unsigned M = 10) +{ + unsigned count = 0; + unsigned fcount = 0; + unsigned long long i = 0; + unsigned long long f = 0; + bool parsing_fraction = false; +#if ONLY_C_LOCALE + typename Traits::int_type decimal_point = '.'; +#else + auto decimal_point = Traits::to_int_type( + std::use_facet>(is.getloc()).decimal_point()); +#endif + while (true) + { + auto ic = is.peek(); + if (Traits::eq_int_type(ic, Traits::eof())) + break; + if (Traits::eq_int_type(ic, decimal_point)) + { + decimal_point = Traits::eof(); + parsing_fraction = true; + } + else + { + auto c = static_cast(Traits::to_char_type(ic)); + if (!('0' <= c && c <= '9')) + break; + if (!parsing_fraction) + { + i = 10*i + static_cast(c - '0'); + } + else + { + f = 10*f + static_cast(c - '0'); + ++fcount; + } + } + (void)is.get(); + if (++count == M) + break; + } + if (count < m) + { + is.setstate(std::ios::failbit); + return 0; + } + return i + f/std::pow(10.L, fcount); +} + +struct rs +{ + int& i; + unsigned m; + unsigned M; +}; + +struct ru +{ + int& i; + unsigned m; + unsigned M; +}; + +struct rld +{ + long double& i; + unsigned m; + unsigned M; +}; + +template +void +read(std::basic_istream&) +{ +} + +template +void +read(std::basic_istream& is, CharT a0, Args&& ...args); + +template +void +read(std::basic_istream& is, rs a0, Args&& ...args); + +template +void +read(std::basic_istream& is, ru a0, Args&& ...args); + +template +void +read(std::basic_istream& is, int a0, Args&& ...args); + +template +void +read(std::basic_istream& is, rld a0, Args&& ...args); + +template +void +read(std::basic_istream& is, CharT a0, Args&& ...args) +{ + // No-op if a0 == CharT{} + if (a0 != CharT{}) + { + auto ic = is.peek(); + if (Traits::eq_int_type(ic, Traits::eof())) + { + is.setstate(std::ios::failbit | std::ios::eofbit); + return; + } + if (!Traits::eq(Traits::to_char_type(ic), a0)) + { + is.setstate(std::ios::failbit); + return; + } + (void)is.get(); + } + read(is, std::forward(args)...); +} + +template +void +read(std::basic_istream& is, rs a0, Args&& ...args) +{ + auto x = read_signed(is, a0.m, a0.M); + if (is.fail()) + return; + a0.i = x; + read(is, std::forward(args)...); +} + +template +void +read(std::basic_istream& is, ru a0, Args&& ...args) +{ + auto x = read_unsigned(is, a0.m, a0.M); + if (is.fail()) + return; + a0.i = static_cast(x); + read(is, std::forward(args)...); +} + +template +void +read(std::basic_istream& is, int a0, Args&& ...args) +{ + if (a0 != -1) + { + auto u = static_cast(a0); + CharT buf[std::numeric_limits::digits10+2u] = {}; + auto e = buf; + do + { + *e++ = static_cast(CharT(u % 10) + CharT{'0'}); + u /= 10; + } while (u > 0); + std::reverse(buf, e); + for (auto p = buf; p != e && is.rdstate() == std::ios::goodbit; ++p) + read(is, *p); + } + if (is.rdstate() == std::ios::goodbit) + read(is, std::forward(args)...); +} + +template +void +read(std::basic_istream& is, rld a0, Args&& ...args) +{ + auto x = read_long_double(is, a0.m, a0.M); + if (is.fail()) + return; + a0.i = x; + read(is, std::forward(args)...); +} + +template +inline +void +checked_set(T& value, T from, T not_a_value, std::basic_ios& is) +{ + if (!is.fail()) + { + if (value == not_a_value) + value = std::move(from); + else if (value != from) + is.setstate(std::ios::failbit); + } +} + +} // namespace detail; + +template > +std::basic_istream& +from_stream(std::basic_istream& is, const CharT* fmt, + fields& fds, std::basic_string* abbrev, + std::chrono::minutes* offset) +{ + using std::numeric_limits; + using std::ios; + using std::chrono::duration; + using std::chrono::duration_cast; + using std::chrono::seconds; + using std::chrono::minutes; + using std::chrono::hours; + using detail::round_i; + typename std::basic_istream::sentry ok{is, true}; + if (ok) + { + date::detail::save_istream ss(is); + is.fill(' '); + is.flags(std::ios::skipws | std::ios::dec); + is.width(0); +#if !ONLY_C_LOCALE + auto& f = std::use_facet>(is.getloc()); + std::tm tm{}; +#endif + const CharT* command = nullptr; + auto modified = CharT{}; + auto width = -1; + + CONSTDATA int not_a_year = numeric_limits::min(); + CONSTDATA int not_a_2digit_year = 100; + CONSTDATA int not_a_century = not_a_year / 100; + CONSTDATA int not_a_month = 0; + CONSTDATA int not_a_day = 0; + CONSTDATA int not_a_hour = numeric_limits::min(); + CONSTDATA int not_a_hour_12_value = 0; + CONSTDATA int not_a_minute = not_a_hour; + CONSTDATA Duration not_a_second = Duration::min(); + CONSTDATA int not_a_doy = -1; + CONSTDATA int not_a_weekday = 8; + CONSTDATA int not_a_week_num = 100; + CONSTDATA int not_a_ampm = -1; + CONSTDATA minutes not_a_offset = minutes::min(); + + int Y = not_a_year; // c, F, Y * + int y = not_a_2digit_year; // D, x, y * + int g = not_a_2digit_year; // g * + int G = not_a_year; // G * + int C = not_a_century; // C * + int m = not_a_month; // b, B, h, m, c, D, F, x * + int d = not_a_day; // c, d, D, e, F, x * + int j = not_a_doy; // j * + int wd = not_a_weekday; // a, A, u, w * + int H = not_a_hour; // c, H, R, T, X * + int I = not_a_hour_12_value; // I, r * + int p = not_a_ampm; // p, r * + int M = not_a_minute; // c, M, r, R, T, X * + Duration s = not_a_second; // c, r, S, T, X * + int U = not_a_week_num; // U * + int V = not_a_week_num; // V * + int W = not_a_week_num; // W * + std::basic_string temp_abbrev; // Z * + minutes temp_offset = not_a_offset; // z * + + using detail::read; + using detail::rs; + using detail::ru; + using detail::rld; + using detail::checked_set; + for (; *fmt != CharT{} && !is.fail(); ++fmt) + { + switch (*fmt) + { + case 'a': + case 'A': + case 'u': + case 'w': // wd: a, A, u, w + if (command) + { + int trial_wd = not_a_weekday; + if (*fmt == 'a' || *fmt == 'A') + { + if (modified == CharT{}) + { +#if !ONLY_C_LOCALE + ios::iostate err = ios::goodbit; + f.get(is, nullptr, is, err, &tm, command, fmt+1); + is.setstate(err); + if (!is.fail()) + trial_wd = tm.tm_wday; +#else + auto nm = detail::weekday_names(); + auto i = detail::scan_keyword(is, nm.first, nm.second) - nm.first; + if (!is.fail()) + trial_wd = i % 7; +#endif + } + else + read(is, CharT{'%'}, width, modified, *fmt); + } + else // *fmt == 'u' || *fmt == 'w' + { +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#else + if (modified != CharT{'E'}) +#endif + { + read(is, ru{trial_wd, 1, width == -1 ? + 1u : static_cast(width)}); + if (!is.fail()) + { + if (*fmt == 'u') + { + if (!(1 <= trial_wd && trial_wd <= 7)) + { + trial_wd = not_a_weekday; + is.setstate(ios::failbit); + } + else if (trial_wd == 7) + trial_wd = 0; + } + else // *fmt == 'w' + { + if (!(0 <= trial_wd && trial_wd <= 6)) + { + trial_wd = not_a_weekday; + is.setstate(ios::failbit); + } + } + } + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'O'}) + { + ios::iostate err = ios::goodbit; + f.get(is, nullptr, is, err, &tm, command, fmt+1); + is.setstate(err); + if (!is.fail()) + trial_wd = tm.tm_wday; + } +#endif + else + read(is, CharT{'%'}, width, modified, *fmt); + } + if (trial_wd != not_a_weekday) + checked_set(wd, trial_wd, not_a_weekday, is); + } + else // !command + read(is, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + break; + case 'b': + case 'B': + case 'h': + if (command) + { + if (modified == CharT{}) + { + int ttm = not_a_month; +#if !ONLY_C_LOCALE + ios::iostate err = ios::goodbit; + f.get(is, nullptr, is, err, &tm, command, fmt+1); + if ((err & ios::failbit) == 0) + ttm = tm.tm_mon + 1; + is.setstate(err); +#else + auto nm = detail::month_names(); + auto i = detail::scan_keyword(is, nm.first, nm.second) - nm.first; + if (!is.fail()) + ttm = i % 12 + 1; +#endif + checked_set(m, ttm, not_a_month, is); + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'c': + if (command) + { + if (modified != CharT{'O'}) + { +#if !ONLY_C_LOCALE + ios::iostate err = ios::goodbit; + f.get(is, nullptr, is, err, &tm, command, fmt+1); + if ((err & ios::failbit) == 0) + { + checked_set(Y, tm.tm_year + 1900, not_a_year, is); + checked_set(m, tm.tm_mon + 1, not_a_month, is); + checked_set(d, tm.tm_mday, not_a_day, is); + checked_set(H, tm.tm_hour, not_a_hour, is); + checked_set(M, tm.tm_min, not_a_minute, is); + checked_set(s, duration_cast(seconds{tm.tm_sec}), + not_a_second, is); + } + is.setstate(err); +#else + // "%a %b %e %T %Y" + auto nm = detail::weekday_names(); + auto i = detail::scan_keyword(is, nm.first, nm.second) - nm.first; + checked_set(wd, static_cast(i % 7), not_a_weekday, is); + ws(is); + nm = detail::month_names(); + i = detail::scan_keyword(is, nm.first, nm.second) - nm.first; + checked_set(m, static_cast(i % 12 + 1), not_a_month, is); + ws(is); + int td = not_a_day; + read(is, rs{td, 1, 2}); + checked_set(d, td, not_a_day, is); + ws(is); + using dfs = detail::decimal_format_seconds; + CONSTDATA auto w = Duration::period::den == 1 ? 2 : 3 + dfs::width; + int tH; + int tM; + long double S; + read(is, ru{tH, 1, 2}, CharT{':'}, ru{tM, 1, 2}, + CharT{':'}, rld{S, 1, w}); + checked_set(H, tH, not_a_hour, is); + checked_set(M, tM, not_a_minute, is); + checked_set(s, round_i(duration{S}), + not_a_second, is); + ws(is); + int tY = not_a_year; + read(is, rs{tY, 1, 4u}); + checked_set(Y, tY, not_a_year, is); +#endif + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'x': + if (command) + { + if (modified != CharT{'O'}) + { +#if !ONLY_C_LOCALE + ios::iostate err = ios::goodbit; + f.get(is, nullptr, is, err, &tm, command, fmt+1); + if ((err & ios::failbit) == 0) + { + checked_set(Y, tm.tm_year + 1900, not_a_year, is); + checked_set(m, tm.tm_mon + 1, not_a_month, is); + checked_set(d, tm.tm_mday, not_a_day, is); + } + is.setstate(err); +#else + // "%m/%d/%y" + int ty = not_a_2digit_year; + int tm = not_a_month; + int td = not_a_day; + read(is, ru{tm, 1, 2}, CharT{'/'}, ru{td, 1, 2}, CharT{'/'}, + rs{ty, 1, 2}); + checked_set(y, ty, not_a_2digit_year, is); + checked_set(m, tm, not_a_month, is); + checked_set(d, td, not_a_day, is); +#endif + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'X': + if (command) + { + if (modified != CharT{'O'}) + { +#if !ONLY_C_LOCALE + ios::iostate err = ios::goodbit; + f.get(is, nullptr, is, err, &tm, command, fmt+1); + if ((err & ios::failbit) == 0) + { + checked_set(H, tm.tm_hour, not_a_hour, is); + checked_set(M, tm.tm_min, not_a_minute, is); + checked_set(s, duration_cast(seconds{tm.tm_sec}), + not_a_second, is); + } + is.setstate(err); +#else + // "%T" + using dfs = detail::decimal_format_seconds; + CONSTDATA auto w = Duration::period::den == 1 ? 2 : 3 + dfs::width; + int tH = not_a_hour; + int tM = not_a_minute; + long double S; + read(is, ru{tH, 1, 2}, CharT{':'}, ru{tM, 1, 2}, + CharT{':'}, rld{S, 1, w}); + checked_set(H, tH, not_a_hour, is); + checked_set(M, tM, not_a_minute, is); + checked_set(s, round_i(duration{S}), + not_a_second, is); +#endif + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'C': + if (command) + { + int tC = not_a_century; +#if !ONLY_C_LOCALE + if (modified == CharT{}) + { +#endif + read(is, rs{tC, 1, width == -1 ? 2u : static_cast(width)}); +#if !ONLY_C_LOCALE + } + else + { + ios::iostate err = ios::goodbit; + f.get(is, nullptr, is, err, &tm, command, fmt+1); + if ((err & ios::failbit) == 0) + { + auto tY = tm.tm_year + 1900; + tC = (tY >= 0 ? tY : tY-99) / 100; + } + is.setstate(err); + } +#endif + checked_set(C, tC, not_a_century, is); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'D': + if (command) + { + if (modified == CharT{}) + { + int tn = not_a_month; + int td = not_a_day; + int ty = not_a_2digit_year; + read(is, ru{tn, 1, 2}, CharT{'\0'}, CharT{'/'}, CharT{'\0'}, + ru{td, 1, 2}, CharT{'\0'}, CharT{'/'}, CharT{'\0'}, + rs{ty, 1, 2}); + checked_set(y, ty, not_a_2digit_year, is); + checked_set(m, tn, not_a_month, is); + checked_set(d, td, not_a_day, is); + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'F': + if (command) + { + if (modified == CharT{}) + { + int tY = not_a_year; + int tn = not_a_month; + int td = not_a_day; + read(is, rs{tY, 1, width == -1 ? 4u : static_cast(width)}, + CharT{'-'}, ru{tn, 1, 2}, CharT{'-'}, ru{td, 1, 2}); + checked_set(Y, tY, not_a_year, is); + checked_set(m, tn, not_a_month, is); + checked_set(d, td, not_a_day, is); + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'd': + case 'e': + if (command) + { +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#else + if (modified != CharT{'E'}) +#endif + { + int td = not_a_day; + read(is, rs{td, 1, width == -1 ? 2u : static_cast(width)}); + checked_set(d, td, not_a_day, is); + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'O'}) + { + ios::iostate err = ios::goodbit; + f.get(is, nullptr, is, err, &tm, command, fmt+1); + command = nullptr; + width = -1; + modified = CharT{}; + if ((err & ios::failbit) == 0) + checked_set(d, tm.tm_mday, not_a_day, is); + is.setstate(err); + } +#endif + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'H': + if (command) + { +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#else + if (modified != CharT{'E'}) +#endif + { + int tH = not_a_hour; + read(is, ru{tH, 1, width == -1 ? 2u : static_cast(width)}); + checked_set(H, tH, not_a_hour, is); + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'O'}) + { + ios::iostate err = ios::goodbit; + f.get(is, nullptr, is, err, &tm, command, fmt+1); + if ((err & ios::failbit) == 0) + checked_set(H, tm.tm_hour, not_a_hour, is); + is.setstate(err); + } +#endif + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'I': + if (command) + { + if (modified == CharT{}) + { + int tI = not_a_hour_12_value; + // reads in an hour into I, but most be in [1, 12] + read(is, rs{tI, 1, width == -1 ? 2u : static_cast(width)}); + if (!(1 <= tI && tI <= 12)) + is.setstate(ios::failbit); + checked_set(I, tI, not_a_hour_12_value, is); + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'j': + if (command) + { + if (modified == CharT{}) + { + int tj = not_a_doy; + read(is, ru{tj, 1, width == -1 ? 3u : static_cast(width)}); + checked_set(j, tj, not_a_doy, is); + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'M': + if (command) + { +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#else + if (modified != CharT{'E'}) +#endif + { + int tM = not_a_minute; + read(is, ru{tM, 1, width == -1 ? 2u : static_cast(width)}); + checked_set(M, tM, not_a_minute, is); + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'O'}) + { + ios::iostate err = ios::goodbit; + f.get(is, nullptr, is, err, &tm, command, fmt+1); + if ((err & ios::failbit) == 0) + checked_set(M, tm.tm_min, not_a_minute, is); + is.setstate(err); + } +#endif + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'm': + if (command) + { +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#else + if (modified != CharT{'E'}) +#endif + { + int tn = not_a_month; + read(is, rs{tn, 1, width == -1 ? 2u : static_cast(width)}); + checked_set(m, tn, not_a_month, is); + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'O'}) + { + ios::iostate err = ios::goodbit; + f.get(is, nullptr, is, err, &tm, command, fmt+1); + if ((err & ios::failbit) == 0) + checked_set(m, tm.tm_mon + 1, not_a_month, is); + is.setstate(err); + } +#endif + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'n': + case 't': + if (command) + { + if (modified == CharT{}) + { + // %n matches a single white space character + // %t matches 0 or 1 white space characters + auto ic = is.peek(); + if (Traits::eq_int_type(ic, Traits::eof())) + { + ios::iostate err = ios::eofbit; + if (*fmt == 'n') + err |= ios::failbit; + is.setstate(err); + break; + } + if (isspace(ic)) + { + (void)is.get(); + } + else if (*fmt == 'n') + is.setstate(ios::failbit); + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'p': + if (command) + { + if (modified == CharT{}) + { + int tp = not_a_ampm; +#if !ONLY_C_LOCALE + tm = std::tm{}; + tm.tm_hour = 1; + ios::iostate err = ios::goodbit; + f.get(is, nullptr, is, err, &tm, command, fmt+1); + is.setstate(err); + if (tm.tm_hour == 1) + tp = 0; + else if (tm.tm_hour == 13) + tp = 1; + else + is.setstate(err); +#else + auto nm = detail::ampm_names(); + auto i = detail::scan_keyword(is, nm.first, nm.second) - nm.first; + tp = static_cast(i); +#endif + checked_set(p, tp, not_a_ampm, is); + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + + break; + case 'r': + if (command) + { + if (modified == CharT{}) + { +#if !ONLY_C_LOCALE + ios::iostate err = ios::goodbit; + f.get(is, nullptr, is, err, &tm, command, fmt+1); + if ((err & ios::failbit) == 0) + { + checked_set(H, tm.tm_hour, not_a_hour, is); + checked_set(M, tm.tm_min, not_a_hour, is); + checked_set(s, duration_cast(seconds{tm.tm_sec}), + not_a_second, is); + } + is.setstate(err); +#else + // "%I:%M:%S %p" + using dfs = detail::decimal_format_seconds; + CONSTDATA auto w = Duration::period::den == 1 ? 2 : 3 + dfs::width; + long double S; + int tI = not_a_hour_12_value; + int tM = not_a_minute; + read(is, ru{tI, 1, 2}, CharT{':'}, ru{tM, 1, 2}, + CharT{':'}, rld{S, 1, w}); + checked_set(I, tI, not_a_hour_12_value, is); + checked_set(M, tM, not_a_minute, is); + checked_set(s, round_i(duration{S}), + not_a_second, is); + ws(is); + auto nm = detail::ampm_names(); + auto i = detail::scan_keyword(is, nm.first, nm.second) - nm.first; + checked_set(p, static_cast(i), not_a_ampm, is); +#endif + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'R': + if (command) + { + if (modified == CharT{}) + { + int tH = not_a_hour; + int tM = not_a_minute; + read(is, ru{tH, 1, 2}, CharT{'\0'}, CharT{':'}, CharT{'\0'}, + ru{tM, 1, 2}, CharT{'\0'}); + checked_set(H, tH, not_a_hour, is); + checked_set(M, tM, not_a_minute, is); + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'S': + if (command) + { + #if !ONLY_C_LOCALE + if (modified == CharT{}) +#else + if (modified != CharT{'E'}) +#endif + { + using dfs = detail::decimal_format_seconds; + CONSTDATA auto w = Duration::period::den == 1 ? 2 : 3 + dfs::width; + long double S; + read(is, rld{S, 1, width == -1 ? w : static_cast(width)}); + checked_set(s, round_i(duration{S}), + not_a_second, is); + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'O'}) + { + ios::iostate err = ios::goodbit; + f.get(is, nullptr, is, err, &tm, command, fmt+1); + if ((err & ios::failbit) == 0) + checked_set(s, duration_cast(seconds{tm.tm_sec}), + not_a_second, is); + is.setstate(err); + } +#endif + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'T': + if (command) + { + if (modified == CharT{}) + { + using dfs = detail::decimal_format_seconds; + CONSTDATA auto w = Duration::period::den == 1 ? 2 : 3 + dfs::width; + int tH = not_a_hour; + int tM = not_a_minute; + long double S; + read(is, ru{tH, 1, 2}, CharT{':'}, ru{tM, 1, 2}, + CharT{':'}, rld{S, 1, w}); + checked_set(H, tH, not_a_hour, is); + checked_set(M, tM, not_a_minute, is); + checked_set(s, round_i(duration{S}), + not_a_second, is); + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'Y': + if (command) + { +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#else + if (modified != CharT{'O'}) +#endif + { + int tY = not_a_year; + read(is, rs{tY, 1, width == -1 ? 4u : static_cast(width)}); + checked_set(Y, tY, not_a_year, is); + } +#if !ONLY_C_LOCALE + else if (modified == CharT{'E'}) + { + ios::iostate err = ios::goodbit; + f.get(is, nullptr, is, err, &tm, command, fmt+1); + if ((err & ios::failbit) == 0) + checked_set(Y, tm.tm_year + 1900, not_a_year, is); + is.setstate(err); + } +#endif + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'y': + if (command) + { +#if !ONLY_C_LOCALE + if (modified == CharT{}) +#endif + { + int ty = not_a_2digit_year; + read(is, ru{ty, 1, width == -1 ? 2u : static_cast(width)}); + checked_set(y, ty, not_a_2digit_year, is); + } +#if !ONLY_C_LOCALE + else + { + ios::iostate err = ios::goodbit; + f.get(is, nullptr, is, err, &tm, command, fmt+1); + if ((err & ios::failbit) == 0) + checked_set(Y, tm.tm_year + 1900, not_a_year, is); + is.setstate(err); + } +#endif + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'g': + if (command) + { + if (modified == CharT{}) + { + int tg = not_a_2digit_year; + read(is, ru{tg, 1, width == -1 ? 2u : static_cast(width)}); + checked_set(g, tg, not_a_2digit_year, is); + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'G': + if (command) + { + if (modified == CharT{}) + { + int tG = not_a_year; + read(is, rs{tG, 1, width == -1 ? 4u : static_cast(width)}); + checked_set(G, tG, not_a_year, is); + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'U': + if (command) + { + if (modified == CharT{}) + { + int tU = not_a_week_num; + read(is, ru{tU, 1, width == -1 ? 2u : static_cast(width)}); + checked_set(U, tU, not_a_week_num, is); + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'V': + if (command) + { + if (modified == CharT{}) + { + int tV = not_a_week_num; + read(is, ru{tV, 1, width == -1 ? 2u : static_cast(width)}); + checked_set(V, tV, not_a_week_num, is); + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'W': + if (command) + { + if (modified == CharT{}) + { + int tW = not_a_week_num; + read(is, ru{tW, 1, width == -1 ? 2u : static_cast(width)}); + checked_set(W, tW, not_a_week_num, is); + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'E': + case 'O': + if (command) + { + if (modified == CharT{}) + { + modified = *fmt; + } + else + { + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + } + else + read(is, *fmt); + break; + case '%': + if (command) + { + if (modified == CharT{}) + read(is, *fmt); + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + command = fmt; + break; + case 'z': + if (command) + { + int tH, tM; + minutes toff = not_a_offset; + bool neg = false; + auto ic = is.peek(); + if (!Traits::eq_int_type(ic, Traits::eof())) + { + auto c = static_cast(Traits::to_char_type(ic)); + if (c == '-') + neg = true; + } + if (modified == CharT{}) + { + read(is, rs{tH, 2, 2}); + if (!is.fail()) + toff = hours{std::abs(tH)}; + if (is.good()) + { + ic = is.peek(); + if (!Traits::eq_int_type(ic, Traits::eof())) + { + auto c = static_cast(Traits::to_char_type(ic)); + if ('0' <= c && c <= '9') + { + read(is, ru{tM, 2, 2}); + if (!is.fail()) + toff += minutes{tM}; + } + } + } + } + else + { + read(is, rs{tH, 1, 2}); + if (!is.fail()) + toff = hours{std::abs(tH)}; + if (is.good()) + { + ic = is.peek(); + if (!Traits::eq_int_type(ic, Traits::eof())) + { + auto c = static_cast(Traits::to_char_type(ic)); + if (c == ':') + { + (void)is.get(); + read(is, ru{tM, 2, 2}); + if (!is.fail()) + toff += minutes{tM}; + } + } + } + } + if (neg) + toff = -toff; + checked_set(temp_offset, toff, not_a_offset, is); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + case 'Z': + if (command) + { + if (modified == CharT{}) + { + std::basic_string buf; + while (is.rdstate() == std::ios::goodbit) + { + auto i = is.rdbuf()->sgetc(); + if (Traits::eq_int_type(i, Traits::eof())) + { + is.setstate(ios::eofbit); + break; + } + auto wc = Traits::to_char_type(i); + auto c = static_cast(wc); + // is c a valid time zone name or abbreviation character? + if (!(CharT{1} < wc && wc < CharT{127}) || !(isalnum(c) || + c == '_' || c == '/' || c == '-' || c == '+')) + break; + buf.push_back(c); + is.rdbuf()->sbumpc(); + } + if (buf.empty()) + is.setstate(ios::failbit); + checked_set(temp_abbrev, buf, {}, is); + } + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + else + read(is, *fmt); + break; + default: + if (command) + { + if (width == -1 && modified == CharT{} && '0' <= *fmt && *fmt <= '9') + { + width = static_cast(*fmt) - '0'; + while ('0' <= fmt[1] && fmt[1] <= '9') + width = 10*width + static_cast(*++fmt) - '0'; + } + else + { + if (modified == CharT{}) + read(is, CharT{'%'}, width, *fmt); + else + read(is, CharT{'%'}, width, modified, *fmt); + command = nullptr; + width = -1; + modified = CharT{}; + } + } + else // !command + { + if (isspace(static_cast(*fmt))) + { + // space matches 0 or more white space characters + if (is.good()) + ws(is); + } + else + read(is, *fmt); + } + break; + } + } + // is.fail() || *fmt == CharT{} + if (is.rdstate() == ios::goodbit && command) + { + if (modified == CharT{}) + read(is, CharT{'%'}, width); + else + read(is, CharT{'%'}, width, modified); + } + if (!is.fail()) + { + if (y != not_a_2digit_year) + { + // Convert y and an optional C to Y + if (!(0 <= y && y <= 99)) + goto broken; + if (C == not_a_century) + { + if (Y == not_a_year) + { + if (y >= 69) + C = 19; + else + C = 20; + } + else + { + C = (Y >= 0 ? Y : Y-100) / 100; + } + } + int tY; + if (C >= 0) + tY = 100*C + y; + else + tY = 100*(C+1) - (y == 0 ? 100 : y); + if (Y != not_a_year && Y != tY) + goto broken; + Y = tY; + } + if (g != not_a_2digit_year) + { + // Convert g and an optional C to G + if (!(0 <= g && g <= 99)) + goto broken; + if (C == not_a_century) + { + if (G == not_a_year) + { + if (g >= 69) + C = 19; + else + C = 20; + } + else + { + C = (G >= 0 ? G : G-100) / 100; + } + } + int tG; + if (C >= 0) + tG = 100*C + g; + else + tG = 100*(C+1) - (g == 0 ? 100 : g); + if (G != not_a_year && G != tG) + goto broken; + G = tG; + } + if (Y < static_cast(year::min()) || Y > static_cast(year::max())) + Y = not_a_year; + bool computed = false; + if (G != not_a_year && V != not_a_week_num && wd != not_a_weekday) + { + year_month_day ymd_trial = sys_days(year{G-1}/December/Thursday[last]) + + (Monday-Thursday) + weeks{V-1} + + (weekday{static_cast(wd)}-Monday); + if (Y == not_a_year) + Y = static_cast(ymd_trial.year()); + else if (year{Y} != ymd_trial.year()) + goto broken; + if (m == not_a_month) + m = static_cast(static_cast(ymd_trial.month())); + else if (month(static_cast(m)) != ymd_trial.month()) + goto broken; + if (d == not_a_day) + d = static_cast(static_cast(ymd_trial.day())); + else if (day(static_cast(d)) != ymd_trial.day()) + goto broken; + computed = true; + } + if (Y != not_a_year && U != not_a_week_num && wd != not_a_weekday) + { + year_month_day ymd_trial = sys_days(year{Y}/January/Sunday[1]) + + weeks{U-1} + + (weekday{static_cast(wd)} - Sunday); + if (Y == not_a_year) + Y = static_cast(ymd_trial.year()); + else if (year{Y} != ymd_trial.year()) + goto broken; + if (m == not_a_month) + m = static_cast(static_cast(ymd_trial.month())); + else if (month(static_cast(m)) != ymd_trial.month()) + goto broken; + if (d == not_a_day) + d = static_cast(static_cast(ymd_trial.day())); + else if (day(static_cast(d)) != ymd_trial.day()) + goto broken; + computed = true; + } + if (Y != not_a_year && W != not_a_week_num && wd != not_a_weekday) + { + year_month_day ymd_trial = sys_days(year{Y}/January/Monday[1]) + + weeks{W-1} + + (weekday{static_cast(wd)} - Monday); + if (Y == not_a_year) + Y = static_cast(ymd_trial.year()); + else if (year{Y} != ymd_trial.year()) + goto broken; + if (m == not_a_month) + m = static_cast(static_cast(ymd_trial.month())); + else if (month(static_cast(m)) != ymd_trial.month()) + goto broken; + if (d == not_a_day) + d = static_cast(static_cast(ymd_trial.day())); + else if (day(static_cast(d)) != ymd_trial.day()) + goto broken; + computed = true; + } + if (j != not_a_doy && Y != not_a_year) + { + auto ymd_trial = year_month_day{local_days(year{Y}/1/1) + days{j-1}}; + if (m == 0) + m = static_cast(static_cast(ymd_trial.month())); + else if (month(static_cast(m)) != ymd_trial.month()) + goto broken; + if (d == 0) + d = static_cast(static_cast(ymd_trial.day())); + else if (day(static_cast(d)) != ymd_trial.day()) + goto broken; + j = not_a_doy; + } + auto ymd = year{Y}/m/d; + if (ymd.ok()) + { + if (wd == not_a_weekday) + wd = static_cast((weekday(sys_days(ymd)) - Sunday).count()); + else if (wd != static_cast((weekday(sys_days(ymd)) - Sunday).count())) + goto broken; + if (!computed) + { + if (G != not_a_year || V != not_a_week_num) + { + sys_days sd = ymd; + auto G_trial = year_month_day{sd + days{3}}.year(); + auto start = sys_days((G_trial - years{1})/December/Thursday[last]) + + (Monday - Thursday); + if (sd < start) + { + --G_trial; + if (V != not_a_week_num) + start = sys_days((G_trial - years{1})/December/Thursday[last]) + + (Monday - Thursday); + } + if (G != not_a_year && G != static_cast(G_trial)) + goto broken; + if (V != not_a_week_num) + { + auto V_trial = duration_cast(sd - start).count() + 1; + if (V != V_trial) + goto broken; + } + } + if (U != not_a_week_num) + { + auto start = sys_days(Sunday[1]/January/ymd.year()); + auto U_trial = floor(sys_days(ymd) - start).count() + 1; + if (U != U_trial) + goto broken; + } + if (W != not_a_week_num) + { + auto start = sys_days(Monday[1]/January/ymd.year()); + auto W_trial = floor(sys_days(ymd) - start).count() + 1; + if (W != W_trial) + goto broken; + } + } + } + fds.ymd = ymd; + if (I != not_a_hour_12_value) + { + if (!(1 <= I && I <= 12)) + goto broken; + if (p != not_a_ampm) + { + // p is in [0, 1] == [AM, PM] + // Store trial H in I + if (I == 12) + --p; + I += p*12; + // Either set H from I or make sure H and I are consistent + if (H == not_a_hour) + H = I; + else if (I != H) + goto broken; + } + else // p == not_a_ampm + { + // if H, make sure H and I could be consistent + if (H != not_a_hour) + { + if (I == 12) + { + if (H != 0 && H != 12) + goto broken; + } + else if (!(I == H || I == H+12)) + { + goto broken; + } + } + else // I is ambiguous, AM or PM? + goto broken; + } + } + if (H != not_a_hour) + { + fds.has_tod = true; + fds.tod = hh_mm_ss{hours{H}}; + } + if (M != not_a_minute) + { + fds.has_tod = true; + fds.tod.m_ = minutes{M}; + } + if (s != not_a_second) + { + fds.has_tod = true; + fds.tod.s_ = detail::decimal_format_seconds{s}; + } + if (j != not_a_doy) + { + fds.has_tod = true; + fds.tod.h_ += hours{days{j}}; + } + if (wd != not_a_weekday) + fds.wd = weekday{static_cast(wd)}; + if (abbrev != nullptr) + *abbrev = std::move(temp_abbrev); + if (offset != nullptr && temp_offset != not_a_offset) + *offset = temp_offset; + } + return is; + } +broken: + is.setstate(ios::failbit); + return is; +} + +template > +std::basic_istream& +from_stream(std::basic_istream& is, const CharT* fmt, year& y, + std::basic_string* abbrev = nullptr, + std::chrono::minutes* offset = nullptr) +{ + using CT = std::chrono::seconds; + fields fds{}; + from_stream(is, fmt, fds, abbrev, offset); + if (!fds.ymd.year().ok()) + is.setstate(std::ios::failbit); + if (!is.fail()) + y = fds.ymd.year(); + return is; +} + +template > +std::basic_istream& +from_stream(std::basic_istream& is, const CharT* fmt, month& m, + std::basic_string* abbrev = nullptr, + std::chrono::minutes* offset = nullptr) +{ + using CT = std::chrono::seconds; + fields fds{}; + from_stream(is, fmt, fds, abbrev, offset); + if (!fds.ymd.month().ok()) + is.setstate(std::ios::failbit); + if (!is.fail()) + m = fds.ymd.month(); + return is; +} + +template > +std::basic_istream& +from_stream(std::basic_istream& is, const CharT* fmt, day& d, + std::basic_string* abbrev = nullptr, + std::chrono::minutes* offset = nullptr) +{ + using CT = std::chrono::seconds; + fields fds{}; + from_stream(is, fmt, fds, abbrev, offset); + if (!fds.ymd.day().ok()) + is.setstate(std::ios::failbit); + if (!is.fail()) + d = fds.ymd.day(); + return is; +} + +template > +std::basic_istream& +from_stream(std::basic_istream& is, const CharT* fmt, weekday& wd, + std::basic_string* abbrev = nullptr, + std::chrono::minutes* offset = nullptr) +{ + using CT = std::chrono::seconds; + fields fds{}; + from_stream(is, fmt, fds, abbrev, offset); + if (!fds.wd.ok()) + is.setstate(std::ios::failbit); + if (!is.fail()) + wd = fds.wd; + return is; +} + +template > +std::basic_istream& +from_stream(std::basic_istream& is, const CharT* fmt, year_month& ym, + std::basic_string* abbrev = nullptr, + std::chrono::minutes* offset = nullptr) +{ + using CT = std::chrono::seconds; + fields fds{}; + from_stream(is, fmt, fds, abbrev, offset); + if (!fds.ymd.month().ok()) + is.setstate(std::ios::failbit); + if (!is.fail()) + ym = fds.ymd.year()/fds.ymd.month(); + return is; +} + +template > +std::basic_istream& +from_stream(std::basic_istream& is, const CharT* fmt, month_day& md, + std::basic_string* abbrev = nullptr, + std::chrono::minutes* offset = nullptr) +{ + using CT = std::chrono::seconds; + fields fds{}; + from_stream(is, fmt, fds, abbrev, offset); + if (!fds.ymd.month().ok() || !fds.ymd.day().ok()) + is.setstate(std::ios::failbit); + if (!is.fail()) + md = fds.ymd.month()/fds.ymd.day(); + return is; +} + +template > +std::basic_istream& +from_stream(std::basic_istream& is, const CharT* fmt, + year_month_day& ymd, std::basic_string* abbrev = nullptr, + std::chrono::minutes* offset = nullptr) +{ + using CT = std::chrono::seconds; + fields fds{}; + from_stream(is, fmt, fds, abbrev, offset); + if (!fds.ymd.ok()) + is.setstate(std::ios::failbit); + if (!is.fail()) + ymd = fds.ymd; + return is; +} + +template > +std::basic_istream& +from_stream(std::basic_istream& is, const CharT* fmt, + sys_time& tp, std::basic_string* abbrev = nullptr, + std::chrono::minutes* offset = nullptr) +{ + using CT = typename std::common_type::type; + using detail::round_i; + std::chrono::minutes offset_local{}; + auto offptr = offset ? offset : &offset_local; + fields fds{}; + fds.has_tod = true; + from_stream(is, fmt, fds, abbrev, offptr); + if (!fds.ymd.ok() || !fds.tod.in_conventional_range()) + is.setstate(std::ios::failbit); + if (!is.fail()) + tp = round_i(sys_days(fds.ymd) - *offptr + fds.tod.to_duration()); + return is; +} + +template > +std::basic_istream& +from_stream(std::basic_istream& is, const CharT* fmt, + local_time& tp, std::basic_string* abbrev = nullptr, + std::chrono::minutes* offset = nullptr) +{ + using CT = typename std::common_type::type; + using detail::round_i; + fields fds{}; + fds.has_tod = true; + from_stream(is, fmt, fds, abbrev, offset); + if (!fds.ymd.ok() || !fds.tod.in_conventional_range()) + is.setstate(std::ios::failbit); + if (!is.fail()) + tp = round_i(local_seconds{local_days(fds.ymd)} + fds.tod.to_duration()); + return is; +} + +template > +std::basic_istream& +from_stream(std::basic_istream& is, const CharT* fmt, + std::chrono::duration& d, + std::basic_string* abbrev = nullptr, + std::chrono::minutes* offset = nullptr) +{ + using Duration = std::chrono::duration; + using CT = typename std::common_type::type; + fields fds{}; + from_stream(is, fmt, fds, abbrev, offset); + if (!fds.has_tod) + is.setstate(std::ios::failbit); + if (!is.fail()) + d = std::chrono::duration_cast(fds.tod.to_duration()); + return is; +} + +template , + class Alloc = std::allocator> +struct parse_manip +{ + const std::basic_string format_; + Parsable& tp_; + std::basic_string* abbrev_; + std::chrono::minutes* offset_; + +public: + parse_manip(std::basic_string format, Parsable& tp, + std::basic_string* abbrev = nullptr, + std::chrono::minutes* offset = nullptr) + : format_(std::move(format)) + , tp_(tp) + , abbrev_(abbrev) + , offset_(offset) + {} + +}; + +template +std::basic_istream& +operator>>(std::basic_istream& is, + const parse_manip& x) +{ + return from_stream(is, x.format_.c_str(), x.tp_, x.abbrev_, x.offset_); +} + +template +inline +auto +parse(const std::basic_string& format, Parsable& tp) + -> decltype(from_stream(std::declval&>(), + format.c_str(), tp), + parse_manip{format, tp}) +{ + return {format, tp}; +} + +template +inline +auto +parse(const std::basic_string& format, Parsable& tp, + std::basic_string& abbrev) + -> decltype(from_stream(std::declval&>(), + format.c_str(), tp, &abbrev), + parse_manip{format, tp, &abbrev}) +{ + return {format, tp, &abbrev}; +} + +template +inline +auto +parse(const std::basic_string& format, Parsable& tp, + std::chrono::minutes& offset) + -> decltype(from_stream(std::declval&>(), + format.c_str(), tp, + std::declval*>(), + &offset), + parse_manip{format, tp, nullptr, &offset}) +{ + return {format, tp, nullptr, &offset}; +} + +template +inline +auto +parse(const std::basic_string& format, Parsable& tp, + std::basic_string& abbrev, std::chrono::minutes& offset) + -> decltype(from_stream(std::declval&>(), + format.c_str(), tp, &abbrev, &offset), + parse_manip{format, tp, &abbrev, &offset}) +{ + return {format, tp, &abbrev, &offset}; +} + +// const CharT* formats + +template +inline +auto +parse(const CharT* format, Parsable& tp) + -> decltype(from_stream(std::declval&>(), format, tp), + parse_manip{format, tp}) +{ + return {format, tp}; +} + +template +inline +auto +parse(const CharT* format, Parsable& tp, std::basic_string& abbrev) + -> decltype(from_stream(std::declval&>(), format, + tp, &abbrev), + parse_manip{format, tp, &abbrev}) +{ + return {format, tp, &abbrev}; +} + +template +inline +auto +parse(const CharT* format, Parsable& tp, std::chrono::minutes& offset) + -> decltype(from_stream(std::declval&>(), format, + tp, std::declval*>(), &offset), + parse_manip{format, tp, nullptr, &offset}) +{ + return {format, tp, nullptr, &offset}; +} + +template +inline +auto +parse(const CharT* format, Parsable& tp, + std::basic_string& abbrev, std::chrono::minutes& offset) + -> decltype(from_stream(std::declval&>(), format, + tp, &abbrev, &offset), + parse_manip{format, tp, &abbrev, &offset}) +{ + return {format, tp, &abbrev, &offset}; +} + +// duration streaming + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, + const std::chrono::duration& d) +{ + return os << detail::make_string::from(d.count()) + + detail::get_units(typename Period::type{}); +} + +} // namespace date + +#ifdef _MSC_VER +# pragma warning(pop) +#endif + +#ifdef __GNUC__ +# pragma GCC diagnostic pop +#endif + +#endif // DATE_H diff --git a/third_party/date/include/date/ios.h b/third_party/date/include/date/ios.h new file mode 100644 index 0000000..ee54b9d --- /dev/null +++ b/third_party/date/include/date/ios.h @@ -0,0 +1,50 @@ +// +// ios.h +// DateTimeLib +// +// The MIT License (MIT) +// +// Copyright (c) 2016 Alexander Kormanovsky +// +// 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. + +#ifndef ios_hpp +#define ios_hpp + +#if __APPLE__ +# include +# if TARGET_OS_IPHONE +# include + + namespace date + { + namespace iOSUtils + { + + std::string get_tzdata_path(); + std::string get_current_timezone(); + + } // namespace iOSUtils + } // namespace date + +# endif // TARGET_OS_IPHONE +#else // !__APPLE__ +# define TARGET_OS_IPHONE 0 +#endif // !__APPLE__ +#endif // ios_hpp diff --git a/third_party/date/include/date/islamic.h b/third_party/date/include/date/islamic.h new file mode 100644 index 0000000..82ed659 --- /dev/null +++ b/third_party/date/include/date/islamic.h @@ -0,0 +1,3031 @@ +#ifndef ISLAMIC_H +#define ISLAMIC_H + +// The MIT License (MIT) +// +// Copyright (c) 2016 Howard Hinnant +// +// 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. +// +// Our apologies. When the previous paragraph was written, lowercase had not yet +// been invented (that would involve another several millennia of evolution). +// We did not mean to shout. + +#include "date.h" + +namespace islamic +{ + +// durations + +using days = date::days; + +using weeks = date::weeks; + +using years = std::chrono::duration + , days::period>>; + +using months = std::chrono::duration + >>; + +// time_point + +using sys_days = date::sys_days; +using local_days = date::local_days; + +// types + +struct last_spec +{ + explicit last_spec() = default; +}; + +class day; +class month; +class year; + +class weekday; +class weekday_indexed; +class weekday_last; + +class month_day; +class month_day_last; +class month_weekday; +class month_weekday_last; + +class year_month; + +class year_month_day; +class year_month_day_last; +class year_month_weekday; +class year_month_weekday_last; + +// date composition operators + +CONSTCD11 year_month operator/(const year& y, const month& m) NOEXCEPT; +CONSTCD11 year_month operator/(const year& y, int m) NOEXCEPT; + +CONSTCD11 month_day operator/(const day& d, const month& m) NOEXCEPT; +CONSTCD11 month_day operator/(const day& d, int m) NOEXCEPT; +CONSTCD11 month_day operator/(const month& m, const day& d) NOEXCEPT; +CONSTCD11 month_day operator/(const month& m, int d) NOEXCEPT; +CONSTCD11 month_day operator/(int m, const day& d) NOEXCEPT; + +CONSTCD11 month_day_last operator/(const month& m, last_spec) NOEXCEPT; +CONSTCD11 month_day_last operator/(int m, last_spec) NOEXCEPT; +CONSTCD11 month_day_last operator/(last_spec, const month& m) NOEXCEPT; +CONSTCD11 month_day_last operator/(last_spec, int m) NOEXCEPT; + +CONSTCD11 month_weekday operator/(const month& m, const weekday_indexed& wdi) NOEXCEPT; +CONSTCD11 month_weekday operator/(int m, const weekday_indexed& wdi) NOEXCEPT; +CONSTCD11 month_weekday operator/(const weekday_indexed& wdi, const month& m) NOEXCEPT; +CONSTCD11 month_weekday operator/(const weekday_indexed& wdi, int m) NOEXCEPT; + +CONSTCD11 month_weekday_last operator/(const month& m, const weekday_last& wdl) NOEXCEPT; +CONSTCD11 month_weekday_last operator/(int m, const weekday_last& wdl) NOEXCEPT; +CONSTCD11 month_weekday_last operator/(const weekday_last& wdl, const month& m) NOEXCEPT; +CONSTCD11 month_weekday_last operator/(const weekday_last& wdl, int m) NOEXCEPT; + +CONSTCD11 year_month_day operator/(const year_month& ym, const day& d) NOEXCEPT; +CONSTCD11 year_month_day operator/(const year_month& ym, int d) NOEXCEPT; +CONSTCD11 year_month_day operator/(const year& y, const month_day& md) NOEXCEPT; +CONSTCD11 year_month_day operator/(int y, const month_day& md) NOEXCEPT; +CONSTCD11 year_month_day operator/(const month_day& md, const year& y) NOEXCEPT; +CONSTCD11 year_month_day operator/(const month_day& md, int y) NOEXCEPT; + +CONSTCD11 + year_month_day_last operator/(const year_month& ym, last_spec) NOEXCEPT; +CONSTCD11 + year_month_day_last operator/(const year& y, const month_day_last& mdl) NOEXCEPT; +CONSTCD11 + year_month_day_last operator/(int y, const month_day_last& mdl) NOEXCEPT; +CONSTCD11 + year_month_day_last operator/(const month_day_last& mdl, const year& y) NOEXCEPT; +CONSTCD11 + year_month_day_last operator/(const month_day_last& mdl, int y) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(const year_month& ym, const weekday_indexed& wdi) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(const year& y, const month_weekday& mwd) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(int y, const month_weekday& mwd) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(const month_weekday& mwd, const year& y) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(const month_weekday& mwd, int y) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(const year_month& ym, const weekday_last& wdl) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(const year& y, const month_weekday_last& mwdl) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(int y, const month_weekday_last& mwdl) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(const month_weekday_last& mwdl, const year& y) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(const month_weekday_last& mwdl, int y) NOEXCEPT; + +// Detailed interface + +// day + +class day +{ + unsigned char d_; + +public: + explicit CONSTCD11 day(unsigned d) NOEXCEPT; + + CONSTCD14 day& operator++() NOEXCEPT; + CONSTCD14 day operator++(int) NOEXCEPT; + CONSTCD14 day& operator--() NOEXCEPT; + CONSTCD14 day operator--(int) NOEXCEPT; + + CONSTCD14 day& operator+=(const days& d) NOEXCEPT; + CONSTCD14 day& operator-=(const days& d) NOEXCEPT; + + CONSTCD11 explicit operator unsigned() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator!=(const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator< (const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator> (const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator<=(const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator>=(const day& x, const day& y) NOEXCEPT; + +CONSTCD11 day operator+(const day& x, const days& y) NOEXCEPT; +CONSTCD11 day operator+(const days& x, const day& y) NOEXCEPT; +CONSTCD11 day operator-(const day& x, const days& y) NOEXCEPT; +CONSTCD11 days operator-(const day& x, const day& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const day& d); + +// month + +class month +{ + unsigned char m_; + +public: + explicit CONSTCD11 month(unsigned m) NOEXCEPT; + + CONSTCD14 month& operator++() NOEXCEPT; + CONSTCD14 month operator++(int) NOEXCEPT; + CONSTCD14 month& operator--() NOEXCEPT; + CONSTCD14 month operator--(int) NOEXCEPT; + + CONSTCD14 month& operator+=(const months& m) NOEXCEPT; + CONSTCD14 month& operator-=(const months& m) NOEXCEPT; + + CONSTCD11 explicit operator unsigned() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator!=(const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator< (const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator> (const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator<=(const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator>=(const month& x, const month& y) NOEXCEPT; + +CONSTCD14 month operator+(const month& x, const months& y) NOEXCEPT; +CONSTCD14 month operator+(const months& x, const month& y) NOEXCEPT; +CONSTCD14 month operator-(const month& x, const months& y) NOEXCEPT; +CONSTCD14 months operator-(const month& x, const month& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month& m); + +// year + +class year +{ + short y_; + +public: + explicit CONSTCD11 year(int y) NOEXCEPT; + + CONSTCD14 year& operator++() NOEXCEPT; + CONSTCD14 year operator++(int) NOEXCEPT; + CONSTCD14 year& operator--() NOEXCEPT; + CONSTCD14 year operator--(int) NOEXCEPT; + + CONSTCD14 year& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year& operator-=(const years& y) NOEXCEPT; + + CONSTCD14 bool is_leap() const NOEXCEPT; + + CONSTCD11 explicit operator int() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; + + static CONSTCD11 year min() NOEXCEPT; + static CONSTCD11 year max() NOEXCEPT; +}; + +CONSTCD11 bool operator==(const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator< (const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator> (const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year& x, const year& y) NOEXCEPT; + +CONSTCD11 year operator+(const year& x, const years& y) NOEXCEPT; +CONSTCD11 year operator+(const years& x, const year& y) NOEXCEPT; +CONSTCD11 year operator-(const year& x, const years& y) NOEXCEPT; +CONSTCD11 years operator-(const year& x, const year& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year& y); + +// weekday + +class weekday +{ + unsigned char wd_; +public: + explicit CONSTCD11 weekday(unsigned wd) NOEXCEPT; + explicit weekday(int) = delete; + CONSTCD11 weekday(const sys_days& dp) NOEXCEPT; + CONSTCD11 explicit weekday(const local_days& dp) NOEXCEPT; + + CONSTCD14 weekday& operator++() NOEXCEPT; + CONSTCD14 weekday operator++(int) NOEXCEPT; + CONSTCD14 weekday& operator--() NOEXCEPT; + CONSTCD14 weekday operator--(int) NOEXCEPT; + + CONSTCD14 weekday& operator+=(const days& d) NOEXCEPT; + CONSTCD14 weekday& operator-=(const days& d) NOEXCEPT; + + CONSTCD11 explicit operator unsigned() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; + + CONSTCD11 weekday_indexed operator[](unsigned index) const NOEXCEPT; + CONSTCD11 weekday_last operator[](last_spec) const NOEXCEPT; + +private: + static CONSTCD11 unsigned char weekday_from_days(int z) NOEXCEPT; +}; + +CONSTCD11 bool operator==(const weekday& x, const weekday& y) NOEXCEPT; +CONSTCD11 bool operator!=(const weekday& x, const weekday& y) NOEXCEPT; + +CONSTCD14 weekday operator+(const weekday& x, const days& y) NOEXCEPT; +CONSTCD14 weekday operator+(const days& x, const weekday& y) NOEXCEPT; +CONSTCD14 weekday operator-(const weekday& x, const days& y) NOEXCEPT; +CONSTCD14 days operator-(const weekday& x, const weekday& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday& wd); + +// weekday_indexed + +class weekday_indexed +{ + unsigned char wd_ : 4; + unsigned char index_ : 4; + +public: + CONSTCD11 weekday_indexed(const islamic::weekday& wd, unsigned index) NOEXCEPT; + + CONSTCD11 islamic::weekday weekday() const NOEXCEPT; + CONSTCD11 unsigned index() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT; +CONSTCD11 bool operator!=(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday_indexed& wdi); + +// weekday_last + +class weekday_last +{ + islamic::weekday wd_; + +public: + explicit CONSTCD11 weekday_last(const islamic::weekday& wd) NOEXCEPT; + + CONSTCD11 islamic::weekday weekday() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const weekday_last& x, const weekday_last& y) NOEXCEPT; +CONSTCD11 bool operator!=(const weekday_last& x, const weekday_last& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday_last& wdl); + +// year_month + +class year_month +{ + islamic::year y_; + islamic::month m_; + +public: + CONSTCD11 year_month(const islamic::year& y, const islamic::month& m) NOEXCEPT; + + CONSTCD11 islamic::year year() const NOEXCEPT; + CONSTCD11 islamic::month month() const NOEXCEPT; + + CONSTCD14 year_month& operator+=(const months& dm) NOEXCEPT; + CONSTCD14 year_month& operator-=(const months& dm) NOEXCEPT; + CONSTCD14 year_month& operator+=(const years& dy) NOEXCEPT; + CONSTCD14 year_month& operator-=(const years& dy) NOEXCEPT; + + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator< (const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator> (const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year_month& x, const year_month& y) NOEXCEPT; + +CONSTCD14 year_month operator+(const year_month& ym, const months& dm) NOEXCEPT; +CONSTCD14 year_month operator+(const months& dm, const year_month& ym) NOEXCEPT; +CONSTCD14 year_month operator-(const year_month& ym, const months& dm) NOEXCEPT; + +CONSTCD11 months operator-(const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 year_month operator+(const year_month& ym, const years& dy) NOEXCEPT; +CONSTCD11 year_month operator+(const years& dy, const year_month& ym) NOEXCEPT; +CONSTCD11 year_month operator-(const year_month& ym, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month& ym); + +// month_day + +class month_day +{ + islamic::month m_; + islamic::day d_; + +public: + CONSTCD11 month_day(const islamic::month& m, const islamic::day& d) NOEXCEPT; + + CONSTCD11 islamic::month month() const NOEXCEPT; + CONSTCD11 islamic::day day() const NOEXCEPT; + + CONSTCD14 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator!=(const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator< (const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator> (const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator<=(const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator>=(const month_day& x, const month_day& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_day& md); + +// month_day_last + +class month_day_last +{ + islamic::month m_; + +public: + CONSTCD11 explicit month_day_last(const islamic::month& m) NOEXCEPT; + + CONSTCD11 islamic::month month() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator!=(const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator< (const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator> (const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator<=(const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator>=(const month_day_last& x, const month_day_last& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_day_last& mdl); + +// month_weekday + +class month_weekday +{ + islamic::month m_; + islamic::weekday_indexed wdi_; +public: + CONSTCD11 month_weekday(const islamic::month& m, + const islamic::weekday_indexed& wdi) NOEXCEPT; + + CONSTCD11 islamic::month month() const NOEXCEPT; + CONSTCD11 islamic::weekday_indexed weekday_indexed() const NOEXCEPT; + + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const month_weekday& x, const month_weekday& y) NOEXCEPT; +CONSTCD11 bool operator!=(const month_weekday& x, const month_weekday& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_weekday& mwd); + +// month_weekday_last + +class month_weekday_last +{ + islamic::month m_; + islamic::weekday_last wdl_; + +public: + CONSTCD11 month_weekday_last(const islamic::month& m, + const islamic::weekday_last& wd) NOEXCEPT; + + CONSTCD11 islamic::month month() const NOEXCEPT; + CONSTCD11 islamic::weekday_last weekday_last() const NOEXCEPT; + + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 + bool operator==(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT; +CONSTCD11 + bool operator!=(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_weekday_last& mwdl); + +// class year_month_day + +class year_month_day +{ + islamic::year y_; + islamic::month m_; + islamic::day d_; + +public: + CONSTCD11 year_month_day(const islamic::year& y, const islamic::month& m, + const islamic::day& d) NOEXCEPT; + CONSTCD14 year_month_day(const year_month_day_last& ymdl) NOEXCEPT; + + CONSTCD14 year_month_day(sys_days dp) NOEXCEPT; + CONSTCD14 explicit year_month_day(local_days dp) NOEXCEPT; + + CONSTCD14 year_month_day& operator+=(const months& m) NOEXCEPT; + CONSTCD14 year_month_day& operator-=(const months& m) NOEXCEPT; + CONSTCD14 year_month_day& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year_month_day& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 islamic::year year() const NOEXCEPT; + CONSTCD11 islamic::month month() const NOEXCEPT; + CONSTCD11 islamic::day day() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD14 bool ok() const NOEXCEPT; + +private: + static CONSTCD14 year_month_day from_days(days dp) NOEXCEPT; + CONSTCD14 days to_days() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator< (const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator> (const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year_month_day& x, const year_month_day& y) NOEXCEPT; + +CONSTCD14 year_month_day operator+(const year_month_day& ymd, const months& dm) NOEXCEPT; +CONSTCD14 year_month_day operator+(const months& dm, const year_month_day& ymd) NOEXCEPT; +CONSTCD14 year_month_day operator-(const year_month_day& ymd, const months& dm) NOEXCEPT; +CONSTCD11 year_month_day operator+(const year_month_day& ymd, const years& dy) NOEXCEPT; +CONSTCD11 year_month_day operator+(const years& dy, const year_month_day& ymd) NOEXCEPT; +CONSTCD11 year_month_day operator-(const year_month_day& ymd, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_day& ymd); + +// year_month_day_last + +class year_month_day_last +{ + islamic::year y_; + islamic::month_day_last mdl_; + +public: + CONSTCD11 year_month_day_last(const islamic::year& y, + const islamic::month_day_last& mdl) NOEXCEPT; + + CONSTCD14 year_month_day_last& operator+=(const months& m) NOEXCEPT; + CONSTCD14 year_month_day_last& operator-=(const months& m) NOEXCEPT; + CONSTCD14 year_month_day_last& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year_month_day_last& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 islamic::year year() const NOEXCEPT; + CONSTCD11 islamic::month month() const NOEXCEPT; + CONSTCD11 islamic::month_day_last month_day_last() const NOEXCEPT; + CONSTCD14 islamic::day day() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 + bool operator==(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator!=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator< (const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator> (const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator<=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator>=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; + +CONSTCD14 +year_month_day_last +operator+(const year_month_day_last& ymdl, const months& dm) NOEXCEPT; + +CONSTCD14 +year_month_day_last +operator+(const months& dm, const year_month_day_last& ymdl) NOEXCEPT; + +CONSTCD11 +year_month_day_last +operator+(const year_month_day_last& ymdl, const years& dy) NOEXCEPT; + +CONSTCD11 +year_month_day_last +operator+(const years& dy, const year_month_day_last& ymdl) NOEXCEPT; + +CONSTCD14 +year_month_day_last +operator-(const year_month_day_last& ymdl, const months& dm) NOEXCEPT; + +CONSTCD11 +year_month_day_last +operator-(const year_month_day_last& ymdl, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_day_last& ymdl); + +// year_month_weekday + +class year_month_weekday +{ + islamic::year y_; + islamic::month m_; + islamic::weekday_indexed wdi_; + +public: + CONSTCD11 year_month_weekday(const islamic::year& y, const islamic::month& m, + const islamic::weekday_indexed& wdi) NOEXCEPT; + CONSTCD14 year_month_weekday(const sys_days& dp) NOEXCEPT; + CONSTCD14 explicit year_month_weekday(const local_days& dp) NOEXCEPT; + + CONSTCD14 year_month_weekday& operator+=(const months& m) NOEXCEPT; + CONSTCD14 year_month_weekday& operator-=(const months& m) NOEXCEPT; + CONSTCD14 year_month_weekday& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year_month_weekday& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 islamic::year year() const NOEXCEPT; + CONSTCD11 islamic::month month() const NOEXCEPT; + CONSTCD11 islamic::weekday weekday() const NOEXCEPT; + CONSTCD11 unsigned index() const NOEXCEPT; + CONSTCD11 islamic::weekday_indexed weekday_indexed() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD14 bool ok() const NOEXCEPT; + +private: + static CONSTCD14 year_month_weekday from_days(days dp) NOEXCEPT; + CONSTCD14 days to_days() const NOEXCEPT; +}; + +CONSTCD11 + bool operator==(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT; +CONSTCD11 + bool operator!=(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT; + +CONSTCD14 +year_month_weekday +operator+(const year_month_weekday& ymwd, const months& dm) NOEXCEPT; + +CONSTCD14 +year_month_weekday +operator+(const months& dm, const year_month_weekday& ymwd) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator+(const year_month_weekday& ymwd, const years& dy) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator+(const years& dy, const year_month_weekday& ymwd) NOEXCEPT; + +CONSTCD14 +year_month_weekday +operator-(const year_month_weekday& ymwd, const months& dm) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator-(const year_month_weekday& ymwd, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_weekday& ymwdi); + +// year_month_weekday_last + +class year_month_weekday_last +{ + islamic::year y_; + islamic::month m_; + islamic::weekday_last wdl_; + +public: + CONSTCD11 year_month_weekday_last(const islamic::year& y, const islamic::month& m, + const islamic::weekday_last& wdl) NOEXCEPT; + + CONSTCD14 year_month_weekday_last& operator+=(const months& m) NOEXCEPT; + CONSTCD14 year_month_weekday_last& operator-=(const months& m) NOEXCEPT; + CONSTCD14 year_month_weekday_last& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year_month_weekday_last& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 islamic::year year() const NOEXCEPT; + CONSTCD11 islamic::month month() const NOEXCEPT; + CONSTCD11 islamic::weekday weekday() const NOEXCEPT; + CONSTCD11 islamic::weekday_last weekday_last() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; + +private: + CONSTCD14 days to_days() const NOEXCEPT; +}; + +CONSTCD11 +bool +operator==(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT; + +CONSTCD11 +bool +operator!=(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT; + +CONSTCD14 +year_month_weekday_last +operator+(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT; + +CONSTCD14 +year_month_weekday_last +operator+(const months& dm, const year_month_weekday_last& ymwdl) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator+(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator+(const years& dy, const year_month_weekday_last& ymwdl) NOEXCEPT; + +CONSTCD14 +year_month_weekday_last +operator-(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator-(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_weekday_last& ymwdl); + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) +inline namespace literals +{ + +CONSTCD11 islamic::day operator "" _d(unsigned long long d) NOEXCEPT; +CONSTCD11 islamic::year operator "" _y(unsigned long long y) NOEXCEPT; + +} // inline namespace literals +#endif // !defined(_MSC_VER) || (_MSC_VER >= 1900) + +//----------------+ +// Implementation | +//----------------+ + +// day + +CONSTCD11 inline day::day(unsigned d) NOEXCEPT : d_(static_cast(d)) {} +CONSTCD14 inline day& day::operator++() NOEXCEPT {++d_; return *this;} +CONSTCD14 inline day day::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +CONSTCD14 inline day& day::operator--() NOEXCEPT {--d_; return *this;} +CONSTCD14 inline day day::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} +CONSTCD14 inline day& day::operator+=(const days& d) NOEXCEPT {*this = *this + d; return *this;} +CONSTCD14 inline day& day::operator-=(const days& d) NOEXCEPT {*this = *this - d; return *this;} +CONSTCD11 inline day::operator unsigned() const NOEXCEPT {return d_;} +CONSTCD11 inline bool day::ok() const NOEXCEPT {return 1 <= d_ && d_ <= 30;} + +CONSTCD11 +inline +bool +operator==(const day& x, const day& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const day& x, const day& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const day& x, const day& y) NOEXCEPT +{ + return static_cast(x) < static_cast(y); +} + +CONSTCD11 +inline +bool +operator>(const day& x, const day& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const day& x, const day& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const day& x, const day& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD11 +inline +days +operator-(const day& x, const day& y) NOEXCEPT +{ + return days{static_cast(static_cast(x) + - static_cast(y))}; +} + +CONSTCD11 +inline +day +operator+(const day& x, const days& y) NOEXCEPT +{ + return day{static_cast(x) + static_cast(y.count())}; +} + +CONSTCD11 +inline +day +operator+(const days& x, const day& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD11 +inline +day +operator-(const day& x, const days& y) NOEXCEPT +{ + return x + -y; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const day& d) +{ + date::detail::save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::right); + os.width(2); + os << static_cast(d); + return os; +} + +// month + +CONSTCD11 inline month::month(unsigned m) NOEXCEPT : m_(static_cast(m)) {} +CONSTCD14 inline month& month::operator++() NOEXCEPT {if (++m_ == 13) m_ = 1; return *this;} +CONSTCD14 inline month month::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +CONSTCD14 inline month& month::operator--() NOEXCEPT {if (--m_ == 0) m_ = 12; return *this;} +CONSTCD14 inline month month::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} + +CONSTCD14 +inline +month& +month::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +CONSTCD14 +inline +month& +month::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD11 inline month::operator unsigned() const NOEXCEPT {return m_;} +CONSTCD11 inline bool month::ok() const NOEXCEPT {return 1 <= m_ && m_ <= 12;} + +CONSTCD11 +inline +bool +operator==(const month& x, const month& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const month& x, const month& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const month& x, const month& y) NOEXCEPT +{ + return static_cast(x) < static_cast(y); +} + +CONSTCD11 +inline +bool +operator>(const month& x, const month& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const month& x, const month& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const month& x, const month& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD14 +inline +months +operator-(const month& x, const month& y) NOEXCEPT +{ + auto const d = static_cast(x) - static_cast(y); + return months(d <= 11 ? d : d + 12); +} + +CONSTCD14 +inline +month +operator+(const month& x, const months& y) NOEXCEPT +{ + auto const mu = static_cast(static_cast(x)) - 1 + y.count(); + auto const yr = (mu >= 0 ? mu : mu-11) / 12; + return month{static_cast(mu - yr * 12 + 1)}; +} + +CONSTCD14 +inline +month +operator+(const months& x, const month& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD14 +inline +month +operator-(const month& x, const months& y) NOEXCEPT +{ + return x + -y; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month& m) +{ + switch (static_cast(m)) + { + case 1: + os << "Muharram"; + break; + case 2: + os << "Safar"; + break; + case 3: + os << "Rabi' al-awwal"; + break; + case 4: + os << "Rabi' al-thani"; + break; + case 5: + os << "Jumada al-awwal"; + break; + case 6: + os << "Jumada al-Thani"; + break; + case 7: + os << "Rajab"; + break; + case 8: + os << "Sha'ban"; + break; + case 9: + os << "Ramadan"; + break; + case 10: + os << "Shawwal"; + break; + case 11: + os << "Dhu al-Qi'dah"; + break; + case 12: + os << "Dhu al-Hijjah"; + break; + default: + os << static_cast(m) << " is not a valid month"; + break; + } + return os; +} + +// year + +CONSTCD11 inline year::year(int y) NOEXCEPT : y_(static_cast(y)) {} +CONSTCD14 inline year& year::operator++() NOEXCEPT {++y_; return *this;} +CONSTCD14 inline year year::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +CONSTCD14 inline year& year::operator--() NOEXCEPT {--y_; return *this;} +CONSTCD14 inline year year::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} +CONSTCD14 inline year& year::operator+=(const years& y) NOEXCEPT {*this = *this + y; return *this;} +CONSTCD14 inline year& year::operator-=(const years& y) NOEXCEPT {*this = *this - y; return *this;} + +CONSTCD14 +inline +bool +year::is_leap() const NOEXCEPT +{ + int y = y_ - 1; + const int era = (y >= 0 ? y : y-29) / 30; + const unsigned yoe = static_cast(y - era * 30); + switch (yoe) + { + case 1: + case 4: + case 6: + case 9: + case 12: + case 15: + case 17: + case 20: + case 23: + case 25: + case 28: + return true; + default: + return false; + } +} + +CONSTCD11 inline year::operator int() const NOEXCEPT {return y_;} +CONSTCD11 inline bool year::ok() const NOEXCEPT {return true;} + +CONSTCD11 +inline +year +year::min() NOEXCEPT +{ + return year{std::numeric_limits::min()}; +} + +CONSTCD11 +inline +year +year::max() NOEXCEPT +{ + return year{std::numeric_limits::max()}; +} + +CONSTCD11 +inline +bool +operator==(const year& x, const year& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const year& x, const year& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year& x, const year& y) NOEXCEPT +{ + return static_cast(x) < static_cast(y); +} + +CONSTCD11 +inline +bool +operator>(const year& x, const year& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year& x, const year& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year& x, const year& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD11 +inline +years +operator-(const year& x, const year& y) NOEXCEPT +{ + return years{static_cast(x) - static_cast(y)}; +} + +CONSTCD11 +inline +year +operator+(const year& x, const years& y) NOEXCEPT +{ + return year{static_cast(x) + y.count()}; +} + +CONSTCD11 +inline +year +operator+(const years& x, const year& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD11 +inline +year +operator-(const year& x, const years& y) NOEXCEPT +{ + return year{static_cast(x) - y.count()}; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year& y) +{ + date::detail::save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::internal); + os.width(4 + (y < year{0})); + os << static_cast(y); + return os; +} + +// weekday + +CONSTCD11 +inline +unsigned char +weekday::weekday_from_days(int z) NOEXCEPT +{ + return static_cast(static_cast( + z >= -4 ? (z+4) % 7 : (z+5) % 7 + 6)); +} + +CONSTCD11 +inline +weekday::weekday(unsigned wd) NOEXCEPT + : wd_(static_cast(wd)) + {} + +CONSTCD11 +inline +weekday::weekday(const sys_days& dp) NOEXCEPT + : wd_(weekday_from_days(dp.time_since_epoch().count())) + {} + +CONSTCD11 +inline +weekday::weekday(const local_days& dp) NOEXCEPT + : wd_(weekday_from_days(dp.time_since_epoch().count())) + {} + +CONSTCD14 inline weekday& weekday::operator++() NOEXCEPT {if (++wd_ == 7) wd_ = 0; return *this;} +CONSTCD14 inline weekday weekday::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +CONSTCD14 inline weekday& weekday::operator--() NOEXCEPT {if (wd_-- == 0) wd_ = 6; return *this;} +CONSTCD14 inline weekday weekday::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} + +CONSTCD14 +inline +weekday& +weekday::operator+=(const days& d) NOEXCEPT +{ + *this = *this + d; + return *this; +} + +CONSTCD14 +inline +weekday& +weekday::operator-=(const days& d) NOEXCEPT +{ + *this = *this - d; + return *this; +} + +CONSTCD11 +inline +weekday::operator unsigned() const NOEXCEPT +{ + return static_cast(wd_); +} + +CONSTCD11 inline bool weekday::ok() const NOEXCEPT {return wd_ <= 6;} + +CONSTCD11 +inline +bool +operator==(const weekday& x, const weekday& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const weekday& x, const weekday& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD14 +inline +days +operator-(const weekday& x, const weekday& y) NOEXCEPT +{ + auto const diff = static_cast(x) - static_cast(y); + return days{diff <= 6 ? diff : diff + 7}; +} + +CONSTCD14 +inline +weekday +operator+(const weekday& x, const days& y) NOEXCEPT +{ + auto const wdu = static_cast(static_cast(x)) + y.count(); + auto const wk = (wdu >= 0 ? wdu : wdu-6) / 7; + return weekday{static_cast(wdu - wk * 7)}; +} + +CONSTCD14 +inline +weekday +operator+(const days& x, const weekday& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD14 +inline +weekday +operator-(const weekday& x, const days& y) NOEXCEPT +{ + return x + -y; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday& wd) +{ + switch (static_cast(wd)) + { + case 0: + os << "al-Aḥad"; + break; + case 1: + os << "al-Ithnayn"; + break; + case 2: + os << "ath-ThulÄthÄ’"; + break; + case 3: + os << "al-Arba‘Ä’"; + break; + case 4: + os << "al-KhamÄ«s"; + break; + case 5: + os << "al-Jum‘ah"; + break; + case 6: + os << "as-Sabt"; + break; + default: + os << static_cast(wd) << " is not a valid weekday"; + break; + } + return os; +} + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) +inline namespace literals +{ + +CONSTCD11 +inline +islamic::day +operator "" _d(unsigned long long d) NOEXCEPT +{ + return islamic::day{static_cast(d)}; +} + +CONSTCD11 +inline +islamic::year +operator "" _y(unsigned long long y) NOEXCEPT +{ + return islamic::year(static_cast(y)); +} +#endif // !defined(_MSC_VER) || (_MSC_VER >= 1900) + +CONSTDATA islamic::last_spec last{}; + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) +} // inline namespace literals +#endif + +// weekday_indexed + +CONSTCD11 +inline +weekday +weekday_indexed::weekday() const NOEXCEPT +{ + return islamic::weekday{static_cast(wd_)}; +} + +CONSTCD11 inline unsigned weekday_indexed::index() const NOEXCEPT {return index_;} + +CONSTCD11 +inline +bool +weekday_indexed::ok() const NOEXCEPT +{ + return weekday().ok() && 1 <= index_ && index_ <= 5; +} + +CONSTCD11 +inline +weekday_indexed::weekday_indexed(const islamic::weekday& wd, unsigned index) NOEXCEPT + : wd_(static_cast(static_cast(wd))) + , index_(static_cast(index)) + {} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday_indexed& wdi) +{ + return os << wdi.weekday() << '[' << wdi.index() << ']'; +} + +CONSTCD11 +inline +weekday_indexed +weekday::operator[](unsigned index) const NOEXCEPT +{ + return {*this, index}; +} + +CONSTCD11 +inline +bool +operator==(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT +{ + return x.weekday() == y.weekday() && x.index() == y.index(); +} + +CONSTCD11 +inline +bool +operator!=(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT +{ + return !(x == y); +} + +// weekday_last + +CONSTCD11 inline islamic::weekday weekday_last::weekday() const NOEXCEPT {return wd_;} +CONSTCD11 inline bool weekday_last::ok() const NOEXCEPT {return wd_.ok();} +CONSTCD11 inline weekday_last::weekday_last(const islamic::weekday& wd) NOEXCEPT : wd_(wd) {} + +CONSTCD11 +inline +bool +operator==(const weekday_last& x, const weekday_last& y) NOEXCEPT +{ + return x.weekday() == y.weekday(); +} + +CONSTCD11 +inline +bool +operator!=(const weekday_last& x, const weekday_last& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday_last& wdl) +{ + return os << wdl.weekday() << "[last]"; +} + +CONSTCD11 +inline +weekday_last +weekday::operator[](last_spec) const NOEXCEPT +{ + return weekday_last{*this}; +} + +// year_month + +CONSTCD11 +inline +year_month::year_month(const islamic::year& y, const islamic::month& m) NOEXCEPT + : y_(y) + , m_(m) + {} + +CONSTCD11 inline year year_month::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month::month() const NOEXCEPT {return m_;} +CONSTCD11 inline bool year_month::ok() const NOEXCEPT {return y_.ok() && m_.ok();} + +CONSTCD14 +inline +year_month& +year_month::operator+=(const months& dm) NOEXCEPT +{ + *this = *this + dm; + return *this; +} + +CONSTCD14 +inline +year_month& +year_month::operator-=(const months& dm) NOEXCEPT +{ + *this = *this - dm; + return *this; +} + +CONSTCD14 +inline +year_month& +year_month::operator+=(const years& dy) NOEXCEPT +{ + *this = *this + dy; + return *this; +} + +CONSTCD14 +inline +year_month& +year_month::operator-=(const years& dy) NOEXCEPT +{ + *this = *this - dy; + return *this; +} + +CONSTCD11 +inline +bool +operator==(const year_month& x, const year_month& y) NOEXCEPT +{ + return x.year() == y.year() && x.month() == y.month(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month& x, const year_month& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year_month& x, const year_month& y) NOEXCEPT +{ + return x.year() < y.year() ? true + : (x.year() > y.year() ? false + : (x.month() < y.month())); +} + +CONSTCD11 +inline +bool +operator>(const year_month& x, const year_month& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year_month& x, const year_month& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year_month& x, const year_month& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD14 +inline +year_month +operator+(const year_month& ym, const months& dm) NOEXCEPT +{ + auto dmi = static_cast(static_cast(ym.month())) - 1 + dm.count(); + auto dy = (dmi >= 0 ? dmi : dmi-11) / 12; + dmi = dmi - dy * 12 + 1; + return (ym.year() + years(dy)) / month(static_cast(dmi)); +} + +CONSTCD14 +inline +year_month +operator+(const months& dm, const year_month& ym) NOEXCEPT +{ + return ym + dm; +} + +CONSTCD14 +inline +year_month +operator-(const year_month& ym, const months& dm) NOEXCEPT +{ + return ym + -dm; +} + +CONSTCD11 +inline +months +operator-(const year_month& x, const year_month& y) NOEXCEPT +{ + return (x.year() - y.year()) + + months(static_cast(x.month()) - static_cast(y.month())); +} + +CONSTCD11 +inline +year_month +operator+(const year_month& ym, const years& dy) NOEXCEPT +{ + return (ym.year() + dy) / ym.month(); +} + +CONSTCD11 +inline +year_month +operator+(const years& dy, const year_month& ym) NOEXCEPT +{ + return ym + dy; +} + +CONSTCD11 +inline +year_month +operator-(const year_month& ym, const years& dy) NOEXCEPT +{ + return ym + -dy; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month& ym) +{ + return os << ym.year() << '/' << ym.month(); +} + +// month_day + +CONSTCD11 +inline +month_day::month_day(const islamic::month& m, const islamic::day& d) NOEXCEPT + : m_(m) + , d_(d) + {} + +CONSTCD11 inline islamic::month month_day::month() const NOEXCEPT {return m_;} +CONSTCD11 inline islamic::day month_day::day() const NOEXCEPT {return d_;} + +CONSTCD14 +inline +bool +month_day::ok() const NOEXCEPT +{ + CONSTDATA islamic::day d[] = + {30_d, 29_d, 30_d, 29_d, 30_d, 29_d, 30_d, 29_d, 30_d, 29_d, 30_d, 30_d}; + return m_.ok() && 1_d <= d_ && d_ <= d[static_cast(m_)-1]; +} + +CONSTCD11 +inline +bool +operator==(const month_day& x, const month_day& y) NOEXCEPT +{ + return x.month() == y.month() && x.day() == y.day(); +} + +CONSTCD11 +inline +bool +operator!=(const month_day& x, const month_day& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const month_day& x, const month_day& y) NOEXCEPT +{ + return x.month() < y.month() ? true + : (x.month() > y.month() ? false + : (x.day() < y.day())); +} + +CONSTCD11 +inline +bool +operator>(const month_day& x, const month_day& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const month_day& x, const month_day& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const month_day& x, const month_day& y) NOEXCEPT +{ + return !(x < y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_day& md) +{ + return os << md.month() << '/' << md.day(); +} + +// month_day_last + +CONSTCD11 inline month month_day_last::month() const NOEXCEPT {return m_;} +CONSTCD11 inline bool month_day_last::ok() const NOEXCEPT {return m_.ok();} +CONSTCD11 inline month_day_last::month_day_last(const islamic::month& m) NOEXCEPT : m_(m) {} + +CONSTCD11 +inline +bool +operator==(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return x.month() == y.month(); +} + +CONSTCD11 +inline +bool +operator!=(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return x.month() < y.month(); +} + +CONSTCD11 +inline +bool +operator>(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return !(x < y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_day_last& mdl) +{ + return os << mdl.month() << "/last"; +} + +// month_weekday + +CONSTCD11 +inline +month_weekday::month_weekday(const islamic::month& m, + const islamic::weekday_indexed& wdi) NOEXCEPT + : m_(m) + , wdi_(wdi) + {} + +CONSTCD11 inline month month_weekday::month() const NOEXCEPT {return m_;} + +CONSTCD11 +inline +weekday_indexed +month_weekday::weekday_indexed() const NOEXCEPT +{ + return wdi_; +} + +CONSTCD11 +inline +bool +month_weekday::ok() const NOEXCEPT +{ + return m_.ok() && wdi_.ok(); +} + +CONSTCD11 +inline +bool +operator==(const month_weekday& x, const month_weekday& y) NOEXCEPT +{ + return x.month() == y.month() && x.weekday_indexed() == y.weekday_indexed(); +} + +CONSTCD11 +inline +bool +operator!=(const month_weekday& x, const month_weekday& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_weekday& mwd) +{ + return os << mwd.month() << '/' << mwd.weekday_indexed(); +} + +// month_weekday_last + +CONSTCD11 +inline +month_weekday_last::month_weekday_last(const islamic::month& m, + const islamic::weekday_last& wdl) NOEXCEPT + : m_(m) + , wdl_(wdl) + {} + +CONSTCD11 inline month month_weekday_last::month() const NOEXCEPT {return m_;} + +CONSTCD11 +inline +weekday_last +month_weekday_last::weekday_last() const NOEXCEPT +{ + return wdl_; +} + +CONSTCD11 +inline +bool +month_weekday_last::ok() const NOEXCEPT +{ + return m_.ok() && wdl_.ok(); +} + +CONSTCD11 +inline +bool +operator==(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT +{ + return x.month() == y.month() && x.weekday_last() == y.weekday_last(); +} + +CONSTCD11 +inline +bool +operator!=(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_weekday_last& mwdl) +{ + return os << mwdl.month() << '/' << mwdl.weekday_last(); +} + +// year_month_day_last + +CONSTCD11 +inline +year_month_day_last::year_month_day_last(const islamic::year& y, + const islamic::month_day_last& mdl) NOEXCEPT + : y_(y) + , mdl_(mdl) + {} + +CONSTCD14 +inline +year_month_day_last& +year_month_day_last::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +CONSTCD14 +inline +year_month_day_last& +year_month_day_last::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD14 +inline +year_month_day_last& +year_month_day_last::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +CONSTCD14 +inline +year_month_day_last& +year_month_day_last::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD11 inline year year_month_day_last::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month_day_last::month() const NOEXCEPT {return mdl_.month();} + +CONSTCD11 +inline +month_day_last +year_month_day_last::month_day_last() const NOEXCEPT +{ + return mdl_; +} + +CONSTCD14 +inline +day +year_month_day_last::day() const NOEXCEPT +{ + CONSTDATA islamic::day d[] = + {30_d, 29_d, 30_d, 29_d, 30_d, 29_d, 30_d, 29_d, 30_d, 29_d, 30_d, 29_d}; + return month() != islamic::month(12) || !y_.is_leap() ? + d[static_cast(month())-1] : 30_d; +} + +CONSTCD14 +inline +year_month_day_last::operator sys_days() const NOEXCEPT +{ + return sys_days(year()/month()/day()); +} + +CONSTCD14 +inline +year_month_day_last::operator local_days() const NOEXCEPT +{ + return local_days(year()/month()/day()); +} + +CONSTCD11 +inline +bool +year_month_day_last::ok() const NOEXCEPT +{ + return y_.ok() && mdl_.ok(); +} + +CONSTCD11 +inline +bool +operator==(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return x.year() == y.year() && x.month_day_last() == y.month_day_last(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return x.year() < y.year() ? true + : (x.year() > y.year() ? false + : (x.month_day_last() < y.month_day_last())); +} + +CONSTCD11 +inline +bool +operator>(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return !(x < y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_day_last& ymdl) +{ + return os << ymdl.year() << '/' << ymdl.month_day_last(); +} + +CONSTCD14 +inline +year_month_day_last +operator+(const year_month_day_last& ymdl, const months& dm) NOEXCEPT +{ + return (ymdl.year() / ymdl.month() + dm) / last; +} + +CONSTCD14 +inline +year_month_day_last +operator+(const months& dm, const year_month_day_last& ymdl) NOEXCEPT +{ + return ymdl + dm; +} + +CONSTCD14 +inline +year_month_day_last +operator-(const year_month_day_last& ymdl, const months& dm) NOEXCEPT +{ + return ymdl + (-dm); +} + +CONSTCD11 +inline +year_month_day_last +operator+(const year_month_day_last& ymdl, const years& dy) NOEXCEPT +{ + return {ymdl.year()+dy, ymdl.month_day_last()}; +} + +CONSTCD11 +inline +year_month_day_last +operator+(const years& dy, const year_month_day_last& ymdl) NOEXCEPT +{ + return ymdl + dy; +} + +CONSTCD11 +inline +year_month_day_last +operator-(const year_month_day_last& ymdl, const years& dy) NOEXCEPT +{ + return ymdl + (-dy); +} + +// year_month_day + +CONSTCD11 +inline +year_month_day::year_month_day(const islamic::year& y, const islamic::month& m, + const islamic::day& d) NOEXCEPT + : y_(y) + , m_(m) + , d_(d) + {} + +CONSTCD14 +inline +year_month_day::year_month_day(const year_month_day_last& ymdl) NOEXCEPT + : y_(ymdl.year()) + , m_(ymdl.month()) + , d_(ymdl.day()) + {} + +CONSTCD14 +inline +year_month_day::year_month_day(sys_days dp) NOEXCEPT + : year_month_day(from_days(dp.time_since_epoch())) + {} + +CONSTCD14 +inline +year_month_day::year_month_day(local_days dp) NOEXCEPT + : year_month_day(from_days(dp.time_since_epoch())) + {} + +CONSTCD11 inline year year_month_day::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month_day::month() const NOEXCEPT {return m_;} +CONSTCD11 inline day year_month_day::day() const NOEXCEPT {return d_;} + +CONSTCD14 +inline +year_month_day& +year_month_day::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +CONSTCD14 +inline +year_month_day& +year_month_day::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD14 +inline +year_month_day& +year_month_day::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +CONSTCD14 +inline +year_month_day& +year_month_day::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD14 +inline +days +year_month_day::to_days() const NOEXCEPT +{ + static_assert(std::numeric_limits::digits >= 18, + "This algorithm has not been ported to a 16 bit unsigned integer"); + static_assert(std::numeric_limits::digits >= 20, + "This algorithm has not been ported to a 16 bit signed integer"); + auto const y = static_cast(y_) - 1; + auto const m = static_cast(m_); + auto const d = static_cast(d_); + auto const era = (y >= 0 ? y : y-29) / 30; + auto const yoe = static_cast(y - era * 30); // [0, 29] + auto const doy = 29*(m-1) + m/2 + d-1; // [0, 354] + auto const doe = yoe * 354 + (11*(yoe+1)+3)/30 + doy; // [0, 10630] + return days{era * 10631 + static_cast(doe) - 492148}; +} + +CONSTCD14 +inline +year_month_day::operator sys_days() const NOEXCEPT +{ + return sys_days{to_days()}; +} + +CONSTCD14 +inline +year_month_day::operator local_days() const NOEXCEPT +{ + return local_days{to_days()}; +} + +CONSTCD14 +inline +bool +year_month_day::ok() const NOEXCEPT +{ + if (!(y_.ok() && m_.ok())) + return false; + return 1_d <= d_ && d_ <= (y_/m_/last).day(); +} + +CONSTCD11 +inline +bool +operator==(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return x.year() == y.year() && x.month() == y.month() && x.day() == y.day(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return x.year() < y.year() ? true + : (x.year() > y.year() ? false + : (x.month() < y.month() ? true + : (x.month() > y.month() ? false + : (x.day() < y.day())))); +} + +CONSTCD11 +inline +bool +operator>(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return !(x < y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_day& ymd) +{ + date::detail::save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::right); + os << ymd.year() << '-'; + os.width(2); + os << static_cast(ymd.month()) << '-'; + os << ymd.day(); + return os; +} + +CONSTCD14 +inline +year_month_day +year_month_day::from_days(days dp) NOEXCEPT +{ + static_assert(std::numeric_limits::digits >= 18, + "This algorithm has not been ported to a 16 bit unsigned integer"); + static_assert(std::numeric_limits::digits >= 20, + "This algorithm has not been ported to a 16 bit signed integer"); + auto const z = dp.count() + 492148; + auto const era = (z >= 0 ? z : z - 10630) / 10631; + auto const doe = static_cast(z - era * 10631); // [0, 10630] + auto const yoe = (30*doe + 10646)/10631 - 1; // [0, 29] + auto const y = static_cast(yoe) + era * 30 + 1; + auto const doy = doe - (yoe * 354 + (11*(yoe+1)+3)/30); // [0, 354] + auto const m = (11*doy + 330) / 325; // [1, 12] + auto const d = doy - (29*(m-1) + m/2) + 1; // [1, 30] + return year_month_day{islamic::year{y}, islamic::month(m), islamic::day(d)}; +} + +CONSTCD14 +inline +year_month_day +operator+(const year_month_day& ymd, const months& dm) NOEXCEPT +{ + return (ymd.year() / ymd.month() + dm) / ymd.day(); +} + +CONSTCD14 +inline +year_month_day +operator+(const months& dm, const year_month_day& ymd) NOEXCEPT +{ + return ymd + dm; +} + +CONSTCD14 +inline +year_month_day +operator-(const year_month_day& ymd, const months& dm) NOEXCEPT +{ + return ymd + (-dm); +} + +CONSTCD11 +inline +year_month_day +operator+(const year_month_day& ymd, const years& dy) NOEXCEPT +{ + return (ymd.year() + dy) / ymd.month() / ymd.day(); +} + +CONSTCD11 +inline +year_month_day +operator+(const years& dy, const year_month_day& ymd) NOEXCEPT +{ + return ymd + dy; +} + +CONSTCD11 +inline +year_month_day +operator-(const year_month_day& ymd, const years& dy) NOEXCEPT +{ + return ymd + (-dy); +} + +// year_month_weekday + +CONSTCD11 +inline +year_month_weekday::year_month_weekday(const islamic::year& y, const islamic::month& m, + const islamic::weekday_indexed& wdi) + NOEXCEPT + : y_(y) + , m_(m) + , wdi_(wdi) + {} + +CONSTCD14 +inline +year_month_weekday::year_month_weekday(const sys_days& dp) NOEXCEPT + : year_month_weekday(from_days(dp.time_since_epoch())) + {} + +CONSTCD14 +inline +year_month_weekday::year_month_weekday(const local_days& dp) NOEXCEPT + : year_month_weekday(from_days(dp.time_since_epoch())) + {} + +CONSTCD14 +inline +year_month_weekday& +year_month_weekday::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +CONSTCD14 +inline +year_month_weekday& +year_month_weekday::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD14 +inline +year_month_weekday& +year_month_weekday::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +CONSTCD14 +inline +year_month_weekday& +year_month_weekday::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD11 inline year year_month_weekday::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month_weekday::month() const NOEXCEPT {return m_;} + +CONSTCD11 +inline +weekday +year_month_weekday::weekday() const NOEXCEPT +{ + return wdi_.weekday(); +} + +CONSTCD11 +inline +unsigned +year_month_weekday::index() const NOEXCEPT +{ + return wdi_.index(); +} + +CONSTCD11 +inline +weekday_indexed +year_month_weekday::weekday_indexed() const NOEXCEPT +{ + return wdi_; +} + +CONSTCD14 +inline +year_month_weekday::operator sys_days() const NOEXCEPT +{ + return sys_days{to_days()}; +} + +CONSTCD14 +inline +year_month_weekday::operator local_days() const NOEXCEPT +{ + return local_days{to_days()}; +} + +CONSTCD14 +inline +bool +year_month_weekday::ok() const NOEXCEPT +{ + if (!y_.ok() || !m_.ok() || !wdi_.weekday().ok() || wdi_.index() < 1) + return false; + if (wdi_.index() <= 4) + return true; + auto d2 = wdi_.weekday() - islamic::weekday(y_/m_/1) + days((wdi_.index()-1)*7 + 1); + return static_cast(d2.count()) <= static_cast((y_/m_/last).day()); +} + +CONSTCD14 +inline +year_month_weekday +year_month_weekday::from_days(days d) NOEXCEPT +{ + sys_days dp{d}; + auto const wd = islamic::weekday(dp); + auto const ymd = year_month_day(dp); + return {ymd.year(), ymd.month(), wd[(static_cast(ymd.day())-1)/7+1]}; +} + +CONSTCD14 +inline +days +year_month_weekday::to_days() const NOEXCEPT +{ + auto d = sys_days(y_/m_/1); + return (d + (wdi_.weekday() - islamic::weekday(d) + days{(wdi_.index()-1)*7}) + ).time_since_epoch(); +} + +CONSTCD11 +inline +bool +operator==(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT +{ + return x.year() == y.year() && x.month() == y.month() && + x.weekday_indexed() == y.weekday_indexed(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_weekday& ymwdi) +{ + return os << ymwdi.year() << '/' << ymwdi.month() + << '/' << ymwdi.weekday_indexed(); +} + +CONSTCD14 +inline +year_month_weekday +operator+(const year_month_weekday& ymwd, const months& dm) NOEXCEPT +{ + return (ymwd.year() / ymwd.month() + dm) / ymwd.weekday_indexed(); +} + +CONSTCD14 +inline +year_month_weekday +operator+(const months& dm, const year_month_weekday& ymwd) NOEXCEPT +{ + return ymwd + dm; +} + +CONSTCD14 +inline +year_month_weekday +operator-(const year_month_weekday& ymwd, const months& dm) NOEXCEPT +{ + return ymwd + (-dm); +} + +CONSTCD11 +inline +year_month_weekday +operator+(const year_month_weekday& ymwd, const years& dy) NOEXCEPT +{ + return {ymwd.year()+dy, ymwd.month(), ymwd.weekday_indexed()}; +} + +CONSTCD11 +inline +year_month_weekday +operator+(const years& dy, const year_month_weekday& ymwd) NOEXCEPT +{ + return ymwd + dy; +} + +CONSTCD11 +inline +year_month_weekday +operator-(const year_month_weekday& ymwd, const years& dy) NOEXCEPT +{ + return ymwd + (-dy); +} + +// year_month_weekday_last + +CONSTCD11 +inline +year_month_weekday_last::year_month_weekday_last(const islamic::year& y, + const islamic::month& m, + const islamic::weekday_last& wdl) NOEXCEPT + : y_(y) + , m_(m) + , wdl_(wdl) + {} + +CONSTCD14 +inline +year_month_weekday_last& +year_month_weekday_last::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +CONSTCD14 +inline +year_month_weekday_last& +year_month_weekday_last::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD14 +inline +year_month_weekday_last& +year_month_weekday_last::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +CONSTCD14 +inline +year_month_weekday_last& +year_month_weekday_last::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD11 inline year year_month_weekday_last::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month_weekday_last::month() const NOEXCEPT {return m_;} + +CONSTCD11 +inline +weekday +year_month_weekday_last::weekday() const NOEXCEPT +{ + return wdl_.weekday(); +} + +CONSTCD11 +inline +weekday_last +year_month_weekday_last::weekday_last() const NOEXCEPT +{ + return wdl_; +} + +CONSTCD14 +inline +year_month_weekday_last::operator sys_days() const NOEXCEPT +{ + return sys_days{to_days()}; +} + +CONSTCD14 +inline +year_month_weekday_last::operator local_days() const NOEXCEPT +{ + return local_days{to_days()}; +} + +CONSTCD11 +inline +bool +year_month_weekday_last::ok() const NOEXCEPT +{ + return y_.ok() && m_.ok() && wdl_.ok(); +} + +CONSTCD14 +inline +days +year_month_weekday_last::to_days() const NOEXCEPT +{ + auto const d = sys_days(y_/m_/last); + return (d - (islamic::weekday{d} - wdl_.weekday())).time_since_epoch(); +} + +CONSTCD11 +inline +bool +operator==(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT +{ + return x.year() == y.year() && x.month() == y.month() && + x.weekday_last() == y.weekday_last(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_weekday_last& ymwdl) +{ + return os << ymwdl.year() << '/' << ymwdl.month() << '/' << ymwdl.weekday_last(); +} + +CONSTCD14 +inline +year_month_weekday_last +operator+(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT +{ + return (ymwdl.year() / ymwdl.month() + dm) / ymwdl.weekday_last(); +} + +CONSTCD14 +inline +year_month_weekday_last +operator+(const months& dm, const year_month_weekday_last& ymwdl) NOEXCEPT +{ + return ymwdl + dm; +} + +CONSTCD14 +inline +year_month_weekday_last +operator-(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT +{ + return ymwdl + (-dm); +} + +CONSTCD11 +inline +year_month_weekday_last +operator+(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT +{ + return {ymwdl.year()+dy, ymwdl.month(), ymwdl.weekday_last()}; +} + +CONSTCD11 +inline +year_month_weekday_last +operator+(const years& dy, const year_month_weekday_last& ymwdl) NOEXCEPT +{ + return ymwdl + dy; +} + +CONSTCD11 +inline +year_month_weekday_last +operator-(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT +{ + return ymwdl + (-dy); +} + +// year_month from operator/() + +CONSTCD11 +inline +year_month +operator/(const year& y, const month& m) NOEXCEPT +{ + return {y, m}; +} + +CONSTCD11 +inline +year_month +operator/(const year& y, int m) NOEXCEPT +{ + return y / month(static_cast(m)); +} + +// month_day from operator/() + +CONSTCD11 +inline +month_day +operator/(const month& m, const day& d) NOEXCEPT +{ + return {m, d}; +} + +CONSTCD11 +inline +month_day +operator/(const day& d, const month& m) NOEXCEPT +{ + return m / d; +} + +CONSTCD11 +inline +month_day +operator/(const month& m, int d) NOEXCEPT +{ + return m / day(static_cast(d)); +} + +CONSTCD11 +inline +month_day +operator/(int m, const day& d) NOEXCEPT +{ + return month(static_cast(m)) / d; +} + +CONSTCD11 inline month_day operator/(const day& d, int m) NOEXCEPT {return m / d;} + +// month_day_last from operator/() + +CONSTCD11 +inline +month_day_last +operator/(const month& m, last_spec) NOEXCEPT +{ + return month_day_last{m}; +} + +CONSTCD11 +inline +month_day_last +operator/(last_spec, const month& m) NOEXCEPT +{ + return m/last; +} + +CONSTCD11 +inline +month_day_last +operator/(int m, last_spec) NOEXCEPT +{ + return month(static_cast(m))/last; +} + +CONSTCD11 +inline +month_day_last +operator/(last_spec, int m) NOEXCEPT +{ + return m/last; +} + +// month_weekday from operator/() + +CONSTCD11 +inline +month_weekday +operator/(const month& m, const weekday_indexed& wdi) NOEXCEPT +{ + return {m, wdi}; +} + +CONSTCD11 +inline +month_weekday +operator/(const weekday_indexed& wdi, const month& m) NOEXCEPT +{ + return m / wdi; +} + +CONSTCD11 +inline +month_weekday +operator/(int m, const weekday_indexed& wdi) NOEXCEPT +{ + return month(static_cast(m)) / wdi; +} + +CONSTCD11 +inline +month_weekday +operator/(const weekday_indexed& wdi, int m) NOEXCEPT +{ + return m / wdi; +} + +// month_weekday_last from operator/() + +CONSTCD11 +inline +month_weekday_last +operator/(const month& m, const weekday_last& wdl) NOEXCEPT +{ + return {m, wdl}; +} + +CONSTCD11 +inline +month_weekday_last +operator/(const weekday_last& wdl, const month& m) NOEXCEPT +{ + return m / wdl; +} + +CONSTCD11 +inline +month_weekday_last +operator/(int m, const weekday_last& wdl) NOEXCEPT +{ + return month(static_cast(m)) / wdl; +} + +CONSTCD11 +inline +month_weekday_last +operator/(const weekday_last& wdl, int m) NOEXCEPT +{ + return m / wdl; +} + +// year_month_day from operator/() + +CONSTCD11 +inline +year_month_day +operator/(const year_month& ym, const day& d) NOEXCEPT +{ + return {ym.year(), ym.month(), d}; +} + +CONSTCD11 +inline +year_month_day +operator/(const year_month& ym, int d) NOEXCEPT +{ + return ym / day(static_cast(d)); +} + +CONSTCD11 +inline +year_month_day +operator/(const year& y, const month_day& md) NOEXCEPT +{ + return y / md.month() / md.day(); +} + +CONSTCD11 +inline +year_month_day +operator/(int y, const month_day& md) NOEXCEPT +{ + return year(y) / md; +} + +CONSTCD11 +inline +year_month_day +operator/(const month_day& md, const year& y) NOEXCEPT +{ + return y / md; +} + +CONSTCD11 +inline +year_month_day +operator/(const month_day& md, int y) NOEXCEPT +{ + return year(y) / md; +} + +// year_month_day_last from operator/() + +CONSTCD11 +inline +year_month_day_last +operator/(const year_month& ym, last_spec) NOEXCEPT +{ + return {ym.year(), month_day_last{ym.month()}}; +} + +CONSTCD11 +inline +year_month_day_last +operator/(const year& y, const month_day_last& mdl) NOEXCEPT +{ + return {y, mdl}; +} + +CONSTCD11 +inline +year_month_day_last +operator/(int y, const month_day_last& mdl) NOEXCEPT +{ + return year(y) / mdl; +} + +CONSTCD11 +inline +year_month_day_last +operator/(const month_day_last& mdl, const year& y) NOEXCEPT +{ + return y / mdl; +} + +CONSTCD11 +inline +year_month_day_last +operator/(const month_day_last& mdl, int y) NOEXCEPT +{ + return year(y) / mdl; +} + +// year_month_weekday from operator/() + +CONSTCD11 +inline +year_month_weekday +operator/(const year_month& ym, const weekday_indexed& wdi) NOEXCEPT +{ + return {ym.year(), ym.month(), wdi}; +} + +CONSTCD11 +inline +year_month_weekday +operator/(const year& y, const month_weekday& mwd) NOEXCEPT +{ + return {y, mwd.month(), mwd.weekday_indexed()}; +} + +CONSTCD11 +inline +year_month_weekday +operator/(int y, const month_weekday& mwd) NOEXCEPT +{ + return year(y) / mwd; +} + +CONSTCD11 +inline +year_month_weekday +operator/(const month_weekday& mwd, const year& y) NOEXCEPT +{ + return y / mwd; +} + +CONSTCD11 +inline +year_month_weekday +operator/(const month_weekday& mwd, int y) NOEXCEPT +{ + return year(y) / mwd; +} + +// year_month_weekday_last from operator/() + +CONSTCD11 +inline +year_month_weekday_last +operator/(const year_month& ym, const weekday_last& wdl) NOEXCEPT +{ + return {ym.year(), ym.month(), wdl}; +} + +CONSTCD11 +inline +year_month_weekday_last +operator/(const year& y, const month_weekday_last& mwdl) NOEXCEPT +{ + return {y, mwdl.month(), mwdl.weekday_last()}; +} + +CONSTCD11 +inline +year_month_weekday_last +operator/(int y, const month_weekday_last& mwdl) NOEXCEPT +{ + return year(y) / mwdl; +} + +CONSTCD11 +inline +year_month_weekday_last +operator/(const month_weekday_last& mwdl, const year& y) NOEXCEPT +{ + return y / mwdl; +} + +CONSTCD11 +inline +year_month_weekday_last +operator/(const month_weekday_last& mwdl, int y) NOEXCEPT +{ + return year(y) / mwdl; +} + +} // namespace islamic + +#endif // ISLAMIC_H diff --git a/third_party/date/include/date/iso_week.h b/third_party/date/include/date/iso_week.h new file mode 100644 index 0000000..4a0a4a9 --- /dev/null +++ b/third_party/date/include/date/iso_week.h @@ -0,0 +1,1751 @@ +#ifndef ISO_WEEK_H +#define ISO_WEEK_H + +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016, 2017 Howard Hinnant +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "date.h" + +#include + +namespace iso_week +{ + +// y/wn/wd +// wn/wd/y +// wd/wn/y + +using days = date::days; +using weeks = date::weeks; +using years = date::years; + +// time_point + +using sys_days = date::sys_days; +using local_days = date::local_days; + +// types + +struct last_week +{ + explicit last_week() = default; +}; + +class weekday; +class weeknum; +class year; + +class year_weeknum; +class year_lastweek; +class weeknum_weekday; +class lastweek_weekday; + +class year_weeknum_weekday; +class year_lastweek_weekday; + +// date composition operators + +CONSTCD11 year_weeknum operator/(const year& y, const weeknum& wn) NOEXCEPT; +CONSTCD11 year_weeknum operator/(const year& y, int wn) NOEXCEPT; + +CONSTCD11 year_lastweek operator/(const year& y, last_week wn) NOEXCEPT; + +CONSTCD11 weeknum_weekday operator/(const weeknum& wn, const weekday& wd) NOEXCEPT; +CONSTCD11 weeknum_weekday operator/(const weeknum& wn, int wd) NOEXCEPT; +CONSTCD11 weeknum_weekday operator/(const weekday& wd, const weeknum& wn) NOEXCEPT; +CONSTCD11 weeknum_weekday operator/(const weekday& wd, int wn) NOEXCEPT; + +CONSTCD11 lastweek_weekday operator/(const last_week& wn, const weekday& wd) NOEXCEPT; +CONSTCD11 lastweek_weekday operator/(const last_week& wn, int wd) NOEXCEPT; +CONSTCD11 lastweek_weekday operator/(const weekday& wd, const last_week& wn) NOEXCEPT; + +CONSTCD11 year_weeknum_weekday operator/(const year_weeknum& ywn, const weekday& wd) NOEXCEPT; +CONSTCD11 year_weeknum_weekday operator/(const year_weeknum& ywn, int wd) NOEXCEPT; +CONSTCD11 year_weeknum_weekday operator/(const weeknum_weekday& wnwd, const year& y) NOEXCEPT; +CONSTCD11 year_weeknum_weekday operator/(const weeknum_weekday& wnwd, int y) NOEXCEPT; + +CONSTCD11 year_lastweek_weekday operator/(const year_lastweek& ylw, const weekday& wd) NOEXCEPT; +CONSTCD11 year_lastweek_weekday operator/(const year_lastweek& ylw, int wd) NOEXCEPT; + +CONSTCD11 year_lastweek_weekday operator/(const lastweek_weekday& lwwd, const year& y) NOEXCEPT; +CONSTCD11 year_lastweek_weekday operator/(const lastweek_weekday& lwwd, int y) NOEXCEPT; + +// weekday + +class weekday +{ + unsigned char wd_; +public: + explicit CONSTCD11 weekday(unsigned wd) NOEXCEPT; + CONSTCD11 weekday(date::weekday wd) NOEXCEPT; + explicit weekday(int) = delete; + CONSTCD11 weekday(const sys_days& dp) NOEXCEPT; + CONSTCD11 explicit weekday(const local_days& dp) NOEXCEPT; + + weekday& operator++() NOEXCEPT; + weekday operator++(int) NOEXCEPT; + weekday& operator--() NOEXCEPT; + weekday operator--(int) NOEXCEPT; + + weekday& operator+=(const days& d) NOEXCEPT; + weekday& operator-=(const days& d) NOEXCEPT; + + CONSTCD11 explicit operator unsigned() const NOEXCEPT; + CONSTCD11 operator date::weekday() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; + +private: + static CONSTCD11 unsigned char weekday_from_days(int z) NOEXCEPT; + static CONSTCD11 unsigned char to_iso_encoding(unsigned char) NOEXCEPT; + static CONSTCD11 unsigned from_iso_encoding(unsigned) NOEXCEPT; +}; + +CONSTCD11 bool operator==(const weekday& x, const weekday& y) NOEXCEPT; +CONSTCD11 bool operator!=(const weekday& x, const weekday& y) NOEXCEPT; + +CONSTCD14 weekday operator+(const weekday& x, const days& y) NOEXCEPT; +CONSTCD14 weekday operator+(const days& x, const weekday& y) NOEXCEPT; +CONSTCD14 weekday operator-(const weekday& x, const days& y) NOEXCEPT; +CONSTCD14 days operator-(const weekday& x, const weekday& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday& wd); + +// year + +class year +{ + short y_; + +public: + explicit CONSTCD11 year(int y) NOEXCEPT; + + year& operator++() NOEXCEPT; + year operator++(int) NOEXCEPT; + year& operator--() NOEXCEPT; + year operator--(int) NOEXCEPT; + + year& operator+=(const years& y) NOEXCEPT; + year& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 explicit operator int() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; + + static CONSTCD11 year min() NOEXCEPT; + static CONSTCD11 year max() NOEXCEPT; +}; + +CONSTCD11 bool operator==(const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator< (const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator> (const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year& x, const year& y) NOEXCEPT; + +CONSTCD11 year operator+(const year& x, const years& y) NOEXCEPT; +CONSTCD11 year operator+(const years& x, const year& y) NOEXCEPT; +CONSTCD11 year operator-(const year& x, const years& y) NOEXCEPT; +CONSTCD11 years operator-(const year& x, const year& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year& y); + +// weeknum + +class weeknum +{ + unsigned char wn_; + +public: + explicit CONSTCD11 weeknum(unsigned wn) NOEXCEPT; + + weeknum& operator++() NOEXCEPT; + weeknum operator++(int) NOEXCEPT; + weeknum& operator--() NOEXCEPT; + weeknum operator--(int) NOEXCEPT; + + weeknum& operator+=(const weeks& y) NOEXCEPT; + weeknum& operator-=(const weeks& y) NOEXCEPT; + + CONSTCD11 explicit operator unsigned() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const weeknum& x, const weeknum& y) NOEXCEPT; +CONSTCD11 bool operator!=(const weeknum& x, const weeknum& y) NOEXCEPT; +CONSTCD11 bool operator< (const weeknum& x, const weeknum& y) NOEXCEPT; +CONSTCD11 bool operator> (const weeknum& x, const weeknum& y) NOEXCEPT; +CONSTCD11 bool operator<=(const weeknum& x, const weeknum& y) NOEXCEPT; +CONSTCD11 bool operator>=(const weeknum& x, const weeknum& y) NOEXCEPT; + +CONSTCD11 weeknum operator+(const weeknum& x, const weeks& y) NOEXCEPT; +CONSTCD11 weeknum operator+(const weeks& x, const weeknum& y) NOEXCEPT; +CONSTCD11 weeknum operator-(const weeknum& x, const weeks& y) NOEXCEPT; +CONSTCD11 weeks operator-(const weeknum& x, const weeknum& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const weeknum& wn); + +// year_weeknum + +class year_weeknum +{ + iso_week::year y_; + iso_week::weeknum wn_; + +public: + CONSTCD11 year_weeknum(const iso_week::year& y, const iso_week::weeknum& wn) NOEXCEPT; + + CONSTCD11 iso_week::year year() const NOEXCEPT; + CONSTCD11 iso_week::weeknum weeknum() const NOEXCEPT; + + year_weeknum& operator+=(const years& dy) NOEXCEPT; + year_weeknum& operator-=(const years& dy) NOEXCEPT; + + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const year_weeknum& x, const year_weeknum& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year_weeknum& x, const year_weeknum& y) NOEXCEPT; +CONSTCD11 bool operator< (const year_weeknum& x, const year_weeknum& y) NOEXCEPT; +CONSTCD11 bool operator> (const year_weeknum& x, const year_weeknum& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year_weeknum& x, const year_weeknum& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year_weeknum& x, const year_weeknum& y) NOEXCEPT; + +CONSTCD11 year_weeknum operator+(const year_weeknum& ym, const years& dy) NOEXCEPT; +CONSTCD11 year_weeknum operator+(const years& dy, const year_weeknum& ym) NOEXCEPT; +CONSTCD11 year_weeknum operator-(const year_weeknum& ym, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_weeknum& ym); + +// year_lastweek + +class year_lastweek +{ + iso_week::year y_; + +public: + CONSTCD11 explicit year_lastweek(const iso_week::year& y) NOEXCEPT; + + CONSTCD11 iso_week::year year() const NOEXCEPT; + CONSTCD14 iso_week::weeknum weeknum() const NOEXCEPT; + + year_lastweek& operator+=(const years& dy) NOEXCEPT; + year_lastweek& operator-=(const years& dy) NOEXCEPT; + + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const year_lastweek& x, const year_lastweek& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year_lastweek& x, const year_lastweek& y) NOEXCEPT; +CONSTCD11 bool operator< (const year_lastweek& x, const year_lastweek& y) NOEXCEPT; +CONSTCD11 bool operator> (const year_lastweek& x, const year_lastweek& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year_lastweek& x, const year_lastweek& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year_lastweek& x, const year_lastweek& y) NOEXCEPT; + +CONSTCD11 year_lastweek operator+(const year_lastweek& ym, const years& dy) NOEXCEPT; +CONSTCD11 year_lastweek operator+(const years& dy, const year_lastweek& ym) NOEXCEPT; +CONSTCD11 year_lastweek operator-(const year_lastweek& ym, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_lastweek& ym); + +// weeknum_weekday + +class weeknum_weekday +{ + iso_week::weeknum wn_; + iso_week::weekday wd_; + +public: + CONSTCD11 weeknum_weekday(const iso_week::weeknum& wn, + const iso_week::weekday& wd) NOEXCEPT; + + CONSTCD11 iso_week::weeknum weeknum() const NOEXCEPT; + CONSTCD11 iso_week::weekday weekday() const NOEXCEPT; + + CONSTCD14 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const weeknum_weekday& x, const weeknum_weekday& y) NOEXCEPT; +CONSTCD11 bool operator!=(const weeknum_weekday& x, const weeknum_weekday& y) NOEXCEPT; +CONSTCD11 bool operator< (const weeknum_weekday& x, const weeknum_weekday& y) NOEXCEPT; +CONSTCD11 bool operator> (const weeknum_weekday& x, const weeknum_weekday& y) NOEXCEPT; +CONSTCD11 bool operator<=(const weeknum_weekday& x, const weeknum_weekday& y) NOEXCEPT; +CONSTCD11 bool operator>=(const weeknum_weekday& x, const weeknum_weekday& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const weeknum_weekday& md); + +// lastweek_weekday + +class lastweek_weekday +{ + iso_week::weekday wd_; + +public: + CONSTCD11 explicit lastweek_weekday(const iso_week::weekday& wd) NOEXCEPT; + + CONSTCD11 iso_week::weekday weekday() const NOEXCEPT; + + CONSTCD14 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const lastweek_weekday& x, const lastweek_weekday& y) NOEXCEPT; +CONSTCD11 bool operator!=(const lastweek_weekday& x, const lastweek_weekday& y) NOEXCEPT; +CONSTCD11 bool operator< (const lastweek_weekday& x, const lastweek_weekday& y) NOEXCEPT; +CONSTCD11 bool operator> (const lastweek_weekday& x, const lastweek_weekday& y) NOEXCEPT; +CONSTCD11 bool operator<=(const lastweek_weekday& x, const lastweek_weekday& y) NOEXCEPT; +CONSTCD11 bool operator>=(const lastweek_weekday& x, const lastweek_weekday& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const lastweek_weekday& md); + +// year_lastweek_weekday + +class year_lastweek_weekday +{ + iso_week::year y_; + iso_week::weekday wd_; + +public: + CONSTCD11 year_lastweek_weekday(const iso_week::year& y, + const iso_week::weekday& wd) NOEXCEPT; + + year_lastweek_weekday& operator+=(const years& y) NOEXCEPT; + year_lastweek_weekday& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 iso_week::year year() const NOEXCEPT; + CONSTCD14 iso_week::weeknum weeknum() const NOEXCEPT; + CONSTCD11 iso_week::weekday weekday() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const year_lastweek_weekday& x, const year_lastweek_weekday& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year_lastweek_weekday& x, const year_lastweek_weekday& y) NOEXCEPT; +CONSTCD11 bool operator< (const year_lastweek_weekday& x, const year_lastweek_weekday& y) NOEXCEPT; +CONSTCD11 bool operator> (const year_lastweek_weekday& x, const year_lastweek_weekday& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year_lastweek_weekday& x, const year_lastweek_weekday& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year_lastweek_weekday& x, const year_lastweek_weekday& y) NOEXCEPT; + +CONSTCD11 year_lastweek_weekday operator+(const year_lastweek_weekday& ywnwd, const years& y) NOEXCEPT; +CONSTCD11 year_lastweek_weekday operator+(const years& y, const year_lastweek_weekday& ywnwd) NOEXCEPT; +CONSTCD11 year_lastweek_weekday operator-(const year_lastweek_weekday& ywnwd, const years& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_lastweek_weekday& ywnwd); + +// class year_weeknum_weekday + +class year_weeknum_weekday +{ + iso_week::year y_; + iso_week::weeknum wn_; + iso_week::weekday wd_; + +public: + CONSTCD11 year_weeknum_weekday(const iso_week::year& y, const iso_week::weeknum& wn, + const iso_week::weekday& wd) NOEXCEPT; + CONSTCD14 year_weeknum_weekday(const year_lastweek_weekday& ylwwd) NOEXCEPT; + CONSTCD14 year_weeknum_weekday(const sys_days& dp) NOEXCEPT; + CONSTCD14 explicit year_weeknum_weekday(const local_days& dp) NOEXCEPT; + + year_weeknum_weekday& operator+=(const years& y) NOEXCEPT; + year_weeknum_weekday& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 iso_week::year year() const NOEXCEPT; + CONSTCD11 iso_week::weeknum weeknum() const NOEXCEPT; + CONSTCD11 iso_week::weekday weekday() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD14 bool ok() const NOEXCEPT; + +private: + static CONSTCD14 year_weeknum_weekday from_days(days dp) NOEXCEPT; +}; + +CONSTCD11 bool operator==(const year_weeknum_weekday& x, const year_weeknum_weekday& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year_weeknum_weekday& x, const year_weeknum_weekday& y) NOEXCEPT; +CONSTCD11 bool operator< (const year_weeknum_weekday& x, const year_weeknum_weekday& y) NOEXCEPT; +CONSTCD11 bool operator> (const year_weeknum_weekday& x, const year_weeknum_weekday& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year_weeknum_weekday& x, const year_weeknum_weekday& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year_weeknum_weekday& x, const year_weeknum_weekday& y) NOEXCEPT; + +CONSTCD11 year_weeknum_weekday operator+(const year_weeknum_weekday& ywnwd, const years& y) NOEXCEPT; +CONSTCD11 year_weeknum_weekday operator+(const years& y, const year_weeknum_weekday& ywnwd) NOEXCEPT; +CONSTCD11 year_weeknum_weekday operator-(const year_weeknum_weekday& ywnwd, const years& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_weeknum_weekday& ywnwd); + +//----------------+ +// Implementation | +//----------------+ + +// weekday + +CONSTCD11 +inline +unsigned char +weekday::to_iso_encoding(unsigned char z) NOEXCEPT +{ + return z != 0 ? z : (unsigned char)7; +} + +CONSTCD11 +inline +unsigned +weekday::from_iso_encoding(unsigned z) NOEXCEPT +{ + return z != 7 ? z : 0u; +} + +CONSTCD11 +inline +unsigned char +weekday::weekday_from_days(int z) NOEXCEPT +{ + return to_iso_encoding(static_cast(static_cast( + z >= -4 ? (z+4) % 7 : (z+5) % 7 + 6))); +} + +CONSTCD11 +inline +weekday::weekday(unsigned wd) NOEXCEPT + : wd_(static_cast(wd)) + {} + +CONSTCD11 +inline +weekday::weekday(date::weekday wd) NOEXCEPT + : wd_(wd.iso_encoding()) + {} + +CONSTCD11 +inline +weekday::weekday(const sys_days& dp) NOEXCEPT + : wd_(weekday_from_days(dp.time_since_epoch().count())) + {} + +CONSTCD11 +inline +weekday::weekday(const local_days& dp) NOEXCEPT + : wd_(weekday_from_days(dp.time_since_epoch().count())) + {} + +inline weekday& weekday::operator++() NOEXCEPT {if (++wd_ == 8) wd_ = 1; return *this;} +inline weekday weekday::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +inline weekday& weekday::operator--() NOEXCEPT {if (wd_-- == 1) wd_ = 7; return *this;} +inline weekday weekday::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} + +inline +weekday& +weekday::operator+=(const days& d) NOEXCEPT +{ + *this = *this + d; + return *this; +} + +inline +weekday& +weekday::operator-=(const days& d) NOEXCEPT +{ + *this = *this - d; + return *this; +} + +CONSTCD11 +inline +weekday::operator unsigned() const NOEXCEPT +{ + return wd_; +} + +CONSTCD11 +inline +weekday::operator date::weekday() const NOEXCEPT +{ + return date::weekday{from_iso_encoding(unsigned{wd_})}; +} + +CONSTCD11 inline bool weekday::ok() const NOEXCEPT {return 1 <= wd_ && wd_ <= 7;} + +CONSTCD11 +inline +bool +operator==(const weekday& x, const weekday& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const weekday& x, const weekday& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD14 +inline +days +operator-(const weekday& x, const weekday& y) NOEXCEPT +{ + auto const diff = static_cast(x) - static_cast(y); + return days{diff <= 6 ? diff : diff + 7}; +} + +CONSTCD14 +inline +weekday +operator+(const weekday& x, const days& y) NOEXCEPT +{ + auto const wdu = static_cast(static_cast(x) - 1u) + y.count(); + auto const wk = (wdu >= 0 ? wdu : wdu-6) / 7; + return weekday{static_cast(wdu - wk * 7) + 1u}; +} + +CONSTCD14 +inline +weekday +operator+(const days& x, const weekday& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD14 +inline +weekday +operator-(const weekday& x, const days& y) NOEXCEPT +{ + return x + -y; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday& wd) +{ + switch (static_cast(wd)) + { + case 7: + os << "Sun"; + break; + case 1: + os << "Mon"; + break; + case 2: + os << "Tue"; + break; + case 3: + os << "Wed"; + break; + case 4: + os << "Thu"; + break; + case 5: + os << "Fri"; + break; + case 6: + os << "Sat"; + break; + default: + os << static_cast(wd) << " is not a valid weekday"; + break; + } + return os; +} + +// year + +CONSTCD11 inline year::year(int y) NOEXCEPT : y_(static_cast(y)) {} +inline year& year::operator++() NOEXCEPT {++y_; return *this;} +inline year year::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +inline year& year::operator--() NOEXCEPT {--y_; return *this;} +inline year year::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} +inline year& year::operator+=(const years& y) NOEXCEPT {*this = *this + y; return *this;} +inline year& year::operator-=(const years& y) NOEXCEPT {*this = *this - y; return *this;} + +CONSTCD11 inline year::operator int() const NOEXCEPT {return y_;} +CONSTCD11 inline bool year::ok() const NOEXCEPT {return min() <= *this && *this <= max();} + +CONSTCD11 +inline +year +year::min() NOEXCEPT +{ + using std::chrono::seconds; + using std::chrono::minutes; + using std::chrono::hours; + using std::chrono::duration_cast; + static_assert(sizeof(seconds)*CHAR_BIT >= 41, "seconds may overflow"); + static_assert(sizeof(hours)*CHAR_BIT >= 30, "hours may overflow"); + return sizeof(minutes)*CHAR_BIT < 34 ? + year{1970} + duration_cast(minutes::min()) : + year{std::numeric_limits::min()}; +} + +CONSTCD11 +inline +year +year::max() NOEXCEPT +{ + using std::chrono::seconds; + using std::chrono::minutes; + using std::chrono::hours; + using std::chrono::duration_cast; + static_assert(sizeof(seconds)*CHAR_BIT >= 41, "seconds may overflow"); + static_assert(sizeof(hours)*CHAR_BIT >= 30, "hours may overflow"); + return sizeof(minutes)*CHAR_BIT < 34 ? + year{1969} + duration_cast(minutes::max()) : + year{std::numeric_limits::max()}; +} + +CONSTCD11 +inline +bool +operator==(const year& x, const year& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const year& x, const year& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year& x, const year& y) NOEXCEPT +{ + return static_cast(x) < static_cast(y); +} + +CONSTCD11 +inline +bool +operator>(const year& x, const year& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year& x, const year& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year& x, const year& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD11 +inline +years +operator-(const year& x, const year& y) NOEXCEPT +{ + return years{static_cast(x) - static_cast(y)}; +} + +CONSTCD11 +inline +year +operator+(const year& x, const years& y) NOEXCEPT +{ + return year{static_cast(x) + y.count()}; +} + +CONSTCD11 +inline +year +operator+(const years& x, const year& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD11 +inline +year +operator-(const year& x, const years& y) NOEXCEPT +{ + return year{static_cast(x) - y.count()}; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year& y) +{ + date::detail::save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::internal); + os.width(4 + (y < year{0})); + os << static_cast(y); + return os; +} + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) +inline namespace literals +{ + +CONSTCD11 +inline +iso_week::year +operator "" _y(unsigned long long y) NOEXCEPT +{ + return iso_week::year(static_cast(y)); +} + +CONSTCD11 +inline +iso_week::weeknum +operator "" _w(unsigned long long wn) NOEXCEPT +{ + return iso_week::weeknum(static_cast(wn)); +} + +#endif // !defined(_MSC_VER) || (_MSC_VER >= 1900) + +CONSTDATA iso_week::last_week last{}; + +CONSTDATA iso_week::weekday sun{7u}; +CONSTDATA iso_week::weekday mon{1u}; +CONSTDATA iso_week::weekday tue{2u}; +CONSTDATA iso_week::weekday wed{3u}; +CONSTDATA iso_week::weekday thu{4u}; +CONSTDATA iso_week::weekday fri{5u}; +CONSTDATA iso_week::weekday sat{6u}; + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) +} // inline namespace literals +#endif + +// weeknum + +CONSTCD11 +inline +weeknum::weeknum(unsigned wn) NOEXCEPT + : wn_(static_cast(wn)) + {} + +inline weeknum& weeknum::operator++() NOEXCEPT {++wn_; return *this;} +inline weeknum weeknum::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +inline weeknum& weeknum::operator--() NOEXCEPT {--wn_; return *this;} +inline weeknum weeknum::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} + +inline +weeknum& +weeknum::operator+=(const weeks& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +inline +weeknum& +weeknum::operator-=(const weeks& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD11 inline weeknum::operator unsigned() const NOEXCEPT {return wn_;} +CONSTCD11 inline bool weeknum::ok() const NOEXCEPT {return 1 <= wn_ && wn_ <= 53;} + +CONSTCD11 +inline +bool +operator==(const weeknum& x, const weeknum& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const weeknum& x, const weeknum& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const weeknum& x, const weeknum& y) NOEXCEPT +{ + return static_cast(x) < static_cast(y); +} + +CONSTCD11 +inline +bool +operator>(const weeknum& x, const weeknum& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const weeknum& x, const weeknum& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const weeknum& x, const weeknum& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD11 +inline +weeks +operator-(const weeknum& x, const weeknum& y) NOEXCEPT +{ + return weeks{static_cast(static_cast(x)) - + static_cast(static_cast(y))}; +} + +CONSTCD11 +inline +weeknum +operator+(const weeknum& x, const weeks& y) NOEXCEPT +{ + return weeknum{static_cast(x) + static_cast(y.count())}; +} + +CONSTCD11 +inline +weeknum +operator+(const weeks& x, const weeknum& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD11 +inline +weeknum +operator-(const weeknum& x, const weeks& y) NOEXCEPT +{ + return x + -y; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const weeknum& wn) +{ + date::detail::save_ostream _(os); + os << 'W'; + os.fill('0'); + os.flags(std::ios::dec | std::ios::right); + os.width(2); + os << static_cast(wn); + return os; +} + +// year_weeknum + +CONSTCD11 +inline +year_weeknum::year_weeknum(const iso_week::year& y, const iso_week::weeknum& wn) NOEXCEPT + : y_(y) + , wn_(wn) + {} + +CONSTCD11 inline year year_weeknum::year() const NOEXCEPT {return y_;} +CONSTCD11 inline weeknum year_weeknum::weeknum() const NOEXCEPT {return wn_;} +CONSTCD11 inline bool year_weeknum::ok() const NOEXCEPT +{ + return y_.ok() && 1u <= static_cast(wn_) && wn_ <= (y_/last).weeknum(); +} + +inline +year_weeknum& +year_weeknum::operator+=(const years& dy) NOEXCEPT +{ + *this = *this + dy; + return *this; +} + +inline +year_weeknum& +year_weeknum::operator-=(const years& dy) NOEXCEPT +{ + *this = *this - dy; + return *this; +} + +CONSTCD11 +inline +bool +operator==(const year_weeknum& x, const year_weeknum& y) NOEXCEPT +{ + return x.year() == y.year() && x.weeknum() == y.weeknum(); +} + +CONSTCD11 +inline +bool +operator!=(const year_weeknum& x, const year_weeknum& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year_weeknum& x, const year_weeknum& y) NOEXCEPT +{ + return x.year() < y.year() ? true + : (x.year() > y.year() ? false + : (x.weeknum() < y.weeknum())); +} + +CONSTCD11 +inline +bool +operator>(const year_weeknum& x, const year_weeknum& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year_weeknum& x, const year_weeknum& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year_weeknum& x, const year_weeknum& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD11 +inline +year_weeknum +operator+(const year_weeknum& ym, const years& dy) NOEXCEPT +{ + return (ym.year() + dy) / ym.weeknum(); +} + +CONSTCD11 +inline +year_weeknum +operator+(const years& dy, const year_weeknum& ym) NOEXCEPT +{ + return ym + dy; +} + +CONSTCD11 +inline +year_weeknum +operator-(const year_weeknum& ym, const years& dy) NOEXCEPT +{ + return ym + -dy; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_weeknum& ywn) +{ + return os << ywn.year() << '-' << ywn.weeknum(); +} + + +// year_lastweek + +CONSTCD11 +inline +year_lastweek::year_lastweek(const iso_week::year& y) NOEXCEPT + : y_(y) + {} + +CONSTCD11 inline year year_lastweek::year() const NOEXCEPT {return y_;} + +CONSTCD14 +inline +weeknum +year_lastweek::weeknum() const NOEXCEPT +{ + const auto y = date::year{static_cast(y_)}; + const auto s0 = sys_days((y-years{1})/12/date::thu[date::last]); + const auto s1 = sys_days(y/12/date::thu[date::last]); + return iso_week::weeknum(static_cast(date::trunc(s1-s0).count())); +} + +CONSTCD11 inline bool year_lastweek::ok() const NOEXCEPT {return y_.ok();} + +inline +year_lastweek& +year_lastweek::operator+=(const years& dy) NOEXCEPT +{ + *this = *this + dy; + return *this; +} + +inline +year_lastweek& +year_lastweek::operator-=(const years& dy) NOEXCEPT +{ + *this = *this - dy; + return *this; +} + +CONSTCD11 +inline +bool +operator==(const year_lastweek& x, const year_lastweek& y) NOEXCEPT +{ + return x.year() == y.year(); +} + +CONSTCD11 +inline +bool +operator!=(const year_lastweek& x, const year_lastweek& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year_lastweek& x, const year_lastweek& y) NOEXCEPT +{ + return x.year() < y.year(); +} + +CONSTCD11 +inline +bool +operator>(const year_lastweek& x, const year_lastweek& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year_lastweek& x, const year_lastweek& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year_lastweek& x, const year_lastweek& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD11 +inline +year_lastweek +operator+(const year_lastweek& ym, const years& dy) NOEXCEPT +{ + return year_lastweek{ym.year() + dy}; +} + +CONSTCD11 +inline +year_lastweek +operator+(const years& dy, const year_lastweek& ym) NOEXCEPT +{ + return ym + dy; +} + +CONSTCD11 +inline +year_lastweek +operator-(const year_lastweek& ym, const years& dy) NOEXCEPT +{ + return ym + -dy; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_lastweek& ywn) +{ + return os << ywn.year() << "-W last"; +} + +// weeknum_weekday + +CONSTCD11 +inline +weeknum_weekday::weeknum_weekday(const iso_week::weeknum& wn, + const iso_week::weekday& wd) NOEXCEPT + : wn_(wn) + , wd_(wd) + {} + +CONSTCD11 inline weeknum weeknum_weekday::weeknum() const NOEXCEPT {return wn_;} +CONSTCD11 inline weekday weeknum_weekday::weekday() const NOEXCEPT {return wd_;} + +CONSTCD14 +inline +bool +weeknum_weekday::ok() const NOEXCEPT +{ + return wn_.ok() && wd_.ok(); +} + +CONSTCD11 +inline +bool +operator==(const weeknum_weekday& x, const weeknum_weekday& y) NOEXCEPT +{ + return x.weeknum() == y.weeknum() && x.weekday() == y.weekday(); +} + +CONSTCD11 +inline +bool +operator!=(const weeknum_weekday& x, const weeknum_weekday& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const weeknum_weekday& x, const weeknum_weekday& y) NOEXCEPT +{ + return x.weeknum() < y.weeknum() ? true + : (x.weeknum() > y.weeknum() ? false + : (static_cast(x.weekday()) < static_cast(y.weekday()))); +} + +CONSTCD11 +inline +bool +operator>(const weeknum_weekday& x, const weeknum_weekday& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const weeknum_weekday& x, const weeknum_weekday& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const weeknum_weekday& x, const weeknum_weekday& y) NOEXCEPT +{ + return !(x < y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const weeknum_weekday& md) +{ + return os << md.weeknum() << '-' << md.weekday(); +} + +// lastweek_weekday + +CONSTCD11 +inline +lastweek_weekday::lastweek_weekday(const iso_week::weekday& wd) NOEXCEPT + : wd_(wd) + {} + +CONSTCD11 inline weekday lastweek_weekday::weekday() const NOEXCEPT {return wd_;} + +CONSTCD14 +inline +bool +lastweek_weekday::ok() const NOEXCEPT +{ + return wd_.ok(); +} + +CONSTCD11 +inline +bool +operator==(const lastweek_weekday& x, const lastweek_weekday& y) NOEXCEPT +{ + return x.weekday() == y.weekday(); +} + +CONSTCD11 +inline +bool +operator!=(const lastweek_weekday& x, const lastweek_weekday& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const lastweek_weekday& x, const lastweek_weekday& y) NOEXCEPT +{ + return static_cast(x.weekday()) < static_cast(y.weekday()); +} + +CONSTCD11 +inline +bool +operator>(const lastweek_weekday& x, const lastweek_weekday& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const lastweek_weekday& x, const lastweek_weekday& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const lastweek_weekday& x, const lastweek_weekday& y) NOEXCEPT +{ + return !(x < y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const lastweek_weekday& md) +{ + return os << "W last-" << md.weekday(); +} + +// year_lastweek_weekday + +CONSTCD11 +inline +year_lastweek_weekday::year_lastweek_weekday(const iso_week::year& y, + const iso_week::weekday& wd) NOEXCEPT + : y_(y) + , wd_(wd) + {} + +inline +year_lastweek_weekday& +year_lastweek_weekday::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +inline +year_lastweek_weekday& +year_lastweek_weekday::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD11 inline year year_lastweek_weekday::year() const NOEXCEPT {return y_;} + +CONSTCD14 +inline +weeknum +year_lastweek_weekday::weeknum() const NOEXCEPT +{ + return (y_ / last).weeknum(); +} + +CONSTCD11 inline weekday year_lastweek_weekday::weekday() const NOEXCEPT {return wd_;} + +CONSTCD14 +inline +year_lastweek_weekday::operator sys_days() const NOEXCEPT +{ + return sys_days(date::year{static_cast(y_)}/date::dec/date::thu[date::last]) + + (sun - thu) - (sun - wd_); +} + +CONSTCD14 +inline +year_lastweek_weekday::operator local_days() const NOEXCEPT +{ + return local_days(date::year{static_cast(y_)}/date::dec/date::thu[date::last]) + + (sun - thu) - (sun - wd_); +} + +CONSTCD11 +inline +bool +year_lastweek_weekday::ok() const NOEXCEPT +{ + return y_.ok() && wd_.ok(); +} + +CONSTCD11 +inline +bool +operator==(const year_lastweek_weekday& x, const year_lastweek_weekday& y) NOEXCEPT +{ + return x.year() == y.year() && x.weekday() == y.weekday(); +} + +CONSTCD11 +inline +bool +operator!=(const year_lastweek_weekday& x, const year_lastweek_weekday& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year_lastweek_weekday& x, const year_lastweek_weekday& y) NOEXCEPT +{ + return x.year() < y.year() ? true + : (x.year() > y.year() ? false + : (static_cast(x.weekday()) < static_cast(y.weekday()))); +} + +CONSTCD11 +inline +bool +operator>(const year_lastweek_weekday& x, const year_lastweek_weekday& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year_lastweek_weekday& x, const year_lastweek_weekday& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year_lastweek_weekday& x, const year_lastweek_weekday& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD11 +inline +year_lastweek_weekday +operator+(const year_lastweek_weekday& ywnwd, const years& y) NOEXCEPT +{ + return (ywnwd.year() + y) / last / ywnwd.weekday(); +} + +CONSTCD11 +inline +year_lastweek_weekday +operator+(const years& y, const year_lastweek_weekday& ywnwd) NOEXCEPT +{ + return ywnwd + y; +} + +CONSTCD11 +inline +year_lastweek_weekday +operator-(const year_lastweek_weekday& ywnwd, const years& y) NOEXCEPT +{ + return ywnwd + -y; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_lastweek_weekday& ywnwd) +{ + return os << ywnwd.year() << "-W last-" << ywnwd.weekday(); +} + +// year_weeknum_weekday + +CONSTCD11 +inline +year_weeknum_weekday::year_weeknum_weekday(const iso_week::year& y, + const iso_week::weeknum& wn, + const iso_week::weekday& wd) NOEXCEPT + : y_(y) + , wn_(wn) + , wd_(wd) + {} + +CONSTCD14 +inline +year_weeknum_weekday::year_weeknum_weekday(const year_lastweek_weekday& ylwwd) NOEXCEPT + : y_(ylwwd.year()) + , wn_(ylwwd.weeknum()) + , wd_(ylwwd.weekday()) + {} + +CONSTCD14 +inline +year_weeknum_weekday::year_weeknum_weekday(const sys_days& dp) NOEXCEPT + : year_weeknum_weekday(from_days(dp.time_since_epoch())) + {} + +CONSTCD14 +inline +year_weeknum_weekday::year_weeknum_weekday(const local_days& dp) NOEXCEPT + : year_weeknum_weekday(from_days(dp.time_since_epoch())) + {} + +inline +year_weeknum_weekday& +year_weeknum_weekday::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +inline +year_weeknum_weekday& +year_weeknum_weekday::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD11 inline year year_weeknum_weekday::year() const NOEXCEPT {return y_;} +CONSTCD11 inline weeknum year_weeknum_weekday::weeknum() const NOEXCEPT {return wn_;} +CONSTCD11 inline weekday year_weeknum_weekday::weekday() const NOEXCEPT {return wd_;} + +CONSTCD14 +inline +year_weeknum_weekday::operator sys_days() const NOEXCEPT +{ + return sys_days(date::year{static_cast(y_)-1}/date::dec/date::thu[date::last]) + + (date::mon - date::thu) + weeks{static_cast(wn_)-1} + (wd_ - mon); +} + +CONSTCD14 +inline +year_weeknum_weekday::operator local_days() const NOEXCEPT +{ + return local_days(date::year{static_cast(y_)-1}/date::dec/date::thu[date::last]) + + (date::mon - date::thu) + weeks{static_cast(wn_)-1} + (wd_ - mon); +} + +CONSTCD14 +inline +bool +year_weeknum_weekday::ok() const NOEXCEPT +{ + return y_.ok() && wd_.ok() && iso_week::weeknum{1u} <= wn_ && wn_ <= year_lastweek{y_}.weeknum(); +} + +CONSTCD14 +inline +year_weeknum_weekday +year_weeknum_weekday::from_days(days d) NOEXCEPT +{ + const auto dp = sys_days{d}; + const auto wd = iso_week::weekday{dp}; + auto y = date::year_month_day{dp + days{3}}.year(); + auto start = sys_days((y - date::years{1})/date::dec/date::thu[date::last]) + (mon-thu); + if (dp < start) + { + --y; + start = sys_days((y - date::years{1})/date::dec/date::thu[date::last]) + (mon-thu); + } + const auto wn = iso_week::weeknum( + static_cast(date::trunc(dp - start).count() + 1)); + return {iso_week::year(static_cast(y)), wn, wd}; +} + +CONSTCD11 +inline +bool +operator==(const year_weeknum_weekday& x, const year_weeknum_weekday& y) NOEXCEPT +{ + return x.year() == y.year() && x.weeknum() == y.weeknum() && x.weekday() == y.weekday(); +} + +CONSTCD11 +inline +bool +operator!=(const year_weeknum_weekday& x, const year_weeknum_weekday& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year_weeknum_weekday& x, const year_weeknum_weekday& y) NOEXCEPT +{ + return x.year() < y.year() ? true + : (x.year() > y.year() ? false + : (x.weeknum() < y.weeknum() ? true + : (x.weeknum() > y.weeknum() ? false + : (static_cast(x.weekday()) < static_cast(y.weekday()))))); +} + +CONSTCD11 +inline +bool +operator>(const year_weeknum_weekday& x, const year_weeknum_weekday& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year_weeknum_weekday& x, const year_weeknum_weekday& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year_weeknum_weekday& x, const year_weeknum_weekday& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD11 +inline +year_weeknum_weekday +operator+(const year_weeknum_weekday& ywnwd, const years& y) NOEXCEPT +{ + return (ywnwd.year() + y) / ywnwd.weeknum() / ywnwd.weekday(); +} + +CONSTCD11 +inline +year_weeknum_weekday +operator+(const years& y, const year_weeknum_weekday& ywnwd) NOEXCEPT +{ + return ywnwd + y; +} + +CONSTCD11 +inline +year_weeknum_weekday +operator-(const year_weeknum_weekday& ywnwd, const years& y) NOEXCEPT +{ + return ywnwd + -y; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_weeknum_weekday& ywnwd) +{ + return os << ywnwd.year() << '-' << ywnwd.weeknum() << '-' << ywnwd.weekday(); +} + +// date composition operators + +CONSTCD11 +inline +year_weeknum +operator/(const year& y, const weeknum& wn) NOEXCEPT +{ + return {y, wn}; +} + +CONSTCD11 +inline +year_weeknum +operator/(const year& y, int wn) NOEXCEPT +{ + return y/weeknum(static_cast(wn)); +} + +CONSTCD11 +inline +year_lastweek +operator/(const year& y, last_week) NOEXCEPT +{ + return year_lastweek{y}; +} + +CONSTCD11 +inline +weeknum_weekday +operator/(const weeknum& wn, const weekday& wd) NOEXCEPT +{ + return {wn, wd}; +} + +CONSTCD11 +inline +weeknum_weekday +operator/(const weeknum& wn, int wd) NOEXCEPT +{ + return wn/weekday{static_cast(wd)}; +} + +CONSTCD11 +inline +weeknum_weekday +operator/(const weekday& wd, const weeknum& wn) NOEXCEPT +{ + return wn/wd; +} + +CONSTCD11 +inline +weeknum_weekday +operator/(const weekday& wd, int wn) NOEXCEPT +{ + return weeknum{static_cast(wn)}/wd; +} + +CONSTCD11 +inline +lastweek_weekday +operator/(const last_week&, const weekday& wd) NOEXCEPT +{ + return lastweek_weekday{wd}; +} + +CONSTCD11 +inline +lastweek_weekday +operator/(const last_week& wn, int wd) NOEXCEPT +{ + return wn / weekday{static_cast(wd)}; +} + +CONSTCD11 +inline +lastweek_weekday +operator/(const weekday& wd, const last_week& wn) NOEXCEPT +{ + return wn / wd; +} + +CONSTCD11 +inline +year_weeknum_weekday +operator/(const year_weeknum& ywn, const weekday& wd) NOEXCEPT +{ + return {ywn.year(), ywn.weeknum(), wd}; +} + +CONSTCD11 +inline +year_weeknum_weekday +operator/(const year_weeknum& ywn, int wd) NOEXCEPT +{ + return ywn / weekday(static_cast(wd)); +} + +CONSTCD11 +inline +year_weeknum_weekday +operator/(const weeknum_weekday& wnwd, const year& y) NOEXCEPT +{ + return {y, wnwd.weeknum(), wnwd.weekday()}; +} + +CONSTCD11 +inline +year_weeknum_weekday +operator/(const weeknum_weekday& wnwd, int y) NOEXCEPT +{ + return wnwd / year{y}; +} + +CONSTCD11 +inline +year_lastweek_weekday +operator/(const year_lastweek& ylw, const weekday& wd) NOEXCEPT +{ + return {ylw.year(), wd}; +} + +CONSTCD11 +inline +year_lastweek_weekday +operator/(const year_lastweek& ylw, int wd) NOEXCEPT +{ + return ylw / weekday(static_cast(wd)); +} + +CONSTCD11 +inline +year_lastweek_weekday +operator/(const lastweek_weekday& lwwd, const year& y) NOEXCEPT +{ + return {y, lwwd.weekday()}; +} + +CONSTCD11 +inline +year_lastweek_weekday +operator/(const lastweek_weekday& lwwd, int y) NOEXCEPT +{ + return lwwd / year{y}; +} + +} // namespace iso_week + +#endif // ISO_WEEK_H diff --git a/third_party/date/include/date/julian.h b/third_party/date/include/date/julian.h new file mode 100644 index 0000000..d909d69 --- /dev/null +++ b/third_party/date/include/date/julian.h @@ -0,0 +1,3052 @@ +#ifndef JULIAN_H +#define JULIAN_H + +// The MIT License (MIT) +// +// Copyright (c) 2016 Howard Hinnant +// +// 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. +// +// Our apologies. When the previous paragraph was written, lowercase had not yet +// been invented (that would involve another several millennia of evolution). +// We did not mean to shout. + +#include "date.h" + +namespace julian +{ + +// durations + +using days = date::days; + +using weeks = date::weeks; + +using years = std::chrono::duration + , days::period>>; + +using months = std::chrono::duration + >>; + +// time_point + +using sys_days = date::sys_days; +using local_days = date::local_days; + +// types + +struct last_spec +{ + explicit last_spec() = default; +}; + +class day; +class month; +class year; + +class weekday; +class weekday_indexed; +class weekday_last; + +class month_day; +class month_day_last; +class month_weekday; +class month_weekday_last; + +class year_month; + +class year_month_day; +class year_month_day_last; +class year_month_weekday; +class year_month_weekday_last; + +// date composition operators + +CONSTCD11 year_month operator/(const year& y, const month& m) NOEXCEPT; +CONSTCD11 year_month operator/(const year& y, int m) NOEXCEPT; + +CONSTCD11 month_day operator/(const day& d, const month& m) NOEXCEPT; +CONSTCD11 month_day operator/(const day& d, int m) NOEXCEPT; +CONSTCD11 month_day operator/(const month& m, const day& d) NOEXCEPT; +CONSTCD11 month_day operator/(const month& m, int d) NOEXCEPT; +CONSTCD11 month_day operator/(int m, const day& d) NOEXCEPT; + +CONSTCD11 month_day_last operator/(const month& m, last_spec) NOEXCEPT; +CONSTCD11 month_day_last operator/(int m, last_spec) NOEXCEPT; +CONSTCD11 month_day_last operator/(last_spec, const month& m) NOEXCEPT; +CONSTCD11 month_day_last operator/(last_spec, int m) NOEXCEPT; + +CONSTCD11 month_weekday operator/(const month& m, const weekday_indexed& wdi) NOEXCEPT; +CONSTCD11 month_weekday operator/(int m, const weekday_indexed& wdi) NOEXCEPT; +CONSTCD11 month_weekday operator/(const weekday_indexed& wdi, const month& m) NOEXCEPT; +CONSTCD11 month_weekday operator/(const weekday_indexed& wdi, int m) NOEXCEPT; + +CONSTCD11 month_weekday_last operator/(const month& m, const weekday_last& wdl) NOEXCEPT; +CONSTCD11 month_weekday_last operator/(int m, const weekday_last& wdl) NOEXCEPT; +CONSTCD11 month_weekday_last operator/(const weekday_last& wdl, const month& m) NOEXCEPT; +CONSTCD11 month_weekday_last operator/(const weekday_last& wdl, int m) NOEXCEPT; + +CONSTCD11 year_month_day operator/(const year_month& ym, const day& d) NOEXCEPT; +CONSTCD11 year_month_day operator/(const year_month& ym, int d) NOEXCEPT; +CONSTCD11 year_month_day operator/(const year& y, const month_day& md) NOEXCEPT; +CONSTCD11 year_month_day operator/(int y, const month_day& md) NOEXCEPT; +CONSTCD11 year_month_day operator/(const month_day& md, const year& y) NOEXCEPT; +CONSTCD11 year_month_day operator/(const month_day& md, int y) NOEXCEPT; + +CONSTCD11 + year_month_day_last operator/(const year_month& ym, last_spec) NOEXCEPT; +CONSTCD11 + year_month_day_last operator/(const year& y, const month_day_last& mdl) NOEXCEPT; +CONSTCD11 + year_month_day_last operator/(int y, const month_day_last& mdl) NOEXCEPT; +CONSTCD11 + year_month_day_last operator/(const month_day_last& mdl, const year& y) NOEXCEPT; +CONSTCD11 + year_month_day_last operator/(const month_day_last& mdl, int y) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(const year_month& ym, const weekday_indexed& wdi) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(const year& y, const month_weekday& mwd) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(int y, const month_weekday& mwd) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(const month_weekday& mwd, const year& y) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(const month_weekday& mwd, int y) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(const year_month& ym, const weekday_last& wdl) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(const year& y, const month_weekday_last& mwdl) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(int y, const month_weekday_last& mwdl) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(const month_weekday_last& mwdl, const year& y) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(const month_weekday_last& mwdl, int y) NOEXCEPT; + +// Detailed interface + +// day + +class day +{ + unsigned char d_; + +public: + explicit CONSTCD11 day(unsigned d) NOEXCEPT; + + CONSTCD14 day& operator++() NOEXCEPT; + CONSTCD14 day operator++(int) NOEXCEPT; + CONSTCD14 day& operator--() NOEXCEPT; + CONSTCD14 day operator--(int) NOEXCEPT; + + CONSTCD14 day& operator+=(const days& d) NOEXCEPT; + CONSTCD14 day& operator-=(const days& d) NOEXCEPT; + + CONSTCD11 explicit operator unsigned() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator!=(const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator< (const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator> (const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator<=(const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator>=(const day& x, const day& y) NOEXCEPT; + +CONSTCD11 day operator+(const day& x, const days& y) NOEXCEPT; +CONSTCD11 day operator+(const days& x, const day& y) NOEXCEPT; +CONSTCD11 day operator-(const day& x, const days& y) NOEXCEPT; +CONSTCD11 days operator-(const day& x, const day& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const day& d); + +// month + +class month +{ + unsigned char m_; + +public: + explicit CONSTCD11 month(unsigned m) NOEXCEPT; + + CONSTCD14 month& operator++() NOEXCEPT; + CONSTCD14 month operator++(int) NOEXCEPT; + CONSTCD14 month& operator--() NOEXCEPT; + CONSTCD14 month operator--(int) NOEXCEPT; + + CONSTCD14 month& operator+=(const months& m) NOEXCEPT; + CONSTCD14 month& operator-=(const months& m) NOEXCEPT; + + CONSTCD11 explicit operator unsigned() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator!=(const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator< (const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator> (const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator<=(const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator>=(const month& x, const month& y) NOEXCEPT; + +CONSTCD14 month operator+(const month& x, const months& y) NOEXCEPT; +CONSTCD14 month operator+(const months& x, const month& y) NOEXCEPT; +CONSTCD14 month operator-(const month& x, const months& y) NOEXCEPT; +CONSTCD14 months operator-(const month& x, const month& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month& m); + +// year + +class year +{ + short y_; + +public: + explicit CONSTCD11 year(int y) NOEXCEPT; + + CONSTCD14 year& operator++() NOEXCEPT; + CONSTCD14 year operator++(int) NOEXCEPT; + CONSTCD14 year& operator--() NOEXCEPT; + CONSTCD14 year operator--(int) NOEXCEPT; + + CONSTCD14 year& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 bool is_leap() const NOEXCEPT; + + CONSTCD11 explicit operator int() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; + + static CONSTCD11 year min() NOEXCEPT; + static CONSTCD11 year max() NOEXCEPT; +}; + +CONSTCD11 bool operator==(const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator< (const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator> (const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year& x, const year& y) NOEXCEPT; + +CONSTCD11 year operator+(const year& x, const years& y) NOEXCEPT; +CONSTCD11 year operator+(const years& x, const year& y) NOEXCEPT; +CONSTCD11 year operator-(const year& x, const years& y) NOEXCEPT; +CONSTCD11 years operator-(const year& x, const year& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year& y); + +// weekday + +class weekday +{ + unsigned char wd_; +public: + explicit CONSTCD11 weekday(unsigned wd) NOEXCEPT; + explicit weekday(int) = delete; + CONSTCD11 weekday(const sys_days& dp) NOEXCEPT; + CONSTCD11 explicit weekday(const local_days& dp) NOEXCEPT; + + CONSTCD14 weekday& operator++() NOEXCEPT; + CONSTCD14 weekday operator++(int) NOEXCEPT; + CONSTCD14 weekday& operator--() NOEXCEPT; + CONSTCD14 weekday operator--(int) NOEXCEPT; + + CONSTCD14 weekday& operator+=(const days& d) NOEXCEPT; + CONSTCD14 weekday& operator-=(const days& d) NOEXCEPT; + + CONSTCD11 explicit operator unsigned() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; + + CONSTCD11 weekday_indexed operator[](unsigned index) const NOEXCEPT; + CONSTCD11 weekday_last operator[](last_spec) const NOEXCEPT; + +private: + static CONSTCD11 unsigned char weekday_from_days(int z) NOEXCEPT; +}; + +CONSTCD11 bool operator==(const weekday& x, const weekday& y) NOEXCEPT; +CONSTCD11 bool operator!=(const weekday& x, const weekday& y) NOEXCEPT; + +CONSTCD14 weekday operator+(const weekday& x, const days& y) NOEXCEPT; +CONSTCD14 weekday operator+(const days& x, const weekday& y) NOEXCEPT; +CONSTCD14 weekday operator-(const weekday& x, const days& y) NOEXCEPT; +CONSTCD14 days operator-(const weekday& x, const weekday& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday& wd); + +// weekday_indexed + +class weekday_indexed +{ + unsigned char wd_ : 4; + unsigned char index_ : 4; + +public: + CONSTCD11 weekday_indexed(const julian::weekday& wd, unsigned index) NOEXCEPT; + + CONSTCD11 julian::weekday weekday() const NOEXCEPT; + CONSTCD11 unsigned index() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT; +CONSTCD11 bool operator!=(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday_indexed& wdi); + +// weekday_last + +class weekday_last +{ + julian::weekday wd_; + +public: + explicit CONSTCD11 weekday_last(const julian::weekday& wd) NOEXCEPT; + + CONSTCD11 julian::weekday weekday() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const weekday_last& x, const weekday_last& y) NOEXCEPT; +CONSTCD11 bool operator!=(const weekday_last& x, const weekday_last& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday_last& wdl); + +// year_month + +class year_month +{ + julian::year y_; + julian::month m_; + +public: + CONSTCD11 year_month(const julian::year& y, const julian::month& m) NOEXCEPT; + + CONSTCD11 julian::year year() const NOEXCEPT; + CONSTCD11 julian::month month() const NOEXCEPT; + + CONSTCD14 year_month& operator+=(const months& dm) NOEXCEPT; + CONSTCD14 year_month& operator-=(const months& dm) NOEXCEPT; + CONSTCD14 year_month& operator+=(const years& dy) NOEXCEPT; + CONSTCD14 year_month& operator-=(const years& dy) NOEXCEPT; + + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator< (const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator> (const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year_month& x, const year_month& y) NOEXCEPT; + +CONSTCD14 year_month operator+(const year_month& ym, const months& dm) NOEXCEPT; +CONSTCD14 year_month operator+(const months& dm, const year_month& ym) NOEXCEPT; +CONSTCD14 year_month operator-(const year_month& ym, const months& dm) NOEXCEPT; + +CONSTCD11 months operator-(const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 year_month operator+(const year_month& ym, const years& dy) NOEXCEPT; +CONSTCD11 year_month operator+(const years& dy, const year_month& ym) NOEXCEPT; +CONSTCD11 year_month operator-(const year_month& ym, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month& ym); + +// month_day + +class month_day +{ + julian::month m_; + julian::day d_; + +public: + CONSTCD11 month_day(const julian::month& m, const julian::day& d) NOEXCEPT; + + CONSTCD11 julian::month month() const NOEXCEPT; + CONSTCD11 julian::day day() const NOEXCEPT; + + CONSTCD14 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator!=(const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator< (const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator> (const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator<=(const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator>=(const month_day& x, const month_day& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_day& md); + +// month_day_last + +class month_day_last +{ + julian::month m_; + +public: + CONSTCD11 explicit month_day_last(const julian::month& m) NOEXCEPT; + + CONSTCD11 julian::month month() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator!=(const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator< (const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator> (const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator<=(const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator>=(const month_day_last& x, const month_day_last& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_day_last& mdl); + +// month_weekday + +class month_weekday +{ + julian::month m_; + julian::weekday_indexed wdi_; +public: + CONSTCD11 month_weekday(const julian::month& m, + const julian::weekday_indexed& wdi) NOEXCEPT; + + CONSTCD11 julian::month month() const NOEXCEPT; + CONSTCD11 julian::weekday_indexed weekday_indexed() const NOEXCEPT; + + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const month_weekday& x, const month_weekday& y) NOEXCEPT; +CONSTCD11 bool operator!=(const month_weekday& x, const month_weekday& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_weekday& mwd); + +// month_weekday_last + +class month_weekday_last +{ + julian::month m_; + julian::weekday_last wdl_; + +public: + CONSTCD11 month_weekday_last(const julian::month& m, + const julian::weekday_last& wd) NOEXCEPT; + + CONSTCD11 julian::month month() const NOEXCEPT; + CONSTCD11 julian::weekday_last weekday_last() const NOEXCEPT; + + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 + bool operator==(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT; +CONSTCD11 + bool operator!=(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_weekday_last& mwdl); + +// class year_month_day + +class year_month_day +{ + julian::year y_; + julian::month m_; + julian::day d_; + +public: + CONSTCD11 year_month_day(const julian::year& y, const julian::month& m, + const julian::day& d) NOEXCEPT; + CONSTCD14 year_month_day(const year_month_day_last& ymdl) NOEXCEPT; + + CONSTCD14 year_month_day(sys_days dp) NOEXCEPT; + CONSTCD14 explicit year_month_day(local_days dp) NOEXCEPT; + + CONSTCD14 year_month_day& operator+=(const months& m) NOEXCEPT; + CONSTCD14 year_month_day& operator-=(const months& m) NOEXCEPT; + CONSTCD14 year_month_day& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year_month_day& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 julian::year year() const NOEXCEPT; + CONSTCD11 julian::month month() const NOEXCEPT; + CONSTCD11 julian::day day() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD14 bool ok() const NOEXCEPT; + +private: + static CONSTCD14 year_month_day from_days(days dp) NOEXCEPT; + CONSTCD14 days to_days() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator< (const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator> (const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year_month_day& x, const year_month_day& y) NOEXCEPT; + +CONSTCD14 year_month_day operator+(const year_month_day& ymd, const months& dm) NOEXCEPT; +CONSTCD14 year_month_day operator+(const months& dm, const year_month_day& ymd) NOEXCEPT; +CONSTCD14 year_month_day operator-(const year_month_day& ymd, const months& dm) NOEXCEPT; +CONSTCD11 year_month_day operator+(const year_month_day& ymd, const years& dy) NOEXCEPT; +CONSTCD11 year_month_day operator+(const years& dy, const year_month_day& ymd) NOEXCEPT; +CONSTCD11 year_month_day operator-(const year_month_day& ymd, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_day& ymd); + +// year_month_day_last + +class year_month_day_last +{ + julian::year y_; + julian::month_day_last mdl_; + +public: + CONSTCD11 year_month_day_last(const julian::year& y, + const julian::month_day_last& mdl) NOEXCEPT; + + CONSTCD14 year_month_day_last& operator+=(const months& m) NOEXCEPT; + CONSTCD14 year_month_day_last& operator-=(const months& m) NOEXCEPT; + CONSTCD14 year_month_day_last& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year_month_day_last& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 julian::year year() const NOEXCEPT; + CONSTCD11 julian::month month() const NOEXCEPT; + CONSTCD11 julian::month_day_last month_day_last() const NOEXCEPT; + CONSTCD14 julian::day day() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 + bool operator==(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator!=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator< (const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator> (const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator<=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator>=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; + +CONSTCD14 +year_month_day_last +operator+(const year_month_day_last& ymdl, const months& dm) NOEXCEPT; + +CONSTCD14 +year_month_day_last +operator+(const months& dm, const year_month_day_last& ymdl) NOEXCEPT; + +CONSTCD11 +year_month_day_last +operator+(const year_month_day_last& ymdl, const years& dy) NOEXCEPT; + +CONSTCD11 +year_month_day_last +operator+(const years& dy, const year_month_day_last& ymdl) NOEXCEPT; + +CONSTCD14 +year_month_day_last +operator-(const year_month_day_last& ymdl, const months& dm) NOEXCEPT; + +CONSTCD11 +year_month_day_last +operator-(const year_month_day_last& ymdl, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_day_last& ymdl); + +// year_month_weekday + +class year_month_weekday +{ + julian::year y_; + julian::month m_; + julian::weekday_indexed wdi_; + +public: + CONSTCD11 year_month_weekday(const julian::year& y, const julian::month& m, + const julian::weekday_indexed& wdi) NOEXCEPT; + CONSTCD14 year_month_weekday(const sys_days& dp) NOEXCEPT; + CONSTCD14 explicit year_month_weekday(const local_days& dp) NOEXCEPT; + + CONSTCD14 year_month_weekday& operator+=(const months& m) NOEXCEPT; + CONSTCD14 year_month_weekday& operator-=(const months& m) NOEXCEPT; + CONSTCD14 year_month_weekday& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year_month_weekday& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 julian::year year() const NOEXCEPT; + CONSTCD11 julian::month month() const NOEXCEPT; + CONSTCD11 julian::weekday weekday() const NOEXCEPT; + CONSTCD11 unsigned index() const NOEXCEPT; + CONSTCD11 julian::weekday_indexed weekday_indexed() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD14 bool ok() const NOEXCEPT; + +private: + static CONSTCD14 year_month_weekday from_days(days dp) NOEXCEPT; + CONSTCD14 days to_days() const NOEXCEPT; +}; + +CONSTCD11 + bool operator==(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT; +CONSTCD11 + bool operator!=(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT; + +CONSTCD14 +year_month_weekday +operator+(const year_month_weekday& ymwd, const months& dm) NOEXCEPT; + +CONSTCD14 +year_month_weekday +operator+(const months& dm, const year_month_weekday& ymwd) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator+(const year_month_weekday& ymwd, const years& dy) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator+(const years& dy, const year_month_weekday& ymwd) NOEXCEPT; + +CONSTCD14 +year_month_weekday +operator-(const year_month_weekday& ymwd, const months& dm) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator-(const year_month_weekday& ymwd, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_weekday& ymwdi); + +// year_month_weekday_last + +class year_month_weekday_last +{ + julian::year y_; + julian::month m_; + julian::weekday_last wdl_; + +public: + CONSTCD11 year_month_weekday_last(const julian::year& y, const julian::month& m, + const julian::weekday_last& wdl) NOEXCEPT; + + CONSTCD14 year_month_weekday_last& operator+=(const months& m) NOEXCEPT; + CONSTCD14 year_month_weekday_last& operator-=(const months& m) NOEXCEPT; + CONSTCD14 year_month_weekday_last& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year_month_weekday_last& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 julian::year year() const NOEXCEPT; + CONSTCD11 julian::month month() const NOEXCEPT; + CONSTCD11 julian::weekday weekday() const NOEXCEPT; + CONSTCD11 julian::weekday_last weekday_last() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; + +private: + CONSTCD14 days to_days() const NOEXCEPT; +}; + +CONSTCD11 +bool +operator==(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT; + +CONSTCD11 +bool +operator!=(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT; + +CONSTCD14 +year_month_weekday_last +operator+(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT; + +CONSTCD14 +year_month_weekday_last +operator+(const months& dm, const year_month_weekday_last& ymwdl) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator+(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator+(const years& dy, const year_month_weekday_last& ymwdl) NOEXCEPT; + +CONSTCD14 +year_month_weekday_last +operator-(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator-(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_weekday_last& ymwdl); + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) +inline namespace literals +{ + +CONSTCD11 julian::day operator "" _d(unsigned long long d) NOEXCEPT; +CONSTCD11 julian::year operator "" _y(unsigned long long y) NOEXCEPT; + +// CONSTDATA julian::month jan{1}; +// CONSTDATA julian::month feb{2}; +// CONSTDATA julian::month mar{3}; +// CONSTDATA julian::month apr{4}; +// CONSTDATA julian::month may{5}; +// CONSTDATA julian::month jun{6}; +// CONSTDATA julian::month jul{7}; +// CONSTDATA julian::month aug{8}; +// CONSTDATA julian::month sep{9}; +// CONSTDATA julian::month oct{10}; +// CONSTDATA julian::month nov{11}; +// CONSTDATA julian::month dec{12}; + +} // inline namespace literals +#endif // !defined(_MSC_VER) || (_MSC_VER >= 1900) + +//----------------+ +// Implementation | +//----------------+ + +// day + +CONSTCD11 inline day::day(unsigned d) NOEXCEPT : d_(static_cast(d)) {} +CONSTCD14 inline day& day::operator++() NOEXCEPT {++d_; return *this;} +CONSTCD14 inline day day::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +CONSTCD14 inline day& day::operator--() NOEXCEPT {--d_; return *this;} +CONSTCD14 inline day day::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} +CONSTCD14 inline day& day::operator+=(const days& d) NOEXCEPT {*this = *this + d; return *this;} +CONSTCD14 inline day& day::operator-=(const days& d) NOEXCEPT {*this = *this - d; return *this;} +CONSTCD11 inline day::operator unsigned() const NOEXCEPT {return d_;} +CONSTCD11 inline bool day::ok() const NOEXCEPT {return 1 <= d_ && d_ <= 31;} + +CONSTCD11 +inline +bool +operator==(const day& x, const day& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const day& x, const day& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const day& x, const day& y) NOEXCEPT +{ + return static_cast(x) < static_cast(y); +} + +CONSTCD11 +inline +bool +operator>(const day& x, const day& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const day& x, const day& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const day& x, const day& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD11 +inline +days +operator-(const day& x, const day& y) NOEXCEPT +{ + return days{static_cast(static_cast(x) + - static_cast(y))}; +} + +CONSTCD11 +inline +day +operator+(const day& x, const days& y) NOEXCEPT +{ + return day{static_cast(x) + static_cast(y.count())}; +} + +CONSTCD11 +inline +day +operator+(const days& x, const day& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD11 +inline +day +operator-(const day& x, const days& y) NOEXCEPT +{ + return x + -y; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const day& d) +{ + date::detail::save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::right); + os.width(2); + os << static_cast(d); + return os; +} + +// month + +CONSTCD11 inline month::month(unsigned m) NOEXCEPT : m_(static_cast(m)) {} +CONSTCD14 inline month& month::operator++() NOEXCEPT {if (++m_ == 13) m_ = 1; return *this;} +CONSTCD14 inline month month::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +CONSTCD14 inline month& month::operator--() NOEXCEPT {if (--m_ == 0) m_ = 12; return *this;} +CONSTCD14 inline month month::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} + +CONSTCD14 +inline +month& +month::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +CONSTCD14 +inline +month& +month::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD11 inline month::operator unsigned() const NOEXCEPT {return m_;} +CONSTCD11 inline bool month::ok() const NOEXCEPT {return 1 <= m_ && m_ <= 12;} + +CONSTCD11 +inline +bool +operator==(const month& x, const month& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const month& x, const month& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const month& x, const month& y) NOEXCEPT +{ + return static_cast(x) < static_cast(y); +} + +CONSTCD11 +inline +bool +operator>(const month& x, const month& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const month& x, const month& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const month& x, const month& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD14 +inline +months +operator-(const month& x, const month& y) NOEXCEPT +{ + auto const d = static_cast(x) - static_cast(y); + return months(d <= 11 ? d : d + 12); +} + +CONSTCD14 +inline +month +operator+(const month& x, const months& y) NOEXCEPT +{ + auto const mu = static_cast(static_cast(x)) - 1 + y.count(); + auto const yr = (mu >= 0 ? mu : mu-11) / 12; + return month{static_cast(mu - yr * 12 + 1)}; +} + +CONSTCD14 +inline +month +operator+(const months& x, const month& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD14 +inline +month +operator-(const month& x, const months& y) NOEXCEPT +{ + return x + -y; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month& m) +{ + switch (static_cast(m)) + { + case 1: + os << "Jan"; + break; + case 2: + os << "Feb"; + break; + case 3: + os << "Mar"; + break; + case 4: + os << "Apr"; + break; + case 5: + os << "May"; + break; + case 6: + os << "Jun"; + break; + case 7: + os << "Jul"; + break; + case 8: + os << "Aug"; + break; + case 9: + os << "Sep"; + break; + case 10: + os << "Oct"; + break; + case 11: + os << "Nov"; + break; + case 12: + os << "Dec"; + break; + default: + os << static_cast(m) << " is not a valid month"; + break; + } + return os; +} + +// year + +CONSTCD11 inline year::year(int y) NOEXCEPT : y_(static_cast(y)) {} +CONSTCD14 inline year& year::operator++() NOEXCEPT {++y_; return *this;} +CONSTCD14 inline year year::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +CONSTCD14 inline year& year::operator--() NOEXCEPT {--y_; return *this;} +CONSTCD14 inline year year::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} +CONSTCD14 inline year& year::operator+=(const years& y) NOEXCEPT {*this = *this + y; return *this;} +CONSTCD14 inline year& year::operator-=(const years& y) NOEXCEPT {*this = *this - y; return *this;} + +CONSTCD11 +inline +bool +year::is_leap() const NOEXCEPT +{ + return y_ % 4 == 0; +} + +CONSTCD11 inline year::operator int() const NOEXCEPT {return y_;} +CONSTCD11 inline bool year::ok() const NOEXCEPT {return true;} + +CONSTCD11 +inline +year +year::min() NOEXCEPT +{ + return year{std::numeric_limits::min()}; +} + +CONSTCD11 +inline +year +year::max() NOEXCEPT +{ + return year{std::numeric_limits::max()}; +} + +CONSTCD11 +inline +bool +operator==(const year& x, const year& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const year& x, const year& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year& x, const year& y) NOEXCEPT +{ + return static_cast(x) < static_cast(y); +} + +CONSTCD11 +inline +bool +operator>(const year& x, const year& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year& x, const year& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year& x, const year& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD11 +inline +years +operator-(const year& x, const year& y) NOEXCEPT +{ + return years{static_cast(x) - static_cast(y)}; +} + +CONSTCD11 +inline +year +operator+(const year& x, const years& y) NOEXCEPT +{ + return year{static_cast(x) + y.count()}; +} + +CONSTCD11 +inline +year +operator+(const years& x, const year& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD11 +inline +year +operator-(const year& x, const years& y) NOEXCEPT +{ + return year{static_cast(x) - y.count()}; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year& y) +{ + date::detail::save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::internal); + os.width(4 + (y < year{0})); + os << static_cast(y); + return os; +} + +// weekday + +CONSTCD11 +inline +unsigned char +weekday::weekday_from_days(int z) NOEXCEPT +{ + return static_cast(static_cast( + z >= -4 ? (z+4) % 7 : (z+5) % 7 + 6)); +} + +CONSTCD11 +inline +weekday::weekday(unsigned wd) NOEXCEPT + : wd_(static_cast(wd)) + {} + +CONSTCD11 +inline +weekday::weekday(const sys_days& dp) NOEXCEPT + : wd_(weekday_from_days(dp.time_since_epoch().count())) + {} + +CONSTCD11 +inline +weekday::weekday(const local_days& dp) NOEXCEPT + : wd_(weekday_from_days(dp.time_since_epoch().count())) + {} + +CONSTCD14 inline weekday& weekday::operator++() NOEXCEPT {if (++wd_ == 7) wd_ = 0; return *this;} +CONSTCD14 inline weekday weekday::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +CONSTCD14 inline weekday& weekday::operator--() NOEXCEPT {if (wd_-- == 0) wd_ = 6; return *this;} +CONSTCD14 inline weekday weekday::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} + +CONSTCD14 +inline +weekday& +weekday::operator+=(const days& d) NOEXCEPT +{ + *this = *this + d; + return *this; +} + +CONSTCD14 +inline +weekday& +weekday::operator-=(const days& d) NOEXCEPT +{ + *this = *this - d; + return *this; +} + +CONSTCD11 +inline +weekday::operator unsigned() const NOEXCEPT +{ + return static_cast(wd_); +} + +CONSTCD11 inline bool weekday::ok() const NOEXCEPT {return wd_ <= 6;} + +CONSTCD11 +inline +bool +operator==(const weekday& x, const weekday& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const weekday& x, const weekday& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD14 +inline +days +operator-(const weekday& x, const weekday& y) NOEXCEPT +{ + auto const diff = static_cast(x) - static_cast(y); + return days{diff <= 6 ? diff : diff + 7}; +} + +CONSTCD14 +inline +weekday +operator+(const weekday& x, const days& y) NOEXCEPT +{ + auto const wdu = static_cast(static_cast(x)) + y.count(); + auto const wk = (wdu >= 0 ? wdu : wdu-6) / 7; + return weekday{static_cast(wdu - wk * 7)}; +} + +CONSTCD14 +inline +weekday +operator+(const days& x, const weekday& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD14 +inline +weekday +operator-(const weekday& x, const days& y) NOEXCEPT +{ + return x + -y; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday& wd) +{ + switch (static_cast(wd)) + { + case 0: + os << "Sun"; + break; + case 1: + os << "Mon"; + break; + case 2: + os << "Tue"; + break; + case 3: + os << "Wed"; + break; + case 4: + os << "Thu"; + break; + case 5: + os << "Fri"; + break; + case 6: + os << "Sat"; + break; + default: + os << static_cast(wd) << " is not a valid weekday"; + break; + } + return os; +} + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) +inline namespace literals +{ + +CONSTCD11 +inline +julian::day +operator "" _d(unsigned long long d) NOEXCEPT +{ + return julian::day{static_cast(d)}; +} + +CONSTCD11 +inline +julian::year +operator "" _y(unsigned long long y) NOEXCEPT +{ + return julian::year(static_cast(y)); +} +#endif // !defined(_MSC_VER) || (_MSC_VER >= 1900) + +CONSTDATA julian::last_spec last{}; + +CONSTDATA julian::month jan{1}; +CONSTDATA julian::month feb{2}; +CONSTDATA julian::month mar{3}; +CONSTDATA julian::month apr{4}; +CONSTDATA julian::month may{5}; +CONSTDATA julian::month jun{6}; +CONSTDATA julian::month jul{7}; +CONSTDATA julian::month aug{8}; +CONSTDATA julian::month sep{9}; +CONSTDATA julian::month oct{10}; +CONSTDATA julian::month nov{11}; +CONSTDATA julian::month dec{12}; + +CONSTDATA julian::weekday sun{0u}; +CONSTDATA julian::weekday mon{1u}; +CONSTDATA julian::weekday tue{2u}; +CONSTDATA julian::weekday wed{3u}; +CONSTDATA julian::weekday thu{4u}; +CONSTDATA julian::weekday fri{5u}; +CONSTDATA julian::weekday sat{6u}; + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) +} // inline namespace literals +#endif + +// weekday_indexed + +CONSTCD11 +inline +weekday +weekday_indexed::weekday() const NOEXCEPT +{ + return julian::weekday{static_cast(wd_)}; +} + +CONSTCD11 inline unsigned weekday_indexed::index() const NOEXCEPT {return index_;} + +CONSTCD11 +inline +bool +weekday_indexed::ok() const NOEXCEPT +{ + return weekday().ok() && 1 <= index_ && index_ <= 5; +} + +CONSTCD11 +inline +weekday_indexed::weekday_indexed(const julian::weekday& wd, unsigned index) NOEXCEPT + : wd_(static_cast(static_cast(wd))) + , index_(static_cast(index)) + {} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday_indexed& wdi) +{ + return os << wdi.weekday() << '[' << wdi.index() << ']'; +} + +CONSTCD11 +inline +weekday_indexed +weekday::operator[](unsigned index) const NOEXCEPT +{ + return {*this, index}; +} + +CONSTCD11 +inline +bool +operator==(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT +{ + return x.weekday() == y.weekday() && x.index() == y.index(); +} + +CONSTCD11 +inline +bool +operator!=(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT +{ + return !(x == y); +} + +// weekday_last + +CONSTCD11 inline julian::weekday weekday_last::weekday() const NOEXCEPT {return wd_;} +CONSTCD11 inline bool weekday_last::ok() const NOEXCEPT {return wd_.ok();} +CONSTCD11 inline weekday_last::weekday_last(const julian::weekday& wd) NOEXCEPT : wd_(wd) {} + +CONSTCD11 +inline +bool +operator==(const weekday_last& x, const weekday_last& y) NOEXCEPT +{ + return x.weekday() == y.weekday(); +} + +CONSTCD11 +inline +bool +operator!=(const weekday_last& x, const weekday_last& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday_last& wdl) +{ + return os << wdl.weekday() << "[last]"; +} + +CONSTCD11 +inline +weekday_last +weekday::operator[](last_spec) const NOEXCEPT +{ + return weekday_last{*this}; +} + +// year_month + +CONSTCD11 +inline +year_month::year_month(const julian::year& y, const julian::month& m) NOEXCEPT + : y_(y) + , m_(m) + {} + +CONSTCD11 inline year year_month::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month::month() const NOEXCEPT {return m_;} +CONSTCD11 inline bool year_month::ok() const NOEXCEPT {return y_.ok() && m_.ok();} + +CONSTCD14 +inline +year_month& +year_month::operator+=(const months& dm) NOEXCEPT +{ + *this = *this + dm; + return *this; +} + +CONSTCD14 +inline +year_month& +year_month::operator-=(const months& dm) NOEXCEPT +{ + *this = *this - dm; + return *this; +} + +CONSTCD14 +inline +year_month& +year_month::operator+=(const years& dy) NOEXCEPT +{ + *this = *this + dy; + return *this; +} + +CONSTCD14 +inline +year_month& +year_month::operator-=(const years& dy) NOEXCEPT +{ + *this = *this - dy; + return *this; +} + +CONSTCD11 +inline +bool +operator==(const year_month& x, const year_month& y) NOEXCEPT +{ + return x.year() == y.year() && x.month() == y.month(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month& x, const year_month& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year_month& x, const year_month& y) NOEXCEPT +{ + return x.year() < y.year() ? true + : (x.year() > y.year() ? false + : (x.month() < y.month())); +} + +CONSTCD11 +inline +bool +operator>(const year_month& x, const year_month& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year_month& x, const year_month& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year_month& x, const year_month& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD14 +inline +year_month +operator+(const year_month& ym, const months& dm) NOEXCEPT +{ + auto dmi = static_cast(static_cast(ym.month())) - 1 + dm.count(); + auto dy = (dmi >= 0 ? dmi : dmi-11) / 12; + dmi = dmi - dy * 12 + 1; + return (ym.year() + years(dy)) / month(static_cast(dmi)); +} + +CONSTCD14 +inline +year_month +operator+(const months& dm, const year_month& ym) NOEXCEPT +{ + return ym + dm; +} + +CONSTCD14 +inline +year_month +operator-(const year_month& ym, const months& dm) NOEXCEPT +{ + return ym + -dm; +} + +CONSTCD11 +inline +months +operator-(const year_month& x, const year_month& y) NOEXCEPT +{ + return (x.year() - y.year()) + + months(static_cast(x.month()) - static_cast(y.month())); +} + +CONSTCD11 +inline +year_month +operator+(const year_month& ym, const years& dy) NOEXCEPT +{ + return (ym.year() + dy) / ym.month(); +} + +CONSTCD11 +inline +year_month +operator+(const years& dy, const year_month& ym) NOEXCEPT +{ + return ym + dy; +} + +CONSTCD11 +inline +year_month +operator-(const year_month& ym, const years& dy) NOEXCEPT +{ + return ym + -dy; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month& ym) +{ + return os << ym.year() << '/' << ym.month(); +} + +// month_day + +CONSTCD11 +inline +month_day::month_day(const julian::month& m, const julian::day& d) NOEXCEPT + : m_(m) + , d_(d) + {} + +CONSTCD11 inline julian::month month_day::month() const NOEXCEPT {return m_;} +CONSTCD11 inline julian::day month_day::day() const NOEXCEPT {return d_;} + +CONSTCD14 +inline +bool +month_day::ok() const NOEXCEPT +{ + CONSTDATA julian::day d[] = { + julian::day(31), julian::day(29), julian::day(31), julian::day(30), + julian::day(31), julian::day(30), julian::day(31), julian::day(31), + julian::day(30), julian::day(31), julian::day(30), julian::day(31) + }; + return m_.ok() && julian::day(1) <= d_ && d_ <= d[static_cast(m_)-1]; +} + +CONSTCD11 +inline +bool +operator==(const month_day& x, const month_day& y) NOEXCEPT +{ + return x.month() == y.month() && x.day() == y.day(); +} + +CONSTCD11 +inline +bool +operator!=(const month_day& x, const month_day& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const month_day& x, const month_day& y) NOEXCEPT +{ + return x.month() < y.month() ? true + : (x.month() > y.month() ? false + : (x.day() < y.day())); +} + +CONSTCD11 +inline +bool +operator>(const month_day& x, const month_day& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const month_day& x, const month_day& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const month_day& x, const month_day& y) NOEXCEPT +{ + return !(x < y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_day& md) +{ + return os << md.month() << '/' << md.day(); +} + +// month_day_last + +CONSTCD11 inline month month_day_last::month() const NOEXCEPT {return m_;} +CONSTCD11 inline bool month_day_last::ok() const NOEXCEPT {return m_.ok();} +CONSTCD11 inline month_day_last::month_day_last(const julian::month& m) NOEXCEPT : m_(m) {} + +CONSTCD11 +inline +bool +operator==(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return x.month() == y.month(); +} + +CONSTCD11 +inline +bool +operator!=(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return x.month() < y.month(); +} + +CONSTCD11 +inline +bool +operator>(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return !(x < y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_day_last& mdl) +{ + return os << mdl.month() << "/last"; +} + +// month_weekday + +CONSTCD11 +inline +month_weekday::month_weekday(const julian::month& m, + const julian::weekday_indexed& wdi) NOEXCEPT + : m_(m) + , wdi_(wdi) + {} + +CONSTCD11 inline month month_weekday::month() const NOEXCEPT {return m_;} + +CONSTCD11 +inline +weekday_indexed +month_weekday::weekday_indexed() const NOEXCEPT +{ + return wdi_; +} + +CONSTCD11 +inline +bool +month_weekday::ok() const NOEXCEPT +{ + return m_.ok() && wdi_.ok(); +} + +CONSTCD11 +inline +bool +operator==(const month_weekday& x, const month_weekday& y) NOEXCEPT +{ + return x.month() == y.month() && x.weekday_indexed() == y.weekday_indexed(); +} + +CONSTCD11 +inline +bool +operator!=(const month_weekday& x, const month_weekday& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_weekday& mwd) +{ + return os << mwd.month() << '/' << mwd.weekday_indexed(); +} + +// month_weekday_last + +CONSTCD11 +inline +month_weekday_last::month_weekday_last(const julian::month& m, + const julian::weekday_last& wdl) NOEXCEPT + : m_(m) + , wdl_(wdl) + {} + +CONSTCD11 inline month month_weekday_last::month() const NOEXCEPT {return m_;} + +CONSTCD11 +inline +weekday_last +month_weekday_last::weekday_last() const NOEXCEPT +{ + return wdl_; +} + +CONSTCD11 +inline +bool +month_weekday_last::ok() const NOEXCEPT +{ + return m_.ok() && wdl_.ok(); +} + +CONSTCD11 +inline +bool +operator==(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT +{ + return x.month() == y.month() && x.weekday_last() == y.weekday_last(); +} + +CONSTCD11 +inline +bool +operator!=(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_weekday_last& mwdl) +{ + return os << mwdl.month() << '/' << mwdl.weekday_last(); +} + +// year_month_day_last + +CONSTCD11 +inline +year_month_day_last::year_month_day_last(const julian::year& y, + const julian::month_day_last& mdl) NOEXCEPT + : y_(y) + , mdl_(mdl) + {} + +CONSTCD14 +inline +year_month_day_last& +year_month_day_last::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +CONSTCD14 +inline +year_month_day_last& +year_month_day_last::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD14 +inline +year_month_day_last& +year_month_day_last::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +CONSTCD14 +inline +year_month_day_last& +year_month_day_last::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD11 inline year year_month_day_last::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month_day_last::month() const NOEXCEPT {return mdl_.month();} + +CONSTCD11 +inline +month_day_last +year_month_day_last::month_day_last() const NOEXCEPT +{ + return mdl_; +} + +CONSTCD14 +inline +day +year_month_day_last::day() const NOEXCEPT +{ + CONSTDATA julian::day d[] = { + julian::day(31), julian::day(28), julian::day(31), julian::day(30), + julian::day(31), julian::day(30), julian::day(31), julian::day(31), + julian::day(30), julian::day(31), julian::day(30), julian::day(31) + }; + return month() != feb || !y_.is_leap() ? d[static_cast(month())-1] : julian::day(29); +} + +CONSTCD14 +inline +year_month_day_last::operator sys_days() const NOEXCEPT +{ + return sys_days(year()/month()/day()); +} + +CONSTCD14 +inline +year_month_day_last::operator local_days() const NOEXCEPT +{ + return local_days(year()/month()/day()); +} + +CONSTCD11 +inline +bool +year_month_day_last::ok() const NOEXCEPT +{ + return y_.ok() && mdl_.ok(); +} + +CONSTCD11 +inline +bool +operator==(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return x.year() == y.year() && x.month_day_last() == y.month_day_last(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return x.year() < y.year() ? true + : (x.year() > y.year() ? false + : (x.month_day_last() < y.month_day_last())); +} + +CONSTCD11 +inline +bool +operator>(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return !(x < y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_day_last& ymdl) +{ + return os << ymdl.year() << '/' << ymdl.month_day_last(); +} + +CONSTCD14 +inline +year_month_day_last +operator+(const year_month_day_last& ymdl, const months& dm) NOEXCEPT +{ + return (ymdl.year() / ymdl.month() + dm) / last; +} + +CONSTCD14 +inline +year_month_day_last +operator+(const months& dm, const year_month_day_last& ymdl) NOEXCEPT +{ + return ymdl + dm; +} + +CONSTCD14 +inline +year_month_day_last +operator-(const year_month_day_last& ymdl, const months& dm) NOEXCEPT +{ + return ymdl + (-dm); +} + +CONSTCD11 +inline +year_month_day_last +operator+(const year_month_day_last& ymdl, const years& dy) NOEXCEPT +{ + return {ymdl.year()+dy, ymdl.month_day_last()}; +} + +CONSTCD11 +inline +year_month_day_last +operator+(const years& dy, const year_month_day_last& ymdl) NOEXCEPT +{ + return ymdl + dy; +} + +CONSTCD11 +inline +year_month_day_last +operator-(const year_month_day_last& ymdl, const years& dy) NOEXCEPT +{ + return ymdl + (-dy); +} + +// year_month_day + +CONSTCD11 +inline +year_month_day::year_month_day(const julian::year& y, const julian::month& m, + const julian::day& d) NOEXCEPT + : y_(y) + , m_(m) + , d_(d) + {} + +CONSTCD14 +inline +year_month_day::year_month_day(const year_month_day_last& ymdl) NOEXCEPT + : y_(ymdl.year()) + , m_(ymdl.month()) + , d_(ymdl.day()) + {} + +CONSTCD14 +inline +year_month_day::year_month_day(sys_days dp) NOEXCEPT + : year_month_day(from_days(dp.time_since_epoch())) + {} + +CONSTCD14 +inline +year_month_day::year_month_day(local_days dp) NOEXCEPT + : year_month_day(from_days(dp.time_since_epoch())) + {} + +CONSTCD11 inline year year_month_day::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month_day::month() const NOEXCEPT {return m_;} +CONSTCD11 inline day year_month_day::day() const NOEXCEPT {return d_;} + +CONSTCD14 +inline +year_month_day& +year_month_day::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +CONSTCD14 +inline +year_month_day& +year_month_day::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD14 +inline +year_month_day& +year_month_day::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +CONSTCD14 +inline +year_month_day& +year_month_day::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD14 +inline +days +year_month_day::to_days() const NOEXCEPT +{ + static_assert(std::numeric_limits::digits >= 18, + "This algorithm has not been ported to a 16 bit unsigned integer"); + static_assert(std::numeric_limits::digits >= 20, + "This algorithm has not been ported to a 16 bit signed integer"); + auto const y = static_cast(y_) - (m_ <= feb); + auto const m = static_cast(m_); + auto const d = static_cast(d_); + auto const era = (y >= 0 ? y : y-3) / 4; + auto const yoe = static_cast(y - era * 4); // [0, 3] + auto const doy = (153*(m > 2 ? m-3 : m+9) + 2)/5 + d-1; // [0, 365] + auto const doe = yoe * 365 + doy; // [0, 1460] + return days{era * 1461 + static_cast(doe) - 719470}; +} + +CONSTCD14 +inline +year_month_day::operator sys_days() const NOEXCEPT +{ + return sys_days{to_days()}; +} + +CONSTCD14 +inline +year_month_day::operator local_days() const NOEXCEPT +{ + return local_days{to_days()}; +} + +CONSTCD14 +inline +bool +year_month_day::ok() const NOEXCEPT +{ + if (!(y_.ok() && m_.ok())) + return false; + return julian::day(1) <= d_ && d_ <= (y_/m_/last).day(); +} + +CONSTCD11 +inline +bool +operator==(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return x.year() == y.year() && x.month() == y.month() && x.day() == y.day(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return x.year() < y.year() ? true + : (x.year() > y.year() ? false + : (x.month() < y.month() ? true + : (x.month() > y.month() ? false + : (x.day() < y.day())))); +} + +CONSTCD11 +inline +bool +operator>(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return !(x < y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_day& ymd) +{ + date::detail::save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::right); + os << ymd.year() << '-'; + os.width(2); + os << static_cast(ymd.month()) << '-'; + os << ymd.day(); + return os; +} + +CONSTCD14 +inline +year_month_day +year_month_day::from_days(days dp) NOEXCEPT +{ + static_assert(std::numeric_limits::digits >= 18, + "This algorithm has not been ported to a 16 bit unsigned integer"); + static_assert(std::numeric_limits::digits >= 20, + "This algorithm has not been ported to a 16 bit signed integer"); + auto const z = dp.count() + 719470; + auto const era = (z >= 0 ? z : z - 1460) / 1461; + auto const doe = static_cast(z - era * 1461); // [0, 1460] + auto const yoe = (doe - doe/1460) / 365; // [0, 3] + auto const y = static_cast(yoe) + era * 4; + auto const doy = doe - 365*yoe; // [0, 365] + auto const mp = (5*doy + 2)/153; // [0, 11] + auto const d = doy - (153*mp+2)/5 + 1; // [1, 31] + auto const m = mp < 10 ? mp+3 : mp-9; // [1, 12] + return year_month_day{julian::year{y + (m <= 2)}, julian::month(m), julian::day(d)}; +} + +CONSTCD14 +inline +year_month_day +operator+(const year_month_day& ymd, const months& dm) NOEXCEPT +{ + return (ymd.year() / ymd.month() + dm) / ymd.day(); +} + +CONSTCD14 +inline +year_month_day +operator+(const months& dm, const year_month_day& ymd) NOEXCEPT +{ + return ymd + dm; +} + +CONSTCD14 +inline +year_month_day +operator-(const year_month_day& ymd, const months& dm) NOEXCEPT +{ + return ymd + (-dm); +} + +CONSTCD11 +inline +year_month_day +operator+(const year_month_day& ymd, const years& dy) NOEXCEPT +{ + return (ymd.year() + dy) / ymd.month() / ymd.day(); +} + +CONSTCD11 +inline +year_month_day +operator+(const years& dy, const year_month_day& ymd) NOEXCEPT +{ + return ymd + dy; +} + +CONSTCD11 +inline +year_month_day +operator-(const year_month_day& ymd, const years& dy) NOEXCEPT +{ + return ymd + (-dy); +} + +// year_month_weekday + +CONSTCD11 +inline +year_month_weekday::year_month_weekday(const julian::year& y, const julian::month& m, + const julian::weekday_indexed& wdi) + NOEXCEPT + : y_(y) + , m_(m) + , wdi_(wdi) + {} + +CONSTCD14 +inline +year_month_weekday::year_month_weekday(const sys_days& dp) NOEXCEPT + : year_month_weekday(from_days(dp.time_since_epoch())) + {} + +CONSTCD14 +inline +year_month_weekday::year_month_weekday(const local_days& dp) NOEXCEPT + : year_month_weekday(from_days(dp.time_since_epoch())) + {} + +CONSTCD14 +inline +year_month_weekday& +year_month_weekday::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +CONSTCD14 +inline +year_month_weekday& +year_month_weekday::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD14 +inline +year_month_weekday& +year_month_weekday::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +CONSTCD14 +inline +year_month_weekday& +year_month_weekday::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD11 inline year year_month_weekday::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month_weekday::month() const NOEXCEPT {return m_;} + +CONSTCD11 +inline +weekday +year_month_weekday::weekday() const NOEXCEPT +{ + return wdi_.weekday(); +} + +CONSTCD11 +inline +unsigned +year_month_weekday::index() const NOEXCEPT +{ + return wdi_.index(); +} + +CONSTCD11 +inline +weekday_indexed +year_month_weekday::weekday_indexed() const NOEXCEPT +{ + return wdi_; +} + +CONSTCD14 +inline +year_month_weekday::operator sys_days() const NOEXCEPT +{ + return sys_days{to_days()}; +} + +CONSTCD14 +inline +year_month_weekday::operator local_days() const NOEXCEPT +{ + return local_days{to_days()}; +} + +CONSTCD14 +inline +bool +year_month_weekday::ok() const NOEXCEPT +{ + if (!y_.ok() || !m_.ok() || !wdi_.weekday().ok() || wdi_.index() < 1) + return false; + if (wdi_.index() <= 4) + return true; + auto d2 = wdi_.weekday() - julian::weekday(y_/m_/1) + days((wdi_.index()-1)*7 + 1); + return static_cast(d2.count()) <= static_cast((y_/m_/last).day()); +} + +CONSTCD14 +inline +year_month_weekday +year_month_weekday::from_days(days d) NOEXCEPT +{ + sys_days dp{d}; + auto const wd = julian::weekday(dp); + auto const ymd = year_month_day(dp); + return {ymd.year(), ymd.month(), wd[(static_cast(ymd.day())-1)/7+1]}; +} + +CONSTCD14 +inline +days +year_month_weekday::to_days() const NOEXCEPT +{ + auto d = sys_days(y_/m_/1); + return (d + (wdi_.weekday() - julian::weekday(d) + days{(wdi_.index()-1)*7}) + ).time_since_epoch(); +} + +CONSTCD11 +inline +bool +operator==(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT +{ + return x.year() == y.year() && x.month() == y.month() && + x.weekday_indexed() == y.weekday_indexed(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_weekday& ymwdi) +{ + return os << ymwdi.year() << '/' << ymwdi.month() + << '/' << ymwdi.weekday_indexed(); +} + +CONSTCD14 +inline +year_month_weekday +operator+(const year_month_weekday& ymwd, const months& dm) NOEXCEPT +{ + return (ymwd.year() / ymwd.month() + dm) / ymwd.weekday_indexed(); +} + +CONSTCD14 +inline +year_month_weekday +operator+(const months& dm, const year_month_weekday& ymwd) NOEXCEPT +{ + return ymwd + dm; +} + +CONSTCD14 +inline +year_month_weekday +operator-(const year_month_weekday& ymwd, const months& dm) NOEXCEPT +{ + return ymwd + (-dm); +} + +CONSTCD11 +inline +year_month_weekday +operator+(const year_month_weekday& ymwd, const years& dy) NOEXCEPT +{ + return {ymwd.year()+dy, ymwd.month(), ymwd.weekday_indexed()}; +} + +CONSTCD11 +inline +year_month_weekday +operator+(const years& dy, const year_month_weekday& ymwd) NOEXCEPT +{ + return ymwd + dy; +} + +CONSTCD11 +inline +year_month_weekday +operator-(const year_month_weekday& ymwd, const years& dy) NOEXCEPT +{ + return ymwd + (-dy); +} + +// year_month_weekday_last + +CONSTCD11 +inline +year_month_weekday_last::year_month_weekday_last(const julian::year& y, + const julian::month& m, + const julian::weekday_last& wdl) NOEXCEPT + : y_(y) + , m_(m) + , wdl_(wdl) + {} + +CONSTCD14 +inline +year_month_weekday_last& +year_month_weekday_last::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +CONSTCD14 +inline +year_month_weekday_last& +year_month_weekday_last::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD14 +inline +year_month_weekday_last& +year_month_weekday_last::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +CONSTCD14 +inline +year_month_weekday_last& +year_month_weekday_last::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD11 inline year year_month_weekday_last::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month_weekday_last::month() const NOEXCEPT {return m_;} + +CONSTCD11 +inline +weekday +year_month_weekday_last::weekday() const NOEXCEPT +{ + return wdl_.weekday(); +} + +CONSTCD11 +inline +weekday_last +year_month_weekday_last::weekday_last() const NOEXCEPT +{ + return wdl_; +} + +CONSTCD14 +inline +year_month_weekday_last::operator sys_days() const NOEXCEPT +{ + return sys_days{to_days()}; +} + +CONSTCD14 +inline +year_month_weekday_last::operator local_days() const NOEXCEPT +{ + return local_days{to_days()}; +} + +CONSTCD11 +inline +bool +year_month_weekday_last::ok() const NOEXCEPT +{ + return y_.ok() && m_.ok() && wdl_.ok(); +} + +CONSTCD14 +inline +days +year_month_weekday_last::to_days() const NOEXCEPT +{ + auto const d = sys_days(y_/m_/last); + return (d - (julian::weekday{d} - wdl_.weekday())).time_since_epoch(); +} + +CONSTCD11 +inline +bool +operator==(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT +{ + return x.year() == y.year() && x.month() == y.month() && + x.weekday_last() == y.weekday_last(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_weekday_last& ymwdl) +{ + return os << ymwdl.year() << '/' << ymwdl.month() << '/' << ymwdl.weekday_last(); +} + +CONSTCD14 +inline +year_month_weekday_last +operator+(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT +{ + return (ymwdl.year() / ymwdl.month() + dm) / ymwdl.weekday_last(); +} + +CONSTCD14 +inline +year_month_weekday_last +operator+(const months& dm, const year_month_weekday_last& ymwdl) NOEXCEPT +{ + return ymwdl + dm; +} + +CONSTCD14 +inline +year_month_weekday_last +operator-(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT +{ + return ymwdl + (-dm); +} + +CONSTCD11 +inline +year_month_weekday_last +operator+(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT +{ + return {ymwdl.year()+dy, ymwdl.month(), ymwdl.weekday_last()}; +} + +CONSTCD11 +inline +year_month_weekday_last +operator+(const years& dy, const year_month_weekday_last& ymwdl) NOEXCEPT +{ + return ymwdl + dy; +} + +CONSTCD11 +inline +year_month_weekday_last +operator-(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT +{ + return ymwdl + (-dy); +} + +// year_month from operator/() + +CONSTCD11 +inline +year_month +operator/(const year& y, const month& m) NOEXCEPT +{ + return {y, m}; +} + +CONSTCD11 +inline +year_month +operator/(const year& y, int m) NOEXCEPT +{ + return y / month(static_cast(m)); +} + +// month_day from operator/() + +CONSTCD11 +inline +month_day +operator/(const month& m, const day& d) NOEXCEPT +{ + return {m, d}; +} + +CONSTCD11 +inline +month_day +operator/(const day& d, const month& m) NOEXCEPT +{ + return m / d; +} + +CONSTCD11 +inline +month_day +operator/(const month& m, int d) NOEXCEPT +{ + return m / day(static_cast(d)); +} + +CONSTCD11 +inline +month_day +operator/(int m, const day& d) NOEXCEPT +{ + return month(static_cast(m)) / d; +} + +CONSTCD11 inline month_day operator/(const day& d, int m) NOEXCEPT {return m / d;} + +// month_day_last from operator/() + +CONSTCD11 +inline +month_day_last +operator/(const month& m, last_spec) NOEXCEPT +{ + return month_day_last{m}; +} + +CONSTCD11 +inline +month_day_last +operator/(last_spec, const month& m) NOEXCEPT +{ + return m/last; +} + +CONSTCD11 +inline +month_day_last +operator/(int m, last_spec) NOEXCEPT +{ + return month(static_cast(m))/last; +} + +CONSTCD11 +inline +month_day_last +operator/(last_spec, int m) NOEXCEPT +{ + return m/last; +} + +// month_weekday from operator/() + +CONSTCD11 +inline +month_weekday +operator/(const month& m, const weekday_indexed& wdi) NOEXCEPT +{ + return {m, wdi}; +} + +CONSTCD11 +inline +month_weekday +operator/(const weekday_indexed& wdi, const month& m) NOEXCEPT +{ + return m / wdi; +} + +CONSTCD11 +inline +month_weekday +operator/(int m, const weekday_indexed& wdi) NOEXCEPT +{ + return month(static_cast(m)) / wdi; +} + +CONSTCD11 +inline +month_weekday +operator/(const weekday_indexed& wdi, int m) NOEXCEPT +{ + return m / wdi; +} + +// month_weekday_last from operator/() + +CONSTCD11 +inline +month_weekday_last +operator/(const month& m, const weekday_last& wdl) NOEXCEPT +{ + return {m, wdl}; +} + +CONSTCD11 +inline +month_weekday_last +operator/(const weekday_last& wdl, const month& m) NOEXCEPT +{ + return m / wdl; +} + +CONSTCD11 +inline +month_weekday_last +operator/(int m, const weekday_last& wdl) NOEXCEPT +{ + return month(static_cast(m)) / wdl; +} + +CONSTCD11 +inline +month_weekday_last +operator/(const weekday_last& wdl, int m) NOEXCEPT +{ + return m / wdl; +} + +// year_month_day from operator/() + +CONSTCD11 +inline +year_month_day +operator/(const year_month& ym, const day& d) NOEXCEPT +{ + return {ym.year(), ym.month(), d}; +} + +CONSTCD11 +inline +year_month_day +operator/(const year_month& ym, int d) NOEXCEPT +{ + return ym / day(static_cast(d)); +} + +CONSTCD11 +inline +year_month_day +operator/(const year& y, const month_day& md) NOEXCEPT +{ + return y / md.month() / md.day(); +} + +CONSTCD11 +inline +year_month_day +operator/(int y, const month_day& md) NOEXCEPT +{ + return year(y) / md; +} + +CONSTCD11 +inline +year_month_day +operator/(const month_day& md, const year& y) NOEXCEPT +{ + return y / md; +} + +CONSTCD11 +inline +year_month_day +operator/(const month_day& md, int y) NOEXCEPT +{ + return year(y) / md; +} + +// year_month_day_last from operator/() + +CONSTCD11 +inline +year_month_day_last +operator/(const year_month& ym, last_spec) NOEXCEPT +{ + return {ym.year(), month_day_last{ym.month()}}; +} + +CONSTCD11 +inline +year_month_day_last +operator/(const year& y, const month_day_last& mdl) NOEXCEPT +{ + return {y, mdl}; +} + +CONSTCD11 +inline +year_month_day_last +operator/(int y, const month_day_last& mdl) NOEXCEPT +{ + return year(y) / mdl; +} + +CONSTCD11 +inline +year_month_day_last +operator/(const month_day_last& mdl, const year& y) NOEXCEPT +{ + return y / mdl; +} + +CONSTCD11 +inline +year_month_day_last +operator/(const month_day_last& mdl, int y) NOEXCEPT +{ + return year(y) / mdl; +} + +// year_month_weekday from operator/() + +CONSTCD11 +inline +year_month_weekday +operator/(const year_month& ym, const weekday_indexed& wdi) NOEXCEPT +{ + return {ym.year(), ym.month(), wdi}; +} + +CONSTCD11 +inline +year_month_weekday +operator/(const year& y, const month_weekday& mwd) NOEXCEPT +{ + return {y, mwd.month(), mwd.weekday_indexed()}; +} + +CONSTCD11 +inline +year_month_weekday +operator/(int y, const month_weekday& mwd) NOEXCEPT +{ + return year(y) / mwd; +} + +CONSTCD11 +inline +year_month_weekday +operator/(const month_weekday& mwd, const year& y) NOEXCEPT +{ + return y / mwd; +} + +CONSTCD11 +inline +year_month_weekday +operator/(const month_weekday& mwd, int y) NOEXCEPT +{ + return year(y) / mwd; +} + +// year_month_weekday_last from operator/() + +CONSTCD11 +inline +year_month_weekday_last +operator/(const year_month& ym, const weekday_last& wdl) NOEXCEPT +{ + return {ym.year(), ym.month(), wdl}; +} + +CONSTCD11 +inline +year_month_weekday_last +operator/(const year& y, const month_weekday_last& mwdl) NOEXCEPT +{ + return {y, mwdl.month(), mwdl.weekday_last()}; +} + +CONSTCD11 +inline +year_month_weekday_last +operator/(int y, const month_weekday_last& mwdl) NOEXCEPT +{ + return year(y) / mwdl; +} + +CONSTCD11 +inline +year_month_weekday_last +operator/(const month_weekday_last& mwdl, const year& y) NOEXCEPT +{ + return y / mwdl; +} + +CONSTCD11 +inline +year_month_weekday_last +operator/(const month_weekday_last& mwdl, int y) NOEXCEPT +{ + return year(y) / mwdl; +} + +} // namespace julian + +#endif // JULIAN_H diff --git a/third_party/date/include/date/ptz.h b/third_party/date/include/date/ptz.h new file mode 100644 index 0000000..ebd6e04 --- /dev/null +++ b/third_party/date/include/date/ptz.h @@ -0,0 +1,861 @@ +#ifndef PTZ_H +#define PTZ_H + +// The MIT License (MIT) +// +// Copyright (c) 2017 Howard Hinnant +// +// 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. + +// This header allows Posix-style time zones as specified for TZ here: +// http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_03 +// +// Posix::time_zone can be constructed with a posix-style string and then used in +// a zoned_time like so: +// +// zoned_time zt{"EST5EDT,M3.2.0,M11.1.0", +// system_clock::now()}; +// or: +// +// Posix::time_zone tz{"EST5EDT,M3.2.0,M11.1.0"}; +// zoned_time zt{tz, system_clock::now()}; +// +// If the rule set is missing (everything starting with ','), then the rule is that the +// alternate offset is never enabled. +// +// Note, Posix-style time zones are not recommended for all of the reasons described here: +// https://stackoverflow.com/tags/timezone/info +// +// They are provided here as a non-trivial custom time zone example, and if you really +// have to have Posix time zones, you're welcome to use this one. + +#include "date/tz.h" +#include +#include +#include + +namespace Posix +{ + +namespace detail +{ + +#if HAS_STRING_VIEW + +using string_t = std::string_view; + +#else // !HAS_STRING_VIEW + +using string_t = std::string; + +#endif // !HAS_STRING_VIEW + +class rule; + +void throw_invalid(const string_t& s, unsigned i, const string_t& message); +unsigned read_date(const string_t& s, unsigned i, rule& r); +unsigned read_name(const string_t& s, unsigned i, std::string& name); +unsigned read_signed_time(const string_t& s, unsigned i, std::chrono::seconds& t); +unsigned read_unsigned_time(const string_t& s, unsigned i, std::chrono::seconds& t); +unsigned read_unsigned(const string_t& s, unsigned i, unsigned limit, unsigned& u, + const string_t& message = string_t{}); + +class rule +{ + enum {off, J, M, N}; + + date::month m_; + date::weekday wd_; + unsigned short n_ : 14; + unsigned short mode_ : 2; + std::chrono::duration time_ = std::chrono::hours{2}; + +public: + rule() : mode_(off) {} + + bool ok() const {return mode_ != off;} + date::local_seconds operator()(date::year y) const; + std::string to_string() const; + + friend std::ostream& operator<<(std::ostream& os, const rule& r); + friend unsigned read_date(const string_t& s, unsigned i, rule& r); + friend bool operator==(const rule& x, const rule& y); +}; + +inline +bool +operator==(const rule& x, const rule& y) +{ + if (x.mode_ != y.mode_) + return false; + switch (x.mode_) + { + case rule::J: + case rule::N: + return x.n_ == y.n_; + case rule::M: + return x.m_ == y.m_ && x.n_ == y.n_ && x.wd_ == y.wd_; + default: + return true; + } +} + +inline +bool +operator!=(const rule& x, const rule& y) +{ + return !(x == y); +} + +inline +date::local_seconds +rule::operator()(date::year y) const +{ + using date::local_days; + using date::January; + using date::days; + using date::last; + using sec = std::chrono::seconds; + date::local_seconds t; + switch (mode_) + { + case J: + t = local_days{y/January/0} + days{n_ + (y.is_leap() && n_ > 59)} + sec{time_}; + break; + case M: + t = (n_ == 5 ? local_days{y/m_/wd_[last]} : local_days{y/m_/wd_[n_]}) + sec{time_}; + break; + case N: + t = local_days{y/January/1} + days{n_} + sec{time_}; + break; + default: + assert(!"rule called with bad mode"); + } + return t; +} + +inline +std::string +rule::to_string() const +{ + using namespace std::chrono; + auto print_offset = [](seconds off) + { + std::string nm; + if (off != hours{2}) + { + date::hh_mm_ss offset{off}; + nm = '/'; + nm += std::to_string(offset.hours().count()); + if (offset.minutes() != minutes{0} || offset.seconds() != seconds{0}) + { + nm += ':'; + if (offset.minutes() < minutes{10}) + nm += '0'; + nm += std::to_string(offset.minutes().count()); + if (offset.seconds() != seconds{0}) + { + nm += ':'; + if (offset.seconds() < seconds{10}) + nm += '0'; + nm += std::to_string(offset.seconds().count()); + } + } + } + return nm; + }; + + std::string nm; + switch (mode_) + { + case rule::J: + nm = 'J'; + nm += std::to_string(n_); + break; + case rule::M: + nm = 'M'; + nm += std::to_string(static_cast(m_)); + nm += '.'; + nm += std::to_string(n_); + nm += '.'; + nm += std::to_string(wd_.c_encoding()); + break; + case rule::N: + nm = std::to_string(n_); + break; + default: + break; + } + nm += print_offset(time_); + return nm; +} + +inline +std::ostream& +operator<<(std::ostream& os, const rule& r) +{ + switch (r.mode_) + { + case rule::J: + os << 'J' << r.n_ << date::format(" %T", r.time_); + break; + case rule::M: + if (r.n_ == 5) + os << r.m_/r.wd_[date::last]; + else + os << r.m_/r.wd_[r.n_]; + os << date::format(" %T", r.time_); + break; + case rule::N: + os << r.n_ << date::format(" %T", r.time_); + break; + default: + break; + } + return os; +} + +} // namespace detail + +class time_zone +{ + std::string std_abbrev_; + std::string dst_abbrev_ = {}; + std::chrono::seconds offset_; + std::chrono::seconds save_ = std::chrono::hours{1}; + detail::rule start_rule_; + detail::rule end_rule_; + +public: + explicit time_zone(const detail::string_t& name); + + template + date::sys_info get_info(date::sys_time st) const; + template + date::local_info get_info(date::local_time tp) const; + + template + date::sys_time::type> + to_sys(date::local_time tp) const; + + template + date::sys_time::type> + to_sys(date::local_time tp, date::choose z) const; + + template + date::local_time::type> + to_local(date::sys_time tp) const; + + friend std::ostream& operator<<(std::ostream& os, const time_zone& z); + + const time_zone* operator->() const {return this;} + + std::string name() const; + + friend bool operator==(const time_zone& x, const time_zone& y); + +private: + date::sys_seconds get_start(date::year y) const; + date::sys_seconds get_prev_start(date::year y) const; + date::sys_seconds get_next_start(date::year y) const; + date::sys_seconds get_end(date::year y) const; + date::sys_seconds get_prev_end(date::year y) const; + date::sys_seconds get_next_end(date::year y) const; + date::sys_info contant_offset() const; +}; + +inline +date::sys_seconds +time_zone::get_start(date::year y) const +{ + return date::sys_seconds{(start_rule_(y) - offset_).time_since_epoch()}; +} + +inline +date::sys_seconds +time_zone::get_prev_start(date::year y) const +{ + return date::sys_seconds{(start_rule_(--y) - offset_).time_since_epoch()}; +} + +inline +date::sys_seconds +time_zone::get_next_start(date::year y) const +{ + return date::sys_seconds{(start_rule_(++y) - offset_).time_since_epoch()}; +} + +inline +date::sys_seconds +time_zone::get_end(date::year y) const +{ + return date::sys_seconds{(end_rule_(y) - (offset_ + save_)).time_since_epoch()}; +} + +inline +date::sys_seconds +time_zone::get_prev_end(date::year y) const +{ + return date::sys_seconds{(end_rule_(--y) - (offset_ + save_)).time_since_epoch()}; +} + +inline +date::sys_seconds +time_zone::get_next_end(date::year y) const +{ + return date::sys_seconds{(end_rule_(++y) - (offset_ + save_)).time_since_epoch()}; +} + +date::sys_info +time_zone::contant_offset() const +{ + using date::year; + using date::sys_info; + using date::sys_days; + using date::January; + using date::December; + using date::last; + sys_info r; + r.begin = sys_days{year::min()/January/1}; + r.end = sys_days{year::max()/December/last}; + r.abbrev = std_abbrev_; + r.offset = offset_; + return r; +} + +inline +time_zone::time_zone(const detail::string_t& s) +{ + using detail::read_name; + using detail::read_signed_time; + using detail::throw_invalid; + auto i = read_name(s, 0, std_abbrev_); + i = read_signed_time(s, i, offset_); + offset_ = -offset_; + if (i != s.size()) + { + i = read_name(s, i, dst_abbrev_); + if (i != s.size()) + { + if (s[i] != ',') + { + i = read_signed_time(s, i, save_); + save_ = -save_ - offset_; + } + if (i != s.size()) + { + if (s[i] != ',') + throw_invalid(s, i, "Expecting end of string or ',' to start rule"); + ++i; + i = read_date(s, i, start_rule_); + if (i == s.size() || s[i] != ',') + throw_invalid(s, i, "Expecting ',' and then the ending rule"); + ++i; + i = read_date(s, i, end_rule_); + if (i != s.size()) + throw_invalid(s, i, "Found unexpected trailing characters"); + } + } + } +} + +template +date::sys_info +time_zone::get_info(date::sys_time st) const +{ + using date::sys_info; + using date::year_month_day; + using date::sys_days; + using date::floor; + using date::ceil; + using date::days; + using date::year; + using date::January; + using date::December; + using date::last; + using std::chrono::minutes; + sys_info r{}; + r.offset = offset_; + if (start_rule_.ok()) + { + auto y = year_month_day{floor(st)}.year(); + auto start = get_start(y); + auto end = get_end(y); + if (start <= end) // (northern hemisphere) + { + if (start <= st && st < end) + { + r.begin = start; + r.end = end; + r.offset += save_; + r.save = ceil(save_); + r.abbrev = dst_abbrev_; + } + else if (st < start) + { + r.begin = get_prev_end(y); + r.end = start; + r.abbrev = std_abbrev_; + } + else // st >= end + { + r.begin = end; + r.end = get_next_start(y); + r.abbrev = std_abbrev_; + } + } + else // end < start (southern hemisphere) + { + if (end <= st && st < start) + { + r.begin = end; + r.end = start; + r.abbrev = std_abbrev_; + } + else if (st < end) + { + r.begin = get_prev_start(y); + r.end = end; + r.offset += save_; + r.save = ceil(save_); + r.abbrev = dst_abbrev_; + } + else // st >= start + { + r.begin = start; + r.end = get_next_end(y); + r.offset += save_; + r.save = ceil(save_); + r.abbrev = dst_abbrev_; + } + } + } + else + r = contant_offset(); + return r; +} + +template +date::local_info +time_zone::get_info(date::local_time tp) const +{ + using date::local_info; + using date::year_month_day; + using date::days; + using date::sys_days; + using date::sys_seconds; + using date::year; + using date::ceil; + using date::January; + using date::December; + using date::last; + using std::chrono::seconds; + using std::chrono::minutes; + local_info r{}; + using date::floor; + if (start_rule_.ok()) + { + auto y = year_month_day{floor(tp)}.year(); + auto start = get_start(y); + auto end = get_end(y); + auto utcs = sys_seconds{floor(tp - offset_).time_since_epoch()}; + auto utcd = sys_seconds{floor(tp - (offset_ + save_)).time_since_epoch()}; + auto northern = start <= end; + if ((utcs < start) != (utcd < start)) + { + if (northern) + r.first.begin = get_prev_end(y); + else + r.first.begin = end; + r.first.end = start; + r.first.offset = offset_; + r.first.abbrev = std_abbrev_; + r.second.begin = start; + if (northern) + r.second.end = end; + else + r.second.end = get_next_end(y); + r.second.abbrev = dst_abbrev_; + r.second.offset = offset_ + save_; + r.second.save = ceil(save_); + r.result = save_ > seconds{0} ? local_info::nonexistent + : local_info::ambiguous; + } + else if ((utcs < end) != (utcd < end)) + { + if (northern) + r.first.begin = start; + else + r.first.begin = get_prev_start(y); + r.first.end = end; + r.first.offset = offset_ + save_; + r.first.save = ceil(save_); + r.first.abbrev = dst_abbrev_; + r.second.begin = end; + if (northern) + r.second.end = get_next_start(y); + else + r.second.end = start; + r.second.abbrev = std_abbrev_; + r.second.offset = offset_; + r.result = save_ > seconds{0} ? local_info::ambiguous + : local_info::nonexistent; + } + else + r.first = get_info(utcs); + } + else + r.first = contant_offset(); + return r; +} + +template +date::sys_time::type> +time_zone::to_sys(date::local_time tp) const +{ + using date::local_info; + using date::sys_time; + using date::ambiguous_local_time; + using date::nonexistent_local_time; + auto i = get_info(tp); + if (i.result == local_info::nonexistent) + throw nonexistent_local_time(tp, i); + else if (i.result == local_info::ambiguous) + throw ambiguous_local_time(tp, i); + return sys_time{tp.time_since_epoch()} - i.first.offset; +} + +template +date::sys_time::type> +time_zone::to_sys(date::local_time tp, date::choose z) const +{ + using date::local_info; + using date::sys_time; + using date::choose; + auto i = get_info(tp); + if (i.result == local_info::nonexistent) + { + return i.first.end; + } + else if (i.result == local_info::ambiguous) + { + if (z == choose::latest) + return sys_time{tp.time_since_epoch()} - i.second.offset; + } + return sys_time{tp.time_since_epoch()} - i.first.offset; +} + +template +date::local_time::type> +time_zone::to_local(date::sys_time tp) const +{ + using date::local_time; + using std::chrono::seconds; + using LT = local_time::type>; + auto i = get_info(tp); + return LT{(tp + i.offset).time_since_epoch()}; +} + +inline +std::ostream& +operator<<(std::ostream& os, const time_zone& z) +{ + using date::operator<<; + os << '{'; + os << z.std_abbrev_ << ", " << z.dst_abbrev_ << date::format(", %T, ", z.offset_) + << date::format("%T, [", z.save_) << z.start_rule_ << ", " << z.end_rule_ << ")}"; + return os; +} + +inline +std::string +time_zone::name() const +{ + using namespace date; + using namespace std::chrono; + auto nm = std_abbrev_; + auto print_offset = [](seconds off) + { + std::string nm; + hh_mm_ss offset{-off}; + if (offset.is_negative()) + nm += '-'; + nm += std::to_string(offset.hours().count()); + if (offset.minutes() != minutes{0} || offset.seconds() != seconds{0}) + { + nm += ':'; + if (offset.minutes() < minutes{10}) + nm += '0'; + nm += std::to_string(offset.minutes().count()); + if (offset.seconds() != seconds{0}) + { + nm += ':'; + if (offset.seconds() < seconds{10}) + nm += '0'; + nm += std::to_string(offset.seconds().count()); + } + } + return nm; + }; + nm += print_offset(offset_); + if (!dst_abbrev_.empty()) + { + nm += dst_abbrev_; + if (save_ != hours{1}) + nm += print_offset(offset_+save_); + if (start_rule_.ok()) + { + nm += ','; + nm += start_rule_.to_string(); + nm += ','; + nm += end_rule_.to_string(); + } + } + return nm; +} + +inline +bool +operator==(const time_zone& x, const time_zone& y) +{ + return x.std_abbrev_ == y.std_abbrev_ && + x.dst_abbrev_ == y. dst_abbrev_ && + x.offset_ == y.offset_ && + x.save_ == y.save_ && + x.start_rule_ == y.start_rule_ && + x.end_rule_ == y.end_rule_; +} + +inline +bool +operator!=(const time_zone& x, const time_zone& y) +{ + return !(x == y); +} + +namespace detail +{ + +inline +void +throw_invalid(const string_t& s, unsigned i, const string_t& message) +{ + throw std::runtime_error(std::string("Invalid time_zone initializer.\n") + + std::string(message) + ":\n" + + std::string(s) + '\n' + + "\x1b[1;32m" + + std::string(i, '~') + '^' + + std::string(i < s.size() ? s.size()-i-1 : 0, '~') + + "\x1b[0m"); +} + +inline +unsigned +read_date(const string_t& s, unsigned i, rule& r) +{ + using date::month; + using date::weekday; + if (i == s.size()) + throw_invalid(s, i, "Expected rule but found end of string"); + if (s[i] == 'J') + { + ++i; + unsigned n; + i = read_unsigned(s, i, 3, n, "Expected to find the Julian day [1, 365]"); + r.mode_ = rule::J; + r.n_ = n; + } + else if (s[i] == 'M') + { + ++i; + unsigned m; + i = read_unsigned(s, i, 2, m, "Expected to find month [1, 12]"); + if (i == s.size() || s[i] != '.') + throw_invalid(s, i, "Expected '.' after month"); + ++i; + unsigned n; + i = read_unsigned(s, i, 1, n, "Expected to find week number [1, 5]"); + if (i == s.size() || s[i] != '.') + throw_invalid(s, i, "Expected '.' after weekday index"); + ++i; + unsigned wd; + i = read_unsigned(s, i, 1, wd, "Expected to find day of week [0, 6]"); + r.mode_ = rule::M; + r.m_ = month{m}; + r.wd_ = weekday{wd}; + r.n_ = n; + } + else if (std::isdigit(s[i])) + { + unsigned n; + i = read_unsigned(s, i, 3, n); + r.mode_ = rule::N; + r.n_ = n; + } + else + throw_invalid(s, i, "Expected 'J', 'M', or a digit to start rule"); + if (i != s.size() && s[i] == '/') + { + ++i; + std::chrono::seconds t; + i = read_unsigned_time(s, i, t); + r.time_ = t; + } + return i; +} + +inline +unsigned +read_name(const string_t& s, unsigned i, std::string& name) +{ + if (i == s.size()) + throw_invalid(s, i, "Expected a name but found end of string"); + if (s[i] == '<') + { + ++i; + while (true) + { + if (i == s.size()) + throw_invalid(s, i, + "Expected to find closing '>', but found end of string"); + if (s[i] == '>') + break; + name.push_back(s[i]); + ++i; + } + ++i; + } + else + { + while (i != s.size() && std::isalpha(s[i])) + { + name.push_back(s[i]); + ++i; + } + } + if (name.size() < 3) + throw_invalid(s, i, "Found name to be shorter than 3 characters"); + return i; +} + +inline +unsigned +read_signed_time(const string_t& s, unsigned i, + std::chrono::seconds& t) +{ + if (i == s.size()) + throw_invalid(s, i, "Expected to read signed time, but found end of string"); + bool negative = false; + if (s[i] == '-') + { + negative = true; + ++i; + } + else if (s[i] == '+') + ++i; + i = read_unsigned_time(s, i, t); + if (negative) + t = -t; + return i; +} + +inline +unsigned +read_unsigned_time(const string_t& s, unsigned i, std::chrono::seconds& t) +{ + using std::chrono::seconds; + using std::chrono::minutes; + using std::chrono::hours; + if (i == s.size()) + throw_invalid(s, i, "Expected to read unsigned time, but found end of string"); + unsigned x; + i = read_unsigned(s, i, 2, x, "Expected to find hours [0, 24]"); + t = hours{x}; + if (i != s.size() && s[i] == ':') + { + ++i; + i = read_unsigned(s, i, 2, x, "Expected to find minutes [0, 59]"); + t += minutes{x}; + if (i != s.size() && s[i] == ':') + { + ++i; + i = read_unsigned(s, i, 2, x, "Expected to find seconds [0, 59]"); + t += seconds{x}; + } + } + return i; +} + +inline +unsigned +read_unsigned(const string_t& s, unsigned i, unsigned limit, unsigned& u, + const string_t& message) +{ + if (i == s.size() || !std::isdigit(s[i])) + throw_invalid(s, i, message); + u = static_cast(s[i] - '0'); + unsigned count = 1; + for (++i; count < limit && i != s.size() && std::isdigit(s[i]); ++i, ++count) + u = u * 10 + static_cast(s[i] - '0'); + return i; +} + +} // namespace detail + +} // namespace Posix + +namespace date +{ + +template <> +struct zoned_traits +{ + +#if HAS_STRING_VIEW + + static + Posix::time_zone + locate_zone(std::string_view name) + { + return Posix::time_zone{name}; + } + +#else // !HAS_STRING_VIEW + + static + Posix::time_zone + locate_zone(const std::string& name) + { + return Posix::time_zone{name}; + } + + static + Posix::time_zone + locate_zone(const char* name) + { + return Posix::time_zone{name}; + } + +#endif // !HAS_STRING_VIEW + +}; + +} // namespace date + +#endif // PTZ_H diff --git a/third_party/date/include/date/solar_hijri.h b/third_party/date/include/date/solar_hijri.h new file mode 100644 index 0000000..6f6c331 --- /dev/null +++ b/third_party/date/include/date/solar_hijri.h @@ -0,0 +1,3151 @@ +#ifndef SOLAR_HIJRI_H +#define SOLAR_HIJRI_H + +// The MIT License (MIT) +// +// Copyright (c) 2016 Howard Hinnant +// Copyright (c) 2019 Asad. Gharighi +// +// Calculations are based on: +// https://www.timeanddate.com/calendar/persian-calendar.html +// and follow style +// +// 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. +// +// Our apologies. When the previous paragraph was written, lowercase had not yet +// been invented (that would involve another several millennia of evolution). +// We did not mean to shout. + +#include "date.h" + +namespace solar_hijri +{ + +namespace internal +{ +static const auto epoch = static_cast(2121446); +static const auto days_in_era = static_cast(1029983); +static const auto years_in_era = static_cast(2820); +static const auto unix_time_shift = static_cast(2440588); +auto const years_in_first_cycle = static_cast(29); +auto const years_in_other_cycles = static_cast(33); +auto const years_in_period = static_cast(128); // 29 + 3*33 +auto const days_in_first_cycle = static_cast(10592); // 28/4 + 29*365 +auto const days_in_other_cycles = static_cast(12053); // 32/4 + 33*365 +auto const days_in_period = static_cast(46751); // days_in_first_cycle + 3*days_in_other_cycles; +} + +// durations + +using days = date::days; + +using weeks = date::weeks; + +using years = std::chrono::duration + , days::period>>; + +using months = std::chrono::duration + >>; + +// time_point + +using sys_days = date::sys_days; +using local_days = date::local_days; + +// types + +struct last_spec +{ + explicit last_spec() = default; +}; + +class day; +class month; +class year; + +class weekday; +class weekday_indexed; +class weekday_last; + +class month_day; +class month_day_last; +class month_weekday; +class month_weekday_last; + +class year_month; + +class year_month_day; +class year_month_day_last; +class year_month_weekday; +class year_month_weekday_last; + +// date composition operators + +CONSTCD11 year_month operator/(const year& y, const month& m) NOEXCEPT; +CONSTCD11 year_month operator/(const year& y, int m) NOEXCEPT; + +CONSTCD11 month_day operator/(const day& d, const month& m) NOEXCEPT; +CONSTCD11 month_day operator/(const day& d, int m) NOEXCEPT; +CONSTCD11 month_day operator/(const month& m, const day& d) NOEXCEPT; +CONSTCD11 month_day operator/(const month& m, int d) NOEXCEPT; +CONSTCD11 month_day operator/(int m, const day& d) NOEXCEPT; + +CONSTCD11 month_day_last operator/(const month& m, last_spec) NOEXCEPT; +CONSTCD11 month_day_last operator/(int m, last_spec) NOEXCEPT; +CONSTCD11 month_day_last operator/(last_spec, const month& m) NOEXCEPT; +CONSTCD11 month_day_last operator/(last_spec, int m) NOEXCEPT; + +CONSTCD11 month_weekday operator/(const month& m, const weekday_indexed& wdi) NOEXCEPT; +CONSTCD11 month_weekday operator/(int m, const weekday_indexed& wdi) NOEXCEPT; +CONSTCD11 month_weekday operator/(const weekday_indexed& wdi, const month& m) NOEXCEPT; +CONSTCD11 month_weekday operator/(const weekday_indexed& wdi, int m) NOEXCEPT; + +CONSTCD11 month_weekday_last operator/(const month& m, const weekday_last& wdl) NOEXCEPT; +CONSTCD11 month_weekday_last operator/(int m, const weekday_last& wdl) NOEXCEPT; +CONSTCD11 month_weekday_last operator/(const weekday_last& wdl, const month& m) NOEXCEPT; +CONSTCD11 month_weekday_last operator/(const weekday_last& wdl, int m) NOEXCEPT; + +CONSTCD11 year_month_day operator/(const year_month& ym, const day& d) NOEXCEPT; +CONSTCD11 year_month_day operator/(const year_month& ym, int d) NOEXCEPT; +CONSTCD11 year_month_day operator/(const year& y, const month_day& md) NOEXCEPT; +CONSTCD11 year_month_day operator/(int y, const month_day& md) NOEXCEPT; +CONSTCD11 year_month_day operator/(const month_day& md, const year& y) NOEXCEPT; +CONSTCD11 year_month_day operator/(const month_day& md, int y) NOEXCEPT; + +CONSTCD11 + year_month_day_last operator/(const year_month& ym, last_spec) NOEXCEPT; +CONSTCD11 + year_month_day_last operator/(const year& y, const month_day_last& mdl) NOEXCEPT; +CONSTCD11 + year_month_day_last operator/(int y, const month_day_last& mdl) NOEXCEPT; +CONSTCD11 + year_month_day_last operator/(const month_day_last& mdl, const year& y) NOEXCEPT; +CONSTCD11 + year_month_day_last operator/(const month_day_last& mdl, int y) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(const year_month& ym, const weekday_indexed& wdi) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(const year& y, const month_weekday& mwd) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(int y, const month_weekday& mwd) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(const month_weekday& mwd, const year& y) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator/(const month_weekday& mwd, int y) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(const year_month& ym, const weekday_last& wdl) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(const year& y, const month_weekday_last& mwdl) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(int y, const month_weekday_last& mwdl) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(const month_weekday_last& mwdl, const year& y) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator/(const month_weekday_last& mwdl, int y) NOEXCEPT; + +// Detailed interface + +// day + +class day +{ + unsigned char d_; + +public: + day() = default; + explicit CONSTCD11 day(unsigned d) NOEXCEPT; + + CONSTCD14 day& operator++() NOEXCEPT; + CONSTCD14 day operator++(int) NOEXCEPT; + CONSTCD14 day& operator--() NOEXCEPT; + CONSTCD14 day operator--(int) NOEXCEPT; + + CONSTCD14 day& operator+=(const days& d) NOEXCEPT; + CONSTCD14 day& operator-=(const days& d) NOEXCEPT; + + CONSTCD11 explicit operator unsigned() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator!=(const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator< (const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator> (const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator<=(const day& x, const day& y) NOEXCEPT; +CONSTCD11 bool operator>=(const day& x, const day& y) NOEXCEPT; + +CONSTCD11 day operator+(const day& x, const days& y) NOEXCEPT; +CONSTCD11 day operator+(const days& x, const day& y) NOEXCEPT; +CONSTCD11 day operator-(const day& x, const days& y) NOEXCEPT; +CONSTCD11 days operator-(const day& x, const day& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const day& d); + +// month + +class month +{ + unsigned char m_; + +public: + month() = default; + explicit CONSTCD11 month(unsigned m) NOEXCEPT; + + CONSTCD14 month& operator++() NOEXCEPT; + CONSTCD14 month operator++(int) NOEXCEPT; + CONSTCD14 month& operator--() NOEXCEPT; + CONSTCD14 month operator--(int) NOEXCEPT; + + CONSTCD14 month& operator+=(const months& m) NOEXCEPT; + CONSTCD14 month& operator-=(const months& m) NOEXCEPT; + + CONSTCD11 explicit operator unsigned() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator!=(const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator< (const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator> (const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator<=(const month& x, const month& y) NOEXCEPT; +CONSTCD11 bool operator>=(const month& x, const month& y) NOEXCEPT; + +CONSTCD14 month operator+(const month& x, const months& y) NOEXCEPT; +CONSTCD14 month operator+(const months& x, const month& y) NOEXCEPT; +CONSTCD14 month operator-(const month& x, const months& y) NOEXCEPT; +CONSTCD14 months operator-(const month& x, const month& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month& m); + +// year + +class year +{ + short y_; + +public: + year() = default; + explicit CONSTCD11 year(int y) NOEXCEPT; + + CONSTCD14 year& operator++() NOEXCEPT; + CONSTCD14 year operator++(int) NOEXCEPT; + CONSTCD14 year& operator--() NOEXCEPT; + CONSTCD14 year operator--(int) NOEXCEPT; + + CONSTCD14 year& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year& operator-=(const years& y) NOEXCEPT; + + CONSTCD14 bool is_leap() const NOEXCEPT; + + CONSTCD11 explicit operator int() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; + + static CONSTCD11 year min() NOEXCEPT; + static CONSTCD11 year max() NOEXCEPT; +}; + +CONSTCD11 bool operator==(const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator< (const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator> (const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year& x, const year& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year& x, const year& y) NOEXCEPT; + +CONSTCD11 year operator+(const year& x, const years& y) NOEXCEPT; +CONSTCD11 year operator+(const years& x, const year& y) NOEXCEPT; +CONSTCD11 year operator-(const year& x, const years& y) NOEXCEPT; +CONSTCD11 years operator-(const year& x, const year& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year& y); + +// weekday + +class weekday +{ + unsigned char wd_; +public: + weekday() = default; + explicit CONSTCD11 weekday(unsigned wd) NOEXCEPT; + explicit weekday(int) = delete; + CONSTCD11 weekday(const sys_days& dp) NOEXCEPT; + CONSTCD11 explicit weekday(const local_days& dp) NOEXCEPT; + + CONSTCD14 weekday& operator++() NOEXCEPT; + CONSTCD14 weekday operator++(int) NOEXCEPT; + CONSTCD14 weekday& operator--() NOEXCEPT; + CONSTCD14 weekday operator--(int) NOEXCEPT; + + CONSTCD14 weekday& operator+=(const days& d) NOEXCEPT; + CONSTCD14 weekday& operator-=(const days& d) NOEXCEPT; + + CONSTCD11 explicit operator unsigned() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; + + CONSTCD11 weekday_indexed operator[](unsigned index) const NOEXCEPT; + CONSTCD11 weekday_last operator[](last_spec) const NOEXCEPT; + +private: + static CONSTCD11 unsigned char weekday_from_days(int z) NOEXCEPT; +}; + +CONSTCD11 bool operator==(const weekday& x, const weekday& y) NOEXCEPT; +CONSTCD11 bool operator!=(const weekday& x, const weekday& y) NOEXCEPT; + +CONSTCD14 weekday operator+(const weekday& x, const days& y) NOEXCEPT; +CONSTCD14 weekday operator+(const days& x, const weekday& y) NOEXCEPT; +CONSTCD14 weekday operator-(const weekday& x, const days& y) NOEXCEPT; +CONSTCD14 days operator-(const weekday& x, const weekday& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday& wd); + +// weekday_indexed + +class weekday_indexed +{ + unsigned char wd_ : 4; + unsigned char index_ : 4; + +public: + weekday_indexed() = default; + CONSTCD11 weekday_indexed(const solar_hijri::weekday& wd, unsigned index) NOEXCEPT; + + CONSTCD11 solar_hijri::weekday weekday() const NOEXCEPT; + CONSTCD11 unsigned index() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT; +CONSTCD11 bool operator!=(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday_indexed& wdi); + +// weekday_last + +class weekday_last +{ + solar_hijri::weekday wd_; + +public: + weekday_last() = default; + explicit CONSTCD11 weekday_last(const solar_hijri::weekday& wd) NOEXCEPT; + + CONSTCD11 solar_hijri::weekday weekday() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const weekday_last& x, const weekday_last& y) NOEXCEPT; +CONSTCD11 bool operator!=(const weekday_last& x, const weekday_last& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday_last& wdl); + +// year_month + +class year_month +{ + solar_hijri::year y_; + solar_hijri::month m_; + +public: + year_month() = default; + CONSTCD11 year_month(const solar_hijri::year& y, const solar_hijri::month& m) NOEXCEPT; + + CONSTCD11 solar_hijri::year year() const NOEXCEPT; + CONSTCD11 solar_hijri::month month() const NOEXCEPT; + + CONSTCD14 year_month& operator+=(const months& dm) NOEXCEPT; + CONSTCD14 year_month& operator-=(const months& dm) NOEXCEPT; + CONSTCD14 year_month& operator+=(const years& dy) NOEXCEPT; + CONSTCD14 year_month& operator-=(const years& dy) NOEXCEPT; + + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator< (const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator> (const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year_month& x, const year_month& y) NOEXCEPT; + +CONSTCD14 year_month operator+(const year_month& ym, const months& dm) NOEXCEPT; +CONSTCD14 year_month operator+(const months& dm, const year_month& ym) NOEXCEPT; +CONSTCD14 year_month operator-(const year_month& ym, const months& dm) NOEXCEPT; + +CONSTCD11 months operator-(const year_month& x, const year_month& y) NOEXCEPT; +CONSTCD11 year_month operator+(const year_month& ym, const years& dy) NOEXCEPT; +CONSTCD11 year_month operator+(const years& dy, const year_month& ym) NOEXCEPT; +CONSTCD11 year_month operator-(const year_month& ym, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month& ym); + +// month_day + +class month_day +{ + solar_hijri::month m_; + solar_hijri::day d_; + +public: + month_day() = default; + CONSTCD11 month_day(const solar_hijri::month& m, const solar_hijri::day& d) NOEXCEPT; + + CONSTCD11 solar_hijri::month month() const NOEXCEPT; + CONSTCD11 solar_hijri::day day() const NOEXCEPT; + + CONSTCD14 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator!=(const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator< (const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator> (const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator<=(const month_day& x, const month_day& y) NOEXCEPT; +CONSTCD11 bool operator>=(const month_day& x, const month_day& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_day& md); + +// month_day_last + +class month_day_last +{ + solar_hijri::month m_; + +public: + month_day_last() = default; + CONSTCD11 explicit month_day_last(const solar_hijri::month& m) NOEXCEPT; + + CONSTCD11 solar_hijri::month month() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator!=(const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator< (const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator> (const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator<=(const month_day_last& x, const month_day_last& y) NOEXCEPT; +CONSTCD11 bool operator>=(const month_day_last& x, const month_day_last& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_day_last& mdl); + +// month_weekday + +class month_weekday +{ + solar_hijri::month m_; + solar_hijri::weekday_indexed wdi_; +public: + month_weekday() = default; + CONSTCD11 month_weekday(const solar_hijri::month& m, + const solar_hijri::weekday_indexed& wdi) NOEXCEPT; + + CONSTCD11 solar_hijri::month month() const NOEXCEPT; + CONSTCD11 solar_hijri::weekday_indexed weekday_indexed() const NOEXCEPT; + + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const month_weekday& x, const month_weekday& y) NOEXCEPT; +CONSTCD11 bool operator!=(const month_weekday& x, const month_weekday& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_weekday& mwd); + +// month_weekday_last + +class month_weekday_last +{ + solar_hijri::month m_; + solar_hijri::weekday_last wdl_; + +public: + month_weekday_last() = default; + CONSTCD11 month_weekday_last(const solar_hijri::month& m, + const solar_hijri::weekday_last& wd) NOEXCEPT; + + CONSTCD11 solar_hijri::month month() const NOEXCEPT; + CONSTCD11 solar_hijri::weekday_last weekday_last() const NOEXCEPT; + + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 + bool operator==(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT; +CONSTCD11 + bool operator!=(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_weekday_last& mwdl); + +// class year_month_day + +class year_month_day +{ + solar_hijri::year y_; + solar_hijri::month m_; + solar_hijri::day d_; + +public: + year_month_day() = default; + CONSTCD11 year_month_day(const solar_hijri::year& y, const solar_hijri::month& m, + const solar_hijri::day& d) NOEXCEPT; + CONSTCD14 year_month_day(const year_month_day_last& ymdl) NOEXCEPT; + + CONSTCD14 year_month_day(sys_days dp) NOEXCEPT; + CONSTCD14 explicit year_month_day(local_days dp) NOEXCEPT; + + CONSTCD14 year_month_day& operator+=(const months& m) NOEXCEPT; + CONSTCD14 year_month_day& operator-=(const months& m) NOEXCEPT; + CONSTCD14 year_month_day& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year_month_day& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 solar_hijri::year year() const NOEXCEPT; + CONSTCD11 solar_hijri::month month() const NOEXCEPT; + CONSTCD11 solar_hijri::day day() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD14 bool ok() const NOEXCEPT; + +private: + static CONSTCD14 year_month_day from_days(days dp) NOEXCEPT; + CONSTCD14 days to_days() const NOEXCEPT; +}; + +CONSTCD11 bool operator==(const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator!=(const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator< (const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator> (const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator<=(const year_month_day& x, const year_month_day& y) NOEXCEPT; +CONSTCD11 bool operator>=(const year_month_day& x, const year_month_day& y) NOEXCEPT; + +CONSTCD14 year_month_day operator+(const year_month_day& ymd, const months& dm) NOEXCEPT; +CONSTCD14 year_month_day operator+(const months& dm, const year_month_day& ymd) NOEXCEPT; +CONSTCD14 year_month_day operator-(const year_month_day& ymd, const months& dm) NOEXCEPT; +CONSTCD11 year_month_day operator+(const year_month_day& ymd, const years& dy) NOEXCEPT; +CONSTCD11 year_month_day operator+(const years& dy, const year_month_day& ymd) NOEXCEPT; +CONSTCD11 year_month_day operator-(const year_month_day& ymd, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_day& ymd); + +// year_month_day_last + +class year_month_day_last +{ + solar_hijri::year y_; + solar_hijri::month_day_last mdl_; + +public: + year_month_day_last() = default; + CONSTCD11 year_month_day_last(const solar_hijri::year& y, + const solar_hijri::month_day_last& mdl) NOEXCEPT; + + CONSTCD14 year_month_day_last& operator+=(const months& m) NOEXCEPT; + CONSTCD14 year_month_day_last& operator-=(const months& m) NOEXCEPT; + CONSTCD14 year_month_day_last& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year_month_day_last& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 solar_hijri::year year() const NOEXCEPT; + CONSTCD11 solar_hijri::month month() const NOEXCEPT; + CONSTCD11 solar_hijri::month_day_last month_day_last() const NOEXCEPT; + CONSTCD14 solar_hijri::day day() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; +}; + +CONSTCD11 + bool operator==(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator!=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator< (const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator> (const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator<=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; +CONSTCD11 + bool operator>=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; + +CONSTCD14 +year_month_day_last +operator+(const year_month_day_last& ymdl, const months& dm) NOEXCEPT; + +CONSTCD14 +year_month_day_last +operator+(const months& dm, const year_month_day_last& ymdl) NOEXCEPT; + +CONSTCD11 +year_month_day_last +operator+(const year_month_day_last& ymdl, const years& dy) NOEXCEPT; + +CONSTCD11 +year_month_day_last +operator+(const years& dy, const year_month_day_last& ymdl) NOEXCEPT; + +CONSTCD14 +year_month_day_last +operator-(const year_month_day_last& ymdl, const months& dm) NOEXCEPT; + +CONSTCD11 +year_month_day_last +operator-(const year_month_day_last& ymdl, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_day_last& ymdl); + +// year_month_weekday + +class year_month_weekday +{ + solar_hijri::year y_; + solar_hijri::month m_; + solar_hijri::weekday_indexed wdi_; + +public: + year_month_weekday() = default; + CONSTCD11 year_month_weekday(const solar_hijri::year& y, const solar_hijri::month& m, + const solar_hijri::weekday_indexed& wdi) NOEXCEPT; + CONSTCD14 year_month_weekday(const sys_days& dp) NOEXCEPT; + CONSTCD14 explicit year_month_weekday(const local_days& dp) NOEXCEPT; + + CONSTCD14 year_month_weekday& operator+=(const months& m) NOEXCEPT; + CONSTCD14 year_month_weekday& operator-=(const months& m) NOEXCEPT; + CONSTCD14 year_month_weekday& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year_month_weekday& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 solar_hijri::year year() const NOEXCEPT; + CONSTCD11 solar_hijri::month month() const NOEXCEPT; + CONSTCD11 solar_hijri::weekday weekday() const NOEXCEPT; + CONSTCD11 unsigned index() const NOEXCEPT; + CONSTCD11 solar_hijri::weekday_indexed weekday_indexed() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD14 bool ok() const NOEXCEPT; + +private: + static CONSTCD14 year_month_weekday from_days(days dp) NOEXCEPT; + CONSTCD14 days to_days() const NOEXCEPT; +}; + +CONSTCD11 + bool operator==(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT; +CONSTCD11 + bool operator!=(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT; + +CONSTCD14 +year_month_weekday +operator+(const year_month_weekday& ymwd, const months& dm) NOEXCEPT; + +CONSTCD14 +year_month_weekday +operator+(const months& dm, const year_month_weekday& ymwd) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator+(const year_month_weekday& ymwd, const years& dy) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator+(const years& dy, const year_month_weekday& ymwd) NOEXCEPT; + +CONSTCD14 +year_month_weekday +operator-(const year_month_weekday& ymwd, const months& dm) NOEXCEPT; + +CONSTCD11 +year_month_weekday +operator-(const year_month_weekday& ymwd, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_weekday& ymwdi); + +// year_month_weekday_last + +class year_month_weekday_last +{ + solar_hijri::year y_; + solar_hijri::month m_; + solar_hijri::weekday_last wdl_; + +public: + year_month_weekday_last() = default; + CONSTCD11 year_month_weekday_last(const solar_hijri::year& y, const solar_hijri::month& m, + const solar_hijri::weekday_last& wdl) NOEXCEPT; + + CONSTCD14 year_month_weekday_last& operator+=(const months& m) NOEXCEPT; + CONSTCD14 year_month_weekday_last& operator-=(const months& m) NOEXCEPT; + CONSTCD14 year_month_weekday_last& operator+=(const years& y) NOEXCEPT; + CONSTCD14 year_month_weekday_last& operator-=(const years& y) NOEXCEPT; + + CONSTCD11 solar_hijri::year year() const NOEXCEPT; + CONSTCD11 solar_hijri::month month() const NOEXCEPT; + CONSTCD11 solar_hijri::weekday weekday() const NOEXCEPT; + CONSTCD11 solar_hijri::weekday_last weekday_last() const NOEXCEPT; + + CONSTCD14 operator sys_days() const NOEXCEPT; + CONSTCD14 explicit operator local_days() const NOEXCEPT; + CONSTCD11 bool ok() const NOEXCEPT; + +private: + CONSTCD14 days to_days() const NOEXCEPT; +}; + +CONSTCD11 +bool +operator==(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT; + +CONSTCD11 +bool +operator!=(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT; + +CONSTCD14 +year_month_weekday_last +operator+(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT; + +CONSTCD14 +year_month_weekday_last +operator+(const months& dm, const year_month_weekday_last& ymwdl) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator+(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator+(const years& dy, const year_month_weekday_last& ymwdl) NOEXCEPT; + +CONSTCD14 +year_month_weekday_last +operator-(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT; + +CONSTCD11 +year_month_weekday_last +operator-(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_weekday_last& ymwdl); + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) +inline namespace literals +{ + +CONSTCD11 solar_hijri::day operator "" _d(unsigned long long d) NOEXCEPT; +CONSTCD11 solar_hijri::year operator "" _y(unsigned long long y) NOEXCEPT; + +} // inline namespace literals +#endif // !defined(_MSC_VER) || (_MSC_VER >= 1900) + +//----------------+ +// Implementation | +//----------------+ + +// day + +CONSTCD11 inline day::day(unsigned d) NOEXCEPT : d_(static_cast(d)) {} +CONSTCD14 inline day& day::operator++() NOEXCEPT {++d_; return *this;} +CONSTCD14 inline day day::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +CONSTCD14 inline day& day::operator--() NOEXCEPT {--d_; return *this;} +CONSTCD14 inline day day::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} +CONSTCD14 inline day& day::operator+=(const days& d) NOEXCEPT {*this = *this + d; return *this;} +CONSTCD14 inline day& day::operator-=(const days& d) NOEXCEPT {*this = *this - d; return *this;} +CONSTCD11 inline day::operator unsigned() const NOEXCEPT {return d_;} +CONSTCD11 inline bool day::ok() const NOEXCEPT {return 1 <= d_ && d_ <= 30;} + +CONSTCD11 +inline +bool +operator==(const day& x, const day& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const day& x, const day& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const day& x, const day& y) NOEXCEPT +{ + return static_cast(x) < static_cast(y); +} + +CONSTCD11 +inline +bool +operator>(const day& x, const day& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const day& x, const day& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const day& x, const day& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD11 +inline +days +operator-(const day& x, const day& y) NOEXCEPT +{ + return days{static_cast(static_cast(x) + - static_cast(y))}; +} + +CONSTCD11 +inline +day +operator+(const day& x, const days& y) NOEXCEPT +{ + return day{static_cast(x) + static_cast(y.count())}; +} + +CONSTCD11 +inline +day +operator+(const days& x, const day& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD11 +inline +day +operator-(const day& x, const days& y) NOEXCEPT +{ + return x + -y; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const day& d) +{ + date::detail::save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::right); + os.width(2); + os << static_cast(d); + return os; +} + +// month + +CONSTCD11 inline month::month(unsigned m) NOEXCEPT : m_(static_cast(m)) {} +CONSTCD14 inline month& month::operator++() NOEXCEPT {if (++m_ == 13) m_ = 1; return *this;} +CONSTCD14 inline month month::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +CONSTCD14 inline month& month::operator--() NOEXCEPT {if (--m_ == 0) m_ = 12; return *this;} +CONSTCD14 inline month month::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} + +CONSTCD14 +inline +month& +month::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +CONSTCD14 +inline +month& +month::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD11 inline month::operator unsigned() const NOEXCEPT {return m_;} +CONSTCD11 inline bool month::ok() const NOEXCEPT {return 1 <= m_ && m_ <= 12;} + +CONSTCD11 +inline +bool +operator==(const month& x, const month& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const month& x, const month& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const month& x, const month& y) NOEXCEPT +{ + return static_cast(x) < static_cast(y); +} + +CONSTCD11 +inline +bool +operator>(const month& x, const month& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const month& x, const month& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const month& x, const month& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD14 +inline +months +operator-(const month& x, const month& y) NOEXCEPT +{ + auto const d = static_cast(x) - static_cast(y); + return months(d <= 11 ? d : d + 12); +} + +CONSTCD14 +inline +month +operator+(const month& x, const months& y) NOEXCEPT +{ + auto const mu = static_cast(static_cast(x)) - 1 + y.count(); + auto const yr = (mu >= 0 ? mu : mu-11) / 12; + return month{static_cast(mu - yr * 12 + 1)}; +} + +CONSTCD14 +inline +month +operator+(const months& x, const month& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD14 +inline +month +operator-(const month& x, const months& y) NOEXCEPT +{ + return x + -y; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month& m) +{ + switch (static_cast(m)) + { + case 1: + os << "Farvardin"; + break; + case 2: + os << "Ordibehesht"; + break; + case 3: + os << "Khordad"; + break; + case 4: + os << "Tir"; + break; + case 5: + os << "Mordad"; + break; + case 6: + os << "Shahrivar"; + break; + case 7: + os << "Mehr"; + break; + case 8: + os << "Aban"; + break; + case 9: + os << "Azar"; + break; + case 10: + os << "Dey"; + break; + case 11: + os << "Bahman"; + break; + case 12: + os << "Esfand"; + break; + default: + os << static_cast(m) << " is not a valid month"; + break; + } + return os; +} + +// year + +CONSTCD11 inline year::year(int y) NOEXCEPT : y_(static_cast(y)) {} +CONSTCD14 inline year& year::operator++() NOEXCEPT {++y_; return *this;} +CONSTCD14 inline year year::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +CONSTCD14 inline year& year::operator--() NOEXCEPT {--y_; return *this;} +CONSTCD14 inline year year::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} +CONSTCD14 inline year& year::operator+=(const years& y) NOEXCEPT {*this = *this + y; return *this;} +CONSTCD14 inline year& year::operator-=(const years& y) NOEXCEPT {*this = *this - y; return *this;} + +CONSTCD14 +inline +bool +year::is_leap() const NOEXCEPT +{ + using namespace internal; + auto const y = static_cast(y_)-475; + auto const era_d = static_cast(y >= 0 ? y : y-years_in_era+1) / static_cast(years_in_era); + auto const era = static_cast(era_d); + auto const yoe = static_cast(y - era * years_in_era); + + // Reference: https://www.timeanddate.com/date/iran-leap-year.html + // 29 + 33 + 33 + 33 = 128 + // 22 * 128 + 4 + auto const yoc = (yoe < (22 * 128)) ? ((yoe%128) < 29 ? yoe%128 : (yoe%128 - 29)%33) : yoe - (22 * 128) + 33; + return (yoc != 0 && (yoc%4)==0); +} + +CONSTCD11 inline year::operator int() const NOEXCEPT {return y_;} +CONSTCD11 inline bool year::ok() const NOEXCEPT {return true;} + +CONSTCD11 +inline +year +year::min() NOEXCEPT +{ + return year{std::numeric_limits::min()}; +} + +CONSTCD11 +inline +year +year::max() NOEXCEPT +{ + return year{std::numeric_limits::max()}; +} + +CONSTCD11 +inline +bool +operator==(const year& x, const year& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const year& x, const year& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year& x, const year& y) NOEXCEPT +{ + return static_cast(x) < static_cast(y); +} + +CONSTCD11 +inline +bool +operator>(const year& x, const year& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year& x, const year& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year& x, const year& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD11 +inline +years +operator-(const year& x, const year& y) NOEXCEPT +{ + return years{static_cast(x) - static_cast(y)}; +} + +CONSTCD11 +inline +year +operator+(const year& x, const years& y) NOEXCEPT +{ + return year{static_cast(x) + y.count()}; +} + +CONSTCD11 +inline +year +operator+(const years& x, const year& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD11 +inline +year +operator-(const year& x, const years& y) NOEXCEPT +{ + return year{static_cast(x) - y.count()}; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year& y) +{ + date::detail::save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::internal); + os.width(4 + (y < year{0})); + os << static_cast(y); + return os; +} + +// weekday + +CONSTCD11 +inline +unsigned char +weekday::weekday_from_days(int z) NOEXCEPT +{ + auto u = static_cast(z); + return static_cast(z >= -4 ? (u+4) % 7 : u % 7); +} + +CONSTCD11 +inline +weekday::weekday(unsigned wd) NOEXCEPT + : wd_(static_cast(wd != 7 ? wd : 0)) + {} + +CONSTCD11 +inline +weekday::weekday(const sys_days& dp) NOEXCEPT + : wd_(weekday_from_days(dp.time_since_epoch().count())) + {} + +CONSTCD11 +inline +weekday::weekday(const local_days& dp) NOEXCEPT + : wd_(weekday_from_days(dp.time_since_epoch().count())) + {} + +CONSTCD14 inline weekday& weekday::operator++() NOEXCEPT {if (++wd_ == 7) wd_ = 0; return *this;} +CONSTCD14 inline weekday weekday::operator++(int) NOEXCEPT {auto tmp(*this); ++(*this); return tmp;} +CONSTCD14 inline weekday& weekday::operator--() NOEXCEPT {if (wd_-- == 0) wd_ = 6; return *this;} +CONSTCD14 inline weekday weekday::operator--(int) NOEXCEPT {auto tmp(*this); --(*this); return tmp;} + +CONSTCD14 +inline +weekday& +weekday::operator+=(const days& d) NOEXCEPT +{ + *this = *this + d; + return *this; +} + +CONSTCD14 +inline +weekday& +weekday::operator-=(const days& d) NOEXCEPT +{ + *this = *this - d; + return *this; +} + +CONSTCD11 +inline +weekday::operator unsigned() const NOEXCEPT +{ + return static_cast(wd_); +} + +CONSTCD11 inline bool weekday::ok() const NOEXCEPT {return wd_ <= 6;} + +CONSTCD11 +inline +bool +operator==(const weekday& x, const weekday& y) NOEXCEPT +{ + return static_cast(x) == static_cast(y); +} + +CONSTCD11 +inline +bool +operator!=(const weekday& x, const weekday& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD14 +inline +days +operator-(const weekday& x, const weekday& y) NOEXCEPT +{ + auto const diff = static_cast(x) - static_cast(y); + return days{diff <= 6 ? diff : diff + 7}; +} + +CONSTCD14 +inline +weekday +operator+(const weekday& x, const days& y) NOEXCEPT +{ + auto const wdu = static_cast(static_cast(x)) + y.count(); + auto const wk = (wdu >= 0 ? wdu : wdu-6) / 7; + return weekday{static_cast(wdu - wk * 7)}; +} + +CONSTCD14 +inline +weekday +operator+(const days& x, const weekday& y) NOEXCEPT +{ + return y + x; +} + +CONSTCD14 +inline +weekday +operator-(const weekday& x, const days& y) NOEXCEPT +{ + return x + -y; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday& wd) +{ + switch (static_cast(wd)) + { + case 0: + os << "Yekshanbe"; + break; + case 1: + os << "Doshanbe"; + break; + case 2: + os << "Seshanbe"; + break; + case 3: + os << "Chaharshanbe"; + break; + case 4: + os << "Panjshanbe"; + break; + case 5: + os << "Adine"; + break; + case 6: + os << "Shanbe"; + break; + default: + os << static_cast(wd) << " is not a valid weekday"; + break; + } + return os; +} + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) +inline namespace literals +{ + +CONSTCD11 +inline +solar_hijri::day +operator "" _d(unsigned long long d) NOEXCEPT +{ + return solar_hijri::day{static_cast(d)}; +} + +CONSTCD11 +inline +solar_hijri::year +operator "" _y(unsigned long long y) NOEXCEPT +{ + return solar_hijri::year(static_cast(y)); +} +#endif // !defined(_MSC_VER) || (_MSC_VER >= 1900) + +CONSTDATA solar_hijri::last_spec last{}; + +CONSTDATA solar_hijri::month far {1}; +CONSTDATA solar_hijri::month ord {2}; +CONSTDATA solar_hijri::month kho {3}; +CONSTDATA solar_hijri::month tir {4}; +CONSTDATA solar_hijri::month mor {5}; +CONSTDATA solar_hijri::month sha {6}; +CONSTDATA solar_hijri::month meh {7}; +CONSTDATA solar_hijri::month aba {8}; +CONSTDATA solar_hijri::month aza {9}; +CONSTDATA solar_hijri::month dey {10}; +CONSTDATA solar_hijri::month bah {11}; +CONSTDATA solar_hijri::month esf {12}; + +CONSTDATA solar_hijri::month Farvardin {1}; +CONSTDATA solar_hijri::month Ordibehesht {2}; +CONSTDATA solar_hijri::month Khordad {3}; +CONSTDATA solar_hijri::month Tir {4}; +CONSTDATA solar_hijri::month Mordad {5}; +CONSTDATA solar_hijri::month Shahrivar {6}; +CONSTDATA solar_hijri::month Mehr {7}; +CONSTDATA solar_hijri::month Aban {8}; +CONSTDATA solar_hijri::month Azar {9}; +CONSTDATA solar_hijri::month Dey {10}; +CONSTDATA solar_hijri::month Bahman {11}; +CONSTDATA solar_hijri::month Esfand {12}; + +CONSTDATA solar_hijri::weekday yek {0u}; +CONSTDATA solar_hijri::weekday dos {1u}; +CONSTDATA solar_hijri::weekday ses {2u}; +CONSTDATA solar_hijri::weekday cha {3u}; +CONSTDATA solar_hijri::weekday pan {4u}; +CONSTDATA solar_hijri::weekday adi {5u}; +CONSTDATA solar_hijri::weekday shn {6u}; + +CONSTDATA solar_hijri::weekday Yekshanbe {0u}; +CONSTDATA solar_hijri::weekday Doshanbe {1u}; +CONSTDATA solar_hijri::weekday Seshanbe {2u}; +CONSTDATA solar_hijri::weekday Chaharshanbe {3u}; +CONSTDATA solar_hijri::weekday Panjshanbe {4u}; +CONSTDATA solar_hijri::weekday Adine {5u}; +CONSTDATA solar_hijri::weekday Shanbe {6u}; + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) +} // inline namespace literals +#endif + +// weekday_indexed + +CONSTCD11 +inline +weekday +weekday_indexed::weekday() const NOEXCEPT +{ + return solar_hijri::weekday{static_cast(wd_)}; +} + +CONSTCD11 inline unsigned weekday_indexed::index() const NOEXCEPT {return index_;} + +CONSTCD11 +inline +bool +weekday_indexed::ok() const NOEXCEPT +{ + return weekday().ok() && 1 <= index_ && index_ <= 5; +} + +CONSTCD11 +inline +weekday_indexed::weekday_indexed(const solar_hijri::weekday& wd, unsigned index) NOEXCEPT + : wd_(static_cast(static_cast(wd))) + , index_(static_cast(index)) + {} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday_indexed& wdi) +{ + return os << wdi.weekday() << '[' << wdi.index() << ']'; +} + +CONSTCD11 +inline +weekday_indexed +weekday::operator[](unsigned index) const NOEXCEPT +{ + return {*this, index}; +} + +CONSTCD11 +inline +bool +operator==(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT +{ + return x.weekday() == y.weekday() && x.index() == y.index(); +} + +CONSTCD11 +inline +bool +operator!=(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT +{ + return !(x == y); +} + +// weekday_last + +CONSTCD11 inline solar_hijri::weekday weekday_last::weekday() const NOEXCEPT {return wd_;} +CONSTCD11 inline bool weekday_last::ok() const NOEXCEPT {return wd_.ok();} +CONSTCD11 inline weekday_last::weekday_last(const solar_hijri::weekday& wd) NOEXCEPT : wd_(wd) {} + +CONSTCD11 +inline +bool +operator==(const weekday_last& x, const weekday_last& y) NOEXCEPT +{ + return x.weekday() == y.weekday(); +} + +CONSTCD11 +inline +bool +operator!=(const weekday_last& x, const weekday_last& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const weekday_last& wdl) +{ + return os << wdl.weekday() << "[last]"; +} + +CONSTCD11 +inline +weekday_last +weekday::operator[](last_spec) const NOEXCEPT +{ + return weekday_last{*this}; +} + +// year_month + +CONSTCD11 +inline +year_month::year_month(const solar_hijri::year& y, const solar_hijri::month& m) NOEXCEPT + : y_(y) + , m_(m) + {} + +CONSTCD11 inline year year_month::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month::month() const NOEXCEPT {return m_;} +CONSTCD11 inline bool year_month::ok() const NOEXCEPT {return y_.ok() && m_.ok();} + +CONSTCD14 +inline +year_month& +year_month::operator+=(const months& dm) NOEXCEPT +{ + *this = *this + dm; + return *this; +} + +CONSTCD14 +inline +year_month& +year_month::operator-=(const months& dm) NOEXCEPT +{ + *this = *this - dm; + return *this; +} + +CONSTCD14 +inline +year_month& +year_month::operator+=(const years& dy) NOEXCEPT +{ + *this = *this + dy; + return *this; +} + +CONSTCD14 +inline +year_month& +year_month::operator-=(const years& dy) NOEXCEPT +{ + *this = *this - dy; + return *this; +} + +CONSTCD11 +inline +bool +operator==(const year_month& x, const year_month& y) NOEXCEPT +{ + return x.year() == y.year() && x.month() == y.month(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month& x, const year_month& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year_month& x, const year_month& y) NOEXCEPT +{ + return x.year() < y.year() ? true + : (x.year() > y.year() ? false + : (x.month() < y.month())); +} + +CONSTCD11 +inline +bool +operator>(const year_month& x, const year_month& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year_month& x, const year_month& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year_month& x, const year_month& y) NOEXCEPT +{ + return !(x < y); +} + +CONSTCD14 +inline +year_month +operator+(const year_month& ym, const months& dm) NOEXCEPT +{ + auto dmi = static_cast(static_cast(ym.month())) - 1 + dm.count(); + auto dy = (dmi >= 0 ? dmi : dmi-11) / 12; + dmi = dmi - dy * 12 + 1; + return (ym.year() + years(dy)) / month(static_cast(dmi)); +} + +CONSTCD14 +inline +year_month +operator+(const months& dm, const year_month& ym) NOEXCEPT +{ + return ym + dm; +} + +CONSTCD14 +inline +year_month +operator-(const year_month& ym, const months& dm) NOEXCEPT +{ + return ym + -dm; +} + +CONSTCD11 +inline +months +operator-(const year_month& x, const year_month& y) NOEXCEPT +{ + return (x.year() - y.year()) + + months(static_cast(x.month()) - static_cast(y.month())); +} + +CONSTCD11 +inline +year_month +operator+(const year_month& ym, const years& dy) NOEXCEPT +{ + return (ym.year() + dy) / ym.month(); +} + +CONSTCD11 +inline +year_month +operator+(const years& dy, const year_month& ym) NOEXCEPT +{ + return ym + dy; +} + +CONSTCD11 +inline +year_month +operator-(const year_month& ym, const years& dy) NOEXCEPT +{ + return ym + -dy; +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month& ym) +{ + return os << ym.year() << '/' << ym.month(); +} + +// month_day + +CONSTCD11 +inline +month_day::month_day(const solar_hijri::month& m, const solar_hijri::day& d) NOEXCEPT + : m_(m) + , d_(d) + {} + +CONSTCD11 inline solar_hijri::month month_day::month() const NOEXCEPT {return m_;} +CONSTCD11 inline solar_hijri::day month_day::day() const NOEXCEPT {return d_;} + +CONSTCD14 +inline +bool +month_day::ok() const NOEXCEPT +{ + CONSTDATA solar_hijri::day d[] = { + solar_hijri::day(31), solar_hijri::day(31), solar_hijri::day(31), + solar_hijri::day(31), solar_hijri::day(31), solar_hijri::day(31), + solar_hijri::day(30), solar_hijri::day(30), solar_hijri::day(30), + solar_hijri::day(30), solar_hijri::day(30), solar_hijri::day(30) + }; + return m_.ok() && solar_hijri::day(1) <= d_ && d_ <= d[static_cast(m_)-1]; +} + +CONSTCD11 +inline +bool +operator==(const month_day& x, const month_day& y) NOEXCEPT +{ + return x.month() == y.month() && x.day() == y.day(); +} + +CONSTCD11 +inline +bool +operator!=(const month_day& x, const month_day& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const month_day& x, const month_day& y) NOEXCEPT +{ + return x.month() < y.month() ? true + : (x.month() > y.month() ? false + : (x.day() < y.day())); +} + +CONSTCD11 +inline +bool +operator>(const month_day& x, const month_day& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const month_day& x, const month_day& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const month_day& x, const month_day& y) NOEXCEPT +{ + return !(x < y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_day& md) +{ + return os << md.month() << '/' << md.day(); +} + +// month_day_last + +CONSTCD11 inline month month_day_last::month() const NOEXCEPT {return m_;} +CONSTCD11 inline bool month_day_last::ok() const NOEXCEPT {return m_.ok();} +CONSTCD11 inline month_day_last::month_day_last(const solar_hijri::month& m) NOEXCEPT : m_(m) {} + +CONSTCD11 +inline +bool +operator==(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return x.month() == y.month(); +} + +CONSTCD11 +inline +bool +operator!=(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return x.month() < y.month(); +} + +CONSTCD11 +inline +bool +operator>(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const month_day_last& x, const month_day_last& y) NOEXCEPT +{ + return !(x < y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_day_last& mdl) +{ + return os << mdl.month() << "/last"; +} + +// month_weekday + +CONSTCD11 +inline +month_weekday::month_weekday(const solar_hijri::month& m, + const solar_hijri::weekday_indexed& wdi) NOEXCEPT + : m_(m) + , wdi_(wdi) + {} + +CONSTCD11 inline month month_weekday::month() const NOEXCEPT {return m_;} + +CONSTCD11 +inline +weekday_indexed +month_weekday::weekday_indexed() const NOEXCEPT +{ + return wdi_; +} + +CONSTCD11 +inline +bool +month_weekday::ok() const NOEXCEPT +{ + return m_.ok() && wdi_.ok(); +} + +CONSTCD11 +inline +bool +operator==(const month_weekday& x, const month_weekday& y) NOEXCEPT +{ + return x.month() == y.month() && x.weekday_indexed() == y.weekday_indexed(); +} + +CONSTCD11 +inline +bool +operator!=(const month_weekday& x, const month_weekday& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_weekday& mwd) +{ + return os << mwd.month() << '/' << mwd.weekday_indexed(); +} + +// month_weekday_last + +CONSTCD11 +inline +month_weekday_last::month_weekday_last(const solar_hijri::month& m, + const solar_hijri::weekday_last& wdl) NOEXCEPT + : m_(m) + , wdl_(wdl) + {} + +CONSTCD11 inline month month_weekday_last::month() const NOEXCEPT {return m_;} + +CONSTCD11 +inline +weekday_last +month_weekday_last::weekday_last() const NOEXCEPT +{ + return wdl_; +} + +CONSTCD11 +inline +bool +month_weekday_last::ok() const NOEXCEPT +{ + return m_.ok() && wdl_.ok(); +} + +CONSTCD11 +inline +bool +operator==(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT +{ + return x.month() == y.month() && x.weekday_last() == y.weekday_last(); +} + +CONSTCD11 +inline +bool +operator!=(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const month_weekday_last& mwdl) +{ + return os << mwdl.month() << '/' << mwdl.weekday_last(); +} + +// year_month_day_last + +CONSTCD11 +inline +year_month_day_last::year_month_day_last(const solar_hijri::year& y, + const solar_hijri::month_day_last& mdl) NOEXCEPT + : y_(y) + , mdl_(mdl) + {} + +CONSTCD14 +inline +year_month_day_last& +year_month_day_last::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +CONSTCD14 +inline +year_month_day_last& +year_month_day_last::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD14 +inline +year_month_day_last& +year_month_day_last::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +CONSTCD14 +inline +year_month_day_last& +year_month_day_last::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD11 inline year year_month_day_last::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month_day_last::month() const NOEXCEPT {return mdl_.month();} + +CONSTCD11 +inline +month_day_last +year_month_day_last::month_day_last() const NOEXCEPT +{ + return mdl_; +} + +CONSTCD14 +inline +day +year_month_day_last::day() const NOEXCEPT +{ + CONSTDATA solar_hijri::day d[] = { + solar_hijri::day(31), solar_hijri::day(31), solar_hijri::day(31), + solar_hijri::day(31), solar_hijri::day(31), solar_hijri::day(31), + solar_hijri::day(30), solar_hijri::day(30), solar_hijri::day(30), + solar_hijri::day(30), solar_hijri::day(30), solar_hijri::day(29) + }; + return month() != esf || !y_.is_leap() ? + d[static_cast(month()) - 1] : solar_hijri::day(30); +} + +CONSTCD14 +inline +year_month_day_last::operator sys_days() const NOEXCEPT +{ + return sys_days(year()/month()/day()); +} + +CONSTCD14 +inline +year_month_day_last::operator local_days() const NOEXCEPT +{ + return local_days(year()/month()/day()); +} + +CONSTCD11 +inline +bool +year_month_day_last::ok() const NOEXCEPT +{ + return y_.ok() && mdl_.ok(); +} + +CONSTCD11 +inline +bool +operator==(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return x.year() == y.year() && x.month_day_last() == y.month_day_last(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return x.year() < y.year() ? true + : (x.year() > y.year() ? false + : (x.month_day_last() < y.month_day_last())); +} + +CONSTCD11 +inline +bool +operator>(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT +{ + return !(x < y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_day_last& ymdl) +{ + return os << ymdl.year() << '/' << ymdl.month_day_last(); +} + +CONSTCD14 +inline +year_month_day_last +operator+(const year_month_day_last& ymdl, const months& dm) NOEXCEPT +{ + return (ymdl.year() / ymdl.month() + dm) / last; +} + +CONSTCD14 +inline +year_month_day_last +operator+(const months& dm, const year_month_day_last& ymdl) NOEXCEPT +{ + return ymdl + dm; +} + +CONSTCD14 +inline +year_month_day_last +operator-(const year_month_day_last& ymdl, const months& dm) NOEXCEPT +{ + return ymdl + (-dm); +} + +CONSTCD11 +inline +year_month_day_last +operator+(const year_month_day_last& ymdl, const years& dy) NOEXCEPT +{ + return {ymdl.year()+dy, ymdl.month_day_last()}; +} + +CONSTCD11 +inline +year_month_day_last +operator+(const years& dy, const year_month_day_last& ymdl) NOEXCEPT +{ + return ymdl + dy; +} + +CONSTCD11 +inline +year_month_day_last +operator-(const year_month_day_last& ymdl, const years& dy) NOEXCEPT +{ + return ymdl + (-dy); +} + +// year_month_day + +CONSTCD11 +inline +year_month_day::year_month_day(const solar_hijri::year& y, const solar_hijri::month& m, + const solar_hijri::day& d) NOEXCEPT + : y_(y) + , m_(m) + , d_(d) + {} + +CONSTCD14 +inline +year_month_day::year_month_day(const year_month_day_last& ymdl) NOEXCEPT + : y_(ymdl.year()) + , m_(ymdl.month()) + , d_(ymdl.day()) + {} + +CONSTCD14 +inline +year_month_day::year_month_day(sys_days dp) NOEXCEPT + : year_month_day(from_days(dp.time_since_epoch())) + {} + +CONSTCD14 +inline +year_month_day::year_month_day(local_days dp) NOEXCEPT + : year_month_day(from_days(dp.time_since_epoch())) + {} + +CONSTCD11 inline year year_month_day::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month_day::month() const NOEXCEPT {return m_;} +CONSTCD11 inline day year_month_day::day() const NOEXCEPT {return d_;} + +CONSTCD14 +inline +year_month_day& +year_month_day::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +CONSTCD14 +inline +year_month_day& +year_month_day::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD14 +inline +year_month_day& +year_month_day::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +CONSTCD14 +inline +year_month_day& +year_month_day::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD14 +inline +days +year_month_day::to_days() const NOEXCEPT +{ + static_assert(std::numeric_limits::digits >= 18, + "This algorithm has not been ported to a 16 bit unsigned integer"); + static_assert(std::numeric_limits::digits >= 20, + "This algorithm has not been ported to a 16 bit signed integer"); + + using namespace internal; + auto const y = static_cast(y_) - 475; + auto const m = static_cast(m_); + auto const d = static_cast(d_); + auto const era_d = static_cast(y >= 0 ? y : y-years_in_era+1) / static_cast(years_in_era); + auto const era = static_cast(era_d); + auto const fdoe = static_cast(epoch + era * days_in_era); + auto const yoe = static_cast(y - era * years_in_era); + + auto const period_d = static_cast(yoe/years_in_period); + auto const period = static_cast(period_d); + auto const yop = yoe%years_in_period; + auto const fdop = period*days_in_period; + auto const cycle = yop < 29 ? 0 : static_cast((yop-29)/years_in_other_cycles + 1); + auto const yoc = yop < 29 ? yop : (yop-29)%years_in_other_cycles; + auto const fdoc = cycle > 0 ? days_in_first_cycle + (cycle-1)*days_in_other_cycles : 0; + auto const group = yoc < 1 ? 0 : static_cast((yoc-1) / 4); + auto const yog = static_cast(yoc < 1 ? -1 : (yoc-1) % 4); + auto const fdoyog = group*1461 + (yog+1)*365; + auto const fdoyoe = fdop + fdoc + fdoyog; + + auto const doy = 30*(m-1) + ((m > 6) ? 6 : m-1) + d-1; // [0, 365] + auto const doe = fdoe + fdoyoe + doy; + return days{doe - unix_time_shift}; +} + +CONSTCD14 +inline +year_month_day::operator sys_days() const NOEXCEPT +{ + return sys_days{to_days()}; +} + +CONSTCD14 +inline +year_month_day::operator local_days() const NOEXCEPT +{ + return local_days{to_days()}; +} + +CONSTCD14 +inline +bool +year_month_day::ok() const NOEXCEPT +{ + if (!(y_.ok() && m_.ok())) + return false; + return solar_hijri::day(1) <= d_ && d_ <= (y_/m_/last).day(); +} + +CONSTCD11 +inline +bool +operator==(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return x.year() == y.year() && x.month() == y.month() && x.day() == y.day(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return !(x == y); +} + +CONSTCD11 +inline +bool +operator<(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return x.year() < y.year() ? true + : (x.year() > y.year() ? false + : (x.month() < y.month() ? true + : (x.month() > y.month() ? false + : (x.day() < y.day())))); +} + +CONSTCD11 +inline +bool +operator>(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return y < x; +} + +CONSTCD11 +inline +bool +operator<=(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return !(y < x); +} + +CONSTCD11 +inline +bool +operator>=(const year_month_day& x, const year_month_day& y) NOEXCEPT +{ + return !(x < y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_day& ymd) +{ + date::detail::save_ostream _(os); + os.fill('0'); + os.flags(std::ios::dec | std::ios::right); + os << ymd.year() << '-'; + os.width(2); + os << static_cast(ymd.month()) << '-'; + os << ymd.day(); + return os; +} + +CONSTCD14 +inline +year_month_day +year_month_day::from_days(days dp) NOEXCEPT +{ + static_assert(std::numeric_limits::digits >= 18, + "This algorithm has not been ported to a 16 bit unsigned integer"); + static_assert(std::numeric_limits::digits >= 20, + "This algorithm has not been ported to a 16 bit signed integer"); + + using namespace internal; + auto const z = dp.count() + unix_time_shift; + auto const delta = static_cast(z - epoch); + auto const era = static_cast(delta >= 0 ? delta : delta-days_in_era+1) / static_cast(days_in_era); + auto const era_i = static_cast(era); + auto const fdoe = static_cast(epoch + static_cast(era_i * days_in_era)); + + auto const doe_fdoe = z - fdoe; + auto const period = static_cast(doe_fdoe < 22*days_in_period ? doe_fdoe / days_in_period : 22); + auto const dop = doe_fdoe % days_in_period; + auto const cycle = dop < days_in_first_cycle ? 0 : (dop-days_in_first_cycle) / days_in_other_cycles + 1; + auto const doc = dop < days_in_first_cycle ? dop : (dop-days_in_first_cycle) % days_in_other_cycles; + auto const group = doc < 365 && period != 22 ? -1 : static_cast(((doc < 365 ? 365 : doc)-365)/1461); + auto const yog = doc < 365 && period != 22 ? -1 : static_cast( (period != 22 ? ((doc-365 )%1461) : doc)/365); + auto const yoc = group == -1 ? 0 : (period != 22 ? 1 : 0) + group*4 + (yog == 4 ? 3 : yog); + auto const doy = group == -1 ? doc : (period != 22 ? ((yoc-1)%4 == 0 ? (group >= 0 ? (doe_fdoe - + (period*days_in_period) - + (cycle > 0 ? days_in_first_cycle + (cycle-1)*days_in_other_cycles : 0) - + (group*1461 + ((yog == 4 ? 3 : yog)+1)*365)) + : 365) + : doe_fdoe - + (period*days_in_period) - + (cycle > 0 ? days_in_first_cycle + (cycle-1)*days_in_other_cycles : 0) - + (group*1461 + ((yog == 4 ? 3 : yog)+1)*365)) + : (yog == 4 ? 365 : doe_fdoe - (period*days_in_period) - yog*365)); + auto const yoe = period != 22 ? period*years_in_period + + (cycle > 0 ? years_in_first_cycle + + (cycle-1)*years_in_other_cycles + : 0) + + yoc + : 22*years_in_period + ((yog == 4) ? 3 : yog); + auto const y = static_cast(static_cast(yoe) + 475 + era_i * years_in_era); + auto const m = doy < 186 ? doy/31 + 1 : (doy-186)/30 + 7; // [1, 12] + auto const d = doy - (30*(m-1) + ((m > 6) ? 6 : m-1) - 1); // [1, 31] + + return year_month_day{solar_hijri::year(y), solar_hijri::month(m), solar_hijri::day(d)}; +} + +CONSTCD14 +inline +year_month_day +operator+(const year_month_day& ymd, const months& dm) NOEXCEPT +{ + return (ymd.year() / ymd.month() + dm) / ymd.day(); +} + +CONSTCD14 +inline +year_month_day +operator+(const months& dm, const year_month_day& ymd) NOEXCEPT +{ + return ymd + dm; +} + +CONSTCD14 +inline +year_month_day +operator-(const year_month_day& ymd, const months& dm) NOEXCEPT +{ + return ymd + (-dm); +} + +CONSTCD11 +inline +year_month_day +operator+(const year_month_day& ymd, const years& dy) NOEXCEPT +{ + return (ymd.year() + dy) / ymd.month() / ymd.day(); +} + +CONSTCD11 +inline +year_month_day +operator+(const years& dy, const year_month_day& ymd) NOEXCEPT +{ + return ymd + dy; +} + +CONSTCD11 +inline +year_month_day +operator-(const year_month_day& ymd, const years& dy) NOEXCEPT +{ + return ymd + (-dy); +} + +// year_month_weekday + +CONSTCD11 +inline +year_month_weekday::year_month_weekday(const solar_hijri::year& y, const solar_hijri::month& m, + const solar_hijri::weekday_indexed& wdi) + NOEXCEPT + : y_(y) + , m_(m) + , wdi_(wdi) + {} + +CONSTCD14 +inline +year_month_weekday::year_month_weekday(const sys_days& dp) NOEXCEPT + : year_month_weekday(from_days(dp.time_since_epoch())) + {} + +CONSTCD14 +inline +year_month_weekday::year_month_weekday(const local_days& dp) NOEXCEPT + : year_month_weekday(from_days(dp.time_since_epoch())) + {} + +CONSTCD14 +inline +year_month_weekday& +year_month_weekday::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +CONSTCD14 +inline +year_month_weekday& +year_month_weekday::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD14 +inline +year_month_weekday& +year_month_weekday::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +CONSTCD14 +inline +year_month_weekday& +year_month_weekday::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD11 inline year year_month_weekday::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month_weekday::month() const NOEXCEPT {return m_;} + +CONSTCD11 +inline +weekday +year_month_weekday::weekday() const NOEXCEPT +{ + return wdi_.weekday(); +} + +CONSTCD11 +inline +unsigned +year_month_weekday::index() const NOEXCEPT +{ + return wdi_.index(); +} + +CONSTCD11 +inline +weekday_indexed +year_month_weekday::weekday_indexed() const NOEXCEPT +{ + return wdi_; +} + +CONSTCD14 +inline +year_month_weekday::operator sys_days() const NOEXCEPT +{ + return sys_days{to_days()}; +} + +CONSTCD14 +inline +year_month_weekday::operator local_days() const NOEXCEPT +{ + return local_days{to_days()}; +} + +CONSTCD14 +inline +bool +year_month_weekday::ok() const NOEXCEPT +{ + if (!y_.ok() || !m_.ok() || !wdi_.weekday().ok() || wdi_.index() < 1) + return false; + if (wdi_.index() <= 4) + return true; + auto d2 = wdi_.weekday() - solar_hijri::weekday(y_/m_/1) + days((wdi_.index()-1)*7 + 1); + return static_cast(d2.count()) <= static_cast((y_/m_/last).day()); +} + +CONSTCD14 +inline +year_month_weekday +year_month_weekday::from_days(days d) NOEXCEPT +{ + sys_days dp{d}; + auto const wd = solar_hijri::weekday(dp); + auto const ymd = year_month_day(dp); + return {ymd.year(), ymd.month(), wd[(static_cast(ymd.day())-1)/7+1]}; +} + +CONSTCD14 +inline +days +year_month_weekday::to_days() const NOEXCEPT +{ + auto d = sys_days(y_/m_/1); + return (d + (wdi_.weekday() - solar_hijri::weekday(d) + days{(wdi_.index()-1)*7}) + ).time_since_epoch(); +} + +CONSTCD11 +inline +bool +operator==(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT +{ + return x.year() == y.year() && x.month() == y.month() && + x.weekday_indexed() == y.weekday_indexed(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_weekday& ymwdi) +{ + return os << ymwdi.year() << '/' << ymwdi.month() + << '/' << ymwdi.weekday_indexed(); +} + +CONSTCD14 +inline +year_month_weekday +operator+(const year_month_weekday& ymwd, const months& dm) NOEXCEPT +{ + return (ymwd.year() / ymwd.month() + dm) / ymwd.weekday_indexed(); +} + +CONSTCD14 +inline +year_month_weekday +operator+(const months& dm, const year_month_weekday& ymwd) NOEXCEPT +{ + return ymwd + dm; +} + +CONSTCD14 +inline +year_month_weekday +operator-(const year_month_weekday& ymwd, const months& dm) NOEXCEPT +{ + return ymwd + (-dm); +} + +CONSTCD11 +inline +year_month_weekday +operator+(const year_month_weekday& ymwd, const years& dy) NOEXCEPT +{ + return {ymwd.year()+dy, ymwd.month(), ymwd.weekday_indexed()}; +} + +CONSTCD11 +inline +year_month_weekday +operator+(const years& dy, const year_month_weekday& ymwd) NOEXCEPT +{ + return ymwd + dy; +} + +CONSTCD11 +inline +year_month_weekday +operator-(const year_month_weekday& ymwd, const years& dy) NOEXCEPT +{ + return ymwd + (-dy); +} + +// year_month_weekday_last + +CONSTCD11 +inline +year_month_weekday_last::year_month_weekday_last(const solar_hijri::year& y, + const solar_hijri::month& m, + const solar_hijri::weekday_last& wdl) NOEXCEPT + : y_(y) + , m_(m) + , wdl_(wdl) + {} + +CONSTCD14 +inline +year_month_weekday_last& +year_month_weekday_last::operator+=(const months& m) NOEXCEPT +{ + *this = *this + m; + return *this; +} + +CONSTCD14 +inline +year_month_weekday_last& +year_month_weekday_last::operator-=(const months& m) NOEXCEPT +{ + *this = *this - m; + return *this; +} + +CONSTCD14 +inline +year_month_weekday_last& +year_month_weekday_last::operator+=(const years& y) NOEXCEPT +{ + *this = *this + y; + return *this; +} + +CONSTCD14 +inline +year_month_weekday_last& +year_month_weekday_last::operator-=(const years& y) NOEXCEPT +{ + *this = *this - y; + return *this; +} + +CONSTCD11 inline year year_month_weekday_last::year() const NOEXCEPT {return y_;} +CONSTCD11 inline month year_month_weekday_last::month() const NOEXCEPT {return m_;} + +CONSTCD11 +inline +weekday +year_month_weekday_last::weekday() const NOEXCEPT +{ + return wdl_.weekday(); +} + +CONSTCD11 +inline +weekday_last +year_month_weekday_last::weekday_last() const NOEXCEPT +{ + return wdl_; +} + +CONSTCD14 +inline +year_month_weekday_last::operator sys_days() const NOEXCEPT +{ + return sys_days{to_days()}; +} + +CONSTCD14 +inline +year_month_weekday_last::operator local_days() const NOEXCEPT +{ + return local_days{to_days()}; +} + +CONSTCD11 +inline +bool +year_month_weekday_last::ok() const NOEXCEPT +{ + return y_.ok() && m_.ok() && wdl_.ok(); +} + +CONSTCD14 +inline +days +year_month_weekday_last::to_days() const NOEXCEPT +{ + auto const d = sys_days(y_/m_/last); + return (d - (solar_hijri::weekday{d} - wdl_.weekday())).time_since_epoch(); +} + +CONSTCD11 +inline +bool +operator==(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT +{ + return x.year() == y.year() && x.month() == y.month() && + x.weekday_last() == y.weekday_last(); +} + +CONSTCD11 +inline +bool +operator!=(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT +{ + return !(x == y); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const year_month_weekday_last& ymwdl) +{ + return os << ymwdl.year() << '/' << ymwdl.month() << '/' << ymwdl.weekday_last(); +} + +CONSTCD14 +inline +year_month_weekday_last +operator+(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT +{ + return (ymwdl.year() / ymwdl.month() + dm) / ymwdl.weekday_last(); +} + +CONSTCD14 +inline +year_month_weekday_last +operator+(const months& dm, const year_month_weekday_last& ymwdl) NOEXCEPT +{ + return ymwdl + dm; +} + +CONSTCD14 +inline +year_month_weekday_last +operator-(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT +{ + return ymwdl + (-dm); +} + +CONSTCD11 +inline +year_month_weekday_last +operator+(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT +{ + return {ymwdl.year()+dy, ymwdl.month(), ymwdl.weekday_last()}; +} + +CONSTCD11 +inline +year_month_weekday_last +operator+(const years& dy, const year_month_weekday_last& ymwdl) NOEXCEPT +{ + return ymwdl + dy; +} + +CONSTCD11 +inline +year_month_weekday_last +operator-(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT +{ + return ymwdl + (-dy); +} + +// year_month from operator/() + +CONSTCD11 +inline +year_month +operator/(const year& y, const month& m) NOEXCEPT +{ + return {y, m}; +} + +CONSTCD11 +inline +year_month +operator/(const year& y, int m) NOEXCEPT +{ + return y / month(static_cast(m)); +} + +// month_day from operator/() + +CONSTCD11 +inline +month_day +operator/(const month& m, const day& d) NOEXCEPT +{ + return {m, d}; +} + +CONSTCD11 +inline +month_day +operator/(const day& d, const month& m) NOEXCEPT +{ + return m / d; +} + +CONSTCD11 +inline +month_day +operator/(const month& m, int d) NOEXCEPT +{ + return m / day(static_cast(d)); +} + +CONSTCD11 +inline +month_day +operator/(int m, const day& d) NOEXCEPT +{ + return month(static_cast(m)) / d; +} + +CONSTCD11 inline month_day operator/(const day& d, int m) NOEXCEPT {return m / d;} + +// month_day_last from operator/() + +CONSTCD11 +inline +month_day_last +operator/(const month& m, last_spec) NOEXCEPT +{ + return month_day_last{m}; +} + +CONSTCD11 +inline +month_day_last +operator/(last_spec, const month& m) NOEXCEPT +{ + return m/last; +} + +CONSTCD11 +inline +month_day_last +operator/(int m, last_spec) NOEXCEPT +{ + return month(static_cast(m))/last; +} + +CONSTCD11 +inline +month_day_last +operator/(last_spec, int m) NOEXCEPT +{ + return m/last; +} + +// month_weekday from operator/() + +CONSTCD11 +inline +month_weekday +operator/(const month& m, const weekday_indexed& wdi) NOEXCEPT +{ + return {m, wdi}; +} + +CONSTCD11 +inline +month_weekday +operator/(const weekday_indexed& wdi, const month& m) NOEXCEPT +{ + return m / wdi; +} + +CONSTCD11 +inline +month_weekday +operator/(int m, const weekday_indexed& wdi) NOEXCEPT +{ + return month(static_cast(m)) / wdi; +} + +CONSTCD11 +inline +month_weekday +operator/(const weekday_indexed& wdi, int m) NOEXCEPT +{ + return m / wdi; +} + +// month_weekday_last from operator/() + +CONSTCD11 +inline +month_weekday_last +operator/(const month& m, const weekday_last& wdl) NOEXCEPT +{ + return {m, wdl}; +} + +CONSTCD11 +inline +month_weekday_last +operator/(const weekday_last& wdl, const month& m) NOEXCEPT +{ + return m / wdl; +} + +CONSTCD11 +inline +month_weekday_last +operator/(int m, const weekday_last& wdl) NOEXCEPT +{ + return month(static_cast(m)) / wdl; +} + +CONSTCD11 +inline +month_weekday_last +operator/(const weekday_last& wdl, int m) NOEXCEPT +{ + return m / wdl; +} + +// year_month_day from operator/() + +CONSTCD11 +inline +year_month_day +operator/(const year_month& ym, const day& d) NOEXCEPT +{ + return {ym.year(), ym.month(), d}; +} + +CONSTCD11 +inline +year_month_day +operator/(const year_month& ym, int d) NOEXCEPT +{ + return ym / day(static_cast(d)); +} + +CONSTCD11 +inline +year_month_day +operator/(const year& y, const month_day& md) NOEXCEPT +{ + return y / md.month() / md.day(); +} + +CONSTCD11 +inline +year_month_day +operator/(int y, const month_day& md) NOEXCEPT +{ + return year(y) / md; +} + +CONSTCD11 +inline +year_month_day +operator/(const month_day& md, const year& y) NOEXCEPT +{ + return y / md; +} + +CONSTCD11 +inline +year_month_day +operator/(const month_day& md, int y) NOEXCEPT +{ + return year(y) / md; +} + +// year_month_day_last from operator/() + +CONSTCD11 +inline +year_month_day_last +operator/(const year_month& ym, last_spec) NOEXCEPT +{ + return {ym.year(), month_day_last{ym.month()}}; +} + +CONSTCD11 +inline +year_month_day_last +operator/(const year& y, const month_day_last& mdl) NOEXCEPT +{ + return {y, mdl}; +} + +CONSTCD11 +inline +year_month_day_last +operator/(int y, const month_day_last& mdl) NOEXCEPT +{ + return year(y) / mdl; +} + +CONSTCD11 +inline +year_month_day_last +operator/(const month_day_last& mdl, const year& y) NOEXCEPT +{ + return y / mdl; +} + +CONSTCD11 +inline +year_month_day_last +operator/(const month_day_last& mdl, int y) NOEXCEPT +{ + return year(y) / mdl; +} + +// year_month_weekday from operator/() + +CONSTCD11 +inline +year_month_weekday +operator/(const year_month& ym, const weekday_indexed& wdi) NOEXCEPT +{ + return {ym.year(), ym.month(), wdi}; +} + +CONSTCD11 +inline +year_month_weekday +operator/(const year& y, const month_weekday& mwd) NOEXCEPT +{ + return {y, mwd.month(), mwd.weekday_indexed()}; +} + +CONSTCD11 +inline +year_month_weekday +operator/(int y, const month_weekday& mwd) NOEXCEPT +{ + return year(y) / mwd; +} + +CONSTCD11 +inline +year_month_weekday +operator/(const month_weekday& mwd, const year& y) NOEXCEPT +{ + return y / mwd; +} + +CONSTCD11 +inline +year_month_weekday +operator/(const month_weekday& mwd, int y) NOEXCEPT +{ + return year(y) / mwd; +} + +// year_month_weekday_last from operator/() + +CONSTCD11 +inline +year_month_weekday_last +operator/(const year_month& ym, const weekday_last& wdl) NOEXCEPT +{ + return {ym.year(), ym.month(), wdl}; +} + +CONSTCD11 +inline +year_month_weekday_last +operator/(const year& y, const month_weekday_last& mwdl) NOEXCEPT +{ + return {y, mwdl.month(), mwdl.weekday_last()}; +} + +CONSTCD11 +inline +year_month_weekday_last +operator/(int y, const month_weekday_last& mwdl) NOEXCEPT +{ + return year(y) / mwdl; +} + +CONSTCD11 +inline +year_month_weekday_last +operator/(const month_weekday_last& mwdl, const year& y) NOEXCEPT +{ + return y / mwdl; +} + +CONSTCD11 +inline +year_month_weekday_last +operator/(const month_weekday_last& mwdl, int y) NOEXCEPT +{ + return year(y) / mwdl; +} + +} // namespace solar_hijri + +#endif // SOLAR_HIJRI_H diff --git a/third_party/date/include/date/tz.h b/third_party/date/include/date/tz.h new file mode 100644 index 0000000..4921068 --- /dev/null +++ b/third_party/date/include/date/tz.h @@ -0,0 +1,2792 @@ +#ifndef TZ_H +#define TZ_H + +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016, 2017 Howard Hinnant +// Copyright (c) 2017 Jiangang Zhuang +// Copyright (c) 2017 Aaron Bishop +// Copyright (c) 2017 Tomasz KamiÅ„ski +// +// 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. +// +// Our apologies. When the previous paragraph was written, lowercase had not yet +// been invented (that would involve another several millennia of evolution). +// We did not mean to shout. + +// Get more recent database at http://www.iana.org/time-zones + +// The notion of "current timezone" is something the operating system is expected to "just +// know". How it knows this is system specific. It's often a value set by the user at OS +// installation time and recorded by the OS somewhere. On Linux and Mac systems the current +// timezone name is obtained by looking at the name or contents of a particular file on +// disk. On Windows the current timezone name comes from the registry. In either method, +// there is no guarantee that the "native" current timezone name obtained will match any +// of the "Standard" names in this library's "database". On Linux, the names usually do +// seem to match so mapping functions to map from native to "Standard" are typically not +// required. On Windows, the names are never "Standard" so mapping is always required. +// Technically any OS may use the mapping process but currently only Windows does use it. + +#ifndef USE_OS_TZDB +# define USE_OS_TZDB 0 +#endif + +#ifndef HAS_REMOTE_API +# if USE_OS_TZDB == 0 +# ifdef _WIN32 +# define HAS_REMOTE_API 0 +# else +# define HAS_REMOTE_API 1 +# endif +# else // HAS_REMOTE_API makes no since when using the OS timezone database +# define HAS_REMOTE_API 0 +# endif +#endif + +#ifdef __clang__ +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wconstant-logical-operand" +#endif + +static_assert(!(USE_OS_TZDB && HAS_REMOTE_API), + "USE_OS_TZDB and HAS_REMOTE_API can not be used together"); + +#ifdef __clang__ +# pragma clang diagnostic pop +#endif + +#ifndef AUTO_DOWNLOAD +# define AUTO_DOWNLOAD HAS_REMOTE_API +#endif + +static_assert(HAS_REMOTE_API == 0 ? AUTO_DOWNLOAD == 0 : true, + "AUTO_DOWNLOAD can not be turned on without HAS_REMOTE_API"); + +#ifndef USE_SHELL_API +# define USE_SHELL_API 1 +#endif + +#if USE_OS_TZDB +# ifdef _WIN32 +# error "USE_OS_TZDB can not be used on Windows" +# endif +#endif + +#ifndef HAS_DEDUCTION_GUIDES +# if __cplusplus >= 201703 +# define HAS_DEDUCTION_GUIDES 1 +# else +# define HAS_DEDUCTION_GUIDES 0 +# endif +#endif // HAS_DEDUCTION_GUIDES + +#include "date.h" + +#if defined(_MSC_VER) && (_MSC_VER < 1900) +#include "tz_private.h" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +# ifdef DATE_BUILD_DLL +# define DATE_API __declspec(dllexport) +# elif defined(DATE_USE_DLL) +# define DATE_API __declspec(dllimport) +# else +# define DATE_API +# endif +#else +# ifdef DATE_BUILD_DLL +# define DATE_API __attribute__ ((visibility ("default"))) +# else +# define DATE_API +# endif +#endif + +namespace date +{ + +enum class choose {earliest, latest}; + +namespace detail +{ + struct undocumented; + + template + struct nodeduct + { + using type = T; + }; + + template + using nodeduct_t = typename nodeduct::type; +} + +struct sys_info +{ + sys_seconds begin; + sys_seconds end; + std::chrono::seconds offset; + std::chrono::minutes save; + std::string abbrev; +}; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const sys_info& r) +{ + os << r.begin << '\n'; + os << r.end << '\n'; + os << make_time(r.offset) << "\n"; + os << make_time(r.save) << "\n"; + os << r.abbrev << '\n'; + return os; +} + +struct local_info +{ + enum {unique, nonexistent, ambiguous} result; + sys_info first; + sys_info second; +}; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const local_info& r) +{ + if (r.result == local_info::nonexistent) + os << "nonexistent between\n"; + else if (r.result == local_info::ambiguous) + os << "ambiguous between\n"; + os << r.first; + if (r.result != local_info::unique) + { + os << "and\n"; + os << r.second; + } + return os; +} + +class nonexistent_local_time + : public std::runtime_error +{ +public: + template + nonexistent_local_time(local_time tp, const local_info& i); + +private: + template + static + std::string + make_msg(local_time tp, const local_info& i); +}; + +template +inline +nonexistent_local_time::nonexistent_local_time(local_time tp, + const local_info& i) + : std::runtime_error(make_msg(tp, i)) +{ +} + +template +std::string +nonexistent_local_time::make_msg(local_time tp, const local_info& i) +{ + assert(i.result == local_info::nonexistent); + std::ostringstream os; + os << tp << " is in a gap between\n" + << local_seconds{i.first.end.time_since_epoch()} + i.first.offset << ' ' + << i.first.abbrev << " and\n" + << local_seconds{i.second.begin.time_since_epoch()} + i.second.offset << ' ' + << i.second.abbrev + << " which are both equivalent to\n" + << i.first.end << " UTC"; + return os.str(); +} + +class ambiguous_local_time + : public std::runtime_error +{ +public: + template + ambiguous_local_time(local_time tp, const local_info& i); + +private: + template + static + std::string + make_msg(local_time tp, const local_info& i); +}; + +template +inline +ambiguous_local_time::ambiguous_local_time(local_time tp, const local_info& i) + : std::runtime_error(make_msg(tp, i)) +{ +} + +template +std::string +ambiguous_local_time::make_msg(local_time tp, const local_info& i) +{ + assert(i.result == local_info::ambiguous); + std::ostringstream os; + os << tp << " is ambiguous. It could be\n" + << tp << ' ' << i.first.abbrev << " == " + << tp - i.first.offset << " UTC or\n" + << tp << ' ' << i.second.abbrev << " == " + << tp - i.second.offset << " UTC"; + return os.str(); +} + +class time_zone; + +#if HAS_STRING_VIEW +DATE_API const time_zone* locate_zone(std::string_view tz_name); +#else +DATE_API const time_zone* locate_zone(const std::string& tz_name); +#endif + +DATE_API const time_zone* current_zone(); + +template +struct zoned_traits +{ +}; + +template <> +struct zoned_traits +{ + static + const time_zone* + default_zone() + { + return date::locate_zone("Etc/UTC"); + } + +#if HAS_STRING_VIEW + + static + const time_zone* + locate_zone(std::string_view name) + { + return date::locate_zone(name); + } + +#else // !HAS_STRING_VIEW + + static + const time_zone* + locate_zone(const std::string& name) + { + return date::locate_zone(name); + } + + static + const time_zone* + locate_zone(const char* name) + { + return date::locate_zone(name); + } + +#endif // !HAS_STRING_VIEW +}; + +template +class zoned_time; + +template +bool +operator==(const zoned_time& x, + const zoned_time& y); + +template +class zoned_time +{ +public: + using duration = typename std::common_type::type; + +private: + TimeZonePtr zone_; + sys_time tp_; + +public: +#if !defined(_MSC_VER) || (_MSC_VER > 1916) + template ::default_zone())> +#endif + zoned_time(); + +#if !defined(_MSC_VER) || (_MSC_VER > 1916) + template ::default_zone())> +#endif + zoned_time(const sys_time& st); + explicit zoned_time(TimeZonePtr z); + +#if HAS_STRING_VIEW + template ::locate_zone(std::string_view())) + >::value + >::type> + explicit zoned_time(std::string_view name); +#else +# if !defined(_MSC_VER) || (_MSC_VER > 1916) + template ::locate_zone(std::string())) + >::value + >::type> +# endif + explicit zoned_time(const std::string& name); +#endif + + template , + sys_time>::value + >::type> + zoned_time(const zoned_time& zt) NOEXCEPT; + + zoned_time(TimeZonePtr z, const sys_time& st); + +#if !defined(_MSC_VER) || (_MSC_VER > 1916) + template ()->to_sys(local_time{})), + sys_time + >::value + >::type> +#endif + zoned_time(TimeZonePtr z, const local_time& tp); + +#if !defined(_MSC_VER) || (_MSC_VER > 1916) + template ()->to_sys(local_time{}, + choose::earliest)), + sys_time + >::value + >::type> +#endif + zoned_time(TimeZonePtr z, const local_time& tp, choose c); + + template , + sys_time>::value + >::type> + zoned_time(TimeZonePtr z, const zoned_time& zt); + + template , + sys_time>::value + >::type> + zoned_time(TimeZonePtr z, const zoned_time& zt, choose); + +#if HAS_STRING_VIEW + + template ::locate_zone(std::string_view())), + sys_time + >::value + >::type> + zoned_time(std::string_view name, detail::nodeduct_t&> st); + + template ::locate_zone(std::string_view())), + local_time + >::value + >::type> + zoned_time(std::string_view name, detail::nodeduct_t&> tp); + + template ::locate_zone(std::string_view())), + local_time, + choose + >::value + >::type> + zoned_time(std::string_view name, detail::nodeduct_t&> tp, choose c); + + template , + sys_time>::value && + std::is_constructible + < + zoned_time, + decltype(zoned_traits::locate_zone(std::string_view())), + zoned_time + >::value + >::type> + zoned_time(std::string_view name, const zoned_time& zt); + + template , + sys_time>::value && + std::is_constructible + < + zoned_time, + decltype(zoned_traits::locate_zone(std::string_view())), + zoned_time, + choose + >::value + >::type> + zoned_time(std::string_view name, const zoned_time& zt, choose); + +#else // !HAS_STRING_VIEW + +#if !defined(_MSC_VER) || (_MSC_VER > 1916) + template ::locate_zone(std::string())), + sys_time + >::value + >::type> +#endif + zoned_time(const std::string& name, const sys_time& st); + +#if !defined(_MSC_VER) || (_MSC_VER > 1916) + template ::locate_zone(std::string())), + sys_time + >::value + >::type> +#endif + zoned_time(const char* name, const sys_time& st); + +#if !defined(_MSC_VER) || (_MSC_VER > 1916) + template ::locate_zone(std::string())), + local_time + >::value + >::type> +#endif + zoned_time(const std::string& name, const local_time& tp); + +#if !defined(_MSC_VER) || (_MSC_VER > 1916) + template ::locate_zone(std::string())), + local_time + >::value + >::type> +#endif + zoned_time(const char* name, const local_time& tp); + +#if !defined(_MSC_VER) || (_MSC_VER > 1916) + template ::locate_zone(std::string())), + local_time, + choose + >::value + >::type> +#endif + zoned_time(const std::string& name, const local_time& tp, choose c); + +#if !defined(_MSC_VER) || (_MSC_VER > 1916) + template ::locate_zone(std::string())), + local_time, + choose + >::value + >::type> +#endif + zoned_time(const char* name, const local_time& tp, choose c); + +#if !defined(_MSC_VER) || (_MSC_VER > 1916) + template , + sys_time>::value && + std::is_constructible + < + zoned_time, + decltype(zoned_traits::locate_zone(std::string())), + zoned_time + >::value + >::type> +#else + template +#endif + zoned_time(const std::string& name, const zoned_time& zt); + +#if !defined(_MSC_VER) || (_MSC_VER > 1916) + template , + sys_time>::value && + std::is_constructible + < + zoned_time, + decltype(zoned_traits::locate_zone(std::string())), + zoned_time + >::value + >::type> +#else + template +#endif + zoned_time(const char* name, const zoned_time& zt); + +#if !defined(_MSC_VER) || (_MSC_VER > 1916) + template , + sys_time>::value && + std::is_constructible + < + zoned_time, + decltype(zoned_traits::locate_zone(std::string())), + zoned_time, + choose + >::value + >::type> +#else + template +#endif + zoned_time(const std::string& name, const zoned_time& zt, + choose); + +#if !defined(_MSC_VER) || (_MSC_VER > 1916) + template , + sys_time>::value && + std::is_constructible + < + zoned_time, + decltype(zoned_traits::locate_zone(std::string())), + zoned_time, + choose + >::value + >::type> +#else + template +#endif + zoned_time(const char* name, const zoned_time& zt, + choose); + +#endif // !HAS_STRING_VIEW + + zoned_time& operator=(const sys_time& st); + zoned_time& operator=(const local_time& ut); + + explicit operator sys_time() const; + explicit operator local_time() const; + + TimeZonePtr get_time_zone() const; + local_time get_local_time() const; + sys_time get_sys_time() const; + sys_info get_info() const; + + template + friend + bool + operator==(const zoned_time& x, + const zoned_time& y); + + template + friend + std::basic_ostream& + operator<<(std::basic_ostream& os, + const zoned_time& t); + +private: + template friend class zoned_time; + + template + static + TimeZonePtr2&& + check(TimeZonePtr2&& p); +}; + +using zoned_seconds = zoned_time; + +#if HAS_DEDUCTION_GUIDES + +namespace detail +{ + template + using time_zone_representation = + std::conditional_t + < + std::is_convertible::value, + time_zone const*, + std::remove_cv_t> + >; +} + +zoned_time() + -> zoned_time; + +template +zoned_time(sys_time) + -> zoned_time>; + +template +zoned_time(TimeZonePtrOrName&&) + -> zoned_time>; + +template +zoned_time(TimeZonePtrOrName&&, sys_time) + -> zoned_time, detail::time_zone_representation>; + +template +zoned_time(TimeZonePtrOrName&&, local_time, choose = choose::earliest) + -> zoned_time, detail::time_zone_representation>; + +template +zoned_time(TimeZonePtrOrName&&, zoned_time, choose = choose::earliest) + -> zoned_time, detail::time_zone_representation>; + +#endif // HAS_DEDUCTION_GUIDES + +template +inline +bool +operator==(const zoned_time& x, + const zoned_time& y) +{ + return x.zone_ == y.zone_ && x.tp_ == y.tp_; +} + +template +inline +bool +operator!=(const zoned_time& x, + const zoned_time& y) +{ + return !(x == y); +} + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) + +namespace detail +{ +# if USE_OS_TZDB + struct transition; + struct expanded_ttinfo; +# else // !USE_OS_TZDB + struct zonelet; + class Rule; +# endif // !USE_OS_TZDB +} + +#endif // !defined(_MSC_VER) || (_MSC_VER >= 1900) + +class time_zone +{ +private: + std::string name_; +#if USE_OS_TZDB + std::vector transitions_; + std::vector ttinfos_; +#else // !USE_OS_TZDB + std::vector zonelets_; +#endif // !USE_OS_TZDB + std::unique_ptr adjusted_; + +public: +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) + time_zone(time_zone&&) = default; + time_zone& operator=(time_zone&&) = default; +#else // defined(_MSC_VER) && (_MSC_VER < 1900) + time_zone(time_zone&& src); + time_zone& operator=(time_zone&& src); +#endif // defined(_MSC_VER) && (_MSC_VER < 1900) + + DATE_API explicit time_zone(const std::string& s, detail::undocumented); + + const std::string& name() const NOEXCEPT; + + template sys_info get_info(sys_time st) const; + template local_info get_info(local_time tp) const; + + template + sys_time::type> + to_sys(local_time tp) const; + + template + sys_time::type> + to_sys(local_time tp, choose z) const; + + template + local_time::type> + to_local(sys_time tp) const; + + friend bool operator==(const time_zone& x, const time_zone& y) NOEXCEPT; + friend bool operator< (const time_zone& x, const time_zone& y) NOEXCEPT; + friend DATE_API std::ostream& operator<<(std::ostream& os, const time_zone& z); + +#if !USE_OS_TZDB + DATE_API void add(const std::string& s); +#endif // !USE_OS_TZDB + +private: + DATE_API sys_info get_info_impl(sys_seconds tp) const; + DATE_API local_info get_info_impl(local_seconds tp) const; + + template + sys_time::type> + to_sys_impl(local_time tp, choose z, std::false_type) const; + template + sys_time::type> + to_sys_impl(local_time tp, choose, std::true_type) const; + +#if USE_OS_TZDB + DATE_API void init() const; + DATE_API void init_impl(); + DATE_API sys_info + load_sys_info(std::vector::const_iterator i) const; + + template + DATE_API void + load_data(std::istream& inf, std::int32_t tzh_leapcnt, std::int32_t tzh_timecnt, + std::int32_t tzh_typecnt, std::int32_t tzh_charcnt); +#else // !USE_OS_TZDB + DATE_API sys_info get_info_impl(sys_seconds tp, int timezone) const; + DATE_API void adjust_infos(const std::vector& rules); + DATE_API void parse_info(std::istream& in); +#endif // !USE_OS_TZDB +}; + +#if defined(_MSC_VER) && (_MSC_VER < 1900) + +inline +time_zone::time_zone(time_zone&& src) + : name_(std::move(src.name_)) + , zonelets_(std::move(src.zonelets_)) + , adjusted_(std::move(src.adjusted_)) + {} + +inline +time_zone& +time_zone::operator=(time_zone&& src) +{ + name_ = std::move(src.name_); + zonelets_ = std::move(src.zonelets_); + adjusted_ = std::move(src.adjusted_); + return *this; +} + +#endif // defined(_MSC_VER) && (_MSC_VER < 1900) + +inline +const std::string& +time_zone::name() const NOEXCEPT +{ + return name_; +} + +template +inline +sys_info +time_zone::get_info(sys_time st) const +{ + return get_info_impl(date::floor(st)); +} + +template +inline +local_info +time_zone::get_info(local_time tp) const +{ + return get_info_impl(date::floor(tp)); +} + +template +inline +sys_time::type> +time_zone::to_sys(local_time tp) const +{ + return to_sys_impl(tp, choose{}, std::true_type{}); +} + +template +inline +sys_time::type> +time_zone::to_sys(local_time tp, choose z) const +{ + return to_sys_impl(tp, z, std::false_type{}); +} + +template +inline +local_time::type> +time_zone::to_local(sys_time tp) const +{ + using LT = local_time::type>; + auto i = get_info(tp); + return LT{(tp + i.offset).time_since_epoch()}; +} + +inline bool operator==(const time_zone& x, const time_zone& y) NOEXCEPT {return x.name_ == y.name_;} +inline bool operator< (const time_zone& x, const time_zone& y) NOEXCEPT {return x.name_ < y.name_;} + +inline bool operator!=(const time_zone& x, const time_zone& y) NOEXCEPT {return !(x == y);} +inline bool operator> (const time_zone& x, const time_zone& y) NOEXCEPT {return y < x;} +inline bool operator<=(const time_zone& x, const time_zone& y) NOEXCEPT {return !(y < x);} +inline bool operator>=(const time_zone& x, const time_zone& y) NOEXCEPT {return !(x < y);} + +template +sys_time::type> +time_zone::to_sys_impl(local_time tp, choose z, std::false_type) const +{ + auto i = get_info(tp); + if (i.result == local_info::nonexistent) + { + return i.first.end; + } + else if (i.result == local_info::ambiguous) + { + if (z == choose::latest) + return sys_time{tp.time_since_epoch()} - i.second.offset; + } + return sys_time{tp.time_since_epoch()} - i.first.offset; +} + +template +sys_time::type> +time_zone::to_sys_impl(local_time tp, choose, std::true_type) const +{ + auto i = get_info(tp); + if (i.result == local_info::nonexistent) + throw nonexistent_local_time(tp, i); + else if (i.result == local_info::ambiguous) + throw ambiguous_local_time(tp, i); + return sys_time{tp.time_since_epoch()} - i.first.offset; +} + +#if !USE_OS_TZDB + +class time_zone_link +{ +private: + std::string name_; + std::string target_; +public: + DATE_API explicit time_zone_link(const std::string& s); + + const std::string& name() const {return name_;} + const std::string& target() const {return target_;} + + friend bool operator==(const time_zone_link& x, const time_zone_link& y) {return x.name_ == y.name_;} + friend bool operator< (const time_zone_link& x, const time_zone_link& y) {return x.name_ < y.name_;} + + friend DATE_API std::ostream& operator<<(std::ostream& os, const time_zone_link& x); +}; + +using link = time_zone_link; + +inline bool operator!=(const time_zone_link& x, const time_zone_link& y) {return !(x == y);} +inline bool operator> (const time_zone_link& x, const time_zone_link& y) {return y < x;} +inline bool operator<=(const time_zone_link& x, const time_zone_link& y) {return !(y < x);} +inline bool operator>=(const time_zone_link& x, const time_zone_link& y) {return !(x < y);} + +#endif // !USE_OS_TZDB + +class leap_second +{ +private: + sys_seconds date_; + +public: +#if USE_OS_TZDB + DATE_API explicit leap_second(const sys_seconds& s, detail::undocumented); +#else + DATE_API explicit leap_second(const std::string& s, detail::undocumented); +#endif + + sys_seconds date() const {return date_;} + + friend bool operator==(const leap_second& x, const leap_second& y) {return x.date_ == y.date_;} + friend bool operator< (const leap_second& x, const leap_second& y) {return x.date_ < y.date_;} + + template + friend + bool + operator==(const leap_second& x, const sys_time& y) + { + return x.date_ == y; + } + + template + friend + bool + operator< (const leap_second& x, const sys_time& y) + { + return x.date_ < y; + } + + template + friend + bool + operator< (const sys_time& x, const leap_second& y) + { + return x < y.date_; + } + + friend DATE_API std::ostream& operator<<(std::ostream& os, const leap_second& x); +}; + +inline bool operator!=(const leap_second& x, const leap_second& y) {return !(x == y);} +inline bool operator> (const leap_second& x, const leap_second& y) {return y < x;} +inline bool operator<=(const leap_second& x, const leap_second& y) {return !(y < x);} +inline bool operator>=(const leap_second& x, const leap_second& y) {return !(x < y);} + +template +inline +bool +operator==(const sys_time& x, const leap_second& y) +{ + return y == x; +} + +template +inline +bool +operator!=(const leap_second& x, const sys_time& y) +{ + return !(x == y); +} + +template +inline +bool +operator!=(const sys_time& x, const leap_second& y) +{ + return !(x == y); +} + +template +inline +bool +operator> (const leap_second& x, const sys_time& y) +{ + return y < x; +} + +template +inline +bool +operator> (const sys_time& x, const leap_second& y) +{ + return y < x; +} + +template +inline +bool +operator<=(const leap_second& x, const sys_time& y) +{ + return !(y < x); +} + +template +inline +bool +operator<=(const sys_time& x, const leap_second& y) +{ + return !(y < x); +} + +template +inline +bool +operator>=(const leap_second& x, const sys_time& y) +{ + return !(x < y); +} + +template +inline +bool +operator>=(const sys_time& x, const leap_second& y) +{ + return !(x < y); +} + +using leap = leap_second; + +#ifdef _WIN32 + +namespace detail +{ + +// The time zone mapping is modelled after this data file: +// http://unicode.org/repos/cldr/trunk/common/supplemental/windowsZones.xml +// and the field names match the element names from the mapZone element +// of windowsZones.xml. +// The website displays this file here: +// http://www.unicode.org/cldr/charts/latest/supplemental/zone_tzid.html +// The html view is sorted before being displayed but is otherwise the same +// There is a mapping between the os centric view (in this case windows) +// the html displays uses and the generic view the xml file. +// That mapping is this: +// display column "windows" -> xml field "other". +// display column "region" -> xml field "territory". +// display column "tzid" -> xml field "type". +// This structure uses the generic terminology because it could be +// used to to support other os/native name conversions, not just windows, +// and using the same generic names helps retain the connection to the +// origin of the data that we are using. +struct timezone_mapping +{ + timezone_mapping(const char* other, const char* territory, const char* type) + : other(other), territory(territory), type(type) + { + } + timezone_mapping() = default; + std::string other; + std::string territory; + std::string type; +}; + +} // detail + +#endif // _WIN32 + +struct tzdb +{ + std::string version = "unknown"; + std::vector zones; +#if !USE_OS_TZDB + std::vector links; +#endif + std::vector leap_seconds; +#if !USE_OS_TZDB + std::vector rules; +#endif +#ifdef _WIN32 + std::vector mappings; +#endif + tzdb* next = nullptr; + + tzdb() = default; +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) + tzdb(tzdb&&) = default; + tzdb& operator=(tzdb&&) = default; +#else // defined(_MSC_VER) && (_MSC_VER < 1900) + tzdb(tzdb&& src) + : version(std::move(src.version)) + , zones(std::move(src.zones)) + , links(std::move(src.links)) + , leap_seconds(std::move(src.leap_seconds)) + , rules(std::move(src.rules)) + , mappings(std::move(src.mappings)) + {} + + tzdb& operator=(tzdb&& src) + { + version = std::move(src.version); + zones = std::move(src.zones); + links = std::move(src.links); + leap_seconds = std::move(src.leap_seconds); + rules = std::move(src.rules); + mappings = std::move(src.mappings); + return *this; + } +#endif // defined(_MSC_VER) && (_MSC_VER < 1900) + +#if HAS_STRING_VIEW + const time_zone* locate_zone(std::string_view tz_name) const; +#else + const time_zone* locate_zone(const std::string& tz_name) const; +#endif + const time_zone* current_zone() const; +}; + +using TZ_DB = tzdb; + +DATE_API std::ostream& +operator<<(std::ostream& os, const tzdb& db); + +DATE_API const tzdb& get_tzdb(); + +class tzdb_list +{ + std::atomic head_{nullptr}; + +public: + ~tzdb_list(); + tzdb_list() = default; + tzdb_list(tzdb_list&& x) NOEXCEPT; + + const tzdb& front() const NOEXCEPT {return *head_;} + tzdb& front() NOEXCEPT {return *head_;} + + class const_iterator; + + const_iterator begin() const NOEXCEPT; + const_iterator end() const NOEXCEPT; + + const_iterator cbegin() const NOEXCEPT; + const_iterator cend() const NOEXCEPT; + + const_iterator erase_after(const_iterator p) NOEXCEPT; + + struct undocumented_helper; +private: + void push_front(tzdb* tzdb) NOEXCEPT; +}; + +class tzdb_list::const_iterator +{ + tzdb* p_ = nullptr; + + explicit const_iterator(tzdb* p) NOEXCEPT : p_{p} {} +public: + const_iterator() = default; + + using iterator_category = std::forward_iterator_tag; + using value_type = tzdb; + using reference = const value_type&; + using pointer = const value_type*; + using difference_type = std::ptrdiff_t; + + reference operator*() const NOEXCEPT {return *p_;} + pointer operator->() const NOEXCEPT {return p_;} + + const_iterator& operator++() NOEXCEPT {p_ = p_->next; return *this;} + const_iterator operator++(int) NOEXCEPT {auto t = *this; ++(*this); return t;} + + friend + bool + operator==(const const_iterator& x, const const_iterator& y) NOEXCEPT + {return x.p_ == y.p_;} + + friend + bool + operator!=(const const_iterator& x, const const_iterator& y) NOEXCEPT + {return !(x == y);} + + friend class tzdb_list; +}; + +inline +tzdb_list::const_iterator +tzdb_list::begin() const NOEXCEPT +{ + return const_iterator{head_}; +} + +inline +tzdb_list::const_iterator +tzdb_list::end() const NOEXCEPT +{ + return const_iterator{nullptr}; +} + +inline +tzdb_list::const_iterator +tzdb_list::cbegin() const NOEXCEPT +{ + return begin(); +} + +inline +tzdb_list::const_iterator +tzdb_list::cend() const NOEXCEPT +{ + return end(); +} + +DATE_API tzdb_list& get_tzdb_list(); + +#if !USE_OS_TZDB + +DATE_API const tzdb& reload_tzdb(); +DATE_API void set_install(const std::string& install); + +#endif // !USE_OS_TZDB + +#if HAS_REMOTE_API + +DATE_API std::string remote_version(); +// if provided error_buffer size should be at least CURL_ERROR_SIZE +DATE_API bool remote_download(const std::string& version, char* error_buffer = nullptr); +DATE_API bool remote_install(const std::string& version); + +#endif + +// zoned_time + +namespace detail +{ + +template +inline +T* +to_raw_pointer(T* p) NOEXCEPT +{ + return p; +} + +template +inline +auto +to_raw_pointer(Pointer p) NOEXCEPT + -> decltype(detail::to_raw_pointer(p.operator->())) +{ + return detail::to_raw_pointer(p.operator->()); +} + +} // namespace detail + +template +template +inline +TimeZonePtr2&& +zoned_time::check(TimeZonePtr2&& p) +{ + if (detail::to_raw_pointer(p) == nullptr) + throw std::runtime_error( + "zoned_time constructed with a time zone pointer == nullptr"); + return std::forward(p); +} + +template +#if !defined(_MSC_VER) || (_MSC_VER > 1916) +template +#endif +inline +zoned_time::zoned_time() + : zone_(check(zoned_traits::default_zone())) + {} + +template +#if !defined(_MSC_VER) || (_MSC_VER > 1916) +template +#endif +inline +zoned_time::zoned_time(const sys_time& st) + : zone_(check(zoned_traits::default_zone())) + , tp_(st) + {} + +template +inline +zoned_time::zoned_time(TimeZonePtr z) + : zone_(check(std::move(z))) + {} + +#if HAS_STRING_VIEW + +template +template +inline +zoned_time::zoned_time(std::string_view name) + : zoned_time(zoned_traits::locate_zone(name)) + {} + +#else // !HAS_STRING_VIEW + +template +#if !defined(_MSC_VER) || (_MSC_VER > 1916) +template +#endif +inline +zoned_time::zoned_time(const std::string& name) + : zoned_time(zoned_traits::locate_zone(name)) + {} + +#endif // !HAS_STRING_VIEW + +template +template +inline +zoned_time::zoned_time(const zoned_time& zt) NOEXCEPT + : zone_(zt.zone_) + , tp_(zt.tp_) + {} + +template +inline +zoned_time::zoned_time(TimeZonePtr z, const sys_time& st) + : zone_(check(std::move(z))) + , tp_(st) + {} + +template +#if !defined(_MSC_VER) || (_MSC_VER > 1916) +template +#endif +inline +zoned_time::zoned_time(TimeZonePtr z, const local_time& t) + : zone_(check(std::move(z))) + , tp_(zone_->to_sys(t)) + {} + +template +#if !defined(_MSC_VER) || (_MSC_VER > 1916) +template +#endif +inline +zoned_time::zoned_time(TimeZonePtr z, const local_time& t, + choose c) + : zone_(check(std::move(z))) + , tp_(zone_->to_sys(t, c)) + {} + +template +template +inline +zoned_time::zoned_time(TimeZonePtr z, + const zoned_time& zt) + : zone_(check(std::move(z))) + , tp_(zt.tp_) + {} + +template +template +inline +zoned_time::zoned_time(TimeZonePtr z, + const zoned_time& zt, choose) + : zoned_time(std::move(z), zt) + {} + +#if HAS_STRING_VIEW + +template +template +inline +zoned_time::zoned_time(std::string_view name, + detail::nodeduct_t&> st) + : zoned_time(zoned_traits::locate_zone(name), st) + {} + +template +template +inline +zoned_time::zoned_time(std::string_view name, + detail::nodeduct_t&> t) + : zoned_time(zoned_traits::locate_zone(name), t) + {} + +template +template +inline +zoned_time::zoned_time(std::string_view name, + detail::nodeduct_t&> t, choose c) + : zoned_time(zoned_traits::locate_zone(name), t, c) + {} + +template +template +inline +zoned_time::zoned_time(std::string_view name, + const zoned_time& zt) + : zoned_time(zoned_traits::locate_zone(name), zt) + {} + +template +template +inline +zoned_time::zoned_time(std::string_view name, + const zoned_time& zt, + choose c) + : zoned_time(zoned_traits::locate_zone(name), zt, c) + {} + +#else // !HAS_STRING_VIEW + +template +#if !defined(_MSC_VER) || (_MSC_VER > 1916) +template +#endif +inline +zoned_time::zoned_time(const std::string& name, + const sys_time& st) + : zoned_time(zoned_traits::locate_zone(name), st) + {} + +template +#if !defined(_MSC_VER) || (_MSC_VER > 1916) +template +#endif +inline +zoned_time::zoned_time(const char* name, + const sys_time& st) + : zoned_time(zoned_traits::locate_zone(name), st) + {} + +template +#if !defined(_MSC_VER) || (_MSC_VER > 1916) +template +#endif +inline +zoned_time::zoned_time(const std::string& name, + const local_time& t) + : zoned_time(zoned_traits::locate_zone(name), t) + {} + +template +#if !defined(_MSC_VER) || (_MSC_VER > 1916) +template +#endif +inline +zoned_time::zoned_time(const char* name, + const local_time& t) + : zoned_time(zoned_traits::locate_zone(name), t) + {} + +template +#if !defined(_MSC_VER) || (_MSC_VER > 1916) +template +#endif +inline +zoned_time::zoned_time(const std::string& name, + const local_time& t, choose c) + : zoned_time(zoned_traits::locate_zone(name), t, c) + {} + +template +#if !defined(_MSC_VER) || (_MSC_VER > 1916) +template +#endif +inline +zoned_time::zoned_time(const char* name, + const local_time& t, choose c) + : zoned_time(zoned_traits::locate_zone(name), t, c) + {} + +template +#if !defined(_MSC_VER) || (_MSC_VER > 1916) +template +#else +template +#endif +inline +zoned_time::zoned_time(const std::string& name, + const zoned_time& zt) + : zoned_time(zoned_traits::locate_zone(name), zt) + {} + +template +#if !defined(_MSC_VER) || (_MSC_VER > 1916) +template +#else +template +#endif +inline +zoned_time::zoned_time(const char* name, + const zoned_time& zt) + : zoned_time(zoned_traits::locate_zone(name), zt) + {} + +template +#if !defined(_MSC_VER) || (_MSC_VER > 1916) +template +#else +template +#endif +inline +zoned_time::zoned_time(const std::string& name, + const zoned_time& zt, + choose c) + : zoned_time(zoned_traits::locate_zone(name), zt, c) + {} + +template +#if !defined(_MSC_VER) || (_MSC_VER > 1916) +template +#else +template +#endif +inline +zoned_time::zoned_time(const char* name, + const zoned_time& zt, + choose c) + : zoned_time(zoned_traits::locate_zone(name), zt, c) + {} + +#endif // HAS_STRING_VIEW + +template +inline +zoned_time& +zoned_time::operator=(const sys_time& st) +{ + tp_ = st; + return *this; +} + +template +inline +zoned_time& +zoned_time::operator=(const local_time& ut) +{ + tp_ = zone_->to_sys(ut); + return *this; +} + +template +inline +zoned_time::operator local_time::duration>() const +{ + return get_local_time(); +} + +template +inline +zoned_time::operator sys_time::duration>() const +{ + return get_sys_time(); +} + +template +inline +TimeZonePtr +zoned_time::get_time_zone() const +{ + return zone_; +} + +template +inline +local_time::duration> +zoned_time::get_local_time() const +{ + return zone_->to_local(tp_); +} + +template +inline +sys_time::duration> +zoned_time::get_sys_time() const +{ + return tp_; +} + +template +inline +sys_info +zoned_time::get_info() const +{ + return zone_->get_info(tp_); +} + +// make_zoned_time + +inline +zoned_time +make_zoned() +{ + return zoned_time(); +} + +template +inline +zoned_time::type> +make_zoned(const sys_time& tp) +{ + return zoned_time::type>(tp); +} + +template 1916) +#if !defined(__INTEL_COMPILER) || (__INTEL_COMPILER > 1600) + , class = typename std::enable_if + < + std::is_class + < + typename std::decay + < + decltype(*detail::to_raw_pointer(std::declval())) + >::type + >{} + >::type +#endif +#endif + > +inline +zoned_time +make_zoned(TimeZonePtr z) +{ + return zoned_time(std::move(z)); +} + +inline +zoned_seconds +make_zoned(const std::string& name) +{ + return zoned_seconds(name); +} + +template 1916) +#if !defined(__INTEL_COMPILER) || (__INTEL_COMPILER > 1600) + , class = typename std::enable_if + < + std::is_class())>::type>{} + >::type +#endif +#endif + > +inline +zoned_time::type, TimeZonePtr> +make_zoned(TimeZonePtr zone, const local_time& tp) +{ + return zoned_time::type, + TimeZonePtr>(std::move(zone), tp); +} + +template 1916) +#if !defined(__INTEL_COMPILER) || (__INTEL_COMPILER > 1600) + , class = typename std::enable_if + < + std::is_class())>::type>{} + >::type +#endif +#endif + > +inline +zoned_time::type, TimeZonePtr> +make_zoned(TimeZonePtr zone, const local_time& tp, choose c) +{ + return zoned_time::type, + TimeZonePtr>(std::move(zone), tp, c); +} + +template +inline +zoned_time::type> +make_zoned(const std::string& name, const local_time& tp) +{ + return zoned_time::type>(name, tp); +} + +template +inline +zoned_time::type> +make_zoned(const std::string& name, const local_time& tp, choose c) +{ + return zoned_time::type>(name, tp, c); +} + +template +inline +zoned_time +make_zoned(TimeZonePtr zone, const zoned_time& zt) +{ + return zoned_time(std::move(zone), zt); +} + +template +inline +zoned_time +make_zoned(const std::string& name, const zoned_time& zt) +{ + return zoned_time(name, zt); +} + +template +inline +zoned_time +make_zoned(TimeZonePtr zone, const zoned_time& zt, choose c) +{ + return zoned_time(std::move(zone), zt, c); +} + +template +inline +zoned_time +make_zoned(const std::string& name, const zoned_time& zt, choose c) +{ + return zoned_time(name, zt, c); +} + +template 1916) +#if !defined(__INTEL_COMPILER) || (__INTEL_COMPILER > 1600) + , class = typename std::enable_if + < + std::is_class())>::type>{} + >::type +#endif +#endif + > +inline +zoned_time::type, TimeZonePtr> +make_zoned(TimeZonePtr zone, const sys_time& st) +{ + return zoned_time::type, + TimeZonePtr>(std::move(zone), st); +} + +template +inline +zoned_time::type> +make_zoned(const std::string& name, const sys_time& st) +{ + return zoned_time::type>(name, st); +} + +template +std::basic_ostream& +to_stream(std::basic_ostream& os, const CharT* fmt, + const zoned_time& tp) +{ + using duration = typename zoned_time::duration; + using LT = local_time; + auto const st = tp.get_sys_time(); + auto const info = tp.get_time_zone()->get_info(st); + return to_stream(os, fmt, LT{(st+info.offset).time_since_epoch()}, + &info.abbrev, &info.offset); +} + +template +inline +std::basic_ostream& +operator<<(std::basic_ostream& os, const zoned_time& t) +{ + const CharT fmt[] = {'%', 'F', ' ', '%', 'T', ' ', '%', 'Z', CharT{}}; + return to_stream(os, fmt, t); +} + +class utc_clock +{ +public: + using duration = std::chrono::system_clock::duration; + using rep = duration::rep; + using period = duration::period; + using time_point = std::chrono::time_point; + static CONSTDATA bool is_steady = false; + + static time_point now(); + + template + static + std::chrono::time_point::type> + to_sys(const std::chrono::time_point&); + + template + static + std::chrono::time_point::type> + from_sys(const std::chrono::time_point&); + + template + static + std::chrono::time_point::type> + to_local(const std::chrono::time_point&); + + template + static + std::chrono::time_point::type> + from_local(const std::chrono::time_point&); +}; + +template + using utc_time = std::chrono::time_point; + +using utc_seconds = utc_time; + +template +utc_time::type> +utc_clock::from_sys(const sys_time& st) +{ + using std::chrono::seconds; + using CD = typename std::common_type::type; + auto const& leaps = get_tzdb().leap_seconds; + auto const lt = std::upper_bound(leaps.begin(), leaps.end(), st); + return utc_time{st.time_since_epoch() + seconds{lt-leaps.begin()}}; +} + +// Return pair +// first is true if ut is during a leap second insertion, otherwise false. +// If ut is during a leap second insertion, that leap second is included in the count +template +std::pair +is_leap_second(date::utc_time const& ut) +{ + using std::chrono::seconds; + using duration = typename std::common_type::type; + auto const& leaps = get_tzdb().leap_seconds; + auto tp = sys_time{ut.time_since_epoch()}; + auto const lt = std::upper_bound(leaps.begin(), leaps.end(), tp); + auto ds = seconds{lt-leaps.begin()}; + tp -= ds; + auto ls = false; + if (lt > leaps.begin()) + { + if (tp < lt[-1]) + { + if (tp >= lt[-1].date() - seconds{1}) + ls = true; + else + --ds; + } + } + return {ls, ds}; +} + +struct leap_second_info +{ + bool is_leap_second; + std::chrono::seconds elapsed; +}; + +template +leap_second_info +get_leap_second_info(date::utc_time const& ut) +{ + auto p = is_leap_second(ut); + return {p.first, p.second}; +} + +template +sys_time::type> +utc_clock::to_sys(const utc_time& ut) +{ + using std::chrono::seconds; + using CD = typename std::common_type::type; + auto ls = is_leap_second(ut); + auto tp = sys_time{ut.time_since_epoch() - ls.second}; + if (ls.first) + tp = floor(tp) + seconds{1} - CD{1}; + return tp; +} + +inline +utc_clock::time_point +utc_clock::now() +{ + return from_sys(std::chrono::system_clock::now()); +} + +template +utc_time::type> +utc_clock::from_local(const local_time& st) +{ + return from_sys(sys_time{st.time_since_epoch()}); +} + +template +local_time::type> +utc_clock::to_local(const utc_time& ut) +{ + using CD = typename std::common_type::type; + return local_time{to_sys(ut).time_since_epoch()}; +} + +template +std::basic_ostream& +to_stream(std::basic_ostream& os, const CharT* fmt, + const utc_time& t) +{ + using std::chrono::seconds; + using CT = typename std::common_type::type; + const std::string abbrev("UTC"); + CONSTDATA seconds offset{0}; + auto ls = is_leap_second(t); + auto tp = sys_time{t.time_since_epoch() - ls.second}; + auto const sd = floor(tp); + year_month_day ymd = sd; + auto time = make_time(tp - sys_seconds{sd}); + time.seconds(detail::undocumented{}) += seconds{ls.first}; + fields fds{ymd, time}; + return to_stream(os, fmt, fds, &abbrev, &offset); +} + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const utc_time& t) +{ + const CharT fmt[] = {'%', 'F', ' ', '%', 'T', CharT{}}; + return to_stream(os, fmt, t); +} + +template > +std::basic_istream& +from_stream(std::basic_istream& is, const CharT* fmt, + utc_time& tp, std::basic_string* abbrev = nullptr, + std::chrono::minutes* offset = nullptr) +{ + using std::chrono::seconds; + using std::chrono::minutes; + using CT = typename std::common_type::type; + minutes offset_local{}; + auto offptr = offset ? offset : &offset_local; + fields fds{}; + fds.has_tod = true; + from_stream(is, fmt, fds, abbrev, offptr); + if (!fds.ymd.ok()) + is.setstate(std::ios::failbit); + if (!is.fail()) + { + bool is_60_sec = fds.tod.seconds() == seconds{60}; + if (is_60_sec) + fds.tod.seconds(detail::undocumented{}) -= seconds{1}; + auto tmp = utc_clock::from_sys(sys_days(fds.ymd) - *offptr + fds.tod.to_duration()); + if (is_60_sec) + tmp += seconds{1}; + if (is_60_sec != is_leap_second(tmp).first || !fds.tod.in_conventional_range()) + { + is.setstate(std::ios::failbit); + return is; + } + tp = std::chrono::time_point_cast(tmp); + } + return is; +} + +// tai_clock + +class tai_clock +{ +public: + using duration = std::chrono::system_clock::duration; + using rep = duration::rep; + using period = duration::period; + using time_point = std::chrono::time_point; + static const bool is_steady = false; + + static time_point now(); + + template + static + std::chrono::time_point::type> + to_utc(const std::chrono::time_point&) NOEXCEPT; + + template + static + std::chrono::time_point::type> + from_utc(const std::chrono::time_point&) NOEXCEPT; + + template + static + std::chrono::time_point::type> + to_local(const std::chrono::time_point&) NOEXCEPT; + + template + static + std::chrono::time_point::type> + from_local(const std::chrono::time_point&) NOEXCEPT; +}; + +template + using tai_time = std::chrono::time_point; + +using tai_seconds = tai_time; + +template +inline +utc_time::type> +tai_clock::to_utc(const tai_time& t) NOEXCEPT +{ + using std::chrono::seconds; + using CD = typename std::common_type::type; + return utc_time{t.time_since_epoch()} - + (sys_days(year{1970}/January/1) - sys_days(year{1958}/January/1) + seconds{10}); +} + +template +inline +tai_time::type> +tai_clock::from_utc(const utc_time& t) NOEXCEPT +{ + using std::chrono::seconds; + using CD = typename std::common_type::type; + return tai_time{t.time_since_epoch()} + + (sys_days(year{1970}/January/1) - sys_days(year{1958}/January/1) + seconds{10}); +} + +inline +tai_clock::time_point +tai_clock::now() +{ + return from_utc(utc_clock::now()); +} + +template +inline +local_time::type> +tai_clock::to_local(const tai_time& t) NOEXCEPT +{ + using CD = typename std::common_type::type; + return local_time{t.time_since_epoch()} - + (local_days(year{1970}/January/1) - local_days(year{1958}/January/1)); +} + +template +inline +tai_time::type> +tai_clock::from_local(const local_time& t) NOEXCEPT +{ + using CD = typename std::common_type::type; + return tai_time{t.time_since_epoch()} + + (local_days(year{1970}/January/1) - local_days(year{1958}/January/1)); +} + +template +std::basic_ostream& +to_stream(std::basic_ostream& os, const CharT* fmt, + const tai_time& t) +{ + const std::string abbrev("TAI"); + CONSTDATA std::chrono::seconds offset{0}; + return to_stream(os, fmt, tai_clock::to_local(t), &abbrev, &offset); +} + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const tai_time& t) +{ + const CharT fmt[] = {'%', 'F', ' ', '%', 'T', CharT{}}; + return to_stream(os, fmt, t); +} + +template > +std::basic_istream& +from_stream(std::basic_istream& is, const CharT* fmt, + tai_time& tp, + std::basic_string* abbrev = nullptr, + std::chrono::minutes* offset = nullptr) +{ + local_time lp; + from_stream(is, fmt, lp, abbrev, offset); + if (!is.fail()) + tp = tai_clock::from_local(lp); + return is; +} + +// gps_clock + +class gps_clock +{ +public: + using duration = std::chrono::system_clock::duration; + using rep = duration::rep; + using period = duration::period; + using time_point = std::chrono::time_point; + static const bool is_steady = false; + + static time_point now(); + + template + static + std::chrono::time_point::type> + to_utc(const std::chrono::time_point&) NOEXCEPT; + + template + static + std::chrono::time_point::type> + from_utc(const std::chrono::time_point&) NOEXCEPT; + + template + static + std::chrono::time_point::type> + to_local(const std::chrono::time_point&) NOEXCEPT; + + template + static + std::chrono::time_point::type> + from_local(const std::chrono::time_point&) NOEXCEPT; +}; + +template + using gps_time = std::chrono::time_point; + +using gps_seconds = gps_time; + +template +inline +utc_time::type> +gps_clock::to_utc(const gps_time& t) NOEXCEPT +{ + using std::chrono::seconds; + using CD = typename std::common_type::type; + return utc_time{t.time_since_epoch()} + + (sys_days(year{1980}/January/Sunday[1]) - sys_days(year{1970}/January/1) + + seconds{9}); +} + +template +inline +gps_time::type> +gps_clock::from_utc(const utc_time& t) NOEXCEPT +{ + using std::chrono::seconds; + using CD = typename std::common_type::type; + return gps_time{t.time_since_epoch()} - + (sys_days(year{1980}/January/Sunday[1]) - sys_days(year{1970}/January/1) + + seconds{9}); +} + +inline +gps_clock::time_point +gps_clock::now() +{ + return from_utc(utc_clock::now()); +} + +template +inline +local_time::type> +gps_clock::to_local(const gps_time& t) NOEXCEPT +{ + using CD = typename std::common_type::type; + return local_time{t.time_since_epoch()} + + (local_days(year{1980}/January/Sunday[1]) - local_days(year{1970}/January/1)); +} + +template +inline +gps_time::type> +gps_clock::from_local(const local_time& t) NOEXCEPT +{ + using CD = typename std::common_type::type; + return gps_time{t.time_since_epoch()} - + (local_days(year{1980}/January/Sunday[1]) - local_days(year{1970}/January/1)); +} + + +template +std::basic_ostream& +to_stream(std::basic_ostream& os, const CharT* fmt, + const gps_time& t) +{ + const std::string abbrev("GPS"); + CONSTDATA std::chrono::seconds offset{0}; + return to_stream(os, fmt, gps_clock::to_local(t), &abbrev, &offset); +} + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const gps_time& t) +{ + const CharT fmt[] = {'%', 'F', ' ', '%', 'T', CharT{}}; + return to_stream(os, fmt, t); +} + +template > +std::basic_istream& +from_stream(std::basic_istream& is, const CharT* fmt, + gps_time& tp, + std::basic_string* abbrev = nullptr, + std::chrono::minutes* offset = nullptr) +{ + local_time lp; + from_stream(is, fmt, lp, abbrev, offset); + if (!is.fail()) + tp = gps_clock::from_local(lp); + return is; +} + +// clock_time_conversion + +template +struct clock_time_conversion +{}; + +template <> +struct clock_time_conversion +{ + template + CONSTCD14 + sys_time + operator()(const sys_time& st) const + { + return st; + } +}; + +template <> +struct clock_time_conversion +{ + template + CONSTCD14 + utc_time + operator()(const utc_time& ut) const + { + return ut; + } +}; + +template<> +struct clock_time_conversion +{ + template + CONSTCD14 + local_time + operator()(const local_time& lt) const + { + return lt; + } +}; + +template <> +struct clock_time_conversion +{ + template + utc_time::type> + operator()(const sys_time& st) const + { + return utc_clock::from_sys(st); + } +}; + +template <> +struct clock_time_conversion +{ + template + sys_time::type> + operator()(const utc_time& ut) const + { + return utc_clock::to_sys(ut); + } +}; + +template<> +struct clock_time_conversion +{ + template + CONSTCD14 + local_time + operator()(const sys_time& st) const + { + return local_time{st.time_since_epoch()}; + } +}; + +template<> +struct clock_time_conversion +{ + template + CONSTCD14 + sys_time + operator()(const local_time& lt) const + { + return sys_time{lt.time_since_epoch()}; + } +}; + +template<> +struct clock_time_conversion +{ + template + utc_time::type> + operator()(const local_time& lt) const + { + return utc_clock::from_local(lt); + } +}; + +template<> +struct clock_time_conversion +{ + template + local_time::type> + operator()(const utc_time& ut) const + { + return utc_clock::to_local(ut); + } +}; + +template +struct clock_time_conversion +{ + template + CONSTCD14 + std::chrono::time_point + operator()(const std::chrono::time_point& tp) const + { + return tp; + } +}; + +namespace ctc_detail +{ + +template + using time_point = std::chrono::time_point; + +using std::declval; +using std::chrono::system_clock; + +//Check if TimePoint is time for given clock, +//if not emits hard error +template +struct return_clock_time +{ + using clock_time_point = time_point; + using type = TimePoint; + + static_assert(std::is_same::value, + "time point with appropariate clock shall be returned"); +}; + +// Check if Clock has to_sys method accepting TimePoint with given duration const& and +// returning sys_time. If so has nested type member equal to return type to_sys. +template +struct return_to_sys +{}; + +template +struct return_to_sys + < + Clock, Duration, + decltype(Clock::to_sys(declval const&>()), void()) + > + : return_clock_time + < + system_clock, + decltype(Clock::to_sys(declval const&>())) + > +{}; + +// Similiar to above +template +struct return_from_sys +{}; + +template +struct return_from_sys + < + Clock, Duration, + decltype(Clock::from_sys(declval const&>()), + void()) + > + : return_clock_time + < + Clock, + decltype(Clock::from_sys(declval const&>())) + > +{}; + +// Similiar to above +template +struct return_to_utc +{}; + +template +struct return_to_utc + < + Clock, Duration, + decltype(Clock::to_utc(declval const&>()), void()) + > + : return_clock_time + < + utc_clock, + decltype(Clock::to_utc(declval const&>()))> +{}; + +// Similiar to above +template +struct return_from_utc +{}; + +template +struct return_from_utc + < + Clock, Duration, + decltype(Clock::from_utc(declval const&>()), + void()) + > + : return_clock_time + < + Clock, + decltype(Clock::from_utc(declval const&>())) + > +{}; + +// Similiar to above +template +struct return_to_local +{}; + +template +struct return_to_local + < + Clock, Duration, + decltype(Clock::to_local(declval const&>()), + void()) + > + : return_clock_time + < + local_t, + decltype(Clock::to_local(declval const&>())) + > +{}; + +// Similiar to above +template +struct return_from_local +{}; + +template +struct return_from_local + < + Clock, Duration, + decltype(Clock::from_local(declval const&>()), + void()) + > + : return_clock_time + < + Clock, + decltype(Clock::from_local(declval const&>())) + > +{}; + +} // namespace ctc_detail + +template +struct clock_time_conversion +{ + template + CONSTCD14 + typename ctc_detail::return_to_sys::type + operator()(const std::chrono::time_point& tp) const + { + return SrcClock::to_sys(tp); + } +}; + +template +struct clock_time_conversion +{ + template + CONSTCD14 + typename ctc_detail::return_from_sys::type + operator()(const sys_time& st) const + { + return DstClock::from_sys(st); + } +}; + +template +struct clock_time_conversion +{ + template + CONSTCD14 + typename ctc_detail::return_to_utc::type + operator()(const std::chrono::time_point& tp) const + { + return SrcClock::to_utc(tp); + } +}; + +template +struct clock_time_conversion +{ + template + CONSTCD14 + typename ctc_detail::return_from_utc::type + operator()(const utc_time& ut) const + { + return DstClock::from_utc(ut); + } +}; + +template +struct clock_time_conversion +{ + template + CONSTCD14 + typename ctc_detail::return_to_local::type + operator()(const std::chrono::time_point& tp) const + { + return SrcClock::to_local(tp); + } +}; + +template +struct clock_time_conversion +{ + template + CONSTCD14 + typename ctc_detail::return_from_local::type + operator()(const local_time& lt) const + { + return DstClock::from_local(lt); + } +}; + +namespace clock_cast_detail +{ + +template + using time_point = std::chrono::time_point; +using std::chrono::system_clock; + +template +CONSTCD14 +auto +conv_clock(const time_point& t) + -> decltype(std::declval>()(t)) +{ + return clock_time_conversion{}(t); +} + +//direct trait conversion, 1st candidate +template +CONSTCD14 +auto +cc_impl(const time_point& t, const time_point*) + -> decltype(conv_clock(t)) +{ + return conv_clock(t); +} + +//conversion through sys, 2nd candidate +template +CONSTCD14 +auto +cc_impl(const time_point& t, const void*) + -> decltype(conv_clock(conv_clock(t))) +{ + return conv_clock(conv_clock(t)); +} + +//conversion through utc, 2nd candidate +template +CONSTCD14 +auto +cc_impl(const time_point& t, const void*) + -> decltype(0, // MSVC_WORKAROUND + conv_clock(conv_clock(t))) +{ + return conv_clock(conv_clock(t)); +} + +//conversion through sys and utc, 3rd candidate +template +CONSTCD14 +auto +cc_impl(const time_point& t, ...) + -> decltype(conv_clock(conv_clock(conv_clock(t)))) +{ + return conv_clock(conv_clock(conv_clock(t))); +} + +//conversion through utc and sys, 3rd candidate +template +CONSTCD14 +auto +cc_impl(const time_point& t, ...) + -> decltype(0, // MSVC_WORKAROUND + conv_clock(conv_clock(conv_clock(t)))) +{ + return conv_clock(conv_clock(conv_clock(t))); +} + +} // namespace clock_cast_detail + +template +CONSTCD14 +auto +clock_cast(const std::chrono::time_point& tp) + -> decltype(clock_cast_detail::cc_impl(tp, &tp)) +{ + return clock_cast_detail::cc_impl(tp, &tp); +} + +// Deprecated API + +template +inline +sys_time::type> +to_sys_time(const utc_time& t) +{ + return utc_clock::to_sys(t); +} + +template +inline +sys_time::type> +to_sys_time(const tai_time& t) +{ + return utc_clock::to_sys(tai_clock::to_utc(t)); +} + +template +inline +sys_time::type> +to_sys_time(const gps_time& t) +{ + return utc_clock::to_sys(gps_clock::to_utc(t)); +} + + +template +inline +utc_time::type> +to_utc_time(const sys_time& t) +{ + return utc_clock::from_sys(t); +} + +template +inline +utc_time::type> +to_utc_time(const tai_time& t) +{ + return tai_clock::to_utc(t); +} + +template +inline +utc_time::type> +to_utc_time(const gps_time& t) +{ + return gps_clock::to_utc(t); +} + + +template +inline +tai_time::type> +to_tai_time(const sys_time& t) +{ + return tai_clock::from_utc(utc_clock::from_sys(t)); +} + +template +inline +tai_time::type> +to_tai_time(const utc_time& t) +{ + return tai_clock::from_utc(t); +} + +template +inline +tai_time::type> +to_tai_time(const gps_time& t) +{ + return tai_clock::from_utc(gps_clock::to_utc(t)); +} + + +template +inline +gps_time::type> +to_gps_time(const sys_time& t) +{ + return gps_clock::from_utc(utc_clock::from_sys(t)); +} + +template +inline +gps_time::type> +to_gps_time(const utc_time& t) +{ + return gps_clock::from_utc(t); +} + +template +inline +gps_time::type> +to_gps_time(const tai_time& t) +{ + return gps_clock::from_utc(tai_clock::to_utc(t)); +} + +} // namespace date + +#endif // TZ_H diff --git a/third_party/date/include/date/tz_private.h b/third_party/date/include/date/tz_private.h new file mode 100644 index 0000000..aec01d0 --- /dev/null +++ b/third_party/date/include/date/tz_private.h @@ -0,0 +1,316 @@ +#ifndef TZ_PRIVATE_H +#define TZ_PRIVATE_H + +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. +// +// Our apologies. When the previous paragraph was written, lowercase had not yet +// been invented (that would involve another several millennia of evolution). +// We did not mean to shout. + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) +#include "tz.h" +#else +#include "date.h" +#include +#endif + +namespace date +{ + +namespace detail +{ + +#if !USE_OS_TZDB + +enum class tz {utc, local, standard}; + +//forward declare to avoid warnings in gcc 6.2 +class MonthDayTime; +std::istream& operator>>(std::istream& is, MonthDayTime& x); +std::ostream& operator<<(std::ostream& os, const MonthDayTime& x); + + +class MonthDayTime +{ +private: + struct pair + { +#if defined(_MSC_VER) && (_MSC_VER < 1900) + pair() : month_day_(date::jan / 1), weekday_(0U) {} + + pair(const date::month_day& month_day, const date::weekday& weekday) + : month_day_(month_day), weekday_(weekday) {} +#endif + + date::month_day month_day_; + date::weekday weekday_; + }; + + enum Type {month_day, month_last_dow, lteq, gteq}; + + Type type_{month_day}; + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) + union U +#else + struct U +#endif + { + date::month_day month_day_; + date::month_weekday_last month_weekday_last_; + pair month_day_weekday_; + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) + U() : month_day_{date::jan/1} {} +#else + U() : + month_day_(date::jan/1), + month_weekday_last_(date::month(0U), date::weekday_last(date::weekday(0U))) + {} + +#endif // !defined(_MSC_VER) || (_MSC_VER >= 1900) + + U& operator=(const date::month_day& x); + U& operator=(const date::month_weekday_last& x); + U& operator=(const pair& x); + } u; + + std::chrono::hours h_{0}; + std::chrono::minutes m_{0}; + std::chrono::seconds s_{0}; + tz zone_{tz::local}; + +public: + MonthDayTime() = default; + MonthDayTime(local_seconds tp, tz timezone); + MonthDayTime(const date::month_day& md, tz timezone); + + date::day day() const; + date::month month() const; + tz zone() const {return zone_;} + + void canonicalize(date::year y); + + sys_seconds + to_sys(date::year y, std::chrono::seconds offset, std::chrono::seconds save) const; + sys_days to_sys_days(date::year y) const; + + sys_seconds to_time_point(date::year y) const; + int compare(date::year y, const MonthDayTime& x, date::year yx, + std::chrono::seconds offset, std::chrono::minutes prev_save) const; + + friend std::istream& operator>>(std::istream& is, MonthDayTime& x); + friend std::ostream& operator<<(std::ostream& os, const MonthDayTime& x); +}; + +// A Rule specifies one or more set of datetimes without using an offset. +// Multiple dates are specified with multiple years. The years in effect +// go from starting_year_ to ending_year_, inclusive. starting_year_ <= +// ending_year_. save_ is in effect for times from the specified time +// onward, including the specified time. When the specified time is +// local, it uses the save_ from the chronologically previous Rule, or if +// there is none, 0. + +//forward declare to avoid warnings in gcc 6.2 +class Rule; +bool operator==(const Rule& x, const Rule& y); +bool operator<(const Rule& x, const Rule& y); +bool operator==(const Rule& x, const date::year& y); +bool operator<(const Rule& x, const date::year& y); +bool operator==(const date::year& x, const Rule& y); +bool operator<(const date::year& x, const Rule& y); +bool operator==(const Rule& x, const std::string& y); +bool operator<(const Rule& x, const std::string& y); +bool operator==(const std::string& x, const Rule& y); +bool operator<(const std::string& x, const Rule& y); +std::ostream& operator<<(std::ostream& os, const Rule& r); + +class Rule +{ +private: + std::string name_; + date::year starting_year_{0}; + date::year ending_year_{0}; + MonthDayTime starting_at_; + std::chrono::minutes save_{0}; + std::string abbrev_; + +public: + Rule() = default; + explicit Rule(const std::string& s); + Rule(const Rule& r, date::year starting_year, date::year ending_year); + + const std::string& name() const {return name_;} + const std::string& abbrev() const {return abbrev_;} + + const MonthDayTime& mdt() const {return starting_at_;} + const date::year& starting_year() const {return starting_year_;} + const date::year& ending_year() const {return ending_year_;} + const std::chrono::minutes& save() const {return save_;} + + static void split_overlaps(std::vector& rules); + + friend bool operator==(const Rule& x, const Rule& y); + friend bool operator<(const Rule& x, const Rule& y); + friend bool operator==(const Rule& x, const date::year& y); + friend bool operator<(const Rule& x, const date::year& y); + friend bool operator==(const date::year& x, const Rule& y); + friend bool operator<(const date::year& x, const Rule& y); + friend bool operator==(const Rule& x, const std::string& y); + friend bool operator<(const Rule& x, const std::string& y); + friend bool operator==(const std::string& x, const Rule& y); + friend bool operator<(const std::string& x, const Rule& y); + + friend std::ostream& operator<<(std::ostream& os, const Rule& r); + +private: + date::day day() const; + date::month month() const; + static void split_overlaps(std::vector& rules, std::size_t i, std::size_t& e); + static bool overlaps(const Rule& x, const Rule& y); + static void split(std::vector& rules, std::size_t i, std::size_t k, + std::size_t& e); +}; + +inline bool operator!=(const Rule& x, const Rule& y) {return !(x == y);} +inline bool operator> (const Rule& x, const Rule& y) {return y < x;} +inline bool operator<=(const Rule& x, const Rule& y) {return !(y < x);} +inline bool operator>=(const Rule& x, const Rule& y) {return !(x < y);} + +inline bool operator!=(const Rule& x, const date::year& y) {return !(x == y);} +inline bool operator> (const Rule& x, const date::year& y) {return y < x;} +inline bool operator<=(const Rule& x, const date::year& y) {return !(y < x);} +inline bool operator>=(const Rule& x, const date::year& y) {return !(x < y);} + +inline bool operator!=(const date::year& x, const Rule& y) {return !(x == y);} +inline bool operator> (const date::year& x, const Rule& y) {return y < x;} +inline bool operator<=(const date::year& x, const Rule& y) {return !(y < x);} +inline bool operator>=(const date::year& x, const Rule& y) {return !(x < y);} + +inline bool operator!=(const Rule& x, const std::string& y) {return !(x == y);} +inline bool operator> (const Rule& x, const std::string& y) {return y < x;} +inline bool operator<=(const Rule& x, const std::string& y) {return !(y < x);} +inline bool operator>=(const Rule& x, const std::string& y) {return !(x < y);} + +inline bool operator!=(const std::string& x, const Rule& y) {return !(x == y);} +inline bool operator> (const std::string& x, const Rule& y) {return y < x;} +inline bool operator<=(const std::string& x, const Rule& y) {return !(y < x);} +inline bool operator>=(const std::string& x, const Rule& y) {return !(x < y);} + +struct zonelet +{ + enum tag {has_rule, has_save, is_empty}; + + std::chrono::seconds gmtoff_; + tag tag_ = has_rule; + +#if !defined(_MSC_VER) || (_MSC_VER >= 1900) + union U +#else + struct U +#endif + { + std::string rule_; + std::chrono::minutes save_; + + ~U() {} + U() {} + U(const U&) {} + U& operator=(const U&) = delete; + } u; + + std::string format_; + date::year until_year_{0}; + MonthDayTime until_date_; + sys_seconds until_utc_; + local_seconds until_std_; + local_seconds until_loc_; + std::chrono::minutes initial_save_{0}; + std::string initial_abbrev_; + std::pair first_rule_{nullptr, date::year::min()}; + std::pair last_rule_{nullptr, date::year::max()}; + + ~zonelet(); + zonelet(); + zonelet(const zonelet& i); + zonelet& operator=(const zonelet&) = delete; +}; + +#else // USE_OS_TZDB + +struct ttinfo +{ + std::int32_t tt_gmtoff; + unsigned char tt_isdst; + unsigned char tt_abbrind; + unsigned char pad[2]; +}; + +static_assert(sizeof(ttinfo) == 8, ""); + +struct expanded_ttinfo +{ + std::chrono::seconds offset; + std::string abbrev; + bool is_dst; +}; + +struct transition +{ + sys_seconds timepoint; + const expanded_ttinfo* info; + + transition(sys_seconds tp, const expanded_ttinfo* i = nullptr) + : timepoint(tp) + , info(i) + {} + + friend + std::ostream& + operator<<(std::ostream& os, const transition& t) + { + using date::operator<<; + os << t.timepoint << "Z "; + if (t.info->offset >= std::chrono::seconds{0}) + os << '+'; + os << make_time(t.info->offset); + if (t.info->is_dst > 0) + os << " daylight "; + else + os << " standard "; + os << t.info->abbrev; + return os; + } +}; + +#endif // USE_OS_TZDB + +} // namespace detail + +} // namespace date + +#if defined(_MSC_VER) && (_MSC_VER < 1900) +#include "tz.h" +#endif + +#endif // TZ_PRIVATE_H diff --git a/third_party/date/src/ios.mm b/third_party/date/src/ios.mm new file mode 100644 index 0000000..fe3bb24 --- /dev/null +++ b/third_party/date/src/ios.mm @@ -0,0 +1,337 @@ +// +// The MIT License (MIT) +// +// Copyright (c) 2016 Alexander Kormanovsky +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// + +#include "date/ios.h" + +#if TARGET_OS_IPHONE + +#include + +#include +#include +#include + +#ifndef TAR_DEBUG +# define TAR_DEBUG 0 +#endif + +#define INTERNAL_DIR "Library" +#define TZDATA_DIR "tzdata" +#define TARGZ_EXTENSION "tar.gz" + +#define TAR_BLOCK_SIZE 512 +#define TAR_TYPE_POSITION 156 +#define TAR_NAME_POSITION 0 +#define TAR_NAME_SIZE 100 +#define TAR_SIZE_POSITION 124 +#define TAR_SIZE_SIZE 12 + +namespace date +{ + namespace iOSUtils + { + + struct TarInfo + { + char objType; + std::string objName; + size_t realContentSize; // writable size without padding zeroes + size_t blocksContentSize; // adjusted size to 512 bytes blocks + bool success; + }; + + std::string convertCFStringRefPathToCStringPath(CFStringRef ref); + bool extractTzdata(CFURLRef homeUrl, CFURLRef archiveUrl, std::string destPath); + TarInfo getTarObjectInfo(std::ifstream &readStream); + std::string getTarObject(std::ifstream &readStream, int64_t size); + bool writeFile(const std::string &tzdataPath, const std::string &fileName, + const std::string &data, size_t realContentSize); + + std::string + get_current_timezone() + { + CFTimeZoneRef tzRef = CFTimeZoneCopySystem(); + CFStringRef tzNameRef = CFTimeZoneGetName(tzRef); + CFIndex bufferSize = CFStringGetLength(tzNameRef) + 1; + char buffer[bufferSize]; + + if (CFStringGetCString(tzNameRef, buffer, bufferSize, kCFStringEncodingUTF8)) + { + CFRelease(tzRef); + return std::string(buffer); + } + + CFRelease(tzRef); + + return ""; + } + + std::string + get_tzdata_path() + { + CFURLRef homeUrlRef = CFCopyHomeDirectoryURL(); + CFStringRef homePath = CFURLCopyPath(homeUrlRef); + std::string path(std::string(convertCFStringRefPathToCStringPath(homePath)) + + INTERNAL_DIR + "/" + TZDATA_DIR); + std::string result_path(std::string(convertCFStringRefPathToCStringPath(homePath)) + + INTERNAL_DIR); + + if (access(path.c_str(), F_OK) == 0) + { +#if TAR_DEBUG + printf("tzdata dir exists\n"); +#endif + CFRelease(homeUrlRef); + CFRelease(homePath); + + return result_path; + } + + CFBundleRef mainBundle = CFBundleGetMainBundle(); + CFArrayRef paths = CFBundleCopyResourceURLsOfType(mainBundle, CFSTR(TARGZ_EXTENSION), + NULL); + + if (CFArrayGetCount(paths) != 0) + { + // get archive path, assume there is no other tar.gz in bundle + CFURLRef archiveUrl = static_cast(CFArrayGetValueAtIndex(paths, 0)); + CFStringRef archiveName = CFURLCopyPath(archiveUrl); + archiveUrl = CFBundleCopyResourceURL(mainBundle, archiveName, NULL, NULL); + + extractTzdata(homeUrlRef, archiveUrl, path); + + CFRelease(archiveUrl); + CFRelease(archiveName); + } + + CFRelease(homeUrlRef); + CFRelease(homePath); + CFRelease(paths); + + return result_path; + } + + std::string + convertCFStringRefPathToCStringPath(CFStringRef ref) + { + CFIndex bufferSize = CFStringGetMaximumSizeOfFileSystemRepresentation(ref); + char *buffer = new char[bufferSize]; + CFStringGetFileSystemRepresentation(ref, buffer, bufferSize); + auto result = std::string(buffer); + delete[] buffer; + return result; + } + + bool + extractTzdata(CFURLRef homeUrl, CFURLRef archiveUrl, std::string destPath) + { + std::string TAR_TMP_PATH = "/tmp.tar"; + + CFStringRef homeStringRef = CFURLCopyPath(homeUrl); + auto homePath = convertCFStringRefPathToCStringPath(homeStringRef); + CFRelease(homeStringRef); + + CFStringRef archiveStringRef = CFURLCopyPath(archiveUrl); + auto archivePath = convertCFStringRefPathToCStringPath(archiveStringRef); + CFRelease(archiveStringRef); + + // create Library path + auto libraryPath = homePath + INTERNAL_DIR; + + // create tzdata path + auto tzdataPath = libraryPath + "/" + TZDATA_DIR; + + // -- replace %20 with " " + const std::string search = "%20"; + const std::string replacement = " "; + size_t pos = 0; + + while ((pos = archivePath.find(search, pos)) != std::string::npos) { + archivePath.replace(pos, search.length(), replacement); + pos += replacement.length(); + } + + gzFile tarFile = gzopen(archivePath.c_str(), "rb"); + + // create tar unpacking path + auto tarPath = libraryPath + TAR_TMP_PATH; + + // create tzdata directory + mkdir(destPath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); + + // ======= extract tar ======== + + std::ofstream os(tarPath.c_str(), std::ofstream::out | std::ofstream::app); + unsigned int bufferLength = 1024 * 256; // 256Kb + unsigned char *buffer = (unsigned char *)malloc(bufferLength); + bool success = true; + + while (true) + { + int readBytes = gzread(tarFile, buffer, bufferLength); + + if (readBytes > 0) + { + os.write((char *) &buffer[0], readBytes); + } + else + if (readBytes == 0) + { + break; + } + else + if (readBytes == -1) + { + printf("decompression failed\n"); + success = false; + break; + } + else + { + printf("unexpected zlib state\n"); + success = false; + break; + } + } + + os.close(); + free(buffer); + gzclose(tarFile); + + if (!success) + { + remove(tarPath.c_str()); + return false; + } + + // ======== extract files ========= + + uint64_t location = 0; // Position in the file + + // get file size + struct stat stat_buf; + int res = stat(tarPath.c_str(), &stat_buf); + if (res != 0) + { + printf("error file size\n"); + remove(tarPath.c_str()); + return false; + } + int64_t tarSize = stat_buf.st_size; + + // create read stream + std::ifstream is(tarPath.c_str(), std::ifstream::in | std::ifstream::binary); + + // process files + while (location < tarSize) + { + TarInfo info = getTarObjectInfo(is); + + if (!info.success || info.realContentSize == 0) + { + break; // something wrong or all files are read + } + + switch (info.objType) + { + case '0': // file + case '\0': // + { + std::string obj = getTarObject(is, info.blocksContentSize); +#if TAR_DEBUG + size += info.realContentSize; + printf("#%i %s file size %lld written total %ld from %lld\n", ++count, + info.objName.c_str(), info.realContentSize, size, tarSize); +#endif + writeFile(tzdataPath, info.objName, obj, info.realContentSize); + location += info.blocksContentSize; + + break; + } + } + } + + remove(tarPath.c_str()); + + return true; + } + + TarInfo + getTarObjectInfo(std::ifstream &readStream) + { + int64_t length = TAR_BLOCK_SIZE; + char buffer[length]; + char type; + char name[TAR_NAME_SIZE + 1]; + char sizeBuf[TAR_SIZE_SIZE + 1]; + + readStream.read(buffer, length); + + memcpy(&type, &buffer[TAR_TYPE_POSITION], 1); + + memset(&name, '\0', TAR_NAME_SIZE + 1); + memcpy(&name, &buffer[TAR_NAME_POSITION], TAR_NAME_SIZE); + + memset(&sizeBuf, '\0', TAR_SIZE_SIZE + 1); + memcpy(&sizeBuf, &buffer[TAR_SIZE_POSITION], TAR_SIZE_SIZE); + size_t realSize = strtol(sizeBuf, NULL, 8); + size_t blocksSize = realSize + (TAR_BLOCK_SIZE - (realSize % TAR_BLOCK_SIZE)); + + return {type, std::string(name), realSize, blocksSize, true}; + } + + std::string + getTarObject(std::ifstream &readStream, int64_t size) + { + char buffer[size]; + readStream.read(buffer, size); + return std::string(buffer); + } + + bool + writeFile(const std::string &tzdataPath, const std::string &fileName, const std::string &data, + size_t realContentSize) + { + std::ofstream os(tzdataPath + "/" + fileName, std::ofstream::out | std::ofstream::binary); + + if (!os) { + return false; + } + + // trim empty space + char trimmedData[realContentSize + 1]; + memset(&trimmedData, '\0', realContentSize); + memcpy(&trimmedData, data.c_str(), realContentSize); + + // write + os.write(trimmedData, realContentSize); + os.close(); + + return true; + } + + } // namespace iOSUtils +} // namespace date + +#endif // TARGET_OS_IPHONE diff --git a/third_party/date/src/tz.cpp b/third_party/date/src/tz.cpp new file mode 100644 index 0000000..26babbd --- /dev/null +++ b/third_party/date/src/tz.cpp @@ -0,0 +1,3944 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016, 2017 Howard Hinnant +// Copyright (c) 2015 Ville Voutilainen +// Copyright (c) 2016 Alexander Kormanovsky +// Copyright (c) 2016, 2017 Jiangang Zhuang +// Copyright (c) 2017 Nicolas Veloz Savino +// Copyright (c) 2017 Florian Dang +// Copyright (c) 2017 Aaron Bishop +// +// 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. +// +// Our apologies. When the previous paragraph was written, lowercase had not yet +// been invented (that would involve another several millennia of evolution). +// We did not mean to shout. + +#ifdef _WIN32 + // windows.h will be included directly and indirectly (e.g. by curl). + // We need to define these macros to prevent windows.h bringing in + // more than we need and do it early so windows.h doesn't get included + // without these macros having been defined. + // min/max macros interfere with the C++ versions. +# ifndef NOMINMAX +# define NOMINMAX +# endif + // We don't need all that Windows has to offer. +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif + + // for wcstombs +# ifndef _CRT_SECURE_NO_WARNINGS +# define _CRT_SECURE_NO_WARNINGS +# endif + + // None of this happens with the MS SDK (at least VS14 which I tested), but: + // Compiling with mingw, we get "error: 'KF_FLAG_DEFAULT' was not declared in this scope." + // and error: 'SHGetKnownFolderPath' was not declared in this scope.". + // It seems when using mingw NTDDI_VERSION is undefined and that + // causes KNOWN_FOLDER_FLAG and the KF_ flags to not get defined. + // So we must define NTDDI_VERSION to get those flags on mingw. + // The docs say though here: + // https://msdn.microsoft.com/en-nz/library/windows/desktop/aa383745(v=vs.85).aspx + // that "If you define NTDDI_VERSION, you must also define _WIN32_WINNT." + // So we declare we require Vista or greater. +# ifdef __MINGW32__ + +# ifndef NTDDI_VERSION +# define NTDDI_VERSION 0x06000000 +# define _WIN32_WINNT _WIN32_WINNT_VISTA +# elif NTDDI_VERSION < 0x06000000 +# warning "If this fails to compile NTDDI_VERSION may be to low. See comments above." +# endif + // But once we define the values above we then get this linker error: + // "tz.cpp:(.rdata$.refptr.FOLDERID_Downloads[.refptr.FOLDERID_Downloads]+0x0): " + // "undefined reference to `FOLDERID_Downloads'" + // which #include cures see: + // https://support.microsoft.com/en-us/kb/130869 +# include + // But with included, the error moves on to: + // error: 'FOLDERID_Downloads' was not declared in this scope + // Which #include cures. +# include + +# endif // __MINGW32__ + +# include +#endif // _WIN32 + +#include "date/tz_private.h" + +#ifdef __APPLE__ +# include "date/ios.h" +#else +# define TARGET_OS_IPHONE 0 +# define TARGET_OS_SIMULATOR 0 +#endif + +#if USE_OS_TZDB +# include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if USE_OS_TZDB +# include +#endif +#include +#include +#include +#include +#include + +// unistd.h is used on some platforms as part of the the means to get +// the current time zone. On Win32 windows.h provides a means to do it. +// gcc/mingw supports unistd.h on Win32 but MSVC does not. + +#ifdef _WIN32 +# ifdef WINAPI_FAMILY +# include +# if WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP +# define WINRT +# define INSTALL . +# endif +# endif + +# include // _unlink etc. + +# if defined(__clang__) + struct IUnknown; // fix for issue with static_cast<> in objbase.h + // (see https://github.com/philsquared/Catch/issues/690) +# endif + +# include // CoTaskFree, ShGetKnownFolderPath etc. +# if HAS_REMOTE_API +# include // _mkdir +# include // ShFileOperation etc. +# endif // HAS_REMOTE_API +#else // !_WIN32 +# include +# if !USE_OS_TZDB && !defined(INSTALL) +# include +# endif +# include +# include +# if !USE_SHELL_API +# include +# include +# include +# include +# include +# include +# endif //!USE_SHELL_API +#endif // !_WIN32 + + +#if HAS_REMOTE_API + // Note curl includes windows.h so we must include curl AFTER definitions of things + // that affect windows.h such as NOMINMAX. +#if defined(_MSC_VER) && defined(SHORTENED_CURL_INCLUDE) + // For rmt_curl nuget package +# include +#else +# include +#endif +#endif + +#ifdef _WIN32 +static CONSTDATA char folder_delimiter = '\\'; +#else // !_WIN32 +static CONSTDATA char folder_delimiter = '/'; +#endif // !_WIN32 + +#if defined(__GNUC__) && __GNUC__ < 5 + // GCC 4.9 Bug 61489 Wrong warning with -Wmissing-field-initializers +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#endif // defined(__GNUC__) && __GNUC__ < 5 + +#if !USE_OS_TZDB + +# ifdef _WIN32 +# ifndef WINRT + +namespace +{ + struct task_mem_deleter + { + void operator()(wchar_t buf[]) + { + if (buf != nullptr) + CoTaskMemFree(buf); + } + }; + using co_task_mem_ptr = std::unique_ptr; +} + +// We might need to know certain locations even if not using the remote API, +// so keep these routines out of that block for now. +static +std::string +get_known_folder(const GUID& folderid) +{ + std::string folder; + PWSTR pfolder = nullptr; + HRESULT hr = SHGetKnownFolderPath(folderid, KF_FLAG_DEFAULT, nullptr, &pfolder); + if (SUCCEEDED(hr)) + { + co_task_mem_ptr folder_ptr(pfolder); + const wchar_t* fptr = folder_ptr.get(); + auto state = std::mbstate_t(); + const auto required = std::wcsrtombs(nullptr, &fptr, 0, &state); + if (required != 0 && required != std::size_t(-1)) + { + folder.resize(required); + std::wcsrtombs(&folder[0], &fptr, folder.size(), &state); + } + } + return folder; +} + +# ifndef INSTALL + +// Usually something like "c:\Users\username\Downloads". +static +std::string +get_download_folder() +{ + return get_known_folder(FOLDERID_Downloads); +} + +# endif // !INSTALL + +# endif // WINRT +# else // !_WIN32 + +# if !defined(INSTALL) + +static +std::string +expand_path(std::string path) +{ +# if TARGET_OS_IPHONE + return date::iOSUtils::get_tzdata_path(); +# else // !TARGET_OS_IPHONE + ::wordexp_t w{}; + std::unique_ptr<::wordexp_t, void(*)(::wordexp_t*)> hold{&w, ::wordfree}; + ::wordexp(path.c_str(), &w, 0); + if (w.we_wordc != 1) + throw std::runtime_error("Cannot expand path: " + path); + path = w.we_wordv[0]; + return path; +# endif // !TARGET_OS_IPHONE +} + +static +std::string +get_download_folder() +{ + return expand_path("~/Downloads"); +} + +# endif // !defined(INSTALL) + +# endif // !_WIN32 + +#endif // !USE_OS_TZDB + +namespace date +{ +// +---------------------+ +// | Begin Configuration | +// +---------------------+ + +using namespace detail; + +#if !USE_OS_TZDB + +static +std::string& +access_install() +{ + static std::string install +#ifndef INSTALL + + = get_download_folder() + folder_delimiter + "tzdata"; + +#else // !INSTALL + +# define STRINGIZEIMP(x) #x +# define STRINGIZE(x) STRINGIZEIMP(x) + + = STRINGIZE(INSTALL) + std::string(1, folder_delimiter) + "tzdata"; + + #undef STRINGIZEIMP + #undef STRINGIZE +#endif // !INSTALL + + return install; +} + +void +set_install(const std::string& s) +{ + access_install() = s; +} + +static +const std::string& +get_install() +{ + static const std::string& ref = access_install(); + return ref; +} + +#if HAS_REMOTE_API +static +std::string +get_download_gz_file(const std::string& version) +{ + auto file = get_install() + version + ".tar.gz"; + return file; +} +#endif // HAS_REMOTE_API + +#endif // !USE_OS_TZDB + +// These can be used to reduce the range of the database to save memory +CONSTDATA auto min_year = date::year::min(); +CONSTDATA auto max_year = date::year::max(); + +CONSTDATA auto min_day = date::January/1; +CONSTDATA auto max_day = date::December/31; + +#if USE_OS_TZDB + +CONSTCD14 const sys_seconds min_seconds = sys_days(min_year/min_day); + +#endif // USE_OS_TZDB + +#ifndef _WIN32 + +static +std::string +discover_tz_dir() +{ + struct stat sb; + using namespace std; +# ifndef __APPLE__ + CONSTDATA auto tz_dir_default = "/usr/share/zoneinfo"; + CONSTDATA auto tz_dir_buildroot = "/usr/share/zoneinfo/uclibc"; + + // Check special path which is valid for buildroot with uclibc builds + if(stat(tz_dir_buildroot, &sb) == 0 && S_ISDIR(sb.st_mode)) + return tz_dir_buildroot; + else if(stat(tz_dir_default, &sb) == 0 && S_ISDIR(sb.st_mode)) + return tz_dir_default; + else + throw runtime_error("discover_tz_dir failed to find zoneinfo\n"); +# else // __APPLE__ +# if TARGET_OS_IPHONE +# if TARGET_OS_SIMULATOR + return "/usr/share/zoneinfo"; +# else + return "/var/db/timezone/zoneinfo"; +# endif +# else + CONSTDATA auto timezone = "/etc/localtime"; + if (!(lstat(timezone, &sb) == 0 && S_ISLNK(sb.st_mode) && sb.st_size > 0)) + throw runtime_error("discover_tz_dir failed\n"); + string result; + char rp[PATH_MAX+1] = {}; + if (readlink(timezone, rp, sizeof(rp)-1) > 0) + result = string(rp); + else + throw system_error(errno, system_category(), "readlink() failed"); + auto i = result.find("zoneinfo"); + if (i == string::npos) + throw runtime_error("discover_tz_dir failed to find zoneinfo\n"); + i = result.find('/', i); + if (i == string::npos) + throw runtime_error("discover_tz_dir failed to find '/'\n"); + return result.substr(0, i); +# endif +# endif // __APPLE__ +} + +static +const std::string& +get_tz_dir() +{ + static const std::string tz_dir = discover_tz_dir(); + return tz_dir; +} + +#endif + +// +-------------------+ +// | End Configuration | +// +-------------------+ + +#ifndef _MSC_VER +static_assert(min_year <= max_year, "Configuration error"); +#endif + +static std::unique_ptr init_tzdb(); + +tzdb_list::~tzdb_list() +{ + const tzdb* ptr = head_; + head_ = nullptr; + while (ptr != nullptr) + { + auto next = ptr->next; + delete ptr; + ptr = next; + } +} + +tzdb_list::tzdb_list(tzdb_list&& x) NOEXCEPT + : head_{x.head_.exchange(nullptr)} +{ +} + +void +tzdb_list::push_front(tzdb* tzdb) NOEXCEPT +{ + tzdb->next = head_; + head_ = tzdb; +} + +tzdb_list::const_iterator +tzdb_list::erase_after(const_iterator p) NOEXCEPT +{ + auto t = p.p_->next; + p.p_->next = p.p_->next->next; + delete t; + return ++p; +} + +struct tzdb_list::undocumented_helper +{ + static void push_front(tzdb_list& db_list, tzdb* tzdb) NOEXCEPT + { + db_list.push_front(tzdb); + } +}; + +static +tzdb_list +create_tzdb() +{ + tzdb_list tz_db; + tzdb_list::undocumented_helper::push_front(tz_db, init_tzdb().release()); + return tz_db; +} + +tzdb_list& +get_tzdb_list() +{ + static tzdb_list tz_db = create_tzdb(); + return tz_db; +} + +static +std::string +parse3(std::istream& in) +{ + std::string r(3, ' '); + ws(in); + r[0] = static_cast(in.get()); + r[1] = static_cast(in.get()); + r[2] = static_cast(in.get()); + return r; +} + +static +unsigned +parse_month(std::istream& in) +{ + CONSTDATA char*const month_names[] = + {"Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; + auto s = parse3(in); + auto m = std::find(std::begin(month_names), std::end(month_names), s) - month_names; + if (m >= std::end(month_names) - std::begin(month_names)) + throw std::runtime_error("oops: bad month name: " + s); + return static_cast(++m); +} + +#if !USE_OS_TZDB + +#ifdef _WIN32 + +static +void +sort_zone_mappings(std::vector& mappings) +{ + std::sort(mappings.begin(), mappings.end(), + [](const date::detail::timezone_mapping& lhs, + const date::detail::timezone_mapping& rhs)->bool + { + auto other_result = lhs.other.compare(rhs.other); + if (other_result < 0) + return true; + else if (other_result == 0) + { + auto territory_result = lhs.territory.compare(rhs.territory); + if (territory_result < 0) + return true; + else if (territory_result == 0) + { + if (lhs.type < rhs.type) + return true; + } + } + return false; + }); +} + +static +bool +native_to_standard_timezone_name(const std::string& native_tz_name, + std::string& standard_tz_name) +{ + // TOOD! Need be a case insensitive compare? + if (native_tz_name == "UTC") + { + standard_tz_name = "Etc/UTC"; + return true; + } + standard_tz_name.clear(); + // TODO! we can improve on linear search. + const auto& mappings = date::get_tzdb().mappings; + for (const auto& tzm : mappings) + { + if (tzm.other == native_tz_name) + { + standard_tz_name = tzm.type; + return true; + } + } + return false; +} + +// Parse this XML file: +// https://raw.githubusercontent.com/unicode-org/cldr/master/common/supplemental/windowsZones.xml +// The parsing method is designed to be simple and quick. It is not overly +// forgiving of change but it should diagnose basic format issues. +// See timezone_mapping structure for more info. +static +std::vector +load_timezone_mappings_from_xml_file(const std::string& input_path) +{ + std::size_t line_num = 0; + std::vector mappings; + std::string line; + + std::ifstream is(input_path); + if (!is.is_open()) + { + // We don't emit file exceptions because that's an implementation detail. + std::string msg = "Error opening time zone mapping file \""; + msg += input_path; + msg += "\"."; + throw std::runtime_error(msg); + } + + auto error = [&input_path, &line_num](const char* info) + { + std::string msg = "Error loading time zone mapping file \""; + msg += input_path; + msg += "\" at line "; + msg += std::to_string(line_num); + msg += ": "; + msg += info; + throw std::runtime_error(msg); + }; + // [optional space]a="b" + auto read_attribute = [&line, &error] + (const char* name, std::string& value, std::size_t startPos) + ->std::size_t + { + value.clear(); + // Skip leading space before attribute name. + std::size_t spos = line.find_first_not_of(' ', startPos); + if (spos == std::string::npos) + spos = startPos; + // Assume everything up to next = is the attribute name + // and that an = will always delimit that. + std::size_t epos = line.find('=', spos); + if (epos == std::string::npos) + error("Expected \'=\' right after attribute name."); + std::size_t name_len = epos - spos; + // Expect the name we find matches the name we expect. + if (line.compare(spos, name_len, name) != 0) + { + std::string msg; + msg = "Expected attribute name \'"; + msg += name; + msg += "\' around position "; + msg += std::to_string(spos); + msg += " but found something else."; + error(msg.c_str()); + } + ++epos; // Skip the '=' that is after the attribute name. + spos = epos; + if (spos < line.length() && line[spos] == '\"') + ++spos; // Skip the quote that is before the attribute value. + else + { + std::string msg = "Expected '\"' to begin value of attribute \'"; + msg += name; + msg += "\'."; + error(msg.c_str()); + } + epos = line.find('\"', spos); + if (epos == std::string::npos) + { + std::string msg = "Expected '\"' to end value of attribute \'"; + msg += name; + msg += "\'."; + error(msg.c_str()); + } + // Extract everything in between the quotes. Note no escaping is done. + std::size_t value_len = epos - spos; + value.assign(line, spos, value_len); + ++epos; // Skip the quote that is after the attribute value; + return epos; + }; + + // Quick but not overly forgiving XML mapping file processing. + bool mapTimezonesOpenTagFound = false; + bool mapTimezonesCloseTagFound = false; + std::size_t mapZonePos = std::string::npos; + std::size_t mapTimezonesPos = std::string::npos; + CONSTDATA char mapTimeZonesOpeningTag[] = { ""); + mapTimezonesCloseTagFound = (mapTimezonesPos != std::string::npos); + if (!mapTimezonesCloseTagFound) + { + std::size_t commentPos = line.find(" " << x.target_; +} + +// leap_second + +leap_second::leap_second(const std::string& s, detail::undocumented) +{ + using namespace date; + std::istringstream in(s); + in.exceptions(std::ios::failbit | std::ios::badbit); + std::string word; + int y; + MonthDayTime date; + in >> word >> y >> date; + date_ = date.to_time_point(year(y)); +} + +static +bool +file_exists(const std::string& filename) +{ +#ifdef _WIN32 + return ::_access(filename.c_str(), 0) == 0; +#else + return ::access(filename.c_str(), F_OK) == 0; +#endif +} + +#if HAS_REMOTE_API + +// CURL tools + +namespace +{ + +struct curl_global_init_and_cleanup +{ + ~curl_global_init_and_cleanup() + { + ::curl_global_cleanup(); + } + curl_global_init_and_cleanup() + { + if (::curl_global_init(CURL_GLOBAL_DEFAULT) != 0) + throw std::runtime_error("CURL global initialization failed"); + } + curl_global_init_and_cleanup(curl_global_init_and_cleanup const&) = delete; + curl_global_init_and_cleanup& operator=(curl_global_init_and_cleanup const&) = delete; +}; + +struct curl_deleter +{ + void operator()(CURL* p) const + { + ::curl_easy_cleanup(p); + } +}; + +} // unnamed namespace + +static +std::unique_ptr +curl_init() +{ + static const curl_global_init_and_cleanup _{}; + return std::unique_ptr{::curl_easy_init()}; +} + +static +bool +download_to_string(const std::string& url, std::string& str) +{ + str.clear(); + auto curl = curl_init(); + if (!curl) + return false; + std::string version; + curl_easy_setopt(curl.get(), CURLOPT_USERAGENT, "curl"); + curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str()); + curl_write_callback write_cb = [](char* contents, std::size_t size, std::size_t nmemb, + void* userp) -> std::size_t + { + auto& userstr = *static_cast(userp); + auto realsize = size * nmemb; + userstr.append(contents, realsize); + return realsize; + }; + curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_cb); + curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &str); + curl_easy_setopt(curl.get(), CURLOPT_SSL_VERIFYPEER, false); + auto res = curl_easy_perform(curl.get()); + return (res == CURLE_OK); +} + +namespace +{ + enum class download_file_options { binary, text }; +} + +static +bool +download_to_file(const std::string& url, const std::string& local_filename, + download_file_options opts, char* error_buffer) +{ + auto curl = curl_init(); + if (!curl) + return false; + curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str()); + curl_easy_setopt(curl.get(), CURLOPT_SSL_VERIFYPEER, false); + if (error_buffer) + curl_easy_setopt(curl.get(), CURLOPT_ERRORBUFFER, error_buffer); + curl_write_callback write_cb = [](char* contents, std::size_t size, std::size_t nmemb, + void* userp) -> std::size_t + { + auto& of = *static_cast(userp); + auto realsize = size * nmemb; + of.write(contents, static_cast(realsize)); + return realsize; + }; + curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_cb); + decltype(curl_easy_perform(curl.get())) res; + { + std::ofstream of(local_filename, + opts == download_file_options::binary ? + std::ofstream::out | std::ofstream::binary : + std::ofstream::out); + of.exceptions(std::ios::badbit); + curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &of); + res = curl_easy_perform(curl.get()); + } + return res == CURLE_OK; +} + +std::string +remote_version() +{ + std::string version; + std::string str; + if (download_to_string("https://www.iana.org/time-zones", str)) + { + CONSTDATA char db[] = "/time-zones/releases/tzdata"; + CONSTDATA auto db_size = sizeof(db) - 1; + auto p = str.find(db, 0, db_size); + const int ver_str_len = 5; + if (p != std::string::npos && p + (db_size + ver_str_len) <= str.size()) + version = str.substr(p + db_size, ver_str_len); + } + return version; +} + + +// TODO! Using system() create a process and a console window. +// This is useful to see what errors may occur but is slow and distracting. +// Consider implementing this functionality more directly, such as +// using _mkdir and CreateProcess etc. +// But use the current means now as matches Unix implementations and while +// in proof of concept / testing phase. +// TODO! Use eventually. +static +bool +remove_folder_and_subfolders(const std::string& folder) +{ +# ifdef _WIN32 +# if USE_SHELL_API + // Delete the folder contents by deleting the folder. + std::string cmd = "rd /s /q \""; + cmd += folder; + cmd += '\"'; + return std::system(cmd.c_str()) == EXIT_SUCCESS; +# else // !USE_SHELL_API + // Create a buffer containing the path to delete. It must be terminated + // by two nuls. Who designs these API's... + std::vector from; + from.assign(folder.begin(), folder.end()); + from.push_back('\0'); + from.push_back('\0'); + SHFILEOPSTRUCT fo{}; // Zero initialize. + fo.wFunc = FO_DELETE; + fo.pFrom = from.data(); + fo.fFlags = FOF_NO_UI; + int ret = SHFileOperation(&fo); + if (ret == 0 && !fo.fAnyOperationsAborted) + return true; + return false; +# endif // !USE_SHELL_API +# else // !_WIN32 +# if USE_SHELL_API + return std::system(("rm -R " + folder).c_str()) == EXIT_SUCCESS; +# else // !USE_SHELL_API + struct dir_deleter { + dir_deleter() {} + void operator()(DIR* d) const + { + if (d != nullptr) + { + int result = closedir(d); + assert(result == 0); + } + } + }; + using closedir_ptr = std::unique_ptr; + + std::string filename; + struct stat statbuf; + std::size_t folder_len = folder.length(); + struct dirent* p = nullptr; + + closedir_ptr d(opendir(folder.c_str())); + bool r = d.get() != nullptr; + while (r && (p=readdir(d.get())) != nullptr) + { + if (strcmp(p->d_name, ".") == 0 || strcmp(p->d_name, "..") == 0) + continue; + + // + 2 for path delimiter and nul terminator. + std::size_t buf_len = folder_len + strlen(p->d_name) + 2; + filename.resize(buf_len); + std::size_t path_len = static_cast( + snprintf(&filename[0], buf_len, "%s/%s", folder.c_str(), p->d_name)); + assert(path_len == buf_len - 1); + filename.resize(path_len); + + if (stat(filename.c_str(), &statbuf) == 0) + r = S_ISDIR(statbuf.st_mode) + ? remove_folder_and_subfolders(filename) + : unlink(filename.c_str()) == 0; + } + d.reset(); + + if (r) + r = rmdir(folder.c_str()) == 0; + + return r; +# endif // !USE_SHELL_API +# endif // !_WIN32 +} + +static +bool +make_directory(const std::string& folder) +{ +# ifdef _WIN32 +# if USE_SHELL_API + // Re-create the folder. + std::string cmd = "mkdir \""; + cmd += folder; + cmd += '\"'; + return std::system(cmd.c_str()) == EXIT_SUCCESS; +# else // !USE_SHELL_API + return _mkdir(folder.c_str()) == 0; +# endif // !USE_SHELL_API +# else // !_WIN32 +# if USE_SHELL_API + return std::system(("mkdir -p " + folder).c_str()) == EXIT_SUCCESS; +# else // !USE_SHELL_API + return mkdir(folder.c_str(), 0777) == 0; +# endif // !USE_SHELL_API +# endif // !_WIN32 +} + +static +bool +delete_file(const std::string& file) +{ +# ifdef _WIN32 +# if USE_SHELL_API + std::string cmd = "del \""; + cmd += file; + cmd += '\"'; + return std::system(cmd.c_str()) == 0; +# else // !USE_SHELL_API + return _unlink(file.c_str()) == 0; +# endif // !USE_SHELL_API +# else // !_WIN32 +# if USE_SHELL_API + return std::system(("rm " + file).c_str()) == EXIT_SUCCESS; +# else // !USE_SHELL_API + return unlink(file.c_str()) == 0; +# endif // !USE_SHELL_API +# endif // !_WIN32 +} + +# ifdef _WIN32 + +static +bool +move_file(const std::string& from, const std::string& to) +{ +# if USE_SHELL_API + std::string cmd = "move \""; + cmd += from; + cmd += "\" \""; + cmd += to; + cmd += '\"'; + return std::system(cmd.c_str()) == EXIT_SUCCESS; +# else // !USE_SHELL_API + return !!::MoveFile(from.c_str(), to.c_str()); +# endif // !USE_SHELL_API +} + +// Usually something like "c:\Program Files". +static +std::string +get_program_folder() +{ + return get_known_folder(FOLDERID_ProgramFiles); +} + +// Note folder can and usually does contain spaces. +static +std::string +get_unzip_program() +{ + std::string path; + + // 7-Zip appears to note its location in the registry. + // If that doesn't work, fall through and take a guess, but it will likely be wrong. + HKEY hKey = nullptr; + if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\7-Zip", 0, KEY_READ, &hKey) == ERROR_SUCCESS) + { + char value_buffer[MAX_PATH + 1]; // fyi 260 at time of writing. + // in/out parameter. Documentation say that size is a count of bytes not chars. + DWORD size = sizeof(value_buffer) - sizeof(value_buffer[0]); + DWORD tzi_type = REG_SZ; + // Testing shows Path key value is "C:\Program Files\7-Zip\" i.e. always with trailing \. + bool got_value = (RegQueryValueExA(hKey, "Path", nullptr, &tzi_type, + reinterpret_cast(value_buffer), &size) == ERROR_SUCCESS); + RegCloseKey(hKey); // Close now incase of throw later. + if (got_value) + { + // Function does not guarantee to null terminate. + value_buffer[size / sizeof(value_buffer[0])] = '\0'; + path = value_buffer; + if (!path.empty()) + { + path += "7z.exe"; + return path; + } + } + } + path += get_program_folder(); + path += folder_delimiter; + path += "7-Zip\\7z.exe"; + return path; +} + +# if !USE_SHELL_API +static +int +run_program(const std::string& command) +{ + STARTUPINFO si{}; + si.cb = sizeof(si); + PROCESS_INFORMATION pi{}; + + // Allegedly CreateProcess overwrites the command line. Ugh. + std::string mutable_command(command); + if (CreateProcess(nullptr, &mutable_command[0], + nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)) + { + WaitForSingleObject(pi.hProcess, INFINITE); + DWORD exit_code; + bool got_exit_code = !!GetExitCodeProcess(pi.hProcess, &exit_code); + CloseHandle(pi.hProcess); + CloseHandle(pi.hThread); + // Not 100% sure about this still active thing is correct, + // but I'm going with it because I *think* WaitForSingleObject might + // return in some cases without INFINITE-ly waiting. + // But why/wouldn't GetExitCodeProcess return false in that case? + if (got_exit_code && exit_code != STILL_ACTIVE) + return static_cast(exit_code); + } + return EXIT_FAILURE; +} +# endif // !USE_SHELL_API + +static +std::string +get_download_tar_file(const std::string& version) +{ + auto file = get_install(); + file += folder_delimiter; + file += "tzdata"; + file += version; + file += ".tar"; + return file; +} + +static +bool +extract_gz_file(const std::string& version, const std::string& gz_file, + const std::string& dest_folder) +{ + auto unzip_prog = get_unzip_program(); + bool unzip_result = false; + // Use the unzip program to extract the tar file from the archive. + + // Aim to create a string like: + // "C:\Program Files\7-Zip\7z.exe" x "C:\Users\SomeUser\Downloads\tzdata2016d.tar.gz" + // -o"C:\Users\SomeUser\Downloads\tzdata" + std::string cmd; + cmd = '\"'; + cmd += unzip_prog; + cmd += "\" x \""; + cmd += gz_file; + cmd += "\" -o\""; + cmd += dest_folder; + cmd += '\"'; + +# if USE_SHELL_API + // When using shelling out with std::system() extra quotes are required around the + // whole command. It's weird but necessary it seems, see: + // http://stackoverflow.com/q/27975969/576911 + + cmd = "\"" + cmd + "\""; + if (std::system(cmd.c_str()) == EXIT_SUCCESS) + unzip_result = true; +# else // !USE_SHELL_API + if (run_program(cmd) == EXIT_SUCCESS) + unzip_result = true; +# endif // !USE_SHELL_API + if (unzip_result) + delete_file(gz_file); + + // Use the unzip program extract the data from the tar file that was + // just extracted from the archive. + auto tar_file = get_download_tar_file(version); + cmd = '\"'; + cmd += unzip_prog; + cmd += "\" x \""; + cmd += tar_file; + cmd += "\" -o\""; + cmd += get_install(); + cmd += '\"'; +# if USE_SHELL_API + cmd = "\"" + cmd + "\""; + if (std::system(cmd.c_str()) == EXIT_SUCCESS) + unzip_result = true; +# else // !USE_SHELL_API + if (run_program(cmd) == EXIT_SUCCESS) + unzip_result = true; +# endif // !USE_SHELL_API + + if (unzip_result) + delete_file(tar_file); + + return unzip_result; +} + +static +std::string +get_download_mapping_file(const std::string& version) +{ + auto file = get_install() + version + "windowsZones.xml"; + return file; +} + +# else // !_WIN32 + +# if !USE_SHELL_API +static +int +run_program(const char* prog, const char*const args[]) +{ + pid_t pid = fork(); + if (pid == -1) // Child failed to start. + return EXIT_FAILURE; + + if (pid != 0) + { + // We are in the parent. Child started. Wait for it. + pid_t ret; + int status; + while ((ret = waitpid(pid, &status, 0)) == -1) + { + if (errno != EINTR) + break; + } + if (ret != -1) + { + if (WIFEXITED(status)) + return WEXITSTATUS(status); + } + printf("Child issues!\n"); + + return EXIT_FAILURE; // Not sure what status of child is. + } + else // We are in the child process. Start the program the parent wants to run. + { + + if (execv(prog, const_cast(args)) == -1) // Does not return. + { + perror("unreachable 0\n"); + _Exit(127); + } + printf("unreachable 2\n"); + } + printf("unreachable 2\n"); + // Unreachable. + assert(false); + exit(EXIT_FAILURE); + return EXIT_FAILURE; +} +# endif // !USE_SHELL_API + +static +bool +extract_gz_file(const std::string&, const std::string& gz_file, const std::string&) +{ +# if USE_SHELL_API + bool unzipped = std::system(("tar -xzf " + gz_file + " -C " + get_install()).c_str()) == EXIT_SUCCESS; +# else // !USE_SHELL_API + const char prog[] = {"/usr/bin/tar"}; + const char*const args[] = + { + prog, "-xzf", gz_file.c_str(), "-C", get_install().c_str(), nullptr + }; + bool unzipped = (run_program(prog, args) == EXIT_SUCCESS); +# endif // !USE_SHELL_API + if (unzipped) + { + delete_file(gz_file); + return true; + } + return false; +} + +# endif // !_WIN32 + +bool +remote_download(const std::string& version, char* error_buffer) +{ + assert(!version.empty()); + +# ifdef _WIN32 + // Download folder should be always available for Windows +# else // !_WIN32 + // Create download folder if it does not exist on UNIX system + auto download_folder = get_install(); + if (!file_exists(download_folder)) + { + if (!make_directory(download_folder)) + return false; + } +# endif // _WIN32 + + auto url = "https://data.iana.org/time-zones/releases/tzdata" + version + + ".tar.gz"; + bool result = download_to_file(url, get_download_gz_file(version), + download_file_options::binary, error_buffer); +# ifdef _WIN32 + if (result) + { + auto mapping_file = get_download_mapping_file(version); + result = download_to_file( + "https://raw.githubusercontent.com/unicode-org/cldr/master/" + "common/supplemental/windowsZones.xml", + mapping_file, download_file_options::text, error_buffer); + } +# endif // _WIN32 + return result; +} + +bool +remote_install(const std::string& version) +{ + auto success = false; + assert(!version.empty()); + + std::string install = get_install(); + auto gz_file = get_download_gz_file(version); + if (file_exists(gz_file)) + { + if (file_exists(install)) + remove_folder_and_subfolders(install); + if (make_directory(install)) + { + if (extract_gz_file(version, gz_file, install)) + success = true; +# ifdef _WIN32 + auto mapping_file_source = get_download_mapping_file(version); + auto mapping_file_dest = get_install(); + mapping_file_dest += folder_delimiter; + mapping_file_dest += "windowsZones.xml"; + if (!move_file(mapping_file_source, mapping_file_dest)) + success = false; +# endif // _WIN32 + } + } + return success; +} + +#endif // HAS_REMOTE_API + +static +std::string +get_version(const std::string& path) +{ + std::string version; + std::ifstream infile(path + "version"); + if (infile.is_open()) + { + infile >> version; + if (!infile.fail()) + return version; + } + else + { + infile.open(path + "NEWS"); + while (infile) + { + infile >> version; + if (version == "Release") + { + infile >> version; + return version; + } + } + } + throw std::runtime_error("Unable to get Timezone database version from " + path); +} + +static +std::unique_ptr +init_tzdb() +{ + using namespace date; + const std::string install = get_install(); + const std::string path = install + folder_delimiter; + std::string line; + bool continue_zone = false; + std::unique_ptr db(new tzdb); + +#if AUTO_DOWNLOAD + if (!file_exists(install)) + { + auto rv = remote_version(); + if (!rv.empty() && remote_download(rv)) + { + if (!remote_install(rv)) + { + std::string msg = "Timezone database version \""; + msg += rv; + msg += "\" did not install correctly to \""; + msg += install; + msg += "\""; + throw std::runtime_error(msg); + } + } + if (!file_exists(install)) + { + std::string msg = "Timezone database not found at \""; + msg += install; + msg += "\""; + throw std::runtime_error(msg); + } + db->version = get_version(path); + } + else + { + db->version = get_version(path); + auto rv = remote_version(); + if (!rv.empty() && db->version != rv) + { + if (remote_download(rv)) + { + remote_install(rv); + db->version = get_version(path); + } + } + } +#else // !AUTO_DOWNLOAD + if (!file_exists(install)) + { + std::string msg = "Timezone database not found at \""; + msg += install; + msg += "\""; + throw std::runtime_error(msg); + } + db->version = get_version(path); +#endif // !AUTO_DOWNLOAD + + CONSTDATA char*const files[] = + { + "africa", "antarctica", "asia", "australasia", "backward", "etcetera", "europe", + "pacificnew", "northamerica", "southamerica", "systemv", "leapseconds" + }; + + for (const auto& filename : files) + { + std::ifstream infile(path + filename); + while (infile) + { + std::getline(infile, line); + if (!line.empty() && line[0] != '#') + { + std::istringstream in(line); + std::string word; + in >> word; + if (word == "Rule") + { + db->rules.push_back(Rule(line)); + continue_zone = false; + } + else if (word == "Link") + { + db->links.push_back(time_zone_link(line)); + continue_zone = false; + } + else if (word == "Leap") + { + db->leap_seconds.push_back(leap_second(line, detail::undocumented{})); + continue_zone = false; + } + else if (word == "Zone") + { + db->zones.push_back(time_zone(line, detail::undocumented{})); + continue_zone = true; + } + else if (line[0] == '\t' && continue_zone) + { + db->zones.back().add(line); + } + else + { + std::cerr << line << '\n'; + } + } + } + } + std::sort(db->rules.begin(), db->rules.end()); + Rule::split_overlaps(db->rules); + std::sort(db->zones.begin(), db->zones.end()); + db->zones.shrink_to_fit(); + std::sort(db->links.begin(), db->links.end()); + db->links.shrink_to_fit(); + std::sort(db->leap_seconds.begin(), db->leap_seconds.end()); + db->leap_seconds.shrink_to_fit(); + +#ifdef _WIN32 + std::string mapping_file = get_install() + folder_delimiter + "windowsZones.xml"; + db->mappings = load_timezone_mappings_from_xml_file(mapping_file); + sort_zone_mappings(db->mappings); +#endif // _WIN32 + + return db; +} + +const tzdb& +reload_tzdb() +{ +#if AUTO_DOWNLOAD + auto const& v = get_tzdb_list().front().version; + if (!v.empty() && v == remote_version()) + return get_tzdb_list().front(); +#endif // AUTO_DOWNLOAD + tzdb_list::undocumented_helper::push_front(get_tzdb_list(), init_tzdb().release()); + return get_tzdb_list().front(); +} + +#endif // !USE_OS_TZDB + +const tzdb& +get_tzdb() +{ + return get_tzdb_list().front(); +} + +const time_zone* +#if HAS_STRING_VIEW +tzdb::locate_zone(std::string_view tz_name) const +#else +tzdb::locate_zone(const std::string& tz_name) const +#endif +{ + auto zi = std::lower_bound(zones.begin(), zones.end(), tz_name, +#if HAS_STRING_VIEW + [](const time_zone& z, const std::string_view& nm) +#else + [](const time_zone& z, const std::string& nm) +#endif + { + return z.name() < nm; + }); + if (zi == zones.end() || zi->name() != tz_name) + { +#if !USE_OS_TZDB + auto li = std::lower_bound(links.begin(), links.end(), tz_name, +#if HAS_STRING_VIEW + [](const time_zone_link& z, const std::string_view& nm) +#else + [](const time_zone_link& z, const std::string& nm) +#endif + { + return z.name() < nm; + }); + if (li != links.end() && li->name() == tz_name) + { + zi = std::lower_bound(zones.begin(), zones.end(), li->target(), + [](const time_zone& z, const std::string& nm) + { + return z.name() < nm; + }); + if (zi != zones.end() && zi->name() == li->target()) + return &*zi; + } +#endif // !USE_OS_TZDB + throw std::runtime_error(std::string(tz_name) + " not found in timezone database"); + } + return &*zi; +} + +const time_zone* +#if HAS_STRING_VIEW +locate_zone(std::string_view tz_name) +#else +locate_zone(const std::string& tz_name) +#endif +{ + return get_tzdb().locate_zone(tz_name); +} + +#if USE_OS_TZDB + +std::ostream& +operator<<(std::ostream& os, const tzdb& db) +{ + os << "Version: " << db.version << "\n\n"; + for (const auto& x : db.zones) + os << x << '\n'; + os << '\n'; + for (const auto& x : db.leap_seconds) + os << x << '\n'; + return os; +} + +#else // !USE_OS_TZDB + +std::ostream& +operator<<(std::ostream& os, const tzdb& db) +{ + os << "Version: " << db.version << '\n'; + std::string title("--------------------------------------------" + "--------------------------------------------\n" + "Name ""Start Y ""End Y " + "Beginning ""Offset " + "Designator\n" + "--------------------------------------------" + "--------------------------------------------\n"); + int count = 0; + for (const auto& x : db.rules) + { + if (count++ % 50 == 0) + os << title; + os << x << '\n'; + } + os << '\n'; + title = std::string("---------------------------------------------------------" + "--------------------------------------------------------\n" + "Name ""Offset " + "Rule ""Abrev ""Until\n" + "---------------------------------------------------------" + "--------------------------------------------------------\n"); + count = 0; + for (const auto& x : db.zones) + { + if (count++ % 10 == 0) + os << title; + os << x << '\n'; + } + os << '\n'; + title = std::string("---------------------------------------------------------" + "--------------------------------------------------------\n" + "Alias ""To\n" + "---------------------------------------------------------" + "--------------------------------------------------------\n"); + count = 0; + for (const auto& x : db.links) + { + if (count++ % 45 == 0) + os << title; + os << x << '\n'; + } + os << '\n'; + title = std::string("---------------------------------------------------------" + "--------------------------------------------------------\n" + "Leap second on\n" + "---------------------------------------------------------" + "--------------------------------------------------------\n"); + os << title; + for (const auto& x : db.leap_seconds) + os << x << '\n'; + return os; +} + +#endif // !USE_OS_TZDB + +// ----------------------- + +#ifdef _WIN32 + +static +std::string +getTimeZoneKeyName() +{ + DYNAMIC_TIME_ZONE_INFORMATION dtzi{}; + auto result = GetDynamicTimeZoneInformation(&dtzi); + if (result == TIME_ZONE_ID_INVALID) + throw std::runtime_error("current_zone(): GetDynamicTimeZoneInformation()" + " reported TIME_ZONE_ID_INVALID."); + auto wlen = wcslen(dtzi.TimeZoneKeyName); + char buf[128] = {}; + assert(sizeof(buf) >= wlen+1); + wcstombs(buf, dtzi.TimeZoneKeyName, wlen); + if (strcmp(buf, "Coordinated Universal Time") == 0) + return "UTC"; + return buf; +} + +const time_zone* +tzdb::current_zone() const +{ + std::string win_tzid = getTimeZoneKeyName(); + std::string standard_tzid; + if (!native_to_standard_timezone_name(win_tzid, standard_tzid)) + { + std::string msg; + msg = "current_zone() failed: A mapping from the Windows Time Zone id \""; + msg += win_tzid; + msg += "\" was not found in the time zone mapping database."; + throw std::runtime_error(msg); + } + return locate_zone(standard_tzid); +} + +#else // !_WIN32 + +#if HAS_STRING_VIEW + +static +std::string_view +extract_tz_name(char const* rp) +{ + using namespace std; + string_view result = rp; + CONSTDATA string_view zoneinfo = "zoneinfo"; + size_t pos = result.rfind(zoneinfo); + if (pos == result.npos) + throw runtime_error( + "current_zone() failed to find \"zoneinfo\" in " + string(result)); + pos = result.find('/', pos); + result.remove_prefix(pos + 1); + return result; +} + +#else // !HAS_STRING_VIEW + +static +std::string +extract_tz_name(char const* rp) +{ + using namespace std; + string result = rp; + CONSTDATA char zoneinfo[] = "zoneinfo"; + size_t pos = result.rfind(zoneinfo); + if (pos == result.npos) + throw runtime_error( + "current_zone() failed to find \"zoneinfo\" in " + result); + pos = result.find('/', pos); + result.erase(0, pos + 1); + return result; +} + +#endif // HAS_STRING_VIEW + +static +bool +sniff_realpath(const char* timezone) +{ + using namespace std; + char rp[PATH_MAX+1] = {}; + if (realpath(timezone, rp) == nullptr) + throw system_error(errno, system_category(), "realpath() failed"); + auto result = extract_tz_name(rp); + return result != "posixrules"; +} + +const time_zone* +tzdb::current_zone() const +{ + // On some OS's a file called /etc/localtime may + // exist and it may be either a real file + // containing time zone details or a symlink to such a file. + // On MacOS and BSD Unix if this file is a symlink it + // might resolve to a path like this: + // "/usr/share/zoneinfo/America/Los_Angeles" + // If it does, we try to determine the current + // timezone from the remainder of the path by removing the prefix + // and hoping the rest resolves to a valid timezone. + // It may not always work though. If it doesn't then an + // exception will be thrown by local_timezone. + // The path may also take a relative form: + // "../usr/share/zoneinfo/America/Los_Angeles". + { + struct stat sb; + CONSTDATA auto timezone = "/etc/localtime"; + if (lstat(timezone, &sb) == 0 && S_ISLNK(sb.st_mode) && sb.st_size > 0) + { + using namespace std; + static const bool use_realpath = sniff_realpath(timezone); + char rp[PATH_MAX+1] = {}; + if (use_realpath) + { + if (realpath(timezone, rp) == nullptr) + throw system_error(errno, system_category(), "realpath() failed"); + } + else + { + if (readlink(timezone, rp, sizeof(rp)-1) <= 0) + throw system_error(errno, system_category(), "readlink() failed"); + } + return locate_zone(extract_tz_name(rp)); + } + } + // On embedded systems e.g. buildroot with uclibc the timezone is linked + // into /etc/TZ which is a symlink to path like this: + // "/usr/share/zoneinfo/uclibc/America/Los_Angeles" + // If it does, we try to determine the current + // timezone from the remainder of the path by removing the prefix + // and hoping the rest resolves to valid timezone. + // It may not always work though. If it doesn't then an + // exception will be thrown by local_timezone. + // The path may also take a relative form: + // "../usr/share/zoneinfo/uclibc/America/Los_Angeles". + { + struct stat sb; + CONSTDATA auto timezone = "/etc/TZ"; + if (lstat(timezone, &sb) == 0 && S_ISLNK(sb.st_mode) && sb.st_size > 0) { + using namespace std; + string result; + char rp[PATH_MAX+1] = {}; + if (readlink(timezone, rp, sizeof(rp)-1) > 0) + result = string(rp); + else + throw system_error(errno, system_category(), "readlink() failed"); + + const size_t pos = result.find(get_tz_dir()); + if (pos != result.npos) + result.erase(0, get_tz_dir().size() + 1 + pos); + return locate_zone(result); + } + } + { + // On some versions of some linux distro's (e.g. Ubuntu), + // the current timezone might be in the first line of + // the /etc/timezone file. + std::ifstream timezone_file("/etc/timezone"); + if (timezone_file.is_open()) + { + std::string result; + std::getline(timezone_file, result); + if (!result.empty()) + return locate_zone(result); + } + // Fall through to try other means. + } + { + // On some versions of some bsd distro's (e.g. FreeBSD), + // the current timezone might be in the first line of + // the /var/db/zoneinfo file. + std::ifstream timezone_file("/var/db/zoneinfo"); + if (timezone_file.is_open()) + { + std::string result; + std::getline(timezone_file, result); + if (!result.empty()) + return locate_zone(result); + } + // Fall through to try other means. + } + { + // On some versions of some bsd distro's (e.g. iOS), + // it is not possible to use file based approach, + // we switch to system API, calling functions in + // CoreFoundation framework. +#if TARGET_OS_IPHONE + std::string result = date::iOSUtils::get_current_timezone(); + if (!result.empty()) + return locate_zone(result); +#endif + // Fall through to try other means. + } + { + // On some versions of some linux distro's (e.g. Red Hat), + // the current timezone might be in the first line of + // the /etc/sysconfig/clock file as: + // ZONE="US/Eastern" + std::ifstream timezone_file("/etc/sysconfig/clock"); + std::string result; + while (timezone_file) + { + std::getline(timezone_file, result); + auto p = result.find("ZONE=\""); + if (p != std::string::npos) + { + result.erase(p, p+6); + result.erase(result.rfind('"')); + return locate_zone(result); + } + } + // Fall through to try other means. + } + throw std::runtime_error("Could not get current timezone"); +} + +#endif // !_WIN32 + +const time_zone* +current_zone() +{ + return get_tzdb().current_zone(); +} + +} // namespace date + +#if defined(__GNUC__) && __GNUC__ < 5 +# pragma GCC diagnostic pop +#endif diff --git a/third_party/date/test/clock_cast_test/constexpr.pass.cpp b/third_party/date/test/clock_cast_test/constexpr.pass.cpp new file mode 100644 index 0000000..5fdb758 --- /dev/null +++ b/third_party/date/test/clock_cast_test/constexpr.pass.cpp @@ -0,0 +1,75 @@ +// The MIT License (MIT) +// +// Copyright (c) 2019 nanoric +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "tz.h" +#include +#include + +struct const_clock { + using duration = + typename std::common_type::type; + using rep = duration::rep; + using period = duration::period; + using time_point = std::chrono::time_point; + + static constexpr date::sys_days epoch { date::days { 1000 } }; + + template + static std::chrono::time_point::type> + CONSTCD11 to_sys(std::chrono::time_point const& tp) + { + return epoch + tp.time_since_epoch(); + } + + template + static std::chrono::time_point::type> + CONSTCD11 from_sys( + std::chrono::time_point const& + tp) + { + using res = std::chrono::time_point::type>; + return res(tp - epoch); + } +}; + +int main() +{ + using namespace date; + using namespace std::chrono; + using const_days = time_point; + + CONSTCD14 sys_days sys { days { 1024 } }; + static_assert(sys.time_since_epoch().count() == 1024, ""); + + CONSTCD14 const_days c {clock_cast(sys)}; + CONSTCD14 sys_days sys2 {clock_cast(c)}; + CONSTCD14 sys_days sys3 { clock_cast(const_days(days(48))) }; +#if __cplusplus >= 201402L + static_assert(c.time_since_epoch().count() == 24, ""); + static_assert(sys2.time_since_epoch().count() == 1024, ""); + static_assert(sys3.time_since_epoch().count() == 1048, ""); +#endif +} diff --git a/third_party/date/test/clock_cast_test/custom_clock.pass.cpp b/third_party/date/test/clock_cast_test/custom_clock.pass.cpp new file mode 100644 index 0000000..1c64a5d --- /dev/null +++ b/third_party/date/test/clock_cast_test/custom_clock.pass.cpp @@ -0,0 +1,213 @@ +// The MIT License (MIT) +// +// Copyright (c) 2017, 2018 Tomasz KamiÅ„ski +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "tz.h" +#include +#include + +//used to count number of conversion +int conversions = 0; + +//to/from impl +struct mil_clock +{ + using duration = typename std::common_type::type; + using rep = duration::rep; + using period = duration::period; + using time_point = std::chrono::time_point; + + static constexpr date::sys_days epoch{date::days{1000}}; + + template + static + std::chrono::time_point::type> + to_sys(std::chrono::time_point const& tp) + { + ++conversions; + return epoch + tp.time_since_epoch(); + } + + template + static + std::chrono::time_point::type> + from_sys(std::chrono::time_point const& tp) + { + ++conversions; + using res = std::chrono::time_point::type>; + return res(tp - epoch); + } + + template + static + std::chrono::time_point::type> + to_local(std::chrono::time_point const& tp) + { + return date::clock_cast(to_sys(tp)); + } + + template + static + std::chrono::time_point::type> + from_local(std::chrono::time_point const& tp) + { + return from_sys(date::clock_cast(tp)); + } + + + static time_point now() + { + return from_sys(std::chrono::system_clock::now()); + } +}; + + +date::sys_days const mil_clock::epoch; + +// traits example +struct s2s_clock +{ + using duration = std::chrono::system_clock::duration; + using rep = duration::rep; + using period = duration::period; + using time_point = std::chrono::time_point; + + template + static + std::chrono::time_point + to_sys(std::chrono::time_point const& tp) + { + ++conversions; + return std::chrono::time_point(tp.time_since_epoch()); + } + + template + static + std::chrono::time_point + from_sys(std::chrono::time_point const& tp) + { + ++conversions; + return std::chrono::time_point(tp.time_since_epoch()); + } + + static time_point now() + { + return from_sys(std::chrono::system_clock::now()); + } +}; + +namespace date +{ + template<> + struct clock_time_conversion + { + template + std::chrono::time_point::type> + operator()(std::chrono::time_point const& tp) + { + ++conversions; + using res = std::chrono::time_point::type>; + return res(tp.time_since_epoch() - mil_clock::epoch.time_since_epoch()); + } + }; +} + +int +main() +{ + using namespace date; + using sys_clock = std::chrono::system_clock; + + // self + { + sys_days st(1997_y/dec/12); + auto mt = mil_clock::from_sys(st); + + assert(clock_cast(mt) == mt); + } + + // mil <-> local + { + local_days lt(1997_y/dec/12); + auto mt = mil_clock::from_local(lt); + + assert(clock_cast(lt) == mt); + assert(clock_cast(mt) == lt); + } + + // mil <-> sys + { + sys_days st(1997_y/dec/12); + auto mt = mil_clock::from_sys(st); + + assert(clock_cast(st) == mt); + assert(clock_cast(mt) == st); + } + + // mil <-> utc + { + sys_days st(1997_y/dec/12); + auto mt = mil_clock::from_sys(st); + auto ut = utc_clock::from_sys(st); + + assert(clock_cast(ut) == mt); + assert(clock_cast(mt) == ut); + } + + // mil <-> tai + { + sys_days st(1997_y/dec/12); + auto mt = mil_clock::from_sys(st); + auto ut = utc_clock::from_sys(st); + auto tt = tai_clock::from_utc(ut); + + assert(clock_cast(mt) == tt); + assert(clock_cast(tt) == mt); + } + + // mil <-> gps + { + sys_days st(1997_y/dec/12); + auto mt = mil_clock::from_sys(st); + auto ut = utc_clock::from_sys(st); + auto gt = gps_clock::from_utc(ut); + + assert(clock_cast(mt) == gt); + assert(clock_cast(gt) == mt); + } + + // s2s -> mil + { + sys_days st(1997_y/dec/12); + auto mt = mil_clock::from_sys(st); + auto s2t = s2s_clock::from_sys(st); + + //direct trait conversion + conversions = 0; + assert(clock_cast(s2t) == mt); + assert(conversions == 1); + + //uses sys_clock + conversions = 0; + assert(clock_cast(mt) == s2t); + assert(conversions == 2); + } +} diff --git a/third_party/date/test/clock_cast_test/deprecated.pass.cpp b/third_party/date/test/clock_cast_test/deprecated.pass.cpp new file mode 100644 index 0000000..74d246e --- /dev/null +++ b/third_party/date/test/clock_cast_test/deprecated.pass.cpp @@ -0,0 +1,90 @@ +// The MIT License (MIT) +// +// Copyright (c) 2017 Tomasz KamiÅ„ski +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "tz.h" +#include + +int +main() +{ + using namespace date; + + // sys <-> utc + { + sys_days st(1997_y/dec/12); + auto ut = utc_clock::from_sys(st); + + assert(to_utc_time(st) == ut); + assert(to_sys_time(ut) == st); + } + + // tai <-> utc + { + sys_days st(1997_y/dec/12); + auto ut = utc_clock::from_sys(st); + auto tt = tai_clock::from_utc(ut); + + assert(to_tai_time(ut) == tt); + assert(to_utc_time(tt) == ut); + } + + // tai <-> sys + { + sys_days st(1997_y/dec/12); + auto ut = utc_clock::from_sys(st); + auto tt = tai_clock::from_utc(ut); + + assert(to_tai_time(st) == tt); + assert(to_sys_time(tt) == st); + } + + // gps <-> utc + { + sys_days st(1997_y/dec/12); + auto ut = utc_clock::from_sys(st); + auto gt = gps_clock::from_utc(ut); + + assert(to_gps_time(ut) == gt); + assert(to_utc_time(gt) == ut); + } + + // gps <-> sys + { + sys_days st(1997_y/dec/12); + auto ut = utc_clock::from_sys(st); + auto gt = gps_clock::from_utc(ut); + + assert(to_gps_time(st) == gt); + assert(to_sys_time(gt) == st); + } + + // tai <-> gps + { + sys_days st(1997_y/dec/12); + auto ut = utc_clock::from_sys(st); + auto tt = tai_clock::from_utc(ut); + auto gt = gps_clock::from_utc(ut); + + assert(to_gps_time(tt) == gt); + assert(to_tai_time(gt) == tt); + } +} diff --git a/third_party/date/test/clock_cast_test/local_t.pass.cpp b/third_party/date/test/clock_cast_test/local_t.pass.cpp new file mode 100644 index 0000000..c80459d --- /dev/null +++ b/third_party/date/test/clock_cast_test/local_t.pass.cpp @@ -0,0 +1,132 @@ +// The MIT License (MIT) +// +// Copyright (c) 2018 Tomasz KamiÅ„ski +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include +#include "date/tz.h" + +int +main() +{ + using namespace date; + using namespace std::chrono; + + // self + { + auto ls = local_days{1970_y/January/1_d}; + assert(clock_cast(ls) == ls); + } + + /// sys epoch + { + auto ls = local_days{1970_y/January/1_d}; + auto st = clock_cast(ls); + assert(clock_cast(st) == ls); + assert(st.time_since_epoch() == seconds(0)); + } + + /// sys 2000 case + { + auto ls = local_days{2000_y/January/1_d}; + auto st = clock_cast(ls); + assert(clock_cast(st) == ls); + assert(st.time_since_epoch() == seconds(946684800)); + } + + /// utc epoch + { + auto lu = local_days{1970_y/January/1_d}; + auto ut = clock_cast(lu); + assert(clock_cast(ut) == lu); + assert(ut.time_since_epoch() == seconds(0)); + } + + // utc leap second + { + auto lu = local_days{2015_y/July/1_d} - milliseconds(1); + auto ut = clock_cast(lu) + milliseconds(50); //into leap second + + assert(clock_cast(ut) == lu); + } + + /// utc paper example + { + auto lu = local_days{2000_y/January/1_d}; + auto ut = clock_cast(lu); + assert(clock_cast(ut) == lu); + assert(ut.time_since_epoch() == seconds(946684822)); + } + + /// tai epoch + { + auto lt = local_days{1958_y/January/1_d}; + auto tt = clock_cast(lt); + assert(clock_cast(tt) == lt); + assert(tt.time_since_epoch() == seconds(0)); + + auto lu = local_days{1958_y/January/1_d} - seconds(10); + auto ut = clock_cast(lu); + assert(clock_cast(ut) == tt); + } + + // tai paper example + { + auto lt = local_days{2000_y/January/1_d} + seconds(32); + auto tt = clock_cast(lt); + assert(clock_cast(tt) == lt); + + auto lu = local_days{2000_y/January/1_d}; + auto ut = clock_cast(lu); + assert(clock_cast(ut) == tt); + } + + /// gps epoch + { + auto lg = local_days{1980_y/January/Sunday[1]}; + auto gt = clock_cast(lg); + assert(clock_cast(gt) == lg); + assert(gt.time_since_epoch() == seconds(0)); + + auto lu = local_days{1980_y/January/Sunday[1]}; + auto ut = clock_cast(lu); + assert(clock_cast(ut) == gt); + + auto lt = local_days{1980_y/January/Sunday[1]} + seconds(19); + auto tt = clock_cast(lt); + assert(clock_cast(tt) == gt); + } + + // gps 2000 example + { + auto lg = local_days{2000_y/January/1_d}; + auto gt = clock_cast(lg); + assert(clock_cast(gt) == lg); + + auto lu = local_days{2000_y/January/1_d} - seconds(13); + auto ut = clock_cast(lu); + assert(clock_cast(ut) == gt); + + auto lt = local_days{2000_y/January/1_d} + seconds(19); + auto tt = clock_cast(lt); + assert(clock_cast(tt) == gt); + } + +} diff --git a/third_party/date/test/clock_cast_test/noncastable.pass.cpp b/third_party/date/test/clock_cast_test/noncastable.pass.cpp new file mode 100644 index 0000000..373f223 --- /dev/null +++ b/third_party/date/test/clock_cast_test/noncastable.pass.cpp @@ -0,0 +1,251 @@ +// The MIT License (MIT) +// +// Copyright (c) 2017, 2018 Tomasz KamiÅ„ski +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "tz.h" +#include +#include + +template +struct is_clock_castable + : std::false_type +{}; + +template +struct is_clock_castable(typename SourceClock::time_point()), void())> + : std::true_type +{}; + + +//Clock based on steady clock, not related to wall time (sys_clock/utc_clock) +struct steady_based_clock +{ + using duration = std::chrono::steady_clock::duration; + using rep = duration::rep; + using period = duration::period; + using time_point = std::chrono::time_point; + + static time_point now() + { + return time_point(std::chrono::steady_clock::now().time_since_epoch()); + } +}; + +//Traits that allow conversion between steady_clock and steady_based clock +//Does not use wall-time clocks as rally (sys/utc) +namespace date +{ + template<> + struct clock_time_conversion + { + template + std::chrono::time_point + operator()(std::chrono::time_point const& tp) const + { + using res = std::chrono::time_point; + return res(tp.time_since_epoch()); + } + }; + + template<> + struct clock_time_conversion + { + template + std::chrono::time_point + operator()(std::chrono::time_point const& tp) const + { + using res = std::chrono::time_point; + return res(tp.time_since_epoch()); + } + }; +} + +//Ambigous clocks both providing to/from_sys and to/from_utc +//They are mock_ups just returning zero time_point +struct amb1_clock +{ + using duration = std::chrono::seconds; + using rep = duration::rep; + using period = duration::period; + using time_point = std::chrono::time_point; + + static time_point now() + { + return {}; + } + + template + static + std::chrono::time_point + to_sys(std::chrono::time_point const&) + { + return {}; + } + + template + static + std::chrono::time_point + from_sys(std::chrono::time_point const&) + { + return {}; + } + + template + static + std::chrono::time_point + to_utc(std::chrono::time_point const&) + { + return {}; + } + + template + static + std::chrono::time_point + from_utc(std::chrono::time_point const&) + { + return {}; + } +}; + +struct amb2_clock +{ + using duration = std::chrono::seconds; + using rep = duration::rep; + using period = duration::period; + using time_point = std::chrono::time_point; + + static time_point now() + { + return {}; + } + + template + static + std::chrono::time_point + to_sys(std::chrono::time_point const&) + { + return {}; + } + + template + static + std::chrono::time_point + from_sys(std::chrono::time_point const&) + { + return {}; + } + + template + static + std::chrono::time_point + to_utc(std::chrono::time_point const&) + { + return {}; + } + + template + static + std::chrono::time_point + from_utc(std::chrono::time_point const&) + { + return {}; + } +}; + +namespace date +{ + //Disambiguates that sys_clock is preffered + template<> + struct clock_time_conversion + { + template + std::chrono::time_point + operator()(std::chrono::time_point const& tp) const + { + return amb1_clock::from_sys(amb2_clock::to_sys(tp)); + } + }; +} + +int +main() +{ + using namespace date; + using namespace std::chrono; + using sys_clock = std::chrono::system_clock; + + //steady_clock (must be different that sys_clock) + static_assert(is_clock_castable::value, "steady_clock -> steady_clock"); + static_assert(!is_clock_castable::value, "steady_clock -> local_t"); + static_assert(!is_clock_castable::value, "local_t -> steady_clock"); + static_assert(!is_clock_castable::value, "steady_clock -> sys_clock"); + static_assert(!is_clock_castable::value, "sys_clock -> steady_clock"); + static_assert(!is_clock_castable::value, "steady_clock -> utc_clock"); + static_assert(!is_clock_castable::value, "utc_clock -> steady_clock"); + static_assert(!is_clock_castable::value, "steady_clock -> tai_clock"); + static_assert(!is_clock_castable::value, "tai_clock -> steady_clock"); + + //steady_based_clock (unrelated to sys_clock and utc_clocks) + static_assert(is_clock_castable::value, "steady_based_clock -> steady_based_clock"); + static_assert(!is_clock_castable::value, "steady_based_clock -> local_t"); + static_assert(!is_clock_castable::value, "local_t -> steady_based_clock"); + static_assert(!is_clock_castable::value, "steady_based_clock -> sys_clock"); + static_assert(!is_clock_castable::value, "sys_clock -> steady_based_clock"); + static_assert(!is_clock_castable::value, "steady_based_clock -> utc_clock"); + static_assert(!is_clock_castable::value, "utc_clock -> steady_based_clock"); + static_assert(!is_clock_castable::value, "steady_based_clock -> tai_clock"); + static_assert(!is_clock_castable::value, "tai_clock -> steady_based_clock"); + + //steady_based <-> steady_clock + { + auto s1 = steady_clock::time_point(steady_clock::duration(200)); + auto s2 = steady_based_clock::time_point(steady_based_clock::duration(200)); + + assert(clock_cast(s1) == s2); + assert(clock_cast(s2) == s1); + } + + //ambX <-> sys/utc works as one rally can be used in each case, or one lead to quicker conversione + static_assert(is_clock_castable::value, "amb1_clock -> amb1_clock"); + static_assert(is_clock_castable::value, "amb1_clock -> sys_clock"); + static_assert(is_clock_castable::value, "sys_clock -> amb1_clock"); + static_assert(is_clock_castable::value, "amb1_clock -> utc_clock"); + static_assert(is_clock_castable::value, "utc_clock -> amb1_clock"); + static_assert(is_clock_castable::value, "amb1_clock -> tai_clock"); + static_assert(is_clock_castable::value, "tai_clock -> amb1_clock"); + static_assert(is_clock_castable::value, "amb1_clock -> tai_clock"); + static_assert(is_clock_castable::value, "gps_clock -> amb1_clock"); + static_assert(is_clock_castable::value, "amb2_clock -> amb2_clock"); + static_assert(is_clock_castable::value, "amb2_clock -> sys_clock"); + static_assert(is_clock_castable::value, "sys_clock -> amb2_clock"); + static_assert(is_clock_castable::value, "amb2_clock -> utc_clock"); + static_assert(is_clock_castable::value, "utc_clock -> amb2_clock"); + static_assert(is_clock_castable::value, "amb2_clock -> tai_clock"); + static_assert(is_clock_castable::value, "tai_clock -> amb2_clock"); + static_assert(is_clock_castable::value, "amb2_clock -> tai_clock"); + static_assert(is_clock_castable::value, "gps_clock -> amb2_clock"); + + //amb1 -> amb2: ambigous because can either go trough sys_clock or utc_clock + static_assert(!is_clock_castable::value, "amb1_clock -> amb2_clock"); + + //amb2 -> amb1: disambiguated via trait specialization + static_assert(is_clock_castable::value, "amb2_clock -> amb1_clock"); +} diff --git a/third_party/date/test/clock_cast_test/normal_clocks.pass.cpp b/third_party/date/test/clock_cast_test/normal_clocks.pass.cpp new file mode 100644 index 0000000..525bc02 --- /dev/null +++ b/third_party/date/test/clock_cast_test/normal_clocks.pass.cpp @@ -0,0 +1,102 @@ +// The MIT License (MIT) +// +// Copyright (c) 2017 Tomasz KamiÅ„ski +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "tz.h" +#include + +int +main() +{ + using namespace date; + using sys_clock = std::chrono::system_clock; + + // self + { + sys_days st(1997_y/dec/12); + auto ut = utc_clock::from_sys(st); + auto tt = tai_clock::from_utc(ut); + + assert(clock_cast(st) == st); + assert(clock_cast(ut) == ut); + assert(clock_cast(tt) == tt); + } + + // sys <-> utc + { + sys_days st(1997_y/dec/12); + auto ut = utc_clock::from_sys(st); + + assert(clock_cast(st) == ut); + assert(clock_cast(ut) == st); + } + + // tai <-> utc + { + sys_days st(1997_y/dec/12); + auto ut = utc_clock::from_sys(st); + auto tt = tai_clock::from_utc(ut); + + assert(clock_cast(ut) == tt); + assert(clock_cast(tt) == ut); + } + + // tai <-> sys + { + sys_days st(1997_y/dec/12); + auto ut = utc_clock::from_sys(st); + auto tt = tai_clock::from_utc(ut); + + assert(clock_cast(st) == tt); + assert(clock_cast(tt) == st); + } + + // gps <-> utc + { + sys_days st(1997_y/dec/12); + auto ut = utc_clock::from_sys(st); + auto gt = gps_clock::from_utc(ut); + + assert(clock_cast(ut) == gt); + assert(clock_cast(gt) == ut); + } + + // gps <-> sys + { + sys_days st(1997_y/dec/12); + auto ut = utc_clock::from_sys(st); + auto gt = gps_clock::from_utc(ut); + + assert(clock_cast(st) == gt); + assert(clock_cast(gt) == st); + } + + // tai <-> gps + { + sys_days st(1997_y/dec/12); + auto ut = utc_clock::from_sys(st); + auto tt = tai_clock::from_utc(ut); + auto gt = gps_clock::from_utc(ut); + + assert(clock_cast(tt) == gt); + assert(clock_cast(gt) == tt); + } +} diff --git a/third_party/date/test/clock_cast_test/to_sys_return_int.fail.cpp b/third_party/date/test/clock_cast_test/to_sys_return_int.fail.cpp new file mode 100644 index 0000000..370c682 --- /dev/null +++ b/third_party/date/test/clock_cast_test/to_sys_return_int.fail.cpp @@ -0,0 +1,49 @@ +// The MIT License (MIT) +// +// Copyright (c) 2017 Tomasz KamiÅ„ski +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "tz.h" + +struct bad_clock +{ + using duration = std::chrono::system_clock::duration; + using rep = duration::rep; + using period = duration::period; + using time_point = std::chrono::time_point; + + template + static + int + to_sys(std::chrono::time_point const& tp) + { + return tp.time_since_epoch().count(); + } +}; + +int +main() +{ + using namespace date; + using sys_clock = std::chrono::system_clock; + + auto bt = bad_clock::time_point(); + clock_cast(bt); +} diff --git a/third_party/date/test/clock_cast_test/to_sys_return_reference.fail.cpp b/third_party/date/test/clock_cast_test/to_sys_return_reference.fail.cpp new file mode 100644 index 0000000..5fae165 --- /dev/null +++ b/third_party/date/test/clock_cast_test/to_sys_return_reference.fail.cpp @@ -0,0 +1,51 @@ +// The MIT License (MIT) +// +// Copyright (c) 2017 Tomasz KamiÅ„ski +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "tz.h" + +struct bad_clock +{ + using duration = std::chrono::system_clock::duration; + using rep = duration::rep; + using period = duration::period; + using time_point = std::chrono::time_point; + + template + static + date::sys_time const& + to_sys(std::chrono::time_point const& tp) + { + static date::sys_time val; + val = date::sys_time(tp.time_since_epoch()); + return val; + } +}; + +int +main() +{ + using namespace date; + using sys_clock = std::chrono::system_clock; + + auto bt = bad_clock::time_point(); + clock_cast(bt); +} diff --git a/third_party/date/test/clock_cast_test/to_sys_return_utc_time.fail.cpp b/third_party/date/test/clock_cast_test/to_sys_return_utc_time.fail.cpp new file mode 100644 index 0000000..a3e715c --- /dev/null +++ b/third_party/date/test/clock_cast_test/to_sys_return_utc_time.fail.cpp @@ -0,0 +1,49 @@ +// The MIT License (MIT) +// +// Copyright (c) 2017, 2018 Tomasz KamiÅ„ski +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "tz.h" + +struct bad_clock +{ + using duration = std::chrono::system_clock::duration; + using rep = duration::rep; + using period = duration::period; + using time_point = std::chrono::time_point; + + template + static + date::utc_time + to_sys(std::chrono::time_point const& tp) + { + return date::utc_time(tp.time_since_epoch()); + } +}; + +int +main() +{ + using namespace date; + using sys_clock = std::chrono::system_clock; + + auto bt = bad_clock::time_point(); + clock_cast(bt); +} diff --git a/third_party/date/test/date_test/day.pass.cpp b/third_party/date/test/date_test/day.pass.cpp new file mode 100644 index 0000000..0dbdf68 --- /dev/null +++ b/third_party/date/test/date_test/day.pass.cpp @@ -0,0 +1,143 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class day +// { +// unsigned char d_; +// public: +// explicit constexpr day(unsigned d) noexcept; +// +// day& operator++() noexcept; +// day operator++(int) noexcept; +// day& operator--() noexcept; +// day operator--(int) noexcept; +// +// day& operator+=(const days& d) noexcept; +// day& operator-=(const days& d) noexcept; +// +// constexpr explicit operator unsigned() const noexcept; +// constexpr bool ok() const noexcept; +// }; +// +// constexpr bool operator==(const day& x, const day& y) noexcept; +// constexpr bool operator!=(const day& x, const day& y) noexcept; +// constexpr bool operator< (const day& x, const day& y) noexcept; +// constexpr bool operator> (const day& x, const day& y) noexcept; +// constexpr bool operator<=(const day& x, const day& y) noexcept; +// constexpr bool operator>=(const day& x, const day& y) noexcept; +// +// constexpr day operator+(const day& x, const days& y) noexcept; +// constexpr day operator+(const days& x, const day& y) noexcept; +// constexpr day operator-(const day& x, const days& y) noexcept; +// constexpr days operator-(const day& x, const day& y) noexcept; +// +// constexpr day operator "" _d(unsigned long long d) noexcept; +// std::ostream& operator<<(std::ostream& os, const day& d); + +#include "date.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert( std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert( std::is_nothrow_constructible{}, ""); +static_assert( std::is_nothrow_constructible{}, ""); +static_assert(!std::is_convertible{}, ""); +static_assert(!std::is_convertible{}, ""); +static_assert(static_cast(date::day{1}) == 1, ""); + +static_assert(!date::day{0}.ok(), ""); +static_assert( date::day{1}.ok(), ""); +static_assert( date::day{2}.ok(), ""); +static_assert( date::day{3}.ok(), ""); +static_assert( date::day{29}.ok(), ""); +static_assert( date::day{30}.ok(), ""); +static_assert( date::day{31}.ok(), ""); +static_assert(!date::day{32}.ok(), ""); + +int +main() +{ + using namespace date; + static_assert(std::is_same{}, ""); + + static_assert(1_d == day{1}, ""); + static_assert(2_d == day{2}, ""); + + static_assert( 1_d == 1_d, ""); + static_assert(!(1_d == 2_d), ""); + static_assert(!(2_d == 1_d), ""); + + static_assert(!(1_d != 1_d), ""); + static_assert( 1_d != 2_d, ""); + static_assert( 2_d != 1_d, ""); + + static_assert(!(1_d < 1_d), ""); + static_assert( 1_d < 2_d, ""); + static_assert(!(2_d < 1_d), ""); + + static_assert( 1_d <= 1_d, ""); + static_assert( 1_d <= 2_d, ""); + static_assert(!(2_d <= 1_d), ""); + + static_assert(!(1_d > 1_d), ""); + static_assert(!(1_d > 2_d), ""); + static_assert( 2_d > 1_d, ""); + + static_assert( 1_d >= 1_d, ""); + static_assert(!(1_d >= 2_d), ""); + static_assert( 2_d >= 1_d, ""); + + static_assert(3_d + days{7} == 10_d, ""); + static_assert(days{7} + 3_d == 10_d, ""); + static_assert(3_d + weeks{1} == 10_d, ""); + static_assert(weeks{1} + 3_d == 10_d, ""); + + static_assert(7_d - days{3} == 4_d, ""); + static_assert(3_d - 7_d == days{-4}, ""); + static_assert(25_d - 11_d == weeks{2}, ""); + + auto d = 1_d; + assert(++d == 2_d); + assert(d++ == 2_d); + assert(d == 3_d); + assert(d-- == 3_d); + assert(d == 2_d); + assert(--d == 1_d); + assert((d += days{2}) == 3_d); + assert((d -= days{2}) == 1_d); + + std::ostringstream os; + os << d; + assert(os.str() == "01"); + d += days{11}; + os.str(""); + os << d; + assert(os.str() == "12"); +} diff --git a/third_party/date/test/date_test/daypday.fail.cpp b/third_party/date/test/date_test/daypday.fail.cpp new file mode 100644 index 0000000..80a92c7 --- /dev/null +++ b/third_party/date/test/date_test/daypday.fail.cpp @@ -0,0 +1,32 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// day + day not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + auto x = 3_d + 7_d; +} diff --git a/third_party/date/test/date_test/daysmday.fail.cpp b/third_party/date/test/date_test/daysmday.fail.cpp new file mode 100644 index 0000000..42db047 --- /dev/null +++ b/third_party/date/test/date_test/daysmday.fail.cpp @@ -0,0 +1,32 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// days - day not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + auto x = days{3} - 7_d; +} diff --git a/third_party/date/test/date_test/daysmweekday.fail.cpp b/third_party/date/test/date_test/daysmweekday.fail.cpp new file mode 100644 index 0000000..05e8e4c --- /dev/null +++ b/third_party/date/test/date_test/daysmweekday.fail.cpp @@ -0,0 +1,32 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// days - weekday not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + auto b = days{1} - sun; +} diff --git a/third_party/date/test/date_test/detail/decimal_format_seconds.pass.cpp b/third_party/date/test/date_test/detail/decimal_format_seconds.pass.cpp new file mode 100644 index 0000000..cce6ae8 --- /dev/null +++ b/third_party/date/test/date_test/detail/decimal_format_seconds.pass.cpp @@ -0,0 +1,141 @@ +// The MIT License (MIT) +// +// Copyright (c) 2017 Howard Hinnant +// +// 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. + +// template +// class decimal_format_seconds +// { +// using CT = typename std::common_type::type; +// using rep = typename CT::rep; +// public: +// static unsigned constexpr width = detail::width::value < 19 ? +// detail::width::value : 6u; +// using precision = std::chrono::duration::value>>; +// private: +// std::chrono::seconds s_; +// precision sub_s_; +// +// public: +// constexpr explicit decimal_format_seconds(const Duration& d) noexcept; +// +// constexpr std::chrono::seconds& seconds() noexcept; +// constexpr std::chrono::seconds seconds() const noexcept; +// constexpr precision subseconds() const noexcept; +// constexpr precision to_duration() const noexcept; +// +// template +// friend +// std::basic_ostream& +// operator<<(std::basic_ostream& os, const decimal_format_seconds& x); +// }; + +#include "date.h" + +#include +#include +#include + +using fortnights = std::chrono::duration, + date::weeks::period>>; + +using microfortnights = std::chrono::duration>; + +int +main() +{ + using namespace date::detail; + using namespace std; + using namespace std::chrono; + + { + using D = decimal_format_seconds; + static_assert(is_same{}, ""); + static_assert(D::width == 0, ""); + D dfs{minutes{3}}; + assert(dfs.seconds() == seconds{180}); + assert(dfs.to_duration() == seconds{180}); + ostringstream out; + out << dfs; + assert(out.str() == "180"); + } + { + using D = decimal_format_seconds; + static_assert(is_same{}, ""); + static_assert(D::width == 0, ""); + D dfs{seconds{3}}; + assert(dfs.seconds() == seconds{3}); + assert(dfs.to_duration() == seconds{3}); + ostringstream out; + out << dfs; + assert(out.str() == "03"); + } + { + using D = decimal_format_seconds; + static_assert(D::width == 3, ""); + D dfs{seconds{3}}; + assert(dfs.seconds() == seconds{3}); + assert(dfs.to_duration() == seconds{3}); + assert(dfs.subseconds() == milliseconds{0}); + ostringstream out; + out << dfs; + assert(out.str() == "03.000"); + } + { + using D = decimal_format_seconds; + static_assert(D::width == 3, ""); + D dfs{milliseconds{3}}; + assert(dfs.seconds() == seconds{0}); + assert(dfs.to_duration() == milliseconds{3}); + assert(dfs.subseconds() == milliseconds{3}); + ostringstream out; + out << dfs; + assert(out.str() == "00.003"); + } + { + using D = decimal_format_seconds; + static_assert(D::width == 4, ""); + D dfs{microfortnights{3}}; + using S = D::precision; + assert(dfs.seconds() == seconds{3}); + assert(dfs.to_duration() == S{36288}); + assert(dfs.subseconds() == S{6288}); + ostringstream out; + out << dfs; + assert(out.str() == "03.6288"); + } + { + using CT = common_type::type; + using D = decimal_format_seconds; + static_assert(D::width == 4, ""); + D dfs{microfortnights{3}}; + using S = D::precision; + assert(dfs.seconds() == seconds{3}); + assert(dfs.to_duration() == S{36288}); + assert(dfs.subseconds() == S{6288}); + ostringstream out; + out << dfs; + assert(out.str() == "03.6288"); + } +} diff --git a/third_party/date/test/date_test/detail/static_pow10.pass.cpp b/third_party/date/test/date_test/detail/static_pow10.pass.cpp new file mode 100644 index 0000000..fe44fa4 --- /dev/null +++ b/third_party/date/test/date_test/detail/static_pow10.pass.cpp @@ -0,0 +1,50 @@ +// The MIT License (MIT) +// +// Copyright (c) 2017 Howard Hinnant +// +// 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. + +// template +// struct static_pow10 +// { +// static constepxr std::uint64_t value = ...; +// }; + +#include "date.h" + +#include +#include +#include + +int +main() +{ + using namespace date::detail; + static_assert(static_pow10<0>::value == 1, ""); + static_assert(static_pow10<1>::value == 10, ""); + static_assert(static_pow10<2>::value == 100, ""); + static_assert(static_pow10<3>::value == 1000, ""); + static_assert(static_pow10<4>::value == 10000, ""); + static_assert(static_pow10<5>::value == 100000, ""); + static_assert(static_pow10<6>::value == 1000000, ""); + static_assert(static_pow10<7>::value == 10000000, ""); + static_assert(static_pow10<8>::value == 100000000, ""); + static_assert(static_pow10<9>::value == 1000000000, ""); + static_assert(static_pow10<10>::value == 10000000000, ""); +} diff --git a/third_party/date/test/date_test/detail/width.pass.cpp b/third_party/date/test/date_test/detail/width.pass.cpp new file mode 100644 index 0000000..94f57b7 --- /dev/null +++ b/third_party/date/test/date_test/detail/width.pass.cpp @@ -0,0 +1,64 @@ +// The MIT License (MIT) +// +// Copyright (c) 2017 Howard Hinnant +// +// 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. + +// width::value is the number of fractional decimal digits in 1/n +// width<0>::value and width<1>::value are defined to be 0 +// If 1/n takes more than 18 fractional decimal digits, +// the result is truncated to 19. +// Example: width<2>::value == 1 +// Example: width<3>::value == 19 +// Example: width<4>::value == 2 +// Example: width<10>::value == 1 +// Example: width<1000>::value == 3 +// template +// +// struct width +// { +// static constexpr unsigned value = ...; +// }; + +#include "date.h" + +#include +#include +#include + +int +main() +{ + using namespace date::detail; + static_assert(width<0, 1>::value == 0, ""); + static_assert(width<1, 1>::value == 0, ""); + static_assert(width<1, 2>::value == 1, ""); + static_assert(width<1, 3>::value == 19, ""); + static_assert(width<1, 4>::value == 2, ""); + static_assert(width<1, 5>::value == 1, ""); + static_assert(width<1, 6>::value == 19, ""); + static_assert(width<1, 7>::value == 19, ""); + static_assert(width<1, 8>::value == 3, ""); + static_assert(width<1, 9>::value == 19, ""); + static_assert(width<1, 10>::value == 1, ""); + static_assert(width<1, 100>::value == 2, ""); + static_assert(width<1, 1000>::value == 3, ""); + static_assert(width<1, 10000>::value == 4, ""); + static_assert(width<756, 625>::value == 4, ""); +} diff --git a/third_party/date/test/date_test/durations.pass.cpp b/third_party/date/test/date_test/durations.pass.cpp new file mode 100644 index 0000000..970ddde --- /dev/null +++ b/third_party/date/test/date_test/durations.pass.cpp @@ -0,0 +1,62 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// durations +// +// using days = std::chrono::duration +// , std::chrono::hours::period>>; +// +// using weeks = std::chrono::duration +// , days::period>>; +// +// using years = std::chrono::duration +// , days::period>>; +// +// using months = std::chrono::duration +// >>; +// +// time_point +// +// using sys_days = std::chrono::time_point; + +#include "date.h" + +#include + +static_assert(date::days{1} == std::chrono::hours{24}, ""); + +static_assert(date::weeks{1} == date::days{7}, ""); + +static_assert(date::months{12} == date::years{1}, ""); +static_assert(date::days{30} < date::months{1} && date::months{1} < date::days{31}, ""); +static_assert(date::weeks{4} < date::months{1} && date::months{1} < date::weeks{5}, ""); + +static_assert(date::years{400} == date::days{146097}, ""); +static_assert(date::days{365} < date::years{1} && date::years{1} < date::days{366}, ""); +static_assert(date::weeks{52} < date::years{1} && date::years{1} < date::weeks{53}, ""); + +static_assert(std::is_same{}, ""); + +int +main() +{ +} diff --git a/third_party/date/test/date_test/durations_output.pass.cpp b/third_party/date/test/date_test/durations_output.pass.cpp new file mode 100644 index 0000000..ebf3ff5 --- /dev/null +++ b/third_party/date/test/date_test/durations_output.pass.cpp @@ -0,0 +1,328 @@ +// The MIT License (MIT) +// +// Copyright (c) 2018 Tomasz KamiÅ„ski +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +#include "date.h" + +#include +#include + +void test_SI() +{ + using namespace std::chrono; + using namespace date; + + std::ostringstream os; + + // atto + { + duration d(13); + os << d; + assert(os.str() == "13as"); + os.str(""); + } + + // femto + { + duration d(13); + os << d; + assert(os.str() == "13fs"); + os.str(""); + } + + // pico + { + duration d(13); + os << d; + assert(os.str() == "13ps"); + os.str(""); + } + + // nano + { + duration d(13); + os << d; + assert(os.str() == "13ns"); + os.str(""); + } + + // mikro + { + duration d(13); + os << d; + assert(os.str() == "13\xC2\xB5s"); + os.str(""); + } + + // milli + { + duration d(13); + os << d; + assert(os.str() == "13ms"); + os.str(""); + } + + // centi + { + duration d(13); + os << d; + assert(os.str() == "13cs"); + os.str(""); + } + + // deci + { + duration d(13); + os << d; + assert(os.str() == "13ds"); + os.str(""); + } + + // seconds + { + duration d(13); + os << d; + assert(os.str() == "13s"); + os.str(""); + } + + // deca + { + duration d(13); + os << d; + assert(os.str() == "13das"); + os.str(""); + } + + // hecto + { + duration d(13); + os << d; + assert(os.str() == "13hs"); + os.str(""); + } + + // kilo + { + duration d(13); + os << d; + assert(os.str() == "13ks"); + os.str(""); + } + + // mega + { + duration d(13); + os << d; + assert(os.str() == "13Ms"); + os.str(""); + } + + // giga + { + duration d(13); + os << d; + assert(os.str() == "13Gs"); + os.str(""); + } + + // tera + { + duration d(13); + os << d; + assert(os.str() == "13Ts"); + os.str(""); + } + + // peta + { + duration d(13); + os << d; + assert(os.str() == "13Ps"); + os.str(""); + } + + // femto + { + duration d(13); + os << d; + assert(os.str() == "13Es"); + os.str(""); + } +} + +void test_calendar() +{ + using namespace std::chrono; + using namespace date; + + std::ostringstream os; + + // minutes + { + minutes d(13); + os << d; + assert(os.str() == "13min"); + os.str(""); + } + + // hours + { + hours d(13); + os << d; + assert(os.str() == "13h"); + os.str(""); + } + + // days + { + days d(13); + os << d; + assert(os.str() == "13d"); + os.str(""); + } +} + +void test_integral_scale() +{ + using namespace std::chrono; + using namespace date; + + std::ostringstream os; + + // ratio 123 / 1 + { + duration> d(13); + os << d; + assert(os.str() == "13[123]s"); + os.str(""); + } + + // ratio 100 / 4 = ratio 25 / 1 + { + duration> d(13); + os << d; + assert(os.str() == "13[25]s"); + os.str(""); + } + + // weeks = ratio 7 * 24 * 60 * 60 / 1 = ratio 604800 / 1 + { + weeks d(13); + os << d; + assert(os.str() == "13[604800]s"); + os.str(""); + } + + // years = 146097/400 days = ratio 146097/400 * 24 * 60 * 60 = ratio 31556952 / 1 + { + years d(13); + os << d; + assert(os.str() == "13[31556952]s"); + os.str(""); + } + + // months = 1/12 years = ratio 1/12 * 31556952 = ratio 2629746 / 1 + { + months d(13); + os << d; + assert(os.str() == "13[2629746]s"); + os.str(""); + } +} + +void test_ratio_scale() +{ + using namespace std::chrono; + using namespace date; + + std::ostringstream os; + + // ratio 1 / 2 + { + duration> d(13); + os << d; + assert(os.str() == "13[1/2]s"); + os.str(""); + } + + // ratio 100 / 3 + { + duration> d(13); + os << d; + assert(os.str() == "13[100/3]s"); + os.str(""); + } + + // ratio 100 / 6 = ratio 50 / 3 + { + duration> d(13); + os << d; + assert(os.str() == "13[50/3]s"); + os.str(""); + } +} + +void test_constexpr() +{ + using date::detail::get_units; + + CONSTCD11 auto as = get_units(std::atto{}); + CONSTCD11 auto fs = get_units(std::femto{}); + CONSTCD11 auto ps = get_units(std::pico{}); + CONSTCD11 auto ns = get_units(std::nano{}); + CONSTCD11 auto us = get_units(std::micro{}); + CONSTCD11 auto usw = get_units(std::micro{}); + CONSTCD11 auto ms = get_units(std::milli{}); + CONSTCD11 auto cs = get_units(std::centi{}); + CONSTCD11 auto ds = get_units(std::deci{}); + CONSTCD11 auto s = get_units(std::ratio<1>{}); + CONSTCD11 auto das = get_units(std::deca{}); + CONSTCD11 auto hs = get_units(std::hecto{}); + CONSTCD11 auto ks = get_units(std::kilo{}); + CONSTCD11 auto Ms = get_units(std::mega{}); + CONSTCD11 auto Gs = get_units(std::giga{}); + CONSTCD11 auto Ts = get_units(std::tera{}); + CONSTCD11 auto Ps = get_units(std::peta{}); + CONSTCD11 auto Es = get_units(std::exa{}); + (void)as, (void)fs, (void)ps, (void)ns, (void)usw, (void)us, + (void)ms, (void)cs, (void)ds, (void)s, (void)das, (void)hs, + (void)ks, (void)Ms, (void)Gs, (void)Ts, (void)Ps, (void)Es; + + CONSTCD11 auto min = get_units(std::ratio<60>{}); + CONSTCD11 auto h = get_units(std::ratio<3600>{}); + CONSTCD11 auto d = get_units(std::ratio<86400>{}); + (void)min, (void)h, (void)d; + + CONSTCD14 auto integer = get_units(std::ratio<123>{}); + CONSTCD14 auto ratio = get_units(std::ratio<123, 3>{}); + (void)integer, (void)ratio; +} + +int +main() +{ + test_SI(); + test_calendar(); + test_integral_scale(); + test_ratio_scale(); +} diff --git a/third_party/date/test/date_test/format/century.pass.cpp b/third_party/date/test/date_test/format/century.pass.cpp new file mode 100644 index 0000000..1b401f7 --- /dev/null +++ b/third_party/date/test/date_test/format/century.pass.cpp @@ -0,0 +1,117 @@ +// The MIT License (MIT) +// +// Copyright (c) 2016 Howard Hinnant +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "date.h" + +#include +#include +#include + +int +main() +{ + using namespace date; + using namespace std::chrono; + std::ostringstream os; + os << format("%C", sys_days{jun/1/20001}); + assert(os.str() == "200"); + + os.str(""); + os << format("%C", sys_days{jun/1/20000}); + assert(os.str() == "200"); + + os.str(""); + os << format("%C", sys_days{jun/1/19999}); + assert(os.str() == "199"); + + os.str(""); + os << format("%C", sys_days{jun/1/2001}); + assert(os.str() == "20"); + + os.str(""); + os << format("%C", sys_days{jun/1/2000}); + assert(os.str() == "20"); + + os.str(""); + os << format("%C", sys_days{jun/1/1999}); + assert(os.str() == "19"); + + os.str(""); + os << format("%C", sys_days{jun/1/101}); + assert(os.str() == "01"); + + os.str(""); + os << format("%C", sys_days{jun/1/100}); + assert(os.str() == "01"); + + os.str(""); + os << format("%C", sys_days{jun/1/99}); + assert(os.str() == "00"); + + os.str(""); + os << format("%C", sys_days{jun/1/1}); + assert(os.str() == "00"); + + os.str(""); + os << format("%C", sys_days{jun/1/0}); + assert(os.str() == "00"); + + os.str(""); + os << format("%C", sys_days{jun/1/-1}); + assert(os.str() == "-01"); + + os.str(""); + os << format("%C", sys_days{jun/1/-99}); + assert(os.str() == "-01"); + + os.str(""); + os << format("%C", sys_days{jun/1/-100}); + assert(os.str() == "-01"); + + os.str(""); + os << format("%C", sys_days{jun/1/-101}); + assert(os.str() == "-02"); + + os.str(""); + os << format("%C", sys_days{jun/1/-1999}); + assert(os.str() == "-20"); + + os.str(""); + os << format("%C", sys_days{jun/1/-2000}); + assert(os.str() == "-20"); + + os.str(""); + os << format("%C", sys_days{jun/1/-2001}); + assert(os.str() == "-21"); + + os.str(""); + os << format("%C", sys_days{jun/1/-19999}); + assert(os.str() == "-200"); + + os.str(""); + os << format("%C", sys_days{jun/1/-20000}); + assert(os.str() == "-200"); + + os.str(""); + os << format("%C", sys_days{jun/1/-20001}); + assert(os.str() == "-201"); +} diff --git a/third_party/date/test/date_test/format/misc.pass.cpp b/third_party/date/test/date_test/format/misc.pass.cpp new file mode 100644 index 0000000..06deb24 --- /dev/null +++ b/third_party/date/test/date_test/format/misc.pass.cpp @@ -0,0 +1,52 @@ +// The MIT License (MIT) +// +// Copyright (c) 2016 Howard Hinnant +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "date.h" +#include +#include + +template +void +test(const std::string& in_fmt, const std::string& input, + const std::string& out_fmt, const std::string& output) +{ + using namespace date; + std::istringstream in{input}; + T t; + in >> parse(in_fmt, t); + assert(!in.fail()); + auto s = format(out_fmt, t); + assert(s == output); +} + +int +main() +{ + using namespace date; + test("%Y", "2017", "%Y", "2017"); + test("%m", "3", "%m", "03"); + test("%d", "25", "%d", "25"); + test("%Y-%m", "2017-03", "%Y-%m", "2017-03"); + test("%y%m", "1703", "%Y-%m", "2017-03"); + test("%m/%d", "3/25", "%m/%d", "03/25"); + test("%w", "3", "%w", "3"); +} diff --git a/third_party/date/test/date_test/format/range.pass.cpp b/third_party/date/test/date_test/format/range.pass.cpp new file mode 100644 index 0000000..fbe2d8c --- /dev/null +++ b/third_party/date/test/date_test/format/range.pass.cpp @@ -0,0 +1,78 @@ +// The MIT License (MIT) +// +// Copyright (c) 2016 Howard Hinnant +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "date.h" + +#include +#include +#include + +using fortnights = std::chrono::duration, + date::weeks::period>>; + +using microfortnights = std::chrono::duration>; + +int +main() +{ + using namespace date; + using namespace std::chrono; + std::ostringstream os; + os << format("%F %T", sys_days{jan/1/year::min()}); + assert(os.str() == "-32767-01-01 00:00:00"); + os.str(""); + os << format("%F %T", sys_days{dec/last/year::max()}); + assert(os.str() == "32767-12-31 00:00:00"); + os.str(""); + os << format("%F %T", sys_days{dec/last/year::max()} + hours{23} + minutes{59} + + seconds{59} + microseconds{999999}); + assert(os.str() == "32767-12-31 23:59:59.999999"); + os.str(""); + + os << format("%Y-%m-%d %H:%M:%S", sys_days{jan/1/year::min()}); + assert(os.str() == "-32767-01-01 00:00:00"); + os.str(""); + os << format("%Y-%m-%d %H:%M:%S", sys_days{dec/last/year::max()}); + assert(os.str() == "32767-12-31 00:00:00"); + os.str(""); + os << format("%Y-%m-%d %H:%M:%S", sys_days{dec/last/year::max()} + hours{23} + + minutes{59} + seconds{59} + microseconds{999999}); + assert(os.str() == "32767-12-31 23:59:59.999999"); + os.str(""); + + os << format("%F %T", sys_days{jan/1/year::min()} + microfortnights{1}); + assert(os.str() == "-32767-01-01 00:00:01.2096"); + os.str(""); + os << format("%F %T", sys_days{dec/last/year::max()} + microfortnights{1}); + assert(os.str() == "32767-12-31 00:00:01.2096"); + os.str(""); + + os << format("%F", jan/1/year::min()); + assert(os.str() == "-32767-01-01"); + os.str(""); + os << format("%F", dec/last/year::max()); + assert(os.str() == "32767-12-31"); + os.str(""); +} diff --git a/third_party/date/test/date_test/format/two_dight_year.pass.cpp b/third_party/date/test/date_test/format/two_dight_year.pass.cpp new file mode 100644 index 0000000..3f615b3 --- /dev/null +++ b/third_party/date/test/date_test/format/two_dight_year.pass.cpp @@ -0,0 +1,121 @@ +// The MIT License (MIT) +// +// Copyright (c) 2016 Howard Hinnant +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "date.h" + +#include +#include +#include + +int +main() +{ + using namespace date; + using namespace std::chrono; + std::ostringstream os; + os << format("%y", sys_days{jun/1/20001}); + assert(os.str() == "01"); + + os.str(""); + os << format("%y", sys_days{jun/1/20000}); + assert(os.str() == "00"); + + os.str(""); + os << format("%y", sys_days{jun/1/19999}); + assert(os.str() == "99"); + + os.str(""); + os << format("%y", sys_days{jun/1/2001}); + assert(os.str() == "01"); + + os.str(""); + os << format("%y", sys_days{jun/1/2000}); + assert(os.str() == "00"); + + os.str(""); + os << format("%y", sys_days{jun/1/1999}); + assert(os.str() == "99"); + + os.str(""); + os << format("%y", sys_days{jun/1/101}); + assert(os.str() == "01"); + + os.str(""); + os << format("%y", sys_days{jun/1/100}); + assert(os.str() == "00"); + + os.str(""); + os << format("%y", sys_days{jun/1/99}); + assert(os.str() == "99"); + + os.str(""); + os << format("%y", sys_days{jun/1/1}); + assert(os.str() == "01"); + + os.str(""); + os << format("%y", sys_days{jun/1/0}); + assert(os.str() == "00"); + + os.str(""); + os << format("%y", sys_days{jun/1/-1}); + assert(os.str() == "01"); + + os.str(""); + os << format("%y", sys_days{jun/1/-99}); + assert(os.str() == "99"); + + os.str(""); + os << format("%y", sys_days{jun/1/-100}); + assert(os.str() == "00"); + + os.str(""); + os << format("%y", sys_days{jun/1/-101}); + assert(os.str() == "01"); + + os.str(""); + os << format("%y", sys_days{jun/1/-1999}); + assert(os.str() == "99"); + + os.str(""); + os << format("%y", sys_days{jun/1/-2000}); + assert(os.str() == "00"); + + os.str(""); + os << format("%y", sys_days{jun/1/-2001}); + assert(os.str() == "01"); + + os.str(""); + os << format("%y", sys_days{jun/1/-19999}); + assert(os.str() == "99"); + + os.str(""); + os << format("%y", sys_days{jun/1/-20000}); + assert(os.str() == "00"); + + os.str(""); + os << format("%y", sys_days{jun/1/-20001}); + assert(os.str() == "01"); + + os.str(""); + os << format("%y", sys_days{jun/1/year::min()}); + assert(os.str() == "67"); +} diff --git a/third_party/date/test/date_test/last.pass.cpp b/third_party/date/test/date_test/last.pass.cpp new file mode 100644 index 0000000..11b991c --- /dev/null +++ b/third_party/date/test/date_test/last.pass.cpp @@ -0,0 +1,34 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// constexpr struct last_spec {} last{}; + +#include "date.h" + +#include + +static_assert(std::is_same{}, ""); + +int +main() +{ +} diff --git a/third_party/date/test/date_test/make_time.pass.cpp b/third_party/date/test/date_test/make_time.pass.cpp new file mode 100644 index 0000000..f203807 --- /dev/null +++ b/third_party/date/test/date_test/make_time.pass.cpp @@ -0,0 +1,81 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// template ::value>::type> +// constexpr +// time_of_day> +// make_time(std::chrono::duration d) noexcept; + +#include "date.h" + +#include +#include + +int +main() +{ + using namespace date; + using namespace std; + using namespace std::chrono; + + { + static_assert(is_same>{}, ""); + auto tod = make_time(nanoseconds{18429000000022}); + assert(tod.hours() == hours{5}); + assert(tod.minutes() == minutes{7}); + assert(tod.seconds() == seconds{9}); + assert(tod.subseconds() == nanoseconds{22}); + } + { + static_assert(is_same>{}, ""); + auto tod = make_time(microseconds{18429000022}); + assert(tod.hours() == hours{5}); + assert(tod.minutes() == minutes{7}); + assert(tod.seconds() == seconds{9}); + assert(tod.subseconds() == microseconds{22}); + } + { + static_assert(is_same>{}, ""); + auto tod = make_time(seconds{18429}); + assert(tod.hours() == hours{5}); + assert(tod.minutes() == minutes{7}); + assert(tod.seconds() == seconds{9}); + } + { + static_assert(is_same>{}, ""); + auto tod = make_time(minutes{307}); + assert(tod.hours() == hours{5}); + assert(tod.minutes() == minutes{7}); + } + { + static_assert(is_same>{}, ""); + auto tod = make_time(hours{5}); + assert(tod.hours() == hours{5}); + } +} diff --git a/third_party/date/test/date_test/month.pass.cpp b/third_party/date/test/date_test/month.pass.cpp new file mode 100644 index 0000000..4dffa6b --- /dev/null +++ b/third_party/date/test/date_test/month.pass.cpp @@ -0,0 +1,181 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class month +// { +// unsigned char m_; +// public: +// explicit constexpr month(unsigned m) noexcept; +// +// month& operator++() noexcept; +// month operator++(int) noexcept; +// month& operator--() noexcept; +// month operator--(int) noexcept; +// +// month& operator+=(const months& m) noexcept; +// month& operator-=(const months& m) noexcept; +// +// constexpr explicit operator unsigned() const noexcept; +// constexpr bool ok() const noexcept; +// }; +// +// constexpr bool operator==(const month& x, const month& y) noexcept; +// constexpr bool operator!=(const month& x, const month& y) noexcept; +// constexpr bool operator< (const month& x, const month& y) noexcept; +// constexpr bool operator> (const month& x, const month& y) noexcept; +// constexpr bool operator<=(const month& x, const month& y) noexcept; +// constexpr bool operator>=(const month& x, const month& y) noexcept; +// +// constexpr month operator+(const month& x, const months& y) noexcept; +// constexpr month operator+(const months& x, const month& y) noexcept; +// constexpr month operator-(const month& x, const months& y) noexcept; +// constexpr months operator-(const month& x, const month& y) noexcept; +// +// std::ostream& operator<<(std::ostream& os, const month& m); + +// constexpr month jan{1}; +// constexpr month feb{2}; +// constexpr month mar{3}; +// constexpr month apr{4}; +// constexpr month may{5}; +// constexpr month jun{6}; +// constexpr month jul{7}; +// constexpr month aug{8}; +// constexpr month sep{9}; +// constexpr month oct{10}; +// constexpr month nov{11}; +// constexpr month dec{12}; + +#include "date.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert( std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert( std::is_nothrow_constructible{}, ""); +static_assert( std::is_nothrow_constructible{}, ""); +static_assert(!std::is_convertible{}, ""); +static_assert(!std::is_convertible{}, ""); +static_assert(static_cast(date::month{1}) == 1, ""); + +static_assert(!date::month{0}.ok(), ""); +static_assert( date::month{1}.ok(), ""); +static_assert( date::month{2}.ok(), ""); +static_assert( date::month{3}.ok(), ""); +static_assert( date::month{4}.ok(), ""); +static_assert( date::month{5}.ok(), ""); +static_assert( date::month{6}.ok(), ""); +static_assert( date::month{7}.ok(), ""); +static_assert( date::month{8}.ok(), ""); +static_assert( date::month{9}.ok(), ""); +static_assert( date::month{10}.ok(), ""); +static_assert( date::month{11}.ok(), ""); +static_assert( date::month{12}.ok(), ""); +static_assert(!date::month{13}.ok(), ""); + +int +main() +{ + using namespace date; + + static_assert(jan == month{1}, ""); + static_assert(feb == month{2}, ""); + static_assert(mar == month{3}, ""); + static_assert(apr == month{4}, ""); + static_assert(may == month{5}, ""); + static_assert(jun == month{6}, ""); + static_assert(jul == month{7}, ""); + static_assert(aug == month{8}, ""); + static_assert(sep == month{9}, ""); + static_assert(oct == month{10}, ""); + static_assert(nov == month{11}, ""); + static_assert(dec == month{12}, ""); + + static_assert(!(jan != jan), ""); + static_assert( jan != feb, ""); + static_assert( feb != jan, ""); + + static_assert(!(jan < jan), ""); + static_assert( jan < feb, ""); + static_assert(!(feb < jan), ""); + + static_assert( jan <= jan, ""); + static_assert( jan <= feb, ""); + static_assert(!(feb <= jan), ""); + + static_assert(!(jan > jan), ""); + static_assert(!(jan > feb), ""); + static_assert( feb > jan, ""); + + static_assert( jan >= jan, ""); + static_assert(!(jan >= feb), ""); + static_assert( feb >= jan, ""); + + assert(mar + months{7} == oct); + assert(mar + months{27} == jun); + assert(months{7} + mar == oct); + assert(months{27} + mar == jun); + + assert(mar - months{7} == aug); + assert(mar - months{27} == dec); + + assert(mar - feb == months{1}); + assert(feb - mar == months{11}); + +#if __cplusplus >= 201402 + static_assert(mar + months{7} == oct, ""); + static_assert(mar + months{27} == jun, ""); + static_assert(months{7} + mar == oct, ""); + static_assert(months{27} + mar == jun, ""); + + static_assert(mar - months{7} == aug, ""); + static_assert(mar - months{27} == dec, ""); + + static_assert(mar - feb == months{1}, ""); + static_assert(feb - mar == months{11}, ""); +#endif + + auto m = dec; + assert(++m == jan); + assert(m++ == jan); + assert(m == feb); + assert(m-- == feb); + assert(m == jan); + assert(--m == dec); + assert((m += months{2}) == feb); + assert((m -= months{2}) == dec); + + std::ostringstream os; + os << m; + assert(os.str() == "Dec"); + m += months{11}; + os.str(""); + os << m; + assert(os.str() == "Nov"); +} diff --git a/third_party/date/test/date_test/month_day.pass.cpp b/third_party/date/test/date_test/month_day.pass.cpp new file mode 100644 index 0000000..5fca9b2 --- /dev/null +++ b/third_party/date/test/date_test/month_day.pass.cpp @@ -0,0 +1,82 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class month_day +// { +// public: +// constexpr month_day(const date::month& m, const date::day& d) noexcept; +// +// constexpr date::month month() const noexcept; +// constexpr date::day day() const noexcept; +// +// constexpr bool ok() const noexcept; +// }; + +// constexpr bool operator==(const month_day& x, const month_day& y) noexcept; +// constexpr bool operator!=(const month_day& x, const month_day& y) noexcept; +// constexpr bool operator< (const month_day& x, const month_day& y) noexcept; +// constexpr bool operator> (const month_day& x, const month_day& y) noexcept; +// constexpr bool operator<=(const month_day& x, const month_day& y) noexcept; +// constexpr bool operator>=(const month_day& x, const month_day& y) noexcept; + +// std::ostream& operator<<(std::ostream& os, const month_day& md); + +#include "date.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert( std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_nothrow_constructible{}, ""); + +int +main() +{ + using namespace date; + + constexpr month_day md1 = {feb, day{28}}; + constexpr month_day md2 = {mar, day{1}}; +#if __cplusplus >= 201402 + static_assert(md1.ok(), ""); + static_assert(md2.ok(), ""); + static_assert(!month_day{feb, day{32}}.ok(), ""); + static_assert(!month_day{month{0}, day{1}}.ok(), ""); +#endif + static_assert(md1.month() == feb, ""); + static_assert(md1.day() == day{28}, ""); + static_assert(md2.month() == mar, ""); + static_assert(md2.day() == day{1}, ""); + static_assert(md1 == md1, ""); + static_assert(md1 != md2, ""); + static_assert(md1 < md2, ""); + std::ostringstream os; + os << md1; + assert(os.str() == "Feb/28"); +} diff --git a/third_party/date/test/date_test/month_day_last.pass.cpp b/third_party/date/test/date_test/month_day_last.pass.cpp new file mode 100644 index 0000000..d458aee --- /dev/null +++ b/third_party/date/test/date_test/month_day_last.pass.cpp @@ -0,0 +1,75 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class month_day_last +// { +// public: +// constexpr explicit month_day_last(const date::month& m) noexcept; +// +// constexpr date::month month() const noexcept; +// constexpr bool ok() const noexcept; +// }; + +// constexpr bool operator==(const month_day_last& x, const month_day_last& y) noexcept; +// constexpr bool operator!=(const month_day_last& x, const month_day_last& y) noexcept; +// constexpr bool operator< (const month_day_last& x, const month_day_last& y) noexcept; +// constexpr bool operator> (const month_day_last& x, const month_day_last& y) noexcept; +// constexpr bool operator<=(const month_day_last& x, const month_day_last& y) noexcept; +// constexpr bool operator>=(const month_day_last& x, const month_day_last& y) noexcept; + +// std::ostream& operator<<(std::ostream& os, const month_day_last& mdl); + +#include "date.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert(!std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(!std::is_convertible{}, ""); + +int +main() +{ + using namespace date; + + constexpr month_day_last mdl1{feb}; + constexpr month_day_last mdl2{mar}; + static_assert(mdl1.ok(), ""); + static_assert(mdl2.ok(), ""); + static_assert(!month_day_last{month{0}}.ok(), ""); + static_assert(mdl1.month() == feb, ""); + static_assert(mdl2.month() == mar, ""); + static_assert(mdl1 == mdl1, ""); + static_assert(mdl1 != mdl2, ""); + static_assert(mdl1 < mdl2, ""); + std::ostringstream os; + os << mdl1; + assert(os.str() == "Feb/last"); +} diff --git a/third_party/date/test/date_test/month_weekday.pass.cpp b/third_party/date/test/date_test/month_weekday.pass.cpp new file mode 100644 index 0000000..e059d2b --- /dev/null +++ b/third_party/date/test/date_test/month_weekday.pass.cpp @@ -0,0 +1,77 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class month_weekday +// { +// public: +// constexpr month_weekday(const date::month& m, +// const date::weekday_indexed& wdi) noexcept; +// +// constexpr date::month month() const noexcept; +// constexpr date::weekday_indexed weekday_indexed() const noexcept; +// +// constexpr bool ok() const noexcept; +// }; + +// constexpr bool operator==(const month_weekday& x, const month_weekday& y) noexcept; +// constexpr bool operator!=(const month_weekday& x, const month_weekday& y) noexcept; + +// std::ostream& operator<<(std::ostream& os, const month_weekday& mwd); + +#include "date.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert(!std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_nothrow_constructible{}, ""); + +int +main() +{ + using namespace date; + + constexpr month_weekday mwd1 = {feb, sat[4]}; + constexpr month_weekday mwd2 = {mar, mon[1]}; + static_assert(mwd1.ok(), ""); + static_assert(mwd2.ok(), ""); + static_assert(!month_weekday{feb, sat[0]}.ok(), ""); + static_assert(!month_weekday{month{0}, sun[1]}.ok(), ""); + static_assert(mwd1.month() == feb, ""); + static_assert(mwd1.weekday_indexed() == sat[4], ""); + static_assert(mwd2.month() == mar, ""); + static_assert(mwd2.weekday_indexed() == mon[1], ""); + static_assert(mwd1 == mwd1, ""); + static_assert(mwd1 != mwd2, ""); + std::ostringstream os; + os << mwd1; + assert(os.str() == "Feb/Sat[4]"); +} diff --git a/third_party/date/test/date_test/month_weekday_last.pass.cpp b/third_party/date/test/date_test/month_weekday_last.pass.cpp new file mode 100644 index 0000000..4964d5e --- /dev/null +++ b/third_party/date/test/date_test/month_weekday_last.pass.cpp @@ -0,0 +1,77 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class month_weekday_last +// { +// public: +// constexpr month_weekday_last(const date::month& m, +// const date::weekday_last& wdl) noexcept; +// +// constexpr date::month month() const noexcept; +// constexpr date::weekday_last weekday_last() const noexcept; +// +// constexpr bool ok() const noexcept; +// }; + +// constexpr +// bool operator==(const month_weekday_last& x, const month_weekday_last& y) noexcept; +// constexpr +// bool operator!=(const month_weekday_last& x, const month_weekday_last& y) noexcept; + +// std::ostream& operator<<(std::ostream& os, const month_weekday_last& mwdl); + +#include "date.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert(!std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_nothrow_constructible{}, ""); + +int +main() +{ + using namespace date; + + constexpr month_weekday_last mwdl1 = {feb, sat[last]}; + constexpr month_weekday_last mwdl2 = {mar, mon[last]}; + static_assert(mwdl1.ok(), ""); + static_assert(mwdl2.ok(), ""); + static_assert(!month_weekday_last{month{0}, sun[last]}.ok(), ""); + static_assert(mwdl1.month() == feb, ""); + static_assert(mwdl1.weekday_last() == sat[last], ""); + static_assert(mwdl2.month() == mar, ""); + static_assert(mwdl2.weekday_last() == mon[last], ""); + static_assert(mwdl1 == mwdl1, ""); + static_assert(mwdl1 != mwdl2, ""); + std::ostringstream os; + os << mwdl1; + assert(os.str() == "Feb/Sat[last]"); +} diff --git a/third_party/date/test/date_test/month_weekday_last_less.fail.cpp b/third_party/date/test/date_test/month_weekday_last_less.fail.cpp new file mode 100644 index 0000000..beee0e1 --- /dev/null +++ b/third_party/date/test/date_test/month_weekday_last_less.fail.cpp @@ -0,0 +1,34 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// month_weekday_last < month_weekday_last not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + month_weekday_last mwdl1 = {feb, sat[last]}; + month_weekday_last mwdl2 = {mar, mon[last]}; + auto b = mwdl1 < mwdl2; +} diff --git a/third_party/date/test/date_test/month_weekday_less.fail.cpp b/third_party/date/test/date_test/month_weekday_less.fail.cpp new file mode 100644 index 0000000..b3ead83 --- /dev/null +++ b/third_party/date/test/date_test/month_weekday_less.fail.cpp @@ -0,0 +1,34 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// month_weekday < month_weekday not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + month_weekday mwd1 = {feb, sat[4]}; + month_weekday mwd2 = {mar, mon[1]}; + auto b = mwd1 < mwd2; +} diff --git a/third_party/date/test/date_test/monthpmonth.fail.cpp b/third_party/date/test/date_test/monthpmonth.fail.cpp new file mode 100644 index 0000000..0f73aae --- /dev/null +++ b/third_party/date/test/date_test/monthpmonth.fail.cpp @@ -0,0 +1,32 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// month + month not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + auto x = mar + jul; +} diff --git a/third_party/date/test/date_test/months_m_year_month.fail.cpp b/third_party/date/test/date_test/months_m_year_month.fail.cpp new file mode 100644 index 0000000..74ada08 --- /dev/null +++ b/third_party/date/test/date_test/months_m_year_month.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// months - year_month not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = months{1} - year_month{2015_y, jan}; +} diff --git a/third_party/date/test/date_test/months_m_year_month_day.fail.cpp b/third_party/date/test/date_test/months_m_year_month_day.fail.cpp new file mode 100644 index 0000000..8d48619 --- /dev/null +++ b/third_party/date/test/date_test/months_m_year_month_day.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// months - year_month_day not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = jan - year_month_day{2015_y, aug, 9_d}; +} diff --git a/third_party/date/test/date_test/monthsmmonth.fail.cpp b/third_party/date/test/date_test/monthsmmonth.fail.cpp new file mode 100644 index 0000000..e3fa50c --- /dev/null +++ b/third_party/date/test/date_test/monthsmmonth.fail.cpp @@ -0,0 +1,32 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// months - month not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + auto x = months{3} - jul; +} diff --git a/third_party/date/test/date_test/multi_year_duration_addition.pass.cpp b/third_party/date/test/date_test/multi_year_duration_addition.pass.cpp new file mode 100644 index 0000000..5d1d031 --- /dev/null +++ b/third_party/date/test/date_test/multi_year_duration_addition.pass.cpp @@ -0,0 +1,487 @@ +// The MIT License (MIT) +// +// Copyright (c) 2018 Tomasz KamiÅ„ski +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "date.h" +#include +#include +#include + +#define CPP11_ASSERT(...) static_assert(__VA_ARGS__, "") + +#if __cplusplus >= 201402 +// C++14 +# define CPP14_ASSERT(...) static_assert(__VA_ARGS__, "") +#else +// C++11 +# define CPP14_ASSERT(...) assert(__VA_ARGS__) +#endif + +#define NOEXCEPT_ASSERT(...) static_assert(noexcept(__VA_ARGS__), "") + +//Invocation involves a conversion between duration that is currently +//not marked as noexcept. +#define NOEXCEPT_CONVERSION(...) + +template +constexpr T copy(T const& t) noexcept { return t; } + +struct ConvertibleToYears +{ + CONSTCD11 operator date::years() const NOEXCEPT + { return date::years{1}; }; +}; + +struct ConvertibleToMonths +{ + CONSTCD11 operator date::months() const NOEXCEPT + { return date::months{1}; }; +}; + +struct ConvertibleToYearsAndMonths +{ + CONSTCD11 operator date::years() const NOEXCEPT + { return date::years{1}; }; + + CONSTCD11 operator date::months() const NOEXCEPT + { return date::months{1}; }; + +}; + +int +main() +{ + using namespace date; + using namespace std::chrono; + + using decades = duration, years::period>>; + using decamonths = duration, months::period>>; + + constexpr months one_month{1}; + constexpr years one_year{1}; + constexpr decades one_decade{1}; + constexpr decamonths one_decamonth{1}; + + constexpr ConvertibleToMonths custom_month; + constexpr ConvertibleToYears custom_year; + constexpr ConvertibleToYearsAndMonths prefer_year; + + + { + constexpr year_month ym = 2001_y/feb; + CPP14_ASSERT(ym + one_month == 2001_y/mar); + NOEXCEPT_ASSERT(ym + one_month); + CPP14_ASSERT(one_month + ym == 2001_y/mar); + NOEXCEPT_ASSERT(one_month + ym); + CPP14_ASSERT(ym - one_month == 2001_y/jan); + NOEXCEPT_ASSERT(ym - one_month); + CPP14_ASSERT((copy(ym) += one_month) == 2001_y/mar); + NOEXCEPT_ASSERT(copy(ym) += one_month); + CPP14_ASSERT((copy(ym) -= one_month) == 2001_y/jan); + NOEXCEPT_ASSERT(copy(ym) -= one_month); + + CPP11_ASSERT(ym + one_year == 2002_y/feb); + NOEXCEPT_ASSERT(ym + one_year); + CPP11_ASSERT(one_year + ym == 2002_y/feb); + NOEXCEPT_ASSERT(one_year + ym); + CPP11_ASSERT(ym - one_year == 2000_y/feb); + NOEXCEPT_ASSERT(ym - one_year); + CPP14_ASSERT((copy(ym) += one_year) == 2002_y/feb); + NOEXCEPT_ASSERT(copy(ym) += one_year); + CPP14_ASSERT((copy(ym) -= one_year) == 2000_y/feb); + NOEXCEPT_ASSERT(copy(ym) -= one_year); + + CPP11_ASSERT(ym + one_decade == 2011_y/feb); + NOEXCEPT_CONVERSION(ym + one_decade); + CPP11_ASSERT(one_decade + ym == 2011_y/feb); + NOEXCEPT_CONVERSION(one_decade + ym); + CPP11_ASSERT(ym - one_decade == 1991_y/feb); + NOEXCEPT_CONVERSION(ym - one_decade); + CPP14_ASSERT((copy(ym) += one_decade) == 2011_y/feb); + NOEXCEPT_CONVERSION(copy(ym) += one_decade); + CPP14_ASSERT((copy(ym) -= one_decade) == 1991_y/feb); + NOEXCEPT_CONVERSION(copy(ym) -= one_decade); + + CPP14_ASSERT(ym + one_decamonth == 2001_y/dec); + NOEXCEPT_CONVERSION(ym + one_decamonth); + CPP14_ASSERT(one_decamonth + ym == 2001_y/dec); + NOEXCEPT_CONVERSION(one_decamonth + ym); + CPP14_ASSERT(ym - one_decamonth == 2000_y/apr); + NOEXCEPT_CONVERSION(ym - one_decamonth); + CPP14_ASSERT((copy(ym) += one_decamonth) == 2001_y/dec); + NOEXCEPT_CONVERSION(copy(ym) += one_decamonth); + CPP14_ASSERT((copy(ym) -= one_decamonth) == 2000_y/apr); + NOEXCEPT_CONVERSION(copy(ym) -= one_decamonth); + + CPP14_ASSERT(ym + custom_month == 2001_y/mar); + NOEXCEPT_ASSERT(ym + custom_month); + CPP14_ASSERT(custom_month + ym == 2001_y/mar); + NOEXCEPT_ASSERT(custom_month + ym); + CPP14_ASSERT(ym - custom_month == 2001_y/jan); + NOEXCEPT_ASSERT(ym - custom_month); + CPP14_ASSERT((copy(ym) += custom_month) == 2001_y/mar); + NOEXCEPT_ASSERT(copy(ym) += custom_month); + CPP14_ASSERT((copy(ym) -= custom_month) == 2001_y/jan); + NOEXCEPT_ASSERT(copy(ym) -= custom_month); + + CPP11_ASSERT(ym + custom_year == 2002_y/feb); + NOEXCEPT_ASSERT(ym + custom_year); + CPP11_ASSERT(custom_year + ym == 2002_y/feb); + NOEXCEPT_ASSERT(custom_year + ym); + CPP11_ASSERT(ym - custom_year == 2000_y/feb); + NOEXCEPT_ASSERT(ym - custom_year); + CPP14_ASSERT((copy(ym) += custom_year) == 2002_y/feb); + NOEXCEPT_ASSERT(copy(ym) += custom_year); + CPP14_ASSERT((copy(ym) -= custom_year) == 2000_y/feb); + NOEXCEPT_ASSERT(copy(ym) -= custom_year); + + CPP11_ASSERT(ym + prefer_year == 2002_y/feb); + NOEXCEPT_ASSERT(ym + prefer_year); + CPP11_ASSERT(prefer_year + ym == 2002_y/feb); + NOEXCEPT_ASSERT(prefer_year + ym); + CPP11_ASSERT(ym - prefer_year == 2000_y/feb); + NOEXCEPT_ASSERT(ym - prefer_year); + CPP14_ASSERT((copy(ym) += prefer_year) == 2002_y/feb); + NOEXCEPT_ASSERT(copy(ym) += prefer_year); + CPP14_ASSERT((copy(ym) -= prefer_year) == 2000_y/feb); + NOEXCEPT_ASSERT(copy(ym) -= prefer_year); + } + + { + constexpr year_month_day ym = 2001_y/feb/10; + CPP14_ASSERT(ym + one_month == 2001_y/mar/10); + NOEXCEPT_ASSERT(ym + one_month); + CPP14_ASSERT(one_month + ym == 2001_y/mar/10); + NOEXCEPT_ASSERT(one_month + ym); + CPP14_ASSERT(ym - one_month == 2001_y/jan/10); + NOEXCEPT_ASSERT(ym - one_month); + CPP14_ASSERT((copy(ym) += one_month) == 2001_y/mar/10); + NOEXCEPT_ASSERT(copy(ym) += one_month); + CPP14_ASSERT((copy(ym) -= one_month) == 2001_y/jan/10); + NOEXCEPT_ASSERT(copy(ym) -= one_month); + + CPP11_ASSERT(ym + one_year == 2002_y/feb/10); + NOEXCEPT_ASSERT(ym + one_year); + CPP11_ASSERT(one_year + ym == 2002_y/feb/10); + NOEXCEPT_ASSERT(one_year + ym); + CPP11_ASSERT(ym - one_year == 2000_y/feb/10); + NOEXCEPT_ASSERT(ym - one_year); + CPP14_ASSERT((copy(ym) += one_year) == 2002_y/feb/10); + NOEXCEPT_ASSERT(copy(ym) += one_year); + CPP14_ASSERT((copy(ym) -= one_year) == 2000_y/feb/10); + NOEXCEPT_ASSERT(copy(ym) -= one_year); + + CPP11_ASSERT(ym + one_decade == 2011_y/feb/10); + NOEXCEPT_CONVERSION(ym + one_decade); + CPP11_ASSERT(one_decade + ym == 2011_y/feb/10); + NOEXCEPT_CONVERSION(one_decade + ym); + CPP11_ASSERT(ym - one_decade == 1991_y/feb/10); + NOEXCEPT_CONVERSION(ym - one_decade); + CPP14_ASSERT((copy(ym) += one_decade) == 2011_y/feb/10); + NOEXCEPT_CONVERSION(copy(ym) += one_decade); + CPP14_ASSERT((copy(ym) -= one_decade) == 1991_y/feb/10); + NOEXCEPT_CONVERSION(copy(ym) -= one_decade); + + CPP14_ASSERT(ym + one_decamonth == 2001_y/dec/10); + NOEXCEPT_CONVERSION(ym + one_decamonth); + CPP14_ASSERT(one_decamonth + ym == 2001_y/dec/10); + NOEXCEPT_CONVERSION(one_decamonth + ym); + CPP14_ASSERT(ym - one_decamonth == 2000_y/apr/10); + NOEXCEPT_CONVERSION(ym - one_decamonth); + CPP14_ASSERT((copy(ym) += one_decamonth) == 2001_y/dec/10); + NOEXCEPT_CONVERSION(copy(ym) += one_decamonth); + CPP14_ASSERT((copy(ym) -= one_decamonth) == 2000_y/apr/10); + NOEXCEPT_CONVERSION(copy(ym) -= one_decamonth); + + CPP14_ASSERT(ym + custom_month == 2001_y/mar/10); + NOEXCEPT_ASSERT(ym + custom_month); + CPP14_ASSERT(custom_month + ym == 2001_y/mar/10); + NOEXCEPT_ASSERT(custom_month + ym); + CPP14_ASSERT(ym - custom_month == 2001_y/jan/10); + NOEXCEPT_ASSERT(ym - custom_month); + CPP14_ASSERT((copy(ym) += custom_month) == 2001_y/mar/10); + NOEXCEPT_ASSERT(copy(ym) += custom_month); + CPP14_ASSERT((copy(ym) -= custom_month) == 2001_y/jan/10); + NOEXCEPT_ASSERT(copy(ym) -= custom_month); + + CPP11_ASSERT(ym + custom_year == 2002_y/feb/10); + NOEXCEPT_ASSERT(ym + custom_year); + CPP11_ASSERT(custom_year + ym == 2002_y/feb/10); + NOEXCEPT_ASSERT(custom_year + ym); + CPP11_ASSERT(ym - custom_year == 2000_y/feb/10); + NOEXCEPT_ASSERT(ym - custom_year); + CPP14_ASSERT((copy(ym) += custom_year) == 2002_y/feb/10); + NOEXCEPT_ASSERT(copy(ym) += custom_year); + CPP14_ASSERT((copy(ym) -= custom_year) == 2000_y/feb/10); + NOEXCEPT_ASSERT(copy(ym) -= custom_year); + + CPP11_ASSERT(ym + prefer_year == 2002_y/feb/10); + NOEXCEPT_ASSERT(ym + prefer_year); + CPP11_ASSERT(prefer_year + ym == 2002_y/feb/10); + NOEXCEPT_ASSERT(prefer_year + ym); + CPP11_ASSERT(ym - prefer_year == 2000_y/feb/10); + NOEXCEPT_ASSERT(ym - prefer_year); + CPP14_ASSERT((copy(ym) += prefer_year) == 2002_y/feb/10); + NOEXCEPT_ASSERT(copy(ym) += prefer_year); + CPP14_ASSERT((copy(ym) -= prefer_year) == 2000_y/feb/10); + NOEXCEPT_ASSERT(copy(ym) -= prefer_year); + } + + { + constexpr year_month_day_last ym = 2001_y/feb/last; + CPP14_ASSERT(ym + one_month == 2001_y/mar/last); + NOEXCEPT_ASSERT(ym + one_month); + CPP14_ASSERT(one_month + ym == 2001_y/mar/last); + NOEXCEPT_ASSERT(one_month + ym); + CPP14_ASSERT(ym - one_month == 2001_y/jan/last); + NOEXCEPT_ASSERT(ym - one_month); + CPP14_ASSERT((copy(ym) += one_month) == 2001_y/mar/last); + NOEXCEPT_ASSERT(copy(ym) += one_month); + CPP14_ASSERT((copy(ym) -= one_month) == 2001_y/jan/last); + NOEXCEPT_ASSERT(copy(ym) -= one_month); + + CPP11_ASSERT(ym + one_year == 2002_y/feb/last); + NOEXCEPT_ASSERT(ym + one_year); + CPP11_ASSERT(one_year + ym == 2002_y/feb/last); + NOEXCEPT_ASSERT(one_year + ym); + CPP11_ASSERT(ym - one_year == 2000_y/feb/last); + NOEXCEPT_ASSERT(ym - one_year); + CPP14_ASSERT((copy(ym) += one_year) == 2002_y/feb/last); + NOEXCEPT_ASSERT(copy(ym) += one_year); + CPP14_ASSERT((copy(ym) -= one_year) == 2000_y/feb/last); + NOEXCEPT_ASSERT(copy(ym) -= one_year); + + CPP11_ASSERT(ym + one_decade == 2011_y/feb/last); + NOEXCEPT_CONVERSION(ym + one_decade); + CPP11_ASSERT(one_decade + ym == 2011_y/feb/last); + NOEXCEPT_CONVERSION(one_decade + ym); + CPP11_ASSERT(ym - one_decade == 1991_y/feb/last); + NOEXCEPT_CONVERSION(ym - one_decade); + CPP14_ASSERT((copy(ym) += one_decade) == 2011_y/feb/last); + NOEXCEPT_CONVERSION(copy(ym) += one_decade); + CPP14_ASSERT((copy(ym) -= one_decade) == 1991_y/feb/last); + NOEXCEPT_CONVERSION(copy(ym) -= one_decade); + + CPP14_ASSERT(ym + one_decamonth == 2001_y/dec/last); + NOEXCEPT_CONVERSION(ym + one_decamonth); + CPP14_ASSERT(one_decamonth + ym == 2001_y/dec/last); + NOEXCEPT_CONVERSION(one_decamonth + ym); + CPP14_ASSERT(ym - one_decamonth == 2000_y/apr/last); + NOEXCEPT_CONVERSION(ym - one_decamonth); + CPP14_ASSERT((copy(ym) += one_decamonth) == 2001_y/dec/last); + NOEXCEPT_CONVERSION(copy(ym) += one_decamonth); + CPP14_ASSERT((copy(ym) -= one_decamonth) == 2000_y/apr/last); + NOEXCEPT_CONVERSION(copy(ym) -= one_decamonth); + + CPP14_ASSERT(ym + custom_month == 2001_y/mar/last); + NOEXCEPT_ASSERT(ym + custom_month); + CPP14_ASSERT(custom_month + ym == 2001_y/mar/last); + NOEXCEPT_ASSERT(custom_month + ym); + CPP14_ASSERT(ym - custom_month == 2001_y/jan/last); + NOEXCEPT_ASSERT(ym - custom_month); + CPP14_ASSERT((copy(ym) += custom_month) == 2001_y/mar/last); + NOEXCEPT_ASSERT(copy(ym) += custom_month); + CPP14_ASSERT((copy(ym) -= custom_month) == 2001_y/jan/last); + NOEXCEPT_ASSERT(copy(ym) -= custom_month); + + CPP11_ASSERT(ym + custom_year == 2002_y/feb/last); + NOEXCEPT_ASSERT(ym + custom_year); + CPP11_ASSERT(custom_year + ym == 2002_y/feb/last); + NOEXCEPT_ASSERT(custom_year + ym); + CPP11_ASSERT(ym - custom_year == 2000_y/feb/last); + NOEXCEPT_ASSERT(ym - custom_year); + CPP14_ASSERT((copy(ym) += custom_year) == 2002_y/feb/last); + NOEXCEPT_ASSERT(copy(ym) += custom_year); + CPP14_ASSERT((copy(ym) -= custom_year) == 2000_y/feb/last); + NOEXCEPT_ASSERT(copy(ym) -= custom_year); + + CPP11_ASSERT(ym + prefer_year == 2002_y/feb/last); + NOEXCEPT_ASSERT(ym + prefer_year); + CPP11_ASSERT(prefer_year + ym == 2002_y/feb/last); + NOEXCEPT_ASSERT(prefer_year + ym); + CPP11_ASSERT(ym - prefer_year == 2000_y/feb/last); + NOEXCEPT_ASSERT(ym - prefer_year); + CPP14_ASSERT((copy(ym) += prefer_year) == 2002_y/feb/last); + NOEXCEPT_ASSERT(copy(ym) += prefer_year); + CPP14_ASSERT((copy(ym) -= prefer_year) == 2000_y/feb/last); + NOEXCEPT_ASSERT(copy(ym) -= prefer_year); + } + + { + constexpr year_month_weekday ym = 2001_y/feb/fri[4]; + CPP14_ASSERT(ym + one_month == 2001_y/mar/fri[4]); + NOEXCEPT_ASSERT(ym + one_month); + CPP14_ASSERT(one_month + ym == 2001_y/mar/fri[4]); + NOEXCEPT_ASSERT(one_month + ym); + CPP14_ASSERT(ym - one_month == 2001_y/jan/fri[4]); + NOEXCEPT_ASSERT(ym - one_month); + CPP14_ASSERT((copy(ym) += one_month) == 2001_y/mar/fri[4]); + NOEXCEPT_ASSERT(copy(ym) += one_month); + CPP14_ASSERT((copy(ym) -= one_month) == 2001_y/jan/fri[4]); + NOEXCEPT_ASSERT(copy(ym) -= one_month); + + CPP11_ASSERT(ym + one_year == 2002_y/feb/fri[4]); + NOEXCEPT_ASSERT(ym + one_year); + CPP11_ASSERT(one_year + ym == 2002_y/feb/fri[4]); + NOEXCEPT_ASSERT(one_year + ym); + CPP11_ASSERT(ym - one_year == 2000_y/feb/fri[4]); + NOEXCEPT_ASSERT(ym - one_year); + CPP14_ASSERT((copy(ym) += one_year) == 2002_y/feb/fri[4]); + NOEXCEPT_ASSERT(copy(ym) += one_year); + CPP14_ASSERT((copy(ym) -= one_year) == 2000_y/feb/fri[4]); + NOEXCEPT_ASSERT(copy(ym) -= one_year); + + CPP11_ASSERT(ym + one_decade == 2011_y/feb/fri[4]); + NOEXCEPT_CONVERSION(ym + one_decade); + CPP11_ASSERT(one_decade + ym == 2011_y/feb/fri[4]); + NOEXCEPT_CONVERSION(one_decade + ym); + CPP11_ASSERT(ym - one_decade == 1991_y/feb/fri[4]); + NOEXCEPT_CONVERSION(ym - one_decade); + CPP14_ASSERT((copy(ym) += one_decade) == 2011_y/feb/fri[4]); + NOEXCEPT_CONVERSION(copy(ym) += one_decade); + CPP14_ASSERT((copy(ym) -= one_decade) == 1991_y/feb/fri[4]); + NOEXCEPT_CONVERSION(copy(ym) -= one_decade); + + CPP14_ASSERT(ym + one_decamonth == 2001_y/dec/fri[4]); + NOEXCEPT_CONVERSION(ym + one_decamonth); + CPP14_ASSERT(one_decamonth + ym == 2001_y/dec/fri[4]); + NOEXCEPT_CONVERSION(one_decamonth + ym); + CPP14_ASSERT(ym - one_decamonth == 2000_y/apr/fri[4]); + NOEXCEPT_CONVERSION(ym - one_decamonth); + CPP14_ASSERT((copy(ym) += one_decamonth) == 2001_y/dec/fri[4]); + NOEXCEPT_CONVERSION(copy(ym) += one_decamonth); + CPP14_ASSERT((copy(ym) -= one_decamonth) == 2000_y/apr/fri[4]); + NOEXCEPT_CONVERSION(copy(ym) -= one_decamonth); + + CPP14_ASSERT(ym + custom_month == 2001_y/mar/fri[4]); + NOEXCEPT_ASSERT(ym + custom_month); + CPP14_ASSERT(custom_month + ym == 2001_y/mar/fri[4]); + NOEXCEPT_ASSERT(custom_month + ym); + CPP14_ASSERT(ym - custom_month == 2001_y/jan/fri[4]); + NOEXCEPT_ASSERT(ym - custom_month); + CPP14_ASSERT((copy(ym) += custom_month) == 2001_y/mar/fri[4]); + NOEXCEPT_ASSERT(copy(ym) += custom_month); + CPP14_ASSERT((copy(ym) -= custom_month) == 2001_y/jan/fri[4]); + NOEXCEPT_ASSERT(copy(ym) -= custom_month); + + CPP11_ASSERT(ym + custom_year == 2002_y/feb/fri[4]); + NOEXCEPT_ASSERT(ym + custom_year); + CPP11_ASSERT(custom_year + ym == 2002_y/feb/fri[4]); + NOEXCEPT_ASSERT(custom_year + ym); + CPP11_ASSERT(ym - custom_year == 2000_y/feb/fri[4]); + NOEXCEPT_ASSERT(ym - custom_year); + CPP14_ASSERT((copy(ym) += custom_year) == 2002_y/feb/fri[4]); + NOEXCEPT_ASSERT(copy(ym) += custom_year); + CPP14_ASSERT((copy(ym) -= custom_year) == 2000_y/feb/fri[4]); + NOEXCEPT_ASSERT(copy(ym) -= custom_year); + + CPP11_ASSERT(ym + prefer_year == 2002_y/feb/fri[4]); + NOEXCEPT_ASSERT(ym + prefer_year); + CPP11_ASSERT(prefer_year + ym == 2002_y/feb/fri[4]); + NOEXCEPT_ASSERT(prefer_year + ym); + CPP11_ASSERT(ym - prefer_year == 2000_y/feb/fri[4]); + NOEXCEPT_ASSERT(ym - prefer_year); + CPP14_ASSERT((copy(ym) += prefer_year) == 2002_y/feb/fri[4]); + NOEXCEPT_ASSERT(copy(ym) += prefer_year); + CPP14_ASSERT((copy(ym) -= prefer_year) == 2000_y/feb/fri[4]); + NOEXCEPT_ASSERT(copy(ym) -= prefer_year); + } + + { + constexpr year_month_weekday_last ym = 2001_y/feb/fri[last]; + CPP14_ASSERT(ym + one_month == 2001_y/mar/fri[last]); + NOEXCEPT_ASSERT(ym + one_month); + CPP14_ASSERT(one_month + ym == 2001_y/mar/fri[last]); + NOEXCEPT_ASSERT(one_month + ym); + CPP14_ASSERT(ym - one_month == 2001_y/jan/fri[last]); + NOEXCEPT_ASSERT(ym - one_month); + CPP14_ASSERT((copy(ym) += one_month) == 2001_y/mar/fri[last]); + NOEXCEPT_ASSERT(copy(ym) += one_month); + CPP14_ASSERT((copy(ym) -= one_month) == 2001_y/jan/fri[last]); + NOEXCEPT_ASSERT(copy(ym) -= one_month); + + CPP11_ASSERT(ym + one_year == 2002_y/feb/fri[last]); + NOEXCEPT_ASSERT(ym + one_year); + CPP11_ASSERT(one_year + ym == 2002_y/feb/fri[last]); + NOEXCEPT_ASSERT(one_year + ym); + CPP11_ASSERT(ym - one_year == 2000_y/feb/fri[last]); + NOEXCEPT_ASSERT(ym - one_year); + CPP14_ASSERT((copy(ym) += one_year) == 2002_y/feb/fri[last]); + NOEXCEPT_ASSERT(copy(ym) += one_year); + CPP14_ASSERT((copy(ym) -= one_year) == 2000_y/feb/fri[last]); + NOEXCEPT_ASSERT(copy(ym) -= one_year); + + CPP11_ASSERT(ym + one_decade == 2011_y/feb/fri[last]); + NOEXCEPT_CONVERSION(ym + one_decade); + CPP11_ASSERT(one_decade + ym == 2011_y/feb/fri[last]); + NOEXCEPT_CONVERSION(one_decade + ym); + CPP11_ASSERT(ym - one_decade == 1991_y/feb/fri[last]); + NOEXCEPT_CONVERSION(ym - one_decade); + CPP14_ASSERT((copy(ym) += one_decade) == 2011_y/feb/fri[last]); + NOEXCEPT_CONVERSION(copy(ym) += one_decade); + CPP14_ASSERT((copy(ym) -= one_decade) == 1991_y/feb/fri[last]); + NOEXCEPT_CONVERSION(copy(ym) -= one_decade); + + CPP14_ASSERT(ym + one_decamonth == 2001_y/dec/fri[last]); + NOEXCEPT_CONVERSION(ym + one_decamonth); + CPP14_ASSERT(one_decamonth + ym == 2001_y/dec/fri[last]); + NOEXCEPT_CONVERSION(one_decamonth + ym); + CPP14_ASSERT(ym - one_decamonth == 2000_y/apr/fri[last]); + NOEXCEPT_CONVERSION(ym - one_decamonth); + CPP14_ASSERT((copy(ym) += one_decamonth) == 2001_y/dec/fri[last]); + NOEXCEPT_CONVERSION(copy(ym) += one_decamonth); + CPP14_ASSERT((copy(ym) -= one_decamonth) == 2000_y/apr/fri[last]); + NOEXCEPT_CONVERSION(copy(ym) -= one_decamonth); + + CPP14_ASSERT(ym + custom_month == 2001_y/mar/fri[last]); + NOEXCEPT_ASSERT(ym + custom_month); + CPP14_ASSERT(custom_month + ym == 2001_y/mar/fri[last]); + NOEXCEPT_ASSERT(custom_month + ym); + CPP14_ASSERT(ym - custom_month == 2001_y/jan/fri[last]); + NOEXCEPT_ASSERT(ym - custom_month); + CPP14_ASSERT((copy(ym) += custom_month) == 2001_y/mar/fri[last]); + NOEXCEPT_ASSERT(copy(ym) += custom_month); + CPP14_ASSERT((copy(ym) -= custom_month) == 2001_y/jan/fri[last]); + NOEXCEPT_ASSERT(copy(ym) -= custom_month); + + CPP11_ASSERT(ym + custom_year == 2002_y/feb/fri[last]); + NOEXCEPT_ASSERT(ym + custom_year); + CPP11_ASSERT(custom_year + ym == 2002_y/feb/fri[last]); + NOEXCEPT_ASSERT(custom_year + ym); + CPP11_ASSERT(ym - custom_year == 2000_y/feb/fri[last]); + NOEXCEPT_ASSERT(ym - custom_year); + CPP14_ASSERT((copy(ym) += custom_year) == 2002_y/feb/fri[last]); + NOEXCEPT_ASSERT(copy(ym) += custom_year); + CPP14_ASSERT((copy(ym) -= custom_year) == 2000_y/feb/fri[last]); + NOEXCEPT_ASSERT(copy(ym) -= custom_year); + + CPP11_ASSERT(ym + prefer_year == 2002_y/feb/fri[last]); + NOEXCEPT_ASSERT(ym + prefer_year); + CPP11_ASSERT(prefer_year + ym == 2002_y/feb/fri[last]); + NOEXCEPT_ASSERT(prefer_year + ym); + CPP11_ASSERT(ym - prefer_year == 2000_y/feb/fri[last]); + NOEXCEPT_ASSERT(ym - prefer_year); + CPP14_ASSERT((copy(ym) += prefer_year) == 2002_y/feb/fri[last]); + NOEXCEPT_ASSERT(copy(ym) += prefer_year); + CPP14_ASSERT((copy(ym) -= prefer_year) == 2000_y/feb/fri[last]); + NOEXCEPT_ASSERT(copy(ym) -= prefer_year); + } +} diff --git a/third_party/date/test/date_test/op_div_day_day.fail.cpp b/third_party/date/test/date_test/op_div_day_day.fail.cpp new file mode 100644 index 0000000..891f814 --- /dev/null +++ b/third_party/date/test/date_test/op_div_day_day.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// day / day not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = 14_d/14_d; +} diff --git a/third_party/date/test/date_test/op_div_int_month.fail.cpp b/third_party/date/test/date_test/op_div_int_month.fail.cpp new file mode 100644 index 0000000..1ecb3c1 --- /dev/null +++ b/third_party/date/test/date_test/op_div_int_month.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// int / month not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = 8/aug; +} diff --git a/third_party/date/test/date_test/op_div_int_year.fail.cpp b/third_party/date/test/date_test/op_div_int_year.fail.cpp new file mode 100644 index 0000000..74a31b7 --- /dev/null +++ b/third_party/date/test/date_test/op_div_int_year.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// int / year not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = 8/2015_y; +} diff --git a/third_party/date/test/date_test/op_div_last_last.fail.cpp b/third_party/date/test/date_test/op_div_last_last.fail.cpp new file mode 100644 index 0000000..2dca221 --- /dev/null +++ b/third_party/date/test/date_test/op_div_last_last.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// last / last not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = last/last; +} diff --git a/third_party/date/test/date_test/op_div_month_day.pass.cpp b/third_party/date/test/date_test/op_div_month_day.pass.cpp new file mode 100644 index 0000000..46062f4 --- /dev/null +++ b/third_party/date/test/date_test/op_div_month_day.pass.cpp @@ -0,0 +1,41 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// constexpr month_day operator/(const month& m, const day& d) noexcept; +// constexpr month_day operator/(const month& m, int d) noexcept; +// constexpr month_day operator/(int m, const day& d) noexcept; +// constexpr month_day operator/(const day& d, const month& m) noexcept; +// constexpr month_day operator/(const day& d, int m) noexcept; + +#include "date.h" + +int +main() +{ + using namespace date; + + static_assert( aug/14_d == month_day{month{8}, day{14}}, ""); + static_assert( aug/14 == month_day{month{8}, day{14}}, ""); + static_assert( 8/14_d == month_day{month{8}, day{14}}, ""); + static_assert(14_d/aug == month_day{month{8}, day{14}}, ""); + static_assert(14_d/8 == month_day{month{8}, day{14}}, ""); +} diff --git a/third_party/date/test/date_test/op_div_month_day_last.pass.cpp b/third_party/date/test/date_test/op_div_month_day_last.pass.cpp new file mode 100644 index 0000000..9de4538 --- /dev/null +++ b/third_party/date/test/date_test/op_div_month_day_last.pass.cpp @@ -0,0 +1,39 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// constexpr month_day_last operator/(const month& m, last_spec) noexcept; +// constexpr month_day_last operator/(int m, last_spec) noexcept; +// constexpr month_day_last operator/(last_spec, const month& m) noexcept; +// constexpr month_day_last operator/(last_spec, int m) noexcept; + +#include "date.h" + +int +main() +{ + using namespace date; + + static_assert( aug/last == month_day_last{month{8}}, ""); + static_assert( 8/last == month_day_last{month{8}}, ""); + static_assert(last/aug == month_day_last{month{8}}, ""); + static_assert(last/8 == month_day_last{month{8}}, ""); +} diff --git a/third_party/date/test/date_test/op_div_month_day_month_day.fail.cpp b/third_party/date/test/date_test/op_div_month_day_month_day.fail.cpp new file mode 100644 index 0000000..20fcf0f --- /dev/null +++ b/third_party/date/test/date_test/op_div_month_day_month_day.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// month_day / month_day not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = (aug/14_d)/(aug/14_d); +} diff --git a/third_party/date/test/date_test/op_div_month_month.fail.cpp b/third_party/date/test/date_test/op_div_month_month.fail.cpp new file mode 100644 index 0000000..85965a7 --- /dev/null +++ b/third_party/date/test/date_test/op_div_month_month.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// month / month not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = aug/aug; +} diff --git a/third_party/date/test/date_test/op_div_month_weekday.pass.cpp b/third_party/date/test/date_test/op_div_month_weekday.pass.cpp new file mode 100644 index 0000000..a2311fe --- /dev/null +++ b/third_party/date/test/date_test/op_div_month_weekday.pass.cpp @@ -0,0 +1,39 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// constexpr month_weekday operator/(const month& m, const weekday_indexed& wdi) noexcept; +// constexpr month_weekday operator/(int m, const weekday_indexed& wdi) noexcept; +// constexpr month_weekday operator/(const weekday_indexed& wdi, const month& m) noexcept; +// constexpr month_weekday operator/(const weekday_indexed& wdi, int m) noexcept; + +#include "date.h" + +int +main() +{ + using namespace date; + + static_assert( aug/fri[2] == month_weekday{month{8}, weekday_indexed{weekday{5u}, 2}}, ""); + static_assert( 8/fri[2] == month_weekday{month{8}, weekday_indexed{weekday{5u}, 2}}, ""); + static_assert(fri[2]/aug == month_weekday{month{8}, weekday_indexed{weekday{5u}, 2}}, ""); + static_assert(fri[2]/8 == month_weekday{month{8}, weekday_indexed{weekday{5u}, 2}}, ""); +} diff --git a/third_party/date/test/date_test/op_div_month_weekday_last.pass.cpp b/third_party/date/test/date_test/op_div_month_weekday_last.pass.cpp new file mode 100644 index 0000000..0024960 --- /dev/null +++ b/third_party/date/test/date_test/op_div_month_weekday_last.pass.cpp @@ -0,0 +1,39 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// constexpr month_weekday_last operator/(const month& m, const weekday_last& wdl) noexcept; +// constexpr month_weekday_last operator/(int m, const weekday_last& wdl) noexcept; +// constexpr month_weekday_last operator/(const weekday_last& wdl, const month& m) noexcept; +// constexpr month_weekday_last operator/(const weekday_last& wdl, int m) noexcept; + +#include "date.h" + +int +main() +{ + using namespace date; + + static_assert( aug/fri[last] == month_weekday_last{month{8}, weekday_last{weekday{5u}}}, ""); + static_assert( 8/fri[last] == month_weekday_last{month{8}, weekday_last{weekday{5u}}}, ""); + static_assert(fri[last]/aug == month_weekday_last{month{8}, weekday_last{weekday{5u}}}, ""); + static_assert(fri[last]/8 == month_weekday_last{month{8}, weekday_last{weekday{5u}}}, ""); +} diff --git a/third_party/date/test/date_test/op_div_month_year.fail.cpp b/third_party/date/test/date_test/op_div_month_year.fail.cpp new file mode 100644 index 0000000..c3af87f --- /dev/null +++ b/third_party/date/test/date_test/op_div_month_year.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// month / year not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = aug/2015_y; +} diff --git a/third_party/date/test/date_test/op_div_survey.pass.cpp b/third_party/date/test/date_test/op_div_survey.pass.cpp new file mode 100644 index 0000000..987850f --- /dev/null +++ b/third_party/date/test/date_test/op_div_survey.pass.cpp @@ -0,0 +1,437 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "date.h" + +#include + +template +constexpr +auto +test(I i, J j, K k) -> decltype(i/j/k) +{ + return i/j/k; +} + +void +test(...) +{ +} + +int +main() +{ + using std::is_same; + using namespace date; + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); +} diff --git a/third_party/date/test/date_test/op_div_weekday_indexed_weekday_indexed.fail.cpp b/third_party/date/test/date_test/op_div_weekday_indexed_weekday_indexed.fail.cpp new file mode 100644 index 0000000..38def30 --- /dev/null +++ b/third_party/date/test/date_test/op_div_weekday_indexed_weekday_indexed.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// weekday_indexed / weekday_indexed not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = fri[2]/fri[2]; +} diff --git a/third_party/date/test/date_test/op_div_weekday_last_weekday_last.fail.cpp b/third_party/date/test/date_test/op_div_weekday_last_weekday_last.fail.cpp new file mode 100644 index 0000000..c4dba10 --- /dev/null +++ b/third_party/date/test/date_test/op_div_weekday_last_weekday_last.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// weekday_last / weekday_last not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = fri[last]/fri[last]; +} diff --git a/third_party/date/test/date_test/op_div_year_month.pass.cpp b/third_party/date/test/date_test/op_div_year_month.pass.cpp new file mode 100644 index 0000000..48ff6c6 --- /dev/null +++ b/third_party/date/test/date_test/op_div_year_month.pass.cpp @@ -0,0 +1,35 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// constexpr year_month operator/(const year& y, const month& m) noexcept; +// constexpr year_month operator/(const year& y, int m) noexcept; + +#include "date.h" + +int +main() +{ + using namespace date; + + static_assert(2015_y/aug == year_month{year{2015}, aug}, ""); + static_assert(2015_y/8 == year_month{year{2015}, aug}, ""); +} diff --git a/third_party/date/test/date_test/op_div_year_month_day.pass.cpp b/third_party/date/test/date_test/op_div_year_month_day.pass.cpp new file mode 100644 index 0000000..96baa3f --- /dev/null +++ b/third_party/date/test/date_test/op_div_year_month_day.pass.cpp @@ -0,0 +1,43 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// constexpr year_month_day operator/(const year_month& ym, const day& d) noexcept; +// constexpr year_month_day operator/(const year_month& ym, int d) noexcept; +// constexpr year_month_day operator/(const year& y, const month_day& md) noexcept; +// constexpr year_month_day operator/(int y, const month_day& md) noexcept; +// constexpr year_month_day operator/(const month_day& md, const year& y) noexcept; +// constexpr year_month_day operator/(const month_day& md, int y) noexcept; + +#include "date.h" + +int +main() +{ + using namespace date; + + static_assert( 2015_y/aug/14_d == year_month_day{year{2015}, month{8}, day{14}}, ""); + static_assert( 2015_y/aug/14 == year_month_day{year{2015}, month{8}, day{14}}, ""); + static_assert( 2015_y/(aug/14_d) == year_month_day{year{2015}, month{8}, day{14}}, ""); + static_assert( 2015/(aug/14_d) == year_month_day{year{2015}, month{8}, day{14}}, ""); + static_assert(aug/14_d/2015_y == year_month_day{year{2015}, month{8}, day{14}}, ""); + static_assert(aug/14_d/2015 == year_month_day{year{2015}, month{8}, day{14}}, ""); +} diff --git a/third_party/date/test/date_test/op_div_year_month_day_last.pass.cpp b/third_party/date/test/date_test/op_div_year_month_day_last.pass.cpp new file mode 100644 index 0000000..f98993b --- /dev/null +++ b/third_party/date/test/date_test/op_div_year_month_day_last.pass.cpp @@ -0,0 +1,41 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// constexpr year_month_day_last operator/(const year_month& ym, last_spec) noexcept; +// constexpr year_month_day_last operator/(const year& y, const month_day_last& mdl) noexcept; +// constexpr year_month_day_last operator/(int y, const month_day_last& mdl) noexcept; +// constexpr year_month_day_last operator/(const month_day_last& mdl, const year& y) noexcept; +// constexpr year_month_day_last operator/(const month_day_last& mdl, int y) noexcept; + +#include "date.h" + +int +main() +{ + using namespace date; + + static_assert(2015_y/aug/last == year_month_day_last{year{2015}, month_day_last{month{8}}}, ""); + static_assert( 2015_y/(aug/last) == year_month_day_last{year{2015}, month_day_last{month{8}}}, ""); + static_assert( 2015/(aug/last) == year_month_day_last{year{2015}, month_day_last{month{8}}}, ""); + static_assert( aug/last/2015_y == year_month_day_last{year{2015}, month_day_last{month{8}}}, ""); + static_assert( aug/last/2015 == year_month_day_last{year{2015}, month_day_last{month{8}}}, ""); +} diff --git a/third_party/date/test/date_test/op_div_year_month_weekday.pass.cpp b/third_party/date/test/date_test/op_div_year_month_weekday.pass.cpp new file mode 100644 index 0000000..90f2f55 --- /dev/null +++ b/third_party/date/test/date_test/op_div_year_month_weekday.pass.cpp @@ -0,0 +1,41 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// constexpr year_month_weekday operator/(const year_month& ym, const weekday_indexed& wdi) noexcept; +// constexpr year_month_weekday operator/(const year& y, const month_weekday& mwd) noexcept; +// constexpr year_month_weekday operator/(int y, const month_weekday& mwd) noexcept; +// constexpr year_month_weekday operator/(const month_weekday& mwd, const year& y) noexcept; +// constexpr year_month_weekday operator/(const month_weekday& mwd, int y) noexcept; + +#include "date.h" + +int +main() +{ + using namespace date; + + static_assert(2015_y/aug/fri[2] == year_month_weekday{year{2015}, month{8}, weekday_indexed{weekday{5u}, 2}}, ""); + static_assert( 2015_y/(aug/fri[2]) == year_month_weekday{year{2015}, month{8}, weekday_indexed{weekday{5u}, 2}}, ""); + static_assert( 2015/(aug/fri[2]) == year_month_weekday{year{2015}, month{8}, weekday_indexed{weekday{5u}, 2}}, ""); + static_assert(aug/fri[2]/2015_y == year_month_weekday{year{2015}, month{8}, weekday_indexed{weekday{5u}, 2}}, ""); + static_assert(aug/fri[2]/2015 == year_month_weekday{year{2015}, month{8}, weekday_indexed{weekday{5u}, 2}}, ""); +} diff --git a/third_party/date/test/date_test/op_div_year_month_weekday_last.pass.cpp b/third_party/date/test/date_test/op_div_year_month_weekday_last.pass.cpp new file mode 100644 index 0000000..63f8066 --- /dev/null +++ b/third_party/date/test/date_test/op_div_year_month_weekday_last.pass.cpp @@ -0,0 +1,41 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// constexpr year_month_weekday_last operator/(const year_month& ym, const weekday_last& wdl) noexcept; +// constexpr year_month_weekday_last operator/(const year& y, const month_weekday_last& mwdl) noexcept; +// constexpr year_month_weekday_last operator/(int y, const month_weekday_last& mwdl) noexcept; +// constexpr year_month_weekday_last operator/(const month_weekday_last& mwdl, const year& y) noexcept; +// constexpr year_month_weekday_last operator/(const month_weekday_last& mwdl, int y) noexcept; + +#include "date.h" + +int +main() +{ + using namespace date; + + static_assert( 2015_y/aug/fri[last] == year_month_weekday_last{year{2015}, month{8}, weekday_last{weekday{5u}}}, ""); + static_assert( 2015_y/(aug/fri[last]) == year_month_weekday_last{year{2015}, month{8}, weekday_last{weekday{5u}}}, ""); + static_assert( 2015/(aug/fri[last]) == year_month_weekday_last{year{2015}, month{8}, weekday_last{weekday{5u}}}, ""); + static_assert(aug/fri[last]/2015_y == year_month_weekday_last{year{2015}, month{8}, weekday_last{weekday{5u}}}, ""); + static_assert(aug/fri[last]/2015 == year_month_weekday_last{year{2015}, month{8}, weekday_last{weekday{5u}}}, ""); +} diff --git a/third_party/date/test/date_test/op_div_year_month_year_month.fail.cpp b/third_party/date/test/date_test/op_div_year_month_year_month.fail.cpp new file mode 100644 index 0000000..73a9208 --- /dev/null +++ b/third_party/date/test/date_test/op_div_year_month_year_month.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// year_month / year_month not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = (2015_y/aug)/(2015_y/aug); +} diff --git a/third_party/date/test/date_test/op_div_year_year.fail.cpp b/third_party/date/test/date_test/op_div_year_year.fail.cpp new file mode 100644 index 0000000..c7054d0 --- /dev/null +++ b/third_party/date/test/date_test/op_div_year_year.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// year / year not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = 2015_y/2015_y; +} diff --git a/third_party/date/test/date_test/parse.pass.cpp b/third_party/date/test/date_test/parse.pass.cpp new file mode 100644 index 0000000..a7fecfd --- /dev/null +++ b/third_party/date/test/date_test/parse.pass.cpp @@ -0,0 +1,921 @@ +// The MIT License (MIT) +// +// Copyright (c) 2016 Howard Hinnant +// +// 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. + +// This test is meant to maintain a record of the sizeof each type. + +#include "date.h" +#include +#include + +void +test_a() +{ + using namespace date; + { + // correct abbreviation + std::istringstream in{"Sun 2016-12-11"}; + sys_days tp; + in >> parse("%a %F", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(!in.eof()); + assert(tp == 2016_y/12/11); + } + { + // correct abbreviation + std::istringstream in{"Sun 2016-12-11"}; + sys_days tp; + in >> parse("%A %F", tp); + // this may fail with libstdc++, see https://github.com/HowardHinnant/date/issues/388 + // possible workaround: compile date.h with -DONLY_C_LOCALE=1 + assert(!in.fail()); + assert(!in.bad()); + assert(!in.eof()); + assert(tp == 2016_y/12/11); + } + { + // correct full name + std::istringstream in{"Sunday 2016-12-11"}; + sys_days tp; + in >> parse("%a %F", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(!in.eof()); + assert(tp == 2016_y/12/11); + } + { + // correct full name + std::istringstream in{"Sunday 2016-12-11"}; + sys_days tp; + in >> parse("%A %F", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(!in.eof()); + assert(tp == 2016_y/12/11); + } + { + // not a valid name + std::istringstream in{"Dec 2016-12-11"}; + sys_days tp; + in >> parse("%a %F", tp); + assert( in.fail()); + assert(!in.bad()); + assert(!in.eof()); + assert(tp == 1970_y/1/1); + } + { + // wrong name + std::istringstream in{"Sat 2016-12-11"}; + sys_days tp; + in >> parse("%a %F", tp); + assert( in.fail()); + assert(!in.bad()); + assert(!in.eof()); + assert(tp == 1970_y/1/1); + } + { + // extra ws in input + std::istringstream in{"Sun 2016-12-11"}; + sys_days tp; + in >> parse("%a %F", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(!in.eof()); + assert(tp == 2016_y/12/11); + } + { + // extra ws in format + std::istringstream in{"Sun 2016-12-11"}; + sys_days tp; + in >> parse("%a %F", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(!in.eof()); + assert(tp == 2016_y/12/11); + } +} + +void +test_b() +{ + using namespace date; + { + // correct abbreviation + std::istringstream in{"Dec 11 2016"}; + sys_days tp; + in >> parse("%b %d %Y", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(!in.eof()); + assert(tp == 2016_y/12/11); + } + { + // correct abbreviation + std::istringstream in{"Dec 11 2016"}; + sys_days tp; + in >> parse("%B %d %Y", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(!in.eof()); + assert(tp == 2016_y/12/11); + } + { + // correct abbreviation + std::istringstream in{"Dec 11 2016"}; + sys_days tp; + in >> parse("%h %d %Y", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(!in.eof()); + assert(tp == 2016_y/12/11); + } + { + // correct full name + std::istringstream in{"December 11 2016"}; + sys_days tp; + in >> parse("%b %d %Y", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(!in.eof()); + assert(tp == 2016_y/12/11); + } + { + // correct full name + std::istringstream in{"December 11 2016"}; + sys_days tp; + in >> parse("%B %d %Y", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(!in.eof()); + assert(tp == 2016_y/12/11); + } + { + // correct full name + std::istringstream in{"December 11 2016"}; + sys_days tp; + in >> parse("%h %d %Y", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(!in.eof()); + assert(tp == 2016_y/12/11); + } + { + // incorrect abbreviation + std::istringstream in{"Dece 11 2016"}; + sys_days tp; + in >> parse("%b %d %Y", tp); + assert( in.fail()); + assert(!in.bad()); + assert(!in.eof()); + assert(tp == 1970_y/1/1); + } +} + +void +test_c() +{ + using namespace date; + using namespace std::chrono; + { + // correct abbreviation + std::istringstream in{"Sun Dec 11 14:02:43 2016"}; + sys_seconds tp; + in >> parse("%c", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/11} + hours{14} + minutes{2} + seconds{43}); + } +} + +void +test_x() +{ + using namespace date; + using namespace std::chrono; + { + // correct abbreviation + std::istringstream in{"12/11/16"}; + sys_seconds tp; + in >> parse("%x", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/11}); + } +} + +void +test_X() +{ + using namespace date; + using namespace std::chrono; + { + // correct abbreviation + std::istringstream in{"2016-12-11 14:02:43"}; + sys_seconds tp; + in >> parse("%F %X", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/11} + hours{14} + minutes{2} + seconds{43}); + } +} + +void +test_C() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"20 16 12 11"}; + sys_days tp; + in >> parse("%C %y %m %d", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == 2016_y/12/11); + } + { + std::istringstream in{"-2 1 12 11"}; + sys_days tp; + in >> parse("%C %y %m %d", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == -101_y/12/11); + } + { + std::istringstream in{"-1 0 12 11"}; + sys_days tp; + in >> parse("%C %y %m %d", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == -100_y/12/11); + } + { + std::istringstream in{"-1 99 12 11"}; + sys_days tp; + in >> parse("%C %y %m %d", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == -99_y/12/11); + } + { + std::istringstream in{"-1 1 12 11"}; + sys_days tp; + in >> parse("%C %y %m %d", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == -1_y/12/11); + } + { + std::istringstream in{"0 0 12 11"}; + sys_days tp; + in >> parse("%C %y %m %d", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == 0_y/12/11); + } + { + std::istringstream in{"0 1 12 11"}; + sys_days tp; + in >> parse("%C %y %m %d", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == 1_y/12/11); + } + { + std::istringstream in{"0 99 12 11"}; + sys_days tp; + in >> parse("%C %y %m %d", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == 99_y/12/11); + } + { + std::istringstream in{"1 0 12 11"}; + sys_days tp; + in >> parse("%C %y %m %d", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == 100_y/12/11); + } + { + std::istringstream in{"1 1 12 11"}; + sys_days tp; + in >> parse("%C %y %m %d", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == 101_y/12/11); + } +} + +void +test_d() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"2016 09 12"}; + sys_days tp; + in >> parse("%Y %d %m", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == 2016_y/12/9); + } + { + std::istringstream in{"2016 09 12"}; + sys_days tp; + in >> parse("%Y %e %m", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == 2016_y/12/9); + } + { + std::istringstream in{"2016 9 12"}; + sys_days tp; + in >> parse("%Y %d %m", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == 2016_y/12/9); + } + { + std::istringstream in{"2016 9 12"}; + sys_days tp; + in >> parse("%Y %e %m", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == 2016_y/12/9); + } + { + std::istringstream in{"2016 31 11"}; + sys_days tp; + in >> parse("%Y %e %m", tp); + assert(in.fail()); + } +} + +void +test_D() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"12/11/16"}; + sys_days tp; + in >> parse("%D", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == 2016_y/12/11); + } +} + +void +test_F() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"2016-12-13"}; + sys_days tp; + in >> parse("%F", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == 2016_y/12/13); + } + { + std::istringstream in{"2016-12-13"}; + year_month_day tp; + in >> parse("%F", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == 2016_y/12/13); + } +} + +void +test_H() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"2016-12-11 15"}; + sys_time tp; + in >> parse("%F %H", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/11} + hours{15}); + } + { + std::istringstream in{"2016-12-11 24"}; + sys_time tp; + in >> parse("%F %H", tp); + assert(in.fail()); + } +} + +void +test_Ip() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"2016-12-11 1 pm"}; + sys_time tp; + in >> parse("%F %I %p", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/11} + hours{13}); + } + { + std::istringstream in{"2016-12-11 1 am"}; + sys_time tp; + in >> parse("%F %I %p", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/11} + hours{1}); + } + { + std::istringstream in{"2016-12-11 13 am"}; + sys_time tp; + in >> parse("%F %I %p", tp); + assert(in.fail()); + } +} + +void +test_j() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"2016 361"}; + sys_days tp; + in >> parse("%Y %j", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/26}); + } +} + +void +test_m() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"2016 12 09"}; + sys_days tp; + in >> parse("%Y %d %m", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == 2016_y/9/12); + } + { + std::istringstream in{"2016 12 9"}; + sys_days tp; + in >> parse("%Y %d %m", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == 2016_y/9/12); + } + { + std::istringstream in{"2016 12 13"}; + sys_days tp; + in >> parse("%Y %d %m", tp); + assert(in.fail()); + } +} + +void +test_M() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"2016-12-11 15"}; + sys_time tp; + in >> parse("%F %M", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/11} + minutes{15}); + } + { + std::istringstream in{"2016-12-11 65"}; + sys_time tp; + in >> parse("%F %M", tp); + assert(in.fail()); + } +} + +void +test_S() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"2016-12-11 15"}; + sys_seconds tp; + in >> parse("%F %S", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/11} + seconds{15}); + } + { + std::istringstream in{"2016-12-11 15.001"}; + sys_time tp; + in >> parse("%F %S", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/11} + seconds{15} + milliseconds{1}); + } + { + std::istringstream in{"2016-12-11 60"}; + sys_seconds tp; + in >> parse("%F %S", tp); + assert(in.fail()); + } +} + +void +test_T() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"2016-12-11 15:43:22"}; + sys_seconds tp; + in >> parse("%F %T", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/11} + hours{15} + minutes{43} + seconds{22}); + } + { + std::istringstream in{"2016-12-11 15:43:22.001"}; + sys_time tp; + in >> parse("%F %T", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/11} + hours{15} + minutes{43} + seconds{22} + + milliseconds{1}); + } + { + std::istringstream in{"2016-12-11 15:43:22"}; + sys_time tp; + in >> parse("%F %T", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/11} + hours{15} + minutes{43} + seconds{22}); + } + { + std::istringstream in{"15:43:22.001"}; + milliseconds d; + in >> parse("%T", d); + assert(!in.fail()); + assert(!in.bad()); + assert(d == hours{15} + minutes{43} + seconds{22} + milliseconds{1}); + } + { + std::istringstream in{"2016-12-11 24:43:22"}; + sys_seconds tp; + in >> parse("%F %T", tp); + assert(in.fail()); + } + { + std::istringstream in{"2016-12-11 15:60:22"}; + sys_seconds tp; + in >> parse("%F %T", tp); + assert(in.fail()); + } + { + std::istringstream in{"2016-12-11 15:43:60"}; + sys_seconds tp; + in >> parse("%F %T", tp); + assert(in.fail()); + } +} + +void +test_p() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"2016-12-11 11pm"}; + sys_time tp; + in >> parse("%F %I%p", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/11} + hours{23}); + } + { + std::istringstream in{"1986-12-01 01:01:01 pm"}; + sys_time tp; + in >> parse("%Y-%m-%d %I:%M:%S %p", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{1986_y/12/01} + hours{13} + minutes{01} + seconds{01}); + } + { + std::istringstream in{"1986-12-01 01:01:01"}; + sys_time tp; + in >> parse("%Y-%m-%d %I:%M:%S", tp); + // The test will fail because %I needs the %p option to shows if it is AM or PM + assert(in.fail()); + } +} + +void +test_r() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"2016-12-26 1:36:57 pm"}; + sys_seconds tp; + in >> parse("%F %r", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/26} + hours{13} + minutes{36} + seconds{57}); + } +} + +void +test_R() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"2016-12-26 13:36"}; + sys_seconds tp; + in >> parse("%F %R", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/26} + hours{13} + minutes{36}); + } +} + +void +test_U() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"2016-52-1"}; + sys_days tp; + in >> parse("%Y-%U-%w", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/26}); + } +} + +void +test_W() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"2016-52-1"}; + sys_days tp; + in >> parse("%Y-%W-%w", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/26}); + } +} + +void +test_GV() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"2016-52-1"}; + sys_days tp; + in >> parse("%G-%V-%w", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/26}); + } + { + std::istringstream in{"2016-52-1"}; + sys_days tp; + in >> parse("%G-%V-%w", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/26}); + } + { + std::istringstream in{"20 16-52-1"}; + sys_days tp; + in >> parse("%C %g-%V-%w", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/26}); + } + { + std::istringstream in{"20 16-52-1"}; + sys_days tp; + in >> parse("%C %g-%V-%u", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/26}); + } +} + +void +test_z() +{ + using namespace date; + using namespace std::chrono; + { + std::istringstream in{"2016-12-26 15:53:22 -0500"}; + sys_seconds tp; + in >> parse("%F %T %z", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/26} + hours{20} + minutes{53} + seconds{22}); + } + { + std::istringstream in{"2016-12-26 15:53:22 -0500"}; + local_seconds tp; + in >> parse("%F %T %z", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == local_days{2016_y/12/26} + hours{15} + minutes{53} + seconds{22}); + } + { + std::istringstream in{"2016-12-26 15:53:22 -05:00"}; + sys_seconds tp; + in >> parse("%F %T %Ez", tp); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == sys_days{2016_y/12/26} + hours{20} + minutes{53} + seconds{22}); + } +} + +void +test_Z() +{ + using namespace date; + using namespace std::chrono; + { + std::string a; + std::istringstream in{"2016-12-26 15:53:22 word"}; + local_seconds tp; + in >> parse("%F %T %Z", tp, a); + assert(!in.fail()); + assert(!in.bad()); + assert(tp == local_days{2016_y/12/26} + hours{15} + minutes{53} + seconds{22}); + assert(a == "word"); + } +} + +void +test_trailing_Z() +{ + std::string format = "%FT%TZ"; + std::string datetime = "2017-2-15T13:13:13"; + std::istringstream input(datetime); + date::sys_seconds tp; + input >> date::parse(format, tp); + assert(input.fail()); + assert(input.eof()); +} + +void +test_leading_ws() +{ + using namespace std; + using namespace date; + istringstream in{"05/04/17 5/4/17"}; + year_month_day d1, d2; + in >> parse("%D", d1) >> parse("%n%D", d2); + assert(d1 == may/4/2017); + assert(d2 == may/4/2017); +} + +void +test_space() +{ + using namespace std; + using namespace date; + { + istringstream in{"05/04/17"}; + year_month_day d1; + in >> parse(" %D", d1); + assert(d1 == may/4/2017); + } + { + istringstream in{" 05/04/17"}; + year_month_day d1; + in >> parse(" %D", d1); + assert(d1 == may/4/2017); + } + { + istringstream in{" 05/04/17"}; + year_month_day d1; + in >> parse(" %D", d1); + assert(d1 == may/4/2017); + } +} + +void +test_n() +{ + using namespace std; + using namespace date; + { + istringstream in{"05/04/17"}; + year_month_day d1; + in >> parse("%n%D", d1); + assert(in.fail()); + } + { + istringstream in{" 05/04/17"}; + year_month_day d1; + in >> parse("%n%D", d1); + assert(d1 == may/4/2017); + } + { + istringstream in{" 05/04/17"}; + year_month_day d1; + in >> parse("%n%D", d1); + assert(in.fail()); + } +} + +void +test_t() +{ + using namespace std; + using namespace date; + { + istringstream in{"05/04/17"}; + year_month_day d1; + in >> parse("%t%D", d1); + assert(d1 == may/4/2017); + } + { + istringstream in{" 05/04/17"}; + year_month_day d1; + in >> parse("%t%D", d1); + assert(d1 == may/4/2017); + } + { + istringstream in{" 05/04/17"}; + year_month_day d1; + in >> parse("%t%D", d1); + assert(in.fail()); + } +} + +int +main() +{ + test_a(); + test_b(); + test_c(); + test_C(); + test_d(); + test_D(); + test_F(); + test_H(); + test_Ip(); + test_j(); + test_m(); + test_M(); + test_p(); + test_r(); + test_R(); + test_S(); + test_T(); + test_U(); + test_W(); + test_GV(); + test_x(); + test_X(); + test_z(); + test_Z(); + test_trailing_Z(); + test_leading_ws(); + test_space(); + test_n(); + test_t(); +} diff --git a/third_party/date/test/date_test/sizeof.pass.cpp b/third_party/date/test/date_test/sizeof.pass.cpp new file mode 100644 index 0000000..1d91b66 --- /dev/null +++ b/third_party/date/test/date_test/sizeof.pass.cpp @@ -0,0 +1,62 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// This test is meant to maintain a record of the sizeof each type. + +#include "date.h" + +int +main() +{ + using namespace date; + + static_assert(sizeof(days) == 4, ""); + static_assert(sizeof(weeks) == 4, ""); + static_assert(sizeof(months) == 4, ""); + static_assert(sizeof(years) == 4, ""); + + static_assert(sizeof(sys_days) == 4, ""); + + static_assert(sizeof(last_spec) == 1, ""); + + static_assert(sizeof(day) == 1, ""); + static_assert(sizeof(month) == 1, ""); + static_assert(sizeof(year) == 2, ""); + + static_assert(sizeof(weekday) == 1, ""); + static_assert(sizeof(weekday_indexed) == 1, ""); + static_assert(sizeof(weekday_last) == 1, ""); + + static_assert(sizeof(month_day) == 2, ""); + static_assert(sizeof(month_day_last) == 1, ""); + static_assert(sizeof(month_weekday) == 2, ""); + static_assert(sizeof(month_weekday_last) == 2, ""); + + static_assert(sizeof(year_month) == 4, ""); + + static_assert(sizeof(year_month_day) == 4, ""); + static_assert(sizeof(year_month_day_last) == 4, ""); + static_assert(sizeof(year_month_weekday) == 4, ""); + static_assert(sizeof(year_month_weekday_last) == 4, ""); + + // sizeof time_of_day varies +} diff --git a/third_party/date/test/date_test/time_of_day_hours.pass.cpp b/third_party/date/test/date_test/time_of_day_hours.pass.cpp new file mode 100644 index 0000000..5b12429 --- /dev/null +++ b/third_party/date/test/date_test/time_of_day_hours.pass.cpp @@ -0,0 +1,94 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// enum {am = 1, pm}; + +// class time_of_day +// { +// public: +// using precision = std::chrono::hours; +// +// constexpr explicit time_of_day(std::chrono::hours since_midnight) noexcept; +// constexpr time_of_day(std::chrono::hours h, unsigned md) noexcept; +// +// constexpr std::chrono::hours hours() const noexcept; +// constexpr unsigned mode() const noexcept; +// +// constexpr explicit operator precision() const noexcept; +// constexpr precision to_duration() const noexcept; +// +// void make24() noexcept; +// void make12() noexcept; +// }; + +// std::ostream& operator<<(std::ostream& os, const time_of_day& t); + +#include "date.h" + +#include +#include +#include + +int +main() +{ + using namespace date; + using namespace std; + using namespace std::chrono; + + using tod = time_of_day; + + static_assert(is_same{}, ""); + + static_assert( is_trivially_destructible{}, ""); + static_assert( is_default_constructible{}, ""); + static_assert( is_trivially_copy_constructible{}, ""); + static_assert( is_trivially_copy_assignable{}, ""); + static_assert( is_trivially_move_constructible{}, ""); + static_assert( is_trivially_move_assignable{}, ""); + + static_assert(is_nothrow_constructible{}, ""); + static_assert(!is_convertible{}, ""); + + static_assert(is_nothrow_constructible{}, ""); + static_assert(!is_convertible{}, ""); + + constexpr tod t1 = tod{hours{13}}; + static_assert(t1.hours() == hours{13}, ""); +#if __cplusplus >= 201402 + static_assert(static_cast(t1) == hours{13}, ""); + static_assert(t1.to_duration() == hours{13}, ""); +#endif + + auto t2 = t1; + assert(t2.hours() == t1.hours()); + assert(t2.to_duration() == t1.to_duration()); + ostringstream os; + os << t2; + assert(os.str() == "13:00:00"); + auto h = make12(t2.hours()); + os.str(""); + assert(h == hours{1}); + assert(t2.to_duration() == t1.to_duration()); + assert(!is_am(t2.hours())); + assert(is_pm(t2.hours())); +} diff --git a/third_party/date/test/date_test/time_of_day_microfortnights.pass.cpp b/third_party/date/test/date_test/time_of_day_microfortnights.pass.cpp new file mode 100644 index 0000000..362c793 --- /dev/null +++ b/third_party/date/test/date_test/time_of_day_microfortnights.pass.cpp @@ -0,0 +1,111 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// enum {am = 1, pm}; + +// template +// class time_of_day> +// { +// public: +// using precision = std::chrono::std::chrono::duration; +// +// constexpr explicit time_of_day(precision since_midnight) noexcept; +// constexpr time_of_day(std::chrono::hours h, std::chrono::minutes m, +// std::chrono::seconds s, precision sub_s, +// unsigned md) noexcept; +// +// constexpr std::chrono::hours hours() const noexcept; +// constexpr std::chrono::minutes minutes() const noexcept; +// constexpr std::chrono::seconds seconds() const noexcept; +// constexpr precision subseconds() const noexcept; +// constexpr unsigned mode() const noexcept; +// +// constexpr explicit operator precision() const noexcept; +// constexpr precision to_duration() const noexcept; +// +// void make24() noexcept; +// void make12() noexcept; +// }; + +// template +// std::ostream& +// operator<<(std::ostream& os, const time_of_day>& t); + +#include "date.h" + +#include +#include +#include + +using fortnights = std::chrono::duration, + date::weeks::period>>; + +using microfortnights = std::chrono::duration>; + +int +main() +{ + using namespace date; + using namespace std; + using namespace std::chrono; + + using tod = time_of_day::type>; + + static_assert(is_same>{}, ""); + + static_assert( is_trivially_destructible{}, ""); + static_assert( is_default_constructible{}, ""); + static_assert( is_trivially_copy_constructible{}, ""); + static_assert( is_trivially_copy_assignable{}, ""); + static_assert( is_trivially_move_constructible{}, ""); + static_assert( is_trivially_move_assignable{}, ""); + + static_assert(is_constructible{}, ""); + static_assert(!is_convertible{}, ""); + + static_assert(is_nothrow_constructible{}, ""); + static_assert(!is_convertible{}, ""); + + constexpr tod t1 = tod{hours{13} + minutes{7} + microfortnights{5}}; + static_assert(t1.hours() == hours{13}, ""); + static_assert(t1.minutes() == minutes{7}, ""); + static_assert(t1.seconds() == seconds{6}, ""); + static_assert(t1.subseconds() == tod::precision{480}, ""); +#if __cplusplus >= 201402 + static_assert(static_cast(t1) == hours{13} + minutes{7} + + microfortnights{5}, ""); + static_assert(t1.to_duration() == hours{13} + minutes{7} + microfortnights{5}, ""); +#endif + + auto t2 = t1; + assert(t2.hours() == t1.hours()); + assert(t2.minutes() == t1.minutes()); + assert(t2.seconds() == t1.seconds()); + assert(t2.subseconds() == t1.subseconds()); + assert(t2.to_duration() == t1.to_duration()); + ostringstream os; + os << t2; + assert(os.str() == "13:07:06.0480"); +} diff --git a/third_party/date/test/date_test/time_of_day_milliseconds.pass.cpp b/third_party/date/test/date_test/time_of_day_milliseconds.pass.cpp new file mode 100644 index 0000000..c13fe4c --- /dev/null +++ b/third_party/date/test/date_test/time_of_day_milliseconds.pass.cpp @@ -0,0 +1,104 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// enum {am = 1, pm}; + +// template +// class time_of_day> +// { +// public: +// using precision = std::chrono::std::chrono::duration; +// +// constexpr explicit time_of_day(precision since_midnight) noexcept; +// constexpr time_of_day(std::chrono::hours h, std::chrono::minutes m, +// std::chrono::seconds s, precision sub_s, +// unsigned md) noexcept; +// +// constexpr std::chrono::hours hours() const noexcept; +// constexpr std::chrono::minutes minutes() const noexcept; +// constexpr std::chrono::seconds seconds() const noexcept; +// constexpr precision subseconds() const noexcept; +// constexpr unsigned mode() const noexcept; +// +// constexpr explicit operator precision() const noexcept; +// constexpr precision to_duration() const noexcept; +// +// void make24() noexcept; +// void make12() noexcept; +// }; + +// template +// std::ostream& +// operator<<(std::ostream& os, const time_of_day>& t); + +#include "date.h" + +#include +#include +#include + +int +main() +{ + using namespace date; + using namespace std; + using namespace std::chrono; + + using tod = time_of_day; + + static_assert(is_same{}, ""); + + static_assert( is_trivially_destructible{}, ""); + static_assert( is_default_constructible{}, ""); + static_assert( is_trivially_copy_constructible{}, ""); + static_assert( is_trivially_copy_assignable{}, ""); + static_assert( is_trivially_move_constructible{}, ""); + static_assert( is_trivially_move_assignable{}, ""); + + static_assert(is_nothrow_constructible{}, ""); + static_assert(!is_convertible{}, ""); + + static_assert(is_nothrow_constructible{}, ""); + static_assert(!is_convertible{}, ""); + + constexpr tod t1 = tod{hours{13} + minutes{7} + seconds{5} + milliseconds{22}}; + static_assert(t1.hours() == hours{13}, ""); + static_assert(t1.minutes() == minutes{7}, ""); + static_assert(t1.seconds() == seconds{5}, ""); + static_assert(t1.subseconds() == milliseconds{22}, ""); +#if __cplusplus >= 201402 + static_assert(static_cast(t1) == hours{13} + minutes{7} + + seconds{5} + milliseconds{22}, ""); + static_assert(t1.to_duration() == hours{13} + minutes{7} + seconds{5} + + milliseconds{22}, ""); +#endif + + auto t2 = t1; + assert(t2.hours() == t1.hours()); + assert(t2.minutes() == t1.minutes()); + assert(t2.seconds() == t1.seconds()); + assert(t2.subseconds() == t1.subseconds()); + assert(t2.to_duration() == t1.to_duration()); + ostringstream os; + os << t2; + assert(os.str() == "13:07:05.022"); +} diff --git a/third_party/date/test/date_test/time_of_day_minutes.pass.cpp b/third_party/date/test/date_test/time_of_day_minutes.pass.cpp new file mode 100644 index 0000000..47cdafc --- /dev/null +++ b/third_party/date/test/date_test/time_of_day_minutes.pass.cpp @@ -0,0 +1,92 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// enum {am = 1, pm}; + +// class time_of_day +// { +// public: +// using precision = std::chrono::minutes; +// +// constexpr explicit time_of_day(std::chrono::minutes since_midnight) noexcept; +// constexpr time_of_day(std::chrono::hours h, std::chrono::minutes m, +// unsigned md) noexcept; +// +// constexpr std::chrono::hours hours() const noexcept; +// constexpr std::chrono::minutes minutes() const noexcept; +// constexpr unsigned mode() const noexcept; +// +// constexpr explicit operator precision() const noexcept; +// constexpr precision to_duration() const noexcept; +// +// void make24() noexcept; +// void make12() noexcept; +// }; + +// std::ostream& operator<<(std::ostream& os, const time_of_day& t); + +#include "date.h" + +#include +#include +#include + +int +main() +{ + using namespace date; + using namespace std; + using namespace std::chrono; + + using tod = time_of_day; + + static_assert(is_same{}, ""); + + static_assert( is_trivially_destructible{}, ""); + static_assert( is_default_constructible{}, ""); + static_assert( is_trivially_copy_constructible{}, ""); + static_assert( is_trivially_copy_assignable{}, ""); + static_assert( is_trivially_move_constructible{}, ""); + static_assert( is_trivially_move_assignable{}, ""); + + static_assert(is_nothrow_constructible{}, ""); + static_assert(!is_convertible{}, ""); + + static_assert(is_nothrow_constructible{}, ""); + static_assert(!is_convertible{}, ""); + + constexpr tod t1 = tod{hours{13} + minutes{7}}; + static_assert(t1.hours() == hours{13}, ""); + static_assert(t1.minutes() == minutes{7}, ""); +#if __cplusplus >= 201402 + static_assert(static_cast(t1) == hours{13} + minutes{7}, ""); + static_assert(t1.to_duration() == hours{13} + minutes{7}, ""); +#endif + + auto t2 = t1; + assert(t2.hours() == t1.hours()); + assert(t2.minutes() == t1.minutes()); + assert(t2.to_duration() == t1.to_duration()); + ostringstream os; + os << t2; + assert(os.str() == "13:07:00"); +} diff --git a/third_party/date/test/date_test/time_of_day_nanoseconds.pass.cpp b/third_party/date/test/date_test/time_of_day_nanoseconds.pass.cpp new file mode 100644 index 0000000..71a7fe8 --- /dev/null +++ b/third_party/date/test/date_test/time_of_day_nanoseconds.pass.cpp @@ -0,0 +1,104 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// enum {am = 1, pm}; + +// template +// class time_of_day> +// { +// public: +// using precision = std::chrono::std::chrono::duration; +// +// constexpr explicit time_of_day(precision since_midnight) noexcept; +// constexpr time_of_day(std::chrono::hours h, std::chrono::minutes m, +// std::chrono::seconds s, precision sub_s, +// unsigned md) noexcept; +// +// constexpr std::chrono::hours hours() const noexcept; +// constexpr std::chrono::minutes minutes() const noexcept; +// constexpr std::chrono::seconds seconds() const noexcept; +// constexpr precision subseconds() const noexcept; +// constexpr unsigned mode() const noexcept; +// +// constexpr explicit operator precision() const noexcept; +// constexpr precision to_duration() const noexcept; +// +// void make24() noexcept; +// void make12() noexcept; +// }; + +// template +// std::ostream& +// operator<<(std::ostream& os, const time_of_day>& t); + +#include "date.h" + +#include +#include +#include + +int +main() +{ + using namespace date; + using namespace std; + using namespace std::chrono; + + using tod = time_of_day; + + static_assert(is_same{}, ""); + + static_assert( is_trivially_destructible{}, ""); + static_assert( is_default_constructible{}, ""); + static_assert( is_trivially_copy_constructible{}, ""); + static_assert( is_trivially_copy_assignable{}, ""); + static_assert( is_trivially_move_constructible{}, ""); + static_assert( is_trivially_move_assignable{}, ""); + + static_assert(is_nothrow_constructible{}, ""); + static_assert(!is_convertible{}, ""); + + static_assert(is_nothrow_constructible{}, ""); + static_assert(!is_convertible{}, ""); + + constexpr tod t1 = tod{hours{13} + minutes{7} + seconds{5} + nanoseconds{22}}; + static_assert(t1.hours() == hours{13}, ""); + static_assert(t1.minutes() == minutes{7}, ""); + static_assert(t1.seconds() == seconds{5}, ""); + static_assert(t1.subseconds() == nanoseconds{22}, ""); +#if __cplusplus >= 201402 + static_assert(static_cast(t1) == hours{13} + minutes{7} + + seconds{5} + nanoseconds{22}, ""); + static_assert(t1.to_duration() == hours{13} + minutes{7} + seconds{5} + + nanoseconds{22}, ""); +#endif + + auto t2 = t1; + assert(t2.hours() == t1.hours()); + assert(t2.minutes() == t1.minutes()); + assert(t2.seconds() == t1.seconds()); + assert(t2.subseconds() == t1.subseconds()); + assert(t2.to_duration() == t1.to_duration()); + ostringstream os; + os << t2; + assert(os.str() == "13:07:05.000000022"); +} diff --git a/third_party/date/test/date_test/time_of_day_seconds.pass.cpp b/third_party/date/test/date_test/time_of_day_seconds.pass.cpp new file mode 100644 index 0000000..eaf4fb9 --- /dev/null +++ b/third_party/date/test/date_test/time_of_day_seconds.pass.cpp @@ -0,0 +1,96 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// enum {am = 1, pm}; + +// class time_of_day +// { +// public: +// using precision = std::chrono::seconds; +// +// constexpr explicit time_of_day(std::chrono::seconds since_midnight) noexcept; +// constexpr time_of_day(std::chrono::hours h, std::chrono::minutes m, +// std::chrono::seconds s, unsigned md) noexcept; +// +// constexpr std::chrono::hours hours() const noexcept; +// constexpr std::chrono::minutes minutes() const noexcept; +// constexpr std::chrono::seconds seconds() const noexcept; +// constexpr unsigned mode() const noexcept; +// +// constexpr explicit operator precision() const noexcept; +// constexpr precision to_duration() const noexcept; +// +// void make24() noexcept; +// void make12() noexcept; +// }; + +// std::ostream& operator<<(std::ostream& os, const time_of_day& t); + +#include "date.h" + +#include +#include +#include + +int +main() +{ + using namespace date; + using namespace std; + using namespace std::chrono; + + using tod = time_of_day; + + static_assert(is_same{}, ""); + + static_assert( is_trivially_destructible{}, ""); + static_assert( is_default_constructible{}, ""); + static_assert( is_trivially_copy_constructible{}, ""); + static_assert( is_trivially_copy_assignable{}, ""); + static_assert( is_trivially_move_constructible{}, ""); + static_assert( is_trivially_move_assignable{}, ""); + + static_assert(is_nothrow_constructible{}, ""); + static_assert(!is_convertible{}, ""); + + static_assert(is_nothrow_constructible{}, ""); + static_assert(!is_convertible{}, ""); + + constexpr tod t1 = tod{hours{13} + minutes{7} + seconds{5}}; + static_assert(t1.hours() == hours{13}, ""); + static_assert(t1.minutes() == minutes{7}, ""); + static_assert(t1.seconds() == seconds{5}, ""); +#if __cplusplus >= 201402 + static_assert(static_cast(t1) == hours{13} + minutes{7} + + seconds{5}, ""); + static_assert(t1.to_duration() == hours{13} + minutes{7} + seconds{5}, ""); +#endif + + auto t2 = t1; + assert(t2.hours() == t1.hours()); + assert(t2.minutes() == t1.minutes()); + assert(t2.seconds() == t1.seconds()); + assert(t2.to_duration() == t1.to_duration()); + ostringstream os; + os << t2; + assert(os.str() == "13:07:05"); +} diff --git a/third_party/date/test/date_test/weekday.pass.cpp b/third_party/date/test/date_test/weekday.pass.cpp new file mode 100644 index 0000000..de31faf --- /dev/null +++ b/third_party/date/test/date_test/weekday.pass.cpp @@ -0,0 +1,201 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class weekday +// { +// unsigned char wd_; +// public: +// explicit constexpr weekday(unsigned wd) noexcept; +// constexpr weekday(const sys_days& dp) noexcept; +// +// weekday& operator++() noexcept; +// weekday operator++(int) noexcept; +// weekday& operator--() noexcept; +// weekday operator--(int) noexcept; +// +// weekday& operator+=(const days& d) noexcept; +// weekday& operator-=(const days& d) noexcept; +// +// constexpr explicit operator unsigned() const noexcept; +// constexpr bool ok() const noexcept; +// +// // tested with weekday_indexed +// constexpr weekday_indexed operator[](unsigned index) const noexcept; +// // tested with weekday_last +// constexpr weekday_last operator[](last_spec) const noexcept; +// }; + +// constexpr bool operator==(const weekday& x, const weekday& y) noexcept; +// constexpr bool operator!=(const weekday& x, const weekday& y) noexcept; + +// constexpr weekday operator+(const weekday& x, const days& y) noexcept; +// constexpr weekday operator+(const days& x, const weekday& y) noexcept; +// constexpr weekday operator-(const weekday& x, const days& y) noexcept; +// constexpr days operator-(const weekday& x, const weekday& y) noexcept; + +// std::ostream& operator<<(std::ostream& os, const weekday& wd); + +// constexpr weekday sun{0}; +// constexpr weekday mon{1}; +// constexpr weekday tue{2}; +// constexpr weekday wed{3}; +// constexpr weekday thu{4}; +// constexpr weekday fri{5}; +// constexpr weekday sat{6}; + +#include "date.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert( std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert( std::is_nothrow_constructible{}, ""); +static_assert( std::is_nothrow_constructible{}, ""); +static_assert(!std::is_convertible{}, ""); +static_assert( std::is_convertible{}, ""); +static_assert(!std::is_convertible{}, ""); + +static_assert( date::weekday{0u}.ok(), ""); +static_assert( date::weekday{1u}.ok(), ""); +static_assert( date::weekday{2u}.ok(), ""); +static_assert( date::weekday{3u}.ok(), ""); +static_assert( date::weekday{4u}.ok(), ""); +static_assert( date::weekday{5u}.ok(), ""); +static_assert( date::weekday{6u}.ok(), ""); +static_assert( date::weekday{7u}.ok(), ""); +static_assert(!date::weekday{8u}.ok(), ""); + +void +test_weekday_arithmetic() +{ + using namespace date; + constexpr unsigned a[7][7] = + {// - Sun Mon Tue Wed Thu Fri Sat + /*Sun*/ {0, 6, 5, 4, 3, 2, 1}, + /*Mon*/ {1, 0, 6, 5, 4, 3, 2}, + /*Tue*/ {2, 1, 0, 6, 5, 4, 3}, + /*Wed*/ {3, 2, 1, 0, 6, 5, 4}, + /*Thu*/ {4, 3, 2, 1, 0, 6, 5}, + /*Fri*/ {5, 4, 3, 2, 1, 0, 6}, + /*Sat*/ {6, 5, 4, 3, 2, 1, 0} + }; + for (unsigned x = 0; x < 7; ++x) + { + for (unsigned y = 0; y < 7; ++y) + { + assert(weekday{x} - weekday{y} == days{a[x][y]}); + assert(weekday{x} - days{a[x][y]} == weekday{y}); + assert(weekday{x} == weekday{y} + days{a[x][y]}); + assert(weekday{x} == days{a[x][y]} + weekday{y}); + } + } + for (unsigned x = 0; x < 7; ++x) + { + for (int y = -21; y < 21; ++y) + { + weekday wx{x}; + days dy{y}; + wx += dy; + weekday wz = weekday{x} + days{y}; + assert(wx.ok()); + assert(wz.ok()); + assert(wx == wz); + assert(wx - weekday{x} == days{y % 7 + (y % 7 < 0 ? 7 : 0)}); + } + } + for (unsigned x = 0; x < 7; ++x) + { + for (int y = -21; y < 21; ++y) + { + weekday wx{x}; + days dy{y}; + wx -= dy; + assert(wx == weekday{x} + days{-y}); + } + } + for (unsigned x = 0; x < 7; ++x) + { + weekday wx{x}; + assert(++wx - weekday{x} == days{1}); + assert(wx++ - weekday{x} == days{1}); + assert(wx - weekday{x} == days{2}); + assert(wx-- - weekday{x} == days{2}); + assert(wx - weekday{x} == days{1}); + assert(--wx - weekday{x} == days{0}); + } +} + +int +main() +{ + using namespace date; + + static_assert(sun == weekday{0u}, ""); + static_assert(mon == weekday{1u}, ""); + static_assert(tue == weekday{2u}, ""); + static_assert(wed == weekday{3u}, ""); + static_assert(thu == weekday{4u}, ""); + static_assert(fri == weekday{5u}, ""); + static_assert(sat == weekday{6u}, ""); + + static_assert(!(sun != sun), ""); + static_assert( sun != mon, ""); + static_assert( mon != sun, ""); + + test_weekday_arithmetic(); + + std::ostringstream os; + + os << sun; + assert(os.str() == "Sun"); + os.str(""); + + os << mon; + assert(os.str() == "Mon"); + os.str(""); + + os << tue; + assert(os.str() == "Tue"); + os.str(""); + + os << wed; + assert(os.str() == "Wed"); + os.str(""); + + os << thu; + assert(os.str() == "Thu"); + os.str(""); + + os << fri; + assert(os.str() == "Fri"); + os.str(""); + + os << sat; + assert(os.str() == "Sat"); +} diff --git a/third_party/date/test/date_test/weekday_indexed.pass.cpp b/third_party/date/test/date_test/weekday_indexed.pass.cpp new file mode 100644 index 0000000..5d25d2b --- /dev/null +++ b/third_party/date/test/date_test/weekday_indexed.pass.cpp @@ -0,0 +1,70 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class weekday_indexed +// { +// public: +// weekday_indexed() = default; +// constexpr weekday_indexed(const date::weekday& wd, unsigned index) noexcept; +// +// constexpr date::weekday weekday() const noexcept; +// constexpr unsigned index() const noexcept; +// constexpr bool ok() const noexcept; +// }; +// +// constexpr bool operator==(const weekday_indexed& x, const weekday_indexed& y) noexcept; +// constexpr bool operator!=(const weekday_indexed& x, const weekday_indexed& y) noexcept; +// +// std::ostream& operator<<(std::ostream& os, const weekday_indexed& wdi); + +#include "date.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert( std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_nothrow_constructible{}, ""); + +int +main() +{ + using namespace date; + + constexpr weekday_indexed wdi = sun[1]; + static_assert(wdi.weekday() == sun, ""); + static_assert(wdi.index() == 1, ""); + static_assert(wdi.ok(), ""); + static_assert(wdi == weekday_indexed{sun, 1}, ""); + static_assert(wdi != weekday_indexed{sun, 2}, ""); + static_assert(wdi != weekday_indexed{mon, 1}, ""); + std::ostringstream os; + os << wdi; + assert(os.str() == "Sun[1]"); +} diff --git a/third_party/date/test/date_test/weekday_last.pass.cpp b/third_party/date/test/date_test/weekday_last.pass.cpp new file mode 100644 index 0000000..3c30bf7 --- /dev/null +++ b/third_party/date/test/date_test/weekday_last.pass.cpp @@ -0,0 +1,66 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class weekday_last +// { +// public: +// explicit constexpr weekday_last(const date::weekday& wd) noexcept; +// +// constexpr date::weekday weekday() const noexcept; +// constexpr bool ok() const noexcept; +// }; +// +// constexpr bool operator==(const weekday_last& x, const weekday_last& y) noexcept; +// constexpr bool operator!=(const weekday_last& x, const weekday_last& y) noexcept; +// +// std::ostream& operator<<(std::ostream& os, const weekday_last& wdl); + +#include "date.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert(!std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(!std::is_convertible{}, ""); + +int +main() +{ + using namespace date; + + constexpr weekday_last wdl = sun[last]; + static_assert(wdl.weekday() == sun, ""); + static_assert(wdl.ok(), ""); + static_assert(wdl == weekday_last{sun}, ""); + static_assert(wdl != weekday_last{mon}, ""); + std::ostringstream os; + os << wdl; + assert(os.str() == "Sun[last]"); +} diff --git a/third_party/date/test/date_test/weekday_lessthan.fail.cpp b/third_party/date/test/date_test/weekday_lessthan.fail.cpp new file mode 100644 index 0000000..a1fbc28 --- /dev/null +++ b/third_party/date/test/date_test/weekday_lessthan.fail.cpp @@ -0,0 +1,32 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// weekday < weekday not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + auto b = sun < mon; +} diff --git a/third_party/date/test/date_test/weekday_sum.fail.cpp b/third_party/date/test/date_test/weekday_sum.fail.cpp new file mode 100644 index 0000000..f429051 --- /dev/null +++ b/third_party/date/test/date_test/weekday_sum.fail.cpp @@ -0,0 +1,32 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// weekday + weekday not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + auto b = sun + mon; +} diff --git a/third_party/date/test/date_test/year.pass.cpp b/third_party/date/test/date_test/year.pass.cpp new file mode 100644 index 0000000..585a245 --- /dev/null +++ b/third_party/date/test/date_test/year.pass.cpp @@ -0,0 +1,146 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class year +// { +// public: +// explicit constexpr year(int y) noexcept; +// +// year& operator++() noexcept; +// year operator++(int) noexcept; +// year& operator--() noexcept; +// year operator--(int) noexcept; +// +// year& operator+=(const years& y) noexcept; +// year& operator-=(const years& y) noexcept; +// +// constexpr bool is_leap() const noexcept; +// +// constexpr explicit operator int() const noexcept; +// constexpr bool ok() const noexcept; +// +// static constexpr year min() noexcept; +// static constexpr year max() noexcept; +// }; + +// constexpr bool operator==(const year& x, const year& y) noexcept; +// constexpr bool operator!=(const year& x, const year& y) noexcept; +// constexpr bool operator< (const year& x, const year& y) noexcept; +// constexpr bool operator> (const year& x, const year& y) noexcept; +// constexpr bool operator<=(const year& x, const year& y) noexcept; +// constexpr bool operator>=(const year& x, const year& y) noexcept; + +// constexpr year operator+(const year& x, const years& y) noexcept; +// constexpr year operator+(const years& x, const year& y) noexcept; +// constexpr year operator-(const year& x, const years& y) noexcept; +// constexpr years operator-(const year& x, const year& y) noexcept; + +// constexpr year operator "" _y(unsigned long long y) noexcept; +// std::ostream& operator<<(std::ostream& os, const year& y); + +#include "date.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert( std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert( std::is_nothrow_constructible{}, ""); +static_assert(!std::is_convertible{}, ""); +static_assert( std::is_nothrow_constructible{}, ""); +static_assert(!std::is_convertible{}, ""); +static_assert(static_cast(date::year{-1}) == -1, ""); + +template +constexpr +inline +std::chrono::duration +as(std::chrono::duration d) +{ + return d; +} + +int +main() +{ + using namespace date; + using namespace std::chrono; + + static_assert(year{2015} == 2015_y, ""); + static_assert(year{2015} != 2016_y, ""); + static_assert(year{2015} < 2016_y, ""); + static_assert(year{2016} > 2015_y, ""); + static_assert(year{2015} <= 2015_y, ""); + static_assert(year{2016} >= 2015_y, ""); + + static_assert(!year{2015}.is_leap(), ""); + static_assert( year{2016}.is_leap(), ""); + + static_assert(year::min().ok(), ""); + static_assert(year{2015}.ok(), ""); + static_assert(year{2016}.ok(), ""); + static_assert(year::max().ok(), ""); + +#if __cplusplus >= 201402 + using std::int64_t; + static_assert(sys_days(year::min()/jan/1) - sys_days(1970_y/jan/1) + >= as(days::min()), ""); + static_assert(sys_days(year::min()/jan/1) - sys_days(1970_y/jan/1) + >= as(hours::min()), ""); + static_assert(sys_days(year::min()/jan/1) - sys_days(1970_y/jan/1) + >= as(minutes::min()), ""); + static_assert(sys_days(year::min()/jan/1) - sys_days(1970_y/jan/1) + >= as(seconds::min()), ""); + static_assert(sys_days(year::min()/jan/1) - sys_days(1970_y/jan/1) + >= as(milliseconds::min()), ""); + static_assert(sys_days(year::min()/jan/1) - sys_days(1970_y/jan/1) + >= as(microseconds::min()), ""); + static_assert(sys_days(year::max()/dec/31) - sys_days(1970_y/jan/1) + <= as(microseconds::max()), ""); + static_assert(sys_days(year::max()/dec/31) - sys_days(1970_y/jan/1) + <= as(milliseconds::max()), ""); + static_assert(sys_days(year::max()/dec/31) - sys_days(1970_y/jan/1) + <= as(seconds::max()), ""); + static_assert(sys_days(year::max()/dec/31) - sys_days(1970_y/jan/1) + <= as(minutes::max()), ""); + static_assert(sys_days(year::max()/dec/31) - sys_days(1970_y/jan/1) + <= as(hours::max()), ""); + static_assert(sys_days(year::max()/dec/31) - sys_days(1970_y/jan/1) + <= as(days::max()), ""); +#endif + + static_assert(2015_y - 2010_y == years{5}, ""); + static_assert(2015_y - years{5} == 2010_y, ""); + static_assert(2015_y == years{5} + 2010_y, ""); + static_assert(2015_y == 2010_y + years{5}, ""); + + auto y = 2015_y; + std::ostringstream os; + os << y; + assert(os.str() == "2015"); +} diff --git a/third_party/date/test/date_test/year_month.pass.cpp b/third_party/date/test/date_test/year_month.pass.cpp new file mode 100644 index 0000000..eec28a9 --- /dev/null +++ b/third_party/date/test/date_test/year_month.pass.cpp @@ -0,0 +1,227 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class year_month +// { +// public: +// constexpr year_month(const date::year& y, const date::month& m) noexcept; +// +// constexpr date::year year() const noexcept; +// constexpr date::month month() const noexcept; +// +// year_month& operator+=(const months& dm) noexcept; +// year_month& operator-=(const months& dm) noexcept; +// year_month& operator+=(const years& dy) noexcept; +// year_month& operator-=(const years& dy) noexcept; +// +// constexpr bool ok() const noexcept; +// }; + +// constexpr bool operator==(const year_month& x, const year_month& y) noexcept; +// constexpr bool operator!=(const year_month& x, const year_month& y) noexcept; +// constexpr bool operator< (const year_month& x, const year_month& y) noexcept; +// constexpr bool operator> (const year_month& x, const year_month& y) noexcept; +// constexpr bool operator<=(const year_month& x, const year_month& y) noexcept; +// constexpr bool operator>=(const year_month& x, const year_month& y) noexcept; + +// constexpr year_month operator+(const year_month& ym, const months& dm) noexcept; +// constexpr year_month operator+(const months& dm, const year_month& ym) noexcept; +// constexpr year_month operator-(const year_month& ym, const months& dm) noexcept; + +// constexpr months operator-(const year_month& x, const year_month& y) noexcept; +// constexpr year_month operator+(const year_month& ym, const years& dy) noexcept; +// constexpr year_month operator+(const years& dy, const year_month& ym) noexcept; +// constexpr year_month operator-(const year_month& ym, const years& dy) noexcept; + +// std::ostream& operator<<(std::ostream& os, const year_month& ym); + +#include "date.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert( std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_nothrow_constructible{}, ""); + +void +test_arithmetic() +{ + using namespace date; + using namespace std::chrono; + + for (int y1 = 2010; y1 <= 2015; ++y1) + { + for (int y2 = 2010; y2 <= 2015; ++y2) + { + for (unsigned m1 = 1; m1 <= 12; ++m1) + { + for (unsigned m2 = 1; m2 <= 12; ++m2) + { + year_month ym1{year{y1}, month{m1}}; + year_month ym2 = {year{y2}, month{m2}}; + months dm = ym1 - ym2; + assert((dm < months{0}) == (ym1 < ym2)); + assert((dm == months{0}) == (ym1 == ym2)); + assert((dm > months{0}) == (ym1 > ym2)); + assert(dm + ym2 == ym1); + assert(ym2 + dm == ym1); + assert(ym1 - dm == ym2); + years dy{y1-y2}; + assert((ym1 + dy == year_month{ym1.year() + dy, ym1.month()})); + assert((dy + ym1 == year_month{ym1.year() + dy, ym1.month()})); + assert((ym1 - dy == year_month{ym1.year() - dy, ym1.month()})); + assert((year_month{ym2} += dm) == ym1); + assert((year_month{ym1} -= dm) == ym2); + assert(((year_month{ym1} += dy) == + year_month{ym1.year() + dy, ym1.month()})); + assert(((year_month{ym1} -= dy) == + year_month{ym1.year() - dy, ym1.month()})); + } + } + } + } +} + + +void test_arithemtic_not_ok() +{ + using namespace date; + using namespace std::chrono; + + year_month ym{2018_y, month{14}}; + + { + year_month ym2{2019_y, month{2}}; + assert(ym + months{0} == ym2); + assert(ym - months{0} == ym2); + assert(ym - ym2 == months{0}); + assert(ym2 - ym == months{0}); + + auto ymc = ym; + ymc += months{0}; + assert(ymc.ok()); + assert(ymc == ym2); + } + + { + year_month ym2{2019_y, month{6}}; + assert(ym + months{4} == ym2); + assert(ym2 - ym == months{4}); + assert(ym - ym2 == -months{4}); + + auto ymc = ym; + ymc += months{4}; + assert(ymc.ok()); + assert(ymc == ym2); + } + + { + year_month ym2{2018_y, month{10}}; + assert(ym - months{4} == ym2); + assert(ym2 - ym == -months{4}); + assert(ym - ym2 == months{4}); + + auto ymc = ym; + ymc -= months{4}; + assert(ymc.ok()); + assert(ymc == ym2); + } + + + { + year_month ym2{2020_y, month{6}}; + assert(ym + months{16} == ym2); + assert(ym2 - ym == months{16}); + assert(ym - ym2 == -months{16}); + + auto ymc = ym; + ymc += months{16}; + assert(ymc.ok()); + assert(ymc == ym2); + } + + { + year_month ym2{2017_y, month{10}}; + assert(ym - months{16} == ym2); + assert(ym2 - ym == -months{16}); + assert(ym - ym2 == months(16)); + + auto ymc = ym; + ymc -= months{16}; + assert(ymc.ok()); + assert(ymc == ym2); + } + + { + year_month ym2{2018_y, month{25}}; + assert(ym2 - ym == months{11}); + assert(ym - ym2 == -months{11}); + } + + { + year_month ym2{2019_y, month{25}}; + assert(ym2 - ym == months{23}); + assert(ym - ym2 == -months{23}); + } + +} + +int +main() +{ + using namespace date; + + constexpr year_month ym1 = {2015_y, jun}; + static_assert(ym1.year() == year{2015}, ""); + static_assert(ym1.month() == jun, ""); + static_assert(ym1.ok(), ""); + + constexpr year_month ym2 = {2016_y, may}; + static_assert(ym2.year() == year{2016}, ""); + static_assert(ym2.month() == may, ""); + static_assert(ym2.ok(), ""); + + static_assert(ym1 == ym1, ""); + static_assert(ym1 != ym2, ""); + static_assert(ym1 < ym2, ""); + static_assert(ym1 <= ym2, ""); + static_assert(ym2 > ym1, ""); + static_assert(ym2 >= ym2, ""); + + static_assert(ym2 - ym1 == months{11}, ""); + static_assert(ym1 - ym2 == -months{11}, ""); + + test_arithmetic(); + test_arithemtic_not_ok(); + + std::ostringstream os; + os << ym1; + assert(os.str() == "2015/Jun"); +} diff --git a/third_party/date/test/date_test/year_month_day.pass.cpp b/third_party/date/test/date_test/year_month_day.pass.cpp new file mode 100644 index 0000000..9166888 --- /dev/null +++ b/third_party/date/test/date_test/year_month_day.pass.cpp @@ -0,0 +1,244 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class year_month_day +// { +// public: +// constexpr year_month_day(const date::year& y, const date::month& m, +// const date::day& d) noexcept; +// constexpr year_month_day(const year_month_day_last& ymdl) noexcept; +// constexpr year_month_day(const sys_days& dp) noexcept; +// +// year_month_day& operator+=(const months& m) noexcept; +// year_month_day& operator-=(const months& m) noexcept; +// year_month_day& operator+=(const years& y) noexcept; +// year_month_day& operator-=(const years& y) noexcept; +// +// constexpr date::year year() const noexcept; +// constexpr date::month month() const noexcept; +// constexpr date::day day() const noexcept; +// +// constexpr operator sys_days() const noexcept; +// constexpr bool ok() const noexcept; +// }; + +// constexpr bool operator==(const year_month_day& x, const year_month_day& y) noexcept; +// constexpr bool operator!=(const year_month_day& x, const year_month_day& y) noexcept; +// constexpr bool operator< (const year_month_day& x, const year_month_day& y) noexcept; +// constexpr bool operator> (const year_month_day& x, const year_month_day& y) noexcept; +// constexpr bool operator<=(const year_month_day& x, const year_month_day& y) noexcept; +// constexpr bool operator>=(const year_month_day& x, const year_month_day& y) noexcept; + +// constexpr year_month_day operator+(const year_month_day& ymd, const months& dm) noexcept; +// constexpr year_month_day operator+(const months& dm, const year_month_day& ymd) noexcept; +// constexpr year_month_day operator-(const year_month_day& ymd, const months& dm) noexcept; +// constexpr year_month_day operator+(const year_month_day& ymd, const years& dy) noexcept; +// constexpr year_month_day operator+(const years& dy, const year_month_day& ymd) noexcept; +// constexpr year_month_day operator-(const year_month_day& ymd, const years& dy) noexcept; + +// std::ostream& operator<<(std::ostream& os, const year_month_day& ymd); + +#include "date.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert( std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(std::is_convertible{}, ""); +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(std::is_convertible{}, ""); +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(std::is_convertible{}, ""); + +void +test_arithmetic() +{ + using namespace date; + + for (int y1 = 2010; y1 <= 2015; ++y1) + { + for (unsigned m1 = 1; m1 <= 12; ++m1) + { + year_month_day ymd1{year{y1}, month{m1}, 9_d}; + year_month_day ymd2 = ymd1 + months(24); + assert((ymd2 == year_month_day{year{y1+2}, ymd1.month(), ymd1.day()})); + ymd2 = ymd1 - months(24); + assert((ymd2 == year_month_day{year{y1-2}, ymd1.month(), ymd1.day()})); + for (int m2 = -24; m2 <= 24; ++m2) + { + months m{m2}; + year_month_day ymd3 = ymd1 + m; + months dm = year_month{ymd3.year(), ymd3.month()} - + year_month{ymd2.year(), ymd2.month()}; + assert(dm == m + years{2}); + assert(ymd3 - m == ymd1); + assert(ymd3 + -m == ymd1); + assert(-m + ymd3 == ymd1); + assert((year_month_day{ymd1} += m) == ymd3); + assert((year_month_day{ymd3} -= m) == ymd1); + } + for (int y2 = -2; y2 <= 5; ++y2) + { + years y{y2}; + year_month_day ymd3 = ymd1 + y; + years dy = floor(year_month{ymd3.year(), ymd3.month()} - + year_month{ymd2.year(), ymd2.month()}); + assert(dy == y + years{2}); + assert(ymd3 - y == ymd1); + assert(ymd3 + -y == ymd1); + assert(-y + ymd3 == ymd1); + assert((year_month_day{ymd1} += y) == ymd3); + assert((year_month_day{ymd3} -= y) == ymd1); + } + } + } +} + +void +test_day_point_conversion() +{ + using namespace date; + year y = year{-1000}; + year end = 3000_y; + sys_days prev_dp = sys_days(year_month_day{y, jan, 1_d}) - days{1}; + weekday prev_wd = weekday{prev_dp}; + for (; y <= end; ++y) + { + month m = jan; + do + { + day last_day = year_month_day_last{y, month_day_last{m}}.day(); + for (day d = 1_d; d <= last_day; ++d) + { + year_month_day ymd = {y, m, d}; + assert(ymd.ok()); + sys_days dp = ymd; + assert(dp == prev_dp + days{1}); + year_month_day ymd2 = dp; + assert(ymd2 == ymd); + weekday wd = dp; + assert(wd.ok()); + assert(wd == prev_wd + days{1}); + prev_wd = wd; + prev_dp = dp; + } + } while (++m != jan); + } +} + +int +main() +{ + using namespace date; + + constexpr year_month_day ymd1 = {2015_y, aug, 9_d}; +#if __cplusplus >= 201402 + static_assert(ymd1.ok(), ""); +#endif + static_assert(ymd1.year() == 2015_y, ""); + static_assert(ymd1.month() == aug, ""); + static_assert(ymd1.day() == 9_d, ""); + +#if __cplusplus >= 201402 + constexpr sys_days dp = ymd1; + static_assert(dp.time_since_epoch() == days{16656}, ""); + constexpr year_month_day ymd2 = dp; + static_assert(ymd1 == ymd2, ""); +#endif + + constexpr year_month_day ymd3 = {1969_y, dec, 31_d}; +#if __cplusplus >= 201402 + static_assert(ymd3.ok(), ""); +#endif + static_assert(ymd3.year() == 1969_y, ""); + static_assert(ymd3.month() == dec, ""); + static_assert(ymd3.day() == 31_d, ""); + +#if __cplusplus >= 201402 + constexpr sys_days dp3 = ymd3; + static_assert(dp3.time_since_epoch() == days{-1}, ""); + constexpr year_month_day ymd4 = dp3; + static_assert(ymd3 == ymd4, ""); +#endif + + static_assert(ymd1 != ymd3, ""); + static_assert(ymd1 > ymd3, ""); + static_assert(ymd3 < ymd1, ""); + static_assert(ymd1 >= ymd1, ""); + static_assert(ymd3 <= ymd1, ""); + + test_arithmetic(); + test_day_point_conversion(); + + std::ostringstream os; + os << ymd1; + assert(os.str() == "2015-08-09"); + +#if __cplusplus >= 201402 + static_assert( (2000_y/feb/29).ok(), ""); + static_assert(!(2000_y/feb/30).ok(), ""); + static_assert( (2100_y/feb/28).ok(), ""); + static_assert(!(2100_y/feb/29).ok(), ""); + + static_assert(sys_days(2100_y/feb/28) + days{1} == sys_days(2100_y/mar/1), ""); + static_assert(sys_days(2000_y/mar/1) - sys_days(2000_y/feb/28) == days{2}, ""); + static_assert(sys_days(2100_y/mar/1) - sys_days(2100_y/feb/28) == days{1}, ""); + + static_assert(jan/31/2015 == jan/last/2015, ""); + static_assert(feb/28/2015 == feb/last/2015, ""); + static_assert(mar/31/2015 == mar/last/2015, ""); + static_assert(apr/30/2015 == apr/last/2015, ""); + static_assert(may/31/2015 == may/last/2015, ""); + static_assert(jun/30/2015 == jun/last/2015, ""); + static_assert(jul/31/2015 == jul/last/2015, ""); + static_assert(aug/31/2015 == aug/last/2015, ""); + static_assert(sep/30/2015 == sep/last/2015, ""); + static_assert(oct/31/2015 == oct/last/2015, ""); + static_assert(nov/30/2015 == nov/last/2015, ""); + static_assert(dec/31/2015 == dec/last/2015, ""); + + static_assert(jan/31/2016 == jan/last/2016, ""); + static_assert(feb/29/2016 == feb/last/2016, ""); + static_assert(mar/31/2016 == mar/last/2016, ""); + static_assert(apr/30/2016 == apr/last/2016, ""); + static_assert(may/31/2016 == may/last/2016, ""); + static_assert(jun/30/2016 == jun/last/2016, ""); + static_assert(jul/31/2016 == jul/last/2016, ""); + static_assert(aug/31/2016 == aug/last/2016, ""); + static_assert(sep/30/2016 == sep/last/2016, ""); + static_assert(oct/31/2016 == oct/last/2016, ""); + static_assert(nov/30/2016 == nov/last/2016, ""); + static_assert(dec/31/2016 == dec/last/2016, ""); +#endif +} diff --git a/third_party/date/test/date_test/year_month_day_last.pass.cpp b/third_party/date/test/date_test/year_month_day_last.pass.cpp new file mode 100644 index 0000000..41f1858 --- /dev/null +++ b/third_party/date/test/date_test/year_month_day_last.pass.cpp @@ -0,0 +1,177 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class year_month_day_last +// { +// public: +// constexpr year_month_day_last(const date::year& y, +// const date::month_day_last& mdl) noexcept; +// +// year_month_day_last& operator+=(const months& m) noexcept; +// year_month_day_last& operator-=(const months& m) noexcept; +// year_month_day_last& operator+=(const years& y) noexcept; +// year_month_day_last& operator-=(const years& y) noexcept; +// +// constexpr date::year year() const noexcept; +// constexpr date::month month() const noexcept; +// constexpr date::month_day_last month_day_last() const noexcept; +// constexpr date::day day() const noexcept; +// +// constexpr operator sys_days() const noexcept; +// constexpr bool ok() const noexcept; +// }; + +// constexpr +// bool operator==(const year_month_day_last& x, const year_month_day_last& y) noexcept; +// constexpr +// bool operator!=(const year_month_day_last& x, const year_month_day_last& y) noexcept; +// constexpr +// bool operator< (const year_month_day_last& x, const year_month_day_last& y) noexcept; +// constexpr +// bool operator> (const year_month_day_last& x, const year_month_day_last& y) noexcept; +// constexpr +// bool operator<=(const year_month_day_last& x, const year_month_day_last& y) noexcept; +// constexpr +// bool operator>=(const year_month_day_last& x, const year_month_day_last& y) noexcept; + +// constexpr +// year_month_day_last +// operator+(const year_month_day_last& ymdl, const months& dm) noexcept; +// +// constexpr +// year_month_day_last +// operator+(const months& dm, const year_month_day_last& ymdl) noexcept; +// +// constexpr +// year_month_day_last +// operator+(const year_month_day_last& ymdl, const years& dy) noexcept; +// +// constexpr +// year_month_day_last +// operator+(const years& dy, const year_month_day_last& ymdl) noexcept; +// +// constexpr +// year_month_day_last +// operator-(const year_month_day_last& ymdl, const months& dm) noexcept; +// +// constexpr +// year_month_day_last +// operator-(const year_month_day_last& ymdl, const years& dy) noexcept; + +// std::ostream& operator<<(std::ostream& os, const year_month_day_last& ymdl); + +#include "date.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert(!std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(std::is_convertible{}, ""); + +void +test_arithmetic() +{ + using namespace date; + + for (int y1 = 2010; y1 <= 2015; ++y1) + { + for (int m1 = 1; m1 <= 12; ++m1) + { + auto ymd1 = last/m1/y1;; + auto ymd2 = ymd1 + months(24); + assert(ymd2 == last/m1/(y1+2)); + ymd2 = ymd1 - months(24); + assert(ymd2 == last/m1/(y1-2)); + for (int m2 = -24; m2 <= 24; ++m2) + { + months m{m2}; + auto ymd3 = ymd1 + m; + months dm = year_month{ymd3.year(), ymd3.month()} - + year_month{ymd2.year(), ymd2.month()}; + assert(dm == m + years{2}); + assert(ymd3 - m == ymd1); + assert(ymd3 + -m == ymd1); + assert(-m + ymd3 == ymd1); + assert((year_month_day_last{ymd1} += m) == ymd3); + assert((year_month_day_last{ymd3} -= m) == ymd1); + } + for (int y2 = -2; y2 <= 5; ++y2) + { + years y{y2}; + auto ymd3 = ymd1 + y; + years dy = floor(year_month{ymd3.year(), ymd3.month()} - + year_month{ymd2.year(), ymd2.month()}); + assert(dy == y + years{2}); + assert(ymd3 - y == ymd1); + assert(ymd3 + -y == ymd1); + assert(-y + ymd3 == ymd1); + assert((year_month_day_last{ymd1} += y) == ymd3); + assert((year_month_day_last{ymd3} -= y) == ymd1); + } + } + } +} + +int +main() +{ + using namespace date; + + constexpr year_month_day_last ymdl1 = {2015_y, month_day_last{aug}}; + static_assert(ymdl1.ok(), ""); + static_assert(ymdl1.year() == 2015_y, ""); + static_assert(ymdl1.month() == aug, ""); + static_assert(ymdl1.month_day_last() == month_day_last{aug}, ""); +#if __cplusplus >= 201402 + static_assert(ymdl1.day() == 31_d, ""); + constexpr sys_days dp = ymdl1; + constexpr year_month_day ymd = dp; + static_assert(ymd == 2015_y/aug/31, ""); +#endif + + constexpr year_month_day_last ymdl2 = {2015_y, month_day_last{sep}}; + + static_assert(ymdl1 == ymdl1, ""); + static_assert(ymdl1 != ymdl2, ""); + static_assert(ymdl1 < ymdl2, ""); + static_assert(ymdl2 > ymdl1, ""); + static_assert(ymdl1 <= ymdl1, ""); + static_assert(ymdl2 >= ymdl1, ""); + + test_arithmetic(); + + std::ostringstream os; + os << ymdl1; + assert(os.str() == "2015/Aug/last"); + +} diff --git a/third_party/date/test/date_test/year_month_day_m_year_month_day.fail.cpp b/third_party/date/test/date_test/year_month_day_m_year_month_day.fail.cpp new file mode 100644 index 0000000..ceb2f9e --- /dev/null +++ b/third_party/date/test/date_test/year_month_day_m_year_month_day.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// year_month_day - year_month_day not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = year_month_day{2015_y, aug, 9_d} - year_month_day{2015_y, aug, 9_d}; +} diff --git a/third_party/date/test/date_test/year_month_day_p_year_month_day.fail.cpp b/third_party/date/test/date_test/year_month_day_p_year_month_day.fail.cpp new file mode 100644 index 0000000..11e589f --- /dev/null +++ b/third_party/date/test/date_test/year_month_day_p_year_month_day.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// year_month_day + year_month_day not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = year_month_day{2015_y, aug, 9_d} + year_month_day{2015_y, aug, 9_d}; +} diff --git a/third_party/date/test/date_test/year_month_p_year_month.fail.cpp b/third_party/date/test/date_test/year_month_p_year_month.fail.cpp new file mode 100644 index 0000000..00049f1 --- /dev/null +++ b/third_party/date/test/date_test/year_month_p_year_month.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// year_month + year_month not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = year_month{2015_y, jan} + year_month{2015_y, jan}; +} diff --git a/third_party/date/test/date_test/year_month_weekday.pass.cpp b/third_party/date/test/date_test/year_month_weekday.pass.cpp new file mode 100644 index 0000000..1a6ed0d --- /dev/null +++ b/third_party/date/test/date_test/year_month_weekday.pass.cpp @@ -0,0 +1,178 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class year_month_weekday +// { +// public: +// year_month_weekday() = default; +// constexpr year_month_weekday(const date::year& y, const date::month& m, +// const date::weekday_indexed& wdi) noexcept; +// constexpr year_month_weekday(const sys_days& dp) noexcept; +// +// year_month_weekday& operator+=(const months& m) noexcept; +// year_month_weekday& operator-=(const months& m) noexcept; +// year_month_weekday& operator+=(const years& y) noexcept; +// year_month_weekday& operator-=(const years& y) noexcept; +// +// constexpr date::year year() const noexcept; +// constexpr date::month month() const noexcept; +// constexpr date::weekday weekday() const noexcept; +// constexpr unsigned index() const noexcept; +// constexpr date::weekday_indexed weekday_indexed() const noexcept; +// +// constexpr operator sys_days() const noexcept; +// constexpr bool ok() const noexcept; +// +// private: +// static constexpr year_month_weekday from_day_point(const sys_days& dp) noexcept; +// }; + +// constexpr +// bool operator==(const year_month_weekday& x, const year_month_weekday& y) noexcept; +// constexpr +// bool operator!=(const year_month_weekday& x, const year_month_weekday& y) noexcept; + +// constexpr +// year_month_weekday +// operator+(const year_month_weekday& ymwd, const months& dm) noexcept; +// +// constexpr +// year_month_weekday +// operator+(const months& dm, const year_month_weekday& ymwd) noexcept; +// +// constexpr +// year_month_weekday +// operator+(const year_month_weekday& ymwd, const years& dy) noexcept; +// +// constexpr +// year_month_weekday +// operator+(const years& dy, const year_month_weekday& ymwd) noexcept; +// +// constexpr +// year_month_weekday +// operator-(const year_month_weekday& ymwd, const months& dm) noexcept; +// +// constexpr +// year_month_weekday +// operator-(const year_month_weekday& ymwd, const years& dy) noexcept; + +// std::ostream& operator<<(std::ostream& os, const year_month_weekday& ymwdi); + +#include "date.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert( std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(std::is_convertible{}, ""); +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(std::is_convertible{}, ""); + +void +test_arithmetic() +{ + using namespace date; + + for (int y1 = 2010; y1 <= 2015; ++y1) + { + for (int m1 = 1; m1 <= 12; ++m1) + { + auto ymd1 = mon[2]/m1/y1;; + auto ymd2 = ymd1 + months(24); + assert(ymd2 == mon[2]/m1/(y1+2)); + ymd2 = ymd1 - months(24); + assert(ymd2 == mon[2]/m1/(y1-2)); + for (int m2 = -24; m2 <= 24; ++m2) + { + months m{m2}; + auto ymd3 = ymd1 + m; + months dm = year_month{ymd3.year(), ymd3.month()} - + year_month{ymd2.year(), ymd2.month()}; + assert(dm == m + years{2}); + assert(ymd3 - m == ymd1); + assert(ymd3 + -m == ymd1); + assert(-m + ymd3 == ymd1); + assert((year_month_weekday{ymd1} += m) == ymd3); + assert((year_month_weekday{ymd3} -= m) == ymd1); + } + for (int y2 = -2; y2 <= 5; ++y2) + { + years y{y2}; + auto ymd3 = ymd1 + y; + years dy = floor(year_month{ymd3.year(), ymd3.month()} - + year_month{ymd2.year(), ymd2.month()}); + assert(dy == y + years{2}); + assert(ymd3 - y == ymd1); + assert(ymd3 + -y == ymd1); + assert(-y + ymd3 == ymd1); + assert((year_month_weekday{ymd1} += y) == ymd3); + assert((year_month_weekday{ymd3} -= y) == ymd1); + } + } + } +} + +int +main() +{ + using namespace date; + + constexpr year_month_weekday ymdl1 = {2015_y, aug, weekday_indexed{fri, 2}}; +#if __cplusplus >= 201402 + static_assert(ymdl1.ok(), ""); +#endif + static_assert(ymdl1.year() == 2015_y, ""); + static_assert(ymdl1.month() == aug, ""); + static_assert(ymdl1.weekday() == fri, ""); + static_assert(ymdl1.index() == 2u, ""); + static_assert(ymdl1.weekday_indexed() == fri[2], ""); +#if __cplusplus >= 201402 + constexpr sys_days dp = ymdl1; + constexpr year_month_day ymd = dp; + static_assert(ymd == 2015_y/aug/14, ""); +#endif + + constexpr year_month_weekday ymdl2 = sat[1]/aug/2015; + + static_assert(ymdl1 == ymdl1, ""); + static_assert(ymdl1 != ymdl2, ""); + + test_arithmetic(); + + std::ostringstream os; + os << ymdl1; + assert(os.str() == "2015/Aug/Fri[2]"); + +} diff --git a/third_party/date/test/date_test/year_month_weekday_last.pass.cpp b/third_party/date/test/date_test/year_month_weekday_last.pass.cpp new file mode 100644 index 0000000..3abe113 --- /dev/null +++ b/third_party/date/test/date_test/year_month_weekday_last.pass.cpp @@ -0,0 +1,169 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class year_month_weekday_last +// { +// public: +// constexpr year_month_weekday_last(const date::year& y, const date::month& m, +// const date::weekday_last& wdl) noexcept; +// +// year_month_weekday_last& operator+=(const months& m) noexcept; +// year_month_weekday_last& operator-=(const months& m) noexcept; +// year_month_weekday_last& operator+=(const years& y) noexcept; +// year_month_weekday_last& operator-=(const years& y) noexcept; +// +// constexpr date::year year() const noexcept; +// constexpr date::month month() const noexcept; +// constexpr date::weekday weekday() const noexcept; +// constexpr date::weekday_last weekday_last() const noexcept; +// +// constexpr operator sys_days() const noexcept; +// constexpr bool ok() const noexcept; +// }; + +// constexpr +// bool +// operator==(const year_month_weekday_last& x, const year_month_weekday_last& y) noexcept; +// +// constexpr +// bool +// operator!=(const year_month_weekday_last& x, const year_month_weekday_last& y) noexcept; + +// constexpr +// year_month_weekday_last +// operator+(const year_month_weekday_last& ymwdl, const months& dm) noexcept; +// +// constexpr +// year_month_weekday_last +// operator+(const months& dm, const year_month_weekday_last& ymwdl) noexcept; +// +// constexpr +// year_month_weekday_last +// operator+(const year_month_weekday_last& ymwdl, const years& dy) noexcept; +// +// constexpr +// year_month_weekday_last +// operator+(const years& dy, const year_month_weekday_last& ymwdl) noexcept; +// +// constexpr +// year_month_weekday_last +// operator-(const year_month_weekday_last& ymwdl, const months& dm) noexcept; +// +// constexpr +// year_month_weekday_last +// operator-(const year_month_weekday_last& ymwdl, const years& dy) noexcept; + +// std::ostream& operator<<(std::ostream& os, const year_month_weekday_last& ymwdl); + +#include "date.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert(!std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(std::is_convertible{}, ""); + +void +test_arithmetic() +{ + using namespace date; + + for (int y1 = 2010; y1 <= 2015; ++y1) + { + for (int m1 = 1; m1 <= 12; ++m1) + { + auto ymd1 = mon[last]/m1/y1;; + auto ymd2 = ymd1 + months(24); + assert(ymd2 == mon[last]/m1/(y1+2)); + ymd2 = ymd1 - months(24); + assert(ymd2 == mon[last]/m1/(y1-2)); + for (int m2 = -24; m2 <= 24; ++m2) + { + months m{m2}; + auto ymd3 = ymd1 + m; + months dm = year_month{ymd3.year(), ymd3.month()} - + year_month{ymd2.year(), ymd2.month()}; + assert(dm == m + years{2}); + assert(ymd3 - m == ymd1); + assert(ymd3 + -m == ymd1); + assert(-m + ymd3 == ymd1); + assert((year_month_weekday_last{ymd1} += m) == ymd3); + assert((year_month_weekday_last{ymd3} -= m) == ymd1); + } + for (int y2 = -2; y2 <= 5; ++y2) + { + years y{y2}; + auto ymd3 = ymd1 + y; + years dy = floor(year_month{ymd3.year(), ymd3.month()} - + year_month{ymd2.year(), ymd2.month()}); + assert(dy == y + years{2}); + assert(ymd3 - y == ymd1); + assert(ymd3 + -y == ymd1); + assert(-y + ymd3 == ymd1); + assert((year_month_weekday_last{ymd1} += y) == ymd3); + assert((year_month_weekday_last{ymd3} -= y) == ymd1); + } + } + } +} + +int +main() +{ + using namespace date; + + constexpr year_month_weekday_last ymdl1 = {2015_y, aug, weekday_last{fri}}; + static_assert(ymdl1.ok(), ""); + static_assert(ymdl1.year() == 2015_y, ""); + static_assert(ymdl1.month() == aug, ""); + static_assert(ymdl1.weekday() == fri, ""); + static_assert(ymdl1.weekday_last() == fri[last], ""); +#if __cplusplus >= 201402 + constexpr sys_days dp = ymdl1; + constexpr year_month_day ymd = dp; + static_assert(ymd == 2015_y/aug/28, ""); +#endif + + constexpr year_month_weekday_last ymdl2 = sat[last]/aug/2015; + + static_assert(ymdl1 == ymdl1, ""); + static_assert(ymdl1 != ymdl2, ""); + + test_arithmetic(); + + std::ostringstream os; + os << ymdl1; + assert(os.str() == "2015/Aug/Fri[last]"); + +} diff --git a/third_party/date/test/date_test/year_p_year.fail.cpp b/third_party/date/test/date_test/year_p_year.fail.cpp new file mode 100644 index 0000000..79e56b9 --- /dev/null +++ b/third_party/date/test/date_test/year_p_year.fail.cpp @@ -0,0 +1,32 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// year + year not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + auto x = 2015_y + 2015_y; +} diff --git a/third_party/date/test/date_test/years_m_year.fail.cpp b/third_party/date/test/date_test/years_m_year.fail.cpp new file mode 100644 index 0000000..b2c01cf --- /dev/null +++ b/third_party/date/test/date_test/years_m_year.fail.cpp @@ -0,0 +1,32 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// years - year not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + auto x = years{3} - 2015_y; +} diff --git a/third_party/date/test/date_test/years_m_year_month.fail.cpp b/third_party/date/test/date_test/years_m_year_month.fail.cpp new file mode 100644 index 0000000..c2cb96c --- /dev/null +++ b/third_party/date/test/date_test/years_m_year_month.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// years - year_month not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = years{1} - year_month{2015_y, jan}; +} diff --git a/third_party/date/test/date_test/years_m_year_month_day.fail.cpp b/third_party/date/test/date_test/years_m_year_month_day.fail.cpp new file mode 100644 index 0000000..beeb4f5 --- /dev/null +++ b/third_party/date/test/date_test/years_m_year_month_day.fail.cpp @@ -0,0 +1,33 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// years - year_month_day not allowed + +#include "date.h" + +int +main() +{ + using namespace date; + + auto x = 2015_y - year_month_day{2015_y, aug, 9_d}; +} diff --git a/third_party/date/test/iso_week/last.pass.cpp b/third_party/date/test/iso_week/last.pass.cpp new file mode 100644 index 0000000..dad8cbb --- /dev/null +++ b/third_party/date/test/iso_week/last.pass.cpp @@ -0,0 +1,34 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// constexpr struct last_spec {} last{}; + +#include "iso_week.h" + +#include + +static_assert(std::is_same{}, ""); + +int +main() +{ +} diff --git a/third_party/date/test/iso_week/lastweek_weekday.pass.cpp b/third_party/date/test/iso_week/lastweek_weekday.pass.cpp new file mode 100644 index 0000000..3ffbb25 --- /dev/null +++ b/third_party/date/test/iso_week/lastweek_weekday.pass.cpp @@ -0,0 +1,82 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class lastweek_weekday +// { +// iso_week::weekday wd_; // exposition only +// +// public: +// explicit constexpr lastweek_weekday(const iso_week::weekday& wd) noexcept; +// +// constexpr iso_week::weekday weekday() const noexcept; +// +// constexpr bool ok() const noexcept; +// }; +// +// constexpr bool operator==(const lastweek_weekday& x, const lastweek_weekday& y) noexcept; +// constexpr bool operator!=(const lastweek_weekday& x, const lastweek_weekday& y) noexcept; +// constexpr bool operator< (const lastweek_weekday& x, const lastweek_weekday& y) noexcept; +// constexpr bool operator> (const lastweek_weekday& x, const lastweek_weekday& y) noexcept; +// constexpr bool operator<=(const lastweek_weekday& x, const lastweek_weekday& y) noexcept; +// constexpr bool operator>=(const lastweek_weekday& x, const lastweek_weekday& y) noexcept; +// +// std::ostream& operator<<(std::ostream& os, const lastweek_weekday& md); + +#include "iso_week.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert(!std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_trivially_copyable{}, ""); +static_assert(std::is_standard_layout{}, ""); +static_assert(std::is_literal_type{}, ""); + +static_assert( std::is_nothrow_constructible{}, ""); +static_assert(!std::is_convertible{}, ""); + +int +main() +{ + using namespace iso_week; + + constexpr auto wn_wd = lastweek_weekday{tue}; + static_assert(wn_wd.weekday() == tue, ""); + + static_assert(wn_wd.ok(), ""); + + static_assert(wn_wd == lastweek_weekday{tue}, ""); + static_assert(!(wn_wd != lastweek_weekday{tue}), ""); + static_assert(wn_wd < lastweek_weekday{wed}, ""); + + std::ostringstream os; + os << wn_wd; + assert(os.str() == "W last-Tue"); +} diff --git a/third_party/date/test/iso_week/op_div_survey.pass.cpp b/third_party/date/test/iso_week/op_div_survey.pass.cpp new file mode 100644 index 0000000..52e1886 --- /dev/null +++ b/third_party/date/test/iso_week/op_div_survey.pass.cpp @@ -0,0 +1,196 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "iso_week.h" + +#include + +template +constexpr +auto +test(I i, J j, K k) -> decltype(i/j/k) +{ + return i/j/k; +} + +void +test(...) +{ +} + +int +main() +{ + using std::is_same; + using namespace iso_week; + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same{}, ""); + +} diff --git a/third_party/date/test/iso_week/weekday.pass.cpp b/third_party/date/test/iso_week/weekday.pass.cpp new file mode 100644 index 0000000..25b3545 --- /dev/null +++ b/third_party/date/test/iso_week/weekday.pass.cpp @@ -0,0 +1,227 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class weekday +// { +// unsigned char wd_; +// public: +// explicit constexpr weekday(unsigned wd) noexcept; +// constexpr weekday(date::weekday wd) noexcept; +// constexpr weekday(const sys_days& dp) noexcept; +// +// weekday& operator++() noexcept; +// weekday operator++(int) noexcept; +// weekday& operator--() noexcept; +// weekday operator--(int) noexcept; +// +// weekday& operator+=(const days& d) noexcept; +// weekday& operator-=(const days& d) noexcept; +// +// constexpr explicit operator unsigned() const noexcept; +// constexpr operator date::weekday() const noexcept; +// constexpr bool ok() const noexcept; +// +// // tested with weekday_indexed +// constexpr weekday_indexed operator[](unsigned index) const noexcept; +// // tested with weekday_last +// constexpr weekday_last operator[](last_spec) const noexcept; +// }; + +// constexpr bool operator==(const weekday& x, const weekday& y) noexcept; +// constexpr bool operator!=(const weekday& x, const weekday& y) noexcept; + +// constexpr weekday operator+(const weekday& x, const days& y) noexcept; +// constexpr weekday operator+(const days& x, const weekday& y) noexcept; +// constexpr weekday operator-(const weekday& x, const days& y) noexcept; +// constexpr days operator-(const weekday& x, const weekday& y) noexcept; + +// std::ostream& operator<<(std::ostream& os, const weekday& wd); + +// constexpr weekday sun{7}; +// constexpr weekday mon{1}; +// constexpr weekday tue{2}; +// constexpr weekday wed{3}; +// constexpr weekday thu{4}; +// constexpr weekday fri{5}; +// constexpr weekday sat{6}; + +#include "iso_week.h" +#include "date.h" + +#include +#include +#include + +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert(!std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_trivially_copyable{}, ""); +static_assert(std::is_standard_layout{}, ""); +static_assert(std::is_literal_type{}, ""); + +static_assert( std::is_nothrow_constructible{}, ""); +static_assert( std::is_nothrow_constructible{}, ""); +static_assert( std::is_nothrow_constructible{}, ""); +static_assert( std::is_nothrow_constructible{}, ""); +static_assert( std::is_nothrow_constructible{}, ""); +static_assert(!std::is_convertible{}, ""); +static_assert( std::is_convertible{}, ""); +static_assert( std::is_convertible{}, ""); +static_assert( std::is_convertible{}, ""); +static_assert(!std::is_convertible{}, ""); +static_assert(static_cast(iso_week::weekday{1u}) == 1, ""); + +static_assert(!iso_week::weekday{0u}.ok(), ""); +static_assert( iso_week::weekday{1u}.ok(), ""); +static_assert( iso_week::weekday{2u}.ok(), ""); +static_assert( iso_week::weekday{3u}.ok(), ""); +static_assert( iso_week::weekday{4u}.ok(), ""); +static_assert( iso_week::weekday{5u}.ok(), ""); +static_assert( iso_week::weekday{6u}.ok(), ""); +static_assert( iso_week::weekday{7u}.ok(), ""); + +void +test_weekday_arithmetic() +{ + using namespace iso_week; + constexpr unsigned a[7][7] = + {// - Mon Tue Wed Thu Fri Sat Sun + /*Mon*/ {0, 6, 5, 4, 3, 2, 1}, + /*Tue*/ {1, 0, 6, 5, 4, 3, 2}, + /*Wed*/ {2, 1, 0, 6, 5, 4, 3}, + /*Thu*/ {3, 2, 1, 0, 6, 5, 4}, + /*Fri*/ {4, 3, 2, 1, 0, 6, 5}, + /*Sat*/ {5, 4, 3, 2, 1, 0, 6}, + /*Sun*/ {6, 5, 4, 3, 2, 1, 0} + }; + for (unsigned x = 1; x <= 7; ++x) + { + for (unsigned y = 1; y <= 7; ++y) + { + assert(weekday{x} - weekday{y} == days{a[x-1][y-1]}); + assert(weekday{x} - days{a[x-1][y-1]} == weekday{y}); + assert(weekday{x} == weekday{y} + days{a[x-1][y-1]}); + assert(weekday{x} == days{a[x-1][y-1]} + weekday{y}); + } + } + for (unsigned x = 1; x <= 7; ++x) + { + for (int y = -21; y < 21; ++y) + { + weekday wx{x}; + days dy{y}; + wx += dy; + weekday wz = weekday{x} + days{y}; + assert(wx.ok()); + assert(wz.ok()); + assert(wx == wz); + assert(wx - weekday{x} == days{y % 7 + (y % 7 < 0 ? 7 : 0)}); + } + } + for (unsigned x = 1; x <= 7; ++x) + { + for (int y = -21; y < 21; ++y) + { + weekday wx{x}; + days dy{y}; + wx -= dy; + assert(wx == weekday{x} + days{-y}); + } + } + for (unsigned x = 1; x <= 7; ++x) + { + weekday wx{x}; + assert(++wx - weekday{x} == days{1}); + assert(wx++ - weekday{x} == days{1}); + assert(wx - weekday{x} == days{2}); + assert(wx-- - weekday{x} == days{2}); + assert(wx - weekday{x} == days{1}); + assert(--wx - weekday{x} == days{0}); + } +} + +void +test_with_date_weekday() +{ + auto constexpr d1 = iso_week::sun; + static_assert(unsigned{d1} == 7, ""); + auto constexpr d2 = date::weekday{d1}; + static_assert(d2 == date::Sunday, ""); + auto constexpr d3 = iso_week::weekday{d2}; + static_assert(unsigned{d3} == 7, ""); +} + +int +main() +{ + using namespace iso_week; + + static_assert(sun == weekday{7u}, ""); + static_assert(mon == weekday{1u}, ""); + static_assert(tue == weekday{2u}, ""); + static_assert(wed == weekday{3u}, ""); + static_assert(thu == weekday{4u}, ""); + static_assert(fri == weekday{5u}, ""); + static_assert(sat == weekday{6u}, ""); + + static_assert(!(sun != sun), ""); + static_assert( sun != mon, ""); + static_assert( mon != sun, ""); + + test_weekday_arithmetic(); + test_with_date_weekday(); + + std::ostringstream os; + + os << sun; + assert(os.str() == "Sun"); + os.str(""); + + os << mon; + assert(os.str() == "Mon"); + os.str(""); + + os << tue; + assert(os.str() == "Tue"); + os.str(""); + + os << wed; + assert(os.str() == "Wed"); + os.str(""); + + os << thu; + assert(os.str() == "Thu"); + os.str(""); + + os << fri; + assert(os.str() == "Fri"); + os.str(""); + + os << sat; + assert(os.str() == "Sat"); +} diff --git a/third_party/date/test/iso_week/weekday_lessthan.fail.cpp b/third_party/date/test/iso_week/weekday_lessthan.fail.cpp new file mode 100644 index 0000000..ff74e16 --- /dev/null +++ b/third_party/date/test/iso_week/weekday_lessthan.fail.cpp @@ -0,0 +1,32 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// weekday < weekday not allowed + +#include "iso_week.h" + +int +main() +{ + using namespace iso_week; + auto b = sun < mon; +} diff --git a/third_party/date/test/iso_week/weekday_sum.fail.cpp b/third_party/date/test/iso_week/weekday_sum.fail.cpp new file mode 100644 index 0000000..648af12 --- /dev/null +++ b/third_party/date/test/iso_week/weekday_sum.fail.cpp @@ -0,0 +1,32 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// weekday + weekday not allowed + +#include "iso_week.h" + +int +main() +{ + using namespace iso_week; + auto b = sun + mon; +} diff --git a/third_party/date/test/iso_week/weeknum.pass.cpp b/third_party/date/test/iso_week/weeknum.pass.cpp new file mode 100644 index 0000000..5e60d77 --- /dev/null +++ b/third_party/date/test/iso_week/weeknum.pass.cpp @@ -0,0 +1,121 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class weeknum +// { +// unsigned char wn_; +// +// public: +// explicit constexpr weeknum(unsigned wn) noexcept; +// +// weeknum& operator++() noexcept; +// weeknum operator++(int) noexcept; +// weeknum& operator--() noexcept; +// weeknum operator--(int) noexcept; +// +// weeknum& operator+=(const weeks& y) noexcept; +// weeknum& operator-=(const weeks& y) noexcept; +// +// constexpr explicit operator unsigned() const noexcept; +// constexpr bool ok() const noexcept; +// }; +// +// constexpr bool operator==(const weeknum& x, const weeknum& y) noexcept; +// constexpr bool operator!=(const weeknum& x, const weeknum& y) noexcept; +// constexpr bool operator< (const weeknum& x, const weeknum& y) noexcept; +// constexpr bool operator> (const weeknum& x, const weeknum& y) noexcept; +// constexpr bool operator<=(const weeknum& x, const weeknum& y) noexcept; +// constexpr bool operator>=(const weeknum& x, const weeknum& y) noexcept; +// +// constexpr weeknum operator+(const weeknum& x, const weeks& y) noexcept; +// constexpr weeknum operator+(const weeks& x, const weeknum& y) noexcept; +// constexpr weeknum operator-(const weeknum& x, const weeks& y) noexcept; +// constexpr weeks operator-(const weeknum& x, const weeknum& y) noexcept; +// +// std::ostream& operator<<(std::ostream& os, const weeknum& wn); +// +// constexpr weeknum operator "" _w(unsigned long long wn) noexcept; + +#include "iso_week.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert(!std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_trivially_copyable{}, ""); +static_assert(std::is_standard_layout{}, ""); +static_assert(std::is_literal_type{}, ""); + +static_assert( std::is_nothrow_constructible{}, ""); +static_assert(!std::is_convertible{}, ""); +static_assert( std::is_nothrow_constructible{}, ""); +static_assert(!std::is_convertible{}, ""); +static_assert(static_cast(iso_week::weeknum{3}) == 3, ""); + +int +main() +{ + using namespace iso_week; + using namespace std::chrono; + + static_assert(weeknum{2} == 2_w, ""); + static_assert(unsigned{weeknum{2}} == 2, ""); + static_assert(unsigned{weeknum{3}} == 3, ""); + static_assert(weeknum{2} != 3_w, ""); + static_assert(weeknum{2} < 3_w, ""); + static_assert(weeknum{3} > 2_w, ""); + static_assert(weeknum{2} <= 2_w, ""); + static_assert(weeknum{3} >= 2_w, ""); + + auto wn = weeknum{4}; + assert(++wn == weeknum{5}); + assert(wn == weeknum{5}); + assert(wn++ == weeknum{5}); + assert(wn == weeknum{6}); + assert(--wn == weeknum{5}); + assert(wn == weeknum{5}); + assert(wn-- == weeknum{5}); + assert(wn == weeknum{4}); + + static_assert(!weeknum{0}.ok(), ""); + static_assert( weeknum{1}.ok(), ""); + static_assert( weeknum{53}.ok(), ""); + static_assert(!weeknum{54}.ok(), ""); + + static_assert(15_w - 10_w == weeks{5}, ""); + static_assert(15_w - weeks{5} == 10_w, ""); + static_assert(15_w == weeks{5} + 10_w, ""); + static_assert(15_w == 10_w + weeks{5}, ""); + static_assert(10_w - 15_w == -weeks{5}, ""); + + auto w = 5_w; + std::ostringstream os; + os << w; + assert(os.str() == "W05"); +} diff --git a/third_party/date/test/iso_week/weeknum_p_weeknum.fail.cpp b/third_party/date/test/iso_week/weeknum_p_weeknum.fail.cpp new file mode 100644 index 0000000..2199aa3 --- /dev/null +++ b/third_party/date/test/iso_week/weeknum_p_weeknum.fail.cpp @@ -0,0 +1,32 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// weeknum + weeknum not allowed + +#include "iso_week.h" + +int +main() +{ + using namespace iso_week; + auto x = 3_w + 4_w; +} diff --git a/third_party/date/test/iso_week/weeknum_weekday.pass.cpp b/third_party/date/test/iso_week/weeknum_weekday.pass.cpp new file mode 100644 index 0000000..c02c093 --- /dev/null +++ b/third_party/date/test/iso_week/weeknum_weekday.pass.cpp @@ -0,0 +1,86 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class weeknum_weekday +// { +// iso_week::weeknum wn_; // exposition only +// iso_week::weekday wd_; // exposition only +// +// public: +// constexpr weeknum_weekday(const iso_week::weeknum& wn, +// const iso_week::weekday& wd) noexcept; +// +// constexpr iso_week::weeknum weeknum() const noexcept; +// constexpr iso_week::weekday weekday() const noexcept; +// +// constexpr bool ok() const noexcept; +// }; +// +// constexpr bool operator==(const weeknum_weekday& x, const weeknum_weekday& y) noexcept; +// constexpr bool operator!=(const weeknum_weekday& x, const weeknum_weekday& y) noexcept; +// constexpr bool operator< (const weeknum_weekday& x, const weeknum_weekday& y) noexcept; +// constexpr bool operator> (const weeknum_weekday& x, const weeknum_weekday& y) noexcept; +// constexpr bool operator<=(const weeknum_weekday& x, const weeknum_weekday& y) noexcept; +// constexpr bool operator>=(const weeknum_weekday& x, const weeknum_weekday& y) noexcept; +// +// std::ostream& operator<<(std::ostream& os, const weeknum_weekday& md); + +#include "iso_week.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert(!std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_trivially_copyable{}, ""); +static_assert(std::is_standard_layout{}, ""); +static_assert(std::is_literal_type{}, ""); + +static_assert( std::is_nothrow_constructible{}, ""); + +int +main() +{ + using namespace iso_week; + + constexpr auto wn_wd = weeknum_weekday{52_w, tue}; + static_assert(wn_wd.weeknum() == 52_w, ""); + static_assert(wn_wd.weekday() == tue, ""); + + static_assert(wn_wd.ok(), ""); + + static_assert(wn_wd == weeknum_weekday{52_w, tue}, ""); + static_assert(!(wn_wd != weeknum_weekday{52_w, tue}), ""); + static_assert(wn_wd < weeknum_weekday{52_w, wed}, ""); + + std::ostringstream os; + os << wn_wd; + assert(os.str() == "W52-Tue"); +} diff --git a/third_party/date/test/iso_week/year.pass.cpp b/third_party/date/test/iso_week/year.pass.cpp new file mode 100644 index 0000000..1f1675a --- /dev/null +++ b/third_party/date/test/iso_week/year.pass.cpp @@ -0,0 +1,120 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class year +// { +// public: +// explicit constexpr year(int y) noexcept; +// +// year& operator++() noexcept; +// year operator++(int) noexcept; +// year& operator--() noexcept; +// year operator--(int) noexcept; +// +// year& operator+=(const years& y) noexcept; +// year& operator-=(const years& y) noexcept; +// +// constexpr explicit operator int() const noexcept; +// constexpr bool ok() const noexcept; +// +// static constexpr year min() noexcept; +// static constexpr year max() noexcept; +// }; + +// constexpr bool operator==(const year& x, const year& y) noexcept; +// constexpr bool operator!=(const year& x, const year& y) noexcept; +// constexpr bool operator< (const year& x, const year& y) noexcept; +// constexpr bool operator> (const year& x, const year& y) noexcept; +// constexpr bool operator<=(const year& x, const year& y) noexcept; +// constexpr bool operator>=(const year& x, const year& y) noexcept; + +// constexpr year operator+(const year& x, const years& y) noexcept; +// constexpr year operator+(const years& x, const year& y) noexcept; +// constexpr year operator-(const year& x, const years& y) noexcept; +// constexpr years operator-(const year& x, const year& y) noexcept; + +// std::ostream& operator<<(std::ostream& os, const year& y); +// inline namespace literals { +// constexpr year operator "" _y(unsigned long long y) noexcept; +// } + +#include "iso_week.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert(!std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_trivially_copyable{}, ""); +static_assert(std::is_standard_layout{}, ""); +static_assert(std::is_literal_type{}, ""); + +static_assert( std::is_nothrow_constructible{}, ""); +static_assert(!std::is_convertible{}, ""); +static_assert( std::is_nothrow_constructible{}, ""); +static_assert(!std::is_convertible{}, ""); +static_assert(static_cast(iso_week::year{-1}) == -1, ""); + +int +main() +{ + using namespace iso_week; + + static_assert(year{2015} == 2015_y, ""); + static_assert(int{year{2015}} == 2015, ""); + static_assert(year{2015} != 2016_y, ""); + static_assert(year{2015} < 2016_y, ""); + static_assert(year{2016} > 2015_y, ""); + static_assert(year{2015} <= 2015_y, ""); + static_assert(year{2016} >= 2015_y, ""); + + auto y = year{2014}; + assert(++y == year{2015}); + assert(y == year{2015}); + assert(y++ == year{2015}); + assert(y == year{2016}); + assert(--y == year{2015}); + assert(y == year{2015}); + assert(y-- == year{2015}); + assert(y == year{2014}); + + static_assert(year::min().ok(), ""); + static_assert(year{2015}.ok(), ""); + static_assert(year{2016}.ok(), ""); + static_assert(year::max().ok(), ""); + + static_assert(2015_y - 2010_y == years{5}, ""); + static_assert(2015_y - years{5} == 2010_y, ""); + static_assert(2015_y == years{5} + 2010_y, ""); + static_assert(2015_y == 2010_y + years{5}, ""); + + y = 2015_y; + std::ostringstream os; + os << y; + assert(os.str() == "2015"); +} diff --git a/third_party/date/test/iso_week/year_lastweek.pass.cpp b/third_party/date/test/iso_week/year_lastweek.pass.cpp new file mode 100644 index 0000000..8874472 --- /dev/null +++ b/third_party/date/test/iso_week/year_lastweek.pass.cpp @@ -0,0 +1,97 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class year_lastweek +// { +// iso_week::year y_; +// +// public: +// explicit constexpr year_lastweek(const iso_week::year& y) noexcept; +// +// constexpr iso_week::year year() const noexcept; +// constexpr iso_week::weeknum weeknum() const noexcept; +// +// year_lastweek& operator+=(const years& dy) noexcept; +// year_lastweek& operator-=(const years& dy) noexcept; +// +// constexpr bool ok() const noexcept; +// }; +// +// constexpr bool operator==(const year_lastweek& x, const year_lastweek& y) noexcept; +// constexpr bool operator!=(const year_lastweek& x, const year_lastweek& y) noexcept; +// constexpr bool operator< (const year_lastweek& x, const year_lastweek& y) noexcept; +// constexpr bool operator> (const year_lastweek& x, const year_lastweek& y) noexcept; +// constexpr bool operator<=(const year_lastweek& x, const year_lastweek& y) noexcept; +// constexpr bool operator>=(const year_lastweek& x, const year_lastweek& y) noexcept; +// +// constexpr year_lastweek operator+(const year_lastweek& ym, const years& dy) noexcept; +// constexpr year_lastweek operator+(const years& dy, const year_lastweek& ym) noexcept; +// constexpr year_lastweek operator-(const year_lastweek& ym, const years& dy) noexcept; +// +// std::ostream& operator<<(std::ostream& os, const year_lastweek& ym); + +#include "iso_week.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert(!std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_trivially_copyable{}, ""); +static_assert(std::is_standard_layout{}, ""); +static_assert(std::is_literal_type{}, ""); + +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(!std::is_convertible{}, ""); + +int +main() +{ + using namespace iso_week; + + constexpr auto y_wn = year_lastweek{2015_y}; + static_assert(y_wn.year() == 2015_y, ""); + static_assert(y_wn.weeknum() == 53_w, ""); + static_assert(year_lastweek{2016_y}.weeknum() == 52_w, ""); + + static_assert(y_wn.ok(), ""); + + static_assert(y_wn == year_lastweek{2015_y}, ""); + static_assert(!(y_wn != year_lastweek{2015_y}), ""); + static_assert(y_wn < year_lastweek{2016_y}, ""); + + auto y_wn2 = y_wn + years{2}; + assert(y_wn2 == year_lastweek{2017_y}); + y_wn2 -= years{1}; + assert(y_wn2 == year_lastweek{2016_y}); + + std::ostringstream os; + os << y_wn; + assert(os.str() == "2015-W last"); +} diff --git a/third_party/date/test/iso_week/year_lastweek_weekday.pass.cpp b/third_party/date/test/iso_week/year_lastweek_weekday.pass.cpp new file mode 100644 index 0000000..5f65f6f --- /dev/null +++ b/third_party/date/test/iso_week/year_lastweek_weekday.pass.cpp @@ -0,0 +1,129 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class year_lastweek_weekday +// { +// public: +// constexpr year_lastweek_weekday(const iso_week::year& y, +// const iso_week::weekday& wd) noexcept; +// +// year_lastweek_weekday& operator+=(const years& y) noexcept; +// year_lastweek_weekday& operator-=(const years& y) noexcept; +// +// constexpr iso_week::year year() const noexcept; +// constexpr iso_week::weeknum weeknum() const noexcept; +// constexpr iso_week::weekday weekday() const noexcept; +// +// constexpr operator sys_days() const noexcept; +// constexpr bool ok() const noexcept; +// }; +// +// constexpr bool operator==(const year_lastweek_weekday& x, const year_lastweek_weekday& y) noexcept; +// constexpr bool operator!=(const year_lastweek_weekday& x, const year_lastweek_weekday& y) noexcept; +// constexpr bool operator< (const year_lastweek_weekday& x, const year_lastweek_weekday& y) noexcept; +// constexpr bool operator> (const year_lastweek_weekday& x, const year_lastweek_weekday& y) noexcept; +// constexpr bool operator<=(const year_lastweek_weekday& x, const year_lastweek_weekday& y) noexcept; +// constexpr bool operator>=(const year_lastweek_weekday& x, const year_lastweek_weekday& y) noexcept; +// +// constexpr year_lastweek_weekday operator+(const year_lastweek_weekday& x, const years& y) noexcept; +// constexpr year_lastweek_weekday operator+(const years& y, const year_lastweek_weekday& x) noexcept; +// constexpr year_lastweek_weekday operator-(const year_lastweek_weekday& x, const years& y) noexcept; +// +// std::ostream& operator<<(std::ostream& os, const year_lastweek_weekday& x); + +#include "iso_week.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert(!std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_trivially_copyable{}, ""); +static_assert(std::is_standard_layout{}, ""); +static_assert(std::is_literal_type{}, ""); + +static_assert( std::is_nothrow_constructible{}, ""); +static_assert( std::is_nothrow_constructible{}, ""); +static_assert( std::is_convertible{}, ""); + +int +main() +{ + using namespace iso_week; + + constexpr auto x0 = year_lastweek_weekday{2015_y, tue}; + static_assert(x0.year() == 2015_y, ""); + static_assert(x0.weeknum() == 53_w, ""); + static_assert(x0.weekday() == tue, ""); + + auto x3 = x0; + x3 += years{2}; + assert(x3.year() == 2017_y); + assert(x3.weeknum() == 52_w); + assert(x3.weekday() == tue); + + x3 -= years{1}; + assert(x3.year() == 2016_y); + assert(x3.weeknum() == 52_w); + assert(x3.weekday() == tue); + + x3 -= years{1}; + assert(x3.year() == 2015_y); + assert(x3.weeknum() == 53_w); + assert(x3.weekday() == tue); + + constexpr sys_days dp = 2015_y/last/wed; + static_assert(dp == sys_days{days{16799}}, ""); + + static_assert(x0.ok(), ""); + assert(x3.ok()); + + static_assert(2015_y/last/mon < 2015_y/last/sun, ""); + + static_assert(x0 + years{3} == 2018_y/last/tue, ""); + static_assert(years{3} + x0 == 2018_y/last/tue, ""); + static_assert(x0 - years{3} == 2012_y/last/tue, ""); + + std::ostringstream os; + os << x0; + assert(os.str() == "2015-W last-Tue"); + + for (auto y = 1950_y; y <= 2050_y; ++y) + { + auto wd = mon; + do + { + auto x = y/last/wd; + assert(date::year_month_day{x} == date::year_month_day{year_weeknum_weekday{x}}); + ++wd; + } while (wd != mon); + } +} diff --git a/third_party/date/test/iso_week/year_p_year.fail.cpp b/third_party/date/test/iso_week/year_p_year.fail.cpp new file mode 100644 index 0000000..c0eba47 --- /dev/null +++ b/third_party/date/test/iso_week/year_p_year.fail.cpp @@ -0,0 +1,32 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// year + year not allowed + +#include "iso_week.h" + +int +main() +{ + using namespace iso_week; + auto x = 2015_y + 2015_y; +} diff --git a/third_party/date/test/iso_week/year_weeknum.pass.cpp b/third_party/date/test/iso_week/year_weeknum.pass.cpp new file mode 100644 index 0000000..6e9d4b6 --- /dev/null +++ b/third_party/date/test/iso_week/year_weeknum.pass.cpp @@ -0,0 +1,97 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class year_weeknum +// { +// iso_week::year y_; +// iso_week::weeknum wn_; +// +// public: +// constexpr year_weeknum(const iso_week::year& y, const iso_week::weeknum& wn) noexcept; +// +// constexpr iso_week::year year() const noexcept; +// constexpr iso_week::weeknum weeknum() const noexcept; +// +// year_weeknum& operator+=(const years& dy) noexcept; +// year_weeknum& operator-=(const years& dy) noexcept; +// +// constexpr bool ok() const noexcept; +// }; +// +// constexpr bool operator==(const year_weeknum& x, const year_weeknum& y) noexcept; +// constexpr bool operator!=(const year_weeknum& x, const year_weeknum& y) noexcept; +// constexpr bool operator< (const year_weeknum& x, const year_weeknum& y) noexcept; +// constexpr bool operator> (const year_weeknum& x, const year_weeknum& y) noexcept; +// constexpr bool operator<=(const year_weeknum& x, const year_weeknum& y) noexcept; +// constexpr bool operator>=(const year_weeknum& x, const year_weeknum& y) noexcept; +// +// constexpr year_weeknum operator+(const year_weeknum& ym, const years& dy) noexcept; +// constexpr year_weeknum operator+(const years& dy, const year_weeknum& ym) noexcept; +// constexpr year_weeknum operator-(const year_weeknum& ym, const years& dy) noexcept; +// +// std::ostream& operator<<(std::ostream& os, const year_weeknum& ym); + +#include "iso_week.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert(!std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_trivially_copyable{}, ""); +static_assert(std::is_standard_layout{}, ""); +static_assert(std::is_literal_type{}, ""); + +static_assert( std::is_nothrow_constructible{}, ""); + +int +main() +{ + using namespace iso_week; + + constexpr auto y_wn = year_weeknum{2015_y, 52_w}; + static_assert(y_wn.year() == 2015_y, ""); + static_assert(y_wn.weeknum() == 52_w, ""); + + static_assert(y_wn.ok(), ""); + + static_assert(y_wn == year_weeknum{2015_y, 52_w}, ""); + static_assert(!(y_wn != year_weeknum{2015_y, 52_w}), ""); + static_assert(y_wn < year_weeknum{2015_y, 53_w}, ""); + + auto y_wn2 = y_wn + years{2}; + assert((y_wn2 == year_weeknum{2017_y, 52_w})); + y_wn2 -= years{1}; + assert((y_wn2 == year_weeknum{2016_y, 52_w})); + + std::ostringstream os; + os << y_wn; + assert(os.str() == "2015-W52"); +} diff --git a/third_party/date/test/iso_week/year_weeknum_weekday.pass.cpp b/third_party/date/test/iso_week/year_weeknum_weekday.pass.cpp new file mode 100644 index 0000000..0540f97 --- /dev/null +++ b/third_party/date/test/iso_week/year_weeknum_weekday.pass.cpp @@ -0,0 +1,139 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class year_weeknum_weekday + +// class year_weeknum_weekday +// { +// public: +// constexpr year_weeknum_weekday(const iso_week::year& y, const iso_week::weeknum& wn, +// const iso_week::weekday& wd) noexcept; +// constexpr year_weeknum_weekday(const year_lastweek_weekday& ylwwd) noexcept; +// constexpr year_weeknum_weekday(const sys_days& dp) noexcept; +// +// year_weeknum_weekday& operator+=(const years& y) noexcept; +// year_weeknum_weekday& operator-=(const years& y) noexcept; +// +// constexpr iso_week::year year() const noexcept; +// constexpr iso_week::weeknum weeknum() const noexcept; +// constexpr iso_week::weekday weekday() const noexcept; +// +// constexpr operator sys_days() const noexcept; +// constexpr bool ok() const noexcept; +// }; +// +// constexpr bool operator==(const year_weeknum_weekday& x, const year_weeknum_weekday& y) noexcept; +// constexpr bool operator!=(const year_weeknum_weekday& x, const year_weeknum_weekday& y) noexcept; +// constexpr bool operator< (const year_weeknum_weekday& x, const year_weeknum_weekday& y) noexcept; +// constexpr bool operator> (const year_weeknum_weekday& x, const year_weeknum_weekday& y) noexcept; +// constexpr bool operator<=(const year_weeknum_weekday& x, const year_weeknum_weekday& y) noexcept; +// constexpr bool operator>=(const year_weeknum_weekday& x, const year_weeknum_weekday& y) noexcept; +// +// constexpr year_weeknum_weekday operator+(const year_weeknum_weekday& ywnwd, const years& y) noexcept; +// constexpr year_weeknum_weekday operator+(const years& y, const year_weeknum_weekday& ywnwd) noexcept; +// constexpr year_weeknum_weekday operator-(const year_weeknum_weekday& ywnwd, const years& y) noexcept; +// +// std::ostream& operator<<(std::ostream& os, const year_weeknum_weekday& ywnwd); + +#include "iso_week.h" + +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert(!std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_trivially_copyable{}, ""); +static_assert(std::is_standard_layout{}, ""); +static_assert(std::is_literal_type{}, ""); + +static_assert( std::is_nothrow_constructible{}, ""); +static_assert( std::is_nothrow_constructible{}, ""); +static_assert( std::is_convertible{}, ""); +static_assert( std::is_nothrow_constructible{}, ""); +static_assert( std::is_convertible{}, ""); +static_assert( std::is_nothrow_constructible{}, ""); +static_assert( std::is_convertible{}, ""); + +int +main() +{ + using namespace iso_week; + + constexpr auto x0 = year_weeknum_weekday{2015_y, 52_w, tue}; + static_assert(x0.year() == 2015_y, ""); + static_assert(x0.weeknum() == 52_w, ""); + static_assert(x0.weekday() == tue, ""); + + constexpr auto x1 = year_weeknum_weekday{2015_y/last/tue}; + static_assert(x1.year() == 2015_y, ""); + static_assert(x1.weeknum() == 53_w, ""); + static_assert(x1.weekday() == tue, ""); + + constexpr year_weeknum_weekday x2 = sys_days{days{16792}}; + static_assert(x2.year() == 2015_y, ""); + static_assert(x2.weeknum() == 52_w, ""); + static_assert(x2.weekday() == wed, ""); + + auto x3 = x2; + x3 += years{2}; + assert(x3.year() == 2017_y); + assert(x3.weeknum() == 52_w); + assert(x3.weekday() == wed); + + x3 -= years{1}; + assert(x3.year() == 2016_y); + assert(x3.weeknum() == 52_w); + assert(x3.weekday() == wed); + + constexpr sys_days dp = 2015_y/52_w/wed; + static_assert(dp == sys_days{days{16792}}, ""); + + static_assert(x0.ok(), ""); + static_assert(x1.ok(), ""); + static_assert(x2.ok(), ""); + assert(x3.ok()); + static_assert(!(2016_y/53_w/sun).ok(), ""); + + static_assert(2015_y/52_w/mon < 2015_y/52_w/sun, ""); + + static_assert(x0 + years{3} == 2018_y/52_w/tue, ""); + static_assert(years{3} + x0 == 2018_y/52_w/tue, ""); + static_assert(x0 - years{3} == 2012_y/52_w/tue, ""); + + std::ostringstream os; + os << x0; + assert(os.str() == "2015-W52-Tue"); +} diff --git a/third_party/date/test/iso_week/years_m_year.fail.cpp b/third_party/date/test/iso_week/years_m_year.fail.cpp new file mode 100644 index 0000000..8eb4307 --- /dev/null +++ b/third_party/date/test/iso_week/years_m_year.fail.cpp @@ -0,0 +1,32 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// years - year not allowed + +#include "iso_week.h" + +int +main() +{ + using namespace iso_week; + auto x = years{3} - 2015_y; +} diff --git a/third_party/date/test/just.pass.cpp b/third_party/date/test/just.pass.cpp new file mode 100644 index 0000000..f31a8e9 --- /dev/null +++ b/third_party/date/test/just.pass.cpp @@ -0,0 +1,26 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +int +main() +{ +} diff --git a/third_party/date/test/posix/ptz.pass.cpp b/third_party/date/test/posix/ptz.pass.cpp new file mode 100644 index 0000000..5601c21 --- /dev/null +++ b/third_party/date/test/posix/ptz.pass.cpp @@ -0,0 +1,108 @@ +// The MIT License (MIT) +// +// Copyright (c) 2021 Howard Hinnant +// +// 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. + +// Test Posix::time_zone + +#include "tz.h" +#include "ptz.h" +#include + +bool +is_equal(date::sys_info const& x, date::sys_info const& y) +{ + return x.begin == y.begin && + x.end == y.end && + x.offset == y.offset && + x.save == y.save && + x.abbrev == y.abbrev; +} + +bool +is_equal(date::local_info const& x, date::local_info const& y) +{ + return x.result == y.result && is_equal(x.first, y.first) + && is_equal(x.second, y.second); +} + +int +main() +{ + using namespace date; + using namespace std; + using namespace std::chrono; + + auto tzi = locate_zone("Australia/Sydney"); + Posix::time_zone tzp{"AEST-10AEDT,M10.1.0,M4.1.0/3"}; + auto tp = local_days{2021_y/1/1} + 0s; + assert(tzp.get_info(tp).result == local_info::unique); + assert(is_equal(tzi->get_info(tp), tzp.get_info(tp))); + + tp = local_days{2021_y/10/Sunday[1]} + 2h + 30min; + assert(tzp.get_info(tp).result == local_info::nonexistent); + assert(is_equal(tzi->get_info(tp), tzp.get_info(tp))); + + tp = local_days{2021_y/4/Sunday[1]} + 2h + 30min; + assert(tzp.get_info(tp).result == local_info::ambiguous); + assert(is_equal(tzi->get_info(tp), tzp.get_info(tp))); + + tp = local_days{2021_y/7/1}; + assert(tzp.get_info(tp).result == local_info::unique); + assert(is_equal(tzi->get_info(tp), tzp.get_info(tp))); + + + tzi = locate_zone("America/New_York"); + tzp = Posix::time_zone{"EST5EDT,M3.2.0,M11.1.0"}; + tp = local_days{2021_y/1/1}; + assert(tzp.get_info(tp).result == local_info::unique); + assert(is_equal(tzi->get_info(tp), tzp.get_info(tp))); + + tp = local_days{2021_y/3/Sunday[2]} + 2h + 30min; + assert(tzp.get_info(tp).result == local_info::nonexistent); + assert(is_equal(tzi->get_info(tp), tzp.get_info(tp))); + + tp = local_days{2021_y/11/Sunday[1]} + 1h + 30min; + assert(tzp.get_info(tp).result == local_info::ambiguous); + assert(is_equal(tzi->get_info(tp), tzp.get_info(tp))); + + tp = local_days{2021_y/7/1}; + assert(tzp.get_info(tp).result == local_info::unique); + assert(is_equal(tzi->get_info(tp), tzp.get_info(tp))); + + + tzi = locate_zone("Europe/Dublin"); + tzp = Posix::time_zone{"IST-1GMT0,M10.5.0,M3.5.0/1"}; + tp = local_days{2021_y/1/1}; + assert(tzp.get_info(tp).result == local_info::unique); + assert(is_equal(tzi->get_info(tp), tzp.get_info(tp))); + + tp = local_days{2021_y/3/Sunday[last]} + 1h + 30min; + assert(tzp.get_info(tp).result == local_info::nonexistent); + assert(is_equal(tzi->get_info(tp), tzp.get_info(tp))); + + tp = local_days{2021_y/10/Sunday[last]} + 1h + 30min; + assert(tzp.get_info(tp).result == local_info::ambiguous); + assert(is_equal(tzi->get_info(tp), tzp.get_info(tp))); + + tp = local_days{2021_y/7/1}; + assert(tzp.get_info(tp).result == local_info::unique); + assert(is_equal(tzi->get_info(tp), tzp.get_info(tp))); +} diff --git a/third_party/date/test/solar_hijri_test/parse.pass.cpp b/third_party/date/test/solar_hijri_test/parse.pass.cpp new file mode 100644 index 0000000..9a98209 --- /dev/null +++ b/third_party/date/test/solar_hijri_test/parse.pass.cpp @@ -0,0 +1,237 @@ +// The MIT License (MIT) +// +// Copyright (c) 2020 Asad. Gharighi +// Copyright (c) 2020 Howard Hinnant +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "date.h" +#include "solar_hijri.h" +#include "islamic.h" +#include "tz.h" +#include +#include +#include +#include + +void +test_a() { + constexpr auto civil = date::year{2020}/date::January/27; + using namespace solar_hijri; + static_assert(year_month_day{civil} == 1398_y/11/07, ""); +} + +void +test_b() { + using namespace solar_hijri::literals; + static_assert(date::year_month_day{475_y/far/1} == date::year{1096}/03/21, ""); + static_assert(date::year_month_weekday{475_y/far/1} == + date::year{1096}/03/date::Saturday[3], ""); +} + +void +test_c() { + using namespace solar_hijri; + auto date = solar_hijri::year_month_day{1398_y/bah/6}; + for (auto i = 0; i < 24; i++) { + auto weekday = solar_hijri::weekday{date}; + assert(date == 1398_y/11/06 + months{i}); + assert(date.month() == month{(i+10u)%12 + 1}); + assert(weekday == (weekday[1]/date.month()/date.year()).weekday()); + auto k = weekday; + for (auto j = 0; j < 14; j++, k++) { + assert(weekday + days{j} == k); + } + date+=solar_hijri::months(1); + } +} + +void +test_d() { + auto zt = date::make_zoned(date::current_zone(), std::chrono::system_clock::now()); + auto ld = date::floor(zt.get_local_time()); + solar_hijri::year_month_day ymd{ld}; + auto time = date::make_time(zt.get_local_time() - ld); + (void)time; +} + +void +test_e() { + auto sd = date::floor(std::chrono::system_clock::now()); + auto today = solar_hijri::year_month_day{sd}; + assert(solar_hijri::year_month_weekday{today}.weekday() == solar_hijri::weekday{sd}); +} + +void +test_f() { + constexpr auto isl = islamic::year{1441}/6/1; + using namespace solar_hijri; + static_assert(year_month_day{isl} == 1398_y/11/07, ""); +} + +void +test_g() { + date::year_month_day ymdd[] = { + date::year{1583}/date::November/21, + date::year{1583}/date::November/22, + date::year{1583}/date::December/6, + date::year{1591}/date::December/26, + date::year{1616}/date::October/20, + date::year{1619}/date::October/13, + date::year{1627}/date::August/9, + date::year{1649}/date::October/15, + date::year{1657}/date::August/9, + date::year{1682}/date::June/23, + date::year{1691}/date::October/12, + date::year{1712}/date::September/13, + date::year{1718}/date::July/17, + date::year{1747}/date::January/4, + date::year{1756}/date::January/1, + date::year{1770}/date::January/15, + date::year{1798}/date::October/24, + date::year{1809}/date::July/11, + date::year{1834}/date::July/17, + date::year{1850}/date::September/9, + date::year{1865}/date::November/4, + date::year{1902}/date::December/21, + date::year{1926}/date::March/21, + date::year{1926}/date::March/22, + date::year{1957}/date::June/1, + date::year{1977}/date::March/7, + date::year{1982}/date::May/30, + date::year{1992}/date::December/8 + }; + + solar_hijri::year_month_day ymdh[] = { + solar_hijri::year{962}/solar_hijri::Aban/30, + solar_hijri::year{962}/solar_hijri::Azar/1, + solar_hijri::year{962}/solar_hijri::Azar/15, + solar_hijri::year{970}/solar_hijri::Dey/5, + solar_hijri::year{995}/solar_hijri::Mehr/29, + solar_hijri::year{998}/solar_hijri::Mehr/21, + solar_hijri::year{1006}/solar_hijri::Mordad/18, + solar_hijri::year{1028}/solar_hijri::Mehr/24, + solar_hijri::year{1036}/solar_hijri::Mordad/19, + solar_hijri::year{1061}/solar_hijri::Tir/3, + solar_hijri::year{1070}/solar_hijri::Mehr/20, + solar_hijri::year{1091}/solar_hijri::Shahrivar/22, + solar_hijri::year{1097}/solar_hijri::Tir/26, + solar_hijri::year{1125}/solar_hijri::Dey/14, + solar_hijri::year{1134}/solar_hijri::Dey/11, + solar_hijri::year{1148}/solar_hijri::Dey/26, + solar_hijri::year{1177}/solar_hijri::Aban/2, + solar_hijri::year{1188}/solar_hijri::Tir/20, + solar_hijri::year{1213}/solar_hijri::Tir/26, + solar_hijri::year{1229}/solar_hijri::Shahrivar/18, + solar_hijri::year{1244}/solar_hijri::Aban/13, + solar_hijri::year{1281}/solar_hijri::Azar/29, + solar_hijri::year{1304}/solar_hijri::Esfand/30, + solar_hijri::year{1305}/solar_hijri::Farvardin/1, + solar_hijri::year{1336}/solar_hijri::Khordad/11, + solar_hijri::year{1355}/solar_hijri::Esfand/16, + solar_hijri::year{1361}/solar_hijri::Khordad/9, + solar_hijri::year{1371}/solar_hijri::Azar/17 + }; + + solar_hijri::year_month_weekday ymdwd[] = { + solar_hijri::year{962}/solar_hijri::Aban/solar_hijri::Doshanbe[5], + solar_hijri::year{962}/solar_hijri::Azar/solar_hijri::Seshanbe[1], + solar_hijri::year{962}/solar_hijri::Azar/solar_hijri::Seshanbe[3], + solar_hijri::year{970}/solar_hijri::Dey/solar_hijri::Panjshanbe[1], + solar_hijri::year{995}/solar_hijri::Mehr/solar_hijri::Panjshanbe[5], + solar_hijri::year{998}/solar_hijri::Mehr/solar_hijri::Yekshanbe[3], + solar_hijri::year{1006}/solar_hijri::Mordad/solar_hijri::Doshanbe[3], + solar_hijri::year{1028}/solar_hijri::Mehr/solar_hijri::Adine[4], + solar_hijri::year{1036}/solar_hijri::Mordad/solar_hijri::Panjshanbe[3], + solar_hijri::year{1061}/solar_hijri::Tir/solar_hijri::Seshanbe[1], + solar_hijri::year{1070}/solar_hijri::Mehr/solar_hijri::Adine[3], + solar_hijri::year{1091}/solar_hijri::Shahrivar/solar_hijri::Seshanbe[4], + solar_hijri::year{1097}/solar_hijri::Tir/solar_hijri::Yekshanbe[4], + solar_hijri::year{1125}/solar_hijri::Dey/solar_hijri::Chaharshanbe[2], + solar_hijri::year{1134}/solar_hijri::Dey/solar_hijri::Panjshanbe[2], + solar_hijri::year{1148}/solar_hijri::Dey/solar_hijri::Doshanbe[4], + solar_hijri::year{1177}/solar_hijri::Aban/solar_hijri::Chaharshanbe[1], + solar_hijri::year{1188}/solar_hijri::Tir/solar_hijri::Seshanbe[3], + solar_hijri::year{1213}/solar_hijri::Tir/solar_hijri::Panjshanbe[4], + solar_hijri::year{1229}/solar_hijri::Shahrivar/solar_hijri::Doshanbe[3], + solar_hijri::year{1244}/solar_hijri::Aban/solar_hijri::Shanbe[2], + solar_hijri::year{1281}/solar_hijri::Azar/solar_hijri::Yekshanbe[5], + solar_hijri::year{1304}/solar_hijri::Esfand/solar_hijri::Yekshanbe[5], + solar_hijri::year{1305}/solar_hijri::Farvardin/solar_hijri::Doshanbe[1], + solar_hijri::year{1336}/solar_hijri::Khordad/solar_hijri::Shanbe[2], + solar_hijri::year{1355}/solar_hijri::Esfand/solar_hijri::Doshanbe[3], + solar_hijri::year{1361}/solar_hijri::Khordad/solar_hijri::Yekshanbe[2], + solar_hijri::year{1371}/solar_hijri::Azar/solar_hijri::Seshanbe[3] + }; + + bool leaps[] = { + true, + true, + true, + true, + true, + false, + false, + true, + true, + true, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false + }; + + static_assert(sizeof(ymdd)/sizeof(ymdd[0]) == sizeof(ymdwd)/sizeof(ymdwd[0]), ""); + static_assert(sizeof(ymdd)/sizeof(ymdd[0]) == sizeof(ymdh)/sizeof(ymdh[0]), ""); + static_assert(sizeof(ymdd)/sizeof(ymdd[0]) == sizeof(leaps)/sizeof(leaps[0]), ""); + + for (auto i = 0; i < sizeof(ymdd)/sizeof(ymdd[0]); ++i) + { + assert(solar_hijri::year_month_day{ymdd[i]} == ymdh[i]); + assert(ymdd[i] == date::year_month_day{ymdh[i]}); + assert(ymdh[i].year().is_leap() == leaps[i]); + assert(solar_hijri::year_month_weekday{ymdd[i]} == ymdwd[i]); + } +} + +int +main() +{ + test_a(); + test_b(); + test_c(); + test_d(); + test_e(); + test_f(); + test_g(); +} diff --git a/third_party/date/test/solar_hijri_test/year_month_day.pass.cpp b/third_party/date/test/solar_hijri_test/year_month_day.pass.cpp new file mode 100644 index 0000000..5429314 --- /dev/null +++ b/third_party/date/test/solar_hijri_test/year_month_day.pass.cpp @@ -0,0 +1,168 @@ +// The MIT License (MIT) +// +// Copyright (c) 2020 Asad. Gharighi +// Copyright (c) 2015, 2016 Howard Hinnant +// +// 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. + +// class year_month_day +// { +// public: +// constexpr year_month_day(const date::year& y, const date::month& m, +// const date::day& d) noexcept; +// constexpr year_month_day(const year_month_day_last& ymdl) noexcept; +// constexpr year_month_day(const sys_days& dp) noexcept; +// +// year_month_day& operator+=(const months& m) noexcept; +// year_month_day& operator-=(const months& m) noexcept; +// year_month_day& operator+=(const years& y) noexcept; +// year_month_day& operator-=(const years& y) noexcept; +// +// constexpr date::year year() const noexcept; +// constexpr date::month month() const noexcept; +// constexpr date::day day() const noexcept; +// +// constexpr operator sys_days() const noexcept; +// constexpr bool ok() const noexcept; +// }; + +// constexpr bool operator==(const year_month_day& x, const year_month_day& y) noexcept; +// constexpr bool operator!=(const year_month_day& x, const year_month_day& y) noexcept; +// constexpr bool operator< (const year_month_day& x, const year_month_day& y) noexcept; +// constexpr bool operator> (const year_month_day& x, const year_month_day& y) noexcept; +// constexpr bool operator<=(const year_month_day& x, const year_month_day& y) noexcept; +// constexpr bool operator>=(const year_month_day& x, const year_month_day& y) noexcept; + +// constexpr year_month_day operator+(const year_month_day& ymd, const months& dm) noexcept; +// constexpr year_month_day operator+(const months& dm, const year_month_day& ymd) noexcept; +// constexpr year_month_day operator-(const year_month_day& ymd, const months& dm) noexcept; +// constexpr year_month_day operator+(const year_month_day& ymd, const years& dy) noexcept; +// constexpr year_month_day operator+(const years& dy, const year_month_day& ymd) noexcept; +// constexpr year_month_day operator-(const year_month_day& ymd, const years& dy) noexcept; + +// std::ostream& operator<<(std::ostream& os, const year_month_day& ymd); + +#include "date.h" +#include "solar_hijri.h" + +#include +#include +#include +#include + +static_assert( std::is_trivially_destructible{}, ""); +static_assert( std::is_default_constructible{}, ""); +static_assert( std::is_trivially_copy_constructible{}, ""); +static_assert( std::is_trivially_copy_assignable{}, ""); +static_assert( std::is_trivially_move_constructible{}, ""); +static_assert( std::is_trivially_move_assignable{}, ""); + +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(std::is_convertible{}, ""); +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(std::is_convertible{}, ""); +static_assert(std::is_nothrow_constructible{}, ""); +static_assert(std::is_convertible{}, ""); + +void +test_arithmetic() +{ + using namespace solar_hijri; + + for (int y1 = 1380; y1 <= 1400; ++y1) + { + for (unsigned m1 = 1; m1 <= 12; ++m1) + { + year_month_day ymd1{year{y1}, month{m1}, 9_d}; + year_month_day ymd2 = ymd1 + months(24); + assert((ymd2 == year_month_day{year{y1+2}, ymd1.month(), ymd1.day()})); + ymd2 = ymd1 - months(24); + assert((ymd2 == year_month_day{year{y1-2}, ymd1.month(), ymd1.day()})); + for (int m2 = -24; m2 <= 24; ++m2) + { + months m{m2}; + year_month_day ymd3 = ymd1 + m; + months dm = year_month{ymd3.year(), ymd3.month()} - + year_month{ymd2.year(), ymd2.month()}; + assert(dm == m + years{2}); + assert(ymd3 - m == ymd1); + assert(ymd3 + -m == ymd1); + assert(-m + ymd3 == ymd1); + assert((year_month_day{ymd1} += m) == ymd3); + assert((year_month_day{ymd3} -= m) == ymd1); + } + for (int y2 = -2; y2 <= 5; ++y2) + { + years y{y2}; + year_month_day ymd3 = ymd1 + y; + years dy = date::floor(year_month{ymd3.year(), ymd3.month()} - + year_month{ymd2.year(), ymd2.month()}); + assert(dy == y + years{2}); + assert(ymd3 - y == ymd1); + assert(ymd3 + -y == ymd1); + assert(-y + ymd3 == ymd1); + assert((year_month_day{ymd1} += y) == ymd3); + assert((year_month_day{ymd3} -= y) == ymd1); + } + } + } +} + +void +test_day_point_conversion() +{ + using namespace solar_hijri; + year y = year{-30000}; + year end = 30000_y; + sys_days prev_dp = sys_days(year_month_day{y, far, 1_d}) - days{1}; + weekday prev_wd = weekday{prev_dp}; + for (; y <= end; ++y) + { + month m = far; + do + { + day last_day = year_month_day_last{y, month_day_last{m}}.day(); + for (day d = 1_d; d <= last_day; ++d) + { + year_month_day ymd = {y, m, d}; + assert(ymd.ok()); + sys_days dp = sys_days(ymd); + assert(dp == prev_dp + days{1}); + year_month_day ymd2 = dp; + assert(ymd2 == ymd); + weekday wd = dp; + assert(wd.ok()); + assert(wd == prev_wd + days{1}); + prev_wd = wd; + prev_dp = dp; + } + } while (++m != far); + } +} + +int +main() +{ + test_arithmetic(); + test_day_point_conversion(); +} diff --git a/third_party/date/test/testit b/third_party/date/test/testit new file mode 100755 index 0000000..21ec3a2 --- /dev/null +++ b/third_party/date/test/testit @@ -0,0 +1,177 @@ +#!/bin/sh +# The MIT License (MIT) +# +# Copyright (c) 2015, 2016 Howard Hinnant +# +# 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. + +currentpath=`pwd` +origpath=$currentpath +currentdir=`basename $currentpath` +while [ $currentdir != "test" ]; do + if [ $currentdir = "/" ] + then + echo "current directory must be in or under \"test\"." + exit 1 + fi + cd .. + currentpath=`pwd` + currentdir=`basename $currentpath` +done + +cd .. +ROOT=`pwd` +cd $origpath + +if [ -z "$CXX" ] +then + CXX=clang++ +fi + +if [ -z "$CXX_LANG" ] +then + CXX_LANG=c++14 +fi +OPTIONS="-std=${CXX_LANG} $OPTIONS -I$ROOT -Wall $ROOT/src/tz.cpp -lcurl" + +echo $ROOT +HEADER_INCLUDE="-I$ROOT/include -I$ROOT/include/date" + +case $TRIPLE in + *-*-mingw* | *-*-cygwin* | *-*-win*) + TEST_EXE=test.exe + ;; + *) + TEST_EXE=a.out + ;; +esac + +case $(uname -s) in + NetBSD) + THREAD_FLAGS=-lpthread + ;; +esac + +FAIL=0 +PASS=0 +UNIMPLEMENTED=0 +IMPLEMENTED_FAIL=0 +IMPLEMENTED_PASS=0 + +afunc() { + fail=0 + pass=0 + if (ls ${TEST_PREFIX}*fail.cpp > /dev/null 2>&1) + then + for FILE in $(ls ${TEST_PREFIX}*fail.cpp); do + if $CXX $OPTIONS $HEADER_INCLUDE $SOURCE_LIB $FILE $LIBS -o ./$TEST_EXE > /dev/null 2>&1 + then + rm ./$TEST_EXE + echo "$FILE should not compile" + fail=$(($fail+1)) + else + pass=$(($pass+1)) + fi + done + fi + + if (ls ${TEST_PREFIX}*pass.cpp > /dev/null 2>&1) + then + for FILE in $(ls ${TEST_PREFIX}*pass.cpp); do + if [ "$VERBOSE" ] + then + echo "Running test: " $FILE + fi + if $CXX $OPTIONS $HEADER_INCLUDE $SOURCE_LIB $FILE $LIBS $(test $1 = no || echo $THREAD_FLAGS) -o ./$TEST_EXE + then + if ./$TEST_EXE + then + rm ./$TEST_EXE + pass=$(($pass+1)) + else + echo "`pwd`/$FILE failed at run time" + echo "Compile line was:" $CXX $OPTIONS $HEADER_INCLUDE $SOURCE_LIB $FILE $LIBS $(test $1 = no || echo $THREAD_FLAGS) + fail=$(($fail+1)) + rm ./$TEST_EXE + fi + else + echo "`pwd`/$FILE failed to compile" + echo "Compile line was:" $CXX $OPTIONS $HEADER_INCLUDE $SOURCE_LIB $FILE $LIBS $(test $1 = no || echo $THREAD_FLAGS) + fail=$(($fail+1)) + fi + done + fi + + if [ $fail -gt 0 ] + then + echo "failed $fail tests in `pwd`" + IMPLEMENTED_FAIL=$(($IMPLEMENTED_FAIL+1)) + fi + if [ $pass -gt 0 ] + then + echo "passed $pass tests in `pwd`" + if [ $fail -eq 0 ] + then + IMPLEMENTED_PASS=$((IMPLEMENTED_PASS+1)) + fi + fi + if [ $fail -eq 0 -a $pass -eq 0 ] + then + echo "not implemented: `pwd`" + UNIMPLEMENTED=$(($UNIMPLEMENTED+1)) + fi + + FAIL=$(($FAIL+$fail)) + PASS=$(($PASS+$pass)) + + for FILE in * + do + if [ -d "$FILE" ]; + then + cd $FILE + if [ $FILE = thread -o $1 = yes ]; then + afunc yes + else + afunc no + fi + cd .. + fi + done +} + +afunc no + +echo "****************************************************" +echo "Results for `pwd`:" +echo "using `$CXX --version`" +echo "with $OPTIONS $HEADER_INCLUDE $SOURCE_LIB" +echo "----------------------------------------------------" +echo "sections without tests : $UNIMPLEMENTED" +echo "sections with failures : $IMPLEMENTED_FAIL" +echo "sections without failures: $IMPLEMENTED_PASS" +echo " + ----" +echo "total number of sections : $(($UNIMPLEMENTED+$IMPLEMENTED_FAIL+$IMPLEMENTED_PASS))" +echo "----------------------------------------------------" +echo "number of tests failed : $FAIL" +echo "number of tests passed : $PASS" +echo " + ----" +echo "total number of tests : $(($FAIL+$PASS))" +echo "****************************************************" + +exit $FAIL diff --git a/third_party/date/test/tz_test/OffsetZone.h b/third_party/date/test/tz_test/OffsetZone.h new file mode 100644 index 0000000..bacb03c --- /dev/null +++ b/third_party/date/test/tz_test/OffsetZone.h @@ -0,0 +1,73 @@ +#ifndef OFFSET_ZONE_H +#define OFFSET_ZONE_H + +// The MIT License (MIT) +// +// Copyright (c) 2017 Howard Hinnant +// +// 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. + +// Test custom time zone support + +#include "tz.h" + +class OffsetZone +{ + std::chrono::minutes offset_; + +public: + explicit OffsetZone(std::chrono::minutes offset) + : offset_{offset} + {} + + template + auto + to_local(date::sys_time tp) const + { + using namespace date; + using namespace std::chrono; + using LT = local_time>; + return LT{(tp + offset_).time_since_epoch()}; + } + + template + auto + to_sys(date::local_time tp, date::choose = date::choose::earliest) const + { + using namespace date; + using namespace std::chrono; + using ST = sys_time>; + return ST{(tp - offset_).time_since_epoch()}; + } + + template + date::sys_info + get_info(date::sys_time st) const + { + using namespace date; + using namespace std::chrono; + return {sys_seconds::min(), sys_seconds::max(), offset_, + minutes{0}, offset_ >= minutes{0} ? "+" + date::format("%H%M", offset_) + : "-" + date::format("%H%M", -offset_)}; + } + + const OffsetZone* operator->() const {return this;} +}; + +#endif // OFFSET_ZONE_H diff --git a/third_party/date/test/tz_test/OffsetZone.pass.cpp b/third_party/date/test/tz_test/OffsetZone.pass.cpp new file mode 100644 index 0000000..0cef837 --- /dev/null +++ b/third_party/date/test/tz_test/OffsetZone.pass.cpp @@ -0,0 +1,38 @@ +// The MIT License (MIT) +// +// Copyright (c) 2017 Howard Hinnant +// +// 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. + +// Test custom time zone support + +#include "tz.h" +#include "OffsetZone.h" +#include + +int +main() +{ + using namespace date; + using namespace std::chrono; + auto now = system_clock::now(); + auto offset = hours{-4}; + zoned_time zt{OffsetZone{offset}, now}; + assert(zt.get_local_time().time_since_epoch() == now.time_since_epoch() + offset); +} diff --git a/third_party/date/test/tz_test/README.md b/third_party/date/test/tz_test/README.md new file mode 100644 index 0000000..9a3699e --- /dev/null +++ b/third_party/date/test/tz_test/README.md @@ -0,0 +1,22 @@ +# TZ Test + +## How to Test + +* Install tz.cpp by downloading the IANA timezone database at: http://www.iana.org/time-zones You only need the data, not the code. +* Change the string `install` in tz.cpp to point to your downloaded IANA database. +* Compile validate.cpp along with tz.cpp. +* Run the binary and direct the terminal output to a temporary file. +* Unzip the tzdata file that has the version corresponding to the IANA database you downloaded (e.g. tzdata2015f.txt.zip). +* Compare the unzipped txt file with the output of your validate test program. If they are identical, the test passes, else it fails. + +## Miscellaneous + +You can also compare one version of the tzdatabase with another using +these uncompressed text files. The text files contain for each +timezone its initial state, and each {offset, abbreviation} change +contained in the database up through the year 2035. As the database +versions change, minor updates to the set of these transitions are +typically made, typically due to changes in government policies. + +The tests in this section will run much faster with optimizations +cranked up. diff --git a/third_party/date/test/tz_test/tzdata2015e.txt.zip b/third_party/date/test/tz_test/tzdata2015e.txt.zip new file mode 100644 index 0000000000000000000000000000000000000000..144f7d35a23db024a38ffffd6bbf1c113db89212 GIT binary patch literal 124808 zcmbSy2Ut_f)@VZSpn^yj5fl(mKsq8~1woV!p^FGe2)!3Y#3M~XiqdRI?=2972ud$X z3y=W801-p)E$}Ajx%b@r|L^tVQ-1@jmG>T7z;zWD(B3PVrei+NU6$KE+m$zKxw-0gU0S0^|8ZlcoK~q(MX@c`RlPfbDSi9} zjF_phV;$!^F0|KDzAzuMNt)Qp+#`}lQ&CMF$ql$&&#h1)uhEz#MaxYh#*J-5gI_Ro zlc>?K`786L{Capd|NfSQ%;t3F{?w*5F|>W;R;_jt-PiXuwKOX3+Lj+2$rQY$MTIG1x4K=YhPGR7l@XPrB>aB{G>Z~UG zKQ*reL=e|_dq}0kHZek^(7aXX&Md0QSJfgWbY?b2AkHFb&e%R+c6-b16`!NqcF48` ze5d+CNL7H+Yp23phCqTI=EAM0QRh<0s2y9>rpCvCCg)0?qycUjt&rsop#`{*^#U13 zSnm|vAKt}r#L->25VE~B_=KR*Q5d5*__8uH+tSorHP!Yf99DP#NwG!-W_w0KtO)md zN}6jYguIm8Vb`Z?XDTyB9oKioltIvO@hRGt%J;>?CYE&ue#a79yizzlRfbP((ip)h z8yjpRKvjJCHhpSa?@=BZbqFhpE1`)$^R)ZQQzXMY(ZV*eI9AY`E~!%JV`YoU&n2M^ zBi|pDsZpC}Ex))g-Hk(d916tS(pk`Dj91@7`bk#V^b9C$&KR^^_4qud%l+WF*j2g0 z%H(2SmsO7>U0FI3>{!R-T9g`A=5puO(dBXGlkeYJ z!1=bkZP&jOv_gXq1=`4sD;QLl*B!TNP?-((--lX97F&<*5q3w2ktUIuLSq55(_0gJ zE!ikZ3l?8OH~iP?9`j1EGW^_b%$$tG8Y#irb03qP?6!}=eF_Qo8`+U-kyOk3fZdnt zc;wbQvSRHSq|cIHd4GI+cWPpSx%l zq)>-~eVXFceAlZ!H~n9S?z-=FA6^{Zab(UIFXDW#JO~Y&TRogsa0TrXQtD6R!&_ou z^?(NFf(DPVThB-ARWvm{yA%D9Lw?6>>91oeY7TY&@Us7U(H#~ZI;s} zhA6=8S<<|6H6P-l=H|r&4x6n2#hB7*G;a?dSB4^>GxQtFS*p7|;r|{GMi6OZh_wIe zRbA~B&-GiDG_E{K-Dr98kSl{*K7*U{|K9(o(-1snI^lnt;14AJ=~ud=n0lgK`&t?L zS@ru-`ZV>P*q;QkZd4a1Q_iE{Si>VFJujRg8R|V{ajQz9M6=Zwf{s0@9&$8kCkE81 zdKT0=>TlYA5PDukQh88Uk;1cpRLJ5{qt2FZdWt@pe?sbBo>GywDVNhZgRkzcaWTn9 z?Fphi%q(eYGABwfIVb!DpO)}rVtI`|)N(d@bLlZREwe;Kuku$HDWt24D2rD_Gm&1y}iOcCVOf+GA)UP>D3t(QusxP7M8S|m+ zP<3~txq8wb8qB^?H4CEUuW~7VXmF7yY_u#~6R&*Qy{?5rt>LV&UjXtPqTN{&5nw~h z#8!?w=I1X5T|ArIbJ2)Jr$&e-&eM{cI@_F&YJG((jzx|8w9hd$JEP80{v3i~=T9EL z5OIFRP7W~i;a%QSbZ*WskGG>dN}Z}2*FJ}gJi3S&G3G$PmfIN8w2U~^f}8Zuh8W-U zP9IvC-Bq`FzBIe*T&7NI-=jnOe$oGdK_PW-X?i}6#goIuV~Zbx9saiXOv=}Zl*Fz< z1p|?;-~)lf}Z)Se{Isfx7+=Tu96*hnup`jheV|lvr8q)zE{!0 zn1w?n@BBZ|UfH|-=)?sLH_esni#k_ny(Ax>YlvV}8dsoV+w#{z+cGvBMs)UAP{rz~ zu!Pwsk2ga2vs4a+>4q>LDKV3kpn1U69F@c;Q@eXq%%=K769dvD=fpaU%UwUmu8mvH z$S-CoXzUVnF$XcDG%dvmp^uTcG-gVT=+8M}_0zbPK~LP~ex3hPSp=0$xMhG<-Gc(? z5csB|-b&nII+kZ=#bWg04*HwliXFTTidwDn8#bi|KaEC7!*kAt=Ohdd$u~1I5w6Vk zuGszT6>kbNvXwr6eEwm~C9YZhOc?r}SG$R(P{ z)y&5wZAsMw;g`>2U^2QKBXPpy3L}9E@mCd9$!(+;<1?xfqnvj%SD-`UhPNNRgWx2i zO#o0k4FrNg7sCmzykqC{j&bEN@Dgaj*Vve)qhG-$t$7vM*s zQ;?itfe{kg`W19ZZ+b*Q%`rtpwSM_io=i9JGo- zEeK|e&BiisHj&37v)>1g2Pl$TWEz5fkb$+bIi5;;Idb3i_Fi96l|d?0qlt!uUsV~5 zbrFFUg(K3)fxJrdO5=PVTAcHMd7*i}5sD37>0D@BIFL8@(1J3s^T}mkZ*6IPy{l>8 ze<%BLkjLiy#L~px9DC!=>Z0GK!1Np$+jJ{(X9tTJS6AOdZnSi++K##Io2Im@Jdkc< zw(He>PUvv7&airANv~WR71hT94^(NIDR?L=qZhAE*2aqVaEYW2e?m;07a`6{%Ex5Ow+!0BiY zW%Kx8rWPJZ>vz2C2anombcTGCV~I)FwcaxspDAV)_y#EtmB*s2%qt$5(`quUyUtX` zepV&mM+SC=Z2c?xepb96X<{fF!ME$lEX^6o?Jb@1m(Vc3bQnwX{>H5p#9# z$A1>%f;aqjc39f?SDNzEHJ16V8t?7OljGd>tJQ)xR)3+INSR~x_`TiL?Zp+W1`Pkz zU1Mu>euk=HI40126Wf<68F_5?Uc>a-9HD!HTZ%J_;mW5JwpUno!z$Ibg~_HkikY`x zk>9Q{VuFo|+-Zqy7`JrVn;+eh(|9}}7izWGl~pM-xkZpJn2Xc6|CM|qRA%Z~zQ5+0 zlll>vb}rps&p_nG74_6tXPK0 zj1H`=uG{w5nw{UI_Q`V&ZSoy*WWN=e*|0w|(Un?VpT4z`-L#auw75!Wn!lmfFbr&# ziKVV4`b_m*^4tPdy_#Ck&cH&c!0xa40pD914gNcd3;8Xm2KCv{kPmtNdyVOmLZ+l8!{mMnp3M_}))Uo{h1`{h& zfptr94wr*2<8Irc`j^Mk>B^<8F8}g8?`h^}Qu7o?tW~C3U%qnPb`jye)OMvce0OGV zUVA8Op<9R`oNoM@jqY4&r(|Qx%>|qrw@lhhm2X4G=47p~Ly#c%>vrCY@xMl8ZF42E>yGN_-Z(|}PHtgx{k$I$o+24Ix<9Dd2`FCLEReEJ zO|6=h(ARsdw@aI5yzxe)bi6i-n@%qukh$<$Du{d~L{eJtSJ@83ob-b?K7vuBS?@#E zDS!YBRoCdRPAk(G-wlo3Rm9Fp;=&|im!bCP5x!XK#XXOkXM#^Rh@2~R_+aQu7Rb1x zIdeLF#A?pPjE_kCd7fFyJ?wN3%EitSU0&kCKFXqJ@x9%}4%&nLP}J*{{@K2WK!^9r zxRw>69NttWc?w^`&-n?`5-_}V1=eh~)Okic$Bm>@yV5g9{8X<8tM&ePUpQe4? zbxW1P26f@nP}bEp@Aa?z3UO%GQP2D4mwO|zrox>mSwY?8ipo3syhaun z*S&9GXNV@AZ|1AfNxePMD|Q-e5P46*(jFmkN94F%#vEs}4mqGRtME3mq7ue6C}H>_ zU@=9az#!+u8vYz%*vh`{A*w=vQ#!r*g4Ta))M`0$H9`j!o8RcoWTez&G!cD?tJ{O1 z40ai?J*OKWD@ZjGusEZoTRm2z-I;t4?zU4`(+M&lym8Jj)F! z*~OIiTVWERCsrO+_;_w*wneUa^)$#X7w&2nT|1M!Ka5fSc2v*tgSGjNKVy3h{QP>* z25->VcV172xs?h9>46lJ;*G6q9V46@$N<(J&rg98-)V8@6!VY3i@u5CaCh{OTl{v7 zl{#OZAw~}$7ll>R6fh|2%GhlvZX_I;KYQ&3{|`1Mb-#$wx<>dGgI%LQa+Pf(E0a1+ zgy6eN>@P^dUbr}eD{AEyX93hyTOrug2tJw$V2C9NBbft!R^c2owdd+yar>Ga4V5rk z2@!cJ4VU@R7nf8S^+Gp2wMSeGC#g&ficrI0 z>*A03%KI=i;^BQfjWGfkE%}bIL5EHJO@^dS9b)jE3^}7rL(%zigy4yRCW&zUsiJP<<1j6P#8Elm2Rk!*}eKo;gKN z+t-J0tUdpDSyugKIe)1jxVKie)st?mak|Tji-PT*hu#W4y2O6_ZDi}(^Ls3^sNq|?J#y(`0e}f?ZK5pjonjyQW zI`9H+v4b6C!~Bk}2AM>h@{Jc!vg+UM zRbkIXEibml%N)OZ;}}QTT^4|*d#rZ9V&eSKRbFQ85rB8Q*sA$H=FRu3{r5#ADsIQq zhr!C|A3xw6vs?y%YveQ!%_Scu*O&Z{l&#N9Hl%&zSbh}cl1X+-&@z44G;Fl%lyLbc z#H@_r@fjzYOG#=}!a64&J{L^@(`p~T+a}6UcJc^=SsCNwGcz<7rMEz1q`j0BO(o11 zp`fkz@Ofe5Bhh?7YTOKC>G4TT0L+iyEiQe7G1V_)eyk=@hnnPOP`+Pr=={i2 zQ$7;ER$`r=EJxYru}^w(9A#feOi%GL4BNUE7_dIZ*)ta(fZfJ8Xzge7*PXbr;{R!s2eLv+Ra{tUR`J>TH3(_-;;I4qi$aF~o+-6Q% zVT%Y_o%l!3(;HDbuOB@R1h?tkJ8dfmiIAY$z#7G@{nL@D-Q!+FxzD`}TsuZqi@N5h zEraaPnXb{eTMaEj0c!mF-J@gCXpx0xm`Vm_)jwmT44>*hH+@SzlPLf3NP*amjVa^I zwP>|{ySV^H>Vx(AzF*-Hq{0%S`| zB~wX9pDM{lqbEJ}Nk6n?feY^>_A{u62g)w=pvMnIH(lKr_?3(3D@hf{w3q{>XJhlv z)I~L0%+PERZZ+y#YlOh@Od;U|`*mOd2>vpEuXHnURapy=lBl2&suA$98WP4n#ggsr|gaudld zb5wn7{^sE{({R=C(-A558UC6h2|S@?>rL|aYdfe5lWCJT+?*CfRR7xB-FVqGU$*fg z{mU=Cxre$TDjX$U^>k>3hG>Q%aS&&m=fYc23v%K$sn;oS#%r`7ssbz}d3+A!8ZB}` z$b0PwQXhod|9-wo4Sl`EA%Y{P)y0qR^Wh7H+J99O|>gb-k4c7Zi zLB{Jl@OnGQ)g7{NB2 zQqjB8ZQ_IMcvRKos*3xsZo@V*@LpVTwFS;^_o8&iWC>cH=oj0FLPff1D8u1yp+Q6Gv_81j?bHcp z+Qzy!b6!}z>i_IEMp<^M%xv}%FK{yKGUG5w=d+4rCXdqks)dpHsyR6JKfCeB(YdwL za2KJSblb#$2n71kr9P=|L(XD*r!!7_w$R$TCV1fH8sz6 zitWk>LB@CxA^x<#-gC>>F z$Wz<#RvM$Bp&KQ9?|l@td~?%_IzpYyDBfO=Re?gyXxm76{`RiSO4Da6e?2&6{qFlu z1p=)r8!HVTPH_gI#z2^zN7D2ocL%b3} zv{Yla;f|&fVji*@uF7~w9K9)ZuAai1z3_dS!&*T zCaG0;mj2Din((g!7f2VAEM+xHg$MTu0+)O z9rKVL_4l7#s>`CaVWTWhOwz{uXN^B>($MrQF;aV}6{n-WXvRi4_Q)lkZKS%o^cPEp zZz`SA_3h;wnT0gb&Ynk0KCmzxGnzhwPtmY|`uT+TN#4vxILS4v+?+D-f}ZLTahoCh znDqZ?d@TQ9_>2b!VKICU=@-iqPfxB(y6`g&h%ax|>pC?)W0y^gY7KrADH_D5p`Sh^fOjwdJe2 zV#XZsT97(e&57PYNyCYQpb`izF)$I97U~E;{@eF>VHc{;CH}c9npn{22Ow-jIYK9! zM$sUGFzzp^vNJtTjLh7Sd`j+G5<=yE!bd zWJpcGX77_;@)K$)^NCb-fD`ByLK3-Q6YHMQfg}1>pPm#GE1OPYr2^jQaySQ8DI z>n@5WtHa5se80Z5cCMY1AwSqCf|&*enB2Spo3#w@aWAjK{}>_W&;GbAaNygBqWrwl z@-femggXDs!ND4P?FQDTstcppm0>PP?I#-3tLOX3w79KvKC6ct(;Hs7USVhU4S6OY zl=WEE(M{DSbZ3h3BC_f5mhiva2G_yurHC8I@*Ygk&zh5tCI2?Y@5pt=88|-~mU6h4 zB9z_9vO;*7VjFP%FP@K)FO$K6|En0mTB(iUY@P?5bx2g%W}guo(U8LuXZ0mpD3QPW z?p*_7w|JU?=B!8L>}nXP+z&!=d*A_wfX?^8LHoGU7uMm{Fuvp;#~WjYXGpNNF-TDw z@h0-#U#o|UCIX%Ui+u{7GWyQqN8MvmSsyjLXRYKVpNRUGha_Q9_?th@ggfK6BlE3f zCAx?|%3oi5?xD~LS9a8zO}eAd8RyylWOGTvUJIG@%Qmq@7;`3vlVqxvq z(*G$evC2^+cqin^aF-7bF0S6RJH$KRBCguBY9ocw((XR1ZrTFWm;0xmBQ8h123)ga z2OkC|6m7)li4A+c8lmh0mcDS{7u~t@Wacvum^#7M$Ko~Hi_tsUPqvnNJ)iC>IowSV zOiI#vLw|!^O=GuWJkeQ3Z#VX1&+st|u@KZ;rhmONL;B5n?ZfHb$JJz5-v(E95NhNf zXPmd6eI!7?@uK4A8NBeoMA~$R4_Yf5$`|sLVtM`$WH+Wx`iNCg^8V?aSWhBi+0-E! zM2Xb{Ts7FWD zdN~wQ#YE7(ZAfjYa^-ecD>@fauZ6dI`^*sHHdJ^_K5vo9=sHvltXlc2jM88VW3|V3 zP7hoZXc_in3Ce9-kyWBKFtE7HdWLo}v8ta%FN2#ysZwN}nTL$wu4B zwsoG(zSv zj^qky3uz>*Y)fFWN>`4$XA#*E4lDG((r4qP=x`w+mAZ#v?oB>(#5?5pdAA%7QJ$9# zeuEgvOaAV!Sx(^6{@0f0Vbb@XV|caMfD7O4V}@RuQF7l;s z3GF*n2-hk;eC=#Y7^zH%8lJfZK?V;}x+G`C5`rMUogpkp&9{+n zzG(sP+e3XQ7E5`g2k&ao!J5cJ=0%bHdEluAL5yGhwgDyT)v0q_K72?a?8BYXHA)=LL$1x_YcsKa zFF$&d?%5o{o_NP#c^AaJoR*GF0@X+2rJo zI=r^hU@NRYVcnqGe=YkF;)rL6>uJv;8)#W>t}s{a^K3K^9OfCI*^eW&Y+k8eLd(Jr zhq>x~=P2peIuFrP9}=PN$-UYqj3_=g_U3Fxr+~0crof@FPgl9#U*dXyl}q#OGm!K& zJSHOn8}Y_vCC|{`vC?DxJAe6lR@(sPfla@~IWEJy#!xVzD6dZXW`iDptvV^-fA+Ued;AjRVgU?3f{-1#^Lprn7t1-<{XuxXo8} z=~7y%dyd<6N-@3VZ(I|cpA{nzAg;k~6!P-mK?ThSB?k~J>C0_WNHnjhG= zuaNqrPBnHh*Vk06`-fah@w(XIJU4v2fPFu>KFUY>st32Vr9;!=!kvq0vX}BzJrC7w zm--g_if9mY$H!N(FK=8wVi22p44bG?Zg4hP^wrzynJC0}?1%1O252r6 z6fUT96=_$kV$vKBEs7Qu!Ko!hBeG1X5K`5tf1j?H$~Ni>DZjbzb{-%pX9Ao7i%cm0 zh|y(m(q-Sqpm=(fgEQbM2ptyD^XSkaWdR}UhCL4uoJoH#jzgs{G-t9d$!COTC3LulP zg%8}J7kwdMiZ|XTbd~QEO@IR|}S&jBv5D{c#qaZ96zvd~Aemm*_o-BD;U% z_&5U?e#c2M;WvRC3Lgk^+~gI3b*vpvXlB5;AE-B1GfKGtHe8$o009w#b(h%RAAG=- zzA3Q)A=iXvh>2JXw1~pn^qbe?;3j$hW&)8~S*L<_DW~{s>`o+R`~oVl?$e;nk8aXk zt(T*uGMjA|a?H{x7mb@;r$^J~UaiC*guoqo?odN@UWLAJ8NYrna9~+qb#T$l$sf{o z8+2xv-sP~*deryCS7eeZK}{8?A~_3)OACy`%-VOO915vA?@U{tapC&UsK*Z4neiv! zz^#1rsQNqb@pEW_c6RF6Clw{5&uGafMrQ%vR^cL3@_INOh&2fc$n6w(4Xt9Qlhn_u z%r2YFl+2K_gsfjaM$AD_EV0UsH0a)WcW9kiD%+j1L^{;eiH~2kDnoz1>g>v|zN0Sb zxza1%2Z^4Z{&VPkHZ?W*vlGaF9P8@puo;$sEb_mTPxQCvNvmQ?jLml3InpbwV-U;G zPzQn_k34~k&)1mt` zOQhlk>79YqXLIeDfywy}Pts`X5i}FOBq!c4UmRcUtoGXUhU-LDd-?t8tcmscGmBB= zD}_uk=A}~OdIy%J$i4E=5Yo(>DB%II_cIwswkkke~T9WXXy7hv3|6FD>Bj~ zG;ni0p@p#TTK)aoD3V!@QIBq|hWv`A@YNnC?)3~UXw1m-eGLs=t5XHiR7vHv5L1s> z2(0@T)!cr(=SdsoeC9Aw;&pVq7nM!^Su4sZg>Zhw%n~Hp4Q~TN8{-aryJAx=4`Xg< z2N(twbk8F7mGh$jWzojH3s2GpXwej;#jjpcc`d^buw+W|gp2n%O)7t~#{bA$9C%5U z-SDC3=3 zQu%9ArN(*Brdasz*J;|;0T&REdd|ofy~?vQ%&`MmZAu=iISLdy04I;alAM4@kw|jy zy3VD;$7B#uzPpx574Y9P%$as=i_He?ll$g5hCpn=tu}-YA=T2dy&Nf>WdFgVNxsIZ za^3D#ORbut+J5OW^@XvQL`cy;8a!p^Y?Wt*qKgLZ<#P1Ej)k_rv#28JP6qFW;_0cH zI~j5h4A=r;$_iYFEH(Q7Xo1ev-u`TO?LY1JO5*WA0^eSm8^*`!!_0(gqa5W5702lo zdg`hw7`1zjMc5n6jRhP_^gLK_o0Y%qz0%8i`}OH0+VR$rwJU9JRh`6k z%Z?X%XLGM*3MF$I{b;Y-DHmw2Q1C7Ga$jjgp)JWnil7v)Wuf?HdwQ*6(W;gVb8n_I z`5PC46bUDPBjN|yN4MYhd@dBKUDI;IRE6A!?r-e8?U`L#E7#TXVs8zdee(0h7o+68 zfKPs>o*`))()CCK&Fjh7ogK-_X9{CO0}XZk60dg;!;ZpsYch9T)-*lKe1dNmvzavd z`ykzY_B-s%N`e}r6`NmHhMEVPeW+Y{G}@Ey9jPg$RyBV%Ct`F^fG$k(e>QLU%-I}I zok%EN`%eSLWv?v+WO&|s9fQDo=8RQXASRUdj1T%dkM*C<5~0^tpP0lJu2K!?foFLd zOyW{AN)e|r-;&h?K?G7H>JyTD3AbAI_gf+*i6*{^^SfU@20eR`Td7g3caEwi#pBs+ z^%jxrV~5}$N;^0eSIUJ+uqgZPnKv%guAyUuA1R*gs_TmvZn_ZE>}U{E^89FT`BRB{ zHS;sUKZzvTbIV?>-VLtQREiVEwgEoTgORZ=>gVs5IgW>soIOIt%CR;zqjW9fX5oZ|g15wg zW5DON#RnWiSa!J=0`H(t^%Ww#f?r-9?|9P0u$Ok`2><#Bh^7Vr}I=3B_LSJJ#^-mR)H)Uji19MPj0da!2nRJ~RTddqM6rM8W_1BE{{PrXE|OjlOWUGorlV z%C_8;#3%)Dor~~jl*UW^CeUq?9wN`x2m-1w)zhnQo{GOb;sZ4~WN`Y_EEODh;NY%s z1w4hZYl0z>hyx4&7!UQAFB-#uH{E{S_F$HOgWvAT-4AE+u}tc%U>rD9Z2-jJ;ySL| zeslZoe!%PUo3|1NcL1c|!J+`L`BT8ZGRwW?G)Q0^Q9$V8g_Ag6yBwkF3m-OW*u}Y6 zOD=pclt*trhpB&*48AU2)3g2jPANS}OZ%%}!EgM@@;OXhZ{(zYk-xfF%9`+PRN}eM z6kH&MclPu4^BlqU6q~`w%WL}0G}M3GwJSkklA!&==Ft-Wk?*NwHG_?zuB$REdV(Nq5ks31vI#B ziX?#z!ksVlNOg+9e0R*1APsea*!|hWC4n2{h}s?5GP||x=DExO;VJEqq>N&ivGXZi z2cG(NZ>QCVS6~S)`%n|}(*4%V{DmP#CGHwhj}amuGN_2ED7x!n_6Yj@{7A0C!b+~f z=1UQtR4B#X1XkFGkUGKC+r*?&o>@b_yhvGv@N{P_a0l*{7`Wz)whyuR9QyTHa&{WHq%}gRFLp{9|DEXn4BXf%f=@Xx2hW34e+Q&b>vd)8>T`3t6v5t{ zD<32KWzn1tI3uDp(R1@9~Ui;30&_+;wDy*t(*(YOV=GP;0*%Z6SkNH-WTk86~ z<__|7noHhKs;cU1-)c0DDmJXlJ`(n8oW9RoBlZ4i7jTZPd5!93UEz#!IB68Y*XO1+ zE_eH?H*`MDDlH9ya8(G3v0&Nv+u81FnuirHecT}0Z)-jGyq!#o8qaTuyEH6VaG|Ub z#6p%!XTFP9PtmK53amG@;B-U99Z?rB-d2dM;J$8eb=qoAOIlpFw-nx|$VC;i#t)8N ziM1Kw*qWj_7{+sP#}|x;R0=c%&?(Gq4*2Z;Qbr0ijKo^2(^nHruuJ(wyw9$)YRDS@ zuC;Q=nv)6>+*iyyl<-l+w1?__K4Em4b|z1ur9^$F;BuaG3rgL>y8l|_4%jX;K|R~% z4!m_3m$EmBubFD!<&?|R#wO8{0`>3Q$(%$6Yo98*ROL7vU##)s@kJQgQPG!KkC07h z8?h|uY@)?0doBzXhlZ`MWzwj4j4{F$>GCW3A+}f7qY$jT;CB!AJTZ_ttxPS z;=-(!Dk}56rT;23J;BCgv>6Y#7~JdF%>-_Rzx(pXO^xD>zWAl)XzsB?24^KZWk?R6 z6<0>O#r<%W&!jy6K@7#!=7@kk@#^d2heFQf*(>NVu2MmPo0ZmNR*y|6Busx%641+?1F055bli9#ElmG9|rMgR}w zh8-|Z0O!-|G1#;30#>lJ$|l8vJsWtc*N}h5S}o>RPT{~Wd3EauWtj(o)?7j3;60=H z+8!YU`1P-W2`dfRNf$!V-oL?I?&x6fUYM%BhSkOvSSu+(v**93rv`3xEP|rKG?-VC zkEDW`1iH9@>3@%a>%@4V693jOI*S?K_nAA&zTEkBhK$N%}8Pxbkr}#0u2?u?uo^5)gp(-s2+wL_5?y47lHibYz4Hy3{g}*9!m)>P=Hk2DvhRN!(dW+>Nx<4%h!u3T26&2q0htEDFEowH&QatwAMWo2Vd9^ z33QO}=a8A>A*L5AkJPRE_GWx{4JCDdz?L}{c&~rtti|pPsu%ry->v&1vP;e-(q-v# zPygV2)d;Z7`h28*BCO&*)wYk0t7aCD&Zd(vh;vg7E7ig>v8Og9#-uBL865 zm{1fO!uAzqYexT5YI(Pm(Ty+{@EGKsM1vBjED1&g2&Lv~Q{ghOg@&Tgd2}X;GWZE( z8s5??12wKi2u^~jD7FbjV2x06lPn2$Cy@r}VJe2_EsCT7b9glcfL{6nk zz-_t$Oc;sWZmCFz!5WHgz$~Pw+A(JgW(L6~X)qV%3C;V!>zim1u(FBRm~Jnz3AFDN ztKn3Ab*$u!srAbO%WeUlkC*>a{*)8t=vizHdV6D1*OK3V$w=qOK^=iE^Ec(U=<1vsU0nDB=Ge2Z6pn zno({Gc+4mW`l3h*{lUVh`{xq>QD6C%rkRAJ5HyjIfSF>D1BogJOq7QnjQQdZuIztZ z7XPURc-Sd|z!LzbA^pCKzz_#o5|YrHP5G!D$(EmMeGjpY^m$(^bWFPw7CRm~V;pBf zcAN4eck-`QEBnd~l^@&1wIt_;w{35u$(vI?qe2ehhP`BG^aJ4#+>6|Be^ zc#UhNM?QP!>*6UQgqL_WR!HbNzHmwFnY?HCxbf?neIbR|x-JKb^VyLq^I>r=TsBR`n@D4*F^=%r z8C}kPc2Qpc+|&ce5O{MF*GU-S3RLbt^bmvxt=zvZj|l&r;nTE2L(;mdacPH9^y|u( zE}>^`E(<=q#_D&0r-qMF>FbY=27yqe^{xIfUZvol+scqoC~UAjcl}-nBL+G3d4CxT zie&afHYaR-ISB~4&D6cwVU4-R<$2SzB*pjwDKXx43C+p*pp^Hx4hHN1`xxQLtH7E^ zjva~A*IjTPp7Yk@V?rTAg-OTa8n!Q0eyK=y+-V`0`-d0(Qg8He-?vxdjx|rw1+qd^k>-!GwQ&VjNky#rTLC!V$I&NF z#Wij&DOHnOZ5&o@E7bF?#nqErP(|Vvqsj6vSZhOcG8(#FTPmvv=C_b@$iY6fP}L$X zY@q;V1bELAU|7*V1Pur>rnko56U<8~$*oDBSqkspICA1{rtFiB1@6#8@Q1qD?a%>SB6x%~xw5m)s zpM!Li%|489&=bW^Yq>C*uoV`1PJJ^+OGOS+6}6FXhXsnCs&1idXkf4_a`12wzd19- z&uc4(&Lgg{m#y2kx!-PhUdM$`8pCq=y7}a(^*DdpBQ*{D!g(OgQw0X@U8@|v?dsG2 z1bgqAs~x?okKx~geDgw~KK-1kN_BN)?`rR8{D&Ep8qEiQbbX zc{Y{U%*EX(!|KztvsGutsC5#;sBKz4XWf8=fy4YqItdU;mOAT3SQys^Ql62cM4qw# z4;liYU_ql=vAF%324Xs59#?1Z7TAU_*}L^`oyM}CHAxQm9y?Fe^1Us&%(9}j2*u1IC!H>vGwkKstl0| zI#_8Pt%kq<=H5D%7-_ve_GtdzQ|=K_a6#Nhx|j!L9L;uaQvGx)d8^TIW{b5)0lJz` z7ETRYHJT5(xE(YncHFYz$>Gxl`&FRx>_FG3RI{W}!+4bFk+KLjgae)*zm99BfOfPp zI`N@rm}JDyFiC16#DwWP^dI@0NLfTtw-ms+AR7`dc^#M&90HW>M*K1;(Z&{XzN4N; zlaT=YS>=I@4fE>BB#JO#l8aFQ*l?(czi@Y+vK>qhHd%@$V4jlWe<-PP{9N*Oui$h`wS$#@{UR)RC>}miosy*!*sYQ5T&|fSLdf%I*gk*ubg} z=nsl9Qvaa-X?NTZ1Dh8hc(UV8VV(*&4J3O1W>P;82=2^~RjP0K6xfD~boYimfSvWP zA1}DLlL;i;Z*_PmmdAk|Qi-*%SFBOAJxs5B-qVHYve{BEo_W!AW%iM)v=1%b zOe8gGh!zDSv!KhbE4cW64(>h-DVa29^lM$Kfv9ODDRP%GuQM4%^BP5im%U<^zzZZR z3I6ZjSRy(rN#2NA&b+4rCRgOaYamTVhYB10zIza^WFuyNB6V6o8O4yN(HD?uRyqx; zu9_1V_#kmi$(Q)XAP;@`ZvI1q=d8SL0uI!aw-g2LfvkX0X>2*Pq$$so zeguMSX|}jF0`Wsje`2eI{;%&Rl4{t!5lq#ZMk%rRC%$6eNKDUUf(kA?U5w)yMXP5> z&18jGlowMCAjkj&xHl4=Z}cND$9g2A6+!wt8kc1-6q83u1f0)%3gZ%A1dOWiI!^y^ zX;)U?8P0(4ypklqIQB-OfRK0nv*LX_cFcCl67D7}3 z;l!2Ty$?_vsQeIG{&)<2+^B#j24Rdo(8VP4UG z^Ef*3)x|fiSME_gtm0yfhZMDqKw*EqsPHKo>>e1YF;~Sr!H(4I@y)?J`KMKUM=@{- zm=n?5z2}Es&xMgy&tVnQ?HV+#j)n>O5$Mt_wre0Je;UT4DKSJE{db#_VX%vnB*Q?& zQ~f0v2W}b2jDN^vMq~}qP^@;~y@T}jhXB(JPq27tANjp_i5)Cn-eL!fmxI{B;+20B zLNS=7Wubo-uYb(?_v`@v!u9qT5tIJt;7W!SX1a9!53qlh42x^oU&9t>2!@WyoP5Q0 z)Qrph!=?Bclsb2OC-cV!@7;1j%sGd-%sV?KudS1Ioy|)M)ISx)DLzy`OJhwHSZSL> zLR$gcBq{1SUE=LbQY)d3cB##yAT-a5w&q{hgKqINa^G^c1xIknWFwFiH1M zD%D@se&G&ds9}GRpp+bnyE?_Y6)mDi#_qU-F^a1PNdM(b-hix~dTGr4L zVgi*|6)^Z@dx-)-QJw%03hJ0*fsBKqJU=ji^ZD5$R)k?AJ4Np8(nap|*Jr~Q*fnMa zD-pZNaXBF?=eQEwlaB9JKz83|H?ddC2xaV51)i96+pZqN)vMIu$Y$4~Kdok8lD-4V zJXd;9^d&Ln3O-|R?ULC&g}dcTcI7XWHl^45K4G7A$Q(l?AL30y^xdQmH0$7l^E#FM zB?6nACa!nO?LAJ-#HRWUT$vwv*}%WI(Kp&b_PnfHS327KGQWrHpjlh6g^Vj(-%stj z5COmI+CYjG%76{ZMDAGn*Q9>V*eLt*HIXRaS$90*>h{FsLeTPV0xU=AjB=g-*Qu|e zZC@=2@yQm2qq|`h3hi;0=Xug<`YMb=X0s!cefLR=p&R6NzrNX5a*3L&9gi#}%E?>rkpc{jAsOMdiRXITgQz5G|qZy&w^0ZETb+fLX%JCvYWvU`0MEZ{a zVx$p91g_y3_$6I(j}6z|=P7TqMpELi`5(u>b1$j(N*+wvwYFQ=GD+u! zX$0062hZ(@SH}dt$_FoMpdZRj(X4J;y-y2cLwZoD;M*C2eRJv!bs+9$ih-L3Qb|@!u!FY>K|3j^>OC*^2Q6yzm(hv+#W(0SOpu%m9(6%5u`$7A&(%4y!8U3t~I&vP7!z>bIok1 z#e7=$c>mp5_fJ3e0zyK`=!Ify-FskTc|n|7NRh%20|e2!=bm(oR{}~;hwZg|Mv@Uc zkB|AOq_QMBG0iC5!o%1b-ev|Znk;~rco>IK#?$RtX7`fPxbP~plp(Ank{b8~faZ6p z-~lHW{$uSqAE8G-_CBf~E62{deLRJGzHZYxey6+r4bkkmiY_{x+;tp9Ya!NUQj^p` zG&n*Zxc4z_;A2uy9F`d1f~FJ?dVCVXckfl@3XBncuTwLrk(LW!Wme&foH+wR$Gb5z zXMmlmoUfudRgfa6-OYs19c{w8)R7(%(K zgR(}CWpTV!yV;!k6y5;+>1BCst0l3(8JC_mAc)b|7;6Ir_6zTz_5p_%Cj5 z&x?VuHYjvHi~pOTiN{6YU;z;VNI~i8uytfSH5E=r`HgzfWEf=Q4%_`WP&;Ye37vBX zaiC<6i>kPI>O4;w3gwfXrLRB&2$;YqcmYfk-nUEW{uce=kf*spb<_VL>^;DmYMMXL zgx(PqkgA}dbW!Qej)EY9N(U9O0ihSEu~0+-k*YKm0hK18B%wx;-V~4;Aas!~0@ClC zfbZ-3-T!m%^JFt;cW3A9IVU;0GxOV7o#M}NODSqu)d#^xKY!RNs;i4XFvB^mM4{@j*au0T z5$4@l@{pk$crG$vHjqCPWT)C6&{eS;BW$%^J`)7iZe$g&j<6M0B3u@Xxc@9WesR14 zhFu1Wi#4L8;;y~gFjy0F{cPfF-_|er6Q;s$COZur#hQ7<3sdyAC!sQzKuz{F};A#Ht`%cVG1shiFfKIy09aM9;I6z={~y_wA1 zG`l=q$<{RRD&)Yaun9N0Q|lHn%30J6SPArXVifiuS&ImoH<<;$)q&28QL&ARK?Oac zmPHf)agOagd*<;EQLpp2etSr|__9;$yy=5m66fqh-Wn1zkI%86d%3hY5!Y2o376s_ zGR$FLkW;SOfVWo|4i8u{_Z9uH0-Oa!K(#F67&go zcR(~Nu1sHj( zXy0#r(W_)OpPz~=4qN>wW&1mjov$Qw?GkBZJ&=j7q)o(V%HhV9urALS`4?Jkcg;acb^*<#OxdS7kvH zI-IqGjFTxsHoq3c;dp%u4{5!qaD8olZEe1WU~#OC7vZh2;~_Fqy%VqR$ zJ0qKWRSq}b(lo)Q(%$&@OWN5KDezrD)%OZo^q7nBjV|+Xuf2GAFyglQyYJJ)o_)eQ zq<%ENRG0cOyLQ4y-g2PSc>7S;4z(Kzd!;L#tyaX$3hr8$1Kfpm>9*di>yVn#X*FM0lyVZWA*?=m3172HWbEUB{r)! zl}(o}Z8b|-PNv4aUgoU}_5h_E@S9wq7F^Ge9kSG2#WrhtIYk1bBBph1w4C%X zW{KR;nrIpMz)Hi}cuK2LW3A$H0o_COyOl@2+6>&Dw)+*_Y;{u5n@@A?t9rxE^y%}@ zh#H+KpPx7+3%_o=n`1A#!&Hz8A{Tb5xuloo3|F-0X=1$#rJ0*Vc>J2PI|DW1ccPmU zC3UDRxiVxdTh*7Zn5Y!*9?!ify)OA~ef;5Ki6W!2S(UWy$2@_0B5~G~>aJan+?IC+ z*aSL~1hJS70!H1V8|S=~jot_kfJ7ZUhYn?O=yjZa@AjEYu<`vVifZ++m~wLBfJPaQ zO*Kl>`!Y|>_VRd`*o^+QKHgw5@-F8>yBDiR-8n6kpj-vBQV|PrHuOek0z^uiu|_50 zj&~24<`~E2S2bUBEB~OvEi0ufV_`~rw)$}4hi*Z|SM;q|qAVXT*2?qJ++K2C*SxE6 zj5k^Co_E4mvAYJct|#M|^LvVKbV#*KovdMeMw~p^DfNgU{(K+Cc;HA#w&l#Nh1-5!9-VKF$W|t#7t1;puAb4w4EM)hE*c%lu7RbPtreq{0qnL5 zQ4_5;3T=_k%CFw4O}Qq!n3FWsmLH$p-IAZdbbDU8@8{K^v9{@Rw_R*`Yv*|(%RrQh z5JI&{TB_Zbxc-_7qkb&PVTk1d(RJsz0u6>Bt#JjVpee&(_>vnNm&|?tpWo)tciKL! zUsRh0B^%b4rkFv`$KT7J@#T|B<4?*+XLdUQICE<;stxf711Fg1A6R7I9cx#$hXqUT z--2Ktqwgo{VkIg(=F^%#<;`(UJ#il55gutec)a1m^`LQ?eK%s_(;K%a#Uu$iWoaB6 zG{Xi|5vW+hof&zBv{`wDYE!p`J9F|1L&%R;Y^>oB@4 zFRr+2VfE20JfJH1Q(=lIYxupBeCLuwfuGqYnrT=WO-^v|j4J&RKAdhwFenE0JRN#|;2sb>yq z-S#Cv8GG#WOpTlH2`*^SMQj)TPi*Uam|Z#oNx{pV-im z;%!9Ds^zFL4RYJE2A`o9^ix(s8?>?rS$P-5dc}v%;xqNv4*8HOqTlC;j72)~nKo5K zXEcAdv#s{Cx2^8+2ng-8Q_H7u=xTq`{N7=s+Tf#|?P)&KT;28j91-AD9_rd?f5@J~ zu+nV0(^U9DH#hr&{bWh0&*IO^8aZSAArtH2TMMU-zI?w&^04r6$40GBR1TaA8G9sQ zw)_rdcG?J)wMPE6D||#F!fYB;$>cEh}(>p;x>aa#BJ6J zst>rvY&Pd-|AWT=yBh%DLIi;y5#a`~4hTZmw$GgskghV@tDrU5)Ie76ehRfff0{^9?`D zxd6#(r~KO4=VWSzYpn?(yK&v8$9wPB_C?}5PLEmY#P#JRdQx$LTZ;qUrQ!S1>%MpK z2bI^`@{)Md?4}j{lqH#^F*6$L9wkff`Z4yUD=m!%XPW(2R-2N>Ca4sL%o#jd}haH2!kil-eIWaEHO$yUfEE~5rvEFM`5JPg(wVQH-REU z-DL_t@|u8JM8${F4G&p_fjSy#_P6uhspNWsDZ&A8&lE+ zB0ZqEyZ?-o}$L6;Aan&0wjg3TRnxNR85c@SaAX*LiI>10gl}qMi?P``&pw1364dR zn1Q*W*;~2~Bq=PCmduLX9InUR^Z8`w{O;^5;eOZfCHtQQERdvOXGUE8$DTpwF_Jue zVf{z-zI>(jv_&(7RbkPL=%X=mX??M8ouux&yg1Oky09$uW!*kiqDax(&kN`E=yh?< z{I&Mfr^(>~Gu9t}xs&FnAP|;GT&lzwktgZCj)lb^8cSnKE92{X6%edP7cEH%g@Bd> znj37;imu9hez_j>-e&2jzvB`lCPdsx8?KGyr@z!ILCj-TbSw9*64}B~XYaodED^mR zv^nEtW6M2=B0tXWr>0uwFAyR-`tF}+fCY7zrAa$DJlN#zNPgU^XZ2!B#?gwyFAkwp z{oN;uCSKn&hWgj;gU_dCXyoHCBGR zSkIr;&>8P&b;ztNs$(vxwrO*|Yw_yq2?Gba20v-$)DK=({^nUpRJTi&vX!en}4h&O#=+dcw0#{ zl8h*MZJJ@+%gx*$B+Y*rKp(i&VbuCjY+2P#0p+2kvD4kaT%gEPRikJ1_w;bhY=@<% zdZS}P`C;FMMeij+4{v98zlG8yH=B;IbzeWL!d0Iy5Hn5NW_`}G+5fcT@6rBQ=Gt=2 zglv*YhtaDmU-YF)MV=ns?LG^OacjRU&n~ofGA{=f7k@S7_3v${^sQ{H>=_VU zytf?Jnp?2wYK|hCfXW91(fokSGZnJ7^tQU9kr$MnAb}W~c*+%>A*k_<_EKSA!Qy#t z;)>!o+Wi_BP3iZ$x#dZ2gP&5RQ4U?<%y9)MqMfF+?GGvxPJr<44fAVfD4m)MXO>|r z73?WeB~6_@k<`CrShC&F5A5S9+j(PE%NuLb{Vs_5$2Qjl2xMtn@^d-X`+uJiG`t&> zQKszL*h0AJxtJR~*eGYwH#@5BD4V;)(snP0gsE^U zEe6T9k>n@tLv09eh2-VerD`21N-4eMsCVCgli?L#7({3ixPOXe;Ox6tLBF@m7k z**U$ESo(nB}D2f2+{rVy85zNFmP<)7ADMzT!vAo?osf`GgxDootjml00$rWTR=# z8~nP-f`w?>>d}-F{T;rzDr=wAUGKU~y{UB3^_SBLwHh)~pmrb*zw@%|yl6H@?qM}R zEq*C8eT$QU1_(lJR`AHGC)m%S27xG0#84z6-VTt4pu&KFO8#X@S^k3f)LBdVtN{hE z_*hmhliH4qor0dV0#)0jezirFt!-bIluax($HoAlix4B{P15_KBy_-U#ldOTJ)IjFB_sep2R4QYztP4>5e8|UxdIKQtM z) zj54=)v-sPb^TfhfWlu zdnRQ#y~4cs*xFS00{eysVD(NiX6d>HSuxQvHe+=lEc_|&vvGPA`X$@DKDx5RlBu8j zekkK&jinrNiku`DG{~08kZmtA-JJrg{Y0sLij%t+;=Vp;UszbslqM zi0k~C&fS`3V+om^ZhdlLW0lzRDxrgjIa$O+3hxE&y9{QFZb1$EFH6tb|l`0twNY67}#gSdZ#HT=u%Y88UW>z+lW#wk&%r(L;>f*V^zJx%Navfs?4C4hezzFhGf?yV zQ~FxIrJ@(W_Y_SR>JPkrH#uvqCqxd_7TVbtx>#gOWYzvC&=;WkdYi+5zJn(Ibj0_k z$}ZYyQ8I$#>wlJliU15>8LY}q{m_EBXUeo6VnpwRbwXp8zY_!l?u=dD@h8{|EDA5H z>g@*a>5(6{Ceav6B&1f-GXj~3IkzKSPx)Ld9PAd1Jm(PT;oUR9K0~NrYb5tHO}%xbB?=emVS zq{w0=q9FN0a)o3K=>nt^kmMkVK;o3e^1&K$@D4b|^17R|QsebmATfjL_2aTRBQ-u0 z2tBB8AG!*d=#U87W4t>yS2MmsrOwBjwUxFcMvVQ0(d`GMen_1$%DBjq7DCETT8ETr zNRzZk=iYdt&BP$RxlQrco-d+klt0Y>Xp~o=sR{SrO8bjQ0!XQ$g%xxI`U6xDp6A7R zJo2>m%}G(b#y_|yx2ltCvqykd{u{8|@*bMMf?Lih1&>@%ON|-Pv-Rt#5SPju>y2*Y zwg5;wS^*aphBK^q@N0PGv0e8{Kh7mlpHJ@VNu79yuGbIh)2>i5@6T2NEI_;cRe&n~9>e=qoHt5@WkLfu(oO2`g9u!h3?{?4+xKri4 zt5G(0`;}ck`D;v@&dTN9|GDKh+prX4HLr2vmmt-^+33itA(A=l#}lbNwe@pPhVt6| z62M*Ry(!t=c%)cF7O>QB9PgUEi}BdLtMU3(9U&s;Vus4N#@Z92bS3iyFUg#W{f$Pd z1|djoddn=Cr0gLcDnCo(ftnYi?&t8R%2uQjbmCD*)#8}Z+6ls_+Dc~7FCD7tb@pCz zH?}umv{$}fp9pL1L&cp22XmSqSLzwdym@hmcMZgorPoFCPeXwGW<^rpkvk$LcI0hPNJ|6n*wwq_ePgXuJ?E{8^7P#-PV+7rlbGC`Cr2eeL~6NvBs{KX?Bl>rOk#;D~oK0~38iYv|EyMUK}4dvsPs2we6S@7S)@b{>*Qt1C68&0C(Z z_F4Iw>($GyA8iw zwi)TzO4r>xYImUS86D}6<@cXTr%W+PBPA&Kszy!jckY-=y<{AScwCb-egmegkCrGf zE6GCCDW2qTJSI)1BDFO0ZBZD03a{UY#2)1~*W2<;WUaF@1bZ#bcH{auf82G9(uQwz9&wWWAv41vV{dKm^pZ^gp0*ir2e8W7Nt{8~45oK&* z*f!bNq-3}w~gOs0TB=C;?c1}Zh6E)mxB&A?3PRRmrsSB)kNCl{b+qY6< z&VN6`^k9s1Ks&ubD(^kT@P!bVpCLkEJ`atN`8*;6rsYWCf7dy0@0~@?4x^QI^u+|z zYd0x)V~PyqvMA7{vSBo0`8rrYagYPqu)rb9UU|&_v$RytyAdf$|D7mnLD?$54$}Cs}h4&}alAjUv<)^Ykk%{y;J_1u+kYV1}#vPKB&}0fLwV5%SO4 z7v5|%#9=W5f>;ALMw5y$UiWSfRs{O&d6JuAgcy*c7$Jbnw_wI9Y={D{cV_ctZ-%jX z{6m=-1wD``cLgAR0m|^!7|QUP%Qr&G`>X~zq%SGCuoMW9g~3s>SsPjS#UQ0%$43Z+ zK3nsf@5%1KbX9c~C!Gyne$!Hjdb|rib+vk%#G1;J2>!8(4-+>sd?cq54E;na7k^z3 z-^FXRCuiDad!ypP45thFj4QU%^X$96bbkj0{$=cDEODfwfEo_kC4c%5S(f7pey zx9@Fpp3@x&QTevsaDZI%bTlY|KPO_hTW*=!mA#tdgPU2W1h3D!q3zWiDoT`M<%K^L zlw#M(KNXbXF_K?Hdo{Pr`qG2~yS;CQrtZ=~8v~zRb*04n+4Wz3Yv(LsO=H$FTbzOmMn0&XD^qw)yEp1s zRrQ>@{j=|+ztJ0U()m}aUEGOPHt-;Y{h$tCwt;&4xOJy*^wX;9Z`mbD$xFn#3m0}O zieYB?)WcNDMrPJSnHWH|?ST+JjhtIh?t>;%C(A?J&1q>e=8~yCeOh%rf0+1H#G00d zpHo$Qmt=>QChh$yHSt~i#@?D-z3V}e>eR{0os#OyrVn%XhDw&~emGUt-_<8bsSYo9 zzd9pe?A=BH-ai>Qbe;Sw1BVG-S7%nUtNRO=YrEOm7v^$lio2pU@Hd1GvE!W{FQ%9< z4AI;xsa}=aL&e`#&aOGzccZ6IFm$-=tGD7aN>-h}J}`OF;n2>_!Ue*AvcRM9Gwki3^dg`7k_ zz*^@I@eT&Jl=@OzoIdHi8M+^*U(2YF61@$hCAF6nX`+j-9yp5^117J3@Iy0uNrR9m zNFBtcKj^t7OoJR;ndHElRM|hX7YQ>c==TZq)&3b7JOnXY6?JU1OsVFRwcuI)-dsC< zI0u#VX-P=X$CGF0sj%Bo@l-TH@xqXfLb?L!E~J-`K0)e-L`4hru;<7N*mJ}PEu3}< zjkx*um|;O#JHohQms2pLv@ZdlS+)=iZyb9`7c@@Ud?b~K7G@9bka|IVoQ>D+5qymJ zPW*nZBi&CQWIH`BEzA&PnBSbhDTP2Wxi9_@7pkU*q@DuE&lb=Zx?r_A$j%;@nD#?U zNE8>p?5+2*;_rnn(;bagq!#8YACEpojkx&tv|_7tU$8!qhbwyb{4*b1Q61)i;;!7b z8)Y`{Wp5xKjze55yv(6+W#RNkqrbp@BID@rkfVHCeGXquhekWMbckKU9pANuU~uEu zl`VEo9QQqD9oB#3M^9kV1ij2>>}7O*7er2!uy}A(TCAn`Ennds8=n0%`boj-z*y3> zy)46)u_L&5r6p$oo3QD6Zz!E z>V}&MQVvc^I-`OtMJuYP#L`_6FBm=8tof!t4=GG{r`soy)_zY<&aZp_`nfvRW%yz0 zMd@fjT=Too+L5i3C*rM**1tAhHyzqKS#DIiCYPjPTp?}z;YEGa)=8|yP-`d2+hANA z=WAfA;^u0QvC2aDWxk9XYI4U)q)edzhKB1RY4{=kySwNg<@r&def^u9i?a z6moo12OB&oOs;`k)aIobg4it5DO=~w4zYCQeDd*rs;U<{(MGC_Ay5xx2Jmh&(U>8f zMJ{0If23@B9sj>>*Po_<3q)?)=GDO_OUOkgHV*uAzXIXv5NI+2F18y)?!`ZygPTsd z%@Et87P;z~+wqi}juhtOm+w5Tl$nAB0nQ>@ntEd;ifzLVS8*^XQ3+}88f3UX?)0Cm zSx0R2oyV;KIF|eG<%_I$(Kv`~p~7!vK$|h%M`h6*MHx~F!CJK~#HhmzWUb9=@DJ?% zc8rJN=FSYKzgoa;r#p&jJEs;2{1Xu83!2Qk2*yBeBeD?Pq(?PmSV>2oPz!;tIMA5w zJ}PkPfrx1DB)f2mB7x-s3f7ONYoT z7a;Zw#F@Oz31M59AQ}v8>EK4?-$Pba;5T`Nofpw<)3@W<(-F(i zPmlt58}$szpAO2pW+_!0Q+O68HTY~qiQAo2x%jSgc)09VTpZFCPiYG?I%tdh*+4Av z#}E9*1>Lah?&)1Sua-WqFnq?uU5m{CtJDx-eOOidDQt<+@4dZHymD~=vMaA%V&T>C z%Jl0?eQT5Tg$oNB=R4IJ*XL=;_I}Ghx{T$7UF5l4j&9Ag98dN<+2b}Y zzB}7q{oa&8>gkxuPS%C$2_Nbq(^BLOzXtyW9{bSKpYAYG1XgOPlt0urP!LotQ& z_HG&D(Q^JyvzaSYSst=z!=hNMgvA*mr;I2$n0uQ;`NNK%>g&{5JEzp`pE@;r_8b^W zofFi8TJT>sJ!Aws)QewNs4zGy9Pi(4J(a_1p=VM5uM{V*;3eBd8ZW2$b4pmZVExb8 z81e9E=RsiO+~eX{P|J{@Ko2M#Vcdx0gusVkr?%o)I}Gq;_01}J$s(?rs~`g~4Ir2V z?-nS-jcio?Uo-tY?!5YXi#nt)$VwWdEvPR@rz%Grk<-Ily*O41(eY6 z9)os2mE}!D>Lv*o8`9yh-<)lBAu8f#u3lMP&mR6bZmy0L*ld?3sv(p!s{o;6uWQr# z3o;!+6|(FBfqpR{IcF^2<;{m-$5DNo`hlhtI()yrjWc^&UEeb$vx9*)!w&U_@D#Gb z?oc1k9@DG7Qi*F^ck*(#)G*a0Vg?ePS`Pi{j6n}2n;-uvvqmbzg_Za@5Al!H<#RON zDDVzVpdVj*uNn5R@GM5TqSdk^dFW-NnQuY9f(gugEW4dW-VKl^Rr|)DSTjpuD9LFw|^$m3e&*&xo=L9~+e- z3}@5S8|lTG74>vU-hwR%2E4*1?^v zwy|#SX0bmSluy>wZ%%RXG(7! z2aA5=OP1^T+O#fdqx6PFUnDSW=PY~zmb80A&5M7{&$5{Z-}umbENg%n?-P6joz*f! zYxV{*`jy-cDWNiCEdfhnlyV7}xxLYbKYmjIgPrqi%1e0#OK~bQ!g&Y`_J#pjFi--A zFfq_fg%`40ZTL;%1gPmiHU`l_eGVju)Tyhy$UJK6Q#w+3;{g9tIuRRPGj^o|V9lU3 zg%^o{8tZz8_HOj#*JcM-5FM5nkj@g696EKba^dxWSIdmKW0-PDdR^527R59SFYlb1 zEcNkRUm8-e7I^8~{^r?|I?J*4zum z#2Iq}3n%}r;w5czboXVckX)h8keubUxZ3S^-rlFf)%E9G6jfY$gniAZ_o0}cYD1=A z)pnhn$*{!wz(ns9;_yegcV=P^$j`%43`O=%xwO~SowmV{i2;7e2r-%oosFWRik6_Y zb12bA5f`=4sM?JJ8}>#&>SM~5I4`vjIIdv0#-UxMdp zw=7_|?JBb{+;@Z@C1#5xoSkBE2;4qQL%LiNPRn~Xu`*zLA{}YJv$1TAtbZEXJ)ZFT zjxDJ%?`618(Nj8J-;{|W+7Lp&(c3_L+;z9O3jM-4=@bc6Rvh7b+&6bK_GYLl8S(u7 zkA^J-wUduAhXDidjt^7islGEltEl&xP2WV>*us=}ga0kAFYgQPFY3A7T1nZ>{Jn}w zITt$*){8IUv@TcC0>+2o5Udxpzrw1i-j4QB>O&=;Q&u`rP{B>vgk7t6pOo8eSe=u+Nmq#C5-ByH1YKeiIlY+WD3} zENUjitgo9rGS_Iyi`1d|F{U2jvQ@7PU&Up9^A%J6={G3bb3WbiQo%?-|MKvplt)|H zD4Q4}87WX9FY+%MYu)Xm(3-n_NX#ux^5o}_&F$!WX%p6k@w0it90B!37-j9Rd);7% zMvQDRZ3&aiZA&``(i7s|fVl>cvzR^|EGBTQYkP)AWseQcr%`oJ#n zPUYYlJz3UTZxU;06}V`0mG5+Z?J*YfrD+RoW1l^X6%&%bG?jYW>(8^iDh!a%Pw&)XV?mr*t<&t**?kbx+{V_V)NL z{B$k;md|HD?rE>0D{YX+CU-G6CIc_V6m!ZbY*jo|U^r}esNIup{(blqqk{cC_e4XB zAw#irPgDDnPZQ(1!41)-jauEII>v9B?eo6#%zx^Q>TRvZ?Yd}O%9(YQ`I$jPTpn$u zyn;3JR>)FeYPj~8RddmhBBf5@pGYy_FQ2v%COyv8L@QVeZJmtG)$B5>K1yTe*Y6e~ z$bgOW+66AVB!z{;C{hdc9fuTpDsreYqZ6XJClH`Zny(@NU|2IRm<-P1^1V}!sY`UzAc?F^Jf`gpVGPp9nxja76s z5@KemM!RTzn!pS0NqF+Fcrj-XS346A`0gh91d79qQ} zU=V_6PEhxMOym7G=BrrWkT2-R2nTqAgf{UJN=s8H&a{c4gOo>dsOW$i1lr=eB)3;i{XQ$Bx6}jqJFpSyd2IKC zd)=q0Pckkrx8ES{>+?l-Nszy_i_sE~O&*fho0ROoIN$bjKsib9cjt-)k=l==xqS`S zYSGK|IY<3f`U&!#)%dJjt!HoUjCkwT63gNVR+?0TSIqM&+V#Vq&* zy{EXgv6CYO?;Yh7vXLP8yU<45)-8;#7NB1Tn8Wp0@B$n`G%a@~; zSA|dxbw{yp_vfIz4qrN$Fe2sMAKMlz8uWmTVLsGK_^$O?)uh=}OHHC|-iJOpGvX{O zcAIgSf%sj!Lzt&TZt03Z`y|yB7k9t<#_w(>!)CvE%x^ty?skdsn_P@&l=&pytTz73 zwve;6iM9AB#xHJ>>X<2Hvhly)fb+ZCF|*~Cjrt|yG6O_WM^+;T3Qic~pNT-Jdd%Ixh4Nt$7AIDdbaol6~;b-iWrNzL<&9TCcsD_iI? ze#rVydizCAdFO@d3`N;fMY~C%Y&k3V%%82J_`{x3Q@hW~|F}`c+-gj3xf(^A{aplA*s?fmW^WtQ71LcOJuGWevv zSD6tjHdDL&)*&GMiWqgx`98_@70p1wLy68LkC}PK_@=A@gHBf?&W@3#)v~x4`_kpb ziRERDHd5Ab1)IWZ{_}8E$! z=c);+Jj)gLC(k&Or>`w<@9m#nneMAyj*7^Y{!((DipZA!G6RT!yoK>3E!ImlrPfmh zH7W^!f#py9y4{IQ*7Y&+?eW{+?%$gg+=&OBQDnKA9Xp*kY-+>K|JdA#ckr>gBAPF!kNna$bm9Ei{LqarP0_B4maOl%_u zxHO|6Ky_H=rC7J3qhn=a-3M8dLG4X33Q&veos~()0D9!pDy_m(b07>!OmwXn1z1NVpQ6@Lzj1FF45&NH8?>)_yMVRt6VNNm?A&)JiF}V_Jb2>1^Ggn<-i?oS2C#$+N*b|)y15+1~Kb1 zvhMuauXMMchaTBd4dC#y!&iw)yXF*<-m`(d>>kW}u6%wl`tjGFK021XxNRHYl0?0^ z(iia=j0r8#J?$QU&{fZ?9+nAavw&x@f*C`eLE)mQ^xz{$@bW7D-Ja@Uc8w#BEC-Ju z8zjQQNBC@ni4AYGQu%qC|Ja!`>^a?1&Bq??msL|NnG!LH;*(ed{0t+vJ5h}E`@RImo2Y~F{scT^Q3dtB zel|saz9a`n`uJq4>94XL<*OguSOnWh_FETL-rNlF`8Ar-*c&@RU3*M*=~vUJrMhF3 zBx?Yp5@D6Y*o0-9lhexX+(SH~gM&+&S8pCXQ&qhfR@HPP_Ho2=(qrfJ%ZH;;C}Hiq z%SYvz>;~P+5EN`3YapYNKbqpQqe2G(5LV~~>i9e_vu6lx%FKQt@M9*JvTplyVppg>p@#}*P3%5lgbJ5xJ;|}-@YTQ%=kC*OA(U}R-lYyA4Rn~_r{4l#(>}S* zQyf&sb%h|wLOKHJ9Hh(OQB_0>X+KAW8@z(_8ilN!-YR)`aJv*F>BEEIi$pxEuw?l@ z3rLduF2{A|95uA0_*7{^*$QAjVT#gUB;&rlgCibIn__~h4f~P9G zFpe>K)f3k+VfgY34WhUtfPY(x;MS=mm#VTM5Wm7W>AOw$#wnV7#Ns_L>feq zXiM&jaiI2GwCJ;S5=g2XVukjAc$9IFCpfu!uG)!}Ub$`iBH_3Hhp~%-wFiH3cRsMP zA>GD2`{h&E5JH>3{P6l~#}UF!-5|a(8}}f-k>MbGj`NFSz*2F*LkIrkc8s{Vk!!ZZ zZ~bmL_<1aTmh@;9_l(qD@_BdG3D4IfMz)n%PLc)l2Y>(STAH_ycsYetdDTmYKh~s- z1lKe?#E7>tX+#+w>KL9s7a`C$uRkr|pi@vli`d89ydHE1JTr@{JuFXbUkqwJB-nqX)bJ9rhVI)5j83}OE z>5M^MyVLp?nLwqy=gvLSJ_fe;dUvrAfZYO|<}}S8FW7%xBLnf;9mB&<80;_&DHO+^ zGbpG|g+peb4|)rZ0D*U|lQigqpsvPjb%5bIr z1k*hTMC^zn9I!TVRx#%I<_K^^OE{iBmd;R1xLq~BBI*ePZJRA2=4NYYv)Ul!H$y7{BT~4rM0sOW zu-3WHh0Az=!Ur@A>k+jtD_?UT8Eisw!zQvu(#=6xX>guK zOLL#&Xt%F-?{1L3BUTVC1hbH_-|LaS29a`Rx1nbcb59i z4%Z~{VIC23(&m!ltd?eL@>x7);?g;rRL;vCHxycJ)8i?ct=4H@vy&Al!!k+B3f#M> zI}xzGf|m4{REXu%|1IE9IoLx>lJ)QHBJqpbJ1^g{*&CRLHslrgKv0VB9$wn!$F3C5 ziWmKmY2%!Ikv}FUtk!w}Jg)IE-8(Us>nR1l<`vA_N9}KwLp1x>YdPN=LvQD(YXB7C zV_1ZSSGB@-J`LfeyyZn6lwqe%KK|9ELYf6YuNg}+qf8)$o?4{vzuy+c(=+&a#a`k42JrDs{wfq6OR=4!g8r%XrwJfX(09O*eLJ=48RkI#wEK+KwVe!Z8OMi zcn!DwpOV2J*Nt(``|FH=NI=AH_QlPNy#uz$*5WaxM zfpO?XE%?y75cpj#2!^fSpbYs*AypgejQ@Jy@`1g-X9E0jIHWJIe>0^mgd;-Q!s`|h zi+BbxIQ)?8%37mLulMp-ySaR zFbCS;=^h>?P01^a_`(YFSt*3T%##3H)4@9nSYhWbr3F69>ko1pvpu9C;6M;^V;{Z$T6ADT+Q={cbV^7NqrJbk2h8&7|;>hGuT779-v_>iX$vf=524CLv9VC3oZ zL!|eOs{ixpH_XT@s8IR>`)^R%B2ORMB2OR0!qbN{;5(Fj7uHKki?c;(*$f(b?rW=;u}|*m=*tsFTzny0_!PWN$Ok ze#wqY?H>Q(u2Q?2emR>NL%jYk=0i<2CrUe63toNa?$i1zL)1A@%3v7mi^kMk6EzcC zqQ$@YQ(@e6U*bgR;pD1qIMaqF>b%r~A?WqMLv$IAaGm^L;KiA(qVycSVN$*4vPg+X zKRN?Zh%YOQPSYbMRYIv{TpTqoHjaw-z770x>@_H`q`aMEWf(XuH7G-%A&@_h|5fr% zGN>IRzP`v9gCLT?f@Fkqz`GgPVZuTW zR|1m)=oxZHpkv^0=KpfT(fRN|UwzqXVW4MfDG!E}Dq-<-RD&JHhFjMzN{2Kx)YYV% z>*TSVq0W6hw zSQU3o*?rUwqZXBk3Upd}!>|i^sG2=Xh+ei8gVc1yxW+h=;|y!O3>Q&uh+D=2~D`5o9x?Dn`{ zX_@uhlc2BrU`Tq=Q$3$U2Db{6`oeS|1Kx@|_V>dLTU<$_v48SgY$=TJ2MB9%7bES% zH@d)CR~Gwv!>*xbeZPAW6%et3^a4olN5ee+8&Kd3c(M-Z3zl-@lU?2s^-F^7fiDBcEz<$|Fx3oI94=K;2i+XWUP z8`TL75xBDki-gS1=|89#8iFYS!|UcwSVZ+Zm0)-cs|<$McRK!*{paIUPlvb&i*!(( zOFXcL^1uKUP!x9!BoTH5N+S5^cW@lg=Xgf%AO16o>GTttqXv?;Q_MTK_UBgqZj-)`5%u1R z@Pwj#d|-1{p*!l&{M|0_wgqSSQ}g*72oc=HQ+cOkfm_{XsB3ASTj7xT15s9RPv3IGv58t`vTMsr-G5j_4T}=!Ob(5&X}uS>o}w!N+MLB8jhpUAoNjp#mz!cqmg+qzi5IJ7!u<{l&s3x`lt z1n@SmgDe|D@QX;Q2!Jn7j7QdQL_mQ(tv0|U|FA#7i~cTySx7aN9Ol^=kI zO_*7V-kB{RPx4REU7W_?L@{KTGYQ*k4A_SY#$X>VSW9x(0mN1XhMZbcD+HLldFLYa zyRjQc!2o73_V)_hQ&2<&uxCIXxS_ztk!q5O`6_yIeBgXwWCUYLzj7jzV7q>?0?o5v zN7*swyMYl%fi<{TOV8i>+DT%_`fq^{Xw^S>{hwR&SA(=Zf~cLKHQ*xif3Phn01o?V zZ~@EX&&B=$_k!kefHVB@NZivE~% z;J(6cEo|%8**=IBSFr`n)qbI&n>Ao+i!#Lb?m?49Xu3B>~q$Njzz3=qaUynm7(sxGVD8Vqoh?tgNs}5p`-&o00$YO zGIbc38+tAw+kIlOeIPg#$0@dBX!;|1{WFE4P_1+}S?(R*lTJpA`YN6mV3}AY`y>jtmvGmNQ%WE5w%p3e2XMIv?_0Vh32w>pR zxdgK4CePUsc+zNxAiu>7WeL)&<0@_%yo8*iIHvmonv{4L_`=o-4 zgjYC5q59Uq=V~y0#Ko`K6!gK+H_D%=* zN`us&z_y@!huOohz_vmMp5WHc&ZS4qZES#>1{>i~kij|yPzz=g!72ko!GfW_;r3t? z^ayFYi^?ipz4Z=;H>Iv5Ds0Uh?#u1(Sop<&u(_K3_mT0^lX|De^$^U+Ux0>|bWHs;C1bP4T)`WQ1XA+a|Pwgjn zeQEUDPI+;l9Kp(|y~MGH-YjcJ3$tqxr#Cl+;g{~JH+vgWy9Vt)o2r{%m8e#eT~4HP zOHJgZMwvBjT<)%8Iz?Ts_0w?s4?yY{Zx>JN9iWL)43P}yE-?=>B~h3s{P_ID$(&u6 zSEtQz>myE#Qz!Zl>rK=wFR@-9p4uEZ1<0QSuf$y|8DN#i%YMV7H|@Vqx2B={E;hU& z73)pQob)EC4xbX*blx_DO!VOdf0gpNNr;3$gX&(&OI;H*(M$v`2H>%C&&kl5v~kjs z0jjj@4W{0Q6E1)7JF~Bc_R;xfpo;?En>(i+JQWPgu!Ju`>PjQ!{zmU@39H2in>7Z0 zMlqH4*5GZ3qFK1#+m^NqQF+xl3cRs7%-uJMs>Q*iw=u7J0fd%}IYa{Z@Tk6FU_gyR zUM0i(<*6|U<%M#mWG3II8Sk+qYz`vb6tA3?>=Er-kh^zW_SKLH%!5aFw!J?qSySO{ zHfeBRx?yiLJb4Y)2~J+;-t}{&!i}~CU$YnA4t3tS2+fcR&X86L8L#2!-p9taC5oz) zsyApWUK2s31EEdx_GrG#Mczu=<-yT{12`GX0$kc!qZkW!41|xu;x zERK@S#cDj3?UOcH&sd6 zK7M~%y}vma%tO6>IkMP(ekfb^A+XVDwQkvZk1qe$Oxoe%Z(kow=s}F{zOmbgc7MR` z${VZCFHr_AuUEQTXyta#kNjRz>obj{zKPBX@|j`jZH?pcrG4$}lSUjzg5wp_XTLx} z*3}meuiAImB*6qvP^IksOeXrbvyo}?Np=Y33h8vqvK5A&!Xe<9pUMElQ3=F+*v}Ao52&F|G{o@k};#C z5{y~pQDBVXvrlTTNIa65VcnA)Tw=Pfga@+GbR^V6I5XK~h(`$NA}rp;cJn{(TS=h@ z#qiE2cl0kYTcVjhAnAr-X9|Qt&u;#YI(I>3d$PyCpB#wbYRM_WZti}hl<@(%+5#gs z*W%Y#PEtwru%X0lpuD-dq9h)6rhN?`V^~X^>#I#l?{cn(qbn6)jq#2`2H|eIhBMpm zl79lI{P_SLDA8f|bdCn~^M{(dZvlM~wa>i@&_J}?M9@CyXJkcC|J1`R8KnNTViV>= zZJPi)=PRq1VX#YF(KW-W ziH8a)0T;b3qM7@!V6`xZxTV;u;Sh;60^c-Bff=+v4tf}NQ{cXzf}F?B@02Y&FX&77g=>vRR3m2A~^K`bOzi#7ABBURz9O%GgllqGIBMJ1EPnc*mL!WaiK21i4dkBhA*l^U9>|g0HB9q^_(yqRhB2?O1!+wm}+8`UaA1_Q; zMDHovFO!v?^Mt6MOrgN_AXE*8I*Q;(RI+jk<2W&tR%U2Jh7F>8zSd&*5 z7iut<{e);E?^$qHJ=w5sP*L@7^&~>uG`!`Sz_zJjY~(V)#9u z1M#?H5zmJ^>rY=*Kh5e`XWO6dYS!XeoMVr9t3DG^Mnzz@UCq~( zX0Ajs$IPFl(7@CUn|#!xPMx$uOUY{Xkd5ln@|mVbC=8T@0-$m|9@4K`p7ZAK^cA`eS_c+8vXo<3 zfXx-3aw!oFvqwTWg)?2=vF%W1eJ@x4^yRe%(R$lS435L1oY#w%+xvc^r~wcUu>MH z4?j9Ly>#Fdq!Vf9O;Z=PUa~Le6{}7EZ0Bg99z!yYBHr?1DA+_GARs@58NSd6?0YJ# zjG$5p2M1+(P8@LQu_=Z3S&GXE58-6r?a4!<>X65{9uE%E-~)H?iKLCvpw)1n^@8Zp zBxugGP>KS@L-&0O?`OJ>FfUE7*YQ0;ri^EK6Citlga<q!Ux9kO_c@|ot zb8^LT*ct0@wD=uP&fM6`U3L~&WYirQb#RPOPUXbviTaHOu* z^?0R|S@2>tf70WkYBpnNiChAL+CYHlj^S7Ve+v6_T~~>+EJ-6$6RJ`s1u>(gbF;yJ z4v|6^VO?X7EmH>p(Pr`;3rJzVmV_@0!P9(+e+29+i;(4Mu2I^nn229yf0B0}){W}qe(?Ocmts){x=&|K z?ZRiFul0#Q2kP)vjqeUP>HQ$T><%r;YpKBtc5fBv!NgdN0*Ffa2l?|)bKWs2ywzBa zlpz{+)D$VXpIJTUG0av_Q>(-!*oztc;TpxTBZg#jY18! zCs;g=x^o9`js570R6kRv%f9jCiTy=Rh~3LWT_*E}C7@1xbI69UCImNPtTyX|EZAq& zDZ-81wNQrSeah@6p-hXeh|K6?s|_KsP+T%Vc>m;0pN8k;3UTRWN!C-+EYa!cfgZe> zZPu?Z#+cdiMskJG@zEtGeqk0IIyw=HN@q-bJK8Fz zg8%K2WrYqAEER078T*V`26d>IHb*H0{Oq6R3<@=&nIX910iiCfPGx2&%aj!H{3aCVH2r>dJPNbYWw3637=-ZOHr6ue`6a9q zFks}Mo)xzLZ3&Xqhqchq+M2}o0cCgn`21L03dg|i8=?pHbmFc=FY%7Rrb=j1%LByG z_(=;i-Gd7l;r_4O*bFY?@B&Q?a*S7#GQWO(+<&&Y*xoiLYM5pS=`6`Ogd4?2YCa)A z=6V`1>1QnC{&gb=`eulrX|dAN@UbGk(X#S1XAycU2}Viosqrh#BZK>;(F+k_nq%=u zZ$@ABhH3#JTA3Jel@?#u6r?G+65&W$z}3WY;M3Edx(lygb&~;?XFTut_7o^~dC);aM%IIY0Ny^0xV{`KZ}B zdainLNMYqG|K`Ihf^Ih!?6BDkNY;;faZS+CPrF%2SMR9ERPPK2na^f~074$B6GsPx znQG^b4~SS`7Rm^S)3R>eW(5woC$1*zG4 zH@eW2)Ym^RH&WVfTC^wpd|n&;yz$|*>8)~u{X3B|(Yf3_3D@#3=dnI1ps6b_y8qHw zv0kT;qTNcAx#w`}Zi0W;yWsI_7X%FF+hXL6Ce4Ki4{7PGoOjI5XGM z1Xr#DRmyaG5g<63cktUTgDY8rY?8e}rSmn0ec_TDhJ6Ky23@Y@*cv3x+7KK>K{%HU z;tWEcG>+MPZRoc^YV>G(8e!GbeW*;X#Lu1S@ZBKQY2PPd<9lQTL~l$t)p6fPQO6<{ zBoss$=4ueVk2g-B3PXb43)%MHa>%9wGwkQiH?7=HL)z0U7L5uSEGY*vH+wmr>O;ET zx2Arb$jIv3y?Gl$?JI_rdBHn#Txoi^Jzyld4yAg#K9Pl5q0-3kP>*QFdQ>I!uJ3Xe zZ;oWwRcV}**$7&g^>{JnEj}XV<*=*sc-QX1@6Fa73!>Kg+tS=qw`|R$1>&0Mh1rmw zqs`5u>|X9Px{qNGkXS}Kttj|=@z-&;X`f0l{AQby9}zVU^NDaJK}={~c5Ylttzk&B z>Q@nbEABc=)hJ0}NR#Gv2#T^n8Cmrxin72VG7Jfh6AK+pn;gHU!%Q}axxw}cT*voV zV1ClU!~HF>{h9q65S)9p`W_1%4#?tu7GQ)ks(2o%^~rejlkpvlo`kT6Vn30a0>7pc z42VKSoix|NkdSN}*qy<7K=8RnI(T?-;7|fm&_9__qT)UBRnO3U6krGf#V|vVu$WY^ zn6wdA2@aMAgL>P8CIP7TTrAuj)EhJm2K9zD2td7Ih5sYe+y2QY3IqtHQ{cmWe*TGG z7_=CS9%1q@)H%=(L!D!x>n^QDHQg@vdbJz-k5BKEeYwwg`+=+g`^)}|WpmreXETg( z&fA~;J{HETzcpBB^)ys=s1`n)Zn$`;4!`vIYI`1oWh?L*QHtlDP;fPh(7S`EeVa~& zR$YTkb83k|RHRJF*(9Rlnj%jwxYJaGj@FNGjx+*G*>ExBdwrcZd2p8r2(|)7U7ZQ? zv+A1nUckGhR*lMU*};1wpJi1X)%AGL{S~R>rP#OoGOtZ-+}nG|ltjN#&Nsi{^rZY5 zR*U=F3kBuf9pxNyk6n!8_o)lB-ZFxF3&_9ZlpXFLvQHLPOdf^xj3;s?70V+1(-*)} zfmpGX4&f&#v6h9iJ?pReB=`sx0x-Won4{H>sE0p^Vgv|L^cEheaZ(ajfnP`x8Um;3 zJcmXOn~p6Q0;a}yn=h$*y`_Dqi4@8%7sW1Dj#0vg?iPL+aIqFV7w%wA!z*9pDU62Otg;z4<3?s-^EwWNAP5dR0>o6Yd!0|X_|u0(&atA4}z2ra18Qm z3~c7pM!|k0+0VO{L*%f+k)z15Sp=*_I4yrTisU@+dL^A3)`bo-G06ofRY0aTkam;- znL$9B0Avya>6UCAP~9A40DHyMg+*i3Md7#gk-6sCk^A(#Ir(Xv)b%{O;_-|!1X)6! zZScmr8eVbV0S=l};E%?c-wsUJGqii0q3!TfJgw)rB8{_X4WC9=Qri<-7zryYv}Sa*}XPu!f~~ywJFT6@y6t8=p1#*jLSXQe=V11 z!}oonHwBkNuboDrF3&Xytl@T94DL*aZ z?|YC%lEtx${oDJ=+0cy=t%9^V>CpTa!C4PfO}Y+nL-XhI^OGuhiP0JcyggrQ`LoHk zNY~Y=w-^guW6|tp@3dVytaQh=z@O-dnwU8*z@74myl(AlKS~?QD96q&!>|*yER+$) zYEsY1e>n^{`kmW?*3v3j796009BgUDX3CHxH&G<69cNtKnRVQnngMAbfH>L+3L&7t zt_~xvQ?F)vT6W?^=o~jo03`N%64m+JDnmCoP-%2Ffr{VLJ3~&zb3_SdL3&OqjT%(5 zuYszPmarP(*}#(Q+i^zo(qMZuvo0_Oe1e6VY(X2sDlp8NDTC_t>0r$54}&(44S>4y zhi?t)2Iwp+)ZR?8nm%JQ9c5+wG)O97PI>-_XLcQ~=Fw+7U70B~yK+`jei3B*0j$Ff z@r$GBLQl+F$J6#Ln&VFXMwQI%mJ_FT0v6+&= zO+j-?0fLuRym(@t2=PD5sOgmatmpZ-y6Ln(UOSd#i-Ke~j!9=JFN7H6wiSviAl8De z>#97uxyNidCMfM)RY*{y%0VL?zLPlZcaz-7JP|Y{KJSp(b!62^XE}|>P^0P)lWis+ zIV$Vrjl|`ElOvmIh?HS1bN}eW2Fb$#JK2yrmQb=XaE&v0=Z{BU8VdxwTWXr7N z%YMS0wHmY(k0MidW05_zN@4sT9)KXheDu4wP!;mfh6EY9VN1f5NWiQIH%q@n4qGud zxx9PZW||=#+JMdRNM-v}>T0q1lExbKSESXIyX;)?Y4e*))ctorTh8ccE$8ch;H=r zs+JEYgiqo~`JO%-v76=?@{XIO&-a8>npLNcB$PBzQlw4jKh;X{+h%`hcC47?SJiJP zy52eItheF!rYt?hDU;dl8n>h}EB^yz#i>1M?kMGv=|>5KZxx=-m)EBgSL9ObF@{zj zc_-4*6{&wzuy0vnL6ucFratJSNO>N4L^FQK@SQc^lUG%1f!JmYSWYvyf@psD(CH9X zx6Xbcsrk0+o9kH)WbfheocNm>!fg=L#gkjZUTn4@RX@qL$>6g^af!Mq_m2)IQ8H2y z&5tZgAJVqTwAnv_DKTPOr0CjBNqFyOjZ<195VCDIDS{d;9c&6TXVsCh^41%xK}%x4 zWjiBT9qHs93$=hM*lAH35gTLg6MPJ%L^|QpavmH7))Xrkx4#%{k>)>iu4RJz366LV zQHBNwCX(Q$Y&zbh2wR#j2zV@D;eIyXP!47jX;^2K?f_F}qgEXlnjxaORDMb(wfX7~ zm!`!r7M)`C8sI3COgIowkv%Gcpzo~}&!}R&%lyhU^u8>%JSUI*Y^~TpIsIK9GpYSK zVG+gowfoz{>W@z{HZ)n^{fKHsDP>h-xhD6hWkOT=!!`sB)m&+U($w?5fnqM@ z3Z3V6{k(ghKE3XW1g_HS~;oeuJ;`iI0LFP+0<03cemL{WzS0MZSt0x-ZwASjUj{T?Oc6`;{&V zL<&E-Y{>x;Pbhsq4_ zJ_tO!YuE1e6Ui&~VlIM09!)7S>n^sA^_TV+6b>L5mj7v$LD1k%DD42gsZc1b@aqSe zU%x#nMVd~~*C>7I^jkt(u0Fz3vj1^6p`}L9_ET>5f`_^IrmD`*d6CKA(|X58ysK4= zMgM<0WD?+zK4BywvPq^TIFg`HP1bueRJ?b*JHB$*Jln3>-s@)XQKRFbz_aj!Z%Y>{ z>uwxHk%WVERGi)mJ+7&6$_T=IX*Zxfyp#MD^~(-HJyq7G#J~^jo)yRr>SM!5Lmfm$ z)QrrMG!-iinH|Lgb&H2b7`M5*Zc3iz7FT2Y`Q*0p7^qUGVE~rH4()ZG2tt z!8fxGQl>p+UzP#0DhS+}$vo%TXg@>UoM)No;fL;J5_{qH#jr(4(W9TU zep#UacNP1+N70^3i3+n0zwpJosS4sua*vMXR>DeQ_`u+gR_2jY6-gk=RJ@0}(Obl^sykn~Hm%C|Sy2izw_yzGl`yIezJ|(w}6DJ3k+i!K<_=9vzhM{hC>Tu*q=p z%>LqyQXsQ6Jm0moBCi$7z2y9L zDYw5b4fJ|lh&-lMGqFEM2OHI@#>+33$#Q8`gl2MA#Qw~r^VP37DUKK!Jw1P1({SDA zKYQOL%FZQ$ZP)+oWIWuf>~Og!1FNw$ZX(|={$`_PRrqqKLF!x}{BcGjYjz8IuKw0~Ddljs3*)8sZ`=<9b92Y|_U0~d+up`HY}9oY z`BB5iL?j>us&mo7LBT%+Xg)d@oXwA)ikP}^(Z`2gD0M}stZ>cUufsan7!^94E?*lj zMVEYx;b2Xpg>;T9EHLb~T=O9!j_^AuM8GY*a*}3nEL}0f6S?4jYk(cn2Y8mEq~Vu z9O||0TVCC4bfWX+1>+#{G&94-{EXVs9j!93<)4cC3;KN2P@(X+wpCZhvk@u7qGHzv zqvt~@(&YX)hszb-`)L{Egjqi4z2}}`a~Ju3u{tOa8BTGQiYvwTtJOmRFWbyke3<3V zLLsfV>JXCDvxvkM)sCl2?oUu7a3g1Fb)`J|{fr_fe_!}-0k{kbe*#x~P#~8ZJ9n0r zUDgxX`0rw*)^XZ%46h1lXQF=}?P!`Gk@I7xzRiTyea6OU6q*>--pkx%do_PW2oC@A zj2~@6h+h)aY?9|Zp1f<%jKzonL58;{fh%+!>ua*NCqqpyLF@K<)F|Q&VPb0wp4gIL z9xTaVAp6Z=0SP8rGp3X>HvpO^N7tAvEG-@-o!lOkm$@op0Y6D*^{rDVNhOxDPq8pfRMyB?psWFg{-kvZo*3})6?a>@-U*w@> zD4F+zvGHrH8iWWCBH*hHA>SuLK1)J;4fA{C{Lwxi6;b*5#@6XkHQtD_5gHE?h1#OH zZ}|!c4-SO+U(mFB-!|2)3PY$a>YTk6_EkNz=hZ~7B~Dtlcvf7TdL8n_zIv95<7D-` z0K>V)M_Azh<6OnZx_;I#M^fMR{5;-kTKwKbZR*x*e{?_G9n2whQq}*k@9JQAQ6p8` z`UOlC-Utx?3>W%v- zKIj6>g~qGMK3e=tg;go_jD=rVsFM}2^XQ){{E*I9QJM2-)%k9KJLR~SNH6?(HlOz~ zc5rjP2@wJZan5p$z;pVg5BDaDqdx}>#bZWwybJaFkmg?d&5`l*3YBXAGZ#rdH4#%s z#g(-yf8mb)N{#5Upk^kg0}zUW+Hm=4|FbpwXVzuNTJ<09A+HOuKDh1rye5qA_>A*N zcB*k_u?*G!y7WmuUow^7+yz@(=4E^62Ni!E0_3xDjs-qAi6h@pNr5{w_ zioC2rHA?W(BG_B`Er4b#u=JxjHK6PZ3?h+2*eZXQ6vt{(E<=H!%UypYp9n1MEv$6Q^;D;(khD(OD)1QC7QEZ+HZRuZqfTK@TH$*_ z^n(8o@IjAO;~c|x1KDhLt#YvD{d19DLuo6&;a=)@-d?<7V>a&KyEQ&VC$c;Y3!)wu zFlz^l?dWc^sYEvbyeQ8teiJynxOn4nx$&}A_Q=uY#$r76fl_^B*LUaadPSRyp{W>S z^W1@Bji#eVT~Vz*9~Y%k9Xk6k+bOrXQE#`l4Or1bb{2*O57FAN|s*V>5W=zRDcD-IgRJnPI3{ zui@P?h@dBVlRITdC*|+H?yI`Aes0+2d3$nlJdjmhr@Yzhh3jjd=6JyKeX8oq*sck# zZv&~#>H3Yp&iWWZq^aE>g39hsPOZx1QsjDQbP=CdRD)=CqZYJ?rU>QCvPLi3e8#9F#%YY zL{*9el{c#R5_6K6^d(LudzwL`|2c)obj9X^TF(=i>Hd? zR9}wSM9?!Q3EI!UP$kiyta+lU)t*@GChgi1V;jjXWeN`U%#6v;rN}~GuI?D|I2_@tlE$Y}816y!686(G-qtZz>sz!%4-&c!9^W-VA>B z>)yN%T+0e}t}w5?wK@lVdOW;x=8!qAL^N_SJwILKqzJ$vt@sxW4 zp@9ux&kEGWGq{HH1;ix~l*0~V0w4HUX{X}RNU%LK^~U$n0~;NAfp?^;-5{Ub}Q( zye6baD)QwWCi-o+RWlS9>aRF#(|j`Rmd5(EeI0VXb*WXq>sR_%Zg8vTwKx&4U8$yo zpWR&4j>%&slb<6;6TOBbuLz4O;|$}cTk^~t%PZsDH_Z=EMuOEBPSnc2{0E4m=Eu|~ zoUXO4D-xHW5E?k31v#{qMU{c0Y9_(i`8_ByicwfWN#qo0Kmbl`a*B3S9~2Bl%h(cu z9OrvAP3&vr6p|j;MU}7mR1?W5SOS3b=FZb7tOMAhwlk;>KA_)#`Wc%Sp|HweIXl+I z7T0yO6r-^RMLLE(^hs0{b5m*Mm|QYUY)><%v{D+jt_@>gJr>5mBBlgIt7#0+oF>J2tkvp`}`Z;CkxAT4YYG~)Q0{Y7W znWApmbd@q&RWf8SUioLm>8&Dlm@=8-G8b*?|T&065(1{=ra*Bc(b1{7>XG4*p?@CkU$R+9gtV-^2G zdMPd_L1v-tV);Z_neJNIzp1jYR>pQZ)2L;OoBC>-z5SnsR(#-8Br^^`AjrAfL`=(bH z{Ao!24%B7Vng+kg>+cOiHjO($Tv>PO7BP8uI6FJOG6t)Hw5dHJ8)iwo;^f0 z>AC&0vsRf-$n$J#HIovn7)_IXR)3YC|1I*5126+UJf`gG8Ev0C;36PR(Z-$#v4l-P zuY=Z6X+80bHs3U}sX3&3-|2s~J+_`BzN@nq%Q)f$uFTatAW2qOW*{dmdwn!&)OnNH zQq+~9hO!A=7keI!E8ITlPccRIArOJl5K-thR;Ie&0P93p%V3~Ba&;q-;V>#rg?~$# zA@*-bn{(Re;_+dlig*{o8)~0&WiP+ zo!QIqEQdw?-)N3PDf4o)5cbUM`r13m6*6LE~a!2}(*JkQwNIo4vjk zGV1J1Zz(ED2a4guveMCD1Y4r{^f6y)f-R=J48z%(9aSr<%f3B8%kN`)x>o?G?d1)s zIpEY<5V#h`sy`5=bFGL=0H*8t+9MdCqz{|}J5`eo=z^^VsHlKv;cT5dkU((vEI=vj zS%3z>o`p00W^`Jm#63LM5f(2`QhLiDZqG&ya&ckoAAk~2gs|yDN`FT-cBsO^>ptUi z_jxGJPwOij+OM~-RsB5;qn>2oFpW#4eOPBZJrT=l9jr>&y`<1PI`QJpXt=B)+OePW zbEp`h@fF&=up1NLyhZaq=Nk!zXpSG}HS`2Qzh8HkbPIl8Iy5$e7#!6!h4D_7*l;ct zS??6w>*>kM@=u65x-J0|-M@$wN~a@8Rgym?XT)F*bUGhCp#kufgA7COJb?y7`|Fp` zq8BKsC?v$GVW;Q$TGIx-C*&vDCOG77qm{v7lE0>MgXS|dwxM~iD5z#Fr@Ge&>&%^h zcC4?J;&8J-3>|hCCN>Jve8keY*<5}j3NNNfDjVcXF?E;S_A%_&`}kd6@5uVzG}~L; zq^*Qc`K8>>(j2S{{2ZZ4nG&(9{;|$&$3&o((|4@tt|G;*=_ z7KKuAN)IVIO|mOfgeZe%!y(k@<&D7|<%n?}gjyY;l>L`Y%t#jf>?J9+jPjHOG-agiYw$5JRvon<2pv5H``&%Dx!}enz zXYqOtW5a=j6tzcQG!9y}>W?1yA2m;V(~F`$E?#FoHziAV!FDTuLQ?*1vCJ8p^FQzl zio>0?B_iltqNw6pPIZ?3qO^b>{>?XEQTUhVGC|;Sm>>b!e>hyW%P_n&BpoqGNE~B2 zFArU}sy=QX+LI*^Bbr$kYab_7dg zhDB*NrNI&!$c4Qu5K3GCwdre+T-6vg8LpSGnXbJ< z+As!Q7g(7=J}y{w%2w;ke*WZH3a{m$$iZ8K4N5pypx@H%w`k5-8AL$a8QTrY{1RIw z?Tp4@v8`+|fU1Dw{p`%+bMjAF+-AeI5p^a~hOYxyd!PcJ&o0K=^Pa7+?LAv5j_7$H zay@m~Jo)}=|B%d4EGF^Re2^yD`I%M6fmTyS<+zuW^4Rgz0L#U%g!9_7mD*DOq9+?A zs%mGKEyGQ6KLmoro5zvzPB6L+CpS*2#lL(;jShwC-87+5%N*QC*u$+KhHII+x}M#2 zs0axu)EiEdE$*Am+|V0#dE%kYz3uKyc(Ve%3_tY$DIW15BMm(_DhhieXy|2A%IB2n zMu^*_Ev4g_OY?+i_I4wdUJDO*nqeN~b7QHm?JOm*r6FS4cUX-=+2_?;nI5c9Zl#@`W#0s|6w%_$AaO&{e@Gl8 z7E{rE)={ZNN>9H+vrXpbf^U9okCtBCM*xOlEcWQ;5^M~r9c%)se<4Q3&Mw=F_l38q zuG@3=h1I)3+VZLunI@_|re{%nDR=*L?93bUhGy~XG9vue=WPFa5o*|0qQ$#aNY6Bj zJzl4H1HJ!V^ld9uG&{3AQ9|y!r&zukygE5C?93cT&$~@S9~6H`+{}H~PyFv}R4v|V zpPja|gP3Hp$6D=fkTH@wZsi!hD8JC(-g*gzDu{mZgO+?A&g>7J8*vnW&;02YttrkB zr8>&TC&iT^3+%DPV_6fY3W!8trjG>>Cb``j0U+ckp#yY4U^C(K5IG7@>D(wEncS!r z;C1sLXH3ojRBg|m2FEb^lZL4?yl3yQwk|sQSEl{9&QyFd_W~$%lQfNmC$G8cr^6V2 z28$*72t&6Wx^MfU z^6T0;sGt9^f96e(#xE!UNTCAPjfo2*C0Vt z=G2sl*j3fd1%0QVkhmtV5C7<4!RKtIr%Bm}I&YDw`jR+uAD!8Ah z;PC{5#}f=5PbYXhotWf1O9X(BquloRQ=v-?fc{PcnBg9P8J+={p~wG&I?Pm{8b(0< zxKT}T7AlYUnQ(o@?^8xQf0O3cA8CyrM$QBE-B+&w>U=KYs*C-&z~^Ep{2J%?kF<=! z~-FQ7B zE^&{Lh31VHj|Z@+b56ONG{>rf7s*;cvaR7nJ}0U&-u!7Itk(=6UOCjz z5mje@z2nB=4|aHK>V4hP!#MHeaiu+ewQO^0kuL?g&d0}NZkULvc#ArpdX=O$aS7V* zw;bzcI@$Wqu=%Jhd&zs1az3{D@_9VW*d!gjg%kn_zohYND|3H~F8uT5Rr9oneNoQ} zisz>ZoHu0|E`q;rW-$FJGa#}vR>Tfh?_Pf?UYT{AAARU!sm=8T_m@i1qA|*u5f=oKMT1h6iIx>4qhdF0VM{abJGXW5TrEAht zKzIUT1B`&s$TQ6Fy>>a(<#*rje9Af03CniJbk`W$;;eR;i0iz)8N#GCWJRf8#e{Ue zJCl*gJqyZy?n9UJ+(&wpwJjD9ttFx16F|5E?|2vip^1SV#`S8ag>U)q$^qF-@-*|&Uy;HshFC+0X3TvoTmm^cP&+$Fq zEW<|;voTloSp1XQkZ~wwLDu5U*{_r1mlM%0BX4)QSJfrhri-SEsgfglZ#x*YbC0$U z<+BVjxyv=r0U$eroAY6A9cs|c?X-6@b8DRO;%TO8C6tBolY!>(oboJ+IhRCQRBKAG z!yEGg;Z@0kp?yrG%kiuvh2w)KDaHOm<{4z4(2Tn=KHccV9Av4n@pBN6d&iEAP6Y>r z^-!A%2%KbR=TxGSVMR%@T3T*P%gLJHV37a+iFAhbz$yxz(B^`Q$e>~$tYY<)YcF-; z?|}cKQo)meWOdQJ$i5;>9?4|gtUsBbP47(1`_T3@F!dU$*tsVHLX9N;lrdKzTMo5bj$&G`hs zrI<_GysM#ItyCrx?KvdKwfI7LP=R#e|MQu7GbUkjTht$@(;Q?0*rkwd4ea z+VQlx?;p_({2Hxb_3>?mNb!(x&^0H!?>?w}o$|_8iRz2C)?3ro(8`+vf__3Y$EM%aM{4IR(lRN%jQ_gjQ)w&2{#J~af7u6$%M1kRmU-{C+P*{SQB zAa1>qGJHcNif;4VgdveDjSt(%rpxuO(g9kXfM&17ntF<&>R4O6*-g`F*6nh-!P(CV zLh=1h30&rH(&XYp9=LnM`S^R^7VbJM?u`WG^RK)rsq(o@YDZ#HIr&A%S; z@*d9e%`8vsq_xjwJm$HYFtkrdoYy=GIyX2Qad3P7bfr4}>dV-qP2=9<%&3SEo)%h8 zzSXQrp%FXjhGo-(!%PaKNebk-H!l5%diN&Lzo>wHA%Z?9=(Xnw681Qe*QasNSi()B zHN5BuWe$|$!t?m>8|icsvjM^1r8+>-Ohm*U*Ae+<<6{8FUOiJW^kF&4*(`owcq4*; z8uCR(SpdiAF6ZbjAHmhLkwK?d{~vGf0Tsp4EsV|(hn%AX$$|t?5J7TAB!ftfB9e2? zpn!lND4-}oQ4u64AVZLxlq^vgV8}U2j;|U#=R4p1?tS-vYrXf@>eah?*G{#&!mgUC zp30fB`N*|kWaWLXUn4V(IokKJ2@K5~0@UtZD3gVMYMIO%c7Hdny>79=Pwh33zy8TQ zR7p;P+N?kQGKNr})rQ_mIji&^#Bnh%HqrLo06qVLt*$SWf3kl{t>|`Z#y9Dg&fPlg zHkA2`xL5seVvU>kga)hx-)1qzU>|q!-u2mT5pf<5Fc&#Gn4H{@(d(jp7tA4%Lu_w0 zx_qE697EFLVLBS{e0<(7_&D-qzN4#eu9mRTw&Ykqsei5lEMLKvPv!#IuyXgE2!4&y zVs!>OlXScLYLfUB;{Bu^zPU2GzgTI@){g9v>R*q%IC;_cFco z;29Je`Ajoo1{%k=p*L^)hD}sj^lQ{IDn*6Ld2I?M1&ECv&Mgp~E|ztDZHnQzIi~%6 z=4IN2PGk2^DLux;Spsa&Z|7Iv^P9ec*J|;DuL$O*Yb3)dJ2qyI&-Q_4WGsx(K($p- z_B#2O=Lz`{%k0)%EdHU_-*nO8M~JHy_$C{>CnSVNFmOyGlG@TJ%DWy2`ed}_QIyY? z(AL6FB_tkV{OW3ln z$*^slUA`pr-~GF3@qQ_{Chlg|jfac+ZS0VkoosiQ?YDRT^o(S0>A9GsnOE+PS3mP*>8zQ+p{iW0433_;$wPnas zDMrBv@lzJ#l=Amo+m{FBcIyZVL>zh(HGoWs%lDi@mzciQL|xo-EoUb#e?T_(KJi97 zEq_Lpz4Mh8J){rQ0DojXRinwx8g-v7v*os85h4^mq&Wp6GfqLD;XbQ z%D*tA<7r*cQF-<9V!^ojEbCyJ>SV%UQF7)Y!o+#Z6gF7-%tC^9w{^R7NzU#wcC8x8 zM}+I3do)f(O`Ri`Hux~3^ko89orQHmSN%#grpei#77=M0m)KANvUC##Y4zWwQOE_t zi2|c~yb9B+3+*l`r55915mWDvFJ?z-D}=kK;?toE((3Rk$EtowBbVIW!nQ78r^VfK z9J>Emlwa?6o$G69lBE>dSsL!zf}+ElbKkDlzAoD(tv9KuFPbyJF9`R$d+ZoCmiBqi z$k{A0Y-Y**Lt6*;!h#=3gR5!>&QrcocPg#t^{z2BaFnOn7ytXNDDBU1m%)zX)zJ>u z6+dS2#tvpv#9$UP+y4AuCpCje$|4)8NAqtXl9ne;>SWh#$>PM1A%hgu z$Js77nr7bf`4Jk79blHNDVd8~dMD&It^SnPNZ3iYyV48>X@tESNpOh0tHd)3XT;!y zpC*5oH~5t)o1=c)SLjM@M+-06>MO3BFjUdXTT-W1D@K?T7*u-8h2{)T5Eh@AGS&h* z%YM5JpbZz5ba zj%EsyQ?Bve)i^FR3w}Y6NW!>FJXp#{+?{m@4eX02uA{M!I{9dXdZ^-*QVMKIU(P>n zeygf4gi!NPnCf|VnLdKE;?2hVPbwl=3X>imkA=rLSwecm7r{yYdc*dz7NUPXR_SK6Y>wi6@!^>Ec@CRb98apL;;f#i6FnD| z!M)2Os$FHQH2+5R(+yZ5_W##}v#5@EY%$zu4GAc(Ep~)F6 zQR=vWRmq4=&wXsnk;!4+3aKhfLiL+(TF@noeuV0kit%+1Zf?=O`YQL|CrWHxUJgH* z%2*`{E_>+3>-w8mV065H?eX}x^2*?$#qo^Tny)0M{NpA{9VwBgH%?y~R>qm6ZoV%y z@NdNo+AcBf9T{00JK7$Nj9){Nb&{CTcvYuP4bgx5deMOB$feSQU5Y;_WpZ>|HQT>% zSb)qjz(lKI%}w%SKs4>YM<8ab_tWZPIXAPpY$KPiU3=M@l%Cm^f(U~!^P3!DnbG14 zcohNB7j0QJ{KELnSYa=JByG+goabz$D#+;Uv#);CtdWnRVCb8)b`L*l+~jxz7ka8I zA(J9NHoZ!w(oa!B)f#;(H$C&Uyt=&hHkL`XJn3HqSZeHg8r?IhSTagaWq+h7(~Jg1 zZ}qGI6YlKkWF3>sbkplA9|Cnm1qnNV$_Nz;WqKjsmYK04hGQrvIq+X7;J@I&$78*Q z6HUjqIuG(g3P5H>5HK6erh@mTCU?uE0uJ^jtSOx9o3JHcqxn^rSdR}fUaH@4xWGic zc720d+Mdi%wOcXbI(Z3IRvYJu1M~BqdlbQ5M9VVYv-sf<8tcy(-<3%p2kQ)}O;Qw7G%W0Bqi`SQ@4=5l`{2)8p$TojT zTlrU`ch3rEb-a_v2EuSc(ugCCz_ovHjvCJ5q3H>$?mdT@QZ1Y!N(aEMvv?D4A??39kcjH;k)uyv>S20zs}I@JE9Tytf1@bT%}|1js0kn81Io2I%%EX zFMK`dx&yp+ufBZQ-Ts!3^+T*z)GPd97PlX^@#0kYV$O#wTd{u<9@6Rf*ssfuNyQ#h zCYBusdK9nVc6WSbmc2avQ4?q&$pXH$0RZ?G0>HNr0KSEY{#)Pv+F_gjvH~gypzDWx zt9os*nCN%K4d=u0@#E*r^aUxisVf;y*f+eEFw1dP%YtXGG#%}B1y}N#;xx`5J4#iJ zlr@3sCWbh&*l?m?hL=!hm0~%{+p@_Rk%21KwWCF+rZ$4^A^!E|9#n-ueN+PVkpxs# zCQ#SJBS3w`0`-v;5W|H;mmet%f;x03LYBCp4`0l2a{IY1NnTCB=aCHxHohO80sE77 zBqX72)RH@OeO1KN#@E+tsZx$_V(^c6!;HPw5J-oy=qCU5SRV(Rl;iCeQP*9hkA%b9 zR_S3W9l{v={!2{AQA6*#l}>utw= zc}=Q%e`n6@WZZjgO|pArJ~D1oTX4Md?WkXcK(W_=>&=m{!6n1{g%u9RJWU;*CYAhm z2bhQ{0`?Drr$egDSgmz_xk-ILb^h&cb{d~DV)wkeqQIsn&#>1MHm_HpT4DyD*DGxE zxQbw8pTAVGcuD$$70D$rwMdzsTM>82x5Tt=cU&C4)&1a$z@=&-rhDKo%R0(lNpDrD z-3{-yxR4){)k|7LC-;FnC5LY6x-+rNg;FBPhusgdzgr7#iB)>vr)A2=-W?ut{KWj| zYnZ-Ds$f6up_ME`G#er2gjT^K2X7XI%n=Rpf?XRBiIFeY(SKzzGxHn@bo zfaS;)N|!%u!)$1F*B}4J~K*5x;VD4Q;ajz3`#jVDq`TMK+`YC=Is4CTUq>F1fegHNwOr3kxIFBLOn1aa z4BxW4jws=K{95XD#>ikBP(|5vGCd&k@H;5a>*p1l#=RUtykGY?(<(?xc0QH)6Kwdo zAlM@C@hC{X+t97>H8sjU<&oM=Qpe3hG8v<2y4O^xJ)!_4rS_c1AH^cF^P>K2VZ^Kt zv7%+)D6?o~l1izx&x7K9`yp4%;=vR{kX0(rVoE?c87I#&hM=6xZ;Ty-VuUBFuWNh0 zNolnPZHO~_b!^%1-ZNz^A6V!?KQ9GSn3m;xo<`lb@@~!E24FelFmjch*+0b($cO zcx~x45ht$m_IVZFS6%)c&L~m6hgl}nh_Ic=D?@a{&MF)T3Dq$yqxZB`gQ6A>voOh~ z%zL!56OFWpV|<$l4lWp5X+ry9Y^-?S&5)^ zbD{`N$GnSD*9$AT`>e#a0@_h2m#nF|t&=aYN43)en~`r*2(M1gbAWA2)@>|S_`ecc zGi9}@>2#xhl3(NDyYlubxstvjdj7{P$}j!zE%AThD1_i^slOo=xcW9F)iwEs->oO% zPtp^oie$s&S%86;G^5hlZEk;e?T$56VUXZxkx?3lczO&o6C5?Ma!4Jq@O$o9Hb48R z)B)aC0eD}fG~A7DOsF+!?wyT>Q|^aQBE>5+K7<6&C4*foiT~blpg|TQ0@wn zDXeLQ`V%zYnL@ir5u0Y>3UoKTx^^2ZWX`ipGmzF2VN^D~>V+f8cBgL4M5t$6;4&uB znwh>>tA}KI)4W10>{Mp!W=M*rN5#Kw+9u^Ih@5wkkmu?Sry1%XSiZyK0$YtebS1=) zzzSu0BTYiqFNZ&4>1B^u4%5#HLMgh!3lz7zAGyE_WVXATo#6!vD+4$H$Q>i&P#DGn zK+e2Hr*H_&+f?KJ-KaEmP1s>1Ws%;JGbVCj5349xxo3DQuxIYQd4AYdQG{K8u4hPP zP#ljkiR!C6`G&YiuwwTUIjS9d2R;txmd(49k7*pUWP#W9#!tD&;5Lb>1NFeUsn_SU zEke?chC{d1SnLDV)kEW15ccUPi_1T%_)mqsI?lU{SCTl&}q7 zVtHsTSoz>`QCh?C-J2kPovIHqni{%T5X;n9UNK1KrKm$!e59q{6^epLO2?)xb4md1 znwD*ZfaLp4M?O(@S3C31~g8S^S_*XWR`tn?>^ z0e*~3vj;! z-1r=TTOAm2FA*5Q0gPZ(0Y*FpVxl22%3sXCNGD=aY(E9u@ql|#nJHH3ZtL(l_@N9e zQ3SF~*fE{Ly@JaR8`f6Gf?EhH&B9!pnIcD9?tuy2ay~(F?dZgf{oe6>*UIfA-@$8Z z>zC6{oQ}~dad-SyddYoE8+Knx8V8qtJ()B^fdIJWWO(7t{l&pYGlTqsYmRjY(kHNq z|F~(R$u2U$>!F)0mN-TPoAeFn78RltvR=a{y%#e=#&@CTDzW&Rdu)c+q1&Snr4k4E zHbv+LTaQYPv;Fm7ZW^41I~irW!9K2syOsW8mS2y)3F`-EJR0FYPTX?yE-BCP^|mNY za6BF}Fb#K-nz_9e+}OMI?X9?AT{>LA9g9W-Y1kH;-^ukZ+Nd1&!sJF>Slg$|Fk?e) z7POENZsp|9Bz*XX?_wo$tF`=$>E5J6@2-%ol;14U5Lm^-I268}ZQC^(u2YHM?h`~r z!9DE0i}nbTG)Mo*=!GB9VHR4jDoAzhnqR(>UWPGMj`AaeL#UcqZ?qpi6D;WiTJ#Fl z*ZXz4L+O}00#wwuAFhaA+19o=M_BluBmSoN-w^O53xDFHkkcr^u)|9lAm{5Cjxo=W4;L!v;PiH*VMwaH^^F|DDcAytO{~`?L4G zyOyH+h@%R$aOn<>y~^^Jp3DJLv;LUAhrzy92f|my`ZKPq1g|wrGEC|(syHwDDi)^S zp9jpPRV3ak%+J4Tf@!FRAzqm zymYi!-_$$riXDNFan7D}OH6!fkt;n*e?#rsBlX`|n%4>@D;ICJz3mWNw8WcXo8L+> zyK03noa>{F7yv=G_5hKtvL93U?(nk&kqECu{}qMZVb#^`S6rUb^9Jav@3E>`JQ7k} z`%5=3`mIa{dLH_0C8`W8IT6T=sF*9}MOAl-8>)1Reb~JS{)zm(nn`|Czrf~VQPD{M z{bfgiC&pg4yu%iYZT#KMQ@#mRne99tx|i}myY*g**L3&24;Ie!RSuP=UvUL0mua82 znPzC>2gtq?!^p2~^IEzG;_Us)*yYPt2?;731YFauk`PoZZf&`DEK+#1lH5TsZiZ9I zv>XLRbPGz|g_m5${6t!!vws|wSvqZclMgxAIlW;;TA{me(e|?7+hUAsVqAi6-N~={ zJ*E5B80)^Hh>*DNEZ;4Yop4c0nUb3wpK_8bn(mnW%3J;NX9Ti&#%&KX|CcCRPuS+A zbij}h^H{}5bdhhTC%iGum4w(p6>-Cw8;(wW9ue{uJ-_zsZ4_*8{2n2`7QR0$-hE^W zwL>P}=?GFv>o>|IIvtto0P03rAlCnudD;pNO^qENN1nPL4vI*vbC`=69|w*sT zCuk*|)h|!AQ+e#2YgX;|OV@NkU271OT3pAp0Th}dx>O7n~xjp6{kHep)o!&Y<+R2H#W5Q zuwNG4-^LXgnv`NyW*JzcPK}vTA_g-ZFVue|2~V*lhVhGfVi~^?g(0o`$XrNi3#WU@ zT-v)%B!|>Q=P*J>Bl6z7Umz>0*V9VcLfoBd&g1sOa&Sp0zyrWluWw5nLp>c=;<`Qf zXBYp_jazn1@Ghk4V52w&F@~OeG!JXR`)*4bdAvhRv#Nr4Xjohg%zmQb(JsqlZ%8EV>@f z$LyqVFH7RrC${UP;SXX@V>OsnR~_t1o=oU_JFl(&3bwDfG&ye9`P_jZVSH!Z3~biB zxhwD@#(yvMmx!lxQ2$q`wcjhx)gAfusq`@KpeZ=Na$R)p@Fm?78|NLfBmLnokw+8V z&thHBiP(y@9|d$GY6WS$VCHEU?$q!RZZ3N=mxD)FN$<{3N@A!_z==XtscGS9xtUBp zA8TAt5}X6gOU}iM&WACGj|qDRb#Ti$avy)D6$55!FPz+<2)m(f&J6G;%O8DTHrGNxE&rLFHZpBnAYQm)2u(mA3x6@Ew14lBks8?Ml za@Ks^iehqbJ2u+T>pxlWw_fHqhN+`R>+q^>f-hgANACt|TKK8YU80=jwn(;Ra|q>+ zVqmAf%_5}PrG*|{xP+Y(cLT44?78#>EdYA`Nh`aw2zXP~bwV^wY_Y}|^J^>LQrWVJ z)g?)ZMPJ|4;*476pl-ka;^HQ+&!)2y&lQbmnKyB%-mwVL`r%8FJfx1?=gFnSb4@4!uqLrb+f^)3!y!o5sNkQ`2xiT(QpkY>KtX|~kO^pPQ7x~lS3 zKCDzwwS??z<7Ii`5fr0P^F9bYn8VlbKXo?76oWrEX z=~Wan7qpPfX}_Zhf7&rH4`Ve7z5a~KR!$UvB-;j6-gyq{SJ-3uvnv;YSaL_K=<9EQ zTQi9y@OV>+4MV8=ZUI+hW6zHo5|liBVi+>qt(ZyVh&8OtNGwC}zJWRi`*m$)?*oGF zN}VNn-3z8~;tbBNi=WLC?q0#Ksw`2HZ?z$}Wn(Odl|H4v8a90Cn3m-#Q_}ZHerW=F zw)ItyMU1W0{2n$N87m9N67Db%LyuMOuRcjjp%M6D>hZg9_+ia>r+er=c|(C3A*=9Kgg{xg-pF_2c=XlzIY1NPYKM0~qPtq}bk z495~+ujmSX(cGDwxY|m{R0r%~TOj949?OE{FO`xWV7axxXLHER`*le*YM^+aia}D9 z?p_#Fc}QIDVJFM$^BUw+Esp|(q(Q?lQXP=t3^aQJMPJDYt^@3^y0Jir=$rh7;8EFo9L zNne19{uP7ZD`XK~RpptKH$(zG&Aia12r7^=FD*92b!H1k8B`#=bBFU4nV(7dr=u9b z3q<;!&NeVRua#%lV@f|*M1Adm`?-Jq-Lx?1P+`R&IrKC*ERsYK&yK@Pw5yVNb@g;T z4{W2^R1sa_-l=l;GTj))lW`mlwIT=gOKg&5;m;t9tfdM0@$x~ivj zQ>|y23?TDlf^e*N5+w;N6s?!t}ZeD-8v$;6asXrNMC1mU$pi3G7A? zAC5fEwii)6EMoL6A+i7dUkM(40$C7M>2#0eCyw|X3%>uPWA2w+Uih%PHvUS8srZUq1(}+H6HqI58D^4dG6}qcwTsJ+*6LdmM>WNv4KB| zv20@v>JB@8k`TsX+3&@$+{f!yF0$57_=1(`{ec%=GG4WcJHU0bu6mWs0HZH#lNY|# zw4MWm5cwvsL;W2?p|87-^Rxs2+- zHb$@jAeF-IHx$MhGt1t?N>z54QvK_N2bF4dK}p3v+4!=Rcax4Ujuhk= zLrtGZEAjBRe+fs17TJ?q;S32c#uV8P(O3wOAtO&i22BV&50`bnz1RP|`)ehVyODp} zp7iE48l#a|bPo2}YQQ{W6uD41cD%83tR(ruek$DgHHSMh(}jU_?6-8C=>D(+9j6KB~TbUyvBOu;uEoGh6IHhGU< zI}x&S;vdeA-8UF=i23|$hi3U|dCf^bfAgK*YLXiB6tQLzGQ1ShZQUN2&A9PZ~BqP#%?b}s?x3}9Rk{K{V*_s0VKoz?5WI^j=o5Fk1SU~q>_W?UY11SkW z&iP^G5FPnB7xg(8**Vvl9iHDEV^=zky}g60@5R4wy!ZIw%>nTd8@Hy-jAH2#T6b54 z6TIt1^c|h?R0dM-Z07PCz^5`snS-`hosHWn$PAgYw$Ek*x8O zGwd}9-wzQ65KP-P0_H{6_e?@3h3h(ES<`3NXq2Gpf6r z%4D&Wa3v=0u&1o(RyKtz+E@&}XWVS(+|y54_gZwY*2aR5f@0&VIZqE`<4-z9qxa|f zkCLyPUY8sem=!tM=6U{Yf4BE-;CC{r{J!xbW+n;!e3xmvo^JdYPW>3xX-lmLV_y6O z`&EpKgD8dhB>PV^7YFYONEcjt3wMjF@ch2gIL}{xOs>#6qe{t=;@X2Kza694dhf1B z3Tkiq^vJ{8`*dQZ;q(WW^YiN4E#<54ykC|N?N4qQtUq9P4qp5|LRMcm-5dz!RgE=2 zC+|rdwyxPOU;PodY#U^G^QFDWQlgQ_Qc@ayv}F0mryzX!pA+92!_?yBGf;iXASwch ze?>L)(fsB4|70!&gEOFTz#6u-XFssMTx4#<*28r()VoZWJkU)Cq(%Npbdfs>LFt6M zMUeitU_iEdX5v;^x0nP%=M|hh4fRTluD zHIUe@Fs@)o6$l_+f|7v98CmdjK4Gva2fGlm1lxbt6Bzc%!qIpT2!z5K$W9QiK|*lP zbC)@WQ_n6)^7MPfHyTcV5~@!2>=n~r|AF~C>tBhlAQ}TD`T_zQ$SJ^WpkFdLHy!v4 z0U|*VCZBmI1qBrg#K=&wKAjf}iUpw}7=>bwfFeMV&6yba|0X&H8Hs@C-21>?=VGWG zprV4<7&7$S8b-G?t-V9A{W_SLi(BdHYJ|AD_Sb3G#4jB2NzeFvUu8RdpJKnK%EZMT z{PP~|6#LAR|CT`R&L1kH%^NDe5?fS$B>yK}yqL=V;!Z<`^V&FSQ;Ec(>XOC`UOn|e zFp|~2tJ*zTpUvkU_#ZTqX*}_h)!@4fSmP^_i0YBR$Jkb8gOax_SGkEF2AXswp(_JT zYeK1LYnb*^pTV6x4%Ct|bdjTNhXRJlFW@}4q z0HKQ0reKZ#@0AwswXRJ;&h+$=yYvci?iZvU2eh|R#EQdJnS8^T?bBg>%{R(6NM`YZ z*ypZO`iLl|qZ7Dj=dKTn*Ga9RaMGc)mv5M>)7uV;SoaH#>E^FSY=2`-p_(BnGLhn& zSm3AqCX}lYoXOfkIbkoskl_bn9SlNuex25e`tuTI4?Po~A7k0~b$Ey!V(hd)k zreAx}_`eG2V_%E?mQ#$UY!N*Y!DU$Zz4DmkV@yjoO_=zj>XK=}t#=&pSps~%gnZ8=b>OmVn5b^XXa|v{*2*>+P{PF)?l;dtevrbcw&vrqo#5bp60$ zCHb8wi04FANH!)l61(CM2RqV9Dfa4e>o-gGJZNX+5m(2 z#*I%LaFQ-DEaUoO#E|p&JgJYVrT-6ED38GBO7q-D)P))=<>d5kGt1 z+YAhtt0(@P!bdJIQr`8?HcDlbVHfreF9k2qn3+jssC~G_Hv?AxWM6~vciqP_PVXY6t)bf9Ck$x=R9zVB zyl`9w`o>pZ0jo8i58n5 zxbqxC!`O2kwUnCcJHKJ;2RH_VaUp}TuP_R3)L>y}D( z4w%dLSGEtkm;`c+k2{>b*J@@zxS=;suEB=T=z|l?+U?`}6(Av3i(fMdfiQpL@n8h9 z>h!=ofmH4yzB?rZ7QvqGCY{N$`T%CVc|!-3M!*fgwJKd&!;oBOLDgRo`|6W zqfk5yqfnmYT(WO{JS^s1S`TS*>YblHK)e#~k^{1-#Ur$vqA)xe^rtM)h_%bZM3y8d zCsHz(%_>-E8x9%VzVDq*X;hf=Lm9oNF$&ZjY+#KmK}0#13T~$M@eY>zf-w(9xd#tb zow1nS;~Wk;%uxNV-l6&8i%%-9}>1qcZtl^TW70-8>diRsG`(0_XiJ0D_klbz@?+1=px!ur$Ac0KW92T_7 zI>6-pV1*+$6+8EzrfH#n+SCKCh>+YX`1%U?^P#y{=!1_xgfQ8PTLH0dKx|x-3HawR zD$(H|8Khml9mjYZd3Fh&bxWt_ZkdiH{fvdxoR((GZ}K~4+|lHYrBF4Xcf_t09=59l z2?eMcKmb&OxA_R9ywM^0r6U%|#t%^~p#m$>m$90i72>{P0A_{SVwkvUEgW~y_A;!X z=MK#H%^3?E)bSKsduC%yFBlSM*$xPj*&zGm_?D3ZMnm4ejl51BB!r&tdni_TC`JI+HwflQySe?Bw zq(!5-x-2eCrV$~dce3$A8H3{I3|yLi=i;wibRji%75h|OEQI?6LytE`9~WNBlA^$d zzUONE#Dc|~BVpvr4O1GNbu>y06Ju_G4spY~Go%(rU!gVb+QlL&+O@kb9vG&K*7r$? zUy-!RnhQXSrcJz>3JJ6Vh}abMmN4Qke(8^x(p<@NSk;j{UpJCddEV6PeO4=LjHMBF zs&Yhf%>L{_^E2j4Q}s;dMyY2$78)kkeV9Vq=LiChG4n<2&3gF={D@J|oUy%}|Nd)#}W~%)O-alWgia z+d}FF_y(tFN0j(=on$h7&`>Osb1bRB!f`AOR&z{|>YNbU}uqIzhcl9GVZc zkvu=OJi2{uO*QK%qJREC^XGq(rus3NtErxeKZBLKPCn%ux?vNlnn&lo;DKP&QvmDG zw{*!|_2yN~#U&=1dvBqCa(6_PmkeO&*~aC`UI^tWsRMtMRqHd1A3KM|pU=4Zb68b( z;;hz!x{Dy6!VcYdQ~S=d(Pa2GhF&V3{zEMcJ=%wP^=Pu>S2m5Y_tz1s>enp!9f2Xu zZ*up3^`;aax$V9Be&wKn`MHbp7oUYsMjGk^dA?usM+qedOBqCL!ZA^)E2DG6+7baj zjyWR@8WNG+vkoiHcFJDmV<*CUzHKmAO-G7|aIFd3mzZRDK`nINyt=hc*yxEN z;S)MqRqK>j!zaica&wML5Nx~oYr_mUH5qIkROPw&aG9ENwZ$mIv^8EQ&Gh!a@8S9C zIp4HAyFPa?kU_IKg~s+<$B<|@O1cwsR|-MT_N!z>ts+ zWn#^Ze701(Jn&u&Rv>$f?C^jY$1P^50T8~J)!_~^jv3BZ10eFiHEjllJlj|#XD1oI zz|y~C5S4c8FyvV7mTR`%rI55oQeaQdvkB$Ws6eM5E|-)^mO|U~mSEmQJ0NYx_*h8h zKy9C>-Rahpm+Ar$b^z|Qx=zdhyr5}2leZx98LDk8j))z5<>4VBvru*ugU+bmgBrcoZ@JhaEgW zY|PJg@H}g;J=?+atgZHJ2hXz~wP!ncbT~14!$0RR1?_C@oa|JNWCZVTtgIZjh>UM4 zy?-V_+#lQa9_6eiIEY<%8lHQsq4HRKaN$ z&aYi&DpN5obMxn#PoF9MC`*Svc$imoSae77GN$X?wjWDPw>!TpHqzpo>9XV}&n}Ah z<48CExokkZ@f~XvxA-6}Y&HCai$rSwIOQ~r;)LH_(~CKyvCS*V#GaNx4x6d!5tRpN z&B*H+FW|_whOA(xRRhyB@*3D+q4DwwXK;A>P0sxbUf*Ui;eV>}onRv&JQu41-8FYd zznX1z63I4utxAK3QiG17)-V@U!TJUNbOFU11*24KTf0~TbJNxIcB@m(Q-uLyV!aMty2`@WrckY$T_YDy*Ps zWtP`TWDXk~&0JlJJ$#tvTH|tleur|1Z_?{GeN9buUj(Lc__&$#x-*0G#v$5K-4JdZ zxinb$>IjBp3SQmQCLwlFeM(o$r(gpUK`e9bUC#%pGRha*<)y8kx}XRB3BMc&OnK!2 zFo+H^j%f$Vw>2Tqa1PEk!d;&_%W?u$60t>!?H7e)vU_TfVFc0DA0w$>z>VXUvLFzC z4q`^~p{K}0SH7#5f0_?BNZr5oXa}WjjpGtt>-4Ub5Uq%cxBnx^3ChPGl!F-P%Zwm^ zvpZ!7Xu+;L2!NAb=dA=Hytdj>3ixsU+LmWzJuvkZDht?_cV^CF)|rHUIU`7dUD;Pa zE!G!5!g?)a>8yWw22w_k+hJ#VAzPBq5eFzk>w&p}f9C!%=Px2~Y^x6v<8ltLy?$d< zKL3mU|GA4kOQw-m&iREhb@@3?2UbAbj zC$CH$G>ibj?kSq2{=?q)?LZ6Swrr=*iw8mOC~d19Uy{`ihFI8)idWz5%zbcm89y-Q z>N|D3PQ(MlmmM({t>r6s3o&w=0rkg03xKleABV;wGk!^ugKEf8J7Oj@4;-pIqCS9X z9b}`SZcWpD9R`lHxu}EPm_=zcL;2G?aHsDpn1A++GpK&$j{6}@WP#?A zi?jQge7TInoJYK{T`eL5*y>yQFI(mD_N^E$%>4=2Xvtg_g4#e`Icn(OTpuvc6I8BgU58=-_$%4P+|4%gk#gJsC-OqpQ{Fj`6(l8Pk zc$IJVB-|6SrXw;?luKsx7P9^|^Fv84`3$-LK*ZWN=nx!aN-1LwLLTp}fQ5|8Z*#@7 zPg-BLlzM)@!?NTy5HNNcBjELG#iy!bQ`L0&%ScC|4f5k#%(nxKA{`<_de_~JpWh6C zp@ecqWKlnR;OIq^FC6`zn5V>W*Es1W_|8$E%)>iN>1oY*ounci%}uKf2MX1BtrJL< z`yKG7;=e5RA;4VuHZngJ1|F&`9n~< zejvl(YOdsgWQG{Kc~_$0Hrz$EAGelIj~P~`8wf*b{|gaVkmfe1ouDt0=?QGA_Ru2S)w9%x3uQs%gI!DjL68 zD!21C>0UkfF+5ipsQ3F-+2Qy>Kv^Lx56v#>DnX~|?RX;|dWV!s&#Kldpue@O9tqQY-Rp&*Y51EH)Vq+^~T?~WM>ISeu@{2p6j$Y7A6r#>2n@ZYrWcr$wK#o35R%stTC3 zdi$dYmyc^~;D}~r{}XRm%7Nr0l6p{X(I;}D?uIeR$0^2~^Y-D`=}#YGl-mw>YF#r9 zxq#&tg(1;c)w1H=yUSoxcEIOZk$jpgRxlc<3Ljj;9$a#L-S5mjIo+IYRQ>K?ZU2A| z+Xb^aIA>fN?4M5HugUMqAJ;xUTpB=d&(drg;iGwsNg!Z%6sT464pvZ?aT9tpJSx|L z9vjXd{X$1=Q1PR&!MJ_+ej!Hht1wZQy5;s2m)w^`3^SHK7<0p2s8(A{XKvwzfJ3K! zPC;P2@XHxJf(ENQmHTIX{mLw^%Qw(VXGR*FT^Ebe(EiownlNbpwV!NOS3Vad7%;Xq zH7Qg(A%!3s8p!3-xJ#&gY*!jIKVFoeR z?FL9>!CZt3A|Yn_b7rc5E{I#SEm2k290fN-!G{5d3VGRRot(pEX7kMDmq z=&ukG67bqpssJ!R!yt&vv?NNnDE&}7AVV*QxeSs7HiMs)sb9_?DpQ}+3RD$f%{Pbj^A9B_KA><;>oK=5vpOu^FXZ*gi*0?+1|85Fh4o{ zyY6h%*>jdk%^V=fo_U0c5(*-jT;#^>J1~|YQ;HQW_yHFV$y=Z75xYu_wyR3Ln-X%f zRyb^OlUXkGQ0gP;H_rS6<1hKtEpdC>i7SP)tGwOBztkU3;g`sLO`1e<7+|`5^wMS+ zoY+lq;A(P}IN@a(QE^4l1t%x0WP`6*%!k?m^jm2X-J9HxjFN-{`62FPYogkB!z!*I zS_y^NhzfAOyryg^MUJ+f2@ARn2?x=BF2M4Arw>sr{fDwLc6%6qzxv~e0c*7k)qk1+ z-V__8KJgPA2^2m7ZwfL4#8A>_0?kGKO`y!Vf;bEb&6R9rr?gKCt}lRo5WBRO0DbiR zn7zPQdR>y+kSwiAK}eR|aq0tL@_GA$6hS^v{epvr3I*9}lqekNq&BcsF8q&-elSk| zg9fTXfE*e)0TwiRFmL-y&Od7qr~LuyCD4JtI|TvyK{>SnFgIGt;W*04RkFc;C|T{bk|W$xh99 zV8!Vw__3#%!=e4>ZFE8rp6W#|(YCV*~`Zl4a~+ zFeeo(I7+y@m{xhW+*R$8IIXE?xe*t3xXV%-9y&LGl^LC!L<19fy-ZB1KNn9NVkBk; zHwN31U`~tK=!;HxvzVwpl{#4zc{}cTklMi84K6v-AwCc>uZx(3?FX(7JRtrlwXhHhFx}FO1{2(u;adq}9Tt99mTX+gA01b|3w+vN8t3&> z)%h@(WDs3Yk~H9k68gYjGu~NlZ=OBB{3^}nP>s}kyW>r9lYJb8%e3`Z<%_NdhbL2m-U-vpFe*SEZ4F2BtrA=Yq)LebATx#iTlidp0BhHfTtI z6o4TCQUJpL6~O)PLxK@-?qtw%n)(w7r+krlo%Wsg0!8lGeGkH()+i&^8ekc`myHhe9mP@A4uRo2+uA4 zHw0+uw}5iU;(rdOrI1kU3+F~_10%tJY6t+)IpA|DgPy=hQ3~7uW+?yhF$v@yikE<8BWlCf;l*;8rKN7_Ix6ROT5T zb$HfgyyTC>Z*e=W`9*ak{5*-U%!BmC+~)V=sbLd0X5=IB0r;Myr#w?_$7?)Nr-j=v zm*01BBaE8GU?`9^kxb?r=tQ>!b6JWK4@pZpL;zzheGiNP-OlrA$$Gx;foGG3Y00y` z&yD#{-v_3V!sR3`;nE~BnUNsiY24OKJcJEuAV+VxF;DQI;#C1i23*3R!vb7}C?|*> zcmx8VVsij+Ka>ejLu*u6{&9&YB_u~VSOft~`9NzPm?eTF)DHt1aL&vg5@SqqCZ-_r zB?|OBP&*p|=gibr|20VhHT&7$BBTl+NuaL(-&g{ou2(=eh;>BE%CMN#?{^F zbY>+IoWBQOa~>Uc`qe{xGFjiWXA&k=pj2B%cWEhXr~b!q@TzTOK1J(xEb*f>vCw53 zQx`BHL&A)oSBiqU7oNO~@oNnvChDgzF1mpETIDZchQV2W2H4=N6EV#Dm{xx%@UB#I zKbC7!Cuh_JtX+}7Sf!{7?zo|ngX+Ho4p4o3a&%FZL9v&WYd#u13R`W6w`7lO$>1o> z#6h1VDF!|ZqmMAcw}UzH=g1)6Wxns?!xn~>QTM@6Klw1B@W0du=d1#j5r#l?P?ID8 z0Icvp;5?43xCdr#nwTzN#wCbreTW+F4?`!HYNU1auSp%RKN;1_C-r1VEv*tupI;8N zTX{;gd-`L|`(9G6sn*cx&vCQ0++j!d7B#sdhQ@a!ovQT27rMPbKVkUYDj5IgChGln4#@5*XKN96Yd^b5O)~u6 zbsif#K3b?ejCWpLTa_BCp0Ui@vD|K2z1D8A@6eS`J%C;Ku~c9Xx$yF*@wMO%!?K!B zA8JeoC6P;2ZYIZg4Bj2B%gE%3=JryPf^_$tSLkG;ldZue@0Y|Q-WmipL9dAE0=B1U zT_{7|!W=jm960gr;?>^57{Dl!gs%V#ZoDMtxZLy2yrx>^XHEjYPhgTQp?F~-IU|{inEFRb9R6>?u%aIvM2Nd{vrI4_ zBK43rscNe`7$Ito;p4a|J5sQrSwaa6{$oJac8>@#biVi9y@dw$O3_80kO2$)a-b(4 z$}^Cf`GxexZRCdbPXZxR<@C9WMdV12Ztz3eFoCYZ6#&NoECTtH1j6YJCSv!hrBlEG zS$qL41s=h02KJe1O+Bp8jj%=^GVg_F#~3DJ;0K$@3OXGo%*)19+^5*Ntahk(Iv9jP zrb0;74}`SyKfy0H%G_5psd^@Il|`?BKbJ8V7Z4naT^rS=CiGaK1*UnLsxhOsv{u8| zK0SVhXoyXrut?a@<|K4qc!d|vw8c&J=p*Zg`ipwm#k%yMc3tO@{oMQthM8t z#VkbL&cdkWhJ}t=={0M@(c3o#;%b({9Sf?kYwbCfBE;i$OnINXyquc6yiRQezREr^ zHF{Vm`HHA2UBHg>KzHEc)LEFhAG3t)>K`8UlsMhwxUhDkFH4el7L$qhID}xSLl6ao2m**BfY^g5E&@adKw#Cs`ACZZ z6c8c|2qmn~`hEi-FjxR00#H!8T?*>5<)NOuD?~+T(W5IAp`=L?`Tv7h${fm2+5!T6t@9F2q5|(84yAZ zAZ`G}G$aE;r~`yJKx_fT1ccB42x)-8dZ>`ZLJ2I@1PFP6pnM2qPyz}qfKUbqc7Vu& z5ZVB7TeQ#p(|m@+@m7lwf6yeqSbDR@SM0*y!(Z>U7Han-8QI^N%;WGOFH2@=`MaZxEukYO@rBOm!TImiYzKU3sG{_Q)gyaI!4Jrr{f&xm4gn*RP(n~ie-7GD&fRsqR zv&i=s&o7?m_gwGw{_$QHGv~}XpL6Ei3*0+%X70IrqjtIq`-S(ppO`C`+f<&sR!g?E zcHdk>Ds|x1zOU*jNf!ar1Nb5iV&EloZ(K`WOkteE!XvO^vEr@urMznn(Xt@%p5L;b z@A~s-Cp>rr0k4e_QVg!FxnFP)`D-ZiorWO>9!gR<-g}P#{UX}pYtk4==DK72^tPBC?Mbrw}zdsWWcH#WoKkkW-jF& zd+J2NE*BROh(68;V=$NGsc%JSdZ}MOzV(7u8dG7`Fxm3h=Jjkwj9#R10zM5$@0G9e)O>PBtBhRTjPgd zv+=v1vsFrjbt3y$iqd)pCZKlFLsz0AJe<)y>oZan8k z4{}++#@4*rwS4|>88A{<*7x=s>-1Q6?D$)T0et;i>_C5?n`UWIy@$j)&<69*qF-Q) z>hTFEu>*#lW$;Wr$VCkhU}p&)I)9E}{!1c0X<*%HOn+V0PBw@9G$jIn*pvwHiJj8| zpV*X$#g6BAvaIiMi0Yx2@X`?rpS2UpR@i81VZZ6=r|;g!RW}zk8b-{83CP@oBK$N7 z|G18J9A$#GBq)3j)RgaO@_|SxmlFs>boOUSpgHhnsGsxXJiAF^B?S&zd$%&wqz|n4zB6|WS47(t&RZdXx6nlTKkOlX3aDUhKOyNnr@Tp$ul`g#(46Tpu zEotC}ke%0lBg6;+>+x?u>N3H4=hAG6zZB%NNvs{a14OSO+fu>d^i&yBK)|Uo4Bjvk zg3703OBW!Xr+Yt&Zc-QhL4EyE)g>XLXNDDFmv-x}1Q2GYzMy~>od0y=3Yw(a0<_xChgbtSb7@KB3^Smo;kSdm@S*=?>8>c0;lYl-YeOJ*=#Dm8nj;5hotcI zev((F#*ZjSL$O)O1m4!ucnrRTsPu8QUuPV#g4OsR1U4%B$K*yC@`#?~w&Tmr%gX1U zm`^gnKK6i{jpTDN(RC?1>38G^rH3}j1{O<+j{8sUw3JlpdmLHcQEVT!-Rm+e!!j%I+ZT(}G0X@1CN$BDW#-{0a z^z*}nAbA(Q*ZrP(VlAky{QdL+Y6&SL`vWYh?af|=kYW$caE8!hXEMtWF)$md8~}i! z>7E^|^7p9S9YSB9i09FY^OeF5Ow-B#P{3wxAEb>h4q}~w4&cwhY#b1fy~UD1Fz435 z$L6)May(mQ(uWfOM!P`{_MFlpQjZ;$e9K5HJtk zVuK8U)w>KuFeC++wS7M%8)`@AhmY8Th&?mFPl1kWXptg1AjM$1uf12EO#&_r8!$i4 z*WZ}~0Kbxrk4*nWkDXwZ0CM#=`JLy&%41Tk{w|U6Kx<-g5Xi8ZQpJJO+X5iiGzOM{ zc?6b#L|14w^mkA~#M|J90@sBYR;dUkbL!4u6*T)``~e6JBucRaY?;6kFp~_~`z3N$mqxP%-lb4IOiOE6*ja#LIY8L^*V4a(UZ?o!+E?(XF zo_M?@NhKM38n;Ox(nq@&HEx;vFXFvi#QU@69~p3O3%Ft8zsSEdFrPz#Lo6eBM@EqF zU)J__zvLyBUMfIsr8aJ*{-vHvq{U03njy){)^BQl2E8+Sd zxd@O$7ay?^CXk!3qqV9ngb>5s^Q>sNDy~2KFX+3i+{n$|N1blc(-p%w&_$eKLU7-@ z6Dq7d_l7qur1+wyVt4tCW~I=Fv-7FHotS{J@(-Cy^-;ZfNS=k`Haz!;;W0nt;z?xc#P6( zawys8Q>@IXy`wVH;PEk5@2C{*Y?PyIcwj>+mD3M7nC8st3z)x`5n4!lVa3dM$I+m& z`hNZ(Chu45O9Ofn$ufmC`aK^VE^->JY-Bp6PdJATCdk-UBJX_hvsgffo zB)wnigYnHCopI_W}u)1h(n$_X}0?Iq)3%bT6Ks9D0YliK}%A z932`-7J^NBsv`DQXR*iC+%0h(-T`S2a2!me>Pw)q>yT!H|9PSg*hpXl)|pgLN5kMm z9UWiIuTB%6OU@B_)bhKVRr^{9!wu+}bL1okeEt}+UWCU(5IA;{432A;5iD#!Vy6KDukG{(xx6O!`hUQ7+>%o`twZMZyr2~TRvU7ZxmhR~u z=S76P3$yR>)d+dtiC4di<^beVkY8#D4f0z49AIdFl@}bMQ{sx+jQrmxxHMdeV3;I3D)o?~LudSw|6Vq*)drCqIJw@lj1^t=BG>HU z#(_sz%cg%5&dq$X7B{F#!_@anBAco2FS~&HS?_`6m}C+}mQNmIS%Mm7{Yjfk9;2>> zECilCLW;N;~#|IRH!vme~W0GnU!XiRuuu=PXxV$71Y&WCe@CGK*LYmYD^NIF^~hVr&63 zhQ(l+AuI;V^kFerrU#3$0ZfO^i=0m}xg@&kOa{^d1BGvAHAt~c0bq_E045(WYgi@^ zFcVlN7cgB|<}+Zbu}ltNaVRa>hQ{5Y>P;3amC?>>Eo~WeJz(+9$?7%cY;cfKLmQNWem)d z%kBjw{ZcSKK`b02GL8{>z88`5B>gNeeg(ZgXt;Cqkk9w$oWl*@ddu+E{Ir1`@^aru zs$bE!zN<-n@V!oS^wR1?`&OQDX`hkU_1 zdmb7SE9Yj7j3Y5SX%$1JRVzmm6W{?xuY>ACwUZ&uL))^?D!$vxSB`I!TlcX{)b6iL z9FUjU&-?!R)i)yYuhrRn^z>*&OQ6PvZu>#Goq$Wl z_l@@t4$Q95_7D`bKPbuNH+Y@zRQ^*ZCjVeuI#xPMuIx=Hxbc*PYf%6WXIu*-t}w14 zFuAzgf3=qtE<3P^Ftp>LEu+vKSV9=)}o%SYZ-c)$bCE$e&VF5k$dI_5)PW3ZrZ#o#C@1vd{bae2`!3Be=hx<>R4d`<_ zK%O{8P4}k<7(Fx-fpJv>Fm_7(gB<3YGd}~4H5;}yO5&{C%c%Ii(sPubyl&N@i#VPf z8X9|+KZJu^7?pNn^oIuV?j!_$#AVE%b0R7ok?nI~&+WQ)2=jTs@PerwMQ$vo7XRX5 zCnO$cSWCgRE}d2iR=UFs7&54fULWdjBz|CkAAxu@I5mkLg@*K zx5eXVQk$Gw`?Z}HB0F`iMSAhf4dJUZH+aowZg5P`-1z_LrcO^t`&_es);%E_<+lM2 zCfQWLsKkUZE*sCZ4!j`#oOwu{rI02mfLLK6fdIk?AUjwH0f1b;NRUBP54=zUNC+14 z3_v&lMEoIuoC6Sb013fDr~xD!3wbVV@`djePP8)?LJS}ev0fSggbqO3v5*(Qix@T* zEQAz59I#%n5GDXw#zKMsL0J#Dn_pp!<5U$oMoahoPgc?8!FA_Af^C_47 zCgs4O9cv(XD?sV}{&A)2`qWfX+NUG4FO?iyBEzX1?FI?=M@l&1GGJsyZy5H~Ea9K{t;n7%ZzGi}( z?3h2!;>=BOiUPF~`w;y3Xf?H}y=J1nXF_ww6`Qo>s_+k!r1z##a%GN*;8_q3-LH+U z4_IINEi%SKQRz3%LkZZP)%z)c6t6?+YTP)cZr zL!M61mE^O7$?{zv5hKh+y;+pj^SL&+a#O80IGTk&qBk8|K3yircr?#FJ0D)?NT%G> zuGZW!ot<(jLCmV3VhWU^e^Z`Tz5O;fX+7%4pAR2bG1|z8=m5WDE>C__9XvYT^;fYC zTGvnAFu4vg#)Z612GL+XgHyJ6vC$k(&Y-lg*5eKxssZn?{>o>&-~SoSI{#S={@Es{ zG5nz|blNv^^V4ta9?e<22<`j7H9V&p>2bGHzl`5|m4SaE#?M3|I^6+TdeT@t9|*+B zgy*jUZl@I!?Z`q$8gR+j*ub%3pA$e7|6D*PM8~^`di-w?|GkfYK>QP@%nu(vnrFNi zQ6TjDm!S_Ldf}3i;%VU%M@<7sj79Qjg@gP-|6tg`NM@}AVY|L&6A?ltOF}bkI9lSz=3$VcD#w;dNR)Gt8g^t(I7x5mXs{{1T$Cuc5B+iu`9_?M<1=<1%V{iUD3I{BGFrI5OQ z!{*k8iYD>Cv<2?eoW>o!m0=JI{M^eG=zB`9XkylfvL>Pd_Kr*(Hj-GRK%k7do|J&t z)&iIAbvq9T@@r>&JRG-t35vdf#gWblSJyj$E+xxxf5aJ1BfnzZLEV+}5O7PZyHeoZ6^Xbk%EOCZpP_9M4t9~M7RQt2fc=}ob|fKe%7n^v!jbx4ey_t>DgUdA_TS{ zuL<^+=jOOm8)gxVv>@gNU0FwLSER<1TrHXBI=!XBG=*7H`i0ihly6&HyuKfahlbyl@g)aAgfc zl4pR)Gl26MpegKkP(u=DfYCF6*`G1|2@pR647MT)vDdBrXAA%k9(yQ?{g61%z`9~l z;~A-&YU}p3m9sr3`HTL0oMB3++xD5yRfY|<^bd-qJ@R4hy_JW4zVYhvcJYz@1jM(F zUVRXtmKpU7-%Yx`VYx0n>d9R9v3k*R-5ob#Hwkc1<>pN(A-dLC)Zd9I|IP-35=ZSF zuf==%WQ2;+GVM-R#~E)Z*?y|M==~$>)EPnQ%Jj}~a z95Qam9r^j;Fh4JfHu2i2^-0qd>mSd({vu02E@9O7*P$Y5D266EGL}h{YAPo)EmBD! zlNYj)5EQ`<-Ec3b&Fofb4vt`D-#7}rxS{Ta-&ZnuSuk!5sy*6 zx+3VKwH8U1$;soL$E}s|f-drNvV5%|dy6VIz1Wg774GBiZlvGvAv(Z$CT1mBB&)jvIXnp`4b7o)obkCd+w&vl9Fx z)^qkBy_Z+rJSu;=Zg5n9J+h3eX>W)Argr`tt09cQay%7(nRUWdIQ3;w7Ikr26A#w~ zV_DjQs-OW4+`RWCfD`Xy z+yqw?g`Pe2A>pu1U*V;KkstVk!*=%KgxI6m#?lxGS4*p)u-!3BV#3ujz$KME!^Ks- zLWSqw;F5;}QxNTw5E2vR5B%`q$+=ggDr2bO{$f%R6_pMXOPf*r!B$8D$%};yTl5#4 zTd1$-Vp5ye{&939Dym~B&OU#?58s|JT%=Eosr$NGOe(XO^?>jqeNw5vQU(rGp%3d> z7I@x#GWCYT%hziZ--xF2sPUQa$}3r)aq_$nJ<(mFD(V0Q_bomo_13FJgM~{->L=(X zT(78Cjlb@Ejz+)MV|lsrT2CGtfo+58oEyjB?ML1mgK8-DLb>xR?1ersW-Nr|r8Be4 z`4#!2#$TECwYA>9d(-UlR~kk`y@YtiEe1&JCkdEnbfZ@Tw0!m9O9#2!NZ*o`-)N zotikF7yFcZs3_@Mg;$bEk1kqxG~^phl6>;iph|@(dxeH+C1k(qBFv~`urQ=h?2)Hy z%uAdT4&HBX5seZ|{c?U23o~nv$oR6_qxZrU;(K3uwy2>0h-Yb_pp~=@>Yym-xJ^b` zU|2*#??@3lkN>G&`rPn2ln>pSsJ}@vSTS&$M1dD$;q(LqY&yPzKq5?WXD>pb%q@gO zZj9`g(GIUt{91$qVEpp7s;&mu6!;|^1g2P}_T$ai4lO;^jdXL4b z8PUPBP|=PyNQsL?A7*BI#W^>ec4cKWSAL3qMY;O0^QrnSUsTSZrL>`-NAO%WV}H`s zS{D@&J`=>f%I@oHa&EXdw}lY@s)~d~n4k&q!?6_`nv#UE4t0VtLHDgsdAT|H9=y!2 zaS8ualh<&SS)eIqc_pYs_vC9RJSpLYl+0)6`P5qnugTnsS+1acmv-5e$oC?TJ`$AX z1YZ87b(OmRxb5wT{5Y{nN2;H3)nWem7sg4~Nry3Yf<|(@>OY&9HIsAj;QVNM=;@mQ zOUmz!ZI`=S59ZAy1zam2NOy}D2yeR(9K=>L$#i$QKR&AKK;#*NV?426e3==ccI0?Nml6Xp*df{$j54QC;<>lDt{C3$Np zz$71Y5g#8Mcu>D=-4fiY-VF{vb;SHD@>z#ze*9y?0U`50Bgcy|PVxuaEoJs`ty|GS zwS7Z)qXu*C{C}vd={fU!ogB2%9+LA^|JdeXt6VK`N8QR)kZW+|gohwn(|K)YbYlKQ z#6eRQfm~L~-QAmCFf)p$eknFEh{Z#yIVrI|p>|-`MZYrgw^Qu>kDt$9L7_!INfr&+CI%p{H z+{}7ZePNPmquf%9#z-}(lLN`6G=)3F!6MmEBAt})U@Fsid&(+|()9=0K*_-n;t9iQlSXWXdJPHwM<3pwJ`g9v;yk$R9c+T!9k zl|Kk`2-1?ijxcO!QSh1*@Aq+f5fSvWadzgR*G$QZC(FzOp9zgFV%M7Rsg}aI=b=Gb zn>U&iKD!BD+uLbequTt+JD98cIeu}^fyed3t^=Rz^sYm;%k<2{)@Xi0j2Kt_{hl)6 zCpJSpd?;$}i-mXN8t(lj7&1gXHCzhv?Z4_CF8or#4mw8IG$fB=<#MqiNp8p=n;9m9RK; z^ST+2&q2%y^YX`=or(7SSxC3wtJJjQ>KUmRa&NC1_02I)MVZDKo8|q%#m3HoHoZ+f z`=1sc$`0+fVoq#*LhfS9+*?{Ik{?A?>K?>II8SY^3)RdfKd)Ido!ImG?Ag;&0mwm0 za1i*pPDzf#LjGZTh+pim;$^c~qj`w9Rl0B{`u0ssIH00`)3?vVixBv=nvKr#Tx1Aq?z z9FaJ1?$OQM!-zJ%?X&pDZYErBREFc~LBmuw<044yS40y1^#$XOS zbOFG701yWND*zY(fJ^{T#l`>tbXdSU5Tqyw(i{M~03eobrq|<~&^uOv+*n8iKr;h0 zpE;YPL8n~J(em;35Ab$7>ezSXmTOm#oy|CTUTu7a=09l}B?XFBYEvpYeWnD8X0JKE zW14#1vHCL{Zr-K*H;dAUetV>kA*b>oRS8$=3UdA@n zJX4iDaBbVAc&qC*NYJ2fsdaZaS>6ftHJxhOpNh9ztGxL3;kAACUZ^fr!E)uNn$YD+3gm#Rx;O1<6>MXzN?mgptN=8?T%2?AU(F17^zDWlrbD(%X&cKwY?^KKBLK4Q~e{wFI-+ zcV*bHVFdF>1S{=CU47KTej4EL#+mxsZ}nREZ*|$3di6|w6_)oMoY(zr`FGpp>Th`1 z89ez6zHp|N{;gIyQ%9VsXU^18Fzm$!lb)%4&(xD=YRTW$U17gtu|HFfo~b3y`aV+| zv!flc7dm*R7H0$hsa2uiqgj3O`=c?SSF|e?^Z79|zcQvPKi(eGyh&a@{gupGY4-B6 z^DKG6u1S2La8J6ayuRM7PRr=dU0IJ}1ljQB@DH5vUoCPTZxV5Y*~?@u`dRGcjt~$; zThqjQBhGQ-!`maz6;P>B@V#YaFW^93FVK4N3Kaz-sMDYmfhnD5#8onDCFFa8I0Mw5 z0fI;gT|j89L_v6UoS{&W(DPX0Y?ifD4-2!8lW7lFHJ7B zwwa`~f_5utw*h?{&;yzVC`UVJw}UpIX@GKcfOZFH1DXaXM<-}^f;OOOfO2#}3oduD z7JLFFtqZiffxa8)0ZjvxqX)EmKpW6BKsmmG_E*pbG!0OWZ=n4Rv;j>6l%p5;>jnNm zN$UmeKA`UddO*_v<>&|Pe$WOq4N#5&&>jG7K+^!_7zFJ>&;~ROP>vzsZwUAUC2a__ zhkfIjrGb_OaWzIS|Jw3hFqIF}sezYDF|Tw7MYM$I zbXfX!YIn>Nq&N!pS!~PpJ9MD@i!tTwspQGlxrF@HjQ18sv;Y$6wdk4{STk#rQ z#E7WQYSrVzOSC<_G=gay*YL;=yOr$7e!L2LT+fAS>!!Sn*mgpM(jGC!7*tt)N25#w zMk1Oa_~X2GH@vIPy*6o5X_bu53ahN#=W@S#5%ILcVQ84wZrilJn1PgX+XZx$P>dz9@|z$s8eQvHAY<(RIJ{ZXpVpH7?W31^smR z0htqz>4{dG4W@Z`E)CCT!l2#hq)HpAIJ8zLJ@1qr#dnj!clS;bDjuWK{fVIh~n(pM<&aP|Xh;y_A?1;%rR8nQCk5KzKap3%=yChP+P))Q1 zKQj*I2R98)_%(0%Q8$i;KxSdI$?=od*3TKJE+&Y8D2xeBk} zV=J0RjYy;X_?f6V-`>5csA{I6uI~8mrq&xcSCJd%yEgD*d;6t?F8GlQE=FAa8*gf= z1Y*C09vO+2zkx%09?pQILfE3C>Pq~TY|(6f);O`SJW@E(Px7y*c|k#paqUmnwFwa? z>-Ct?O0%}yY6GkF7`(DwyR2#h0c44*(%OXMxx7>9&ht;Fl=HVXW_+|Veb-Lk@vo*d z0*$A#KW$6pf2`?*wKvvdS~6qH^6iYh zJ$--Sm)XB-4;spAW|i;hIWeHsS=0{q4mS8=6IDw-#IK)suJ7EcQ$Rn3i7%&pEq+h} zs~L)wVQ#n1Hrnb7-Nx`h!{-Sc!qsO7jJUBJSD6+xUvP!F} zW1(K>4M$6Li4%z3FgJ?vV@;D~yx|<<)UKK}M{`TJmxeDkb;%9!Aa&}TiSjfN26$yE z3-GKsyRNQ$NQWt9*@gDEl#;bDp>a9dmJ8#DL?}e{eY`N_KDFO8{s$d8hb>-61Jg4N zGnC4CyAFiu(N$XV+B6^U6rx$BqY743x=$j6mQr_Ek)c4zWZ_k4NQa+6O->!(tO#25 z+d#^9BngtR92XQ4~#cz&#C?$SZ+A1oia|lW&I)u8@xq|eMkFG49 zH@SVgNu!4o?Cf?^x*iL0-HtKhslY`J-BipECdz+Flph?DqFlWjDuAuxp_585>BFw&_G7$dq;&H&FLP-9hb0^aCcl>*eWNn?&?d{VZ1KD^H<@~;XvTL_|67rvp6^H| z3`ZcDXy{pxa}F;){DC1Qx_3DQ8mps=tLNyo>dQl6()Oe9BriGf3z-cQhB1E6?)ZVq7-;K0OwOKuax9cHI;u5z%Ubim7cb^wnrkRJ2ODX=uv*vYTT3 zN}fZ0d2{s){lOgAYne24NwqhTRq8U0{T(h@BF4(gc=!nwmmRL<+x~2_R#|>^(?1Nx zn1g8(4Yz$zvEtGhe_QQGohC#2e4TD>89GL)(A(lOZRqO-(-5Jdm)!n~($8??teT?h zUPKV((W>DaJlsT88`v}ldVO$WB7nwJZ2p1Zy@>}?THqs$>C`7w-kEJ1inD5U3hdIS zP=0W!>!xq?PcCRIrpdAS+KsayS96PRk&P!KORFBwMhDRKnuA z&_LWGetglTxaH2@Zb}w@yYbli?WXI@9D_A~j!Km#_Rrdtp;O*j{EegE{*7bu_}vYS z?C)+O&bqmK)=m2FZmjx#ceAsEHOF0`-}!BxcxJA1W}bg$u775pduBd#X1;RP`|erq zp4i^~%VW;Wd(O($zc^hzzxp6lR6RjmR6Tb< zXua#+a=i6??4qyj;C$@E?ayO2?F{4;&l{zTExlkabBuLA!P8M6xa_tmG@bSr!pCtX zF*mGk+1j*rb?K=_$Xj7P(0y?%>?xVAc1pe`e@K`&ZJ{y-f7F7o4Yvqjm}uyiQC#`? zu4&M0=?%KnJw>W6OoW)awsh8lxMh)9(qMR@LiWWN?_k%KXsB)8s44P#p`E`&G&d&F z>eWRIDz1%vNZd;X3IEc9AY~!XN_!g;q}SWtm8b%aRj-haZGTOdH@jD8z3+DC`4=r2 zWO%Y{((>bSx9`*|gIK2rQrc}A2g7(iESYTj0?aRD*aFeb^!m&DF;1~|w&fz5S=rdSpn0}Tt>lsczua7^z5I}-IZuCy?3%)D;#=c2U zl0%FAf?h?N?SfYMUE2i-GUdzwDINFsiF}9}3L{DzxkV(%@Mz|j6I1?JB&ka$x^cm^ z)mZdkJa2mayrGvtdY-~(QSp95wwQO0_D>2s-^A-M=O~w7nJ8?3<7tIZ%y`K#rIS_0 zoYySoaP62sfLB;$Jjr*|i8|xu%02_GuE~2ONNs9)Kbav5aZ71eVwa4GbyV}rs}OS_ zJ)x!zRVvRPshQ&-w7YwkVmvD95|WesI^yG1g(mytvG1beagpe5$?R0P%uVe#p+T2J zH1>kzbC-Cu3FfzVQ)ZcRx)nFtM!2xsZRr z4Ajhhj0=-KEBKtAvOV$X#USg;*X3 zIr9^C7ILlUTf$>3`_3PUfa>UuUM72Nj=h}u7CRF;+q(l^>QUX7Et zfN^ZZFg9(o`GfKr128s}dt{33x#RY#HR#z9^o%tYU@6R@M3h$mW01YkF7;|m0>(S% zOD&}xo>V`})mMdQo9_pchOw1hq@OyhrIq(_-di{}&?*{dwDCk7wf9RYpF7SnA7O&K z%H4VsVS1z^CLV5EKr8ajru`KG`6tB#dYSoLK3$STo3LvEuCSnlOX9dv8|h867kVRe zk+T<~m~37Xz~FD$Vz;=5De*}^ig#{tfA?98u@k><6A2I69U&N54K&2$cKI2qW}UYf z&uAf&7ykIcBj^@4$H-@&(i`W|#zG+t>Zi5FX|0K^1DA6=|+?K$~5*G8VpT^2V!}edkB;*z9nmY^QnC7>&%ix&S zwzWUPZx%{d-80sc!kHDc{Ldo|a=OzYeNoxOTSRks;Y+BgnJEyN2JvjoLVZonqd@ zcyE1+zy8`(42N8G?IDu2UZN-FF{<{G``xg+C!B3cR?5Ew?;1G{{iNj(ET`MkWHeCn z_pQ6^asE)?_BSQWxqqKiHi z@&cxaFrjwgG9p<_7k^dLF${K)RxW~0ff7u5=@hw$TXXw?m00sNt3eDA5=#J|_isdG zf!2c<*T@pjebI!XF~$mn<>1{)p;8qQX=f8ML*IEN3opp-$|2sb-fx4SE3~94$#<*b z7+L&sl&NtS?Q%%;vK5}A$L-!iG6_r+{B5H{bO<-%l9qsW%S<_QxGX{V9+7ly z8Gg{YPQzKbG--Ykx41FbYG6>>?eiw`Z|9`Jq$xfPYyp215Yk+6FM~O zUrI#@n8Ch3<#3nZEeyW@I=ndH>r$l*&8HE9*iBgyw^4V~CRXTfdEhmi-SVU;NDv&| z?x&C>cHOUN$R9>te&30O@n`IORCpRqeg?bsRSn3{)5j{e2cOPSBd`SUM$rF8l-Kuq zuS~G!+R;y3nraTOT%h3q6@kp-K#I_@h0lQST;e~ae2f7 z$#8}Up`XRKyb*$)RKp^20oEqJP|MqX>5%~@cZ(H33H%Qzj)^+3!IuBb?qA_A)csK$ z4a&dL|EKc*+wuLs^JnxBn#u%IN@c=TN=+mbNS#>A8Im`t%d;jkm)+xe^>J?PF+%oZ zQ2$Tst1kPxNjK~4-oK{y+>gt#pyF=Wj^5LtST)D=wR|+P$S^$;t;{j20Si`}6AuOj zbYs~bt3P(XGAjPFtuG>kUV1t6zhr`_L+(*X%BRM(u-S3zg;7e%f4FFuY&(N1DW7sN zuSdWkAU;`*M3QjgB|s%z#6*%FAB@)#u9OPW2*B1V^e%pCtdBJFU@H^~eSV|Zv@lX? zmW@UP%|>$`lz&gJU!Ydx8^;lBsyE!w;Nw6k@;wHH0~HegF`}+-@}?>wOaZ)a$lqMyzV+HQ|Cmp>W$>+$#cdoeLNt}n7c}J2x>|O=<9h-_>;NDLtIwd=j>5vi6fd5qNV*0M68>Ihr5=*A%t3-#4vLhsF}TsQFm4FmAh* zxGOHXvVxDQxKge;?^V=i#=bWu;hs+SWBZad>~;+o!mf1=GHKTGRDXIrvh7?|X!z0` zX7+&_{HgNdt&I%x$sexG58fW(byckpPL6hZp3589D)I0EM~?mHq*iC=aAE}h9z^bP2JH*&$ixN!*t6?jKknJD+f&DZ6;ef6SYb2w5pm5)P+F+3tG zj^CJ(7`gO%@D(>ae66%a?rzJA?b(Y0)^R0G#k@DS+n;4@n(Hb!igV~H{D_I~AC8&6 zB^(nP);RIFSJw4=d{ZPm4x?e>zDCX zpmMux#ZO7DpKCVrA-LqG3{_!_URmmZn$FK*CF^cs$jCTDZ zw43NM9`ld*VL2&j!#TePfzf@60uK!Xi(vQsReXZDQ2NkxltisDCHk|Uh6z|PajZZ% z$oT3|qJQW&`E|HbLj|U^NkAs(`OwYhx;GWS@)_OdGukhHgqk0-Vv+GR5Eg$&%0j)> zLX9KgrFB@(qXAo`GVnNl%!bNk<5{rhf{kBEeROQehN?E-^k|xKZ;D}-sZC$(;lhU- zblc|KIft;7)&*Q$$voUvx(sh9#;Ig}9INa?k2>a+CX5AGca)Dh+TnH6FHafOR`n{R zI@6vA?L=A@^)xZPQuDo8+;=m%L#)&7*HoVB_ukCt%)$JcS%@1S328K!)n47YS%>si z9#?jsc<{v2sY~2HUDR1piDG_n?b}{NOwB!P#+7pUf~LurbdM8;CSe%n;ER(#IP;IF z?64f?1sWVX>d>LGkfzY0qPvLL+wk>3YqMpNyti2;BF@DB8&a!bw!D~mFgB!DU@Y!9 zDdCOj9B*|mTPn&@Nw)4=e7aG33+fM;(QS9)yi*ZBQok|u_Ii(IwO4voSfDtfUR zHe`8*31#Tfrt*b$>%6Lkb~;4Y+ab6+wvxulEC2DHHy>MBpu}~JoaRp}666_n$|~;= z6A#|_Y+w6=slM}}hW60@5459yyety2CfM{YP?%-I^KG)Wv*m;o$7>ib?tJ!!_Vaum zFYW0ZB4h2J+4Z{AHGdIBqy8ek?Uz%(cg*XxmuWv$g_;*ilrLU;FlilB?mMs#S3ZGX z-QCi-D*BkkL5{|Y=3N^-I2cQ-aEMyya(-R(`ZvT>ar2g8nDQMmBO*q(raW7!nwC8c z>hyevFC)F#mQU}BqO(fqpFnL7<`OMXa@tz=O_Hm&NTfJ&6JSADkwW%^4=5bLC%Pwg zJL^Q~Y>cjRZT5jKN_!%I*++XX-!G@ac;F}-V+=i2XiwC_^011WiikSx3E%aBBk+>@ z>PHjKM|HNv-twJ;hAU(eOFKEHwQi1CK9XC75=;i&$N9XQl_QHZ-y+duTVAhZ^TI>} z<3p#+hiEs{DbWr65$3N$DT1!tCU%lfXA35;+0*#E$luvln3E)r{__0u9-m;ml;}0$ z+*wY$-Ey6}672d+V!#*=(hMf#;GIq*7i@qJxiBsQi9^Ti*W#9So^T?~4h8Gp{@S}_ z_wHB;(XnkjJzQU%a6A?wYpAoAr2mjQz=AZ1S_cNF(!mGi-%{{TnL5O0l&>dq_hGfj zk?Von3y`|{HI{U25VSqWT5W(}>IIx#o%0=grrt`tA=YZ=JL@#?zbFrQNtcdhFfF`X zi!M@6j~)=N&C+Ty_Ih%aflUat!CV%x0@FYAQX-p@PI9^%>^tUGzwmm}uHrGB^G{DY z(N*p??<1nevJ^5L?$MAj8Rl3hwu1CjN1fa7%-X*7I;oth{X-jj+=D6?kF?h~-X*0r zWp-uNrX362Qp#(kZB3fPUk;=WRb!W z|AzRapAXN>WKr8I2yS4qaXRkdah2vA{KfIBV*0D9ulejFpI_5Y3*sFglv1uO#s~J4 z;fTKU?|K`^;=4apL?)SC6dG8$lP=9tMKROOZHo`H)wayJevNwc$=6(>2_m9vH))G% z&Auk46e>L3Jkb1Z)LQ+=)51edOTov+mnx9QSDtPjiGF`{NJ}R0UF*Kk+}w!I_3Kgd z0`oqouxv(MLXo*jam`PcMvo=YPdQ(>S=aK({jnF$IyDw+U{=Jo7#PcDbkd0nOI*k3 z(pIJv`S~~(idLA-d`dCk3KyxkFhlt98Y?OBH(94^m%q!&ez;O>VMlZ~k9wl}j@EK2t>i!NDx8C_1r7MO^d zo-+~>F^qZj98HiJG03y7I5HsF=IEzD%*1|-+02~p8uEPsdj0&s_;sa zXAeE!TW$qJmMRxY!$AaBt?UA~q=%m2OnJDwZ%3C|CvF*)@P%=W24zGj{0?HJsz`+U zUKH`SVLWw#o9L@|a>+Et0#+`ST)ksU?6VixPecA(rF!@0{mWJl%TDqPYZ82r2TPt( z+8OlhE_DMJ)x#)HD-t9YwhDmin%)$@rG>48&{nTLH3wrWLVS1_rSE0a#tC`5 zhf~f@2#kq@3WJ5(Guh$euNk*q8Tx)J-s~GLE@Z;1>_@eyXM|lk**c)zd&Db$eGzVW zE;;#aN5ZA{XH9nZa~4b?2^H6!sgO?tAEBZ{uDSd$Mcry`WG_%zx$dtd`N^CG?qZ|h z7s_=Hl=gp115f8DA*ZMc@+5I}n2dEQF0#1VqLY%#{>e0Ew`J?)&2_L!_Fz~6A?!#2(KKNK6pXZl@B|f?sa(uogsbCXUD#ibRLinrz7F+&j`2P;~KlR6k zv`m$s@;+*Cbrtk&toT&8cw+PPo6t&Xu6*%_PyXiWy1U!o(n1Bq`t78OkErLrD%<{0 zQIh5mZ?Lhl|G6AVg&JVhXNnqNb;pBa3E*}AJ5g05 zFhAV;orhG2%V*qkiDp7|CO0fE&&m2@&Xn56oV~i+ZROS$^KT%u^KYP_{8Q>0^69&H zD7W*s(H(UWbZWwRu+kec^(^8`#rYiG!iw`?*nuTEyp(~b3?9OnQ%CoaGbbD38>{`g zT7I6`Be90MJhRq1K6>HOu6_BT;?G$@#Y>IZcn>pRyu0fdJ3EGNHJX#s7m(87ztcz zj~f^uzw=R(yM*MGsv!e>=0RSXDsEE$ms`6QcBrTaFHqk&+r_Iwtw*-0kV<%mR8q_R zOn4ZlYiju8#PmF{gYoWYsOR^(Y^^@=VHx}$ zxqGtk;B#*J0KH-EHzmw^9sN;^ImC5kvKu|QmDkl>^2ElLz7lsRqp;-3Dh+&XWFV>9 zIa$ZkrNqL%ZXn5UZNvakVxjA~d#1yyHSpYxJ=w>MRUTB@7o^w`e6X-_s7tJ!hZn8V z@m{u4(O|oxxaQptnXL}oNDgl(_Rw+7_INlzoMUu(`T30&T8G*$k7*yHkN5nn&qcZ~ zK-AWp0euKb8s&jvs)e-972NaFhJ8M7@)nYVtH+7rf$IDzLgOcJqH2?C+_zZLPQ(dZ zkIl)gkMf)lRx8)hjL`mqYoOocu$nOfZc17p&?u?x1}(5e$ZUE&dlz?)K>o&93L@W^VR zrKN>)1h3bvPU8itFT)m}jM35X8Z=3Qf8>d%oPaLVJ*bqdKzVqf%XtfB6R^KTaENQC zTFkqd(yTN6yT(g-Jj@S1VVI2U07>SrVsDy`mrBC66s76^hqLzpi=x@qg~=ci6_AX8 zl7j@vK}0}BK!SpR2I}RgD0bIe)G{Q{EG$elV)HWzZ{~b zLy-Z6W-8WoJ*{lY=)6wlhEv{dwEEglJSs$A6M+_BHOod<8;4v+I%lsi$K#nTMuSl4 z&ze9*j0h`@Ek>E@yHIiOY{z|nAFBAxT}C!e_Ku#_;IyNjl^q-kfbXJocD<=9>g*E5 zov=4`btL~;bZ2dC3tea`h;4sAPd8ZPm8SX7+?M`+5WMA;0oMS2KF)XLU~{*__m+Uv z_-!ekhaY=y$Xrg7%M7%=dh;Qp4F~xRy3GD)6K*_xpJ=p-z5D3ux7j9RPL68ZmSZ{h z>s>#D-LF5Taerp7@9_OSt!ASAqgjD0(Zc3H=0S2e^I&0_)ssz8oJf(WZ9Vk@m|U5a zLQ$ZVgCazVz~l;wxMKz;SIv9oW?|q9#@(((MTl7&xjPzN&ocx#M@{DKG4YLF>ldER z%$NDldk@>q>!@yRsM%RMtwzM(2$jcX)yT60cZ}G-}jN zmggBJ2{;@|FfFZL^j%Bu{F(oetJ_s){WNUpftAvm+D%0w*vqTc{;ba!=*!SwLd_?e z5^Tkcgoq`Kgh&DXANkSJ&3BV*Lq|AWFj}+PkMclOs{1d|H;@BSrTPww<$e?haezp* zsBsYTlWeTt-#Q|5CL7hn(=Sb08&KokH|W_73V97jy;8pee8|F;kX`yJ6Y?*ka?~>D ze2u+cm%ApMe_KSq+)X(k+WSPhLUCs$Y=2=9!;$|QjT+lC%BHts-R_BZ_+Q8N_kW1! zzKyqZWbjVA9uMciC zT~#;C9FH;i;`Z!5jQD--D?-R)CDRYvjK3{k|I&e5Smob}W6C!Y(1=Wr%vo`oN0rTmP!a-j{Ey*7}NL+i#2yS44ta;aU1&SLcfASuXI{9rDhlj$y$m6 z+;IZntZzEjNAv|J0>)LFRKeH&aa-&8)Z{zU)~J(1^LCNN?IKLm@>Fgc<394Er-{l1 zsl>RL3vHc*GPS#JxWpf=ckOh~A8pQCn||=Io*hC|?`VbI??L++!)oty)hgwy!?ZZB zhd%4SLniqv#qchgh7G$IS=^m~QLt{FzWi2tdnIq^d_+db>V|4{jq4S7TEpaPSI$B_ zCuQPKFOvsVY6c(eB+wr30!tF4dYSKhA+_Ec-u+=^ILhM+$3JPkOp=z#NJ>}zIi3jr zA%n>uH-+?Aqu^}{Nhy^gPSleprA$m2q#^IolNW}kDzcX8E-?$2P37f!K+laLvxvj% zO~tHSY;VwJt@931$l#hJvw0pJUMA(K(~-9(UbdFNMp<@4!n|V?))lT<0dUxvwF4tSDopMDv9Mxy~xU)01(B5{1XkLSXU*Jw?k`c8~1ztjzc3v zAG%i*zrVk;4c=gVdf}_IHE9r{xQiB)v6tb(l!R$2$^~}el}5p=RK=LgC~*_ zA(gu0EPqF?294&g>}Kp^N*gts?Y!Xl(ycNU7G-(bj&ui7442Y=u+ku1jIWgc6swLS zUSxi~yhJhGHA;T;6S8hX#1La2WUP1C^V(jJoVg{EJ>Wx(jy*(@abr?Wq~ zCB#4&jDG)TQK$0`!Eo?cjg?-Ga-ev#u{_~p_tH@tY3>oiE-W)3UjUsyQPLVK_DJQB3+k;)F$b~&zHU9)O_p_7c3DWV@w z!Cu;Np(_<*Pr*#=NYOsVcq_0`v!qJ^>F$E~OI{eONNBYY zzNDT^zKX4iNnU7Byy`;!R(Y2Bi$~j8J8xY-`a>&?2#Q0u_q*BDxF_us<6{U?LnSLA zv97y5UIU@7$aS9sHD9o(guvF0j*8z;s41=0XQT(u;sVh%0iis~y({+Tc0v{-!NYiL zP!5i6z)k%3uAE!}V!@dO_u*hdUvgtgX9l+#@qD~)&?ckpnW2qx!qsGOf#@S!ZR#XWpGGX5KiXI!kR1c^(!L3O1EBi$-?i zMOY^v7a;DeU448&s|lw(S}N@xh@*lHt@=HcXec%sdM6W*NP$Y=dHTa=?n8pdr&`Cf z0%j@8cJ<3jfNFNCZq{#liy!}(Q#umQUDzqm9$GipFTr~-Wc^L|Z?|gV#*b>i!XB`v z(vyyC`%6yy6$Z}20XyVoeTI(m5`j-t;a4PU&QMD!YGu)@Awh2t^# zky_Cl`L`vwbI;ryx2Jm|Wu)l*TI|9ju-K?`Cl*KRl<2CZpI;zl6UJNmMUM%IGya|>Ay(&tK6;;00IEOmadzF+Q5bcpaBBN0e~9-3O00sb%3IJk|1_&Sv01tqM??6Ki0H_0iF90k)0~*)>Kn4Ju0N@({qyc~=0NmAX zVlI9bE~*3pqyfO;nx(lUvD(S%BO7~wZUg9e!)djhogGvjCg?kVxjEZ5^5<8x;%6s6 z;TC@fND$_1g|9%Y6w;iH$3)b=Qu?lFUPtlWHW$Yt=;s>t??BOA?biP+Zu(oS9q|vX zKflI;#CG(HpW%;*1wV&}trln>8mN6gKD*S23?oebY%HNme||I~Xn)^>HsQHtcFUrZW{NWd8Qc>1Nj<=l zhAm~G@A0k;jauVhBfct6ooFT6kMh$QqNUC~sM$4Z?S^sxe!MSb7)BR3``G?!|07(d zwXW6EWT#|fTym8#Dff%MC=%z8XGA*mL;-F0SvpwD1V(F$lBIBN$M2f%y>Mz8Ins={ zU*ji(lbcZ!f_Ld?4dqW$k}nGg>gq)7zpTt{8t8H5Bu^~8oJi`tLQ6^~ysZm8iU!Nt zPf1a$tQz*o$Duivh!!Wcl*3PP4&SnIiMpmv#KxS*8=esNfa-jnoi|yT;d4%6?Br&# z9pN*142i+`*$)LxA!`nXxcR7NxZy;Ka6HNW^jEv4ktdoF1y+>8?g~HL_y&bJv`nrIk)C7z1=f#`aDPOvOR%jA!w(V*xb>#W3B^x|5y2)q`i#td zyH~WeO7GQKmHW5s7+r607my_OOyCLL+l)`cAIpoJlcD60I5OO`Q}7s?A4#M4SL3SP zBhAqll!*)Vm3Ehn>87++TsO#>jY>(W2^a9OgaPvk)u9FmQaz_tovVTclar{bQ`C^>RKd_O==_f7H zq4Ct}MkujmJ_o$E{I>n-h7-LT2qOqQwoo{@jRSro{4CClL?q*t91gfCYT`9@yo7se zrqX$r9%W&zN>)^v| zF5jDl&X2Lnfx2UId9~U1p#t&5d-@^fO7T_R8$%U_j7)}74|45rd3;KXo#=R$AQ&Mq zZ@9nH-oSnSmq_l_OC$DR)&3LQ=XPks7TL`mrHoEx3EpDGy5`!serdNUeHvFhz#Y}{ z3SIk6HhAxM24*evF_k||_+DzE!ZR7H&M8;_O2 zu*JTZf%2A}d-!kuZi-SIjV819Ndy~&!f-bwVr&m5xvti$W6(+L&%P_Kez3f;H0HYD ziqTZ&99`Nr$T|A9>-tTWQu**Ttb!(tBZ({F$?ou)Yta1g?#pEl>*Ir|Q`xW7GfS@^ zdZr%tEkF3s_=BfrUCNldz4W-h<+x%;*Ux%t{8y4_{qB-&N80d?XTJNMYT?hI9r&(k zXkG1b3)zpUbKBz$0faTQsM5%G&hdd@{pxFM+4pKGB~lyVjH7)14RXf~`@7Dptc{4JEp)tmDQpGjl(B`Hy{mXDAUS}i z)naD$bEs6}lY@;T?@DI8&=v~ zT(aGo3sKk}T4x@2fz9eP?zLr4H78APK)QjwXOF&G!Y70Nn|E}k%_y{9v`5AG!04aH z4Er`4O{3m(YcP#`a5$q?#r}C9IV&3L(or0Zeb@m)qIUKw{$|cO=SN(7z@hk{Lqn5W zb~-{J&4_kZsXeN5!7}c0x>q9QI{w=V%KwtV?6!?cx*+1s0@kHOrjc?Ab)ZPu4IS$Q zPWlhMim$H19R?nByz!TNzS1xkPQyn<6BQD*B$g!IKXlA`V9SSsmzH8 z|4rR^5~Xslf-=F0-n?4|?UF5gw}P_xe>xep(p;wk2wl4dq{DiRRdMQ;t*qaHu2U#bwuMBqF5a zrPbKr6w4v{ggp+EgpF1nSKEFnSkm$mS4ryAuv;IgFkUX2&XdL5x+~ySl#d+Y?1I-m z>@^;e_x@Bbf}*W%j-Sw16rU1a{sNo2%#W;|y3mraPW5qtF#)nCUFQaH zefBMIuS%sB;Oc~7p$6$cH{g{rF}oZ}GgN?QXz3n1WQBpjr$oVp{J!A;e|Otg3=BQx>5?cieV47no$Qt8rVlv`5JV zt0(|gaZsb!RcdjD@F`@GvoR^m^Db;RF)HEkfN08?u4Q5vBvdt~#?9K{nCufVkm z7CCsDtS*^ht5vtw9JrawJ8wCvsO9WXT3p=eyXwX+@2$=gj~p|x`7H!{_(>Z+#rh&~ z(n%{5tXe9~NA7-ThHIAKE+X^u*-_oO3@zf~KewuF_pWmd`R6Dj-U=cIbSv^F-C!C9 za4=m$tq~YF0V^lKe;ugX4iPSyr`FomZ))myh}YV6a(!vGeEDc|IA*}ZTP?(7IqF<@ z;n&R_Rvvwz{WM9e%n zzHRnac59dIg?aXfkgZzFT7GBvYi3FBg8NaL*-D+^n%qha^f0gZTNKz)>`F9I+E1q@ z$JGm9|1L_I6gChNOKiOEB!iqPE#Hol+3I`9yZy#0Dr)lC)X+VC`3$QlO0fPQIEufC zuwFDFcU>eQ1*2Dr>W{rdm3Z%(3;wB0^ZDTq8+4?pZ>%)I^QEhqXDCo$p!iLShfb_yx|%HvX6)<~ zsQw?97->F4ciLQ%1CVkELJJ@;0EvPioB%R?i7Zth253Q;jv!f_s4sG_14Yjj)GR9agtOUnc4yJR&U)+{h3!Q?^?b zjM#rZVPRJ1K#7OSMRI_?f{AeH#O)M7EO|MDh|33R*@tdG7va+W2vy0{pKDXC5#L1y zi>Fo=-c4CI>|eY6-3d-`G{&IlKJ7b3AfiK_Ob6Krfe@&&nu$9 z?lT&2IcjY|ZaUyO4VduzKiKtWHCN+~PE3kOd@N?Qs9^2OQ;z13aa(a< z+Zy4L@U`f8%AB@nY3#g3;5Oz96SK}f6Dq4ApJVcn_ro>Z9@+Re- zPJ)S0P~aNUC*J8AY|Kurm0_G%it7x%oe`Uw6eGpa+@|?08cwiL(gMpneHNG(ShhJT zlM)Qp!`PsX6?96#S5`z)Ogh!XV7J^s4O)c?kyJdf?RhH-Tm{;0sngBqD4$@J)(cb! zSk;{(3$V2cL)cgNaHRvX8h3L1yH{zwy=!+ zo_E0!%g0saeEqlj8haBorFyLkt1SuC@>TAZpE6=G`L1p7+QpFz$PgnIHrPYVbvP6# z>GidUuN{g=z;gxhD_F!(H5X6(GdCty&arQ3ayt)#n}zOgH7oo(MzPXc&sZuqD~G;U34)2{TJ#^RI-SNKW=X|nI* z)D_1b;_IbmlxFYr)b- zcoBUjTtaB#IKww;HsgHO57gwm(GCYzAEtOgGj=jGjB?-csW=fjZI|bZ3QTQFbI^P7 z{H=llQnBDPAJ@54|83b`*Yp-}r>DdnsHNh6a*&~G`j}G)L9fT!Q%lmHjd!`Jd^@C9 zpga$B?2`gBN;2|Jbk-)}XDNYs2{F~%#0x|RJLtl5+k%&Pf)A8o2L^{$6j)x{WVwhORPgo|h=FPVF>sIE zJAEFyM=F3?Wi@Umpmyt|{hQqlQE??E15OM7S@Ph@MK5Q7U@CxW8 zZj-c+tHAp|%jBrq40}i4X==BKl8b?Hw##t`bsjD5rd%Luz0mM*im|t#55BziUOkBW zXXNlWDnS$f6_u>=NlKb-O6)+!h0@>MKjTB zg*}n;K0m2W_SLX2oKn+s9H%%H>G;+-tGk({XsY${{h6w}E`yLR8iY&`QqyX$42`CZ z#@mwDU-HLsik{`tp?kOo96wx!(I~PAKB}#CXA&Kji(_`H4RCO(Q1jPF)J}8jxS!qT zM6u!AE0`~^8C$2q`eNOgTq}_qmCcW*KOLu1O_q_!k2g3S$GLJKuG7PFjwzs{mnk|^ zU6S=t>@Q2r=bCwDsPdZrlCbj^+D)@l`7N~E$O>Z<6l~+4CE%FK8Fk#Ai?W(`Q){P5 zASgADe!T6d7my3obMrqr$hxU1x~b{n#<;q~Ibh^dZ^0Dxkr>hq$^0y(iUwh9*Xh_& zjI(*Nt#m!n!#a__oqLg12ZXQ#B6Jw@da0|AGS0x5s?YvnAifFns%&=BD&DN+^nSLzSj$bh4<8X&D z0{qNh5Rv;jEbc_^b@l0eRN}8O#r$ha%PRiy2?44~io0nxZeb={fYSnjIqaQMt zKmUBo(k)&8EXN;{Q~!Dpy@;3G3wiXtRr`Bu+uNrJ8jKuOhDC3|zxE)(&d(xmcuW}I zijJ;~8@_%|5Jp~X+#2o9Ec(Ero7y*S%v~A1tY0lC{U3_fof5t5o4_Y$nHQVz^2wxK z3!9dkLZO+4GqdPirk$U10Z@DnU2J1C^?KNUb!45MJ9Leg_4DPUr|ar&r202rYhrkw zB^21##1AM&ndUC<&Xr^ai}KK#jQMY5`tDD+xPF$f>#70N4CpJMen6vuCIS5hv<7HT z!iF^BTviKy83J0DT4Y4NwoD?|}LN{QxuwXc*8aAS|F?fN+2&0Zjv%Jw1G7 zgWT=y9$%H%K3`Q4Ah83$0f`*~4oK_>a6n?mfCCaE;;$+KBt{H4ATbia0f~_UP8#nf zL>BM%kqn%ZgL6P)6o3N~qXZm~7!}}v#7+SYNQ@eAKw_r>2P8%VI3O`vz-dY47-EPy zKDNY)cL7=ebhS10a^fb8V%wB=>l>E6c4BnP#2&DbT}=UeG^5T zlwH>gKyLu$0{RQkXFxT8ngM+U)DLJB&?KPWfYt!*0V0vM>!Jp91`xZn4JjjASw!5k z;m^+iB?3wY^a9XJK&gPz0lg9X%oFUpho9e9#^T;`(2dogG^mUw2sw=BdM_KK5D*uYE#;dm`_)*XZUOFjIY+JQ`6Aj z8|BW35qqvT_wBo1XPd!6Rl`*2y>Y>_>Mi*h8d*tM%k!3t8{RS>*UNcd*<7;JD%#fk zydnemz8TAv%OQWFfZtXF`6wkG@LG2rIB#7snjmlSaa+$3mKk(oZ{(90qxoz4`^WN` zY#2o)s~j30bnWNyh=gB{NgJ-%rG>K*tHH z3UoR<`+E@R&oDnZMo-ETbRs}9L4mHBu{EXva}Q58IkfC4*p9zY%Li64rg=w`VF&df z(g39t%993AU^;Xn&En&BSzpYooSd4F?^nsdw0GGWR|agYR0qf@m(&stkjnzWSCW3h zNYwAvvZ=joFOnx!cN&|vHFj8c^R@J2lhcyxb!ztkDj~tx*D~SH;7X@@nhd@S=L*8@ zXuap%74v^P(h#SIq+a%e=UP5=%#L`g(8T$(o>&Ra7HeMpQ3BZql*w`bQN}^Q0VGyD@N3fUdUX19El*j8py>zF5*ww zF?vgKy+;S}F>h6D55THHpTfue-({-w270mq)L9H%n&(i@A97QU=nwaAAY(7_Lj#N+fI&X?Ps1MkMONYPnF z{n52_13H3!AuTTxxoKneu|jLloW6%FUqZL|(~TI~()-3+{BMrhKb*uWKXh2qc#S4tR>AlWFFQI#ClZftnYLOWg z!8E4jEEl`l;modvpM$}CVvP}-Ib)B!*rfvp^I)&kB;2eRPmB29VCau`*ky$kfRRTz z3@kRd*`*q30WSR4F^py>P@)JF&^9LF#duD}FyQ)y9sl%-U@(;)a)(k$Y%J{s(!WPk zJ!>a55lR{iV-$fwl%T4Ci?hHb^3J;_6%nLdGBZ>RF)(xMT$6(4l`p_0pdNx%4`49c zbx$pNVK>C`b1)6$3K|;Bwzcqe={)Pkt#N>hH%)WTFwMYARBdo7T`1+ln@FOXEan0(366b>?OrO zMF4Kszs>spSxR6M0TTIhzy7xgu7A(kk{4t`56Fe1cm)JnkYEQ0 zCV}7y5RgLx&{CTGO6sulQRjbNm*%&As(V;B1V^kHccVt5M!er}Yt?-msfk*TsR~hJwna?f7Mqhc z9F+VI?p6vj=^$?Vt3{ZqPp>BlN)0F8CzBXA(Dm_C+>*Sfpw`Gf8ZYAanuE64H!ii> zC3t~JNrKjdzESz`U~Il!sn5`E=xL&bZ`K^r@!tbo>;YMGW`ar*!#=rr9VKVE5Q|EE zo?ZVr;C9ct^eoq|!l$!b@&IONb9`4osps=rhP=8>bx0ABRs7d@wYuf+BkN(;^7khM zttF0n@&*=itg(5aAC7DeP_Q2hyyt$;l4k3+t9{ivJ=Hb7H~jO4YFv)T4Hm!NH;+C& zPHn?SP4zj(zW*NR9hL1eD*klKGjaOLyO5HL6W{ait3>snFK~{2F!!WZ4PnVv-%$9X zyF@DVr7Ofr*n6I%_btZ6we_9ufmLxw~fCv9KqO zt#kUra|~mrIJokHc(0zXImbtqXJ6pk^{$?Qmz7Jli`Aq{fr^7Gm(n&*)BCFvobg3q z)%Jx^A-)T<(!*3Ys-GolT69adnNU>s*$YIC%?YQVw65QDNM?L-hRyPED_yqt-*nm`=?`{_&Rj^Aiis~yFJX`J%#G!)xHLTofn zY+fW$@yVG@Z@I}8!+_2n>)RZv1(I`)i*pH9pU?f!mK-@PeKqjTV}HHJ{&yae1?IJD z=fpX3&LwaMg?vtmd{K?#Yn6RN_4g%{MmtYkv= zitv+WFB?wXW3b7|e?Xx!_O31J6dY{2{-WXywk0{AZz6PO#mDVT>T7ESd*E~V^ey=E z?9%0^{Dh4VA{mv$*Aag&EzHlbuCsnc2HUC z^eIlnroOlfg#jk8G*m9a%QTD{t8cSgQb~ar!S;q1sMeXPW;Ahewf8OC42mW+9b!4$ zcou=L1m%5W+@%P=uYa9YaE=pN1zSKO9&){Gs_HZ>r>{z|BNR=X>tzS-eA}`R#<4G( z?lLkD5)7a3C3qRyTBwPD7Frmr*qHQ*6L${^)x`jp6IP7O;8%l@S);-~3b>p=r~1-1 z<{M)?B}6hO^7uBn@GPLe7sJ>_P8f(y7@$k85cLI)KJa+QZ+I%=c()}+U^`q6!HOYF#5U;@9&H116 z7kytTtPZ`%8cER8w*NF)6|_fKONxl>pzoQm?M62~OMT&Mc&Ny=8vNHBCng)F{_)LH zxkXM_yB6WsOL&Y>yWf9zzCAhup)g^1C2|tvrQWmSmbnSGmi5$%= z*P51wH3Z!$ojjfuQERAIx31?gn3GUE3R1Sb!_`kr@Tg1+TPV#5_5Gyup1<|1E@kgu znlc`r?yC47vH6v*7?^%-SLT08cUm2z(028%4$tw@L%FCK3{$9Cew2=e&A=@afnN0q z>w*;nNo#Cmc=k~}k|DnRj=Yr>!9#VI?0`x`Brtg0Hnq&ocE2+5BR}#WTCiYc980={ zH!vI>Q6oxKZ}OQVCJJjhQXD%TmzT84!Bqq(q@PzIpDnOavZ=m-SKpjC*VX8=-`%Kx zrIDj|V0XROV*I(pY}W7&visP_%SboNP0e?6Up=1DLWG8e|5mFLXC%d)cI}NUalk#;Bww&Swyt54Eg*POAj z3h%mjd~gu4 zrapDNV~@>IQx8jdw?D9BJ5}1im|6N)f(IEUs0T0KrS7%AK2(4S+F%bn(#4<47A-Z{ z4ab8$@Z#&c&LgLp&i2`c-mg>hU07f5A{a>G(pGj4`>e*+@di@XTL*jehf5XUKKZ>d z@JhZEu@kc#c9bLNw=HQE_9VNke7kqnsc!Bplg06SozCMbgWHOglKR_zc**A;sKdpm zo%!0=rJe*jRj%_581>*x4`qSwhb`kY^gLlk%gPdZ!!6b%PgSOmq-R3*sTBkA#WnT0 zYyw}n^@}I)W@KjNb(9~+7j(#-{=hVn-y=;kGSeWKm!{_`aCZE@LALh%?BeOeLh_9T1(+QD+fM@M zr;%XO_ex3k#{;hVv#QD=ey3k$uWznIy77tfG!GEl-BQ_KO^H|c4%-`gH5BBW-##%Z z)4V4Ob6I!XA{6L8*&o>%KHS|ndvK<53O{uDXX~>SYxlqrtB@Sk47W>5GvyudHN@g@ zY{Fd@Ys!0dBABI-@zh_xyWTfaB|hgmd!9z&gWno>G_^F_(ta*%cBaeX{Kb5_cxBXJs*T0*yP0i5SWakQ+PS6W zud+y|{`soy#WfaH5qwCEvqxfm=kljdir;<@Z+5D@NnA=fZ;wxRksGh4=TYsZG$47K zmB$=u@Az}K4@R}>&@Fp3X+xH+)}b9G4>nm`y`kXWL(p1HMs)`-3UuuXMa0m+d{KGg zdAhEM?S;1Tdxs{Sw+?CsXZwct(~5nn=Ux-zdkkohdOk-?$Znhy5B8$puJq`6h1!C2 zR~7U@`V+gR5EqILOKSD%9gAh7ogdZl#O>+yoC*jVko#Et=5Rto8hGyzGy5*?i+0KzCSw=c)Uk17{%~WV+qQVU-hRC6@G4k zMWB}rC&0eVwMoX_IunehYQFJ9`t7e7EeuM1Q-n$76h&CeIt?{|lVW$T zvH${AS(n8d;@Z0WQ}DvrxOX#oe5sQuhKv@}DTaNnETsnK(xeiOJ2bZ<6Z!j+x*84^!6>2>HZ)Qkw^2YXPNUo zFID(guV!1;CI0HKUd*m`pUn-D6A9EZ@z*o)*D@jNo+L+4(r%>o%xry2mGJSfG)a$6 ziZk2R*47dWp33EuqY^kL$=qNV@0@9;ThJ`;qMHFa=?^n`&ECK(GCG?E`NwHR>2QDB zx`k2|sZ$=GP_EtgYv?AOC+uZ!d1lBOd*hzi8_G&79&IPG#^Z30~iz zD~eI!0-k}Kj(YX2;#34BX1Lw4nR6!tF_Yfn)7DDfvVa{3j}=;k6-!N*ypN z{H0#)y115cntYjQ2svaqW#yUR1&bvK3XMV@%wCNELz&O$2oi&f`-Q-vlzW}~qd&g3 z*B_HmyD{M`C$2@<)7LN8=*|krp?T=(2DDg;s7MsID(&`O0x*WWMmbkOhu&KTyDi09qo--Ne?WpuM1 zl@4D}D+qoqBN5F~OHWt*N`MrENK~eSRY4#%1n&IEJd4OrAS0Tp?2hGB&)N{uYku%X zMEq1d5p+kGhZ1V^%l+>cnAL&L64cuff&)2no7C!QrJzmMVAu!hEh!IkMfX#pUO7RM z%$PkxoShdRG~lbB$;*YdYIE^0hZLICHQW)i0;9H&c8~dn#xu;Wcq2&#IFWp!A#rrl z=BfAwF|yR)dkkW`pBc>795q(Yrz;RCu#l5*d}mkL|4dcJc)^-VF7hd9#KoTsk;OKX zS8%!PXKbM;xajo;1}ta@&H~6X86_RbcI5PF)ITfT1#1>E-TzWgWVYeRTQ=8q)uuCz z9Q8u-bi_pfFtr}ESa(FZg7m*n-e>?`w1e+afs^yV7~Zn!u1J8s7#Sg{OF?SQLITwN zC%}^?pe_=q`@aSdiS2>>LI(Xw;{RR4e>al6DHmi(>;J)q|E}TRZ1{I0>zYaaQ}OTw z6A&>-`mrC)L5`i&Qwra(F(s~Ng9ivplJbhhIf1!b>#yHxzb5dntqs%e*!J`%cr+9P z=jrt6H`N8x^6@&p z(2zo$$Rt=W<9Ca7b2_AbV8J&uP_50Nw_II(us$>%aXpFW9$w;KDDbdYE12 z6C?}XKICadKcAZqU3vV6hpFvXVV0*2Jnb8l7QJ{>>O(e{<_l_rehe)g{KooF)(SsJ zSAMta>7AEB%`VrjmeB6IJ6o?XSZaXpRJbGf=H+RHoLU1t(ykR19!r{LxiM$VW}mCK zviQ_2uKP=b|LTT-Qw;$(Hn=mO+GN=s;dld3m}!bOcv7&XF$<40j)j*>)x^5X{o{d@-BVDk2xfGJL(t+RY!z z3p&i*waI9Akj7m|tYlKCO%f{W6!0L)bbLsiIi>^L&^>YJkbyA|0q_0UOa5?|K>6Fa zY3>4+Qg@@YyTCnvR2(thjhnn@+@1!hE5Qr8WkW`C@~vmg%96s=)4;jeBsmI2hl&^v z=;XhZ?U|i@Ej;g|4GH-&dnh6IFPmz#=qwmNn4dp1A=d~GLhA|1IoPA(GLk*|Mfpg# z^h#!Vn+DP@RIk@fYOfT)0`+<$n1_aIf7pA@PsiX?QY#;Bp)Q{8XTZr-Ua|^YW>CQM zeA0csp7bsMJ9aF%M_n5Fy3GF0Xit{sZR}i#aKim?gnMpdhtU-!Gqd_fEWIBBZrK^A zlO>+L*mmwTiP+{w6wYkf1$&hZYZ(-XMfH%acxITdf zA7t-@m?HqExjO%m3Z&vhh(o6gpGQxQJhI_`Y0C$`6_RVF^7LZ|i-Cv;h>DG~BRH@C zZ&ualg*ovo@$AB!n5KFGXykF7#egbRESpN~o(iwoXMesj2f|~U&dF0vx#+VITJeG; zy4o`T3GlS(MITM%MF{YpH2?tm?7sqt#LQI~&AxynobXRs49GyL3?NlTkm^;C>NT70 zp0ncrX2`#(`G=(>We>nLeUtxNz(2Ag9LW>ByUKRcLvA7L68Ao?tKfKZqHAD*2luS* z##Z?PTfn=dy%zPWMn&6_LiPm{k6K?}5Ayjk6r!h!T*a&~j`2LR4Lg*BGD~5%S$udGLl8EMNE* z^?~iPaci5(gHbnniRojBdyhM_lj#|f4lnK2jn<8xh7V_INe6anej-++AI!$vovjYodQITyuYi>G$LeY zUlzyAS!72}nf8XwaN6icQ!+@OrkGDITAz_av*2k0FdVE8@bbG7x5!)@MD=DE9IUeC zQs2uN*O{lOCCrU(J7}&fYZ*|-f$w&h$>zW9NK8!7GNq2g_KPAP=xRJy4)l}UGrBzu zmM(yW7Xqi+lglU8S-qk;gAg(+98w-qdVC)`Qep=#ffG;LyVm*1oHFO4<7v;v)OZm% zjZcCFP|)k#G&Osn87jT*60MGJz!_Cd7<0L;IVi&oayAb8y~w1$t)1eY_C-7mN)9le zp`qaTm$K%hsE!0H8fkjq`0_kaH>jFq5w|YG;<0Y z0966;0ueHCK|__YX;TIETY;#Al`fp4n)?Tg2-~{()`=A7q>25^3!9WBT5er83!!Kd zr%*MC;uiVYGH5^NiC`hcDZOd8h$4oo0*Mt7_R412<#R;x{Ydv>@+LjmBt#nt&MAuf zvj+X72vJEob+~9Y2`(<52stSP(xMJ2**g_dGI}ap6b8hviICatdc|bmL%GCo^mQU^ z$L3o(5}ZH@t+e0O`DeV zE*wNKT;S~iA~=6ihB-xehCg?qEfI3$ZH(LZ76<6ilxi(zoxB^sU1<0n|Ca$Ey^~_l zBY}#+g%MmIP((qD(=MT`qzuHyE3Xm=?nmD5rTP^*pwy?gGIkJi~DBKh#4RrnrPel)o`Pi z+bgZ|e0Xg-+oGDo>%hgan0p+hzruDl2oo{Yb?4nMJMRtGT#g?&qJ?0ov z5}lAZtwKHdq4K%`(%p-0LT(@$K2!WY9CM4K`BmBr64;-z7^+d8kg)I)nTS3+q^aPk zO4h!~z&WJ3sscl;BcC*_E0ATk^FC62+_A}UW=Qiog{s*2RL*e_uk-kqiuG|`-!Q@K z_O2s%YWq9ZjoUPVA3-%KiSeKGj2Gla%=vTcfPbg4aBP~px7I4>u|DI0mFUDmh34thXn#<%5$u3&{ zxf1a&rD69`7=p07P(vEB7a+~@@RQ3R8RiD0b;I`zOm2>sW8-_E@+m**xp$jD0RAF~ z%>;mGs=f!y-*OBb+B>t;X(Spj6g3UJeoFdznj(zCtx5CGgU zm*?IYsk#L!*JAYm2;8_Czx10oP3R#8UUxz)K^6uvaOcW{WHM+2J1A7Y0D=48i6S67 z7J#}z%qe953Ee;zBU0cN|78l4C?w(^ih^=88JG+dbVnl{HL>OZRRzvKE5a1T{g(#) zs|AffWnxn(I|P+f5CiUCs3amF`6>A|9@3#6pV6=%7uz4tZr#DZgr$^IH%hG0hrDwc?yaB}{Zg zrqq<-qEAShUNsZrZcY%v^Wop|E)#EifBy6Qq+L7xUnpP|xE7SmcL4d*!WtNF;P!#8A^mgBG)P+`2}4b}qR#F1EHg|yFn4F_4eG}(8|ID1 zv2x)c&EEKvN+%*@^vbZ6mE$P>H;xBavt>zwEKw~WDUqEgE}=Oh{wIgR|4M(yFaJw( zD-abHE*cdUQbKpMS*^4~3H3Xa$3(!ad7zpiyB(4}Kat6Ms?Gt~pOOKYC8K-nKQc&p&we;q$l-MTq{VzZXNEje9klfy@^zaH^m^3ivzfzv)<%6ty zHMoz63Tw(yAe`8&^qb!e%7NF3wG<_kkev@=EhYnsKwkgcJhv!R!NH`7rMdiMJk0|E zAeQZ$m)KmWA%)`3DnZqv}u;xD<4B|01Kk zOb(gg_FYqMPJ`l@2(%v%L$FRlg>MnSy@0dMDg5(4gfINbt7=lliJlXiLDvuI25lc` zJltY4z+VdW`yi80Lk4Q42|Wg-{=L9E*AoL7o)=IDWyoN&3`!St{tyEtkPFE<4ukT- zJT_Jmj_Ugww>ka(5uyR1L!OP5`jDNO2?F75NN-jTD(mp)ucKYUx9-Ld+g%YWsTDcL zv4|W*zCt5sx@19#^GyHvO^cg>^J9o#og@4u4V*Q-KhLR=F3Tnzh_8f=WUAiJ$?_Oi zlHOfA8fa+`t80`}e4S&{em~h7H$ClP+w6IZZ@GrQ?f%ivUuQ2&bOC4&G{WMwx$gjr}tG&Tz#oxZ8fA|3$jc3 z27-JwRtJ&`{cV8)acE6$NA2NPr!u4#c7l9|*MyWbOE6S5?kF-u3k< zryRBeHEV6EWbR8MRw+5rYC7_m@E#-KKrrS0sM1}L`H-I`l`~T};@js2{;Xd(zA#)f zQ(;hpV73-@@kbT;7(96&N?_IWWm1MolAfK++|Q%m2%tsy{_2|5t0FJnk=GAt{lGX-$=h611o0n z*`ES>QZ?)Bh+|t;>H-9ZaI3il1jkG>8vzm&hqDj@&4j}LDAHnGGxb|g)MY{OYsi8_ zGJb9-7OgU~3uD6D1kUG}Dz=7(Ykj}pbR!ZU6~qEeZYS_DNz-Zd^PcWVY*kX3#`8Srsly#sB3_yz!%mVlfm<3vlKnxb+!VtU| zp$1-ze`MVY(1=(45B3<7y{>$OwgF;!z#}?Vk=YFVc_9S;K_qXwQ678^n*bbq4Rb>m z(-kN$VNM09f=UI(zn{_DvZ^_~z{Hrhsz2ldPRRv|0oSrlYz#Vc}`)!#Gv}~ zhucbpU&94cuM+W?m7WnfY`9)~=jnM!7@dw@7DqzD=gm8o#W1#iM6nPS!&rY3JcXoN z`+3Y9KUt}zYRJtbMzO7HzQz`V@6F|uyO2do+c|AmZwWV}APrY(x;`>Alx*ncPZx8# zLWeugN#1BVVn0^ogpG}hhs(c;-qq@b?Vpg;M~c{4=B7(y;ul$}(SM7}$$FEL$QkoY z!O*Ai+;f7Vw$4Y7CYP2z3ED{t{bpp5Uj=PGs8hW31YJc539Y;rLfRRx$NxA|;$fyu zIYGu?zZjaD=@DC013A@};ezlyiqYvnH{19_8U0*q-JFxGkZ9!r$8kRTej>RmfGnYy zxpX8shZwju=th%gV<<(wmqlre#O5xPpfY@+w5vn>PKY*~6ijxMoD~nt%?=!*qGn=#Cgg-kyS;Zabc%8a;mPbkYKuIzVsEOOAz;)*xMj12wo`*JVC$)8d zC^3s@u*>hkGSmD`s(khhjJ%uB;1YWKjxpQ1#TKx%{Zpe%*Dg~&&x}1`$|Wq%#iLbd~$iqKbNdqSH5f3{43opzFK?$J&+J$ zWnMw>AS&-R-WxRC{*vvuVKdfFX4)%r=IIIRi|FYGh0O=mxOKGXy@ZlQ7eHcslxL$&5<3;E6&KVtYDOq!nG2IraY&jPKsJ^+H<5qb<_MCVJEn<^F%j-CIk)qeH)= zK;M(fQ?{HMUATXV_0&*zwpQq6&;Hz0i*v}ZP+n+4vijCl3oWG9_(!F{K*y6UmEpDk9R5yvyf+z})~ zpt2QVZ;O;tMr}mMfu}{V(vj6;N(cqS%HzO;IOr;v;^h(SVel_~!?U`IjvHoieg)=t9o|=Q~LM| z7%@|0$2!h;TxhSQd|^IhlQglHxkn_ArlOiUk{fWlo?D?pUZXKfik6#1j2qjA2ESnF zCQ+kd^H=6g`StK_{{1Zpna%0U{i#iBVrcuwtyq`+nc-#M`u)A7l6{ldeU|mv;>XJ- z)3m72ua~jG-@cYrk$TNli^&s<9UUm4(14Ym%%JV5vdv9q*hZqaVz5~d&jWdz_Ye!# zAqlh|wGR`b7`nl<_y)?(RDucnM5X48eow_OkADNX#;W8|(&v|9;Ft0L)ms%W)mcsW ze`;O{h#;=<_K-@6ZDNE-p?Ry&omo_quc}2%=*(=4K%7O=oUwht?Dm%1D?UfJ?T~E? z_)hhOkg5Qs*G`4I41oka%!OM~qt2z0Q9HJ%O^uHOP0p1(Ndw$6S|Q6FLJM#q>jg57 zu-+-SKfH_Mh@-o3A!K`N@CiYqqcBEs@MUFYwxy}LYO3u|IIQmelVXhw%=V0eSP|~^ zlr+~)2ze>F!>&))&QxZMIJU~GS3(ni=4tnpr$~l*qJ?c_ajc*>T~ejc$I2FypG!g; zM!r8PQ=>M|T7Gd~x*Lb^I24GtrL&;R7_YvE^pmWz=^0SioH1y->hXC@m;1qUv8!^0 zmC41vF179m^m4VHBy4L=RPJo*=-+#`xFxFH?kwwBB_@50lP2P z@yM-rWX0MuNS`IY^8Wbt?$pFymrPvsPVM>8h^W`=+$|XE6q>#kf}lS+N0L2!O)5lf zcbhb^;45Q2zgIZkopviUIACqG@4VY?OvpfFB&tO~CS||tz0BA02H8+m(M+N3)X%V8 zNudq}`!vO?`L0)eZu-9t-F4sVKD;=*lw|Y3O;0oF&q|~3rhquJS z>H!VT1q~i!x1NvKt7vL^b|?BHhy0G!NIW@fxm1x97EZ-4Hv~n%(8=q!`AQZzZN|mX zSE&`4N(RCTsb=MEvLPG1h++sk@8TOsAgdBRHG^M&*fmsdKc)30<#G4({f_O&wf zv+DPw^l9onu|El7-KZ{3rkqE?v4%%VdR{m~GSqv@;#QSHiDs)W1RZ-)J>+Q8P7J71 z^(?4$)ZeuKAoRS7r1GGyB86uGsgT8^Mx8C+^b~zG|Af@NJf$LUQ!b}-24CG><6@GJ z+7m>3m|4=)WKNV|a!&XQJ}u$L#PS+_sO7j<_vV~c%85+XRh9+pRYw5WSB4=JP%P48Q5ms_WFNYO{6PMF#m}tWKs9$rQ7QnoQRbN8iGv-6t zq3Z5PbM>S>G?;y(Y8FJxU*%H#(BL9Z*l1a}CSLipdtD2MTEkgkzX0SpM7y&lBEW{0 ziLD%W%+FsAx_CCZ=b{mdPK^*voTnu>b+$Pl)%pro9E%$FX`f?ic1E40{5b@}&YwJf zA>#asog853!@Inv=-ixN9&bl^lsZ*4u6+&}d2|smV$6YnEw?eGX&G^-1vlxR4Kcpy zoj$ZOyQ^;Vd}(&qxlEnbzDI}l{i6Q^gF@=w()4^BizkPR#}+>XJN#|&nUt>+DT!T! z#s|0ZpyB1y3BL=(>_W_UisG$;HY3 zpA&DDuO1yUj5Fco)6?=(#ZUe91wHdu|JtN|Z@2pwT_rp2G!Mt44~a@AW|vBoeXpX0 zF$;%E-uZu^y|Q=v(TNKhZkj9C7j>@EdPzP$*AT&|G_F9!w&kybwqY0Q)w(Vug|>ZfrngPyp}{W|}pvIr`haLWLzx(5Z& zA@EH_y_LAbbS%%#ipA)~9rQQ96+3tx6t!CCH*87`ej1IEhUc6O&q){_l5b{aB3zm6 zU9tPwE8Y}lWGj9C`253|OI*zeqhtAJGfHuO&El|HnhhvW?A;eU)K5R>-Q#xXkV`a? ztC^2W+LEdV!Y`l4z+`keM&g9Y6-ELT;;$;IlG{ix#%EL|Mmg_ju0V&x4R1es2f;~3 zn*gA88VCe~E`}3adB@J@9plPl;3d$4udy*pN56tiTJtu9(iE7CUcNaEv4~jG*5?dM zryx1Q0wW}}^(*L--u!GLPY_$I#{$?luSI6E$2Bxr`|qx=uT@(MS_!fh@7=z4IA|4v zS`f?_n~i1OY$A_EX1@;}4^Skx$TS4|AOmYmmXz3P+@o19_F^mB#r#v^eJh^Fs4{BNQ9F(z(#Ma3F8)p#^1N=ab98-rCaodRNoF z|4#PhAdk)YiKU6XIrhe#)kVKef$2Fiw&_;n&JGqcuCBg^+-T`swH z{j5sBj|}V#+4@)X{j7LD(!@|Uf^XN8S(-DF+gm#2FQH+6=`fb&{h7sIZYJ-RLMw1h znIS4__5Oaf@fOYtU)J>={OLk*zCT9eB9l#emm0oj&u7lhTkm`Mk=NxWLNDxYBIfGe zkN+&j1#kH6?69=&uQcVSYb^6!HQw8mC&#(%SE~hYto}kZkut~X@q4?g+lwn$4H*8b zyT;b&{0vpYa7>{4CblnCGV<8&y@u(vIYRdYw-jd1r}20|F4StVE2~mwa*H5cFc+tB|10@KsLa%}e1FX~ z%jIFOv3B46vs@vWpa%G=D>{VHnsf z6H8r9^qK0rf?f!$y81HQL38vJ(@7xG(B4eGO@As_Pk_ZrhB%c)u% zzJ2}LzVu#;DAONsBfvZ@-DBMMDB^W;*S0HtHlzbF>N1w`85kJS(WYvFJMHJFQ}`y8 z#1Wr`O>P`6=?hDzIxtPrv~SbV33A#r^mm^qxv2rg-}aQe`jv~G6<7|psbl&14JKBm z0_&FI94-f4#@)6>^)HX7)0InGUH;{H-qXy{q~INkU)8{N6mPRYiWn+rHMZke>1D&K~V&BW`{o!r9Y`guPhJVi2abbnB@6HvUgSs-Pd znp!n0p|AH^Z3D4vH=SNSAamihR1o<}h@`aOud*G6Iq3&)d<3ILv)+fS zQvd-Ns;<#romQqXz8f05tB9SI#Dz)3E<^3nBYd&ei+dh7&jg=t5II-s@WIfRERbAzpax3&UF*onZU}hNd~+Z!A>D@HA3QQjKrfxKTZ3( z>y|2o5z^^#y|#I0(=TzEpscHH-s@la72?pWqn`K8FZV`bO@%vCvVywF6_t1Nd5tVE zu6y6W&JayJ-^^E|lX`oiSL`&{Ao8Aqr9DF8j>vJjj5*F`9dbZtR^e@AMJ0@DP{Qy< zz+#F-fkDoRHT*fku$6t?LsW$Tr*wMr1+D+qsMT`hYJ?6dHowuE$w;ZmXd?O&SGNa2 z8SFA(drmh%R*-5WU~xuEw|cBbyE8F8Axg8s=6tH6$1&#yR-NVy9?otio-?5Gc$OPd zvWqG2x56YsPpmwu@bTQrY>Qm;>S>T&F5J~Dx^^ace;A|u?WmsP2W#^kf5!G2`1$pq z4c?%!@4TK4b1M}J(gP_b#T#4KIz~7*kO8bco}U6GzSH8)Ddr!67kv}O;qK@mxA^TE zD|Nm+LyR6iE()urDPU04m9g7U+(V6TUb&c>X2D?UqM{`SJcWa&H|{ZwnDI}5qvZizz|CkMluKdtim~FYR}cZ;`TK;8Y*G7 z5+d?c8ZPsrFD|Jv>Vg{R8FEIMhNAQ32*DErO%mbyQ$^jz$6;DzKko{v3G=+jfi|Ycq#QwG zdPxrWt+^@{lZOcUUoH9eTnre=RXkTfO5gVg~X!)c@RefYPL#Nl*b`^M|bt7(FXEzWw*gj4L>zGUW)tNGSC;in7hws=eJ#&hl zwyzK0SbP5QvaI^ea{f|5aBr<_t0&!B<8+r57X{lr54{z9bcy};+sM|n=l57-QNyuV zDP5|&ArDwL2wu@tec_cb_8CsvkMty@V6QM!C%npJ$Q2**fPTKk$ylgA+~lXNA>|`{ zdiE%%PZTcBbuuJvdi9(-5_~T)Gxh<9CnRCr8G9ekB&-zcjD5%~{{}(+eca6FHA8k$ zb>IcuVh20OhWQ;`4Kj&14k_l3Cmx;mb4(;PJHB^_9?m~ri zs=}U&T3&38mpOj-#xahvyDR`r_gL+I#l-oetGvwGBLMGqu~qYZ%$x65`|pcLRNRiI z4}+D_KYqYDX1NRi*T`uenoB-Rt}po?DO;bJY)JdavHU2?C6nxwpk?~7Y1nAjDdF-@ zh*=rK<1UO##s2yWB6ciL7C5+Omgfi;R*`==vQyT`qVa-Vw{xOR-J7In>0 zTL#&oGhL%`w;Ec60@V2TyGO^O(IN}YFqI6w7Umw#QO)y1RN3Z<;_w-a(Pu3c(Qlb&#-Qx!bPqPUvX>B?1<00` zN~V&IK2?&9Mo)U`lYVH)0vFy%>}OCB50qW#L60AbZo0ZL@GBS5SCT4@X)y;%&&KAT zsfiYzTcf8*de6k@r}AWNb*MQQpdua0n4#Gs+-lUf$bV&@8k!65yKm(4)jeb1;rY@X zbo`@FRB2CkN-Yj0EU8h&@s?a_5jS^A3BUPWJ22q-;svE2CI(E#BYk~bzG!7*Wq~4X z^u78P=tBoyacIx^!%r+rEqy8&W^*L&Y-Xj-LD9|MC9URSLh97#o95Z~30r-0gmu54bcok;vmjA&xN<57UaZhQm<3ujMr#ER0UW{^7tIcHCp6? zlApP%UCFCBD-1Vjh6>6B3g5Mf8p5)otEm6g7MYSJmVCr}Op6+}Uhu@-V6=N??ZLW73VX?<|5+o==I zw2gId=De_a)&JRTjI!)hnc3_kUf^WdWyWEW&Sw?LOdh56RSP5YRdaCce|F=MqjPJg z;Vwcu>Ar6_#`my&6MNbzl^Pm!B>B#fj&r82A|nd#{@rmQuurRE?&lYgwOq{|YigeD z6x)>%f{gJXLi}lez2}y%$uqWDebRY8^I|hBYxO9C(k*%)0MMEEHceZeF1C!Hv(bq5 zNw#jlV0FrUFD`8@=*YCS7AeQ9mwkEUUxk@|{=?EMUZ4aYp}S;qYh2?~?NQ+>%PbCG zt8eRHTyNq2v)hGVeQJ^0h%NqdetzG!e`ACH?T%1!Xn+b#m8PqvonzEr6RTXE?)jhH z%1(*r7D{(5lC`rY@R z3ItkLHdY!woZ<|yKV!3M+-+0A2t)sjdGY!F5oB069Y5EGk_7rK0sqYj{d2_y%16mu zVD1Ld`7i;eii_=V0IQ#V*!c|ZI;w)Dy0a1>{K`y;)mi~pdZcSed(RVkErNI@hIl1{ zXsO0-!yQc}#5`m*T$S;VIC@j+Ts?(1d*KoL0|)vB%5fwQZ1}Sbi11$dswxu@v(&ux zOj4`z=wi;fj34RT3B)xP{uM#)Fo!q`+77|$!hC|fRF_3-!$w)2n52#Q&l-Q&q@n3qVx;y`D^5p$(Tt69?2$`6+emeF=`WTH z-&8uK>)XpWG7D*CZ+VZuW_@a8X&e*nYc%{`M zz^X%N_1?N#)Yx&c`-X?ODE`M#EMJcg6JdBO-SI`Z>3f8eON~Tu5mSe6YRgx3 z#f&-NwIFq{niIW)l7>M`F?$A?OZ!2Lw>MP1Tzf`Fu8dHHftH)<6d5e|1m<$pZ#%L;J~*LMfrK9 zB33dLNgM&5p+6}BvRToCHE5lrp+D|m5SI_s6X>nWUd{z%PrZ>EDy~57y8}dv* zDC@DRqnoNv=*|@5MP$?AE#ZH;4X%UROA$AayW6j%|0VGq9KPR&gx6HP$GZ# z-Ma?FZt*k&%~_Ag+0`&oxgUh$_P_%U0iExGgZ6QyFRa6@VSLFyjyJ{(&yZkkW00aW z;!Whezg7x%Ty%sX*mu+H+Fznh|NjruEUR;8`NLI>r zc`B6sfOQZ!62hlk7!(I0H=d??o`0O$-X!&7+K_c(`WFIyzQ$7skzEXza}hvv#n+3# zTwJ|rcZhesMO?LM)kX@VrQLm2-LwU$FZWMBM_i724Y+2< z4n7P_DB6h86C3t?HA2}1EPdg?FS>K*$;@XSFm-~hkHu@Y7o&HypKLAldOqD%a=4o! zn3SaThW-Y-n#OL$c%rk6-fry2p5bE_Vj-xxO#gakhV+~D+K1DFiL~hsAGB6BlrQ8f#q#_i$ZkxX^bxC~{C{x($bJRbd7xFMKP>BAg6E7BFZBdYcY?a5P=yILZJ zzfH~NnN-$$XdO1PRa>~T@Q8pjJa*_<<%+t@T#%16T|u~+>i9};w<9s&4&>@wP>+tP z^>Qeriix0m+mPB)<;v}@R&*|;UJGya_L(8XZK&{=eBL6H(RHXAShez38KuD##%ho6 zoF2F+&@$}D5|rDvBCAAeU|?~X^$hJ|VpTtjUIsUZQl-c`%Y$5c-nfla02M z$Hk8)s$6!)_vy}6_r&dIV_TZ$X%?0~%AJa?K&4-3?F;lYvX_JJk42f8_Fa3EX@tyU z9LW{Z7Sc#q*_Oa$m989h&myuT99HOmrO(Do(cwZuDs>OT+?#ynhOB?LiyJ40BInr|cD zeA5Enw}<*rESB;}58l=CGgAbiJsEAJgW8I%A>yk;$<}BF*Snk21W@VH@h{gz-$a`Y3eP2>CF-k(JlT zFG8ZO+3$TL_+(k)rRN@9<+}a$S&sgdad)HD^hUo=6V0TU#;m?Kw9~zxK#Io~#$`W( zcPsWQCupz8HrM0+Dr#h1;r?rQWd4L=K?WzL#zEvDhe~fPSRd%``ov2}`ldKze%ud` zdUM;B&HAvXYyI(MzdfzPa;wq&-sFpw%G5RywW3AD=DNm0?0z*FI?+O28$La6^uX2( zv30BPs{5_dh>4L~L&h2~KKRO+mfV}c{I}@dKWt%y*)c;v3+4hHO=tJ2zdNtRahtE| z(xtRi_Z+wDlwzbHXVoB+U!5L23=^#iL+=`+sV`ckH6LY2NuOEyAzyV7J$o~gJG+z? z0(c-vLsZa?J^HX~tfqF%-e>umcMAHK`>)C0!h1`dpw2W&x1uQ)Bx_uN18rQZGf{}|*bm*m4A5LC zC|pqID$=f6#iThNS`;lRf>TS1Mr4^%A*8BP|2|zYm2K1&Qhsya?L0tI&IC9E7MW1~ z5u?lCq|3gILGkn|2WP-j5IQWP=h2}<$^t^x4SOCSJc*>)9DfM>HlLT?eT?-)wS73( zD6r{iDHe0+_d@ghRLr6IoNrng@>h}Ix2)zAjS$%&c<8a5ez$-WyxV(hg13nN6+k9o z3m>>cG42{kH|&8V^;U``&Vc(}qSn&ZuNEvl8R24Q`{OJ;+jelU_}B>BF421yi~d
k$NlU3TJDc@i(-=HxeZ&>q< zl9nJ`ZLs%@l75$&?80n-Vs^64hF>eR(?(E!rg36v)Im@>s!TKIAAy47KjvozvRe_~ z&ce7yq12KmQ`wy|R_#}g);FZY(96z=BX!Z-`Kg=r-LG3Ief@bQ;r_g`qC2m3Nm{Qe z+&!Hl1Qj8TC%M`G)Y&tFmLwADV1SKc?PO=(sUp7`7(5cj+KJDsp!#8SW_O?UB0g}4 zT47>Zlq6D6`zBUW-Tj1u{#9WJXYxKPCH|5sImC6<@^xst@z!Omsa@s$@|6#5?slX| zqn|V+C>oP*i8;JT8WUX;D_s_A`^uCA0lf8CmtvUyn^Xqd!AzZbgwo>gW9{hA}cUQAUiO|BO*FPptg zW3tX}vJPf3b|tLNmkG0uK2zbS^xgxq$xiT#Sn-e0Ny17)sA7e}G+7KkMm3ul)}bNL54jLmW-+U<4-i+N zq+tjFLwWh`5(Gs=tcyr;HCgyCRZu0q`+YDxHXUg*vim8~fI*#yJ2<>%b$NekW6hmj zoFUSzCaFau{cvM*Z?8!{Su02lJsNQ2Te4)C?zcA3Hr*FF)I>`t!4Tq=PA}l|ElLPs zI^7Y0`m!Ccxi?rBG^#h-EzBkNPOeE#=>s-wscCL+_OCmoZTLGmrY^r86$a;_;oXIo9g8fKW?X(bu04<3teXsZA*LRyBBN~Yd9mQUUfEe! zX4{^s zNL%0XwSH!Fk=lIBuU5#Ii8+leMUw^WYR(hqWr$^$!~3Mp1Xv64NY}sPDPC2wplb~A z^W8wv{@i8|-CCYBh>Voqif8lC*+?}Xefn3jy%!`fa_H;pcb@A=IA}K5FJNmovwjYh ze&VQmtZ7dt^VH$Zkjc%x$mG!}g=F>Nn!#NN*^p=sP(38U_5B6rM`WG%c zR3+@|j~w~>BKCGO^-O~A+qfAlEpaa%1qZy}!FW%1?lU@e?jve_TwKyy*P3#_y2Y#C zZwyMTN%Cm;g|^+YTKxqV8r-T$rm4xd-rrcBor0~INL!B&XgAl-G5Njqe!1N|ytcU;jxg9tWU~>o8RibbUNc$9-=^Q2JzQB{V*tbRTkAzhA8q<7sL3w! zgj9~IxUZP)S=x-MSC$`b=j_$g99UuHBlo654n@ntL#l&-Db?vda@fANR=+U1h*DR- zZSnx)G2QwV8_e!ict-T;{h0TjJR;NtdX6lI){ZiY5viiFx6PdP?DpkXkDHOiO zn5zWrwc1^N%`x%gI=uG0nf9rI?$A_H+yiVbY06DQB}(vUsQ>EVEzngb!CQL@`!}#q z(J5TQ8j{6vavF`T?W$UDH+enNxq`E{!}P30AQ^kmMPF`#Bz2Ov;JV=^(z1RUSmhM-{u;_qQl^E$s@YogUC(TcNR(2v$;J2DW zj6-|&^|kT!>gae!TAPsPqfx&;_Q~+A_Ay*ZEV2 z_3b#sFwH0Fo6^JUc1x;W(h6=@eXLKP_QhS4Ro3e}i^d(f%jfQ_I^mdU*~YnY zon){H&0J8;ih5^w)i{e+$oM%s$(t3|j}q3iefDB*v2_`_li3BP@1uIcn~d#JHCet; z#h>jgV<&jyGTbuZGcucJv+G=pe+nD_bOFmsBP~1O>SC9i5L78ur^$E>Sdm@jUb-wD zmyDlxWY{-)f}PPzjLXw`ni=fgc{F`@P4>rjf31s#kRY&g5kKMPH1GVabSHJ~Uu zxZZg3MDzL2yDRH9owoz@j3}SP&~^Dlf&zcVGfUHMUVs%}ug*)1hoQrvne!636#a1pV>o;KmXW&D8_9RxEKz(L>Z zpvyB-;0w&Od{E`9U#a`_NN(488)2j1-Rr!_5Knc*F{C|n%XwJlk8rd8cH#M6gNR>` zh78>5A8|1IQ`4wkiQwk#t2aIszpr5OO&X)evU0=e%el0j6=TNubw&|T!~iHRiu*19 z)-LUrRC&VqRNc7v1(y*q@}J)(uLiEnlpv*w2BwildTL|Hffzkf~Uf+;VHh&1We1IA#r+GAFsGi1^a~W;@o+|%G{p&b6U4{em@-E)R z*Re3{;d%a#O;Km+VvWAgjm4E}&=n1tm&gV-lP)g*a=VsG1``U@^gl!Mri+RRe+Py# zc50kYoc*pFjwS?q{7}M|K^f{_-pG!W;eRn>_j>Zl2A&1EMuXuG(F%5bQS)%?R$4Um z1|zfo6EM?xkuvtr2HNFtFy~X}*6dx-Jel^)uerZY`rpXBB%x~FwDFAI&=y&oTLlg37*rDDPSWX1H@@)}hGUI1z!L&K+@^ptw1A3FEIJp>9e1m7r zei~GKHb|EtFT?-R%tH)Ma7Bp1KKj>-2ZLia>f$vCoV6==Dijh&gHn#>ka5`N!L_!V z4(|Nd;WN|09#wBHm|IphpMq8>&IsL1d{n+m1jUq(aLy%TvaIXuv^NJqx%=g2 zjgPVKeqQUj&nHx3_<|}FT1558m3hQ!6%dxeOJ~V7ku+{EIl~lfL?&udJ~OU{{VMIV z5%ZvyhAUvA#M!hTQ9k332F+YMcdvzyvFO4nY740ok3_zZYbHWT&+AA%e8!&)iuEBA zFATtS3y57}EHb?Rae|q8KuE;Ah~|-qGleD$H1?E2bCG%Q(iaNNO?F!USPFj3<>sn7 zj85>wXW`d43_r#`DV6M$oPRN`O{po@kC}F+)GRaSSi3@YUioXRU-rXimaesaMGv1T z&kwJ8k)02Sm8-nQ@d5$HugF+5!AWiLg8q?+1(jxE3E8=%N^pH6JFhbZI=FGU+0?G~ zMIh*#8e`EX9_n(F`yVfyqb@hP|MAl~>H!y#-?FSPMaa+Vu!j-50_H61=QU$623|<{ z1wQJ5OO=>UfPg7Hb?VVP7=z#mFd|kF?Gs=`BUW92DLc5#?zVpXBafvBZwxaW8|GIf zY35f4mxf03wfC_vKAgLkQ(&uoo3Y5q*GJok(Ie-_HErYh7fx@YczE1xV0ts^tz+3M zX6-w=1u~iq!7teYlX}GtduD9>J@*I%_mxO)`lcFBj4a=BGe*j#Y3;3Cr%^I%pnRUy z{ucp4N~2fUuX8hHxY^>g=K`IL2ATq*AB&eqSo`(yjU)vGJThfGF?d)Et&>T5#McDwzvD+2%ts$Aafgzui-b2T0`CABZSZ_NjAPC0%LUrz+{n0ev5)M`Tr;^uNtLssn1h|K1waZA>rqYtA9>v4 z_6jid>Z*Q~<(LovK5mXV+P}bKXK_2%1ix{veW&e8`@Wq}n*K?nTaWv`s;K#BO-5Dx z{Dr}_Q6o7__sDhRsbb|)3b~z`%UHQRcF54a6fXcymFdtXp_X)Lqfh`G2?Mxjkp;Nw z066^-`jM2A1z$FXw{wfHbyV@M(z1=6rZXBPt-6~@B0SOinN1DDGBVk)hhIlP^81CM zgQzIWF&41}Wjb?2d{tklgChfEi=7am5=j=SHImB&Pr02yo+4*5hq_xR$I>&9YSrY$ zR6h>$Y4a7`J2=S4&J~UN5Ln102A6D-4yrk*0_VdsPn||KNJcPok!H>#>#;>95WLs7 z!H$da;oYWoPEI~mRiZXYj)RGq+y(*s%kQQ3EB%Ws)AtrfF8YvWioZ;i(5Ae;nh{i0 z-EuIoJheQ#yj&lVMYuH)Xcwt0nx%}ZsL%b+B!~xzcG}!VmN!(r#Ow#TBB+>_D%MeJ z4bgj>LyM_>W$3N^MH>~&!QNQISe@i!?{v$p^1l)cN!}i=qBHle#0Qzaw>*BhN6Ue0 z_`DGqt~^xIO9vaq|C20+&QYRZ@Hxt@)KPr(Q7O&Q?si|3jo3H$_E&{TWhg>eMOE(5 z(0?U1hyYAEZF~2K82iLf0$tvK zXTTcaU`nKbaIM$In@yOpk-|IE(x>9Tk|oD}R0rwa@Kui*#mYd>FIlzFQt9RgL2g4m z!*0XFz5kh1Ghl|=3~_^Mn;c7;OKC@Qgt0}<*QKiJlyfrQ2U{i0z4`9QfA}X+##b=q za{RnwwWr~B=X!ZL*H(JNy}gyMSRdhw0bBb9@hG+^dRJ7ROYbl1;tGyD%-C_#hX3n+ zWSB15=Y1veW?A@w#GqC1p0&GpdoM}Dbd7k`1wPD_%wXFo+NlBSXssyupV~-lm~isA zy87Yr_U!FP{c_3?Xz-^L$O{<%uf#`M6RN{963m~6IEpkJ9rbv$SW|O2vjU%Cl$l08 z{vAg<+flxlGWVa!Xk_XdD>_j}WPBj@E@3~fq(IeLY3sYUnOjYNccaD;GRiHUwkzH{ zT7AtV`0-RT9ii^~L(i?tN6vU1(n0nydLF!0d0YYrAgRVOw${1^YYpdF}nv3J=36Ia#(8gs|_& z@IUTjf3LZaa?te)VUz9!QX*-9+r>hE>JD*T0g!Gb5nBEs3{YlT4U%48qK`e;-k-WZ zO&&+n8O`1qP19+q%3ymshLq=Yzjc3E+QX*d@78w%NnKRL=|?GehEloq$${SdwdD@_ zU?Nv&#P6p|OkccNrL?gNDOhC$NBkuHtlO}XO9&G4O*F=KfUx*YfN~j~$i9T`pI~5y z=%=BqKLk;hP3U-$4%wY!uey7^`iejSN9}S{w{rY&6mxngUQ*32G_I+X?6pEOV&%7= zqd<(rL&HGc@TTFc^`11hK6V0#&(2*%BTM)!|uhYWO&9F>&s5J;N?x z{O4M;r9U)BV&u2qgs5uXB!j=Sf7(@d#?vy{PiRc8Lg-`-~tE6Jl;3>oTnBO^99y0D^B6 zs%J&L#5*24A%Kc4q|{{?g(ZKfTUn|+l^W!^w|3Au#PaQMb~`@xmz?fTi>G7;wADH; z2I6xGD=tkjBr)%e)n2yECMIpPWOfhQCHYpy2U%chxuj4l_8jW1v|{if$wpPzOXAk` zD8eADxq&;suR_PAro)ABrgN#YuXQ6B>E9GG^5nNuevGeIN_5{d^a0wBr+3kF?`7~DqYn5CuR!vT z)8nX^Vx%F1@ME$GyyKw|{=8kyM|UiR=5E4}LnalJ=;^3MQ^C8Vv$Sx;8>7R<^MBkP z7Ahv#cm0~qSMzlER=BU*cHRedA4J&GQ~je>lm(TZkT=r1ZbUYPzbMpzy_6*NJ4 zi^OMpR_F@EmW5Fp!(z*=29;%-vPIiZTLm33+ z>*pOUBZie0o5~2mDN@q67_8q%{`mnX=T^U{hkDubJw$7(gev;++g6Z*=YPjNJo8a{p)R*o1n6A*(M)?{Oa)w~oessg)toqwfh8 zTEA^qEnfWoN;anLOzq}_QAxX@_1i+a@nSy$&Y>OMLB4pKtHZh4l?*4#UNB}B2+e^A zFCv^|ZJjHIsWR!S95a`8TZ*(8LYuCL{sTIZx#vous%hnT;Goj{v~2GA+M;mz(g zr1Z`hOn1H9!vkh+4SeCrzWMb6J)&)9pXiavH~+L`O;%@Xl)S0%iv+L4gXw_VgFEx) zC(#U!3xNhVmD9QAv`NmCuBi$x1hyQJ^b5tvUooWfnqj^wt4fwhx=s1eGD7G!Nu?d? z0}%l+K2Nbso}%KOX#fYSX~FpUmzrNFXBFZa?eV1-JH6pFpFfv9Q7vG`E|p|B!dELp zv0u0f9c*>1lp>7is#)T)dD-assI*DG^qeoEQXB433-Q=jA6DU%6Y$+Ki&eDyG`z5^ zkv5WC%$^*)vy~QC$F4?tkX2`)_v6~Zt=;XjDSb;GR_w~|OlJOv5Hq=ucOxzO19!1* zO=d&qYR}4x^aYFl5}!GIY?XH*e3h+p-~Z|*1A_#ON6G*9g~3@!-A_{1p=5$}iKA+}wHZSqatt#G!WLD~F4BYdYxn2e8He;kn!Q!Bs!8a(#|;Cg<K7vGI^D*IX;yTJbx!IvL{VzU1ARwynVPl9=sMkVC6kFdjlFQsiSuP&hqf!pn$;| z+wXzFUr+VF1P{l@P85s(D5m^4XK}C#cd95tMss*{QNlAe=-}7$?*xvyBkT`n2d4Em z=IF*A_hj@ect-znw;rh+lq*+cZ*|XvWKyv4K9Hp_HwvA`za{-Dh-Fz0NF+^Bzv6y` zDBfUR$WscCD#FBQx@IP|q4Amuz0J^`giRxq??z@A{Iq9quCV866jq9jCDiSvERx*S zVUe07^HHRh?HgrHtQ722sGI&z#)7sTS%|)BzbaY$muubU;5m}knG$K=xz5|Bb1{Wh zU1O=zWC5wh`>1!4*2ZVVg`k77;OK3J3gB;W6J1M1aDrAYlwxwGQxR6_yi4Ng+~<*$ z_L)b*1Ra-C=Y4#5Q`zWSRR?|q;n^qCP5$>9;BLzQgcqqq8cj-kx+q5%s9I~4COBi#qOJ8$u6g*HL_B_PMuj> zmnpl9o!3pz%sj4#0+QHIO44>n1r{gsyR>_@axq&KJ*)Ha_qnlacdk&XHU$Tw0aobR?GPTME1I?2&Y-KLuQ!LMdHB%XgX*I;^n z(X%P8p!xv-hL#QWe+k=`^n~60s`)9TDkLudIS+epx0lO&C6Yt{LvWJ7dh>Ngm z=XbPN_IqFcZ6PH2rsq=&R!8gmV%m{)1yiSbMdXuZDA5-U*ujuNi))~+QXEX`uiN&7 zMrzcg|1)Akh~tJf{)`uh5zB}$>EGjh1L`5_f$<*qa!!LdG%()dUj7*`nx_qDZqN`d z1+aX9A6QbsV4DxjFUFGO>9UhSiMo&f=uRRNfbQHMCAV@g2mNBGPukq>i;FhuHPu1r z@*dmqj=6hUFNfz!Y`0w&UabhYsB5=hYJa_OcI^crtOSX0==<_8G~;{vbEfwWSU zc`g@Ut2^A6J&ZxpTUw%G3)~Wm*8PDJQ<6nyygr$u;F?qS9g5dLN6&@DHc=`>F4yEg zagTYjA)U+W$-N$(9IXR?LmwaPYXl0C?AJGIztB)xOMVUWlgph%)d2{^2kf2P0bbwd zy=MxXliEcsZN2&@iT7JN>S?bYEsu~O&vJS`IuV*NY)?^Xo=ktcNSO}Vef4BCX87>E z%bR4>=uK~{si_R3&m?Es+c9FEYh8lf;DwVH5ATlaIxq1yIjNS2f=FI*Moz^#zz2oq zy;Q8+4Q^N_edc7Ut_A@MVV=m77ZoAvK~UfT{Zy~sW< z-@g)@sp_1W6}qfE{_c{3HH05(A5e5rvXHIVdopR#YZu!4vX3p2!2)pMdlxlFFo z=diEt8X!!fN6rc6(b(t-7PLZ@s7#;hWHt+V&M;fZT4qRt7`8PL%zx}JQ{$%~a&+D^ zfwOe}KQfnvOs*<=#)VFPSA>*pi-ORq9^dX-`3ccf-mg6w-7WIBST6dFSj*zNIqyyq z;}v{kSNs>dW|leD6ZH*Eci*K`u3RQMejhYhy3vlGqGa;UvWv&MI5z4K-oDq#M6`d; z0Q@Y#e^XxKP+HC3d(%WR^&weopI}U%AXEv6ilsKn8WE!)j@>|F41(ct3<6PQ-Rl&+ zQ3I&-%iRZBcG>X6nnR<@4FBB%SB{0vBdeugUmPdtkX7k{Nw*kT-sHBq&Eby+ir0kX zbrX^uUCi24rY02+cH&?0EDwB8p@L`p>#FaMEKFIeG~a9a@G^6>swU&5Q~rdbb!&0c z0n1H4v6s_cZ7=It&EoVZpn{zw|GsdEgKpMoWa!&}UB{;_;hf1dXb)E*{2%*_cz12K zY0chftNb%}ve2aBQeEK};XCvAk{)w+*wVd){SOmA zQe{pD-+9(s(H*@T-+41i2;netFhFl_o{TYji}oGMg?FReXJ6g%Q%w7sI{aE51RF;3 zi0S^~Qc@LL*EgW;O3$w9R>lu1TLolx)|UEIZ0e_nyDWJvq*~|YR&|pej&A9v4-kgt zuC95}HuE6Y*3XSwB^@HGefh@G+ry2obsM( z>OiO?Mf<{C%DJIU8+fG%?g{C;;?+rfWRHhO!5Q3KIS=MvcJbijpsEY$a01q&kZi+4BJ=AM^K8>y_23S@Ql*4 zsVb0ozH9-8%1!|We8QzqrDx&c$2QQ71K*Ls%1+VT_W22t?8vUc@A};D{4X76AE5qZ zgQ0hl2U^IC89o#IZ`c=tqub+iYw*6zl=CG2>wWp#k3{oW)*mR8o&7l+W9 z^Re}J{cnhpeTS8q^yd!RU`l4jI4Bea}axJ64 zt8{1j964i2p009vK~Ar_xI|joO^qC_FQYP@A=vtNs|b+fUMG z$m8A9q==5&&HAX;QS04vook~IYI!|KrN@v*7>|;hB`oMpyyjuMj1{asu`V~%%YC#p z-3dcQ_IsOk*qrq#D^AtxJ;N4=D%(sB(X$+~oAk9SZeYtE>=vZk8>Onhqy9Ea*hSp9 zbg1xcKsraGAnQ!i0>XaR?RUV%)+fwZuI}jY(~!LO$D;(+dUaf7uxE{;K}OAkgPlv0 zj1%(}&b3opvnwBOl~EPPe=UISl?J-{d!4e|A&EytE-Xp<{K}hjopxG^rR^P+-l3Nrb4-34 zPbxj(s=WE!&wc3gu1^4oj@qLHzE$o>g1?;8ZIl^I;o_2rgpzWY6ZBc$1B7wMh8h3u zQXlfpjr|X5s<7YOKAkCxR*2HYrn&boop- z^y@Hr+YKlr@%2TLHeD!$o6Ijdx}QAYKO-C^wa~YITr{5=Uko?8#-7b92W1iDqcdTm zGrQXQMuTv*EjH;?*N=>k1TijvKHY6IVNwPp^HzlTOqufnPt%c##okVLf_y_r)rh`M zqi}bACEsIP(=#@`VCQZujjmZs>aH-A#vB&x7ltV2y2$ETU>ahzSXx#dpUyMRjIhe< z!CFtj`mkyFs<{s-YI1cuQeMeyP1m?dDoHPfwY{$M4X%ymER4xWwpkvy8d!BkhYIZ{ z!Zp@vu7qv3pP}x{!xf9dxOJ|hZ=>jsO8^8jS?Kjh*nS2eIYf-88Hl0GexHxe;KKoI zkti#b2umjlpkgw}fHN5fr|S!k$>4*wEnFnl37j`j1JQXiSNg||^hj4HqOcjA>BNQ3 z@O|Ws4T-t6(aDazeUiRg>S^&A$B5O^8Wl1A1Q4P{G&0SA=Gq|mrK{urAVUA{yjf!x z$#LI{3P+~jswC3GWB=}ug9sNf+(ZiS)<7p-6?%mdw;duOZX#ZxbH{Nee~rsOh$}B3#FZB?L14-Mf?dVzXEw`;g>7Jp!6x{xp8TZ+VspR* z#$%`-sU1y>O-)Vb!hhfR-NEqsl~|;6ZAAW?Q}n}oENgN{2l<~)l~pzm(_5zHTa_$^ zyZrWhl*P$Nh29BOsCz{=4w2_!ypHy`j8ikCe?o@yxXg*4A{(dfgJW7q5RbrCH}RJo zajmENMgjwtfH%=S9R@2av5p1LZ2EuiI?q6zeeyUMsA&ugpGfX-&w!Sw`&N9SIYDEh z@$=emqv3r;P)lh3kMQZ|){5ui-~oSx%nAiS4b<|hH}Z+SoD5YswgLbFUU&UqK~Mc; zN56sl;$g6-os2PC-)0PmKe(iA<@eEL#6NP{nR#Rd3^$w0;`dQJ|i`cf4w|vbQkW_#J;MRB4IP= zPT@&Bf%bhnwO^o%HMw8K334>KN%c~|HnE@vF8KSVZkg#whvPkwNQ~b@@`yrzsWkjm zYSy1S9So&!BibfpX`dCDzJaWI>n#lZvvw~iMcSz&7rh;T*O8}i$6!A>A1TtoTP28i2q;0{JNSY4NL?Hl? zDuO2ej^UD53?e5QC>!g~r7l9!-Di7$acUHU51byg9_FBMQ=O z5r{>JbMK8oD+K>bpiuz$yaEGXK=UL4@_zv!Xk-2b&$j=WwLi+h90AGz0U>GuQ|zWm z7q?HMrT-c{WN)gjz&5~}x!u`AP)i}l! zaUI78L9=$;XGRGfWQ0(cES^px`NBN~q`(Q)8jvdMfe{I^Cw>|*|4clw>A!mS_ke}} zOu&DQXu%YWh&X6shrnY%>=0Pxh%<5==}7Div4|4jSjX#iGjR^~aKy@ir*b?P)t5j( zDK8T6Z~(ajJQN`qN}Q= zF4+u^SSeh~=c31{Dc=(PY*pu#_9&g+7^9-IRm_&ZxFp6sJcToH>b$#b&u6on2dts3 zpAD4pto*9$bljph{hL*;ek;|B8$Q^j<1Wei^%mDmg^v2*q#s4I-2a`>&k~^6!}M2x z*XrPT@F^Vl9u8ZpVU2~PbfBOqr!W+oikcv%OLvv^VE~=4%GvUn6ABIEkBtII6v}pb zMpWUuKQ`ya;1*!_n^)phecJu*eN*-~XIOs!skNHqXd z_-lEiFQ!MQdkJ^u5V-<4f9RZZS`Bw!)PiZeOKwwX8XT~rfgBJpSleIviO4l4#*G5_ z7T7$Wf>T!azsCcS4RkLBio4JM?R0)q>0Q;Hf2!l{WI%&bziWi_C7uzLquHs+xrN5> zaPR$Yx0)LdQc`-Az(+}vMg}gqnWbsuU31R4=~JZ}CB1KL{gY1Vf*b!kb0<(~y>Cy& z@oYNhs(`13C+Ts(@yb}QibsNldaU~5xC`&!NgrC4$>#KmEK^Ng?$hnJPeQ0pugEOh zurFHhrcwUZsaMtc*8ND&8J+)hd(?r~x;ITmJWe~-ouLNjRwj-#a|@VE6csuDDfkUx zlxEW1t>o>eZ`*foG+oQlZgF1U!xtbS!d-{$FiO0nl5IZ=!;GtP^~hGOpj#w&vY@+DlW!xp!t}!9 zDpoQE%0gKWua(>a3&{Anw4#PYs}vLC)o*Od`_U6bOl zP)h!z+ga~$zi2`pDo*;FEz(+)w2Q5Lh-3zAk)i8{vM(=>9l8rYtP6rEUUf>hjM{~m z>Hh>cF0N>wIq5r_D7ZOO!UbKV?x7@?Nx+jIdDRmak{|3MlEfYa7?Tci2 zf0Y9h`cKhG^b1`|958x70SXvBK=034(SeJP@B?8Rm*!c)wA@=&LtRMND(45a1G@n#0VhqW!7b6Qud|x(?^UBrAv0+G;vz`+jVXM4gO1$BP=+b1o zoYM(#+K@|*o7@H7FHhV5;r*_(R08i;VQO$A2=2<9{RDWuG9Y@Z-h>H!3*GS6|yjHt9y zVkt4}D&HxwtT}hNoycq>O(YpgNZ`@2^6`K~TKRK7AhXRki~t`1_knMKvv}{vurW7A z_h(Gke+BOmj?%=AJuiycJv>|DaSks9?%hhvWTOs~{O_(tM3Vk_`7D}l50g)?IgBG_ zm_g*&Utc~Zr(wKkFoqz4Oz6WkmghimnNm)*j=jZFtSjrEiIa-G@~g88@8(Os-yaos0=JKZ5vQ>2(t{_= zets}^fAU&cVM^&0FOZxxCPw6fntF37f_*3^^-wQ%#*-?rT9Ldcf4znInKXhBW(rmNgURCbr?OVQ69Crq@nW-su zJB<}M8B-*#2U)SPK3V;f3D76fCq>j_4P4=oOR0ls!I+}6NKZPUn4YVVoQcwMtAmGrps>?CVTi2qBa^r zS{f`5UM3~yTJ49H$hF3&%AQRr?=CP6o@a|pLLDtFj}8R~R61{df75zy*SYrd=x0CW z7cp+E>bB2ScjU+3`5WWvX>9MM%U>T^4ZztZ|mF2x^wqW-u07t4D|!kKzYo<>QN z#uv)!-8f*V9*35+x!mu+NO3-R>>Cf#-9zh-DWUXe4^kz3>xti?!UFHe^6sC4Pm+6K ziHn$y{Dd0HOA7!(TST&GsT7(8DDknbU7T2QN`l@E{X6X%=KOFmq@by`b7` z=kQ9wAv%DR?W?^My9{uUU}CPfqxxHJYS2?l<-O{b+V_J4X3BdHoJPYyo|WQqs3pS# zOJ)cOOf}2R5JHaLcvp6ngc08xKKTDp*jRlm(^zfbVm}&V$+4%F8yh4IbDQ5Qk=txX zFX`KlvPIU|WM$3exmGGIc8eSDfPkbnm*II`lz5}Rj52G>o9*W_-Ne`tz4RMFF+8Ou z9tY8PTV!~H47G}CxjZI=b$DoDtvTWkD9g|n`?P@R=R>+^UXOZ@;g|mv>-SC1`~2J? zY9dZ?`>I|eE0~x3>8(DW{lndXds9|0p;hQnoP|eF-ZTl0+1~sp&&s1I1)$pLdgh~( zpDPMO(JzWgp)D3*0qA&;Zs}nfDy%4seU-w3zu7?pZ#qMUso{5`KnHuw@arMc&9K@;?KKRv zZFKF+({R-gqmBoLI@Jwso>j7-T8wx32m=ta?4fr@{K0V7+w1d)Aa`nPy%#GpQs=PI zi)e_Y{8E#j{Q8=k*gL&mEmSA5UxTjl$6cp`8d$6D6JLQpG;7D_RN4R_9S+4DQJBs` z*>keN@tgG2@PLK`y7dD&bv0%CA*lhPGpHtl65flWDD8D|GJ0XpZD{8pWo~Mdd->ZKHGK9y`B5o z5B|wYwHjSPvpmaU$k?xQzj{9_@0l$>rM%}SPloby$*duNl$#`7L3I>AJ2`9EzYv5u zRX15}L&TN$z!cC9P6!S=Xo)5Jmd3#lC+-WhIUnI8J*Dm%%^HCYfvYn}2hdtyayeoO zBx?@R4Cr|TKZv^A8pIMgke6pB#Ug@ zp|KZOc*FU2;8Fo1X_)U;xOm)pObJg>km_=CMNdVkPg&wHzi32~wQ|*u6jASMmCIaG zJ0829nrb!ZnQeb1-FIl_s)fn7+@CB1I)StYTt8!2_u4NIGH;O&>z~^F0hp`ZAAnfe z{eise)!vKCbJg^0&f zzd>6_pd4tq!Hn;rQLpQg^Ub@pjT(!``SFmRI`s#1nSpMkKf#ywr$96B-~q8Z_T zE=naCZ59OHem8b?cb@Xu@pkvMT^r{rYGN>Bqcj*0GB?Zf_>0edL@l-l3rG+sdhdI! z&J!*^Rg)uNir|PB^orQa;%_JY!;&}A=}(Wrh|8VvNv?K2d{gOwnX$0Ge}+3xblo?N zBJCtp`>#>GvD+v_dOqR;V(I3@LqLFa%hJ_MIX2A8{8s63lF=l){?&b``%Oif(;?E{ zzXtaypGUh!qn9xht_=aecX~?^Z-f3ug9l-05rByF5%d&`#yxWc6e7}x0))6hz>qJ- zbN2!PX{wV=O^)MIw>_kgLGq}%KJ7Wm8(%h_Xk(8uI;7w)&dW!Pdc;E3skxqPdPrfF z^fVWZ`P6~Rx@J$Ig(y|DI1wvqgcyPfWFdrpTMJ>$X4SvN^N$)eijdAYO)0<)wi`&_ zu<;ZqD*`z?lp)f2z`IG9!OIK3P2m>IdUFb$qtVa+*l=Vva3zreH#;HHVXORF^@a{L zbu|)c4R7*=#6nlNTXWs6<@zU|jMMQ&(HGqn@BUW1@sg=!ZuOTX-I!C$3Eo$=t|dEP z`DN?w9!1*_qx=t(b%?-elbP`xI9d#Y5{Tpz7OCj@(4&%Y^kLrhBHMfI_tCH0IKCTV zCC_Jyy#1REAzgm4ay0U_ug~1bNdNp|IGd*V1CNgxgJrK}!$lS+Yt&jESIpZOgbKZL z@ynJCC^Gy}G;}%XwKQEKRaTmR4qOA|i2oMjRkE2^it0Z+;kDy|m}z zptZdDrGNj8lXgjG%;Z_@H(wZykC9IHb6y>ZVd~Etq-o_y=~Kci6s8rGg|B^(w_o}Y z#L{=kPiAUv<9TJ^^lgSVRsOh+fwtb%mD{VCURi+K5ariVBG1f6M%0!44yzWDcF8$n*~ycTDLp6x() zcS%)76&p`Dvnuw0-Ic4Ke59#4=MUtK-76J1zR*ki_UHL)g5J;H>M5^fQp>$}eMM_~ z(?9K>zw3#n)N=Ai=HlsW*IhSe7mjtF>NY3*DhY049$D^qQAKU~^1+qX*ZQF=t*@I` zdFD;LLpN@ok7SeeJg2IE^Y`-;Z2$KMv+_Lml1}j0Z}QA^k!E%+%evBf$o`F~+Ovlz z=OdEkhNlCDyRyIex;wa*S(tCMC;O^MCSA_0lER07tBrhSrd@$qy@lb6D-{dpks25S z=d2qS1QrOQj`isFp|i^5F7IzBik>^GLGYCSxbtOxT=ySKCcJ}Q2sJi_dN(M9o^x)! z7*?oMOIJ`{?9@CGM7JMN7~q9(;^t}hUrei!wlbDKk1+O_!CGLO23fMX3vtH23q z;D;m2Y|#(AU~Tlc5WFn8gPso(K{t$O(@bX-fBy+pUmV=|&szNboAAE0m^yzuD0c<{eb~wjo_l3R?KMSq#qblIwQU|{bQgH3 zqriwg2S)51FlKi>K{3+`oY-bP!cbAFfXjl8u!ukfvWP&xtwrSAX4StJk>|Y{MSvVx zL;yFkh(KRhM4${=M4${=L;&yqTtqgf&^;Or4PX&LW&?`|GT>$>WD$8?R4aM3Y(uTo zyVU39qn|8Ml9s&RRm0`5Mui|yzF0V6L(nbA5x48%b>o$saQz@cg-_Oy-cDR&lG=WR z7)8H_th0?BCqhM!=Rj}6JVa4tX`|3a!v6l^Th*I0gGz+&gnDFYrc@K*%Y_0mf2%w2 zozN4xOn?)SssT!b?}Q%zXyX7SqK$(Fn|!C!akdPRn{)JgV$=3+C;Ev&RX-0a43twkS8`<1UJ zaeZQ*4r*-W^X5*TXPWOh`ZQ~HtlD(PL^6;r098)D@)3D~PU2k~m9^2o5dU%r*JiSf}Y#Gou%F(S~3Vs+N#hB^l`A;&t=_#Fhdh^5Va9PH|n9M>d+<3X4=Wyj>UY;Q7UtvlyW~s z+m$+5NEA}fQP~#O`31%QjXFaeo!nFC$VnKYmgXJmex$cOVfO`_0+ZbNk>d?m%MI+S zgy#$s*jGKr!ilG~(<_aQZ0e~9h-dwd#G=7K=fz+b_ui#7@uW$OX)J3vpZtLlyvutd zQK_QjPoEl%6TZzGO)eQKueDcqDgEjAmFu99*XTVt5ND7dd&a@Ujypndb>7vXVY%zL zL&LkrHW{2!`hj?FmgMM@wJ&n*Gqyt(MLNVwg=_r%T?_9Vc#u4D_#%T*(>WT<;*6^n z`RVxVURs>X@4Gk=Pc&ZH^C!`DcRVr?rL~zppw> zK1Br3KWOmgK$*SZp-_6iuhxX>PFWmUToNfLT3BiLR(#k>YUdyvROT;pIX-n6<`o`o zIjr6E-sZuC(T;-CP2X)EBs4U$E4L>LIZGYU8p7NOtRrj-eVj@g`q=v0!#V;Z%ahP! zd*5R>ER8*OM299WkLC65B@5&?t-)|p!!&Cb1&bxLcV0p=s{q;na0gR9a zbI@aX;*zpUcvMGTyXouIW6_u8k40aF=Vxy9Wv4ZS2Z1?}Q*UN8pZ3 zA?NfjfsvU)dF{qu>?C5v+o3K?$oY%yUfY80@?8%Y9Zs$764FKU3G>}|(`DcjHodR# z>H*6WbUpNz9h{c~dlA13+6N_RwTP^IuynB=qchvOYjH+njrX3j9Pyzln5XCSxbilpD@ z->SX~)hdP8lGZb=bbod{^{6k}?0=(|(qOsDRM1rTVNW_l+Qa(cJ(g#ERddG&q8$A6 zANIHjoxjY%y=VIiyp4z@8XxR+iGv#m<{T8}v@t4cp9IQ?gWF%6fr%IuKttB4q{1Ps z>=;5Mkvgz3-t+;E*sA=ui7i72D0=`$zb^(*0L72=20=5FAz~jW>z*0)L|SYT{4fS$ z;Q^Qs3lA6tEIdvdPq^rA4T@-LBq;PdG(o;8&;-6I2)cj1DF_burciKf$}&@$OtKk5 z;&P0K+X9ZCHE!Mfs|F90&0}vFhLDog4c~QX3$q^@b4J(&>Gplqj!#~Fxn;&;=ahb# z{GrlPa#G>uUN&x4JEx-aRrhM&uTGRrYE&IfcYC#Jk7qj&n>wK}=(&_r(u~Xb(#_ufeM7`fPPz4N8V=Dzp0LEz`7uv zf$9L<2-N|7f$D%VgzA7Ygz5mi|C8$2oC2^e&;VgwU^Z~?kO4P4AykJ+ey!xExFApl z1K;nr=COM2OgngY2wNOZyse69hfi(6!f!`2Klz%VVztv)@RN|r8u#=y^HWjVSosys z)P5~H!D8fby-68ZWwy1Y-BTI0xmJH!F*9m)WvH*F(TyW?Hyd;O9Ue{cr;0{D;$(*I zNtU4ZE+<9-j3s=XsYqIDRkFXgI`a+u7>lbnR`O?lRy`^yU7Nj7p(lHmXLeE7E31eL zS6{;ZYYCMnaK}oo6ope+axyMuV>NdYZ%IE?!c{dYO}EJJEgY2oQf`NNjv#SQ*s{AEefU{W>?fa4t8a zaMn5d;U*x)gUau9@J}y;X6^r+d-uK9Vb!Cddmb3mRYYYqE%gXPp4J47Wc*4s0G?yKkP9}GnT2R-A8eUsU^ddShO z@`xd(;K!5~rig{nt1QsJHqSpTrbWyTf&JE_r$I9pTcuE32<3FF%_yk%;JkaRQ+y}OZJy0_Evi=Zo>s4gI z2d>PNI_|6RXc!Ox!O=YWYI4$7w13c96bB|2frry!HCE@JGe+yTDbql%a+aHbowtK1~6&92#IOHLD;zos& zOPVw3+#st@Y2_`2wBlLD5TP__#073CiBLB>)%-mJS}AwzC#le_$|dXKZ?i54Co>`7 zhDHo-oPXlDhFh}f=#}>Wx6Sk@|Ac1GMtft`T(%%~+P4FHXT9QC*00~csv0LpWM3@Q zcV%FoT@O34t0tYMs?VvRVh*f46wVs$)Y)gVHsI=Em#oHDQJc`%r&uV_OV!OlQbM`% zlLU5u3$sHj-B#iA%X6njVi)lFR@c5~1g}Q7OVk315qE+{8Y21WuJj!wzGPBztuAj6 zVWcz-ciJbF; zl%!5yl)(>lmdsE68XUaesW~Z=YhzL+FF1EdYDp?Pv6;a$?gS6Zhxf7@%91IQ_ozhll@ffSfZw9&%QBuzj5l< zv{Z9?vV%lA%{X62XGfN$mGWvP)?=+*pNFsES%%{sYpYHw2vL@oyA6`P+Xri_(}*2S zr!fay*qBfebVH4^AVwh?g(L|+U8?9%5h{oZv6cI4Mf0Bx5F;9U3DEGbs@W@|+)rr= zx?O10a9?ou#jnk*H{Ku3xA4*kcS`(p#CLAldqu$A-NnmoH90)~{Y0%_MOj|s!j}KP z-}>k+O9Ou2;-x>8&NJr+-LRSV5(curs#U#K?)CAT_h^zF%U8j^Z6!P1%WkrM-O|qS zcl3$=_PJb5lU5qklq1+5b1QxlB=r?Ue{XCar=l30AOMU`02G1q$;)+xY$g=4OwHEO zxc=6D%XDRa>5UYso29)my%;r8`$o!t*-70wMSze)ZrjVleH-m>8jdjr{8)8o%kw-a z{CwU0<7PySA_2lLb3p<;>fu%KF+nAhZ+>WDHY#HVCZy*ZDk6_j-%DRQ@3CqTby{eo zAkXsNcneR^aZEmkdhdV^`;*(o=~K^quyN+)uTK$VdcI4zHS>{XtNEL=jdsl5nyF^S z&;HL;TASzx!G%UGKKqMrCB*s^4#!_pK(|3jV?`|5sC+YRSvpH!Cq_Zq^p+EzA6({{ z(`c82$S3`tGJ)eCc4pB*Oq55%u7|@`bDc=xXB+0PT+X8V=A<602k|9y;wdKA_MTI< zqW^Ng?#7jL26i{Xm!J)&Sr|S30lI+b`rV*s4*0M;K#Ui>U^gKAU$(~`@Iio&0OF$n zksimq9*kM82pn^DiSBlIYkJgof`8Gf-B}&fFe%=$eWWt{M(y>}J;uV0P5RW4q2oXt zIAzWlO}_ghl}M|k_Si+#0|WGd)Xx=@^((Zge9c24ypgq^gGU<8O^%Ai(Q$Db$g$}t z>U>qBRb`3&-lG=Z1{)Jlk!}#*O^qOa*w=3>HmAL3l*uRoAL=dN>sy|CsoCtjm=&y; z?XwMjbQVN=nX7&*9OHt>azaIyZXQM}?e?rDzKLWtmz7BM`VZgh^uu`vj5Qok`1YOB zLuE`5Z$7g}IGuriZiL4F!n2K)OyhTFttuw;bcvMMb4Ap{m%F4E;+?W|yYKU5@AN<4 zU48pT32w0WvpL?OPty>=~`+4ZXIIrrm}zx_&JS zXFYk}Biyu1_0Y7_#;*F(+O@tym1(CC@i_q?15^-TG@?$0ZFax_$olLBGNED=0!d)3 zJfeQra~NDJk>Y2I^oY$matQP&(g&zS1k@(`SoiMTqAd?iZ^wDv7w9!8^FcZQeGlMg zJ0Cb~Kn=+KC}=h@!WR=6XA>z&FD0m}J@>VNhu?|{Zg)kBFJ@JxceI@K^2y61>UjXC zO*Y|%>4-=s0jlt^s1bs7nUIRhDczwf3Dum{+ z#s%;C7tfB&tIqhW>%Cjsm{-kR*hu!EJO1eZiNH|msJ-~4i;e64?dd4G|kZ)Z~KWT0Q6%Z+@; z-0w}ZY+lE@zGT>G_9|sypVT@B=bLniCgwP9Ywt8WOW|3eP!S=Pg zq8Do~DX?%w-s19H>egRzP3Ce-oHYD#VH;!Gyl-s%nUAcq&8Ak#UX`9!98E3BC^UN( zlf+7=t7TS0Q)N+%Q;Ox^7oGjn9#`8w{0cvmm9Jl&|74Fv`kQv1@L<)wx>d45y0wrR zAT`VGiAl3MB4t(^AmISXrxt?Qa!Vw_VJ4)q+5i%SYAp_DKmxq}7UbL%-yBHcI2LWp zAVe3caQAPxS+-aRH@ltlm^ss+!&8=pDUUA!k0sk`)a;MdvD#S)Cw2)uLHoXfPSv43F=5un6d0$a z)Eg*Kdd(UrL1%p$;JhS^Rbt@0+>6R?;g)zi?FyW3#Ln>&+HGI9gH%dlryTbqq~m9Q zOk6CQa7&gGiN*UHfT3~DtwWqhN6(VA-gt0jWH_9xA{#5uF$tb07@ zrP}GwFpcEyF^Tt#4AS?POYvIZR1lUEt8vuR_vuzDFZ(RhGs;Rkt9!D8%xX7yVA3_Y zJB&o@)P1L0`{Qno4&D7717Y)vXOCbsoxMKp9!-?GRb0J$+@4#|%9P|gfZ4%>d>-h{$Cb!V1=w75WSr`ou{YNOxWM%RCt|1O$LdJN{s zNsoQ{Bo4bT`jmer(~x}Mp5IS8AEB@Z8+-E;gW?cxt3O}*W#`JXaoWwTS!~e9%o~0Y;T>8ZY48Fd414_YOi&q*t9vIJ(JY z{~V418Fr6SXF6olUs(&5~M{c#Pt7S8H^37 zwUokb9yCWG_SExIe+5LjOk|x*CWHz9$LXjZ14iQYG!)mfK|liDV|WzedNwafF{u8@ zO}SQG+*=+{ASZ&~-`G3&)&daGoo>)5x>x|RKIkO@vc4W2c_u_gml{ojm|Pfq%BxM} z$txv*Ni9J}@0GmKNTt$~wetdwXX{cmom%<)Pl<9gZSeH(|e zc276{@=B-4NUqsfkCCp)el>O@@~NctyoyJu>J7;~Zj8?9!d`l=v)4qgrQ`YZ>SfqH zn1_^4L?2_;7SQszuyP|@B1KJG;GV~YW6t3c`nK8vRUQ{~;4qg>TY%d0f`M~5zkHW1 zANE7xSL2-B_dG9Lbq===tYNtM;nKi)e>H&(r2v%8Q2tbo--a$#3BPoK3of5_%E0f8 zm-BX0ved{2!YVmMsq0ZtJSs<@mpzo zINmjPY4UUgn<*-6n5KeB>gD@|4=K|6nLaqOex{60Cs901c{iGvU(_U}l$Oq2Jn)9~ zv6<7Ehx>wvX{C(|AFMSk^Q~_d zgnXA@fyE?Dm5fv@9r~I>ob0&~+Rt}Ule7E17a-QZr(6?9xhZIr_jJv+0fW|TP|}ci zmpU4g?J#?t3unDclpMzJsoI0b6r<|=b?v>Ce%8@NH~J3Om$g*bxP}~G-;YnbM|?eq z4laTkWY@hhW{xX$w(JP^H5bBxTP>9YOYKE=YV6PLj~?(j5AfkGNMAfcinT#cxFr5Q zHtAv(;Z=_|@=QS)jT}NjObB3vBx&qFbf)p8Ir^G-7ST;STk|2h{nuu=GKyZylLop&5LjaiXFmq7M zcVIxod~BE!T;cnx6=mn+$(fLFj0TQm5Y(#*6oy;S2rf>$Aiy( zR4Mp!_@&>WB7##HxeQ1Z_w5$hj|Uu&?BSX`;}x^DX?)!2uasVjO(@6g7PdGwHp z9AmiGpSwiUHacI9@Zqb^PD)-9^e<}U5?D0$@$WHs57qB9P>#87q?d&k1&;_M8z(*S zFpl|2{f_Zo<)AuwJERpJ9TTB7X^t$jecc6soe#pzteF~nfqKBdHa@)e@D?W zOLA>u|J+jFODZZdYp@&aoaI8Zjkuf8R&w5H(98&pw)4sM&%yceak1lWoi;(EPtq(h z((4wsn4^W9;mC`-FR6O5LO7(E_@i7Qq`BPj{KChi>LQz&NfU2Al6r_^^FVk0(t<>} zddRej+y7;tyrijTt7fxNmdm0z=;mshUekLTN?Gm;B|fxJ=MlB&J4N`1G;B>bewFgx0wGWX!KmE-Fu?2aptgc6P$R$C{ZZW~O4RYAyY<9N{iZ7F zYASE~@gVo#pFF(xsE-&rGqUe-4u-_I9Uvq|4uFstIRQdq+yQV0dtLzSV{(<|LBd^{ z2lhL<9^=rUG^Y`{;$J6r)gLhc;5d9_$UKGR;jTSfT6ZeC2Wkhd7X`4g1Dhm!vq1K$ z!;b!Y3WNuOd-6Wymps_BC$GBez*YJO6FCaO2dISII_@6lM?djWD+xJ8wZ$rn#RC2~ zNC}XVAU%il;z%8b!Jcam#b9y=VR8re0F!iXfbl^B71M(RVWtNpV7_x{w5LD^{{z89 zQ&w|Vj0im|{Wtejsd@di=Jl7r0A6~N0cJRzd{bc-P~dkxHl`K^PH$fqoKfXn4o5g6 z*%FZf|4kmU=J{9nod5#>TM4Cu*Ne0T=uM8X1xV!5Q5g5%XoPX+@H=uXJ+_DA&XFNK zxEez%1X=$grC}7PirGnG+N&bzl8C zVm;~gBfJNvCT7JI(=0*?QEJFpf0^7^SP#d!zH4?GUU`qq@@{Iyi;IxZM)jHR3Cn36 zhS;^Vj^U2)XLA=054E^W_C@RVp|c{(sWJB@oySy(h8@B&<#sMEa2VC%28y_8|Nx7k^j|dDba%bd$XIg2*qqcKL)b;)I6e zK+#tI1j23=nIb^lqJ1t@dyAYHf>x{$h71Z2_f`PAm(`m7q8Wx-P);K_fKfy`hcyo( zIS9Lf0FXISVqGZ`po)5POyGc!FWuXq*%MboOnXml!)T29>Z+(Cr~KrMJUgfEJXUAV zqdT^6q)vdobLc;^ggjYEYN1RPM_&3H4(<&{=*c>JfFxn3!gJ80F$@8ytZm0oMpQ!J z)W%MX+NwTDx$1}5TQrP^|J4KZ1I*9?NFHh-V1Y}bpv&Z#niS-=PKh-06f%7Hd;92) zq1=X8^ZDt~tbNpOr9*(`Kj+od0~;RgxyBao{7BuX^!j>_ks@qD=q=AZP@~T6{GrE6 z$V=i{`2C68$Kxb*?!4M#3&wQqFfOxLFjC6?Hl{R%Z{k*C zFNq;PQSRC54MJJTa_(iJ7Qt1^m&b+*Y|YL@)*rndcfglB$x$tm_vMk#9?6-EZXBm7 zrp{g(tT`A(>y+w0urcznY%QnjTUBz((Tu)dmhWqN#CO(Na;Zww-k%c&C#W5+d}C^1 zL52$98w^~`H!;fZz{2_xe0Vb;4vis%;yFmJx8%YN=RgcgW17F!Tk*lSD*yG#5)!-w zZyhwO8gVHynRX5|~*)klkNZ)=+Um)m^zR1gFOoP1m zf|pET8onMbZgVd4@45sV9~MkS@~5F(681OvyGI`y{JK2gy`$t{?U2l>`L1(GCD$f` zGHhTQk%j(7u(uYUOd8!-Vg9w=FSGm6S#7n~y=1%^%$9Yy?Cp~dfc8z+{ zu9*B`QS95R2CGS$#ZM8|znm}sh$AOByUf>S8eqHF5-wm-Mh5@?)7I-8$w%A`><$1} zTTa)5@lE~N`1lLhE>eOsHU23iutZKLQ3!i6MgQ?7wI%>yO)wP6=cjxLFPLS34bF|X z$ZH8vE+7n4Z^O)7rOI-bMH`jI`iq;NA#zEJl7o5jhke%fV>Elcdk+n#&6ir&pB-0^ zgj#S@-qd`=ote^=% zm^3crB?~JTvQ+~oWg?vaCS;(pn*{BUr(yx74NnE&fTsdM3{M4=Ax{NT^}n798|mxu z@nx~dTqsWkay}$1(iffzWO#Tgykt#Dl~zl*xw*!w$;Cx^{WMkApv>}j12Py|HGQkq z7Z=B4=8W5uLnkvINtPu!*|(=p#9ANWA8+!j8Wr@7oH`h{IN4t&ch%*WQFGp5vAZF; zK@GXf!=kT>!-`Yj$k)N|GzTTwqv#)1k)XidTeqp;!?j@I{Wp4li?u=E{YC<(;<8_Lo{ zwU9`qCb)DEUC)F|ZaPB$*#gWo_H(zhq1hOJJx9zm2DVX?*~^+j9ez+P7`rL%Il}Fd$(5!Q(^K-u@6JZQ6_XbX#?iLhMzV#azoH~`<^E2wNmmYq;8+VZN@0wKgCY`_VUEOC zNu0S(UwLd>i%pRx#zbdwEP1`sRKZKmA=Wi#&i`kVil^A>Lhz!v=<9kmUsn~aKh7&< zekE;vp95Z+_^DPN(3`V9GFGgn`|}}oh_z?0R8QTccwCR=%7>_L8^Q5rRYu7v>n+l? zS>~Rr9zjwb9Np7G?fTnD8XiDL{M=8K)vCV@^Cp=dZ=ksym+C7_)>#8GVFd_{c}}E3 zAwl_BNn_(D5?BasCLjWw4=ExBVEo%rq_A$uliN^5qjO3Cw$`<4SjxKg07WsV6hl4G%5;cae+DT#tT{Tc3KF*Ze?e-ny2ieXHN=gzL_e_w7FI3vYkVqAe^?Tw_V;>(pYTSZv6_Q|Q@9G`iJe&G5RNb??LNFksV9S(p0~B#t=fjDgQ;Z4O zJJ^9_rvP|D#A&uk7%_H{y;D*Cb5T^N=*HQD?}rR#o9o#ImKL&=aIhUk;Si`?3G`Q8uJCtH?pXLmgDnL4fFf_T7Q#l7nU z8rQT;Ba7~|OuW?PliyC+d&L)y)HHhq;b(L{FD!UAhFZ9V;B(tPFDN)P-ag)+#9id& zcO#evpS$OaKR#c)D`!zA8#CgMKX22Gt&mqd(Cc{XxMRs$8%Z{k$^q+kYVJkjuPEPi|Mm^ThT>uZ;FzkM;gxBQI~&s&ot z-+pq8XmzH{#4JcWS7)+qrs^7*GCAVK{UwQ}zy>{Oa-^LA8O{AnuhW7y>+}67O@Dwm zgR1Lq#_s^rkA?LTHUaEZmf^?laZL-l>G|Zvm1aJ2+4`LM24UxFc$=TE>&D7R|H9=- z8@~yut|OrXmyK!F`gX0lo7YbYS=%IpnrXJ?N1mnnIj#|Li{o4szK+}M#w*6c({E7r z=Y4t-B!fRd-2dt)$*GSxSSfZ@NJi3%>&hkmWfPsd{S;V#x1W3-Ex<*dB7XSRfxeeM zXqmoL0Mu(1@YqWg8f>#m$*SlKd~az<$n3kMwODRF<`d=ubV&iEB9wp*)v$2)h# zZ9~ghnEDs&Kys?r4;A*%0X8-pTBjq+TA#!E8(9S{8(-r)UD%+-Y_{^tT-U^B-*U~Q z#P5^JeI1SZ%)|qIOXr&uUGr_8vzWhlKk=~Eo#bXiX7c*uAym8cby@1IPIMWS`_Qu5 zja|<^Gw?4mh6W6toF|PtIMlEwX0T{b*M51JsHNVxUoSUe?0J{xz)n@=vfvu^&}{;z z-)_7-w78NHU!thkr|#o3w-#bF&z)}8Ve2AKIMb-oYW&GOZy@aeM%Yq)p+U(tRx@tY zYMi&@+lli1q*9h%cXN*@i?nw?8$9Q@ur`VYx1!$=tPDRdWuIUuKaK}Dor2Tn8XmQH09oYPsDqPXQjV7HMiNes4Xfk_56 z;mc!edy)B4Fd=jzAOw}_W8@kD5sX|Be2+6ALs(GAZE66ZFVdY7p884iV1i!f2r}RZ zG?2%zDI;f8WQt&_r65EI#q_|fyBK|Gr6!n>w^R9YA6Jvl>Qj$Lo*eN#r$tNNbF zeY!R2gID^3-*>%9>qEouF(GViPlmeV1+%Z6a$V>!b5+tD+P2_9oXgC$sGj!_;QOXv zJ#oBiWKe%JS7Z1_V(LAt%V=F!u-D9W?kW6}4a5E}q3;K}$s@Yd$u&7{dp?n8gzQg| z?M@dksDVK$)dVa51nVvt9lQnc1oa7qMWzmObasuN7)ro7J@<~Y&Gw?aifF<1<=@2i zkwq$jrI6T~g=teSA942DmB$N}s_QQ8OBh3%peKvFTgiL&k>=;UKEO+qj0~5M)TvpA7 zvM(}d878=D=5`ITcu#Y4vXLVN?j7S2vXm{E%}n%DRZ5 zSN1%%#|N*jpiO^VSV0>c|EziCg37Sqxxx8cI_cZC$)#G+QeC1c9*Q6Wrh6y2?&#eh zM596#Ti_{X|8h()pS>e8%!J;UOO*Qx8@+wnTTfmg)iS5YZ&g{vL9ujGE%f79DHZ^x>6;JaeT+yoZX7Oa?yO*$scS} zie}8WoA$gjdJQ|a%O1EWYrC~$d#JZg_j%b=D?9cyMz?dXg%@aHe~c3;!Kuphhm!Ic z2dk&{*z2gK$F}6E(_gqho^!BC`0`?(I$>jZVd}DRgTpObRVF(^Yf7f7>uB@B_lV}E z7fTm9!++!AY1F^n|8*nARkC-cKVpaB`?<8|OJC)uV)JyG@!0CMrPIzi-PX;6yU0JT zR2*0`K*ullE}-w6tv@VEUd}t{eKnrrE<=YHQObH7CoUc3CU*SK&B^#%7&Bk9^EB@+ zsViJ}#W&8b+mNodko*>h8@r9ZGq}XvTDQ#}>HSPy&)~`J)N8tnn_QOKuhrS|>&v_4 zoFchW)U+haVss$S6+>OEi&uy4VXg+q(@TgyV$ZonM|}m^lCtFw9r?$1{+;;vqVsgy zrgprI9bjijA?Hdz***`eEudSE8C&MHF<%m# zSmqsMpsip$X(%+at>vpy4X1>IUsu2Wg-82y#1aP>Y;|hgso)7sVm~~>pd`T2nXyw2 zo^QkFhfcy<{fMW+!~Sk8bz%#L{vIZuN88UC?tFRf{xh4TsV*4*F?B&HYeLM5%>k7E_TRRiDdbH4v1*AScn42ZtRL9FSYy#n+kLTu-QT8Ss8b7rF1bk0Mmg>fCrgP;Q0FX(FyQq? zn9&{S1wvE{r@2sS`wZECQRXjw;E^I=7W={Iex|XZn;c7GGTff;_3YqPXX%U8ws-`} z_1Y3<04B7&9E1gE@tEPG-A2dHOx=IG6GFbjzGw!9%>H!MkxkasC?(sALbt0??yawn zF^0S+iV=8tvzargaz0!rmXJh(*1dQKfHmWVgcL1tw}QEe8MD8aT57}WRn&w$viA-1 zE<86cPriZCbd{U%vDf|-g)osgI=YyU}G!hx5A!-u?Md{k+m(Y<_mhnlkw<- zSeg6am&h>dn&$^!D2BZeZsVmif6bUJn`E@p@!XlQAE8zkRHApiL>{C^u!<6ClnQ?PC~ykxP3Hy&3!_eBT&o!^v>SH$D{If+9Q@un;3S?gHoe2!g}JxQ`Z>oy)?=wquKjM z7kN7C-xDsmI{S;ODih`31fP!YJ}vsy5L@=LVYs99tM$z1g5(di^&9HT4!Ns4y=*it ztxvNXE$I8JT2$L~&E)w|kseDGqO*>T=g#f?7G`AY^B_?{t$(D|o$^sXEI|3FKcd6L zU{$EHhN`KtpE+%&!31gN)fIm&#FL1k6mS3qxLe^?(6&vTz~d$b|9I7IunwS9A@l{3 z1HvoO0n7qi8xSx$?m1;oy%}Uu>!-aI9>kk(@>!7W6%B0oDnTa@y@dvg)WTL^D&6eB z;6^kl1c2BMDv_ z#qr9;w^m2e<0rqgOrLd|sLJJQOA(P)+^H9SEv)9O-}U9>jNC!XtmD_%rcEMhFU5K2 z#146KCi}gbQOACk!g{wn#*mgAvhXvf_hOv}sj<$3oRC2)5@r~TNK5|lq@@6HtT*v2 z*1M8RQG+b1sL>DBcM~i>n|qeL?ydA)zqjJlxTfHwpB&fLaWXk!^-n0l`-;Z{I8dSQOr(Mbyd37Cxs5@wSO%E}wtO;)-%ot-y0ou};C>NrqG zu8le9*PTcSCG{jd26Z8!LR~0b1|{qUmcM&YPrN|+xC7LUh$Hp$--P``M`cS~(!Gwc z?s9kpKVv@YqE%4>JtIYfO3y^mpi)s&G^k$y320DpfCMzCzfgZQsK-F>sSW7_q*IV| zAe{jX>i#{~7$~Y;(4ultG^n82O?UyRl7^x|MN?BWsE^TqHK;eCr~Q9wP(QNLo7|)-K{W(Y@uT+*#vazmny0O5l~1(1C(J!@Vmyt`!kk8t2)xyn zQk<3G$u*)f+)g3g31_p;_Qary@Si(}nnDj;-992(gl~Xj zp98Gw1KdW+@gxHJbBY#eK-4DU|9#|xmoN1W*gIKG^P~mMa@a(GAxga}-~_+dY@7lC zMAWmiHW7$lAdgZ!hM-cmUKnYSt5*0$?@wjdZSnA7-j&0XA9LlinkRkYNXA!6G`#|M zxz(vBL&l;+i}bjJR-TZ1K1+)vtH^TG+3L1~F1|-d(fg)Ti803O2qt1x9qN4^p2URw zKG&R!=P#+x{n6D-{^mH|U2!(JoOeQI8*W$Yc4Foe3 ziem0g``fjAmqZrV+-}_oh1Q`i3~k=0+hg^+$;G6VqEC}8QL4mAgK8z>7QW_hffgPw+5CH2LAOw*nf)JDsQV&shbuhBpN3~`4WWdocN0h@G zaC{hnyAr8=06+57D~Ve<)b>uQD3$w_HxIw~k};fsRen3l=q60RRU5)qvBcPI9limK zJ%M{}Vvqy%cC9P`n~GPYAyW8{;uY+&+O%z*8sg|T?Xmy^*kvJzKuHMzvCC@HMj^V$&{M%_VeT+#2iwziF zzNnxW^r@TVOYZvAZ%>RmaoPdPYEwj5C-!Nv+E8bmb{Ov>WpLG6PYgPDF0E9Dr&}-9 z#vA!%N|mkUGV!gQ&BWh|Mt|4jUh9;VZX2Z=Z`WLMnzfN$ru7*-sqN>gsYy-NDfz^$ zSgd|k;93Y@ZJ>vJNW8^LLs7PQt0u$LHb$Q0Z8!FpFu(TYsPB!a9xRz3)YR#n6xp5X z{%4obWqqow9vQ1p@m>ca*R%pT*o_ZYUBZGN=%K~TV5zg*i$D?B?f>7^h*Sksemz(x zUFcMAKu_raq=sh^>|v!I3D|(t(1AL{_yBU7VwI2o3-hFcqE`{9@&0c_u*|Uj*IdA~ zVgXByZJvKz*1h#QKHQq-KhHZD8kBW|A`hkvG?*96!dd+q;DFZ=5F;7}C_^+1NEO8p z;=i7#d^gZg^it-6MBYRC!UKg&3Pe1}@USS9bxUGBm@8HrLV~6>@NatSr^DB9v=7{d z)2Xk-NzD0+YXslmymnKAk$1JfoNy1<0gntS&>-VeO7{g!^L#iFNT5p5Tcd^02+@hKIR~s} zO|aDnULel}HoW_5eBu;FJw+UKat)(~(CP@$3;tt?gOb=WemaEEL;&1J61MWUDD%^c! zc9fl&9&T0r`|c+WI$)t4a`#nX7I60g2XgoM>5#h*Wysw}s{ZHQcPVXb+?)&L?n7VX z?!%HLPzvxk%CN`zxYl{c_0}OcJ-`y_FL+14-9?WM0cT#)(E*gcMYU zUOlAVucDk_ua;fEsYbLyy(=uM39RI?CL(zgSMwmL9Rl=2;di$GyZvK7=n&f@Lb4#Tj-Q}d!Q{nQgqYIGq1wNA zU=RTAhG-VV9mM*`|Bth`0IRC$`iF@_OG$?aB2og?pB%uhlc+gyzlpU?)Q1$@B4q>bup~HXV$ElJ^Sp5HNUk6)eb<9xYCfJqRE|z zyZ=$ei_SA4!hQ~~tPuo^%xMzP+e1j&zb1j#Xat@3i;n+A$Ntbiuq+{Pt^kDRF9%16 zWe@lWA{zPl!P6r!zo?Wqp9Lrw{CGf90Gpdw5Qmr)0P>$REyUJh+VI+%wd`eToS^+l=oa!0HPEoZ*j$Q@cE_hioeAu8 zerrRZj;_Q3Tu5;{&RgzAX%J%@_Sww|Scf=P&y05MIHzcz-|YY{evr)cX&jGP90|JU zmBeX-+JtP>d2HVSy`!w3)9)Ni1=)#25%$f8N)QBmv6|JW9jB`k1P+vE&QI24wsbpf z6b0LHQGnW806`GnfeQ?~4tIAs@vhCYO(8IBjiUdB>;BS1=Qr(yVN*Td+Fz&beM_Wx zU8r}pldnj+s7A@V;4*n|wG)Yd@A3(|7&;V&{@BIR%>Ep8Ttm!uVG^7HvVid2ykcYL zYk7Kn&ouy5yK_8w1{cpxxN!#&I}LMYM8p=COoL8^-4O#!Trli0QFp!#1qcLA&uBj` z?(atk0WY(z1#yPNjYy!cM`Q*7?i(3@(*6nTP)=HR$N;7oB7y3=v2dRWlv8?38Jc7iDRX7qUfAz$r8+&GPP$KvwI%W~sB!GUDt%?kY86 z-=u-*O|*GdGoqJ9T2~HgcR^W00Me}B$=C; z<^cT!&i+=A8(dPvgD!={mE(JP&;Jy4lFIh|3CGpC2+HdZ?{$X;-5~`8_-qrPgg-eO z2nKaOn6}U2>=zvTE6TQnV35BWUuCsCROB{5>aF7^c=*Jw2D z8WeQIK-mb0=pXWDUGR6>-y>zf=V)t3N9IXBem!LHQO*}foK=3TAbih7LG4wRiP=h$MV%9@%{^TfnrCSdx!snD1Kj(3}8(|d)2_@X_fZVrb-5Dx%W z1?1+;+G;<5sRK7azXi&@L7daY34wAes1cx9K}|fw&ZJE5%?6yAAVT+phy!aS1o<;* z`7DHnuvcMr#zxqyAPDHBZ)%dc3edX>h*5e)DF^iPvktk+&CXzX2JR5BHU#;*YkLlo z?tlpm;Qz0!$V4%S48a^Ne^_!o&IE452CvNMXA~a)t`w(rk-psbyK6A(e>T~b2C%xC& zVg0V51DtGBW(%-dnEG*?yqdpB}t?WSJ7d*gHvj{`BaabWL8l^;? zS?OY&Q74LPm`7aXzB>85C4q1O{@2p6m^zRNrm)|m6oFeW z3F^~OkF$var2~$R$7d@un?6T$G+qun@TN23j}NO?Fl!iLkE28hU*7Y`NP8Na=nyDE zfXh%e6GOiuUXa}7pcNh|!*xyO(8z(&bsI(eO%10ELT~128jjGLosLn{376sBM>zTm zL?NhAGkfBX{9%ii^pFy#XIoH`hPYgKK9zn2K=uLF|3l@gxpd3ukP@VOR6se_jC4<{ zAnYEGFEAF*#Kfa@c+aLDh(S=(Szd=p0L&N6+AJ&R_)gH6^Bj1NK9tyc2Iic-R~ zmu3057Ho{^$Dz?-x1d^+UA#qa=uvlG^ErgEPImd$#r!)9fC3a+tx&3!MIpPgQq^?C zSiNbU?U63BXP~06t1gRTok)8blx#G7KOez_iAIDu8vY3W5!w6{0~6!9o^P3P`(gEe5KG zsN%l|*L)_Mpv3a1X;4FO@Y7!b^p>XdsE7wf1jIU`JnBZZ1fKjazjvT@5H0lY3X%b7 z8%IYF2S#=T0bK$@CYXZ)S%}%}jSQFoLh?W7KYtmpS*`H#o6>_N9%wYMyc>|dS>AzM z2vs>EGw2g0yV!PiX=cGmCMS#iD?FZ_u(Ng!S=YtSWpxf@SGpqclY*z~6_vp?z0x$B z$K9w27-HTkTX7FMo#!7=b<^HknY1?V2exKWz2mTzHQVaqm||0wI3p8I;^OsI0!11x zZVyI=UukYdth=*C^XGg}&s`&$88!4oo(MMD^<#yuUk%mWrn{HhgTS?8%EhlmAVSxC zc5>D(SJ9CZ-Ycl%o%fuVs@JLic)pixi4uUN#geaM2W`AhimUnYt9w!jJEAUXWbO{o zpnkFtqwo==aBx~|n=~e<4uM-G{OpER8!4Hc<2u8REf4H{W#9ozQI{`taf_m#^bp>A z)BT8UMMX0>@;x*G_e1@R#0I$r*9*+auUqtz;jo|FW%8#+fg(Qi_nnsv{DJX38 z;0w8BuV+CHTrkk@yjb*rQ{oJKIv?V8U|9|7qVq~dICnr;EwNM(;$h>w3uyIMelb|& zqaOo4S>e7qmEN&1hJwxt!ZkrmQ`cKt64rqV1}#J84<}enTsKI{h26sV3^|pv*J&vp z1d0GZ5sDw^=`q64mMI8-yQ}o=aPF|jr^G$FJJMlBT<1@|AzU&k+9B9ACw=Rv@Vg!Z z_>99_8e>lKR}?twjG(p*S1dJpaOV#*tZ?Vd8?UD1{54kD-_z#(`dc_}+)yAomQp^$ z6@1M{cz9MMVWnc#x{Y}&0vL3_-Rjr9yFa8uuO+O%BGG~iBuSiX0@_Ob2vb*Vl#EHX zSK}e9NA&A%#U7uZ!rUc7=U~4sYek^4DZGSt#L!Ml>tqO#18>G0(y9iN6DHQu4`MA^GTFSm#y8O}yFv9$xmg4V$B*HScY)p_4_%MZ8 zl5~)mF2poAvYi{PYw{-ii%r#x-Xj|mc!P-&RSukCe)t8Dzw`X@1`{An1^#Zl!7P0H zGCR!etWVmP!Ym%1l8aidfB1rePq_>T-|lEEl0}r%sl4wOg{aAFM|kN?%rTX42MeMy ze}+FiDvzt1TWX#u%)j@Iy19cMl4Cr;GAR;{FcB_b>Lnik0|qfmNUgY#3Ock(pW{8n_@@y)1_iezxk9GPf*sq-oiJj zyOuTD4IBg0ADLlJuEO*afeoI4P!QjX;-PoHc&GL#ao&cZyt-d=aa~`UwNV7|CA~6h(+EOKR#hJoY~OML-%ln#jfK&E2a)yX z;am<|-OGz5iNvW!RjlPDThX_qpCpuB^eH)Ucg7ZE24hQ=eY1RahmcFud>hb3zMiKb zi9DoohT#3mU`Kkt`ZcKemxo;Qvcu36N^wWW!B1tyeSeR|4m}z}O6o+e=?88OQE>Tb z(JLO0XE~eP<8$Aa6+ewQ))=8Q@9PV2*~PJAAn$pyC$SF^*rnQFAlo$s8WB$9Y)T+) z#hE=s8HBa*taYN$#Ogmp!3f&-?{G7!rGqrnYp{^+Em2D4k*{;4oA+%%!0GeDoY<;_W076MpXEeLzKEvQjIeF6ZSz+g8#ZZVaF*%3(lPH#G{?88&yD5TIqLR|z z$TI3N@#-q(R6r%WKa;94DWgphJpiDK_Ow@0Y05&z8?TnboMh!Js5Ca(af4M1@UT_; z1g&7APDp%?2W$Y~gPjMS8!lYpO6`>vE4uG_nCN{6*){hoCDI^c6RJi;=4R>pJb-%2 zTkeKUv{eFB)W&Zla3-$+Vy5OW#|z0{|2jSIr#{=+Ly_N9rOQJ_UlWM#72& z&{~aNRnD;Xyf2>NDkLN71=!Q}%koAw`)3rPq;IKMUCVy(R>}CXTafqMQwRZ$-q(>V1Un9I-bvMPET<=2U8t*rLimMALHID5qN{8e$a?15cB)Nf?M+)3IWyM==ww< z^yrZAk9x}U>_~jrs^sA4N7u0-w+@Hpb_Mx-JvFo(mRZOQvx5QE|EYSDQI+osY{*xF%-mBQ>dzq+>QTJ`Wk zKjB2p;CQ}?#Yzhr>P%$F!-hoQDGwD>J%OLdE*K5Tj^mgM2^#VK3KjXh?KT;m{#_2x zl6-RN5WjW$CJKTH_E&_Es$XaKk?I(j{F`BZKE{!hP-XH#SM22@xnOF5?yruKU|EP1 zk$_M~Gk)+5Gn9S5f_YE>3N0j{^QbcueNC@Kz)hR#EBekJoF0#6Jhg)o+BqHZCl2m* zPKaUjPax8q_xF}^M*`nY@HH&^!hm~x1E{3n9{a0>^dWWdBX#8HE;k{@mU*A6^^H{@zkvn_3xps5vL2c9WYaCV$~-pzy;1idK0! z!NqK<(ZIylz;nQH4zjELgmWO(rSl8?A3pAuRxR>InKZ$b`CRLa_(}1tjH?q<-0C*V z!wyt(sV1%R?9Q#*P#4lBnjhhZW)A=c>dxT$#nMlsUDpLiZ~Nb+#|VT^@3uzk9iWAe z!xjIe}{;N!xVk}+uoyF;=4gM(u8D*Wnj zv)NKDvhjG<@86v;9RWhqvu5#A>D>YE6@%Jtv8=Cg8aQO`KkrJ59YpeBx)?FmpbvJV z?KC6&W?D8kpltE#H*IZU0kkDXJJI_rN^F!IDg~s6rOGJ4{{;0#w1a=M_j5tI1r=8s zKjlSt6ubnrDC|L^J?*aTN001SMDUx93f?Rey5*V<(d~J9wTqWLr=mj&uU7jK9%q5x z1x8cxcg?{+t+zmj;qkC7bew~k5tG_cqqhHZIj_Jh%@h5m``rY4XmW6cirbozqxNPB5fiPUxgR2WM3Bb?M%xsd=RB82s}Z$B7)=uN3_ zx>dmyq!LwfTWtF&cTpQJ38fE2l!E{-oehwGSoU1Y?)}2>U{~N(A%)_kk6Xg1zS%T| zf@E|5_R`b*L{X+tQ~VjXF_6mZxu%i-GN@9UWDIo4chrKmi956;llt5m0LCvx(R}ki z(20M*f93!dY=~ulPgMZmP`S1L=MFUlXJ==PqiJ;Ng2HjD!)SMNU&e!n(c#!LAKH>R zc-PB|)VELZemm}1fFp!!7ftC^;DwfAKu9mD@{3)hAs1AyeM&SogDyj-ZANgYTZdx( zQ(@d%<@AuU0c)pVY2890x{Zt?N2+9$=v&E>(U{4GfMx*N8huOWvx`lp@|)=Nkf{Or z3J4>iX6q+RYd&Jb{0-uC9xocND4nPw=BFBXMUUVAoY2nryup~ADe@#ooI%o+Qt)}f z?R1Z@r2E<*hjhzXo_)Waj?te-D*G_LjgBVhL>-rLub?{G-ZVPqm?Lc^G5{e{@HH+rvi68B}Z?I$zx1=;Mo0AwL7 zI5JoO>t!3MR*RX!XX;^fB$)a3h!Wf0Z5DOJybx=?!!P2R zIKwqk+|I^*2~Iq_L~>=te7y{gIN}0qz>qlp7Y0TiX)3#6iT$H%tbz*o@? z0lHt>#JkO)i;C=54AHXj)|_#G0mJBlQv?AD;2DquD1iCJZWO?Ysidxx7xmt!%l*gv zw!f!S=kCn5tNw5}cYI4s#TVBqqvz#GYTQtJt$|*SJ7m7c((~3@E^6p?kaS&Ip!75? zIKt$mWM*|yJG-@ z>5t&JR?-{YD!t3DqiRsw8f%lKz^}I6#1-Kz1)sry5ydZhZhaPYop?xiTP@n=@-_!- zF(s)`XjLoMe)gTcg?7$D&ric-mTms8D$6~Z<#cttYOldb4ngR4#_`D78pcR! zW5DGf1G-%`dzdQJ-OJn&_8SFiQgiM$p^iMJ{mG)F+PO-5?2UH*f)Ls`Gc?(Mni<;Q zKg|l&Z8^f;Ndw+5Y+l+0_zSZ@=~t!s36~%66Rs?sKJdz>ARFZW#nlgWYkVGI-q8+| z7ka_Xo?6DB05{Cep>`v9TdTm8drYe(yh5Vk+eec(7%l>}Bf}#$J6K`~ zrt|ta^k&q(DH}Pg-Re1QF%1c!Ka*3sY_C4z(|B>=rX+Ap9hI&uO~$o2^vnv~?#&m& z)lGJg@vUO1_?ecBz0I?s5VXVRLZMobYEqo7tU)O02?ke%Ex>!?nj1!F*KMHR_mX*4ccr`S;}Gde>k-qb78; zvQl!q^0gug{TUi-INfmPe#_dq2m9#Gp$ilrXrRie`CFFr`DL-Tba-e5WU(S6%c%j= z&LRlpp$?YjLK&+Bk+us1lKwAQ@#Y^fNWOn_xTupD1IC?_{hlHS65z#Duf2^_GXAZV z6=AypEI0^xI&iR;!`x)!bg-uM9bbNHrG~ONsG*>MbzluBN6V&uCdSwIPU;WDo$H^- zV-*tfUZ3M-#iN19tBJ{8R&s-9?+LhHG*B*+gocz3<60>@?>TIhcxU89z=%X=X6p<2 z40a=m#LhW-jfM@9mZYlmyj>Z5IOj*_m^`#Y~8#Xk*bzC$3GVDW1J@?QM^a%Pxn_-MQD?zT5ULcV9;kDHp;@E~5Gk6@Cf$VVm>^ zaBxpq>Sumap|V^k%^QnVTS~xCTtN0)Ur04R3bD30z-?~G9&<1L<~#?y>o7HEqKi0` zh%q%^r6Ez_PT1`cAHq~f0#tpIvr(?*jK!OEk*~%#xq#8+hpeRGd&JRRa` zwNNg%!_f$+m8esF15l`^$sVbGhohCCG@49?ZsX9Zms@p&3Sd@I+Fi&BL)N55S=AVU zow3mKW-V7n%Z0*L!trS`bvTO~p>uf!hdM*ZXmkCCT8$|(^@{eXf;-?aZse`lQdN;9 z*>nHi5Vyny*`p7v+c@mDFUOj-R_Ti>IH2{C8mP8EBcMMT7Y^`@aqCsZGlmcL8uM@)M?DTX|4~Zm zjGMG_@~pt)thh$Z5)+?J)l!ItLH`vnu90_kStjWiQ8DF5P5mLK2l)m}P};#lqD$3) z_vd7d;F4ns`%t*K%xpQvEw&@d0`-Nfida3N!-IU8;oAbj1TfO>Y370%>F-Jay zlkSq4J6rzJmy<-4yk=xP7Q-n+-(>32Ud6!!rLCvX!YC^ld47+wn~mm+roSq8k;rt} z#tJ*D#G!PyQZySa(;50^e(rCgGfk9mWDO#qIzx_Q*A|EEd3)V5ld~q23{;O#H$?ZjSXV?H$JL!#dOj)opf16)4E@qNWinz4px6SF$X+eL{k zYc6DHYEWr^9pq_|swv}xcBR(fJuX%oLrP^F0#Pl9s5Eo`kYHnLyC}&Kh;TtLj5^@~ zw5>x}F~i)yeO9{pvZ6MAJ1@s{!PxX@55CiGZEeI$JquOE9^>G@A10RK?W;59;CdzV z_{4KgZSr&AHf-em5vsh=GOB2!`%&98zpc&h_@52JQ%6A~_r`@^IEN;Au^WYm!S*js zbTllxQoZ#&Wi~snN6OvzJcWNcjqrUd8MW9ODgH50BJ$LL+0`c3*eVnaW#>RwcWz9t zhk#?UXq$MXKc{JNnRm9|_1d~#IF7$r%4S8KA_-8Opf=4<^Sas|+elM+L$3o|SSm)+ zgh@0V1~GhNS73f=43|l14A<1@45-Oz3}|=K8L$Aw0TdrlLO@CGq&cz+NvvBr`SZnL zN43P6l>?PjA$AS7I?|v4FW=y~@c|J7>z#Dt&KE<;(hBZ_FNPWb8GnJ8O|A^+LqyG9 z2hC7~rUl5-{QyKJM)E7SI+2bGx@BfBNVY!7d+CBskC;y)NaqdN2v02Cx+Og%nz~_Z z`p6&7666*pi5??~9wzDE6DncU5v6!o#!W6R2cb%52n-uq3zlR@m-ByHYS4HR{@4rN zt>IgFc}M>I@_c&NR=1%sH+GJ~ko4^Bh*++tI-YhpN260k_k@_&nc4G!&#Yxf^Cha)#0(*+>*9DV}+T<=b=MXVa}UolaJ{SrHy8VG^++N z|G|<0gU6>;Q*Mq8OJ_#bdp$7A=UjeWJR_v(@*Oa;R)_EKU{C&z(ULi)46-`vDa>r> z3Dq^~kl-F>a3)Fz&4bK(KL*Rni-}$+oQ5n%m&&?(Kw^lmfxzG8%{r}FoGzwB=BJc2 zsc}e{!drh*9ij?GDshSPiUUF?XcAXk>a}sn^GfHcsz+pl24@uu1Qk}Pgi|@yGDBrv z(i?OQqW-bf?}zC6Is6rPUC7_QfZ?RATHKSI4rmP>)1F+>&5%#fgIM!om%dJqWT3!h zxj*+Z5W6(FBeZJd3ul%;ms4u&^Z(&Zyy70-{`O^qlQ)dz`yFCzjp&gy$)s0I-!;N0 zl2yM93-&*CRp1!QdRf z{o5k-SK*2NVvj2<#UB%;m-g2zK~HC$Fv9F`*A-0X%+v49xIN}$)9Uf#f3SwMQy)wo z0;S6u1XqFNaGJHm`K`+iqf+z!r-JJ)a)H(DVWx&7n%`C604te_J35_Qkp-BL;%p`?#2sn=; zdFi7EIIvP=zkVw@Rv7{hW~AX!6hWL_iHE)S4LO2ZgqnC^@n*8|GmC z0BHUsN+6R0D>ZMlUT7@G;pG{il>t9jwmHv1Eb(#E8 zKrq(xN~MD8)Y$zatQ=c5c}e`2$RaKV%KfP|4}8zf6CAbLD;I zGFFt%7V7tLRgIC;++4!5M;p zC5I_^%`N>xCE+8*pkVuF7oeWcVGdridsV?Ob8xVhBT5XX!VQ{j%!_rw99gBUoyUe_7A#eLR6w7qYQ`GROUg8fB4 z8i%Sklrh$zXw->}o0o*zs9n8{W{qSX`ldViN!#y*pY%~r$_n-yY@R$d_Bp7Z~AP8$Vo^RGa3Cbv$R-_p>|yZr#Z!G|0spTYBPtE;0OcnSYF} z8`NOO%VotUn};bwQ!U>e;0kvjkyQU56VHOv2){)+L9MvNZTl(poiyYfvCxFPN^*; z_h;m#yARZmY_s2}i_tuJ3^DEhd~37QC=OyV_oBPRTg2vh+8QG2$Ed+_4B>e!iy=Yd zWt5<0HqXaK=g5qm!> z_3u~O|E2a}LNQNVXiRzwzW`%ajJTB1>nivyY48V8vn*|uax>c#2E#!WI_o}6^*g09 zGM{~z48^!g9vh0$?%ghx>G(uRib+imH(OgppN3e~uzdAKL)oN<_qkn*e}DYQZZM}p zrAS=A7_n2=eq$u9c&GHe^4Z-F6Wpp7sDvKb!CCRQm4a0A#r1o`7%N!_Cia=xVps^& zDN3(Tz{be5g=+WZ!KLbs_vzLA^1)>%N23q4SmCyCb;Cr${oAv4%fq;8^~fI7))AT8 z_7&J}H$*hNs&klf=7zuprf6j9(C3!TZkQ^U%$f%J)vT$*a+j(JWfGe*dBS6DBDRog zMa8QzHsDCJyn8fh)2L1!zB}_m;;z@T%W>87UM?QTWpn4&jW`~JzI&g>d;3L`)~725 zN7U6qFO`bkO8aP1Z~a(+b-q0lkfK#0vpvO%YuHJ-AJM4wUb9FSM>I)~u2A&J6o=ln zDp_j!E-VB)o5yxeJeue! zT6bId2@m>b_ym3q(l6NCN7LHnF+iHV@)({rH#ilb>4#0d{iTM}T(diMaYpm1Mo-pyHpoJ|C@|%w0!#I>NfdApFWR7z3R6m9`gKF;UE@;fKnFEoJT3U zVEsha#E5bnGXKd}SqKH?eDpT5@B7acPnv%%JZU!Ae@AbpUcU$tVR?M*tzEx}B=WWF z0wO|9YAb+D6~uzxrpl=vw2$5!#@{zDA|Ub3Y0qH6cpSJwRSSaj5<(H4CqmarIuhkN z+Gf`t{cugf!}B@sjmeYEK}~KF;C{BeYw-BOd2oLEo5cP;*?iw1_sST@Q9vJ;0GZ*W zfcvW6Sv$X8*02$5D`qGen@w~QQpAI(EBMTk>Ek&BHCXQc1D~tjZ?eCKCG37?e zs}IZT9c~xiXL}>l{KYY*vEvW?R4;*ba%tvQ{)_N;5&upI);=jZ1GNoE^ zLQXJcyH$}7qG%6GN=J$^+BueGU2v1VZb1+M=;<9wUt(zv7`B(a z)*|VsVJM%xVzRtE@=Q_dQe_qeY?doU>EntacXa9j}9&Y*7oFf0W%~zCSx7 zj!npqt@Nz6&X4$>4e^@}_lnj~u+;i>g|6w>9wtfh-<$XGa8>|C{DwmmD$93jVr6;4}$JGqg02BnyNm0 zH44XG){r_MQCG*{Bic4uuCy7z7I>g>ujF}LIMSEuHI-PwU-re{RrmvQGhhYma5hEmMw|r#s+(SaYtwlL_rr9R0 zgIMs^PHea;W`TO(yS5)sKl&PRspJc_qVUPF^PsSjo*CH8{bXs20xlOt7@qVWbv;{* zY+?KO33gqFtPq~%U_~+m?l7j&k56u!$-V>jAWD{O(AxGlOia}h`=@u`F*HT_1{kK_ zZSAnWwh=wqG?kK#72Mrh9#h;unz?5C?sNvTP~x={_)5u%WJM}RZ})(jiGR>6l6NfF=Rz38*%p zBI%GV-VQnMmngAC`;esiGzc|M-m}LqQD}Jcp3%Hi+FtezQ#%pE5~vX)RIlwoEoskV z@=S$nm9StBG9tT9xCMa@6uA7rDP}Cve4@HYlJ~43AHTo2!cC-Yav@*UGCKkVIVS`T zNjfMd5YVZ>(Es#Sjc9LalLym^XJNE1!MCs#0iuW}ZjiaT6~=`w=RIlwzFy`^-xS|7 z)}|{_Bj;GvqT4GeAVE~_#_7j$*p1VVxute#Pr z5<9t;-LuJXd{3Ra6aHSLs{N=v#Lj&Soj-mpF0rZ6>)Vux$keZ&#a7DotveeJ0<0Qi z#l({JIXM2h>%-(JX+Hc5J4?ev_dH21=q+}zI3)_#Vh7FWq{)V(F}vPrbt15Q=T zT8Hl%5qJquSyr!J@kojLm3uI21{y}-kX5RyL%+4RwyKVDn6Qzi^k|!nYsW0fXU`fg z<~|jhW+NqKwV-IKe)Z(6YHP0;Fj7{#4)Lh#ZJ@2#6r5Rr& zJ~i&fWeW#xD%;%_DQ5JB1qnZt+UkbkeYM!1d$<@{$1fL2J3RN$z&3U-pI`1nR__;@ zi-XzwGj3I;gTfEz=~|N`;8vm`ap&nYN?^;oD1vKV^E`U=qS?vXCivc+f#XNKHhnnO zkWtd2=jl?-Qj6d`$WK8cOBoy6ty9hHBc0lMKIqOKDFti=3nq6G?G!l=X7$? z2c|4l6%68=;mT4Sa*5QZFG*2t{@!5y0dd1k7_7horf1rd|?OM^z-n;|Y@m?_!H z#N>}$@y%hr_5J9PgJ@SfMsxo$4Z>v1O8HwX@C?xQBNXYE1j`!&;D;shfIM)Td20;j zZUs((&3c5s2uvydq4gg$5Si95SqDdB=y2*Z18aPz22Y!ac*gpUUZGy^WFt*Bl_K;{`P4x zTm|=Oxk_wQu%}o>S)rVsj6Rz?q-2zdYL;6%Ojt2GK?^SYKukbdRtLJITo|r@EF~2t z8!sQGriB$PU_jc?28oU!0c=c_s)Cp<&Y|CVk(O463xWk5Yc(C{ryrG!P}4zv39!+< zN=XHowOsjZX+=;mUVsgfCGZne>Bc8$H`0_ofC9nLNdO9e8pq2wwNVC=sTx^6gYu>v zf^LZY4XIr=c?d)}4Klvf0OdEx{^w42LqRF>P)&#Qxux3Jgqint4<%K9vCdSy*v!S= zL6!IGl0~jWt0dIJ-1m_hW!+~-S3ccsCCo;-Oi4{E$|UPapEqvXIwjCW6xy8^N~>R< z<#->MH6{prxxbt7W2}9FBdcO?YlEZn3)*{23Sg`rPP>)mHb)^Q_u-(f7S)J%&dVV?gO&>TLroQ^CDB0&LP|;qu0@iN+%@~Yidt5T||bcVilWta2T=;mF#ikdBUNU8HS&G z>uPO8X8rw6y=l~wXpv6yz28II$eMVwm~8KD{9~W+OZKKGrmYTz4LNK)FcWm5ub{5Q z`YYLY0I(nepBix)ubaXtTc!%xiZR{_%a{Jb6NkqDgE%68>7Xul98-sRiQE3sSSVq7 zovZ4E`|hC3M}?|Ax~fMU5il-zfS9P9=`~Hty3ZZ4mIF;18(rXG+5u))NZ;K32F`^d zsCFvWC->U*ZOL|uXDaZ1>+MiG)?!MLq^K}HC6kO^te`MXNqfISHN6l$Ob82`()soa zv(e`-ha4PgUz>@hudX;1P6no}t~>=Xl4gQ}gcV6i1eyv85H?1}z}Qbj620A6fD1Bo z3Rn=q)qZ@eQ`8#X*{JgH@PcoQ zxR2Y0WE-5yOu*vYDMgACiWu8@NuA<$ICR;HqR>-GS%r@?a(?oL*68XOAuFm{a`fnH ze>p6-EsyecbN4tlYLNWMt3}xM>-LcY+|@u(U037>hMtJ9&-yqGGwx2Dmd`5l{Q_Jb zT=s`NxVtd9;+idbn)xWuPra?wOF%)BkG*RZo)qK?qdR%lS zra(%0WcYjbTz_BTBJA9+{&V)lFN4O(2U$b;nX)T*B4`%?h#KIoM!y-Zp1!?ntEQd(!4tlbIq7jv5To5VI%MUOvE6{+1oWN`ltoN)m0JBDXo=XQ z082Id+nNq|d__yz84T;bX$Hj-LN^=}QmRL_hMGQza&z=)iys^}idoE|zJ=Pc- z{rVPI(g|X$Fv<=fOUeO8#E=AdcX%Co1Ti4n;6oV@q}`AJyJjF3fUlkb9ss@yjWbQc zuI&>v%j`u+_EcqZ#Jl-a5Sc)ag%AOyK&0)QKIK59{pb4l@i0jD9RNA{ZA2M)YLAl8 z#O*iGR?uZWB=y((Pmkj)Ad2w(5pu7-#JuCj_H}brKyEeQp865 zwK|@c8?MYdZkQrFP>Y&UTm>=s4qTOC^1?|!36EpdhvHLzmWv8y$wiEf(bl2;mo?bi zty3be)BOug&wb6YCY8gZ)lTNu-kP6v=)Y68B+qV;D|rMh%~(2~Pr4dRpmye+u&wJt z@abykk=;I=TOsLMUBQp=`PG&>M`AWYhzh%=Y1UYW9WPEYswQL{Y_2Zg@6SiB3#;ik zsm95rsp{_a{Y%6q6Z-Zc|V#=_t8B~OAvB^KetSHl*hq}oop5_z^DWC6ga->FKd-9 z>9itGFlRgM+{SALnC==m0i8PAB6*W zScz@XEnd4tI>6F$7M6O&lON#c^4vyAT*Z9R%zV$c*+meEs6=b!U32b=2x95A)TZC@ zDFFsaS~>xXID|LDEuGfuy4t`t>5*$Zoz{33@1N|8>Lea6qf}bY$sD=@pBh zap{lTrxt$6LDOGvfyoq)55G_dRQXu7L2?m7PfRv6y_IN|s- zP@2jez|K4+GsEhEq0Hm-VQJkVGx}5zILs=d6hR>4nd)K$0f*9hg$M*RkQFBZTqD9? z_Xu(A`ZkVLe{xhLI+SET?Fh@Q6BO!L>&E$2RB#k$_HlryB5<8ha|s4vLw*~mFzp=} zOCTzlV=X2r7fF*oQgs)E)O4A48}X`3Bps`BLLuvO3J?gvT#*=XgE6cfFo7}5a5@4p zh9U0$$Eo53JhR~xpd_!?tgrb5ZO)rcY8vNvv+rr!I5vr`iz)gT<%JwyG=vT4>UqL{ zo_b$Tp|Sphf#4iOS(tdZJb)hx|%@v8*Cg+r8ih_X_eK7 zqVLNM`4xQk$9vNoGeocP5lu9jZQOq#z6_GAY>YK!#k7(!o0?V~ZETq@Ik!u-hZx$E zwB)=q=zFWuhVej?rkg7SQA^IF#E9L?EDrx$I$q;4dwFLLu+E zM+m~-_kq&FZW5Vyz#F^+-r)adacKQOG$H`;=8vXY1_R>mT(tG)pNT%7zN^TgPk&@m zbm91xcKlAV&(&OqX!l4H3;*6~o1W*m;`MK<>&E@913bjlF-_6MfbrJYT0=)A)yx!3 zs2wJRR;_GTy;JcMT4p*w!B<$Lr8Z@uJz0XfGZt1wsphijTj!i!*b!4Gv|ux9ns0BM z+Q?b8kX>r8rK-K1+n3(IX+>f)mjT$V0Xux%mvtJ3yYoAFb=Lhnd9^{%?OmaVEpL%k zAF}J_lvWsPokR0%?a}LHIQF)c&RZZ)3=gX1ItPjj1u|l)L6J+o!Yqfh(|e@VGeOnR zRT|(}AQ`rb4lLh)KB+lJ*OobYY14pQo$11QJX`3@XyeuB>F#aoQ{;tES!^|7JeN`4R;YCtu;>e(uPhRq#>T80dnh(G~1UbY6br zfWp3}AqV@aaWF-^?qv4X@Ex*A(_f6`elb*YopD?#Cx2(@E_`%U%QYPc@ZC zD#DL7Hb@`AMohe?`V^^R<(z*nR9zp9nDjAFIooMVZAcuLJ1#pKC%I1)$H|J=HHBIH zYSDReS%JJm@pCv}SyNm1%@h3aO}p*LOA&#hPOnCqk;*s!mFQtAAJTZ*+YK>mq#~*9F`uc>6k+#kSYj{D(X4P$ z*7+(&rD&X?p4T|Jnp`QqrH|tVntLT&0CT_ExhQEipENQ8vpS5&{!&pC&+DSV>c|^* zc79$w!2!Kae`U|Ht9KpWlx%P*GZ3?FdDXs~$`*oz2&;( zBJ5}WHq~3nCP#2*#n!uttY%Xv4Q$P&>9f^Kem&5R z{ZsZ-&+Q*u)UV((Hoy&knu}Rnh@D9BZM--?$h?LY+0^nv7RpXu&VEJa;UP)SNYBMY z!2&Aquaa?&d*5e!5QLcrYa4MZn`;mO9^hwdMCfXA8P z%YVgCNQ@hG6Vw9sp(Ay!K)w>mGjKm8+o%2~2Ze-3lw|!=I*G55w6C5K$8*Z|eX*0- zjbK3CaCrza|9*g3Xv4Hp0e#Ic=(}a$a4K@rd%4UXckNAYPQZTGl>ZZY+_8k46a%iV z_u=HvkM9yS0=zh5`JfLUZ=KpQ;5C}{2X({;1iy2@Sj|gck&t@wE5QHV0R{=KF#$HE zES(Au@V98j6!LQTB@KAkr{EcLL5nzG0R|$#zz7&#P7JF{r>B)BNlGX`N24hmi#U%8 zxP-?noV3~M{gnCHR<}D*)(;iUR^Tkozh5zDqRkR`vKA&_C)qP@hTYmh`@Q z;sMon^s2tje3$uy&$&Ou zN4&ZFe|UQjsHm1^VRUB5ISELRj3^lq5F{fYqGBLOMo~nNVaPdyh(tvJMY4)yRA7cY z7zhFaDhy$OA*19RhVXjB@qFig-~I1>Z>{&F_p3Mfm_>i84LT{^GhKe;fh{feGf|mnR}jFH`ZqN)D`{$tBU=;YWlBt zl~j1Wp2tp56w3LUsI9+0Q*Uai|Dbp5w_tw{T~qg{?dW~$noAa~0u5icf67Rl3)@Zl zaie&K%plr2Nuxu(XsA`GVt!)mlZi8LozKRk-(K(51l-R@1)o2A%ByE$u!Gw~rOBwn zrCZ!Lu0S<&3iF%fPk^Tgys`XwBiXjLvshEaEvG7NjYJc1K>--n+C`I~N(M7elP;P` zzmep6wR6Hz9T%2qbgfG!KC<6&mt?M63@ts6RV#7gm$C#pYIPi~8mpR{MK5wfVtWoZtXy-4 zVsK!sEbkhcnyswv!!OonPIwx!Qnr}a`7nnDZ&Uw=5rYnP-UT)xx>^!PX*eAkZggFt zX$*Z}CT)EBXXv}kEVdX{x^f$F`?qAa+W#ZUPWB}&PV{$C`$95X4S*@OonczK_$9-t z-e*^$8eI4#nZ|24r+#hEWI612*?M$5gHvABmt0vDYyX{lJ~=aEYZ(p|>tELLbh_`C z6E~M~BXi9Voo3-Z%w0Xit~HkMR&&g!1D>>Ci%ZUtgqfj|)y$OeH}D3A#PPFAL+gLTokkEZOgf6EoValXn) z@H@e;OQopSOm!TmAmW;_a%)i)XCmU-?jsY}j$xSma)x80q2{QFc}qaW6JiX}#wy0z z?WqO$$rex59IcyFnTmegEx@n8S}5deY=+8s#)iKu-1XtfwCTvgQ$To_uz6Nks&PSf z?{Z7@l4IlWNgtWZNt>BZHZzlIu9uCcWecmmg?){nKF>F!V4N<^%VN6qwTzE z+XFN8OV6{)wYi2v%?r+cpl9|s>RAuy4Sa5UY{bE7{*!0^?beZ7=K1{F1Xrq`WxS~c zFD}R#@ES~D>}a$KGVbpW!*P@tITmmp9V==u@FDF;)kito;$aL=6@wM3)`je=2wsy!CNp#a(sH0=(S5XiJ@lixHIQ_!a@UIG&nY~ggC00 z{5g-*MM2~m=je;waFLJYe!Lpvs=d3?+Yy2c!dk1QfJ z5}EdGT}NPs%4uib;{|bC6_Gz3Xo6FDuThO6rv~eO#S#p9bYy>JAyR-NLFQa>Q@^ISH9F68a_6;%l9hMOgjwa zNX&IJY8@@*2 ze>=mx29mjlOu5m<_hEP^w;*pXH;d{)3I>?V9nj~ItQ=(_}8Iipi z43r8-z_Eg_sYypB$tBoElLQ#UQ!m`h)PV4$T4a=@-=enS#4xY*@7D|(f{o!A4I=2^$Eh+Ss-+O6|gY^ z7Y-Ds_2kkLlq}AUUp*c-AT!lSXCmLyoRlI|CmnU)j5<_0=&JXrZLl5~di zqr~o4Mr2eDKmL0m?TAjuAo#SeuX22pa00o_T?6XGp9(KPPLB|ri?sTRg0(On2TF@}T=q+P|H;qRnzF*2jI9Ex7ZXt}TzH8U^3!uC5ea zoD_oclKbh&uC*MP<{^sY0SeooDjnnLZh#^drD>*XOIjps_v*!wmFcR5$j)<#w|Ja{ zsk6Yly~tI{?pGc6qIm$-7i zJ=fM=@XGm1dA9aqGC7ILTkC>uy#<-adt}OzPY69c!Yo7`B_OL4#gX{AYs1zpB?l*T zHhid~{U&vuk0)&rDRo{R0AzNBeV(*Vq;Xa(^G7-Nk%iVH&ik87yF{-QLI1#ThOPt9 z5x=;_q^kCDN_TUIGJ|*IzeMi8i(hP7*jwIzA4Z2yGoN?gNG6gdZC?t|$UR%VE0*gJ zzCV?`#=Et?`=NuEXJPBNOHPNS>-uPD`HR7!U!`6xin}Rl{;Ry!7DklAqDOn#(aa-D zgi6KL&6sqpc!p^Z;8cm^;q7#rUV{H00@+zj1Ad0T28f@A=dzCJ<7gzuw2PH4WMo^-7_!vBkBFUxt{dp;0)Cg-0I|B0WQdIV~*%G zd-aR=-A`$X@h^Xx6S3{sYZ_W=1Lhq64WKo#)b5$*TgR_zrL^ z>(9YXKNFegn$stRa95aqJ$kdOhrgZ`5XG2VlJ^DEK9Eeg%o6qL_g~c4*2w#*$Il5H zIcKJwyL=A39x}`GB>~JBPd_%S4Jo!3pj3)Fa;^T{gXul}+cEPXq3mM@^=>j{Xb(nn zTZ)O)2^Fylu=+>sW}(DS$7=V1Y*w!rrLLZ5JSlYk2(z|b472QUd>2uQ2{u@Fj?tY6 z5Pm<<+#89HR>KFa4Eog#pRbW!`lhX#MwsuZ$l2~zlS@PO%UiJV$}h30J2IK+cj|=8 zGncVu%^ctBQO(Z;z?ePtk!Leo5eV~W;w~wN7N>esS}H72Rv}0E-3LDlPFF=mc6zWd zWDXqX(Le(PA9pF4mglH3AA2_~<^?{0)Ez1OgwQ`WFK&V%VV&RYfwknmei)w~--rxW5#uD@6=5AA4TJ5a7r8#lt{halk z(sIGtS<5uPHI`e8>#f7JnEv(ag0=C{0~HzeU#~gu-dVaizzZ*9%PJ>zI%hAaVa`-_ zpGf3j6tAN1yFv-V{O*10w$tzDB0KL4#Amfu@MmMTwyp9;le3{u7DU4@|0J4`Ub5jdPNC)721eh{1^I6d?3xGK6i1r`Rk0I#Ya@wlnBjd6x4pZ8 zA0(|J&;A~BQmY-<_~OB0up2zDvo~29WdJja?lcRP7btt2Sp*d^^!in@OP9Wmb>+zT-S8)+_-spqnJ;mU zvZv7fYz>0N01FI_tI#|l#G*Au{6ZnTR8zS;c&3gM<~Xirh4nC@3#Kc46lg#fEOEak zP?s+F*fOmYp(=wMYn4qcbwxYjtpKGVlW=1+VobRAH8EiID88Z#hMCKTmomQQNwV1LEcy6BV{8q6#GNpU>bwv-^afr4%Pu0FQ#gI1PPrc?b5yD0jkWsf z@w%||8>{l^dy6bS?mPr8Y4`Li@h@ChhDZ6!`jjN|!n0P+eEf22+Uat0gS4_4&3ySg z;&~*k6WK;TX4j2F>ugKydbZ!3@P_Y?wVN{W^oV2`m!Q|TrccO>y>Xn-aPOyg5~g%Y zmarrB&9Nl4D|5&Qi_3aOTI=+w>+Zur?pf(YH-6(FW8Q;X zw`zP#N5sW_fi!M@mo9>vJrdO~_oHMm`Hsh^XMu>jxNB(VyJjklTmccvwDr@sdDlle zUHSyu7?mXbTq!gQR4(?h4Fh08nWaBUsg>Nu6fT*U^M!Bv$=T3O&-l}}CQib3g&9qZ z{d1L?l$MX`rT_Ll@<6N-nBQDak$rI4kC{;;S35i5sm({(pYhQK-5F>gsxi&y!!rB) z)}mE%IO~JBb1`AspiO6Hip=biv!s3gZZi7UiBYPeM;Ti7+Ws9M>|@1VO~x=qJbfke zCgFvg&XH?B8WT7ihmM}k0Uh4$IJ&f`Gg-Cg`K_`O_^zE#I3e_??WnNbMNAHk_SERK zTm-G??GAoh>b}J0Oifod4#S5)W>E?0oKwuYCOU-auNRKI$Gy2l-AADvOnvooHlx(3 zoa7Xl^V}*TO&Yo#EiO0suVyC*T|3Ww;+zz-?Bw_vdz~Voxb(!a%$$WV0rd#r$2F^- zKo~xhM??TG&i3-J96NVrUEF2D^ndm{LN2Qo5-_DIQz2@ZXmx%ay(3R(nA9VVO32ts zo`bd9$9(RJWja&!jyd9}XxRB2^Y*?bhWMbZc`>_~PanPv<+|{BzlJ5)PkX9#P|H=ObV&eRQBE?V*>QwiOVB|%DE7p zCtx7ktwld^%X5aL5@wPWh}U(27wfEbMxx-w8f%?R&T!~Y6AA#db}{jIgoRXR82dE; zQ%?0@u8JQVU_OE62zHO3;(qr!xJ*q|6+X-BS|%T49aE`zqkvDPFw3m`-Z28wI*0oE zC(c}>)E;+-yY(GA6rbet0$UIjN)e+Z3 zX;B~Q;R{*JPs!F8$$ZZvRD>)Th^E5LNZ*FJB-?i>yp9n>7y8e)e4DjyN~?^Y5Pw7A z1P=LT6u0}=(A$N+F4TANVB8(5&H%>UCrZsf?%oi=$Gc%!e}tI=e0#As6gdE15wlas z0jFo55u0pkBm~|UFQ%})s!~QdvqD5~#1F6J`bzD~?j5yhXDF(rcC%D(bj=7_-Ky%{ zzV5_kKJhfixpggs-(#n|KFH-ngV1P)E~*G?2*a@1AZ$e4J3`m;#G@&$hxoDGzpQPl zjOnowAei}51$R)eI0rk92*Zj!k|}#>44H)TDG^35QGE? zv!9tGY=p09i&c zOHxh|eRsQIidvuNBI}L!1h)WThBsfuOcyJwp1@_lJUg9ISOlo=0csOtKwS!`XG8(D zF`zbj2B`A^^@|HU7oQmdYHdJGEefd9pHN(%cq+bWaj7LN@74t%#B0FjB*f<0dz<$O zPe@oio&xF|KrITWS+4?WIzWBl1fUKD)MOB~8lYa*1Jvn&dPxYVa2W{U4ulXB0YaPs zLU<$sHmQJ3z8>2}wo9%y*>-?hI1y0G0P0YPIvG$`0%{X|Kz##HI|>78Q9%9d37~!o zsFn193VJ|@XF?2b9ti;ELm&o#(NRc} z$FvxR{@t~a_ZI|mP# zw@#~F+5P|enAK&GAWrNKsDbO?cR!gc-KyBDl`{#-h#V;1eX{E7RaSX@1a-40!HGCz zY8^IzX5u1m(C3w%+8kw>hIDv|8>xu_#;i4@NK)i=l(`Qn*XUA1=uDv)%)_hRgwkY<{zq$ur>nkPdLB`&_Q?@$SKtEO)A4y0i@+3yxl z@DEhIMffXW1-=~|f|h=qoiU|b%6hcJJY>n@UhTtRD9XB#0(F**A-LuGB6kY)zy}-A z`yC;9$<#D&KCW}8_~w-!MwF@?M*NNOzeNPMl&Vl1{{(pa-zEvk`(KzEgg!4-p|gVo z`+tvV$Nv|S{{O{viIRq;VhZaW9ziwW27ReeU_&b8O=8Dnme;uuHq zT<(xzwwmmoz58NOmI|Cd`)3Na#l1$Xhf@NhV4eFhfU)REW@TxXoz$fiNJjqmT9wB3Rtwon9TG#%|~tNT(s=PG@PAwt}acW8()NI zbPkNilz);6rx&&k%S4ZGn5ZqW`LYZ%16P|N0&=yDhD~{#Dz36Sp5WD(irjg@q19RS zs*$gZ4eyxv0hy_}ymGV#_vS$je_0~lQK|}O7lovF?~w%Qfh@6Q-PXT!PwV%li^znelFwh-Ktm& zGvtV=B-OL!BfC{5pCzj=Cu&MoR|rN*o@Ma+LAWz8_g=-j&!g#~#rk^qH3Ew$j>(?P zs$xKri#1Bj`egGR+|3)Ecl@FTe)`<#G@8oIm@yt!2M%^b=R4&aOzxr!x|C^O!&ud; zm9W$rXN`v9Db4if%YTIW&0XYBBhPYtMju+iEUP3Yo#O_8h)fRq^Dh0iqmL9cr-7dh z%@$;zvK%-#roEx zN3xHslcrBqOjXXwdZ!P7PzS*W>6bpB8U~_#kVM-5Eph*`+d#d~=3eT)-#!{QyeMp= zWVIVG{7V{Vx6k*1%9pX~%1t4%sfps)+%OBb-(Zs54Tfre zD@ZsYZPlJDNH9#_wJkNj@Qn;sO=hC4|3lCwq99xN7gK3tEbiJWWiLT;kQso{eEVNM zq%Tz%eD7C`D7nIA0aX9v~2uF&L}8`CbZy=~681F~g^vwLt7N=aYCL9s!Am9c zVOWo4IfT46D-fc_!yr1?NrneDr0l%Qr-3cTocqKf&w9J&7O*ALysswwji zmwqpg5SFLfs@AuMx8AN-v|n=Tp2+X^yvmz@-FP~OeXwDpRn?-~x-}7Z#_u?>B1LfE z$>p%-*ESpi$^M+@tJ58xLEpgR#m&DYSszLqs2Z{lH*C-IEp0eR{ zJ((BMthkaX?V1M#)?h<-rQX@}{*Y#@{Ctzo6~7|QsCc35u~7ecgwtnjn+6P}IELp@ zXA^JplWv}@u;z(bwR1fPr*YXMney38_JX|G>Lq;_#HUGzj-_F%S7fNkhGN?(Sl>+f z$7$Y7XAV2Z<-*{uF@EBm4SiOK?`6coH{Fx!POr2xV_%W>pTCe9`*b+0H{i0FO@sdn zg#WUL;NtvkvZ1s>b*>hw^qm&Hva4~YG;RYC6t*ZO1x#z`G> zc=FZ3%30l6Ror#fhw{Jks6SWFyrVwHwRVHdyPdp8N5v$>K8L4JUHk@vaWI?s-4}fC z!)mMji?sY+`IaG;=6x#=KXnqoZ4pr>54ktAIvEw`o|`;;xh~sDX)3W;SIk`!Tt~68 zMIBvB(Yp1BY)eU!LY($ZtUvZvga4K1wV4Qk)Y>lixeA2S39-%xt^kO1JxIRMsV{z% zbg1ZKU;?XvZj^lXIWE2ISfS1bR-|lg6cXw*4#JD`{@)R+$Re`-W?cz&Cwsxp2lBwM z^pTllD>rF=hF&HNZk3Tu4_0~z3?8ag@ck@qFJ2g{s=e6#37nX1t%6!v{+{;UtBQz= z^FjFC9Za*_f7jYS_Dm(HQbIBkQDw7n=UoW;etjQzVB^a5YYj2Y0oNMDNnA4w zk0w^X`j~32mrYzy>_(OKyUXT(+2RUB!ln_!mel|+J3g|Q|%r*-t zz^J@M1h3q}{nOBEXt_(8;n4)g+~c1^aUg5chM@oukqFkM%mB3eHcl2Itc|zD-q}E! zADbP7koxq?n1uQ%nVsDKO;|0+gij#;|1{yh>;dWXp7l`W%ZIZ2MUmBh4%HwGLM8_G zItT0p3e!QN5M&Hfs+wv@SF=NWt`PZcNH8+CS;&4YhYHu8+T^wgFpxEP#ZyJ{CPtvgdf%{8>S%Z%?-HNk;e;yM75U7Zt`O3Zw@j z>00)GbJX;y&OTBeh+G@*Q!NzfSih;_Q^7FP@*$u%zRJ_Kg5hk!U1Dkae;_nF9Ae!t zNT2)UyL_LwC-Fb-!DC<5 z6miCQ72J;Q`)FZUP(Rqg){biLop=bsHe*>F&S`7B82DkGgha4`bMMv(Q^aXz@jljZ zarpG0qCRX+p@bL`+j64-1e{J_(p;r3=IAwF9r1A{HH&ss21qH;Q*K zXRxJ>8ubo^GJq@H_Us9kiDP?spH*Jg5Hko2$P zNv@VY9vgyzL8W>11Eg+=gE5@_4oObc35?icyNF)PEB0+jMcVMeCr9Bn=(kcIkvFZw zYjp^c`y?gRtiR*>Dt#|G-{Sp1WVrs&at6oeDc(T#@EF)_bSpQzL8jX6hjk6{$L^S) z>T|~*U(iTlH>r3!M`yAeyHguMBF|@*7|L2lPf!+bpE#ek`LgtrW~QnhbB^N8$O!dM z0_W4hC9dRQg~l$v=y;{5o36L={Pa|_>^;@QNp7Fx?RUSw6zq7lb@7GU`18{ldTw#b ziIcMTzCFJC-T!#I;_|-{?JGl~b;;JKW~Tk$?3OW3-I*#PPYuR7ZMB-q16VbSW#q#xZ0}Q6Huf^Q#=heR3Dp8p zrzpraV%ip?aHUAsJ zfk;5-S<-%c2ne&SGSiTUc%gxs|7_OSY)P6W0PknmYI7i?V~D&N0H9TafO!ZR6bZTk zh-{tN$va9u^cm0E+7EfG>9>1`z0FXg*Id= zaL)CMOdj9oretZxHE0Nbac!qX< z4SK~pJJUs;SI|8_aJIIM>HGfZyS2Wl(MQTei`8)uP$~$XvNX$v@pmwNSJ~1%t7#VE zWxHOPVrmo@bJr;2v?k|*8-HgbH~(Pb6y>jUW!>`|5iV z^A~mc$xSL&Cu2YHoTZ5lI4LA>5?A7}(8~>`FP{!4+ zUzYWf$14ViZJtg-?h{1c^ZcVSs>+) zd&x1|x|#^e{7(VUM^|%3$y63R2L2HU{Ov)n$}wxXTK|(6l;>@L(MMUc;>XVB~SPeXj>k4~h_3iVF|R*>%uiBHjxSYHCzy;cB+4N46=Oa(QL^q|H;Eb!exfxiO41C0HgfQMB2_oRQs z7-z;FYU>0HV+&fPLoay{BD)IeaF@;#dqFD5G6(!p3Q30!(tv9N(E<1PfR6P>DWnM) zZxA6<>X(fOL(UeEEcphb43d;*SaaK`r24_ zNPH0S^+c)Y976S=Zi82K$2*(ZnSK$yHkGEV(vq1{%DRD1>vVf0}w?Md{@QcKDr^xVJSEraF_;l_Tp`#}!v!i*#g3sc<+;D@E3EH@i*i8|?AZ1;ERf zNI18%M;`O5y~>gT4(rWnn$7VHE$iX~lyog?-(~LY?}>m>T;b%ubMv7O_|*cj`WsI| zb#-E_iMSuQJDJNHu(he4%Oklz&-vY?$xZ8CfLy`aldqvB$>n~LxGedb?|%l3Q!c z&7CB7R(z}%MN4Y;k^|Sb)>it;3Y1u%?98rwS}`pL602s&0f8|p8E}-J>I^>!fVr}g z13=(GPst*RJEmm*N+uy}`|DuWwrE3^%)8P%V1Sqj#TXn$%IyM(Nx)^i;4*Rzt#5I zM|N?$hV&N0LF6zlZv0RX3{$(`#s~tGH%3ej04jcf$NnXGbsX2J~f2@qy|m=HKR0YuMR{V4|~vSI45 z{Olvqg)elmsZ;#U2^M0Ax)-iRl#}0I8^&!IO zT-4GNtoJ=B9&N0HhGmsulsdzY!T0DDw${*{SN7@}vr9(1<_B3G|G}ISb-b-8n)hFmU?TSM_xD?>QWSR?(*)DeBfE@Y`0OH2N)R9|Toi+VIHpOW z|531GnFlShPX|hdVRX!yP_Y%7Hao^;_F^zVOv+74;DhUOAEauV!$GP5fzyc$tAQx) z>XE^a&B9PLy|Gwc<)9@p9Jl(heH+Wv$XulErbmFjzjxrWT1i^1TUVyMlMDs@1XV7W zL5&Q2Hapf}PBm-PxJ2$P7NTN7MpDt5mmW%CZuyxuxOGX8(&7!c%Bc84dD4>MYtr+Jo=o6O`TLjkXNdq|=>>&$4o1`H*Br;F0t@@0?h4ayr-;}w#Z zaS?E3Oxd?!>}wBlgk+j5UulC8ll~YjD0_`(*|`T{&h)O*loXN_xA{xi-wK>JWFpOf z$ULSUvb6l`MyG~+$B#~1SqX&ED>9QWszc1zwXb1B*MB9YEInzAMKhp3TPShhUnjD@ z6)?46Z2@0j*E}?Tk$G%ucTp4p7F!J&ys_OlbHVVck|94q=&H7AGJVa(nRo7=z1MCi z5%|^&l}5jV$6{|`p(3tQSV|n{~T1#!kj^8E}N?i-lE} zy+;_Gh%V4n3=w_G^7f;C%oJH84IkW7YN@K z+aFez^&pJwV+%B)LfZh2y}^3-Q^!n^N){cP|K6`}I6{_B$!tU#BAWf#`>IWi5b9nU zDp@{SozC;7KM+YPV=g|d>gL)}6IEO6;;K(D> z{M4%nq`v3DRq1;qD`U0SrEa6&qSS_ntD1o?2Uc(W+wz@SEh#&NNHyHXUQGh8?%|S| z*-N2}NXBXYB*Wv_SVZ;fCoQBHs*N$j9|N{XGnC3J3m4KpiIWx#dSjlBA_cJGzJWk~ zi!h?gd$79a%US|=apX8DSjJNA6EdjT;z;uEYk0nS*m%xdKX$N&=dKbATEim(09eB_ zrFgLMITrx1hNr_7_SYI7g^Z?EFf!B*Zl~}XER$J%fT$z6keg?8u!QFd*gznAYQmW1?OlEMtSnvty77NOL>nbKWkFavi>>jBtL@NHJ4 zYeV)^&rYJ$dgwRCUUtF2a-jca-^|o~@;4M80DcSYMFyP_-{wl%Hl)s&XKNm9TYPN8 z?wPx%q*aba{~igO+HhW|uiF3hXNjl&Uh~uUQ&}(W4L&8-o}8>8bQ`?w-+%e)gxfJB zujuA&>uMAAVdd*r5=A{_U-7y*^6lHDw#HW1spB`LJ4Eg{;pIP%%~)FVA!U`YgO8*c zF43Gp(qTxz<`&L|HKcG#>-6e{$^KYJ{(0jNMP+1SC2}n8a%aG`o=NIE!80bsALlPg2RAIPd0>{b-OCSRbXbZY&{ zW~rEuYo&GSSE@O{GB4iWpLcqn%A`?xttiC0I4R1Kpm33&Ht~2M;pH8KMZL>AV(KoP z?|jOvbMIPD82Mjcp?AlrTL^pU^|gSu@~vHYC6!G*)9C(o(Va@<3_nS*c{CHUZffgR z_)5Q)%tvnnn*cq@*bUB}VE`65~sM_%pZfjLExqM<60*K8s~Z-(6EbP1y@l;&tyR$@(>)Xfs-Hv;vwRHRBN-p zc^p#39-@aGg6M&w10F;du~Q@%E3lNVQ%eGb&~~)PD$AQ`31H)o!($HYB@8cG;DZbr zAmhz$lcQLRBaHz7o6R6VH{VnQaLp_jAfOb&Q-eiX*`OgrlEWmOKP&RAZ_AIaYug>v zW_BQb?C&fokRN%smNmeZa6s2V9Dc?VfkkG>pw(?Z|JVkS3lixsV>RN9Z_7_s{4)&p#I3fe!+9a5dj= zbAogm@wJBlXzu{P9e$JIFVHvC!C$+*zB6+0@8nLF&#{FVwVx?pOl)n(0sna0`9#k5 zFuaJ|Z8*ljq50ILY7svTHsG2TTQKp}198}f9-S!+QrdL_h64tvbp1#C-?SWV89fPP z1l7F%r2QM`fIkA2@$(R|HHBFAhyVWx=iddG6FD6A5A&bf$Jt2$%|5secf&excX5M=_V2+nnXZ(TOZJJ~ zwrqJ3Iaa^f$6uZH&BP?Aaukqjsg6+B?|DT#mitoy2VQy;ld_zgF>^ zOND4cIjkb0es~#$ppKiK zj>Fd!aLdEjfXSUt5`1e3zAD8Z)+MxG;?KCwpnq&FVW~GCy zG%_Q70UGFYeuF$xQEEt$BaL{7vIoKk1yAJ2K`#ig1|B3Nm&76KzdId>0XaT?05IS> zTv%<$uuB!egjNH{tiPLfK>~Dm4#WxgkQpFbwsP|zKn3+W2RcF9ncsqRqzWLJ0r=(y zCt!GpF%ZKRc{WRWvH~EYA(7XBKA?_3Hu)P1^n;L^9)FqYu;2MZ0E*3tPA%qX{sV0e zwG%y*w*d54kN|{3J-^KLKzf3u@{pdj>I_zykzl1f@U*FC*}ziy1FQc_od3Z*H$O|P zxnLv!_Ael!M3a0_69qghoi2eERdB&a;_ zjy~=Plk5iRJ-6wwulx06@JWRnZV=|*DGqq#ZNSz%Q4W?2GIWtBrhvo%UkZ{6G-*2j zWC#lMK?Zu66hMcTxkNcZ$sd5f=+F4)0No_V*QOun6!tsh9>mK*;SI#=Ew3yjGW&D` z&FU495tKP(hXbV`Ssj6vPAxBF(8B*n0JTj2A2^^?CjlGK3F_G- zP`wVNXat6WW2g`F0&W733-U1`0Q&DIa)L;`9{;_?jeXyZ!GV$?i@hL=kBx=xq?f5u zG32iAKg`ltU3FCJhvG=e8_{=L&{%0q9&M{((qWFTVg}sbPe#s~} zQAI?LbSG4MU6ZCn*S>@mi;676kt#lL)Jn@drHjYbGz?R|!U`Ph91_ChWor7-9vf9` zd)g84&qWRX|JH7SEf1;KVRyR8_)5QA#q$i6Ke*pS*8bpr6^Xw`|Krn;9{hc37iMt% zvfJT-14H-dziZ8(j{MbdKeb_vGj1ViPrIkbv%f{Ec6VRdGOYUhWvf<~m6uh^fz|DU z2tlK}=t`f8VT6mqaG?^ocC+p|A96nXF5moQs^iqL;M5CVbuu_)U1gm@6CST!@_SZZ z!He}fqk>n+Dx-;(FCm)tnA8db{!|;b!yc~OF6L8_GH4GV04O6f5EtO~U!**6`%@SX+FArlsa zMdY@NHQ;*K7DN3110U&mM-M~C zc&KAM&JCrQHz~pJ@&XKmq;b`cz|nMYo}lhJOp5n z4Q>Z+2?#e&B-$b`&6D7ve4zFZ5JK%Apn%#x0HF4dc;NE31c0Uo+Pp;u%nY&yBid|r z2EEM4@RdO09@NB;J7o($+>Ks|c_z@aayxz;(c9*I{4 zLpb2*1R!|{4u%X6;5-CoKatQI?DwL5fBS1F8{!T$_t2v#?}YCpxL`Wyg;x1*A6_KRy!CrCV_D!^~M+kz+ONwkhB1^ z4-@Oax^q3QkaYv`5TNB5{(D*={$PXEUsX2gy5k~JX?+rN54+m|n zeHvcq>!RQL_T}st1Jz#HG5GM^%=S3jJQPRhQBccX9ni*YheKJISE0bxpDINde$Lk7=EhCpQ4^Za?Mmi+$RqgS z9hr1Kr06lyMvLkr^+(;@(6o2>=GSG4!Av5O0}R8|9zN#g2}&vpPUraTdKw0oQsv;?mDQrGcH}GOJ!+$pG5qR(NYY( zkZ9*#X_M)I9xV9hw&{wKe?98j)BX;F*nxi}@}lClW^m3tf!jNS0~;m7sx<*Y`wyZc z`p*_D%*uS?#&xWJcerW3_{fat8l8$f*)FkyEAnV+_1!CQn)_n;snKIj1cjFnbR(EO zNTtTnS1LW7Rct6i?`)M+ESx^Jv5?NwwsYnf&F1eW8G;Z@1l}utrdOP~lsWhrDYzCa zfW-esHF>Q{vn5XFX?4_%O0nXbfiKtoFXG-iu8C-C7Y@BQ>CyxQm0qMb6~O|cbd(MX z3K9ZH?;wI8ARtAmAiV?-fzX3=X)02LAfZd|y?uL>_q?ay_uTLP?)_u(ta;Y6*6f6k z%wBtCW;&poiFK7F>H_&=?|br918oCCmTrwco-tFJoXV@)ykD85pBA4wIA)d^{Ay2JtiOFgG#{zYOB+XP!9d?D9sAK-&Wj*i*F^>^OtRO0c2W4}|!O1g#rq zCWF4M5x{0?SV{11fR%&m^taxH3i9R(;75?bYm+x|!x_tFWrz#$h1evJp~>60x-=93 zcK`|k|L(Q$Sp@iHg7BBD_l#g6LnlhD>l{%>m9P#ySb+dbBA<+9tsAbyYk)Plk9MtZ z+R&u>Dm}jb`8UtH&LzX}!sE%8zscYcRzLdyn(|4>byOSyQj+TiF*5b4y<%LgGwccQ z7fQ*vLSNclz#Lek_*oedpc_SNp0IYCi(Jg4=efC%v6%UnK*gL-BD!yMm@-3?$(qSr1ux4LgXtNHa=5iPlhVU_aEKS#3uIrA!tBS~-492Zo~lg?!hZ7IXPk0R-q5Gi zX{naXkkw09$HhmF|4_s^i_<2#?MNKK!gSfh#z{CBD_?dt#*qC%xWcb3y*H$aquY7? zuOqf*&SComBa2#f(#x;VyTc{2L!AW+L*-Ft#eY^aNTu3ps|90?ZiOj~uK%*RM{kl5 z`qw`pK&dU9N6dLWrqB+$kDuS3GXQ=O$#bv8=P89)>Q~&!X(wB-w!;k+2%sn};oE*Q z5O!ccrX=sPzm!B4-1#I(jy|NKT`;Fy*iEI#d+mpF;<(My_>J1#Upy=(N^G7eftkq# zfke`hvd3bddeS?n!$ItgY@BonND+kNLKN8Vj5mE5O+RoX3EG$wy{$ ztpcJE5QM!MdFKF;0TE4rpajGf`7mDYHP%G(7C z@eWczL?cWq4hS@qV+RnUfN%i> z7E(aO7$AHA0aFBuT|kV3m-9t$ddE3HWI)6uP(%R56-coMh-pB?0m2MYK*TH{QUT!y zDfR&|2Z(Gyyn_@Fu>g`Hd(%76km3LkOF&Tp6j(?B5i5YG2Lwzh@EE)2>RUZ)vA?X5 zlO%css=^;CRuXr^yq25n9v#eGu)U(RWK7%Jzcn)0mH+faAhNq~&@OWD=rG1xuz^z+ zF^F{X8F}%ls)D@-6t`HNVW|1m?1}d78y9h#yA1_oA3IJ}hufY*)|5KSIo4s1Jr0jO zg2zl(LgaDVMorGhUd1eN6V*_;Ki6k3kehnp(qq$JGc8 zb4IiscP$LgJRXEtAQtvBRCVLTV6y0{8-VMR1nzG~(eD!k8k5sG3O{!(HJojn08zQb zw0+q9Qh4=v#thd=if^F>;nbsc^;k8#RvO8d^u$kXx<(p48i0c_>_CFjXbBOzE_P1V z(N^Eg&y&B~c?v#um28Sp%E{;kIJXN#D}ZoJ4RV@;HKD4H8YjN&<|lBb#x|C<-#DT5!zp3Nj)Akg*h}Im7(e z7QY>p;K3Go@>g+n@qd3AYFgBS-!(!(=OP+q0*Lc7f~cXZ@m#xPMDIR@^H@F$jOZNK zuWz5RLMiV<-toNwEi+9J{$29|>#gg$Gz9rK&*+{vqW7R-x+{!Ya}=QgEjQpK;p_E# z^baQU+s6S8WAoeBu7CNf{sozgko-^ob-4x550rs+yM_HGI}Q#Q`i^hC#7UiArjR(F z>#kgzj`=FF8l^x+tGL^9o*N9B@jX#0_vqcRG8v&%14?GLpCf%&#ZLS^*Iq70u9pM| zM8Ow#E{W_<#CR_uU&9xr+KNUkz{%<>Hm4EkwIm~-bBpdv=E=LeXC0%&wnx0Y%keM< zp;}PeLeWiTEa}s)p>M#9J(C<^8zqJ=Dt3nE71Lagy5NvIaebE%m{x+(K z%9VcX&t+!OU9xeWT};uI3auG9zHF{W_RH~-mqYv#+F6w7XTA8nRlTEJR(v4|18Rd6 zQ+(o~o9O92b{s>JAyV{6Wvj;sbxBhra+6mXEriWS@O&ose-BG09fDyWBs7pW`q20t zal!aW3`o!qa0hTpqWr>PPkGGvVR9rxBxn=d?P)&}7-*fO_Ir=dN?`VKcKQ_`A?2Cg z&P%$~0&BI&+60YfdPn4x%zg%e zkCj&XO^F0SXxv`IzJdjPPC^DZlQ(WAbpQGhQ;juI#GWfbZ$vk5ME~V+DkUC2HU9ic z?fKQ(^J~zf&ORF#htz@j#}F?}rj{DM|B;Un6;8Yb7qJng88_Cb&RPV4>7C}pYH8s6 z)9&NkUoU#SwrdjC14VTE)+mcM-IU-`pLH3~%9>l@sfv$JNQm5o;LG6$rFW zWjpRX>)IG-Vc)EEwnK9TJwg(LpWjM~7t%Nq8+~>L9hK5I*{|T5I1IsA9@lCSKlgi& z-q^0fGeQWhy@1zz(c)-!NQ6t*y5Jj$slh#(PBg~1#Tx0Sip3|y- z?&tjDE4Nv=9JnG9(O1I3(hAV6C0+1Zympo4di)t)d?TfEG*DL?@y~Ozf4Kx&qw>uQ zhxg4H{Q0^93O-%*=X>=@*Zd>eO?9$WT(#uVWkS~{mIV1C47x2u!X`?JhzkR8a!bf# zu1JlS?iXW^Z{1(bFRXj2yfA#X;v*tepn}q>&%M!ur!%G0mAAa}cyqem1SiIN`VGxiB7Qsj%7K;;g&+%k!YsG#5N0UB25m z@CXc3NI|E0w;`sG$hb`hhFNq4mqQkN&xnP?a|n0LXNQlp$;W2|JOWTMCN`YQ+tu25 z3X7orZPg(!+SJb#(;Eh?HH*|E!B3LQ(;PKZZD%w)w&dWmH028W1yUM2P`OF2SE4B9CYO< z40h{X&3(5s^57^daz)^U?ScWW#LNuoonIby7wMmaQx2E1(&SaxvhuZ`ZE{kvwCt8h zLqttgt*_rE_PYts3&h3+@n;-HKT*p2&RLXH<7Y9EDUC-%(?@ul?2ZgOmb0s~)!^E} za*;~DDQ#&DLfBqY#?@JSK12-8zuqpn0OVH2I@Ey2z zE)E5Dfbub{Qt}EOs*0IB)6{-#g){9S&3rKF?niLBq&o>B3RA!6HoaE&jtJ)}op0ix z7J`*_eKsT{ANAPs@AM%jC_EVn!%r#(RKS(1_`H8rmJ4ygr1a;Md*>la){CmIIs|4E zX{*3kWBvd%5qlt=n?6F-zCUF)P*+!Fi>N9JBSvRcBb_kADi3ROc#@D#M#h^kL|%j$ z>mZ#1SoWHhZ7VXq4wj@GQYHt$A>wUNJr1^vG=6GZhO=O;lPG^w7Oa5PXpRoZz?Znh zW}>?XnBfatxQINH1y)c3JZD(s1nQCDiywO&!1C+E_s$XEqxQA;fDDpv6~v zT40Tz{{ReLVAwzgJH(U%gJI!({F71*$G4OaQvw)5NCO$i^MEM^#x^i)AY&O~kieLM z7|8euF-5=_fEdW=ftW&Iw9b?3YlinTBQy5%os9B}W!tibA)^Qw)sRsDj6}%D1BM4= zc{Y!@zh`wd3h;N0)XY z`Sv-MPISAE=JE{eO-)YT9CSLpH8n9l`GW9$oU3$siAr!MIBs8g)-wEMxCU()i9O&?9|b6(oCPWh5{NwtK7?{>+;`gYE%he|qc9u7`#-K|>S8C|&V zT7~J4UfwFKF<5?ZYsX{2m~YaA10t#h#artX&jX25vGprY@0-LwA8S3u>U+h+KM;rJlU-5U8@|emOS~&*t@1wUD)lrxxF>U&fZYx z%YD+PKUTM=v8z9(P=Bz{bXRG=vvP%l9W*DBoec7gGLIh1#)lOf64uclCdt)c=5|5t zPg9UlxGi(xL3weJVN|bL)vk}5Mr2j`8<{-O%DAusQ7I`mJ!)X#VT_jP&%p&5Ih>r~ ztBce~lVR#XPO11X!;peu@#qVkLzm-1rsk;usJH$O7*AIA7f4qThc4M@Zwjzz3cAm zdfCR9BU8$nX_yeTTD^9NXurN#FL;2RLvQV9yKN_BLqJ+(MQV=NYF~Ws2D0daxYaVg zWcL?kM9PrApIuFxGJ@@gzn`(pRSCjb25T&R@V8|GoEwewl?>J}>GC_HOv%GYIDU^{ z4gjz&*uO&ctWRRj!=VA=OLPaS{K%N0FnIwv@eL@(TM7_^%FetJ0T<1*S zJF#d4zedPE4kIA)=gY+vVPFMrKC}U1SWX(p>;wKQyc`03g8O)_0rW`H55%tsz%@S} z(ldc%YB7(@1i)oj&Mlw~N@#Nf`0y?n*AqgdrI6{&@AYlg*0&~^`K4OqX1I~eNf=uFIzEU{st*JKi4c$kK@xHxc?4x?0+O>J%Qq;?3m}n%#sWzwfy5cg0!i3` zWF3+O1BoIu77OwO0qRNg!yqV2Gmvlr$r(`~2>}vSXe<^W%NdX*7Rmxic!5L=lDq^G z4QMQogbqlupe!vw!Uu+{B?^Wc3M6{aSS(nXB1=U2|G+d9zz72Bm`IRMW-3kVJiTfg zqB6E!!xYZH9bD6v=vWjw*^rs{+;#OyQ%>P=FkdD@^!<+~AoT~_9TmSkB_eeo;DB!GrCYx+F%~WUAg&Q8O0+O zj!;vQea;fb4uk(JHrtUR*}Ufgr>c^WCLAhiZRKj#&9xu+V&DhWW5QqIcwCGUy-p<| zLij74uoYI*k75EH?E4NRVVu47XBnFQVbN*df#M~OkCC#)YxeCBrc9zNaE<%<6y5h% zHbV-z2j63=!SxQdzz<&c;$W>mtNN-ihqv1;mj*;N4rJan4Z8?QEgJGH?Ud)dUv+evX>Wwy;7_25m_!|0=Ex4}m9v43AOZ@Xh z$k{Mln8x&^bz!K%#JP|)3z?r3xdHN~%>j8EDy#{ifhFJ;Ff>Hj6XygHWKEm>0efoP zre#pqO+=XGe|t`#9m~s_kbl`6yn9K&yY~)w_dfaLpZ7;1V)o(N^Azg4|0D7LAm3jk z=M(ZSn_p=Dw+H`=_+O9jA0>Fa{C9?~F8{M9^N-?xc)tHe;@5GT*5$R_U%fd0M*Lr| z-~T}J`z6MU`Rl(zE4P3;_+y;H>EGm9fLh_e*`NhVDqEA(^Zk4cRW!&V<%~><{(Vn6^0yuEY#&zOK$x_hh{uq=L zc;hUQNS0pF%DN*M@|u;vicvWcSO>PVAVJvDs`=TzzF#Ld_$I;_HpnHu>UU1?y*k`{1`Bs5Sgh(xG>E7IcLDj5Xn+f~6iR?&o_!mB zs(jh*QrAU-|UlN z12#TdFRC`LD}Za#)*qB*4O3yO34Cv(Y7K*y13T^S{<<{2PQ?9;12ePx{?aJN;OA(9 zWQ`^A;{gPrudTEpsTwG{j-BlpuOXgYt$eYuJMz>05N90s*bjl@dj$nrPnunQg?=}3 z?GpHo9DrM{=+|q|C0;FD>_9R;x=4n^&rtgeOe)y=+|j<)RtUmL6}QHuQs0*g z!^+UI`TBjvmyO0*#tWII9QYm~3(Hg^1P9SXi(yUQqml**gBr*JTYU|`?Anth@s^G; zkR!KBo}BU2BMP%skoIz-V?7okX9p9UpyrS4xX3MPL=n^x^Iz>{Q`c^G!5tcxR0pm) z8mT-qkQTZux<08zP_=-Ay++HeB&71Xh8-rPi{IfO7-ce!(xEut=6u~HXi|&kHEU(^ z<7+4#g7a;l)8QV$YgQ@JMb&;KN6htydQ3w1kK4hW)E4{;eWpO;1>XI`cF=w+^K2B%?qwp$f7{fh-l!SRjcVkUW91K$0Io z@(Gei0tpft3nZ}x!@bYl#8Yq!Lp6e|O)Vku4@852*vlXwBWlWpKHS%*_GI2) z>7*frNHOj*5{IKMjX`n^q3OJ|vHYtpbn4d1KHjk%;iGEr`d>@}OmAdva7nH{jZjLO zOlvHYIer@9OV~TJ3oK^&q)A|15MgcuXHVxM@&1Ok{@WN>C2VXmY4EA_;UhLTw<^Qn zRg-+S@orhMufJH*WIx9X?O$=b8@u*WDon!_aWR;~&py}1%KgwG+d}5Z&ySlus7&oi z53%3L7I(^|(_Q1tKD(6l!4X zAB0>+qTZZD*16h7PfCAq9^2#JR8&oR)vk7ZfQ1ZSIOED!;@jSmCJ$B4a2eu$m8ZBi zoM_s>KN)xbZ9Sj9*_X?>&*Wq+%OqYFmx;-*fAFfR;Y0?JXPxe>B42)MaTEt zgoh(E6D(qUe9w2?uQB69(0;xdWkBzvyQ@3ifU6f|3Yo=zy5su5Jmxopc>SOg(tnh2 zJQ(*qn(yCWEH0_H$D|t{PUf!E1l5oI*ud${w2agotGs$$!dJw~eQ`b$p7G!(LCUZx z)0@T{-;>E6?;yJlQpplho2wB3;xrCL+kT%H|P~5El&0OMgPsMR7;X3~uuPS6jPJEa7ZY96FBK zFQ)N3<|Dq4J(@h>Y;qi$O`KXhFt6hYiIEr^U{d1H-+z51&$i0pDe2TMXA+T+7xY)l z4#d&!>pPQ>m>SpkefMKh^z$)}v^aEMx43tR@Y3yB7U&HMBvyaN)Y$d_CEW_Jp0A(uWHa#ZsU6#GFA z=R1X#Kr?pKyuYyGBR{I-yG54z=BqPNO_*+q+zo7R_Qc5~w?3+ywAh(@L_4iLyzwu|~!jtm0fe9qR6!7@_>s zc|JUL$1|}o>$SJIHObd`(D%Kv(e+$>t%z(SL8{PUD@$^cc0Kq6Xb%ne}26Gl>dK~kD;+F z|LACLwjiT|nbKt~GA4Jl3)ggzy?QnH`rhHF-P!=t=RsrL0f`w8Q9{ZE-1l);A|JKHXjTy69v_FsO$ZA%z<@F7cs^U7l1PU=D36 za#PvT_)-lCqDJv7kEy{eY+DiDaHp$?4O`|WHmCS7Z@AW&+zUC$OM9x$&ABTvpPYN& z#(Ll$T6t?d_v}3jA#us}tsmRB%ri1BZe7=*%Sy#z%u0oU4WJKItdrLweUNwnKli5nbuuDyOxRW+X^^v{)$b&Vv$^YR^TW*^qQjlTlj9d_iNKF){I)> zQo*qnZ8JXUUvDv>rRV1O9cvAgNuh!YKsls$y#pmJq*Lf)d@eW8Zh*skig*?SIK?CoJdD^jn z{tL*z+bN>Z`&TZ(U32dVj)vpy7QuU|O7bUio^yv9pPdjDt%}8xvJHKu16^%ChY$5) z?0&hiQHJn2kFX6pD4z6|C9vAn#J3?ePWsxzRV{tLt_~L#cdk8Alyv!J!WxEBtXgD3 z_I@L1WOKSni;)j|jU8V9S=F1u;e$W;a4rd(_>kHfCE2zi0e=;|`^&IMbb`>Sp`5O= zJG`F+eiJ7lW#KhS(@K<1>LIM_ro%zMS<)ul38%;}-I;u@AO$j%ws4*hG zpYHWmUV8F$uvY+0e}nrR+%0^z$2IX)NrwtIa&}OVQuT4(tP1O^k{x*sjA(=DvQwWC z{=95vDY1_HrYh6T0Mr^qYBi-dD(ya>k7rT?IWfF*WwIU&hGUEa+?X(t^6JuL{p`xZ zBWe65w%r4JrPZCWpKGU^eskb#THBEU4HY*Bm2%UVZ}1D#%Er}|{=km3m-v;r&G?le zr`zLZd?_Dc?KQb)hdW=Wc`TN_-fOh9D1XmGxrK<)JNq(CY=no7HR?7i7w%`L+AC{x z8L?H-M>@aoWsvPWk+j|$o4Ka$*w9_>RaiqEgQ**K21crHu!F*hz%x9K1vu7nR7PgQ5YRAxhy8e$Jg6nVHCi>|VQq;Q31DFv3cOukV<} z3BT}bG=%@{H|k2pDR^_N{F9KRPBCWW!&}Nm`ZQG0+!PMpE!DSPTyAC~$YVjMD4oSd zP;gLXuu(Wbz(V052oAtZ;b7>)5oU6^d1=>;y6ADp$gI6~0Kd#vYJIT`PUOSu%0?Z* zFHq4`6b?KrXD4n;UT%&xdd$U$`f^=JBpnE@0YM-T5CH)h5HJ7%>*El9nJ*y2J0Q3M z1inCULhitGz&vq#Tf8|IV;#a@)e8h^K%fW&o`k539ddA14g>>0kPHMekRTNZ-@HEOsH%Uuc|A8YD!E_@pb3o?v?*vL>T7s5F&@Rb#2m7Wbt_^Vep;ri{GC-ETOQ! zAveZKg2{%D(V^eP)gaW;9WE!ce6VEMuQfjE}NBi8o&fT3{^Op~ABU-=A&e8sN#27NCl(nGFd%$dI z>3yAd#eWP~*N>IGImKyX4PIM^N<*#=$2-}k2SU7$h6sJH%VI-uv+K#WjB{76Ve?n6 zc{9$}+#4g9I5lBc)BoFPG3Hu2Q@>@R_3~iA^A^vt;R+9Zm3>3J&cxr6u_*hxe?saA z=eaG8tnmB`_dkjGtL$x0125ZG#(x*BIoCb1#N*t>+ivGW;E-pc)wbx5$=0Wip9dsE zyPeA^={Gg$4^f0SeMWO3l`ke+4;H@wsO=lF>?nxx$(;0uh?yH6qrVC7%pK7|wfTgi z$Y=71y3B|ldyjv@h4Z*26}g1^)#gLIBSX}-qGc^cxF@uLduZ#T;|~+98&5s1gVo*d zG@k4<&@h_gZZv0k++r)8q=5!_r*6B`=u>y= zsk@j4Q3X8{+tcW?H1Pv!>>1E=2IlYQtQwUh7@nr!yEeZ)tz`d5ZE`ahoSlZ-s!g7s z-|C|(*)~fG6b18ZB}0Qry|&@4TM9n42+E@3Btw`@fX*nVbRk*tdtask9jB1;A zP(bnkdq#sC^@fwy>{9AE13qOiC-Dn3%Ohv@=OLgB$P#;qA9r4wIPUXn8iQ}xQ^E67 z0sU_Qi~)RMF?2$L@l!#_setD+L*{>Fm^c-@3N*VFt_(JS5db3qMgoik_?ouy%IlcM zD^XxS3hYM%j0PA3Fb3cofNucC0*nP12QUs`JivH>2>=rSz6JOeU?QHGW}>p0W)j#> z0{h7TlL4jxOaYh*Fcn}Lz%+pG0KNm54lo^H2EYt}?*YCCmwbO<^#+JSOBm9U?IRlfJFd{03ty?B*<3`_KU%O3BVG7rOIX|<~Y%8 zxN6aC_-ctM#65|lv&AOzCnKX{C)-n-TKrMgNIfoFp7rR0*!Bl6Yq2&wAN06P5#?v@ z^G69cK6qIe+rB`S{@XY8+b3N0n^gPnu)BSw&kAk-DlXor==#9zDIR_PsPZ%J9sRc- z7F{=S{GIY&x%TvPuOEBu+c$V0;p%hk9Hm!6Z^+yqbDz{z(4*;VYnl7whiQ95z3*d% z;{`R^DrTEvspI*niR~64J=C)>wBdtKsN}v%L6oH!*Iy^UZSVkw^5UgpI z6zxs!_Q5JSJ`&HBeh^h`AV0E!?f5RHZhogfN9xj8n}2U{>lCwV>FqeV$-}Ro^}pXG zqQ(BYz}cw4L2oR=US@4nx)Hq=Xe19RL5e&-E|tu>nm9VWwwC9mmBi6-p}gz=J}uC& z_Sb9)W_sfkFNJ)@$8^GR(sSWp~S{B7S_CYYBj< zrI??SUgWjBSn{2jFrW!8MnM42F&yXPJBRANOMsiK#uA53Ar$(4oF*RMESbWBT3k7i zaqjR_!(+rXa*QWOT}E)CdE6l)-g`B|FsuR#y`>|KP-y&TJe)P+=kHLE;cXQ>ob%OI-PZ>nhu- zD*8_oOIgFLU_NK=O-+lHJ9wc)EN77PBaY6;yRjf?l=rYT-p9h5S+2*yvnS6MgzKs_b7VG`zfgg1#DpvrRC3mI$K()Z)#fM;%nzhm&%nWue<0mvqG^W9RTMWgCx6;QqSod1=<)b$1*epHC zyW+<)*mj(Qixc;h;~$(cgc~@U;dP;zX7$#RnU{&gmy4HoX%=%hxzBG{<^0 zawET!u{&hxt%mTI2i!2qqm`eyor0y&x51A@X>q$X$L^znga}9^A&Ebbkkz&m7-Ln0 z9^(QDEs%IX5%I@ZQZ{eef!w1Xm6El_LN~87r+si!gqhZQm_~^bfxwonI z!XN^@X`Q&0R&|MYj{hswEEL5_RzzQuH`N|R<*U(y;_P9w!#pdE|<4L^_W>*lV z4&lLxw(>egmhtoK7fU9kZt_=&oEy>?_?Zx@2eR~S-(Yv< z-vo!=nOJ|QG4sk8*L2A_7Ol852R_zDW0*zyA4>$b8HH6)MX+h=m(fw9)RnBz6%%LM zQgbm95el06ZP!Hl=_LGXLR%)QGk6i8-e+X^9iQEXA#y$}5iL|lp=p*cYJ+=_nEOul zJ?|>0;py0ZCypr6>}Z+vc+XqX!S;c<PhWqwn=?n9p`RXl9O4>yZ;=p{$2|Rr0$2)weRcut=ZwqV)-dnoMI(}=R^ikr~6f>Sbd5$r&xQ6b*ET= ziVdfTKE*}|LB3C?`%S0Ve2Oin*t%||nZKIjTMH_kN*cmzt6+PbkR!;Z2!~a{I7J-IR1CW|F81?U(46UFK}fX%!0p{Ma$#Lf$$h|1a{3NY$Tf@PN*M(lPe-JS7i{^*Jz6P`kUW|Gjpt_rSX{>=a>O0H z~DQZD-}_X{~OtMzs} z7De`9qYrHeP^!$!j13Jo_*PxL!-&&NKjs4F9mspn#U z5$epsH_*LyAg$Y>b%5GBRMb%UU?l&_{UK{(xWtF=8-o4q%XIeFm*3o89K2QAUGohT z%1Wphues?z2(&|h!BIdfn((!%urSfUPI=QXDF^#%v_X z#K9etWOU(LNmXQHE=JUCe0R%Y2znSl>Eb7K%D^X{H;wSQb9x;obE0&vKAxCKy@y|E zzgu&iV@xk^fqFrm!Z|+VQ8vc#fq;1V_t6i%3h7MnP9+HxS6_3ueZhA_Dt*gDl)?!^ zV{8KNGFoY=inOoU`H&)jU*wLFDGim5_mhbT`n4;u@v3kE;px_Btw6ZXx*>8L2esvX-foy%1V! zawt%F?i=CQVUVA?jP1v1TQjiUwN5WPw0DX-u@jQyP4`K%-7|14^(1yKc46aKK+c** z81*WVjiTGCS#}NXw)E%}%C)ssZ_uw{`6tW^LxQ6sgAL}oijqJXdy+JTc2I<2zB%hc zN3f-~JhhQWw3oDG3tnSZesbgw+*`XjwDEk7idIDD&C@hMH_u)I#p~yuvJQD?W-YhD z)#$J2N^_JQMVU(FqxTX z2ejq}jU1r!pD0>1fsz?d_l-qYP(jMr3t5T?QKP@iQ3}<-JZ88h<+y}&d%T)WK+gQP zkwfz!SQG?e>vqiwuZr^J<1lV4o8rhbBQ3{RWL8 zsEqMhC|U%ALrQerc!~hQ&-X%(!u>jRML0_9Krk){mIA>IUd>Pi>~nnN&XT;6%(=~EE=3>-Ne99f8?vzcvcccb>zibm#A+SH5648G%hfD_*!sfwS%PWNq{L<%j&syU!mI z8BY1b^t0Nh4@q2}Uu}9!v2jRJJyw-vNI}PPelXp8`zk1%N$w0-q3tyC&RAoz+9;Jo z-=}*7t6n(&qtK_~+8L}AQ_EK^=+XSrD$A=01l=x$s>8iHXBoMNso_`lIEAge79ZXh zvi7=n$FuJh)%vSTHy+}~?`RXM-{%s35xjW*g-~$tJ+}CfXmd04n@j5!Zp2k?Z}=e` zba-2)VnR+e?tyizZx0*ie5iA;6+$EZg*mLxQt%J?W5zy-?W9719NWd%`^H`9A=?jP zz33tP4<8czMPGcMJ0>HuHuDPP>d^ zZO?*{Bbg1oot9d6(-3I-Id_kHTTfeirq*xsUQI6hPKUCft7GPOd}TG&n5RH4b$w{& zM>P2^MRff4giWbiCR&!?#?HHU7=zPc6G!o7WmZEq|1mQ<1rncj%}vg>D-jv?KcrJ- zjW)-%jCy%v8<#D2-PKd`9gjV_R-&4^`eH5H&EISEbul|G3p8nnbKGZCv2pt9IK>$g zpZ$z)BQ?$9 zFYAN)2s%|N?a6>fnG3E#nM-1MU*RZyiPh3&+noC~{AS(5zg?h%2RKr!mXLlDz#-Q? zYz{O(0}DsPOtHzMGhYsr%QS}f^6a8J^6;E~1@oKA_TeE6W`)1RYuI($B#~P0G)6GS zOyVJ8^8&CKyI34G=UnRKk)ku$P1w_mC3ae0NpVuYi8sks5)vHj_}p}~JEAOiGj`Kp z)@XZM6H05%n)H4fGa;jhss6$iYb>8uFuvXE)~@WCAkO|Gxn}6DJca1wyfmU#zkRPx zVu(n@HJm7I=A#JK0Zvvz#U8_c%g^{?hi#Q-kZm-3hhO+>&{?A$_4NaN*z8lE0BY-G z0xnWawmK{&;`~aR5Ce@~Cb!^)XVr?41UB1^kG!bxDCO+)rO%^ll{qZt>Hr!lBMKBZc?U%vQud)vlH# zRo!h!*p#J>aP}>!c`zeqW1sf3=+Tm+^Cd3^mALo}!@xB8BUElwjL-1jwbG>A(+NQB z(UgNu8qY?XSExOb7DVtp zXdVx?T)WG|U{(4W##nkU#6^JN43>*Q3~c{vgz9MqC?b>4AW%;;xak*W&UgGB$NheZ|i;Iw@5UWJZ*U*J4?=C;loOQjB*2lC^i zu3hV;h@JJ#(b3pTRg>xE3&lYWqSWOI9Fu85mc1O5P-h5zJ;TIY(rUY+uf|79+3oc= zT7f@7DOqB{Hi2ccbwVxQ(k6P~CPJV-Q#L!azk}N7M*+&`wou=V9g6I!3h<4XJ>_V9 zNT}_Y*OHW3?sK$F)+pHEW-rDQzd$sa(-BXv?O4^)r`ks~_E=V`-Qh9F$+(k z8Xm+H7PG(x?{rYaZggwJhhywVredwy$FB~!MR?u8VqSOP)OJS9efU(x8AI#F$kx{} z+E%`b`jyZVj=j@eJH7I%obQ0JyVe=MSaQQ8pxncxV7Ah%D0OgtPtc%Xw%o&qY+&BK zD0S@LyN(C*QyVI{MC2|WEODe1z9r5*?<_sq9=b4RkmkeM^oXLYBEcmn#N_Q4 zo7x{XH}#Z1oQ@;;{IkSj9IbV^jIml>{+AcBdYO3fVB zYK+k_5x=4p z61ER-mF}yP5$e%eVUm=kSRZ&!zfEc#a5C{g@De7aSt_J;z_Vf<2&f z2y}_Xa0cNrt}x;BkX|HU-$)u#l$J4`@_P^%)2AY2ZX8&Kd)xnxPaPNfK28=|vcZ%F zTj-~Sjf)JOdNw}cc3jAXo-PB0;T1kyqxu3Sr~-uK)O)KS3jD6=6gU&wq2mwGm_m~_m)LwMbcYxc=LXeVoqSC1SxUhowV|~4Tiq~ zLZiXWst#e!l>(Y~YYSST-HpR7?qmZ(J&F8-MpZMPnM-CqOXwr39J^!1&AMZ4kw#9_ ziTu{+Q@4bEkKd`gq2Fk4bVms@I_5(p_x!E$J>9`Q$FUh)DbL484_${|hT^U7b%`v>C|Xrb2`*ABW%uZUYnI#yG>I-2I=cElRr1lBE_ zZQYAmW{-7eokV}P@ZX;6O7L#pGg!U|?id-_*BuSg93ceC6r(Q?`}(hC58rA=m3?oS*v+E#yASTypn;48b-; zwds^!^S@#8P45J`?@CaTe~`aiQ0+@lIA0H$rZ@%F#gM6whWO(7WBOA`WMlqv!^Zsa zV5O2#>2gI=`sm{Wcyduqg~CwgU~$CJen-~+Xjj|tv!^l#N=3~pR%wRUl>_8@Hbl2k zl0D>bA)h2;Q*@h(-%dJ5Hy0x(rFI0v3}+@+2vxnSR^hB**Z7cbF9+g>*MMhS{GH^t zDM15sXa0Ug>n%*($TTmAY9bB?jbBL)<3&9>7H$;W@FjsWpQs_Sjuk=-vro=o#E$f( zD-gmtCoUFu`rysfj#23M8Sgu)?!+V91@5(5^q%O> zj#oZ%gqQJqGA`n?k@#n&p6ILhSoM*fg-mLBUiTQ-h&+2d4)g%)t&1jEmCM^yjY_Se zi&c)fAOfA>XGY<9+uHqDsvg~r5KNM@~IhX-b|=(Ulbup7bTC|OtN z1qrrsx{N0qXAK2#DBaoDmnC1_cm7FK!|Ml~*MC@4_q+31UDHhaYs-k9Kq@~8<;1Iz z&>Jzfd-pexpdEH_S_dCznLp#x)-@qq|H+=oRQGbhA+W^zphR1Wa~3QVZ>-S6>9Sj| zthP7kKPG7-A2>rPI6f3m{#;p2y24Cw{L7gLK?61EkIya1{;ey*H1GN3++0qdg22RM zstTDC>)0Cdm*t!<>%m$5r?elagft&IO1QE{r)0*Fm(%K=i&+5Ekde%8Si@o3{othU zKUx}(_P-@lnGie7#z=DeSLi-A41^bav7@N||9E>3sHm20U6>3iQ9+_0AfiM;XfkXi zsYnnIQJM^*gr>+Y4U%(epvfRPXL!}R_c`aDckg{?jDL)O3_fP9 zSzpant9pg1T65OQe(d1gNZQx3W=U(y`)-X~`|N_!ncSL}T$}5Xa{S5|bpTJE$5n0D zOX5nJOJARBqEwW@B2HzxD&a;I3KdN7R1PGScknT+i;^Rt%)@q*W-j-<=m=|4Os<3L z;2512P+mMro4C2bAbM??veIxi^NZNsQ2t8lS)x=IW|C`txHe+OQsznDL8dX+EMrBmL|tETb@?H@dpU*Uv0ogK)k}(5Qbz?N&RxTCw9$8kA(#_2?igQ=AIX$qdkY05a+kh>#E&OsCL zzi!}Yoa$p|pBH!zxog&&N^$9xGTkf~C$lM1UH8Wnoe>0E*EHAt@j=OdBX8UYiFQby8B7mJYn(%_d}Tg-1DkW;;{N$Smm6 z?IrDxGm=^x%o;q$nhmRlEbk#($9QZ+b{>=B`G#oMF4dO%jHLGvc0jM*N>6VZ7fbA7jHrw3Vy@-zQ zh`j>4Z*Uip=Jy$WvmzY*v$~j{{aNI-zES)aJTiK>zNPyNmi;Br{!HJ>9PgR`EY0wL z{Nmc_xx@O-!d_2R@+Ef0k4!!T>YP?0LAgx6#~~ENnjsXX!77Fy=vZkA=vW77QZQK$ z^!~~=4c4nS4L;JQW!<=Nzjm4zFFnE7nf`um?PCF<7(?Y?Kp_)P9K@Y59%3J*7el96 zn)RNw?XvoER>ypSeK{eUb7rU5`tuE$&jq6-rbDj8o@zpwNjNbu6=LB`gc`dPf%%8$ z;y4o}jFbplAIw-D3Bg0W`-%ba|0YNO3gr37kN)~`!^cGNPpqD}d)Pb{o3u6`+O^&w zs?IN5S^7>Nd8XYwAcuA`;c1%cku{`wNMLIm`d3N~o?GGPY>?S`RKMCFBj9@fl?Z_R zKaf~lrhtpVf5!iR@%~eLETA>&P;Q4kOq)7qAM9Qj_FRrFe{~<06?0g2eSzEcHE(TY z?n@Alz@WRhZ4=c(?+3_ndMZPtV3T=?P_^hC`~uNCL(EyE?VNgcPrgg5-imxx|1(_O z|C{KYd{0cqQ@bZR*x8tjpW)Rw8vgV7^WkTUd$TR;9Wk%OBj;M`sKg`F&k~0Ur$5xb z7{F~Y52Nb7&p4qtXZLxNW$yU;%*ssh%57Yw(KwWWu~lQ+pwkq#q%bMIzk*1aK;<*s z;Ezm)N|mzZQI4g3Lw0$PN@ou`?V4+n&$_k6I5Y4N_cDk9{(G4p5Sa3I`y0=jD#>RA z&_C5MAsDklGpXvYzE)lz`s9e8lP6=x_MMZ$XXsOAo(%Tin_fYrPA(qKPH7aWv}E?& z(xGqr0t(H#FDufGeHr`Hsk5y;6!*ESKR(o>rr#(Zq^;7-cFU?|h9~1I5ujdq`irx8 zVv}W6CSX@#*)xp3OeiGN8DyE>b5PNgelv)p;dH@9>pFv(T&V3v$ZE4#~h)lDQT zuZpJFnHZ^bZS!%DfXf3n+TzL+?Dw{&DjoI9gQX2@c?-{e%AmhQ3l>S);6@MfvE?shg9RQvoqR*;J4lfzxlokI!(3inhqw;<+lQFv|r0P3q;XGhX$sBm>4nV?Pw4a z!}Cl67vO(#=~4d)TzUZecQj6BEC`=5=e%hN;(Xv*g=rYALUF*M+cb#A!9>%5;GnKq z5-`Ka@hjp-Pxl7ZKZ6fJS#eA>kGlB^hWS@CPxeDf4y!5Cmj+0SQPW(9qwt5{@Q;I155d7F(pbe(6uyoGleOfR14axVxy-1x77S+efM zrzn=XF*jJmG|~Tp4~Enz*R|TSn}_7=b+Rz^!GrnHX71g@zw}@1FY+Vh>}z>D!lw5{ zD7Qn7ETSVcZFvFd-kNu?pIdgBJ@W&Q$LCwZPqE#hVXr zZ=8Tvb`R3!_jt+!V9k|OT^8(V5eUD@U0Lgir|<9N8PBEMgUN^+wS;{1XF*VGtKbP4 zOa@N1=4$n9%yE_T9S*XTTWvp3Z}!O!AOz7JwFZ-}EtMf_l02&Pg<(O1a$w9pp6U4H zSv&)9$T|MXvo64>fbv?1F5kI4-uACLt=cT~Xbo))2#9`kg0JAZSzI-$~fLvq8yV|l$8o|AaDz8lGy zszFm3-@>S{E+Bmn_s84FWT`XVS0;5Yrk;O)pasGpA$BWY>me^=DfDhpi22ybx>b;5)gcKXQeqbcrup&=6vWtRq9{g3WPF#VIcM*D z`4mOxEq_tdD3m2}*Jff*Q8w;bR7_m;;5-|F*^X*d436gS%>@u#%`51X)!qSKCg_-A zvcSs(z)QQ!3tlETRXo#~lJq#<`EVL5aNZDSw_(kt$hnrX3En0ws3D1+Vk;-bE>B#I zgxI2DEi+@o1O}JBT`4vq&d{MrR(*pvD)%T7H=~646Y^MlFOazh0kLp=Yl9|7%E3mr z>J;hw`R$(3tFlN_&&A%LHSPD4MDht<)XdlzbL3KoTQBrMLlYQ1#3@ab!zi{7+nOcUB?iSg`Dxp`9pYLu&ayKuGB9BKuDtykGYu^2IPG7>ABuYo} z4z})+@-CUzic|TMuJ+aScX_wEcoCb@@-~A-PB*2gv9UKKifK6TKscyYoPknzHje@5 z*%{o!{dWlliv}Ptlf~~k+CSOgBL0SS%fn&P8HECSq7l*=t^ZEY17&i}mUp_}2S8y16pgJ1;s-psA;9ctm;6`jhMKNM8u%&W^-D)3p>yM zM3Jx>Tba5MllY%-{{wUXpvdQ?q`Un3_iNv`K-H2$yLjh>GEQG*c<6o}ar>-4{dSI; z)?S2u8hoy@T-4s~S>1G;aQIp5w`?MvYWCEeK-!0hF?_9ft#YgG4`|32>%+~j6SuwM z-QY(_&`H7D2xZ;vPQlQ98*W1IPyL-ePfw-+Pm5)WdtMM<&!?BRth#5TRfBpj#+l6E zn;)75abglEa1ScVg0Pm#;wc^H=N#Yd5HQzEN9BX5MhhVc!qDPjV*G9kq5B0?Ys5sT zbb=sC#6qgUGRIBJWjrxlEHU8apY@SV(7yW^daKh@qRtW4Ni|CBI8SW}GkEH`bT=9g zF*wez*Tg#oHS6%qMaw=yf5m->nZB(Uj>ZOIzpqR!XyHAZ)tF7Pe}o_pkDKPM-^?j3 zdt+9GW0t#q{dW@IEH`&}9MyMbw`2ef@N|~t=L&OR5O_Zs1m2(iQ|4%&lqgK!{NKb`sQrq|!O6uz6;njPD8u;f zt18`VL2mSNMtEcO|A^M-ma}A-D_DcFxk;8;kS>ldhwxCw2tnCQse?MQ#>cuB?_MDm z<~se!g{3Kf@V!R`E4xR<&F|+!Fm_5#IUyc00fQ1r>3!PoJzG~bF&XN~GgJkbj7-TU zPQ88FyU8;d@~ z=xAsu44{v{;~c2<=KMM|IY)tb#H7X>9V!xfWg~VW&@GRfH~tiL{81jRnD^x_;zgjv z{k*P6&*7=pSMS5hYuy2 zOV27x_3H#t$7N@dFfmES*@vM){*Vo!pS4p5p!cVqGoexl3!O&h&K+8<0tdDe5GQT3 z>E z(@vs2O!u}eJ~^+hh+Sm$9iC~)Oz$d(xTBK~&g-XdJ0t%B@J>teI9)}8<2rT>u(^%M zI2R}IMq`}Ql)TWjZ~Y?!fMXgNa7<(LMn?@6g*G{DTe+O5KSpSE?)rS;TA>l6{L7&FTL*wVX z(9bHxXUjwwiSmqGWl%~_vTodGg4rj7U!L0 zP%qljvGU$I;h_p=<{sIKv*ZCG0K~$G;+_}_h)Xx@+Xz710wLGHdF=Ge;u)N+n059U za2@+p9U8#-`WD5jB2kvSdEhhFz7l|l?0YeflbYIwF9`^)fH1}Y2qJ)B4G0T>&`x2+ z76mLY0)jZk0)`+A2*7cyeFhL30Ko?kF65d&orM4k^w_UTgmChfVSq3R2o-=}0|--q zPz?yL>460ZumHTr+Q$H)5D*Ljp%xHaF&5|mK@bp30bvLbvMAuPYOLtMBtQ_ySilej z0O1`V^Z`N&upkXAxMS)N3@p$B!b3oK3kY3+@EH&u0)h^v4uJ5Q7F3cSRMH3#+5sVg z!s>ku-VqHZbkj2gu;~GtM=s*DAp=RqG(F|R_|eoDHTV6~i`-ySV|7ke^j}Fz1ZFe! z4K1H$ZZK2k?|jONzm!8i0{+hbpOQp>6Y%ri&<_2`)Q~IXX8}p3!5@wnOmLQKM}(I{ z>X%VutCvsL>ku9nXA5=tq_GhfVbDpSIo;fOk*t0d9#*&s%ET)edqhSnnTnqvVO@$+SfQU-c*5fzJbq)67@<%>b``b#qVMqj@guKO zw9yKf?I_Zq6ke-NPpjW9O<$-Vb7}H)`*E(S$5fA+4Y|)O=Or)6;g@c(eOC;t%CV1B zPn-~f{oEpanecY10Y6^B3kni!BlYK@SP+g#R!^>G&jx>nelf zJz{Dqp3g=13Ka6V2okh~DTT#%iTB^pwFV+D$?cO;7!~uL!gL7M8Xxwkgxxja_{vhr zh{%MO8Ei+cd%Y1KxoaqiA3D7~nEGB6QY*-Z4h_3H@=8Y5Rx%tDE`{+=nA=l*QfqOS z7uzaC>gcR$iMRXGQk~~5>9Fou>RtqBM4p%5~LmoBGbx{AUNd=a`^oI=xpJzJR|1vysu-| z!{y>~!}8M3-J^Xo!h1`Gj~S7< zm;I@imfJBKwM}(yu^P_16X&tKg;oR4CiYx3vJaR0cJj|`9WJY`Wb!6WUv8Zo2QBfg z7)|>tM(G?qhc!g@nB7pDcICfJW6xlElpM1{DQ2@=O^#4xa#yl>aG|$WOg^72wX@f^ z6IOk6aiH6izZPCwb%f-5hC&3KFrUYD6)Gn|p>qp`@wylD`5jTtZXS~HBU?G+($nTW zrc>nuJ(fRS=U%F69%}~l1`ia*@83IIVE4FkIIjM&7iw-z0cG$wX97`-)E&unL>3g{ zy78B&^POwN!G{)AZs%wF9TQ@Ru|~;J6bCY#@blrL>X$H{)sX?sww_JpSIcEmy4fT( z$xS)y-LFnR+pY;I?>Lmh*M1tfU)WI|6g@Q&rIC}C9LGXr{0iDCaYA~YuPm{E(n%moo?N!<{%4s83zCXl z=5oRLJU`S>_$i&Wt~4WufuX1))Fk=#*ib@owup(Y^nu`fp`UpFyz2J`=#t|Dr$mK9 z0-Nq_y^Dln2^zA+_A|y{!rl42MNtRAkZA?YCWf4OAZ?;{qsPx9z1hdfT2VYc&Jl9ShgOTvduy;|ZkFU@ z(Zy(PcA)q7mX;bYPeImHL;(-hAJn*QN2zaZiI?qQkU*)_b@{ z=86UxT3okpR&O?9{b=3sc;`n^_Zg>Dk_0Wi-P6S~k?o;18?ee0&uzo*@@(`$yEhVk z+G%lEF}BqX^-q~~mA>y?O1(5;QNgt2bFM)ZsoePL3}Fs4;2CeTQCoU!%69_ykFTVF zoI;xjm6;M0TUAi~74XXwIhU5fz5sMtR=Dp>tKrWCb-ScmEJN&%5c-I8qs^=;FD5ak+_${M&)rVd9;G8=F~arxXruU_|h|%$XmR6h;`8m_+Q*ru~EnwgG8{ zYdeP-ASxzkn)X*D0%uO<`-~BWvf{z6;&+^q-;@uY2fPt7J90C(Dd+PuJ9aFH4)edW zrnar8CCM0>qnsPR&M}<3bXd54>}KwdS$XMKz$WN5gMdviO)TfmG!Ze4#0**{wzhle zBpKg;q}j2Z8Cd@3X>-Pb)x^%J@Y5r8@seBgWK3tHBu*IeDlb}5#6Q0`XLZ~xh2m%kqc#{QN%23{Y+jf4daq!mpdjc? zj||_V6ylr(j&Dx4TDpX&{8nx7fhP&~5E1OAFAeN{R$0&f46EInIkydzcM{q!=B+}@ z7$)^blCgSWuA$sj{3trae|Pbcwkj0aUW5u;&E2$l3>%|T*!Z%r^!3kdq~z7QLc5hz zYo_XVIxq8(9-m;w3(jYScY?izdrHnYYO;x7lv;9r6aJm^$F*{B!|TgueckX>A4CS? zk@MI>@B#Og{=%DG1!pAxL?_HMg@p{5Z(x_i-G z2oI41mX`EkzXFfBHbo1M*^nlVjT4G*knjje%oaAJPP}QIzalvLD#7YZ)NKCkfZ3KN z1r^UUnh1U-ZiXOq3V?sidsP}dOxH-x_Yu7Fu4=iWl?Dw?81VR;EqFi# zaa9i(XuLhT6T}{R%?BMl-9KCXfN0|=lbq1+5nPvos=xUGQM8;NbAbRqv3J^MeIl+d zVjsQt?`Uuoq?>MQ#?jsNZWw$(OWcZ~KmerzLm>eaIH34oC=7n}{qqHzg$4tbBOi9j(5(!@CXZUzy&aW~Pj^hy7W?55^01yXZD-YfqQRt5U4%EMR`m z;B%f7%2u4iEZx+fL)j2iW)#Sv=g18kZKu2&&?vVDc;({5SHSqX>$Ur2zj;JWEcirm zJZu`T{Ai2_hD0{4nXn?jYd2!5RS1YO+%Bd-%>oSw5Of81RWK2=v;E+7?4Y7JIRs7T z&eY=$@dmfm*mHBd@`XA513(Ye6`FpTqt!D#;?}b{x7>JpPCqk%For()24-b7$tB4v zdHI^D{p%J-E3VCQ-M;!QyIRVC-)Qsx`X1 z{otSTK*nE*8|=;`89_ylz+D@}%^A%xQ&T-$E$a*+hc<1@8Jm7Uzkx7Df2Q!BDB3P~ z9!!o3)h;*I`G7uHlhjFxOgvXS!gaz}W_%{=Ix2A4Owsyv31SkP|tKNvmmd zE|y?swgKG24Q_(s6Fb}FQMXZ*V|fOX&fr0mG>zoLf85#xYM#f!2*n(_-7ffYZTOg@O!YLR(gRKA50spK4V@^a?o& zJn7khktI;Hic{+FxM?;2+Vbh zsRg)hG0hXITaIZ$m*1IxwbH+xXpY_Q)@(2h-;F7M^sD^H&ML%2;MW?GnDU^bwiw*X z=(ysiqe@{Yt^ z+EY{<6j*hQ5XG9-Ce-T@{Yk8KU{7YEhM!H_*OtfvxEnv2c=JYo{ z){9_`ImT+Sz)AnGpIi(jO27@DMA}H>bz`@+HlfJ8Y_N*9ACya@89etYNr1~f=nO6g zwjb3zNBZOk_!qJ;%1JVsH|58tao(LfX-TVXo8wE&h zQ*0Mh+FuH`I__D_UGfc9gTt6uT4t{}-_W*$#09+`)BObO@ zuZ=Eszp0mW7{(z2bGG^zu`pr*1ZFK!%+A4myBO@oMUwF?wSxFu3&@!@)gif4DNgd5|@_}XQq@_X(<3nqVJdW3% zUdJ-HK5e@lV4^Pob#dy~l?*a{w6@u+B)#;bA)Mi{d(k~;IQ?gabCxDsc(DTMBdO1n zMAp{9dz2!6=SEukZ7r!S;d7`eKUVpXwzdfAW#wpAKL$6}Bv#}jnNU`T3Kle$0niG+`_;KOuhN-}s*eLVr%sSSMM_L>L+ybVRttxj%|f2%(n_ZTX1W*oX_H zTEpPP$>?pdq~oJdxft^{?WESX1bZ<(-l|c~GCGXJ?Z?I5Eb?LK`iNbBd|6VShV-Sj z;{k6Lq?iXXVi$=o%eec{mwBn@n%`Qg(1?oBw0aI&UHkor6nW$vr!q3aLe|_-i-O*& z@g^;OZEiq_ut5;?(ezM`p6!aYOYf30Nuc;(bF0b?`nj7Yq$z(Wtim*=b=d1UQ+YARyA)-VO1KRRfU$ek_79inFi zK{PXR5iT z&R7%Jiz=}gebp*4vdOOotn5*lqit&C;NQv}4#~axx`Bh1T49x1_s1X-Gfo3m<3t2i325!nJOg}-SH<3LEgNM3 zN)_z<5Wl!lxM1OosX^07&X@ex4TS~{69DCkvgRcK-?%8L>2tFJLWVVR^vpOl3M@G7 z9VWnU@MqAh#)GWw=jN_k3&mtiZU+=JMS|xaccs?EmB9LgLJYwn8HOi810p`JzHS^Z z*Cx2KGm)rII_@RdpRT2v74aB!R01>t`~c_&7zdaI_zAEBaKfX9>qTAQ)fhBd)C|xH z&<5}Wpc9}QpckMYU=Uy!U=&~+00l4wfCiWam0&o!m z3BW}JBmmbHAOX0p0tvu%4M+ekVjuyyNPr~4g^>GW(`PmXaCZQ#0$ghj;N}ES05Agx z0>}pF09XaM)&lYY6adTsf&j7sIsjHdWEGxaJwYI!K}RG&9KctA?*K&rl>m(ZKLGjx z#sOvlegfSlo!kiA~CM$Tgkc?YN|<1|HC@9 zhpsqr^zM$B(?otu zp6T!U(v9?U5v3Nxoh1J0nxo7{LtM@>?9VrLNDGq%UwORwhoGCS?ZeF7LccIVc_ANB zCUCE|iPjYwNpHO7H&N8(@%U}dn1H)1w31f6J>`XA$E`_XQ$F*+8So4N4{vd@coxiX zWcjU1kiHsm42+NcyF2fv@~#m1k>~C)MTmG^PLD@t+4} zN5IO{j1b^u*iyLwHXY^x(zDo_ z!}}|H<=2pB9#cJxl~s-3h1{V3rLej9pZaP>yXMZA(E~Vi#BY1s=>M`RSzQ=tI_R!B z=(GG63HnmMw(b8aYA)W{lx`ny;<3Nas*?2J9DFFWH2XvUs6Yk!i`3p^1Hxo`RKaoO zLcHeHxKwPv;&I*1F>k*X(~@DT;P>P(S!h(qJMaskp3bjG_gf{eN}D>Hj>*EC?X-Xv23%#0K_if2d@X)e1r-TMn7SwcHK=qG_v>0P(gMeVIS@>PM1$hMZKLa7 z+6~jw!W@_c6B%Iq)$P*)2lmU_zs@44fQEAbEraRzVGM$c7E_|kRlF0}o7e_}3QVnj zXa091BydjuYlVP238ws;-wh1bvB9+d@9Ip)@AW*cN0mTkb`~XJTq*#J{F^X-V zXax)^j17!p3n&_a0v}`JjNi%qn#=j5lx_l_=y$m6@C#psqEHTKq@DUqWKQZ;R*`sT zTlJJs4$5}X?_1tL6JvDiCF0I%W+U5cc`6>Dg+KlGLexg7|8E|bP)u|in~+_#%X!nv z!9pEOx7smuM-9Zv`i$AeCCOB0j+OZj->TereXnujET#0CRDTqFYcJPS?Vb{h`I5`? zmDGH;vJZ`U1`kfmW=2|N6~if#iy>K;WL@@CRc8o+KK)nYJi2L7-%thIp;RX2x--X< zr|hE7%oCRp#;Y<&ZY_3E*qCUaRmbqhP^~g0TU3#82$Ws)rwkGwWCi{&JiD)R(cG)6 zqJ0rzH-I($RT+7&bFI(I!W}>IbuVvptgGQ~y;0ZMo3S9Pk+_ssuLQldn3icLSLgkX zU6;Y0!CS#%qan@`i;pK=>p?&!vf`b-^RX6Fm1q`ndzZU?cAY8CI_pDp>ypo0pK-vq zUT0e$Qo;3TnJQs<>uC6yTDno}ta<|)1YrT0Y^?bDL{kL0>k%!Y~|nj7;%r8BAt z%7giG8+cNC+?wu}WQ{FPU8Uf^T|&k3&3{=VfII-^OVqHeq$wA$@xi!xS!Z;aeDWIo ztyDth$G4ryS@2Q~GweH363Llq*3F{(UUAReGq(+3^bH~HyC2^m`{d`CWcWKZ3TD2T z2Dv9cjQ1GEhq(-&8;8?NyyYJaN#du4e)uLsK+AkT0+83xPvzTGii4$x_(f+D$-ZiL z$tk}k=6_tI`6H#HO_D%jheFkwrjvisFA2pTO-WGPXG7rQLir~#L25^9EVs%hn_6Dx@S8@z^12IN>oNMS9A{ z2;a-zVha9SYb%H(etZcRvd^Rkdx@6MDEHPRj6_EVwBG)>@sH#)kWAGBS_et`a$@Qc zh&k;+w-DQvWunidi>yXJD0+dVPWiS!S-!+ri6RVWPdyhI@gbxnESs+OnIFSJbR|^r z1L8Z;wqVC{cC=N_=(2sz*s=v^Tnn`u%wXscK0GM%#Edh#uvD;Pw2X?r#=;EZJn>TI z$;37VfA*<|)H#mg>D!`o%jc(ad#*w$OOc5=D-9)e`}LRmys!NO-$(6S`#{R$ao+Lx zbsVXVE&LIB`BN!_aJ887m78FhCIUY6)}lE#KBM(w5Vrr};tCg0LC4Aq0*0x$3?HzZ z)9dPYO{@3eD>O2msd3G+vXoJ6nE`LEQ&U;t+@_^69KDT7dvZe$VJ5!v#7}h2$*1n@ z;`qEgfAbQT-%*WO(V?KrIZCLbwt4`2sj9uqbUC}{LOf`{t7t#6S4!xXc>A-@P#v$UWo9CHODuVCT?)3HTfEuh(At$- ztd30JRd=W@=XnKg7wt?Y)LhF~U$e|bN!>he%NzJfB%Z$5e~Qjz94kG1jJK3U?IP=Z zg#oGaz$Bs0=kR+!|LB7ntLvll8AQ0D6V4goJYI8UQ!8QN4f;7oG%>_HqjdOw?eyk}!FV z(lI9>Fyg&QOnq7Vi$bz8#g^IEO}t5hR6@-3)52NYiE?`I7y4R~9R0+^JRIgodEYc= zino}hOF@898E#$Ly2`J`i=m3@MayI?ehZ}KiU6t4$H3#<&HavnY28cf^)5@{J^Njrajwd!q{|P~%B%5p zJQw{L8Pplc%2KGB$BR`Ly{EfD>nF;k$E89{1(Y~%htMxB?sXv-g${EYw^rmmDuwft zYinAf|L|BwT0AGqCcJGav&^;>#~1!;4p)FI#DM{M=!(h+Ql1=!uJ`i zBZaQ+VtsRt$H+e-E=1x;hoNU3?`+m?-n!C=-SarcD~syzz~}oIW7WQn`w<{`@1{<*`!?PAhh5*eyE!=?jWm|0>r6QzgyKO+or|oVMtM2gP9^H0=xxq{ zo*EQSvRgvfdPa*vQm&ut$&w69E0Y=8e5P8#5mU3I4AadOt7FvNU|IZ0F0QR7yelY-rB!)_14 z#m=L$zyF(13!ExsP11bCg><&fI%dD_kor~Ow%}Y0&lS$j8T(QgQ z{aY&r1Ti6D6K8cWCDW{^E@YnjWelHz!q9|4PV^`i`^mGev~+@2(@)bU3oH8)jvss% zY?f4@$?hj>#5h)#O^VW{_b=^gpO&qRqFyi_;Qv(3dpkx=1fN7yWGN^{M|Yeotee3t zKl4P=`s!9v3N&HAfAPwLji}??`o&UEo#bg>B=a`bND!48?P;ptEzddGu5{z3?sb~sf*(y4OmEIzT1ExB{{rH#mho{O<$1%f}{ z!8Sb{?142SWq!x`hPiM{ zymLumI^m3k6^HtTNDsS`7+_WpQ^VycNP3O$o4_Xh0x^{X{ z7dw+H2aGk>k}vy@b60mk{}gkJ&ZrVU;Kwc!h1e-om3%hF&owW%ynvdsu8%w2_BJ#^auMT_G7C+X ztxJy1qZn{QH$wH9#PfU4^ZUJK7WaBMZ+5*MJH;Z^H5$RjS)RB?ya-koW(m82SxgS%RY$0H>}g{x6c z457CoIgFNKO(D}YVT@8;goIT6-F;UZ3g?f`-U;CeA4!K)3DbBr5sn$XeOoUXvvHNM z=VL1o<3q&fu*q+4nAo>s8@hOehhI0BPMq2eh_^GB9Nl);Hc`V#LYQmES9v`^qpn9_ zJ7i&luS)VG#t09y)=X(F$P>7sor0u%QfZAe@HLfZzHg~H`9wEV5rh4a*vMG$-O0nd z#`S!Q^rQ*&QQ#w*>GL@VsbRFF!-qRxzw!!xA|7Q|7Qkg3;7O}zWkO1C;I(`D-_ zr=4@brLjrUjZcKuvp2A`2&aY)nu z%5wPa*ke6WJO5U>o!{m@r!y1L`R z)T!FP1de?T9QzVzeqRSdnU9W!*}QwA&@m&He$`>-d#3;97mlARV(EdRB1|_eCEWZ2 zm%LNbMg|-*(fkO0e#=EN1Ruf#m2b!zM7G{2hzdQ;` zalB{@T1rewtC{0ouX#i@W%Ke#PsNuEO6AT^*`w?SzC)sL+NL$m9>fv(h^knYs`wGr zm}<58JsrN165i^xrj{>(@R{#K-CqLH2o7%{N?u2uYI0)kTR4_04`|gX?tTxXR(QOz zB=tU{UPtnromt|!6?!xOMYCPQ4lnfJve9MxXa8(u$eNJT-r?+!Ncl9uVEuZnG#-qV zygWz{t`j9qlt6+uaGGsws3ncMM+B8RyFE&qG%AMc_$EXHFNqj!8pT&Jt# zxtY8sNV*<>4M)DoEP*TEiod$Gi~ceCv(S@w(@=6@`oIwuQXIxRnyKo!W#Bj z!uqsKma$^8*^{w?v}u1WB42(wnvppS#XmkDF+oDM9APHcQYc@$SR_s5=P zli`o`kw-Y_c9m-3?b()h_jH2&X4w?BBU2oAPb`SMmi8yeu}y+FiXKt5d<|@T*=MMP zg~9+kF zo)nSQJH0VMJpPReF03R1ty&I8eo9`_GS`=IhC6TpIGy?NceIg8i}{NdbCnj1LHPeuj&5pefB_yd80d2b>{$ubL!s<;f7hi=5YM8gUUla+rQzkm_1dNOSKUCM%U$z|_0%$#a&{lMy ztyCLQp~K{7vksR#&yuAb5?O15j20G>mLdK;N}OkJXD6iUEXyuLV+Hrw`_k=(nId{d zraW~8WAdi5A+ra%8M>vV#zIvp3*BZiesC?d8!*^_EVdARQaKI6*JcjS85hRC zr0uZ!Y(stsf?psHyZ@SHBcOXQ~S0 zbVu~^R+CE{flFDT|RH-pF8g=Ega^zZh09(39H3D(39eI`9hnLG1ZA3 zIo7KgZjVqUu)`Z0=8jXQL&D89Q`f44xp7gb+I_4IJAw{=;K;X%cXvC5{KHLlOz+-Dk!Ng;Lo`dr20i z><-_;*Q_2>sTO}ykd5vXv+N>jVu!sF#)eO-!)d+de5vy{I2<*^uQ1_mUH3}J&$x{x zOgr`A=O2)(km@U4G5ee>*gY}!afF`vb$9fay8MJrjztwWBWXsr=z8=M3lWMt*=T#A zwFPV9o7D3-^#h`fj`0-(^<5q^yt2DY?F#x%4)O7qPwIm|~U^AvTuwf<~WwUJ};j&~+JgAtZ zIF&P*QuJ(ThXxVCjuEH4N`pvPOFe?nUsVte9`wYap`;Dhx9_w>1+c#(|LCYhyheb0 zAXtF>9v;B1A{*q$^72XZjm*a^N#7i=ZyU7)A=0#(Z4Q^-qm5q3@@E=QZmTz>24oO0 z%8I|-x;LBUB~PJDB_8O=f!1$U!zE))qI0Aa07vuRP)yM;dY|Kmv0x~`%J#`bNDU<* zUIn%UF}A#cEfQesJNgB%1&AE~r?M-7hjM%WFJdH&B}r4HO+uoOWt8TZ7FoI~ZYHv{ zVvJ?%%alU8madyfNSmTYDQ4_r3zemXxy%eBvQ0DAvBdB{@1%R(<@f)8{=CO|pYtr| zd!F;0=bU$DJ_8n{R>QW;P4u2W9FO`Jflt)rCKO=*R|}u0fA2)pF!%{8Quy z4qx%`QGV|5u8{Hk1!Qu8c6r29g45i{^sPO)0llZlVRQ5GrFVwrJ9*na+AHtNp&2?Z z^ivT|QDsyN6wV3n&EDY812g?c;DnPv+Wzk2^M4RS^-8uxXep2U)$8JVi=~&WZTK1%T;HO zx5tF8+uV(O@V?$TtQylhXcQz@-o){hxzVGSyJofF$yYZt6^^9qi+ zqt#Kr%5&v){a7

nb9XseOBk+qnU5`1@U|A(8su_J6#xR!vk1r*v zMe4tCYcanj=K0(C_vZP>cKp2U_eUZd#ykeVS3fM`mS{5vUpOIZuu)y6y_?(l?!jKS zgn}1JhcDF&xx4PXDSSf>TiIwY@t=4~iGi=WjN#9~2OSh#_wL7WMWIweFGv!Ca zuCpy`VnUfUMTx_xRtmnv>EX5_BgOa&)vXrH)Qnt0cZxo?tTlbGC|L3NAV|v(RHuq^l8A?0erV7r+4|06QZ~zE3sDd{PV7b z@U_ulTZ)!~W)yd_7U(q+JH!fmN3S{q?p(;_^R+na7R$X0eybKdycR=Lg#v}Hq z)~xA~acdQoJr|U(M&P?Eja%;r20u_oU&;UK(YlaINZ9a6l)&L$D-W7t+#e{c=IB&= z9lP%G+`r#uqEU~dRE+87KIQwIvtfipX$Q>Ll%1RQIcL4rx5QY8;$j7n0_BMsZOd4( zI{|qFB2CK?H3|W#0m#D;Zr6aS(onJ_K^`NFuT6j$9xWLCfvnXNHWcMz1@Ctpt7R;s z&N^l^gl*=voD!!>VUf(p5wbgiYp$ot?I`#1SFS;;^)@zLrks0G+HNRA)DQ#K7a)qu z9*9Ii5;ginSg})pL_?(AfP7u8L!OncW8jPdTbjrQ{q#eW4B9heX`)7y2+Im|fP)zI zyp~2Ws%2F1W(>3D0>nt2@}5$H3{Vp`lEGV#AsrIBV@e8EL$vp%ooghC>?g{Flfo>q zoakpo5JmnOz3n8#I5->Vt_k6E!3ZbTlZ08ZPaw)?b%4D7RGZ5v*l(&H-WS}&WC>fk01z+`1#b+=~iQyjH zN-$B@0EoU2%ZL<>lY>b81okQ+mKbpQdWdn2okbTpz{oWondymGm_B4k9q~!^yQRVi zuiir|%gA2n@)XV{i%gL!oUy3hBB|_0{FfE{i>FGIV;brhAEav_96ber)!EAR%{4n} zkeWGPm@UdB8W)7j_LZOLZ+o$x=+G!RX|&0Z7dT<0*%8R={%D=464CNXR^{`TN$MMO z)XZd%8z(niU*ElFzTJuQN=LZ)vAgdZn^=@RFNW1d+!nIqJ{7_mHcL_(U#T*T zs$BOm&UVP)?Bfip(%ZsLR6P?h(f$0Ikd%R^_pYt-d?eNV=Gg-x{Rpb+ro|y}q#R0? zB51J7jl0{P7+%F!UuCOeDax07g2m(6s)3GVRuFR^D{QUsaL*2J^p$ID)&G#9Wu$^1 zclFd|D&|iT97;l^U(f>j!m$0(FHNP}??!_-))~mcqmL*$k_W5U`i7l#NnnO5a+zO- z`cHY$Op!^6=MF~EG?g4*wvXIy1b4pAXs8n@ZR}mg9`S;!B|a82o(ofWQ3{WEgjL&u zhm%kz#A)Nj`@uO^WZ_-xrHHe&00;z}4)^RH@7kb)nn;}S zx?wLFocP4DjuBiZlu}V!;E2(>Ui`6Dlc)1BYBt7(5fJn?D~kb zM{X?`-2rEP_)a0C1?~OiKn1sJ?hHS7Q1CPA* zm*c(@aMGlLw~C=x=0sZ-jwhCYPDuB|O5rLy_;)ws8#G)&QIt0ULOw4IRvj}<2Ayw-RQ}Zr`BHGT+mJmTJ9LL>wp&qedZ+;)N%(bw zen5a60))u0D;OEK2Kc85!~L}@gg<>N({X*~CCJ zN6CD5wfMQ!&Q!kMRayVa7rV#HDel~13Ue<5@3lQDv}~u$M^!Q^2Bezx%HCuY;sAs5 zT8Q=LUrVJ9*=y}u-`OS1U`KMfH$=%_EFiOW?G_|i18I<$;0+)NB(IyGEb&d&4=Z2? z2veijZmsA`t-U0r|%q{rX^AkGFa z?EqLHyTJz4NYUlq_!>_XLd8@=e&el(jiyIS%g^mlnM2Xhkv+pt!|>b50$_PSk5Yj7t!Vi2#U`L@{jrpONI3YNZgE!AZj2MAiI6Rf;!;GVghL< z={qmJh|lWMA*;-ZfG}=B&I`eb7pNGFm~ufC@Huz@rhL#7Kt4^9U=dZ^SPDL?wC67# zQkgUEn*;*vK$WR7f9lP$$r5Z>9^apX%UfrH(JejOAjmBq`lV-6-OGjxL~z|FheJ4Z zjB;A|J5C6P$es>y>T*Ybr{}h*4k3e)sq%7~G`#bGMtBnhz;L>sET!j#z%rr$wD1ny zSF!&a0HWnr5fL(ioR$YUE*yAa9Z$9pV5a#BFoPh5h0-Mn*T3Wb+Z;uquU2Sx;eY`U zyVV}Q+rs0eJ^*RQ=UXD3t>HUtb;iCu(+J9v?CQ4I1Z=?oK!CskmjsGG z#20xp}L-3rv%)-Idied1{p5YWaJOiND|8+9ffE^T`hz59EAn@Rs`H@vP zm3tCxi(864VM8FZpg~U=L(cHwvm&5x%A6sn zn&vu*A$?QxD!o&kCiA?}o&%f9`?n)2(bH)~{I|_J$#bclG|`C1?wJenUKw>i-N{># zT&K=H88l%aXK_utY!)%>_Utw17DmN)_G&ZHSo^^I5MMj3;1<2$?OU>PYUm6%yAC|8 z5l+#=v*U(K=Y>x8Tx zoqVmB=^7Hi&398c_af zyUM-M;9CQuXFIxT-hW!Se?Mbz=)UarR)4?#;Zbq%xcJNidz&_{Z>IFiCNj6ku`&+q z^-nuU3{e(p_uL@F4O;fVr+MT0n}7}q0Bv|clvsLG(Fw$_`n5t+Cc^pjl?cYTcsRVb)=n@f7;G-C#Z>&r!=_gJ$SZz!TOySN$qI?n()kd606dWT#wwW>)hm<9Yfw z4;|{wb{C??%Ua0pLjyR)in0zHDdD9~4iCCf_0E@NCnXf2(Je!8sK z7t1IvnnI-27DTY!On?@1uuZ@xMKUwHUqLcD+jR;i!sa=Zu) z1H|BD`dW@j4z^2=p}; zM0oFAiUJED*!{AZs<7CxPI7$FQXqg0+(Gz*E6APjXy75k*-J}FfFE|&lHB3vI+#KS z{eYbp_DTjj3yc6HtztmP=Q+U68xvsvx1E;}_s|t*AOP~;Juw(lvf84{bbhp_B5dw{ zpGG6{{hpeq-ww}zScofKFene>Y81WYjMu-6C>g)`Mu$9e_=*Ocn@wMR-EKE^0Y~G8 zt{IUGYE_%2C#&1y7Sb%b-~6Ud<=8%g$d;)auysy|RNeg)-7^w+`fuu0H`Q&4^hZZz zNk>wJ8Tw~p@vdn`VwCU4ptMCfko$lOTv{;Q!HGaTZF?zB7f7xfc7-kZAQV|*q-fJJ z3A`Fe>3}i^bFPM9xV1!1_Y%QbY`v)=>nw&TnaTW|Bv0yo=@9Be<$yNu?7&SDfwwR~ zz|RgqsV_+$K7p7Tb}tResRnS|{v#+6qYXmj*L(pi$aW`T0NmB74!-D`Z34;JJ3E+d6>xCoR;_3D|*iDX=|( z0f8eIA&3a92@s5JxC{wq$pWQxUQz4kaPCz4S}? z1kaE$dVy16`V+N@{QH4koD#Ov3{&F^vJ||5zgjzGW|Ys)X4_?(9O*{hFYsb(q>}QAyYdJ~660xlo;&kb*O3`#pSK;) zNeX38cV_l~QOXF{_M}~8l)kfZ)I~nbOUF^14(+|CX<+bc^ww4QpGo^dbNFM2Cu&P@ zfwSCPf~TX3OKZcJOv$&huqobkBh?NkTVz^+L_oSpSo;z7d?P3QwpUl#DOw*dVIw0K zWtl-E7m)IJvjurh+Ij6`(&@?ly!pg5=53F5pPS&N<^IM_Do+fz10Q+GSc&p+XmYCN zm!>%Ps&geLdS173)EI2?9p=vSj910{E5>;r>B|EgKdM{_;U~Xz$n_o{nw01A9O4sV z9Bh%7@D}MVdt`A%c=Sqx7R>LyPE)f}7oWOqJpFL+mgi8m*ZyYOMPzr-jqCm3fBvj{ zZ%uKIi{F@V<=faB<#8w@(i=eq_<7W z^MpbB2QjZ4f<>BMna71lgVy4QjT7q~I`$$#)1X=5t4pv-Zkor1m+(2q(;}_(2~d0b z_dq?bLeuhWgZYD%rzk+D@Ln{(V^x^(+)uNg`5zG*_5VozWSsZ)vD{nQnXUE$UqENrZ+icR#iXNn}XYUT5d6UKY=xZ-&TTyTtEE=A>xlq)6q|Cx1SJ8GZBZ z(N*e0(OU_XUtDbV^BXIV9lc|wz&AiZA(+uN6}iWOY~=E`4{Yt_pFW%cFKYAEFC9C2 z&rE^swfs@6n|emCD-@{z$`4r&;R_${lhcK;n&9Q}ce3{3)`_1zcj`i4@fKbfP`%hz zsICM_+bhshBq3``ApMRcbb#@JepeFu=ey+KD?2JQ_gcKwULknX-ag{wj^n%QjvwvO zeID2}{<-M%`3s7H7Bs5lvD$AtS3J45RdQxAi=t~f1iA@#l`Svtu~!TDZJ;AnJa z#B_V|${7_K3xv4pFO$Dq8yA9h#jb&DEJT(`K=4oPi>8Buo5erNAsNWY$`il7oN~cf!az)9Q=MF{Z(zvQnl?)e!*_ee$Ki(bo9?`_Y3rc?RXTNwmS_9 zY{&Jqg6p}{E~iHQIkOld2g19oX%B>5sp_?HM7}rux{=8z5}*Z zF*1tQP0g(qnp^7+wXQhyY^!&pMU!>II}60&s3^+dNqf|qwAD(t9Zse|03<@ZTJb0S zQ(#27px9Ul2`h;F345s@kdWk$!S8)=3BLUYa`8Wqe>e2s-1es-zF8Y^^AabD|KY^H iV_AxG&0nxcO)N3-FAiM_OH>R-E&_g8psoU%5cEHjNf#6V literal 0 HcmV?d00001 diff --git a/third_party/date/test/tz_test/tzdata2016f.txt.zip b/third_party/date/test/tz_test/tzdata2016f.txt.zip new file mode 100644 index 0000000000000000000000000000000000000000..e96b5365dd1ba585b12781943bec582694ba8ea1 GIT binary patch literal 128214 zcmbSzc_38Z`~TP_TMNqCM%h*NHSHxNSz>Gn31e)7v5kbvmL*HJv>>u&8x0x6kgbTZ z42H4qvhTlh)%*QA=AP%?bDrlp%f0uU=XpKnx~)M&dl<$D{-e!CuEYNE zj}68Sb45R}aJ4umbyn6|!qvl7&yX25+3jWE0gh#=!?5WJv*z-Ng-@#EVSwo_BfeOb9!!^RdoQ|Y{wQE1~Q z7*lypqH9Z3sArTS6kDtr-Pz+b6H+57>FBpL(R?k{Z=tzpZEZh%G1ASz;a)kbEO)*R zCWqdh!#smZi4NO=F{Z<|W0dH+?C_>kvod5;DpqdfZOmJGUWG1O(N$0fkBBH;$EzA*kHjFq0%Zhsp3)Z zpkvv{z{WIs1u0!)w0>aaTXL>X6eq6xz5!=xpYuW`TQ;uyQM+cgf#fCMUyTBej{K&M z+a$_L6aVhLEfRYKy{f8j&q8MqMXfz2%%C%-*et`u&`9Z3nq4j&E>lyQ8fLeRPhT1vJ@t<9&bVGMH_yyOA5(b#Ye@aWTG** zkl*g0TEgmY^QMa-v8s*psH6&v1;-Ik!<%}>Y2m3MT`46ezwg?$2t}I49__Xsis;f> z#Ac?#LQm}#?%h^Xze1KOMDwoBPZJ%)V@!xomDM4?0b?^5)HFMp-k@c|rY0bLShMspz<1oLr?c$$qL+T9iv>S~5JZQi?G>jG*#sOUHnpe$jXf zxkgZ9^{ez*cV2YdMvr=LO;NJv1SCBvc}v-<3M5r~kE%6CejnkK?UxI^!t35dQ#b47 zJa3`iP+!uK=8~h`XGd&zx^32#H1IZase&HfxI6g`#tg8M8VzJVCspr4?dX9nTRZ|? zZ~&Q2RmwDvRpCMKP`UGx-t*nMOwJw48m~sy))-NRhE3HEP3Yto_=-mBc08!UVKxx_~!3)G?|Mdg-d3xJafK0a{)@_ z(J3=O2%5a^iNc5T_pd12(Zs7>%cAmFQf^djqpT&{{J4hZRdK9uW=B51Tgs^XWl?PN zTv(*a!h+Rt;DB7HAhLjJ^zP*t$;H@eq}u*0<29^QHF3b%9aW1>pbahQHSvvl*G zXo><&MwhzFr!{JMF`_AT2Id?LXUh%5pmqZ+v4KLGU9UJ6UdI%27CoA4q2$NBlSJMxJ5 z;~?w$6}th^Pcv)IW%nreAy&s7j`@6bzWHSkMHx(#ocYE(%IB#QKUtC zrI$~SA+ui?ix>y4VkwU7Q!}=$M#Xipz6ir3>l3N%rkPyAL9#T9AutqZglAWKyY!R`WD6W#q*z*2T3#Q70$fj0f>Tq2}W{hR@ zKsAi_z2X6krtkhk`3dJlXze-bLSlI&KW}jgnajPeVZ`cXo+yEH6zFE&|HgG*&m(NX zyZ<5;G7mY?H70%-#tUT%hcsB1c^p5NHjf>w#E^q> zKl6DEbx_t3u1k9F4ogY*W8-=9Y9v%7Qe-<}(=u7}OnOV)dP`vZ!WJG^dmO+mVUK)v z{U&9u7hg>ORXkrOv-(IblO;#p`B|GdsUnBk5Sdu+?7E8XP=8&Qn&d^xWP`tZA$n?3l9>s><-I*xuP$XdcC4 z*k)Jz)%a&NJ8=_gUh7*M$W0H6+cxf7IyP_kwq!z3aHK85zx6|1w}Z+d50=$Vqhd{D zj$U^0qhkFTYHVj#hf%RnHtHzcuH#XTQI1|OH4(~KF(zhhFV-|SCvNVdH#07K`>yTm z4DQU%uvKpk%_G-XMrXFCwzY$CxJ2TBn(7vInb0(E(J!`Zc;uU+y+p(Q`)yZVP!gvc zwep%;0(hGzhoqnMrnDdx?Or#9L_g53Y?E!UtgXL~niEoZd4ujkZ11{oM*m zR$i&-=C-3JvSkz5bU$%P>_)q;+r~$A+t#PzgIwpV|FWa5y{bLmC5#uhnX2tvxapYv=p4He1!q?_eXGV20g2U?;bdu z5*H+_PN4&4=zdN&;?YMe)xa@iyFTFeP zY&qHRPf|JHJ~R^%9LLqRP}!C-8&~R{=ciciyO}Vr#^+mJ>DvDzZ^-~r>4#l+pdZWAjtA(ZYK^H=(LFK-VnYde}D{m|Y%YwI%t67x&g)GgmdSAVmaIu(_z znT6)SOU%B-W{Vr67L@rA?&o)&yh&jVZgOA{nMxjZ|FuJ?3F#%OIb{91wE4&j?YD~D zUG3f9JdmU0HySMEH5#%1i?Q+M-4r#1m4nxo`uW+yt%?}Y+&VhkTvT4rqW+iNzPoEa z%R_m=26FC+d9M}@wze4ZwrD2pyr`HQa;+QEpD@{wKxQL!f609!3WR!nE-hbkUY}f9 zqmj*eSFUjkrgqnp9PP=QA?a>=rl|2I+8#{x|+XS<|-R+q< z>Msf;wcSO>0=})q8DNw6`7W+F_NNLUc2Skv>ycS^dS5CTSktYvzYgj6w($1SnB>px zsHGx#rIC`kTV!d;#N}R;7FF!v=eTl}03|y4kD-RjUYp;}(!}!&%L^l`jvL%KnBR^` zrY1eY=TIlz)KR3LJ#4Pl(Q+dHmKqh=)I}6s%fY}Re+I8Z6VA)4JGi)^V!B3+Xui`?r`{mw+Y73ENlVLxO&#%!sbXJD6;NN!exQaN4 z>N7}w=+rzEiyDa`R(}wlcvord^YQz^Ej9V4o;G=#m5NV21(XE^yEf62Hxzt0?fr=@ zrrorShg=1C>pod`y!E8mFLzuk49u&ncdVUElSqvCZf!+VykKbG8NSht7L&Cj^g8%Y z9SLb4ZFY2=Gu?9aTU-pB8%Az1em;C?D%@<|S4AjRHD(|(zDxQ}R@oM-_J`N5F)jV3 zGsgFL2xH@d`!$^~XIgO@_mlB&^H=#lA5AKGqm=h-pE4r)RdV_i^Q;S>94uo|8D$iI zUj7!&nVPj-{WzoYtn`Yh{UHx;l8lnC(&I%P#jhUgr}!R}djsA377lqN-6&bDYcki+ zi_~sY&#J#R!LBzP?fOFG*B{PD<+B%4DF;awaV^&-E`Vi11RW@X2Cs3o2bfE*n<(Z4 zN+d_LS!79pS(FQB7H9tU_LWIrt2zyptnVHlZoDija$<^;6*st|_=X{?+7-@`-kw=4 z8agIZH&v#QXgb&?bmr~>>8z(rdY1!5?wmY!KE>g1oyIo0>3xn4wx}4+(J68_5!VLhW~c4xs%3sg*jy83&wY=MPyToT8$M})%BLPI z`H3iW;b1I%>#MA!?~kmw$Yz=re3s84o`0jj`TZ5rS)M-3_NALwBRI}J;mNqeQ_W`= z!2O`K;Gx~x3p&zZc5kQ=1L^MClO?Ic=ialOz!#GcA6i1Y#XAxb=$#1L!>`@&4rTm7 z!jX5`Y;T@wuaRmzF!g(QHFkowx=#7g%%v%F9hm%kfNkrJ6(%}h``S)j7$tNf)wBp_ zq*M$WmtSb5=tn(N!H8ip!59bz2D<%gt|p({dU*YS%R&W zKzjffwzhcHbOswhV^po>Y|8rDUZ{=|TAb9h&Tqu?!!?#~x6!z(ZMp6u*POBiJBn&5 zeNBB&D?FwYyE=(gZp!ZxXL$W1i^t+#e(S#(PHt=69!8(Pkze8wDTsA-Y14}lQ+KhL zIlL`m`&c8+d%O08HgZBl$oa-$m~+En_D}Da81FgLJrQf5z8GsybzI{!=7pfyh59I| zV-FgRfMRCGvi65Hc4Ff)oH0e9ydU!-;3|*$+px?ZSMNT2dx{NK_JEDC`%F1*7!Z*n zopX#&rVsa=QJ{7CVp#8|pm}_lF551z5HEGTyth?}=C$?Zwy!)W7){}YmMk)eMESq)3UrU#qCUjy|Kmh%)3^yi0SuwCnNW1DfORUAVCc`im>v4jy5$rzoICXV8BI_D`qy81H>z zeIjPda6!To9M2do#x~I$*O>HwkyHIxa2;^^fG()9J7<5tdgB7Sa|R&l?4O8+-|fWC z++(~LD@_YE9WZ8~4_9E$H?FdO((!P=aSe0_4B;upZm16jL65`?qW}>u$GsC| z?6xZ!l<67Y`!RCwrw^lhTaD8|Q@_yg1;^vZFTyVJ2wqXI*SDyOdUxzW#{6tl`mtgC zw6Lg5(BX3&0L1u0de!C^Q=>=8d$pKgZu{i<_8G}Fi5!!y5ABspqbmf$zz~}XZ@AwW z%I+#T(%q^vd`!k6B|}zx4FSik>1x+0giX+9tG79nb=at!)J_RYeWGP_)n>3lJUnvt&+-~McZjMLh;bUH*1Z}OIk$G6s2nU_vFz*Gd*uEU|KOdk?T4mIs%(oya6|GfyXWdXgw1bMnNn%hY&NskR(33>*74*D^$*-xd(aDS89crp-diVpHJ(keH094^g|3ZhZ z)uPd_&(W0hMv0a;hOAaiP++D72G}A;j?!vTcn?rC#P5|y)!4)jo0X~C@5#yl3obW4 zNtS;vv`^k4tJAUezJo|+p%N~9;zUqw-)!uH(aPqgnLp90a;{F4-n?j_Qex9bj&-ez zL0eF0`ne^Oup+Hi_e_w#RW=Mi@w7Nu6G5MmQ{B=si}o`9BGFtV?rt2SjTcU^BMcSv ziMBM5Dl}(lwam^aSwu014{L0qeWEuT2Ac;v1_y)p>k!iF*Q;6Gjc&VR-GYt(oouR3 zBU`5zW}HL3gx%LSyM|a#^t(+sj)ico&Xo2kgr(a_9~YwHbir3o!-5~Hiw7wx#~Yj9~F@W(MRrNnN_N+^4YcH z*jZl4i>QP@9e5>bDe2%ypmXywE-n49q;hBl<-+wUqrybGzVtK?ywGwonq{`S(=A|A z6oE8YN%K=w_CtB?5;fk_Zhspeiq09&e~q{@rC;>#WT`K-h@0D%Z`N3w`HoV(>bp+? z8FKEDv%5|f=chkYI9J-NJ>a+HYTVAl|D9|l)>^HeTAJxb9U)kq<#ymYXCzy8YIrl( z-Wm6PRKmfTf@H5!DsJ!rjo4bGjIN9lHk3*A4dRXXcB_3vb$Io~mv zZUq-I?CavOK6*zdpzM*&i;j(+k`K7v&$yg_Cq4qG(zv(SVxMWb{=j~fT_T~TFHp+P z%a^&+Hoo|!W&Y&VBE;pXzY}-7+est2H^rY<0(y$Von4e>)j}FpDEIv5^lz=quBY-l zN*?CxLgW!YW>;9d$-&)g_L8`&Kj-B*9@)8zo-;A_44W23xUH3ne$!VuG|yZ8%+NQk zqMB`s;siOH3M)8+4?Dhzp2pA_$kzJ#ZVfJUyk{(MKruOiTd56S{rX?Yob?lItVsFx zO*mzT?d_M!5yn10zwLI)VB7JBEi=qN__%&1yYwj#|D9B_DUFFE#p4XW7V^~At((|d zc$K@(CQRk__!eY@1?0>KhO+5R^y+g)s z##M7iqy6z*XQ!!JvV(JCbg_-W^0HZ7a6rX;5?Jd!7n=V6oCNegBf-SWlzzsh6%E&D0d z`O{ABRi6lb&$OAzPU15CP6Z7DXJARnjun?Tne7|m#%W7xE=Z$m!@Zwrnae#M=>k+UQmX9EH-H!v7mmtc9}i`r%A(m%4hvut3LJBVueG7cj#$D zMO=iCO{qCBWkt1ej&$G;93Akq9@BNDKHYlKae^{5>^ZJ~BpYda9zeLx?3DR{9jr$v za}>iiHdb{!BIH_YVZHjTV1Xq8Wk0!!9Q$|3#7gdW~KzyWz5 zT|qppvP_ijg=Cw^0K>OPTi_>r)XS_^%w=kHPbAce%cVE~p9QPYt2NlxDSCHMCTpA{ zYg{Iak%_V}S56uFZ_gw0zTa&Q;i~4)v5(arfWmte0yQ#d<#Yon1D=A4o1-gZo2jLu zPq#Z31eCHJ;@=b=WJuxkj_XV@?L18(h99Lla_NKjnYa#d$*E}VjN%%J1rLGEPpAN; z2M7v5);ER=PA;(w_3FB9S{~#`DDHa^qGFoo7T4*UOsqSbGLV}0a%y{eDSWs5K-%ux z0)sjezSa5=T(Ywlp_S1x*T`>VXd&;`uA6Owyf<~waUQ4g4JUOY9QIA#7lks>^sPJX zVtx|_iSAZbGZQ9f1)U1qSX2qkzaDoKYg>2MzEzYkor~7iKrM{RbLAa(+H_h}{n$6Q zBD~#sd=~32&`F(}AQHmpPWsHY%7r8lx_)Rdx^G#RD52xA6y52y2ggWfy?XOEd$qJ- z)ide!Z2xf^-gZVv-m2#F@of!Gx$aCq^|vuDEK{>3|K2*j?~ZlQy3@BNDK)KUN7I92 z;w{kEJ)x7hd%vBYdUMOV+UCGovnFTxjK>d$ex3NTRy2&H2Tspye6<3{SE15IEjBFV z>G*K6k<+n_Vr%%AS#UN2TeY?31ZXe(QDaY6lL~RHnd~E6V~UCZ`HL&!jT^fMqa!W1iE= zB{vAE>xsQWO3FG;g7dLrh1_RpX6HK`uIA9>CbYRfvAZhKmRCSR)PWXChuN~rEkBU| z3R-syI4e=ox7gDEawMlRK8g+sL7q-hnm?M6N#$}N{|VxyZ>>_e?x0@r_crkY#x>jW zRyOhcA4kyF8;+(kOkw%&AcDG^OPFwOqzDHBD7AjgUw)AdIB4JpoSfJB#>2k$Cs!#k zFD=kW7UHFw-=tLJYnER)pKC(swjcjwe6vAHEd|XQDUcD$++Oq3nQ`gZg#YQ_)DqmC znaQtn4||fr3ao}ojdv1G7Y2Q=8ZJEb;~qnGbQ^omEXq?kGU$7ub*N@Og)AGznY@qm zUNNcNyPFRMbj|Jkzou4u8l;0RKnsb@VU2BoUh8BHzqXw2(Q&wA7@O}^d{$ER<&$J>OT zKSI-M(ap0^11S3)wMPx&N`_9LLFPp!@;-Ubeyvn8m`%-VFP#az!}8OKH;jO{(@dEn zAHJpOaKOu47&Bn2(M%rpr1IBQy5ES8{p`w=!R;-|t9M0$_bO`?^_>rw9T_VBxFRVH;^n3+LtY21Y(h zqxw(eE^Sfe+V5Pbh)(`gi|Gx|D^Y)Z9$}cfZIor!w#|Zr-=H6nOj%!kemf;aD1cG! z^#6LG$_gKRmvE0|K0$g1kka;^yY2MY*hveJ0l&5^r9poHp)n&15v|`xt^q(YmX7sh zVS2S2)T>#TaCCuvCzdIs(o0+Nr88nn`9_ys^`dw^^v80O)!Dpc^43RinaBHvzHL$? z9ZGn}pQj0!sZRnlh{R9taU7^F%+XPuWPr`+&67V^z0 z9&)&8@mlr3P~BEXVQcavk*AvFgT{y6G0yCP@^a5&2WJ=Qm;o&+t^E?0e?DT$PlvTu z$FbgCT=Sa9=IP3?9!5if=Y! zRNvq9-Z=aAl_{*qMp2cS>B4=&%TcQ(hq6P>ta71dr>t#pdWd)xVF{PUtFt46v%wLS z3f{ZF+L$L~Ki(4FR~Rt_#=vpo-1`T+iC=CBcSmry5tFLX;4Sn8#Lc53c)> z_;($9X{sYOrwVmQg*LxF1dhz?gjE_n_8AU(cH!`a}QX3dwUl(m4-c)|9TFF0i&!ECeALU z)IK(0YwwTgPEgg>w%pSL6Dy#jj@@PhlT-dz&Xp?rBXe#aM!E%lC}YNopE7%!x_xF! zQQ7b-uUsO{ZN0o#7egRsBx*h3;qopmS-IhRE#CD)qy0?xv5(q24&@;zv8&G6dAXk~ z*5rhbX&p`LPQFLi>N`C%)m*Rb*HL0HbI$5u+t(P1P@U{ZtNr1o_pD868r~%(W~RHu zkerL8v2Z?%3|(W{GS6}jGOK?iV)}{Epu~O#E1Yw|cWW=4^A}WsNw;LK#>uLn;>}t& z)8~RPchV5cGhI9fjtarAaTR;N)F(GokOqDfoO_BL9lTjUOEyBt{dGB7@Zd?Js`G^( z{q~>`y6P2PB6FY?nQ$Xe5h3cpKcUWZvCK#-z{ovII2Rj=6ek9R3Z8@$mXBFBFqV#> zqHkC}>0KE6e2e=eJnwse!T51)?vo^d9xB_0A_J-so^3}40Sq^ibmaEs0i;U(yR*=8 zehw6hml}5uQRh;8#iHwgCiDwPlkn2*M2#;AU(OBSMh}v1nP& z^ohK9(dAk1uI$UvgN0&E<=^2^tbrEIf*npo%Da6;1u_FJRj%`v% zXaoBI>KM6MaEqG;o*+$+g=ATN%Qnsk0a@a2pvJ{#w&EV^&7f@b=h{3zogmos*1Ru%Sf2$-^Wy1X zGg;PNp55(3UkRG$XAIg!ON9MqO>$!=oH;#47^}MtsxwCXzlE4n7TvQKSyYjDl4*IwGy009Ek4X;&8RiaR}J70mZJMTk9wBA@P zP56@3aRu+J&jr(HIe=-rXYzX6%sHG^%*Kr>f0%clVU!jO>>m(?E+Iw-)$IKs$S(5j zo(Zh!(b1dJ9N8CJCQq0vfNX%qEwGE&xE%nT%l%D+7lof;hESn~3EEemi%Kc$Ij_FV z@N()<7H5U}9XQ9AS9i=`mbtQiJQ1fAsW;jt{OM82O&buI8@q=Rg(6LVtuIZrf-rmT z$+q>MJWH>&2lcX^JCE{GH72;g>=%p`=?p(Cqz5?G8!KKh{GgE$?f6>c*01u4N7xL7 zuix|rIkM)tDa)ky?SpdT;>mA5E~%@r4Eg^FJEc1{U+1uepO-e}CN_n})yZ6n)1tge z(8zFVz76HO*fu`$(fIf>>%Jll19zV8kvv_jD`15yhS{b6?FK@d9NtuW=nS?&A`=s* zc+;PQvpcmvgR1WiiurA4VEF&L1||K%FO0bU?Rl&MZ3*ttW_G#>J-l(D;LBE8hjZv% zM7)q(b7yX>XH%og#-f0z8oBU_CoB2pKaQXRHcN#u&w`ccE5h29UVa+Ft)>mlS=-}c!sI1Bq3 zF-AzAb(w$R3+^Xg1G-9SUn`jv(> zC0n7bqGLI38C=T(sV@)f4Sg%$Eaa=pmvzsRc3P-59!z%}_$gZa%USuJ67H-cYaT0` z8azHr$rTMBPfp={r>5tX;f^nM|Gc7=8eli)I+Lu*K51~*`NZl#5*XbP^ z!d`gJQaZ27Y)9#$XT>_-ry?tI%iTI1S+b;BL|J|;e^v2mkx9v=j&xCt_Xg~E(IKz)^;}%|7_&Ihe&9039bNEzRO<60&C@()Tqb!%wld|bVTy%_- zIJ1OtNhK8Pq%kCID*KiL%lykAYB6ZDKu+4m2M#2aTYSO~-22E7;gTxsp)nKtxb!=M zZO1=Ka|YktcP?#U9JaW4TYa5CZ`31^iUi2P;g+%Qof zuaF`%0P!Uk4`F4yZmZ=M56!vccyRO8KB{dWKcg=?yJGqIj%bR}=X)S`9ppBDg0Ecs z!_oXHWAtJU_EOpC`k8C`qFOWhR~0@PElB?g>3E(oNcB-aX)-O;`9bl}T{f$jlVtQ> zWcJ**14!tKK9K+MMK+zZ;QHm;R~5i8p1FpXAw@t0I5iN5Vs0?RY>X&{h|(~5gB%l5uFAzAst^6kCL zpNQX=+t?!6!f1v}{#%6Q7j^fc&@B|V2JcI|i<;~|-j~1pNTgZ`cx4_PHAi1x%#Y{4 z(+F$7#2s9_^umZfzRx~8-xzp`m~mGW0IeV|^>6re<|Dg3UPfBSCGfHG-c} zC&=d3ehF`(_e92L2gem#Z|ao~jO?U$Oey8~uChtaR#r+)TAuwv@%~A$_rAurTtJii zR&_En!Uf5^tl zYib{YtzarQsq);cy^T`h$FmY^2!|QD-B%?gHQyGhtwSX57H8;kuT-)H75hr-7<8Iu zJ}R}8Syhz_)fH=t=%v&x^?qNy6>~rsqm<6Ya2f_rWT_;G2l-(=w?}2LDqeXh74EFQyDk0M*M>Vz{%XOe^G6y))GIL% zPyU)b;5kM{Up7@aF~dVIrx`8k|F26C!47VI>)V9UC<*u_4@zJYKs1TlDkthnwY4``N z{W$ms|B9x*Tz?faFC&`$zQzej3Zk~Nt$w}tU9CxUac2V;wjOgS+&`)zS4l1mSwo+V zWkoI;DptQNaK$7N+79HJl-U@Qlw-q@?-6`^B>;kHw47ixsB5G8jS;;7Y>2$?m-scV zVF9)X@mh)XsX`2hqZ$mrndBSf&Sf|Xieq~<>wr$+ya5f6^H$*c4>wZP4?xtNt-IX#WXBAd9F~0I4)dSXA}H|3-v<{j>3* z?`ihhZe>}~Dg)X<=KiZe-wYL@?IuM5&8Fdtnfjda$^hA{5D-}ZZSU7S7gZ0VfWoN*SVC3=53||lA4x*xIh8V$8*YFn~ znCn@e(vW~9Fm)KXr#R2RzF(lMckC|TKUbY&KxeKawr?0CUk$ns6jm22w}G0#J)PrJ z0F@c@cSlQe4dz;vm0(TN7+OzOIA7o$T=~OvUmIvRfEbQ6g<9E2<+L{d5Gm^mDz^9# z+?ZUD+E3cv9<6?uDUmyKl#raK(BnNf_fF-l@lI#hjZ&*tEU`QB&NyP-xD@*)!UyqO zSuEuq4?N^FI=uu{`g4cVJ*mV_J$TW3y5q|1O8>g|%>B7?KbCCa-LL`ult7GVuobmL zO1grY*dgSCbo07J0w()AS^->f7)b_Ofkm~D9YVw-GHhGe8u!*jRzN;nq=G|Ce?&t5 zl;-6dw{By3WA_2ugh5%;#n(`XJY@T7vF6-r*?WTB(UV@m!O}&F;6r2spt*Azr{%#(06##+>X~CJ_FAby5Ktrbi7y$qR z6^RoseE_u(mT!Yf0pKGFb=*l!0+9a=0CDL5eSDF*ug)iwqWe3ZgMy<=Z}eM7<4@n*_*7!D)74sX zNN~)K>si#xZd{{XeeH#~JPRG>qSob!`tPwwjf)sMAn`pvM3RD(y80{&#DjA{HhU+TZgvGzP0>P}hOkwbvQ+8NlEMXM^$p zatHDdgl#M|QhQeUI0qX17=OnW{u+)o)l!H7xi^$Xzi+{BA!vs7Ur<5p3mvHZT!BM| znkw;PeNeBBZsDFxDDP9_%S3s`&e}+t_6?XQe{L?zZb_*n6Rv()G6B}m?As6)e({^= zaUNx(n57q<&!5^Q^5Qm^d6XaOWXqIAvLQLH%yo`lRmJNat}rGfs`m#59kv~%ugsBl z*%gotFVCTmSk1S1%xPrDBQ(C9!*ZzDV(5u6j}WJ4T91?tkIyR-hXeOY!DX?<{VE_EQhwVZehtqfq>A(LD95e$HU};qp>#N9d}-R>zz6|) zaV_U=6H}S(+Wix1sAvoAJMLLeDHa>ZC#s#azIGGgKSP@$kb&KY;wAAfJ7)O4FhRaD zeWb3#X0ljpAB9k#h36E z)FeB+e?UMvhDtu!u}oeNwSU^>$rDU_!mv2?D)+p{Ip_96$mg{z87tIC`^66xUgV{; zDFSSZ3H$M-?o9LA!G20C!*1i)0I%uJ_WY2q%VA6Rj`i%7>29^@Cxuycbc=FPAH{_x zOGMO%XT77|lG+)2yV?4Of+BIIRfWUfsNQ*zoLy#32S|LT_WBx21ha}e;%BEvx_1_^ z`u(p9(GmIZM0)3*pLXt_Q2~i7hUq8aryb*8PQAp%)B7kMeNoZs;LyTnGQ6W5l+9Mz z{KoDDc6!H=C+KCORnB+%Qr7m|nxZjMsmv|oUt13t^M=={O2>%c9Fw@X^+eRu7as<% z6l|?*%^?(bQjD~*%h=9#Wj~c%j@}%8qEUpM${@(*0(^iWWpsVuEybt+ia!0`G1b{w_J$=4POfG2 z`bPegSIBXLBL^+hQ#y^b?Ns)?Beolf z@Uk+?_qZUh*ryr$65EhwhZZUuFPDE*u{Gt5<{sepE$g*6o6hZ7`6g~`c=7u7IYK4J zw}GCAGB=(r)V>H0(~pj7A73qdyTf%!u>^atvTLlwdYb3clipXn1GMm?pFARQ$pH#x zxcVx9PPEH0tUIU@o=_PC$$=#fYva7eNxq3-K)N7;k%Fa#tuINeD+DCx;{mAtrQzCnoyesL%jGx z7y1}IUyKRc*Gz`{NysVxBN=p&PmI~V8XmsfNpm*8Z}Pu#;`z1iGX%%U?RF(CnCHR0 ze&tD?7SP-uq&5=kH`!2V;gH}h&C_TRr#9G7=#*+KB+&iIW4~B*1TRd9RU$e9hP|cg zj3b|0e~MwL9D)ePD#$uvp5R@?_NSa0TwKPVTW18pq%%OouwRMx_ijRYz)B5-88KGB z4p21?p9K2?0W&S$GT&uzCz0&*_1ioh3*OQdpD)Va){XM6m1tpCPoR?75>`ui2$%9x zXza1u_d28f)z-RIgCo|I_PZo&g%RyLN#|0UHn2oeO>Enp@vq(<(5DXEBso8CQ7t{Z zOqHAT2H=oC8L-aJS;5LyH*%N{|MHD0{-v%f%;5P3%s}f069BfuKWK-%T9>GH|>#0QqeqL%L15smg|dBm|^I1LY7vlQBN+0&$JL zQH26PP~E^jfe2V38v!q5769JA_uWH+rDMKu&?u-uAgl})MC~8ll$H?C0I)`KfgXWf z>=1doN1(X3Bxrs(Kp-;Nes5xDxFJN7dn%gBAgTc)+VBAX^1(Us&2s>rh-%m*Mctx@ z|0##iqP?P{NWlbVEHHXN0Rk93K<;;}=*GFC^80qVB5y+E^#m{4Z}W&8$xp~8bCX+8=%(w7KH2u zkO%CBs9Ru4mfF}3kyGRQGQj%A*so)~@b0f4A2yt5)WqY>Vm@xKEFQdVywz2B8DE;J zu_XTT^Q%QO9Bl;CQPf*{j3%oE&HS0j+AH>t9VAe6WSx_cBaDM@GvnW0=d_cna%edS z%O5t{hizOggDI=Va{W*5mlEv>ykBHf@zf@{3w$@ill%PP;jE`Y*(Z#^$C)E_Az*LT z52v{BoQoUy!3_2LK*>{^(}srnKIEp^$4<(@Gt z7#7roXFLl=T)$Sig&xnEeV_j!4Vjb2k>8ev%!*r5{z(tM^kvGseI-xl3P`^nkvtR1 zRiM!td=I=wSeC46X*h>)KfRs>v%wW6tUBdrV_4h?#P|1M6p7@Eh}#_LBU#ta%4IUO z3xl0wb&E`tW$;yuiu=T2)LXEFOz(1-$O#}=u1@I=;*q@4|60Si#zZl&|Fy_RAXoqd zLGb&|JPUVg2@}PQDXxSMi2A<$?++|N>_OH!PV2aQCKC~<_wESq-75gB%0envN4-J* z^a#IZc;`qs*icfVu7{1yy3ZMm^YbZ4Dy~qh?&+@llH{Z!e%A<9;L zgT*#yD=3e1II;IQLS(1pNw4fl;sHeBqe`!@GAD^A5RdqOJ++JE zFVRSAB}&{(>)p1SUoUmrtZW_|pvU^`IAD5hzy_y>2a#8zF-ng=HsQw?vlei= z&tT{jCefzoQ0|*6*-f<6@PvJ|J^BxX*dH249@|GAJv#G5^lVg5i(YTpBP9ceF(ag% z5^?uUvR!Bme6(e=r>Nn7?{*PM!svXdkvVS(Ibj78^H&@|*kZr_9831^v z7S+JFsO2Wt&+&?#6CJu9c&f(TOXAc~E@r=}HJi=sw{;I@;y!GPHcM*w%812-jgLf| z5Ip~p$CCaP6&9I`_2I*+6et66 zEU5T(e&W|Cu{-(_0_N)@w$Js}<78z2B1fsD>eewH z=h}HzX`W=^bb6wP@I^Q(Q?#+`Wfe~ia-7G~w?^i7`5ny=sV5%|y>#GAPx6`7-rr^w zM(~L#-W_rGw??pms60+kD_1$)qK-~jx(#*OZ*1{&>e$6v z#J9mP(N3;iK`zH-T~kB}YJsM$=ZqSv^8s>H3;eB;0yAFI{++SG%F^u>kM`+=^Dotx z+8=9HYA&Kq9qkqK#h>uBzkE5)7ys2qgJ#wtTIujgp1UEB^FikbB~;q28~rK>=QdWS z_aNGk^LXkoQAzdVD^920$lepPh6|2e%czsY^SqKx7@O(FDLT*&+B%V)nhsRX_9<3C%QU>;MA%)yKs302K+k6jE>S}&?k@9o9 zOrFgqL}??@iZtvvjSddJ)Q_8SdjFOMxm|CyD!0yqo_!~w;ZbqUc>f=K;>W<9(s~I4 zt;GJZbcx0f*X@IQK`84(W0VTfI3b%3JBRl_KSH~-U2#=`iVrzL>xzGQ=sT5x)&&Om zk5lAt`^GWQBo>RP_d!eq0YGTZ5fDGh!i%fF@ zGl%QgI5tY+0^V(FCl(Ngb)PdP7=VLpLsvP;KF^GmHV>AfR(zrZE)^H%p;kItzR-bd zaV89`l>cYR85lJQeY^J!j1f7d?hrzK44=bL{QoEn^V#DG^GWTj`*O5YcE!htXVaS0 z)3s{rFrDZ$kX-jg68uq<+d4#(ZVxw7hFRt>upudq__;d)VHUdl5G59Me&J+$2DEqN zm1^Y15w%CQBO6?`QMQ*i-UK}eP#XTW9jnSoiZL+z$!zbWnHvm)3(wM$3W6LjxoaS@ zcov@~PG0QXc5L8tnGbmtDh|fQtaUDLZf$$Hu%QV@x;tF9!&f-G0dJ+j3fJZDnBa!P z6#%NOmYDygQPa(m%1O|M4jWYnz@VfK)zaaQFau|OjHrSr{$&yeIs7a=%1@((37PyD z%5va<087C0d%cJT95+FsZr>3co4S){b&V%L*}$l*KI zFZv#fM~}Lf#a52#9%As?Nl)r{6YCw)JBqdgYEe_p6#{^*B$Kay=(mA7kr-^^2taN{ zp5O_wGt;qKVH0A&5L3wZL43P+RwV}1{pw>dA{A;^aW`VG$!^^dR8aGKt-+>8(9F_C zGz@}Hl9s4I7pY0An`g=28Zt1r*utKnZ&iCIMk6gQ`d*~4qz+DCt@hX71O8A)&DEAi zApp{mb=Ef~#r8OyWGJeA$;(b&dA`XrzUkoWeTICKl@WPzImDCoVX7VXELZzr8o46D z<-)K}r1OQJlKL(ejNuJbRI^5`4?{#1j^RxjsT`aDnA5@gozuYi0%!tF&k&@8=zPJL zgx~g%0ab)CseBy4$YKQ)|gDhFg5-}KivJ*o1pJ(Xv?fdXmv&NWzHx&lNA# zI^~ml)a#t@e9_YXRdahz60>*L#C_76ln+B0Iu}c>_E(l0xN z<1S{SM4QC>Dz|{SQoRM6C6!xc2To}3`{mHQeJcS8#r=so+WW}5|Ac9cd^_hn`=qY0 zZ$B%!zDcLw;Gu@uZ*M{sA|BU$B}YaAC3bhFQfUO|W|CIwEMGpg%WGQ3XQ(}6X8FL{Q@=3Tg61YB0tlIt z>|{_T!*|h>864`S&LCm2`iDXJvhyUJ=#2|c8kvy`&9;h6{ggWP_=hS zrYqqRJSz(`k0zo_W@MxyU-@G1s=+GKl+ZkeLZs(V4O5+@dR1d5*kf$F*WDX4cKN$& z=D;OC;=~`_hu0cOym%WT?fnOE|F|i)NqVjTg>Y?11bpWb25$<32wO&<5-V(iVW#kcS01JLDnKd7!(oF@s6(AK?~^dSeJVP0~;S*l=Vt z@FbBAHyR<*;VSD0@0cu4FAqY&ic?N<0q-_@RlncuFB%@KoO`I~DE(#{OEc=(e0=AN zk;T4>ZOsEO!uFqtm~fLjv2GEo(n#HimqgnTqw(@&T_W(zsa57{ z+K60o7N=S|uD9)0^PC_ck~uq39##!4q)LeNn5)_8d*Oa$lN=|mg;^`A*(X2STFSR(Fyan#d^8! zZx&>v3AygJ+n>DNOgj9OS*>p9Wr;0kYlwc#pJQIZR;t6%l+yHjaXDweckK6TewG6P zX7Yr0q$g!*+<(4`Yv7tiIABFE-(8bL>h8uIY=38Wy+W&jJn3Xdmv4=ud}$7D#WL%+ zem?s5SE`HMwP$zs_$7S)n4j++WD+DOBf#xOI`x(K@xh7(-JTz(ty<_k)kDUMna{R8 zuhIB*$T-1y*^K_$^@$VApIcG-|9my5xzC*=fxCV# z>sSzd-tp~auTLlO%)dFEv?%){=NHd<+q1obSAHhDCANM)947FeFBsL&`vput(H z;KX&sbJCM!=v83hJ}kER$EZT-R*Zj@{JGB$zm3HJQRP(ro}nkm`Tw498Tjs4L475O zmp47=;Idi3I43YK?@3rNLaO}I%QNWs#Yr<0o}$RE*jlMEj6cxnG{8&U^1@3V21YCyVa(=X5_t`r*k(CQB9tQFvY;WtQMFRk zztC=T5=q`D`g;;NTG^{vLDh2`@ng(+hMU}o;yr~0& zLfD_|hVsLgl{Sh&aYaRFlHP3215X56!d(GP1PulxVd+IECV-oZ%Sy111CofS5h`q` z1wV4Ar^dW)5W!!15`Gl5k}#H_jXHcj3ZM%SFaQubYNOEYr`794fCVtpOoSBh@R+*g z>*p^@kC_d9%`Um{)nqeSSd(_ucgppAZ>fL8c z!q`JXpDZ|GbVY}7dVA};vW|SNd(td7t4lSo0w3Be&bzq!tVs!?XD3voPsCdNHdeJ0 zT(k0_+3KCG!0ZFS8K3jstM;aQrLe6Si2I zCx|l*=5Z$B&)nz<=dA_H`aaKr#SD+Um7+prHEe70qk+aYi^l|#-ySg~ODBW&i@5_P zLq9L>v>TYVtfYXe zfIqY~x48#L1CMb)n|kSW5nRNEFHGgp-)YIi z-)aA2mZ|J@n7~$y+K|fk83lZQz*``&+e>cbj_9K7t1qFsxq8U|_!)?yU{1PgfkMy; zUqZQ+WD5L0kp^Nv_jHcQ8jdyIE4XwIE|{8zO^S3HqiurY^_p0f+Y^PdFP{FqN7*Dv z$XP~HYY^jqr=|eK9O**KBRs;Ua3qEYg1(sWh=jsX#Vrme_<4lQ0%=p&poTb)a6aV7 z@d&#^q|77i9Y$MRb*n&_ITGB1=;`wa|KlFyTx_0UBF9Ui?6MwpNqsG=&|Eo511+l{ zhzzv`In8kAlJC^;FHD}li%?N4I?h|53q3rBF{m6k+8B5}I9{@iRarZf@%;5RhVvnC zZSoEVY@%iLE;D&Ys*rQKDU3b)PEFboUZeMSY7!vIyHjIfc{n5MQaT38KHRARhbqZm zj<;SDk$5jOZ+BaY);`#NM~}29L>!&>g%yvw!F_P^!d)@x3h}~SO~n`~9^LR);uWR{ zpIcS84qKMJp2mvXidemYAbwp7oTl7~$`t~qDW|q{v3?UTGSls1Eik^O71Fiv>A{6x zv%`}O11y^Bvxfd3{EK{77rSC*9c50IxSKSbe_R)&w&dp_bffOhBJ*UXqD+^!A|dUQ zvDpe~(dpTm_1)>&{H3SIuY9?XQ)zs%HRIu6??atgJ?yK4=gHj%HCZ*EM~%?;+eFR& zCW^ObH5n%gUi)4Uv9pN<;~Zo%oh{*M*K@eWtt$gHKZ`}X?C5!ShQYePx;z>qPaej| z_vxl{<6P1o<3!uH66~U9c~v9}hJ6#-beArO`@yq=Yf`!! zrT${Uw^Gc*9i_(}9BFYqkXo5={U$wAQ11J#*I{a=2U9D%k2A9fv`^+N=B;d{Pw0u9 z%<0oez7&(aa&N4!Vp5}`?1-c6_rAfv*y_s_R-mu#v2ZFru!MQowE5-p*bKS;?QNi8 z_uzopCso6#3bpgp4{kk3MPqcn!jrZ`nLIcEYO^PxqxuTJL^d5x^gOUHP!6|FDdGW* z8Z+hIp#U}zNV^TI&`%pheCvfJl z)HZjvl)A3AaS8sI-Cbad*xjd(ExE3aPX8XO(3HVEEOz#LtR-PHZ-96TjNA4jJ}FY% zuKWGD$+3t2yh^<~3T|rq?CC6i2kb!-D}~@Kqm8K zwPBEL*$>Y3v8JkbEb^1H3w4I8DwPW6HNCPE1wH48;!{V61JpHMG~voKRK!to_2n6j zgC3P>Cz5K%&uvXAdmRAS}4CM^4qJ5w>SO+oGuv4*Eqp zg4uuR;oh!wZ0zYXF_PEo@3uddeKpSB2rx5hho4o@pEW21>jXp|e4rzRYqsnC;MvsV zDhusEwt9m;r;yG1r_p3QNTOnM4#RfOm6@RIs*eEc;+eJ}d(rqUTPVOf_8rKM*jae* zU%)z^y$GL5SY9TT2fB-CVBQMka<9pP-08bFhJxAiUx=f?3Hf|zU#DR;-Wr+ z07J~F#r&z#qxw^A9nyu6Uz{iLMhW9}2KCl|mTtO3FV4vP=wCXpkf# zJV8o9vkbYL8}u_8Xr$TSA{^(E5e+%j?!3%3CT}l=9=MgF7YdGCo{=qReBVK0UoKy^6bylGtPW?-*>188FB~5icIXGUHeKodL+|LdxHMpJr341qVQUs zA?^(0F5mCqS7ypOguzdDP!{gFHd(IYJ#Jlp`rzTqzq0AckAj*})2uzY19_H$@#VL7 zfIrsYq-ya)*44Y31rE~J+-VS{W{JsTh^JeBzcs$6f*fKq^|i1fB4VfY`umEHiC3B1 zed_B78`Z;iAbyeBjw6S5Lh;y>5mO6+{wqgv86mOj`?wctU5;E$lnH*`WC8Jly)XI z`AsaTRk`k=UTPSb8}%mlHB59*tb3DEuWGKXOhh~6Egq)uRcmvaub3Y8Pq$Q#?2HMG z;3;*nyJ{I3a#ObFTZ`cD;prc1eSUM@BN?6GbF$ma&SZhb%=>x1!j{s+h}BQeWKcN& zy1A@;g3cOw?PYE%*3V)mh#r4jMk0W&BT-s8Fz)%D<|qUJ6QwPa`CQD%9QCf+&=uW* zC15q$Xu(~IE4n^nERt!yCXhB?pdj-#6N=z z$e*vLNR8xRcucT=d1uKE8~-;K*HU)yaH&;B)OM}EJ-J2hRWvg%Cbs0DRR5Fc?=zex zw}MkER9u_JU0Qz59y?YWIGS!<;N3%xksbE%D}HwWRj8~rG5TM_u=?chP|pa}^(%Ck zrOlu>zYj@*hyo%+Rk2pNl`y**Hg-uqa@6S%up5)k8^Na1M~ek7`@Hsn-Lo8qr3$Cc zRX1TRl^^FsiU=Fg4dZ_uzhc2ibrcylhcyuiq7VDyA9Z z&v!Q zn6j`AScO>ipflOHL`qT*|Rwp0aNvh;Oft!<*aA@Fgjxy#j9=4V3pTvUP{m-=4V*Xty^f6r7`eXsk~ zJ2DA}JC}W`zH68?UfZ3cB$^Gj@**yQl6JE7-lQMhk)9DN?Wf?4T+eF*tq11uA_MFz z&m+;Mv7?GYjCw$f7K<6y5bwY^mmR0&9SZPA7e9bCfJ5~++pNgz^P8<(6D z*u*Q}_oP@6PRIP1sDlP!upubYK2_QSOC^-R3q&EaK@l_U1 zX}>x4i+O&avwcQm(e<-R^Zu#GdDqWgO&jrY@BXQ*1y`ut*?xLOg_A^yhW|wFuQLXI z3ChaU`~E18HgEK8o?nk}IWP5S=5hZS&IX#dy?3YP+^b(p0c5yd-#jX_g#g7#sS4NsL-CM_1 zw~rxiU_mTLY2zk|>I=Ca@#K^?y0$_Ods1nBx@*d6&!yCf(wL) z5ON^2K$x?-Ep>PQk(iU*!XsxPV7Ng#qPW}aPL07+=1;Lg&LEwzs%KSx1!1I~_1nLB z8x?gwUh_ar#Of1>VoqPvnzaFG1ZUJ%9${4wqHJT1L06_=s{eX)`U?&0Gu7%VpW==3Hv z%MzL{5sz4BFK{_NM10N$?4kIaz06MW zIZI>|%I9Hn1Antw?3?~(Ur0Z`pCSuE4uU*{1CQ^^He_KQ=(+6Q6+3BlBxV7^n$?lK zEle@nt{#cugdlMB2$rLBuX!!v0Qa&?L!`RMhK#HE?a7+vcPIarD4phsK^NSRVn>|L zj-H1b`+R)#!X7JdRXb`1_jS3fxd85~yl^5VprWb9;(3@}MSN3D@o`@GfJ`Yl>(W_h zc$sdn`Qz4_l+eeB=h>8q$A|~ql!uS+LrXnbc_9$EMPY}{of!*By{psKsy~`79(%M& zjWufF3XWg8urGr4Q)laQH6N-MjNLg&ncJW0$oaW={phNinYemqRKtDW{fjE)bO8L( zw#{E5xeY1?cWoo>5uUtHv`{JIbO%FEs{ZB3E|JNDQ#YQrNKcyDR%Aa*COq6 zR{h8Q@D+l4tpZ{Q-;5N*xw& z$7h)Tygj~R{kW`fYVInXEP3Hfm`Y#xllN$+inDqK1fiy6I?}0O|I{tSSj%hI`KBQJZX%3Z$&Avp5y7t({^-}+tUkLHD9=ng&yc6i-a z;Uxmx;Y31%MmwwsC7KJ%8+=HU0G>!0M}h2&{1g^kEQ`LKr#H0JOY6uYqOu#JS;FiX~0`5dEgMdCOIb z@Tt}c7{c*A$M#d$T(-x)*f;k9o(%zX^0k)05*9}HKN_IQsfh06GWm*iN>QN0rR;~W z4}uH?DF_k}_CnYLVK)R}I^1)LJ*LIBoazLV3RLdgDlu z5S`5j&Uuy4ng>EAgbV+l?O)2vtHAJH0IcLQS_E(S#)iUvzdcV;Oyx>ZFy^{3>XSwH zhd{Sn(Gch)oK~=ZXVu;Dh*=LaZQ8G=*ns0L?#RSVG^6iIRoT3xxw)-mMqG$A1F04{dfvh!hR z2bH@VOJg@ZOXU}9H4+Wpw-)a~GdU|6jxWUAVIj^=93dLLVj#}W903a>K4+H}#*VZx zhrNCJ+QFSJt}>ra9}ABsDe*Y>?yY%~dY{qKlrK5T`;*{PJ#6(Eb3<9rx&1zV`M2u6 zS9_!VlYBa;a8k0r%yHalxh&g!J+Ds$Q2SpGJY7p?;Z#4$fJ!WObt{uo&;86{=!ypy z$-29hX%vSX@>m4qb?QCduzjYXa~qh^xGWfdrN+rVfkgX?nAw%EL*Zu2ao1N*)dGCa z(V{|Q*)q>=M^FFC?B#tDRc3UYhB#1S@A$)*PLF>(>Xl8Uf!!*NOyJQK@(%u*9XQ@w znMUXH7L0qfXde$i1U^X@qwrlL4%~34K@b=2OvELCd$afAhfTEhNVGzd!(Mo9cpAwxOV$-Jir;3D()hm-dqj!T3Z4&U6g7B-p^@>+YT zyq8nG2~#7O^+zMB#(O0RL0ev>`&60RC4T~ZmRR4%kIjdS&0}mJQ=@b0=+?!Fi9W=xky3s=YSoT(Acxz4{ym_C;(b8sX_&iA|nx4q*&jl=)9mq#OeZx zKq8D}{`Vwt#-}M3`a`6K+`Csu$Pi$Xczl?O0ww}dFtx;Mf-yQ|I#4DnB%)}DDML}D z7^1)~lCqV))$d(WuZYG}F8UzVU<-+)K(1#Uhf4qNvJG|_ioyDW-gfr}iU?AG$EjC@ zdGp&Iykw3(MNS8o01>OTXQ!COKm@vUB=rxV>BVJc96$_GAOeLxcn~=;zt7RMYoL+$ zE5$0N2?hbYyQ3*J!n;F+@a{dCfcTmp@T}n3w9+w(1_*x_4Xh1l+|@irvaUWA;PxNF zJg(ERF&+-ajWNM0gA8w;fs#b*HesZQWj!)rK=-fvFZ85;3-3D7QoNY)**D0N6ECsj zdhh8MT`%V^hwbjFE;?=h$v#qhM}Cmt#Pg+j8)Ni|OKlQTYPNYFh9*OBA8+82ZQ9@Z z+@#vi{us<@9oS((*@L`w0NARB53B)sI!R{N;i>k`5nAE);1@?yFos-xlsnl?5{U*k z$|!)X%SPYf1I}sy&=$9(CX=hbOfu?v(IgEO5n(9MM{s!1m8*|HETmK^nd+0r=(@W` z9D7Kmc8jCuuXQomxsb$OJn^W*FBe#iALEa1n(8en_U~!FC7GbP($@=pOJyNmRvfRdeGupXcFuqkPMHLg^x zXz3}xGIvwzyC2k-S84b7SiNk#7}7>h%CovMuzQZ>tl*)il!6BmHapC3ca&Kggz{3g05Y!D^J(d>Sp}9I=H#o3l5v zay3kp+tyMCMvG*Bpn4Ow@4MER6 zgS-zuVbPxJyQYC8mv9P#;lmYQd^R(CMg;y&LY;N1@ZliAq$%&m>y;gaa-{P)^ZTpc zW95CV>bpOY3YLDGG_P|jT8<38-yZXl9NO;2eZR^=x&pk@IQZ;h0EGlYk5JMK&!qtdGwcC3N4 z7%BdO0qAGqaW2=D`-WTLpc(=H@&>4+DzWLK@oI!-pEZOH#ahl07Wwu7kKbq$wYA%J zztlLP1mtWpzu4jb!5ZOTsor2Vd2#>ZZ{rI^+vmcvA~XuNvYcg_7PlAd{~{JUbMyBj zrBBL-@HNUuARL8o9Ks0*x)4r6Fo19hg3+NGHi=zUcR6-BZ{ysBFskLW6h;+~79I&k z3$uXgydD*)4b19w{HET08{e+k7mvExR1OU$f2m6SQgtu)bRf&}poAa3hOTK+;ugM! z)9!hQ(5~!?&ezWvg4HfDopYi&DljviF3cD_exP%j$6@dimGH{fFbBiQD)+BZ!yPf{7NH}xE5~DksW(vx50CT0 zhr+IrQ{m1$cUdv219vLG`fcxfp)d4DfqT^bjgCyX;-*JK6-f_IgYJu%$>CrnmW+#} z{Os* zFLCVH*6PHLh=Tb2RC6Y9_{Uw*pZdgyRBE<}ZTN093K!hfzx}3fWAkpZE#tCOpA{-m zft-0IHF?P2G%EDahj`~c0Vy@kt!-9Oi2G_pb(-13s>AFDtHuV05 z_deXRC#uNrFsBy#G*7J}`RU-#8lSSDJy;}ZCC*5tX+V{_< z-1g?Md7S6}GpFqwTp#%A=-*&t*xV6i%)5*c@7qQ&!lpGzD^+5hyOb)^tFhRS`J|^& zC1dM(M$6l9DL?ti685Kcd(r9ToGCxeVYd&LQ6^C`#Dq6EuJO0Eu`; zy;X_Lo3soA}gXI{BU^zy}{_AqA#0ECWn^gW^o|O8e->$)#x%R2V(t_;_ z+*9>o7J1sc1{rSi-MlZt>P&OQt>C|sSo@P>hfX+Fn9(2c;_Xpkr6RB~pfQZMQRy^C zz?Mx2Y}r_e(T5nwy1Qs_q8r7e^G|~w|9HCX_D_~`n^}|=DPFIsg(#05>ThesxoIS|0EO#O_`c1qr&zUE)ABp`ap_<_NxG@gu)1Lgv56Ks z|GBo+cO#lT_W}t^!GRd32-BMFOv+b;w55#I4wwlw|_> zVvqQh#ct&NsZ6N~`-siT+nJU!?gswuTlZaBUR$vaJmIfopvoZ}du;6bGlgyY>yFO6 zoAw!bTF*y&MP|kR03q~Hm4jn8r_#AM3c-@JJJwajCi#QfA_dmAGGAD|#qv&i@^smu zZSOif<;3H6QasIfog8seOU?HDEqJOdxiY#!f?RtUd{$;|Avl`?;5wBmo$nmlWE*fc zLB_;C#hZR+HVQX1+>bcC9>K2mGQjYm;sN+~04b1*AXH%g3dgSg@U0>#MO)h!cQP=L6`z<$KWpoWclI$dpWl{y5h&q#f&L``$XevRhK;u zs-i)nM7|Ln9@Zu!>k^j|6~W5%S~=xB_o<8iz1J3t*4lUC zFD4n(m30i#t48nKXJ4(+X*Fm}Z<_C$717D<*>0)C?PJN3j(@TziaZ?gcE_StOdw!fGXOu`azFe*M?EkiNC-)vhPDIl2B%uWw?XH503FNcE7f&XGr%ELbF zqp5K>I^!(70{Ogv*?O^T|9jIscWb9=9zksqj$bMr>dN0U}52g(Po+ zwVy$IeWmtlT#*0DFt|G|_32)FDNF3TZc_B*+7h?zq19_Uw?~C)E>1T*pXwoXXdZOw zMqO6a`lgvm?dIS4yxO?2z$}kt!en8u=xe>^C29RVnfm0o3r&}*%PN+%tj@eVx>GIv zqOi--F)SXoH6Ga2C6r3SUoK7Rmf zB${G0Y1G7t59#<09t>vRir4z7;-2@Eaoq7}S_ZMjc^8Hxj`EQV>)XQj^`W)R^HRL! z$(oD;38jIrNzp8iMty2_PFe@9wal5wJ~4RE*LZJdan{V(=d(IRq}^=btfp7~#bbf-NxydM>fOnkbwUR5l z{IKnzi4R35e%!?lqPs=XyK7b@pH$c`m4&se-!a2fC?!2zZO*91T6nE{z7q0gTbX*= zYDfd8!@#!ShZt2lBrtE17zjq1+i@v=!erf5*jOyXzG0pnsQ`$|$AwMOpGW`@+z5yn z!G0w~>&mtrMY`FQc9e#~mqWDay44CxOaKvmFba{8?-oW8lvBs6lf5ucB@4-F@k*o0$_X{)Z<&jPw@&&L2*bElk@|SZoBxw|2bSPbZim%2FGB zOM+$L?TH`N7t@0hol}T0Wzv}#aUAl7V8l^m=afrguI|(_CR-Rfrp1s5Htu!NR8%pN zw7$3kBNTB+7meD?V5q-%49S}PB1G0f!`7TwhLpxi(xRl0mgzfC(=X6a8D*iaLfNj{ zt={9lX%ZWL*|6x>sflHWsetDh4AOC5&RdxT>9WKp9IHDXdb6d8nmo^xU7*@blc9v# z>e2s${nu(;dp?g}V1gmpws%B+agLLYnDvoQf3)hx%yo=^Y`H|BRkd< z9qPi87ST=v(T`Rq=3{tECpn!g(;lxnbjFOmEmv2coE~f4!GyCsoXqHCV)Fj-)MfL6 zdPb+`jSJm=X4q3jz28H6+*ce5Tr6mpNqtcx$C6Y((pCsfesJA?qErim`Rsj)BeAp4 z{D!)lOCiIK(pevAZXZ7zyz0kg7%e2Z!{hmmB#lb)O zaDAlol@B!=&L*%MCsH)GM7}YwnulR>6tpPzZ^y|fk=WAy#7ckIY!{GT)2b{+GZ6do_DC6{+f%!yScVmS4NiBpWnx)CP~bpQj0(6!L53EI=gs0)@3bQ_x5FZ zN7F{5pLY}JQtz9cbiA2SuGeEC$d|u+`tIf8IoTG|HHo4ty49Z*X(fBI7I~(l5^7Lz z+{4c7MM1pfl{g!+a^X7KqmesGmE6!_tIqk&;DLizux*WCkD2(ph~2$}q`_F zchOu!yqXeARoMBhKg+}~)Fpa^SNpo7OR}qz*p;gyWZX~dXOD9bMKVToT0U7dk_jf? zck^jpAF-ISlfUyFV>eBE@Q%Sa&yP_Jr|<+R`nDeS>W)uK#y2Kyt)@>JtqQgkw8N2x ze(viHE%}SR8vboqCzaa?iYB3Tt@c`BVdJ8b*pOOLwmi$yV9QtY&pnm%5^fgT4{Dc7 zcaalDqD_{LHNGuLSL!8ia}zr@@}#R#w^$%9$0)Yf`iuN{U@32@gQ??T`)og6%qLET zS2FolOpU(SM$X-kq#?yipCCMtW*{h=-N%WVvEsCJ?Sx79bF|S)HbQKZ@j2Qnm`_J& zF#i2+4+R+TW?s8clOL1ve;z`SNYpoRDfCq2Moei6{gEWe(I~uGvpBGo3DGxnDSn0$ z*budt&MO*Zo_%qKYOQRaz`K+21+U$1VMZtnvh*xeD6BA zd9##!);EbEG=6>aK)eM%B+H-B=}mrqrVt-tFhT2cA zVOu|y^)R>dHyVoG^yQzncN{ly^0lb0dauvz9i6xItHm|7$@9X_(c~4h?X(}+C+=XY8i4pQQLHA_*!ICc|UI5wgt{&kgyJv7{;u!<16m+ z$_{fM8lct6Gh?*haYn^7J>-!s%6L1U$+43M@NXHYl`QHHBv`&Z z{#uxG_9*-A$>=wmXPrMb9DTsHl_)3r=*<-iCCir&pCy!mvhO3{aLMKrHU${0^Kjr|)5=LNLUv6GsYn0yU154{auqPN!_`AvPjDAHgw z9*=){qy7-_?V(to{T@cIuQb0F{wyxt&Xzo5t&-xxMs?x4B_~x}vm6upUHM0Cu&2uVn7wO`#nUYrrz>Bas(f+!*eNdAYxk7q#2suZ zqr%e;KazlXBBX=&_M38UI0fE?)k@8Vqbjufa7UDzfn18EH|xtSN|%f=N8bySc+O4_ zz-FQR0``?w*D=$&p=}No-MA(Di|R|`!Xc$mt2He7W}oFRGF)`C&F|+g^?dOBty}kw zvzi|&6I{-X(zZJgO1&TOk1I}iV(9t!$4zK2@?6U4>CzC&{N!0hQ)F>2(9quH$Ud|x zZO72POH=|o$U?7zdsBTMM!XwsH#R0-XtT7m4(gJg@-Iu<(@>#wkyPs67Qb&qXJl%; zffVO@Nd2&^aHFMGl-D)Jf)Arw5^#nnrn#=#dVpPYHW)L zjZ}9Tszc(QQlZ*9`k>bVF*<>-4y}wg=>sKVJZ_o4yMvm3jT|6XK62y`4WEt0t3A3@ zhCG>9wudNjGq=vfFA~=k)HMg{nbrfTSC3YtsQsJrgxRo+tNdMb5WQImD z#YGLRKgwlz>5NJh`;{s+bhVbSH^;-{9EYE7IXk>Jz$S2}UnxSL)#cfl3;m2%Pb1{0 z-fpqn@pj)>ea^L8T%o1Sa>oya+3>CDR&${fnypX0F8}!0X1ho0>vH5c%&NFwQHtzP zNTxRbex}s&b;$Xr@Y&+s|29)Ba3-~{D(ARdO4`tw&I^GOsRL&^RRSf(iN=@d!)A^L z&K$3d%1bn~9Xs&$(T=x|6cC?iaGZ*D;EZ);l$)4FiY1H7>n%3m1Fg;Wj8<^ z-(1k%W%UTkV)emJ7ANX)XCXDpwWT9IC_a;g*dM!_EEl_v=2BA29fl4YW7Kq%@nPaa z%CR-c`+A;yzwtDgm#nNLI~8E*EPM7?{p8iR!Jmpxapd$N@n?@5a9sDP7^mA5ZaDgg z#AGao%pCr zJK$|_4|tf%kV`b-ax^+Q3Qf+a#PCoY+12wH*JC&qUhGR$cN(a?Zi&-1t9W%oN{P;R zd$H3=j;tQ8v&Vi`$r*pVW%=2|?G%^e*+1?1DBkQ&@))0_{PefVJ#wz-cEPM`>IUQU z9JnuWrF(OHI8w!fVyAkKaBtIWrEvXGQ!mOL1WSa-Pgd5I7JL4h42ltH>v|oO*?ihtKhlbZ2ixqvg+D(ktK($6)tZZjdN>)tR@SF_(F?Ho6ebR zUnD{3z_aAOeZY z38>1Ccy&e`wo}?|6oDQb+3LIzc-yFGj^+2K!f1^+@%vFBQabG<6e6W76C?7!?*7ri zPT6@q{o~)@Me0_vLBRtJa@EStOY5uy268O|I7`Q?nf}3-#lF7D`vHSK4!1)YRr5EB zF&%Ov$k=slco9h%B?6`%QXBdJWMI*7H-BsAk*0c31CirG5h4VD6k@5A!%W@=C^?7_ zK`xa2%a$;yIweOxNfI7pKJtVC+J-z~Kyg4$`-~?BQixUl7{U^X{-;i0qau^39_}4Mqdc8ATEbD30E1$LiiSDNa(MkCyiH$!MhRk z{P1cD@A|b<>vi_0G#wF(>bX}hl@>sEs^M>$E@&!%s8J2pm+!_|joKL2e4B`9yDPih^s}ARUf)SZPow(D=F!Ca0Tk7x{MX~%6D4}-x2S^c zr^nOFA<9yGOGF8)riMu<;A^P!E^+W38r%*_RyEMZK4;GOay*NZQZE(B@1g#C7?j_LaUW0(!(CZR6^tx7m^t$0Z(2{qT^XF?K*WSz7y_b`G zFO)@nB!-L@<^^r(G@1f}#^VtXG@}qGV>6R!wu3UZ9?K{Kw{)!nn%E+r?FyV*d6*hQ zzDf7d9EtG&t?nUoB;a1zj1IvgNv7cdb874S+Z?Q(r><#HG5I>*l`2{p9#~PDvQYD% z|6QHb*)|z#T9p~b^D*q$b>p0^9t)@Q4Sp3m`mIm*&v&^!#<_n;H(@_wyvK*K{~j4b z*MHO+xPUdU>Qp#q@omI#w!WVKNJ}uG&A3s<-2vso z!4jBc+bJQqq=x(3{k;5;*#_1jwP5^ zw>?=#NwL;7ST*+LVRLM1x&x#8!RR}N>XWRYc80-rx}~pVl=5U}5ci**%ABCVQ0CNH z=k{51uw2jA`QlDYn02HkiQDlbu0JK8(2$ffY#<(YsXjAl*)|exG|i9GFZn(-XAPx#$U&$d#oGTv1?DT~Qe%^kkIXDtf~e zD5CUqQUArBAE!Cw%Se6_<)TH{Go^=^J9>yq(gG(}Rv79s?f|^pa8SGpH9-XCi``WJ zF8cqJ0w&5jx53w(5rvy8*x=@5Hn=&65NQoz+8a$fYt zq`y~m`!WfsaHnYii2&Gz5QIq|2qKE92Y`i{^~C53Z{o{#iEeKM`M#v+c6;uweqEj0 zA$I8nv9^(Q!2+h&h4J(;PZ(C|WexyUBX%?(aj5`pMFRlYe=eh+0L5{JXO)x-P(MR@ z)8{Z$L^A&~-vXzte_J3w{Vs}dr*Yr|5WDa;2#HiSB1BgSjrd2^((V2k;DPOcw1rgb zQ55D4wA>iS5dc*Q|19`3An2z!Ovjx4X@1`ur0IWG-WW787D=E6z^^@0!TWfKVZm#8X~DcqR6HJWB`D&21m#srGO8`)1t#LK)8;6chS>_-w^2?76W9| zuoxg+!eRg^WHEqI6I>IXZ@%U)rv;l=J^@*CBF{9vF-h>UbX!I6b_>X{WLJk-R;c7v zOUtfSu9!4+CDFLk1->)9_5Ptg^^>IA9~Q0Ve_>aCMP$3HraV6z(c7;(rbEnCwYGPv zEMzA1chg~Ju+-@u`Jngf!b|oz5ILq4$sz8%xc@13hkegWuh+$0>evZrbbbq^0f>37 zLw$I~I)NH>t{Ie(A{z&g)CRWkUnzHwa89{_M({s9A{xQ}j0MpM!cY*6AdF;FBe*fl z|I!G$gPH;AAsRs#1qgW%8i+=)i=q*PJVYZ1(f^riyFgJqgIz4BEJVhlNYMyFTSOz+ zMbQW%-GfHZy|6khqAz28`FDeoV6T$nP=x!y4Ro;kP%QPOM5!@6uSUpKcB=~-TR=e^ z#(v|&+VFr?k3aOuO$|dx#e0c8ha0m%>&jBr9Iz}3Zv}+;tH=IUn7X5{7gF^WIpdL)e2yNJd z0}VjuARW@f`@~0&%qU3Fzk*E~XEgFR#zK!wD9{!bTBI%i#!XWr-7gXEr%zh%#)t(y1mSQjSKJY0@xiu{ zZHlU&u+Hm|bbfV?Ip4VlQJw1!dYl>GLQ2b`pIuCjJSV=~=J;9kSSf=^h#wj&vwVzT z^pgqaq6q$1zQ__A{uDGm*n<&YrsX-7Na)s$`T2!w`r6iCy)Wc0fl9V88czqWdAB&4 zdDAD?i#kEF0T{YOXd>UAz-q{>t}c_Qi-)jj;HD0kp|e$F9o|0_~ISDc(bwKzNGGzR@4AS8%jg;7aHgT3?9ZP!qf zhbGR^E1(bz5~Th`ta?MB8c!Ej?b=%czRDC(O7sd0CR99lN%a)~;Xus48Lz^D14z1i zBi>x_Ucqq$(BykpFuuN)> z$Y_#=>c}4g?gVjGra*ZjFaQLWg+Cr)M#aP8C}2_Qea&V$ZnV+dwep?(YCF0~k7KF6uTeDX}DFHJ=Yv|Q%5u{MFMNk+uTfEY7mG>XBMRLT+AR!Ud zOgthY;Vc-;oOvc^!b8yHWPCCho7G5Pd>7-ucza{{Z>-cMdJ1%qrrA^@ee}1Scka)y zM(_61U1k0$|L*Ks9^N)UWPHy@1`t_+I87Im-_N|gFS8GFz9p49J54aM2BeWQ=-`T; zeRW-tw>xOg%J`H&()9DLD;5B6ceHwY@EPplHQR7n{X~NxNWqRLq+sV0rrY|ROla^# zxks?Uw(I(teXdvwj2G;P{6Bf$4{p0+p*AYN8{q?GjzEJ(V35VRV#)air(`t;EC4OD zdpf&#c-p&oD6h3>QH-l6o*o_5S`sObJ#!DXzlB0hOkT)Z1JUg~(weL07D$)1&UX({2-b$qPe0xNB}h>G3F< z_Tjs^c9P38&(`)rNzX&H51^qgJ*3zqtd|z=B zG7y1Z5#pS+SqHKI$OBBCBWUfVhKK?3eD`22&fERcvzuad>n+UQYo37c!_h0n#Uk(p z7%oj{+83(j%D^>2b|s(twSzgMPI4W`&e)vd^Mihb;_3d-V(o7|*m)IrzB@PUmDtA; z;8h)j;2 zI>K0_En2LvM&MZ#4Pv6!q+`J(cjy;ruEF?6p4X%gA!5}*R9zJNU9rew$PE-^%T5L# zN@wKUMZt_38eI_p)&r?OCLk8^h;EShJ0etlwW5!E!0zguHWx+>&~9+!q6TQ`i&qmS zz(YN*fczP^sIQVkSp(@ahuBe1EQ<7kY*b5vV==E93VJTZBn;HZKT8E2^~i!0s^>zH zfA(A;3)ORh3;S2k758w%b`4a7>bX!&0X>&45vu13kHtjwTyou4=vj~gJ(pzqVuSrl z1JD{~AcShwzv$GTTk}_gP!zNVTx5)Tjt`2W%wrX_sL3SiV*hwFqT2kp8}*?Dp_u=y zP%7sB60Zilk!@Ffa63@eF;EID-2#oM6-v}C0+UHV{^N58wxdFUV|4%45U@fCDh6SE zP|XbQn+FxceL-yJZg>6QSmfem(9zcB^agG>vh}*Ne~kzxq-A#*3bCa2#dn^Eou}=4 zTeroE$PNz~Lx>Nq)s{0=ww)e*{PB?(mNl%C!Wr)IEk@VaCxPxHfU^?BlNQ;<*M1X* zZtb){W?c~6J!Jz4{h!%&k2ua1AtXgw&4c)|DSZ!1XIX1V5aA_#t$0i%9kQVm>CKw!#V%GzGsv!7c-lM<}}) z%6x`~ab-RW_+vg}yfU8!{KI^9_kS>-p<_$&9BrXJmm&ZW4aXx>Q7W*R3xEo~I_8o; zMn&D_D5bZvC;8gM-pJX5Zg0yW=Cin87D~qlD-PmyFuo&5{^fWD-PxGQ&(uTdla0RP z0y=&eeO*n!&Dy@Fs~(!Zarw7<%qAWhX;A8yeYClRISJZ*;2i7l0h4d|oTA|UnN1U> zYS^c+>oE7R4(_7YOqiR7e-{Do|6$oj5Wrp*2M%BsH?_+?qC4}_)U?LDece3SEo%)` z60}RHOZdCC*a<7h-z02ti-IOWQRfA>(H_~WAn5;A7ciBK0!6lFS5-OJI11WDOmqMS zn9PKMa$s9U0aO#@4*F4C+&9&-poL&M14kvVMv%Cmd8j7-{eU;5!w9WAWx>{%;4)E{ ziaNmO5_PeE9bhhjy0VWTf;ZD&Ga7JrP%+m97tWwuD@sYgWsRnUV?kB;MRjMdSPHA3vkm=BU&0NRCj@Da67POfx_UU z@S5oe*5tN-I(d<>HN~y+z5U201)1qU$-`bp<2>8+p0!+v6`5GA#pgWMVSJ%<=o8x# z!Jv7T)oLqt*eQGeJ)Wzhp6=eqc(;Yq1K`ea6lW7tY{njEti|`N7|}(dN`GN-prSY^ zd7uxOs+(*)@`PSYA?~}py)NiVulI;&D=Bi%eJhH0>g2m8 zh_tt0mr9;{BY4NI*8kqUve%zU$~wp70%#HWX0H?W+VNa3WRqw3>+0J`>_oA3W$DSs zKhHG|-P;9j)bRLkN5E@HpY_P%^@4uawU5%556OVN+j!XASj(I#k^JU$);>%=q{G5^X3p2wC9MJ^U$)#c=Mv&Db-qPWF5(g<_=-;>8*!V8 zB|sF|zE$7zGvS6|&r^}Ex@!I06yD^CPuBPxVPPy7Vjy{aKWTJ5d7k#Q4b!_*!8w~x zz@w=B#kB0X@^0$qNj`WrsdtoUwkI89M2P3)AOEH{Wu63fzGdfE_RxQQS_;B$o%r7j z^~cncF<$SpiYsOj?v<3U(xDMP52_%Y_kKzvjP|~Ql*y;xPZ&#{TWD@9$=}D^Nr^nt z19$#~P@O$(pMZyBDwHj#2|?M;3!W+E2cGOt0Qz|F}0M zh}887b06t*#hWB$s;#S}&qHpK>_&GbGuag!ZQK&R>BDgAIRPb!-P@XG(<7+54pfMp zONguRzSeXu_kt*l@q-zMX|s03Y*FW2e3??uu^TjsE16yDW*_;T4`v~et^6__bMcI? zcb<@zxn$!#7u5&=*^hYs9RCyp;b~ElDrsRrcmX^he=GARI?QK*aqz>VzJ?QqZPvOT zo}5co{$l3|y50Vhq|ewHW?d!m>OlEh=R-$jR87LkA*!LMme4yngJCfO7w+P+Rz2~0Yzg{E;^py&}0ha>SkH$g!!1~b! zC;--vP^qi+qqfX}wr9Qmo>z5d4x7A3)tTJwTB3xyM!_6A`t>N~B2%f3>_ptN*X~Ji zgDjvA3LDC}^I97eLwV#;k&oZYkfJdi0xLjV%MWfQmQBY;=GdigMS)c<5S;fp_@xoL ztLyY9li#e6<*O?MetDJ@;{e`5xJEu+0+y3R*tpEWO9Pzpsxn?V=@k#W8!-pZC-^a$ zbKMfS3GbAD8wGBg6KkL#z_t*Yk&i=V0in3*06YW{;GRyod<|O&V;%pRp#e}N zr#mM!R&UM>nL|;}ZujTwU&=A}-kWTfU`w3d4>Q2vnwQH#{}c6^efkJ%hTUq2RA>Q& zZKEAjxaPZe6zhX<=pVL#$ z?rul>mEzHow_O7W*OPZ7Xnn79kI?(gRYwn@?ZVuM^7Tbxb`i>o+rFQp7GHpqN|OtN{9@Qnl)Q>(|(1`*> z@qEQ;UK`u`F=e~&t9$rkZQu$KweaZ;xEbdvuf@WP+DY>O_UUUlW#2sB2nrjOKQZS* zJF8n7O6cIn<<(AFL;+w>tQ~Vsw6jt+BX{j!wPQk(k>MK;C1+MmxwTvG-^_otBdo5; zWn2p2E@9Q7i)}R8_jH%73gDeukTn#-1BG}1xCgAj9ltgg{**x{ttS@Fb9rEL!jU+e z2Ob*&vznbm&0BrK;#o-=Pb?r%O&EH9x|5>U$@XUJ9^^=|c;Sn9!iDdhr_OcM(O`{{!d`GMk2 zke}q@k-0qbU+jMti;5t>`0|&Cis)b3{?0b)phVA0p}#B&3v69oRch;2xExyHxOw>7 z=n{I8)9AIgy&AKs+NxY`U|jS&rIz}vy_lgJ$6dja&tyHO@5I(1$*ME-zUOvrli|23 zX$goXo3Wqx4vtV zIuG}|wAszKswgKIjbI@-Cb2}>p1s5=3K`AE&-)fipy?8}Q~%8+>Xl+bu&M>w71Zbt zYNhlgnZOlnC0zLmwo*|^psCZX`4Vg+Ic%%>BU|||#EON;E<4?Xpqi#jAO}kr2TLFa z_{T}Utbfjzwed5@;pZD)@XsqEFaujtDsVrc=;a7Sa6yvoL)bTH0Z<9xrU;)=95f!P z65C9Rou^Jq^SWbr*9onsT$ZpD7kV#yd!BBeo~0yDH=P{jARvkZM4Nsj<(;uF2EM#} zIXOALXntZj;`zm^Jb?Mtjp_!t-Bwd6d~fNz?XAM3xo?n$qCr7>RkME&ck2^|^=;is zqVNGUjM%9jtVDlwEUumee4%y>G?!?1Dm2kHX=Jd^1$(Ou-e`OGdvsrAf)BU1-4-BZ z7!%|ak}nd9RWVAGBuTLhiO*^LE1Lbkxp)E0&J%V!y!u+WAdZEP^dS~0v?KX8hF}Og zT^ZARpA$+hqU36Zh?}3iTjpk5EhBHbG*3hbxlDOc>&=kbNc`cA&Tq)khHCyh9O;Y{ zx42glEm@U7^CxRj$WUKk?kn&~$xXV(KlQd|M_r02VX%B&!;Kyw#Bhs3T%Ubq%$|RQ z`hTAH2B%{KjMPJx`DSOZ!zZ2y;^$45;jgczg!9(@vcj$bH+Ux%a_*7=7yq7K;d1OM z9SULMps$QMvri%A8F`Uhv`)REgaq@R(9l%u%b8n}*Unq`{B9om8)I>AfQAx--P#{}A+%5dD7>{Fg@b%kBTF`by)vpZCG?M)w)=V7b`J zrlC&cq;9~v{$P)!yl8Upnzd*IexLYwXR+&k%z3c3#8lH+?txre-7g17zy?EUO=>zm zLJr1%I3_1Ti0DP`=et~t7c1=8pY&+AgzQNKBYF$Led?0eJt5#bRvI1LL7(?0Qrg!DP9Oj z*iyx`wi_i3pt*2-LOkg0YV)?W$2fyNuQHzxK}nqW{2S}R=rF&I_57F}jZ%u~w;mox z0Qz?NWJGKs=O#b~EGyv%dvVu;(X*uEL{$~BLoX0vzrU;`&n1CWMgKUi00hn7N6#|0}9L*7MlPxp((?c4^@6&kK9@E@V)L!kv{>x zQ=~^a@2J50#fnF3|NPx#bUC-sG`;kTluxhmTmaI}RWVlsixxcRH-`nuF#5V7#6|7p zw0>?c#>`3S5F9u+>j}mzuyJ}%q_EyTcp*H2R+4CiCuChUDgsz|i3tiM_mE4iE!x3p z+$FR&csjih;4rbkf=i1=L_Hr^pMgD-$Q#gXZzqFM0{Y6A3!#|Jp!Z=4qD2GS&T`*T zsVi!4;FTw`m70(DrRfVLn9m|%2pX}btl&q zUW&TUp`f381+)BpDCj4E39DSegx6E=84}pupAQRRw~`ajD*SJRBFHck&zc0-VDh=g ze|ka~2dXE0ZY_!+*BA#K;$-U6K$@={pRR2lTo`%3sXXCd0{)A#)8P{1z|oet?=XZ$ z^z?jSgc7}D_pv(sg$V5N?QX-{lrn5h2cocA(UKqgDri>D{o2K9{Wsnf$X0v33YOkH z|6y72D;1ZbmSYVrhcI90$s_YCT77slAbh*CU-)itzc34+9Ds6l_G?-o#2?DBP}Syb zz-5%6H`16zgZoY8?oxA_%D+YVL67S-7AbQ5QpZYQC z2M4L!P=~^|7`%-K`F@YNNZket2yRq7UQSh)57%SdFHn~!GB_O2T)&Z;zsxK})5!4* z{YgNT{vFNhWNCET@)T{4mwgjTLtZoPcd)uO#`|c!sQL1UV(tM!{4;`h0Rnsuew;8W zGx34eZdsOE*w~@>9L2*)H6h>PBz^Vm8Oyk;MI>VK;>>Avc8p?xnfJ!<+@{PoU3kMIoe!uQX`J+(fw2dyD%Q`} zOe_w^dx=>mt>D6dI+(j;3CiR$1jJB544z0dPktz@gt@0xPP%fP#Ru8wdG7bpe7OTB z%+aIyvNzl{btB11+F#<-)QsQutyg$YU+IakphVL`kLm{zyN&1`;u$w_ME4Rdl=Tk* zpQy4Ebnu139XsEL9W3Rv7eXX_ESD3DQ3Uv>fD!<>;I@Z}0xmS1tl0iqLTr54+G+y6 zT~n8#o4p1G%!Snw2)WXi&g>rhzqfeO3m``l7WXF5l5lO(3#zNgsjM{3E3S2!R}kI+ z6EhQmaeRF0jllcVR`0OFs-&sH4yFBMMbblM^%x~Hl+|Q23_hj~G_qw3w8{6ITSoW4 zwTT{h>l{5`?ta(2LXu;7?b>T?|E9}zMn-pgNM&e@=0*@D!epbkz08Tr^6C##EVeRY ztI2z3+~W=#97>Jd{S)IW@HR9 zwundFUdDPlD|>(V1ZrZ#VoZo&-L3PUo0m)B@{h|7b#mvbaXS>yQK@m4d*yn7Xi3o6 zyxy-BSVdi-k(Pub_O<_eFHc5rtj1^_IPVU zVq&?0&YY~F8rv%4NHC3if0L&ocxp08Z~%N#w6CS5_6*8eXk@Oqjd@fF->B2eA1bf6 zahxbsF8Kj*#<6K}H^47a-RWDMK#S89*L$&|2(=tGEpcETb+yq0GGaR{SM=$1g_#Ff50+wDU-*y8N`+sLH|-kW@;Uy~?yRAcvm2D)e}IMdYt zFjAIdKAdr7=-QjFF^k|GIQlh_gfKfg0Pm?T1*=w+G|--Kdfi3)#hIstj*u>i_U+MJ zeSh}_P)b>B9pn1ZMl`<%Z67wS-4GByS(g9LG4}{rvD1QlwJVZ0GpN=V%k0xCb&>SM!#vYi={H zvQ+Yp-u+O~T>rjSVdEOt_^XZKaM)xcnp5{EC%tWkXUl<1y#X}C?MK)l_6UScZ>C|F z6f#b!ZN8JLR=JTrp;Z;K&H^x<^|;8hYy z0VqXYKVSoIGG#|6{vGzDQ^rSNQqExtT*-UG$>TAwA z<X*P>Ku*FR8I@mLoCh*!dGeR1aW+Qh+x78Cet6id)-dvhbip>(kfwFoE444w_DuoCC7V1ob4ffbO18T4BYBTe^z z=WTb|e5mVjP!#moo#=jinb3OshD(_G=ZoJ<1YFMr(L^&Zv+=kr1kq@>eqiIo(&M77 zYtX1;^==Ac6otgp@W8r~ZN;FPg$2Y#gJ!iedHT;8^cVZ!I7Y*qYd*YW=79AAuuS?L zS~OeB#9@kQD}HoZttLdul%g-@4Oj*oTIQ^oW^A8N{`C6&>l$?Yd4ntR^rU;Z?M~%}v&np%>XPA=+jD)n!Yp z`f}d=yK)3QwUEH-fq9OU2%+24H0C1@408qX6g=I*K78HXK2qKL{rI}-{iM2|04)P_ z7tk96q`K+@=(P*!WDcFOtmgKGBvc+@f+Fr;hx493^vB+&)iT~IGh&fYD;p%$b^3`V zX1?(35Rf+u&zyR&z+h5p<+^Ntl&L0LQVZV0ujGt?xM{IJe(3Kw;AmDNUb_jh-xU)$ zn%(mQ!$}lz`a|epRBOF2u*7zQ4V`hA%!}3EkFdQ~XMa7&cK7SgTLPwuCy$Fo{Lw2O zmyqg8jpA8Zvn{+Sx%*X{W+{Jb`4_K54PMD%Q-*63a(j2;OxtEFAqxjD)mghLL)OBR8perBLJR1a_!$lF<<8b+>Zo{%+}=icsx$Rk)j*l2>~d0D ztyRU_6jHaGQfnIS3A2DHi-HN+?nA1yzl$h4jER%&8yZgvj+>LKSM_08Juro@#Q?$Z zTWQX2i&X>uvUl7Y>?W4gG9nucYpg1?;|DB%3R$q!W?C~kJY~Q8B5>ipZv(N(cy z{AFS9?Bn>i%AS&1i!vl6b1yd2klCX-8^{1pgveiJ;7sbeJMmhN&7s$P>FB;`dZK+0 z`Rs=6eEjJC%{RgeMETrk&cFRvl(#rOU0fasd}eJItr1qGHxxTR-jEg{H7y=G zkzovterVJ_+|wl9T{P$R_U)x3Q?yv+7^VD`+%*y`IJGBEXD0 z+qH22xHF^O@@~ue`a}_q_xWAipx)t{>xBl37~bcPUrB4<2{C|H^+X)mG`S-WWgS!Y z9LyIKvsT5wPnPrswpE(bXh(G`7FFk;aml#kolbE>^;KAKdXvQPgjnvo5_6tJjBA(ki7@1*$`9fXT1XdUTn*n zwU5sOejBPMEiG9YSm?la^jj)A=QGmbedlAou&j6$bYJZ)Hjj46qIC?Ye7hDF5y5ui zt{{m{>DylS!e7?Wrr)OPpHmB#4nBc7J%6KxXSvA6G2U}tR{!JVId+!h9tSza#*!MQ z*0YMJOGv!{85ZIX*~8!yt|e|MU(%e>{Ukg_;XD80`Vv2{8PlVZ-#$A(fiOv^rNYu< zEP^(E-kdv6?u2{SFY9v{d&6e_?Sqk&C5U;Pl^0!qqvC^0 z&+uIy-u@|inwn1GafQdnd%ubqI`M}bZZuOu-B`gK(Wa5y8S*)ywB^_24Gtq?|GLSa zd($pwbC(CzeG>;=a6`PZB5hN9yxlyujwqeB_rE#a)j1*$y6uy2yO+Hdi&?WU;xWQj zW5n1gI>^nR6|XDgKFWTS;bx+$h+XE@a9{HO>$EJ?^q?y_n&9<@S(aeU`{-Av|dIN3CckG1h)wV*A6TZB=7o%G&WkonAVP zIn3Gc_=yPB>&Yf>GE0wL+Z6^L&r=R_ccMcNp(DkG6l)Uf&4b**K4Ca-$zSB7>tTb9 zYE;na1^#ZLtI@^+ktKh9fx(66#ABYkvrx{deXy4-u3$_VVVgq%*HCzUE0!OBHoWGG zX$p-yb9}g*xZQkXN9qwtRE{#@E3!f{S==$aT6Jw>aMa3NZFD0y?`j;7Uy$7-@7v|&p_5$;$jT8ePID;@<~ z)9qa1`|zE0v!ro4d>WDac=*gKRr+cP~ z?;I_tOLkV@d#Y0K;Y}ku^aV6@A5V+OpRbd;6U1&Yy3D0Q$5MvLrAIFns7h6h;Eg*^ z=pX`g+h1^CaQ{Ks^|}{P9O4((NzY^`uOdthElQM|WAmj}wQrY* zzv>G;B7VG%i5cOcsI*9cb$GSp^~cqBh}2yu3+ek_OruqTq|_`=z9%}8BU2X}L(f_? zSJSsST-74?nQwE~`wIXp^EfMeuDJ{I@Q!lVZ$zfpo?JTjHF@s!C*F0kaxaA_+^wBm z5`j!^gq;hM}2ow>SGnb>?xOx0OgAOG${2}8)6k=3qE07&x zBui^`5k4rS+bCv-wH%H%Nt!Bx;ZWTy=d+2|PlsNM1S7H_;KAc^(qqPJ)MS3-rMLCX z5c~G|+<~1XG2%dQqg-@Y)3_-zKY1YKCT^YR@os6dcrWRDc&nb*H^<^S*0GGOsL;ZF#-E$fItE`|nn>TkX4yZgAVBCM(^Vw!@mS=;9{iQdE#r;oeGb5}~UnlVwK_ z>&4{rSEfz&M_c0TFV)O=2-u7QTfB~fe>_DD*`!Z~8#E&*e_8rGqbZ{_QqoTe|Gw;d zp}xyHh1?W}Itb|E80s;6gOGOhz{Q0|`j}>fg%wDIMs8rt@QvJHoKbr?j8P(Mm9d|X zJ)s%{#F8Q^b$edq)i;oWYk26ZoYY>r0Md2@@M??UMSAY{bRia!GPk(#1kk z?ZgJXT}YhF4D8|+*@CE0EH2ZG%eL>s5}ub)%BiMAOm^Z9#~p3-gRf({(PQ{mH3O41O!9HLla%hq{HaNWxycnqzP}nIGbnbvIH=K`>(x7e02Y(t-TTSNT#9(4Qx>2|Z`ofbQ+ zKaTXSfjh&WcA(Y5J^OSB|L;x616j?iJ>OoVB&y7vqYC=VcV-M5L#fA;43`z+eb028 zDv0k}K-qtk+3#{R?Gt;SazrH8nH7i9KQmwHlrGxr#(hPKcs z({xl>x@QFVI(HoBw`x8V(Re#cU_1V2jmy+&G9y^rwX&#jDXKk(t>q&!afVY^25zpH zJ28e+cpE#9i``wB_5(n1UYh_S7s6arGIS)eHVz_*615W0$ll)t%~O+KSyb*<$%q{6 zPDsTKqf+9v@uPphX@ue$W|0)Db!4h{WU9$OjpsA}DP+mwwz5drpY=~I1ndp<_~UPW z>bSX*Rs4Fg|3`}ytpucP{^%D(0xV4*1|8yih$2Vkm#_>E48@Sh@j6?ND#)P)*I})` zdq?{h(Zh$Iju%(ou(cZ6yc3_FQC~k8u7vH)6z?uy%5;WSaa8m+zC@{zf%JPEMU|EhO}TBgf|B`!7i z>ye@6R&SmWP9J1Gr&wao3cG`vK1AbrFo@-o-;aChikmbM!^gj*M`MoNOV~Y{7rAAX zN};10dna%qfkyt$oU9~4r!yo{>PML0PguCtXWIobvFYhYoFy=|uTu50ccK*UM9JQf z1R)pr=6|x*I^1I-GvKj%6!P{Q{X~*xGJ53Rr?}V+63V#>%C^0ygZT}#y@!q3AhyB-tx8B(sJbW! z1n*jNiyWh?8~9!)xi*7+eG|6mM1vzN6}Uua+p(ELiCp9VL{v4WFiIhN!jBU zQM`2M_iTD{x$N)H83xx_<7u?cJU56!`Us31#-Ck3Rmd(o(+lS|MMG9Ix@_M|0Va&9+;m%&k=-_1>@S z$NkRKoq={ec!f54SBVMwgj)bF@j?ubRtYnaWVF!2lyx6$ENO&|7HcQG%OwI3NiYg#1oM=OFw%%Jah!jIUemN=`f!?LNBc3C=o&*#QM8CGtbqo6$o@= ze5i)0O8UaoC*S#$OGNvWi;(-4LjdImlowD=Kv|=Gz!vml#EQ*>50ZV#DWiS-WhusR z6`RWe!BouiOf1>qK(eBn9kF64jkutJh3uHEC?7g4nZ=X4Gw3wMyY4r(-{&|i9{kX> z{E9L{)i@vIp2ggZFoWIlD1Xzlt9E3aky_};{I^?ixqrh+v+_7tBtJ7o(9+p}4m zypUVV=NA{mM>bOrL>{X;BajA_*~H!4^O3qlp@Nm!P1I+$Ki@iJC3i)pnAeuasqUZ2 zt#RLSosILKT%3`RxX|%aaN=&XbDS;nvF|Vw&Kg&K33fOtsyDPR_G`6Wci}L0*Eedw z({9^@mRoq$A}7uu$`e1Gom>xSCY}{TVfG&+os7CuQi_UAbP*&ry1F6hCt%IJ_P36xLB{&k=Gx3HER*Bmb_ugYmBc= zzm%hzywFnW#qRPx_1Kmle~xwYXAS#da46rBDciv{fHb+Pox8C|!XXNgYSufv$cLggp?RT2>v;rPDr>>n`#^36%|_hsi)TmfC6ui2`)iHue#Szx1RtVYSnTwCP!1DA zQD`eqx=cxmSbb-5gh|Mc)B+N|R|e1wiibck6^LBEe1D{m+SNec0}ViI(4mAW?SesX z@Ig?3Oj9g*V)Z-zz=6U)y8SjBnDjsP83P9ju0TFK;EVbn@!clk`;6J&p~Ki!0`_mm z+`|LG#^tH5e*+#A>X<-BO1nCmKNL4FXt@KqaM`8|ds(Q{6ebmLyOMXQ@>N4&QWbOA zcJY|2RkirUEC<0(@uI8O`DW`y9fR&iQu|u_?g#`F5M{GB+i7P)obyuFUb{Xh`MFP54H z3!IPu4oSt(=p*yoQptXGW6ZRyHXKQ%Fv0*JfMx(P9Z(rpOWc6Nj5DrJp%@lMDjM{A zw0>yxwuIW7x3@w0+sl$nIqJs#si5Oj3?uYA{GyqL;wqGLM1z{ZxaK1upwnc0AXvLx z+a}9kFfw}E{JVBwEvQegC=x|P{t#k#s3TB84@{4ipmEylKP<`b=aS#IAiwd<^g1>Gn{IF!6XzU-CMgRRqo2a1J2Kyv+14Rd zU2h4RacKtbX^3k&_I3vI?8xTCca7pW!z}|ISbMLsMhxc%M|JKNaab7;UP>vR6@*{9 z6*S#fH5fxUJg?5eCSp&*_qETvhTg}%@88UiZ5CMXxdTw+u~KbyI}T>5dV!<0Vl5sJ zebG;$7v5e*mtA#~63NH|&$F%TOTGF@Bt80JWsGmqA>V zPYN@hX)g%iDpLI1)Dlf1rZ>ERPB+pD7I`ifNqK8HzIqt2cfY*+?32OHi`^z z@Y5C-9{1bXNtp`^lU5`qlIW_aU~#ju27v5GaXScoJH1fFmsOSCA$gkEKa=DbEIxoEkgq#xJ3>$y$%{cycU}7)&*e~7KMol(utUlmWPXR zj(%5YrB|V@8Ym5WXP~U|(vrpOn!al9;f$Nz<;CS<-7wtYgDN6VscZbSx$wwT^@BE> zlY;Gp#IF1~cgm!5HSHzs%@6 z;)w0k_VF{h&9Q5mO3uK#jf)vGZ*btzsuNORBy03s#|mHE#6(xEk;FxBUm`V?dJ*Lo za~sO#yhS={I*(q{xoVV!6LoLWlapa~ti*lf1_w5nPD~GUi z_b}lJnLi^1_(~9muZH7Q20lL%^o;;1o=f;d=E-5u)R1I70GKCbxm7?t#TgeQH;OoR|#~Y-cOZM>TM~^7oy@8#ud@FEgJY_|ET|yy$?A4 zCyLh3jPOZS>P1JrCi+>KUQ?vgPh(9%$XxS%frvJuq6 zF^QO0UD5(A$v&9Lp}4p)Qg?w2cu|(t_*F0s5VZRPj(`tPS3|I_@z$es!STR)oZK3=r%OL*|sNK)BI+>q((yiB@8Id}EZ_8WG zSgq-$!9?BkK>a*&_Htw5&~eP7#@p3k`7502pqsF_vVY)Uv`=t@F|Sl)lBdyYKcCiF z6r0`|UI8D)MKGM5F6PUYot!koXbo49_gNB@Hol79zKD5gw!Uktv$W^5zDVY|Q+H5# zyjuCzJ9l~Q!}OxgiL07Z5{V@iu~Uw*{2E1weQ_V1_H^J&u$#}^QKCDkXyAG{@G96W zM;979znIwCwD}Pc$2p+Qs{658tWZ0B2<+&=7ORVn8; z-AUJuky}NvzJsam%T81<^ZrRo{-==TcNa5J-Uu^`{-iJM7$uF8N5Ksta4{lZgo7R9 zMXE9XmddqoIMzv~xj>R78DmLjs~@_MbA!08xLUD<#VA`eXaqFjxx;>ay z(Wdw`$Wj=lg=8olduzo(N6k;YrBIDcsZ6&L_|kB_P2A7}c+52g{hR#ogoviE@zJ3UaYQZVV@26aq#e zN?Z{%ivuun03!x4WB?p3uxU_W$@uN{OhB}1t(fNl-u?S1`nO-=&5jWV* z|L7iE=VP@#z8z)}Rt>uLE3k(EpLKJOh}E|k63EO_62R~T&_MT860Q!j%fQ$qr#QWh z3Vg`cp98=Op8;tQeEK&K0*;(-a+G0AN$sfAe@6nz-h+)>MA7X8ugxOHEJkvV?Ni)` zzgHOK+pNzZw~gJ`#JOY&;G4sqJq(8QX1Scz=fU~CI^M_Y`Q7f-)yZOnJPAihVU6|c zdow)^6Zrp*D`?n{y}a*s_gZ7XrP66iSPj3`aLwW6uU95(uJ*kOkNKq9#5 zC#!c9D(mhnnK23QBO7(8132Ot14M@X=ENxj=48C)6=8km6%mvI0Eup18xvt(8xPV6 zAl+vsFy4QS+G>TLdSeAU%;|tCtm*)4es&frE8;Gh(cmeY(bJGRa0t|00(C(^-3Oqq z6BO?T#SyFm6U$}-6RSYY8luI#yopFf zYJ2mehXAiwwG6~*fcS;*OxK}DP@SupiSv}VnTZWi^2@C$fKR2dZ=S3Z9G>ecqJ5v=wwVmpOW`%F_d4E5;7xAwvd!r1q^g`m(@dhxsoO)!B0;q8_QCOf zt9HYUDXs%lNdpY7;%q5H;Uu5-L$T#>wZ)qFE}>D@l{+FZXUMNY9Z_bi?e1rZOg3xh{# z;x{9M-R$cowaYla`4c&A1nG1@e5FjaSSH{Od=7!OsY ziB)o}ovA`D{>tuSrZIr(%PdRoTG;Q_4EBi*QD;h51fN+wQ@XxM-IYTK?fV*ji*{sg z{0_}4sD6-T(0Wjdt=Q(?!7rSdURd9VDvb{fG^IF25Dh}G|5V({4Sx75yWL8{3av=W zv+<$=9Y+0I`pg0oN|+aP2+HUVS#RVhZ`DK{N*Ea&echU}d1{uPOZ#4sVK=t$q5e zfMp4H+aS(JYn>SK`P|G}&Ur8nJ>eqJuBLRSzu&t-Tq?pvVgl-}+ph(prP$2bf+Gi> z-b_nP6P1#c4i4~pr;ZN;ht@9w(JB= zH*!SeojEg%mGzW}XA|)iC)}-=dS!_8zMEFOl-M_t{Q+uWRL1Z{(y&BHO}eh`g}r+< zvOFMT?qOkT6*Gnagz(FIk`V;4ypPDWB8Y3DAME8K^?SW{pU~hs8D$2WtHlJh#EsET z`!!yU!zN!jn++Ol#wWstp37Igw_+<_=WrS!S+a_ir#W1Jb>8Ivp-d(rl~N~$*4X5J zmb0~GxYy^CwKMZFzs!Rzrt}fOq2I6l0v|6DiCGb>b-M-KTX!{dcfo?f1qSQ+SDfZK z5@|eQy;2gUO1mDxsp4<%b9EcfI=vGSLDUq{0Q*|d(<4N_K?ca*YhL@J6K9+VFeN?SU6I$^I_hOkz)!(AqtyPF} z?3Mg0z;6Ja@c(*}+^X+J%v%)A6?PHs@ThB&7H~J~)>tQhXU4QV z;@W@y-X7^R6(;3LLul$Qci*y2w%C>>EYP93(`-&!jG#!22thF)6H-T4bUrvGnbHCG z0e6+Jip{0)nQL}pdNO^mA_|8>e`1nRUtNy1D@ekXVp<2>4G`lNpPAAfgs<4pH*WM($D+o=eCz?bFrWR z3#<0_4b20+??HU?+9s#cSl7frtmOAkKzxwuELKNpq+lih}k z`{z}bG9^e%_5|kTKmjxe#Fe(MFbUepV{)T{&gI}0JDTOE@e$`-%mRTqUgDfvP+$rK ztg@oba>jW{tX@DdBOoRR3Jiik8x-gVfuB&IhnKi=$&JFNwPkww&~>%(yKAsW3hzXv z?(U>4>eC|wBunZ}U$a(q&VFRwrIS|%m~C1^mp2AAyubDi3%0706k@x~cNRCNOLW{* zC)RrFJ-_gq@Qtj;-4;NiP!2y6E$YI5CX)Ej=UG14<{#h;QMo~?WtWEg`u!-;Rf>%r z6D>ONy5Suf%MJs1QOeTj*M-4Pxh%QaB?(7}%PD-mX|T=eJN1;!CI$sFU6{SZu9RRj zk=)^PH>?q3WRlV$lH0l`G9!~fGh>OuA23gT%C$RkdqsF9=&_J*kDL>9AyNm-_Y$j; z1#jub2J`io#VqJQZuHSLa7cT5v-fu9qv!Qn-_4WH5~fz)l+)Gs?n!d-w-wX-;yvu2m|2k6i0evM1mYWcMNj0tS!(%a54d z^tSrK@8$_lFRaROdXO=Mo?e|^eaaI-ZOR?DYRq2>29|H;=uDO;(xGl?SS z3Vkb&{UnVz(Q$XqIn?PkJR4)b8oYEB33}l<&jlIx#_boj{u_@q(VO$x-TV&YS-Z3p za9M%)7IrcIX_Pi)2z~QhtlKilPXrNd@3Up6OGa|2it(B4b!sAV?`w-_&rdb~_h4WY1;$q0AY zBzzcLV@Je|<2aKe3_^t53!a@>!p+7*FMNn8Ba?Q5UbEb$CTZfoZ0TQPhsXWfbJGfE zs;IY<@VhN@&E2HEQ?CQQS#J%*8mrHW$ zi1Dr9F*ROPR0Ri5$n~PO?R1f%5dJS@zvLK=$P8UrOOqgZ0YXP z3mz~Y*kDJoYr*U&JHc`Anx#8<=|R}Mg69G|1q6)3C-v9`9;FT>G&;Qdp*W_uH0o1{en?`JCG&}^%;Ea} z#t3p5_h=5oI!IlInOa@l8{yP@6^4;gO3@fuF7$AgI<{QqOmuzWZL;<;ddlz3u;-#S zn9lc3W)q0{#D8!9=w?)P(XnV!4JOvwl?!v!>d6j5EV=!wi>icRk2%XiHy)%R17CtE6BqraZw^|lRS7tuIG_}jpZ zc+qj9R^Ug5jl0d$3_TODP~V%*q2utZU{za!IEZX7`Ud`158}3~ zD{S@C43pxpz(irn0bX9ToHkRa#Whg=HP4TPp~`Vt7w@q0JNQL}INgUZFjdI&`3fs) zu25ikIE`T0-5ETZtk0FuxcNh*kq7F#Za&`*rVy!(b?j>#?rno0JNn5rj=@YBiY{s@&~l`DA}@ zN8N9)XJc~mIFyxg(P}!V?AyIMlkf?d>tr_d%4HU}F(0g!Go-u4()^CLVo_7{n39o$ zv}dDn#pq?)`sx}lOnXfYnHw3m!oA}9sq4?pf4!_f!gD(!38<~AKiVGfPFU;X$2b^| zO~XXGKMVN2)7v#%w!HSk`9peWWSi7yZ{i!)neT<71k!NG6Bn$z-*?es1z(h4*j(7S z2g^8Pp*>{@D@wy7NL&OgZ*Q_!ycY@_q7>Ftd*$IWva4X7sUj3rN%>p@JeS8_3Vx#5 z{l2av+{C<1e|ljoK)t&^?^iVU0*v>9o(CV2;`4&$JcYlW+~uv8YzFg;f$3^r*vUs{ zK_IM%-KAe7P~h{6K1Cz}_%y*9EFc^MbLmV{SXfSH+Bo-EbDnOrIda0XS7_^8J&_Z( zj~H*168;|j_t`!nm*6yZH3nvR``o!J!f|&bUg)kBq^smuSo3Qrcjj7Hb80B7OvSr+*3opCrE?9+ADosZAJcu-j`AzOADHd`$Yj#Aa zobpmu)~HZ9O~NP3F`;sb>z*nI3+uz0Pu|b#kD4F3u}(xpt*ui`C`LgX5! zm33-{)7v}vACV{RGEJ;9$NMJ_@fi_eNdlkuyKJ#l_jA5v&a@Vte9d5(I@yofh^jqV zo9)7cNPh7|Em*`S7b48^tg2|G?TwvCWq>7sGAcwxEeLJ7 zhp;F_+4oy4tdmN=U|H?^&jEf0&)P3aZ)GM~kL`$;?@#|^Hu+p%FiBnS<#V$0dC`2DLX^Z79G z$mAb3n1;ayd|Yo%%)z zd6p8TltrBQmD^GM`2m-F@|PT%8PQ@>jt=z;G5OpJ8(e|up;?QBqeQbexpdU~?s9N* zO0YUo<8nIE;{%cF!fShR;@MyTI>>#8inbLSVvnn%{qjqdYD>g248IHLrZU+Tn-{ z&-<>6#~;JgfLX%g`X8Pr%jmkuA{VbF6)ceC4mTEEC;$9(n!;tIMPZ>d6ucxwx%59oqj!8&0sg3gh0f0*dR#J*9<_Cr=N`@wL=*YEY z*3IT=h^-TN#z_GI7CHQA`LBQ|LF7xAo!GjMOHHU!ACVtVImo)u@i|0n9nOfOa3y$J zc2Keh2%}+C(_BRF6p7w(5fO3-+5Yc7CD@)^-?ILu+~(m^kZ4hxOYGJoboQLZbj7C7?V`HY-(9j$yv8zoZ_`D zY`(VBHCYEX+iP*w?S?H?rdfa0v^#pXZa2mXE2qh*fZN`*=9Dv}kg&&$(UbFiJ~yI4 z0K)7p6FU|QwaX!W9%E4%o0Y8c^R}`tzK!`3q*NWz0R{?}6vv?SE|9=0&mO55e=E49 zr2^-(3&#&`1Xla zp#oVcEYSZIVAE8Fo-aXUx4);7^@bS8weWSWyc|#=cnBdsx)Ve&iY9t2NzP#%mh{P1 z{$)Dz%7QJc{C}=ymE7$9MQVf;F1D&K(+5N4NyEC>-j$JTe!gyxVO=@#+>K*RSZeA? zv%|gax-|6#Z>7qwjp^iFaa?PcgHm1na)=wI67h68kF^igQS6$uN044YP{?J?DbGka z`l|2YdB4i2uhvgAS)yD!X!t=@JgYdM>JfmdM*ylGJE(e`pz4JHX0r57xwm|u?WQTp zIjEfIf{pqfpD(u0^1Oev6*eB3MyI4#H1mtL%F7+czl(+ird76c-(jQy2VLr?)bJ2P z>fg1(j1}J_`N^Ful_IJKU0N@5z8{bDWxbWdh%w-*zSZ#1ejFT`xFmoW*T(@T6Fqbrmtd81GXrr!v3{huxPW8DNsL^r?*xWl8+&Zc>}1ztYcqrJw$aO~{0t zPOwQ}eC0g`{W$`!;TbK7|JxhXk9oKSvd|&+gJerVD4@#8Ak$ADZFz2}oyBy>R8JXQe2QL)qlw?v56cy%;xV zvE9H>$Qg#xr%)&Kivtpy&>z;lz-5(OCMLfi?!_5M%JCc?Dxay$elML|R;7D^JAl4! z6pz?qVK#zD!6sC`mgZ6mBOnx)S^!Ml+k}1^D(Tq?@1T6{6g~erap0J zc!u+$^;H6i`AD|%agLs09gs)Yyil;KVG+6f{IuY?<-hvM%W3W865z9DRf6z~NJC0; zxptMz*Kam(sVRZ0Wk^G-rTl|Z_?FKV3uEKH$*fm>s3t~FiB@p;$hpPqasFwZ(Qoj> zg84)WHGJgoWwHk)!sU}Ox5+)@Y6&av2)P$KHxVh|bF?*Pf?+QDr9$6AjKGWT`x~t; zRO|k_Bfae99AD=3%iE|mo!VZ?JAJ3qQto8nB)a_Aq9dHk{#;`JRAj1f`-^Wknf~La zSV4NrmVQ+tdhL!lg*K{Eu4uXES$tPNkY{sQX&ac`dUzqSD7>Nn?b}P11!}ESr6jLl z)S1aQ*-b2O2@1{dIc~jS!e^G|YJc$WcO|XToe(pVPG1po-Sc*2P~?|WnTi|iW9bAM z?4tx!nT0Lkm$Rc1!TT}>@5@F|^W}eY;?xJR)88klWReRLQklQG$(~1!rTwy>QaDE* z-WT4c%rs6H@Sc(P-ph=uFRy(bO7?L*S(}fV6tZASy|a@!t;l>Jz|WyPXd=V!UQslD zqILOZLQKxoquAp3horL8`<1S-VFfngMPqo+*-;zUun;!kZtKkcOJy3cl|(!JFLhWe z$vW5$$op%hH0Zbxf(A8eC5q`dZsjz_izvGXP0KXe0?%Oxo_cH;m^PAMD+)1lkcI~> zvEN78H4^>)=^#r=x;ul$J)JU&H^Uts1+d6}!@`1Q7~SH`{)~>Yky>{bwyGVQw#jww zl42V@Ut)iPvb#6q8g?-k7pti8=(>RsS^u=>OH!nQ3%0a-z<6zgT{bp8m;8Wf(h#t!5`9hVK)u**OGS%*qD^K?K#OJo z`Duhh;4r`K^5Qw-7aX_5PZ`Uw;#kx_DN-GV385-fo22!zBO2mSCR6>OTWElfSVDdX z+$w2#JedE?zreBPa>N*at2Ol+^J|XsCxa3V6$qBNHNN~1s+3m1W%b~Xs?Gw`c!-0W9bj=!ZX)*bim`S^=Smsj$1Kg6Q%^4ZzydiZHOWR$P+ z>t)5soG~1QCnq-b9-nv{FHHA(Ipj5H!w^(v*k(K~y@A^qd|~)n0bVpuNfq^_5I;;f z(3+lv{!#en)f=+cC}HuRRpGyJ^Aou86L9mdv#3a6;RmeWZso#`4Dpos^2LGjLuQ;I zwi%a(B7Y^k!N9E6;0d9Bo~9~|_s8z~l)nEJcIR;C(_3gEUkA*<`F_6~P1=1xzdWi=}>jG(= zw?H}{NGINAx${;VNGk$qA|4=}8iTJj_l9rpzFKEcp80K{L^goA48drYnw7qe!8!lz z4Um2hq0;F$W0@8s%8W)n51=1TTKpL#F)?U8=if|Vw;R2N4X~jRDecfV6}P zD1r)5;_U^poL3is61O0j7y!fG8Q6)fLVD+i5|EaH%*W|*h2;Ue%^BeZM28O2B>EhJ zWb|n6n5@3WZ!ePGwH`hbE=^h!)%8=bYS@sLFQBH`apO_F;f(7N_h!+fi77oP%=kfL zEJNYeXfD@U?Tb|rAH=bh?NMtzqQ=j?{dn|O=A%XAi#eo#(5h`C0eK{B>c8DI(G+Y< zSWVDP9xjC)%z5KFbbINqcQRw!8tkyT*`KVnj!&*mey1p#TP>{K$6Q0X{)*3vuX*32*i%DX@cil0?zasF z7tG~Ho+q5C*{jTRp@ci<+~08`+?#p~NS{8FxvYlzDm_ddMMh&}WsHUX9z%qcJ0dYm z9iOUAa9wREL)s1B_19W$P=mnpQ0w0D03T0Bb@Jij2ONrCD=f*QI%aK~HVMl8sWtey zo10iTeB_o7eEyiEuBHE5wC zcDHAFreF1Znw&MWE(Rth_)?IcJD~B#GAm`r+7iskHmZ!}ga(I|sp<=<_^- z6xO&VXP$PK>E(`x@el6zJ@g74d*gAxPbW7w%|-(^I~#D!~i6c1IsK*12AcVh!rczK#EX+spo%ZA5M`XCMHOh}I3#$?Y!?t=|HK z%W6y4{1&&P%PKr_KHZ$Nzcw^}H@L^Sh?s36+{*#{f2x69l@Qkc@dBI) zSIIAzNfF*~B4DBMQgax`J$Z~}zA_5!Xy=tYCKK3Rz3ga*AplVz#Q8rZ9xHvb^?P=* z%X-{9Zfbhc5byuXVRP3uw^`e(LV!&nA#L6~pX>5Op6~wQLoJVNNk!wdc}*TH_mnLk z=ht!gN`%*^(aYI^0r9QJp`rxW2d~kcdumQYBot?bUqnsvD0-RXX_t!=?4#2llhD8c zOkf7=u}}QSe8u7Nby!0|yt**n-Bmr}06oDpCcL{Qk>jtnk0kWZ8GT=bx%<>l&>g^y zGR0wt*&h@Rp+8~hn0rbMa%QzL>PihlvKWk+*jzF(%=LWHtHd1e%RG9DYTr4{A{dKv z7AQ&@jXz%mq*dqMz$U?U50))(2(t(9C)#-PJm69@0>9$ngtbPUYwyQ0Ua)(k;KDkq4=Uu_rKhd^|~Z7?lxWFQ9J*Pd>P+2#)f6fDfy@eB}{ENs3b`4OXuG zC7b}AyHlKKDwaNSgk=ClNgmN+K>Pu5`?!U?kf`STPo_ifFGR~$NWV_|EH*+kAc8j*Z3bcL>k z_*1z5O!?b*9JF?U&;t_&9T_ROzm6_0_7GxSvk=d^)_P-K5SE;n`}o{bN1ZGK5)JD9 zseI)M2C#9k!QI5Xmfr2xbz&n4ya1lSo7DHxUl9~=P}`WbsoKcRWSd90aP)0A7R>V- zs+0LY)5V1e#1>PObmoIvG|%s40DoGx4)pQp!Y9Ob9m&S}6Wr0K2Kv^{1;Md;v30sB zb>IQ(fi3PrHP>J!()OW3Ff);dZz zW~H{$dBak*#e*sI_xbM9ot;S!1JALXoa#l-!6$Ve)Cbvlx3(0W*N#4u>CGWGX1Ttl zc6<@|*&&)cz~&@y|3!y*8eVjd>m_WC`Iv{nQuCe+!BR^i_na^|`c9;cH!RC=$H0aa z5U80m0|I#g9hW!LuQ(M!fo<5tBf(GT+Uy75r;D3!%$Cf7z-w#H+vOCvqXe-Hfe$F} zJBU+d?8?68D&UvLkKP>dd-)M}RQb`R8@6!HzFQJE15C=^-tQxv@oNwP#zjTW)qfQsK3KeaNbAR6PKoU+8Jrn2gyu(ovC*t)We06DK zooK=9N=k9bu-BEe;)K`5Gu{nNW~0jZd>6a%-;NORu$7K5FyFA`?R!y*ZF`Bk?}Zbk zt$QdgP`Rw3X0Vpo@_C0`W&~URtvA-3MCBRWprmrdeSrqRVkzaYIzyWP(eL+&H5f+; z$}=KvFy=M0TQ|B4V^^e~cXyMp#qxA}lJfFNvue4}=|ypY<{TyQtpK<9%20xlJJ_~a zoV4kpnhLix7_(V9Z?;)n-S5M-ma~9Qq}(<3pQsb@Y~i!!`xqgrxCVZ*E&tPb{%XS@LP93)Bae zf}hNQ$iJRv|1wMeMe5J9qJNh+NRNP?83RN|f$&pYny0ZuKBd4WNq?7zvh1a_y#{g> zSLPcASL2VjEsPVXTWNV!_Zv-Vx`)IcM1%hN4YJ=E74Li-~?fnwSFr+&x z5Yun2(S*~>`j3(RD)DI{x&EUa|6=);hr+-9G4Hl)0Qc-pX>6tMZlJYx`5IDPixT@e5W{j%e7m0r?=H) zsjKcM%6Mcb{>XC^9q6N*SKZS^eQ(lBk<9z~-l3Q3t6`09#7R5k3=+HQ&KZOstpo|u zZFHa`Abz>o=tf3*sYrmr8PpCES6RQIrJ?`TVnXn97&j7i=$4y5&-!hjo3LheRbW|e zHrTLc9g0!Hl*CDmhE&Y<%lzgxt`QmyS?+l6b6@qpGKg4;oN;~RirRU=?@>->)A`@{ z4nOQX=#`O?s+D=nVuezSou_J|*+cG_d(M0JEivc^Msv|Yx4qp?%7#ywN|uCuTHYrt z`qnvh>NO)uQu0FPPy~h~Y zM|IagpK;Do_y^oMee8v>se2H}1|QZQ|Hk{Tl>Vl%Q5}Eo=|WZ>aj=SXDOH%S+U+v9 zd)5@iS&mmq;Y=Qugty}S*`xRxJ1E2Xz)y2Q`muGY#i94dnaI=1KG9DHW_wl zDf!4Po*kK*qbtvcvwca-Lzs;GhuPN=Pl8ltC3mz z%8Aai(brg2oFk=TesVtk7OnK%`$CWShH_$5mbem&%4YPn`3}ylr0MmKXmdtDliT&%<(C%H;d;y-Y!n0 z8_SgQx^s!OgRAYuYgG(Su#x#wg6fuGa;MNw?6Z^>3LwE%A=TRHvFRL)IF61{UO-4R zSSohZ>{J5hvD}M45-=xQQ{2}!;Uw(wJ30jVgyr|jrU~?k`R(BrVFE&06NnH+j5~wf$E4q8W8QQhyv|Iz+eFg$r&kZ z34~MzL#8dr(rdV84Ct21bqeseGGNUzSm1PsK!t-e`=kHg7}%jM7vyBgeMSU7rN`fQ zpmBGDatEWpUp~hNAyI!Li>IJqwKZ+SgIx3j2)c2N<#ee|g8nSC|q z_b8xJ=;!o{!}CwgL=sb2c}sn7_k1%9@!MS+2VL5Vy;0X^3Io=R?bDm^20>v|pM(+% z^bG1uxs3eMIgj8WC2OC5-HyVg46K9eg-hL*%*s~W)$0{kFg-TA&(Q59rC zRINhgy}!Zuh0d)s_cC_bkNGI7MrDd{Dl9dY%Yo4x=#IT5>nws}9ZmSjMqx>NV?mnd zE137jDObsCGzZ;f>_{n1IHzJmw9+fHEQ0GBr_xG)q&XGWqH+m9E8X)AkNU!Of(eg0 z?l}tGpC3GoyK*8bGb;E~?0AspZQcIvzlT9 z-wQV4BYJJKg3X3RDK5m?e57SV-WR-4B>W!BDdO|9&gGT`f$Ael#f~{uD)xBCeuC;d zVYfOS-gk*d?aiJXyZfE&93?HC#H&y6_`HjB9#>tx=KN{1^;a2sKzZW$M{E^muxV!m zrq+8m+Aq7c%X24svVZvD8_aP3VTV(i6X_lPGTO+ed+5cHcz5fC6~{HK7o`Gz47$g6?y z|8hc4k<}t@rlFuz5Qs+&DZ6yq{w?NTN&gN!#T~T<#e{kQ$SA;UXFf6n{SUu}Ayl9m z(&Ft|vGj@0ighbJ0xCi!HgP2=0@Mkd!HCx0WGp+qfL8;|MRl6MRrQzkA#*`xBjy{1 zih2t;L_pCqZ6szz->-qQbSF-HlCzjP5$89qtBl07t9*@ljnY6&3r2-y=Ee zP$m9BcOb9MWy|#CvyVo7r!xp)G7fJC*He z#>o=3zSmAlSuH~&FQZ4GADcRQ-RVc~} z9!Ge(W`~}$7Pn+xa7KA|M+vjyD9y1%N6AIW9DB`LXxN5(cgw~_?a!0c%fH_zniz@K zVl?YEZl1IfXANpYan%&RiNdOroU=$zsq@~W{!;99Qw9$>3amIjNzy#5K~EG?qp<1^ ze6{!K)@qI@{<>dF6zpwJr+G7P(Xi_JSOzcZmlOwJw)mGK9qm_Uqoe5e6QZL6IyhN{ zH-s)!ceWp{Y*(>PNGH!(+>w&5`gH9T!@Q_36=33~^T3Xi+JMUrNnw46aI~9Y?LL2~ z{LS{#nq9b5BfI*QZ?@&YA`{glQc(E!27Cr}D~X$KUUXEd@p@JNPr|n92nZ#R)MJ+L zR;oW|lvHEKd576k$8_6~~$RaF)RQ-ckTiIME2`|3*kM2>B`1G%Jyk;HfqXpio&=xM}Ff#}>%qoI^Z1F+(a(AHdLKlt78%mdjqq2&QFR8QHgV8N#iOxcX_Q~D z&*XclYnggds4)UVb^CyB^mkccmpN&2jn5rY7$eiunZys8;LsFw(IMUrc^Jd|V;E-aBvGSWv#RV|vgUU)B3at9VgEc_U2Ft@n`*tuuPVdk8j+ zMjv?NHEi#HtO0>r4Mg?R5DD}$O6w&+NTp%^B%kx|+N8&dpBIL=*(>_U-~i!U4P`JX z)dnnlP|Xc(u8 z@g_W3O7I4{RPJU2!?R!7{F!LO2O2uF=Fy6q1n%2Xvm`N36dUxk@~In*B;sG)5J$IQ0E25&R>JOJT7zuIT{S91`8$XByVO7`yh$e-+Y`_>)04~T_zb;t0G0{BS~$jw z(&#EiR&H>&IGZ^8$sgu0SQ@V_KDt9%9#Q#uW)OMvH*Jlzjq^Se;-(=#R1Iz!VmU-q zjtYPP1yl_n0;+*EFSbDckPO0#5lY5JQ`#yvaE%fLtQ+2YUkC%j6l;92UP_0CMv+k> zf17e@Sp2DoE>y?4Mo00H{>-od@J2&twmLN)P&&nw!yXl?=~+30|sgEmzK~4-Ps{2l$0% z6eAez8SO%=U9KTim3TE2%Mm=8=Ra^nRKj(pxY{(!=w<;S<~P~Rrh z&Y&uKzZW>X0QqrlbBi73)5iYld%>@c8ZcrP{EW*|I4l@TcN z=>w09$IgaLJ(J9%tKr9MN?fQUJ`;(hq1f2%C#m)}VnMyn_}e2!&@eG8uiffOZL&0{ z`pySKB^LzB#SJk@3^B$e(lEJ8^T zeg_kq_GMD_tm%z7UlfwS6UkPic(#gX+mgCL#BfY7*v3INk_M?zj$p}b-X{N-YRQ{m zXHDDDb-VzUz#C-HW|T$tIf*MZ6?vro1sbw;!ptze_ny}0nPJFuPwP!47&6ntfLMBjr9LO9f3`)c{(lqG#fjB9!-U`=9G5B$h{=5OODeJN~-olESBH2CHm zL_6F={5$TDWWz#aUN{;iMzBQ=_k0N!@feX^E)Ez`16yY_4RAIs3LRwc>XY0dGnnyI zRsnPr?WrtI(rq_-x&~?ptbuyd58DRopb}0m0_+;xfN_qMc8O`<*_EoEA#5IwbfpjsqL!6=*thI6hvl9 zFYg*^bw2|$%6kTun1wM4d1`BO1D- zYqts?->enYxrAd>??CO!I`s9?L$;M#6Tw+p&u?5sFtLxwus!4&(!DlX)3oS=w_)Rxv-W+??HBx-i>jEe!4RMhv-LGE+J{}lvg>}k=u@P&S~c;j zao&UfiCDqf{Ad1M2KG|a0t7ILAgj7?LIw}Dpp*MyBlJ$i+p@|ED;-94MWa8A_ObE#*+2_VnT$ToJ3N5Ht%SrQ4hG(3PM^9C6OQi1>Kk~74vgJ4B+2!nNM(mw#P zaX2H6HG|-3$w9VA(F%qn-U1c!5(w=+ZR<-leANxJ15Pc~J1o>ojN@NG{2*O#%JTz6 zW?Ty(Ikc})ST_vXXal0aid&;WU`E{|$~J=4=VtlJY+2^9$}yo1!a zCtVI9fYuC&DlQKJZljO`M?*_IhdR(>rH5#OkSZtuly4QJ%UJ~2F%{N*fHL@7>K}Ff z#l&9}0wpt_k-7#u6SJzn(EcBoXy}oa`L2;*U-L*UO4^NP;Q`G8``OEeO#6TIy7Z%x z!n#w(>yOqPc3;R|D{gMxGmg-|Z%(^u5LUwPzAb#r=KU%SH9`Bc zQis2*#UB_*%K1(cvpH}bVeeCPe(^*!36C0vn_*kTgpM;3Z{V+X@@IrsUIN6>Y0jr8 z$*E2yZ3!&O6u~ERcnd919AuJe;1_oX$!lO6ndb)(Tyl`U{#UQ2>x6+-&F)}2<<-DDk?38OkwU2+&7BLl~>I^@l*GF4{#vk+H1s`np9*O<|s$Ikq3la6C z1KWXh@HH-4CZC=7w2lJxB#g*J^ho~}|1Vjel^KRo7)t3s$o`Ax6d$(o{tx3XXIA82 z`2Q=O|DuR$6lVC3p8v-AJ5S^bz8a%_>yE1orQt95-m`Z_N-~uGcA5jB)5ybe#?o4Z z*U408SIw?0%4cr}gQ*{{n=AVn*^$^@@vKvqeaUIad*UR_^mpmly8E-ac<)bLc4GC3 zQ#p~O;RbG~Ym;VrBi)WVD{EK|1L=0ej;c!d{sqqSxc*5JANrn*JFBgD<2Y#HQyUa| z*)bGLD4?z}($DO-u`|MZj4>)q`eRojXVcvQftqub%#<;(bcdG-j z&_$-RcPg4wYZmq7b~AK+k`IJTw;hdY3Jw-9-ixpOrB$B{;y3W?u)?aeePAffZ7c`X ze@ARp+kMqfk`dGK`F$0a3E}|DZUG7m_!WhKobp4>35Y?>36MX{=?_i>=ZZ_%p@jlNY(PJ#W!Il=TR5j5%d>%iK6nTcf*gIQR1@1Sauz~^8Sn)W#s6#Lq0e{ zNR}95q{YKiQ;i3!w3I8*r8cZB^5t6tFIU`Xp zsoByQAzkIIx;?qMZAgU1^FGn2&xWlqup9dtrWw{}AM7FvDKxtU7ptg156uFR!97f- zuPT;NkgOZ@Sh44v3q6LMJ%WC|2fP)DESC|kr$1;&a$ z{l-h+GNQe{K*E8m`=0Vx=qE;Gkg&*^Fz;S!G2k!y!()<;FW9Fb4)OqN!M_4M5i&)G!EfY91 z2P)Ht@lmKSz=?!({<$4i_f>5%~MSBc0JVKLlX)rcU)Widf2kaPg1|kaqlbRgmo@P*IQtmd=*U z|6`Z+jHi4?Zy`6;0SaOSUIJv~LBu%phJc3+y%cCrhDu-UyAtNcI_Zn>>Y?fDp|udO zGrd8}okn)?DY41XZ@)vcKm*y=ag3x61AEdh3v!t>mYlb5G70@e@ZkS|6*Yw^Ep^=Y zFIYD>H^yFpAqie}`JKaEImwdWN-SS=?yNLm5}QV!fbhv7QW0G7s#~?6_5CjgY@COiEb-@NEF!;C3P%$5|5ZaQLUl_)U z_z3(%jfk-bD0|gXJhbL=)^%W=8;}~LNSrgk@qYkvVt0k|158;V zKOU0~G!H!{{jRWhE#%jOr7YM;k2T89Fju?-+WX+XbPfL(`?JL6EwiB>v=a%&O%=mY zV8gha6+f}#$5PZdZp~ddhj@I~*tb5#8QGxRKO!#Hvy;TOvY4d!XdX42L@}Ks;E6X~ z^rhNm0t+GJHoxS&yqMJGRo1I!y!Gnax9Yrt*Dnxx#91K-hVMA0mJUWWyjM$(Y%Z0Z zH$JJ_KOBRtB>OQoq?8SvPBi!vp>e4fX4h|-mSn{pcQkt$$)$$((oh0?dIV#zD>#(l zv+M5#C)Ig;e<%|59h~7XI!c(;#h=0ocHx8L8_tGeC_YZW^B+^vicN(yL&-lvao@;J zhXf!74GAFnbVvXhKtlqM{^yWT1&rHrG%S|FEewK7PGlN`zP>))Jee56xqTLyTI|L5kLb|*-+yJ8omkRa_)o2xCfc$JFaEZ5hXDV^ zc&70`B0K}eZ-dMsjsN~>p#lQMWjs?_6DSE84-m+BfI!9r1Tr2l!+&~>2;K8L)u$)` z8JfL81avu2(LhUwiUxX|0zxm8k=kBTjlJm!a>>40zRBUw4`h-+VuTRQ0}LKo*HTOzW98pPw(S6GoNF_;FC*-xYm_63|9FuRpI{tl{-u>F(T zCD>3`hrrPzpGXO+!aJ6nyY7R^tTc;-N=7Lmh>!{@E1Zz0d105rPGtqhC~PU?;w~06 ze#T<{=3{jF0N3E(eP0X;AK}}ytQ&(NfCf-NsxAO2P_-ecY0#hgoX%_^0wyznND^;p z#9)ABe_tH7c{3~1#NT-&0}0uwfm}grgK`CfIV2DDe-I4l{~#FYAG0!Go7i8IY$sMQ zSO4o9)l$a4AV60Okia+&A^k5j0f(i`g1l33Jv%ymf`PNsRSk%vtN@r|89D>?=65Kd zhUNsyHRH+)62Vvw5`)2~s5dB?CU6+d*`_z~swjs?s3=uC)+wM2G~FLmh#gyX8bir6 z=zL(U0(j8;8W5-!L*!mf1t3en3j+C^P4_zhupyZFLAly>F5{q*$CMCURg?2^0HqLc zCpiPdf@vXSm_OPmwAFTsE6}z|dFUvO{iWxIK5aRz?$EKblH}8r8+MOeuAqJpT8eE3&g7#Sanbpx9xQau zT{fcWMeinNblf*dnA=gpNKereLey;v25!zU#8Nw=X{Gr!AkdTxkU#xAKMp!Bkinl3 z*ELL>ZESw1hz4Hu(P!vsk?+ZRh}-X?C(l33G<=*JT)+8fRm&#oBjQBQx1Kjid;3+> zas2VItKOg;r??$M;2fL4;I*WwA*XIFfs>uIsg!M=F;kzft;->h`0Z1!V z&UPuM?$aCGZ8kwE(&NvqxBA~HobBGi@|PF-n7o=0~F9$;1;H+Dx2um{=uGT}sGJ5c%e1PAq8z~aTa zuhL)u8{$Tfk8&+6%dM1(rlWLPzK%PPY|eb_rG0vUrmv@X+~hwb*&1u(^C3d|GwpAr zmTNo)qj#xa}2?Pk^VV_!XiwAl*Bo%^9JZ+fBRhy^&aZiYs54%j$Jd z7K%3i726e)*K~r@0{<6rZvswL)b{^7<}p+f8A8fDCNl{sW2T5hB4j?uJP(n%WFAW) zgbMBIlJXQ7&XpJCrTZn_<8A%wxX*dZ8^I0W;5{2Y9l10w5 zx2CSw8FmB)@G*j}z3C}f2uhXdFhT_DzC8OVY2AsHT*$a1_z_>a@FOs1nB6F#JEL>) zU3eT>6VsMBEnyxjdy_z7PrE?B`x%#oG>Ra&M0S&juKQmm_;45dI9Wn2@n`X+3z=d- zf@Uy3$tkE$qdd#vf}>y9;*Ft6qEyyE}UB5`RsK!pO4+~l{oH&kJDew zJ9a!2zem$K>c6Pp?Q!-pPDZBfx!2T)_h$Sxn2&*S(=8IarDW>D1%g%CZw7{gjEfcX zFyHM`4Ja1$i_hT7jQ0&&tI`;d>Aak~Z~d! zLQD5bROdIsp6#jOhYVK17LGk-?{?AA?Vf2Ubqvy05 z4@)Pvn@U2LOl3azWaZ&VMqFiEW=J6~*?hv)3LKXuV{)>Vc~VHrfTIUEZUP7E3UHJI z#~^T+Km_Ed1dboT;SUj5;HUzQIpBCL8FBS379_0!4lHn>AYwJN>^_~^vmcBRIi{H#@pmIh=3el0dWfu zRMLRh0**f5PzDYG;Fy9O{lK9G9QPn%8#o4m!vHuC5CJ)cK~GJ4-?YDgh#lY<1%x#q zK0*ZKKm&&paD0V`UEufu9G<|j1`&`00~~?CK_wG$)$AAeaZUk8IB*Ea0OA)QW`H9W zIPL+5=^k**0Y?gOARq#A`~;3H;CKNM`@pdX9QnZUQ6}Q*^gc+s3>>Av@f9Kt0D%RL zYT#IdazKtX;h!2AK8MqcwBOxm88yuI!IPJV-I&O_-U2$*uybd+H^JW*U450QU}>m0 zS#jj}E`92QqA_go!N{f^Z#~PXV`7oB?|8^oRRu#2_#i&B3l4Jev3ALP4%>OKPpTo0 z#FNtb>Uf*WMUo@cD^pu;-pCy_u;MiD*^}SN zJFWn;7aO5nt?~$_ZRBOE-A4;Gl3@m^jd4U{)@~uqgK1ISY_(MOi&~`P6CgB65BnVe zdkBJ>4>AAg5O$W@7(4*3;Ubq@$-RzqnrYqrv;|;gm*Tfgk(~3{m;KnZjT!W2yRW0N zH;fo6Z5wc~4@zx%MZ}k3h+ZKhFZ%^jazt+*+zY$UcwNrdF=cwx8C3l&Ns6T1dKv`$ zy%NSporivG6QQ+>9wOMaLm4D%M`*OqEu}gR>PY z17IiSBcxq1AwncSw4#n4B?3kc;EK@HD;#B6 z=@BBdvxqh$`isat9OhijzZ|g6y9?C6Ujcio+3SJs)d=~gj)A?``ijV*3VOK_9jY5@ z47GHw5ehaO1=;-%9PPksu;Ck+>wzLRpjiQUGy-YB1`PK=58y#dZz{O)poc98g+>V= z)t~x=#oz5708$OkC%Bs9R6;y>E{Av#`^r(!18CL>q=p{1T+OAi*Z7US)vo!17d%dAG2&G=|m+s7~P$k2$KfzS23S|qR_nIzDe!2qM3j$exhXw zj!7o>H>!`c?@bfln_hU&dMA<=zg49H2Yd`QqoAKCH^u25OEnB!d5AfV#hF8!!U3LAWBL+ibo&Lds~>pu&A#)XxI6i8Clo=8^PG5p z9kzo35#3iDunL9{swzm}(L>`47sBhmE6wCjz;A2K004$2d$*zBpOLW#;q~8xFX7kJ zV0x3c*Z($>8k8j7q2~voWZ(kOQ1Ai}sLTNbDsyNN{w{L>Q3vJf-xXb`Cv>~hLU{Cl z9ex?ULr+&!QU5M9YqQ}%ixq^~eot?n0|M>{o2@+ZND z7B}(GS~?VnPV%2%_E&eeD!&W7HK@b9!modiz#;(7nNNt!eov19`=FEqf$j}JKCWC#Q1aDjk@w@jy(690ndl5U{Q8xa7Lx|DXNZzXIV8CM;90AEFy&E(+O!Cp@5b#V zJKIb4m$PAM!DcMMGZb#GVP8R~9t+_GcjFiC##I0QtY3pMmc?BDh}z6*-pu;1^GrG| zK?W`RYAwfFEyp@^PC8&@WfmQK^vT~F-3(X34>)q=qlC?yvJ$6Jny_JX>MR8i!#%Ss z7`Qrq0NXw+d9(1vdY@^RyZB`FFdl3kZB71RIYy=7?C(<_KgHsrtk1r`rDo{tO2tsZ zao;$yT`e2CkTlO5A^p>%bCfRP{9G05^Ld|*sqH3dJu+FNPc?fH{c+Oo9BKD0!Rp!C z9j>*~ojrPly0A*ZOMVGn{i4U!7rg{ajCbbwE6c~owk=k$`F_dBY?!OFWdE_N_l{6; zo&6`UTQP$uqj3q9C=m;_ecmP!Qjq!AsP|2r7_yVkM5b=N zR>8CNPc>Er8w^VwQDTZ#*$1j9FAdpKdIYCVZGy5bzaW|8P-X1m&qrY9V7#xkJ=#~) ze*esODo_tfkZHOsJGc=4?y~(pY0#F*RXF9syJ7sjR81sPpPZm7rNuZ2Hp2&+Boxlu zIa6aCbWlbBSdzF%Kq}*tjg59q^9SEomb;y^rG#d zKe5~P7DB0Q`+apNn12Pc&p!#u7=T7dQ97LW)5kqAfNTkEB7j4*c4G*3l z&)voguEjUd9zPA1pxujti-TKw)Z+B-Br=J%(;bMVy~qA4E{?O{c?NH!Ier?fqIpcI z7Y)isR}GO)po|r;jOlPRI=(@G)WOq>R@ru#Me3Z~k5(y%j00e}K*laGL>$F_19^F_19?F_7^cVr+rY3o*9l$Z+eC4g}3W zN&K`HqoFw8z(-(EKt?ezjtqcN1dJ8PC>Kbs@U-S%vnUDXD9XBOZsT7n{Ndj#dgvG<;A(z%XYzpaHW zq^vfaGnMstxw`t8Ws}m_k9RLodovd;oBz}A(~+LYZf>Y)ot?*?HkLoe+}FxwPrm8s z&70$|{j#6X%m#~;c1Q9=yQ69aoy?wCO6l#;&&QKpN0X{YlkgJ(gx|&YvgF&8Y`dW^ z_nY*O*V?CpkAuH4ynJ}KV2Ro3~d-CA*Wm2J1=P~zQh`XzPgO-w4FxW3&t8LD(2`VZQ#(^^=w2A zfyit)1186*m~JY;XB<)(+sKD|)Lf>B-9)s7(%?O7XP&xF~WPEif>W_uHNHV@|V02!4zi;9cD@t_r znuoKAb*w1((u2Pm!ha3rZ$uDizp51%py_zr(0|3@jB1O}0|AltR6OmLhdfCsGu;7s zi~JW<)i&l(I(xK#(&QhXHqymu4a~dygCQv&#|&yssG8vK_&a%yHA??a8by=SG+Y9w zY3MGVra2S&=i0i&AdRxX8CBiD5|jM%k$BqKpiw@-G)jjTu;C4N1hmO-2PIoWNDx36 z05S_9L;#Tn2x+63fG!ot5)L830J#DX_D29A0f-uu1wzgPBp*Va0fZ+K_R9PbL(&H_ zfEYnpngDVUARQ1A0+8!aU!W`$0I`FzKnMds79k`QAW~3YAcPViK2VnCivkZWw+6J6 z3IgOgKop?9m;!_vAW=}3W{~9y$if97VE|DDh&hCu14ufQr3D}y08xgJaDeE5?q-{U z?$Q9H5Xu4&rbmzR|40YafDbhA6g&&>>vE{~+Fe7q#b)g!wqs+vI!z*CAG;2n?492p zKa!kych6FtVV;0(Q8-KHpHA`tO8u4!KDVJ0)!Os@$oIX_NrM)iC9^6kg+5w48aF)t z71=j*vNA1Gt!kUh=lXfLJZT-#KewM*VG6I$ltPFZIUi|cXIY0`Q*$XCJ3%k`aS`Ya z+1xAX{o5VnN2R3YcdPb1#)@W<=1gZ$-7$v2OPdPdc_*`i*sTW-{N45)Wx&*p(2Vx-|^KYYyx*&sAWG-jG+qidbYNUryY& z7{fsy{!~ET7`uq6wl(u#!oRU|tzy{OSym!AmF+vR=3C@h@ zHJTKs9esF^#-3Q zm7X|@8jg@m>r^YoFIQhNXce=Y_jk2fszQ5=aaq+DN;5puaQ@XLfpEDsmzdoGOSdYn zm_GMa)hk{p6qXmI#JFNr_+5O|S&}XaZ~m<`_^cv#f*`SPz0aKeGnM)?)ooT{Ww%-* zvvc~a`K`|^Z(a^2!70`dC+IdTo{ykH{77NLIDICD5wXJB13LGz=y2K&*T3s2esQE~ zc4uK;CDf72;FqB5@m5uFHsLzsB$T$7lmKo93^R|#HU)XX{b5t_T2pe22m!baTo(u6 z2Tlx1C%e5JF=v)dLX^X$rXC_Zo&Wlew!ZzXO?+ziQ_{#SLv-c-UZa%$yf#Yt03{ft;f!wlHM@|>wWm>bv1$3>TUR+EBz4&vPiaG`k)7m0eQ;jE~x6JAWZW6f(gLo zf4}|Y{og%))S&a{t^a%UH-dMSTTM*h!N1A&-^~L3jQ{RJ0w$$>!FaF!^yyEQRyH10 z(4|v3ZE!2l`NLt^f#`|L?lIm_@$P=;VisCP|8p14piP&(;m1SC@5d8+<|GL<*u&ah zV|yFjMV0;!vq;Xqkz}PxN0oCb{+BAGs2h3Jc))t}6fjs1GtVsOY%S|8bddEgctO{B zNzX0-OqHhSs(Zl@Jm_xI() zkEq{mz<(nvQxe2bE$$9FPmSjQ4tD!|4=x5xkf!S6!lSxck9p>qAJrreOk7>|1cUTe zFpmuZ@)q_E@V_khy#bcV9cbbHt|6+BAk6H!C=k=JT)JNm>=u;sYJ@9gxvlIgR~bFN z-1gh4I2}@XcTn z-EzVr(ONhowrg;@$5tBKb%TO5RKa%skoBg0GY{2R+7iD%nfmvPl1tPZyX2^-U)bI` zYgzxLtB0JEefBiflzes4Z*qfGm?OXXAPS~;bDsL$=TfQiz;r6vgwMUw&l$>0o(#+nTj<@!=!ENl( z$kC%3lgv$jJIAC^=kKErCRZCDOxN2D{&GmwQ!}l%yMY{>*L^iy=2?Lpv}s%z?oB831F(z^Cw3ZqeBk}QQuL*; zF489UPG&m$G=%hvffxp`;Nx-xvp9JEx;-f41nOCW5B9$}@`AN>8!xA;5A8@1d5uaS zx3m*HANz7z%RGi5k;`iasWZUVmYvTe&ZoO|$0<2WDYmm;3LtX;VTTY8fV2RF3qsbu zIOYXHStJ4S10b`}0C59IIh2JFAj<$Tg%AmV3<4xOnmm!m2 z%5n)HXpm*+083srrgops72t6KF}Z*G|;^si_Xbf*PwKp7~h;f8QMf0#I~|y-d28Zyt>Sn4<_pw>huDn7L0sR z_1&*kE4yh|f(U|y+U_)yGIg&jIUlmQUvFdXUXQ_iWAMA)CL0J`-xyACu1>o%B$3ZJ z{=J*{@7lOw=rLaIn<*=ivb=bd#cnpVKO(Z(Y9HLbO7F9g_tqPmMH#%S!<6Z6@U%K$ z-uoBqS4h5P!U3}-*UWcHVlj-SnB?qSB+jpgvV9}6yZs6hj=(1%-#_{` zK6P%R)GTDmYdh||Q~T^w0-TJ>A7$q-ES;v6Om{U=bxA{c=c#LGon=g5aHlVAoG-no zH`*`aFl>^L;WIckJmZ{rj8nVK-_rP5XPl2LXFt)&iyMkf#pW1~ahGPV1^ zB){11e{Ss#VdP`f9m2F`2_+$uD|oksF!)js1HfyT-^|JSV^q_4=+No}`e++_g+<`u zhw*Fp33t+ZNMJsi$KadyL^(ZPr(E)Hv{hn%NpD z>8}**r|?TD_yk`HLI8IS^BbX_l!cv?u^lo`)YtoMX2h%(?3t#>s;?hag{>O;7_EV? zKYI|qx+L;E-#166#??)8;@y)fqv`(1oSVse&-1HrzSjt!ELQo?N`FXTMGSnHwO`-A zo^;;hT8E-{nUR8h$ONAS%9D}(Ef4;WA5Da~#Tt0$(+pYIFtvCgD9-|n63QYqdi$hg z*Hy#yl2XNL&2hL#<~;@-8X3|9wbU&32RR?8W*5AE34Kd=l4lpbGIn-ldT*(ha1rmx z<)Kz(MlF^Ox*<2yXre=r8(d_}+KBza937VkTe2?_%1j6; zv}E7GeAZU*jvG(VZE$cxM%nG}$Wbc_$I@?V;jjGP#x^;$hVigATom zR^7<1sm*F9`=M*g3vVMM&UG$VU|yKtCS^!?=titQwTTKCi&bDp84dDtA`-uwlOy@> z>JXw6uW-Tmri2NYl+VWF(5@%rDkCZ4r-5Rf_ zJh+y+UM4;6n&p>p;kqkx7vZZ_2vpV2PECr0BU8Hv7~E z16VP{s7CUYVEYG+FnMj=366jC|8HO8eS8mcLC3$o-v8A9|5v^U zjN-uY&d#cyqTNvD;Ucr8X3Ycq&o|OW_b9_Q_729T3LWE$4Rr@a5hjEQVRrk%uyJe^=9*qa*o_MhnIpmOrWv2z7{=n%$0dtch(-_TLy%9^`1s6FMx5f0 zQ7dWYYyE@^%1CO>Z!YwRT%6tSPclRBciH)G`G=BcoD?fzeNL-2RQlSrXJ=2c_A-3<|JFYT!Ixk{2mKGk@bJ=S)vMtlBYSKI!2|4wH~ zmF&a^mmFi?H{w-0DX~iyqho?q&X3WZd7lP+e8hLYF?-%$ zZnt{gG&@|B5m(MEj$?T6lJr=uk~!HE*;XnWjasRdOM}Prg^jMJcON_P)-qh6Ib7bG z*A2W`+TTM21&(nc?HsK_&Fnoy44EU4Mhj2n5S^)X zO)Dze41tEmT^F(U=$}xbH;h{mW>(H1W<%G+sFE0AW`BReFhuf(_}*=o=C8YVC#&aq zl%-+E9zI&ZUcDC%H}~IBnJm33U47N4ps2eT_Wr%HG+q%Pzyb7#+P$!!IdJH|9MZ6z ztpsE4ZG5q>nkDxaNf0XhKMeA&p>*>s!Ep^$ca_UiQHLDdQO;{pi$u`UM2PkodV(B5 zwAmRr{2-5O_a9#MXEWCA~`7n2usV3;fJ%yIvSxVf0XK6_=2A4qFWM%0owEXRj z=&h*=zw(iwJ7}{88kpoh4~MSceQmTHTzyadlMTpU3H5NF4WYZpe=@zjTd5aSW5o7k z+fhWnhOX>>z2weaAuQpf{^jMW>$D}=qi`N0UE-FHoF+ExS&Y_nm1QVuWUsU`m|1g2 zKmU>!e@Dsf@Zy|sPHm<(_shFY7?dNfXqw}Yg+_{oH|32?GAU;BPsi}`!k0FW^Of=ID#SWA_zf{&4J=w}?M1?L1zTUuF zModyvyqeyIo}E-e7`^;VQq)Q47_y`y^>8}J{Z7p1ZhAJXEp|6!Dx^<89n-^!Z zwKAfIge$e1<%{(zjZ5tD>SLT4DavEC87V4boarcNDb47THSp_Gw|&R^OoDGp^Mmu-dB?fv*`tl5)Opr>Lo6|huczKPH{Lwk ztmd%R@A7l*AUSuca&xxR9|Jn#7BJCfL<)ObQ7Y0~YKsDRF8Pjow$#hd(yr5g^hTpsl*{)(j+!!WG1c?)HoKs+%glWVSHxi% zV(rl3lGMpqi1^j2i5vJbgQ39i+WxvxBJ=c6vg_-5Z{wSJGoPP(`pkqN7!b3~!Zii{ zJ<@4z`qCzE`^zPQqTW7Bkis$jvIkqyyA;+U{`H#(_HXAM<->>qxvTo9DrvUto8wij zo{y0@iB2hJTyN$zPbSwZeaC`*{hX-%We8HU#6FgV!cj?Xkr4hZh7f7i)E4waNgm$T z7WDJBJiNC!^~r5{G-}oCTSN$wmzgq)hQhIC!%i8&evN)g`S$hZ_{b;Ex%a+O>217W zDS9j~4{r|%LB^7)&EV3ed?C0B0962ZK)`DN$N?Y_0C*IR>_i{~Appps47~uz1b{36 zd;xGk?#RANH>Er$+#KI!2{QEJ=xt@dik?UVz!LzQ0GJ0rD*z$^u-5}Jq=O8S0B{As z5&(t(kOKf!C<6qf0YDr8P5_uDM<}+@VZuWIKn`U9HOq}u0Ehy>9spw?LnX*y0rkNG zWPpGa0Ehs<8UWt`kPCp@P#*xW*9AJ63_2+c01E(gk~><};U{%bB@U|iw*fi^&=-VX z8uD0VqL20_cLp>nDfQqMSk2yh4dyo(5wj{5D?&~6m|Ev#qZ5KTp#!^`uAbE|=B~a< zd}W)GPRZ#LFFThHqv00wZZkrX^=yeFdyG~8Bc!=Ih=Nk$QJQQKQIq;b!?oJ5lpu*H z+?~y_Zw;bKgrVq_RNPSR@!J)c1S>Nwl%0nxD@w;N4i~$DuX0A!VXk6cbkkJ&3Nmhc z4gMi?PYwltZeypngITt^qAoT&R7JKvC>;fQXC+n7rZK(8=t1AR`sKU3uTnxZt=QQP`UD`fM_ETjwL=vAHq19m9X}%!fA7Z?(E`)l@6wXgTH! z5nL11<@V?^*`^UOeA6gtwb7e)uIA=n%*z~q6J$8xt3X%&P~mc(@Z`_y@>!~TcXoGW zH@4#+oI<;W|H7HL$Q~co}buH zSHq;pH>R=}sTT8GWjhuOo7jGLV|e2^m|4#gc9mjPLV^719f5P3-e_9u_ zVZx1-P&9?7uX9iFpMUTj@jtlTX*lsTJaZZr`xE9p4TplNJ9uxynA5Q6pYTf5pNqMj zwnm?ZZ~O@to`x+?!^5Xx5nMj-1B$de4ePN@^?A0}`~*LmjN5;HG})Rn7gVNm`5zv+ z@9sOem1aBc%RiDTpC0TJ3-cV`!mE|to0~zCEevbu4I;Zse7&?ZGKc z=v|;zK&^m=J;mV(2X;O<^1$nMpzS~xfGz+faRKdJKzpE^K<@&*3)Bjz70@uCVLxdz3ugXK0o{*!}a{*$BS zopN1Pet3aGh4PHZ5ZBAXvmPzw%8v^ae4GCWc?I<9hcWTrBHh1Z#?FOjN4Q=Nf!4km zG1+G0Q1d`RfJ#UC1v$d8Rk#WT)4`cv5+$NYcgE#wrb8MAj%Nj~FQ}BABi- z^zgWh;ow2(Mto_@!Z1SITjKsFgR2K-c?LzYIPqRppZ)dfFZge2KYESYEBUHrlKVcr zr$<&JpwsIj!H)PyoBuVNR`WeEL;ya>8SzTP|ZgNo^Qk zY)qV$K;8F@{d#O>lXFBOIU|F+vH;~PL4Vk8cU11(zlZ*r8*C*?$Hnn+ie7{6yRS^xP5&m_x7Nv5>Ew^_pAaJ?gP7+@sgd5!+KE}- zPlXe2IlEoz&=bXDIv;Zqcf$our_>T9GpjZ}J!VlO{cEZCe*4!2lSkW&54?|b?}k*A zjpT|G=Gy+;GL`es?h&ApTD>~Y@v)zdFmQf+hMtrm$8hp0*JZJ|TwEAmHigZa93HLp z34gMRX(}HDJbL#ew)!!uJb(;VRHZ@)zl5a1q|`!=PC@r}Tqv|Zy!>#;biRnrK5jOrX zB{iMq4Ifp1pywU7Sdepq$t?w8s-{8x3KpFK5zhWFF9|Mdu2;{)V>{kuWz7kJQDK#; z#k#f7E5q98AARhpVA7cQ&*}7fQ%?<(JV7grhS%E3AT$ZxCfp`S;>m zNdfmg*_dogJSqLbOE%a@<(X?h!T8h+_cV+DX7pbV%vVinE3b0!9U)AmQp7c zgVhUvnm87^sg%fWELqeUesJqdvH72fZ@>@U%!$v{UOv0~HKAh;jt2=<-tJ4*44s>Y z8-5gy&c@rr*O2U;e0v9v$6{ww1kxMi@4k@0m4dgAIW&|!zC(xLA*?b(jLoFj5=yyj zBMf(OaET^mh#ExhD*KPcqAgH%?ctgjG|o?hh5lE%y=VQt?tpJ`OsrfPz?~;GuBNhU z*dDg*l`TGt4XNRt@ZC9__O=b5noC-uffr*42}C)Ng@I!h&P6(^m9q(Y{@W$sS$wwR zxuG%aqW#10X%c%60uyA=J%T9YERFxEnd@Y|syn1~aT^8URw z7L)LXZda4wQ82zh(H(Ooy zP&HQ2{hJHP8td{|6E}9Q#gck%_8-wU&G%$~VU3URd=`w3Cue0>c2pd!`WMv45sUk@ zeI=Pg`c>orqZQ|UKqvfehP7(FN}kRJX!`89r{X8#a7 z$z=U(a%L(o>QW&B+oJQi(a_Dw_^`VEP%manR&M11BlynOFDbLb_6OShCj$m7&eMWJ z+(_dF3aC6}NKnc3_&CXsM#!(Lkd&_B-yg|{<#5Aj>HA;$n5NE`Hmim0vb9`y&K_LH zREFWwNf71HN&P-eDc51B^%eU%FO(?&124t2h=&ye9J>a|lGB6`TO`Y_@vXD*>0yf$0?eQHDbTHHKP z$}R4hqf4|Bv;C40Ua%)B1*VH}V|#I4*f_&Uc7}8(>&}+(P^W>H)9O{J8p-65>hASQ zx#)RVN_B%jlourj=5x;o1Ok*hCN#A{6miuP~!vnYP&tYDQI{j7CJ= z5sCY6V89UBhG*;D4oz}xO^lmgz$3<3K!dAsZCKj z8XdUyG!aT7**ut{q&~pLm->Uw+_U2(bHArRFpya4|JHQk^C%~BleUqK=B!60Q)n_Kydtb)gQD8SBPy4Ma4D} zHT*?$*6Kw5V;&8Byk{DOc>n$D{D1Wa>c{`4|Nk!U|Fe7^&j>iY!RW~wjDoybkzC%p z#r1XfeLePu>rXypem&M5$*$of5@%$$IW8rJzWzXYxIH#CJZa zwWk*LJbeTWj4F4|p-VVu+u#o;Bx9;Nn_@5$tx0KB+0D_D`)7OcMXN&d_NHWJgf50$ z3V*7M(0;?=#u(dmtED)zt_gj(vxS!2xMFFaH)e(e<>$UT99+IWd81}ft@5SgD@$yW zP2@%Fm!$S{qSw8pg0)K95RA-}Rqx`%Lv{M9t9Dt6=7)HL;n7_PP+gYqY?J4U%bsF+ zTGf#}=^F0-lV)jsS<gCQyKj77B(;WJeV39!oS%R#V8y{o_M8qx{9 z#obMMk<+5iT;nr0oQu%!Za7Q&jXBDtzG@CRJY;OUs(jOBbj@ z6Kr9>K%$7K38`0kx?mSyeI~D`U(+p2$D*SyJ6lLwW1P39?_BsK;c;FAO|pf(r(yOF zPbB^Ku9aVv#6`{5oxP5&dUca5u&9a4NZjvTQQ_{d7gdDabei#WjZ=_$wQ*jf&I8%W zOTUVdI`9sk?j4b9atIscK+IqqenTN0NnmO}9Vk-wU5c2@0b{t&cWGv)Sn{&qQdczN zs%5tp8t%3@$bvub>JENrL&U>Auy-^=t{G9AEE!SnNkzkEz1^LtyYK(hu=}NhtMw>( znV00->KP~)Pk0zSLGd~xW*fe&+OjXORwARIC;0zBr!I z>`f2cGxpHiHkv36th6n;DAYLdekWvOP*yhZlX`gLgsIu-WeUDW7-K0R{Flv`cJt_F3E1 zj^KAgah`3e!dvP&sDrI^RB|?CbEWnU?||CSqfJl*qfX4Xkum!YN=D}0mdhUJt88^Q z=?sCJ%UZ^)4Y)0Zw)83&cLz&T-8Py^HL^=`EQ1-6dl-r*&X zQv@_-1dT0Z%yL0VOdXWOqCl&7q0EwA&z$F#CESC}Bk|BGM6i{P<%#wO)L=`D$3@Tx|DDPJ6ZO}NecNnUG?QPI`T>_1b zWz1|qEf~SN8VV3JY=Pyp&nt8`s0p)=#`Q{fv*-<_|byQ#L73rKj zU)?E~<(;-z8JqX5T&KHqsZ3=ppD(?^`A3Iy%h!=X_si~<2p$qGC4aVu22#>2j3eQa z(kvql7tAlCbUB@*{Q?;ueHAch67mbgx?vaY;|&nDyF7X5{i0h?EbhlBxma8rmt(7) z@ABF?VfuWxCr-CwyBBG>ufUG!-iqN8Kxe7nXF}3L;oFY)>RiMnA16oM++$(x{w4OM zR4QX#PGqH9Smujx4#P`2_=E4v{p5IfIjS#XLPB3eC{?jC zQ&3Jy@Htm}QEHM$G9lCWH@>Y=32||l&Agptf$J@SB_>OuBhtru-$kNRKYYlwVTgYq zof6>K|JXb^z!Ck}Tm;W7O*^-ZpC>I~-SYYatM4i-BMv#V8MQc4Dy?b@BODN;weM(3YUk)2)e-u_*$p zi`qpy^)ac@-G5b>x?5Ob>u%NU(b0+2nUz?nyGRJ-> zoOpAgI6YH4`nzL7(Nr^C?%aFEN_RYF`xP`}yiu)w{$zA7l3(5{Nf>(&TO+0}waqy# zfxtX1ezECgh)8Qdi(t(%zBl@}W%Hs0-Mc)mz?kM@Yfn~j&zgTQv- zj*60j#0Keb-%BVoL-P>|SS@_vHh}_teJ}M;3DM{rHfF4`uirtFO~>Xj5T1O+D{ zTu~C2=h=CDl`KYFaQsgcCjzvAj{jl1f5WE}6K1886aHVz$M}D_fB*0DZIY5vtx)No zUAYVn1q96s*7)R?D9^A4+A~k=i2P0?K zn-OiMYqE3E>iU&tB?y`)p{8%B;`Dj0pmcd2qXLFbXiHwe^h#dffa6~(R8Iq8sGepz zN$t*i0o2n>Sztw`EO_96?L5`_&~gix;pcn(h-YBKKUxRg3uiH)+G+zD?WVl{Nuw$F zB+K-kf?_|9u@29VI}Quw`tIb$&9`uCpFhJNHVO;(TwV=NNl^c_##rXdgRcJ!w#Mp+ zL$9Ad+_8BCr%<3sG@FXp8}1AZa_cO4*z=HVVQc*G%V%%(U_s`CUvW-BKa4pLE@L+O z^jkSoD*0yC34?bKT%X@b zg^N!xJRRXUsxW$B6(S}3CFRS@Vv;mTA#s1VaY3W|Vs4L}a98uqB&rUO7nousa-7-R zorN9tB+Uvsjw3C8+z1>>@hEP%FYPd}>Ge^!*Kqrg$#!7#zH~j2;dZTV@9KXJov7&c zPMrMeK9be6AJ@op7B#t6lp4Eg=gz{Inuh#-PT+wuGxL(VJ(^LntF5}-bzwR$y>nS! z#?`!?n+_pscuud4)xN9HaU97oh6TIEkh^1xl+&8u!(v`Jn<)1pw;NL9RYRHrsK?~R@jhfEL+-sCRJ{g|S=nim>1=B~oW96sle9hXiCbZ-H8^M8B9&!?yxro? z59c!aF(LGoR;Tqf^{5{EF<$!g;CWh)twYwBS&trsN@MV3h4ETqX|uFN;BU&$(j4mYS#Rrv!Vmwl=``&yjiWh zqg+8sr##_#Xx5<6`n?tdR;GM?u$Xngy2@o~*a!a3U@pfX+klVBQ&H*;RtqZaQPC`2 zpjo<6dVuWs)GSjZ#7jf@ARCOS3O+eW*~aKfzOF|e%pJE$ial-5gd@GRY-PS%;1#4= zqHDCrG6U;3y1LDls*235Z0nr6E*%PJJaObD%3vGS%p{x|_9QMcTOvVpg`6ja*O}oX zIbMUmJ`SdBnB}K0@vO;u)M=}NUC8)IIS5>5x5II03F2@MHhdNRBXE@i@R(^v78+aD zHy$YZFIj@Z@PsZt(pOIqV@ypGbd`%xQAeSBO0i{XK!ckQUSAm9&{;_XGnN6>V{HY+ zV`NsA>7I!xD&t}8Y(y9g{4(=rs*)pT-!Nj$w-9Ke)J?wMAMJlm*23b%1uNwy-03(?toCdp;Bd^O7~;G z=!ip;|3MD9@KsdaD}qY*I_{=Ok~Qy%%kvVu8T=kA^9VLzv7~;yh$zsn{jAGloRY2< zSR*vGf6+ERk8GGryHLo5vZ6z$Ky^H*P-uWld)K5uwY;NW`ag&K-gNZyJ1}E?n*)z> zUT%I~aGp=N-4m*onJ(f}k<+_}@rlC4HT-UAvtLW}cY?Q+A|pD>K2vFp|75Bn&eZLr zi{p==!icij4qiR`DknnQDyPnP!y>fPEcvk0Yyx*BylS?C?&E2=GhW!_H0&Uv=XgL;Z@$DQd-~Wr0W^W7oZdNW$&Hqz zng49y-+0!0UPk+u>LeQq)QC<9SvYBrbh!)e>H zY~61&u@)$28<9TT(VY>=UjI2Z+{dk@`qIAku+>2mQs2!- zZ12O6L-f(&h}m|{gXrzOVb2}E;pY?Gf|cPR_-^nyGX_VW6gsrjzMZcZEb~50rswF% z{VHO|B&Sk=U1zSqUl=d`7SA7zQp`0Adw6_?Jf6M#rD4Kl5nm;Y{$Wnb@EXp!AwBEK zAfyY9Ktmy(KZ$+%i3(!r@L`}~+sRpYo*(7Z;6goqrTPg?bRoL!yPsi6Zs**OGL8?o z)@&Oh8kPME8au%8pB1bt-AZX$qKUZ1`9Uw|1Uu12rLU#$H~!tv?oKhq!g$bsmR0`i z?{*6gn2VCq#@73{4Ou>EJiKRhXZ0ES^NZ*suH-cN&%sM(0k;x7j~yf^>v>-}a}+Jh zuU-CmhnQ#ku-??kwdVd;$PC2@cBbMFC$1yOp%cFQLcFT~gi5w(*j88ey)$YVsQ#() zO|~e8p9SUSp>{PZc!oFJS{>~x)%Y?R6UK8VC(wlLq8}3Ij>jp5-7%;IV``4m=lZIa zvl#JS`5)u^CGUIMFmI9@&~>Iy!k1P3je1lyO>%!ut$>+^etaUwR=M>j^tiG%zE8k2 z#V2+eIcV7}dHRcpo0w0VNXv{00?E2;XEN8ttJf9ObQF&3OfNpm6Qq*bSf#n&SmIw8 z+@vhFW5PZ8@ocp8u(H^PU^B{!vuC&`hlBoOXquL5(%tu0Ci|o0>S!VtP-u>S-D6wJi0B+{RR##ogJP zjnqe@@J9>28V8->diwRXAx$;SdDrJf7Jj|2CFRUQe=hFkeyw}q74Xw~FZXNE3!i|W zi~G4>2X=d37py-NLuNV4HR#7$wh<6KNbus>#k1F%Mc#T*f-X$HMeuDW2FqwxT`tQf zb8|QPn{b4WxI6C@Baf?GVvS@dAFjkR`(&~Fp9x`a1F^wkjX%}zG~IgIi#`MP*VA}H zDlJeM6wb7fdg)noKJndR{h4wmU235@T7R>r16%LSKVCa7}5}Lje64epY#3a-nH&p^GsFm zdV2Tno}TX7Rkf=&S(VZ*)aa|B{NyV%j?M@tF8vy|!2 zl`*|A)!K_3-_V$CM913k+If)IG4$YQYCXbMqy%QK9nqU-z%1~TuKgn+jXXUlW%Onlp*?QM#_kUz~ zpK2o|o^}%`UpgcyB@NhwH+mm5nVXrNRUPZ!oJI43D2BxAuBd@<-L|Fy5#SCCpe22r zr7fgaM!e9>t7Z0;9S>sa;_?b;<(3YyF!*yz2bY4}8qKq# z<~r`{AB_70QMq?Z%}KGsqDY^6zl8TH2``3}^P zLIP3b#(}8twe!6DhMOU)>_V2wi$>|2okRs2h(F0@P~6z+htk5~3^uYy!s{{96>G`; z)2Q<^ec4CfU(rNZNNBtj`}T^)_LW7W?W=3n&zQJ=G9p4c87;q)V2eU=Q-2perLG47Nz

m2>ns z!@&bVmFr6rCNDoI3J%L%e?zJ@`ChuS6-U-PY?TkXLDUjrN9Vmd-x`u0_fpd$b2tod z7;?W;42BvB$I;h*g9YyYmTLa02tE46+GVVJl11Rtt40cS_V0enWis0LZE|C}n-??| z5EwXEQXvLUzz7(keQJ~A;Y$|o!EcY7CfM~G7tgL8w7UE_MTA_{rhN(!`d_3W>VS*I zf64#9@%~GF4+-?Ock_;2&h}4F3)xFWR!aa*i*I(TDad#QSD=i2Uh|V ze3auZ3BeZJa=&SYo2t6Q;C3@8@OX7_a&1^&F@7#PSkQ;t^i(0$8lG{ip-n|wrJ^UB z=i#IfJ#5nuWiqezEH9$FIE-A@a`Sdn;vgxP?vf30^QbGItjTIwMeidvi#sQwoBuW+RHF=5mw@o~K)*aN${$8TSD~KYdh+MAb5!d(1>XW6E zB&mZquXKaNW35jv=u}yJwg*k8f2D87IaIJ0x{yrJJx##%#`d`rTth1BCrcnLiKtk7 z?x(q?Axs{U>+q>-B3+59SbT)~ro?>2KY5{TxEfs>hP64=LhMGz-IJ{fTzMNowY?Xu zL(^|Nn`QOdh7_7;!&F*rBsgMHH2Br7c!*3|-;pr2up+c`&Zy&P)^i*3Xcjzu3~{3vDbsR)>)BLvCE2oLirhq`s)Q6DJLb6WkTiDV{Mk>d4J& zG!;SSHQvfY@j=bUe8rJwJ@;vR_%;-owyxYvCt-2-e?-OtUe^v;H+rL_$X9<5I*s-`0zT9h{_?3=Bo@pQ1E6 z)LLr2buJ-44M+g6KOMe($^l}0{wBC&aSt>sfLIuOR=QuYFuSuwiGFw{iGD-?|7m2; zzX_=^`yGlCh7Gt;!cDTJVLxslh5m`R`R&|OME;85k#)%86v(mycUGI`uP7dDM9$r^ z9BjZ4=!D0{15y5t83IwEF4$~w8^?^Gq|ggJh-sr|X`$lVnqDUYqZ zN)?RW8%mM$L2l!&q0L(l7(RX+EZgA1IPYDk+32o6(RajjM*nMLk^mfI4N06n5v%&) zLh!%fTbUq4Zr>nC%l}2f^hFtd2TeDp#UaeyKl1yvC;En5wG+t;t(*HSpAI!nq`Pl^ zerH@E6Kb6E8{^`A&Wm~r(MYezk(KA5-Re^<&BUy>9ZWT-2{c#HP^~DvsBOsRWcz;d zLU~@VHyZfv)vO;S#fQuM8*W30`J;dCIVnDDi3YwqOl{$*$XE#Mfzb<{xmG|2Qi~B-V4TYY6B0)7Czo6XQL@QQ`J&hbW(hOae34FM=)HOWTJDL*Cb_h9oLrXnt#X> zD(cIMk;l&Mv+UzZFicRFrX#03fbzG~%p&FOyU`IXZW zx#t}+{u8Ugrf)lZ7GwRV)8)^tl!xwJvPib>z9pDeo0`L>Wtqa^uYJXRv|HueT*eNr zJ7rRQ%@_njDtoVFH7e`BrLkb9sSR;f`z+Nz<_I0S(~)8iy!ro}G!ETy#5I->cFe6H z{+-~8-bUW@o}TzdQ`T9)dT+AwFW&t?CgRI?QFt!qplLhtYhzr=?2*BisicyKf8}}o zT2%J>2;CdDKa6fE=FIFaQ#AT5sw*B0!faSS5+{uScJrU}QF ztUUc&)~exhD|6M%r^shJ`~>@;;p5ZrJK4GSK9UqqGcoZzxUYfFabu7h&l~)8@8{zZ)gd;lY*L` zl=hYz%B4FSsK~o!h8b`TWXeUwcA00!I^{jSh^9!~c^z|<=7APsYAs+8S$so}yMHTg zzERHk=7Q^)uwP4@-DhoPvk?}b7;9b`r^8@v=00)HyUY(bRa0l*USg88Z!(yDd-;57 zt6KchkhTFsBhTm5QpmR>x>C|LY!-xlf2+Y}fkO`DAglk+6l2TN!L?c$6)T&1Pu{9R zvdbdZXUo5!W(ztKl^X(gy&)MkWp!-KM}Bud_)AhQqs1wo_{FA74lulh>s^^d#PJy-=(M6XZ6WIc69}uRQ=fPWtiflAb0-H+0~ws!Of?_9+H~E zsSIKsbkxYH@)sYlelggUE@FqXaAlUXw}P<-Zjc~WW8!%oieqWnpF2m7$O z%J~yzn4p>BjLbk-X0Q_bPl}^1;saC@CUNPtbh*MI{OmBIrP^DP^4M+bM~%1SliK$M z?MOQ9P9o7K4zfP#x^svNDJfKDy#vp-LUT2q=}Ss+*S#;`p8*t7K)DYn+21Z0rO-9# z77L{G6_cf0Zq@G{_^aX7B2PGjq>Mz}`X`?~s z&L2dv=k6ToTl_hT6*JokX``UeIV~gf4vT|nAX6l)8p{T}Xpntg33#yqEC<@7R|sG( zKcql=9Q0&IwsdF<6_mNF3JoI2 zWp|=vUghAW;>MoLf|-s;xB8mnafXeIiPjHWj2)brN*U_-NK8B}h*%Eu4Zt?G&C4(?2GHU1W5wENSJ{1!?0#^Ron`)+O?P#v73PvK^>w~eOP z1?~0E0=>zsi$A8v2JYsaNglV@Nmxs;k3)i0m85+;lI6z|SxA0l@T^?x%Asqv8z@ng zClAm`mdYz%^uT(#iymMU$-$zP<|mj8gTjNH`gekl_OsmH35jTI50zKvynNJ1ZPF1! z3Khn;ZLFYti!&^5L1c2_DJfVU{00E$|C;7XrE`m9Ww2$zUNpwTND%S=ln&)|*X)8< z;Qx|r+9x+KxUiubFl?kzo%|*ZV{>{2>)#YPt&=DMyjM@6Fa|0aV}r}l?w6BHKYbK! z4PTruj-Gn5G`kaCsOGHeD)&fX{HTxnDQ_yRCiB6_@YD|o;0?g)6R#`30siTy+t+>5I$;m*lsvkQcUJFBFE{D1rQrr<7T1bU@#e!vJ)+$xp3n+z^>%;fA zsV{@TX!qg|`^L}!#gDBl3{?Hr#gkLV)WhgC`o+^B=o0f`Ad3+oNyJ1&#O*VCnp357 zviY^t>_vKFi$LIVMBC;ZHQn~Lq^V;9?=(9{o$jgvx%z44a~sEHBh%DAI)?>R3{ z+{qmKxp8v6mC#k;4Kc1e2a$RyMGjfG>^v5vYdpox0ob?~uc$5+nKaj6s2EG?Hp z5L<2XF8eyPUz5|5wZ?bOe-$#CXs=E#vvn_81dIBj2QEsc9V${aF~L#G@@ECTdnf%3 zYZzuVnJt+Y5TpyW>BDB#`RTJ7Q19hpr?RIcIQVM*{V!^h*5H;Le(H%~C-X}*1XYV1 zB#=&3>WP%_E3jMfA7-mWbyFE3KW;#m#uq}>!&5)r7h#LPczcrlXczf$wu&88dGo4N zP{J_LYItEnR$p1zT;}tzrQmTSW?K5ESo>)u2N;6}GLwZ7NwIq$=FDTlV}j`^mB5I# z?$%!e)W`!qQvsvE2UNv1l-aDBN{m6Y^`-jQ7i-Txlg-}#rZ{_ak%~aSZ-GYUjn5TW z{5FlNF-J})EFOeXDsW_j%m$5XhnilvU^N?!_xNdt;cEpgj$z#&E7WCY)-6;c_C=XN~8Zpp0jw~ zL(Qap&arM8-;1w@J0AUgkssX_r5T*d34iF5Pfd*-y0SqT=9|eRm zK(Gdc20#eFYPbvtQh?w92!nu7Km%3R1;gGzTxFsnRs)tG2?$RBp%)N701c`@LlD-6 zS3m<3AV>g$Eg*CP!aG2a00c9v4S-39{1#iQ79WNHzK`sxyq-)WxL9zEw&BI$%mCSHS>am~r_Z~i zTCJvTL(&#UJ}xj^&rmT7KJi;ZK{CuSEv z+=XRc+)I9McUSf*w-Ry2X~lfv3tu8R!WiFFaikct5+Ag;l?1wj6K4k+abDp%W)%sN zG2x5svy+){+Y_0rtI*2M`^(@%+)-h8RRIq@Oz#HWM?$>5c+kSS4F$;*H|u!rBX^B1 z$wIfMt|8yL!)ax^EFjz8)2Oo>xj^+G+n}zUvQfnB3qGvv=_Gls^vxaoI2|!2ypjBy z;W**~JeoMnbfYwl!e-N8?kEE&-`0uJj33#A-93833>7{W20B$~8yzG^?H5L<>&$&5 z=G{`hrml(r+xcl7nq}|F<&^bBo5rS-pY8+M_Rz@uo5jQ;0z@SSbx!{8>0L-h-`;!L z@2$A^Bqc`MMf+Fx?lP^;>olsze>#?A?utI2AGh7VNIiTQ*4^NXS=~9;Sg=CPgBH9u za7K}F&!GK8e6ydekh4ZRbo-sG%uH?OPWuCde)mcF(gJdQ{BarnaY@uiwsjBM))=EURCuMh^fxE=k?FM#}B!^>+>L~?WWx#X5hkszNA{?ond!ldCb~q{tMvlN$H5~ z=)7jxpP#)Nr35;jb)8n$%knBcHtBRY-mZ&*xQ`pqQEO0xQ$*OtBGRq2E-3qxqoj1o zWX7zq^GVhBvxUtiw)m&nAFl6Jc~_O34{L(XhmD1Ef7o%W(hrWq1opcSsp&JSisjl& zHs`7IP?ZXFz;WrR^*xo8Sk}Dm8f32Z+DpuC&KDN{yTlQL2unHGMkVoi!8+P)H;pAE zPbUbSu;~J?J*PPx+aHL@^EyB6Us7?$Tz2nl?+(r#7j9zDv*xw7l&d@&Gn4m{%ZaFE z4?dcq&lrT(m^_7~w!Tc5?ClILQ1MK*UR3NVJ=MB*1|Kx9IVU>b4>DSrbcwaDZic+o z8(W$#H>~HqHx#@87WfKI4LLelXac>*4StxEyZeD7l9=b+iS$AXbzWk7dz(q{-SvI{ zo+TUkmZ9`9J_1O8r%Ik&wU66b3(I_}%FapqQEc7OK8jtmWIe7pa5q->4f&kF>hX!A zSF5uB{_^FL*vZo!yYmX=0vW30a$o#zfwUUiV7-op^q?T!ZinOK#l(BhNjha&YmH<5 z%!BsxFlMQOG%1>?CItGe<_GLk>`x09M3u>$Y3fW;gD1~-FOk2R9`ib0T}U1FK7f{Y z9$R=9vMedKeWB_ra`QHXr+mK=v=8-vj;igb80)RQ`tyc=^_b{KYj}`eL+x{G83uHD zNqnjP9r=F5waY&cVy*LoIA`mHv1o*$cpZJ?h3X7A9z4l-^PeV*I@kjy-EbGzY@ zkXBO!Ez9>xFpzlZD*B_$k@fJPJMxj8=jZNkF>fQ^I&t5E7~V2dA2JMDXpQ2v&J$^$ zxPQ^SQw$7^%L#cUH?4=*_(B*vn^o%IwB*p-DTi z62B$A@9a`?HD!T0Ki!*z>a1xquwq!^4T_cxUPx2Ai}_LWrD4mvTSu?ur+3V*r)>_< zIlWDzYsT2Rf6jxouyla=Rl9YEWxT5E1rX6W-=b!^~-%9F<2TC2#rK-ko zh3TCy2D%z*h=p1v(3>#Q_<$LqeQPgc7OOB- zUcf(c+*XsbN!Z+kyvkZd!=JRNX!1J=>i)hMI7NS4gf?rUail^L zijY9Yo>i&IvtoQiOosm~=CI-BWo2fnf@7T~S0y;aa3c?;V7SgZrR#XWg*pOZ2{5a@ z$1o7sQY@>)1Tn9Pqn_wNf>@KwEFSQMGnZ>7&&2$Sq-fhwu7Fe@(^NpF zwvR`W0b>}wjZ|W%G91a9MGz~qeffN^DAff-zkp)z6XpGS;A5x*pZ%X&iFb}iVo#JQ z!IVxPX687+gifJza~wWFlc6A>ChBlNnG(#OWcV#_mgB3FV!+n%I6Gvsp;|q$da{7& zZZgB`=uj0s23KX|bC30w;gX0$kExpeu=fmjIk1H8@4Ft!-+2W~$`QbMJL|Hr@_58Aw%-5NWlizEE|To=N0` zVz%SQXVI2z?1`<&N9a#}N@wL>f`!9#2U3=jQRq7zC1bUbNS-pA$FRw?cXboPB#_&9 zrpjYX5I1UXT5o#el$p23h^6zo)3uGlWN$v{GzBSL5wAWWV6%NxwCYYH&FX#1cpY6 z_oMgH>AZb=j#N2>=ZW`Tyo#^U5O0|NH%hz+6Ve+`!|)~+&V2gD8!0FF8(lp|k&fT{ z^A<#YxLMnKbfrOe)uT8Yuj5maK?`v~%xkis0Y8|=FZqTp*~En!UOcK4Eit|>S%*d) zTsA4>YvS0IVo~$C&a<`_T&@;YT1S~ArV{;%g%$1x4Cs~p{bgoVMbh_k?YuhA>+r3c zJT9^;`jd^9p)$GA3($Jx#7KI3xrbaDw<*`w{S%R4R2!j*UCV_@`zoYC?p<-DL3j*% z*mxgj0&Z2qZY@WnCzxT9RqAYPeVHTPF3giY3eiVqO zv1G2d83{n_YQpzt*P*@+f|Pd zFP4IxZnpFqiC4hG7yaL^jG&`pWC~{Z|4WPsUN*I>HP1HEcEk;1E`4UiW1BxM* zauHD80!kB>!UMEOVzpo?cLBv0OSuFn@3FSD016+Vs9|l11e6DW^3DoJsEbzB!Zjaj z3zi}f-dOhy?|UT2wUW}1YODr2prQ0F$r*CgUDCjDTEtb}>xj6iJl6A^Z>5P}&EZ}V zmE%(D!mdhJ>mtcZ@Mus-BH@6wyuAgcWgxyx1(Q)vj&`TH3G-S{jtW;u-`tk_2+5yt zF;4k#aYE99`+-S|(MJqte;I*(8NGd7o5#ACcYe2L=vpLIIC7{}9BiqNa)z{iUeBt)BH{X{CfY+}oRDCa$nQl!l ziiH#fT5!r1n_{cM1Zz#pxBJ~g*A9Ic!Gk}0Y1ml^&B+8o9&C^7Y+nOU{#W3sZ~b?x zR@In76}FCjK)~D|tG;aCkBofhX}qKX#?BsW%S+vWDlt>7{Ukw9I4OR<#6?hLGwhts zzyV{ejUBe90Zml1AM~4>K2ytyu!Sp1znSTp?u(ett;m-h%_Bjb2v1UPQt@AncW{iU z=D#|d?*p}mT&9EbbN$LXVY3|Hij2j%+}4tIIARVdZ?42is>C3HrFTZDrP&@xKZ_zB z<_E|4Yz$`g`#PN;xE`)}o;(BQ&-+K9-%D!9WB_PL`4I*^9#H_30!orFP)(t?J7PgR`l~nVA$7m#7}DKwB$}h&D8Q3@h^~B}KhWv<+9FXV?^ziEf%7DsnmW zEM%ext$i#>f@;j%jPJbyyPA!FI%ecPYn5PMNb9sWR=PpA-2;C6$C8X-y1$6{UJGmpZAAhOf)x{JB5|3(yB#RQ zieq9UQa}R!B-jMJ<)y$;jg{FPG{XK7Gh2k!)3`Z@rTl3dlV;OnidIF*W9jK9DzbB}6fZr2TJ6=S3Mu7&-(ZD*99ofYpz%muT zOi%?5^6MP2W=R3P;3Q|Tg~Ch};l{w`zY~7{XK(*0{^$Sf{XeH>(z-c^y;PuvfW1^i zzb}?DhS()gYhtCoJyRt1f~)r9&SBumfnW{dH}@{}j6)XrR;5n0ry% z^+Yik4b8cc?JwEnl-e!Zr6431`RL$#kpFsuc1)Jae7Lw{+Dwx4Hu-S!L@Tt-bcdO>;w!ZfElq+h+&0u)4hP;6&f_`Dm54?;9B}E!IG~h&`AvexV~P`HFOQbT zM`pQmf1fil4BTJnUqai1vOGba{sVDlDlK-bs_#vGL{Gty))rSH+jr}KqO9-f-^tyy zk^h%UqQ)G**{I%AH43*1Z}O>4OR5bD(*}Gf3MR3mlewDjfq_NYhHgRnDd_W#ffVE`UGC6 z(8RpH6PkcHR6$#9tK5A1Fd)x5LT*2{I*Oi}3VcE9AW`&xK??z{it^0r35Otm1NowM z2rmZa_(yO%$ha8{ocLUU6Usc|W8jGU>j_yzNImiC4}Ra6pZ+Mzwwlbcn$+-OFR2Kz zMr9GQxHAAv^2%)VAn^;D#3rCsUepK&;SAmfUvWamx3^250JXm#f#45>wF|T!gPBBs z&mt;h)F|fNi$_unZo4c(YLo8PCXh@t{!Wt2tJE)Cfq};!_CWjCD0S?7Dwg0K0(ul4 zejW#J5A_SOiz0v5GG~cZ2HqVY!M-}M%93Iu0BJU8tL1{ChRCbqBlt+`x}fXXe5$TY zv~_As;Lo$!mU1DSkK7H8{WPMBz0jHMTfy6$1%w4~)wkhYgJB%Ll$iFctrrt*^YaWV zd0}8w8_RCOt*2M)T5oE;)*ZQ5Nf&OSWJE64S??(8<`(^m#h3E5-K{w;!G+sxUh>5g zWSeur3ri5h*^=F6TJX}c%~a%jc3VYFG{-^pt9Z`gBk6FHTo#@Ahwm6=-G26q^0^hc zTDKL*z8;@+&Ne_)>U_2s7v_>k-9QMsiPzAoqK+iJB;Lb)!~~_PHRtETII08m?$6KD ztjoD!O5eAYYn86Zx?#S)Z(He_cAMXEz5cp&=ZnVb-vS+R!%ySF71=x=|1rd zH@^jYxi9+78oQArH!oGTjet;mX8UIP>d>;m&lYYgZvNMj?omWeI9g>7H-CTsGWz-@ zW}Wg-@X5CF&U5PsH%3T4>7byMqcf47Aj`dF95c>eF#lyn54!u!pOrhWs-*F?F4cZG zS6-DU%04mN*?EeQqq>t+CUSz*#d37dnUJ^+7H3i4Yh5X+fnkl*;RdYk(HlS z(QT7isON5o)DS2Nw*h4NSG#%DDuSdgN{HR%@OWd_=Mqb-#H-&Cp zO3#PV>@2{h%X=@dhvS4&S9TYDyvj=R?Ht}W#5rjKw2hZ+Mjla-+fEw86 zUFu(fp?X(L8kuzt+&uK}H6+FoeS*mQ-Kq^d>XkBND6=sIumrFHum^Aka0T!L@C68D zD1F*^VdSqFbtl7FfH{D9fCYd>fF*!sfE9pMfHi=1fDHf?z$U;Jz&5}R0GiP0$`PLQ z{XiPyB!D3R`XCx(J%A*DAprVdunmv|Fa$s!0=5B?0EPhQpMq_GB!Ho(>e95K>e3HG z!8X7U0DTxJ2S@@K0-%2ewgHj=h5+cFgKdB$fFS_-aIg)K1TYki%lx7#gkr$5IcWi4 z4}j3BIf)M7Du5J#I=~|U8vsv$=KzTSIRF&^EdYZ63jljojYOeh7WgfUWj5^qodCT6 zg8-udlK?XS3jiws8vxq?djJ@KQvh71G8;kwQUD63(x)%TNB&aRa5B^Y&;+;%a0}oz zfEK_V0B!nF_5j!8*m3yO91-!P&uS$FrBxd9<-41Cg}E2rTmBWePaQqxro%E=DkAk} zK_hP|OZJncsRLg}^pAZH)lVH|=mRDhf$?s_*$l?f#FUFib2=72ZGC4W;*VcC-B|kG z&>nfK@$vd0-|;18>^kKJ0IO z3L)~88`|E!*3n<$*nnQ{_C>zCo2K-H(kp8T=}{7G^LDW}Mp z{a^jPb>yj>*!q=+ME+nYf4G)Rm=Oh#bd>Ugnn>WU(u~-Mo4>?Xus^JEfuW+g%{46P zcWqylNxB6}tgiURQkPr?6q2V}!9dk{t&~6a7PP5Vl@$~NH^Xy;wh6dLgILzqF^m$h zK*a_t-JspJ=q%S7ij0jgzlC;!u$M$=8=}{z-Ox^6Cf*WTb2X`l97=k%FHa0MY)|6Y z%BNnPy!F%%*M8kuKI%FNRE#R7vJRU@{1SK;Hs!W0j;_DmlXr@A%IN$K3{aQu&YkHF_MjM)gQ%$w&-@XQ>xt^cXZLVnUmsxrS4<2liwuPH*3m; zEslC9?*3}e`o~;k^9S2Nw<9=W)4!(00_n0_@cFS$tY`dhchO&I9ZPw&1zNdZ6=IqDCzs{O;*Y>saCYpmV(ad1hylv+zb2Z1B=E_}J7w0}C z3$6AVz#h>j&J6wR6RWblTH@}i=N7!qBj_7IDb=BQQhBvQ6RMRIJ0mcZWs6}fwi0$o zibaYTDu)_>2_Ubs#r&!|wC~VN#4lLGz#hNIz@ZxuV#ogSJ%U3;peo~BtqFAmJN~mH zmk*TGJ_ZV~_2&gH7`PX)2g3)|VZf|BsSyT*ao`YRrT*&JAB4|PIb4Ac_#qfZ>;Q@O z9kGemz{LRN$wKT1zz+viY@jzB%o$$@5-{k&q#T&JF!uo%{}2ECHaH>56Xjwo1=Nqg zEdpx3i3?mB4@JQ-LF{T>*A9(I_xC1wtU?=>SFP^u`TJD@gLVJqwvAs@^4VJ*;)W3B&FO9JC~%Y3wcH0!Yne=4(E(@k?{f2!!qCf+E6C0jm6DQ21>^&RnMTDuZiX4j z!y1yg(TUZzT3S9D#&vkfwN4#Q7-5swQ7*yD3< z2j5I0I|TwX5c~uJ0U(Gx0fKEHXa)i@ECVap1cEyD*Db3-YV=XZK(GM>UjgGs5MW>h zYe4WB2tENpdJX8Vjd~GvQ9zWW$e{AHjIW^S?=rYS8hxiS3Q#-(Y^k z7w`OVhU-hTfJp+#r2J1_al7;y$MY1GEwDm)K;@aSFnH(K13+_vjjpb$kaSWYXk=F|qj`Dwy4Sg>dxleru+g^829N zrgjQmxNb@7gM4F35P5(6l~(wUXz;kT4DX&~V1tdJ;)$lNXkt&_p&L}bhVnJ7Q7o#* zUAvaIS2cx8?!oehfq3Zhm`KL;WUGsm8}3E2&ofjmh_d^!$j|TN(#pS4E}^a2kGAV^ zE|!|@sqj<`L%EgFM4+TPMhcT$+lmPIJRUe`Tx6A^xd@{B95}h@yee4am!x1eckC&= zn5UM#OSjCz6x35$wLYrDe5%_|Ngxy7ouLbCGPTIwmx6~7**-L#e~TpwTL zu++q?Tla9Wb4W!XgsknC+l8&QEw3@xKfVUjyxwVXt;66Vqsg;31Vnp$e3%O&H*TMW zjxApeye?|3>9U(r|6ba!(=3jruaNU`k6PRN$hey>y93L*Wv{sEdv#0h?d#l^U@&H&bxEHbxJiij4N;{^&%mwKh-+x-xo(@^o&j#Ni8t$=pnc+mQy_KgOIX{BsRp0-L zr_?EbrBm@L+ba85r@U7+`$b&O6Habf^=AZmFXNDO9gKChOse;tcBv(qmA*!jkP5SN zMAe)pk7vHOpVl7QO}7tD%h-gVs^@tfkDSJ){gLNu_tYb9+b0}dcm`re_VNU`mB)n(*>e(EH=&)5f@+;FBCOtqj_KiuU21~?Sd!l!18?S@TJuWF6$iejow z^7q|bOiR3!_PyceCZ+EMA4k8MK5bal3`*70M2g8ID--eVwYk(YaKi4?%L?>$ASL%h z<>q!+10E*oHO8z&Cm@Oy)fu5dRrr%zu9ipE| z3Y8#I+?>gdp=6rqbxl)FoU|;DB}XL(fzCHeBKC)Sw$OLds!!)w=!lDy#bGc8zAZ4w zzzEFb#~nZ+rqEU+U)4%rS}%I5TGnSI_U zYDN+%%xVN?FL7nO^H9ho(8X-}Y@zes@YKnX?vnRrR_7;$m4$n1+g}^bN(Rl3=Jy9T zrhknsdAC`k%OEORIj%zY!_h^~LYP446Cz7y5Y1Xi@Lg91 zbz!V^S3~kNC!ldR*^3U78L;bgnmjcTzBrU zE_VN8@XOo;@7Ob&FLITIF$8E_(M1t_T|v|-@uPATug&_CkG7WHR}X5fGXvl;9rrfP zr{R9+Rf;3hT2BT-s#3uKff_*Y6eO|`|p5!T~tBA*2d)4GO#F)PeLd|XLth9m& ziTw=s3w4A;YVRbdEDn)w#~>+nFTLO?1~rMpl_P<(v$Nx2l{1g?vEteDjz=e8ren9g zAeg#$`^xn3_NUc2s++-ufhSdGTcZrIk0Jt|`B-6)>Yh)Mga;#uMOEg`S|i2;S7pdYuDg8lwFSM~3QE|sC=$nemxgQvh!b-A?nU16KGk6QaK9TKJMJ;t!>IV0767E6$9)r_a#z%ijII;WInvO7D-F60iWj ziKKH+?+1?QPI6x8WB5%PxyO~*>?R^Hb)1G&w8gt<`WIRII*R^m~bsV$UT){ zuP!{-rKQyHfd^-WZVBX=kv<)^eL@HKV%tdu5@>|0w{CKZP*L(;RILnhO5BuNh79f@ z{G^L`UVZW;(a-=j6jft#vN3vYzwOH2`RLfHNHEy-d@K1_zZ9oMn>D2vPFN)dCp3@Q zi#_iNaH^7{H#wUY&OM*}D|}-)ep<=g_iPdYGQzWu&_0!jvmYm@-b7z?la{Rb=8lWP zR)dk7gJ~2*-&~PDJm}ogJx&QT+m4=HI*7nzkY})8>%6}IF+`J1aeqOhhcztWsk>1I z3dckglbl@g@jTpD z(|Hd&+-El#{MSx@tW6uAs8Xq%9+V$PB&(b;DJ|;i)=gfr9Q;dkueqbU{Ct?mZ*QQX zCJ+V>pbR8N*|FztZcZW#G(~sNxUQ2CEZ(i(K zPt%44EmF=x%r`S&n+9>+qA2kgUP+F%Cv?g z)MkTVO2OT&C=Ux*_31cWlx_d!v8ZCwrigj9*{iD5SmoedJG1&4d_O&iQUJA+GezYF zyHPOv`Q|tr-Vx;$Y;(s!BI^0EzgJ*X#{9AJbh&ry6zzrK2`Ojy_5H^gU9J0ubURvi zq-r;(c<*H_^nh^dd+UgX6SqZHZX4R*Iop@lWm`%R*8Y zMod5L*%QSQPOyaPrmGv(W}C}&Caf>fvp1JG2HtJFlw3rS!%TuNB22>sO=U*jM^=WU zT0@gNiidiM5G~(YOy=Yk^Bywd-(|gB(Bq_gRinc+lB4SD<3|2PE@F}TTTIYMOgMh> z_m2cHEq*ysRID&ekd@W~eF^Jx}H&66Zc{u+XGA@0F7N~i>79~&lYmL;R zV?Jo>W*xV}>w`HHi)QsdtKF3ev2FkCAk-Mpl^ght&|6E<79)8rJ_mmEIUmm}J_xWrMKm!0L2W0{q; z`|$(z3*@{8?C488K5{UWWLJ5tXf{nqYsp-e{x{17*6e<;tn?6Wn9KSm74Y!mtOBrP zkClP0z+Ji8r}`+yNRffoSYCfx$9SwFG9N0;PFD;jVk(lg!7g+GCJh5|#T!IHT6xMC zr-y2PTiz5jGH(YoiDr0%LRNTAy}sJ>gMf#J?_ZFyALefrfkF^C1fq@uTV3p@|Lwwo z$FHaRKIo{aKLOL1fdDwfwhm356{rm`h!V6UfiX>eA0C0i(fmUTx3+o=<)f#8J{aB) zDi!H*)7^T_;ML8LvSAJ@sICe65r1o?%5POhN`GlWk4OzEz8Qy?O#fmnj7HXWiJCBm zY%5=G?ltl8z#XfPjVm*np_Av%o3H$?R!0k-G{8AGzjLa7Y3JEY{c7}>)shY&XlV&I zm1VZGw4wW)!`N2RyWHJ5=$DqhW&xlk;4YureUYKa)cm zH(*x?_D`5fmcp++8tA^a|4Q|EA+)h~>s7)66K|6QWQrQEJK*WF{SLyX*UDFPO_(K&`}?itLTOddWnkBfNZ{RAtn)yuZv`_|k!e@+W5sg%G7tf3@j%o>vI z_<;jwKirN*DfqkCXZCckz>g?S26;==B~i0i;j=AI_{_f0iZVsYl)%HOeawO>XrPt( zoXih(gg)_^&?zkvG-9#w)tDgZ?Ij%lFoF1`Pd5?oBWYm*eUJIfQh=uLtLdEPef*O; zEy~qzh)7wU8+SA4;;|nyvn_s++~P~l3Dv9?qEP%{Q-BmFapgnS@ZW!lyMa(jCTxWC z>^wq1sAqc`vx`5F?T1lE5G56J#JP6c;BHAi!F)ot->;L!rm{DYPmsSPkMFlQ>9jcA zZ}}I+IwD%QRPKhCecpETHD;S6k+CiOId-?nkZ4lJgUoHfr*nDJ@c;pei9qo~tZ7ey zX>`Ce3dC&@M{+$kpy5AJ?2+Iggt7ncD0siF!L@%J=>LC%f$PD5Wg-kQ!2QT=4_cZd7ko2f-`N?YyIyI<|o_pa_> zDrAuQojHX|pQ2%>8@q*G&ZC_o53A9aUvo@U=99`)tz?CyQXCkQPkgK11|KV=JpM2f zET}Vwrg+ISYC}e7h6vwV9LkF?a~amV6_D`M(ZI!38fu3x!wd`GqmROFuY7^@5KlZd zaPcIFB|e z8X|Yo^W1ug)uTaFs`S*^^Cp+Ej)3#A5}C}0LFba;GAwiQ$OR0=<{~Dr9O3c@I`T6IA$Uj{3k)WJ|n~9O`~Nhz}cP66)}=Yb?6-w#WVEjx$)bBvW}$ z@q=oyF_lAuAhM)|tTtnF&9?X5E0Xa^)%2_tk#WaIkfN4Xu)&h9)(M79<)EYfx!|)y z!_>9?-F~_6#KGksKHR&JnvCXZ@>Ff=tk_(wC=2v)DNaAALVL-L<%Pc?oInMdMG*a% z#(0zwJUcy-Q`jh(%Fc6SauI2e+j(ymaC)_p{b4W^W?X_hT>$$ zCi$xI&CP`hC(CLknY=E81Xp+b2ng~1#^<|uW~tVf@Tzuc@M`IIh>$}`8ptGNPNcok z8Ou}f5RD0+#k3*TdTK)(9sOA7Txve+8qtgtnLi|$m{25uY+4hr48Nhq(=3i0yZ_$X z$-vi96PMmanpTwR;<|t=IW5yYW_GBQy z;cbez&)TMe2&ejh`EsVljl}eMp>ekMv@aIdjc#36G0$5uy@=18vCT5X6gAEbCxh5E znTfPoxLy~*Q7qzmRrOARV&X(|moMe~CfoCcerL!T7jAcW$$9melbv@O1^aHfQ}kqr zORL&>aRuH`6!Bm}?IFsKZvdK`NmR^xTS!F+$49dN9^vptG38TDiPMLr=F{0EK5`$e zO33I~#;WjeTK5T8ASILfe$hTzdnzpTd7+xw2a;P)b~DJ>qNn;BFK%;Ny!62r!25NrPyPGrr_ zcij&M$jAI<3Qo^M#($_Hy@tqe?V<#BEOb8+iO@fKgBa@N0J=Z=T-+wOpvIYT3BML0 zeTQPbOn`fq^kFY&#!Wg<@+s~GFMo!bqTx2DS)cH1^)Xr!`X!%}>7iJp&nKi#vo3xt zXNG_e?e;)p_KQ3+Hg!e1t!uLdPa|mVQ7Dq76#QF?)E3{9+)zy{1*^p;(AzrJigx=U z0;nJYDjsd|0TrN}4wO4!RS<%skohozqcj0Z<>xxfe{*E1Qn20!SH@*v&HqK!-zj)( z8j4cC4E~=-`#a@t2FZcv-r1mcO1jx*O=jRxh+JprRcENgIX^r=Lo~(1G6mLz6$|zB%1--4RUH23^Hq`W!ekh z&-=~?H-^*0rjB$+c)s1E+%IfV0S8HNAM~J~YvSHytwB4w;wonSjY7I&)#hJnUTd_x zY7q0#7wg6i&*Dx$IjJ?o#BUMzJ(({JLUQbQq$`qUx*xNt&HHqIBGQPVcjne2Ovnk< z-&PU!Rm&KrQc~-pcYYit9jVUT@;=((LgU~hRSM5zJA=v7_x3mTiJW)Ca!KVFzxGn4 zcvUf6z#PnSn#_@Igw9m_Kb2j1Ak=I3{|>TbEhI*kQo7lqGDTBKdMlA4ltKG)F~+X3 zmM$W6DJ9w3C>d?cj3r}BZdq>1TxN!mCCo))EZKhNJKXAh-{0?#AK$NM&htFyJfCx( z^PJ~AGiJv1$(H;_hl7OcaRJXnOJ7GF(&_SVg!ik+KCplDs4x0j4O(*{?Q+DMPV+~K z-Y(kB8eb=De*KMLZ?NQdXiTW>_73uXw$EM$7>FxQUw%`c8TUzAQMb*ed};IX-O;+K zD&iN6&fVKD>T&&CYjNfBJ=`M?X?QbQ|JwgxN0)>HX+yHm@2gxmsdR^)4u zk~L4_`fY+ICbJU~GBzeuY^QzUru84(%6WfXZRZgaCw|x&&OLGdCGx;v{HqJ&?0db1 zl>^3=o_4V(NCWj*y>*)g)QZeI1_@K$^_jE)S=YhoD?#I5y6e+7_xJ}0k*e$m& zv=~Ei3PY+60a6`tC;^fO8}VWcehHD|1&yjmz$bFAzc6<< zC5mVapGPmiW-ZLE2M`$;(hD=$>ddH}{HOfo@ieDc3~7aPjZ*}Mg#TFC?1Hd&@Sko{ zLIUpkv5rcHWBW|nR3yVwrO10k@zJ>m?Zi5S61X^ACs~Laa}UV1sy@XTq;~`UK&Jw| z27x?=XAe{oP+G`f6~EC#gb_!O2(+eks;FL$NNs(_!qt~0rqSNM_#jZ7+wP1=2 z?k$#w5W^1!(n1Igyk{vhLX!rV-!_G#hDx2NAbhmxiu!ziWc z*>mk4LfKT|amvtoiu6}@q;1n|TYG4MOEEFJwub%QxC$Y=H6D+Vr_beWOQJR3M%6^!cB=UzMuU z$39wPQ{6ge+gt};8mjwPV8eARxKHpQ`v=Hq8sMugDYLYV_%K!QKNj4{w%8M2X_k;2k?;@pPtMpbJ%Q!bIj`e&>2G{N*b=&0UlzIcaiES!YeV zlJ@}5f8Z;=Dt+i3(<@EAzS--IDE?H0T8x?OZ@lA0Uy7`hT&T6fep|P^il6cS8hm^Zg4l=`r=)I%K^vZNAsI(Qkr=ZI{SIv6^pse^7glynMZPZ zUmUP@)P%`dhR=7Bnl{xDolR4O+1c!cuX@9mTQz5eP0AvAkmNhSRclhpVyj>s^$e|i zwtQ5>HZ`8kzbb4`_3iMpjL+}vY7JV4I!YH^?GTr|=ORzjs)TqReEqB6ot0rYtJ=({ zQ;n7G=w)vFp{~*Pn#S4=74qVxB8vzTmzGjG$=@qh6U+~oUCO-7g4@&!zenym>7JQv zWcno$GYRHA%Wv}+?%z0)FwyGxTW5Fa1D$VPwBKOOhVT#N?q(fo&=q*G<%@M z9_BDwDX@h3Tj2ihTL``y9pmsk?J{fO=3U^RD(EfT^2`WS6>t0=7zE~K0S$@>wW|OP zO-*ZFA3}`)KGR3gTUfvv@X0R;)df|00m}DD(ZlxJPnaaTYjgJ%%9GIcc%B*HSio>m zpfUsy4OH30_Mn-Gn;9;%V@+kD!5@UvhmYSTYMV?yHV?LBXq1ljR*y-ox^w*UhO6tj zv$re6i@A<>CW~lpgF`gV4mQbCCNj8mgItp)6&qc{CTgg8QR5<34HkMKwD+44!g*DM zvQY+cP!S8)i4$hrcn$FgClgOE{iz+|nxF~8-Pb7yDs7t~Eb$w$Vh|twEF+8dLiGb+ z_$mI6&I>}A!+vb&$D^x}p_4Gv+*1`oBd;0iu#+Z(AlFJ1uN9#NeulbQ7O};KTEX=4 zRE5t9?1adM^3nvnuyTNx$mP*+GJ-%4Y7pI2gD0Nsze<>mo7go>ZaB7W0#}HS=xl#d zdX_ZpL>revm|w80w+A2AuwM#GohIFcP$u3k>xUg#tN?FfW!XAWH&bv-ZekV%6 z2J}7fW9Q=OXm^uW@j>}3NDr8yH*?2ZJ@YyI)^fa70Xtr#jP zZ`@_dkUHL)Krdy=(Bi|!_%5dC*lliNY{vE}GDv}tf>JOyxLFMBe^#K@AjGwH&UM3 zUVGelQ~_mz0Du-ZKnw(uQ7Ev|Gx0F}`#7-kjs#g7dXx&@a5&J$Z7J=hBSB|F zJ*)6&G4yUong+$3S?Ew*r>pw*P`gh-gJ0#?5oIZ?vXXRqcf;r_moHJ|fswFJbt8^3 zBm7I<{(q43*x#^M9#q|In~4bU&U-x&Wv=csb+IAb)WB)Bf6^e;&49|(Pw?azO@8GZ zNXVF*?x?S?9TjP^y;fF{mJ}vws@jkiUF=&$mmhX`A@9{NGlh+ve*5upp7L=Y+EO^K$_k1f;CMAWD>WUT6%aFvUXLARQ#8j_eJ;e)*l@;3Kd++n zuRLNv8@cB_}d%}Z=n3heyBjaqLL-fzfuKfYkC8pGHcN!4RwyLBCJ&odro4EoeuX(0V z^GwwkV0!KrBRoi7bc(4U#`ckXL-|DpWo%ZM8~%J?J3iDd^;4f_a#Y|8iTgt?YiHC` z#^>I!S`}_`Bvaj*W_tt~&um~r4WXqJp(XycwP#Ejo}SrOsZ7d0;WBH?a9&5-9<;B+ ze^rOR18ymt=9MLC#v9MZu9))(DO}F|!`+Z^qvb@nPTwhpVuTQBb($1SG;iG3h^z9l ztqBsTbZb#GQ*EjZhX7ADQ6^P83K0yG5r?a*8EFvQpa!;G*kMlPuwb#`k`Wws^qMqz zttegrGC188KE=;OXt4DYb-}~Qy|0&YMbUb2a9(rVYDV0&Pbt>&pIjBXf)AX~#So1@ zSiuN-kPDvdyTyWziYFyVE12dm0CS|s4+scZ97iGc6`?Q{5@VET4a;|QUMNFAppkuCD93lt%7VCiX>1aQ*1#!bj0u4J~&ClB|`%L zLwhuH|3QH*iU9rZ0yOhG%N3vns`P4NM{T6YYaz>ZH0kjNu`2}F2@U*4&KoMph zst9Z>0Ba4T5oWSr3%FocanEt;;L)&_unGQSQNchkC+Mh<9SST8;vTFTJfRyhHBpl= zH#VGbJAdQ$U2}3T`gJBP=Wt(V+b728`Caypr-%FLGp08yZv0{!&dT18A*LEx(Bij?r9feHdNGN0{g?T+hx?aM z_NNH3jZeprPNtfO(gg0{gmy>!p(-pK8Lok-RQ(d75%dHbphdToz94Lq712Y(3{Y|C ziANQki%&_ygYJzH6J2PYydgLs_JB1la)>xwi=j?+p?ho50U264GY<$X9748j;TmV$ zfsI6LxK;wE0*4NCgRh$x_Y(>^kX{U&;FW_(!l+jQCwL_gs8@z~3%nA9&Yz$*f=t*- zZ^Pg)6+KDv#15Wgus361VZ0SgK#1l)RodEUG6)3hBhk?PPe^Cc!&BZQRE_xQZrjoU zi2|CP_aE;}Qun5U1e2n8v>-o@$^%G{3-SQPE?yzO7K4M(jTVCA(>Y*{fgW|*+62@9 zAW~=Bq@lx4K&rLH&@&X^_gLsG&omzg0p56D)S!Y)5b#q31|`E;K_NnIF^WE%1x)C1 z7rMc57v+KDE)d!-RIm!Mi%0uzj(4JXxK5dKAmM?XY%odP2L@)Nmh2Q*61H`e2a+A& z0ZaI1Oh*?F*Sdy|bmV6{gp#|n9k%tPyG-`o$XNIjGWg?h-;MUq|L?}RR-Lf%3H9yU z;+?;?Z=RFuiOLT1`%9?556m%C|r+A7qP&k}ATq-fFw2(77 zP~civ|3RMIx3;Z#jKj~L9=!2Y%te1{?ihWndOTy>EHkPh?80>USVn2s>)~eP#Yd9igi+SDxQt?;+lGWSrizc=*xS+oWElA^S>J zfNLJJhrh-?O&9kpw;jl`9QnI5oA^)Z_8pX@Y=hMEoH9Dzc4VNK$}6}q(u8qMLC9Wq$Tr^dtHT92;S6!`- zbE`NTl=nI=mvw-~blp-M)JQw;Hzg6^l1-H#EP1$HeEgfv*?_#)bqgJ~tt49EMJn|C zVrF*Hx-0lL>>aYl8$vh@?YYkq!%xe4PSp#ZF|>j>lK4l5Pp_oC{L z3m()hD}DL0JnC1E^BeGcEU~>=g)dXo?mv(owVCg9#xK@)1vS}t(k4&OGWsiZ0oWR)9Hg#pJtkrR)(Yo%@v(Jp1iHPhnc~eyEruU zOZ%oS8r@O&^GA0xuG^!VLAtwC}x)5p+e?wWD`d5O@XP{9Bj>=zB!CX{$si-xaqdC$s}LbPMoC7LO|uuyzqrr2_*#C@$xx#iI|T}EOuPV(X6 zfR4wGu6noD-RXRsc!g}5FN)w5ci^@4M{7sUN?yfnLxsI?g2LRoas!o-* zY^@94%WRZ7Y+;;p*U|1EZC&%pqeq6Pe^c`Gd;3@7SiC`>%AJdkzoh5hU2`^bT`>3Y zm!zz~P$LBcmE@NR!F#7p9kc*l3v*5w=d5&!xhY+(6S;ao()InO9m0o~=o1vnmFGncW+c}X3YA7hf5|Z8@5loTgFVw+E|K-Hy68MvcF=GwPY2< z#!^^hF@pYVKGwZQ@L=JO1R{sHx>}i;AFy>aIP55e@LGZ#(3_7@5U?pA;_yp${dYE% zpV{%lGbO_ktm8>7=F1> Ja)A>;{s)sE+ + +int +main() +{ + using namespace date; + static_assert( std::is_nothrow_destructible{}, ""); + static_assert( std::is_nothrow_default_constructible{}, ""); + static_assert(!std::is_copy_constructible{}, ""); + static_assert(!std::is_copy_assignable{}, ""); + static_assert( std::is_nothrow_move_constructible{}, ""); + static_assert(!std::is_move_assignable{}, ""); +} diff --git a/third_party/date/test/tz_test/validate.cpp b/third_party/date/test/tz_test/validate.cpp new file mode 100644 index 0000000..2202b37 --- /dev/null +++ b/third_party/date/test/tz_test/validate.cpp @@ -0,0 +1,165 @@ +#include "date/tz.h" +#include + +void +test_info(const date::time_zone* zone, const date::sys_info& info) +{ + using namespace date; + using namespace std::chrono; + auto begin = info.begin; + auto end = info.end - microseconds{1}; + auto mid = begin + (end - begin) /2; + using sys_microseconds = sys_time; + using zoned_microseconds = zoned_time; + zoned_microseconds local{zone}; + + if (begin > sys_days{jan/1/1700}) + { + auto prev_local = local; + local = begin; + prev_local = begin - seconds{1}; + auto slocal = local.get_local_time(); + auto plocal = prev_local.get_local_time(); + if (plocal < slocal - seconds{1}) + { + assert(sys_microseconds{local} == begin); + try + { + local = plocal + (slocal - seconds{1} - plocal) / 2; + assert(false); + } + catch (const nonexistent_local_time&) + { + } + } + else if (plocal > slocal - seconds{1}) + { + try + { + local = slocal - seconds{1} + (plocal - (slocal - seconds{1})) / 2; + assert(false); + } + catch (const ambiguous_local_time&) + { + } + } + } + + local = mid; + assert(sys_microseconds{local} == mid); + + if (end < sys_days{jan/1/3000}) + { + local = end; + auto next_local = local; + next_local = info.end; + auto slocal = local.get_local_time(); + auto nlocal = next_local.get_local_time(); + if (nlocal < slocal + microseconds{1}) + { + try + { + local = nlocal + (slocal + microseconds{1} - nlocal) / 2; + assert(false); + } + catch (const ambiguous_local_time&) + { + } + } + else if (nlocal > slocal + microseconds{1}) + { + assert(sys_microseconds{local} == end); + try + { + local = slocal + microseconds{1} + + (nlocal - (slocal + microseconds{1})) / 2; + assert(false); + } + catch (const nonexistent_local_time&) + { + } + } + } +} + +void +tzmain() +{ + using namespace date; + using namespace std::chrono; + auto& db = get_tzdb(); + std::vector names; +#if USE_OS_TZDB + names.reserve(db.zones.size()); + for (auto& zone : db.zones) + names.push_back(zone.name()); +#else // !USE_OS_TZDB + names.reserve(db.zones.size() + db.links.size()); + for (auto& zone : db.zones) + names.push_back(zone.name()); + for (auto& link : db.links) + names.push_back(link.name()); + std::sort(names.begin(), names.end()); +#endif // !USE_OS_TZDB + std::cout << db.version << "\n\n"; + for (auto const& name : names) + { + std::cout << name << '\n'; + auto z = locate_zone(name); + auto begin = sys_days(jan/1/year::min()) + seconds{0}; + auto end = sys_days(jan/1/2035) + seconds{0}; + auto info = z->get_info(begin); + std::cout << "Initially: "; + if (info.offset >= seconds{0}) + std::cout << '+'; + std::cout << make_time(info.offset); + if (info.save == minutes{0}) + std::cout << " standard "; + else + std::cout << " daylight "; + std::cout << info.abbrev << '\n'; + test_info(z, info); + auto prev_offset = info.offset; + auto prev_abbrev = info.abbrev; + auto prev_save = info.save; + for (begin = info.end; begin < end; begin = info.end) + { + info = z->get_info(begin); + test_info(z, info); + if (info.offset == prev_offset && info.abbrev == prev_abbrev && + info.save == prev_save) + continue; + auto dp = floor(begin); + auto ymd = year_month_day(dp); + auto time = make_time(begin - dp); + std::cout << ymd << ' ' << time << "Z "; + if (info.offset >= seconds{0}) + std::cout << '+'; + std::cout << make_time(info.offset); + if (info.save == minutes{0}) + std::cout << " standard "; + else + std::cout << " daylight "; + std::cout << info.abbrev << '\n'; + prev_offset = info.offset; + prev_abbrev = info.abbrev; + prev_save = info.save; + } + std::cout << '\n'; + } +} + +int +main() +{ + try + { + tzmain(); + } + catch(const std::exception& ex) + { + std::cout << "An exception occured: " << ex.what() << std::endl; + return EXIT_FAILURE; + } + return EXIT_SUCCESS; +} diff --git a/third_party/date/test/tz_test/zone.pass.cpp b/third_party/date/test/tz_test/zone.pass.cpp new file mode 100644 index 0000000..a0b003c --- /dev/null +++ b/third_party/date/test/tz_test/zone.pass.cpp @@ -0,0 +1,37 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015, 2016 Howard Hinnant +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "tz.h" +#include + +int +main() +{ + using namespace std; + using namespace date; + static_assert( is_nothrow_destructible{}, ""); + static_assert(!is_default_constructible{}, ""); + static_assert(!is_copy_constructible{}, ""); + static_assert(!is_copy_assignable{}, ""); + static_assert( is_nothrow_move_constructible{}, ""); + static_assert( is_nothrow_move_assignable{}, ""); +} diff --git a/third_party/date/test/tz_test/zoned_time.pass.cpp b/third_party/date/test/tz_test/zoned_time.pass.cpp new file mode 100644 index 0000000..70f3a83 --- /dev/null +++ b/third_party/date/test/tz_test/zoned_time.pass.cpp @@ -0,0 +1,464 @@ +// The MIT License (MIT) +// +// Copyright (c) 2017 Howard Hinnant +// +// 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. + +// template +// class zoned_time +// { +// public: +// using duration = typename std::common_type::type; +// +// zoned_time(); +// zoned_time(const sys_time& st); +// explicit zoned_time(const time_zone* z); +// explicit zoned_time(std::string_view name); +// +// template , +// sys_time>::value +// >::type> +// zoned_time(const zoned_time& zt) NOEXCEPT; +// +// zoned_time(const time_zone* z, const local_time& tp); +// zoned_time(std::string_view name, const local_time& tp); +// zoned_time(const time_zone* z, const local_time& tp, choose c); +// zoned_time(std::string_view name, const local_time& tp, choose c); +// +// zoned_time(const time_zone* z, const zoned_time& zt); +// zoned_time(std::string_view name, const zoned_time& zt); +// zoned_time(const time_zone* z, const zoned_time& zt, choose); +// zoned_time(std::string_view name, const zoned_time& zt, choose); +// +// zoned_time(const time_zone* z, const sys_time& st); +// zoned_time(std::string_view name, const sys_time& st); +// +// zoned_time& operator=(const sys_time& st); +// zoned_time& operator=(const local_time& ut); +// +// explicit operator sys_time() const; +// explicit operator local_time() const; +// +// const time_zone* get_time_zone() const; +// local_time get_local_time() const; +// sys_time get_sys_time() const; +// sys_info get_info() const; +// +// template +// friend +// bool +// operator==(const zoned_time& x, const zoned_time& y); +// +// template +// friend +// std::basic_ostream& +// operator<<(std::basic_ostream& os, const zoned_time& t); +// }; +// +// using zoned_seconds = zoned_time; +// +// template +// inline +// bool +// operator!=(const zoned_time& x, const zoned_time& y); +// +// template +// zoned_time(sys_time) +// -> zoned_time>; +// +// template +// zoned_time(Zone, sys_time) +// -> zoned_time>; +// +// template +// zoned_time(Zone, local_time, choose = choose::earliest) +// -> zoned_time>; +// +// template +// zoned_time(Zone, zoned_time, choose = choose::earliest) +// -> zoned_time>; + +#include "tz.h" +#include +#include +#include + +int +main() +{ + using namespace std; + using namespace std::chrono; + using namespace date; + static_assert( is_nothrow_destructible{}, ""); + static_assert( is_default_constructible{}, ""); + static_assert( is_nothrow_copy_constructible{}, ""); + static_assert( is_nothrow_copy_assignable{}, ""); + static_assert( is_nothrow_move_constructible{}, ""); + static_assert( is_nothrow_move_assignable{}, ""); + + static_assert(is_same::duration, seconds>{}, ""); + static_assert(is_same{}, ""); + static_assert(is_same::duration, milliseconds>{}, ""); + + // zoned_time(); + { + zoned_seconds zt; + assert(zt.get_sys_time() == sys_seconds{}); + assert(zt.get_time_zone()->name() == "Etc/UTC"); + } + + // zoned_time(const sys_time& st); + { + static_assert(!is_convertible{}, ""); + static_assert( is_constructible{}, ""); + static_assert( is_convertible{}, ""); + static_assert(!is_convertible, zoned_seconds>{}, ""); + static_assert(!is_constructible>{}, ""); + + auto now = floor(system_clock::now()); + zoned_seconds zt = now; + assert(zt.get_sys_time() == now); + assert(zt.get_time_zone()->name() == "Etc/UTC"); + } + + // explicit zoned_time(const time_zone* z); + { + static_assert(!is_convertible{}, ""); + static_assert( is_constructible{}, ""); + zoned_seconds zt{locate_zone("America/New_York")}; + assert(zt.get_sys_time() == sys_seconds{}); + assert(zt.get_time_zone()->name() == "America/New_York"); + } + + // explicit zoned_time(std::string_view name); + { + static_assert(!is_convertible{}, ""); + static_assert( is_constructible{}, ""); + static_assert( is_constructible{}, ""); + static_assert( is_constructible{}, ""); + zoned_seconds zt{"America/New_York"}; + assert(zt.get_sys_time() == sys_seconds{}); + assert(zt.get_time_zone()->name() == "America/New_York"); + } + + // template , + // sys_time>::value + // >::type> + // zoned_time(const zoned_time& zt) NOEXCEPT; + { + static_assert( is_convertible, zoned_seconds>{}, ""); + static_assert(!is_constructible, zoned_seconds>{}, ""); + zoned_time zt1{"America/New_York", sys_days{2017_y/jul/5}}; + zoned_seconds zt2 = zt1; + assert(zt2.get_sys_time() == sys_days{2017_y/jul/5}); + assert(zt2.get_time_zone()->name() == "America/New_York"); + } + + // zoned_time(const time_zone* z, const local_time& tp); + { + static_assert( is_constructible{}, ""); + zoned_seconds zt = {locate_zone("America/New_York"), local_days{2017_y/jul/5}}; + assert(zt.get_local_time() == local_days{2017_y/jul/5}); + assert(zt.get_time_zone()->name() == "America/New_York"); + try + { + zoned_seconds zt1 = {locate_zone("America/New_York"), + local_days{2017_y/mar/sun[2]} + hours{2} + minutes{15}}; + assert(false); + } + catch(const nonexistent_local_time&) + { + } + try + { + zoned_seconds zt1 = {locate_zone("America/New_York"), + local_days{2017_y/nov/sun[1]} + hours{1} + minutes{15}}; + assert(false); + } + catch(const ambiguous_local_time&) + { + } + } + + // zoned_time(std::string_view name, const local_time& tp); + { + static_assert( is_constructible{}, ""); + static_assert( is_constructible{}, ""); + zoned_seconds zt = {"America/New_York", local_days{2017_y/jul/5}}; + assert(zt.get_local_time() == local_days{2017_y/jul/5}); + assert(zt.get_time_zone()->name() == "America/New_York"); + try + { + zoned_seconds zt1 = {"America/New_York", + local_days{2017_y/mar/sun[2]} + hours{2} + minutes{15}}; + assert(false); + } + catch(const nonexistent_local_time&) + { + } + try + { + zoned_seconds zt1 = {"America/New_York", + local_days{2017_y/nov/sun[1]} + hours{1} + minutes{15}}; + assert(false); + } + catch(const ambiguous_local_time&) + { + } + } + + // zoned_time(const time_zone* z, const local_time& tp, choose c); + { + static_assert( is_constructible{}, ""); + zoned_seconds zt = {locate_zone("America/New_York"), + local_days{2017_y/jul/5} + hours{2} + minutes{15}, + choose::earliest}; + assert(zt.get_sys_time() == sys_days{2017_y/jul/5} + hours{6} + minutes{15}); + assert(zt.get_time_zone()->name() == "America/New_York"); + + zt = {locate_zone("America/New_York"), + local_days{2017_y/jul/5} + hours{2} + minutes{15}, + choose::latest}; + assert(zt.get_sys_time() == sys_days{2017_y/jul/5} + hours{6} + minutes{15}); + assert(zt.get_time_zone()->name() == "America/New_York"); + + static_assert( is_constructible{}, ""); + zoned_seconds zt1 = {locate_zone("America/New_York"), + local_days{2017_y/mar/sun[2]} + hours{2} + minutes{15}, + choose::earliest}; + assert(zt1.get_sys_time() == sys_days{2017_y/mar/12} + hours{7}); + assert(zt1.get_time_zone()->name() == "America/New_York"); + + zoned_seconds zt2 = {locate_zone("America/New_York"), + local_days{2017_y/mar/sun[2]} + hours{2} + minutes{15}, + choose::latest}; + assert(zt2.get_sys_time() == sys_days{2017_y/mar/12} + hours{7}); + assert(zt2.get_time_zone()->name() == "America/New_York"); + + zoned_seconds zt3 = {locate_zone("America/New_York"), + local_days{2017_y/nov/sun[1]} + hours{1} + minutes{15}, + choose::earliest}; + assert(zt3.get_sys_time() == sys_days{2017_y/nov/5} + hours{5} + minutes{15}); + assert(zt3.get_time_zone()->name() == "America/New_York"); + + zoned_seconds zt4 = {locate_zone("America/New_York"), + local_days{2017_y/nov/sun[1]} + hours{1} + minutes{15}, + choose::latest}; + assert(zt4.get_sys_time() == sys_days{2017_y/nov/5} + hours{6} + minutes{15}); + assert(zt4.get_time_zone()->name() == "America/New_York"); + } + + // zoned_time(std::string_view name, const local_time& tp, choose c); + { + static_assert( is_constructible{}, ""); + static_assert( is_constructible{}, ""); + zoned_seconds zt = {"America/New_York", + local_days{2017_y/jul/5} + hours{2} + minutes{15}, + choose::earliest}; + assert(zt.get_sys_time() == sys_days{2017_y/jul/5} + hours{6} + minutes{15}); + assert(zt.get_time_zone()->name() == "America/New_York"); + + zt = {"America/New_York", + local_days{2017_y/jul/5} + hours{2} + minutes{15}, + choose::latest}; + assert(zt.get_sys_time() == sys_days{2017_y/jul/5} + hours{6} + minutes{15}); + assert(zt.get_time_zone()->name() == "America/New_York"); + + static_assert( is_constructible{}, ""); + zoned_seconds zt1 = {"America/New_York", + local_days{2017_y/mar/sun[2]} + hours{2} + minutes{15}, + choose::earliest}; + assert(zt1.get_sys_time() == sys_days{2017_y/mar/12} + hours{7}); + assert(zt1.get_time_zone()->name() == "America/New_York"); + + zoned_seconds zt2 = {"America/New_York", + local_days{2017_y/mar/sun[2]} + hours{2} + minutes{15}, + choose::latest}; + assert(zt2.get_sys_time() == sys_days{2017_y/mar/12} + hours{7}); + assert(zt2.get_time_zone()->name() == "America/New_York"); + + zoned_seconds zt3 = {"America/New_York", + local_days{2017_y/nov/sun[1]} + hours{1} + minutes{15}, + choose::earliest}; + assert(zt3.get_sys_time() == sys_days{2017_y/nov/5} + hours{5} + minutes{15}); + assert(zt3.get_time_zone()->name() == "America/New_York"); + + zoned_seconds zt4 = {"America/New_York", + local_days{2017_y/nov/sun[1]} + hours{1} + minutes{15}, + choose::latest}; + assert(zt4.get_sys_time() == sys_days{2017_y/nov/5} + hours{6} + minutes{15}); + assert(zt4.get_time_zone()->name() == "America/New_York"); + } + + // zoned_time(const time_zone* z, const sys_time& st); + { + static_assert( is_constructible{}, ""); + + zoned_seconds zt = {locate_zone("America/New_York"), + sys_days{2017_y/jul/5} + hours{2} + minutes{15}}; + assert(zt.get_sys_time() == sys_days{2017_y/jul/5} + hours{2} + minutes{15}); + assert(zt.get_time_zone()->name() == "America/New_York"); + } + + // zoned_time(std::string_view name, const sys_time& st); + { + static_assert( is_constructible{}, ""); + static_assert( is_constructible{}, ""); + + zoned_seconds zt = {"America/New_York", + sys_days{2017_y/jul/5} + hours{2} + minutes{15}}; + assert(zt.get_sys_time() == sys_days{2017_y/jul/5} + hours{2} + minutes{15}); + assert(zt.get_time_zone()->name() == "America/New_York"); + } + + // zoned_time& operator=(const sys_time& st); + { + static_assert( is_assignable{}, ""); + + zoned_seconds zt{"America/New_York"}; + zt = sys_days{2017_y/jul/5}; + assert(zt.get_sys_time() == sys_days{2017_y/jul/5}); + assert(zt.get_time_zone()->name() == "America/New_York"); + } + + // zoned_time& operator=(const local_time& st); + { + static_assert( is_assignable{}, ""); + + zoned_seconds zt{"America/New_York"}; + zt = local_days{2017_y/jul/5}; + assert(zt.get_local_time() == local_days{2017_y/jul/5}); + assert(zt.get_time_zone()->name() == "America/New_York"); + try + { + zt = {"America/New_York", + local_days{2017_y/mar/sun[2]} + hours{2} + minutes{15}}; + assert(false); + } + catch(const nonexistent_local_time&) + { + assert(zt.get_local_time() == local_days{2017_y/jul/5}); + assert(zt.get_time_zone()->name() == "America/New_York"); + } + try + { + zt = {"America/New_York", + local_days{2017_y/nov/sun[1]} + hours{1} + minutes{15}}; + assert(false); + } + catch(const ambiguous_local_time&) + { + assert(zt.get_local_time() == local_days{2017_y/jul/5}); + assert(zt.get_time_zone()->name() == "America/New_York"); + } + } + + // explicit operator sys_time() const; + { + static_assert(!is_convertible{}, ""); + static_assert( is_constructible{}, ""); + auto now = floor(system_clock::now()); + const zoned_seconds zt = {"America/New_York", now}; + assert(sys_seconds{zt} == now); + } + + // explicit operator local_time() const; + { + static_assert(!is_convertible{}, ""); + static_assert( is_constructible{}, ""); + auto now = local_days{2017_y/jul/5} + hours{23} + minutes{1} + seconds{48}; + const zoned_seconds zt = {"America/New_York", now}; + assert(local_seconds{zt} == now); + } + + // const time_zone* get_time_zone() const; + { + const zoned_seconds zt{"America/New_York"}; + assert(zt.get_time_zone() == locate_zone("America/New_York")); + } + + // local_time get_local_time() const; + { + const zoned_seconds zt{"America/New_York", sys_days{2017_y/jul/6} + + hours{3} + minutes{7} + seconds{9}}; + assert(zt.get_local_time() == local_days{2017_y/jul/5} + + hours{23} + minutes{7} + seconds{9}); + } + + // sys_time get_sys_time() const; + { + const zoned_seconds zt{"America/New_York", sys_days{2017_y/jul/6} + + hours{3} + minutes{7} + seconds{9}}; + assert(zt.get_sys_time() == sys_days{2017_y/jul/6} + + hours{3} + minutes{7} + seconds{9}); + } + + // sys_info get_info() const; + { + const zoned_seconds zt{"America/New_York", sys_days{2017_y/jul/6} + + hours{3} + minutes{7} + seconds{9}}; + auto info = zt.get_info(); + assert(info.begin == sys_days{2017_y/mar/12} + hours{7}); + assert(info.end == sys_days{2017_y/nov/5} + hours{6}); + assert(info.offset == hours{-4}); + assert(info.save != minutes{0}); + assert(info.abbrev == "EDT"); + } + + // template + // bool + // operator==(const zoned_time& x, const zoned_time& y); + { + const zoned_seconds zt{"America/New_York", sys_days{2017_y/jul/6} + + hours{3} + minutes{7} + seconds{9}}; + const zoned_seconds zt1{"America/New_York", sys_days{2017_y/jul/6} + + hours{3} + minutes{7} + seconds{10}}; + assert(zt == zt); + assert(!(zt == zt1)); + } + + // template + // bool + // operator!=(const zoned_time& x, const zoned_time& y); + { + const zoned_seconds zt{"America/New_York", sys_days{2017_y/jul/6} + + hours{3} + minutes{7} + seconds{9}}; + const zoned_seconds zt1{"America/New_York", sys_days{2017_y/jul/6} + + hours{3} + minutes{7} + seconds{10}}; + assert(!(zt != zt)); + assert(zt != zt1); + } + + // template + // std::basic_ostream& + // operator<<(std::basic_ostream& os, const zoned_time& t); + { + const zoned_seconds zt{"America/New_York", sys_days{2017_y/jul/6} + + hours{3} + minutes{7} + seconds{9}}; + std::ostringstream test; + test << zt; + assert(test.str() == "2017-07-05 23:07:09 EDT"); + } +} diff --git a/third_party/date/test/tz_test/zoned_time_deduction.pass.cpp b/third_party/date/test/tz_test/zoned_time_deduction.pass.cpp new file mode 100644 index 0000000..e62e11a --- /dev/null +++ b/third_party/date/test/tz_test/zoned_time_deduction.pass.cpp @@ -0,0 +1,246 @@ +// The MIT License (MIT) +// +// Copyright (c) 2019 Tomasz KamiÅ„ski +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "tz.h" +#include "OffsetZone.h" +#include +#include +#include + +#if HAS_DEDUCTION_GUIDES +#include + +template +void testDeductionFrom(Source&& s) +{ + using namespace date; + using namespace std::chrono; + + // No time point + { + zoned_time zt(std::forward(s)); + static_assert(std::is_same>::value, ""); + } + + // sys_time + { + sys_days sd(2017_y/feb/20); + zoned_time ztd(std::forward(s), sd); + static_assert(std::is_same>::value, ""); + + sys_time ss(sd); + zoned_time zts(std::forward(s), ss); + static_assert(std::is_same>::value, ""); + + sys_time sms(ss); + zoned_time ztms(std::forward(s), sms); + static_assert(std::is_same>::value, ""); + } + + // local_time + { + local_days ld(2017_y/feb/20); + zoned_time ztd(std::forward(s), ld); + static_assert(std::is_same>::value, ""); + + local_time ls(ld); + zoned_time zts(std::forward(s), ls); + static_assert(std::is_same>::value, ""); + + local_time lms(ls); + zoned_time ztms(std::forward(s), lms); + static_assert(std::is_same>::value, ""); + } + + // local_time, choose + { + local_days ld(2017_y/feb/20); + zoned_time ztd(std::forward(s), ld, choose::earliest); + static_assert(std::is_same>::value, ""); + + local_time ls(ld); + zoned_time zts(std::forward(s), ls, choose::earliest); + static_assert(std::is_same>::value, ""); + + local_time lms(ls); + zoned_time ztms(std::forward(s), lms, choose::earliest); + static_assert(std::is_same>::value, ""); + } + + // zoned_time + { + zoned_time zd(sys_days(2017_y/feb/20)); + zoned_time ztd(std::forward(s), zd); + static_assert(std::is_same>::value, ""); + + zoned_time zs(zd); + zoned_time zts(std::forward(s), zs); + static_assert(std::is_same>::value, ""); + + zoned_time zms(zs); + zoned_time ztms(std::forward(s), zms); + static_assert(std::is_same>::value, ""); + } + + // zoned_time, choose + { + zoned_time zd(sys_days(2017_y/feb/20)); + zoned_time ztd(std::forward(s), zd, choose::earliest); + static_assert(std::is_same>::value, ""); + + zoned_time zs(zd); + zoned_time zts(std::forward(s), zs, choose::earliest); + static_assert(std::is_same>::value, ""); + + zoned_time zms(zs); + zoned_time ztms(std::forward(s), zms, choose::earliest); + static_assert(std::is_same>::value, ""); + } +} + +struct MyString +{ + MyString(std::string s) : ms(std::move(s)) {} + + operator std::string_view() const { return ms; } + +private: + std::string ms; +}; + +struct OnlyLValueString +{ + OnlyLValueString(std::string s) : ms(std::move(s)) {} + + operator std::string_view() & { return ms; } + +private: + std::string ms; +}; + +#endif // HAS_DEDUCTION_GUIDES + +template +T const& to_const(T& t) { return t; } + + +int +main() +{ + using namespace date; + using namespace std::chrono; + +#if HAS_DEDUCTION_GUIDES + // no arguments + { + zoned_time zt{}; + static_assert(std::is_same>::value, ""); + } + + // zoned_time + { + zoned_time zd(sys_days(2017_y/feb/20)); + zoned_time ztd(zd); + static_assert(std::is_same>::value, ""); + + zoned_time zs(zd); + zoned_time zts(zs); + static_assert(std::is_same>::value, ""); + + zoned_time zms(zs); + zoned_time ztms(zms); + static_assert(std::is_same>::value, ""); + } + + // sys_time + { + sys_days sd(2017_y/feb/20); + zoned_time ztd(sd); + static_assert(std::is_same>::value, ""); + + sys_time ss(sd); + zoned_time zts(ss); + static_assert(std::is_same>::value, ""); + + sys_time sms(ss); + zoned_time ztms(sms); + static_assert(std::is_same>::value, ""); + } + + // time_zone const* + { + time_zone const* tz = current_zone(); + testDeductionFrom(tz); + testDeductionFrom(to_const(tz)); + testDeductionFrom(std::move(tz)); + } + + // char const* + { + char const* tz = "Europe/Warsaw"; + testDeductionFrom(tz); + testDeductionFrom(to_const(tz)); + testDeductionFrom(std::move(tz)); + } + + // std::string + { + std::string tz = "Europe/Warsaw"; + testDeductionFrom(tz); + testDeductionFrom(to_const(tz)); + testDeductionFrom(std::move(tz)); + } + + // std::string_view + { + std::string_view tz = "Europe/Warsaw"; + testDeductionFrom(tz); + testDeductionFrom(to_const(tz)); + testDeductionFrom(std::move(tz)); + } + + // MyString + { + MyString tz("Europe/Warsaw"); + testDeductionFrom(tz); + testDeductionFrom(to_const(tz)); + testDeductionFrom(std::move(tz)); + } + + // custom time zone + { + OffsetZone tz(minutes(45)); + testDeductionFrom(tz); + testDeductionFrom(to_const(tz)); + testDeductionFrom(std::move(tz)); + } + + // OnlyLValue + { + OnlyLValueString tz("Europe/Warsaw"); + testDeductionFrom(tz); + //testDeductionFrom(to_const(tz)); + //testDeductionFrom(std::move(tz)); + } + +#endif // HAS_DEDUCTION_GUIDES +} diff --git a/third_party/date/test_fail.sh b/third_party/date/test_fail.sh new file mode 100755 index 0000000..6562647 --- /dev/null +++ b/third_party/date/test_fail.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +echo $1 +eval $1 + +if [ $? -eq 0 ]; then + exit 0; +fi +exit 1; + diff --git a/third_party/fmt/.clang-format b/third_party/fmt/.clang-format new file mode 100644 index 0000000..df55d34 --- /dev/null +++ b/third_party/fmt/.clang-format @@ -0,0 +1,8 @@ +# Run manually to reformat a file: +# clang-format -i --style=file +Language: Cpp +BasedOnStyle: Google +IndentPPDirectives: AfterHash +IndentCaseLabels: false +AlwaysBreakTemplateDeclarations: false +DerivePointerAlignment: false diff --git a/third_party/fmt/CMakeLists.txt b/third_party/fmt/CMakeLists.txt new file mode 100644 index 0000000..4b928ae --- /dev/null +++ b/third_party/fmt/CMakeLists.txt @@ -0,0 +1,453 @@ +cmake_minimum_required(VERSION 3.8...3.26) + +# Fallback for using newer policies on CMake <3.12. +if (${CMAKE_VERSION} VERSION_LESS 3.12) + cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}) +endif () + +# Determine if fmt is built as a subproject (using add_subdirectory) +# or if it is the master project. +if (NOT DEFINED FMT_MASTER_PROJECT) + set(FMT_MASTER_PROJECT OFF) + if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) + set(FMT_MASTER_PROJECT ON) + message(STATUS "CMake version: ${CMAKE_VERSION}") + endif () +endif () + +# Joins arguments and places the results in ${result_var}. +function(join result_var) + set(result "") + foreach (arg ${ARGN}) + set(result "${result}${arg}") + endforeach () + set(${result_var} "${result}" PARENT_SCOPE) +endfunction() + +# DEPRECATED! Should be merged into add_module_library. +function(enable_module target) + if (MSVC) + set(BMI ${CMAKE_CURRENT_BINARY_DIR}/${target}.ifc) + target_compile_options(${target} + PRIVATE /interface /ifcOutput ${BMI} + INTERFACE /reference fmt=${BMI}) + set_target_properties(${target} PROPERTIES ADDITIONAL_CLEAN_FILES ${BMI}) + set_source_files_properties(${BMI} PROPERTIES GENERATED ON) + endif () +endfunction() + +# Adds a library compiled with C++20 module support. +# `enabled` is a CMake variables that specifies if modules are enabled. +# If modules are disabled `add_module_library` falls back to creating a +# non-modular library. +# +# Usage: +# add_module_library( [sources...] FALLBACK [sources...] [IF enabled]) +function(add_module_library name) + cmake_parse_arguments(AML "" "IF" "FALLBACK" ${ARGN}) + set(sources ${AML_UNPARSED_ARGUMENTS}) + + add_library(${name}) + set_target_properties(${name} PROPERTIES LINKER_LANGUAGE CXX) + + if (NOT ${${AML_IF}}) + # Create a non-modular library. + target_sources(${name} PRIVATE ${AML_FALLBACK}) + return() + endif () + + # Modules require C++20. + target_compile_features(${name} PUBLIC cxx_std_20) + if (CMAKE_COMPILER_IS_GNUCXX) + target_compile_options(${name} PUBLIC -fmodules-ts) + endif () + + # `std` is affected by CMake options and may be higher than C++20. + get_target_property(std ${name} CXX_STANDARD) + + if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(pcms) + foreach (src ${sources}) + get_filename_component(pcm ${src} NAME_WE) + set(pcm ${pcm}.pcm) + + # Propagate -fmodule-file=*.pcm to targets that link with this library. + target_compile_options( + ${name} PUBLIC -fmodule-file=${CMAKE_CURRENT_BINARY_DIR}/${pcm}) + + # Use an absolute path to prevent target_link_libraries prepending -l + # to it. + set(pcms ${pcms} ${CMAKE_CURRENT_BINARY_DIR}/${pcm}) + add_custom_command( + OUTPUT ${pcm} + COMMAND ${CMAKE_CXX_COMPILER} + -std=c++${std} -x c++-module --precompile -c + -o ${pcm} ${CMAKE_CURRENT_SOURCE_DIR}/${src} + "-I$,;-I>" + # Required by the -I generator expression above. + COMMAND_EXPAND_LISTS + DEPENDS ${src}) + endforeach () + + # Add .pcm files as sources to make sure they are built before the library. + set(sources) + foreach (pcm ${pcms}) + get_filename_component(pcm_we ${pcm} NAME_WE) + set(obj ${pcm_we}.o) + # Use an absolute path to prevent target_link_libraries prepending -l. + set(sources ${sources} ${pcm} ${CMAKE_CURRENT_BINARY_DIR}/${obj}) + add_custom_command( + OUTPUT ${obj} + COMMAND ${CMAKE_CXX_COMPILER} $ + -c -o ${obj} ${pcm} + DEPENDS ${pcm}) + endforeach () + endif () + target_sources(${name} PRIVATE ${sources}) +endfunction() + +include(CMakeParseArguments) + +# Sets a cache variable with a docstring joined from multiple arguments: +# set( ... CACHE ...) +# This allows splitting a long docstring for readability. +function(set_verbose) + # cmake_parse_arguments is broken in CMake 3.4 (cannot parse CACHE) so use + # list instead. + list(GET ARGN 0 var) + list(REMOVE_AT ARGN 0) + list(GET ARGN 0 val) + list(REMOVE_AT ARGN 0) + list(REMOVE_AT ARGN 0) + list(GET ARGN 0 type) + list(REMOVE_AT ARGN 0) + join(doc ${ARGN}) + set(${var} ${val} CACHE ${type} ${doc}) +endfunction() + +# Set the default CMAKE_BUILD_TYPE to Release. +# This should be done before the project command since the latter can set +# CMAKE_BUILD_TYPE itself (it does so for nmake). +if (FMT_MASTER_PROJECT AND NOT CMAKE_BUILD_TYPE) + set_verbose(CMAKE_BUILD_TYPE Release CACHE STRING + "Choose the type of build, options are: None(CMAKE_CXX_FLAGS or " + "CMAKE_C_FLAGS used) Debug Release RelWithDebInfo MinSizeRel.") +endif () + +project(FMT CXX) +include(GNUInstallDirs) +set_verbose(FMT_INC_DIR ${CMAKE_INSTALL_INCLUDEDIR} CACHE STRING + "Installation directory for include files, a relative path that " + "will be joined with ${CMAKE_INSTALL_PREFIX} or an absolute path.") + +option(FMT_PEDANTIC "Enable extra warnings and expensive tests." OFF) +option(FMT_WERROR "Halt the compilation with an error on compiler warnings." + OFF) + +# Options that control generation of various targets. +option(FMT_DOC "Generate the doc target." ${FMT_MASTER_PROJECT}) +option(FMT_INSTALL "Generate the install target." ON) +option(FMT_TEST "Generate the test target." ${FMT_MASTER_PROJECT}) +option(FMT_FUZZ "Generate the fuzz target." OFF) +option(FMT_CUDA_TEST "Generate the cuda-test target." OFF) +option(FMT_OS "Include core requiring OS (Windows/Posix) " ON) +option(FMT_MODULE "Build a module instead of a traditional library." OFF) +option(FMT_SYSTEM_HEADERS "Expose headers with marking them as system." OFF) + +if (FMT_TEST AND FMT_MODULE) + # The tests require {fmt} to be compiled as traditional library + message(STATUS "Testing is incompatible with build mode 'module'.") +endif () +set(FMT_SYSTEM_HEADERS_ATTRIBUTE "") +if (FMT_SYSTEM_HEADERS) + set(FMT_SYSTEM_HEADERS_ATTRIBUTE SYSTEM) +endif () +if (CMAKE_SYSTEM_NAME STREQUAL "MSDOS") + set(FMT_TEST OFF) + message(STATUS "MSDOS is incompatible with gtest") +endif () + +# Get version from core.h +file(READ include/fmt/core.h core_h) +if (NOT core_h MATCHES "FMT_VERSION ([0-9]+)([0-9][0-9])([0-9][0-9])") + message(FATAL_ERROR "Cannot get FMT_VERSION from core.h.") +endif () +# Use math to skip leading zeros if any. +math(EXPR CPACK_PACKAGE_VERSION_MAJOR ${CMAKE_MATCH_1}) +math(EXPR CPACK_PACKAGE_VERSION_MINOR ${CMAKE_MATCH_2}) +math(EXPR CPACK_PACKAGE_VERSION_PATCH ${CMAKE_MATCH_3}) +join(FMT_VERSION ${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}. + ${CPACK_PACKAGE_VERSION_PATCH}) +message(STATUS "Version: ${FMT_VERSION}") + +message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") + +if (NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin) +endif () + +set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} + "${CMAKE_CURRENT_SOURCE_DIR}/support/cmake") + +include(CheckCXXCompilerFlag) +include(JoinPaths) + +if (FMT_MASTER_PROJECT AND NOT DEFINED CMAKE_CXX_VISIBILITY_PRESET) + set_verbose(CMAKE_CXX_VISIBILITY_PRESET hidden CACHE STRING + "Preset for the export of private symbols") + set_property(CACHE CMAKE_CXX_VISIBILITY_PRESET PROPERTY STRINGS + hidden default) +endif () + +if (FMT_MASTER_PROJECT AND NOT DEFINED CMAKE_VISIBILITY_INLINES_HIDDEN) + set_verbose(CMAKE_VISIBILITY_INLINES_HIDDEN ON CACHE BOOL + "Whether to add a compile flag to hide symbols of inline functions") +endif () + +if (CMAKE_CXX_COMPILER_ID MATCHES "GNU") + set(PEDANTIC_COMPILE_FLAGS -pedantic-errors -Wall -Wextra -pedantic + -Wold-style-cast -Wundef + -Wredundant-decls -Wwrite-strings -Wpointer-arith + -Wcast-qual -Wformat=2 -Wmissing-include-dirs + -Wcast-align + -Wctor-dtor-privacy -Wdisabled-optimization + -Winvalid-pch -Woverloaded-virtual + -Wconversion -Wundef + -Wno-ctor-dtor-privacy -Wno-format-nonliteral) + if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.6) + set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS} + -Wno-dangling-else -Wno-unused-local-typedefs) + endif () + if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0) + set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS} -Wdouble-promotion + -Wtrampolines -Wzero-as-null-pointer-constant -Wuseless-cast + -Wvector-operation-performance -Wsized-deallocation -Wshadow) + endif () + if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 6.0) + set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS} -Wshift-overflow=2 + -Wnull-dereference -Wduplicated-cond) + endif () + set(WERROR_FLAG -Werror) +endif () + +if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(PEDANTIC_COMPILE_FLAGS -Wall -Wextra -pedantic -Wconversion -Wundef + -Wdeprecated -Wweak-vtables -Wshadow + -Wno-gnu-zero-variadic-macro-arguments) + check_cxx_compiler_flag(-Wzero-as-null-pointer-constant HAS_NULLPTR_WARNING) + if (HAS_NULLPTR_WARNING) + set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS} + -Wzero-as-null-pointer-constant) + endif () + set(WERROR_FLAG -Werror) +endif () + +if (MSVC) + set(PEDANTIC_COMPILE_FLAGS /W3) + set(WERROR_FLAG /WX) +endif () + +if (FMT_MASTER_PROJECT AND CMAKE_GENERATOR MATCHES "Visual Studio") + # If Microsoft SDK is installed create script run-msbuild.bat that + # calls SetEnv.cmd to set up build environment and runs msbuild. + # It is useful when building Visual Studio projects with the SDK + # toolchain rather than Visual Studio. + include(FindSetEnv) + if (WINSDK_SETENV) + set(MSBUILD_SETUP "call \"${WINSDK_SETENV}\"") + endif () + # Set FrameworkPathOverride to get rid of MSB3644 warnings. + join(netfxpath + "C:\\Program Files\\Reference Assemblies\\Microsoft\\Framework\\" + ".NETFramework\\v4.0") + file(WRITE run-msbuild.bat " + ${MSBUILD_SETUP} + ${CMAKE_MAKE_PROGRAM} -p:FrameworkPathOverride=\"${netfxpath}\" %*") +endif () + +function(add_headers VAR) + set(headers ${${VAR}}) + foreach (header ${ARGN}) + set(headers ${headers} include/fmt/${header}) + endforeach() + set(${VAR} ${headers} PARENT_SCOPE) +endfunction() + +# Define the fmt library, its includes and the needed defines. +add_headers(FMT_HEADERS args.h chrono.h color.h compile.h core.h format.h + format-inl.h os.h ostream.h printf.h ranges.h std.h + xchar.h) +set(FMT_SOURCES src/format.cc) +if (FMT_OS) + set(FMT_SOURCES ${FMT_SOURCES} src/os.cc) +endif () + +add_module_library(fmt src/fmt.cc FALLBACK + ${FMT_SOURCES} ${FMT_HEADERS} README.md ChangeLog.md + IF FMT_MODULE) +add_library(fmt::fmt ALIAS fmt) +if (FMT_MODULE) + enable_module(fmt) +endif () + +if (FMT_WERROR) + target_compile_options(fmt PRIVATE ${WERROR_FLAG}) +endif () +if (FMT_PEDANTIC) + target_compile_options(fmt PRIVATE ${PEDANTIC_COMPILE_FLAGS}) +endif () + +if (cxx_std_11 IN_LIST CMAKE_CXX_COMPILE_FEATURES) + target_compile_features(fmt PUBLIC cxx_std_11) +else () + message(WARNING "Feature cxx_std_11 is unknown for the CXX compiler") +endif () + +target_include_directories(fmt ${FMT_SYSTEM_HEADERS_ATTRIBUTE} PUBLIC + $ + $) + +set(FMT_DEBUG_POSTFIX d CACHE STRING "Debug library postfix.") + +set_target_properties(fmt PROPERTIES + VERSION ${FMT_VERSION} SOVERSION ${CPACK_PACKAGE_VERSION_MAJOR} + PUBLIC_HEADER "${FMT_HEADERS}" + DEBUG_POSTFIX "${FMT_DEBUG_POSTFIX}" + + # Workaround for Visual Studio 2017: + # Ensure the .pdb is created with the same name and in the same directory + # as the .lib. Newer VS versions already do this by default, but there is no + # harm in setting it for those too. Ignored by other generators. + COMPILE_PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + COMPILE_PDB_NAME "fmt" + COMPILE_PDB_NAME_DEBUG "fmt${FMT_DEBUG_POSTFIX}") + +# Set FMT_LIB_NAME for pkg-config fmt.pc. We cannot use the OUTPUT_NAME target +# property because it's not set by default. +set(FMT_LIB_NAME fmt) +if (CMAKE_BUILD_TYPE STREQUAL "Debug") + set(FMT_LIB_NAME ${FMT_LIB_NAME}${FMT_DEBUG_POSTFIX}) +endif () + +if (BUILD_SHARED_LIBS) + target_compile_definitions(fmt PRIVATE FMT_LIB_EXPORT INTERFACE FMT_SHARED) +endif () +if (FMT_SAFE_DURATION_CAST) + target_compile_definitions(fmt PUBLIC FMT_SAFE_DURATION_CAST) +endif () + +add_library(fmt-header-only INTERFACE) +add_library(fmt::fmt-header-only ALIAS fmt-header-only) + +target_compile_definitions(fmt-header-only INTERFACE FMT_HEADER_ONLY=1) +target_compile_features(fmt-header-only INTERFACE cxx_std_11) + +target_include_directories(fmt-header-only + ${FMT_SYSTEM_HEADERS_ATTRIBUTE} INTERFACE + $ + $) + +# Install targets. +if (FMT_INSTALL) + include(CMakePackageConfigHelpers) + set_verbose(FMT_CMAKE_DIR ${CMAKE_INSTALL_LIBDIR}/cmake/fmt CACHE STRING + "Installation directory for cmake files, a relative path that " + "will be joined with ${CMAKE_INSTALL_PREFIX} or an absolute " + "path.") + set(version_config ${PROJECT_BINARY_DIR}/fmt-config-version.cmake) + set(project_config ${PROJECT_BINARY_DIR}/fmt-config.cmake) + set(pkgconfig ${PROJECT_BINARY_DIR}/fmt.pc) + set(targets_export_name fmt-targets) + + set_verbose(FMT_LIB_DIR ${CMAKE_INSTALL_LIBDIR} CACHE STRING + "Installation directory for libraries, a relative path that " + "will be joined to ${CMAKE_INSTALL_PREFIX} or an absolute path.") + + set_verbose(FMT_PKGCONFIG_DIR ${CMAKE_INSTALL_LIBDIR}/pkgconfig CACHE STRING + "Installation directory for pkgconfig (.pc) files, a relative " + "path that will be joined with ${CMAKE_INSTALL_PREFIX} or an " + "absolute path.") + + # Generate the version, config and target files into the build directory. + write_basic_package_version_file( + ${version_config} + VERSION ${FMT_VERSION} + COMPATIBILITY AnyNewerVersion) + + join_paths(libdir_for_pc_file "\${exec_prefix}" "${FMT_LIB_DIR}") + join_paths(includedir_for_pc_file "\${prefix}" "${FMT_INC_DIR}") + + configure_file( + "${PROJECT_SOURCE_DIR}/support/cmake/fmt.pc.in" + "${pkgconfig}" + @ONLY) + configure_package_config_file( + ${PROJECT_SOURCE_DIR}/support/cmake/fmt-config.cmake.in + ${project_config} + INSTALL_DESTINATION ${FMT_CMAKE_DIR}) + + set(INSTALL_TARGETS fmt fmt-header-only) + + # Install the library and headers. + install(TARGETS ${INSTALL_TARGETS} EXPORT ${targets_export_name} + LIBRARY DESTINATION ${FMT_LIB_DIR} + ARCHIVE DESTINATION ${FMT_LIB_DIR} + PUBLIC_HEADER DESTINATION "${FMT_INC_DIR}/fmt" + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) + + # Use a namespace because CMake provides better diagnostics for namespaced + # imported targets. + export(TARGETS ${INSTALL_TARGETS} NAMESPACE fmt:: + FILE ${PROJECT_BINARY_DIR}/${targets_export_name}.cmake) + + # Install version, config and target files. + install( + FILES ${project_config} ${version_config} + DESTINATION ${FMT_CMAKE_DIR}) + install(EXPORT ${targets_export_name} DESTINATION ${FMT_CMAKE_DIR} + NAMESPACE fmt::) + + install(FILES "${pkgconfig}" DESTINATION "${FMT_PKGCONFIG_DIR}") +endif () + +if (FMT_DOC) + add_subdirectory(doc) +endif () + +if (FMT_TEST) + enable_testing() + add_subdirectory(test) +endif () + +# Control fuzzing independent of the unit tests. +if (FMT_FUZZ) + add_subdirectory(test/fuzzing) + + # The FMT_FUZZ macro is used to prevent resource exhaustion in fuzzing + # mode and make fuzzing practically possible. It is similar to + # FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION but uses a different name to + # avoid interfering with fuzzing of projects that use {fmt}. + # See also https://llvm.org/docs/LibFuzzer.html#fuzzer-friendly-build-mode. + target_compile_definitions(fmt PUBLIC FMT_FUZZ) +endif () + +set(gitignore ${PROJECT_SOURCE_DIR}/.gitignore) +if (FMT_MASTER_PROJECT AND EXISTS ${gitignore}) + # Get the list of ignored files from .gitignore. + file (STRINGS ${gitignore} lines) + list(REMOVE_ITEM lines /doc/html) + foreach (line ${lines}) + string(REPLACE "." "[.]" line "${line}") + string(REPLACE "*" ".*" line "${line}") + set(ignored_files ${ignored_files} "${line}$" "${line}/") + endforeach () + set(ignored_files ${ignored_files} + /.git /breathe /format-benchmark sphinx/ .buildinfo .doctrees) + + set(CPACK_SOURCE_GENERATOR ZIP) + set(CPACK_SOURCE_IGNORE_FILES ${ignored_files}) + set(CPACK_SOURCE_PACKAGE_FILE_NAME fmt-${FMT_VERSION}) + set(CPACK_PACKAGE_NAME fmt) + set(CPACK_RESOURCE_FILE_README ${PROJECT_SOURCE_DIR}/README.md) + include(CPack) +endif () diff --git a/third_party/fmt/CONTRIBUTING.md b/third_party/fmt/CONTRIBUTING.md new file mode 100644 index 0000000..b82f145 --- /dev/null +++ b/third_party/fmt/CONTRIBUTING.md @@ -0,0 +1,20 @@ +Contributing to {fmt} +===================== + +By submitting a pull request or a patch, you represent that you have the right +to license your contribution to the {fmt} project owners and the community, +agree that your contributions are licensed under the {fmt} license, and agree +to future changes to the licensing. + +All C++ code must adhere to [Google C++ Style Guide]( +https://google.github.io/styleguide/cppguide.html) with the following +exceptions: + +* Exceptions are permitted +* snake_case should be used instead of UpperCamelCase for function and type + names + +All documentation must adhere to the [Google Developer Documentation Style +Guide](https://developers.google.com/style). + +Thanks for contributing! diff --git a/third_party/fmt/ChangeLog.md b/third_party/fmt/ChangeLog.md new file mode 100644 index 0000000..515f9fd --- /dev/null +++ b/third_party/fmt/ChangeLog.md @@ -0,0 +1,5533 @@ +# 10.2.1 - 2024-01-03 + +- Fixed ABI compatibility with earlier 10.x versions + (https://github.com/fmtlib/fmt/pull/3786). Thanks @saraedum. + +# 10.2.0 - 2024-01-01 + +- Added support for the `%j` specifier (the number of days) for + `std::chrono::duration` (https://github.com/fmtlib/fmt/issues/3643, + https://github.com/fmtlib/fmt/pull/3732). Thanks @intelfx. + +- Added support for the chrono suffix for days and changed + the suffix for minutes from "m" to the correct "min" + (https://github.com/fmtlib/fmt/issues/3662, + https://github.com/fmtlib/fmt/pull/3664). + For example ([godbolt](https://godbolt.org/z/9KhMnq9ba)): + + ```c++ + #include + + int main() { + fmt::print("{}\n", std::chrono::days(42)); // prints "42d" + } + ``` + + Thanks @Richardk2n. + +- Fixed an overflow in `std::chrono::time_point` formatting with large dates + (https://github.com/fmtlib/fmt/issues/3725, + https://github.com/fmtlib/fmt/pull/3727). Thanks @cschreib. + +- Added a formatter for `std::source_location` + (https://github.com/fmtlib/fmt/pull/3730). + For example ([godbolt](https://godbolt.org/z/YajfKjhhr)): + + ```c++ + #include + #include + + int main() { + fmt::print("{}\n", std::source_location::current()); + } + ``` + + prints + + ``` + /app/example.cpp:5:51: int main() + ``` + + Thanks @felix642. + +- Added a formatter for `std::bitset` + (https://github.com/fmtlib/fmt/pull/3660). + For example ([godbolt](https://godbolt.org/z/bdEaGeYxe)): + + ```c++ + #include + #include + + int main() { + fmt::print("{}\n", std::bitset<6>(42)); // prints "101010" + } + ``` + + Thanks @muggenhor. + +- Added an experimental `nested_formatter` that provides an easy way of + applying a formatter to one or more subobjects while automatically handling + width, fill and alignment. For example: + + ```c++ + #include + + struct point { + double x, y; + }; + + template <> + struct fmt::formatter : nested_formatter { + auto format(point p, format_context& ctx) const { + return write_padded(ctx, [=](auto out) { + return format_to(out, "({}, {})", nested(p.x), nested(p.y)); + }); + } + }; + + int main() { + fmt::print("[{:>20.2f}]", point{1, 2}); + } + ``` + + prints + + ``` + [ (1.00, 2.00)] + ``` + +- Added the generic representation (`g`) to `std::filesystem::path` + (https://github.com/fmtlib/fmt/issues/3715, + https://github.com/fmtlib/fmt/pull/3729). For example: + + ```c++ + #include + #include + + int main() { + fmt::print("{:g}\n", std::filesystem::path("C:\\foo")); + } + ``` + + prints `"C:/foo"` on Windows. + + Thanks @js324. + +- Made `format_as` work with references + (https://github.com/fmtlib/fmt/pull/3739). Thanks @tchaikov. + +- Fixed formatting of invalid UTF-8 with precision + (https://github.com/fmtlib/fmt/issues/3284). + +- Fixed an inconsistency between `fmt::to_string` and `fmt::format` + (https://github.com/fmtlib/fmt/issues/3684). + +- Disallowed unsafe uses of `fmt::styled` + (https://github.com/fmtlib/fmt/issues/3625): + + ```c++ + auto s = fmt::styled(std::string("dangle"), fmt::emphasis::bold); + fmt::print("{}\n", s); // compile error + ``` + + Pass `fmt::styled(...)` as a parameter instead. + +- Added a null check when formatting a C string with the `s` specifier + (https://github.com/fmtlib/fmt/issues/3706). + +- Disallowed the `c` specifier for `bool` + (https://github.com/fmtlib/fmt/issues/3726, + https://github.com/fmtlib/fmt/pull/3734). Thanks @js324. + +- Made the default formatting unlocalized in `fmt::ostream_formatter` for + consistency with the rest of the library + (https://github.com/fmtlib/fmt/issues/3460). + +- Fixed localized formatting in bases other than decimal + (https://github.com/fmtlib/fmt/issues/3693, + https://github.com/fmtlib/fmt/pull/3750). Thanks @js324. + +- Fixed a performance regression in experimental `fmt::ostream::print` + (https://github.com/fmtlib/fmt/issues/3674). + +- Added synchronization with the underlying output stream when writing to + the Windows console + (https://github.com/fmtlib/fmt/pull/3668, + https://github.com/fmtlib/fmt/issues/3688, + https://github.com/fmtlib/fmt/pull/3689). + Thanks @Roman-Koshelev and @dimztimz. + +- Changed to only export `format_error` when {fmt} is built as a shared + library (https://github.com/fmtlib/fmt/issues/3626, + https://github.com/fmtlib/fmt/pull/3627). Thanks @phprus. + +- Made `fmt::streamed` `constexpr`. + (https://github.com/fmtlib/fmt/pull/3650). Thanks @muggenhor. + +- Enabled `consteval` on older versions of MSVC + (https://github.com/fmtlib/fmt/pull/3757). Thanks @phprus. + +- Added an option to build without `wchar_t` support on Windows + (https://github.com/fmtlib/fmt/issues/3631, + https://github.com/fmtlib/fmt/pull/3636). Thanks @glebm. + +- Improved build and CI configuration + (https://github.com/fmtlib/fmt/pull/3679, + https://github.com/fmtlib/fmt/issues/3701, + https://github.com/fmtlib/fmt/pull/3702, + https://github.com/fmtlib/fmt/pull/3749). + Thanks @jcar87, @pklima and @tchaikov. + +- Fixed various warnings, compilation and test issues + (https://github.com/fmtlib/fmt/issues/3607, + https://github.com/fmtlib/fmt/pull/3610, + https://github.com/fmtlib/fmt/pull/3624, + https://github.com/fmtlib/fmt/pull/3630, + https://github.com/fmtlib/fmt/pull/3634, + https://github.com/fmtlib/fmt/pull/3638, + https://github.com/fmtlib/fmt/issues/3645, + https://github.com/fmtlib/fmt/issues/3646, + https://github.com/fmtlib/fmt/pull/3647, + https://github.com/fmtlib/fmt/pull/3652, + https://github.com/fmtlib/fmt/issues/3654, + https://github.com/fmtlib/fmt/pull/3663, + https://github.com/fmtlib/fmt/issues/3670, + https://github.com/fmtlib/fmt/pull/3680, + https://github.com/fmtlib/fmt/issues/3694, + https://github.com/fmtlib/fmt/pull/3695, + https://github.com/fmtlib/fmt/pull/3699, + https://github.com/fmtlib/fmt/issues/3705, + https://github.com/fmtlib/fmt/issues/3710, + https://github.com/fmtlib/fmt/issues/3712, + https://github.com/fmtlib/fmt/pull/3713, + https://github.com/fmtlib/fmt/issues/3714, + https://github.com/fmtlib/fmt/pull/3716, + https://github.com/fmtlib/fmt/pull/3723, + https://github.com/fmtlib/fmt/issues/3738, + https://github.com/fmtlib/fmt/issues/3740, + https://github.com/fmtlib/fmt/pull/3741, + https://github.com/fmtlib/fmt/pull/3743, + https://github.com/fmtlib/fmt/issues/3745, + https://github.com/fmtlib/fmt/pull/3747, + https://github.com/fmtlib/fmt/pull/3748, + https://github.com/fmtlib/fmt/pull/3751, + https://github.com/fmtlib/fmt/pull/3754, + https://github.com/fmtlib/fmt/pull/3755, + https://github.com/fmtlib/fmt/issues/3760, + https://github.com/fmtlib/fmt/pull/3762, + https://github.com/fmtlib/fmt/issues/3763, + https://github.com/fmtlib/fmt/pull/3764, + https://github.com/fmtlib/fmt/issues/3774, + https://github.com/fmtlib/fmt/pull/3779). + Thanks @danakj, @vinayyadav3016, @cyyever, @phprus, @qimiko, @saschasc, + @gsjaardema, @lazka, @Zhaojun-Liu, @carlsmedstad, @hotwatermorning, + @cptFracassa, @kuguma, @PeterJohnson, @H1X4Dev, @asantoni, @eltociear, + @msimberg, @tchaikov, @waywardmonkeys. + +- Improved documentation and README + (https://github.com/fmtlib/fmt/issues/2086, + https://github.com/fmtlib/fmt/issues/3637, + https://github.com/fmtlib/fmt/pull/3642, + https://github.com/fmtlib/fmt/pull/3653, + https://github.com/fmtlib/fmt/pull/3655, + https://github.com/fmtlib/fmt/pull/3661, + https://github.com/fmtlib/fmt/issues/3673, + https://github.com/fmtlib/fmt/pull/3677, + https://github.com/fmtlib/fmt/pull/3737, + https://github.com/fmtlib/fmt/issues/3742, + https://github.com/fmtlib/fmt/pull/3744). + Thanks @idzm, @perlun, @joycebrum, @fennewald, @reinhardt1053, @GeorgeLS. + +- Updated CI dependencies + (https://github.com/fmtlib/fmt/pull/3615, + https://github.com/fmtlib/fmt/pull/3622, + https://github.com/fmtlib/fmt/pull/3623, + https://github.com/fmtlib/fmt/pull/3666, + https://github.com/fmtlib/fmt/pull/3696, + https://github.com/fmtlib/fmt/pull/3697, + https://github.com/fmtlib/fmt/pull/3759, + https://github.com/fmtlib/fmt/pull/3782). + +# 10.1.1 - 2023-08-28 + +- Added formatters for `std::atomic` and `atomic_flag` + (https://github.com/fmtlib/fmt/pull/3574, + https://github.com/fmtlib/fmt/pull/3594). + Thanks @wangzw and @AlexGuteniev. +- Fixed an error about partial specialization of `formatter` + after instantiation when compiled with gcc and C++20 + (https://github.com/fmtlib/fmt/issues/3584). +- Fixed compilation as a C++20 module with gcc and clang + (https://github.com/fmtlib/fmt/issues/3587, + https://github.com/fmtlib/fmt/pull/3597, + https://github.com/fmtlib/fmt/pull/3605). + Thanks @MathewBensonCode. +- Made `fmt::to_string` work with types that have `format_as` + overloads (https://github.com/fmtlib/fmt/pull/3575). Thanks @phprus. +- Made `formatted_size` work with integral format specifiers at + compile time (https://github.com/fmtlib/fmt/pull/3591). + Thanks @elbeno. +- Fixed a warning about the `no_unique_address` attribute on clang-cl + (https://github.com/fmtlib/fmt/pull/3599). Thanks @lukester1975. +- Improved compatibility with the legacy GBK encoding + (https://github.com/fmtlib/fmt/issues/3598, + https://github.com/fmtlib/fmt/pull/3599). Thanks @YuHuanTin. +- Added OpenSSF Scorecard analysis + (https://github.com/fmtlib/fmt/issues/3530, + https://github.com/fmtlib/fmt/pull/3571). Thanks @joycebrum. +- Updated CI dependencies + (https://github.com/fmtlib/fmt/pull/3591, + https://github.com/fmtlib/fmt/pull/3592, + https://github.com/fmtlib/fmt/pull/3593, + https://github.com/fmtlib/fmt/pull/3602). + +# 10.1.0 - 2023-08-12 + +- Optimized format string compilation resulting in up to 40% speed up + in compiled `format_to` and \~4x speed up in compiled `format_to_n` + on a concatenation benchmark + (https://github.com/fmtlib/fmt/issues/3133, + https://github.com/fmtlib/fmt/issues/3484). + + {fmt} 10.0: + + --------------------------------------------------------- + Benchmark Time CPU Iterations + --------------------------------------------------------- + BM_format_to 78.9 ns 78.9 ns 8881746 + BM_format_to_n 568 ns 568 ns 1232089 + + {fmt} 10.1: + + --------------------------------------------------------- + Benchmark Time CPU Iterations + --------------------------------------------------------- + BM_format_to 54.9 ns 54.9 ns 12727944 + BM_format_to_n 133 ns 133 ns 5257795 + +- Optimized storage of an empty allocator in `basic_memory_buffer` + (https://github.com/fmtlib/fmt/pull/3485). Thanks @Minty-Meeo. + +- Added formatters for proxy references to elements of + `std::vector` and `std::bitset` + (https://github.com/fmtlib/fmt/issues/3567, + https://github.com/fmtlib/fmt/pull/3570). For example + ([godbolt](https://godbolt.org/z/zYb79Pvn8)): + + ```c++ + #include + #include + + int main() { + auto v = std::vector{true}; + fmt::print("{}", v[0]); + } + ``` + + Thanks @phprus and @felix642. + +- Fixed an ambiguous formatter specialization for containers that look + like container adaptors such as `boost::flat_set` + (https://github.com/fmtlib/fmt/issues/3556, + https://github.com/fmtlib/fmt/pull/3561). Thanks @5chmidti. + +- Fixed compilation when formatting durations not convertible from + `std::chrono::seconds` + (https://github.com/fmtlib/fmt/pull/3430). Thanks @patlkli. + +- Made the `formatter` specialization for `char*` const-correct + (https://github.com/fmtlib/fmt/pull/3432). Thanks @timsong-cpp. + +- Made `{}` and `{:}` handled consistently during compile-time checks + (https://github.com/fmtlib/fmt/issues/3526). + +- Disallowed passing temporaries to `make_format_args` to improve API + safety by preventing dangling references. + +- Improved the compile-time error for unformattable types + (https://github.com/fmtlib/fmt/pull/3478). Thanks @BRevzin. + +- Improved the floating-point formatter + (https://github.com/fmtlib/fmt/pull/3448, + https://github.com/fmtlib/fmt/pull/3450). + Thanks @florimond-collette. + +- Fixed handling of precision for `long double` larger than 64 bits. + (https://github.com/fmtlib/fmt/issues/3539, + https://github.com/fmtlib/fmt/issues/3564). + +- Made floating-point and chrono tests less platform-dependent + (https://github.com/fmtlib/fmt/issues/3337, + https://github.com/fmtlib/fmt/issues/3433, + https://github.com/fmtlib/fmt/pull/3434). Thanks @phprus. + +- Removed the remnants of the Grisu floating-point formatter that has + been replaced by Dragonbox in earlier versions. + +- Added `throw_format_error` to the public API + (https://github.com/fmtlib/fmt/pull/3551). Thanks @mjerabek. + +- Made `FMT_THROW` assert even if assertions are disabled when + compiling with exceptions disabled + (https://github.com/fmtlib/fmt/issues/3418, + https://github.com/fmtlib/fmt/pull/3439). Thanks @BRevzin. + +- Made `format_as` and `std::filesystem::path` formatter work with + exotic code unit types. + (https://github.com/fmtlib/fmt/pull/3457, + https://github.com/fmtlib/fmt/pull/3476). Thanks @gix and @hmbj. + +- Added support for the `?` format specifier to + `std::filesystem::path` and made the default unescaped for + consistency with strings. + +- Deprecated the wide stream overload of `printf`. + +- Removed unused `basic_printf_parse_context`. + +- Improved RTTI detection used when formatting exceptions + (https://github.com/fmtlib/fmt/pull/3468). Thanks @danakj. + +- Improved compatibility with VxWorks7 + (https://github.com/fmtlib/fmt/pull/3467). Thanks @wenshan1. + +- Improved documentation + (https://github.com/fmtlib/fmt/issues/3174, + https://github.com/fmtlib/fmt/issues/3423, + https://github.com/fmtlib/fmt/pull/3454, + https://github.com/fmtlib/fmt/issues/3458, + https://github.com/fmtlib/fmt/pull/3461, + https://github.com/fmtlib/fmt/issues/3487, + https://github.com/fmtlib/fmt/pull/3515). + Thanks @zencatalyst, @rlalik and @mikecrowe. + +- Improved build and CI configurations + (https://github.com/fmtlib/fmt/issues/3449, + https://github.com/fmtlib/fmt/pull/3451, + https://github.com/fmtlib/fmt/pull/3452, + https://github.com/fmtlib/fmt/pull/3453, + https://github.com/fmtlib/fmt/pull/3459, + https://github.com/fmtlib/fmt/issues/3481, + https://github.com/fmtlib/fmt/pull/3486, + https://github.com/fmtlib/fmt/issues/3489, + https://github.com/fmtlib/fmt/pull/3496, + https://github.com/fmtlib/fmt/issues/3517, + https://github.com/fmtlib/fmt/pull/3523, + https://github.com/fmtlib/fmt/pull/3563). + Thanks @joycebrum, @glebm, @phprus, @petrmanek, @setoye and @abouvier. + +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/issues/3408, + https://github.com/fmtlib/fmt/issues/3424, + https://github.com/fmtlib/fmt/issues/3444, + https://github.com/fmtlib/fmt/pull/3446, + https://github.com/fmtlib/fmt/pull/3475, + https://github.com/fmtlib/fmt/pull/3482, + https://github.com/fmtlib/fmt/issues/3492, + https://github.com/fmtlib/fmt/pull/3493, + https://github.com/fmtlib/fmt/pull/3508, + https://github.com/fmtlib/fmt/issues/3509, + https://github.com/fmtlib/fmt/issues/3533, + https://github.com/fmtlib/fmt/pull/3542, + https://github.com/fmtlib/fmt/issues/3543, + https://github.com/fmtlib/fmt/issues/3540, + https://github.com/fmtlib/fmt/pull/3544, + https://github.com/fmtlib/fmt/issues/3548, + https://github.com/fmtlib/fmt/pull/3549, + https://github.com/fmtlib/fmt/pull/3550, + https://github.com/fmtlib/fmt/pull/3552). + Thanks @adesitter, @hmbj, @Minty-Meeo, @phprus, @TobiSchluter, + @kieranclancy, @alexeedm, @jurihock, @Ozomahtli and @razaqq. + +# 10.0.0 - 2023-05-09 + +- Replaced Grisu with a new floating-point formatting algorithm for + given precision (https://github.com/fmtlib/fmt/issues/3262, + https://github.com/fmtlib/fmt/issues/2750, + https://github.com/fmtlib/fmt/pull/3269, + https://github.com/fmtlib/fmt/pull/3276). The new algorithm + is based on Dragonbox already used for the shortest representation + and gives substantial performance improvement: + + ![](https://user-images.githubusercontent.com/33922675/211956670-84891a09-6867-47d9-82fc-3230da7abe0f.png) + + - Red: new algorithm + - Green: new algorithm with `FMT_USE_FULL_CACHE_DRAGONBOX` defined + to 1 + - Blue: old algorithm + + Thanks @jk-jeon. + +- Replaced `snprintf`-based hex float formatter with an internal + implementation (https://github.com/fmtlib/fmt/pull/3179, + https://github.com/fmtlib/fmt/pull/3203). This removes the + last usage of `s(n)printf` in {fmt}. Thanks @phprus. + +- Fixed alignment of floating-point numbers with localization + (https://github.com/fmtlib/fmt/issues/3263, + https://github.com/fmtlib/fmt/pull/3272). Thanks @ShawnZhong. + +- Made handling of `#` consistent with `std::format`. + +- Improved C++20 module support + (https://github.com/fmtlib/fmt/pull/3134, + https://github.com/fmtlib/fmt/pull/3254, + https://github.com/fmtlib/fmt/pull/3386, + https://github.com/fmtlib/fmt/pull/3387, + https://github.com/fmtlib/fmt/pull/3388, + https://github.com/fmtlib/fmt/pull/3392, + https://github.com/fmtlib/fmt/pull/3397, + https://github.com/fmtlib/fmt/pull/3399, + https://github.com/fmtlib/fmt/pull/3400). + Thanks @laitingsheng, @Orvid and @DanielaE. + +- Switched to the [modules CMake library](https://github.com/vitaut/modules) + which allows building {fmt} as a C++20 module with clang: + + CXX=clang++ cmake -DFMT_MODULE=ON . + make + +- Made `format_as` work with any user-defined type and not just enums. + For example ([godbolt](https://godbolt.org/z/b7rqhq5Kh)): + + ```c++ + #include + + struct floaty_mc_floatface { + double value; + }; + + auto format_as(floaty_mc_floatface f) { return f.value; } + + int main() { + fmt::print("{:8}\n", floaty_mc_floatface{0.42}); // prints " 0.42" + } + ``` + +- Removed deprecated implicit conversions for enums and conversions to + primitive types for compatibility with `std::format` and to prevent + potential ODR violations. Use `format_as` instead. + +- Added support for fill, align and width to the time point formatter + (https://github.com/fmtlib/fmt/issues/3237, + https://github.com/fmtlib/fmt/pull/3260, + https://github.com/fmtlib/fmt/pull/3275). For example + ([godbolt](https://godbolt.org/z/rKP6MGz6c)): + + ```c++ + #include + + int main() { + // prints " 2023" + fmt::print("{:>8%Y}\n", std::chrono::system_clock::now()); + } + ``` + + Thanks @ShawnZhong. + +- Implemented formatting of subseconds + (https://github.com/fmtlib/fmt/issues/2207, + https://github.com/fmtlib/fmt/issues/3117, + https://github.com/fmtlib/fmt/pull/3115, + https://github.com/fmtlib/fmt/pull/3143, + https://github.com/fmtlib/fmt/pull/3144, + https://github.com/fmtlib/fmt/pull/3349). For example + ([godbolt](https://godbolt.org/z/45738oGEo)): + + ```c++ + #include + + int main() { + // prints 01.234567 + fmt::print("{:%S}\n", std::chrono::microseconds(1234567)); + } + ``` + + Thanks @patrickroocks @phprus and @BRevzin. + +- Added precision support to `%S` + (https://github.com/fmtlib/fmt/pull/3148). Thanks @SappyJoy + +- Added support for `std::utc_time` + (https://github.com/fmtlib/fmt/issues/3098, + https://github.com/fmtlib/fmt/pull/3110). Thanks @patrickroocks. + +- Switched formatting of `std::chrono::system_clock` from local time + to UTC for compatibility with the standard + (https://github.com/fmtlib/fmt/issues/3199, + https://github.com/fmtlib/fmt/pull/3230). Thanks @ned14. + +- Added support for `%Ez` and `%Oz` to chrono formatters. + (https://github.com/fmtlib/fmt/issues/3220, + https://github.com/fmtlib/fmt/pull/3222). Thanks @phprus. + +- Improved validation of format specifiers for `std::chrono::duration` + (https://github.com/fmtlib/fmt/issues/3219, + https://github.com/fmtlib/fmt/pull/3232). Thanks @ShawnZhong. + +- Fixed formatting of time points before the epoch + (https://github.com/fmtlib/fmt/issues/3117, + https://github.com/fmtlib/fmt/pull/3261). For example + ([godbolt](https://godbolt.org/z/f7bcznb3W)): + + ```c++ + #include + + int main() { + auto t = std::chrono::system_clock::from_time_t(0) - + std::chrono::milliseconds(250); + fmt::print("{:%S}\n", t); // prints 59.750000000 + } + ``` + + Thanks @ShawnZhong. + +- Experimental: implemented glibc extension for padding seconds, + minutes and hours + (https://github.com/fmtlib/fmt/issues/2959, + https://github.com/fmtlib/fmt/pull/3271). Thanks @ShawnZhong. + +- Added a formatter for `std::exception` + (https://github.com/fmtlib/fmt/issues/2977, + https://github.com/fmtlib/fmt/issues/3012, + https://github.com/fmtlib/fmt/pull/3062, + https://github.com/fmtlib/fmt/pull/3076, + https://github.com/fmtlib/fmt/pull/3119). For example + ([godbolt](https://godbolt.org/z/8xoWGs9e4)): + + ```c++ + #include + #include + + int main() { + try { + std::vector().at(0); + } catch(const std::exception& e) { + fmt::print("{}", e); + } + } + ``` + + prints: + + vector::_M_range_check: __n (which is 0) >= this->size() (which is 0) + + on libstdc++. Thanks @zach2good and @phprus. + +- Moved `std::error_code` formatter from `fmt/os.h` to `fmt/std.h`. + (https://github.com/fmtlib/fmt/pull/3125). Thanks @phprus. + +- Added formatters for standard container adapters: + `std::priority_queue`, `std::queue` and `std::stack` + (https://github.com/fmtlib/fmt/issues/3215, + https://github.com/fmtlib/fmt/pull/3279). For example + ([godbolt](https://godbolt.org/z/74h1xY9qK)): + + ```c++ + #include + #include + #include + + int main() { + auto s = std::stack>(); + for (auto b: {true, false, true}) s.push(b); + fmt::print("{}\n", s); // prints [true, false, true] + } + ``` + + Thanks @ShawnZhong. + +- Added a formatter for `std::optional` to `fmt/std.h` + (https://github.com/fmtlib/fmt/issues/1367, + https://github.com/fmtlib/fmt/pull/3303). + Thanks @tom-huntington. + +- Fixed formatting of valueless by exception variants + (https://github.com/fmtlib/fmt/pull/3347). Thanks @TheOmegaCarrot. + +- Made `fmt::ptr` accept `unique_ptr` with a custom deleter + (https://github.com/fmtlib/fmt/pull/3177). Thanks @hmbj. + +- Fixed formatting of noncopyable ranges and nested ranges of chars + (https://github.com/fmtlib/fmt/pull/3158 + https://github.com/fmtlib/fmt/issues/3286, + https://github.com/fmtlib/fmt/pull/3290). Thanks @BRevzin. + +- Fixed issues with formatting of paths and ranges of paths + (https://github.com/fmtlib/fmt/issues/3319, + https://github.com/fmtlib/fmt/pull/3321 + https://github.com/fmtlib/fmt/issues/3322). Thanks @phprus. + +- Improved handling of invalid Unicode in paths. + +- Enabled compile-time checks on Apple clang 14 and later + (https://github.com/fmtlib/fmt/pull/3331). Thanks @cloyce. + +- Improved compile-time checks of named arguments + (https://github.com/fmtlib/fmt/issues/3105, + https://github.com/fmtlib/fmt/pull/3214). Thanks @rbrich. + +- Fixed formatting when both alignment and `0` are given + (https://github.com/fmtlib/fmt/issues/3236, + https://github.com/fmtlib/fmt/pull/3248). Thanks @ShawnZhong. + +- Improved Unicode support in the experimental file API on Windows + (https://github.com/fmtlib/fmt/issues/3234, + https://github.com/fmtlib/fmt/pull/3293). Thanks @Fros1er. + +- Unified UTF transcoding + (https://github.com/fmtlib/fmt/pull/3416). Thanks @phprus. + +- Added support for UTF-8 digit separators via an experimental locale + facet (https://github.com/fmtlib/fmt/issues/1861). For + example ([godbolt](https://godbolt.org/z/f7bcznb3W)): + + ```c++ + auto loc = std::locale( + std::locale(), new fmt::format_facet("’")); + auto s = fmt::format(loc, "{:L}", 1000); + ``` + + where `’` is U+2019 used as a digit separator in the de_CH locale. + +- Added an overload of `formatted_size` that takes a locale + (https://github.com/fmtlib/fmt/issues/3084, + https://github.com/fmtlib/fmt/pull/3087). Thanks @gerboengels. + +- Removed the deprecated `FMT_DEPRECATED_OSTREAM`. + +- Fixed a UB when using a null `std::string_view` with + `fmt::to_string` or format string compilation + (https://github.com/fmtlib/fmt/issues/3241, + https://github.com/fmtlib/fmt/pull/3244). Thanks @phprus. + +- Added `starts_with` to the fallback `string_view` implementation + (https://github.com/fmtlib/fmt/pull/3080). Thanks @phprus. + +- Added `fmt::basic_format_string::get()` for compatibility with + `basic_format_string` + (https://github.com/fmtlib/fmt/pull/3111). Thanks @huangqinjin. + +- Added `println` for compatibility with C++23 + (https://github.com/fmtlib/fmt/pull/3267). Thanks @ShawnZhong. + +- Renamed the `FMT_EXPORT` macro for shared library usage to + `FMT_LIB_EXPORT`. + +- Improved documentation + (https://github.com/fmtlib/fmt/issues/3108, + https://github.com/fmtlib/fmt/issues/3169, + https://github.com/fmtlib/fmt/pull/3243). + https://github.com/fmtlib/fmt/pull/3404). + Thanks @Cleroth and @Vertexwahn. + +- Improved build configuration and tests + (https://github.com/fmtlib/fmt/pull/3118, + https://github.com/fmtlib/fmt/pull/3120, + https://github.com/fmtlib/fmt/pull/3188, + https://github.com/fmtlib/fmt/issues/3189, + https://github.com/fmtlib/fmt/pull/3198, + https://github.com/fmtlib/fmt/pull/3205, + https://github.com/fmtlib/fmt/pull/3207, + https://github.com/fmtlib/fmt/pull/3210, + https://github.com/fmtlib/fmt/pull/3240, + https://github.com/fmtlib/fmt/pull/3256, + https://github.com/fmtlib/fmt/pull/3264, + https://github.com/fmtlib/fmt/issues/3299, + https://github.com/fmtlib/fmt/pull/3302, + https://github.com/fmtlib/fmt/pull/3312, + https://github.com/fmtlib/fmt/issues/3317, + https://github.com/fmtlib/fmt/pull/3328, + https://github.com/fmtlib/fmt/pull/3333, + https://github.com/fmtlib/fmt/pull/3369, + https://github.com/fmtlib/fmt/issues/3373, + https://github.com/fmtlib/fmt/pull/3395, + https://github.com/fmtlib/fmt/pull/3406, + https://github.com/fmtlib/fmt/pull/3411). + Thanks @dimztimz, @phprus, @DavidKorczynski, @ChrisThrasher, + @FrancoisCarouge, @kennyweiss, @luzpaz, @codeinred, @Mixaill, @joycebrum, + @kevinhwang and @Vertexwahn. + +- Fixed a regression in handling empty format specifiers after a colon + (`{:}`) (https://github.com/fmtlib/fmt/pull/3086). Thanks @oxidase. + +- Worked around a broken implementation of + `std::is_constant_evaluated` in some versions of libstdc++ on clang + (https://github.com/fmtlib/fmt/issues/3247, + https://github.com/fmtlib/fmt/pull/3281). Thanks @phprus. + +- Fixed formatting of volatile variables + (https://github.com/fmtlib/fmt/pull/3068). + +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/pull/3057, + https://github.com/fmtlib/fmt/pull/3066, + https://github.com/fmtlib/fmt/pull/3072, + https://github.com/fmtlib/fmt/pull/3082, + https://github.com/fmtlib/fmt/pull/3091, + https://github.com/fmtlib/fmt/issues/3092, + https://github.com/fmtlib/fmt/pull/3093, + https://github.com/fmtlib/fmt/pull/3095, + https://github.com/fmtlib/fmt/issues/3096, + https://github.com/fmtlib/fmt/pull/3097, + https://github.com/fmtlib/fmt/issues/3128, + https://github.com/fmtlib/fmt/pull/3129, + https://github.com/fmtlib/fmt/pull/3137, + https://github.com/fmtlib/fmt/pull/3139, + https://github.com/fmtlib/fmt/issues/3140, + https://github.com/fmtlib/fmt/pull/3142, + https://github.com/fmtlib/fmt/issues/3149, + https://github.com/fmtlib/fmt/pull/3150, + https://github.com/fmtlib/fmt/issues/3154, + https://github.com/fmtlib/fmt/issues/3163, + https://github.com/fmtlib/fmt/issues/3178, + https://github.com/fmtlib/fmt/pull/3184, + https://github.com/fmtlib/fmt/pull/3196, + https://github.com/fmtlib/fmt/issues/3204, + https://github.com/fmtlib/fmt/pull/3206, + https://github.com/fmtlib/fmt/pull/3208, + https://github.com/fmtlib/fmt/issues/3213, + https://github.com/fmtlib/fmt/pull/3216, + https://github.com/fmtlib/fmt/issues/3224, + https://github.com/fmtlib/fmt/issues/3226, + https://github.com/fmtlib/fmt/issues/3228, + https://github.com/fmtlib/fmt/pull/3229, + https://github.com/fmtlib/fmt/pull/3259, + https://github.com/fmtlib/fmt/issues/3274, + https://github.com/fmtlib/fmt/issues/3287, + https://github.com/fmtlib/fmt/pull/3288, + https://github.com/fmtlib/fmt/issues/3292, + https://github.com/fmtlib/fmt/pull/3295, + https://github.com/fmtlib/fmt/pull/3296, + https://github.com/fmtlib/fmt/issues/3298, + https://github.com/fmtlib/fmt/issues/3325, + https://github.com/fmtlib/fmt/pull/3326, + https://github.com/fmtlib/fmt/issues/3334, + https://github.com/fmtlib/fmt/issues/3342, + https://github.com/fmtlib/fmt/pull/3343, + https://github.com/fmtlib/fmt/issues/3351, + https://github.com/fmtlib/fmt/pull/3352, + https://github.com/fmtlib/fmt/pull/3362, + https://github.com/fmtlib/fmt/issues/3365, + https://github.com/fmtlib/fmt/pull/3366, + https://github.com/fmtlib/fmt/pull/3374, + https://github.com/fmtlib/fmt/issues/3377, + https://github.com/fmtlib/fmt/pull/3378, + https://github.com/fmtlib/fmt/issues/3381, + https://github.com/fmtlib/fmt/pull/3398, + https://github.com/fmtlib/fmt/pull/3413, + https://github.com/fmtlib/fmt/issues/3415). + Thanks @phprus, @gsjaardema, @NewbieOrange, @EngineLessCC, @asmaloney, + @HazardyKnusperkeks, @sergiud, @Youw, @thesmurph, @czudziakm, + @Roman-Koshelev, @chronoxor, @ShawnZhong, @russelltg, @glebm, @tmartin-gh, + @Zhaojun-Liu, @louiswins and @mogemimi. + +# 9.1.0 - 2022-08-27 + +- `fmt::formatted_size` now works at compile time + (https://github.com/fmtlib/fmt/pull/3026). For example + ([godbolt](https://godbolt.org/z/1MW5rMdf8)): + + ```c++ + #include + + int main() { + using namespace fmt::literals; + constexpr size_t n = fmt::formatted_size("{}"_cf, 42); + fmt::print("{}\n", n); // prints 2 + } + ``` + + Thanks @marksantaniello. + +- Fixed handling of invalid UTF-8 + (https://github.com/fmtlib/fmt/pull/3038, + https://github.com/fmtlib/fmt/pull/3044, + https://github.com/fmtlib/fmt/pull/3056). + Thanks @phprus and @skeeto. + +- Improved Unicode support in `ostream` overloads of `print` + (https://github.com/fmtlib/fmt/pull/2994, + https://github.com/fmtlib/fmt/pull/3001, + https://github.com/fmtlib/fmt/pull/3025). Thanks @dimztimz. + +- Fixed handling of the sign specifier in localized formatting on + systems with 32-bit `wchar_t` + (https://github.com/fmtlib/fmt/issues/3041). + +- Added support for wide streams to `fmt::streamed` + (https://github.com/fmtlib/fmt/pull/2994). Thanks @phprus. + +- Added the `n` specifier that disables the output of delimiters when + formatting ranges (https://github.com/fmtlib/fmt/pull/2981, + https://github.com/fmtlib/fmt/pull/2983). For example + ([godbolt](https://godbolt.org/z/roKqGdj8c)): + + ```c++ + #include + #include + + int main() { + auto v = std::vector{1, 2, 3}; + fmt::print("{:n}\n", v); // prints 1, 2, 3 + } + ``` + + Thanks @BRevzin. + +- Worked around problematic `std::string_view` constructors introduced + in C++23 (https://github.com/fmtlib/fmt/issues/3030, + https://github.com/fmtlib/fmt/issues/3050). Thanks @strega-nil-ms. + +- Improve handling (exclusion) of recursive ranges + (https://github.com/fmtlib/fmt/issues/2968, + https://github.com/fmtlib/fmt/pull/2974). Thanks @Dani-Hub. + +- Improved error reporting in format string compilation + (https://github.com/fmtlib/fmt/issues/3055). + +- Improved the implementation of + [Dragonbox](https://github.com/jk-jeon/dragonbox), the algorithm + used for the default floating-point formatting + (https://github.com/fmtlib/fmt/pull/2984). Thanks @jk-jeon. + +- Fixed issues with floating-point formatting on exotic platforms. + +- Improved the implementation of chrono formatting + (https://github.com/fmtlib/fmt/pull/3010). Thanks @phprus. + +- Improved documentation + (https://github.com/fmtlib/fmt/pull/2966, + https://github.com/fmtlib/fmt/pull/3009, + https://github.com/fmtlib/fmt/issues/3020, + https://github.com/fmtlib/fmt/pull/3037). + Thanks @mwinterb, @jcelerier and @remiburtin. + +- Improved build configuration + (https://github.com/fmtlib/fmt/pull/2991, + https://github.com/fmtlib/fmt/pull/2995, + https://github.com/fmtlib/fmt/issues/3004, + https://github.com/fmtlib/fmt/pull/3007, + https://github.com/fmtlib/fmt/pull/3040). + Thanks @dimztimz and @hwhsu1231. + +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/issues/2969, + https://github.com/fmtlib/fmt/pull/2971, + https://github.com/fmtlib/fmt/issues/2975, + https://github.com/fmtlib/fmt/pull/2982, + https://github.com/fmtlib/fmt/pull/2985, + https://github.com/fmtlib/fmt/issues/2988, + https://github.com/fmtlib/fmt/issues/2989, + https://github.com/fmtlib/fmt/issues/3000, + https://github.com/fmtlib/fmt/issues/3006, + https://github.com/fmtlib/fmt/issues/3014, + https://github.com/fmtlib/fmt/issues/3015, + https://github.com/fmtlib/fmt/pull/3021, + https://github.com/fmtlib/fmt/issues/3023, + https://github.com/fmtlib/fmt/pull/3024, + https://github.com/fmtlib/fmt/pull/3029, + https://github.com/fmtlib/fmt/pull/3043, + https://github.com/fmtlib/fmt/issues/3052, + https://github.com/fmtlib/fmt/pull/3053, + https://github.com/fmtlib/fmt/pull/3054). + Thanks @h-friederich, @dimztimz, @olupton, @bernhardmgruber and @phprus. + +# 9.0.0 - 2022-07-04 + +- Switched to the internal floating point formatter for all decimal + presentation formats. In particular this results in consistent + rounding on all platforms and removing the `s[n]printf` fallback for + decimal FP formatting. + +- Compile-time floating point formatting no longer requires the + header-only mode. For example + ([godbolt](https://godbolt.org/z/G37PTeG3b)): + + ```c++ + #include + #include + + consteval auto compile_time_dtoa(double value) -> std::array { + auto result = std::array(); + fmt::format_to(result.data(), FMT_COMPILE("{}"), value); + return result; + } + + constexpr auto answer = compile_time_dtoa(0.42); + ``` + + works with the default settings. + +- Improved the implementation of + [Dragonbox](https://github.com/jk-jeon/dragonbox), the algorithm + used for the default floating-point formatting + (https://github.com/fmtlib/fmt/pull/2713, + https://github.com/fmtlib/fmt/pull/2750). Thanks @jk-jeon. + +- Made `fmt::to_string` work with `__float128`. This uses the internal + FP formatter and works even on system without `__float128` support + in `[s]printf`. + +- Disabled automatic `std::ostream` insertion operator (`operator<<`) + discovery when `fmt/ostream.h` is included to prevent ODR + violations. You can get the old behavior by defining + `FMT_DEPRECATED_OSTREAM` but this will be removed in the next major + release. Use `fmt::streamed` or `fmt::ostream_formatter` to enable + formatting via `std::ostream` instead. + +- Added `fmt::ostream_formatter` that can be used to write `formatter` + specializations that perform formatting via `std::ostream`. For + example ([godbolt](https://godbolt.org/z/5sEc5qMsf)): + + ```c++ + #include + + struct date { + int year, month, day; + + friend std::ostream& operator<<(std::ostream& os, const date& d) { + return os << d.year << '-' << d.month << '-' << d.day; + } + }; + + template <> struct fmt::formatter : ostream_formatter {}; + + std::string s = fmt::format("The date is {}", date{2012, 12, 9}); + // s == "The date is 2012-12-9" + ``` + +- Added the `fmt::streamed` function that takes an object and formats + it via `std::ostream`. For example + ([godbolt](https://godbolt.org/z/5G3346G1f)): + + ```c++ + #include + #include + + int main() { + fmt::print("Current thread id: {}\n", + fmt::streamed(std::this_thread::get_id())); + } + ``` + + Note that `fmt/std.h` provides a `formatter` specialization for + `std::thread::id` so you don\'t need to format it via + `std::ostream`. + +- Deprecated implicit conversions of unscoped enums to integers for + consistency with scoped enums. + +- Added an argument-dependent lookup based `format_as` extension API + to simplify formatting of enums. + +- Added experimental `std::variant` formatting support + (https://github.com/fmtlib/fmt/pull/2941). For example + ([godbolt](https://godbolt.org/z/KG9z6cq68)): + + ```c++ + #include + #include + + int main() { + auto v = std::variant(42); + fmt::print("{}\n", v); + } + ``` + + prints: + + variant(42) + + Thanks @jehelset. + +- Added experimental `std::filesystem::path` formatting support + (https://github.com/fmtlib/fmt/issues/2865, + https://github.com/fmtlib/fmt/pull/2902, + https://github.com/fmtlib/fmt/issues/2917, + https://github.com/fmtlib/fmt/pull/2918). For example + ([godbolt](https://godbolt.org/z/o44dMexEb)): + + ```c++ + #include + #include + + int main() { + fmt::print("There is no place like {}.", std::filesystem::path("/home")); + } + ``` + + prints: + + There is no place like "/home". + + Thanks @phprus. + +- Added a `std::thread::id` formatter to `fmt/std.h`. For example + ([godbolt](https://godbolt.org/z/j1azbYf3E)): + + ```c++ + #include + #include + + int main() { + fmt::print("Current thread id: {}\n", std::this_thread::get_id()); + } + ``` + +- Added `fmt::styled` that applies a text style to an individual + argument (https://github.com/fmtlib/fmt/pull/2793). For + example ([godbolt](https://godbolt.org/z/vWGW7v5M6)): + + ```c++ + #include + #include + + int main() { + auto now = std::chrono::system_clock::now(); + fmt::print( + "[{}] {}: {}\n", + fmt::styled(now, fmt::emphasis::bold), + fmt::styled("error", fg(fmt::color::red)), + "something went wrong"); + } + ``` + + prints + + ![](https://user-images.githubusercontent.com/576385/175071215-12809244-dab0-4005-96d8-7cd911c964d5.png) + + Thanks @rbrugo. + +- Made `fmt::print` overload for text styles correctly handle UTF-8 + (https://github.com/fmtlib/fmt/issues/2681, + https://github.com/fmtlib/fmt/pull/2701). Thanks @AlexGuteniev. + +- Fixed Unicode handling when writing to an ostream. + +- Added support for nested specifiers to range formatting + (https://github.com/fmtlib/fmt/pull/2673). For example + ([godbolt](https://godbolt.org/z/xd3Gj38cf)): + + ```c++ + #include + #include + + int main() { + fmt::print("{::#x}\n", std::vector{10, 20, 30}); + } + ``` + + prints `[0xa, 0x14, 0x1e]`. + + Thanks @BRevzin. + +- Implemented escaping of wide strings in ranges + (https://github.com/fmtlib/fmt/pull/2904). Thanks @phprus. + +- Added support for ranges with `begin` / `end` found via the + argument-dependent lookup + (https://github.com/fmtlib/fmt/pull/2807). Thanks @rbrugo. + +- Fixed formatting of certain kinds of ranges of ranges + (https://github.com/fmtlib/fmt/pull/2787). Thanks @BRevzin. + +- Fixed handling of maps with element types other than `std::pair` + (https://github.com/fmtlib/fmt/pull/2944). Thanks @BrukerJWD. + +- Made tuple formatter enabled only if elements are formattable + (https://github.com/fmtlib/fmt/issues/2939, + https://github.com/fmtlib/fmt/pull/2940). Thanks @jehelset. + +- Made `fmt::join` compatible with format string compilation + (https://github.com/fmtlib/fmt/issues/2719, + https://github.com/fmtlib/fmt/pull/2720). Thanks @phprus. + +- Made compile-time checks work with named arguments of custom types + and `std::ostream` `print` overloads + (https://github.com/fmtlib/fmt/issues/2816, + https://github.com/fmtlib/fmt/issues/2817, + https://github.com/fmtlib/fmt/pull/2819). Thanks @timsong-cpp. + +- Removed `make_args_checked` because it is no longer needed for + compile-time checks + (https://github.com/fmtlib/fmt/pull/2760). Thanks @phprus. + +- Removed the following deprecated APIs: `_format`, `arg_join`, the + `format_to` overload that takes a memory buffer, `[v]fprintf` that + takes an `ostream`. + +- Removed the deprecated implicit conversion of `[const] signed char*` + and `[const] unsigned char*` to C strings. + +- Removed the deprecated `fmt/locale.h`. + +- Replaced the deprecated `fileno()` with `descriptor()` in + `buffered_file`. + +- Moved `to_string_view` to the `detail` namespace since it\'s an + implementation detail. + +- Made access mode of a created file consistent with `fopen` by + setting `S_IWGRP` and `S_IWOTH` + (https://github.com/fmtlib/fmt/pull/2733). Thanks @arogge. + +- Removed a redundant buffer resize when formatting to `std::ostream` + (https://github.com/fmtlib/fmt/issues/2842, + https://github.com/fmtlib/fmt/pull/2843). Thanks @jcelerier. + +- Made precision computation for strings consistent with width + (https://github.com/fmtlib/fmt/issues/2888). + +- Fixed handling of locale separators in floating point formatting + (https://github.com/fmtlib/fmt/issues/2830). + +- Made sign specifiers work with `__int128_t` + (https://github.com/fmtlib/fmt/issues/2773). + +- Improved support for systems such as CHERI with extra data stored in + pointers (https://github.com/fmtlib/fmt/pull/2932). + Thanks @davidchisnall. + +- Improved documentation + (https://github.com/fmtlib/fmt/pull/2706, + https://github.com/fmtlib/fmt/pull/2712, + https://github.com/fmtlib/fmt/pull/2789, + https://github.com/fmtlib/fmt/pull/2803, + https://github.com/fmtlib/fmt/pull/2805, + https://github.com/fmtlib/fmt/pull/2815, + https://github.com/fmtlib/fmt/pull/2924). + Thanks @BRevzin, @Pokechu22, @setoye, @rtobar, @rbrugo, @anoonD and + @leha-bot. + +- Improved build configuration + (https://github.com/fmtlib/fmt/pull/2766, + https://github.com/fmtlib/fmt/pull/2772, + https://github.com/fmtlib/fmt/pull/2836, + https://github.com/fmtlib/fmt/pull/2852, + https://github.com/fmtlib/fmt/pull/2907, + https://github.com/fmtlib/fmt/pull/2913, + https://github.com/fmtlib/fmt/pull/2914). + Thanks @kambala-decapitator, @mattiasljungstrom, @kieselnb, @nathannaveen + and @Vertexwahn. + +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/issues/2408, + https://github.com/fmtlib/fmt/issues/2507, + https://github.com/fmtlib/fmt/issues/2697, + https://github.com/fmtlib/fmt/issues/2715, + https://github.com/fmtlib/fmt/issues/2717, + https://github.com/fmtlib/fmt/pull/2722, + https://github.com/fmtlib/fmt/pull/2724, + https://github.com/fmtlib/fmt/pull/2725, + https://github.com/fmtlib/fmt/issues/2726, + https://github.com/fmtlib/fmt/pull/2728, + https://github.com/fmtlib/fmt/pull/2732, + https://github.com/fmtlib/fmt/issues/2738, + https://github.com/fmtlib/fmt/pull/2742, + https://github.com/fmtlib/fmt/issues/2744, + https://github.com/fmtlib/fmt/issues/2745, + https://github.com/fmtlib/fmt/issues/2746, + https://github.com/fmtlib/fmt/issues/2754, + https://github.com/fmtlib/fmt/pull/2755, + https://github.com/fmtlib/fmt/issues/2757, + https://github.com/fmtlib/fmt/pull/2758, + https://github.com/fmtlib/fmt/issues/2761, + https://github.com/fmtlib/fmt/pull/2762, + https://github.com/fmtlib/fmt/issues/2763, + https://github.com/fmtlib/fmt/pull/2765, + https://github.com/fmtlib/fmt/issues/2769, + https://github.com/fmtlib/fmt/pull/2770, + https://github.com/fmtlib/fmt/issues/2771, + https://github.com/fmtlib/fmt/issues/2777, + https://github.com/fmtlib/fmt/pull/2779, + https://github.com/fmtlib/fmt/pull/2782, + https://github.com/fmtlib/fmt/pull/2783, + https://github.com/fmtlib/fmt/issues/2794, + https://github.com/fmtlib/fmt/issues/2796, + https://github.com/fmtlib/fmt/pull/2797, + https://github.com/fmtlib/fmt/pull/2801, + https://github.com/fmtlib/fmt/pull/2802, + https://github.com/fmtlib/fmt/issues/2808, + https://github.com/fmtlib/fmt/issues/2818, + https://github.com/fmtlib/fmt/pull/2819, + https://github.com/fmtlib/fmt/issues/2829, + https://github.com/fmtlib/fmt/issues/2835, + https://github.com/fmtlib/fmt/issues/2848, + https://github.com/fmtlib/fmt/issues/2860, + https://github.com/fmtlib/fmt/pull/2861, + https://github.com/fmtlib/fmt/pull/2882, + https://github.com/fmtlib/fmt/issues/2886, + https://github.com/fmtlib/fmt/issues/2891, + https://github.com/fmtlib/fmt/pull/2892, + https://github.com/fmtlib/fmt/issues/2895, + https://github.com/fmtlib/fmt/issues/2896, + https://github.com/fmtlib/fmt/pull/2903, + https://github.com/fmtlib/fmt/issues/2906, + https://github.com/fmtlib/fmt/issues/2908, + https://github.com/fmtlib/fmt/pull/2909, + https://github.com/fmtlib/fmt/issues/2920, + https://github.com/fmtlib/fmt/pull/2922, + https://github.com/fmtlib/fmt/pull/2927, + https://github.com/fmtlib/fmt/pull/2929, + https://github.com/fmtlib/fmt/issues/2936, + https://github.com/fmtlib/fmt/pull/2937, + https://github.com/fmtlib/fmt/pull/2938, + https://github.com/fmtlib/fmt/pull/2951, + https://github.com/fmtlib/fmt/issues/2954, + https://github.com/fmtlib/fmt/pull/2957, + https://github.com/fmtlib/fmt/issues/2958, + https://github.com/fmtlib/fmt/pull/2960). + Thanks @matrackif @Tobi823, @ivan-volnov, @VasiliPupkin256, + @federico-busato, @barcharcraz, @jk-jeon, @HazardyKnusperkeks, @dalboris, + @seanm, @gsjaardema, @timsong-cpp, @seanm, @frithrah, @chronoxor, @Agga, + @madmaxoft, @JurajX, @phprus and @Dani-Hub. + +# 8.1.1 - 2022-01-06 + +- Restored ABI compatibility with version 8.0.x + (https://github.com/fmtlib/fmt/issues/2695, + https://github.com/fmtlib/fmt/pull/2696). Thanks @saraedum. +- Fixed chrono formatting on big endian systems + (https://github.com/fmtlib/fmt/issues/2698, + https://github.com/fmtlib/fmt/pull/2699). + Thanks @phprus and @xvitaly. +- Fixed a linkage error with mingw + (https://github.com/fmtlib/fmt/issues/2691, + https://github.com/fmtlib/fmt/pull/2692). Thanks @rbberger. + +# 8.1.0 - 2022-01-02 + +- Optimized chrono formatting + (https://github.com/fmtlib/fmt/pull/2500, + https://github.com/fmtlib/fmt/pull/2537, + https://github.com/fmtlib/fmt/issues/2541, + https://github.com/fmtlib/fmt/pull/2544, + https://github.com/fmtlib/fmt/pull/2550, + https://github.com/fmtlib/fmt/pull/2551, + https://github.com/fmtlib/fmt/pull/2576, + https://github.com/fmtlib/fmt/issues/2577, + https://github.com/fmtlib/fmt/pull/2586, + https://github.com/fmtlib/fmt/pull/2591, + https://github.com/fmtlib/fmt/pull/2594, + https://github.com/fmtlib/fmt/pull/2602, + https://github.com/fmtlib/fmt/pull/2617, + https://github.com/fmtlib/fmt/issues/2628, + https://github.com/fmtlib/fmt/pull/2633, + https://github.com/fmtlib/fmt/issues/2670, + https://github.com/fmtlib/fmt/pull/2671). + + Processing of some specifiers such as `%z` and `%Y` is now up to + 10-20 times faster, for example on GCC 11 with libstdc++: + + ---------------------------------------------------------------------------- + Benchmark Before After + ---------------------------------------------------------------------------- + FMTFormatter_z 261 ns 26.3 ns + FMTFormatterCompile_z 246 ns 11.6 ns + FMTFormatter_Y 263 ns 26.1 ns + FMTFormatterCompile_Y 244 ns 10.5 ns + ---------------------------------------------------------------------------- + + Thanks @phprus and @toughengineer. + +- Implemented subsecond formatting for chrono durations + (https://github.com/fmtlib/fmt/pull/2623). For example + ([godbolt](https://godbolt.org/z/es7vWTETe)): + + ```c++ + #include + + int main() { + fmt::print("{:%S}", std::chrono::milliseconds(1234)); + } + ``` + + prints \"01.234\". + + Thanks @matrackif. + +- Fixed handling of precision 0 when formatting chrono durations + (https://github.com/fmtlib/fmt/issues/2587, + https://github.com/fmtlib/fmt/pull/2588). Thanks @lukester1975. + +- Fixed an overflow on invalid inputs in the `tm` formatter + (https://github.com/fmtlib/fmt/pull/2564). Thanks @phprus. + +- Added `fmt::group_digits` that formats integers with a non-localized + digit separator (comma) for groups of three digits. For example + ([godbolt](https://godbolt.org/z/TxGxG9Poq)): + + ```c++ + #include + + int main() { + fmt::print("{} dollars", fmt::group_digits(1000000)); + } + ``` + + prints \"1,000,000 dollars\". + +- Added support for faint, conceal, reverse and blink text styles + (https://github.com/fmtlib/fmt/pull/2394): + + + + Thanks @benit8 and @data-man. + +- Added experimental support for compile-time floating point + formatting (https://github.com/fmtlib/fmt/pull/2426, + https://github.com/fmtlib/fmt/pull/2470). It is currently + limited to the header-only mode. Thanks @alexezeder. + +- Added UDL-based named argument support to compile-time format string + checks (https://github.com/fmtlib/fmt/issues/2640, + https://github.com/fmtlib/fmt/pull/2649). For example + ([godbolt](https://godbolt.org/z/ohGbbvonv)): + + ```c++ + #include + + int main() { + using namespace fmt::literals; + fmt::print("{answer:s}", "answer"_a=42); + } + ``` + + gives a compile-time error on compilers with C++20 `consteval` and + non-type template parameter support (gcc 10+) because `s` is not a + valid format specifier for an integer. + + Thanks @alexezeder. + +- Implemented escaping of string range elements. For example + ([godbolt](https://godbolt.org/z/rKvM1vKf3)): + + ```c++ + #include + #include + + int main() { + fmt::print("{}", std::vector{"\naan"}); + } + ``` + + is now printed as: + + ["\naan"] + + instead of: + + [" + aan"] + +- Added an experimental `?` specifier for escaping strings. + (https://github.com/fmtlib/fmt/pull/2674). Thanks @BRevzin. + +- Switched to JSON-like representation of maps and sets for + consistency with Python\'s `str.format`. For example + ([godbolt](https://godbolt.org/z/seKjoY9W5)): + + ```c++ + #include + #include + + int main() { + fmt::print("{}", std::map{{"answer", 42}}); + } + ``` + + is now printed as: + + {"answer": 42} + +- Extended `fmt::join` to support C++20-only ranges + (https://github.com/fmtlib/fmt/pull/2549). Thanks @BRevzin. + +- Optimized handling of non-const-iterable ranges and implemented + initial support for non-const-formattable types. + +- Disabled implicit conversions of scoped enums to integers that was + accidentally introduced in earlier versions + (https://github.com/fmtlib/fmt/pull/1841). + +- Deprecated implicit conversion of `[const] signed char*` and + `[const] unsigned char*` to C strings. + +- Deprecated `_format`, a legacy UDL-based format API + (https://github.com/fmtlib/fmt/pull/2646). Thanks @alexezeder. + +- Marked `format`, `formatted_size` and `to_string` as `[[nodiscard]]` + (https://github.com/fmtlib/fmt/pull/2612). @0x8000-0000. + +- Added missing diagnostic when trying to format function and member + pointers as well as objects convertible to pointers which is + explicitly disallowed + (https://github.com/fmtlib/fmt/issues/2598, + https://github.com/fmtlib/fmt/pull/2609, + https://github.com/fmtlib/fmt/pull/2610). Thanks @AlexGuteniev. + +- Optimized writing to a contiguous buffer with `format_to_n` + (https://github.com/fmtlib/fmt/pull/2489). Thanks @Roman-Koshelev. + +- Optimized writing to non-`char` buffers + (https://github.com/fmtlib/fmt/pull/2477). Thanks @Roman-Koshelev. + +- Decimal point is now localized when using the `L` specifier. + +- Improved floating point formatter implementation + (https://github.com/fmtlib/fmt/pull/2498, + https://github.com/fmtlib/fmt/pull/2499). Thanks @Roman-Koshelev. + +- Fixed handling of very large precision in fixed format + (https://github.com/fmtlib/fmt/pull/2616). + +- Made a table of cached powers used in FP formatting static + (https://github.com/fmtlib/fmt/pull/2509). Thanks @jk-jeon. + +- Resolved a lookup ambiguity with C++20 format-related functions due + to ADL (https://github.com/fmtlib/fmt/issues/2639, + https://github.com/fmtlib/fmt/pull/2641). Thanks @mkurdej. + +- Removed unnecessary inline namespace qualification + (https://github.com/fmtlib/fmt/issues/2642, + https://github.com/fmtlib/fmt/pull/2643). Thanks @mkurdej. + +- Implemented argument forwarding in `format_to_n` + (https://github.com/fmtlib/fmt/issues/2462, + https://github.com/fmtlib/fmt/pull/2463). Thanks @owent. + +- Fixed handling of implicit conversions in `fmt::to_string` and + format string compilation + (https://github.com/fmtlib/fmt/issues/2565). + +- Changed the default access mode of files created by + `fmt::output_file` to `-rw-r--r--` for consistency with `fopen` + (https://github.com/fmtlib/fmt/issues/2530). + +- Make `fmt::ostream::flush` public + (https://github.com/fmtlib/fmt/issues/2435). + +- Improved C++14/17 attribute detection + (https://github.com/fmtlib/fmt/pull/2615). Thanks @AlexGuteniev. + +- Improved `consteval` detection for MSVC + (https://github.com/fmtlib/fmt/pull/2559). Thanks @DanielaE. + +- Improved documentation + (https://github.com/fmtlib/fmt/issues/2406, + https://github.com/fmtlib/fmt/pull/2446, + https://github.com/fmtlib/fmt/issues/2493, + https://github.com/fmtlib/fmt/issues/2513, + https://github.com/fmtlib/fmt/pull/2515, + https://github.com/fmtlib/fmt/issues/2522, + https://github.com/fmtlib/fmt/pull/2562, + https://github.com/fmtlib/fmt/pull/2575, + https://github.com/fmtlib/fmt/pull/2606, + https://github.com/fmtlib/fmt/pull/2620, + https://github.com/fmtlib/fmt/issues/2676). + Thanks @sobolevn, @UnePierre, @zhsj, @phprus, @ericcurtin and @Lounarok. + +- Improved fuzzers and added a fuzzer for chrono timepoint formatting + (https://github.com/fmtlib/fmt/pull/2461, + https://github.com/fmtlib/fmt/pull/2469). @pauldreik, + +- Added the `FMT_SYSTEM_HEADERS` CMake option setting which marks + {fmt}\'s headers as system. It can be used to suppress warnings + (https://github.com/fmtlib/fmt/issues/2644, + https://github.com/fmtlib/fmt/pull/2651). Thanks @alexezeder. + +- Added the Bazel build system support + (https://github.com/fmtlib/fmt/pull/2505, + https://github.com/fmtlib/fmt/pull/2516). Thanks @Vertexwahn. + +- Improved build configuration and tests + (https://github.com/fmtlib/fmt/issues/2437, + https://github.com/fmtlib/fmt/pull/2558, + https://github.com/fmtlib/fmt/pull/2648, + https://github.com/fmtlib/fmt/pull/2650, + https://github.com/fmtlib/fmt/pull/2663, + https://github.com/fmtlib/fmt/pull/2677). + Thanks @DanielaE, @alexezeder and @phprus. + +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/pull/2353, + https://github.com/fmtlib/fmt/pull/2356, + https://github.com/fmtlib/fmt/pull/2399, + https://github.com/fmtlib/fmt/issues/2408, + https://github.com/fmtlib/fmt/pull/2414, + https://github.com/fmtlib/fmt/pull/2427, + https://github.com/fmtlib/fmt/pull/2432, + https://github.com/fmtlib/fmt/pull/2442, + https://github.com/fmtlib/fmt/pull/2434, + https://github.com/fmtlib/fmt/issues/2439, + https://github.com/fmtlib/fmt/pull/2447, + https://github.com/fmtlib/fmt/pull/2450, + https://github.com/fmtlib/fmt/issues/2455, + https://github.com/fmtlib/fmt/issues/2465, + https://github.com/fmtlib/fmt/issues/2472, + https://github.com/fmtlib/fmt/issues/2474, + https://github.com/fmtlib/fmt/pull/2476, + https://github.com/fmtlib/fmt/issues/2478, + https://github.com/fmtlib/fmt/issues/2479, + https://github.com/fmtlib/fmt/issues/2481, + https://github.com/fmtlib/fmt/pull/2482, + https://github.com/fmtlib/fmt/pull/2483, + https://github.com/fmtlib/fmt/issues/2490, + https://github.com/fmtlib/fmt/pull/2491, + https://github.com/fmtlib/fmt/pull/2510, + https://github.com/fmtlib/fmt/pull/2518, + https://github.com/fmtlib/fmt/issues/2528, + https://github.com/fmtlib/fmt/pull/2529, + https://github.com/fmtlib/fmt/pull/2539, + https://github.com/fmtlib/fmt/issues/2540, + https://github.com/fmtlib/fmt/pull/2545, + https://github.com/fmtlib/fmt/pull/2555, + https://github.com/fmtlib/fmt/issues/2557, + https://github.com/fmtlib/fmt/issues/2570, + https://github.com/fmtlib/fmt/pull/2573, + https://github.com/fmtlib/fmt/pull/2582, + https://github.com/fmtlib/fmt/issues/2605, + https://github.com/fmtlib/fmt/pull/2611, + https://github.com/fmtlib/fmt/pull/2647, + https://github.com/fmtlib/fmt/issues/2627, + https://github.com/fmtlib/fmt/pull/2630, + https://github.com/fmtlib/fmt/issues/2635, + https://github.com/fmtlib/fmt/issues/2638, + https://github.com/fmtlib/fmt/issues/2653, + https://github.com/fmtlib/fmt/issues/2654, + https://github.com/fmtlib/fmt/issues/2661, + https://github.com/fmtlib/fmt/pull/2664, + https://github.com/fmtlib/fmt/pull/2684). + Thanks @DanielaE, @mwinterb, @cdacamar, @TrebledJ, @bodomartin, @cquammen, + @white238, @mmarkeloff, @palacaze, @jcelerier, @mborn-adi, @BrukerJWD, + @spyridon97, @phprus, @oliverlee, @joshessman-llnl, @akohlmey, @timkalu, + @olupton, @Acretock, @alexezeder, @andrewcorrigan, @lucpelletier and + @HazardyKnusperkeks. + +# 8.0.1 - 2021-07-02 + +- Fixed the version number in the inline namespace + (https://github.com/fmtlib/fmt/issues/2374). +- Added a missing presentation type check for `std::string` + (https://github.com/fmtlib/fmt/issues/2402). +- Fixed a linkage error when mixing code built with clang and gcc + (https://github.com/fmtlib/fmt/issues/2377). +- Fixed documentation issues + (https://github.com/fmtlib/fmt/pull/2396, + https://github.com/fmtlib/fmt/issues/2403, + https://github.com/fmtlib/fmt/issues/2406). Thanks @mkurdej. +- Removed dead code in FP formatter ( + https://github.com/fmtlib/fmt/pull/2398). Thanks @javierhonduco. +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/issues/2351, + https://github.com/fmtlib/fmt/issues/2359, + https://github.com/fmtlib/fmt/pull/2365, + https://github.com/fmtlib/fmt/issues/2368, + https://github.com/fmtlib/fmt/pull/2370, + https://github.com/fmtlib/fmt/pull/2376, + https://github.com/fmtlib/fmt/pull/2381, + https://github.com/fmtlib/fmt/pull/2382, + https://github.com/fmtlib/fmt/issues/2386, + https://github.com/fmtlib/fmt/pull/2389, + https://github.com/fmtlib/fmt/pull/2395, + https://github.com/fmtlib/fmt/pull/2397, + https://github.com/fmtlib/fmt/issues/2400, + https://github.com/fmtlib/fmt/issues/2401, + https://github.com/fmtlib/fmt/pull/2407). + Thanks @zx2c4, @AidanSun05, @mattiasljungstrom, @joemmett, @erengy, + @patlkli, @gsjaardema and @phprus. + +# 8.0.0 - 2021-06-21 + +- Enabled compile-time format string checks by default. For example + ([godbolt](https://godbolt.org/z/sMxcohGjz)): + + ```c++ + #include + + int main() { + fmt::print("{:d}", "I am not a number"); + } + ``` + + gives a compile-time error on compilers with C++20 `consteval` + support (gcc 10+, clang 11+) because `d` is not a valid format + specifier for a string. + + To pass a runtime string wrap it in `fmt::runtime`: + + ```c++ + fmt::print(fmt::runtime("{:d}"), "I am not a number"); + ``` + +- Added compile-time formatting + (https://github.com/fmtlib/fmt/pull/2019, + https://github.com/fmtlib/fmt/pull/2044, + https://github.com/fmtlib/fmt/pull/2056, + https://github.com/fmtlib/fmt/pull/2072, + https://github.com/fmtlib/fmt/pull/2075, + https://github.com/fmtlib/fmt/issues/2078, + https://github.com/fmtlib/fmt/pull/2129, + https://github.com/fmtlib/fmt/pull/2326). For example + ([godbolt](https://godbolt.org/z/Mxx9d89jM)): + + ```c++ + #include + + consteval auto compile_time_itoa(int value) -> std::array { + auto result = std::array(); + fmt::format_to(result.data(), FMT_COMPILE("{}"), value); + return result; + } + + constexpr auto answer = compile_time_itoa(42); + ``` + + Most of the formatting functionality is available at compile time + with a notable exception of floating-point numbers and pointers. + Thanks @alexezeder. + +- Optimized handling of format specifiers during format string + compilation. For example, hexadecimal formatting (`"{:x}"`) is now + 3-7x faster than before when using `format_to` with format string + compilation and a stack-allocated buffer + (https://github.com/fmtlib/fmt/issues/1944). + + Before (7.1.3): + + ---------------------------------------------------------------------------- + Benchmark Time CPU Iterations + ---------------------------------------------------------------------------- + FMTCompileOld/0 15.5 ns 15.5 ns 43302898 + FMTCompileOld/42 16.6 ns 16.6 ns 43278267 + FMTCompileOld/273123 18.7 ns 18.6 ns 37035861 + FMTCompileOld/9223372036854775807 19.4 ns 19.4 ns 35243000 + ---------------------------------------------------------------------------- + + After (8.x): + + ---------------------------------------------------------------------------- + Benchmark Time CPU Iterations + ---------------------------------------------------------------------------- + FMTCompileNew/0 1.99 ns 1.99 ns 360523686 + FMTCompileNew/42 2.33 ns 2.33 ns 279865664 + FMTCompileNew/273123 3.72 ns 3.71 ns 190230315 + FMTCompileNew/9223372036854775807 5.28 ns 5.26 ns 130711631 + ---------------------------------------------------------------------------- + + It is even faster than `std::to_chars` from libc++ compiled with + clang on macOS: + + ---------------------------------------------------------------------------- + Benchmark Time CPU Iterations + ---------------------------------------------------------------------------- + ToChars/0 4.42 ns 4.41 ns 160196630 + ToChars/42 5.00 ns 4.98 ns 140735201 + ToChars/273123 7.26 ns 7.24 ns 95784130 + ToChars/9223372036854775807 8.77 ns 8.75 ns 75872534 + ---------------------------------------------------------------------------- + + In other cases, especially involving `std::string` construction, the + speed up is usually lower because handling format specifiers takes a + smaller fraction of the total time. + +- Added the `_cf` user-defined literal to represent a compiled format + string. It can be used instead of the `FMT_COMPILE` macro + (https://github.com/fmtlib/fmt/pull/2043, + https://github.com/fmtlib/fmt/pull/2242): + + ```c++ + #include + + using namespace fmt::literals; + auto s = fmt::format(FMT_COMPILE("{}"), 42); // 🙠not modern + auto s = fmt::format("{}"_cf, 42); // 🙂 modern as hell + ``` + + It requires compiler support for class types in non-type template + parameters (a C++20 feature) which is available in GCC 9.3+. + Thanks @alexezeder. + +- Format string compilation now requires `format` functions of + `formatter` specializations for user-defined types to be `const`: + + ```c++ + template <> struct fmt::formatter: formatter { + template + auto format(my_type obj, FormatContext& ctx) const { // Note const here. + // ... + } + }; + ``` + +- Added UDL-based named argument support to format string compilation + (https://github.com/fmtlib/fmt/pull/2243, + https://github.com/fmtlib/fmt/pull/2281). For example: + + ```c++ + #include + + using namespace fmt::literals; + auto s = fmt::format(FMT_COMPILE("{answer}"), "answer"_a = 42); + ``` + + Here the argument named \"answer\" is resolved at compile time with + no runtime overhead. Thanks @alexezeder. + +- Added format string compilation support to `fmt::print` + (https://github.com/fmtlib/fmt/issues/2280, + https://github.com/fmtlib/fmt/pull/2304). Thanks @alexezeder. + +- Added initial support for compiling {fmt} as a C++20 module + (https://github.com/fmtlib/fmt/pull/2235, + https://github.com/fmtlib/fmt/pull/2240, + https://github.com/fmtlib/fmt/pull/2260, + https://github.com/fmtlib/fmt/pull/2282, + https://github.com/fmtlib/fmt/pull/2283, + https://github.com/fmtlib/fmt/pull/2288, + https://github.com/fmtlib/fmt/pull/2298, + https://github.com/fmtlib/fmt/pull/2306, + https://github.com/fmtlib/fmt/pull/2307, + https://github.com/fmtlib/fmt/pull/2309, + https://github.com/fmtlib/fmt/pull/2318, + https://github.com/fmtlib/fmt/pull/2324, + https://github.com/fmtlib/fmt/pull/2332, + https://github.com/fmtlib/fmt/pull/2340). Thanks @DanielaE. + +- Made symbols private by default reducing shared library size + (https://github.com/fmtlib/fmt/pull/2301). For example + there was a \~15% reported reduction on one platform. Thanks @sergiud. + +- Optimized includes making the result of preprocessing `fmt/format.h` + \~20% smaller with libstdc++/C++20 and slightly improving build + times (https://github.com/fmtlib/fmt/issues/1998). + +- Added support of ranges with non-const `begin` / `end` + (https://github.com/fmtlib/fmt/pull/1953). Thanks @kitegi. + +- Added support of `std::byte` and other formattable types to + `fmt::join` (https://github.com/fmtlib/fmt/issues/1981, + https://github.com/fmtlib/fmt/issues/2040, + https://github.com/fmtlib/fmt/pull/2050, + https://github.com/fmtlib/fmt/issues/2262). For example: + + ```c++ + #include + #include + #include + + int main() { + auto bytes = std::vector{std::byte(4), std::byte(2)}; + fmt::print("{}", fmt::join(bytes, "")); + } + ``` + + prints \"42\". + + Thanks @kamibo. + +- Implemented the default format for `std::chrono::system_clock` + (https://github.com/fmtlib/fmt/issues/2319, + https://github.com/fmtlib/fmt/pull/2345). For example: + + ```c++ + #include + + int main() { + fmt::print("{}", std::chrono::system_clock::now()); + } + ``` + + prints \"2021-06-18 15:22:00\" (the output depends on the current + date and time). Thanks @sunmy2019. + +- Made more chrono specifiers locale independent by default. Use the + `'L'` specifier to get localized formatting. For example: + + ```c++ + #include + + int main() { + std::locale::global(std::locale("ru_RU.UTF-8")); + auto monday = std::chrono::weekday(1); + fmt::print("{}\n", monday); // prints "Mon" + fmt::print("{:L}\n", monday); // prints "пн" + } + ``` + +- Improved locale handling in chrono formatting + (https://github.com/fmtlib/fmt/issues/2337, + https://github.com/fmtlib/fmt/pull/2349, + https://github.com/fmtlib/fmt/pull/2350). Thanks @phprus. + +- Deprecated `fmt/locale.h` moving the formatting functions that take + a locale to `fmt/format.h` (`char`) and `fmt/xchar` (other + overloads). This doesn\'t introduce a dependency on `` so + there is virtually no compile time effect. + +- Deprecated an undocumented `format_to` overload that takes + `basic_memory_buffer`. + +- Made parameter order in `vformat_to` consistent with `format_to` + (https://github.com/fmtlib/fmt/issues/2327). + +- Added support for time points with arbitrary durations + (https://github.com/fmtlib/fmt/issues/2208). For example: + + ```c++ + #include + + int main() { + using tp = std::chrono::time_point< + std::chrono::system_clock, std::chrono::seconds>; + fmt::print("{:%S}", tp(std::chrono::seconds(42))); + } + ``` + + prints \"42\". + +- Formatting floating-point numbers no longer produces trailing zeros + by default for consistency with `std::format`. For example: + + ```c++ + #include + + int main() { + fmt::print("{0:.3}", 1.1); + } + ``` + + prints \"1.1\". Use the `'#'` specifier to keep trailing zeros. + +- Dropped a limit on the number of elements in a range and replaced + `{}` with `[]` as range delimiters for consistency with Python\'s + `str.format`. + +- The `'L'` specifier for locale-specific numeric formatting can now + be combined with presentation specifiers as in `std::format`. For + example: + + ```c++ + #include + #include + + int main() { + std::locale::global(std::locale("fr_FR.UTF-8")); + fmt::print("{0:.2Lf}", 0.42); + } + ``` + + prints \"0,42\". The deprecated `'n'` specifier has been removed. + +- Made the `0` specifier ignored for infinity and NaN + (https://github.com/fmtlib/fmt/issues/2305, + https://github.com/fmtlib/fmt/pull/2310). Thanks @Liedtke. + +- Made the hexfloat formatting use the right alignment by default + (https://github.com/fmtlib/fmt/issues/2308, + https://github.com/fmtlib/fmt/pull/2317). Thanks @Liedtke. + +- Removed the deprecated numeric alignment (`'='`). Use the `'0'` + specifier instead. + +- Removed the deprecated `fmt/posix.h` header that has been replaced + with `fmt/os.h`. + +- Removed the deprecated `format_to_n_context`, `format_to_n_args` and + `make_format_to_n_args`. They have been replaced with + `format_context`, `` format_args` and ``make_format_args\`\` + respectively. + +- Moved `wchar_t`-specific functions and types to `fmt/xchar.h`. You + can define `FMT_DEPRECATED_INCLUDE_XCHAR` to automatically include + `fmt/xchar.h` from `fmt/format.h` but this will be disabled in the + next major release. + +- Fixed handling of the `'+'` specifier in localized formatting + (https://github.com/fmtlib/fmt/issues/2133). + +- Added support for the `'s'` format specifier that gives textual + representation of `bool` + (https://github.com/fmtlib/fmt/issues/2094, + https://github.com/fmtlib/fmt/pull/2109). For example: + + ```c++ + #include + + int main() { + fmt::print("{:s}", true); + } + ``` + + prints \"true\". Thanks @powercoderlol. + +- Made `fmt::ptr` work with function pointers + (https://github.com/fmtlib/fmt/pull/2131). For example: + + ```c++ + #include + + int main() { + fmt::print("My main: {}\n", fmt::ptr(main)); + } + ``` + + Thanks @mikecrowe. + +- The undocumented support for specializing `formatter` for pointer + types has been removed. + +- Fixed `fmt::formatted_size` with format string compilation + (https://github.com/fmtlib/fmt/pull/2141, + https://github.com/fmtlib/fmt/pull/2161). Thanks @alexezeder. + +- Fixed handling of empty format strings during format string + compilation (https://github.com/fmtlib/fmt/issues/2042): + + ```c++ + auto s = fmt::format(FMT_COMPILE("")); + ``` + + Thanks @alexezeder. + +- Fixed handling of enums in `fmt::to_string` + (https://github.com/fmtlib/fmt/issues/2036). + +- Improved width computation + (https://github.com/fmtlib/fmt/issues/2033, + https://github.com/fmtlib/fmt/issues/2091). For example: + + ```c++ + #include + + int main() { + fmt::print("{:-<10}{}\n", "你好", "世界"); + fmt::print("{:-<10}{}\n", "hello", "world"); + } + ``` + + prints + + ![](https://user-images.githubusercontent.com/576385/119840373-cea3ca80-beb9-11eb-91e0-54266c48e181.png) + + on a modern terminal. + +- The experimental fast output stream (`fmt::ostream`) is now + truncated by default for consistency with `fopen` + (https://github.com/fmtlib/fmt/issues/2018). For example: + + ```c++ + #include + + int main() { + fmt::ostream out1 = fmt::output_file("guide"); + out1.print("Zaphod"); + out1.close(); + fmt::ostream out2 = fmt::output_file("guide"); + out2.print("Ford"); + } + ``` + + writes \"Ford\" to the file \"guide\". To preserve the old file + content if any pass `fmt::file::WRONLY | fmt::file::CREATE` flags to + `fmt::output_file`. + +- Fixed moving of `fmt::ostream` that holds buffered data + (https://github.com/fmtlib/fmt/issues/2197, + https://github.com/fmtlib/fmt/pull/2198). Thanks @vtta. + +- Replaced the `fmt::system_error` exception with a function of the + same name that constructs `std::system_error` + (https://github.com/fmtlib/fmt/issues/2266). + +- Replaced the `fmt::windows_error` exception with a function of the + same name that constructs `std::system_error` with the category + returned by `fmt::system_category()` + (https://github.com/fmtlib/fmt/issues/2274, + https://github.com/fmtlib/fmt/pull/2275). The latter is + similar to `std::sytem_category` but correctly handles UTF-8. + Thanks @phprus. + +- Replaced `fmt::error_code` with `std::error_code` and made it + formattable (https://github.com/fmtlib/fmt/issues/2269, + https://github.com/fmtlib/fmt/pull/2270, + https://github.com/fmtlib/fmt/pull/2273). Thanks @phprus. + +- Added speech synthesis support + (https://github.com/fmtlib/fmt/pull/2206). + +- Made `format_to` work with a memory buffer that has a custom + allocator (https://github.com/fmtlib/fmt/pull/2300). + Thanks @voxmea. + +- Added `Allocator::max_size` support to `basic_memory_buffer`. + (https://github.com/fmtlib/fmt/pull/1960). Thanks @phprus. + +- Added wide string support to `fmt::join` + (https://github.com/fmtlib/fmt/pull/2236). Thanks @crbrz. + +- Made iterators passed to `formatter` specializations via a format + context satisfy C++20 `std::output_iterator` requirements + (https://github.com/fmtlib/fmt/issues/2156, + https://github.com/fmtlib/fmt/pull/2158, + https://github.com/fmtlib/fmt/issues/2195, + https://github.com/fmtlib/fmt/pull/2204). Thanks @randomnetcat. + +- Optimized the `printf` implementation + (https://github.com/fmtlib/fmt/pull/1982, + https://github.com/fmtlib/fmt/pull/1984, + https://github.com/fmtlib/fmt/pull/2016, + https://github.com/fmtlib/fmt/pull/2164). + Thanks @rimathia and @moiwi. + +- Improved detection of `constexpr` `char_traits` + (https://github.com/fmtlib/fmt/pull/2246, + https://github.com/fmtlib/fmt/pull/2257). Thanks @phprus. + +- Fixed writing to `stdout` when it is redirected to `NUL` on Windows + (https://github.com/fmtlib/fmt/issues/2080). + +- Fixed exception propagation from iterators + (https://github.com/fmtlib/fmt/issues/2097). + +- Improved `strftime` error handling + (https://github.com/fmtlib/fmt/issues/2238, + https://github.com/fmtlib/fmt/pull/2244). Thanks @yumeyao. + +- Stopped using deprecated GCC UDL template extension. + +- Added `fmt/args.h` to the install target + (https://github.com/fmtlib/fmt/issues/2096). + +- Error messages are now passed to assert when exceptions are disabled + (https://github.com/fmtlib/fmt/pull/2145). Thanks @NobodyXu. + +- Added the `FMT_MASTER_PROJECT` CMake option to control build and + install targets when {fmt} is included via `add_subdirectory` + (https://github.com/fmtlib/fmt/issues/2098, + https://github.com/fmtlib/fmt/pull/2100). + Thanks @randomizedthinking. + +- Improved build configuration + (https://github.com/fmtlib/fmt/pull/2026, + https://github.com/fmtlib/fmt/pull/2122). + Thanks @luncliff and @ibaned. + +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/issues/1947, + https://github.com/fmtlib/fmt/pull/1959, + https://github.com/fmtlib/fmt/pull/1963, + https://github.com/fmtlib/fmt/pull/1965, + https://github.com/fmtlib/fmt/issues/1966, + https://github.com/fmtlib/fmt/pull/1974, + https://github.com/fmtlib/fmt/pull/1975, + https://github.com/fmtlib/fmt/pull/1990, + https://github.com/fmtlib/fmt/issues/2000, + https://github.com/fmtlib/fmt/pull/2001, + https://github.com/fmtlib/fmt/issues/2002, + https://github.com/fmtlib/fmt/issues/2004, + https://github.com/fmtlib/fmt/pull/2006, + https://github.com/fmtlib/fmt/pull/2009, + https://github.com/fmtlib/fmt/pull/2010, + https://github.com/fmtlib/fmt/issues/2038, + https://github.com/fmtlib/fmt/issues/2039, + https://github.com/fmtlib/fmt/issues/2047, + https://github.com/fmtlib/fmt/pull/2053, + https://github.com/fmtlib/fmt/issues/2059, + https://github.com/fmtlib/fmt/pull/2065, + https://github.com/fmtlib/fmt/pull/2067, + https://github.com/fmtlib/fmt/pull/2068, + https://github.com/fmtlib/fmt/pull/2073, + https://github.com/fmtlib/fmt/issues/2103, + https://github.com/fmtlib/fmt/issues/2105, + https://github.com/fmtlib/fmt/pull/2106, + https://github.com/fmtlib/fmt/pull/2107, + https://github.com/fmtlib/fmt/issues/2116, + https://github.com/fmtlib/fmt/pull/2117, + https://github.com/fmtlib/fmt/issues/2118, + https://github.com/fmtlib/fmt/pull/2119, + https://github.com/fmtlib/fmt/issues/2127, + https://github.com/fmtlib/fmt/pull/2128, + https://github.com/fmtlib/fmt/issues/2140, + https://github.com/fmtlib/fmt/issues/2142, + https://github.com/fmtlib/fmt/pull/2143, + https://github.com/fmtlib/fmt/pull/2144, + https://github.com/fmtlib/fmt/issues/2147, + https://github.com/fmtlib/fmt/issues/2148, + https://github.com/fmtlib/fmt/issues/2149, + https://github.com/fmtlib/fmt/pull/2152, + https://github.com/fmtlib/fmt/pull/2160, + https://github.com/fmtlib/fmt/issues/2170, + https://github.com/fmtlib/fmt/issues/2175, + https://github.com/fmtlib/fmt/issues/2176, + https://github.com/fmtlib/fmt/pull/2177, + https://github.com/fmtlib/fmt/issues/2178, + https://github.com/fmtlib/fmt/pull/2179, + https://github.com/fmtlib/fmt/issues/2180, + https://github.com/fmtlib/fmt/issues/2181, + https://github.com/fmtlib/fmt/pull/2183, + https://github.com/fmtlib/fmt/issues/2184, + https://github.com/fmtlib/fmt/issues/2185, + https://github.com/fmtlib/fmt/pull/2186, + https://github.com/fmtlib/fmt/pull/2187, + https://github.com/fmtlib/fmt/pull/2190, + https://github.com/fmtlib/fmt/pull/2192, + https://github.com/fmtlib/fmt/pull/2194, + https://github.com/fmtlib/fmt/pull/2205, + https://github.com/fmtlib/fmt/issues/2210, + https://github.com/fmtlib/fmt/pull/2211, + https://github.com/fmtlib/fmt/pull/2215, + https://github.com/fmtlib/fmt/pull/2216, + https://github.com/fmtlib/fmt/pull/2218, + https://github.com/fmtlib/fmt/pull/2220, + https://github.com/fmtlib/fmt/issues/2228, + https://github.com/fmtlib/fmt/pull/2229, + https://github.com/fmtlib/fmt/pull/2230, + https://github.com/fmtlib/fmt/issues/2233, + https://github.com/fmtlib/fmt/pull/2239, + https://github.com/fmtlib/fmt/issues/2248, + https://github.com/fmtlib/fmt/issues/2252, + https://github.com/fmtlib/fmt/pull/2253, + https://github.com/fmtlib/fmt/pull/2255, + https://github.com/fmtlib/fmt/issues/2261, + https://github.com/fmtlib/fmt/issues/2278, + https://github.com/fmtlib/fmt/issues/2284, + https://github.com/fmtlib/fmt/pull/2287, + https://github.com/fmtlib/fmt/pull/2289, + https://github.com/fmtlib/fmt/pull/2290, + https://github.com/fmtlib/fmt/pull/2293, + https://github.com/fmtlib/fmt/issues/2295, + https://github.com/fmtlib/fmt/pull/2296, + https://github.com/fmtlib/fmt/pull/2297, + https://github.com/fmtlib/fmt/issues/2311, + https://github.com/fmtlib/fmt/pull/2313, + https://github.com/fmtlib/fmt/pull/2315, + https://github.com/fmtlib/fmt/issues/2320, + https://github.com/fmtlib/fmt/pull/2321, + https://github.com/fmtlib/fmt/pull/2323, + https://github.com/fmtlib/fmt/issues/2328, + https://github.com/fmtlib/fmt/pull/2329, + https://github.com/fmtlib/fmt/pull/2333, + https://github.com/fmtlib/fmt/pull/2338, + https://github.com/fmtlib/fmt/pull/2341). + Thanks @darklukee, @fagg, @killerbot242, @jgopel, @yeswalrus, @Finkman, + @HazardyKnusperkeks, @dkavolis, @concatime, @chronoxor, @summivox, @yNeo, + @Apache-HB, @alexezeder, @toojays, @Brainy0207, @vadz, @imsherlock, @phprus, + @white238, @yafshar, @BillyDonahue, @jstaahl, @denchat, @DanielaE, + @ilyakurdyukov, @ilmai, @JessyDL, @sergiud, @mwinterb, @sven-herrmann, + @jmelas, @twoixter, @crbrz and @upsj. + +- Improved documentation + (https://github.com/fmtlib/fmt/issues/1986, + https://github.com/fmtlib/fmt/pull/2051, + https://github.com/fmtlib/fmt/issues/2057, + https://github.com/fmtlib/fmt/pull/2081, + https://github.com/fmtlib/fmt/issues/2084, + https://github.com/fmtlib/fmt/pull/2312). + Thanks @imba-tjd, @0x416c69 and @mordante. + +- Continuous integration and test improvements + (https://github.com/fmtlib/fmt/issues/1969, + https://github.com/fmtlib/fmt/pull/1991, + https://github.com/fmtlib/fmt/pull/2020, + https://github.com/fmtlib/fmt/pull/2110, + https://github.com/fmtlib/fmt/pull/2114, + https://github.com/fmtlib/fmt/issues/2196, + https://github.com/fmtlib/fmt/pull/2217, + https://github.com/fmtlib/fmt/pull/2247, + https://github.com/fmtlib/fmt/pull/2256, + https://github.com/fmtlib/fmt/pull/2336, + https://github.com/fmtlib/fmt/pull/2346). + Thanks @jgopel, @alexezeder and @DanielaE. + +# 7.1.3 - 2020-11-24 + +- Fixed handling of buffer boundaries in `format_to_n` + (https://github.com/fmtlib/fmt/issues/1996, + https://github.com/fmtlib/fmt/issues/2029). +- Fixed linkage errors when linking with a shared library + (https://github.com/fmtlib/fmt/issues/2011). +- Reintroduced ostream support to range formatters + (https://github.com/fmtlib/fmt/issues/2014). +- Worked around an issue with mixing std versions in gcc + (https://github.com/fmtlib/fmt/issues/2017). + +# 7.1.2 - 2020-11-04 + +- Fixed floating point formatting with large precision + (https://github.com/fmtlib/fmt/issues/1976). + +# 7.1.1 - 2020-11-01 + +- Fixed ABI compatibility with 7.0.x + (https://github.com/fmtlib/fmt/issues/1961). +- Added the `FMT_ARM_ABI_COMPATIBILITY` macro to work around ABI + incompatibility between GCC and Clang on ARM + (https://github.com/fmtlib/fmt/issues/1919). +- Worked around a SFINAE bug in GCC 8 + (https://github.com/fmtlib/fmt/issues/1957). +- Fixed linkage errors when building with GCC\'s LTO + (https://github.com/fmtlib/fmt/issues/1955). +- Fixed a compilation error when building without `__builtin_clz` or + equivalent (https://github.com/fmtlib/fmt/pull/1968). + Thanks @tohammer. +- Fixed a sign conversion warning + (https://github.com/fmtlib/fmt/pull/1964). Thanks @OptoCloud. + +# 7.1.0 - 2020-10-25 + +- Switched from + [Grisu3](https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf) + to [Dragonbox](https://github.com/jk-jeon/dragonbox) for the default + floating-point formatting which gives the shortest decimal + representation with round-trip guarantee and correct rounding + (https://github.com/fmtlib/fmt/pull/1882, + https://github.com/fmtlib/fmt/pull/1887, + https://github.com/fmtlib/fmt/pull/1894). This makes {fmt} + up to 20-30x faster than common implementations of + `std::ostringstream` and `sprintf` on + [dtoa-benchmark](https://github.com/fmtlib/dtoa-benchmark) and + faster than double-conversion and RyÅ«: + + ![](https://user-images.githubusercontent.com/576385/95684665-11719600-0ba8-11eb-8e5b-972ff4e49428.png) + + It is possible to get even better performance at the cost of larger + binary size by compiling with the `FMT_USE_FULL_CACHE_DRAGONBOX` + macro set to 1. + + Thanks @jk-jeon. + +- Added an experimental unsynchronized file output API which, together + with [format string + compilation](https://fmt.dev/latest/api.html#compile-api), can give + [5-9 times speed up compared to + fprintf](https://www.zverovich.net/2020/08/04/optimal-file-buffer-size.html) + on common platforms ([godbolt](https://godbolt.org/z/nsTcG8)): + + ```c++ + #include + + int main() { + auto f = fmt::output_file("guide"); + f.print("The answer is {}.", 42); + } + ``` + +- Added a formatter for `std::chrono::time_point` + (https://github.com/fmtlib/fmt/issues/1819, + https://github.com/fmtlib/fmt/pull/1837). For example + ([godbolt](https://godbolt.org/z/c4M6fh)): + + ```c++ + #include + + int main() { + auto now = std::chrono::system_clock::now(); + fmt::print("The time is {:%H:%M:%S}.\n", now); + } + ``` + + Thanks @adamburgess. + +- Added support for ranges with non-const `begin`/`end` to `fmt::join` + (https://github.com/fmtlib/fmt/issues/1784, + https://github.com/fmtlib/fmt/pull/1786). For example + ([godbolt](https://godbolt.org/z/jP63Tv)): + + ```c++ + #include + #include + + int main() { + using std::literals::string_literals::operator""s; + auto strs = std::array{"a"s, "bb"s, "ccc"s}; + auto range = strs | ranges::views::filter( + [] (const std::string &x) { return x.size() != 2; } + ); + fmt::print("{}\n", fmt::join(range, "")); + } + ``` + + prints \"accc\". + + Thanks @tonyelewis. + +- Added a `memory_buffer::append` overload that takes a range + (https://github.com/fmtlib/fmt/pull/1806). Thanks @BRevzin. + +- Improved handling of single code units in `FMT_COMPILE`. For + example: + + ```c++ + #include + + char* f(char* buf) { + return fmt::format_to(buf, FMT_COMPILE("x{}"), 42); + } + ``` + + compiles to just ([godbolt](https://godbolt.org/z/5vncz3)): + + ```asm + _Z1fPc: + movb $120, (%rdi) + xorl %edx, %edx + cmpl $42, _ZN3fmt2v76detail10basic_dataIvE23zero_or_powers_of_10_32E+8(%rip) + movl $3, %eax + seta %dl + subl %edx, %eax + movzwl _ZN3fmt2v76detail10basic_dataIvE6digitsE+84(%rip), %edx + cltq + addq %rdi, %rax + movw %dx, -2(%rax) + ret + ``` + + Here a single `mov` instruction writes `'x'` (`$120`) to the output + buffer. + +- Added dynamic width support to format string compilation + (https://github.com/fmtlib/fmt/issues/1809). + +- Improved error reporting for unformattable types: now you\'ll get + the type name directly in the error message instead of the note: + + ```c++ + #include + + struct how_about_no {}; + + int main() { + fmt::print("{}", how_about_no()); + } + ``` + + Error ([godbolt](https://godbolt.org/z/GoxM4e)): + + `fmt/core.h:1438:3: error: static_assert failed due to requirement 'fmt::v7::formattable()' "Cannot format an argument. To make type T formattable provide a formatter specialization: https://fmt.dev/latest/api.html#udt" ...` + +- Added the + [make_args_checked](https://fmt.dev/7.1.0/api.html#argument-lists) + function template that allows you to write formatting functions with + compile-time format string checks and avoid binary code bloat + ([godbolt](https://godbolt.org/z/PEf9qr)): + + ```c++ + void vlog(const char* file, int line, fmt::string_view format, + fmt::format_args args) { + fmt::print("{}: {}: ", file, line); + fmt::vprint(format, args); + } + + template + void log(const char* file, int line, const S& format, Args&&... args) { + vlog(file, line, format, + fmt::make_args_checked(format, args...)); + } + + #define MY_LOG(format, ...) \ + log(__FILE__, __LINE__, FMT_STRING(format), __VA_ARGS__) + + MY_LOG("invalid squishiness: {}", 42); + ``` + +- Replaced `snprintf` fallback with a faster internal IEEE 754 `float` + and `double` formatter for arbitrary precision. For example + ([godbolt](https://godbolt.org/z/dPhWvj)): + + ```c++ + #include + + int main() { + fmt::print("{:.500}\n", 4.9406564584124654E-324); + } + ``` + + prints + + `4.9406564584124654417656879286822137236505980261432476442558568250067550727020875186529983636163599237979656469544571773092665671035593979639877479601078187812630071319031140452784581716784898210368871863605699873072305000638740915356498438731247339727316961514003171538539807412623856559117102665855668676818703956031062493194527159149245532930545654440112748012970999954193198940908041656332452475714786901472678015935523861155013480352649347201937902681071074917033322268447533357208324319360923829e-324`. + +- Made `format_to_n` and `formatted_size` part of the [core + API](https://fmt.dev/latest/api.html#core-api) + ([godbolt](https://godbolt.org/z/sPjY1K)): + + ```c++ + #include + + int main() { + char buffer[10]; + auto result = fmt::format_to_n(buffer, sizeof(buffer), "{}", 42); + } + ``` + +- Added `fmt::format_to_n` overload with format string compilation + (https://github.com/fmtlib/fmt/issues/1764, + https://github.com/fmtlib/fmt/pull/1767, + https://github.com/fmtlib/fmt/pull/1869). For example + ([godbolt](https://godbolt.org/z/93h86q)): + + ```c++ + #include + + int main() { + char buffer[8]; + fmt::format_to_n(buffer, sizeof(buffer), FMT_COMPILE("{}"), 42); + } + ``` + + Thanks @Kurkin and @alexezeder. + +- Added `fmt::format_to` overload that take `text_style` + (https://github.com/fmtlib/fmt/issues/1593, + https://github.com/fmtlib/fmt/issues/1842, + https://github.com/fmtlib/fmt/pull/1843). For example + ([godbolt](https://godbolt.org/z/91153r)): + + ```c++ + #include + + int main() { + std::string out; + fmt::format_to(std::back_inserter(out), + fmt::emphasis::bold | fg(fmt::color::red), + "The answer is {}.", 42); + } + ``` + + Thanks @Naios. + +- Made the `'#'` specifier emit trailing zeros in addition to the + decimal point (https://github.com/fmtlib/fmt/issues/1797). + For example ([godbolt](https://godbolt.org/z/bhdcW9)): + + ```c++ + #include + + int main() { + fmt::print("{:#.2g}", 0.5); + } + ``` + + prints `0.50`. + +- Changed the default floating point format to not include `.0` for + consistency with `std::format` and `std::to_chars` + (https://github.com/fmtlib/fmt/issues/1893, + https://github.com/fmtlib/fmt/issues/1943). It is possible + to get the decimal point and trailing zero with the `#` specifier. + +- Fixed an issue with floating-point formatting that could result in + addition of a non-significant trailing zero in rare cases e.g. + `1.00e-34` instead of `1.0e-34` + (https://github.com/fmtlib/fmt/issues/1873, + https://github.com/fmtlib/fmt/issues/1917). + +- Made `fmt::to_string` fallback on `ostream` insertion operator if + the `formatter` specialization is not provided + (https://github.com/fmtlib/fmt/issues/1815, + https://github.com/fmtlib/fmt/pull/1829). Thanks @alexezeder. + +- Added support for the append mode to the experimental file API and + improved `fcntl.h` detection. + (https://github.com/fmtlib/fmt/pull/1847, + https://github.com/fmtlib/fmt/pull/1848). Thanks @t-wiser. + +- Fixed handling of types that have both an implicit conversion + operator and an overloaded `ostream` insertion operator + (https://github.com/fmtlib/fmt/issues/1766). + +- Fixed a slicing issue in an internal iterator type + (https://github.com/fmtlib/fmt/pull/1822). Thanks @BRevzin. + +- Fixed an issue in locale-specific integer formatting + (https://github.com/fmtlib/fmt/issues/1927). + +- Fixed handling of exotic code unit types + (https://github.com/fmtlib/fmt/issues/1870, + https://github.com/fmtlib/fmt/issues/1932). + +- Improved `FMT_ALWAYS_INLINE` + (https://github.com/fmtlib/fmt/pull/1878). Thanks @jk-jeon. + +- Removed dependency on `windows.h` + (https://github.com/fmtlib/fmt/pull/1900). Thanks @bernd5. + +- Optimized counting of decimal digits on MSVC + (https://github.com/fmtlib/fmt/pull/1890). Thanks @mwinterb. + +- Improved documentation + (https://github.com/fmtlib/fmt/issues/1772, + https://github.com/fmtlib/fmt/pull/1775, + https://github.com/fmtlib/fmt/pull/1792, + https://github.com/fmtlib/fmt/pull/1838, + https://github.com/fmtlib/fmt/pull/1888, + https://github.com/fmtlib/fmt/pull/1918, + https://github.com/fmtlib/fmt/pull/1939). + Thanks @leolchat, @pepsiman, @Klaim, @ravijanjam, @francesco-st and @udnaan. + +- Added the `FMT_REDUCE_INT_INSTANTIATIONS` CMake option that reduces + the binary code size at the cost of some integer formatting + performance. This can be useful for extremely memory-constrained + embedded systems + (https://github.com/fmtlib/fmt/issues/1778, + https://github.com/fmtlib/fmt/pull/1781). Thanks @kammce. + +- Added the `FMT_USE_INLINE_NAMESPACES` macro to control usage of + inline namespaces + (https://github.com/fmtlib/fmt/pull/1945). Thanks @darklukee. + +- Improved build configuration + (https://github.com/fmtlib/fmt/pull/1760, + https://github.com/fmtlib/fmt/pull/1770, + https://github.com/fmtlib/fmt/issues/1779, + https://github.com/fmtlib/fmt/pull/1783, + https://github.com/fmtlib/fmt/pull/1823). + Thanks @dvetutnev, @xvitaly, @tambry, @medithe and @martinwuehrer. + +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/pull/1790, + https://github.com/fmtlib/fmt/pull/1802, + https://github.com/fmtlib/fmt/pull/1808, + https://github.com/fmtlib/fmt/issues/1810, + https://github.com/fmtlib/fmt/issues/1811, + https://github.com/fmtlib/fmt/pull/1812, + https://github.com/fmtlib/fmt/pull/1814, + https://github.com/fmtlib/fmt/pull/1816, + https://github.com/fmtlib/fmt/pull/1817, + https://github.com/fmtlib/fmt/pull/1818, + https://github.com/fmtlib/fmt/issues/1825, + https://github.com/fmtlib/fmt/pull/1836, + https://github.com/fmtlib/fmt/pull/1855, + https://github.com/fmtlib/fmt/pull/1856, + https://github.com/fmtlib/fmt/pull/1860, + https://github.com/fmtlib/fmt/pull/1877, + https://github.com/fmtlib/fmt/pull/1879, + https://github.com/fmtlib/fmt/pull/1880, + https://github.com/fmtlib/fmt/issues/1896, + https://github.com/fmtlib/fmt/pull/1897, + https://github.com/fmtlib/fmt/pull/1898, + https://github.com/fmtlib/fmt/issues/1904, + https://github.com/fmtlib/fmt/pull/1908, + https://github.com/fmtlib/fmt/issues/1911, + https://github.com/fmtlib/fmt/issues/1912, + https://github.com/fmtlib/fmt/issues/1928, + https://github.com/fmtlib/fmt/pull/1929, + https://github.com/fmtlib/fmt/issues/1935, + https://github.com/fmtlib/fmt/pull/1937, + https://github.com/fmtlib/fmt/pull/1942, + https://github.com/fmtlib/fmt/issues/1949). + Thanks @TheQwertiest, @medithe, @martinwuehrer, @n16h7hunt3r, @Othereum, + @gsjaardema, @AlexanderLanin, @gcerretani, @chronoxor, @noizefloor, + @akohlmey, @jk-jeon, @rimathia, @rglarix, @moiwi, @heckad, @MarcDirven. + @BartSiwek and @darklukee. + +# 7.0.3 - 2020-08-06 + +- Worked around broken `numeric_limits` for 128-bit integers + (https://github.com/fmtlib/fmt/issues/1787). +- Added error reporting on missing named arguments + (https://github.com/fmtlib/fmt/issues/1796). +- Stopped using 128-bit integers with clang-cl + (https://github.com/fmtlib/fmt/pull/1800). Thanks @Kingcom. +- Fixed issues in locale-specific integer formatting + (https://github.com/fmtlib/fmt/issues/1782, + https://github.com/fmtlib/fmt/issues/1801). + +# 7.0.2 - 2020-07-29 + +- Worked around broken `numeric_limits` for 128-bit integers + (https://github.com/fmtlib/fmt/issues/1725). +- Fixed compatibility with CMake 3.4 + (https://github.com/fmtlib/fmt/issues/1779). +- Fixed handling of digit separators in locale-specific formatting + (https://github.com/fmtlib/fmt/issues/1782). + +# 7.0.1 - 2020-07-07 + +- Updated the inline version namespace name. +- Worked around a gcc bug in mangling of alias templates + (https://github.com/fmtlib/fmt/issues/1753). +- Fixed a linkage error on Windows + (https://github.com/fmtlib/fmt/issues/1757). Thanks @Kurkin. +- Fixed minor issues with the documentation. + +# 7.0.0 - 2020-07-05 + +- Reduced the library size. For example, on macOS a stripped test + binary statically linked with {fmt} [shrank from \~368k to less than + 100k](http://www.zverovich.net/2020/05/21/reducing-library-size.html). + +- Added a simpler and more efficient [format string compilation + API](https://fmt.dev/7.0.0/api.html#compile-api): + + ```c++ + #include + + // Converts 42 into std::string using the most efficient method and no + // runtime format string processing. + std::string s = fmt::format(FMT_COMPILE("{}"), 42); + ``` + + The old `fmt::compile` API is now deprecated. + +- Optimized integer formatting: `format_to` with format string + compilation and a stack-allocated buffer is now [faster than + to_chars on both libc++ and + libstdc++](http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html). + +- Optimized handling of small format strings. For example, + + ```c++ + fmt::format("Result: {}: ({},{},{},{})", str1, str2, str3, str4, str5) + ``` + + is now \~40% faster + (https://github.com/fmtlib/fmt/issues/1685). + +- Applied extern templates to improve compile times when using the + core API and `fmt/format.h` + (https://github.com/fmtlib/fmt/issues/1452). For example, + on macOS with clang the compile time of a test translation unit + dropped from 2.3s to 0.3s with `-O2` and from 0.6s to 0.3s with the + default settings (`-O0`). + + Before (`-O2`): + + % time c++ -c test.cc -I include -std=c++17 -O2 + c++ -c test.cc -I include -std=c++17 -O2 2.22s user 0.08s system 99% cpu 2.311 total + + After (`-O2`): + + % time c++ -c test.cc -I include -std=c++17 -O2 + c++ -c test.cc -I include -std=c++17 -O2 0.26s user 0.04s system 98% cpu 0.303 total + + Before (default): + + % time c++ -c test.cc -I include -std=c++17 + c++ -c test.cc -I include -std=c++17 0.53s user 0.06s system 98% cpu 0.601 total + + After (default): + + % time c++ -c test.cc -I include -std=c++17 + c++ -c test.cc -I include -std=c++17 0.24s user 0.06s system 98% cpu 0.301 total + + It is still recommended to use `fmt/core.h` instead of + `fmt/format.h` but the compile time difference is now smaller. + Thanks @alex3d for the suggestion. + +- Named arguments are now stored on stack (no dynamic memory + allocations) and the compiled code is more compact and efficient. + For example + + ```c++ + #include + + int main() { + fmt::print("The answer is {answer}\n", fmt::arg("answer", 42)); + } + ``` + + compiles to just ([godbolt](https://godbolt.org/z/NcfEp_)) + + ```asm + .LC0: + .string "answer" + .LC1: + .string "The answer is {answer}\n" + main: + sub rsp, 56 + mov edi, OFFSET FLAT:.LC1 + mov esi, 23 + movabs rdx, 4611686018427387905 + lea rax, [rsp+32] + lea rcx, [rsp+16] + mov QWORD PTR [rsp+8], 1 + mov QWORD PTR [rsp], rax + mov DWORD PTR [rsp+16], 42 + mov QWORD PTR [rsp+32], OFFSET FLAT:.LC0 + mov DWORD PTR [rsp+40], 0 + call fmt::v6::vprint(fmt::v6::basic_string_view, + fmt::v6::format_args) + xor eax, eax + add rsp, 56 + ret + + .L.str.1: + .asciz "answer" + ``` + +- Implemented compile-time checks for dynamic width and precision + (https://github.com/fmtlib/fmt/issues/1614): + + ```c++ + #include + + int main() { + fmt::print(FMT_STRING("{0:{1}}"), 42); + } + ``` + + now gives a compilation error because argument 1 doesn\'t exist: + + In file included from test.cc:1: + include/fmt/format.h:2726:27: error: constexpr variable 'invalid_format' must be + initialized by a constant expression + FMT_CONSTEXPR_DECL bool invalid_format = + ^ + ... + include/fmt/core.h:569:26: note: in call to + '&checker(s, {}).context_->on_error(&"argument not found"[0])' + if (id >= num_args_) on_error("argument not found"); + ^ + +- Added sentinel support to `fmt::join` + (https://github.com/fmtlib/fmt/pull/1689) + + ```c++ + struct zstring_sentinel {}; + bool operator==(const char* p, zstring_sentinel) { return *p == '\0'; } + bool operator!=(const char* p, zstring_sentinel) { return *p != '\0'; } + + struct zstring { + const char* p; + const char* begin() const { return p; } + zstring_sentinel end() const { return {}; } + }; + + auto s = fmt::format("{}", fmt::join(zstring{"hello"}, "_")); + // s == "h_e_l_l_o" + ``` + + Thanks @BRevzin. + +- Added support for named arguments, `clear` and `reserve` to + `dynamic_format_arg_store` + (https://github.com/fmtlib/fmt/issues/1655, + https://github.com/fmtlib/fmt/pull/1663, + https://github.com/fmtlib/fmt/pull/1674, + https://github.com/fmtlib/fmt/pull/1677). Thanks @vsolontsov-ll. + +- Added support for the `'c'` format specifier to integral types for + compatibility with `std::format` + (https://github.com/fmtlib/fmt/issues/1652). + +- Replaced the `'n'` format specifier with `'L'` for compatibility + with `std::format` + (https://github.com/fmtlib/fmt/issues/1624). The `'n'` + specifier can be enabled via the `FMT_DEPRECATED_N_SPECIFIER` macro. + +- The `'='` format specifier is now disabled by default for + compatibility with `std::format`. It can be enabled via the + `FMT_DEPRECATED_NUMERIC_ALIGN` macro. + +- Removed the following deprecated APIs: + + - `FMT_STRING_ALIAS` and `fmt` macros - replaced by `FMT_STRING` + - `fmt::basic_string_view::char_type` - replaced by + `fmt::basic_string_view::value_type` + - `convert_to_int` + - `format_arg_store::types` + - `*parse_context` - replaced by `*format_parse_context` + - `FMT_DEPRECATED_INCLUDE_OS` + - `FMT_DEPRECATED_PERCENT` - incompatible with `std::format` + - `*writer` - replaced by compiled format API + +- Renamed the `internal` namespace to `detail` + (https://github.com/fmtlib/fmt/issues/1538). The former is + still provided as an alias if the `FMT_USE_INTERNAL` macro is + defined. + +- Improved compatibility between `fmt::printf` with the standard specs + (https://github.com/fmtlib/fmt/issues/1595, + https://github.com/fmtlib/fmt/pull/1682, + https://github.com/fmtlib/fmt/pull/1683, + https://github.com/fmtlib/fmt/pull/1687, + https://github.com/fmtlib/fmt/pull/1699). Thanks @rimathia. + +- Fixed handling of `operator<<` overloads that use `copyfmt` + (https://github.com/fmtlib/fmt/issues/1666). + +- Added the `FMT_OS` CMake option to control inclusion of OS-specific + APIs in the fmt target. This can be useful for embedded platforms + (https://github.com/fmtlib/fmt/issues/1654, + https://github.com/fmtlib/fmt/pull/1656). Thanks @kwesolowski. + +- Replaced `FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION` with the + `FMT_FUZZ` macro to prevent interfering with fuzzing of projects + using {fmt} (https://github.com/fmtlib/fmt/pull/1650). + Thanks @asraa. + +- Fixed compatibility with emscripten + (https://github.com/fmtlib/fmt/issues/1636, + https://github.com/fmtlib/fmt/pull/1637). Thanks @ArthurSonzogni. + +- Improved documentation + (https://github.com/fmtlib/fmt/issues/704, + https://github.com/fmtlib/fmt/pull/1643, + https://github.com/fmtlib/fmt/pull/1660, + https://github.com/fmtlib/fmt/pull/1681, + https://github.com/fmtlib/fmt/pull/1691, + https://github.com/fmtlib/fmt/pull/1706, + https://github.com/fmtlib/fmt/pull/1714, + https://github.com/fmtlib/fmt/pull/1721, + https://github.com/fmtlib/fmt/pull/1739, + https://github.com/fmtlib/fmt/pull/1740, + https://github.com/fmtlib/fmt/pull/1741, + https://github.com/fmtlib/fmt/pull/1751). + Thanks @senior7515, @lsr0, @puetzk, @fpelliccioni, Alexey Kuzmenko, @jelly, + @claremacrae, @jiapengwen, @gsjaardema and @alexey-milovidov. + +- Implemented various build configuration fixes and improvements + (https://github.com/fmtlib/fmt/pull/1603, + https://github.com/fmtlib/fmt/pull/1657, + https://github.com/fmtlib/fmt/pull/1702, + https://github.com/fmtlib/fmt/pull/1728). + Thanks @scramsby, @jtojnar, @orivej and @flagarde. + +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/pull/1616, + https://github.com/fmtlib/fmt/issues/1620, + https://github.com/fmtlib/fmt/issues/1622, + https://github.com/fmtlib/fmt/issues/1625, + https://github.com/fmtlib/fmt/pull/1627, + https://github.com/fmtlib/fmt/issues/1628, + https://github.com/fmtlib/fmt/pull/1629, + https://github.com/fmtlib/fmt/issues/1631, + https://github.com/fmtlib/fmt/pull/1633, + https://github.com/fmtlib/fmt/pull/1649, + https://github.com/fmtlib/fmt/issues/1658, + https://github.com/fmtlib/fmt/pull/1661, + https://github.com/fmtlib/fmt/pull/1667, + https://github.com/fmtlib/fmt/issues/1668, + https://github.com/fmtlib/fmt/pull/1669, + https://github.com/fmtlib/fmt/issues/1692, + https://github.com/fmtlib/fmt/pull/1696, + https://github.com/fmtlib/fmt/pull/1697, + https://github.com/fmtlib/fmt/issues/1707, + https://github.com/fmtlib/fmt/pull/1712, + https://github.com/fmtlib/fmt/pull/1716, + https://github.com/fmtlib/fmt/pull/1722, + https://github.com/fmtlib/fmt/issues/1724, + https://github.com/fmtlib/fmt/pull/1729, + https://github.com/fmtlib/fmt/pull/1738, + https://github.com/fmtlib/fmt/issues/1742, + https://github.com/fmtlib/fmt/issues/1743, + https://github.com/fmtlib/fmt/pull/1744, + https://github.com/fmtlib/fmt/issues/1747, + https://github.com/fmtlib/fmt/pull/1750). + Thanks @gsjaardema, @gabime, @johnor, @Kurkin, @invexed, @peterbell10, + @daixtrose, @petrutlucian94, @Neargye, @ambitslix, @gabime, @erthink, + @tohammer and @0x8000-0000. + +# 6.2.1 - 2020-05-09 + +- Fixed ostream support in `sprintf` + (https://github.com/fmtlib/fmt/issues/1631). +- Fixed type detection when using implicit conversion to `string_view` + and ostream `operator<<` inconsistently + (https://github.com/fmtlib/fmt/issues/1662). + +# 6.2.0 - 2020-04-05 + +- Improved error reporting when trying to format an object of a + non-formattable type: + + ```c++ + fmt::format("{}", S()); + ``` + + now gives: + + include/fmt/core.h:1015:5: error: static_assert failed due to requirement + 'formattable' "Cannot format argument. To make type T formattable provide a + formatter specialization: + https://fmt.dev/latest/api.html#formatting-user-defined-types" + static_assert( + ^ + ... + note: in instantiation of function template specialization + 'fmt::v6::format' requested here + fmt::format("{}", S()); + ^ + + if `S` is not formattable. + +- Reduced the library size by \~10%. + +- Always print decimal point if `#` is specified + (https://github.com/fmtlib/fmt/issues/1476, + https://github.com/fmtlib/fmt/issues/1498): + + ```c++ + fmt::print("{:#.0f}", 42.0); + ``` + + now prints `42.` + +- Implemented the `'L'` specifier for locale-specific numeric + formatting to improve compatibility with `std::format`. The `'n'` + specifier is now deprecated and will be removed in the next major + release. + +- Moved OS-specific APIs such as `windows_error` from `fmt/format.h` + to `fmt/os.h`. You can define `FMT_DEPRECATED_INCLUDE_OS` to + automatically include `fmt/os.h` from `fmt/format.h` for + compatibility but this will be disabled in the next major release. + +- Added precision overflow detection in floating-point formatting. + +- Implemented detection of invalid use of `fmt::arg`. + +- Used `type_identity` to block unnecessary template argument + deduction. Thanks Tim Song. + +- Improved UTF-8 handling + (https://github.com/fmtlib/fmt/issues/1109): + + ```c++ + fmt::print("┌{0:─^{2}}â”\n" + "│{1: ^{2}}│\n" + "â””{0:─^{2}}┘\n", "", "Привет, мир!", 20); + ``` + + now prints: + + ┌────────────────────┠+ │ Привет, мир! │ + └────────────────────┘ + + on systems that support Unicode. + +- Added experimental dynamic argument storage + (https://github.com/fmtlib/fmt/issues/1170, + https://github.com/fmtlib/fmt/pull/1584): + + ```c++ + fmt::dynamic_format_arg_store store; + store.push_back("answer"); + store.push_back(42); + fmt::vprint("The {} is {}.\n", store); + ``` + + prints: + + The answer is 42. + + Thanks @vsolontsov-ll. + +- Made `fmt::join` accept `initializer_list` + (https://github.com/fmtlib/fmt/pull/1591). Thanks @Rapotkinnik. + +- Fixed handling of empty tuples + (https://github.com/fmtlib/fmt/issues/1588). + +- Fixed handling of output iterators in `format_to_n` + (https://github.com/fmtlib/fmt/issues/1506). + +- Fixed formatting of `std::chrono::duration` types to wide output + (https://github.com/fmtlib/fmt/pull/1533). Thanks @zeffy. + +- Added const `begin` and `end` overload to buffers + (https://github.com/fmtlib/fmt/pull/1553). Thanks @dominicpoeschko. + +- Added the ability to disable floating-point formatting via + `FMT_USE_FLOAT`, `FMT_USE_DOUBLE` and `FMT_USE_LONG_DOUBLE` macros + for extremely memory-constrained embedded system + (https://github.com/fmtlib/fmt/pull/1590). Thanks @albaguirre. + +- Made `FMT_STRING` work with `constexpr` `string_view` + (https://github.com/fmtlib/fmt/pull/1589). Thanks @scramsby. + +- Implemented a minor optimization in the format string parser + (https://github.com/fmtlib/fmt/pull/1560). Thanks @IkarusDeveloper. + +- Improved attribute detection + (https://github.com/fmtlib/fmt/pull/1469, + https://github.com/fmtlib/fmt/pull/1475, + https://github.com/fmtlib/fmt/pull/1576). + Thanks @federico-busato, @chronoxor and @refnum. + +- Improved documentation + (https://github.com/fmtlib/fmt/pull/1481, + https://github.com/fmtlib/fmt/pull/1523). + Thanks @JackBoosY and @imba-tjd. + +- Fixed symbol visibility on Linux when compiling with + `-fvisibility=hidden` + (https://github.com/fmtlib/fmt/pull/1535). Thanks @milianw. + +- Implemented various build configuration fixes and improvements + (https://github.com/fmtlib/fmt/issues/1264, + https://github.com/fmtlib/fmt/issues/1460, + https://github.com/fmtlib/fmt/pull/1534, + https://github.com/fmtlib/fmt/issues/1536, + https://github.com/fmtlib/fmt/issues/1545, + https://github.com/fmtlib/fmt/pull/1546, + https://github.com/fmtlib/fmt/issues/1566, + https://github.com/fmtlib/fmt/pull/1582, + https://github.com/fmtlib/fmt/issues/1597, + https://github.com/fmtlib/fmt/pull/1598). + Thanks @ambitslix, @jwillikers and @stac47. + +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/pull/1433, + https://github.com/fmtlib/fmt/issues/1461, + https://github.com/fmtlib/fmt/pull/1470, + https://github.com/fmtlib/fmt/pull/1480, + https://github.com/fmtlib/fmt/pull/1485, + https://github.com/fmtlib/fmt/pull/1492, + https://github.com/fmtlib/fmt/issues/1493, + https://github.com/fmtlib/fmt/issues/1504, + https://github.com/fmtlib/fmt/pull/1505, + https://github.com/fmtlib/fmt/pull/1512, + https://github.com/fmtlib/fmt/issues/1515, + https://github.com/fmtlib/fmt/pull/1516, + https://github.com/fmtlib/fmt/pull/1518, + https://github.com/fmtlib/fmt/pull/1519, + https://github.com/fmtlib/fmt/pull/1520, + https://github.com/fmtlib/fmt/pull/1521, + https://github.com/fmtlib/fmt/pull/1522, + https://github.com/fmtlib/fmt/issues/1524, + https://github.com/fmtlib/fmt/pull/1530, + https://github.com/fmtlib/fmt/issues/1531, + https://github.com/fmtlib/fmt/pull/1532, + https://github.com/fmtlib/fmt/issues/1539, + https://github.com/fmtlib/fmt/issues/1547, + https://github.com/fmtlib/fmt/issues/1548, + https://github.com/fmtlib/fmt/pull/1554, + https://github.com/fmtlib/fmt/issues/1567, + https://github.com/fmtlib/fmt/pull/1568, + https://github.com/fmtlib/fmt/pull/1569, + https://github.com/fmtlib/fmt/pull/1571, + https://github.com/fmtlib/fmt/pull/1573, + https://github.com/fmtlib/fmt/pull/1575, + https://github.com/fmtlib/fmt/pull/1581, + https://github.com/fmtlib/fmt/issues/1583, + https://github.com/fmtlib/fmt/issues/1586, + https://github.com/fmtlib/fmt/issues/1587, + https://github.com/fmtlib/fmt/issues/1594, + https://github.com/fmtlib/fmt/pull/1596, + https://github.com/fmtlib/fmt/issues/1604, + https://github.com/fmtlib/fmt/pull/1606, + https://github.com/fmtlib/fmt/issues/1607, + https://github.com/fmtlib/fmt/issues/1609). + Thanks @marti4d, @iPherian, @parkertomatoes, @gsjaardema, @chronoxor, + @DanielaE, @torsten48, @tohammer, @lefticus, @ryusakki, @adnsv, @fghzxm, + @refnum, @pramodk, @Spirrwell and @scramsby. + +# 6.1.2 - 2019-12-11 + +- Fixed ABI compatibility with `libfmt.so.6.0.0` + (https://github.com/fmtlib/fmt/issues/1471). +- Fixed handling types convertible to `std::string_view` + (https://github.com/fmtlib/fmt/pull/1451). Thanks @denizevrenci. +- Made CUDA test an opt-in enabled via the `FMT_CUDA_TEST` CMake + option. +- Fixed sign conversion warnings + (https://github.com/fmtlib/fmt/pull/1440). Thanks @0x8000-0000. + +# 6.1.1 - 2019-12-04 + +- Fixed shared library build on Windows + (https://github.com/fmtlib/fmt/pull/1443, + https://github.com/fmtlib/fmt/issues/1445, + https://github.com/fmtlib/fmt/pull/1446, + https://github.com/fmtlib/fmt/issues/1450). + Thanks @egorpugin and @bbolli. +- Added a missing decimal point in exponent notation with trailing + zeros. +- Removed deprecated `format_arg_store::TYPES`. + +# 6.1.0 - 2019-12-01 + +- {fmt} now formats IEEE 754 `float` and `double` using the shortest + decimal representation with correct rounding by default: + + ```c++ + #include + #include + + int main() { + fmt::print("{}", M_PI); + } + ``` + + prints `3.141592653589793`. + +- Made the fast binary to decimal floating-point formatter the + default, simplified it and improved performance. {fmt} is now 15 + times faster than libc++\'s `std::ostringstream`, 11 times faster + than `printf` and 10% faster than double-conversion on + [dtoa-benchmark](https://github.com/fmtlib/dtoa-benchmark): + + | Function | Time (ns) | Speedup | + | ------------- | --------: | ------: | + | ostringstream | 1,346.30 | 1.00x | + | ostrstream | 1,195.74 | 1.13x | + | sprintf | 995.08 | 1.35x | + | doubleconv | 99.10 | 13.59x | + | fmt | 88.34 | 15.24x | + + ![](https://user-images.githubusercontent.com/576385/69767160-cdaca400-112f-11ea-9fc5-347c9f83caad.png) + +- {fmt} no longer converts `float` arguments to `double`. In + particular this improves the default (shortest) representation of + floats and makes `fmt::format` consistent with `std::format` specs + (https://github.com/fmtlib/fmt/issues/1336, + https://github.com/fmtlib/fmt/issues/1353, + https://github.com/fmtlib/fmt/pull/1360, + https://github.com/fmtlib/fmt/pull/1361): + + ```c++ + fmt::print("{}", 0.1f); + ``` + + prints `0.1` instead of `0.10000000149011612`. + + Thanks @orivej. + +- Made floating-point formatting output consistent with + `printf`/iostreams + (https://github.com/fmtlib/fmt/issues/1376, + https://github.com/fmtlib/fmt/issues/1417). + +- Added support for 128-bit integers + (https://github.com/fmtlib/fmt/pull/1287): + + ```c++ + fmt::print("{}", std::numeric_limits<__int128_t>::max()); + ``` + + prints `170141183460469231731687303715884105727`. + + Thanks @denizevrenci. + +- The overload of `print` that takes `text_style` is now atomic, i.e. + the output from different threads doesn\'t interleave + (https://github.com/fmtlib/fmt/pull/1351). Thanks @tankiJong. + +- Made compile time in the header-only mode \~20% faster by reducing + the number of template instantiations. `wchar_t` overload of + `vprint` was moved from `fmt/core.h` to `fmt/format.h`. + +- Added an overload of `fmt::join` that works with tuples + (https://github.com/fmtlib/fmt/issues/1322, + https://github.com/fmtlib/fmt/pull/1330): + + ```c++ + #include + #include + + int main() { + std::tuple t{'a', 1, 2.0f}; + fmt::print("{}", t); + } + ``` + + prints `('a', 1, 2.0)`. + + Thanks @jeremyong. + +- Changed formatting of octal zero with prefix from \"00\" to \"0\": + + ```c++ + fmt::print("{:#o}", 0); + ``` + + prints `0`. + +- The locale is now passed to ostream insertion (`<<`) operators + (https://github.com/fmtlib/fmt/pull/1406): + + ```c++ + #include + #include + + struct S { + double value; + }; + + std::ostream& operator<<(std::ostream& os, S s) { + return os << s.value; + } + + int main() { + auto s = fmt::format(std::locale("fr_FR.UTF-8"), "{}", S{0.42}); + // s == "0,42" + } + ``` + + Thanks @dlaugt. + +- Locale-specific number formatting now uses grouping + (https://github.com/fmtlib/fmt/issues/1393, + https://github.com/fmtlib/fmt/pull/1394). Thanks @skrdaniel. + +- Fixed handling of types with deleted implicit rvalue conversion to + `const char**` (https://github.com/fmtlib/fmt/issues/1421): + + ```c++ + struct mystring { + operator const char*() const&; + operator const char*() &; + operator const char*() const&& = delete; + operator const char*() && = delete; + }; + mystring str; + fmt::print("{}", str); // now compiles + ``` + +- Enums are now mapped to correct underlying types instead of `int` + (https://github.com/fmtlib/fmt/pull/1286). Thanks @agmt. + +- Enum classes are no longer implicitly converted to `int` + (https://github.com/fmtlib/fmt/issues/1424). + +- Added `basic_format_parse_context` for consistency with C++20 + `std::format` and deprecated `basic_parse_context`. + +- Fixed handling of UTF-8 in precision + (https://github.com/fmtlib/fmt/issues/1389, + https://github.com/fmtlib/fmt/pull/1390). Thanks @tajtiattila. + +- {fmt} can now be installed on Linux, macOS and Windows with + [Conda](https://docs.conda.io/en/latest/) using its + [conda-forge](https://conda-forge.org) + [package](https://github.com/conda-forge/fmt-feedstock) + (https://github.com/fmtlib/fmt/pull/1410): + + conda install -c conda-forge fmt + + Thanks @tdegeus. + +- Added a CUDA test (https://github.com/fmtlib/fmt/pull/1285, + https://github.com/fmtlib/fmt/pull/1317). + Thanks @luncliff and @risa2000. + +- Improved documentation + (https://github.com/fmtlib/fmt/pull/1276, + https://github.com/fmtlib/fmt/issues/1291, + https://github.com/fmtlib/fmt/issues/1296, + https://github.com/fmtlib/fmt/pull/1315, + https://github.com/fmtlib/fmt/pull/1332, + https://github.com/fmtlib/fmt/pull/1337, + https://github.com/fmtlib/fmt/issues/1395 + https://github.com/fmtlib/fmt/pull/1418). + Thanks @waywardmonkeys, @pauldreik and @jackoalan. + +- Various code improvements + (https://github.com/fmtlib/fmt/pull/1358, + https://github.com/fmtlib/fmt/pull/1407). + Thanks @orivej and @dpacbach. + +- Fixed compile-time format string checks for user-defined types + (https://github.com/fmtlib/fmt/issues/1292). + +- Worked around a false positive in `unsigned-integer-overflow` sanitizer + (https://github.com/fmtlib/fmt/issues/1377). + +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/issues/1273, + https://github.com/fmtlib/fmt/pull/1278, + https://github.com/fmtlib/fmt/pull/1280, + https://github.com/fmtlib/fmt/issues/1281, + https://github.com/fmtlib/fmt/issues/1288, + https://github.com/fmtlib/fmt/pull/1290, + https://github.com/fmtlib/fmt/pull/1301, + https://github.com/fmtlib/fmt/issues/1305, + https://github.com/fmtlib/fmt/issues/1306, + https://github.com/fmtlib/fmt/issues/1309, + https://github.com/fmtlib/fmt/pull/1312, + https://github.com/fmtlib/fmt/issues/1313, + https://github.com/fmtlib/fmt/issues/1316, + https://github.com/fmtlib/fmt/issues/1319, + https://github.com/fmtlib/fmt/pull/1320, + https://github.com/fmtlib/fmt/pull/1326, + https://github.com/fmtlib/fmt/pull/1328, + https://github.com/fmtlib/fmt/issues/1344, + https://github.com/fmtlib/fmt/pull/1345, + https://github.com/fmtlib/fmt/pull/1347, + https://github.com/fmtlib/fmt/pull/1349, + https://github.com/fmtlib/fmt/issues/1354, + https://github.com/fmtlib/fmt/issues/1362, + https://github.com/fmtlib/fmt/issues/1366, + https://github.com/fmtlib/fmt/pull/1364, + https://github.com/fmtlib/fmt/pull/1370, + https://github.com/fmtlib/fmt/pull/1371, + https://github.com/fmtlib/fmt/issues/1385, + https://github.com/fmtlib/fmt/issues/1388, + https://github.com/fmtlib/fmt/pull/1397, + https://github.com/fmtlib/fmt/pull/1414, + https://github.com/fmtlib/fmt/pull/1416, + https://github.com/fmtlib/fmt/issues/1422 + https://github.com/fmtlib/fmt/pull/1427, + https://github.com/fmtlib/fmt/issues/1431, + https://github.com/fmtlib/fmt/pull/1433). + Thanks @hhb, @gsjaardema, @gabime, @neheb, @vedranmiletic, @dkavolis, + @mwinterb, @orivej, @denizevrenci, @leonklingele, @chronoxor, @kent-tri, + @0x8000-0000 and @marti4d. + +# 6.0.0 - 2019-08-26 + +- Switched to the [MIT license]( + https://github.com/fmtlib/fmt/blob/5a4b24613ba16cc689977c3b5bd8274a3ba1dd1f/LICENSE.rst) + with an optional exception that allows distributing binary code + without attribution. + +- Floating-point formatting is now locale-independent by default: + + ```c++ + #include + #include + + int main() { + std::locale::global(std::locale("ru_RU.UTF-8")); + fmt::print("value = {}", 4.2); + } + ``` + + prints \"value = 4.2\" regardless of the locale. + + For locale-specific formatting use the `n` specifier: + + ```c++ + std::locale::global(std::locale("ru_RU.UTF-8")); + fmt::print("value = {:n}", 4.2); + ``` + + prints \"value = 4,2\". + +- Added an experimental Grisu floating-point formatting algorithm + implementation (disabled by default). To enable it compile with the + `FMT_USE_GRISU` macro defined to 1: + + ```c++ + #define FMT_USE_GRISU 1 + #include + + auto s = fmt::format("{}", 4.2); // formats 4.2 using Grisu + ``` + + With Grisu enabled, {fmt} is 13x faster than `std::ostringstream` + (libc++) and 10x faster than `sprintf` on + [dtoa-benchmark](https://github.com/fmtlib/dtoa-benchmark) ([full + results](https://fmt.dev/unknown_mac64_clang10.0.html)): + + ![](https://user-images.githubusercontent.com/576385/54883977-9fe8c000-4e28-11e9-8bde-272d122e7c52.jpg) + +- Separated formatting and parsing contexts for consistency with + [C++20 std::format](http://eel.is/c++draft/format), removing the + undocumented `basic_format_context::parse_context()` function. + +- Added [oss-fuzz](https://github.com/google/oss-fuzz) support + (https://github.com/fmtlib/fmt/pull/1199). Thanks @pauldreik. + +- `formatter` specializations now always take precedence over + `operator<<` (https://github.com/fmtlib/fmt/issues/952): + + ```c++ + #include + #include + + struct S {}; + + std::ostream& operator<<(std::ostream& os, S) { + return os << 1; + } + + template <> + struct fmt::formatter : fmt::formatter { + auto format(S, format_context& ctx) { + return formatter::format(2, ctx); + } + }; + + int main() { + std::cout << S() << "\n"; // prints 1 using operator<< + fmt::print("{}\n", S()); // prints 2 using formatter + } + ``` + +- Introduced the experimental `fmt::compile` function that does format + string compilation + (https://github.com/fmtlib/fmt/issues/618, + https://github.com/fmtlib/fmt/issues/1169, + https://github.com/fmtlib/fmt/pull/1171): + + ```c++ + #include + + auto f = fmt::compile("{}"); + std::string s = fmt::format(f, 42); // can be called multiple times to + // format different values + // s == "42" + ``` + + It moves the cost of parsing a format string outside of the format + function which can be beneficial when identically formatting many + objects of the same types. Thanks @stryku. + +- Added experimental `%` format specifier that formats floating-point + values as percentages + (https://github.com/fmtlib/fmt/pull/1060, + https://github.com/fmtlib/fmt/pull/1069, + https://github.com/fmtlib/fmt/pull/1071): + + ```c++ + auto s = fmt::format("{:.1%}", 0.42); // s == "42.0%" + ``` + + Thanks @gawain-bolton. + +- Implemented precision for floating-point durations + (https://github.com/fmtlib/fmt/issues/1004, + https://github.com/fmtlib/fmt/pull/1012): + + ```c++ + auto s = fmt::format("{:.1}", std::chrono::duration(1.234)); + // s == 1.2s + ``` + + Thanks @DanielaE. + +- Implemented `chrono` format specifiers `%Q` and `%q` that give the + value and the unit respectively + (https://github.com/fmtlib/fmt/pull/1019): + + ```c++ + auto value = fmt::format("{:%Q}", 42s); // value == "42" + auto unit = fmt::format("{:%q}", 42s); // unit == "s" + ``` + + Thanks @DanielaE. + +- Fixed handling of dynamic width in chrono formatter: + + ```c++ + auto s = fmt::format("{0:{1}%H:%M:%S}", std::chrono::seconds(12345), 12); + // ^ width argument index ^ width + // s == "03:25:45 " + ``` + + Thanks Howard Hinnant. + +- Removed deprecated `fmt/time.h`. Use `fmt/chrono.h` instead. + +- Added `fmt::format` and `fmt::vformat` overloads that take + `text_style` (https://github.com/fmtlib/fmt/issues/993, + https://github.com/fmtlib/fmt/pull/994): + + ```c++ + #include + + std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red), + "The answer is {}.", 42); + ``` + + Thanks @Naios. + +- Removed the deprecated color API (`print_colored`). Use the new API, + namely `print` overloads that take `text_style` instead. + +- Made `std::unique_ptr` and `std::shared_ptr` formattable as pointers + via `fmt::ptr` (https://github.com/fmtlib/fmt/pull/1121): + + ```c++ + std::unique_ptr p = ...; + fmt::print("{}", fmt::ptr(p)); // prints p as a pointer + ``` + + Thanks @sighingnow. + +- Made `print` and `vprint` report I/O errors + (https://github.com/fmtlib/fmt/issues/1098, + https://github.com/fmtlib/fmt/pull/1099). Thanks @BillyDonahue. + +- Marked deprecated APIs with the `[[deprecated]]` attribute and + removed internal uses of deprecated APIs + (https://github.com/fmtlib/fmt/pull/1022). Thanks @eliaskosunen. + +- Modernized the codebase using more C++11 features and removing + workarounds. Most importantly, `buffer_context` is now an alias + template, so use `buffer_context` instead of + `buffer_context::type`. These features require GCC 4.8 or later. + +- `formatter` specializations now always take precedence over implicit + conversions to `int` and the undocumented `convert_to_int` trait is + now deprecated. + +- Moved the undocumented `basic_writer`, `writer`, and `wwriter` types + to the `internal` namespace. + +- Removed deprecated `basic_format_context::begin()`. Use `out()` + instead. + +- Disallowed passing the result of `join` as an lvalue to prevent + misuse. + +- Refactored the undocumented structs that represent parsed format + specifiers to simplify the API and allow multibyte fill. + +- Moved SFINAE to template parameters to reduce symbol sizes. + +- Switched to `fputws` for writing wide strings so that it\'s no + longer required to call `_setmode` on Windows + (https://github.com/fmtlib/fmt/issues/1229, + https://github.com/fmtlib/fmt/pull/1243). Thanks @jackoalan. + +- Improved literal-based API + (https://github.com/fmtlib/fmt/pull/1254). Thanks @sylveon. + +- Added support for exotic platforms without `uintptr_t` such as IBM i + (AS/400) which has 128-bit pointers and only 64-bit integers + (https://github.com/fmtlib/fmt/issues/1059). + +- Added [Sublime Text syntax highlighting config]( + https://github.com/fmtlib/fmt/blob/master/support/C%2B%2B.sublime-syntax) + (https://github.com/fmtlib/fmt/issues/1037). Thanks @Kronuz. + +- Added the `FMT_ENFORCE_COMPILE_STRING` macro to enforce the use of + compile-time format strings + (https://github.com/fmtlib/fmt/pull/1231). Thanks @jackoalan. + +- Stopped setting `CMAKE_BUILD_TYPE` if {fmt} is a subproject + (https://github.com/fmtlib/fmt/issues/1081). + +- Various build improvements + (https://github.com/fmtlib/fmt/pull/1039, + https://github.com/fmtlib/fmt/pull/1078, + https://github.com/fmtlib/fmt/pull/1091, + https://github.com/fmtlib/fmt/pull/1103, + https://github.com/fmtlib/fmt/pull/1177). + Thanks @luncliff, @jasonszang, @olafhering, @Lecetem and @pauldreik. + +- Improved documentation + (https://github.com/fmtlib/fmt/issues/1049, + https://github.com/fmtlib/fmt/pull/1051, + https://github.com/fmtlib/fmt/pull/1083, + https://github.com/fmtlib/fmt/pull/1113, + https://github.com/fmtlib/fmt/pull/1114, + https://github.com/fmtlib/fmt/issues/1146, + https://github.com/fmtlib/fmt/issues/1180, + https://github.com/fmtlib/fmt/pull/1250, + https://github.com/fmtlib/fmt/pull/1252, + https://github.com/fmtlib/fmt/pull/1265). + Thanks @mikelui, @foonathan, @BillyDonahue, @jwakely, @kaisbe and + @sdebionne. + +- Fixed ambiguous formatter specialization in `fmt/ranges.h` + (https://github.com/fmtlib/fmt/issues/1123). + +- Fixed formatting of a non-empty `std::filesystem::path` which is an + infinitely deep range of its components + (https://github.com/fmtlib/fmt/issues/1268). + +- Fixed handling of general output iterators when formatting + characters (https://github.com/fmtlib/fmt/issues/1056, + https://github.com/fmtlib/fmt/pull/1058). Thanks @abolz. + +- Fixed handling of output iterators in `formatter` specialization for + ranges (https://github.com/fmtlib/fmt/issues/1064). + +- Fixed handling of exotic character types + (https://github.com/fmtlib/fmt/issues/1188). + +- Made chrono formatting work with exceptions disabled + (https://github.com/fmtlib/fmt/issues/1062). + +- Fixed DLL visibility issues + (https://github.com/fmtlib/fmt/pull/1134, + https://github.com/fmtlib/fmt/pull/1147). Thanks @denchat. + +- Disabled the use of UDL template extension on GCC 9 + (https://github.com/fmtlib/fmt/issues/1148). + +- Removed misplaced `format` compile-time checks from `printf` + (https://github.com/fmtlib/fmt/issues/1173). + +- Fixed issues in the experimental floating-point formatter + (https://github.com/fmtlib/fmt/issues/1072, + https://github.com/fmtlib/fmt/issues/1129, + https://github.com/fmtlib/fmt/issues/1153, + https://github.com/fmtlib/fmt/pull/1155, + https://github.com/fmtlib/fmt/issues/1210, + https://github.com/fmtlib/fmt/issues/1222). Thanks @alabuzhev. + +- Fixed bugs discovered by fuzzing or during fuzzing integration + (https://github.com/fmtlib/fmt/issues/1124, + https://github.com/fmtlib/fmt/issues/1127, + https://github.com/fmtlib/fmt/issues/1132, + https://github.com/fmtlib/fmt/pull/1135, + https://github.com/fmtlib/fmt/issues/1136, + https://github.com/fmtlib/fmt/issues/1141, + https://github.com/fmtlib/fmt/issues/1142, + https://github.com/fmtlib/fmt/issues/1178, + https://github.com/fmtlib/fmt/issues/1179, + https://github.com/fmtlib/fmt/issues/1194). Thanks @pauldreik. + +- Fixed building tests on FreeBSD and Hurd + (https://github.com/fmtlib/fmt/issues/1043). Thanks @jackyf. + +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/pull/998, + https://github.com/fmtlib/fmt/pull/1006, + https://github.com/fmtlib/fmt/issues/1008, + https://github.com/fmtlib/fmt/issues/1011, + https://github.com/fmtlib/fmt/issues/1025, + https://github.com/fmtlib/fmt/pull/1027, + https://github.com/fmtlib/fmt/pull/1028, + https://github.com/fmtlib/fmt/pull/1029, + https://github.com/fmtlib/fmt/pull/1030, + https://github.com/fmtlib/fmt/pull/1031, + https://github.com/fmtlib/fmt/pull/1054, + https://github.com/fmtlib/fmt/issues/1063, + https://github.com/fmtlib/fmt/pull/1068, + https://github.com/fmtlib/fmt/pull/1074, + https://github.com/fmtlib/fmt/pull/1075, + https://github.com/fmtlib/fmt/pull/1079, + https://github.com/fmtlib/fmt/pull/1086, + https://github.com/fmtlib/fmt/issues/1088, + https://github.com/fmtlib/fmt/pull/1089, + https://github.com/fmtlib/fmt/pull/1094, + https://github.com/fmtlib/fmt/issues/1101, + https://github.com/fmtlib/fmt/pull/1102, + https://github.com/fmtlib/fmt/issues/1105, + https://github.com/fmtlib/fmt/pull/1107, + https://github.com/fmtlib/fmt/issues/1115, + https://github.com/fmtlib/fmt/issues/1117, + https://github.com/fmtlib/fmt/issues/1118, + https://github.com/fmtlib/fmt/issues/1120, + https://github.com/fmtlib/fmt/issues/1123, + https://github.com/fmtlib/fmt/pull/1139, + https://github.com/fmtlib/fmt/issues/1140, + https://github.com/fmtlib/fmt/issues/1143, + https://github.com/fmtlib/fmt/pull/1144, + https://github.com/fmtlib/fmt/pull/1150, + https://github.com/fmtlib/fmt/pull/1151, + https://github.com/fmtlib/fmt/issues/1152, + https://github.com/fmtlib/fmt/issues/1154, + https://github.com/fmtlib/fmt/issues/1156, + https://github.com/fmtlib/fmt/pull/1159, + https://github.com/fmtlib/fmt/issues/1175, + https://github.com/fmtlib/fmt/issues/1181, + https://github.com/fmtlib/fmt/issues/1186, + https://github.com/fmtlib/fmt/pull/1187, + https://github.com/fmtlib/fmt/pull/1191, + https://github.com/fmtlib/fmt/issues/1197, + https://github.com/fmtlib/fmt/issues/1200, + https://github.com/fmtlib/fmt/issues/1203, + https://github.com/fmtlib/fmt/issues/1205, + https://github.com/fmtlib/fmt/pull/1206, + https://github.com/fmtlib/fmt/issues/1213, + https://github.com/fmtlib/fmt/issues/1214, + https://github.com/fmtlib/fmt/pull/1217, + https://github.com/fmtlib/fmt/issues/1228, + https://github.com/fmtlib/fmt/pull/1230, + https://github.com/fmtlib/fmt/issues/1232, + https://github.com/fmtlib/fmt/pull/1235, + https://github.com/fmtlib/fmt/pull/1236, + https://github.com/fmtlib/fmt/issues/1240). + Thanks @DanielaE, @mwinterb, @eliaskosunen, @morinmorin, @ricco19, + @waywardmonkeys, @chronoxor, @remyabel, @pauldreik, @gsjaardema, @rcane, + @mocabe, @denchat, @cjdb, @HazardyKnusperkeks, @vedranmiletic, @jackoalan, + @DaanDeMeyer and @starkmapper. + +# 5.3.0 - 2018-12-28 + +- Introduced experimental chrono formatting support: + + ```c++ + #include + + int main() { + using namespace std::literals::chrono_literals; + fmt::print("Default format: {} {}\n", 42s, 100ms); + fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s); + } + ``` + + prints: + + Default format: 42s 100ms + strftime-like format: 03:15:30 + +- Added experimental support for emphasis (bold, italic, underline, + strikethrough), colored output to a file stream, and improved + colored formatting API + (https://github.com/fmtlib/fmt/pull/961, + https://github.com/fmtlib/fmt/pull/967, + https://github.com/fmtlib/fmt/pull/973): + + ```c++ + #include + + int main() { + print(fg(fmt::color::crimson) | fmt::emphasis::bold, + "Hello, {}!\n", "world"); + print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) | + fmt::emphasis::underline, "Hello, {}!\n", "мир"); + print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, + "Hello, {}!\n", "世界"); + } + ``` + + prints the following on modern terminals with RGB color support: + + ![](https://user-images.githubusercontent.com/576385/50405788-b66e7500-076e-11e9-9592-7324d1f951d8.png) + + Thanks @Rakete1111. + +- Added support for 4-bit terminal colors + (https://github.com/fmtlib/fmt/issues/968, + https://github.com/fmtlib/fmt/pull/974) + + ```c++ + #include + + int main() { + print(fg(fmt::terminal_color::red), "stop\n"); + } + ``` + + Note that these colors vary by terminal: + + ![](https://user-images.githubusercontent.com/576385/50405925-dbfc7e00-0770-11e9-9b85-333fab0af9ac.png) + + Thanks @Rakete1111. + +- Parameterized formatting functions on the type of the format string + (https://github.com/fmtlib/fmt/issues/880, + https://github.com/fmtlib/fmt/pull/881, + https://github.com/fmtlib/fmt/pull/883, + https://github.com/fmtlib/fmt/pull/885, + https://github.com/fmtlib/fmt/pull/897, + https://github.com/fmtlib/fmt/issues/920). Any object of + type `S` that has an overloaded `to_string_view(const S&)` returning + `fmt::string_view` can be used as a format string: + + ```c++ + 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); + ``` + + Thanks @DanielaE. + +- Made `std::string_view` work as a format string + (https://github.com/fmtlib/fmt/pull/898): + + ```c++ + auto message = fmt::format(std::string_view("The answer is {}."), 42); + ``` + + Thanks @DanielaE. + +- Added wide string support to compile-time format string checks + (https://github.com/fmtlib/fmt/pull/924): + + ```c++ + print(fmt(L"{:f}"), 42); // compile-time error: invalid type specifier + ``` + + Thanks @XZiar. + +- Made colored print functions work with wide strings + (https://github.com/fmtlib/fmt/pull/867): + + ```c++ + #include + + int main() { + print(fg(fmt::color::red), L"{}\n", 42); + } + ``` + + Thanks @DanielaE. + +- Introduced experimental Unicode support + (https://github.com/fmtlib/fmt/issues/628, + https://github.com/fmtlib/fmt/pull/891): + + ```c++ + using namespace fmt::literals; + auto s = fmt::format("{:*^5}"_u, "🤡"_u); // s == "**🤡**"_u + ``` + +- Improved locale support: + + ```c++ + #include + + struct numpunct : std::numpunct { + protected: + char do_thousands_sep() const override { return '~'; } + }; + + std::locale loc; + auto s = fmt::format(std::locale(loc, new numpunct()), "{:n}", 1234567); + // s == "1~234~567" + ``` + +- Constrained formatting functions on proper iterator types + (https://github.com/fmtlib/fmt/pull/921). Thanks @DanielaE. + +- Added `make_printf_args` and `make_wprintf_args` functions + (https://github.com/fmtlib/fmt/pull/934). Thanks @tnovotny. + +- Deprecated `fmt::visit`, `parse_context`, and `wparse_context`. Use + `fmt::visit_format_arg`, `format_parse_context`, and + `wformat_parse_context` instead. + +- Removed undocumented `basic_fixed_buffer` which has been superseded + by the iterator-based API + (https://github.com/fmtlib/fmt/issues/873, + https://github.com/fmtlib/fmt/pull/902). Thanks @superfunc. + +- Disallowed repeated leading zeros in an argument ID: + + ```c++ + fmt::print("{000}", 42); // error + ``` + +- Reintroduced support for gcc 4.4. + +- Fixed compilation on platforms with exotic `double` + (https://github.com/fmtlib/fmt/issues/878). + +- Improved documentation + (https://github.com/fmtlib/fmt/issues/164, + https://github.com/fmtlib/fmt/issues/877, + https://github.com/fmtlib/fmt/pull/901, + https://github.com/fmtlib/fmt/pull/906, + https://github.com/fmtlib/fmt/pull/979). + Thanks @kookjr, @DarkDimius and @HecticSerenity. + +- Added pkgconfig support which makes it easier to consume the library + from meson and other build systems + (https://github.com/fmtlib/fmt/pull/916). Thanks @colemickens. + +- Various build improvements + (https://github.com/fmtlib/fmt/pull/909, + https://github.com/fmtlib/fmt/pull/926, + https://github.com/fmtlib/fmt/pull/937, + https://github.com/fmtlib/fmt/pull/953, + https://github.com/fmtlib/fmt/pull/959). + Thanks @tchaikov, @luncliff, @AndreasSchoenle, @hotwatermorning and @Zefz. + +- Improved `string_view` construction performance + (https://github.com/fmtlib/fmt/pull/914). Thanks @gabime. + +- Fixed non-matching char types + (https://github.com/fmtlib/fmt/pull/895). Thanks @DanielaE. + +- Fixed `format_to_n` with `std::back_insert_iterator` + (https://github.com/fmtlib/fmt/pull/913). Thanks @DanielaE. + +- Fixed locale-dependent formatting + (https://github.com/fmtlib/fmt/issues/905). + +- Fixed various compiler warnings and errors + (https://github.com/fmtlib/fmt/pull/882, + https://github.com/fmtlib/fmt/pull/886, + https://github.com/fmtlib/fmt/pull/933, + https://github.com/fmtlib/fmt/pull/941, + https://github.com/fmtlib/fmt/issues/931, + https://github.com/fmtlib/fmt/pull/943, + https://github.com/fmtlib/fmt/pull/954, + https://github.com/fmtlib/fmt/pull/956, + https://github.com/fmtlib/fmt/pull/962, + https://github.com/fmtlib/fmt/issues/965, + https://github.com/fmtlib/fmt/issues/977, + https://github.com/fmtlib/fmt/pull/983, + https://github.com/fmtlib/fmt/pull/989). + Thanks @Luthaf, @stevenhoving, @christinaa, @lgritz, @DanielaE, + @0x8000-0000 and @liuping1997. + +# 5.2.1 - 2018-09-21 + +- Fixed `visit` lookup issues on gcc 7 & 8 + (https://github.com/fmtlib/fmt/pull/870). Thanks @medithe. +- Fixed linkage errors on older gcc. +- Prevented `fmt/range.h` from specializing `fmt::basic_string_view` + (https://github.com/fmtlib/fmt/issues/865, + https://github.com/fmtlib/fmt/pull/868). Thanks @hhggit. +- Improved error message when formatting unknown types + (https://github.com/fmtlib/fmt/pull/872). Thanks @foonathan. +- Disabled templated user-defined literals when compiled under nvcc + (https://github.com/fmtlib/fmt/pull/875). Thanks @CandyGumdrop. +- Fixed `format_to` formatting to `wmemory_buffer` + (https://github.com/fmtlib/fmt/issues/874). + +# 5.2.0 - 2018-09-13 + +- Optimized format string parsing and argument processing which + resulted in up to 5x speed up on long format strings and significant + performance boost on various benchmarks. For example, version 5.2 is + 2.22x faster than 5.1 on decimal integer formatting with `format_to` + (macOS, clang-902.0.39.2): + + | Method | Time, s | Speedup | + | -------------------------- | --------------: | ------: | + | fmt::format 5.1 | 0.58 | | + | fmt::format 5.2 | 0.35 | 1.66x | + | fmt::format_to 5.1 | 0.51 | | + | fmt::format_to 5.2 | 0.23 | 2.22x | + | sprintf | 0.71 | | + | std::to_string | 1.01 | | + | std::stringstream | 1.73 | | + +- Changed the `fmt` macro from opt-out to opt-in to prevent name + collisions. To enable it define the `FMT_STRING_ALIAS` macro to 1 + before including `fmt/format.h`: + + ```c++ + #define FMT_STRING_ALIAS 1 + #include + std::string answer = format(fmt("{}"), 42); + ``` + +- Added compile-time format string checks to `format_to` overload that + takes `fmt::memory_buffer` + (https://github.com/fmtlib/fmt/issues/783): + + ```c++ + fmt::memory_buffer buf; + // Compile-time error: invalid type specifier. + fmt::format_to(buf, fmt("{:d}"), "foo"); + ``` + +- Moved experimental color support to `fmt/color.h` and enabled the + new API by default. The old API can be enabled by defining the + `FMT_DEPRECATED_COLORS` macro. + +- Added formatting support for types explicitly convertible to + `fmt::string_view`: + + ```c++ + struct foo { + explicit operator fmt::string_view() const { return "foo"; } + }; + auto s = format("{}", foo()); + ``` + + In particular, this makes formatting function work with + `folly::StringPiece`. + +- Implemented preliminary support for `char*_t` by replacing the + `format` function overloads with a single function template + parameterized on the string type. + +- Added support for dynamic argument lists + (https://github.com/fmtlib/fmt/issues/814, + https://github.com/fmtlib/fmt/pull/819). Thanks @MikePopoloski. + +- Reduced executable size overhead for embedded targets using newlib + nano by making locale dependency optional + (https://github.com/fmtlib/fmt/pull/839). Thanks @teajay-fr. + +- Keep `noexcept` specifier when exceptions are disabled + (https://github.com/fmtlib/fmt/issues/801, + https://github.com/fmtlib/fmt/pull/810). Thanks @qis. + +- Fixed formatting of user-defined types providing `operator<<` with + `format_to_n` (https://github.com/fmtlib/fmt/pull/806). + Thanks @mkurdej. + +- Fixed dynamic linkage of new symbols + (https://github.com/fmtlib/fmt/issues/808). + +- Fixed global initialization issue + (https://github.com/fmtlib/fmt/issues/807): + + ```c++ + // This works on compilers with constexpr support. + static const std::string answer = fmt::format("{}", 42); + ``` + +- Fixed various compiler warnings and errors + (https://github.com/fmtlib/fmt/pull/804, + https://github.com/fmtlib/fmt/issues/809, + https://github.com/fmtlib/fmt/pull/811, + https://github.com/fmtlib/fmt/issues/822, + https://github.com/fmtlib/fmt/pull/827, + https://github.com/fmtlib/fmt/issues/830, + https://github.com/fmtlib/fmt/pull/838, + https://github.com/fmtlib/fmt/issues/843, + https://github.com/fmtlib/fmt/pull/844, + https://github.com/fmtlib/fmt/issues/851, + https://github.com/fmtlib/fmt/pull/852, + https://github.com/fmtlib/fmt/pull/854). + Thanks @henryiii, @medithe, and @eliasdaler. + +# 5.1.0 - 2018-07-05 + +- Added experimental support for RGB color output enabled with the + `FMT_EXTENDED_COLORS` macro: + + ```c++ + #define FMT_EXTENDED_COLORS + #define FMT_HEADER_ONLY // or compile fmt with FMT_EXTENDED_COLORS defined + #include + + fmt::print(fmt::color::steel_blue, "Some beautiful text"); + ``` + + The old API (the `print_colored` and `vprint_colored` functions and + the `color` enum) is now deprecated. + (https://github.com/fmtlib/fmt/issues/762 + https://github.com/fmtlib/fmt/pull/767). thanks @Remotion. + +- Added quotes to strings in ranges and tuples + (https://github.com/fmtlib/fmt/pull/766). Thanks @Remotion. + +- Made `format_to` work with `basic_memory_buffer` + (https://github.com/fmtlib/fmt/issues/776). + +- Added `vformat_to_n` and `wchar_t` overload of `format_to_n` + (https://github.com/fmtlib/fmt/issues/764, + https://github.com/fmtlib/fmt/issues/769). + +- Made `is_range` and `is_tuple_like` part of public (experimental) + API to allow specialization for user-defined types + (https://github.com/fmtlib/fmt/issues/751, + https://github.com/fmtlib/fmt/pull/759). Thanks @drrlvn. + +- Added more compilers to continuous integration and increased + `FMT_PEDANTIC` warning levels + (https://github.com/fmtlib/fmt/pull/736). Thanks @eliaskosunen. + +- Fixed compilation with MSVC 2013. + +- Fixed handling of user-defined types in `format_to` + (https://github.com/fmtlib/fmt/issues/793). + +- Forced linking of inline `vformat` functions into the library + (https://github.com/fmtlib/fmt/issues/795). + +- Fixed incorrect call to on_align in `'{:}='` + (https://github.com/fmtlib/fmt/issues/750). + +- Fixed floating-point formatting to a non-back_insert_iterator with + sign & numeric alignment specified + (https://github.com/fmtlib/fmt/issues/756). + +- Fixed formatting to an array with `format_to_n` + (https://github.com/fmtlib/fmt/issues/778). + +- Fixed formatting of more than 15 named arguments + (https://github.com/fmtlib/fmt/issues/754). + +- Fixed handling of compile-time strings when including + `fmt/ostream.h`. (https://github.com/fmtlib/fmt/issues/768). + +- Fixed various compiler warnings and errors + (https://github.com/fmtlib/fmt/issues/742, + https://github.com/fmtlib/fmt/issues/748, + https://github.com/fmtlib/fmt/issues/752, + https://github.com/fmtlib/fmt/issues/770, + https://github.com/fmtlib/fmt/pull/775, + https://github.com/fmtlib/fmt/issues/779, + https://github.com/fmtlib/fmt/pull/780, + https://github.com/fmtlib/fmt/pull/790, + https://github.com/fmtlib/fmt/pull/792, + https://github.com/fmtlib/fmt/pull/800). + Thanks @Remotion, @gabime, @foonathan, @Dark-Passenger and @0x8000-0000. + +# 5.0.0 - 2018-05-21 + +- Added a requirement for partial C++11 support, most importantly + variadic templates and type traits, and dropped `FMT_VARIADIC_*` + emulation macros. Variadic templates are available since GCC 4.4, + Clang 2.9 and MSVC 18.0 (2013). For older compilers use {fmt} + [version 4.x](https://github.com/fmtlib/fmt/releases/tag/4.1.0) + which continues to be maintained and works with C++98 compilers. + +- Renamed symbols to follow standard C++ naming conventions and + proposed a subset of the library for standardization in [P0645R2 + Text Formatting](https://wg21.link/P0645). + +- Implemented `constexpr` parsing of format strings and [compile-time + format string + checks](https://fmt.dev/latest/api.html#compile-time-format-string-checks). + For example + + ```c++ + #include + + std::string s = format(fmt("{:d}"), "foo"); + ``` + + gives a compile-time error because `d` is an invalid specifier for + strings ([godbolt](https://godbolt.org/g/rnCy9Q)): + + ... + :4:19: note: in instantiation of function template specialization 'fmt::v5::format' requested here + std::string s = format(fmt("{:d}"), "foo"); + ^ + format.h:1337:13: note: non-constexpr function 'on_error' cannot be used in a constant expression + handler.on_error("invalid type specifier"); + + Compile-time checks require relaxed `constexpr` (C++14 feature) + support. If the latter is not available, checks will be performed at + runtime. + +- Separated format string parsing and formatting in the extension API + to enable compile-time format string processing. For example + + ```c++ + struct Answer {}; + + namespace fmt { + template <> + struct formatter { + constexpr auto parse(parse_context& ctx) { + auto it = ctx.begin(); + spec = *it; + if (spec != 'd' && spec != 's') + throw format_error("invalid specifier"); + return ++it; + } + + template + auto format(Answer, FormatContext& ctx) { + return spec == 's' ? + format_to(ctx.begin(), "{}", "fourty-two") : + format_to(ctx.begin(), "{}", 42); + } + + char spec = 0; + }; + } + + std::string s = format(fmt("{:x}"), Answer()); + ``` + + gives a compile-time error due to invalid format specifier + ([godbolt](https://godbolt.org/g/2jQ1Dv)): + + ... + :12:45: error: expression '' is not a constant expression + throw format_error("invalid specifier"); + +- Added [iterator + support](https://fmt.dev/latest/api.html#output-iterator-support): + + ```c++ + #include + #include + + std::vector out; + fmt::format_to(std::back_inserter(out), "{}", 42); + ``` + +- Added the + [format_to_n](https://fmt.dev/latest/api.html#_CPPv2N3fmt11format_to_nE8OutputItNSt6size_tE11string_viewDpRK4Args) + function that restricts the output to the specified number of + characters (https://github.com/fmtlib/fmt/issues/298): + + ```c++ + char out[4]; + fmt::format_to_n(out, sizeof(out), "{}", 12345); + // out == "1234" (without terminating '\0') + ``` + +- Added the [formatted_size]( + https://fmt.dev/latest/api.html#_CPPv2N3fmt14formatted_sizeE11string_viewDpRK4Args) + function for computing the output size: + + ```c++ + #include + + auto size = fmt::formatted_size("{}", 12345); // size == 5 + ``` + +- Improved compile times by reducing dependencies on standard headers + and providing a lightweight [core + API](https://fmt.dev/latest/api.html#core-api): + + ```c++ + #include + + fmt::print("The answer is {}.", 42); + ``` + + See [Compile time and code + bloat](https://github.com/fmtlib/fmt#compile-time-and-code-bloat). + +- Added the [make_format_args]( + https://fmt.dev/latest/api.html#_CPPv2N3fmt16make_format_argsEDpRK4Args) + function for capturing formatting arguments: + + ```c++ + // Prints formatted error message. + void vreport_error(const char *format, fmt::format_args args) { + fmt::print("Error: "); + fmt::vprint(format, args); + } + template + void report_error(const char *format, const Args & ... args) { + vreport_error(format, fmt::make_format_args(args...)); + } + ``` + +- Added the `make_printf_args` function for capturing `printf` + arguments (https://github.com/fmtlib/fmt/issues/687, + https://github.com/fmtlib/fmt/pull/694). Thanks @Kronuz. + +- Added prefix `v` to non-variadic functions taking `format_args` to + distinguish them from variadic ones: + + ```c++ + std::string vformat(string_view format_str, format_args args); + + template + std::string format(string_view format_str, const Args & ... args); + ``` + +- Added experimental support for formatting ranges, containers and + tuple-like types in `fmt/ranges.h` + (https://github.com/fmtlib/fmt/pull/735): + + ```c++ + #include + + std::vector v = {1, 2, 3}; + fmt::print("{}", v); // prints {1, 2, 3} + ``` + + Thanks @Remotion. + +- Implemented `wchar_t` date and time formatting + (https://github.com/fmtlib/fmt/pull/712): + + ```c++ + #include + + std::time_t t = std::time(nullptr); + auto s = fmt::format(L"The date is {:%Y-%m-%d}.", *std::localtime(&t)); + ``` + + Thanks @DanielaE. + +- Provided more wide string overloads + (https://github.com/fmtlib/fmt/pull/724). Thanks @DanielaE. + +- Switched from a custom null-terminated string view class to + `string_view` in the format API and provided `fmt::string_view` + which implements a subset of `std::string_view` API for pre-C++17 + systems. + +- Added support for `std::experimental::string_view` + (https://github.com/fmtlib/fmt/pull/607): + + ```c++ + #include + #include + + fmt::print("{}", std::experimental::string_view("foo")); + ``` + + Thanks @virgiliofornazin. + +- Allowed mixing named and automatic arguments: + + ```c++ + fmt::format("{} {two}", 1, fmt::arg("two", 2)); + ``` + +- Removed the write API in favor of the [format + API](https://fmt.dev/latest/api.html#format-api) with compile-time + handling of format strings. + +- Disallowed formatting of multibyte strings into a wide character + target (https://github.com/fmtlib/fmt/pull/606). + +- Improved documentation + (https://github.com/fmtlib/fmt/pull/515, + https://github.com/fmtlib/fmt/issues/614, + https://github.com/fmtlib/fmt/pull/617, + https://github.com/fmtlib/fmt/pull/661, + https://github.com/fmtlib/fmt/pull/680). + Thanks @ibell, @mihaitodor and @johnthagen. + +- Implemented more efficient handling of large number of format + arguments. + +- Introduced an inline namespace for symbol versioning. + +- Added debug postfix `d` to the `fmt` library name + (https://github.com/fmtlib/fmt/issues/636). + +- Removed unnecessary `fmt/` prefix in includes + (https://github.com/fmtlib/fmt/pull/397). Thanks @chronoxor. + +- Moved `fmt/*.h` to `include/fmt/*.h` to prevent irrelevant files and + directories appearing on the include search paths when fmt is used + as a subproject and moved source files to the `src` directory. + +- Added qmake project file `support/fmt.pro` + (https://github.com/fmtlib/fmt/pull/641). Thanks @cowo78. + +- Added Gradle build file `support/build.gradle` + (https://github.com/fmtlib/fmt/pull/649). Thanks @luncliff. + +- Removed `FMT_CPPFORMAT` CMake option. + +- Fixed a name conflict with the macro `CHAR_WIDTH` in glibc + (https://github.com/fmtlib/fmt/pull/616). Thanks @aroig. + +- Fixed handling of nested braces in `fmt::join` + (https://github.com/fmtlib/fmt/issues/638). + +- Added `SOURCELINK_SUFFIX` for compatibility with Sphinx 1.5 + (https://github.com/fmtlib/fmt/pull/497). Thanks @ginggs. + +- Added a missing `inline` in the header-only mode + (https://github.com/fmtlib/fmt/pull/626). Thanks @aroig. + +- Fixed various compiler warnings + (https://github.com/fmtlib/fmt/pull/640, + https://github.com/fmtlib/fmt/pull/656, + https://github.com/fmtlib/fmt/pull/679, + https://github.com/fmtlib/fmt/pull/681, + https://github.com/fmtlib/fmt/pull/705, + https://github.com/fmtlib/fmt/issues/715, + https://github.com/fmtlib/fmt/pull/717, + https://github.com/fmtlib/fmt/pull/720, + https://github.com/fmtlib/fmt/pull/723, + https://github.com/fmtlib/fmt/pull/726, + https://github.com/fmtlib/fmt/pull/730, + https://github.com/fmtlib/fmt/pull/739). + Thanks @peterbell10, @LarsGullik, @foonathan, @eliaskosunen, + @christianparpart, @DanielaE and @mwinterb. + +- Worked around an MSVC bug and fixed several warnings + (https://github.com/fmtlib/fmt/pull/653). Thanks @alabuzhev. + +- Worked around GCC bug 67371 + (https://github.com/fmtlib/fmt/issues/682). + +- Fixed compilation with `-fno-exceptions` + (https://github.com/fmtlib/fmt/pull/655). Thanks @chenxiaolong. + +- Made `constexpr remove_prefix` gcc version check tighter + (https://github.com/fmtlib/fmt/issues/648). + +- Renamed internal type enum constants to prevent collision with + poorly written C libraries + (https://github.com/fmtlib/fmt/issues/644). + +- Added detection of `wostream operator<<` + (https://github.com/fmtlib/fmt/issues/650). + +- Fixed compilation on OpenBSD + (https://github.com/fmtlib/fmt/pull/660). Thanks @hubslave. + +- Fixed compilation on FreeBSD 12 + (https://github.com/fmtlib/fmt/pull/732). Thanks @dankm. + +- Fixed compilation when there is a mismatch between `-std` options + between the library and user code + (https://github.com/fmtlib/fmt/issues/664). + +- Fixed compilation with GCC 7 and `-std=c++11` + (https://github.com/fmtlib/fmt/issues/734). + +- Improved generated binary code on GCC 7 and older + (https://github.com/fmtlib/fmt/issues/668). + +- Fixed handling of numeric alignment with no width + (https://github.com/fmtlib/fmt/issues/675). + +- Fixed handling of empty strings in UTF8/16 converters + (https://github.com/fmtlib/fmt/pull/676). Thanks @vgalka-sl. + +- Fixed formatting of an empty `string_view` + (https://github.com/fmtlib/fmt/issues/689). + +- Fixed detection of `string_view` on libc++ + (https://github.com/fmtlib/fmt/issues/686). + +- Fixed DLL issues (https://github.com/fmtlib/fmt/pull/696). + Thanks @sebkoenig. + +- Fixed compile checks for mixing narrow and wide strings + (https://github.com/fmtlib/fmt/issues/690). + +- Disabled unsafe implicit conversion to `std::string` + (https://github.com/fmtlib/fmt/issues/729). + +- Fixed handling of reused format specs (as in `fmt::join`) for + pointers (https://github.com/fmtlib/fmt/pull/725). Thanks @mwinterb. + +- Fixed installation of `fmt/ranges.h` + (https://github.com/fmtlib/fmt/pull/738). Thanks @sv1990. + +# 4.1.0 - 2017-12-20 + +- Added `fmt::to_wstring()` in addition to `fmt::to_string()` + (https://github.com/fmtlib/fmt/pull/559). Thanks @alabuzhev. +- Added support for C++17 `std::string_view` + (https://github.com/fmtlib/fmt/pull/571 and + https://github.com/fmtlib/fmt/pull/578). + Thanks @thelostt and @mwinterb. +- Enabled stream exceptions to catch errors + (https://github.com/fmtlib/fmt/issues/581). Thanks @crusader-mike. +- Allowed formatting of class hierarchies with `fmt::format_arg()` + (https://github.com/fmtlib/fmt/pull/547). Thanks @rollbear. +- Removed limitations on character types + (https://github.com/fmtlib/fmt/pull/563). Thanks @Yelnats321. +- Conditionally enabled use of `std::allocator_traits` + (https://github.com/fmtlib/fmt/pull/583). Thanks @mwinterb. +- Added support for `const` variadic member function emulation with + `FMT_VARIADIC_CONST` + (https://github.com/fmtlib/fmt/pull/591). Thanks @ludekvodicka. +- Various bugfixes: bad overflow check, unsupported implicit type + conversion when determining formatting function, test segfaults + (https://github.com/fmtlib/fmt/issues/551), ill-formed + macros (https://github.com/fmtlib/fmt/pull/542) and + ambiguous overloads + (https://github.com/fmtlib/fmt/issues/580). Thanks @xylosper. +- Prevented warnings on MSVC + (https://github.com/fmtlib/fmt/pull/605, + https://github.com/fmtlib/fmt/pull/602, and + https://github.com/fmtlib/fmt/pull/545), clang + (https://github.com/fmtlib/fmt/pull/582), GCC + (https://github.com/fmtlib/fmt/issues/573), various + conversion warnings (https://github.com/fmtlib/fmt/pull/609, + https://github.com/fmtlib/fmt/pull/567, + https://github.com/fmtlib/fmt/pull/553 and + https://github.com/fmtlib/fmt/pull/553), and added + `override` and `[[noreturn]]` + (https://github.com/fmtlib/fmt/pull/549 and + https://github.com/fmtlib/fmt/issues/555). + Thanks @alabuzhev, @virgiliofornazin, @alexanderbock, @yumetodo, @VaderY, + @jpcima, @thelostt and @Manu343726. +- Improved CMake: Used `GNUInstallDirs` to set installation location + (https://github.com/fmtlib/fmt/pull/610) and fixed warnings + (https://github.com/fmtlib/fmt/pull/536 and + https://github.com/fmtlib/fmt/pull/556). + Thanks @mikecrowe, @evgen231 and @henryiii. + +# 4.0.0 - 2017-06-27 + +- Removed old compatibility headers `cppformat/*.h` and CMake options + (https://github.com/fmtlib/fmt/pull/527). Thanks @maddinat0r. + +- Added `string.h` containing `fmt::to_string()` as alternative to + `std::to_string()` as well as other string writer functionality + (https://github.com/fmtlib/fmt/issues/326 and + https://github.com/fmtlib/fmt/pull/441): + + ```c++ + #include "fmt/string.h" + + std::string answer = fmt::to_string(42); + ``` + + Thanks @glebov-andrey. + +- Moved `fmt::printf()` to new `printf.h` header and allowed `%s` as + generic specifier (https://github.com/fmtlib/fmt/pull/453), + made `%.f` more conformant to regular `printf()` + (https://github.com/fmtlib/fmt/pull/490), added custom + writer support (https://github.com/fmtlib/fmt/issues/476) + and implemented missing custom argument formatting + (https://github.com/fmtlib/fmt/pull/339 and + https://github.com/fmtlib/fmt/pull/340): + + ```c++ + #include "fmt/printf.h" + + // %s format specifier can be used with any argument type. + fmt::printf("%s", 42); + ``` + + Thanks @mojoBrendan, @manylegged and @spacemoose. + See also https://github.com/fmtlib/fmt/issues/360, + https://github.com/fmtlib/fmt/issues/335 and + https://github.com/fmtlib/fmt/issues/331. + +- Added `container.h` containing a `BasicContainerWriter` to write to + containers like `std::vector` + (https://github.com/fmtlib/fmt/pull/450). Thanks @polyvertex. + +- Added `fmt::join()` function that takes a range and formats its + elements separated by a given string + (https://github.com/fmtlib/fmt/pull/466): + + ```c++ + #include "fmt/format.h" + + std::vector v = {1.2, 3.4, 5.6}; + // Prints "(+01.20, +03.40, +05.60)". + fmt::print("({:+06.2f})", fmt::join(v.begin(), v.end(), ", ")); + ``` + + Thanks @olivier80. + +- Added support for custom formatting specifications to simplify + customization of built-in formatting + (https://github.com/fmtlib/fmt/pull/444). Thanks @polyvertex. + See also https://github.com/fmtlib/fmt/issues/439. + +- Added `fmt::format_system_error()` for error code formatting + (https://github.com/fmtlib/fmt/issues/323 and + https://github.com/fmtlib/fmt/pull/526). Thanks @maddinat0r. + +- Added thread-safe `fmt::localtime()` and `fmt::gmtime()` as + replacement for the standard version to `time.h` + (https://github.com/fmtlib/fmt/pull/396). Thanks @codicodi. + +- Internal improvements to `NamedArg` and `ArgLists` + (https://github.com/fmtlib/fmt/pull/389 and + https://github.com/fmtlib/fmt/pull/390). Thanks @chronoxor. + +- Fixed crash due to bug in `FormatBuf` + (https://github.com/fmtlib/fmt/pull/493). Thanks @effzeh. See also + https://github.com/fmtlib/fmt/issues/480 and + https://github.com/fmtlib/fmt/issues/491. + +- Fixed handling of wide strings in `fmt::StringWriter`. + +- Improved compiler error messages + (https://github.com/fmtlib/fmt/issues/357). + +- Fixed various warnings and issues with various compilers + (https://github.com/fmtlib/fmt/pull/494, + https://github.com/fmtlib/fmt/pull/499, + https://github.com/fmtlib/fmt/pull/483, + https://github.com/fmtlib/fmt/pull/485, + https://github.com/fmtlib/fmt/pull/482, + https://github.com/fmtlib/fmt/pull/475, + https://github.com/fmtlib/fmt/pull/473 and + https://github.com/fmtlib/fmt/pull/414). + Thanks @chronoxor, @zhaohuaxishi, @pkestene, @dschmidt and @0x414c. + +- Improved CMake: targets are now namespaced + (https://github.com/fmtlib/fmt/pull/511 and + https://github.com/fmtlib/fmt/pull/513), supported + header-only `printf.h` + (https://github.com/fmtlib/fmt/pull/354), fixed issue with + minimal supported library subset + (https://github.com/fmtlib/fmt/issues/418, + https://github.com/fmtlib/fmt/pull/419 and + https://github.com/fmtlib/fmt/pull/420). + Thanks @bjoernthiel, @niosHD, @LogicalKnight and @alabuzhev. + +- Improved documentation (https://github.com/fmtlib/fmt/pull/393). + Thanks @pwm1234. + +# 3.0.2 - 2017-06-14 + +- Added `FMT_VERSION` macro + (https://github.com/fmtlib/fmt/issues/411). +- Used `FMT_NULL` instead of literal `0` + (https://github.com/fmtlib/fmt/pull/409). Thanks @alabuzhev. +- Added extern templates for `format_float` + (https://github.com/fmtlib/fmt/issues/413). +- Fixed implicit conversion issue + (https://github.com/fmtlib/fmt/issues/507). +- Fixed signbit detection + (https://github.com/fmtlib/fmt/issues/423). +- Fixed naming collision + (https://github.com/fmtlib/fmt/issues/425). +- Fixed missing intrinsic for C++/CLI + (https://github.com/fmtlib/fmt/pull/457). Thanks @calumr. +- Fixed Android detection + (https://github.com/fmtlib/fmt/pull/458). Thanks @Gachapen. +- Use lean `windows.h` if not in header-only mode + (https://github.com/fmtlib/fmt/pull/503). Thanks @Quentin01. +- Fixed issue with CMake exporting C++11 flag + (https://github.com/fmtlib/fmt/pull/455). Thanks @EricWF. +- Fixed issue with nvcc and MSVC compiler bug and MinGW + (https://github.com/fmtlib/fmt/issues/505). +- Fixed DLL issues (https://github.com/fmtlib/fmt/pull/469 and + https://github.com/fmtlib/fmt/pull/502). + Thanks @richardeakin and @AndreasSchoenle. +- Fixed test compilation under FreeBSD + (https://github.com/fmtlib/fmt/issues/433). +- Fixed various warnings + (https://github.com/fmtlib/fmt/pull/403, + https://github.com/fmtlib/fmt/pull/410 and + https://github.com/fmtlib/fmt/pull/510). + Thanks @Lecetem, @chenhayat and @trozen. +- Worked around a broken `__builtin_clz` in clang with MS codegen + (https://github.com/fmtlib/fmt/issues/519). +- Removed redundant include + (https://github.com/fmtlib/fmt/issues/479). +- Fixed documentation issues. + +# 3.0.1 - 2016-11-01 + +- Fixed handling of thousands separator + (https://github.com/fmtlib/fmt/issues/353). +- Fixed handling of `unsigned char` strings + (https://github.com/fmtlib/fmt/issues/373). +- Corrected buffer growth when formatting time + (https://github.com/fmtlib/fmt/issues/367). +- Removed warnings under MSVC and clang + (https://github.com/fmtlib/fmt/issues/318, + https://github.com/fmtlib/fmt/issues/250, also merged + https://github.com/fmtlib/fmt/pull/385 and + https://github.com/fmtlib/fmt/pull/361). + Thanks @jcelerier and @nmoehrle. +- Fixed compilation issues under Android + (https://github.com/fmtlib/fmt/pull/327, + https://github.com/fmtlib/fmt/issues/345 and + https://github.com/fmtlib/fmt/pull/381), FreeBSD + (https://github.com/fmtlib/fmt/pull/358), Cygwin + (https://github.com/fmtlib/fmt/issues/388), MinGW + (https://github.com/fmtlib/fmt/issues/355) as well as other + issues (https://github.com/fmtlib/fmt/issues/350, + https://github.com/fmtlib/fmt/issues/355, + https://github.com/fmtlib/fmt/pull/348, + https://github.com/fmtlib/fmt/pull/402, + https://github.com/fmtlib/fmt/pull/405). + Thanks @dpantele, @hghwng, @arvedarved, @LogicalKnight and @JanHellwig. +- Fixed some documentation issues and extended specification + (https://github.com/fmtlib/fmt/issues/320, + https://github.com/fmtlib/fmt/pull/333, + https://github.com/fmtlib/fmt/issues/347, + https://github.com/fmtlib/fmt/pull/362). Thanks @smellman. + +# 3.0.0 - 2016-05-07 + +- The project has been renamed from C++ Format (cppformat) to fmt for + consistency with the used namespace and macro prefix + (https://github.com/fmtlib/fmt/issues/307). Library headers + are now located in the `fmt` directory: + + ```c++ + #include "fmt/format.h" + ``` + + Including `format.h` from the `cppformat` directory is deprecated + but works via a proxy header which will be removed in the next major + version. + + The documentation is now available at . + +- Added support for + [strftime](http://en.cppreference.com/w/cpp/chrono/c/strftime)-like + [date and time + formatting](https://fmt.dev/3.0.0/api.html#date-and-time-formatting) + (https://github.com/fmtlib/fmt/issues/283): + + ```c++ + #include "fmt/time.h" + + std::time_t t = std::time(nullptr); + // Prints "The date is 2016-04-29." (with the current date) + fmt::print("The date is {:%Y-%m-%d}.", *std::localtime(&t)); + ``` + +- `std::ostream` support including formatting of user-defined types + that provide overloaded `operator<<` has been moved to + `fmt/ostream.h`: + + ```c++ + #include "fmt/ostream.h" + + class Date { + int year_, month_, day_; + public: + Date(int year, int month, int day) : year_(year), month_(month), day_(day) {} + + friend std::ostream &operator<<(std::ostream &os, const Date &d) { + return os << d.year_ << '-' << d.month_ << '-' << d.day_; + } + }; + + std::string s = fmt::format("The date is {}", Date(2012, 12, 9)); + // s == "The date is 2012-12-9" + ``` + +- Added support for [custom argument + formatters](https://fmt.dev/3.0.0/api.html#argument-formatters) + (https://github.com/fmtlib/fmt/issues/235). + +- Added support for locale-specific integer formatting with the `n` + specifier (https://github.com/fmtlib/fmt/issues/305): + + ```c++ + std::setlocale(LC_ALL, "en_US.utf8"); + fmt::print("cppformat: {:n}\n", 1234567); // prints 1,234,567 + ``` + +- Sign is now preserved when formatting an integer with an incorrect + `printf` format specifier + (https://github.com/fmtlib/fmt/issues/265): + + ```c++ + fmt::printf("%lld", -42); // prints -42 + ``` + + Note that it would be an undefined behavior in `std::printf`. + +- Length modifiers such as `ll` are now optional in printf formatting + functions and the correct type is determined automatically + (https://github.com/fmtlib/fmt/issues/255): + + ```c++ + fmt::printf("%d", std::numeric_limits::max()); + ``` + + Note that it would be an undefined behavior in `std::printf`. + +- Added initial support for custom formatters + (https://github.com/fmtlib/fmt/issues/231). + +- Fixed detection of user-defined literal support on Intel C++ + compiler (https://github.com/fmtlib/fmt/issues/311, + https://github.com/fmtlib/fmt/pull/312). + Thanks @dean0x7d and @speth. + +- Reduced compile time + (https://github.com/fmtlib/fmt/pull/243, + https://github.com/fmtlib/fmt/pull/249, + https://github.com/fmtlib/fmt/issues/317): + + ![](https://cloud.githubusercontent.com/assets/4831417/11614060/b9e826d2-9c36-11e5-8666-d4131bf503ef.png) + + ![](https://cloud.githubusercontent.com/assets/4831417/11614080/6ac903cc-9c37-11e5-8165-26df6efae364.png) + + Thanks @dean0x7d. + +- Compile test fixes (https://github.com/fmtlib/fmt/pull/313). + Thanks @dean0x7d. + +- Documentation fixes (https://github.com/fmtlib/fmt/pull/239, + https://github.com/fmtlib/fmt/issues/248, + https://github.com/fmtlib/fmt/issues/252, + https://github.com/fmtlib/fmt/pull/258, + https://github.com/fmtlib/fmt/issues/260, + https://github.com/fmtlib/fmt/issues/301, + https://github.com/fmtlib/fmt/pull/309). + Thanks @ReadmeCritic @Gachapen and @jwilk. + +- Fixed compiler and sanitizer warnings + (https://github.com/fmtlib/fmt/issues/244, + https://github.com/fmtlib/fmt/pull/256, + https://github.com/fmtlib/fmt/pull/259, + https://github.com/fmtlib/fmt/issues/263, + https://github.com/fmtlib/fmt/issues/274, + https://github.com/fmtlib/fmt/pull/277, + https://github.com/fmtlib/fmt/pull/286, + https://github.com/fmtlib/fmt/issues/291, + https://github.com/fmtlib/fmt/issues/296, + https://github.com/fmtlib/fmt/issues/308). + Thanks @mwinterb, @pweiskircher and @Naios. + +- Improved compatibility with Windows Store apps + (https://github.com/fmtlib/fmt/issues/280, + https://github.com/fmtlib/fmt/pull/285) Thanks @mwinterb. + +- Added tests of compatibility with older C++ standards + (https://github.com/fmtlib/fmt/pull/273). Thanks @niosHD. + +- Fixed Android build + (https://github.com/fmtlib/fmt/pull/271). Thanks @newnon. + +- Changed `ArgMap` to be backed by a vector instead of a map. + (https://github.com/fmtlib/fmt/issues/261, + https://github.com/fmtlib/fmt/pull/262). Thanks @mwinterb. + +- Added `fprintf` overload that writes to a `std::ostream` + (https://github.com/fmtlib/fmt/pull/251). + Thanks @nickhutchinson. + +- Export symbols when building a Windows DLL + (https://github.com/fmtlib/fmt/pull/245). + Thanks @macdems. + +- Fixed compilation on Cygwin + (https://github.com/fmtlib/fmt/issues/304). + +- Implemented a workaround for a bug in Apple LLVM version 4.2 of + clang (https://github.com/fmtlib/fmt/issues/276). + +- Implemented a workaround for Google Test bug + https://github.com/google/googletest/issues/705 on gcc 6 + (https://github.com/fmtlib/fmt/issues/268). Thanks @octoploid. + +- Removed Biicode support because the latter has been discontinued. + +# 2.1.1 - 2016-04-11 + +- The install location for generated CMake files is now configurable + via the `FMT_CMAKE_DIR` CMake variable + (https://github.com/fmtlib/fmt/pull/299). Thanks @niosHD. +- Documentation fixes + (https://github.com/fmtlib/fmt/issues/252). + +# 2.1.0 - 2016-03-21 + +- Project layout and build system improvements + (https://github.com/fmtlib/fmt/pull/267): + + - The code have been moved to the `cppformat` directory. Including + `format.h` from the top-level directory is deprecated but works + via a proxy header which will be removed in the next major + version. + - C++ Format CMake targets now have proper interface definitions. + - Installed version of the library now supports the header-only + configuration. + - Targets `doc`, `install`, and `test` are now disabled if C++ + Format is included as a CMake subproject. They can be enabled by + setting `FMT_DOC`, `FMT_INSTALL`, and `FMT_TEST` in the parent + project. + + Thanks @niosHD. + +# 2.0.1 - 2016-03-13 + +- Improved CMake find and package support + (https://github.com/fmtlib/fmt/issues/264). Thanks @niosHD. +- Fix compile error with Android NDK and mingw32 + (https://github.com/fmtlib/fmt/issues/241). Thanks @Gachapen. +- Documentation fixes + (https://github.com/fmtlib/fmt/issues/248, + https://github.com/fmtlib/fmt/issues/260). + +# 2.0.0 - 2015-12-01 + +## General + +- \[Breaking\] Named arguments + (https://github.com/fmtlib/fmt/pull/169, + https://github.com/fmtlib/fmt/pull/173, + https://github.com/fmtlib/fmt/pull/174): + + ```c++ + fmt::print("The answer is {answer}.", fmt::arg("answer", 42)); + ``` + + Thanks @jamboree. + +- \[Experimental\] User-defined literals for format and named + arguments (https://github.com/fmtlib/fmt/pull/204, + https://github.com/fmtlib/fmt/pull/206, + https://github.com/fmtlib/fmt/pull/207): + + ```c++ + using namespace fmt::literals; + fmt::print("The answer is {answer}.", "answer"_a=42); + ``` + + Thanks @dean0x7d. + +- \[Breaking\] Formatting of more than 16 arguments is now supported + when using variadic templates + (https://github.com/fmtlib/fmt/issues/141). Thanks @Shauren. + +- Runtime width specification + (https://github.com/fmtlib/fmt/pull/168): + + ```c++ + fmt::format("{0:{1}}", 42, 5); // gives " 42" + ``` + + Thanks @jamboree. + +- \[Breaking\] Enums are now formatted with an overloaded + `std::ostream` insertion operator (`operator<<`) if available + (https://github.com/fmtlib/fmt/issues/232). + +- \[Breaking\] Changed default `bool` format to textual, \"true\" or + \"false\" (https://github.com/fmtlib/fmt/issues/170): + + ```c++ + fmt::print("{}", true); // prints "true" + ``` + + To print `bool` as a number use numeric format specifier such as + `d`: + + ```c++ + fmt::print("{:d}", true); // prints "1" + ``` + +- `fmt::printf` and `fmt::sprintf` now support formatting of `bool` + with the `%s` specifier giving textual output, \"true\" or \"false\" + (https://github.com/fmtlib/fmt/pull/223): + + ```c++ + fmt::printf("%s", true); // prints "true" + ``` + + Thanks @LarsGullik. + +- \[Breaking\] `signed char` and `unsigned char` are now formatted as + integers by default + (https://github.com/fmtlib/fmt/pull/217). + +- \[Breaking\] Pointers to C strings can now be formatted with the `p` + specifier (https://github.com/fmtlib/fmt/pull/223): + + ```c++ + fmt::print("{:p}", "test"); // prints pointer value + ``` + + Thanks @LarsGullik. + +- \[Breaking\] `fmt::printf` and `fmt::sprintf` now print null + pointers as `(nil)` and null strings as `(null)` for consistency + with glibc (https://github.com/fmtlib/fmt/pull/226). + Thanks @LarsGullik. + +- \[Breaking\] `fmt::(s)printf` now supports formatting of objects of + user-defined types that provide an overloaded `std::ostream` + insertion operator (`operator<<`) + (https://github.com/fmtlib/fmt/issues/201): + + ```c++ + fmt::printf("The date is %s", Date(2012, 12, 9)); + ``` + +- \[Breaking\] The `Buffer` template is now part of the public API and + can be used to implement custom memory buffers + (https://github.com/fmtlib/fmt/issues/140). Thanks @polyvertex. + +- \[Breaking\] Improved compatibility between `BasicStringRef` and + [std::experimental::basic_string_view]( + http://en.cppreference.com/w/cpp/experimental/basic_string_view) + (https://github.com/fmtlib/fmt/issues/100, + https://github.com/fmtlib/fmt/issues/159, + https://github.com/fmtlib/fmt/issues/183): + + - Comparison operators now compare string content, not pointers + - `BasicStringRef::c_str` replaced by `BasicStringRef::data` + - `BasicStringRef` is no longer assumed to be null-terminated + + References to null-terminated strings are now represented by a new + class, `BasicCStringRef`. + +- Dependency on pthreads introduced by Google Test is now optional + (https://github.com/fmtlib/fmt/issues/185). + +- New CMake options `FMT_DOC`, `FMT_INSTALL` and `FMT_TEST` to control + generation of `doc`, `install` and `test` targets respectively, on + by default (https://github.com/fmtlib/fmt/issues/197, + https://github.com/fmtlib/fmt/issues/198, + https://github.com/fmtlib/fmt/issues/200). Thanks @maddinat0r. + +- `noexcept` is now used when compiling with MSVC2015 + (https://github.com/fmtlib/fmt/pull/215). Thanks @dmkrepo. + +- Added an option to disable use of `windows.h` when + `FMT_USE_WINDOWS_H` is defined as 0 before including `format.h` + (https://github.com/fmtlib/fmt/issues/171). Thanks @alfps. + +- \[Breaking\] `windows.h` is now included with `NOMINMAX` unless + `FMT_WIN_MINMAX` is defined. This is done to prevent breaking code + using `std::min` and `std::max` and only affects the header-only + configuration (https://github.com/fmtlib/fmt/issues/152, + https://github.com/fmtlib/fmt/pull/153, + https://github.com/fmtlib/fmt/pull/154). Thanks @DevO2012. + +- Improved support for custom character types + (https://github.com/fmtlib/fmt/issues/171). Thanks @alfps. + +- Added an option to disable use of IOStreams when `FMT_USE_IOSTREAMS` + is defined as 0 before including `format.h` + (https://github.com/fmtlib/fmt/issues/205, + https://github.com/fmtlib/fmt/pull/208). Thanks @JodiTheTigger. + +- Improved detection of `isnan`, `isinf` and `signbit`. + +## Optimization + +- Made formatting of user-defined types more efficient with a custom + stream buffer (https://github.com/fmtlib/fmt/issues/92, + https://github.com/fmtlib/fmt/pull/230). Thanks @NotImplemented. +- Further improved performance of `fmt::Writer` on integer formatting + and fixed a minor regression. Now it is \~7% faster than + `karma::generate` on Karma\'s benchmark + (https://github.com/fmtlib/fmt/issues/186). +- \[Breaking\] Reduced [compiled code + size](https://github.com/fmtlib/fmt#compile-time-and-code-bloat) + (https://github.com/fmtlib/fmt/issues/143, + https://github.com/fmtlib/fmt/pull/149). + +## Distribution + +- \[Breaking\] Headers are now installed in + `${CMAKE_INSTALL_PREFIX}/include/cppformat` + (https://github.com/fmtlib/fmt/issues/178). Thanks @jackyf. + +- \[Breaking\] Changed the library name from `format` to `cppformat` + for consistency with the project name and to avoid potential + conflicts (https://github.com/fmtlib/fmt/issues/178). + Thanks @jackyf. + +- C++ Format is now available in [Debian](https://www.debian.org/) + GNU/Linux + ([stretch](https://packages.debian.org/source/stretch/cppformat), + [sid](https://packages.debian.org/source/sid/cppformat)) and derived + distributions such as + [Ubuntu](https://launchpad.net/ubuntu/+source/cppformat) 15.10 and + later (https://github.com/fmtlib/fmt/issues/155): + + $ sudo apt-get install libcppformat1-dev + + Thanks @jackyf. + +- [Packages for Fedora and + RHEL](https://admin.fedoraproject.org/pkgdb/package/cppformat/) are + now available. Thanks Dave Johansen. + +- C++ Format can now be installed via [Homebrew](http://brew.sh/) on + OS X (https://github.com/fmtlib/fmt/issues/157): + + $ brew install cppformat + + Thanks @ortho and Anatoliy Bulukin. + +## Documentation + +- Migrated from ReadTheDocs to GitHub Pages for better responsiveness + and reliability (https://github.com/fmtlib/fmt/issues/128). + New documentation address is . +- Added [Building thedocumentation]( + https://fmt.dev/2.0.0/usage.html#building-the-documentation) + section to the documentation. +- Documentation build script is now compatible with Python 3 and newer + pip versions. (https://github.com/fmtlib/fmt/pull/189, + https://github.com/fmtlib/fmt/issues/209). + Thanks @JodiTheTigger and @xentec. +- Documentation fixes and improvements + (https://github.com/fmtlib/fmt/issues/36, + https://github.com/fmtlib/fmt/issues/75, + https://github.com/fmtlib/fmt/issues/125, + https://github.com/fmtlib/fmt/pull/160, + https://github.com/fmtlib/fmt/pull/161, + https://github.com/fmtlib/fmt/issues/162, + https://github.com/fmtlib/fmt/issues/165, + https://github.com/fmtlib/fmt/issues/210). + Thanks @syohex. +- Fixed out-of-tree documentation build + (https://github.com/fmtlib/fmt/issues/177). Thanks @jackyf. + +## Fixes + +- Fixed `initializer_list` detection + (https://github.com/fmtlib/fmt/issues/136). Thanks @Gachapen. + +- \[Breaking\] Fixed formatting of enums with numeric format + specifiers in `fmt::(s)printf` + (https://github.com/fmtlib/fmt/issues/131, + https://github.com/fmtlib/fmt/issues/139): + + ```c++ + enum { ANSWER = 42 }; + fmt::printf("%d", ANSWER); + ``` + + Thanks @Naios. + +- Improved compatibility with old versions of MinGW + (https://github.com/fmtlib/fmt/issues/129, + https://github.com/fmtlib/fmt/pull/130, + https://github.com/fmtlib/fmt/issues/132). Thanks @cstamford. + +- Fixed a compile error on MSVC with disabled exceptions + (https://github.com/fmtlib/fmt/issues/144). + +- Added a workaround for broken implementation of variadic templates + in MSVC2012 (https://github.com/fmtlib/fmt/issues/148). + +- Placed the anonymous namespace within `fmt` namespace for the + header-only configuration (https://github.com/fmtlib/fmt/issues/171). + Thanks @alfps. + +- Fixed issues reported by Coverity Scan + (https://github.com/fmtlib/fmt/issues/187, + https://github.com/fmtlib/fmt/issues/192). + +- Implemented a workaround for a name lookup bug in MSVC2010 + (https://github.com/fmtlib/fmt/issues/188). + +- Fixed compiler warnings + (https://github.com/fmtlib/fmt/issues/95, + https://github.com/fmtlib/fmt/issues/96, + https://github.com/fmtlib/fmt/pull/114, + https://github.com/fmtlib/fmt/issues/135, + https://github.com/fmtlib/fmt/issues/142, + https://github.com/fmtlib/fmt/issues/145, + https://github.com/fmtlib/fmt/issues/146, + https://github.com/fmtlib/fmt/issues/158, + https://github.com/fmtlib/fmt/issues/163, + https://github.com/fmtlib/fmt/issues/175, + https://github.com/fmtlib/fmt/issues/190, + https://github.com/fmtlib/fmt/pull/191, + https://github.com/fmtlib/fmt/issues/194, + https://github.com/fmtlib/fmt/pull/196, + https://github.com/fmtlib/fmt/issues/216, + https://github.com/fmtlib/fmt/pull/218, + https://github.com/fmtlib/fmt/pull/220, + https://github.com/fmtlib/fmt/pull/229, + https://github.com/fmtlib/fmt/issues/233, + https://github.com/fmtlib/fmt/issues/234, + https://github.com/fmtlib/fmt/pull/236, + https://github.com/fmtlib/fmt/issues/281, + https://github.com/fmtlib/fmt/issues/289). + Thanks @seanmiddleditch, @dixlorenz, @CarterLi, @Naios, @fmatthew5876, + @LevskiWeng, @rpopescu, @gabime, @cubicool, @jkflying, @LogicalKnight, + @inguin and @Jopie64. + +- Fixed portability issues (mostly causing test failures) on ARM, + ppc64, ppc64le, s390x and SunOS 5.11 i386 + (https://github.com/fmtlib/fmt/issues/138, + https://github.com/fmtlib/fmt/issues/179, + https://github.com/fmtlib/fmt/issues/180, + https://github.com/fmtlib/fmt/issues/202, + https://github.com/fmtlib/fmt/issues/225, [Red Hat Bugzilla + Bug 1260297](https://bugzilla.redhat.com/show_bug.cgi?id=1260297)). + Thanks @Naios, @jackyf and Dave Johansen. + +- Fixed a name conflict with macro `free` defined in `crtdbg.h` when + `_CRTDBG_MAP_ALLOC` is set (https://github.com/fmtlib/fmt/issues/211). + +- Fixed shared library build on OS X + (https://github.com/fmtlib/fmt/pull/212). Thanks @dean0x7d. + +- Fixed an overload conflict on MSVC when `/Zc:wchar_t-` option is + specified (https://github.com/fmtlib/fmt/pull/214). + Thanks @slavanap. + +- Improved compatibility with MSVC 2008 + (https://github.com/fmtlib/fmt/pull/236). Thanks @Jopie64. + +- Improved compatibility with bcc32 + (https://github.com/fmtlib/fmt/issues/227). + +- Fixed `static_assert` detection on Clang + (https://github.com/fmtlib/fmt/pull/228). Thanks @dean0x7d. + +# 1.1.0 - 2015-03-06 + +- Added `BasicArrayWriter`, a class template that provides operations + for formatting and writing data into a fixed-size array + (https://github.com/fmtlib/fmt/issues/105 and + https://github.com/fmtlib/fmt/issues/122): + + ```c++ + char buffer[100]; + fmt::ArrayWriter w(buffer); + w.write("The answer is {}", 42); + ``` + +- Added [0 A.D.](http://play0ad.com/) and [PenUltima Online + (POL)](http://www.polserver.com/) to the list of notable projects + using C++ Format. + +- C++ Format now uses MSVC intrinsics for better formatting performance + (https://github.com/fmtlib/fmt/pull/115, + https://github.com/fmtlib/fmt/pull/116, + https://github.com/fmtlib/fmt/pull/118 and + https://github.com/fmtlib/fmt/pull/121). Previously these + optimizations where only used on GCC and Clang. + Thanks @CarterLi and @objectx. + +- CMake install target + (https://github.com/fmtlib/fmt/pull/119). Thanks @TrentHouliston. + + You can now install C++ Format with `make install` command. + +- Improved [Biicode](http://www.biicode.com/) support + (https://github.com/fmtlib/fmt/pull/98 and + https://github.com/fmtlib/fmt/pull/104). + Thanks @MariadeAnton and @franramirez688. + +- Improved support for building with [Android NDK]( + https://developer.android.com/tools/sdk/ndk/index.html) + (https://github.com/fmtlib/fmt/pull/107). Thanks @newnon. + + The [android-ndk-example](https://github.com/fmtlib/android-ndk-example) + repository provides and example of using C++ Format with Android NDK: + + ![](https://raw.githubusercontent.com/fmtlib/android-ndk-example/master/screenshot.png) + +- Improved documentation of `SystemError` and `WindowsError` + (https://github.com/fmtlib/fmt/issues/54). + +- Various code improvements + (https://github.com/fmtlib/fmt/pull/110, + https://github.com/fmtlib/fmt/pull/111 + https://github.com/fmtlib/fmt/pull/112). Thanks @CarterLi. + +- Improved compile-time errors when formatting wide into narrow + strings (https://github.com/fmtlib/fmt/issues/117). + +- Fixed `BasicWriter::write` without formatting arguments when C++11 + support is disabled + (https://github.com/fmtlib/fmt/issues/109). + +- Fixed header-only build on OS X with GCC 4.9 + (https://github.com/fmtlib/fmt/issues/124). + +- Fixed packaging issues (https://github.com/fmtlib/fmt/issues/94). + +- Added [changelog](https://github.com/fmtlib/fmt/blob/master/ChangeLog.md) + (https://github.com/fmtlib/fmt/issues/103). + +# 1.0.0 - 2015-02-05 + +- Add support for a header-only configuration when `FMT_HEADER_ONLY` + is defined before including `format.h`: + + ```c++ + #define FMT_HEADER_ONLY + #include "format.h" + ``` + +- Compute string length in the constructor of `BasicStringRef` instead + of the `size` method + (https://github.com/fmtlib/fmt/issues/79). This eliminates + size computation for string literals on reasonable optimizing + compilers. + +- Fix formatting of types with overloaded `operator <<` for + `std::wostream` (https://github.com/fmtlib/fmt/issues/86): + + ```c++ + fmt::format(L"The date is {0}", Date(2012, 12, 9)); + ``` + +- Fix linkage of tests on Arch Linux + (https://github.com/fmtlib/fmt/issues/89). + +- Allow precision specifier for non-float arguments + (https://github.com/fmtlib/fmt/issues/90): + + ```c++ + fmt::print("{:.3}\n", "Carpet"); // prints "Car" + ``` + +- Fix build on Android NDK (https://github.com/fmtlib/fmt/issues/93). + +- Improvements to documentation build procedure. + +- Remove `FMT_SHARED` CMake variable in favor of standard [BUILD_SHARED_LIBS]( + http://www.cmake.org/cmake/help/v3.0/variable/BUILD_SHARED_LIBS.html). + +- Fix error handling in `fmt::fprintf`. + +- Fix a number of warnings. + +# 0.12.0 - 2014-10-25 + +- \[Breaking\] Improved separation between formatting and buffer + management. `Writer` is now a base class that cannot be instantiated + directly. The new `MemoryWriter` class implements the default buffer + management with small allocations done on stack. So `fmt::Writer` + should be replaced with `fmt::MemoryWriter` in variable + declarations. + + Old code: + + ```c++ + fmt::Writer w; + ``` + + New code: + + ```c++ + fmt::MemoryWriter w; + ``` + + If you pass `fmt::Writer` by reference, you can continue to do so: + + ```c++ + void f(fmt::Writer &w); + ``` + + This doesn\'t affect the formatting API. + +- Support for custom memory allocators + (https://github.com/fmtlib/fmt/issues/69) + +- Formatting functions now accept [signed char]{.title-ref} and + [unsigned char]{.title-ref} strings as arguments + (https://github.com/fmtlib/fmt/issues/73): + + ```c++ + auto s = format("GLSL version: {}", glGetString(GL_VERSION)); + ``` + +- Reduced code bloat. According to the new [benchmark + results](https://github.com/fmtlib/fmt#compile-time-and-code-bloat), + cppformat is close to `printf` and by the order of magnitude better + than Boost Format in terms of compiled code size. + +- Improved appearance of the documentation on mobile by using the + [Sphinx Bootstrap + theme](http://ryan-roemer.github.io/sphinx-bootstrap-theme/): + + | Old | New | + | --- | --- | + | ![](https://cloud.githubusercontent.com/assets/576385/4792130/cd256436-5de3-11e4-9a62-c077d0c2b003.png) | ![](https://cloud.githubusercontent.com/assets/576385/4792131/cd29896c-5de3-11e4-8f59-cac952942bf0.png) | + +# 0.11.0 - 2014-08-21 + +- Safe printf implementation with a POSIX extension for positional + arguments: + + ```c++ + fmt::printf("Elapsed time: %.2f seconds", 1.23); + fmt::printf("%1$s, %3$d %2$s", weekday, month, day); + ``` + +- Arguments of `char` type can now be formatted as integers (Issue + https://github.com/fmtlib/fmt/issues/55): + + ```c++ + fmt::format("0x{0:02X}", 'a'); + ``` + +- Deprecated parts of the API removed. + +- The library is now built and tested on MinGW with Appveyor in + addition to existing test platforms Linux/GCC, OS X/Clang, + Windows/MSVC. + +# 0.10.0 - 2014-07-01 + +**Improved API** + +- All formatting methods are now implemented as variadic functions + instead of using `operator<<` for feeding arbitrary arguments into a + temporary formatter object. This works both with C++11 where + variadic templates are used and with older standards where variadic + functions are emulated by providing lightweight wrapper functions + defined with the `FMT_VARIADIC` macro. You can use this macro for + defining your own portable variadic functions: + + ```c++ + void report_error(const char *format, const fmt::ArgList &args) { + fmt::print("Error: {}"); + fmt::print(format, args); + } + FMT_VARIADIC(void, report_error, const char *) + + report_error("file not found: {}", path); + ``` + + Apart from a more natural syntax, this also improves performance as + there is no need to construct temporary formatter objects and + control arguments\' lifetimes. Because the wrapper functions are + very lightweight, this doesn\'t cause code bloat even in pre-C++11 + mode. + +- Simplified common case of formatting an `std::string`. Now it + requires a single function call: + + ```c++ + std::string s = format("The answer is {}.", 42); + ``` + + Previously it required 2 function calls: + + ```c++ + std::string s = str(Format("The answer is {}.") << 42); + ``` + + Instead of unsafe `c_str` function, `fmt::Writer` should be used + directly to bypass creation of `std::string`: + + ```c++ + fmt::Writer w; + w.write("The answer is {}.", 42); + w.c_str(); // returns a C string + ``` + + This doesn\'t do dynamic memory allocation for small strings and is + less error prone as the lifetime of the string is the same as for + `std::string::c_str` which is well understood (hopefully). + +- Improved consistency in naming functions that are a part of the + public API. Now all public functions are lowercase following the + standard library conventions. Previously it was a combination of + lowercase and CapitalizedWords. Issue + https://github.com/fmtlib/fmt/issues/50. + +- Old functions are marked as deprecated and will be removed in the + next release. + +**Other Changes** + +- Experimental support for printf format specifications (work in + progress): + + ```c++ + fmt::printf("The answer is %d.", 42); + std::string s = fmt::sprintf("Look, a %s!", "string"); + ``` + +- Support for hexadecimal floating point format specifiers `a` and + `A`: + + ```c++ + print("{:a}", -42.0); // Prints -0x1.5p+5 + print("{:A}", -42.0); // Prints -0X1.5P+5 + ``` + +- CMake option `FMT_SHARED` that specifies whether to build format as + a shared library (off by default). + +# 0.9.0 - 2014-05-13 + +- More efficient implementation of variadic formatting functions. + +- `Writer::Format` now has a variadic overload: + + ```c++ + Writer out; + out.Format("Look, I'm {}!", "variadic"); + ``` + +- For efficiency and consistency with other overloads, variadic + overload of the `Format` function now returns `Writer` instead of + `std::string`. Use the `str` function to convert it to + `std::string`: + + ```c++ + std::string s = str(Format("Look, I'm {}!", "variadic")); + ``` + +- Replaced formatter actions with output sinks: `NoAction` -\> + `NullSink`, `Write` -\> `FileSink`, `ColorWriter` -\> + `ANSITerminalSink`. This improves naming consistency and shouldn\'t + affect client code unless these classes are used directly which + should be rarely needed. + +- Added `ThrowSystemError` function that formats a message and throws + `SystemError` containing the formatted message and system-specific + error description. For example, the following code + + ```c++ + FILE *f = fopen(filename, "r"); + if (!f) + ThrowSystemError(errno, "Failed to open file '{}'") << filename; + ``` + + will throw `SystemError` exception with description \"Failed to open + file \'\\': No such file or directory\" if file doesn\'t + exist. + +- Support for AppVeyor continuous integration platform. + +- `Format` now throws `SystemError` in case of I/O errors. + +- Improve test infrastructure. Print functions are now tested by + redirecting the output to a pipe. + +# 0.8.0 - 2014-04-14 + +- Initial release diff --git a/third_party/fmt/LICENSE b/third_party/fmt/LICENSE new file mode 100644 index 0000000..1cd1ef9 --- /dev/null +++ b/third_party/fmt/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors + +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/third_party/fmt/README.md b/third_party/fmt/README.md new file mode 100644 index 0000000..dcfb16e --- /dev/null +++ b/third_party/fmt/README.md @@ -0,0 +1,490 @@ +{fmt} + +[![image](https://github.com/fmtlib/fmt/workflows/linux/badge.svg)](https://github.com/fmtlib/fmt/actions?query=workflow%3Alinux) +[![image](https://github.com/fmtlib/fmt/workflows/macos/badge.svg)](https://github.com/fmtlib/fmt/actions?query=workflow%3Amacos) +[![image](https://github.com/fmtlib/fmt/workflows/windows/badge.svg)](https://github.com/fmtlib/fmt/actions?query=workflow%3Awindows) +[![fmt is continuously fuzzed at oss-fuzz](https://oss-fuzz-build-logs.storage.googleapis.com/badges/fmt.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?\%0Acolspec=ID%20Type%20Component%20Status%20Proj%20Reported%20Owner%20\%0ASummary&q=proj%3Dfmt&can=1) +[![Ask questions at StackOverflow with the tag fmt](https://img.shields.io/badge/stackoverflow-fmt-blue.svg)](https://stackoverflow.com/questions/tagged/fmt) +[![image](https://api.securityscorecards.dev/projects/github.com/fmtlib/fmt/badge)](https://securityscorecards.dev/viewer/?uri=github.com/fmtlib/fmt) + +**{fmt}** is an open-source formatting library providing a fast and safe +alternative to C stdio and C++ iostreams. + +If you like this project, please consider donating to one of the funds +that help victims of the war in Ukraine: . + +[Documentation](https://fmt.dev) + +[Cheat Sheets](https://hackingcpp.com/cpp/libs/fmt.html) + +Q&A: ask questions on [StackOverflow with the tag +fmt](https://stackoverflow.com/questions/tagged/fmt). + +Try {fmt} in [Compiler Explorer](https://godbolt.org/z/Eq5763). + +# Features + +- Simple [format API](https://fmt.dev/latest/api.html) with positional + arguments for localization +- Implementation of [C++20 + std::format](https://en.cppreference.com/w/cpp/utility/format) and + [C++23 std::print](https://en.cppreference.com/w/cpp/io/print) +- [Format string syntax](https://fmt.dev/latest/syntax.html) similar + to Python\'s + [format](https://docs.python.org/3/library/stdtypes.html#str.format) +- Fast IEEE 754 floating-point formatter with correct rounding, + shortness and round-trip guarantees using the + [Dragonbox](https://github.com/jk-jeon/dragonbox) algorithm +- Portable Unicode support +- Safe [printf + implementation](https://fmt.dev/latest/api.html#printf-formatting) + including the POSIX extension for positional arguments +- Extensibility: [support for user-defined + types](https://fmt.dev/latest/api.html#formatting-user-defined-types) +- High performance: faster than common standard library + implementations of `(s)printf`, iostreams, `to_string` and + `to_chars`, see [Speed tests](#speed-tests) and [Converting a + hundred million integers to strings per + second](http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html) +- Small code size both in terms of source code with the minimum + configuration consisting of just three files, `core.h`, `format.h` + and `format-inl.h`, and compiled code; see [Compile time and code + bloat](#compile-time-and-code-bloat) +- Reliability: the library has an extensive set of + [tests](https://github.com/fmtlib/fmt/tree/master/test) and is + [continuously fuzzed](https://bugs.chromium.org/p/oss-fuzz/issues/list?colspec=ID%20Type%20Component%20Status%20Proj%20Reported%20Owner%20Summary&q=proj%3Dfmt&can=1) +- Safety: the library is fully type-safe, errors in format strings can + be reported at compile time, automatic memory management prevents + buffer overflow errors +- Ease of use: small self-contained code base, no external + dependencies, permissive MIT + [license](https://github.com/fmtlib/fmt/blob/master/LICENSE.rst) +- [Portability](https://fmt.dev/latest/index.html#portability) with + consistent output across platforms and support for older compilers +- Clean warning-free codebase even on high warning levels such as + `-Wall -Wextra -pedantic` +- Locale independence by default +- Optional header-only configuration enabled with the + `FMT_HEADER_ONLY` macro + +See the [documentation](https://fmt.dev) for more details. + +# Examples + +**Print to stdout** ([run](https://godbolt.org/z/Tevcjh)) + +``` c++ +#include + +int main() { + fmt::print("Hello, world!\n"); +} +``` + +**Format a string** ([run](https://godbolt.org/z/oK8h33)) + +``` c++ +std::string s = fmt::format("The answer is {}.", 42); +// s == "The answer is 42." +``` + +**Format a string using positional arguments** +([run](https://godbolt.org/z/Yn7Txe)) + +``` c++ +std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy"); +// s == "I'd rather be happy than right." +``` + +**Print dates and times** ([run](https://godbolt.org/z/c31ExdY3W)) + +``` c++ +#include + +int main() { + auto now = std::chrono::system_clock::now(); + fmt::print("Date and time: {}\n", now); + fmt::print("Time: {:%H:%M}\n", now); +} +``` + +Output: + + Date and time: 2023-12-26 19:10:31.557195597 + Time: 19:10 + +**Print a container** ([run](https://godbolt.org/z/MxM1YqjE7)) + +``` c++ +#include +#include + +int main() { + std::vector v = {1, 2, 3}; + fmt::print("{}\n", v); +} +``` + +Output: + + [1, 2, 3] + +**Check a format string at compile time** + +``` c++ +std::string s = fmt::format("{:d}", "I am not a number"); +``` + +This gives a compile-time error in C++20 because `d` is an invalid +format specifier for a string. + +**Write a file from a single thread** + +``` c++ +#include + +int main() { + auto out = fmt::output_file("guide.txt"); + out.print("Don't {}", "Panic"); +} +``` + +This can be [5 to 9 times faster than +fprintf](http://www.zverovich.net/2020/08/04/optimal-file-buffer-size.html). + +**Print with colors and text styles** + +``` c++ +#include + +int main() { + fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold, + "Hello, {}!\n", "world"); + fmt::print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) | + fmt::emphasis::underline, "Olá, {}!\n", "Mundo"); + fmt::print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, + "你好{}ï¼\n", "世界"); +} +``` + +Output on a modern terminal with Unicode support: + +![image](https://github.com/fmtlib/fmt/assets/%0A576385/2a93c904-d6fa-4aa6-b453-2618e1c327d7) + +# Benchmarks + +## Speed tests + +| Library | Method | Run Time, s | +|-------------------|---------------|-------------| +| libc | printf | 0.91 | +| libc++ | std::ostream | 2.49 | +| {fmt} 9.1 | fmt::print | 0.74 | +| Boost Format 1.80 | boost::format | 6.26 | +| Folly Format | folly::format | 1.87 | + +{fmt} is the fastest of the benchmarked methods, \~20% faster than +`printf`. + +The above results were generated by building `tinyformat_test.cpp` on +macOS 12.6.1 with `clang++ -O3 -DNDEBUG -DSPEED_TEST -DHAVE_FORMAT`, and +taking the best of three runs. In the test, the format string +`"%0.10f:%04d:%+g:%s:%p:%c:%%\n"` or equivalent is filled 2,000,000 +times with output sent to `/dev/null`; for further details refer to the +[source](https://github.com/fmtlib/format-benchmark/blob/master/src/tinyformat-test.cc). + +{fmt} is up to 20-30x faster than `std::ostringstream` and `sprintf` on +IEEE754 `float` and `double` formatting +([dtoa-benchmark](https://github.com/fmtlib/dtoa-benchmark)) and faster +than [double-conversion](https://github.com/google/double-conversion) +and [ryu](https://github.com/ulfjack/ryu): + +[![image](https://user-images.githubusercontent.com/576385/95684665-11719600-0ba8-11eb-8e5b-972ff4e49428.png)](https://fmt.dev/unknown_mac64_clang12.0.html) + +## Compile time and code bloat + +The script +[bloat-test.py](https://github.com/fmtlib/format-benchmark/blob/master/bloat-test.py) +from [format-benchmark](https://github.com/fmtlib/format-benchmark) +tests compile time and code bloat for nontrivial projects. It generates +100 translation units and uses `printf()` or its alternative five times +in each to simulate a medium-sized project. The resulting executable +size and compile time (Apple LLVM version 8.1.0 (clang-802.0.42), macOS +Sierra, best of three) is shown in the following tables. + +**Optimized build (-O3)** + +| Method | Compile Time, s | Executable size, KiB | Stripped size, KiB | +|---------------|-----------------|----------------------|--------------------| +| printf | 2.6 | 29 | 26 | +| printf+string | 16.4 | 29 | 26 | +| iostreams | 31.1 | 59 | 55 | +| {fmt} | 19.0 | 37 | 34 | +| Boost Format | 91.9 | 226 | 203 | +| Folly Format | 115.7 | 101 | 88 | + +As you can see, {fmt} has 60% less overhead in terms of resulting binary +code size compared to iostreams and comes pretty close to `printf`. +Boost Format and Folly Format have the largest overheads. + +`printf+string` is the same as `printf` but with an extra `` +include to measure the overhead of the latter. + +**Non-optimized build** + +| Method | Compile Time, s | Executable size, KiB | Stripped size, KiB | +|---------------|-----------------|----------------------|--------------------| +| printf | 2.2 | 33 | 30 | +| printf+string | 16.0 | 33 | 30 | +| iostreams | 28.3 | 56 | 52 | +| {fmt} | 18.2 | 59 | 50 | +| Boost Format | 54.1 | 365 | 303 | +| Folly Format | 79.9 | 445 | 430 | + +`libc`, `lib(std)c++`, and `libfmt` are all linked as shared libraries +to compare formatting function overhead only. Boost Format is a +header-only library so it doesn\'t provide any linkage options. + +## Running the tests + +Please refer to [Building the +library](https://fmt.dev/latest/usage.html#building-the-library) for +instructions on how to build the library and run the unit tests. + +Benchmarks reside in a separate repository, +[format-benchmarks](https://github.com/fmtlib/format-benchmark), so to +run the benchmarks you first need to clone this repository and generate +Makefiles with CMake: + + $ git clone --recursive https://github.com/fmtlib/format-benchmark.git + $ cd format-benchmark + $ cmake . + +Then you can run the speed test: + + $ make speed-test + +or the bloat test: + + $ make bloat-test + +# Migrating code + +[clang-tidy](https://clang.llvm.org/extra/clang-tidy/) v17 (not yet +released) provides the +[modernize-use-std-print](https://clang.llvm.org/extra/clang-tidy/checks/modernize/use-std-print.html) +check that is capable of converting occurrences of `printf` and +`fprintf` to `fmt::print` if configured to do so. (By default it +converts to `std::print`.) + +# Notable projects using this library + +- [0 A.D.](https://play0ad.com/): a free, open-source, cross-platform + real-time strategy game +- [AMPL/MP](https://github.com/ampl/mp): an open-source library for + mathematical programming +- [Apple's FoundationDB](https://github.com/apple/foundationdb): an open-source, + distributed, transactional key-value store +- [Aseprite](https://github.com/aseprite/aseprite): animated sprite + editor & pixel art tool +- [AvioBook](https://www.aviobook.aero/en): a comprehensive aircraft + operations suite +- [Blizzard Battle.net](https://battle.net/): an online gaming + platform +- [Celestia](https://celestia.space/): real-time 3D visualization of + space +- [Ceph](https://ceph.com/): a scalable distributed storage system +- [ccache](https://ccache.dev/): a compiler cache +- [ClickHouse](https://github.com/ClickHouse/ClickHouse): an + analytical database management system +- [Contour](https://github.com/contour-terminal/contour/): a modern + terminal emulator +- [CUAUV](https://cuauv.org/): Cornell University\'s autonomous + underwater vehicle +- [Drake](https://drake.mit.edu/): a planning, control, and analysis + toolbox for nonlinear dynamical systems (MIT) +- [Envoy](https://lyft.github.io/envoy/): C++ L7 proxy and + communication bus (Lyft) +- [FiveM](https://fivem.net/): a modification framework for GTA V +- [fmtlog](https://github.com/MengRao/fmtlog): a performant + fmtlib-style logging library with latency in nanoseconds +- [Folly](https://github.com/facebook/folly): Facebook open-source + library +- [GemRB](https://gemrb.org/): a portable open-source implementation + of Bioware's Infinity Engine +- [Grand Mountain + Adventure](https://store.steampowered.com/app/1247360/Grand_Mountain_Adventure/): + a beautiful open-world ski & snowboarding game +- [HarpyWar/pvpgn](https://github.com/pvpgn/pvpgn-server): Player vs + Player Gaming Network with tweaks +- [KBEngine](https://github.com/kbengine/kbengine): an open-source + MMOG server engine +- [Keypirinha](https://keypirinha.com/): a semantic launcher for + Windows +- [Kodi](https://kodi.tv/) (formerly xbmc): home theater software +- [Knuth](https://kth.cash/): high-performance Bitcoin full-node +- [libunicode](https://github.com/contour-terminal/libunicode/): a + modern C++17 Unicode library +- [MariaDB](https://mariadb.org/): relational database management + system +- [Microsoft Verona](https://github.com/microsoft/verona): research + programming language for concurrent ownership +- [MongoDB](https://mongodb.com/): distributed document database +- [MongoDB Smasher](https://github.com/duckie/mongo_smasher): a small + tool to generate randomized datasets +- [OpenSpace](https://openspaceproject.com/): an open-source + astrovisualization framework +- [PenUltima Online (POL)](https://www.polserver.com/): an MMO server, + compatible with most Ultima Online clients +- [PyTorch](https://github.com/pytorch/pytorch): an open-source + machine learning library +- [quasardb](https://www.quasardb.net/): a distributed, + high-performance, associative database +- [Quill](https://github.com/odygrd/quill): asynchronous low-latency + logging library +- [QKW](https://github.com/ravijanjam/qkw): generalizing aliasing to + simplify navigation, and executing complex multi-line terminal + command sequences +- [redis-cerberus](https://github.com/HunanTV/redis-cerberus): a Redis + cluster proxy +- [redpanda](https://vectorized.io/redpanda): a 10x faster Kafka® + replacement for mission-critical systems written in C++ +- [rpclib](http://rpclib.net/): a modern C++ msgpack-RPC server and + client library +- [Salesforce Analytics + Cloud](https://www.salesforce.com/analytics-cloud/overview/): + business intelligence software +- [Scylla](https://www.scylladb.com/): a Cassandra-compatible NoSQL + data store that can handle 1 million transactions per second on a + single server +- [Seastar](http://www.seastar-project.org/): an advanced, open-source + C++ framework for high-performance server applications on modern + hardware +- [spdlog](https://github.com/gabime/spdlog): super fast C++ logging + library +- [Stellar](https://www.stellar.org/): financial platform +- [Touch Surgery](https://www.touchsurgery.com/): surgery simulator +- [TrinityCore](https://github.com/TrinityCore/TrinityCore): + open-source MMORPG framework +- [🙠userver framework](https://userver.tech/): open-source + asynchronous framework with a rich set of abstractions and database + drivers +- [Windows Terminal](https://github.com/microsoft/terminal): the new + Windows terminal + +[More\...](https://github.com/search?q=fmtlib&type=Code) + +If you are aware of other projects using this library, please let me +know by [email](mailto:victor.zverovich@gmail.com) or by submitting an +[issue](https://github.com/fmtlib/fmt/issues). + +# Motivation + +So why yet another formatting library? + +There are plenty of methods for doing this task, from standard ones like +the printf family of function and iostreams to Boost Format and +FastFormat libraries. The reason for creating a new library is that +every existing solution that I found either had serious issues or +didn\'t provide all the features I needed. + +## printf + +The good thing about `printf` is that it is pretty fast and readily +available being a part of the C standard library. The main drawback is +that it doesn\'t support user-defined types. `printf` also has safety +issues although they are somewhat mitigated with [\_\_attribute\_\_ +((format (printf, +\...))](https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html) in +GCC. There is a POSIX extension that adds positional arguments required +for +[i18n](https://en.wikipedia.org/wiki/Internationalization_and_localization) +to `printf` but it is not a part of C99 and may not be available on some +platforms. + +## iostreams + +The main issue with iostreams is best illustrated with an example: + +``` c++ +std::cout << std::setprecision(2) << std::fixed << 1.23456 << "\n"; +``` + +which is a lot of typing compared to printf: + +``` c++ +printf("%.2f\n", 1.23456); +``` + +Matthew Wilson, the author of FastFormat, called this \"chevron hell\". +iostreams don\'t support positional arguments by design. + +The good part is that iostreams support user-defined types and are safe +although error handling is awkward. + +## Boost Format + +This is a very powerful library that supports both `printf`-like format +strings and positional arguments. Its main drawback is performance. +According to various benchmarks, it is much slower than other methods +considered here. Boost Format also has excessive build times and severe +code bloat issues (see [Benchmarks](#benchmarks)). + +## FastFormat + +This is an interesting library that is fast, safe, and has positional +arguments. However, it has significant limitations, citing its author: + +> Three features that have no hope of being accommodated within the +> current design are: +> +> - Leading zeros (or any other non-space padding) +> - Octal/hexadecimal encoding +> - Runtime width/alignment specification + +It is also quite big and has a heavy dependency, STLSoft, which might be +too restrictive for using it in some projects. + +## Boost Spirit.Karma + +This is not a formatting library but I decided to include it here for +completeness. As iostreams, it suffers from the problem of mixing +verbatim text with arguments. The library is pretty fast, but slower on +integer formatting than `fmt::format_to` with format string compilation +on Karma\'s own benchmark, see [Converting a hundred million integers to +strings per +second](http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html). + +# License + +{fmt} is distributed under the MIT +[license](https://github.com/fmtlib/fmt/blob/master/LICENSE). + +# Documentation License + +The [Format String Syntax](https://fmt.dev/latest/syntax.html) section +in the documentation is based on the one from Python [string module +documentation](https://docs.python.org/3/library/string.html#module-string). +For this reason, the documentation is distributed under the Python +Software Foundation license available in +[doc/python-license.txt](https://raw.github.com/fmtlib/fmt/master/doc/python-license.txt). +It only applies if you distribute the documentation of {fmt}. + +# Maintainers + +The {fmt} library is maintained by Victor Zverovich +([vitaut](https://github.com/vitaut)) with contributions from many other +people. See +[Contributors](https://github.com/fmtlib/fmt/graphs/contributors) and +[Releases](https://github.com/fmtlib/fmt/releases) for some of the +names. Let us know if your contribution is not listed or mentioned +incorrectly and we\'ll make it right. + +# Security Policy + +To report a security issue, please disclose it at [security +advisory](https://github.com/fmtlib/fmt/security/advisories/new). + +This project is maintained by a team of volunteers on a +reasonable-effort basis. As such, please give us at least 90 days to +work on a fix before public exposure. diff --git a/third_party/fmt/include/fmt/args.h b/third_party/fmt/include/fmt/args.h new file mode 100644 index 0000000..ad1654b --- /dev/null +++ b/third_party/fmt/include/fmt/args.h @@ -0,0 +1,235 @@ +// Formatting library for C++ - dynamic argument lists +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_ARGS_H_ +#define FMT_ARGS_H_ + +#include // std::reference_wrapper +#include // std::unique_ptr +#include + +#include "core.h" + +FMT_BEGIN_NAMESPACE + +namespace detail { + +template struct is_reference_wrapper : std::false_type {}; +template +struct is_reference_wrapper> : std::true_type {}; + +template auto unwrap(const T& v) -> const T& { return v; } +template +auto unwrap(const std::reference_wrapper& v) -> const T& { + return static_cast(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 struct node { + virtual ~node() = default; + std::unique_ptr> next; + }; + + template struct typed_node : node<> { + T value; + + template + FMT_CONSTEXPR typed_node(const Arg& arg) : value(arg) {} + + template + FMT_CONSTEXPR typed_node(const basic_string_view& arg) + : value(arg.data(), arg.size()) {} + }; + + std::unique_ptr> head_; + + public: + template auto push(const Arg& arg) -> const T& { + auto new_node = std::unique_ptr>(new typed_node(arg)); + auto& value = new_node->value; + new_node->next = std::move(head_); + head_ = std::move(new_node); + return value; + } +}; +} // namespace detail + +/** + \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 +class dynamic_format_arg_store +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 + // Workaround a GCC template argument substitution bug. + : public basic_format_args +#endif +{ + private: + using char_type = typename Context::char_type; + + template struct need_copy { + static constexpr detail::type mapped_type = + detail::mapped_type_constant::value; + + enum { + value = !(detail::is_reference_wrapper::value || + std::is_same>::value || + std::is_same>::value || + (mapped_type != detail::type::cstring_type && + mapped_type != detail::type::string_type && + mapped_type != detail::type::custom_type)) + }; + }; + + template + using stored_type = conditional_t< + std::is_convertible>::value && + !detail::is_reference_wrapper::value, + std::basic_string, T>; + + // Storage of basic_format_arg must be contiguous. + std::vector> data_; + std::vector> 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; + + auto get_types() const -> unsigned long long { + return detail::is_unpacked_bit | data_.size() | + (named_info_.empty() + ? 0ULL + : static_cast(detail::has_named_args_bit)); + } + + auto data() const -> const basic_format_arg* { + return named_info_.empty() ? data_.data() : data_.data() + 1; + } + + template void emplace_arg(const T& arg) { + data_.emplace_back(detail::make_arg(arg)); + } + + template + void emplace_arg(const detail::named_arg& arg) { + if (named_info_.empty()) { + constexpr const detail::named_arg_info* zero_ptr{nullptr}; + data_.insert(data_.begin(), {zero_ptr, 0}); + } + data_.emplace_back(detail::make_arg(detail::unwrap(arg.value))); + auto pop_one = [](std::vector>* data) { + data->pop_back(); + }; + std::unique_ptr>, decltype(pop_one)> + guard{&data_, pop_one}; + named_info_.push_back({arg.name, static_cast(data_.size() - 2u)}); + data_[0].value_.named_args = {named_info_.data(), named_info_.size()}; + guard.release(); + } + + public: + constexpr dynamic_format_arg_store() = default; + + /** + \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 store; + store.push_back(42); + store.push_back("abc"); + store.push_back(1.5f); + std::string result = fmt::vformat("{} and {} and {}", store); + \endrst + */ + template void push_back(const T& arg) { + if (detail::const_check(need_copy::value)) + emplace_arg(dynamic_args_.push>(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. + + **Example**:: + + fmt::dynamic_format_arg_store store; + char band[] = "Rolling Stones"; + store.push_back(std::cref(band)); + band[9] = 'c'; // Changing str affects the output. + std::string result = fmt::vformat("{}", store); + // result == "Rolling Scones" + \endrst + */ + template void push_back(std::reference_wrapper arg) { + static_assert( + need_copy::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. The name is always copied into the store. + */ + template + void push_back(const detail::named_arg& arg) { + const char_type* arg_name = + dynamic_args_.push>(arg.name).c_str(); + if (detail::const_check(need_copy::value)) { + emplace_arg( + fmt::arg(arg_name, dynamic_args_.push>(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); + } +}; + +FMT_END_NAMESPACE + +#endif // FMT_ARGS_H_ diff --git a/third_party/fmt/include/fmt/chrono.h b/third_party/fmt/include/fmt/chrono.h new file mode 100644 index 0000000..9d54574 --- /dev/null +++ b/third_party/fmt/include/fmt/chrono.h @@ -0,0 +1,2240 @@ +// 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 +#include +#include // std::isfinite +#include // std::memcpy +#include +#include +#include +#include +#include + +#include "ostream.h" // formatbuf + +FMT_BEGIN_NAMESPACE + +// Check if std::chrono::local_t is available. +#ifndef FMT_USE_LOCAL_TIME +# ifdef __cpp_lib_chrono +# define FMT_USE_LOCAL_TIME (__cpp_lib_chrono >= 201907L) +# else +# define FMT_USE_LOCAL_TIME 0 +# endif +#endif + +// Check if std::chrono::utc_timestamp is available. +#ifndef FMT_USE_UTC_TIME +# ifdef __cpp_lib_chrono +# define FMT_USE_UTC_TIME (__cpp_lib_chrono >= 201907L) +# else +# define FMT_USE_UTC_TIME 0 +# endif +#endif + +// Enable tzset. +#ifndef FMT_USE_TZSET +// UWP doesn't provide _tzset. +# if FMT_HAS_INCLUDE("winapifamily.h") +# include +# endif +# if defined(_WIN32) && (!defined(WINAPI_FAMILY) || \ + (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)) +# define FMT_USE_TZSET 1 +# else +# define FMT_USE_TZSET 0 +# endif +#endif + +// 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 ::value && + std::numeric_limits::is_signed == + std::numeric_limits::is_signed)> +FMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec) + -> To { + ec = 0; + using F = std::numeric_limits; + using T = std::numeric_limits; + 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 (detail::const_check(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(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 ::value && + std::numeric_limits::is_signed != + std::numeric_limits::is_signed)> +FMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec) + -> To { + ec = 0; + using F = std::numeric_limits; + using T = std::numeric_limits; + 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 (detail::const_check(F::digits > T::digits) && + from > static_cast(detail::max_value())) { + ec = 1; + return {}; + } + } + + if (detail::const_check(!F::is_signed && T::is_signed && + F::digits >= T::digits) && + from > static_cast(detail::max_value())) { + ec = 1; + return {}; + } + return static_cast(from); // Lossless conversion. +} + +template ::value)> +FMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec) + -> To { + ec = 0; + return from; +} // function + +// clang-format off +/** + * 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 + */ +// clang-format on +template ::value)> +FMT_CONSTEXPR auto safe_float_conversion(const From from, int& ec) -> To { + ec = 0; + using T = std::numeric_limits; + static_assert(std::is_floating_point::value, "From must be floating"); + static_assert(std::is_floating_point::value, "To must be floating"); + + // catch the only happy case + if (std::isfinite(from)) { + if (from >= T::lowest() && from <= (T::max)()) { + return static_cast(from); + } + // not within range. + ec = 1; + return {}; + } + + // nan and inf will be preserved + return static_cast(from); +} // function + +template ::value)> +FMT_CONSTEXPR auto safe_float_conversion(const From from, int& ec) -> To { + ec = 0; + static_assert(std::is_floating_point::value, "From must be floating"); + return from; +} + +/** + * safe duration cast between integral durations + */ +template ::value), + FMT_ENABLE_IF(std::is_integral::value)> +auto safe_duration_cast(std::chrono::duration from, + int& ec) -> To { + using From = std::chrono::duration; + 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 {}; + + 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::type; + + // safe conversion to IntermediateRep + IntermediateRep count = + lossless_integral_conversion(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() / Factor::num; + if (count > max1) { + ec = 1; + return {}; + } + const auto min1 = + (std::numeric_limits::min)() / Factor::num; + if (detail::const_check(!std::is_unsigned::value) && + count < min1) { + ec = 1; + return {}; + } + count *= Factor::num; + } + + if (detail::const_check(Factor::den != 1)) count /= Factor::den; + auto tocount = lossless_integral_conversion(count, ec); + return ec ? To() : To(tocount); +} + +/** + * safe duration_cast between floating point durations + */ +template ::value), + FMT_ENABLE_IF(std::is_floating_point::value)> +auto safe_duration_cast(std::chrono::duration from, + int& ec) -> To { + using From = std::chrono::duration; + ec = 0; + if (std::isnan(from.count())) { + // nan in, gives nan out. easy. + return To{std::numeric_limits::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 {}; + + 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::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(from.count(), ec); + if (ec) { + return {}; + } + + // multiply with Factor::num without overflow or underflow + if (detail::const_check(Factor::num != 1)) { + constexpr auto max1 = detail::max_value() / + static_cast(Factor::num); + if (count > max1) { + ec = 1; + return {}; + } + constexpr auto min1 = std::numeric_limits::lowest() / + static_cast(Factor::num); + if (count < min1) { + ec = 1; + return {}; + } + count *= static_cast(Factor::num); + } + + // this can't go wrong, right? den>0 is checked earlier. + if (detail::const_check(Factor::den != 1)) { + using common_t = typename std::common_type::type; + count /= static_cast(Factor::den); + } + + // convert to the to type, safely + using ToRep = typename To::rep; + + const ToRep tocount = safe_float_conversion(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 { +template struct null {}; +inline auto localtime_r FMT_NOMACRO(...) -> null<> { return null<>(); } +inline auto localtime_s(...) -> null<> { return null<>(); } +inline auto gmtime_r(...) -> null<> { return null<>(); } +inline auto gmtime_s(...) -> null<> { return null<>(); } + +inline auto get_classic_locale() -> const std::locale& { + static const auto& locale = std::locale::classic(); + return locale; +} + +template struct codecvt_result { + static constexpr const size_t max_size = 32; + CodeUnit buf[max_size]; + CodeUnit* end; +}; + +template +void write_codecvt(codecvt_result& out, string_view in_buf, + const std::locale& loc) { +#if FMT_CLANG_VERSION +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wdeprecated" + auto& f = std::use_facet>(loc); +# pragma clang diagnostic pop +#else + auto& f = std::use_facet>(loc); +#endif + auto mb = std::mbstate_t(); + const char* from_next = nullptr; + auto result = f.in(mb, in_buf.begin(), in_buf.end(), from_next, + std::begin(out.buf), std::end(out.buf), out.end); + if (result != std::codecvt_base::ok) + FMT_THROW(format_error("failed to format time")); +} + +template +auto write_encoded_tm_str(OutputIt out, string_view in, const std::locale& loc) + -> OutputIt { + if (detail::is_utf8() && loc != get_classic_locale()) { + // char16_t and char32_t codecvts are broken in MSVC (linkage errors) and + // gcc-4. +#if FMT_MSC_VERSION != 0 || \ + (defined(__GLIBCXX__) && !defined(_GLIBCXX_USE_DUAL_ABI)) + // The _GLIBCXX_USE_DUAL_ABI macro is always defined in libstdc++ from gcc-5 + // and newer. + using code_unit = wchar_t; +#else + using code_unit = char32_t; +#endif + + using unit_t = codecvt_result; + unit_t unit; + write_codecvt(unit, in, loc); + // In UTF-8 is used one to four one-byte code units. + auto u = + to_utf8>(); + if (!u.convert({unit.buf, to_unsigned(unit.end - unit.buf)})) + FMT_THROW(format_error("failed to format time")); + return copy_str(u.c_str(), u.c_str() + u.size(), out); + } + return copy_str(in.data(), in.data() + in.size(), out); +} + +template ::value)> +auto write_tm_str(OutputIt out, string_view sv, const std::locale& loc) + -> OutputIt { + codecvt_result unit; + write_codecvt(unit, sv, loc); + return copy_str(unit.buf, unit.end, out); +} + +template ::value)> +auto write_tm_str(OutputIt out, string_view sv, const std::locale& loc) + -> OutputIt { + return write_encoded_tm_str(out, sv, loc); +} + +template +inline void do_write(buffer& buf, const std::tm& time, + const std::locale& loc, char format, char modifier) { + auto&& format_buf = formatbuf>(buf); + auto&& os = std::basic_ostream(&format_buf); + os.imbue(loc); + const auto& facet = std::use_facet>(loc); + auto end = facet.put(os, os, Char(' '), &time, format, modifier); + if (end.failed()) FMT_THROW(format_error("failed to format time")); +} + +template ::value)> +auto write(OutputIt out, const std::tm& time, const std::locale& loc, + char format, char modifier = 0) -> OutputIt { + auto&& buf = get_buffer(out); + do_write(buf, time, loc, format, modifier); + return get_iterator(buf, out); +} + +template ::value)> +auto write(OutputIt out, const std::tm& time, const std::locale& loc, + char format, char modifier = 0) -> OutputIt { + auto&& buf = basic_memory_buffer(); + do_write(buf, time, loc, format, modifier); + return write_encoded_tm_str(out, string_view(buf.data(), buf.size()), loc); +} + +template +struct is_same_arithmetic_type + : public std::integral_constant::value && + std::is_integral::value) || + (std::is_floating_point::value && + std::is_floating_point::value)> { +}; + +template < + typename To, typename FromRep, typename FromPeriod, + FMT_ENABLE_IF(is_same_arithmetic_type::value)> +auto fmt_duration_cast(std::chrono::duration from) -> To { +#if FMT_SAFE_DURATION_CAST + // Throwing version of safe_duration_cast is only available for + // integer to integer or float to float casts. + int ec; + To to = safe_duration_cast::safe_duration_cast(from, ec); + if (ec) FMT_THROW(format_error("cannot format duration")); + return to; +#else + // Standard duration cast, may overflow. + return std::chrono::duration_cast(from); +#endif +} + +template < + typename To, typename FromRep, typename FromPeriod, + FMT_ENABLE_IF(!is_same_arithmetic_type::value)> +auto fmt_duration_cast(std::chrono::duration from) -> To { + // Mixed integer <-> float cast is not supported by safe_duration_cast. + return std::chrono::duration_cast(from); +} + +template +auto to_time_t( + std::chrono::time_point time_point) + -> std::time_t { + // Cannot use std::chrono::system_clock::to_time_t since this would first + // require a cast to std::chrono::system_clock::time_point, which could + // overflow. + return fmt_duration_cast>( + time_point.time_since_epoch()) + .count(); +} +} // namespace detail + +FMT_BEGIN_EXPORT + +/** + Converts given time since epoch as ``std::time_t`` value into calendar time, + expressed in local time. Unlike ``std::localtime``, this function is + thread-safe on most platforms. + */ +inline auto localtime(std::time_t time) -> std::tm { + struct dispatcher { + std::time_t time_; + std::tm tm_; + + dispatcher(std::time_t t) : time_(t) {} + + auto run() -> bool { + using namespace fmt::detail; + return handle(localtime_r(&time_, &tm_)); + } + + auto handle(std::tm* tm) -> bool { return tm != nullptr; } + + auto handle(detail::null<>) -> bool { + using namespace fmt::detail; + return fallback(localtime_s(&tm_, &time_)); + } + + auto fallback(int res) -> bool { return res == 0; } + +#if !FMT_MSC_VERSION + auto fallback(detail::null<>) -> bool { + 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_; +} + +#if FMT_USE_LOCAL_TIME +template +inline auto localtime(std::chrono::local_time time) -> std::tm { + return localtime( + detail::to_time_t(std::chrono::current_zone()->to_sys(time))); +} +#endif + +/** + Converts given time since epoch as ``std::time_t`` value into calendar time, + expressed in Coordinated Universal Time (UTC). Unlike ``std::gmtime``, this + function is thread-safe on most platforms. + */ +inline auto gmtime(std::time_t time) -> std::tm { + struct dispatcher { + std::time_t time_; + std::tm tm_; + + dispatcher(std::time_t t) : time_(t) {} + + auto run() -> bool { + using namespace fmt::detail; + return handle(gmtime_r(&time_, &tm_)); + } + + auto handle(std::tm* tm) -> bool { return tm != nullptr; } + + auto handle(detail::null<>) -> bool { + using namespace fmt::detail; + return fallback(gmtime_s(&tm_, &time_)); + } + + auto fallback(int res) -> bool { return res == 0; } + +#if !FMT_MSC_VERSION + auto fallback(detail::null<>) -> bool { + std::tm* tm = std::gmtime(&time_); + if (tm) tm_ = *tm; + return tm != nullptr; + } +#endif + }; + auto gt = dispatcher(time); + // Too big time values may be unsupported. + if (!gt.run()) FMT_THROW(format_error("time_t value out of range")); + return gt.tm_; +} + +template +inline auto gmtime( + std::chrono::time_point time_point) + -> std::tm { + return gmtime(detail::to_time_t(time_point)); +} + +namespace detail { + +// Writes two-digit numbers a, b and c separated by sep to buf. +// The method by Pavel Novikov based on +// https://johnnylee-sde.github.io/Fast-unsigned-integer-to-time-string/. +inline void write_digit2_separated(char* buf, unsigned a, unsigned b, + unsigned c, char sep) { + unsigned long long digits = + a | (b << 24) | (static_cast(c) << 48); + // Convert each value to BCD. + // We have x = a * 10 + b and we want to convert it to BCD y = a * 16 + b. + // The difference is + // y - x = a * 6 + // a can be found from x: + // a = floor(x / 10) + // then + // y = x + a * 6 = x + floor(x / 10) * 6 + // floor(x / 10) is (x * 205) >> 11 (needs 16 bits). + digits += (((digits * 205) >> 11) & 0x000f00000f00000f) * 6; + // Put low nibbles to high bytes and high nibbles to low bytes. + digits = ((digits & 0x00f00000f00000f0) >> 4) | + ((digits & 0x000f00000f00000f) << 8); + auto usep = static_cast(sep); + // Add ASCII '0' to each digit byte and insert separators. + digits |= 0x3030003030003030 | (usep << 16) | (usep << 40); + + constexpr const size_t len = 8; + if (const_check(is_big_endian())) { + char tmp[len]; + std::memcpy(tmp, &digits, len); + std::reverse_copy(tmp, tmp + len, buf); + } else { + std::memcpy(buf, &digits, len); + } +} + +template +FMT_CONSTEXPR inline auto get_units() -> const char* { + if (std::is_same::value) return "as"; + if (std::is_same::value) return "fs"; + if (std::is_same::value) return "ps"; + if (std::is_same::value) return "ns"; + if (std::is_same::value) return "µs"; + if (std::is_same::value) return "ms"; + if (std::is_same::value) return "cs"; + if (std::is_same::value) return "ds"; + if (std::is_same>::value) return "s"; + if (std::is_same::value) return "das"; + if (std::is_same::value) return "hs"; + if (std::is_same::value) return "ks"; + if (std::is_same::value) return "Ms"; + if (std::is_same::value) return "Gs"; + if (std::is_same::value) return "Ts"; + if (std::is_same::value) return "Ps"; + if (std::is_same::value) return "Es"; + if (std::is_same>::value) return "min"; + if (std::is_same>::value) return "h"; + if (std::is_same>::value) return "d"; + return nullptr; +} + +enum class numeric_system { + standard, + // Alternative numeric system, e.g. å二 instead of 12 in ja_JP locale. + alternative +}; + +// Glibc extensions for formatting numeric values. +enum class pad_type { + unspecified, + // Do not pad a numeric result string. + none, + // Pad a numeric result string with zeros even if the conversion specifier + // character uses space-padding by default. + zero, + // Pad a numeric result string with spaces. + space, +}; + +template +auto write_padding(OutputIt out, pad_type pad, int width) -> OutputIt { + if (pad == pad_type::none) return out; + return std::fill_n(out, width, pad == pad_type::space ? ' ' : '0'); +} + +template +auto write_padding(OutputIt out, pad_type pad) -> OutputIt { + if (pad != pad_type::none) *out++ = pad == pad_type::space ? ' ' : '0'; + return out; +} + +// Parses a put_time-like format string and invokes handler actions. +template +FMT_CONSTEXPR auto parse_chrono_format(const Char* begin, const Char* end, + Handler&& handler) -> const Char* { + if (begin == end || *begin == '}') return begin; + if (*begin != '%') FMT_THROW(format_error("invalid format")); + auto ptr = begin; + pad_type pad = pad_type::unspecified; + 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 '_': + pad = pad_type::space; + ++ptr; + break; + case '-': + pad = pad_type::none; + ++ptr; + break; + case '0': + pad = pad_type::zero; + ++ptr; + break; + } + 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; + } + // Year: + case 'Y': + handler.on_year(numeric_system::standard); + break; + case 'y': + handler.on_short_year(numeric_system::standard); + break; + case 'C': + handler.on_century(numeric_system::standard); + break; + case 'G': + handler.on_iso_week_based_year(); + break; + case 'g': + handler.on_iso_week_based_short_year(); + 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': + case 'h': + handler.on_abbr_month(); + break; + case 'B': + handler.on_full_month(); + break; + case 'm': + handler.on_dec_month(numeric_system::standard); + break; + // Day of the year/month: + case 'U': + handler.on_dec0_week_of_year(numeric_system::standard); + break; + case 'W': + handler.on_dec1_week_of_year(numeric_system::standard); + break; + case 'V': + handler.on_iso_week_of_year(numeric_system::standard); + break; + case 'j': + handler.on_day_of_year(); + break; + case 'd': + handler.on_day_of_month(numeric_system::standard); + break; + case 'e': + handler.on_day_of_month_space(numeric_system::standard); + break; + // Hour, minute, second: + case 'H': + handler.on_24_hour(numeric_system::standard, pad); + break; + case 'I': + handler.on_12_hour(numeric_system::standard, pad); + break; + case 'M': + handler.on_minute(numeric_system::standard, pad); + break; + case 'S': + handler.on_second(numeric_system::standard, pad); + 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(numeric_system::standard); + 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 'Y': + handler.on_year(numeric_system::alternative); + break; + case 'y': + handler.on_offset_year(); + break; + case 'C': + handler.on_century(numeric_system::alternative); + break; + 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; + case 'z': + handler.on_utc_offset(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 'y': + handler.on_short_year(numeric_system::alternative); + break; + case 'm': + handler.on_dec_month(numeric_system::alternative); + break; + case 'U': + handler.on_dec0_week_of_year(numeric_system::alternative); + break; + case 'W': + handler.on_dec1_week_of_year(numeric_system::alternative); + break; + case 'V': + handler.on_iso_week_of_year(numeric_system::alternative); + break; + case 'd': + handler.on_day_of_month(numeric_system::alternative); + break; + case 'e': + handler.on_day_of_month_space(numeric_system::alternative); + break; + 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, pad); + break; + case 'I': + handler.on_12_hour(numeric_system::alternative, pad); + break; + case 'M': + handler.on_minute(numeric_system::alternative, pad); + break; + case 'S': + handler.on_second(numeric_system::alternative, pad); + break; + case 'z': + handler.on_utc_offset(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; +} + +template struct null_chrono_spec_handler { + FMT_CONSTEXPR void unsupported() { + static_cast(this)->unsupported(); + } + FMT_CONSTEXPR void on_year(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_short_year(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_offset_year() { unsupported(); } + FMT_CONSTEXPR void on_century(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_iso_week_based_year() { unsupported(); } + FMT_CONSTEXPR void on_iso_week_based_short_year() { unsupported(); } + FMT_CONSTEXPR void on_abbr_weekday() { unsupported(); } + FMT_CONSTEXPR void on_full_weekday() { unsupported(); } + FMT_CONSTEXPR void on_dec0_weekday(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_dec1_weekday(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_abbr_month() { unsupported(); } + FMT_CONSTEXPR void on_full_month() { unsupported(); } + FMT_CONSTEXPR void on_dec_month(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_iso_week_of_year(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_day_of_year() { unsupported(); } + FMT_CONSTEXPR void on_day_of_month(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_day_of_month_space(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_24_hour(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_12_hour(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_minute(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_second(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_datetime(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_loc_date(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_loc_time(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_us_date() { unsupported(); } + FMT_CONSTEXPR void on_iso_date() { unsupported(); } + FMT_CONSTEXPR void on_12_hour_time() { unsupported(); } + FMT_CONSTEXPR void on_24_hour_time() { unsupported(); } + FMT_CONSTEXPR void on_iso_time() { unsupported(); } + FMT_CONSTEXPR void on_am_pm() { unsupported(); } + FMT_CONSTEXPR void on_duration_value() { unsupported(); } + FMT_CONSTEXPR void on_duration_unit() { unsupported(); } + FMT_CONSTEXPR void on_utc_offset(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_tz_name() { unsupported(); } +}; + +struct tm_format_checker : null_chrono_spec_handler { + FMT_NORETURN void unsupported() { FMT_THROW(format_error("no format")); } + + template + FMT_CONSTEXPR void on_text(const Char*, const Char*) {} + FMT_CONSTEXPR void on_year(numeric_system) {} + FMT_CONSTEXPR void on_short_year(numeric_system) {} + FMT_CONSTEXPR void on_offset_year() {} + FMT_CONSTEXPR void on_century(numeric_system) {} + FMT_CONSTEXPR void on_iso_week_based_year() {} + FMT_CONSTEXPR void on_iso_week_based_short_year() {} + FMT_CONSTEXPR void on_abbr_weekday() {} + FMT_CONSTEXPR void on_full_weekday() {} + FMT_CONSTEXPR void on_dec0_weekday(numeric_system) {} + FMT_CONSTEXPR void on_dec1_weekday(numeric_system) {} + FMT_CONSTEXPR void on_abbr_month() {} + FMT_CONSTEXPR void on_full_month() {} + FMT_CONSTEXPR void on_dec_month(numeric_system) {} + FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system) {} + FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system) {} + FMT_CONSTEXPR void on_iso_week_of_year(numeric_system) {} + FMT_CONSTEXPR void on_day_of_year() {} + FMT_CONSTEXPR void on_day_of_month(numeric_system) {} + FMT_CONSTEXPR void on_day_of_month_space(numeric_system) {} + FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_second(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_datetime(numeric_system) {} + FMT_CONSTEXPR void on_loc_date(numeric_system) {} + FMT_CONSTEXPR void on_loc_time(numeric_system) {} + FMT_CONSTEXPR void on_us_date() {} + FMT_CONSTEXPR void on_iso_date() {} + FMT_CONSTEXPR void on_12_hour_time() {} + FMT_CONSTEXPR void on_24_hour_time() {} + FMT_CONSTEXPR void on_iso_time() {} + FMT_CONSTEXPR void on_am_pm() {} + FMT_CONSTEXPR void on_utc_offset(numeric_system) {} + FMT_CONSTEXPR void on_tz_name() {} +}; + +inline auto tm_wday_full_name(int wday) -> const char* { + static constexpr const char* full_name_list[] = { + "Sunday", "Monday", "Tuesday", "Wednesday", + "Thursday", "Friday", "Saturday"}; + return wday >= 0 && wday <= 6 ? full_name_list[wday] : "?"; +} +inline auto tm_wday_short_name(int wday) -> const char* { + static constexpr const char* short_name_list[] = {"Sun", "Mon", "Tue", "Wed", + "Thu", "Fri", "Sat"}; + return wday >= 0 && wday <= 6 ? short_name_list[wday] : "???"; +} + +inline auto tm_mon_full_name(int mon) -> const char* { + static constexpr const char* full_name_list[] = { + "January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December"}; + return mon >= 0 && mon <= 11 ? full_name_list[mon] : "?"; +} +inline auto tm_mon_short_name(int mon) -> const char* { + static constexpr const char* short_name_list[] = { + "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", + }; + return mon >= 0 && mon <= 11 ? short_name_list[mon] : "???"; +} + +template +struct has_member_data_tm_gmtoff : std::false_type {}; +template +struct has_member_data_tm_gmtoff> + : std::true_type {}; + +template +struct has_member_data_tm_zone : std::false_type {}; +template +struct has_member_data_tm_zone> + : std::true_type {}; + +#if FMT_USE_TZSET +inline void tzset_once() { + static bool init = []() -> bool { + _tzset(); + return true; + }(); + ignore_unused(init); +} +#endif + +// Converts value to Int and checks that it's in the range [0, upper). +template ::value)> +inline auto to_nonnegative_int(T value, Int upper) -> Int { + if (!std::is_unsigned::value && + (value < 0 || to_unsigned(value) > to_unsigned(upper))) { + FMT_THROW(fmt::format_error("chrono value is out of range")); + } + return static_cast(value); +} +template ::value)> +inline auto to_nonnegative_int(T value, Int upper) -> Int { + if (value < 0 || value > static_cast(upper)) + FMT_THROW(format_error("invalid value")); + return static_cast(value); +} + +constexpr auto pow10(std::uint32_t n) -> long long { + return n == 0 ? 1 : 10 * pow10(n - 1); +} + +// Counts the number of fractional digits in the range [0, 18] according to the +// C++20 spec. If more than 18 fractional digits are required then returns 6 for +// microseconds precision. +template () / 10)> +struct count_fractional_digits { + static constexpr int value = + Num % Den == 0 ? N : count_fractional_digits::value; +}; + +// Base case that doesn't instantiate any more templates +// in order to avoid overflow. +template +struct count_fractional_digits { + static constexpr int value = (Num % Den == 0) ? N : 6; +}; + +// Format subseconds which are given as an integer type with an appropriate +// number of digits. +template +void write_fractional_seconds(OutputIt& out, Duration d, int precision = -1) { + constexpr auto num_fractional_digits = + count_fractional_digits::value; + + using subsecond_precision = std::chrono::duration< + typename std::common_type::type, + std::ratio<1, detail::pow10(num_fractional_digits)>>; + + const auto fractional = d - fmt_duration_cast(d); + const auto subseconds = + std::chrono::treat_as_floating_point< + typename subsecond_precision::rep>::value + ? fractional.count() + : fmt_duration_cast(fractional).count(); + auto n = static_cast>(subseconds); + const int num_digits = detail::count_digits(n); + + int leading_zeroes = (std::max)(0, num_fractional_digits - num_digits); + if (precision < 0) { + FMT_ASSERT(!std::is_floating_point::value, ""); + if (std::ratio_less::value) { + *out++ = '.'; + out = std::fill_n(out, leading_zeroes, '0'); + out = format_decimal(out, n, num_digits).end; + } + } else { + *out++ = '.'; + leading_zeroes = (std::min)(leading_zeroes, precision); + out = std::fill_n(out, leading_zeroes, '0'); + int remaining = precision - leading_zeroes; + if (remaining != 0 && remaining < num_digits) { + n /= to_unsigned(detail::pow10(to_unsigned(num_digits - remaining))); + out = format_decimal(out, n, remaining).end; + return; + } + out = format_decimal(out, n, num_digits).end; + remaining -= num_digits; + out = std::fill_n(out, remaining, '0'); + } +} + +// Format subseconds which are given as a floating point type with an +// appropriate number of digits. We cannot pass the Duration here, as we +// explicitly need to pass the Rep value in the chrono_formatter. +template +void write_floating_seconds(memory_buffer& buf, Duration duration, + int num_fractional_digits = -1) { + using rep = typename Duration::rep; + FMT_ASSERT(std::is_floating_point::value, ""); + + auto val = duration.count(); + + if (num_fractional_digits < 0) { + // For `std::round` with fallback to `round`: + // On some toolchains `std::round` is not available (e.g. GCC 6). + using namespace std; + num_fractional_digits = + count_fractional_digits::value; + if (num_fractional_digits < 6 && static_cast(round(val)) != val) + num_fractional_digits = 6; + } + + fmt::format_to(std::back_inserter(buf), FMT_STRING("{:.{}f}"), + std::fmod(val * static_cast(Duration::period::num) / + static_cast(Duration::period::den), + static_cast(60)), + num_fractional_digits); +} + +template +class tm_writer { + private: + static constexpr int days_per_week = 7; + + const std::locale& loc_; + const bool is_classic_; + OutputIt out_; + const Duration* subsecs_; + const std::tm& tm_; + + auto tm_sec() const noexcept -> int { + FMT_ASSERT(tm_.tm_sec >= 0 && tm_.tm_sec <= 61, ""); + return tm_.tm_sec; + } + auto tm_min() const noexcept -> int { + FMT_ASSERT(tm_.tm_min >= 0 && tm_.tm_min <= 59, ""); + return tm_.tm_min; + } + auto tm_hour() const noexcept -> int { + FMT_ASSERT(tm_.tm_hour >= 0 && tm_.tm_hour <= 23, ""); + return tm_.tm_hour; + } + auto tm_mday() const noexcept -> int { + FMT_ASSERT(tm_.tm_mday >= 1 && tm_.tm_mday <= 31, ""); + return tm_.tm_mday; + } + auto tm_mon() const noexcept -> int { + FMT_ASSERT(tm_.tm_mon >= 0 && tm_.tm_mon <= 11, ""); + return tm_.tm_mon; + } + auto tm_year() const noexcept -> long long { return 1900ll + tm_.tm_year; } + auto tm_wday() const noexcept -> int { + FMT_ASSERT(tm_.tm_wday >= 0 && tm_.tm_wday <= 6, ""); + return tm_.tm_wday; + } + auto tm_yday() const noexcept -> int { + FMT_ASSERT(tm_.tm_yday >= 0 && tm_.tm_yday <= 365, ""); + return tm_.tm_yday; + } + + auto tm_hour12() const noexcept -> int { + const auto h = tm_hour(); + const auto z = h < 12 ? h : h - 12; + return z == 0 ? 12 : z; + } + + // POSIX and the C Standard are unclear or inconsistent about what %C and %y + // do if the year is negative or exceeds 9999. Use the convention that %C + // concatenated with %y yields the same output as %Y, and that %Y contains at + // least 4 characters, with more only if necessary. + auto split_year_lower(long long year) const noexcept -> int { + auto l = year % 100; + if (l < 0) l = -l; // l in [0, 99] + return static_cast(l); + } + + // Algorithm: https://en.wikipedia.org/wiki/ISO_week_date. + auto iso_year_weeks(long long curr_year) const noexcept -> int { + const auto prev_year = curr_year - 1; + const auto curr_p = + (curr_year + curr_year / 4 - curr_year / 100 + curr_year / 400) % + days_per_week; + const auto prev_p = + (prev_year + prev_year / 4 - prev_year / 100 + prev_year / 400) % + days_per_week; + return 52 + ((curr_p == 4 || prev_p == 3) ? 1 : 0); + } + auto iso_week_num(int tm_yday, int tm_wday) const noexcept -> int { + return (tm_yday + 11 - (tm_wday == 0 ? days_per_week : tm_wday)) / + days_per_week; + } + auto tm_iso_week_year() const noexcept -> long long { + const auto year = tm_year(); + const auto w = iso_week_num(tm_yday(), tm_wday()); + if (w < 1) return year - 1; + if (w > iso_year_weeks(year)) return year + 1; + return year; + } + auto tm_iso_week_of_year() const noexcept -> int { + const auto year = tm_year(); + const auto w = iso_week_num(tm_yday(), tm_wday()); + if (w < 1) return iso_year_weeks(year - 1); + if (w > iso_year_weeks(year)) return 1; + return w; + } + + void write1(int value) { + *out_++ = static_cast('0' + to_unsigned(value) % 10); + } + void write2(int value) { + const char* d = digits2(to_unsigned(value) % 100); + *out_++ = *d++; + *out_++ = *d; + } + void write2(int value, pad_type pad) { + unsigned int v = to_unsigned(value) % 100; + if (v >= 10) { + const char* d = digits2(v); + *out_++ = *d++; + *out_++ = *d; + } else { + out_ = detail::write_padding(out_, pad); + *out_++ = static_cast('0' + v); + } + } + + void write_year_extended(long long year) { + // At least 4 characters. + int width = 4; + if (year < 0) { + *out_++ = '-'; + year = 0 - year; + --width; + } + uint32_or_64_or_128_t n = to_unsigned(year); + const int num_digits = count_digits(n); + if (width > num_digits) out_ = std::fill_n(out_, width - num_digits, '0'); + out_ = format_decimal(out_, n, num_digits).end; + } + void write_year(long long year) { + if (year >= 0 && year < 10000) { + write2(static_cast(year / 100)); + write2(static_cast(year % 100)); + } else { + write_year_extended(year); + } + } + + void write_utc_offset(long offset, numeric_system ns) { + if (offset < 0) { + *out_++ = '-'; + offset = -offset; + } else { + *out_++ = '+'; + } + offset /= 60; + write2(static_cast(offset / 60)); + if (ns != numeric_system::standard) *out_++ = ':'; + write2(static_cast(offset % 60)); + } + template ::value)> + void format_utc_offset_impl(const T& tm, numeric_system ns) { + write_utc_offset(tm.tm_gmtoff, ns); + } + template ::value)> + void format_utc_offset_impl(const T& tm, numeric_system ns) { +#if defined(_WIN32) && defined(_UCRT) +# if FMT_USE_TZSET + tzset_once(); +# endif + long offset = 0; + _get_timezone(&offset); + if (tm.tm_isdst) { + long dstbias = 0; + _get_dstbias(&dstbias); + offset += dstbias; + } + write_utc_offset(-offset, ns); +#else + if (ns == numeric_system::standard) return format_localized('z'); + + // Extract timezone offset from timezone conversion functions. + std::tm gtm = tm; + std::time_t gt = std::mktime(>m); + std::tm ltm = gmtime(gt); + std::time_t lt = std::mktime(<m); + long offset = gt - lt; + write_utc_offset(offset, ns); +#endif + } + + template ::value)> + void format_tz_name_impl(const T& tm) { + if (is_classic_) + out_ = write_tm_str(out_, tm.tm_zone, loc_); + else + format_localized('Z'); + } + template ::value)> + void format_tz_name_impl(const T&) { + format_localized('Z'); + } + + void format_localized(char format, char modifier = 0) { + out_ = write(out_, tm_, loc_, format, modifier); + } + + public: + tm_writer(const std::locale& loc, OutputIt out, const std::tm& tm, + const Duration* subsecs = nullptr) + : loc_(loc), + is_classic_(loc_ == get_classic_locale()), + out_(out), + subsecs_(subsecs), + tm_(tm) {} + + auto out() const -> OutputIt { return out_; } + + FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) { + out_ = copy_str(begin, end, out_); + } + + void on_abbr_weekday() { + if (is_classic_) + out_ = write(out_, tm_wday_short_name(tm_wday())); + else + format_localized('a'); + } + void on_full_weekday() { + if (is_classic_) + out_ = write(out_, tm_wday_full_name(tm_wday())); + else + format_localized('A'); + } + void on_dec0_weekday(numeric_system ns) { + if (is_classic_ || ns == numeric_system::standard) return write1(tm_wday()); + format_localized('w', 'O'); + } + void on_dec1_weekday(numeric_system ns) { + if (is_classic_ || ns == numeric_system::standard) { + auto wday = tm_wday(); + write1(wday == 0 ? days_per_week : wday); + } else { + format_localized('u', 'O'); + } + } + + void on_abbr_month() { + if (is_classic_) + out_ = write(out_, tm_mon_short_name(tm_mon())); + else + format_localized('b'); + } + void on_full_month() { + if (is_classic_) + out_ = write(out_, tm_mon_full_name(tm_mon())); + else + format_localized('B'); + } + + void on_datetime(numeric_system ns) { + if (is_classic_) { + on_abbr_weekday(); + *out_++ = ' '; + on_abbr_month(); + *out_++ = ' '; + on_day_of_month_space(numeric_system::standard); + *out_++ = ' '; + on_iso_time(); + *out_++ = ' '; + on_year(numeric_system::standard); + } else { + format_localized('c', ns == numeric_system::standard ? '\0' : 'E'); + } + } + void on_loc_date(numeric_system ns) { + if (is_classic_) + on_us_date(); + else + format_localized('x', ns == numeric_system::standard ? '\0' : 'E'); + } + void on_loc_time(numeric_system ns) { + if (is_classic_) + on_iso_time(); + else + format_localized('X', ns == numeric_system::standard ? '\0' : 'E'); + } + void on_us_date() { + char buf[8]; + write_digit2_separated(buf, to_unsigned(tm_mon() + 1), + to_unsigned(tm_mday()), + to_unsigned(split_year_lower(tm_year())), '/'); + out_ = copy_str(std::begin(buf), std::end(buf), out_); + } + void on_iso_date() { + auto year = tm_year(); + char buf[10]; + size_t offset = 0; + if (year >= 0 && year < 10000) { + copy2(buf, digits2(static_cast(year / 100))); + } else { + offset = 4; + write_year_extended(year); + year = 0; + } + write_digit2_separated(buf + 2, static_cast(year % 100), + to_unsigned(tm_mon() + 1), to_unsigned(tm_mday()), + '-'); + out_ = copy_str(std::begin(buf) + offset, std::end(buf), out_); + } + + void on_utc_offset(numeric_system ns) { format_utc_offset_impl(tm_, ns); } + void on_tz_name() { format_tz_name_impl(tm_); } + + void on_year(numeric_system ns) { + if (is_classic_ || ns == numeric_system::standard) + return write_year(tm_year()); + format_localized('Y', 'E'); + } + void on_short_year(numeric_system ns) { + if (is_classic_ || ns == numeric_system::standard) + return write2(split_year_lower(tm_year())); + format_localized('y', 'O'); + } + void on_offset_year() { + if (is_classic_) return write2(split_year_lower(tm_year())); + format_localized('y', 'E'); + } + + void on_century(numeric_system ns) { + if (is_classic_ || ns == numeric_system::standard) { + auto year = tm_year(); + auto upper = year / 100; + if (year >= -99 && year < 0) { + // Zero upper on negative year. + *out_++ = '-'; + *out_++ = '0'; + } else if (upper >= 0 && upper < 100) { + write2(static_cast(upper)); + } else { + out_ = write(out_, upper); + } + } else { + format_localized('C', 'E'); + } + } + + void on_dec_month(numeric_system ns) { + if (is_classic_ || ns == numeric_system::standard) + return write2(tm_mon() + 1); + format_localized('m', 'O'); + } + + void on_dec0_week_of_year(numeric_system ns) { + if (is_classic_ || ns == numeric_system::standard) + return write2((tm_yday() + days_per_week - tm_wday()) / days_per_week); + format_localized('U', 'O'); + } + void on_dec1_week_of_year(numeric_system ns) { + if (is_classic_ || ns == numeric_system::standard) { + auto wday = tm_wday(); + write2((tm_yday() + days_per_week - + (wday == 0 ? (days_per_week - 1) : (wday - 1))) / + days_per_week); + } else { + format_localized('W', 'O'); + } + } + void on_iso_week_of_year(numeric_system ns) { + if (is_classic_ || ns == numeric_system::standard) + return write2(tm_iso_week_of_year()); + format_localized('V', 'O'); + } + + void on_iso_week_based_year() { write_year(tm_iso_week_year()); } + void on_iso_week_based_short_year() { + write2(split_year_lower(tm_iso_week_year())); + } + + void on_day_of_year() { + auto yday = tm_yday() + 1; + write1(yday / 100); + write2(yday % 100); + } + void on_day_of_month(numeric_system ns) { + if (is_classic_ || ns == numeric_system::standard) return write2(tm_mday()); + format_localized('d', 'O'); + } + void on_day_of_month_space(numeric_system ns) { + if (is_classic_ || ns == numeric_system::standard) { + auto mday = to_unsigned(tm_mday()) % 100; + const char* d2 = digits2(mday); + *out_++ = mday < 10 ? ' ' : d2[0]; + *out_++ = d2[1]; + } else { + format_localized('e', 'O'); + } + } + + void on_24_hour(numeric_system ns, pad_type pad) { + if (is_classic_ || ns == numeric_system::standard) + return write2(tm_hour(), pad); + format_localized('H', 'O'); + } + void on_12_hour(numeric_system ns, pad_type pad) { + if (is_classic_ || ns == numeric_system::standard) + return write2(tm_hour12(), pad); + format_localized('I', 'O'); + } + void on_minute(numeric_system ns, pad_type pad) { + if (is_classic_ || ns == numeric_system::standard) + return write2(tm_min(), pad); + format_localized('M', 'O'); + } + + void on_second(numeric_system ns, pad_type pad) { + if (is_classic_ || ns == numeric_system::standard) { + write2(tm_sec(), pad); + if (subsecs_) { + if (std::is_floating_point::value) { + auto buf = memory_buffer(); + write_floating_seconds(buf, *subsecs_); + if (buf.size() > 1) { + // Remove the leading "0", write something like ".123". + out_ = std::copy(buf.begin() + 1, buf.end(), out_); + } + } else { + write_fractional_seconds(out_, *subsecs_); + } + } + } else { + // Currently no formatting of subseconds when a locale is set. + format_localized('S', 'O'); + } + } + + void on_12_hour_time() { + if (is_classic_) { + char buf[8]; + write_digit2_separated(buf, to_unsigned(tm_hour12()), + to_unsigned(tm_min()), to_unsigned(tm_sec()), ':'); + out_ = copy_str(std::begin(buf), std::end(buf), out_); + *out_++ = ' '; + on_am_pm(); + } else { + format_localized('r'); + } + } + void on_24_hour_time() { + write2(tm_hour()); + *out_++ = ':'; + write2(tm_min()); + } + void on_iso_time() { + on_24_hour_time(); + *out_++ = ':'; + on_second(numeric_system::standard, pad_type::unspecified); + } + + void on_am_pm() { + if (is_classic_) { + *out_++ = tm_hour() < 12 ? 'A' : 'P'; + *out_++ = 'M'; + } else { + format_localized('p'); + } + } + + // These apply to chrono durations but not tm. + void on_duration_value() {} + void on_duration_unit() {} +}; + +struct chrono_format_checker : null_chrono_spec_handler { + bool has_precision_integral = false; + + FMT_NORETURN void unsupported() { FMT_THROW(format_error("no date")); } + + template + FMT_CONSTEXPR void on_text(const Char*, const Char*) {} + FMT_CONSTEXPR void on_day_of_year() {} + FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_second(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_12_hour_time() {} + FMT_CONSTEXPR void on_24_hour_time() {} + FMT_CONSTEXPR void on_iso_time() {} + FMT_CONSTEXPR void on_am_pm() {} + FMT_CONSTEXPR void on_duration_value() const { + if (has_precision_integral) { + FMT_THROW(format_error("precision not allowed for this argument type")); + } + } + FMT_CONSTEXPR void on_duration_unit() {} +}; + +template ::value&& has_isfinite::value)> +inline auto isfinite(T) -> bool { + return true; +} + +template ::value)> +inline auto mod(T x, int y) -> T { + return x % static_cast(y); +} +template ::value)> +inline auto mod(T x, int y) -> T { + return std::fmod(x, static_cast(y)); +} + +// If T is an integral type, maps T to its unsigned counterpart, otherwise +// leaves it unchanged (unlike std::make_unsigned). +template ::value> +struct make_unsigned_or_unchanged { + using type = T; +}; + +template struct make_unsigned_or_unchanged { + using type = typename std::make_unsigned::type; +}; + +template ::value)> +inline auto get_milliseconds(std::chrono::duration d) + -> std::chrono::duration { + // 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::type; + const auto d_as_common = fmt_duration_cast(d); + const auto d_as_whole_seconds = + fmt_duration_cast(d_as_common); + // this conversion should be nonproblematic + const auto diff = d_as_common - d_as_whole_seconds; + const auto ms = + fmt_duration_cast>(diff); + return ms; +#else + auto s = fmt_duration_cast(d); + return fmt_duration_cast(d - s); +#endif +} + +template ::value)> +auto format_duration_value(OutputIt out, Rep val, int) -> OutputIt { + return write(out, val); +} + +template ::value)> +auto format_duration_value(OutputIt out, Rep val, int precision) -> OutputIt { + auto specs = format_specs(); + specs.precision = precision; + specs.type = precision >= 0 ? presentation_type::fixed_lower + : presentation_type::general_lower; + return write(out, val, specs); +} + +template +auto copy_unit(string_view unit, OutputIt out, Char) -> OutputIt { + return std::copy(unit.begin(), unit.end(), out); +} + +template +auto copy_unit(string_view unit, OutputIt out, wchar_t) -> OutputIt { + // 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 +auto format_duration_unit(OutputIt out) -> OutputIt { + if (const char* unit = get_units()) + return copy_unit(string_view(unit), out, Char()); + *out++ = '['; + out = write(out, Period::num); + if (const_check(Period::den != 1)) { + *out++ = '/'; + out = write(out, Period::den); + } + *out++ = ']'; + *out++ = 's'; + return out; +} + +class get_locale { + private: + union { + std::locale locale_; + }; + bool has_locale_ = false; + + public: + get_locale(bool localized, locale_ref loc) : has_locale_(localized) { + if (localized) + ::new (&locale_) std::locale(loc.template get()); + } + ~get_locale() { + if (has_locale_) locale_.~locale(); + } + operator const std::locale&() const { + return has_locale_ ? locale_ : get_classic_locale(); + } +}; + +template +struct chrono_formatter { + FormatContext& context; + OutputIt out; + int precision; + bool localized = false; + // rep is unsigned to avoid overflow. + using rep = + conditional_t::value && sizeof(Rep) < sizeof(int), + unsigned, typename make_unsigned_or_unchanged::type>; + rep val; + using seconds = std::chrono::duration; + seconds s; + using milliseconds = std::chrono::duration; + bool negative; + + using char_type = typename FormatContext::char_type; + using tm_writer_type = tm_writer; + + chrono_formatter(FormatContext& ctx, OutputIt o, + std::chrono::duration d) + : context(ctx), + out(o), + val(static_cast(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. + // might need checked conversion (rep!=Rep) + s = fmt_duration_cast(std::chrono::duration(val)); + } + + // returns true if nan or inf, writes to out. + auto handle_nan_inf() -> bool { + 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; + } + + auto days() const -> Rep { return static_cast(s.count() / 86400); } + auto hour() const -> Rep { + return static_cast(mod((s.count() / 3600), 24)); + } + + auto hour12() const -> Rep { + Rep hour = static_cast(mod((s.count() / 3600), 12)); + return hour <= 0 ? 12 : hour; + } + + auto minute() const -> Rep { + return static_cast(mod((s.count() / 60), 60)); + } + auto second() const -> Rep { return static_cast(mod(s.count(), 60)); } + + auto time() const -> std::tm { + 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, pad_type pad = pad_type::unspecified) { + write_sign(); + if (isnan(value)) return write_nan(); + uint32_or_64_or_128_t n = + to_unsigned(to_nonnegative_int(value, max_value())); + int num_digits = detail::count_digits(n); + if (width > num_digits) { + out = detail::write_padding(out, pad, width - num_digits); + } + out = format_decimal(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); } + + template + void format_tm(const tm& time, Callback cb, Args... args) { + if (isnan(val)) return write_nan(); + get_locale loc(localized, context.locale()); + auto w = tm_writer_type(loc, out, time); + (w.*cb)(args...); + out = w.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(numeric_system) {} + void on_tz_name() {} + void on_year(numeric_system) {} + void on_short_year(numeric_system) {} + void on_offset_year() {} + void on_century(numeric_system) {} + void on_iso_week_based_year() {} + void on_iso_week_based_short_year() {} + void on_dec_month(numeric_system) {} + void on_dec0_week_of_year(numeric_system) {} + void on_dec1_week_of_year(numeric_system) {} + void on_iso_week_of_year(numeric_system) {} + void on_day_of_month(numeric_system) {} + void on_day_of_month_space(numeric_system) {} + + void on_day_of_year() { + if (handle_nan_inf()) return; + write(days(), 0); + } + + void on_24_hour(numeric_system ns, pad_type pad) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) return write(hour(), 2, pad); + auto time = tm(); + time.tm_hour = to_nonnegative_int(hour(), 24); + format_tm(time, &tm_writer_type::on_24_hour, ns, pad); + } + + void on_12_hour(numeric_system ns, pad_type pad) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) return write(hour12(), 2, pad); + auto time = tm(); + time.tm_hour = to_nonnegative_int(hour12(), 12); + format_tm(time, &tm_writer_type::on_12_hour, ns, pad); + } + + void on_minute(numeric_system ns, pad_type pad) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) return write(minute(), 2, pad); + auto time = tm(); + time.tm_min = to_nonnegative_int(minute(), 60); + format_tm(time, &tm_writer_type::on_minute, ns, pad); + } + + void on_second(numeric_system ns, pad_type pad) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) { + if (std::is_floating_point::value) { + auto buf = memory_buffer(); + write_floating_seconds(buf, std::chrono::duration(val), + precision); + if (negative) *out++ = '-'; + if (buf.size() < 2 || buf[1] == '.') { + out = detail::write_padding(out, pad); + } + out = std::copy(buf.begin(), buf.end(), out); + } else { + write(second(), 2, pad); + write_fractional_seconds( + out, std::chrono::duration(val), precision); + } + return; + } + auto time = tm(); + time.tm_sec = to_nonnegative_int(second(), 60); + format_tm(time, &tm_writer_type::on_second, ns, pad); + } + + void on_12_hour_time() { + if (handle_nan_inf()) return; + format_tm(time(), &tm_writer_type::on_12_hour_time); + } + + 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; + on_second(numeric_system::standard, pad_type::unspecified); + } + + void on_am_pm() { + if (handle_nan_inf()) return; + format_tm(time(), &tm_writer_type::on_am_pm); + } + + void on_duration_value() { + if (handle_nan_inf()) return; + write_sign(); + out = format_duration_value(out, val, precision); + } + + void on_duration_unit() { + out = format_duration_unit(out); + } +}; + +} // namespace detail + +#if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907 +using weekday = std::chrono::weekday; +#else +// A fallback version of weekday. +class weekday { + private: + unsigned char value; + + public: + weekday() = default; + explicit constexpr weekday(unsigned wd) noexcept + : value(static_cast(wd != 7 ? wd : 0)) {} + constexpr auto c_encoding() const noexcept -> unsigned { return value; } +}; + +class year_month_day {}; +#endif + +// A rudimentary weekday formatter. +template struct formatter { + private: + bool localized = false; + + public: + FMT_CONSTEXPR auto parse(basic_format_parse_context& ctx) + -> decltype(ctx.begin()) { + auto begin = ctx.begin(), end = ctx.end(); + if (begin != end && *begin == 'L') { + ++begin; + localized = true; + } + return begin; + } + + template + auto format(weekday wd, FormatContext& ctx) const -> decltype(ctx.out()) { + auto time = std::tm(); + time.tm_wday = static_cast(wd.c_encoding()); + detail::get_locale loc(localized, ctx.locale()); + auto w = detail::tm_writer(loc, ctx.out(), time); + w.on_abbr_weekday(); + return w.out(); + } +}; + +template +struct formatter, Char> { + private: + format_specs specs_; + detail::arg_ref width_ref_; + detail::arg_ref precision_ref_; + bool localized_ = false; + basic_string_view format_str_; + + public: + FMT_CONSTEXPR auto parse(basic_format_parse_context& ctx) + -> decltype(ctx.begin()) { + auto it = ctx.begin(), end = ctx.end(); + if (it == end || *it == '}') return it; + + it = detail::parse_align(it, end, specs_); + if (it == end) return it; + + it = detail::parse_dynamic_spec(it, end, specs_.width, width_ref_, ctx); + if (it == end) return it; + + auto checker = detail::chrono_format_checker(); + if (*it == '.') { + checker.has_precision_integral = !std::is_floating_point::value; + it = detail::parse_precision(it, end, specs_.precision, precision_ref_, + ctx); + } + if (it != end && *it == 'L') { + localized_ = true; + ++it; + } + end = detail::parse_chrono_format(it, end, checker); + format_str_ = {it, detail::to_unsigned(end - it)}; + return end; + } + + template + auto format(std::chrono::duration d, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto specs = specs_; + auto precision = specs.precision; + specs.precision = -1; + auto begin = format_str_.begin(), end = format_str_.end(); + // As a possible future optimization, we could avoid extra copying if width + // is not specified. + auto buf = basic_memory_buffer(); + auto out = std::back_inserter(buf); + detail::handle_dynamic_spec(specs.width, width_ref_, + ctx); + detail::handle_dynamic_spec(precision, + precision_ref_, ctx); + if (begin == end || *begin == '}') { + out = detail::format_duration_value(out, d.count(), precision); + detail::format_duration_unit(out); + } else { + using chrono_formatter = + detail::chrono_formatter; + auto f = chrono_formatter(ctx, out, d); + f.precision = precision; + f.localized = localized_; + detail::parse_chrono_format(begin, end, f); + } + return detail::write( + ctx.out(), basic_string_view(buf.data(), buf.size()), specs); + } +}; + +template +struct formatter, + Char> : formatter { + FMT_CONSTEXPR formatter() { + this->format_str_ = detail::string_literal{}; + } + + template + auto format(std::chrono::time_point val, + FormatContext& ctx) const -> decltype(ctx.out()) { + using period = typename Duration::period; + if (detail::const_check( + period::num != 1 || period::den != 1 || + std::is_floating_point::value)) { + const auto epoch = val.time_since_epoch(); + auto subsecs = detail::fmt_duration_cast( + epoch - detail::fmt_duration_cast(epoch)); + + if (subsecs.count() < 0) { + auto second = + detail::fmt_duration_cast(std::chrono::seconds(1)); + if (epoch.count() < ((Duration::min)() + second).count()) + FMT_THROW(format_error("duration is too small")); + subsecs += second; + val -= second; + } + + return formatter::do_format(gmtime(val), ctx, &subsecs); + } + + return formatter::format(gmtime(val), ctx); + } +}; + +#if FMT_USE_LOCAL_TIME +template +struct formatter, Char> + : formatter { + FMT_CONSTEXPR formatter() { + this->format_str_ = detail::string_literal{}; + } + + template + auto format(std::chrono::local_time val, FormatContext& ctx) const + -> decltype(ctx.out()) { + using period = typename Duration::period; + if (period::num != 1 || period::den != 1 || + std::is_floating_point::value) { + const auto epoch = val.time_since_epoch(); + const auto subsecs = detail::fmt_duration_cast( + epoch - detail::fmt_duration_cast(epoch)); + + return formatter::do_format(localtime(val), ctx, &subsecs); + } + + return formatter::format(localtime(val), ctx); + } +}; +#endif + +#if FMT_USE_UTC_TIME +template +struct formatter, + Char> + : formatter, + Char> { + template + auto format(std::chrono::time_point val, + FormatContext& ctx) const -> decltype(ctx.out()) { + return formatter< + std::chrono::time_point, + Char>::format(std::chrono::utc_clock::to_sys(val), ctx); + } +}; +#endif + +template struct formatter { + private: + format_specs specs_; + detail::arg_ref width_ref_; + + protected: + basic_string_view format_str_; + + template + auto do_format(const std::tm& tm, FormatContext& ctx, + const Duration* subsecs) const -> decltype(ctx.out()) { + auto specs = specs_; + auto buf = basic_memory_buffer(); + auto out = std::back_inserter(buf); + detail::handle_dynamic_spec(specs.width, width_ref_, + ctx); + + auto loc_ref = ctx.locale(); + detail::get_locale loc(static_cast(loc_ref), loc_ref); + auto w = + detail::tm_writer(loc, out, tm, subsecs); + detail::parse_chrono_format(format_str_.begin(), format_str_.end(), w); + return detail::write( + ctx.out(), basic_string_view(buf.data(), buf.size()), specs); + } + + public: + FMT_CONSTEXPR auto parse(basic_format_parse_context& ctx) + -> decltype(ctx.begin()) { + auto it = ctx.begin(), end = ctx.end(); + if (it == end || *it == '}') return it; + + it = detail::parse_align(it, end, specs_); + if (it == end) return it; + + it = detail::parse_dynamic_spec(it, end, specs_.width, width_ref_, ctx); + if (it == end) return it; + + end = detail::parse_chrono_format(it, end, detail::tm_format_checker()); + // Replace the default format_str only if the new spec is not empty. + if (end != it) format_str_ = {it, detail::to_unsigned(end - it)}; + return end; + } + + template + auto format(const std::tm& tm, FormatContext& ctx) const + -> decltype(ctx.out()) { + return do_format(tm, ctx, nullptr); + } +}; + +FMT_END_EXPORT +FMT_END_NAMESPACE + +#endif // FMT_CHRONO_H_ diff --git a/third_party/fmt/include/fmt/color.h b/third_party/fmt/include/fmt/color.h new file mode 100644 index 0000000..367849a --- /dev/null +++ b/third_party/fmt/include/fmt/color.h @@ -0,0 +1,643 @@ +// 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 +FMT_BEGIN_EXPORT + +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, + faint = 1 << 1, + italic = 1 << 2, + underline = 1 << 3, + blink = 1 << 4, + reverse = 1 << 5, + conceal = 1 << 6, + strikethrough = 1 << 7, +}; + +// 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() noexcept : is_rgb(), value{} {} + FMT_CONSTEXPR color_type(color rgb_color) noexcept : is_rgb(true), value{} { + value.rgb_color = static_cast(rgb_color); + } + FMT_CONSTEXPR color_type(rgb rgb_color) noexcept : is_rgb(true), value{} { + value.rgb_color = (static_cast(rgb_color.r) << 16) | + (static_cast(rgb_color.g) << 8) | rgb_color.b; + } + FMT_CONSTEXPR color_type(terminal_color term_color) noexcept + : is_rgb(), value{} { + value.term_color = static_cast(term_color); + } + bool is_rgb; + union color_union { + uint8_t term_color; + uint32_t rgb_color; + } value; +}; +} // namespace detail + +/** A text style consisting of foreground and background colors and emphasis. */ +class text_style { + public: + FMT_CONSTEXPR text_style(emphasis em = emphasis()) noexcept + : set_foreground_color(), set_background_color(), ems(em) {} + + FMT_CONSTEXPR auto operator|=(const text_style& rhs) -> text_style& { + 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(static_cast(ems) | + static_cast(rhs.ems)); + return *this; + } + + friend FMT_CONSTEXPR auto operator|(text_style lhs, const text_style& rhs) + -> text_style { + return lhs |= rhs; + } + + FMT_CONSTEXPR auto has_foreground() const noexcept -> bool { + return set_foreground_color; + } + FMT_CONSTEXPR auto has_background() const noexcept -> bool { + return set_background_color; + } + FMT_CONSTEXPR auto has_emphasis() const noexcept -> bool { + return static_cast(ems) != 0; + } + FMT_CONSTEXPR auto get_foreground() const noexcept -> detail::color_type { + FMT_ASSERT(has_foreground(), "no foreground specified for this style"); + return foreground_color; + } + FMT_CONSTEXPR auto get_background() const noexcept -> detail::color_type { + FMT_ASSERT(has_background(), "no background specified for this style"); + return background_color; + } + FMT_CONSTEXPR auto get_emphasis() const noexcept -> emphasis { + 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) 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 auto fg(detail::color_type foreground) noexcept + -> text_style; + + friend FMT_CONSTEXPR auto bg(detail::color_type background) noexcept + -> text_style; + + detail::color_type foreground_color; + detail::color_type background_color; + bool set_foreground_color; + bool set_background_color; + emphasis ems; +}; + +/** Creates a text style from the foreground (text) color. */ +FMT_CONSTEXPR inline auto fg(detail::color_type foreground) noexcept + -> text_style { + return text_style(true, foreground); +} + +/** Creates a text style from the background color. */ +FMT_CONSTEXPR inline auto bg(detail::color_type background) noexcept + -> text_style { + return text_style(false, background); +} + +FMT_CONSTEXPR inline auto operator|(emphasis lhs, emphasis rhs) noexcept + -> text_style { + return text_style(lhs) | rhs; +} + +namespace detail { + +template struct ansi_color_escape { + FMT_CONSTEXPR ansi_color_escape(detail::color_type text_color, + const char* esc) noexcept { + // If we have a terminal color, we need to output another escape code + // sequence. + if (!text_color.is_rgb) { + bool is_background = esc == string_view("\x1b[48;2;"); + 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('\x1b'); + buffer[index++] = static_cast('['); + + if (value >= 100u) { + buffer[index++] = static_cast('1'); + value %= 100u; + } + buffer[index++] = static_cast('0' + value / 10u); + buffer[index++] = static_cast('0' + value % 10u); + + buffer[index++] = static_cast('m'); + buffer[index++] = static_cast('\0'); + return; + } + + for (int i = 0; i < 7; i++) { + buffer[i] = static_cast(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(0); + } + FMT_CONSTEXPR ansi_color_escape(emphasis em) noexcept { + uint8_t em_codes[num_emphases] = {}; + if (has_emphasis(em, emphasis::bold)) em_codes[0] = 1; + if (has_emphasis(em, emphasis::faint)) em_codes[1] = 2; + if (has_emphasis(em, emphasis::italic)) em_codes[2] = 3; + if (has_emphasis(em, emphasis::underline)) em_codes[3] = 4; + if (has_emphasis(em, emphasis::blink)) em_codes[4] = 5; + if (has_emphasis(em, emphasis::reverse)) em_codes[5] = 7; + if (has_emphasis(em, emphasis::conceal)) em_codes[6] = 8; + if (has_emphasis(em, emphasis::strikethrough)) em_codes[7] = 9; + + size_t index = 0; + for (size_t i = 0; i < num_emphases; ++i) { + if (!em_codes[i]) continue; + buffer[index++] = static_cast('\x1b'); + buffer[index++] = static_cast('['); + buffer[index++] = static_cast('0' + em_codes[i]); + buffer[index++] = static_cast('m'); + } + buffer[index++] = static_cast(0); + } + FMT_CONSTEXPR operator const Char*() const noexcept { return buffer; } + + FMT_CONSTEXPR auto begin() const noexcept -> const Char* { return buffer; } + FMT_CONSTEXPR_CHAR_TRAITS auto end() const noexcept -> const Char* { + return buffer + std::char_traits::length(buffer); + } + + private: + static constexpr size_t num_emphases = 8; + Char buffer[7u + 3u * num_emphases + 1u]; + + static FMT_CONSTEXPR void to_esc(uint8_t c, Char* out, + char delimiter) noexcept { + out[0] = static_cast('0' + c / 100); + out[1] = static_cast('0' + c / 10 % 10); + out[2] = static_cast('0' + c % 10); + out[3] = static_cast(delimiter); + } + static FMT_CONSTEXPR auto has_emphasis(emphasis em, emphasis mask) noexcept + -> bool { + return static_cast(em) & static_cast(mask); + } +}; + +template +FMT_CONSTEXPR auto make_foreground_color(detail::color_type foreground) noexcept + -> ansi_color_escape { + return ansi_color_escape(foreground, "\x1b[38;2;"); +} + +template +FMT_CONSTEXPR auto make_background_color(detail::color_type background) noexcept + -> ansi_color_escape { + return ansi_color_escape(background, "\x1b[48;2;"); +} + +template +FMT_CONSTEXPR auto make_emphasis(emphasis em) noexcept + -> ansi_color_escape { + return ansi_color_escape(em); +} + +template inline void reset_color(buffer& buffer) { + auto reset_color = string_view("\x1b[0m"); + buffer.append(reset_color.begin(), reset_color.end()); +} + +template struct styled_arg : detail::view { + const T& value; + text_style style; + styled_arg(const T& v, text_style s) : value(v), style(s) {} +}; + +template +void vformat_to(buffer& buf, const text_style& ts, + basic_string_view format_str, + basic_format_args>> args) { + bool has_style = false; + if (ts.has_emphasis()) { + has_style = true; + auto emphasis = detail::make_emphasis(ts.get_emphasis()); + buf.append(emphasis.begin(), emphasis.end()); + } + if (ts.has_foreground()) { + has_style = true; + auto foreground = detail::make_foreground_color(ts.get_foreground()); + buf.append(foreground.begin(), foreground.end()); + } + if (ts.has_background()) { + has_style = true; + auto background = detail::make_background_color(ts.get_background()); + buf.append(background.begin(), background.end()); + } + detail::vformat_to(buf, format_str, args, {}); + if (has_style) detail::reset_color(buf); +} + +} // namespace detail + +inline void vprint(std::FILE* f, const text_style& ts, string_view fmt, + format_args args) { + // Legacy wide streams are not supported. + auto buf = memory_buffer(); + detail::vformat_to(buf, ts, fmt, args); + if (detail::is_utf8()) { + detail::print(f, string_view(buf.begin(), buf.size())); + return; + } + buf.push_back('\0'); + int result = std::fputs(buf.data(), f); + if (result < 0) + FMT_THROW(system_error(errno, FMT_STRING("cannot write to file"))); +} + +/** + \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 ::value)> +void print(std::FILE* f, const text_style& ts, const S& format_str, + const Args&... args) { + vprint(f, ts, format_str, + fmt::make_format_args>>(args...)); +} + +/** + \rst + 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); + \endrst + */ +template ::value)> +void print(const text_style& ts, const S& format_str, const Args&... args) { + return print(stdout, ts, format_str, args...); +} + +template > +inline auto vformat( + const text_style& ts, const S& format_str, + basic_format_args>> args) + -> std::basic_string { + basic_memory_buffer buf; + detail::vformat_to(buf, ts, detail::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 + std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red), + "The answer is {}", 42); + \endrst +*/ +template > +inline auto format(const text_style& ts, const S& format_str, + const Args&... args) -> std::basic_string { + return fmt::vformat(ts, detail::to_string_view(format_str), + fmt::make_format_args>(args...)); +} + +/** + Formats a string with the given text_style and writes the output to ``out``. + */ +template ::value)> +auto vformat_to(OutputIt out, const text_style& ts, + basic_string_view format_str, + basic_format_args>> args) + -> OutputIt { + auto&& buf = detail::get_buffer(out); + detail::vformat_to(buf, ts, format_str, args); + return detail::get_iterator(buf, out); +} + +/** + \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 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>::value && + detail::is_string::value> +inline auto format_to(OutputIt out, const text_style& ts, const S& format_str, + Args&&... args) -> + typename std::enable_if::type { + return vformat_to(out, ts, detail::to_string_view(format_str), + fmt::make_format_args>>(args...)); +} + +template +struct formatter, Char> : formatter { + template + auto format(const detail::styled_arg& arg, FormatContext& ctx) const + -> decltype(ctx.out()) { + const auto& ts = arg.style; + const auto& value = arg.value; + auto out = ctx.out(); + + bool has_style = false; + if (ts.has_emphasis()) { + has_style = true; + auto emphasis = detail::make_emphasis(ts.get_emphasis()); + out = std::copy(emphasis.begin(), emphasis.end(), out); + } + if (ts.has_foreground()) { + has_style = true; + auto foreground = + detail::make_foreground_color(ts.get_foreground()); + out = std::copy(foreground.begin(), foreground.end(), out); + } + if (ts.has_background()) { + has_style = true; + auto background = + detail::make_background_color(ts.get_background()); + out = std::copy(background.begin(), background.end(), out); + } + out = formatter::format(value, ctx); + if (has_style) { + auto reset_color = string_view("\x1b[0m"); + out = std::copy(reset_color.begin(), reset_color.end(), out); + } + return out; + } +}; + +/** + \rst + Returns an argument that will be formatted using ANSI escape sequences, + to be used in a formatting function. + + **Example**:: + + fmt::print("Elapsed time: {0:.2f} seconds", + fmt::styled(1.23, fmt::fg(fmt::color::green) | + fmt::bg(fmt::color::blue))); + \endrst + */ +template +FMT_CONSTEXPR auto styled(const T& value, text_style ts) + -> detail::styled_arg> { + return detail::styled_arg>{value, ts}; +} + +FMT_END_EXPORT +FMT_END_NAMESPACE + +#endif // FMT_COLOR_H_ diff --git a/third_party/fmt/include/fmt/compile.h b/third_party/fmt/include/fmt/compile.h new file mode 100644 index 0000000..3b3f166 --- /dev/null +++ b/third_party/fmt/include/fmt/compile.h @@ -0,0 +1,535 @@ +// 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 "format.h" + +FMT_BEGIN_NAMESPACE +namespace detail { + +template +FMT_CONSTEXPR inline auto copy_str(InputIt begin, InputIt end, + counting_iterator it) -> counting_iterator { + return it + (end - begin); +} + +// A compile-time string which is compiled into fast formatting code. +class compiled_string {}; + +template +struct is_compiled_string : std::is_base_of {}; + +/** + \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 + */ +#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction) +# define FMT_COMPILE(s) \ + FMT_STRING_IMPL(s, fmt::detail::compiled_string, explicit) +#else +# define FMT_COMPILE(s) FMT_STRING(s) +#endif + +#if FMT_USE_NONTYPE_TEMPLATE_ARGS +template Str> +struct udl_compiled_string : compiled_string { + using char_type = Char; + explicit constexpr operator basic_string_view() const { + return {Str.data, N - 1}; + } +}; +#endif + +template +auto first(const T& value, const Tail&...) -> const T& { + return value; +} + +#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction) +template struct type_list {}; + +// Returns a reference to the argument at index N from [first, rest...]. +template +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 detail::get(rest...); +} + +template +constexpr int get_arg_index_by_name(basic_string_view name, + type_list) { + return get_arg_index_by_name(name); +} + +template struct get_type_impl; + +template struct get_type_impl> { + using type = + remove_cvref_t(std::declval()...))>; +}; + +template +using get_type = typename get_type_impl::type; + +template struct is_compiled_format : std::false_type {}; + +template struct text { + basic_string_view data; + using char_type = Char; + + template + constexpr OutputIt format(OutputIt out, const Args&...) const { + return write(out, data); + } +}; + +template +struct is_compiled_format> : std::true_type {}; + +template +constexpr text make_text(basic_string_view s, size_t pos, + size_t size) { + return {{&s[pos], size}}; +} + +template struct code_unit { + Char value; + using char_type = Char; + + template + constexpr OutputIt format(OutputIt out, const Args&...) const { + *out++ = value; + return out; + } +}; + +// This ensures that the argument type is convertible to `const T&`. +template +constexpr const T& get_arg_checked(const Args&... args) { + const auto& arg = detail::get(args...); + if constexpr (detail::is_named_arg>()) { + return arg.value; + } else { + return arg; + } +} + +template +struct is_compiled_format> : std::true_type {}; + +// A replacement field that refers to argument N. +template struct field { + using char_type = Char; + + template + constexpr OutputIt format(OutputIt out, const Args&... args) const { + const T& arg = get_arg_checked(args...); + if constexpr (std::is_convertible_v>) { + auto s = basic_string_view(arg); + return copy_str(s.begin(), s.end(), out); + } + return write(out, arg); + } +}; + +template +struct is_compiled_format> : std::true_type {}; + +// A replacement field that refers to argument with name. +template struct runtime_named_field { + using char_type = Char; + basic_string_view name; + + template + constexpr static bool try_format_argument( + OutputIt& out, + // [[maybe_unused]] due to unused-but-set-parameter warning in GCC 7,8,9 + [[maybe_unused]] basic_string_view arg_name, const T& arg) { + if constexpr (is_named_arg::type>::value) { + if (arg_name == arg.name) { + out = write(out, arg.value); + return true; + } + } + return false; + } + + template + constexpr OutputIt format(OutputIt out, const Args&... args) const { + bool found = (try_format_argument(out, name, args) || ...); + if (!found) { + FMT_THROW(format_error("argument with specified name is not found")); + } + return out; + } +}; + +template +struct is_compiled_format> : std::true_type {}; + +// A replacement field that refers to argument N and has format specifiers. +template struct spec_field { + using char_type = Char; + formatter fmt; + + template + constexpr FMT_INLINE OutputIt format(OutputIt out, + const Args&... args) const { + const auto& vargs = + fmt::make_format_args>(args...); + basic_format_context ctx(out, vargs); + return fmt.format(get_arg_checked(args...), ctx); + } +}; + +template +struct is_compiled_format> : std::true_type {}; + +template struct concat { + L lhs; + R rhs; + using char_type = typename L::char_type; + + template + constexpr OutputIt format(OutputIt out, const Args&... args) const { + out = lhs.format(out, args...); + return rhs.format(out, args...); + } +}; + +template +struct is_compiled_format> : std::true_type {}; + +template +constexpr concat make_concat(L lhs, R rhs) { + return {lhs, rhs}; +} + +struct unknown_format {}; + +template +constexpr size_t parse_text(basic_string_view str, size_t pos) { + for (size_t size = str.size(); pos != size; ++pos) { + if (str[pos] == '{' || str[pos] == '}') break; + } + return pos; +} + +template +constexpr auto compile_format_string(S format_str); + +template +constexpr auto parse_tail(T head, S format_str) { + if constexpr (POS != + basic_string_view(format_str).size()) { + constexpr auto tail = compile_format_string(format_str); + if constexpr (std::is_same, + unknown_format>()) + return tail; + else + return make_concat(head, tail); + } else { + return head; + } +} + +template struct parse_specs_result { + formatter fmt; + size_t end; + int next_arg_id; +}; + +enum { manual_indexing_id = -1 }; + +template +constexpr parse_specs_result parse_specs(basic_string_view str, + size_t pos, int next_arg_id) { + str.remove_prefix(pos); + auto ctx = + compile_parse_context(str, max_value(), nullptr, next_arg_id); + auto f = formatter(); + auto end = f.parse(ctx); + return {f, pos + fmt::detail::to_unsigned(end - str.data()), + next_arg_id == 0 ? manual_indexing_id : ctx.next_arg_id()}; +} + +template struct arg_id_handler { + arg_ref arg_id; + + constexpr int on_auto() { + FMT_ASSERT(false, "handler cannot be used with automatic indexing"); + return 0; + } + constexpr int on_index(int id) { + arg_id = arg_ref(id); + return 0; + } + constexpr int on_name(basic_string_view id) { + arg_id = arg_ref(id); + return 0; + } +}; + +template struct parse_arg_id_result { + arg_ref arg_id; + const Char* arg_id_end; +}; + +template +constexpr auto parse_arg_id(const Char* begin, const Char* end) { + auto handler = arg_id_handler{arg_ref{}}; + auto arg_id_end = parse_arg_id(begin, end, handler); + return parse_arg_id_result{handler.arg_id, arg_id_end}; +} + +template struct field_type { + using type = remove_cvref_t; +}; + +template +struct field_type::value>> { + using type = remove_cvref_t; +}; + +template +constexpr auto parse_replacement_field_then_tail(S format_str) { + using char_type = typename S::char_type; + constexpr auto str = basic_string_view(format_str); + constexpr char_type c = END_POS != str.size() ? str[END_POS] : char_type(); + if constexpr (c == '}') { + return parse_tail( + field::type, ARG_INDEX>(), + format_str); + } else if constexpr (c != ':') { + FMT_THROW(format_error("expected ':'")); + } else { + constexpr auto result = parse_specs::type>( + str, END_POS + 1, NEXT_ID == manual_indexing_id ? 0 : NEXT_ID); + if constexpr (result.end >= str.size() || str[result.end] != '}') { + FMT_THROW(format_error("expected '}'")); + return 0; + } else { + return parse_tail( + spec_field::type, ARG_INDEX>{ + result.fmt}, + format_str); + } + } +} + +// Compiles a non-empty format string and returns the compiled representation +// or unknown_format() on unrecognized input. +template +constexpr auto compile_format_string(S format_str) { + using char_type = typename S::char_type; + constexpr auto str = basic_string_view(format_str); + if constexpr (str[POS] == '{') { + if constexpr (POS + 1 == str.size()) + FMT_THROW(format_error("unmatched '{' in format string")); + if constexpr (str[POS + 1] == '{') { + return parse_tail(make_text(str, POS, 1), format_str); + } else if constexpr (str[POS + 1] == '}' || str[POS + 1] == ':') { + static_assert(ID != manual_indexing_id, + "cannot switch from manual to automatic argument indexing"); + constexpr auto next_id = + ID != manual_indexing_id ? ID + 1 : manual_indexing_id; + return parse_replacement_field_then_tail, Args, + POS + 1, ID, next_id>( + format_str); + } else { + constexpr auto arg_id_result = + parse_arg_id(str.data() + POS + 1, str.data() + str.size()); + constexpr auto arg_id_end_pos = arg_id_result.arg_id_end - str.data(); + constexpr char_type c = + arg_id_end_pos != str.size() ? str[arg_id_end_pos] : char_type(); + static_assert(c == '}' || c == ':', "missing '}' in format string"); + if constexpr (arg_id_result.arg_id.kind == arg_id_kind::index) { + static_assert( + ID == manual_indexing_id || ID == 0, + "cannot switch from automatic to manual argument indexing"); + constexpr auto arg_index = arg_id_result.arg_id.val.index; + return parse_replacement_field_then_tail, + Args, arg_id_end_pos, + arg_index, manual_indexing_id>( + format_str); + } else if constexpr (arg_id_result.arg_id.kind == arg_id_kind::name) { + constexpr auto arg_index = + get_arg_index_by_name(arg_id_result.arg_id.val.name, Args{}); + if constexpr (arg_index >= 0) { + constexpr auto next_id = + ID != manual_indexing_id ? ID + 1 : manual_indexing_id; + return parse_replacement_field_then_tail< + decltype(get_type::value), Args, arg_id_end_pos, + arg_index, next_id>(format_str); + } else if constexpr (c == '}') { + return parse_tail( + runtime_named_field{arg_id_result.arg_id.val.name}, + format_str); + } else if constexpr (c == ':') { + return unknown_format(); // no type info for specs parsing + } + } + } + } else if constexpr (str[POS] == '}') { + if constexpr (POS + 1 == str.size()) + FMT_THROW(format_error("unmatched '}' in format string")); + return parse_tail(make_text(str, POS, 1), format_str); + } else { + constexpr auto end = parse_text(str, POS + 1); + if constexpr (end - POS > 1) { + return parse_tail(make_text(str, POS, end - POS), + format_str); + } else { + return parse_tail(code_unit{str[POS]}, + format_str); + } + } +} + +template ::value)> +constexpr auto compile(S format_str) { + constexpr auto str = basic_string_view(format_str); + if constexpr (str.size() == 0) { + return detail::make_text(str, 0, 0); + } else { + constexpr auto result = + detail::compile_format_string, 0, 0>( + format_str); + return result; + } +} +#endif // defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction) +} // namespace detail + +FMT_BEGIN_EXPORT + +#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction) + +template ::value)> +FMT_INLINE std::basic_string format(const CompiledFormat& cf, + const Args&... args) { + auto s = std::basic_string(); + cf.format(std::back_inserter(s), args...); + return s; +} + +template ::value)> +constexpr FMT_INLINE OutputIt format_to(OutputIt out, const CompiledFormat& cf, + const Args&... args) { + return cf.format(out, args...); +} + +template ::value)> +FMT_INLINE std::basic_string format(const S&, + Args&&... args) { + if constexpr (std::is_same::value) { + constexpr auto str = basic_string_view(S()); + if constexpr (str.size() == 2 && str[0] == '{' && str[1] == '}') { + const auto& first = detail::first(args...); + if constexpr (detail::is_named_arg< + remove_cvref_t>::value) { + return fmt::to_string(first.value); + } else { + return fmt::to_string(first); + } + } + } + constexpr auto compiled = detail::compile(S()); + if constexpr (std::is_same, + detail::unknown_format>()) { + return fmt::format( + static_cast>(S()), + std::forward(args)...); + } else { + return fmt::format(compiled, std::forward(args)...); + } +} + +template ::value)> +FMT_CONSTEXPR OutputIt format_to(OutputIt out, const S&, Args&&... args) { + constexpr auto compiled = detail::compile(S()); + if constexpr (std::is_same, + detail::unknown_format>()) { + return fmt::format_to( + out, static_cast>(S()), + std::forward(args)...); + } else { + return fmt::format_to(out, compiled, std::forward(args)...); + } +} +#endif + +template ::value)> +auto format_to_n(OutputIt out, size_t n, const S& format_str, Args&&... args) + -> format_to_n_result { + using traits = detail::fixed_buffer_traits; + auto buf = detail::iterator_buffer(out, n); + fmt::format_to(std::back_inserter(buf), format_str, + std::forward(args)...); + return {buf.out(), buf.count()}; +} + +template ::value)> +FMT_CONSTEXPR20 auto formatted_size(const S& format_str, const Args&... args) + -> size_t { + return fmt::format_to(detail::counting_iterator(), format_str, args...) + .count(); +} + +template ::value)> +void print(std::FILE* f, const S& format_str, const Args&... args) { + memory_buffer buffer; + fmt::format_to(std::back_inserter(buffer), format_str, args...); + detail::print(f, {buffer.data(), buffer.size()}); +} + +template ::value)> +void print(const S& format_str, const Args&... args) { + print(stdout, format_str, args...); +} + +#if FMT_USE_NONTYPE_TEMPLATE_ARGS +inline namespace literals { +template constexpr auto operator""_cf() { + using char_t = remove_cvref_t; + return detail::udl_compiled_string(); +} +} // namespace literals +#endif + +FMT_END_EXPORT +FMT_END_NAMESPACE + +#endif // FMT_COMPILE_H_ diff --git a/third_party/fmt/include/fmt/core.h b/third_party/fmt/include/fmt/core.h new file mode 100644 index 0000000..b51c140 --- /dev/null +++ b/third_party/fmt/include/fmt/core.h @@ -0,0 +1,2969 @@ +// Formatting library for C++ - the core API for char/UTF-8 +// +// 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 // std::byte +#include // std::FILE +#include // std::strlen +#include +#include +#include // std::addressof +#include +#include + +// The fmt library version in the form major * 10000 + minor * 100 + patch. +#define FMT_VERSION 100201 + +#if defined(__clang__) && !defined(__ibmxl__) +# define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) +#else +# define FMT_CLANG_VERSION 0 +#endif + +#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) && \ + !defined(__NVCOMPILER) +# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) +#else +# define FMT_GCC_VERSION 0 +#endif + +#ifndef FMT_GCC_PRAGMA +// Workaround _Pragma bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59884. +# if FMT_GCC_VERSION >= 504 +# define FMT_GCC_PRAGMA(arg) _Pragma(arg) +# else +# define FMT_GCC_PRAGMA(arg) +# endif +#endif + +#ifdef __ICL +# define FMT_ICC_VERSION __ICL +#elif defined(__INTEL_COMPILER) +# define FMT_ICC_VERSION __INTEL_COMPILER +#else +# define FMT_ICC_VERSION 0 +#endif + +#ifdef _MSC_VER +# define FMT_MSC_VERSION _MSC_VER +# define FMT_MSC_WARNING(...) __pragma(warning(__VA_ARGS__)) +#else +# define FMT_MSC_VERSION 0 +# define FMT_MSC_WARNING(...) +#endif + +#ifdef _MSVC_LANG +# define FMT_CPLUSPLUS _MSVC_LANG +#else +# define FMT_CPLUSPLUS __cplusplus +#endif + +#ifdef __has_feature +# define FMT_HAS_FEATURE(x) __has_feature(x) +#else +# define FMT_HAS_FEATURE(x) 0 +#endif + +#if defined(__has_include) || FMT_ICC_VERSION >= 1600 || FMT_MSC_VERSION > 1900 +# 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) \ + (FMT_CPLUSPLUS >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute)) + +#define FMT_HAS_CPP17_ATTRIBUTE(attribute) \ + (FMT_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 +# if (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VERSION >= 1912 || \ + (FMT_GCC_VERSION >= 600 && FMT_CPLUSPLUS >= 201402L)) && \ + !FMT_ICC_VERSION && (!defined(__NVCC__) || FMT_CPLUSPLUS >= 202002L) +# define FMT_USE_CONSTEXPR 1 +# else +# define FMT_USE_CONSTEXPR 0 +# endif +#endif +#if FMT_USE_CONSTEXPR +# define FMT_CONSTEXPR constexpr +#else +# define FMT_CONSTEXPR +#endif + +#if (FMT_CPLUSPLUS >= 202002L || \ + (FMT_CPLUSPLUS >= 201709L && FMT_GCC_VERSION >= 1002)) && \ + ((!defined(_GLIBCXX_RELEASE) || _GLIBCXX_RELEASE >= 10) && \ + (!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION >= 10000) && \ + (!FMT_MSC_VERSION || FMT_MSC_VERSION >= 1928)) && \ + defined(__cpp_lib_is_constant_evaluated) +# define FMT_CONSTEXPR20 constexpr +#else +# define FMT_CONSTEXPR20 +#endif + +// Check if constexpr std::char_traits<>::{compare,length} are supported. +#if defined(__GLIBCXX__) +# if FMT_CPLUSPLUS >= 201703L && defined(_GLIBCXX_RELEASE) && \ + _GLIBCXX_RELEASE >= 7 // GCC 7+ libstdc++ has _GLIBCXX_RELEASE. +# define FMT_CONSTEXPR_CHAR_TRAITS constexpr +# endif +#elif defined(_LIBCPP_VERSION) && FMT_CPLUSPLUS >= 201703L && \ + _LIBCPP_VERSION >= 4000 +# define FMT_CONSTEXPR_CHAR_TRAITS constexpr +#elif FMT_MSC_VERSION >= 1914 && FMT_CPLUSPLUS >= 201703L +# define FMT_CONSTEXPR_CHAR_TRAITS constexpr +#endif +#ifndef FMT_CONSTEXPR_CHAR_TRAITS +# define FMT_CONSTEXPR_CHAR_TRAITS +#endif + +// Check if exceptions are disabled. +#ifndef FMT_EXCEPTIONS +# if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \ + (FMT_MSC_VERSION && !_HAS_EXCEPTIONS) +# define FMT_EXCEPTIONS 0 +# else +# define FMT_EXCEPTIONS 1 +# endif +#endif + +// Disable [[noreturn]] on MSVC/NVCC because of bogus unreachable code warnings. +#if FMT_EXCEPTIONS && FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VERSION && \ + !defined(__NVCC__) +# define FMT_NORETURN [[noreturn]] +#else +# define FMT_NORETURN +#endif + +#ifndef FMT_NODISCARD +# if FMT_HAS_CPP17_ATTRIBUTE(nodiscard) +# define FMT_NODISCARD [[nodiscard]] +# else +# define FMT_NODISCARD +# endif +#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 + +#ifdef _MSC_VER +# define FMT_UNCHECKED_ITERATOR(It) \ + using _Unchecked_type = It // Mark iterator as checked. +#else +# define FMT_UNCHECKED_ITERATOR(It) using unchecked_type = It +#endif + +#ifndef FMT_BEGIN_NAMESPACE +# define FMT_BEGIN_NAMESPACE \ + namespace fmt { \ + inline namespace v10 { +# define FMT_END_NAMESPACE \ + } \ + } +#endif + +#ifndef FMT_EXPORT +# define FMT_EXPORT +# define FMT_BEGIN_EXPORT +# define FMT_END_EXPORT +#endif + +#if FMT_GCC_VERSION || FMT_CLANG_VERSION +# define FMT_VISIBILITY(value) __attribute__((visibility(value))) +#else +# define FMT_VISIBILITY(value) +#endif + +#if !defined(FMT_HEADER_ONLY) && defined(_WIN32) +# if defined(FMT_LIB_EXPORT) +# define FMT_API __declspec(dllexport) +# elif defined(FMT_SHARED) +# define FMT_API __declspec(dllimport) +# endif +#elif defined(FMT_LIB_EXPORT) || defined(FMT_SHARED) +# define FMT_API FMT_VISIBILITY("default") +#endif +#ifndef FMT_API +# define FMT_API +#endif + +// libc++ supports string_view in pre-c++17. +#if FMT_HAS_INCLUDE() && \ + (FMT_CPLUSPLUS >= 201703L || defined(_LIBCPP_VERSION)) +# include +# define FMT_USE_STRING_VIEW +#elif FMT_HAS_INCLUDE("experimental/string_view") && FMT_CPLUSPLUS >= 201402L +# include +# define FMT_USE_EXPERIMENTAL_STRING_VIEW +#endif + +#ifndef FMT_UNICODE +# define FMT_UNICODE !FMT_MSC_VERSION +#endif + +#ifndef FMT_CONSTEVAL +# if ((FMT_GCC_VERSION >= 1000 || FMT_CLANG_VERSION >= 1101) && \ + (!defined(__apple_build_version__) || \ + __apple_build_version__ >= 14000029L) && \ + FMT_CPLUSPLUS >= 202002L) || \ + (defined(__cpp_consteval) && \ + (!FMT_MSC_VERSION || FMT_MSC_VERSION >= 1929)) +// consteval is broken in MSVC before VS2019 version 16.10 and Apple clang +// before 14. +# define FMT_CONSTEVAL consteval +# define FMT_HAS_CONSTEVAL +# else +# define FMT_CONSTEVAL +# endif +#endif + +#ifndef FMT_USE_NONTYPE_TEMPLATE_ARGS +# if defined(__cpp_nontype_template_args) && \ + ((FMT_GCC_VERSION >= 903 && FMT_CPLUSPLUS >= 201709L) || \ + __cpp_nontype_template_args >= 201911L) && \ + !defined(__NVCOMPILER) && !defined(__LCC__) +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 1 +# else +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 0 +# endif +#endif + +// GCC < 5 requires this-> in decltype +#ifndef FMT_DECLTYPE_THIS +# if FMT_GCC_VERSION && FMT_GCC_VERSION < 500 +# define FMT_DECLTYPE_THIS this-> +# else +# define FMT_DECLTYPE_THIS +# endif +#endif + +// Enable minimal optimizations for more compact code in debug mode. +FMT_GCC_PRAGMA("GCC push_options") +#if !defined(__OPTIMIZE__) && !defined(__NVCOMPILER) && !defined(__LCC__) && \ + !defined(__CUDACC__) +FMT_GCC_PRAGMA("GCC optimize(\"Og\")") +#endif + +FMT_BEGIN_NAMESPACE + +// Implementations of enable_if_t and other metafunctions for older systems. +template +using enable_if_t = typename std::enable_if::type; +template +using conditional_t = typename std::conditional::type; +template using bool_constant = std::integral_constant; +template +using remove_reference_t = typename std::remove_reference::type; +template +using remove_const_t = typename std::remove_const::type; +template +using remove_cvref_t = typename std::remove_cv>::type; +template struct type_identity { + using type = T; +}; +template using type_identity_t = typename type_identity::type; +template +using underlying_t = typename std::underlying_type::type; + +// Checks whether T is a container with contiguous storage. +template struct is_contiguous : std::false_type {}; +template +struct is_contiguous> : std::true_type {}; + +struct monostate { + constexpr 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). +#ifdef FMT_DOC +# define FMT_ENABLE_IF(...) +#else +# define FMT_ENABLE_IF(...) fmt::enable_if_t<(__VA_ARGS__), int> = 0 +#endif + +// This is defined in core.h instead of format.h to avoid injecting in std. +// It is a template to avoid undesirable implicit conversions to std::byte. +#ifdef __cpp_lib_byte +template ::value)> +inline auto format_as(T b) -> unsigned char { + return static_cast(b); +} +#endif + +namespace detail { +// Suppresses "unused variable" warnings with the method described in +// https://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/. +// (void)var does not work on many Intel compilers. +template FMT_CONSTEXPR void ignore_unused(const T&...) {} + +constexpr FMT_INLINE auto is_constant_evaluated( + bool default_value = false) noexcept -> bool { +// Workaround for incompatibility between libstdc++ consteval-based +// std::is_constant_evaluated() implementation and clang-14. +// https://github.com/fmtlib/fmt/issues/3247 +#if FMT_CPLUSPLUS >= 202002L && defined(_GLIBCXX_RELEASE) && \ + _GLIBCXX_RELEASE >= 12 && \ + (FMT_CLANG_VERSION >= 1400 && FMT_CLANG_VERSION < 1500) + ignore_unused(default_value); + return __builtin_is_constant_evaluated(); +#elif defined(__cpp_lib_is_constant_evaluated) + ignore_unused(default_value); + return std::is_constant_evaluated(); +#else + return default_value; +#endif +} + +// Suppresses "conditional expression is constant" warnings. +template constexpr FMT_INLINE auto const_check(T value) -> T { + 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 -Wempty-body. +# define FMT_ASSERT(condition, message) \ + fmt::detail::ignore_unused((condition), (message)) +# 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 using std_string_view = std::basic_string_view; +#elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW) +template +using std_string_view = std::experimental::basic_string_view; +#else +template struct std_string_view {}; +#endif + +#ifdef FMT_USE_INT128 +// Do nothing. +#elif defined(__SIZEOF_INT128__) && !defined(__NVCC__) && \ + !(FMT_CLANG_VERSION && FMT_MSC_VERSION) +# define FMT_USE_INT128 1 +using int128_opt = __int128_t; // An optional native 128-bit integer. +using uint128_opt = __uint128_t; +template inline auto convert_for_visit(T value) -> T { + return value; +} +#else +# define FMT_USE_INT128 0 +#endif +#if !FMT_USE_INT128 +enum class int128_opt {}; +enum class uint128_opt {}; +// Reduce template instantiations. +template auto convert_for_visit(T) -> monostate { return {}; } +#endif + +// Casts a nonnegative integer to unsigned. +template +FMT_CONSTEXPR auto to_unsigned(Int value) -> + typename std::make_unsigned::type { + FMT_ASSERT(std::is_unsigned::value || value >= 0, "negative value"); + return static_cast::type>(value); +} + +FMT_CONSTEXPR inline auto is_utf8() -> bool { + FMT_MSC_WARNING(suppress : 4566) constexpr unsigned char section[] = "\u00A7"; + + // Avoid buggy sign extensions in MSVC's constant evaluation mode (#2297). + using uchar = unsigned char; + return FMT_UNICODE || (sizeof(section) == 3 && uchar(section[0]) == 0xC2 && + uchar(section[1]) == 0xA7); +} +} // namespace detail + +/** + 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). + */ +FMT_EXPORT +template class basic_string_view { + private: + const Char* data_; + size_t size_; + + public: + using value_type = Char; + using iterator = const Char*; + + constexpr basic_string_view() 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) noexcept + : data_(s), size_(count) {} + + /** + \rst + Constructs a string reference object from a C string computing + the size with ``std::char_traits::length``. + \endrst + */ + FMT_CONSTEXPR_CHAR_TRAITS + FMT_INLINE + basic_string_view(const Char* s) + : data_(s), + size_(detail::const_check(std::is_same::value && + !detail::is_constant_evaluated(true)) + ? std::strlen(reinterpret_cast(s)) + : std::char_traits::length(s)) {} + + /** Constructs a string reference from a ``std::basic_string`` object. */ + template + FMT_CONSTEXPR basic_string_view( + const std::basic_string& s) noexcept + : data_(s.data()), size_(s.size()) {} + + template >::value)> + FMT_CONSTEXPR basic_string_view(S s) noexcept + : data_(s.data()), size_(s.size()) {} + + /** Returns a pointer to the string data. */ + constexpr auto data() const noexcept -> const Char* { return data_; } + + /** Returns the string size. */ + constexpr auto size() const noexcept -> size_t { return size_; } + + constexpr auto begin() const noexcept -> iterator { return data_; } + constexpr auto end() const noexcept -> iterator { return data_ + size_; } + + constexpr auto operator[](size_t pos) const noexcept -> const Char& { + return data_[pos]; + } + + FMT_CONSTEXPR void remove_prefix(size_t n) noexcept { + data_ += n; + size_ -= n; + } + + FMT_CONSTEXPR_CHAR_TRAITS auto starts_with( + basic_string_view sv) const noexcept -> bool { + return size_ >= sv.size_ && + std::char_traits::compare(data_, sv.data_, sv.size_) == 0; + } + FMT_CONSTEXPR_CHAR_TRAITS auto starts_with(Char c) const noexcept -> bool { + return size_ >= 1 && std::char_traits::eq(*data_, c); + } + FMT_CONSTEXPR_CHAR_TRAITS auto starts_with(const Char* s) const -> bool { + return starts_with(basic_string_view(s)); + } + + // Lexicographically compare this string reference to other. + FMT_CONSTEXPR_CHAR_TRAITS auto compare(basic_string_view other) const -> int { + size_t str_size = size_ < other.size_ ? size_ : other.size_; + int result = std::char_traits::compare(data_, other.data_, str_size); + if (result == 0) + result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1); + return result; + } + + FMT_CONSTEXPR_CHAR_TRAITS friend auto operator==(basic_string_view lhs, + basic_string_view rhs) + -> bool { + return lhs.compare(rhs) == 0; + } + friend auto operator!=(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) != 0; + } + friend auto operator<(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) < 0; + } + friend auto operator<=(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) <= 0; + } + friend auto operator>(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) > 0; + } + friend auto operator>=(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) >= 0; + } +}; + +FMT_EXPORT +using string_view = basic_string_view; + +/** Specifies if ``T`` is a character type. Can be specialized by users. */ +FMT_EXPORT +template struct is_char : std::false_type {}; +template <> struct is_char : std::true_type {}; + +namespace detail { + +// A base class for compile-time strings. +struct compile_string {}; + +template +struct is_compile_string : std::is_base_of {}; + +template ::value)> +FMT_INLINE auto to_string_view(const Char* s) -> basic_string_view { + return s; +} +template +inline auto to_string_view(const std::basic_string& s) + -> basic_string_view { + return s; +} +template +constexpr auto to_string_view(basic_string_view s) + -> basic_string_view { + return s; +} +template >::value)> +inline auto to_string_view(std_string_view s) -> basic_string_view { + return s; +} +template ::value)> +constexpr auto to_string_view(const S& s) + -> basic_string_view { + return basic_string_view(s); +} +void 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. +// ADL is intentionally disabled as to_string_view is not an extension point. +template +struct is_string + : std::is_class()))> {}; + +template struct char_t_impl {}; +template struct char_t_impl::value>> { + using result = decltype(to_string_view(std::declval())); + using type = typename result::value_type; +}; + +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 +struct type_constant : std::integral_constant {}; + +#define FMT_TYPE_CONSTANT(Type, constant) \ + template \ + struct type_constant \ + : std::integral_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_opt, int128_type); +FMT_TYPE_CONSTANT(uint128_opt, 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, string_type); +FMT_TYPE_CONSTANT(const void*, pointer_type); + +constexpr auto is_integral_type(type t) -> bool { + return t > type::none_type && t <= type::last_integer_type; +} +constexpr auto is_arithmetic_type(type t) -> bool { + return t > type::none_type && t <= type::last_numeric_type; +} + +constexpr auto set(type rhs) -> int { return 1 << static_cast(rhs); } +constexpr auto in(type t, int set) -> bool { + return ((set >> static_cast(t)) & 1) != 0; +} + +// Bitsets of types. +enum { + sint_set = + set(type::int_type) | set(type::long_long_type) | set(type::int128_type), + uint_set = set(type::uint_type) | set(type::ulong_long_type) | + set(type::uint128_type), + bool_set = set(type::bool_type), + char_set = set(type::char_type), + float_set = set(type::float_type) | set(type::double_type) | + set(type::long_double_type), + string_set = set(type::string_type), + cstring_set = set(type::cstring_type), + pointer_set = set(type::pointer_type) +}; + +// DEPRECATED! +FMT_NORETURN FMT_API void throw_format_error(const char* message); + +struct error_handler { + constexpr error_handler() = default; + + // This function is intentionally not constexpr to give a compile-time error. + FMT_NORETURN void on_error(const char* message) { + throw_format_error(message); + } +}; +} // namespace detail + +/** Throws ``format_error`` with a given message. */ +using detail::throw_format_error; + +/** String's character type. */ +template using char_t = typename detail::char_t_impl::type; + +/** + \rst + Parsing context consisting of a format string range being parsed and an + argument counter for automatic indexing. + You can use the ``format_parse_context`` type alias for ``char`` instead. + \endrst + */ +FMT_EXPORT +template class basic_format_parse_context { + private: + basic_string_view format_str_; + int next_arg_id_; + + FMT_CONSTEXPR void do_check_arg_id(int id); + + public: + using char_type = Char; + using iterator = const Char*; + + explicit constexpr basic_format_parse_context( + basic_string_view format_str, int next_arg_id = 0) + : format_str_(format_str), next_arg_id_(next_arg_id) {} + + /** + Returns an iterator to the beginning of the format string range being + parsed. + */ + constexpr auto begin() const noexcept -> iterator { + return format_str_.begin(); + } + + /** + Returns an iterator past the end of the format string range being parsed. + */ + constexpr auto end() const noexcept -> iterator { 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 auto next_arg_id() -> int { + if (next_arg_id_ < 0) { + detail::throw_format_error( + "cannot switch from manual to automatic argument indexing"); + return 0; + } + int id = next_arg_id_++; + do_check_arg_id(id); + return id; + } + + /** + Reports an error if using the automatic argument indexing; otherwise + switches to the manual indexing. + */ + FMT_CONSTEXPR void check_arg_id(int id) { + if (next_arg_id_ > 0) { + detail::throw_format_error( + "cannot switch from automatic to manual argument indexing"); + return; + } + next_arg_id_ = -1; + do_check_arg_id(id); + } + FMT_CONSTEXPR void check_arg_id(basic_string_view) {} + FMT_CONSTEXPR void check_dynamic_spec(int arg_id); +}; + +FMT_EXPORT +using format_parse_context = basic_format_parse_context; + +namespace detail { +// A parse context with extra data used only in compile-time checks. +template +class compile_parse_context : public basic_format_parse_context { + private: + int num_args_; + const type* types_; + using base = basic_format_parse_context; + + public: + explicit FMT_CONSTEXPR compile_parse_context( + basic_string_view format_str, int num_args, const type* types, + int next_arg_id = 0) + : base(format_str, next_arg_id), num_args_(num_args), types_(types) {} + + constexpr auto num_args() const -> int { return num_args_; } + constexpr auto arg_type(int id) const -> type { return types_[id]; } + + FMT_CONSTEXPR auto next_arg_id() -> int { + int id = base::next_arg_id(); + if (id >= num_args_) throw_format_error("argument not found"); + return id; + } + + FMT_CONSTEXPR void check_arg_id(int id) { + base::check_arg_id(id); + if (id >= num_args_) throw_format_error("argument not found"); + } + using base::check_arg_id; + + FMT_CONSTEXPR void check_dynamic_spec(int arg_id) { + detail::ignore_unused(arg_id); +#if !defined(__LCC__) + if (arg_id < num_args_ && types_ && !is_integral_type(types_[arg_id])) + throw_format_error("width/precision is not integer"); +#endif + } +}; + +// Extracts a reference to the container from back_insert_iterator. +template +inline auto get_container(std::back_insert_iterator it) + -> Container& { + using base = std::back_insert_iterator; + struct accessor : base { + accessor(base b) : base(b) {} + using base::container; + }; + return *accessor(it).container; +} + +template +FMT_CONSTEXPR auto copy_str(InputIt begin, InputIt end, OutputIt out) + -> OutputIt { + while (begin != end) *out++ = static_cast(*begin++); + return out; +} + +template , U>::value&& is_char::value)> +FMT_CONSTEXPR auto copy_str(T* begin, T* end, U* out) -> U* { + if (is_constant_evaluated()) return copy_str(begin, end, out); + auto size = to_unsigned(end - begin); + if (size > 0) memcpy(out, begin, size * sizeof(U)); + return out + size; +} + +/** + \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 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_MSC_WARNING(suppress : 26495) + FMT_CONSTEXPR buffer(size_t sz) noexcept : size_(sz), capacity_(sz) {} + + FMT_CONSTEXPR20 buffer(T* p = nullptr, size_t sz = 0, size_t cap = 0) noexcept + : ptr_(p), size_(sz), capacity_(cap) {} + + FMT_CONSTEXPR20 ~buffer() = default; + buffer(buffer&&) = default; + + /** Sets the buffer data and capacity. */ + FMT_CONSTEXPR void set(T* buf_data, size_t buf_capacity) noexcept { + ptr_ = buf_data; + capacity_ = buf_capacity; + } + + /** Increases the buffer capacity to hold at least *capacity* elements. */ + // DEPRECATED! + virtual FMT_CONSTEXPR20 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; + + FMT_INLINE auto begin() noexcept -> T* { return ptr_; } + FMT_INLINE auto end() noexcept -> T* { return ptr_ + size_; } + + FMT_INLINE auto begin() const noexcept -> const T* { return ptr_; } + FMT_INLINE auto end() const noexcept -> const T* { return ptr_ + size_; } + + /** Returns the size of this buffer. */ + constexpr auto size() const noexcept -> size_t { return size_; } + + /** Returns the capacity of this buffer. */ + constexpr auto capacity() const noexcept -> size_t { return capacity_; } + + /** Returns a pointer to the buffer data (not null-terminated). */ + FMT_CONSTEXPR auto data() noexcept -> T* { return ptr_; } + FMT_CONSTEXPR auto data() const noexcept -> const T* { 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. + FMT_CONSTEXPR20 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. + FMT_CONSTEXPR20 void try_reserve(size_t new_capacity) { + if (new_capacity > capacity_) grow(new_capacity); + } + + FMT_CONSTEXPR20 void push_back(const T& value) { + try_reserve(size_ + 1); + ptr_[size_++] = value; + } + + /** Appends data to the end of the buffer. */ + template void append(const U* begin, const U* end); + + template FMT_CONSTEXPR auto operator[](Idx index) -> T& { + return ptr_[index]; + } + template + FMT_CONSTEXPR auto operator[](Idx index) const -> const T& { + return ptr_[index]; + } +}; + +struct buffer_traits { + explicit buffer_traits(size_t) {} + auto count() const -> size_t { return 0; } + auto limit(size_t size) -> size_t { return size; } +}; + +class fixed_buffer_traits { + private: + size_t count_ = 0; + size_t limit_; + + public: + explicit fixed_buffer_traits(size_t limit) : limit_(limit) {} + auto count() const -> size_t { return count_; } + auto limit(size_t size) -> size_t { + 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 +class iterator_buffer final : public Traits, public buffer { + private: + OutputIt out_; + enum { buffer_size = 256 }; + T data_[buffer_size]; + + protected: + FMT_CONSTEXPR20 void grow(size_t) override { + if (this->size() == buffer_size) flush(); + } + + void flush() { + auto size = this->size(); + this->clear(); + out_ = copy_str(data_, data_ + this->limit(size), out_); + } + + public: + explicit iterator_buffer(OutputIt out, size_t n = buffer_size) + : Traits(n), buffer(data_, 0, buffer_size), out_(out) {} + iterator_buffer(iterator_buffer&& other) + : Traits(other), buffer(data_, 0, buffer_size), out_(other.out_) {} + ~iterator_buffer() { flush(); } + + auto out() -> OutputIt { + flush(); + return out_; + } + auto count() const -> size_t { return Traits::count() + this->size(); } +}; + +template +class iterator_buffer final + : public fixed_buffer_traits, + public buffer { + private: + T* out_; + enum { buffer_size = 256 }; + T data_[buffer_size]; + + protected: + FMT_CONSTEXPR20 void grow(size_t) override { + if (this->size() == this->capacity()) flush(); + } + + void flush() { + size_t n = this->limit(this->size()); + if (this->data() == out_) { + out_ += n; + this->set(data_, buffer_size); + } + this->clear(); + } + + public: + explicit iterator_buffer(T* out, size_t n = buffer_size) + : fixed_buffer_traits(n), buffer(out, 0, n), out_(out) {} + iterator_buffer(iterator_buffer&& other) + : fixed_buffer_traits(other), + buffer(std::move(other)), + out_(other.out_) { + if (this->data() != out_) { + this->set(data_, buffer_size); + this->clear(); + } + } + ~iterator_buffer() { flush(); } + + auto out() -> T* { + flush(); + return out_; + } + auto count() const -> size_t { + return fixed_buffer_traits::count() + this->size(); + } +}; + +template class iterator_buffer final : public buffer { + protected: + FMT_CONSTEXPR20 void grow(size_t) override {} + + public: + explicit iterator_buffer(T* out, size_t = 0) : buffer(out, 0, ~size_t()) {} + + auto out() -> T* { return &*this->end(); } +}; + +// A buffer that writes to a container with the contiguous storage. +template +class iterator_buffer, + enable_if_t::value, + typename Container::value_type>> + final : public buffer { + private: + Container& container_; + + protected: + FMT_CONSTEXPR20 void grow(size_t capacity) override { + container_.resize(capacity); + this->set(&container_[0], capacity); + } + + public: + explicit iterator_buffer(Container& c) + : buffer(c.size()), container_(c) {} + explicit iterator_buffer(std::back_insert_iterator out, size_t = 0) + : iterator_buffer(get_container(out)) {} + + auto out() -> std::back_insert_iterator { + return std::back_inserter(container_); + } +}; + +// A buffer that counts the number of code units written discarding the output. +template class counting_buffer final : public buffer { + private: + enum { buffer_size = 256 }; + T data_[buffer_size]; + size_t count_ = 0; + + protected: + FMT_CONSTEXPR20 void grow(size_t) override { + if (this->size() != buffer_size) return; + count_ += this->size(); + this->clear(); + } + + public: + counting_buffer() : buffer(data_, 0, buffer_size) {} + + auto count() -> size_t { return count_ + this->size(); } +}; +} // namespace detail + +template +FMT_CONSTEXPR void basic_format_parse_context::do_check_arg_id(int id) { + // Argument id is only checked at compile-time during parsing because + // formatting has its own validation. + if (detail::is_constant_evaluated() && + (!FMT_GCC_VERSION || FMT_GCC_VERSION >= 1200)) { + using context = detail::compile_parse_context; + if (id >= static_cast(this)->num_args()) + detail::throw_format_error("argument not found"); + } +} + +template +FMT_CONSTEXPR void basic_format_parse_context::check_dynamic_spec( + int arg_id) { + if (detail::is_constant_evaluated() && + (!FMT_GCC_VERSION || FMT_GCC_VERSION >= 1200)) { + using context = detail::compile_parse_context; + static_cast(this)->check_dynamic_spec(arg_id); + } +} + +FMT_EXPORT template class basic_format_arg; +FMT_EXPORT template class basic_format_args; +FMT_EXPORT template class dynamic_format_arg_store; + +// A formatter for objects of type T. +FMT_EXPORT +template +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 +using has_formatter = + std::is_constructible>; + +// An output iterator that appends to a buffer. +// It is used to reduce symbol sizes for the common case. +class appender : public std::back_insert_iterator> { + using base = std::back_insert_iterator>; + + public: + using std::back_insert_iterator>::back_insert_iterator; + appender(base it) noexcept : base(it) {} + FMT_UNCHECKED_ITERATOR(appender); + + auto operator++() noexcept -> appender& { return *this; } + auto operator++(int) noexcept -> appender { return *this; } +}; + +namespace detail { + +template +constexpr auto has_const_formatter_impl(T*) + -> decltype(typename Context::template formatter_type().format( + std::declval(), std::declval()), + true) { + return true; +} +template +constexpr auto has_const_formatter_impl(...) -> bool { + return false; +} +template +constexpr auto has_const_formatter() -> bool { + return has_const_formatter_impl(static_cast(nullptr)); +} + +template +using buffer_appender = conditional_t::value, appender, + std::back_insert_iterator>>; + +// Maps an output iterator to a buffer. +template +auto get_buffer(OutputIt out) -> iterator_buffer { + return iterator_buffer(out); +} +template , Buf>::value)> +auto get_buffer(std::back_insert_iterator out) -> buffer& { + return get_container(out); +} + +template +FMT_INLINE auto get_iterator(Buf& buf, OutputIt) -> decltype(buf.out()) { + return buf.out(); +} +template +auto get_iterator(buffer&, OutputIt out) -> OutputIt { + return out; +} + +struct view {}; + +template struct named_arg : view { + const Char* name; + const T& value; + named_arg(const Char* n, const T& v) : name(n), value(v) {} +}; + +template struct named_arg_info { + const Char* name; + int id; +}; + +template +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 named_args_[NUM_NAMED_ARGS]; + + template + arg_data(const U&... init) : args_{T(named_args_, NUM_NAMED_ARGS), init...} {} + arg_data(const arg_data& other) = delete; + auto args() const -> const T* { return args_ + 1; } + auto named_args() -> named_arg_info* { return named_args_; } +}; + +template +struct arg_data { + // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning. + T args_[NUM_ARGS != 0 ? NUM_ARGS : +1]; + + template + FMT_CONSTEXPR FMT_INLINE arg_data(const U&... init) : args_{init...} {} + FMT_CONSTEXPR FMT_INLINE auto args() const -> const T* { return args_; } + FMT_CONSTEXPR FMT_INLINE auto named_args() -> std::nullptr_t { + return nullptr; + } +}; + +template +inline void init_named_args(named_arg_info*, int, int) {} + +template struct is_named_arg : std::false_type {}; +template struct is_statically_named_arg : std::false_type {}; + +template +struct is_named_arg> : std::true_type {}; + +template ::value)> +void init_named_args(named_arg_info* 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 ::value)> +void init_named_args(named_arg_info* named_args, int arg_count, + int named_arg_count, const 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 +FMT_CONSTEXPR FMT_INLINE void init_named_args(std::nullptr_t, int, int, + const Args&...) {} + +template constexpr auto count() -> size_t { return B ? 1 : 0; } +template constexpr auto count() -> size_t { + return (B1 ? 1 : 0) + count(); +} + +template constexpr auto count_named_args() -> size_t { + return count::value...>(); +} + +template +constexpr auto count_statically_named_args() -> size_t { + return count::value...>(); +} + +struct unformattable {}; +struct unformattable_char : unformattable {}; +struct unformattable_pointer : unformattable {}; + +template struct string_value { + const Char* data; + size_t size; +}; + +template struct named_arg_value { + const named_arg_info* data; + size_t size; +}; + +template struct custom_value { + using parse_context = typename Context::parse_context_type; + void* value; + void (*format)(void* arg, parse_context& parse_ctx, Context& ctx); +}; + +// A formatting argument value. +template class value { + public: + using char_type = typename Context::char_type; + + union { + monostate no_value; + int int_value; + unsigned uint_value; + long long long_long_value; + unsigned long long ulong_long_value; + int128_opt int128_value; + uint128_opt 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 string; + custom_value custom; + named_arg_value named_args; + }; + + constexpr FMT_INLINE value() : no_value() {} + constexpr FMT_INLINE value(int val) : int_value(val) {} + constexpr FMT_INLINE value(unsigned val) : uint_value(val) {} + constexpr FMT_INLINE value(long long val) : long_long_value(val) {} + constexpr FMT_INLINE value(unsigned long long val) : ulong_long_value(val) {} + FMT_INLINE value(int128_opt val) : int128_value(val) {} + FMT_INLINE value(uint128_opt val) : uint128_value(val) {} + constexpr FMT_INLINE value(float val) : float_value(val) {} + constexpr FMT_INLINE value(double val) : double_value(val) {} + FMT_INLINE value(long double val) : long_double_value(val) {} + constexpr FMT_INLINE value(bool val) : bool_value(val) {} + constexpr FMT_INLINE value(char_type val) : char_value(val) {} + FMT_CONSTEXPR FMT_INLINE value(const char_type* val) { + string.data = val; + if (is_constant_evaluated()) string.size = {}; + } + FMT_CONSTEXPR FMT_INLINE value(basic_string_view val) { + string.data = val.data(); + string.size = val.size(); + } + FMT_INLINE value(const void* val) : pointer(val) {} + FMT_INLINE value(const named_arg_info* args, size_t size) + : named_args{args, size} {} + + template FMT_CONSTEXPR20 FMT_INLINE value(T& val) { + using value_type = remove_const_t; + custom.value = const_cast(std::addressof(val)); + // Get the formatter type through the context to allow different contexts + // have different extension points, e.g. `formatter` for `format` and + // `printf_formatter` for `printf`. + custom.format = format_custom_arg< + value_type, typename Context::template formatter_type>; + } + value(unformattable); + value(unformattable_char); + value(unformattable_pointer); + + private: + // Formats an argument of a custom type, such as a user-defined class. + template + static void format_custom_arg(void* arg, + typename Context::parse_context_type& parse_ctx, + Context& ctx) { + auto f = Formatter(); + parse_ctx.advance_to(f.parse(parse_ctx)); + using qualified_type = + conditional_t(), const T, T>; + // Calling format through a mutable reference is deprecated. + ctx.advance_to(f.format(*static_cast(arg), ctx)); + } +}; + +// 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; +using ulong_type = conditional_t; + +template struct format_as_result { + template ::value || std::is_class::value)> + static auto map(U*) -> remove_cvref_t()))>; + static auto map(...) -> void; + + using type = decltype(map(static_cast(nullptr))); +}; +template using format_as_t = typename format_as_result::type; + +template +struct has_format_as + : bool_constant, void>::value> {}; + +// Maps formatting arguments to core types. +// arg_mapper reports errors by returning unformattable instead of using +// static_assert because it's used in the is_formattable trait. +template struct arg_mapper { + using char_type = typename Context::char_type; + + FMT_CONSTEXPR FMT_INLINE auto map(signed char val) -> int { return val; } + FMT_CONSTEXPR FMT_INLINE auto map(unsigned char val) -> unsigned { + return val; + } + FMT_CONSTEXPR FMT_INLINE auto map(short val) -> int { return val; } + FMT_CONSTEXPR FMT_INLINE auto map(unsigned short val) -> unsigned { + return val; + } + FMT_CONSTEXPR FMT_INLINE auto map(int val) -> int { return val; } + FMT_CONSTEXPR FMT_INLINE auto map(unsigned val) -> unsigned { return val; } + FMT_CONSTEXPR FMT_INLINE auto map(long val) -> long_type { return val; } + FMT_CONSTEXPR FMT_INLINE auto map(unsigned long val) -> ulong_type { + return val; + } + FMT_CONSTEXPR FMT_INLINE auto map(long long val) -> long long { return val; } + FMT_CONSTEXPR FMT_INLINE auto map(unsigned long long val) + -> unsigned long long { + return val; + } + FMT_CONSTEXPR FMT_INLINE auto map(int128_opt val) -> int128_opt { + return val; + } + FMT_CONSTEXPR FMT_INLINE auto map(uint128_opt val) -> uint128_opt { + return val; + } + FMT_CONSTEXPR FMT_INLINE auto map(bool val) -> bool { return val; } + + template ::value || + std::is_same::value)> + FMT_CONSTEXPR FMT_INLINE auto map(T val) -> char_type { + return val; + } + template ::value || +#ifdef __cpp_char8_t + std::is_same::value || +#endif + std::is_same::value || + std::is_same::value) && + !std::is_same::value, + int> = 0> + FMT_CONSTEXPR FMT_INLINE auto map(T) -> unformattable_char { + return {}; + } + + FMT_CONSTEXPR FMT_INLINE auto map(float val) -> float { return val; } + FMT_CONSTEXPR FMT_INLINE auto map(double val) -> double { return val; } + FMT_CONSTEXPR FMT_INLINE auto map(long double val) -> long double { + return val; + } + + FMT_CONSTEXPR FMT_INLINE auto map(char_type* val) -> const char_type* { + return val; + } + FMT_CONSTEXPR FMT_INLINE auto map(const char_type* val) -> const char_type* { + return val; + } + template ::value && !std::is_pointer::value && + std::is_same>::value)> + FMT_CONSTEXPR FMT_INLINE auto map(const T& val) + -> basic_string_view { + return to_string_view(val); + } + template ::value && !std::is_pointer::value && + !std::is_same>::value)> + FMT_CONSTEXPR FMT_INLINE auto map(const T&) -> unformattable_char { + return {}; + } + + FMT_CONSTEXPR FMT_INLINE auto map(void* val) -> const void* { return val; } + FMT_CONSTEXPR FMT_INLINE auto map(const void* val) -> const void* { + return val; + } + FMT_CONSTEXPR FMT_INLINE auto map(std::nullptr_t val) -> const void* { + return val; + } + + // Use SFINAE instead of a const T* parameter to avoid a conflict with the + // array overload. + template < + typename T, + FMT_ENABLE_IF( + std::is_pointer::value || std::is_member_pointer::value || + std::is_function::type>::value || + (std::is_array::value && + !std::is_convertible::value))> + FMT_CONSTEXPR auto map(const T&) -> unformattable_pointer { + return {}; + } + + template ::value)> + FMT_CONSTEXPR FMT_INLINE auto map(const T (&values)[N]) -> const T (&)[N] { + return values; + } + + // Only map owning types because mapping views can be unsafe. + template , + FMT_ENABLE_IF(std::is_arithmetic::value)> + FMT_CONSTEXPR FMT_INLINE auto map(const T& val) + -> decltype(FMT_DECLTYPE_THIS map(U())) { + return map(format_as(val)); + } + + template > + struct formattable : bool_constant() || + (has_formatter::value && + !std::is_const::value)> {}; + + template ::value)> + FMT_CONSTEXPR FMT_INLINE auto do_map(T& val) -> T& { + return val; + } + template ::value)> + FMT_CONSTEXPR FMT_INLINE auto do_map(T&) -> unformattable { + return {}; + } + + template , + FMT_ENABLE_IF((std::is_class::value || std::is_enum::value || + std::is_union::value) && + !is_string::value && !is_char::value && + !is_named_arg::value && + !std::is_arithmetic>::value)> + FMT_CONSTEXPR FMT_INLINE auto map(T& val) + -> decltype(FMT_DECLTYPE_THIS do_map(val)) { + return do_map(val); + } + + template ::value)> + FMT_CONSTEXPR FMT_INLINE auto map(const T& named_arg) + -> decltype(FMT_DECLTYPE_THIS map(named_arg.value)) { + return map(named_arg.value); + } + + auto map(...) -> unformattable { return {}; } +}; + +// A type constant after applying arg_mapper. +template +using mapped_type_constant = + type_constant().map(std::declval())), + 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 }; + +template +auto copy_str(InputIt begin, InputIt end, appender out) -> appender { + get_container(out).append(begin, end); + return out; +} +template +auto copy_str(InputIt begin, InputIt end, + std::back_insert_iterator out) + -> std::back_insert_iterator { + get_container(out).append(begin, end); + return out; +} + +template +FMT_CONSTEXPR auto copy_str(R&& rng, OutputIt out) -> OutputIt { + return detail::copy_str(rng.begin(), rng.end(), out); +} + +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 500 +// A workaround for gcc 4.8 to make void_t work in a SFINAE context. +template struct void_t_impl { + using type = void; +}; +template using void_t = typename void_t_impl::type; +#else +template using void_t = void; +#endif + +template +struct is_output_iterator : std::false_type {}; + +template +struct is_output_iterator< + It, T, + void_t::iterator_category, + decltype(*std::declval() = std::declval())>> + : std::true_type {}; + +template struct is_back_insert_iterator : std::false_type {}; +template +struct is_back_insert_iterator> + : std::true_type {}; + +// A type-erased reference to an std::locale to avoid a heavy include. +class locale_ref { + private: + const void* locale_; // A type-erased pointer to std::locale. + + public: + constexpr FMT_INLINE locale_ref() : locale_(nullptr) {} + template explicit locale_ref(const Locale& loc); + + explicit operator bool() const noexcept { return locale_ != nullptr; } + + template auto get() const -> Locale; +}; + +template constexpr auto encode_types() -> unsigned long long { + return 0; +} + +template +constexpr auto encode_types() -> unsigned long long { + return static_cast(mapped_type_constant::value) | + (encode_types() << packed_arg_bits); +} + +#if defined(__cpp_if_constexpr) +// This type is intentionally undefined, only used for errors +template struct type_is_unformattable_for; +#endif + +template +FMT_CONSTEXPR FMT_INLINE auto make_arg(T& val) -> value { + using arg_type = remove_cvref_t().map(val))>; + + constexpr bool formattable_char = + !std::is_same::value; + static_assert(formattable_char, "Mixing character types is disallowed."); + + // Formatting of arbitrary pointers is disallowed. If you want to format a + // pointer cast it to `void*` or `const void*`. In particular, this forbids + // formatting of `[const] volatile char*` printed as bool by iostreams. + constexpr bool formattable_pointer = + !std::is_same::value; + static_assert(formattable_pointer, + "Formatting of non-void pointers is disallowed."); + + constexpr bool formattable = !std::is_same::value; +#if defined(__cpp_if_constexpr) + if constexpr (!formattable) { + type_is_unformattable_for _; + } +#endif + static_assert( + formattable, + "Cannot format an argument. To make type T formattable provide a " + "formatter specialization: https://fmt.dev/latest/api.html#udt"); + return {arg_mapper().map(val)}; +} + +template +FMT_CONSTEXPR auto make_arg(T& val) -> basic_format_arg { + auto arg = basic_format_arg(); + arg.type_ = mapped_type_constant::value; + arg.value_ = make_arg(val); + return arg; +} + +template +FMT_CONSTEXPR inline auto make_arg(T& val) -> basic_format_arg { + return make_arg(val); +} +} // namespace detail +FMT_BEGIN_EXPORT + +// A formatting argument. Context is a template parameter for the compiled API +// where output can be unbuffered. +template class basic_format_arg { + private: + detail::value value_; + detail::type type_; + + template + friend FMT_CONSTEXPR auto detail::make_arg(T& value) + -> basic_format_arg; + + template + friend FMT_CONSTEXPR auto visit_format_arg(Visitor&& vis, + const basic_format_arg& arg) + -> decltype(vis(0)); + + friend class basic_format_args; + friend class dynamic_format_arg_store; + + using char_type = typename Context::char_type; + + template + friend struct detail::arg_data; + + basic_format_arg(const detail::named_arg_info* args, size_t size) + : value_(args, size) {} + + public: + class handle { + public: + explicit handle(detail::custom_value 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 custom_; + }; + + constexpr basic_format_arg() : type_(detail::type::none_type) {} + + constexpr explicit operator bool() const noexcept { + return type_ != detail::type::none_type; + } + + auto type() const -> detail::type { return type_; } + + auto is_integral() const -> bool { return detail::is_integral_type(type_); } + auto is_arithmetic() const -> bool { + return detail::is_arithmetic_type(type_); + } + + FMT_INLINE auto format_custom(const char_type* parse_begin, + typename Context::parse_context_type& parse_ctx, + Context& ctx) -> bool { + if (type_ != detail::type::custom_type) return false; + parse_ctx.advance_to(parse_begin); + value_.custom.format(value_.custom.value, parse_ctx, ctx); + return true; + } +}; + +/** + \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 + */ +// DEPRECATED! +template +FMT_CONSTEXPR FMT_INLINE auto visit_format_arg( + Visitor&& vis, const basic_format_arg& arg) -> decltype(vis(0)) { + 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); + case detail::type::int128_type: + return vis(detail::convert_for_visit(arg.value_.int128_value)); + case detail::type::uint128_type: + return vis(detail::convert_for_visit(arg.value_.uint128_value)); + 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: + using sv = basic_string_view; + return vis(sv(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::handle(arg.value_.custom)); + } + return vis(monostate()); +} + +// Formatting context. +template class basic_format_context { + private: + OutputIt out_; + basic_format_args args_; + detail::locale_ref loc_; + + public: + using iterator = OutputIt; + using format_arg = basic_format_arg; + using format_args = basic_format_args; + using parse_context_type = basic_format_parse_context; + template using formatter_type = formatter; + + /** The character type for the output. */ + using char_type = Char; + + basic_format_context(basic_format_context&&) = default; + 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. + */ + constexpr basic_format_context(OutputIt out, format_args ctx_args, + detail::locale_ref loc = {}) + : out_(out), args_(ctx_args), loc_(loc) {} + + constexpr auto arg(int id) const -> format_arg { return args_.get(id); } + FMT_CONSTEXPR auto arg(basic_string_view name) -> format_arg { + return args_.get(name); + } + FMT_CONSTEXPR auto arg_id(basic_string_view name) -> int { + return args_.get_id(name); + } + auto args() const -> const format_args& { return args_; } + + // DEPRECATED! + FMT_CONSTEXPR auto error_handler() -> detail::error_handler { return {}; } + void on_error(const char* message) { error_handler().on_error(message); } + + // Returns an iterator to the beginning of the output range. + FMT_CONSTEXPR auto out() -> iterator { return out_; } + + // Advances the begin iterator to ``it``. + void advance_to(iterator it) { + if (!detail::is_back_insert_iterator()) out_ = it; + } + + FMT_CONSTEXPR auto locale() -> detail::locale_ref { return loc_; } +}; + +template +using buffer_context = + basic_format_context, Char>; +using format_context = buffer_context; + +template +using is_formattable = bool_constant>() + .map(std::declval()))>::value>; + +/** + \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 +class format_arg_store +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 + // Workaround a GCC template argument substitution bug. + : public basic_format_args +#endif +{ + private: + static const size_t num_args = sizeof...(Args); + static constexpr size_t num_named_args = detail::count_named_args(); + static const bool is_packed = num_args <= detail::max_packed_args; + + using value_type = conditional_t, + basic_format_arg>; + + detail::arg_data + data_; + + friend class basic_format_args; + + static constexpr unsigned long long desc = + (is_packed ? detail::encode_types() + : detail::is_unpacked_bit | num_args) | + (num_named_args != 0 + ? static_cast(detail::has_named_args_bit) + : 0); + + public: + template + FMT_CONSTEXPR FMT_INLINE format_arg_store(T&... args) + : +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 + basic_format_args(*this), +#endif + data_{detail::make_arg(args)...} { + if (detail::const_check(num_named_args != 0)) + 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::format_context`. + See `~fmt::arg` for lifetime considerations. + \endrst + */ +// Arguments are taken by lvalue references to avoid some lifetime issues. +template +constexpr auto make_format_args(T&... args) + -> format_arg_store...> { + 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 or + `dynamic_format_arg_store::push_back`. + + **Example**:: + + fmt::print("Elapsed time: {s:.2f} seconds", fmt::arg("s", 1.23)); + \endrst + */ +template +inline auto arg(const Char* name, const T& arg) -> detail::named_arg { + static_assert(!detail::is_named_arg(), "nested named arguments"); + return {name, arg}; +} +FMT_END_EXPORT + +/** + \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(); // Error: dangling reference + \endrst + */ +template class basic_format_args { + public: + using size_type = int; + using format_arg = basic_format_arg; + + 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* values_; + const format_arg* args_; + }; + + constexpr auto is_packed() const -> bool { + return (desc_ & detail::is_unpacked_bit) == 0; + } + auto has_named_args() const -> bool { + return (desc_ & detail::has_named_args_bit) != 0; + } + + FMT_CONSTEXPR auto type(int index) const -> detail::type { + int shift = index * detail::packed_arg_bits; + unsigned int mask = (1 << detail::packed_arg_bits) - 1; + return static_cast((desc_ >> shift) & mask); + } + + constexpr FMT_INLINE basic_format_args(unsigned long long desc, + const detail::value* values) + : desc_(desc), values_(values) {} + constexpr basic_format_args(unsigned long long desc, const format_arg* args) + : desc_(desc), args_(args) {} + + public: + constexpr basic_format_args() : desc_(0), args_(nullptr) {} + + /** + \rst + Constructs a `basic_format_args` object from `~fmt::format_arg_store`. + \endrst + */ + template + constexpr FMT_INLINE basic_format_args( + const format_arg_store& store) + : basic_format_args(format_arg_store::desc, + store.data_.args()) {} + + /** + \rst + Constructs a `basic_format_args` object from + `~fmt::dynamic_format_arg_store`. + \endrst + */ + constexpr FMT_INLINE basic_format_args( + const dynamic_format_arg_store& store) + : basic_format_args(store.get_types(), store.data()) {} + + /** + \rst + Constructs a `basic_format_args` object from a dynamic set of arguments. + \endrst + */ + constexpr 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. */ + FMT_CONSTEXPR auto get(int id) const -> format_arg { + 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 + auto get(basic_string_view name) const -> format_arg { + int id = get_id(name); + return id >= 0 ? get(id) : format_arg(); + } + + template + auto get_id(basic_string_view name) const -> int { + 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; + } + + auto max_size() const -> int { + unsigned long long max_packed = detail::max_packed_args; + return static_cast(is_packed() ? max_packed + : desc_ & ~detail::is_unpacked_bit); + } +}; + +/** An alias to ``basic_format_args``. */ +// A separate type would result in shorter symbols but break ABI compatibility +// between clang and gcc on ARM (#1919). +FMT_EXPORT using format_args = basic_format_args; + +// We cannot use enum classes as bit fields because of a gcc bug, so we put them +// in namespaces instead (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61414). +// Additionally, if an underlying type is specified, older gcc incorrectly warns +// that the type is too small. Both bugs are fixed in gcc 9.3. +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 903 +# define FMT_ENUM_UNDERLYING_TYPE(type) +#else +# define FMT_ENUM_UNDERLYING_TYPE(type) : type +#endif +namespace align { +enum type FMT_ENUM_UNDERLYING_TYPE(unsigned char){none, left, right, center, + numeric}; +} +using align_t = align::type; +namespace sign { +enum type FMT_ENUM_UNDERLYING_TYPE(unsigned char){none, minus, plus, space}; +} +using sign_t = sign::type; + +namespace detail { + +// Workaround an array initialization issue in gcc 4.8. +template 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 s) { + auto size = s.size(); + FMT_ASSERT(size <= max_size, "invalid fill"); + for (size_t i = 0; i < size; ++i) data_[i] = s[i]; + size_ = static_cast(size); + } + + constexpr auto size() const -> size_t { return size_; } + constexpr auto data() const -> const Char* { return data_; } + + FMT_CONSTEXPR auto operator[](size_t index) -> Char& { return data_[index]; } + FMT_CONSTEXPR auto operator[](size_t index) const -> const Char& { + return data_[index]; + } +}; +} // namespace detail + +enum class presentation_type : unsigned char { + none, + dec, // 'd' + oct, // 'o' + hex_lower, // 'x' + hex_upper, // 'X' + bin_lower, // 'b' + bin_upper, // 'B' + hexfloat_lower, // 'a' + hexfloat_upper, // 'A' + exp_lower, // 'e' + exp_upper, // 'E' + fixed_lower, // 'f' + fixed_upper, // 'F' + general_lower, // 'g' + general_upper, // 'G' + chr, // 'c' + string, // 's' + pointer, // 'p' + debug // '?' +}; + +// Format specifiers for built-in and string types. +template struct format_specs { + int width; + int precision; + presentation_type type; + align_t align : 4; + sign_t sign : 3; + bool alt : 1; // Alternate form ('#'). + bool localized : 1; + detail::fill_t fill; + + constexpr format_specs() + : width(0), + precision(-1), + type(presentation_type::none), + align(align::none), + sign(sign::none), + alt(false), + localized(false) {} +}; + +namespace detail { + +enum class arg_id_kind { none, index, name }; + +// An argument reference. +template 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 name) + : kind(arg_id_kind::name), val(name) {} + + FMT_CONSTEXPR auto operator=(int idx) -> arg_ref& { + kind = arg_id_kind::index; + val.index = idx; + return *this; + } + + arg_id_kind kind; + union value { + FMT_CONSTEXPR value(int idx = 0) : index(idx) {} + FMT_CONSTEXPR value(basic_string_view n) : name(n) {} + + int index; + basic_string_view name; + } val; +}; + +// Format specifiers with width and precision resolved at formatting rather +// than parsing time to allow reusing the same parsed specifiers with +// different sets of arguments (precompilation of format strings). +template +struct dynamic_format_specs : format_specs { + arg_ref width_ref; + arg_ref precision_ref; +}; + +// Converts a character to ASCII. Returns '\0' on conversion failure. +template ::value)> +constexpr auto to_ascii(Char c) -> char { + return c <= 0xff ? static_cast(c) : '\0'; +} +template ::value)> +constexpr auto to_ascii(Char c) -> char { + return c <= 0xff ? static_cast(c) : '\0'; +} + +// Returns the number of code units in a code point or 1 on error. +template +FMT_CONSTEXPR auto code_point_length(const Char* begin) -> int { + if (const_check(sizeof(Char) != 1)) return 1; + auto c = static_cast(*begin); + return static_cast((0x3a55000000000000ull >> (2 * (c >> 3))) & 0x3) + 1; +} + +// Return the result via the out param to workaround gcc bug 77539. +template +FMT_CONSTEXPR auto find(Ptr first, Ptr last, T value, Ptr& out) -> bool { + for (out = first; out != last; ++out) { + if (*out == value) return true; + } + return false; +} + +template <> +inline auto find(const char* first, const char* last, char value, + const char*& out) -> bool { + out = static_cast( + std::memchr(first, value, to_unsigned(last - first))); + return out != nullptr; +} + +// 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 +FMT_CONSTEXPR auto parse_nonnegative_int(const Char*& begin, const Char* end, + int error_value) noexcept -> int { + FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', ""); + unsigned value = 0, prev = 0; + auto p = begin; + do { + prev = value; + value = value * 10 + unsigned(*p - '0'); + ++p; + } while (p != end && '0' <= *p && *p <= '9'); + auto num_digits = p - begin; + begin = p; + if (num_digits <= std::numeric_limits::digits10) + return static_cast(value); + // Check for overflow. + const unsigned max = to_unsigned((std::numeric_limits::max)()); + return num_digits == std::numeric_limits::digits10 + 1 && + prev * 10ull + unsigned(p[-1] - '0') <= max + ? static_cast(value) + : error_value; +} + +FMT_CONSTEXPR inline auto parse_align(char c) -> align_t { + switch (c) { + case '<': + return align::left; + case '>': + return align::right; + case '^': + return align::center; + } + return align::none; +} + +template constexpr auto is_name_start(Char c) -> bool { + return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_'; +} + +template +FMT_CONSTEXPR auto do_parse_arg_id(const Char* begin, const Char* end, + Handler&& handler) -> const Char* { + Char c = *begin; + if (c >= '0' && c <= '9') { + int index = 0; + constexpr int max = (std::numeric_limits::max)(); + if (c != '0') + index = parse_nonnegative_int(begin, end, max); + else + ++begin; + if (begin == end || (*begin != '}' && *begin != ':')) + throw_format_error("invalid format string"); + else + handler.on_index(index); + return begin; + } + if (!is_name_start(c)) { + throw_format_error("invalid format string"); + return begin; + } + auto it = begin; + do { + ++it; + } while (it != end && (is_name_start(*it) || ('0' <= *it && *it <= '9'))); + handler.on_name({begin, to_unsigned(it - begin)}); + return it; +} + +template +FMT_CONSTEXPR FMT_INLINE auto parse_arg_id(const Char* begin, const Char* end, + Handler&& handler) -> const Char* { + FMT_ASSERT(begin != end, ""); + Char c = *begin; + if (c != '}' && c != ':') return do_parse_arg_id(begin, end, handler); + handler.on_auto(); + return begin; +} + +template struct dynamic_spec_id_handler { + basic_format_parse_context& ctx; + arg_ref& ref; + + FMT_CONSTEXPR void on_auto() { + int id = ctx.next_arg_id(); + ref = arg_ref(id); + ctx.check_dynamic_spec(id); + } + FMT_CONSTEXPR void on_index(int id) { + ref = arg_ref(id); + ctx.check_arg_id(id); + ctx.check_dynamic_spec(id); + } + FMT_CONSTEXPR void on_name(basic_string_view id) { + ref = arg_ref(id); + ctx.check_arg_id(id); + } +}; + +// Parses [integer | "{" [arg_id] "}"]. +template +FMT_CONSTEXPR auto parse_dynamic_spec(const Char* begin, const Char* end, + int& value, arg_ref& ref, + basic_format_parse_context& ctx) + -> const Char* { + FMT_ASSERT(begin != end, ""); + if ('0' <= *begin && *begin <= '9') { + int val = parse_nonnegative_int(begin, end, -1); + if (val != -1) + value = val; + else + throw_format_error("number is too big"); + } else if (*begin == '{') { + ++begin; + auto handler = dynamic_spec_id_handler{ctx, ref}; + if (begin != end) begin = parse_arg_id(begin, end, handler); + if (begin != end && *begin == '}') return ++begin; + throw_format_error("invalid format string"); + } + return begin; +} + +template +FMT_CONSTEXPR auto parse_precision(const Char* begin, const Char* end, + int& value, arg_ref& ref, + basic_format_parse_context& ctx) + -> const Char* { + ++begin; + if (begin == end || *begin == '}') { + throw_format_error("invalid precision"); + return begin; + } + return parse_dynamic_spec(begin, end, value, ref, ctx); +} + +enum class state { start, align, sign, hash, zero, width, precision, locale }; + +// Parses standard format specifiers. +template +FMT_CONSTEXPR FMT_INLINE auto parse_format_specs( + const Char* begin, const Char* end, dynamic_format_specs& specs, + basic_format_parse_context& ctx, type arg_type) -> const Char* { + auto c = '\0'; + if (end - begin > 1) { + auto next = to_ascii(begin[1]); + c = parse_align(next) == align::none ? to_ascii(*begin) : '\0'; + } else { + if (begin == end) return begin; + c = to_ascii(*begin); + } + + struct { + state current_state = state::start; + FMT_CONSTEXPR void operator()(state s, bool valid = true) { + if (current_state >= s || !valid) + throw_format_error("invalid format specifier"); + current_state = s; + } + } enter_state; + + using pres = presentation_type; + constexpr auto integral_set = sint_set | uint_set | bool_set | char_set; + struct { + const Char*& begin; + dynamic_format_specs& specs; + type arg_type; + + FMT_CONSTEXPR auto operator()(pres pres_type, int set) -> const Char* { + if (!in(arg_type, set)) { + if (arg_type == type::none_type) return begin; + throw_format_error("invalid format specifier"); + } + specs.type = pres_type; + return begin + 1; + } + } parse_presentation_type{begin, specs, arg_type}; + + for (;;) { + switch (c) { + case '<': + case '>': + case '^': + enter_state(state::align); + specs.align = parse_align(c); + ++begin; + break; + case '+': + case '-': + case ' ': + if (arg_type == type::none_type) return begin; + enter_state(state::sign, in(arg_type, sint_set | float_set)); + switch (c) { + case '+': + specs.sign = sign::plus; + break; + case '-': + specs.sign = sign::minus; + break; + case ' ': + specs.sign = sign::space; + break; + } + ++begin; + break; + case '#': + if (arg_type == type::none_type) return begin; + enter_state(state::hash, is_arithmetic_type(arg_type)); + specs.alt = true; + ++begin; + break; + case '0': + enter_state(state::zero); + if (!is_arithmetic_type(arg_type)) { + if (arg_type == type::none_type) return begin; + throw_format_error("format specifier requires numeric argument"); + } + if (specs.align == align::none) { + // Ignore 0 if align is specified for compatibility with std::format. + specs.align = align::numeric; + specs.fill[0] = Char('0'); + } + ++begin; + break; + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '{': + enter_state(state::width); + begin = parse_dynamic_spec(begin, end, specs.width, specs.width_ref, ctx); + break; + case '.': + if (arg_type == type::none_type) return begin; + enter_state(state::precision, + in(arg_type, float_set | string_set | cstring_set)); + begin = parse_precision(begin, end, specs.precision, specs.precision_ref, + ctx); + break; + case 'L': + if (arg_type == type::none_type) return begin; + enter_state(state::locale, is_arithmetic_type(arg_type)); + specs.localized = true; + ++begin; + break; + case 'd': + return parse_presentation_type(pres::dec, integral_set); + case 'o': + return parse_presentation_type(pres::oct, integral_set); + case 'x': + return parse_presentation_type(pres::hex_lower, integral_set); + case 'X': + return parse_presentation_type(pres::hex_upper, integral_set); + case 'b': + return parse_presentation_type(pres::bin_lower, integral_set); + case 'B': + return parse_presentation_type(pres::bin_upper, integral_set); + case 'a': + return parse_presentation_type(pres::hexfloat_lower, float_set); + case 'A': + return parse_presentation_type(pres::hexfloat_upper, float_set); + case 'e': + return parse_presentation_type(pres::exp_lower, float_set); + case 'E': + return parse_presentation_type(pres::exp_upper, float_set); + case 'f': + return parse_presentation_type(pres::fixed_lower, float_set); + case 'F': + return parse_presentation_type(pres::fixed_upper, float_set); + case 'g': + return parse_presentation_type(pres::general_lower, float_set); + case 'G': + return parse_presentation_type(pres::general_upper, float_set); + case 'c': + if (arg_type == type::bool_type) + throw_format_error("invalid format specifier"); + return parse_presentation_type(pres::chr, integral_set); + case 's': + return parse_presentation_type(pres::string, + bool_set | string_set | cstring_set); + case 'p': + return parse_presentation_type(pres::pointer, pointer_set | cstring_set); + case '?': + return parse_presentation_type(pres::debug, + char_set | string_set | cstring_set); + case '}': + return begin; + default: { + if (*begin == '}') return begin; + // Parse fill and alignment. + auto fill_end = begin + code_point_length(begin); + if (end - fill_end <= 0) { + throw_format_error("invalid format specifier"); + return begin; + } + if (*begin == '{') { + throw_format_error("invalid fill character '{'"); + return begin; + } + auto align = parse_align(to_ascii(*fill_end)); + enter_state(state::align, align != align::none); + specs.fill = {begin, to_unsigned(fill_end - begin)}; + specs.align = align; + begin = fill_end + 1; + } + } + if (begin == end) return begin; + c = to_ascii(*begin); + } +} + +template +FMT_CONSTEXPR auto parse_replacement_field(const Char* begin, const Char* end, + Handler&& handler) -> const Char* { + struct id_adapter { + Handler& handler; + int arg_id; + + FMT_CONSTEXPR void on_auto() { arg_id = handler.on_arg_id(); } + FMT_CONSTEXPR void on_index(int id) { arg_id = handler.on_arg_id(id); } + FMT_CONSTEXPR void on_name(basic_string_view id) { + arg_id = handler.on_arg_id(id); + } + }; + + ++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, 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 +FMT_CONSTEXPR FMT_INLINE void parse_format_string( + basic_string_view 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* from, const Char* to) { + if (from == to) return; + for (;;) { + const Char* p = nullptr; + if (!find(from, to, Char('}'), p)) + return handler_.on_text(from, to); + ++p; + if (p == to || *p != '}') + return handler_.on_error("unmatched '}' in format string"); + handler_.on_text(from, p); + from = 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(begin + 1, end, Char('{'), p)) + return write(begin, end); + write(begin, p); + begin = parse_replacement_field(p, end, handler); + } +} + +template ::value> struct strip_named_arg { + using type = T; +}; +template struct strip_named_arg { + using type = remove_cvref_t; +}; + +template +FMT_CONSTEXPR auto parse_format_specs(ParseContext& ctx) + -> decltype(ctx.begin()) { + using char_type = typename ParseContext::char_type; + using context = buffer_context; + using mapped_type = conditional_t< + mapped_type_constant::value != type::custom_type, + decltype(arg_mapper().map(std::declval())), + typename strip_named_arg::type>; +#if defined(__cpp_if_constexpr) + if constexpr (std::is_default_constructible< + formatter>::value) { + return formatter().parse(ctx); + } else { + type_is_unformattable_for _; + return ctx.begin(); + } +#else + return formatter().parse(ctx); +#endif +} + +// Checks char specs and returns true iff the presentation type is char-like. +template +FMT_CONSTEXPR auto check_char_specs(const format_specs& specs) -> bool { + if (specs.type != presentation_type::none && + specs.type != presentation_type::chr && + specs.type != presentation_type::debug) { + return false; + } + if (specs.align == align::numeric || specs.sign != sign::none || specs.alt) + throw_format_error("invalid format specifier for char"); + return true; +} + +#if FMT_USE_NONTYPE_TEMPLATE_ARGS +template +constexpr auto get_arg_index_by_name(basic_string_view name) -> int { + if constexpr (is_statically_named_arg()) { + if (name == T::name) return N; + } + if constexpr (sizeof...(Args) > 0) + return get_arg_index_by_name(name); + (void)name; // Workaround an MSVC bug about "unused" parameter. + return -1; +} +#endif + +template +FMT_CONSTEXPR auto get_arg_index_by_name(basic_string_view name) -> int { +#if FMT_USE_NONTYPE_TEMPLATE_ARGS + if constexpr (sizeof...(Args) > 0) + return get_arg_index_by_name<0, Args...>(name); +#endif + (void)name; + return -1; +} + +template class format_string_checker { + private: + using parse_context_type = compile_parse_context; + static constexpr int num_args = sizeof...(Args); + + // Format specifier parsing function. + // In the future basic_format_parse_context will replace compile_parse_context + // here and will use is_constant_evaluated and downcasting to access the data + // needed for compile-time checks: https://godbolt.org/z/GvWzcTjh1. + using parse_func = const Char* (*)(parse_context_type&); + + type types_[num_args > 0 ? static_cast(num_args) : 1]; + parse_context_type context_; + parse_func parse_funcs_[num_args > 0 ? static_cast(num_args) : 1]; + + public: + explicit FMT_CONSTEXPR format_string_checker(basic_string_view fmt) + : types_{mapped_type_constant>::value...}, + context_(fmt, num_args, types_), + parse_funcs_{&parse_format_specs...} {} + + FMT_CONSTEXPR void on_text(const Char*, const Char*) {} + + FMT_CONSTEXPR auto on_arg_id() -> int { return context_.next_arg_id(); } + FMT_CONSTEXPR auto on_arg_id(int id) -> int { + return context_.check_arg_id(id), id; + } + FMT_CONSTEXPR auto on_arg_id(basic_string_view id) -> int { +#if FMT_USE_NONTYPE_TEMPLATE_ARGS + auto index = get_arg_index_by_name(id); + if (index < 0) on_error("named argument is not found"); + return index; +#else + (void)id; + on_error("compile-time checks for named arguments require C++20 support"); + return 0; +#endif + } + + FMT_CONSTEXPR void on_replacement_field(int id, const Char* begin) { + on_format_specs(id, begin, begin); // Call parse() on empty specs. + } + + FMT_CONSTEXPR auto on_format_specs(int id, const Char* begin, const Char*) + -> const Char* { + context_.advance_to(begin); + // id >= 0 check is a workaround for gcc 10 bug (#2065). + return id >= 0 && id < num_args ? parse_funcs_[id](context_) : begin; + } + + FMT_CONSTEXPR void on_error(const char* message) { + throw_format_error(message); + } +}; + +// Reports a compile-time error if S is not a valid format string. +template ::value)> +FMT_INLINE void check_format_string(const S&) { +#ifdef FMT_ENFORCE_COMPILE_STRING + static_assert(is_compile_string::value, + "FMT_ENFORCE_COMPILE_STRING requires all format strings to use " + "FMT_STRING."); +#endif +} +template ::value)> +void check_format_string(S format_str) { + using char_t = typename S::char_type; + FMT_CONSTEXPR auto s = basic_string_view(format_str); + using checker = format_string_checker...>; + FMT_CONSTEXPR bool error = (parse_format_string(s, checker(s)), true); + ignore_unused(error); +} + +template struct vformat_args { + using type = basic_format_args< + basic_format_context>, Char>>; +}; +template <> struct vformat_args { + using type = format_args; +}; + +// Use vformat_args and avoid type_identity to keep symbols short. +template +void vformat_to(buffer& buf, basic_string_view fmt, + typename vformat_args::type args, locale_ref loc = {}); + +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 + +FMT_BEGIN_EXPORT + +// A formatter specialization for natively supported types. +template +struct formatter::value != + detail::type::custom_type>> { + private: + detail::dynamic_format_specs specs_; + + public: + template + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> const Char* { + auto type = detail::type_constant::value; + auto end = + detail::parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, type); + if (type == detail::type::char_type) detail::check_char_specs(specs_); + return end; + } + + template ::value, + FMT_ENABLE_IF(U == detail::type::string_type || + U == detail::type::cstring_type || + U == detail::type::char_type)> + FMT_CONSTEXPR void set_debug_format(bool set = true) { + specs_.type = set ? presentation_type::debug : presentation_type::none; + } + + template + FMT_CONSTEXPR auto format(const T& val, FormatContext& ctx) const + -> decltype(ctx.out()); +}; + +template struct runtime_format_string { + basic_string_view str; +}; + +/** A compile-time format string. */ +template class basic_format_string { + private: + basic_string_view str_; + + public: + template >::value)> + FMT_CONSTEVAL FMT_INLINE basic_format_string(const S& s) : str_(s) { + static_assert( + detail::count< + (std::is_base_of>::value && + std::is_reference::value)...>() == 0, + "passing views as lvalues is disallowed"); +#ifdef FMT_HAS_CONSTEVAL + if constexpr (detail::count_named_args() == + detail::count_statically_named_args()) { + using checker = + detail::format_string_checker...>; + detail::parse_format_string(str_, checker(s)); + } +#else + detail::check_format_string(s); +#endif + } + basic_format_string(runtime_format_string fmt) : str_(fmt.str) {} + + FMT_INLINE operator basic_string_view() const { return str_; } + FMT_INLINE auto get() const -> basic_string_view { return str_; } +}; + +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 +// Workaround broken conversion on older gcc. +template using format_string = string_view; +inline auto runtime(string_view s) -> string_view { return s; } +#else +template +using format_string = basic_format_string...>; +/** + \rst + Creates a runtime format string. + + **Example**:: + + // Check format string at runtime instead of compile-time. + fmt::print(fmt::runtime("{:d}"), "I am not a number"); + \endrst + */ +inline auto runtime(string_view s) -> runtime_format_string<> { return {{s}}; } +#endif + +FMT_API auto vformat(string_view fmt, format_args args) -> std::string; + +/** + \rst + Formats ``args`` according to specifications in ``fmt`` and returns the result + as a string. + + **Example**:: + + #include + std::string message = fmt::format("The answer is {}.", 42); + \endrst +*/ +template +FMT_NODISCARD FMT_INLINE auto format(format_string fmt, T&&... args) + -> std::string { + return vformat(fmt, fmt::make_format_args(args...)); +} + +/** Formats a string and writes the output to ``out``. */ +template ::value)> +auto vformat_to(OutputIt out, string_view fmt, format_args args) -> OutputIt { + auto&& buf = detail::get_buffer(out); + detail::vformat_to(buf, fmt, args, {}); + return detail::get_iterator(buf, out); +} + +/** + \rst + Formats ``args`` according to specifications in ``fmt``, writes the result to + the output iterator ``out`` and returns the iterator past the end of the output + range. `format_to` does not append a terminating null character. + + **Example**:: + + auto out = std::vector(); + fmt::format_to(std::back_inserter(out), "{}", 42); + \endrst + */ +template ::value)> +FMT_INLINE auto format_to(OutputIt out, format_string fmt, T&&... args) + -> OutputIt { + return vformat_to(out, fmt, fmt::make_format_args(args...)); +} + +template struct format_to_n_result { + /** Iterator past the end of the output range. */ + OutputIt out; + /** Total (not truncated) output size. */ + size_t size; +}; + +template ::value)> +auto vformat_to_n(OutputIt out, size_t n, string_view fmt, format_args args) + -> format_to_n_result { + using traits = detail::fixed_buffer_traits; + auto buf = detail::iterator_buffer(out, n); + detail::vformat_to(buf, fmt, args, {}); + return {buf.out(), buf.count()}; +} + +/** + \rst + Formats ``args`` according to specifications in ``fmt``, writes up to ``n`` + characters of the result to the output iterator ``out`` and returns the total + (not truncated) output size and the iterator past the end of the output range. + `format_to_n` does not append a terminating null character. + \endrst + */ +template ::value)> +FMT_INLINE auto format_to_n(OutputIt out, size_t n, format_string fmt, + T&&... args) -> format_to_n_result { + return vformat_to_n(out, n, fmt, fmt::make_format_args(args...)); +} + +/** Returns the number of chars in the output of ``format(fmt, args...)``. */ +template +FMT_NODISCARD FMT_INLINE auto formatted_size(format_string fmt, + T&&... args) -> size_t { + auto buf = detail::counting_buffer<>(); + detail::vformat_to(buf, fmt, fmt::make_format_args(args...), {}); + return buf.count(); +} + +FMT_API void vprint(string_view fmt, format_args args); +FMT_API void vprint(std::FILE* f, string_view fmt, format_args args); + +/** + \rst + Formats ``args`` according to specifications in ``fmt`` and writes the output + to ``stdout``. + + **Example**:: + + fmt::print("Elapsed time: {0:.2f} seconds", 1.23); + \endrst + */ +template +FMT_INLINE void print(format_string fmt, T&&... args) { + const auto& vargs = fmt::make_format_args(args...); + return detail::is_utf8() ? vprint(fmt, vargs) + : detail::vprint_mojibake(stdout, fmt, vargs); +} + +/** + \rst + Formats ``args`` according to specifications in ``fmt`` and writes the + output to the file ``f``. + + **Example**:: + + fmt::print(stderr, "Don't {}!", "panic"); + \endrst + */ +template +FMT_INLINE void print(std::FILE* f, format_string fmt, T&&... args) { + const auto& vargs = fmt::make_format_args(args...); + return detail::is_utf8() ? vprint(f, fmt, vargs) + : detail::vprint_mojibake(f, fmt, vargs); +} + +/** + Formats ``args`` according to specifications in ``fmt`` and writes the + output to the file ``f`` followed by a newline. + */ +template +FMT_INLINE void println(std::FILE* f, format_string fmt, T&&... args) { + return fmt::print(f, "{}\n", fmt::format(fmt, std::forward(args)...)); +} + +/** + Formats ``args`` according to specifications in ``fmt`` and writes the output + to ``stdout`` followed by a newline. + */ +template +FMT_INLINE void println(format_string fmt, T&&... args) { + return fmt::println(stdout, fmt, std::forward(args)...); +} + +FMT_END_EXPORT +FMT_GCC_PRAGMA("GCC pop_options") +FMT_END_NAMESPACE + +#ifdef FMT_HEADER_ONLY +# include "format.h" +#endif +#endif // FMT_CORE_H_ diff --git a/third_party/fmt/include/fmt/format-inl.h b/third_party/fmt/include/fmt/format-inl.h new file mode 100644 index 0000000..efac5d1 --- /dev/null +++ b/third_party/fmt/include/fmt/format-inl.h @@ -0,0 +1,1678 @@ +// 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 +#include // errno +#include +#include +#include + +#ifndef FMT_STATIC_THOUSANDS_SEPARATOR +# include +#endif + +#if defined(_WIN32) && !defined(FMT_WINDOWS_NO_WCHAR) +# include // _isatty +#endif + +#include "format.h" + +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(); +} + +FMT_FUNC void throw_format_error(const char* message) { + FMT_THROW(format_error(message)); +} + +FMT_FUNC void format_error_code(detail::buffer& out, int error_code, + string_view message) 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>(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(out); + if (message.size() <= inline_buffer_size - error_code_size) + fmt::format_to(it, FMT_STRING("{}{}"), message, SEP); + fmt::format_to(it, FMT_STRING("{}{}"), ERROR_STR, error_code); + FMT_ASSERT(out.size() <= inline_buffer_size, ""); +} + +FMT_FUNC void report_error(format_func func, int error_code, + const char* message) noexcept { + memory_buffer full_message; + func(full_message, error_code, message); + // Don't use fwrite_fully because the latter may throw. + if (std::fwrite(full_message.data(), full_message.size(), 1, stderr) > 0) + std::fputc('\n', stderr); +} + +// A wrapper around fwrite that throws on error. +inline void fwrite_fully(const void* ptr, size_t count, FILE* stream) { + size_t written = std::fwrite(ptr, 1, count, stream); + if (written < count) + FMT_THROW(system_error(errno, FMT_STRING("cannot write to file"))); +} + +#ifndef FMT_STATIC_THOUSANDS_SEPARATOR +template +locale_ref::locale_ref(const Locale& loc) : locale_(&loc) { + static_assert(std::is_same::value, ""); +} + +template auto locale_ref::get() const -> Locale { + static_assert(std::is_same::value, ""); + return locale_ ? *static_cast(locale_) : std::locale(); +} + +template +FMT_FUNC auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result { + auto& facet = std::use_facet>(loc.get()); + auto grouping = facet.grouping(); + auto thousands_sep = grouping.empty() ? Char() : facet.thousands_sep(); + return {std::move(grouping), thousands_sep}; +} +template +FMT_FUNC auto decimal_point_impl(locale_ref loc) -> Char { + return std::use_facet>(loc.get()) + .decimal_point(); +} +#else +template +FMT_FUNC auto thousands_sep_impl(locale_ref) -> thousands_sep_result { + return {"\03", FMT_STATIC_THOUSANDS_SEPARATOR}; +} +template FMT_FUNC Char decimal_point_impl(locale_ref) { + return '.'; +} +#endif + +FMT_FUNC auto write_loc(appender out, loc_value value, + const format_specs<>& specs, locale_ref loc) -> bool { +#ifndef FMT_STATIC_THOUSANDS_SEPARATOR + auto locale = loc.get(); + // We cannot use the num_put facet because it may produce output in + // a wrong encoding. + using facet = format_facet; + if (std::has_facet(locale)) + return std::use_facet(locale).put(out, value, specs); + return facet(locale).put(out, value, specs); +#endif + return false; +} +} // namespace detail + +template typename Locale::id format_facet::id; + +#ifndef FMT_STATIC_THOUSANDS_SEPARATOR +template format_facet::format_facet(Locale& loc) { + auto& numpunct = std::use_facet>(loc); + grouping_ = numpunct.grouping(); + if (!grouping_.empty()) separator_ = std::string(1, numpunct.thousands_sep()); +} + +template <> +FMT_API FMT_FUNC auto format_facet::do_put( + appender out, loc_value val, const format_specs<>& specs) const -> bool { + return val.visit( + detail::loc_writer<>{out, specs, separator_, grouping_, decimal_point_}); +} +#endif + +FMT_FUNC auto vsystem_error(int error_code, string_view fmt, format_args args) + -> std::system_error { + auto ec = std::error_code(error_code, std::generic_category()); + return std::system_error(ec, vformat(fmt, args)); +} + +namespace detail { + +template +inline auto operator==(basic_fp x, basic_fp y) -> bool { + return x.f == y.f && x.e == y.e; +} + +// Compilers should be able to optimize this into the ror instruction. +FMT_CONSTEXPR inline auto rotr(uint32_t n, uint32_t r) noexcept -> uint32_t { + r &= 31; + return (n >> r) | (n << (32 - r)); +} +FMT_CONSTEXPR inline auto rotr(uint64_t n, uint32_t r) noexcept -> uint64_t { + r &= 63; + return (n >> r) | (n << (64 - r)); +} + +// Implementation of Dragonbox algorithm: https://github.com/jk-jeon/dragonbox. +namespace dragonbox { +// Computes upper 64 bits of multiplication of a 32-bit unsigned integer and a +// 64-bit unsigned integer. +inline auto umul96_upper64(uint32_t x, uint64_t y) noexcept -> uint64_t { + return umul128_upper64(static_cast(x) << 32, y); +} + +// Computes lower 128 bits of multiplication of a 64-bit unsigned integer and a +// 128-bit unsigned integer. +inline auto umul192_lower128(uint64_t x, uint128_fallback y) noexcept + -> uint128_fallback { + uint64_t high = x * y.high(); + uint128_fallback high_low = umul128(x, y.low()); + return {high + high_low.high(), high_low.low()}; +} + +// Computes lower 64 bits of multiplication of a 32-bit unsigned integer and a +// 64-bit unsigned integer. +inline auto umul96_lower64(uint32_t x, uint64_t y) noexcept -> uint64_t { + return x * y; +} + +// Various fast log computations. +inline auto floor_log10_pow2_minus_log10_4_over_3(int e) noexcept -> int { + FMT_ASSERT(e <= 2936 && e >= -2985, "too large exponent"); + return (e * 631305 - 261663) >> 21; +} + +FMT_INLINE_VARIABLE constexpr struct { + uint32_t divisor; + int shift_amount; +} div_small_pow10_infos[] = {{10, 16}, {100, 16}}; + +// Replaces n by floor(n / pow(10, N)) returning true if and only if n is +// divisible by pow(10, N). +// Precondition: n <= pow(10, N + 1). +template +auto check_divisibility_and_divide_by_pow10(uint32_t& n) noexcept -> bool { + // The numbers below are chosen such that: + // 1. floor(n/d) = floor(nm / 2^k) where d=10 or d=100, + // 2. nm mod 2^k < m if and only if n is divisible by d, + // where m is magic_number, k is shift_amount + // and d is divisor. + // + // Item 1 is a common technique of replacing division by a constant with + // multiplication, see e.g. "Division by Invariant Integers Using + // Multiplication" by Granlund and Montgomery (1994). magic_number (m) is set + // to ceil(2^k/d) for large enough k. + // The idea for item 2 originates from Schubfach. + constexpr auto info = div_small_pow10_infos[N - 1]; + FMT_ASSERT(n <= info.divisor * 10, "n is too large"); + constexpr uint32_t magic_number = + (1u << info.shift_amount) / info.divisor + 1; + n *= magic_number; + const uint32_t comparison_mask = (1u << info.shift_amount) - 1; + bool result = (n & comparison_mask) < magic_number; + n >>= info.shift_amount; + return result; +} + +// Computes floor(n / pow(10, N)) for small n and N. +// Precondition: n <= pow(10, N + 1). +template auto small_division_by_pow10(uint32_t n) noexcept -> uint32_t { + constexpr auto info = div_small_pow10_infos[N - 1]; + FMT_ASSERT(n <= info.divisor * 10, "n is too large"); + constexpr uint32_t magic_number = + (1u << info.shift_amount) / info.divisor + 1; + return (n * magic_number) >> info.shift_amount; +} + +// Computes floor(n / 10^(kappa + 1)) (float) +inline auto divide_by_10_to_kappa_plus_1(uint32_t n) noexcept -> uint32_t { + // 1374389535 = ceil(2^37/100) + return static_cast((static_cast(n) * 1374389535) >> 37); +} +// Computes floor(n / 10^(kappa + 1)) (double) +inline auto divide_by_10_to_kappa_plus_1(uint64_t n) noexcept -> uint64_t { + // 2361183241434822607 = ceil(2^(64+7)/1000) + return umul128_upper64(n, 2361183241434822607ull) >> 7; +} + +// Various subroutines using pow10 cache +template struct cache_accessor; + +template <> struct cache_accessor { + using carrier_uint = float_info::carrier_uint; + using cache_entry_type = uint64_t; + + static auto get_cached_power(int k) noexcept -> uint64_t { + FMT_ASSERT(k >= float_info::min_k && k <= float_info::max_k, + "k is out of range"); + static constexpr const uint64_t pow10_significands[] = { + 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, 0x813f3978f8940985, + 0xa18f07d736b90be6, 0xc9f2c9cd04674edf, 0xfc6f7c4045812297, + 0x9dc5ada82b70b59e, 0xc5371912364ce306, 0xf684df56c3e01bc7, + 0x9a130b963a6c115d, 0xc097ce7bc90715b4, 0xf0bdc21abb48db21, + 0x96769950b50d88f5, 0xbc143fa4e250eb32, 0xeb194f8e1ae525fe, + 0x92efd1b8d0cf37bf, 0xb7abc627050305ae, 0xe596b7b0c643c71a, + 0x8f7e32ce7bea5c70, 0xb35dbf821ae4f38c, 0xe0352f62a19e306f}; + return pow10_significands[k - float_info::min_k]; + } + + struct compute_mul_result { + carrier_uint result; + bool is_integer; + }; + struct compute_mul_parity_result { + bool parity; + bool is_integer; + }; + + static auto compute_mul(carrier_uint u, + const cache_entry_type& cache) noexcept + -> compute_mul_result { + auto r = umul96_upper64(u, cache); + return {static_cast(r >> 32), + static_cast(r) == 0}; + } + + static auto compute_delta(const cache_entry_type& cache, int beta) noexcept + -> uint32_t { + return static_cast(cache >> (64 - 1 - beta)); + } + + static auto compute_mul_parity(carrier_uint two_f, + const cache_entry_type& cache, + int beta) noexcept + -> compute_mul_parity_result { + FMT_ASSERT(beta >= 1, ""); + FMT_ASSERT(beta < 64, ""); + + auto r = umul96_lower64(two_f, cache); + return {((r >> (64 - beta)) & 1) != 0, + static_cast(r >> (32 - beta)) == 0}; + } + + static auto compute_left_endpoint_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return static_cast( + (cache - (cache >> (num_significand_bits() + 2))) >> + (64 - num_significand_bits() - 1 - beta)); + } + + static auto compute_right_endpoint_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return static_cast( + (cache + (cache >> (num_significand_bits() + 1))) >> + (64 - num_significand_bits() - 1 - beta)); + } + + static auto compute_round_up_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return (static_cast( + cache >> (64 - num_significand_bits() - 2 - beta)) + + 1) / + 2; + } +}; + +template <> struct cache_accessor { + using carrier_uint = float_info::carrier_uint; + using cache_entry_type = uint128_fallback; + + static auto get_cached_power(int k) noexcept -> uint128_fallback { + FMT_ASSERT(k >= float_info::min_k && k <= float_info::max_k, + "k is out of range"); + + static constexpr const uint128_fallback pow10_significands[] = { +#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, 0xbff8f10e7a8921a5}, + {0xa321f2d7226895c7, 0xaff72d52192b6a0e}, + {0xcbea6f8ceb02bb39, 0x9bf4f8a69f764491}, + {0xfee50b7025c36a08, 0x02f236d04753d5b5}, + {0x9f4f2726179a2245, 0x01d762422c946591}, + {0xc722f0ef9d80aad6, 0x424d3ad2b7b97ef6}, + {0xf8ebad2b84e0d58b, 0xd2e0898765a7deb3}, + {0x9b934c3b330c8577, 0x63cc55f49f88eb30}, + {0xc2781f49ffcfa6d5, 0x3cbf6b71c76b25fc}, + {0xf316271c7fc3908a, 0x8bef464e3945ef7b}, + {0x97edd871cfda3a56, 0x97758bf0e3cbb5ad}, + {0xbde94e8e43d0c8ec, 0x3d52eeed1cbea318}, + {0xed63a231d4c4fb27, 0x4ca7aaa863ee4bde}, + {0x945e455f24fb1cf8, 0x8fe8caa93e74ef6b}, + {0xb975d6b6ee39e436, 0xb3e2fd538e122b45}, + {0xe7d34c64a9c85d44, 0x60dbbca87196b617}, + {0x90e40fbeea1d3a4a, 0xbc8955e946fe31ce}, + {0xb51d13aea4a488dd, 0x6babab6398bdbe42}, + {0xe264589a4dcdab14, 0xc696963c7eed2dd2}, + {0x8d7eb76070a08aec, 0xfc1e1de5cf543ca3}, + {0xb0de65388cc8ada8, 0x3b25a55f43294bcc}, + {0xdd15fe86affad912, 0x49ef0eb713f39ebf}, + {0x8a2dbf142dfcc7ab, 0x6e3569326c784338}, + {0xacb92ed9397bf996, 0x49c2c37f07965405}, + {0xd7e77a8f87daf7fb, 0xdc33745ec97be907}, + {0x86f0ac99b4e8dafd, 0x69a028bb3ded71a4}, + {0xa8acd7c0222311bc, 0xc40832ea0d68ce0d}, + {0xd2d80db02aabd62b, 0xf50a3fa490c30191}, + {0x83c7088e1aab65db, 0x792667c6da79e0fb}, + {0xa4b8cab1a1563f52, 0x577001b891185939}, + {0xcde6fd5e09abcf26, 0xed4c0226b55e6f87}, + {0x80b05e5ac60b6178, 0x544f8158315b05b5}, + {0xa0dc75f1778e39d6, 0x696361ae3db1c722}, + {0xc913936dd571c84c, 0x03bc3a19cd1e38ea}, + {0xfb5878494ace3a5f, 0x04ab48a04065c724}, + {0x9d174b2dcec0e47b, 0x62eb0d64283f9c77}, + {0xc45d1df942711d9a, 0x3ba5d0bd324f8395}, + {0xf5746577930d6500, 0xca8f44ec7ee3647a}, + {0x9968bf6abbe85f20, 0x7e998b13cf4e1ecc}, + {0xbfc2ef456ae276e8, 0x9e3fedd8c321a67f}, + {0xefb3ab16c59b14a2, 0xc5cfe94ef3ea101f}, + {0x95d04aee3b80ece5, 0xbba1f1d158724a13}, + {0xbb445da9ca61281f, 0x2a8a6e45ae8edc98}, + {0xea1575143cf97226, 0xf52d09d71a3293be}, + {0x924d692ca61be758, 0x593c2626705f9c57}, + {0xb6e0c377cfa2e12e, 0x6f8b2fb00c77836d}, + {0xe498f455c38b997a, 0x0b6dfb9c0f956448}, + {0x8edf98b59a373fec, 0x4724bd4189bd5ead}, + {0xb2977ee300c50fe7, 0x58edec91ec2cb658}, + {0xdf3d5e9bc0f653e1, 0x2f2967b66737e3ee}, + {0x8b865b215899f46c, 0xbd79e0d20082ee75}, + {0xae67f1e9aec07187, 0xecd8590680a3aa12}, + {0xda01ee641a708de9, 0xe80e6f4820cc9496}, + {0x884134fe908658b2, 0x3109058d147fdcde}, + {0xaa51823e34a7eede, 0xbd4b46f0599fd416}, + {0xd4e5e2cdc1d1ea96, 0x6c9e18ac7007c91b}, + {0x850fadc09923329e, 0x03e2cf6bc604ddb1}, + {0xa6539930bf6bff45, 0x84db8346b786151d}, + {0xcfe87f7cef46ff16, 0xe612641865679a64}, + {0x81f14fae158c5f6e, 0x4fcb7e8f3f60c07f}, + {0xa26da3999aef7749, 0xe3be5e330f38f09e}, + {0xcb090c8001ab551c, 0x5cadf5bfd3072cc6}, + {0xfdcb4fa002162a63, 0x73d9732fc7c8f7f7}, + {0x9e9f11c4014dda7e, 0x2867e7fddcdd9afb}, + {0xc646d63501a1511d, 0xb281e1fd541501b9}, + {0xf7d88bc24209a565, 0x1f225a7ca91a4227}, + {0x9ae757596946075f, 0x3375788de9b06959}, + {0xc1a12d2fc3978937, 0x0052d6b1641c83af}, + {0xf209787bb47d6b84, 0xc0678c5dbd23a49b}, + {0x9745eb4d50ce6332, 0xf840b7ba963646e1}, + {0xbd176620a501fbff, 0xb650e5a93bc3d899}, + {0xec5d3fa8ce427aff, 0xa3e51f138ab4cebf}, + {0x93ba47c980e98cdf, 0xc66f336c36b10138}, + {0xb8a8d9bbe123f017, 0xb80b0047445d4185}, + {0xe6d3102ad96cec1d, 0xa60dc059157491e6}, + {0x9043ea1ac7e41392, 0x87c89837ad68db30}, + {0xb454e4a179dd1877, 0x29babe4598c311fc}, + {0xe16a1dc9d8545e94, 0xf4296dd6fef3d67b}, + {0x8ce2529e2734bb1d, 0x1899e4a65f58660d}, + {0xb01ae745b101e9e4, 0x5ec05dcff72e7f90}, + {0xdc21a1171d42645d, 0x76707543f4fa1f74}, + {0x899504ae72497eba, 0x6a06494a791c53a9}, + {0xabfa45da0edbde69, 0x0487db9d17636893}, + {0xd6f8d7509292d603, 0x45a9d2845d3c42b7}, + {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b3}, + {0xa7f26836f282b732, 0x8e6cac7768d7141f}, + {0xd1ef0244af2364ff, 0x3207d795430cd927}, + {0x8335616aed761f1f, 0x7f44e6bd49e807b9}, + {0xa402b9c5a8d3a6e7, 0x5f16206c9c6209a7}, + {0xcd036837130890a1, 0x36dba887c37a8c10}, + {0x802221226be55a64, 0xc2494954da2c978a}, + {0xa02aa96b06deb0fd, 0xf2db9baa10b7bd6d}, + {0xc83553c5c8965d3d, 0x6f92829494e5acc8}, + {0xfa42a8b73abbf48c, 0xcb772339ba1f17fa}, + {0x9c69a97284b578d7, 0xff2a760414536efc}, + {0xc38413cf25e2d70d, 0xfef5138519684abb}, + {0xf46518c2ef5b8cd1, 0x7eb258665fc25d6a}, + {0x98bf2f79d5993802, 0xef2f773ffbd97a62}, + {0xbeeefb584aff8603, 0xaafb550ffacfd8fb}, + {0xeeaaba2e5dbf6784, 0x95ba2a53f983cf39}, + {0x952ab45cfa97a0b2, 0xdd945a747bf26184}, + {0xba756174393d88df, 0x94f971119aeef9e5}, + {0xe912b9d1478ceb17, 0x7a37cd5601aab85e}, + {0x91abb422ccb812ee, 0xac62e055c10ab33b}, + {0xb616a12b7fe617aa, 0x577b986b314d600a}, + {0xe39c49765fdf9d94, 0xed5a7e85fda0b80c}, + {0x8e41ade9fbebc27d, 0x14588f13be847308}, + {0xb1d219647ae6b31c, 0x596eb2d8ae258fc9}, + {0xde469fbd99a05fe3, 0x6fca5f8ed9aef3bc}, + {0x8aec23d680043bee, 0x25de7bb9480d5855}, + {0xada72ccc20054ae9, 0xaf561aa79a10ae6b}, + {0xd910f7ff28069da4, 0x1b2ba1518094da05}, + {0x87aa9aff79042286, 0x90fb44d2f05d0843}, + {0xa99541bf57452b28, 0x353a1607ac744a54}, + {0xd3fa922f2d1675f2, 0x42889b8997915ce9}, + {0x847c9b5d7c2e09b7, 0x69956135febada12}, + {0xa59bc234db398c25, 0x43fab9837e699096}, + {0xcf02b2c21207ef2e, 0x94f967e45e03f4bc}, + {0x8161afb94b44f57d, 0x1d1be0eebac278f6}, + {0xa1ba1ba79e1632dc, 0x6462d92a69731733}, + {0xca28a291859bbf93, 0x7d7b8f7503cfdcff}, + {0xfcb2cb35e702af78, 0x5cda735244c3d43f}, + {0x9defbf01b061adab, 0x3a0888136afa64a8}, + {0xc56baec21c7a1916, 0x088aaa1845b8fdd1}, + {0xf6c69a72a3989f5b, 0x8aad549e57273d46}, + {0x9a3c2087a63f6399, 0x36ac54e2f678864c}, + {0xc0cb28a98fcf3c7f, 0x84576a1bb416a7de}, + {0xf0fdf2d3f3c30b9f, 0x656d44a2a11c51d6}, + {0x969eb7c47859e743, 0x9f644ae5a4b1b326}, + {0xbc4665b596706114, 0x873d5d9f0dde1fef}, + {0xeb57ff22fc0c7959, 0xa90cb506d155a7eb}, + {0x9316ff75dd87cbd8, 0x09a7f12442d588f3}, + {0xb7dcbf5354e9bece, 0x0c11ed6d538aeb30}, + {0xe5d3ef282a242e81, 0x8f1668c8a86da5fb}, + {0x8fa475791a569d10, 0xf96e017d694487bd}, + {0xb38d92d760ec4455, 0x37c981dcc395a9ad}, + {0xe070f78d3927556a, 0x85bbe253f47b1418}, + {0x8c469ab843b89562, 0x93956d7478ccec8f}, + {0xaf58416654a6babb, 0x387ac8d1970027b3}, + {0xdb2e51bfe9d0696a, 0x06997b05fcc0319f}, + {0x88fcf317f22241e2, 0x441fece3bdf81f04}, + {0xab3c2fddeeaad25a, 0xd527e81cad7626c4}, + {0xd60b3bd56a5586f1, 0x8a71e223d8d3b075}, + {0x85c7056562757456, 0xf6872d5667844e4a}, + {0xa738c6bebb12d16c, 0xb428f8ac016561dc}, + {0xd106f86e69d785c7, 0xe13336d701beba53}, + {0x82a45b450226b39c, 0xecc0024661173474}, + {0xa34d721642b06084, 0x27f002d7f95d0191}, + {0xcc20ce9bd35c78a5, 0x31ec038df7b441f5}, + {0xff290242c83396ce, 0x7e67047175a15272}, + {0x9f79a169bd203e41, 0x0f0062c6e984d387}, + {0xc75809c42c684dd1, 0x52c07b78a3e60869}, + {0xf92e0c3537826145, 0xa7709a56ccdf8a83}, + {0x9bbcc7a142b17ccb, 0x88a66076400bb692}, + {0xc2abf989935ddbfe, 0x6acff893d00ea436}, + {0xf356f7ebf83552fe, 0x0583f6b8c4124d44}, + {0x98165af37b2153de, 0xc3727a337a8b704b}, + {0xbe1bf1b059e9a8d6, 0x744f18c0592e4c5d}, + {0xeda2ee1c7064130c, 0x1162def06f79df74}, + {0x9485d4d1c63e8be7, 0x8addcb5645ac2ba9}, + {0xb9a74a0637ce2ee1, 0x6d953e2bd7173693}, + {0xe8111c87c5c1ba99, 0xc8fa8db6ccdd0438}, + {0x910ab1d4db9914a0, 0x1d9c9892400a22a3}, + {0xb54d5e4a127f59c8, 0x2503beb6d00cab4c}, + {0xe2a0b5dc971f303a, 0x2e44ae64840fd61e}, + {0x8da471a9de737e24, 0x5ceaecfed289e5d3}, + {0xb10d8e1456105dad, 0x7425a83e872c5f48}, + {0xdd50f1996b947518, 0xd12f124e28f7771a}, + {0x8a5296ffe33cc92f, 0x82bd6b70d99aaa70}, + {0xace73cbfdc0bfb7b, 0x636cc64d1001550c}, + {0xd8210befd30efa5a, 0x3c47f7e05401aa4f}, + {0x8714a775e3e95c78, 0x65acfaec34810a72}, + {0xa8d9d1535ce3b396, 0x7f1839a741a14d0e}, + {0xd31045a8341ca07c, 0x1ede48111209a051}, + {0x83ea2b892091e44d, 0x934aed0aab460433}, + {0xa4e4b66b68b65d60, 0xf81da84d56178540}, + {0xce1de40642e3f4b9, 0x36251260ab9d668f}, + {0x80d2ae83e9ce78f3, 0xc1d72b7c6b42601a}, + {0xa1075a24e4421730, 0xb24cf65b8612f820}, + {0xc94930ae1d529cfc, 0xdee033f26797b628}, + {0xfb9b7cd9a4a7443c, 0x169840ef017da3b2}, + {0x9d412e0806e88aa5, 0x8e1f289560ee864f}, + {0xc491798a08a2ad4e, 0xf1a6f2bab92a27e3}, + {0xf5b5d7ec8acb58a2, 0xae10af696774b1dc}, + {0x9991a6f3d6bf1765, 0xacca6da1e0a8ef2a}, + {0xbff610b0cc6edd3f, 0x17fd090a58d32af4}, + {0xeff394dcff8a948e, 0xddfc4b4cef07f5b1}, + {0x95f83d0a1fb69cd9, 0x4abdaf101564f98f}, + {0xbb764c4ca7a4440f, 0x9d6d1ad41abe37f2}, + {0xea53df5fd18d5513, 0x84c86189216dc5ee}, + {0x92746b9be2f8552c, 0x32fd3cf5b4e49bb5}, + {0xb7118682dbb66a77, 0x3fbc8c33221dc2a2}, + {0xe4d5e82392a40515, 0x0fabaf3feaa5334b}, + {0x8f05b1163ba6832d, 0x29cb4d87f2a7400f}, + {0xb2c71d5bca9023f8, 0x743e20e9ef511013}, + {0xdf78e4b2bd342cf6, 0x914da9246b255417}, + {0x8bab8eefb6409c1a, 0x1ad089b6c2f7548f}, + {0xae9672aba3d0c320, 0xa184ac2473b529b2}, + {0xda3c0f568cc4f3e8, 0xc9e5d72d90a2741f}, + {0x8865899617fb1871, 0x7e2fa67c7a658893}, + {0xaa7eebfb9df9de8d, 0xddbb901b98feeab8}, + {0xd51ea6fa85785631, 0x552a74227f3ea566}, + {0x8533285c936b35de, 0xd53a88958f872760}, + {0xa67ff273b8460356, 0x8a892abaf368f138}, + {0xd01fef10a657842c, 0x2d2b7569b0432d86}, + {0x8213f56a67f6b29b, 0x9c3b29620e29fc74}, + {0xa298f2c501f45f42, 0x8349f3ba91b47b90}, + {0xcb3f2f7642717713, 0x241c70a936219a74}, + {0xfe0efb53d30dd4d7, 0xed238cd383aa0111}, + {0x9ec95d1463e8a506, 0xf4363804324a40ab}, + {0xc67bb4597ce2ce48, 0xb143c6053edcd0d6}, + {0xf81aa16fdc1b81da, 0xdd94b7868e94050b}, + {0x9b10a4e5e9913128, 0xca7cf2b4191c8327}, + {0xc1d4ce1f63f57d72, 0xfd1c2f611f63a3f1}, + {0xf24a01a73cf2dccf, 0xbc633b39673c8ced}, + {0x976e41088617ca01, 0xd5be0503e085d814}, + {0xbd49d14aa79dbc82, 0x4b2d8644d8a74e19}, + {0xec9c459d51852ba2, 0xddf8e7d60ed1219f}, + {0x93e1ab8252f33b45, 0xcabb90e5c942b504}, + {0xb8da1662e7b00a17, 0x3d6a751f3b936244}, + {0xe7109bfba19c0c9d, 0x0cc512670a783ad5}, + {0x906a617d450187e2, 0x27fb2b80668b24c6}, + {0xb484f9dc9641e9da, 0xb1f9f660802dedf7}, + {0xe1a63853bbd26451, 0x5e7873f8a0396974}, + {0x8d07e33455637eb2, 0xdb0b487b6423e1e9}, + {0xb049dc016abc5e5f, 0x91ce1a9a3d2cda63}, + {0xdc5c5301c56b75f7, 0x7641a140cc7810fc}, + {0x89b9b3e11b6329ba, 0xa9e904c87fcb0a9e}, + {0xac2820d9623bf429, 0x546345fa9fbdcd45}, + {0xd732290fbacaf133, 0xa97c177947ad4096}, + {0x867f59a9d4bed6c0, 0x49ed8eabcccc485e}, + {0xa81f301449ee8c70, 0x5c68f256bfff5a75}, + {0xd226fc195c6a2f8c, 0x73832eec6fff3112}, + {0x83585d8fd9c25db7, 0xc831fd53c5ff7eac}, + {0xa42e74f3d032f525, 0xba3e7ca8b77f5e56}, + {0xcd3a1230c43fb26f, 0x28ce1bd2e55f35ec}, + {0x80444b5e7aa7cf85, 0x7980d163cf5b81b4}, + {0xa0555e361951c366, 0xd7e105bcc3326220}, + {0xc86ab5c39fa63440, 0x8dd9472bf3fefaa8}, + {0xfa856334878fc150, 0xb14f98f6f0feb952}, + {0x9c935e00d4b9d8d2, 0x6ed1bf9a569f33d4}, + {0xc3b8358109e84f07, 0x0a862f80ec4700c9}, + {0xf4a642e14c6262c8, 0xcd27bb612758c0fb}, + {0x98e7e9cccfbd7dbd, 0x8038d51cb897789d}, + {0xbf21e44003acdd2c, 0xe0470a63e6bd56c4}, + {0xeeea5d5004981478, 0x1858ccfce06cac75}, + {0x95527a5202df0ccb, 0x0f37801e0c43ebc9}, + {0xbaa718e68396cffd, 0xd30560258f54e6bb}, + {0xe950df20247c83fd, 0x47c6b82ef32a206a}, + {0x91d28b7416cdd27e, 0x4cdc331d57fa5442}, + {0xb6472e511c81471d, 0xe0133fe4adf8e953}, + {0xe3d8f9e563a198e5, 0x58180fddd97723a7}, + {0x8e679c2f5e44ff8f, 0x570f09eaa7ea7649}, + {0xb201833b35d63f73, 0x2cd2cc6551e513db}, + {0xde81e40a034bcf4f, 0xf8077f7ea65e58d2}, + {0x8b112e86420f6191, 0xfb04afaf27faf783}, + {0xadd57a27d29339f6, 0x79c5db9af1f9b564}, + {0xd94ad8b1c7380874, 0x18375281ae7822bd}, + {0x87cec76f1c830548, 0x8f2293910d0b15b6}, + {0xa9c2794ae3a3c69a, 0xb2eb3875504ddb23}, + {0xd433179d9c8cb841, 0x5fa60692a46151ec}, + {0x849feec281d7f328, 0xdbc7c41ba6bcd334}, + {0xa5c7ea73224deff3, 0x12b9b522906c0801}, + {0xcf39e50feae16bef, 0xd768226b34870a01}, + {0x81842f29f2cce375, 0xe6a1158300d46641}, + {0xa1e53af46f801c53, 0x60495ae3c1097fd1}, + {0xca5e89b18b602368, 0x385bb19cb14bdfc5}, + {0xfcf62c1dee382c42, 0x46729e03dd9ed7b6}, + {0x9e19db92b4e31ba9, 0x6c07a2c26a8346d2}, + {0xc5a05277621be293, 0xc7098b7305241886}, + {0xf70867153aa2db38, 0xb8cbee4fc66d1ea8}, + {0x9a65406d44a5c903, 0x737f74f1dc043329}, + {0xc0fe908895cf3b44, 0x505f522e53053ff3}, + {0xf13e34aabb430a15, 0x647726b9e7c68ff0}, + {0x96c6e0eab509e64d, 0x5eca783430dc19f6}, + {0xbc789925624c5fe0, 0xb67d16413d132073}, + {0xeb96bf6ebadf77d8, 0xe41c5bd18c57e890}, + {0x933e37a534cbaae7, 0x8e91b962f7b6f15a}, + {0xb80dc58e81fe95a1, 0x723627bbb5a4adb1}, + {0xe61136f2227e3b09, 0xcec3b1aaa30dd91d}, + {0x8fcac257558ee4e6, 0x213a4f0aa5e8a7b2}, + {0xb3bd72ed2af29e1f, 0xa988e2cd4f62d19e}, + {0xe0accfa875af45a7, 0x93eb1b80a33b8606}, + {0x8c6c01c9498d8b88, 0xbc72f130660533c4}, + {0xaf87023b9bf0ee6a, 0xeb8fad7c7f8680b5}, + {0xdb68c2ca82ed2a05, 0xa67398db9f6820e2}, +#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, 0x02f236d04753d5b5}, + {0xcde6fd5e09abcf26, 0xed4c0226b55e6f87}, + {0xa6539930bf6bff45, 0x84db8346b786151d}, + {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b3}, + {0xd910f7ff28069da4, 0x1b2ba1518094da05}, + {0xaf58416654a6babb, 0x387ac8d1970027b3}, + {0x8da471a9de737e24, 0x5ceaecfed289e5d3}, + {0xe4d5e82392a40515, 0x0fabaf3feaa5334b}, + {0xb8da1662e7b00a17, 0x3d6a751f3b936244}, + {0x95527a5202df0ccb, 0x0f37801e0c43ebc9}, + {0xf13e34aabb430a15, 0x647726b9e7c68ff0} +#endif + }; + +#if FMT_USE_FULL_CACHE_DRAGONBOX + return pow10_significands[k - float_info::min_k]; +#else + static constexpr const uint64_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}; + + static const int compression_ratio = 27; + + // Compute base index. + int cache_index = (k - float_info::min_k) / compression_ratio; + int kb = cache_index * compression_ratio + float_info::min_k; + int offset = k - kb; + + // Get base cache. + uint128_fallback base_cache = pow10_significands[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 = powers_of_5_64[offset]; + uint128_fallback recovered_cache = umul128(base_cache.high(), pow5); + uint128_fallback middle_low = umul128(base_cache.low(), 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_fallback{(recovered_cache.low() >> alpha) | high_to_middle, + ((middle_low.low() >> alpha) | middle_to_low)}; + FMT_ASSERT(recovered_cache.low() + 1 != 0, ""); + return {recovered_cache.high(), recovered_cache.low() + 1}; +#endif + } + + struct compute_mul_result { + carrier_uint result; + bool is_integer; + }; + struct compute_mul_parity_result { + bool parity; + bool is_integer; + }; + + static auto compute_mul(carrier_uint u, + const cache_entry_type& cache) noexcept + -> compute_mul_result { + auto r = umul192_upper128(u, cache); + return {r.high(), r.low() == 0}; + } + + static auto compute_delta(cache_entry_type const& cache, int beta) noexcept + -> uint32_t { + return static_cast(cache.high() >> (64 - 1 - beta)); + } + + static auto compute_mul_parity(carrier_uint two_f, + const cache_entry_type& cache, + int beta) noexcept + -> compute_mul_parity_result { + FMT_ASSERT(beta >= 1, ""); + FMT_ASSERT(beta < 64, ""); + + auto r = umul192_lower128(two_f, cache); + return {((r.high() >> (64 - beta)) & 1) != 0, + ((r.high() << beta) | (r.low() >> (64 - beta))) == 0}; + } + + static auto compute_left_endpoint_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return (cache.high() - + (cache.high() >> (num_significand_bits() + 2))) >> + (64 - num_significand_bits() - 1 - beta); + } + + static auto compute_right_endpoint_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return (cache.high() + + (cache.high() >> (num_significand_bits() + 1))) >> + (64 - num_significand_bits() - 1 - beta); + } + + static auto compute_round_up_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return ((cache.high() >> (64 - num_significand_bits() - 2 - beta)) + + 1) / + 2; + } +}; + +FMT_FUNC auto get_cached_power(int k) noexcept -> uint128_fallback { + return cache_accessor::get_cached_power(k); +} + +// Various integer checks +template +auto is_left_endpoint_integer_shorter_interval(int exponent) noexcept -> bool { + const int case_shorter_interval_left_endpoint_lower_threshold = 2; + const int case_shorter_interval_left_endpoint_upper_threshold = 3; + return exponent >= case_shorter_interval_left_endpoint_lower_threshold && + exponent <= case_shorter_interval_left_endpoint_upper_threshold; +} + +// Remove trailing zeros from n and return the number of zeros removed (float) +FMT_INLINE int remove_trailing_zeros(uint32_t& n, int s = 0) noexcept { + FMT_ASSERT(n != 0, ""); + // Modular inverse of 5 (mod 2^32): (mod_inv_5 * 5) mod 2^32 = 1. + constexpr uint32_t mod_inv_5 = 0xcccccccd; + constexpr uint32_t mod_inv_25 = 0xc28f5c29; // = mod_inv_5 * mod_inv_5 + + while (true) { + auto q = rotr(n * mod_inv_25, 2); + if (q > max_value() / 100) break; + n = q; + s += 2; + } + auto q = rotr(n * mod_inv_5, 1); + if (q <= max_value() / 10) { + n = q; + s |= 1; + } + return s; +} + +// Removes trailing zeros and returns the number of zeros removed (double) +FMT_INLINE int remove_trailing_zeros(uint64_t& n) noexcept { + FMT_ASSERT(n != 0, ""); + + // This magic number is ceil(2^90 / 10^8). + constexpr uint64_t magic_number = 12379400392853802749ull; + auto nm = umul128(n, magic_number); + + // Is n is divisible by 10^8? + if ((nm.high() & ((1ull << (90 - 64)) - 1)) == 0 && nm.low() < magic_number) { + // If yes, work with the quotient... + auto n32 = static_cast(nm.high() >> (90 - 64)); + // ... and use the 32 bit variant of the function + int s = remove_trailing_zeros(n32, 8); + n = n32; + return s; + } + + // If n is not divisible by 10^8, work with n itself. + constexpr uint64_t mod_inv_5 = 0xcccccccccccccccd; + constexpr uint64_t mod_inv_25 = 0x8f5c28f5c28f5c29; // mod_inv_5 * mod_inv_5 + + int s = 0; + while (true) { + auto q = rotr(n * mod_inv_25, 2); + if (q > max_value() / 100) break; + n = q; + s += 2; + } + auto q = rotr(n * mod_inv_5, 1); + if (q <= max_value() / 10) { + n = q; + s |= 1; + } + + return s; +} + +// The main algorithm for shorter interval case +template +FMT_INLINE decimal_fp shorter_interval_case(int exponent) noexcept { + decimal_fp ret_value; + // Compute k and beta + const int minus_k = floor_log10_pow2_minus_log10_4_over_3(exponent); + const int beta = exponent + floor_log2_pow10(-minus_k); + + // Compute xi and zi + using cache_entry_type = typename cache_accessor::cache_entry_type; + const cache_entry_type cache = cache_accessor::get_cached_power(-minus_k); + + auto xi = cache_accessor::compute_left_endpoint_for_shorter_interval_case( + cache, beta); + auto zi = cache_accessor::compute_right_endpoint_for_shorter_interval_case( + cache, beta); + + // If the left endpoint is not an integer, increase it + if (!is_left_endpoint_integer_shorter_interval(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::compute_round_up_for_shorter_interval_case(cache, + beta); + ret_value.exponent = minus_k; + + // When tie occurs, choose one of them according to the rule + if (exponent >= float_info::shorter_interval_tie_lower_threshold && + exponent <= float_info::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 auto to_decimal(T x) noexcept -> decimal_fp { + // Step 1: integer promotion & Schubfach multiplier calculation. + + using carrier_uint = typename float_info::carrier_uint; + using cache_entry_type = typename cache_accessor::cache_entry_type; + auto br = bit_cast(x); + + // Extract significand bits and exponent bits. + const carrier_uint significand_mask = + (static_cast(1) << num_significand_bits()) - 1; + carrier_uint significand = (br & significand_mask); + int exponent = + static_cast((br & exponent_mask()) >> num_significand_bits()); + + if (exponent != 0) { // Check if normal. + exponent -= exponent_bias() + num_significand_bits(); + + // Shorter interval case; proceed like Schubfach. + // In fact, when exponent == 1 and significand == 0, the interval is + // regular. However, it can be shown that the end-results are anyway same. + if (significand == 0) return shorter_interval_case(exponent); + + significand |= (static_cast(1) << num_significand_bits()); + } else { + // Subnormal case; the interval is always regular. + if (significand == 0) return {0, 0}; + exponent = + std::numeric_limits::min_exponent - num_significand_bits() - 1; + } + + 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::kappa; + const cache_entry_type cache = cache_accessor::get_cached_power(-minus_k); + const int beta = exponent + floor_log2_pow10(-minus_k); + + // Compute zi and deltai. + // 10^kappa <= deltai < 10^(kappa + 1) + const uint32_t deltai = cache_accessor::compute_delta(cache, beta); + const carrier_uint two_fc = significand << 1; + + // For the case of binary32, the result of integer check is not correct for + // 29711844 * 2^-82 + // = 6.1442653300000000008655037797566933477355632930994033813476... * 10^-18 + // and 29711844 * 2^-81 + // = 1.2288530660000000001731007559513386695471126586198806762695... * 10^-17, + // and they are the unique counterexamples. However, since 29711844 is even, + // this does not cause any problem for the endpoints calculations; it can only + // cause a problem when we need to perform integer check for the center. + // Fortunately, with these inputs, that branch is never executed, so we are + // fine. + const typename cache_accessor::compute_mul_result z_mul = + cache_accessor::compute_mul((two_fc | 1) << beta, 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 ret_value; + ret_value.significand = divide_by_10_to_kappa_plus_1(z_mul.result); + uint32_t r = static_cast(z_mul.result - float_info::big_divisor * + ret_value.significand); + + if (r < deltai) { + // Exclude the right endpoint if necessary. + if (r == 0 && (z_mul.is_integer & !include_right_endpoint)) { + --ret_value.significand; + r = float_info::big_divisor; + goto small_divisor_case_label; + } + } else if (r > deltai) { + goto small_divisor_case_label; + } else { + // r == deltai; compare fractional parts. + const typename cache_accessor::compute_mul_parity_result x_mul = + cache_accessor::compute_mul_parity(two_fc - 1, cache, beta); + + if (!(x_mul.parity | (x_mul.is_integer & include_left_endpoint))) + goto small_divisor_case_label; + } + ret_value.exponent = minus_k + float_info::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::kappa; + + uint32_t dist = r - (deltai / 2) + (float_info::small_divisor / 2); + const bool approx_y_parity = + ((dist ^ (float_info::small_divisor / 2)) & 1) != 0; + + // Is dist divisible by 10^kappa? + const bool divisible_by_small_divisor = + check_divisibility_and_divide_by_pow10::kappa>(dist); + + // Add dist / 10^kappa to the significand. + ret_value.significand += dist; + + if (!divisible_by_small_divisor) return ret_value; + + // 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. + const auto y_mul = cache_accessor::compute_mul_parity(two_fc, cache, beta); + + // If z^(f) >= epsilon^(f), we might have a tie when z^(f) == epsilon^(f), + // or equivalently, when y is an integer. + if (y_mul.parity != approx_y_parity) + --ret_value.significand; + else if (y_mul.is_integer & (ret_value.significand % 2 != 0)) + --ret_value.significand; + return ret_value; +} +} // namespace dragonbox +} // namespace detail + +template <> struct formatter { + FMT_CONSTEXPR auto parse(format_parse_context& ctx) + -> format_parse_context::iterator { + return ctx.begin(); + } + + auto format(const detail::bigint& n, format_context& ctx) const + -> format_context::iterator { + 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 = fmt::format_to(out, FMT_STRING("{:x}"), value); + first = false; + continue; + } + out = fmt::format_to(out, FMT_STRING("{:08x}"), value); + } + if (n.exp_ > 0) + out = fmt::format_to(out, FMT_STRING("p{}"), + n.exp_ * detail::bigint::bigit_bits); + return out; + } +}; + +FMT_FUNC detail::utf8_to_utf16::utf8_to_utf16(string_view s) { + for_each_codepoint(s, [this](uint32_t cp, string_view) { + if (cp == invalid_code_point) FMT_THROW(std::runtime_error("invalid utf8")); + if (cp <= 0xFFFF) { + buffer_.push_back(static_cast(cp)); + } else { + cp -= 0x10000; + buffer_.push_back(static_cast(0xD800 + (cp >> 10))); + buffer_.push_back(static_cast(0xDC00 + (cp & 0x3FF))); + } + return true; + }); + buffer_.push_back(0); +} + +FMT_FUNC void format_system_error(detail::buffer& out, int error_code, + const char* message) noexcept { + FMT_TRY { + auto ec = std::error_code(error_code, std::generic_category()); + write(std::back_inserter(out), std::system_error(ec, message).what()); + return; + } + FMT_CATCH(...) {} + format_error_code(out, error_code, message); +} + +FMT_FUNC void report_system_error(int error_code, + const char* message) noexcept { + report_error(format_system_error, error_code, message); +} + +FMT_FUNC auto vformat(string_view fmt, format_args args) -> std::string { + // Don't optimize the "{}" case to keep the binary size small and because it + // can be better optimized in fmt::format anyway. + auto buffer = memory_buffer(); + detail::vformat_to(buffer, fmt, args); + return to_string(buffer); +} + +namespace detail { +#if !defined(_WIN32) || defined(FMT_WINDOWS_NO_WCHAR) +FMT_FUNC auto write_console(int, string_view) -> bool { return false; } +FMT_FUNC auto write_console(std::FILE*, string_view) -> bool { return false; } +#else +using dword = conditional_t; +extern "C" __declspec(dllimport) int __stdcall WriteConsoleW( // + void*, const void*, dword, dword*, void*); + +FMT_FUNC bool write_console(int fd, string_view text) { + auto u16 = utf8_to_utf16(text); + return WriteConsoleW(reinterpret_cast(_get_osfhandle(fd)), u16.c_str(), + static_cast(u16.size()), nullptr, nullptr) != 0; +} + +FMT_FUNC auto write_console(std::FILE* f, string_view text) -> bool { + return write_console(_fileno(f), text); +} +#endif + +#ifdef _WIN32 +// Print assuming legacy (non-Unicode) encoding. +FMT_FUNC void vprint_mojibake(std::FILE* f, string_view fmt, format_args args) { + auto buffer = memory_buffer(); + detail::vformat_to(buffer, fmt, args); + fwrite_fully(buffer.data(), buffer.size(), f); +} +#endif + +FMT_FUNC void print(std::FILE* f, string_view text) { +#ifdef _WIN32 + int fd = _fileno(f); + if (_isatty(fd)) { + std::fflush(f); + if (write_console(fd, text)) return; + } +#endif + fwrite_fully(text.data(), text.size(), f); +} +} // namespace detail + +FMT_FUNC void vprint(std::FILE* f, string_view fmt, format_args args) { + auto buffer = memory_buffer(); + detail::vformat_to(buffer, fmt, args); + detail::print(f, {buffer.data(), buffer.size()}); +} + +FMT_FUNC void vprint(string_view fmt, format_args args) { + vprint(stdout, fmt, args); +} + +namespace detail { + +struct singleton { + unsigned char upper; + unsigned char lower_count; +}; + +inline auto is_printable(uint16_t x, const singleton* singletons, + size_t singletons_size, + const unsigned char* singleton_lowers, + const unsigned char* normal, size_t normal_size) + -> bool { + auto upper = x >> 8; + auto lower_start = 0; + for (size_t i = 0; i < singletons_size; ++i) { + auto s = singletons[i]; + auto lower_end = lower_start + s.lower_count; + if (upper < s.upper) break; + if (upper == s.upper) { + for (auto j = lower_start; j < lower_end; ++j) { + if (singleton_lowers[j] == (x & 0xff)) return false; + } + } + lower_start = lower_end; + } + + auto xsigned = static_cast(x); + auto current = true; + for (size_t i = 0; i < normal_size; ++i) { + auto v = static_cast(normal[i]); + auto len = (v & 0x80) != 0 ? (v & 0x7f) << 8 | normal[++i] : v; + xsigned -= len; + if (xsigned < 0) break; + current = !current; + } + return current; +} + +// This code is generated by support/printable.py. +FMT_FUNC auto is_printable(uint32_t cp) -> bool { + static constexpr singleton singletons0[] = { + {0x00, 1}, {0x03, 5}, {0x05, 6}, {0x06, 3}, {0x07, 6}, {0x08, 8}, + {0x09, 17}, {0x0a, 28}, {0x0b, 25}, {0x0c, 20}, {0x0d, 16}, {0x0e, 13}, + {0x0f, 4}, {0x10, 3}, {0x12, 18}, {0x13, 9}, {0x16, 1}, {0x17, 5}, + {0x18, 2}, {0x19, 3}, {0x1a, 7}, {0x1c, 2}, {0x1d, 1}, {0x1f, 22}, + {0x20, 3}, {0x2b, 3}, {0x2c, 2}, {0x2d, 11}, {0x2e, 1}, {0x30, 3}, + {0x31, 2}, {0x32, 1}, {0xa7, 2}, {0xa9, 2}, {0xaa, 4}, {0xab, 8}, + {0xfa, 2}, {0xfb, 5}, {0xfd, 4}, {0xfe, 3}, {0xff, 9}, + }; + static constexpr unsigned char singletons0_lower[] = { + 0xad, 0x78, 0x79, 0x8b, 0x8d, 0xa2, 0x30, 0x57, 0x58, 0x8b, 0x8c, 0x90, + 0x1c, 0x1d, 0xdd, 0x0e, 0x0f, 0x4b, 0x4c, 0xfb, 0xfc, 0x2e, 0x2f, 0x3f, + 0x5c, 0x5d, 0x5f, 0xb5, 0xe2, 0x84, 0x8d, 0x8e, 0x91, 0x92, 0xa9, 0xb1, + 0xba, 0xbb, 0xc5, 0xc6, 0xc9, 0xca, 0xde, 0xe4, 0xe5, 0xff, 0x00, 0x04, + 0x11, 0x12, 0x29, 0x31, 0x34, 0x37, 0x3a, 0x3b, 0x3d, 0x49, 0x4a, 0x5d, + 0x84, 0x8e, 0x92, 0xa9, 0xb1, 0xb4, 0xba, 0xbb, 0xc6, 0xca, 0xce, 0xcf, + 0xe4, 0xe5, 0x00, 0x04, 0x0d, 0x0e, 0x11, 0x12, 0x29, 0x31, 0x34, 0x3a, + 0x3b, 0x45, 0x46, 0x49, 0x4a, 0x5e, 0x64, 0x65, 0x84, 0x91, 0x9b, 0x9d, + 0xc9, 0xce, 0xcf, 0x0d, 0x11, 0x29, 0x45, 0x49, 0x57, 0x64, 0x65, 0x8d, + 0x91, 0xa9, 0xb4, 0xba, 0xbb, 0xc5, 0xc9, 0xdf, 0xe4, 0xe5, 0xf0, 0x0d, + 0x11, 0x45, 0x49, 0x64, 0x65, 0x80, 0x84, 0xb2, 0xbc, 0xbe, 0xbf, 0xd5, + 0xd7, 0xf0, 0xf1, 0x83, 0x85, 0x8b, 0xa4, 0xa6, 0xbe, 0xbf, 0xc5, 0xc7, + 0xce, 0xcf, 0xda, 0xdb, 0x48, 0x98, 0xbd, 0xcd, 0xc6, 0xce, 0xcf, 0x49, + 0x4e, 0x4f, 0x57, 0x59, 0x5e, 0x5f, 0x89, 0x8e, 0x8f, 0xb1, 0xb6, 0xb7, + 0xbf, 0xc1, 0xc6, 0xc7, 0xd7, 0x11, 0x16, 0x17, 0x5b, 0x5c, 0xf6, 0xf7, + 0xfe, 0xff, 0x80, 0x0d, 0x6d, 0x71, 0xde, 0xdf, 0x0e, 0x0f, 0x1f, 0x6e, + 0x6f, 0x1c, 0x1d, 0x5f, 0x7d, 0x7e, 0xae, 0xaf, 0xbb, 0xbc, 0xfa, 0x16, + 0x17, 0x1e, 0x1f, 0x46, 0x47, 0x4e, 0x4f, 0x58, 0x5a, 0x5c, 0x5e, 0x7e, + 0x7f, 0xb5, 0xc5, 0xd4, 0xd5, 0xdc, 0xf0, 0xf1, 0xf5, 0x72, 0x73, 0x8f, + 0x74, 0x75, 0x96, 0x2f, 0x5f, 0x26, 0x2e, 0x2f, 0xa7, 0xaf, 0xb7, 0xbf, + 0xc7, 0xcf, 0xd7, 0xdf, 0x9a, 0x40, 0x97, 0x98, 0x30, 0x8f, 0x1f, 0xc0, + 0xc1, 0xce, 0xff, 0x4e, 0x4f, 0x5a, 0x5b, 0x07, 0x08, 0x0f, 0x10, 0x27, + 0x2f, 0xee, 0xef, 0x6e, 0x6f, 0x37, 0x3d, 0x3f, 0x42, 0x45, 0x90, 0x91, + 0xfe, 0xff, 0x53, 0x67, 0x75, 0xc8, 0xc9, 0xd0, 0xd1, 0xd8, 0xd9, 0xe7, + 0xfe, 0xff, + }; + static constexpr singleton singletons1[] = { + {0x00, 6}, {0x01, 1}, {0x03, 1}, {0x04, 2}, {0x08, 8}, {0x09, 2}, + {0x0a, 5}, {0x0b, 2}, {0x0e, 4}, {0x10, 1}, {0x11, 2}, {0x12, 5}, + {0x13, 17}, {0x14, 1}, {0x15, 2}, {0x17, 2}, {0x19, 13}, {0x1c, 5}, + {0x1d, 8}, {0x24, 1}, {0x6a, 3}, {0x6b, 2}, {0xbc, 2}, {0xd1, 2}, + {0xd4, 12}, {0xd5, 9}, {0xd6, 2}, {0xd7, 2}, {0xda, 1}, {0xe0, 5}, + {0xe1, 2}, {0xe8, 2}, {0xee, 32}, {0xf0, 4}, {0xf8, 2}, {0xf9, 2}, + {0xfa, 2}, {0xfb, 1}, + }; + static constexpr unsigned char singletons1_lower[] = { + 0x0c, 0x27, 0x3b, 0x3e, 0x4e, 0x4f, 0x8f, 0x9e, 0x9e, 0x9f, 0x06, 0x07, + 0x09, 0x36, 0x3d, 0x3e, 0x56, 0xf3, 0xd0, 0xd1, 0x04, 0x14, 0x18, 0x36, + 0x37, 0x56, 0x57, 0x7f, 0xaa, 0xae, 0xaf, 0xbd, 0x35, 0xe0, 0x12, 0x87, + 0x89, 0x8e, 0x9e, 0x04, 0x0d, 0x0e, 0x11, 0x12, 0x29, 0x31, 0x34, 0x3a, + 0x45, 0x46, 0x49, 0x4a, 0x4e, 0x4f, 0x64, 0x65, 0x5c, 0xb6, 0xb7, 0x1b, + 0x1c, 0x07, 0x08, 0x0a, 0x0b, 0x14, 0x17, 0x36, 0x39, 0x3a, 0xa8, 0xa9, + 0xd8, 0xd9, 0x09, 0x37, 0x90, 0x91, 0xa8, 0x07, 0x0a, 0x3b, 0x3e, 0x66, + 0x69, 0x8f, 0x92, 0x6f, 0x5f, 0xee, 0xef, 0x5a, 0x62, 0x9a, 0x9b, 0x27, + 0x28, 0x55, 0x9d, 0xa0, 0xa1, 0xa3, 0xa4, 0xa7, 0xa8, 0xad, 0xba, 0xbc, + 0xc4, 0x06, 0x0b, 0x0c, 0x15, 0x1d, 0x3a, 0x3f, 0x45, 0x51, 0xa6, 0xa7, + 0xcc, 0xcd, 0xa0, 0x07, 0x19, 0x1a, 0x22, 0x25, 0x3e, 0x3f, 0xc5, 0xc6, + 0x04, 0x20, 0x23, 0x25, 0x26, 0x28, 0x33, 0x38, 0x3a, 0x48, 0x4a, 0x4c, + 0x50, 0x53, 0x55, 0x56, 0x58, 0x5a, 0x5c, 0x5e, 0x60, 0x63, 0x65, 0x66, + 0x6b, 0x73, 0x78, 0x7d, 0x7f, 0x8a, 0xa4, 0xaa, 0xaf, 0xb0, 0xc0, 0xd0, + 0xae, 0xaf, 0x79, 0xcc, 0x6e, 0x6f, 0x93, + }; + static constexpr unsigned char normal0[] = { + 0x00, 0x20, 0x5f, 0x22, 0x82, 0xdf, 0x04, 0x82, 0x44, 0x08, 0x1b, 0x04, + 0x06, 0x11, 0x81, 0xac, 0x0e, 0x80, 0xab, 0x35, 0x28, 0x0b, 0x80, 0xe0, + 0x03, 0x19, 0x08, 0x01, 0x04, 0x2f, 0x04, 0x34, 0x04, 0x07, 0x03, 0x01, + 0x07, 0x06, 0x07, 0x11, 0x0a, 0x50, 0x0f, 0x12, 0x07, 0x55, 0x07, 0x03, + 0x04, 0x1c, 0x0a, 0x09, 0x03, 0x08, 0x03, 0x07, 0x03, 0x02, 0x03, 0x03, + 0x03, 0x0c, 0x04, 0x05, 0x03, 0x0b, 0x06, 0x01, 0x0e, 0x15, 0x05, 0x3a, + 0x03, 0x11, 0x07, 0x06, 0x05, 0x10, 0x07, 0x57, 0x07, 0x02, 0x07, 0x15, + 0x0d, 0x50, 0x04, 0x43, 0x03, 0x2d, 0x03, 0x01, 0x04, 0x11, 0x06, 0x0f, + 0x0c, 0x3a, 0x04, 0x1d, 0x25, 0x5f, 0x20, 0x6d, 0x04, 0x6a, 0x25, 0x80, + 0xc8, 0x05, 0x82, 0xb0, 0x03, 0x1a, 0x06, 0x82, 0xfd, 0x03, 0x59, 0x07, + 0x15, 0x0b, 0x17, 0x09, 0x14, 0x0c, 0x14, 0x0c, 0x6a, 0x06, 0x0a, 0x06, + 0x1a, 0x06, 0x59, 0x07, 0x2b, 0x05, 0x46, 0x0a, 0x2c, 0x04, 0x0c, 0x04, + 0x01, 0x03, 0x31, 0x0b, 0x2c, 0x04, 0x1a, 0x06, 0x0b, 0x03, 0x80, 0xac, + 0x06, 0x0a, 0x06, 0x21, 0x3f, 0x4c, 0x04, 0x2d, 0x03, 0x74, 0x08, 0x3c, + 0x03, 0x0f, 0x03, 0x3c, 0x07, 0x38, 0x08, 0x2b, 0x05, 0x82, 0xff, 0x11, + 0x18, 0x08, 0x2f, 0x11, 0x2d, 0x03, 0x20, 0x10, 0x21, 0x0f, 0x80, 0x8c, + 0x04, 0x82, 0x97, 0x19, 0x0b, 0x15, 0x88, 0x94, 0x05, 0x2f, 0x05, 0x3b, + 0x07, 0x02, 0x0e, 0x18, 0x09, 0x80, 0xb3, 0x2d, 0x74, 0x0c, 0x80, 0xd6, + 0x1a, 0x0c, 0x05, 0x80, 0xff, 0x05, 0x80, 0xdf, 0x0c, 0xee, 0x0d, 0x03, + 0x84, 0x8d, 0x03, 0x37, 0x09, 0x81, 0x5c, 0x14, 0x80, 0xb8, 0x08, 0x80, + 0xcb, 0x2a, 0x38, 0x03, 0x0a, 0x06, 0x38, 0x08, 0x46, 0x08, 0x0c, 0x06, + 0x74, 0x0b, 0x1e, 0x03, 0x5a, 0x04, 0x59, 0x09, 0x80, 0x83, 0x18, 0x1c, + 0x0a, 0x16, 0x09, 0x4c, 0x04, 0x80, 0x8a, 0x06, 0xab, 0xa4, 0x0c, 0x17, + 0x04, 0x31, 0xa1, 0x04, 0x81, 0xda, 0x26, 0x07, 0x0c, 0x05, 0x05, 0x80, + 0xa5, 0x11, 0x81, 0x6d, 0x10, 0x78, 0x28, 0x2a, 0x06, 0x4c, 0x04, 0x80, + 0x8d, 0x04, 0x80, 0xbe, 0x03, 0x1b, 0x03, 0x0f, 0x0d, + }; + static constexpr unsigned char normal1[] = { + 0x5e, 0x22, 0x7b, 0x05, 0x03, 0x04, 0x2d, 0x03, 0x66, 0x03, 0x01, 0x2f, + 0x2e, 0x80, 0x82, 0x1d, 0x03, 0x31, 0x0f, 0x1c, 0x04, 0x24, 0x09, 0x1e, + 0x05, 0x2b, 0x05, 0x44, 0x04, 0x0e, 0x2a, 0x80, 0xaa, 0x06, 0x24, 0x04, + 0x24, 0x04, 0x28, 0x08, 0x34, 0x0b, 0x01, 0x80, 0x90, 0x81, 0x37, 0x09, + 0x16, 0x0a, 0x08, 0x80, 0x98, 0x39, 0x03, 0x63, 0x08, 0x09, 0x30, 0x16, + 0x05, 0x21, 0x03, 0x1b, 0x05, 0x01, 0x40, 0x38, 0x04, 0x4b, 0x05, 0x2f, + 0x04, 0x0a, 0x07, 0x09, 0x07, 0x40, 0x20, 0x27, 0x04, 0x0c, 0x09, 0x36, + 0x03, 0x3a, 0x05, 0x1a, 0x07, 0x04, 0x0c, 0x07, 0x50, 0x49, 0x37, 0x33, + 0x0d, 0x33, 0x07, 0x2e, 0x08, 0x0a, 0x81, 0x26, 0x52, 0x4e, 0x28, 0x08, + 0x2a, 0x56, 0x1c, 0x14, 0x17, 0x09, 0x4e, 0x04, 0x1e, 0x0f, 0x43, 0x0e, + 0x19, 0x07, 0x0a, 0x06, 0x48, 0x08, 0x27, 0x09, 0x75, 0x0b, 0x3f, 0x41, + 0x2a, 0x06, 0x3b, 0x05, 0x0a, 0x06, 0x51, 0x06, 0x01, 0x05, 0x10, 0x03, + 0x05, 0x80, 0x8b, 0x62, 0x1e, 0x48, 0x08, 0x0a, 0x80, 0xa6, 0x5e, 0x22, + 0x45, 0x0b, 0x0a, 0x06, 0x0d, 0x13, 0x39, 0x07, 0x0a, 0x36, 0x2c, 0x04, + 0x10, 0x80, 0xc0, 0x3c, 0x64, 0x53, 0x0c, 0x48, 0x09, 0x0a, 0x46, 0x45, + 0x1b, 0x48, 0x08, 0x53, 0x1d, 0x39, 0x81, 0x07, 0x46, 0x0a, 0x1d, 0x03, + 0x47, 0x49, 0x37, 0x03, 0x0e, 0x08, 0x0a, 0x06, 0x39, 0x07, 0x0a, 0x81, + 0x36, 0x19, 0x80, 0xb7, 0x01, 0x0f, 0x32, 0x0d, 0x83, 0x9b, 0x66, 0x75, + 0x0b, 0x80, 0xc4, 0x8a, 0xbc, 0x84, 0x2f, 0x8f, 0xd1, 0x82, 0x47, 0xa1, + 0xb9, 0x82, 0x39, 0x07, 0x2a, 0x04, 0x02, 0x60, 0x26, 0x0a, 0x46, 0x0a, + 0x28, 0x05, 0x13, 0x82, 0xb0, 0x5b, 0x65, 0x4b, 0x04, 0x39, 0x07, 0x11, + 0x40, 0x05, 0x0b, 0x02, 0x0e, 0x97, 0xf8, 0x08, 0x84, 0xd6, 0x2a, 0x09, + 0xa2, 0xf7, 0x81, 0x1f, 0x31, 0x03, 0x11, 0x04, 0x08, 0x81, 0x8c, 0x89, + 0x04, 0x6b, 0x05, 0x0d, 0x03, 0x09, 0x07, 0x10, 0x93, 0x60, 0x80, 0xf6, + 0x0a, 0x73, 0x08, 0x6e, 0x17, 0x46, 0x80, 0x9a, 0x14, 0x0c, 0x57, 0x09, + 0x19, 0x80, 0x87, 0x81, 0x47, 0x03, 0x85, 0x42, 0x0f, 0x15, 0x85, 0x50, + 0x2b, 0x80, 0xd5, 0x2d, 0x03, 0x1a, 0x04, 0x02, 0x81, 0x70, 0x3a, 0x05, + 0x01, 0x85, 0x00, 0x80, 0xd7, 0x29, 0x4c, 0x04, 0x0a, 0x04, 0x02, 0x83, + 0x11, 0x44, 0x4c, 0x3d, 0x80, 0xc2, 0x3c, 0x06, 0x01, 0x04, 0x55, 0x05, + 0x1b, 0x34, 0x02, 0x81, 0x0e, 0x2c, 0x04, 0x64, 0x0c, 0x56, 0x0a, 0x80, + 0xae, 0x38, 0x1d, 0x0d, 0x2c, 0x04, 0x09, 0x07, 0x02, 0x0e, 0x06, 0x80, + 0x9a, 0x83, 0xd8, 0x08, 0x0d, 0x03, 0x0d, 0x03, 0x74, 0x0c, 0x59, 0x07, + 0x0c, 0x14, 0x0c, 0x04, 0x38, 0x08, 0x0a, 0x06, 0x28, 0x08, 0x22, 0x4e, + 0x81, 0x54, 0x0c, 0x15, 0x03, 0x03, 0x05, 0x07, 0x09, 0x19, 0x07, 0x07, + 0x09, 0x03, 0x0d, 0x07, 0x29, 0x80, 0xcb, 0x25, 0x0a, 0x84, 0x06, + }; + auto lower = static_cast(cp); + if (cp < 0x10000) { + return is_printable(lower, singletons0, + sizeof(singletons0) / sizeof(*singletons0), + singletons0_lower, normal0, sizeof(normal0)); + } + if (cp < 0x20000) { + return is_printable(lower, singletons1, + sizeof(singletons1) / sizeof(*singletons1), + singletons1_lower, normal1, sizeof(normal1)); + } + if (0x2a6de <= cp && cp < 0x2a700) return false; + if (0x2b735 <= cp && cp < 0x2b740) return false; + if (0x2b81e <= cp && cp < 0x2b820) return false; + if (0x2cea2 <= cp && cp < 0x2ceb0) return false; + if (0x2ebe1 <= cp && cp < 0x2f800) return false; + if (0x2fa1e <= cp && cp < 0x30000) return false; + if (0x3134b <= cp && cp < 0xe0100) return false; + if (0xe01f0 <= cp && cp < 0x110000) return false; + return cp < 0x110000; +} + +} // namespace detail + +FMT_END_NAMESPACE + +#endif // FMT_FORMAT_INL_H_ diff --git a/third_party/fmt/include/fmt/format.h b/third_party/fmt/include/fmt/format.h new file mode 100644 index 0000000..7637c8a --- /dev/null +++ b/third_party/fmt/include/fmt/format.h @@ -0,0 +1,4535 @@ +/* + 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 // std::signbit +#include // uint32_t +#include // std::memcpy +#include // std::initializer_list +#include // std::numeric_limits +#include // std::uninitialized_copy +#include // std::runtime_error +#include // std::system_error + +#ifdef __cpp_lib_bit_cast +# include // std::bit_cast +#endif + +#include "core.h" + +#if defined __cpp_inline_variables && __cpp_inline_variables >= 201606L +# define FMT_INLINE_VARIABLE inline +#else +# define FMT_INLINE_VARIABLE +#endif + +#if FMT_HAS_CPP17_ATTRIBUTE(fallthrough) +# define FMT_FALLTHROUGH [[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 + +#ifndef FMT_DEPRECATED +# if FMT_HAS_CPP14_ATTRIBUTE(deprecated) || FMT_MSC_VERSION >= 1900 +# define FMT_DEPRECATED [[deprecated]] +# else +# if (defined(__GNUC__) && !defined(__LCC__)) || defined(__clang__) +# define FMT_DEPRECATED __attribute__((deprecated)) +# elif FMT_MSC_VERSION +# define FMT_DEPRECATED __declspec(deprecated) +# else +# define FMT_DEPRECATED /* deprecated */ +# endif +# endif +#endif + +#ifndef FMT_NO_UNIQUE_ADDRESS +# if FMT_CPLUSPLUS >= 202002L +# if FMT_HAS_CPP_ATTRIBUTE(no_unique_address) +# define FMT_NO_UNIQUE_ADDRESS [[no_unique_address]] +// VS2019 v16.10 and later except clang-cl (https://reviews.llvm.org/D110485) +# elif (FMT_MSC_VERSION >= 1929) && !FMT_CLANG_VERSION +# define FMT_NO_UNIQUE_ADDRESS [[msvc::no_unique_address]] +# endif +# endif +#endif +#ifndef FMT_NO_UNIQUE_ADDRESS +# define FMT_NO_UNIQUE_ADDRESS +#endif + +// Visibility when compiled as a shared library/object. +#if defined(FMT_LIB_EXPORT) || defined(FMT_SHARED) +# define FMT_SO_VISIBILITY(value) FMT_VISIBILITY(value) +#else +# define FMT_SO_VISIBILITY(value) +#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 + +#ifndef FMT_THROW +# if FMT_EXCEPTIONS +# if FMT_MSC_VERSION || defined(__NVCC__) +FMT_BEGIN_NAMESPACE +namespace detail { +template 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) \ + ::fmt::detail::assert_fail(__FILE__, __LINE__, (x).what()) +# 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_MAYBE_UNUSED +# if FMT_HAS_CPP17_ATTRIBUTE(maybe_unused) +# define FMT_MAYBE_UNUSED [[maybe_unused]] +# else +# define FMT_MAYBE_UNUSED +# endif +#endif + +#ifndef FMT_USE_USER_DEFINED_LITERALS +// EDG based compilers (Intel, NVIDIA, Elbrus, etc), GCC and MSVC support UDLs. +// +// GCC before 4.9 requires a space in `operator"" _a` which is invalid in later +// compiler versions. +# if (FMT_HAS_FEATURE(cxx_user_literals) || FMT_GCC_VERSION >= 409 || \ + FMT_MSC_VERSION >= 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 + +// Defining FMT_REDUCE_INT_INSTANTIATIONS to 1, will reduce the number of +// integer formatter template instantiations 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_MSC_VERSION +# if FMT_HAS_BUILTIN(__builtin_clz) || FMT_GCC_VERSION || FMT_ICC_VERSION +# define FMT_BUILTIN_CLZ(n) __builtin_clz(n) +# endif +# if FMT_HAS_BUILTIN(__builtin_clzll) || FMT_GCC_VERSION || FMT_ICC_VERSION +# define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n) +# endif +#endif + +// __builtin_ctz is broken in Intel Compiler Classic on Windows: +// https://github.com/fmtlib/fmt/issues/2510. +#ifndef __ICL +# if FMT_HAS_BUILTIN(__builtin_ctz) || FMT_GCC_VERSION || FMT_ICC_VERSION || \ + defined(__NVCOMPILER) +# define FMT_BUILTIN_CTZ(n) __builtin_ctz(n) +# endif +# if FMT_HAS_BUILTIN(__builtin_ctzll) || FMT_GCC_VERSION || \ + FMT_ICC_VERSION || defined(__NVCOMPILER) +# define FMT_BUILTIN_CTZLL(n) __builtin_ctzll(n) +# endif +#endif + +#if FMT_MSC_VERSION +# include // _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_VERSION && !defined(FMT_BUILTIN_CLZLL) && \ + !defined(FMT_BUILTIN_CTZLL) +FMT_BEGIN_NAMESPACE +namespace detail { +// Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning. +# if !defined(__clang__) +# pragma intrinsic(_BitScanForward) +# pragma intrinsic(_BitScanReverse) +# if defined(_WIN64) +# pragma intrinsic(_BitScanForward64) +# pragma intrinsic(_BitScanReverse64) +# endif +# endif + +inline auto clz(uint32_t x) -> int { + 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_MSC_WARNING(suppress : 6102) + return 31 ^ static_cast(r); +} +# define FMT_BUILTIN_CLZ(n) detail::clz(n) + +inline auto clzll(uint64_t x) -> int { + unsigned long r = 0; +# ifdef _WIN64 + _BitScanReverse64(&r, x); +# else + // Scan the high 32 bits. + if (_BitScanReverse(&r, static_cast(x >> 32))) + return 63 ^ static_cast(r + 32); + // Scan the low 32 bits. + _BitScanReverse(&r, static_cast(x)); +# endif + FMT_ASSERT(x != 0, ""); + FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning. + return 63 ^ static_cast(r); +} +# define FMT_BUILTIN_CLZLL(n) detail::clzll(n) + +inline auto ctz(uint32_t x) -> int { + unsigned long r = 0; + _BitScanForward(&r, x); + FMT_ASSERT(x != 0, ""); + FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning. + return static_cast(r); +} +# define FMT_BUILTIN_CTZ(n) detail::ctz(n) + +inline auto ctzll(uint64_t x) -> int { + unsigned long r = 0; + FMT_ASSERT(x != 0, ""); + FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning. +# ifdef _WIN64 + _BitScanForward64(&r, x); +# else + // Scan the low 32 bits. + if (_BitScanForward(&r, static_cast(x))) return static_cast(r); + // Scan the high 32 bits. + _BitScanForward(&r, static_cast(x >> 32)); + r += 32; +# endif + return static_cast(r); +} +# define FMT_BUILTIN_CTZLL(n) detail::ctzll(n) +} // namespace detail +FMT_END_NAMESPACE +#endif + +FMT_BEGIN_NAMESPACE +namespace detail { + +FMT_CONSTEXPR inline void abort_fuzzing_if(bool condition) { + ignore_unused(condition); +#ifdef FMT_FUZZ + if (condition) throw std::runtime_error("fuzzing limit reached"); +#endif +} + +template struct string_literal { + static constexpr CharT value[sizeof...(C)] = {C...}; + constexpr operator basic_string_view() const { + return {value, sizeof...(C)}; + } +}; + +#if FMT_CPLUSPLUS < 201703L +template +constexpr CharT string_literal::value[sizeof...(C)]; +#endif + +// Implementation of std::bit_cast for pre-C++20. +template +FMT_CONSTEXPR20 auto bit_cast(const From& from) -> To { +#ifdef __cpp_lib_bit_cast + if (is_constant_evaluated()) return std::bit_cast(from); +#endif + auto to = To(); + // The cast suppresses a bogus -Wclass-memaccess on GCC. + std::memcpy(static_cast(&to), &from, sizeof(to)); + return to; +} + +inline auto is_big_endian() -> bool { +#ifdef _WIN32 + return false; +#elif defined(__BIG_ENDIAN__) + return true; +#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) + return __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__; +#else + struct bytes { + char data[sizeof(int)]; + }; + return bit_cast(1).data[0] == 0; +#endif +} + +class uint128_fallback { + private: + uint64_t lo_, hi_; + + public: + constexpr uint128_fallback(uint64_t hi, uint64_t lo) : lo_(lo), hi_(hi) {} + constexpr uint128_fallback(uint64_t value = 0) : lo_(value), hi_(0) {} + + constexpr auto high() const noexcept -> uint64_t { return hi_; } + constexpr auto low() const noexcept -> uint64_t { return lo_; } + + template ::value)> + constexpr explicit operator T() const { + return static_cast(lo_); + } + + friend constexpr auto operator==(const uint128_fallback& lhs, + const uint128_fallback& rhs) -> bool { + return lhs.hi_ == rhs.hi_ && lhs.lo_ == rhs.lo_; + } + friend constexpr auto operator!=(const uint128_fallback& lhs, + const uint128_fallback& rhs) -> bool { + return !(lhs == rhs); + } + friend constexpr auto operator>(const uint128_fallback& lhs, + const uint128_fallback& rhs) -> bool { + return lhs.hi_ != rhs.hi_ ? lhs.hi_ > rhs.hi_ : lhs.lo_ > rhs.lo_; + } + friend constexpr auto operator|(const uint128_fallback& lhs, + const uint128_fallback& rhs) + -> uint128_fallback { + return {lhs.hi_ | rhs.hi_, lhs.lo_ | rhs.lo_}; + } + friend constexpr auto operator&(const uint128_fallback& lhs, + const uint128_fallback& rhs) + -> uint128_fallback { + return {lhs.hi_ & rhs.hi_, lhs.lo_ & rhs.lo_}; + } + friend constexpr auto operator~(const uint128_fallback& n) + -> uint128_fallback { + return {~n.hi_, ~n.lo_}; + } + friend auto operator+(const uint128_fallback& lhs, + const uint128_fallback& rhs) -> uint128_fallback { + auto result = uint128_fallback(lhs); + result += rhs; + return result; + } + friend auto operator*(const uint128_fallback& lhs, uint32_t rhs) + -> uint128_fallback { + FMT_ASSERT(lhs.hi_ == 0, ""); + uint64_t hi = (lhs.lo_ >> 32) * rhs; + uint64_t lo = (lhs.lo_ & ~uint32_t()) * rhs; + uint64_t new_lo = (hi << 32) + lo; + return {(hi >> 32) + (new_lo < lo ? 1 : 0), new_lo}; + } + friend auto operator-(const uint128_fallback& lhs, uint64_t rhs) + -> uint128_fallback { + return {lhs.hi_ - (lhs.lo_ < rhs ? 1 : 0), lhs.lo_ - rhs}; + } + FMT_CONSTEXPR auto operator>>(int shift) const -> uint128_fallback { + if (shift == 64) return {0, hi_}; + if (shift > 64) return uint128_fallback(0, hi_) >> (shift - 64); + return {hi_ >> shift, (hi_ << (64 - shift)) | (lo_ >> shift)}; + } + FMT_CONSTEXPR auto operator<<(int shift) const -> uint128_fallback { + if (shift == 64) return {lo_, 0}; + if (shift > 64) return uint128_fallback(lo_, 0) << (shift - 64); + return {hi_ << shift | (lo_ >> (64 - shift)), (lo_ << shift)}; + } + FMT_CONSTEXPR auto operator>>=(int shift) -> uint128_fallback& { + return *this = *this >> shift; + } + FMT_CONSTEXPR void operator+=(uint128_fallback n) { + uint64_t new_lo = lo_ + n.lo_; + uint64_t new_hi = hi_ + n.hi_ + (new_lo < lo_ ? 1 : 0); + FMT_ASSERT(new_hi >= hi_, ""); + lo_ = new_lo; + hi_ = new_hi; + } + FMT_CONSTEXPR void operator&=(uint128_fallback n) { + lo_ &= n.lo_; + hi_ &= n.hi_; + } + + FMT_CONSTEXPR20 auto operator+=(uint64_t n) noexcept -> uint128_fallback& { + if (is_constant_evaluated()) { + lo_ += n; + hi_ += (lo_ < n ? 1 : 0); + return *this; + } +#if FMT_HAS_BUILTIN(__builtin_addcll) && !defined(__ibmxl__) + unsigned long long carry; + lo_ = __builtin_addcll(lo_, n, 0, &carry); + hi_ += carry; +#elif FMT_HAS_BUILTIN(__builtin_ia32_addcarryx_u64) && !defined(__ibmxl__) + unsigned long long result; + auto carry = __builtin_ia32_addcarryx_u64(0, lo_, n, &result); + lo_ = result; + hi_ += carry; +#elif defined(_MSC_VER) && defined(_M_X64) + auto carry = _addcarry_u64(0, lo_, n, &lo_); + _addcarry_u64(carry, hi_, 0, &hi_); +#else + lo_ += n; + hi_ += (lo_ < n ? 1 : 0); +#endif + return *this; + } +}; + +using uint128_t = conditional_t; + +#ifdef UINTPTR_MAX +using uintptr_t = ::uintptr_t; +#else +using uintptr_t = uint128_t; +#endif + +// Returns the largest possible value for type T. Same as +// std::numeric_limits::max() but shorter and not affected by the max macro. +template constexpr auto max_value() -> T { + return (std::numeric_limits::max)(); +} +template constexpr auto num_bits() -> int { + return std::numeric_limits::digits; +} +// std::numeric_limits::digits may return 0 for 128-bit ints. +template <> constexpr auto num_bits() -> int { return 128; } +template <> constexpr auto num_bits() -> int { return 128; } + +// A heterogeneous bit_cast used for converting 96-bit long double to uint128_t +// and 128-bit pointers to uint128_fallback. +template sizeof(From))> +inline auto bit_cast(const From& from) -> To { + constexpr auto size = static_cast(sizeof(From) / sizeof(unsigned)); + struct data_t { + unsigned value[static_cast(size)]; + } data = bit_cast(from); + auto result = To(); + if (const_check(is_big_endian())) { + for (int i = 0; i < size; ++i) + result = (result << num_bits()) | data.value[i]; + } else { + for (int i = size - 1; i >= 0; --i) + result = (result << num_bits()) | data.value[i]; + } + return result; +} + +template +FMT_CONSTEXPR20 inline auto countl_zero_fallback(UInt n) -> int { + int lz = 0; + constexpr UInt msb_mask = static_cast(1) << (num_bits() - 1); + for (; (n & msb_mask) == 0; n <<= 1) lz++; + return lz; +} + +FMT_CONSTEXPR20 inline auto countl_zero(uint32_t n) -> int { +#ifdef FMT_BUILTIN_CLZ + if (!is_constant_evaluated()) return FMT_BUILTIN_CLZ(n); +#endif + return countl_zero_fallback(n); +} + +FMT_CONSTEXPR20 inline auto countl_zero(uint64_t n) -> int { +#ifdef FMT_BUILTIN_CLZLL + if (!is_constant_evaluated()) return FMT_BUILTIN_CLZLL(n); +#endif + return countl_zero_fallback(n); +} + +FMT_INLINE void assume(bool condition) { + (void)condition; +#if FMT_HAS_BUILTIN(__builtin_assume) && !FMT_ICC_VERSION + __builtin_assume(condition); +#elif FMT_GCC_VERSION + if (!condition) __builtin_unreachable(); +#endif +} + +// An approximation of iterator_t for pre-C++20 systems. +template +using iterator_t = decltype(std::begin(std::declval())); +template using sentinel_t = decltype(std::end(std::declval())); + +// A workaround for std::string not having mutable data() until C++17. +template +inline auto get_data(std::basic_string& s) -> Char* { + return &s[0]; +} +template +inline auto get_data(Container& c) -> typename Container::value_type* { + return c.data(); +} + +// Attempts to reserve space for n extra characters in the output range. +// Returns a pointer to the reserved range or a reference to it. +template ::value)> +#if FMT_CLANG_VERSION >= 307 && !FMT_ICC_VERSION +__attribute__((no_sanitize("undefined"))) +#endif +inline auto +reserve(std::back_insert_iterator it, size_t n) -> + typename Container::value_type* { + Container& c = get_container(it); + size_t size = c.size(); + c.resize(size + n); + return get_data(c) + size; +} + +template +inline auto reserve(buffer_appender it, size_t n) -> buffer_appender { + buffer& buf = get_container(it); + buf.try_reserve(buf.size() + n); + return it; +} + +template +constexpr auto reserve(Iterator& it, size_t) -> Iterator& { + return it; +} + +template +using reserve_iterator = + remove_reference_t(), 0))>; + +template +constexpr auto to_pointer(OutputIt, size_t) -> T* { + return nullptr; +} +template auto to_pointer(buffer_appender it, size_t n) -> T* { + buffer& 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 ::value)> +inline auto base_iterator(std::back_insert_iterator it, + typename Container::value_type*) + -> std::back_insert_iterator { + return it; +} + +template +constexpr auto base_iterator(Iterator, Iterator it) -> Iterator { + return it; +} + +// is spectacularly slow to compile in C++20 so use a simple fill_n +// instead (#1998). +template +FMT_CONSTEXPR auto fill_n(OutputIt out, Size count, const T& value) + -> OutputIt { + for (Size i = 0; i < count; ++i) *out++ = value; + return out; +} +template +FMT_CONSTEXPR20 auto fill_n(T* out, Size count, char value) -> T* { + if (is_constant_evaluated()) { + return fill_n(out, count, value); + } + std::memset(out, value, to_unsigned(count)); + return out + count; +} + +#ifdef __cpp_char8_t +using char8_type = char8_t; +#else +enum char8_type : unsigned char {}; +#endif + +template +FMT_CONSTEXPR FMT_NOINLINE auto copy_str_noinline(InputIt begin, InputIt end, + OutputIt out) -> OutputIt { + return copy_str(begin, end, out); +} + +// A public domain branchless UTF-8 decoder by Christopher Wellons: +// https://github.com/skeeto/branchless-utf8 +/* Decode the next character, c, from s, 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. + */ +FMT_CONSTEXPR inline auto utf8_decode(const char* s, uint32_t* c, int* e) + -> const char* { + constexpr const int masks[] = {0x00, 0x7f, 0x1f, 0x0f, 0x07}; + constexpr const uint32_t mins[] = {4194304, 0, 128, 2048, 65536}; + constexpr const int shiftc[] = {0, 18, 12, 6, 0}; + constexpr const int shifte[] = {0, 6, 4, 2, 0}; + + int len = "\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" + [static_cast(*s) >> 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. + const char* next = s + len + !len; + + using uchar = unsigned char; + + // Assume a four-byte character and load four bytes. Unused bits are + // shifted out. + *c = uint32_t(uchar(s[0]) & masks[len]) << 18; + *c |= uint32_t(uchar(s[1]) & 0x3f) << 12; + *c |= uint32_t(uchar(s[2]) & 0x3f) << 6; + *c |= uint32_t(uchar(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 |= (uchar(s[1]) & 0xc0) >> 2; + *e |= (uchar(s[2]) & 0xc0) >> 4; + *e |= uchar(s[3]) >> 6; + *e ^= 0x2a; // top two bits of each tail byte correct? + *e >>= shifte[len]; + + return next; +} + +constexpr FMT_INLINE_VARIABLE uint32_t invalid_code_point = ~uint32_t(); + +// Invokes f(cp, sv) for every code point cp in s with sv being the string view +// corresponding to the code point. cp is invalid_code_point on error. +template +FMT_CONSTEXPR void for_each_codepoint(string_view s, F f) { + auto decode = [f](const char* buf_ptr, const char* ptr) { + auto cp = uint32_t(); + auto error = 0; + auto end = utf8_decode(buf_ptr, &cp, &error); + bool result = f(error ? invalid_code_point : cp, + string_view(ptr, error ? 1 : to_unsigned(end - buf_ptr))); + return result ? (error ? buf_ptr + 1 : end) : nullptr; + }; + 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 = decode(p, p); + if (!p) return; + } + } + if (auto num_chars_left = s.data() + s.size() - p) { + char buf[2 * block_size - 1] = {}; + copy_str(p, p + num_chars_left, buf); + const char* buf_ptr = buf; + do { + auto end = decode(buf_ptr, p); + if (!end) return; + p += end - buf_ptr; + buf_ptr = end; + } while (buf_ptr - buf < num_chars_left); + } +} + +template +inline auto compute_width(basic_string_view s) -> size_t { + return s.size(); +} + +// Computes approximate display width of a UTF-8 string. +FMT_CONSTEXPR inline auto compute_width(string_view s) -> size_t { + size_t num_code_points = 0; + // It is not a lambda for compatibility with C++14. + struct count_code_points { + size_t* count; + FMT_CONSTEXPR auto operator()(uint32_t cp, string_view) const -> bool { + *count += detail::to_unsigned( + 1 + + (cp >= 0x1100 && + (cp <= 0x115f || // Hangul Jamo init. consonants + cp == 0x2329 || // LEFT-POINTING ANGLE BRACKET + cp == 0x232a || // RIGHT-POINTING ANGLE BRACKET + // CJK ... Yi except IDEOGRAPHIC HALF FILL SPACE: + (cp >= 0x2e80 && cp <= 0xa4cf && cp != 0x303f) || + (cp >= 0xac00 && cp <= 0xd7a3) || // Hangul Syllables + (cp >= 0xf900 && cp <= 0xfaff) || // CJK Compatibility Ideographs + (cp >= 0xfe10 && cp <= 0xfe19) || // Vertical Forms + (cp >= 0xfe30 && cp <= 0xfe6f) || // CJK Compatibility Forms + (cp >= 0xff00 && cp <= 0xff60) || // Fullwidth Forms + (cp >= 0xffe0 && cp <= 0xffe6) || // Fullwidth Forms + (cp >= 0x20000 && cp <= 0x2fffd) || // CJK + (cp >= 0x30000 && cp <= 0x3fffd) || + // Miscellaneous Symbols and Pictographs + Emoticons: + (cp >= 0x1f300 && cp <= 0x1f64f) || + // Supplemental Symbols and Pictographs: + (cp >= 0x1f900 && cp <= 0x1f9ff)))); + return true; + } + }; + // We could avoid branches by using utf8_decode directly. + for_each_codepoint(s, count_code_points{&num_code_points}); + return num_code_points; +} + +inline auto compute_width(basic_string_view s) -> size_t { + return compute_width( + string_view(reinterpret_cast(s.data()), s.size())); +} + +template +inline auto code_point_index(basic_string_view s, size_t n) -> size_t { + size_t size = s.size(); + return n < size ? n : size; +} + +// Calculates the index of the nth code point in a UTF-8 string. +inline auto code_point_index(string_view s, size_t n) -> size_t { + size_t result = s.size(); + const char* begin = s.begin(); + for_each_codepoint(s, [begin, &n, &result](uint32_t, string_view sv) { + if (n != 0) { + --n; + return true; + } + result = to_unsigned(sv.begin() - begin); + return false; + }); + return result; +} + +inline auto code_point_index(basic_string_view s, size_t n) + -> size_t { + return code_point_index( + string_view(reinterpret_cast(s.data()), s.size()), n); +} + +template struct is_integral : std::is_integral {}; +template <> struct is_integral : std::true_type {}; +template <> struct is_integral : std::true_type {}; + +template +using is_signed = + std::integral_constant::is_signed || + std::is_same::value>; + +template +using is_integer = + bool_constant::value && !std::is_same::value && + !std::is_same::value && + !std::is_same::value>; + +#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 + +#ifndef FMT_USE_FLOAT128 +# ifdef __clang__ +// Clang emulates GCC, so it has to appear early. +# if FMT_HAS_INCLUDE() +# define FMT_USE_FLOAT128 1 +# endif +# elif defined(__GNUC__) +// GNU C++: +# if defined(_GLIBCXX_USE_FLOAT128) && !defined(__STRICT_ANSI__) +# define FMT_USE_FLOAT128 1 +# endif +# endif +# ifndef FMT_USE_FLOAT128 +# define FMT_USE_FLOAT128 0 +# endif +#endif + +#if FMT_USE_FLOAT128 +using float128 = __float128; +#else +using float128 = void; +#endif +template using is_float128 = std::is_same; + +template +using is_floating_point = + bool_constant::value || is_float128::value>; + +template ::value> +struct is_fast_float : bool_constant::is_iec559 && + sizeof(T) <= sizeof(double)> {}; +template struct is_fast_float : std::false_type {}; + +template +using is_double_double = bool_constant::digits == 106>; + +#ifndef FMT_USE_FULL_CACHE_DRAGONBOX +# define FMT_USE_FULL_CACHE_DRAGONBOX 0 +#endif + +template +template +void buffer::append(const U* begin, const U* end) { + while (begin != end) { + 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, ptr_ + size_); + size_ += count; + begin += count; + } +} + +template +struct is_locale : std::false_type {}; +template +struct is_locale> : std::true_type {}; +} // namespace detail + +FMT_BEGIN_EXPORT + +// 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 the ``memory_buffer`` type alias for ``char`` instead. + + **Example**:: + + auto out = fmt::memory_buffer(); + fmt::format_to(std::back_inserter(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 > +class basic_memory_buffer final : public detail::buffer { + private: + T store_[SIZE]; + + // Don't inherit from Allocator to avoid generating type_info for it. + FMT_NO_UNIQUE_ADDRESS Allocator alloc_; + + // Deallocate memory allocated by the buffer. + FMT_CONSTEXPR20 void deallocate() { + T* data = this->data(); + if (data != store_) alloc_.deallocate(data, this->capacity()); + } + + protected: + FMT_CONSTEXPR20 void grow(size_t size) override { + detail::abort_fuzzing_if(size > 5000); + const size_t max_size = std::allocator_traits::max_size(alloc_); + size_t old_capacity = this->capacity(); + size_t new_capacity = old_capacity + old_capacity / 2; + if (size > new_capacity) + new_capacity = size; + else if (new_capacity > max_size) + new_capacity = size > max_size ? size : max_size; + T* old_data = this->data(); + T* new_data = + std::allocator_traits::allocate(alloc_, new_capacity); + // Suppress a bogus -Wstringop-overflow in gcc 13.1 (#3481). + detail::assume(this->size() <= new_capacity); + // The following code doesn't throw, so the raw pointer above doesn't leak. + std::uninitialized_copy_n(old_data, this->size(), new_data); + 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); + } + + public: + using value_type = T; + using const_reference = const T&; + + FMT_CONSTEXPR20 explicit basic_memory_buffer( + const Allocator& alloc = Allocator()) + : alloc_(alloc) { + this->set(store_, SIZE); + if (detail::is_constant_evaluated()) detail::fill_n(store_, SIZE, T()); + } + FMT_CONSTEXPR20 ~basic_memory_buffer() { deallocate(); } + + private: + // Move data from other to this buffer. + FMT_CONSTEXPR20 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); + detail::copy_str(other.store_, other.store_ + size, store_); + } else { + this->set(data, capacity); + // Set pointer to the inline array so that delete is not called + // when deallocating. + other.set(other.store_, 0); + other.clear(); + } + this->resize(size); + } + + public: + /** + \rst + Constructs a :class:`fmt::basic_memory_buffer` object moving the content + of the other object to it. + \endrst + */ + FMT_CONSTEXPR20 basic_memory_buffer(basic_memory_buffer&& other) noexcept { + move(other); + } + + /** + \rst + Moves the content of the other ``basic_memory_buffer`` object to this one. + \endrst + */ + auto operator=(basic_memory_buffer&& other) noexcept -> basic_memory_buffer& { + FMT_ASSERT(this != &other, ""); + deallocate(); + move(other); + return *this; + } + + // Returns a copy of the allocator associated with this buffer. + auto get_allocator() const -> Allocator { return alloc_; } + + /** + Resizes the buffer to contain *count* elements. If T is a POD type new + elements may not be initialized. + */ + FMT_CONSTEXPR20 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); } + + using detail::buffer::append; + template + void append(const ContiguousRange& range) { + append(range.data(), range.data() + range.size()); + } +}; + +using memory_buffer = basic_memory_buffer; + +template +struct is_contiguous> : std::true_type { +}; + +FMT_END_EXPORT +namespace detail { +FMT_API auto write_console(int fd, string_view text) -> bool; +FMT_API auto write_console(std::FILE* f, string_view text) -> bool; +FMT_API void print(std::FILE*, string_view); +} // namespace detail + +FMT_BEGIN_EXPORT + +// Suppress a misleading warning in older versions of clang. +#if FMT_CLANG_VERSION +# pragma clang diagnostic ignored "-Wweak-vtables" +#endif + +/** An error reported from a formatting function. */ +class FMT_SO_VISIBILITY("default") format_error : public std::runtime_error { + public: + using std::runtime_error::runtime_error; +}; + +namespace detail_exported { +#if FMT_USE_NONTYPE_TEMPLATE_ARGS +template struct fixed_string { + constexpr fixed_string(const Char (&str)[N]) { + detail::copy_str(static_cast(str), + str + N, data); + } + Char data[N] = {}; +}; +#endif + +// Converts a compile-time string to basic_string_view. +template +constexpr auto compile_string_to_view(const Char (&s)[N]) + -> basic_string_view { + // Remove trailing NUL character if needed. Won't be present if this is used + // with a raw character array (i.e. not defined as a string). + return {s, N - (std::char_traits::to_int_type(s[N - 1]) == 0 ? 1 : 0)}; +} +template +constexpr auto compile_string_to_view(detail::std_string_view s) + -> basic_string_view { + return {s.data(), s.size()}; +} +} // namespace detail_exported + +class loc_value { + private: + basic_format_arg value_; + + public: + template ::value)> + loc_value(T value) : value_(detail::make_arg(value)) {} + + template ::value)> + loc_value(T) {} + + template auto visit(Visitor&& vis) -> decltype(vis(0)) { + return visit_format_arg(vis, value_); + } +}; + +// A locale facet that formats values in UTF-8. +// It is parameterized on the locale to avoid the heavy include. +template class format_facet : public Locale::facet { + private: + std::string separator_; + std::string grouping_; + std::string decimal_point_; + + protected: + virtual auto do_put(appender out, loc_value val, + const format_specs<>& specs) const -> bool; + + public: + static FMT_API typename Locale::id id; + + explicit format_facet(Locale& loc); + explicit format_facet(string_view sep = "", + std::initializer_list g = {3}, + std::string decimal_point = ".") + : separator_(sep.data(), sep.size()), + grouping_(g.begin(), g.end()), + decimal_point_(decimal_point) {} + + auto put(appender out, loc_value val, const format_specs<>& specs) const + -> bool { + return do_put(out, val, specs); + } +}; + +namespace detail { + +// Returns true if value is negative, false otherwise. +// Same as `value < 0` but doesn't produce warnings if T is an unsigned type. +template ::value)> +constexpr auto is_negative(T value) -> bool { + return value < 0; +} +template ::value)> +constexpr auto is_negative(T) -> bool { + return false; +} + +template +FMT_CONSTEXPR auto is_supported_floating_point(T) -> bool { + if (std::is_same()) return FMT_USE_FLOAT; + if (std::is_same()) return FMT_USE_DOUBLE; + if (std::is_same()) return FMT_USE_LONG_DOUBLE; + return true; +} + +// Smallest of uint32_t, uint64_t, uint128_t that is large enough to +// represent all values of an integral type T. +template +using uint32_or_64_or_128_t = + conditional_t() <= 32 && !FMT_REDUCE_INT_INSTANTIATIONS, + uint32_t, + conditional_t() <= 64, uint64_t, uint128_t>>; +template +using uint64_or_128_t = conditional_t() <= 64, uint64_t, uint128_t>; + +#define FMT_POWERS_OF_10(factor) \ + factor * 10, (factor) * 100, (factor) * 1000, (factor) * 10000, \ + (factor) * 100000, (factor) * 1000000, (factor) * 10000000, \ + (factor) * 100000000, (factor) * 1000000000 + +// Converts value in the range [0, 100) to a string. +constexpr auto digits2(size_t value) -> const char* { + // GCC generates slightly better code when value is pointer-size. + return &"0001020304050607080910111213141516171819" + "2021222324252627282930313233343536373839" + "4041424344454647484950515253545556575859" + "6061626364656667686970717273747576777879" + "8081828384858687888990919293949596979899"[value * 2]; +} + +// Sign is a template parameter to workaround a bug in gcc 4.8. +template constexpr auto sign(Sign s) -> Char { +#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 604 + static_assert(std::is_same::value, ""); +#endif + return static_cast("\0-+ "[s]); +} + +template FMT_CONSTEXPR auto count_digits_fallback(T n) -> int { + 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; + } +} +#if FMT_USE_INT128 +FMT_CONSTEXPR inline auto count_digits(uint128_opt n) -> int { + return count_digits_fallback(n); +} +#endif + +#ifdef FMT_BUILTIN_CLZLL +// It is a separate function rather than a part of count_digits to workaround +// the lack of static constexpr in constexpr functions. +inline auto do_count_digits(uint64_t n) -> int { + // This has comparable performance to the version by Kendall Willets + // (https://github.com/fmtlib/format-benchmark/blob/master/digits10) + // but uses smaller tables. + // Maps bsr(n) to ceil(log10(pow(2, bsr(n) + 1) - 1)). + static constexpr uint8_t bsr2log10[] = { + 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}; + auto t = bsr2log10[FMT_BUILTIN_CLZLL(n | 1) ^ 63]; + static constexpr const uint64_t zero_or_powers_of_10[] = { + 0, 0, FMT_POWERS_OF_10(1U), FMT_POWERS_OF_10(1000000000ULL), + 10000000000000000000ULL}; + return t - (n < zero_or_powers_of_10[t]); +} +#endif + +// Returns the number of decimal digits in n. Leading zeros are not counted +// except for n == 0 in which case count_digits returns 1. +FMT_CONSTEXPR20 inline auto count_digits(uint64_t n) -> int { +#ifdef FMT_BUILTIN_CLZLL + if (!is_constant_evaluated()) { + return do_count_digits(n); + } +#endif + return count_digits_fallback(n); +} + +// Counts the number of digits in n. BITS = log2(radix). +template +FMT_CONSTEXPR auto count_digits(UInt n) -> int { +#ifdef FMT_BUILTIN_CLZ + if (!is_constant_evaluated() && num_bits() == 32) + return (FMT_BUILTIN_CLZ(static_cast(n) | 1) ^ 31) / BITS + 1; +#endif + // Lambda avoids unreachable code warnings from NVHPC. + return [](UInt m) { + int num_digits = 0; + do { + ++num_digits; + } while ((m >>= BITS) != 0); + return num_digits; + }(n); +} + +#ifdef FMT_BUILTIN_CLZ +// It is a separate function rather than a part of count_digits to workaround +// the lack of static constexpr in constexpr functions. +FMT_INLINE auto do_count_digits(uint32_t n) -> int { +// An optimization by Kendall Willets from https://bit.ly/3uOIQrB. +// This increments the upper 32 bits (log10(T) - 1) when >= T is added. +# define FMT_INC(T) (((sizeof(#T) - 1ull) << 32) - T) + static constexpr uint64_t table[] = { + FMT_INC(0), FMT_INC(0), FMT_INC(0), // 8 + FMT_INC(10), FMT_INC(10), FMT_INC(10), // 64 + FMT_INC(100), FMT_INC(100), FMT_INC(100), // 512 + FMT_INC(1000), FMT_INC(1000), FMT_INC(1000), // 4096 + FMT_INC(10000), FMT_INC(10000), FMT_INC(10000), // 32k + FMT_INC(100000), FMT_INC(100000), FMT_INC(100000), // 256k + FMT_INC(1000000), FMT_INC(1000000), FMT_INC(1000000), // 2048k + FMT_INC(10000000), FMT_INC(10000000), FMT_INC(10000000), // 16M + FMT_INC(100000000), FMT_INC(100000000), FMT_INC(100000000), // 128M + FMT_INC(1000000000), FMT_INC(1000000000), FMT_INC(1000000000), // 1024M + FMT_INC(1000000000), FMT_INC(1000000000) // 4B + }; + auto inc = table[FMT_BUILTIN_CLZ(n | 1) ^ 31]; + return static_cast((n + inc) >> 32); +} +#endif + +// Optional version of count_digits for better performance on 32-bit platforms. +FMT_CONSTEXPR20 inline auto count_digits(uint32_t n) -> int { +#ifdef FMT_BUILTIN_CLZ + if (!is_constant_evaluated()) { + return do_count_digits(n); + } +#endif + return count_digits_fallback(n); +} + +template constexpr auto digits10() noexcept -> int { + return std::numeric_limits::digits10; +} +template <> constexpr auto digits10() noexcept -> int { return 38; } +template <> constexpr auto digits10() noexcept -> int { return 38; } + +template struct thousands_sep_result { + std::string grouping; + Char thousands_sep; +}; + +template +FMT_API auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result; +template +inline auto thousands_sep(locale_ref loc) -> thousands_sep_result { + auto result = thousands_sep_impl(loc); + return {result.grouping, Char(result.thousands_sep)}; +} +template <> +inline auto thousands_sep(locale_ref loc) -> thousands_sep_result { + return thousands_sep_impl(loc); +} + +template +FMT_API auto decimal_point_impl(locale_ref loc) -> Char; +template inline auto decimal_point(locale_ref loc) -> Char { + return Char(decimal_point_impl(loc)); +} +template <> inline auto decimal_point(locale_ref loc) -> wchar_t { + return decimal_point_impl(loc); +} + +// Compares two characters for equality. +template auto equal2(const Char* lhs, const char* rhs) -> bool { + return lhs[0] == Char(rhs[0]) && lhs[1] == Char(rhs[1]); +} +inline auto equal2(const char* lhs, const char* rhs) -> bool { + return memcmp(lhs, rhs, 2) == 0; +} + +// Copies two characters from src to dst. +template +FMT_CONSTEXPR20 FMT_INLINE void copy2(Char* dst, const char* src) { + if (!is_constant_evaluated() && sizeof(Char) == sizeof(char)) { + memcpy(dst, src, 2); + return; + } + *dst++ = static_cast(*src++); + *dst = static_cast(*src); +} + +template 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 +FMT_CONSTEXPR20 auto format_decimal(Char* out, UInt value, int size) + -> format_decimal_result { + 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, digits2(static_cast(value % 100))); + value /= 100; + } + if (value < 10) { + *--out = static_cast('0' + value); + return {out, end}; + } + out -= 2; + copy2(out, digits2(static_cast(value))); + return {out, end}; +} + +template >::value)> +FMT_CONSTEXPR inline auto format_decimal(Iterator out, UInt value, int size) + -> format_decimal_result { + // Buffer is large enough to hold all digits (digits10 + 1). + Char buffer[digits10() + 1] = {}; + auto end = format_decimal(buffer, value, size).end; + return {out, detail::copy_str_noinline(buffer, end, out)}; +} + +template +FMT_CONSTEXPR auto format_uint(Char* buffer, UInt value, int num_digits, + bool upper = false) -> Char* { + buffer += num_digits; + Char* end = buffer; + do { + const char* digits = upper ? "0123456789ABCDEF" : "0123456789abcdef"; + unsigned digit = static_cast(value & ((1 << BASE_BITS) - 1)); + *--buffer = static_cast(BASE_BITS < 4 ? static_cast('0' + digit) + : digits[digit]); + } while ((value >>= BASE_BITS) != 0); + return end; +} + +template +FMT_CONSTEXPR inline auto format_uint(It out, UInt value, int num_digits, + bool upper = false) -> It { + if (auto ptr = to_pointer(out, to_unsigned(num_digits))) { + format_uint(ptr, value, num_digits, upper); + return out; + } + // Buffer should be large enough to hold all digits (digits / BASE_BITS + 1). + char buffer[num_bits() / BASE_BITS + 1] = {}; + format_uint(buffer, value, num_digits, upper); + return detail::copy_str_noinline(buffer, buffer + num_digits, out); +} + +// A converter from UTF-8 to UTF-16. +class utf8_to_utf16 { + private: + basic_memory_buffer buffer_; + + public: + FMT_API explicit utf8_to_utf16(string_view s); + operator basic_string_view() const { return {&buffer_[0], size()}; } + auto size() const -> size_t { return buffer_.size() - 1; } + auto c_str() const -> const wchar_t* { return &buffer_[0]; } + auto str() const -> std::wstring { return {&buffer_[0], size()}; } +}; + +enum class to_utf8_error_policy { abort, replace }; + +// A converter from UTF-16/UTF-32 (host endian) to UTF-8. +template class to_utf8 { + private: + Buffer buffer_; + + public: + to_utf8() {} + explicit to_utf8(basic_string_view s, + to_utf8_error_policy policy = to_utf8_error_policy::abort) { + static_assert(sizeof(WChar) == 2 || sizeof(WChar) == 4, + "Expect utf16 or utf32"); + if (!convert(s, policy)) + FMT_THROW(std::runtime_error(sizeof(WChar) == 2 ? "invalid utf16" + : "invalid utf32")); + } + operator string_view() const { return string_view(&buffer_[0], size()); } + auto size() const -> size_t { return buffer_.size() - 1; } + auto c_str() const -> const char* { return &buffer_[0]; } + auto str() const -> std::string { return std::string(&buffer_[0], size()); } + + // Performs conversion returning a bool instead of throwing exception on + // conversion error. This method may still throw in case of memory allocation + // error. + auto convert(basic_string_view s, + to_utf8_error_policy policy = to_utf8_error_policy::abort) + -> bool { + if (!convert(buffer_, s, policy)) return false; + buffer_.push_back(0); + return true; + } + static auto convert(Buffer& buf, basic_string_view s, + to_utf8_error_policy policy = to_utf8_error_policy::abort) + -> bool { + for (auto p = s.begin(); p != s.end(); ++p) { + uint32_t c = static_cast(*p); + if (sizeof(WChar) == 2 && c >= 0xd800 && c <= 0xdfff) { + // Handle a surrogate pair. + ++p; + if (p == s.end() || (c & 0xfc00) != 0xd800 || (*p & 0xfc00) != 0xdc00) { + if (policy == to_utf8_error_policy::abort) return false; + buf.append(string_view("\xEF\xBF\xBD")); + --p; + } else { + c = (c << 10) + static_cast(*p) - 0x35fdc00; + } + } else if (c < 0x80) { + buf.push_back(static_cast(c)); + } else if (c < 0x800) { + buf.push_back(static_cast(0xc0 | (c >> 6))); + buf.push_back(static_cast(0x80 | (c & 0x3f))); + } else if ((c >= 0x800 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xffff)) { + buf.push_back(static_cast(0xe0 | (c >> 12))); + buf.push_back(static_cast(0x80 | ((c & 0xfff) >> 6))); + buf.push_back(static_cast(0x80 | (c & 0x3f))); + } else if (c >= 0x10000 && c <= 0x10ffff) { + buf.push_back(static_cast(0xf0 | (c >> 18))); + buf.push_back(static_cast(0x80 | ((c & 0x3ffff) >> 12))); + buf.push_back(static_cast(0x80 | ((c & 0xfff) >> 6))); + buf.push_back(static_cast(0x80 | (c & 0x3f))); + } else { + return false; + } + } + return true; + } +}; + +// Computes 128-bit result of multiplication of two 64-bit unsigned integers. +inline auto umul128(uint64_t x, uint64_t y) noexcept -> uint128_fallback { +#if FMT_USE_INT128 + auto p = static_cast(x) * static_cast(y); + return {static_cast(p >> 64), static_cast(p)}; +#elif defined(_MSC_VER) && defined(_M_X64) + auto hi = uint64_t(); + auto lo = _umul128(x, y, &hi); + return {hi, lo}; +#else + const uint64_t mask = static_cast(max_value()); + + 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 +} + +namespace dragonbox { +// Computes floor(log10(pow(2, e))) for e in [-2620, 2620] using the method from +// https://fmt.dev/papers/Dragonbox.pdf#page=28, section 6.1. +inline auto floor_log10_pow2(int e) noexcept -> int { + FMT_ASSERT(e <= 2620 && e >= -2620, "too large exponent"); + static_assert((-1 >> 1) == -1, "right shift is not arithmetic"); + return (e * 315653) >> 20; +} + +inline auto floor_log2_pow10(int e) noexcept -> int { + FMT_ASSERT(e <= 1233 && e >= -1233, "too large exponent"); + return (e * 1741647) >> 19; +} + +// Computes upper 64 bits of multiplication of two 64-bit unsigned integers. +inline auto umul128_upper64(uint64_t x, uint64_t y) noexcept -> uint64_t { +#if FMT_USE_INT128 + auto p = static_cast(x) * static_cast(y); + return static_cast(p >> 64); +#elif defined(_MSC_VER) && defined(_M_X64) + return __umulh(x, y); +#else + return umul128(x, y).high(); +#endif +} + +// Computes upper 128 bits of multiplication of a 64-bit unsigned integer and a +// 128-bit unsigned integer. +inline auto umul192_upper128(uint64_t x, uint128_fallback y) noexcept + -> uint128_fallback { + uint128_fallback r = umul128(x, y.high()); + r += umul128_upper64(x, y.low()); + return r; +} + +FMT_API auto get_cached_power(int k) noexcept -> uint128_fallback; + +// Type-specific information that Dragonbox uses. +template struct float_info; + +template <> struct float_info { + using carrier_uint = uint32_t; + static const int exponent_bits = 8; + 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 shorter_interval_tie_lower_threshold = -35; + static const int shorter_interval_tie_upper_threshold = -35; +}; + +template <> struct float_info { + using carrier_uint = uint64_t; + static const int exponent_bits = 11; + 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 = 341; + static const int shorter_interval_tie_lower_threshold = -77; + static const int shorter_interval_tie_upper_threshold = -77; +}; + +// An 80- or 128-bit floating point number. +template +struct float_info::digits == 64 || + std::numeric_limits::digits == 113 || + is_float128::value>> { + using carrier_uint = detail::uint128_t; + static const int exponent_bits = 15; +}; + +// A double-double floating point number. +template +struct float_info::value>> { + using carrier_uint = detail::uint128_t; +}; + +template struct decimal_fp { + using significand_type = typename float_info::carrier_uint; + significand_type significand; + int exponent; +}; + +template FMT_API auto to_decimal(T x) noexcept -> decimal_fp; +} // namespace dragonbox + +// Returns true iff Float has the implicit bit which is not stored. +template constexpr auto has_implicit_bit() -> bool { + // An 80-bit FP number has a 64-bit significand an no implicit bit. + return std::numeric_limits::digits != 64; +} + +// Returns the number of significand bits stored in Float. The implicit bit is +// not counted since it is not stored. +template constexpr auto num_significand_bits() -> int { + // std::numeric_limits may not support __float128. + return is_float128() ? 112 + : (std::numeric_limits::digits - + (has_implicit_bit() ? 1 : 0)); +} + +template +constexpr auto exponent_mask() -> + typename dragonbox::float_info::carrier_uint { + using float_uint = typename dragonbox::float_info::carrier_uint; + return ((float_uint(1) << dragonbox::float_info::exponent_bits) - 1) + << num_significand_bits(); +} +template constexpr auto exponent_bias() -> int { + // std::numeric_limits may not support __float128. + return is_float128() ? 16383 + : std::numeric_limits::max_exponent - 1; +} + +// Writes the exponent exp in the form "[+-]d{2,3}" to buffer. +template +FMT_CONSTEXPR auto write_exponent(int exp, It it) -> It { + FMT_ASSERT(-10000 < exp && exp < 10000, "exponent out of range"); + if (exp < 0) { + *it++ = static_cast('-'); + exp = -exp; + } else { + *it++ = static_cast('+'); + } + if (exp >= 100) { + const char* top = digits2(to_unsigned(exp / 100)); + if (exp >= 1000) *it++ = static_cast(top[0]); + *it++ = static_cast(top[1]); + exp %= 100; + } + const char* d = digits2(to_unsigned(exp)); + *it++ = static_cast(d[0]); + *it++ = static_cast(d[1]); + return it; +} + +// A floating-point number f * pow(2, e) where F is an unsigned type. +template struct basic_fp { + F f; + int e; + + static constexpr const int num_significand_bits = + static_cast(sizeof(F) * num_bits()); + + constexpr basic_fp() : f(0), e(0) {} + constexpr basic_fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {} + + // Constructs fp from an IEEE754 floating-point number. + template FMT_CONSTEXPR basic_fp(Float n) { assign(n); } + + // Assigns n to this and return true iff predecessor is closer than successor. + template ::value)> + FMT_CONSTEXPR auto assign(Float n) -> bool { + static_assert(std::numeric_limits::digits <= 113, "unsupported FP"); + // Assume Float is in the format [sign][exponent][significand]. + using carrier_uint = typename dragonbox::float_info::carrier_uint; + const auto num_float_significand_bits = + detail::num_significand_bits(); + const auto implicit_bit = carrier_uint(1) << num_float_significand_bits; + const auto significand_mask = implicit_bit - 1; + auto u = bit_cast(n); + f = static_cast(u & significand_mask); + auto biased_e = static_cast((u & exponent_mask()) >> + num_float_significand_bits); + // The predecessor is closer if n is a normalized power of 2 (f == 0) + // other than the smallest normalized number (biased_e > 1). + auto is_predecessor_closer = f == 0 && biased_e > 1; + if (biased_e == 0) + biased_e = 1; // Subnormals use biased exponent 1 (min exponent). + else if (has_implicit_bit()) + f += static_cast(implicit_bit); + e = biased_e - exponent_bias() - num_float_significand_bits; + if (!has_implicit_bit()) ++e; + return is_predecessor_closer; + } + + template ::value)> + FMT_CONSTEXPR auto assign(Float n) -> bool { + static_assert(std::numeric_limits::is_iec559, "unsupported FP"); + return assign(static_cast(n)); + } +}; + +using fp = basic_fp; + +// Normalizes the value converted from double and multiplied by (1 << SHIFT). +template +FMT_CONSTEXPR auto normalize(basic_fp value) -> basic_fp { + // Handle subnormals. + const auto implicit_bit = F(1) << num_significand_bits(); + const auto shifted_implicit_bit = 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 = basic_fp::num_significand_bits - + num_significand_bits() - SHIFT - 1; + value.f <<= offset; + value.e -= offset; + return value; +} + +// Computes lhs * rhs / pow(2, 64) rounded to nearest with half-up tie breaking. +FMT_CONSTEXPR inline auto multiply(uint64_t lhs, uint64_t rhs) -> uint64_t { +#if FMT_USE_INT128 + auto product = static_cast<__uint128_t>(lhs) * rhs; + auto f = static_cast(product >> 64); + return (static_cast(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 +} + +FMT_CONSTEXPR inline auto operator*(fp x, fp y) -> fp { + return {multiply(x.f, y.f), x.e + y.e + 64}; +} + +template () == num_bits()> +using convert_float_result = + conditional_t::value || doublish, double, T>; + +template +constexpr auto convert_float(T value) -> convert_float_result { + return static_cast>(value); +} + +template +FMT_NOINLINE FMT_CONSTEXPR auto fill(OutputIt it, size_t n, + const fill_t& fill) -> OutputIt { + auto fill_size = fill.size(); + if (fill_size == 1) return detail::fill_n(it, n, fill[0]); + auto data = fill.data(); + for (size_t i = 0; i < n; ++i) + it = copy_str(data, 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 +FMT_CONSTEXPR auto write_padded(OutputIt out, const format_specs& specs, + size_t size, size_t width, F&& f) -> OutputIt { + 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; + // Shifts are encoded as string literals because static constexpr is not + // supported in constexpr functions. + auto* shifts = align == align::left ? "\x1f\x1f\x00\x01" : "\x00\x1f\x00\x01"; + size_t left_padding = padding >> shifts[specs.align]; + size_t right_padding = padding - left_padding; + auto it = reserve(out, size + padding * specs.fill.size()); + if (left_padding != 0) it = fill(it, left_padding, specs.fill); + it = f(it); + if (right_padding != 0) it = fill(it, right_padding, specs.fill); + return base_iterator(out, it); +} + +template +constexpr auto write_padded(OutputIt out, const format_specs& specs, + size_t size, F&& f) -> OutputIt { + return write_padded(out, specs, size, size, f); +} + +template +FMT_CONSTEXPR auto write_bytes(OutputIt out, string_view bytes, + const format_specs& specs) -> OutputIt { + return write_padded( + out, specs, bytes.size(), [bytes](reserve_iterator it) { + const char* data = bytes.data(); + return copy_str(data, data + bytes.size(), it); + }); +} + +template +auto write_ptr(OutputIt out, UIntPtr value, const format_specs* specs) + -> OutputIt { + int num_digits = count_digits<4>(value); + auto size = to_unsigned(num_digits) + size_t(2); + auto write = [=](reserve_iterator it) { + *it++ = static_cast('0'); + *it++ = static_cast('x'); + return format_uint<4, Char>(it, value, num_digits); + }; + return specs ? write_padded(out, *specs, size, write) + : base_iterator(out, write(reserve(out, size))); +} + +// Returns true iff the code point cp is printable. +FMT_API auto is_printable(uint32_t cp) -> bool; + +inline auto needs_escape(uint32_t cp) -> bool { + return cp < 0x20 || cp == 0x7f || cp == '"' || cp == '\\' || + !is_printable(cp); +} + +template struct find_escape_result { + const Char* begin; + const Char* end; + uint32_t cp; +}; + +template +using make_unsigned_char = + typename conditional_t::value, + std::make_unsigned, + type_identity>::type; + +template +auto find_escape(const Char* begin, const Char* end) + -> find_escape_result { + for (; begin != end; ++begin) { + uint32_t cp = static_cast>(*begin); + if (const_check(sizeof(Char) == 1) && cp >= 0x80) continue; + if (needs_escape(cp)) return {begin, begin + 1, cp}; + } + return {begin, nullptr, 0}; +} + +inline auto find_escape(const char* begin, const char* end) + -> find_escape_result { + if (!is_utf8()) return find_escape(begin, end); + auto result = find_escape_result{end, nullptr, 0}; + for_each_codepoint(string_view(begin, to_unsigned(end - begin)), + [&](uint32_t cp, string_view sv) { + if (needs_escape(cp)) { + result = {sv.begin(), sv.end(), cp}; + return false; + } + return true; + }); + return result; +} + +#define FMT_STRING_IMPL(s, base, explicit) \ + [] { \ + /* Use the hidden visibility as a workaround for a GCC bug (#1973). */ \ + /* Use a macro-like name to avoid shadowing warnings. */ \ + struct FMT_VISIBILITY("hidden") FMT_COMPILE_STRING : base { \ + using char_type FMT_MAYBE_UNUSED = fmt::remove_cvref_t; \ + FMT_MAYBE_UNUSED FMT_CONSTEXPR explicit \ + operator fmt::basic_string_view() const { \ + return fmt::detail_exported::compile_string_to_view(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::detail::compile_string, ) + +template +auto write_codepoint(OutputIt out, char prefix, uint32_t cp) -> OutputIt { + *out++ = static_cast('\\'); + *out++ = static_cast(prefix); + Char buf[width]; + fill_n(buf, width, static_cast('0')); + format_uint<4>(buf, cp, width); + return copy_str(buf, buf + width, out); +} + +template +auto write_escaped_cp(OutputIt out, const find_escape_result& escape) + -> OutputIt { + auto c = static_cast(escape.cp); + switch (escape.cp) { + case '\n': + *out++ = static_cast('\\'); + c = static_cast('n'); + break; + case '\r': + *out++ = static_cast('\\'); + c = static_cast('r'); + break; + case '\t': + *out++ = static_cast('\\'); + c = static_cast('t'); + break; + case '"': + FMT_FALLTHROUGH; + case '\'': + FMT_FALLTHROUGH; + case '\\': + *out++ = static_cast('\\'); + break; + default: + if (escape.cp < 0x100) { + return write_codepoint<2, Char>(out, 'x', escape.cp); + } + if (escape.cp < 0x10000) { + return write_codepoint<4, Char>(out, 'u', escape.cp); + } + if (escape.cp < 0x110000) { + return write_codepoint<8, Char>(out, 'U', escape.cp); + } + for (Char escape_char : basic_string_view( + escape.begin, to_unsigned(escape.end - escape.begin))) { + out = write_codepoint<2, Char>(out, 'x', + static_cast(escape_char) & 0xFF); + } + return out; + } + *out++ = c; + return out; +} + +template +auto write_escaped_string(OutputIt out, basic_string_view str) + -> OutputIt { + *out++ = static_cast('"'); + auto begin = str.begin(), end = str.end(); + do { + auto escape = find_escape(begin, end); + out = copy_str(begin, escape.begin, out); + begin = escape.end; + if (!begin) break; + out = write_escaped_cp(out, escape); + } while (begin != end); + *out++ = static_cast('"'); + return out; +} + +template +auto write_escaped_char(OutputIt out, Char v) -> OutputIt { + Char v_array[1] = {v}; + *out++ = static_cast('\''); + if ((needs_escape(static_cast(v)) && v != static_cast('"')) || + v == static_cast('\'')) { + out = write_escaped_cp(out, + find_escape_result{v_array, v_array + 1, + static_cast(v)}); + } else { + *out++ = v; + } + *out++ = static_cast('\''); + return out; +} + +template +FMT_CONSTEXPR auto write_char(OutputIt out, Char value, + const format_specs& specs) -> OutputIt { + bool is_debug = specs.type == presentation_type::debug; + return write_padded(out, specs, 1, [=](reserve_iterator it) { + if (is_debug) return write_escaped_char(it, value); + *it++ = value; + return it; + }); +} +template +FMT_CONSTEXPR auto write(OutputIt out, Char value, + const format_specs& specs, locale_ref loc = {}) + -> OutputIt { + // char is formatted as unsigned char for consistency across platforms. + using unsigned_type = + conditional_t::value, unsigned char, unsigned>; + return check_char_specs(specs) + ? write_char(out, value, specs) + : write(out, static_cast(value), specs, loc); +} + +// Data for write_int that doesn't depend on output iterator type. It is used to +// avoid template code bloat. +template struct write_int_data { + size_t size; + size_t padding; + + FMT_CONSTEXPR write_int_data(int num_digits, unsigned prefix, + const format_specs& specs) + : size((prefix >> 24) + 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 >> 24) + to_unsigned(specs.precision); + padding = to_unsigned(specs.precision - num_digits); + } + } +}; + +// Writes an integer in the format +// +// where are written by write_digits(it). +// prefix contains chars in three lower bytes and the size in the fourth byte. +template +FMT_CONSTEXPR FMT_INLINE auto write_int(OutputIt out, int num_digits, + unsigned prefix, + const format_specs& specs, + W write_digits) -> OutputIt { + // Slightly faster check for specs.width == 0 && specs.precision == -1. + if ((specs.width | (specs.precision + 1)) == 0) { + auto it = reserve(out, to_unsigned(num_digits) + (prefix >> 24)); + if (prefix != 0) { + for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8) + *it++ = static_cast(p & 0xff); + } + return base_iterator(out, write_digits(it)); + } + auto data = write_int_data(num_digits, prefix, specs); + return write_padded( + out, specs, data.size, [=](reserve_iterator it) { + for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8) + *it++ = static_cast(p & 0xff); + it = detail::fill_n(it, data.padding, static_cast('0')); + return write_digits(it); + }); +} + +template class digit_grouping { + private: + std::string grouping_; + std::basic_string thousands_sep_; + + struct next_state { + std::string::const_iterator group; + int pos; + }; + auto initial_state() const -> next_state { return {grouping_.begin(), 0}; } + + // Returns the next digit group separator position. + auto next(next_state& state) const -> int { + if (thousands_sep_.empty()) return max_value(); + if (state.group == grouping_.end()) return state.pos += grouping_.back(); + if (*state.group <= 0 || *state.group == max_value()) + return max_value(); + state.pos += *state.group++; + return state.pos; + } + + public: + explicit digit_grouping(locale_ref loc, bool localized = true) { + if (!localized) return; + auto sep = thousands_sep(loc); + grouping_ = sep.grouping; + if (sep.thousands_sep) thousands_sep_.assign(1, sep.thousands_sep); + } + digit_grouping(std::string grouping, std::basic_string sep) + : grouping_(std::move(grouping)), thousands_sep_(std::move(sep)) {} + + auto has_separator() const -> bool { return !thousands_sep_.empty(); } + + auto count_separators(int num_digits) const -> int { + int count = 0; + auto state = initial_state(); + while (num_digits > next(state)) ++count; + return count; + } + + // Applies grouping to digits and write the output to out. + template + auto apply(Out out, basic_string_view digits) const -> Out { + auto num_digits = static_cast(digits.size()); + auto separators = basic_memory_buffer(); + separators.push_back(0); + auto state = initial_state(); + while (int i = next(state)) { + if (i >= num_digits) break; + separators.push_back(i); + } + for (int i = 0, sep_index = static_cast(separators.size() - 1); + i < num_digits; ++i) { + if (num_digits - i == separators[sep_index]) { + out = + copy_str(thousands_sep_.data(), + thousands_sep_.data() + thousands_sep_.size(), out); + --sep_index; + } + *out++ = static_cast(digits[to_unsigned(i)]); + } + return out; + } +}; + +FMT_CONSTEXPR inline void prefix_append(unsigned& prefix, unsigned value) { + prefix |= prefix != 0 ? value << 8 : value; + prefix += (1u + (value > 0xff ? 1 : 0)) << 24; +} + +// Writes a decimal integer with digit grouping. +template +auto write_int(OutputIt out, UInt value, unsigned prefix, + const format_specs& specs, + const digit_grouping& grouping) -> OutputIt { + static_assert(std::is_same, UInt>::value, ""); + int num_digits = 0; + auto buffer = memory_buffer(); + switch (specs.type) { + case presentation_type::none: + case presentation_type::dec: { + num_digits = count_digits(value); + format_decimal(appender(buffer), value, num_digits); + break; + } + case presentation_type::hex_lower: + case presentation_type::hex_upper: { + bool upper = specs.type == presentation_type::hex_upper; + if (specs.alt) + prefix_append(prefix, unsigned(upper ? 'X' : 'x') << 8 | '0'); + num_digits = count_digits<4>(value); + format_uint<4, char>(appender(buffer), value, num_digits, upper); + break; + } + case presentation_type::bin_lower: + case presentation_type::bin_upper: { + bool upper = specs.type == presentation_type::bin_upper; + if (specs.alt) + prefix_append(prefix, unsigned(upper ? 'B' : 'b') << 8 | '0'); + num_digits = count_digits<1>(value); + format_uint<1, char>(appender(buffer), value, num_digits); + break; + } + case presentation_type::oct: { + num_digits = count_digits<3>(value); + // Octal prefix '0' is counted as a digit, so only add it if precision + // is not greater than the number of digits. + if (specs.alt && specs.precision <= num_digits && value != 0) + prefix_append(prefix, '0'); + format_uint<3, char>(appender(buffer), value, num_digits); + break; + } + case presentation_type::chr: + return write_char(out, static_cast(value), specs); + default: + throw_format_error("invalid format specifier"); + } + + unsigned size = (prefix != 0 ? prefix >> 24 : 0) + to_unsigned(num_digits) + + to_unsigned(grouping.count_separators(num_digits)); + return write_padded( + out, specs, size, size, [&](reserve_iterator it) { + for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8) + *it++ = static_cast(p & 0xff); + return grouping.apply(it, string_view(buffer.data(), buffer.size())); + }); +} + +// Writes a localized value. +FMT_API auto write_loc(appender out, loc_value value, + const format_specs<>& specs, locale_ref loc) -> bool; +template +inline auto write_loc(OutputIt, loc_value, const format_specs&, + locale_ref) -> bool { + return false; +} + +template struct write_int_arg { + UInt abs_value; + unsigned prefix; +}; + +template +FMT_CONSTEXPR auto make_write_int_arg(T value, sign_t sign) + -> write_int_arg> { + auto prefix = 0u; + auto abs_value = static_cast>(value); + if (is_negative(value)) { + prefix = 0x01000000 | '-'; + abs_value = 0 - abs_value; + } else { + constexpr const unsigned prefixes[4] = {0, 0, 0x1000000u | '+', + 0x1000000u | ' '}; + prefix = prefixes[sign]; + } + return {abs_value, prefix}; +} + +template struct loc_writer { + buffer_appender out; + const format_specs& specs; + std::basic_string sep; + std::string grouping; + std::basic_string decimal_point; + + template ::value)> + auto operator()(T value) -> bool { + auto arg = make_write_int_arg(value, specs.sign); + write_int(out, static_cast>(arg.abs_value), arg.prefix, + specs, digit_grouping(grouping, sep)); + return true; + } + + template ::value)> + auto operator()(T) -> bool { + return false; + } +}; + +template +FMT_CONSTEXPR FMT_INLINE auto write_int(OutputIt out, write_int_arg arg, + const format_specs& specs, + locale_ref) -> OutputIt { + static_assert(std::is_same>::value, ""); + auto abs_value = arg.abs_value; + auto prefix = arg.prefix; + switch (specs.type) { + case presentation_type::none: + case presentation_type::dec: { + auto num_digits = count_digits(abs_value); + return write_int( + out, num_digits, prefix, specs, [=](reserve_iterator it) { + return format_decimal(it, abs_value, num_digits).end; + }); + } + case presentation_type::hex_lower: + case presentation_type::hex_upper: { + bool upper = specs.type == presentation_type::hex_upper; + if (specs.alt) + prefix_append(prefix, unsigned(upper ? 'X' : 'x') << 8 | '0'); + int num_digits = count_digits<4>(abs_value); + return write_int( + out, num_digits, prefix, specs, [=](reserve_iterator it) { + return format_uint<4, Char>(it, abs_value, num_digits, upper); + }); + } + case presentation_type::bin_lower: + case presentation_type::bin_upper: { + bool upper = specs.type == presentation_type::bin_upper; + if (specs.alt) + prefix_append(prefix, unsigned(upper ? 'B' : 'b') << 8 | '0'); + int num_digits = count_digits<1>(abs_value); + return write_int(out, num_digits, prefix, specs, + [=](reserve_iterator it) { + return format_uint<1, Char>(it, abs_value, num_digits); + }); + } + case presentation_type::oct: { + int num_digits = count_digits<3>(abs_value); + // Octal prefix '0' is counted as a digit, so only add it if precision + // is not greater than the number of digits. + if (specs.alt && specs.precision <= num_digits && abs_value != 0) + prefix_append(prefix, '0'); + return write_int(out, num_digits, prefix, specs, + [=](reserve_iterator it) { + return format_uint<3, Char>(it, abs_value, num_digits); + }); + } + case presentation_type::chr: + return write_char(out, static_cast(abs_value), specs); + default: + throw_format_error("invalid format specifier"); + } + return out; +} +template +FMT_CONSTEXPR FMT_NOINLINE auto write_int_noinline( + OutputIt out, write_int_arg arg, const format_specs& specs, + locale_ref loc) -> OutputIt { + return write_int(out, arg, specs, loc); +} +template ::value && + !std::is_same::value && + std::is_same>::value)> +FMT_CONSTEXPR FMT_INLINE auto write(OutputIt out, T value, + const format_specs& specs, + locale_ref loc) -> OutputIt { + if (specs.localized && write_loc(out, value, specs, loc)) return out; + return write_int_noinline(out, make_write_int_arg(value, specs.sign), specs, + loc); +} +// An inlined version of write used in format string compilation. +template ::value && + !std::is_same::value && + !std::is_same>::value)> +FMT_CONSTEXPR FMT_INLINE auto write(OutputIt out, T value, + const format_specs& specs, + locale_ref loc) -> OutputIt { + if (specs.localized && write_loc(out, value, specs, loc)) return out; + return write_int(out, make_write_int_arg(value, specs.sign), specs, loc); +} + +// 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; + FMT_UNCHECKED_ITERATOR(counting_iterator); + + struct value_type { + template FMT_CONSTEXPR void operator=(const T&) {} + }; + + FMT_CONSTEXPR counting_iterator() : count_(0) {} + + FMT_CONSTEXPR auto count() const -> size_t { return count_; } + + FMT_CONSTEXPR auto operator++() -> counting_iterator& { + ++count_; + return *this; + } + FMT_CONSTEXPR auto operator++(int) -> counting_iterator { + auto it = *this; + ++*this; + return it; + } + + FMT_CONSTEXPR friend auto operator+(counting_iterator it, difference_type n) + -> counting_iterator { + it.count_ += static_cast(n); + return it; + } + + FMT_CONSTEXPR auto operator*() const -> value_type { return {}; } +}; + +template +FMT_CONSTEXPR auto write(OutputIt out, basic_string_view s, + const format_specs& specs) -> OutputIt { + 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)); + bool is_debug = specs.type == presentation_type::debug; + size_t width = 0; + if (specs.width != 0) { + if (is_debug) + width = write_escaped_string(counting_iterator{}, s).count(); + else + width = compute_width(basic_string_view(data, size)); + } + return write_padded(out, specs, size, width, + [=](reserve_iterator it) { + if (is_debug) return write_escaped_string(it, s); + return copy_str(data, data + size, it); + }); +} +template +FMT_CONSTEXPR auto write(OutputIt out, + basic_string_view> s, + const format_specs& specs, locale_ref) + -> OutputIt { + return write(out, s, specs); +} +template +FMT_CONSTEXPR auto write(OutputIt out, const Char* s, + const format_specs& specs, locale_ref) + -> OutputIt { + if (specs.type == presentation_type::pointer) + return write_ptr(out, bit_cast(s), &specs); + if (!s) throw_format_error("string pointer is null"); + return write(out, basic_string_view(s), specs, {}); +} + +template ::value && + !std::is_same::value && + !std::is_same::value)> +FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt { + auto abs_value = static_cast>(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(num_digits); + auto it = reserve(out, size); + if (auto ptr = to_pointer(it, size)) { + if (negative) *ptr++ = static_cast('-'); + format_decimal(ptr, abs_value, num_digits); + return out; + } + if (negative) *it++ = static_cast('-'); + it = format_decimal(it, abs_value, num_digits).end; + return base_iterator(out, it); +} + +// DEPRECATED! +template +FMT_CONSTEXPR auto parse_align(const Char* begin, const Char* end, + format_specs& specs) -> const Char* { + FMT_ASSERT(begin != end, ""); + auto align = align::none; + auto p = begin + code_point_length(begin); + if (end - p <= 0) p = begin; + for (;;) { + switch (to_ascii(*p)) { + case '<': + align = align::left; + break; + case '>': + align = align::right; + break; + case '^': + align = align::center; + break; + } + if (align != align::none) { + if (p != begin) { + auto c = *begin; + if (c == '}') return begin; + if (c == '{') { + throw_format_error("invalid fill character '{'"); + return begin; + } + specs.fill = {begin, to_unsigned(p - begin)}; + begin = p + 1; + } else { + ++begin; + } + break; + } else if (p == begin) { + break; + } + p = begin; + } + specs.align = align; + return begin; +} + +// 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 showpoint : 1; +}; + +template +FMT_CONSTEXPR auto parse_float_type_spec(const format_specs& specs) + -> float_specs { + auto result = float_specs(); + result.showpoint = specs.alt; + result.locale = specs.localized; + switch (specs.type) { + case presentation_type::none: + result.format = float_format::general; + break; + case presentation_type::general_upper: + result.upper = true; + FMT_FALLTHROUGH; + case presentation_type::general_lower: + result.format = float_format::general; + break; + case presentation_type::exp_upper: + result.upper = true; + FMT_FALLTHROUGH; + case presentation_type::exp_lower: + result.format = float_format::exp; + result.showpoint |= specs.precision != 0; + break; + case presentation_type::fixed_upper: + result.upper = true; + FMT_FALLTHROUGH; + case presentation_type::fixed_lower: + result.format = float_format::fixed; + result.showpoint |= specs.precision != 0; + break; + case presentation_type::hexfloat_upper: + result.upper = true; + FMT_FALLTHROUGH; + case presentation_type::hexfloat_lower: + result.format = float_format::hex; + break; + default: + throw_format_error("invalid format specifier"); + break; + } + return result; +} + +template +FMT_CONSTEXPR20 auto write_nonfinite(OutputIt out, bool isnan, + format_specs specs, + const float_specs& fspecs) -> OutputIt { + auto str = + isnan ? (fspecs.upper ? "NAN" : "nan") : (fspecs.upper ? "INF" : "inf"); + constexpr size_t str_size = 3; + auto sign = fspecs.sign; + auto size = str_size + (sign ? 1 : 0); + // Replace '0'-padding with space for non-finite values. + const bool is_zero_fill = + specs.fill.size() == 1 && *specs.fill.data() == static_cast('0'); + if (is_zero_fill) specs.fill[0] = static_cast(' '); + return write_padded(out, specs, size, [=](reserve_iterator it) { + if (sign) *it++ = detail::sign(sign); + return copy_str(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; +}; + +constexpr auto get_significand_size(const big_decimal_fp& f) -> int { + return f.significand_size; +} +template +inline auto get_significand_size(const dragonbox::decimal_fp& f) -> int { + return count_digits(f.significand); +} + +template +constexpr auto write_significand(OutputIt out, const char* significand, + int significand_size) -> OutputIt { + return copy_str(significand, significand + significand_size, out); +} +template +inline auto write_significand(OutputIt out, UInt significand, + int significand_size) -> OutputIt { + return format_decimal(out, significand, significand_size).end; +} +template +FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand, + int significand_size, int exponent, + const Grouping& grouping) -> OutputIt { + if (!grouping.has_separator()) { + out = write_significand(out, significand, significand_size); + return detail::fill_n(out, exponent, static_cast('0')); + } + auto buffer = memory_buffer(); + write_significand(appender(buffer), significand, significand_size); + detail::fill_n(appender(buffer), exponent, '0'); + return grouping.apply(out, string_view(buffer.data(), buffer.size())); +} + +template ::value)> +inline auto write_significand(Char* out, UInt significand, int significand_size, + int integral_size, Char decimal_point) -> Char* { + if (!decimal_point) + return format_decimal(out, significand, significand_size).end; + out += significand_size + 1; + Char* end = out; + int floating_size = significand_size - integral_size; + for (int i = floating_size / 2; i > 0; --i) { + out -= 2; + copy2(out, digits2(static_cast(significand % 100))); + significand /= 100; + } + if (floating_size % 2 != 0) { + *--out = static_cast('0' + significand % 10); + significand /= 10; + } + *--out = decimal_point; + format_decimal(out - integral_size, significand, integral_size); + return end; +} + +template >::value)> +inline auto write_significand(OutputIt out, UInt significand, + int significand_size, int integral_size, + Char decimal_point) -> OutputIt { + // Buffer is large enough to hold digits (digits10 + 1) and a decimal point. + Char buffer[digits10() + 2]; + auto end = write_significand(buffer, significand, significand_size, + integral_size, decimal_point); + return detail::copy_str_noinline(buffer, end, out); +} + +template +FMT_CONSTEXPR auto write_significand(OutputIt out, const char* significand, + int significand_size, int integral_size, + Char decimal_point) -> OutputIt { + out = detail::copy_str_noinline(significand, + significand + integral_size, out); + if (!decimal_point) return out; + *out++ = decimal_point; + return detail::copy_str_noinline(significand + integral_size, + significand + significand_size, out); +} + +template +FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand, + int significand_size, int integral_size, + Char decimal_point, + const Grouping& grouping) -> OutputIt { + if (!grouping.has_separator()) { + return write_significand(out, significand, significand_size, integral_size, + decimal_point); + } + auto buffer = basic_memory_buffer(); + write_significand(buffer_appender(buffer), significand, + significand_size, integral_size, decimal_point); + grouping.apply( + out, basic_string_view(buffer.data(), to_unsigned(integral_size))); + return detail::copy_str_noinline(buffer.data() + integral_size, + buffer.end(), out); +} + +template > +FMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& f, + const format_specs& specs, + float_specs fspecs, locale_ref loc) + -> OutputIt { + auto significand = f.significand; + int significand_size = get_significand_size(f); + const Char zero = static_cast('0'); + auto sign = fspecs.sign; + size_t size = to_unsigned(significand_size) + (sign ? 1 : 0); + using iterator = reserve_iterator; + + Char decimal_point = + fspecs.locale ? detail::decimal_point(loc) : static_cast('.'); + + int output_exp = f.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 = fspecs.precision - significand_size; + if (num_zeros < 0) num_zeros = 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++ = detail::sign(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 = detail::fill_n(it, num_zeros, zero); + *it++ = static_cast(exp_char); + return write_exponent(output_exp, it); + }; + return specs.width > 0 ? write_padded(out, specs, size, write) + : base_iterator(out, write(reserve(out, size))); + } + + int exp = f.exponent + significand_size; + if (f.exponent >= 0) { + // 1234e5 -> 123400000[.0+] + size += to_unsigned(f.exponent); + int num_zeros = fspecs.precision - exp; + abort_fuzzing_if(num_zeros > 5000); + if (fspecs.showpoint) { + ++size; + if (num_zeros <= 0 && fspecs.format != float_format::fixed) num_zeros = 0; + if (num_zeros > 0) size += to_unsigned(num_zeros); + } + auto grouping = Grouping(loc, fspecs.locale); + size += to_unsigned(grouping.count_separators(exp)); + return write_padded(out, specs, size, [&](iterator it) { + if (sign) *it++ = detail::sign(sign); + it = write_significand(it, significand, significand_size, + f.exponent, grouping); + if (!fspecs.showpoint) return it; + *it++ = decimal_point; + return num_zeros > 0 ? detail::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); + auto grouping = Grouping(loc, fspecs.locale); + size += to_unsigned(grouping.count_separators(exp)); + return write_padded(out, specs, size, [&](iterator it) { + if (sign) *it++ = detail::sign(sign); + it = write_significand(it, significand, significand_size, exp, + decimal_point, grouping); + return num_zeros > 0 ? detail::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; + } + bool pointy = num_zeros != 0 || significand_size != 0 || fspecs.showpoint; + size += 1 + (pointy ? 1 : 0) + to_unsigned(num_zeros); + return write_padded(out, specs, size, [&](iterator it) { + if (sign) *it++ = detail::sign(sign); + *it++ = zero; + if (!pointy) return it; + *it++ = decimal_point; + it = detail::fill_n(it, num_zeros, zero); + return write_significand(it, significand, significand_size); + }); +} + +template class fallback_digit_grouping { + public: + constexpr fallback_digit_grouping(locale_ref, bool) {} + + constexpr auto has_separator() const -> bool { return false; } + + constexpr auto count_separators(int) const -> int { return 0; } + + template + constexpr auto apply(Out out, basic_string_view) const -> Out { + return out; + } +}; + +template +FMT_CONSTEXPR20 auto write_float(OutputIt out, const DecimalFP& f, + const format_specs& specs, + float_specs fspecs, locale_ref loc) + -> OutputIt { + if (is_constant_evaluated()) { + return do_write_float>(out, f, specs, fspecs, + loc); + } else { + return do_write_float(out, f, specs, fspecs, loc); + } +} + +template constexpr auto isnan(T value) -> bool { + return !(value >= value); // std::isnan doesn't support __float128. +} + +template +struct has_isfinite : std::false_type {}; + +template +struct has_isfinite> + : std::true_type {}; + +template ::value&& + has_isfinite::value)> +FMT_CONSTEXPR20 auto isfinite(T value) -> bool { + constexpr T inf = T(std::numeric_limits::infinity()); + if (is_constant_evaluated()) + return !detail::isnan(value) && value < inf && value > -inf; + return std::isfinite(value); +} +template ::value)> +FMT_CONSTEXPR auto isfinite(T value) -> bool { + T inf = T(std::numeric_limits::infinity()); + // std::isfinite doesn't support __float128. + return !detail::isnan(value) && value < inf && value > -inf; +} + +template ::value)> +FMT_INLINE FMT_CONSTEXPR bool signbit(T value) { + if (is_constant_evaluated()) { +#ifdef __cpp_if_constexpr + if constexpr (std::numeric_limits::is_iec559) { + auto bits = detail::bit_cast(static_cast(value)); + return (bits >> (num_bits() - 1)) != 0; + } +#endif + } + return std::signbit(static_cast(value)); +} + +inline FMT_CONSTEXPR20 void adjust_precision(int& precision, int exp10) { + // Adjust fixed precision by exponent because it is relative to decimal + // point. + if (exp10 > 0 && precision > max_value() - exp10) + FMT_THROW(format_error("number is too big")); + precision += exp10; +} + +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 bigits_; + int exp_; + + FMT_CONSTEXPR20 auto operator[](int index) const -> bigit { + return bigits_[to_unsigned(index)]; + } + FMT_CONSTEXPR20 auto operator[](int index) -> bigit& { + return bigits_[to_unsigned(index)]; + } + + static constexpr const int bigit_bits = num_bits(); + + friend struct formatter; + + FMT_CONSTEXPR20 void subtract_bigits(int index, bigit other, bigit& borrow) { + auto result = static_cast((*this)[index]) - other - borrow; + (*this)[index] = static_cast(result); + borrow = static_cast(result >> (bigit_bits * 2 - 1)); + } + + FMT_CONSTEXPR20 void remove_leading_zeros() { + int num_bigits = static_cast(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. + FMT_CONSTEXPR20 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(); + } + + FMT_CONSTEXPR20 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(result); + carry = static_cast(result >> bigit_bits); + } + if (carry != 0) bigits_.push_back(carry); + } + + template ::value || + std::is_same::value)> + FMT_CONSTEXPR20 void multiply(UInt value) { + using half_uint = + conditional_t::value, uint64_t, uint32_t>; + const int shift = num_bits() - bigit_bits; + const UInt lower = static_cast(value); + const UInt upper = value >> num_bits(); + UInt carry = 0; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + UInt result = lower * bigits_[i] + static_cast(carry); + carry = (upper * bigits_[i] << shift) + (result >> bigit_bits) + + (carry >> bigit_bits); + bigits_[i] = static_cast(result); + } + while (carry != 0) { + bigits_.push_back(static_cast(carry)); + carry >>= bigit_bits; + } + } + + template ::value || + std::is_same::value)> + FMT_CONSTEXPR20 void assign(UInt n) { + size_t num_bigits = 0; + do { + bigits_[num_bigits++] = static_cast(n); + n >>= bigit_bits; + } while (n != 0); + bigits_.resize(num_bigits); + exp_ = 0; + } + + public: + FMT_CONSTEXPR20 bigint() : exp_(0) {} + explicit bigint(uint64_t n) { assign(n); } + + bigint(const bigint&) = delete; + void operator=(const bigint&) = delete; + + FMT_CONSTEXPR20 void assign(const bigint& other) { + auto size = other.bigits_.size(); + bigits_.resize(size); + auto data = other.bigits_.data(); + copy_str(data, data + size, bigits_.data()); + exp_ = other.exp_; + } + + template FMT_CONSTEXPR20 void operator=(Int n) { + FMT_ASSERT(n > 0, ""); + assign(uint64_or_128_t(n)); + } + + FMT_CONSTEXPR20 auto num_bigits() const -> int { + return static_cast(bigits_.size()) + exp_; + } + + FMT_NOINLINE FMT_CONSTEXPR20 auto operator<<=(int shift) -> bigint& { + FMT_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 + FMT_CONSTEXPR20 auto operator*=(Int value) -> bigint& { + FMT_ASSERT(value > 0, ""); + multiply(uint32_or_64_or_128_t(value)); + return *this; + } + + friend FMT_CONSTEXPR20 auto compare(const bigint& lhs, const bigint& rhs) + -> int { + 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(lhs.bigits_.size()) - 1; + int j = static_cast(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 FMT_CONSTEXPR20 auto add_compare(const bigint& lhs1, + const bigint& lhs2, const bigint& rhs) + -> int { + auto minimum = [](int a, int b) { return a < b ? a : b; }; + auto maximum = [](int a, int b) { return a > b ? a : b; }; + int max_lhs_bigits = maximum(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 = minimum(minimum(lhs1.exp_, lhs2.exp_), rhs.exp_); + for (int i = num_rhs_bigits - 1; i >= min_exp; --i) { + double_bigit sum = + static_cast(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. + FMT_CONSTEXPR20 void assign_pow10(int exp) { + FMT_ASSERT(exp >= 0, ""); + if (exp == 0) return *this = 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. + *this = 5; + bitmask >>= 1; + while (bitmask != 0) { + square(); + if ((exp & bitmask) != 0) *this *= 5; + bitmask >>= 1; + } + *this <<= exp; // Multiply by pow(2, exp) by shifting. + } + + FMT_CONSTEXPR20 void square() { + int num_bigits = static_cast(bigits_.size()); + int num_result_bigits = 2 * num_bigits; + basic_memory_buffer n(std::move(bigits_)); + bigits_.resize(to_unsigned(num_result_bigits)); + auto sum = uint128_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(n[i]) * n[j]; + } + (*this)[bigit_index] = static_cast(sum); + sum >>= num_bits(); // 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(n[i++]) * n[j--]; + (*this)[bigit_index] = static_cast(sum); + sum >>= num_bits(); + } + 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. + FMT_CONSTEXPR20 void align(const bigint& other) { + int exp_difference = exp_ - other.exp_; + if (exp_difference <= 0) return; + int num_bigits = static_cast(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, 0u); + exp_ -= exp_difference; + } + + // Divides this bignum by divisor, assigning the remainder to this and + // returning the quotient. + FMT_CONSTEXPR20 auto divmod_assign(const bigint& divisor) -> int { + 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; + } +}; + +// format_dragon flags. +enum dragon { + predecessor_closer = 1, + fixup = 2, // Run fixup to correct exp10 which can be off by one. + fixed = 4, +}; + +// Formats a floating-point number using a variation of the Fixed-Precision +// Positive Floating-Point Printout ((FPP)^2) algorithm by Steele & White: +// https://fmt.dev/papers/p372-steele.pdf. +FMT_CONSTEXPR20 inline void format_dragon(basic_fp value, + unsigned flags, int num_digits, + buffer& 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). + // 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. + bool is_predecessor_closer = (flags & dragon::predecessor_closer) != 0; + int shift = is_predecessor_closer ? 2 : 1; + if (value.e >= 0) { + numerator = value.f; + numerator <<= value.e + shift; + lower = 1; + lower <<= value.e; + if (is_predecessor_closer) { + upper_store = 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 (is_predecessor_closer) { + upper_store.assign(numerator); + upper_store <<= 1; + upper = &upper_store; + } + numerator *= value.f; + numerator <<= shift; + denominator = 1; + denominator <<= shift - value.e; + } else { + numerator = value.f; + numerator <<= shift; + denominator.assign_pow10(exp10); + denominator <<= shift - value.e; + lower = 1; + if (is_predecessor_closer) { + upper_store = 1ULL << 1; + upper = &upper_store; + } + } + int even = static_cast((value.f & 1) == 0); + if (!upper) upper = &lower; + bool shortest = num_digits < 0; + if ((flags & dragon::fixup) != 0) { + if (add_compare(numerator, *upper, denominator) + even <= 0) { + --exp10; + numerator *= 10; + if (num_digits < 0) { + lower *= 10; + if (upper != &lower) *upper *= 10; + } + } + if ((flags & dragon::fixed) != 0) adjust_precision(num_digits, exp10 + 1); + } + // Invariant: value == (numerator / denominator) * pow(10, exp10). + if (shortest) { + // Generate the shortest representation. + 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('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) { + denominator *= 10; + auto digit = add_compare(numerator, numerator, denominator) > 0 ? '1' : '0'; + buf.push_back(digit); + 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('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'; + if ((flags & dragon::fixed) != 0) + buf.push_back('0'); + else + ++exp10; + } + return; + } + ++digit; + } + buf[num_digits - 1] = static_cast('0' + digit); +} + +// Formats a floating-point number using the hexfloat format. +template ::value)> +FMT_CONSTEXPR20 void format_hexfloat(Float value, int precision, + float_specs specs, buffer& buf) { + // float is passed as double to reduce the number of instantiations and to + // simplify implementation. + static_assert(!std::is_same::value, ""); + + using info = dragonbox::float_info; + + // Assume Float is in the format [sign][exponent][significand]. + using carrier_uint = typename info::carrier_uint; + + constexpr auto num_float_significand_bits = + detail::num_significand_bits(); + + basic_fp f(value); + f.e += num_float_significand_bits; + if (!has_implicit_bit()) --f.e; + + constexpr auto num_fraction_bits = + num_float_significand_bits + (has_implicit_bit() ? 1 : 0); + constexpr auto num_xdigits = (num_fraction_bits + 3) / 4; + + constexpr auto leading_shift = ((num_xdigits - 1) * 4); + const auto leading_mask = carrier_uint(0xF) << leading_shift; + const auto leading_xdigit = + static_cast((f.f & leading_mask) >> leading_shift); + if (leading_xdigit > 1) f.e -= (32 - countl_zero(leading_xdigit) - 1); + + int print_xdigits = num_xdigits - 1; + if (precision >= 0 && print_xdigits > precision) { + const int shift = ((print_xdigits - precision - 1) * 4); + const auto mask = carrier_uint(0xF) << shift; + const auto v = static_cast((f.f & mask) >> shift); + + if (v >= 8) { + const auto inc = carrier_uint(1) << (shift + 4); + f.f += inc; + f.f &= ~(inc - 1); + } + + // Check long double overflow + if (!has_implicit_bit()) { + const auto implicit_bit = carrier_uint(1) << num_float_significand_bits; + if ((f.f & implicit_bit) == implicit_bit) { + f.f >>= 4; + f.e += 4; + } + } + + print_xdigits = precision; + } + + char xdigits[num_bits() / 4]; + detail::fill_n(xdigits, sizeof(xdigits), '0'); + format_uint<4>(xdigits, f.f, num_xdigits, specs.upper); + + // Remove zero tail + while (print_xdigits > 0 && xdigits[print_xdigits] == '0') --print_xdigits; + + buf.push_back('0'); + buf.push_back(specs.upper ? 'X' : 'x'); + buf.push_back(xdigits[0]); + if (specs.showpoint || print_xdigits > 0 || print_xdigits < precision) + buf.push_back('.'); + buf.append(xdigits + 1, xdigits + 1 + print_xdigits); + for (; print_xdigits < precision; ++print_xdigits) buf.push_back('0'); + + buf.push_back(specs.upper ? 'P' : 'p'); + + uint32_t abs_e; + if (f.e < 0) { + buf.push_back('-'); + abs_e = static_cast(-f.e); + } else { + buf.push_back('+'); + abs_e = static_cast(f.e); + } + format_decimal(appender(buf), abs_e, detail::count_digits(abs_e)); +} + +template ::value)> +FMT_CONSTEXPR20 void format_hexfloat(Float value, int precision, + float_specs specs, buffer& buf) { + format_hexfloat(static_cast(value), precision, specs, buf); +} + +constexpr auto fractional_part_rounding_thresholds(int index) -> uint32_t { + // For checking rounding thresholds. + // The kth entry is chosen to be the smallest integer such that the + // upper 32-bits of 10^(k+1) times it is strictly bigger than 5 * 10^k. + // It is equal to ceil(2^31 + 2^32/10^(k + 1)). + // These are stored in a string literal because we cannot have static arrays + // in constexpr functions and non-static ones are poorly optimized. + return U"\x9999999a\x828f5c29\x80418938\x80068db9\x8000a7c6\x800010c7" + U"\x800001ae\x8000002b"[index]; +} + +template +FMT_CONSTEXPR20 auto format_float(Float value, int precision, float_specs specs, + buffer& buf) -> int { + // float is passed as double to reduce the number of instantiations. + static_assert(!std::is_same::value, ""); + FMT_ASSERT(value >= 0, "value is negative"); + auto converted_value = convert_float(value); + + 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)); + fill_n(buf.data(), precision, '0'); + return -precision; + } + + int exp = 0; + bool use_dragon = true; + unsigned dragon_flags = 0; + if (!is_fast_float() || is_constant_evaluated()) { + const auto inv_log2_10 = 0.3010299956639812; // 1 / log2(10) + using info = dragonbox::float_info; + const auto f = basic_fp(converted_value); + // Compute exp, an approximate power of 10, such that + // 10^(exp - 1) <= value < 10^exp or 10^exp <= value < 10^(exp + 1). + // This is based on log10(value) == log2(value) / log2(10) and approximation + // of log2(value) by e + num_fraction_bits idea from double-conversion. + auto e = (f.e + count_digits<1>(f.f) - 1) * inv_log2_10 - 1e-10; + exp = static_cast(e); + if (e > exp) ++exp; // Compute ceil. + dragon_flags = dragon::fixup; + } else if (precision < 0) { + // Use Dragonbox for the shortest format. + if (specs.binary32) { + auto dec = dragonbox::to_decimal(static_cast(value)); + write(buffer_appender(buf), dec.significand); + return dec.exponent; + } + auto dec = dragonbox::to_decimal(static_cast(value)); + write(buffer_appender(buf), dec.significand); + return dec.exponent; + } else { + // Extract significand bits and exponent bits. + using info = dragonbox::float_info; + auto br = bit_cast(static_cast(value)); + + const uint64_t significand_mask = + (static_cast(1) << num_significand_bits()) - 1; + uint64_t significand = (br & significand_mask); + int exponent = static_cast((br & exponent_mask()) >> + num_significand_bits()); + + if (exponent != 0) { // Check if normal. + exponent -= exponent_bias() + num_significand_bits(); + significand |= + (static_cast(1) << num_significand_bits()); + significand <<= 1; + } else { + // Normalize subnormal inputs. + FMT_ASSERT(significand != 0, "zeros should not appear here"); + int shift = countl_zero(significand); + FMT_ASSERT(shift >= num_bits() - num_significand_bits(), + ""); + shift -= (num_bits() - num_significand_bits() - 2); + exponent = (std::numeric_limits::min_exponent - + num_significand_bits()) - + shift; + significand <<= shift; + } + + // Compute the first several nonzero decimal significand digits. + // We call the number we get the first segment. + const int k = info::kappa - dragonbox::floor_log10_pow2(exponent); + exp = -k; + const int beta = exponent + dragonbox::floor_log2_pow10(k); + uint64_t first_segment; + bool has_more_segments; + int digits_in_the_first_segment; + { + const auto r = dragonbox::umul192_upper128( + significand << beta, dragonbox::get_cached_power(k)); + first_segment = r.high(); + has_more_segments = r.low() != 0; + + // The first segment can have 18 ~ 19 digits. + if (first_segment >= 1000000000000000000ULL) { + digits_in_the_first_segment = 19; + } else { + // When it is of 18-digits, we align it to 19-digits by adding a bogus + // zero at the end. + digits_in_the_first_segment = 18; + first_segment *= 10; + } + } + + // Compute the actual number of decimal digits to print. + if (fixed) adjust_precision(precision, exp + digits_in_the_first_segment); + + // Use Dragon4 only when there might be not enough digits in the first + // segment. + if (digits_in_the_first_segment > precision) { + use_dragon = false; + + if (precision <= 0) { + exp += digits_in_the_first_segment; + + if (precision < 0) { + // Nothing to do, since all we have are just leading zeros. + buf.try_resize(0); + } else { + // We may need to round-up. + buf.try_resize(1); + if ((first_segment | static_cast(has_more_segments)) > + 5000000000000000000ULL) { + buf[0] = '1'; + } else { + buf[0] = '0'; + } + } + } // precision <= 0 + else { + exp += digits_in_the_first_segment - precision; + + // When precision > 0, we divide the first segment into three + // subsegments, each with 9, 9, and 0 ~ 1 digits so that each fits + // in 32-bits which usually allows faster calculation than in + // 64-bits. Since some compiler (e.g. MSVC) doesn't know how to optimize + // division-by-constant for large 64-bit divisors, we do it here + // manually. The magic number 7922816251426433760 below is equal to + // ceil(2^(64+32) / 10^10). + const uint32_t first_subsegment = static_cast( + dragonbox::umul128_upper64(first_segment, 7922816251426433760ULL) >> + 32); + const uint64_t second_third_subsegments = + first_segment - first_subsegment * 10000000000ULL; + + uint64_t prod; + uint32_t digits; + bool should_round_up; + int number_of_digits_to_print = precision > 9 ? 9 : precision; + + // Print a 9-digits subsegment, either the first or the second. + auto print_subsegment = [&](uint32_t subsegment, char* buffer) { + int number_of_digits_printed = 0; + + // If we want to print an odd number of digits from the subsegment, + if ((number_of_digits_to_print & 1) != 0) { + // Convert to 64-bit fixed-point fractional form with 1-digit + // integer part. The magic number 720575941 is a good enough + // approximation of 2^(32 + 24) / 10^8; see + // https://jk-jeon.github.io/posts/2022/12/fixed-precision-formatting/#fixed-length-case + // for details. + prod = ((subsegment * static_cast(720575941)) >> 24) + 1; + digits = static_cast(prod >> 32); + *buffer = static_cast('0' + digits); + number_of_digits_printed++; + } + // If we want to print an even number of digits from the + // first_subsegment, + else { + // Convert to 64-bit fixed-point fractional form with 2-digits + // integer part. The magic number 450359963 is a good enough + // approximation of 2^(32 + 20) / 10^7; see + // https://jk-jeon.github.io/posts/2022/12/fixed-precision-formatting/#fixed-length-case + // for details. + prod = ((subsegment * static_cast(450359963)) >> 20) + 1; + digits = static_cast(prod >> 32); + copy2(buffer, digits2(digits)); + number_of_digits_printed += 2; + } + + // Print all digit pairs. + while (number_of_digits_printed < number_of_digits_to_print) { + prod = static_cast(prod) * static_cast(100); + digits = static_cast(prod >> 32); + copy2(buffer + number_of_digits_printed, digits2(digits)); + number_of_digits_printed += 2; + } + }; + + // Print first subsegment. + print_subsegment(first_subsegment, buf.data()); + + // Perform rounding if the first subsegment is the last subsegment to + // print. + if (precision <= 9) { + // Rounding inside the subsegment. + // We round-up if: + // - either the fractional part is strictly larger than 1/2, or + // - the fractional part is exactly 1/2 and the last digit is odd. + // We rely on the following observations: + // - If fractional_part >= threshold, then the fractional part is + // strictly larger than 1/2. + // - If the MSB of fractional_part is set, then the fractional part + // must be at least 1/2. + // - When the MSB of fractional_part is set, either + // second_third_subsegments being nonzero or has_more_segments + // being true means there are further digits not printed, so the + // fractional part is strictly larger than 1/2. + if (precision < 9) { + uint32_t fractional_part = static_cast(prod); + should_round_up = + fractional_part >= fractional_part_rounding_thresholds( + 8 - number_of_digits_to_print) || + ((fractional_part >> 31) & + ((digits & 1) | (second_third_subsegments != 0) | + has_more_segments)) != 0; + } + // Rounding at the subsegment boundary. + // In this case, the fractional part is at least 1/2 if and only if + // second_third_subsegments >= 5000000000ULL, and is strictly larger + // than 1/2 if we further have either second_third_subsegments > + // 5000000000ULL or has_more_segments == true. + else { + should_round_up = second_third_subsegments > 5000000000ULL || + (second_third_subsegments == 5000000000ULL && + ((digits & 1) != 0 || has_more_segments)); + } + } + // Otherwise, print the second subsegment. + else { + // Compilers are not aware of how to leverage the maximum value of + // second_third_subsegments to find out a better magic number which + // allows us to eliminate an additional shift. 1844674407370955162 = + // ceil(2^64/10) < ceil(2^64*(10^9/(10^10 - 1))). + const uint32_t second_subsegment = + static_cast(dragonbox::umul128_upper64( + second_third_subsegments, 1844674407370955162ULL)); + const uint32_t third_subsegment = + static_cast(second_third_subsegments) - + second_subsegment * 10; + + number_of_digits_to_print = precision - 9; + print_subsegment(second_subsegment, buf.data() + 9); + + // Rounding inside the subsegment. + if (precision < 18) { + // The condition third_subsegment != 0 implies that the segment was + // of 19 digits, so in this case the third segment should be + // consisting of a genuine digit from the input. + uint32_t fractional_part = static_cast(prod); + should_round_up = + fractional_part >= fractional_part_rounding_thresholds( + 8 - number_of_digits_to_print) || + ((fractional_part >> 31) & + ((digits & 1) | (third_subsegment != 0) | + has_more_segments)) != 0; + } + // Rounding at the subsegment boundary. + else { + // In this case, the segment must be of 19 digits, thus + // the third subsegment should be consisting of a genuine digit from + // the input. + should_round_up = third_subsegment > 5 || + (third_subsegment == 5 && + ((digits & 1) != 0 || has_more_segments)); + } + } + + // Round-up if necessary. + if (should_round_up) { + ++buf[precision - 1]; + for (int i = precision - 1; i > 0 && buf[i] > '9'; --i) { + buf[i] = '0'; + ++buf[i - 1]; + } + if (buf[0] > '9') { + buf[0] = '1'; + if (fixed) + buf[precision++] = '0'; + else + ++exp; + } + } + buf.try_resize(to_unsigned(precision)); + } + } // if (digits_in_the_first_segment > precision) + else { + // Adjust the exponent for its use in Dragon4. + exp += digits_in_the_first_segment - 1; + } + } + if (use_dragon) { + auto f = basic_fp(); + bool is_predecessor_closer = specs.binary32 + ? f.assign(static_cast(value)) + : f.assign(converted_value); + if (is_predecessor_closer) dragon_flags |= dragon::predecessor_closer; + if (fixed) dragon_flags |= dragon::fixed; + // 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; + format_dragon(f, dragon_flags, precision, buf, exp); + } + 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; +} +template +FMT_CONSTEXPR20 auto write_float(OutputIt out, T value, + format_specs specs, locale_ref loc) + -> OutputIt { + float_specs fspecs = parse_float_type_spec(specs); + fspecs.sign = specs.sign; + if (detail::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 (!detail::isfinite(value)) + return write_nonfinite(out, detail::isnan(value), specs, fspecs); + + if (specs.align == align::numeric && fspecs.sign) { + auto it = reserve(out, 1); + *it++ = detail::sign(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(detail::sign(fspecs.sign)); + format_hexfloat(convert_float(value), specs.precision, fspecs, buffer); + return write_bytes(out, {buffer.data(), buffer.size()}, + specs); + } + int precision = specs.precision >= 0 || specs.type == presentation_type::none + ? specs.precision + : 6; + if (fspecs.format == float_format::exp) { + if (precision == max_value()) + throw_format_error("number is too big"); + else + ++precision; + } else if (fspecs.format != float_format::fixed && precision == 0) { + precision = 1; + } + if (const_check(std::is_same())) fspecs.binary32 = true; + int exp = format_float(convert_float(value), precision, fspecs, buffer); + fspecs.precision = precision; + auto f = big_decimal_fp{buffer.data(), static_cast(buffer.size()), exp}; + return write_float(out, f, specs, fspecs, loc); +} + +template ::value)> +FMT_CONSTEXPR20 auto write(OutputIt out, T value, format_specs specs, + locale_ref loc = {}) -> OutputIt { + if (const_check(!is_supported_floating_point(value))) return out; + return specs.localized && write_loc(out, value, specs, loc) + ? out + : write_float(out, value, specs, loc); +} + +template ::value)> +FMT_CONSTEXPR20 auto write(OutputIt out, T value) -> OutputIt { + if (is_constant_evaluated()) return write(out, value, format_specs()); + if (const_check(!is_supported_floating_point(value))) return out; + + auto fspecs = float_specs(); + if (detail::signbit(value)) { + fspecs.sign = sign::minus; + value = -value; + } + + constexpr auto specs = format_specs(); + using floaty = conditional_t::value, double, T>; + using floaty_uint = typename dragonbox::float_info::carrier_uint; + floaty_uint mask = exponent_mask(); + if ((bit_cast(value) & mask) == mask) + return write_nonfinite(out, std::isnan(value), specs, fspecs); + + auto dec = dragonbox::to_decimal(static_cast(value)); + return write_float(out, dec, specs, fspecs, {}); +} + +template ::value && + !is_fast_float::value)> +inline auto write(OutputIt out, T value) -> OutputIt { + return write(out, value, format_specs()); +} + +template +auto write(OutputIt out, monostate, format_specs = {}, locale_ref = {}) + -> OutputIt { + FMT_ASSERT(false, ""); + return out; +} + +template +FMT_CONSTEXPR auto write(OutputIt out, basic_string_view value) + -> OutputIt { + auto it = reserve(out, value.size()); + it = copy_str_noinline(value.begin(), value.end(), it); + return base_iterator(out, it); +} + +template ::value)> +constexpr auto write(OutputIt out, const T& value) -> OutputIt { + return write(out, to_string_view(value)); +} + +// FMT_ENABLE_IF() condition separated to workaround an MSVC bug. +template < + typename Char, typename OutputIt, typename T, + bool check = + std::is_enum::value && !std::is_same::value && + mapped_type_constant>::value != + type::custom_type, + FMT_ENABLE_IF(check)> +FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt { + return write(out, static_cast>(value)); +} + +template ::value)> +FMT_CONSTEXPR auto write(OutputIt out, T value, + const format_specs& specs = {}, locale_ref = {}) + -> OutputIt { + return specs.type != presentation_type::none && + specs.type != presentation_type::string + ? write(out, value ? 1 : 0, specs, {}) + : write_bytes(out, value ? "true" : "false", specs); +} + +template +FMT_CONSTEXPR auto write(OutputIt out, Char value) -> OutputIt { + auto it = reserve(out, 1); + *it++ = value; + return base_iterator(out, it); +} + +template +FMT_CONSTEXPR_CHAR_TRAITS auto write(OutputIt out, const Char* value) + -> OutputIt { + if (value) return write(out, basic_string_view(value)); + throw_format_error("string pointer is null"); + return out; +} + +template ::value)> +auto write(OutputIt out, const T* value, const format_specs& specs = {}, + locale_ref = {}) -> OutputIt { + return write_ptr(out, bit_cast(value), &specs); +} + +// A write overload that handles implicit conversions. +template > +FMT_CONSTEXPR auto write(OutputIt out, const T& value) -> enable_if_t< + std::is_class::value && !is_string::value && + !is_floating_point::value && !std::is_same::value && + !std::is_same().map( + value))>>::value, + OutputIt> { + return write(out, arg_mapper().map(value)); +} + +template > +FMT_CONSTEXPR auto write(OutputIt out, const T& value) + -> enable_if_t::value == type::custom_type, + OutputIt> { + auto formatter = typename Context::template formatter_type(); + auto parse_ctx = typename Context::parse_context_type({}); + formatter.parse(parse_ctx); + auto ctx = Context(out, {}, {}); + return formatter.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 struct default_arg_formatter { + using iterator = buffer_appender; + using context = buffer_context; + + iterator out; + basic_format_args args; + locale_ref loc; + + template auto operator()(T value) -> iterator { + return write(out, value); + } + auto operator()(typename basic_format_arg::handle h) -> iterator { + basic_format_parse_context parse_ctx({}); + context format_ctx(out, args, loc); + h.format(parse_ctx, format_ctx); + return format_ctx.out(); + } +}; + +template struct arg_formatter { + using iterator = buffer_appender; + using context = buffer_context; + + iterator out; + const format_specs& specs; + locale_ref locale; + + template + FMT_CONSTEXPR FMT_INLINE auto operator()(T value) -> iterator { + return detail::write(out, value, specs, locale); + } + auto operator()(typename basic_format_arg::handle) -> iterator { + // User-defined types are handled separately because they require access + // to the parse context. + return out; + } +}; + +struct width_checker { + template ::value)> + FMT_CONSTEXPR auto operator()(T value) -> unsigned long long { + if (is_negative(value)) throw_format_error("negative width"); + return static_cast(value); + } + + template ::value)> + FMT_CONSTEXPR auto operator()(T) -> unsigned long long { + throw_format_error("width is not integer"); + return 0; + } +}; + +struct precision_checker { + template ::value)> + FMT_CONSTEXPR auto operator()(T value) -> unsigned long long { + if (is_negative(value)) throw_format_error("negative precision"); + return static_cast(value); + } + + template ::value)> + FMT_CONSTEXPR auto operator()(T) -> unsigned long long { + throw_format_error("precision is not integer"); + return 0; + } +}; + +template +FMT_CONSTEXPR auto get_dynamic_spec(FormatArg arg) -> int { + unsigned long long value = visit_format_arg(Handler(), arg); + if (value > to_unsigned(max_value())) + throw_format_error("number is too big"); + return static_cast(value); +} + +template +FMT_CONSTEXPR auto get_arg(Context& ctx, ID id) -> decltype(ctx.arg(id)) { + auto arg = ctx.arg(id); + if (!arg) ctx.on_error("argument not found"); + return arg; +} + +template +FMT_CONSTEXPR void handle_dynamic_spec(int& value, + arg_ref ref, + Context& ctx) { + switch (ref.kind) { + case arg_id_kind::none: + break; + case arg_id_kind::index: + value = detail::get_dynamic_spec(get_arg(ctx, ref.val.index)); + break; + case arg_id_kind::name: + value = detail::get_dynamic_spec(get_arg(ctx, ref.val.name)); + break; + } +} + +#if FMT_USE_USER_DEFINED_LITERALS +# if FMT_USE_NONTYPE_TEMPLATE_ARGS +template Str> +struct statically_named_arg : view { + static constexpr auto name = Str.data; + + const T& value; + statically_named_arg(const T& v) : value(v) {} +}; + +template Str> +struct is_named_arg> : std::true_type {}; + +template Str> +struct is_statically_named_arg> + : std::true_type {}; + +template Str> +struct udl_arg { + template auto operator=(T&& value) const { + return statically_named_arg(std::forward(value)); + } +}; +# else +template struct udl_arg { + const Char* str; + + template auto operator=(T&& value) const -> named_arg { + return {str, std::forward(value)}; + } +}; +# endif +#endif // FMT_USE_USER_DEFINED_LITERALS + +template +auto vformat(const Locale& loc, basic_string_view fmt, + basic_format_args>> args) + -> std::basic_string { + auto buf = basic_memory_buffer(); + detail::vformat_to(buf, fmt, args, detail::locale_ref(loc)); + return {buf.data(), buf.size()}; +} + +using format_func = void (*)(detail::buffer&, int, const char*); + +FMT_API void format_error_code(buffer& out, int error_code, + string_view message) noexcept; + +FMT_API void report_error(format_func func, int error_code, + const char* message) noexcept; +} // namespace detail + +FMT_API auto vsystem_error(int error_code, string_view format_str, + format_args args) -> std::system_error; + +/** + \rst + Constructs :class:`std::system_error` with a message formatted with + ``fmt::format(fmt, args...)``. + *error_code* is a system error code as given by ``errno``. + + **Example**:: + + // This throws std::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 +auto system_error(int error_code, format_string fmt, T&&... args) + -> std::system_error { + return vsystem_error(error_code, fmt, fmt::make_format_args(args...)); +} + +/** + \rst + Formats an error message for an error returned by an operating system or a + language runtime, for example a file opening error, and writes it to *out*. + The format is the same as the one used by ``std::system_error(ec, message)`` + where ``ec`` is ``std::error_code(error_code, std::generic_category()})``. + It is implementation-defined but normally looks like: + + .. parsed-literal:: + **: ** + + where ** is the passed message and ** is the system + message corresponding to the error code. + *error_code* is a system error code as given by ``errno``. + \endrst + */ +FMT_API void format_system_error(detail::buffer& out, int error_code, + const char* message) 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, const char* message) 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::digits10 + 3 }; + mutable char buffer_[buffer_size]; + char* str_; + + template auto format_unsigned(UInt value) -> char* { + auto n = static_cast>(value); + return detail::format_decimal(buffer_, n, buffer_size - 1).begin; + } + + template auto format_signed(Int value) -> char* { + auto abs_value = static_cast>(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. */ + auto size() const -> size_t { + return detail::to_unsigned(buffer_ - str_ + buffer_size - 1); + } + + /** + Returns a pointer to the output buffer content. No terminating null + character is appended. + */ + auto data() const -> const char* { return str_; } + + /** + Returns a pointer to the output buffer content with terminating null + character appended. + */ + auto c_str() const -> const char* { + buffer_[buffer_size - 1] = '\0'; + return str_; + } + + /** + \rst + Returns the content of the output buffer as an ``std::string``. + \endrst + */ + auto str() const -> std::string { return std::string(str_, size()); } +}; + +template +struct formatter::value>> + : formatter, Char> { + template + auto format(const T& value, FormatContext& ctx) const -> decltype(ctx.out()) { + using base = formatter, Char>; + return base::format(format_as(value), ctx); + } +}; + +#define FMT_FORMAT_AS(Type, Base) \ + template \ + struct formatter : formatter {} + +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, detail::long_type); +FMT_FORMAT_AS(unsigned long, detail::ulong_type); +FMT_FORMAT_AS(Char*, const Char*); +FMT_FORMAT_AS(std::basic_string, basic_string_view); +FMT_FORMAT_AS(std::nullptr_t, const void*); +FMT_FORMAT_AS(detail::std_string_view, basic_string_view); +FMT_FORMAT_AS(void*, const void*); + +template +struct formatter : formatter, Char> {}; + +/** + \rst + Converts ``p`` to ``const void*`` for pointer formatting. + + **Example**:: + + auto s = fmt::format("{}", fmt::ptr(p)); + \endrst + */ +template auto ptr(T p) -> const void* { + static_assert(std::is_pointer::value, ""); + return detail::bit_cast(p); +} +template +auto ptr(const std::unique_ptr& p) -> const void* { + return p.get(); +} +template auto ptr(const std::shared_ptr& p) -> const void* { + return p.get(); +} + +/** + \rst + Converts ``e`` to the underlying type. + + **Example**:: + + enum class color { red, green, blue }; + auto s = fmt::format("{}", fmt::underlying(color::red)); + \endrst + */ +template +constexpr auto underlying(Enum e) noexcept -> underlying_t { + return static_cast>(e); +} + +namespace enums { +template ::value)> +constexpr auto format_as(Enum e) noexcept -> underlying_t { + return static_cast>(e); +} +} // namespace enums + +class bytes { + private: + string_view data_; + friend struct formatter; + + public: + explicit bytes(string_view data) : data_(data) {} +}; + +template <> struct formatter { + private: + detail::dynamic_format_specs<> specs_; + + public: + template + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> const char* { + return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, + detail::type::string_type); + } + + template + auto format(bytes b, FormatContext& ctx) -> decltype(ctx.out()) { + detail::handle_dynamic_spec(specs_.width, + specs_.width_ref, ctx); + detail::handle_dynamic_spec( + specs_.precision, specs_.precision_ref, ctx); + return detail::write_bytes(ctx.out(), b.data_, specs_); + } +}; + +// group_digits_view is not derived from view because it copies the argument. +template struct group_digits_view { + T value; +}; + +/** + \rst + Returns a view that formats an integer value using ',' as a locale-independent + thousands separator. + + **Example**:: + + fmt::print("{}", fmt::group_digits(12345)); + // Output: "12,345" + \endrst + */ +template auto group_digits(T value) -> group_digits_view { + return {value}; +} + +template struct formatter> : formatter { + private: + detail::dynamic_format_specs<> specs_; + + public: + template + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> const char* { + return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, + detail::type::int_type); + } + + template + auto format(group_digits_view t, FormatContext& ctx) + -> decltype(ctx.out()) { + detail::handle_dynamic_spec(specs_.width, + specs_.width_ref, ctx); + detail::handle_dynamic_spec( + specs_.precision, specs_.precision_ref, ctx); + return detail::write_int( + ctx.out(), static_cast>(t.value), 0, specs_, + detail::digit_grouping("\3", ",")); + } +}; + +template struct nested_view { + const formatter* fmt; + const T* value; +}; + +template struct formatter> { + FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> const char* { + return ctx.begin(); + } + auto format(nested_view view, format_context& ctx) const + -> decltype(ctx.out()) { + return view.fmt->format(*view.value, ctx); + } +}; + +template struct nested_formatter { + private: + int width_; + detail::fill_t fill_; + align_t align_ : 4; + formatter formatter_; + + public: + constexpr nested_formatter() : width_(0), align_(align_t::none) {} + + FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> const char* { + auto specs = detail::dynamic_format_specs(); + auto it = parse_format_specs(ctx.begin(), ctx.end(), specs, ctx, + detail::type::none_type); + width_ = specs.width; + fill_ = specs.fill; + align_ = specs.align; + ctx.advance_to(it); + return formatter_.parse(ctx); + } + + template + auto write_padded(format_context& ctx, F write) const -> decltype(ctx.out()) { + if (width_ == 0) return write(ctx.out()); + auto buf = memory_buffer(); + write(std::back_inserter(buf)); + auto specs = format_specs<>(); + specs.width = width_; + specs.fill = fill_; + specs.align = align_; + return detail::write(ctx.out(), string_view(buf.data(), buf.size()), specs); + } + + auto nested(const T& value) const -> nested_view { + return nested_view{&formatter_, &value}; + } +}; + +// DEPRECATED! join_view will be moved to ranges.h. +template +struct join_view : detail::view { + It begin; + Sentinel end; + basic_string_view sep; + + join_view(It b, Sentinel e, basic_string_view s) + : begin(b), end(e), sep(s) {} +}; + +template +struct formatter, Char> { + private: + using value_type = +#ifdef __cpp_lib_ranges + std::iter_value_t; +#else + typename std::iterator_traits::value_type; +#endif + formatter, Char> value_formatter_; + + public: + template + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> const Char* { + return value_formatter_.parse(ctx); + } + + template + auto format(const join_view& value, + FormatContext& ctx) const -> decltype(ctx.out()) { + auto it = value.begin; + auto out = ctx.out(); + if (it != value.end) { + out = value_formatter_.format(*it, ctx); + ++it; + while (it != value.end) { + out = detail::copy_str(value.sep.begin(), value.sep.end(), out); + ctx.advance_to(out); + out = value_formatter_.format(*it, ctx); + ++it; + } + } + return out; + } +}; + +/** + Returns a view that formats the iterator range `[begin, end)` with elements + separated by `sep`. + */ +template +auto join(It begin, Sentinel end, string_view sep) -> join_view { + return {begin, end, sep}; +} + +/** + \rst + Returns a view that formats `range` with elements separated by `sep`. + + **Example**:: + + std::vector 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 +auto join(Range&& range, string_view sep) + -> join_view, detail::sentinel_t> { + return join(std::begin(range), std::end(range), sep); +} + +/** + \rst + Converts *value* to ``std::string`` using the default format for type *T*. + + **Example**:: + + #include + + std::string answer = fmt::to_string(42); + \endrst + */ +template ::value && + !detail::has_format_as::value)> +inline auto to_string(const T& value) -> std::string { + auto buffer = memory_buffer(); + detail::write(appender(buffer), value); + return {buffer.data(), buffer.size()}; +} + +template ::value)> +FMT_NODISCARD inline auto to_string(T value) -> std::string { + // The buffer should be large enough to store the number including the sign + // or "false" for bool. + constexpr int max_size = detail::digits10() + 2; + char buffer[max_size > 5 ? static_cast(max_size) : 5]; + char* begin = buffer; + return std::string(begin, detail::write(begin, value)); +} + +template +FMT_NODISCARD auto to_string(const basic_memory_buffer& buf) + -> std::basic_string { + auto size = buf.size(); + detail::assume(size < std::basic_string().max_size()); + return std::basic_string(buf.data(), size); +} + +template ::value && + detail::has_format_as::value)> +inline auto to_string(const T& value) -> std::string { + return to_string(format_as(value)); +} + +FMT_END_EXPORT + +namespace detail { + +template +void vformat_to(buffer& buf, basic_string_view fmt, + typename vformat_args::type args, locale_ref loc) { + auto out = buffer_appender(buf); + if (fmt.size() == 2 && equal2(fmt.data(), "{}")) { + auto arg = args.get(0); + if (!arg) throw_format_error("argument not found"); + visit_format_arg(default_arg_formatter{out, args, loc}, arg); + return; + } + + struct format_handler : error_handler { + basic_format_parse_context parse_context; + buffer_context context; + + format_handler(buffer_appender p_out, basic_string_view str, + basic_format_args> p_args, + locale_ref p_loc) + : parse_context(str), context(p_out, p_args, p_loc) {} + + void on_text(const Char* begin, const Char* end) { + auto text = basic_string_view(begin, to_unsigned(end - begin)); + context.advance_to(write(context.out(), text)); + } + + FMT_CONSTEXPR auto on_arg_id() -> int { + return parse_context.next_arg_id(); + } + FMT_CONSTEXPR auto on_arg_id(int id) -> int { + return parse_context.check_arg_id(id), id; + } + FMT_CONSTEXPR auto on_arg_id(basic_string_view id) -> int { + int arg_id = context.arg_id(id); + if (arg_id < 0) throw_format_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{context.out(), context.args(), + context.locale()}, + arg)); + } + + auto on_format_specs(int id, const Char* begin, const Char* end) + -> const Char* { + auto arg = get_arg(context, id); + // Not using a visitor for custom types gives better codegen. + if (arg.format_custom(begin, parse_context, context)) + return parse_context.begin(); + auto specs = detail::dynamic_format_specs(); + begin = parse_format_specs(begin, end, specs, parse_context, arg.type()); + detail::handle_dynamic_spec( + specs.width, specs.width_ref, context); + detail::handle_dynamic_spec( + specs.precision, specs.precision_ref, context); + if (begin == end || *begin != '}') + throw_format_error("missing '}' in format string"); + auto f = arg_formatter{context.out(), specs, context.locale()}; + context.advance_to(visit_format_arg(f, arg)); + return begin; + } + }; + detail::parse_format_string(fmt, format_handler(out, fmt, args, loc)); +} + +FMT_BEGIN_EXPORT + +#ifndef FMT_HEADER_ONLY +extern template FMT_API void vformat_to(buffer&, string_view, + typename vformat_args<>::type, + locale_ref); +extern template FMT_API auto thousands_sep_impl(locale_ref) + -> thousands_sep_result; +extern template FMT_API auto thousands_sep_impl(locale_ref) + -> thousands_sep_result; +extern template FMT_API auto decimal_point_impl(locale_ref) -> char; +extern template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t; +#endif // FMT_HEADER_ONLY + +} // namespace detail + +#if FMT_USE_USER_DEFINED_LITERALS +inline namespace literals { +/** + \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 + */ +# if FMT_USE_NONTYPE_TEMPLATE_ARGS +template constexpr auto operator""_a() { + using char_t = remove_cvref_t; + return detail::udl_arg(); +} +# else +constexpr auto operator""_a(const char* s, size_t) -> detail::udl_arg { + return {s}; +} +# endif +} // namespace literals +#endif // FMT_USE_USER_DEFINED_LITERALS + +template ::value)> +inline auto vformat(const Locale& loc, string_view fmt, format_args args) + -> std::string { + return detail::vformat(loc, fmt, args); +} + +template ::value)> +inline auto format(const Locale& loc, format_string fmt, T&&... args) + -> std::string { + return fmt::vformat(loc, string_view(fmt), fmt::make_format_args(args...)); +} + +template ::value&& + detail::is_locale::value)> +auto vformat_to(OutputIt out, const Locale& loc, string_view fmt, + format_args args) -> OutputIt { + using detail::get_buffer; + auto&& buf = get_buffer(out); + detail::vformat_to(buf, fmt, args, detail::locale_ref(loc)); + return detail::get_iterator(buf, out); +} + +template ::value&& + detail::is_locale::value)> +FMT_INLINE auto format_to(OutputIt out, const Locale& loc, + format_string fmt, T&&... args) -> OutputIt { + return vformat_to(out, loc, fmt, fmt::make_format_args(args...)); +} + +template ::value)> +FMT_NODISCARD FMT_INLINE auto formatted_size(const Locale& loc, + format_string fmt, + T&&... args) -> size_t { + auto buf = detail::counting_buffer<>(); + detail::vformat_to(buf, fmt, fmt::make_format_args(args...), + detail::locale_ref(loc)); + return buf.count(); +} + +FMT_END_EXPORT + +template +template +FMT_CONSTEXPR FMT_INLINE auto +formatter::value != + detail::type::custom_type>>::format(const T& val, + FormatContext& ctx) + const -> decltype(ctx.out()) { + if (specs_.width_ref.kind == detail::arg_id_kind::none && + specs_.precision_ref.kind == detail::arg_id_kind::none) { + return detail::write(ctx.out(), val, specs_, ctx.locale()); + } + auto specs = specs_; + detail::handle_dynamic_spec(specs.width, + specs.width_ref, ctx); + detail::handle_dynamic_spec( + specs.precision, specs.precision_ref, ctx); + return detail::write(ctx.out(), val, specs, ctx.locale()); +} + +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/third_party/fmt/include/fmt/os.h b/third_party/fmt/include/fmt/os.h new file mode 100644 index 0000000..3c7b3cc --- /dev/null +++ b/third_party/fmt/include/fmt/os.h @@ -0,0 +1,455 @@ +// 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_ + +#include +#include +#include +#include // std::system_error + +#include "format.h" + +#if defined __APPLE__ || defined(__FreeBSD__) +# if FMT_HAS_INCLUDE() +# include // for LC_NUMERIC_MASK on OS X +# endif +#endif + +#ifndef FMT_USE_FCNTL +// UWP doesn't provide _pipe. +# if FMT_HAS_INCLUDE("winapifamily.h") +# include +# endif +# if (FMT_HAS_INCLUDE() || defined(__APPLE__) || \ + defined(__linux__)) && \ + (!defined(WINAPI_FAMILY) || \ + (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)) +# include // for O_RDONLY +# define FMT_USE_FCNTL 1 +# else +# define FMT_USE_FCNTL 0 +# endif +#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_HAS_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 +FMT_BEGIN_EXPORT + +/** + \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 | + +---------------+-----------------------------+ + | wcstring_view | basic_cstring_view | + +---------------+-----------------------------+ + + This class is most useful as a parameter type to allow passing + different types of strings to a function, for example:: + + template + std::string format(cstring_view format_str, const Args & ... args); + + format("{}", 42); + format(std::string("{}"), 42); + \endrst + */ +template 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& s) : data_(s.c_str()) {} + + /** Returns the pointer to a C string. */ + auto c_str() const -> const Char* { return data_; } +}; + +using cstring_view = basic_cstring_view; +using wcstring_view = basic_cstring_view; + +#ifdef _WIN32 +FMT_API const std::error_category& system_category() noexcept; + +namespace detail { +FMT_API void format_windows_error(buffer& out, int error_code, + const char* message) noexcept; +} + +FMT_API std::system_error vwindows_error(int error_code, string_view format_str, + format_args args); + +/** + \rst + Constructs a :class:`std::system_error` object with the description + of the form + + .. parsed-literal:: + **: ** + + where ** is the formatted message and ** 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 system_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 +std::system_error windows_error(int error_code, string_view message, + const Args&... args) { + return vwindows_error(error_code, message, fmt::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, const char* message) noexcept; +#else +inline auto system_category() noexcept -> const std::error_category& { + return std::system_category(); +} +#endif // _WIN32 + +// std::system is not available on some platforms such as iOS (#2248). +#ifdef __OSX__ +template > +void say(const S& format_str, Args&&... args) { + std::system(format("say \"{}\"", format(format_str, args...)).c_str()); +} +#endif + +// 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() noexcept : file_(nullptr) {} + + // Destroys the object closing the file it represents if any. + FMT_API ~buffered_file() noexcept; + + public: + buffered_file(buffered_file&& other) noexcept : file_(other.file_) { + other.file_ = nullptr; + } + + auto operator=(buffered_file&& other) -> buffered_file& { + 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. + auto get() const noexcept -> FILE* { return file_; } + + FMT_API auto descriptor() const -> int; + + void vprint(string_view format_str, format_args args) { + fmt::vprint(file_, format_str, args); + } + + template + inline void print(string_view format_str, const Args&... args) { + vprint(format_str, fmt::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 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 FMT_API 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. + TRUNC = FMT_POSIX(O_TRUNC) // Truncate the content of the file. + }; + + // Constructs a file object which doesn't represent any file. + file() noexcept : fd_(-1) {} + + // Opens a file and constructs a file object representing this file. + file(cstring_view path, int oflag); + + public: + file(const file&) = delete; + void operator=(const file&) = delete; + + file(file&& other) noexcept : fd_(other.fd_) { other.fd_ = -1; } + + // Move assignment is not noexcept because close may throw. + auto operator=(file&& other) -> file& { + close(); + fd_ = other.fd_; + other.fd_ = -1; + return *this; + } + + // Destroys the object closing the file it represents if any. + ~file() noexcept; + + // Returns the file descriptor. + auto descriptor() const noexcept -> int { return fd_; } + + // Closes the file. + void close(); + + // Returns the file size. The size has signed type for consistency with + // stat::st_size. + auto size() const -> long long; + + // Attempts to read count bytes from the file into the specified buffer. + auto read(void* buffer, size_t count) -> size_t; + + // Attempts to write count bytes from the specified buffer to the file. + auto write(const void* buffer, size_t count) -> size_t; + + // Duplicates a file descriptor with the dup function and returns + // the duplicate as a file object. + static auto dup(int fd) -> file; + + // Makes fd be the copy of this file descriptor, closing fd first if + // necessary. + void dup2(int fd); + + // Makes fd be the copy of this file descriptor, closing fd first if + // necessary. + void dup2(int fd, std::error_code& ec) noexcept; + + // Creates a pipe setting up read_end and write_end file objects for reading + // and writing respectively. + // DEPRECATED! Taking files as out parameters is deprecated. + 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. + auto fdopen(const char* mode) -> buffered_file; + +# if defined(_WIN32) && !defined(__MINGW32__) + // Opens a file and constructs a file object representing this file by + // wcstring_view filename. Windows only. + static file open_windows_file(wcstring_view path, int oflag); +# endif +}; + +// Returns the memory page size. +auto getpagesize() -> long; + +namespace detail { + +struct buffer_size { + buffer_size() = default; + size_t value = 0; + auto operator=(size_t val) const -> buffer_size { + auto bs = buffer_size(); + bs.value = val; + return bs; + } +}; + +struct ostream_params { + int oflag = file::WRONLY | file::CREATE | file::TRUNC; + size_t buffer_size = BUFSIZ > 32768 ? BUFSIZ : 32768; + + ostream_params() {} + + template + ostream_params(T... params, int new_oflag) : ostream_params(params...) { + oflag = new_oflag; + } + + template + ostream_params(T... params, detail::buffer_size bs) + : ostream_params(params...) { + this->buffer_size = bs.value; + } + +// Intel has a bug that results in failure to deduce a constructor +// for empty parameter packs. +# if defined(__INTEL_COMPILER) && __INTEL_COMPILER < 2000 + ostream_params(int new_oflag) : oflag(new_oflag) {} + ostream_params(detail::buffer_size bs) : buffer_size(bs.value) {} +# endif +}; + +class file_buffer final : public buffer { + file file_; + + FMT_API void grow(size_t) override; + + public: + FMT_API file_buffer(cstring_view path, const ostream_params& params); + FMT_API file_buffer(file_buffer&& other); + FMT_API ~file_buffer(); + + void flush() { + if (size() == 0) return; + file_.write(data(), size() * sizeof(data()[0])); + clear(); + } + + void close() { + flush(); + file_.close(); + } +}; + +} // namespace detail + +// Added {} below to work around default constructor error known to +// occur in Xcode versions 7.2.1 and 8.2.1. +constexpr detail::buffer_size buffer_size{}; + +/** A fast output stream which is not thread-safe. */ +class FMT_API ostream { + private: + FMT_MSC_WARNING(suppress : 4251) + detail::file_buffer buffer_; + + ostream(cstring_view path, const detail::ostream_params& params) + : buffer_(path, params) {} + + public: + ostream(ostream&& other) : buffer_(std::move(other.buffer_)) {} + + ~ostream(); + + void flush() { buffer_.flush(); } + + template + friend auto output_file(cstring_view path, T... params) -> ostream; + + void close() { buffer_.close(); } + + /** + Formats ``args`` according to specifications in ``fmt`` and writes the + output to the file. + */ + template void print(format_string fmt, T&&... args) { + vformat_to(std::back_inserter(buffer_), fmt, + fmt::make_format_args(args...)); + } +}; + +/** + \rst + Opens a file for writing. Supported parameters passed in *params*: + + * ````: Flags passed to `open + `_ + (``file::WRONLY | file::CREATE | file::TRUNC`` by default) + * ``buffer_size=``: Output buffer size + + **Example**:: + + auto out = fmt::output_file("guide.txt"); + out.print("Don't {}", "Panic"); + \endrst + */ +template +inline auto output_file(cstring_view path, T... params) -> ostream { + return {path, detail::ostream_params(params...)}; +} +#endif // FMT_USE_FCNTL + +FMT_END_EXPORT +FMT_END_NAMESPACE + +#endif // FMT_OS_H_ diff --git a/third_party/fmt/include/fmt/ostream.h b/third_party/fmt/include/fmt/ostream.h new file mode 100644 index 0000000..26fb3b5 --- /dev/null +++ b/third_party/fmt/include/fmt/ostream.h @@ -0,0 +1,245 @@ +// 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 // std::filebuf + +#ifdef _WIN32 +# ifdef __GLIBCXX__ +# include +# include +# endif +# include +#endif + +#include "format.h" + +FMT_BEGIN_NAMESPACE +namespace detail { + +template class formatbuf : public Streambuf { + private: + using char_type = typename Streambuf::char_type; + using streamsize = decltype(std::declval().sputn(nullptr, 0)); + using int_type = typename Streambuf::int_type; + using traits_type = typename Streambuf::traits_type; + + buffer& buffer_; + + public: + explicit formatbuf(buffer& buf) : buffer_(buf) {} + + protected: + // The put area is 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. A 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. + + auto overflow(int_type ch) -> int_type override { + if (!traits_type::eq_int_type(ch, traits_type::eof())) + buffer_.push_back(static_cast(ch)); + return ch; + } + + auto xsputn(const char_type* s, streamsize count) -> streamsize override { + buffer_.append(s, s + count); + return count; + } +}; + +// Generate a unique explicit instantion in every translation unit using a tag +// type in an anonymous namespace. +namespace { +struct file_access_tag {}; +} // namespace +template +class file_access { + friend auto get_file(BufType& obj) -> FILE* { return obj.*FileMemberPtr; } +}; + +#if FMT_MSC_VERSION +template class file_access; +auto get_file(std::filebuf&) -> FILE*; +#endif + +inline auto write_ostream_unicode(std::ostream& os, fmt::string_view data) + -> bool { + FILE* f = nullptr; +#if FMT_MSC_VERSION + if (auto* buf = dynamic_cast(os.rdbuf())) + f = get_file(*buf); + else + return false; +#elif defined(_WIN32) && defined(__GLIBCXX__) + auto* rdbuf = os.rdbuf(); + if (auto* sfbuf = dynamic_cast<__gnu_cxx::stdio_sync_filebuf*>(rdbuf)) + f = sfbuf->file(); + else if (auto* fbuf = dynamic_cast<__gnu_cxx::stdio_filebuf*>(rdbuf)) + f = fbuf->file(); + else + return false; +#else + ignore_unused(os, data, f); +#endif +#ifdef _WIN32 + if (f) { + int fd = _fileno(f); + if (_isatty(fd)) { + os.flush(); + return write_console(fd, data); + } + } +#endif + return false; +} +inline auto write_ostream_unicode(std::wostream&, + fmt::basic_string_view) -> bool { + return false; +} + +// Write the content of buf to os. +// It is a separate function rather than a part of vprint to simplify testing. +template +void write_buffer(std::basic_ostream& os, buffer& buf) { + const Char* buf_data = buf.data(); + using unsigned_streamsize = std::make_unsigned::type; + unsigned_streamsize size = buf.size(); + unsigned_streamsize max_size = to_unsigned(max_value()); + do { + unsigned_streamsize n = size <= max_size ? size : max_size; + os.write(buf_data, static_cast(n)); + buf_data += n; + size -= n; + } while (size != 0); +} + +template +void format_value(buffer& buf, const T& value) { + auto&& format_buf = formatbuf>(buf); + auto&& output = std::basic_ostream(&format_buf); +#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) + output.imbue(std::locale::classic()); // The default is always unlocalized. +#endif + output << value; + output.exceptions(std::ios_base::failbit | std::ios_base::badbit); +} + +template struct streamed_view { + const T& value; +}; + +} // namespace detail + +// Formats an object of type T that has an overloaded ostream operator<<. +template +struct basic_ostream_formatter : formatter, Char> { + void set_debug_format() = delete; + + template + auto format(const T& value, basic_format_context& ctx) const + -> OutputIt { + auto buffer = basic_memory_buffer(); + detail::format_value(buffer, value); + return formatter, Char>::format( + {buffer.data(), buffer.size()}, ctx); + } +}; + +using ostream_formatter = basic_ostream_formatter; + +template +struct formatter, Char> + : basic_ostream_formatter { + template + auto format(detail::streamed_view view, + basic_format_context& ctx) const -> OutputIt { + return basic_ostream_formatter::format(view.value, ctx); + } +}; + +/** + \rst + Returns a view that formats `value` via an ostream ``operator<<``. + + **Example**:: + + fmt::print("Current thread id: {}\n", + fmt::streamed(std::this_thread::get_id())); + \endrst + */ +template +constexpr auto streamed(const T& value) -> detail::streamed_view { + return {value}; +} + +namespace detail { + +inline void vprint_directly(std::ostream& os, string_view format_str, + format_args args) { + auto buffer = memory_buffer(); + detail::vformat_to(buffer, format_str, args); + detail::write_buffer(os, buffer); +} + +} // namespace detail + +FMT_EXPORT template +void vprint(std::basic_ostream& os, + basic_string_view> format_str, + basic_format_args>> args) { + auto buffer = basic_memory_buffer(); + detail::vformat_to(buffer, format_str, args); + if (detail::write_ostream_unicode(os, {buffer.data(), buffer.size()})) return; + detail::write_buffer(os, buffer); +} + +/** + \rst + Prints formatted data to the stream *os*. + + **Example**:: + + fmt::print(cerr, "Don't {}!", "panic"); + \endrst + */ +FMT_EXPORT template +void print(std::ostream& os, format_string fmt, T&&... args) { + const auto& vargs = fmt::make_format_args(args...); + if (detail::is_utf8()) + vprint(os, fmt, vargs); + else + detail::vprint_directly(os, fmt, vargs); +} + +FMT_EXPORT +template +void print(std::wostream& os, + basic_format_string...> fmt, + Args&&... args) { + vprint(os, fmt, fmt::make_format_args>(args...)); +} + +FMT_EXPORT template +void println(std::ostream& os, format_string fmt, T&&... args) { + fmt::print(os, "{}\n", fmt::format(fmt, std::forward(args)...)); +} + +FMT_EXPORT +template +void println(std::wostream& os, + basic_format_string...> fmt, + Args&&... args) { + print(os, L"{}\n", fmt::format(fmt, std::forward(args)...)); +} + +FMT_END_NAMESPACE + +#endif // FMT_OSTREAM_H_ diff --git a/third_party/fmt/include/fmt/printf.h b/third_party/fmt/include/fmt/printf.h new file mode 100644 index 0000000..07e8157 --- /dev/null +++ b/third_party/fmt/include/fmt/printf.h @@ -0,0 +1,675 @@ +// 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 // std::max +#include // std::numeric_limits + +#include "format.h" + +FMT_BEGIN_NAMESPACE +FMT_BEGIN_EXPORT + +template struct printf_formatter { + printf_formatter() = delete; +}; + +template class basic_printf_context { + private: + detail::buffer_appender out_; + basic_format_args args_; + + static_assert(std::is_same::value || + std::is_same::value, + "Unsupported code unit type."); + + public: + using char_type = Char; + using parse_context_type = basic_format_parse_context; + template using formatter_type = printf_formatter; + + /** + \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(detail::buffer_appender out, + basic_format_args args) + : out_(out), args_(args) {} + + auto out() -> detail::buffer_appender { return out_; } + void advance_to(detail::buffer_appender) {} + + auto locale() -> detail::locale_ref { return {}; } + + auto arg(int id) const -> basic_format_arg { + return args_.get(id); + } + + FMT_CONSTEXPR void on_error(const char* message) { + detail::error_handler().on_error(message); + } +}; + +namespace detail { + +// Checks if a value fits in int - used to avoid warnings about comparing +// signed and unsigned integers. +template struct int_checker { + template static auto fits_in_int(T value) -> bool { + unsigned max = max_value(); + return value <= max; + } + static auto fits_in_int(bool) -> bool { return true; } +}; + +template <> struct int_checker { + template static auto fits_in_int(T value) -> bool { + return value >= (std::numeric_limits::min)() && + value <= max_value(); + } + static auto fits_in_int(int) -> bool { return true; } +}; + +struct printf_precision_handler { + template ::value)> + auto operator()(T value) -> int { + if (!int_checker::is_signed>::fits_in_int(value)) + throw_format_error("number is too big"); + return (std::max)(static_cast(value), 0); + } + + template ::value)> + auto operator()(T) -> int { + throw_format_error("precision is not integer"); + return 0; + } +}; + +// An argument visitor that returns true iff arg is a zero integer. +struct is_zero_int { + template ::value)> + auto operator()(T value) -> bool { + return value == 0; + } + + template ::value)> + auto operator()(T) -> bool { + return false; + } +}; + +template struct make_unsigned_or_bool : std::make_unsigned {}; + +template <> struct make_unsigned_or_bool { + using type = bool; +}; + +template class arg_converter { + private: + using char_type = typename Context::char_type; + + basic_format_arg& arg_; + char_type type_; + + public: + arg_converter(basic_format_arg& arg, char_type type) + : arg_(arg), type_(type) {} + + void operator()(bool value) { + if (type_ != 's') operator()(value); + } + + template ::value)> + void operator()(U value) { + bool is_signed = type_ == 'd' || type_ == 'i'; + using target_type = conditional_t::value, U, T>; + if (const_check(sizeof(target_type) <= sizeof(int))) { + // Extra casts are used to silence warnings. + if (is_signed) { + auto n = static_cast(static_cast(value)); + arg_ = detail::make_arg(n); + } else { + using unsigned_type = typename make_unsigned_or_bool::type; + auto n = static_cast(static_cast(value)); + arg_ = detail::make_arg(n); + } + } 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. + auto n = static_cast(value); + arg_ = detail::make_arg(n); + } else { + auto n = static_cast::type>(value); + arg_ = detail::make_arg(n); + } + } + } + + template ::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 +void convert_arg(basic_format_arg& arg, Char type) { + visit_format_arg(arg_converter(arg, type), arg); +} + +// Converts an integer argument to char for printf. +template class char_converter { + private: + basic_format_arg& arg_; + + public: + explicit char_converter(basic_format_arg& arg) : arg_(arg) {} + + template ::value)> + void operator()(T value) { + auto c = static_cast(value); + arg_ = detail::make_arg(c); + } + + template ::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 struct get_cstring { + template auto operator()(T) -> const Char* { return nullptr; } + auto operator()(const Char* s) -> const Char* { return s; } +}; + +// Checks if an argument is a valid printf width specifier and sets +// left alignment if it is negative. +template class printf_width_handler { + private: + format_specs& specs_; + + public: + explicit printf_width_handler(format_specs& specs) : specs_(specs) {} + + template ::value)> + auto operator()(T value) -> unsigned { + auto width = static_cast>(value); + if (detail::is_negative(value)) { + specs_.align = align::left; + width = 0 - width; + } + unsigned int_max = max_value(); + if (width > int_max) throw_format_error("number is too big"); + return static_cast(width); + } + + template ::value)> + auto operator()(T) -> unsigned { + throw_format_error("width is not integer"); + return 0; + } +}; + +// Workaround for a bug with the XL compiler when initializing +// printf_arg_formatter's base class. +template +auto make_arg_formatter(buffer_appender iter, format_specs& s) + -> arg_formatter { + return {iter, s, locale_ref()}; +} + +// The ``printf`` argument formatter. +template +class printf_arg_formatter : public arg_formatter { + private: + using base = arg_formatter; + using context_type = basic_printf_context; + + context_type& context_; + + void write_null_pointer(bool is_string = false) { + auto s = this->specs; + s.type = presentation_type::none; + write_bytes(this->out, is_string ? "(null)" : "(nil)", s); + } + + public: + printf_arg_formatter(buffer_appender iter, format_specs& s, + context_type& ctx) + : base(make_arg_formatter(iter, s)), context_(ctx) {} + + void operator()(monostate value) { base::operator()(value); } + + template ::value)> + void operator()(T value) { + // MSVC2013 fails to compile separate overloads for bool and Char so use + // std::is_same instead. + if (!std::is_same::value) { + base::operator()(value); + return; + } + format_specs fmt_specs = this->specs; + if (fmt_specs.type != presentation_type::none && + fmt_specs.type != presentation_type::chr) { + return (*this)(static_cast(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; + write(this->out, static_cast(value), fmt_specs); + } + + template ::value)> + void operator()(T value) { + base::operator()(value); + } + + /** Formats a null-terminated C string. */ + void operator()(const char* value) { + if (value) + base::operator()(value); + else + write_null_pointer(this->specs.type != presentation_type::pointer); + } + + /** Formats a null-terminated wide C string. */ + void operator()(const wchar_t* value) { + if (value) + base::operator()(value); + else + write_null_pointer(this->specs.type != presentation_type::pointer); + } + + void operator()(basic_string_view value) { base::operator()(value); } + + /** Formats a pointer. */ + void operator()(const void* value) { + if (value) + base::operator()(value); + else + write_null_pointer(); + } + + /** Formats an argument of a custom (user-defined) type. */ + void operator()(typename basic_format_arg::handle handle) { + auto parse_ctx = basic_format_parse_context({}); + handle.format(parse_ctx, context_); + } +}; + +template +void 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 +auto parse_header(const Char*& it, const Char* end, format_specs& specs, + GetArg get_arg) -> int { + int arg_index = -1; + Char c = *it; + if (c >= '0' && c <= '9') { + // Parse an argument index (if followed by '$') or a width possibly + // preceded with '0' flag(s). + int value = parse_nonnegative_int(it, end, -1); + if (it != end && *it == '$') { // value is an argument index + ++it; + arg_index = value != -1 ? value : max_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. + if (value == -1) throw_format_error("number is too big"); + specs.width = value; + return arg_index; + } + } + } + parse_flags(specs, it, end); + // Parse width. + if (it != end) { + if (*it >= '0' && *it <= '9') { + specs.width = parse_nonnegative_int(it, end, -1); + if (specs.width == -1) throw_format_error("number is too big"); + } else if (*it == '*') { + ++it; + specs.width = static_cast(visit_format_arg( + detail::printf_width_handler(specs), get_arg(-1))); + } + } + return arg_index; +} + +inline auto parse_printf_presentation_type(char c, type t) + -> presentation_type { + using pt = presentation_type; + constexpr auto integral_set = sint_set | uint_set | bool_set | char_set; + switch (c) { + case 'd': + return in(t, integral_set) ? pt::dec : pt::none; + case 'o': + return in(t, integral_set) ? pt::oct : pt::none; + case 'x': + return in(t, integral_set) ? pt::hex_lower : pt::none; + case 'X': + return in(t, integral_set) ? pt::hex_upper : pt::none; + case 'a': + return in(t, float_set) ? pt::hexfloat_lower : pt::none; + case 'A': + return in(t, float_set) ? pt::hexfloat_upper : pt::none; + case 'e': + return in(t, float_set) ? pt::exp_lower : pt::none; + case 'E': + return in(t, float_set) ? pt::exp_upper : pt::none; + case 'f': + return in(t, float_set) ? pt::fixed_lower : pt::none; + case 'F': + return in(t, float_set) ? pt::fixed_upper : pt::none; + case 'g': + return in(t, float_set) ? pt::general_lower : pt::none; + case 'G': + return in(t, float_set) ? pt::general_upper : pt::none; + case 'c': + return in(t, integral_set) ? pt::chr : pt::none; + case 's': + return in(t, string_set | cstring_set) ? pt::string : pt::none; + case 'p': + return in(t, pointer_set | cstring_set) ? pt::pointer : pt::none; + default: + return pt::none; + } +} + +template +void vprintf(buffer& buf, basic_string_view format, + basic_format_args args) { + using iterator = buffer_appender; + auto out = iterator(buf); + auto context = basic_printf_context(out, args); + auto parse_ctx = basic_format_parse_context(format); + + // Returns the argument with specified index or, if arg_index is -1, the next + // argument. + auto 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(context, arg_index); + }; + + const Char* start = parse_ctx.begin(); + const Char* end = parse_ctx.end(); + auto it = start; + while (it != end) { + if (!find(it, end, '%', it)) { + it = end; // find leaves it == nullptr if it doesn't find '%'. + break; + } + Char c = *it++; + if (it != end && *it == c) { + write(out, basic_string_view(start, to_unsigned(it - start))); + start = ++it; + continue; + } + write(out, basic_string_view(start, to_unsigned(it - 1 - start))); + + auto specs = format_specs(); + specs.align = align::right; + + // Parse argument index, flags and width. + int arg_index = parse_header(it, end, specs, get_arg); + if (arg_index == 0) throw_format_error("argument not found"); + + // Parse precision. + if (it != end && *it == '.') { + ++it; + c = it != end ? *it : 0; + if ('0' <= c && c <= '9') { + specs.precision = parse_nonnegative_int(it, end, 0); + } else if (c == '*') { + ++it; + specs.precision = static_cast( + visit_format_arg(printf_precision_handler(), get_arg(-1))); + } else { + specs.precision = 0; + } + } + + auto 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()) { + // Ignore '0' for non-numeric types or if '-' present. + specs.fill[0] = ' '; + } + if (specs.precision >= 0 && arg.type() == type::cstring_type) { + auto str = visit_format_arg(get_cstring(), arg); + auto str_end = str + specs.precision; + auto nul = std::find(str, str_end, Char()); + auto sv = basic_string_view( + str, to_unsigned(nul != str_end ? nul - str : specs.precision)); + arg = make_arg>(sv); + } + if (specs.alt && visit_format_arg(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 t = it != end ? *it : 0; + switch (c) { + case 'h': + if (t == 'h') { + ++it; + t = it != end ? *it : 0; + convert_arg(arg, t); + } else { + convert_arg(arg, t); + } + break; + case 'l': + if (t == 'l') { + ++it; + t = it != end ? *it : 0; + convert_arg(arg, t); + } else { + convert_arg(arg, t); + } + break; + case 'j': + convert_arg(arg, t); + break; + case 'z': + convert_arg(arg, t); + break; + case 't': + convert_arg(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(arg, c); + } + + // Parse type. + if (it == end) throw_format_error("invalid format string"); + char type = static_cast(*it++); + if (arg.is_integral()) { + // Normalize type. + switch (type) { + case 'i': + case 'u': + type = 'd'; + break; + case 'c': + visit_format_arg(char_converter>(arg), arg); + break; + } + } + specs.type = parse_printf_presentation_type(type, arg.type()); + if (specs.type == presentation_type::none) + throw_format_error("invalid format specifier"); + + start = it; + + // Format argument. + visit_format_arg(printf_arg_formatter(out, specs, context), arg); + } + write(out, basic_string_view(start, to_unsigned(it - start))); +} +} // namespace detail + +using printf_context = basic_printf_context; +using wprintf_context = basic_printf_context; + +using printf_args = basic_format_args; +using wprintf_args = basic_format_args; + +/** + \rst + Constructs an `~fmt::format_arg_store` object that contains references to + arguments and can be implicitly converted to `~fmt::printf_args`. + \endrst + */ +template +inline auto make_printf_args(const T&... args) + -> format_arg_store { + return {args...}; +} + +// DEPRECATED! +template +inline auto make_wprintf_args(const T&... args) + -> format_arg_store { + return {args...}; +} + +template +inline auto vsprintf( + basic_string_view fmt, + basic_format_args>> args) + -> std::basic_string { + auto buf = basic_memory_buffer(); + detail::vprintf(buf, fmt, args); + return to_string(buf); +} + +/** + \rst + Formats arguments and returns the result as a string. + + **Example**:: + + std::string message = fmt::sprintf("The answer is %d", 42); + \endrst +*/ +template ::value, char_t>> +inline auto sprintf(const S& fmt, const T&... args) -> std::basic_string { + return vsprintf(detail::to_string_view(fmt), + fmt::make_format_args>(args...)); +} + +template +inline auto vfprintf( + std::FILE* f, basic_string_view fmt, + basic_format_args>> args) + -> int { + auto buf = basic_memory_buffer(); + detail::vprintf(buf, fmt, args); + size_t size = buf.size(); + return std::fwrite(buf.data(), sizeof(Char), size, f) < size + ? -1 + : static_cast(size); +} + +/** + \rst + Prints formatted data to the file *f*. + + **Example**:: + + fmt::fprintf(stderr, "Don't %s!", "panic"); + \endrst + */ +template > +inline auto fprintf(std::FILE* f, const S& fmt, const T&... args) -> int { + return vfprintf(f, detail::to_string_view(fmt), + fmt::make_format_args>(args...)); +} + +template +FMT_DEPRECATED inline auto vprintf( + basic_string_view fmt, + basic_format_args>> args) + -> int { + return vfprintf(stdout, fmt, args); +} + +/** + \rst + Prints formatted data to ``stdout``. + + **Example**:: + + fmt::printf("Elapsed time: %.2f seconds", 1.23); + \endrst + */ +template +inline auto printf(string_view fmt, const T&... args) -> int { + return vfprintf(stdout, fmt, make_printf_args(args...)); +} +template +FMT_DEPRECATED inline auto printf(basic_string_view fmt, + const T&... args) -> int { + return vfprintf(stdout, fmt, make_wprintf_args(args...)); +} + +FMT_END_EXPORT +FMT_END_NAMESPACE + +#endif // FMT_PRINTF_H_ diff --git a/third_party/fmt/include/fmt/ranges.h b/third_party/fmt/include/fmt/ranges.h new file mode 100644 index 0000000..3638fff --- /dev/null +++ b/third_party/fmt/include/fmt/ranges.h @@ -0,0 +1,738 @@ +// Formatting library for C++ - range and tuple support +// +// Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_RANGES_H_ +#define FMT_RANGES_H_ + +#include +#include +#include + +#include "format.h" + +FMT_BEGIN_NAMESPACE + +namespace detail { + +template +auto copy(const Range& range, OutputIt out) -> OutputIt { + for (auto it = range.begin(), end = range.end(); it != end; ++it) + *out++ = *it; + return out; +} + +template +auto copy(const char* str, OutputIt out) -> OutputIt { + while (*str) *out++ = *str++; + return out; +} + +template auto copy(char ch, OutputIt out) -> OutputIt { + *out++ = ch; + return out; +} + +template auto copy(wchar_t ch, OutputIt out) -> OutputIt { + *out++ = ch; + return out; +} + +// Returns true if T has a std::string-like interface, like std::string_view. +template class is_std_string_like { + template + static auto check(U* p) + -> decltype((void)p->find('a'), p->length(), (void)p->data(), int()); + template static void check(...); + + public: + static constexpr const bool value = + is_string::value || + std::is_convertible>::value || + !std::is_void(nullptr))>::value; +}; + +template +struct is_std_string_like> : std::true_type {}; + +template class is_map { + template static auto check(U*) -> typename U::mapped_type; + template static void check(...); + + public: +#ifdef FMT_FORMAT_MAP_AS_LIST // DEPRECATED! + static constexpr const bool value = false; +#else + static constexpr const bool value = + !std::is_void(nullptr))>::value; +#endif +}; + +template class is_set { + template static auto check(U*) -> typename U::key_type; + template static void check(...); + + public: +#ifdef FMT_FORMAT_SET_AS_LIST // DEPRECATED! + static constexpr const bool value = false; +#else + static constexpr const bool value = + !std::is_void(nullptr))>::value && !is_map::value; +#endif +}; + +template struct conditional_helper {}; + +template struct is_range_ : std::false_type {}; + +#if !FMT_MSC_VERSION || FMT_MSC_VERSION > 1800 + +# define FMT_DECLTYPE_RETURN(val) \ + ->decltype(val) { return val; } \ + static_assert( \ + true, "") // This makes it so that a semicolon is required after the + // macro, which helps clang-format handle the formatting. + +// C array overload +template +auto range_begin(const T (&arr)[N]) -> const T* { + return arr; +} +template +auto range_end(const T (&arr)[N]) -> const T* { + return arr + N; +} + +template +struct has_member_fn_begin_end_t : std::false_type {}; + +template +struct has_member_fn_begin_end_t().begin()), + decltype(std::declval().end())>> + : std::true_type {}; + +// Member function overload +template +auto range_begin(T&& rng) FMT_DECLTYPE_RETURN(static_cast(rng).begin()); +template +auto range_end(T&& rng) FMT_DECLTYPE_RETURN(static_cast(rng).end()); + +// ADL overload. Only participates in overload resolution if member functions +// are not found. +template +auto range_begin(T&& rng) + -> enable_if_t::value, + decltype(begin(static_cast(rng)))> { + return begin(static_cast(rng)); +} +template +auto range_end(T&& rng) -> enable_if_t::value, + decltype(end(static_cast(rng)))> { + return end(static_cast(rng)); +} + +template +struct has_const_begin_end : std::false_type {}; +template +struct has_mutable_begin_end : std::false_type {}; + +template +struct has_const_begin_end< + T, + void_t< + decltype(detail::range_begin(std::declval&>())), + decltype(detail::range_end(std::declval&>()))>> + : std::true_type {}; + +template +struct has_mutable_begin_end< + T, void_t())), + decltype(detail::range_end(std::declval())), + // the extra int here is because older versions of MSVC don't + // SFINAE properly unless there are distinct types + int>> : std::true_type {}; + +template +struct is_range_ + : std::integral_constant::value || + has_mutable_begin_end::value)> {}; +# undef FMT_DECLTYPE_RETURN +#endif + +// tuple_size and tuple_element check. +template class is_tuple_like_ { + template + static auto check(U* p) -> decltype(std::tuple_size::value, int()); + template static void check(...); + + public: + static constexpr const bool value = + !std::is_void(nullptr))>::value; +}; + +// Check for integer_sequence +#if defined(__cpp_lib_integer_sequence) || FMT_MSC_VERSION >= 1900 +template +using integer_sequence = std::integer_sequence; +template using index_sequence = std::index_sequence; +template using make_index_sequence = std::make_index_sequence; +#else +template struct integer_sequence { + using value_type = T; + + static FMT_CONSTEXPR auto size() -> size_t { return sizeof...(N); } +}; + +template using index_sequence = integer_sequence; + +template +struct make_integer_sequence : make_integer_sequence {}; +template +struct make_integer_sequence : integer_sequence {}; + +template +using make_index_sequence = make_integer_sequence; +#endif + +template +using tuple_index_sequence = make_index_sequence::value>; + +template ::value> +class is_tuple_formattable_ { + public: + static constexpr const bool value = false; +}; +template class is_tuple_formattable_ { + template + static auto check2(index_sequence, + integer_sequence) -> std::true_type; + static auto check2(...) -> std::false_type; + template + static auto check(index_sequence) -> decltype(check2( + index_sequence{}, + integer_sequence::type, + C>::value)...>{})); + + public: + static constexpr const bool value = + decltype(check(tuple_index_sequence{}))::value; +}; + +template +FMT_CONSTEXPR void for_each(index_sequence, Tuple&& t, F&& f) { + using std::get; + // Using a free function get(Tuple) now. + const int unused[] = {0, ((void)f(get(t)), 0)...}; + ignore_unused(unused); +} + +template +FMT_CONSTEXPR void for_each(Tuple&& t, F&& f) { + for_each(tuple_index_sequence>(), + std::forward(t), std::forward(f)); +} + +template +void for_each2(index_sequence, Tuple1&& t1, Tuple2&& t2, F&& f) { + using std::get; + const int unused[] = {0, ((void)f(get(t1), get(t2)), 0)...}; + ignore_unused(unused); +} + +template +void for_each2(Tuple1&& t1, Tuple2&& t2, F&& f) { + for_each2(tuple_index_sequence>(), + std::forward(t1), std::forward(t2), + std::forward(f)); +} + +namespace tuple { +// Workaround a bug in MSVC 2019 (v140). +template +using result_t = std::tuple, Char>...>; + +using std::get; +template +auto get_formatters(index_sequence) + -> result_t(std::declval()))...>; +} // namespace tuple + +#if FMT_MSC_VERSION && FMT_MSC_VERSION < 1920 +// Older MSVC doesn't get the reference type correctly for arrays. +template struct range_reference_type_impl { + using type = decltype(*detail::range_begin(std::declval())); +}; + +template struct range_reference_type_impl { + using type = T&; +}; + +template +using range_reference_type = typename range_reference_type_impl::type; +#else +template +using range_reference_type = + decltype(*detail::range_begin(std::declval())); +#endif + +// We don't use the Range's value_type for anything, but we do need the Range's +// reference type, with cv-ref stripped. +template +using uncvref_type = remove_cvref_t>; + +template +FMT_CONSTEXPR auto maybe_set_debug_format(Formatter& f, bool set) + -> decltype(f.set_debug_format(set)) { + f.set_debug_format(set); +} +template +FMT_CONSTEXPR void maybe_set_debug_format(Formatter&, ...) {} + +// These are not generic lambdas for compatibility with C++11. +template struct parse_empty_specs { + template FMT_CONSTEXPR void operator()(Formatter& f) { + f.parse(ctx); + detail::maybe_set_debug_format(f, true); + } + ParseContext& ctx; +}; +template struct format_tuple_element { + using char_type = typename FormatContext::char_type; + + template + void operator()(const formatter& f, const T& v) { + if (i > 0) + ctx.advance_to(detail::copy_str(separator, ctx.out())); + ctx.advance_to(f.format(v, ctx)); + ++i; + } + + int i; + FormatContext& ctx; + basic_string_view separator; +}; + +} // namespace detail + +template struct is_tuple_like { + static constexpr const bool value = + detail::is_tuple_like_::value && !detail::is_range_::value; +}; + +template struct is_tuple_formattable { + static constexpr const bool value = + detail::is_tuple_formattable_::value; +}; + +template +struct formatter::value && + fmt::is_tuple_formattable::value>> { + private: + decltype(detail::tuple::get_formatters( + detail::tuple_index_sequence())) formatters_; + + basic_string_view separator_ = detail::string_literal{}; + basic_string_view opening_bracket_ = + detail::string_literal{}; + basic_string_view closing_bracket_ = + detail::string_literal{}; + + public: + FMT_CONSTEXPR formatter() {} + + FMT_CONSTEXPR void set_separator(basic_string_view sep) { + separator_ = sep; + } + + FMT_CONSTEXPR void set_brackets(basic_string_view open, + basic_string_view close) { + opening_bracket_ = open; + closing_bracket_ = close; + } + + template + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + auto it = ctx.begin(); + if (it != ctx.end() && *it != '}') + FMT_THROW(format_error("invalid format specifier")); + detail::for_each(formatters_, detail::parse_empty_specs{ctx}); + return it; + } + + template + auto format(const Tuple& value, FormatContext& ctx) const + -> decltype(ctx.out()) { + ctx.advance_to(detail::copy_str(opening_bracket_, ctx.out())); + detail::for_each2( + formatters_, value, + detail::format_tuple_element{0, ctx, separator_}); + return detail::copy_str(closing_bracket_, ctx.out()); + } +}; + +template struct is_range { + static constexpr const bool value = + detail::is_range_::value && !detail::is_std_string_like::value && + !std::is_convertible>::value && + !std::is_convertible>::value; +}; + +namespace detail { +template struct range_mapper { + using mapper = arg_mapper; + + template , Context>::value)> + static auto map(T&& value) -> T&& { + return static_cast(value); + } + template , Context>::value)> + static auto map(T&& value) + -> decltype(mapper().map(static_cast(value))) { + return mapper().map(static_cast(value)); + } +}; + +template +using range_formatter_type = + formatter>{}.map( + std::declval()))>, + Char>; + +template +using maybe_const_range = + conditional_t::value, const R, R>; + +// Workaround a bug in MSVC 2015 and earlier. +#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1910 +template +struct is_formattable_delayed + : is_formattable>, Char> {}; +#endif +} // namespace detail + +template struct conjunction : std::true_type {}; +template struct conjunction +
+
+ {{ content }} +
+ +
+ + + + diff --git a/third_party/googletest/docs/_sass/main.scss b/third_party/googletest/docs/_sass/main.scss new file mode 100644 index 0000000..92edc87 --- /dev/null +++ b/third_party/googletest/docs/_sass/main.scss @@ -0,0 +1,200 @@ +// Styles for GoogleTest docs website on GitHub Pages. +// Color variables are defined in +// https://github.com/pages-themes/primer/tree/master/_sass/primer-support/lib/variables + +$sidebar-width: 260px; + +body { + display: flex; + margin: 0; +} + +.sidebar { + background: $black; + color: $text-white; + flex-shrink: 0; + height: 100vh; + overflow: auto; + position: sticky; + top: 0; + width: $sidebar-width; +} + +.sidebar h1 { + font-size: 1.5em; +} + +.sidebar h2 { + color: $gray-light; + font-size: 0.8em; + font-weight: normal; + margin-bottom: 0.8em; + padding-left: 2.5em; + text-transform: uppercase; +} + +.sidebar .header { + background: $black; + padding: 2em; + position: sticky; + top: 0; + width: 100%; +} + +.sidebar .header a { + color: $text-white; + text-decoration: none; +} + +.sidebar .nav-toggle { + display: none; +} + +.sidebar .expander { + cursor: pointer; + display: none; + height: 3em; + position: absolute; + right: 1em; + top: 1.5em; + width: 3em; +} + +.sidebar .expander .arrow { + border: solid $white; + border-width: 0 3px 3px 0; + display: block; + height: 0.7em; + margin: 1em auto; + transform: rotate(45deg); + transition: transform 0.5s; + width: 0.7em; +} + +.sidebar nav { + width: 100%; +} + +.sidebar nav ul { + list-style-type: none; + margin-bottom: 1em; + padding: 0; + + &:last-child { + margin-bottom: 2em; + } + + a { + text-decoration: none; + } + + li { + color: $text-white; + padding-left: 2em; + text-decoration: none; + } + + li.active { + background: $border-gray-darker; + font-weight: bold; + } + + li:hover { + background: $border-gray-darker; + } +} + +.main { + background-color: $bg-gray; + width: calc(100% - #{$sidebar-width}); +} + +.main .main-inner { + background-color: $white; + padding: 2em; +} + +.main .footer { + margin: 0; + padding: 2em; +} + +.main table th { + text-align: left; +} + +.main .callout { + border-left: 0.25em solid $white; + padding: 1em; + + a { + text-decoration: underline; + } + + &.important { + background-color: $bg-yellow-light; + border-color: $bg-yellow; + color: $black; + } + + &.note { + background-color: $bg-blue-light; + border-color: $text-blue; + color: $text-blue; + } + + &.tip { + background-color: $green-000; + border-color: $green-700; + color: $green-700; + } + + &.warning { + background-color: $red-000; + border-color: $text-red; + color: $text-red; + } +} + +.main .good pre { + background-color: $bg-green-light; +} + +.main .bad pre { + background-color: $red-000; +} + +@media all and (max-width: 768px) { + body { + flex-direction: column; + } + + .sidebar { + height: auto; + position: relative; + width: 100%; + } + + .sidebar .expander { + display: block; + } + + .sidebar nav { + height: 0; + overflow: hidden; + } + + .sidebar .nav-toggle:checked { + & ~ nav { + height: auto; + } + + & + .expander .arrow { + transform: rotate(-135deg); + } + } + + .main { + width: 100%; + } +} diff --git a/third_party/googletest/docs/advanced.md b/third_party/googletest/docs/advanced.md new file mode 100644 index 0000000..9a752b9 --- /dev/null +++ b/third_party/googletest/docs/advanced.md @@ -0,0 +1,2398 @@ +# Advanced googletest Topics + +## Introduction + +Now that you have read the [googletest Primer](primer.md) and learned how to +write tests using googletest, it's time to learn some new tricks. This document +will show you more assertions as well as how to construct complex failure +messages, propagate fatal failures, reuse and speed up your test fixtures, and +use various flags with your tests. + +## More Assertions + +This section covers some less frequently used, but still significant, +assertions. + +### Explicit Success and Failure + +See [Explicit Success and Failure](reference/assertions.md#success-failure) in +the Assertions Reference. + +### Exception Assertions + +See [Exception Assertions](reference/assertions.md#exceptions) in the Assertions +Reference. + +### Predicate Assertions for Better Error Messages + +Even though googletest has a rich set of assertions, they can never be complete, +as it's impossible (nor a good idea) to anticipate all scenarios a user might +run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` to check a +complex expression, for lack of a better macro. This has the problem of not +showing you the values of the parts of the expression, making it hard to +understand what went wrong. As a workaround, some users choose to construct the +failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this +is awkward especially when the expression has side-effects or is expensive to +evaluate. + +googletest gives you three different options to solve this problem: + +#### Using an Existing Boolean Function + +If you already have a function or functor that returns `bool` (or a type that +can be implicitly converted to `bool`), you can use it in a *predicate +assertion* to get the function arguments printed for free. See +[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the Assertions +Reference for details. + +#### Using a Function That Returns an AssertionResult + +While `EXPECT_PRED*()` and friends are handy for a quick job, the syntax is not +satisfactory: you have to use different macros for different arities, and it +feels more like Lisp than C++. The `::testing::AssertionResult` class solves +this problem. + +An `AssertionResult` object represents the result of an assertion (whether it's +a success or a failure, and an associated message). You can create an +`AssertionResult` using one of these factory functions: + +```c++ +namespace testing { + +// Returns an AssertionResult object to indicate that an assertion has +// succeeded. +AssertionResult AssertionSuccess(); + +// Returns an AssertionResult object to indicate that an assertion has +// failed. +AssertionResult AssertionFailure(); + +} +``` + +You can then use the `<<` operator to stream messages to the `AssertionResult` +object. + +To provide more readable messages in Boolean assertions (e.g. `EXPECT_TRUE()`), +write a predicate function that returns `AssertionResult` instead of `bool`. For +example, if you define `IsEven()` as: + +```c++ +testing::AssertionResult IsEven(int n) { + if ((n % 2) == 0) + return testing::AssertionSuccess(); + else + return testing::AssertionFailure() << n << " is odd"; +} +``` + +instead of: + +```c++ +bool IsEven(int n) { + return (n % 2) == 0; +} +``` + +the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print: + +```none +Value of: IsEven(Fib(4)) + Actual: false (3 is odd) +Expected: true +``` + +instead of a more opaque + +```none +Value of: IsEven(Fib(4)) + Actual: false +Expected: true +``` + +If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` as well +(one third of Boolean assertions in the Google code base are negative ones), and +are fine with making the predicate slower in the success case, you can supply a +success message: + +```c++ +testing::AssertionResult IsEven(int n) { + if ((n % 2) == 0) + return testing::AssertionSuccess() << n << " is even"; + else + return testing::AssertionFailure() << n << " is odd"; +} +``` + +Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print + +```none + Value of: IsEven(Fib(6)) + Actual: true (8 is even) + Expected: false +``` + +#### Using a Predicate-Formatter + +If you find the default message generated by +[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) and +[`EXPECT_TRUE`](reference/assertions.md#EXPECT_TRUE) unsatisfactory, or some +arguments to your predicate do not support streaming to `ostream`, you can +instead use *predicate-formatter assertions* to *fully* customize how the +message is formatted. See +[`EXPECT_PRED_FORMAT*`](reference/assertions.md#EXPECT_PRED_FORMAT) in the +Assertions Reference for details. + +### Floating-Point Comparison + +See [Floating-Point Comparison](reference/assertions.md#floating-point) in the +Assertions Reference. + +#### Floating-Point Predicate-Format Functions + +Some floating-point operations are useful, but not that often used. In order to +avoid an explosion of new macros, we provide them as predicate-format functions +that can be used in the predicate assertion macro +[`EXPECT_PRED_FORMAT2`](reference/assertions.md#EXPECT_PRED_FORMAT), for +example: + +```c++ +using ::testing::FloatLE; +using ::testing::DoubleLE; +... +EXPECT_PRED_FORMAT2(FloatLE, val1, val2); +EXPECT_PRED_FORMAT2(DoubleLE, val1, val2); +``` + +The above code verifies that `val1` is less than, or approximately equal to, +`val2`. + +### Asserting Using gMock Matchers + +See [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions +Reference. + +### More String Assertions + +(Please read the [previous](#asserting-using-gmock-matchers) section first if +you haven't.) + +You can use the gMock [string matchers](reference/matchers.md#string-matchers) +with [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) to do more string +comparison tricks (sub-string, prefix, suffix, regular expression, and etc). For +example, + +```c++ +using ::testing::HasSubstr; +using ::testing::MatchesRegex; +... + ASSERT_THAT(foo_string, HasSubstr("needle")); + EXPECT_THAT(bar_string, MatchesRegex("\\w*\\d+")); +``` + +### Windows HRESULT assertions + +See [Windows HRESULT Assertions](reference/assertions.md#HRESULT) in the +Assertions Reference. + +### Type Assertions + +You can call the function + +```c++ +::testing::StaticAssertTypeEq(); +``` + +to assert that types `T1` and `T2` are the same. The function does nothing if +the assertion is satisfied. If the types are different, the function call will +fail to compile, the compiler error message will say that `T1 and T2 are not the +same type` and most likely (depending on the compiler) show you the actual +values of `T1` and `T2`. This is mainly useful inside template code. + +**Caveat**: When used inside a member function of a class template or a function +template, `StaticAssertTypeEq()` is effective only if the function is +instantiated. For example, given: + +```c++ +template class Foo { + public: + void Bar() { testing::StaticAssertTypeEq(); } +}; +``` + +the code: + +```c++ +void Test1() { Foo foo; } +``` + +will not generate a compiler error, as `Foo::Bar()` is never actually +instantiated. Instead, you need: + +```c++ +void Test2() { Foo foo; foo.Bar(); } +``` + +to cause a compiler error. + +### Assertion Placement + +You can use assertions in any C++ function. In particular, it doesn't have to be +a method of the test fixture class. The one constraint is that assertions that +generate a fatal failure (`FAIL*` and `ASSERT_*`) can only be used in +void-returning functions. This is a consequence of Google's not using +exceptions. By placing it in a non-void function you'll get a confusing compile +error like `"error: void value not ignored as it ought to be"` or `"cannot +initialize return object of type 'bool' with an rvalue of type 'void'"` or +`"error: no viable conversion from 'void' to 'string'"`. + +If you need to use fatal assertions in a function that returns non-void, one +option is to make the function return the value in an out parameter instead. For +example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You +need to make sure that `*result` contains some sensible value even when the +function returns prematurely. As the function now returns `void`, you can use +any assertion inside of it. + +If changing the function's type is not an option, you should just use assertions +that generate non-fatal failures, such as `ADD_FAILURE*` and `EXPECT_*`. + +{: .callout .note} +NOTE: Constructors and destructors are not considered void-returning functions, +according to the C++ language specification, and so you may not use fatal +assertions in them; you'll get a compilation error if you try. Instead, either +call `abort` and crash the entire test executable, or put the fatal assertion in +a `SetUp`/`TearDown` function; see +[constructor/destructor vs. `SetUp`/`TearDown`](faq.md#CtorVsSetUp) + +{: .callout .warning} +WARNING: A fatal assertion in a helper function (private void-returning method) +called from a constructor or destructor does not terminate the current test, as +your intuition might suggest: it merely returns from the constructor or +destructor early, possibly leaving your object in a partially-constructed or +partially-destructed state! You almost certainly want to `abort` or use +`SetUp`/`TearDown` instead. + +## Skipping test execution + +Related to the assertions `SUCCEED()` and `FAIL()`, you can prevent further test +execution at runtime with the `GTEST_SKIP()` macro. This is useful when you need +to check for preconditions of the system under test during runtime and skip +tests in a meaningful way. + +`GTEST_SKIP()` can be used in individual test cases or in the `SetUp()` methods +of classes derived from either `::testing::Environment` or `::testing::Test`. +For example: + +```c++ +TEST(SkipTest, DoesSkip) { + GTEST_SKIP() << "Skipping single test"; + EXPECT_EQ(0, 1); // Won't fail; it won't be executed +} + +class SkipFixture : public ::testing::Test { + protected: + void SetUp() override { + GTEST_SKIP() << "Skipping all tests for this fixture"; + } +}; + +// Tests for SkipFixture won't be executed. +TEST_F(SkipFixture, SkipsOneTest) { + EXPECT_EQ(5, 7); // Won't fail +} +``` + +As with assertion macros, you can stream a custom message into `GTEST_SKIP()`. + +## Teaching googletest How to Print Your Values + +When a test assertion such as `EXPECT_EQ` fails, googletest prints the argument +values to help you debug. It does this using a user-extensible value printer. + +This printer knows how to print built-in C++ types, native arrays, STL +containers, and any type that supports the `<<` operator. For other types, it +prints the raw bytes in the value and hopes that you the user can figure it out. + +As mentioned earlier, the printer is *extensible*. That means you can teach it +to do a better job at printing your particular type than to dump the bytes. To +do that, define `<<` for your type: + +```c++ +#include + +namespace foo { + +class Bar { // We want googletest to be able to print instances of this. +... + // Create a free inline friend function. + friend std::ostream& operator<<(std::ostream& os, const Bar& bar) { + return os << bar.DebugString(); // whatever needed to print bar to os + } +}; + +// If you can't declare the function in the class it's important that the +// << operator is defined in the SAME namespace that defines Bar. C++'s look-up +// rules rely on that. +std::ostream& operator<<(std::ostream& os, const Bar& bar) { + return os << bar.DebugString(); // whatever needed to print bar to os +} + +} // namespace foo +``` + +Sometimes, this might not be an option: your team may consider it bad style to +have a `<<` operator for `Bar`, or `Bar` may already have a `<<` operator that +doesn't do what you want (and you cannot change it). If so, you can instead +define a `PrintTo()` function like this: + +```c++ +#include + +namespace foo { + +class Bar { + ... + friend void PrintTo(const Bar& bar, std::ostream* os) { + *os << bar.DebugString(); // whatever needed to print bar to os + } +}; + +// If you can't declare the function in the class it's important that PrintTo() +// is defined in the SAME namespace that defines Bar. C++'s look-up rules rely +// on that. +void PrintTo(const Bar& bar, std::ostream* os) { + *os << bar.DebugString(); // whatever needed to print bar to os +} + +} // namespace foo +``` + +If you have defined both `<<` and `PrintTo()`, the latter will be used when +googletest is concerned. This allows you to customize how the value appears in +googletest's output without affecting code that relies on the behavior of its +`<<` operator. + +If you want to print a value `x` using googletest's value printer yourself, just +call `::testing::PrintToString(x)`, which returns an `std::string`: + +```c++ +vector > bar_ints = GetBarIntVector(); + +EXPECT_TRUE(IsCorrectBarIntVector(bar_ints)) + << "bar_ints = " << testing::PrintToString(bar_ints); +``` + +## Death Tests + +In many applications, there are assertions that can cause application failure if +a condition is not met. These consistency checks, which ensure that the program +is in a known good state, are there to fail at the earliest possible time after +some program state is corrupted. If the assertion checks the wrong condition, +then the program may proceed in an erroneous state, which could lead to memory +corruption, security holes, or worse. Hence it is vitally important to test that +such assertion statements work as expected. + +Since these precondition checks cause the processes to die, we call such tests +_death tests_. More generally, any test that checks that a program terminates +(except by throwing an exception) in an expected fashion is also a death test. + +Note that if a piece of code throws an exception, we don't consider it "death" +for the purpose of death tests, as the caller of the code could catch the +exception and avoid the crash. If you want to verify exceptions thrown by your +code, see [Exception Assertions](#ExceptionAssertions). + +If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see +["Catching" Failures](#catching-failures). + +### How to Write a Death Test + +GoogleTest provides assertion macros to support death tests. See +[Death Assertions](reference/assertions.md#death) in the Assertions Reference +for details. + +To write a death test, simply use one of the macros inside your test function. +For example, + +```c++ +TEST(MyDeathTest, Foo) { + // This death test uses a compound statement. + ASSERT_DEATH({ + int n = 5; + Foo(&n); + }, "Error on line .* of Foo()"); +} + +TEST(MyDeathTest, NormalExit) { + EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success"); +} + +TEST(MyDeathTest, KillProcess) { + EXPECT_EXIT(KillProcess(), testing::KilledBySignal(SIGKILL), + "Sending myself unblockable signal"); +} +``` + +verifies that: + +* calling `Foo(5)` causes the process to die with the given error message, +* calling `NormalExit()` causes the process to print `"Success"` to stderr and + exit with exit code 0, and +* calling `KillProcess()` kills the process with signal `SIGKILL`. + +The test function body may contain other assertions and statements as well, if +necessary. + +Note that a death test only cares about three things: + +1. does `statement` abort or exit the process? +2. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status + satisfy `predicate`? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) + is the exit status non-zero? And +3. does the stderr output match `matcher`? + +In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it +will **not** cause the death test to fail, as googletest assertions don't abort +the process. + +### Death Test Naming + +{: .callout .important} +IMPORTANT: We strongly recommend you to follow the convention of naming your +**test suite** (not test) `*DeathTest` when it contains a death test, as +demonstrated in the above example. The +[Death Tests And Threads](#death-tests-and-threads) section below explains why. + +If a test fixture class is shared by normal tests and death tests, you can use +`using` or `typedef` to introduce an alias for the fixture class and avoid +duplicating its code: + +```c++ +class FooTest : public testing::Test { ... }; + +using FooDeathTest = FooTest; + +TEST_F(FooTest, DoesThis) { + // normal test +} + +TEST_F(FooDeathTest, DoesThat) { + // death test +} +``` + +### Regular Expression Syntax + +When built with Bazel and using Abseil, googletest uses the +[RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX +systems (Linux, Cygwin, Mac), googletest uses the +[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) +syntax. To learn about POSIX syntax, you may want to read this +[Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). + +On Windows, googletest uses its own simple regular expression implementation. It +lacks many features. For example, we don't support union (`"x|y"`), grouping +(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among +others. Below is what we do support (`A` denotes a literal character, period +(`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular +expressions.): + +Expression | Meaning +---------- | -------------------------------------------------------------- +`c` | matches any literal character `c` +`\\d` | matches any decimal digit +`\\D` | matches any character that's not a decimal digit +`\\f` | matches `\f` +`\\n` | matches `\n` +`\\r` | matches `\r` +`\\s` | matches any ASCII whitespace, including `\n` +`\\S` | matches any character that's not a whitespace +`\\t` | matches `\t` +`\\v` | matches `\v` +`\\w` | matches any letter, `_`, or decimal digit +`\\W` | matches any character that `\\w` doesn't match +`\\c` | matches any literal character `c`, which must be a punctuation +`.` | matches any single character except `\n` +`A?` | matches 0 or 1 occurrences of `A` +`A*` | matches 0 or many occurrences of `A` +`A+` | matches 1 or many occurrences of `A` +`^` | matches the beginning of a string (not that of each line) +`$` | matches the end of a string (not that of each line) +`xy` | matches `x` followed by `y` + +To help you determine which capability is available on your system, googletest +defines macros to govern which regular expression it is using. The macros are: +`GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death +tests to work in all cases, you can either `#if` on these macros or use the more +limited syntax only. + +### How It Works + +See [Death Assertions](reference/assertions.md#death) in the Assertions +Reference. + +### Death Tests And Threads + +The reason for the two death test styles has to do with thread safety. Due to +well-known problems with forking in the presence of threads, death tests should +be run in a single-threaded context. Sometimes, however, it isn't feasible to +arrange that kind of environment. For example, statically-initialized modules +may start threads before main is ever reached. Once threads have been created, +it may be difficult or impossible to clean them up. + +googletest has three features intended to raise awareness of threading issues. + +1. A warning is emitted if multiple threads are running when a death test is + encountered. +2. Test suites with a name ending in "DeathTest" are run before all other + tests. +3. It uses `clone()` instead of `fork()` to spawn the child process on Linux + (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely + to cause the child to hang when the parent process has multiple threads. + +It's perfectly fine to create threads inside a death test statement; they are +executed in a separate process and cannot affect the parent. + +### Death Test Styles + +The "threadsafe" death test style was introduced in order to help mitigate the +risks of testing in a possibly multithreaded environment. It trades increased +test execution time (potentially dramatically so) for improved thread safety. + +The automated testing framework does not set the style flag. You can choose a +particular style of death tests by setting the flag programmatically: + +```c++ +GTEST_FLAG_SET(death_test_style, "threadsafe") +``` + +You can do this in `main()` to set the style for all death tests in the binary, +or in individual tests. Recall that flags are saved before running each test and +restored afterwards, so you need not do that yourself. For example: + +```c++ +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + GTEST_FLAG_SET(death_test_style, "fast"); + return RUN_ALL_TESTS(); +} + +TEST(MyDeathTest, TestOne) { + GTEST_FLAG_SET(death_test_style, "threadsafe"); + // This test is run in the "threadsafe" style: + ASSERT_DEATH(ThisShouldDie(), ""); +} + +TEST(MyDeathTest, TestTwo) { + // This test is run in the "fast" style: + ASSERT_DEATH(ThisShouldDie(), ""); +} +``` + +### Caveats + +The `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If +it leaves the current function via a `return` statement or by throwing an +exception, the death test is considered to have failed. Some googletest macros +may return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid +them in `statement`. + +Since `statement` runs in the child process, any in-memory side effect (e.g. +modifying a variable, releasing memory, etc) it causes will *not* be observable +in the parent process. In particular, if you release memory in a death test, +your program will fail the heap check as the parent process will never see the +memory reclaimed. To solve this problem, you can + +1. try not to free memory in a death test; +2. free the memory again in the parent process; or +3. do not use the heap checker in your program. + +Due to an implementation detail, you cannot place multiple death test assertions +on the same line; otherwise, compilation will fail with an unobvious error +message. + +Despite the improved thread safety afforded by the "threadsafe" style of death +test, thread problems such as deadlock are still possible in the presence of +handlers registered with `pthread_atfork(3)`. + +## Using Assertions in Sub-routines + +{: .callout .note} +Note: If you want to put a series of test assertions in a subroutine to check +for a complex condition, consider using +[a custom GMock matcher](gmock_cook_book.md#NewMatchers) instead. This lets you +provide a more readable error message in case of failure and avoid all of the +issues described below. + +### Adding Traces to Assertions + +If a test sub-routine is called from several places, when an assertion inside it +fails, it can be hard to tell which invocation of the sub-routine the failure is +from. You can alleviate this problem using extra logging or custom failure +messages, but that usually clutters up your tests. A better solution is to use +the `SCOPED_TRACE` macro or the `ScopedTrace` utility: + +```c++ +SCOPED_TRACE(message); +``` + +```c++ +ScopedTrace trace("file_path", line_number, message); +``` + +where `message` can be anything streamable to `std::ostream`. `SCOPED_TRACE` +macro will cause the current file name, line number, and the given message to be +added in every failure message. `ScopedTrace` accepts explicit file name and +line number in arguments, which is useful for writing test helpers. The effect +will be undone when the control leaves the current lexical scope. + +For example, + +```c++ +10: void Sub1(int n) { +11: EXPECT_EQ(Bar(n), 1); +12: EXPECT_EQ(Bar(n + 1), 2); +13: } +14: +15: TEST(FooTest, Bar) { +16: { +17: SCOPED_TRACE("A"); // This trace point will be included in +18: // every failure in this scope. +19: Sub1(1); +20: } +21: // Now it won't. +22: Sub1(9); +23: } +``` + +could result in messages like these: + +```none +path/to/foo_test.cc:11: Failure +Value of: Bar(n) +Expected: 1 + Actual: 2 +Google Test trace: +path/to/foo_test.cc:17: A + +path/to/foo_test.cc:12: Failure +Value of: Bar(n + 1) +Expected: 2 + Actual: 3 +``` + +Without the trace, it would've been difficult to know which invocation of +`Sub1()` the two failures come from respectively. (You could add an extra +message to each assertion in `Sub1()` to indicate the value of `n`, but that's +tedious.) + +Some tips on using `SCOPED_TRACE`: + +1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the + beginning of a sub-routine, instead of at each call site. +2. When calling sub-routines inside a loop, make the loop iterator part of the + message in `SCOPED_TRACE` such that you can know which iteration the failure + is from. +3. Sometimes the line number of the trace point is enough for identifying the + particular invocation of a sub-routine. In this case, you don't have to + choose a unique message for `SCOPED_TRACE`. You can simply use `""`. +4. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer + scope. In this case, all active trace points will be included in the failure + messages, in reverse order they are encountered. +5. The trace dump is clickable in Emacs - hit `return` on a line number and + you'll be taken to that line in the source file! + +### Propagating Fatal Failures + +A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that +when they fail they only abort the _current function_, not the entire test. For +example, the following test will segfault: + +```c++ +void Subroutine() { + // Generates a fatal failure and aborts the current function. + ASSERT_EQ(1, 2); + + // The following won't be executed. + ... +} + +TEST(FooTest, Bar) { + Subroutine(); // The intended behavior is for the fatal failure + // in Subroutine() to abort the entire test. + + // The actual behavior: the function goes on after Subroutine() returns. + int* p = nullptr; + *p = 3; // Segfault! +} +``` + +To alleviate this, googletest provides three different solutions. You could use +either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the +`HasFatalFailure()` function. They are described in the following two +subsections. + +#### Asserting on Subroutines with an exception + +The following code can turn ASSERT-failure into an exception: + +```c++ +class ThrowListener : public testing::EmptyTestEventListener { + void OnTestPartResult(const testing::TestPartResult& result) override { + if (result.type() == testing::TestPartResult::kFatalFailure) { + throw testing::AssertionException(result); + } + } +}; +int main(int argc, char** argv) { + ... + testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener); + return RUN_ALL_TESTS(); +} +``` + +This listener should be added after other listeners if you have any, otherwise +they won't see failed `OnTestPartResult`. + +#### Asserting on Subroutines + +As shown above, if your test calls a subroutine that has an `ASSERT_*` failure +in it, the test will continue after the subroutine returns. This may not be what +you want. + +Often people want fatal failures to propagate like exceptions. For that +googletest offers the following macros: + +Fatal assertion | Nonfatal assertion | Verifies +------------------------------------- | ------------------------------------- | -------- +`ASSERT_NO_FATAL_FAILURE(statement);` | `EXPECT_NO_FATAL_FAILURE(statement);` | `statement` doesn't generate any new fatal failures in the current thread. + +Only failures in the thread that executes the assertion are checked to determine +the result of this type of assertions. If `statement` creates new threads, +failures in these threads are ignored. + +Examples: + +```c++ +ASSERT_NO_FATAL_FAILURE(Foo()); + +int i; +EXPECT_NO_FATAL_FAILURE({ + i = Bar(); +}); +``` + +Assertions from multiple threads are currently not supported on Windows. + +#### Checking for Failures in the Current Test + +`HasFatalFailure()` in the `::testing::Test` class returns `true` if an +assertion in the current test has suffered a fatal failure. This allows +functions to catch fatal failures in a sub-routine and return early. + +```c++ +class Test { + public: + ... + static bool HasFatalFailure(); +}; +``` + +The typical usage, which basically simulates the behavior of a thrown exception, +is: + +```c++ +TEST(FooTest, Bar) { + Subroutine(); + // Aborts if Subroutine() had a fatal failure. + if (HasFatalFailure()) return; + + // The following won't be executed. + ... +} +``` + +If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test +fixture, you must add the `::testing::Test::` prefix, as in: + +```c++ +if (testing::Test::HasFatalFailure()) return; +``` + +Similarly, `HasNonfatalFailure()` returns `true` if the current test has at +least one non-fatal failure, and `HasFailure()` returns `true` if the current +test has at least one failure of either kind. + +## Logging Additional Information + +In your test code, you can call `RecordProperty("key", value)` to log additional +information, where `value` can be either a string or an `int`. The *last* value +recorded for a key will be emitted to the +[XML output](#generating-an-xml-report) if you specify one. For example, the +test + +```c++ +TEST_F(WidgetUsageTest, MinAndMaxWidgets) { + RecordProperty("MaximumWidgets", ComputeMaxUsage()); + RecordProperty("MinimumWidgets", ComputeMinUsage()); +} +``` + +will output XML like this: + +```xml + ... + + ... +``` + +{: .callout .note} +> NOTE: +> +> * `RecordProperty()` is a static member of the `Test` class. Therefore it +> needs to be prefixed with `::testing::Test::` if used outside of the +> `TEST` body and the test fixture class. +> * *`key`* must be a valid XML attribute name, and cannot conflict with the +> ones already used by googletest (`name`, `status`, `time`, `classname`, +> `type_param`, and `value_param`). +> * Calling `RecordProperty()` outside of the lifespan of a test is allowed. +> If it's called outside of a test but between a test suite's +> `SetUpTestSuite()` and `TearDownTestSuite()` methods, it will be +> attributed to the XML element for the test suite. If it's called outside +> of all test suites (e.g. in a test environment), it will be attributed to +> the top-level XML element. + +## Sharing Resources Between Tests in the Same Test Suite + +googletest creates a new test fixture object for each test in order to make +tests independent and easier to debug. However, sometimes tests use resources +that are expensive to set up, making the one-copy-per-test model prohibitively +expensive. + +If the tests don't change the resource, there's no harm in their sharing a +single resource copy. So, in addition to per-test set-up/tear-down, googletest +also supports per-test-suite set-up/tear-down. To use it: + +1. In your test fixture class (say `FooTest` ), declare as `static` some member + variables to hold the shared resources. +2. Outside your test fixture class (typically just below it), define those + member variables, optionally giving them initial values. +3. In the same test fixture class, define a `static void SetUpTestSuite()` + function (remember not to spell it as **`SetupTestSuite`** with a small + `u`!) to set up the shared resources and a `static void TearDownTestSuite()` + function to tear them down. + +That's it! googletest automatically calls `SetUpTestSuite()` before running the +*first test* in the `FooTest` test suite (i.e. before creating the first +`FooTest` object), and calls `TearDownTestSuite()` after running the *last test* +in it (i.e. after deleting the last `FooTest` object). In between, the tests can +use the shared resources. + +Remember that the test order is undefined, so your code can't depend on a test +preceding or following another. Also, the tests must either not modify the state +of any shared resource, or, if they do modify the state, they must restore the +state to its original value before passing control to the next test. + +Note that `SetUpTestSuite()` may be called multiple times for a test fixture +class that has derived classes, so you should not expect code in the function +body to be run only once. Also, derived classes still have access to shared +resources defined as static members, so careful consideration is needed when +managing shared resources to avoid memory leaks. + +Here's an example of per-test-suite set-up and tear-down: + +```c++ +class FooTest : public testing::Test { + protected: + // Per-test-suite set-up. + // Called before the first test in this test suite. + // Can be omitted if not needed. + static void SetUpTestSuite() { + // Avoid reallocating static objects if called in subclasses of FooTest. + if (shared_resource_ == nullptr) { + shared_resource_ = new ...; + } + } + + // Per-test-suite tear-down. + // Called after the last test in this test suite. + // Can be omitted if not needed. + static void TearDownTestSuite() { + delete shared_resource_; + shared_resource_ = nullptr; + } + + // You can define per-test set-up logic as usual. + void SetUp() override { ... } + + // You can define per-test tear-down logic as usual. + void TearDown() override { ... } + + // Some expensive resource shared by all tests. + static T* shared_resource_; +}; + +T* FooTest::shared_resource_ = nullptr; + +TEST_F(FooTest, Test1) { + ... you can refer to shared_resource_ here ... +} + +TEST_F(FooTest, Test2) { + ... you can refer to shared_resource_ here ... +} +``` + +{: .callout .note} +NOTE: Though the above code declares `SetUpTestSuite()` protected, it may +sometimes be necessary to declare it public, such as when using it with +`TEST_P`. + +## Global Set-Up and Tear-Down + +Just as you can do set-up and tear-down at the test level and the test suite +level, you can also do it at the test program level. Here's how. + +First, you subclass the `::testing::Environment` class to define a test +environment, which knows how to set-up and tear-down: + +```c++ +class Environment : public ::testing::Environment { + public: + ~Environment() override {} + + // Override this to define how to set up the environment. + void SetUp() override {} + + // Override this to define how to tear down the environment. + void TearDown() override {} +}; +``` + +Then, you register an instance of your environment class with googletest by +calling the `::testing::AddGlobalTestEnvironment()` function: + +```c++ +Environment* AddGlobalTestEnvironment(Environment* env); +``` + +Now, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of +each environment object, then runs the tests if none of the environments +reported fatal failures and `GTEST_SKIP()` was not called. `RUN_ALL_TESTS()` +always calls `TearDown()` with each environment object, regardless of whether or +not the tests were run. + +It's OK to register multiple environment objects. In this suite, their `SetUp()` +will be called in the order they are registered, and their `TearDown()` will be +called in the reverse order. + +Note that googletest takes ownership of the registered environment objects. +Therefore **do not delete them** by yourself. + +You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called, +probably in `main()`. If you use `gtest_main`, you need to call this before +`main()` starts for it to take effect. One way to do this is to define a global +variable like this: + +```c++ +testing::Environment* const foo_env = + testing::AddGlobalTestEnvironment(new FooEnvironment); +``` + +However, we strongly recommend you to write your own `main()` and call +`AddGlobalTestEnvironment()` there, as relying on initialization of global +variables makes the code harder to read and may cause problems when you register +multiple environments from different translation units and the environments have +dependencies among them (remember that the compiler doesn't guarantee the order +in which global variables from different translation units are initialized). + +## Value-Parameterized Tests + +*Value-parameterized tests* allow you to test your code with different +parameters without writing multiple copies of the same test. This is useful in a +number of situations, for example: + +* You have a piece of code whose behavior is affected by one or more + command-line flags. You want to make sure your code performs correctly for + various values of those flags. +* You want to test different implementations of an OO interface. +* You want to test your code over various inputs (a.k.a. data-driven testing). + This feature is easy to abuse, so please exercise your good sense when doing + it! + +### How to Write Value-Parameterized Tests + +To write value-parameterized tests, first you should define a fixture class. It +must be derived from both `testing::Test` and `testing::WithParamInterface` +(the latter is a pure interface), where `T` is the type of your parameter +values. For convenience, you can just derive the fixture class from +`testing::TestWithParam`, which itself is derived from both `testing::Test` +and `testing::WithParamInterface`. `T` can be any copyable type. If it's a +raw pointer, you are responsible for managing the lifespan of the pointed +values. + +{: .callout .note} +NOTE: If your test fixture defines `SetUpTestSuite()` or `TearDownTestSuite()` +they must be declared **public** rather than **protected** in order to use +`TEST_P`. + +```c++ +class FooTest : + public testing::TestWithParam { + // You can implement all the usual fixture class members here. + // To access the test parameter, call GetParam() from class + // TestWithParam. +}; + +// Or, when you want to add parameters to a pre-existing fixture class: +class BaseTest : public testing::Test { + ... +}; +class BarTest : public BaseTest, + public testing::WithParamInterface { + ... +}; +``` + +Then, use the `TEST_P` macro to define as many test patterns using this fixture +as you want. The `_P` suffix is for "parameterized" or "pattern", whichever you +prefer to think. + +```c++ +TEST_P(FooTest, DoesBlah) { + // Inside a test, access the test parameter with the GetParam() method + // of the TestWithParam class: + EXPECT_TRUE(foo.Blah(GetParam())); + ... +} + +TEST_P(FooTest, HasBlahBlah) { + ... +} +``` + +Finally, you can use the `INSTANTIATE_TEST_SUITE_P` macro to instantiate the +test suite with any set of parameters you want. GoogleTest defines a number of +functions for generating test parameters—see details at +[`INSTANTIATE_TEST_SUITE_P`](reference/testing.md#INSTANTIATE_TEST_SUITE_P) in +the Testing Reference. + +For example, the following statement will instantiate tests from the `FooTest` +test suite each with parameter values `"meeny"`, `"miny"`, and `"moe"` using the +[`Values`](reference/testing.md#param-generators) parameter generator: + +```c++ +INSTANTIATE_TEST_SUITE_P(MeenyMinyMoe, + FooTest, + testing::Values("meeny", "miny", "moe")); +``` + +{: .callout .note} +NOTE: The code above must be placed at global or namespace scope, not at +function scope. + +The first argument to `INSTANTIATE_TEST_SUITE_P` is a unique name for the +instantiation of the test suite. The next argument is the name of the test +pattern, and the last is the +[parameter generator](reference/testing.md#param-generators). + +You can instantiate a test pattern more than once, so to distinguish different +instances of the pattern, the instantiation name is added as a prefix to the +actual test suite name. Remember to pick unique prefixes for different +instantiations. The tests from the instantiation above will have these names: + +* `MeenyMinyMoe/FooTest.DoesBlah/0` for `"meeny"` +* `MeenyMinyMoe/FooTest.DoesBlah/1` for `"miny"` +* `MeenyMinyMoe/FooTest.DoesBlah/2` for `"moe"` +* `MeenyMinyMoe/FooTest.HasBlahBlah/0` for `"meeny"` +* `MeenyMinyMoe/FooTest.HasBlahBlah/1` for `"miny"` +* `MeenyMinyMoe/FooTest.HasBlahBlah/2` for `"moe"` + +You can use these names in [`--gtest_filter`](#running-a-subset-of-the-tests). + +The following statement will instantiate all tests from `FooTest` again, each +with parameter values `"cat"` and `"dog"` using the +[`ValuesIn`](reference/testing.md#param-generators) parameter generator: + +```c++ +const char* pets[] = {"cat", "dog"}; +INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(pets)); +``` + +The tests from the instantiation above will have these names: + +* `Pets/FooTest.DoesBlah/0` for `"cat"` +* `Pets/FooTest.DoesBlah/1` for `"dog"` +* `Pets/FooTest.HasBlahBlah/0` for `"cat"` +* `Pets/FooTest.HasBlahBlah/1` for `"dog"` + +Please note that `INSTANTIATE_TEST_SUITE_P` will instantiate *all* tests in the +given test suite, whether their definitions come before or *after* the +`INSTANTIATE_TEST_SUITE_P` statement. + +Additionally, by default, every `TEST_P` without a corresponding +`INSTANTIATE_TEST_SUITE_P` causes a failing test in test suite +`GoogleTestVerification`. If you have a test suite where that omission is not an +error, for example it is in a library that may be linked in for other reasons or +where the list of test cases is dynamic and may be empty, then this check can be +suppressed by tagging the test suite: + +```c++ +GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest); +``` + +You can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples. + +[sample7_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample7_unittest.cc "Parameterized Test example" +[sample8_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters" + +### Creating Value-Parameterized Abstract Tests + +In the above, we define and instantiate `FooTest` in the *same* source file. +Sometimes you may want to define value-parameterized tests in a library and let +other people instantiate them later. This pattern is known as *abstract tests*. +As an example of its application, when you are designing an interface you can +write a standard suite of abstract tests (perhaps using a factory function as +the test parameter) that all implementations of the interface are expected to +pass. When someone implements the interface, they can instantiate your suite to +get all the interface-conformance tests for free. + +To define abstract tests, you should organize your code like this: + +1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) + in a header file, say `foo_param_test.h`. Think of this as *declaring* your + abstract tests. +2. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes + `foo_param_test.h`. Think of this as *implementing* your abstract tests. + +Once they are defined, you can instantiate them by including `foo_param_test.h`, +invoking `INSTANTIATE_TEST_SUITE_P()`, and depending on the library target that +contains `foo_param_test.cc`. You can instantiate the same abstract test suite +multiple times, possibly in different source files. + +### Specifying Names for Value-Parameterized Test Parameters + +The optional last argument to `INSTANTIATE_TEST_SUITE_P()` allows the user to +specify a function or functor that generates custom test name suffixes based on +the test parameters. The function should accept one argument of type +`testing::TestParamInfo`, and return `std::string`. + +`testing::PrintToStringParamName` is a builtin test suffix generator that +returns the value of `testing::PrintToString(GetParam())`. It does not work for +`std::string` or C strings. + +{: .callout .note} +NOTE: test names must be non-empty, unique, and may only contain ASCII +alphanumeric characters. In particular, they +[should not contain underscores](faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore) + +```c++ +class MyTestSuite : public testing::TestWithParam {}; + +TEST_P(MyTestSuite, MyTest) +{ + std::cout << "Example Test Param: " << GetParam() << std::endl; +} + +INSTANTIATE_TEST_SUITE_P(MyGroup, MyTestSuite, testing::Range(0, 10), + testing::PrintToStringParamName()); +``` + +Providing a custom functor allows for more control over test parameter name +generation, especially for types where the automatic conversion does not +generate helpful parameter names (e.g. strings as demonstrated above). The +following example illustrates this for multiple parameters, an enumeration type +and a string, and also demonstrates how to combine generators. It uses a lambda +for conciseness: + +```c++ +enum class MyType { MY_FOO = 0, MY_BAR = 1 }; + +class MyTestSuite : public testing::TestWithParam> { +}; + +INSTANTIATE_TEST_SUITE_P( + MyGroup, MyTestSuite, + testing::Combine( + testing::Values(MyType::MY_FOO, MyType::MY_BAR), + testing::Values("A", "B")), + [](const testing::TestParamInfo& info) { + std::string name = absl::StrCat( + std::get<0>(info.param) == MyType::MY_FOO ? "Foo" : "Bar", + std::get<1>(info.param)); + absl::c_replace_if(name, [](char c) { return !std::isalnum(c); }, '_'); + return name; + }); +``` + +## Typed Tests + +Suppose you have multiple implementations of the same interface and want to make +sure that all of them satisfy some common requirements. Or, you may have defined +several types that are supposed to conform to the same "concept" and you want to +verify it. In both cases, you want the same test logic repeated for different +types. + +While you can write one `TEST` or `TEST_F` for each type you want to test (and +you may even factor the test logic into a function template that you invoke from +the `TEST`), it's tedious and doesn't scale: if you want `m` tests over `n` +types, you'll end up writing `m*n` `TEST`s. + +*Typed tests* allow you to repeat the same test logic over a list of types. You +only need to write the test logic once, although you must know the type list +when writing typed tests. Here's how you do it: + +First, define a fixture class template. It should be parameterized by a type. +Remember to derive it from `::testing::Test`: + +```c++ +template +class FooTest : public testing::Test { + public: + ... + using List = std::list; + static T shared_; + T value_; +}; +``` + +Next, associate a list of types with the test suite, which will be repeated for +each type in the list: + +```c++ +using MyTypes = ::testing::Types; +TYPED_TEST_SUITE(FooTest, MyTypes); +``` + +The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE` +macro to parse correctly. Otherwise the compiler will think that each comma in +the type list introduces a new macro argument. + +Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test for this +test suite. You can repeat this as many times as you want: + +```c++ +TYPED_TEST(FooTest, DoesBlah) { + // Inside a test, refer to the special name TypeParam to get the type + // parameter. Since we are inside a derived class template, C++ requires + // us to visit the members of FooTest via 'this'. + TypeParam n = this->value_; + + // To visit static members of the fixture, add the 'TestFixture::' + // prefix. + n += TestFixture::shared_; + + // To refer to typedefs in the fixture, add the 'typename TestFixture::' + // prefix. The 'typename' is required to satisfy the compiler. + typename TestFixture::List values; + + values.push_back(n); + ... +} + +TYPED_TEST(FooTest, HasPropertyA) { ... } +``` + +You can see [sample6_unittest.cc] for a complete example. + +[sample6_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample6_unittest.cc "Typed Test example" + +## Type-Parameterized Tests + +*Type-parameterized tests* are like typed tests, except that they don't require +you to know the list of types ahead of time. Instead, you can define the test +logic first and instantiate it with different type lists later. You can even +instantiate it more than once in the same program. + +If you are designing an interface or concept, you can define a suite of +type-parameterized tests to verify properties that any valid implementation of +the interface/concept should have. Then, the author of each implementation can +just instantiate the test suite with their type to verify that it conforms to +the requirements, without having to write similar tests repeatedly. Here's an +example: + +First, define a fixture class template, as we did with typed tests: + +```c++ +template +class FooTest : public testing::Test { + void DoSomethingInteresting(); + ... +}; +``` + +Next, declare that you will define a type-parameterized test suite: + +```c++ +TYPED_TEST_SUITE_P(FooTest); +``` + +Then, use `TYPED_TEST_P()` to define a type-parameterized test. You can repeat +this as many times as you want: + +```c++ +TYPED_TEST_P(FooTest, DoesBlah) { + // Inside a test, refer to TypeParam to get the type parameter. + TypeParam n = 0; + + // You will need to use `this` explicitly to refer to fixture members. + this->DoSomethingInteresting() + ... +} + +TYPED_TEST_P(FooTest, HasPropertyA) { ... } +``` + +Now the tricky part: you need to register all test patterns using the +`REGISTER_TYPED_TEST_SUITE_P` macro before you can instantiate them. The first +argument of the macro is the test suite name; the rest are the names of the +tests in this test suite: + +```c++ +REGISTER_TYPED_TEST_SUITE_P(FooTest, + DoesBlah, HasPropertyA); +``` + +Finally, you are free to instantiate the pattern with the types you want. If you +put the above code in a header file, you can `#include` it in multiple C++ +source files and instantiate it multiple times. + +```c++ +using MyTypes = ::testing::Types; +INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); +``` + +To distinguish different instances of the pattern, the first argument to the +`INSTANTIATE_TYPED_TEST_SUITE_P` macro is a prefix that will be added to the +actual test suite name. Remember to pick unique prefixes for different +instances. + +In the special case where the type list contains only one type, you can write +that type directly without `::testing::Types<...>`, like this: + +```c++ +INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int); +``` + +You can see [sample6_unittest.cc] for a complete example. + +## Testing Private Code + +If you change your software's internal implementation, your tests should not +break as long as the change is not observable by users. Therefore, **per the +black-box testing principle, most of the time you should test your code through +its public interfaces.** + +**If you still find yourself needing to test internal implementation code, +consider if there's a better design.** The desire to test internal +implementation is often a sign that the class is doing too much. Consider +extracting an implementation class, and testing it. Then use that implementation +class in the original class. + +If you absolutely have to test non-public interface code though, you can. There +are two cases to consider: + +* Static functions ( *not* the same as static member functions!) or unnamed + namespaces, and +* Private or protected class members + +To test them, we use the following special techniques: + +* Both static functions and definitions/declarations in an unnamed namespace + are only visible within the same translation unit. To test them, you can + `#include` the entire `.cc` file being tested in your `*_test.cc` file. + (#including `.cc` files is not a good way to reuse code - you should not do + this in production code!) + + However, a better approach is to move the private code into the + `foo::internal` namespace, where `foo` is the namespace your project + normally uses, and put the private declarations in a `*-internal.h` file. + Your production `.cc` files and your tests are allowed to include this + internal header, but your clients are not. This way, you can fully test your + internal implementation without leaking it to your clients. + +* Private class members are only accessible from within the class or by + friends. To access a class' private members, you can declare your test + fixture as a friend to the class and define accessors in your fixture. Tests + using the fixture can then access the private members of your production + class via the accessors in the fixture. Note that even though your fixture + is a friend to your production class, your tests are not automatically + friends to it, as they are technically defined in sub-classes of the + fixture. + + Another way to test private members is to refactor them into an + implementation class, which is then declared in a `*-internal.h` file. Your + clients aren't allowed to include this header but your tests can. Such is + called the + [Pimpl](https://www.gamedev.net/articles/programming/general-and-gameplay-programming/the-c-pimpl-r1794/) + (Private Implementation) idiom. + + Or, you can declare an individual test as a friend of your class by adding + this line in the class body: + + ```c++ + FRIEND_TEST(TestSuiteName, TestName); + ``` + + For example, + + ```c++ + // foo.h + class Foo { + ... + private: + FRIEND_TEST(FooTest, BarReturnsZeroOnNull); + + int Bar(void* x); + }; + + // foo_test.cc + ... + TEST(FooTest, BarReturnsZeroOnNull) { + Foo foo; + EXPECT_EQ(foo.Bar(NULL), 0); // Uses Foo's private member Bar(). + } + ``` + + Pay special attention when your class is defined in a namespace. If you want + your test fixtures and tests to be friends of your class, then they must be + defined in the exact same namespace (no anonymous or inline namespaces). + + For example, if the code to be tested looks like: + + ```c++ + namespace my_namespace { + + class Foo { + friend class FooTest; + FRIEND_TEST(FooTest, Bar); + FRIEND_TEST(FooTest, Baz); + ... definition of the class Foo ... + }; + + } // namespace my_namespace + ``` + + Your test code should be something like: + + ```c++ + namespace my_namespace { + + class FooTest : public testing::Test { + protected: + ... + }; + + TEST_F(FooTest, Bar) { ... } + TEST_F(FooTest, Baz) { ... } + + } // namespace my_namespace + ``` + +## "Catching" Failures + +If you are building a testing utility on top of googletest, you'll want to test +your utility. What framework would you use to test it? googletest, of course. + +The challenge is to verify that your testing utility reports failures correctly. +In frameworks that report a failure by throwing an exception, you could catch +the exception and assert on it. But googletest doesn't use exceptions, so how do +we test that a piece of code generates an expected failure? + +`"gtest/gtest-spi.h"` contains some constructs to do this. +After #including this header, you can use + +```c++ + EXPECT_FATAL_FAILURE(statement, substring); +``` + +to assert that `statement` generates a fatal (e.g. `ASSERT_*`) failure in the +current thread whose message contains the given `substring`, or use + +```c++ + EXPECT_NONFATAL_FAILURE(statement, substring); +``` + +if you are expecting a non-fatal (e.g. `EXPECT_*`) failure. + +Only failures in the current thread are checked to determine the result of this +type of expectations. If `statement` creates new threads, failures in these +threads are also ignored. If you want to catch failures in other threads as +well, use one of the following macros instead: + +```c++ + EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substring); + EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substring); +``` + +{: .callout .note} +NOTE: Assertions from multiple threads are currently not supported on Windows. + +For technical reasons, there are some caveats: + +1. You cannot stream a failure message to either macro. + +2. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot reference + local non-static variables or non-static members of `this` object. + +3. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot return a + value. + +## Registering tests programmatically + +The `TEST` macros handle the vast majority of all use cases, but there are few +where runtime registration logic is required. For those cases, the framework +provides the `::testing::RegisterTest` that allows callers to register arbitrary +tests dynamically. + +This is an advanced API only to be used when the `TEST` macros are insufficient. +The macros should be preferred when possible, as they avoid most of the +complexity of calling this function. + +It provides the following signature: + +```c++ +template +TestInfo* RegisterTest(const char* test_suite_name, const char* test_name, + const char* type_param, const char* value_param, + const char* file, int line, Factory factory); +``` + +The `factory` argument is a factory callable (move-constructible) object or +function pointer that creates a new instance of the Test object. It handles +ownership to the caller. The signature of the callable is `Fixture*()`, where +`Fixture` is the test fixture class for the test. All tests registered with the +same `test_suite_name` must return the same fixture type. This is checked at +runtime. + +The framework will infer the fixture class from the factory and will call the +`SetUpTestSuite` and `TearDownTestSuite` for it. + +Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is +undefined. + +Use case example: + +```c++ +class MyFixture : public testing::Test { + public: + // All of these optional, just like in regular macro usage. + static void SetUpTestSuite() { ... } + static void TearDownTestSuite() { ... } + void SetUp() override { ... } + void TearDown() override { ... } +}; + +class MyTest : public MyFixture { + public: + explicit MyTest(int data) : data_(data) {} + void TestBody() override { ... } + + private: + int data_; +}; + +void RegisterMyTests(const std::vector& values) { + for (int v : values) { + testing::RegisterTest( + "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr, + std::to_string(v).c_str(), + __FILE__, __LINE__, + // Important to use the fixture type as the return type here. + [=]() -> MyFixture* { return new MyTest(v); }); + } +} +... +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + std::vector values_to_test = LoadValuesFromConfig(); + RegisterMyTests(values_to_test); + ... + return RUN_ALL_TESTS(); +} +``` + +## Getting the Current Test's Name + +Sometimes a function may need to know the name of the currently running test. +For example, you may be using the `SetUp()` method of your test fixture to set +the golden file name based on which test is running. The +[`TestInfo`](reference/testing.md#TestInfo) class has this information. + +To obtain a `TestInfo` object for the currently running test, call +`current_test_info()` on the [`UnitTest`](reference/testing.md#UnitTest) +singleton object: + +```c++ + // Gets information about the currently running test. + // Do NOT delete the returned object - it's managed by the UnitTest class. + const testing::TestInfo* const test_info = + testing::UnitTest::GetInstance()->current_test_info(); + + printf("We are in test %s of test suite %s.\n", + test_info->name(), + test_info->test_suite_name()); +``` + +`current_test_info()` returns a null pointer if no test is running. In +particular, you cannot find the test suite name in `SetUpTestSuite()`, +`TearDownTestSuite()` (where you know the test suite name implicitly), or +functions called from them. + +## Extending googletest by Handling Test Events + +googletest provides an **event listener API** to let you receive notifications +about the progress of a test program and test failures. The events you can +listen to include the start and end of the test program, a test suite, or a test +method, among others. You may use this API to augment or replace the standard +console output, replace the XML output, or provide a completely different form +of output, such as a GUI or a database. You can also use test events as +checkpoints to implement a resource leak checker, for example. + +### Defining Event Listeners + +To define a event listener, you subclass either +[`testing::TestEventListener`](reference/testing.md#TestEventListener) or +[`testing::EmptyTestEventListener`](reference/testing.md#EmptyTestEventListener) +The former is an (abstract) interface, where *each pure virtual method can be +overridden to handle a test event* (For example, when a test starts, the +`OnTestStart()` method will be called.). The latter provides an empty +implementation of all methods in the interface, such that a subclass only needs +to override the methods it cares about. + +When an event is fired, its context is passed to the handler function as an +argument. The following argument types are used: + +* UnitTest reflects the state of the entire test program, +* TestSuite has information about a test suite, which can contain one or more + tests, +* TestInfo contains the state of a test, and +* TestPartResult represents the result of a test assertion. + +An event handler function can examine the argument it receives to find out +interesting information about the event and the test program's state. + +Here's an example: + +```c++ + class MinimalistPrinter : public testing::EmptyTestEventListener { + // Called before a test starts. + void OnTestStart(const testing::TestInfo& test_info) override { + printf("*** Test %s.%s starting.\n", + test_info.test_suite_name(), test_info.name()); + } + + // Called after a failed assertion or a SUCCESS(). + void OnTestPartResult(const testing::TestPartResult& test_part_result) override { + printf("%s in %s:%d\n%s\n", + test_part_result.failed() ? "*** Failure" : "Success", + test_part_result.file_name(), + test_part_result.line_number(), + test_part_result.summary()); + } + + // Called after a test ends. + void OnTestEnd(const testing::TestInfo& test_info) override { + printf("*** Test %s.%s ending.\n", + test_info.test_suite_name(), test_info.name()); + } + }; +``` + +### Using Event Listeners + +To use the event listener you have defined, add an instance of it to the +googletest event listener list (represented by class +[`TestEventListeners`](reference/testing.md#TestEventListeners) - note the "s" +at the end of the name) in your `main()` function, before calling +`RUN_ALL_TESTS()`: + +```c++ +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + // Gets hold of the event listener list. + testing::TestEventListeners& listeners = + testing::UnitTest::GetInstance()->listeners(); + // Adds a listener to the end. googletest takes the ownership. + listeners.Append(new MinimalistPrinter); + return RUN_ALL_TESTS(); +} +``` + +There's only one problem: the default test result printer is still in effect, so +its output will mingle with the output from your minimalist printer. To suppress +the default printer, just release it from the event listener list and delete it. +You can do so by adding one line: + +```c++ + ... + delete listeners.Release(listeners.default_result_printer()); + listeners.Append(new MinimalistPrinter); + return RUN_ALL_TESTS(); +``` + +Now, sit back and enjoy a completely different output from your tests. For more +details, see [sample9_unittest.cc]. + +[sample9_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample9_unittest.cc "Event listener example" + +You may append more than one listener to the list. When an `On*Start()` or +`OnTestPartResult()` event is fired, the listeners will receive it in the order +they appear in the list (since new listeners are added to the end of the list, +the default text printer and the default XML generator will receive the event +first). An `On*End()` event will be received by the listeners in the *reverse* +order. This allows output by listeners added later to be framed by output from +listeners added earlier. + +### Generating Failures in Listeners + +You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, `FAIL()`, etc) +when processing an event. There are some restrictions: + +1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will + cause `OnTestPartResult()` to be called recursively). +2. A listener that handles `OnTestPartResult()` is not allowed to generate any + failure. + +When you add listeners to the listener list, you should put listeners that +handle `OnTestPartResult()` *before* listeners that can generate failures. This +ensures that failures generated by the latter are attributed to the right test +by the former. + +See [sample10_unittest.cc] for an example of a failure-raising listener. + +[sample10_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample10_unittest.cc "Failure-raising listener example" + +## Running Test Programs: Advanced Options + +googletest test programs are ordinary executables. Once built, you can run them +directly and affect their behavior via the following environment variables +and/or command line flags. For the flags to work, your programs must call +`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. + +To see a list of supported flags and their usage, please run your test program +with the `--help` flag. You can also use `-h`, `-?`, or `/?` for short. + +If an option is specified both by an environment variable and by a flag, the +latter takes precedence. + +### Selecting Tests + +#### Listing Test Names + +Sometimes it is necessary to list the available tests in a program before +running them so that a filter may be applied if needed. Including the flag +`--gtest_list_tests` overrides all other flags and lists tests in the following +format: + +```none +TestSuite1. + TestName1 + TestName2 +TestSuite2. + TestName +``` + +None of the tests listed are actually run if the flag is provided. There is no +corresponding environment variable for this flag. + +#### Running a Subset of the Tests + +By default, a googletest program runs all tests the user has defined. Sometimes, +you want to run only a subset of the tests (e.g. for debugging or quickly +verifying a change). If you set the `GTEST_FILTER` environment variable or the +`--gtest_filter` flag to a filter string, googletest will only run the tests +whose full names (in the form of `TestSuiteName.TestName`) match the filter. + +The format of a filter is a '`:`'-separated list of wildcard patterns (called +the *positive patterns*) optionally followed by a '`-`' and another +'`:`'-separated pattern list (called the *negative patterns*). A test matches +the filter if and only if it matches any of the positive patterns but does not +match any of the negative patterns. + +A pattern may contain `'*'` (matches any string) or `'?'` (matches any single +character). For convenience, the filter `'*-NegativePatterns'` can be also +written as `'-NegativePatterns'`. + +For example: + +* `./foo_test` Has no flag, and thus runs all its tests. +* `./foo_test --gtest_filter=*` Also runs everything, due to the single + match-everything `*` value. +* `./foo_test --gtest_filter=FooTest.*` Runs everything in test suite + `FooTest` . +* `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full + name contains either `"Null"` or `"Constructor"` . +* `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests. +* `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test + suite `FooTest` except `FooTest.Bar`. +* `./foo_test --gtest_filter=FooTest.*:BarTest.*-FooTest.Bar:BarTest.Foo` Runs + everything in test suite `FooTest` except `FooTest.Bar` and everything in + test suite `BarTest` except `BarTest.Foo`. + +#### Stop test execution upon first failure + +By default, a googletest program runs all tests the user has defined. In some +cases (e.g. iterative test development & execution) it may be desirable stop +test execution upon first failure (trading improved latency for completeness). +If `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set, +the test runner will stop execution as soon as the first test failure is found. + +#### Temporarily Disabling Tests + +If you have a broken test that you cannot fix right away, you can add the +`DISABLED_` prefix to its name. This will exclude it from execution. This is +better than commenting out the code or using `#if 0`, as disabled tests are +still compiled (and thus won't rot). + +If you need to disable all tests in a test suite, you can either add `DISABLED_` +to the front of the name of each test, or alternatively add it to the front of +the test suite name. + +For example, the following tests won't be run by googletest, even though they +will still be compiled: + +```c++ +// Tests that Foo does Abc. +TEST(FooTest, DISABLED_DoesAbc) { ... } + +class DISABLED_BarTest : public testing::Test { ... }; + +// Tests that Bar does Xyz. +TEST_F(DISABLED_BarTest, DoesXyz) { ... } +``` + +{: .callout .note} +NOTE: This feature should only be used for temporary pain-relief. You still have +to fix the disabled tests at a later date. As a reminder, googletest will print +a banner warning you if a test program contains any disabled tests. + +{: .callout .tip} +TIP: You can easily count the number of disabled tests you have using +`grep`. This number can be used as a metric for +improving your test quality. + +#### Temporarily Enabling Disabled Tests + +To include disabled tests in test execution, just invoke the test program with +the `--gtest_also_run_disabled_tests` flag or set the +`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other than `0`. +You can combine this with the `--gtest_filter` flag to further select which +disabled tests to run. + +### Repeating the Tests + +Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it +will fail only 1% of the time, making it rather hard to reproduce the bug under +a debugger. This can be a major source of frustration. + +The `--gtest_repeat` flag allows you to repeat all (or selected) test methods in +a program many times. Hopefully, a flaky test will eventually fail and give you +a chance to debug. Here's how to use it: + +```none +$ foo_test --gtest_repeat=1000 +Repeat foo_test 1000 times and don't stop at failures. + +$ foo_test --gtest_repeat=-1 +A negative count means repeating forever. + +$ foo_test --gtest_repeat=1000 --gtest_break_on_failure +Repeat foo_test 1000 times, stopping at the first failure. This +is especially useful when running under a debugger: when the test +fails, it will drop into the debugger and you can then inspect +variables and stacks. + +$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar.* +Repeat the tests whose name matches the filter 1000 times. +``` + +If your test program contains +[global set-up/tear-down](#global-set-up-and-tear-down) code, it will be +repeated in each iteration as well, as the flakiness may be in it. You can also +specify the repeat count by setting the `GTEST_REPEAT` environment variable. + +### Shuffling the Tests + +You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE` +environment variable to `1`) to run the tests in a program in a random order. +This helps to reveal bad dependencies between tests. + +By default, googletest uses a random seed calculated from the current time. +Therefore you'll get a different order every time. The console output includes +the random seed value, such that you can reproduce an order-related test failure +later. To specify the random seed explicitly, use the `--gtest_random_seed=SEED` +flag (or set the `GTEST_RANDOM_SEED` environment variable), where `SEED` is an +integer in the range [0, 99999]. The seed value 0 is special: it tells +googletest to do the default behavior of calculating the seed from the current +time. + +If you combine this with `--gtest_repeat=N`, googletest will pick a different +random seed and re-shuffle the tests in each iteration. + +### Distributing Test Functions to Multiple Machines + +If you have more than one machine you can use to run a test program, you might +want to run the test functions in parallel and get the result faster. We call +this technique *sharding*, where each machine is called a *shard*. + +GoogleTest is compatible with test sharding. To take advantage of this feature, +your test runner (not part of GoogleTest) needs to do the following: + +1. Allocate a number of machines (shards) to run the tests. +1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total + number of shards. It must be the same for all shards. +1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index + of the shard. Different shards must be assigned different indices, which + must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`. +1. Run the same test program on all shards. When GoogleTest sees the above two + environment variables, it will select a subset of the test functions to run. + Across all shards, each test function in the program will be run exactly + once. +1. Wait for all shards to finish, then collect and report the results. + +Your project may have tests that were written without GoogleTest and thus don't +understand this protocol. In order for your test runner to figure out which test +supports sharding, it can set the environment variable `GTEST_SHARD_STATUS_FILE` +to a non-existent file path. If a test program supports sharding, it will create +this file to acknowledge that fact; otherwise it will not create it. The actual +contents of the file are not important at this time, although we may put some +useful information in it in the future. + +Here's an example to make it clear. Suppose you have a test program `foo_test` +that contains the following 5 test functions: + +``` +TEST(A, V) +TEST(A, W) +TEST(B, X) +TEST(B, Y) +TEST(B, Z) +``` + +Suppose you have 3 machines at your disposal. To run the test functions in +parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and set +`GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. Then you would +run the same `foo_test` on each machine. + +GoogleTest reserves the right to change how the work is distributed across the +shards, but here's one possible scenario: + +* Machine #0 runs `A.V` and `B.X`. +* Machine #1 runs `A.W` and `B.Y`. +* Machine #2 runs `B.Z`. + +### Controlling Test Output + +#### Colored Terminal Output + +googletest can use colors in its terminal output to make it easier to spot the +important information: + +
...
+[----------] 1 test from FooTest
+[ RUN      ] FooTest.DoesAbc
+[       OK ] FooTest.DoesAbc
+[----------] 2 tests from BarTest
+[ RUN      ] BarTest.HasXyzProperty
+[       OK ] BarTest.HasXyzProperty
+[ RUN      ] BarTest.ReturnsTrueOnSuccess
+... some error messages ...
+[   FAILED ] BarTest.ReturnsTrueOnSuccess
+...
+[==========] 30 tests from 14 test suites ran.
+[   PASSED ] 28 tests.
+[   FAILED ] 2 tests, listed below:
+[   FAILED ] BarTest.ReturnsTrueOnSuccess
+[   FAILED ] AnotherTest.DoesXyz
+
+ 2 FAILED TESTS
+
+ +You can set the `GTEST_COLOR` environment variable or the `--gtest_color` +command line flag to `yes`, `no`, or `auto` (the default) to enable colors, +disable colors, or let googletest decide. When the value is `auto`, googletest +will use colors if and only if the output goes to a terminal and (on non-Windows +platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`. + +#### Suppressing test passes + +By default, googletest prints 1 line of output for each test, indicating if it +passed or failed. To show only test failures, run the test program with +`--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`. + +#### Suppressing the Elapsed Time + +By default, googletest prints the time it takes to run each test. To disable +that, run the test program with the `--gtest_print_time=0` command line flag, or +set the GTEST_PRINT_TIME environment variable to `0`. + +#### Suppressing UTF-8 Text Output + +In case of assertion failures, googletest prints expected and actual values of +type `string` both as hex-encoded strings as well as in readable UTF-8 text if +they contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8 +text because, for example, you don't have an UTF-8 compatible output medium, run +the test program with `--gtest_print_utf8=0` or set the `GTEST_PRINT_UTF8` +environment variable to `0`. + +#### Generating an XML Report + +googletest can emit a detailed XML report to a file in addition to its normal +textual output. The report contains the duration of each test, and thus can help +you identify slow tests. + +To generate the XML report, set the `GTEST_OUTPUT` environment variable or the +`--gtest_output` flag to the string `"xml:path_to_output_file"`, which will +create the file at the given location. You can also just use the string `"xml"`, +in which case the output can be found in the `test_detail.xml` file in the +current directory. + +If you specify a directory (for example, `"xml:output/directory/"` on Linux or +`"xml:output\directory\"` on Windows), googletest will create the XML file in +that directory, named after the test executable (e.g. `foo_test.xml` for test +program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left +over from a previous run), googletest will pick a different name (e.g. +`foo_test_1.xml`) to avoid overwriting it. + +The report is based on the `junitreport` Ant task. Since that format was +originally intended for Java, a little interpretation is required to make it +apply to googletest tests, as shown here: + +```xml + + + + + + + + + +``` + +* The root `` element corresponds to the entire test program. +* `` elements correspond to googletest test suites. +* `` elements correspond to googletest test functions. + +For instance, the following program + +```c++ +TEST(MathTest, Addition) { ... } +TEST(MathTest, Subtraction) { ... } +TEST(LogicTest, NonContradiction) { ... } +``` + +could generate this report: + +```xml + + + + + ... + ... + + + + + + + + + +``` + +Things to note: + +* The `tests` attribute of a `` or `` element tells how + many test functions the googletest program or test suite contains, while the + `failures` attribute tells how many of them failed. + +* The `time` attribute expresses the duration of the test, test suite, or + entire test program in seconds. + +* The `timestamp` attribute records the local date and time of the test + execution. + +* The `file` and `line` attributes record the source file location, where the + test was defined. + +* Each `` element corresponds to a single failed googletest + assertion. + +#### Generating a JSON Report + +googletest can also emit a JSON report as an alternative format to XML. To +generate the JSON report, set the `GTEST_OUTPUT` environment variable or the +`--gtest_output` flag to the string `"json:path_to_output_file"`, which will +create the file at the given location. You can also just use the string +`"json"`, in which case the output can be found in the `test_detail.json` file +in the current directory. + +The report format conforms to the following JSON Schema: + +```json +{ + "$schema": "http://json-schema.org/schema#", + "type": "object", + "definitions": { + "TestCase": { + "type": "object", + "properties": { + "name": { "type": "string" }, + "tests": { "type": "integer" }, + "failures": { "type": "integer" }, + "disabled": { "type": "integer" }, + "time": { "type": "string" }, + "testsuite": { + "type": "array", + "items": { + "$ref": "#/definitions/TestInfo" + } + } + } + }, + "TestInfo": { + "type": "object", + "properties": { + "name": { "type": "string" }, + "file": { "type": "string" }, + "line": { "type": "integer" }, + "status": { + "type": "string", + "enum": ["RUN", "NOTRUN"] + }, + "time": { "type": "string" }, + "classname": { "type": "string" }, + "failures": { + "type": "array", + "items": { + "$ref": "#/definitions/Failure" + } + } + } + }, + "Failure": { + "type": "object", + "properties": { + "failures": { "type": "string" }, + "type": { "type": "string" } + } + } + }, + "properties": { + "tests": { "type": "integer" }, + "failures": { "type": "integer" }, + "disabled": { "type": "integer" }, + "errors": { "type": "integer" }, + "timestamp": { + "type": "string", + "format": "date-time" + }, + "time": { "type": "string" }, + "name": { "type": "string" }, + "testsuites": { + "type": "array", + "items": { + "$ref": "#/definitions/TestCase" + } + } + } +} +``` + +The report uses the format that conforms to the following Proto3 using the +[JSON encoding](https://developers.google.com/protocol-buffers/docs/proto3#json): + +```proto +syntax = "proto3"; + +package googletest; + +import "google/protobuf/timestamp.proto"; +import "google/protobuf/duration.proto"; + +message UnitTest { + int32 tests = 1; + int32 failures = 2; + int32 disabled = 3; + int32 errors = 4; + google.protobuf.Timestamp timestamp = 5; + google.protobuf.Duration time = 6; + string name = 7; + repeated TestCase testsuites = 8; +} + +message TestCase { + string name = 1; + int32 tests = 2; + int32 failures = 3; + int32 disabled = 4; + int32 errors = 5; + google.protobuf.Duration time = 6; + repeated TestInfo testsuite = 7; +} + +message TestInfo { + string name = 1; + string file = 6; + int32 line = 7; + enum Status { + RUN = 0; + NOTRUN = 1; + } + Status status = 2; + google.protobuf.Duration time = 3; + string classname = 4; + message Failure { + string failures = 1; + string type = 2; + } + repeated Failure failures = 5; +} +``` + +For instance, the following program + +```c++ +TEST(MathTest, Addition) { ... } +TEST(MathTest, Subtraction) { ... } +TEST(LogicTest, NonContradiction) { ... } +``` + +could generate this report: + +```json +{ + "tests": 3, + "failures": 1, + "errors": 0, + "time": "0.035s", + "timestamp": "2011-10-31T18:52:42Z", + "name": "AllTests", + "testsuites": [ + { + "name": "MathTest", + "tests": 2, + "failures": 1, + "errors": 0, + "time": "0.015s", + "testsuite": [ + { + "name": "Addition", + "file": "test.cpp", + "line": 1, + "status": "RUN", + "time": "0.007s", + "classname": "", + "failures": [ + { + "message": "Value of: add(1, 1)\n Actual: 3\nExpected: 2", + "type": "" + }, + { + "message": "Value of: add(1, -1)\n Actual: 1\nExpected: 0", + "type": "" + } + ] + }, + { + "name": "Subtraction", + "file": "test.cpp", + "line": 2, + "status": "RUN", + "time": "0.005s", + "classname": "" + } + ] + }, + { + "name": "LogicTest", + "tests": 1, + "failures": 0, + "errors": 0, + "time": "0.005s", + "testsuite": [ + { + "name": "NonContradiction", + "file": "test.cpp", + "line": 3, + "status": "RUN", + "time": "0.005s", + "classname": "" + } + ] + } + ] +} +``` + +{: .callout .important} +IMPORTANT: The exact format of the JSON document is subject to change. + +### Controlling How Failures Are Reported + +#### Detecting Test Premature Exit + +Google Test implements the _premature-exit-file_ protocol for test runners to +catch any kind of unexpected exits of test programs. Upon start, Google Test +creates the file which will be automatically deleted after all work has been +finished. Then, the test runner can check if this file exists. In case the file +remains undeleted, the inspected test has exited prematurely. + +This feature is enabled only if the `TEST_PREMATURE_EXIT_FILE` environment +variable has been set. + +#### Turning Assertion Failures into Break-Points + +When running test programs under a debugger, it's very convenient if the +debugger can catch an assertion failure and automatically drop into interactive +mode. googletest's *break-on-failure* mode supports this behavior. + +To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value +other than `0`. Alternatively, you can use the `--gtest_break_on_failure` +command line flag. + +#### Disabling Catching Test-Thrown Exceptions + +googletest can be used either with or without exceptions enabled. If a test +throws a C++ exception or (on Windows) a structured exception (SEH), by default +googletest catches it, reports it as a test failure, and continues with the next +test method. This maximizes the coverage of a test run. Also, on Windows an +uncaught exception will cause a pop-up window, so catching the exceptions allows +you to run the tests automatically. + +When debugging the test failures, however, you may instead want the exceptions +to be handled by the debugger, such that you can examine the call stack when an +exception is thrown. To achieve that, set the `GTEST_CATCH_EXCEPTIONS` +environment variable to `0`, or use the `--gtest_catch_exceptions=0` flag when +running the tests. + +### Sanitizer Integration + +The +[Undefined Behavior Sanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html), +[Address Sanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer), +and +[Thread Sanitizer](https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual) +all provide weak functions that you can override to trigger explicit failures +when they detect sanitizer errors, such as creating a reference from `nullptr`. +To override these functions, place definitions for them in a source file that +you compile as part of your main binary: + +``` +extern "C" { +void __ubsan_on_report() { + FAIL() << "Encountered an undefined behavior sanitizer error"; +} +void __asan_on_error() { + FAIL() << "Encountered an address sanitizer error"; +} +void __tsan_on_report() { + FAIL() << "Encountered a thread sanitizer error"; +} +} // extern "C" +``` + +After compiling your project with one of the sanitizers enabled, if a particular +test triggers a sanitizer error, googletest will report that it failed. diff --git a/third_party/googletest/docs/assets/css/style.scss b/third_party/googletest/docs/assets/css/style.scss new file mode 100644 index 0000000..bb30f41 --- /dev/null +++ b/third_party/googletest/docs/assets/css/style.scss @@ -0,0 +1,5 @@ +--- +--- + +@import "jekyll-theme-primer"; +@import "main"; diff --git a/third_party/googletest/docs/community_created_documentation.md b/third_party/googletest/docs/community_created_documentation.md new file mode 100644 index 0000000..4569075 --- /dev/null +++ b/third_party/googletest/docs/community_created_documentation.md @@ -0,0 +1,7 @@ +# Community-Created Documentation + +The following is a list, in no particular order, of links to documentation +created by the Googletest community. + +* [Googlemock Insights](https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/googletest/insights.md), + by [ElectricRCAircraftGuy](https://github.com/ElectricRCAircraftGuy) diff --git a/third_party/googletest/docs/faq.md b/third_party/googletest/docs/faq.md new file mode 100644 index 0000000..c849aff --- /dev/null +++ b/third_party/googletest/docs/faq.md @@ -0,0 +1,692 @@ +# GoogleTest FAQ + +## Why should test suite names and test names not contain underscore? + +{: .callout .note} +Note: GoogleTest reserves underscore (`_`) for special purpose keywords, such as +[the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition +to the following rationale. + +Underscore (`_`) is special, as C++ reserves the following to be used by the +compiler and the standard library: + +1. any identifier that starts with an `_` followed by an upper-case letter, and +2. any identifier that contains two consecutive underscores (i.e. `__`) + *anywhere* in its name. + +User code is *prohibited* from using such identifiers. + +Now let's look at what this means for `TEST` and `TEST_F`. + +Currently `TEST(TestSuiteName, TestName)` generates a class named +`TestSuiteName_TestName_Test`. What happens if `TestSuiteName` or `TestName` +contains `_`? + +1. If `TestSuiteName` starts with an `_` followed by an upper-case letter (say, + `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus + invalid. +2. If `TestSuiteName` ends with an `_` (say, `Foo_`), we get + `Foo__TestName_Test`, which is invalid. +3. If `TestName` starts with an `_` (say, `_Bar`), we get + `TestSuiteName__Bar_Test`, which is invalid. +4. If `TestName` ends with an `_` (say, `Bar_`), we get + `TestSuiteName_Bar__Test`, which is invalid. + +So clearly `TestSuiteName` and `TestName` cannot start or end with `_` +(Actually, `TestSuiteName` can start with `_` -- as long as the `_` isn't +followed by an upper-case letter. But that's getting complicated. So for +simplicity we just say that it cannot start with `_`.). + +It may seem fine for `TestSuiteName` and `TestName` to contain `_` in the +middle. However, consider this: + +```c++ +TEST(Time, Flies_Like_An_Arrow) { ... } +TEST(Time_Flies, Like_An_Arrow) { ... } +``` + +Now, the two `TEST`s will both generate the same class +(`Time_Flies_Like_An_Arrow_Test`). That's not good. + +So for simplicity, we just ask the users to avoid `_` in `TestSuiteName` and +`TestName`. The rule is more constraining than necessary, but it's simple and +easy to remember. It also gives GoogleTest some wiggle room in case its +implementation needs to change in the future. + +If you violate the rule, there may not be immediate consequences, but your test +may (just may) break with a new compiler (or a new version of the compiler you +are using) or with a new version of GoogleTest. Therefore it's best to follow +the rule. + +## Why does GoogleTest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`? + +First of all, you can use `nullptr` with each of these macros, e.g. +`EXPECT_EQ(ptr, nullptr)`, `EXPECT_NE(ptr, nullptr)`, `ASSERT_EQ(ptr, nullptr)`, +`ASSERT_NE(ptr, nullptr)`. This is the preferred syntax in the style guide +because `nullptr` does not have the type problems that `NULL` does. + +Due to some peculiarity of C++, it requires some non-trivial template meta +programming tricks to support using `NULL` as an argument of the `EXPECT_XX()` +and `ASSERT_XX()` macros. Therefore we only do it where it's most needed +(otherwise we make the implementation of GoogleTest harder to maintain and more +error-prone than necessary). + +Historically, the `EXPECT_EQ()` macro took the *expected* value as its first +argument and the *actual* value as the second, though this argument order is now +discouraged. It was reasonable that someone wanted +to write `EXPECT_EQ(NULL, some_expression)`, and this indeed was requested +several times. Therefore we implemented it. + +The need for `EXPECT_NE(NULL, ptr)` wasn't nearly as strong. When the assertion +fails, you already know that `ptr` must be `NULL`, so it doesn't add any +information to print `ptr` in this case. That means `EXPECT_TRUE(ptr != NULL)` +works just as well. + +If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'd have to +support `EXPECT_NE(ptr, NULL)` as well. This means using the template meta +programming tricks twice in the implementation, making it even harder to +understand and maintain. We believe the benefit doesn't justify the cost. + +Finally, with the growth of the gMock matcher library, we are encouraging people +to use the unified `EXPECT_THAT(value, matcher)` syntax more often in tests. One +significant advantage of the matcher approach is that matchers can be easily +combined to form new matchers, while the `EXPECT_NE`, etc, macros cannot be +easily combined. Therefore we want to invest more in the matchers than in the +`EXPECT_XX()` macros. + +## I need to test that different implementations of an interface satisfy some common requirements. Should I use typed tests or value-parameterized tests? + +For testing various implementations of the same interface, either typed tests or +value-parameterized tests can get it done. It's really up to you the user to +decide which is more convenient for you, depending on your particular case. Some +rough guidelines: + +* Typed tests can be easier to write if instances of the different + implementations can be created the same way, modulo the type. For example, + if all these implementations have a public default constructor (such that + you can write `new TypeParam`), or if their factory functions have the same + form (e.g. `CreateInstance()`). +* Value-parameterized tests can be easier to write if you need different code + patterns to create different implementations' instances, e.g. `new Foo` vs + `new Bar(5)`. To accommodate for the differences, you can write factory + function wrappers and pass these function pointers to the tests as their + parameters. +* When a typed test fails, the default output includes the name of the type, + which can help you quickly identify which implementation is wrong. + Value-parameterized tests only show the number of the failed iteration by + default. You will need to define a function that returns the iteration name + and pass it as the third parameter to INSTANTIATE_TEST_SUITE_P to have more + useful output. +* When using typed tests, you need to make sure you are testing against the + interface type, not the concrete types (in other words, you want to make + sure `implicit_cast(my_concrete_impl)` works, not just that + `my_concrete_impl` works). It's less likely to make mistakes in this area + when using value-parameterized tests. + +I hope I didn't confuse you more. :-) If you don't mind, I'd suggest you to give +both approaches a try. Practice is a much better way to grasp the subtle +differences between the two tools. Once you have some concrete experience, you +can much more easily decide which one to use the next time. + +## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help! + +{: .callout .note} +**Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated* +now. Please use `EqualsProto`, etc instead. + +`ProtocolMessageEquals` and `ProtocolMessageEquiv` were redefined recently and +are now less tolerant of invalid protocol buffer definitions. In particular, if +you have a `foo.proto` that doesn't fully qualify the type of a protocol message +it references (e.g. `message` where it should be `message`), you +will now get run-time errors like: + +``` +... descriptor.cc:...] Invalid proto descriptor for file "path/to/foo.proto": +... descriptor.cc:...] blah.MyMessage.my_field: ".Bar" is not defined. +``` + +If you see this, your `.proto` file is broken and needs to be fixed by making +the types fully qualified. The new definition of `ProtocolMessageEquals` and +`ProtocolMessageEquiv` just happen to reveal your bug. + +## My death test modifies some state, but the change seems lost after the death test finishes. Why? + +Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the +expected crash won't kill the test program (i.e. the parent process). As a +result, any in-memory side effects they incur are observable in their respective +sub-processes, but not in the parent process. You can think of them as running +in a parallel universe, more or less. + +In particular, if you use mocking and the death test statement invokes some mock +methods, the parent process will think the calls have never occurred. Therefore, +you may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH` +macro. + +## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a GoogleTest bug? + +Actually, the bug is in `htonl()`. + +According to `'man htonl'`, `htonl()` is a *function*, which means it's valid to +use `htonl` as a function pointer. However, in opt mode `htonl()` is defined as +a *macro*, which breaks this usage. + +Worse, the macro definition of `htonl()` uses a `gcc` extension and is *not* +standard C++. That hacky implementation has some ad hoc limitations. In +particular, it prevents you from writing `Foo()`, where `Foo` +is a template that has an integral argument. + +The implementation of `EXPECT_EQ(a, b)` uses `sizeof(... a ...)` inside a +template argument, and thus doesn't compile in opt mode when `a` contains a call +to `htonl()`. It is difficult to make `EXPECT_EQ` bypass the `htonl()` bug, as +the solution must work with different compilers on various platforms. + +## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? + +If your class has a static data member: + +```c++ +// foo.h +class Foo { + ... + static const int kBar = 100; +}; +``` + +You also need to define it *outside* of the class body in `foo.cc`: + +```c++ +const int Foo::kBar; // No initializer here. +``` + +Otherwise your code is **invalid C++**, and may break in unexpected ways. In +particular, using it in GoogleTest comparison assertions (`EXPECT_EQ`, etc) will +generate an "undefined reference" linker error. The fact that "it used to work" +doesn't mean it's valid. It just means that you were lucky. :-) + +If the declaration of the static data member is `constexpr` then it is +implicitly an `inline` definition, and a separate definition in `foo.cc` is not +needed: + +```c++ +// foo.h +class Foo { + ... + static constexpr int kBar = 100; // Defines kBar, no need to do it in foo.cc. +}; +``` + +## Can I derive a test fixture from another? + +Yes. + +Each test fixture has a corresponding and same named test suite. This means only +one test suite can use a particular fixture. Sometimes, however, multiple test +cases may want to use the same or slightly different fixtures. For example, you +may want to make sure that all of a GUI library's test suites don't leak +important system resources like fonts and brushes. + +In GoogleTest, you share a fixture among test suites by putting the shared logic +in a base test fixture, then deriving from that base a separate fixture for each +test suite that wants to use this common logic. You then use `TEST_F()` to write +tests using each derived fixture. + +Typically, your code looks like this: + +```c++ +// Defines a base test fixture. +class BaseTest : public ::testing::Test { + protected: + ... +}; + +// Derives a fixture FooTest from BaseTest. +class FooTest : public BaseTest { + protected: + void SetUp() override { + BaseTest::SetUp(); // Sets up the base fixture first. + ... additional set-up work ... + } + + void TearDown() override { + ... clean-up work for FooTest ... + BaseTest::TearDown(); // Remember to tear down the base fixture + // after cleaning up FooTest! + } + + ... functions and variables for FooTest ... +}; + +// Tests that use the fixture FooTest. +TEST_F(FooTest, Bar) { ... } +TEST_F(FooTest, Baz) { ... } + +... additional fixtures derived from BaseTest ... +``` + +If necessary, you can continue to derive test fixtures from a derived fixture. +GoogleTest has no limit on how deep the hierarchy can be. + +For a complete example using derived test fixtures, see +[sample5_unittest.cc](https://github.com/google/googletest/blob/master/googletest/samples/sample5_unittest.cc). + +## My compiler complains "void value not ignored as it ought to be." What does this mean? + +You're probably using an `ASSERT_*()` in a function that doesn't return `void`. +`ASSERT_*()` can only be used in `void` functions, due to exceptions being +disabled by our build system. Please see more details +[here](advanced.md#assertion-placement). + +## My death test hangs (or seg-faults). How do I fix it? + +In GoogleTest, death tests are run in a child process and the way they work is +delicate. To write death tests you really need to understand how they work—see +the details at [Death Assertions](reference/assertions.md#death) in the +Assertions Reference. + +In particular, death tests don't like having multiple threads in the parent +process. So the first thing you can try is to eliminate creating threads outside +of `EXPECT_DEATH()`. For example, you may want to use mocks or fake objects +instead of real ones in your tests. + +Sometimes this is impossible as some library you must use may be creating +threads before `main()` is even reached. In this case, you can try to minimize +the chance of conflicts by either moving as many activities as possible inside +`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or +leaving as few things as possible in it. Also, you can try to set the death test +style to `"threadsafe"`, which is safer but slower, and see if it helps. + +If you go with thread-safe death tests, remember that they rerun the test +program from the beginning in the child process. Therefore make sure your +program can run side-by-side with itself and is deterministic. + +In the end, this boils down to good concurrent programming. You have to make +sure that there are no race conditions or deadlocks in your program. No silver +bullet - sorry! + +## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp} + +The first thing to remember is that GoogleTest does **not** reuse the same test +fixture object across multiple tests. For each `TEST_F`, GoogleTest will create +a **fresh** test fixture object, immediately call `SetUp()`, run the test body, +call `TearDown()`, and then delete the test fixture object. + +When you need to write per-test set-up and tear-down logic, you have the choice +between using the test fixture constructor/destructor or `SetUp()/TearDown()`. +The former is usually preferred, as it has the following benefits: + +* By initializing a member variable in the constructor, we have the option to + make it `const`, which helps prevent accidental changes to its value and + makes the tests more obviously correct. +* In case we need to subclass the test fixture class, the subclass' + constructor is guaranteed to call the base class' constructor *first*, and + the subclass' destructor is guaranteed to call the base class' destructor + *afterward*. With `SetUp()/TearDown()`, a subclass may make the mistake of + forgetting to call the base class' `SetUp()/TearDown()` or call them at the + wrong time. + +You may still want to use `SetUp()/TearDown()` in the following cases: + +* C++ does not allow virtual function calls in constructors and destructors. + You can call a method declared as virtual, but it will not use dynamic + dispatch. It will use the definition from the class the constructor of which + is currently executing. This is because calling a virtual method before the + derived class constructor has a chance to run is very dangerous - the + virtual method might operate on uninitialized data. Therefore, if you need + to call a method that will be overridden in a derived class, you have to use + `SetUp()/TearDown()`. +* In the body of a constructor (or destructor), it's not possible to use the + `ASSERT_xx` macros. Therefore, if the set-up operation could cause a fatal + test failure that should prevent the test from running, it's necessary to + use `abort` and abort the whole test + executable, or to use `SetUp()` instead of a constructor. +* If the tear-down operation could throw an exception, you must use + `TearDown()` as opposed to the destructor, as throwing in a destructor leads + to undefined behavior and usually will kill your program right away. Note + that many standard libraries (like STL) may throw when exceptions are + enabled in the compiler. Therefore you should prefer `TearDown()` if you + want to write portable tests that work with or without exceptions. +* The GoogleTest team is considering making the assertion macros throw on + platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux + client-side), which will eliminate the need for the user to propagate + failures from a subroutine to its caller. Therefore, you shouldn't use + GoogleTest assertions in a destructor if your code could run on such a + platform. + +## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it? + +See details for [`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the +Assertions Reference. + +## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why? + +Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is, +instead of + +```c++ + return RUN_ALL_TESTS(); +``` + +they write + +```c++ + RUN_ALL_TESTS(); +``` + +This is **wrong and dangerous**. The testing services needs to see the return +value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your +`main()` function ignores it, your test will be considered successful even if it +has a GoogleTest assertion failure. Very bad. + +We have decided to fix this (thanks to Michael Chastain for the idea). Now, your +code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with +`gcc`. If you do so, you'll get a compiler error. + +If you see the compiler complaining about you ignoring the return value of +`RUN_ALL_TESTS()`, the fix is simple: just make sure its value is used as the +return value of `main()`. + +But how could we introduce a change that breaks existing tests? Well, in this +case, the code was already broken in the first place, so we didn't break it. :-) + +## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? + +Due to a peculiarity of C++, in order to support the syntax for streaming +messages to an `ASSERT_*`, e.g. + +```c++ + ASSERT_EQ(1, Foo()) << "blah blah" << foo; +``` + +we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and +`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the +content of your constructor/destructor to a private void member function, or +switch to `EXPECT_*()` if that works. This +[section](advanced.md#assertion-placement) in the user's guide explains it. + +## My SetUp() function is not called. Why? + +C++ is case-sensitive. Did you spell it as `Setup()`? + +Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and +wonder why it's never called. + +## I have several test suites which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. + +You don't have to. Instead of + +```c++ +class FooTest : public BaseTest {}; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +class BarTest : public BaseTest {}; + +TEST_F(BarTest, Abc) { ... } +TEST_F(BarTest, Def) { ... } +``` + +you can simply `typedef` the test fixtures: + +```c++ +typedef BaseTest FooTest; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +typedef BaseTest BarTest; + +TEST_F(BarTest, Abc) { ... } +TEST_F(BarTest, Def) { ... } +``` + +## GoogleTest output is buried in a whole bunch of LOG messages. What do I do? + +The GoogleTest output is meant to be a concise and human-friendly report. If +your test generates textual output itself, it will mix with the GoogleTest +output, making it hard to read. However, there is an easy solution to this +problem. + +Since `LOG` messages go to stderr, we decided to let GoogleTest output go to +stdout. This way, you can easily separate the two using redirection. For +example: + +```shell +$ ./my_test > gtest_output.txt +``` + +## Why should I prefer test fixtures over global variables? + +There are several good reasons: + +1. It's likely your test needs to change the states of its global variables. + This makes it difficult to keep side effects from escaping one test and + contaminating others, making debugging difficult. By using fixtures, each + test has a fresh set of variables that's different (but with the same + names). Thus, tests are kept independent of each other. +2. Global variables pollute the global namespace. +3. Test fixtures can be reused via subclassing, which cannot be done easily + with global variables. This is useful if many test suites have something in + common. + +## What can the statement argument in ASSERT_DEATH() be? + +`ASSERT_DEATH(statement, matcher)` (or any death assertion macro) can be used +wherever *`statement`* is valid. So basically *`statement`* can be any C++ +statement that makes sense in the current context. In particular, it can +reference global and/or local variables, and can be: + +* a simple function call (often the case), +* a complex expression, or +* a compound statement. + +Some examples are shown here: + +```c++ +// A death test can be a simple function call. +TEST(MyDeathTest, FunctionCall) { + ASSERT_DEATH(Xyz(5), "Xyz failed"); +} + +// Or a complex expression that references variables and functions. +TEST(MyDeathTest, ComplexExpression) { + const bool c = Condition(); + ASSERT_DEATH((c ? Func1(0) : object2.Method("test")), + "(Func1|Method) failed"); +} + +// Death assertions can be used anywhere in a function. In +// particular, they can be inside a loop. +TEST(MyDeathTest, InsideLoop) { + // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die. + for (int i = 0; i < 5; i++) { + EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors", + ::testing::Message() << "where i is " << i); + } +} + +// A death assertion can contain a compound statement. +TEST(MyDeathTest, CompoundStatement) { + // Verifies that at lease one of Bar(0), Bar(1), ..., and + // Bar(4) dies. + ASSERT_DEATH({ + for (int i = 0; i < 5; i++) { + Bar(i); + } + }, + "Bar has \\d+ errors"); +} +``` + +## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why? + +GoogleTest needs to be able to create objects of your test fixture class, so it +must have a default constructor. Normally the compiler will define one for you. +However, there are cases where you have to define your own: + +* If you explicitly declare a non-default constructor for class `FooTest` + (`DISALLOW_EVIL_CONSTRUCTORS()` does this), then you need to define a + default constructor, even if it would be empty. +* If `FooTest` has a const non-static data member, then you have to define the + default constructor *and* initialize the const member in the initializer + list of the constructor. (Early versions of `gcc` doesn't force you to + initialize the const member. It's a bug that has been fixed in `gcc 4`.) + +## Why does ASSERT_DEATH complain about previous threads that were already joined? + +With the Linux pthread library, there is no turning back once you cross the line +from a single thread to multiple threads. The first time you create a thread, a +manager thread is created in addition, so you get 3, not 2, threads. Later when +the thread you create joins the main thread, the thread count decrements by 1, +but the manager thread will never be killed, so you still have 2 threads, which +means you cannot safely run a death test. + +The new NPTL thread library doesn't suffer from this problem, as it doesn't +create a manager thread. However, if you don't control which machine your test +runs on, you shouldn't depend on this. + +## Why does GoogleTest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH? + +GoogleTest does not interleave tests from different test suites. That is, it +runs all tests in one test suite first, and then runs all tests in the next test +suite, and so on. GoogleTest does this because it needs to set up a test suite +before the first test in it is run, and tear it down afterwards. Splitting up +the test case would require multiple set-up and tear-down processes, which is +inefficient and makes the semantics unclean. + +If we were to determine the order of tests based on test name instead of test +case name, then we would have a problem with the following situation: + +```c++ +TEST_F(FooTest, AbcDeathTest) { ... } +TEST_F(FooTest, Uvw) { ... } + +TEST_F(BarTest, DefDeathTest) { ... } +TEST_F(BarTest, Xyz) { ... } +``` + +Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't +interleave tests from different test suites, we need to run all tests in the +`FooTest` case before running any test in the `BarTest` case. This contradicts +with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`. + +## But I don't like calling my entire test suite \*DeathTest when it contains both death tests and non-death tests. What do I do? + +You don't have to, but if you like, you may split up the test suite into +`FooTest` and `FooDeathTest`, where the names make it clear that they are +related: + +```c++ +class FooTest : public ::testing::Test { ... }; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +using FooDeathTest = FooTest; + +TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... } +TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... } +``` + +## GoogleTest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds? + +Printing the LOG messages generated by the statement inside `EXPECT_DEATH()` +makes it harder to search for real problems in the parent's log. Therefore, +GoogleTest only prints them when the death test has failed. + +If you really need to see such LOG messages, a workaround is to temporarily +break the death test (e.g. by changing the regex pattern it is expected to +match). Admittedly, this is a hack. We'll consider a more permanent solution +after the fork-and-exec-style death tests are implemented. + +## The compiler complains about `no match for 'operator<<'` when I use an assertion. What gives? + +If you use a user-defined type `FooType` in an assertion, you must make sure +there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function +defined such that we can print a value of `FooType`. + +In addition, if `FooType` is declared in a name space, the `<<` operator also +needs to be defined in the *same* name space. See +[Tip of the Week #49](http://abseil.io/tips/49) for details. + +## How do I suppress the memory leak messages on Windows? + +Since the statically initialized GoogleTest singleton requires allocations on +the heap, the Visual C++ memory leak detector will report memory leaks at the +end of the program run. The easiest way to avoid this is to use the +`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any +statically initialized heap objects. See MSDN for more details and additional +heap check/debug routines. + +## How can my code detect if it is running in a test? + +If you write code that sniffs whether it's running in a test and does different +things accordingly, you are leaking test-only logic into production code and +there is no easy way to ensure that the test-only code paths aren't run by +mistake in production. Such cleverness also leads to +[Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly +advise against the practice, and GoogleTest doesn't provide a way to do it. + +In general, the recommended way to cause the code to behave differently under +test is [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection). You can inject +different functionality from the test and from the production code. Since your +production code doesn't link in the for-test logic at all (the +[`testonly`](http://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure +that), there is no danger in accidentally running it. + +However, if you *really*, *really*, *really* have no choice, and if you follow +the rule of ending your test program names with `_test`, you can use the +*horrible* hack of sniffing your executable name (`argv[0]` in `main()`) to know +whether the code is under test. + +## How do I temporarily disable a test? + +If you have a broken test that you cannot fix right away, you can add the +`DISABLED_` prefix to its name. This will exclude it from execution. This is +better than commenting out the code or using `#if 0`, as disabled tests are +still compiled (and thus won't rot). + +To include disabled tests in test execution, just invoke the test program with +the `--gtest_also_run_disabled_tests` flag. + +## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces? + +Yes. + +The rule is **all test methods in the same test suite must use the same fixture +class.** This means that the following is **allowed** because both tests use the +same fixture class (`::testing::Test`). + +```c++ +namespace foo { +TEST(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace foo + +namespace bar { +TEST(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace bar +``` + +However, the following code is **not allowed** and will produce a runtime error +from GoogleTest because the test methods are using different test fixture +classes with the same test suite name. + +```c++ +namespace foo { +class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest +TEST_F(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace foo + +namespace bar { +class CoolTest : public ::testing::Test {}; // Fixture: bar::CoolTest +TEST_F(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace bar +``` diff --git a/third_party/googletest/docs/gmock_cheat_sheet.md b/third_party/googletest/docs/gmock_cheat_sheet.md new file mode 100644 index 0000000..67d075d --- /dev/null +++ b/third_party/googletest/docs/gmock_cheat_sheet.md @@ -0,0 +1,241 @@ +# gMock Cheat Sheet + +## Defining a Mock Class + +### Mocking a Normal Class {#MockClass} + +Given + +```cpp +class Foo { + public: + virtual ~Foo(); + virtual int GetSize() const = 0; + virtual string Describe(const char* name) = 0; + virtual string Describe(int type) = 0; + virtual bool Process(Bar elem, int count) = 0; +}; +``` + +(note that `~Foo()` **must** be virtual) we can define its mock as + +```cpp +#include "gmock/gmock.h" + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, GetSize, (), (const, override)); + MOCK_METHOD(string, Describe, (const char* name), (override)); + MOCK_METHOD(string, Describe, (int type), (override)); + MOCK_METHOD(bool, Process, (Bar elem, int count), (override)); +}; +``` + +To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock, +which warns on all uninteresting calls, or a "strict" mock, which treats them as +failures: + +```cpp +using ::testing::NiceMock; +using ::testing::NaggyMock; +using ::testing::StrictMock; + +NiceMock nice_foo; // The type is a subclass of MockFoo. +NaggyMock naggy_foo; // The type is a subclass of MockFoo. +StrictMock strict_foo; // The type is a subclass of MockFoo. +``` + +{: .callout .note} +**Note:** A mock object is currently naggy by default. We may make it nice by +default in the future. + +### Mocking a Class Template {#MockTemplate} + +Class templates can be mocked just like any class. + +To mock + +```cpp +template +class StackInterface { + public: + virtual ~StackInterface(); + virtual int GetSize() const = 0; + virtual void Push(const Elem& x) = 0; +}; +``` + +(note that all member functions that are mocked, including `~StackInterface()` +**must** be virtual). + +```cpp +template +class MockStack : public StackInterface { + public: + MOCK_METHOD(int, GetSize, (), (const, override)); + MOCK_METHOD(void, Push, (const Elem& x), (override)); +}; +``` + +### Specifying Calling Conventions for Mock Functions + +If your mock function doesn't use the default calling convention, you can +specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter. +For example, + +```cpp + MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE))); + MOCK_METHOD(int, Bar, (double x, double y), + (const, Calltype(STDMETHODCALLTYPE))); +``` + +where `STDMETHODCALLTYPE` is defined by `` on Windows. + +## Using Mocks in Tests {#UsingMocks} + +The typical work flow is: + +1. Import the gMock names you need to use. All gMock symbols are in the + `testing` namespace unless they are macros or otherwise noted. +2. Create the mock objects. +3. Optionally, set the default actions of the mock objects. +4. Set your expectations on the mock objects (How will they be called? What + will they do?). +5. Exercise code that uses the mock objects; if necessary, check the result + using googletest assertions. +6. When a mock object is destructed, gMock automatically verifies that all + expectations on it have been satisfied. + +Here's an example: + +```cpp +using ::testing::Return; // #1 + +TEST(BarTest, DoesThis) { + MockFoo foo; // #2 + + ON_CALL(foo, GetSize()) // #3 + .WillByDefault(Return(1)); + // ... other default actions ... + + EXPECT_CALL(foo, Describe(5)) // #4 + .Times(3) + .WillRepeatedly(Return("Category 5")); + // ... other expectations ... + + EXPECT_EQ(MyProductionFunction(&foo), "good"); // #5 +} // #6 +``` + +## Setting Default Actions {#OnCall} + +gMock has a **built-in default action** for any function that returns `void`, +`bool`, a numeric value, or a pointer. In C++11, it will additionally returns +the default-constructed value, if one exists for the given type. + +To customize the default action for functions with return type `T`, use +[`DefaultValue`](reference/mocking.md#DefaultValue). For example: + +```cpp + // Sets the default action for return type std::unique_ptr to + // creating a new Buzz every time. + DefaultValue>::SetFactory( + [] { return MakeUnique(AccessLevel::kInternal); }); + + // When this fires, the default action of MakeBuzz() will run, which + // will return a new Buzz object. + EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber()); + + auto buzz1 = mock_buzzer_.MakeBuzz("hello"); + auto buzz2 = mock_buzzer_.MakeBuzz("hello"); + EXPECT_NE(buzz1, nullptr); + EXPECT_NE(buzz2, nullptr); + EXPECT_NE(buzz1, buzz2); + + // Resets the default action for return type std::unique_ptr, + // to avoid interfere with other tests. + DefaultValue>::Clear(); +``` + +To customize the default action for a particular method of a specific mock +object, use [`ON_CALL`](reference/mocking.md#ON_CALL). `ON_CALL` has a similar +syntax to `EXPECT_CALL`, but it is used for setting default behaviors when you +do not require that the mock method is called. See +[Knowing When to Expect](gmock_cook_book.md#UseOnCall) for a more detailed +discussion. + +## Setting Expectations {#ExpectCall} + +See [`EXPECT_CALL`](reference/mocking.md#EXPECT_CALL) in the Mocking Reference. + +## Matchers {#MatcherList} + +See the [Matchers Reference](reference/matchers.md). + +## Actions {#ActionList} + +See the [Actions Reference](reference/actions.md). + +## Cardinalities {#CardinalityList} + +See the [`Times` clause](reference/mocking.md#EXPECT_CALL.Times) of +`EXPECT_CALL` in the Mocking Reference. + +## Expectation Order + +By default, expectations can be matched in *any* order. If some or all +expectations must be matched in a given order, you can use the +[`After` clause](reference/mocking.md#EXPECT_CALL.After) or +[`InSequence` clause](reference/mocking.md#EXPECT_CALL.InSequence) of +`EXPECT_CALL`, or use an [`InSequence` object](reference/mocking.md#InSequence). + +## Verifying and Resetting a Mock + +gMock will verify the expectations on a mock object when it is destructed, or +you can do it earlier: + +```cpp +using ::testing::Mock; +... +// Verifies and removes the expectations on mock_obj; +// returns true if and only if successful. +Mock::VerifyAndClearExpectations(&mock_obj); +... +// Verifies and removes the expectations on mock_obj; +// also removes the default actions set by ON_CALL(); +// returns true if and only if successful. +Mock::VerifyAndClear(&mock_obj); +``` + +Do not set new expectations after verifying and clearing a mock after its use. +Setting expectations after code that exercises the mock has undefined behavior. +See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more +information. + +You can also tell gMock that a mock object can be leaked and doesn't need to be +verified: + +```cpp +Mock::AllowLeak(&mock_obj); +``` + +## Mock Classes + +gMock defines a convenient mock class template + +```cpp +class MockFunction { + public: + MOCK_METHOD(R, Call, (A1, ..., An)); +}; +``` + +See this [recipe](gmock_cook_book.md#UsingCheckPoints) for one application of +it. + +## Flags + +| Flag | Description | +| :----------------------------- | :---------------------------------------- | +| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | +| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | diff --git a/third_party/googletest/docs/gmock_cook_book.md b/third_party/googletest/docs/gmock_cook_book.md new file mode 100644 index 0000000..8a11d86 --- /dev/null +++ b/third_party/googletest/docs/gmock_cook_book.md @@ -0,0 +1,4342 @@ +# gMock Cookbook + +You can find recipes for using gMock here. If you haven't yet, please read +[the dummy guide](gmock_for_dummies.md) first to make sure you understand the +basics. + +{: .callout .note} +**Note:** gMock lives in the `testing` name space. For readability, it is +recommended to write `using ::testing::Foo;` once in your file before using the +name `Foo` defined by gMock. We omit such `using` statements in this section for +brevity, but you should do it in your own code. + +## Creating Mock Classes + +Mock classes are defined as normal classes, using the `MOCK_METHOD` macro to +generate mocked methods. The macro gets 3 or 4 parameters: + +```cpp +class MyMock { + public: + MOCK_METHOD(ReturnType, MethodName, (Args...)); + MOCK_METHOD(ReturnType, MethodName, (Args...), (Specs...)); +}; +``` + +The first 3 parameters are simply the method declaration, split into 3 parts. +The 4th parameter accepts a closed list of qualifiers, which affect the +generated method: + +* **`const`** - Makes the mocked method a `const` method. Required if + overriding a `const` method. +* **`override`** - Marks the method with `override`. Recommended if overriding + a `virtual` method. +* **`noexcept`** - Marks the method with `noexcept`. Required if overriding a + `noexcept` method. +* **`Calltype(...)`** - Sets the call type for the method (e.g. to + `STDMETHODCALLTYPE`), useful in Windows. +* **`ref(...)`** - Marks the method with the reference qualification + specified. Required if overriding a method that has reference + qualifications. Eg `ref(&)` or `ref(&&)`. + +### Dealing with unprotected commas + +Unprotected commas, i.e. commas which are not surrounded by parentheses, prevent +`MOCK_METHOD` from parsing its arguments correctly: + +{: .bad} +```cpp +class MockFoo { + public: + MOCK_METHOD(std::pair, GetPair, ()); // Won't compile! + MOCK_METHOD(bool, CheckMap, (std::map, bool)); // Won't compile! +}; +``` + +Solution 1 - wrap with parentheses: + +{: .good} +```cpp +class MockFoo { + public: + MOCK_METHOD((std::pair), GetPair, ()); + MOCK_METHOD(bool, CheckMap, ((std::map), bool)); +}; +``` + +Note that wrapping a return or argument type with parentheses is, in general, +invalid C++. `MOCK_METHOD` removes the parentheses. + +Solution 2 - define an alias: + +{: .good} +```cpp +class MockFoo { + public: + using BoolAndInt = std::pair; + MOCK_METHOD(BoolAndInt, GetPair, ()); + using MapIntDouble = std::map; + MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool)); +}; +``` + +### Mocking Private or Protected Methods + +You must always put a mock method definition (`MOCK_METHOD`) in a `public:` +section of the mock class, regardless of the method being mocked being `public`, +`protected`, or `private` in the base class. This allows `ON_CALL` and +`EXPECT_CALL` to reference the mock function from outside of the mock class. +(Yes, C++ allows a subclass to change the access level of a virtual function in +the base class.) Example: + +```cpp +class Foo { + public: + ... + virtual bool Transform(Gadget* g) = 0; + + protected: + virtual void Resume(); + + private: + virtual int GetTimeOut(); +}; + +class MockFoo : public Foo { + public: + ... + MOCK_METHOD(bool, Transform, (Gadget* g), (override)); + + // The following must be in the public section, even though the + // methods are protected or private in the base class. + MOCK_METHOD(void, Resume, (), (override)); + MOCK_METHOD(int, GetTimeOut, (), (override)); +}; +``` + +### Mocking Overloaded Methods + +You can mock overloaded functions as usual. No special attention is required: + +```cpp +class Foo { + ... + + // Must be virtual as we'll inherit from Foo. + virtual ~Foo(); + + // Overloaded on the types and/or numbers of arguments. + virtual int Add(Element x); + virtual int Add(int times, Element x); + + // Overloaded on the const-ness of this object. + virtual Bar& GetBar(); + virtual const Bar& GetBar() const; +}; + +class MockFoo : public Foo { + ... + MOCK_METHOD(int, Add, (Element x), (override)); + MOCK_METHOD(int, Add, (int times, Element x), (override)); + + MOCK_METHOD(Bar&, GetBar, (), (override)); + MOCK_METHOD(const Bar&, GetBar, (), (const, override)); +}; +``` + +{: .callout .note} +**Note:** if you don't mock all versions of the overloaded method, the compiler +will give you a warning about some methods in the base class being hidden. To +fix that, use `using` to bring them in scope: + +```cpp +class MockFoo : public Foo { + ... + using Foo::Add; + MOCK_METHOD(int, Add, (Element x), (override)); + // We don't want to mock int Add(int times, Element x); + ... +}; +``` + +### Mocking Class Templates + +You can mock class templates just like any class. + +```cpp +template +class StackInterface { + ... + // Must be virtual as we'll inherit from StackInterface. + virtual ~StackInterface(); + + virtual int GetSize() const = 0; + virtual void Push(const Elem& x) = 0; +}; + +template +class MockStack : public StackInterface { + ... + MOCK_METHOD(int, GetSize, (), (override)); + MOCK_METHOD(void, Push, (const Elem& x), (override)); +}; +``` + +### Mocking Non-virtual Methods {#MockingNonVirtualMethods} + +gMock can mock non-virtual functions to be used in Hi-perf dependency injection. + +In this case, instead of sharing a common base class with the real class, your +mock class will be *unrelated* to the real class, but contain methods with the +same signatures. The syntax for mocking non-virtual methods is the *same* as +mocking virtual methods (just don't add `override`): + +```cpp +// A simple packet stream class. None of its members is virtual. +class ConcretePacketStream { + public: + void AppendPacket(Packet* new_packet); + const Packet* GetPacket(size_t packet_number) const; + size_t NumberOfPackets() const; + ... +}; + +// A mock packet stream class. It inherits from no other, but defines +// GetPacket() and NumberOfPackets(). +class MockPacketStream { + public: + MOCK_METHOD(const Packet*, GetPacket, (size_t packet_number), (const)); + MOCK_METHOD(size_t, NumberOfPackets, (), (const)); + ... +}; +``` + +Note that the mock class doesn't define `AppendPacket()`, unlike the real class. +That's fine as long as the test doesn't need to call it. + +Next, you need a way to say that you want to use `ConcretePacketStream` in +production code, and use `MockPacketStream` in tests. Since the functions are +not virtual and the two classes are unrelated, you must specify your choice at +*compile time* (as opposed to run time). + +One way to do it is to templatize your code that needs to use a packet stream. +More specifically, you will give your code a template type argument for the type +of the packet stream. In production, you will instantiate your template with +`ConcretePacketStream` as the type argument. In tests, you will instantiate the +same template with `MockPacketStream`. For example, you may write: + +```cpp +template +void CreateConnection(PacketStream* stream) { ... } + +template +class PacketReader { + public: + void ReadPackets(PacketStream* stream, size_t packet_num); +}; +``` + +Then you can use `CreateConnection()` and +`PacketReader` in production code, and use +`CreateConnection()` and `PacketReader` in +tests. + +```cpp + MockPacketStream mock_stream; + EXPECT_CALL(mock_stream, ...)...; + .. set more expectations on mock_stream ... + PacketReader reader(&mock_stream); + ... exercise reader ... +``` + +### Mocking Free Functions + +It is not possible to directly mock a free function (i.e. a C-style function or +a static method). If you need to, you can rewrite your code to use an interface +(abstract class). + +Instead of calling a free function (say, `OpenFile`) directly, introduce an +interface for it and have a concrete subclass that calls the free function: + +```cpp +class FileInterface { + public: + ... + virtual bool Open(const char* path, const char* mode) = 0; +}; + +class File : public FileInterface { + public: + ... + bool Open(const char* path, const char* mode) override { + return OpenFile(path, mode); + } +}; +``` + +Your code should talk to `FileInterface` to open a file. Now it's easy to mock +out the function. + +This may seem like a lot of hassle, but in practice you often have multiple +related functions that you can put in the same interface, so the per-function +syntactic overhead will be much lower. + +If you are concerned about the performance overhead incurred by virtual +functions, and profiling confirms your concern, you can combine this with the +recipe for [mocking non-virtual methods](#MockingNonVirtualMethods). + +### Old-Style `MOCK_METHODn` Macros + +Before the generic `MOCK_METHOD` macro +[was introduced in 2018](https://github.com/google/googletest/commit/c5f08bf91944ce1b19bcf414fa1760e69d20afc2), +mocks where created using a family of macros collectively called `MOCK_METHODn`. +These macros are still supported, though migration to the new `MOCK_METHOD` is +recommended. + +The macros in the `MOCK_METHODn` family differ from `MOCK_METHOD`: + +* The general structure is `MOCK_METHODn(MethodName, ReturnType(Args))`, + instead of `MOCK_METHOD(ReturnType, MethodName, (Args))`. +* The number `n` must equal the number of arguments. +* When mocking a const method, one must use `MOCK_CONST_METHODn`. +* When mocking a class template, the macro name must be suffixed with `_T`. +* In order to specify the call type, the macro name must be suffixed with + `_WITH_CALLTYPE`, and the call type is the first macro argument. + +Old macros and their new equivalents: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Simple
OldMOCK_METHOD1(Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int))
Const Method
OldMOCK_CONST_METHOD1(Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (const))
Method in a Class Template
OldMOCK_METHOD1_T(Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int))
Const Method in a Class Template
OldMOCK_CONST_METHOD1_T(Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (const))
Method with Call Type
OldMOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))
Const Method with Call Type
OldMOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))
Method with Call Type in a Class Template
OldMOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))
Const Method with Call Type in a Class Template
OldMOCK_CONST_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))
+ +### The Nice, the Strict, and the Naggy {#NiceStrictNaggy} + +If a mock method has no `EXPECT_CALL` spec but is called, we say that it's an +"uninteresting call", and the default action (which can be specified using +`ON_CALL()`) of the method will be taken. Currently, an uninteresting call will +also by default cause gMock to print a warning. + +However, sometimes you may want to ignore these uninteresting calls, and +sometimes you may want to treat them as errors. gMock lets you make the decision +on a per-mock-object basis. + +Suppose your test uses a mock class `MockFoo`: + +```cpp +TEST(...) { + MockFoo mock_foo; + EXPECT_CALL(mock_foo, DoThis()); + ... code that uses mock_foo ... +} +``` + +If a method of `mock_foo` other than `DoThis()` is called, you will get a +warning. However, if you rewrite your test to use `NiceMock` instead, +you can suppress the warning: + +```cpp +using ::testing::NiceMock; + +TEST(...) { + NiceMock mock_foo; + EXPECT_CALL(mock_foo, DoThis()); + ... code that uses mock_foo ... +} +``` + +`NiceMock` is a subclass of `MockFoo`, so it can be used wherever +`MockFoo` is accepted. + +It also works if `MockFoo`'s constructor takes some arguments, as +`NiceMock` "inherits" `MockFoo`'s constructors: + +```cpp +using ::testing::NiceMock; + +TEST(...) { + NiceMock mock_foo(5, "hi"); // Calls MockFoo(5, "hi"). + EXPECT_CALL(mock_foo, DoThis()); + ... code that uses mock_foo ... +} +``` + +The usage of `StrictMock` is similar, except that it makes all uninteresting +calls failures: + +```cpp +using ::testing::StrictMock; + +TEST(...) { + StrictMock mock_foo; + EXPECT_CALL(mock_foo, DoThis()); + ... code that uses mock_foo ... + + // The test will fail if a method of mock_foo other than DoThis() + // is called. +} +``` + +{: .callout .note} +NOTE: `NiceMock` and `StrictMock` only affects *uninteresting* calls (calls of +*methods* with no expectations); they do not affect *unexpected* calls (calls of +methods with expectations, but they don't match). See +[Understanding Uninteresting vs Unexpected Calls](#uninteresting-vs-unexpected). + +There are some caveats though (sadly they are side effects of C++'s +limitations): + +1. `NiceMock` and `StrictMock` only work for mock methods + defined using the `MOCK_METHOD` macro **directly** in the `MockFoo` class. + If a mock method is defined in a **base class** of `MockFoo`, the "nice" or + "strict" modifier may not affect it, depending on the compiler. In + particular, nesting `NiceMock` and `StrictMock` (e.g. + `NiceMock >`) is **not** supported. +2. `NiceMock` and `StrictMock` may not work correctly if the + destructor of `MockFoo` is not virtual. We would like to fix this, but it + requires cleaning up existing tests. + +Finally, you should be **very cautious** about when to use naggy or strict +mocks, as they tend to make tests more brittle and harder to maintain. When you +refactor your code without changing its externally visible behavior, ideally you +shouldn't need to update any tests. If your code interacts with a naggy mock, +however, you may start to get spammed with warnings as the result of your +change. Worse, if your code interacts with a strict mock, your tests may start +to fail and you'll be forced to fix them. Our general recommendation is to use +nice mocks (not yet the default) most of the time, use naggy mocks (the current +default) when developing or debugging tests, and use strict mocks only as the +last resort. + +### Simplifying the Interface without Breaking Existing Code {#SimplerInterfaces} + +Sometimes a method has a long list of arguments that is mostly uninteresting. +For example: + +```cpp +class LogSink { + public: + ... + virtual void send(LogSeverity severity, const char* full_filename, + const char* base_filename, int line, + const struct tm* tm_time, + const char* message, size_t message_len) = 0; +}; +``` + +This method's argument list is lengthy and hard to work with (the `message` +argument is not even 0-terminated). If we mock it as is, using the mock will be +awkward. If, however, we try to simplify this interface, we'll need to fix all +clients depending on it, which is often infeasible. + +The trick is to redispatch the method in the mock class: + +```cpp +class ScopedMockLog : public LogSink { + public: + ... + void send(LogSeverity severity, const char* full_filename, + const char* base_filename, int line, const tm* tm_time, + const char* message, size_t message_len) override { + // We are only interested in the log severity, full file name, and + // log message. + Log(severity, full_filename, std::string(message, message_len)); + } + + // Implements the mock method: + // + // void Log(LogSeverity severity, + // const string& file_path, + // const string& message); + MOCK_METHOD(void, Log, + (LogSeverity severity, const string& file_path, + const string& message)); +}; +``` + +By defining a new mock method with a trimmed argument list, we make the mock +class more user-friendly. + +This technique may also be applied to make overloaded methods more amenable to +mocking. For example, when overloads have been used to implement default +arguments: + +```cpp +class MockTurtleFactory : public TurtleFactory { + public: + Turtle* MakeTurtle(int length, int weight) override { ... } + Turtle* MakeTurtle(int length, int weight, int speed) override { ... } + + // the above methods delegate to this one: + MOCK_METHOD(Turtle*, DoMakeTurtle, ()); +}; +``` + +This allows tests that don't care which overload was invoked to avoid specifying +argument matchers: + +```cpp +ON_CALL(factory, DoMakeTurtle) + .WillByDefault(Return(MakeMockTurtle())); +``` + +### Alternative to Mocking Concrete Classes + +Often you may find yourself using classes that don't implement interfaces. In +order to test your code that uses such a class (let's call it `Concrete`), you +may be tempted to make the methods of `Concrete` virtual and then mock it. + +Try not to do that. + +Making a non-virtual function virtual is a big decision. It creates an extension +point where subclasses can tweak your class' behavior. This weakens your control +on the class because now it's harder to maintain the class invariants. You +should make a function virtual only when there is a valid reason for a subclass +to override it. + +Mocking concrete classes directly is problematic as it creates a tight coupling +between the class and the tests - any small change in the class may invalidate +your tests and make test maintenance a pain. + +To avoid such problems, many programmers have been practicing "coding to +interfaces": instead of talking to the `Concrete` class, your code would define +an interface and talk to it. Then you implement that interface as an adaptor on +top of `Concrete`. In tests, you can easily mock that interface to observe how +your code is doing. + +This technique incurs some overhead: + +* You pay the cost of virtual function calls (usually not a problem). +* There is more abstraction for the programmers to learn. + +However, it can also bring significant benefits in addition to better +testability: + +* `Concrete`'s API may not fit your problem domain very well, as you may not + be the only client it tries to serve. By designing your own interface, you + have a chance to tailor it to your need - you may add higher-level + functionalities, rename stuff, etc instead of just trimming the class. This + allows you to write your code (user of the interface) in a more natural way, + which means it will be more readable, more maintainable, and you'll be more + productive. +* If `Concrete`'s implementation ever has to change, you don't have to rewrite + everywhere it is used. Instead, you can absorb the change in your + implementation of the interface, and your other code and tests will be + insulated from this change. + +Some people worry that if everyone is practicing this technique, they will end +up writing lots of redundant code. This concern is totally understandable. +However, there are two reasons why it may not be the case: + +* Different projects may need to use `Concrete` in different ways, so the best + interfaces for them will be different. Therefore, each of them will have its + own domain-specific interface on top of `Concrete`, and they will not be the + same code. +* If enough projects want to use the same interface, they can always share it, + just like they have been sharing `Concrete`. You can check in the interface + and the adaptor somewhere near `Concrete` (perhaps in a `contrib` + sub-directory) and let many projects use it. + +You need to weigh the pros and cons carefully for your particular problem, but +I'd like to assure you that the Java community has been practicing this for a +long time and it's a proven effective technique applicable in a wide variety of +situations. :-) + +### Delegating Calls to a Fake {#DelegatingToFake} + +Some times you have a non-trivial fake implementation of an interface. For +example: + +```cpp +class Foo { + public: + virtual ~Foo() {} + virtual char DoThis(int n) = 0; + virtual void DoThat(const char* s, int* p) = 0; +}; + +class FakeFoo : public Foo { + public: + char DoThis(int n) override { + return (n > 0) ? '+' : + (n < 0) ? '-' : '0'; + } + + void DoThat(const char* s, int* p) override { + *p = strlen(s); + } +}; +``` + +Now you want to mock this interface such that you can set expectations on it. +However, you also want to use `FakeFoo` for the default behavior, as duplicating +it in the mock object is, well, a lot of work. + +When you define the mock class using gMock, you can have it delegate its default +action to a fake class you already have, using this pattern: + +```cpp +class MockFoo : public Foo { + public: + // Normal mock method definitions using gMock. + MOCK_METHOD(char, DoThis, (int n), (override)); + MOCK_METHOD(void, DoThat, (const char* s, int* p), (override)); + + // Delegates the default actions of the methods to a FakeFoo object. + // This must be called *before* the custom ON_CALL() statements. + void DelegateToFake() { + ON_CALL(*this, DoThis).WillByDefault([this](int n) { + return fake_.DoThis(n); + }); + ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) { + fake_.DoThat(s, p); + }); + } + + private: + FakeFoo fake_; // Keeps an instance of the fake in the mock. +}; +``` + +With that, you can use `MockFoo` in your tests as usual. Just remember that if +you don't explicitly set an action in an `ON_CALL()` or `EXPECT_CALL()`, the +fake will be called upon to do it.: + +```cpp +using ::testing::_; + +TEST(AbcTest, Xyz) { + MockFoo foo; + + foo.DelegateToFake(); // Enables the fake for delegation. + + // Put your ON_CALL(foo, ...)s here, if any. + + // No action specified, meaning to use the default action. + EXPECT_CALL(foo, DoThis(5)); + EXPECT_CALL(foo, DoThat(_, _)); + + int n = 0; + EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked. + foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked. + EXPECT_EQ(2, n); +} +``` + +**Some tips:** + +* If you want, you can still override the default action by providing your own + `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`. +* In `DelegateToFake()`, you only need to delegate the methods whose fake + implementation you intend to use. + +* The general technique discussed here works for overloaded methods, but + you'll need to tell the compiler which version you mean. To disambiguate a + mock function (the one you specify inside the parentheses of `ON_CALL()`), + use [this technique](#SelectOverload); to disambiguate a fake function (the + one you place inside `Invoke()`), use a `static_cast` to specify the + function's type. For instance, if class `Foo` has methods `char DoThis(int + n)` and `bool DoThis(double x) const`, and you want to invoke the latter, + you need to write `Invoke(&fake_, static_cast(&FakeFoo::DoThis))` instead of `Invoke(&fake_, &FakeFoo::DoThis)` + (The strange-looking thing inside the angled brackets of `static_cast` is + the type of a function pointer to the second `DoThis()` method.). + +* Having to mix a mock and a fake is often a sign of something gone wrong. + Perhaps you haven't got used to the interaction-based way of testing yet. Or + perhaps your interface is taking on too many roles and should be split up. + Therefore, **don't abuse this**. We would only recommend to do it as an + intermediate step when you are refactoring your code. + +Regarding the tip on mixing a mock and a fake, here's an example on why it may +be a bad sign: Suppose you have a class `System` for low-level system +operations. In particular, it does file and I/O operations. And suppose you want +to test how your code uses `System` to do I/O, and you just want the file +operations to work normally. If you mock out the entire `System` class, you'll +have to provide a fake implementation for the file operation part, which +suggests that `System` is taking on too many roles. + +Instead, you can define a `FileOps` interface and an `IOOps` interface and split +`System`'s functionalities into the two. Then you can mock `IOOps` without +mocking `FileOps`. + +### Delegating Calls to a Real Object + +When using testing doubles (mocks, fakes, stubs, and etc), sometimes their +behaviors will differ from those of the real objects. This difference could be +either intentional (as in simulating an error such that you can test the error +handling code) or unintentional. If your mocks have different behaviors than the +real objects by mistake, you could end up with code that passes the tests but +fails in production. + +You can use the *delegating-to-real* technique to ensure that your mock has the +same behavior as the real object while retaining the ability to validate calls. +This technique is very similar to the [delegating-to-fake](#DelegatingToFake) +technique, the difference being that we use a real object instead of a fake. +Here's an example: + +```cpp +using ::testing::AtLeast; + +class MockFoo : public Foo { + public: + MockFoo() { + // By default, all calls are delegated to the real object. + ON_CALL(*this, DoThis).WillByDefault([this](int n) { + return real_.DoThis(n); + }); + ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) { + real_.DoThat(s, p); + }); + ... + } + MOCK_METHOD(char, DoThis, ...); + MOCK_METHOD(void, DoThat, ...); + ... + private: + Foo real_; +}; + +... + MockFoo mock; + EXPECT_CALL(mock, DoThis()) + .Times(3); + EXPECT_CALL(mock, DoThat("Hi")) + .Times(AtLeast(1)); + ... use mock in test ... +``` + +With this, gMock will verify that your code made the right calls (with the right +arguments, in the right order, called the right number of times, etc), and a +real object will answer the calls (so the behavior will be the same as in +production). This gives you the best of both worlds. + +### Delegating Calls to a Parent Class + +Ideally, you should code to interfaces, whose methods are all pure virtual. In +reality, sometimes you do need to mock a virtual method that is not pure (i.e, +it already has an implementation). For example: + +```cpp +class Foo { + public: + virtual ~Foo(); + + virtual void Pure(int n) = 0; + virtual int Concrete(const char* str) { ... } +}; + +class MockFoo : public Foo { + public: + // Mocking a pure method. + MOCK_METHOD(void, Pure, (int n), (override)); + // Mocking a concrete method. Foo::Concrete() is shadowed. + MOCK_METHOD(int, Concrete, (const char* str), (override)); +}; +``` + +Sometimes you may want to call `Foo::Concrete()` instead of +`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub action, or +perhaps your test doesn't need to mock `Concrete()` at all (but it would be +oh-so painful to have to define a new mock class whenever you don't need to mock +one of its methods). + +You can call `Foo::Concrete()` inside an action by: + +```cpp +... + EXPECT_CALL(foo, Concrete).WillOnce([&foo](const char* str) { + return foo.Foo::Concrete(str); + }); +``` + +or tell the mock object that you don't want to mock `Concrete()`: + +```cpp +... + ON_CALL(foo, Concrete).WillByDefault([&foo](const char* str) { + return foo.Foo::Concrete(str); + }); +``` + +(Why don't we just write `{ return foo.Concrete(str); }`? If you do that, +`MockFoo::Concrete()` will be called (and cause an infinite recursion) since +`Foo::Concrete()` is virtual. That's just how C++ works.) + +## Using Matchers + +### Matching Argument Values Exactly + +You can specify exactly which arguments a mock method is expecting: + +```cpp +using ::testing::Return; +... + EXPECT_CALL(foo, DoThis(5)) + .WillOnce(Return('a')); + EXPECT_CALL(foo, DoThat("Hello", bar)); +``` + +### Using Simple Matchers + +You can use matchers to match arguments that have a certain property: + +```cpp +using ::testing::NotNull; +using ::testing::Return; +... + EXPECT_CALL(foo, DoThis(Ge(5))) // The argument must be >= 5. + .WillOnce(Return('a')); + EXPECT_CALL(foo, DoThat("Hello", NotNull())); + // The second argument must not be NULL. +``` + +A frequently used matcher is `_`, which matches anything: + +```cpp + EXPECT_CALL(foo, DoThat(_, NotNull())); +``` + +### Combining Matchers {#CombiningMatchers} + +You can build complex matchers from existing ones using `AllOf()`, +`AllOfArray()`, `AnyOf()`, `AnyOfArray()` and `Not()`: + +```cpp +using ::testing::AllOf; +using ::testing::Gt; +using ::testing::HasSubstr; +using ::testing::Ne; +using ::testing::Not; +... + // The argument must be > 5 and != 10. + EXPECT_CALL(foo, DoThis(AllOf(Gt(5), + Ne(10)))); + + // The first argument must not contain sub-string "blah". + EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")), + NULL)); +``` + +Matchers are function objects, and parametrized matchers can be composed just +like any other function. However because their types can be long and rarely +provide meaningful information, it can be easier to express them with C++14 +generic lambdas to avoid specifying types. For example, + +```cpp +using ::testing::Contains; +using ::testing::Property; + +inline constexpr auto HasFoo = [](const auto& f) { + return Property(&MyClass::foo, Contains(f)); +}; +... + EXPECT_THAT(x, HasFoo("blah")); +``` + +### Casting Matchers {#SafeMatcherCast} + +gMock matchers are statically typed, meaning that the compiler can catch your +mistake if you use a matcher of the wrong type (for example, if you use `Eq(5)` +to match a `string` argument). Good for you! + +Sometimes, however, you know what you're doing and want the compiler to give you +some slack. One example is that you have a matcher for `long` and the argument +you want to match is `int`. While the two types aren't exactly the same, there +is nothing really wrong with using a `Matcher` to match an `int` - after +all, we can first convert the `int` argument to a `long` losslessly before +giving it to the matcher. + +To support this need, gMock gives you the `SafeMatcherCast(m)` function. It +casts a matcher `m` to type `Matcher`. To ensure safety, gMock checks that +(let `U` be the type `m` accepts : + +1. Type `T` can be *implicitly* cast to type `U`; +2. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and + floating-point numbers), the conversion from `T` to `U` is not lossy (in + other words, any value representable by `T` can also be represented by `U`); + and +3. When `U` is a reference, `T` must also be a reference (as the underlying + matcher may be interested in the address of the `U` value). + +The code won't compile if any of these conditions isn't met. + +Here's one example: + +```cpp +using ::testing::SafeMatcherCast; + +// A base class and a child class. +class Base { ... }; +class Derived : public Base { ... }; + +class MockFoo : public Foo { + public: + MOCK_METHOD(void, DoThis, (Derived* derived), (override)); +}; + +... + MockFoo foo; + // m is a Matcher we got from somewhere. + EXPECT_CALL(foo, DoThis(SafeMatcherCast(m))); +``` + +If you find `SafeMatcherCast(m)` too limiting, you can use a similar function +`MatcherCast(m)`. The difference is that `MatcherCast` works as long as you +can `static_cast` type `T` to type `U`. + +`MatcherCast` essentially lets you bypass C++'s type system (`static_cast` isn't +always safe as it could throw away information, for example), so be careful not +to misuse/abuse it. + +### Selecting Between Overloaded Functions {#SelectOverload} + +If you expect an overloaded function to be called, the compiler may need some +help on which overloaded version it is. + +To disambiguate functions overloaded on the const-ness of this object, use the +`Const()` argument wrapper. + +```cpp +using ::testing::ReturnRef; + +class MockFoo : public Foo { + ... + MOCK_METHOD(Bar&, GetBar, (), (override)); + MOCK_METHOD(const Bar&, GetBar, (), (const, override)); +}; + +... + MockFoo foo; + Bar bar1, bar2; + EXPECT_CALL(foo, GetBar()) // The non-const GetBar(). + .WillOnce(ReturnRef(bar1)); + EXPECT_CALL(Const(foo), GetBar()) // The const GetBar(). + .WillOnce(ReturnRef(bar2)); +``` + +(`Const()` is defined by gMock and returns a `const` reference to its argument.) + +To disambiguate overloaded functions with the same number of arguments but +different argument types, you may need to specify the exact type of a matcher, +either by wrapping your matcher in `Matcher()`, or using a matcher whose +type is fixed (`TypedEq`, `An()`, etc): + +```cpp +using ::testing::An; +using ::testing::Matcher; +using ::testing::TypedEq; + +class MockPrinter : public Printer { + public: + MOCK_METHOD(void, Print, (int n), (override)); + MOCK_METHOD(void, Print, (char c), (override)); +}; + +TEST(PrinterTest, Print) { + MockPrinter printer; + + EXPECT_CALL(printer, Print(An())); // void Print(int); + EXPECT_CALL(printer, Print(Matcher(Lt(5)))); // void Print(int); + EXPECT_CALL(printer, Print(TypedEq('a'))); // void Print(char); + + printer.Print(3); + printer.Print(6); + printer.Print('a'); +} +``` + +### Performing Different Actions Based on the Arguments + +When a mock method is called, the *last* matching expectation that's still +active will be selected (think "newer overrides older"). So, you can make a +method do different things depending on its argument values like this: + +```cpp +using ::testing::_; +using ::testing::Lt; +using ::testing::Return; +... + // The default case. + EXPECT_CALL(foo, DoThis(_)) + .WillRepeatedly(Return('b')); + // The more specific case. + EXPECT_CALL(foo, DoThis(Lt(5))) + .WillRepeatedly(Return('a')); +``` + +Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will be +returned; otherwise `'b'` will be returned. + +### Matching Multiple Arguments as a Whole + +Sometimes it's not enough to match the arguments individually. For example, we +may want to say that the first argument must be less than the second argument. +The `With()` clause allows us to match all arguments of a mock function as a +whole. For example, + +```cpp +using ::testing::_; +using ::testing::Ne; +using ::testing::Lt; +... + EXPECT_CALL(foo, InRange(Ne(0), _)) + .With(Lt()); +``` + +says that the first argument of `InRange()` must not be 0, and must be less than +the second argument. + +The expression inside `With()` must be a matcher of type `Matcher>`, where `A1`, ..., `An` are the types of the function arguments. + +You can also write `AllArgs(m)` instead of `m` inside `.With()`. The two forms +are equivalent, but `.With(AllArgs(Lt()))` is more readable than `.With(Lt())`. + +You can use `Args(m)` to match the `n` selected arguments (as a +tuple) against `m`. For example, + +```cpp +using ::testing::_; +using ::testing::AllOf; +using ::testing::Args; +using ::testing::Lt; +... + EXPECT_CALL(foo, Blah) + .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt()))); +``` + +says that `Blah` will be called with arguments `x`, `y`, and `z` where `x < y < +z`. Note that in this example, it wasn't necessary to specify the positional +matchers. + +As a convenience and example, gMock provides some matchers for 2-tuples, +including the `Lt()` matcher above. See +[Multi-argument Matchers](reference/matchers.md#MultiArgMatchers) for the +complete list. + +Note that if you want to pass the arguments to a predicate of your own (e.g. +`.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be written to +take a `std::tuple` as its argument; gMock will pass the `n` selected arguments +as *one* single tuple to the predicate. + +### Using Matchers as Predicates + +Have you noticed that a matcher is just a fancy predicate that also knows how to +describe itself? Many existing algorithms take predicates as arguments (e.g. +those defined in STL's `` header), and it would be a shame if gMock +matchers were not allowed to participate. + +Luckily, you can use a matcher where a unary predicate functor is expected by +wrapping it inside the `Matches()` function. For example, + +```cpp +#include +#include + +using ::testing::Matches; +using ::testing::Ge; + +vector v; +... +// How many elements in v are >= 10? +const int count = count_if(v.begin(), v.end(), Matches(Ge(10))); +``` + +Since you can build complex matchers from simpler ones easily using gMock, this +gives you a way to conveniently construct composite predicates (doing the same +using STL's `` header is just painful). For example, here's a +predicate that's satisfied by any number that is >= 0, <= 100, and != 50: + +```cpp +using testing::AllOf; +using testing::Ge; +using testing::Le; +using testing::Matches; +using testing::Ne; +... +Matches(AllOf(Ge(0), Le(100), Ne(50))) +``` + +### Using Matchers in googletest Assertions + +See [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions +Reference. + +### Using Predicates as Matchers + +gMock provides a set of built-in matchers for matching arguments with expected +values—see the [Matchers Reference](reference/matchers.md) for more information. +In case you find the built-in set lacking, you can use an arbitrary unary +predicate function or functor as a matcher - as long as the predicate accepts a +value of the type you want. You do this by wrapping the predicate inside the +`Truly()` function, for example: + +```cpp +using ::testing::Truly; + +int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; } +... + // Bar() must be called with an even number. + EXPECT_CALL(foo, Bar(Truly(IsEven))); +``` + +Note that the predicate function / functor doesn't have to return `bool`. It +works as long as the return value can be used as the condition in in statement +`if (condition) ...`. + +### Matching Arguments that Are Not Copyable + +When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, gMock saves away a copy of +`bar`. When `Foo()` is called later, gMock compares the argument to `Foo()` with +the saved copy of `bar`. This way, you don't need to worry about `bar` being +modified or destroyed after the `EXPECT_CALL()` is executed. The same is true +when you use matchers like `Eq(bar)`, `Le(bar)`, and so on. + +But what if `bar` cannot be copied (i.e. has no copy constructor)? You could +define your own matcher function or callback and use it with `Truly()`, as the +previous couple of recipes have shown. Or, you may be able to get away from it +if you can guarantee that `bar` won't be changed after the `EXPECT_CALL()` is +executed. Just tell gMock that it should save a reference to `bar`, instead of a +copy of it. Here's how: + +```cpp +using ::testing::Eq; +using ::testing::Lt; +... + // Expects that Foo()'s argument == bar. + EXPECT_CALL(mock_obj, Foo(Eq(std::ref(bar)))); + + // Expects that Foo()'s argument < bar. + EXPECT_CALL(mock_obj, Foo(Lt(std::ref(bar)))); +``` + +Remember: if you do this, don't change `bar` after the `EXPECT_CALL()`, or the +result is undefined. + +### Validating a Member of an Object + +Often a mock function takes a reference to object as an argument. When matching +the argument, you may not want to compare the entire object against a fixed +object, as that may be over-specification. Instead, you may need to validate a +certain member variable or the result of a certain getter method of the object. +You can do this with `Field()` and `Property()`. More specifically, + +```cpp +Field(&Foo::bar, m) +``` + +is a matcher that matches a `Foo` object whose `bar` member variable satisfies +matcher `m`. + +```cpp +Property(&Foo::baz, m) +``` + +is a matcher that matches a `Foo` object whose `baz()` method returns a value +that satisfies matcher `m`. + +For example: + +| Expression | Description | +| :--------------------------- | :--------------------------------------- | +| `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | +| `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | + +Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no argument +and be declared as `const`. Don't use `Property()` against member functions that +you do not own, because taking addresses of functions is fragile and generally +not part of the contract of the function. + +`Field()` and `Property()` can also match plain pointers to objects. For +instance, + +```cpp +using ::testing::Field; +using ::testing::Ge; +... +Field(&Foo::number, Ge(3)) +``` + +matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`, the match +will always fail regardless of the inner matcher. + +What if you want to validate more than one members at the same time? Remember +that there are [`AllOf()` and `AllOfArray()`](#CombiningMatchers). + +Finally `Field()` and `Property()` provide overloads that take the field or +property names as the first argument to include it in the error message. This +can be useful when creating combined matchers. + +```cpp +using ::testing::AllOf; +using ::testing::Field; +using ::testing::Matcher; +using ::testing::SafeMatcherCast; + +Matcher IsFoo(const Foo& foo) { + return AllOf(Field("some_field", &Foo::some_field, foo.some_field), + Field("other_field", &Foo::other_field, foo.other_field), + Field("last_field", &Foo::last_field, foo.last_field)); +} +``` + +### Validating the Value Pointed to by a Pointer Argument + +C++ functions often take pointers as arguments. You can use matchers like +`IsNull()`, `NotNull()`, and other comparison matchers to match a pointer, but +what if you want to make sure the value *pointed to* by the pointer, instead of +the pointer itself, has a certain property? Well, you can use the `Pointee(m)` +matcher. + +`Pointee(m)` matches a pointer if and only if `m` matches the value the pointer +points to. For example: + +```cpp +using ::testing::Ge; +using ::testing::Pointee; +... + EXPECT_CALL(foo, Bar(Pointee(Ge(3)))); +``` + +expects `foo.Bar()` to be called with a pointer that points to a value greater +than or equal to 3. + +One nice thing about `Pointee()` is that it treats a `NULL` pointer as a match +failure, so you can write `Pointee(m)` instead of + +```cpp +using ::testing::AllOf; +using ::testing::NotNull; +using ::testing::Pointee; +... + AllOf(NotNull(), Pointee(m)) +``` + +without worrying that a `NULL` pointer will crash your test. + +Also, did we tell you that `Pointee()` works with both raw pointers **and** +smart pointers (`std::unique_ptr`, `std::shared_ptr`, etc)? + +What if you have a pointer to pointer? You guessed it - you can use nested +`Pointee()` to probe deeper inside the value. For example, +`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer that points +to a number less than 3 (what a mouthful...). + +### Defining a Custom Matcher Class {#CustomMatcherClass} + +Most matchers can be simply defined using [the MATCHER* macros](#NewMatchers), +which are terse and flexible, and produce good error messages. However, these +macros are not very explicit about the interfaces they create and are not always +suitable, especially for matchers that will be widely reused. + +For more advanced cases, you may need to define your own matcher class. A custom +matcher allows you to test a specific invariant property of that object. Let's +take a look at how to do so. + +Imagine you have a mock function that takes an object of type `Foo`, which has +an `int bar()` method and an `int baz()` method. You want to constrain that the +argument's `bar()` value plus its `baz()` value is a given number. (This is an +invariant.) Here's how we can write and use a matcher class to do so: + +```cpp +class BarPlusBazEqMatcher { + public: + using is_gtest_matcher = void; + + explicit BarPlusBazEqMatcher(int expected_sum) + : expected_sum_(expected_sum) {} + + bool MatchAndExplain(const Foo& foo, + std::ostream* /* listener */) const { + return (foo.bar() + foo.baz()) == expected_sum_; + } + + void DescribeTo(std::ostream* os) const { + *os << "bar() + baz() equals " << expected_sum_; + } + + void DescribeNegationTo(std::ostream* os) const { + *os << "bar() + baz() does not equal " << expected_sum_; + } + private: + const int expected_sum_; +}; + +::testing::Matcher BarPlusBazEq(int expected_sum) { + return BarPlusBazEqMatcher(expected_sum); +} + +... + Foo foo; + EXPECT_CALL(foo, BarPlusBazEq(5))...; +``` + +### Matching Containers + +Sometimes an STL container (e.g. list, vector, map, ...) is passed to a mock +function and you may want to validate it. Since most STL containers support the +`==` operator, you can write `Eq(expected_container)` or simply +`expected_container` to match a container exactly. + +Sometimes, though, you may want to be more flexible (for example, the first +element must be an exact match, but the second element can be any positive +number, and so on). Also, containers used in tests often have a small number of +elements, and having to define the expected container out-of-line is a bit of a +hassle. + +You can use the `ElementsAre()` or `UnorderedElementsAre()` matcher in such +cases: + +```cpp +using ::testing::_; +using ::testing::ElementsAre; +using ::testing::Gt; +... + MOCK_METHOD(void, Foo, (const vector& numbers), (override)); +... + EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5))); +``` + +The above matcher says that the container must have 4 elements, which must be 1, +greater than 0, anything, and 5 respectively. + +If you instead write: + +```cpp +using ::testing::_; +using ::testing::Gt; +using ::testing::UnorderedElementsAre; +... + MOCK_METHOD(void, Foo, (const vector& numbers), (override)); +... + EXPECT_CALL(mock, Foo(UnorderedElementsAre(1, Gt(0), _, 5))); +``` + +It means that the container must have 4 elements, which (under some permutation) +must be 1, greater than 0, anything, and 5 respectively. + +As an alternative you can place the arguments in a C-style array and use +`ElementsAreArray()` or `UnorderedElementsAreArray()` instead: + +```cpp +using ::testing::ElementsAreArray; +... + // ElementsAreArray accepts an array of element values. + const int expected_vector1[] = {1, 5, 2, 4, ...}; + EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1))); + + // Or, an array of element matchers. + Matcher expected_vector2[] = {1, Gt(2), _, 3, ...}; + EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2))); +``` + +In case the array needs to be dynamically created (and therefore the array size +cannot be inferred by the compiler), you can give `ElementsAreArray()` an +additional argument to specify the array size: + +```cpp +using ::testing::ElementsAreArray; +... + int* const expected_vector3 = new int[count]; + ... fill expected_vector3 with values ... + EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count))); +``` + +Use `Pair` when comparing maps or other associative containers. + +{% raw %} + +```cpp +using testing::ElementsAre; +using testing::Pair; +... + std::map m = {{"a", 1}, {"b", 2}, {"c", 3}}; + EXPECT_THAT(m, ElementsAre(Pair("a", 1), Pair("b", 2), Pair("c", 3))); +``` + +{% endraw %} + +**Tips:** + +* `ElementsAre*()` can be used to match *any* container that implements the + STL iterator pattern (i.e. it has a `const_iterator` type and supports + `begin()/end()`), not just the ones defined in STL. It will even work with + container types yet to be written - as long as they follows the above + pattern. +* You can use nested `ElementsAre*()` to match nested (multi-dimensional) + containers. +* If the container is passed by pointer instead of by reference, just write + `Pointee(ElementsAre*(...))`. +* The order of elements *matters* for `ElementsAre*()`. If you are using it + with containers whose element order are undefined (e.g. `hash_map`) you + should use `WhenSorted` around `ElementsAre`. + +### Sharing Matchers + +Under the hood, a gMock matcher object consists of a pointer to a ref-counted +implementation object. Copying matchers is allowed and very efficient, as only +the pointer is copied. When the last matcher that references the implementation +object dies, the implementation object will be deleted. + +Therefore, if you have some complex matcher that you want to use again and +again, there is no need to build it every time. Just assign it to a matcher +variable and use that variable repeatedly! For example, + +```cpp +using ::testing::AllOf; +using ::testing::Gt; +using ::testing::Le; +using ::testing::Matcher; +... + Matcher in_range = AllOf(Gt(5), Le(10)); + ... use in_range as a matcher in multiple EXPECT_CALLs ... +``` + +### Matchers must have no side-effects {#PureMatchers} + +{: .callout .warning} +WARNING: gMock does not guarantee when or how many times a matcher will be +invoked. Therefore, all matchers must be *purely functional*: they cannot have +any side effects, and the match result must not depend on anything other than +the matcher's parameters and the value being matched. + +This requirement must be satisfied no matter how a matcher is defined (e.g., if +it is one of the standard matchers, or a custom matcher). In particular, a +matcher can never call a mock function, as that will affect the state of the +mock object and gMock. + +## Setting Expectations + +### Knowing When to Expect {#UseOnCall} + +**`ON_CALL`** is likely the *single most under-utilized construct* in gMock. + +There are basically two constructs for defining the behavior of a mock object: +`ON_CALL` and `EXPECT_CALL`. The difference? `ON_CALL` defines what happens when +a mock method is called, but doesn't imply any expectation on the method +being called. `EXPECT_CALL` not only defines the behavior, but also sets an +expectation that the method will be called with the given arguments, for the +given number of times (and *in the given order* when you specify the order +too). + +Since `EXPECT_CALL` does more, isn't it better than `ON_CALL`? Not really. Every +`EXPECT_CALL` adds a constraint on the behavior of the code under test. Having +more constraints than necessary is *baaad* - even worse than not having enough +constraints. + +This may be counter-intuitive. How could tests that verify more be worse than +tests that verify less? Isn't verification the whole point of tests? + +The answer lies in *what* a test should verify. **A good test verifies the +contract of the code.** If a test over-specifies, it doesn't leave enough +freedom to the implementation. As a result, changing the implementation without +breaking the contract (e.g. refactoring and optimization), which should be +perfectly fine to do, can break such tests. Then you have to spend time fixing +them, only to see them broken again the next time the implementation is changed. + +Keep in mind that one doesn't have to verify more than one property in one test. +In fact, **it's a good style to verify only one thing in one test.** If you do +that, a bug will likely break only one or two tests instead of dozens (which +case would you rather debug?). If you are also in the habit of giving tests +descriptive names that tell what they verify, you can often easily guess what's +wrong just from the test log itself. + +So use `ON_CALL` by default, and only use `EXPECT_CALL` when you actually intend +to verify that the call is made. For example, you may have a bunch of `ON_CALL`s +in your test fixture to set the common mock behavior shared by all tests in the +same group, and write (scarcely) different `EXPECT_CALL`s in different `TEST_F`s +to verify different aspects of the code's behavior. Compared with the style +where each `TEST` has many `EXPECT_CALL`s, this leads to tests that are more +resilient to implementational changes (and thus less likely to require +maintenance) and makes the intent of the tests more obvious (so they are easier +to maintain when you do need to maintain them). + +If you are bothered by the "Uninteresting mock function call" message printed +when a mock method without an `EXPECT_CALL` is called, you may use a `NiceMock` +instead to suppress all such messages for the mock object, or suppress the +message for specific methods by adding `EXPECT_CALL(...).Times(AnyNumber())`. DO +NOT suppress it by blindly adding an `EXPECT_CALL(...)`, or you'll have a test +that's a pain to maintain. + +### Ignoring Uninteresting Calls + +If you are not interested in how a mock method is called, just don't say +anything about it. In this case, if the method is ever called, gMock will +perform its default action to allow the test program to continue. If you are not +happy with the default action taken by gMock, you can override it using +`DefaultValue::Set()` (described [here](#DefaultValue)) or `ON_CALL()`. + +Please note that once you expressed interest in a particular mock method (via +`EXPECT_CALL()`), all invocations to it must match some expectation. If this +function is called but the arguments don't match any `EXPECT_CALL()` statement, +it will be an error. + +### Disallowing Unexpected Calls + +If a mock method shouldn't be called at all, explicitly say so: + +```cpp +using ::testing::_; +... + EXPECT_CALL(foo, Bar(_)) + .Times(0); +``` + +If some calls to the method are allowed, but the rest are not, just list all the +expected calls: + +```cpp +using ::testing::AnyNumber; +using ::testing::Gt; +... + EXPECT_CALL(foo, Bar(5)); + EXPECT_CALL(foo, Bar(Gt(10))) + .Times(AnyNumber()); +``` + +A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()` statements +will be an error. + +### Understanding Uninteresting vs Unexpected Calls {#uninteresting-vs-unexpected} + +*Uninteresting* calls and *unexpected* calls are different concepts in gMock. +*Very* different. + +A call `x.Y(...)` is **uninteresting** if there's *not even a single* +`EXPECT_CALL(x, Y(...))` set. In other words, the test isn't interested in the +`x.Y()` method at all, as evident in that the test doesn't care to say anything +about it. + +A call `x.Y(...)` is **unexpected** if there are *some* `EXPECT_CALL(x, +Y(...))`s set, but none of them matches the call. Put another way, the test is +interested in the `x.Y()` method (therefore it explicitly sets some +`EXPECT_CALL` to verify how it's called); however, the verification fails as the +test doesn't expect this particular call to happen. + +**An unexpected call is always an error,** as the code under test doesn't behave +the way the test expects it to behave. + +**By default, an uninteresting call is not an error,** as it violates no +constraint specified by the test. (gMock's philosophy is that saying nothing +means there is no constraint.) However, it leads to a warning, as it *might* +indicate a problem (e.g. the test author might have forgotten to specify a +constraint). + +In gMock, `NiceMock` and `StrictMock` can be used to make a mock class "nice" or +"strict". How does this affect uninteresting calls and unexpected calls? + +A **nice mock** suppresses uninteresting call *warnings*. It is less chatty than +the default mock, but otherwise is the same. If a test fails with a default +mock, it will also fail using a nice mock instead. And vice versa. Don't expect +making a mock nice to change the test's result. + +A **strict mock** turns uninteresting call warnings into errors. So making a +mock strict may change the test's result. + +Let's look at an example: + +```cpp +TEST(...) { + NiceMock mock_registry; + EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) + .WillRepeatedly(Return("Larry Page")); + + // Use mock_registry in code under test. + ... &mock_registry ... +} +``` + +The sole `EXPECT_CALL` here says that all calls to `GetDomainOwner()` must have +`"google.com"` as the argument. If `GetDomainOwner("yahoo.com")` is called, it +will be an unexpected call, and thus an error. *Having a nice mock doesn't +change the severity of an unexpected call.* + +So how do we tell gMock that `GetDomainOwner()` can be called with some other +arguments as well? The standard technique is to add a "catch all" `EXPECT_CALL`: + +```cpp + EXPECT_CALL(mock_registry, GetDomainOwner(_)) + .Times(AnyNumber()); // catches all other calls to this method. + EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) + .WillRepeatedly(Return("Larry Page")); +``` + +Remember that `_` is the wildcard matcher that matches anything. With this, if +`GetDomainOwner("google.com")` is called, it will do what the second +`EXPECT_CALL` says; if it is called with a different argument, it will do what +the first `EXPECT_CALL` says. + +Note that the order of the two `EXPECT_CALL`s is important, as a newer +`EXPECT_CALL` takes precedence over an older one. + +For more on uninteresting calls, nice mocks, and strict mocks, read +["The Nice, the Strict, and the Naggy"](#NiceStrictNaggy). + +### Ignoring Uninteresting Arguments {#ParameterlessExpectations} + +If your test doesn't care about the parameters (it only cares about the number +or order of calls), you can often simply omit the parameter list: + +```cpp + // Expect foo.Bar( ... ) twice with any arguments. + EXPECT_CALL(foo, Bar).Times(2); + + // Delegate to the given method whenever the factory is invoked. + ON_CALL(foo_factory, MakeFoo) + .WillByDefault(&BuildFooForTest); +``` + +This functionality is only available when a method is not overloaded; to prevent +unexpected behavior it is a compilation error to try to set an expectation on a +method where the specific overload is ambiguous. You can work around this by +supplying a [simpler mock interface](#SimplerInterfaces) than the mocked class +provides. + +This pattern is also useful when the arguments are interesting, but match logic +is substantially complex. You can leave the argument list unspecified and use +SaveArg actions to [save the values for later verification](#SaveArgVerify). If +you do that, you can easily differentiate calling the method the wrong number of +times from calling it with the wrong arguments. + +### Expecting Ordered Calls {#OrderedCalls} + +Although an `EXPECT_CALL()` statement defined later takes precedence when gMock +tries to match a function call with an expectation, by default calls don't have +to happen in the order `EXPECT_CALL()` statements are written. For example, if +the arguments match the matchers in the second `EXPECT_CALL()`, but not those in +the first and third, then the second expectation will be used. + +If you would rather have all calls occur in the order of the expectations, put +the `EXPECT_CALL()` statements in a block where you define a variable of type +`InSequence`: + +```cpp +using ::testing::_; +using ::testing::InSequence; + + { + InSequence s; + + EXPECT_CALL(foo, DoThis(5)); + EXPECT_CALL(bar, DoThat(_)) + .Times(2); + EXPECT_CALL(foo, DoThis(6)); + } +``` + +In this example, we expect a call to `foo.DoThis(5)`, followed by two calls to +`bar.DoThat()` where the argument can be anything, which are in turn followed by +a call to `foo.DoThis(6)`. If a call occurred out-of-order, gMock will report an +error. + +### Expecting Partially Ordered Calls {#PartialOrder} + +Sometimes requiring everything to occur in a predetermined order can lead to +brittle tests. For example, we may care about `A` occurring before both `B` and +`C`, but aren't interested in the relative order of `B` and `C`. In this case, +the test should reflect our real intent, instead of being overly constraining. + +gMock allows you to impose an arbitrary DAG (directed acyclic graph) on the +calls. One way to express the DAG is to use the +[`After` clause](reference/mocking.md#EXPECT_CALL.After) of `EXPECT_CALL`. + +Another way is via the `InSequence()` clause (not the same as the `InSequence` +class), which we borrowed from jMock 2. It's less flexible than `After()`, but +more convenient when you have long chains of sequential calls, as it doesn't +require you to come up with different names for the expectations in the chains. +Here's how it works: + +If we view `EXPECT_CALL()` statements as nodes in a graph, and add an edge from +node A to node B wherever A must occur before B, we can get a DAG. We use the +term "sequence" to mean a directed path in this DAG. Now, if we decompose the +DAG into sequences, we just need to know which sequences each `EXPECT_CALL()` +belongs to in order to be able to reconstruct the original DAG. + +So, to specify the partial order on the expectations we need to do two things: +first to define some `Sequence` objects, and then for each `EXPECT_CALL()` say +which `Sequence` objects it is part of. + +Expectations in the same sequence must occur in the order they are written. For +example, + +```cpp +using ::testing::Sequence; +... + Sequence s1, s2; + + EXPECT_CALL(foo, A()) + .InSequence(s1, s2); + EXPECT_CALL(bar, B()) + .InSequence(s1); + EXPECT_CALL(bar, C()) + .InSequence(s2); + EXPECT_CALL(foo, D()) + .InSequence(s2); +``` + +specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> C -> D`): + +```text + +---> B + | + A ---| + | + +---> C ---> D +``` + +This means that A must occur before B and C, and C must occur before D. There's +no restriction about the order other than these. + +### Controlling When an Expectation Retires + +When a mock method is called, gMock only considers expectations that are still +active. An expectation is active when created, and becomes inactive (aka +*retires*) when a call that has to occur later has occurred. For example, in + +```cpp +using ::testing::_; +using ::testing::Sequence; +... + Sequence s1, s2; + + EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #1 + .Times(AnyNumber()) + .InSequence(s1, s2); + EXPECT_CALL(log, Log(WARNING, _, "Data set is empty.")) // #2 + .InSequence(s1); + EXPECT_CALL(log, Log(WARNING, _, "User not found.")) // #3 + .InSequence(s2); +``` + +as soon as either #2 or #3 is matched, #1 will retire. If a warning `"File too +large."` is logged after this, it will be an error. + +Note that an expectation doesn't retire automatically when it's saturated. For +example, + +```cpp +using ::testing::_; +... + EXPECT_CALL(log, Log(WARNING, _, _)); // #1 + EXPECT_CALL(log, Log(WARNING, _, "File too large.")); // #2 +``` + +says that there will be exactly one warning with the message `"File too +large."`. If the second warning contains this message too, #2 will match again +and result in an upper-bound-violated error. + +If this is not what you want, you can ask an expectation to retire as soon as it +becomes saturated: + +```cpp +using ::testing::_; +... + EXPECT_CALL(log, Log(WARNING, _, _)); // #1 + EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #2 + .RetiresOnSaturation(); +``` + +Here #2 can be used only once, so if you have two warnings with the message +`"File too large."`, the first will match #2 and the second will match #1 - +there will be no error. + +## Using Actions + +### Returning References from Mock Methods + +If a mock function's return type is a reference, you need to use `ReturnRef()` +instead of `Return()` to return a result: + +```cpp +using ::testing::ReturnRef; + +class MockFoo : public Foo { + public: + MOCK_METHOD(Bar&, GetBar, (), (override)); +}; +... + MockFoo foo; + Bar bar; + EXPECT_CALL(foo, GetBar()) + .WillOnce(ReturnRef(bar)); +... +``` + +### Returning Live Values from Mock Methods + +The `Return(x)` action saves a copy of `x` when the action is created, and +always returns the same value whenever it's executed. Sometimes you may want to +instead return the *live* value of `x` (i.e. its value at the time when the +action is *executed*.). Use either `ReturnRef()` or `ReturnPointee()` for this +purpose. + +If the mock function's return type is a reference, you can do it using +`ReturnRef(x)`, as shown in the previous recipe ("Returning References from Mock +Methods"). However, gMock doesn't let you use `ReturnRef()` in a mock function +whose return type is not a reference, as doing that usually indicates a user +error. So, what shall you do? + +Though you may be tempted, DO NOT use `std::ref()`: + +```cpp +using testing::Return; + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, GetValue, (), (override)); +}; +... + int x = 0; + MockFoo foo; + EXPECT_CALL(foo, GetValue()) + .WillRepeatedly(Return(std::ref(x))); // Wrong! + x = 42; + EXPECT_EQ(42, foo.GetValue()); +``` + +Unfortunately, it doesn't work here. The above code will fail with error: + +```text +Value of: foo.GetValue() + Actual: 0 +Expected: 42 +``` + +The reason is that `Return(*value*)` converts `value` to the actual return type +of the mock function at the time when the action is *created*, not when it is +*executed*. (This behavior was chosen for the action to be safe when `value` is +a proxy object that references some temporary objects.) As a result, +`std::ref(x)` is converted to an `int` value (instead of a `const int&`) when +the expectation is set, and `Return(std::ref(x))` will always return 0. + +`ReturnPointee(pointer)` was provided to solve this problem specifically. It +returns the value pointed to by `pointer` at the time the action is *executed*: + +```cpp +using testing::ReturnPointee; +... + int x = 0; + MockFoo foo; + EXPECT_CALL(foo, GetValue()) + .WillRepeatedly(ReturnPointee(&x)); // Note the & here. + x = 42; + EXPECT_EQ(42, foo.GetValue()); // This will succeed now. +``` + +### Combining Actions + +Want to do more than one thing when a function is called? That's fine. `DoAll()` +allow you to do sequence of actions every time. Only the return value of the +last action in the sequence will be used. + +```cpp +using ::testing::_; +using ::testing::DoAll; + +class MockFoo : public Foo { + public: + MOCK_METHOD(bool, Bar, (int n), (override)); +}; +... + EXPECT_CALL(foo, Bar(_)) + .WillOnce(DoAll(action_1, + action_2, + ... + action_n)); +``` + +### Verifying Complex Arguments {#SaveArgVerify} + +If you want to verify that a method is called with a particular argument but the +match criteria is complex, it can be difficult to distinguish between +cardinality failures (calling the method the wrong number of times) and argument +match failures. Similarly, if you are matching multiple parameters, it may not +be easy to distinguishing which argument failed to match. For example: + +```cpp + // Not ideal: this could fail because of a problem with arg1 or arg2, or maybe + // just the method wasn't called. + EXPECT_CALL(foo, SendValues(_, ElementsAre(1, 4, 4, 7), EqualsProto( ... ))); +``` + +You can instead save the arguments and test them individually: + +```cpp + EXPECT_CALL(foo, SendValues) + .WillOnce(DoAll(SaveArg<1>(&actual_array), SaveArg<2>(&actual_proto))); + ... run the test + EXPECT_THAT(actual_array, ElementsAre(1, 4, 4, 7)); + EXPECT_THAT(actual_proto, EqualsProto( ... )); +``` + +### Mocking Side Effects {#MockingSideEffects} + +Sometimes a method exhibits its effect not via returning a value but via side +effects. For example, it may change some global state or modify an output +argument. To mock side effects, in general you can define your own action by +implementing `::testing::ActionInterface`. + +If all you need to do is to change an output argument, the built-in +`SetArgPointee()` action is convenient: + +```cpp +using ::testing::_; +using ::testing::SetArgPointee; + +class MockMutator : public Mutator { + public: + MOCK_METHOD(void, Mutate, (bool mutate, int* value), (override)); + ... +} +... + MockMutator mutator; + EXPECT_CALL(mutator, Mutate(true, _)) + .WillOnce(SetArgPointee<1>(5)); +``` + +In this example, when `mutator.Mutate()` is called, we will assign 5 to the +`int` variable pointed to by argument #1 (0-based). + +`SetArgPointee()` conveniently makes an internal copy of the value you pass to +it, removing the need to keep the value in scope and alive. The implication +however is that the value must have a copy constructor and assignment operator. + +If the mock method also needs to return a value as well, you can chain +`SetArgPointee()` with `Return()` using `DoAll()`, remembering to put the +`Return()` statement last: + +```cpp +using ::testing::_; +using ::testing::DoAll; +using ::testing::Return; +using ::testing::SetArgPointee; + +class MockMutator : public Mutator { + public: + ... + MOCK_METHOD(bool, MutateInt, (int* value), (override)); +} +... + MockMutator mutator; + EXPECT_CALL(mutator, MutateInt(_)) + .WillOnce(DoAll(SetArgPointee<0>(5), + Return(true))); +``` + +Note, however, that if you use the `ReturnOKWith()` method, it will override the +values provided by `SetArgPointee()` in the response parameters of your function +call. + +If the output argument is an array, use the `SetArrayArgument(first, last)` +action instead. It copies the elements in source range `[first, last)` to the +array pointed to by the `N`-th (0-based) argument: + +```cpp +using ::testing::NotNull; +using ::testing::SetArrayArgument; + +class MockArrayMutator : public ArrayMutator { + public: + MOCK_METHOD(void, Mutate, (int* values, int num_values), (override)); + ... +} +... + MockArrayMutator mutator; + int values[5] = {1, 2, 3, 4, 5}; + EXPECT_CALL(mutator, Mutate(NotNull(), 5)) + .WillOnce(SetArrayArgument<0>(values, values + 5)); +``` + +This also works when the argument is an output iterator: + +```cpp +using ::testing::_; +using ::testing::SetArrayArgument; + +class MockRolodex : public Rolodex { + public: + MOCK_METHOD(void, GetNames, (std::back_insert_iterator>), + (override)); + ... +} +... + MockRolodex rolodex; + vector names = {"George", "John", "Thomas"}; + EXPECT_CALL(rolodex, GetNames(_)) + .WillOnce(SetArrayArgument<0>(names.begin(), names.end())); +``` + +### Changing a Mock Object's Behavior Based on the State + +If you expect a call to change the behavior of a mock object, you can use +`::testing::InSequence` to specify different behaviors before and after the +call: + +```cpp +using ::testing::InSequence; +using ::testing::Return; + +... + { + InSequence seq; + EXPECT_CALL(my_mock, IsDirty()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(my_mock, Flush()); + EXPECT_CALL(my_mock, IsDirty()) + .WillRepeatedly(Return(false)); + } + my_mock.FlushIfDirty(); +``` + +This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called +and return `false` afterwards. + +If the behavior change is more complex, you can store the effects in a variable +and make a mock method get its return value from that variable: + +```cpp +using ::testing::_; +using ::testing::SaveArg; +using ::testing::Return; + +ACTION_P(ReturnPointee, p) { return *p; } +... + int previous_value = 0; + EXPECT_CALL(my_mock, GetPrevValue) + .WillRepeatedly(ReturnPointee(&previous_value)); + EXPECT_CALL(my_mock, UpdateValue) + .WillRepeatedly(SaveArg<0>(&previous_value)); + my_mock.DoSomethingToUpdateValue(); +``` + +Here `my_mock.GetPrevValue()` will always return the argument of the last +`UpdateValue()` call. + +### Setting the Default Value for a Return Type {#DefaultValue} + +If a mock method's return type is a built-in C++ type or pointer, by default it +will return 0 when invoked. Also, in C++ 11 and above, a mock method whose +return type has a default constructor will return a default-constructed value by +default. You only need to specify an action if this default value doesn't work +for you. + +Sometimes, you may want to change this default value, or you may want to specify +a default value for types gMock doesn't know about. You can do this using the +`::testing::DefaultValue` class template: + +```cpp +using ::testing::DefaultValue; + +class MockFoo : public Foo { + public: + MOCK_METHOD(Bar, CalculateBar, (), (override)); +}; + + +... + Bar default_bar; + // Sets the default return value for type Bar. + DefaultValue::Set(default_bar); + + MockFoo foo; + + // We don't need to specify an action here, as the default + // return value works for us. + EXPECT_CALL(foo, CalculateBar()); + + foo.CalculateBar(); // This should return default_bar. + + // Unsets the default return value. + DefaultValue::Clear(); +``` + +Please note that changing the default value for a type can make your tests hard +to understand. We recommend you to use this feature judiciously. For example, +you may want to make sure the `Set()` and `Clear()` calls are right next to the +code that uses your mock. + +### Setting the Default Actions for a Mock Method + +You've learned how to change the default value of a given type. However, this +may be too coarse for your purpose: perhaps you have two mock methods with the +same return type and you want them to have different behaviors. The `ON_CALL()` +macro allows you to customize your mock's behavior at the method level: + +```cpp +using ::testing::_; +using ::testing::AnyNumber; +using ::testing::Gt; +using ::testing::Return; +... + ON_CALL(foo, Sign(_)) + .WillByDefault(Return(-1)); + ON_CALL(foo, Sign(0)) + .WillByDefault(Return(0)); + ON_CALL(foo, Sign(Gt(0))) + .WillByDefault(Return(1)); + + EXPECT_CALL(foo, Sign(_)) + .Times(AnyNumber()); + + foo.Sign(5); // This should return 1. + foo.Sign(-9); // This should return -1. + foo.Sign(0); // This should return 0. +``` + +As you may have guessed, when there are more than one `ON_CALL()` statements, +the newer ones in the order take precedence over the older ones. In other words, +the **last** one that matches the function arguments will be used. This matching +order allows you to set up the common behavior in a mock object's constructor or +the test fixture's set-up phase and specialize the mock's behavior later. + +Note that both `ON_CALL` and `EXPECT_CALL` have the same "later statements take +precedence" rule, but they don't interact. That is, `EXPECT_CALL`s have their +own precedence order distinct from the `ON_CALL` precedence order. + +### Using Functions/Methods/Functors/Lambdas as Actions {#FunctionsAsActions} + +If the built-in actions don't suit you, you can use an existing callable +(function, `std::function`, method, functor, lambda) as an action. + +```cpp +using ::testing::_; using ::testing::Invoke; + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, Sum, (int x, int y), (override)); + MOCK_METHOD(bool, ComplexJob, (int x), (override)); +}; + +int CalculateSum(int x, int y) { return x + y; } +int Sum3(int x, int y, int z) { return x + y + z; } + +class Helper { + public: + bool ComplexJob(int x); +}; + +... + MockFoo foo; + Helper helper; + EXPECT_CALL(foo, Sum(_, _)) + .WillOnce(&CalculateSum) + .WillRepeatedly(Invoke(NewPermanentCallback(Sum3, 1))); + EXPECT_CALL(foo, ComplexJob(_)) + .WillOnce(Invoke(&helper, &Helper::ComplexJob)) + .WillOnce([] { return true; }) + .WillRepeatedly([](int x) { return x > 0; }); + + foo.Sum(5, 6); // Invokes CalculateSum(5, 6). + foo.Sum(2, 3); // Invokes Sum3(1, 2, 3). + foo.ComplexJob(10); // Invokes helper.ComplexJob(10). + foo.ComplexJob(-1); // Invokes the inline lambda. +``` + +The only requirement is that the type of the function, etc must be *compatible* +with the signature of the mock function, meaning that the latter's arguments (if +it takes any) can be implicitly converted to the corresponding arguments of the +former, and the former's return type can be implicitly converted to that of the +latter. So, you can invoke something whose type is *not* exactly the same as the +mock function, as long as it's safe to do so - nice, huh? + +Note that: + +* The action takes ownership of the callback and will delete it when the + action itself is destructed. +* If the type of a callback is derived from a base callback type `C`, you need + to implicitly cast it to `C` to resolve the overloading, e.g. + + ```cpp + using ::testing::Invoke; + ... + ResultCallback* is_ok = ...; + ... Invoke(is_ok) ...; // This works. + + BlockingClosure* done = new BlockingClosure; + ... Invoke(implicit_cast(done)) ...; // The cast is necessary. + ``` + +### Using Functions with Extra Info as Actions + +The function or functor you call using `Invoke()` must have the same number of +arguments as the mock function you use it for. Sometimes you may have a function +that takes more arguments, and you are willing to pass in the extra arguments +yourself to fill the gap. You can do this in gMock using callbacks with +pre-bound arguments. Here's an example: + +```cpp +using ::testing::Invoke; + +class MockFoo : public Foo { + public: + MOCK_METHOD(char, DoThis, (int n), (override)); +}; + +char SignOfSum(int x, int y) { + const int sum = x + y; + return (sum > 0) ? '+' : (sum < 0) ? '-' : '0'; +} + +TEST_F(FooTest, Test) { + MockFoo foo; + + EXPECT_CALL(foo, DoThis(2)) + .WillOnce(Invoke(NewPermanentCallback(SignOfSum, 5))); + EXPECT_EQ('+', foo.DoThis(2)); // Invokes SignOfSum(5, 2). +} +``` + +### Invoking a Function/Method/Functor/Lambda/Callback Without Arguments + +`Invoke()` passes the mock function's arguments to the function, etc being +invoked such that the callee has the full context of the call to work with. If +the invoked function is not interested in some or all of the arguments, it can +simply ignore them. + +Yet, a common pattern is that a test author wants to invoke a function without +the arguments of the mock function. She could do that using a wrapper function +that throws away the arguments before invoking an underlining nullary function. +Needless to say, this can be tedious and obscures the intent of the test. + +There are two solutions to this problem. First, you can pass any callable of +zero args as an action. Alternatively, use `InvokeWithoutArgs()`, which is like +`Invoke()` except that it doesn't pass the mock function's arguments to the +callee. Here's an example of each: + +```cpp +using ::testing::_; +using ::testing::InvokeWithoutArgs; + +class MockFoo : public Foo { + public: + MOCK_METHOD(bool, ComplexJob, (int n), (override)); +}; + +bool Job1() { ... } +bool Job2(int n, char c) { ... } + +... + MockFoo foo; + EXPECT_CALL(foo, ComplexJob(_)) + .WillOnce([] { Job1(); }); + .WillOnce(InvokeWithoutArgs(NewPermanentCallback(Job2, 5, 'a'))); + + foo.ComplexJob(10); // Invokes Job1(). + foo.ComplexJob(20); // Invokes Job2(5, 'a'). +``` + +Note that: + +* The action takes ownership of the callback and will delete it when the + action itself is destructed. +* If the type of a callback is derived from a base callback type `C`, you need + to implicitly cast it to `C` to resolve the overloading, e.g. + + ```cpp + using ::testing::InvokeWithoutArgs; + ... + ResultCallback* is_ok = ...; + ... InvokeWithoutArgs(is_ok) ...; // This works. + + BlockingClosure* done = ...; + ... InvokeWithoutArgs(implicit_cast(done)) ...; + // The cast is necessary. + ``` + +### Invoking an Argument of the Mock Function + +Sometimes a mock function will receive a function pointer, a functor (in other +words, a "callable") as an argument, e.g. + +```cpp +class MockFoo : public Foo { + public: + MOCK_METHOD(bool, DoThis, (int n, (ResultCallback1* callback)), + (override)); +}; +``` + +and you may want to invoke this callable argument: + +```cpp +using ::testing::_; +... + MockFoo foo; + EXPECT_CALL(foo, DoThis(_, _)) + .WillOnce(...); + // Will execute callback->Run(5), where callback is the + // second argument DoThis() receives. +``` + +{: .callout .note} +NOTE: The section below is legacy documentation from before C++ had lambdas: + +Arghh, you need to refer to a mock function argument but C++ has no lambda +(yet), so you have to define your own action. :-( Or do you really? + +Well, gMock has an action to solve *exactly* this problem: + +```cpp +InvokeArgument(arg_1, arg_2, ..., arg_m) +``` + +will invoke the `N`-th (0-based) argument the mock function receives, with +`arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is a function +pointer, a functor, or a callback. gMock handles them all. + +With that, you could write: + +```cpp +using ::testing::_; +using ::testing::InvokeArgument; +... + EXPECT_CALL(foo, DoThis(_, _)) + .WillOnce(InvokeArgument<1>(5)); + // Will execute callback->Run(5), where callback is the + // second argument DoThis() receives. +``` + +What if the callable takes an argument by reference? No problem - just wrap it +inside `std::ref()`: + +```cpp + ... + MOCK_METHOD(bool, Bar, + ((ResultCallback2* callback)), + (override)); + ... + using ::testing::_; + using ::testing::InvokeArgument; + ... + MockFoo foo; + Helper helper; + ... + EXPECT_CALL(foo, Bar(_)) + .WillOnce(InvokeArgument<0>(5, std::ref(helper))); + // std::ref(helper) guarantees that a reference to helper, not a copy of + // it, will be passed to the callback. +``` + +What if the callable takes an argument by reference and we do **not** wrap the +argument in `std::ref()`? Then `InvokeArgument()` will *make a copy* of the +argument, and pass a *reference to the copy*, instead of a reference to the +original value, to the callable. This is especially handy when the argument is a +temporary value: + +```cpp + ... + MOCK_METHOD(bool, DoThat, (bool (*f)(const double& x, const string& s)), + (override)); + ... + using ::testing::_; + using ::testing::InvokeArgument; + ... + MockFoo foo; + ... + EXPECT_CALL(foo, DoThat(_)) + .WillOnce(InvokeArgument<0>(5.0, string("Hi"))); + // Will execute (*f)(5.0, string("Hi")), where f is the function pointer + // DoThat() receives. Note that the values 5.0 and string("Hi") are + // temporary and dead once the EXPECT_CALL() statement finishes. Yet + // it's fine to perform this action later, since a copy of the values + // are kept inside the InvokeArgument action. +``` + +### Ignoring an Action's Result + +Sometimes you have an action that returns *something*, but you need an action +that returns `void` (perhaps you want to use it in a mock function that returns +`void`, or perhaps it needs to be used in `DoAll()` and it's not the last in the +list). `IgnoreResult()` lets you do that. For example: + +```cpp +using ::testing::_; +using ::testing::DoAll; +using ::testing::IgnoreResult; +using ::testing::Return; + +int Process(const MyData& data); +string DoSomething(); + +class MockFoo : public Foo { + public: + MOCK_METHOD(void, Abc, (const MyData& data), (override)); + MOCK_METHOD(bool, Xyz, (), (override)); +}; + + ... + MockFoo foo; + EXPECT_CALL(foo, Abc(_)) + // .WillOnce(Invoke(Process)); + // The above line won't compile as Process() returns int but Abc() needs + // to return void. + .WillOnce(IgnoreResult(Process)); + EXPECT_CALL(foo, Xyz()) + .WillOnce(DoAll(IgnoreResult(DoSomething), + // Ignores the string DoSomething() returns. + Return(true))); +``` + +Note that you **cannot** use `IgnoreResult()` on an action that already returns +`void`. Doing so will lead to ugly compiler errors. + +### Selecting an Action's Arguments {#SelectingArgs} + +Say you have a mock function `Foo()` that takes seven arguments, and you have a +custom action that you want to invoke when `Foo()` is called. Trouble is, the +custom action only wants three arguments: + +```cpp +using ::testing::_; +using ::testing::Invoke; +... + MOCK_METHOD(bool, Foo, + (bool visible, const string& name, int x, int y, + (const map>), double& weight, double min_weight, + double max_wight)); +... +bool IsVisibleInQuadrant1(bool visible, int x, int y) { + return visible && x >= 0 && y >= 0; +} +... + EXPECT_CALL(mock, Foo) + .WillOnce(Invoke(IsVisibleInQuadrant1)); // Uh, won't compile. :-( +``` + +To please the compiler God, you need to define an "adaptor" that has the same +signature as `Foo()` and calls the custom action with the right arguments: + +```cpp +using ::testing::_; +using ::testing::Invoke; +... +bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y, + const map, double>& weight, + double min_weight, double max_wight) { + return IsVisibleInQuadrant1(visible, x, y); +} +... + EXPECT_CALL(mock, Foo) + .WillOnce(Invoke(MyIsVisibleInQuadrant1)); // Now it works. +``` + +But isn't this awkward? + +gMock provides a generic *action adaptor*, so you can spend your time minding +more important business than writing your own adaptors. Here's the syntax: + +```cpp +WithArgs(action) +``` + +creates an action that passes the arguments of the mock function at the given +indices (0-based) to the inner `action` and performs it. Using `WithArgs`, our +original example can be written as: + +```cpp +using ::testing::_; +using ::testing::Invoke; +using ::testing::WithArgs; +... + EXPECT_CALL(mock, Foo) + .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1))); // No need to define your own adaptor. +``` + +For better readability, gMock also gives you: + +* `WithoutArgs(action)` when the inner `action` takes *no* argument, and +* `WithArg(action)` (no `s` after `Arg`) when the inner `action` takes + *one* argument. + +As you may have realized, `InvokeWithoutArgs(...)` is just syntactic sugar for +`WithoutArgs(Invoke(...))`. + +Here are more tips: + +* The inner action used in `WithArgs` and friends does not have to be + `Invoke()` -- it can be anything. +* You can repeat an argument in the argument list if necessary, e.g. + `WithArgs<2, 3, 3, 5>(...)`. +* You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`. +* The types of the selected arguments do *not* have to match the signature of + the inner action exactly. It works as long as they can be implicitly + converted to the corresponding arguments of the inner action. For example, + if the 4-th argument of the mock function is an `int` and `my_action` takes + a `double`, `WithArg<4>(my_action)` will work. + +### Ignoring Arguments in Action Functions + +The [selecting-an-action's-arguments](#SelectingArgs) recipe showed us one way +to make a mock function and an action with incompatible argument lists fit +together. The downside is that wrapping the action in `WithArgs<...>()` can get +tedious for people writing the tests. + +If you are defining a function (or method, functor, lambda, callback) to be used +with `Invoke*()`, and you are not interested in some of its arguments, an +alternative to `WithArgs` is to declare the uninteresting arguments as `Unused`. +This makes the definition less cluttered and less fragile in case the types of +the uninteresting arguments change. It could also increase the chance the action +function can be reused. For example, given + +```cpp + public: + MOCK_METHOD(double, Foo, double(const string& label, double x, double y), + (override)); + MOCK_METHOD(double, Bar, (int index, double x, double y), (override)); +``` + +instead of + +```cpp +using ::testing::_; +using ::testing::Invoke; + +double DistanceToOriginWithLabel(const string& label, double x, double y) { + return sqrt(x*x + y*y); +} +double DistanceToOriginWithIndex(int index, double x, double y) { + return sqrt(x*x + y*y); +} +... + EXPECT_CALL(mock, Foo("abc", _, _)) + .WillOnce(Invoke(DistanceToOriginWithLabel)); + EXPECT_CALL(mock, Bar(5, _, _)) + .WillOnce(Invoke(DistanceToOriginWithIndex)); +``` + +you could write + +```cpp +using ::testing::_; +using ::testing::Invoke; +using ::testing::Unused; + +double DistanceToOrigin(Unused, double x, double y) { + return sqrt(x*x + y*y); +} +... + EXPECT_CALL(mock, Foo("abc", _, _)) + .WillOnce(Invoke(DistanceToOrigin)); + EXPECT_CALL(mock, Bar(5, _, _)) + .WillOnce(Invoke(DistanceToOrigin)); +``` + +### Sharing Actions + +Just like matchers, a gMock action object consists of a pointer to a ref-counted +implementation object. Therefore copying actions is also allowed and very +efficient. When the last action that references the implementation object dies, +the implementation object will be deleted. + +If you have some complex action that you want to use again and again, you may +not have to build it from scratch every time. If the action doesn't have an +internal state (i.e. if it always does the same thing no matter how many times +it has been called), you can assign it to an action variable and use that +variable repeatedly. For example: + +```cpp +using ::testing::Action; +using ::testing::DoAll; +using ::testing::Return; +using ::testing::SetArgPointee; +... + Action set_flag = DoAll(SetArgPointee<0>(5), + Return(true)); + ... use set_flag in .WillOnce() and .WillRepeatedly() ... +``` + +However, if the action has its own state, you may be surprised if you share the +action object. Suppose you have an action factory `IncrementCounter(init)` which +creates an action that increments and returns a counter whose initial value is +`init`, using two actions created from the same expression and using a shared +action will exhibit different behaviors. Example: + +```cpp + EXPECT_CALL(foo, DoThis()) + .WillRepeatedly(IncrementCounter(0)); + EXPECT_CALL(foo, DoThat()) + .WillRepeatedly(IncrementCounter(0)); + foo.DoThis(); // Returns 1. + foo.DoThis(); // Returns 2. + foo.DoThat(); // Returns 1 - Blah() uses a different + // counter than Bar()'s. +``` + +versus + +```cpp +using ::testing::Action; +... + Action increment = IncrementCounter(0); + EXPECT_CALL(foo, DoThis()) + .WillRepeatedly(increment); + EXPECT_CALL(foo, DoThat()) + .WillRepeatedly(increment); + foo.DoThis(); // Returns 1. + foo.DoThis(); // Returns 2. + foo.DoThat(); // Returns 3 - the counter is shared. +``` + +### Testing Asynchronous Behavior + +One oft-encountered problem with gMock is that it can be hard to test +asynchronous behavior. Suppose you had a `EventQueue` class that you wanted to +test, and you created a separate `EventDispatcher` interface so that you could +easily mock it out. However, the implementation of the class fired all the +events on a background thread, which made test timings difficult. You could just +insert `sleep()` statements and hope for the best, but that makes your test +behavior nondeterministic. A better way is to use gMock actions and +`Notification` objects to force your asynchronous test to behave synchronously. + +```cpp +class MockEventDispatcher : public EventDispatcher { + MOCK_METHOD(bool, DispatchEvent, (int32), (override)); +}; + +TEST(EventQueueTest, EnqueueEventTest) { + MockEventDispatcher mock_event_dispatcher; + EventQueue event_queue(&mock_event_dispatcher); + + const int32 kEventId = 321; + absl::Notification done; + EXPECT_CALL(mock_event_dispatcher, DispatchEvent(kEventId)) + .WillOnce([&done] { done.Notify(); }); + + event_queue.EnqueueEvent(kEventId); + done.WaitForNotification(); +} +``` + +In the example above, we set our normal gMock expectations, but then add an +additional action to notify the `Notification` object. Now we can just call +`Notification::WaitForNotification()` in the main thread to wait for the +asynchronous call to finish. After that, our test suite is complete and we can +safely exit. + +{: .callout .note} +Note: this example has a downside: namely, if the expectation is not satisfied, +our test will run forever. It will eventually time-out and fail, but it will +take longer and be slightly harder to debug. To alleviate this problem, you can +use `WaitForNotificationWithTimeout(ms)` instead of `WaitForNotification()`. + +## Misc Recipes on Using gMock + +### Mocking Methods That Use Move-Only Types + +C++11 introduced *move-only types*. A move-only-typed value can be moved from +one object to another, but cannot be copied. `std::unique_ptr` is probably +the most commonly used move-only type. + +Mocking a method that takes and/or returns move-only types presents some +challenges, but nothing insurmountable. This recipe shows you how you can do it. +Note that the support for move-only method arguments was only introduced to +gMock in April 2017; in older code, you may find more complex +[workarounds](#LegacyMoveOnly) for lack of this feature. + +Let’s say we are working on a fictional project that lets one post and share +snippets called “buzzesâ€. Your code uses these types: + +```cpp +enum class AccessLevel { kInternal, kPublic }; + +class Buzz { + public: + explicit Buzz(AccessLevel access) { ... } + ... +}; + +class Buzzer { + public: + virtual ~Buzzer() {} + virtual std::unique_ptr MakeBuzz(StringPiece text) = 0; + virtual bool ShareBuzz(std::unique_ptr buzz, int64_t timestamp) = 0; + ... +}; +``` + +A `Buzz` object represents a snippet being posted. A class that implements the +`Buzzer` interface is capable of creating and sharing `Buzz`es. Methods in +`Buzzer` may return a `unique_ptr` or take a `unique_ptr`. Now we +need to mock `Buzzer` in our tests. + +To mock a method that accepts or returns move-only types, you just use the +familiar `MOCK_METHOD` syntax as usual: + +```cpp +class MockBuzzer : public Buzzer { + public: + MOCK_METHOD(std::unique_ptr, MakeBuzz, (StringPiece text), (override)); + MOCK_METHOD(bool, ShareBuzz, (std::unique_ptr buzz, int64_t timestamp), + (override)); +}; +``` + +Now that we have the mock class defined, we can use it in tests. In the +following code examples, we assume that we have defined a `MockBuzzer` object +named `mock_buzzer_`: + +```cpp + MockBuzzer mock_buzzer_; +``` + +First let’s see how we can set expectations on the `MakeBuzz()` method, which +returns a `unique_ptr`. + +As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or +`.WillRepeatedly()` clause), when that expectation fires, the default action for +that method will be taken. Since `unique_ptr<>` has a default constructor that +returns a null `unique_ptr`, that’s what you’ll get if you don’t specify an +action: + +```cpp + // Use the default action. + EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")); + + // Triggers the previous EXPECT_CALL. + EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz("hello")); +``` + +If you are not happy with the default action, you can tweak it as usual; see +[Setting Default Actions](#OnCall). + +If you just need to return a pre-defined move-only value, you can use the +`Return(ByMove(...))` action: + +```cpp + // When this fires, the unique_ptr<> specified by ByMove(...) will + // be returned. + EXPECT_CALL(mock_buzzer_, MakeBuzz("world")) + .WillOnce(Return(ByMove(MakeUnique(AccessLevel::kInternal)))); + + EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("world")); +``` + +Note that `ByMove()` is essential here - if you drop it, the code won’t compile. + +Quiz time! What do you think will happen if a `Return(ByMove(...))` action is +performed more than once (e.g. you write `... +.WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first time +the action runs, the source value will be consumed (since it’s a move-only +value), so the next time around, there’s no value to move from -- you’ll get a +run-time error that `Return(ByMove(...))` can only be run once. + +If you need your mock method to do more than just moving a pre-defined value, +remember that you can always use a lambda or a callable object, which can do +pretty much anything you want: + +```cpp + EXPECT_CALL(mock_buzzer_, MakeBuzz("x")) + .WillRepeatedly([](StringPiece text) { + return MakeUnique(AccessLevel::kInternal); + }); + + EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); + EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); +``` + +Every time this `EXPECT_CALL` fires, a new `unique_ptr` will be created +and returned. You cannot do this with `Return(ByMove(...))`. + +That covers returning move-only values; but how do we work with methods +accepting move-only arguments? The answer is that they work normally, although +some actions will not compile when any of method's arguments are move-only. You +can always use `Return`, or a [lambda or functor](#FunctionsAsActions): + +```cpp + using ::testing::Unused; + + EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)).WillOnce(Return(true)); + EXPECT_TRUE(mock_buzzer_.ShareBuzz(MakeUnique(AccessLevel::kInternal)), + 0); + + EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)).WillOnce( + [](std::unique_ptr buzz, Unused) { return buzz != nullptr; }); + EXPECT_FALSE(mock_buzzer_.ShareBuzz(nullptr, 0)); +``` + +Many built-in actions (`WithArgs`, `WithoutArgs`,`DeleteArg`, `SaveArg`, ...) +could in principle support move-only arguments, but the support for this is not +implemented yet. If this is blocking you, please file a bug. + +A few actions (e.g. `DoAll`) copy their arguments internally, so they can never +work with non-copyable objects; you'll have to use functors instead. + +#### Legacy workarounds for move-only types {#LegacyMoveOnly} + +Support for move-only function arguments was only introduced to gMock in April +of 2017. In older code, you may encounter the following workaround for the lack +of this feature (it is no longer necessary - we're including it just for +reference): + +```cpp +class MockBuzzer : public Buzzer { + public: + MOCK_METHOD(bool, DoShareBuzz, (Buzz* buzz, Time timestamp)); + bool ShareBuzz(std::unique_ptr buzz, Time timestamp) override { + return DoShareBuzz(buzz.get(), timestamp); + } +}; +``` + +The trick is to delegate the `ShareBuzz()` method to a mock method (let’s call +it `DoShareBuzz()`) that does not take move-only parameters. Then, instead of +setting expectations on `ShareBuzz()`, you set them on the `DoShareBuzz()` mock +method: + +```cpp + MockBuzzer mock_buzzer_; + EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _)); + + // When one calls ShareBuzz() on the MockBuzzer like this, the call is + // forwarded to DoShareBuzz(), which is mocked. Therefore this statement + // will trigger the above EXPECT_CALL. + mock_buzzer_.ShareBuzz(MakeUnique(AccessLevel::kInternal), 0); +``` + +### Making the Compilation Faster + +Believe it or not, the *vast majority* of the time spent on compiling a mock +class is in generating its constructor and destructor, as they perform +non-trivial tasks (e.g. verification of the expectations). What's more, mock +methods with different signatures have different types and thus their +constructors/destructors need to be generated by the compiler separately. As a +result, if you mock many different types of methods, compiling your mock class +can get really slow. + +If you are experiencing slow compilation, you can move the definition of your +mock class' constructor and destructor out of the class body and into a `.cc` +file. This way, even if you `#include` your mock class in N files, the compiler +only needs to generate its constructor and destructor once, resulting in a much +faster compilation. + +Let's illustrate the idea using an example. Here's the definition of a mock +class before applying this recipe: + +```cpp +// File mock_foo.h. +... +class MockFoo : public Foo { + public: + // Since we don't declare the constructor or the destructor, + // the compiler will generate them in every translation unit + // where this mock class is used. + + MOCK_METHOD(int, DoThis, (), (override)); + MOCK_METHOD(bool, DoThat, (const char* str), (override)); + ... more mock methods ... +}; +``` + +After the change, it would look like: + +```cpp +// File mock_foo.h. +... +class MockFoo : public Foo { + public: + // The constructor and destructor are declared, but not defined, here. + MockFoo(); + virtual ~MockFoo(); + + MOCK_METHOD(int, DoThis, (), (override)); + MOCK_METHOD(bool, DoThat, (const char* str), (override)); + ... more mock methods ... +}; +``` + +and + +```cpp +// File mock_foo.cc. +#include "path/to/mock_foo.h" + +// The definitions may appear trivial, but the functions actually do a +// lot of things through the constructors/destructors of the member +// variables used to implement the mock methods. +MockFoo::MockFoo() {} +MockFoo::~MockFoo() {} +``` + +### Forcing a Verification + +When it's being destroyed, your friendly mock object will automatically verify +that all expectations on it have been satisfied, and will generate googletest +failures if not. This is convenient as it leaves you with one less thing to +worry about. That is, unless you are not sure if your mock object will be +destroyed. + +How could it be that your mock object won't eventually be destroyed? Well, it +might be created on the heap and owned by the code you are testing. Suppose +there's a bug in that code and it doesn't delete the mock object properly - you +could end up with a passing test when there's actually a bug. + +Using a heap checker is a good idea and can alleviate the concern, but its +implementation is not 100% reliable. So, sometimes you do want to *force* gMock +to verify a mock object before it is (hopefully) destructed. You can do this +with `Mock::VerifyAndClearExpectations(&mock_object)`: + +```cpp +TEST(MyServerTest, ProcessesRequest) { + using ::testing::Mock; + + MockFoo* const foo = new MockFoo; + EXPECT_CALL(*foo, ...)...; + // ... other expectations ... + + // server now owns foo. + MyServer server(foo); + server.ProcessRequest(...); + + // In case that server's destructor will forget to delete foo, + // this will verify the expectations anyway. + Mock::VerifyAndClearExpectations(foo); +} // server is destroyed when it goes out of scope here. +``` + +{: .callout .tip} +**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a `bool` to +indicate whether the verification was successful (`true` for yes), so you can +wrap that function call inside a `ASSERT_TRUE()` if there is no point going +further when the verification has failed. + +Do not set new expectations after verifying and clearing a mock after its use. +Setting expectations after code that exercises the mock has undefined behavior. +See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more +information. + +### Using Checkpoints {#UsingCheckPoints} + +Sometimes you might want to test a mock object's behavior in phases whose sizes +are each manageable, or you might want to set more detailed expectations about +which API calls invoke which mock functions. + +A technique you can use is to put the expectations in a sequence and insert +calls to a dummy "checkpoint" function at specific places. Then you can verify +that the mock function calls do happen at the right time. For example, if you +are exercising the code: + +```cpp + Foo(1); + Foo(2); + Foo(3); +``` + +and want to verify that `Foo(1)` and `Foo(3)` both invoke `mock.Bar("a")`, but +`Foo(2)` doesn't invoke anything, you can write: + +```cpp +using ::testing::MockFunction; + +TEST(FooTest, InvokesBarCorrectly) { + MyMock mock; + // Class MockFunction has exactly one mock method. It is named + // Call() and has type F. + MockFunction check; + { + InSequence s; + + EXPECT_CALL(mock, Bar("a")); + EXPECT_CALL(check, Call("1")); + EXPECT_CALL(check, Call("2")); + EXPECT_CALL(mock, Bar("a")); + } + Foo(1); + check.Call("1"); + Foo(2); + check.Call("2"); + Foo(3); +} +``` + +The expectation spec says that the first `Bar("a")` call must happen before +checkpoint "1", the second `Bar("a")` call must happen after checkpoint "2", and +nothing should happen between the two checkpoints. The explicit checkpoints make +it clear which `Bar("a")` is called by which call to `Foo()`. + +### Mocking Destructors + +Sometimes you want to make sure a mock object is destructed at the right time, +e.g. after `bar->A()` is called but before `bar->B()` is called. We already know +that you can specify constraints on the [order](#OrderedCalls) of mock function +calls, so all we need to do is to mock the destructor of the mock function. + +This sounds simple, except for one problem: a destructor is a special function +with special syntax and special semantics, and the `MOCK_METHOD` macro doesn't +work for it: + +```cpp +MOCK_METHOD(void, ~MockFoo, ()); // Won't compile! +``` + +The good news is that you can use a simple pattern to achieve the same effect. +First, add a mock function `Die()` to your mock class and call it in the +destructor, like this: + +```cpp +class MockFoo : public Foo { + ... + // Add the following two lines to the mock class. + MOCK_METHOD(void, Die, ()); + ~MockFoo() override { Die(); } +}; +``` + +(If the name `Die()` clashes with an existing symbol, choose another name.) Now, +we have translated the problem of testing when a `MockFoo` object dies to +testing when its `Die()` method is called: + +```cpp + MockFoo* foo = new MockFoo; + MockBar* bar = new MockBar; + ... + { + InSequence s; + + // Expects *foo to die after bar->A() and before bar->B(). + EXPECT_CALL(*bar, A()); + EXPECT_CALL(*foo, Die()); + EXPECT_CALL(*bar, B()); + } +``` + +And that's that. + +### Using gMock and Threads {#UsingThreads} + +In a **unit** test, it's best if you could isolate and test a piece of code in a +single-threaded context. That avoids race conditions and dead locks, and makes +debugging your test much easier. + +Yet most programs are multi-threaded, and sometimes to test something we need to +pound on it from more than one thread. gMock works for this purpose too. + +Remember the steps for using a mock: + +1. Create a mock object `foo`. +2. Set its default actions and expectations using `ON_CALL()` and + `EXPECT_CALL()`. +3. The code under test calls methods of `foo`. +4. Optionally, verify and reset the mock. +5. Destroy the mock yourself, or let the code under test destroy it. The + destructor will automatically verify it. + +If you follow the following simple rules, your mocks and threads can live +happily together: + +* Execute your *test code* (as opposed to the code being tested) in *one* + thread. This makes your test easy to follow. +* Obviously, you can do step #1 without locking. +* When doing step #2 and #5, make sure no other thread is accessing `foo`. + Obvious too, huh? +* #3 and #4 can be done either in one thread or in multiple threads - anyway + you want. gMock takes care of the locking, so you don't have to do any - + unless required by your test logic. + +If you violate the rules (for example, if you set expectations on a mock while +another thread is calling its methods), you get undefined behavior. That's not +fun, so don't do it. + +gMock guarantees that the action for a mock function is done in the same thread +that called the mock function. For example, in + +```cpp + EXPECT_CALL(mock, Foo(1)) + .WillOnce(action1); + EXPECT_CALL(mock, Foo(2)) + .WillOnce(action2); +``` + +if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2, gMock will +execute `action1` in thread 1 and `action2` in thread 2. + +gMock does *not* impose a sequence on actions performed in different threads +(doing so may create deadlocks as the actions may need to cooperate). This means +that the execution of `action1` and `action2` in the above example *may* +interleave. If this is a problem, you should add proper synchronization logic to +`action1` and `action2` to make the test thread-safe. + +Also, remember that `DefaultValue` is a global resource that potentially +affects *all* living mock objects in your program. Naturally, you won't want to +mess with it from multiple threads or when there still are mocks in action. + +### Controlling How Much Information gMock Prints + +When gMock sees something that has the potential of being an error (e.g. a mock +function with no expectation is called, a.k.a. an uninteresting call, which is +allowed but perhaps you forgot to explicitly ban the call), it prints some +warning messages, including the arguments of the function, the return value, and +the stack trace. Hopefully this will remind you to take a look and see if there +is indeed a problem. + +Sometimes you are confident that your tests are correct and may not appreciate +such friendly messages. Some other times, you are debugging your tests or +learning about the behavior of the code you are testing, and wish you could +observe every mock call that happens (including argument values, the return +value, and the stack trace). Clearly, one size doesn't fit all. + +You can control how much gMock tells you using the `--gmock_verbose=LEVEL` +command-line flag, where `LEVEL` is a string with three possible values: + +* `info`: gMock will print all informational messages, warnings, and errors + (most verbose). At this setting, gMock will also log any calls to the + `ON_CALL/EXPECT_CALL` macros. It will include a stack trace in + "uninteresting call" warnings. +* `warning`: gMock will print both warnings and errors (less verbose); it will + omit the stack traces in "uninteresting call" warnings. This is the default. +* `error`: gMock will print errors only (least verbose). + +Alternatively, you can adjust the value of that flag from within your tests like +so: + +```cpp + ::testing::FLAGS_gmock_verbose = "error"; +``` + +If you find gMock printing too many stack frames with its informational or +warning messages, remember that you can control their amount with the +`--gtest_stack_trace_depth=max_depth` flag. + +Now, judiciously use the right flag to enable gMock serve you better! + +### Gaining Super Vision into Mock Calls + +You have a test using gMock. It fails: gMock tells you some expectations aren't +satisfied. However, you aren't sure why: Is there a typo somewhere in the +matchers? Did you mess up the order of the `EXPECT_CALL`s? Or is the code under +test doing something wrong? How can you find out the cause? + +Won't it be nice if you have X-ray vision and can actually see the trace of all +`EXPECT_CALL`s and mock method calls as they are made? For each call, would you +like to see its actual argument values and which `EXPECT_CALL` gMock thinks it +matches? If you still need some help to figure out who made these calls, how +about being able to see the complete stack trace at each mock call? + +You can unlock this power by running your test with the `--gmock_verbose=info` +flag. For example, given the test program: + +```cpp +#include "gmock/gmock.h" + +using testing::_; +using testing::HasSubstr; +using testing::Return; + +class MockFoo { + public: + MOCK_METHOD(void, F, (const string& x, const string& y)); +}; + +TEST(Foo, Bar) { + MockFoo mock; + EXPECT_CALL(mock, F(_, _)).WillRepeatedly(Return()); + EXPECT_CALL(mock, F("a", "b")); + EXPECT_CALL(mock, F("c", HasSubstr("d"))); + + mock.F("a", "good"); + mock.F("a", "b"); +} +``` + +if you run it with `--gmock_verbose=info`, you will see this output: + +```shell +[ RUN ] Foo.Bar + +foo_test.cc:14: EXPECT_CALL(mock, F(_, _)) invoked +Stack trace: ... + +foo_test.cc:15: EXPECT_CALL(mock, F("a", "b")) invoked +Stack trace: ... + +foo_test.cc:16: EXPECT_CALL(mock, F("c", HasSubstr("d"))) invoked +Stack trace: ... + +foo_test.cc:14: Mock function call matches EXPECT_CALL(mock, F(_, _))... + Function call: F(@0x7fff7c8dad40"a",@0x7fff7c8dad10"good") +Stack trace: ... + +foo_test.cc:15: Mock function call matches EXPECT_CALL(mock, F("a", "b"))... + Function call: F(@0x7fff7c8dada0"a",@0x7fff7c8dad70"b") +Stack trace: ... + +foo_test.cc:16: Failure +Actual function call count doesn't match EXPECT_CALL(mock, F("c", HasSubstr("d")))... + Expected: to be called once + Actual: never called - unsatisfied and active +[ FAILED ] Foo.Bar +``` + +Suppose the bug is that the `"c"` in the third `EXPECT_CALL` is a typo and +should actually be `"a"`. With the above message, you should see that the actual +`F("a", "good")` call is matched by the first `EXPECT_CALL`, not the third as +you thought. From that it should be obvious that the third `EXPECT_CALL` is +written wrong. Case solved. + +If you are interested in the mock call trace but not the stack traces, you can +combine `--gmock_verbose=info` with `--gtest_stack_trace_depth=0` on the test +command line. + +### Running Tests in Emacs + +If you build and run your tests in Emacs using the `M-x google-compile` command +(as many googletest users do), the source file locations of gMock and googletest +errors will be highlighted. Just press `` on one of them and you'll be +taken to the offending line. Or, you can just type `C-x`` to jump to the next +error. + +To make it even easier, you can add the following lines to your `~/.emacs` file: + +```text +(global-set-key "\M-m" 'google-compile) ; m is for make +(global-set-key [M-down] 'next-error) +(global-set-key [M-up] '(lambda () (interactive) (next-error -1))) +``` + +Then you can type `M-m` to start a build (if you want to run the test as well, +just make sure `foo_test.run` or `runtests` is in the build command you supply +after typing `M-m`), or `M-up`/`M-down` to move back and forth between errors. + +## Extending gMock + +### Writing New Matchers Quickly {#NewMatchers} + +{: .callout .warning} +WARNING: gMock does not guarantee when or how many times a matcher will be +invoked. Therefore, all matchers must be functionally pure. See +[this section](#PureMatchers) for more details. + +The `MATCHER*` family of macros can be used to define custom matchers easily. +The syntax: + +```cpp +MATCHER(name, description_string_expression) { statements; } +``` + +will define a matcher with the given name that executes the statements, which +must return a `bool` to indicate if the match succeeds. Inside the statements, +you can refer to the value being matched by `arg`, and refer to its type by +`arg_type`. + +The *description string* is a `string`-typed expression that documents what the +matcher does, and is used to generate the failure message when the match fails. +It can (and should) reference the special `bool` variable `negation`, and should +evaluate to the description of the matcher when `negation` is `false`, or that +of the matcher's negation when `negation` is `true`. + +For convenience, we allow the description string to be empty (`""`), in which +case gMock will use the sequence of words in the matcher name as the +description. + +For example: + +```cpp +MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; } +``` + +allows you to write + +```cpp + // Expects mock_foo.Bar(n) to be called where n is divisible by 7. + EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7())); +``` + +or, + +```cpp + using ::testing::Not; + ... + // Verifies that a value is divisible by 7 and the other is not. + EXPECT_THAT(some_expression, IsDivisibleBy7()); + EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7())); +``` + +If the above assertions fail, they will print something like: + +```shell + Value of: some_expression + Expected: is divisible by 7 + Actual: 27 + ... + Value of: some_other_expression + Expected: not (is divisible by 7) + Actual: 21 +``` + +where the descriptions `"is divisible by 7"` and `"not (is divisible by 7)"` are +automatically calculated from the matcher name `IsDivisibleBy7`. + +As you may have noticed, the auto-generated descriptions (especially those for +the negation) may not be so great. You can always override them with a `string` +expression of your own: + +```cpp +MATCHER(IsDivisibleBy7, + absl::StrCat(negation ? "isn't" : "is", " divisible by 7")) { + return (arg % 7) == 0; +} +``` + +Optionally, you can stream additional information to a hidden argument named +`result_listener` to explain the match result. For example, a better definition +of `IsDivisibleBy7` is: + +```cpp +MATCHER(IsDivisibleBy7, "") { + if ((arg % 7) == 0) + return true; + + *result_listener << "the remainder is " << (arg % 7); + return false; +} +``` + +With this definition, the above assertion will give a better message: + +```shell + Value of: some_expression + Expected: is divisible by 7 + Actual: 27 (the remainder is 6) +``` + +You should let `MatchAndExplain()` print *any additional information* that can +help a user understand the match result. Note that it should explain why the +match succeeds in case of a success (unless it's obvious) - this is useful when +the matcher is used inside `Not()`. There is no need to print the argument value +itself, as gMock already prints it for you. + +{: .callout .note} +NOTE: The type of the value being matched (`arg_type`) is determined by the +context in which you use the matcher and is supplied to you by the compiler, so +you don't need to worry about declaring it (nor can you). This allows the +matcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match +any type where the value of `(arg % 7) == 0` can be implicitly converted to a +`bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an +`int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will +be `unsigned long`; and so on. + +### Writing New Parameterized Matchers Quickly + +Sometimes you'll want to define a matcher that has parameters. For that you can +use the macro: + +```cpp +MATCHER_P(name, param_name, description_string) { statements; } +``` + +where the description string can be either `""` or a `string` expression that +references `negation` and `param_name`. + +For example: + +```cpp +MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } +``` + +will allow you to write: + +```cpp + EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); +``` + +which may lead to this message (assuming `n` is 10): + +```shell + Value of: Blah("a") + Expected: has absolute value 10 + Actual: -9 +``` + +Note that both the matcher description and its parameter are printed, making the +message human-friendly. + +In the matcher definition body, you can write `foo_type` to reference the type +of a parameter named `foo`. For example, in the body of +`MATCHER_P(HasAbsoluteValue, value)` above, you can write `value_type` to refer +to the type of `value`. + +gMock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to `MATCHER_P10` to +support multi-parameter matchers: + +```cpp +MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; } +``` + +Please note that the custom description string is for a particular *instance* of +the matcher, where the parameters have been bound to actual values. Therefore +usually you'll want the parameter values to be part of the description. gMock +lets you do that by referencing the matcher parameters in the description string +expression. + +For example, + +```cpp +using ::testing::PrintToString; +MATCHER_P2(InClosedRange, low, hi, + absl::StrFormat("%s in range [%s, %s]", negation ? "isn't" : "is", + PrintToString(low), PrintToString(hi))) { + return low <= arg && arg <= hi; +} +... +EXPECT_THAT(3, InClosedRange(4, 6)); +``` + +would generate a failure that contains the message: + +```shell + Expected: is in range [4, 6] +``` + +If you specify `""` as the description, the failure message will contain the +sequence of words in the matcher name followed by the parameter values printed +as a tuple. For example, + +```cpp + MATCHER_P2(InClosedRange, low, hi, "") { ... } + ... + EXPECT_THAT(3, InClosedRange(4, 6)); +``` + +would generate a failure that contains the text: + +```shell + Expected: in closed range (4, 6) +``` + +For the purpose of typing, you can view + +```cpp +MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } +``` + +as shorthand for + +```cpp +template +FooMatcherPk +Foo(p1_type p1, ..., pk_type pk) { ... } +``` + +When you write `Foo(v1, ..., vk)`, the compiler infers the types of the +parameters `v1`, ..., and `vk` for you. If you are not happy with the result of +the type inference, you can specify the types by explicitly instantiating the +template, as in `Foo(5, false)`. As said earlier, you don't get to +(or need to) specify `arg_type` as that's determined by the context in which the +matcher is used. + +You can assign the result of expression `Foo(p1, ..., pk)` to a variable of type +`FooMatcherPk`. This can be useful when composing +matchers. Matchers that don't have a parameter or have only one parameter have +special types: you can assign `Foo()` to a `FooMatcher`-typed variable, and +assign `Foo(p)` to a `FooMatcherP`-typed variable. + +While you can instantiate a matcher template with reference types, passing the +parameters by pointer usually makes your code more readable. If, however, you +still want to pass a parameter by reference, be aware that in the failure +message generated by the matcher you will see the value of the referenced object +but not its address. + +You can overload matchers with different numbers of parameters: + +```cpp +MATCHER_P(Blah, a, description_string_1) { ... } +MATCHER_P2(Blah, a, b, description_string_2) { ... } +``` + +While it's tempting to always use the `MATCHER*` macros when defining a new +matcher, you should also consider implementing the matcher interface directly +instead (see the recipes that follow), especially if you need to use the matcher +a lot. While these approaches require more work, they give you more control on +the types of the value being matched and the matcher parameters, which in +general leads to better compiler error messages that pay off in the long run. +They also allow overloading matchers based on parameter types (as opposed to +just based on the number of parameters). + +### Writing New Monomorphic Matchers + +A matcher of argument type `T` implements the matcher interface for `T` and does +two things: it tests whether a value of type `T` matches the matcher, and can +describe what kind of values it matches. The latter ability is used for +generating readable error messages when expectations are violated. + +A matcher of `T` must declare a typedef like: + +```cpp +using is_gtest_matcher = void; +``` + +and supports the following operations: + +```cpp +// Match a value and optionally explain into an ostream. +bool matched = matcher.MatchAndExplain(value, maybe_os); +// where `value` is of type `T` and +// `maybe_os` is of type `std::ostream*`, where it can be null if the caller +// is not interested in there textual explanation. + +matcher.DescribeTo(os); +matcher.DescribeNegationTo(os); +// where `os` is of type `std::ostream*`. +``` + +If you need a custom matcher but `Truly()` is not a good option (for example, +you may not be happy with the way `Truly(predicate)` describes itself, or you +may want your matcher to be polymorphic as `Eq(value)` is), you can define a +matcher to do whatever you want in two steps: first implement the matcher +interface, and then define a factory function to create a matcher instance. The +second step is not strictly needed but it makes the syntax of using the matcher +nicer. + +For example, you can define a matcher to test whether an `int` is divisible by 7 +and then use it like this: + +```cpp +using ::testing::Matcher; + +class DivisibleBy7Matcher { + public: + using is_gtest_matcher = void; + + bool MatchAndExplain(int n, std::ostream*) const { + return (n % 7) == 0; + } + + void DescribeTo(std::ostream* os) const { + *os << "is divisible by 7"; + } + + void DescribeNegationTo(std::ostream* os) const { + *os << "is not divisible by 7"; + } +}; + +Matcher DivisibleBy7() { + return DivisibleBy7Matcher(); +} + +... + EXPECT_CALL(foo, Bar(DivisibleBy7())); +``` + +You may improve the matcher message by streaming additional information to the +`os` argument in `MatchAndExplain()`: + +```cpp +class DivisibleBy7Matcher { + public: + bool MatchAndExplain(int n, std::ostream* os) const { + const int remainder = n % 7; + if (remainder != 0 && os != nullptr) { + *os << "the remainder is " << remainder; + } + return remainder == 0; + } + ... +}; +``` + +Then, `EXPECT_THAT(x, DivisibleBy7());` may generate a message like this: + +```shell +Value of: x +Expected: is divisible by 7 + Actual: 23 (the remainder is 2) +``` + +{: .callout .tip} +Tip: for convenience, `MatchAndExplain()` can take a `MatchResultListener*` +instead of `std::ostream*`. + +### Writing New Polymorphic Matchers + +Expanding what we learned above to *polymorphic* matchers is now just as simple +as adding templates in the right place. + +```cpp + +class NotNullMatcher { + public: + using is_gtest_matcher = void; + + // To implement a polymorphic matcher, we just need to make MatchAndExplain a + // template on its first argument. + + // In this example, we want to use NotNull() with any pointer, so + // MatchAndExplain() accepts a pointer of any type as its first argument. + // In general, you can define MatchAndExplain() as an ordinary method or + // a method template, or even overload it. + template + bool MatchAndExplain(T* p, std::ostream*) const { + return p != nullptr; + } + + // Describes the property of a value matching this matcher. + void DescribeTo(std::ostream* os) const { *os << "is not NULL"; } + + // Describes the property of a value NOT matching this matcher. + void DescribeNegationTo(std::ostream* os) const { *os << "is NULL"; } +}; + +NotNullMatcher NotNull() { + return NotNullMatcher(); +} + +... + + EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. +``` + +### Legacy Matcher Implementation + +Defining matchers used to be somewhat more complicated, in which it required +several supporting classes and virtual functions. To implement a matcher for +type `T` using the legacy API you have to derive from `MatcherInterface` and +call `MakeMatcher` to construct the object. + +The interface looks like this: + +```cpp +class MatchResultListener { + public: + ... + // Streams x to the underlying ostream; does nothing if the ostream + // is NULL. + template + MatchResultListener& operator<<(const T& x); + + // Returns the underlying ostream. + std::ostream* stream(); +}; + +template +class MatcherInterface { + public: + virtual ~MatcherInterface(); + + // Returns true if and only if the matcher matches x; also explains the match + // result to 'listener'. + virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; + + // Describes this matcher to an ostream. + virtual void DescribeTo(std::ostream* os) const = 0; + + // Describes the negation of this matcher to an ostream. + virtual void DescribeNegationTo(std::ostream* os) const; +}; +``` + +Fortunately, most of the time you can define a polymorphic matcher easily with +the help of `MakePolymorphicMatcher()`. Here's how you can define `NotNull()` as +an example: + +```cpp +using ::testing::MakePolymorphicMatcher; +using ::testing::MatchResultListener; +using ::testing::PolymorphicMatcher; + +class NotNullMatcher { + public: + // To implement a polymorphic matcher, first define a COPYABLE class + // that has three members MatchAndExplain(), DescribeTo(), and + // DescribeNegationTo(), like the following. + + // In this example, we want to use NotNull() with any pointer, so + // MatchAndExplain() accepts a pointer of any type as its first argument. + // In general, you can define MatchAndExplain() as an ordinary method or + // a method template, or even overload it. + template + bool MatchAndExplain(T* p, + MatchResultListener* /* listener */) const { + return p != NULL; + } + + // Describes the property of a value matching this matcher. + void DescribeTo(std::ostream* os) const { *os << "is not NULL"; } + + // Describes the property of a value NOT matching this matcher. + void DescribeNegationTo(std::ostream* os) const { *os << "is NULL"; } +}; + +// To construct a polymorphic matcher, pass an instance of the class +// to MakePolymorphicMatcher(). Note the return type. +PolymorphicMatcher NotNull() { + return MakePolymorphicMatcher(NotNullMatcher()); +} + +... + + EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. +``` + +{: .callout .note} +**Note:** Your polymorphic matcher class does **not** need to inherit from +`MatcherInterface` or any other class, and its methods do **not** need to be +virtual. + +Like in a monomorphic matcher, you may explain the match result by streaming +additional information to the `listener` argument in `MatchAndExplain()`. + +### Writing New Cardinalities + +A cardinality is used in `Times()` to tell gMock how many times you expect a +call to occur. It doesn't have to be exact. For example, you can say +`AtLeast(5)` or `Between(2, 4)`. + +If the [built-in set](gmock_cheat_sheet.md#CardinalityList) of cardinalities +doesn't suit you, you are free to define your own by implementing the following +interface (in namespace `testing`): + +```cpp +class CardinalityInterface { + public: + virtual ~CardinalityInterface(); + + // Returns true if and only if call_count calls will satisfy this cardinality. + virtual bool IsSatisfiedByCallCount(int call_count) const = 0; + + // Returns true if and only if call_count calls will saturate this + // cardinality. + virtual bool IsSaturatedByCallCount(int call_count) const = 0; + + // Describes self to an ostream. + virtual void DescribeTo(std::ostream* os) const = 0; +}; +``` + +For example, to specify that a call must occur even number of times, you can +write + +```cpp +using ::testing::Cardinality; +using ::testing::CardinalityInterface; +using ::testing::MakeCardinality; + +class EvenNumberCardinality : public CardinalityInterface { + public: + bool IsSatisfiedByCallCount(int call_count) const override { + return (call_count % 2) == 0; + } + + bool IsSaturatedByCallCount(int call_count) const override { + return false; + } + + void DescribeTo(std::ostream* os) const { + *os << "called even number of times"; + } +}; + +Cardinality EvenNumber() { + return MakeCardinality(new EvenNumberCardinality); +} + +... + EXPECT_CALL(foo, Bar(3)) + .Times(EvenNumber()); +``` + +### Writing New Actions {#QuickNewActions} + +If the built-in actions don't work for you, you can easily define your own one. +All you need is a call operator with a signature compatible with the mocked +function. So you can use a lambda: + +``` +MockFunction mock; +EXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; }); +EXPECT_EQ(14, mock.AsStdFunction()(2)); +``` + +Or a struct with a call operator (even a templated one): + +``` +struct MultiplyBy { + template + T operator()(T arg) { return arg * multiplier; } + + int multiplier; +}; + +// Then use: +// EXPECT_CALL(...).WillOnce(MultiplyBy{7}); +``` + +It's also fine for the callable to take no arguments, ignoring the arguments +supplied to the mock function: + +``` +MockFunction mock; +EXPECT_CALL(mock, Call).WillOnce([] { return 17; }); +EXPECT_EQ(17, mock.AsStdFunction()(0)); +``` + +When used with `WillOnce`, the callable can assume it will be called at most +once and is allowed to be a move-only type: + +``` +// An action that contains move-only types and has an &&-qualified operator, +// demanding in the type system that it be called at most once. This can be +// used with WillOnce, but the compiler will reject it if handed to +// WillRepeatedly. +struct MoveOnlyAction { + std::unique_ptr move_only_state; + std::unique_ptr operator()() && { return std::move(move_only_state); } +}; + +MockFunction()> mock; +EXPECT_CALL(mock, Call).WillOnce(MoveOnlyAction{std::make_unique(17)}); +EXPECT_THAT(mock.AsStdFunction()(), Pointee(Eq(17))); +``` + +More generally, to use with a mock function whose signature is `R(Args...)` the +object can be anything convertible to `OnceAction` or +`Action. The difference between the two is that `OnceAction` has +weaker requirements (`Action` requires a copy-constructible input that can be +called repeatedly whereas `OnceAction` requires only move-constructible and +supports `&&`-qualified call operators), but can be used only with `WillOnce`. +`OnceAction` is typically relevant only when supporting move-only types or +actions that want a type-system guarantee that they will be called at most once. + +Typically the `OnceAction` and `Action` templates need not be referenced +directly in your actions: a struct or class with a call operator is sufficient, +as in the examples above. But fancier polymorphic actions that need to know the +specific return type of the mock function can define templated conversion +operators to make that possible. See `gmock-actions.h` for examples. + +#### Legacy macro-based Actions + +Before C++11, the functor-based actions were not supported; the old way of +writing actions was through a set of `ACTION*` macros. We suggest to avoid them +in new code; they hide a lot of logic behind the macro, potentially leading to +harder-to-understand compiler errors. Nevertheless, we cover them here for +completeness. + +By writing + +```cpp +ACTION(name) { statements; } +``` + +in a namespace scope (i.e. not inside a class or function), you will define an +action with the given name that executes the statements. The value returned by +`statements` will be used as the return value of the action. Inside the +statements, you can refer to the K-th (0-based) argument of the mock function as +`argK`. For example: + +```cpp +ACTION(IncrementArg1) { return ++(*arg1); } +``` + +allows you to write + +```cpp +... WillOnce(IncrementArg1()); +``` + +Note that you don't need to specify the types of the mock function arguments. +Rest assured that your code is type-safe though: you'll get a compiler error if +`*arg1` doesn't support the `++` operator, or if the type of `++(*arg1)` isn't +compatible with the mock function's return type. + +Another example: + +```cpp +ACTION(Foo) { + (*arg2)(5); + Blah(); + *arg1 = 0; + return arg0; +} +``` + +defines an action `Foo()` that invokes argument #2 (a function pointer) with 5, +calls function `Blah()`, sets the value pointed to by argument #1 to 0, and +returns argument #0. + +For more convenience and flexibility, you can also use the following pre-defined +symbols in the body of `ACTION`: + +`argK_type` | The type of the K-th (0-based) argument of the mock function +:-------------- | :----------------------------------------------------------- +`args` | All arguments of the mock function as a tuple +`args_type` | The type of all arguments of the mock function as a tuple +`return_type` | The return type of the mock function +`function_type` | The type of the mock function + +For example, when using an `ACTION` as a stub action for mock function: + +```cpp +int DoSomething(bool flag, int* ptr); +``` + +we have: + +Pre-defined Symbol | Is Bound To +------------------ | --------------------------------- +`arg0` | the value of `flag` +`arg0_type` | the type `bool` +`arg1` | the value of `ptr` +`arg1_type` | the type `int*` +`args` | the tuple `(flag, ptr)` +`args_type` | the type `std::tuple` +`return_type` | the type `int` +`function_type` | the type `int(bool, int*)` + +#### Legacy macro-based parameterized Actions + +Sometimes you'll want to parameterize an action you define. For that we have +another macro + +```cpp +ACTION_P(name, param) { statements; } +``` + +For example, + +```cpp +ACTION_P(Add, n) { return arg0 + n; } +``` + +will allow you to write + +```cpp +// Returns argument #0 + 5. +... WillOnce(Add(5)); +``` + +For convenience, we use the term *arguments* for the values used to invoke the +mock function, and the term *parameters* for the values used to instantiate an +action. + +Note that you don't need to provide the type of the parameter either. Suppose +the parameter is named `param`, you can also use the gMock-defined symbol +`param_type` to refer to the type of the parameter as inferred by the compiler. +For example, in the body of `ACTION_P(Add, n)` above, you can write `n_type` for +the type of `n`. + +gMock also provides `ACTION_P2`, `ACTION_P3`, and etc to support multi-parameter +actions. For example, + +```cpp +ACTION_P2(ReturnDistanceTo, x, y) { + double dx = arg0 - x; + double dy = arg1 - y; + return sqrt(dx*dx + dy*dy); +} +``` + +lets you write + +```cpp +... WillOnce(ReturnDistanceTo(5.0, 26.5)); +``` + +You can view `ACTION` as a degenerated parameterized action where the number of +parameters is 0. + +You can also easily define actions overloaded on the number of parameters: + +```cpp +ACTION_P(Plus, a) { ... } +ACTION_P2(Plus, a, b) { ... } +``` + +### Restricting the Type of an Argument or Parameter in an ACTION + +For maximum brevity and reusability, the `ACTION*` macros don't ask you to +provide the types of the mock function arguments and the action parameters. +Instead, we let the compiler infer the types for us. + +Sometimes, however, we may want to be more explicit about the types. There are +several tricks to do that. For example: + +```cpp +ACTION(Foo) { + // Makes sure arg0 can be converted to int. + int n = arg0; + ... use n instead of arg0 here ... +} + +ACTION_P(Bar, param) { + // Makes sure the type of arg1 is const char*. + ::testing::StaticAssertTypeEq(); + + // Makes sure param can be converted to bool. + bool flag = param; +} +``` + +where `StaticAssertTypeEq` is a compile-time assertion in googletest that +verifies two types are the same. + +### Writing New Action Templates Quickly + +Sometimes you want to give an action explicit template parameters that cannot be +inferred from its value parameters. `ACTION_TEMPLATE()` supports that and can be +viewed as an extension to `ACTION()` and `ACTION_P*()`. + +The syntax: + +```cpp +ACTION_TEMPLATE(ActionName, + HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), + AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } +``` + +defines an action template that takes *m* explicit template parameters and *n* +value parameters, where *m* is in [1, 10] and *n* is in [0, 10]. `name_i` is the +name of the *i*-th template parameter, and `kind_i` specifies whether it's a +`typename`, an integral constant, or a template. `p_i` is the name of the *i*-th +value parameter. + +Example: + +```cpp +// DuplicateArg(output) converts the k-th argument of the mock +// function to type T and copies it to *output. +ACTION_TEMPLATE(DuplicateArg, + // Note the comma between int and k: + HAS_2_TEMPLATE_PARAMS(int, k, typename, T), + AND_1_VALUE_PARAMS(output)) { + *output = T(std::get(args)); +} +``` + +To create an instance of an action template, write: + +```cpp +ActionName(v1, ..., v_n) +``` + +where the `t`s are the template arguments and the `v`s are the value arguments. +The value argument types are inferred by the compiler. For example: + +```cpp +using ::testing::_; +... + int n; + EXPECT_CALL(mock, Foo).WillOnce(DuplicateArg<1, unsigned char>(&n)); +``` + +If you want to explicitly specify the value argument types, you can provide +additional template arguments: + +```cpp +ActionName(v1, ..., v_n) +``` + +where `u_i` is the desired type of `v_i`. + +`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the number of +value parameters, but not on the number of template parameters. Without the +restriction, the meaning of the following is unclear: + +```cpp + OverloadedAction(x); +``` + +Are we using a single-template-parameter action where `bool` refers to the type +of `x`, or a two-template-parameter action where the compiler is asked to infer +the type of `x`? + +### Using the ACTION Object's Type + +If you are writing a function that returns an `ACTION` object, you'll need to +know its type. The type depends on the macro used to define the action and the +parameter types. The rule is relatively simple: + + +| Given Definition | Expression | Has Type | +| ----------------------------- | ------------------- | --------------------- | +| `ACTION(Foo)` | `Foo()` | `FooAction` | +| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo()` | `FooAction` | +| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP` | +| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar(int_value)` | `BarActionP` | +| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2` | +| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz(bool_value, int_value)` | `BazActionP2` | +| ... | ... | ... | + + +Note that we have to pick different suffixes (`Action`, `ActionP`, `ActionP2`, +and etc) for actions with different numbers of value parameters, or the action +definitions cannot be overloaded on the number of them. + +### Writing New Monomorphic Actions {#NewMonoActions} + +While the `ACTION*` macros are very convenient, sometimes they are +inappropriate. For example, despite the tricks shown in the previous recipes, +they don't let you directly specify the types of the mock function arguments and +the action parameters, which in general leads to unoptimized compiler error +messages that can baffle unfamiliar users. They also don't allow overloading +actions based on parameter types without jumping through some hoops. + +An alternative to the `ACTION*` macros is to implement +`::testing::ActionInterface`, where `F` is the type of the mock function in +which the action will be used. For example: + +```cpp +template +class ActionInterface { + public: + virtual ~ActionInterface(); + + // Performs the action. Result is the return type of function type + // F, and ArgumentTuple is the tuple of arguments of F. + // + + // For example, if F is int(bool, const string&), then Result would + // be int, and ArgumentTuple would be std::tuple. + virtual Result Perform(const ArgumentTuple& args) = 0; +}; +``` + +```cpp +using ::testing::_; +using ::testing::Action; +using ::testing::ActionInterface; +using ::testing::MakeAction; + +typedef int IncrementMethod(int*); + +class IncrementArgumentAction : public ActionInterface { + public: + int Perform(const std::tuple& args) override { + int* p = std::get<0>(args); // Grabs the first argument. + return *p++; + } +}; + +Action IncrementArgument() { + return MakeAction(new IncrementArgumentAction); +} + +... + EXPECT_CALL(foo, Baz(_)) + .WillOnce(IncrementArgument()); + + int n = 5; + foo.Baz(&n); // Should return 5 and change n to 6. +``` + +### Writing New Polymorphic Actions {#NewPolyActions} + +The previous recipe showed you how to define your own action. This is all good, +except that you need to know the type of the function in which the action will +be used. Sometimes that can be a problem. For example, if you want to use the +action in functions with *different* types (e.g. like `Return()` and +`SetArgPointee()`). + +If an action can be used in several types of mock functions, we say it's +*polymorphic*. The `MakePolymorphicAction()` function template makes it easy to +define such an action: + +```cpp +namespace testing { +template +PolymorphicAction MakePolymorphicAction(const Impl& impl); +} // namespace testing +``` + +As an example, let's define an action that returns the second argument in the +mock function's argument list. The first step is to define an implementation +class: + +```cpp +class ReturnSecondArgumentAction { + public: + template + Result Perform(const ArgumentTuple& args) const { + // To get the i-th (0-based) argument, use std::get(args). + return std::get<1>(args); + } +}; +``` + +This implementation class does *not* need to inherit from any particular class. +What matters is that it must have a `Perform()` method template. This method +template takes the mock function's arguments as a tuple in a **single** +argument, and returns the result of the action. It can be either `const` or not, +but must be invocable with exactly one template argument, which is the result +type. In other words, you must be able to call `Perform(args)` where `R` is +the mock function's return type and `args` is its arguments in a tuple. + +Next, we use `MakePolymorphicAction()` to turn an instance of the implementation +class into the polymorphic action we need. It will be convenient to have a +wrapper for this: + +```cpp +using ::testing::MakePolymorphicAction; +using ::testing::PolymorphicAction; + +PolymorphicAction ReturnSecondArgument() { + return MakePolymorphicAction(ReturnSecondArgumentAction()); +} +``` + +Now, you can use this polymorphic action the same way you use the built-in ones: + +```cpp +using ::testing::_; + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, DoThis, (bool flag, int n), (override)); + MOCK_METHOD(string, DoThat, (int x, const char* str1, const char* str2), + (override)); +}; + + ... + MockFoo foo; + EXPECT_CALL(foo, DoThis).WillOnce(ReturnSecondArgument()); + EXPECT_CALL(foo, DoThat).WillOnce(ReturnSecondArgument()); + ... + foo.DoThis(true, 5); // Will return 5. + foo.DoThat(1, "Hi", "Bye"); // Will return "Hi". +``` + +### Teaching gMock How to Print Your Values + +When an uninteresting or unexpected call occurs, gMock prints the argument +values and the stack trace to help you debug. Assertion macros like +`EXPECT_THAT` and `EXPECT_EQ` also print the values in question when the +assertion fails. gMock and googletest do this using googletest's user-extensible +value printer. + +This printer knows how to print built-in C++ types, native arrays, STL +containers, and any type that supports the `<<` operator. For other types, it +prints the raw bytes in the value and hopes that you the user can figure it out. +[The GoogleTest advanced guide](advanced.md#teaching-googletest-how-to-print-your-values) +explains how to extend the printer to do a better job at printing your +particular type than to dump the bytes. + +## Useful Mocks Created Using gMock + + + + +### Mock std::function {#MockFunction} + +`std::function` is a general function type introduced in C++11. It is a +preferred way of passing callbacks to new interfaces. Functions are copiable, +and are not usually passed around by pointer, which makes them tricky to mock. +But fear not - `MockFunction` can help you with that. + +`MockFunction` has a mock method `Call()` with the signature: + +```cpp + R Call(T1, ..., Tn); +``` + +It also has a `AsStdFunction()` method, which creates a `std::function` proxy +forwarding to Call: + +```cpp + std::function AsStdFunction(); +``` + +To use `MockFunction`, first create `MockFunction` object and set up +expectations on its `Call` method. Then pass proxy obtained from +`AsStdFunction()` to the code you are testing. For example: + +```cpp +TEST(FooTest, RunsCallbackWithBarArgument) { + // 1. Create a mock object. + MockFunction mock_function; + + // 2. Set expectations on Call() method. + EXPECT_CALL(mock_function, Call("bar")).WillOnce(Return(1)); + + // 3. Exercise code that uses std::function. + Foo(mock_function.AsStdFunction()); + // Foo's signature can be either of: + // void Foo(const std::function& fun); + // void Foo(std::function fun); + + // 4. All expectations will be verified when mock_function + // goes out of scope and is destroyed. +} +``` + +Remember that function objects created with `AsStdFunction()` are just +forwarders. If you create multiple of them, they will share the same set of +expectations. + +Although `std::function` supports unlimited number of arguments, `MockFunction` +implementation is limited to ten. If you ever hit that limit... well, your +callback has bigger problems than being mockable. :-) diff --git a/third_party/googletest/docs/gmock_faq.md b/third_party/googletest/docs/gmock_faq.md new file mode 100644 index 0000000..8f220bf --- /dev/null +++ b/third_party/googletest/docs/gmock_faq.md @@ -0,0 +1,390 @@ +# Legacy gMock FAQ + +### When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? + +In order for a method to be mocked, it must be *virtual*, unless you use the +[high-perf dependency injection technique](gmock_cook_book.md#MockingNonVirtualMethods). + +### Can I mock a variadic function? + +You cannot mock a variadic function (i.e. a function taking ellipsis (`...`) +arguments) directly in gMock. + +The problem is that in general, there is *no way* for a mock object to know how +many arguments are passed to the variadic method, and what the arguments' types +are. Only the *author of the base class* knows the protocol, and we cannot look +into his or her head. + +Therefore, to mock such a function, the *user* must teach the mock object how to +figure out the number of arguments and their types. One way to do it is to +provide overloaded versions of the function. + +Ellipsis arguments are inherited from C and not really a C++ feature. They are +unsafe to use and don't work with arguments that have constructors or +destructors. Therefore we recommend to avoid them in C++ as much as possible. + +### MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? + +If you compile this using Microsoft Visual C++ 2005 SP1: + +```cpp +class Foo { + ... + virtual void Bar(const int i) = 0; +}; + +class MockFoo : public Foo { + ... + MOCK_METHOD(void, Bar, (const int i), (override)); +}; +``` + +You may get the following warning: + +```shell +warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier +``` + +This is a MSVC bug. The same code compiles fine with gcc, for example. If you +use Visual C++ 2008 SP1, you would get the warning: + +```shell +warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers +``` + +In C++, if you *declare* a function with a `const` parameter, the `const` +modifier is ignored. Therefore, the `Foo` base class above is equivalent to: + +```cpp +class Foo { + ... + virtual void Bar(int i) = 0; // int or const int? Makes no difference. +}; +``` + +In fact, you can *declare* `Bar()` with an `int` parameter, and define it with a +`const int` parameter. The compiler will still match them up. + +Since making a parameter `const` is meaningless in the method declaration, we +recommend to remove it in both `Foo` and `MockFoo`. That should workaround the +VC bug. + +Note that we are talking about the *top-level* `const` modifier here. If the +function parameter is passed by pointer or reference, declaring the pointee or +referee as `const` is still meaningful. For example, the following two +declarations are *not* equivalent: + +```cpp +void Bar(int* p); // Neither p nor *p is const. +void Bar(const int* p); // p is not const, but *p is. +``` + +### I can't figure out why gMock thinks my expectations are not satisfied. What should I do? + +You might want to run your test with `--gmock_verbose=info`. This flag lets +gMock print a trace of every mock function call it receives. By studying the +trace, you'll gain insights on why the expectations you set are not met. + +If you see the message "The mock function has no default action set, and its +return type has no default value set.", then try +[adding a default action](gmock_cheat_sheet.md#OnCall). Due to a known issue, +unexpected calls on mocks without default actions don't print out a detailed +comparison between the actual arguments and the expected arguments. + +### My program crashed and `ScopedMockLog` spit out tons of messages. Is it a gMock bug? + +gMock and `ScopedMockLog` are likely doing the right thing here. + +When a test crashes, the failure signal handler will try to log a lot of +information (the stack trace, and the address map, for example). The messages +are compounded if you have many threads with depth stacks. When `ScopedMockLog` +intercepts these messages and finds that they don't match any expectations, it +prints an error for each of them. + +You can learn to ignore the errors, or you can rewrite your expectations to make +your test more robust, for example, by adding something like: + +```cpp +using ::testing::AnyNumber; +using ::testing::Not; +... + // Ignores any log not done by us. + EXPECT_CALL(log, Log(_, Not(EndsWith("/my_file.cc")), _)) + .Times(AnyNumber()); +``` + +### How can I assert that a function is NEVER called? + +```cpp +using ::testing::_; +... + EXPECT_CALL(foo, Bar(_)) + .Times(0); +``` + +### I have a failed test where gMock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? + +When gMock detects a failure, it prints relevant information (the mock function +arguments, the state of relevant expectations, and etc) to help the user debug. +If another failure is detected, gMock will do the same, including printing the +state of relevant expectations. + +Sometimes an expectation's state didn't change between two failures, and you'll +see the same description of the state twice. They are however *not* redundant, +as they refer to *different points in time*. The fact they are the same *is* +interesting information. + +### I get a heapcheck failure when using a mock object, but using a real object is fine. What can be wrong? + +Does the class (hopefully a pure interface) you are mocking have a virtual +destructor? + +Whenever you derive from a base class, make sure its destructor is virtual. +Otherwise Bad Things will happen. Consider the following code: + +```cpp +class Base { + public: + // Not virtual, but should be. + ~Base() { ... } + ... +}; + +class Derived : public Base { + public: + ... + private: + std::string value_; +}; + +... + Base* p = new Derived; + ... + delete p; // Surprise! ~Base() will be called, but ~Derived() will not + // - value_ is leaked. +``` + +By changing `~Base()` to virtual, `~Derived()` will be correctly called when +`delete p` is executed, and the heap checker will be happy. + +### The "newer expectations override older ones" rule makes writing expectations awkward. Why does gMock do that? + +When people complain about this, often they are referring to code like: + +```cpp +using ::testing::Return; +... + // foo.Bar() should be called twice, return 1 the first time, and return + // 2 the second time. However, I have to write the expectations in the + // reverse order. This sucks big time!!! + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(2)) + .RetiresOnSaturation(); + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(1)) + .RetiresOnSaturation(); +``` + +The problem, is that they didn't pick the **best** way to express the test's +intent. + +By default, expectations don't have to be matched in *any* particular order. If +you want them to match in a certain order, you need to be explicit. This is +gMock's (and jMock's) fundamental philosophy: it's easy to accidentally +over-specify your tests, and we want to make it harder to do so. + +There are two better ways to write the test spec. You could either put the +expectations in sequence: + +```cpp +using ::testing::Return; +... + // foo.Bar() should be called twice, return 1 the first time, and return + // 2 the second time. Using a sequence, we can write the expectations + // in their natural order. + { + InSequence s; + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(1)) + .RetiresOnSaturation(); + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(2)) + .RetiresOnSaturation(); + } +``` + +or you can put the sequence of actions in the same expectation: + +```cpp +using ::testing::Return; +... + // foo.Bar() should be called twice, return 1 the first time, and return + // 2 the second time. + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(1)) + .WillOnce(Return(2)) + .RetiresOnSaturation(); +``` + +Back to the original questions: why does gMock search the expectations (and +`ON_CALL`s) from back to front? Because this allows a user to set up a mock's +behavior for the common case early (e.g. in the mock's constructor or the test +fixture's set-up phase) and customize it with more specific rules later. If +gMock searches from front to back, this very useful pattern won't be possible. + +### gMock prints a warning when a function without EXPECT_CALL is called, even if I have set its behavior using ON_CALL. Would it be reasonable not to show the warning in this case? + +When choosing between being neat and being safe, we lean toward the latter. So +the answer is that we think it's better to show the warning. + +Often people write `ON_CALL`s in the mock object's constructor or `SetUp()`, as +the default behavior rarely changes from test to test. Then in the test body +they set the expectations, which are often different for each test. Having an +`ON_CALL` in the set-up part of a test doesn't mean that the calls are expected. +If there's no `EXPECT_CALL` and the method is called, it's possibly an error. If +we quietly let the call go through without notifying the user, bugs may creep in +unnoticed. + +If, however, you are sure that the calls are OK, you can write + +```cpp +using ::testing::_; +... + EXPECT_CALL(foo, Bar(_)) + .WillRepeatedly(...); +``` + +instead of + +```cpp +using ::testing::_; +... + ON_CALL(foo, Bar(_)) + .WillByDefault(...); +``` + +This tells gMock that you do expect the calls and no warning should be printed. + +Also, you can control the verbosity by specifying `--gmock_verbose=error`. Other +values are `info` and `warning`. If you find the output too noisy when +debugging, just choose a less verbose level. + +### How can I delete the mock function's argument in an action? + +If your mock function takes a pointer argument and you want to delete that +argument, you can use testing::DeleteArg() to delete the N'th (zero-indexed) +argument: + +```cpp +using ::testing::_; + ... + MOCK_METHOD(void, Bar, (X* x, const Y& y)); + ... + EXPECT_CALL(mock_foo_, Bar(_, _)) + .WillOnce(testing::DeleteArg<0>())); +``` + +### How can I perform an arbitrary action on a mock function's argument? + +If you find yourself needing to perform some action that's not supported by +gMock directly, remember that you can define your own actions using +[`MakeAction()`](#NewMonoActions) or +[`MakePolymorphicAction()`](#NewPolyActions), or you can write a stub function +and invoke it using [`Invoke()`](#FunctionsAsActions). + +```cpp +using ::testing::_; +using ::testing::Invoke; + ... + MOCK_METHOD(void, Bar, (X* p)); + ... + EXPECT_CALL(mock_foo_, Bar(_)) + .WillOnce(Invoke(MyAction(...))); +``` + +### My code calls a static/global function. Can I mock it? + +You can, but you need to make some changes. + +In general, if you find yourself needing to mock a static function, it's a sign +that your modules are too tightly coupled (and less flexible, less reusable, +less testable, etc). You are probably better off defining a small interface and +call the function through that interface, which then can be easily mocked. It's +a bit of work initially, but usually pays for itself quickly. + +This Google Testing Blog +[post](https://testing.googleblog.com/2008/06/defeat-static-cling.html) says it +excellently. Check it out. + +### My mock object needs to do complex stuff. It's a lot of pain to specify the actions. gMock sucks! + +I know it's not a question, but you get an answer for free any way. :-) + +With gMock, you can create mocks in C++ easily. And people might be tempted to +use them everywhere. Sometimes they work great, and sometimes you may find them, +well, a pain to use. So, what's wrong in the latter case? + +When you write a test without using mocks, you exercise the code and assert that +it returns the correct value or that the system is in an expected state. This is +sometimes called "state-based testing". + +Mocks are great for what some call "interaction-based" testing: instead of +checking the system state at the very end, mock objects verify that they are +invoked the right way and report an error as soon as it arises, giving you a +handle on the precise context in which the error was triggered. This is often +more effective and economical to do than state-based testing. + +If you are doing state-based testing and using a test double just to simulate +the real object, you are probably better off using a fake. Using a mock in this +case causes pain, as it's not a strong point for mocks to perform complex +actions. If you experience this and think that mocks suck, you are just not +using the right tool for your problem. Or, you might be trying to solve the +wrong problem. :-) + +### I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? + +By all means, NO! It's just an FYI. :-) + +What it means is that you have a mock function, you haven't set any expectations +on it (by gMock's rule this means that you are not interested in calls to this +function and therefore it can be called any number of times), and it is called. +That's OK - you didn't say it's not OK to call the function! + +What if you actually meant to disallow this function to be called, but forgot to +write `EXPECT_CALL(foo, Bar()).Times(0)`? While one can argue that it's the +user's fault, gMock tries to be nice and prints you a note. + +So, when you see the message and believe that there shouldn't be any +uninteresting calls, you should investigate what's going on. To make your life +easier, gMock dumps the stack trace when an uninteresting call is encountered. +From that you can figure out which mock function it is, and how it is called. + +### I want to define a custom action. Should I use Invoke() or implement the ActionInterface interface? + +Either way is fine - you want to choose the one that's more convenient for your +circumstance. + +Usually, if your action is for a particular function type, defining it using +`Invoke()` should be easier; if your action can be used in functions of +different types (e.g. if you are defining `Return(*value*)`), +`MakePolymorphicAction()` is easiest. Sometimes you want precise control on what +types of functions the action can be used in, and implementing `ActionInterface` +is the way to go here. See the implementation of `Return()` in `gmock-actions.h` +for an example. + +### I use SetArgPointee() in WillOnce(), but gcc complains about "conflicting return type specified". What does it mean? + +You got this error as gMock has no idea what value it should return when the +mock method is called. `SetArgPointee()` says what the side effect is, but +doesn't say what the return value should be. You need `DoAll()` to chain a +`SetArgPointee()` with a `Return()` that provides a value appropriate to the API +being mocked. + +See this [recipe](gmock_cook_book.md#mocking-side-effects) for more details and +an example. + +### I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? + +We've noticed that when the `/clr` compiler flag is used, Visual C++ uses 5~6 +times as much memory when compiling a mock class. We suggest to avoid `/clr` +when compiling native C++ mocks. diff --git a/third_party/googletest/docs/gmock_for_dummies.md b/third_party/googletest/docs/gmock_for_dummies.md new file mode 100644 index 0000000..b7264d3 --- /dev/null +++ b/third_party/googletest/docs/gmock_for_dummies.md @@ -0,0 +1,700 @@ +# gMock for Dummies + +## What Is gMock? + +When you write a prototype or test, often it's not feasible or wise to rely on +real objects entirely. A **mock object** implements the same interface as a real +object (so it can be used as one), but lets you specify at run time how it will +be used and what it should do (which methods will be called? in which order? how +many times? with what arguments? what will they return? etc). + +It is easy to confuse the term *fake objects* with mock objects. Fakes and mocks +actually mean very different things in the Test-Driven Development (TDD) +community: + +* **Fake** objects have working implementations, but usually take some + shortcut (perhaps to make the operations less expensive), which makes them + not suitable for production. An in-memory file system would be an example of + a fake. +* **Mocks** are objects pre-programmed with *expectations*, which form a + specification of the calls they are expected to receive. + +If all this seems too abstract for you, don't worry - the most important thing +to remember is that a mock allows you to check the *interaction* between itself +and code that uses it. The difference between fakes and mocks shall become much +clearer once you start to use mocks. + +**gMock** is a library (sometimes we also call it a "framework" to make it sound +cool) for creating mock classes and using them. It does to C++ what +jMock/EasyMock does to Java (well, more or less). + +When using gMock, + +1. first, you use some simple macros to describe the interface you want to + mock, and they will expand to the implementation of your mock class; +2. next, you create some mock objects and specify its expectations and behavior + using an intuitive syntax; +3. then you exercise code that uses the mock objects. gMock will catch any + violation to the expectations as soon as it arises. + +## Why gMock? + +While mock objects help you remove unnecessary dependencies in tests and make +them fast and reliable, using mocks manually in C++ is *hard*: + +* Someone has to implement the mocks. The job is usually tedious and + error-prone. No wonder people go great distance to avoid it. +* The quality of those manually written mocks is a bit, uh, unpredictable. You + may see some really polished ones, but you may also see some that were + hacked up in a hurry and have all sorts of ad hoc restrictions. +* The knowledge you gained from using one mock doesn't transfer to the next + one. + +In contrast, Java and Python programmers have some fine mock frameworks (jMock, +EasyMock, etc), which automate the creation of mocks. As a result, mocking is a +proven effective technique and widely adopted practice in those communities. +Having the right tool absolutely makes the difference. + +gMock was built to help C++ programmers. It was inspired by jMock and EasyMock, +but designed with C++'s specifics in mind. It is your friend if any of the +following problems is bothering you: + +* You are stuck with a sub-optimal design and wish you had done more + prototyping before it was too late, but prototyping in C++ is by no means + "rapid". +* Your tests are slow as they depend on too many libraries or use expensive + resources (e.g. a database). +* Your tests are brittle as some resources they use are unreliable (e.g. the + network). +* You want to test how your code handles a failure (e.g. a file checksum + error), but it's not easy to cause one. +* You need to make sure that your module interacts with other modules in the + right way, but it's hard to observe the interaction; therefore you resort to + observing the side effects at the end of the action, but it's awkward at + best. +* You want to "mock out" your dependencies, except that they don't have mock + implementations yet; and, frankly, you aren't thrilled by some of those + hand-written mocks. + +We encourage you to use gMock as + +* a *design* tool, for it lets you experiment with your interface design early + and often. More iterations lead to better designs! +* a *testing* tool to cut your tests' outbound dependencies and probe the + interaction between your module and its collaborators. + +## Getting Started + +gMock is bundled with googletest. + +## A Case for Mock Turtles + +Let's look at an example. Suppose you are developing a graphics program that +relies on a [LOGO](http://en.wikipedia.org/wiki/Logo_programming_language)-like +API for drawing. How would you test that it does the right thing? Well, you can +run it and compare the screen with a golden screen snapshot, but let's admit it: +tests like this are expensive to run and fragile (What if you just upgraded to a +shiny new graphics card that has better anti-aliasing? Suddenly you have to +update all your golden images.). It would be too painful if all your tests are +like this. Fortunately, you learned about +[Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection) and know the right thing +to do: instead of having your application talk to the system API directly, wrap +the API in an interface (say, `Turtle`) and code to that interface: + +```cpp +class Turtle { + ... + virtual ~Turtle() {} + virtual void PenUp() = 0; + virtual void PenDown() = 0; + virtual void Forward(int distance) = 0; + virtual void Turn(int degrees) = 0; + virtual void GoTo(int x, int y) = 0; + virtual int GetX() const = 0; + virtual int GetY() const = 0; +}; +``` + +(Note that the destructor of `Turtle` **must** be virtual, as is the case for +**all** classes you intend to inherit from - otherwise the destructor of the +derived class will not be called when you delete an object through a base +pointer, and you'll get corrupted program states like memory leaks.) + +You can control whether the turtle's movement will leave a trace using `PenUp()` +and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and +`GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the +turtle. + +Your program will normally use a real implementation of this interface. In +tests, you can use a mock implementation instead. This allows you to easily +check what drawing primitives your program is calling, with what arguments, and +in which order. Tests written this way are much more robust (they won't break +because your new machine does anti-aliasing differently), easier to read and +maintain (the intent of a test is expressed in the code, not in some binary +images), and run *much, much faster*. + +## Writing the Mock Class + +If you are lucky, the mocks you need to use have already been implemented by +some nice people. If, however, you find yourself in the position to write a mock +class, relax - gMock turns this task into a fun game! (Well, almost.) + +### How to Define It + +Using the `Turtle` interface as example, here are the simple steps you need to +follow: + +* Derive a class `MockTurtle` from `Turtle`. +* Take a *virtual* function of `Turtle` (while it's possible to + [mock non-virtual methods using templates](gmock_cook_book.md#MockingNonVirtualMethods), + it's much more involved). +* In the `public:` section of the child class, write `MOCK_METHOD();` +* Now comes the fun part: you take the function signature, cut-and-paste it + into the macro, and add two commas - one between the return type and the + name, another between the name and the argument list. +* If you're mocking a const method, add a 4th parameter containing `(const)` + (the parentheses are required). +* Since you're overriding a virtual method, we suggest adding the `override` + keyword. For const methods the 4th parameter becomes `(const, override)`, + for non-const methods just `(override)`. This isn't mandatory. +* Repeat until all virtual functions you want to mock are done. (It goes + without saying that *all* pure virtual methods in your abstract class must + be either mocked or overridden.) + +After the process, you should have something like: + +```cpp +#include "gmock/gmock.h" // Brings in gMock. + +class MockTurtle : public Turtle { + public: + ... + MOCK_METHOD(void, PenUp, (), (override)); + MOCK_METHOD(void, PenDown, (), (override)); + MOCK_METHOD(void, Forward, (int distance), (override)); + MOCK_METHOD(void, Turn, (int degrees), (override)); + MOCK_METHOD(void, GoTo, (int x, int y), (override)); + MOCK_METHOD(int, GetX, (), (const, override)); + MOCK_METHOD(int, GetY, (), (const, override)); +}; +``` + +You don't need to define these mock methods somewhere else - the `MOCK_METHOD` +macro will generate the definitions for you. It's that simple! + +### Where to Put It + +When you define a mock class, you need to decide where to put its definition. +Some people put it in a `_test.cc`. This is fine when the interface being mocked +(say, `Foo`) is owned by the same person or team. Otherwise, when the owner of +`Foo` changes it, your test could break. (You can't really expect `Foo`'s +maintainer to fix every test that uses `Foo`, can you?) + +Generally, you should not mock classes you don't own. If you must mock such a +class owned by others, define the mock class in `Foo`'s Bazel package (usually +the same directory or a `testing` sub-directory), and put it in a `.h` and a +`cc_library` with `testonly=True`. Then everyone can reference them from their +tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and +only tests that depend on the changed methods need to be fixed. + +Another way to do it: you can introduce a thin layer `FooAdaptor` on top of +`Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb +changes in `Foo` much more easily. While this is more work initially, carefully +choosing the adaptor interface can make your code easier to write and more +readable (a net win in the long run), as you can choose `FooAdaptor` to fit your +specific domain much better than `Foo` does. + +## Using Mocks in Tests + +Once you have a mock class, using it is easy. The typical work flow is: + +1. Import the gMock names from the `testing` namespace such that you can use + them unqualified (You only have to do it once per file). Remember that + namespaces are a good idea. +2. Create some mock objects. +3. Specify your expectations on them (How many times will a method be called? + With what arguments? What should it do? etc.). +4. Exercise some code that uses the mocks; optionally, check the result using + googletest assertions. If a mock method is called more than expected or with + wrong arguments, you'll get an error immediately. +5. When a mock is destructed, gMock will automatically check whether all + expectations on it have been satisfied. + +Here's an example: + +```cpp +#include "path/to/mock-turtle.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +using ::testing::AtLeast; // #1 + +TEST(PainterTest, CanDrawSomething) { + MockTurtle turtle; // #2 + EXPECT_CALL(turtle, PenDown()) // #3 + .Times(AtLeast(1)); + + Painter painter(&turtle); // #4 + + EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); // #5 +} +``` + +As you might have guessed, this test checks that `PenDown()` is called at least +once. If the `painter` object didn't call this method, your test will fail with +a message like this: + +```text +path/to/my_test.cc:119: Failure +Actual function call count doesn't match this expectation: +Actually: never called; +Expected: called at least once. +Stack trace: +... +``` + +**Tip 1:** If you run the test from an Emacs buffer, you can hit `` on +the line number to jump right to the failed expectation. + +**Tip 2:** If your mock objects are never deleted, the final verification won't +happen. Therefore it's a good idea to turn on the heap checker in your tests +when you allocate mocks on the heap. You get that automatically if you use the +`gtest_main` library already. + +**Important note:** gMock requires expectations to be set **before** the mock +functions are called, otherwise the behavior is **undefined**. Do not alternate +between calls to `EXPECT_CALL()` and calls to the mock functions, and do not set +any expectations on a mock after passing the mock to an API. + +This means `EXPECT_CALL()` should be read as expecting that a call will occur +*in the future*, not that a call has occurred. Why does gMock work like that? +Well, specifying the expectation beforehand allows gMock to report a violation +as soon as it rises, when the context (stack trace, etc) is still available. +This makes debugging much easier. + +Admittedly, this test is contrived and doesn't do much. You can easily achieve +the same effect without using gMock. However, as we shall reveal soon, gMock +allows you to do *so much more* with the mocks. + +## Setting Expectations + +The key to using a mock object successfully is to set the *right expectations* +on it. If you set the expectations too strict, your test will fail as the result +of unrelated changes. If you set them too loose, bugs can slip through. You want +to do it just right such that your test can catch exactly the kind of bugs you +intend it to catch. gMock provides the necessary means for you to do it "just +right." + +### General Syntax + +In gMock we use the `EXPECT_CALL()` macro to set an expectation on a mock +method. The general syntax is: + +```cpp +EXPECT_CALL(mock_object, method(matchers)) + .Times(cardinality) + .WillOnce(action) + .WillRepeatedly(action); +``` + +The macro has two arguments: first the mock object, and then the method and its +arguments. Note that the two are separated by a comma (`,`), not a period (`.`). +(Why using a comma? The answer is that it was necessary for technical reasons.) +If the method is not overloaded, the macro can also be called without matchers: + +```cpp +EXPECT_CALL(mock_object, non-overloaded-method) + .Times(cardinality) + .WillOnce(action) + .WillRepeatedly(action); +``` + +This syntax allows the test writer to specify "called with any arguments" +without explicitly specifying the number or types of arguments. To avoid +unintended ambiguity, this syntax may only be used for methods that are not +overloaded. + +Either form of the macro can be followed by some optional *clauses* that provide +more information about the expectation. We'll discuss how each clause works in +the coming sections. + +This syntax is designed to make an expectation read like English. For example, +you can probably guess that + +```cpp +using ::testing::Return; +... +EXPECT_CALL(turtle, GetX()) + .Times(5) + .WillOnce(Return(100)) + .WillOnce(Return(150)) + .WillRepeatedly(Return(200)); +``` + +says that the `turtle` object's `GetX()` method will be called five times, it +will return 100 the first time, 150 the second time, and then 200 every time. +Some people like to call this style of syntax a Domain-Specific Language (DSL). + +{: .callout .note} +**Note:** Why do we use a macro to do this? Well it serves two purposes: first +it makes expectations easily identifiable (either by `grep` or by a human +reader), and second it allows gMock to include the source file location of a +failed expectation in messages, making debugging easier. + +### Matchers: What Arguments Do We Expect? + +When a mock function takes arguments, we may specify what arguments we are +expecting, for example: + +```cpp +// Expects the turtle to move forward by 100 units. +EXPECT_CALL(turtle, Forward(100)); +``` + +Oftentimes you do not want to be too specific. Remember that talk about tests +being too rigid? Over specification leads to brittle tests and obscures the +intent of tests. Therefore we encourage you to specify only what's necessary—no +more, no less. If you aren't interested in the value of an argument, write `_` +as the argument, which means "anything goes": + +```cpp +using ::testing::_; +... +// Expects that the turtle jumps to somewhere on the x=50 line. +EXPECT_CALL(turtle, GoTo(50, _)); +``` + +`_` is an instance of what we call **matchers**. A matcher is like a predicate +and can test whether an argument is what we'd expect. You can use a matcher +inside `EXPECT_CALL()` wherever a function argument is expected. `_` is a +convenient way of saying "any value". + +In the above examples, `100` and `50` are also matchers; implicitly, they are +the same as `Eq(100)` and `Eq(50)`, which specify that the argument must be +equal (using `operator==`) to the matcher argument. There are many +[built-in matchers](reference/matchers.md) for common types (as well as +[custom matchers](gmock_cook_book.md#NewMatchers)); for example: + +```cpp +using ::testing::Ge; +... +// Expects the turtle moves forward by at least 100. +EXPECT_CALL(turtle, Forward(Ge(100))); +``` + +If you don't care about *any* arguments, rather than specify `_` for each of +them you may instead omit the parameter list: + +```cpp +// Expects the turtle to move forward. +EXPECT_CALL(turtle, Forward); +// Expects the turtle to jump somewhere. +EXPECT_CALL(turtle, GoTo); +``` + +This works for all non-overloaded methods; if a method is overloaded, you need +to help gMock resolve which overload is expected by specifying the number of +arguments and possibly also the +[types of the arguments](gmock_cook_book.md#SelectOverload). + +### Cardinalities: How Many Times Will It Be Called? + +The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We +call its argument a **cardinality** as it tells *how many times* the call should +occur. It allows us to repeat an expectation many times without actually writing +it as many times. More importantly, a cardinality can be "fuzzy", just like a +matcher can be. This allows a user to express the intent of a test exactly. + +An interesting special case is when we say `Times(0)`. You may have guessed - it +means that the function shouldn't be called with the given arguments at all, and +gMock will report a googletest failure whenever the function is (wrongfully) +called. + +We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the +list of built-in cardinalities you can use, see +[here](gmock_cheat_sheet.md#CardinalityList). + +The `Times()` clause can be omitted. **If you omit `Times()`, gMock will infer +the cardinality for you.** The rules are easy to remember: + +* If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the + `EXPECT_CALL()`, the inferred cardinality is `Times(1)`. +* If there are *n* `WillOnce()`'s but **no** `WillRepeatedly()`, where *n* >= + 1, the cardinality is `Times(n)`. +* If there are *n* `WillOnce()`'s and **one** `WillRepeatedly()`, where *n* >= + 0, the cardinality is `Times(AtLeast(n))`. + +**Quick quiz:** what do you think will happen if a function is expected to be +called twice but actually called four times? + +### Actions: What Should It Do? + +Remember that a mock object doesn't really have a working implementation? We as +users have to tell it what to do when a method is invoked. This is easy in +gMock. + +First, if the return type of a mock function is a built-in type or a pointer, +the function has a **default action** (a `void` function will just return, a +`bool` function will return `false`, and other functions will return 0). In +addition, in C++ 11 and above, a mock function whose return type is +default-constructible (i.e. has a default constructor) has a default action of +returning a default-constructed value. If you don't say anything, this behavior +will be used. + +Second, if a mock function doesn't have a default action, or the default action +doesn't suit you, you can specify the action to be taken each time the +expectation matches using a series of `WillOnce()` clauses followed by an +optional `WillRepeatedly()`. For example, + +```cpp +using ::testing::Return; +... +EXPECT_CALL(turtle, GetX()) + .WillOnce(Return(100)) + .WillOnce(Return(200)) + .WillOnce(Return(300)); +``` + +says that `turtle.GetX()` will be called *exactly three times* (gMock inferred +this from how many `WillOnce()` clauses we've written, since we didn't +explicitly write `Times()`), and will return 100, 200, and 300 respectively. + +```cpp +using ::testing::Return; +... +EXPECT_CALL(turtle, GetY()) + .WillOnce(Return(100)) + .WillOnce(Return(200)) + .WillRepeatedly(Return(300)); +``` + +says that `turtle.GetY()` will be called *at least twice* (gMock knows this as +we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no +explicit `Times()`), will return 100 and 200 respectively the first two times, +and 300 from the third time on. + +Of course, if you explicitly write a `Times()`, gMock will not try to infer the +cardinality itself. What if the number you specified is larger than there are +`WillOnce()` clauses? Well, after all `WillOnce()`s are used up, gMock will do +the *default* action for the function every time (unless, of course, you have a +`WillRepeatedly()`.). + +What can we do inside `WillOnce()` besides `Return()`? You can return a +reference using `ReturnRef(`*`variable`*`)`, or invoke a pre-defined function, +among [others](gmock_cook_book.md#using-actions). + +**Important note:** The `EXPECT_CALL()` statement evaluates the action clause +only once, even though the action may be performed many times. Therefore you +must be careful about side effects. The following may not do what you want: + +```cpp +using ::testing::Return; +... +int n = 100; +EXPECT_CALL(turtle, GetX()) + .Times(4) + .WillRepeatedly(Return(n++)); +``` + +Instead of returning 100, 101, 102, ..., consecutively, this mock function will +always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` +will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will +return the same pointer every time. If you want the side effect to happen every +time, you need to define a custom action, which we'll teach in the +[cook book](gmock_cook_book.md). + +Time for another quiz! What do you think the following means? + +```cpp +using ::testing::Return; +... +EXPECT_CALL(turtle, GetY()) + .Times(4) + .WillOnce(Return(100)); +``` + +Obviously `turtle.GetY()` is expected to be called four times. But if you think +it will return 100 every time, think twice! Remember that one `WillOnce()` +clause will be consumed each time the function is invoked and the default action +will be taken afterwards. So the right answer is that `turtle.GetY()` will +return 100 the first time, but **return 0 from the second time on**, as +returning 0 is the default action for `int` functions. + +### Using Multiple Expectations {#MultiExpectations} + +So far we've only shown examples where you have a single expectation. More +realistically, you'll specify expectations on multiple mock methods which may be +from multiple mock objects. + +By default, when a mock method is invoked, gMock will search the expectations in +the **reverse order** they are defined, and stop when an active expectation that +matches the arguments is found (you can think of it as "newer rules override +older ones."). If the matching expectation cannot take any more calls, you will +get an upper-bound-violated failure. Here's an example: + +```cpp +using ::testing::_; +... +EXPECT_CALL(turtle, Forward(_)); // #1 +EXPECT_CALL(turtle, Forward(10)) // #2 + .Times(2); +``` + +If `Forward(10)` is called three times in a row, the third time it will be an +error, as the last matching expectation (#2) has been saturated. If, however, +the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, +as now #1 will be the matching expectation. + +{: .callout .note} +**Note:** Why does gMock search for a match in the *reverse* order of the +expectations? The reason is that this allows a user to set up the default +expectations in a mock object's constructor or the test fixture's set-up phase +and then customize the mock by writing more specific expectations in the test +body. So, if you have two expectations on the same method, you want to put the +one with more specific matchers **after** the other, or the more specific rule +would be shadowed by the more general one that comes after it. + +{: .callout .tip} +**Tip:** It is very common to start with a catch-all expectation for a method +and `Times(AnyNumber())` (omitting arguments, or with `_` for all arguments, if +overloaded). This makes any calls to the method expected. This is not necessary +for methods that are not mentioned at all (these are "uninteresting"), but is +useful for methods that have some expectations, but for which other calls are +ok. See +[Understanding Uninteresting vs Unexpected Calls](gmock_cook_book.md#uninteresting-vs-unexpected). + +### Ordered vs Unordered Calls {#OrderedCalls} + +By default, an expectation can match a call even though an earlier expectation +hasn't been satisfied. In other words, the calls don't have to occur in the +order the expectations are specified. + +Sometimes, you may want all the expected calls to occur in a strict order. To +say this in gMock is easy: + +```cpp +using ::testing::InSequence; +... +TEST(FooTest, DrawsLineSegment) { + ... + { + InSequence seq; + + EXPECT_CALL(turtle, PenDown()); + EXPECT_CALL(turtle, Forward(100)); + EXPECT_CALL(turtle, PenUp()); + } + Foo(); +} +``` + +By creating an object of type `InSequence`, all expectations in its scope are +put into a *sequence* and have to occur *sequentially*. Since we are just +relying on the constructor and destructor of this object to do the actual work, +its name is really irrelevant. + +In this example, we test that `Foo()` calls the three expected functions in the +order as written. If a call is made out-of-order, it will be an error. + +(What if you care about the relative order of some of the calls, but not all of +them? Can you specify an arbitrary partial order? The answer is ... yes! The +details can be found [here](gmock_cook_book.md#OrderedCalls).) + +### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations} + +Now let's do a quick quiz to see how well you can use this mock stuff already. +How would you test that the turtle is asked to go to the origin *exactly twice* +(you want to ignore any other instructions it receives)? + +After you've come up with your answer, take a look at ours and compare notes +(solve it yourself first - don't cheat!): + +```cpp +using ::testing::_; +using ::testing::AnyNumber; +... +EXPECT_CALL(turtle, GoTo(_, _)) // #1 + .Times(AnyNumber()); +EXPECT_CALL(turtle, GoTo(0, 0)) // #2 + .Times(2); +``` + +Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, gMock will +see that the arguments match expectation #2 (remember that we always pick the +last matching expectation). Now, since we said that there should be only two +such calls, gMock will report an error immediately. This is basically what we've +told you in the [Using Multiple Expectations](#MultiExpectations) section above. + +This example shows that **expectations in gMock are "sticky" by default**, in +the sense that they remain active even after we have reached their invocation +upper bounds. This is an important rule to remember, as it affects the meaning +of the spec, and is **different** to how it's done in many other mocking +frameworks (Why'd we do that? Because we think our rule makes the common cases +easier to express and understand.). + +Simple? Let's see if you've really understood it: what does the following code +say? + +```cpp +using ::testing::Return; +... +for (int i = n; i > 0; i--) { + EXPECT_CALL(turtle, GetX()) + .WillOnce(Return(10*i)); +} +``` + +If you think it says that `turtle.GetX()` will be called `n` times and will +return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we +said, expectations are sticky. So, the second time `turtle.GetX()` is called, +the last (latest) `EXPECT_CALL()` statement will match, and will immediately +lead to an "upper bound violated" error - this piece of code is not very useful! + +One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is +to explicitly say that the expectations are *not* sticky. In other words, they +should *retire* as soon as they are saturated: + +```cpp +using ::testing::Return; +... +for (int i = n; i > 0; i--) { + EXPECT_CALL(turtle, GetX()) + .WillOnce(Return(10*i)) + .RetiresOnSaturation(); +} +``` + +And, there's a better way to do it: in this case, we expect the calls to occur +in a specific order, and we line up the actions to match the order. Since the +order is important here, we should make it explicit using a sequence: + +```cpp +using ::testing::InSequence; +using ::testing::Return; +... +{ + InSequence s; + + for (int i = 1; i <= n; i++) { + EXPECT_CALL(turtle, GetX()) + .WillOnce(Return(10*i)) + .RetiresOnSaturation(); + } +} +``` + +By the way, the other situation where an expectation may *not* be sticky is when +it's in a sequence - as soon as another expectation that comes after it in the +sequence has been used, it automatically retires (and will never be used to +match any call). + +### Uninteresting Calls + +A mock object may have many methods, and not all of them are that interesting. +For example, in some tests we may not care about how many times `GetX()` and +`GetY()` get called. + +In gMock, if you are not interested in a method, just don't say anything about +it. If a call to this method occurs, you'll see a warning in the test output, +but it won't be a failure. This is called "naggy" behavior; to change, see +[The Nice, the Strict, and the Naggy](gmock_cook_book.md#NiceStrictNaggy). diff --git a/third_party/googletest/docs/index.md b/third_party/googletest/docs/index.md new file mode 100644 index 0000000..b162c74 --- /dev/null +++ b/third_party/googletest/docs/index.md @@ -0,0 +1,22 @@ +# GoogleTest User's Guide + +## Welcome to GoogleTest! + +GoogleTest is Google's C++ testing and mocking framework. This user's guide has +the following contents: + +* [GoogleTest Primer](primer.md) - Teaches you how to write simple tests using + GoogleTest. Read this first if you are new to GoogleTest. +* [GoogleTest Advanced](advanced.md) - Read this when you've finished the + Primer and want to utilize GoogleTest to its full potential. +* [GoogleTest Samples](samples.md) - Describes some GoogleTest samples. +* [GoogleTest FAQ](faq.md) - Have a question? Want some tips? Check here + first. +* [Mocking for Dummies](gmock_for_dummies.md) - Teaches you how to create mock + objects and use them in tests. +* [Mocking Cookbook](gmock_cook_book.md) - Includes tips and approaches to + common mocking use cases. +* [Mocking Cheat Sheet](gmock_cheat_sheet.md) - A handy reference for + matchers, actions, invariants, and more. +* [Mocking FAQ](gmock_faq.md) - Contains answers to some mocking-specific + questions. diff --git a/third_party/googletest/docs/pkgconfig.md b/third_party/googletest/docs/pkgconfig.md new file mode 100644 index 0000000..18a2546 --- /dev/null +++ b/third_party/googletest/docs/pkgconfig.md @@ -0,0 +1,148 @@ +## Using GoogleTest from various build systems + +GoogleTest comes with pkg-config files that can be used to determine all +necessary flags for compiling and linking to GoogleTest (and GoogleMock). +Pkg-config is a standardised plain-text format containing + +* the includedir (-I) path +* necessary macro (-D) definitions +* further required flags (-pthread) +* the library (-L) path +* the library (-l) to link to + +All current build systems support pkg-config in one way or another. For all +examples here we assume you want to compile the sample +`samples/sample3_unittest.cc`. + +### CMake + +Using `pkg-config` in CMake is fairly easy: + +```cmake +cmake_minimum_required(VERSION 3.0) + +cmake_policy(SET CMP0048 NEW) +project(my_gtest_pkgconfig VERSION 0.0.1 LANGUAGES CXX) + +find_package(PkgConfig) +pkg_search_module(GTEST REQUIRED gtest_main) + +add_executable(testapp samples/sample3_unittest.cc) +target_link_libraries(testapp ${GTEST_LDFLAGS}) +target_compile_options(testapp PUBLIC ${GTEST_CFLAGS}) + +include(CTest) +add_test(first_and_only_test testapp) +``` + +It is generally recommended that you use `target_compile_options` + `_CFLAGS` +over `target_include_directories` + `_INCLUDE_DIRS` as the former includes not +just -I flags (GoogleTest might require a macro indicating to internal headers +that all libraries have been compiled with threading enabled. In addition, +GoogleTest might also require `-pthread` in the compiling step, and as such +splitting the pkg-config `Cflags` variable into include dirs and macros for +`target_compile_definitions()` might still miss this). The same recommendation +goes for using `_LDFLAGS` over the more commonplace `_LIBRARIES`, which happens +to discard `-L` flags and `-pthread`. + +### Help! pkg-config can't find GoogleTest! + +Let's say you have a `CMakeLists.txt` along the lines of the one in this +tutorial and you try to run `cmake`. It is very possible that you get a failure +along the lines of: + +``` +-- Checking for one of the modules 'gtest_main' +CMake Error at /usr/share/cmake/Modules/FindPkgConfig.cmake:640 (message): + None of the required 'gtest_main' found +``` + +These failures are common if you installed GoogleTest yourself and have not +sourced it from a distro or other package manager. If so, you need to tell +pkg-config where it can find the `.pc` files containing the information. Say you +installed GoogleTest to `/usr/local`, then it might be that the `.pc` files are +installed under `/usr/local/lib64/pkgconfig`. If you set + +``` +export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig +``` + +pkg-config will also try to look in `PKG_CONFIG_PATH` to find `gtest_main.pc`. + +### Using pkg-config in a cross-compilation setting + +Pkg-config can be used in a cross-compilation setting too. To do this, let's +assume the final prefix of the cross-compiled installation will be `/usr`, and +your sysroot is `/home/MYUSER/sysroot`. Configure and install GTest using + +``` +mkdir build && cmake -DCMAKE_INSTALL_PREFIX=/usr .. +``` + +Install into the sysroot using `DESTDIR`: + +``` +make -j install DESTDIR=/home/MYUSER/sysroot +``` + +Before we continue, it is recommended to **always** define the following two +variables for pkg-config in a cross-compilation setting: + +``` +export PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=yes +export PKG_CONFIG_ALLOW_SYSTEM_LIBS=yes +``` + +otherwise `pkg-config` will filter `-I` and `-L` flags against standard prefixes +such as `/usr` (see https://bugs.freedesktop.org/show_bug.cgi?id=28264#c3 for +reasons why this stripping needs to occur usually). + +If you look at the generated pkg-config file, it will look something like + +``` +libdir=/usr/lib64 +includedir=/usr/include + +Name: gtest +Description: GoogleTest (without main() function) +Version: 1.11.0 +URL: https://github.com/google/googletest +Libs: -L${libdir} -lgtest -lpthread +Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread +``` + +Notice that the sysroot is not included in `libdir` and `includedir`! If you try +to run `pkg-config` with the correct +`PKG_CONFIG_LIBDIR=/home/MYUSER/sysroot/usr/lib64/pkgconfig` against this `.pc` +file, you will get + +``` +$ pkg-config --cflags gtest +-DGTEST_HAS_PTHREAD=1 -lpthread -I/usr/include +$ pkg-config --libs gtest +-L/usr/lib64 -lgtest -lpthread +``` + +which is obviously wrong and points to the `CBUILD` and not `CHOST` root. In +order to use this in a cross-compilation setting, we need to tell pkg-config to +inject the actual sysroot into `-I` and `-L` variables. Let us now tell +pkg-config about the actual sysroot + +``` +export PKG_CONFIG_DIR= +export PKG_CONFIG_SYSROOT_DIR=/home/MYUSER/sysroot +export PKG_CONFIG_LIBDIR=${PKG_CONFIG_SYSROOT_DIR}/usr/lib64/pkgconfig +``` + +and running `pkg-config` again we get + +``` +$ pkg-config --cflags gtest +-DGTEST_HAS_PTHREAD=1 -lpthread -I/home/MYUSER/sysroot/usr/include +$ pkg-config --libs gtest +-L/home/MYUSER/sysroot/usr/lib64 -lgtest -lpthread +``` + +which contains the correct sysroot now. For a more comprehensive guide to also +including `${CHOST}` in build system calls, see the excellent tutorial by Diego +Elio Pettenò: diff --git a/third_party/googletest/docs/platforms.md b/third_party/googletest/docs/platforms.md new file mode 100644 index 0000000..eba6ef8 --- /dev/null +++ b/third_party/googletest/docs/platforms.md @@ -0,0 +1,35 @@ +# Supported Platforms + +GoogleTest requires a codebase and compiler compliant with the C++11 standard or +newer. + +The GoogleTest code is officially supported on the following platforms. +Operating systems or tools not listed below are community-supported. For +community-supported platforms, patches that do not complicate the code may be +considered. + +If you notice any problems on your platform, please file an issue on the +[GoogleTest GitHub Issue Tracker](https://github.com/google/googletest/issues). +Pull requests containing fixes are welcome! + +### Operating systems + +* Linux +* macOS +* Windows + +### Compilers + +* gcc 5.0+ +* clang 5.0+ +* MSVC 2015+ + +**macOS users:** Xcode 9.3+ provides clang 5.0+. + +### Build systems + +* [Bazel](https://bazel.build/) +* [CMake](https://cmake.org/) + +Bazel is the build system used by the team internally and in tests. CMake is +supported on a best-effort basis and by the community. diff --git a/third_party/googletest/docs/primer.md b/third_party/googletest/docs/primer.md new file mode 100644 index 0000000..aecc368 --- /dev/null +++ b/third_party/googletest/docs/primer.md @@ -0,0 +1,482 @@ +# Googletest Primer + +## Introduction: Why googletest? + +*googletest* helps you write better C++ tests. + +googletest is a testing framework developed by the Testing Technology team with +Google's specific requirements and constraints in mind. Whether you work on +Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it +supports *any* kind of tests, not just unit tests. + +So what makes a good test, and how does googletest fit in? We believe: + +1. Tests should be *independent* and *repeatable*. It's a pain to debug a test + that succeeds or fails as a result of other tests. googletest isolates the + tests by running each of them on a different object. When a test fails, + googletest allows you to run it in isolation for quick debugging. +2. Tests should be well *organized* and reflect the structure of the tested + code. googletest groups related tests into test suites that can share data + and subroutines. This common pattern is easy to recognize and makes tests + easy to maintain. Such consistency is especially helpful when people switch + projects and start to work on a new code base. +3. Tests should be *portable* and *reusable*. Google has a lot of code that is + platform-neutral; its tests should also be platform-neutral. googletest + works on different OSes, with different compilers, with or without + exceptions, so googletest tests can work with a variety of configurations. +4. When tests fail, they should provide as much *information* about the problem + as possible. googletest doesn't stop at the first test failure. Instead, it + only stops the current test and continues with the next. You can also set up + tests that report non-fatal failures after which the current test continues. + Thus, you can detect and fix multiple bugs in a single run-edit-compile + cycle. +5. The testing framework should liberate test writers from housekeeping chores + and let them focus on the test *content*. googletest automatically keeps + track of all tests defined, and doesn't require the user to enumerate them + in order to run them. +6. Tests should be *fast*. With googletest, you can reuse shared resources + across tests and pay for the set-up/tear-down only once, without making + tests depend on each other. + +Since googletest is based on the popular xUnit architecture, you'll feel right +at home if you've used JUnit or PyUnit before. If not, it will take you about 10 +minutes to learn the basics and get started. So let's go! + +## Beware of the nomenclature + +{: .callout .note} +_Note:_ There might be some confusion arising from different definitions of the +terms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these. + +Historically, googletest started to use the term _Test Case_ for grouping +related tests, whereas current publications, including International Software +Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and +various textbooks on software quality, use the term +_[Test Suite][istqb test suite]_ for this. + +The related term _Test_, as it is used in googletest, corresponds to the term +_[Test Case][istqb test case]_ of ISTQB and others. + +The term _Test_ is commonly of broad enough sense, including ISTQB's definition +of _Test Case_, so it's not much of a problem here. But the term _Test Case_ as +was used in Google Test is of contradictory sense and thus confusing. + +googletest recently started replacing the term _Test Case_ with _Test Suite_. +The preferred API is *TestSuite*. The older TestCase API is being slowly +deprecated and refactored away. + +So please be aware of the different definitions of the terms: + + +Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term +:----------------------------------------------------------------------------------- | :---------------------- | :---------------------------------- +Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case] + + +[istqb test case]: http://glossary.istqb.org/en/search/test%20case +[istqb test suite]: http://glossary.istqb.org/en/search/test%20suite + +## Basic Concepts + +When using googletest, you start by writing *assertions*, which are statements +that check whether a condition is true. An assertion's result can be *success*, +*nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the +current function; otherwise the program continues normally. + +*Tests* use assertions to verify the tested code's behavior. If a test crashes +or has a failed assertion, then it *fails*; otherwise it *succeeds*. + +A *test suite* contains one or many tests. You should group your tests into test +suites that reflect the structure of the tested code. When multiple tests in a +test suite need to share common objects and subroutines, you can put them into a +*test fixture* class. + +A *test program* can contain multiple test suites. + +We'll now explain how to write a test program, starting at the individual +assertion level and building up to tests and test suites. + +## Assertions + +googletest assertions are macros that resemble function calls. You test a class +or function by making assertions about its behavior. When an assertion fails, +googletest prints the assertion's source file and line number location, along +with a failure message. You may also supply a custom failure message which will +be appended to googletest's message. + +The assertions come in pairs that test the same thing but have different effects +on the current function. `ASSERT_*` versions generate fatal failures when they +fail, and **abort the current function**. `EXPECT_*` versions generate nonfatal +failures, which don't abort the current function. Usually `EXPECT_*` are +preferred, as they allow more than one failure to be reported in a test. +However, you should use `ASSERT_*` if it doesn't make sense to continue when the +assertion in question fails. + +Since a failed `ASSERT_*` returns from the current function immediately, +possibly skipping clean-up code that comes after it, it may cause a space leak. +Depending on the nature of the leak, it may or may not be worth fixing - so keep +this in mind if you get a heap checker error in addition to assertion errors. + +To provide a custom failure message, simply stream it into the macro using the +`<<` operator or a sequence of such operators. See the following example, using +the [`ASSERT_EQ` and `EXPECT_EQ`](reference/assertions.md#EXPECT_EQ) macros to +verify value equality: + +```c++ +ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length"; + +for (int i = 0; i < x.size(); ++i) { + EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i; +} +``` + +Anything that can be streamed to an `ostream` can be streamed to an assertion +macro--in particular, C strings and `string` objects. If a wide string +(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is +streamed to an assertion, it will be translated to UTF-8 when printed. + +GoogleTest provides a collection of assertions for verifying the behavior of +your code in various ways. You can check Boolean conditions, compare values +based on relational operators, verify string values, floating-point values, and +much more. There are even assertions that enable you to verify more complex +states by providing custom predicates. For the complete list of assertions +provided by GoogleTest, see the [Assertions Reference](reference/assertions.md). + +## Simple Tests + +To create a test: + +1. Use the `TEST()` macro to define and name a test function. These are + ordinary C++ functions that don't return a value. +2. In this function, along with any valid C++ statements you want to include, + use the various googletest assertions to check values. +3. The test's result is determined by the assertions; if any assertion in the + test fails (either fatally or non-fatally), or if the test crashes, the + entire test fails. Otherwise, it succeeds. + +```c++ +TEST(TestSuiteName, TestName) { + ... test body ... +} +``` + +`TEST()` arguments go from general to specific. The *first* argument is the name +of the test suite, and the *second* argument is the test's name within the test +suite. Both names must be valid C++ identifiers, and they should not contain any +underscores (`_`). A test's *full name* consists of its containing test suite +and its individual name. Tests from different test suites can have the same +individual name. + +For example, let's take a simple integer function: + +```c++ +int Factorial(int n); // Returns the factorial of n +``` + +A test suite for this function might look like: + +```c++ +// Tests factorial of 0. +TEST(FactorialTest, HandlesZeroInput) { + EXPECT_EQ(Factorial(0), 1); +} + +// Tests factorial of positive numbers. +TEST(FactorialTest, HandlesPositiveInput) { + EXPECT_EQ(Factorial(1), 1); + EXPECT_EQ(Factorial(2), 2); + EXPECT_EQ(Factorial(3), 6); + EXPECT_EQ(Factorial(8), 40320); +} +``` + +googletest groups the test results by test suites, so logically related tests +should be in the same test suite; in other words, the first argument to their +`TEST()` should be the same. In the above example, we have two tests, +`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test +suite `FactorialTest`. + +When naming your test suites and tests, you should follow the same convention as +for +[naming functions and classes](https://google.github.io/styleguide/cppguide.html#Function_Names). + +**Availability**: Linux, Windows, Mac. + +## Test Fixtures: Using the Same Data Configuration for Multiple Tests {#same-data-multiple-tests} + +If you find yourself writing two or more tests that operate on similar data, you +can use a *test fixture*. This allows you to reuse the same configuration of +objects for several different tests. + +To create a fixture: + +1. Derive a class from `::testing::Test` . Start its body with `protected:`, as + we'll want to access fixture members from sub-classes. +2. Inside the class, declare any objects you plan to use. +3. If necessary, write a default constructor or `SetUp()` function to prepare + the objects for each test. A common mistake is to spell `SetUp()` as + **`Setup()`** with a small `u` - Use `override` in C++11 to make sure you + spelled it correctly. +4. If necessary, write a destructor or `TearDown()` function to release any + resources you allocated in `SetUp()` . To learn when you should use the + constructor/destructor and when you should use `SetUp()/TearDown()`, read + the [FAQ](faq.md#CtorVsSetUp). +5. If needed, define subroutines for your tests to share. + +When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to +access objects and subroutines in the test fixture: + +```c++ +TEST_F(TestFixtureName, TestName) { + ... test body ... +} +``` + +Like `TEST()`, the first argument is the test suite name, but for `TEST_F()` +this must be the name of the test fixture class. You've probably guessed: `_F` +is for fixture. + +Unfortunately, the C++ macro system does not allow us to create a single macro +that can handle both types of tests. Using the wrong macro causes a compiler +error. + +Also, you must first define a test fixture class before using it in a +`TEST_F()`, or you'll get the compiler error "`virtual outside class +declaration`". + +For each test defined with `TEST_F()`, googletest will create a *fresh* test +fixture at runtime, immediately initialize it via `SetUp()`, run the test, clean +up by calling `TearDown()`, and then delete the test fixture. Note that +different tests in the same test suite have different test fixture objects, and +googletest always deletes a test fixture before it creates the next one. +googletest does **not** reuse the same test fixture for multiple tests. Any +changes one test makes to the fixture do not affect other tests. + +As an example, let's write tests for a FIFO queue class named `Queue`, which has +the following interface: + +```c++ +template // E is the element type. +class Queue { + public: + Queue(); + void Enqueue(const E& element); + E* Dequeue(); // Returns NULL if the queue is empty. + size_t size() const; + ... +}; +``` + +First, define a fixture class. By convention, you should give it the name +`FooTest` where `Foo` is the class being tested. + +```c++ +class QueueTest : public ::testing::Test { + protected: + void SetUp() override { + q1_.Enqueue(1); + q2_.Enqueue(2); + q2_.Enqueue(3); + } + + // void TearDown() override {} + + Queue q0_; + Queue q1_; + Queue q2_; +}; +``` + +In this case, `TearDown()` is not needed since we don't have to clean up after +each test, other than what's already done by the destructor. + +Now we'll write tests using `TEST_F()` and this fixture. + +```c++ +TEST_F(QueueTest, IsEmptyInitially) { + EXPECT_EQ(q0_.size(), 0); +} + +TEST_F(QueueTest, DequeueWorks) { + int* n = q0_.Dequeue(); + EXPECT_EQ(n, nullptr); + + n = q1_.Dequeue(); + ASSERT_NE(n, nullptr); + EXPECT_EQ(*n, 1); + EXPECT_EQ(q1_.size(), 0); + delete n; + + n = q2_.Dequeue(); + ASSERT_NE(n, nullptr); + EXPECT_EQ(*n, 2); + EXPECT_EQ(q2_.size(), 1); + delete n; +} +``` + +The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is +to use `EXPECT_*` when you want the test to continue to reveal more errors after +the assertion failure, and use `ASSERT_*` when continuing after failure doesn't +make sense. For example, the second assertion in the `Dequeue` test is +`ASSERT_NE(n, nullptr)`, as we need to dereference the pointer `n` later, which +would lead to a segfault when `n` is `NULL`. + +When these tests run, the following happens: + +1. googletest constructs a `QueueTest` object (let's call it `t1`). +2. `t1.SetUp()` initializes `t1`. +3. The first test (`IsEmptyInitially`) runs on `t1`. +4. `t1.TearDown()` cleans up after the test finishes. +5. `t1` is destructed. +6. The above steps are repeated on another `QueueTest` object, this time + running the `DequeueWorks` test. + +**Availability**: Linux, Windows, Mac. + +## Invoking the Tests + +`TEST()` and `TEST_F()` implicitly register their tests with googletest. So, +unlike with many other C++ testing frameworks, you don't have to re-list all +your defined tests in order to run them. + +After defining your tests, you can run them with `RUN_ALL_TESTS()`, which +returns `0` if all the tests are successful, or `1` otherwise. Note that +`RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from different +test suites, or even different source files. + +When invoked, the `RUN_ALL_TESTS()` macro: + +* Saves the state of all googletest flags. + +* Creates a test fixture object for the first test. + +* Initializes it via `SetUp()`. + +* Runs the test on the fixture object. + +* Cleans up the fixture via `TearDown()`. + +* Deletes the fixture. + +* Restores the state of all googletest flags. + +* Repeats the above steps for the next test, until all tests have run. + +If a fatal failure happens the subsequent steps will be skipped. + +{: .callout .important} +> IMPORTANT: You must **not** ignore the return value of `RUN_ALL_TESTS()`, or +> you will get a compiler error. The rationale for this design is that the +> automated testing service determines whether a test has passed based on its +> exit code, not on its stdout/stderr output; thus your `main()` function must +> return the value of `RUN_ALL_TESTS()`. +> +> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than +> once conflicts with some advanced googletest features (e.g., thread-safe +> [death tests](advanced.md#death-tests)) and thus is not supported. + +**Availability**: Linux, Windows, Mac. + +## Writing the main() Function + +Most users should _not_ need to write their own `main` function and instead link +with `gtest_main` (as opposed to with `gtest`), which defines a suitable entry +point. See the end of this section for details. The remainder of this section +should only apply when you need to do something custom before the tests run that +cannot be expressed within the framework of fixtures and test suites. + +If you write your own `main` function, it should return the value of +`RUN_ALL_TESTS()`. + +You can start from this boilerplate: + +```c++ +#include "this/package/foo.h" + +#include "gtest/gtest.h" + +namespace my { +namespace project { +namespace { + +// The fixture for testing class Foo. +class FooTest : public ::testing::Test { + protected: + // You can remove any or all of the following functions if their bodies would + // be empty. + + FooTest() { + // You can do set-up work for each test here. + } + + ~FooTest() override { + // You can do clean-up work that doesn't throw exceptions here. + } + + // If the constructor and destructor are not enough for setting up + // and cleaning up each test, you can define the following methods: + + void SetUp() override { + // Code here will be called immediately after the constructor (right + // before each test). + } + + void TearDown() override { + // Code here will be called immediately after each test (right + // before the destructor). + } + + // Class members declared here can be used by all tests in the test suite + // for Foo. +}; + +// Tests that the Foo::Bar() method does Abc. +TEST_F(FooTest, MethodBarDoesAbc) { + const std::string input_filepath = "this/package/testdata/myinputfile.dat"; + const std::string output_filepath = "this/package/testdata/myoutputfile.dat"; + Foo f; + EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0); +} + +// Tests that Foo does Xyz. +TEST_F(FooTest, DoesXyz) { + // Exercises the Xyz feature of Foo. +} + +} // namespace +} // namespace project +} // namespace my + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} +``` + +The `::testing::InitGoogleTest()` function parses the command line for +googletest flags, and removes all recognized flags. This allows the user to +control a test program's behavior via various flags, which we'll cover in the +[AdvancedGuide](advanced.md). You **must** call this function before calling +`RUN_ALL_TESTS()`, or the flags won't be properly initialized. + +On Windows, `InitGoogleTest()` also works with wide strings, so it can be used +in programs compiled in `UNICODE` mode as well. + +But maybe you think that writing all those `main` functions is too much work? We +agree with you completely, and that's why Google Test provides a basic +implementation of main(). If it fits your needs, then just link your test with +the `gtest_main` library and you are good to go. + +{: .callout .note} +NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`. + +## Known Limitations + +* Google Test is designed to be thread-safe. The implementation is thread-safe + on systems where the `pthreads` library is available. It is currently + _unsafe_ to use Google Test assertions from two threads concurrently on + other systems (e.g. Windows). In most tests this is not an issue as usually + the assertions are done in the main thread. If you want to help, you can + volunteer to implement the necessary synchronization primitives in + `gtest-port.h` for your platform. diff --git a/third_party/googletest/docs/quickstart-bazel.md b/third_party/googletest/docs/quickstart-bazel.md new file mode 100644 index 0000000..5d6e9c6 --- /dev/null +++ b/third_party/googletest/docs/quickstart-bazel.md @@ -0,0 +1,147 @@ +# Quickstart: Building with Bazel + +This tutorial aims to get you up and running with GoogleTest using the Bazel +build system. If you're using GoogleTest for the first time or need a refresher, +we recommend this tutorial as a starting point. + +## Prerequisites + +To complete this tutorial, you'll need: + +* A compatible operating system (e.g. Linux, macOS, Windows). +* A compatible C++ compiler that supports at least C++11. +* [Bazel](https://bazel.build/), the preferred build system used by the + GoogleTest team. + +See [Supported Platforms](platforms.md) for more information about platforms +compatible with GoogleTest. + +If you don't already have Bazel installed, see the +[Bazel installation guide](https://docs.bazel.build/versions/main/install.html). + +{: .callout .note} +Note: The terminal commands in this tutorial show a Unix shell prompt, but the +commands work on the Windows command line as well. + +## Set up a Bazel workspace + +A +[Bazel workspace](https://docs.bazel.build/versions/main/build-ref.html#workspace) +is a directory on your filesystem that you use to manage source files for the +software you want to build. Each workspace directory has a text file named +`WORKSPACE` which may be empty, or may contain references to external +dependencies required to build the outputs. + +First, create a directory for your workspace: + +``` +$ mkdir my_workspace && cd my_workspace +``` + +Next, you’ll create the `WORKSPACE` file to specify dependencies. A common and +recommended way to depend on GoogleTest is to use a +[Bazel external dependency](https://docs.bazel.build/versions/main/external.html) +via the +[`http_archive` rule](https://docs.bazel.build/versions/main/repo/http.html#http_archive). +To do this, in the root directory of your workspace (`my_workspace/`), create a +file named `WORKSPACE` with the following contents: + +``` +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + +http_archive( + name = "com_google_googletest", + urls = ["https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip"], + strip_prefix = "googletest-609281088cfefc76f9d0ce82e1ff6c30cc3591e5", +) +``` + +The above configuration declares a dependency on GoogleTest which is downloaded +as a ZIP archive from GitHub. In the above example, +`609281088cfefc76f9d0ce82e1ff6c30cc3591e5` is the Git commit hash of the +GoogleTest version to use; we recommend updating the hash often to point to the +latest version. + +Now you're ready to build C++ code that uses GoogleTest. + +## Create and run a binary + +With your Bazel workspace set up, you can now use GoogleTest code within your +own project. + +As an example, create a file named `hello_test.cc` in your `my_workspace` +directory with the following contents: + +```cpp +#include + +// Demonstrate some basic assertions. +TEST(HelloTest, BasicAssertions) { + // Expect two strings not to be equal. + EXPECT_STRNE("hello", "world"); + // Expect equality. + EXPECT_EQ(7 * 6, 42); +} +``` + +GoogleTest provides [assertions](primer.md#assertions) that you use to test the +behavior of your code. The above sample includes the main GoogleTest header file +and demonstrates some basic assertions. + +To build the code, create a file named `BUILD` in the same directory with the +following contents: + +``` +cc_test( + name = "hello_test", + size = "small", + srcs = ["hello_test.cc"], + deps = ["@com_google_googletest//:gtest_main"], +) +``` + +This `cc_test` rule declares the C++ test binary you want to build, and links to +GoogleTest (`//:gtest_main`) using the prefix you specified in the `WORKSPACE` +file (`@com_google_googletest`). For more information about Bazel `BUILD` files, +see the +[Bazel C++ Tutorial](https://docs.bazel.build/versions/main/tutorial/cpp.html). + +Now you can build and run your test: + +
+my_workspace$ bazel test --test_output=all //:hello_test
+INFO: Analyzed target //:hello_test (26 packages loaded, 362 targets configured).
+INFO: Found 1 test target...
+INFO: From Testing //:hello_test:
+==================== Test output for //:hello_test:
+Running main() from gmock_main.cc
+[==========] Running 1 test from 1 test suite.
+[----------] Global test environment set-up.
+[----------] 1 test from HelloTest
+[ RUN      ] HelloTest.BasicAssertions
+[       OK ] HelloTest.BasicAssertions (0 ms)
+[----------] 1 test from HelloTest (0 ms total)
+
+[----------] Global test environment tear-down
+[==========] 1 test from 1 test suite ran. (0 ms total)
+[  PASSED  ] 1 test.
+================================================================================
+Target //:hello_test up-to-date:
+  bazel-bin/hello_test
+INFO: Elapsed time: 4.190s, Critical Path: 3.05s
+INFO: 27 processes: 8 internal, 19 linux-sandbox.
+INFO: Build completed successfully, 27 total actions
+//:hello_test                                                     PASSED in 0.1s
+
+INFO: Build completed successfully, 27 total actions
+
+ +Congratulations! You've successfully built and run a test binary using +GoogleTest. + +## Next steps + +* [Check out the Primer](primer.md) to start learning how to write simple + tests. +* [See the code samples](samples.md) for more examples showing how to use a + variety of GoogleTest features. diff --git a/third_party/googletest/docs/quickstart-cmake.md b/third_party/googletest/docs/quickstart-cmake.md new file mode 100644 index 0000000..420f1d3 --- /dev/null +++ b/third_party/googletest/docs/quickstart-cmake.md @@ -0,0 +1,156 @@ +# Quickstart: Building with CMake + +This tutorial aims to get you up and running with GoogleTest using CMake. If +you're using GoogleTest for the first time or need a refresher, we recommend +this tutorial as a starting point. If your project uses Bazel, see the +[Quickstart for Bazel](quickstart-bazel.md) instead. + +## Prerequisites + +To complete this tutorial, you'll need: + +* A compatible operating system (e.g. Linux, macOS, Windows). +* A compatible C++ compiler that supports at least C++11. +* [CMake](https://cmake.org/) and a compatible build tool for building the + project. + * Compatible build tools include + [Make](https://www.gnu.org/software/make/), + [Ninja](https://ninja-build.org/), and others - see + [CMake Generators](https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html) + for more information. + +See [Supported Platforms](platforms.md) for more information about platforms +compatible with GoogleTest. + +If you don't already have CMake installed, see the +[CMake installation guide](https://cmake.org/install). + +{: .callout .note} +Note: The terminal commands in this tutorial show a Unix shell prompt, but the +commands work on the Windows command line as well. + +## Set up a project + +CMake uses a file named `CMakeLists.txt` to configure the build system for a +project. You'll use this file to set up your project and declare a dependency on +GoogleTest. + +First, create a directory for your project: + +``` +$ mkdir my_project && cd my_project +``` + +Next, you'll create the `CMakeLists.txt` file and declare a dependency on +GoogleTest. There are many ways to express dependencies in the CMake ecosystem; +in this quickstart, you'll use the +[`FetchContent` CMake module](https://cmake.org/cmake/help/latest/module/FetchContent.html). +To do this, in your project directory (`my_project`), create a file named +`CMakeLists.txt` with the following contents: + +```cmake +cmake_minimum_required(VERSION 3.14) +project(my_project) + +# GoogleTest requires at least C++11 +set(CMAKE_CXX_STANDARD 11) + +include(FetchContent) +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip +) +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) +FetchContent_MakeAvailable(googletest) +``` + +The above configuration declares a dependency on GoogleTest which is downloaded +from GitHub. In the above example, `609281088cfefc76f9d0ce82e1ff6c30cc3591e5` is +the Git commit hash of the GoogleTest version to use; we recommend updating the +hash often to point to the latest version. + +For more information about how to create `CMakeLists.txt` files, see the +[CMake Tutorial](https://cmake.org/cmake/help/latest/guide/tutorial/index.html). + +## Create and run a binary + +With GoogleTest declared as a dependency, you can use GoogleTest code within +your own project. + +As an example, create a file named `hello_test.cc` in your `my_project` +directory with the following contents: + +```cpp +#include + +// Demonstrate some basic assertions. +TEST(HelloTest, BasicAssertions) { + // Expect two strings not to be equal. + EXPECT_STRNE("hello", "world"); + // Expect equality. + EXPECT_EQ(7 * 6, 42); +} +``` + +GoogleTest provides [assertions](primer.md#assertions) that you use to test the +behavior of your code. The above sample includes the main GoogleTest header file +and demonstrates some basic assertions. + +To build the code, add the following to the end of your `CMakeLists.txt` file: + +```cmake +enable_testing() + +add_executable( + hello_test + hello_test.cc +) +target_link_libraries( + hello_test + gtest_main +) + +include(GoogleTest) +gtest_discover_tests(hello_test) +``` + +The above configuration enables testing in CMake, declares the C++ test binary +you want to build (`hello_test`), and links it to GoogleTest (`gtest_main`). The +last two lines enable CMake's test runner to discover the tests included in the +binary, using the +[`GoogleTest` CMake module](https://cmake.org/cmake/help/git-stage/module/GoogleTest.html). + +Now you can build and run your test: + +
+my_project$ cmake -S . -B build
+-- The C compiler identification is GNU 10.2.1
+-- The CXX compiler identification is GNU 10.2.1
+...
+-- Build files have been written to: .../my_project/build
+
+my_project$ cmake --build build
+Scanning dependencies of target gtest
+...
+[100%] Built target gmock_main
+
+my_project$ cd build && ctest
+Test project .../my_project/build
+    Start 1: HelloTest.BasicAssertions
+1/1 Test #1: HelloTest.BasicAssertions ........   Passed    0.00 sec
+
+100% tests passed, 0 tests failed out of 1
+
+Total Test time (real) =   0.01 sec
+
+ +Congratulations! You've successfully built and run a test binary using +GoogleTest. + +## Next steps + +* [Check out the Primer](primer.md) to start learning how to write simple + tests. +* [See the code samples](samples.md) for more examples showing how to use a + variety of GoogleTest features. diff --git a/third_party/googletest/docs/reference/actions.md b/third_party/googletest/docs/reference/actions.md new file mode 100644 index 0000000..ab81a12 --- /dev/null +++ b/third_party/googletest/docs/reference/actions.md @@ -0,0 +1,115 @@ +# Actions Reference + +[**Actions**](../gmock_for_dummies.md#actions-what-should-it-do) specify what a +mock function should do when invoked. This page lists the built-in actions +provided by GoogleTest. All actions are defined in the `::testing` namespace. + +## Returning a Value + +| Action | Description | +| :-------------------------------- | :-------------------------------------------- | +| `Return()` | Return from a `void` mock function. | +| `Return(value)` | Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type at the time the expectation is set, not when the action is executed. | +| `ReturnArg()` | Return the `N`-th (0-based) argument. | +| `ReturnNew(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. | +| `ReturnNull()` | Return a null pointer. | +| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. | +| `ReturnRef(variable)` | Return a reference to `variable`. | +| `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. | +| `ReturnRoundRobin({a1, ..., ak})` | Each call will return the next `ai` in the list, starting at the beginning when the end of the list is reached. | + +## Side Effects + +| Action | Description | +| :--------------------------------- | :-------------------------------------- | +| `Assign(&variable, value)` | Assign `value` to variable. | +| `DeleteArg()` | Delete the `N`-th (0-based) argument, which must be a pointer. | +| `SaveArg(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | +| `SaveArgPointee(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. | +| `SetArgReferee(value)` | Assign `value` to the variable referenced by the `N`-th (0-based) argument. | +| `SetArgPointee(value)` | Assign `value` to the variable pointed by the `N`-th (0-based) argument. | +| `SetArgumentPointee(value)` | Same as `SetArgPointee(value)`. Deprecated. Will be removed in v1.7.0. | +| `SetArrayArgument(first, last)` | Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range. | +| `SetErrnoAndReturn(error, value)` | Set `errno` to `error` and return `value`. | +| `Throw(exception)` | Throws the given exception, which can be any copyable value. Available since v1.1.0. | + +## Using a Function, Functor, or Lambda as an Action + +In the following, by "callable" we mean a free function, `std::function`, +functor, or lambda. + +| Action | Description | +| :---------------------------------- | :------------------------------------- | +| `f` | Invoke `f` with the arguments passed to the mock function, where `f` is a callable. | +| `Invoke(f)` | Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor. | +| `Invoke(object_pointer, &class::method)` | Invoke the method on the object with the arguments passed to the mock function. | +| `InvokeWithoutArgs(f)` | Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | +| `InvokeWithoutArgs(object_pointer, &class::method)` | Invoke the method on the object, which takes no arguments. | +| `InvokeArgument(arg1, arg2, ..., argk)` | Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments. | + +The return value of the invoked function is used as the return value of the +action. + +When defining a callable to be used with `Invoke*()`, you can declare any unused +parameters as `Unused`: + +```cpp +using ::testing::Invoke; +double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } +... +EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); +``` + +`Invoke(callback)` and `InvokeWithoutArgs(callback)` take ownership of +`callback`, which must be permanent. The type of `callback` must be a base +callback type instead of a derived one, e.g. + +```cpp + BlockingClosure* done = new BlockingClosure; + ... Invoke(done) ...; // This won't compile! + + Closure* done2 = new BlockingClosure; + ... Invoke(done2) ...; // This works. +``` + +In `InvokeArgument(...)`, if an argument needs to be passed by reference, +wrap it inside `std::ref()`. For example, + +```cpp +using ::testing::InvokeArgument; +... +InvokeArgument<2>(5, string("Hi"), std::ref(foo)) +``` + +calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by +value, and `foo` by reference. + +## Default Action + +| Action | Description | +| :------------ | :----------------------------------------------------- | +| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). | + +{: .callout .note} +**Note:** due to technical reasons, `DoDefault()` cannot be used inside a +composite action - trying to do so will result in a run-time error. + +## Composite Actions + +| Action | Description | +| :----------------------------- | :------------------------------------------ | +| `DoAll(a1, a2, ..., an)` | Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void and will receive a readonly view of the arguments. | +| `IgnoreResult(a)` | Perform action `a` and ignore its result. `a` must not return void. | +| `WithArg(a)` | Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | +| `WithArgs(a)` | Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | +| `WithoutArgs(a)` | Perform action `a` without any arguments. | + +## Defining Actions + +| Macro | Description | +| :--------------------------------- | :-------------------------------------- | +| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | +| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | +| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | + +The `ACTION*` macros cannot be used inside a function or class. diff --git a/third_party/googletest/docs/reference/assertions.md b/third_party/googletest/docs/reference/assertions.md new file mode 100644 index 0000000..7bf03a3 --- /dev/null +++ b/third_party/googletest/docs/reference/assertions.md @@ -0,0 +1,633 @@ +# Assertions Reference + +This page lists the assertion macros provided by GoogleTest for verifying code +behavior. To use them, include the header `gtest/gtest.h`. + +The majority of the macros listed below come as a pair with an `EXPECT_` variant +and an `ASSERT_` variant. Upon failure, `EXPECT_` macros generate nonfatal +failures and allow the current function to continue running, while `ASSERT_` +macros generate fatal failures and abort the current function. + +All assertion macros support streaming a custom failure message into them with +the `<<` operator, for example: + +```cpp +EXPECT_TRUE(my_condition) << "My condition is not true"; +``` + +Anything that can be streamed to an `ostream` can be streamed to an assertion +macro—in particular, C strings and string objects. If a wide string (`wchar_t*`, +`TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is streamed to an +assertion, it will be translated to UTF-8 when printed. + +## Explicit Success and Failure {#success-failure} + +The assertions in this section generate a success or failure directly instead of +testing a value or expression. These are useful when control flow, rather than a +Boolean expression, determines the test's success or failure, as shown by the +following example: + +```c++ +switch(expression) { + case 1: + ... some checks ... + case 2: + ... some other checks ... + default: + FAIL() << "We shouldn't get here."; +} +``` + +### SUCCEED {#SUCCEED} + +`SUCCEED()` + +Generates a success. This *does not* make the overall test succeed. A test is +considered successful only if none of its assertions fail during its execution. + +The `SUCCEED` assertion is purely documentary and currently doesn't generate any +user-visible output. However, we may add `SUCCEED` messages to GoogleTest output +in the future. + +### FAIL {#FAIL} + +`FAIL()` + +Generates a fatal failure, which returns from the current function. + +Can only be used in functions that return `void`. See +[Assertion Placement](../advanced.md#assertion-placement) for more information. + +### ADD_FAILURE {#ADD_FAILURE} + +`ADD_FAILURE()` + +Generates a nonfatal failure, which allows the current function to continue +running. + +### ADD_FAILURE_AT {#ADD_FAILURE_AT} + +`ADD_FAILURE_AT(`*`file_path`*`,`*`line_number`*`)` + +Generates a nonfatal failure at the file and line number specified. + +## Generalized Assertion {#generalized} + +The following assertion allows [matchers](matchers.md) to be used to verify +values. + +### EXPECT_THAT {#EXPECT_THAT} + +`EXPECT_THAT(`*`value`*`,`*`matcher`*`)` \ +`ASSERT_THAT(`*`value`*`,`*`matcher`*`)` + +Verifies that *`value`* matches the [matcher](matchers.md) *`matcher`*. + +For example, the following code verifies that the string `value1` starts with +`"Hello"`, `value2` matches a regular expression, and `value3` is between 5 and +10: + +```cpp +#include "gmock/gmock.h" + +using ::testing::AllOf; +using ::testing::Gt; +using ::testing::Lt; +using ::testing::MatchesRegex; +using ::testing::StartsWith; + +... +EXPECT_THAT(value1, StartsWith("Hello")); +EXPECT_THAT(value2, MatchesRegex("Line \\d+")); +ASSERT_THAT(value3, AllOf(Gt(5), Lt(10))); +``` + +Matchers enable assertions of this form to read like English and generate +informative failure messages. For example, if the above assertion on `value1` +fails, the resulting message will be similar to the following: + +``` +Value of: value1 + Actual: "Hi, world!" +Expected: starts with "Hello" +``` + +GoogleTest provides a built-in library of matchers—see the +[Matchers Reference](matchers.md). It is also possible to write your own +matchers—see [Writing New Matchers Quickly](../gmock_cook_book.md#NewMatchers). +The use of matchers makes `EXPECT_THAT` a powerful, extensible assertion. + +*The idea for this assertion was borrowed from Joe Walnes' Hamcrest project, +which adds `assertThat()` to JUnit.* + +## Boolean Conditions {#boolean} + +The following assertions test Boolean conditions. + +### EXPECT_TRUE {#EXPECT_TRUE} + +`EXPECT_TRUE(`*`condition`*`)` \ +`ASSERT_TRUE(`*`condition`*`)` + +Verifies that *`condition`* is true. + +### EXPECT_FALSE {#EXPECT_FALSE} + +`EXPECT_FALSE(`*`condition`*`)` \ +`ASSERT_FALSE(`*`condition`*`)` + +Verifies that *`condition`* is false. + +## Binary Comparison {#binary-comparison} + +The following assertions compare two values. The value arguments must be +comparable by the assertion's comparison operator, otherwise a compiler error +will result. + +If an argument supports the `<<` operator, it will be called to print the +argument when the assertion fails. Otherwise, GoogleTest will attempt to print +them in the best way it can—see +[Teaching GoogleTest How to Print Your Values](../advanced.md#teaching-googletest-how-to-print-your-values). + +Arguments are always evaluated exactly once, so it's OK for the arguments to +have side effects. However, the argument evaluation order is undefined and +programs should not depend on any particular argument evaluation order. + +These assertions work with both narrow and wide string objects (`string` and +`wstring`). + +See also the [Floating-Point Comparison](#floating-point) assertions to compare +floating-point numbers and avoid problems caused by rounding. + +### EXPECT_EQ {#EXPECT_EQ} + +`EXPECT_EQ(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_EQ(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`==`*`val2`*. + +Does pointer equality on pointers. If used on two C strings, it tests if they +are in the same memory location, not if they have the same value. Use +[`EXPECT_STREQ`](#EXPECT_STREQ) to compare C strings (e.g. `const char*`) by +value. + +When comparing a pointer to `NULL`, use `EXPECT_EQ(`*`ptr`*`, nullptr)` instead +of `EXPECT_EQ(`*`ptr`*`, NULL)`. + +### EXPECT_NE {#EXPECT_NE} + +`EXPECT_NE(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_NE(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`!=`*`val2`*. + +Does pointer equality on pointers. If used on two C strings, it tests if they +are in different memory locations, not if they have different values. Use +[`EXPECT_STRNE`](#EXPECT_STRNE) to compare C strings (e.g. `const char*`) by +value. + +When comparing a pointer to `NULL`, use `EXPECT_NE(`*`ptr`*`, nullptr)` instead +of `EXPECT_NE(`*`ptr`*`, NULL)`. + +### EXPECT_LT {#EXPECT_LT} + +`EXPECT_LT(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_LT(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`<`*`val2`*. + +### EXPECT_LE {#EXPECT_LE} + +`EXPECT_LE(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_LE(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`<=`*`val2`*. + +### EXPECT_GT {#EXPECT_GT} + +`EXPECT_GT(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_GT(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`>`*`val2`*. + +### EXPECT_GE {#EXPECT_GE} + +`EXPECT_GE(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_GE(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`>=`*`val2`*. + +## String Comparison {#c-strings} + +The following assertions compare two **C strings**. To compare two `string` +objects, use [`EXPECT_EQ`](#EXPECT_EQ) or [`EXPECT_NE`](#EXPECT_NE) instead. + +These assertions also accept wide C strings (`wchar_t*`). If a comparison of two +wide strings fails, their values will be printed as UTF-8 narrow strings. + +To compare a C string with `NULL`, use `EXPECT_EQ(`*`c_string`*`, nullptr)` or +`EXPECT_NE(`*`c_string`*`, nullptr)`. + +### EXPECT_STREQ {#EXPECT_STREQ} + +`EXPECT_STREQ(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STREQ(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have the same contents. + +### EXPECT_STRNE {#EXPECT_STRNE} + +`EXPECT_STRNE(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STRNE(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have different contents. + +### EXPECT_STRCASEEQ {#EXPECT_STRCASEEQ} + +`EXPECT_STRCASEEQ(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STRCASEEQ(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have the same contents, +ignoring case. + +### EXPECT_STRCASENE {#EXPECT_STRCASENE} + +`EXPECT_STRCASENE(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STRCASENE(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have different contents, +ignoring case. + +## Floating-Point Comparison {#floating-point} + +The following assertions compare two floating-point values. + +Due to rounding errors, it is very unlikely that two floating-point values will +match exactly, so `EXPECT_EQ` is not suitable. In general, for floating-point +comparison to make sense, the user needs to carefully choose the error bound. + +GoogleTest also provides assertions that use a default error bound based on +Units in the Last Place (ULPs). To learn more about ULPs, see the article +[Comparing Floating Point Numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). + +### EXPECT_FLOAT_EQ {#EXPECT_FLOAT_EQ} + +`EXPECT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)` + +Verifies that the two `float` values *`val1`* and *`val2`* are approximately +equal, to within 4 ULPs from each other. + +### EXPECT_DOUBLE_EQ {#EXPECT_DOUBLE_EQ} + +`EXPECT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)` + +Verifies that the two `double` values *`val1`* and *`val2`* are approximately +equal, to within 4 ULPs from each other. + +### EXPECT_NEAR {#EXPECT_NEAR} + +`EXPECT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)` \ +`ASSERT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)` + +Verifies that the difference between *`val1`* and *`val2`* does not exceed the +absolute error bound *`abs_error`*. + +## Exception Assertions {#exceptions} + +The following assertions verify that a piece of code throws, or does not throw, +an exception. Usage requires exceptions to be enabled in the build environment. + +Note that the piece of code under test can be a compound statement, for example: + +```cpp +EXPECT_NO_THROW({ + int n = 5; + DoSomething(&n); +}); +``` + +### EXPECT_THROW {#EXPECT_THROW} + +`EXPECT_THROW(`*`statement`*`,`*`exception_type`*`)` \ +`ASSERT_THROW(`*`statement`*`,`*`exception_type`*`)` + +Verifies that *`statement`* throws an exception of type *`exception_type`*. + +### EXPECT_ANY_THROW {#EXPECT_ANY_THROW} + +`EXPECT_ANY_THROW(`*`statement`*`)` \ +`ASSERT_ANY_THROW(`*`statement`*`)` + +Verifies that *`statement`* throws an exception of any type. + +### EXPECT_NO_THROW {#EXPECT_NO_THROW} + +`EXPECT_NO_THROW(`*`statement`*`)` \ +`ASSERT_NO_THROW(`*`statement`*`)` + +Verifies that *`statement`* does not throw any exception. + +## Predicate Assertions {#predicates} + +The following assertions enable more complex predicates to be verified while +printing a more clear failure message than if `EXPECT_TRUE` were used alone. + +### EXPECT_PRED* {#EXPECT_PRED} + +`EXPECT_PRED1(`*`pred`*`,`*`val1`*`)` \ +`EXPECT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \ +`EXPECT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`EXPECT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \ +`EXPECT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +`ASSERT_PRED1(`*`pred`*`,`*`val1`*`)` \ +`ASSERT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \ +`ASSERT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`ASSERT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \ +`ASSERT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +Verifies that the predicate *`pred`* returns `true` when passed the given values +as arguments. + +The parameter *`pred`* is a function or functor that accepts as many arguments +as the corresponding macro accepts values. If *`pred`* returns `true` for the +given arguments, the assertion succeeds, otherwise the assertion fails. + +When the assertion fails, it prints the value of each argument. Arguments are +always evaluated exactly once. + +As an example, see the following code: + +```cpp +// Returns true if m and n have no common divisors except 1. +bool MutuallyPrime(int m, int n) { ... } +... +const int a = 3; +const int b = 4; +const int c = 10; +... +EXPECT_PRED2(MutuallyPrime, a, b); // Succeeds +EXPECT_PRED2(MutuallyPrime, b, c); // Fails +``` + +In the above example, the first assertion succeeds, and the second fails with +the following message: + +``` +MutuallyPrime(b, c) is false, where +b is 4 +c is 10 +``` + +Note that if the given predicate is an overloaded function or a function +template, the assertion macro might not be able to determine which version to +use, and it might be necessary to explicitly specify the type of the function. +For example, for a Boolean function `IsPositive()` overloaded to take either a +single `int` or `double` argument, it would be necessary to write one of the +following: + +```cpp +EXPECT_PRED1(static_cast(IsPositive), 5); +EXPECT_PRED1(static_cast(IsPositive), 3.14); +``` + +Writing simply `EXPECT_PRED1(IsPositive, 5);` would result in a compiler error. +Similarly, to use a template function, specify the template arguments: + +```cpp +template +bool IsNegative(T x) { + return x < 0; +} +... +EXPECT_PRED1(IsNegative, -5); // Must specify type for IsNegative +``` + +If a template has multiple parameters, wrap the predicate in parentheses so the +macro arguments are parsed correctly: + +```cpp +ASSERT_PRED2((MyPredicate), 5, 0); +``` + +### EXPECT_PRED_FORMAT* {#EXPECT_PRED_FORMAT} + +`EXPECT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \ +`EXPECT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \ +`EXPECT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`EXPECT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` +\ +`EXPECT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +`ASSERT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \ +`ASSERT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \ +`ASSERT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`ASSERT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` +\ +`ASSERT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +Verifies that the predicate *`pred_formatter`* succeeds when passed the given +values as arguments. + +The parameter *`pred_formatter`* is a *predicate-formatter*, which is a function +or functor with the signature: + +```cpp +testing::AssertionResult PredicateFormatter(const char* expr1, + const char* expr2, + ... + const char* exprn, + T1 val1, + T2 val2, + ... + Tn valn); +``` + +where *`val1`*, *`val2`*, ..., *`valn`* are the values of the predicate +arguments, and *`expr1`*, *`expr2`*, ..., *`exprn`* are the corresponding +expressions as they appear in the source code. The types `T1`, `T2`, ..., `Tn` +can be either value types or reference types; if an argument has type `T`, it +can be declared as either `T` or `const T&`, whichever is appropriate. For more +about the return type `testing::AssertionResult`, see +[Using a Function That Returns an AssertionResult](../advanced.md#using-a-function-that-returns-an-assertionresult). + +As an example, see the following code: + +```cpp +// Returns the smallest prime common divisor of m and n, +// or 1 when m and n are mutually prime. +int SmallestPrimeCommonDivisor(int m, int n) { ... } + +// Returns true if m and n have no common divisors except 1. +bool MutuallyPrime(int m, int n) { ... } + +// A predicate-formatter for asserting that two integers are mutually prime. +testing::AssertionResult AssertMutuallyPrime(const char* m_expr, + const char* n_expr, + int m, + int n) { + if (MutuallyPrime(m, n)) return testing::AssertionSuccess(); + + return testing::AssertionFailure() << m_expr << " and " << n_expr + << " (" << m << " and " << n << ") are not mutually prime, " + << "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n); +} + +... +const int a = 3; +const int b = 4; +const int c = 10; +... +EXPECT_PRED_FORMAT2(AssertMutuallyPrime, a, b); // Succeeds +EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); // Fails +``` + +In the above example, the final assertion fails and the predicate-formatter +produces the following failure message: + +``` +b and c (4 and 10) are not mutually prime, as they have a common divisor 2 +``` + +## Windows HRESULT Assertions {#HRESULT} + +The following assertions test for `HRESULT` success or failure. For example: + +```cpp +CComPtr shell; +ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application")); +CComVariant empty; +ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty)); +``` + +The generated output contains the human-readable error message associated with +the returned `HRESULT` code. + +### EXPECT_HRESULT_SUCCEEDED {#EXPECT_HRESULT_SUCCEEDED} + +`EXPECT_HRESULT_SUCCEEDED(`*`expression`*`)` \ +`ASSERT_HRESULT_SUCCEEDED(`*`expression`*`)` + +Verifies that *`expression`* is a success `HRESULT`. + +### EXPECT_HRESULT_FAILED {#EXPECT_HRESULT_FAILED} + +`EXPECT_HRESULT_FAILED(`*`expression`*`)` \ +`EXPECT_HRESULT_FAILED(`*`expression`*`)` + +Verifies that *`expression`* is a failure `HRESULT`. + +## Death Assertions {#death} + +The following assertions verify that a piece of code causes the process to +terminate. For context, see [Death Tests](../advanced.md#death-tests). + +These assertions spawn a new process and execute the code under test in that +process. How that happens depends on the platform and the variable +`::testing::GTEST_FLAG(death_test_style)`, which is initialized from the +command-line flag `--gtest_death_test_style`. + +* On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the + child, after which: + * If the variable's value is `"fast"`, the death test statement is + immediately executed. + * If the variable's value is `"threadsafe"`, the child process re-executes + the unit test binary just as it was originally invoked, but with some + extra flags to cause just the single death test under consideration to + be run. +* On Windows, the child is spawned using the `CreateProcess()` API, and + re-executes the binary to cause just the single death test under + consideration to be run - much like the `"threadsafe"` mode on POSIX. + +Other values for the variable are illegal and will cause the death test to fail. +Currently, the flag's default value is +**`"fast"`**. + +If the death test statement runs to completion without dying, the child process +will nonetheless terminate, and the assertion fails. + +Note that the piece of code under test can be a compound statement, for example: + +```cpp +EXPECT_DEATH({ + int n = 5; + DoSomething(&n); +}, "Error on line .* of DoSomething()"); +``` + +### EXPECT_DEATH {#EXPECT_DEATH} + +`EXPECT_DEATH(`*`statement`*`,`*`matcher`*`)` \ +`ASSERT_DEATH(`*`statement`*`,`*`matcher`*`)` + +Verifies that *`statement`* causes the process to terminate with a nonzero exit +status and produces `stderr` output that matches *`matcher`*. + +The parameter *`matcher`* is either a [matcher](matchers.md) for a `const +std::string&`, or a regular expression (see +[Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare +string *`s`* (with no matcher) is treated as +[`ContainsRegex(s)`](matchers.md#string-matchers), **not** +[`Eq(s)`](matchers.md#generic-comparison). + +For example, the following code verifies that calling `DoSomething(42)` causes +the process to die with an error message that contains the text `My error`: + +```cpp +EXPECT_DEATH(DoSomething(42), "My error"); +``` + +### EXPECT_DEATH_IF_SUPPORTED {#EXPECT_DEATH_IF_SUPPORTED} + +`EXPECT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)` \ +`ASSERT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)` + +If death tests are supported, behaves the same as +[`EXPECT_DEATH`](#EXPECT_DEATH). Otherwise, verifies nothing. + +### EXPECT_DEBUG_DEATH {#EXPECT_DEBUG_DEATH} + +`EXPECT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)` \ +`ASSERT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)` + +In debug mode, behaves the same as [`EXPECT_DEATH`](#EXPECT_DEATH). When not in +debug mode (i.e. `NDEBUG` is defined), just executes *`statement`*. + +### EXPECT_EXIT {#EXPECT_EXIT} + +`EXPECT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)` \ +`ASSERT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)` + +Verifies that *`statement`* causes the process to terminate with an exit status +that satisfies *`predicate`*, and produces `stderr` output that matches +*`matcher`*. + +The parameter *`predicate`* is a function or functor that accepts an `int` exit +status and returns a `bool`. GoogleTest provides two predicates to handle common +cases: + +```cpp +// Returns true if the program exited normally with the given exit status code. +::testing::ExitedWithCode(exit_code); + +// Returns true if the program was killed by the given signal. +// Not available on Windows. +::testing::KilledBySignal(signal_number); +``` + +The parameter *`matcher`* is either a [matcher](matchers.md) for a `const +std::string&`, or a regular expression (see +[Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare +string *`s`* (with no matcher) is treated as +[`ContainsRegex(s)`](matchers.md#string-matchers), **not** +[`Eq(s)`](matchers.md#generic-comparison). + +For example, the following code verifies that calling `NormalExit()` causes the +process to print a message containing the text `Success` to `stderr` and exit +with exit status code 0: + +```cpp +EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success"); +``` diff --git a/third_party/googletest/docs/reference/matchers.md b/third_party/googletest/docs/reference/matchers.md new file mode 100644 index 0000000..9fb1592 --- /dev/null +++ b/third_party/googletest/docs/reference/matchers.md @@ -0,0 +1,290 @@ +# Matchers Reference + +A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or +`EXPECT_CALL()`, or use it to validate a value directly using two macros: + +| Macro | Description | +| :----------------------------------- | :------------------------------------ | +| `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. | +| `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. | + +{: .callout .warning} +**WARNING:** Equality matching via `EXPECT_THAT(actual_value, expected_value)` +is supported, however note that implicit conversions can cause surprising +results. For example, `EXPECT_THAT(some_bool, "some string")` will compile and +may pass unintentionally. + +**BEST PRACTICE:** Prefer to make the comparison explicit via +`EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value, +expected_value)`. + +Built-in matchers (where `argument` is the function argument, e.g. +`actual_value` in the example above, or when used in the context of +`EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) are +divided into several categories. All matchers are defined in the `::testing` +namespace unless otherwise noted. + +## Wildcard + +Matcher | Description +:-------------------------- | :----------------------------------------------- +`_` | `argument` can be any value of the correct type. +`A()` or `An()` | `argument` can be any value of type `type`. + +## Generic Comparison + +| Matcher | Description | +| :--------------------- | :-------------------------------------------------- | +| `Eq(value)` or `value` | `argument == value` | +| `Ge(value)` | `argument >= value` | +| `Gt(value)` | `argument > value` | +| `Le(value)` | `argument <= value` | +| `Lt(value)` | `argument < value` | +| `Ne(value)` | `argument != value` | +| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. | +| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. | +| `IsNull()` | `argument` is a `NULL` pointer (raw or smart). | +| `NotNull()` | `argument` is a non-null pointer (raw or smart). | +| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)| +| `VariantWith(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. | +| `Ref(variable)` | `argument` is a reference to `variable`. | +| `TypedEq(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. | + +Except `Ref()`, these matchers make a *copy* of `value` in case it's modified or +destructed later. If the compiler complains that `value` doesn't have a public +copy constructor, try wrap it in `std::ref()`, e.g. +`Eq(std::ref(non_copyable_value))`. If you do that, make sure +`non_copyable_value` is not changed afterwards, or the meaning of your matcher +will be changed. + +`IsTrue` and `IsFalse` are useful when you need to use a matcher, or for types +that can be explicitly converted to Boolean, but are not implicitly converted to +Boolean. In other cases, you can use the basic +[`EXPECT_TRUE` and `EXPECT_FALSE`](assertions.md#boolean) assertions. + +## Floating-Point Matchers {#FpMatchers} + +| Matcher | Description | +| :------------------------------- | :--------------------------------- | +| `DoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal. | +| `FloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | +| `NanSensitiveDoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | +| `NanSensitiveFloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | +| `IsNan()` | `argument` is any floating-point type with a NaN value. | + +The above matchers use ULP-based comparison (the same as used in googletest). +They automatically pick a reasonable error bound based on the absolute value of +the expected value. `DoubleEq()` and `FloatEq()` conform to the IEEE standard, +which requires comparing two NaNs for equality to return false. The +`NanSensitive*` version instead treats two NaNs as equal, which is often what a +user wants. + +| Matcher | Description | +| :------------------------------------------------ | :----------------------- | +| `DoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | +| `FloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | +| `NanSensitiveDoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. | +| `NanSensitiveFloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. | + +## String Matchers + +The `argument` can be either a C string or a C++ string object: + +| Matcher | Description | +| :---------------------- | :------------------------------------------------- | +| `ContainsRegex(string)` | `argument` matches the given regular expression. | +| `EndsWith(suffix)` | `argument` ends with string `suffix`. | +| `HasSubstr(string)` | `argument` contains `string` as a sub-string. | +| `IsEmpty()` | `argument` is an empty string. | +| `MatchesRegex(string)` | `argument` matches the given regular expression with the match starting at the first character and ending at the last character. | +| `StartsWith(prefix)` | `argument` starts with string `prefix`. | +| `StrCaseEq(string)` | `argument` is equal to `string`, ignoring case. | +| `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. | +| `StrEq(string)` | `argument` is equal to `string`. | +| `StrNe(string)` | `argument` is not equal to `string`. | +| `WhenBase64Unescaped(m)` | `argument` is a base-64 escaped string whose unescaped string matches `m`. | + +`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They +use the regular expression syntax defined +[here](../advanced.md#regular-expression-syntax). All of these matchers, except +`ContainsRegex()` and `MatchesRegex()` work for wide strings as well. + +## Container Matchers + +Most STL-style containers support `==`, so you can use `Eq(expected_container)` +or simply `expected_container` to match a container exactly. If you want to +write the elements in-line, match them more flexibly, or get more informative +messages, you can use: + +| Matcher | Description | +| :---------------------------------------- | :------------------------------- | +| `BeginEndDistanceIs(m)` | `argument` is a container whose `begin()` and `end()` iterators are separated by a number of increments matching `m`. E.g. `BeginEndDistanceIs(2)` or `BeginEndDistanceIs(Lt(2))`. For containers that define a `size()` method, `SizeIs(m)` may be more efficient. | +| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | +| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | +| `Contains(e).Times(n)` | `argument` contains elements that match `e`, which can be either a value or a matcher, and the number of matches is `n`, which can be either a value or a matcher. Unlike the plain `Contains` and `Each` this allows to check for arbitrary occurrences including testing for absence with `Contains(e).Times(0)`. | +| `Each(e)` | `argument` is a container where *every* element matches `e`, which can be either a value or a matcher. | +| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the *i*-th element matches `ei`, which can be a value or a matcher. | +| `ElementsAreArray({e0, e1, ..., en})`, `ElementsAreArray(a_container)`, `ElementsAreArray(begin, end)`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `IsEmpty()` | `argument` is an empty container (`container.empty()`). | +| `IsSubsetOf({e0, e1, ..., en})`, `IsSubsetOf(a_container)`, `IsSubsetOf(begin, end)`, `IsSubsetOf(array)`, or `IsSubsetOf(array, count)` | `argument` matches `UnorderedElementsAre(x0, x1, ..., xk)` for some subset `{x0, x1, ..., xk}` of the expected matchers. | +| `IsSupersetOf({e0, e1, ..., en})`, `IsSupersetOf(a_container)`, `IsSupersetOf(begin, end)`, `IsSupersetOf(array)`, or `IsSupersetOf(array, count)` | Some subset of `argument` matches `UnorderedElementsAre(`expected matchers`)`. | +| `Pointwise(m, container)`, `Pointwise(m, {e0, e1, ..., en})` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. | +| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. | +| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under *some* permutation of the elements, each element matches an `ei` (for a different `i`), which can be a value or a matcher. | +| `UnorderedElementsAreArray({e0, e1, ..., en})`, `UnorderedElementsAreArray(a_container)`, `UnorderedElementsAreArray(begin, end)`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `UnorderedPointwise(m, container)`, `UnorderedPointwise(m, {e0, e1, ..., en})` | Like `Pointwise(m, container)`, but ignores the order of elements. | +| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements 1, 2, and 3, ignoring order. | +| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater(), ElementsAre(3, 2, 1))`. | + +**Notes:** + +* These matchers can also match: + 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), + and + 2. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, + int len)` -- see [Multi-argument Matchers](#MultiArgMatchers)). +* The array being matched may be multi-dimensional (i.e. its elements can be + arrays). +* `m` in `Pointwise(m, ...)` and `UnorderedPointwise(m, ...)` should be a + matcher for `::std::tuple` where `T` and `U` are the element type of + the actual container and the expected container, respectively. For example, + to compare two `Foo` containers where `Foo` doesn't support `operator==`, + one might write: + + ```cpp + MATCHER(FooEq, "") { + return std::get<0>(arg).Equals(std::get<1>(arg)); + } + ... + EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos)); + ``` + +## Member Matchers + +| Matcher | Description | +| :------------------------------ | :----------------------------------------- | +| `Field(&class::field, m)` | `argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. | +| `Field(field_name, &class::field, m)` | The same as the two-parameter version, but provides a better error message. | +| `Key(e)` | `argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`. | +| `Pair(m1, m2)` | `argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | +| `FieldsAre(m...)` | `argument` is a compatible object where each field matches piecewise with the matchers `m...`. A compatible object is any that supports the `std::tuple_size`+`get(obj)` protocol. In C++17 and up this also supports types compatible with structured bindings, like aggregates. | +| `Property(&class::property, m)` | `argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. The method `property()` must take no argument and be declared as `const`. | +| `Property(property_name, &class::property, m)` | The same as the two-parameter version, but provides a better error message. + +**Notes:** + +* You can use `FieldsAre()` to match any type that supports structured + bindings, such as `std::tuple`, `std::pair`, `std::array`, and aggregate + types. For example: + + ```cpp + std::tuple my_tuple{7, "hello world"}; + EXPECT_THAT(my_tuple, FieldsAre(Ge(0), HasSubstr("hello"))); + + struct MyStruct { + int value = 42; + std::string greeting = "aloha"; + }; + MyStruct s; + EXPECT_THAT(s, FieldsAre(42, "aloha")); + ``` + +* Don't use `Property()` against member functions that you do not own, because + taking addresses of functions is fragile and generally not part of the + contract of the function. + +## Matching the Result of a Function, Functor, or Callback + +| Matcher | Description | +| :--------------- | :------------------------------------------------ | +| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. | +| `ResultOf(result_description, f, m)` | The same as the two-parameter version, but provides a better error message. + +## Pointer Matchers + +| Matcher | Description | +| :------------------------ | :---------------------------------------------- | +| `Address(m)` | the result of `std::addressof(argument)` matches `m`. | +| `Pointee(m)` | `argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`. | +| `Pointer(m)` | `argument` (either a smart pointer or a raw pointer) contains a pointer that matches `m`. `m` will match against the raw pointer regardless of the type of `argument`. | +| `WhenDynamicCastTo(m)` | when `argument` is passed through `dynamic_cast()`, it matches matcher `m`. | + +## Multi-argument Matchers {#MultiArgMatchers} + +Technically, all matchers match a *single* value. A "multi-argument" matcher is +just one that matches a *tuple*. The following matchers can be used to match a +tuple `(x, y)`: + +Matcher | Description +:------ | :---------- +`Eq()` | `x == y` +`Ge()` | `x >= y` +`Gt()` | `x > y` +`Le()` | `x <= y` +`Lt()` | `x < y` +`Ne()` | `x != y` + +You can use the following selectors to pick a subset of the arguments (or +reorder them) to participate in the matching: + +| Matcher | Description | +| :------------------------- | :---------------------------------------------- | +| `AllArgs(m)` | Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`. | +| `Args(m)` | The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`. | + +## Composite Matchers + +You can make a matcher from one or more other matchers: + +| Matcher | Description | +| :------------------------------- | :-------------------------------------- | +| `AllOf(m1, m2, ..., mn)` | `argument` matches all of the matchers `m1` to `mn`. | +| `AllOfArray({m0, m1, ..., mn})`, `AllOfArray(a_container)`, `AllOfArray(begin, end)`, `AllOfArray(array)`, or `AllOfArray(array, count)` | The same as `AllOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1` to `mn`. | +| `AnyOfArray({m0, m1, ..., mn})`, `AnyOfArray(a_container)`, `AnyOfArray(begin, end)`, `AnyOfArray(array)`, or `AnyOfArray(array, count)` | The same as `AnyOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `Not(m)` | `argument` doesn't match matcher `m`. | +| `Conditional(cond, m1, m2)` | Matches matcher `m1` if `cond` evaluates to true, else matches `m2`.| + +## Adapters for Matchers + +| Matcher | Description | +| :---------------------- | :------------------------------------ | +| `MatcherCast(m)` | casts matcher `m` to type `Matcher`. | +| `SafeMatcherCast(m)` | [safely casts](../gmock_cook_book.md#SafeMatcherCast) matcher `m` to type `Matcher`. | +| `Truly(predicate)` | `predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor. | + +`AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`, +which must be a permanent callback. + +## Using Matchers as Predicates {#MatchersAsPredicatesCheat} + +| Matcher | Description | +| :---------------------------- | :------------------------------------------ | +| `Matches(m)(value)` | evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor. | +| `ExplainMatchResult(m, value, result_listener)` | evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. | +| `Value(value, m)` | evaluates to `true` if `value` matches `m`. | + +## Defining Matchers + +| Macro | Description | +| :----------------------------------- | :------------------------------------ | +| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | +| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a matcher `IsDivisibleBy(n)` to match a number divisible by `n`. | +| `MATCHER_P2(IsBetween, a, b, absl::StrCat(negation ? "isn't" : "is", " between ", PrintToString(a), " and ", PrintToString(b))) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | + +**Notes:** + +1. The `MATCHER*` macros cannot be used inside a function or class. +2. The matcher body must be *purely functional* (i.e. it cannot have any side + effect, and the result must not depend on anything other than the value + being matched and the matcher parameters). +3. You can use `PrintToString(x)` to convert a value `x` of any type to a + string. +4. You can use `ExplainMatchResult()` in a custom matcher to wrap another + matcher, for example: + + ```cpp + MATCHER_P(NestedPropertyMatches, matcher, "") { + return ExplainMatchResult(matcher, arg.nested().property(), result_listener); + } + ``` diff --git a/third_party/googletest/docs/reference/mocking.md b/third_party/googletest/docs/reference/mocking.md new file mode 100644 index 0000000..e414ffb --- /dev/null +++ b/third_party/googletest/docs/reference/mocking.md @@ -0,0 +1,589 @@ +# Mocking Reference + +This page lists the facilities provided by GoogleTest for creating and working +with mock objects. To use them, include the header +`gmock/gmock.h`. + +## Macros {#macros} + +GoogleTest defines the following macros for working with mocks. + +### MOCK_METHOD {#MOCK_METHOD} + +`MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`));` \ +`MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`), +(`*`specs...`*`));` + +Defines a mock method *`method_name`* with arguments `(`*`args...`*`)` and +return type *`return_type`* within a mock class. + +The parameters of `MOCK_METHOD` mirror the method declaration. The optional +fourth parameter *`specs...`* is a comma-separated list of qualifiers. The +following qualifiers are accepted: + +| Qualifier | Meaning | +| -------------------------- | -------------------------------------------- | +| `const` | Makes the mocked method a `const` method. Required if overriding a `const` method. | +| `override` | Marks the method with `override`. Recommended if overriding a `virtual` method. | +| `noexcept` | Marks the method with `noexcept`. Required if overriding a `noexcept` method. | +| `Calltype(`*`calltype`*`)` | Sets the call type for the method, for example `Calltype(STDMETHODCALLTYPE)`. Useful on Windows. | +| `ref(`*`qualifier`*`)` | Marks the method with the given reference qualifier, for example `ref(&)` or `ref(&&)`. Required if overriding a method that has a reference qualifier. | + +Note that commas in arguments prevent `MOCK_METHOD` from parsing the arguments +correctly if they are not appropriately surrounded by parentheses. See the +following example: + +```cpp +class MyMock { + public: + // The following 2 lines will not compile due to commas in the arguments: + MOCK_METHOD(std::pair, GetPair, ()); // Error! + MOCK_METHOD(bool, CheckMap, (std::map, bool)); // Error! + + // One solution - wrap arguments that contain commas in parentheses: + MOCK_METHOD((std::pair), GetPair, ()); + MOCK_METHOD(bool, CheckMap, ((std::map), bool)); + + // Another solution - use type aliases: + using BoolAndInt = std::pair; + MOCK_METHOD(BoolAndInt, GetPair, ()); + using MapIntDouble = std::map; + MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool)); +}; +``` + +`MOCK_METHOD` must be used in the `public:` section of a mock class definition, +regardless of whether the method being mocked is `public`, `protected`, or +`private` in the base class. + +### EXPECT_CALL {#EXPECT_CALL} + +`EXPECT_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))` + +Creates an [expectation](../gmock_for_dummies.md#setting-expectations) that the +method *`method_name`* of the object *`mock_object`* is called with arguments +that match the given matchers *`matchers...`*. `EXPECT_CALL` must precede any +code that exercises the mock object. + +The parameter *`matchers...`* is a comma-separated list of +[matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that +correspond to each argument of the method *`method_name`*. The expectation will +apply only to calls of *`method_name`* whose arguments match all of the +matchers. If `(`*`matchers...`*`)` is omitted, the expectation behaves as if +each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard). +See the [Matchers Reference](matchers.md) for a list of all built-in matchers. + +The following chainable clauses can be used to modify the expectation, and they +must be used in the following order: + +```cpp +EXPECT_CALL(mock_object, method_name(matchers...)) + .With(multi_argument_matcher) // Can be used at most once + .Times(cardinality) // Can be used at most once + .InSequence(sequences...) // Can be used any number of times + .After(expectations...) // Can be used any number of times + .WillOnce(action) // Can be used any number of times + .WillRepeatedly(action) // Can be used at most once + .RetiresOnSaturation(); // Can be used at most once +``` + +See details for each modifier clause below. + +#### With {#EXPECT_CALL.With} + +`.With(`*`multi_argument_matcher`*`)` + +Restricts the expectation to apply only to mock function calls whose arguments +as a whole match the multi-argument matcher *`multi_argument_matcher`*. + +GoogleTest passes all of the arguments as one tuple into the matcher. The +parameter *`multi_argument_matcher`* must thus be a matcher of type +`Matcher>`, where `A1, ..., An` are the types of the +function arguments. + +For example, the following code sets the expectation that +`my_mock.SetPosition()` is called with any two arguments, the first argument +being less than the second: + +```cpp +using ::testing::_; +using ::testing::Lt; +... +EXPECT_CALL(my_mock, SetPosition(_, _)) + .With(Lt()); +``` + +GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()` +matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers). + +The `With` clause can be used at most once on an expectation and must be the +first clause. + +#### Times {#EXPECT_CALL.Times} + +`.Times(`*`cardinality`*`)` + +Specifies how many times the mock function call is expected. + +The parameter *`cardinality`* represents the number of expected calls and can be +one of the following, all defined in the `::testing` namespace: + +| Cardinality | Meaning | +| ------------------- | --------------------------------------------------- | +| `AnyNumber()` | The function can be called any number of times. | +| `AtLeast(n)` | The function call is expected at least *n* times. | +| `AtMost(n)` | The function call is expected at most *n* times. | +| `Between(m, n)` | The function call is expected between *m* and *n* times, inclusive. | +| `Exactly(n)` or `n` | The function call is expected exactly *n* times. If *n* is 0, the call should never happen. | + +If the `Times` clause is omitted, GoogleTest infers the cardinality as follows: + +* If neither [`WillOnce`](#EXPECT_CALL.WillOnce) nor + [`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) are specified, the inferred + cardinality is `Times(1)`. +* If there are *n* `WillOnce` clauses and no `WillRepeatedly` clause, where + *n* >= 1, the inferred cardinality is `Times(n)`. +* If there are *n* `WillOnce` clauses and one `WillRepeatedly` clause, where + *n* >= 0, the inferred cardinality is `Times(AtLeast(n))`. + +The `Times` clause can be used at most once on an expectation. + +#### InSequence {#EXPECT_CALL.InSequence} + +`.InSequence(`*`sequences...`*`)` + +Specifies that the mock function call is expected in a certain sequence. + +The parameter *`sequences...`* is any number of [`Sequence`](#Sequence) objects. +Expected calls assigned to the same sequence are expected to occur in the order +the expectations are declared. + +For example, the following code sets the expectation that the `Reset()` method +of `my_mock` is called before both `GetSize()` and `Describe()`, and `GetSize()` +and `Describe()` can occur in any order relative to each other: + +```cpp +using ::testing::Sequence; +Sequence s1, s2; +... +EXPECT_CALL(my_mock, Reset()) + .InSequence(s1, s2); +EXPECT_CALL(my_mock, GetSize()) + .InSequence(s1); +EXPECT_CALL(my_mock, Describe()) + .InSequence(s2); +``` + +The `InSequence` clause can be used any number of times on an expectation. + +See also the [`InSequence` class](#InSequence). + +#### After {#EXPECT_CALL.After} + +`.After(`*`expectations...`*`)` + +Specifies that the mock function call is expected to occur after one or more +other calls. + +The parameter *`expectations...`* can be up to five +[`Expectation`](#Expectation) or [`ExpectationSet`](#ExpectationSet) objects. +The mock function call is expected to occur after all of the given expectations. + +For example, the following code sets the expectation that the `Describe()` +method of `my_mock` is called only after both `InitX()` and `InitY()` have been +called. + +```cpp +using ::testing::Expectation; +... +Expectation init_x = EXPECT_CALL(my_mock, InitX()); +Expectation init_y = EXPECT_CALL(my_mock, InitY()); +EXPECT_CALL(my_mock, Describe()) + .After(init_x, init_y); +``` + +The `ExpectationSet` object is helpful when the number of prerequisites for an +expectation is large or variable, for example: + +```cpp +using ::testing::ExpectationSet; +... +ExpectationSet all_inits; +// Collect all expectations of InitElement() calls +for (int i = 0; i < element_count; i++) { + all_inits += EXPECT_CALL(my_mock, InitElement(i)); +} +EXPECT_CALL(my_mock, Describe()) + .After(all_inits); // Expect Describe() call after all InitElement() calls +``` + +The `After` clause can be used any number of times on an expectation. + +#### WillOnce {#EXPECT_CALL.WillOnce} + +`.WillOnce(`*`action`*`)` + +Specifies the mock function's actual behavior when invoked, for a single +matching function call. + +The parameter *`action`* represents the +[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function +call will perform. See the [Actions Reference](actions.md) for a list of +built-in actions. + +The use of `WillOnce` implicitly sets a cardinality on the expectation when +`Times` is not specified. See [`Times`](#EXPECT_CALL.Times). + +Each matching function call will perform the next action in the order declared. +For example, the following code specifies that `my_mock.GetNumber()` is expected +to be called exactly 3 times and will return `1`, `2`, and `3` respectively on +the first, second, and third calls: + +```cpp +using ::testing::Return; +... +EXPECT_CALL(my_mock, GetNumber()) + .WillOnce(Return(1)) + .WillOnce(Return(2)) + .WillOnce(Return(3)); +``` + +The `WillOnce` clause can be used any number of times on an expectation. Unlike +`WillRepeatedly`, the action fed to each `WillOnce` call will be called at most +once, so may be a move-only type and/or have an `&&`-qualified call operator. + +#### WillRepeatedly {#EXPECT_CALL.WillRepeatedly} + +`.WillRepeatedly(`*`action`*`)` + +Specifies the mock function's actual behavior when invoked, for all subsequent +matching function calls. Takes effect after the actions specified in the +[`WillOnce`](#EXPECT_CALL.WillOnce) clauses, if any, have been performed. + +The parameter *`action`* represents the +[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function +call will perform. See the [Actions Reference](actions.md) for a list of +built-in actions. + +The use of `WillRepeatedly` implicitly sets a cardinality on the expectation +when `Times` is not specified. See [`Times`](#EXPECT_CALL.Times). + +If any `WillOnce` clauses have been specified, matching function calls will +perform those actions before the action specified by `WillRepeatedly`. See the +following example: + +```cpp +using ::testing::Return; +... +EXPECT_CALL(my_mock, GetName()) + .WillRepeatedly(Return("John Doe")); // Return "John Doe" on all calls + +EXPECT_CALL(my_mock, GetNumber()) + .WillOnce(Return(42)) // Return 42 on the first call + .WillRepeatedly(Return(7)); // Return 7 on all subsequent calls +``` + +The `WillRepeatedly` clause can be used at most once on an expectation. + +#### RetiresOnSaturation {#EXPECT_CALL.RetiresOnSaturation} + +`.RetiresOnSaturation()` + +Indicates that the expectation will no longer be active after the expected +number of matching function calls has been reached. + +The `RetiresOnSaturation` clause is only meaningful for expectations with an +upper-bounded cardinality. The expectation will *retire* (no longer match any +function calls) after it has been *saturated* (the upper bound has been +reached). See the following example: + +```cpp +using ::testing::_; +using ::testing::AnyNumber; +... +EXPECT_CALL(my_mock, SetNumber(_)) // Expectation 1 + .Times(AnyNumber()); +EXPECT_CALL(my_mock, SetNumber(7)) // Expectation 2 + .Times(2) + .RetiresOnSaturation(); +``` + +In the above example, the first two calls to `my_mock.SetNumber(7)` match +expectation 2, which then becomes inactive and no longer matches any calls. A +third call to `my_mock.SetNumber(7)` would then match expectation 1. Without +`RetiresOnSaturation()` on expectation 2, a third call to `my_mock.SetNumber(7)` +would match expectation 2 again, producing a failure since the limit of 2 calls +was exceeded. + +The `RetiresOnSaturation` clause can be used at most once on an expectation and +must be the last clause. + +### ON_CALL {#ON_CALL} + +`ON_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))` + +Defines what happens when the method *`method_name`* of the object +*`mock_object`* is called with arguments that match the given matchers +*`matchers...`*. Requires a modifier clause to specify the method's behavior. +*Does not* set any expectations that the method will be called. + +The parameter *`matchers...`* is a comma-separated list of +[matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that +correspond to each argument of the method *`method_name`*. The `ON_CALL` +specification will apply only to calls of *`method_name`* whose arguments match +all of the matchers. If `(`*`matchers...`*`)` is omitted, the behavior is as if +each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard). +See the [Matchers Reference](matchers.md) for a list of all built-in matchers. + +The following chainable clauses can be used to set the method's behavior, and +they must be used in the following order: + +```cpp +ON_CALL(mock_object, method_name(matchers...)) + .With(multi_argument_matcher) // Can be used at most once + .WillByDefault(action); // Required +``` + +See details for each modifier clause below. + +#### With {#ON_CALL.With} + +`.With(`*`multi_argument_matcher`*`)` + +Restricts the specification to only mock function calls whose arguments as a +whole match the multi-argument matcher *`multi_argument_matcher`*. + +GoogleTest passes all of the arguments as one tuple into the matcher. The +parameter *`multi_argument_matcher`* must thus be a matcher of type +`Matcher>`, where `A1, ..., An` are the types of the +function arguments. + +For example, the following code sets the default behavior when +`my_mock.SetPosition()` is called with any two arguments, the first argument +being less than the second: + +```cpp +using ::testing::_; +using ::testing::Lt; +using ::testing::Return; +... +ON_CALL(my_mock, SetPosition(_, _)) + .With(Lt()) + .WillByDefault(Return(true)); +``` + +GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()` +matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers). + +The `With` clause can be used at most once with each `ON_CALL` statement. + +#### WillByDefault {#ON_CALL.WillByDefault} + +`.WillByDefault(`*`action`*`)` + +Specifies the default behavior of a matching mock function call. + +The parameter *`action`* represents the +[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function +call will perform. See the [Actions Reference](actions.md) for a list of +built-in actions. + +For example, the following code specifies that by default, a call to +`my_mock.Greet()` will return `"hello"`: + +```cpp +using ::testing::Return; +... +ON_CALL(my_mock, Greet()) + .WillByDefault(Return("hello")); +``` + +The action specified by `WillByDefault` is superseded by the actions specified +on a matching `EXPECT_CALL` statement, if any. See the +[`WillOnce`](#EXPECT_CALL.WillOnce) and +[`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) clauses of `EXPECT_CALL`. + +The `WillByDefault` clause must be used exactly once with each `ON_CALL` +statement. + +## Classes {#classes} + +GoogleTest defines the following classes for working with mocks. + +### DefaultValue {#DefaultValue} + +`::testing::DefaultValue` + +Allows a user to specify the default value for a type `T` that is both copyable +and publicly destructible (i.e. anything that can be used as a function return +type). For mock functions with a return type of `T`, this default value is +returned from function calls that do not specify an action. + +Provides the static methods `Set()`, `SetFactory()`, and `Clear()` to manage the +default value: + +```cpp +// Sets the default value to be returned. T must be copy constructible. +DefaultValue::Set(value); + +// Sets a factory. Will be invoked on demand. T must be move constructible. +T MakeT(); +DefaultValue::SetFactory(&MakeT); + +// Unsets the default value. +DefaultValue::Clear(); +``` + +### NiceMock {#NiceMock} + +`::testing::NiceMock` + +Represents a mock object that suppresses warnings on +[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The +template parameter `T` is any mock class, except for another `NiceMock`, +`NaggyMock`, or `StrictMock`. + +Usage of `NiceMock` is analogous to usage of `T`. `NiceMock` is a subclass +of `T`, so it can be used wherever an object of type `T` is accepted. In +addition, `NiceMock` can be constructed with any arguments that a constructor +of `T` accepts. + +For example, the following code suppresses warnings on the mock `my_mock` of +type `MockClass` if a method other than `DoSomething()` is called: + +```cpp +using ::testing::NiceMock; +... +NiceMock my_mock("some", "args"); +EXPECT_CALL(my_mock, DoSomething()); +... code that uses my_mock ... +``` + +`NiceMock` only works for mock methods defined using the `MOCK_METHOD` macro +directly in the definition of class `T`. If a mock method is defined in a base +class of `T`, a warning might still be generated. + +`NiceMock` might not work correctly if the destructor of `T` is not virtual. + +### NaggyMock {#NaggyMock} + +`::testing::NaggyMock` + +Represents a mock object that generates warnings on +[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The +template parameter `T` is any mock class, except for another `NiceMock`, +`NaggyMock`, or `StrictMock`. + +Usage of `NaggyMock` is analogous to usage of `T`. `NaggyMock` is a +subclass of `T`, so it can be used wherever an object of type `T` is accepted. +In addition, `NaggyMock` can be constructed with any arguments that a +constructor of `T` accepts. + +For example, the following code generates warnings on the mock `my_mock` of type +`MockClass` if a method other than `DoSomething()` is called: + +```cpp +using ::testing::NaggyMock; +... +NaggyMock my_mock("some", "args"); +EXPECT_CALL(my_mock, DoSomething()); +... code that uses my_mock ... +``` + +Mock objects of type `T` by default behave the same way as `NaggyMock`. + +### StrictMock {#StrictMock} + +`::testing::StrictMock` + +Represents a mock object that generates test failures on +[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The +template parameter `T` is any mock class, except for another `NiceMock`, +`NaggyMock`, or `StrictMock`. + +Usage of `StrictMock` is analogous to usage of `T`. `StrictMock` is a +subclass of `T`, so it can be used wherever an object of type `T` is accepted. +In addition, `StrictMock` can be constructed with any arguments that a +constructor of `T` accepts. + +For example, the following code generates a test failure on the mock `my_mock` +of type `MockClass` if a method other than `DoSomething()` is called: + +```cpp +using ::testing::StrictMock; +... +StrictMock my_mock("some", "args"); +EXPECT_CALL(my_mock, DoSomething()); +... code that uses my_mock ... +``` + +`StrictMock` only works for mock methods defined using the `MOCK_METHOD` +macro directly in the definition of class `T`. If a mock method is defined in a +base class of `T`, a failure might not be generated. + +`StrictMock` might not work correctly if the destructor of `T` is not +virtual. + +### Sequence {#Sequence} + +`::testing::Sequence` + +Represents a chronological sequence of expectations. See the +[`InSequence`](#EXPECT_CALL.InSequence) clause of `EXPECT_CALL` for usage. + +### InSequence {#InSequence} + +`::testing::InSequence` + +An object of this type causes all expectations encountered in its scope to be +put in an anonymous sequence. + +This allows more convenient expression of multiple expectations in a single +sequence: + +```cpp +using ::testing::InSequence; +{ + InSequence seq; + + // The following are expected to occur in the order declared. + EXPECT_CALL(...); + EXPECT_CALL(...); + ... + EXPECT_CALL(...); +} +``` + +The name of the `InSequence` object does not matter. + +### Expectation {#Expectation} + +`::testing::Expectation` + +Represents a mock function call expectation as created by +[`EXPECT_CALL`](#EXPECT_CALL): + +```cpp +using ::testing::Expectation; +Expectation my_expectation = EXPECT_CALL(...); +``` + +Useful for specifying sequences of expectations; see the +[`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`. + +### ExpectationSet {#ExpectationSet} + +`::testing::ExpectationSet` + +Represents a set of mock function call expectations. + +Use the `+=` operator to add [`Expectation`](#Expectation) objects to the set: + +```cpp +using ::testing::ExpectationSet; +ExpectationSet my_expectations; +my_expectations += EXPECT_CALL(...); +``` + +Useful for specifying sequences of expectations; see the +[`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`. diff --git a/third_party/googletest/docs/reference/testing.md b/third_party/googletest/docs/reference/testing.md new file mode 100644 index 0000000..dc47942 --- /dev/null +++ b/third_party/googletest/docs/reference/testing.md @@ -0,0 +1,1431 @@ +# Testing Reference + + + +This page lists the facilities provided by GoogleTest for writing test programs. +To use them, include the header `gtest/gtest.h`. + +## Macros + +GoogleTest defines the following macros for writing tests. + +### TEST {#TEST} + +
+TEST(TestSuiteName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual test named *`TestName`* in the test suite +*`TestSuiteName`*, consisting of the given statements. + +Both arguments *`TestSuiteName`* and *`TestName`* must be valid C++ identifiers +and must not contain underscores (`_`). Tests in different test suites can have +the same individual name. + +The statements within the test body can be any code under test. +[Assertions](assertions.md) used within the test body determine the outcome of +the test. + +### TEST_F {#TEST_F} + +
+TEST_F(TestFixtureName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual test named *`TestName`* that uses the test fixture class +*`TestFixtureName`*. The test suite name is *`TestFixtureName`*. + +Both arguments *`TestFixtureName`* and *`TestName`* must be valid C++ +identifiers and must not contain underscores (`_`). *`TestFixtureName`* must be +the name of a test fixture class—see +[Test Fixtures](../primer.md#same-data-multiple-tests). + +The statements within the test body can be any code under test. +[Assertions](assertions.md) used within the test body determine the outcome of +the test. + +### TEST_P {#TEST_P} + +
+TEST_P(TestFixtureName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual value-parameterized test named *`TestName`* that uses the +test fixture class *`TestFixtureName`*. The test suite name is +*`TestFixtureName`*. + +Both arguments *`TestFixtureName`* and *`TestName`* must be valid C++ +identifiers and must not contain underscores (`_`). *`TestFixtureName`* must be +the name of a value-parameterized test fixture class—see +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +The statements within the test body can be any code under test. Within the test +body, the test parameter can be accessed with the `GetParam()` function (see +[`WithParamInterface`](#WithParamInterface)). For example: + +```cpp +TEST_P(MyTestSuite, DoesSomething) { + ... + EXPECT_TRUE(DoSomething(GetParam())); + ... +} +``` + +[Assertions](assertions.md) used within the test body determine the outcome of +the test. + +See also [`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P). + +### INSTANTIATE_TEST_SUITE_P {#INSTANTIATE_TEST_SUITE_P} + +`INSTANTIATE_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`param_generator`*`)` +\ +`INSTANTIATE_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`param_generator`*`,`*`name_generator`*`)` + +Instantiates the value-parameterized test suite *`TestSuiteName`* (defined with +[`TEST_P`](#TEST_P)). + +The argument *`InstantiationName`* is a unique name for the instantiation of the +test suite, to distinguish between multiple instantiations. In test output, the +instantiation name is added as a prefix to the test suite name +*`TestSuiteName`*. + +The argument *`param_generator`* is one of the following GoogleTest-provided +functions that generate the test parameters, all defined in the `::testing` +namespace: + + + +| Parameter Generator | Behavior | +| ------------------- | ---------------------------------------------------- | +| `Range(begin, end [, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. | +| `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. | +| `ValuesIn(container)` or `ValuesIn(begin,end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. | +| `Bool()` | Yields sequence `{false, true}`. | +| `Combine(g1, g2, ..., gN)` | Yields as `std::tuple` *n*-tuples all combinations (Cartesian product) of the values generated by the given *n* generators `g1`, `g2`, ..., `gN`. | + +The optional last argument *`name_generator`* is a function or functor that +generates custom test name suffixes based on the test parameters. The function +must accept an argument of type +[`TestParamInfo`](#TestParamInfo) and return a `std::string`. +The test name suffix can only contain alphanumeric characters and underscores. +GoogleTest provides [`PrintToStringParamName`](#PrintToStringParamName), or a +custom function can be used for more control: + +```cpp +INSTANTIATE_TEST_SUITE_P( + MyInstantiation, MyTestSuite, + ::testing::Values(...), + [](const ::testing::TestParamInfo& info) { + // Can use info.param here to generate the test suffix + std::string name = ... + return name; + }); +``` + +For more information, see +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +See also +[`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST`](#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST). + +### TYPED_TEST_SUITE {#TYPED_TEST_SUITE} + +`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`)` + +Defines a typed test suite based on the test fixture *`TestFixtureName`*. The +test suite name is *`TestFixtureName`*. + +The argument *`TestFixtureName`* is a fixture class template, parameterized by a +type, for example: + +```cpp +template +class MyFixture : public ::testing::Test { + public: + ... + using List = std::list; + static T shared_; + T value_; +}; +``` + +The argument *`Types`* is a [`Types`](#Types) object representing the list of +types to run the tests on, for example: + +```cpp +using MyTypes = ::testing::Types; +TYPED_TEST_SUITE(MyFixture, MyTypes); +``` + +The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE` +macro to parse correctly. + +See also [`TYPED_TEST`](#TYPED_TEST) and +[Typed Tests](../advanced.md#typed-tests) for more information. + +### TYPED_TEST {#TYPED_TEST} + +
+TYPED_TEST(TestSuiteName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual typed test named *`TestName`* in the typed test suite +*`TestSuiteName`*. The test suite must be defined with +[`TYPED_TEST_SUITE`](#TYPED_TEST_SUITE). + +Within the test body, the special name `TypeParam` refers to the type parameter, +and `TestFixture` refers to the fixture class. See the following example: + +```cpp +TYPED_TEST(MyFixture, Example) { + // Inside a test, refer to the special name TypeParam to get the type + // parameter. Since we are inside a derived class template, C++ requires + // us to visit the members of MyFixture via 'this'. + TypeParam n = this->value_; + + // To visit static members of the fixture, add the 'TestFixture::' + // prefix. + n += TestFixture::shared_; + + // To refer to typedefs in the fixture, add the 'typename TestFixture::' + // prefix. The 'typename' is required to satisfy the compiler. + typename TestFixture::List values; + + values.push_back(n); + ... +} +``` + +For more information, see [Typed Tests](../advanced.md#typed-tests). + +### TYPED_TEST_SUITE_P {#TYPED_TEST_SUITE_P} + +`TYPED_TEST_SUITE_P(`*`TestFixtureName`*`)` + +Defines a type-parameterized test suite based on the test fixture +*`TestFixtureName`*. The test suite name is *`TestFixtureName`*. + +The argument *`TestFixtureName`* is a fixture class template, parameterized by a +type. See [`TYPED_TEST_SUITE`](#TYPED_TEST_SUITE) for an example. + +See also [`TYPED_TEST_P`](#TYPED_TEST_P) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### TYPED_TEST_P {#TYPED_TEST_P} + +
+TYPED_TEST_P(TestSuiteName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual type-parameterized test named *`TestName`* in the +type-parameterized test suite *`TestSuiteName`*. The test suite must be defined +with [`TYPED_TEST_SUITE_P`](#TYPED_TEST_SUITE_P). + +Within the test body, the special name `TypeParam` refers to the type parameter, +and `TestFixture` refers to the fixture class. See [`TYPED_TEST`](#TYPED_TEST) +for an example. + +See also [`REGISTER_TYPED_TEST_SUITE_P`](#REGISTER_TYPED_TEST_SUITE_P) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### REGISTER_TYPED_TEST_SUITE_P {#REGISTER_TYPED_TEST_SUITE_P} + +`REGISTER_TYPED_TEST_SUITE_P(`*`TestSuiteName`*`,`*`TestNames...`*`)` + +Registers the type-parameterized tests *`TestNames...`* of the test suite +*`TestSuiteName`*. The test suite and tests must be defined with +[`TYPED_TEST_SUITE_P`](#TYPED_TEST_SUITE_P) and [`TYPED_TEST_P`](#TYPED_TEST_P). + +For example: + +```cpp +// Define the test suite and tests. +TYPED_TEST_SUITE_P(MyFixture); +TYPED_TEST_P(MyFixture, HasPropertyA) { ... } +TYPED_TEST_P(MyFixture, HasPropertyB) { ... } + +// Register the tests in the test suite. +REGISTER_TYPED_TEST_SUITE_P(MyFixture, HasPropertyA, HasPropertyB); +``` + +See also [`INSTANTIATE_TYPED_TEST_SUITE_P`](#INSTANTIATE_TYPED_TEST_SUITE_P) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### INSTANTIATE_TYPED_TEST_SUITE_P {#INSTANTIATE_TYPED_TEST_SUITE_P} + +`INSTANTIATE_TYPED_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`Types`*`)` + +Instantiates the type-parameterized test suite *`TestSuiteName`*. The test suite +must be registered with +[`REGISTER_TYPED_TEST_SUITE_P`](#REGISTER_TYPED_TEST_SUITE_P). + +The argument *`InstantiationName`* is a unique name for the instantiation of the +test suite, to distinguish between multiple instantiations. In test output, the +instantiation name is added as a prefix to the test suite name +*`TestSuiteName`*. + +The argument *`Types`* is a [`Types`](#Types) object representing the list of +types to run the tests on, for example: + +```cpp +using MyTypes = ::testing::Types; +INSTANTIATE_TYPED_TEST_SUITE_P(MyInstantiation, MyFixture, MyTypes); +``` + +The type alias (`using` or `typedef`) is necessary for the +`INSTANTIATE_TYPED_TEST_SUITE_P` macro to parse correctly. + +For more information, see +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests). + +### FRIEND_TEST {#FRIEND_TEST} + +`FRIEND_TEST(`*`TestSuiteName`*`,`*`TestName`*`)` + +Within a class body, declares an individual test as a friend of the class, +enabling the test to access private class members. + +If the class is defined in a namespace, then in order to be friends of the +class, test fixtures and tests must be defined in the exact same namespace, +without inline or anonymous namespaces. + +For example, if the class definition looks like the following: + +```cpp +namespace my_namespace { + +class MyClass { + friend class MyClassTest; + FRIEND_TEST(MyClassTest, HasPropertyA); + FRIEND_TEST(MyClassTest, HasPropertyB); + ... definition of class MyClass ... +}; + +} // namespace my_namespace +``` + +Then the test code should look like: + +```cpp +namespace my_namespace { + +class MyClassTest : public ::testing::Test { + ... +}; + +TEST_F(MyClassTest, HasPropertyA) { ... } +TEST_F(MyClassTest, HasPropertyB) { ... } + +} // namespace my_namespace +``` + +See [Testing Private Code](../advanced.md#testing-private-code) for more +information. + +### SCOPED_TRACE {#SCOPED_TRACE} + +`SCOPED_TRACE(`*`message`*`)` + +Causes the current file name, line number, and the given message *`message`* to +be added to the failure message for each assertion failure that occurs in the +scope. + +For more information, see +[Adding Traces to Assertions](../advanced.md#adding-traces-to-assertions). + +See also the [`ScopedTrace` class](#ScopedTrace). + +### GTEST_SKIP {#GTEST_SKIP} + +`GTEST_SKIP()` + +Prevents further test execution at runtime. + +Can be used in individual test cases or in the `SetUp()` methods of test +environments or test fixtures (classes derived from the +[`Environment`](#Environment) or [`Test`](#Test) classes). If used in a global +test environment `SetUp()` method, it skips all tests in the test program. If +used in a test fixture `SetUp()` method, it skips all tests in the corresponding +test suite. + +Similar to assertions, `GTEST_SKIP` allows streaming a custom message into it. + +See [Skipping Test Execution](../advanced.md#skipping-test-execution) for more +information. + +### GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST {#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST} + +`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(`*`TestSuiteName`*`)` + +Allows the value-parameterized test suite *`TestSuiteName`* to be +uninstantiated. + +By default, every [`TEST_P`](#TEST_P) call without a corresponding +[`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P) call causes a failing +test in the test suite `GoogleTestVerification`. +`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST` suppresses this failure for the +given test suite. + +## Classes and types + +GoogleTest defines the following classes and types to help with writing tests. + +### AssertionResult {#AssertionResult} + +`::testing::AssertionResult` + +A class for indicating whether an assertion was successful. + +When the assertion wasn't successful, the `AssertionResult` object stores a +non-empty failure message that can be retrieved with the object's `message()` +method. + +To create an instance of this class, use one of the factory functions +[`AssertionSuccess()`](#AssertionSuccess) or +[`AssertionFailure()`](#AssertionFailure). + +### AssertionException {#AssertionException} + +`::testing::AssertionException` + +Exception which can be thrown from +[`TestEventListener::OnTestPartResult`](#TestEventListener::OnTestPartResult). + +### EmptyTestEventListener {#EmptyTestEventListener} + +`::testing::EmptyTestEventListener` + +Provides an empty implementation of all methods in the +[`TestEventListener`](#TestEventListener) interface, such that a subclass only +needs to override the methods it cares about. + +### Environment {#Environment} + +`::testing::Environment` + +Represents a global test environment. See +[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down). + +#### Protected Methods {#Environment-protected} + +##### SetUp {#Environment::SetUp} + +`virtual void Environment::SetUp()` + +Override this to define how to set up the environment. + +##### TearDown {#Environment::TearDown} + +`virtual void Environment::TearDown()` + +Override this to define how to tear down the environment. + +### ScopedTrace {#ScopedTrace} + +`::testing::ScopedTrace` + +An instance of this class causes a trace to be included in every test failure +message generated by code in the scope of the lifetime of the `ScopedTrace` +instance. The effect is undone with the destruction of the instance. + +The `ScopedTrace` constructor has the following form: + +```cpp +template +ScopedTrace(const char* file, int line, const T& message) +``` + +Example usage: + +```cpp +::testing::ScopedTrace trace("file.cc", 123, "message"); +``` + +The resulting trace includes the given source file path and line number, and the +given message. The `message` argument can be anything streamable to +`std::ostream`. + +See also [`SCOPED_TRACE`](#SCOPED_TRACE). + +### Test {#Test} + +`::testing::Test` + +The abstract class that all tests inherit from. `Test` is not copyable. + +#### Public Methods {#Test-public} + +##### SetUpTestSuite {#Test::SetUpTestSuite} + +`static void Test::SetUpTestSuite()` + +Performs shared setup for all tests in the test suite. GoogleTest calls +`SetUpTestSuite()` before running the first test in the test suite. + +##### TearDownTestSuite {#Test::TearDownTestSuite} + +`static void Test::TearDownTestSuite()` + +Performs shared teardown for all tests in the test suite. GoogleTest calls +`TearDownTestSuite()` after running the last test in the test suite. + +##### HasFatalFailure {#Test::HasFatalFailure} + +`static bool Test::HasFatalFailure()` + +Returns true if and only if the current test has a fatal failure. + +##### HasNonfatalFailure {#Test::HasNonfatalFailure} + +`static bool Test::HasNonfatalFailure()` + +Returns true if and only if the current test has a nonfatal failure. + +##### HasFailure {#Test::HasFailure} + +`static bool Test::HasFailure()` + +Returns true if and only if the current test has any failure, either fatal or +nonfatal. + +##### IsSkipped {#Test::IsSkipped} + +`static bool Test::IsSkipped()` + +Returns true if and only if the current test was skipped. + +##### RecordProperty {#Test::RecordProperty} + +`static void Test::RecordProperty(const std::string& key, const std::string& +value)` \ +`static void Test::RecordProperty(const std::string& key, int value)` + +Logs a property for the current test, test suite, or entire invocation of the +test program. Only the last value for a given key is logged. + +The key must be a valid XML attribute name, and cannot conflict with the ones +already used by GoogleTest (`name`, `file`, `line`, `status`, `time`, +`classname`, `type_param`, and `value_param`). + +`RecordProperty` is `public static` so it can be called from utility functions +that are not members of the test fixture. + +Calls to `RecordProperty` made during the lifespan of the test (from the moment +its constructor starts to the moment its destructor finishes) are output in XML +as attributes of the `` element. Properties recorded from a fixture's +`SetUpTestSuite` or `TearDownTestSuite` methods are logged as attributes of the +corresponding `` element. Calls to `RecordProperty` made in the +global context (before or after invocation of `RUN_ALL_TESTS` or from the +`SetUp`/`TearDown` methods of registered `Environment` objects) are output as +attributes of the `` element. + +#### Protected Methods {#Test-protected} + +##### SetUp {#Test::SetUp} + +`virtual void Test::SetUp()` + +Override this to perform test fixture setup. GoogleTest calls `SetUp()` before +running each individual test. + +##### TearDown {#Test::TearDown} + +`virtual void Test::TearDown()` + +Override this to perform test fixture teardown. GoogleTest calls `TearDown()` +after running each individual test. + +### TestWithParam {#TestWithParam} + +`::testing::TestWithParam` + +A convenience class which inherits from both [`Test`](#Test) and +[`WithParamInterface`](#WithParamInterface). + +### TestSuite {#TestSuite} + +Represents a test suite. `TestSuite` is not copyable. + +#### Public Methods {#TestSuite-public} + +##### name {#TestSuite::name} + +`const char* TestSuite::name() const` + +Gets the name of the test suite. + +##### type_param {#TestSuite::type_param} + +`const char* TestSuite::type_param() const` + +Returns the name of the parameter type, or `NULL` if this is not a typed or +type-parameterized test suite. See [Typed Tests](../advanced.md#typed-tests) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests). + +##### should_run {#TestSuite::should_run} + +`bool TestSuite::should_run() const` + +Returns true if any test in this test suite should run. + +##### successful_test_count {#TestSuite::successful_test_count} + +`int TestSuite::successful_test_count() const` + +Gets the number of successful tests in this test suite. + +##### skipped_test_count {#TestSuite::skipped_test_count} + +`int TestSuite::skipped_test_count() const` + +Gets the number of skipped tests in this test suite. + +##### failed_test_count {#TestSuite::failed_test_count} + +`int TestSuite::failed_test_count() const` + +Gets the number of failed tests in this test suite. + +##### reportable_disabled_test_count {#TestSuite::reportable_disabled_test_count} + +`int TestSuite::reportable_disabled_test_count() const` + +Gets the number of disabled tests that will be reported in the XML report. + +##### disabled_test_count {#TestSuite::disabled_test_count} + +`int TestSuite::disabled_test_count() const` + +Gets the number of disabled tests in this test suite. + +##### reportable_test_count {#TestSuite::reportable_test_count} + +`int TestSuite::reportable_test_count() const` + +Gets the number of tests to be printed in the XML report. + +##### test_to_run_count {#TestSuite::test_to_run_count} + +`int TestSuite::test_to_run_count() const` + +Get the number of tests in this test suite that should run. + +##### total_test_count {#TestSuite::total_test_count} + +`int TestSuite::total_test_count() const` + +Gets the number of all tests in this test suite. + +##### Passed {#TestSuite::Passed} + +`bool TestSuite::Passed() const` + +Returns true if and only if the test suite passed. + +##### Failed {#TestSuite::Failed} + +`bool TestSuite::Failed() const` + +Returns true if and only if the test suite failed. + +##### elapsed_time {#TestSuite::elapsed_time} + +`TimeInMillis TestSuite::elapsed_time() const` + +Returns the elapsed time, in milliseconds. + +##### start_timestamp {#TestSuite::start_timestamp} + +`TimeInMillis TestSuite::start_timestamp() const` + +Gets the time of the test suite start, in ms from the start of the UNIX epoch. + +##### GetTestInfo {#TestSuite::GetTestInfo} + +`const TestInfo* TestSuite::GetTestInfo(int i) const` + +Returns the [`TestInfo`](#TestInfo) for the `i`-th test among all the tests. `i` +can range from 0 to `total_test_count() - 1`. If `i` is not in that range, +returns `NULL`. + +##### ad_hoc_test_result {#TestSuite::ad_hoc_test_result} + +`const TestResult& TestSuite::ad_hoc_test_result() const` + +Returns the [`TestResult`](#TestResult) that holds test properties recorded +during execution of `SetUpTestSuite` and `TearDownTestSuite`. + +### TestInfo {#TestInfo} + +`::testing::TestInfo` + +Stores information about a test. + +#### Public Methods {#TestInfo-public} + +##### test_suite_name {#TestInfo::test_suite_name} + +`const char* TestInfo::test_suite_name() const` + +Returns the test suite name. + +##### name {#TestInfo::name} + +`const char* TestInfo::name() const` + +Returns the test name. + +##### type_param {#TestInfo::type_param} + +`const char* TestInfo::type_param() const` + +Returns the name of the parameter type, or `NULL` if this is not a typed or +type-parameterized test. See [Typed Tests](../advanced.md#typed-tests) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests). + +##### value_param {#TestInfo::value_param} + +`const char* TestInfo::value_param() const` + +Returns the text representation of the value parameter, or `NULL` if this is not +a value-parameterized test. See +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +##### file {#TestInfo::file} + +`const char* TestInfo::file() const` + +Returns the file name where this test is defined. + +##### line {#TestInfo::line} + +`int TestInfo::line() const` + +Returns the line where this test is defined. + +##### is_in_another_shard {#TestInfo::is_in_another_shard} + +`bool TestInfo::is_in_another_shard() const` + +Returns true if this test should not be run because it's in another shard. + +##### should_run {#TestInfo::should_run} + +`bool TestInfo::should_run() const` + +Returns true if this test should run, that is if the test is not disabled (or it +is disabled but the `also_run_disabled_tests` flag has been specified) and its +full name matches the user-specified filter. + +GoogleTest allows the user to filter the tests by their full names. Only the +tests that match the filter will run. See +[Running a Subset of the Tests](../advanced.md#running-a-subset-of-the-tests) +for more information. + +##### is_reportable {#TestInfo::is_reportable} + +`bool TestInfo::is_reportable() const` + +Returns true if and only if this test will appear in the XML report. + +##### result {#TestInfo::result} + +`const TestResult* TestInfo::result() const` + +Returns the result of the test. See [`TestResult`](#TestResult). + +### TestParamInfo {#TestParamInfo} + +`::testing::TestParamInfo` + +Describes a parameter to a value-parameterized test. The type `T` is the type of +the parameter. + +Contains the fields `param` and `index` which hold the value of the parameter +and its integer index respectively. + +### UnitTest {#UnitTest} + +`::testing::UnitTest` + +This class contains information about the test program. + +`UnitTest` is a singleton class. The only instance is created when +`UnitTest::GetInstance()` is first called. This instance is never deleted. + +`UnitTest` is not copyable. + +#### Public Methods {#UnitTest-public} + +##### GetInstance {#UnitTest::GetInstance} + +`static UnitTest* UnitTest::GetInstance()` + +Gets the singleton `UnitTest` object. The first time this method is called, a +`UnitTest` object is constructed and returned. Consecutive calls will return the +same object. + +##### original_working_dir {#UnitTest::original_working_dir} + +`const char* UnitTest::original_working_dir() const` + +Returns the working directory when the first [`TEST()`](#TEST) or +[`TEST_F()`](#TEST_F) was executed. The `UnitTest` object owns the string. + +##### current_test_suite {#UnitTest::current_test_suite} + +`const TestSuite* UnitTest::current_test_suite() const` + +Returns the [`TestSuite`](#TestSuite) object for the test that's currently +running, or `NULL` if no test is running. + +##### current_test_info {#UnitTest::current_test_info} + +`const TestInfo* UnitTest::current_test_info() const` + +Returns the [`TestInfo`](#TestInfo) object for the test that's currently +running, or `NULL` if no test is running. + +##### random_seed {#UnitTest::random_seed} + +`int UnitTest::random_seed() const` + +Returns the random seed used at the start of the current test run. + +##### successful_test_suite_count {#UnitTest::successful_test_suite_count} + +`int UnitTest::successful_test_suite_count() const` + +Gets the number of successful test suites. + +##### failed_test_suite_count {#UnitTest::failed_test_suite_count} + +`int UnitTest::failed_test_suite_count() const` + +Gets the number of failed test suites. + +##### total_test_suite_count {#UnitTest::total_test_suite_count} + +`int UnitTest::total_test_suite_count() const` + +Gets the number of all test suites. + +##### test_suite_to_run_count {#UnitTest::test_suite_to_run_count} + +`int UnitTest::test_suite_to_run_count() const` + +Gets the number of all test suites that contain at least one test that should +run. + +##### successful_test_count {#UnitTest::successful_test_count} + +`int UnitTest::successful_test_count() const` + +Gets the number of successful tests. + +##### skipped_test_count {#UnitTest::skipped_test_count} + +`int UnitTest::skipped_test_count() const` + +Gets the number of skipped tests. + +##### failed_test_count {#UnitTest::failed_test_count} + +`int UnitTest::failed_test_count() const` + +Gets the number of failed tests. + +##### reportable_disabled_test_count {#UnitTest::reportable_disabled_test_count} + +`int UnitTest::reportable_disabled_test_count() const` + +Gets the number of disabled tests that will be reported in the XML report. + +##### disabled_test_count {#UnitTest::disabled_test_count} + +`int UnitTest::disabled_test_count() const` + +Gets the number of disabled tests. + +##### reportable_test_count {#UnitTest::reportable_test_count} + +`int UnitTest::reportable_test_count() const` + +Gets the number of tests to be printed in the XML report. + +##### total_test_count {#UnitTest::total_test_count} + +`int UnitTest::total_test_count() const` + +Gets the number of all tests. + +##### test_to_run_count {#UnitTest::test_to_run_count} + +`int UnitTest::test_to_run_count() const` + +Gets the number of tests that should run. + +##### start_timestamp {#UnitTest::start_timestamp} + +`TimeInMillis UnitTest::start_timestamp() const` + +Gets the time of the test program start, in ms from the start of the UNIX epoch. + +##### elapsed_time {#UnitTest::elapsed_time} + +`TimeInMillis UnitTest::elapsed_time() const` + +Gets the elapsed time, in milliseconds. + +##### Passed {#UnitTest::Passed} + +`bool UnitTest::Passed() const` + +Returns true if and only if the unit test passed (i.e. all test suites passed). + +##### Failed {#UnitTest::Failed} + +`bool UnitTest::Failed() const` + +Returns true if and only if the unit test failed (i.e. some test suite failed or +something outside of all tests failed). + +##### GetTestSuite {#UnitTest::GetTestSuite} + +`const TestSuite* UnitTest::GetTestSuite(int i) const` + +Gets the [`TestSuite`](#TestSuite) object for the `i`-th test suite among all +the test suites. `i` can range from 0 to `total_test_suite_count() - 1`. If `i` +is not in that range, returns `NULL`. + +##### ad_hoc_test_result {#UnitTest::ad_hoc_test_result} + +`const TestResult& UnitTest::ad_hoc_test_result() const` + +Returns the [`TestResult`](#TestResult) containing information on test failures +and properties logged outside of individual test suites. + +##### listeners {#UnitTest::listeners} + +`TestEventListeners& UnitTest::listeners()` + +Returns the list of event listeners that can be used to track events inside +GoogleTest. See [`TestEventListeners`](#TestEventListeners). + +### TestEventListener {#TestEventListener} + +`::testing::TestEventListener` + +The interface for tracing execution of tests. The methods below are listed in +the order the corresponding events are fired. + +#### Public Methods {#TestEventListener-public} + +##### OnTestProgramStart {#TestEventListener::OnTestProgramStart} + +`virtual void TestEventListener::OnTestProgramStart(const UnitTest& unit_test)` + +Fired before any test activity starts. + +##### OnTestIterationStart {#TestEventListener::OnTestIterationStart} + +`virtual void TestEventListener::OnTestIterationStart(const UnitTest& unit_test, +int iteration)` + +Fired before each iteration of tests starts. There may be more than one +iteration if `GTEST_FLAG(repeat)` is set. `iteration` is the iteration index, +starting from 0. + +##### OnEnvironmentsSetUpStart {#TestEventListener::OnEnvironmentsSetUpStart} + +`virtual void TestEventListener::OnEnvironmentsSetUpStart(const UnitTest& +unit_test)` + +Fired before environment set-up for each iteration of tests starts. + +##### OnEnvironmentsSetUpEnd {#TestEventListener::OnEnvironmentsSetUpEnd} + +`virtual void TestEventListener::OnEnvironmentsSetUpEnd(const UnitTest& +unit_test)` + +Fired after environment set-up for each iteration of tests ends. + +##### OnTestSuiteStart {#TestEventListener::OnTestSuiteStart} + +`virtual void TestEventListener::OnTestSuiteStart(const TestSuite& test_suite)` + +Fired before the test suite starts. + +##### OnTestStart {#TestEventListener::OnTestStart} + +`virtual void TestEventListener::OnTestStart(const TestInfo& test_info)` + +Fired before the test starts. + +##### OnTestPartResult {#TestEventListener::OnTestPartResult} + +`virtual void TestEventListener::OnTestPartResult(const TestPartResult& +test_part_result)` + +Fired after a failed assertion or a `SUCCEED()` invocation. If you want to throw +an exception from this function to skip to the next test, it must be an +[`AssertionException`](#AssertionException) or inherited from it. + +##### OnTestEnd {#TestEventListener::OnTestEnd} + +`virtual void TestEventListener::OnTestEnd(const TestInfo& test_info)` + +Fired after the test ends. + +##### OnTestSuiteEnd {#TestEventListener::OnTestSuiteEnd} + +`virtual void TestEventListener::OnTestSuiteEnd(const TestSuite& test_suite)` + +Fired after the test suite ends. + +##### OnEnvironmentsTearDownStart {#TestEventListener::OnEnvironmentsTearDownStart} + +`virtual void TestEventListener::OnEnvironmentsTearDownStart(const UnitTest& +unit_test)` + +Fired before environment tear-down for each iteration of tests starts. + +##### OnEnvironmentsTearDownEnd {#TestEventListener::OnEnvironmentsTearDownEnd} + +`virtual void TestEventListener::OnEnvironmentsTearDownEnd(const UnitTest& +unit_test)` + +Fired after environment tear-down for each iteration of tests ends. + +##### OnTestIterationEnd {#TestEventListener::OnTestIterationEnd} + +`virtual void TestEventListener::OnTestIterationEnd(const UnitTest& unit_test, +int iteration)` + +Fired after each iteration of tests finishes. + +##### OnTestProgramEnd {#TestEventListener::OnTestProgramEnd} + +`virtual void TestEventListener::OnTestProgramEnd(const UnitTest& unit_test)` + +Fired after all test activities have ended. + +### TestEventListeners {#TestEventListeners} + +`::testing::TestEventListeners` + +Lets users add listeners to track events in GoogleTest. + +#### Public Methods {#TestEventListeners-public} + +##### Append {#TestEventListeners::Append} + +`void TestEventListeners::Append(TestEventListener* listener)` + +Appends an event listener to the end of the list. GoogleTest assumes ownership +of the listener (i.e. it will delete the listener when the test program +finishes). + +##### Release {#TestEventListeners::Release} + +`TestEventListener* TestEventListeners::Release(TestEventListener* listener)` + +Removes the given event listener from the list and returns it. It then becomes +the caller's responsibility to delete the listener. Returns `NULL` if the +listener is not found in the list. + +##### default_result_printer {#TestEventListeners::default_result_printer} + +`TestEventListener* TestEventListeners::default_result_printer() const` + +Returns the standard listener responsible for the default console output. Can be +removed from the listeners list to shut down default console output. Note that +removing this object from the listener list with +[`Release()`](#TestEventListeners::Release) transfers its ownership to the +caller and makes this function return `NULL` the next time. + +##### default_xml_generator {#TestEventListeners::default_xml_generator} + +`TestEventListener* TestEventListeners::default_xml_generator() const` + +Returns the standard listener responsible for the default XML output controlled +by the `--gtest_output=xml` flag. Can be removed from the listeners list by +users who want to shut down the default XML output controlled by this flag and +substitute it with custom one. Note that removing this object from the listener +list with [`Release()`](#TestEventListeners::Release) transfers its ownership to +the caller and makes this function return `NULL` the next time. + +### TestPartResult {#TestPartResult} + +`::testing::TestPartResult` + +A copyable object representing the result of a test part (i.e. an assertion or +an explicit `FAIL()`, `ADD_FAILURE()`, or `SUCCESS()`). + +#### Public Methods {#TestPartResult-public} + +##### type {#TestPartResult::type} + +`Type TestPartResult::type() const` + +Gets the outcome of the test part. + +The return type `Type` is an enum defined as follows: + +```cpp +enum Type { + kSuccess, // Succeeded. + kNonFatalFailure, // Failed but the test can continue. + kFatalFailure, // Failed and the test should be terminated. + kSkip // Skipped. +}; +``` + +##### file_name {#TestPartResult::file_name} + +`const char* TestPartResult::file_name() const` + +Gets the name of the source file where the test part took place, or `NULL` if +it's unknown. + +##### line_number {#TestPartResult::line_number} + +`int TestPartResult::line_number() const` + +Gets the line in the source file where the test part took place, or `-1` if it's +unknown. + +##### summary {#TestPartResult::summary} + +`const char* TestPartResult::summary() const` + +Gets the summary of the failure message. + +##### message {#TestPartResult::message} + +`const char* TestPartResult::message() const` + +Gets the message associated with the test part. + +##### skipped {#TestPartResult::skipped} + +`bool TestPartResult::skipped() const` + +Returns true if and only if the test part was skipped. + +##### passed {#TestPartResult::passed} + +`bool TestPartResult::passed() const` + +Returns true if and only if the test part passed. + +##### nonfatally_failed {#TestPartResult::nonfatally_failed} + +`bool TestPartResult::nonfatally_failed() const` + +Returns true if and only if the test part non-fatally failed. + +##### fatally_failed {#TestPartResult::fatally_failed} + +`bool TestPartResult::fatally_failed() const` + +Returns true if and only if the test part fatally failed. + +##### failed {#TestPartResult::failed} + +`bool TestPartResult::failed() const` + +Returns true if and only if the test part failed. + +### TestProperty {#TestProperty} + +`::testing::TestProperty` + +A copyable object representing a user-specified test property which can be +output as a key/value string pair. + +#### Public Methods {#TestProperty-public} + +##### key {#key} + +`const char* key() const` + +Gets the user-supplied key. + +##### value {#value} + +`const char* value() const` + +Gets the user-supplied value. + +##### SetValue {#SetValue} + +`void SetValue(const std::string& new_value)` + +Sets a new value, overriding the previous one. + +### TestResult {#TestResult} + +`::testing::TestResult` + +Contains information about the result of a single test. + +`TestResult` is not copyable. + +#### Public Methods {#TestResult-public} + +##### total_part_count {#TestResult::total_part_count} + +`int TestResult::total_part_count() const` + +Gets the number of all test parts. This is the sum of the number of successful +test parts and the number of failed test parts. + +##### test_property_count {#TestResult::test_property_count} + +`int TestResult::test_property_count() const` + +Returns the number of test properties. + +##### Passed {#TestResult::Passed} + +`bool TestResult::Passed() const` + +Returns true if and only if the test passed (i.e. no test part failed). + +##### Skipped {#TestResult::Skipped} + +`bool TestResult::Skipped() const` + +Returns true if and only if the test was skipped. + +##### Failed {#TestResult::Failed} + +`bool TestResult::Failed() const` + +Returns true if and only if the test failed. + +##### HasFatalFailure {#TestResult::HasFatalFailure} + +`bool TestResult::HasFatalFailure() const` + +Returns true if and only if the test fatally failed. + +##### HasNonfatalFailure {#TestResult::HasNonfatalFailure} + +`bool TestResult::HasNonfatalFailure() const` + +Returns true if and only if the test has a non-fatal failure. + +##### elapsed_time {#TestResult::elapsed_time} + +`TimeInMillis TestResult::elapsed_time() const` + +Returns the elapsed time, in milliseconds. + +##### start_timestamp {#TestResult::start_timestamp} + +`TimeInMillis TestResult::start_timestamp() const` + +Gets the time of the test case start, in ms from the start of the UNIX epoch. + +##### GetTestPartResult {#TestResult::GetTestPartResult} + +`const TestPartResult& TestResult::GetTestPartResult(int i) const` + +Returns the [`TestPartResult`](#TestPartResult) for the `i`-th test part result +among all the results. `i` can range from 0 to `total_part_count() - 1`. If `i` +is not in that range, aborts the program. + +##### GetTestProperty {#TestResult::GetTestProperty} + +`const TestProperty& TestResult::GetTestProperty(int i) const` + +Returns the [`TestProperty`](#TestProperty) object for the `i`-th test property. +`i` can range from 0 to `test_property_count() - 1`. If `i` is not in that +range, aborts the program. + +### TimeInMillis {#TimeInMillis} + +`::testing::TimeInMillis` + +An integer type representing time in milliseconds. + +### Types {#Types} + +`::testing::Types` + +Represents a list of types for use in typed tests and type-parameterized tests. + +The template argument `T...` can be any number of types, for example: + +``` +::testing::Types +``` + +See [Typed Tests](../advanced.md#typed-tests) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### WithParamInterface {#WithParamInterface} + +`::testing::WithParamInterface` + +The pure interface class that all value-parameterized tests inherit from. + +A value-parameterized test fixture class must inherit from both [`Test`](#Test) +and `WithParamInterface`. In most cases that just means inheriting from +[`TestWithParam`](#TestWithParam), but more complicated test hierarchies may +need to inherit from `Test` and `WithParamInterface` at different levels. + +This interface defines the type alias `ParamType` for the parameter type `T` and +has support for accessing the test parameter value via the `GetParam()` method: + +``` +static const ParamType& GetParam() +``` + +For more information, see +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +## Functions + +GoogleTest defines the following functions to help with writing and running +tests. + +### InitGoogleTest {#InitGoogleTest} + +`void ::testing::InitGoogleTest(int* argc, char** argv)` \ +`void ::testing::InitGoogleTest(int* argc, wchar_t** argv)` \ +`void ::testing::InitGoogleTest()` + +Initializes GoogleTest. This must be called before calling +[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line +for the flags that GoogleTest recognizes. Whenever a GoogleTest flag is seen, it +is removed from `argv`, and `*argc` is decremented. + +No value is returned. Instead, the GoogleTest flag variables are updated. + +The `InitGoogleTest(int* argc, wchar_t** argv)` overload can be used in Windows +programs compiled in `UNICODE` mode. + +The argument-less `InitGoogleTest()` overload can be used on Arduino/embedded +platforms where there is no `argc`/`argv`. + +### AddGlobalTestEnvironment {#AddGlobalTestEnvironment} + +`Environment* ::testing::AddGlobalTestEnvironment(Environment* env)` + +Adds a test environment to the test program. Must be called before +[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is called. See +[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down) for +more information. + +See also [`Environment`](#Environment). + +### RegisterTest {#RegisterTest} + +```cpp +template +TestInfo* ::testing::RegisterTest(const char* test_suite_name, const char* test_name, + const char* type_param, const char* value_param, + const char* file, int line, Factory factory) +``` + +Dynamically registers a test with the framework. + +The `factory` argument is a factory callable (move-constructible) object or +function pointer that creates a new instance of the `Test` object. It handles +ownership to the caller. The signature of the callable is `Fixture*()`, where +`Fixture` is the test fixture class for the test. All tests registered with the +same `test_suite_name` must return the same fixture type. This is checked at +runtime. + +The framework will infer the fixture class from the factory and will call the +`SetUpTestSuite` and `TearDownTestSuite` methods for it. + +Must be called before [`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is invoked, otherwise +behavior is undefined. + +See +[Registering tests programmatically](../advanced.md#registering-tests-programmatically) +for more information. + +### RUN_ALL_TESTS {#RUN_ALL_TESTS} + +`int RUN_ALL_TESTS()` + +Use this function in `main()` to run all tests. It returns `0` if all tests are +successful, or `1` otherwise. + +`RUN_ALL_TESTS()` should be invoked after the command line has been parsed by +[`InitGoogleTest()`](#InitGoogleTest). + +This function was formerly a macro; thus, it is in the global namespace and has +an all-caps name. + +### AssertionSuccess {#AssertionSuccess} + +`AssertionResult ::testing::AssertionSuccess()` + +Creates a successful assertion result. See +[`AssertionResult`](#AssertionResult). + +### AssertionFailure {#AssertionFailure} + +`AssertionResult ::testing::AssertionFailure()` + +Creates a failed assertion result. Use the `<<` operator to store a failure +message: + +```cpp +::testing::AssertionFailure() << "My failure message"; +``` + +See [`AssertionResult`](#AssertionResult). + +### StaticAssertTypeEq {#StaticAssertTypeEq} + +`::testing::StaticAssertTypeEq()` + +Compile-time assertion for type equality. Compiles if and only if `T1` and `T2` +are the same type. The value it returns is irrelevant. + +See [Type Assertions](../advanced.md#type-assertions) for more information. + +### PrintToString {#PrintToString} + +`std::string ::testing::PrintToString(x)` + +Prints any value `x` using GoogleTest's value printer. + +See +[Teaching GoogleTest How to Print Your Values](../advanced.md#teaching-googletest-how-to-print-your-values) +for more information. + +### PrintToStringParamName {#PrintToStringParamName} + +`std::string ::testing::PrintToStringParamName(TestParamInfo& info)` + +A built-in parameterized test name generator which returns the result of +[`PrintToString`](#PrintToString) called on `info.param`. Does not work when the +test parameter is a `std::string` or C string. See +[Specifying Names for Value-Parameterized Test Parameters](../advanced.md#specifying-names-for-value-parameterized-test-parameters) +for more information. + +See also [`TestParamInfo`](#TestParamInfo) and +[`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P). diff --git a/third_party/googletest/docs/samples.md b/third_party/googletest/docs/samples.md new file mode 100644 index 0000000..2d97ca5 --- /dev/null +++ b/third_party/googletest/docs/samples.md @@ -0,0 +1,22 @@ +# Googletest Samples + +If you're like us, you'd like to look at +[googletest samples.](https://github.com/google/googletest/tree/master/googletest/samples) +The sample directory has a number of well-commented samples showing how to use a +variety of googletest features. + +* Sample #1 shows the basic steps of using googletest to test C++ functions. +* Sample #2 shows a more complex unit test for a class with multiple member + functions. +* Sample #3 uses a test fixture. +* Sample #4 teaches you how to use googletest and `googletest.h` together to + get the best of both libraries. +* Sample #5 puts shared testing logic in a base test fixture, and reuses it in + derived fixtures. +* Sample #6 demonstrates type-parameterized tests. +* Sample #7 teaches the basics of value-parameterized tests. +* Sample #8 shows using `Combine()` in value-parameterized tests. +* Sample #9 shows use of the listener API to modify Google Test's console + output and the use of its reflection API to inspect test results. +* Sample #10 shows use of the listener API to implement a primitive memory + leak checker. diff --git a/third_party/googletest/googlemock/CMakeLists.txt b/third_party/googletest/googlemock/CMakeLists.txt new file mode 100644 index 0000000..5c1f0da --- /dev/null +++ b/third_party/googletest/googlemock/CMakeLists.txt @@ -0,0 +1,218 @@ +######################################################################## +# Note: CMake support is community-based. The maintainers do not use CMake +# internally. +# +# CMake build script for Google Mock. +# +# To run the tests for Google Mock itself on Linux, use 'make test' or +# ctest. You can select which tests to run using 'ctest -R regex'. +# For more options, run 'ctest --help'. + +option(gmock_build_tests "Build all of Google Mock's own tests." OFF) + +# A directory to find Google Test sources. +if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/gtest/CMakeLists.txt") + set(gtest_dir gtest) +else() + set(gtest_dir ../googletest) +endif() + +# Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build(). +include("${gtest_dir}/cmake/hermetic_build.cmake" OPTIONAL) + +if (COMMAND pre_project_set_up_hermetic_build) + # Google Test also calls hermetic setup functions from add_subdirectory, + # although its changes will not affect things at the current scope. + pre_project_set_up_hermetic_build() +endif() + +######################################################################## +# +# Project-wide settings + +# Name of the project. +# +# CMake files in this project can refer to the root source directory +# as ${gmock_SOURCE_DIR} and to the root binary directory as +# ${gmock_BINARY_DIR}. +# Language "C" is required for find_package(Threads). +cmake_minimum_required(VERSION 3.5) +cmake_policy(SET CMP0048 NEW) +project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) + +if (COMMAND set_up_hermetic_build) + set_up_hermetic_build() +endif() + +# Instructs CMake to process Google Test's CMakeLists.txt and add its +# targets to the current scope. We are placing Google Test's binary +# directory in a subdirectory of our own as VC compilation may break +# if they are the same (the default). +add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/${gtest_dir}") + + +# These commands only run if this is the main project +if(CMAKE_PROJECT_NAME STREQUAL "gmock" OR CMAKE_PROJECT_NAME STREQUAL "googletest-distribution") + # BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to + # make it prominent in the GUI. + option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF) +else() + mark_as_advanced(gmock_build_tests) +endif() + +# Although Google Test's CMakeLists.txt calls this function, the +# changes there don't affect the current scope. Therefore we have to +# call it again here. +config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake + +# Adds Google Mock's and Google Test's header directories to the search path. +set(gmock_build_include_dirs + "${gmock_SOURCE_DIR}/include" + "${gmock_SOURCE_DIR}" + "${gtest_SOURCE_DIR}/include" + # This directory is needed to build directly from Google Test sources. + "${gtest_SOURCE_DIR}") +include_directories(${gmock_build_include_dirs}) + +######################################################################## +# +# Defines the gmock & gmock_main libraries. User tests should link +# with one of them. + +# Google Mock libraries. We build them using more strict warnings than what +# are used for other targets, to ensure that Google Mock can be compiled by +# a user aggressive about warnings. +if (MSVC) + cxx_library(gmock + "${cxx_strict}" + "${gtest_dir}/src/gtest-all.cc" + src/gmock-all.cc) + + cxx_library(gmock_main + "${cxx_strict}" + "${gtest_dir}/src/gtest-all.cc" + src/gmock-all.cc + src/gmock_main.cc) +else() + cxx_library(gmock "${cxx_strict}" src/gmock-all.cc) + target_link_libraries(gmock PUBLIC gtest) + set_target_properties(gmock PROPERTIES VERSION ${GOOGLETEST_VERSION}) + cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc) + target_link_libraries(gmock_main PUBLIC gmock) + set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION}) +endif() +# If the CMake version supports it, attach header directory information +# to the targets for when we are part of a parent build (ie being pulled +# in via add_subdirectory() rather than being a standalone build). +if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11") + string(REPLACE ";" "$" dirs "${gmock_build_include_dirs}") + target_include_directories(gmock SYSTEM INTERFACE + "$" + "$/${CMAKE_INSTALL_INCLUDEDIR}>") + target_include_directories(gmock_main SYSTEM INTERFACE + "$" + "$/${CMAKE_INSTALL_INCLUDEDIR}>") +endif() + +######################################################################## +# +# Install rules +install_project(gmock gmock_main) + +######################################################################## +# +# Google Mock's own tests. +# +# You can skip this section if you aren't interested in testing +# Google Mock itself. +# +# The tests are not built by default. To build them, set the +# gmock_build_tests option to ON. You can do it by running ccmake +# or specifying the -Dgmock_build_tests=ON flag when running cmake. + +if (gmock_build_tests) + # This must be set in the root directory for the tests to be run by + # 'make test' or ctest. + enable_testing() + + if (MINGW OR CYGWIN) + if (CMAKE_VERSION VERSION_LESS "2.8.12") + add_compile_options("-Wa,-mbig-obj") + else() + add_definitions("-Wa,-mbig-obj") + endif() + endif() + + ############################################################ + # C++ tests built with standard compiler flags. + + cxx_test(gmock-actions_test gmock_main) + cxx_test(gmock-cardinalities_test gmock_main) + cxx_test(gmock_ex_test gmock_main) + cxx_test(gmock-function-mocker_test gmock_main) + cxx_test(gmock-internal-utils_test gmock_main) + cxx_test(gmock-matchers-arithmetic_test gmock_main) + cxx_test(gmock-matchers-comparisons_test gmock_main) + cxx_test(gmock-matchers-containers_test gmock_main) + cxx_test(gmock-matchers-misc_test gmock_main) + cxx_test(gmock-more-actions_test gmock_main) + cxx_test(gmock-nice-strict_test gmock_main) + cxx_test(gmock-port_test gmock_main) + cxx_test(gmock-spec-builders_test gmock_main) + cxx_test(gmock_link_test gmock_main test/gmock_link2_test.cc) + cxx_test(gmock_test gmock_main) + + if (DEFINED GTEST_HAS_PTHREAD) + cxx_test(gmock_stress_test gmock) + endif() + + # gmock_all_test is commented to save time building and running tests. + # Uncomment if necessary. + # cxx_test(gmock_all_test gmock_main) + + ############################################################ + # C++ tests built with non-standard compiler flags. + + if (MSVC) + cxx_library(gmock_main_no_exception "${cxx_no_exception}" + "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) + + cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" + "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) + + else() + cxx_library(gmock_main_no_exception "${cxx_no_exception}" src/gmock_main.cc) + target_link_libraries(gmock_main_no_exception PUBLIC gmock) + + cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" src/gmock_main.cc) + target_link_libraries(gmock_main_no_rtti PUBLIC gmock) + endif() + cxx_test_with_flags(gmock-more-actions_no_exception_test "${cxx_no_exception}" + gmock_main_no_exception test/gmock-more-actions_test.cc) + + cxx_test_with_flags(gmock_no_rtti_test "${cxx_no_rtti}" + gmock_main_no_rtti test/gmock-spec-builders_test.cc) + + cxx_shared_library(shared_gmock_main "${cxx_default}" + "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) + + # Tests that a binary can be built with Google Mock as a shared library. On + # some system configurations, it may not possible to run the binary without + # knowing more details about the system configurations. We do not try to run + # this binary. To get a more robust shared library coverage, configure with + # -DBUILD_SHARED_LIBS=ON. + cxx_executable_with_flags(shared_gmock_test_ "${cxx_default}" + shared_gmock_main test/gmock-spec-builders_test.cc) + set_target_properties(shared_gmock_test_ + PROPERTIES + COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1") + + ############################################################ + # Python tests. + + cxx_executable(gmock_leak_test_ test gmock_main) + py_test(gmock_leak_test) + + cxx_executable(gmock_output_test_ test gmock) + py_test(gmock_output_test) +endif() diff --git a/third_party/googletest/googlemock/README.md b/third_party/googletest/googlemock/README.md new file mode 100644 index 0000000..7da6065 --- /dev/null +++ b/third_party/googletest/googlemock/README.md @@ -0,0 +1,40 @@ +# Googletest Mocking (gMock) Framework + +### Overview + +Google's framework for writing and using C++ mock classes. It can help you +derive better designs of your system and write better tests. + +It is inspired by: + +* [jMock](http://www.jmock.org/) +* [EasyMock](http://www.easymock.org/) +* [Hamcrest](http://code.google.com/p/hamcrest/) + +It is designed with C++'s specifics in mind. + +gMock: + +- Provides a declarative syntax for defining mocks. +- Can define partial (hybrid) mocks, which are a cross of real and mock + objects. +- Handles functions of arbitrary types and overloaded functions. +- Comes with a rich set of matchers for validating function arguments. +- Uses an intuitive syntax for controlling the behavior of a mock. +- Does automatic verification of expectations (no record-and-replay needed). +- Allows arbitrary (partial) ordering constraints on function calls to be + expressed. +- Lets a user extend it by defining new matchers and actions. +- Does not use exceptions. +- Is easy to learn and use. + +Details and examples can be found here: + +* [gMock for Dummies](https://google.github.io/googletest/gmock_for_dummies.html) +* [Legacy gMock FAQ](https://google.github.io/googletest/gmock_faq.html) +* [gMock Cookbook](https://google.github.io/googletest/gmock_cook_book.html) +* [gMock Cheat Sheet](https://google.github.io/googletest/gmock_cheat_sheet.html) + +GoogleMock is a part of +[GoogleTest C++ testing framework](http://github.com/google/googletest/) and a +subject to the same requirements. diff --git a/third_party/googletest/googlemock/cmake/gmock.pc.in b/third_party/googletest/googlemock/cmake/gmock.pc.in new file mode 100644 index 0000000..23c67b5 --- /dev/null +++ b/third_party/googletest/googlemock/cmake/gmock.pc.in @@ -0,0 +1,10 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: gmock +Description: GoogleMock (without main() function) +Version: @PROJECT_VERSION@ +URL: https://github.com/google/googletest +Requires: gtest = @PROJECT_VERSION@ +Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ diff --git a/third_party/googletest/googlemock/cmake/gmock_main.pc.in b/third_party/googletest/googlemock/cmake/gmock_main.pc.in new file mode 100644 index 0000000..66ffea7 --- /dev/null +++ b/third_party/googletest/googlemock/cmake/gmock_main.pc.in @@ -0,0 +1,10 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: gmock_main +Description: GoogleMock (with main() function) +Version: @PROJECT_VERSION@ +URL: https://github.com/google/googletest +Requires: gmock = @PROJECT_VERSION@ +Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ diff --git a/third_party/googletest/googlemock/docs/README.md b/third_party/googletest/googlemock/docs/README.md new file mode 100644 index 0000000..1bc57b7 --- /dev/null +++ b/third_party/googletest/googlemock/docs/README.md @@ -0,0 +1,4 @@ +# Content Moved + +We are working on updates to the GoogleTest documentation, which has moved to +the top-level [docs](../../docs) directory. diff --git a/third_party/googletest/googlemock/include/gmock/gmock-actions.h b/third_party/googletest/googlemock/include/gmock/gmock-actions.h new file mode 100644 index 0000000..c785ad8 --- /dev/null +++ b/third_party/googletest/googlemock/include/gmock/gmock-actions.h @@ -0,0 +1,2298 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// The ACTION* family of macros can be used in a namespace scope to +// define custom actions easily. The syntax: +// +// ACTION(name) { statements; } +// +// will define an action with the given name that executes the +// statements. The value returned by the statements will be used as +// the return value of the action. Inside the statements, you can +// refer to the K-th (0-based) argument of the mock function by +// 'argK', and refer to its type by 'argK_type'. For example: +// +// ACTION(IncrementArg1) { +// arg1_type temp = arg1; +// return ++(*temp); +// } +// +// allows you to write +// +// ...WillOnce(IncrementArg1()); +// +// You can also refer to the entire argument tuple and its type by +// 'args' and 'args_type', and refer to the mock function type and its +// return type by 'function_type' and 'return_type'. +// +// Note that you don't need to specify the types of the mock function +// arguments. However rest assured that your code is still type-safe: +// you'll get a compiler error if *arg1 doesn't support the ++ +// operator, or if the type of ++(*arg1) isn't compatible with the +// mock function's return type, for example. +// +// Sometimes you'll want to parameterize the action. For that you can use +// another macro: +// +// ACTION_P(name, param_name) { statements; } +// +// For example: +// +// ACTION_P(Add, n) { return arg0 + n; } +// +// will allow you to write: +// +// ...WillOnce(Add(5)); +// +// Note that you don't need to provide the type of the parameter +// either. If you need to reference the type of a parameter named +// 'foo', you can write 'foo_type'. For example, in the body of +// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type +// of 'n'. +// +// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support +// multi-parameter actions. +// +// For the purpose of typing, you can view +// +// ACTION_Pk(Foo, p1, ..., pk) { ... } +// +// as shorthand for +// +// template +// FooActionPk Foo(p1_type p1, ..., pk_type pk) { ... } +// +// In particular, you can provide the template type arguments +// explicitly when invoking Foo(), as in Foo(5, false); +// although usually you can rely on the compiler to infer the types +// for you automatically. You can assign the result of expression +// Foo(p1, ..., pk) to a variable of type FooActionPk. This can be useful when composing actions. +// +// You can also overload actions with different numbers of parameters: +// +// ACTION_P(Plus, a) { ... } +// ACTION_P2(Plus, a, b) { ... } +// +// While it's tempting to always use the ACTION* macros when defining +// a new action, you should also consider implementing ActionInterface +// or using MakePolymorphicAction() instead, especially if you need to +// use the action a lot. While these approaches require more work, +// they give you more control on the types of the mock function +// arguments and the action parameters, which in general leads to +// better compiler error messages that pay off in the long run. They +// also allow overloading actions based on parameter types (as opposed +// to just based on the number of parameters). +// +// CAVEAT: +// +// ACTION*() can only be used in a namespace scope as templates cannot be +// declared inside of a local class. +// Users can, however, define any local functors (e.g. a lambda) that +// can be used as actions. +// +// MORE INFORMATION: +// +// To learn more about using these macros, please search for 'ACTION' on +// https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ + +#ifndef _WIN32_WCE +#include +#endif + +#include +#include +#include +#include +#include +#include +#include + +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-port.h" +#include "gmock/internal/gmock-pp.h" + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4100) +#endif + +namespace testing { + +// To implement an action Foo, define: +// 1. a class FooAction that implements the ActionInterface interface, and +// 2. a factory function that creates an Action object from a +// const FooAction*. +// +// The two-level delegation design follows that of Matcher, providing +// consistency for extension developers. It also eases ownership +// management as Action objects can now be copied like plain values. + +namespace internal { + +// BuiltInDefaultValueGetter::Get() returns a +// default-constructed T value. BuiltInDefaultValueGetter::Get() crashes with an error. +// +// This primary template is used when kDefaultConstructible is true. +template +struct BuiltInDefaultValueGetter { + static T Get() { return T(); } +}; +template +struct BuiltInDefaultValueGetter { + static T Get() { + Assert(false, __FILE__, __LINE__, + "Default action undefined for the function return type."); + return internal::Invalid(); + // The above statement will never be reached, but is required in + // order for this function to compile. + } +}; + +// BuiltInDefaultValue::Get() returns the "built-in" default value +// for type T, which is NULL when T is a raw pointer type, 0 when T is +// a numeric type, false when T is bool, or "" when T is string or +// std::string. In addition, in C++11 and above, it turns a +// default-constructed T value if T is default constructible. For any +// other type T, the built-in default T value is undefined, and the +// function will abort the process. +template +class BuiltInDefaultValue { + public: + // This function returns true if and only if type T has a built-in default + // value. + static bool Exists() { return ::std::is_default_constructible::value; } + + static T Get() { + return BuiltInDefaultValueGetter< + T, ::std::is_default_constructible::value>::Get(); + } +}; + +// This partial specialization says that we use the same built-in +// default value for T and const T. +template +class BuiltInDefaultValue { + public: + static bool Exists() { return BuiltInDefaultValue::Exists(); } + static T Get() { return BuiltInDefaultValue::Get(); } +}; + +// This partial specialization defines the default values for pointer +// types. +template +class BuiltInDefaultValue { + public: + static bool Exists() { return true; } + static T* Get() { return nullptr; } +}; + +// The following specializations define the default values for +// specific types we care about. +#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ + template <> \ + class BuiltInDefaultValue { \ + public: \ + static bool Exists() { return true; } \ + static type Get() { return value; } \ + } + +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, ""); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0'); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0'); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0'); + +// There's no need for a default action for signed wchar_t, as that +// type is the same as wchar_t for gcc, and invalid for MSVC. +// +// There's also no need for a default action for unsigned wchar_t, as +// that type is the same as unsigned int for gcc, and invalid for +// MSVC. +#if GMOCK_WCHAR_T_IS_NATIVE_ +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT +#endif + +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); + +#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ + +// Partial implementations of metaprogramming types from the standard library +// not available in C++11. + +template +struct negation + // NOLINTNEXTLINE + : std::integral_constant {}; + +// Base case: with zero predicates the answer is always true. +template +struct conjunction : std::true_type {}; + +// With a single predicate, the answer is that predicate. +template +struct conjunction : P1 {}; + +// With multiple predicates the answer is the first predicate if that is false, +// and we recurse otherwise. +template +struct conjunction + : std::conditional, P1>::type {}; + +template +struct disjunction : std::false_type {}; + +template +struct disjunction : P1 {}; + +template +struct disjunction + // NOLINTNEXTLINE + : std::conditional, P1>::type {}; + +template +using void_t = void; + +// Detects whether an expression of type `From` can be implicitly converted to +// `To` according to [conv]. In C++17, [conv]/3 defines this as follows: +// +// An expression e can be implicitly converted to a type T if and only if +// the declaration T t=e; is well-formed, for some invented temporary +// variable t ([dcl.init]). +// +// [conv]/2 implies we can use function argument passing to detect whether this +// initialization is valid. +// +// Note that this is distinct from is_convertible, which requires this be valid: +// +// To test() { +// return declval(); +// } +// +// In particular, is_convertible doesn't give the correct answer when `To` and +// `From` are the same non-moveable type since `declval` will be an rvalue +// reference, defeating the guaranteed copy elision that would otherwise make +// this function work. +// +// REQUIRES: `From` is not cv void. +template +struct is_implicitly_convertible { + private: + // A function that accepts a parameter of type T. This can be called with type + // U successfully only if U is implicitly convertible to T. + template + static void Accept(T); + + // A function that creates a value of type T. + template + static T Make(); + + // An overload be selected when implicit conversion from T to To is possible. + template (Make()))> + static std::true_type TestImplicitConversion(int); + + // A fallback overload selected in all other cases. + template + static std::false_type TestImplicitConversion(...); + + public: + using type = decltype(TestImplicitConversion(0)); + static constexpr bool value = type::value; +}; + +// Like std::invoke_result_t from C++17, but works only for objects with call +// operators (not e.g. member function pointers, which we don't need specific +// support for in OnceAction because std::function deals with them). +template +using call_result_t = decltype(std::declval()(std::declval()...)); + +template +struct is_callable_r_impl : std::false_type {}; + +// Specialize the struct for those template arguments where call_result_t is +// well-formed. When it's not, the generic template above is chosen, resulting +// in std::false_type. +template +struct is_callable_r_impl>, R, F, Args...> + : std::conditional< + std::is_void::value, // + std::true_type, // + is_implicitly_convertible, R>>::type {}; + +// Like std::is_invocable_r from C++17, but works only for objects with call +// operators. See the note on call_result_t. +template +using is_callable_r = is_callable_r_impl; + +// Like std::as_const from C++17. +template +typename std::add_const::type& as_const(T& t) { + return t; +} + +} // namespace internal + +// Specialized for function types below. +template +class OnceAction; + +// An action that can only be used once. +// +// This is accepted by WillOnce, which doesn't require the underlying action to +// be copy-constructible (only move-constructible), and promises to invoke it as +// an rvalue reference. This allows the action to work with move-only types like +// std::move_only_function in a type-safe manner. +// +// For example: +// +// // Assume we have some API that needs to accept a unique pointer to some +// // non-copyable object Foo. +// void AcceptUniquePointer(std::unique_ptr foo); +// +// // We can define an action that provides a Foo to that API. Because It +// // has to give away its unique pointer, it must not be called more than +// // once, so its call operator is &&-qualified. +// struct ProvideFoo { +// std::unique_ptr foo; +// +// void operator()() && { +// AcceptUniquePointer(std::move(Foo)); +// } +// }; +// +// // This action can be used with WillOnce. +// EXPECT_CALL(mock, Call) +// .WillOnce(ProvideFoo{std::make_unique(...)}); +// +// // But a call to WillRepeatedly will fail to compile. This is correct, +// // since the action cannot correctly be used repeatedly. +// EXPECT_CALL(mock, Call) +// .WillRepeatedly(ProvideFoo{std::make_unique(...)}); +// +// A less-contrived example would be an action that returns an arbitrary type, +// whose &&-qualified call operator is capable of dealing with move-only types. +template +class OnceAction final { + private: + // True iff we can use the given callable type (or lvalue reference) directly + // via StdFunctionAdaptor. + template + using IsDirectlyCompatible = internal::conjunction< + // It must be possible to capture the callable in StdFunctionAdaptor. + std::is_constructible::type, Callable>, + // The callable must be compatible with our signature. + internal::is_callable_r::type, + Args...>>; + + // True iff we can use the given callable type via StdFunctionAdaptor once we + // ignore incoming arguments. + template + using IsCompatibleAfterIgnoringArguments = internal::conjunction< + // It must be possible to capture the callable in a lambda. + std::is_constructible::type, Callable>, + // The callable must be invocable with zero arguments, returning something + // convertible to Result. + internal::is_callable_r::type>>; + + public: + // Construct from a callable that is directly compatible with our mocked + // signature: it accepts our function type's arguments and returns something + // convertible to our result type. + template ::type>>, + IsDirectlyCompatible> // + ::value, + int>::type = 0> + OnceAction(Callable&& callable) // NOLINT + : function_(StdFunctionAdaptor::type>( + {}, std::forward(callable))) {} + + // As above, but for a callable that ignores the mocked function's arguments. + template ::type>>, + // Exclude callables for which the overload above works. + // We'd rather provide the arguments if possible. + internal::negation>, + IsCompatibleAfterIgnoringArguments>::value, + int>::type = 0> + OnceAction(Callable&& callable) // NOLINT + // Call the constructor above with a callable + // that ignores the input arguments. + : OnceAction(IgnoreIncomingArguments::type>{ + std::forward(callable)}) {} + + // We are naturally copyable because we store only an std::function, but + // semantically we should not be copyable. + OnceAction(const OnceAction&) = delete; + OnceAction& operator=(const OnceAction&) = delete; + OnceAction(OnceAction&&) = default; + + // Invoke the underlying action callable with which we were constructed, + // handing it the supplied arguments. + Result Call(Args... args) && { + return function_(std::forward(args)...); + } + + private: + // An adaptor that wraps a callable that is compatible with our signature and + // being invoked as an rvalue reference so that it can be used as an + // StdFunctionAdaptor. This throws away type safety, but that's fine because + // this is only used by WillOnce, which we know calls at most once. + // + // Once we have something like std::move_only_function from C++23, we can do + // away with this. + template + class StdFunctionAdaptor final { + public: + // A tag indicating that the (otherwise universal) constructor is accepting + // the callable itself, instead of e.g. stealing calls for the move + // constructor. + struct CallableTag final {}; + + template + explicit StdFunctionAdaptor(CallableTag, F&& callable) + : callable_(std::make_shared(std::forward(callable))) {} + + // Rather than explicitly returning Result, we return whatever the wrapped + // callable returns. This allows for compatibility with existing uses like + // the following, when the mocked function returns void: + // + // EXPECT_CALL(mock_fn_, Call) + // .WillOnce([&] { + // [...] + // return 0; + // }); + // + // Such a callable can be turned into std::function. If we use an + // explicit return type of Result here then it *doesn't* work with + // std::function, because we'll get a "void function should not return a + // value" error. + // + // We need not worry about incompatible result types because the SFINAE on + // OnceAction already checks this for us. std::is_invocable_r_v itself makes + // the same allowance for void result types. + template + internal::call_result_t operator()( + ArgRefs&&... args) const { + return std::move(*callable_)(std::forward(args)...); + } + + private: + // We must put the callable on the heap so that we are copyable, which + // std::function needs. + std::shared_ptr callable_; + }; + + // An adaptor that makes a callable that accepts zero arguments callable with + // our mocked arguments. + template + struct IgnoreIncomingArguments { + internal::call_result_t operator()(Args&&...) { + return std::move(callable)(); + } + + Callable callable; + }; + + std::function function_; +}; + +// When an unexpected function call is encountered, Google Mock will +// let it return a default value if the user has specified one for its +// return type, or if the return type has a built-in default value; +// otherwise Google Mock won't know what value to return and will have +// to abort the process. +// +// The DefaultValue class allows a user to specify the +// default value for a type T that is both copyable and publicly +// destructible (i.e. anything that can be used as a function return +// type). The usage is: +// +// // Sets the default value for type T to be foo. +// DefaultValue::Set(foo); +template +class DefaultValue { + public: + // Sets the default value for type T; requires T to be + // copy-constructable and have a public destructor. + static void Set(T x) { + delete producer_; + producer_ = new FixedValueProducer(x); + } + + // Provides a factory function to be called to generate the default value. + // This method can be used even if T is only move-constructible, but it is not + // limited to that case. + typedef T (*FactoryFunction)(); + static void SetFactory(FactoryFunction factory) { + delete producer_; + producer_ = new FactoryValueProducer(factory); + } + + // Unsets the default value for type T. + static void Clear() { + delete producer_; + producer_ = nullptr; + } + + // Returns true if and only if the user has set the default value for type T. + static bool IsSet() { return producer_ != nullptr; } + + // Returns true if T has a default return value set by the user or there + // exists a built-in default value. + static bool Exists() { + return IsSet() || internal::BuiltInDefaultValue::Exists(); + } + + // Returns the default value for type T if the user has set one; + // otherwise returns the built-in default value. Requires that Exists() + // is true, which ensures that the return value is well-defined. + static T Get() { + return producer_ == nullptr ? internal::BuiltInDefaultValue::Get() + : producer_->Produce(); + } + + private: + class ValueProducer { + public: + virtual ~ValueProducer() {} + virtual T Produce() = 0; + }; + + class FixedValueProducer : public ValueProducer { + public: + explicit FixedValueProducer(T value) : value_(value) {} + T Produce() override { return value_; } + + private: + const T value_; + FixedValueProducer(const FixedValueProducer&) = delete; + FixedValueProducer& operator=(const FixedValueProducer&) = delete; + }; + + class FactoryValueProducer : public ValueProducer { + public: + explicit FactoryValueProducer(FactoryFunction factory) + : factory_(factory) {} + T Produce() override { return factory_(); } + + private: + const FactoryFunction factory_; + FactoryValueProducer(const FactoryValueProducer&) = delete; + FactoryValueProducer& operator=(const FactoryValueProducer&) = delete; + }; + + static ValueProducer* producer_; +}; + +// This partial specialization allows a user to set default values for +// reference types. +template +class DefaultValue { + public: + // Sets the default value for type T&. + static void Set(T& x) { // NOLINT + address_ = &x; + } + + // Unsets the default value for type T&. + static void Clear() { address_ = nullptr; } + + // Returns true if and only if the user has set the default value for type T&. + static bool IsSet() { return address_ != nullptr; } + + // Returns true if T has a default return value set by the user or there + // exists a built-in default value. + static bool Exists() { + return IsSet() || internal::BuiltInDefaultValue::Exists(); + } + + // Returns the default value for type T& if the user has set one; + // otherwise returns the built-in default value if there is one; + // otherwise aborts the process. + static T& Get() { + return address_ == nullptr ? internal::BuiltInDefaultValue::Get() + : *address_; + } + + private: + static T* address_; +}; + +// This specialization allows DefaultValue::Get() to +// compile. +template <> +class DefaultValue { + public: + static bool Exists() { return true; } + static void Get() {} +}; + +// Points to the user-set default value for type T. +template +typename DefaultValue::ValueProducer* DefaultValue::producer_ = nullptr; + +// Points to the user-set default value for type T&. +template +T* DefaultValue::address_ = nullptr; + +// Implement this interface to define an action for function type F. +template +class ActionInterface { + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + ActionInterface() {} + virtual ~ActionInterface() {} + + // Performs the action. This method is not const, as in general an + // action can have side effects and be stateful. For example, a + // get-the-next-element-from-the-collection action will need to + // remember the current element. + virtual Result Perform(const ArgumentTuple& args) = 0; + + private: + ActionInterface(const ActionInterface&) = delete; + ActionInterface& operator=(const ActionInterface&) = delete; +}; + +template +class Action; + +// An Action is a copyable and IMMUTABLE (except by assignment) +// object that represents an action to be taken when a mock function of type +// R(Args...) is called. The implementation of Action is just a +// std::shared_ptr to const ActionInterface. Don't inherit from Action! You +// can view an object implementing ActionInterface as a concrete action +// (including its current state), and an Action object as a handle to it. +template +class Action { + private: + using F = R(Args...); + + // Adapter class to allow constructing Action from a legacy ActionInterface. + // New code should create Actions from functors instead. + struct ActionAdapter { + // Adapter must be copyable to satisfy std::function requirements. + ::std::shared_ptr> impl_; + + template + typename internal::Function::Result operator()(InArgs&&... args) { + return impl_->Perform( + ::std::forward_as_tuple(::std::forward(args)...)); + } + }; + + template + using IsCompatibleFunctor = std::is_constructible, G>; + + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + // Constructs a null Action. Needed for storing Action objects in + // STL containers. + Action() {} + + // Construct an Action from a specified callable. + // This cannot take std::function directly, because then Action would not be + // directly constructible from lambda (it would require two conversions). + template < + typename G, + typename = typename std::enable_if, std::is_constructible, + G>>::value>::type> + Action(G&& fun) { // NOLINT + Init(::std::forward(fun), IsCompatibleFunctor()); + } + + // Constructs an Action from its implementation. + explicit Action(ActionInterface* impl) + : fun_(ActionAdapter{::std::shared_ptr>(impl)}) {} + + // This constructor allows us to turn an Action object into an + // Action, as long as F's arguments can be implicitly converted + // to Func's and Func's return type can be implicitly converted to F's. + template + Action(const Action& action) // NOLINT + : fun_(action.fun_) {} + + // Returns true if and only if this is the DoDefault() action. + bool IsDoDefault() const { return fun_ == nullptr; } + + // Performs the action. Note that this method is const even though + // the corresponding method in ActionInterface is not. The reason + // is that a const Action means that it cannot be re-bound to + // another concrete action, not that the concrete action it binds to + // cannot change state. (Think of the difference between a const + // pointer and a pointer to const.) + Result Perform(ArgumentTuple args) const { + if (IsDoDefault()) { + internal::IllegalDoDefault(__FILE__, __LINE__); + } + return internal::Apply(fun_, ::std::move(args)); + } + + // An action can be used as a OnceAction, since it's obviously safe to call it + // once. + operator OnceAction() const { // NOLINT + // Return a OnceAction-compatible callable that calls Perform with the + // arguments it is provided. We could instead just return fun_, but then + // we'd need to handle the IsDoDefault() case separately. + struct OA { + Action action; + + R operator()(Args... args) && { + return action.Perform( + std::forward_as_tuple(std::forward(args)...)); + } + }; + + return OA{*this}; + } + + private: + template + friend class Action; + + template + void Init(G&& g, ::std::true_type) { + fun_ = ::std::forward(g); + } + + template + void Init(G&& g, ::std::false_type) { + fun_ = IgnoreArgs::type>{::std::forward(g)}; + } + + template + struct IgnoreArgs { + template + Result operator()(const InArgs&...) const { + return function_impl(); + } + + FunctionImpl function_impl; + }; + + // fun_ is an empty function if and only if this is the DoDefault() action. + ::std::function fun_; +}; + +// The PolymorphicAction class template makes it easy to implement a +// polymorphic action (i.e. an action that can be used in mock +// functions of than one type, e.g. Return()). +// +// To define a polymorphic action, a user first provides a COPYABLE +// implementation class that has a Perform() method template: +// +// class FooAction { +// public: +// template +// Result Perform(const ArgumentTuple& args) const { +// // Processes the arguments and returns a result, using +// // std::get(args) to get the N-th (0-based) argument in the tuple. +// } +// ... +// }; +// +// Then the user creates the polymorphic action using +// MakePolymorphicAction(object) where object has type FooAction. See +// the definition of Return(void) and SetArgumentPointee(value) for +// complete examples. +template +class PolymorphicAction { + public: + explicit PolymorphicAction(const Impl& impl) : impl_(impl) {} + + template + operator Action() const { + return Action(new MonomorphicImpl(impl_)); + } + + private: + template + class MonomorphicImpl : public ActionInterface { + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} + + Result Perform(const ArgumentTuple& args) override { + return impl_.template Perform(args); + } + + private: + Impl impl_; + }; + + Impl impl_; +}; + +// Creates an Action from its implementation and returns it. The +// created Action object owns the implementation. +template +Action MakeAction(ActionInterface* impl) { + return Action(impl); +} + +// Creates a polymorphic action from its implementation. This is +// easier to use than the PolymorphicAction constructor as it +// doesn't require you to explicitly write the template argument, e.g. +// +// MakePolymorphicAction(foo); +// vs +// PolymorphicAction(foo); +template +inline PolymorphicAction MakePolymorphicAction(const Impl& impl) { + return PolymorphicAction(impl); +} + +namespace internal { + +// Helper struct to specialize ReturnAction to execute a move instead of a copy +// on return. Useful for move-only types, but could be used on any type. +template +struct ByMoveWrapper { + explicit ByMoveWrapper(T value) : payload(std::move(value)) {} + T payload; +}; + +// The general implementation of Return(R). Specializations follow below. +template +class ReturnAction final { + public: + explicit ReturnAction(R value) : value_(std::move(value)) {} + + template >, // + negation>, // + std::is_convertible, // + std::is_move_constructible>::value>::type> + operator OnceAction() && { // NOLINT + return Impl(std::move(value_)); + } + + template >, // + negation>, // + std::is_convertible, // + std::is_copy_constructible>::value>::type> + operator Action() const { // NOLINT + return Impl(value_); + } + + private: + // Implements the Return(x) action for a mock function that returns type U. + template + class Impl final { + public: + // The constructor used when the return value is allowed to move from the + // input value (i.e. we are converting to OnceAction). + explicit Impl(R&& input_value) + : state_(new State(std::move(input_value))) {} + + // The constructor used when the return value is not allowed to move from + // the input value (i.e. we are converting to Action). + explicit Impl(const R& input_value) : state_(new State(input_value)) {} + + U operator()() && { return std::move(state_->value); } + U operator()() const& { return state_->value; } + + private: + // We put our state on the heap so that the compiler-generated copy/move + // constructors work correctly even when U is a reference-like type. This is + // necessary only because we eagerly create State::value (see the note on + // that symbol for details). If we instead had only the input value as a + // member then the default constructors would work fine. + // + // For example, when R is std::string and U is std::string_view, value is a + // reference to the string backed by input_value. The copy constructor would + // copy both, so that we wind up with a new input_value object (with the + // same contents) and a reference to the *old* input_value object rather + // than the new one. + struct State { + explicit State(const R& input_value_in) + : input_value(input_value_in), + // Make an implicit conversion to Result before initializing the U + // object we store, avoiding calling any explicit constructor of U + // from R. + // + // This simulates the language rules: a function with return type U + // that does `return R()` requires R to be implicitly convertible to + // U, and uses that path for the conversion, even U Result has an + // explicit constructor from R. + value(ImplicitCast_(internal::as_const(input_value))) {} + + // As above, but for the case where we're moving from the ReturnAction + // object because it's being used as a OnceAction. + explicit State(R&& input_value_in) + : input_value(std::move(input_value_in)), + // For the same reason as above we make an implicit conversion to U + // before initializing the value. + // + // Unlike above we provide the input value as an rvalue to the + // implicit conversion because this is a OnceAction: it's fine if it + // wants to consume the input value. + value(ImplicitCast_(std::move(input_value))) {} + + // A copy of the value originally provided by the user. We retain this in + // addition to the value of the mock function's result type below in case + // the latter is a reference-like type. See the std::string_view example + // in the documentation on Return. + R input_value; + + // The value we actually return, as the type returned by the mock function + // itself. + // + // We eagerly initialize this here, rather than lazily doing the implicit + // conversion automatically each time Perform is called, for historical + // reasons: in 2009-11, commit a070cbd91c (Google changelist 13540126) + // made the Action conversion operator eagerly convert the R value to + // U, but without keeping the R alive. This broke the use case discussed + // in the documentation for Return, making reference-like types such as + // std::string_view not safe to use as U where the input type R is a + // value-like type such as std::string. + // + // The example the commit gave was not very clear, nor was the issue + // thread (https://github.com/google/googlemock/issues/86), but it seems + // the worry was about reference-like input types R that flatten to a + // value-like type U when being implicitly converted. An example of this + // is std::vector::reference, which is often a proxy type with an + // reference to the underlying vector: + // + // // Helper method: have the mock function return bools according + // // to the supplied script. + // void SetActions(MockFunction& mock, + // const std::vector& script) { + // for (size_t i = 0; i < script.size(); ++i) { + // EXPECT_CALL(mock, Call(i)).WillOnce(Return(script[i])); + // } + // } + // + // TEST(Foo, Bar) { + // // Set actions using a temporary vector, whose operator[] + // // returns proxy objects that references that will be + // // dangling once the call to SetActions finishes and the + // // vector is destroyed. + // MockFunction mock; + // SetActions(mock, {false, true}); + // + // EXPECT_FALSE(mock.AsStdFunction()(0)); + // EXPECT_TRUE(mock.AsStdFunction()(1)); + // } + // + // This eager conversion helps with a simple case like this, but doesn't + // fully make these types work in general. For example the following still + // uses a dangling reference: + // + // TEST(Foo, Baz) { + // MockFunction()> mock; + // + // // Return the same vector twice, and then the empty vector + // // thereafter. + // auto action = Return(std::initializer_list{ + // "taco", "burrito", + // }); + // + // EXPECT_CALL(mock, Call) + // .WillOnce(action) + // .WillOnce(action) + // .WillRepeatedly(Return(std::vector{})); + // + // EXPECT_THAT(mock.AsStdFunction()(), + // ElementsAre("taco", "burrito")); + // EXPECT_THAT(mock.AsStdFunction()(), + // ElementsAre("taco", "burrito")); + // EXPECT_THAT(mock.AsStdFunction()(), IsEmpty()); + // } + // + U value; + }; + + const std::shared_ptr state_; + }; + + R value_; +}; + +// A specialization of ReturnAction when R is ByMoveWrapper for some T. +// +// This version applies the type system-defeating hack of moving from T even in +// the const call operator, checking at runtime that it isn't called more than +// once, since the user has declared their intent to do so by using ByMove. +template +class ReturnAction> final { + public: + explicit ReturnAction(ByMoveWrapper wrapper) + : state_(new State(std::move(wrapper.payload))) {} + + T operator()() const { + GTEST_CHECK_(!state_->called) + << "A ByMove() action must be performed at most once."; + + state_->called = true; + return std::move(state_->value); + } + + private: + // We store our state on the heap so that we are copyable as required by + // Action, despite the fact that we are stateful and T may not be copyable. + struct State { + explicit State(T&& value_in) : value(std::move(value_in)) {} + + T value; + bool called = false; + }; + + const std::shared_ptr state_; +}; + +// Implements the ReturnNull() action. +class ReturnNullAction { + public: + // Allows ReturnNull() to be used in any pointer-returning function. In C++11 + // this is enforced by returning nullptr, and in non-C++11 by asserting a + // pointer type on compile time. + template + static Result Perform(const ArgumentTuple&) { + return nullptr; + } +}; + +// Implements the Return() action. +class ReturnVoidAction { + public: + // Allows Return() to be used in any void-returning function. + template + static void Perform(const ArgumentTuple&) { + static_assert(std::is_void::value, "Result should be void."); + } +}; + +// Implements the polymorphic ReturnRef(x) action, which can be used +// in any function that returns a reference to the type of x, +// regardless of the argument types. +template +class ReturnRefAction { + public: + // Constructs a ReturnRefAction object from the reference to be returned. + explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT + + // This template type conversion operator allows ReturnRef(x) to be + // used in ANY function that returns a reference to x's type. + template + operator Action() const { + typedef typename Function::Result Result; + // Asserts that the function return type is a reference. This + // catches the user error of using ReturnRef(x) when Return(x) + // should be used, and generates some helpful error message. + static_assert(std::is_reference::value, + "use Return instead of ReturnRef to return a value"); + return Action(new Impl(ref_)); + } + + private: + // Implements the ReturnRef(x) action for a particular function type F. + template + class Impl : public ActionInterface { + public: + typedef typename Function::Result Result; + typedef typename Function::ArgumentTuple ArgumentTuple; + + explicit Impl(T& ref) : ref_(ref) {} // NOLINT + + Result Perform(const ArgumentTuple&) override { return ref_; } + + private: + T& ref_; + }; + + T& ref_; +}; + +// Implements the polymorphic ReturnRefOfCopy(x) action, which can be +// used in any function that returns a reference to the type of x, +// regardless of the argument types. +template +class ReturnRefOfCopyAction { + public: + // Constructs a ReturnRefOfCopyAction object from the reference to + // be returned. + explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT + + // This template type conversion operator allows ReturnRefOfCopy(x) to be + // used in ANY function that returns a reference to x's type. + template + operator Action() const { + typedef typename Function::Result Result; + // Asserts that the function return type is a reference. This + // catches the user error of using ReturnRefOfCopy(x) when Return(x) + // should be used, and generates some helpful error message. + static_assert(std::is_reference::value, + "use Return instead of ReturnRefOfCopy to return a value"); + return Action(new Impl(value_)); + } + + private: + // Implements the ReturnRefOfCopy(x) action for a particular function type F. + template + class Impl : public ActionInterface { + public: + typedef typename Function::Result Result; + typedef typename Function::ArgumentTuple ArgumentTuple; + + explicit Impl(const T& value) : value_(value) {} // NOLINT + + Result Perform(const ArgumentTuple&) override { return value_; } + + private: + T value_; + }; + + const T value_; +}; + +// Implements the polymorphic ReturnRoundRobin(v) action, which can be +// used in any function that returns the element_type of v. +template +class ReturnRoundRobinAction { + public: + explicit ReturnRoundRobinAction(std::vector values) { + GTEST_CHECK_(!values.empty()) + << "ReturnRoundRobin requires at least one element."; + state_->values = std::move(values); + } + + template + T operator()(Args&&...) const { + return state_->Next(); + } + + private: + struct State { + T Next() { + T ret_val = values[i++]; + if (i == values.size()) i = 0; + return ret_val; + } + + std::vector values; + size_t i = 0; + }; + std::shared_ptr state_ = std::make_shared(); +}; + +// Implements the polymorphic DoDefault() action. +class DoDefaultAction { + public: + // This template type conversion operator allows DoDefault() to be + // used in any function. + template + operator Action() const { + return Action(); + } // NOLINT +}; + +// Implements the Assign action to set a given pointer referent to a +// particular value. +template +class AssignAction { + public: + AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {} + + template + void Perform(const ArgumentTuple& /* args */) const { + *ptr_ = value_; + } + + private: + T1* const ptr_; + const T2 value_; +}; + +#if !GTEST_OS_WINDOWS_MOBILE + +// Implements the SetErrnoAndReturn action to simulate return from +// various system calls and libc functions. +template +class SetErrnoAndReturnAction { + public: + SetErrnoAndReturnAction(int errno_value, T result) + : errno_(errno_value), result_(result) {} + template + Result Perform(const ArgumentTuple& /* args */) const { + errno = errno_; + return result_; + } + + private: + const int errno_; + const T result_; +}; + +#endif // !GTEST_OS_WINDOWS_MOBILE + +// Implements the SetArgumentPointee(x) action for any function +// whose N-th argument (0-based) is a pointer to x's type. +template +struct SetArgumentPointeeAction { + A value; + + template + void operator()(const Args&... args) const { + *::std::get(std::tie(args...)) = value; + } +}; + +// Implements the Invoke(object_ptr, &Class::Method) action. +template +struct InvokeMethodAction { + Class* const obj_ptr; + const MethodPtr method_ptr; + + template + auto operator()(Args&&... args) const + -> decltype((obj_ptr->*method_ptr)(std::forward(args)...)) { + return (obj_ptr->*method_ptr)(std::forward(args)...); + } +}; + +// Implements the InvokeWithoutArgs(f) action. The template argument +// FunctionImpl is the implementation type of f, which can be either a +// function pointer or a functor. InvokeWithoutArgs(f) can be used as an +// Action as long as f's type is compatible with F. +template +struct InvokeWithoutArgsAction { + FunctionImpl function_impl; + + // Allows InvokeWithoutArgs(f) to be used as any action whose type is + // compatible with f. + template + auto operator()(const Args&...) -> decltype(function_impl()) { + return function_impl(); + } +}; + +// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action. +template +struct InvokeMethodWithoutArgsAction { + Class* const obj_ptr; + const MethodPtr method_ptr; + + using ReturnType = + decltype((std::declval()->*std::declval())()); + + template + ReturnType operator()(const Args&...) const { + return (obj_ptr->*method_ptr)(); + } +}; + +// Implements the IgnoreResult(action) action. +template +class IgnoreResultAction { + public: + explicit IgnoreResultAction(const A& action) : action_(action) {} + + template + operator Action() const { + // Assert statement belongs here because this is the best place to verify + // conditions on F. It produces the clearest error messages + // in most compilers. + // Impl really belongs in this scope as a local class but can't + // because MSVC produces duplicate symbols in different translation units + // in this case. Until MS fixes that bug we put Impl into the class scope + // and put the typedef both here (for use in assert statement) and + // in the Impl class. But both definitions must be the same. + typedef typename internal::Function::Result Result; + + // Asserts at compile time that F returns void. + static_assert(std::is_void::value, "Result type should be void."); + + return Action(new Impl(action_)); + } + + private: + template + class Impl : public ActionInterface { + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + explicit Impl(const A& action) : action_(action) {} + + void Perform(const ArgumentTuple& args) override { + // Performs the action and ignores its result. + action_.Perform(args); + } + + private: + // Type OriginalFunction is the same as F except that its return + // type is IgnoredValue. + typedef + typename internal::Function::MakeResultIgnoredValue OriginalFunction; + + const Action action_; + }; + + const A action_; +}; + +template +struct WithArgsAction { + InnerAction inner_action; + + // The signature of the function as seen by the inner action, given an out + // action with the given result and argument types. + template + using InnerSignature = + R(typename std::tuple_element>::type...); + + // Rather than a call operator, we must define conversion operators to + // particular action types. This is necessary for embedded actions like + // DoDefault(), which rely on an action conversion operators rather than + // providing a call operator because even with a particular set of arguments + // they don't have a fixed return type. + + template >::type...)>>::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + struct OA { + OnceAction> inner_action; + + R operator()(Args&&... args) && { + return std::move(inner_action) + .Call(std::get( + std::forward_as_tuple(std::forward(args)...))...); + } + }; + + return OA{std::move(inner_action)}; + } + + template >::type...)>>::value, + int>::type = 0> + operator Action() const { // NOLINT + Action> converted(inner_action); + + return [converted](Args&&... args) -> R { + return converted.Perform(std::forward_as_tuple( + std::get(std::forward_as_tuple(std::forward(args)...))...)); + }; + } +}; + +template +class DoAllAction; + +// Base case: only a single action. +template +class DoAllAction { + public: + struct UserConstructorTag {}; + + template + explicit DoAllAction(UserConstructorTag, T&& action) + : final_action_(std::forward(action)) {} + + // Rather than a call operator, we must define conversion operators to + // particular action types. This is necessary for embedded actions like + // DoDefault(), which rely on an action conversion operators rather than + // providing a call operator because even with a particular set of arguments + // they don't have a fixed return type. + + template >::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + return std::move(final_action_); + } + + template < + typename R, typename... Args, + typename std::enable_if< + std::is_convertible>::value, + int>::type = 0> + operator Action() const { // NOLINT + return final_action_; + } + + private: + FinalAction final_action_; +}; + +// Recursive case: support N actions by calling the initial action and then +// calling through to the base class containing N-1 actions. +template +class DoAllAction + : private DoAllAction { + private: + using Base = DoAllAction; + + // The type of reference that should be provided to an initial action for a + // mocked function parameter of type T. + // + // There are two quirks here: + // + // * Unlike most forwarding functions, we pass scalars through by value. + // This isn't strictly necessary because an lvalue reference would work + // fine too and be consistent with other non-reference types, but it's + // perhaps less surprising. + // + // For example if the mocked function has signature void(int), then it + // might seem surprising for the user's initial action to need to be + // convertible to Action. This is perhaps less + // surprising for a non-scalar type where there may be a performance + // impact, or it might even be impossible, to pass by value. + // + // * More surprisingly, `const T&` is often not a const reference type. + // By the reference collapsing rules in C++17 [dcl.ref]/6, if T refers to + // U& or U&& for some non-scalar type U, then InitialActionArgType is + // U&. In other words, we may hand over a non-const reference. + // + // So for example, given some non-scalar type Obj we have the following + // mappings: + // + // T InitialActionArgType + // ------- ----------------------- + // Obj const Obj& + // Obj& Obj& + // Obj&& Obj& + // const Obj const Obj& + // const Obj& const Obj& + // const Obj&& const Obj& + // + // In other words, the initial actions get a mutable view of an non-scalar + // argument if and only if the mock function itself accepts a non-const + // reference type. They are never given an rvalue reference to an + // non-scalar type. + // + // This situation makes sense if you imagine use with a matcher that is + // designed to write through a reference. For example, if the caller wants + // to fill in a reference argument and then return a canned value: + // + // EXPECT_CALL(mock, Call) + // .WillOnce(DoAll(SetArgReferee<0>(17), Return(19))); + // + template + using InitialActionArgType = + typename std::conditional::value, T, const T&>::type; + + public: + struct UserConstructorTag {}; + + template + explicit DoAllAction(UserConstructorTag, T&& initial_action, + U&&... other_actions) + : Base({}, std::forward(other_actions)...), + initial_action_(std::forward(initial_action)) {} + + template ...)>>, + std::is_convertible>>::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + // Return an action that first calls the initial action with arguments + // filtered through InitialActionArgType, then forwards arguments directly + // to the base class to deal with the remaining actions. + struct OA { + OnceAction...)> initial_action; + OnceAction remaining_actions; + + R operator()(Args... args) && { + std::move(initial_action) + .Call(static_cast>(args)...); + + return std::move(remaining_actions).Call(std::forward(args)...); + } + }; + + return OA{ + std::move(initial_action_), + std::move(static_cast(*this)), + }; + } + + template < + typename R, typename... Args, + typename std::enable_if< + conjunction< + // Both the initial action and the rest must support conversion to + // Action. + std::is_convertible...)>>, + std::is_convertible>>::value, + int>::type = 0> + operator Action() const { // NOLINT + // Return an action that first calls the initial action with arguments + // filtered through InitialActionArgType, then forwards arguments directly + // to the base class to deal with the remaining actions. + struct OA { + Action...)> initial_action; + Action remaining_actions; + + R operator()(Args... args) const { + initial_action.Perform(std::forward_as_tuple( + static_cast>(args)...)); + + return remaining_actions.Perform( + std::forward_as_tuple(std::forward(args)...)); + } + }; + + return OA{ + initial_action_, + static_cast(*this), + }; + } + + private: + InitialAction initial_action_; +}; + +template +struct ReturnNewAction { + T* operator()() const { + return internal::Apply( + [](const Params&... unpacked_params) { + return new T(unpacked_params...); + }, + params); + } + std::tuple params; +}; + +template +struct ReturnArgAction { + template ::type> + auto operator()(Args&&... args) const -> decltype(std::get( + std::forward_as_tuple(std::forward(args)...))) { + return std::get(std::forward_as_tuple(std::forward(args)...)); + } +}; + +template +struct SaveArgAction { + Ptr pointer; + + template + void operator()(const Args&... args) const { + *pointer = std::get(std::tie(args...)); + } +}; + +template +struct SaveArgPointeeAction { + Ptr pointer; + + template + void operator()(const Args&... args) const { + *pointer = *std::get(std::tie(args...)); + } +}; + +template +struct SetArgRefereeAction { + T value; + + template + void operator()(Args&&... args) const { + using argk_type = + typename ::std::tuple_element>::type; + static_assert(std::is_lvalue_reference::value, + "Argument must be a reference type."); + std::get(std::tie(args...)) = value; + } +}; + +template +struct SetArrayArgumentAction { + I1 first; + I2 last; + + template + void operator()(const Args&... args) const { + auto value = std::get(std::tie(args...)); + for (auto it = first; it != last; ++it, (void)++value) { + *value = *it; + } + } +}; + +template +struct DeleteArgAction { + template + void operator()(const Args&... args) const { + delete std::get(std::tie(args...)); + } +}; + +template +struct ReturnPointeeAction { + Ptr pointer; + template + auto operator()(const Args&...) const -> decltype(*pointer) { + return *pointer; + } +}; + +#if GTEST_HAS_EXCEPTIONS +template +struct ThrowAction { + T exception; + // We use a conversion operator to adapt to any return type. + template + operator Action() const { // NOLINT + T copy = exception; + return [copy](Args...) -> R { throw copy; }; + } +}; +#endif // GTEST_HAS_EXCEPTIONS + +} // namespace internal + +// An Unused object can be implicitly constructed from ANY value. +// This is handy when defining actions that ignore some or all of the +// mock function arguments. For example, given +// +// MOCK_METHOD3(Foo, double(const string& label, double x, double y)); +// MOCK_METHOD3(Bar, double(int index, double x, double y)); +// +// instead of +// +// double DistanceToOriginWithLabel(const string& label, double x, double y) { +// return sqrt(x*x + y*y); +// } +// double DistanceToOriginWithIndex(int index, double x, double y) { +// return sqrt(x*x + y*y); +// } +// ... +// EXPECT_CALL(mock, Foo("abc", _, _)) +// .WillOnce(Invoke(DistanceToOriginWithLabel)); +// EXPECT_CALL(mock, Bar(5, _, _)) +// .WillOnce(Invoke(DistanceToOriginWithIndex)); +// +// you could write +// +// // We can declare any uninteresting argument as Unused. +// double DistanceToOrigin(Unused, double x, double y) { +// return sqrt(x*x + y*y); +// } +// ... +// EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin)); +// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); +typedef internal::IgnoredValue Unused; + +// Creates an action that does actions a1, a2, ..., sequentially in +// each invocation. All but the last action will have a readonly view of the +// arguments. +template +internal::DoAllAction::type...> DoAll( + Action&&... action) { + return internal::DoAllAction::type...>( + {}, std::forward(action)...); +} + +// WithArg(an_action) creates an action that passes the k-th +// (0-based) argument of the mock function to an_action and performs +// it. It adapts an action accepting one argument to one that accepts +// multiple arguments. For convenience, we also provide +// WithArgs(an_action) (defined below) as a synonym. +template +internal::WithArgsAction::type, k> WithArg( + InnerAction&& action) { + return {std::forward(action)}; +} + +// WithArgs(an_action) creates an action that passes +// the selected arguments of the mock function to an_action and +// performs it. It serves as an adaptor between actions with +// different argument lists. +template +internal::WithArgsAction::type, k, ks...> +WithArgs(InnerAction&& action) { + return {std::forward(action)}; +} + +// WithoutArgs(inner_action) can be used in a mock function with a +// non-empty argument list to perform inner_action, which takes no +// argument. In other words, it adapts an action accepting no +// argument to one that accepts (and ignores) arguments. +template +internal::WithArgsAction::type> WithoutArgs( + InnerAction&& action) { + return {std::forward(action)}; +} + +// Creates an action that returns a value. +// +// The returned type can be used with a mock function returning a non-void, +// non-reference type U as follows: +// +// * If R is convertible to U and U is move-constructible, then the action can +// be used with WillOnce. +// +// * If const R& is convertible to U and U is copy-constructible, then the +// action can be used with both WillOnce and WillRepeatedly. +// +// The mock expectation contains the R value from which the U return value is +// constructed (a move/copy of the argument to Return). This means that the R +// value will survive at least until the mock object's expectations are cleared +// or the mock object is destroyed, meaning that U can safely be a +// reference-like type such as std::string_view: +// +// // The mock function returns a view of a copy of the string fed to +// // Return. The view is valid even after the action is performed. +// MockFunction mock; +// EXPECT_CALL(mock, Call).WillOnce(Return(std::string("taco"))); +// const std::string_view result = mock.AsStdFunction()(); +// EXPECT_EQ("taco", result); +// +template +internal::ReturnAction Return(R value) { + return internal::ReturnAction(std::move(value)); +} + +// Creates an action that returns NULL. +inline PolymorphicAction ReturnNull() { + return MakePolymorphicAction(internal::ReturnNullAction()); +} + +// Creates an action that returns from a void function. +inline PolymorphicAction Return() { + return MakePolymorphicAction(internal::ReturnVoidAction()); +} + +// Creates an action that returns the reference to a variable. +template +inline internal::ReturnRefAction ReturnRef(R& x) { // NOLINT + return internal::ReturnRefAction(x); +} + +// Prevent using ReturnRef on reference to temporary. +template +internal::ReturnRefAction ReturnRef(R&&) = delete; + +// Creates an action that returns the reference to a copy of the +// argument. The copy is created when the action is constructed and +// lives as long as the action. +template +inline internal::ReturnRefOfCopyAction ReturnRefOfCopy(const R& x) { + return internal::ReturnRefOfCopyAction(x); +} + +// DEPRECATED: use Return(x) directly with WillOnce. +// +// Modifies the parent action (a Return() action) to perform a move of the +// argument instead of a copy. +// Return(ByMove()) actions can only be executed once and will assert this +// invariant. +template +internal::ByMoveWrapper ByMove(R x) { + return internal::ByMoveWrapper(std::move(x)); +} + +// Creates an action that returns an element of `vals`. Calling this action will +// repeatedly return the next value from `vals` until it reaches the end and +// will restart from the beginning. +template +internal::ReturnRoundRobinAction ReturnRoundRobin(std::vector vals) { + return internal::ReturnRoundRobinAction(std::move(vals)); +} + +// Creates an action that returns an element of `vals`. Calling this action will +// repeatedly return the next value from `vals` until it reaches the end and +// will restart from the beginning. +template +internal::ReturnRoundRobinAction ReturnRoundRobin( + std::initializer_list vals) { + return internal::ReturnRoundRobinAction(std::vector(vals)); +} + +// Creates an action that does the default action for the give mock function. +inline internal::DoDefaultAction DoDefault() { + return internal::DoDefaultAction(); +} + +// Creates an action that sets the variable pointed by the N-th +// (0-based) function argument to 'value'. +template +internal::SetArgumentPointeeAction SetArgPointee(T value) { + return {std::move(value)}; +} + +// The following version is DEPRECATED. +template +internal::SetArgumentPointeeAction SetArgumentPointee(T value) { + return {std::move(value)}; +} + +// Creates an action that sets a pointer referent to a given value. +template +PolymorphicAction> Assign(T1* ptr, T2 val) { + return MakePolymorphicAction(internal::AssignAction(ptr, val)); +} + +#if !GTEST_OS_WINDOWS_MOBILE + +// Creates an action that sets errno and returns the appropriate error. +template +PolymorphicAction> SetErrnoAndReturn( + int errval, T result) { + return MakePolymorphicAction( + internal::SetErrnoAndReturnAction(errval, result)); +} + +#endif // !GTEST_OS_WINDOWS_MOBILE + +// Various overloads for Invoke(). + +// Legacy function. +// Actions can now be implicitly constructed from callables. No need to create +// wrapper objects. +// This function exists for backwards compatibility. +template +typename std::decay::type Invoke(FunctionImpl&& function_impl) { + return std::forward(function_impl); +} + +// Creates an action that invokes the given method on the given object +// with the mock function's arguments. +template +internal::InvokeMethodAction Invoke(Class* obj_ptr, + MethodPtr method_ptr) { + return {obj_ptr, method_ptr}; +} + +// Creates an action that invokes 'function_impl' with no argument. +template +internal::InvokeWithoutArgsAction::type> +InvokeWithoutArgs(FunctionImpl function_impl) { + return {std::move(function_impl)}; +} + +// Creates an action that invokes the given method on the given object +// with no argument. +template +internal::InvokeMethodWithoutArgsAction InvokeWithoutArgs( + Class* obj_ptr, MethodPtr method_ptr) { + return {obj_ptr, method_ptr}; +} + +// Creates an action that performs an_action and throws away its +// result. In other words, it changes the return type of an_action to +// void. an_action MUST NOT return void, or the code won't compile. +template +inline internal::IgnoreResultAction IgnoreResult(const A& an_action) { + return internal::IgnoreResultAction(an_action); +} + +// Creates a reference wrapper for the given L-value. If necessary, +// you can explicitly specify the type of the reference. For example, +// suppose 'derived' is an object of type Derived, ByRef(derived) +// would wrap a Derived&. If you want to wrap a const Base& instead, +// where Base is a base class of Derived, just write: +// +// ByRef(derived) +// +// N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper. +// However, it may still be used for consistency with ByMove(). +template +inline ::std::reference_wrapper ByRef(T& l_value) { // NOLINT + return ::std::reference_wrapper(l_value); +} + +// The ReturnNew(a1, a2, ..., a_k) action returns a pointer to a new +// instance of type T, constructed on the heap with constructor arguments +// a1, a2, ..., and a_k. The caller assumes ownership of the returned value. +template +internal::ReturnNewAction::type...> ReturnNew( + Params&&... params) { + return {std::forward_as_tuple(std::forward(params)...)}; +} + +// Action ReturnArg() returns the k-th argument of the mock function. +template +internal::ReturnArgAction ReturnArg() { + return {}; +} + +// Action SaveArg(pointer) saves the k-th (0-based) argument of the +// mock function to *pointer. +template +internal::SaveArgAction SaveArg(Ptr pointer) { + return {pointer}; +} + +// Action SaveArgPointee(pointer) saves the value pointed to +// by the k-th (0-based) argument of the mock function to *pointer. +template +internal::SaveArgPointeeAction SaveArgPointee(Ptr pointer) { + return {pointer}; +} + +// Action SetArgReferee(value) assigns 'value' to the variable +// referenced by the k-th (0-based) argument of the mock function. +template +internal::SetArgRefereeAction::type> SetArgReferee( + T&& value) { + return {std::forward(value)}; +} + +// Action SetArrayArgument(first, last) copies the elements in +// source range [first, last) to the array pointed to by the k-th +// (0-based) argument, which can be either a pointer or an +// iterator. The action does not take ownership of the elements in the +// source range. +template +internal::SetArrayArgumentAction SetArrayArgument(I1 first, + I2 last) { + return {first, last}; +} + +// Action DeleteArg() deletes the k-th (0-based) argument of the mock +// function. +template +internal::DeleteArgAction DeleteArg() { + return {}; +} + +// This action returns the value pointed to by 'pointer'. +template +internal::ReturnPointeeAction ReturnPointee(Ptr pointer) { + return {pointer}; +} + +// Action Throw(exception) can be used in a mock function of any type +// to throw the given exception. Any copyable value can be thrown. +#if GTEST_HAS_EXCEPTIONS +template +internal::ThrowAction::type> Throw(T&& exception) { + return {std::forward(exception)}; +} +#endif // GTEST_HAS_EXCEPTIONS + +namespace internal { + +// A macro from the ACTION* family (defined later in gmock-generated-actions.h) +// defines an action that can be used in a mock function. Typically, +// these actions only care about a subset of the arguments of the mock +// function. For example, if such an action only uses the second +// argument, it can be used in any mock function that takes >= 2 +// arguments where the type of the second argument is compatible. +// +// Therefore, the action implementation must be prepared to take more +// arguments than it needs. The ExcessiveArg type is used to +// represent those excessive arguments. In order to keep the compiler +// error messages tractable, we define it in the testing namespace +// instead of testing::internal. However, this is an INTERNAL TYPE +// and subject to change without notice, so a user MUST NOT USE THIS +// TYPE DIRECTLY. +struct ExcessiveArg {}; + +// Builds an implementation of an Action<> for some particular signature, using +// a class defined by an ACTION* macro. +template +struct ActionImpl; + +template +struct ImplBase { + struct Holder { + // Allows each copy of the Action<> to get to the Impl. + explicit operator const Impl&() const { return *ptr; } + std::shared_ptr ptr; + }; + using type = typename std::conditional::value, + Impl, Holder>::type; +}; + +template +struct ActionImpl : ImplBase::type { + using Base = typename ImplBase::type; + using function_type = R(Args...); + using args_type = std::tuple; + + ActionImpl() = default; // Only defined if appropriate for Base. + explicit ActionImpl(std::shared_ptr impl) : Base{std::move(impl)} {} + + R operator()(Args&&... arg) const { + static constexpr size_t kMaxArgs = + sizeof...(Args) <= 10 ? sizeof...(Args) : 10; + return Apply(MakeIndexSequence{}, + MakeIndexSequence<10 - kMaxArgs>{}, + args_type{std::forward(arg)...}); + } + + template + R Apply(IndexSequence, IndexSequence, + const args_type& args) const { + // Impl need not be specific to the signature of action being implemented; + // only the implementing function body needs to have all of the specific + // types instantiated. Up to 10 of the args that are provided by the + // args_type get passed, followed by a dummy of unspecified type for the + // remainder up to 10 explicit args. + static constexpr ExcessiveArg kExcessArg{}; + return static_cast(*this) + .template gmock_PerformImpl< + /*function_type=*/function_type, /*return_type=*/R, + /*args_type=*/args_type, + /*argN_type=*/ + typename std::tuple_element::type...>( + /*args=*/args, std::get(args)..., + ((void)excess_id, kExcessArg)...); + } +}; + +// Stores a default-constructed Impl as part of the Action<>'s +// std::function<>. The Impl should be trivial to copy. +template +::testing::Action MakeAction() { + return ::testing::Action(ActionImpl()); +} + +// Stores just the one given instance of Impl. +template +::testing::Action MakeAction(std::shared_ptr impl) { + return ::testing::Action(ActionImpl(std::move(impl))); +} + +#define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \ + , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_ +#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \ + const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \ + GMOCK_INTERNAL_ARG_UNUSED, , 10) + +#define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i +#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \ + const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10) + +#define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type +#define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \ + GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10)) + +#define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type +#define GMOCK_ACTION_TYPENAME_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params)) + +#define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type +#define GMOCK_ACTION_TYPE_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params)) + +#define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \ + , param##_type gmock_p##i +#define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params)) + +#define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \ + , std::forward(gmock_p##i) +#define GMOCK_ACTION_GVALUE_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params)) + +#define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \ + , param(::std::forward(gmock_p##i)) +#define GMOCK_ACTION_INIT_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params)) + +#define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param; +#define GMOCK_ACTION_FIELD_PARAMS_(params) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params) + +#define GMOCK_INTERNAL_ACTION(name, full_name, params) \ + template \ + class full_name { \ + public: \ + explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ + : impl_(std::make_shared( \ + GMOCK_ACTION_GVALUE_PARAMS_(params))) {} \ + full_name(const full_name&) = default; \ + full_name(full_name&&) noexcept = default; \ + template \ + operator ::testing::Action() const { \ + return ::testing::internal::MakeAction(impl_); \ + } \ + \ + private: \ + class gmock_Impl { \ + public: \ + explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ + : GMOCK_ACTION_INIT_PARAMS_(params) {} \ + template \ + return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ + GMOCK_ACTION_FIELD_PARAMS_(params) \ + }; \ + std::shared_ptr impl_; \ + }; \ + template \ + inline full_name name( \ + GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \ + template \ + inline full_name name( \ + GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \ + return full_name( \ + GMOCK_ACTION_GVALUE_PARAMS_(params)); \ + } \ + template \ + template \ + return_type \ + full_name::gmock_Impl::gmock_PerformImpl( \ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +} // namespace internal + +// Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored. +#define ACTION(name) \ + class name##Action { \ + public: \ + explicit name##Action() noexcept {} \ + name##Action(const name##Action&) noexcept {} \ + template \ + operator ::testing::Action() const { \ + return ::testing::internal::MakeAction(); \ + } \ + \ + private: \ + class gmock_Impl { \ + public: \ + template \ + return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ + }; \ + }; \ + inline name##Action name() GTEST_MUST_USE_RESULT_; \ + inline name##Action name() { return name##Action(); } \ + template \ + return_type name##Action::gmock_Impl::gmock_PerformImpl( \ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__)) + +#define ACTION_P2(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__)) + +#define ACTION_P3(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__)) + +#define ACTION_P4(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__)) + +#define ACTION_P5(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__)) + +#define ACTION_P6(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__)) + +#define ACTION_P7(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__)) + +#define ACTION_P8(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__)) + +#define ACTION_P9(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__)) + +#define ACTION_P10(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__)) + +} // namespace testing + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ diff --git a/third_party/googletest/googlemock/include/gmock/gmock-cardinalities.h b/third_party/googletest/googlemock/include/gmock/gmock-cardinalities.h new file mode 100644 index 0000000..b6ab648 --- /dev/null +++ b/third_party/googletest/googlemock/include/gmock/gmock-cardinalities.h @@ -0,0 +1,159 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements some commonly used cardinalities. More +// cardinalities can be defined by the user implementing the +// CardinalityInterface interface if necessary. + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ + +#include + +#include +#include // NOLINT + +#include "gmock/internal/gmock-port.h" +#include "gtest/gtest.h" + +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ +/* class A needs to have dll-interface to be used by clients of class B */) + +namespace testing { + +// To implement a cardinality Foo, define: +// 1. a class FooCardinality that implements the +// CardinalityInterface interface, and +// 2. a factory function that creates a Cardinality object from a +// const FooCardinality*. +// +// The two-level delegation design follows that of Matcher, providing +// consistency for extension developers. It also eases ownership +// management as Cardinality objects can now be copied like plain values. + +// The implementation of a cardinality. +class CardinalityInterface { + public: + virtual ~CardinalityInterface() {} + + // Conservative estimate on the lower/upper bound of the number of + // calls allowed. + virtual int ConservativeLowerBound() const { return 0; } + virtual int ConservativeUpperBound() const { return INT_MAX; } + + // Returns true if and only if call_count calls will satisfy this + // cardinality. + virtual bool IsSatisfiedByCallCount(int call_count) const = 0; + + // Returns true if and only if call_count calls will saturate this + // cardinality. + virtual bool IsSaturatedByCallCount(int call_count) const = 0; + + // Describes self to an ostream. + virtual void DescribeTo(::std::ostream* os) const = 0; +}; + +// A Cardinality is a copyable and IMMUTABLE (except by assignment) +// object that specifies how many times a mock function is expected to +// be called. The implementation of Cardinality is just a std::shared_ptr +// to const CardinalityInterface. Don't inherit from Cardinality! +class GTEST_API_ Cardinality { + public: + // Constructs a null cardinality. Needed for storing Cardinality + // objects in STL containers. + Cardinality() {} + + // Constructs a Cardinality from its implementation. + explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {} + + // Conservative estimate on the lower/upper bound of the number of + // calls allowed. + int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); } + int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); } + + // Returns true if and only if call_count calls will satisfy this + // cardinality. + bool IsSatisfiedByCallCount(int call_count) const { + return impl_->IsSatisfiedByCallCount(call_count); + } + + // Returns true if and only if call_count calls will saturate this + // cardinality. + bool IsSaturatedByCallCount(int call_count) const { + return impl_->IsSaturatedByCallCount(call_count); + } + + // Returns true if and only if call_count calls will over-saturate this + // cardinality, i.e. exceed the maximum number of allowed calls. + bool IsOverSaturatedByCallCount(int call_count) const { + return impl_->IsSaturatedByCallCount(call_count) && + !impl_->IsSatisfiedByCallCount(call_count); + } + + // Describes self to an ostream + void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } + + // Describes the given actual call count to an ostream. + static void DescribeActualCallCountTo(int actual_call_count, + ::std::ostream* os); + + private: + std::shared_ptr impl_; +}; + +// Creates a cardinality that allows at least n calls. +GTEST_API_ Cardinality AtLeast(int n); + +// Creates a cardinality that allows at most n calls. +GTEST_API_ Cardinality AtMost(int n); + +// Creates a cardinality that allows any number of calls. +GTEST_API_ Cardinality AnyNumber(); + +// Creates a cardinality that allows between min and max calls. +GTEST_API_ Cardinality Between(int min, int max); + +// Creates a cardinality that allows exactly n calls. +GTEST_API_ Cardinality Exactly(int n); + +// Creates a cardinality from its implementation. +inline Cardinality MakeCardinality(const CardinalityInterface* c) { + return Cardinality(c); +} + +} // namespace testing + +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 + +#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ diff --git a/third_party/googletest/googlemock/include/gmock/gmock-function-mocker.h b/third_party/googletest/googlemock/include/gmock/gmock-function-mocker.h new file mode 100644 index 0000000..f565d98 --- /dev/null +++ b/third_party/googletest/googlemock/include/gmock/gmock-function-mocker.h @@ -0,0 +1,514 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements MOCK_METHOD. + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT +#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT + +#include // IWYU pragma: keep +#include // IWYU pragma: keep + +#include "gmock/gmock-spec-builders.h" +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-pp.h" + +namespace testing { +namespace internal { +template +using identity_t = T; + +template +struct ThisRefAdjuster { + template + using AdjustT = typename std::conditional< + std::is_const::type>::value, + typename std::conditional::value, + const T&, const T&&>::type, + typename std::conditional::value, T&, + T&&>::type>::type; + + template + static AdjustT Adjust(const MockType& mock) { + return static_cast>(const_cast(mock)); + } +}; + +constexpr bool PrefixOf(const char* a, const char* b) { + return *a == 0 || (*a == *b && internal::PrefixOf(a + 1, b + 1)); +} + +template +constexpr bool StartsWith(const char (&prefix)[N], const char (&str)[M]) { + return N <= M && internal::PrefixOf(prefix, str); +} + +template +constexpr bool EndsWith(const char (&suffix)[N], const char (&str)[M]) { + return N <= M && internal::PrefixOf(suffix, str + M - N); +} + +template +constexpr bool Equals(const char (&a)[N], const char (&b)[M]) { + return N == M && internal::PrefixOf(a, b); +} + +template +constexpr bool ValidateSpec(const char (&spec)[N]) { + return internal::Equals("const", spec) || + internal::Equals("override", spec) || + internal::Equals("final", spec) || + internal::Equals("noexcept", spec) || + (internal::StartsWith("noexcept(", spec) && + internal::EndsWith(")", spec)) || + internal::Equals("ref(&)", spec) || + internal::Equals("ref(&&)", spec) || + (internal::StartsWith("Calltype(", spec) && + internal::EndsWith(")", spec)); +} + +} // namespace internal + +// The style guide prohibits "using" statements in a namespace scope +// inside a header file. However, the FunctionMocker class template +// is meant to be defined in the ::testing namespace. The following +// line is just a trick for working around a bug in MSVC 8.0, which +// cannot handle it if we define FunctionMocker in ::testing. +using internal::FunctionMocker; +} // namespace testing + +#define MOCK_METHOD(...) \ + GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_2(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \ + GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ()) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \ + GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \ + GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \ + GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ + GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \ + GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ + GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ + GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \ + GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \ + GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \ + GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Spec), \ + GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \ + (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args))) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_6(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_7(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_WRONG_ARITY(...) \ + static_assert( \ + false, \ + "MOCK_METHOD must be called with 3 or 4 arguments. _Ret, " \ + "_MethodName, _Args and optionally _Spec. _Args and _Spec must be " \ + "enclosed in parentheses. If _Ret is a type with unprotected commas, " \ + "it must also be enclosed in parentheses.") + +#define GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Tuple) \ + static_assert( \ + GMOCK_PP_IS_ENCLOSED_PARENS(_Tuple), \ + GMOCK_PP_STRINGIZE(_Tuple) " should be enclosed in parentheses.") + +#define GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(_N, ...) \ + static_assert( \ + std::is_function<__VA_ARGS__>::value, \ + "Signature must be a function type, maybe return type contains " \ + "unprotected comma."); \ + static_assert( \ + ::testing::tuple_size::ArgumentTuple>::value == _N, \ + "This method does not take " GMOCK_PP_STRINGIZE( \ + _N) " arguments. Parenthesize all types with unprotected commas.") + +#define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec) + +#define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \ + _Override, _Final, _NoexceptSpec, \ + _CallType, _RefSpec, _Signature) \ + typename ::testing::internal::Function::Result \ + GMOCK_INTERNAL_EXPAND(_CallType) \ + _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \ + GMOCK_PP_IF(_Constness, const, ) _RefSpec _NoexceptSpec \ + GMOCK_PP_IF(_Override, override, ) GMOCK_PP_IF(_Final, final, ) { \ + GMOCK_MOCKER_(_N, _Constness, _MethodName) \ + .SetOwnerAndName(this, #_MethodName); \ + return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ + .Invoke(GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, _Signature, _N)); \ + } \ + ::testing::MockSpec gmock_##_MethodName( \ + GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \ + GMOCK_PP_IF(_Constness, const, ) _RefSpec { \ + GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \ + return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ + .With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \ + } \ + ::testing::MockSpec gmock_##_MethodName( \ + const ::testing::internal::WithoutMatchers&, \ + GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \ + GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _RefSpec _NoexceptSpec { \ + return ::testing::internal::ThisRefAdjuster::Adjust(*this) \ + .gmock_##_MethodName(GMOCK_PP_REPEAT( \ + GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \ + } \ + mutable ::testing::FunctionMocker \ + GMOCK_MOCKER_(_N, _Constness, _MethodName) + +#define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__ + +// Valid modifiers. +#define GMOCK_INTERNAL_HAS_CONST(_Tuple) \ + GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple)) + +#define GMOCK_INTERNAL_HAS_OVERRIDE(_Tuple) \ + GMOCK_PP_HAS_COMMA( \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_OVERRIDE, ~, _Tuple)) + +#define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \ + GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple)) + +#define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple) + +#define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \ + GMOCK_PP_IF( \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \ + _elem, ) + +#define GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE, ~, _Tuple) + +#define GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE(_i, _, _elem) \ + GMOCK_PP_IF( \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem)), \ + GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), ) + +#define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple) + +#define GMOCK_INTERNAL_REF_SPEC_IF_REF(_i, _, _elem) \ + GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \ + GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), ) + +#ifdef GMOCK_INTERNAL_STRICT_SPEC_ASSERT +#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ + static_assert( \ + ::testing::internal::ValidateSpec(GMOCK_PP_STRINGIZE(_elem)), \ + "Token \'" GMOCK_PP_STRINGIZE( \ + _elem) "\' cannot be recognized as a valid specification " \ + "modifier. Is a ',' missing?"); +#else +#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ + static_assert( \ + (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem))) == 1, \ + GMOCK_PP_STRINGIZE( \ + _elem) " cannot be recognized as a valid specification modifier."); +#endif // GMOCK_INTERNAL_STRICT_SPEC_ASSERT + +// Modifiers implementation. +#define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CONST_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_CONST_I_const , + +#define GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_OVERRIDE_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_OVERRIDE_I_override , + +#define GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_FINAL_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_FINAL_I_final , + +#define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept , + +#define GMOCK_INTERNAL_DETECT_REF(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_REF_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_REF_I_ref , + +#define GMOCK_INTERNAL_UNPACK_ref(x) x + +#define GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CALLTYPE_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_CALLTYPE_I_Calltype , + +#define GMOCK_INTERNAL_UNPACK_Calltype(...) __VA_ARGS__ + +// Note: The use of `identity_t` here allows _Ret to represent return types that +// would normally need to be specified in a different way. For example, a method +// returning a function pointer must be written as +// +// fn_ptr_return_t (*method(method_args_t...))(fn_ptr_args_t...) +// +// But we only support placing the return type at the beginning. To handle this, +// we wrap all calls in identity_t, so that a declaration will be expanded to +// +// identity_t method(method_args_t...) +// +// This allows us to work around the syntactic oddities of function/method +// types. +#define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \ + ::testing::internal::identity_t( \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args)) + +#define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \ + GMOCK_PP_COMMA_IF(_i) \ + GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_elem), GMOCK_PP_REMOVE_PARENS, \ + GMOCK_PP_IDENTITY) \ + (_elem) + +#define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \ + gmock_a##_i + +#define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + ::std::forward(gmock_a##_i) + +#define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \ + gmock_a##_i + +#define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \ + GMOCK_PP_COMMA_IF(_i) \ + gmock_a##_i + +#define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + ::testing::A() + +#define GMOCK_INTERNAL_ARG_O(_i, ...) \ + typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type + +#define GMOCK_INTERNAL_MATCHER_O(_i, ...) \ + const ::testing::Matcher::template Arg<_i>::type>& + +#define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__) +#define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__) +#define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__) +#define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__) +#define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__) +#define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__) +#define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__) +#define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__) +#define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__) +#define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__) +#define MOCK_METHOD10(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__) + +#define MOCK_CONST_METHOD0(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__) +#define MOCK_CONST_METHOD1(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__) +#define MOCK_CONST_METHOD2(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__) +#define MOCK_CONST_METHOD3(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__) +#define MOCK_CONST_METHOD4(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__) +#define MOCK_CONST_METHOD5(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__) +#define MOCK_CONST_METHOD6(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__) +#define MOCK_CONST_METHOD7(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__) +#define MOCK_CONST_METHOD8(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__) +#define MOCK_CONST_METHOD9(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__) +#define MOCK_CONST_METHOD10(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__) + +#define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__) +#define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__) +#define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__) +#define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__) +#define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__) +#define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__) +#define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__) +#define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__) +#define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__) +#define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__) +#define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__) +#define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__) +#define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__) +#define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__) +#define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__) +#define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__) +#define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__) +#define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__) +#define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__) +#define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__) +#define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__) + +#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__) +#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__) +#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__) +#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__) +#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__) +#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__) +#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__) +#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__) +#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__) +#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__) +#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__) +#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__) +#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__) +#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__) +#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__) +#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__) +#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__) +#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__) +#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__) +#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__) +#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__) + +#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \ + GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ + args_num, ::testing::internal::identity_t<__VA_ARGS__>); \ + GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ + args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, , \ + (::testing::internal::identity_t<__VA_ARGS__>)) + +#define GMOCK_MOCKER_(arity, constness, Method) \ + GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) + +#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ diff --git a/third_party/googletest/googlemock/include/gmock/gmock-matchers.h b/third_party/googletest/googlemock/include/gmock/gmock-matchers.h new file mode 100644 index 0000000..6282901 --- /dev/null +++ b/third_party/googletest/googlemock/include/gmock/gmock-matchers.h @@ -0,0 +1,5610 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// The MATCHER* family of macros can be used in a namespace scope to +// define custom matchers easily. +// +// Basic Usage +// =========== +// +// The syntax +// +// MATCHER(name, description_string) { statements; } +// +// defines a matcher with the given name that executes the statements, +// which must return a bool to indicate if the match succeeds. Inside +// the statements, you can refer to the value being matched by 'arg', +// and refer to its type by 'arg_type'. +// +// The description string documents what the matcher does, and is used +// to generate the failure message when the match fails. Since a +// MATCHER() is usually defined in a header file shared by multiple +// C++ source files, we require the description to be a C-string +// literal to avoid possible side effects. It can be empty, in which +// case we'll use the sequence of words in the matcher name as the +// description. +// +// For example: +// +// MATCHER(IsEven, "") { return (arg % 2) == 0; } +// +// allows you to write +// +// // Expects mock_foo.Bar(n) to be called where n is even. +// EXPECT_CALL(mock_foo, Bar(IsEven())); +// +// or, +// +// // Verifies that the value of some_expression is even. +// EXPECT_THAT(some_expression, IsEven()); +// +// If the above assertion fails, it will print something like: +// +// Value of: some_expression +// Expected: is even +// Actual: 7 +// +// where the description "is even" is automatically calculated from the +// matcher name IsEven. +// +// Argument Type +// ============= +// +// Note that the type of the value being matched (arg_type) is +// determined by the context in which you use the matcher and is +// supplied to you by the compiler, so you don't need to worry about +// declaring it (nor can you). This allows the matcher to be +// polymorphic. For example, IsEven() can be used to match any type +// where the value of "(arg % 2) == 0" can be implicitly converted to +// a bool. In the "Bar(IsEven())" example above, if method Bar() +// takes an int, 'arg_type' will be int; if it takes an unsigned long, +// 'arg_type' will be unsigned long; and so on. +// +// Parameterizing Matchers +// ======================= +// +// Sometimes you'll want to parameterize the matcher. For that you +// can use another macro: +// +// MATCHER_P(name, param_name, description_string) { statements; } +// +// For example: +// +// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } +// +// will allow you to write: +// +// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); +// +// which may lead to this message (assuming n is 10): +// +// Value of: Blah("a") +// Expected: has absolute value 10 +// Actual: -9 +// +// Note that both the matcher description and its parameter are +// printed, making the message human-friendly. +// +// In the matcher definition body, you can write 'foo_type' to +// reference the type of a parameter named 'foo'. For example, in the +// body of MATCHER_P(HasAbsoluteValue, value) above, you can write +// 'value_type' to refer to the type of 'value'. +// +// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to +// support multi-parameter matchers. +// +// Describing Parameterized Matchers +// ================================= +// +// The last argument to MATCHER*() is a string-typed expression. The +// expression can reference all of the matcher's parameters and a +// special bool-typed variable named 'negation'. When 'negation' is +// false, the expression should evaluate to the matcher's description; +// otherwise it should evaluate to the description of the negation of +// the matcher. For example, +// +// using testing::PrintToString; +// +// MATCHER_P2(InClosedRange, low, hi, +// std::string(negation ? "is not" : "is") + " in range [" + +// PrintToString(low) + ", " + PrintToString(hi) + "]") { +// return low <= arg && arg <= hi; +// } +// ... +// EXPECT_THAT(3, InClosedRange(4, 6)); +// EXPECT_THAT(3, Not(InClosedRange(2, 4))); +// +// would generate two failures that contain the text: +// +// Expected: is in range [4, 6] +// ... +// Expected: is not in range [2, 4] +// +// If you specify "" as the description, the failure message will +// contain the sequence of words in the matcher name followed by the +// parameter values printed as a tuple. For example, +// +// MATCHER_P2(InClosedRange, low, hi, "") { ... } +// ... +// EXPECT_THAT(3, InClosedRange(4, 6)); +// EXPECT_THAT(3, Not(InClosedRange(2, 4))); +// +// would generate two failures that contain the text: +// +// Expected: in closed range (4, 6) +// ... +// Expected: not (in closed range (2, 4)) +// +// Types of Matcher Parameters +// =========================== +// +// For the purpose of typing, you can view +// +// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } +// +// as shorthand for +// +// template +// FooMatcherPk +// Foo(p1_type p1, ..., pk_type pk) { ... } +// +// When you write Foo(v1, ..., vk), the compiler infers the types of +// the parameters v1, ..., and vk for you. If you are not happy with +// the result of the type inference, you can specify the types by +// explicitly instantiating the template, as in Foo(5, +// false). As said earlier, you don't get to (or need to) specify +// 'arg_type' as that's determined by the context in which the matcher +// is used. You can assign the result of expression Foo(p1, ..., pk) +// to a variable of type FooMatcherPk. This +// can be useful when composing matchers. +// +// While you can instantiate a matcher template with reference types, +// passing the parameters by pointer usually makes your code more +// readable. If, however, you still want to pass a parameter by +// reference, be aware that in the failure message generated by the +// matcher you will see the value of the referenced object but not its +// address. +// +// Explaining Match Results +// ======================== +// +// Sometimes the matcher description alone isn't enough to explain why +// the match has failed or succeeded. For example, when expecting a +// long string, it can be very helpful to also print the diff between +// the expected string and the actual one. To achieve that, you can +// optionally stream additional information to a special variable +// named result_listener, whose type is a pointer to class +// MatchResultListener: +// +// MATCHER_P(EqualsLongString, str, "") { +// if (arg == str) return true; +// +// *result_listener << "the difference: " +/// << DiffStrings(str, arg); +// return false; +// } +// +// Overloading Matchers +// ==================== +// +// You can overload matchers with different numbers of parameters: +// +// MATCHER_P(Blah, a, description_string1) { ... } +// MATCHER_P2(Blah, a, b, description_string2) { ... } +// +// Caveats +// ======= +// +// When defining a new matcher, you should also consider implementing +// MatcherInterface or using MakePolymorphicMatcher(). These +// approaches require more work than the MATCHER* macros, but also +// give you more control on the types of the value being matched and +// the matcher parameters, which may leads to better compiler error +// messages when the matcher is used wrong. They also allow +// overloading matchers based on parameter types (as opposed to just +// based on the number of parameters). +// +// MATCHER*() can only be used in a namespace scope as templates cannot be +// declared inside of a local class. +// +// More Information +// ================ +// +// To learn more about using these macros, please search for 'MATCHER' +// on +// https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md +// +// This file also implements some commonly used argument matchers. More +// matchers can be defined by the user implementing the +// MatcherInterface interface if necessary. +// +// See googletest/include/gtest/gtest-matchers.h for the definition of class +// Matcher, class MatcherInterface, and others. + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ + +#include +#include +#include +#include +#include +#include +#include // NOLINT +#include +#include +#include +#include +#include + +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-port.h" +#include "gmock/internal/gmock-pp.h" +#include "gtest/gtest.h" + +// MSVC warning C5046 is new as of VS2017 version 15.8. +#if defined(_MSC_VER) && _MSC_VER >= 1915 +#define GMOCK_MAYBE_5046_ 5046 +#else +#define GMOCK_MAYBE_5046_ +#endif + +GTEST_DISABLE_MSC_WARNINGS_PUSH_( + 4251 GMOCK_MAYBE_5046_ /* class A needs to have dll-interface to be used by + clients of class B */ + /* Symbol involving type with internal linkage not defined */) + +namespace testing { + +// To implement a matcher Foo for type T, define: +// 1. a class FooMatcherImpl that implements the +// MatcherInterface interface, and +// 2. a factory function that creates a Matcher object from a +// FooMatcherImpl*. +// +// The two-level delegation design makes it possible to allow a user +// to write "v" instead of "Eq(v)" where a Matcher is expected, which +// is impossible if we pass matchers by pointers. It also eases +// ownership management as Matcher objects can now be copied like +// plain values. + +// A match result listener that stores the explanation in a string. +class StringMatchResultListener : public MatchResultListener { + public: + StringMatchResultListener() : MatchResultListener(&ss_) {} + + // Returns the explanation accumulated so far. + std::string str() const { return ss_.str(); } + + // Clears the explanation accumulated so far. + void Clear() { ss_.str(""); } + + private: + ::std::stringstream ss_; + + StringMatchResultListener(const StringMatchResultListener&) = delete; + StringMatchResultListener& operator=(const StringMatchResultListener&) = + delete; +}; + +// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION +// and MUST NOT BE USED IN USER CODE!!! +namespace internal { + +// The MatcherCastImpl class template is a helper for implementing +// MatcherCast(). We need this helper in order to partially +// specialize the implementation of MatcherCast() (C++ allows +// class/struct templates to be partially specialized, but not +// function templates.). + +// This general version is used when MatcherCast()'s argument is a +// polymorphic matcher (i.e. something that can be converted to a +// Matcher but is not one yet; for example, Eq(value)) or a value (for +// example, "hello"). +template +class MatcherCastImpl { + public: + static Matcher Cast(const M& polymorphic_matcher_or_value) { + // M can be a polymorphic matcher, in which case we want to use + // its conversion operator to create Matcher. Or it can be a value + // that should be passed to the Matcher's constructor. + // + // We can't call Matcher(polymorphic_matcher_or_value) when M is a + // polymorphic matcher because it'll be ambiguous if T has an implicit + // constructor from M (this usually happens when T has an implicit + // constructor from any type). + // + // It won't work to unconditionally implicit_cast + // polymorphic_matcher_or_value to Matcher because it won't trigger + // a user-defined conversion from M to T if one exists (assuming M is + // a value). + return CastImpl(polymorphic_matcher_or_value, + std::is_convertible>{}, + std::is_convertible{}); + } + + private: + template + static Matcher CastImpl(const M& polymorphic_matcher_or_value, + std::true_type /* convertible_to_matcher */, + std::integral_constant) { + // M is implicitly convertible to Matcher, which means that either + // M is a polymorphic matcher or Matcher has an implicit constructor + // from M. In both cases using the implicit conversion will produce a + // matcher. + // + // Even if T has an implicit constructor from M, it won't be called because + // creating Matcher would require a chain of two user-defined conversions + // (first to create T from M and then to create Matcher from T). + return polymorphic_matcher_or_value; + } + + // M can't be implicitly converted to Matcher, so M isn't a polymorphic + // matcher. It's a value of a type implicitly convertible to T. Use direct + // initialization to create a matcher. + static Matcher CastImpl(const M& value, + std::false_type /* convertible_to_matcher */, + std::true_type /* convertible_to_T */) { + return Matcher(ImplicitCast_(value)); + } + + // M can't be implicitly converted to either Matcher or T. Attempt to use + // polymorphic matcher Eq(value) in this case. + // + // Note that we first attempt to perform an implicit cast on the value and + // only fall back to the polymorphic Eq() matcher afterwards because the + // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end + // which might be undefined even when Rhs is implicitly convertible to Lhs + // (e.g. std::pair vs. std::pair). + // + // We don't define this method inline as we need the declaration of Eq(). + static Matcher CastImpl(const M& value, + std::false_type /* convertible_to_matcher */, + std::false_type /* convertible_to_T */); +}; + +// This more specialized version is used when MatcherCast()'s argument +// is already a Matcher. This only compiles when type T can be +// statically converted to type U. +template +class MatcherCastImpl> { + public: + static Matcher Cast(const Matcher& source_matcher) { + return Matcher(new Impl(source_matcher)); + } + + private: + class Impl : public MatcherInterface { + public: + explicit Impl(const Matcher& source_matcher) + : source_matcher_(source_matcher) {} + + // We delegate the matching logic to the source matcher. + bool MatchAndExplain(T x, MatchResultListener* listener) const override { + using FromType = typename std::remove_cv::type>::type>::type; + using ToType = typename std::remove_cv::type>::type>::type; + // Do not allow implicitly converting base*/& to derived*/&. + static_assert( + // Do not trigger if only one of them is a pointer. That implies a + // regular conversion and not a down_cast. + (std::is_pointer::type>::value != + std::is_pointer::type>::value) || + std::is_same::value || + !std::is_base_of::value, + "Can't implicitly convert from to "); + + // Do the cast to `U` explicitly if necessary. + // Otherwise, let implicit conversions do the trick. + using CastType = + typename std::conditional::value, + T&, U>::type; + + return source_matcher_.MatchAndExplain(static_cast(x), + listener); + } + + void DescribeTo(::std::ostream* os) const override { + source_matcher_.DescribeTo(os); + } + + void DescribeNegationTo(::std::ostream* os) const override { + source_matcher_.DescribeNegationTo(os); + } + + private: + const Matcher source_matcher_; + }; +}; + +// This even more specialized version is used for efficiently casting +// a matcher to its own type. +template +class MatcherCastImpl> { + public: + static Matcher Cast(const Matcher& matcher) { return matcher; } +}; + +// Template specialization for parameterless Matcher. +template +class MatcherBaseImpl { + public: + MatcherBaseImpl() = default; + + template + operator ::testing::Matcher() const { // NOLINT(runtime/explicit) + return ::testing::Matcher(new + typename Derived::template gmock_Impl()); + } +}; + +// Template specialization for Matcher with parameters. +template

: P {}; +template +struct conjunction + : conditional_t, P1> {}; + +template +struct range_formatter; + +template +struct range_formatter< + T, Char, + enable_if_t>, + is_formattable>::value>> { + private: + detail::range_formatter_type underlying_; + basic_string_view separator_ = detail::string_literal{}; + basic_string_view opening_bracket_ = + detail::string_literal{}; + basic_string_view closing_bracket_ = + detail::string_literal{}; + + public: + FMT_CONSTEXPR range_formatter() {} + + FMT_CONSTEXPR auto underlying() -> detail::range_formatter_type& { + return underlying_; + } + + FMT_CONSTEXPR void set_separator(basic_string_view sep) { + separator_ = sep; + } + + FMT_CONSTEXPR void set_brackets(basic_string_view open, + basic_string_view close) { + opening_bracket_ = open; + closing_bracket_ = close; + } + + template + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + auto it = ctx.begin(); + auto end = ctx.end(); + + if (it != end && *it == 'n') { + set_brackets({}, {}); + ++it; + } + + if (it != end && *it != '}') { + if (*it != ':') FMT_THROW(format_error("invalid format specifier")); + ++it; + } else { + detail::maybe_set_debug_format(underlying_, true); + } + + ctx.advance_to(it); + return underlying_.parse(ctx); + } + + template + auto format(R&& range, FormatContext& ctx) const -> decltype(ctx.out()) { + detail::range_mapper> mapper; + auto out = ctx.out(); + out = detail::copy_str(opening_bracket_, out); + int i = 0; + auto it = detail::range_begin(range); + auto end = detail::range_end(range); + for (; it != end; ++it) { + if (i > 0) out = detail::copy_str(separator_, out); + ctx.advance_to(out); + auto&& item = *it; + out = underlying_.format(mapper.map(item), ctx); + ++i; + } + out = detail::copy_str(closing_bracket_, out); + return out; + } +}; + +enum class range_format { disabled, map, set, sequence, string, debug_string }; + +namespace detail { +template +struct range_format_kind_ + : std::integral_constant, T>::value + ? range_format::disabled + : is_map::value ? range_format::map + : is_set::value ? range_format::set + : range_format::sequence> {}; + +template +struct range_default_formatter; + +template +using range_format_constant = std::integral_constant; + +template +struct range_default_formatter< + K, R, Char, + enable_if_t<(K == range_format::sequence || K == range_format::map || + K == range_format::set)>> { + using range_type = detail::maybe_const_range; + range_formatter, Char> underlying_; + + FMT_CONSTEXPR range_default_formatter() { init(range_format_constant()); } + + FMT_CONSTEXPR void init(range_format_constant) { + underlying_.set_brackets(detail::string_literal{}, + detail::string_literal{}); + } + + FMT_CONSTEXPR void init(range_format_constant) { + underlying_.set_brackets(detail::string_literal{}, + detail::string_literal{}); + underlying_.underlying().set_brackets({}, {}); + underlying_.underlying().set_separator( + detail::string_literal{}); + } + + FMT_CONSTEXPR void init(range_format_constant) {} + + template + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + return underlying_.parse(ctx); + } + + template + auto format(range_type& range, FormatContext& ctx) const + -> decltype(ctx.out()) { + return underlying_.format(range, ctx); + } +}; +} // namespace detail + +template +struct range_format_kind + : conditional_t< + is_range::value, detail::range_format_kind_, + std::integral_constant> {}; + +template +struct formatter< + R, Char, + enable_if_t::value != + range_format::disabled> +// Workaround a bug in MSVC 2015 and earlier. +#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1910 + , + detail::is_formattable_delayed +#endif + >::value>> + : detail::range_default_formatter::value, R, + Char> { +}; + +template struct tuple_join_view : detail::view { + const std::tuple& tuple; + basic_string_view sep; + + tuple_join_view(const std::tuple& t, basic_string_view s) + : tuple(t), sep{s} {} +}; + +// Define FMT_TUPLE_JOIN_SPECIFIERS to enable experimental format specifiers +// support in tuple_join. It is disabled by default because of issues with +// the dynamic width and precision. +#ifndef FMT_TUPLE_JOIN_SPECIFIERS +# define FMT_TUPLE_JOIN_SPECIFIERS 0 +#endif + +template +struct formatter, Char> { + template + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + return do_parse(ctx, std::integral_constant()); + } + + template + auto format(const tuple_join_view& value, + FormatContext& ctx) const -> typename FormatContext::iterator { + return do_format(value, ctx, + std::integral_constant()); + } + + private: + std::tuple::type, Char>...> formatters_; + + template + FMT_CONSTEXPR auto do_parse(ParseContext& ctx, + std::integral_constant) + -> decltype(ctx.begin()) { + return ctx.begin(); + } + + template + FMT_CONSTEXPR auto do_parse(ParseContext& ctx, + std::integral_constant) + -> decltype(ctx.begin()) { + auto end = ctx.begin(); +#if FMT_TUPLE_JOIN_SPECIFIERS + end = std::get(formatters_).parse(ctx); + if (N > 1) { + auto end1 = do_parse(ctx, std::integral_constant()); + if (end != end1) + FMT_THROW(format_error("incompatible format specs for tuple elements")); + } +#endif + return end; + } + + template + auto do_format(const tuple_join_view&, FormatContext& ctx, + std::integral_constant) const -> + typename FormatContext::iterator { + return ctx.out(); + } + + template + auto do_format(const tuple_join_view& value, FormatContext& ctx, + std::integral_constant) const -> + typename FormatContext::iterator { + auto out = std::get(formatters_) + .format(std::get(value.tuple), ctx); + if (N > 1) { + out = std::copy(value.sep.begin(), value.sep.end(), out); + ctx.advance_to(out); + return do_format(value, ctx, std::integral_constant()); + } + return out; + } +}; + +namespace detail { +// Check if T has an interface like a container adaptor (e.g. std::stack, +// std::queue, std::priority_queue). +template class is_container_adaptor_like { + template static auto check(U* p) -> typename U::container_type; + template static void check(...); + + public: + static constexpr const bool value = + !std::is_void(nullptr))>::value; +}; + +template struct all { + const Container& c; + auto begin() const -> typename Container::const_iterator { return c.begin(); } + auto end() const -> typename Container::const_iterator { return c.end(); } +}; +} // namespace detail + +template +struct formatter< + T, Char, + enable_if_t, + bool_constant::value == + range_format::disabled>>::value>> + : formatter, Char> { + using all = detail::all; + template + auto format(const T& t, FormatContext& ctx) const -> decltype(ctx.out()) { + struct getter : T { + static auto get(const T& t) -> all { + return {t.*(&getter::c)}; // Access c through the derived class. + } + }; + return formatter::format(getter::get(t), ctx); + } +}; + +FMT_BEGIN_EXPORT + +/** + \rst + Returns an object that formats `tuple` with elements separated by `sep`. + + **Example**:: + + std::tuple t = {1, 'a'}; + fmt::print("{}", fmt::join(t, ", ")); + // Output: "1, a" + \endrst + */ +template +FMT_CONSTEXPR auto join(const std::tuple& tuple, string_view sep) + -> tuple_join_view { + return {tuple, sep}; +} + +template +FMT_CONSTEXPR auto join(const std::tuple& tuple, + basic_string_view sep) + -> tuple_join_view { + 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 +auto join(std::initializer_list list, string_view sep) + -> join_view { + return join(std::begin(list), std::end(list), sep); +} + +FMT_END_EXPORT +FMT_END_NAMESPACE + +#endif // FMT_RANGES_H_ diff --git a/third_party/fmt/include/fmt/std.h b/third_party/fmt/include/fmt/std.h new file mode 100644 index 0000000..7cff115 --- /dev/null +++ b/third_party/fmt/include/fmt/std.h @@ -0,0 +1,537 @@ +// Formatting library for C++ - formatters for standard library types +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_STD_H_ +#define FMT_STD_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "format.h" +#include "ostream.h" + +#if FMT_HAS_INCLUDE() +# include +#endif +// Checking FMT_CPLUSPLUS for warning suppression in MSVC. +#if FMT_CPLUSPLUS >= 201703L +# if FMT_HAS_INCLUDE() +# include +# endif +# if FMT_HAS_INCLUDE() +# include +# endif +# if FMT_HAS_INCLUDE() +# include +# endif +#endif + +#if FMT_CPLUSPLUS > 201703L && FMT_HAS_INCLUDE() +# include +#endif + +// GCC 4 does not support FMT_HAS_INCLUDE. +#if FMT_HAS_INCLUDE() || defined(__GLIBCXX__) +# include +// Android NDK with gabi++ library on some architectures does not implement +// abi::__cxa_demangle(). +# ifndef __GABIXX_CXXABI_H__ +# define FMT_HAS_ABI_CXA_DEMANGLE +# endif +#endif + +// Check if typeid is available. +#ifndef FMT_USE_TYPEID +// __RTTI is for EDG compilers. In MSVC typeid is available without RTTI. +# if defined(__GXX_RTTI) || FMT_HAS_FEATURE(cxx_rtti) || FMT_MSC_VERSION || \ + defined(__INTEL_RTTI__) || defined(__RTTI) +# define FMT_USE_TYPEID 1 +# else +# define FMT_USE_TYPEID 0 +# endif +#endif + +// For older Xcode versions, __cpp_lib_xxx flags are inaccurately defined. +#ifndef FMT_CPP_LIB_FILESYSTEM +# ifdef __cpp_lib_filesystem +# define FMT_CPP_LIB_FILESYSTEM __cpp_lib_filesystem +# else +# define FMT_CPP_LIB_FILESYSTEM 0 +# endif +#endif + +#ifndef FMT_CPP_LIB_VARIANT +# ifdef __cpp_lib_variant +# define FMT_CPP_LIB_VARIANT __cpp_lib_variant +# else +# define FMT_CPP_LIB_VARIANT 0 +# endif +#endif + +#if FMT_CPP_LIB_FILESYSTEM +FMT_BEGIN_NAMESPACE + +namespace detail { + +template +auto get_path_string(const std::filesystem::path& p, + const std::basic_string& native) { + if constexpr (std::is_same_v && std::is_same_v) + return to_utf8(native, to_utf8_error_policy::replace); + else + return p.string(); +} + +template +void write_escaped_path(basic_memory_buffer& quoted, + const std::filesystem::path& p, + const std::basic_string& native) { + if constexpr (std::is_same_v && + std::is_same_v) { + auto buf = basic_memory_buffer(); + write_escaped_string(std::back_inserter(buf), native); + bool valid = to_utf8::convert(quoted, {buf.data(), buf.size()}); + FMT_ASSERT(valid, "invalid utf16"); + } else if constexpr (std::is_same_v) { + write_escaped_string( + std::back_inserter(quoted), native); + } else { + write_escaped_string(std::back_inserter(quoted), p.string()); + } +} + +} // namespace detail + +FMT_EXPORT +template struct formatter { + private: + format_specs specs_; + detail::arg_ref width_ref_; + bool debug_ = false; + char path_type_ = 0; + + public: + FMT_CONSTEXPR void set_debug_format(bool set = true) { debug_ = set; } + + template FMT_CONSTEXPR auto parse(ParseContext& ctx) { + auto it = ctx.begin(), end = ctx.end(); + if (it == end) return it; + + it = detail::parse_align(it, end, specs_); + if (it == end) return it; + + it = detail::parse_dynamic_spec(it, end, specs_.width, width_ref_, ctx); + if (it != end && *it == '?') { + debug_ = true; + ++it; + } + if (it != end && (*it == 'g')) path_type_ = *it++; + return it; + } + + template + auto format(const std::filesystem::path& p, FormatContext& ctx) const { + auto specs = specs_; +# ifdef _WIN32 + auto path_string = !path_type_ ? p.native() : p.generic_wstring(); +# else + auto path_string = !path_type_ ? p.native() : p.generic_string(); +# endif + + detail::handle_dynamic_spec(specs.width, width_ref_, + ctx); + if (!debug_) { + auto s = detail::get_path_string(p, path_string); + return detail::write(ctx.out(), basic_string_view(s), specs); + } + auto quoted = basic_memory_buffer(); + detail::write_escaped_path(quoted, p, path_string); + return detail::write(ctx.out(), + basic_string_view(quoted.data(), quoted.size()), + specs); + } +}; +FMT_END_NAMESPACE +#endif // FMT_CPP_LIB_FILESYSTEM + +FMT_BEGIN_NAMESPACE +FMT_EXPORT +template +struct formatter, Char> : nested_formatter { + private: + // Functor because C++11 doesn't support generic lambdas. + struct writer { + const std::bitset& bs; + + template + FMT_CONSTEXPR auto operator()(OutputIt out) -> OutputIt { + for (auto pos = N; pos > 0; --pos) { + out = detail::write(out, bs[pos - 1] ? Char('1') : Char('0')); + } + + return out; + } + }; + + public: + template + auto format(const std::bitset& bs, FormatContext& ctx) const + -> decltype(ctx.out()) { + return write_padded(ctx, writer{bs}); + } +}; + +FMT_EXPORT +template +struct formatter : basic_ostream_formatter {}; +FMT_END_NAMESPACE + +#ifdef __cpp_lib_optional +FMT_BEGIN_NAMESPACE +FMT_EXPORT +template +struct formatter, Char, + std::enable_if_t::value>> { + private: + formatter underlying_; + static constexpr basic_string_view optional = + detail::string_literal{}; + static constexpr basic_string_view none = + detail::string_literal{}; + + template + FMT_CONSTEXPR static auto maybe_set_debug_format(U& u, bool set) + -> decltype(u.set_debug_format(set)) { + u.set_debug_format(set); + } + + template + FMT_CONSTEXPR static void maybe_set_debug_format(U&, ...) {} + + public: + template FMT_CONSTEXPR auto parse(ParseContext& ctx) { + maybe_set_debug_format(underlying_, true); + return underlying_.parse(ctx); + } + + template + auto format(const std::optional& opt, FormatContext& ctx) const + -> decltype(ctx.out()) { + if (!opt) return detail::write(ctx.out(), none); + + auto out = ctx.out(); + out = detail::write(out, optional); + ctx.advance_to(out); + out = underlying_.format(*opt, ctx); + return detail::write(out, ')'); + } +}; +FMT_END_NAMESPACE +#endif // __cpp_lib_optional + +#ifdef __cpp_lib_source_location +FMT_BEGIN_NAMESPACE +FMT_EXPORT +template <> struct formatter { + template FMT_CONSTEXPR auto parse(ParseContext& ctx) { + return ctx.begin(); + } + + template + auto format(const std::source_location& loc, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto out = ctx.out(); + out = detail::write(out, loc.file_name()); + out = detail::write(out, ':'); + out = detail::write(out, loc.line()); + out = detail::write(out, ':'); + out = detail::write(out, loc.column()); + out = detail::write(out, ": "); + out = detail::write(out, loc.function_name()); + return out; + } +}; +FMT_END_NAMESPACE +#endif + +#if FMT_CPP_LIB_VARIANT +FMT_BEGIN_NAMESPACE +namespace detail { + +template +using variant_index_sequence = + std::make_index_sequence::value>; + +template struct is_variant_like_ : std::false_type {}; +template +struct is_variant_like_> : std::true_type {}; + +// formattable element check. +template class is_variant_formattable_ { + template + static std::conjunction< + is_formattable, C>...> + check(std::index_sequence); + + public: + static constexpr const bool value = + decltype(check(variant_index_sequence{}))::value; +}; + +template +auto write_variant_alternative(OutputIt out, const T& v) -> OutputIt { + if constexpr (is_string::value) + return write_escaped_string(out, detail::to_string_view(v)); + else if constexpr (std::is_same_v) + return write_escaped_char(out, v); + else + return write(out, v); +} + +} // namespace detail + +template struct is_variant_like { + static constexpr const bool value = detail::is_variant_like_::value; +}; + +template struct is_variant_formattable { + static constexpr const bool value = + detail::is_variant_formattable_::value; +}; + +FMT_EXPORT +template struct formatter { + template + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + + template + auto format(const std::monostate&, FormatContext& ctx) const + -> decltype(ctx.out()) { + return detail::write(ctx.out(), "monostate"); + } +}; + +FMT_EXPORT +template +struct formatter< + Variant, Char, + std::enable_if_t, is_variant_formattable>>> { + template + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + + template + auto format(const Variant& value, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto out = ctx.out(); + + out = detail::write(out, "variant("); + FMT_TRY { + std::visit( + [&](const auto& v) { + out = detail::write_variant_alternative(out, v); + }, + value); + } + FMT_CATCH(const std::bad_variant_access&) { + detail::write(out, "valueless by exception"); + } + *out++ = ')'; + return out; + } +}; +FMT_END_NAMESPACE +#endif // FMT_CPP_LIB_VARIANT + +FMT_BEGIN_NAMESPACE +FMT_EXPORT +template struct formatter { + template + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + + template + FMT_CONSTEXPR auto format(const std::error_code& ec, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto out = ctx.out(); + out = detail::write_bytes(out, ec.category().name(), format_specs()); + out = detail::write(out, Char(':')); + out = detail::write(out, ec.value()); + return out; + } +}; + +FMT_EXPORT +template +struct formatter< + T, Char, // DEPRECATED! Mixing code unit types. + typename std::enable_if::value>::type> { + private: + bool with_typename_ = false; + + public: + FMT_CONSTEXPR auto parse(basic_format_parse_context& ctx) + -> decltype(ctx.begin()) { + auto it = ctx.begin(); + auto end = ctx.end(); + if (it == end || *it == '}') return it; + if (*it == 't') { + ++it; + with_typename_ = FMT_USE_TYPEID != 0; + } + return it; + } + + template + auto format(const std::exception& ex, + basic_format_context& ctx) const -> OutputIt { + format_specs spec; + auto out = ctx.out(); + if (!with_typename_) + return detail::write_bytes(out, string_view(ex.what()), spec); + +#if FMT_USE_TYPEID + const std::type_info& ti = typeid(ex); +# ifdef FMT_HAS_ABI_CXA_DEMANGLE + int status = 0; + std::size_t size = 0; + std::unique_ptr demangled_name_ptr( + abi::__cxa_demangle(ti.name(), nullptr, &size, &status), &std::free); + + string_view demangled_name_view; + if (demangled_name_ptr) { + demangled_name_view = demangled_name_ptr.get(); + + // Normalization of stdlib inline namespace names. + // libc++ inline namespaces. + // std::__1::* -> std::* + // std::__1::__fs::* -> std::* + // libstdc++ inline namespaces. + // std::__cxx11::* -> std::* + // std::filesystem::__cxx11::* -> std::filesystem::* + if (demangled_name_view.starts_with("std::")) { + char* begin = demangled_name_ptr.get(); + char* to = begin + 5; // std:: + for (char *from = to, *end = begin + demangled_name_view.size(); + from < end;) { + // This is safe, because demangled_name is NUL-terminated. + if (from[0] == '_' && from[1] == '_') { + char* next = from + 1; + while (next < end && *next != ':') next++; + if (next[0] == ':' && next[1] == ':') { + from = next + 2; + continue; + } + } + *to++ = *from++; + } + demangled_name_view = {begin, detail::to_unsigned(to - begin)}; + } + } else { + demangled_name_view = string_view(ti.name()); + } + out = detail::write_bytes(out, demangled_name_view, spec); +# elif FMT_MSC_VERSION + string_view demangled_name_view(ti.name()); + if (demangled_name_view.starts_with("class ")) + demangled_name_view.remove_prefix(6); + else if (demangled_name_view.starts_with("struct ")) + demangled_name_view.remove_prefix(7); + out = detail::write_bytes(out, demangled_name_view, spec); +# else + out = detail::write_bytes(out, string_view(ti.name()), spec); +# endif + *out++ = ':'; + *out++ = ' '; + return detail::write_bytes(out, string_view(ex.what()), spec); +#endif + } +}; + +namespace detail { + +template +struct has_flip : std::false_type {}; + +template +struct has_flip().flip())>> + : std::true_type {}; + +template struct is_bit_reference_like { + static constexpr const bool value = + std::is_convertible::value && + std::is_nothrow_assignable::value && has_flip::value; +}; + +#ifdef _LIBCPP_VERSION + +// Workaround for libc++ incompatibility with C++ standard. +// According to the Standard, `bitset::operator[] const` returns bool. +template +struct is_bit_reference_like> { + static constexpr const bool value = true; +}; + +#endif + +} // namespace detail + +// We can't use std::vector::reference and +// std::bitset::reference because the compiler can't deduce Allocator and N +// in partial specialization. +FMT_EXPORT +template +struct formatter::value>> + : formatter { + template + FMT_CONSTEXPR auto format(const BitRef& v, FormatContext& ctx) const + -> decltype(ctx.out()) { + return formatter::format(v, ctx); + } +}; + +FMT_EXPORT +template +struct formatter, Char, + enable_if_t::value>> + : formatter { + template + auto format(const std::atomic& v, FormatContext& ctx) const + -> decltype(ctx.out()) { + return formatter::format(v.load(), ctx); + } +}; + +#ifdef __cpp_lib_atomic_flag_test +FMT_EXPORT +template +struct formatter : formatter { + template + auto format(const std::atomic_flag& v, FormatContext& ctx) const + -> decltype(ctx.out()) { + return formatter::format(v.test(), ctx); + } +}; +#endif // __cpp_lib_atomic_flag_test + +FMT_END_NAMESPACE +#endif // FMT_STD_H_ diff --git a/third_party/fmt/include/fmt/xchar.h b/third_party/fmt/include/fmt/xchar.h new file mode 100644 index 0000000..f609c5c --- /dev/null +++ b/third_party/fmt/include/fmt/xchar.h @@ -0,0 +1,259 @@ +// Formatting library for C++ - optional wchar_t and exotic character support +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_XCHAR_H_ +#define FMT_XCHAR_H_ + +#include + +#include "format.h" + +#ifndef FMT_STATIC_THOUSANDS_SEPARATOR +# include +#endif + +FMT_BEGIN_NAMESPACE +namespace detail { + +template +using is_exotic_char = bool_constant::value>; + +inline auto write_loc(std::back_insert_iterator> out, + loc_value value, const format_specs& specs, + locale_ref loc) -> bool { +#ifndef FMT_STATIC_THOUSANDS_SEPARATOR + auto& numpunct = + std::use_facet>(loc.get()); + auto separator = std::wstring(); + auto grouping = numpunct.grouping(); + if (!grouping.empty()) separator = std::wstring(1, numpunct.thousands_sep()); + return value.visit(loc_writer{out, specs, separator, grouping, {}}); +#endif + return false; +} +} // namespace detail + +FMT_BEGIN_EXPORT + +using wstring_view = basic_string_view; +using wformat_parse_context = basic_format_parse_context; +using wformat_context = buffer_context; +using wformat_args = basic_format_args; +using wmemory_buffer = basic_memory_buffer; + +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 +// Workaround broken conversion on older gcc. +template using wformat_string = wstring_view; +inline auto runtime(wstring_view s) -> wstring_view { return s; } +#else +template +using wformat_string = basic_format_string...>; +inline auto runtime(wstring_view s) -> runtime_format_string { + return {{s}}; +} +#endif + +template <> struct is_char : std::true_type {}; +template <> struct is_char : std::true_type {}; +template <> struct is_char : std::true_type {}; +template <> struct is_char : std::true_type {}; + +template +constexpr auto make_wformat_args(const T&... args) + -> format_arg_store { + return {args...}; +} + +inline namespace literals { +#if FMT_USE_USER_DEFINED_LITERALS && !FMT_USE_NONTYPE_TEMPLATE_ARGS +constexpr auto operator""_a(const wchar_t* s, size_t) + -> detail::udl_arg { + return {s}; +} +#endif +} // namespace literals + +template +auto join(It begin, Sentinel end, wstring_view sep) + -> join_view { + return {begin, end, sep}; +} + +template +auto join(Range&& range, wstring_view sep) + -> join_view, detail::sentinel_t, + wchar_t> { + return join(std::begin(range), std::end(range), sep); +} + +template +auto join(std::initializer_list list, wstring_view sep) + -> join_view { + return join(std::begin(list), std::end(list), sep); +} + +template ::value)> +auto vformat(basic_string_view format_str, + basic_format_args>> args) + -> std::basic_string { + auto buf = basic_memory_buffer(); + detail::vformat_to(buf, format_str, args); + return to_string(buf); +} + +template +auto format(wformat_string fmt, T&&... args) -> std::wstring { + return vformat(fmt::wstring_view(fmt), fmt::make_wformat_args(args...)); +} + +// Pass char_t as a default template parameter instead of using +// std::basic_string> to reduce the symbol size. +template , + FMT_ENABLE_IF(!std::is_same::value && + !std::is_same::value)> +auto format(const S& format_str, T&&... args) -> std::basic_string { + return vformat(detail::to_string_view(format_str), + fmt::make_format_args>(args...)); +} + +template , + FMT_ENABLE_IF(detail::is_locale::value&& + detail::is_exotic_char::value)> +inline auto vformat( + const Locale& loc, const S& format_str, + basic_format_args>> args) + -> std::basic_string { + return detail::vformat(loc, detail::to_string_view(format_str), args); +} + +template , + FMT_ENABLE_IF(detail::is_locale::value&& + detail::is_exotic_char::value)> +inline auto format(const Locale& loc, const S& format_str, T&&... args) + -> std::basic_string { + return detail::vformat(loc, detail::to_string_view(format_str), + fmt::make_format_args>(args...)); +} + +template , + FMT_ENABLE_IF(detail::is_output_iterator::value&& + detail::is_exotic_char::value)> +auto vformat_to(OutputIt out, const S& format_str, + basic_format_args>> args) + -> OutputIt { + auto&& buf = detail::get_buffer(out); + detail::vformat_to(buf, detail::to_string_view(format_str), args); + return detail::get_iterator(buf, out); +} + +template , + FMT_ENABLE_IF(detail::is_output_iterator::value&& + detail::is_exotic_char::value)> +inline auto format_to(OutputIt out, const S& fmt, T&&... args) -> OutputIt { + return vformat_to(out, detail::to_string_view(fmt), + fmt::make_format_args>(args...)); +} + +template , + FMT_ENABLE_IF(detail::is_output_iterator::value&& + detail::is_locale::value&& + detail::is_exotic_char::value)> +inline auto vformat_to( + OutputIt out, const Locale& loc, const S& format_str, + basic_format_args>> args) -> OutputIt { + auto&& buf = detail::get_buffer(out); + vformat_to(buf, detail::to_string_view(format_str), args, + detail::locale_ref(loc)); + return detail::get_iterator(buf, out); +} + +template , + bool enable = detail::is_output_iterator::value && + detail::is_locale::value && + detail::is_exotic_char::value> +inline auto format_to(OutputIt out, const Locale& loc, const S& format_str, + T&&... args) -> + typename std::enable_if::type { + return vformat_to(out, loc, detail::to_string_view(format_str), + fmt::make_format_args>(args...)); +} + +template ::value&& + detail::is_exotic_char::value)> +inline auto vformat_to_n( + OutputIt out, size_t n, basic_string_view format_str, + basic_format_args>> args) + -> format_to_n_result { + using traits = detail::fixed_buffer_traits; + auto buf = detail::iterator_buffer(out, n); + detail::vformat_to(buf, format_str, args); + return {buf.out(), buf.count()}; +} + +template , + FMT_ENABLE_IF(detail::is_output_iterator::value&& + detail::is_exotic_char::value)> +inline auto format_to_n(OutputIt out, size_t n, const S& fmt, T&&... args) + -> format_to_n_result { + return vformat_to_n(out, n, detail::to_string_view(fmt), + fmt::make_format_args>(args...)); +} + +template , + FMT_ENABLE_IF(detail::is_exotic_char::value)> +inline auto formatted_size(const S& fmt, T&&... args) -> size_t { + auto buf = detail::counting_buffer(); + detail::vformat_to(buf, detail::to_string_view(fmt), + fmt::make_format_args>(args...)); + return buf.count(); +} + +inline void vprint(std::FILE* f, wstring_view fmt, wformat_args args) { + auto buf = wmemory_buffer(); + detail::vformat_to(buf, fmt, args); + buf.push_back(L'\0'); + if (std::fputws(buf.data(), f) == -1) + FMT_THROW(system_error(errno, FMT_STRING("cannot write to file"))); +} + +inline void vprint(wstring_view fmt, wformat_args args) { + vprint(stdout, fmt, args); +} + +template +void print(std::FILE* f, wformat_string fmt, T&&... args) { + return vprint(f, wstring_view(fmt), fmt::make_wformat_args(args...)); +} + +template void print(wformat_string fmt, T&&... args) { + return vprint(wstring_view(fmt), fmt::make_wformat_args(args...)); +} + +template +void println(std::FILE* f, wformat_string fmt, T&&... args) { + return print(f, L"{}\n", fmt::format(fmt, std::forward(args)...)); +} + +template void println(wformat_string fmt, T&&... args) { + return print(L"{}\n", fmt::format(fmt, std::forward(args)...)); +} + +/** + Converts *value* to ``std::wstring`` using the default format for type *T*. + */ +template inline auto to_wstring(const T& value) -> std::wstring { + return format(FMT_STRING(L"{}"), value); +} +FMT_END_EXPORT +FMT_END_NAMESPACE + +#endif // FMT_XCHAR_H_ diff --git a/third_party/fmt/src/fmt.cc b/third_party/fmt/src/fmt.cc new file mode 100644 index 0000000..5330463 --- /dev/null +++ b/third_party/fmt/src/fmt.cc @@ -0,0 +1,108 @@ +module; + +// Put all implementation-provided headers into the global module fragment +// to prevent attachment to this module. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if __has_include() +# include +#endif +#if defined(_MSC_VER) || defined(__MINGW32__) +# include +#endif +#if defined __APPLE__ || defined(__FreeBSD__) +# include +#endif +#if __has_include() +# include +#endif +#if (__has_include() || defined(__APPLE__) || \ + defined(__linux__)) && \ + (!defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)) +# include +# include +# include +# ifndef _WIN32 +# include +# else +# include +# endif +#endif +#ifdef _WIN32 +# if defined(__GLIBCXX__) +# include +# include +# endif +# define WIN32_LEAN_AND_MEAN +# include +#endif + +export module fmt; + +#define FMT_EXPORT export +#define FMT_BEGIN_EXPORT export { +#define FMT_END_EXPORT } + +// If you define FMT_ATTACH_TO_GLOBAL_MODULE +// - all declarations are detached from module 'fmt' +// - the module behaves like a traditional static library, too +// - all library symbols are mangled traditionally +// - you can mix TUs with either importing or #including the {fmt} API +#ifdef FMT_ATTACH_TO_GLOBAL_MODULE +extern "C++" { +#endif + +// All library-provided declarations and definitions must be in the module +// purview to be exported. +#include "fmt/args.h" +#include "fmt/chrono.h" +#include "fmt/color.h" +#include "fmt/compile.h" +#include "fmt/format.h" +#include "fmt/os.h" +#include "fmt/printf.h" +#include "fmt/std.h" +#include "fmt/xchar.h" + +#ifdef FMT_ATTACH_TO_GLOBAL_MODULE +} +#endif + +// gcc doesn't yet implement private module fragments +#if !FMT_GCC_VERSION +module :private; +#endif + +#include "format.cc" +#include "os.cc" diff --git a/third_party/fmt/src/format.cc b/third_party/fmt/src/format.cc new file mode 100644 index 0000000..391d3a2 --- /dev/null +++ b/third_party/fmt/src/format.cc @@ -0,0 +1,43 @@ +// Formatting library for C++ +// +// Copyright (c) 2012 - 2016, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#include "fmt/format-inl.h" + +FMT_BEGIN_NAMESPACE +namespace detail { + +template FMT_API auto dragonbox::to_decimal(float x) noexcept + -> dragonbox::decimal_fp; +template FMT_API auto dragonbox::to_decimal(double x) noexcept + -> dragonbox::decimal_fp; + +#ifndef FMT_STATIC_THOUSANDS_SEPARATOR +template FMT_API locale_ref::locale_ref(const std::locale& loc); +template FMT_API auto locale_ref::get() const -> std::locale; +#endif + +// Explicit instantiations for char. + +template FMT_API auto thousands_sep_impl(locale_ref) + -> thousands_sep_result; +template FMT_API auto decimal_point_impl(locale_ref) -> char; + +template FMT_API void buffer::append(const char*, const char*); + +template FMT_API void vformat_to(buffer&, string_view, + typename vformat_args<>::type, locale_ref); + +// Explicit instantiations for wchar_t. + +template FMT_API auto thousands_sep_impl(locale_ref) + -> thousands_sep_result; +template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t; + +template FMT_API void buffer::append(const wchar_t*, const wchar_t*); + +} // namespace detail +FMT_END_NAMESPACE diff --git a/third_party/fmt/src/os.cc b/third_party/fmt/src/os.cc new file mode 100644 index 0000000..a639e78 --- /dev/null +++ b/third_party/fmt/src/os.cc @@ -0,0 +1,402 @@ +// Formatting library for C++ - optional OS-specific functionality +// +// Copyright (c) 2012 - 2016, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +// Disable bogus MSVC warnings. +#if !defined(_CRT_SECURE_NO_WARNINGS) && defined(_MSC_VER) +# define _CRT_SECURE_NO_WARNINGS +#endif + +#include "fmt/os.h" + +#include + +#if FMT_USE_FCNTL +# include +# include + +# ifdef _WRS_KERNEL // VxWorks7 kernel +# include // getpagesize +# endif + +# ifndef _WIN32 +# include +# else +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include + +# ifndef S_IRUSR +# define S_IRUSR _S_IREAD +# endif +# ifndef S_IWUSR +# define S_IWUSR _S_IWRITE +# endif +# ifndef S_IRGRP +# define S_IRGRP 0 +# endif +# ifndef S_IWGRP +# define S_IWGRP 0 +# endif +# ifndef S_IROTH +# define S_IROTH 0 +# endif +# ifndef S_IWOTH +# define S_IWOTH 0 +# endif +# endif // _WIN32 +#endif // FMT_USE_FCNTL + +#ifdef _WIN32 +# include +#endif + +namespace { +#ifdef _WIN32 +// Return type of read and write functions. +using rwresult = int; + +// On Windows the count argument to read and write is unsigned, so convert +// it from size_t preventing integer overflow. +inline unsigned convert_rwcount(std::size_t count) { + return count <= UINT_MAX ? static_cast(count) : UINT_MAX; +} +#elif FMT_USE_FCNTL +// Return type of read and write functions. +using rwresult = ssize_t; + +inline std::size_t convert_rwcount(std::size_t count) { return count; } +#endif +} // namespace + +FMT_BEGIN_NAMESPACE + +#ifdef _WIN32 +namespace detail { + +class system_message { + system_message(const system_message&) = delete; + void operator=(const system_message&) = delete; + + unsigned long result_; + wchar_t* message_; + + static bool is_whitespace(wchar_t c) noexcept { + return c == L' ' || c == L'\n' || c == L'\r' || c == L'\t' || c == L'\0'; + } + + public: + explicit system_message(unsigned long error_code) + : result_(0), message_(nullptr) { + result_ = FormatMessageW( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + reinterpret_cast(&message_), 0, nullptr); + if (result_ != 0) { + while (result_ != 0 && is_whitespace(message_[result_ - 1])) { + --result_; + } + } + } + ~system_message() { LocalFree(message_); } + explicit operator bool() const noexcept { return result_ != 0; } + operator basic_string_view() const noexcept { + return basic_string_view(message_, result_); + } +}; + +class utf8_system_category final : public std::error_category { + public: + const char* name() const noexcept override { return "system"; } + std::string message(int error_code) const override { + auto&& msg = system_message(error_code); + if (msg) { + auto utf8_message = to_utf8(); + if (utf8_message.convert(msg)) { + return utf8_message.str(); + } + } + return "unknown error"; + } +}; + +} // namespace detail + +FMT_API const std::error_category& system_category() noexcept { + static const detail::utf8_system_category category; + return category; +} + +std::system_error vwindows_error(int err_code, string_view format_str, + format_args args) { + auto ec = std::error_code(err_code, system_category()); + return std::system_error(ec, vformat(format_str, args)); +} + +void detail::format_windows_error(detail::buffer& out, int error_code, + const char* message) noexcept { + FMT_TRY { + auto&& msg = system_message(error_code); + if (msg) { + auto utf8_message = to_utf8(); + if (utf8_message.convert(msg)) { + fmt::format_to(appender(out), FMT_STRING("{}: {}"), message, + string_view(utf8_message)); + return; + } + } + } + FMT_CATCH(...) {} + format_error_code(out, error_code, message); +} + +void report_windows_error(int error_code, const char* message) noexcept { + report_error(detail::format_windows_error, error_code, message); +} +#endif // _WIN32 + +buffered_file::~buffered_file() noexcept { + if (file_ && FMT_SYSTEM(fclose(file_)) != 0) + report_system_error(errno, "cannot close file"); +} + +buffered_file::buffered_file(cstring_view filename, cstring_view mode) { + FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())), + nullptr); + if (!file_) + FMT_THROW(system_error(errno, FMT_STRING("cannot open file {}"), + filename.c_str())); +} + +void buffered_file::close() { + if (!file_) return; + int result = FMT_SYSTEM(fclose(file_)); + file_ = nullptr; + if (result != 0) + FMT_THROW(system_error(errno, FMT_STRING("cannot close file"))); +} + +int buffered_file::descriptor() const { +#if !defined(fileno) + int fd = FMT_POSIX_CALL(fileno(file_)); +#elif defined(FMT_HAS_SYSTEM) + // fileno is a macro on OpenBSD so we cannot use FMT_POSIX_CALL. +# define FMT_DISABLE_MACRO + int fd = FMT_SYSTEM(fileno FMT_DISABLE_MACRO(file_)); +#else + int fd = fileno(file_); +#endif + if (fd == -1) + FMT_THROW(system_error(errno, FMT_STRING("cannot get file descriptor"))); + return fd; +} + +#if FMT_USE_FCNTL +# ifdef _WIN32 +using mode_t = int; +# endif +constexpr mode_t default_open_mode = + S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; + +file::file(cstring_view path, int oflag) { +# if defined(_WIN32) && !defined(__MINGW32__) + fd_ = -1; + auto converted = detail::utf8_to_utf16(string_view(path.c_str())); + *this = file::open_windows_file(converted.c_str(), oflag); +# else + FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, default_open_mode))); + if (fd_ == -1) + FMT_THROW( + system_error(errno, FMT_STRING("cannot open file {}"), path.c_str())); +# endif +} + +file::~file() noexcept { + // Don't retry close in case of EINTR! + // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html + if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0) + report_system_error(errno, "cannot close file"); +} + +void file::close() { + if (fd_ == -1) return; + // Don't retry close in case of EINTR! + // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html + int result = FMT_POSIX_CALL(close(fd_)); + fd_ = -1; + if (result != 0) + FMT_THROW(system_error(errno, FMT_STRING("cannot close file"))); +} + +long long file::size() const { +# ifdef _WIN32 + // Use GetFileSize instead of GetFileSizeEx for the case when _WIN32_WINNT + // is less than 0x0500 as is the case with some default MinGW builds. + // Both functions support large file sizes. + DWORD size_upper = 0; + HANDLE handle = reinterpret_cast(_get_osfhandle(fd_)); + DWORD size_lower = FMT_SYSTEM(GetFileSize(handle, &size_upper)); + if (size_lower == INVALID_FILE_SIZE) { + DWORD error = GetLastError(); + if (error != NO_ERROR) + FMT_THROW(windows_error(GetLastError(), "cannot get file size")); + } + unsigned long long long_size = size_upper; + return (long_size << sizeof(DWORD) * CHAR_BIT) | size_lower; +# else + using Stat = struct stat; + Stat file_stat = Stat(); + if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1) + FMT_THROW(system_error(errno, FMT_STRING("cannot get file attributes"))); + static_assert(sizeof(long long) >= sizeof(file_stat.st_size), + "return type of file::size is not large enough"); + return file_stat.st_size; +# endif +} + +std::size_t file::read(void* buffer, std::size_t count) { + rwresult result = 0; + FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count)))); + if (result < 0) + FMT_THROW(system_error(errno, FMT_STRING("cannot read from file"))); + return detail::to_unsigned(result); +} + +std::size_t file::write(const void* buffer, std::size_t count) { + rwresult result = 0; + FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count)))); + if (result < 0) + FMT_THROW(system_error(errno, FMT_STRING("cannot write to file"))); + return detail::to_unsigned(result); +} + +file file::dup(int fd) { + // Don't retry as dup doesn't return EINTR. + // http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html + int new_fd = FMT_POSIX_CALL(dup(fd)); + if (new_fd == -1) + FMT_THROW(system_error( + errno, FMT_STRING("cannot duplicate file descriptor {}"), fd)); + return file(new_fd); +} + +void file::dup2(int fd) { + int result = 0; + FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd))); + if (result == -1) { + FMT_THROW(system_error( + errno, FMT_STRING("cannot duplicate file descriptor {} to {}"), fd_, + fd)); + } +} + +void file::dup2(int fd, std::error_code& ec) noexcept { + int result = 0; + FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd))); + if (result == -1) ec = std::error_code(errno, std::generic_category()); +} + +void file::pipe(file& read_end, file& write_end) { + // Close the descriptors first to make sure that assignments don't throw + // and there are no leaks. + read_end.close(); + write_end.close(); + int fds[2] = {}; +# ifdef _WIN32 + // Make the default pipe capacity same as on Linux 2.6.11+. + enum { DEFAULT_CAPACITY = 65536 }; + int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY)); +# else + // Don't retry as the pipe function doesn't return EINTR. + // http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html + int result = FMT_POSIX_CALL(pipe(fds)); +# endif + if (result != 0) + FMT_THROW(system_error(errno, FMT_STRING("cannot create pipe"))); + // The following assignments don't throw because read_fd and write_fd + // are closed. + read_end = file(fds[0]); + write_end = file(fds[1]); +} + +buffered_file file::fdopen(const char* mode) { +// Don't retry as fdopen doesn't return EINTR. +# if defined(__MINGW32__) && defined(_POSIX_) + FILE* f = ::fdopen(fd_, mode); +# else + FILE* f = FMT_POSIX_CALL(fdopen(fd_, mode)); +# endif + if (!f) { + FMT_THROW(system_error( + errno, FMT_STRING("cannot associate stream with file descriptor"))); + } + buffered_file bf(f); + fd_ = -1; + return bf; +} + +# if defined(_WIN32) && !defined(__MINGW32__) +file file::open_windows_file(wcstring_view path, int oflag) { + int fd = -1; + auto err = _wsopen_s(&fd, path.c_str(), oflag, _SH_DENYNO, default_open_mode); + if (fd == -1) { + FMT_THROW(system_error(err, FMT_STRING("cannot open file {}"), + detail::to_utf8(path.c_str()).c_str())); + } + return file(fd); +} +# endif + +# if !defined(__MSDOS__) +long getpagesize() { +# ifdef _WIN32 + SYSTEM_INFO si; + GetSystemInfo(&si); + return si.dwPageSize; +# else +# ifdef _WRS_KERNEL + long size = FMT_POSIX_CALL(getpagesize()); +# else + long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE)); +# endif + + if (size < 0) + FMT_THROW(system_error(errno, FMT_STRING("cannot get memory page size"))); + return size; +# endif +} +# endif + +namespace detail { + +void file_buffer::grow(size_t) { + if (this->size() == this->capacity()) flush(); +} + +file_buffer::file_buffer(cstring_view path, + const detail::ostream_params& params) + : file_(path, params.oflag) { + set(new char[params.buffer_size], params.buffer_size); +} + +file_buffer::file_buffer(file_buffer&& other) + : detail::buffer(other.data(), other.size(), other.capacity()), + file_(std::move(other.file_)) { + other.clear(); + other.set(nullptr, 0); +} + +file_buffer::~file_buffer() { + flush(); + delete[] data(); +} +} // namespace detail + +ostream::~ostream() = default; +#endif // FMT_USE_FCNTL +FMT_END_NAMESPACE diff --git a/third_party/fmt/support/Android.mk b/third_party/fmt/support/Android.mk new file mode 100644 index 0000000..84a3e32 --- /dev/null +++ b/third_party/fmt/support/Android.mk @@ -0,0 +1,15 @@ +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) + +LOCAL_MODULE := fmt_static +LOCAL_MODULE_FILENAME := libfmt + +LOCAL_SRC_FILES := ../src/format.cc + +LOCAL_C_INCLUDES := $(LOCAL_PATH) +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) + +LOCAL_CFLAGS += -std=c++11 -fexceptions + +include $(BUILD_STATIC_LIBRARY) + diff --git a/third_party/fmt/support/AndroidManifest.xml b/third_party/fmt/support/AndroidManifest.xml new file mode 100644 index 0000000..c282ef5 --- /dev/null +++ b/third_party/fmt/support/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/third_party/fmt/support/C++.sublime-syntax b/third_party/fmt/support/C++.sublime-syntax new file mode 100644 index 0000000..9dfb5cb --- /dev/null +++ b/third_party/fmt/support/C++.sublime-syntax @@ -0,0 +1,2061 @@ +%YAML 1.2 +--- +# http://www.sublimetext.com/docs/3/syntax.html +name: C++ (fmt) +comment: I don't think anyone uses .hp. .cp tends to be paired with .h. (I could be wrong. :) -- chris +file_extensions: + - cpp + - cc + - cp + - cxx + - c++ + - C + - h + - hh + - hpp + - hxx + - h++ + - inl + - ipp +first_line_match: '-\*- C\+\+ -\*-' +scope: source.c++ +variables: + identifier: \b[[:alpha:]_][[:alnum:]_]*\b # upper and lowercase + macro_identifier: \b[[:upper:]_][[:upper:][:digit:]_]{2,}\b # only uppercase, at least 3 chars + path_lookahead: '(?:::\s*)?(?:{{identifier}}\s*::\s*)*(?:template\s+)?{{identifier}}' + operator_method_name: '\boperator\s*(?:[-+*/%^&|~!=<>]|[-+*/%^&|=!<>]=|<<=?|>>=?|&&|\|\||\+\+|--|,|->\*?|\(\)|\[\]|""\s*{{identifier}})' + casts: 'const_cast|dynamic_cast|reinterpret_cast|static_cast' + operator_keywords: 'and|and_eq|bitand|bitor|compl|not|not_eq|or|or_eq|xor|xor_eq|noexcept' + control_keywords: 'break|case|catch|continue|default|do|else|for|goto|if|_Pragma|return|switch|throw|try|while' + memory_operators: 'new|delete' + basic_types: 'asm|__asm__|auto|bool|_Bool|char|_Complex|double|float|_Imaginary|int|long|short|signed|unsigned|void' + before_tag: 'struct|union|enum\s+class|enum\s+struct|enum|class' + declspec: '__declspec\(\s*\w+(?:\([^)]+\))?\s*\)' + storage_classes: 'static|export|extern|friend|explicit|virtual|register|thread_local' + type_qualifier: 'const|constexpr|mutable|typename|volatile' + compiler_directive: 'inline|restrict|__restrict__|__restrict' + visibility_modifiers: 'private|protected|public' + other_keywords: 'typedef|nullptr|{{visibility_modifiers}}|static_assert|sizeof|using|typeid|alignof|alignas|namespace|template' + modifiers: '{{storage_classes}}|{{type_qualifier}}|{{compiler_directive}}' + non_angle_brackets: '(?=<<|<=)' + + regular: '[^(){}&;*^%=<>-]*' + paren_open: (?:\( + paren_close: '\))?' + generic_open: (?:< + generic_close: '>)?' + balance_parentheses: '{{regular}}{{paren_open}}{{regular}}{{paren_close}}{{regular}}' + generic_lookahead: <{{regular}}{{generic_open}}{{regular}}{{generic_open}}{{regular}}{{generic_close}}\s*{{generic_close}}{{balance_parentheses}}> + + data_structures_forward_decl_lookahead: '(\s+{{macro_identifier}})*\s*(:\s*({{path_lookahead}}|{{visibility_modifiers}}|,|\s|<[^;]*>)+)?;' + non_func_keywords: 'if|for|switch|while|decltype|sizeof|__declspec|__attribute__|typeid|alignof|alignas|static_assert' + + format_spec: |- + (?x: + (?:.? [<>=^])? # fill align + [ +-]? # sign + \#? # alternate form + # technically, octal and hexadecimal integers are also supported as 'width', but rarely used + \d* # width + ,? # thousands separator + (?:\.\d+)? # precision + [bcdeEfFgGnosxX%]? # type + ) + +contexts: + main: + - include: preprocessor-global + - include: global + + ############################################################################# + # Reusable contexts + # + # The follow contexts are currently constructed to be reused in the + # Objetive-C++ syntax. They are specifically constructed to not push into + # sub-contexts, which ensures that Objective-C++ code isn't accidentally + # lexed as plain C++. + # + # The "unique-*" contexts are additions that C++ makes over C, and thus can + # be directly reused in Objective-C++ along with contexts from Objective-C + # and C. + ############################################################################# + + unique-late-expressions: + # This is highlighted after all of the other control keywords + # to allow operator overloading to be lexed properly + - match: \boperator\b + scope: keyword.control.c++ + + unique-modifiers: + - match: \b({{modifiers}})\b + scope: storage.modifier.c++ + + unique-variables: + - match: \bthis\b + scope: variable.language.c++ + # common C++ instance var naming idiom -- fMemberName + - match: '\b(f|m)[[:upper:]]\w*\b' + scope: variable.other.readwrite.member.c++ + # common C++ instance var naming idiom -- m_member_name + - match: '\bm_[[:alnum:]_]+\b' + scope: variable.other.readwrite.member.c++ + + unique-constants: + - match: \bnullptr\b + scope: constant.language.c++ + + unique-keywords: + - match: \busing\b + scope: keyword.control.c++ + - match: \bbreak\b + scope: keyword.control.flow.break.c++ + - match: \bcontinue\b + scope: keyword.control.flow.continue.c++ + - match: \bgoto\b + scope: keyword.control.flow.goto.c++ + - match: \breturn\b + scope: keyword.control.flow.return.c++ + - match: \bthrow\b + scope: keyword.control.flow.throw.c++ + - match: \b({{control_keywords}})\b + scope: keyword.control.c++ + - match: '\bdelete\b(\s*\[\])?|\bnew\b(?!])' + scope: keyword.control.c++ + - match: \b({{operator_keywords}})\b + scope: keyword.operator.word.c++ + + unique-types: + - match: \b(char16_t|char32_t|wchar_t|nullptr_t)\b + scope: storage.type.c++ + - match: \bclass\b + scope: storage.type.c++ + + unique-strings: + - match: '((?:L|u8|u|U)?R)("([^\(\)\\ ]{0,16})\()' + captures: + 1: storage.type.string.c++ + 2: punctuation.definition.string.begin.c++ + push: + - meta_scope: string.quoted.double.c++ + - match: '\)\3"' + scope: punctuation.definition.string.end.c++ + pop: true + - match: '\{\{|\}\}' + scope: constant.character.escape.c++ + - include: formatting-syntax + + unique-numbers: + - match: |- + (?x) + (?: + # floats + (?: + (?:\b\d(?:[\d']*\d)?\.\d(?:[\d']*\d)?|\B\.\d(?:[\d']*\d)?)(?:[Ee][+-]?\d(?:[\d']*\d)?)?(?:[fFlL]|(?:i[fl]?|h|min|[mun]?s|_\w*))?\b + | + (?:\b\d(?:[\d']*\d)?\.)(?:\B|(?:[fFlL]|(?:i[fl]?|h|min|[mun]?s|_\w*))\b|(?:[Ee][+-]?\d(?:[\d']*\d)?)(?:[fFlL]|(?:i[fl]?|h|min|[mun]?s|_\w*))?\b) + | + \b\d(?:[\d']*\d)?(?:[Ee][+-]?\d(?:[\d']*\d)?)(?:[fFlL]|(?:i[fl]?|h|min|[mun]?s|_\w*))?\b + ) + | + # ints + \b(?: + (?: + # dec + [1-9](?:[\d']*\d)? + | + # oct + 0(?:[0-7']*[0-7])? + | + # hex + 0[Xx][\da-fA-F](?:[\da-fA-F']*[\da-fA-F])? + | + # bin + 0[Bb][01](?:[01']*[01])? + ) + # int suffixes + (?:(?:l{1,2}|L{1,2})[uU]?|[uU](?:l{0,2}|L{0,2})|(?:i[fl]?|h|min|[mun]?s|_\w*))?)\b + ) + (?!\.) # Number must not be followed by a decimal point + scope: constant.numeric.c++ + + identifiers: + - match: '{{identifier}}\s*(::)\s*' + captures: + 1: punctuation.accessor.c++ + - match: '(?:(::)\s*)?{{identifier}}' + captures: + 1: punctuation.accessor.c++ + + function-specifiers: + - match: \b(const|final|noexcept|override)\b + scope: storage.modifier.c++ + + ############################################################################# + # The following are C++-specific contexts that should not be reused. This is + # because they push into subcontexts and use variables that are C++-specific. + ############################################################################# + + ## Common context layout + + global: + - match: '(?=\btemplate\b)' + push: + - include: template + - match: (?=\S) + set: global-modifier + - include: namespace + - include: keywords-angle-brackets + - match: '(?={{path_lookahead}}\s*<)' + push: global-modifier + # Take care of comments just before a function definition. + - match: /\* + scope: punctuation.definition.comment.c + push: + - - match: \s*(?=\w) + set: global-modifier + - match: "" + pop: true + - - meta_scope: comment.block.c + - match: \*/ + scope: punctuation.definition.comment.c + pop: true + - include: early-expressions + - match: ^\s*\b(extern)(?=\s+"C(\+\+)?") + scope: storage.modifier.c++ + push: + - include: comments + - include: strings + - match: '\{' + scope: punctuation.section.block.begin.c++ + set: + - meta_scope: meta.extern-c.c++ + - match: '^\s*(#\s*ifdef)\s*__cplusplus\s*' + scope: meta.preprocessor.c++ + captures: + 1: keyword.control.import.c++ + set: + - match: '\}' + scope: punctuation.section.block.end.c++ + pop: true + - include: preprocessor-global + - include: global + - match: '\}' + scope: punctuation.section.block.end.c++ + pop: true + - include: preprocessor-global + - include: global + - match: (?=\S) + set: global-modifier + - match: ^\s*(?=\w) + push: global-modifier + - include: late-expressions + + statements: + - include: preprocessor-statements + - include: scope:source.c#label + - include: expressions + + expressions: + - include: early-expressions + - include: late-expressions + + early-expressions: + - include: early-expressions-before-generic-type + - include: generic-type + - include: early-expressions-after-generic-type + + early-expressions-before-generic-type: + - include: preprocessor-expressions + - include: comments + - include: case-default + - include: typedef + - include: keywords-angle-brackets + - include: keywords-parens + - include: keywords + - include: numbers + # Prevent a '<' from getting scoped as the start of another template + # parameter list, if in reality a less-than-or-equals sign is meant. + - match: <= + scope: keyword.operator.comparison.c + + early-expressions-after-generic-type: + - include: members-arrow + - include: operators + - include: members-dot + - include: strings + - include: parens + - include: brackets + - include: block + - include: variables + - include: constants + - match: ',' + scope: punctuation.separator.c++ + - match: '\)|\}' + scope: invalid.illegal.stray-bracket-end.c++ + + expressions-minus-generic-type: + - include: early-expressions-before-generic-type + - include: angle-brackets + - include: early-expressions-after-generic-type + - include: late-expressions + + expressions-minus-generic-type-function-call: + - include: early-expressions-before-generic-type + - include: angle-brackets + - include: early-expressions-after-generic-type + - include: late-expressions-before-function-call + - include: identifiers + - match: ';' + scope: punctuation.terminator.c++ + + late-expressions: + - include: late-expressions-before-function-call + - include: function-call + - include: identifiers + - match: ';' + scope: punctuation.terminator.c++ + + late-expressions-before-function-call: + - include: unique-late-expressions + - include: modifiers-parens + - include: modifiers + - include: types + + expressions-minus-function-call: + - include: early-expressions + - include: late-expressions-before-function-call + - include: identifiers + - match: ';' + scope: punctuation.terminator.c++ + + comments: + - include: scope:source.c#comments + + operators: + - include: scope:source.c#operators + + modifiers: + - include: unique-modifiers + - include: scope:source.c#modifiers + + variables: + - include: unique-variables + - include: scope:source.c#variables + + constants: + - include: unique-constants + - include: scope:source.c#constants + + keywords: + - include: unique-keywords + - include: scope:source.c#keywords + + types: + - include: unique-types + - include: types-parens + - include: scope:source.c#types + + strings: + - include: unique-strings + - match: '(L|u8|u|U)?(")' + captures: + 1: storage.type.string.c++ + 2: punctuation.definition.string.begin.c++ + push: + - meta_scope: string.quoted.double.c++ + - match: '"' + scope: punctuation.definition.string.end.c++ + pop: true + - include: scope:source.c#string_escaped_char + - match: |- + (?x)% + (\d+\$)? # field (argument #) + [#0\- +']* # flags + [,;:_]? # separator character (AltiVec) + ((-?\d+)|\*(-?\d+\$)?)? # minimum field width + (\.((-?\d+)|\*(-?\d+\$)?)?)? # precision + (hh|h|ll|l|j|t|z|q|L|vh|vl|v|hv|hl)? # length modifier + (\[[^\]]+\]|[am]s|[diouxXDOUeEfFgGaACcSspn%]) # conversion type + scope: constant.other.placeholder.c++ + - match: '\{\{|\}\}' + scope: constant.character.escape.c++ + - include: formatting-syntax + - include: scope:source.c#strings + + formatting-syntax: + # https://docs.python.org/3.6/library/string.html#formatstrings + - match: |- # simple form + (?x) + (\{) + (?: [\w.\[\]]+)? # field_name + ( ! [ars])? # conversion + ( : (?:{{format_spec}}| # format_spec OR + [^}%]*%.[^}]*) # any format-like string + )? + (\}) + scope: constant.other.placeholder.c++ + captures: + 1: punctuation.definition.placeholder.begin.c++ + 2: storage.modifier.c++onversion.c++ + 3: constant.other.format-spec.c++ + 4: punctuation.definition.placeholder.end.c++ + - match: \{(?=[^\}"']+\{[^"']*\}) # complex (nested) form + scope: punctuation.definition.placeholder.begin.c++ + push: + - meta_scope: constant.other.placeholder.c++ + - match: \} + scope: punctuation.definition.placeholder.end.c++ + pop: true + - match: '[\w.\[\]]+' + - match: '![ars]' + scope: storage.modifier.conversion.c++ + - match: ':' + push: + - meta_scope: meta.format-spec.c++ constant.other.format-spec.c++ + - match: (?=\}) + pop: true + - include: formatting-syntax + + numbers: + - include: unique-numbers + - include: scope:source.c#numbers + + ## C++-specific contexts + + case-default: + - match: '\b(default|case)\b' + scope: keyword.control.c++ + push: + - match: (?=[);,]) + pop: true + - match: ':' + scope: punctuation.separator.c++ + pop: true + - include: expressions + + modifiers-parens: + - match: '\b(alignas)\b\s*(\()' + captures: + 1: storage.modifier.c++ + 2: meta.group.c++ punctuation.section.group.begin.c++ + push: + - meta_content_scope: meta.group.c++ + - match: '\)' + scope: meta.group.c++ punctuation.section.group.end.c++ + pop: true + - include: expressions + - match: \b(__attribute__)\s*(\(\() + captures: + 1: storage.modifier.c++ + 2: meta.group.c++ punctuation.section.group.begin.c++ + push : + - meta_scope: meta.attribute.c++ + - meta_content_scope: meta.group.c++ + - include: parens + - include: strings + - match: \)\) + scope: meta.group.c++ punctuation.section.group.end.c++ + pop: true + - match: \b(__declspec)(\() + captures: + 1: storage.modifier.c++ + 2: meta.group.c++ punctuation.section.group.begin.c++ + push: + - meta_content_scope: meta.group.c++ + - match: '\)' + scope: meta.group.c++ punctuation.section.group.end.c++ + pop: true + - match: '\b(align|allocate|code_seg|deprecated|property|uuid)\b\s*(\()' + captures: + 1: storage.modifier.c++ + 2: meta.group.c++ punctuation.section.group.begin.c++ + push: + - meta_content_scope: meta.group.c++ + - match: '\)' + scope: meta.group.c++ punctuation.section.group.end.c++ + pop: true + - include: numbers + - include: strings + - match: \b(get|put)\b + scope: variable.parameter.c++ + - match: ',' + scope: punctuation.separator.c++ + - match: '=' + scope: keyword.operator.assignment.c++ + - match: '\b(appdomain|deprecated|dllimport|dllexport|jintrinsic|naked|noalias|noinline|noreturn|nothrow|novtable|process|restrict|safebuffers|selectany|thread)\b' + scope: constant.other.c++ + + types-parens: + - match: '\b(decltype)\b\s*(\()' + captures: + 1: storage.type.c++ + 2: meta.group.c++ punctuation.section.group.begin.c++ + push: + - meta_content_scope: meta.group.c++ + - match: '\)' + scope: meta.group.c++ punctuation.section.group.end.c++ + pop: true + - include: expressions + + keywords-angle-brackets: + - match: \b({{casts}})\b\s* + scope: keyword.operator.word.cast.c++ + push: + - match: '>' + scope: punctuation.section.generic.end.c++ + pop: true + - match: '<' + scope: punctuation.section.generic.begin.c++ + push: + - match: '(?=>)' + pop: true + - include: expressions-minus-generic-type-function-call + + keywords-parens: + - match: '\b(alignof|typeid|static_assert|sizeof)\b\s*(\()' + captures: + 1: keyword.operator.word.c++ + 2: meta.group.c++ punctuation.section.group.begin.c++ + push: + - meta_content_scope: meta.group.c++ + - match: '\)' + scope: meta.group.c++ punctuation.section.group.end.c++ + pop: true + - include: expressions + + namespace: + - match: '\b(using)\s+(namespace)\s+(?={{path_lookahead}})' + captures: + 1: keyword.control.c++ + 2: keyword.control.c++ + push: + - include: identifiers + - match: '' + pop: true + - match: '\b(namespace)\s+(?=({{path_lookahead}})?(?!\s*[;,]))' + scope: meta.namespace.c++ + captures: + 1: keyword.control.c++ + push: + - meta_content_scope: meta.namespace.c++ entity.name.namespace.c++ + - include: identifiers + - match: '' + set: + - meta_scope: meta.namespace.c++ + - include: comments + - match: '=' + scope: keyword.operator.alias.c++ + - match: '(?=;)' + pop: true + - match: '\}' + scope: meta.block.c++ punctuation.section.block.end.c++ + pop: true + - match: '\{' + scope: punctuation.section.block.begin.c++ + push: + - meta_scope: meta.block.c++ + - match: '(?=\})' + pop: true + - include: preprocessor-global + - include: global + - include: expressions + + template-common: + # Exit the template scope if we hit some basic invalid characters. This + # helps when a user is in the middle of typing their template types and + # prevents re-highlighting the whole file until the next > is found. + - match: (?=[{};]) + pop: true + - include: expressions + + template: + - match: \btemplate\b + scope: storage.type.template.c++ + push: + - meta_scope: meta.template.c++ + # Explicitly include comments here at the top, in order to NOT match the + # \S lookahead in the case of comments. + - include: comments + - match: < + scope: punctuation.section.generic.begin.c++ + set: + - meta_content_scope: meta.template.c++ + - match: '>' + scope: meta.template.c++ punctuation.section.generic.end.c++ + pop: true + - match: \.{3} + scope: keyword.operator.variadic.c++ + - match: \b(typename|{{before_tag}})\b + scope: storage.type.c++ + - include: template # include template here for nested templates + - include: template-common + - match: (?=\S) + set: + - meta_content_scope: meta.template.c++ + - match: \b({{before_tag}})\b + scope: storage.type.c++ + - include: template-common + + generic-type: + - match: '(?=(?!template){{path_lookahead}}\s*{{generic_lookahead}}\s*\()' + push: + - meta_scope: meta.function-call.c++ + - match: \btemplate\b + scope: storage.type.template.c++ + - match: '(?:(::)\s*)?{{identifier}}\s*(::)\s*' + captures: + 1: punctuation.accessor.double-colon.c++ + 2: punctuation.accessor.double-colon.c++ + - match: (?:(::)\s*)?({{identifier}})\s*(<) + captures: + 1: punctuation.accessor.double-colon.c++ + 2: variable.function.c++ + 3: punctuation.section.generic.begin.c++ + push: + - match: '>' + scope: punctuation.section.generic.end.c++ + pop: true + - include: expressions-minus-generic-type-function-call + - match: (?:(::)\s*)?({{identifier}})\s*(\() + captures: + 1: punctuation.accessor.double-colon.c++ + 2: variable.function.c++ + 3: punctuation.section.group.begin.c++ + set: + - meta_scope: meta.function-call.c++ + - meta_content_scope: meta.group.c++ + - match: '\)' + scope: meta.group.c++ punctuation.section.group.end.c++ + pop: true + - include: expressions + - include: angle-brackets + - match: '\(' + scope: meta.group.c++ punctuation.section.group.begin.c++ + set: + - meta_scope: meta.function-call.c++ + - meta_content_scope: meta.group.c++ + - match: '\)' + scope: meta.group.c++ punctuation.section.group.end.c++ + pop: true + - include: expressions + - match: '(?=(?!template){{path_lookahead}}\s*{{generic_lookahead}})' + push: + - include: identifiers + - match: '<' + scope: punctuation.section.generic.begin.c++ + set: + - match: '>' + scope: punctuation.section.generic.end.c++ + pop: true + - include: expressions-minus-generic-type-function-call + + angle-brackets: + - match: '<(?!<)' + scope: punctuation.section.generic.begin.c++ + push: + - match: '>' + scope: punctuation.section.generic.end.c++ + pop: true + - include: expressions-minus-generic-type-function-call + + block: + - match: '\{' + scope: punctuation.section.block.begin.c++ + push: + - meta_scope: meta.block.c++ + - match: (?=^\s*#\s*(elif|else|endif)\b) + pop: true + - match: '\}' + scope: punctuation.section.block.end.c++ + pop: true + - include: statements + + function-call: + - match: (?={{path_lookahead}}\s*\() + push: + - meta_scope: meta.function-call.c++ + - include: scope:source.c#c99 + - match: '(?:(::)\s*)?{{identifier}}\s*(::)\s*' + scope: variable.function.c++ + captures: + 1: punctuation.accessor.c++ + 2: punctuation.accessor.c++ + - match: '(?:(::)\s*)?{{identifier}}' + scope: variable.function.c++ + captures: + 1: punctuation.accessor.c++ + - match: '\(' + scope: meta.group.c++ punctuation.section.group.begin.c++ + set: + - meta_content_scope: meta.function-call.c++ meta.group.c++ + - match: '\)' + scope: meta.function-call.c++ meta.group.c++ punctuation.section.group.end.c++ + pop: true + - include: expressions + + members-inside-function-call: + - meta_content_scope: meta.method-call.c++ meta.group.c++ + - match: \) + scope: meta.method-call.c++ meta.group.c++ punctuation.section.group.end.c++ + pop: true + - include: expressions + + members-after-accessor-junction: + # After we've seen an accessor (dot or arrow), this context decides what + # kind of entity we're accessing. + - include: comments + - match: \btemplate\b + scope: meta.method-call.c++ storage.type.template.c++ + # Guaranteed to be a template member function call after we match this + set: + - meta_content_scope: meta.method-call.c++ + - include: comments + - match: '{{identifier}}' + scope: variable.function.member.c++ + set: + - meta_content_scope: meta.method-call.c++ + - match: \( + scope: meta.group.c++ punctuation.section.group.begin.c++ + set: members-inside-function-call + - include: comments + - include: angle-brackets + - match: (?=\S) # safety pop + pop: true + - match: (?=\S) # safety pop + pop: true + # Operator overloading + - match: '({{operator_method_name}})\s*(\()' + captures: + 0: meta.method-call.c++ + 1: variable.function.member.c++ + 2: meta.group.c++ punctuation.section.group.begin.c++ + set: members-inside-function-call + # Non-templated member function call + - match: (~?{{identifier}})\s*(\() + captures: + 0: meta.method-call.c++ + 1: variable.function.member.c++ + 2: meta.group.c++ punctuation.section.group.begin.c++ + set: members-inside-function-call + # Templated member function call + - match: (~?{{identifier}})\s*(?={{generic_lookahead}}) + captures: + 1: variable.function.member.c++ + set: + - meta_scope: meta.method-call.c++ + - match: < + scope: punctuation.section.generic.begin.c++ + set: + - meta_content_scope: meta.method-call.c++ + - match: '>' + scope: punctuation.section.generic.end.c++ + set: + - meta_content_scope: meta.method-call.c++ + - include: comments + - match: \( + scope: punctuation.section.group.begin.c++ + set: members-inside-function-call + - match: (?=\S) # safety pop + pop: true + - include: expressions + # Explicit base-class access + - match: ({{identifier}})\s*(::) + captures: + 1: variable.other.base-class.c++ + 2: punctuation.accessor.double-colon.c++ + set: members-after-accessor-junction # reset + # Just a regular member variable + - match: '{{identifier}}' + scope: variable.other.readwrite.member.c++ + pop: true + + members-dot: + - include: scope:source.c#access-illegal + # No lookahead required because members-dot goes after operators in the + # early-expressions-after-generic-type context. This means triple dots + # (i.e. "..." or "variadic") is attempted first. + - match: \. + scope: punctuation.accessor.dot.c++ + push: members-after-accessor-junction + + members-arrow: + # This needs to be before operators in the + # early-expressions-after-generic-type context because otherwise the "->" + # from the C language will match. + - match: -> + scope: punctuation.accessor.arrow.c++ + push: members-after-accessor-junction + + typedef: + - match: \btypedef\b + scope: storage.type.c++ + push: + - match: ({{identifier}})?\s*(?=;) + captures: + 1: entity.name.type.typedef.c++ + pop: true + - match: \b(struct)\s+({{identifier}})\b + captures: + 1: storage.type.c++ + - include: expressions-minus-generic-type + + parens: + - match: \( + scope: punctuation.section.group.begin.c++ + push: + - meta_scope: meta.group.c++ + - match: \) + scope: punctuation.section.group.end.c++ + pop: true + - include: expressions + + brackets: + - match: \[ + scope: punctuation.section.brackets.begin.c++ + push: + - meta_scope: meta.brackets.c++ + - match: \] + scope: punctuation.section.brackets.end.c++ + pop: true + - include: expressions + + function-trailing-return-type: + - match: '{{non_angle_brackets}}' + pop: true + - include: angle-brackets + - include: types + - include: modifiers-parens + - include: modifiers + - include: identifiers + - match: \*|& + scope: keyword.operator.c++ + - include: function-trailing-return-type-parens + - match: '(?=\S)' + pop: true + + function-trailing-return-type-parens: + - match: \( + scope: punctuation.section.group.begin.c++ + push: + - meta_scope: meta.group.c++ + - match: \) + scope: punctuation.section.group.end.c++ + pop: true + - include: function-trailing-return-type + + ## Detection of function and data structure definitions at the global level + + global-modifier: + - include: comments + - include: modifiers-parens + - include: modifiers + # Constructors and destructors don't have a type + - match: '(?={{path_lookahead}}\s*::\s*{{identifier}}\s*(\(|$))' + set: + - meta_content_scope: meta.function.c++ entity.name.function.constructor.c++ + - include: identifiers + - match: '(?=[^\w\s])' + set: function-definition-params + - match: '(?={{path_lookahead}}\s*::\s*~{{identifier}}\s*(\(|$))' + set: + - meta_content_scope: meta.function.c++ entity.name.function.destructor.c++ + - include: identifiers + - match: '~{{identifier}}' + - match: '(?=[^\w\s])' + set: function-definition-params + # If we see a path ending in :: before a newline, we don't know if it is + # a constructor or destructor, or a long return type, so we are just going + # to treat it like a regular function. Most likely it is a constructor, + # since it doesn't seem most developers would create such a long typename. + - match: '(?={{path_lookahead}}\s*::\s*$)' + set: + - meta_content_scope: meta.function.c++ entity.name.function.c++ + - include: identifiers + - match: '~{{identifier}}' + - match: '(?=[^\w\s])' + set: function-definition-params + - include: unique-strings + - match: '(?=\S)' + set: global-type + + global-type: + - include: comments + - match: \*|& + scope: keyword.operator.c++ + - match: '(?=\b({{control_keywords}}|{{operator_keywords}}|{{casts}}|{{memory_operators}}|{{other_keywords}}|operator)\b)' + pop: true + - match: '(?=\s)' + set: global-maybe-function + # If a class/struct/enum followed by a name that is not a macro or declspec + # then this is likely a return type of a function. This is uncommon. + - match: |- + (?x: + ({{before_tag}}) + \s+ + (?= + (?![[:upper:][:digit:]_]+\b|__declspec|{{before_tag}}) + {{path_lookahead}} + (\s+{{identifier}}\s*\(|\s*[*&]) + ) + ) + captures: + 1: storage.type.c++ + set: + - include: identifiers + - match: '' + set: global-maybe-function + # The previous match handles return types of struct/enum/etc from a func, + # there this one exits the context to allow matching an actual struct/class + - match: '(?=\b({{before_tag}})\b)' + set: data-structures + - match: '(?=\b({{casts}})\b\s*<)' + pop: true + - match: '{{non_angle_brackets}}' + pop: true + - include: angle-brackets + - include: types + # Allow a macro call + - match: '({{identifier}})\s*(\()(?=[^\)]+\))' + captures: + 1: variable.function.c++ + 2: meta.group.c++ punctuation.section.group.begin.c++ + push: + - meta_scope: meta.function-call.c++ + - meta_content_scope: meta.group.c++ + - match: '\)' + scope: meta.group.c++ punctuation.section.group.end.c++ + pop: true + - include: expressions + - match: '(?={{path_lookahead}}\s*\()' + set: + - include: function-call + - match: '' + pop: true + - include: variables + - include: constants + - include: identifiers + - match: (?=\W) + pop: true + + global-maybe-function: + - include: comments + # Consume pointer info, macros and any type info that was offset by macros + - match: \*|& + scope: keyword.operator.c++ + - match: '(?=\b({{control_keywords}}|{{operator_keywords}}|{{casts}}|{{memory_operators}}|{{other_keywords}})\b)' + pop: true + - match: '\b({{type_qualifier}})\b' + scope: storage.modifier.c++ + - match: '{{non_angle_brackets}}' + pop: true + - include: angle-brackets + - include: types + - include: modifiers-parens + - include: modifiers + # All uppercase identifier just before a newline is most likely a macro + - match: '[[:upper:][:digit:]_]+\s*$' + # Operator overloading + - match: '(?=({{path_lookahead}}\s*(?:{{generic_lookahead}})?::\s*)?{{operator_method_name}}\s*(\(|$))' + set: + - meta_content_scope: meta.function.c++ entity.name.function.c++ + - include: identifiers + - match: '(?=\s*(\(|$))' + set: function-definition-params + # Identifier that is not the function name - likely a macro or type + - match: '(?={{path_lookahead}}([ \t]+|[*&])(?!\s*(<|::|\(|$)))' + push: + - include: identifiers + - match: '' + pop: true + # Real function definition + - match: '(?={{path_lookahead}}({{generic_lookahead}}({{path_lookahead}})?)\s*(\(|$))' + set: [function-definition-params, global-function-identifier-generic] + - match: '(?={{path_lookahead}}\s*(\(|$))' + set: [function-definition-params, global-function-identifier] + - match: '(?={{path_lookahead}}\s*::\s*$)' + set: [function-definition-params, global-function-identifier] + - match: '(?=\S)' + pop: true + + global-function-identifier-generic: + - include: angle-brackets + - match: '::' + scope: punctuation.accessor.c++ + - match: '(?={{identifier}}<.*>\s*\()' + push: + - meta_content_scope: entity.name.function.c++ + - include: identifiers + - match: '(?=<)' + pop: true + - match: '(?={{identifier}}\s*\()' + push: + - meta_content_scope: entity.name.function.c++ + - include: identifiers + - match: '' + pop: true + - match: '(?=\()' + pop: true + + global-function-identifier: + - meta_content_scope: entity.name.function.c++ + - include: identifiers + - match: '(?=\S)' + pop: true + + function-definition-params: + - meta_content_scope: meta.function.c++ + - include: comments + - match: '(?=\()' + set: + - match: \( + scope: meta.function.parameters.c++ meta.group.c++ punctuation.section.group.begin.c++ + set: + - meta_content_scope: meta.function.parameters.c++ meta.group.c++ + - match : \) + scope: punctuation.section.group.end.c++ + set: function-definition-continue + - match: '\bvoid\b' + scope: storage.type.c++ + - match: '{{identifier}}(?=\s*(\[|,|\)|=))' + scope: variable.parameter.c++ + - match: '=' + scope: keyword.operator.assignment.c++ + push: + - match: '(?=,|\))' + pop: true + - include: expressions-minus-generic-type + - include: scope:source.c#preprocessor-line-continuation + - include: expressions-minus-generic-type + - include: scope:source.c#preprocessor-line-continuation + - match: (?=\S) + pop: true + + function-definition-continue: + - meta_content_scope: meta.function.c++ + - include: comments + - match: '(?=;)' + pop: true + - match: '->' + scope: punctuation.separator.c++ + set: function-definition-trailing-return + - include: function-specifiers + - match: '=' + scope: keyword.operator.assignment.c++ + - match: '&' + scope: keyword.operator.c++ + - match: \b0\b + scope: constant.numeric.c++ + - match: \b(default|delete)\b + scope: storage.modifier.c++ + - match: '(?=\{)' + set: function-definition-body + - match: '(?=\S)' + pop: true + + function-definition-trailing-return: + - include: comments + - match: '(?=;)' + pop: true + - match: '(?=\{)' + set: function-definition-body + - include: function-specifiers + - include: function-trailing-return-type + + function-definition-body: + - meta_content_scope: meta.function.c++ meta.block.c++ + - match: '\{' + scope: punctuation.section.block.begin.c++ + set: + - meta_content_scope: meta.function.c++ meta.block.c++ + - match: '\}' + scope: meta.function.c++ meta.block.c++ punctuation.section.block.end.c++ + pop: true + - match: (?=^\s*#\s*(elif|else|endif)\b) + pop: true + - match: '(?=({{before_tag}})([^(;]+$|.*\{))' + push: data-structures + - include: statements + + ## Data structures including classes, structs, unions and enums + + data-structures: + - match: '\bclass\b' + scope: storage.type.c++ + set: data-structures-class-definition + # Detect variable type definitions using struct/enum/union followed by a tag + - match: '\b({{before_tag}})(?=\s+{{path_lookahead}}\s+{{path_lookahead}}\s*[=;\[])' + scope: storage.type.c++ + - match: '\bstruct\b' + scope: storage.type.c++ + set: data-structures-struct-definition + - match: '\benum(\s+(class|struct))?\b' + scope: storage.type.c++ + set: data-structures-enum-definition + - match: '\bunion\b' + scope: storage.type.c++ + set: data-structures-union-definition + - match: '(?=\S)' + pop: true + + preprocessor-workaround-eat-macro-before-identifier: + # Handle macros so they aren't matched as the class name + - match: ({{macro_identifier}})(?=\s+~?{{identifier}}) + captures: + 1: meta.assumed-macro.c + + data-structures-class-definition: + - meta_scope: meta.class.c++ + - include: data-structures-definition-common-begin + - match: '{{identifier}}(?={{data_structures_forward_decl_lookahead}})' + scope: entity.name.class.forward-decl.c++ + set: data-structures-class-definition-after-identifier + - match: '{{identifier}}' + scope: entity.name.class.c++ + set: data-structures-class-definition-after-identifier + - match: '(?=[:{])' + set: data-structures-class-definition-after-identifier + - match: '(?=;)' + pop: true + + data-structures-class-definition-after-identifier: + - meta_content_scope: meta.class.c++ + - include: data-structures-definition-common-begin + # No matching of identifiers since they should all be macros at this point + - include: data-structures-definition-common-end + - match: '\{' + scope: meta.block.c++ punctuation.section.block.begin.c++ + set: + - meta_content_scope: meta.class.c++ meta.block.c++ + - match: '\}' + scope: meta.class.c++ meta.block.c++ punctuation.section.block.end.c++ + pop: true + - include: data-structures-body + + data-structures-struct-definition: + - meta_scope: meta.struct.c++ + - include: data-structures-definition-common-begin + - match: '{{identifier}}(?={{data_structures_forward_decl_lookahead}})' + scope: entity.name.struct.forward-decl.c++ + set: data-structures-struct-definition-after-identifier + - match: '{{identifier}}' + scope: entity.name.struct.c++ + set: data-structures-struct-definition-after-identifier + - match: '(?=[:{])' + set: data-structures-struct-definition-after-identifier + - match: '(?=;)' + pop: true + + data-structures-struct-definition-after-identifier: + - meta_content_scope: meta.struct.c++ + - include: data-structures-definition-common-begin + # No matching of identifiers since they should all be macros at this point + - include: data-structures-definition-common-end + - match: '\{' + scope: meta.block.c++ punctuation.section.block.begin.c++ + set: + - meta_content_scope: meta.struct.c++ meta.block.c++ + - match: '\}' + scope: meta.struct.c++ meta.block.c++ punctuation.section.block.end.c++ + pop: true + - include: data-structures-body + + data-structures-enum-definition: + - meta_scope: meta.enum.c++ + - include: data-structures-definition-common-begin + - match: '{{identifier}}(?={{data_structures_forward_decl_lookahead}})' + scope: entity.name.enum.forward-decl.c++ + set: data-structures-enum-definition-after-identifier + - match: '{{identifier}}' + scope: entity.name.enum.c++ + set: data-structures-enum-definition-after-identifier + - match: '(?=[:{])' + set: data-structures-enum-definition-after-identifier + - match: '(?=;)' + pop: true + + data-structures-enum-definition-after-identifier: + - meta_content_scope: meta.enum.c++ + - include: data-structures-definition-common-begin + # No matching of identifiers since they should all be macros at this point + - include: data-structures-definition-common-end + - match: '\{' + scope: meta.block.c++ punctuation.section.block.begin.c++ + set: + - meta_content_scope: meta.enum.c++ meta.block.c++ + # Enums don't support methods so we have a simplified body + - match: '\}' + scope: meta.enum.c++ meta.block.c++ punctuation.section.block.end.c++ + pop: true + - include: statements + + data-structures-union-definition: + - meta_scope: meta.union.c++ + - include: data-structures-definition-common-begin + - match: '{{identifier}}(?={{data_structures_forward_decl_lookahead}})' + scope: entity.name.union.forward-decl.c++ + set: data-structures-union-definition-after-identifier + - match: '{{identifier}}' + scope: entity.name.union.c++ + set: data-structures-union-definition-after-identifier + - match: '(?=[{])' + set: data-structures-union-definition-after-identifier + - match: '(?=;)' + pop: true + + data-structures-union-definition-after-identifier: + - meta_content_scope: meta.union.c++ + - include: data-structures-definition-common-begin + # No matching of identifiers since they should all be macros at this point + # Unions don't support base classes + - include: angle-brackets + - match: '\{' + scope: meta.block.c++ punctuation.section.block.begin.c++ + set: + - meta_content_scope: meta.union.c++ meta.block.c++ + - match: '\}' + scope: meta.union.c++ meta.block.c++ punctuation.section.block.end.c++ + pop: true + - include: data-structures-body + - match: '(?=;)' + pop: true + + data-structures-definition-common-begin: + - include: comments + - match: '(?=\b(?:{{before_tag}}|{{control_keywords}})\b)' + pop: true + - include: preprocessor-other + - include: modifiers-parens + - include: modifiers + - include: preprocessor-workaround-eat-macro-before-identifier + + data-structures-definition-common-end: + - include: angle-brackets + - match: \bfinal\b + scope: storage.modifier.c++ + - match: ':' + scope: punctuation.separator.c++ + push: + - include: comments + - include: preprocessor-other + - include: modifiers-parens + - include: modifiers + - match: '\b(virtual|{{visibility_modifiers}})\b' + scope: storage.modifier.c++ + - match: (?={{path_lookahead}}) + push: + - meta_scope: entity.other.inherited-class.c++ + - include: identifiers + - match: '' + pop: true + - include: angle-brackets + - match: ',' + scope: punctuation.separator.c++ + - match: (?=\{|;) + pop: true + - match: '(?=;)' + pop: true + + data-structures-body: + - include: preprocessor-data-structures + - match: '(?=\btemplate\b)' + push: + - include: template + - match: (?=\S) + set: data-structures-modifier + - include: typedef + - match: \b({{visibility_modifiers}})\s*(:)(?!:) + captures: + 1: storage.modifier.c++ + 2: punctuation.section.class.c++ + - match: '^\s*(?=(?:~?\w+|::))' + push: data-structures-modifier + - include: expressions-minus-generic-type + + data-structures-modifier: + - match: '\bfriend\b' + scope: storage.modifier.c++ + push: + - match: (?=;) + pop: true + - match: '\{' + scope: punctuation.section.block.begin.c++ + set: + - meta_scope: meta.block.c++ + - match: '\}' + scope: punctuation.section.block.end.c++ + pop: true + - include: statements + - match: '\b({{before_tag}})\b' + scope: storage.type.c++ + - include: expressions-minus-function-call + - include: comments + - include: modifiers-parens + - include: modifiers + - match: '\bstatic_assert(?=\s*\()' + scope: meta.static-assert.c++ keyword.operator.word.c++ + push: + - match: '\(' + scope: meta.group.c++ punctuation.section.group.begin.c++ + set: + - meta_content_scope: meta.function-call.c++ meta.group.c++ + - match: '\)' + scope: meta.function-call.c++ meta.group.c++ punctuation.section.group.end.c++ + pop: true + - include: expressions + # Destructor + - match: '(?:{{identifier}}\s*(::)\s*)?~{{identifier}}(?=\s*(\(|$))' + scope: meta.method.destructor.c++ entity.name.function.destructor.c++ + captures: + 1: punctuation.accessor.c++ + set: method-definition-params + # It's a macro, not a constructor if there is no type in the first param + - match: '({{identifier}})\s*(\()(?=\s*(?!void){{identifier}}\s*[),])' + captures: + 1: variable.function.c++ + 2: meta.group.c++ punctuation.section.group.begin.c++ + push: + - meta_scope: meta.function-call.c++ + - meta_content_scope: meta.group.c++ + - match: '\)' + scope: meta.group.c++ punctuation.section.group.end.c++ + pop: true + - include: expressions + # Constructor + - include: preprocessor-workaround-eat-macro-before-identifier + - match: '((?!{{before_tag}}|template){{identifier}})(?=\s*\()' + scope: meta.method.constructor.c++ entity.name.function.constructor.c++ + set: method-definition-params + # Long form constructor + - match: '({{identifier}}\s*(::)\s*{{identifier}})(?=\s*\()' + captures: + 1: meta.method.constructor.c++ entity.name.function.constructor.c++ + 2: punctuation.accessor.c++ + push: method-definition-params + - match: '(?=\S)' + set: data-structures-type + + data-structures-type: + - include: comments + - match: \*|& + scope: keyword.operator.c++ + # Cast methods + - match: '(operator)\s+({{identifier}})(?=\s*(\(|$))' + captures: + 1: keyword.control.c++ + 2: meta.method.c++ entity.name.function.c++ + set: method-definition-params + - match: '(?=\b({{control_keywords}}|{{operator_keywords}}|{{casts}}|{{memory_operators}}|{{other_keywords}}|operator)\b)' + pop: true + - match: '(?=\s)' + set: data-structures-maybe-method + # If a class/struct/enum followed by a name that is not a macro or declspec + # then this is likely a return type of a function. This is uncommon. + - match: |- + (?x: + ({{before_tag}}) + \s+ + (?= + (?![[:upper:][:digit:]_]+\b|__declspec|{{before_tag}}) + {{path_lookahead}} + (\s+{{identifier}}\s*\(|\s*[*&]) + ) + ) + captures: + 1: storage.type.c++ + set: + - include: identifiers + - match: '' + set: data-structures-maybe-method + # The previous match handles return types of struct/enum/etc from a func, + # there this one exits the context to allow matching an actual struct/class + - match: '(?=\b({{before_tag}})\b)' + set: data-structures + - match: '(?=\b({{casts}})\b\s*<)' + pop: true + - match: '{{non_angle_brackets}}' + pop: true + - include: angle-brackets + - include: types + - include: variables + - include: constants + - include: identifiers + - match: (?=[&*]) + set: data-structures-maybe-method + - match: (?=\W) + pop: true + + data-structures-maybe-method: + - include: comments + # Consume pointer info, macros and any type info that was offset by macros + - match: \*|& + scope: keyword.operator.c++ + - match: '(?=\b({{control_keywords}}|{{operator_keywords}}|{{casts}}|{{memory_operators}}|{{other_keywords}})\b)' + pop: true + - match: '\b({{type_qualifier}})\b' + scope: storage.modifier.c++ + - match: '{{non_angle_brackets}}' + pop: true + - include: angle-brackets + - include: types + - include: modifiers-parens + - include: modifiers + # Operator overloading + - match: '{{operator_method_name}}(?=\s*(\(|$))' + scope: meta.method.c++ entity.name.function.c++ + set: method-definition-params + # Identifier that is not the function name - likely a macro or type + - match: '(?={{path_lookahead}}([ \t]+|[*&])(?!\s*(<|::|\()))' + push: + - include: identifiers + - match: '' + pop: true + # Real function definition + - match: '(?={{path_lookahead}}({{generic_lookahead}})\s*(\())' + set: [method-definition-params, data-structures-function-identifier-generic] + - match: '(?={{path_lookahead}}\s*(\())' + set: [method-definition-params, data-structures-function-identifier] + - match: '(?={{path_lookahead}}\s*::\s*$)' + set: [method-definition-params, data-structures-function-identifier] + - match: '(?=\S)' + pop: true + + data-structures-function-identifier-generic: + - include: angle-brackets + - match: '(?={{identifier}})' + push: + - meta_content_scope: entity.name.function.c++ + - include: identifiers + - match: '(?=<)' + pop: true + - match: '(?=\()' + pop: true + + data-structures-function-identifier: + - meta_content_scope: entity.name.function.c++ + - include: identifiers + - match: '(?=\S)' + pop: true + + method-definition-params: + - meta_content_scope: meta.method.c++ + - include: comments + - match: '(?=\()' + set: + - match: \( + scope: meta.method.parameters.c++ meta.group.c++ punctuation.section.group.begin.c++ + set: + - meta_content_scope: meta.method.parameters.c++ meta.group.c++ + - match : \) + scope: punctuation.section.group.end.c++ + set: method-definition-continue + - match: '\bvoid\b' + scope: storage.type.c++ + - match: '{{identifier}}(?=\s*(\[|,|\)|=))' + scope: variable.parameter.c++ + - match: '=' + scope: keyword.operator.assignment.c++ + push: + - match: '(?=,|\))' + pop: true + - include: expressions-minus-generic-type + - include: expressions-minus-generic-type + - match: '(?=\S)' + pop: true + + method-definition-continue: + - meta_content_scope: meta.method.c++ + - include: comments + - match: '(?=;)' + pop: true + - match: '->' + scope: punctuation.separator.c++ + set: method-definition-trailing-return + - include: function-specifiers + - match: '=' + scope: keyword.operator.assignment.c++ + - match: '&' + scope: keyword.operator.c++ + - match: \b0\b + scope: constant.numeric.c++ + - match: \b(default|delete)\b + scope: storage.modifier.c++ + - match: '(?=:)' + set: + - match: ':' + scope: punctuation.separator.initializer-list.c++ + set: + - meta_scope: meta.method.constructor.initializer-list.c++ + - match: '{{identifier}}' + scope: variable.other.readwrite.member.c++ + push: + - match: \( + scope: meta.group.c++ punctuation.section.group.begin.c++ + set: + - meta_content_scope: meta.group.c++ + - match: \) + scope: meta.group.c++ punctuation.section.group.end.c++ + pop: true + - include: expressions + - match: \{ + scope: meta.group.c++ punctuation.section.group.begin.c++ + set: + - meta_content_scope: meta.group.c++ + - match: \} + scope: meta.group.c++ punctuation.section.group.end.c++ + pop: true + - include: expressions + - include: comments + - match: (?=\{|;) + set: method-definition-continue + - include: expressions + - match: '(?=\{)' + set: method-definition-body + - match: '(?=\S)' + pop: true + + method-definition-trailing-return: + - include: comments + - match: '(?=;)' + pop: true + - match: '(?=\{)' + set: method-definition-body + - include: function-specifiers + - include: function-trailing-return-type + + method-definition-body: + - meta_content_scope: meta.method.c++ meta.block.c++ + - match: '\{' + scope: punctuation.section.block.begin.c++ + set: + - meta_content_scope: meta.method.c++ meta.block.c++ + - match: '\}' + scope: meta.method.c++ meta.block.c++ punctuation.section.block.end.c++ + pop: true + - match: (?=^\s*#\s*(elif|else|endif)\b) + pop: true + - match: '(?=({{before_tag}})([^(;]+$|.*\{))' + push: data-structures + - include: statements + + ## Preprocessor for data-structures + + preprocessor-data-structures: + - include: preprocessor-rule-enabled-data-structures + - include: preprocessor-rule-disabled-data-structures + - include: preprocessor-practical-workarounds + + preprocessor-rule-disabled-data-structures: + - match: ^\s*((#if)\s+(0))\b + captures: + 1: meta.preprocessor.c++ + 2: keyword.control.import.c++ + 3: constant.numeric.preprocessor.c++ + push: + - match: ^\s*(#\s*endif)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.c++ + pop: true + - match: ^\s*(#\s*else)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.else.c++ + push: + - match: (?=^\s*#\s*endif\b) + pop: true + - include: negated-block + - include: data-structures-body + - match: "" + push: + - meta_scope: comment.block.preprocessor.if-branch.c++ + - match: (?=^\s*#\s*(else|endif)\b) + pop: true + - include: scope:source.c#preprocessor-disabled + + preprocessor-rule-enabled-data-structures: + - match: ^\s*((#if)\s+(0*1))\b + captures: + 1: meta.preprocessor.c++ + 2: keyword.control.import.c++ + 3: constant.numeric.preprocessor.c++ + push: + - match: ^\s*(#\s*endif)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.c++ + pop: true + - match: ^\s*(#\s*else)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.else.c++ + push: + - meta_content_scope: comment.block.preprocessor.else-branch.c++ + - match: (?=^\s*#\s*endif\b) + pop: true + - include: scope:source.c#preprocessor-disabled + - match: "" + push: + - match: (?=^\s*#\s*(else|endif)\b) + pop: true + - include: negated-block + - include: data-structures-body + + ## Preprocessor for global + + preprocessor-global: + - include: preprocessor-rule-enabled-global + - include: preprocessor-rule-disabled-global + - include: preprocessor-rule-other-global + + preprocessor-statements: + - include: preprocessor-rule-enabled-statements + - include: preprocessor-rule-disabled-statements + - include: preprocessor-rule-other-statements + + preprocessor-expressions: + - include: scope:source.c#incomplete-inc + - include: preprocessor-macro-define + - include: scope:source.c#pragma-mark + - include: preprocessor-other + + preprocessor-rule-disabled-global: + - match: ^\s*((#if)\s+(0))\b + captures: + 1: meta.preprocessor.c++ + 2: keyword.control.import.c++ + 3: constant.numeric.preprocessor.c++ + push: + - match: ^\s*(#\s*endif)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.c++ + pop: true + - match: ^\s*(#\s*else)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.else.c++ + push: + - match: (?=^\s*#\s*endif\b) + pop: true + - include: preprocessor-global + - include: negated-block + - include: global + - match: "" + push: + - meta_scope: comment.block.preprocessor.if-branch.c++ + - match: (?=^\s*#\s*(else|endif)\b) + pop: true + - include: scope:source.c#preprocessor-disabled + + preprocessor-rule-enabled-global: + - match: ^\s*((#if)\s+(0*1))\b + captures: + 1: meta.preprocessor.c++ + 2: keyword.control.import.c++ + 3: constant.numeric.preprocessor.c++ + push: + - match: ^\s*(#\s*endif)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.c++ + pop: true + - match: ^\s*(#\s*else)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.else.c++ + push: + - meta_content_scope: comment.block.preprocessor.else-branch.c++ + - match: (?=^\s*#\s*endif\b) + pop: true + - include: scope:source.c#preprocessor-disabled + - match: "" + push: + - match: (?=^\s*#\s*(else|endif)\b) + pop: true + - include: preprocessor-global + - include: negated-block + - include: global + + preprocessor-rule-other-global: + - match: ^\s*(#\s*(?:if|ifdef|ifndef))\b + captures: + 1: keyword.control.import.c++ + push: + - meta_scope: meta.preprocessor.c++ + - include: scope:source.c#preprocessor-line-continuation + - include: scope:source.c#preprocessor-comments + - match: \bdefined\b + scope: keyword.control.c++ + # Enter a new scope where all elif/else branches have their + # contexts popped by a subsequent elif/else/endif. This ensures that + # preprocessor branches don't push multiple meta.block scopes on + # the stack, thus messing up the "global" context's detection of + # functions. + - match: $\n + set: preprocessor-if-branch-global + + # These gymnastics here ensure that we are properly handling scope even + # when the preprocessor is used to create different scope beginnings, such + # as a different if/while condition + preprocessor-if-branch-global: + - match: ^\s*(#\s*endif)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.c++ + pop: true + - match: (?=^\s*#\s*(elif|else)\b) + push: preprocessor-elif-else-branch-global + - match: \{ + scope: punctuation.section.block.begin.c++ + set: preprocessor-block-if-branch-global + - include: preprocessor-global + - include: negated-block + - include: global + + preprocessor-block-if-branch-global: + - meta_scope: meta.block.c++ + - match: ^\s*(#\s*endif)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.c++ + set: preprocessor-block-finish-global + - match: (?=^\s*#\s*(elif|else)\b) + push: preprocessor-elif-else-branch-global + - match: \} + scope: punctuation.section.block.end.c++ + set: preprocessor-if-branch-global + - include: statements + + preprocessor-block-finish-global: + - meta_scope: meta.block.c++ + - match: ^\s*(#\s*(?:if|ifdef|ifndef))\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.c++ + set: preprocessor-block-finish-if-branch-global + - match: \} + scope: punctuation.section.block.end.c++ + pop: true + - include: statements + + preprocessor-block-finish-if-branch-global: + - match: ^\s*(#\s*endif)\b + captures: + 1: keyword.control.import.c++ + pop: true + - match: \} + scope: punctuation.section.block.end.c++ + set: preprocessor-if-branch-global + - include: statements + + preprocessor-elif-else-branch-global: + - match: (?=^\s*#\s*(endif)\b) + pop: true + - include: preprocessor-global + - include: negated-block + - include: global + + ## Preprocessor for statements + + preprocessor-rule-disabled-statements: + - match: ^\s*((#if)\s+(0))\b + captures: + 1: meta.preprocessor.c++ + 2: keyword.control.import.c++ + 3: constant.numeric.preprocessor.c++ + push: + - match: ^\s*(#\s*endif)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.c++ + pop: true + - match: ^\s*(#\s*else)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.else.c++ + push: + - match: (?=^\s*#\s*endif\b) + pop: true + - include: negated-block + - include: statements + - match: "" + push: + - meta_scope: comment.block.preprocessor.if-branch.c++ + - match: (?=^\s*#\s*(else|endif)\b) + pop: true + - include: scope:source.c#preprocessor-disabled + + preprocessor-rule-enabled-statements: + - match: ^\s*((#if)\s+(0*1))\b + captures: + 1: meta.preprocessor.c++ + 2: keyword.control.import.c++ + 3: constant.numeric.preprocessor.c++ + push: + - match: ^\s*(#\s*endif)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.c++ + pop: true + - match: ^\s*(#\s*else)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.else.c++ + push: + - meta_content_scope: comment.block.preprocessor.else-branch.c++ + - match: (?=^\s*#\s*endif\b) + pop: true + - include: scope:source.c#preprocessor-disabled + - match: "" + push: + - match: (?=^\s*#\s*(else|endif)\b) + pop: true + - include: negated-block + - include: statements + + preprocessor-rule-other-statements: + - match: ^\s*(#\s*(?:if|ifdef|ifndef))\b + captures: + 1: keyword.control.import.c++ + push: + - meta_scope: meta.preprocessor.c++ + - include: scope:source.c#preprocessor-line-continuation + - include: scope:source.c#preprocessor-comments + - match: \bdefined\b + scope: keyword.control.c++ + # Enter a new scope where all elif/else branches have their + # contexts popped by a subsequent elif/else/endif. This ensures that + # preprocessor branches don't push multiple meta.block scopes on + # the stack, thus messing up the "global" context's detection of + # functions. + - match: $\n + set: preprocessor-if-branch-statements + + # These gymnastics here ensure that we are properly handling scope even + # when the preprocessor is used to create different scope beginnings, such + # as a different if/while condition + preprocessor-if-branch-statements: + - match: ^\s*(#\s*endif)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.c++ + pop: true + - match: (?=^\s*#\s*(elif|else)\b) + push: preprocessor-elif-else-branch-statements + - match: \{ + scope: punctuation.section.block.begin.c++ + set: preprocessor-block-if-branch-statements + - match: (?=(?!{{non_func_keywords}}){{path_lookahead}}\s*\() + set: preprocessor-if-branch-function-call + - include: negated-block + - include: statements + + preprocessor-if-branch-function-call: + - meta_content_scope: meta.function-call.c++ + - include: scope:source.c#c99 + - match: '(?:(::)\s*)?{{identifier}}\s*(::)\s*' + scope: variable.function.c++ + captures: + 1: punctuation.accessor.c++ + 2: punctuation.accessor.c++ + - match: '(?:(::)\s*)?{{identifier}}' + scope: variable.function.c++ + captures: + 1: punctuation.accessor.c++ + - match: '\(' + scope: meta.group.c++ punctuation.section.group.begin.c++ + set: preprocessor-if-branch-function-call-arguments + + preprocessor-if-branch-function-call-arguments: + - meta_content_scope: meta.function-call.c++ meta.group.c++ + - match : \) + scope: meta.function-call.c++ meta.group.c++ punctuation.section.group.end.c++ + set: preprocessor-if-branch-statements + - match: ^\s*(#\s*(?:elif|else))\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.c++ + set: preprocessor-if-branch-statements + - match: ^\s*(#\s*endif)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.c++ + set: preprocessor-if-branch-function-call-arguments-finish + - include: expressions + + preprocessor-if-branch-function-call-arguments-finish: + - meta_content_scope: meta.function-call.c++ meta.group.c++ + - match: \) + scope: meta.function-call.c++ meta.group.c++ punctuation.section.group.end.c++ + pop: true + - include: expressions + + preprocessor-block-if-branch-statements: + - meta_scope: meta.block.c++ + - match: ^\s*(#\s*endif)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.c++ + set: preprocessor-block-finish-statements + - match: (?=^\s*#\s*(elif|else)\b) + push: preprocessor-elif-else-branch-statements + - match: \} + scope: punctuation.section.block.end.c++ + set: preprocessor-if-branch-statements + - include: statements + + preprocessor-block-finish-statements: + - meta_scope: meta.block.c++ + - match: ^\s*(#\s*(?:if|ifdef|ifndef))\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.c++ + set: preprocessor-block-finish-if-branch-statements + - match: \} + scope: punctuation.section.block.end.c++ + pop: true + - include: statements + + preprocessor-block-finish-if-branch-statements: + - match: ^\s*(#\s*endif)\b + captures: + 1: keyword.control.import.c++ + pop: true + - match: \} + scope: meta.block.c++ punctuation.section.block.end.c++ + set: preprocessor-if-branch-statements + - include: statements + + preprocessor-elif-else-branch-statements: + - match: (?=^\s*#\s*endif\b) + pop: true + - include: negated-block + - include: statements + + ## Preprocessor other + + negated-block: + - match: '\}' + scope: punctuation.section.block.end.c++ + push: + - match: '\{' + scope: punctuation.section.block.begin.c++ + pop: true + - match: (?=^\s*#\s*(elif|else|endif)\b) + pop: true + - include: statements + + preprocessor-macro-define: + - match: ^\s*(\#\s*define)\b + captures: + 1: meta.preprocessor.macro.c++ keyword.control.import.define.c++ + push: + - meta_content_scope: meta.preprocessor.macro.c++ + - include: scope:source.c#preprocessor-line-continuation + - include: scope:source.c#preprocessor-line-ending + - include: scope:source.c#preprocessor-comments + - match: '({{identifier}})(?=\()' + scope: entity.name.function.preprocessor.c++ + set: + - match: '\(' + scope: punctuation.section.group.begin.c++ + set: preprocessor-macro-params + - match: '{{identifier}}' + scope: entity.name.constant.preprocessor.c++ + set: preprocessor-macro-definition + + preprocessor-macro-params: + - meta_scope: meta.preprocessor.macro.parameters.c++ meta.group.c++ + - match: '{{identifier}}' + scope: variable.parameter.c++ + - match: \) + scope: punctuation.section.group.end.c++ + set: preprocessor-macro-definition + - match: ',' + scope: punctuation.separator.c++ + push: + - match: '{{identifier}}' + scope: variable.parameter.c++ + pop: true + - include: scope:source.c#preprocessor-line-continuation + - include: scope:source.c#preprocessor-comments + - match: '\.\.\.' + scope: keyword.operator.variadic.c++ + - match: '(?=\))' + pop: true + - match: (/\*).*(\*/) + scope: comment.block.c++ + captures: + 1: punctuation.definition.comment.c++ + 2: punctuation.definition.comment.c++ + - match: '\S+' + scope: invalid.illegal.unexpected-character.c++ + - include: scope:source.c#preprocessor-line-continuation + - include: scope:source.c#preprocessor-comments + - match: '\.\.\.' + scope: keyword.operator.variadic.c++ + - match: (/\*).*(\*/) + scope: comment.block.c++ + captures: + 1: punctuation.definition.comment.c++ + 2: punctuation.definition.comment.c++ + - match: $\n + scope: invalid.illegal.unexpected-end-of-line.c++ + + preprocessor-macro-definition: + - meta_content_scope: meta.preprocessor.macro.c++ + - include: scope:source.c#preprocessor-line-continuation + - include: scope:source.c#preprocessor-line-ending + - include: scope:source.c#preprocessor-comments + # Don't define blocks in define statements + - match: '\{' + scope: punctuation.section.block.begin.c++ + - match: '\}' + scope: punctuation.section.block.end.c++ + - include: expressions + + preprocessor-practical-workarounds: + - include: preprocessor-convention-ignore-uppercase-ident-lines + - include: scope:source.c#preprocessor-convention-ignore-uppercase-calls-without-semicolon + + preprocessor-convention-ignore-uppercase-ident-lines: + - match: ^(\s*{{macro_identifier}})+\s*$ + scope: meta.assumed-macro.c++ + push: + # It's possible that we are dealing with a function return type on its own line, and the + # name of the function is on the subsequent line. + - match: '(?={{path_lookahead}}({{generic_lookahead}}({{path_lookahead}})?)\s*\()' + set: [function-definition-params, global-function-identifier-generic] + - match: '(?={{path_lookahead}}\s*\()' + set: [function-definition-params, global-function-identifier] + - match: ^ + pop: true + + preprocessor-other: + - match: ^\s*(#\s*(?:if|ifdef|ifndef|elif|else|line|pragma|undef))\b + captures: + 1: keyword.control.import.c++ + push: + - meta_scope: meta.preprocessor.c++ + - include: scope:source.c#preprocessor-line-continuation + - include: scope:source.c#preprocessor-line-ending + - include: scope:source.c#preprocessor-comments + - match: \bdefined\b + scope: keyword.control.c++ + - match: ^\s*(#\s*endif)\b + captures: + 1: meta.preprocessor.c++ keyword.control.import.c++ + - match: ^\s*(#\s*(?:error|warning))\b + captures: + 1: keyword.control.import.error.c++ + push: + - meta_scope: meta.preprocessor.diagnostic.c++ + - include: scope:source.c#preprocessor-line-continuation + - include: scope:source.c#preprocessor-line-ending + - include: scope:source.c#preprocessor-comments + - include: strings + - match: '\S+' + scope: string.unquoted.c++ + - match: ^\s*(#\s*(?:include|include_next|import))\b + captures: + 1: keyword.control.import.include.c++ + push: + - meta_scope: meta.preprocessor.include.c++ + - include: scope:source.c#preprocessor-line-continuation + - include: scope:source.c#preprocessor-line-ending + - include: scope:source.c#preprocessor-comments + - match: '"' + scope: punctuation.definition.string.begin.c++ + push: + - meta_scope: string.quoted.double.include.c++ + - match: '"' + scope: punctuation.definition.string.end.c++ + pop: true + - match: < + scope: punctuation.definition.string.begin.c++ + push: + - meta_scope: string.quoted.other.lt-gt.include.c++ + - match: '>' + scope: punctuation.definition.string.end.c++ + pop: true + - include: preprocessor-practical-workarounds diff --git a/third_party/fmt/support/README b/third_party/fmt/support/README new file mode 100644 index 0000000..468f548 --- /dev/null +++ b/third_party/fmt/support/README @@ -0,0 +1,4 @@ +This directory contains build support files such as + +* CMake modules +* Build scripts diff --git a/third_party/fmt/support/Vagrantfile b/third_party/fmt/support/Vagrantfile new file mode 100644 index 0000000..9680a1a --- /dev/null +++ b/third_party/fmt/support/Vagrantfile @@ -0,0 +1,20 @@ +# -*- mode: ruby -*- +# vi: set ft=ruby : + +# A vagrant config for testing against gcc-4.8. +Vagrant.configure("2") do |config| + config.vm.box = "ubuntu/xenial64" + config.disksize.size = '15GB' + + config.vm.provider "virtualbox" do |vb| + vb.memory = "4096" + end + + config.vm.provision "shell", inline: <<-SHELL + apt-get update + apt-get install -y g++ make wget git + wget -q https://github.com/Kitware/CMake/releases/download/v3.26.0/cmake-3.26.0-Linux-x86_64.tar.gz + tar xzf cmake-3.26.0-Linux-x86_64.tar.gz + ln -s `pwd`/cmake-3.26.0-Linux-x86_64/bin/cmake /usr/local/bin + SHELL +end diff --git a/third_party/fmt/support/bazel/.bazelversion b/third_party/fmt/support/bazel/.bazelversion new file mode 100644 index 0000000..5e32542 --- /dev/null +++ b/third_party/fmt/support/bazel/.bazelversion @@ -0,0 +1 @@ +6.1.2 diff --git a/third_party/fmt/support/bazel/BUILD.bazel b/third_party/fmt/support/bazel/BUILD.bazel new file mode 100644 index 0000000..29f639b --- /dev/null +++ b/third_party/fmt/support/bazel/BUILD.bazel @@ -0,0 +1,28 @@ +cc_library( + name = "fmt", + srcs = [ + #"src/fmt.cc", # No C++ module support + "src/format.cc", + "src/os.cc", + ], + hdrs = [ + "include/fmt/args.h", + "include/fmt/chrono.h", + "include/fmt/color.h", + "include/fmt/compile.h", + "include/fmt/core.h", + "include/fmt/format.h", + "include/fmt/format-inl.h", + "include/fmt/os.h", + "include/fmt/ostream.h", + "include/fmt/printf.h", + "include/fmt/ranges.h", + "include/fmt/std.h", + "include/fmt/xchar.h", + ], + includes = [ + "include", + ], + strip_include_prefix = "include", + visibility = ["//visibility:public"], +) diff --git a/third_party/fmt/support/bazel/README.md b/third_party/fmt/support/bazel/README.md new file mode 100644 index 0000000..4c29feb --- /dev/null +++ b/third_party/fmt/support/bazel/README.md @@ -0,0 +1,74 @@ +# Bazel support + +To get [Bazel](https://bazel.build/) working with {fmt} you can copy the files `BUILD.bazel`, `WORKSPACE.bazel`, and `.bazelversion` from this folder (`support/bazel`) to the root folder of this project. This way {fmt} gets bazelized and can be used with Bazel (e.g. doing a `bazel build //...` on {fmt}). + +## Using {fmt} as a dependency + +The following minimal example shows how to use {fmt} as a dependency within a Bazel project. + +The following file structure is assumed: + +``` +example +├── BUILD.bazel +├── main.cpp +└── WORKSPACE.bazel +``` + +*main.cpp*: + +```c++ +#include "fmt/core.h" + +int main() { + fmt::print("The answer is {}\n", 42); +} +``` + +The expected output of this example is `The answer is 42`. + +*WORKSPACE.bazel*: + +```python +load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository") + +git_repository( + name = "fmt", + branch = "master", + remote = "https://github.com/fmtlib/fmt", + patch_cmds = [ + "mv support/bazel/.bazelversion .bazelversion", + "mv support/bazel/BUILD.bazel BUILD.bazel", + "mv support/bazel/WORKSPACE.bazel WORKSPACE.bazel", + ], + # Windows-related patch commands are only needed in the case MSYS2 is not installed. + # More details about the installation process of MSYS2 on Windows systems can be found here: + # https://docs.bazel.build/versions/main/install-windows.html#installing-compilers-and-language-runtimes + # Even if MSYS2 is installed the Windows related patch commands can still be used. + patch_cmds_win = [ + "Move-Item -Path support/bazel/.bazelversion -Destination .bazelversion", + "Move-Item -Path support/bazel/BUILD.bazel -Destination BUILD.bazel", + "Move-Item -Path support/bazel/WORKSPACE.bazel -Destination WORKSPACE.bazel", + ], +) +``` + +In the *WORKSPACE* file, the {fmt} GitHub repository is fetched. Using the attribute `patch_cmds` the files `BUILD.bazel`, `WORKSPACE.bazel`, and `.bazelversion` are moved to the root of the {fmt} repository. This way the {fmt} repository is recognized as a bazelized workspace. + +*BUILD.bazel*: + +```python +cc_binary( + name = "Demo", + srcs = ["main.cpp"], + deps = ["@fmt"], +) +``` + +The *BUILD* file defines a binary named `Demo` that has a dependency to {fmt}. + +To execute the binary you can run `bazel run //:Demo`. + +# Using Bzlmod + +The [Bazel Central Registry](https://github.com/bazelbuild/bazel-central-registry/tree/main/modules/fmt) also provides support for {fmt}. diff --git a/third_party/fmt/support/bazel/WORKSPACE.bazel b/third_party/fmt/support/bazel/WORKSPACE.bazel new file mode 100644 index 0000000..5be7781 --- /dev/null +++ b/third_party/fmt/support/bazel/WORKSPACE.bazel @@ -0,0 +1 @@ +workspace(name = "fmt") diff --git a/third_party/fmt/support/build-docs.py b/third_party/fmt/support/build-docs.py new file mode 100755 index 0000000..f1395cd --- /dev/null +++ b/third_party/fmt/support/build-docs.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# Build the documentation in CI. + +from __future__ import print_function +import errno, os, shutil, subprocess, sys, urllib +from subprocess import call, check_call, Popen, PIPE, STDOUT + +def rmtree_if_exists(dir): + try: + shutil.rmtree(dir) + except OSError as e: + if e.errno == errno.ENOENT: + pass + +# Build the docs. +fmt_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) +sys.path.insert(0, os.path.join(fmt_dir, 'doc')) +import build +build.create_build_env() +html_dir = build.build_docs() + +repo = 'fmtlib.github.io' +branch = os.environ['GITHUB_REF'] +is_ci = 'CI' in os.environ +if is_ci and branch != 'refs/heads/master': + print('Branch: ' + branch) + exit(0) # Ignore non-master branches +if is_ci and 'KEY' not in os.environ: + # Don't update the repo if building in CI from an account that doesn't have + # push access. + print('Skipping update of ' + repo) + exit(0) + +# Clone the fmtlib.github.io repo. +rmtree_if_exists(repo) +git_url = 'https://github.com/' if is_ci else 'git@github.com:' +check_call(['git', 'clone', git_url + 'fmtlib/{}.git'.format(repo)]) + +# Copy docs to the repo. +target_dir = os.path.join(repo, 'dev') +rmtree_if_exists(target_dir) +shutil.copytree(html_dir, target_dir, ignore=shutil.ignore_patterns('.*')) +if is_ci: + check_call(['git', 'config', '--global', 'user.name', 'fmtbot']) + check_call(['git', 'config', '--global', 'user.email', 'viz@fmt.dev']) + +# Push docs to GitHub pages. +check_call(['git', 'add', '--all'], cwd=repo) +if call(['git', 'diff-index', '--quiet', 'HEAD'], cwd=repo): + check_call(['git', 'commit', '-m', 'Update documentation'], cwd=repo) + cmd = 'git push' + if is_ci: + cmd += ' https://$KEY@github.com/fmtlib/fmtlib.github.io.git master' + p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT, cwd=repo) + # Print the output without the key. + print(p.communicate()[0].decode('utf-8').replace(os.environ['KEY'], '$KEY')) + if p.returncode != 0: + raise subprocess.CalledProcessError(p.returncode, cmd) diff --git a/third_party/fmt/support/build.gradle b/third_party/fmt/support/build.gradle new file mode 100644 index 0000000..c5126d0 --- /dev/null +++ b/third_party/fmt/support/build.gradle @@ -0,0 +1,132 @@ +import java.nio.file.Paths + +// General gradle arguments for root project +buildscript { + repositories { + google() + jcenter() + } + dependencies { + // + // https://developer.android.com/studio/releases/gradle-plugin#updating-gradle + // + // Notice that 4.0.0 here is the version of [Android Gradle Plugin] + // According to URL above you will need Gradle 6.1 or higher + // + classpath "com.android.tools.build:gradle:4.1.1" + } +} +repositories { + google() + jcenter() +} + +// Project's root where CMakeLists.txt exists: rootDir/support/.cxx -> rootDir +def rootDir = Paths.get(project.buildDir.getParent()).getParent() +println("rootDir: ${rootDir}") + +// Output: Shared library (.so) for Android +apply plugin: "com.android.library" +android { + compileSdkVersion 25 // Android 7.0 + + // Target ABI + // - This option controls target platform of module + // - The platform might be limited by compiler's support + // some can work with Clang(default), but some can work only with GCC... + // if bad, both toolchains might not support it + splits { + abi { + enable true + // Specify platforms for Application + reset() + include "arm64-v8a", "armeabi-v7a", "x86_64" + } + } + ndkVersion "21.3.6528147" // ANDROID_NDK_HOME is deprecated. Be explicit + + defaultConfig { + minSdkVersion 21 // Android 5.0+ + targetSdkVersion 25 // Follow Compile SDK + versionCode 34 // Follow release count + versionName "7.1.2" // Follow Official version + + externalNativeBuild { + cmake { + arguments "-DANDROID_STL=c++_shared" // Specify Android STL + arguments "-DBUILD_SHARED_LIBS=true" // Build shared object + arguments "-DFMT_TEST=false" // Skip test + arguments "-DFMT_DOC=false" // Skip document + cppFlags "-std=c++17" + targets "fmt" + } + } + println(externalNativeBuild.cmake.cppFlags) + println(externalNativeBuild.cmake.arguments) + } + + // External Native build + // - Use existing CMakeList.txt + // - Give path to CMake. This gradle file should be + // neighbor of the top level cmake + externalNativeBuild { + cmake { + version "3.10.0+" + path "${rootDir}/CMakeLists.txt" + // buildStagingDirectory "./build" // Custom path for cmake output + } + } + + sourceSets{ + // Android Manifest for Gradle + main { + manifest.srcFile "AndroidManifest.xml" + } + } + + // https://developer.android.com/studio/build/native-dependencies#build_system_configuration + buildFeatures { + prefab true + prefabPublishing true + } + prefab { + fmt { + headers "${rootDir}/include" + } + } +} + +assemble.doLast +{ + // Instead of `ninja install`, Gradle will deploy the files. + // We are doing this since FMT is dependent to the ANDROID_STL after build + copy { + from "build/intermediates/cmake" + into "${rootDir}/libs" + } + // Copy debug binaries + copy { + from "${rootDir}/libs/debug/obj" + into "${rootDir}/libs/debug" + } + // Copy Release binaries + copy { + from "${rootDir}/libs/release/obj" + into "${rootDir}/libs/release" + } + // Remove empty directory + delete "${rootDir}/libs/debug/obj" + delete "${rootDir}/libs/release/obj" + + // Copy AAR files. Notice that the aar is named after the folder of this script. + copy { + from "build/outputs/aar/support-release.aar" + into "${rootDir}/libs" + rename "support-release.aar", "fmt-release.aar" + } + copy { + from "build/outputs/aar/support-debug.aar" + into "${rootDir}/libs" + rename "support-debug.aar", "fmt-debug.aar" + } +} diff --git a/third_party/fmt/support/cmake/FindSetEnv.cmake b/third_party/fmt/support/cmake/FindSetEnv.cmake new file mode 100644 index 0000000..4e2da54 --- /dev/null +++ b/third_party/fmt/support/cmake/FindSetEnv.cmake @@ -0,0 +1,7 @@ +# A CMake script to find SetEnv.cmd. + +find_program(WINSDK_SETENV NAMES SetEnv.cmd + PATHS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows;CurrentInstallFolder]/bin") +if (WINSDK_SETENV AND PRINT_PATH) + execute_process(COMMAND ${CMAKE_COMMAND} -E echo "${WINSDK_SETENV}") +endif () diff --git a/third_party/fmt/support/cmake/JoinPaths.cmake b/third_party/fmt/support/cmake/JoinPaths.cmake new file mode 100644 index 0000000..32d6d66 --- /dev/null +++ b/third_party/fmt/support/cmake/JoinPaths.cmake @@ -0,0 +1,26 @@ +# This module provides function for joining paths +# known from from most languages +# +# Original license: +# SPDX-License-Identifier: (MIT OR CC0-1.0) +# Explicit permission given to distribute this module under +# the terms of the project as described in /LICENSE.rst. +# Copyright 2020 Jan Tojnar +# https://github.com/jtojnar/cmake-snips +# +# Modelled after Python’s os.path.join +# https://docs.python.org/3.7/library/os.path.html#os.path.join +# Windows not supported +function(join_paths joined_path first_path_segment) + set(temp_path "${first_path_segment}") + foreach(current_segment IN LISTS ARGN) + if(NOT ("${current_segment}" STREQUAL "")) + if(IS_ABSOLUTE "${current_segment}") + set(temp_path "${current_segment}") + else() + set(temp_path "${temp_path}/${current_segment}") + endif() + endif() + endforeach() + set(${joined_path} "${temp_path}" PARENT_SCOPE) +endfunction() diff --git a/third_party/fmt/support/cmake/fmt-config.cmake.in b/third_party/fmt/support/cmake/fmt-config.cmake.in new file mode 100644 index 0000000..bc1684f --- /dev/null +++ b/third_party/fmt/support/cmake/fmt-config.cmake.in @@ -0,0 +1,7 @@ +@PACKAGE_INIT@ + +if (NOT TARGET fmt::fmt) + include(${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake) +endif () + +check_required_components(fmt) diff --git a/third_party/fmt/support/cmake/fmt.pc.in b/third_party/fmt/support/cmake/fmt.pc.in new file mode 100644 index 0000000..29976a8 --- /dev/null +++ b/third_party/fmt/support/cmake/fmt.pc.in @@ -0,0 +1,11 @@ +prefix=@CMAKE_INSTALL_PREFIX@ +exec_prefix=@CMAKE_INSTALL_PREFIX@ +libdir=@libdir_for_pc_file@ +includedir=@includedir_for_pc_file@ + +Name: fmt +Description: A modern formatting library +Version: @FMT_VERSION@ +Libs: -L${libdir} -l@FMT_LIB_NAME@ +Cflags: -I${includedir} + diff --git a/third_party/fmt/support/compute-powers.py b/third_party/fmt/support/compute-powers.py new file mode 100755 index 0000000..601063d --- /dev/null +++ b/third_party/fmt/support/compute-powers.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# Compute 10 ** exp with exp in the range [min_exponent, max_exponent] and print +# normalized (with most-significant bit equal to 1) significands in hexadecimal. + +from __future__ import print_function + +min_exponent = -348 +max_exponent = 340 +step = 8 +significand_size = 64 +exp_offset = 2000 + +class fp: + pass + +powers = [] +for i, exp in enumerate(range(min_exponent, max_exponent + 1, step)): + result = fp() + n = 10 ** exp if exp >= 0 else 2 ** exp_offset / 10 ** -exp + k = significand_size + 1 + # Convert to binary and round. + binary = '{:b}'.format(n) + result.f = (int('{:0<{}}'.format(binary[:k], k), 2) + 1) / 2 + result.e = len(binary) - (exp_offset if exp < 0 else 0) - significand_size + powers.append(result) + # Sanity check. + exp_offset10 = 400 + actual = result.f * 10 ** exp_offset10 + if result.e > 0: + actual *= 2 ** result.e + else: + for j in range(-result.e): + actual /= 2 + expected = 10 ** (exp_offset10 + exp) + precision = len('{}'.format(expected)) - len('{}'.format(actual - expected)) + if precision < 19: + print('low precision:', precision) + exit(1) + +print('Significands:', end='') +for i, fp in enumerate(powers): + if i % 3 == 0: + print(end='\n ') + print(' {:0<#16x}'.format(fp.f, ), end=',') + +print('\n\nExponents:', end='') +for i, fp in enumerate(powers): + if i % 11 == 0: + print(end='\n ') + print(' {:5}'.format(fp.e), end=',') + +print('\n\nMax exponent difference:', + max([x.e - powers[i - 1].e for i, x in enumerate(powers)][1:])) diff --git a/third_party/fmt/support/docopt.py b/third_party/fmt/support/docopt.py new file mode 100644 index 0000000..2e43f7c --- /dev/null +++ b/third_party/fmt/support/docopt.py @@ -0,0 +1,581 @@ +"""Pythonic command-line interface parser that will make you smile. + + * http://docopt.org + * Repository and issue-tracker: https://github.com/docopt/docopt + * Licensed under terms of MIT license (see LICENSE-MIT) + * Copyright (c) 2013 Vladimir Keleshev, vladimir@keleshev.com + +""" +import sys +import re + + +__all__ = ['docopt'] +__version__ = '0.6.1' + + +class DocoptLanguageError(Exception): + + """Error in construction of usage-message by developer.""" + + +class DocoptExit(SystemExit): + + """Exit in case user invoked program with incorrect arguments.""" + + usage = '' + + def __init__(self, message=''): + SystemExit.__init__(self, (message + '\n' + self.usage).strip()) + + +class Pattern(object): + + def __eq__(self, other): + return repr(self) == repr(other) + + def __hash__(self): + return hash(repr(self)) + + def fix(self): + self.fix_identities() + self.fix_repeating_arguments() + return self + + def fix_identities(self, uniq=None): + """Make pattern-tree tips point to same object if they are equal.""" + if not hasattr(self, 'children'): + return self + uniq = list(set(self.flat())) if uniq is None else uniq + for i, child in enumerate(self.children): + if not hasattr(child, 'children'): + assert child in uniq + self.children[i] = uniq[uniq.index(child)] + else: + child.fix_identities(uniq) + + def fix_repeating_arguments(self): + """Fix elements that should accumulate/increment values.""" + either = [list(child.children) for child in transform(self).children] + for case in either: + for e in [child for child in case if case.count(child) > 1]: + if type(e) is Argument or type(e) is Option and e.argcount: + if e.value is None: + e.value = [] + elif type(e.value) is not list: + e.value = e.value.split() + if type(e) is Command or type(e) is Option and e.argcount == 0: + e.value = 0 + return self + + +def transform(pattern): + """Expand pattern into an (almost) equivalent one, but with single Either. + + Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d) + Quirks: [-a] => (-a), (-a...) => (-a -a) + + """ + result = [] + groups = [[pattern]] + while groups: + children = groups.pop(0) + parents = [Required, Optional, OptionsShortcut, Either, OneOrMore] + if any(t in map(type, children) for t in parents): + child = [c for c in children if type(c) in parents][0] + children.remove(child) + if type(child) is Either: + for c in child.children: + groups.append([c] + children) + elif type(child) is OneOrMore: + groups.append(child.children * 2 + children) + else: + groups.append(child.children + children) + else: + result.append(children) + return Either(*[Required(*e) for e in result]) + + +class LeafPattern(Pattern): + + """Leaf/terminal node of a pattern tree.""" + + def __init__(self, name, value=None): + self.name, self.value = name, value + + def __repr__(self): + return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.value) + + def flat(self, *types): + return [self] if not types or type(self) in types else [] + + def match(self, left, collected=None): + collected = [] if collected is None else collected + pos, match = self.single_match(left) + if match is None: + return False, left, collected + left_ = left[:pos] + left[pos + 1:] + same_name = [a for a in collected if a.name == self.name] + if type(self.value) in (int, list): + if type(self.value) is int: + increment = 1 + else: + increment = ([match.value] if type(match.value) is str + else match.value) + if not same_name: + match.value = increment + return True, left_, collected + [match] + same_name[0].value += increment + return True, left_, collected + return True, left_, collected + [match] + + +class BranchPattern(Pattern): + + """Branch/inner node of a pattern tree.""" + + def __init__(self, *children): + self.children = list(children) + + def __repr__(self): + return '%s(%s)' % (self.__class__.__name__, + ', '.join(repr(a) for a in self.children)) + + def flat(self, *types): + if type(self) in types: + return [self] + return sum([child.flat(*types) for child in self.children], []) + + +class Argument(LeafPattern): + + def single_match(self, left): + for n, pattern in enumerate(left): + if type(pattern) is Argument: + return n, Argument(self.name, pattern.value) + return None, None + + @classmethod + def parse(class_, source): + name = re.findall('(<\S*?>)', source)[0] + value = re.findall('\[default: (.*)\]', source, flags=re.I) + return class_(name, value[0] if value else None) + + +class Command(Argument): + + def __init__(self, name, value=False): + self.name, self.value = name, value + + def single_match(self, left): + for n, pattern in enumerate(left): + if type(pattern) is Argument: + if pattern.value == self.name: + return n, Command(self.name, True) + else: + break + return None, None + + +class Option(LeafPattern): + + def __init__(self, short=None, long=None, argcount=0, value=False): + assert argcount in (0, 1) + self.short, self.long, self.argcount = short, long, argcount + self.value = None if value is False and argcount else value + + @classmethod + def parse(class_, option_description): + short, long, argcount, value = None, None, 0, False + options, _, description = option_description.strip().partition(' ') + options = options.replace(',', ' ').replace('=', ' ') + for s in options.split(): + if s.startswith('--'): + long = s + elif s.startswith('-'): + short = s + else: + argcount = 1 + if argcount: + matched = re.findall('\[default: (.*)\]', description, flags=re.I) + value = matched[0] if matched else None + return class_(short, long, argcount, value) + + def single_match(self, left): + for n, pattern in enumerate(left): + if self.name == pattern.name: + return n, pattern + return None, None + + @property + def name(self): + return self.long or self.short + + def __repr__(self): + return 'Option(%r, %r, %r, %r)' % (self.short, self.long, + self.argcount, self.value) + + +class Required(BranchPattern): + + def match(self, left, collected=None): + collected = [] if collected is None else collected + l = left + c = collected + for pattern in self.children: + matched, l, c = pattern.match(l, c) + if not matched: + return False, left, collected + return True, l, c + + +class Optional(BranchPattern): + + def match(self, left, collected=None): + collected = [] if collected is None else collected + for pattern in self.children: + m, left, collected = pattern.match(left, collected) + return True, left, collected + + +class OptionsShortcut(Optional): + + """Marker/placeholder for [options] shortcut.""" + + +class OneOrMore(BranchPattern): + + def match(self, left, collected=None): + assert len(self.children) == 1 + collected = [] if collected is None else collected + l = left + c = collected + l_ = None + matched = True + times = 0 + while matched: + # could it be that something didn't match but changed l or c? + matched, l, c = self.children[0].match(l, c) + times += 1 if matched else 0 + if l_ == l: + break + l_ = l + if times >= 1: + return True, l, c + return False, left, collected + + +class Either(BranchPattern): + + def match(self, left, collected=None): + collected = [] if collected is None else collected + outcomes = [] + for pattern in self.children: + matched, _, _ = outcome = pattern.match(left, collected) + if matched: + outcomes.append(outcome) + if outcomes: + return min(outcomes, key=lambda outcome: len(outcome[1])) + return False, left, collected + + +class Tokens(list): + + def __init__(self, source, error=DocoptExit): + self += source.split() if hasattr(source, 'split') else source + self.error = error + + @staticmethod + def from_pattern(source): + source = re.sub(r'([\[\]\(\)\|]|\.\.\.)', r' \1 ', source) + source = [s for s in re.split('\s+|(\S*<.*?>)', source) if s] + return Tokens(source, error=DocoptLanguageError) + + def move(self): + return self.pop(0) if len(self) else None + + def current(self): + return self[0] if len(self) else None + + +def parse_long(tokens, options): + """long ::= '--' chars [ ( ' ' | '=' ) chars ] ;""" + long, eq, value = tokens.move().partition('=') + assert long.startswith('--') + value = None if eq == value == '' else value + similar = [o for o in options if o.long == long] + if tokens.error is DocoptExit and similar == []: # if no exact match + similar = [o for o in options if o.long and o.long.startswith(long)] + if len(similar) > 1: # might be simply specified ambiguously 2+ times? + raise tokens.error('%s is not a unique prefix: %s?' % + (long, ', '.join(o.long for o in similar))) + elif len(similar) < 1: + argcount = 1 if eq == '=' else 0 + o = Option(None, long, argcount) + options.append(o) + if tokens.error is DocoptExit: + o = Option(None, long, argcount, value if argcount else True) + else: + o = Option(similar[0].short, similar[0].long, + similar[0].argcount, similar[0].value) + if o.argcount == 0: + if value is not None: + raise tokens.error('%s must not have an argument' % o.long) + else: + if value is None: + if tokens.current() in [None, '--']: + raise tokens.error('%s requires argument' % o.long) + value = tokens.move() + if tokens.error is DocoptExit: + o.value = value if value is not None else True + return [o] + + +def parse_shorts(tokens, options): + """shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ;""" + token = tokens.move() + assert token.startswith('-') and not token.startswith('--') + left = token.lstrip('-') + parsed = [] + while left != '': + short, left = '-' + left[0], left[1:] + similar = [o for o in options if o.short == short] + if len(similar) > 1: + raise tokens.error('%s is specified ambiguously %d times' % + (short, len(similar))) + elif len(similar) < 1: + o = Option(short, None, 0) + options.append(o) + if tokens.error is DocoptExit: + o = Option(short, None, 0, True) + else: # why copying is necessary here? + o = Option(short, similar[0].long, + similar[0].argcount, similar[0].value) + value = None + if o.argcount != 0: + if left == '': + if tokens.current() in [None, '--']: + raise tokens.error('%s requires argument' % short) + value = tokens.move() + else: + value = left + left = '' + if tokens.error is DocoptExit: + o.value = value if value is not None else True + parsed.append(o) + return parsed + + +def parse_pattern(source, options): + tokens = Tokens.from_pattern(source) + result = parse_expr(tokens, options) + if tokens.current() is not None: + raise tokens.error('unexpected ending: %r' % ' '.join(tokens)) + return Required(*result) + + +def parse_expr(tokens, options): + """expr ::= seq ( '|' seq )* ;""" + seq = parse_seq(tokens, options) + if tokens.current() != '|': + return seq + result = [Required(*seq)] if len(seq) > 1 else seq + while tokens.current() == '|': + tokens.move() + seq = parse_seq(tokens, options) + result += [Required(*seq)] if len(seq) > 1 else seq + return [Either(*result)] if len(result) > 1 else result + + +def parse_seq(tokens, options): + """seq ::= ( atom [ '...' ] )* ;""" + result = [] + while tokens.current() not in [None, ']', ')', '|']: + atom = parse_atom(tokens, options) + if tokens.current() == '...': + atom = [OneOrMore(*atom)] + tokens.move() + result += atom + return result + + +def parse_atom(tokens, options): + """atom ::= '(' expr ')' | '[' expr ']' | 'options' + | long | shorts | argument | command ; + """ + token = tokens.current() + result = [] + if token in '([': + tokens.move() + matching, pattern = {'(': [')', Required], '[': [']', Optional]}[token] + result = pattern(*parse_expr(tokens, options)) + if tokens.move() != matching: + raise tokens.error("unmatched '%s'" % token) + return [result] + elif token == 'options': + tokens.move() + return [OptionsShortcut()] + elif token.startswith('--') and token != '--': + return parse_long(tokens, options) + elif token.startswith('-') and token not in ('-', '--'): + return parse_shorts(tokens, options) + elif token.startswith('<') and token.endswith('>') or token.isupper(): + return [Argument(tokens.move())] + else: + return [Command(tokens.move())] + + +def parse_argv(tokens, options, options_first=False): + """Parse command-line argument vector. + + If options_first: + argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ; + else: + argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ; + + """ + parsed = [] + while tokens.current() is not None: + if tokens.current() == '--': + return parsed + [Argument(None, v) for v in tokens] + elif tokens.current().startswith('--'): + parsed += parse_long(tokens, options) + elif tokens.current().startswith('-') and tokens.current() != '-': + parsed += parse_shorts(tokens, options) + elif options_first: + return parsed + [Argument(None, v) for v in tokens] + else: + parsed.append(Argument(None, tokens.move())) + return parsed + + +def parse_defaults(doc): + defaults = [] + for s in parse_section('options:', doc): + # FIXME corner case "bla: options: --foo" + _, _, s = s.partition(':') # get rid of "options:" + split = re.split('\n[ \t]*(-\S+?)', '\n' + s)[1:] + split = [s1 + s2 for s1, s2 in zip(split[::2], split[1::2])] + options = [Option.parse(s) for s in split if s.startswith('-')] + defaults += options + return defaults + + +def parse_section(name, source): + pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)', + re.IGNORECASE | re.MULTILINE) + return [s.strip() for s in pattern.findall(source)] + + +def formal_usage(section): + _, _, section = section.partition(':') # drop "usage:" + pu = section.split() + return '( ' + ' '.join(') | (' if s == pu[0] else s for s in pu[1:]) + ' )' + + +def extras(help, version, options, doc): + if help and any((o.name in ('-h', '--help')) and o.value for o in options): + print(doc.strip("\n")) + sys.exit() + if version and any(o.name == '--version' and o.value for o in options): + print(version) + sys.exit() + + +class Dict(dict): + def __repr__(self): + return '{%s}' % ',\n '.join('%r: %r' % i for i in sorted(self.items())) + + +def docopt(doc, argv=None, help=True, version=None, options_first=False): + """Parse `argv` based on command-line interface described in `doc`. + + `docopt` creates your command-line interface based on its + description that you pass as `doc`. Such description can contain + --options, , commands, which could be + [optional], (required), (mutually | exclusive) or repeated... + + Parameters + ---------- + doc : str + Description of your command-line interface. + argv : list of str, optional + Argument vector to be parsed. sys.argv[1:] is used if not + provided. + help : bool (default: True) + Set to False to disable automatic help on -h or --help + options. + version : any object + If passed, the object will be printed if --version is in + `argv`. + options_first : bool (default: False) + Set to True to require options precede positional arguments, + i.e. to forbid options and positional arguments intermix. + + Returns + ------- + args : dict + A dictionary, where keys are names of command-line elements + such as e.g. "--verbose" and "", and values are the + parsed values of those elements. + + Example + ------- + >>> from docopt import docopt + >>> doc = ''' + ... Usage: + ... my_program tcp [--timeout=] + ... my_program serial [--baud=] [--timeout=] + ... my_program (-h | --help | --version) + ... + ... Options: + ... -h, --help Show this screen and exit. + ... --baud= Baudrate [default: 9600] + ... ''' + >>> argv = ['tcp', '127.0.0.1', '80', '--timeout', '30'] + >>> docopt(doc, argv) + {'--baud': '9600', + '--help': False, + '--timeout': '30', + '--version': False, + '': '127.0.0.1', + '': '80', + 'serial': False, + 'tcp': True} + + See also + -------- + * For video introduction see http://docopt.org + * Full documentation is available in README.rst as well as online + at https://github.com/docopt/docopt#readme + + """ + argv = sys.argv[1:] if argv is None else argv + + usage_sections = parse_section('usage:', doc) + if len(usage_sections) == 0: + raise DocoptLanguageError('"usage:" (case-insensitive) not found.') + if len(usage_sections) > 1: + raise DocoptLanguageError('More than one "usage:" (case-insensitive).') + DocoptExit.usage = usage_sections[0] + + options = parse_defaults(doc) + pattern = parse_pattern(formal_usage(DocoptExit.usage), options) + # [default] syntax for argument is disabled + #for a in pattern.flat(Argument): + # same_name = [d for d in arguments if d.name == a.name] + # if same_name: + # a.value = same_name[0].value + argv = parse_argv(Tokens(argv), list(options), options_first) + pattern_options = set(pattern.flat(Option)) + for options_shortcut in pattern.flat(OptionsShortcut): + doc_options = parse_defaults(doc) + options_shortcut.children = list(set(doc_options) - pattern_options) + #if any_options: + # options_shortcut.children += [Option(o.short, o.long, o.argcount) + # for o in argv if type(o) is Option] + extras(help, version, argv, doc) + matched, left, collected = pattern.fix().match(argv) + if matched and left == []: # better error message if left? + return Dict((a.name, a.value) for a in (pattern.flat() + collected)) + raise DocoptExit() diff --git a/third_party/fmt/support/manage.py b/third_party/fmt/support/manage.py new file mode 100755 index 0000000..cfb4979 --- /dev/null +++ b/third_party/fmt/support/manage.py @@ -0,0 +1,329 @@ +#!/usr/bin/env python3 + +"""Manage site and releases. + +Usage: + manage.py release [] + manage.py site + +For the release command $FMT_TOKEN should contain a GitHub personal access token +obtained from https://github.com/settings/tokens. +""" + +from __future__ import print_function +import datetime, docopt, errno, fileinput, json, os +import re, requests, shutil, sys +from contextlib import contextmanager +from distutils.version import LooseVersion +from subprocess import check_call + + +class Git: + def __init__(self, dir): + self.dir = dir + + def call(self, method, args, **kwargs): + return check_call(['git', method] + list(args), **kwargs) + + def add(self, *args): + return self.call('add', args, cwd=self.dir) + + def checkout(self, *args): + return self.call('checkout', args, cwd=self.dir) + + def clean(self, *args): + return self.call('clean', args, cwd=self.dir) + + def clone(self, *args): + return self.call('clone', list(args) + [self.dir]) + + def commit(self, *args): + return self.call('commit', args, cwd=self.dir) + + def pull(self, *args): + return self.call('pull', args, cwd=self.dir) + + def push(self, *args): + return self.call('push', args, cwd=self.dir) + + def reset(self, *args): + return self.call('reset', args, cwd=self.dir) + + def update(self, *args): + clone = not os.path.exists(self.dir) + if clone: + self.clone(*args) + return clone + + +def clean_checkout(repo, branch): + repo.clean('-f', '-d') + repo.reset('--hard') + repo.checkout(branch) + + +class Runner: + def __init__(self, cwd): + self.cwd = cwd + + def __call__(self, *args, **kwargs): + kwargs['cwd'] = kwargs.get('cwd', self.cwd) + check_call(args, **kwargs) + + +def create_build_env(): + """Create a build environment.""" + class Env: + pass + env = Env() + + # Import the documentation build module. + env.fmt_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + sys.path.insert(0, os.path.join(env.fmt_dir, 'doc')) + import build + + env.build_dir = 'build' + env.versions = build.versions + + # Virtualenv and repos are cached to speed up builds. + build.create_build_env(os.path.join(env.build_dir, 'virtualenv')) + + env.fmt_repo = Git(os.path.join(env.build_dir, 'fmt')) + return env + + +@contextmanager +def rewrite(filename): + class Buffer: + pass + buffer = Buffer() + if not os.path.exists(filename): + buffer.data = '' + yield buffer + return + with open(filename) as f: + buffer.data = f.read() + yield buffer + with open(filename, 'w') as f: + f.write(buffer.data) + + +fmt_repo_url = 'git@github.com:fmtlib/fmt' + + +def update_site(env): + env.fmt_repo.update(fmt_repo_url) + + doc_repo = Git(os.path.join(env.build_dir, 'fmtlib.github.io')) + doc_repo.update('git@github.com:fmtlib/fmtlib.github.io') + + for version in env.versions: + clean_checkout(env.fmt_repo, version) + target_doc_dir = os.path.join(env.fmt_repo.dir, 'doc') + # Remove the old theme. + for entry in os.listdir(target_doc_dir): + path = os.path.join(target_doc_dir, entry) + if os.path.isdir(path): + shutil.rmtree(path) + # Copy the new theme. + for entry in ['_static', '_templates', 'basic-bootstrap', 'bootstrap', + 'conf.py', 'fmt.less']: + src = os.path.join(env.fmt_dir, 'doc', entry) + dst = os.path.join(target_doc_dir, entry) + copy = shutil.copytree if os.path.isdir(src) else shutil.copyfile + copy(src, dst) + # Rename index to contents. + contents = os.path.join(target_doc_dir, 'contents.rst') + if not os.path.exists(contents): + os.rename(os.path.join(target_doc_dir, 'index.rst'), contents) + # Fix issues in reference.rst/api.rst. + for filename in ['reference.rst', 'api.rst', 'index.rst']: + pattern = re.compile('doxygenfunction.. (bin|oct|hexu|hex)$', re.M) + with rewrite(os.path.join(target_doc_dir, filename)) as b: + b.data = b.data.replace('std::ostream &', 'std::ostream&') + b.data = re.sub(pattern, r'doxygenfunction:: \1(int)', b.data) + b.data = b.data.replace('std::FILE*', 'std::FILE *') + b.data = b.data.replace('unsigned int', 'unsigned') + #b.data = b.data.replace('operator""_', 'operator"" _') + b.data = b.data.replace( + 'format_to_n(OutputIt, size_t, string_view, Args&&', + 'format_to_n(OutputIt, size_t, const S&, const Args&') + b.data = b.data.replace( + 'format_to_n(OutputIt, std::size_t, string_view, Args&&', + 'format_to_n(OutputIt, std::size_t, const S&, const Args&') + if version == ('3.0.2'): + b.data = b.data.replace( + 'fprintf(std::ostream&', 'fprintf(std::ostream &') + if version == ('5.3.0'): + b.data = b.data.replace( + 'format_to(OutputIt, const S&, const Args&...)', + 'format_to(OutputIt, const S &, const Args &...)') + if version.startswith('5.') or version.startswith('6.'): + b.data = b.data.replace(', size_t', ', std::size_t') + if version.startswith('7.'): + b.data = b.data.replace(', std::size_t', ', size_t') + b.data = b.data.replace('join(It, It', 'join(It, Sentinel') + if version.startswith('7.1.'): + b.data = b.data.replace(', std::size_t', ', size_t') + b.data = b.data.replace('join(It, It', 'join(It, Sentinel') + b.data = b.data.replace( + 'fmt::format_to(OutputIt, const S&, Args&&...)', + 'fmt::format_to(OutputIt, const S&, Args&&...) -> ' + + 'typename std::enable_if::type') + b.data = b.data.replace('aa long', 'a long') + b.data = b.data.replace('serveral', 'several') + if version.startswith('6.2.'): + b.data = b.data.replace( + 'vformat(const S&, basic_format_args<' + + 'buffer_context>)', + 'vformat(const S&, basic_format_args<' + + 'buffer_context>>)') + # Fix a broken link in index.rst. + index = os.path.join(target_doc_dir, 'index.rst') + with rewrite(index) as b: + b.data = b.data.replace( + 'doc/latest/index.html#format-string-syntax', 'syntax.html') + # Fix issues in syntax.rst. + index = os.path.join(target_doc_dir, 'syntax.rst') + with rewrite(index) as b: + b.data = b.data.replace( + '..productionlist:: sf\n', '.. productionlist:: sf\n ') + b.data = b.data.replace('Examples:\n', 'Examples::\n') + # Build the docs. + html_dir = os.path.join(env.build_dir, 'html') + if os.path.exists(html_dir): + shutil.rmtree(html_dir) + include_dir = env.fmt_repo.dir + if LooseVersion(version) >= LooseVersion('5.0.0'): + include_dir = os.path.join(include_dir, 'include', 'fmt') + elif LooseVersion(version) >= LooseVersion('3.0.0'): + include_dir = os.path.join(include_dir, 'fmt') + import build + build.build_docs(version, doc_dir=target_doc_dir, + include_dir=include_dir, work_dir=env.build_dir) + shutil.rmtree(os.path.join(html_dir, '.doctrees')) + # Create symlinks for older versions. + for link, target in {'index': 'contents', 'api': 'reference'}.items(): + link = os.path.join(html_dir, link) + '.html' + target += '.html' + if os.path.exists(os.path.join(html_dir, target)) and \ + not os.path.exists(link): + os.symlink(target, link) + # Copy docs to the website. + version_doc_dir = os.path.join(doc_repo.dir, version) + try: + shutil.rmtree(version_doc_dir) + except OSError as e: + if e.errno != errno.ENOENT: + raise + shutil.move(html_dir, version_doc_dir) + + +def release(args): + env = create_build_env() + fmt_repo = env.fmt_repo + + branch = args.get('') + if branch is None: + branch = 'master' + if not fmt_repo.update('-b', branch, fmt_repo_url): + clean_checkout(fmt_repo, branch) + + # Update the date in the changelog and extract the version and the first + # section content. + changelog = 'ChangeLog.md' + changelog_path = os.path.join(fmt_repo.dir, changelog) + is_first_section = True + first_section = [] + for i, line in enumerate(fileinput.input(changelog_path, inplace=True)): + if i == 0: + version = re.match(r'# (.*) - TBD', line).group(1) + line = '# {} - {}\n'.format( + version, datetime.date.today().isoformat()) + elif not is_first_section: + pass + elif line.startswith('#'): + is_first_section = False + else: + first_section.append(line) + sys.stdout.write(line) + if first_section[0] == '\n': + first_section.pop(0) + + changes = '' + code_block = False + stripped = False + for line in first_section: + if re.match(r'^\s*```', line): + code_block = not code_block + changes += line + stripped = False + continue + if code_block: + changes += line + continue + if line == '\n': + changes += line + if stripped: + changes += line + stripped = False + continue + if stripped: + line = ' ' + line.lstrip() + changes += line.rstrip() + stripped = True + + cmakelists = 'CMakeLists.txt' + for line in fileinput.input(os.path.join(fmt_repo.dir, cmakelists), + inplace=True): + prefix = 'set(FMT_VERSION ' + if line.startswith(prefix): + line = prefix + version + ')\n' + sys.stdout.write(line) + + # Add the version to the build script. + script = os.path.join('doc', 'build.py') + script_path = os.path.join(fmt_repo.dir, script) + for line in fileinput.input(script_path, inplace=True): + m = re.match(r'( *versions \+= )\[(.+)\]', line) + if m: + line = '{}[{}, \'{}\']\n'.format(m.group(1), m.group(2), version) + sys.stdout.write(line) + + fmt_repo.checkout('-B', 'release') + fmt_repo.add(changelog, cmakelists, script) + fmt_repo.commit('-m', 'Update version') + + # Build the docs and package. + run = Runner(fmt_repo.dir) + run('cmake', '.') + run('make', 'doc', 'package_source') + update_site(env) + + # Create a release on GitHub. + fmt_repo.push('origin', 'release') + auth_headers = {'Authorization': 'token ' + os.getenv('FMT_TOKEN')} + r = requests.post('https://api.github.com/repos/fmtlib/fmt/releases', + headers=auth_headers, + data=json.dumps({'tag_name': version, + 'target_commitish': 'release', + 'body': changes, 'draft': True})) + if r.status_code != 201: + raise Exception('Failed to create a release ' + str(r)) + id = r.json()['id'] + uploads_url = 'https://uploads.github.com/repos/fmtlib/fmt/releases' + package = 'fmt-{}.zip'.format(version) + r = requests.post( + '{}/{}/assets?name={}'.format(uploads_url, id, package), + headers={'Content-Type': 'application/zip'} | auth_headers, + data=open('build/fmt/' + package, 'rb')) + if r.status_code != 201: + raise Exception('Failed to upload an asset ' + str(r)) + + +if __name__ == '__main__': + args = docopt.docopt(__doc__) + if args.get('release'): + release(args) + elif args.get('site'): + update_site(create_build_env()) diff --git a/third_party/fmt/support/printable.py b/third_party/fmt/support/printable.py new file mode 100755 index 0000000..8fa86b3 --- /dev/null +++ b/third_party/fmt/support/printable.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 + +# This script is based on +# https://github.com/rust-lang/rust/blob/master/library/core/src/unicode/printable.py +# distributed under https://github.com/rust-lang/rust/blob/master/LICENSE-MIT. + +# This script uses the following Unicode tables: +# - UnicodeData.txt + + +from collections import namedtuple +import csv +import os +import subprocess + +NUM_CODEPOINTS=0x110000 + +def to_ranges(iter): + current = None + for i in iter: + if current is None or i != current[1] or i in (0x10000, 0x20000): + if current is not None: + yield tuple(current) + current = [i, i + 1] + else: + current[1] += 1 + if current is not None: + yield tuple(current) + +def get_escaped(codepoints): + for c in codepoints: + if (c.class_ or "Cn") in "Cc Cf Cs Co Cn Zl Zp Zs".split() and c.value != ord(' '): + yield c.value + +def get_file(f): + try: + return open(os.path.basename(f)) + except FileNotFoundError: + subprocess.run(["curl", "-O", f], check=True) + return open(os.path.basename(f)) + +Codepoint = namedtuple('Codepoint', 'value class_') + +def get_codepoints(f): + r = csv.reader(f, delimiter=";") + prev_codepoint = 0 + class_first = None + for row in r: + codepoint = int(row[0], 16) + name = row[1] + class_ = row[2] + + if class_first is not None: + if not name.endswith("Last>"): + raise ValueError("Missing Last after First") + + for c in range(prev_codepoint + 1, codepoint): + yield Codepoint(c, class_first) + + class_first = None + if name.endswith("First>"): + class_first = class_ + + yield Codepoint(codepoint, class_) + prev_codepoint = codepoint + + if class_first is not None: + raise ValueError("Missing Last after First") + + for c in range(prev_codepoint + 1, NUM_CODEPOINTS): + yield Codepoint(c, None) + +def compress_singletons(singletons): + uppers = [] # (upper, # items in lowers) + lowers = [] + + for i in singletons: + upper = i >> 8 + lower = i & 0xff + if len(uppers) == 0 or uppers[-1][0] != upper: + uppers.append((upper, 1)) + else: + upper, count = uppers[-1] + uppers[-1] = upper, count + 1 + lowers.append(lower) + + return uppers, lowers + +def compress_normal(normal): + # lengths 0x00..0x7f are encoded as 00, 01, ..., 7e, 7f + # lengths 0x80..0x7fff are encoded as 80 80, 80 81, ..., ff fe, ff ff + compressed = [] # [truelen, (truelenaux), falselen, (falselenaux)] + + prev_start = 0 + for start, count in normal: + truelen = start - prev_start + falselen = count + prev_start = start + count + + assert truelen < 0x8000 and falselen < 0x8000 + entry = [] + if truelen > 0x7f: + entry.append(0x80 | (truelen >> 8)) + entry.append(truelen & 0xff) + else: + entry.append(truelen & 0x7f) + if falselen > 0x7f: + entry.append(0x80 | (falselen >> 8)) + entry.append(falselen & 0xff) + else: + entry.append(falselen & 0x7f) + + compressed.append(entry) + + return compressed + +def print_singletons(uppers, lowers, uppersname, lowersname): + print(" static constexpr singleton {}[] = {{".format(uppersname)) + for u, c in uppers: + print(" {{{:#04x}, {}}},".format(u, c)) + print(" };") + print(" static constexpr unsigned char {}[] = {{".format(lowersname)) + for i in range(0, len(lowers), 8): + print(" {}".format(" ".join("{:#04x},".format(l) for l in lowers[i:i+8]))) + print(" };") + +def print_normal(normal, normalname): + print(" static constexpr unsigned char {}[] = {{".format(normalname)) + for v in normal: + print(" {}".format(" ".join("{:#04x},".format(i) for i in v))) + print(" };") + +def main(): + file = get_file("https://www.unicode.org/Public/UNIDATA/UnicodeData.txt") + + codepoints = get_codepoints(file) + + CUTOFF=0x10000 + singletons0 = [] + singletons1 = [] + normal0 = [] + normal1 = [] + extra = [] + + for a, b in to_ranges(get_escaped(codepoints)): + if a > 2 * CUTOFF: + extra.append((a, b - a)) + elif a == b - 1: + if a & CUTOFF: + singletons1.append(a & ~CUTOFF) + else: + singletons0.append(a) + elif a == b - 2: + if a & CUTOFF: + singletons1.append(a & ~CUTOFF) + singletons1.append((a + 1) & ~CUTOFF) + else: + singletons0.append(a) + singletons0.append(a + 1) + else: + if a >= 2 * CUTOFF: + extra.append((a, b - a)) + elif a & CUTOFF: + normal1.append((a & ~CUTOFF, b - a)) + else: + normal0.append((a, b - a)) + + singletons0u, singletons0l = compress_singletons(singletons0) + singletons1u, singletons1l = compress_singletons(singletons1) + normal0 = compress_normal(normal0) + normal1 = compress_normal(normal1) + + print("""\ +FMT_FUNC auto is_printable(uint32_t cp) -> bool {\ +""") + print_singletons(singletons0u, singletons0l, 'singletons0', 'singletons0_lower') + print_singletons(singletons1u, singletons1l, 'singletons1', 'singletons1_lower') + print_normal(normal0, 'normal0') + print_normal(normal1, 'normal1') + print("""\ + auto lower = static_cast(cp); + if (cp < 0x10000) { + return is_printable(lower, singletons0, + sizeof(singletons0) / sizeof(*singletons0), + singletons0_lower, normal0, sizeof(normal0)); + } + if (cp < 0x20000) { + return is_printable(lower, singletons1, + sizeof(singletons1) / sizeof(*singletons1), + singletons1_lower, normal1, sizeof(normal1)); + }\ +""") + for a, b in extra: + print(" if (0x{:x} <= cp && cp < 0x{:x}) return false;".format(a, a + b)) + print("""\ + return cp < 0x{:x}; +}}\ +""".format(NUM_CODEPOINTS)) + +if __name__ == '__main__': + main() diff --git a/third_party/fmt/support/rtd/conf.py b/third_party/fmt/support/rtd/conf.py new file mode 100644 index 0000000..124fb9d --- /dev/null +++ b/third_party/fmt/support/rtd/conf.py @@ -0,0 +1,7 @@ +# Sphinx configuration for readthedocs. + +import os, sys + +master_doc = 'index' +html_theme = 'theme' +html_theme_path = ["."] diff --git a/third_party/fmt/support/rtd/index.rst b/third_party/fmt/support/rtd/index.rst new file mode 100644 index 0000000..7c88322 --- /dev/null +++ b/third_party/fmt/support/rtd/index.rst @@ -0,0 +1,2 @@ +If you are not redirected automatically, follow the +`link to the fmt documentation `_. diff --git a/third_party/fmt/support/rtd/theme/layout.html b/third_party/fmt/support/rtd/theme/layout.html new file mode 100644 index 0000000..29ebc55 --- /dev/null +++ b/third_party/fmt/support/rtd/theme/layout.html @@ -0,0 +1,17 @@ +{% extends "basic/layout.html" %} + +{% block extrahead %} + + + +Page Redirection +{% endblock %} + +{% block document %} +If you are not redirected automatically, follow the link to the fmt documentation. +{% endblock %} + +{% block footer %} +{% endblock %} diff --git a/third_party/fmt/support/rtd/theme/theme.conf b/third_party/fmt/support/rtd/theme/theme.conf new file mode 100644 index 0000000..89e03bb --- /dev/null +++ b/third_party/fmt/support/rtd/theme/theme.conf @@ -0,0 +1,2 @@ +[theme] +inherit = basic diff --git a/third_party/gflags/.gitattributes b/third_party/gflags/.gitattributes new file mode 100644 index 0000000..87fe9c0 --- /dev/null +++ b/third_party/gflags/.gitattributes @@ -0,0 +1,3 @@ +# treat all files in this repository as text files +# and normalize them to LF line endings when committed +* text diff --git a/third_party/gflags/.gitignore b/third_party/gflags/.gitignore new file mode 100644 index 0000000..706f7f8 --- /dev/null +++ b/third_party/gflags/.gitignore @@ -0,0 +1,25 @@ +/xcode/ +/build/ +/builds/ +/build-*/ +/_build/ +.DS_Store +CMakeCache.txt +DartConfiguration.tcl +Makefile +CMakeFiles/ +/Testing/ +/include/gflags/config.h +/include/gflags/gflags_completions.h +/include/gflags/gflags_declare.h +/include/gflags/gflags.h +/lib/ +/test/gflags_unittest_main.cc +/test/gflags_unittest-main.cc +/packages/ +CMakeLists.txt.user +/bazel-bin +/bazel-genfiles +/bazel-gflags +/bazel-out +/bazel-testlogs diff --git a/third_party/gflags/.gitmodules b/third_party/gflags/.gitmodules new file mode 100644 index 0000000..aa2072c --- /dev/null +++ b/third_party/gflags/.gitmodules @@ -0,0 +1,4 @@ +[submodule "doc"] + path = doc + url = https://github.com/gflags/gflags.git + branch = gh-pages diff --git a/third_party/gflags/.travis.yml b/third_party/gflags/.travis.yml new file mode 100644 index 0000000..0989c7c --- /dev/null +++ b/third_party/gflags/.travis.yml @@ -0,0 +1,20 @@ +# Ubuntu 14.04 Trusty support, to get newer cmake and compilers. +sudo: required +dist: trusty + +language: cpp + +os: + - linux + - osx + +compiler: + - clang + - gcc + +env: + - CONFIG=Release + - CONFIG=Debug + +script: + - mkdir out && cd out && cmake -D CMAKE_BUILD_TYPE=$CONFIG -D GFLAGS_BUILD_SHARED_LIBS=ON -D GFLAGS_BUILD_STATIC_LIBS=ON -D GFLAGS_BUILD_TESTING=ON .. && cmake --build . --config $CONFIG && ctest diff --git a/third_party/gflags/AUTHORS.txt b/third_party/gflags/AUTHORS.txt new file mode 100644 index 0000000..887918b --- /dev/null +++ b/third_party/gflags/AUTHORS.txt @@ -0,0 +1,2 @@ +google-gflags@googlegroups.com + diff --git a/third_party/gflags/BUILD b/third_party/gflags/BUILD new file mode 100644 index 0000000..0e7ccdd --- /dev/null +++ b/third_party/gflags/BUILD @@ -0,0 +1,18 @@ +# Bazel (http://bazel.io/) BUILD file for gflags. +# +# See INSTALL.md for instructions for adding gflags to a Bazel workspace. + +licenses(["notice"]) + +exports_files(["src/gflags_completions.sh", "COPYING.txt"]) + +config_setting( + name = "x64_windows", + values = {"cpu": "x64_windows"}, +) + +load(":bazel/gflags.bzl", "gflags_sources", "gflags_library") + +(hdrs, srcs) = gflags_sources(namespace=["gflags", "google"]) +gflags_library(hdrs=hdrs, srcs=srcs, threads=0) +gflags_library(hdrs=hdrs, srcs=srcs, threads=1) diff --git a/third_party/gflags/CMakeLists.txt b/third_party/gflags/CMakeLists.txt new file mode 100644 index 0000000..5a7ebb5 --- /dev/null +++ b/third_party/gflags/CMakeLists.txt @@ -0,0 +1,796 @@ +# CMake configuration file of gflags project +# +# This CMakeLists.txt defines some gflags specific configuration variables using +# the "gflags_define" utility macro. The default values of these variables can +# be overridden either on the CMake command-line using the -D option of the +# cmake command or in a super-project which includes the gflags source tree by +# setting the GFLAGS_ CMake variables before adding the gflags source +# directory via CMake's "add_subdirectory" command. Only when the non-cached +# variable GFLAGS_IS_SUBPROJECT has a value equivalent to FALSE, these +# configuration variables are added to the CMake cache so they can be edited in +# the CMake GUI. By default, GFLAGS_IS_SUBPROJECT is set to TRUE when the +# CMAKE_SOURCE_DIR is not identical to the directory of this CMakeLists.txt +# file, i.e., the top-level directory of the gflags project source tree. +# +# When this project is a subproject (GFLAGS_IS_SUBPROJECT is TRUE), the default +# settings are such that only the static single-threaded library is built +# without installation of the gflags files. The "gflags::gflags" target is in +# this case an ALIAS library target for the "gflags_nothreads_static" library +# target. Targets which depend on the gflags library should link to the +# "gflags::gflags" library target. +# +# Example CMakeLists.txt of user project which requires separate gflags +# installation: cmake_minimum_required(VERSION 2.8.12 FATAL_ERROR) +# +# project(Foo) +# +# find_package(gflags REQUIRED) +# +# add_executable(foo src/foo.cc) target_link_libraries(foo gflags::gflags) +# +# Example CMakeLists.txt of user project which requires separate single-threaded +# static gflags installation: cmake_minimum_required(VERSION 2.8.12 FATAL_ERROR) +# +# project(Foo) +# +# find_package(gflags COMPONENTS nothreads_static) +# +# add_executable(foo src/foo.cc) target_link_libraries(foo gflags::gflags) +# +# Example CMakeLists.txt of super-project which contains gflags source tree: +# cmake_minimum_required(VERSION 2.8.12 FATAL_ERROR) +# +# project(Foo) +# +# add_subdirectory(gflags) +# +# add_executable(foo src/foo.cc) target_link_libraries(foo gflags::gflags) +# +# Variables to configure the source files: - GFLAGS_IS_A_DLL - GFLAGS_NAMESPACE +# - GFLAGS_ATTRIBUTE_UNUSED - GFLAGS_INTTYPES_FORMAT +# +# Variables to configure the build: - GFLAGS_SOVERSION - +# GFLAGS_BUILD_SHARED_LIBS - GFLAGS_BUILD_STATIC_LIBS - GFLAGS_BUILD_gflags_LIB +# - GFLAGS_BUILD_gflags_nothreads_LIB - GFLAGS_BUILD_TESTING - +# GFLAGS_BUILD_PACKAGING +# +# Variables to configure the installation: - GFLAGS_INCLUDE_DIR - +# GFLAGS_LIBRARY_INSTALL_DIR or LIB_INSTALL_DIR or LIB_SUFFIX - +# GFLAGS_INSTALL_HEADERS - GFLAGS_INSTALL_SHARED_LIBS - +# GFLAGS_INSTALL_STATIC_LIBS + +cmake_minimum_required(VERSION 3.0.2 FATAL_ERROR) + +if(POLICY CMP0042) + cmake_policy(SET CMP0042 NEW) +endif() + +if(POLICY CMP0048) + cmake_policy(SET CMP0048 NEW) +endif() + +# ---------------------------------------------------------------------------- +# includes +include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/utils.cmake") + +# ---------------------------------------------------------------------------- +# package information +set(PACKAGE_NAME "gflags") +set(PACKAGE_VERSION "2.2.2") +set(PACKAGE_STRING "${PACKAGE_NAME} ${PACKAGE_VERSION}") +set(PACKAGE_TARNAME "${PACKAGE_NAME}-${PACKAGE_VERSION}") +set(PACKAGE_BUGREPORT "https://github.com/gflags/gflags/issues") +set(PACKAGE_DESCRIPTION + "A commandline flags library that allows for distributed flags.") +set(PACKAGE_URL "http://gflags.github.io/gflags") + +project( + ${PACKAGE_NAME} + VERSION ${PACKAGE_VERSION} + LANGUAGES CXX) +if(CMAKE_VERSION VERSION_LESS 3.4) + # C language still needed because the following required CMake modules (or + # their dependencies, respectively) are not correctly handling the case where + # only CXX is enabled - CheckTypeSize.cmake (fixed in CMake 3.1, cf. + # https://cmake.org/Bug/view.php?id=14056) - FindThreads.cmake (fixed in + # CMake 3.4, cf. https://cmake.org/Bug/view.php?id=14905) + enable_language(C) +endif() + +version_numbers(${PACKAGE_VERSION} PACKAGE_VERSION_MAJOR PACKAGE_VERSION_MINOR + PACKAGE_VERSION_PATCH) + +# shared library ABI version number, can be overridden by package maintainers +# using -DGFLAGS_SOVERSION=XXX on the command-line +if(GFLAGS_SOVERSION) + set(PACKAGE_SOVERSION "${GFLAGS_SOVERSION}") +else() + # TODO: Change default SOVERSION back to PACKAGE_VERSION_MAJOR with the next + # increase of major version number (i.e., 3.0.0 -> SOVERSION 3) The + # . SOVERSION should be used for the 2.x releases versions only + # which temporarily broke the API by changing the default namespace from + # "google" to "gflags". + set(PACKAGE_SOVERSION "${PACKAGE_VERSION_MAJOR}.${PACKAGE_VERSION_MINOR}") +endif() + +# when gflags is included as subproject (e.g., as Git submodule/subtree) in the +# source tree of a project that uses it, no variables should be added to the +# CMake cache; users may set the non-cached variable GFLAGS_IS_SUBPROJECT before +# add_subdirectory(gflags) +if(NOT DEFINED GFLAGS_IS_SUBPROJECT) + if("^${CMAKE_SOURCE_DIR}$" STREQUAL "^${PROJECT_SOURCE_DIR}$") + set(GFLAGS_IS_SUBPROJECT FALSE) + else() + set(GFLAGS_IS_SUBPROJECT TRUE) + endif() +endif() + +# prefix for package variables in CMake configuration file +string(TOUPPER "${PACKAGE_NAME}" PACKAGE_PREFIX) + +# convert file path on Windows with back slashes to path with forward slashes +# otherwise this causes an issue with the cmake_install.cmake script +file(TO_CMAKE_PATH "${CMAKE_INSTALL_PREFIX}" CMAKE_INSTALL_PREFIX) + +# ---------------------------------------------------------------------------- +# options + +# maintain binary backwards compatibility with gflags library version <= 2.0, +# but at the same time enable the use of the preferred new "gflags" namespace +gflags_define( + STRING NAMESPACE + "Name(s) of library namespace (separate multiple options by semicolon)" + "google;${PACKAGE_NAME}" "${PACKAGE_NAME}") +gflags_property(NAMESPACE ADVANCED TRUE) +set(GFLAGS_NAMESPACE_SECONDARY "${NAMESPACE}") +list(REMOVE_DUPLICATES GFLAGS_NAMESPACE_SECONDARY) +if(NOT GFLAGS_NAMESPACE_SECONDARY) + message( + FATAL_ERROR + "GFLAGS_NAMESPACE must be set to one (or more) valid C++ namespace identifier(s separated by semicolon \";\")." + ) +endif() +foreach(ns IN LISTS GFLAGS_NAMESPACE_SECONDARY) + if(NOT ns MATCHES "^[a-zA-Z][a-zA-Z0-9_]*$") + message( + FATAL_ERROR + "GFLAGS_NAMESPACE contains invalid namespace identifier: ${ns}") + endif() +endforeach() +list(GET GFLAGS_NAMESPACE_SECONDARY 0 GFLAGS_NAMESPACE) +list(REMOVE_AT GFLAGS_NAMESPACE_SECONDARY 0) + +# cached build options when gflags is not a subproject, otherwise non-cached +# CMake variables usage: gflags_define(BOOL []) +gflags_define(BOOL BUILD_SHARED_LIBS "Request build of shared libraries." OFF + OFF) +gflags_define( + BOOL BUILD_STATIC_LIBS + "Request build of static libraries (default if BUILD_SHARED_LIBS is OFF)." + OFF ON) +gflags_define(BOOL BUILD_gflags_LIB + "Request build of the multi-threaded gflags library." ON ON) +gflags_define(BOOL BUILD_gflags_nothreads_LIB + "Request build of the single-threaded gflags library." OFF OFF) +gflags_define(BOOL BUILD_PACKAGING + "Enable build of distribution packages using CPack." OFF OFF) +gflags_define( + BOOL BUILD_TESTING + "Enable build of the unit tests and their execution using CTest." OFF OFF) +gflags_define( + BOOL INSTALL_HEADERS + "Request installation of headers and other development files." OFF OFF) +gflags_define(BOOL INSTALL_SHARED_LIBS + "Request installation of shared libraries." OFF OFF) +gflags_define(BOOL INSTALL_STATIC_LIBS + "Request installation of static libraries." OFF OFF) +gflags_define( + BOOL REGISTER_BUILD_DIR + "Request entry of build directory in CMake's package registry." ON ON) +gflags_define( + BOOL REGISTER_INSTALL_PREFIX + "Request entry of installed package in CMake's package registry." ON OFF) + +gflags_property(BUILD_STATIC_LIBS ADVANCED TRUE) +gflags_property(INSTALL_HEADERS ADVANCED TRUE) +gflags_property(INSTALL_SHARED_LIBS ADVANCED TRUE) +gflags_property(INSTALL_STATIC_LIBS ADVANCED TRUE) + +if(NOT GFLAGS_IS_SUBPROJECT) + foreach(varname IN ITEMS CMAKE_INSTALL_PREFIX) + gflags_property(${varname} ADVANCED FALSE) + endforeach() + foreach(varname IN ITEMS CMAKE_CONFIGURATION_TYPES CMAKE_OSX_ARCHITECTURES + CMAKE_OSX_DEPLOYMENT_TARGET CMAKE_OSX_SYSROOT) + gflags_property(${varname} ADVANCED TRUE) + endforeach() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CXX_FLAGS) + gflags_set(CMAKE_BUILD_TYPE Release) + endif() + if(CMAKE_CONFIGURATION_TYPES) + gflags_property(CMAKE_BUILD_TYPE STRINGS "${CMAKE_CONFIGURATION_TYPES}") + endif() +endif() # NOT GFLAGS_IS_SUBPROJECT + +if(NOT BUILD_SHARED_LIBS AND NOT BUILD_STATIC_LIBS) + set(BUILD_STATIC_LIBS ON) +endif() +if(NOT BUILD_gflags_LIB AND NOT BUILD_gflags_nothreads_LIB) + message( + FATAL_ERROR + "At least one of [GFLAGS_]BUILD_gflags_LIB and [GFLAGS_]BUILD_gflags_nothreads_LIB must be ON." + ) +endif() + +gflags_define( + STRING + INCLUDE_DIR + "Name of include directory of installed header files relative to CMAKE_INSTALL_PREFIX/include/" + "${PACKAGE_NAME}") +gflags_property(INCLUDE_DIR ADVANCED TRUE) +file(TO_CMAKE_PATH "${INCLUDE_DIR}" INCLUDE_DIR) +if(IS_ABSOLUTE INCLUDE_DIR) + message( + FATAL_ERROR + "[GFLAGS_]INCLUDE_DIR must be a path relative to CMAKE_INSTALL_PREFIX/include/" + ) +endif() +if(INCLUDE_DIR MATCHES "^\\.\\.[/\\]") + message( + FATAL_ERROR + "[GFLAGS_]INCLUDE_DIR must not start with parent directory reference (../)" + ) +endif() +set(GFLAGS_INCLUDE_DIR "${INCLUDE_DIR}") + +# ---------------------------------------------------------------------------- +# system checks +include(CheckTypeSize) +include(CheckIncludeFileCXX) +include(CheckCXXSymbolExists) + +if(WIN32 AND NOT CYGWIN) + set(OS_WINDOWS 1) +else() + set(OS_WINDOWS 0) +endif() + +if(MSVC) + set(HAVE_SYS_TYPES_H 1) + set(HAVE_STDDEF_H 1) # used by CheckTypeSize module + set(HAVE_UNISTD_H 0) + set(HAVE_SYS_STAT_H 1) + set(HAVE_SHLWAPI_H 1) + if(MSVC_VERSION VERSION_LESS 1600) + check_include_file_cxx("stdint.h" HAVE_STDINT_H) + bool_to_int(HAVE_STDINT_H) # used in #if directive + else() + set(HAVE_STDINT_H 1) + endif() + if(MSVC_VERSION VERSION_LESS 1800) + check_include_file_cxx("inttypes.h" HAVE_INTTYPES_H) + bool_to_int(HAVE_INTTYPES_H) # used in #if directive + else() + set(HAVE_INTTYPES_H 1) + endif() +else() + foreach(fname IN ITEMS unistd stdint inttypes sys/types sys/stat fnmatch) + string(TOUPPER "${fname}" FNAME) + string(REPLACE "/" "_" FNAME "${FNAME}") + if(NOT HAVE_${FNAME}_H) + check_include_file_cxx("${fname}.h" HAVE_${FNAME}_H) + endif() + endforeach() + if(NOT HAVE_FNMATCH_H AND OS_WINDOWS) + check_include_file_cxx("shlwapi.h" HAVE_SHLWAPI_H) + endif() + # the following are used in #if directives not #ifdef + bool_to_int(HAVE_STDINT_H) + bool_to_int(HAVE_SYS_TYPES_H) + bool_to_int(HAVE_INTTYPES_H) +endif() + +gflags_define( + STRING + INTTYPES_FORMAT + "Format of integer types: \"C99\" (uint32_t), \"BSD\" (u_int32_t), \"VC7\" (__int32)" + "") +gflags_property(INTTYPES_FORMAT STRINGS "C99;BSD;VC7") +gflags_property(INTTYPES_FORMAT ADVANCED TRUE) +if(NOT INTTYPES_FORMAT) + set(TYPES uint32_t u_int32_t) + if(MSVC) + list(INSERT TYPES 0 __int32) + endif() + foreach(type IN LISTS TYPES) + check_type_size(${type} ${type} LANGUAGE CXX) + if(HAVE_${type}) + break() + endif() + endforeach() + if(HAVE_uint32_t) + gflags_set(INTTYPES_FORMAT C99) + elseif(HAVE_u_int32_t) + gflags_set(INTTYPES_FORMAT BSD) + elseif(HAVE___int32) + gflags_set(INTTYPES_FORMAT VC7) + else() + gflags_property(INTTYPES_FORMAT ADVANCED FALSE) + message( + FATAL_ERROR + "Do not know how to define a 32-bit integer quantity on your system!" + " Neither uint32_t, u_int32_t, nor __int32 seem to be available." + " Set [GFLAGS_]INTTYPES_FORMAT to either C99, BSD, or VC7 and try again." + ) + endif() +endif() +# use of special characters in strings to circumvent bug #0008226 +if("^${INTTYPES_FORMAT}$" STREQUAL "^WIN$") + gflags_set(INTTYPES_FORMAT VC7) +endif() +if(NOT INTTYPES_FORMAT MATCHES "^(C99|BSD|VC7)$") + message( + FATAL_ERROR + "Invalid value for [GFLAGS_]INTTYPES_FORMAT! Choose one of \"C99\", \"BSD\", or \"VC7\"" + ) +endif() +set(GFLAGS_INTTYPES_FORMAT "${INTTYPES_FORMAT}") +set(GFLAGS_INTTYPES_FORMAT_C99 0) +set(GFLAGS_INTTYPES_FORMAT_BSD 0) +set(GFLAGS_INTTYPES_FORMAT_VC7 0) +set("GFLAGS_INTTYPES_FORMAT_${INTTYPES_FORMAT}" 1) + +if(MSVC) + set(HAVE_strtoll 0) + set(HAVE_strtoq 0) +else() + check_cxx_symbol_exists(strtoll stdlib.h HAVE_STRTOLL) + if(NOT HAVE_STRTOLL) + check_cxx_symbol_exists(strtoq stdlib.h HAVE_STRTOQ) + endif() +endif() + +if(BUILD_gflags_LIB) + set(CMAKE_THREAD_PREFER_PTHREAD TRUE) + find_package(Threads) + if(Threads_FOUND AND CMAKE_USE_PTHREADS_INIT) + set(HAVE_PTHREAD 1) + check_type_size(pthread_rwlock_t RWLOCK LANGUAGE CXX) + else() + set(HAVE_PTHREAD 0) + endif() + if(UNIX AND NOT HAVE_PTHREAD) + if(CMAKE_HAVE_PTHREAD_H) + set(what "library") + else() + set(what ".h file") + endif() + message( + FATAL_ERROR + "Could not find pthread${what}. Check the log file" + "\n\t${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log" + "\nor disable the build of the multi-threaded gflags library (BUILD_gflags_LIB=OFF)." + ) + endif() +else() + set(HAVE_PTHREAD 0) +endif() + +# ---------------------------------------------------------------------------- +# source files - excluding root subdirectory and/or .in suffix +set(PUBLIC_HDRS "gflags.h" "gflags_declare.h" "gflags_completions.h") + +if(GFLAGS_NAMESPACE_SECONDARY) + set(INCLUDE_GFLAGS_NS_H + "// Import gflags library symbols into alternative/deprecated namespace(s)" + ) + foreach(ns IN LISTS GFLAGS_NAMESPACE_SECONDARY) + string(TOUPPER "${ns}" NS) + set(gflags_ns_h + "${PROJECT_BINARY_DIR}/include/${GFLAGS_INCLUDE_DIR}/gflags_${ns}.h") + configure_file("${PROJECT_SOURCE_DIR}/src/gflags_ns.h.in" "${gflags_ns_h}" + @ONLY) + list(APPEND PUBLIC_HDRS "${gflags_ns_h}") + set(INCLUDE_GFLAGS_NS_H + "${INCLUDE_GFLAGS_NS_H}\n#include \"gflags_${ns}.h\"") + endforeach() +else() + set(INCLUDE_GFLAGS_NS_H) +endif() + +set(PRIVATE_HDRS "defines.h" "config.h" "util.h" "mutex.h") + +set(GFLAGS_SRCS "gflags.cc" "gflags_reporting.cc" "gflags_completions.cc") + +if(OS_WINDOWS) + list(APPEND PRIVATE_HDRS "windows_port.h") + list(APPEND GFLAGS_SRCS "windows_port.cc") +endif() + +# ---------------------------------------------------------------------------- +# configure source files +if(NOT DEFINED GFLAGS_ATTRIBUTE_UNUSED) + if(CMAKE_COMPILER_IS_GNUCXX) + set(GFLAGS_ATTRIBUTE_UNUSED "__attribute((unused))") + else() + set(GFLAGS_ATTRIBUTE_UNUSED) + endif() +endif() + +# whenever we build a shared library (DLL on Windows), configure the public +# headers of the API for use of this shared library rather than the optionally +# also build statically linked library; users can override GFLAGS_DLL_DECL in +# particular, this done by setting the INTERFACE_COMPILE_DEFINITIONS of static +# libraries to include an empty definition for GFLAGS_DLL_DECL +if(NOT DEFINED GFLAGS_IS_A_DLL) + if(BUILD_SHARED_LIBS) + set(GFLAGS_IS_A_DLL 1) + else() + set(GFLAGS_IS_A_DLL 0) + endif() +endif() + +configure_headers(PUBLIC_HDRS ${PUBLIC_HDRS}) +configure_sources(PRIVATE_HDRS ${PRIVATE_HDRS}) +configure_sources(GFLAGS_SRCS ${GFLAGS_SRCS}) + +# ---------------------------------------------------------------------------- +# output directories +if(NOT GFLAGS_IS_SUBPROJECT) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "bin") + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "lib") + set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "lib") +endif() +# Set postfixes for generated libraries based on buildtype. +set(CMAKE_RELEASE_POSTFIX "") +set(CMAKE_DEBUG_POSTFIX "_debug") + +# ---------------------------------------------------------------------------- +# installation directories +if(OS_WINDOWS) + set(RUNTIME_INSTALL_DIR "bin") + set(LIBRARY_INSTALL_DIR "lib") + set(INCLUDE_INSTALL_DIR "include") + set(CONFIG_INSTALL_DIR "lib/cmake/${PACKAGE_NAME}") + set(PKGCONFIG_INSTALL_DIR) +else() + set(RUNTIME_INSTALL_DIR bin) + # The LIB_INSTALL_DIR and LIB_SUFFIX variables are used by the Fedora package + # maintainers. Also package maintainers of other distribution packages need to + # be able to specify the name of the library directory. + if(NOT GFLAGS_LIBRARY_INSTALL_DIR AND LIB_INSTALL_DIR) + set(GFLAGS_LIBRARY_INSTALL_DIR "${LIB_INSTALL_DIR}") + endif() + gflags_define( + PATH LIBRARY_INSTALL_DIR + "Directory of installed libraries, e.g., \"lib64\"" "lib${LIB_SUFFIX}") + gflags_property(LIBRARY_INSTALL_DIR ADVANCED TRUE) + set(INCLUDE_INSTALL_DIR include) + set(CONFIG_INSTALL_DIR ${LIBRARY_INSTALL_DIR}/cmake/${PACKAGE_NAME}) + set(PKGCONFIG_INSTALL_DIR ${LIBRARY_INSTALL_DIR}/pkgconfig) +endif() + +# ---------------------------------------------------------------------------- +# add library targets +set(TARGETS) +# static vs. shared +foreach(TYPE IN ITEMS STATIC SHARED) + if(BUILD_${TYPE}_LIBS) + string(TOLOWER "${TYPE}" type) + # whether or not targets are a DLL + if(OS_WINDOWS AND "^${TYPE}$" STREQUAL "^SHARED$") + set(GFLAGS_IS_A_DLL 1) + else() + set(GFLAGS_IS_A_DLL 0) + endif() + # filename suffix for static libraries on Windows + if(OS_WINDOWS AND "^${TYPE}$" STREQUAL "^STATIC$") + set(type_suffix "_${type}") + else() + set(type_suffix "") + endif() + # multi-threaded vs. single-threaded + foreach(opts IN ITEMS "" _nothreads) + if(BUILD_gflags${opts}_LIB) + set(target_name "gflags${opts}_${type}") + add_library(${target_name} ${TYPE} ${GFLAGS_SRCS} ${PRIVATE_HDRS} + ${PUBLIC_HDRS}) + set_target_properties( + ${target_name} + PROPERTIES OUTPUT_NAME "gflags${opts}${type_suffix}" + VERSION "${PACKAGE_VERSION}" + SOVERSION "${PACKAGE_SOVERSION}") + set(include_dirs "$") + if(INSTALL_HEADERS) + list(APPEND include_dirs + "$") + endif() + target_include_directories( + ${target_name} + PUBLIC "${include_dirs}" + PRIVATE + "${PROJECT_SOURCE_DIR}/src;${PROJECT_BINARY_DIR}/include/${GFLAGS_INCLUDE_DIR}" + ) + target_compile_definitions(${target_name} + PUBLIC GFLAGS_IS_A_DLL=${GFLAGS_IS_A_DLL}) + if(opts MATCHES "nothreads") + target_compile_definitions(${target_name} PRIVATE NO_THREADS) + elseif(CMAKE_USE_PTHREADS_INIT) + target_link_libraries(${target_name} ${CMAKE_THREAD_LIBS_INIT}) + endif() + if(HAVE_SHLWAPI_H) + target_link_libraries(${target_name} shlwapi.lib) + endif() + list(APPEND TARGETS ${target_name}) + # add convenience make target for build of both shared and static + # libraries + if(NOT GFLAGS_IS_SUBPROJECT) + if(NOT TARGET gflags${opts}) + add_custom_target(gflags${opts}) + endif() + add_dependencies(gflags${opts} ${target_name}) + endif() + endif() + endforeach() + endif() +endforeach() + +# add ALIAS target for use in super-project, prefer static over shared, +# single-threaded over multi-threaded +if(GFLAGS_IS_SUBPROJECT) + foreach(type IN ITEMS static shared) + foreach(opts IN ITEMS "_nothreads" "") + if(TARGET gflags${opts}_${type}) + # Define "gflags" alias for super-projects treating targets of this + # library as part of their own project (also for backwards compatibility + # with gflags 2.2.1 which only defined this alias) + add_library(gflags ALIAS gflags${opts}_${type}) + # Define "gflags::gflags" alias for projects that support both + # find_package(gflags) and add_subdirectory(gflags) + add_library(gflags::gflags ALIAS gflags${opts}_${type}) + break() + endif() + endforeach() + if(TARGET gflags::gflags) + break() + endif() + endforeach() +endif() + +# ---------------------------------------------------------------------------- +# installation rules +set(EXPORT_NAME ${PACKAGE_NAME}-targets) +file(RELATIVE_PATH INSTALL_PREFIX_REL2CONFIG_DIR + "${CMAKE_INSTALL_PREFIX}/${CONFIG_INSTALL_DIR}" "${CMAKE_INSTALL_PREFIX}") +configure_file( + cmake/config.cmake.in + "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-config-install.cmake" @ONLY) +configure_file( + cmake/version.cmake.in + "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-config-version.cmake" @ONLY) + +if(BUILD_SHARED_LIBS AND INSTALL_SHARED_LIBS) + foreach(opts IN ITEMS "" _nothreads) + if(BUILD_gflags${opts}_LIB) + install( + TARGETS gflags${opts}_shared + EXPORT ${EXPORT_NAME} + RUNTIME DESTINATION ${RUNTIME_INSTALL_DIR} + LIBRARY DESTINATION ${LIBRARY_INSTALL_DIR} + ARCHIVE DESTINATION ${LIBRARY_INSTALL_DIR}) + endif() + endforeach() +endif() +if(BUILD_STATIC_LIBS AND INSTALL_STATIC_LIBS) + foreach(opts IN ITEMS "" _nothreads) + if(BUILD_gflags${opts}_LIB) + install( + TARGETS gflags${opts}_static + EXPORT ${EXPORT_NAME} + RUNTIME DESTINATION ${RUNTIME_INSTALL_DIR} + LIBRARY DESTINATION ${LIBRARY_INSTALL_DIR} + ARCHIVE DESTINATION ${LIBRARY_INSTALL_DIR}) + endif() + endforeach() +endif() + +if(INSTALL_HEADERS) + install(FILES ${PUBLIC_HDRS} + DESTINATION ${INCLUDE_INSTALL_DIR}/${GFLAGS_INCLUDE_DIR}) + install( + FILES "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-config-install.cmake" + RENAME ${PACKAGE_NAME}-config.cmake + DESTINATION ${CONFIG_INSTALL_DIR}) + install(FILES "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-config-version.cmake" + DESTINATION ${CONFIG_INSTALL_DIR}) + install( + EXPORT ${EXPORT_NAME} + NAMESPACE ${PACKAGE_NAME}:: + DESTINATION ${CONFIG_INSTALL_DIR}) + install( + EXPORT ${EXPORT_NAME} + FILE ${PACKAGE_NAME}-nonamespace-targets.cmake + DESTINATION ${CONFIG_INSTALL_DIR}) + if(UNIX) + install(PROGRAMS src/gflags_completions.sh + DESTINATION ${RUNTIME_INSTALL_DIR}) + endif() +endif() + +if(PKGCONFIG_INSTALL_DIR) + configure_file("cmake/package.pc.in" + "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}.pc" @ONLY) + install(FILES "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}.pc" + DESTINATION "${PKGCONFIG_INSTALL_DIR}") +endif() + +# ---------------------------------------------------------------------------- +# support direct use of build tree +set(INSTALL_PREFIX_REL2CONFIG_DIR .) +export( + TARGETS ${TARGETS} + NAMESPACE ${PACKAGE_NAME}:: + FILE "${PROJECT_BINARY_DIR}/${EXPORT_NAME}.cmake") +export(TARGETS ${TARGETS} + FILE "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-nonamespace-targets.cmake") +if(REGISTER_BUILD_DIR) + export(PACKAGE ${PACKAGE_NAME}) +endif() +if(REGISTER_INSTALL_PREFIX) + register_gflags_package(${CONFIG_INSTALL_DIR}) +endif() +# configure_file(cmake/config.cmake.in +# "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-config.cmake" @ONLY) + +# ---------------------------------------------------------------------------- +# testing - MUST follow the generation of the build tree config file +# if(BUILD_TESTING) include(CTest) add_subdirectory(test) endif() + +# ---------------------------------------------------------------------------- +# packaging +if(BUILD_PACKAGING) + + if(NOT BUILD_SHARED_LIBS AND NOT INSTALL_HEADERS) + message( + WARNING "Package will contain static libraries without headers!" + "\nRecommended options for generation of runtime package:" + "\n BUILD_SHARED_LIBS=ON" + "\n BUILD_STATIC_LIBS=OFF" + "\n INSTALL_HEADERS=OFF" + "\n INSTALL_SHARED_LIBS=ON" + "\nRecommended options for generation of development package:" + "\n BUILD_SHARED_LIBS=ON" + "\n BUILD_STATIC_LIBS=ON" + "\n INSTALL_HEADERS=ON" + "\n INSTALL_SHARED_LIBS=ON" + "\n INSTALL_STATIC_LIBS=ON") + endif() + + # default package generators + if(APPLE) + set(PACKAGE_GENERATOR "PackageMaker") + set(PACKAGE_SOURCE_GENERATOR "TGZ;ZIP") + elseif(UNIX) + set(PACKAGE_GENERATOR "DEB;RPM") + set(PACKAGE_SOURCE_GENERATOR "TGZ;ZIP") + else() + set(PACKAGE_GENERATOR "ZIP") + set(PACKAGE_SOURCE_GENERATOR "ZIP") + endif() + + # used package generators + set(CPACK_GENERATOR + "${PACKAGE_GENERATOR}" + CACHE STRING "List of binary package generators (CPack).") + set(CPACK_SOURCE_GENERATOR + "${PACKAGE_SOURCE_GENERATOR}" + CACHE STRING "List of source package generators (CPack).") + mark_as_advanced(CPACK_GENERATOR CPACK_SOURCE_GENERATOR) + + # some package generators (e.g., PackageMaker) do not allow .md extension + configure_file("${CMAKE_CURRENT_LIST_DIR}/README.md" + "${CMAKE_CURRENT_BINARY_DIR}/README.txt" COPYONLY) + + # common package information + set(CPACK_PACKAGE_VENDOR "Andreas Schuh") + set(CPACK_PACKAGE_CONTACT "google-gflags@googlegroups.com") + set(CPACK_PACKAGE_NAME "${PACKAGE_NAME}") + set(CPACK_PACKAGE_VERSION "${PACKAGE_VERSION}") + set(CPACK_PACKAGE_VERSION_MAJOR "${PACKAGE_VERSION_MAJOR}") + set(CPACK_PACKAGE_VERSION_MINOR "${PACKAGE_VERSION_MINOR}") + set(CPACK_PACKAGE_VERSION_PATCH "${PACKAGE_VERSION_PATCH}") + set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "${PACKAGE_DESCRIPTION}") + set(CPACK_RESOURCE_FILE_WELCOME "${CMAKE_CURRENT_BINARY_DIR}/README.txt") + set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_LIST_DIR}/COPYING.txt") + set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_BINARY_DIR}/README.txt") + set(CPACK_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") + set(CPACK_OUTPUT_FILE_PREFIX packages) + set(CPACK_PACKAGE_RELOCATABLE TRUE) + set(CPACK_MONOLITHIC_INSTALL TRUE) + + # RPM package information -- used in cmake/package.cmake.in also for DEB + set(CPACK_RPM_PACKAGE_GROUP "Development/Libraries") + set(CPACK_RPM_PACKAGE_LICENSE "BSD") + set(CPACK_RPM_PACKAGE_URL "${PACKAGE_URL}") + set(CPACK_RPM_CHANGELOG_FILE "${CMAKE_CURRENT_LIST_DIR}/ChangeLog.txt") + + if(INSTALL_HEADERS) + set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_LIST_DIR}/doc/index.html") + else() + set(CPACK_RESOURCE_FILE_README + "${CMAKE_CURRENT_LIST_DIR}/cmake/README_runtime.txt") + endif() + + # system/architecture + if(WINDOWS) + if(CMAKE_CL_64) + set(CPACK_SYSTEM_NAME "win64") + else() + set(CPACK_SYSTEM_NAME "win32") + endif() + set(CPACK_PACKAGE_ARCHITECTURE) + elseif(APPLE) + set(CPACK_PACKAGE_ARCHITECTURE darwin) + else() + string(TOLOWER "${CMAKE_SYSTEM_NAME}" CPACK_SYSTEM_NAME) + if(CMAKE_CXX_FLAGS MATCHES "-m32") + set(CPACK_PACKAGE_ARCHITECTURE i386) + else() + execute_process( + COMMAND dpkg --print-architecture + RESULT_VARIABLE RV + OUTPUT_VARIABLE CPACK_PACKAGE_ARCHITECTURE) + if(RV EQUAL 0) + string(STRIP "${CPACK_PACKAGE_ARCHITECTURE}" CPACK_PACKAGE_ARCHITECTURE) + else() + execute_process(COMMAND uname -m + OUTPUT_VARIABLE CPACK_PACKAGE_ARCHITECTURE) + if(CPACK_PACKAGE_ARCHITECTURE MATCHES "x86_64") + set(CPACK_PACKAGE_ARCHITECTURE amd64) + else() + set(CPACK_PACKAGE_ARCHITECTURE i386) + endif() + endif() + endif() + endif() + + # source package settings + set(CPACK_SOURCE_TOPLEVEL_TAG "source") + set(CPACK_SOURCE_PACKAGE_FILE_NAME + "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}") + set(CPACK_SOURCE_IGNORE_FILES + "/\\\\.git/;\\\\.swp$;\\\\.#;/#;\\\\.*~;cscope\\\\.*;/[Bb]uild[.+-_a-zA-Z0-9]*/" + ) + + # default binary package settings + set(CPACK_INCLUDE_TOPLEVEL_DIRECTORY TRUE) + set(CPACK_PACKAGE_FILE_NAME + "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-${CPACK_SYSTEM_NAME}") + if(CPACK_PACKAGE_ARCHITECTURE) + set(CPACK_PACKAGE_FILE_NAME + "${CPACK_PACKAGE_FILE_NAME}-${CPACK_PACKAGE_ARCHITECTURE}") + endif() + + # generator specific configuration file + # + # allow package maintainers to use their own configuration file $ cmake + # -DCPACK_PROJECT_CONFIG_FILE:FILE=/path/to/package/config + if(NOT CPACK_PROJECT_CONFIG_FILE) + configure_file("${CMAKE_CURRENT_LIST_DIR}/cmake/package.cmake.in" + "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-package.cmake" @ONLY) + set(CPACK_PROJECT_CONFIG_FILE + "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-package.cmake") + endif() + + include(CPack) + +endif() # BUILD_PACKAGING + +if(NOT GFLAGS_IS_SUBPROJECT AND NOT TARGET uninstall) + configure_file("${CMAKE_CURRENT_SOURCE_DIR}/cmake/cmake_uninstall.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" @ONLY) + add_custom_target( + uninstall COMMAND ${CMAKE_COMMAND} -P + "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake") +endif() diff --git a/third_party/gflags/COPYING.txt b/third_party/gflags/COPYING.txt new file mode 100644 index 0000000..d15b0c2 --- /dev/null +++ b/third_party/gflags/COPYING.txt @@ -0,0 +1,28 @@ +Copyright (c) 2006, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/third_party/gflags/ChangeLog.txt b/third_party/gflags/ChangeLog.txt new file mode 100644 index 0000000..ecdd465 --- /dev/null +++ b/third_party/gflags/ChangeLog.txt @@ -0,0 +1,276 @@ +* Sun Nov 11 2018 - Andreas Schuh + +- gflags: version 2.2.2 +Fixed 267: Support build with GCC option "-fvisibility=hidden". +Fixed 262: Declare FALGS_no##name variables as static to avoid "previous extern" warning. +Fixed 261: Declare FlagRegisterer c’tor explicit template instanations as extern in header +Fixed 257: Build with _UNICODE support on Windows. +Fixed 233/234/235: Move CMake defines that are unused by Bazel to separate header; makes config.h private again +Fixed 228: Build with recent MinGW versions that define setenv. +Fixed 226: Remove obsolete and unused CleanFileName code +Merged 266: Various PVS Studio and GCC warnings. +Merged 258: Fix build with some Clang variants that define "restrict" macro. +Merged 252: Update documentation on how to use Bazel. +Merged 249: Use "_debug" postfix for debug libraries. +Merged 247: CMake "project" VERSION; no enable_testing(); "gflags::" import target prefix. +Merged 246: Add Bazel-on-Windows support. +Merged 239: Use GFLAGS_NAMESPACE instead of "gflags" in test executable. +Merged 237: Removed unused functions; fixes compilation with -Werror compiler option. +Merged 232: Fix typo in Bazel's BUILD definition +Merged 230: Remove using ::fLS::clstring. +Merged 221: Add convenience 'uninstall' target + +* Tue Jul 11 2017 - Andreas Schuh + +- gflags: version 2.2.1 +- Link to online documentation in README +- Merged 194: Include utils by file instead of CMAKE_MODULE_PATH search +- Merged 195: Remove unused program_name variable +- Merged 196: Enable language C for older CMake versions when needed +- Merged 202: Changed include directory in bazel build +- Merged 207: Mark single argument constructors in mutex.h as explicit +- Merged 209: Use inttypes.h on VC++ 2013 and later +- Merged 212: Fix statically linked gflags library with MSVC +- Meregd 213: Modify installation paths on Windows for vcpkg +- Merged 215: Fix static initialization order fiasco caused by global registry lock +- Merged 216: Fix use of ARGC in CMake macros +- Merged 222: Static code analyzer error regarding strncmp with empty kRootDir +- Merged 224: Check HAVE_STDINT_H or HAVE_INTTYPES_H for older MSVC versions + +* Fri Nov 25 2016 - Andreas Schuh + +- gflags: version 2.2.0 +- Merged 178: Implicitly convert dashes in option names to underscores +- Merged 159: CI builds and automatic tests with Travis CI and AppVeyor +- Merged 158: Use enum for flag value types +- Merged 126: File name postfix for static libraries on Windows +- Closed issue 120: Configure and install gflags.pc file for pkg-config users +- Fixed issue 127: snprintf already defined when building with MSVC 2015 +- Fixed issue 51/138: Memory leaks reported by valgrind +- Fixed issue 173: Validate flags only once +- Fixed issue 168: Unsigned and signed comparison in gflags_reporting.cc +- Fixed issues 176/153: Add -lpthread link argument to Bazel build, refactor BUILD rules +- Fixed issue 89: Add GFLAGS_IS_A_DLL to imported CMake target INTERFACE_COMPILE_DEFINITIONS +- Fixed issue 104: Set INTERFACE_INCLUDE_DIRECTORIES of exported CMake targets +- Fixed issue 174: Missing gflags-targets.cmake file after installation +- Fixed issue 186: Error linking to gflags IMPLIB with MSVC using CMake +- Closed issue 106: Add example project to test use of gflags library + +* Tue Mar 24 2014 - Andreas Schuh + +- gflags: version 2.1.2 +- Moved project to GitHub +- Added GFLAGS_NAMESPACE definition to gflags_declare.h +- Fixed issue 94: Keep "google" as primary namespace and import symbols into "gflags" namespace +- Fixed issue 96: Fix binary ABI compatibility with gflags 2.0 using "google" as primary namespace +- Fixed issue 97/101: Removed (patched) CMake modules and enabled C language instead +- Fixed issue 103: Set CMake policy CMP0042 to silence warning regarding MACOS_RPATH setting + +* Sun Mar 20 2014 - Andreas Schuh + +- gflags: version 2.1.1 +- Fixed issue 77: GFLAGS_IS_A_DLL expands to empty string in gflags_declare.h +- Fixed issue 79: GFLAGS_NAMESPACE not expanded to actual namespace in gflags_declare.h +- Fixed issue 80: Allow include path to differ from GFLAGS_NAMESPACE + +* Thu Mar 20 2014 - Andreas Schuh + +- gflags: version 2.1.0 +- Build system configuration using CMake instead of autotools +- CPack packaging support for Debian/Ubuntu, Red Hat, and Mac OS X +- Fixed issue 54: Fix "invalid suffix on literal" (C++11) +- Fixed issue 57: Use _strdup instead of strdup on Windows +- Fixed issue 62: Change all preprocessor include guards to start with GFLAGS_ +- Fixed issue 64: Add DEFINE_validator macro +- Fixed issue 73: Warnings in Visual Studio 2010 and unable to compile unit test + +* Wed Jan 25 2012 - Google Inc. + +- gflags: version 2.0 +- Changed the 'official' gflags email in setup.py/etc +- Renamed google-gflags.sln to gflags.sln +- Changed copyright text to reflect Google's relinquished ownership + +* Tue Dec 20 2011 - Google Inc. + +- google-gflags: version 1.7 +- Add CommandLineFlagInfo::flag_ptr pointing to current storage (musji) +- PORTING: flush after writing to stderr, needed on cygwin +- PORTING: Clean up the GFLAGS_DLL_DECL stuff better +- Fix a bug in StringPrintf() that affected large strings (csilvers) +- Die at configure-time when g++ isn't installed + +* Fri Jul 29 2011 - Google Inc. + +- google-gflags: version 1.6 +- BUGFIX: Fix a bug where we were leaving out a required $(top_srcdir) +- Fix definition of clstring (jyrki) +- Split up flag declares into its own file (jyrki) +- Add --version support (csilvers) +- Update the README for gflags with static libs +- Update acx_pthread.m4 for nostdlib +- Change ReparseCommandLineFlags to return void (csilvers) +- Some doc typofixes and example augmentation (various) + +* Mon Jan 24 2011 - Google Inc. + +- google-gflags: version 1.5 +- Better reporting of current vs default value (handler) +- Add API for cleaning up of memory at program-exit (jmarantz) +- Fix macros to work inside namespaces (csilvers) +- Use our own string typedef in case string is redefined (csilvers) +- Updated to autoconf 2.65 + +* Wed Oct 13 2010 - Google Inc. + +- google-gflags: version 1.4 +- Add a check to prevent passing 0 to DEFINE_string (jorg) +- Reduce compile (.o) size (jyrki) +- Some small changes to quiet debug compiles (alexk) +- PORTING: better support static linking on windows (csilvers) +- DOCUMENTATION: change default values, use validators, etc. +- Update the NEWS file to be non-empty +- Add pkg-config (.pc) files for libgflags and libgflags_nothreads + +* Mon Jan 4 2010 - Google Inc. + +- google-gflags: version 1.3 +- PORTABILITY: can now build and run tests under MSVC (csilvers) +- Remove the python gflags code, which is now its own package (tansell) +- Clarify that "last flag wins" in the docs (csilvers) +- Comment danger of using GetAllFlags in validators (wojtekm) +- PORTABILITY: Some fixes necessary for c++0x (mboerger) +- Makefile fix: $(srcdir) -> $(top_srcdir) in one place (csilvres) +- INSTALL: autotools to autoconf v2.64 + automake v1.11 (csilvers) + +* Thu Sep 10 2009 - Google Inc. + +- google-gflags: version 1.2 +- PORTABILITY: can now build and run tests under mingw (csilvers) +- Using a string arg for a bool flag is a compile-time error (rbayardo) +- Add --helpxml to gflags.py (salcianu) +- Protect against a hypothetical global d'tor mutex problem (csilvers) +- BUGFIX: can now define a flag after 'using namespace google' (hamaji) + +* Tue Apr 14 2009 - Google Inc. + +- google-gflags: version 1.1 +- Add both foo and nofoo for boolean flags, with --undefok (andychu) +- Better document how validators work (wojtekm) +- Improve binary-detection for bash-completion (mtamsky) +- Python: Add a concept of "key flags", used with --help (salcianu) +- Python: Robustify flag_values (salcianu) +- Python: Add a new DEFINE_bool alias (keir, andrewliu) +- Python: Do module introspection based on module name (dsturtevant) +- Fix autoconf a bit better, especially on windows and solaris (ajenjo) +- BUG FIX: gflags_nothreads was linking against the wrong lib (ajenjo) +- BUG FIX: threads-detection failed on FreeBSD; replace it (ajenjo) +- PORTABILITY: Quiet an internal compiler error with SUSE 10 (csilvers) +- PORTABILITY: Update deb.sh for more recenty debuilds (csilvers) +- PORTABILITY: #include more headers to satify new gcc's (csilvers) +- INSTALL: Updated to autoconf 2.61 and libtool 1.5.26 (csilvers) + +* Fri Oct 3 2008 - Google Inc. + +- google-gflags: version 1.0 +- Add a missing newline to an error string (bcmills) +- (otherwise exactly the same as gflags 1.0rc2) + +* Thu Sep 18 2008 - Google Inc. + +- google-gflags: version 1.0rc2 +- Report current flag values in --helpxml (hdn) +- Fix compilation troubles with gcc 4.3.3 (simonb) +- BUG FIX: I was missing a std:: in DECLARE_string (csilvers) +- BUG FIX: Clarify in docs how to specify --bool flags (csilvers) +- BUG FIX: Fix --helpshort for source files not in a subdir (csilvers) +- BUG FIX: Fix python unittest for 64-bit builds (bcmills) + +* Tue Aug 19 2008 - Google Inc. + +- google-gflags: version 1.0rc1 +- Move #include files from google/ to gflags/ (csilvers) +- Small optimizations to reduce binary (library) size (jyrki) +- BUGFIX: forgot a std:: in one of the .h files (csilvers) +- Speed up locking by making sure calls are inlined (ajenjo) +- 64-BIT COMPATIBILITY: Use %PRId64 instead of %lld (csilvers) +- PORTABILITY: fix Makefile to work with Cygwin (ajenjo) +- PORTABILITY: fix code to compile under Visual Studio (ajenjo) +- PORTABILITY: fix code to compile under Solaris 10 with CC (csilvers) + +* Mon Jul 21 2008 - Google Inc. + +- google-gflags: version 0.9 +- Add the ability to validate a command-line flag (csilvers) +- Add completion support for commandline flags in bash (daven) +- Add -W compile flags to Makefile, when using gcc (csilvers) +- Allow helpstring to be NULL (cristianoc) +- Improved documentation of classes in the .cc file (csilvers) +- Fix python bug with AppendFlagValues + shortnames (jjtswan) +- Use bool instead of int for boolean flags in gflags.py (bcmills) +- Simplify the way we declare flags, now more foolproof (csilvers) +- Better error messages when bool flags collide (colohan) +- Only evaluate DEFINE_foo macro args once (csilvers) + +* Wed Mar 26 2008 - Google Inc. + +- google-gflags: version 0.8 +- Export DescribeOneFlag() in the API +- Add support for automatic line wrapping at 80 cols for gflags.py +- Bugfix: do not treat an isolated "-" the same as an isolated "--" +- Update rpm spec to point to Google Code rather than sourceforge (!) +- Improve documentation (including documenting thread-safety) +- Improve #include hygiene +- Improve testing + +* Thu Oct 18 2007 - Google Inc. + +- google-gflags: version 0.7 +- Deal even more correctly with libpthread not linked in (csilvers) +- Add STRIP_LOG, an improved DO_NOT_SHOW_COMMANDLINE_HELP (sioffe) +- Be more accurate printing default flag values in --help (dsturtevant) +- Reduce .o file size a bit by using shorter namespace names (jeff) +- Use relative install path, so 'setup.py --home' works (csilvers) +- Notice when a boolean flag has a non-boolean default (bnmouli) +- Broaden --helpshort to match foo-main.cc and foo_main.cc (hendrie) +- Fix "no modules match" message for --helpshort, etc (hendrie) + +* Wed Aug 15 2007 - Google Inc. + +- google-gflags: version 0.6 +- Deal correctly with case that libpthread is not linked in (csilvers) +- Update Makefile/tests so we pass "make distcheck" (csilvers) +- Document and test that last assignment to a flag wins (wan) + +* Tue Jun 12 2007 - Google Inc. + +- google-gflags: version 0.5 +- Include all m4 macros in the distribution (csilvers) +- Python: Fix broken data_files field in setup.py (sidlon) +- Python: better string serliaizing and unparsing (abo, csimmons) +- Fix checks for NaN and inf to work with Mac OS X (csilvers) + +* Thu Apr 19 2007 - Google Inc. + +- google-gflags: version 0.4 +- Remove is_default from GetCommandLineFlagInfo (csilvers) +- Portability fixes: includes, strtoll, gcc4.3 errors (csilvers) +- A few doc typo cleanups (csilvers) + +* Wed Mar 28 2007 - Google Inc. + +- google-gflags: version 0.3 +- python portability fix: use popen instead of subprocess (csilvers) +- Add is_default to CommandLineFlagInfo (pchien) +- Make docs a bit prettier (csilvers) +- Actually include the python files in the distribution! :-/ (csilvers) + +* Mon Jan 22 2007 - Google Inc. + +- google-gflags: version 0.2 +- added support for python commandlineflags, as well as c++ +- gflags2man, a script to turn flags into a man page (dchristian) + +* Wed Dec 13 2006 - Google Inc. + +- google-gflags: version 0.1 diff --git a/third_party/gflags/INSTALL.md b/third_party/gflags/INSTALL.md new file mode 100644 index 0000000..76d7edd --- /dev/null +++ b/third_party/gflags/INSTALL.md @@ -0,0 +1,83 @@ +Installing a binary distribution package +======================================== + +No official binary distribution packages are provided by the gflags developers. +There may, however, be binary packages available for your OS. Please consult +also the package repositories of your Linux distribution. + +For example on Debian/Ubuntu Linux, gflags can be installed using the +following command: + + sudo apt-get install libgflags-dev + + +Compiling the source code with CMake +========================= + +The build system of gflags is since version 2.1 based on [CMake](http://cmake.org). +The common steps to build, test, and install software are therefore: + +1. Extract source files. +2. Create build directory and change to it. +3. Run CMake to configure the build tree. +4. Build the software using selected build tool. +5. Test the built software. +6. Install the built files. + +On Unix-like systems with GNU Make as build tool, these build steps can be +summarized by the following sequence of commands executed in a shell, +where ```$package``` and ```$version``` are shell variables which represent +the name of this package and the obtained version of the software. + + $ tar xzf gflags-$version-source.tar.gz + $ cd gflags-$version + $ mkdir build && cd build + $ ccmake .. + + - Press 'c' to configure the build system and 'e' to ignore warnings. + - Set CMAKE_INSTALL_PREFIX and other CMake variables and options. + - Continue pressing 'c' until the option 'g' is available. + - Then press 'g' to generate the configuration files for GNU Make. + + $ make + $ make test (optional) + $ make install (optional) + +In the following, only gflags-specific CMake settings available to +configure the build and installation are documented. Note that most of these +variables are for advanced users and binary package maintainers only. +They usually do not have to be modified. + + +CMake Option | Description +--------------------------- | ------------------------------------------------------- +CMAKE_INSTALL_PREFIX | Installation directory, e.g., "/usr/local" on Unix and "C:\Program Files\gflags" on Windows. +BUILD_SHARED_LIBS | Request build of dynamic link libraries. +BUILD_STATIC_LIBS | Request build of static link libraries. Implied if BUILD_SHARED_LIBS is OFF. +BUILD_PACKAGING | Enable binary package generation using CPack. +BUILD_TESTING | Build tests for execution by CTest. +BUILD_NC_TESTS | Request inclusion of negative compilation tests (requires Python). +BUILD_CONFIG_TESTS | Request inclusion of package configuration tests (requires Python). +BUILD_gflags_LIBS | Request build of multi-threaded gflags libraries (if threading library found). +BUILD_gflags_nothreads_LIBS | Request build of single-threaded gflags libraries. +GFLAGS_NAMESPACE | Name of the C++ namespace to be used by the gflags library. Note that the public source header files are installed in a subdirectory named after this namespace. To maintain backwards compatibility with the Google Commandline Flags, set this variable to "google". The default is "gflags". +GFLAGS_INTTYPES_FORMAT | String identifying format of built-in integer types. +GFLAGS_INCLUDE_DIR | Name of headers installation directory relative to CMAKE_INSTALL_PREFIX. +LIBRARY_INSTALL_DIR | Name of library installation directory relative to CMAKE_INSTALL_PREFIX. +INSTALL_HEADERS | Request installation of public header files. + +Using gflags with [Bazel](http://bazel.io) +========================= + +To use gflags in a Bazel project, map it in as an external dependency by editing +your WORKSPACE file: + + git_repository( + name = "com_github_gflags_gflags", + commit = "", + remote = "https://github.com/gflags/gflags.git", + ) + +You can then add `@com_github_gflags_gflags//:gflags` to the `deps` section of a +`cc_binary` or `cc_library` rule, and `#include ` to include it +in your source code. diff --git a/third_party/gflags/README.md b/third_party/gflags/README.md new file mode 100644 index 0000000..6e5267c --- /dev/null +++ b/third_party/gflags/README.md @@ -0,0 +1,320 @@ +[![Build Status](https://travis-ci.org/gflags/gflags.svg?branch=master)](https://travis-ci.org/gflags/gflags) +[![Build status](https://ci.appveyor.com/api/projects/status/4ctod566ysraus74/branch/master?svg=true)](https://ci.appveyor.com/project/schuhschuh/gflags/branch/master) + +The documentation of the gflags library is available online at https://gflags.github.io/gflags/. + + +11 November 2018 +---------------- + +I've just released gflags 2.2.2. + +This maintenance release improves lives of Bazel users (no more "config.h" leaking into global include paths), +fixes build with recent MinGW versions, and silences a number of static code analyzer and compiler warnings. +The build targets exported by the CMake configuration of this library are now also prefixed by the package +name "gflags::" following a more recent (unwritten) CMake convention. The unprefixed target names are still +supported to avoid that dependent projects have to be modified due to this change in imported target names. + +Please report any further issues with this release using the GitHub issue tracker. + + +11 July 2017 +------------ + +I've just released gflags 2.2.1. + +This maintenance release primarily fixes build issues on Windows and +false alarms reported by static code analyzers. + +Please report any further issues with this release using the GitHub issue tracker. + + +25 November 2016 +---------------- + +I've finally released gflags 2.2.0. + +This release adds support for use of the gflags library as external dependency +not only in projects using CMake, but also [Bazel](https://bazel.build/), +or [pkg-config](https://www.freedesktop.org/wiki/Software/pkg-config/). +One new minor feature is added in this release: when a command flag argument +contains dashes, these are implicitly converted to underscores. +This is to allow those used to separate words of the flag name by dashes +to do so, while the flag variable names are required to use underscores. + +Memory leaks reported by valgrind should be resolved by this release. +This release fixes build errors with MS Visual Studio 2015. + +Please report any further issues with this release using the GitHub issue tracker. + + +24 March 2015 +------------- + +I've just released gflags 2.1.2. + +This release completes the namespace change fixes. In particular, +it restores binary ABI compatibility with release version 2.0. +The deprecated "google" namespace is by default still kept as +primary namespace while symbols are imported into the new "gflags" namespace. +This can be overridden using the CMake variable GFLAGS_NAMESPACE. + +Other fixes of the build configuration are related to the (patched) +CMake modules FindThreads.cmake and CheckTypeSize.cmake. These have +been removed and instead the C language is enabled again even though +gflags is written in C++ only. + +This release also marks the complete move of the gflags project +from Google Code to GitHub. Email addresses of original issue +reporters got lost in the process. Given the age of most issue reports, +this should be negligable. + +Please report any further issues using the GitHub issue tracker. + + +30 March 2014 +------------- + +I've just released gflags 2.1.1. + +This release fixes a few bugs in the configuration of gflags\_declare.h +and adds a separate GFLAGS\_INCLUDE\_DIR CMake variable to the build configuration. +Setting GFLAGS\_NAMESPACE to "google" no longer changes also the include +path of the public header files. This allows the use of the library with +other Google projects such as glog which still use the deprecated "google" +namespace for the gflags library, but include it as "gflags/gflags.h". + +20 March 2014 +------------- + +I've just released gflags 2.1. + +The major changes are the use of CMake for the build configuration instead +of the autotools and packaging support through CPack. The default namespace +of all C++ symbols is now "gflags" instead of "google". This can be +configured via the GFLAGS\_NAMESPACE variable. + +This release compiles with all major compilers without warnings and passed +the unit tests on Ubuntu 12.04, Windows 7 (Visual Studio 2008 and 2010, +Cygwin, MinGW), and Mac OS X (Xcode 5.1). + +The SVN repository on Google Code is now frozen and replaced by a Git +repository such that it can be used as Git submodule by projects. The main +hosting of this project remains at Google Code. Thanks to the distributed +character of Git, I can push (and pull) changes from both GitHub and Google Code +in order to keep the two public repositories in sync. +When fixing an issue for a pull request through either of these hosting +platforms, please reference the issue number as +[described here](https://code.google.com/p/support/wiki/IssueTracker#Integration_with_version_control). +For the further development, I am following the +[Git branching model](http://nvie.com/posts/a-successful-git-branching-model/) +with feature branch names prefixed by "feature/" and bugfix branch names +prefixed by "bugfix/", respectively. + +Binary and source [packages](https://github.com/schuhschuh/gflags/releases) are available on GitHub. + + +14 January 2014 +--------------- + +The migration of the build system to CMake is almost complete. +What remains to be done is rewriting the tests in Python such they can be +executed on non-Unix platforms and splitting them up into separate CTest tests. +Though merging these changes into the master branch yet remains to be done, +it is recommended to already start using the +[cmake-migration](https://github.com/schuhschuh/gflags/tree/cmake-migration) branch. + + +20 April 2013 +------------- + +More than a year has past since I (Andreas) took over the maintenance for +`gflags`. Only few minor changes have been made since then, much to my regret. +To get more involved and stimulate participation in the further +development of the library, I moved the project source code today to +[GitHub](https://github.com/schuhschuh/gflags). +I believe that the strengths of [Git](http://git-scm.com/) will allow for better community collaboration +as well as ease the integration of changes made by others. I encourage everyone +who would like to contribute to send me pull requests. +Git's lightweight feature branches will also provide the right tool for more +radical changes which should only be merged back into the master branch +after these are complete and implement the desired behavior. + +The SVN repository remains accessible at Google Code and I will keep the +master branch of the Git repository hosted at GitHub and the trunk of the +Subversion repository synchronized. Initially, I was going to simply switch the +Google Code project to Git, but in this case the SVN repository would be +frozen and force everyone who would like the latest development changes to +use Git as well. Therefore I decided to host the public Git repository at GitHub +instead. + +Please continue to report any issues with gflags on Google Code. The GitHub project will +only be used to host the Git repository. + +One major change of the project structure I have in mind for the next weeks +is the migration from autotools to [CMake](http://www.cmake.org/). +Check out the (unstable!) +[cmake-migration](https://github.com/schuhschuh/gflags/tree/cmake-migration) +branch on GitHub for details. + + +25 January 2012 +--------------- + +I've just released gflags 2.0. + +The `google-gflags` project has been renamed to `gflags`. I +(csilvers) am stepping down as maintainer, to be replaced by Andreas +Schuh. Welcome to the team, Andreas! I've seen the energy you have +around gflags and the ideas you have for the project going forward, +and look forward to having you on the team. + +I bumped the major version number up to 2 to reflect the new community +ownership of the project. All the [changes](ChangeLog.txt) +are related to the renaming. There are no functional changes from +gflags 1.7. In particular, I've kept the code in the namespace +`google`, though in a future version it should be renamed to `gflags`. +I've also kept the `/usr/local/include/google/` subdirectory as +synonym of `/usr/local/include/gflags/`, though the former name has +been obsolete for some time now. + + +18 January 2011 +--------------- + +The `google-gflags` Google Code page has been renamed to +`gflags`, in preparation for the project being renamed to +`gflags`. In the coming weeks, I'll be stepping down as +maintainer for the gflags project, and as part of that Google is +relinquishing ownership of the project; it will now be entirely +community run. The name change reflects that shift. + + +20 December 2011 +---------------- + +I've just released gflags 1.7. This is a minor release; the major +change is that `CommandLineFlagInfo` now exports the address in memory +where the flag is located. There has also been a bugfix involving +very long --help strings, and some other minor [changes](ChangeLog.txt). + +29 July 2011 +------------ + +I've just released gflags 1.6. The major new feature in this release +is support for setting version info, so that --version does something +useful. + +One minor change has required bumping the library number: +`ReparseCommandlineFlags` now returns `void` instead of `int` (the int +return value was always meaningless). Though I doubt anyone ever used +this (meaningless) return value, technically it's a change to the ABI +that requires a version bump. A bit sad. + +There's also a procedural change with this release: I've changed the +internal tools used to integrate Google-supplied patches for gflags +into the opensource release. These new tools should result in more +frequent updates with better change descriptions. They will also +result in future `ChangeLog` entries being much more verbose (for better +or for worse). + +See the [ChangeLog](ChangeLog.txt) for a full list of changes for this release. + +24 January 2011 +--------------- + +I've just released gflags 1.5. This release has only minor changes +from 1.4, including some slightly better reporting in --help, and +an new memory-cleanup function that can help when running gflags-using +libraries under valgrind. The major change is to fix up the macros +(`DEFINE_bool` and the like) to work more reliably inside namespaces. + +If you have not had a problem with these macros, and don't need any of +the other changes described, there is no need to upgrade. See the +[ChangeLog](ChangeLog.txt) for a full list of changes for this release. + +11 October 2010 +--------------- + +I've just released gflags 1.4. This release has only minor changes +from 1.3, including some documentation tweaks and some work to make +the library smaller. If 1.3 is working well for you, there's no +particular reason to upgrade. + +4 January 2010 +-------------- + +I've just released gflags 1.3. gflags now compiles under MSVC, and +all tests pass. I **really** never thought non-unix-y Windows folks +would want gflags, but at least some of them do. + +The major news, though, is that I've separated out the python package +into its own library, [python-gflags](http://code.google.com/p/python-gflags). +If you're interested in the Python version of gflags, that's the place to +get it now. + +10 September 2009 +----------------- + +I've just released gflags 1.2. The major change from gflags 1.1 is it +now compiles under MinGW (as well as cygwin), and all tests pass. I +never thought Windows folks would want unix-style command-line flags, +since they're so different from the Windows style, but I guess I was +wrong! + +The other changes are minor, such as support for --htmlxml in the +python version of gflags. + +15 April 2009 +------------- + +I've just released gflags 1.1. It has only minor changes fdrom gflags +1.0 (see the [ChangeLog](ChangeLog.txt) for details). +The major change is that I moved to a new system for creating .deb and .rpm files. +This allows me to create x86\_64 deb and rpm files. + +In the process of moving to this new system, I noticed an +inconsistency: the tar.gz and .rpm files created libraries named +libgflags.so, but the deb file created libgoogle-gflags.so. I have +fixed the deb file to create libraries like the others. I'm no expert +in debian packaging, but I believe this has caused the package name to +change as well. Please let me know (at +[[mailto:google-gflags@googlegroups.com](mailto:google-gflags@googlegroups.com) +google-gflags@googlegroups.com]) if this causes problems for you -- +especially if you know of a fix! I would be happy to change the deb +packages to add symlinks from the old library name to the new +(libgoogle-gflags.so -> libgflags.so), but that is beyond my knowledge +of how to make .debs. + +If you've tried to install a .rpm or .deb and it doesn't work for you, +let me know. I'm excited to finally have 64-bit package files, but +there may still be some wrinkles in the new system to iron out. + +1 October 2008 +-------------- + +gflags 1.0rc2 was out for a few weeks without any issues, so gflags +1.0 is now released. This is much like gflags 0.9. The major change +is that the .h files have been moved from `/usr/include/google` to +`/usr/include/gflags`. While I have backwards-compatibility +forwarding headeds in place, please rewrite existing code to say +``` + #include +``` +instead of +``` + #include +``` + +I've kept the default namespace to google. You can still change with +with the appropriate flag to the configure script (`./configure +--help` to see the flags). If you have feedback as to whether the +default namespace should change to gflags, which would be a +non-backwards-compatible change, send mail to +`google-gflags@googlegroups.com`! + +Version 1.0 also has some neat new features, like support for bash +commandline-completion of help flags. See the [ChangeLog](ChangeLog.txt) +for more details. + +If I don't hear any bad news for a few weeks, I'll release 1.0-final. diff --git a/third_party/gflags/WORKSPACE b/third_party/gflags/WORKSPACE new file mode 100644 index 0000000..f3707e9 --- /dev/null +++ b/third_party/gflags/WORKSPACE @@ -0,0 +1,6 @@ +# Copyright 2006 Google Inc. All Rights Reserved. +# Use of this source code is governed by a BSD-style +# license that can be found in the COPYING.txt file. + +# Bazel (http://bazel.io/) WORKSPACE file for gflags. +workspace(name="com_github_gflags_gflags") diff --git a/third_party/gflags/appveyor.yml b/third_party/gflags/appveyor.yml new file mode 100644 index 0000000..a5110e5 --- /dev/null +++ b/third_party/gflags/appveyor.yml @@ -0,0 +1,68 @@ +# Configuration for continuous integration service at appveyor.com + +version: '{build}' + +os: Visual Studio 2015 + +environment: + matrix: + - Toolset: v140 + - Toolset: v120 + - Toolset: v110 + - Toolset: v100 + - Toolset: v90 + +platform: + - Win32 + - x64 + +configuration: + - Release + +matrix: + exclude: + - Toolset: v90 + platform: x64 + - Toolset: v100 + platform: x64 + +build: + verbosity: minimal + +before_build: +- ps: | + Write-Output "Configuration: $env:CONFIGURATION" + Write-Output "Platform: $env:PLATFORM" + $generator = switch ($env:TOOLSET) + { + "v140" {"Visual Studio 14 2015"} + "v120" {"Visual Studio 12 2013"} + "v110" {"Visual Studio 11 2012"} + "v100" {"Visual Studio 10 2010"} + "v90" {"Visual Studio 9 2008"} + } + if ($env:PLATFORM -eq "x64") + { + $generator = "$generator Win64" + } + +build_script: +- ps: | + md _build -Force | Out-Null + cd _build + + & cmake -G "$generator" -D CMAKE_CONFIGURATION_TYPES="Debug;Release" -D GFLAGS_BUILD_TESTING=ON -D GFLAGS_BUILD_SHARED_LIBS=ON -D GFLAGS_BUILD_STATIC_LIBS=ON .. + if ($LastExitCode -ne 0) { + throw "Exec: $ErrorMessage" + } + & cmake --build . --config $env:CONFIGURATION + if ($LastExitCode -ne 0) { + throw "Exec: $ErrorMessage" + } + +test_script: +- ps: | + & ctest -C $env:CONFIGURATION --output-on-failure + if ($LastExitCode -ne 0) { + throw "Exec: $ErrorMessage" + } diff --git a/third_party/gflags/bazel/gflags.bzl b/third_party/gflags/bazel/gflags.bzl new file mode 100644 index 0000000..533fd61 --- /dev/null +++ b/third_party/gflags/bazel/gflags.bzl @@ -0,0 +1,103 @@ +# ------------------------------------------------------------------------------ +# Add native rules to configure source files +def gflags_sources(namespace=["google", "gflags"]): + native.genrule( + name = "gflags_declare_h", + srcs = ["src/gflags_declare.h.in"], + outs = ["gflags_declare.h"], + cmd = ("awk '{ " + + "gsub(/@GFLAGS_NAMESPACE@/, \"" + namespace[0] + "\"); " + + "gsub(/@(HAVE_STDINT_H|HAVE_SYS_TYPES_H|HAVE_INTTYPES_H|GFLAGS_INTTYPES_FORMAT_C99)@/, \"1\"); " + + "gsub(/@([A-Z0-9_]+)@/, \"0\"); " + + "print; }' $(<) > $(@)") + ) + gflags_ns_h_files = [] + for ns in namespace[1:]: + gflags_ns_h_file = "gflags_{}.h".format(ns) + native.genrule( + name = gflags_ns_h_file.replace('.', '_'), + srcs = ["src/gflags_ns.h.in"], + outs = [gflags_ns_h_file], + cmd = ("awk '{ " + + "gsub(/@ns@/, \"" + ns + "\"); " + + "gsub(/@NS@/, \"" + ns.upper() + "\"); " + + "print; }' $(<) > $(@)") + ) + gflags_ns_h_files.append(gflags_ns_h_file) + native.genrule( + name = "gflags_h", + srcs = ["src/gflags.h.in"], + outs = ["gflags.h"], + cmd = ("awk '{ " + + "gsub(/@GFLAGS_ATTRIBUTE_UNUSED@/, \"\"); " + + "gsub(/@INCLUDE_GFLAGS_NS_H@/, \"" + '\n'.join(["#include \\\"gflags/{}\\\"".format(hdr) for hdr in gflags_ns_h_files]) + "\"); " + + "print; }' $(<) > $(@)") + ) + native.genrule( + name = "gflags_completions_h", + srcs = ["src/gflags_completions.h.in"], + outs = ["gflags_completions.h"], + cmd = "awk '{ gsub(/@GFLAGS_NAMESPACE@/, \"" + namespace[0] + "\"); print; }' $(<) > $(@)" + ) + hdrs = [":gflags_h", ":gflags_declare_h", ":gflags_completions_h"] + hdrs.extend([':' + hdr.replace('.', '_') for hdr in gflags_ns_h_files]) + srcs = [ + "src/config.h", + "src/gflags.cc", + "src/gflags_completions.cc", + "src/gflags_reporting.cc", + "src/mutex.h", + "src/util.h", + ] + select({ + "//:x64_windows": [ + "src/windows_port.cc", + "src/windows_port.h", + ], + "//conditions:default": [], + }) + return [hdrs, srcs] + +# ------------------------------------------------------------------------------ +# Add native rule to build gflags library +def gflags_library(hdrs=[], srcs=[], threads=1): + name = "gflags" + copts = [ + "-DGFLAGS_BAZEL_BUILD", + "-DGFLAGS_INTTYPES_FORMAT_C99", + "-DGFLAGS_IS_A_DLL=0", + # macros otherwise defined by CMake configured defines.h file + "-DHAVE_STDINT_H", + "-DHAVE_SYS_TYPES_H", + "-DHAVE_INTTYPES_H", + "-DHAVE_SYS_STAT_H", + "-DHAVE_STRTOLL", + "-DHAVE_STRTOQ", + "-DHAVE_RWLOCK", + ] + select({ + "//:x64_windows": [ + "-DOS_WINDOWS", + ], + "//conditions:default": [ + "-DHAVE_UNISTD_H", + "-DHAVE_FNMATCH_H", + "-DHAVE_PTHREAD", + ], + }) + linkopts = [] + if threads: + linkopts += select({ + "//:x64_windows": [], + "//conditions:default": ["-lpthread"], + }) + else: + name += "_nothreads" + copts += ["-DNO_THREADS"] + native.cc_library( + name = name, + hdrs = hdrs, + srcs = srcs, + copts = copts, + linkopts = linkopts, + visibility = ["//visibility:public"], + include_prefix = 'gflags' + ) diff --git a/third_party/gflags/cmake/README_runtime.txt b/third_party/gflags/cmake/README_runtime.txt new file mode 100644 index 0000000..d2556b2 --- /dev/null +++ b/third_party/gflags/cmake/README_runtime.txt @@ -0,0 +1,4 @@ +This package contains runtime libraries only which are required +by applications that use these libraries for the commandline flags +processing. If you want to develop such application, download +and install the development package instead. diff --git a/third_party/gflags/cmake/cmake_uninstall.cmake.in b/third_party/gflags/cmake/cmake_uninstall.cmake.in new file mode 100644 index 0000000..d00a516 --- /dev/null +++ b/third_party/gflags/cmake/cmake_uninstall.cmake.in @@ -0,0 +1,26 @@ +if(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") + message(FATAL_ERROR "Cannot find install manifest: @CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") +endif(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") + +if (NOT DEFINED CMAKE_INSTALL_PREFIX) + set (CMAKE_INSTALL_PREFIX "@CMAKE_INSTALL_PREFIX@") +endif () + message(${CMAKE_INSTALL_PREFIX}) + +file(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files) +string(REGEX REPLACE "\n" ";" files "${files}") +foreach(file ${files}) + message(STATUS "Uninstalling $ENV{DESTDIR}${file}") + if(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") + exec_program( + "@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\"" + OUTPUT_VARIABLE rm_out + RETURN_VALUE rm_retval + ) + if(NOT "${rm_retval}" STREQUAL 0) + message(FATAL_ERROR "Problem when removing $ENV{DESTDIR}${file}") + endif(NOT "${rm_retval}" STREQUAL 0) + else(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") + message(STATUS "File $ENV{DESTDIR}${file} does not exist.") + endif(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") +endforeach(file) diff --git a/third_party/gflags/cmake/config.cmake.in b/third_party/gflags/cmake/config.cmake.in new file mode 100644 index 0000000..a512c2a --- /dev/null +++ b/third_party/gflags/cmake/config.cmake.in @@ -0,0 +1,183 @@ +## gflags CMake configuration file + +# library version information +set (@PACKAGE_PREFIX@_VERSION_STRING "@PACKAGE_VERSION@") +set (@PACKAGE_PREFIX@_VERSION_MAJOR @PACKAGE_VERSION_MAJOR@) +set (@PACKAGE_PREFIX@_VERSION_MINOR @PACKAGE_VERSION_MINOR@) +set (@PACKAGE_PREFIX@_VERSION_PATCH @PACKAGE_VERSION_PATCH@) + +# import targets +if (NOT DEFINED @PACKAGE_PREFIX@_USE_TARGET_NAMESPACE) + set (@PACKAGE_PREFIX@_USE_TARGET_NAMESPACE FALSE) +endif () +if (@PACKAGE_PREFIX@_USE_TARGET_NAMESPACE) + include ("${CMAKE_CURRENT_LIST_DIR}/@EXPORT_NAME@.cmake") + set (@PACKAGE_PREFIX@_TARGET_NAMESPACE @PACKAGE_NAME@) +else () + include ("${CMAKE_CURRENT_LIST_DIR}/@PACKAGE_NAME@-nonamespace-targets.cmake") + set (@PACKAGE_PREFIX@_TARGET_NAMESPACE) +endif () +if (@PACKAGE_PREFIX@_TARGET_NAMESPACE) + set (@PACKAGE_PREFIX@_TARGET_PREFIX ${@PACKAGE_PREFIX@_TARGET_NAMESPACE}::) +else () + set (@PACKAGE_PREFIX@_TARGET_PREFIX) +endif () + +# installation prefix +get_filename_component (CMAKE_CURRENT_LIST_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) +get_filename_component (_INSTALL_PREFIX "${CMAKE_CURRENT_LIST_DIR}/@INSTALL_PREFIX_REL2CONFIG_DIR@" ABSOLUTE) + +# include directory +# +# Newer versions of CMake set the INTERFACE_INCLUDE_DIRECTORIES property +# of the imported targets. It is hence not necessary to add this path +# manually to the include search path for targets which link to gflags. +set (@PACKAGE_PREFIX@_INCLUDE_DIR "${_INSTALL_PREFIX}/@INCLUDE_INSTALL_DIR@") + +if (@PACKAGE_NAME@_FIND_COMPONENTS) + foreach (@PACKAGE_NAME@_FIND_COMPONENT IN LISTS @PACKAGE_NAME@_FIND_COMPONENTS) + if (@PACKAGE_NAME@_FIND_REQUIRED_${@PACKAGE_NAME@_FIND_COMPONENT} AND NOT TARGET @PACKAGE_NAME@_${@PACKAGE_NAME@_FIND_COMPONENT}) + message (FATAL_ERROR "Package @PACKAGE_NAME@ was installed without required component ${@PACKAGE_NAME@_FIND_COMPONENT}!") + endif () + endforeach () + list (GET @PACKAGE_NAME@_FIND_COMPONENTS 0 @PACKAGE_NAME@_FIND_COMPONENT) +else () + set (@PACKAGE_NAME@_FIND_COMPONENT) +endif () + +# default settings of @PACKAGE_PREFIX@_SHARED and @PACKAGE_PREFIX@_NOTHREADS +# +# It is recommended to use either one of the following find_package commands +# instead of setting the @PACKAGE_PREFIX@_(SHARED|NOTHREADS) variables: +# - find_package(@PACKAGE_NAME@ REQUIRED) +# - find_package(@PACKAGE_NAME@ COMPONENTS nothreads_static) +# - find_package(@PACKAGE_NAME@ COMPONENTS nothreads_shared) +# - find_package(@PACKAGE_NAME@ COMPONENTS static) +# - find_package(@PACKAGE_NAME@ COMPONENTS shared) +if (NOT DEFINED @PACKAGE_PREFIX@_SHARED) + if (DEFINED @PACKAGE_NAME@_SHARED) + set (@PACKAGE_PREFIX@_SHARED ${@PACKAGE_NAME@_SHARED}) + elseif (@PACKAGE_NAME@_FIND_COMPONENT) + if (@PACKAGE_NAME@_FIND_COMPONENT MATCHES "shared") + set (@PACKAGE_PREFIX@_SHARED TRUE) + else () + set (@PACKAGE_PREFIX@_SHARED FALSE) + endif () + elseif (TARGET ${@PACKAGE_PREFIX@_TARGET_PREFIX}@PACKAGE_NAME@_shared OR TARGET ${@PACKAGE_PREFIX@_TARGET_PREFIX}@PACKAGE_NAME@_nothreads_shared) + set (@PACKAGE_PREFIX@_SHARED TRUE) + else () + set (@PACKAGE_PREFIX@_SHARED FALSE) + endif () +endif () +if (NOT DEFINED @PACKAGE_PREFIX@_NOTHREADS) + if (DEFINED @PACKAGE_NAME@_NOTHREADS) + set (@PACKAGE_PREFIX@_NOTHREADS ${@PACKAGE_NAME@_NOTHREADS}) + elseif (@PACKAGE_NAME@_FIND_COMPONENT) + if (@PACKAGE_NAME@_FIND_COMPONENT MATCHES "nothreads") + set (@PACKAGE_PREFIX@_NOTHREADS TRUE) + else () + set (@PACKAGE_PREFIX@_NOTHREADS FALSE) + endif () + elseif (TARGET ${@PACKAGE_PREFIX@_TARGET_PREFIX}PACKAGE_NAME@_static OR TARGET ${@PACKAGE_PREFIX@_TARGET_PREFIX}@PACKAGE_NAME@_shared) + set (@PACKAGE_PREFIX@_NOTHREADS FALSE) + else () + set (@PACKAGE_PREFIX@_NOTHREADS TRUE) + endif () +endif () + +# choose imported library target +if (NOT @PACKAGE_PREFIX@_TARGET) + if (@PACKAGE_NAME@_TARGET) + set (@PACKAGE_PREFIX@_TARGET ${@PACKAGE_NAME@_TARGET}) + elseif (@PACKAGE_PREFIX@_SHARED) + if (@PACKAGE_PREFIX@_NOTHREADS) + set (@PACKAGE_PREFIX@_TARGET ${@PACKAGE_PREFIX@_TARGET_PREFIX}@PACKAGE_NAME@_nothreads_shared) + else () + set (@PACKAGE_PREFIX@_TARGET ${@PACKAGE_PREFIX@_TARGET_PREFIX}@PACKAGE_NAME@_shared) + endif () + else () + if (@PACKAGE_PREFIX@_NOTHREADS) + set (@PACKAGE_PREFIX@_TARGET ${@PACKAGE_PREFIX@_TARGET_PREFIX}@PACKAGE_NAME@_nothreads_static) + else () + set (@PACKAGE_PREFIX@_TARGET ${@PACKAGE_PREFIX@_TARGET_PREFIX}@PACKAGE_NAME@_static) + endif () + endif () +endif () +if (NOT TARGET ${@PACKAGE_PREFIX@_TARGET}) + message (FATAL_ERROR "Your @PACKAGE_NAME@ installation does not contain a ${@PACKAGE_PREFIX@_TARGET} library target!" + " Try a different combination of @PACKAGE_PREFIX@_SHARED and @PACKAGE_PREFIX@_NOTHREADS.") +endif () + +# add more convenient "${@PACKAGE_PREFIX@_TARGET_PREFIX}@PACKAGE_NAME@" import target +if (NOT TARGET ${@PACKAGE_PREFIX@_TARGET_PREFIX}@PACKAGE_NAME@) + if (@PACKAGE_PREFIX@_SHARED) + add_library (${@PACKAGE_PREFIX@_TARGET_PREFIX}@PACKAGE_NAME@ SHARED IMPORTED) + else () + add_library (${@PACKAGE_PREFIX@_TARGET_PREFIX}@PACKAGE_NAME@ STATIC IMPORTED) + endif () + # copy INTERFACE_* properties + foreach (_@PACKAGE_PREFIX@_PROPERTY_NAME IN ITEMS + COMPILE_DEFINITIONS + COMPILE_FEATURES + COMPILE_OPTIONS + INCLUDE_DIRECTORIES + LINK_LIBRARIES + POSITION_INDEPENDENT_CODE + ) + get_target_property (_@PACKAGE_PREFIX@_PROPERTY_VALUE ${@PACKAGE_PREFIX@_TARGET} INTERFACE_${_@PACKAGE_PREFIX@_PROPERTY_NAME}) + if (_@PACKAGE_PREFIX@_PROPERTY_VALUE) + set_target_properties(${@PACKAGE_PREFIX@_TARGET_PREFIX}@PACKAGE_NAME@ PROPERTIES + INTERFACE_${_@PACKAGE_PREFIX@_PROPERTY_NAME} "${_@PACKAGE_PREFIX@_PROPERTY_VALUE}" + ) + endif () + endforeach () + # copy IMPORTED_*_ properties + get_target_property (_@PACKAGE_PREFIX@_CONFIGURATIONS ${@PACKAGE_PREFIX@_TARGET} IMPORTED_CONFIGURATIONS) + set_target_properties (${@PACKAGE_PREFIX@_TARGET_PREFIX}@PACKAGE_NAME@ PROPERTIES IMPORTED_CONFIGURATIONS "${_@PACKAGE_PREFIX@_CONFIGURATIONS}") + foreach (_@PACKAGE_PREFIX@_PROPERTY_NAME IN ITEMS + IMPLIB + LOCATION + LINK_DEPENDENT_LIBRARIES + LINK_INTERFACE_LIBRARIES + LINK_INTERFACE_LANGUAGES + LINK_INTERFACE_MULTIPLICITY + NO_SONAME + SONAME + ) + foreach (_@PACKAGE_PREFIX@_CONFIG IN LISTS _@PACKAGE_PREFIX@_CONFIGURATIONS) + get_target_property (_@PACKAGE_PREFIX@_PROPERTY_VALUE ${@PACKAGE_PREFIX@_TARGET} IMPORTED_${_@PACKAGE_PREFIX@_PROPERTY_NAME}_${_@PACKAGE_PREFIX@_CONFIG}) + if (_@PACKAGE_PREFIX@_PROPERTY_VALUE) + set_target_properties(${@PACKAGE_PREFIX@_TARGET_PREFIX}@PACKAGE_NAME@ PROPERTIES + IMPORTED_${_@PACKAGE_PREFIX@_PROPERTY_NAME}_${_@PACKAGE_PREFIX@_CONFIG} "${_@PACKAGE_PREFIX@_PROPERTY_VALUE}" + ) + endif () + endforeach () + endforeach () + unset (_@PACKAGE_PREFIX@_CONFIGURATIONS) + unset (_@PACKAGE_PREFIX@_CONFIG) + unset (_@PACKAGE_PREFIX@_PROPERTY_NAME) + unset (_@PACKAGE_PREFIX@_PROPERTY_VALUE) +endif () + +# alias for default import target to be compatible with older CMake package configurations +set (@PACKAGE_PREFIX@_LIBRARIES "${@PACKAGE_PREFIX@_TARGET}") + +# set @PACKAGE_NAME@_* variables for backwards compatibility +if (NOT "^@PACKAGE_NAME@$" STREQUAL "^@PACKAGE_PREFIX@$") + foreach (_@PACKAGE_PREFIX@_VARIABLE IN ITEMS + VERSION_STRING + VERSION_MAJOR + VERSION_MINOR + VERSION_PATCH + INCLUDE_DIR + LIBRARIES + TARGET + ) + set (@PACKAGE_NAME@_${_@PACKAGE_PREFIX@_VARIABLE} "${@PACKAGE_PREFIX@_${_@PACKAGE_PREFIX@_VARIABLE}}") + endforeach () + unset (_@PACKAGE_PREFIX@_VARIABLE) +endif () + +# unset private variables +unset (@PACKAGE_NAME@_FIND_COMPONENT) +unset (_INSTALL_PREFIX) diff --git a/third_party/gflags/cmake/execute_test.cmake b/third_party/gflags/cmake/execute_test.cmake new file mode 100644 index 0000000..df008cf --- /dev/null +++ b/third_party/gflags/cmake/execute_test.cmake @@ -0,0 +1,53 @@ +# ---------------------------------------------------------------------------- +# sanitize string stored in variable for use in regular expression. +macro (sanitize_for_regex STRVAR) + string (REGEX REPLACE "([.+*?^$()])" "\\\\\\1" ${STRVAR} "${${STRVAR}}") +endmacro () + +# ---------------------------------------------------------------------------- +# script arguments +if (NOT COMMAND) + message (FATAL_ERROR "Test command not specified!") +endif () +if (NOT DEFINED EXPECTED_RC) + set (EXPECTED_RC 0) +endif () +if (EXPECTED_OUTPUT) + sanitize_for_regex(EXPECTED_OUTPUT) +endif () +if (UNEXPECTED_OUTPUT) + sanitize_for_regex(UNEXPECTED_OUTPUT) +endif () + +# ---------------------------------------------------------------------------- +# set a few environment variables (useful for --tryfromenv) +set (ENV{FLAGS_undefok} "foo,bar") +set (ENV{FLAGS_weirdo} "") +set (ENV{FLAGS_version} "true") +set (ENV{FLAGS_help} "false") + +# ---------------------------------------------------------------------------- +# execute test command +execute_process( + COMMAND ${COMMAND} + RESULT_VARIABLE RC + OUTPUT_VARIABLE OUTPUT + ERROR_VARIABLE OUTPUT +) + +if (OUTPUT) + message ("${OUTPUT}") +endif () + +# ---------------------------------------------------------------------------- +# check test result +if (NOT RC EQUAL EXPECTED_RC) + string (REPLACE ";" " " COMMAND "${COMMAND}") + message (FATAL_ERROR "Command:\n\t${COMMAND}\nExit status is ${RC}, expected ${EXPECTED_RC}") +endif () +if (EXPECTED_OUTPUT AND NOT OUTPUT MATCHES "${EXPECTED_OUTPUT}") + message (FATAL_ERROR "Test output does not match expected output: ${EXPECTED_OUTPUT}") +endif () +if (UNEXPECTED_OUTPUT AND OUTPUT MATCHES "${UNEXPECTED_OUTPUT}") + message (FATAL_ERROR "Test output matches unexpected output: ${UNEXPECTED_OUTPUT}") +endif () \ No newline at end of file diff --git a/third_party/gflags/cmake/package.cmake.in b/third_party/gflags/cmake/package.cmake.in new file mode 100644 index 0000000..aaec792 --- /dev/null +++ b/third_party/gflags/cmake/package.cmake.in @@ -0,0 +1,49 @@ +# Per-generator CPack configuration file. See CPACK_PROJECT_CONFIG_FILE documented at +# http://www.cmake.org/cmake/help/v2.8.12/cpack.html#variable:CPACK_PROJECT_CONFIG_FILE +# +# All common CPACK_* variables are set in CMakeLists.txt already. This file only +# overrides some of these to provide package generator specific settings. + +# whether package contains all development files or only runtime files +set (DEVEL @INSTALL_HEADERS@) + +# ------------------------------------------------------------------------------ +# Mac OS X package +if (CPACK_GENERATOR MATCHES "PackageMaker|DragNDrop") + + set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}") + if (DEVEL) + set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-devel") + endif () + set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-${CPACK_PACKAGE_VERSION}") + +# ------------------------------------------------------------------------------ +# Debian package +elseif (CPACK_GENERATOR MATCHES "DEB") + + set (CPACK_PACKAGE_FILE_NAME "lib${CPACK_PACKAGE_NAME}") + if (DEVEL) + set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-dev") + else () + set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}0") + endif () + set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}_${CPACK_PACKAGE_VERSION}-1_${CPACK_PACKAGE_ARCHITECTURE}") + + set (CPACK_DEBIAN_PACKAGE_DEPENDS) + set (CPACK_DEBIAN_PACKAGE_SECTION "devel") + set (CPACK_DEBIAN_PACKAGE_PRIORITY "optional") + set (CPACK_DEBIAN_PACKAGE_HOMEPAGE "${CPACK_RPM_PACKAGE_URL}") + set (CPACK_DEBIAN_PACKAGE_MAINTAINER "${CPACK_PACKAGE_VENDOR}") + set (CPACK_DEBIAN_PACKAGE_ARCHITECTURE "${CPACK_PACKAGE_ARCHITECTURE}") + +# ------------------------------------------------------------------------------ +# RPM package +elseif (CPACK_GENERATOR MATCHES "RPM") + + set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}") + if (DEVEL) + set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-devel") + endif () + set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-${CPACK_PACKAGE_VERSION}-1.${CPACK_PACKAGE_ARCHITECTURE}") + +endif () diff --git a/third_party/gflags/cmake/package.pc.in b/third_party/gflags/cmake/package.pc.in new file mode 100644 index 0000000..80df818 --- /dev/null +++ b/third_party/gflags/cmake/package.pc.in @@ -0,0 +1,14 @@ +prefix=@CMAKE_INSTALL_PREFIX@ +exec_prefix=${prefix} +bindir=${prefix}/@RUNTIME_INSTALL_DIR@ +libdir=${prefix}/@LIBRARY_INSTALL_DIR@ +includedir=${prefix}/@INCLUDE_INSTALL_DIR@ + +Name: @PACKAGE_NAME@ +Version: @PACKAGE_VERSION@ +Description: @PACKAGE_DESCRIPTION@ +URL: @PACKAGE_URL@ +Requires: +Libs: -L${libdir} -lgflags +Libs.private: -lpthread +Cflags: -I${includedir} diff --git a/third_party/gflags/cmake/utils.cmake b/third_party/gflags/cmake/utils.cmake new file mode 100644 index 0000000..d039e5c --- /dev/null +++ b/third_party/gflags/cmake/utils.cmake @@ -0,0 +1,205 @@ +## Utility CMake functions. + +# ---------------------------------------------------------------------------- +## Convert boolean value to 0 or 1 +macro (bool_to_int VAR) + if (${VAR}) + set (${VAR} 1) + else () + set (${VAR} 0) + endif () +endmacro () + +# ---------------------------------------------------------------------------- +## Extract version numbers from version string +function (version_numbers version major minor patch) + if (version MATCHES "([0-9]+)(\\.[0-9]+)?(\\.[0-9]+)?(rc[1-9][0-9]*|[a-z]+)?") + if (CMAKE_MATCH_1) + set (_major ${CMAKE_MATCH_1}) + else () + set (_major 0) + endif () + if (CMAKE_MATCH_2) + set (_minor ${CMAKE_MATCH_2}) + string (REGEX REPLACE "^\\." "" _minor "${_minor}") + else () + set (_minor 0) + endif () + if (CMAKE_MATCH_3) + set (_patch ${CMAKE_MATCH_3}) + string (REGEX REPLACE "^\\." "" _patch "${_patch}") + else () + set (_patch 0) + endif () + else () + set (_major 0) + set (_minor 0) + set (_patch 0) + endif () + set ("${major}" "${_major}" PARENT_SCOPE) + set ("${minor}" "${_minor}" PARENT_SCOPE) + set ("${patch}" "${_patch}" PARENT_SCOPE) +endfunction () + +# ---------------------------------------------------------------------------- +## Determine if cache entry exists +macro (gflags_is_cached retvar varname) + if (DEFINED ${varname}) + get_property (${retvar} CACHE ${varname} PROPERTY TYPE SET) + else () + set (${retvar} FALSE) + endif () +endmacro () + +# ---------------------------------------------------------------------------- +## Add gflags configuration variable +# +# The default value of the (cached) configuration value can be overridden either +# on the CMake command-line or the super-project by setting the GFLAGS_ +# variable. When gflags is a subproject of another project (GFLAGS_IS_SUBPROJECT), +# the variable is not added to the CMake cache. Otherwise it is cached. +macro (gflags_define type varname docstring default) + # note that ARGC must be expanded here, as it is not a "real" variable + # (see the CMake documentation for the macro command) + if ("${ARGC}" GREATER 5) + message (FATAL_ERROR "gflags_variable: Too many macro arguments") + endif () + if (NOT DEFINED GFLAGS_${varname}) + if (GFLAGS_IS_SUBPROJECT AND "${ARGC}" EQUAL 5) + set (GFLAGS_${varname} "${ARGV4}") + else () + set (GFLAGS_${varname} "${default}") + endif () + endif () + if (GFLAGS_IS_SUBPROJECT) + if (NOT DEFINED ${varname}) + set (${varname} "${GFLAGS_${varname}}") + endif () + else () + set (${varname} "${GFLAGS_${varname}}" CACHE ${type} "${docstring}") + endif () +endmacro () + +# ---------------------------------------------------------------------------- +## Set property of cached gflags configuration variable +macro (gflags_property varname property value) + gflags_is_cached (_cached ${varname}) + if (_cached) + # note that property must be expanded here, as it is not a "real" variable + # (see the CMake documentation for the macro command) + if ("${property}" STREQUAL "ADVANCED") + if (${value}) + mark_as_advanced (FORCE ${varname}) + else () + mark_as_advanced (CLEAR ${varname}) + endif () + else () + set_property (CACHE ${varname} PROPERTY "${property}" "${value}") + endif () + endif () + unset (_cached) +endmacro () + +# ---------------------------------------------------------------------------- +## Modify value of gflags configuration variable +macro (gflags_set varname value) + gflags_is_cached (_cached ${varname}) + if (_cached) + set_property (CACHE ${varname} PROPERTY VALUE "${value}") + else () + set (${varname} "${value}") + endif () + unset (_cached) +endmacro () + +# ---------------------------------------------------------------------------- +## Configure public header files +function (configure_headers out) + set (tmp) + foreach (src IN LISTS ARGN) + if (IS_ABSOLUTE "${src}") + list (APPEND tmp "${src}") + elseif (EXISTS "${PROJECT_SOURCE_DIR}/src/${src}.in") + configure_file ("${PROJECT_SOURCE_DIR}/src/${src}.in" "${PROJECT_BINARY_DIR}/include/${GFLAGS_INCLUDE_DIR}/${src}" @ONLY) + list (APPEND tmp "${PROJECT_BINARY_DIR}/include/${GFLAGS_INCLUDE_DIR}/${src}") + else () + configure_file ("${PROJECT_SOURCE_DIR}/src/${src}" "${PROJECT_BINARY_DIR}/include/${GFLAGS_INCLUDE_DIR}/${src}" COPYONLY) + list (APPEND tmp "${PROJECT_BINARY_DIR}/include/${GFLAGS_INCLUDE_DIR}/${src}") + endif () + endforeach () + set (${out} "${tmp}" PARENT_SCOPE) +endfunction () + +# ---------------------------------------------------------------------------- +## Configure source files with .in suffix +function (configure_sources out) + set (tmp) + foreach (src IN LISTS ARGN) + if (src MATCHES ".h$" AND EXISTS "${PROJECT_SOURCE_DIR}/src/${src}.in") + configure_file ("${PROJECT_SOURCE_DIR}/src/${src}.in" "${PROJECT_BINARY_DIR}/include/${GFLAGS_INCLUDE_DIR}/${src}" @ONLY) + list (APPEND tmp "${PROJECT_BINARY_DIR}/include/${GFLAGS_INCLUDE_DIR}/${src}") + else () + list (APPEND tmp "${PROJECT_SOURCE_DIR}/src/${src}") + endif () + endforeach () + set (${out} "${tmp}" PARENT_SCOPE) +endfunction () + +# ---------------------------------------------------------------------------- +## Add usage test +# +# Using PASS_REGULAR_EXPRESSION and FAIL_REGULAR_EXPRESSION would +# do as well, but CMake/CTest does not allow us to specify an +# expected exit status. Moreover, the execute_test.cmake script +# sets environment variables needed by the --fromenv/--tryfromenv tests. +macro (add_gflags_test name expected_rc expected_output unexpected_output cmd) + set (args "--test_tmpdir=${PROJECT_BINARY_DIR}/Testing/Temporary" + "--srcdir=${PROJECT_SOURCE_DIR}/test") + add_test ( + NAME ${name} + COMMAND "${CMAKE_COMMAND}" "-DCOMMAND:STRING=$;${args};${ARGN}" + "-DEXPECTED_RC:STRING=${expected_rc}" + "-DEXPECTED_OUTPUT:STRING=${expected_output}" + "-DUNEXPECTED_OUTPUT:STRING=${unexpected_output}" + -P "${PROJECT_SOURCE_DIR}/cmake/execute_test.cmake" + WORKING_DIRECTORY "${GFLAGS_FLAGFILES_DIR}" + ) +endmacro () + +# ------------------------------------------------------------------------------ +## Register installed package with CMake +# +# This function adds an entry to the CMake registry for packages with the +# path of the directory where the package configuration file of the installed +# package is located in order to help CMake find the package in a custom +# installation prefix. This differs from CMake's export(PACKAGE) command +# which registers the build directory instead. +function (register_gflags_package CONFIG_DIR) + if (NOT IS_ABSOLUTE "${CONFIG_DIR}") + set (CONFIG_DIR "${CMAKE_INSTALL_PREFIX}/${CONFIG_DIR}") + endif () + string (MD5 REGISTRY_ENTRY "${CONFIG_DIR}") + if (WIN32) + install (CODE + "execute_process ( + COMMAND reg add \"HKCU\\\\Software\\\\Kitware\\\\CMake\\\\Packages\\\\${PACKAGE_NAME}\" /v \"${REGISTRY_ENTRY}\" /d \"${CONFIG_DIR}\" /t REG_SZ /f + RESULT_VARIABLE RT + ERROR_VARIABLE ERR + OUTPUT_QUIET + ) + if (RT EQUAL 0) + message (STATUS \"Register: Added HKEY_CURRENT_USER\\\\Software\\\\Kitware\\\\CMake\\\\Packages\\\\${PACKAGE_NAME}\\\\${REGISTRY_ENTRY}\") + else () + string (STRIP \"\${ERR}\" ERR) + message (STATUS \"Register: Failed to add registry entry: \${ERR}\") + endif ()" + ) + elseif (IS_DIRECTORY "$ENV{HOME}") + file (WRITE "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-registry-entry" "${CONFIG_DIR}") + install ( + FILES "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-registry-entry" + DESTINATION "$ENV{HOME}/.cmake/packages/${PACKAGE_NAME}" + RENAME "${REGISTRY_ENTRY}" + ) + endif () +endfunction () diff --git a/third_party/gflags/cmake/version.cmake.in b/third_party/gflags/cmake/version.cmake.in new file mode 100644 index 0000000..1e1af05 --- /dev/null +++ b/third_party/gflags/cmake/version.cmake.in @@ -0,0 +1,21 @@ +## gflags CMake configuration version file + +# ----------------------------------------------------------------------------- +# library version +set (PACKAGE_VERSION "@PACKAGE_VERSION@") + +# ----------------------------------------------------------------------------- +# check compatibility + +# Perform compatibility check here using the input CMake variables. +# See example in http://www.cmake.org/Wiki/CMake_2.6_Notes. + +set (PACKAGE_VERSION_COMPATIBLE TRUE) +set (PACKAGE_VERSION_UNSUITABLE FALSE) + +if ("${PACKAGE_FIND_VERSION_MAJOR}" EQUAL "@PACKAGE_VERSION_MAJOR@" AND + "${PACKAGE_FIND_VERSION_MINOR}" EQUAL "@PACKAGE_VERSION_MINOR@") + set (PACKAGE_VERSION_EXACT TRUE) +else () + set (PACKAGE_VERSION_EXACT FALSE) +endif () diff --git a/third_party/gflags/src/config.h b/third_party/gflags/src/config.h new file mode 100644 index 0000000..c33d207 --- /dev/null +++ b/third_party/gflags/src/config.h @@ -0,0 +1,59 @@ +// Note: This header file is only used internally. It is not part of public interface! + +#ifndef GFLAGS_CONFIG_H_ +#define GFLAGS_CONFIG_H_ + + +// --------------------------------------------------------------------------- +// System checks + +// CMake build configuration is written to defines.h file, unused by Bazel build +#if !defined(GFLAGS_BAZEL_BUILD) +# include "defines.h" +#endif + +// gcc requires this to get PRId64, etc. +#if defined(HAVE_INTTYPES_H) && !defined(__STDC_FORMAT_MACROS) +# define __STDC_FORMAT_MACROS 1 +#endif + +// --------------------------------------------------------------------------- +// Path separator +#ifndef PATH_SEPARATOR +# ifdef OS_WINDOWS +# define PATH_SEPARATOR '\\' +# else +# define PATH_SEPARATOR '/' +# endif +#endif + +// --------------------------------------------------------------------------- +// Windows + +// Always export symbols when compiling a shared library as this file is only +// included by internal modules when building the gflags library itself. +// The gflags_declare.h header file will set it to import these symbols otherwise. +#ifndef GFLAGS_DLL_DECL +# if GFLAGS_IS_A_DLL && defined(_MSC_VER) +# define GFLAGS_DLL_DECL __declspec(dllexport) +# elif defined(__GNUC__) && __GNUC__ >= 4 +# define GFLAGS_DLL_DECL __attribute__((visibility("default"))) +# else +# define GFLAGS_DLL_DECL +# endif +#endif +// Flags defined by the gflags library itself must be exported +#ifndef GFLAGS_DLL_DEFINE_FLAG +# define GFLAGS_DLL_DEFINE_FLAG GFLAGS_DLL_DECL +#endif + +#ifdef OS_WINDOWS +// The unittests import the symbols of the shared gflags library +# if GFLAGS_IS_A_DLL && defined(_MSC_VER) +# define GFLAGS_DLL_DECL_FOR_UNITTESTS __declspec(dllimport) +# endif +# include "windows_port.h" +#endif + + +#endif // GFLAGS_CONFIG_H_ diff --git a/third_party/gflags/src/defines.h.in b/third_party/gflags/src/defines.h.in new file mode 100644 index 0000000..dfb214e --- /dev/null +++ b/third_party/gflags/src/defines.h.in @@ -0,0 +1,48 @@ +/* Generated from defines.h.in during build configuration using CMake. */ + +// Note: This header file is only used internally. It is not part of public interface! +// Any cmakedefine is defined using the -D flag instead when Bazel is used. +// For Bazel, this file is thus not used to avoid a private file in $(GENDIR). + +#ifndef GFLAGS_DEFINES_H_ +#define GFLAGS_DEFINES_H_ + + +// Define if you build this library for a MS Windows OS. +#cmakedefine OS_WINDOWS + +// Define if you have the header file. +#cmakedefine HAVE_STDINT_H + +// Define if you have the header file. +#cmakedefine HAVE_SYS_TYPES_H + +// Define if you have the header file. +#cmakedefine HAVE_INTTYPES_H + +// Define if you have the header file. +#cmakedefine HAVE_SYS_STAT_H + +// Define if you have the header file. +#cmakedefine HAVE_UNISTD_H + +// Define if you have the header file. +#cmakedefine HAVE_FNMATCH_H + +// Define if you have the header file (Windows 2000/XP). +#cmakedefine HAVE_SHLWAPI_H + +// Define if you have the strtoll function. +#cmakedefine HAVE_STRTOLL + +// Define if you have the strtoq function. +#cmakedefine HAVE_STRTOQ + +// Define if you have the header file. +#cmakedefine HAVE_PTHREAD + +// Define if your pthread library defines the type pthread_rwlock_t +#cmakedefine HAVE_RWLOCK + + +#endif // GFLAGS_DEFINES_H_ diff --git a/third_party/gflags/src/gflags.cc b/third_party/gflags/src/gflags.cc new file mode 100644 index 0000000..fd6663a --- /dev/null +++ b/third_party/gflags/src/gflags.cc @@ -0,0 +1,2029 @@ +// Copyright (c) 1999, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// --- +// Revamped and reorganized by Craig Silverstein +// +// This file contains the implementation of all our command line flags +// stuff. Here's how everything fits together +// +// * FlagRegistry owns CommandLineFlags owns FlagValue. +// * FlagSaver holds a FlagRegistry (saves it at construct time, +// restores it at destroy time). +// * CommandLineFlagParser lives outside that hierarchy, but works on +// CommandLineFlags (modifying the FlagValues). +// * Free functions like SetCommandLineOption() work via one of the +// above (such as CommandLineFlagParser). +// +// In more detail: +// +// -- The main classes that hold flag data: +// +// FlagValue holds the current value of a flag. It's +// pseudo-templatized: every operation on a FlagValue is typed. It +// also deals with storage-lifetime issues (so flag values don't go +// away in a destructor), which is why we need a whole class to hold a +// variable's value. +// +// CommandLineFlag is all the information about a single command-line +// flag. It has a FlagValue for the flag's current value, but also +// the flag's name, type, etc. +// +// FlagRegistry is a collection of CommandLineFlags. There's the +// global registry, which is where flags defined via DEFINE_foo() +// live. But it's possible to define your own flag, manually, in a +// different registry you create. (In practice, multiple registries +// are used only by FlagSaver). +// +// A given FlagValue is owned by exactly one CommandLineFlag. A given +// CommandLineFlag is owned by exactly one FlagRegistry. FlagRegistry +// has a lock; any operation that writes to a FlagValue or +// CommandLineFlag owned by that registry must acquire the +// FlagRegistry lock before doing so. +// +// --- Some other classes and free functions: +// +// CommandLineFlagInfo is a client-exposed version of CommandLineFlag. +// Once it's instantiated, it has no dependencies or relationships +// with any other part of this file. +// +// FlagRegisterer is the helper class used by the DEFINE_* macros to +// allow work to be done at global initialization time. +// +// CommandLineFlagParser is the class that reads from the commandline +// and instantiates flag values based on that. It needs to poke into +// the innards of the FlagValue->CommandLineFlag->FlagRegistry class +// hierarchy to do that. It's careful to acquire the FlagRegistry +// lock before doing any writing or other non-const actions. +// +// GetCommandLineOption is just a hook into registry routines to +// retrieve a flag based on its name. SetCommandLineOption, on the +// other hand, hooks into CommandLineFlagParser. Other API functions +// are, similarly, mostly hooks into the functionality described above. + +#include "gflags/gflags.h" +#include "config.h" + +#include +#include +#include +#if defined(HAVE_FNMATCH_H) +#include +#elif defined(HAVE_SHLWAPI_H) +#define NO_SHLWAPI_ISOS +#include +#endif +#include // For va_list and related operations +#include +#include + +#include +#include +#include +#include // for pair<> +#include + +#include "mutex.h" +#include "util.h" + +using namespace MUTEX_NAMESPACE; + +// Special flags, type 1: the 'recursive' flags. They set another flag's val. +DEFINE_string(flagfile, "", "load flags from file"); +DEFINE_string(fromenv, "", + "set flags from the environment" + " [use 'export FLAGS_flag1=value']"); +DEFINE_string(tryfromenv, "", "set flags from the environment if present"); + +// Special flags, type 2: the 'parsing' flags. They modify how we parse. +DEFINE_string(undefok, "", + "comma-separated list of flag names that it is okay to specify " + "on the command line even if the program does not define a flag " + "with that name. IMPORTANT: flags in this list that have " + "arguments MUST use the flag=value format"); + +namespace GFLAGS_NAMESPACE { + +using std::map; +using std::pair; +using std::sort; +using std::string; +using std::vector; + +// This is used by the unittest to test error-exit code +void GFLAGS_DLL_DECL (*gflags_exitfunc)(int) = &exit; // from stdlib.h + +// The help message indicating that the commandline flag has been +// 'stripped'. It will not show up when doing "-help" and its +// variants. The flag is stripped if STRIP_FLAG_HELP is set to 1 +// before including base/gflags.h + +// This is used by this file, and also in gflags_reporting.cc +const char kStrippedFlagHelp[] = "\001\002\003\004 (unknown) \004\003\002\001"; + +namespace { + +// There are also 'reporting' flags, in gflags_reporting.cc. + +static const char kError[] = "ERROR: "; + +// Indicates that undefined options are to be ignored. +// Enables deferred processing of flags in dynamically loaded libraries. +static bool allow_command_line_reparsing = false; + +static bool logging_is_probably_set_up = false; + +// This is a 'prototype' validate-function. 'Real' validate +// functions, take a flag-value as an argument: ValidateFn(bool) or +// ValidateFn(uint64). However, for easier storage, we strip off this +// argument and then restore it when actually calling the function on +// a flag value. +typedef bool (*ValidateFnProto)(); + +// Whether we should die when reporting an error. +enum DieWhenReporting { DIE, DO_NOT_DIE }; + +// Report Error and exit if requested. +static void ReportError(DieWhenReporting should_die, const char *format, ...) { + va_list ap; + va_start(ap, format); + vfprintf(stderr, format, ap); + va_end(ap); + fflush(stderr); // should be unnecessary, but cygwin's rxvt buffers stderr + if (should_die == DIE) + gflags_exitfunc(1); +} + +// -------------------------------------------------------------------- +// FlagValue +// This represent the value a single flag might have. The major +// functionality is to convert from a string to an object of a +// given type, and back. Thread-compatible. +// -------------------------------------------------------------------- + +class CommandLineFlag; +class FlagValue { +public: + enum ValueType { + FV_BOOL = 0, + FV_INT32 = 1, + FV_UINT32 = 2, + FV_INT64 = 3, + FV_UINT64 = 4, + FV_DOUBLE = 5, + FV_STRING = 6, + FV_MAX_INDEX = 6, + }; + + template + FlagValue(FlagType *valbuf, bool transfer_ownership_of_value); + ~FlagValue(); + + bool ParseFrom(const char *spec); + string ToString() const; + + ValueType Type() const { return static_cast(type_); } + +private: + friend class CommandLineFlag; // for many things, including Validate() + friend class GFLAGS_NAMESPACE::FlagSaverImpl; // calls New() + friend class FlagRegistry; // checks value_buffer_ for flags_by_ptr_ map + template friend T GetFromEnv(const char *, T); + friend bool TryParseLocked(const CommandLineFlag *, FlagValue *, const char *, + string *); // for New(), CopyFrom() + + template struct FlagValueTraits; + + const char *TypeName() const; + bool Equal(const FlagValue &x) const; + FlagValue *New() const; // creates a new one with default value + void CopyFrom(const FlagValue &x); + + // Calls the given validate-fn on value_buffer_, and returns + // whatever it returns. But first casts validate_fn_proto to a + // function that takes our value as an argument (eg void + // (*validate_fn)(bool) for a bool flag). + bool Validate(const char *flagname, ValidateFnProto validate_fn_proto) const; + + void *const value_buffer_; // points to the buffer holding our data + const int8 type_; // how to interpret value_ + const bool owns_value_; // whether to free value on destruct + + FlagValue(const FlagValue &); // no copying! + void operator=(const FlagValue &); +}; + +// Map the given C++ type to a value of the ValueType enum at compile time. +#define DEFINE_FLAG_TRAITS(type, value) \ + template <> struct FlagValue::FlagValueTraits { \ + static const ValueType kValueType = value; \ + } + +// Define full template specializations of the FlagValueTraits template +// for all supported flag types. +DEFINE_FLAG_TRAITS(bool, FV_BOOL); +DEFINE_FLAG_TRAITS(int32, FV_INT32); +DEFINE_FLAG_TRAITS(uint32, FV_UINT32); +DEFINE_FLAG_TRAITS(int64, FV_INT64); +DEFINE_FLAG_TRAITS(uint64, FV_UINT64); +DEFINE_FLAG_TRAITS(double, FV_DOUBLE); +DEFINE_FLAG_TRAITS(std::string, FV_STRING); + +#undef DEFINE_FLAG_TRAITS + +// This could be a templated method of FlagValue, but doing so adds to the +// size of the .o. Since there's no type-safety here anyway, macro is ok. +#define VALUE_AS(type) *reinterpret_cast(value_buffer_) +#define OTHER_VALUE_AS(fv, type) *reinterpret_cast(fv.value_buffer_) +#define SET_VALUE_AS(type, value) VALUE_AS(type) = (value) + +template +FlagValue::FlagValue(FlagType *valbuf, bool transfer_ownership_of_value) + : value_buffer_(valbuf), type_(FlagValueTraits::kValueType), + owns_value_(transfer_ownership_of_value) {} + +FlagValue::~FlagValue() { + if (!owns_value_) { + return; + } + switch (type_) { + case FV_BOOL: + delete reinterpret_cast(value_buffer_); + break; + case FV_INT32: + delete reinterpret_cast(value_buffer_); + break; + case FV_UINT32: + delete reinterpret_cast(value_buffer_); + break; + case FV_INT64: + delete reinterpret_cast(value_buffer_); + break; + case FV_UINT64: + delete reinterpret_cast(value_buffer_); + break; + case FV_DOUBLE: + delete reinterpret_cast(value_buffer_); + break; + case FV_STRING: + delete reinterpret_cast(value_buffer_); + break; + } +} + +bool FlagValue::ParseFrom(const char *value) { + if (type_ == FV_BOOL) { + const char *kTrue[] = {"1", "t", "true", "y", "yes"}; + const char *kFalse[] = {"0", "f", "false", "n", "no"}; + COMPILE_ASSERT(sizeof(kTrue) == sizeof(kFalse), true_false_equal); + for (size_t i = 0; i < sizeof(kTrue) / sizeof(*kTrue); ++i) { + if (strcasecmp(value, kTrue[i]) == 0) { + SET_VALUE_AS(bool, true); + return true; + } else if (strcasecmp(value, kFalse[i]) == 0) { + SET_VALUE_AS(bool, false); + return true; + } + } + return false; // didn't match a legal input + + } else if (type_ == FV_STRING) { + SET_VALUE_AS(string, value); + return true; + } + + // OK, it's likely to be numeric, and we'll be using a strtoXXX method. + if (value[0] == '\0') // empty-string is only allowed for string type. + return false; + char *end; + // Leading 0x puts us in base 16. But leading 0 does not put us in base 8! + // It caused too many bugs when we had that behavior. + int base = 10; // by default + if (value[0] == '0' && (value[1] == 'x' || value[1] == 'X')) + base = 16; + errno = 0; + + switch (type_) { + case FV_INT32: { + const int64 r = strto64(value, &end, base); + if (errno || end != value + strlen(value)) + return false; // bad parse + if (static_cast(r) != r) // worked, but number out of range + return false; + SET_VALUE_AS(int32, static_cast(r)); + return true; + } + case FV_UINT32: { + while (*value == ' ') + value++; + if (*value == '-') + return false; // negative number + const uint64 r = strtou64(value, &end, base); + if (errno || end != value + strlen(value)) + return false; // bad parse + if (static_cast(r) != r) // worked, but number out of range + return false; + SET_VALUE_AS(uint32, static_cast(r)); + return true; + } + case FV_INT64: { + const int64 r = strto64(value, &end, base); + if (errno || end != value + strlen(value)) + return false; // bad parse + SET_VALUE_AS(int64, r); + return true; + } + case FV_UINT64: { + while (*value == ' ') + value++; + if (*value == '-') + return false; // negative number + const uint64 r = strtou64(value, &end, base); + if (errno || end != value + strlen(value)) + return false; // bad parse + SET_VALUE_AS(uint64, r); + return true; + } + case FV_DOUBLE: { + const double r = strtod(value, &end); + if (errno || end != value + strlen(value)) + return false; // bad parse + SET_VALUE_AS(double, r); + return true; + } + default: { + assert(false); // unknown type + return false; + } + } +} + +string FlagValue::ToString() const { + char intbuf[64]; // enough to hold even the biggest number + switch (type_) { + case FV_BOOL: + return VALUE_AS(bool) ? "true" : "false"; + case FV_INT32: + snprintf(intbuf, sizeof(intbuf), "%" PRId32, VALUE_AS(int32)); + return intbuf; + case FV_UINT32: + snprintf(intbuf, sizeof(intbuf), "%" PRIu32, VALUE_AS(uint32)); + return intbuf; + case FV_INT64: + snprintf(intbuf, sizeof(intbuf), "%" PRId64, VALUE_AS(int64)); + return intbuf; + case FV_UINT64: + snprintf(intbuf, sizeof(intbuf), "%" PRIu64, VALUE_AS(uint64)); + return intbuf; + case FV_DOUBLE: + snprintf(intbuf, sizeof(intbuf), "%.17g", VALUE_AS(double)); + return intbuf; + case FV_STRING: + return VALUE_AS(string); + default: + assert(false); + return ""; // unknown type + } +} + +bool FlagValue::Validate(const char *flagname, + ValidateFnProto validate_fn_proto) const { + switch (type_) { + case FV_BOOL: + return reinterpret_cast(validate_fn_proto)( + flagname, VALUE_AS(bool)); + case FV_INT32: + return reinterpret_cast(validate_fn_proto)( + flagname, VALUE_AS(int32)); + case FV_UINT32: + return reinterpret_cast(validate_fn_proto)( + flagname, VALUE_AS(uint32)); + case FV_INT64: + return reinterpret_cast(validate_fn_proto)( + flagname, VALUE_AS(int64)); + case FV_UINT64: + return reinterpret_cast(validate_fn_proto)( + flagname, VALUE_AS(uint64)); + case FV_DOUBLE: + return reinterpret_cast(validate_fn_proto)( + flagname, VALUE_AS(double)); + case FV_STRING: + return reinterpret_cast( + validate_fn_proto)(flagname, VALUE_AS(string)); + default: + assert(false); // unknown type + return false; + } +} + +const char *FlagValue::TypeName() const { + static const char types[] = "bool\0xx" + "int32\0x" + "uint32\0" + "int64\0x" + "uint64\0" + "double\0" + "string"; + if (type_ > FV_MAX_INDEX) { + assert(false); + return ""; + } + // Directly indexing the strings in the 'types' string, each of them is 7 + // bytes long. + return &types[type_ * 7]; +} + +bool FlagValue::Equal(const FlagValue &x) const { + if (type_ != x.type_) + return false; + switch (type_) { + case FV_BOOL: + return VALUE_AS(bool) == OTHER_VALUE_AS(x, bool); + case FV_INT32: + return VALUE_AS(int32) == OTHER_VALUE_AS(x, int32); + case FV_UINT32: + return VALUE_AS(uint32) == OTHER_VALUE_AS(x, uint32); + case FV_INT64: + return VALUE_AS(int64) == OTHER_VALUE_AS(x, int64); + case FV_UINT64: + return VALUE_AS(uint64) == OTHER_VALUE_AS(x, uint64); + case FV_DOUBLE: + return VALUE_AS(double) == OTHER_VALUE_AS(x, double); + case FV_STRING: + return VALUE_AS(string) == OTHER_VALUE_AS(x, string); + default: + assert(false); + return false; // unknown type + } +} + +FlagValue *FlagValue::New() const { + switch (type_) { + case FV_BOOL: + return new FlagValue(new bool(false), true); + case FV_INT32: + return new FlagValue(new int32(0), true); + case FV_UINT32: + return new FlagValue(new uint32(0), true); + case FV_INT64: + return new FlagValue(new int64(0), true); + case FV_UINT64: + return new FlagValue(new uint64(0), true); + case FV_DOUBLE: + return new FlagValue(new double(0.0), true); + case FV_STRING: + return new FlagValue(new string, true); + default: + assert(false); + return NULL; // unknown type + } +} + +void FlagValue::CopyFrom(const FlagValue &x) { + assert(type_ == x.type_); + switch (type_) { + case FV_BOOL: + SET_VALUE_AS(bool, OTHER_VALUE_AS(x, bool)); + break; + case FV_INT32: + SET_VALUE_AS(int32, OTHER_VALUE_AS(x, int32)); + break; + case FV_UINT32: + SET_VALUE_AS(uint32, OTHER_VALUE_AS(x, uint32)); + break; + case FV_INT64: + SET_VALUE_AS(int64, OTHER_VALUE_AS(x, int64)); + break; + case FV_UINT64: + SET_VALUE_AS(uint64, OTHER_VALUE_AS(x, uint64)); + break; + case FV_DOUBLE: + SET_VALUE_AS(double, OTHER_VALUE_AS(x, double)); + break; + case FV_STRING: + SET_VALUE_AS(string, OTHER_VALUE_AS(x, string)); + break; + default: + assert(false); // unknown type + } +} + +// -------------------------------------------------------------------- +// CommandLineFlag +// This represents a single flag, including its name, description, +// default value, and current value. Mostly this serves as a +// struct, though it also knows how to register itself. +// All CommandLineFlags are owned by a (exactly one) +// FlagRegistry. If you wish to modify fields in this class, you +// should acquire the FlagRegistry lock for the registry that owns +// this flag. +// -------------------------------------------------------------------- + +class CommandLineFlag { +public: + // Note: we take over memory-ownership of current_val and default_val. + CommandLineFlag(const char *name, const char *help, const char *filename, + FlagValue *current_val, FlagValue *default_val); + ~CommandLineFlag(); + + const char *name() const { return name_; } + const char *help() const { return help_; } + const char *filename() const { return file_; } + const char *CleanFileName() const; // nixes irrelevant prefix such as homedir + string current_value() const { return current_->ToString(); } + string default_value() const { return defvalue_->ToString(); } + const char *type_name() const { return defvalue_->TypeName(); } + ValidateFnProto validate_function() const { return validate_fn_proto_; } + const void *flag_ptr() const { return current_->value_buffer_; } + + FlagValue::ValueType Type() const { return defvalue_->Type(); } + + void FillCommandLineFlagInfo(struct CommandLineFlagInfo *result); + + // If validate_fn_proto_ is non-NULL, calls it on value, returns result. + bool Validate(const FlagValue &value) const; + bool ValidateCurrent() const { return Validate(*current_); } + bool Modified() const { return modified_; } + +private: + // for SetFlagLocked() and setting flags_by_ptr_ + friend class FlagRegistry; + friend class GFLAGS_NAMESPACE::FlagSaverImpl; // for cloning the values + // set validate_fn + friend bool AddFlagValidator(const void *, ValidateFnProto); + + // This copies all the non-const members: modified, processed, defvalue, etc. + void CopyFrom(const CommandLineFlag &src); + + void UpdateModifiedBit(); + + const char *const name_; // Flag name + const char *const help_; // Help message + const char *const file_; // Which file did this come from? + bool modified_; // Set after default assignment? + FlagValue *defvalue_; // Default value for flag + FlagValue *current_; // Current value for flag + // This is a casted, 'generic' version of validate_fn, which actually + // takes a flag-value as an arg (void (*validate_fn)(bool), say). + // When we pass this to current_->Validate(), it will cast it back to + // the proper type. This may be NULL to mean we have no validate_fn. + ValidateFnProto validate_fn_proto_; + + CommandLineFlag(const CommandLineFlag &); // no copying! + void operator=(const CommandLineFlag &); +}; + +CommandLineFlag::CommandLineFlag(const char *name, const char *help, + const char *filename, FlagValue *current_val, + FlagValue *default_val) + : name_(name), help_(help), file_(filename), modified_(false), + defvalue_(default_val), current_(current_val), validate_fn_proto_(NULL) {} + +CommandLineFlag::~CommandLineFlag() { + delete current_; + delete defvalue_; +} + +const char *CommandLineFlag::CleanFileName() const { + // This function has been used to strip off a common prefix from + // flag source file names. Because flags can be defined in different + // shared libraries, there may not be a single common prefix. + // Further, this functionality hasn't been active for many years. + // Need a better way to produce more user friendly help output or + // "anonymize" file paths in help output, respectively. + // Follow issue at: https://github.com/gflags/gflags/issues/86 + return filename(); +} + +void CommandLineFlag::FillCommandLineFlagInfo(CommandLineFlagInfo *result) { + result->name = name(); + result->type = type_name(); + result->description = help(); + result->current_value = current_value(); + result->default_value = default_value(); + result->filename = CleanFileName(); + UpdateModifiedBit(); + result->is_default = !modified_; + result->has_validator_fn = validate_function() != NULL; + result->flag_ptr = flag_ptr(); +} + +void CommandLineFlag::UpdateModifiedBit() { + // Update the "modified" bit in case somebody bypassed the + // Flags API and wrote directly through the FLAGS_name variable. + if (!modified_ && !current_->Equal(*defvalue_)) { + modified_ = true; + } +} + +void CommandLineFlag::CopyFrom(const CommandLineFlag &src) { + // Note we only copy the non-const members; others are fixed at construct time + if (modified_ != src.modified_) + modified_ = src.modified_; + if (!current_->Equal(*src.current_)) + current_->CopyFrom(*src.current_); + if (!defvalue_->Equal(*src.defvalue_)) + defvalue_->CopyFrom(*src.defvalue_); + if (validate_fn_proto_ != src.validate_fn_proto_) + validate_fn_proto_ = src.validate_fn_proto_; +} + +bool CommandLineFlag::Validate(const FlagValue &value) const { + + if (validate_function() == NULL) + return true; + else + return value.Validate(name(), validate_function()); +} + +// -------------------------------------------------------------------- +// FlagRegistry +// A FlagRegistry singleton object holds all flag objects indexed +// by their names so that if you know a flag's name (as a C +// string), you can access or set it. If the function is named +// FooLocked(), you must own the registry lock before calling +// the function; otherwise, you should *not* hold the lock, and +// the function will acquire it itself if needed. +// -------------------------------------------------------------------- + +struct StringCmp { // Used by the FlagRegistry map class to compare char*'s + bool operator()(const char *s1, const char *s2) const { + return (strcmp(s1, s2) < 0); + } +}; + +class FlagRegistry { +public: + FlagRegistry() {} + ~FlagRegistry() { + // Not using STLDeleteElements as that resides in util and this + // class is base. + for (FlagMap::iterator p = flags_.begin(), e = flags_.end(); p != e; ++p) { + CommandLineFlag *flag = p->second; + delete flag; + } + } + + static void DeleteGlobalRegistry() { + delete global_registry_; + global_registry_ = NULL; + } + + // Store a flag in this registry. Takes ownership of the given pointer. + void RegisterFlag(CommandLineFlag *flag); + + void Lock() { lock_.Lock(); } + void Unlock() { lock_.Unlock(); } + + // Returns the flag object for the specified name, or NULL if not found. + CommandLineFlag *FindFlagLocked(const char *name); + + // Returns the flag object whose current-value is stored at flag_ptr. + // That is, for whom current_->value_buffer_ == flag_ptr + CommandLineFlag *FindFlagViaPtrLocked(const void *flag_ptr); + + // A fancier form of FindFlag that works correctly if name is of the + // form flag=value. In that case, we set key to point to flag, and + // modify v to point to the value (if present), and return the flag + // with the given name. If the flag does not exist, returns NULL + // and sets error_message. + CommandLineFlag *SplitArgumentLocked(const char *argument, string *key, + const char **v, string *error_message); + + // Set the value of a flag. If the flag was successfully set to + // value, set msg to indicate the new flag-value, and return true. + // Otherwise, set msg to indicate the error, leave flag unchanged, + // and return false. msg can be NULL. + bool SetFlagLocked(CommandLineFlag *flag, const char *value, + FlagSettingMode set_mode, string *msg); + + static FlagRegistry *GlobalRegistry(); // returns a singleton registry + +private: + friend class GFLAGS_NAMESPACE::FlagSaverImpl; // reads all the flags in order + // to copy them + friend class CommandLineFlagParser; // for ValidateUnmodifiedFlags + friend void GFLAGS_NAMESPACE::GetAllFlags(vector *); + + // The map from name to flag, for FindFlagLocked(). + typedef map FlagMap; + typedef FlagMap::iterator FlagIterator; + typedef FlagMap::const_iterator FlagConstIterator; + FlagMap flags_; + + // The map from current-value pointer to flag, fo FindFlagViaPtrLocked(). + typedef map FlagPtrMap; + FlagPtrMap flags_by_ptr_; + + static FlagRegistry *global_registry_; // a singleton registry + + Mutex lock_; + + static void InitGlobalRegistry(); + + // Disallow + FlagRegistry(const FlagRegistry &); + FlagRegistry &operator=(const FlagRegistry &); +}; + +class FlagRegistryLock { +public: + explicit FlagRegistryLock(FlagRegistry *fr) : fr_(fr) { fr_->Lock(); } + ~FlagRegistryLock() { fr_->Unlock(); } + +private: + FlagRegistry *const fr_; +}; + +void FlagRegistry::RegisterFlag(CommandLineFlag *flag) { + Lock(); + pair ins = + flags_.insert(pair(flag->name(), flag)); + if (ins.second == false) { // means the name was already in the map + if (strcmp(ins.first->second->filename(), flag->filename()) != 0) { + ReportError(DIE, + "ERROR: flag '%s' was defined more than once " + "(in files '%s' and '%s').\n", + flag->name(), ins.first->second->filename(), + flag->filename()); + } else { + ReportError(DIE, + "ERROR: something wrong with flag '%s' in file '%s'. " + "One possibility: file '%s' is being linked both statically " + "and dynamically into this executable.\n", + flag->name(), flag->filename(), flag->filename()); + } + } + // Also add to the flags_by_ptr_ map. + flags_by_ptr_[flag->current_->value_buffer_] = flag; + Unlock(); +} + +CommandLineFlag *FlagRegistry::FindFlagLocked(const char *name) { + FlagConstIterator i = flags_.find(name); + if (i == flags_.end()) { + // If the name has dashes in it, try again after replacing with + // underscores. + if (strchr(name, '-') == NULL) + return NULL; + string name_rep = name; + std::replace(name_rep.begin(), name_rep.end(), '-', '_'); + return FindFlagLocked(name_rep.c_str()); + } else { + return i->second; + } +} + +CommandLineFlag *FlagRegistry::FindFlagViaPtrLocked(const void *flag_ptr) { + FlagPtrMap::const_iterator i = flags_by_ptr_.find(flag_ptr); + if (i == flags_by_ptr_.end()) { + return NULL; + } else { + return i->second; + } +} + +CommandLineFlag *FlagRegistry::SplitArgumentLocked(const char *arg, string *key, + const char **v, + string *error_message) { + // Find the flag object for this option + const char *flag_name; + const char *value = strchr(arg, '='); + if (value == NULL) { + key->assign(arg); + *v = NULL; + } else { + // Strip out the "=value" portion from arg + key->assign(arg, value - arg); + *v = ++value; // advance past the '=' + } + flag_name = key->c_str(); + + CommandLineFlag *flag = FindFlagLocked(flag_name); + + if (flag == NULL) { + // If we can't find the flag-name, then we should return an error. + // The one exception is if 1) the flag-name is 'nox', 2) there + // exists a flag named 'x', and 3) 'x' is a boolean flag. + // In that case, we want to return flag 'x'. + if (!(flag_name[0] == 'n' && flag_name[1] == 'o')) { + // flag-name is not 'nox', so we're not in the exception case. + *error_message = StringPrintf("%sunknown command line flag '%s'\n", + kError, key->c_str()); + return NULL; + } + flag = FindFlagLocked(flag_name + 2); + if (flag == NULL) { + // No flag named 'x' exists, so we're not in the exception case. + *error_message = StringPrintf("%sunknown command line flag '%s'\n", + kError, key->c_str()); + return NULL; + } + if (flag->Type() != FlagValue::FV_BOOL) { + // 'x' exists but is not boolean, so we're not in the exception case. + *error_message = StringPrintf( + "%sboolean value (%s) specified for %s command line flag\n", kError, + key->c_str(), flag->type_name()); + return NULL; + } + // We're in the exception case! + // Make up a fake value to replace the "no" we stripped out + key->assign(flag_name + 2); // the name without the "no" + *v = "0"; + } + + // Assign a value if this is a boolean flag + if (*v == NULL && flag->Type() == FlagValue::FV_BOOL) { + *v = "1"; // the --nox case was already handled, so this is the --x case + } + + return flag; +} + +bool TryParseLocked(const CommandLineFlag *flag, FlagValue *flag_value, + const char *value, string *msg) { + // Use tenative_value, not flag_value, until we know value is valid. + FlagValue *tentative_value = flag_value->New(); + if (!tentative_value->ParseFrom(value)) { + if (msg) { + StringAppendF(msg, "%sillegal value '%s' specified for %s flag '%s'\n", + kError, value, flag->type_name(), flag->name()); + } + delete tentative_value; + return false; + } else if (!flag->Validate(*tentative_value)) { + if (msg) { + StringAppendF(msg, + "%sfailed validation of new value '%s' for flag '%s'\n", + kError, tentative_value->ToString().c_str(), flag->name()); + } + delete tentative_value; + return false; + } else { + flag_value->CopyFrom(*tentative_value); + if (msg) { + StringAppendF(msg, "%s set to %s\n", flag->name(), + flag_value->ToString().c_str()); + } + delete tentative_value; + return true; + } +} + +bool FlagRegistry::SetFlagLocked(CommandLineFlag *flag, const char *value, + FlagSettingMode set_mode, string *msg) { + flag->UpdateModifiedBit(); + switch (set_mode) { + case SET_FLAGS_VALUE: { + // set or modify the flag's value + if (!TryParseLocked(flag, flag->current_, value, msg)) + return false; + flag->modified_ = true; + break; + } + case SET_FLAG_IF_DEFAULT: { + // set the flag's value, but only if it hasn't been set by someone else + if (!flag->modified_) { + if (!TryParseLocked(flag, flag->current_, value, msg)) + return false; + flag->modified_ = true; + } else { + *msg = StringPrintf("%s set to %s", flag->name(), + flag->current_value().c_str()); + } + break; + } + case SET_FLAGS_DEFAULT: { + // modify the flag's default-value + if (!TryParseLocked(flag, flag->defvalue_, value, msg)) + return false; + if (!flag->modified_) { + // Need to set both defvalue *and* current, in this case + TryParseLocked(flag, flag->current_, value, NULL); + } + break; + } + default: { + // unknown set_mode + assert(false); + return false; + } + } + + return true; +} + +// Get the singleton FlagRegistry object +FlagRegistry *FlagRegistry::global_registry_ = NULL; + +FlagRegistry *FlagRegistry::GlobalRegistry() { + static Mutex lock(Mutex::LINKER_INITIALIZED); + MutexLock acquire_lock(&lock); + if (!global_registry_) { + global_registry_ = new FlagRegistry; + } + return global_registry_; +} + +// -------------------------------------------------------------------- +// CommandLineFlagParser +// Parsing is done in two stages. In the first, we go through +// argv. For every flag-like arg we can make sense of, we parse +// it and set the appropriate FLAGS_* variable. For every flag- +// like arg we can't make sense of, we store it in a vector, +// along with an explanation of the trouble. In stage 2, we +// handle the 'reporting' flags like --help and --mpm_version. +// (This is via a call to HandleCommandLineHelpFlags(), in +// gflags_reporting.cc.) +// An optional stage 3 prints out the error messages. +// This is a bit of a simplification. For instance, --flagfile +// is handled as soon as it's seen in stage 1, not in stage 2. +// -------------------------------------------------------------------- + +class CommandLineFlagParser { +public: + // The argument is the flag-registry to register the parsed flags in + explicit CommandLineFlagParser(FlagRegistry *reg) : registry_(reg) {} + ~CommandLineFlagParser() {} + + // Stage 1: Every time this is called, it reads all flags in argv. + // However, it ignores all flags that have been successfully set + // before. Typically this is only called once, so this 'reparsing' + // behavior isn't important. It can be useful when trying to + // reparse after loading a dll, though. + uint32 ParseNewCommandLineFlags(int *argc, char ***argv, bool remove_flags); + + // Stage 2: print reporting info and exit, if requested. + // In gflags_reporting.cc:HandleCommandLineHelpFlags(). + + // Stage 3: validate all the commandline flags that have validators + // registered and were not set/modified by ParseNewCommandLineFlags. + void ValidateFlags(bool all); + void ValidateUnmodifiedFlags(); + + // Stage 4: report any errors and return true if any were found. + bool ReportErrors(); + + // Set a particular command line option. "newval" is a string + // describing the new value that the option has been set to. If + // option_name does not specify a valid option name, or value is not + // a valid value for option_name, newval is empty. Does recursive + // processing for --flagfile and --fromenv. Returns the new value + // if everything went ok, or empty-string if not. (Actually, the + // return-string could hold many flag/value pairs due to --flagfile.) + // NB: Must have called registry_->Lock() before calling this function. + string ProcessSingleOptionLocked(CommandLineFlag *flag, const char *value, + FlagSettingMode set_mode); + + // Set a whole batch of command line options as specified by contentdata, + // which is in flagfile format (and probably has been read from a flagfile). + // Returns the new value if everything went ok, or empty-string if + // not. (Actually, the return-string could hold many flag/value + // pairs due to --flagfile.) + // NB: Must have called registry_->Lock() before calling this function. + string ProcessOptionsFromStringLocked(const string &contentdata, + FlagSettingMode set_mode); + + // These are the 'recursive' flags, defined at the top of this file. + // Whenever we see these flags on the commandline, we must take action. + // These are called by ProcessSingleOptionLocked and, similarly, return + // new values if everything went ok, or the empty-string if not. + string ProcessFlagfileLocked(const string &flagval, FlagSettingMode set_mode); + // diff fromenv/tryfromenv + string ProcessFromenvLocked(const string &flagval, FlagSettingMode set_mode, + bool errors_are_fatal); + +private: + FlagRegistry *const registry_; + map error_flags_; // map from name to error message + // This could be a set, but we reuse the map to minimize the .o size + map undefined_names_; // --[flag] name was not registered +}; + +// Parse a list of (comma-separated) flags. +static void ParseFlagList(const char *value, vector *flags) { + for (const char *p = value; p && *p; value = p) { + p = strchr(value, ','); + size_t len; + if (p) { + len = p - value; + p++; + } else { + len = strlen(value); + } + + if (len == 0) + ReportError(DIE, "ERROR: empty flaglist entry\n"); + if (value[0] == '-') + ReportError(DIE, "ERROR: flag \"%*s\" begins with '-'\n", len, value); + + flags->push_back(string(value, len)); + } +} + +// Snarf an entire file into a C++ string. This is just so that we +// can do all the I/O in one place and not worry about it everywhere. +// Plus, it's convenient to have the whole file contents at hand. +// Adds a newline at the end of the file. +#define PFATAL(s) \ + do { \ + perror(s); \ + gflags_exitfunc(1); \ + } while (0) + +static string ReadFileIntoString(const char *filename) { + const int kBufSize = 8092; + char buffer[kBufSize]; + string s; + FILE *fp; + if ((errno = SafeFOpen(&fp, filename, "r")) != 0) + PFATAL(filename); + size_t n; + while ((n = fread(buffer, 1, kBufSize, fp)) > 0) { + if (ferror(fp)) + PFATAL(filename); + s.append(buffer, n); + } + fclose(fp); + return s; +} + +uint32 CommandLineFlagParser::ParseNewCommandLineFlags(int *argc, char ***argv, + bool remove_flags) { + int first_nonopt = *argc; // for non-options moved to the end + + registry_->Lock(); + for (int i = 1; i < first_nonopt; i++) { + char *arg = (*argv)[i]; + + // Like getopt(), we permute non-option flags to be at the end. + if (arg[0] != '-' || arg[1] == '\0') { // must be a program argument: "-" is + // an argument, not a flag + memmove((*argv) + i, (*argv) + i + 1, + (*argc - (i + 1)) * sizeof((*argv)[i])); + (*argv)[*argc - 1] = arg; // we go last + first_nonopt--; // we've been pushed onto the stack + i--; // to undo the i++ in the loop + continue; + } + arg++; // skip leading '-' + if (arg[0] == '-') + arg++; // or leading '--' + + // -- alone means what it does for GNU: stop options parsing + if (*arg == '\0') { + first_nonopt = i + 1; + break; + } + + // Find the flag object for this option + string key; + const char *value; + string error_message; + CommandLineFlag *flag = + registry_->SplitArgumentLocked(arg, &key, &value, &error_message); + if (flag == NULL) { + undefined_names_[key] = ""; // value isn't actually used + error_flags_[key] = error_message; + continue; + } + + if (value == NULL) { + // Boolean options are always assigned a value by SplitArgumentLocked() + assert(flag->Type() != FlagValue::FV_BOOL); + if (i + 1 >= first_nonopt) { + // This flag needs a value, but there is nothing available + error_flags_[key] = (string(kError) + "flag '" + (*argv)[i] + "'" + + " is missing its argument"); + if (flag->help() && flag->help()[0] > '\001') { + // Be useful in case we have a non-stripped description. + error_flags_[key] += string("; flag description: ") + flag->help(); + } + error_flags_[key] += "\n"; + break; // we treat this as an unrecoverable error + } else { + value = (*argv)[++i]; // read next arg for value + + // Heuristic to detect the case where someone treats a string arg + // like a bool: + // --my_string_var --foo=bar + // We look for a flag of string type, whose value begins with a + // dash, and where the flag-name and value are separated by a + // space rather than an '='. + // To avoid false positives, we also require the word "true" + // or "false" in the help string. Without this, a valid usage + // "-lat -30.5" would trigger the warning. The common cases we + // want to solve talk about true and false as values. + if (value[0] == '-' && flag->Type() == FlagValue::FV_STRING && + (strstr(flag->help(), "true") || strstr(flag->help(), "false"))) { + LOG(WARNING) << "Did you really mean to set flag '" << flag->name() + << "' to the value '" << value << "'?"; + } + } + } + + // TODO(csilvers): only set a flag if we hadn't set it before here + ProcessSingleOptionLocked(flag, value, SET_FLAGS_VALUE); + } + registry_->Unlock(); + + if (remove_flags) { // Fix up argc and argv by removing command line flags + (*argv)[first_nonopt - 1] = (*argv)[0]; + (*argv) += (first_nonopt - 1); + (*argc) -= (first_nonopt - 1); + first_nonopt = 1; // because we still don't count argv[0] + } + + logging_is_probably_set_up = true; // because we've parsed --logdir, etc. + + return first_nonopt; +} + +string CommandLineFlagParser::ProcessFlagfileLocked(const string &flagval, + FlagSettingMode set_mode) { + if (flagval.empty()) + return ""; + + string msg; + vector filename_list; + ParseFlagList(flagval.c_str(), &filename_list); // take a list of filenames + for (size_t i = 0; i < filename_list.size(); ++i) { + const char *file = filename_list[i].c_str(); + msg += ProcessOptionsFromStringLocked(ReadFileIntoString(file), set_mode); + } + return msg; +} + +string CommandLineFlagParser::ProcessFromenvLocked(const string &flagval, + FlagSettingMode set_mode, + bool errors_are_fatal) { + if (flagval.empty()) + return ""; + + string msg; + vector flaglist; + ParseFlagList(flagval.c_str(), &flaglist); + + for (size_t i = 0; i < flaglist.size(); ++i) { + const char *flagname = flaglist[i].c_str(); + CommandLineFlag *flag = registry_->FindFlagLocked(flagname); + if (flag == NULL) { + error_flags_[flagname] = StringPrintf("%sunknown command line flag '%s' " + "(via --fromenv or --tryfromenv)\n", + kError, flagname); + undefined_names_[flagname] = ""; + continue; + } + + const string envname = string("FLAGS_") + string(flagname); + string envval; + if (!SafeGetEnv(envname.c_str(), envval)) { + if (errors_are_fatal) { + error_flags_[flagname] = + (string(kError) + envname + " not found in environment\n"); + } + continue; + } + + // Avoid infinite recursion. + if (envval == "fromenv" || envval == "tryfromenv") { + error_flags_[flagname] = + StringPrintf("%sinfinite recursion on environment flag '%s'\n", + kError, envval.c_str()); + continue; + } + + msg += ProcessSingleOptionLocked(flag, envval.c_str(), set_mode); + } + return msg; +} + +string CommandLineFlagParser::ProcessSingleOptionLocked( + CommandLineFlag *flag, const char *value, FlagSettingMode set_mode) { + string msg; + if (value && !registry_->SetFlagLocked(flag, value, set_mode, &msg)) { + error_flags_[flag->name()] = msg; + return ""; + } + + // The recursive flags, --flagfile and --fromenv and --tryfromenv, + // must be dealt with as soon as they're seen. They will emit + // messages of their own. + if (strcmp(flag->name(), "flagfile") == 0) { + msg += ProcessFlagfileLocked(FLAGS_flagfile, set_mode); + + } else if (strcmp(flag->name(), "fromenv") == 0) { + // last arg indicates envval-not-found is fatal (unlike in --tryfromenv) + msg += ProcessFromenvLocked(FLAGS_fromenv, set_mode, true); + + } else if (strcmp(flag->name(), "tryfromenv") == 0) { + msg += ProcessFromenvLocked(FLAGS_tryfromenv, set_mode, false); + } + + return msg; +} + +void CommandLineFlagParser::ValidateFlags(bool all) { + FlagRegistryLock frl(registry_); + for (FlagRegistry::FlagConstIterator i = registry_->flags_.begin(); + i != registry_->flags_.end(); ++i) { + if ((all || !i->second->Modified()) && !i->second->ValidateCurrent()) { + // only set a message if one isn't already there. (If there's + // an error message, our job is done, even if it's not exactly + // the same error.) + if (error_flags_[i->second->name()].empty()) { + error_flags_[i->second->name()] = string(kError) + "--" + + i->second->name() + + " must be set on the commandline"; + if (!i->second->Modified()) { + error_flags_[i->second->name()] += + " (default value fails validation)"; + } + error_flags_[i->second->name()] += "\n"; + } + } + } +} + +void CommandLineFlagParser::ValidateUnmodifiedFlags() { ValidateFlags(false); } + +bool CommandLineFlagParser::ReportErrors() { + // error_flags_ indicates errors we saw while parsing. + // But we ignore undefined-names if ok'ed by --undef_ok + if (!FLAGS_undefok.empty()) { + vector flaglist; + ParseFlagList(FLAGS_undefok.c_str(), &flaglist); + for (size_t i = 0; i < flaglist.size(); ++i) { + // We also deal with --no, in case the flagname was boolean + const string no_version = string("no") + flaglist[i]; + if (undefined_names_.find(flaglist[i]) != undefined_names_.end()) { + error_flags_[flaglist[i]] = ""; // clear the error message + } else if (undefined_names_.find(no_version) != undefined_names_.end()) { + error_flags_[no_version] = ""; + } + } + } + // Likewise, if they decided to allow reparsing, all undefined-names + // are ok; we just silently ignore them now, and hope that a future + // parse will pick them up somehow. + if (allow_command_line_reparsing) { + for (map::const_iterator it = undefined_names_.begin(); + it != undefined_names_.end(); ++it) + error_flags_[it->first] = ""; // clear the error message + } + + bool found_error = false; + string error_message; + for (map::const_iterator it = error_flags_.begin(); + it != error_flags_.end(); ++it) { + if (!it->second.empty()) { + error_message.append(it->second.data(), it->second.size()); + found_error = true; + } + } + if (found_error) + ReportError(DO_NOT_DIE, "%s", error_message.c_str()); + return found_error; +} + +string CommandLineFlagParser::ProcessOptionsFromStringLocked( + const string &contentdata, FlagSettingMode set_mode) { + string retval; + const char *flagfile_contents = contentdata.c_str(); + bool flags_are_relevant = true; // set to false when filenames don't match + bool in_filename_section = false; + + const char *line_end = flagfile_contents; + // We read this file a line at a time. + for (; line_end; flagfile_contents = line_end + 1) { + while (*flagfile_contents && isspace(*flagfile_contents)) + ++flagfile_contents; + // Windows uses "\r\n" + line_end = strchr(flagfile_contents, '\r'); + if (line_end == NULL) + line_end = strchr(flagfile_contents, '\n'); + + size_t len = + line_end ? line_end - flagfile_contents : strlen(flagfile_contents); + string line(flagfile_contents, len); + + // Each line can be one of four things: + // 1) A comment line -- we skip it + // 2) An empty line -- we skip it + // 3) A list of filenames -- starts a new filenames+flags section + // 4) A --flag=value line -- apply if previous filenames match + if (line.empty() || line[0] == '#') { + // comment or empty line; just ignore + + } else if (line[0] == '-') { // flag + in_filename_section = false; // instead, it was a flag-line + if (!flags_are_relevant) // skip this flag; applies to someone else + continue; + + const char *name_and_val = line.c_str() + 1; // skip the leading - + if (*name_and_val == '-') + name_and_val++; // skip second - too + string key; + const char *value; + string error_message; + CommandLineFlag *flag = registry_->SplitArgumentLocked( + name_and_val, &key, &value, &error_message); + // By API, errors parsing flagfile lines are silently ignored. + if (flag == NULL) { + // "WARNING: flagname '" + key + "' not found\n" + } else if (value == NULL) { + // "WARNING: flagname '" + key + "' missing a value\n" + } else { + retval += ProcessSingleOptionLocked(flag, value, set_mode); + } + + } else { // a filename! + if (!in_filename_section) { // start over: assume filenames don't match + in_filename_section = true; + flags_are_relevant = false; + } + + // Split the line up at spaces into glob-patterns + const char *space = line.c_str(); // just has to be non-NULL + for (const char *word = line.c_str(); *space; word = space + 1) { + if (flags_are_relevant) // we can stop as soon as we match + break; + space = strchr(word, ' '); + if (space == NULL) + space = word + strlen(word); + const string glob(word, space - word); + // We try matching both against the full argv0 and basename(argv0) + if (glob == ProgramInvocationName() // small optimization + || glob == ProgramInvocationShortName() +#if defined(HAVE_FNMATCH_H) + || + fnmatch(glob.c_str(), ProgramInvocationName(), FNM_PATHNAME) == 0 || + fnmatch(glob.c_str(), ProgramInvocationShortName(), FNM_PATHNAME) == + 0 +#elif defined(HAVE_SHLWAPI_H) + || PathMatchSpecA(glob.c_str(), ProgramInvocationName()) || + PathMatchSpecA(glob.c_str(), ProgramInvocationShortName()) +#endif + ) { + flags_are_relevant = true; + } + } + } + } + return retval; +} + +// -------------------------------------------------------------------- +// GetFromEnv() +// AddFlagValidator() +// These are helper functions for routines like BoolFromEnv() and +// RegisterFlagValidator, defined below. They're defined here so +// they can live in the unnamed namespace (which makes friendship +// declarations for these classes possible). +// -------------------------------------------------------------------- + +template T GetFromEnv(const char *varname, T dflt) { + std::string valstr; + if (SafeGetEnv(varname, valstr)) { + FlagValue ifv(new T, true); + if (!ifv.ParseFrom(valstr.c_str())) { + ReportError(DIE, + "ERROR: error parsing env variable '%s' with value '%s'\n", + varname, valstr.c_str()); + } + return OTHER_VALUE_AS(ifv, T); + } else + return dflt; +} + +bool AddFlagValidator(const void *flag_ptr, ValidateFnProto validate_fn_proto) { + // We want a lock around this routine, in case two threads try to + // add a validator (hopefully the same one!) at once. We could use + // our own thread, but we need to loook at the registry anyway, so + // we just steal that one. + FlagRegistry *const registry = FlagRegistry::GlobalRegistry(); + FlagRegistryLock frl(registry); + // First, find the flag whose current-flag storage is 'flag'. + // This is the CommandLineFlag whose current_->value_buffer_ == flag + CommandLineFlag *flag = registry->FindFlagViaPtrLocked(flag_ptr); + if (!flag) { + LOG(WARNING) << "Ignoring RegisterValidateFunction() for flag pointer " + << flag_ptr << ": no flag found at that address"; + return false; + } else if (validate_fn_proto == flag->validate_function()) { + return true; // ok to register the same function over and over again + } else if (validate_fn_proto != NULL && flag->validate_function() != NULL) { + LOG(WARNING) << "Ignoring RegisterValidateFunction() for flag '" + << flag->name() << "': validate-fn already registered"; + return false; + } else { + flag->validate_fn_proto_ = validate_fn_proto; + return true; + } +} + +} // namespace + +// Now define the functions that are exported via the .h file + +// -------------------------------------------------------------------- +// FlagRegisterer +// This class exists merely to have a global constructor (the +// kind that runs before main(), that goes an initializes each +// flag that's been declared. Note that it's very important we +// don't have a destructor that deletes flag_, because that would +// cause us to delete current_storage/defvalue_storage as well, +// which can cause a crash if anything tries to access the flag +// values in a global destructor. +// -------------------------------------------------------------------- + +namespace { +void RegisterCommandLineFlag(const char *name, const char *help, + const char *filename, FlagValue *current, + FlagValue *defvalue) { + if (help == NULL) + help = ""; + // Importantly, flag_ will never be deleted, so storage is always good. + CommandLineFlag *flag = + new CommandLineFlag(name, help, filename, current, defvalue); + FlagRegistry::GlobalRegistry()->RegisterFlag(flag); // default registry +} +} // namespace + +template +FlagRegisterer::FlagRegisterer(const char *name, const char *help, + const char *filename, FlagType *current_storage, + FlagType *defvalue_storage) { + FlagValue *const current = new FlagValue(current_storage, false); + FlagValue *const defvalue = new FlagValue(defvalue_storage, false); + RegisterCommandLineFlag(name, help, filename, current, defvalue); +} + +// Force compiler to generate code for the given template specialization. +#define INSTANTIATE_FLAG_REGISTERER_CTOR(type) \ + template GFLAGS_DLL_DECL FlagRegisterer::FlagRegisterer( \ + const char *name, const char *help, const char *filename, \ + type *current_storage, type *defvalue_storage) + +// Do this for all supported flag types. +INSTANTIATE_FLAG_REGISTERER_CTOR(bool); +INSTANTIATE_FLAG_REGISTERER_CTOR(int32); +INSTANTIATE_FLAG_REGISTERER_CTOR(uint32); +INSTANTIATE_FLAG_REGISTERER_CTOR(int64); +INSTANTIATE_FLAG_REGISTERER_CTOR(uint64); +INSTANTIATE_FLAG_REGISTERER_CTOR(double); +INSTANTIATE_FLAG_REGISTERER_CTOR(std::string); + +#undef INSTANTIATE_FLAG_REGISTERER_CTOR + +// -------------------------------------------------------------------- +// GetAllFlags() +// The main way the FlagRegistry class exposes its data. This +// returns, as strings, all the info about all the flags in +// the main registry, sorted first by filename they are defined +// in, and then by flagname. +// -------------------------------------------------------------------- + +struct FilenameFlagnameCmp { + bool operator()(const CommandLineFlagInfo &a, + const CommandLineFlagInfo &b) const { + int cmp = strcmp(a.filename.c_str(), b.filename.c_str()); + if (cmp == 0) + cmp = strcmp(a.name.c_str(), b.name.c_str()); // secondary sort key + return cmp < 0; + } +}; + +void GetAllFlags(vector *OUTPUT) { + FlagRegistry *const registry = FlagRegistry::GlobalRegistry(); + registry->Lock(); + for (FlagRegistry::FlagConstIterator i = registry->flags_.begin(); + i != registry->flags_.end(); ++i) { + CommandLineFlagInfo fi; + i->second->FillCommandLineFlagInfo(&fi); + OUTPUT->push_back(fi); + } + registry->Unlock(); + // Now sort the flags, first by filename they occur in, then alphabetically + sort(OUTPUT->begin(), OUTPUT->end(), FilenameFlagnameCmp()); +} + +// -------------------------------------------------------------------- +// SetArgv() +// GetArgvs() +// GetArgv() +// GetArgv0() +// ProgramInvocationName() +// ProgramInvocationShortName() +// SetUsageMessage() +// ProgramUsage() +// Functions to set and get argv. Typically the setter is called +// by ParseCommandLineFlags. Also can get the ProgramUsage string, +// set by SetUsageMessage. +// -------------------------------------------------------------------- + +// These values are not protected by a Mutex because they are normally +// set only once during program startup. +static string argv0("UNKNOWN"); // just the program name +static string cmdline; // the entire command-line +static string program_usage; +static vector argvs; +static uint32 argv_sum = 0; + +void SetArgv(int argc, const char **argv) { + static bool called_set_argv = false; + if (called_set_argv) + return; + called_set_argv = true; + + assert(argc > 0); // every program has at least a name + argv0 = argv[0]; + + cmdline.clear(); + for (int i = 0; i < argc; i++) { + if (i != 0) + cmdline += " "; + cmdline += argv[i]; + argvs.push_back(argv[i]); + } + + // Compute a simple sum of all the chars in argv + argv_sum = 0; + for (string::const_iterator c = cmdline.begin(); c != cmdline.end(); ++c) { + argv_sum += *c; + } +} + +const vector &GetArgvs() { return argvs; } +const char *GetArgv() { return cmdline.c_str(); } +const char *GetArgv0() { return argv0.c_str(); } +uint32 GetArgvSum() { return argv_sum; } +const char *ProgramInvocationName() { // like the GNU libc fn + return GetArgv0(); +} +const char *ProgramInvocationShortName() { // like the GNU libc fn + size_t pos = argv0.rfind('/'); +#ifdef OS_WINDOWS + if (pos == string::npos) + pos = argv0.rfind('\\'); +#endif + return (pos == string::npos ? argv0.c_str() : (argv0.c_str() + pos + 1)); +} + +void SetUsageMessage(const string &usage) { program_usage = usage; } + +const char *ProgramUsage() { + if (program_usage.empty()) { + return "Warning: SetUsageMessage() never called"; + } + return program_usage.c_str(); +} + +// -------------------------------------------------------------------- +// SetVersionString() +// VersionString() +// -------------------------------------------------------------------- + +static string version_string; + +void SetVersionString(const string &version) { version_string = version; } + +const char *VersionString() { return version_string.c_str(); } + +// -------------------------------------------------------------------- +// GetCommandLineOption() +// GetCommandLineFlagInfo() +// GetCommandLineFlagInfoOrDie() +// SetCommandLineOption() +// SetCommandLineOptionWithMode() +// The programmatic way to set a flag's value, using a string +// for its name rather than the variable itself (that is, +// SetCommandLineOption("foo", x) rather than FLAGS_foo = x). +// There's also a bit more flexibility here due to the various +// set-modes, but typically these are used when you only have +// that flag's name as a string, perhaps at runtime. +// All of these work on the default, global registry. +// For GetCommandLineOption, return false if no such flag +// is known, true otherwise. We clear "value" if a suitable +// flag is found. +// -------------------------------------------------------------------- + +bool GetCommandLineOption(const char *name, string *value) { + if (NULL == name) + return false; + assert(value); + + FlagRegistry *const registry = FlagRegistry::GlobalRegistry(); + FlagRegistryLock frl(registry); + CommandLineFlag *flag = registry->FindFlagLocked(name); + if (flag == NULL) { + return false; + } else { + *value = flag->current_value(); + return true; + } +} + +bool GetCommandLineFlagInfo(const char *name, CommandLineFlagInfo *OUTPUT) { + if (NULL == name) + return false; + FlagRegistry *const registry = FlagRegistry::GlobalRegistry(); + FlagRegistryLock frl(registry); + CommandLineFlag *flag = registry->FindFlagLocked(name); + if (flag == NULL) { + return false; + } else { + assert(OUTPUT); + flag->FillCommandLineFlagInfo(OUTPUT); + return true; + } +} + +CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char *name) { + CommandLineFlagInfo info; + if (!GetCommandLineFlagInfo(name, &info)) { + fprintf(stderr, "FATAL ERROR: flag name '%s' doesn't exist\n", name); + gflags_exitfunc(1); // almost certainly gflags_exitfunc() + } + return info; +} + +string SetCommandLineOptionWithMode(const char *name, const char *value, + FlagSettingMode set_mode) { + string result; + FlagRegistry *const registry = FlagRegistry::GlobalRegistry(); + FlagRegistryLock frl(registry); + CommandLineFlag *flag = registry->FindFlagLocked(name); + if (flag) { + CommandLineFlagParser parser(registry); + result = parser.ProcessSingleOptionLocked(flag, value, set_mode); + if (!result.empty()) { // in the error case, we've already logged + // Could consider logging this change + } + } + // The API of this function is that we return empty string on error + return result; +} + +string SetCommandLineOption(const char *name, const char *value) { + return SetCommandLineOptionWithMode(name, value, SET_FLAGS_VALUE); +} + +// -------------------------------------------------------------------- +// FlagSaver +// FlagSaverImpl +// This class stores the states of all flags at construct time, +// and restores all flags to that state at destruct time. +// Its major implementation challenge is that it never modifies +// pointers in the 'main' registry, so global FLAG_* vars always +// point to the right place. +// -------------------------------------------------------------------- + +class FlagSaverImpl { +public: + // Constructs an empty FlagSaverImpl object. + explicit FlagSaverImpl(FlagRegistry *main_registry) + : main_registry_(main_registry) {} + ~FlagSaverImpl() { + // reclaim memory from each of our CommandLineFlags + vector::const_iterator it; + for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it) + delete *it; + } + + // Saves the flag states from the flag registry into this object. + // It's an error to call this more than once. + // Must be called when the registry mutex is not held. + void SaveFromRegistry() { + FlagRegistryLock frl(main_registry_); + assert(backup_registry_.empty()); // call only once! + for (FlagRegistry::FlagConstIterator it = main_registry_->flags_.begin(); + it != main_registry_->flags_.end(); ++it) { + const CommandLineFlag *main = it->second; + // Sets up all the const variables in backup correctly + CommandLineFlag *backup = + new CommandLineFlag(main->name(), main->help(), main->filename(), + main->current_->New(), main->defvalue_->New()); + // Sets up all the non-const variables in backup correctly + backup->CopyFrom(*main); + backup_registry_.push_back(backup); // add it to a convenient list + } + } + + // Restores the saved flag states into the flag registry. We + // assume no flags were added or deleted from the registry since + // the SaveFromRegistry; if they were, that's trouble! Must be + // called when the registry mutex is not held. + void RestoreToRegistry() { + FlagRegistryLock frl(main_registry_); + vector::const_iterator it; + for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it) { + CommandLineFlag *main = main_registry_->FindFlagLocked((*it)->name()); + if (main != NULL) { // if NULL, flag got deleted from registry(!) + main->CopyFrom(**it); + } + } + } + +private: + FlagRegistry *const main_registry_; + vector backup_registry_; + + FlagSaverImpl(const FlagSaverImpl &); // no copying! + void operator=(const FlagSaverImpl &); +}; + +FlagSaver::FlagSaver() + : impl_(new FlagSaverImpl(FlagRegistry::GlobalRegistry())) { + impl_->SaveFromRegistry(); +} + +FlagSaver::~FlagSaver() { + impl_->RestoreToRegistry(); + delete impl_; +} + +// -------------------------------------------------------------------- +// CommandlineFlagsIntoString() +// ReadFlagsFromString() +// AppendFlagsIntoFile() +// ReadFromFlagsFile() +// These are mostly-deprecated routines that stick the +// commandline flags into a file/string and read them back +// out again. I can see a use for CommandlineFlagsIntoString, +// for creating a flagfile, but the rest don't seem that useful +// -- some, I think, are a poor-man's attempt at FlagSaver -- +// and are included only until we can delete them from callers. +// Note they don't save --flagfile flags (though they do save +// the result of having called the flagfile, of course). +// -------------------------------------------------------------------- + +static string +TheseCommandlineFlagsIntoString(const vector &flags) { + vector::const_iterator i; + + size_t retval_space = 0; + for (i = flags.begin(); i != flags.end(); ++i) { + // An (over)estimate of how much space it will take to print this flag + retval_space += i->name.length() + i->current_value.length() + 5; + } + + string retval; + retval.reserve(retval_space); + for (i = flags.begin(); i != flags.end(); ++i) { + retval += "--"; + retval += i->name; + retval += "="; + retval += i->current_value; + retval += "\n"; + } + return retval; +} + +string CommandlineFlagsIntoString() { + vector sorted_flags; + GetAllFlags(&sorted_flags); + return TheseCommandlineFlagsIntoString(sorted_flags); +} + +bool ReadFlagsFromString(const string &flagfilecontents, + const char * /*prog_name*/, // TODO(csilvers): nix this + bool errors_are_fatal) { + FlagRegistry *const registry = FlagRegistry::GlobalRegistry(); + FlagSaverImpl saved_states(registry); + saved_states.SaveFromRegistry(); + + CommandLineFlagParser parser(registry); + registry->Lock(); + parser.ProcessOptionsFromStringLocked(flagfilecontents, SET_FLAGS_VALUE); + registry->Unlock(); + // Should we handle --help and such when reading flags from a string? Sure. + HandleCommandLineHelpFlags(); + if (parser.ReportErrors()) { + // Error. Restore all global flags to their previous values. + if (errors_are_fatal) + gflags_exitfunc(1); + saved_states.RestoreToRegistry(); + return false; + } + return true; +} + +// TODO(csilvers): nix prog_name in favor of ProgramInvocationShortName() +bool AppendFlagsIntoFile(const string &filename, const char *prog_name) { + FILE *fp; + if (SafeFOpen(&fp, filename.c_str(), "a") != 0) { + return false; + } + + if (prog_name) + fprintf(fp, "%s\n", prog_name); + + vector flags; + GetAllFlags(&flags); + // But we don't want --flagfile, which leads to weird recursion issues + vector::iterator i; + for (i = flags.begin(); i != flags.end(); ++i) { + if (strcmp(i->name.c_str(), "flagfile") == 0) { + flags.erase(i); + break; + } + } + fprintf(fp, "%s", TheseCommandlineFlagsIntoString(flags).c_str()); + + fclose(fp); + return true; +} + +bool ReadFromFlagsFile(const string &filename, const char *prog_name, + bool errors_are_fatal) { + return ReadFlagsFromString(ReadFileIntoString(filename.c_str()), prog_name, + errors_are_fatal); +} + +// -------------------------------------------------------------------- +// BoolFromEnv() +// Int32FromEnv() +// Uint32FromEnv() +// Int64FromEnv() +// Uint64FromEnv() +// DoubleFromEnv() +// StringFromEnv() +// Reads the value from the environment and returns it. +// We use an FlagValue to make the parsing easy. +// Example usage: +// DEFINE_bool(myflag, BoolFromEnv("MYFLAG_DEFAULT", false), "whatever"); +// -------------------------------------------------------------------- + +bool BoolFromEnv(const char *v, bool dflt) { return GetFromEnv(v, dflt); } +int32 Int32FromEnv(const char *v, int32 dflt) { return GetFromEnv(v, dflt); } +uint32 Uint32FromEnv(const char *v, uint32 dflt) { return GetFromEnv(v, dflt); } +int64 Int64FromEnv(const char *v, int64 dflt) { return GetFromEnv(v, dflt); } +uint64 Uint64FromEnv(const char *v, uint64 dflt) { return GetFromEnv(v, dflt); } +double DoubleFromEnv(const char *v, double dflt) { return GetFromEnv(v, dflt); } + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4996) // ignore getenv security warning +#endif +const char *StringFromEnv(const char *varname, const char *dflt) { + const char *const val = getenv(varname); + return val ? val : dflt; +} +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +// -------------------------------------------------------------------- +// RegisterFlagValidator() +// RegisterFlagValidator() is the function that clients use to +// 'decorate' a flag with a validation function. Once this is +// done, every time the flag is set (including when the flag +// is parsed from argv), the validator-function is called. +// These functions return true if the validator was added +// successfully, or false if not: the flag already has a validator, +// (only one allowed per flag), the 1st arg isn't a flag, etc. +// This function is not thread-safe. +// -------------------------------------------------------------------- + +bool RegisterFlagValidator(const bool *flag, + bool (*validate_fn)(const char *, bool)) { + return AddFlagValidator(flag, reinterpret_cast(validate_fn)); +} +bool RegisterFlagValidator(const int32 *flag, + bool (*validate_fn)(const char *, int32)) { + return AddFlagValidator(flag, reinterpret_cast(validate_fn)); +} +bool RegisterFlagValidator(const uint32 *flag, + bool (*validate_fn)(const char *, uint32)) { + return AddFlagValidator(flag, reinterpret_cast(validate_fn)); +} +bool RegisterFlagValidator(const int64 *flag, + bool (*validate_fn)(const char *, int64)) { + return AddFlagValidator(flag, reinterpret_cast(validate_fn)); +} +bool RegisterFlagValidator(const uint64 *flag, + bool (*validate_fn)(const char *, uint64)) { + return AddFlagValidator(flag, reinterpret_cast(validate_fn)); +} +bool RegisterFlagValidator(const double *flag, + bool (*validate_fn)(const char *, double)) { + return AddFlagValidator(flag, reinterpret_cast(validate_fn)); +} +bool RegisterFlagValidator(const string *flag, + bool (*validate_fn)(const char *, const string &)) { + return AddFlagValidator(flag, reinterpret_cast(validate_fn)); +} + +// -------------------------------------------------------------------- +// ParseCommandLineFlags() +// ParseCommandLineNonHelpFlags() +// HandleCommandLineHelpFlags() +// This is the main function called from main(), to actually +// parse the commandline. It modifies argc and argv as described +// at the top of gflags.h. You can also divide this +// function into two parts, if you want to do work between +// the parsing of the flags and the printing of any help output. +// -------------------------------------------------------------------- + +static uint32 ParseCommandLineFlagsInternal(int *argc, char ***argv, + bool remove_flags, bool do_report) { + SetArgv(*argc, const_cast(*argv)); // save it for later + + FlagRegistry *const registry = FlagRegistry::GlobalRegistry(); + CommandLineFlagParser parser(registry); + + // When we parse the commandline flags, we'll handle --flagfile, + // --tryfromenv, etc. as we see them (since flag-evaluation order + // may be important). But sometimes apps set FLAGS_tryfromenv/etc. + // manually before calling ParseCommandLineFlags. We want to evaluate + // those too, as if they were the first flags on the commandline. + registry->Lock(); + parser.ProcessFlagfileLocked(FLAGS_flagfile, SET_FLAGS_VALUE); + // Last arg here indicates whether flag-not-found is a fatal error or not + parser.ProcessFromenvLocked(FLAGS_fromenv, SET_FLAGS_VALUE, true); + parser.ProcessFromenvLocked(FLAGS_tryfromenv, SET_FLAGS_VALUE, false); + registry->Unlock(); + + // Now get the flags specified on the commandline + const int r = parser.ParseNewCommandLineFlags(argc, argv, remove_flags); + + if (do_report) + HandleCommandLineHelpFlags(); // may cause us to exit on --help, etc. + + // See if any of the unset flags fail their validation checks + parser.ValidateUnmodifiedFlags(); + + if (parser.ReportErrors()) // may cause us to exit on illegal flags + gflags_exitfunc(1); + return r; +} + +uint32 ParseCommandLineFlags(int *argc, char ***argv, bool remove_flags) { + return ParseCommandLineFlagsInternal(argc, argv, remove_flags, true); +} + +uint32 ParseCommandLineNonHelpFlags(int *argc, char ***argv, + bool remove_flags) { + return ParseCommandLineFlagsInternal(argc, argv, remove_flags, false); +} + +// -------------------------------------------------------------------- +// AllowCommandLineReparsing() +// ReparseCommandLineNonHelpFlags() +// This is most useful for shared libraries. The idea is if +// a flag is defined in a shared library that is dlopen'ed +// sometime after main(), you can ParseCommandLineFlags before +// the dlopen, then ReparseCommandLineNonHelpFlags() after the +// dlopen, to get the new flags. But you have to explicitly +// Allow() it; otherwise, you get the normal default behavior +// of unrecognized flags calling a fatal error. +// TODO(csilvers): this isn't used. Just delete it? +// -------------------------------------------------------------------- + +void AllowCommandLineReparsing() { allow_command_line_reparsing = true; } + +void ReparseCommandLineNonHelpFlags() { + // We make a copy of argc and argv to pass in + const vector &argvs = GetArgvs(); + int tmp_argc = static_cast(argvs.size()); + char **tmp_argv = new char *[tmp_argc + 1]; + for (int i = 0; i < tmp_argc; ++i) + tmp_argv[i] = strdup(argvs[i].c_str()); // TODO(csilvers): don't dup + + ParseCommandLineNonHelpFlags(&tmp_argc, &tmp_argv, false); + + for (int i = 0; i < tmp_argc; ++i) + free(tmp_argv[i]); + delete[] tmp_argv; +} + +void ShutDownCommandLineFlags() { FlagRegistry::DeleteGlobalRegistry(); } + +} // namespace GFLAGS_NAMESPACE diff --git a/third_party/gflags/src/gflags.h.in b/third_party/gflags/src/gflags.h.in new file mode 100644 index 0000000..7b218b9 --- /dev/null +++ b/third_party/gflags/src/gflags.h.in @@ -0,0 +1,626 @@ +// Copyright (c) 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// --- +// Revamped and reorganized by Craig Silverstein +// +// This is the file that should be included by any file which declares +// or defines a command line flag or wants to parse command line flags +// or print a program usage message (which will include information about +// flags). Executive summary, in the form of an example foo.cc file: +// +// #include "foo.h" // foo.h has a line "DECLARE_int32(start);" +// #include "validators.h" // hypothetical file defining ValidateIsFile() +// +// DEFINE_int32(end, 1000, "The last record to read"); +// +// DEFINE_string(filename, "my_file.txt", "The file to read"); +// // Crash if the specified file does not exist. +// static bool dummy = RegisterFlagValidator(&FLAGS_filename, +// &ValidateIsFile); +// +// DECLARE_bool(verbose); // some other file has a DEFINE_bool(verbose, ...) +// +// void MyFunc() { +// if (FLAGS_verbose) printf("Records %d-%d\n", FLAGS_start, FLAGS_end); +// } +// +// Then, at the command-line: +// ./foo --noverbose --start=5 --end=100 +// +// For more details, see +// doc/gflags.html +// +// --- A note about thread-safety: +// +// We describe many functions in this routine as being thread-hostile, +// thread-compatible, or thread-safe. Here are the meanings we use: +// +// thread-safe: it is safe for multiple threads to call this routine +// (or, when referring to a class, methods of this class) +// concurrently. +// thread-hostile: it is not safe for multiple threads to call this +// routine (or methods of this class) concurrently. In gflags, +// most thread-hostile routines are intended to be called early in, +// or even before, main() -- that is, before threads are spawned. +// thread-compatible: it is safe for multiple threads to read from +// this variable (when applied to variables), or to call const +// methods of this class (when applied to classes), as long as no +// other thread is writing to the variable or calling non-const +// methods of this class. + +#ifndef GFLAGS_GFLAGS_H_ +#define GFLAGS_GFLAGS_H_ + +#include +#include + +#include "gflags/gflags_declare.h" // IWYU pragma: export + + +// We always want to export variables defined in user code +#ifndef GFLAGS_DLL_DEFINE_FLAG +# if GFLAGS_IS_A_DLL && defined(_MSC_VER) +# define GFLAGS_DLL_DEFINE_FLAG __declspec(dllexport) +# else +# define GFLAGS_DLL_DEFINE_FLAG +# endif +#endif + + +namespace GFLAGS_NAMESPACE { + + +// -------------------------------------------------------------------- +// To actually define a flag in a file, use DEFINE_bool, +// DEFINE_string, etc. at the bottom of this file. You may also find +// it useful to register a validator with the flag. This ensures that +// when the flag is parsed from the commandline, or is later set via +// SetCommandLineOption, we call the validation function. It is _not_ +// called when you assign the value to the flag directly using the = operator. +// +// The validation function should return true if the flag value is valid, and +// false otherwise. If the function returns false for the new setting of the +// flag, the flag will retain its current value. If it returns false for the +// default value, ParseCommandLineFlags() will die. +// +// This function is safe to call at global construct time (as in the +// example below). +// +// Example use: +// static bool ValidatePort(const char* flagname, int32 value) { +// if (value > 0 && value < 32768) // value is ok +// return true; +// printf("Invalid value for --%s: %d\n", flagname, (int)value); +// return false; +// } +// DEFINE_int32(port, 0, "What port to listen on"); +// static bool dummy = RegisterFlagValidator(&FLAGS_port, &ValidatePort); + +// Returns true if successfully registered, false if not (because the +// first argument doesn't point to a command-line flag, or because a +// validator is already registered for this flag). +extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const bool* flag, bool (*validate_fn)(const char*, bool)); +extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const int32* flag, bool (*validate_fn)(const char*, int32)); +extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const uint32* flag, bool (*validate_fn)(const char*, uint32)); +extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const int64* flag, bool (*validate_fn)(const char*, int64)); +extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const uint64* flag, bool (*validate_fn)(const char*, uint64)); +extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const double* flag, bool (*validate_fn)(const char*, double)); +extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const std::string* flag, bool (*validate_fn)(const char*, const std::string&)); + +// Convenience macro for the registration of a flag validator +#define DEFINE_validator(name, validator) \ + static const bool name##_validator_registered = \ + GFLAGS_NAMESPACE::RegisterFlagValidator(&FLAGS_##name, validator) + + +// -------------------------------------------------------------------- +// These methods are the best way to get access to info about the +// list of commandline flags. Note that these routines are pretty slow. +// GetAllFlags: mostly-complete info about the list, sorted by file. +// ShowUsageWithFlags: pretty-prints the list to stdout (what --help does) +// ShowUsageWithFlagsRestrict: limit to filenames with restrict as a substr +// +// In addition to accessing flags, you can also access argv[0] (the program +// name) and argv (the entire commandline), which we sock away a copy of. +// These variables are static, so you should only set them once. +// +// No need to export this data only structure from DLL, avoiding VS warning 4251. +struct CommandLineFlagInfo { + std::string name; // the name of the flag + std::string type; // the type of the flag: int32, etc + std::string description; // the "help text" associated with the flag + std::string current_value; // the current value, as a string + std::string default_value; // the default value, as a string + std::string filename; // 'cleaned' version of filename holding the flag + bool has_validator_fn; // true if RegisterFlagValidator called on this flag + bool is_default; // true if the flag has the default value and + // has not been set explicitly from the cmdline + // or via SetCommandLineOption + const void* flag_ptr; // pointer to the flag's current value (i.e. FLAGS_foo) +}; + +// Using this inside of a validator is a recipe for a deadlock. +// TODO(user) Fix locking when validators are running, to make it safe to +// call validators during ParseAllFlags. +// Also make sure then to uncomment the corresponding unit test in +// gflags_unittest.sh +extern GFLAGS_DLL_DECL void GetAllFlags(std::vector* OUTPUT); +// These two are actually defined in gflags_reporting.cc. +extern GFLAGS_DLL_DECL void ShowUsageWithFlags(const char *argv0); // what --help does +extern GFLAGS_DLL_DECL void ShowUsageWithFlagsRestrict(const char *argv0, const char *restrict); + +// Create a descriptive string for a flag. +// Goes to some trouble to make pretty line breaks. +extern GFLAGS_DLL_DECL std::string DescribeOneFlag(const CommandLineFlagInfo& flag); + +// Thread-hostile; meant to be called before any threads are spawned. +extern GFLAGS_DLL_DECL void SetArgv(int argc, const char** argv); + +// The following functions are thread-safe as long as SetArgv() is +// only called before any threads start. +extern GFLAGS_DLL_DECL const std::vector& GetArgvs(); +extern GFLAGS_DLL_DECL const char* GetArgv(); // all of argv as a string +extern GFLAGS_DLL_DECL const char* GetArgv0(); // only argv0 +extern GFLAGS_DLL_DECL uint32 GetArgvSum(); // simple checksum of argv +extern GFLAGS_DLL_DECL const char* ProgramInvocationName(); // argv0, or "UNKNOWN" if not set +extern GFLAGS_DLL_DECL const char* ProgramInvocationShortName(); // basename(argv0) + +// ProgramUsage() is thread-safe as long as SetUsageMessage() is only +// called before any threads start. +extern GFLAGS_DLL_DECL const char* ProgramUsage(); // string set by SetUsageMessage() + +// VersionString() is thread-safe as long as SetVersionString() is only +// called before any threads start. +extern GFLAGS_DLL_DECL const char* VersionString(); // string set by SetVersionString() + + + +// -------------------------------------------------------------------- +// Normally you access commandline flags by just saying "if (FLAGS_foo)" +// or whatever, and set them by calling "FLAGS_foo = bar" (or, more +// commonly, via the DEFINE_foo macro). But if you need a bit more +// control, we have programmatic ways to get/set the flags as well. +// These programmatic ways to access flags are thread-safe, but direct +// access is only thread-compatible. + +// Return true iff the flagname was found. +// OUTPUT is set to the flag's value, or unchanged if we return false. +extern GFLAGS_DLL_DECL bool GetCommandLineOption(const char* name, std::string* OUTPUT); + +// Return true iff the flagname was found. OUTPUT is set to the flag's +// CommandLineFlagInfo or unchanged if we return false. +extern GFLAGS_DLL_DECL bool GetCommandLineFlagInfo(const char* name, CommandLineFlagInfo* OUTPUT); + +// Return the CommandLineFlagInfo of the flagname. exit() if name not found. +// Example usage, to check if a flag's value is currently the default value: +// if (GetCommandLineFlagInfoOrDie("foo").is_default) ... +extern GFLAGS_DLL_DECL CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char* name); + +enum GFLAGS_DLL_DECL FlagSettingMode { + // update the flag's value (can call this multiple times). + SET_FLAGS_VALUE, + // update the flag's value, but *only if* it has not yet been updated + // with SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, or "FLAGS_xxx = nondef". + SET_FLAG_IF_DEFAULT, + // set the flag's default value to this. If the flag has not yet updated + // yet (via SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, or "FLAGS_xxx = nondef") + // change the flag's current value to the new default value as well. + SET_FLAGS_DEFAULT +}; + +// Set a particular flag ("command line option"). Returns a string +// describing the new value that the option has been set to. The +// return value API is not well-specified, so basically just depend on +// it to be empty if the setting failed for some reason -- the name is +// not a valid flag name, or the value is not a valid value -- and +// non-empty else. + +// SetCommandLineOption uses set_mode == SET_FLAGS_VALUE (the common case) +extern GFLAGS_DLL_DECL std::string SetCommandLineOption (const char* name, const char* value); +extern GFLAGS_DLL_DECL std::string SetCommandLineOptionWithMode(const char* name, const char* value, FlagSettingMode set_mode); + + +// -------------------------------------------------------------------- +// Saves the states (value, default value, whether the user has set +// the flag, registered validators, etc) of all flags, and restores +// them when the FlagSaver is destroyed. This is very useful in +// tests, say, when you want to let your tests change the flags, but +// make sure that they get reverted to the original states when your +// test is complete. +// +// Example usage: +// void TestFoo() { +// FlagSaver s1; +// FLAG_foo = false; +// FLAG_bar = "some value"; +// +// // test happens here. You can return at any time +// // without worrying about restoring the FLAG values. +// } +// +// Note: This class is marked with GFLAGS_ATTRIBUTE_UNUSED because all +// the work is done in the constructor and destructor, so in the standard +// usage example above, the compiler would complain that it's an +// unused variable. +// +// This class is thread-safe. However, its destructor writes to +// exactly the set of flags that have changed value during its +// lifetime, so concurrent _direct_ access to those flags +// (i.e. FLAGS_foo instead of {Get,Set}CommandLineOption()) is unsafe. + +class GFLAGS_DLL_DECL FlagSaver { + public: + FlagSaver(); + ~FlagSaver(); + + private: + class FlagSaverImpl* impl_; // we use pimpl here to keep API steady + + FlagSaver(const FlagSaver&); // no copying! + void operator=(const FlagSaver&); +}@GFLAGS_ATTRIBUTE_UNUSED@; + +// -------------------------------------------------------------------- +// Some deprecated or hopefully-soon-to-be-deprecated functions. + +// This is often used for logging. TODO(csilvers): figure out a better way +extern GFLAGS_DLL_DECL std::string CommandlineFlagsIntoString(); +// Usually where this is used, a FlagSaver should be used instead. +extern GFLAGS_DLL_DECL +bool ReadFlagsFromString(const std::string& flagfilecontents, + const char* prog_name, + bool errors_are_fatal); // uses SET_FLAGS_VALUE + +// These let you manually implement --flagfile functionality. +// DEPRECATED. +extern GFLAGS_DLL_DECL bool AppendFlagsIntoFile(const std::string& filename, const char* prog_name); +extern GFLAGS_DLL_DECL bool ReadFromFlagsFile(const std::string& filename, const char* prog_name, bool errors_are_fatal); // uses SET_FLAGS_VALUE + + +// -------------------------------------------------------------------- +// Useful routines for initializing flags from the environment. +// In each case, if 'varname' does not exist in the environment +// return defval. If 'varname' does exist but is not valid +// (e.g., not a number for an int32 flag), abort with an error. +// Otherwise, return the value. NOTE: for booleans, for true use +// 't' or 'T' or 'true' or '1', for false 'f' or 'F' or 'false' or '0'. + +extern GFLAGS_DLL_DECL bool BoolFromEnv(const char *varname, bool defval); +extern GFLAGS_DLL_DECL int32 Int32FromEnv(const char *varname, int32 defval); +extern GFLAGS_DLL_DECL uint32 Uint32FromEnv(const char *varname, uint32 defval); +extern GFLAGS_DLL_DECL int64 Int64FromEnv(const char *varname, int64 defval); +extern GFLAGS_DLL_DECL uint64 Uint64FromEnv(const char *varname, uint64 defval); +extern GFLAGS_DLL_DECL double DoubleFromEnv(const char *varname, double defval); +extern GFLAGS_DLL_DECL const char *StringFromEnv(const char *varname, const char *defval); + + +// -------------------------------------------------------------------- +// The next two functions parse gflags from main(): + +// Set the "usage" message for this program. For example: +// string usage("This program does nothing. Sample usage:\n"); +// usage += argv[0] + " "; +// SetUsageMessage(usage); +// Do not include commandline flags in the usage: we do that for you! +// Thread-hostile; meant to be called before any threads are spawned. +extern GFLAGS_DLL_DECL void SetUsageMessage(const std::string& usage); + +// Sets the version string, which is emitted with --version. +// For instance: SetVersionString("1.3"); +// Thread-hostile; meant to be called before any threads are spawned. +extern GFLAGS_DLL_DECL void SetVersionString(const std::string& version); + + +// Looks for flags in argv and parses them. Rearranges argv to put +// flags first, or removes them entirely if remove_flags is true. +// If a flag is defined more than once in the command line or flag +// file, the last definition is used. Returns the index (into argv) +// of the first non-flag argument. +// See top-of-file for more details on this function. +#ifndef SWIG // In swig, use ParseCommandLineFlagsScript() instead. +extern GFLAGS_DLL_DECL uint32 ParseCommandLineFlags(int *argc, char*** argv, bool remove_flags); +#endif + + +// Calls to ParseCommandLineNonHelpFlags and then to +// HandleCommandLineHelpFlags can be used instead of a call to +// ParseCommandLineFlags during initialization, in order to allow for +// changing default values for some FLAGS (via +// e.g. SetCommandLineOptionWithMode calls) between the time of +// command line parsing and the time of dumping help information for +// the flags as a result of command line parsing. If a flag is +// defined more than once in the command line or flag file, the last +// definition is used. Returns the index (into argv) of the first +// non-flag argument. (If remove_flags is true, will always return 1.) +extern GFLAGS_DLL_DECL uint32 ParseCommandLineNonHelpFlags(int *argc, char*** argv, bool remove_flags); + +// This is actually defined in gflags_reporting.cc. +// This function is misnamed (it also handles --version, etc.), but +// it's too late to change that now. :-( +extern GFLAGS_DLL_DECL void HandleCommandLineHelpFlags(); // in gflags_reporting.cc + +// Allow command line reparsing. Disables the error normally +// generated when an unknown flag is found, since it may be found in a +// later parse. Thread-hostile; meant to be called before any threads +// are spawned. +extern GFLAGS_DLL_DECL void AllowCommandLineReparsing(); + +// Reparse the flags that have not yet been recognized. Only flags +// registered since the last parse will be recognized. Any flag value +// must be provided as part of the argument using "=", not as a +// separate command line argument that follows the flag argument. +// Intended for handling flags from dynamically loaded libraries, +// since their flags are not registered until they are loaded. +extern GFLAGS_DLL_DECL void ReparseCommandLineNonHelpFlags(); + +// Clean up memory allocated by flags. This is only needed to reduce +// the quantity of "potentially leaked" reports emitted by memory +// debugging tools such as valgrind. It is not required for normal +// operation, or for the google perftools heap-checker. It must only +// be called when the process is about to exit, and all threads that +// might access flags are quiescent. Referencing flags after this is +// called will have unexpected consequences. This is not safe to run +// when multiple threads might be running: the function is +// thread-hostile. +extern GFLAGS_DLL_DECL void ShutDownCommandLineFlags(); + + +// -------------------------------------------------------------------- +// Now come the command line flag declaration/definition macros that +// will actually be used. They're kind of hairy. A major reason +// for this is initialization: we want people to be able to access +// variables in global constructors and have that not crash, even if +// their global constructor runs before the global constructor here. +// (Obviously, we can't guarantee the flags will have the correct +// default value in that case, but at least accessing them is safe.) +// The only way to do that is have flags point to a static buffer. +// So we make one, using a union to ensure proper alignment, and +// then use placement-new to actually set up the flag with the +// correct default value. In the same vein, we have to worry about +// flag access in global destructors, so FlagRegisterer has to be +// careful never to destroy the flag-values it constructs. +// +// Note that when we define a flag variable FLAGS_, we also +// preemptively define a junk variable, FLAGS_no. This is to +// cause a link-time error if someone tries to define 2 flags with +// names like "logging" and "nologging". We do this because a bool +// flag FLAG can be set from the command line to true with a "-FLAG" +// argument, and to false with a "-noFLAG" argument, and so this can +// potentially avert confusion. +// +// We also put flags into their own namespace. It is purposefully +// named in an opaque way that people should have trouble typing +// directly. The idea is that DEFINE puts the flag in the weird +// namespace, and DECLARE imports the flag from there into the current +// namespace. The net result is to force people to use DECLARE to get +// access to a flag, rather than saying "extern GFLAGS_DLL_DECL bool FLAGS_whatever;" +// or some such instead. We want this so we can put extra +// functionality (like sanity-checking) in DECLARE if we want, and +// make sure it is picked up everywhere. +// +// We also put the type of the variable in the namespace, so that +// people can't DECLARE_int32 something that they DEFINE_bool'd +// elsewhere. + +class GFLAGS_DLL_DECL FlagRegisterer { + public: + // We instantiate this template ctor for all supported types, + // so it is possible to place implementation of the FlagRegisterer ctor in + // .cc file. + // Calling this constructor with unsupported type will produce linker error. + template + FlagRegisterer(const char* name, + const char* help, const char* filename, + FlagType* current_storage, FlagType* defvalue_storage); +}; + +// Force compiler to not generate code for the given template specialization. +#if defined(_MSC_VER) && _MSC_VER < 1800 // Visual Studio 2013 version 12.0 + #define GFLAGS_DECLARE_FLAG_REGISTERER_CTOR(type) +#else + #define GFLAGS_DECLARE_FLAG_REGISTERER_CTOR(type) \ + extern template GFLAGS_DLL_DECL FlagRegisterer::FlagRegisterer( \ + const char* name, const char* help, const char* filename, \ + type* current_storage, type* defvalue_storage) +#endif + +// Do this for all supported flag types. +GFLAGS_DECLARE_FLAG_REGISTERER_CTOR(bool); +GFLAGS_DECLARE_FLAG_REGISTERER_CTOR(int32); +GFLAGS_DECLARE_FLAG_REGISTERER_CTOR(uint32); +GFLAGS_DECLARE_FLAG_REGISTERER_CTOR(int64); +GFLAGS_DECLARE_FLAG_REGISTERER_CTOR(uint64); +GFLAGS_DECLARE_FLAG_REGISTERER_CTOR(double); +GFLAGS_DECLARE_FLAG_REGISTERER_CTOR(std::string); + +#undef GFLAGS_DECLARE_FLAG_REGISTERER_CTOR + +// If your application #defines STRIP_FLAG_HELP to a non-zero value +// before #including this file, we remove the help message from the +// binary file. This can reduce the size of the resulting binary +// somewhat, and may also be useful for security reasons. + +extern GFLAGS_DLL_DECL const char kStrippedFlagHelp[]; + + +} // namespace GFLAGS_NAMESPACE + + +#ifndef SWIG // In swig, ignore the main flag declarations + +#if defined(STRIP_FLAG_HELP) && STRIP_FLAG_HELP > 0 +// Need this construct to avoid the 'defined but not used' warning. +#define MAYBE_STRIPPED_HELP(txt) \ + (false ? (txt) : GFLAGS_NAMESPACE::kStrippedFlagHelp) +#else +#define MAYBE_STRIPPED_HELP(txt) txt +#endif + +// Each command-line flag has two variables associated with it: one +// with the current value, and one with the default value. However, +// we have a third variable, which is where value is assigned; it's a +// constant. This guarantees that FLAG_##value is initialized at +// static initialization time (e.g. before program-start) rather than +// than global construction time (which is after program-start but +// before main), at least when 'value' is a compile-time constant. We +// use a small trick for the "default value" variable, and call it +// FLAGS_no. This serves the second purpose of assuring a +// compile error if someone tries to define a flag named no +// which is illegal (--foo and --nofoo both affect the "foo" flag). +#define DEFINE_VARIABLE(type, shorttype, name, value, help) \ + namespace fL##shorttype { \ + static const type FLAGS_nono##name = value; \ + /* We always want to export defined variables, dll or no */ \ + GFLAGS_DLL_DEFINE_FLAG type FLAGS_##name = FLAGS_nono##name; \ + static type FLAGS_no##name = FLAGS_nono##name; \ + static GFLAGS_NAMESPACE::FlagRegisterer o_##name( \ + #name, MAYBE_STRIPPED_HELP(help), __FILE__, \ + &FLAGS_##name, &FLAGS_no##name); \ + } \ + using fL##shorttype::FLAGS_##name + +// For DEFINE_bool, we want to do the extra check that the passed-in +// value is actually a bool, and not a string or something that can be +// coerced to a bool. These declarations (no definition needed!) will +// help us do that, and never evaluate From, which is important. +// We'll use 'sizeof(IsBool(val))' to distinguish. This code requires +// that the compiler have different sizes for bool & double. Since +// this is not guaranteed by the standard, we check it with a +// COMPILE_ASSERT. +namespace fLB { +struct CompileAssert {}; +typedef CompileAssert expected_sizeof_double_neq_sizeof_bool[ + (sizeof(double) != sizeof(bool)) ? 1 : -1]; +template double GFLAGS_DLL_DECL IsBoolFlag(const From& from); +GFLAGS_DLL_DECL bool IsBoolFlag(bool from); +} // namespace fLB + +// Here are the actual DEFINE_*-macros. The respective DECLARE_*-macros +// are in a separate include, gflags_declare.h, for reducing +// the physical transitive size for DECLARE use. +#define DEFINE_bool(name, val, txt) \ + namespace fLB { \ + typedef ::fLB::CompileAssert FLAG_##name##_value_is_not_a_bool[ \ + (sizeof(::fLB::IsBoolFlag(val)) != sizeof(double))? 1: -1]; \ + } \ + DEFINE_VARIABLE(bool, B, name, val, txt) + +#define DEFINE_int32(name, val, txt) \ + DEFINE_VARIABLE(GFLAGS_NAMESPACE::int32, I, \ + name, val, txt) + +#define DEFINE_uint32(name,val, txt) \ + DEFINE_VARIABLE(GFLAGS_NAMESPACE::uint32, U, \ + name, val, txt) + +#define DEFINE_int64(name, val, txt) \ + DEFINE_VARIABLE(GFLAGS_NAMESPACE::int64, I64, \ + name, val, txt) + +#define DEFINE_uint64(name,val, txt) \ + DEFINE_VARIABLE(GFLAGS_NAMESPACE::uint64, U64, \ + name, val, txt) + +#define DEFINE_double(name, val, txt) \ + DEFINE_VARIABLE(double, D, name, val, txt) + +// Strings are trickier, because they're not a POD, so we can't +// construct them at static-initialization time (instead they get +// constructed at global-constructor time, which is much later). To +// try to avoid crashes in that case, we use a char buffer to store +// the string, which we can static-initialize, and then placement-new +// into it later. It's not perfect, but the best we can do. + +namespace fLS { + +inline clstring* dont_pass0toDEFINE_string(char *stringspot, + const char *value) { + return new(stringspot) clstring(value); +} +inline clstring* dont_pass0toDEFINE_string(char *stringspot, + const clstring &value) { + return new(stringspot) clstring(value); +} +inline clstring* dont_pass0toDEFINE_string(char *stringspot, + int value); + +// Auxiliary class used to explicitly call destructor of string objects +// allocated using placement new during static program deinitialization. +// The destructor MUST be an inline function such that the explicit +// destruction occurs in the same compilation unit as the placement new. +class StringFlagDestructor { + void *current_storage_; + void *defvalue_storage_; + +public: + + StringFlagDestructor(void *current, void *defvalue) + : current_storage_(current), defvalue_storage_(defvalue) {} + + ~StringFlagDestructor() { + reinterpret_cast(current_storage_ )->~clstring(); + reinterpret_cast(defvalue_storage_)->~clstring(); + } +}; + +} // namespace fLS + +// We need to define a var named FLAGS_no##name so people don't define +// --string and --nostring. And we need a temporary place to put val +// so we don't have to evaluate it twice. Two great needs that go +// great together! +// The weird 'using' + 'extern' inside the fLS namespace is to work around +// an unknown compiler bug/issue with the gcc 4.2.1 on SUSE 10. See +// http://code.google.com/p/google-gflags/issues/detail?id=20 +#define DEFINE_string(name, val, txt) \ + namespace fLS { \ + using ::fLS::clstring; \ + using ::fLS::StringFlagDestructor; \ + static union { void* align; char s[sizeof(clstring)]; } s_##name[2]; \ + clstring* const FLAGS_no##name = ::fLS:: \ + dont_pass0toDEFINE_string(s_##name[0].s, \ + val); \ + static GFLAGS_NAMESPACE::FlagRegisterer o_##name( \ + #name, MAYBE_STRIPPED_HELP(txt), __FILE__, \ + FLAGS_no##name, new (s_##name[1].s) clstring(*FLAGS_no##name)); \ + static StringFlagDestructor d_##name(s_##name[0].s, s_##name[1].s); \ + extern GFLAGS_DLL_DEFINE_FLAG clstring& FLAGS_##name; \ + using fLS::FLAGS_##name; \ + clstring& FLAGS_##name = *FLAGS_no##name; \ + } \ + using fLS::FLAGS_##name + +#endif // SWIG + + +@INCLUDE_GFLAGS_NS_H@ + + +#endif // GFLAGS_GFLAGS_H_ diff --git a/third_party/gflags/src/gflags_completions.cc b/third_party/gflags/src/gflags_completions.cc new file mode 100644 index 0000000..c53a128 --- /dev/null +++ b/third_party/gflags/src/gflags_completions.cc @@ -0,0 +1,772 @@ +// Copyright (c) 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// --- + +// Bash-style command line flag completion for C++ binaries +// +// This module implements bash-style completions. It achieves this +// goal in the following broad chunks: +// +// 1) Take a to-be-completed word, and examine it for search hints +// 2) Identify all potentially matching flags +// 2a) If there are no matching flags, do nothing. +// 2b) If all matching flags share a common prefix longer than the +// completion word, output just that matching prefix +// 3) Categorize those flags to produce a rough ordering of relevence. +// 4) Potentially trim the set of flags returned to a smaller number +// that bash is happier with +// 5) Output the matching flags in groups ordered by relevence. +// 5a) Force bash to place most-relevent groups at the top of the list +// 5b) Trim most flag's descriptions to fit on a single terminal line + +#include +#include +#include // for strlen + +#include +#include +#include +#include + +#include "config.h" +#include "gflags/gflags.h" +#include "gflags/gflags_completions.h" +#include "util.h" + +using std::set; +using std::string; +using std::vector; + + +DEFINE_string(tab_completion_word, "", + "If non-empty, HandleCommandLineCompletions() will hijack the " + "process and attempt to do bash-style command line flag " + "completion on this value."); +DEFINE_int32(tab_completion_columns, 80, + "Number of columns to use in output for tab completion"); + + +namespace GFLAGS_NAMESPACE { + + +namespace { +// Function prototypes and Type forward declarations. Code may be +// more easily understood if it is roughly ordered according to +// control flow, rather than by C's "declare before use" ordering +struct CompletionOptions; +struct NotableFlags; + +// The entry point if flag completion is to be used. +static void PrintFlagCompletionInfo(void); + + +// 1) Examine search word +static void CanonicalizeCursorWordAndSearchOptions( + const string &cursor_word, + string *canonical_search_token, + CompletionOptions *options); + +static bool RemoveTrailingChar(string *str, char c); + + +// 2) Find all matches +static void FindMatchingFlags( + const vector &all_flags, + const CompletionOptions &options, + const string &match_token, + set *all_matches, + string *longest_common_prefix); + +static bool DoesSingleFlagMatch( + const CommandLineFlagInfo &flag, + const CompletionOptions &options, + const string &match_token); + + +// 3) Categorize matches +static void CategorizeAllMatchingFlags( + const set &all_matches, + const string &search_token, + const string &module, + const string &package_dir, + NotableFlags *notable_flags); + +static void TryFindModuleAndPackageDir( + const vector &all_flags, + string *module, + string *package_dir); + + +// 4) Decide which flags to use +static void FinalizeCompletionOutput( + const set &matching_flags, + CompletionOptions *options, + NotableFlags *notable_flags, + vector *completions); + +static void RetrieveUnusedFlags( + const set &matching_flags, + const NotableFlags ¬able_flags, + set *unused_flags); + + +// 5) Output matches +static void OutputSingleGroupWithLimit( + const set &group, + const string &line_indentation, + const string &header, + const string &footer, + bool long_output_format, + int *remaining_line_limit, + size_t *completion_elements_added, + vector *completions); + +// (helpers for #5) +static string GetShortFlagLine( + const string &line_indentation, + const CommandLineFlagInfo &info); + +static string GetLongFlagLine( + const string &line_indentation, + const CommandLineFlagInfo &info); + + +// +// Useful types + +// Try to deduce the intentions behind this completion attempt. Return the +// canonical search term in 'canonical_search_token'. Binary search options +// are returned in the various booleans, which should all have intuitive +// semantics, possibly except: +// - return_all_matching_flags: Generally, we'll trim the number of +// returned candidates to some small number, showing those that are +// most likely to be useful first. If this is set, however, the user +// really does want us to return every single flag as an option. +// - force_no_update: Any time we output lines, all of which share a +// common prefix, bash will 'helpfully' not even bother to show the +// output, instead changing the current word to be that common prefix. +// If it's clear this shouldn't happen, we'll set this boolean +struct CompletionOptions { + bool flag_name_substring_search; + bool flag_location_substring_search; + bool flag_description_substring_search; + bool return_all_matching_flags; + bool force_no_update; + CompletionOptions(): flag_name_substring_search(false), + flag_location_substring_search(false), + flag_description_substring_search(false), + return_all_matching_flags(false), + force_no_update(false) { } +}; + +// Notable flags are flags that are special or preferred for some +// reason. For example, flags that are defined in the binary's module +// are expected to be much more relevent than flags defined in some +// other random location. These sets are specified roughly in precedence +// order. Once a flag is placed in one of these 'higher' sets, it won't +// be placed in any of the 'lower' sets. +struct NotableFlags { + typedef set FlagSet; + FlagSet perfect_match_flag; + FlagSet module_flags; // Found in module file + FlagSet package_flags; // Found in same directory as module file + FlagSet most_common_flags; // One of the XXX most commonly supplied flags + FlagSet subpackage_flags; // Found in subdirectories of package +}; + + +// +// Tab completion implementation - entry point +static void PrintFlagCompletionInfo(void) { + string cursor_word = FLAGS_tab_completion_word; + string canonical_token; + CompletionOptions options = CompletionOptions(); + CanonicalizeCursorWordAndSearchOptions( + cursor_word, + &canonical_token, + &options); + + DVLOG(1) << "Identified canonical_token: '" << canonical_token << "'"; + + vector all_flags; + set matching_flags; + GetAllFlags(&all_flags); + DVLOG(2) << "Found " << all_flags.size() << " flags overall"; + + string longest_common_prefix; + FindMatchingFlags( + all_flags, + options, + canonical_token, + &matching_flags, + &longest_common_prefix); + DVLOG(1) << "Identified " << matching_flags.size() << " matching flags"; + DVLOG(1) << "Identified " << longest_common_prefix + << " as longest common prefix."; + if (longest_common_prefix.size() > canonical_token.size()) { + // There's actually a shared common prefix to all matching flags, + // so may as well output that and quit quickly. + DVLOG(1) << "The common prefix '" << longest_common_prefix + << "' was longer than the token '" << canonical_token + << "'. Returning just this prefix for completion."; + fprintf(stdout, "--%s", longest_common_prefix.c_str()); + return; + } + if (matching_flags.empty()) { + VLOG(1) << "There were no matching flags, returning nothing."; + return; + } + + string module; + string package_dir; + TryFindModuleAndPackageDir(all_flags, &module, &package_dir); + DVLOG(1) << "Identified module: '" << module << "'"; + DVLOG(1) << "Identified package_dir: '" << package_dir << "'"; + + NotableFlags notable_flags; + CategorizeAllMatchingFlags( + matching_flags, + canonical_token, + module, + package_dir, + ¬able_flags); + DVLOG(2) << "Categorized matching flags:"; + DVLOG(2) << " perfect_match: " << notable_flags.perfect_match_flag.size(); + DVLOG(2) << " module: " << notable_flags.module_flags.size(); + DVLOG(2) << " package: " << notable_flags.package_flags.size(); + DVLOG(2) << " most common: " << notable_flags.most_common_flags.size(); + DVLOG(2) << " subpackage: " << notable_flags.subpackage_flags.size(); + + vector completions; + FinalizeCompletionOutput( + matching_flags, + &options, + ¬able_flags, + &completions); + + if (options.force_no_update) + completions.push_back("~"); + + DVLOG(1) << "Finalized with " << completions.size() + << " chosen completions"; + + for (vector::const_iterator it = completions.begin(); + it != completions.end(); + ++it) { + DVLOG(9) << " Completion entry: '" << *it << "'"; + fprintf(stdout, "%s\n", it->c_str()); + } +} + + +// 1) Examine search word (and helper method) +static void CanonicalizeCursorWordAndSearchOptions( + const string &cursor_word, + string *canonical_search_token, + CompletionOptions *options) { + *canonical_search_token = cursor_word; + if (canonical_search_token->empty()) return; + + // Get rid of leading quotes and dashes in the search term + if ((*canonical_search_token)[0] == '"') + *canonical_search_token = canonical_search_token->substr(1); + while ((*canonical_search_token)[0] == '-') + *canonical_search_token = canonical_search_token->substr(1); + + options->flag_name_substring_search = false; + options->flag_location_substring_search = false; + options->flag_description_substring_search = false; + options->return_all_matching_flags = false; + options->force_no_update = false; + + // Look for all search options we can deduce now. Do this by walking + // backwards through the term, looking for up to three '?' and up to + // one '+' as suffixed characters. Consume them if found, and remove + // them from the canonical search token. + int found_question_marks = 0; + int found_plusses = 0; + while (true) { + if (found_question_marks < 3 && + RemoveTrailingChar(canonical_search_token, '?')) { + ++found_question_marks; + continue; + } + if (found_plusses < 1 && + RemoveTrailingChar(canonical_search_token, '+')) { + ++found_plusses; + continue; + } + break; + } + + switch (found_question_marks) { // all fallthroughs + case 3: options->flag_description_substring_search = true; + case 2: options->flag_location_substring_search = true; + case 1: options->flag_name_substring_search = true; + }; + + options->return_all_matching_flags = (found_plusses > 0); +} + +// Returns true if a char was removed +static bool RemoveTrailingChar(string *str, char c) { + if (str->empty()) return false; + if ((*str)[str->size() - 1] == c) { + *str = str->substr(0, str->size() - 1); + return true; + } + return false; +} + + +// 2) Find all matches (and helper methods) +static void FindMatchingFlags( + const vector &all_flags, + const CompletionOptions &options, + const string &match_token, + set *all_matches, + string *longest_common_prefix) { + all_matches->clear(); + bool first_match = true; + for (vector::const_iterator it = all_flags.begin(); + it != all_flags.end(); + ++it) { + if (DoesSingleFlagMatch(*it, options, match_token)) { + all_matches->insert(&*it); + if (first_match) { + first_match = false; + *longest_common_prefix = it->name; + } else { + if (longest_common_prefix->empty() || it->name.empty()) { + longest_common_prefix->clear(); + continue; + } + string::size_type pos = 0; + while (pos < longest_common_prefix->size() && + pos < it->name.size() && + (*longest_common_prefix)[pos] == it->name[pos]) + ++pos; + longest_common_prefix->erase(pos); + } + } + } +} + +// Given the set of all flags, the parsed match options, and the +// canonical search token, produce the set of all candidate matching +// flags for subsequent analysis or filtering. +static bool DoesSingleFlagMatch( + const CommandLineFlagInfo &flag, + const CompletionOptions &options, + const string &match_token) { + // Is there a prefix match? + string::size_type pos = flag.name.find(match_token); + if (pos == 0) return true; + + // Is there a substring match if we want it? + if (options.flag_name_substring_search && + pos != string::npos) + return true; + + // Is there a location match if we want it? + if (options.flag_location_substring_search && + flag.filename.find(match_token) != string::npos) + return true; + + // TODO(user): All searches should probably be case-insensitive + // (especially this one...) + if (options.flag_description_substring_search && + flag.description.find(match_token) != string::npos) + return true; + + return false; +} + +// 3) Categorize matches (and helper method) + +// Given a set of matching flags, categorize them by +// likely relevence to this specific binary +static void CategorizeAllMatchingFlags( + const set &all_matches, + const string &search_token, + const string &module, // empty if we couldn't find any + const string &package_dir, // empty if we couldn't find any + NotableFlags *notable_flags) { + notable_flags->perfect_match_flag.clear(); + notable_flags->module_flags.clear(); + notable_flags->package_flags.clear(); + notable_flags->most_common_flags.clear(); + notable_flags->subpackage_flags.clear(); + + for (set::const_iterator it = + all_matches.begin(); + it != all_matches.end(); + ++it) { + DVLOG(2) << "Examining match '" << (*it)->name << "'"; + DVLOG(7) << " filename: '" << (*it)->filename << "'"; + string::size_type pos = string::npos; + if (!package_dir.empty()) + pos = (*it)->filename.find(package_dir); + string::size_type slash = string::npos; + if (pos != string::npos) // candidate for package or subpackage match + slash = (*it)->filename.find( + PATH_SEPARATOR, + pos + package_dir.size() + 1); + + if ((*it)->name == search_token) { + // Exact match on some flag's name + notable_flags->perfect_match_flag.insert(*it); + DVLOG(3) << "Result: perfect match"; + } else if (!module.empty() && (*it)->filename == module) { + // Exact match on module filename + notable_flags->module_flags.insert(*it); + DVLOG(3) << "Result: module match"; + } else if (!package_dir.empty() && + pos != string::npos && slash == string::npos) { + // In the package, since there was no slash after the package portion + notable_flags->package_flags.insert(*it); + DVLOG(3) << "Result: package match"; + } else if (false) { + // In the list of the XXX most commonly supplied flags overall + // TODO(user): Compile this list. + DVLOG(3) << "Result: most-common match"; + } else if (!package_dir.empty() && + pos != string::npos && slash != string::npos) { + // In a subdirectory of the package + notable_flags->subpackage_flags.insert(*it); + DVLOG(3) << "Result: subpackage match"; + } + + DVLOG(3) << "Result: not special match"; + } +} + +static void PushNameWithSuffix(vector* suffixes, const char* suffix) { + suffixes->push_back( + StringPrintf("/%s%s", ProgramInvocationShortName(), suffix)); +} + +static void TryFindModuleAndPackageDir( + const vector &all_flags, + string *module, + string *package_dir) { + module->clear(); + package_dir->clear(); + + vector suffixes; + // TODO(user): There's some inherant ambiguity here - multiple directories + // could share the same trailing folder and file structure (and even worse, + // same file names), causing us to be unsure as to which of the two is the + // actual package for this binary. In this case, we'll arbitrarily choose. + PushNameWithSuffix(&suffixes, "."); + PushNameWithSuffix(&suffixes, "-main."); + PushNameWithSuffix(&suffixes, "_main."); + // These four are new but probably merited? + PushNameWithSuffix(&suffixes, "-test."); + PushNameWithSuffix(&suffixes, "_test."); + PushNameWithSuffix(&suffixes, "-unittest."); + PushNameWithSuffix(&suffixes, "_unittest."); + + for (vector::const_iterator it = all_flags.begin(); + it != all_flags.end(); + ++it) { + for (vector::const_iterator suffix = suffixes.begin(); + suffix != suffixes.end(); + ++suffix) { + // TODO(user): Make sure the match is near the end of the string + if (it->filename.find(*suffix) != string::npos) { + *module = it->filename; + string::size_type sep = it->filename.rfind(PATH_SEPARATOR); + *package_dir = it->filename.substr(0, (sep == string::npos) ? 0 : sep); + return; + } + } + } +} + +// Can't specialize template type on a locally defined type. Silly C++... +struct DisplayInfoGroup { + const char* header; + const char* footer; + set *group; + + int SizeInLines() const { + int size_in_lines = static_cast(group->size()) + 1; + if (strlen(header) > 0) { + size_in_lines++; + } + if (strlen(footer) > 0) { + size_in_lines++; + } + return size_in_lines; + } +}; + +// 4) Finalize and trim output flag set +static void FinalizeCompletionOutput( + const set &matching_flags, + CompletionOptions *options, + NotableFlags *notable_flags, + vector *completions) { + + // We want to output lines in groups. Each group needs to be indented + // the same to keep its lines together. Unless otherwise required, + // only 99 lines should be output to prevent bash from harassing the + // user. + + // First, figure out which output groups we'll actually use. For each + // nonempty group, there will be ~3 lines of header & footer, plus all + // output lines themselves. + int max_desired_lines = // "999999 flags should be enough for anyone. -dave" + (options->return_all_matching_flags ? 999999 : 98); + int lines_so_far = 0; + + vector output_groups; + bool perfect_match_found = false; + if (!notable_flags->perfect_match_flag.empty()) { + perfect_match_found = true; + DisplayInfoGroup group = + { "", + "==========", + ¬able_flags->perfect_match_flag }; + lines_so_far += group.SizeInLines(); + output_groups.push_back(group); + } + if (lines_so_far < max_desired_lines && + !notable_flags->module_flags.empty()) { + DisplayInfoGroup group = { + "-* Matching module flags *-", + "===========================", + ¬able_flags->module_flags }; + lines_so_far += group.SizeInLines(); + output_groups.push_back(group); + } + if (lines_so_far < max_desired_lines && + !notable_flags->package_flags.empty()) { + DisplayInfoGroup group = { + "-* Matching package flags *-", + "============================", + ¬able_flags->package_flags }; + lines_so_far += group.SizeInLines(); + output_groups.push_back(group); + } + if (lines_so_far < max_desired_lines && + !notable_flags->most_common_flags.empty()) { + DisplayInfoGroup group = { + "-* Commonly used flags *-", + "=========================", + ¬able_flags->most_common_flags }; + lines_so_far += group.SizeInLines(); + output_groups.push_back(group); + } + if (lines_so_far < max_desired_lines && + !notable_flags->subpackage_flags.empty()) { + DisplayInfoGroup group = { + "-* Matching sub-package flags *-", + "================================", + ¬able_flags->subpackage_flags }; + lines_so_far += group.SizeInLines(); + output_groups.push_back(group); + } + + set obscure_flags; // flags not notable + if (lines_so_far < max_desired_lines) { + RetrieveUnusedFlags(matching_flags, *notable_flags, &obscure_flags); + if (!obscure_flags.empty()) { + DisplayInfoGroup group = { + "-* Other flags *-", + "", + &obscure_flags }; + lines_so_far += group.SizeInLines(); + output_groups.push_back(group); + } + } + + // Second, go through each of the chosen output groups and output + // as many of those flags as we can, while remaining below our limit + int remaining_lines = max_desired_lines; + size_t completions_output = 0; + int indent = static_cast(output_groups.size()) - 1; + for (vector::const_iterator it = + output_groups.begin(); + it != output_groups.end(); + ++it, --indent) { + OutputSingleGroupWithLimit( + *it->group, // group + string(indent, ' '), // line indentation + string(it->header), // header + string(it->footer), // footer + perfect_match_found, // long format + &remaining_lines, // line limit - reduces this by number printed + &completions_output, // completions (not lines) added + completions); // produced completions + perfect_match_found = false; + } + + if (completions_output != matching_flags.size()) { + options->force_no_update = false; + completions->push_back("~ (Remaining flags hidden) ~"); + } else { + options->force_no_update = true; + } +} + +static void RetrieveUnusedFlags( + const set &matching_flags, + const NotableFlags ¬able_flags, + set *unused_flags) { + // Remove from 'matching_flags' set all members of the sets of + // flags we've already printed (specifically, those in notable_flags) + for (set::const_iterator it = + matching_flags.begin(); + it != matching_flags.end(); + ++it) { + if (notable_flags.perfect_match_flag.count(*it) || + notable_flags.module_flags.count(*it) || + notable_flags.package_flags.count(*it) || + notable_flags.most_common_flags.count(*it) || + notable_flags.subpackage_flags.count(*it)) + continue; + unused_flags->insert(*it); + } +} + +// 5) Output matches (and helper methods) + +static void OutputSingleGroupWithLimit( + const set &group, + const string &line_indentation, + const string &header, + const string &footer, + bool long_output_format, + int *remaining_line_limit, + size_t *completion_elements_output, + vector *completions) { + if (group.empty()) return; + if (!header.empty()) { + if (*remaining_line_limit < 2) return; + *remaining_line_limit -= 2; + completions->push_back(line_indentation + header); + completions->push_back(line_indentation + string(header.size(), '-')); + } + for (set::const_iterator it = group.begin(); + it != group.end() && *remaining_line_limit > 0; + ++it) { + --*remaining_line_limit; + ++*completion_elements_output; + completions->push_back( + (long_output_format + ? GetLongFlagLine(line_indentation, **it) + : GetShortFlagLine(line_indentation, **it))); + } + if (!footer.empty()) { + if (*remaining_line_limit < 1) return; + --*remaining_line_limit; + completions->push_back(line_indentation + footer); + } +} + +static string GetShortFlagLine( + const string &line_indentation, + const CommandLineFlagInfo &info) { + string prefix; + bool is_string = (info.type == "string"); + SStringPrintf(&prefix, "%s--%s [%s%s%s] ", + line_indentation.c_str(), + info.name.c_str(), + (is_string ? "'" : ""), + info.default_value.c_str(), + (is_string ? "'" : "")); + int remainder = + FLAGS_tab_completion_columns - static_cast(prefix.size()); + string suffix; + if (remainder > 0) + suffix = + (static_cast(info.description.size()) > remainder ? + (info.description.substr(0, remainder - 3) + "...").c_str() : + info.description.c_str()); + return prefix + suffix; +} + +static string GetLongFlagLine( + const string &line_indentation, + const CommandLineFlagInfo &info) { + + string output = DescribeOneFlag(info); + + // Replace '-' with '--', and remove trailing newline before appending + // the module definition location. + string old_flagname = "-" + info.name; + output.replace( + output.find(old_flagname), + old_flagname.size(), + "-" + old_flagname); + // Stick a newline and indentation in front of the type and default + // portions of DescribeOneFlag()s description + static const char kNewlineWithIndent[] = "\n "; + output.replace(output.find(" type:"), 1, string(kNewlineWithIndent)); + output.replace(output.find(" default:"), 1, string(kNewlineWithIndent)); + output = StringPrintf("%s Details for '--%s':\n" + "%s defined: %s", + line_indentation.c_str(), + info.name.c_str(), + output.c_str(), + info.filename.c_str()); + + // Eliminate any doubled newlines that crept in. Specifically, if + // DescribeOneFlag() decided to break the line just before "type" + // or "default", we don't want to introduce an extra blank line + static const string line_of_spaces(FLAGS_tab_completion_columns, ' '); + static const char kDoubledNewlines[] = "\n \n"; + for (string::size_type newlines = output.find(kDoubledNewlines); + newlines != string::npos; + newlines = output.find(kDoubledNewlines)) + // Replace each 'doubled newline' with a single newline + output.replace(newlines, sizeof(kDoubledNewlines) - 1, string("\n")); + + for (string::size_type newline = output.find('\n'); + newline != string::npos; + newline = output.find('\n')) { + int newline_pos = static_cast(newline) % FLAGS_tab_completion_columns; + int missing_spaces = FLAGS_tab_completion_columns - newline_pos; + output.replace(newline, 1, line_of_spaces, 1, missing_spaces); + } + return output; +} +} // anonymous + +void HandleCommandLineCompletions(void) { + if (FLAGS_tab_completion_word.empty()) return; + PrintFlagCompletionInfo(); + gflags_exitfunc(0); +} + + +} // namespace GFLAGS_NAMESPACE diff --git a/third_party/gflags/src/gflags_completions.h.in b/third_party/gflags/src/gflags_completions.h.in new file mode 100644 index 0000000..b27e5fd --- /dev/null +++ b/third_party/gflags/src/gflags_completions.h.in @@ -0,0 +1,121 @@ +// Copyright (c) 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// --- + +// +// Implement helpful bash-style command line flag completions +// +// ** Functional API: +// HandleCommandLineCompletions() should be called early during +// program startup, but after command line flag code has been +// initialized, such as the beginning of HandleCommandLineHelpFlags(). +// It checks the value of the flag --tab_completion_word. If this +// flag is empty, nothing happens here. If it contains a string, +// however, then HandleCommandLineCompletions() will hijack the +// process, attempting to identify the intention behind this +// completion. Regardless of the outcome of this deduction, the +// process will be terminated, similar to --helpshort flag +// handling. +// +// ** Overview of Bash completions: +// Bash can be told to programatically determine completions for the +// current 'cursor word'. It does this by (in this case) invoking a +// command with some additional arguments identifying the command +// being executed, the word being completed, and the previous word +// (if any). Bash then expects a sequence of output lines to be +// printed to stdout. If these lines all contain a common prefix +// longer than the cursor word, bash will replace the cursor word +// with that common prefix, and display nothing. If there isn't such +// a common prefix, bash will display the lines in pages using 'more'. +// +// ** Strategy taken for command line completions: +// If we can deduce either the exact flag intended, or a common flag +// prefix, we'll output exactly that. Otherwise, if information +// must be displayed to the user, we'll take the opportunity to add +// some helpful information beyond just the flag name (specifically, +// we'll include the default flag value and as much of the flag's +// description as can fit on a single terminal line width, as specified +// by the flag --tab_completion_columns). Furthermore, we'll try to +// make bash order the output such that the most useful or relevent +// flags are the most likely to be shown at the top. +// +// ** Additional features: +// To assist in finding that one really useful flag, substring matching +// was implemented. Before pressing a to get completion for the +// current word, you can append one or more '?' to the flag to do +// substring matching. Here's the semantics: +// --foo Show me all flags with names prefixed by 'foo' +// --foo? Show me all flags with 'foo' somewhere in the name +// --foo?? Same as prior case, but also search in module +// definition path for 'foo' +// --foo??? Same as prior case, but also search in flag +// descriptions for 'foo' +// Finally, we'll trim the output to a relatively small number of +// flags to keep bash quiet about the verbosity of output. If one +// really wanted to see all possible matches, appending a '+' to the +// search word will force the exhaustive list of matches to be printed. +// +// ** How to have bash accept completions from a binary: +// Bash requires that it be informed about each command that programmatic +// completion should be enabled for. Example addition to a .bashrc +// file would be (your path to gflags_completions.sh file may differ): + +/* +$ complete -o bashdefault -o default -o nospace -C \ + '/home/build/eng/bash/bash_completions.sh --tab_completion_columns $COLUMNS' \ + time env binary_name another_binary [...] +*/ + +// This would allow the following to work: +// $ /path/to/binary_name --vmodule +// Or: +// $ ./bin/path/another_binary --gfs_u +// (etc) +// +// Sadly, it appears that bash gives no easy way to force this behavior for +// all commands. That's where the "time" in the above example comes in. +// If you haven't specifically added a command to the list of completion +// supported commands, you can still get completions by prefixing the +// entire command with "env". +// $ env /some/brand/new/binary --vmod +// Assuming that "binary" is a newly compiled binary, this should still +// produce the expected completion output. + + +#ifndef GFLAGS_COMPLETIONS_H_ +#define GFLAGS_COMPLETIONS_H_ + +namespace @GFLAGS_NAMESPACE@ { + +extern void HandleCommandLineCompletions(void); + +} + +#endif // GFLAGS_COMPLETIONS_H_ diff --git a/third_party/gflags/src/gflags_completions.sh b/third_party/gflags/src/gflags_completions.sh new file mode 100755 index 0000000..c5fb7e6 --- /dev/null +++ b/third_party/gflags/src/gflags_completions.sh @@ -0,0 +1,117 @@ +#!/bin/bash + +# Copyright (c) 2008, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# --- +# Author: Dave Nicponski +# +# This script is invoked by bash in response to a matching compspec. When +# this happens, bash calls this script using the command shown in the -C +# block of the complete entry, but also appends 3 arguments. They are: +# - The command being used for completion +# - The word being completed +# - The word preceding the completion word. +# +# Here's an example of how you might use this script: +# $ complete -o bashdefault -o default -o nospace -C \ +# '/usr/local/bin/gflags_completions.sh --tab_completion_columns $COLUMNS' \ +# time env binary_name another_binary [...] + +# completion_word_index gets the index of the (N-1)th argument for +# this command line. completion_word gets the actual argument from +# this command line at the (N-1)th position +completion_word_index="$(($# - 1))" +completion_word="${!completion_word_index}" + +# TODO(user): Replace this once gflags_completions.cc has +# a bool parameter indicating unambiguously to hijack the process for +# completion purposes. +if [ -z "$completion_word" ]; then + # Until an empty value for the completion word stops being misunderstood + # by binaries, don't actually execute the binary or the process + # won't be hijacked! + exit 0 +fi + +# binary_index gets the index of the command being completed (which bash +# places in the (N-2)nd position. binary gets the actual command from +# this command line at that (N-2)nd position +binary_index="$(($# - 2))" +binary="${!binary_index}" + +# For completions to be universal, we may have setup the compspec to +# trigger on 'harmless pass-through' commands, like 'time' or 'env'. +# If the command being completed is one of those two, we'll need to +# identify the actual command being executed. To do this, we need +# the actual command line that the was pressed on. Bash helpfully +# places this in the $COMP_LINE variable. +if [ "$binary" == "time" ] || [ "$binary" == "env" ]; then + # we'll assume that the first 'argument' is actually the + # binary + + + # TODO(user): This is not perfect - the 'env' command, for instance, + # is allowed to have options between the 'env' and 'the command to + # be executed'. For example, consider: + # $ env FOO="bar" bin/do_something --help + # In this case, we'll mistake the FOO="bar" portion as the binary. + # Perhaps we should continuing consuming leading words until we + # either run out of words, or find a word that is a valid file + # marked as executable. I can't think of any reason this wouldn't + # work. + + # Break up the 'original command line' (not this script's command line, + # rather the one the was pressed on) and find the second word. + parts=( ${COMP_LINE} ) + binary=${parts[1]} +fi + +# Build the command line to use for completion. Basically it involves +# passing through all the arguments given to this script (except the 3 +# that bash added), and appending a '--tab_completion_word "WORD"' to +# the arguments. +params="" +for ((i=1; i<=$(($# - 3)); ++i)); do + params="$params \"${!i}\""; +done +params="$params --tab_completion_word \"$completion_word\"" + +# TODO(user): Perhaps stash the output in a temporary file somewhere +# in /tmp, and only cat it to stdout if the command returned a success +# code, to prevent false positives + +# If we think we have a reasonable command to execute, then execute it +# and hope for the best. +candidate=$(type -p "$binary") +if [ ! -z "$candidate" ]; then + eval "$candidate 2>/dev/null $params" +elif [ -f "$binary" ] && [ -x "$binary" ]; then + eval "$binary 2>/dev/null $params" +fi diff --git a/third_party/gflags/src/gflags_declare.h.in b/third_party/gflags/src/gflags_declare.h.in new file mode 100644 index 0000000..ab7bd24 --- /dev/null +++ b/third_party/gflags/src/gflags_declare.h.in @@ -0,0 +1,156 @@ +// Copyright (c) 1999, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// --- +// +// Revamped and reorganized by Craig Silverstein +// +// This is the file that should be included by any file which declares +// command line flag. + +#ifndef GFLAGS_DECLARE_H_ +#define GFLAGS_DECLARE_H_ + + +// --------------------------------------------------------------------------- +// Namespace of gflags library symbols. +#define GFLAGS_NAMESPACE @GFLAGS_NAMESPACE@ + +// --------------------------------------------------------------------------- +// Windows DLL import/export. + +// Whether gflags library is a DLL. +// +// Set to 1 by default when the shared gflags library was built on Windows. +// Must be overwritten when this header file is used with the optionally also +// built static library instead; set by CMake's INTERFACE_COMPILE_DEFINITIONS. +#ifndef GFLAGS_IS_A_DLL +# define GFLAGS_IS_A_DLL @GFLAGS_IS_A_DLL@ +#endif + +// We always want to import the symbols of the gflags library. +#ifndef GFLAGS_DLL_DECL +# if GFLAGS_IS_A_DLL && defined(_MSC_VER) +# define GFLAGS_DLL_DECL __declspec(dllimport) +# elif defined(__GNUC__) && __GNUC__ >= 4 +# define GFLAGS_DLL_DECL __attribute__((visibility("default"))) +# else +# define GFLAGS_DLL_DECL +# endif +#endif + +// We always want to import variables declared in user code. +#ifndef GFLAGS_DLL_DECLARE_FLAG +# if GFLAGS_IS_A_DLL && defined(_MSC_VER) +# define GFLAGS_DLL_DECLARE_FLAG __declspec(dllimport) +# elif defined(__GNUC__) && __GNUC__ >= 4 +# define GFLAGS_DLL_DECLARE_FLAG __attribute__((visibility("default"))) +# else +# define GFLAGS_DLL_DECLARE_FLAG +# endif +#endif + +// --------------------------------------------------------------------------- +// Flag types +#include +#if @HAVE_STDINT_H@ +# include // the normal place uint32_t is defined +#elif @HAVE_SYS_TYPES_H@ +# include // the normal place u_int32_t is defined +#elif @HAVE_INTTYPES_H@ +# include // a third place for uint32_t or u_int32_t +#endif + +namespace GFLAGS_NAMESPACE { + +#if @GFLAGS_INTTYPES_FORMAT_C99@ // C99 +typedef int32_t int32; +typedef uint32_t uint32; +typedef int64_t int64; +typedef uint64_t uint64; +#elif @GFLAGS_INTTYPES_FORMAT_BSD@ // BSD +typedef int32_t int32; +typedef u_int32_t uint32; +typedef int64_t int64; +typedef u_int64_t uint64; +#elif @GFLAGS_INTTYPES_FORMAT_VC7@ // Windows +typedef __int32 int32; +typedef unsigned __int32 uint32; +typedef __int64 int64; +typedef unsigned __int64 uint64; +#else +# error Do not know how to define a 32-bit integer quantity on your system +#endif + +} // namespace GFLAGS_NAMESPACE + + +namespace fLS { + +// The meaning of "string" might be different between now and when the +// macros below get invoked (e.g., if someone is experimenting with +// other string implementations that get defined after this file is +// included). Save the current meaning now and use it in the macros. +typedef std::string clstring; + +} // namespace fLS + + +#define DECLARE_VARIABLE(type, shorttype, name) \ + /* We always want to import declared variables, dll or no */ \ + namespace fL##shorttype { extern GFLAGS_DLL_DECLARE_FLAG type FLAGS_##name; } \ + using fL##shorttype::FLAGS_##name + +#define DECLARE_bool(name) \ + DECLARE_VARIABLE(bool, B, name) + +#define DECLARE_int32(name) \ + DECLARE_VARIABLE(::GFLAGS_NAMESPACE::int32, I, name) + +#define DECLARE_uint32(name) \ + DECLARE_VARIABLE(::GFLAGS_NAMESPACE::uint32, U, name) + +#define DECLARE_int64(name) \ + DECLARE_VARIABLE(::GFLAGS_NAMESPACE::int64, I64, name) + +#define DECLARE_uint64(name) \ + DECLARE_VARIABLE(::GFLAGS_NAMESPACE::uint64, U64, name) + +#define DECLARE_double(name) \ + DECLARE_VARIABLE(double, D, name) + +#define DECLARE_string(name) \ + /* We always want to import declared variables, dll or no */ \ + namespace fLS { \ + extern GFLAGS_DLL_DECLARE_FLAG ::fLS::clstring& FLAGS_##name; \ + } \ + using fLS::FLAGS_##name + + +#endif // GFLAGS_DECLARE_H_ diff --git a/third_party/gflags/src/gflags_ns.h.in b/third_party/gflags/src/gflags_ns.h.in new file mode 100644 index 0000000..ef6ac29 --- /dev/null +++ b/third_party/gflags/src/gflags_ns.h.in @@ -0,0 +1,102 @@ +// Copyright (c) 2014, Andreas Schuh +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// ----------------------------------------------------------------------------- +// Imports the gflags library symbols into an alternative/deprecated namespace. + +#ifndef GFLAGS_GFLAGS_H_ +# error The internal header gflags_@ns@.h may only be included by gflags.h +#endif + +#ifndef GFLAGS_NS_@NS@_H_ +#define GFLAGS_NS_@NS@_H_ + + +namespace @ns@ { + + +using GFLAGS_NAMESPACE::int32; +using GFLAGS_NAMESPACE::uint32; +using GFLAGS_NAMESPACE::int64; +using GFLAGS_NAMESPACE::uint64; + +using GFLAGS_NAMESPACE::RegisterFlagValidator; +using GFLAGS_NAMESPACE::CommandLineFlagInfo; +using GFLAGS_NAMESPACE::GetAllFlags; +using GFLAGS_NAMESPACE::ShowUsageWithFlags; +using GFLAGS_NAMESPACE::ShowUsageWithFlagsRestrict; +using GFLAGS_NAMESPACE::DescribeOneFlag; +using GFLAGS_NAMESPACE::SetArgv; +using GFLAGS_NAMESPACE::GetArgvs; +using GFLAGS_NAMESPACE::GetArgv; +using GFLAGS_NAMESPACE::GetArgv0; +using GFLAGS_NAMESPACE::GetArgvSum; +using GFLAGS_NAMESPACE::ProgramInvocationName; +using GFLAGS_NAMESPACE::ProgramInvocationShortName; +using GFLAGS_NAMESPACE::ProgramUsage; +using GFLAGS_NAMESPACE::VersionString; +using GFLAGS_NAMESPACE::GetCommandLineOption; +using GFLAGS_NAMESPACE::GetCommandLineFlagInfo; +using GFLAGS_NAMESPACE::GetCommandLineFlagInfoOrDie; +using GFLAGS_NAMESPACE::FlagSettingMode; +using GFLAGS_NAMESPACE::SET_FLAGS_VALUE; +using GFLAGS_NAMESPACE::SET_FLAG_IF_DEFAULT; +using GFLAGS_NAMESPACE::SET_FLAGS_DEFAULT; +using GFLAGS_NAMESPACE::SetCommandLineOption; +using GFLAGS_NAMESPACE::SetCommandLineOptionWithMode; +using GFLAGS_NAMESPACE::FlagSaver; +using GFLAGS_NAMESPACE::CommandlineFlagsIntoString; +using GFLAGS_NAMESPACE::ReadFlagsFromString; +using GFLAGS_NAMESPACE::AppendFlagsIntoFile; +using GFLAGS_NAMESPACE::ReadFromFlagsFile; +using GFLAGS_NAMESPACE::BoolFromEnv; +using GFLAGS_NAMESPACE::Int32FromEnv; +using GFLAGS_NAMESPACE::Uint32FromEnv; +using GFLAGS_NAMESPACE::Int64FromEnv; +using GFLAGS_NAMESPACE::Uint64FromEnv; +using GFLAGS_NAMESPACE::DoubleFromEnv; +using GFLAGS_NAMESPACE::StringFromEnv; +using GFLAGS_NAMESPACE::SetUsageMessage; +using GFLAGS_NAMESPACE::SetVersionString; +using GFLAGS_NAMESPACE::ParseCommandLineNonHelpFlags; +using GFLAGS_NAMESPACE::HandleCommandLineHelpFlags; +using GFLAGS_NAMESPACE::AllowCommandLineReparsing; +using GFLAGS_NAMESPACE::ReparseCommandLineNonHelpFlags; +using GFLAGS_NAMESPACE::ShutDownCommandLineFlags; +using GFLAGS_NAMESPACE::FlagRegisterer; + +#ifndef SWIG +using GFLAGS_NAMESPACE::ParseCommandLineFlags; +#endif + + +} // namespace @ns@ + + +#endif // GFLAGS_NS_@NS@_H_ diff --git a/third_party/gflags/src/gflags_reporting.cc b/third_party/gflags/src/gflags_reporting.cc new file mode 100644 index 0000000..29be922 --- /dev/null +++ b/third_party/gflags/src/gflags_reporting.cc @@ -0,0 +1,442 @@ +// Copyright (c) 1999, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// --- +// +// Revamped and reorganized by Craig Silverstein +// +// This file contains code for handling the 'reporting' flags. These +// are flags that, when present, cause the program to report some +// information and then exit. --help and --version are the canonical +// reporting flags, but we also have flags like --helpxml, etc. +// +// There's only one function that's meant to be called externally: +// HandleCommandLineHelpFlags(). (Well, actually, ShowUsageWithFlags(), +// ShowUsageWithFlagsRestrict(), and DescribeOneFlag() can be called +// externally too, but there's little need for it.) These are all +// declared in the main gflags.h header file. +// +// HandleCommandLineHelpFlags() will check what 'reporting' flags have +// been defined, if any -- the "help" part of the function name is a +// bit misleading -- and do the relevant reporting. It should be +// called after all flag-values have been assigned, that is, after +// parsing the command-line. + +#include +#include +#include +#include +#include +#include + +#include "config.h" +#include "gflags/gflags.h" +#include "gflags/gflags_completions.h" +#include "util.h" + + +// The 'reporting' flags. They all call gflags_exitfunc(). +DEFINE_bool (help, false, "show help on all flags [tip: all flags can have two dashes]"); +DEFINE_bool (helpfull, false, "show help on all flags -- same as -help"); +DEFINE_bool (helpshort, false, "show help on only the main module for this program"); +DEFINE_string(helpon, "", "show help on the modules named by this flag value"); +DEFINE_string(helpmatch, "", "show help on modules whose name contains the specified substr"); +DEFINE_bool (helppackage, false, "show help on all modules in the main package"); +DEFINE_bool (helpxml, false, "produce an xml version of help"); +DEFINE_bool (version, false, "show version and build info and exit"); + + +namespace GFLAGS_NAMESPACE { + + +using std::string; +using std::vector; + + +// -------------------------------------------------------------------- +// DescribeOneFlag() +// DescribeOneFlagInXML() +// Routines that pretty-print info about a flag. These use +// a CommandLineFlagInfo, which is the way the gflags +// API exposes static info about a flag. +// -------------------------------------------------------------------- + +static const int kLineLength = 80; + +static void AddString(const string& s, + string* final_string, int* chars_in_line) { + const int slen = static_cast(s.length()); + if (*chars_in_line + 1 + slen >= kLineLength) { // < 80 chars/line + *final_string += "\n "; + *chars_in_line = 6; + } else { + *final_string += " "; + *chars_in_line += 1; + } + *final_string += s; + *chars_in_line += slen; +} + +static string PrintStringFlagsWithQuotes(const CommandLineFlagInfo& flag, + const string& text, bool current) { + const char* c_string = (current ? flag.current_value.c_str() : + flag.default_value.c_str()); + if (strcmp(flag.type.c_str(), "string") == 0) { // add quotes for strings + return StringPrintf("%s: \"%s\"", text.c_str(), c_string); + } else { + return StringPrintf("%s: %s", text.c_str(), c_string); + } +} + +// Create a descriptive string for a flag. +// Goes to some trouble to make pretty line breaks. +string DescribeOneFlag(const CommandLineFlagInfo& flag) { + string main_part; + SStringPrintf(&main_part, " -%s (%s)", + flag.name.c_str(), + flag.description.c_str()); + const char* c_string = main_part.c_str(); + int chars_left = static_cast(main_part.length()); + string final_string = ""; + int chars_in_line = 0; // how many chars in current line so far? + while (1) { + assert(static_cast(chars_left) + == strlen(c_string)); // Unless there's a \0 in there? + const char* newline = strchr(c_string, '\n'); + if (newline == NULL && chars_in_line+chars_left < kLineLength) { + // The whole remainder of the string fits on this line + final_string += c_string; + chars_in_line += chars_left; + break; + } + if (newline != NULL && newline - c_string < kLineLength - chars_in_line) { + int n = static_cast(newline - c_string); + final_string.append(c_string, n); + chars_left -= n + 1; + c_string += n + 1; + } else { + // Find the last whitespace on this 80-char line + int whitespace = kLineLength-chars_in_line-1; // < 80 chars/line + while ( whitespace > 0 && !isspace(c_string[whitespace]) ) { + --whitespace; + } + if (whitespace <= 0) { + // Couldn't find any whitespace to make a line break. Just dump the + // rest out! + final_string += c_string; + chars_in_line = kLineLength; // next part gets its own line for sure! + break; + } + final_string += string(c_string, whitespace); + chars_in_line += whitespace; + while (isspace(c_string[whitespace])) ++whitespace; + c_string += whitespace; + chars_left -= whitespace; + } + if (*c_string == '\0') + break; + StringAppendF(&final_string, "\n "); + chars_in_line = 6; + } + + // Append data type + AddString(string("type: ") + flag.type, &final_string, &chars_in_line); + // The listed default value will be the actual default from the flag + // definition in the originating source file, unless the value has + // subsequently been modified using SetCommandLineOptionWithMode() with mode + // SET_FLAGS_DEFAULT, or by setting FLAGS_foo = bar before ParseCommandLineFlags(). + AddString(PrintStringFlagsWithQuotes(flag, "default", false), &final_string, + &chars_in_line); + if (!flag.is_default) { + AddString(PrintStringFlagsWithQuotes(flag, "currently", true), + &final_string, &chars_in_line); + } + + StringAppendF(&final_string, "\n"); + return final_string; +} + +// Simple routine to xml-escape a string: escape & and < only. +static string XMLText(const string& txt) { + string ans = txt; + for (string::size_type pos = 0; (pos = ans.find("&", pos)) != string::npos; ) + ans.replace(pos++, 1, "&"); + for (string::size_type pos = 0; (pos = ans.find("<", pos)) != string::npos; ) + ans.replace(pos++, 1, "<"); + return ans; +} + +static void AddXMLTag(string* r, const char* tag, const string& txt) { + StringAppendF(r, "<%s>%s", tag, XMLText(txt).c_str(), tag); +} + + +static string DescribeOneFlagInXML(const CommandLineFlagInfo& flag) { + // The file and flagname could have been attributes, but default + // and meaning need to avoid attribute normalization. This way it + // can be parsed by simple programs, in addition to xml parsers. + string r(""); + AddXMLTag(&r, "file", flag.filename); + AddXMLTag(&r, "name", flag.name); + AddXMLTag(&r, "meaning", flag.description); + AddXMLTag(&r, "default", flag.default_value); + AddXMLTag(&r, "current", flag.current_value); + AddXMLTag(&r, "type", flag.type); + r += ""; + return r; +} + +// -------------------------------------------------------------------- +// ShowUsageWithFlags() +// ShowUsageWithFlagsRestrict() +// ShowXMLOfFlags() +// These routines variously expose the registry's list of flag +// values. ShowUsage*() prints the flag-value information +// to stdout in a user-readable format (that's what --help uses). +// The Restrict() version limits what flags are shown. +// ShowXMLOfFlags() prints the flag-value information to stdout +// in a machine-readable format. In all cases, the flags are +// sorted: first by filename they are defined in, then by flagname. +// -------------------------------------------------------------------- + +static const char* Basename(const char* filename) { + const char* sep = strrchr(filename, PATH_SEPARATOR); + return sep ? sep + 1 : filename; +} + +static string Dirname(const string& filename) { + string::size_type sep = filename.rfind(PATH_SEPARATOR); + return filename.substr(0, (sep == string::npos) ? 0 : sep); +} + +// Test whether a filename contains at least one of the substrings. +static bool FileMatchesSubstring(const string& filename, + const vector& substrings) { + for (vector::const_iterator target = substrings.begin(); + target != substrings.end(); + ++target) { + if (strstr(filename.c_str(), target->c_str()) != NULL) + return true; + // If the substring starts with a '/', that means that we want + // the string to be at the beginning of a directory component. + // That should match the first directory component as well, so + // we allow '/foo' to match a filename of 'foo'. + if (!target->empty() && (*target)[0] == PATH_SEPARATOR && + strncmp(filename.c_str(), target->c_str() + 1, + strlen(target->c_str() + 1)) == 0) + return true; + } + return false; +} + +// Show help for every filename which matches any of the target substrings. +// If substrings is empty, shows help for every file. If a flag's help message +// has been stripped (e.g. by adding '#define STRIP_FLAG_HELP 1' +// before including gflags/gflags.h), then this flag will not be displayed +// by '--help' and its variants. +static void ShowUsageWithFlagsMatching(const char *argv0, + const vector &substrings) { + fprintf(stdout, "%s: %s\n", Basename(argv0), ProgramUsage()); + + vector flags; + GetAllFlags(&flags); // flags are sorted by filename, then flagname + + string last_filename; // so we know when we're at a new file + bool first_directory = true; // controls blank lines between dirs + bool found_match = false; // stays false iff no dir matches restrict + for (vector::const_iterator flag = flags.begin(); + flag != flags.end(); + ++flag) { + if (substrings.empty() || + FileMatchesSubstring(flag->filename, substrings)) { + // If the flag has been stripped, pretend that it doesn't exist. + if (flag->description == kStrippedFlagHelp) continue; + found_match = true; // this flag passed the match! + if (flag->filename != last_filename) { // new file + if (Dirname(flag->filename) != Dirname(last_filename)) { // new dir! + if (!first_directory) + fprintf(stdout, "\n\n"); // put blank lines between directories + first_directory = false; + } + fprintf(stdout, "\n Flags from %s:\n", flag->filename.c_str()); + last_filename = flag->filename; + } + // Now print this flag + fprintf(stdout, "%s", DescribeOneFlag(*flag).c_str()); + } + } + if (!found_match && !substrings.empty()) { + fprintf(stdout, "\n No modules matched: use -help\n"); + } +} + +void ShowUsageWithFlagsRestrict(const char *argv0, const char *restrict_) { + vector substrings; + if (restrict_ != NULL && *restrict_ != '\0') { + substrings.push_back(restrict_); + } + ShowUsageWithFlagsMatching(argv0, substrings); +} + +void ShowUsageWithFlags(const char *argv0) { + ShowUsageWithFlagsRestrict(argv0, ""); +} + +// Convert the help, program, and usage to xml. +static void ShowXMLOfFlags(const char *prog_name) { + vector flags; + GetAllFlags(&flags); // flags are sorted: by filename, then flagname + + // XML. There is no corresponding schema yet + fprintf(stdout, "\n"); + // The document + fprintf(stdout, "\n"); + // the program name and usage + fprintf(stdout, "%s\n", + XMLText(Basename(prog_name)).c_str()); + fprintf(stdout, "%s\n", + XMLText(ProgramUsage()).c_str()); + // All the flags + for (vector::const_iterator flag = flags.begin(); + flag != flags.end(); + ++flag) { + if (flag->description != kStrippedFlagHelp) + fprintf(stdout, "%s\n", DescribeOneFlagInXML(*flag).c_str()); + } + // The end of the document + fprintf(stdout, "\n"); +} + +// -------------------------------------------------------------------- +// ShowVersion() +// Called upon --version. Prints build-related info. +// -------------------------------------------------------------------- + +static void ShowVersion() { + const char* version_string = VersionString(); + if (version_string && *version_string) { + fprintf(stdout, "%s version %s\n", + ProgramInvocationShortName(), version_string); + } else { + fprintf(stdout, "%s\n", ProgramInvocationShortName()); + } +# if !defined(NDEBUG) + fprintf(stdout, "Debug build (NDEBUG not #defined)\n"); +# endif +} + +static void AppendPrognameStrings(vector* substrings, + const char* progname) { + string r(""); + r += PATH_SEPARATOR; + r += progname; + substrings->push_back(r + "."); + substrings->push_back(r + "-main."); + substrings->push_back(r + "_main."); +} + +// -------------------------------------------------------------------- +// HandleCommandLineHelpFlags() +// Checks all the 'reporting' commandline flags to see if any +// have been set. If so, handles them appropriately. Note +// that all of them, by definition, cause the program to exit +// if they trigger. +// -------------------------------------------------------------------- + +void HandleCommandLineHelpFlags() { + const char* progname = ProgramInvocationShortName(); + + HandleCommandLineCompletions(); + + vector substrings; + AppendPrognameStrings(&substrings, progname); + + if (FLAGS_helpshort) { + // show only flags related to this binary: + // E.g. for fileutil.cc, want flags containing ... "/fileutil." cc + ShowUsageWithFlagsMatching(progname, substrings); + gflags_exitfunc(1); + + } else if (FLAGS_help || FLAGS_helpfull) { + // show all options + ShowUsageWithFlagsRestrict(progname, ""); // empty restrict + gflags_exitfunc(1); + + } else if (!FLAGS_helpon.empty()) { + string restrict_ = PATH_SEPARATOR + FLAGS_helpon + "."; + ShowUsageWithFlagsRestrict(progname, restrict_.c_str()); + gflags_exitfunc(1); + + } else if (!FLAGS_helpmatch.empty()) { + ShowUsageWithFlagsRestrict(progname, FLAGS_helpmatch.c_str()); + gflags_exitfunc(1); + + } else if (FLAGS_helppackage) { + // Shows help for all files in the same directory as main(). We + // don't want to resort to looking at dirname(progname), because + // the user can pick progname, and it may not relate to the file + // where main() resides. So instead, we search the flags for a + // filename like "/progname.cc", and take the dirname of that. + vector flags; + GetAllFlags(&flags); + string last_package; + for (vector::const_iterator flag = flags.begin(); + flag != flags.end(); + ++flag) { + if (!FileMatchesSubstring(flag->filename, substrings)) + continue; + const string package = Dirname(flag->filename) + PATH_SEPARATOR; + if (package != last_package) { + ShowUsageWithFlagsRestrict(progname, package.c_str()); + VLOG(7) << "Found package: " << package; + if (!last_package.empty()) { // means this isn't our first pkg + LOG(WARNING) << "Multiple packages contain a file=" << progname; + } + last_package = package; + } + } + if (last_package.empty()) { // never found a package to print + LOG(WARNING) << "Unable to find a package for file=" << progname; + } + gflags_exitfunc(1); + + } else if (FLAGS_helpxml) { + ShowXMLOfFlags(progname); + gflags_exitfunc(1); + + } else if (FLAGS_version) { + ShowVersion(); + // Unlike help, we may be asking for version in a script, so return 0 + gflags_exitfunc(0); + + } +} + + +} // namespace GFLAGS_NAMESPACE diff --git a/third_party/gflags/src/mutex.h b/third_party/gflags/src/mutex.h new file mode 100644 index 0000000..7d7c364 --- /dev/null +++ b/third_party/gflags/src/mutex.h @@ -0,0 +1,348 @@ +// Copyright (c) 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// --- +// +// A simple mutex wrapper, supporting locks and read-write locks. +// You should assume the locks are *not* re-entrant. +// +// This class is meant to be internal-only and should be wrapped by an +// internal namespace. Before you use this module, please give the +// name of your internal namespace for this module. Or, if you want +// to expose it, you'll want to move it to the Google namespace. We +// cannot put this class in global namespace because there can be some +// problems when we have multiple versions of Mutex in each shared object. +// +// NOTE: by default, we have #ifdef'ed out the TryLock() method. +// This is for two reasons: +// 1) TryLock() under Windows is a bit annoying (it requires a +// #define to be defined very early). +// 2) TryLock() is broken for NO_THREADS mode, at least in NDEBUG +// mode. +// If you need TryLock(), and either these two caveats are not a +// problem for you, or you're willing to work around them, then +// feel free to #define GMUTEX_TRYLOCK, or to remove the #ifdefs +// in the code below. +// +// CYGWIN NOTE: Cygwin support for rwlock seems to be buggy: +// http://www.cygwin.com/ml/cygwin/2008-12/msg00017.html +// Because of that, we might as well use windows locks for +// cygwin. They seem to be more reliable than the cygwin pthreads layer. +// +// TRICKY IMPLEMENTATION NOTE: +// This class is designed to be safe to use during +// dynamic-initialization -- that is, by global constructors that are +// run before main() starts. The issue in this case is that +// dynamic-initialization happens in an unpredictable order, and it +// could be that someone else's dynamic initializer could call a +// function that tries to acquire this mutex -- but that all happens +// before this mutex's constructor has run. (This can happen even if +// the mutex and the function that uses the mutex are in the same .cc +// file.) Basically, because Mutex does non-trivial work in its +// constructor, it's not, in the naive implementation, safe to use +// before dynamic initialization has run on it. +// +// The solution used here is to pair the actual mutex primitive with a +// bool that is set to true when the mutex is dynamically initialized. +// (Before that it's false.) Then we modify all mutex routines to +// look at the bool, and not try to lock/unlock until the bool makes +// it to true (which happens after the Mutex constructor has run.) +// +// This works because before main() starts -- particularly, during +// dynamic initialization -- there are no threads, so a) it's ok that +// the mutex operations are a no-op, since we don't need locking then +// anyway; and b) we can be quite confident our bool won't change +// state between a call to Lock() and a call to Unlock() (that would +// require a global constructor in one translation unit to call Lock() +// and another global constructor in another translation unit to call +// Unlock() later, which is pretty perverse). +// +// That said, it's tricky, and can conceivably fail; it's safest to +// avoid trying to acquire a mutex in a global constructor, if you +// can. One way it can fail is that a really smart compiler might +// initialize the bool to true at static-initialization time (too +// early) rather than at dynamic-initialization time. To discourage +// that, we set is_safe_ to true in code (not the constructor +// colon-initializer) and set it to true via a function that always +// evaluates to true, but that the compiler can't know always +// evaluates to true. This should be good enough. +// +// A related issue is code that could try to access the mutex +// after it's been destroyed in the global destructors (because +// the Mutex global destructor runs before some other global +// destructor, that tries to acquire the mutex). The way we +// deal with this is by taking a constructor arg that global +// mutexes should pass in, that causes the destructor to do no +// work. We still depend on the compiler not doing anything +// weird to a Mutex's memory after it is destroyed, but for a +// static global variable, that's pretty safe. + +#ifndef GFLAGS_MUTEX_H_ +#define GFLAGS_MUTEX_H_ + +#include "gflags/gflags_declare.h" // to figure out pthreads support + +#if defined(NO_THREADS) + typedef int MutexType; // to keep a lock-count +#elif defined(OS_WINDOWS) +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN // We only need minimal includes +# endif +# ifndef NOMINMAX +# define NOMINMAX // Don't want windows to override min()/max() +# endif +# ifdef GMUTEX_TRYLOCK + // We need Windows NT or later for TryEnterCriticalSection(). If you + // don't need that functionality, you can remove these _WIN32_WINNT + // lines, and change TryLock() to assert(0) or something. +# ifndef _WIN32_WINNT +# define _WIN32_WINNT 0x0400 +# endif +# endif +# include + typedef CRITICAL_SECTION MutexType; +#elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK) + // Needed for pthread_rwlock_*. If it causes problems, you could take it + // out, but then you'd have to unset HAVE_RWLOCK (at least on linux -- it + // *does* cause problems for FreeBSD, or MacOSX, but isn't needed + // for locking there.) +# ifdef __linux__ +# if _XOPEN_SOURCE < 500 // including not being defined at all +# undef _XOPEN_SOURCE +# define _XOPEN_SOURCE 500 // may be needed to get the rwlock calls +# endif +# endif +# include + typedef pthread_rwlock_t MutexType; +#elif defined(HAVE_PTHREAD) +# include + typedef pthread_mutex_t MutexType; +#else +# error Need to implement mutex.h for your architecture, or #define NO_THREADS +#endif + +#include +#include // for abort() + +#define MUTEX_NAMESPACE gflags_mutex_namespace + +namespace MUTEX_NAMESPACE { + +class Mutex { + public: + // This is used for the single-arg constructor + enum LinkerInitialized { LINKER_INITIALIZED }; + + // Create a Mutex that is not held by anybody. This constructor is + // typically used for Mutexes allocated on the heap or the stack. + inline Mutex(); + // This constructor should be used for global, static Mutex objects. + // It inhibits work being done by the destructor, which makes it + // safer for code that tries to acqiure this mutex in their global + // destructor. + explicit inline Mutex(LinkerInitialized); + + // Destructor + inline ~Mutex(); + + inline void Lock(); // Block if needed until free then acquire exclusively + inline void Unlock(); // Release a lock acquired via Lock() +#ifdef GMUTEX_TRYLOCK + inline bool TryLock(); // If free, Lock() and return true, else return false +#endif + // Note that on systems that don't support read-write locks, these may + // be implemented as synonyms to Lock() and Unlock(). So you can use + // these for efficiency, but don't use them anyplace where being able + // to do shared reads is necessary to avoid deadlock. + inline void ReaderLock(); // Block until free or shared then acquire a share + inline void ReaderUnlock(); // Release a read share of this Mutex + inline void WriterLock() { Lock(); } // Acquire an exclusive lock + inline void WriterUnlock() { Unlock(); } // Release a lock from WriterLock() + + private: + MutexType mutex_; + // We want to make sure that the compiler sets is_safe_ to true only + // when we tell it to, and never makes assumptions is_safe_ is + // always true. volatile is the most reliable way to do that. + volatile bool is_safe_; + // This indicates which constructor was called. + bool destroy_; + + inline void SetIsSafe() { is_safe_ = true; } + + // Catch the error of writing Mutex when intending MutexLock. + explicit Mutex(Mutex* /*ignored*/) {} + // Disallow "evil" constructors + Mutex(const Mutex&); + void operator=(const Mutex&); +}; + +// Now the implementation of Mutex for various systems +#if defined(NO_THREADS) + +// When we don't have threads, we can be either reading or writing, +// but not both. We can have lots of readers at once (in no-threads +// mode, that's most likely to happen in recursive function calls), +// but only one writer. We represent this by having mutex_ be -1 when +// writing and a number > 0 when reading (and 0 when no lock is held). +// +// In debug mode, we assert these invariants, while in non-debug mode +// we do nothing, for efficiency. That's why everything is in an +// assert. + +Mutex::Mutex() : mutex_(0) { } +Mutex::Mutex(Mutex::LinkerInitialized) : mutex_(0) { } +Mutex::~Mutex() { assert(mutex_ == 0); } +void Mutex::Lock() { assert(--mutex_ == -1); } +void Mutex::Unlock() { assert(mutex_++ == -1); } +#ifdef GMUTEX_TRYLOCK +bool Mutex::TryLock() { if (mutex_) return false; Lock(); return true; } +#endif +void Mutex::ReaderLock() { assert(++mutex_ > 0); } +void Mutex::ReaderUnlock() { assert(mutex_-- > 0); } + +#elif defined(OS_WINDOWS) + +Mutex::Mutex() : destroy_(true) { + InitializeCriticalSection(&mutex_); + SetIsSafe(); +} +Mutex::Mutex(LinkerInitialized) : destroy_(false) { + InitializeCriticalSection(&mutex_); + SetIsSafe(); +} +Mutex::~Mutex() { if (destroy_) DeleteCriticalSection(&mutex_); } +void Mutex::Lock() { if (is_safe_) EnterCriticalSection(&mutex_); } +void Mutex::Unlock() { if (is_safe_) LeaveCriticalSection(&mutex_); } +#ifdef GMUTEX_TRYLOCK +bool Mutex::TryLock() { return is_safe_ ? + TryEnterCriticalSection(&mutex_) != 0 : true; } +#endif +void Mutex::ReaderLock() { Lock(); } // we don't have read-write locks +void Mutex::ReaderUnlock() { Unlock(); } + +#elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK) + +#define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \ + if (is_safe_ && fncall(&mutex_) != 0) abort(); \ +} while (0) + +Mutex::Mutex() : destroy_(true) { + SetIsSafe(); + if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort(); +} +Mutex::Mutex(Mutex::LinkerInitialized) : destroy_(false) { + SetIsSafe(); + if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort(); +} +Mutex::~Mutex() { if (destroy_) SAFE_PTHREAD(pthread_rwlock_destroy); } +void Mutex::Lock() { SAFE_PTHREAD(pthread_rwlock_wrlock); } +void Mutex::Unlock() { SAFE_PTHREAD(pthread_rwlock_unlock); } +#ifdef GMUTEX_TRYLOCK +bool Mutex::TryLock() { return is_safe_ ? + pthread_rwlock_trywrlock(&mutex_) == 0 : true; } +#endif +void Mutex::ReaderLock() { SAFE_PTHREAD(pthread_rwlock_rdlock); } +void Mutex::ReaderUnlock() { SAFE_PTHREAD(pthread_rwlock_unlock); } +#undef SAFE_PTHREAD + +#elif defined(HAVE_PTHREAD) + +#define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \ + if (is_safe_ && fncall(&mutex_) != 0) abort(); \ +} while (0) + +Mutex::Mutex() : destroy_(true) { + SetIsSafe(); + if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort(); +} +Mutex::Mutex(Mutex::LinkerInitialized) : destroy_(false) { + SetIsSafe(); + if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort(); +} +Mutex::~Mutex() { if (destroy_) SAFE_PTHREAD(pthread_mutex_destroy); } +void Mutex::Lock() { SAFE_PTHREAD(pthread_mutex_lock); } +void Mutex::Unlock() { SAFE_PTHREAD(pthread_mutex_unlock); } +#ifdef GMUTEX_TRYLOCK +bool Mutex::TryLock() { return is_safe_ ? + pthread_mutex_trylock(&mutex_) == 0 : true; } +#endif +void Mutex::ReaderLock() { Lock(); } +void Mutex::ReaderUnlock() { Unlock(); } +#undef SAFE_PTHREAD + +#endif + +// -------------------------------------------------------------------------- +// Some helper classes + +// MutexLock(mu) acquires mu when constructed and releases it when destroyed. +class MutexLock { + public: + explicit MutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); } + ~MutexLock() { mu_->Unlock(); } + private: + Mutex * const mu_; + // Disallow "evil" constructors + MutexLock(const MutexLock&); + void operator=(const MutexLock&); +}; + +// ReaderMutexLock and WriterMutexLock do the same, for rwlocks +class ReaderMutexLock { + public: + explicit ReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); } + ~ReaderMutexLock() { mu_->ReaderUnlock(); } + private: + Mutex * const mu_; + // Disallow "evil" constructors + ReaderMutexLock(const ReaderMutexLock&); + void operator=(const ReaderMutexLock&); +}; + +class WriterMutexLock { + public: + explicit WriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); } + ~WriterMutexLock() { mu_->WriterUnlock(); } + private: + Mutex * const mu_; + // Disallow "evil" constructors + WriterMutexLock(const WriterMutexLock&); + void operator=(const WriterMutexLock&); +}; + +// Catch bug where variable name is omitted, e.g. MutexLock (&mu); +#define MutexLock(x) COMPILE_ASSERT(0, mutex_lock_decl_missing_var_name) +#define ReaderMutexLock(x) COMPILE_ASSERT(0, rmutex_lock_decl_missing_var_name) +#define WriterMutexLock(x) COMPILE_ASSERT(0, wmutex_lock_decl_missing_var_name) + +} // namespace MUTEX_NAMESPACE + + +#endif /* #define GFLAGS_MUTEX_H__ */ diff --git a/third_party/gflags/src/util.h b/third_party/gflags/src/util.h new file mode 100644 index 0000000..164e3cf --- /dev/null +++ b/third_party/gflags/src/util.h @@ -0,0 +1,373 @@ +// Copyright (c) 2011, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// --- +// +// Some generically useful utility routines that in google-land would +// be their own projects. We make a shortened version here. + +#ifndef GFLAGS_UTIL_H_ +#define GFLAGS_UTIL_H_ + +#include "config.h" + +#include +#ifdef HAVE_INTTYPES_H +# include +#endif +#include // for va_* +#include +#include +#include +#include +#include +#ifdef HAVE_SYS_STAT_H +# include // for mkdir +#endif + + +namespace GFLAGS_NAMESPACE { + + +// This is used for unittests for death-testing. It is defined in gflags.cc. +extern GFLAGS_DLL_DECL void (*gflags_exitfunc)(int); + +// Work properly if either strtoll or strtoq is on this system. +#if defined(strtoll) || defined(HAVE_STRTOLL) +# define strto64 strtoll +# define strtou64 strtoull +#elif defined(HAVE_STRTOQ) +# define strto64 strtoq +# define strtou64 strtouq +// Neither strtoll nor strtoq are defined. I hope strtol works! +#else +# define strto64 strtol +# define strtou64 strtoul +#endif + +// If we have inttypes.h, it will have defined PRId32/etc for us. +// If not, take our best guess. +#ifndef PRId32 +# define PRId32 "d" +#endif +#ifndef PRId64 +# define PRId64 "lld" +#endif +#ifndef PRIu64 +# define PRIu64 "llu" +#endif + +typedef signed char int8; +typedef unsigned char uint8; + +// -- utility macros --------------------------------------------------------- + +template struct CompileAssert; +template <> struct CompileAssert {}; +#define COMPILE_ASSERT(expr, msg) \ + enum { assert_##msg = sizeof(CompileAssert) } + +// Returns the number of elements in an array. +#define arraysize(arr) (sizeof(arr)/sizeof(*(arr))) + + +// -- logging and testing --------------------------------------------------- + +// For now, we ignore the level for logging, and don't show *VLOG's at +// all, except by hand-editing the lines below +#define LOG(level) std::cerr +#define VLOG(level) if (true) {} else std::cerr +#define DVLOG(level) if (true) {} else std::cerr + +// CHECK dies with a fatal error if condition is not true. It is *not* +// controlled by NDEBUG, so the check will be executed regardless of +// compilation mode. Therefore, it is safe to do things like: +// CHECK(fp->Write(x) == 4) +// We allow stream-like objects after this for debugging, but they're ignored. +#define EXPECT_TRUE(condition) \ + if (true) { \ + if (!(condition)) { \ + fprintf(stderr, "Check failed: %s\n", #condition); \ + exit(1); \ + } \ + } else std::cerr << "" + +#define EXPECT_OP(op, val1, val2) \ + if (true) { \ + if (!((val1) op (val2))) { \ + fprintf(stderr, "Check failed: %s %s %s\n", #val1, #op, #val2); \ + exit(1); \ + } \ + } else std::cerr << "" + +#define EXPECT_EQ(val1, val2) EXPECT_OP(==, val1, val2) +#define EXPECT_NE(val1, val2) EXPECT_OP(!=, val1, val2) +#define EXPECT_LE(val1, val2) EXPECT_OP(<=, val1, val2) +#define EXPECT_LT(val1, val2) EXPECT_OP(< , val1, val2) +#define EXPECT_GE(val1, val2) EXPECT_OP(>=, val1, val2) +#define EXPECT_GT(val1, val2) EXPECT_OP(> , val1, val2) +#define EXPECT_FALSE(cond) EXPECT_TRUE(!(cond)) + +// C99 declares isnan and isinf should be macros, so the #ifdef test +// should be reliable everywhere. Of course, it's not, but these +// are testing pertty marginal functionality anyway, so it's ok to +// not-run them even in situations they might, with effort, be made to work. +#ifdef isnan // Some compilers, like sun's for Solaris 10, don't define this +#define EXPECT_NAN(arg) \ + do { \ + if (!isnan(arg)) { \ + fprintf(stderr, "Check failed: isnan(%s)\n", #arg); \ + exit(1); \ + } \ + } while (0) +#else +#define EXPECT_NAN(arg) +#endif + +#ifdef isinf // Some compilers, like sun's for Solaris 10, don't define this +#define EXPECT_INF(arg) \ + do { \ + if (!isinf(arg)) { \ + fprintf(stderr, "Check failed: isinf(%s)\n", #arg); \ + exit(1); \ + } \ + } while (0) +#else +#define EXPECT_INF(arg) +#endif + +#define EXPECT_DOUBLE_EQ(val1, val2) \ + do { \ + if (((val1) < (val2) - 0.001 || (val1) > (val2) + 0.001)) { \ + fprintf(stderr, "Check failed: %s == %s\n", #val1, #val2); \ + exit(1); \ + } \ + } while (0) + +#define EXPECT_STREQ(val1, val2) \ + do { \ + if (strcmp((val1), (val2)) != 0) { \ + fprintf(stderr, "Check failed: streq(%s, %s)\n", #val1, #val2); \ + exit(1); \ + } \ + } while (0) + +// Call this in a .cc file where you will later call RUN_ALL_TESTS in main(). +#define TEST_INIT \ + static std::vector g_testlist; /* the tests to run */ \ + static int RUN_ALL_TESTS() { \ + std::vector::const_iterator it; \ + for (it = g_testlist.begin(); it != g_testlist.end(); ++it) { \ + (*it)(); /* The test will error-exit if there's a problem. */ \ + } \ + fprintf(stderr, "\nPassed %d tests\n\nPASS\n", \ + static_cast(g_testlist.size())); \ + return 0; \ + } + +// Note that this macro uses a FlagSaver to keep tests isolated. +#define TEST(a, b) \ + struct Test_##a##_##b { \ + Test_##a##_##b() { g_testlist.push_back(&Run); } \ + static void Run() { \ + FlagSaver fs; \ + fprintf(stderr, "Running test %s/%s\n", #a, #b); \ + RunTest(); \ + } \ + static void RunTest(); \ + }; \ + static Test_##a##_##b g_test_##a##_##b; \ + void Test_##a##_##b::RunTest() + +// This is a dummy class that eases the google->opensource transition. +namespace testing { +class Test {}; +} + +// Call this in a .cc file where you will later call EXPECT_DEATH +#define EXPECT_DEATH_INIT \ + static bool g_called_exit; \ + static void CalledExit(int) { g_called_exit = true; } + +#define EXPECT_DEATH(fn, msg) \ + do { \ + g_called_exit = false; \ + gflags_exitfunc = &CalledExit; \ + fn; \ + gflags_exitfunc = &exit; /* set back to its default */ \ + if (!g_called_exit) { \ + fprintf(stderr, "Function didn't die (%s): %s\n", msg, #fn); \ + exit(1); \ + } \ + } while (0) + +#define GTEST_HAS_DEATH_TEST 1 + +// -- path routines ---------------------------------------------------------- + +// Tries to create the directory path as a temp-dir. If it fails, +// changes path to some directory it *can* create. +#if defined(__MINGW32__) +#include +inline void MakeTmpdir(std::string* path) { + if (!path->empty()) { + path->append("/gflags_unittest_testdir"); + int err = mkdir(path->c_str()); + if (err == 0 || errno == EEXIST) return; + } + // I had trouble creating a directory in /tmp from mingw + *path = "./gflags_unittest"; + mkdir(path->c_str()); +} +#elif defined(_MSC_VER) +#include +inline void MakeTmpdir(std::string* path) { + if (!path->empty()) { + int err = _mkdir(path->c_str()); + if (err == 0 || errno == EEXIST) return; + } + char tmppath_buffer[1024]; + int tmppath_len = GetTempPathA(sizeof(tmppath_buffer), tmppath_buffer); + assert(tmppath_len > 0 && tmppath_len < sizeof(tmppath_buffer)); + assert(tmppath_buffer[tmppath_len - 1] == '\\'); // API guarantees it + *path = std::string(tmppath_buffer) + "gflags_unittest"; + _mkdir(path->c_str()); +} +#else +inline void MakeTmpdir(std::string* path) { + if (!path->empty()) { + int err = mkdir(path->c_str(), 0755); + if (err == 0 || errno == EEXIST) return; + } + mkdir("/tmp/gflags_unittest", 0755); +} +#endif + +// -- string routines -------------------------------------------------------- + +inline void InternalStringPrintf(std::string* output, const char* format, + va_list ap) { + char space[128]; // try a small buffer and hope it fits + + // It's possible for methods that use a va_list to invalidate + // the data in it upon use. The fix is to make a copy + // of the structure before using it and use that copy instead. + va_list backup_ap; + va_copy(backup_ap, ap); + int bytes_written = vsnprintf(space, sizeof(space), format, backup_ap); + va_end(backup_ap); + + if ((bytes_written >= 0) && (static_cast(bytes_written) < sizeof(space))) { + output->append(space, bytes_written); + return; + } + + // Repeatedly increase buffer size until it fits. + int length = sizeof(space); + while (true) { + if (bytes_written < 0) { + // Older snprintf() behavior. :-( Just try doubling the buffer size + length *= 2; + } else { + // We need exactly "bytes_written+1" characters + length = bytes_written+1; + } + char* buf = new char[length]; + + // Restore the va_list before we use it again + va_copy(backup_ap, ap); + bytes_written = vsnprintf(buf, length, format, backup_ap); + va_end(backup_ap); + + if ((bytes_written >= 0) && (bytes_written < length)) { + output->append(buf, bytes_written); + delete[] buf; + return; + } + delete[] buf; + } +} + +// Clears output before writing to it. +inline void SStringPrintf(std::string* output, const char* format, ...) { + va_list ap; + va_start(ap, format); + output->clear(); + InternalStringPrintf(output, format, ap); + va_end(ap); +} + +inline void StringAppendF(std::string* output, const char* format, ...) { + va_list ap; + va_start(ap, format); + InternalStringPrintf(output, format, ap); + va_end(ap); +} + +inline std::string StringPrintf(const char* format, ...) { + va_list ap; + va_start(ap, format); + std::string output; + InternalStringPrintf(&output, format, ap); + va_end(ap); + return output; +} + +inline bool SafeGetEnv(const char *varname, std::string &valstr) +{ +#if defined(_MSC_VER) && _MSC_VER >= 1400 + char *val; + size_t sz; + if (_dupenv_s(&val, &sz, varname) != 0 || !val) return false; + valstr = val; + free(val); +#else + const char * const val = getenv(varname); + if (!val) return false; + valstr = val; +#endif + return true; +} + +inline int SafeFOpen(FILE **fp, const char* fname, const char *mode) +{ +#if defined(_MSC_VER) && _MSC_VER >= 1400 + return fopen_s(fp, fname, mode); +#else + assert(fp != NULL); + *fp = fopen(fname, mode); + // errno only guaranteed to be set on failure + return ((*fp == NULL) ? errno : 0); +#endif +} + + +} // namespace GFLAGS_NAMESPACE + + +#endif // GFLAGS_UTIL_H_ diff --git a/third_party/gflags/src/windows_port.cc b/third_party/gflags/src/windows_port.cc new file mode 100644 index 0000000..b5b7194 --- /dev/null +++ b/third_party/gflags/src/windows_port.cc @@ -0,0 +1,73 @@ +/* Copyright (c) 2009, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * --- + * Author: Craig Silverstein + */ + +#ifndef _WIN32 +# error You should only be including windows/port.cc in a windows environment! +#endif + +#include // for strlen(), memset(), memcmp() +#include +#include // for va_list, va_start, va_end +#include + +#include "windows_port.h" + +// These call the windows _vsnprintf, but always NUL-terminate. +#if !defined(__MINGW32__) && !defined(__MINGW64__) /* mingw already defines */ +#if !(defined(_MSC_VER) && _MSC_VER >= 1900) /* msvc 2015 already defines */ + +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable: 4996) // ignore _vsnprintf security warning +#endif +int safe_vsnprintf(char *str, size_t size, const char *format, va_list ap) { + if (size == 0) // not even room for a \0? + return -1; // not what C99 says to do, but what windows does + str[size-1] = '\0'; + return _vsnprintf(str, size-1, format, ap); +} +#ifdef _MSC_VER +# pragma warning(pop) +#endif + +int snprintf(char *str, size_t size, const char *format, ...) { + int r; + va_list ap; + va_start(ap, format); + r = vsnprintf(str, size, format, ap); + va_end(ap); + return r; +} + +#endif /* if !(defined(_MSC_VER) && _MSC_VER >= 1900) */ +#endif /* #if !defined(__MINGW32__) && !defined(__MINGW64__) */ diff --git a/third_party/gflags/src/windows_port.h b/third_party/gflags/src/windows_port.h new file mode 100644 index 0000000..59a310e --- /dev/null +++ b/third_party/gflags/src/windows_port.h @@ -0,0 +1,135 @@ +/* Copyright (c) 2009, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * --- + * Author: Craig Silverstein + * + * These are some portability typedefs and defines to make it a bit + * easier to compile this code under VC++. + * + * Several of these are taken from glib: + * http://developer.gnome.org/doc/API/glib/glib-windows-compatability-functions.html + */ + +#ifndef GFLAGS_WINDOWS_PORT_H_ +#define GFLAGS_WINDOWS_PORT_H_ + +#include "config.h" + +// This must be defined before the windows.h is included. +// It's needed for mutex.h, to give access to the TryLock method. +# if !defined(_WIN32_WINNT) && !(defined( __MINGW32__) || defined(__MINGW64__)) +# define _WIN32_WINNT 0x0400 +# endif +// We always want minimal includes +#ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +#endif +#include +#include /* for mkdir */ +#include /* for _putenv, getenv */ +#include /* need this to override stdio's snprintf, also defines _unlink used by unit tests */ +#include /* util.h uses va_copy */ +#include /* for _stricmp and _strdup */ + +/* We can't just use _vsnprintf and _snprintf as drop-in-replacements, + * because they don't always NUL-terminate. :-( We also can't use the + * name vsnprintf, since windows defines that (but not snprintf (!)). + */ +#if !defined(__MINGW32__) && !defined(__MINGW64__) /* mingw already defines */ +#if !(defined(_MSC_VER) && _MSC_VER >= 1900) /* msvc 2015 already defines */ +extern GFLAGS_DLL_DECL int snprintf(char *str, size_t size, + const char *format, ...); +extern int GFLAGS_DLL_DECL safe_vsnprintf(char *str, size_t size, + const char *format, va_list ap); +#define vsnprintf(str, size, format, ap) safe_vsnprintf(str, size, format, ap) +#define va_copy(dst, src) (dst) = (src) +#endif +#endif /* #if !defined(__MINGW32__) && !defined(__MINGW64__) */ + +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable: 4996) // ignore getenv security warning +#endif +#if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200112L +inline void setenv(const char* name, const char* value, int) { + // In windows, it's impossible to set a variable to the empty string. + // We handle this by setting it to "0" and the NUL-ing out the \0. + // That is, we putenv("FOO=0") and then find out where in memory the + // putenv wrote "FOO=0", and change it in-place to "FOO=\0". + // c.f. http://svn.apache.org/viewvc/stdcxx/trunk/tests/src/environ.cpp?r1=611451&r2=637508&pathrev=637508 + static const char* const kFakeZero = "0"; + if (*value == '\0') + value = kFakeZero; + // Apparently the semantics of putenv() is that the input + // must live forever, so we leak memory here. :-( + const size_t nameval_len = strlen(name) + 1 + strlen(value) + 1; + char* nameval = reinterpret_cast(malloc(nameval_len)); + snprintf(nameval, nameval_len, "%s=%s", name, value); + _putenv(nameval); + if (value == kFakeZero) { + nameval[nameval_len - 2] = '\0'; // works when putenv() makes no copy + if (*getenv(name) != '\0') + *getenv(name) = '\0'; // works when putenv() copies nameval + } +} +#endif +#ifdef _MSC_VER +# pragma warning(pop) +#endif + +#define strcasecmp _stricmp + +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#define strdup _strdup +#define unlink _unlink +#endif + +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#include +#else +#define PRId32 "d" +#define PRIu32 "u" +#define PRId64 "I64d" +#define PRIu64 "I64u" +#endif + +#if !defined(__MINGW32__) && !defined(__MINGW64__) +#define strtoq _strtoi64 +#define strtouq _strtoui64 +#define strtoll _strtoi64 +#define strtoull _strtoui64 +#define atoll _atoi64 +#endif + +#ifndef PATH_MAX +#define PATH_MAX 1024 +#endif + +#endif /* GFLAGS_WINDOWS_PORT_H_ */ diff --git a/third_party/gflags/test/CMakeLists.txt b/third_party/gflags/test/CMakeLists.txt new file mode 100644 index 0000000..4cd1e69 --- /dev/null +++ b/third_party/gflags/test/CMakeLists.txt @@ -0,0 +1,209 @@ +## gflags tests + +# ---------------------------------------------------------------------------- +# output directories +set (CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") +set (CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") +set (CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") + +# set working directory of test commands +set (GFLAGS_FLAGFILES_DIR "${CMAKE_CURRENT_SOURCE_DIR}") + +# ---------------------------------------------------------------------------- +# common include directories and link libraries +include_directories ("${CMAKE_CURRENT_SOURCE_DIR}") +include_directories ("${gflags_SOURCE_DIR}/src") +include_directories ("${gflags_BINARY_DIR}/include") +include_directories ("${gflags_BINARY_DIR}/include/gflags") + +if (BUILD_SHARED_LIBS) + set (type shared) + if (GFLAGS_IS_A_DLL) + add_definitions(-DGFLAGS_IS_A_DLL) + endif () +else () + set (type static) +endif () +if (BUILD_gflags_LIB) + link_libraries (gflags_${type}) +else () + link_libraries (gflags_nothreads_${type}) +endif () + +# ---------------------------------------------------------------------------- +# STRIP_FLAG_HELP +add_executable (gflags_strip_flags_test gflags_strip_flags_test.cc) +# Make sure the --help output doesn't print the stripped text. +add_gflags_test (strip_flags_help 1 "" "This text should be stripped out" gflags_strip_flags_test --help) +# Make sure the stripped text isn't in the binary at all. +add_test ( + NAME strip_flags_binary + COMMAND "${CMAKE_COMMAND}" "-DBINARY=$" + -P "${CMAKE_CURRENT_SOURCE_DIR}/gflags_strip_flags_test.cmake" + CONFIGURATIONS Release MinSizeRel +) + +# ---------------------------------------------------------------------------- +# unit tests +configure_file (gflags_unittest.cc gflags_unittest-main.cc COPYONLY) +configure_file (gflags_unittest.cc gflags_unittest_main.cc COPYONLY) + +add_executable (gflags_unittest gflags_unittest.cc) +add_executable (gflags_unittest-main gflags_unittest-main.cc) +add_executable (gflags_unittest_main gflags_unittest_main.cc) + +if (OS_WINDOWS) + set (SLASH "\\\\") +else () + set (SLASH "/") +endif () + +# First, just make sure the gflags_unittest works as-is +add_gflags_test(unittest 0 "" "" gflags_unittest) + +# --help should show all flags, including flags from gflags_reporting +add_gflags_test(help-reporting 1 "${SLASH}gflags_reporting.cc:" "" gflags_unittest --help) + +# Make sure that --help prints even very long helpstrings. +add_gflags_test(long-helpstring 1 "end of a long helpstring" "" gflags_unittest --help) + +# Make sure --help reflects flag changes made before flag-parsing +add_gflags_test(changed_bool1 1 "-changed_bool1 (changed) type: bool default: true" "" gflags_unittest --help) +add_gflags_test(changed_bool2 1 "-changed_bool2 (changed) type: bool default: false currently: true" "" gflags_unittest --help) +# And on the command-line, too +add_gflags_test(changeable_string_var 1 "-changeable_string_var () type: string default: \"1\" currently: \"2\"" "" gflags_unittest --changeable_string_var 2 --help) + +# --nohelp and --help=false should be as if we didn't say anything +add_gflags_test(nohelp 0 "PASS" "" gflags_unittest --nohelp) +add_gflags_test(help=false 0 "PASS" "" gflags_unittest --help=false) + +# --helpfull is the same as help +add_gflags_test(helpfull 1 "${SLASH}gflags_reporting.cc:" "" gflags_unittest --helpfull) + +# --helpshort should show only flags from the gflags_unittest itself +add_gflags_test(helpshort 1 "${SLASH}gflags_unittest.cc:" "${SLASH}gflags_reporting.cc:" gflags_unittest --helpshort) + +# --helpshort should show the tldflag we created in the gflags_unittest dir +add_gflags_test(helpshort-tldflag1 1 "tldflag1" "${SLASH}google.cc:" gflags_unittest --helpshort) +add_gflags_test(helpshort-tldflag2 1 "tldflag2" "${SLASH}google.cc:" gflags_unittest --helpshort) + +# --helpshort should work if the main source file is suffixed with [_-]main +add_gflags_test(helpshort-main 1 "${SLASH}gflags_unittest-main.cc:" "${SLASH}gflags_reporting.cc:" gflags_unittest-main --helpshort) +add_gflags_test(helpshort_main 1 "${SLASH}gflags_unittest_main.cc:" "${SLASH}gflags_reporting.cc:" gflags_unittest_main --helpshort) + +# --helpon needs an argument +add_gflags_test(helpon 1 "'--helpon' is missing its argument; flag description: show help on" "" gflags_unittest --helpon) +# --helpon argument indicates what file we'll show args from +add_gflags_test(helpon=gflags 1 "${SLASH}gflags.cc:" "${SLASH}gflags_unittest.cc:" gflags_unittest --helpon=gflags) +# another way of specifying the argument +add_gflags_test(helpon_gflags 1 "${SLASH}gflags.cc:" "${SLASH}gflags_unittest.cc:" gflags_unittest --helpon gflags) +# test another argument +add_gflags_test(helpon=gflags_unittest 1 "${SLASH}gflags_unittest.cc:" "${SLASH}gflags.cc:" gflags_unittest --helpon=gflags_unittest) + +# helpmatch is like helpon but takes substrings +add_gflags_test(helpmatch_reporting 1 "${SLASH}gflags_reporting.cc:" "${SLASH}gflags_unittest.cc:" gflags_unittest -helpmatch reporting) +add_gflags_test(helpmatch=unittest 1 "${SLASH}gflags_unittest.cc:" "${SLASH}gflags.cc:" gflags_unittest -helpmatch=unittest) + +# if no flags are found with helpmatch or helpon, suggest --help +add_gflags_test(helpmatch=nosuchsubstring 1 "No modules matched" "${SLASH}gflags_unittest.cc:" gflags_unittest -helpmatch=nosuchsubstring) +add_gflags_test(helpon=nosuchmodule 1 "No modules matched" "${SLASH}gflags_unittest.cc:" gflags_unittest -helpon=nosuchmodule) + +# helppackage shows all the flags in the same dir as this unittest +# --help should show all flags, including flags from google.cc +add_gflags_test(helppackage 1 "${SLASH}gflags_reporting.cc:" "" gflags_unittest --helppackage) + +# xml! +add_gflags_test(helpxml 1 "${SLASH}gflags_unittest.cc" "${SLASH}gflags_unittest.cc:" gflags_unittest --helpxml) + +# just print the version info and exit +add_gflags_test(version-1 0 "gflags_unittest" "${SLASH}gflags_unittest.cc:" gflags_unittest --version) +add_gflags_test(version-2 0 "version test_version" "${SLASH}gflags_unittest.cc:" gflags_unittest --version) + +# --undefok is a fun flag... +add_gflags_test(undefok-1 1 "unknown command line flag 'foo'" "" gflags_unittest --undefok= --foo --unused_bool) +add_gflags_test(undefok-2 0 "PASS" "" gflags_unittest --undefok=foo --foo --unused_bool) +# If you say foo is ok to be undefined, we'll accept --nofoo as well +add_gflags_test(undefok-3 0 "PASS" "" gflags_unittest --undefok=foo --nofoo --unused_bool) +# It's ok if the foo is in the middle +add_gflags_test(undefok-4 0 "PASS" "" gflags_unittest --undefok=fee,fi,foo,fum --foo --unused_bool) +# But the spelling has to be just right... +add_gflags_test(undefok-5 1 "unknown command line flag 'foo'" "" gflags_unittest --undefok=fo --foo --unused_bool) +add_gflags_test(undefok-6 1 "unknown command line flag 'foo'" "" gflags_unittest --undefok=foot --foo --unused_bool) + +# See if we can successfully load our flags from the flagfile +add_gflags_test(flagfile.1 0 "gflags_unittest" "${SLASH}gflags_unittest.cc:" gflags_unittest "--flagfile=flagfile.1") +add_gflags_test(flagfile.2 0 "PASS" "" gflags_unittest "--flagfile=flagfile.2") +add_gflags_test(flagfile.3 0 "PASS" "" gflags_unittest "--flagfile=flagfile.3") + +# Also try to load flags from the environment +add_gflags_test(fromenv=version 0 "gflags_unittest" "${SLASH}gflags_unittest.cc:" gflags_unittest --fromenv=version) +add_gflags_test(tryfromenv=version 0 "gflags_unittest" "${SLASH}gflags_unittest.cc:" gflags_unittest --tryfromenv=version) +add_gflags_test(fromenv=help 0 "PASS" "" gflags_unittest --fromenv=help) +add_gflags_test(tryfromenv=help 0 "PASS" "" gflags_unittest --tryfromenv=help) +add_gflags_test(fromenv=helpfull 1 "helpfull not found in environment" "" gflags_unittest --fromenv=helpfull) +add_gflags_test(tryfromenv=helpfull 0 "PASS" "" gflags_unittest --tryfromenv=helpfull) +add_gflags_test(tryfromenv=undefok 0 "PASS" "" gflags_unittest --tryfromenv=undefok --foo) +add_gflags_test(tryfromenv=weirdo 1 "unknown command line flag" "" gflags_unittest --tryfromenv=weirdo) +add_gflags_test(tryfromenv-multiple 0 "gflags_unittest" "${SLASH}gflags_unittest.cc:" gflags_unittest --tryfromenv=test_bool,version,unused_bool) +add_gflags_test(fromenv=test_bool 1 "not found in environment" "" gflags_unittest --fromenv=test_bool) +add_gflags_test(fromenv=test_bool-ok 1 "unknown command line flag" "" gflags_unittest --fromenv=test_bool,ok) +# Here, the --version overrides the fromenv +add_gflags_test(version-overrides-fromenv 0 "gflags_unittest" "${SLASH}gflags_unittest.cc:" gflags_unittest --fromenv=test_bool,version,ok) + +# Make sure -- by itself stops argv processing +add_gflags_test(dashdash 0 "PASS" "" gflags_unittest -- --help) + +# And we should die if the flag value doesn't pass the validator +add_gflags_test(always_fail 1 "ERROR: failed validation of new value 'true' for flag 'always_fail'" "" gflags_unittest --always_fail) + +# And if locking in validators fails +# TODO(andreas): Worked on Windows 7 Release configuration, but causes +# debugger abort() intervention in case of Debug configuration. +#add_gflags_test(deadlock_if_cant_lock 0 "PASS" "" gflags_unittest --deadlock_if_cant_lock) + +# ---------------------------------------------------------------------------- +# use gflags_declare.h +add_executable (gflags_declare_test gflags_declare_test.cc gflags_declare_flags.cc) + +add_test(NAME gflags_declare COMMAND gflags_declare_test --message "Hello gflags!") +set_tests_properties(gflags_declare PROPERTIES PASS_REGULAR_EXPRESSION "Hello gflags!") + +# ---------------------------------------------------------------------------- +# configure Python script which configures and builds a test project +if (BUILD_NC_TESTS OR BUILD_CONFIG_TESTS) + find_package (PythonInterp) + if (NOT PYTHON_EXECUTABLE) + message (FATAL_ERROR "No Python installation found! It is required by the (negative) compilation tests." + " Either install Python or set BUILD_NC_TESTS and BUILD_CONFIG_TESTS to FALSE.") + endif () + set (TMPDIR "${PROJECT_BINARY_DIR}/Testing/Temporary") + configure_file (gflags_build.py.in "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/build.py" @ONLY) + function (add_gflags_build_test name srcdir expect_fail) + set (srcdir "${CMAKE_CURRENT_SOURCE_DIR}/${srcdir}") + add_test ( + NAME "${name}" + COMMAND "${PYTHON_EXECUTABLE}" "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/build.py" + ${name} ${srcdir} ${expect_fail} + ) + endfunction () +endif () + +# ---------------------------------------------------------------------------- +# negative compilation tests +option (BUILD_NC_TESTS "Request addition of negative compilation tests." OFF) +mark_as_advanced (BUILD_NC_TESTS) +if (BUILD_NC_TESTS) + add_gflags_build_test (nc_sanity nc 0) + add_gflags_build_test (nc_swapped_args nc 1) + add_gflags_build_test (nc_int_instead_of_bool nc 1) + add_gflags_build_test (nc_bool_in_quotes nc 1) + add_gflags_build_test (nc_define_string_with_0 nc 1) +endif () + +# ---------------------------------------------------------------------------- +# build configuration test +option (BUILD_CONFIG_TESTS "Request addition of package configuration tests." OFF) +mark_as_advanced (BUILD_CONFIG_TESTS) +if (BUILD_CONFIG_TESTS) + add_gflags_build_test (cmake_config config 0) +endif () diff --git a/third_party/gflags/test/config/CMakeLists.txt b/third_party/gflags/test/config/CMakeLists.txt new file mode 100644 index 0000000..6190b25 --- /dev/null +++ b/third_party/gflags/test/config/CMakeLists.txt @@ -0,0 +1,10 @@ +## gflags package configuration tests + +cmake_minimum_required (VERSION 2.8.12 FATAL_ERROR) + +project (gflags_${TEST_NAME}) + +find_package (gflags REQUIRED) + +add_executable (foo main.cc) +target_link_libraries (foo gflags::gflags) diff --git a/third_party/gflags/test/config/main.cc b/third_party/gflags/test/config/main.cc new file mode 100644 index 0000000..3c033e3 --- /dev/null +++ b/third_party/gflags/test/config/main.cc @@ -0,0 +1,20 @@ +#include +#include + +DEFINE_string(message, "Hello World!", "The message to print"); + +static bool ValidateMessage(const char* flagname, const std::string &message) +{ + return !message.empty(); +} +DEFINE_validator(message, ValidateMessage); + +int main(int argc, char **argv) +{ + gflags::SetUsageMessage("Test CMake configuration of gflags library (gflags-config.cmake)"); + gflags::SetVersionString("0.1"); + gflags::ParseCommandLineFlags(&argc, &argv, true); + std::cout << FLAGS_message << std::endl; + gflags::ShutDownCommandLineFlags(); + return 0; +} diff --git a/third_party/gflags/test/flagfile.1 b/third_party/gflags/test/flagfile.1 new file mode 100644 index 0000000..e0f9217 --- /dev/null +++ b/third_party/gflags/test/flagfile.1 @@ -0,0 +1 @@ +--version \ No newline at end of file diff --git a/third_party/gflags/test/flagfile.2 b/third_party/gflags/test/flagfile.2 new file mode 100644 index 0000000..864f8e8 --- /dev/null +++ b/third_party/gflags/test/flagfile.2 @@ -0,0 +1,2 @@ +--foo=bar +--nounused_bool \ No newline at end of file diff --git a/third_party/gflags/test/flagfile.3 b/third_party/gflags/test/flagfile.3 new file mode 100644 index 0000000..76d92bb --- /dev/null +++ b/third_party/gflags/test/flagfile.3 @@ -0,0 +1 @@ +--flagfile=flagfile.2 \ No newline at end of file diff --git a/third_party/gflags/test/gflags_build.py.in b/third_party/gflags/test/gflags_build.py.in new file mode 100644 index 0000000..a8cba2b --- /dev/null +++ b/third_party/gflags/test/gflags_build.py.in @@ -0,0 +1,43 @@ +#!/usr/bin/env python + +import os +import sys +import subprocess +import shutil + +CMAKE = '@CMAKE_COMMAND@' +CMAKE_BUILD_TYPE = '@CMAKE_BUILD_TYPE@' +TMPDIR = '@TMPDIR@' +SRCDIR = '@SRCDIR@' +GFLAGS_DIR = '@gflags_BINARY_DIR@' + +if __name__ == "__main__": + if len(sys.argv) != 4: + sys.stderr.write(' '.join(['usage:', sys.argv[0], ' \n'])) + sys.exit(1) + test_name = sys.argv[1] + srcdir = sys.argv[2] + expect_fail = (sys.argv[3].lower() in ['true', 'yes', 'on', '1']) + bindir = os.path.join(TMPDIR, test_name) + if TMPDIR == '': + sys.stderr.write('Temporary directory not set!\n') + sys.exit(1) + # create build directory + if os.path.isdir(bindir): shutil.rmtree(bindir) + os.makedirs(bindir) + # configure the build tree + if subprocess.call([CMAKE, '-DCMAKE_BUILD_TYPE:STRING='+CMAKE_BUILD_TYPE, + '-Dgflags_DIR:PATH='+GFLAGS_DIR, + '-DTEST_NAME:STRING='+test_name, srcdir], cwd=bindir) != 0: + sys.stderr.write('Failed to configure the build tree!\n') + sys.exit(1) + # build the test project + exit_code = subprocess.call([CMAKE, '--build', bindir, '--config', CMAKE_BUILD_TYPE], cwd=bindir) + if expect_fail == True: + if exit_code == 0: + sys.stderr.write('Build expected to fail, but it succeeded!\n') + sys.exit(1) + else: + sys.stderr.write('Build failed as expected\n') + exit_code = 0 + sys.exit(exit_code) diff --git a/third_party/gflags/test/gflags_declare_flags.cc b/third_party/gflags/test/gflags_declare_flags.cc new file mode 100755 index 0000000..3d952a8 --- /dev/null +++ b/third_party/gflags/test/gflags_declare_flags.cc @@ -0,0 +1,12 @@ +#define GFLAGS_DLL_DECLARE_FLAG + +#include +#include + +DECLARE_string(message); // in gflags_delcare_test.cc + +void print_message(); +void print_message() +{ + std::cout << FLAGS_message << std::endl; +} diff --git a/third_party/gflags/test/gflags_declare_test.cc b/third_party/gflags/test/gflags_declare_test.cc new file mode 100644 index 0000000..47d11c2 --- /dev/null +++ b/third_party/gflags/test/gflags_declare_test.cc @@ -0,0 +1,12 @@ +#include + +DEFINE_string(message, "", "The message to print"); +void print_message(); // in gflags_declare_flags.cc + +int main(int argc, char **argv) +{ + GFLAGS_NAMESPACE::SetUsageMessage("Test compilation and use of gflags_declare.h"); + GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true); + print_message(); + return 0; +} diff --git a/third_party/gflags/test/gflags_strip_flags_test.cc b/third_party/gflags/test/gflags_strip_flags_test.cc new file mode 100755 index 0000000..143f0c6 --- /dev/null +++ b/third_party/gflags/test/gflags_strip_flags_test.cc @@ -0,0 +1,60 @@ +// Copyright (c) 2011, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// --- +// Author: csilvers@google.com (Craig Silverstein) +// +// A simple program that uses STRIP_FLAG_HELP. We'll have a shell +// script that runs 'strings' over this program and makes sure +// that the help string is not in there. + +#define STRIP_FLAG_HELP 1 +#include + +#include + +using GFLAGS_NAMESPACE::SetUsageMessage; +using GFLAGS_NAMESPACE::ParseCommandLineFlags; + + +DEFINE_bool(test, true, "This text should be stripped out"); + +int main(int argc, char** argv) { + SetUsageMessage("Usage message"); + ParseCommandLineFlags(&argc, &argv, false); + + // Unfortunately, for us, libtool can replace executables with a shell + // script that does some work before calling the 'real' executable + // under a different name. We need the 'real' executable name to run + // 'strings' on it, so we construct this binary to print the real + // name (argv[0]) on stdout when run. + puts(argv[0]); + + return 0; +} diff --git a/third_party/gflags/test/gflags_strip_flags_test.cmake b/third_party/gflags/test/gflags_strip_flags_test.cmake new file mode 100644 index 0000000..5bb5cc1 --- /dev/null +++ b/third_party/gflags/test/gflags_strip_flags_test.cmake @@ -0,0 +1,7 @@ +if (NOT BINARY) + message (FATAL_ERROR "BINARY file to check not specified!") +endif () +file (STRINGS "${BINARY}" strings REGEX "This text should be stripped out") +if (strings) + message (FATAL_ERROR "Text not stripped from binary like it should be: ${BINARY}") +endif () diff --git a/third_party/gflags/test/gflags_unittest.cc b/third_party/gflags/test/gflags_unittest.cc new file mode 100755 index 0000000..9a922ef --- /dev/null +++ b/third_party/gflags/test/gflags_unittest.cc @@ -0,0 +1,1572 @@ +// Copyright (c) 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// --- +// +// For now, this unit test does not cover all features of +// gflags.cc + +#include + +#include "config.h" +#include "util.h" + +#include // for isinf() and isnan() +#include +#include +#include +#ifdef HAVE_UNISTD_H +# include // for unlink() +#endif +#include +#include +TEST_INIT +EXPECT_DEATH_INIT + +// I don't actually use this header file, but #include it under the +// old location to make sure that the include-header-forwarding +// works. But don't bother on windows; the windows port is so new +// it never had the old location-names. +#ifndef _MSC_VER +#include +void (*unused_fn)() = &GFLAGS_NAMESPACE::HandleCommandLineCompletions; +#endif + +using std::string; +using std::vector; +using GFLAGS_NAMESPACE::int32; +using GFLAGS_NAMESPACE::FlagRegisterer; +using GFLAGS_NAMESPACE::StringFromEnv; +using GFLAGS_NAMESPACE::RegisterFlagValidator; +using GFLAGS_NAMESPACE::CommandLineFlagInfo; +using GFLAGS_NAMESPACE::GetAllFlags; + +DEFINE_string(test_tmpdir, "", "Dir we use for temp files"); +DEFINE_string(srcdir, StringFromEnv("SRCDIR", "."), "Source-dir root, needed to find gflags_unittest_flagfile"); + +DECLARE_string(tryfromenv); // in gflags.cc + +DEFINE_bool(test_bool, false, "tests bool-ness"); +DEFINE_int32(test_int32, -1, ""); +DEFINE_int64(test_int64, -2, ""); +DEFINE_uint32(test_uint32, 1, ""); +DEFINE_uint64(test_uint64, 2, ""); +DEFINE_double(test_double, -1.0, ""); +DEFINE_string(test_string, "initial", ""); + +// +// The below ugliness gets some additional code coverage in the -helpxml +// and -helpmatch test cases having to do with string lengths and formatting +// +DEFINE_bool(test_bool_with_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_long_name, + false, + "extremely_extremely_extremely_extremely_extremely_extremely_extremely_extremely_long_meaning"); + +DEFINE_string(test_str1, "initial", ""); +DEFINE_string(test_str2, "initial", ""); +DEFINE_string(test_str3, "initial", ""); + +// This is used to test setting tryfromenv manually +DEFINE_string(test_tryfromenv, "initial", ""); + +// Don't try this at home! +static int changeable_var = 12; +DEFINE_int32(changeable_var, ++changeable_var, ""); + +static int changeable_bool_var = 8008; +DEFINE_bool(changeable_bool_var, ++changeable_bool_var == 8009, ""); + +static int changeable_string_var = 0; +static string ChangeableString() { + char r[] = {static_cast('0' + ++changeable_string_var), '\0'}; + return r; +} +DEFINE_string(changeable_string_var, ChangeableString(), ""); + +// These are never used in this unittest, but can be used by +// gflags_unittest.sh when it needs to specify flags +// that are legal for gflags_unittest but don't need to +// be a particular value. +DEFINE_bool(unused_bool, true, "unused bool-ness"); +DEFINE_int32(unused_int32, -1001, ""); +DEFINE_int64(unused_int64, -2001, ""); +DEFINE_uint32(unused_uint32, 1000, ""); +DEFINE_uint64(unused_uint64, 2000, ""); +DEFINE_double(unused_double, -1000.0, ""); +DEFINE_string(unused_string, "unused", ""); + +// These flags are used by gflags_unittest.sh +DEFINE_bool(changed_bool1, false, "changed"); +DEFINE_bool(changed_bool2, false, "changed"); +DEFINE_bool(long_helpstring, false, + "This helpstring goes on forever and ever and ever and ever and " + "ever and ever and ever and ever and ever and ever and ever and " + "ever and ever and ever and ever and ever and ever and ever and " + "ever and ever and ever and ever and ever and ever and ever and " + "ever and ever and ever and ever and ever and ever and ever and " + "ever and ever and ever and ever and ever and ever and ever and " + "ever and ever and ever and ever and ever and ever and ever and " + "ever and ever and ever and ever and ever and ever and ever and " + "ever and ever and ever and ever and ever and ever and ever and " + "ever and ever and ever and ever and ever and ever and ever and " + "ever. This is the end of a long helpstring"); + + +static bool AlwaysFail(const char* flag, bool value) { return value == false; } +DEFINE_bool(always_fail, false, "will fail to validate when you set it"); +DEFINE_validator(always_fail, AlwaysFail); + +// See the comment by GetAllFlags in gflags.h +static bool DeadlockIfCantLockInValidators(const char* flag, bool value) { + if (!value) { + return true; + } + vector dummy; + GetAllFlags(&dummy); + return true; +} +DEFINE_bool(deadlock_if_cant_lock, + false, + "will deadlock if set to true and " + "if locking of registry in validators fails."); +DEFINE_validator(deadlock_if_cant_lock, DeadlockIfCantLockInValidators); + +#define MAKEFLAG(x) DEFINE_int32(test_flag_num##x, x, "Test flag") + +// Define 10 flags +#define MAKEFLAG10(x) \ + MAKEFLAG(x##0); \ + MAKEFLAG(x##1); \ + MAKEFLAG(x##2); \ + MAKEFLAG(x##3); \ + MAKEFLAG(x##4); \ + MAKEFLAG(x##5); \ + MAKEFLAG(x##6); \ + MAKEFLAG(x##7); \ + MAKEFLAG(x##8); \ + MAKEFLAG(x##9) + +// Define 100 flags +#define MAKEFLAG100(x) \ + MAKEFLAG10(x##0); \ + MAKEFLAG10(x##1); \ + MAKEFLAG10(x##2); \ + MAKEFLAG10(x##3); \ + MAKEFLAG10(x##4); \ + MAKEFLAG10(x##5); \ + MAKEFLAG10(x##6); \ + MAKEFLAG10(x##7); \ + MAKEFLAG10(x##8); \ + MAKEFLAG10(x##9) + +// Define a bunch of command-line flags. Each occurrence of the MAKEFLAG100 +// macro defines 100 integer flags. This lets us test the effect of having +// many flags on startup time. +MAKEFLAG100(1); +MAKEFLAG100(2); +MAKEFLAG100(3); +MAKEFLAG100(4); +MAKEFLAG100(5); +MAKEFLAG100(6); +MAKEFLAG100(7); +MAKEFLAG100(8); +MAKEFLAG100(9); +MAKEFLAG100(10); +MAKEFLAG100(11); +MAKEFLAG100(12); +MAKEFLAG100(13); +MAKEFLAG100(14); +MAKEFLAG100(15); + +#undef MAKEFLAG100 +#undef MAKEFLAG10 +#undef MAKEFLAG + +// This is a pseudo-flag -- we want to register a flag with a filename +// at the top level, but there is no way to do this except by faking +// the filename. +namespace fLI { + static const int32 FLAGS_nonotldflag1 = 12; + int32 FLAGS_tldflag1 = FLAGS_nonotldflag1; + int32 FLAGS_notldflag1 = FLAGS_nonotldflag1; + static FlagRegisterer o_tldflag1( + "tldflag1", + "should show up in --helpshort", "gflags_unittest.cc", + &FLAGS_tldflag1, &FLAGS_notldflag1); +} +using fLI::FLAGS_tldflag1; + +namespace fLI { + static const int32 FLAGS_nonotldflag2 = 23; + int32 FLAGS_tldflag2 = FLAGS_nonotldflag2; + int32 FLAGS_notldflag2 = FLAGS_nonotldflag2; + static FlagRegisterer o_tldflag2( + "tldflag2", + "should show up in --helpshort", "gflags_unittest.", + &FLAGS_tldflag2, &FLAGS_notldflag2); +} +using fLI::FLAGS_tldflag2; + +namespace GFLAGS_NAMESPACE { + +namespace { + + +static string TmpFile(const string& basename) { +#ifdef _MSC_VER + return FLAGS_test_tmpdir + "\\" + basename; +#else + return FLAGS_test_tmpdir + "/" + basename; +#endif +} + +// Returns the definition of the --flagfile flag to be used in the tests. +// Must be called after ParseCommandLineFlags(). +static const char* GetFlagFileFlag() { +#ifdef _MSC_VER + static const string flagfile = FLAGS_srcdir + "\\gflags_unittest_flagfile"; +#else + static const string flagfile = FLAGS_srcdir + "/gflags_unittest_flagfile"; +#endif + static const string flagfile_flag = string("--flagfile=") + flagfile; + return flagfile_flag.c_str(); +} + + +// Defining a variable of type CompileAssertTypesEqual will cause a +// compiler error iff T1 and T2 are different types. +template +struct CompileAssertTypesEqual; + +template +struct CompileAssertTypesEqual { +}; + + +template +void AssertIsType(Actual& x) { + CompileAssertTypesEqual(); +} + +// Verify all the flags are the right type. +TEST(FlagTypes, FlagTypes) { + AssertIsType(FLAGS_test_bool); + AssertIsType(FLAGS_test_int32); + AssertIsType(FLAGS_test_int64); + AssertIsType(FLAGS_test_uint32); + AssertIsType(FLAGS_test_uint64); + AssertIsType(FLAGS_test_double); + AssertIsType(FLAGS_test_string); +} + +#ifdef GTEST_HAS_DEATH_TEST +// Death tests for "help" options. +// +// The help system automatically calls gflags_exitfunc(1) when you specify any of +// the help-related flags ("-helpmatch", "-helpxml") so we can't test +// those mainline. + +// Tests that "-helpmatch" causes the process to die. +TEST(ReadFlagsFromStringDeathTest, HelpMatch) { + EXPECT_DEATH(ReadFlagsFromString("-helpmatch=base", GetArgv0(), true), + ""); +} + + +// Tests that "-helpxml" causes the process to die. +TEST(ReadFlagsFromStringDeathTest, HelpXml) { + EXPECT_DEATH(ReadFlagsFromString("-helpxml", GetArgv0(), true), + ""); +} +#endif + + +// A subroutine needed for testing reading flags from a string. +void TestFlagString(const string& flags, + const string& expected_string, + bool expected_bool, + int32 expected_int32, + double expected_double) { + EXPECT_TRUE(ReadFlagsFromString(flags, + GetArgv0(), + // errors are fatal + true)); + + EXPECT_EQ(expected_string, FLAGS_test_string); + EXPECT_EQ(expected_bool, FLAGS_test_bool); + EXPECT_EQ(expected_int32, FLAGS_test_int32); + EXPECT_DOUBLE_EQ(expected_double, FLAGS_test_double); +} + + +// Tests reading flags from a string. +TEST(FlagFileTest, ReadFlagsFromString) { + TestFlagString( + // Flag string + "-test_string=continued\n" + "# some comments are in order\n" + "# some\n" + " # comments\n" + "#are\n" + " #trickier\n" + "# than others\n" + "-test_bool=true\n" + " -test_int32=1\n" + "-test_double=0.0\n", + // Expected values + "continued", + true, + 1, + 0.0); + + TestFlagString( + // Flag string + "# let's make sure it can update values\n" + "-test_string=initial\n" + "-test_bool=false\n" + "-test_int32=123\n" + "-test_double=123.0\n", + // Expected values + "initial", + false, + 123, + 123.0); + + // Test that flags can use dashes instead of underscores. + TestFlagString( + // Flag string + "-test-string=initial\n" + "--test-bool=false\n" + "--test-int32=123\n" + "--test-double=123.0\n", + // Expected values + "initial", + false, + 123, + 123.0); +} + +// Tests the filename part of the flagfile +TEST(FlagFileTest, FilenamesOurfileLast) { + FLAGS_test_string = "initial"; + FLAGS_test_bool = false; + FLAGS_test_int32 = -1; + FLAGS_test_double = -1.0; + TestFlagString( + // Flag string + "-test_string=continued\n" + "# some comments are in order\n" + "# some\n" + " # comments\n" + "#are\n" + " #trickier\n" + "# than others\n" + "not_our_filename\n" + "-test_bool=true\n" + " -test_int32=1\n" + "gflags_unittest\n" + "-test_double=1000.0\n", + // Expected values + "continued", + false, + -1, + 1000.0); +} + +TEST(FlagFileTest, FilenamesOurfileFirst) { + FLAGS_test_string = "initial"; + FLAGS_test_bool = false; + FLAGS_test_int32 = -1; + FLAGS_test_double = -1.0; + TestFlagString( + // Flag string + "-test_string=continued\n" + "# some comments are in order\n" + "# some\n" + " # comments\n" + "#are\n" + " #trickier\n" + "# than others\n" + "gflags_unittest\n" + "-test_bool=true\n" + " -test_int32=1\n" + "not_our_filename\n" + "-test_double=1000.0\n", + // Expected values + "continued", + true, + 1, + -1.0); +} + +#if defined(HAVE_FNMATCH_H) || defined(HAVE_SHLWAPI_H) // otherwise glob isn't supported +TEST(FlagFileTest, FilenamesOurfileGlob) { + FLAGS_test_string = "initial"; + FLAGS_test_bool = false; + FLAGS_test_int32 = -1; + FLAGS_test_double = -1.0; + TestFlagString( + // Flag string + "-test_string=continued\n" + "# some comments are in order\n" + "# some\n" + " # comments\n" + "#are\n" + " #trickier\n" + "# than others\n" + "*flags*\n" + "-test_bool=true\n" + " -test_int32=1\n" + "flags\n" + "-test_double=1000.0\n", + // Expected values + "continued", + true, + 1, + -1.0); +} + +TEST(FlagFileTest, FilenamesOurfileInBigList) { + FLAGS_test_string = "initial"; + FLAGS_test_bool = false; + FLAGS_test_int32 = -1; + FLAGS_test_double = -1.0; + TestFlagString( + // Flag string + "-test_string=continued\n" + "# some comments are in order\n" + "# some\n" + " # comments\n" + "#are\n" + " #trickier\n" + "# than others\n" + "*first* *flags* *third*\n" + "-test_bool=true\n" + " -test_int32=1\n" + "flags\n" + "-test_double=1000.0\n", + // Expected values + "continued", + true, + 1, + -1.0); +} +#endif // defined(HAVE_FNMATCH_H) || defined(HAVE_SHLWAPI_H) + +// Tests that a failed flag-from-string read keeps flags at default values +TEST(FlagFileTest, FailReadFlagsFromString) { + FLAGS_test_int32 = 119; + string flags("# let's make sure it can update values\n" + "-test_string=non_initial\n" + "-test_bool=false\n" + "-test_int32=123\n" + "-test_double=illegal\n"); + + EXPECT_FALSE(ReadFlagsFromString(flags, + GetArgv0(), + // errors are fatal + false)); + + EXPECT_EQ(119, FLAGS_test_int32); + EXPECT_EQ("initial", FLAGS_test_string); +} + +// Tests that flags can be set to ordinary values. +TEST(SetFlagValueTest, OrdinaryValues) { + EXPECT_EQ("initial", FLAGS_test_str1); + + SetCommandLineOptionWithMode("test_str1", "second", SET_FLAG_IF_DEFAULT); + EXPECT_EQ("second", FLAGS_test_str1); // set; was default + + SetCommandLineOptionWithMode("test_str1", "third", SET_FLAG_IF_DEFAULT); + EXPECT_EQ("second", FLAGS_test_str1); // already set once + + FLAGS_test_str1 = "initial"; + SetCommandLineOptionWithMode("test_str1", "third", SET_FLAG_IF_DEFAULT); + EXPECT_EQ("initial", FLAGS_test_str1); // still already set before + + SetCommandLineOptionWithMode("test_str1", "third", SET_FLAGS_VALUE); + EXPECT_EQ("third", FLAGS_test_str1); // changed value + + SetCommandLineOptionWithMode("test_str1", "fourth", SET_FLAGS_DEFAULT); + EXPECT_EQ("third", FLAGS_test_str1); + // value not changed (already set before) + + EXPECT_EQ("initial", FLAGS_test_str2); + + SetCommandLineOptionWithMode("test_str2", "second", SET_FLAGS_DEFAULT); + EXPECT_EQ("second", FLAGS_test_str2); // changed (was default) + + FLAGS_test_str2 = "extra"; + EXPECT_EQ("extra", FLAGS_test_str2); + + FLAGS_test_str2 = "second"; + SetCommandLineOptionWithMode("test_str2", "third", SET_FLAGS_DEFAULT); + EXPECT_EQ("third", FLAGS_test_str2); // still changed (was equal to default) + + SetCommandLineOptionWithMode("test_str2", "fourth", SET_FLAG_IF_DEFAULT); + EXPECT_EQ("fourth", FLAGS_test_str2); // changed (was default) + + EXPECT_EQ("initial", FLAGS_test_str3); + + SetCommandLineOptionWithMode("test_str3", "second", SET_FLAGS_DEFAULT); + EXPECT_EQ("second", FLAGS_test_str3); // changed + + FLAGS_test_str3 = "third"; + SetCommandLineOptionWithMode("test_str3", "fourth", SET_FLAGS_DEFAULT); + EXPECT_EQ("third", FLAGS_test_str3); // not changed (was set) + + SetCommandLineOptionWithMode("test_str3", "fourth", SET_FLAG_IF_DEFAULT); + EXPECT_EQ("third", FLAGS_test_str3); // not changed (was set) + + SetCommandLineOptionWithMode("test_str3", "fourth", SET_FLAGS_VALUE); + EXPECT_EQ("fourth", FLAGS_test_str3); // changed value +} + + +// Tests that flags can be set to exceptional values. +// Note: apparently MINGW doesn't parse inf and nan correctly: +// http://www.mail-archive.com/bug-gnulib@gnu.org/msg09573.html +// This url says FreeBSD also has a problem, but I didn't see that. +TEST(SetFlagValueTest, ExceptionalValues) { +#if defined(isinf) && !defined(__MINGW32__) + EXPECT_EQ("test_double set to inf\n", + SetCommandLineOption("test_double", "inf")); + EXPECT_INF(FLAGS_test_double); + + EXPECT_EQ("test_double set to inf\n", + SetCommandLineOption("test_double", "INF")); + EXPECT_INF(FLAGS_test_double); +#endif + + // set some bad values + EXPECT_EQ("", + SetCommandLineOption("test_double", "0.1xxx")); + EXPECT_EQ("", + SetCommandLineOption("test_double", " ")); + EXPECT_EQ("", + SetCommandLineOption("test_double", "")); +#if defined(isinf) && !defined(__MINGW32__) + EXPECT_EQ("test_double set to -inf\n", + SetCommandLineOption("test_double", "-inf")); + EXPECT_INF(FLAGS_test_double); + EXPECT_GT(0, FLAGS_test_double); +#endif + +#if defined(isnan) && !defined(__MINGW32__) + EXPECT_EQ("test_double set to nan\n", + SetCommandLineOption("test_double", "NaN")); + EXPECT_NAN(FLAGS_test_double); +#endif +} + +// Tests that integer flags can be specified in many ways +TEST(SetFlagValueTest, DifferentRadices) { + EXPECT_EQ("test_int32 set to 12\n", + SetCommandLineOption("test_int32", "12")); + + EXPECT_EQ("test_int32 set to 16\n", + SetCommandLineOption("test_int32", "0x10")); + + EXPECT_EQ("test_int32 set to 34\n", + SetCommandLineOption("test_int32", "0X22")); + + // Leading 0 is *not* octal; it's still decimal + EXPECT_EQ("test_int32 set to 10\n", + SetCommandLineOption("test_int32", "010")); +} + +// Tests what happens when you try to set a flag to an illegal value +TEST(SetFlagValueTest, IllegalValues) { + FLAGS_test_bool = true; + FLAGS_test_int32 = 119; + FLAGS_test_int64 = 1191; + FLAGS_test_uint32 = 11911; + FLAGS_test_uint64 = 119111; + + EXPECT_EQ("", + SetCommandLineOption("test_bool", "12")); + + EXPECT_EQ("", + SetCommandLineOption("test_uint32", "-1970")); + + EXPECT_EQ("", + SetCommandLineOption("test_int32", "7000000000000")); + + EXPECT_EQ("", + SetCommandLineOption("test_uint64", "-1")); + + EXPECT_EQ("", + SetCommandLineOption("test_int64", "not a number!")); + + // Test the empty string with each type of input + EXPECT_EQ("", SetCommandLineOption("test_bool", "")); + EXPECT_EQ("", SetCommandLineOption("test_int32", "")); + EXPECT_EQ("", SetCommandLineOption("test_int64", "")); + EXPECT_EQ("", SetCommandLineOption("test_uint32", "")); + EXPECT_EQ("", SetCommandLineOption("test_uint64", "")); + EXPECT_EQ("", SetCommandLineOption("test_double", "")); + EXPECT_EQ("test_string set to \n", SetCommandLineOption("test_string", "")); + + EXPECT_TRUE(FLAGS_test_bool); + EXPECT_EQ(119, FLAGS_test_int32); + EXPECT_EQ(1191, FLAGS_test_int64); + EXPECT_EQ(11911, FLAGS_test_uint32); + EXPECT_EQ(119111, FLAGS_test_uint64); +} + + +// Tests that we only evaluate macro args once +TEST(MacroArgs, EvaluateOnce) { + EXPECT_EQ(13, FLAGS_changeable_var); + // Make sure we don't ++ the value somehow, when evaluating the flag. + EXPECT_EQ(13, FLAGS_changeable_var); + // Make sure the macro only evaluated this var once. + EXPECT_EQ(13, changeable_var); + // Make sure the actual value and default value are the same + SetCommandLineOptionWithMode("changeable_var", "21", SET_FLAG_IF_DEFAULT); + EXPECT_EQ(21, FLAGS_changeable_var); +} + +TEST(MacroArgs, EvaluateOnceBool) { + EXPECT_TRUE(FLAGS_changeable_bool_var); + EXPECT_TRUE(FLAGS_changeable_bool_var); + EXPECT_EQ(8009, changeable_bool_var); + SetCommandLineOptionWithMode("changeable_bool_var", "false", + SET_FLAG_IF_DEFAULT); + EXPECT_FALSE(FLAGS_changeable_bool_var); +} + +TEST(MacroArgs, EvaluateOnceStrings) { + EXPECT_EQ("1", FLAGS_changeable_string_var); + EXPECT_EQ("1", FLAGS_changeable_string_var); + EXPECT_EQ(1, changeable_string_var); + SetCommandLineOptionWithMode("changeable_string_var", "different", + SET_FLAG_IF_DEFAULT); + EXPECT_EQ("different", FLAGS_changeable_string_var); +} + +// Tests that the FooFromEnv does the right thing +TEST(FromEnvTest, LegalValues) { + setenv("BOOL_VAL1", "true", 1); + setenv("BOOL_VAL2", "false", 1); + setenv("BOOL_VAL3", "1", 1); + setenv("BOOL_VAL4", "F", 1); + EXPECT_TRUE(BoolFromEnv("BOOL_VAL1", false)); + EXPECT_FALSE(BoolFromEnv("BOOL_VAL2", true)); + EXPECT_TRUE(BoolFromEnv("BOOL_VAL3", false)); + EXPECT_FALSE(BoolFromEnv("BOOL_VAL4", true)); + EXPECT_TRUE(BoolFromEnv("BOOL_VAL_UNKNOWN", true)); + EXPECT_FALSE(BoolFromEnv("BOOL_VAL_UNKNOWN", false)); + + setenv("INT_VAL1", "1", 1); + setenv("INT_VAL2", "-1", 1); + EXPECT_EQ(1, Int32FromEnv("INT_VAL1", 10)); + EXPECT_EQ(-1, Int32FromEnv("INT_VAL2", 10)); + EXPECT_EQ(10, Int32FromEnv("INT_VAL_UNKNOWN", 10)); + + setenv("INT_VAL3", "4294967295", 1); + EXPECT_EQ(1, Uint32FromEnv("INT_VAL1", 10)); + EXPECT_EQ(4294967295L, Uint32FromEnv("INT_VAL3", 30)); + EXPECT_EQ(10, Uint32FromEnv("INT_VAL_UNKNOWN", 10)); + + setenv("INT_VAL4", "1099511627776", 1); + EXPECT_EQ(1, Int64FromEnv("INT_VAL1", 20)); + EXPECT_EQ(-1, Int64FromEnv("INT_VAL2", 20)); + EXPECT_EQ(1099511627776LL, Int64FromEnv("INT_VAL4", 20)); + EXPECT_EQ(20, Int64FromEnv("INT_VAL_UNKNOWN", 20)); + + EXPECT_EQ(1, Uint64FromEnv("INT_VAL1", 30)); + EXPECT_EQ(1099511627776ULL, Uint64FromEnv("INT_VAL4", 30)); + EXPECT_EQ(30, Uint64FromEnv("INT_VAL_UNKNOWN", 30)); + + // I pick values here that can be easily represented exactly in floating-point + setenv("DOUBLE_VAL1", "0.0", 1); + setenv("DOUBLE_VAL2", "1.0", 1); + setenv("DOUBLE_VAL3", "-1.0", 1); + EXPECT_EQ(0.0, DoubleFromEnv("DOUBLE_VAL1", 40.0)); + EXPECT_EQ(1.0, DoubleFromEnv("DOUBLE_VAL2", 40.0)); + EXPECT_EQ(-1.0, DoubleFromEnv("DOUBLE_VAL3", 40.0)); + EXPECT_EQ(40.0, DoubleFromEnv("DOUBLE_VAL_UNKNOWN", 40.0)); + + setenv("STRING_VAL1", "", 1); + setenv("STRING_VAL2", "my happy string!", 1); + EXPECT_STREQ("", StringFromEnv("STRING_VAL1", "unknown")); + EXPECT_STREQ("my happy string!", StringFromEnv("STRING_VAL2", "unknown")); + EXPECT_STREQ("unknown", StringFromEnv("STRING_VAL_UNKNOWN", "unknown")); +} + +#ifdef GTEST_HAS_DEATH_TEST +// Tests that the FooFromEnv dies on parse-error +TEST(FromEnvDeathTest, IllegalValues) { + setenv("BOOL_BAD1", "so true!", 1); + setenv("BOOL_BAD2", "", 1); + EXPECT_DEATH(BoolFromEnv("BOOL_BAD1", false), "error parsing env variable"); + EXPECT_DEATH(BoolFromEnv("BOOL_BAD2", true), "error parsing env variable"); + + setenv("INT_BAD1", "one", 1); + setenv("INT_BAD2", "100000000000000000", 1); + setenv("INT_BAD3", "0xx10", 1); + setenv("INT_BAD4", "", 1); + EXPECT_DEATH(Int32FromEnv("INT_BAD1", 10), "error parsing env variable"); + EXPECT_DEATH(Int32FromEnv("INT_BAD2", 10), "error parsing env variable"); + EXPECT_DEATH(Int32FromEnv("INT_BAD3", 10), "error parsing env variable"); + EXPECT_DEATH(Int32FromEnv("INT_BAD4", 10), "error parsing env variable"); + + EXPECT_DEATH(Uint32FromEnv("INT_BAD1", 10), "error parsing env variable"); + EXPECT_DEATH(Uint32FromEnv("INT_BAD2", 10), "error parsing env variable"); + EXPECT_DEATH(Uint32FromEnv("INT_BAD3", 10), "error parsing env variable"); + EXPECT_DEATH(Uint32FromEnv("INT_BAD4", 10), "error parsing env variable"); + + setenv("BIGINT_BAD1", "18446744073709551616000", 1); + EXPECT_DEATH(Int64FromEnv("INT_BAD1", 20), "error parsing env variable"); + EXPECT_DEATH(Int64FromEnv("INT_BAD3", 20), "error parsing env variable"); + EXPECT_DEATH(Int64FromEnv("INT_BAD4", 20), "error parsing env variable"); + EXPECT_DEATH(Int64FromEnv("BIGINT_BAD1", 200), "error parsing env variable"); + + setenv("BIGINT_BAD2", "-1", 1); + EXPECT_DEATH(Uint64FromEnv("INT_BAD1", 30), "error parsing env variable"); + EXPECT_DEATH(Uint64FromEnv("INT_BAD3", 30), "error parsing env variable"); + EXPECT_DEATH(Uint64FromEnv("INT_BAD4", 30), "error parsing env variable"); + EXPECT_DEATH(Uint64FromEnv("BIGINT_BAD1", 30), "error parsing env variable"); + // TODO(csilvers): uncomment this when we disallow negative numbers for uint64 +#if 0 + EXPECT_DEATH(Uint64FromEnv("BIGINT_BAD2", 30), "error parsing env variable"); +#endif + + setenv("DOUBLE_BAD1", "0.0.0", 1); + setenv("DOUBLE_BAD2", "", 1); + EXPECT_DEATH(DoubleFromEnv("DOUBLE_BAD1", 40.0), "error parsing env variable"); + EXPECT_DEATH(DoubleFromEnv("DOUBLE_BAD2", 40.0), "error parsing env variable"); +} +#endif + + +// Tests that FlagSaver can save the states of string flags. +TEST(FlagSaverTest, CanSaveStringFlagStates) { + // 1. Initializes the flags. + + // State of flag test_str1: + // default value - "initial" + // current value - "initial" + // not set - true + + SetCommandLineOptionWithMode("test_str2", "second", SET_FLAGS_VALUE); + // State of flag test_str2: + // default value - "initial" + // current value - "second" + // not set - false + + SetCommandLineOptionWithMode("test_str3", "second", SET_FLAGS_DEFAULT); + // State of flag test_str3: + // default value - "second" + // current value - "second" + // not set - true + + // 2. Saves the flag states. + + { + FlagSaver fs; + + // 3. Modifies the flag states. + + SetCommandLineOptionWithMode("test_str1", "second", SET_FLAGS_VALUE); + EXPECT_EQ("second", FLAGS_test_str1); + // State of flag test_str1: + // default value - "second" + // current value - "second" + // not set - true + + SetCommandLineOptionWithMode("test_str2", "third", SET_FLAGS_DEFAULT); + EXPECT_EQ("second", FLAGS_test_str2); + // State of flag test_str2: + // default value - "third" + // current value - "second" + // not set - false + + SetCommandLineOptionWithMode("test_str3", "third", SET_FLAGS_VALUE); + EXPECT_EQ("third", FLAGS_test_str3); + // State of flag test_str1: + // default value - "second" + // current value - "third" + // not set - false + + // 4. Restores the flag states. + } + + // 5. Verifies that the states were restored. + + // Verifies that the value of test_str1 was restored. + EXPECT_EQ("initial", FLAGS_test_str1); + // Verifies that the "not set" attribute of test_str1 was restored to true. + SetCommandLineOptionWithMode("test_str1", "second", SET_FLAG_IF_DEFAULT); + EXPECT_EQ("second", FLAGS_test_str1); + + // Verifies that the value of test_str2 was restored. + EXPECT_EQ("second", FLAGS_test_str2); + // Verifies that the "not set" attribute of test_str2 was restored to false. + SetCommandLineOptionWithMode("test_str2", "fourth", SET_FLAG_IF_DEFAULT); + EXPECT_EQ("second", FLAGS_test_str2); + + // Verifies that the value of test_str3 was restored. + EXPECT_EQ("second", FLAGS_test_str3); + // Verifies that the "not set" attribute of test_str3 was restored to true. + SetCommandLineOptionWithMode("test_str3", "fourth", SET_FLAG_IF_DEFAULT); + EXPECT_EQ("fourth", FLAGS_test_str3); +} + + +// Tests that FlagSaver can save the values of various-typed flags. +TEST(FlagSaverTest, CanSaveVariousTypedFlagValues) { + // Initializes the flags. + FLAGS_test_bool = false; + FLAGS_test_int32 = -1; + FLAGS_test_uint32 = 2; + FLAGS_test_int64 = -3; + FLAGS_test_uint64 = 4; + FLAGS_test_double = 5.0; + FLAGS_test_string = "good"; + + // Saves the flag states. + { + FlagSaver fs; + + // Modifies the flags. + FLAGS_test_bool = true; + FLAGS_test_int32 = -5; + FLAGS_test_uint32 = 6; + FLAGS_test_int64 = -7; + FLAGS_test_uint64 = 8; + FLAGS_test_double = 8.0; + FLAGS_test_string = "bad"; + + // Restores the flag states. + } + + // Verifies the flag values were restored. + EXPECT_FALSE(FLAGS_test_bool); + EXPECT_EQ(-1, FLAGS_test_int32); + EXPECT_EQ(2, FLAGS_test_uint32); + EXPECT_EQ(-3, FLAGS_test_int64); + EXPECT_EQ(4, FLAGS_test_uint64); + EXPECT_DOUBLE_EQ(5.0, FLAGS_test_double); + EXPECT_EQ("good", FLAGS_test_string); +} + +TEST(GetAllFlagsTest, BaseTest) { + vector flags; + GetAllFlags(&flags); + bool found_test_bool = false; + vector::const_iterator i; + for (i = flags.begin(); i != flags.end(); ++i) { + if (i->name == "test_bool") { + found_test_bool = true; + EXPECT_EQ(i->type, "bool"); + EXPECT_EQ(i->default_value, "false"); + EXPECT_EQ(i->flag_ptr, &FLAGS_test_bool); + break; + } + } + EXPECT_TRUE(found_test_bool); +} + +TEST(ShowUsageWithFlagsTest, BaseTest) { + // TODO(csilvers): test this by allowing output other than to stdout. + // Not urgent since this functionality is tested via + // gflags_unittest.sh, though only through use of --help. +} + +TEST(ShowUsageWithFlagsRestrictTest, BaseTest) { + // TODO(csilvers): test this by allowing output other than to stdout. + // Not urgent since this functionality is tested via + // gflags_unittest.sh, though only through use of --helpmatch. +} + +// Note: all these argv-based tests depend on SetArgv being called +// before ParseCommandLineFlags() in main(), below. +TEST(GetArgvsTest, BaseTest) { + vector argvs = GetArgvs(); + EXPECT_EQ(4, argvs.size()); + EXPECT_EQ("/test/argv/for/gflags_unittest", argvs[0]); + EXPECT_EQ("argv 2", argvs[1]); + EXPECT_EQ("3rd argv", argvs[2]); + EXPECT_EQ("argv #4", argvs[3]); +} + +TEST(GetArgvTest, BaseTest) { + EXPECT_STREQ("/test/argv/for/gflags_unittest " + "argv 2 3rd argv argv #4", GetArgv()); +} + +TEST(GetArgv0Test, BaseTest) { + EXPECT_STREQ("/test/argv/for/gflags_unittest", GetArgv0()); +} + +TEST(GetArgvSumTest, BaseTest) { + // This number is just the sum of the ASCII values of all the chars + // in GetArgv(). + EXPECT_EQ(4904, GetArgvSum()); +} + +TEST(ProgramInvocationNameTest, BaseTest) { + EXPECT_STREQ("/test/argv/for/gflags_unittest", + ProgramInvocationName()); +} + +TEST(ProgramInvocationShortNameTest, BaseTest) { + EXPECT_STREQ("gflags_unittest", ProgramInvocationShortName()); +} + +TEST(ProgramUsageTest, BaseTest) { // Depends on 1st arg to ParseCommandLineFlags() + EXPECT_STREQ("/test/argv/for/gflags_unittest: " + " [...]\nDoes something useless.\n", + ProgramUsage()); +} + +TEST(GetCommandLineOptionTest, NameExistsAndIsDefault) { + string value("will be changed"); + bool r = GetCommandLineOption("test_bool", &value); + EXPECT_TRUE(r); + EXPECT_EQ("false", value); + + r = GetCommandLineOption("test_int32", &value); + EXPECT_TRUE(r); + EXPECT_EQ("-1", value); +} + +TEST(GetCommandLineOptionTest, NameExistsAndWasAssigned) { + FLAGS_test_int32 = 400; + string value("will be changed"); + const bool r = GetCommandLineOption("test_int32", &value); + EXPECT_TRUE(r); + EXPECT_EQ("400", value); +} + +TEST(GetCommandLineOptionTest, NameExistsAndWasSet) { + SetCommandLineOption("test_int32", "700"); + string value("will be changed"); + const bool r = GetCommandLineOption("test_int32", &value); + EXPECT_TRUE(r); + EXPECT_EQ("700", value); +} + +TEST(GetCommandLineOptionTest, NameExistsAndWasNotSet) { + // This doesn't set the flag's value, but rather its default value. + // is_default is still true, but the 'default' value returned has changed! + SetCommandLineOptionWithMode("test_int32", "800", SET_FLAGS_DEFAULT); + string value("will be changed"); + const bool r = GetCommandLineOption("test_int32", &value); + EXPECT_TRUE(r); + EXPECT_EQ("800", value); + EXPECT_TRUE(GetCommandLineFlagInfoOrDie("test_int32").is_default); +} + +TEST(GetCommandLineOptionTest, NameExistsAndWasConditionallySet) { + SetCommandLineOptionWithMode("test_int32", "900", SET_FLAG_IF_DEFAULT); + string value("will be changed"); + const bool r = GetCommandLineOption("test_int32", &value); + EXPECT_TRUE(r); + EXPECT_EQ("900", value); +} + +TEST(GetCommandLineOptionTest, NameDoesNotExist) { + string value("will not be changed"); + const bool r = GetCommandLineOption("test_int3210", &value); + EXPECT_FALSE(r); + EXPECT_EQ("will not be changed", value); +} + +TEST(GetCommandLineFlagInfoTest, FlagExists) { + CommandLineFlagInfo info; + bool r = GetCommandLineFlagInfo("test_int32", &info); + EXPECT_TRUE(r); + EXPECT_EQ("test_int32", info.name); + EXPECT_EQ("int32", info.type); + EXPECT_EQ("", info.description); + EXPECT_EQ("-1", info.current_value); + EXPECT_EQ("-1", info.default_value); + EXPECT_TRUE(info.is_default); + EXPECT_FALSE(info.has_validator_fn); + EXPECT_EQ(&FLAGS_test_int32, info.flag_ptr); + + FLAGS_test_bool = true; + r = GetCommandLineFlagInfo("test_bool", &info); + EXPECT_TRUE(r); + EXPECT_EQ("test_bool", info.name); + EXPECT_EQ("bool", info.type); + EXPECT_EQ("tests bool-ness", info.description); + EXPECT_EQ("true", info.current_value); + EXPECT_EQ("false", info.default_value); + EXPECT_FALSE(info.is_default); + EXPECT_FALSE(info.has_validator_fn); + EXPECT_EQ(&FLAGS_test_bool, info.flag_ptr); + + FLAGS_test_bool = false; + r = GetCommandLineFlagInfo("test_bool", &info); + EXPECT_TRUE(r); + EXPECT_EQ("test_bool", info.name); + EXPECT_EQ("bool", info.type); + EXPECT_EQ("tests bool-ness", info.description); + EXPECT_EQ("false", info.current_value); + EXPECT_EQ("false", info.default_value); + EXPECT_FALSE(info.is_default); // value is same, but flag *was* modified + EXPECT_FALSE(info.has_validator_fn); + EXPECT_EQ(&FLAGS_test_bool, info.flag_ptr); +} + +TEST(GetCommandLineFlagInfoTest, FlagDoesNotExist) { + CommandLineFlagInfo info; + // Set to some random values that GetCommandLineFlagInfo should not change + info.name = "name"; + info.type = "type"; + info.current_value = "curr"; + info.default_value = "def"; + info.filename = "/"; + info.is_default = false; + info.has_validator_fn = true; + info.flag_ptr = NULL; + bool r = GetCommandLineFlagInfo("test_int3210", &info); + EXPECT_FALSE(r); + EXPECT_EQ("name", info.name); + EXPECT_EQ("type", info.type); + EXPECT_EQ("", info.description); + EXPECT_EQ("curr", info.current_value); + EXPECT_EQ("def", info.default_value); + EXPECT_EQ("/", info.filename); + EXPECT_FALSE(info.is_default); + EXPECT_TRUE(info.has_validator_fn); + EXPECT_EQ(NULL, info.flag_ptr); +} + +TEST(GetCommandLineFlagInfoOrDieTest, FlagExistsAndIsDefault) { + CommandLineFlagInfo info; + info = GetCommandLineFlagInfoOrDie("test_int32"); + EXPECT_EQ("test_int32", info.name); + EXPECT_EQ("int32", info.type); + EXPECT_EQ("", info.description); + EXPECT_EQ("-1", info.current_value); + EXPECT_EQ("-1", info.default_value); + EXPECT_TRUE(info.is_default); + EXPECT_EQ(&FLAGS_test_int32, info.flag_ptr); + info = GetCommandLineFlagInfoOrDie("test_bool"); + EXPECT_EQ("test_bool", info.name); + EXPECT_EQ("bool", info.type); + EXPECT_EQ("tests bool-ness", info.description); + EXPECT_EQ("false", info.current_value); + EXPECT_EQ("false", info.default_value); + EXPECT_TRUE(info.is_default); + EXPECT_FALSE(info.has_validator_fn); + EXPECT_EQ(&FLAGS_test_bool, info.flag_ptr); +} + +TEST(GetCommandLineFlagInfoOrDieTest, FlagExistsAndWasAssigned) { + FLAGS_test_int32 = 400; + CommandLineFlagInfo info; + info = GetCommandLineFlagInfoOrDie("test_int32"); + EXPECT_EQ("test_int32", info.name); + EXPECT_EQ("int32", info.type); + EXPECT_EQ("", info.description); + EXPECT_EQ("400", info.current_value); + EXPECT_EQ("-1", info.default_value); + EXPECT_FALSE(info.is_default); + EXPECT_EQ(&FLAGS_test_int32, info.flag_ptr); + FLAGS_test_bool = true; + info = GetCommandLineFlagInfoOrDie("test_bool"); + EXPECT_EQ("test_bool", info.name); + EXPECT_EQ("bool", info.type); + EXPECT_EQ("tests bool-ness", info.description); + EXPECT_EQ("true", info.current_value); + EXPECT_EQ("false", info.default_value); + EXPECT_FALSE(info.is_default); + EXPECT_FALSE(info.has_validator_fn); + EXPECT_EQ(&FLAGS_test_bool, info.flag_ptr); +} + +#ifdef GTEST_HAS_DEATH_TEST +TEST(GetCommandLineFlagInfoOrDieDeathTest, FlagDoesNotExist) { + EXPECT_DEATH(GetCommandLineFlagInfoOrDie("test_int3210"), + ".*: flag test_int3210 does not exist"); +} +#endif + + +// These are lightly tested because they're deprecated. Basically, +// the tests are meant to cover how existing users use these functions, +// but not necessarily how new users could use them. +TEST(DeprecatedFunctionsTest, CommandlineFlagsIntoString) { + string s = CommandlineFlagsIntoString(); + EXPECT_NE(string::npos, s.find("--test_bool=")); +} + +TEST(DeprecatedFunctionsTest, AppendFlagsIntoFile) { + FLAGS_test_int32 = 10; // just to make the test more interesting + string filename(TmpFile("flagfile")); + unlink(filename.c_str()); // just to be safe + const bool r = AppendFlagsIntoFile(filename, "not the real argv0"); + EXPECT_TRUE(r); + + FILE* fp; + EXPECT_EQ(0, SafeFOpen(&fp, filename.c_str(), "r")); + EXPECT_TRUE(fp != NULL); + char line[8192]; + EXPECT_TRUE(fgets(line, sizeof(line)-1, fp) != NULL); // get the first line + // First line should be progname. + EXPECT_STREQ("not the real argv0\n", line); + + bool found_bool = false, found_int32 = false; + while (fgets(line, sizeof(line)-1, fp)) { + line[sizeof(line)-1] = '\0'; // just to be safe + if (strcmp(line, "--test_bool=false\n") == 0) + found_bool = true; + if (strcmp(line, "--test_int32=10\n") == 0) + found_int32 = true; + } + EXPECT_TRUE(found_int32); + EXPECT_TRUE(found_bool); + fclose(fp); +} + +TEST(DeprecatedFunctionsTest, ReadFromFlagsFile) { + FLAGS_test_int32 = -10; // just to make the test more interesting + string filename(TmpFile("flagfile2")); + unlink(filename.c_str()); // just to be safe + bool r = AppendFlagsIntoFile(filename, GetArgv0()); + EXPECT_TRUE(r); + + FLAGS_test_int32 = -11; + r = ReadFromFlagsFile(filename, GetArgv0(), true); + EXPECT_TRUE(r); + EXPECT_EQ(-10, FLAGS_test_int32); +} // unnamed namespace + +TEST(DeprecatedFunctionsTest, ReadFromFlagsFileFailure) { + FLAGS_test_int32 = -20; + string filename(TmpFile("flagfile3")); + FILE* fp; + EXPECT_EQ(0, SafeFOpen(&fp, filename.c_str(), "w")); + EXPECT_TRUE(fp != NULL); + // Note the error in the bool assignment below... + fprintf(fp, "%s\n--test_int32=-21\n--test_bool=not_a_bool!\n", GetArgv0()); + fclose(fp); + + FLAGS_test_int32 = -22; + const bool r = ReadFromFlagsFile(filename, GetArgv0(), false); + EXPECT_FALSE(r); + EXPECT_EQ(-22, FLAGS_test_int32); // the -21 from the flagsfile didn't take +} + +TEST(FlagsSetBeforeInitTest, TryFromEnv) { + EXPECT_EQ("pre-set", FLAGS_test_tryfromenv); +} + +// The following test case verifies that ParseCommandLineFlags() and +// ParseCommandLineNonHelpFlags() uses the last definition of a flag +// in case it's defined more than once. + +DEFINE_int32(test_flag, -1, "used for testing gflags.cc"); + +// Parses and returns the --test_flag flag. +// If with_help is true, calls ParseCommandLineFlags; otherwise calls +// ParseCommandLineNonHelpFlags. +int32 ParseTestFlag(bool with_help, int argc, const char** const_argv) { + FlagSaver fs; // Restores the flags before returning. + + // Makes a copy of the input array s.t. it can be reused + // (ParseCommandLineFlags() will alter the array). + char** const argv_save = new char*[argc + 1]; + char** argv = argv_save; + memcpy(argv, const_argv, sizeof(*argv)*(argc + 1)); + + if (with_help) { + ParseCommandLineFlags(&argc, &argv, true); + } else { + ParseCommandLineNonHelpFlags(&argc, &argv, true); + } + + delete[] argv_save; + return FLAGS_test_flag; +} + +TEST(ParseCommandLineFlagsUsesLastDefinitionTest, + WhenFlagIsDefinedTwiceOnCommandLine) { + const char* argv[] = { + "my_test", + "--test_flag=1", + "--test_flag=2", + NULL, + }; + + EXPECT_EQ(2, ParseTestFlag(true, arraysize(argv) - 1, argv)); + EXPECT_EQ(2, ParseTestFlag(false, arraysize(argv) - 1, argv)); +} + +TEST(ParseCommandLineFlagsUsesLastDefinitionTest, + WhenFlagIsDefinedTwiceInFlagFile) { + const char* argv[] = { + "my_test", + GetFlagFileFlag(), + NULL, + }; + + EXPECT_EQ(2, ParseTestFlag(true, arraysize(argv) - 1, argv)); + EXPECT_EQ(2, ParseTestFlag(false, arraysize(argv) - 1, argv)); +} + +TEST(ParseCommandLineFlagsUsesLastDefinitionTest, + WhenFlagIsDefinedInCommandLineAndThenFlagFile) { + const char* argv[] = { + "my_test", + "--test_flag=0", + GetFlagFileFlag(), + NULL, + }; + + EXPECT_EQ(2, ParseTestFlag(true, arraysize(argv) - 1, argv)); + EXPECT_EQ(2, ParseTestFlag(false, arraysize(argv) - 1, argv)); +} + +TEST(ParseCommandLineFlagsUsesLastDefinitionTest, + WhenFlagIsDefinedInFlagFileAndThenCommandLine) { + const char* argv[] = { + "my_test", + GetFlagFileFlag(), + "--test_flag=3", + NULL, + }; + + EXPECT_EQ(3, ParseTestFlag(true, arraysize(argv) - 1, argv)); + EXPECT_EQ(3, ParseTestFlag(false, arraysize(argv) - 1, argv)); +} + +TEST(ParseCommandLineFlagsUsesLastDefinitionTest, + WhenFlagIsDefinedInCommandLineAndFlagFileAndThenCommandLine) { + const char* argv[] = { + "my_test", + "--test_flag=0", + GetFlagFileFlag(), + "--test_flag=3", + NULL, + }; + + EXPECT_EQ(3, ParseTestFlag(true, arraysize(argv) - 1, argv)); + EXPECT_EQ(3, ParseTestFlag(false, arraysize(argv) - 1, argv)); +} + +TEST(ParseCommandLineFlagsAndDashArgs, TwoDashArgFirst) { + const char* argv[] = { + "my_test", + "--", + "--test_flag=0", + NULL, + }; + + EXPECT_EQ(-1, ParseTestFlag(true, arraysize(argv) - 1, argv)); + EXPECT_EQ(-1, ParseTestFlag(false, arraysize(argv) - 1, argv)); +} + +TEST(ParseCommandLineFlagsAndDashArgs, TwoDashArgMiddle) { + const char* argv[] = { + "my_test", + "--test_flag=7", + "--", + "--test_flag=0", + NULL, + }; + + EXPECT_EQ(7, ParseTestFlag(true, arraysize(argv) - 1, argv)); + EXPECT_EQ(7, ParseTestFlag(false, arraysize(argv) - 1, argv)); +} + +TEST(ParseCommandLineFlagsAndDashArgs, OneDashArg) { + const char* argv[] = { + "my_test", + "-", + "--test_flag=0", + NULL, + }; + + EXPECT_EQ(0, ParseTestFlag(true, arraysize(argv) - 1, argv)); + EXPECT_EQ(0, ParseTestFlag(false, arraysize(argv) - 1, argv)); +} + +#ifdef GTEST_HAS_DEATH_TEST +TEST(ParseCommandLineFlagsUnknownFlagDeathTest, + FlagIsCompletelyUnknown) { + const char* argv[] = { + "my_test", + "--this_flag_does_not_exist", + NULL, + }; + + EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv), + "unknown command line flag.*"); + EXPECT_DEATH(ParseTestFlag(false, arraysize(argv) - 1, argv), + "unknown command line flag.*"); +} + +TEST(ParseCommandLineFlagsUnknownFlagDeathTest, + BoolFlagIsCompletelyUnknown) { + const char* argv[] = { + "my_test", + "--nothis_flag_does_not_exist", + NULL, + }; + + EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv), + "unknown command line flag.*"); + EXPECT_DEATH(ParseTestFlag(false, arraysize(argv) - 1, argv), + "unknown command line flag.*"); +} + +TEST(ParseCommandLineFlagsUnknownFlagDeathTest, + FlagIsNotABool) { + const char* argv[] = { + "my_test", + "--notest_string", + NULL, + }; + + EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv), + "boolean value .* specified for .* command line flag"); + EXPECT_DEATH(ParseTestFlag(false, arraysize(argv) - 1, argv), + "boolean value .* specified for .* command line flag"); +} +#endif + +TEST(ParseCommandLineFlagsWrongFields, + DescriptionIsInvalid) { + // These must not be automatic variables, since command line flags + // aren't unregistered and gUnit uses FlagSaver to save and restore + // command line flags' values. If these are on the stack, then when + // later tests attempt to save and restore their values, the stack + // addresses of these variables will be overwritten... Stack smash! + static bool current_storage; + static bool defvalue_storage; + FlagRegisterer fr("flag_name", NULL, "filename", + ¤t_storage, &defvalue_storage); + CommandLineFlagInfo fi; + EXPECT_TRUE(GetCommandLineFlagInfo("flag_name", &fi)); + EXPECT_EQ("", fi.description); + EXPECT_EQ(¤t_storage, fi.flag_ptr); +} + +static bool ValidateTestFlagIs5(const char* flagname, int32 flagval) { + if (flagval == 5) + return true; + printf("%s isn't 5!\n", flagname); + return false; +} + +static bool ValidateTestFlagIs10(const char* flagname, int32 flagval) { + return flagval == 10; +} + + +TEST(FlagsValidator, ValidFlagViaArgv) { + const char* argv[] = { + "my_test", + "--test_flag=5", + NULL, + }; + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); + EXPECT_EQ(5, ParseTestFlag(true, arraysize(argv) - 1, argv)); + // Undo the flag validator setting + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); +} + +TEST(FlagsValidator, ValidFlagViaSetDefault) { + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); + // SetCommandLineOptionWithMode returns the empty string on error. + EXPECT_NE("", SetCommandLineOptionWithMode("test_flag", "5", + SET_FLAG_IF_DEFAULT)); + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); +} + +TEST(FlagsValidator, ValidFlagViaSetValue) { + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); + FLAGS_test_flag = 100; // doesn't trigger the validator + // SetCommandLineOptionWithMode returns the empty string on error. + EXPECT_NE("", SetCommandLineOptionWithMode("test_flag", "5", + SET_FLAGS_VALUE)); + EXPECT_NE("", SetCommandLineOptionWithMode("test_flag", "5", + SET_FLAGS_DEFAULT)); + EXPECT_NE("", SetCommandLineOption("test_flag", "5")); + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); +} + +#ifdef GTEST_HAS_DEATH_TEST +TEST(FlagsValidatorDeathTest, InvalidFlagViaArgv) { + const char* argv[] = { + "my_test", + "--test_flag=50", + NULL, + }; + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); + EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv), + "ERROR: failed validation of new value '50' for flag 'test_flag'"); + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); +} +#endif + +TEST(FlagsValidator, InvalidFlagViaSetDefault) { + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); + // SetCommandLineOptionWithMode returns the empty string on error. + EXPECT_EQ("", SetCommandLineOptionWithMode("test_flag", "50", + SET_FLAG_IF_DEFAULT)); + EXPECT_EQ(-1, FLAGS_test_flag); // the setting-to-50 should have failed + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); +} + +TEST(FlagsValidator, InvalidFlagViaSetValue) { + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); + FLAGS_test_flag = 100; // doesn't trigger the validator + // SetCommandLineOptionWithMode returns the empty string on error. + EXPECT_EQ("", SetCommandLineOptionWithMode("test_flag", "50", + SET_FLAGS_VALUE)); + EXPECT_EQ("", SetCommandLineOptionWithMode("test_flag", "50", + SET_FLAGS_DEFAULT)); + EXPECT_EQ("", SetCommandLineOption("test_flag", "50")); + EXPECT_EQ(100, FLAGS_test_flag); // the setting-to-50 should have failed + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); +} + +#ifdef GTEST_HAS_DEATH_TEST +TEST(FlagsValidatorDeathTest, InvalidFlagNeverSet) { + // If a flag keeps its default value, and that default value is + // invalid, we should die at argv-parse time. + const char* argv[] = { + "my_test", + NULL, + }; + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); + EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv), + "ERROR: --test_flag must be set on the commandline"); +} +#endif + +TEST(FlagsValidator, InvalidFlagPtr) { + int32 dummy; + EXPECT_FALSE(RegisterFlagValidator(NULL, &ValidateTestFlagIs5)); + EXPECT_FALSE(RegisterFlagValidator(&dummy, &ValidateTestFlagIs5)); +} + +TEST(FlagsValidator, RegisterValidatorTwice) { + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); + EXPECT_FALSE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs10)); + EXPECT_FALSE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs10)); + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs10)); + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); +} + +TEST(FlagsValidator, CommandLineFlagInfo) { + CommandLineFlagInfo info; + info = GetCommandLineFlagInfoOrDie("test_flag"); + EXPECT_FALSE(info.has_validator_fn); + + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); + info = GetCommandLineFlagInfoOrDie("test_flag"); + EXPECT_TRUE(info.has_validator_fn); + + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); + info = GetCommandLineFlagInfoOrDie("test_flag"); + EXPECT_FALSE(info.has_validator_fn); +} + +TEST(FlagsValidator, FlagSaver) { + { + FlagSaver fs; + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); + EXPECT_EQ("", SetCommandLineOption("test_flag", "50")); // fails validation + } + EXPECT_NE("", SetCommandLineOption("test_flag", "50")); // validator is gone + + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); + { + FlagSaver fs; + EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); + EXPECT_NE("", SetCommandLineOption("test_flag", "50")); // no validator + } + EXPECT_EQ("", SetCommandLineOption("test_flag", "50")); // validator is back +} + + +} // unnamed namespace + +static int main(int argc, char **argv) { + + // Run unit tests only if called without arguments, otherwise this program + // is used by an "external" usage test + const bool run_tests = (argc == 1); + + // We need to call SetArgv before parsing flags, so our "test" argv will + // win out over this executable's real argv. That makes running this + // test with a real --help flag kinda annoying, unfortunately. + const char* test_argv[] = { "/test/argv/for/gflags_unittest", + "argv 2", "3rd argv", "argv #4" }; + SetArgv(arraysize(test_argv), test_argv); + + // The first arg is the usage message, also important for testing. + string usage_message = (string(GetArgv0()) + + ": [...]\nDoes something useless.\n"); + + // We test setting tryfromenv manually, and making sure + // ParseCommandLineFlags still evaluates it. + FLAGS_tryfromenv = "test_tryfromenv"; + setenv("FLAGS_test_tryfromenv", "pre-set", 1); + + // Modify flag values from declared default value in two ways. + // The recommended way: + SetCommandLineOptionWithMode("changed_bool1", "true", SET_FLAGS_DEFAULT); + + // The non-recommended way: + FLAGS_changed_bool2 = true; + + SetUsageMessage(usage_message); + SetVersionString("test_version"); + ParseCommandLineFlags(&argc, &argv, true); + MakeTmpdir(&FLAGS_test_tmpdir); + + int exit_status = 0; + if (run_tests) { + fprintf(stdout, "Running the unit tests now...\n\n"); fflush(stdout); + exit_status = RUN_ALL_TESTS(); + } else fprintf(stderr, "\n\nPASS\n"); + ShutDownCommandLineFlags(); + return exit_status; +} + +} // GFLAGS_NAMESPACE + +int main(int argc, char** argv) { + return GFLAGS_NAMESPACE::main(argc, argv); +} + diff --git a/third_party/gflags/test/gflags_unittest_flagfile b/third_party/gflags/test/gflags_unittest_flagfile new file mode 100644 index 0000000..f4fa0c4 --- /dev/null +++ b/third_party/gflags/test/gflags_unittest_flagfile @@ -0,0 +1,2 @@ +--test_flag=1 +--test_flag=2 diff --git a/third_party/gflags/test/nc/CMakeLists.txt b/third_party/gflags/test/nc/CMakeLists.txt new file mode 100644 index 0000000..d00b07d --- /dev/null +++ b/third_party/gflags/test/nc/CMakeLists.txt @@ -0,0 +1,16 @@ +## gflags negative compilation tests + +cmake_minimum_required (VERSION 2.8.12 FATAL_ERROR) + +if (NOT TEST_NAME) + message (FATAL_ERROR "Missing TEST_NAME CMake flag") +endif () +string (TOUPPER ${TEST_NAME} TEST_NAME_UPPER) + +project (gflags_${TEST_NAME}) + +find_package (gflags REQUIRED) +include_directories ("${CMAKE_CURRENT_SOURCE_DIR}/..") +add_definitions (-DTEST_${TEST_NAME_UPPER}) +add_executable (gflags_${TEST_NAME} gflags_nc.cc) +target_link_libraries(gflags_${TEST_NAME} gflags) diff --git a/third_party/gflags/test/nc/gflags_nc.cc b/third_party/gflags/test/nc/gflags_nc.cc new file mode 100644 index 0000000..1990c30 --- /dev/null +++ b/third_party/gflags/test/nc/gflags_nc.cc @@ -0,0 +1,73 @@ +// Copyright (c) 2009, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// --- +// +// A negative comiple test for gflags. + +#include + +#if defined(TEST_NC_SWAPPED_ARGS) + +DEFINE_bool(some_bool_flag, + "the default value should go here, not the description", + false); + + +#elif defined(TEST_NC_INT_INSTEAD_OF_BOOL) + +DEFINE_bool(some_bool_flag_2, + 0, + "should have been an int32 flag but mistakenly used bool instead"); + +#elif defined(TEST_NC_BOOL_IN_QUOTES) + + +DEFINE_bool(some_bool_flag_3, + "false", + "false in in quotes, which is wrong"); + +#elif defined(TEST_NC_SANITY) + +DEFINE_bool(some_bool_flag_4, + true, + "this is the correct usage of DEFINE_bool"); + +#elif defined(TEST_NC_DEFINE_STRING_WITH_0) + +DEFINE_string(some_string_flag, + 0, + "Trying to construct a string by passing 0 would cause a crash."); + +#endif + +int main(int, char **) +{ + return 0; +} diff --git a/third_party/glog/.bazelci/presubmit.yml b/third_party/glog/.bazelci/presubmit.yml new file mode 100644 index 0000000..9065173 --- /dev/null +++ b/third_party/glog/.bazelci/presubmit.yml @@ -0,0 +1,58 @@ +--- +tasks: + ubuntu1804: + name: "Ubuntu 18.04" + platform: ubuntu1804 + build_flags: + - "--features=layering_check" + - "--copt=-Werror" + build_targets: + - "//..." + test_flags: + - "--features=layering_check" + - "--copt=-Werror" + test_targets: + - "//..." + macos: + name: "macOS: latest Xcode" + platform: macos + build_flags: + - "--features=layering_check" + - "--copt=-Werror" + build_targets: + - "//..." + test_flags: + - "--features=layering_check" + - "--copt=-Werror" + test_targets: + - "//..." + windows-msvc: + name: "Windows: MSVC 2017" + platform: windows + environment: + BAZEL_VC: "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC" + build_flags: + - "--features=layering_check" + - "--copt=/WX" + build_targets: + - "//..." + test_flags: + - "--features=layering_check" + - "--copt=/WX" + test_targets: + - "//..." + windows-clang-cl: + name: "Windows: Clang" + platform: windows + environment: + BAZEL_VC: "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC" + build_flags: + - "--compiler=clang-cl" + - "--features=layering_check" + build_targets: + - "//..." + test_flags: + - "--compiler=clang-cl" + - "--features=layering_check" + test_targets: + - "//..." diff --git a/third_party/glog/.clang-format b/third_party/glog/.clang-format new file mode 100644 index 0000000..f2dd0de --- /dev/null +++ b/third_party/glog/.clang-format @@ -0,0 +1,168 @@ +--- +Language: Cpp +# BasedOnStyle: Google +AccessModifierOffset: -1 +AlignAfterOpenBracket: Align +AlignConsecutiveMacros: false +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: Left +AlignOperands: true +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: true +AllowAllConstructorInitializersOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AllowShortLambdasOnASingleLine: All +AllowShortIfStatementsOnASingleLine: WithoutElse +AllowShortLoopsOnASingleLine: true +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: true +AlwaysBreakTemplateDeclarations: Yes +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Attach +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeColon +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DeriveLineEnding: true +DerivePointerAlignment: true +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '^' + Priority: 2 + SortPriority: 0 + - Regex: '^<.*\.h>' + Priority: 1 + SortPriority: 0 + - Regex: '^<.*' + Priority: 2 + SortPriority: 0 + - Regex: '.*' + Priority: 3 + SortPriority: 0 +IncludeIsMainRegex: '([-_](test|unittest))?$' +IncludeIsMainSourceRegex: '' +IndentCaseLabels: true +IndentGotoLabels: true +IndentPPDirectives: None +IndentWidth: 2 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Never +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 1 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 200 +PointerAlignment: Left +RawStringFormats: + - Language: Cpp + Delimiters: + - cc + - CC + - cpp + - Cpp + - CPP + - 'c++' + - 'C++' + CanonicalDelimiter: '' + BasedOnStyle: google + - Language: TextProto + Delimiters: + - pb + - PB + - proto + - PROTO + EnclosingFunctions: + - EqualsProto + - EquivToProto + - PARSE_PARTIAL_TEXT_PROTO + - PARSE_TEST_PROTO + - PARSE_TEXT_PROTO + - ParseTextOrDie + - ParseTextProtoOrDie + CanonicalDelimiter: '' + BasedOnStyle: google +ReflowComments: true +SortIncludes: true +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: false +SpacesInConditionalStatement: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +SpaceBeforeSquareBrackets: false +Standard: Auto +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 8 +UseCRLF: false +UseTab: Never +... + diff --git a/third_party/glog/.clang-tidy b/third_party/glog/.clang-tidy new file mode 100644 index 0000000..19082cd --- /dev/null +++ b/third_party/glog/.clang-tidy @@ -0,0 +1,59 @@ +--- +Checks: 'clang-diagnostic-*,clang-analyzer-*,google-*' +WarningsAsErrors: '' +HeaderFilterRegex: '' +AnalyzeTemporaryDtors: false +FormatStyle: file +CheckOptions: + - key: cert-dcl16-c.NewSuffixes + value: 'L;LL;LU;LLU' + - key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField + value: '0' + - key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors + value: '1' + - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic + value: '1' + - key: google-build-namespaces.HeaderFileExtensions + value: ',h,hh,hpp,hxx' + - key: google-global-names-in-headers.HeaderFileExtensions + value: ',h,hh,hpp,hxx' + - key: google-readability-braces-around-statements.ShortStatementLines + value: '1' + - key: google-readability-function-size.BranchThreshold + value: '4294967295' + - key: google-readability-function-size.LineThreshold + value: '4294967295' + - key: google-readability-function-size.NestingThreshold + value: '4294967295' + - key: google-readability-function-size.ParameterThreshold + value: '4294967295' + - key: google-readability-function-size.StatementThreshold + value: '800' + - key: google-readability-function-size.VariableThreshold + value: '4294967295' + - key: google-readability-namespace-comments.ShortNamespaceLines + value: '10' + - key: google-readability-namespace-comments.SpacesBeforeComments + value: '2' + - key: google-runtime-int.SignedTypePrefix + value: int + - key: google-runtime-int.TypeSuffix + value: '' + - key: google-runtime-int.UnsignedTypePrefix + value: uint + - key: google-runtime-references.WhiteListTypes + value: '' + - key: modernize-loop-convert.MaxCopySize + value: '16' + - key: modernize-loop-convert.MinConfidence + value: reasonable + - key: modernize-loop-convert.NamingStyle + value: CamelCase + - key: modernize-pass-by-value.IncludeStyle + value: llvm + - key: modernize-replace-auto-ptr.IncludeStyle + value: llvm + - key: modernize-use-nullptr.NullMacros + value: 'NULL' +... + diff --git a/third_party/glog/.gitattributes b/third_party/glog/.gitattributes new file mode 100644 index 0000000..2f6d494 --- /dev/null +++ b/third_party/glog/.gitattributes @@ -0,0 +1 @@ +*.h linguist-language=C++ diff --git a/third_party/glog/.github/workflows/android.yml b/third_party/glog/.github/workflows/android.yml new file mode 100644 index 0000000..e5f8c2e --- /dev/null +++ b/third_party/glog/.github/workflows/android.yml @@ -0,0 +1,51 @@ +name: Android + +on: [push, pull_request] + +jobs: + build-android: + name: NDK-C++${{matrix.std}}-${{matrix.abi}}-${{matrix.build_type}} + runs-on: ubuntu-latest + defaults: + run: + shell: bash + strategy: + fail-fast: true + matrix: + std: [98, 11, 14, 17, 20] + abi: [arm64-v8a, armeabi-v7a, x86_64, x86] + build_type: [Debug, Release] + + steps: + - uses: actions/checkout@v2 + + - name: Setup Ninja + uses: ashutoshvarma/setup-ninja@master + with: + version: 1.10.0 + + - name: Setup C++98 Environment + if: matrix.std == '98' + run: | + echo 'CXXFLAGS=-Wno-error=variadic-macros -Wno-error=long-long ${{env.CXXFLAGS}}' >> $GITHUB_ENV + + - name: Configure + env: + CXXFLAGS: -Wall -Wextra -Wpedantic -Wsign-conversion -Wtautological-compare -Wformat-nonliteral -Wundef -Werror ${{env.CXXFLAGS}} + run: | + cmake -S . -B build_${{matrix.abi}} \ + -DANDROID_ABI=${{matrix.abi}} \ + -DANDROID_NATIVE_API_LEVEL=28 \ + -DANDROID_STL=c++_shared \ + -DCMAKE_BUILD_TYPE=${{matrix.build_type}} \ + -DCMAKE_CXX_EXTENSIONS=OFF \ + -DCMAKE_CXX_STANDARD=${{matrix.std}} \ + -DCMAKE_CXX_STANDARD_REQUIRED=ON \ + -DCMAKE_TOOLCHAIN_FILE=${ANDROID_NDK_HOME}/build/cmake/android.toolchain.cmake \ + -G Ninja \ + -Werror + + - name: Build + run: | + cmake --build build_${{matrix.abi}} \ + --config ${{matrix.build_type}} diff --git a/third_party/glog/.github/workflows/linux.yml b/third_party/glog/.github/workflows/linux.yml new file mode 100644 index 0000000..c9ac1a4 --- /dev/null +++ b/third_party/glog/.github/workflows/linux.yml @@ -0,0 +1,150 @@ +name: Linux + +on: [push, pull_request] + +jobs: + build-linux: + defaults: + run: + shell: bash + name: GCC-C++${{matrix.std}}-${{matrix.build_type}}-${{matrix.lib}}-${{matrix.extra}} + runs-on: ubuntu-latest + strategy: + fail-fast: true + matrix: + build_type: [Release, Debug] + extra: [no-custom-prefix, custom-prefix] + lib: [shared, static] + std: [98, 11, 14, 17, 20] + + steps: + - uses: actions/checkout@v2 + + - name: Setup Dependencies + run: | + sudo apt-get update + DEBIAN_FRONTEND=noninteractive sudo apt-get install -y \ + build-essential \ + cmake \ + lcov \ + libgflags-dev \ + libunwind-dev \ + ninja-build + + - name: Cache GTest + id: cache-gtest + uses: actions/cache@v2 + with: + path: gtest/ + key: ${{runner.os}}-gtest-1.11 + + - name: Download GTest + if: steps.cache-gtest.outputs.cache-hit != 'true' + run: | + wget https://github.com/google/googletest/archive/refs/tags/release-1.11.0.tar.gz + tar xvf release-1.11.0.tar.gz + + - name: Build GTest + if: steps.cache-gtest.outputs.cache-hit != 'true' + run: | + cmake -S googletest-release-1.11.0 -B build-googletest \ + -DBUILD_SHARED_LIBS=${{matrix.shared}} \ + -DCMAKE_BUILD_TYPE=${{matrix.build_type}} \ + -DCMAKE_INSTALL_PREFIX=${{github.workspace}}/gtest \ + -G Ninja + cmake --build build-googletest --target install + + - name: Setup Environment + if: matrix.build_type == 'Debug' + run: | + echo 'CXXFLAGS=--coverage' >> $GITHUB_ENV + echo 'GTest_ROOT=${{github.workspace}}/gtest' >> $GITHUB_ENV + + - name: Setup C++98 Environment + if: matrix.std == '98' + run: | + echo 'CXXFLAGS=-Wno-error=variadic-macros -Wno-error=long-long ${{env.CXXFLAGS}}' >> $GITHUB_ENV + + - name: Configure + env: + CXXFLAGS: -Wall -Wextra -Wsign-conversion -Wtautological-compare -Wformat-nonliteral -Wundef -Werror ${{env.CXXFLAGS}} + run: | + cmake -S . -B build_${{matrix.build_type}} \ + -DBUILD_SHARED_LIBS=${{matrix.lib == 'shared'}} \ + -DCMAKE_CXX_STANDARD=${{matrix.std}} \ + -DCMAKE_CXX_STANDARD_REQUIRED=ON \ + -DCMAKE_INSTALL_PREFIX=${{github.workspace}}/install \ + -DWITH_CUSTOM_PREFIX=${{matrix.extra == 'custom-prefix'}} \ + -G Ninja \ + -Werror + + - name: Build + run: | + cmake --build build_${{matrix.build_type}} \ + --config ${{matrix.build_type}} + + - name: Install + run: | + cmake --build build_${{matrix.build_type}} \ + --config ${{matrix.build_type}} \ + --target install + + cmake build_${{matrix.build_type}} \ + -DCMAKE_INSTALL_INCLUDEDIR=${{runner.workspace}}/foo/include \ + -DCMAKE_INSTALL_LIBDIR=${{runner.workspace}}/foo/lib \ + -DCMAKE_INSTALL_DATAROOTDIR=${{runner.workspace}}/foo/share + cmake --build build_${{matrix.build_type}} \ + --config ${{matrix.build_type}} \ + --target install + + - name: Test CMake Package (relative GNUInstallDirs) + run: | + cmake -S src/package_config_unittest/working_config \ + -B build_${{matrix.build_type}}_package \ + -DCMAKE_BUILD_TYPE=${{matrix.build_type}} \ + -DCMAKE_PREFIX_PATH=${{github.workspace}}/install \ + -G Ninja + cmake --build build_${{matrix.build_type}}_package \ + --config ${{matrix.build_type}} + + - name: Test CMake Package (absolute GNUInstallDirs) + run: | + cmake -S src/package_config_unittest/working_config \ + -B build_${{matrix.build_type}}_package_foo \ + -DCMAKE_BUILD_TYPE=${{matrix.build_type}} \ + -DCMAKE_PREFIX_PATH=${{runner.workspace}}/foo \ + -G Ninja + cmake --build build_${{matrix.build_type}}_package_foo \ + --config ${{matrix.build_type}} + + - name: Test + run: | + ctest --test-dir build_${{matrix.build_type}} -j$(nproc) --output-on-failure + + - name: Generate Coverage + if: matrix.build_type == 'Debug' + run: | + lcov --directory . --capture --output-file coverage.info + lcov --remove coverage.info \ + '${{github.workspace}}/gtest/*' \ + '*/src/*_unittest.cc' \ + '*/src/googletest.h' \ + '*/src/mock-log.h' \ + '/usr/*' \ + --output-file coverage.info + + for file in src/glog/*.h.in; do + name=$(basename ${file}) + name_we=${name%.h.in} + sed -i "s|build_${{matrix.build_type}}/glog/${name_we}.h\$|${file}|g" coverage.info + done + + lcov --list coverage.info + + - name: Upload Coverage to Codecov + if: matrix.build_type == 'Debug' + uses: codecov/codecov-action@v2 + with: + token: ${{ secrets.CODECOV_TOKEN }} + fail_ci_if_error: true + verbose: true diff --git a/third_party/glog/.github/workflows/macos.yml b/third_party/glog/.github/workflows/macos.yml new file mode 100644 index 0000000..0b20ed2 --- /dev/null +++ b/third_party/glog/.github/workflows/macos.yml @@ -0,0 +1,83 @@ +name: macOS + +on: [push, pull_request] + +jobs: + build-macos: + name: AppleClang-C++${{matrix.std}}-${{matrix.build_type}} + runs-on: macos-10.15 + strategy: + fail-fast: true + matrix: + std: [98, 11, 14, 17, 20] + include: + - generator: Ninja + - build_type: Debug + + steps: + - uses: actions/checkout@v2 + + - name: Setup Ninja + uses: ashutoshvarma/setup-ninja@master + with: + version: 1.10.0 + + - name: Setup Dependencies + run: | + brew install lcov + + - name: Setup Environment + if: matrix.build_type == 'Debug' + run: | + echo 'CXXFLAGS=--coverage' >> $GITHUB_ENV + + - name: Configure + shell: bash + env: + CXXFLAGS: -Wall -Wextra -Wsign-conversion -Wtautological-compare -Wformat-nonliteral -Wundef -Werror ${{env.CXXFLAGS}} + run: | + cmake -S . -B build_${{matrix.build_type}} \ + -DCMAKE_CXX_EXTENSIONS=OFF \ + -DCMAKE_CXX_FLAGS_DEBUG=-pedantic-errors \ + -DCMAKE_CXX_FLAGS_RELEASE=-pedantic-errors \ + -DCMAKE_CXX_STANDARD=${{matrix.std}} \ + -DCMAKE_CXX_STANDARD_REQUIRED=ON \ + -G "${{matrix.generator}}" \ + -Werror + + - name: Build + run: | + cmake --build build_${{matrix.build_type}} \ + --config ${{matrix.build_type}} + + - name: Test + run: | + ctest --test-dir build_${{matrix.build_type}} \ + --output-on-failure + + - name: Generate Coverage + if: matrix.build_type == 'Debug' + run: | + lcov --directory . --capture --output-file coverage.info + lcov --remove coverage.info \ + '*/src/*_unittest.cc' \ + '*/src/googletest.h' \ + '*/src/mock-log.h' \ + '*/usr/*' \ + --output-file coverage.info + + for file in src/glog/*.h.in; do + name=$(basename ${file}) + name_we=${name%.h.in} + sed -i "" "s|${{github.workspace}}/glog/${name_we}.h\$|${file}|g" coverage.info + done + + lcov --list coverage.info + + - name: Upload Coverage to Codecov + if: matrix.build_type == 'Debug' + uses: codecov/codecov-action@v2 + with: + token: ${{ secrets.CODECOV_TOKEN }} + fail_ci_if_error: true + verbose: true diff --git a/third_party/glog/.github/workflows/windows.yml b/third_party/glog/.github/workflows/windows.yml new file mode 100644 index 0000000..de3b05d --- /dev/null +++ b/third_party/glog/.github/workflows/windows.yml @@ -0,0 +1,234 @@ +name: Windows + +on: [push, pull_request] + +jobs: + build-msvc: + name: ${{matrix.msvc}}-${{matrix.arch}}-C++${{matrix.std}}-${{matrix.build_type}}-${{matrix.lib}}-${{matrix.extra}} + runs-on: ${{matrix.os}} + defaults: + run: + shell: powershell + env: + CL: /MP + CXXFLAGS: /WX /permissive- + strategy: + fail-fast: true + matrix: + arch: [Win32, x64] + build_type: [Debug, Release] + extra: [no-custom-prefix, custom-prefix] + lib: [shared, static] + msvc: [VS-16-2019, VS-17-2022] + # Visual Studio 17 2022 does not support C++11 and older language standard + std: [14, 17, 20] + include: + - msvc: VS-16-2019 + os: windows-2019 + generator: 'Visual Studio 16 2019' + - msvc: VS-17-2022 + os: windows-2022 + generator: 'Visual Studio 17 2022' + + steps: + - uses: actions/checkout@v2 + + - name: Cache GTest + id: cache-gtest + uses: actions/cache@v2 + with: + path: gtest/ + key: ${{runner.os}}-gtest-1.11-${{matrix.lib}}-${{matrix.arch}}-${{matrix.build_type}} + + - name: Download GTest + if: steps.cache-gtest.outputs.cache-hit != 'true' + run: | + (New-Object System.Net.WebClient).DownloadFile("https://github.com/google/googletest/archive/refs/tags/release-1.11.0.zip", "release-1.11.0.zip") + Expand-Archive release-1.11.0.zip . + + - name: Build GTest + if: steps.cache-gtest.outputs.cache-hit != 'true' + run: | + cmake -S googletest-release-1.11.0 -B build-googletest ` + -A ${{matrix.arch}} ` + -DBUILD_SHARED_LIBS=${{matrix.lib == 'shared'}} ` + -Dgtest_force_shared_crt=ON ` + -DCMAKE_INSTALL_PREFIX=${{github.workspace}}/gtest + cmake --build build-googletest ` + --config ${{matrix.build_type}} ` + --target install + + - name: Cache gflags + id: cache-gflags + uses: actions/cache@v2 + with: + path: gflags/ + key: ${{runner.os}}-gflags-2.2.2-${{matrix.lib}}-${{matrix.arch}}-${{matrix.build_type}} + + - name: Download gflags + if: steps.cache-gflags.outputs.cache-hit != 'true' + run: | + (New-Object System.Net.WebClient).DownloadFile("https://github.com/gflags/gflags/archive/refs/tags/v2.2.2.zip", "v2.2.2.zip") + Expand-Archive v2.2.2.zip . + + - name: Build gflags + if: steps.cache-gflags.outputs.cache-hit != 'true' + run: | + cmake -S gflags-2.2.2 -B build-gflags ` + -A ${{matrix.arch}} ` + -DBUILD_SHARED_LIBS=${{matrix.lib == 'shared'}} ` + -DCMAKE_INSTALL_PREFIX=${{github.workspace}}/gflags + cmake --build build-gflags ` + --config ${{matrix.build_type}} ` + --target install + + - name: Setup Environment + run: | + echo "GTest_ROOT=$((Get-Item .).FullName)/gtest" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + echo "gflags_ROOT=$((Get-Item .).FullName)/gflags" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + echo "${{github.workspace}}/gtest/bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + echo "${{github.workspace}}/gflags/bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + + - name: Setup Release Environment + if: matrix.build_type != 'Debug' + run: | + echo "CXXFLAGS=/Zi ${{env.CXXFLAGS}}" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + + - name: Configure + run: | + cmake -S . -B build_${{matrix.build_type}} ` + -A ${{matrix.arch}} ` + -DBUILD_SHARED_LIBS=${{matrix.lib == 'shared'}} ` + -DCMAKE_CXX_EXTENSIONS=OFF ` + -DCMAKE_CXX_STANDARD=${{matrix.std}} ` + -DCMAKE_CXX_STANDARD_REQUIRED=ON ` + -DCMAKE_EXE_LINKER_FLAGS='/NOIMPLIB' ` + -DCMAKE_EXE_LINKER_FLAGS_RELEASE='/INCREMENTAL:NO /DEBUG' ` + -DCMAKE_INSTALL_PREFIX:PATH=./install ` + -DCMAKE_MSVC_RUNTIME_LIBRARY='MultiThreaded$<$:Debug>DLL' ` + -DWITH_CUSTOM_PREFIX=${{matrix.extra == 'custom-prefix'}} ` + -G "${{matrix.generator}}" ` + -Werror + + - name: Build + run: cmake --build build_${{matrix.build_type}} ` + --config ${{matrix.build_type}} + + - name: Test + env: + CTEST_OUTPUT_ON_FAILURE: 1 + run: | + cmake --build build_${{matrix.build_type}}/ ` + --config ${{matrix.build_type}} ` + --target RUN_TESTS + + - name: Install + run: | + cmake --build build_${{matrix.build_type}}/ ` + --config ${{matrix.build_type}} ` + --target install + + build-mingw: + name: ${{matrix.sys}}-${{matrix.env}}-C++${{matrix.std}}-${{matrix.build_type}}-${{matrix.lib}}-${{matrix.extra}} + runs-on: windows-2022 + env: + BUILDDIR: 'build_${{matrix.sys}}-${{matrix.env}}-C++${{matrix.std}}-${{matrix.build_type}}-${{matrix.lib}}-${{matrix.extra}}' + defaults: + run: + shell: msys2 {0} + strategy: + fail-fast: true + matrix: + build_type: [Debug] + extra: [no-custom-prefix, custom-prefix] + lib: [shared, static] + std: [98, 11, 14, 17, 20] + sys: [mingw32, mingw64] + include: + - sys: mingw32 + env: i686 + - sys: mingw64 + env: x86_64 + + steps: + - uses: actions/checkout@v2 + - uses: msys2/setup-msys2@v2 + with: + msystem: ${{matrix.sys}} + install: >- + lcov + mingw-w64-${{matrix.env}}-cmake + mingw-w64-${{matrix.env}}-gcc + mingw-w64-${{matrix.env}}-gflags + mingw-w64-${{matrix.env}}-ninja + + - name: Setup C++98 Environment + if: matrix.std == '98' + run: | + echo 'CXXFLAGS=-Wno-error=variadic-macros -Wno-error=long-long ${{env.CXXFLAGS}}' >> $GITHUB_ENV + + - name: Setup Environment + if: matrix.build_type == 'Debug' + run: | + echo 'CXXFLAGS=--coverage ${{env.CXXFLAGS}}' >> $GITHUB_ENV + + - name: Configure + env: + CXXFLAGS: -Wall -Wextra -Wpedantic -Wsign-conversion -Wtautological-compare -Wformat-nonliteral -Wundef -Werror ${{env.CXXFLAGS}} + run: | + cmake -S . -B build_${{matrix.build_type}}/ \ + -DBUILD_SHARED_LIBS=${{matrix.lib == 'shared'}} \ + -DCMAKE_BUILD_TYPE=${{matrix.build_type}} \ + -DCMAKE_CXX_EXTENSIONS=OFF \ + -DCMAKE_CXX_STANDARD=${{matrix.std}} \ + -DCMAKE_CXX_STANDARD_REQUIRED=ON \ + -DCMAKE_INSTALL_PREFIX:PATH=./install \ + -DWITH_CUSTOM_PREFIX=${{matrix.extra == 'custom-prefix'}} \ + -G Ninja \ + -Werror + + - name: Build + run: | + cmake --build build_${{matrix.build_type}}/ --config ${{matrix.build_type}} + + - name: Test + env: + CTEST_OUTPUT_ON_FAILURE: 1 + run: | + cmake --build build_${{matrix.build_type}}/ --config ${{matrix.build_type}} \ + --target test + + - name: Install + run: | + cmake --build build_${{matrix.build_type}}/ \ + --config ${{matrix.build_type}} \ + --target install + + - name: Generate Coverage + if: matrix.build_type == 'Debug' + run: | + lcov --directory . --capture --output-file coverage.info + lcov --remove coverage.info \ + '*/install/include/*' \ + '*/msys64/mingw32/*' \ + '*/msys64/mingw64/*' \ + '*/src/*_unittest.cc' \ + '*/src/googletest.h' \ + '*/src/mock-log.h' \ + --output-file coverage.info + + for file in src/glog/*.h.in; do + name=$(basename ${file}) + name_we=${name%.h.in} + sed -i "s|build_${{matrix.build_type}}/glog/${name_we}.h\$|${file}|g" coverage.info + done + + lcov --list coverage.info + + - name: Upload Coverage to Codecov + if: matrix.build_type == 'Debug' + uses: codecov/codecov-action@v2 + with: + token: ${{ secrets.CODECOV_TOKEN }} + fail_ci_if_error: true + verbose: true diff --git a/third_party/glog/.gitignore b/third_party/glog/.gitignore new file mode 100644 index 0000000..2678271 --- /dev/null +++ b/third_party/glog/.gitignore @@ -0,0 +1,3 @@ +*.orig +/build*/ +bazel-* diff --git a/third_party/glog/AUTHORS b/third_party/glog/AUTHORS new file mode 100644 index 0000000..9d711ec --- /dev/null +++ b/third_party/glog/AUTHORS @@ -0,0 +1,29 @@ +# This is the official list of glog authors for copyright purposes. +# This file is distinct from the CONTRIBUTORS files. +# See the latter for an explanation. +# +# Names should be added to this file as: +# Name or Organization +# The email address is not required for organizations. +# +# Please keep the list sorted. + +Abhishek Dasgupta +Abhishek Parmar +Andrew Schwartzmeyer +Andy Ying +Brian Silverman +Dmitriy Arbitman +Google Inc. +Guillaume Dumont +Marco Wang +Michael Tanner +MiniLight +romange +Roman Perepelitsa +Sergiu Deitsch +tbennun +Teddy Reed +Vijaymahantesh Sattigeri +Zhongming Qu +Zhuoran Shen diff --git a/third_party/glog/BUILD.bazel b/third_party/glog/BUILD.bazel new file mode 100644 index 0000000..0acdc72 --- /dev/null +++ b/third_party/glog/BUILD.bazel @@ -0,0 +1,22 @@ +licenses(["notice"]) + +exports_files(["COPYING"]) + +load(":bazel/glog.bzl", "glog_library") + +glog_library() + +# platform() to build with clang-cl on Bazel CI. This is enabled with +# the flags in .bazelci/presubmit.yml: +# +# --incompatible_enable_cc_toolchain_resolution +# --extra_toolchains=@local_config_cc//:cc-toolchain-x64_windows-clang-cl +# --extra_execution_platforms=//:x64_windows-clang-cl +platform( + name = "x64_windows-clang-cl", + constraint_values = [ + "@platforms//cpu:x86_64", + "@platforms//os:windows", + "@bazel_tools//tools/cpp:clang-cl", + ], +) diff --git a/third_party/glog/CMakeLists.txt b/third_party/glog/CMakeLists.txt new file mode 100644 index 0000000..b02caa6 --- /dev/null +++ b/third_party/glog/CMakeLists.txt @@ -0,0 +1,1139 @@ +cmake_minimum_required(VERSION 3.16) +project( + glog + VERSION 0.6.0 + DESCRIPTION "C++ implementation of the Google logging module" + HOMEPAGE_URL https://github.com/google/glog + LANGUAGES CXX) + +set(CPACK_PACKAGE_NAME glog) +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Google logging library") +set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) +set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) +set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) +set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION}) + +list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake) + +include(CheckCXXCompilerFlag) +include(CheckCXXSourceCompiles) +include(CheckCXXSourceRuns) +include(CheckCXXSymbolExists) +include(CheckFunctionExists) +include(CheckIncludeFileCXX) +include(CheckLibraryExists) +include(CheckStructHasMember) +include(CheckTypeSize) +include(CMakeDependentOption) +include(CMakePackageConfigHelpers) +include(CMakePushCheckState) +include(CPack) +include(CTest) +# include (DetermineGflagsNamespace) +include(GenerateExportHeader) +include(GetCacheVariables) +include(GNUInstallDirs) + +option(BUILD_SHARED_LIBS "Build shared libraries" OFF) +option(PRINT_UNSYMBOLIZED_STACK_TRACES + "Print file offsets in traces instead of symbolizing" OFF) +option(WITH_CUSTOM_PREFIX "Enable support for user-generated message prefixes" + ON) +option(WITH_GFLAGS "Use gflags" ON) +option(WITH_GTEST "Use Google Test" OFF) +option(WITH_PKGCONFIG "Enable pkg-config support" OFF) +option(WITH_SYMBOLIZE "Enable symbolize module" ON) +option(WITH_THREADS "Enable multithreading support" ON) +option(WITH_TLS "Enable Thread Local Storage (TLS) support" ON) +option(WITH_UNWIND "Enable libunwind support" OFF) + +cmake_dependent_option(WITH_GMOCK "Use Google Mock" ON WITH_GTEST OFF) + +if(NOT WITH_UNWIND) + set(CMAKE_DISABLE_FIND_PACKAGE_Unwind ON) +endif(NOT WITH_UNWIND) + +if(NOT WITH_GTEST) + set(CMAKE_DISABLE_FIND_PACKAGE_GTest ON) +endif(NOT WITH_GTEST) + +if(NOT WITH_THREADS) + set(CMAKE_DISABLE_FIND_PACKAGE_Threads ON) +endif(NOT WITH_THREADS) + +set(CMAKE_C_VISIBILITY_PRESET hidden) +set(CMAKE_CXX_VISIBILITY_PRESET hidden) +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +set(CMAKE_VISIBILITY_INLINES_HIDDEN ON) + +set(CMAKE_DEBUG_POSTFIX d) +set(CMAKE_THREAD_PREFER_PTHREAD 1) + +find_package(GTest NO_MODULE) + +if(GTest_FOUND) + set(HAVE_LIB_GTEST 1) +endif(GTest_FOUND) + +if(WITH_GMOCK AND TARGET GTest::gmock) + set(HAVE_LIB_GMOCK 1) +endif(WITH_GMOCK AND TARGET GTest::gmock) + +if(WITH_GFLAGS) + # find_package (gflags 2.2.2) + + # if (gflags_FOUND) + set(HAVE_LIB_GFLAGS 1) + set(gflags_FOUND 1) + set(gflags_NAMESPACE + gflags + CACHE INTERNAL "gflags namespace") + # determine_gflags_namespace (gflags_NAMESPACE) endif (gflags_FOUND) +endif(WITH_GFLAGS) + +find_package(Threads) +find_package(Unwind) + +if(Unwind_FOUND) + set(HAVE_LIB_UNWIND 1) +else(Unwind_FOUND) + check_include_file_cxx(unwind.h HAVE_UNWIND_H) + # Check whether linking actually succeeds. ARM toolchains of LLVM unwind + # implementation do not necessarily provide the _Unwind_Backtrace function + # which causes the previous check to succeed but the linking to fail. + check_cxx_symbol_exists(_Unwind_Backtrace unwind.h HAVE__UNWIND_BACKTRACE) +endif(Unwind_FOUND) + +check_include_file_cxx(dlfcn.h HAVE_DLFCN_H) +check_include_file_cxx(execinfo.h HAVE_EXECINFO_H) +check_include_file_cxx(glob.h HAVE_GLOB_H) +check_include_file_cxx(inttypes.h HAVE_INTTYPES_H) +check_include_file_cxx(memory.h HAVE_MEMORY_H) +check_include_file_cxx(pwd.h HAVE_PWD_H) +check_include_file_cxx(stdint.h HAVE_STDINT_H) +check_include_file_cxx(strings.h HAVE_STRINGS_H) +check_include_file_cxx(sys/stat.h HAVE_SYS_STAT_H) +check_include_file_cxx(sys/syscall.h HAVE_SYS_SYSCALL_H) +check_include_file_cxx(sys/time.h HAVE_SYS_TIME_H) +check_include_file_cxx(sys/types.h HAVE_SYS_TYPES_H) +check_include_file_cxx(sys/utsname.h HAVE_SYS_UTSNAME_H) +check_include_file_cxx(sys/wait.h HAVE_SYS_WAIT_H) +check_include_file_cxx(syscall.h HAVE_SYSCALL_H) +check_include_file_cxx(syslog.h HAVE_SYSLOG_H) +check_include_file_cxx(ucontext.h HAVE_UCONTEXT_H) +check_include_file_cxx(unistd.h HAVE_UNISTD_H) + +check_include_file_cxx("ext/hash_map" HAVE_EXT_HASH_MAP) +check_include_file_cxx("ext/hash_set" HAVE_EXT_HASH_SET) +check_include_file_cxx("ext/slist" HAVE_EXT_SLIST) +check_include_file_cxx("tr1/unordered_map" HAVE_TR1_UNORDERED_MAP) +check_include_file_cxx("tr1/unordered_set" HAVE_TR1_UNORDERED_SET) +check_include_file_cxx("unordered_map" HAVE_UNORDERED_MAP) +check_include_file_cxx("unordered_set" HAVE_UNORDERED_SET) + +check_type_size("unsigned __int16" HAVE___UINT16 LANGUAGE CXX) +check_type_size(u_int16_t HAVE_U_INT16_T LANGUAGE CXX) +check_type_size(uint16_t HAVE_UINT16_T LANGUAGE CXX) + +check_function_exists(dladdr HAVE_DLADDR) +check_function_exists(fcntl HAVE_FCNTL) +check_function_exists(pread HAVE_PREAD) +check_function_exists(pwrite HAVE_PWRITE) +check_function_exists(sigaction HAVE_SIGACTION) +check_function_exists(sigaltstack HAVE_SIGALTSTACK) + +# NOTE gcc does not fail if you pass a non-existent -Wno-* option as an +# argument. However, it will happily fail if you pass the corresponding -W* +# option. So, we check whether options that disable warnings exist by testing +# the availability of the corresponding option that enables the warning. This +# eliminates the need to check for compiler for several (mainly Clang) options. + +check_cxx_compiler_flag(-Wdeprecated HAVE_NO_DEPRECATED) +check_cxx_compiler_flag(-Wunnamed-type-template-args + HAVE_NO_UNNAMED_TYPE_TEMPLATE_ARGS) + +cmake_push_check_state(RESET) + +if(Threads_FOUND) + set(CMAKE_REQUIRED_LIBRARIES Threads::Threads) +endif(Threads_FOUND) + +check_cxx_symbol_exists(pthread_threadid_np "pthread.h" + HAVE_PTHREAD_THREADID_NP) +cmake_pop_check_state() + +# NOTE: Cannot use check_function_exists here since >=vc-14.0 can define +# snprintf as an inline function +check_cxx_symbol_exists(snprintf cstdio HAVE_SNPRINTF) + +check_library_exists(dbghelp UnDecorateSymbolName "" HAVE_DBGHELP) + +check_cxx_source_compiles( + " +#include +static void foo(void) __attribute__ ((unused)); +int main(void) { return 0; } +" + HAVE___ATTRIBUTE__) + +check_cxx_source_compiles( + " +#include +static void foo(void) __attribute__ ((visibility(\"default\"))); +int main(void) { return 0; } +" + HAVE___ATTRIBUTE__VISIBILITY_DEFAULT) + +check_cxx_source_compiles( + " +#include +static void foo(void) __attribute__ ((visibility(\"hidden\"))); +int main(void) { return 0; } +" + HAVE___ATTRIBUTE__VISIBILITY_HIDDEN) + +check_cxx_source_compiles( + " +int main(void) { if (__builtin_expect(0, 0)) return 1; return 0; } +" HAVE___BUILTIN_EXPECT) + +check_cxx_source_compiles( + " +int main(void) +{ + int a; if (__sync_val_compare_and_swap(&a, 0, 1)) return 1; return 0; +} +" + HAVE___SYNC_VAL_COMPARE_AND_SWAP) + +cmake_push_check_state(RESET) +set(CMAKE_REQUIRED_LIBRARIES Threads::Threads) +check_cxx_source_compiles( + " +#define _XOPEN_SOURCE 500 +#include +int main(void) +{ + pthread_rwlock_t l; + pthread_rwlock_init(&l, NULL); + pthread_rwlock_rdlock(&l); + return 0; +} +" + HAVE_RWLOCK) +cmake_pop_check_state() + +check_cxx_source_compiles( + " +__declspec(selectany) int a; +int main(void) { return 0; } +" + HAVE___DECLSPEC) + +check_cxx_source_compiles( + " +#include +vector t; int main() { } +" + STL_NO_NAMESPACE) + +check_cxx_source_compiles( + " +#include +std::vector t; int main() { } +" + STL_STD_NAMESPACE) + +check_cxx_source_compiles( + " +#include +std::ostream& operator<<(std::ostream&, struct s); +using ::operator<<; +int main() { } +" + HAVE_USING_OPERATOR) + +check_cxx_source_compiles( + " +namespace Outer { namespace Inner { int i = 0; }} +using namespace Outer::Inner;; +int main() { return i; } +" + HAVE_NAMESPACES) + +check_cxx_source_compiles( + " +__thread int tls; +int main() { } +" + HAVE_GCC_TLS) + +check_cxx_source_compiles( + " +__declspec(thread) int tls; +int main() { } +" + HAVE_MSVC_TLS) + +check_cxx_source_compiles( + " +thread_local int tls; +int main() { } +" + HAVE_CXX11_TLS) + +check_cxx_source_compiles( + " +#include +std::aligned_storage::type data; +int main() { } +" + HAVE_ALIGNED_STORAGE) + +check_cxx_source_compiles( + " +#include +std::atomic i; +int main() { } +" + HAVE_CXX11_ATOMIC) + +check_cxx_source_compiles( + " +constexpr int x = 0; +int main() { } +" + HAVE_CXX11_CONSTEXPR) + +check_cxx_source_compiles( + " +#include +std::chrono::seconds s; +int main() { } +" + HAVE_CXX11_CHRONO) + +check_cxx_source_compiles( + " +#include +void foo(std::nullptr_t) {} +int main(void) { foo(nullptr); } +" + HAVE_CXX11_NULLPTR_T) + +if(WITH_TLS) + # Cygwin does not support the thread attribute. Don't bother. + if(HAVE_GCC_TLS) + set(GLOG_THREAD_LOCAL_STORAGE "__thread") + elseif(HAVE_MSVC_TLS) + set(GLOG_THREAD_LOCAL_STORAGE "__declspec(thread)") + elseif(HAVE_CXX11_TLS) + set(GLOG_THREAD_LOCAL_STORAGE thread_local) + endif(HAVE_GCC_TLS) +endif(WITH_TLS) + +set(_PC_FIELDS + "gregs[REG_PC]" + "gregs[REG_EIP]" + "gregs[REG_RIP]" + "sc_ip" + "uc_regs->gregs[PT_NIP]" + "gregs[R15]" + "arm_pc" + "mc_eip" + "mc_rip" + "__gregs[REG_EIP]" + "__gregs[REG_RIP]" + "ss.eip" + "__ss.__eip" + "ss.rip" + "__ss.__rip" + "ss.srr0" + "__ss.__srr0") + +set(_PC_HEADERS ucontext.h signal.h) + +if(HAVE_UCONTEXT_H AND NOT PC_FROM_UCONTEXT) + foreach(_PC_FIELD ${_PC_FIELDS}) + foreach(_PC_HEADER ${_PC_HEADERS}) + set(_TMP + ${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/uctfield.cpp + ) + file( + WRITE ${_TMP} + " +#define _GNU_SOURCE 1 +#include <${_PC_HEADER}> +int main(void) +{ + ucontext_t u; + return u.${_PC_FIELD} == 0; +} +") + try_compile( + HAVE_PC_FROM_UCONTEXT ${CMAKE_CURRENT_BINARY_DIR} + ${_TMP} + COMPILE_DEFINITIONS _GNU_SOURCE=1) + + if(HAVE_PC_FROM_UCONTEXT) + set(PC_FROM_UCONTEXT + ${_PC_FIELD} + CACHE) + endif(HAVE_PC_FROM_UCONTEXT) + endforeach(_PC_HEADER) + endforeach(_PC_FIELD) +endif(HAVE_UCONTEXT_H AND NOT PC_FROM_UCONTEXT) + +if(STL_STD_NAMESPACE) + set(STL_NAMESPACE std) +else(STL_STD_NAMESPACE) + set(STL_NAMESPACE "") +endif(STL_STD_NAMESPACE) + +set(GOOGLE_NAMESPACE google) +set(_START_GOOGLE_NAMESPACE_ "namespace ${GOOGLE_NAMESPACE} {") +set(_END_GOOGLE_NAMESPACE_ "}") +set(ac_cv_have_glog_export 1) + +if(HAVE___UINT16) + set(ac_cv_have___uint16 1) +else(HAVE___UINT16) + set(ac_cv_have___uint16 0) +endif(HAVE___UINT16) + +if(HAVE_INTTYPES_H) + set(ac_cv_have_inttypes_h 1) +else(HAVE_INTTYPES_H) + set(ac_cv_have_inttypes_h 0) +endif(HAVE_INTTYPES_H) + +if(HAVE_LIB_GFLAGS) + set(ac_cv_have_libgflags 1) +else(HAVE_LIB_GFLAGS) + set(ac_cv_have_libgflags 0) +endif(HAVE_LIB_GFLAGS) + +if(HAVE_STDINT_H) + set(ac_cv_have_stdint_h 1) +else(HAVE_STDINT_H) + set(ac_cv_have_stdint_h 0) +endif(HAVE_STDINT_H) + +if(HAVE_SYS_TYPES_H) + set(ac_cv_have_systypes_h 1) +else(HAVE_SYS_TYPES_H) + set(ac_cv_have_systypes_h 0) +endif(HAVE_SYS_TYPES_H) + +if(HAVE_U_INT16_T) + set(ac_cv_have_u_int16_t 1) +else(HAVE_U_INT16_T) + set(ac_cv_have_u_int16_t 0) +endif(HAVE_U_INT16_T) + +if(HAVE_UINT16_T) + set(ac_cv_have_uint16_t 1) +else(HAVE_UINT16_T) + set(ac_cv_have_uint16_t 0) +endif(HAVE_UINT16_T) + +if(HAVE_UNISTD_H) + set(ac_cv_have_unistd_h 1) +else(HAVE_UNISTD_H) + set(ac_cv_have_unistd_h 0) +endif(HAVE_UNISTD_H) + +set(ac_google_namespace ${GOOGLE_NAMESPACE}) +set(ac_google_end_namespace ${_END_GOOGLE_NAMESPACE_}) +set(ac_google_start_namespace ${_START_GOOGLE_NAMESPACE_}) + +if(HAVE___ATTRIBUTE__) + set(ac_cv___attribute___noreturn "__attribute__((noreturn))") + set(ac_cv___attribute___noinline "__attribute__((noinline))") + set(ac_cv___attribute___printf_4_5 + "__attribute__((__format__(__printf__, 4, 5)))") +elseif(HAVE___DECLSPEC) + set(ac_cv___attribute___noreturn "__declspec(noreturn)") + # set (ac_cv___attribute___noinline "__declspec(noinline)") +endif(HAVE___ATTRIBUTE__) + +if(HAVE___BUILTIN_EXPECT) + set(ac_cv_have___builtin_expect 1) +else(HAVE___BUILTIN_EXPECT) + set(ac_cv_have___builtin_expect 0) +endif(HAVE___BUILTIN_EXPECT) + +if(HAVE_USING_OPERATOR) + set(ac_cv_cxx_using_operator 1) +else(HAVE_USING_OPERATOR) + set(ac_cv_cxx_using_operator 0) +endif(HAVE_USING_OPERATOR) + +if(HAVE_CXX11_CONSTEXPR) + set(ac_cv_cxx11_constexpr 1) +else(HAVE_CXX11_CONSTEXPR) + set(ac_cv_cxx11_constexpr 0) +endif(HAVE_CXX11_CONSTEXPR) + +if(HAVE_CXX11_CHRONO) + set(ac_cv_cxx11_chrono 1) +else(HAVE_CXX11_CHRONO) + set(ac_cv_cxx11_chrono 0) +endif(HAVE_CXX11_CHRONO) + +if(HAVE_CXX11_NULLPTR_T) + set(ac_cv_cxx11_nullptr_t 1) +else(HAVE_CXX11_NULLPTR_T) + set(ac_cv_cxx11_nullptr_t 0) +endif(HAVE_CXX11_NULLPTR_T) + +if(HAVE_EXECINFO_H) + set(HAVE_STACKTRACE 1) +endif(HAVE_EXECINFO_H) + +if(HAVE_CXX11_ATOMIC) + set(ac_cv_cxx11_atomic 1) +else(HAVE_CXX11_ATOMIC) + set(ac_cv_cxx11_atomic 0) +endif(HAVE_CXX11_ATOMIC) + +if(WITH_SYMBOLIZE) + if(WIN32 OR CYGWIN) + cmake_push_check_state(RESET) + set(CMAKE_REQUIRED_LIBRARIES DbgHelp) + + check_cxx_source_runs( + [=[ + #include + #include + #include + + void foobar() { } + + int main() + { + HANDLE process = GetCurrentProcess(); + + if (!SymInitialize(process, NULL, TRUE)) + return EXIT_FAILURE; + + char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME]; + SYMBOL_INFO *symbol = reinterpret_cast(buf); + symbol->SizeOfStruct = sizeof(SYMBOL_INFO); + symbol->MaxNameLen = MAX_SYM_NAME; + + void* const pc = reinterpret_cast(&foobar); + BOOL ret = SymFromAddr(process, reinterpret_cast(pc), 0, symbol); + + return ret ? EXIT_SUCCESS : EXIT_FAILURE; + } + ]=] + HAVE_SYMBOLIZE) + + cmake_pop_check_state() + + if(HAVE_SYMBOLIZE) + set(HAVE_STACKTRACE 1) + endif(HAVE_SYMBOLIZE) + elseif(UNIX OR (APPLE AND HAVE_DLADDR)) + set(HAVE_SYMBOLIZE 1) + endif(WIN32 OR CYGWIN) +endif(WITH_SYMBOLIZE) + +# CMake manages symbolize availability. The definition is necessary only when +# building the library. Switch to add_compile_definitions once we drop support +# for CMake below version 3.12. +add_definitions(-DGLOG_NO_SYMBOLIZE_DETECTION) + +check_cxx_source_compiles( + " +#include +#include +int main() +{ + time_t timep; + struct tm result; + localtime_r(&timep, &result); + return EXIT_SUCCESS; +} +" + HAVE_LOCALTIME_R) + +set(SIZEOF_VOID_P ${CMAKE_SIZEOF_VOID_P}) + +if(WITH_THREADS AND Threads_FOUND) + if(CMAKE_USE_PTHREADS_INIT) + set(HAVE_PTHREAD 1) + endif(CMAKE_USE_PTHREADS_INIT) +else(WITH_THREADS AND Threads_FOUND) + set(NO_THREADS 1) +endif(WITH_THREADS AND Threads_FOUND) + +# fopen/open on Cygwin can not handle unix-type paths like /home/.... therefore +# we translate TEST_SRC_DIR to windows-path. +if(CYGWIN) + execute_process( + COMMAND cygpath.exe -m ${CMAKE_CURRENT_SOURCE_DIR} + OUTPUT_STRIP_TRAILING_WHITESPACE + OUTPUT_VARIABLE TEST_SRC_DIR) + set(TEST_SRC_DIR \"${TEST_SRC_DIR}\") +else(CYGWIN) + set(TEST_SRC_DIR \"${CMAKE_CURRENT_SOURCE_DIR}\") +endif(CYGWIN) + +configure_file(src/config.h.cmake.in config.h) +configure_file(src/glog/logging.h.in glog/logging.h @ONLY) +configure_file(src/glog/raw_logging.h.in glog/raw_logging.h @ONLY) +configure_file(src/glog/stl_logging.h.in glog/stl_logging.h @ONLY) +configure_file(src/glog/vlog_is_on.h.in glog/vlog_is_on.h @ONLY) + +add_compile_options( + $<$,$>>:-Wno-unnamed-type-template-args> +) + +set(_glog_CMake_BINDIR ${CMAKE_INSTALL_BINDIR}) +set(_glog_CMake_INCLUDE_DIR ${CMAKE_INSTALL_INCLUDEDIR}) +set(_glog_CMake_LIBDIR ${CMAKE_INSTALL_LIBDIR}) +set(_glog_CMake_INSTALLDIR ${_glog_CMake_LIBDIR}/cmake/glog) + +set(_glog_CMake_DIR glog/cmake) +set(_glog_CMake_DATADIR ${CMAKE_INSTALL_DATAROOTDIR}/${_glog_CMake_DIR}) +set(_glog_BINARY_CMake_DATADIR + ${CMAKE_CURRENT_BINARY_DIR}/${_glog_CMake_DATADIR}) + +# Add additional CMake find modules here. +set(_glog_CMake_MODULES) + +if(Unwind_FOUND) + # Copy the module only if libunwind is actually used. + list(APPEND _glog_CMake_MODULES + ${CMAKE_CURRENT_SOURCE_DIR}/cmake/FindUnwind.cmake) +endif(Unwind_FOUND) + +# Generate file name for each module in the binary directory +foreach(_file ${_glog_CMake_MODULES}) + get_filename_component(_module "${_file}" NAME) + + list(APPEND _glog_BINARY_CMake_MODULES + ${_glog_BINARY_CMake_DATADIR}/${_module}) +endforeach(_file) + +if(_glog_CMake_MODULES) + # Copy modules to binary directory during the build + add_custom_command( + OUTPUT ${_glog_BINARY_CMake_MODULES} + COMMAND ${CMAKE_COMMAND} -E make_directory ${_glog_BINARY_CMake_DATADIR} + COMMAND ${CMAKE_COMMAND} -E copy ${_glog_CMake_MODULES} + ${_glog_BINARY_CMake_DATADIR} + DEPENDS ${_glog_CMake_MODULES} + COMMENT "Copying find modules...") +endif(_glog_CMake_MODULES) + +set(GLOG_PUBLIC_H + ${CMAKE_CURRENT_BINARY_DIR}/glog/export.h + ${CMAKE_CURRENT_BINARY_DIR}/glog/logging.h + ${CMAKE_CURRENT_BINARY_DIR}/glog/raw_logging.h + ${CMAKE_CURRENT_BINARY_DIR}/glog/stl_logging.h + ${CMAKE_CURRENT_BINARY_DIR}/glog/vlog_is_on.h + src/glog/log_severity.h + src/glog/platform.h) + +set(GLOG_SRCS + ${GLOG_PUBLIC_H} + src/base/commandlineflags.h + src/base/googleinit.h + src/base/mutex.h + src/demangle.cc + src/demangle.h + src/logging.cc + src/raw_logging.cc + src/symbolize.cc + src/symbolize.h + src/utilities.cc + src/utilities.h + src/vlog_is_on.cc) + +if(HAVE_PTHREAD + OR WIN32 + OR CYGWIN) + list(APPEND GLOG_SRCS src/signalhandler.cc) +endif( + HAVE_PTHREAD + OR WIN32 + OR CYGWIN) + +if(CYGWIN OR WIN32) + list(APPEND GLOG_SRCS src/windows/port.cc src/windows/port.h) +endif(CYGWIN OR WIN32) + +add_library(glogbase OBJECT ${_glog_BINARY_CMake_MODULES} ${GLOG_SRCS}) + +add_library(glog $) + +add_library(glog::glog ALIAS glog) + +set(glog_libraries_options_for_static_linking) + +if(Unwind_FOUND) + target_link_libraries(glog PRIVATE unwind::unwind) + set(glog_libraries_options_for_static_linking + "${glog_libraries_options_for_static_linking} -lunwind") + set(Unwind_DEPENDENCY "find_dependency (Unwind ${Unwind_VERSION})") +endif(Unwind_FOUND) + +if(HAVE_DBGHELP) + target_link_libraries(glog PRIVATE dbghelp) + set(glog_libraries_options_for_static_linking + "${glog_libraries_options_for_static_linking} -ldbghelp") +endif(HAVE_DBGHELP) + +if(HAVE_PTHREAD) + target_link_libraries(glog PRIVATE ${CMAKE_THREAD_LIBS_INIT}) + + if(CMAKE_THREAD_LIBS_INIT) + set(glog_libraries_options_for_static_linking + "${glog_libraries_options_for_static_linking} ${CMAKE_THREAD_LIBS_INIT}" + ) + endif(CMAKE_THREAD_LIBS_INIT) +endif(HAVE_PTHREAD) + +if(gflags_FOUND) + # Prefer the gflags target that uses double colon convention + # target_link_libraries(glog PRIVATE gflags::gflags) + # if (TARGET + # gflags::gflags) target_link_libraries (glog PUBLIC gflags::gflags) else + # (TARGET gflags::gflags) target_link_libraries (glog PUBLIC gflags) endif + # (TARGET gflags::gflags) + + # set (glog_libraries_options_for_static_linking + # "${glog_libraries_options_for_static_linking} -lgflags") +endif(gflags_FOUND) + +if(ANDROID) + target_link_libraries(glog PRIVATE log) + set(glog_libraries_options_for_static_linking + "${glog_libraries_options_for_static_linking} -llog") +endif(ANDROID) + +set_target_properties(glog PROPERTIES VERSION ${PROJECT_VERSION}) +set_target_properties(glog PROPERTIES SOVERSION 1) + +if(CYGWIN OR WIN32) + target_compile_definitions(glog PUBLIC GLOG_NO_ABBREVIATED_SEVERITIES) +endif(CYGWIN OR WIN32) + +if(WITH_CUSTOM_PREFIX) + target_compile_definitions(glog PUBLIC GLOG_CUSTOM_PREFIX_SUPPORT) +endif(WITH_CUSTOM_PREFIX) + +set_target_properties(glog PROPERTIES PUBLIC_HEADER "${GLOG_PUBLIC_H}") + +target_include_directories( + glog BEFORE + PUBLIC "$" + "$" + "$" + PRIVATE ${CMAKE_CURRENT_BINARY_DIR} + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + +if(CYGWIN OR WIN32) + target_include_directories( + glogbase + PUBLIC "$" + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/windows) + + target_include_directories( + glog + PUBLIC "$" + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/windows) +endif(CYGWIN OR WIN32) + +set_target_properties(glog PROPERTIES DEFINE_SYMBOL GOOGLE_GLOG_IS_A_DLL) + +target_include_directories(glogbase + PUBLIC $) +target_compile_definitions( + glogbase + PUBLIC $ + PRIVATE GOOGLE_GLOG_IS_A_DLL) + +generate_export_header(glog EXPORT_MACRO_NAME GLOG_EXPORT EXPORT_FILE_NAME + ${CMAKE_CURRENT_BINARY_DIR}/glog/export.h) + +string(STRIP "${glog_libraries_options_for_static_linking}" + glog_libraries_options_for_static_linking) + +if(WITH_PKGCONFIG) + set(VERSION ${PROJECT_VERSION}) + set(prefix ${CMAKE_INSTALL_PREFIX}) + set(exec_prefix ${CMAKE_INSTALL_FULL_BINDIR}) + set(libdir ${CMAKE_INSTALL_FULL_LIBDIR}) + set(includedir ${CMAKE_INSTALL_FULL_INCLUDEDIR}) + + configure_file("${PROJECT_SOURCE_DIR}/libglog.pc.in" + "${PROJECT_BINARY_DIR}/libglog.pc" @ONLY) + + unset(VERSION) + unset(prefix) + unset(exec_prefix) + unset(libdir) + unset(includedir) +endif(WITH_PKGCONFIG) + +# Unit testing + +# if(BUILD_TESTING) +if(FALSE) + add_library(glogtest STATIC $) + + target_include_directories(glogtest + PUBLIC $) + target_compile_definitions( + glogtest PUBLIC $ + GLOG_STATIC_DEFINE) + target_link_libraries(glogtest PUBLIC $) + + set(_GLOG_TEST_LIBS glogtest) + + if(HAVE_LIB_GTEST) + list(APPEND _GLOG_TEST_LIBS GTest::gtest) + endif(HAVE_LIB_GTEST) + + if(HAVE_LIB_GMOCK) + list(APPEND _GLOG_TEST_LIBS GTest::gmock) + endif(HAVE_LIB_GMOCK) + + add_executable(logging_unittest src/logging_unittest.cc) + + target_link_libraries(logging_unittest PRIVATE ${_GLOG_TEST_LIBS}) + + if(WITH_CUSTOM_PREFIX) + add_executable(logging_custom_prefix_unittest + src/logging_custom_prefix_unittest.cc) + + target_link_libraries(logging_custom_prefix_unittest + PRIVATE ${_GLOG_TEST_LIBS}) + + add_test(NAME logging_custom_prefix COMMAND logging_custom_prefix_unittest) + + # FIXME: Skip flaky test + set_tests_properties( + logging_custom_prefix + PROPERTIES + SKIP_REGULAR_EXPRESSION + "Check failed: time_ns within LogTimes::LOG_PERIOD_TOL_NS of LogTimes::LOG_PERIOD_NS" + ) + + if(APPLE) + # FIXME: Skip flaky test + set_property( + TEST logging_custom_prefix + APPEND + PROPERTY + SKIP_REGULAR_EXPRESSION + "unexpected new.*PASS\nTest with golden file failed. We'll try to show the diff:" + ) + endif(APPLE) + endif(WITH_CUSTOM_PREFIX) + + add_executable(stl_logging_unittest src/stl_logging_unittest.cc) + + target_link_libraries(stl_logging_unittest PRIVATE ${_GLOG_TEST_LIBS}) + + if(HAVE_NO_DEPRECATED) + set_property( + TARGET stl_logging_unittest + APPEND + PROPERTY COMPILE_OPTIONS -Wno-deprecated) + endif(HAVE_NO_DEPRECATED) + + if(HAVE_UNORDERED_MAP AND HAVE_UNORDERED_SET) + target_compile_definitions(stl_logging_unittest + PRIVATE GLOG_STL_LOGGING_FOR_UNORDERED) + endif(HAVE_UNORDERED_MAP AND HAVE_UNORDERED_SET) + + if(HAVE_TR1_UNORDERED_MAP AND HAVE_TR1_UNORDERED_SET) + target_compile_definitions(stl_logging_unittest + PRIVATE GLOG_STL_LOGGING_FOR_TR1_UNORDERED) + endif(HAVE_TR1_UNORDERED_MAP AND HAVE_TR1_UNORDERED_SET) + + if(HAVE_EXT_HASH_MAP AND HAVE_EXT_HASH_SET) + target_compile_definitions(stl_logging_unittest + PRIVATE GLOG_STL_LOGGING_FOR_EXT_HASH) + endif(HAVE_EXT_HASH_MAP AND HAVE_EXT_HASH_SET) + + if(HAVE_EXT_SLIST) + target_compile_definitions(stl_logging_unittest + PRIVATE GLOG_STL_LOGGING_FOR_EXT_SLIST) + endif(HAVE_EXT_SLIST) + + if(HAVE_SYMBOLIZE) + add_executable(symbolize_unittest src/symbolize_unittest.cc) + + target_link_libraries(symbolize_unittest PRIVATE ${_GLOG_TEST_LIBS}) + endif(HAVE_SYMBOLIZE) + + add_executable(demangle_unittest src/demangle_unittest.cc) + + target_link_libraries(demangle_unittest PRIVATE ${_GLOG_TEST_LIBS}) + + if(HAVE_STACKTRACE) + add_executable(stacktrace_unittest src/stacktrace_unittest.cc) + + target_link_libraries(stacktrace_unittest PRIVATE ${_GLOG_TEST_LIBS}) + endif(HAVE_STACKTRACE) + + add_executable(utilities_unittest src/utilities_unittest.cc) + + target_link_libraries(utilities_unittest PRIVATE ${_GLOG_TEST_LIBS}) + + if(HAVE_STACKTRACE AND HAVE_SYMBOLIZE) + add_executable(signalhandler_unittest src/signalhandler_unittest.cc) + + target_link_libraries(signalhandler_unittest PRIVATE ${_GLOG_TEST_LIBS}) + endif(HAVE_STACKTRACE AND HAVE_SYMBOLIZE) + + add_test(NAME demangle COMMAND demangle_unittest) + add_test(NAME logging COMMAND logging_unittest) + + set_tests_properties(logging PROPERTIES TIMEOUT 30) + + # FIXME: Skip flaky test + set_tests_properties( + logging + PROPERTIES + SKIP_REGULAR_EXPRESSION + "Check failed: time_ns within LogTimes::LOG_PERIOD_TOL_NS of LogTimes::LOG_PERIOD_NS" + ) + + if(APPLE) + # FIXME: Skip flaky test + set_property( + TEST logging + APPEND + PROPERTY + SKIP_REGULAR_EXPRESSION + "unexpected new.*PASS\nTest with golden file failed. We'll try to show the diff:" + ) + endif(APPLE) + + if(TARGET signalhandler_unittest) + add_test(NAME signalhandler COMMAND signalhandler_unittest) + endif(TARGET signalhandler_unittest) + + if(TARGET stacktrace_unittest) + add_test(NAME stacktrace COMMAND stacktrace_unittest) + set_tests_properties(stacktrace PROPERTIES TIMEOUT 30) + endif(TARGET stacktrace_unittest) + + add_test(NAME stl_logging COMMAND stl_logging_unittest) + + if(TARGET symbolize_unittest) + add_test(NAME symbolize COMMAND symbolize_unittest) + endif(TARGET symbolize_unittest) + + if(HAVE_LIB_GMOCK) + add_executable(mock-log_unittest src/mock-log_unittest.cc src/mock-log.h) + + target_link_libraries(mock-log_unittest PRIVATE ${_GLOG_TEST_LIBS}) + + add_test(NAME mock-log COMMAND mock-log_unittest) + endif(HAVE_LIB_GMOCK) + + # Generate an initial cache + + get_cache_variables(_CACHEVARS) + + set(_INITIAL_CACHE + ${CMAKE_CURRENT_BINARY_DIR}/test_package_config/glog_package_config_initial_cache.cmake + ) + + # Package config test + + add_test( + NAME cmake_package_config_init + COMMAND + ${CMAKE_COMMAND} + -DTEST_BINARY_DIR=${CMAKE_CURRENT_BINARY_DIR}/test_package_config + -DINITIAL_CACHE=${_INITIAL_CACHE} -DCACHEVARS=${_CACHEVARS} -P + ${CMAKE_CURRENT_SOURCE_DIR}/cmake/TestInitPackageConfig.cmake) + + add_test( + NAME cmake_package_config_generate + COMMAND + ${CMAKE_COMMAND} -DGENERATOR=${CMAKE_GENERATOR} + -DGENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM} + -DGENERATOR_TOOLSET=${CMAKE_GENERATOR_TOOLSET} + -DINITIAL_CACHE=${_INITIAL_CACHE} + -DPACKAGE_DIR=${CMAKE_CURRENT_BINARY_DIR} -DPATH=$ENV{PATH} + -DSOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR}/src/package_config_unittest/working_config + -DTEST_BINARY_DIR=${CMAKE_CURRENT_BINARY_DIR}/test_package_config/working_config + -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/TestPackageConfig.cmake) + + add_test( + NAME cmake_package_config_build + COMMAND + ${CMAKE_COMMAND} --build + ${CMAKE_CURRENT_BINARY_DIR}/test_package_config/working_config --config + $) + + add_test(NAME cmake_package_config_cleanup + COMMAND ${CMAKE_COMMAND} -E remove_directory + ${CMAKE_CURRENT_BINARY_DIR}/test_package_config) + + # Fixtures setup + set_tests_properties(cmake_package_config_init + PROPERTIES FIXTURES_SETUP cmake_package_config) + set_tests_properties(cmake_package_config_generate + PROPERTIES FIXTURES_SETUP cmake_package_config_working) + + # Fixtures cleanup + set_tests_properties(cmake_package_config_cleanup + PROPERTIES FIXTURES_CLEANUP cmake_package_config) + + # Fixture requirements + set_tests_properties(cmake_package_config_generate + PROPERTIES FIXTURES_REQUIRED cmake_package_config) + set_tests_properties( + cmake_package_config_build + PROPERTIES FIXTURES_REQUIRED + "cmake_package_config;cmake_package_config_working") + + add_executable(cleanup_immediately_unittest + src/cleanup_immediately_unittest.cc) + + target_link_libraries(cleanup_immediately_unittest PRIVATE ${_GLOG_TEST_LIBS}) + + add_executable(cleanup_with_absolute_prefix_unittest + src/cleanup_with_absolute_prefix_unittest.cc) + + target_link_libraries(cleanup_with_absolute_prefix_unittest + PRIVATE ${_GLOG_TEST_LIBS}) + + add_executable(cleanup_with_relative_prefix_unittest + src/cleanup_with_relative_prefix_unittest.cc) + + target_link_libraries(cleanup_with_relative_prefix_unittest + PRIVATE ${_GLOG_TEST_LIBS}) + + set(CLEANUP_LOG_DIR ${CMAKE_CURRENT_BINARY_DIR}/cleanup_tests) + + add_test(NAME cleanup_init COMMAND ${CMAKE_COMMAND} -E make_directory + ${CLEANUP_LOG_DIR}) + add_test(NAME cleanup_logdir COMMAND ${CMAKE_COMMAND} -E remove_directory + ${CLEANUP_LOG_DIR}) + add_test( + NAME cleanup_immediately + COMMAND + ${CMAKE_COMMAND} -DLOGCLEANUP=$ + # NOTE The trailing slash is important + -DTEST_DIR=${CLEANUP_LOG_DIR}/ -P + ${CMAKE_CURRENT_SOURCE_DIR}/cmake/RunCleanerTest1.cmake + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) + add_test( + NAME cleanup_with_absolute_prefix + COMMAND + ${CMAKE_COMMAND} + -DLOGCLEANUP=$ + -DTEST_DIR=${CMAKE_CURRENT_BINARY_DIR}/ -P + ${CMAKE_CURRENT_SOURCE_DIR}/cmake/RunCleanerTest2.cmake + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) + add_test( + NAME cleanup_with_relative_prefix + COMMAND + ${CMAKE_COMMAND} + -DLOGCLEANUP=$ + -DTEST_DIR=${CMAKE_CURRENT_BINARY_DIR}/ -DTEST_SUBDIR=test_subdir/ -P + ${CMAKE_CURRENT_SOURCE_DIR}/cmake/RunCleanerTest3.cmake + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) + + # Fixtures setup + set_tests_properties(cleanup_init PROPERTIES FIXTURES_SETUP logcleanuptest) + # Fixtures cleanup + set_tests_properties(cleanup_logdir PROPERTIES FIXTURES_CLEANUP + logcleanuptest) + # Fixture requirements + set_tests_properties(cleanup_immediately PROPERTIES FIXTURES_REQUIRED + logcleanuptest) + set_tests_properties(cleanup_with_absolute_prefix PROPERTIES FIXTURES_REQUIRED + logcleanuptest) + set_tests_properties(cleanup_with_relative_prefix PROPERTIES FIXTURES_REQUIRED + logcleanuptest) +endif() +# endif(BUILD_TESTING) + +# install (TARGETS glog EXPORT glog-targets RUNTIME DESTINATION +# ${_glog_CMake_BINDIR} PUBLIC_HEADER DESTINATION +# ${_glog_CMake_INCLUDE_DIR}/glog LIBRARY DESTINATION ${_glog_CMake_LIBDIR} +# ARCHIVE DESTINATION ${_glog_CMake_LIBDIR}) +# +if(WITH_PKGCONFIG) + install(FILES "${PROJECT_BINARY_DIR}/libglog.pc" + DESTINATION "${_glog_CMake_LIBDIR}/pkgconfig") +endif(WITH_PKGCONFIG) + +set(glog_CMake_VERSION 3.0) + +# if (gflags_FOUND) # Ensure clients locate only the package config and not +# third party find # modules having the same name. This avoid cmake_policy +# PUSH/POP errors. if (CMAKE_VERSION VERSION_LESS 3.9) set (gflags_DEPENDENCY +# "find_dependency (gflags ${gflags_VERSION})") else (CMAKE_VERSION VERSION_LESS +# 3.9) # Passing additional find_package arguments to find_dependency is +# possible # starting with CMake 3.9. set (glog_CMake_VERSION 3.9) set +# (gflags_DEPENDENCY "find_dependency (gflags ${gflags_VERSION} NO_MODULE)") +# endif (CMAKE_VERSION VERSION_LESS 3.9) endif (gflags_FOUND) + +# configure_package_config_file( glog-config.cmake.in +# ${CMAKE_CURRENT_BINARY_DIR}/glog-config.cmake INSTALL_DESTINATION +# ${_glog_CMake_INSTALLDIR} NO_CHECK_REQUIRED_COMPONENTS_MACRO) +# +# write_basic_package_version_file( +# ${CMAKE_CURRENT_BINARY_DIR}/glog-config-version.cmake COMPATIBILITY +# SameMajorVersion) + +# export (TARGETS glog NAMESPACE glog:: FILE glog-targets.cmake) export (PACKAGE +# glog) + +get_filename_component(_PREFIX "${CMAKE_INSTALL_PREFIX}" ABSOLUTE) + +# Directory containing the find modules relative to the config install +# directory. +file(RELATIVE_PATH glog_REL_CMake_MODULES ${_PREFIX}/${_glog_CMake_INSTALLDIR} + ${_PREFIX}/${_glog_CMake_DATADIR}/glog-modules.cmake) + +get_filename_component(glog_REL_CMake_DATADIR ${glog_REL_CMake_MODULES} + DIRECTORY) + +set(glog_FULL_CMake_DATADIR ${CMAKE_CURRENT_BINARY_DIR}/${_glog_CMake_DATADIR}) + +# configure_file(glog-modules.cmake.in +# ${CMAKE_CURRENT_BINARY_DIR}/glog-modules.cmake @ONLY) + +install( + CODE " +set (glog_FULL_CMake_DATADIR \"\\\${CMAKE_CURRENT_LIST_DIR}/${glog_REL_CMake_DATADIR}\") +set (glog_DATADIR_DESTINATION ${_glog_CMake_INSTALLDIR}) + +if (NOT IS_ABSOLUTE ${_glog_CMake_INSTALLDIR}) + set (glog_DATADIR_DESTINATION \"\${CMAKE_INSTALL_PREFIX}/\${glog_DATADIR_DESTINATION}\") +endif (NOT IS_ABSOLUTE ${_glog_CMake_INSTALLDIR}) + +configure_file (\"${CMAKE_CURRENT_SOURCE_DIR}/glog-modules.cmake.in\" + \"${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/glog-modules.cmake\" @ONLY) +file (INSTALL + \"${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/glog-modules.cmake\" + DESTINATION + \"\${glog_DATADIR_DESTINATION}\") +" + COMPONENT Development) + +# install (FILES ${CMAKE_CURRENT_BINARY_DIR}/glog-config.cmake +# ${CMAKE_CURRENT_BINARY_DIR}/glog-config-version.cmake DESTINATION +# ${_glog_CMake_INSTALLDIR}) + +# Find modules in share/glog/cmake install (DIRECTORY +# ${_glog_BINARY_CMake_DATADIR} DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/glog +# COMPONENT Development FILES_MATCHING PATTERN "*.cmake" ) + +# install (EXPORT glog-targets NAMESPACE glog:: DESTINATION +# ${_glog_CMake_INSTALLDIR}) diff --git a/third_party/glog/CONTRIBUTORS b/third_party/glog/CONTRIBUTORS new file mode 100644 index 0000000..05cb688 --- /dev/null +++ b/third_party/glog/CONTRIBUTORS @@ -0,0 +1,52 @@ +# People who have agreed to one of the CLAs and can contribute patches. +# The AUTHORS file lists the copyright holders; this file +# lists people. For example, Google employees are listed here +# but not in AUTHORS, because Google holds the copyright. +# +# Names should be added to this file only after verifying that +# the individual or the individual's organization has agreed to +# the appropriate Contributor License Agreement, found here: +# +# https://developers.google.com/open-source/cla/individual +# https://developers.google.com/open-source/cla/corporate +# +# The agreement for individuals can be filled out on the web. +# +# When adding J Random Contributor's name to this file, +# either J's name or J's organization's name should be +# added to the AUTHORS file, depending on whether the +# individual or corporate CLA was used. +# +# Names should be added to this file as: +# Name +# +# Please keep the list sorted. + +Abhishek Dasgupta +Abhishek Parmar +Andrew Schwartzmeyer +Andy Ying +Bret McKee +Brian Silverman +Dmitriy Arbitman +Fumitoshi Ukai +Guillaume Dumont +HÃ¥kan L. S. Younes +Ivan Penkov +Jacob Trimble +Jim Ray +Marco Wang +Michael Darr +Michael Tanner +MiniLight +Peter Collingbourne +Rodrigo Queiro +romange +Roman Perepelitsa +Sergiu Deitsch +Shinichiro Hamaji +tbennun +Teddy Reed +Vijaymahantesh Sattigeri +Zhongming Qu +Zhuoran Shen diff --git a/third_party/glog/COPYING b/third_party/glog/COPYING new file mode 100644 index 0000000..38396b5 --- /dev/null +++ b/third_party/glog/COPYING @@ -0,0 +1,65 @@ +Copyright (c) 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +A function gettimeofday in utilities.cc is based on + +http://www.google.com/codesearch/p?hl=en#dR3YEbitojA/COPYING&q=GetSystemTimeAsFileTime%20license:bsd + +The license of this code is: + +Copyright (c) 2003-2008, Jouni Malinen and contributors +All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the name(s) of the above-listed copyright holder(s) nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/third_party/glog/ChangeLog b/third_party/glog/ChangeLog new file mode 100644 index 0000000..a107e93 --- /dev/null +++ b/third_party/glog/ChangeLog @@ -0,0 +1,109 @@ +2022-04-05 Google Inc. + + * google-glog: version 0.6.0. + * See git log for the details. + +2021-05-08 Google Inc. + + * google-glog: version 0.5.0. + * See git log for the details. + +2019-01-22 Google Inc. + + * google-glog: version 0.4.0. + * See git log for the details. + +2017-05-09 Google Inc. + + * google-glog: version 0.3.5 + * See git log for the details. + +2015-03-09 Google Inc. + + * google-glog: version 0.3.4 + * See git log for the details. + +2013-02-01 Google Inc. + + * google-glog: version 0.3.3 + * Add --disable-rtti option for configure. + * Visual Studio build and test fix. + * QNX build fix (thanks vanuan). + * Reduce warnings. + * Fixed LOG_SYSRESULT (thanks ukai). + * FreeBSD build fix (thanks yyanagisawa). + * Clang build fix. + * Now users can re-initialize glog after ShutdownGoogleLogging. + * Color output support by GLOG_colorlogtostderr (thanks alexs). + * Now glog's ABI around flags are compatible with gflags. + * Document mentions how to modify flags from user programs. + +2012-01-12 Google Inc. + + * google-glog: version 0.3.2 + * Clang support. + * Demangler and stacktrace improvement for newer GCCs. + * Now fork(2) doesn't mess up log files. + * Make valgrind happier. + * Reduce warnings for more -W options. + * Provide a workaround for ERROR defined by windows.h. + +2010-06-15 Google Inc. + + * google-glog: version 0.3.1 + * GLOG_* environment variables now work even when gflags is installed. + * Snow leopard support. + * Now we can build and test from out side tree. + * Add DCHECK_NOTNULL. + * Add ShutdownGoogleLogging to close syslog (thanks DGunchev) + * Fix --enable-frame-pointers option (thanks kazuki.ohta) + * Fix libunwind detection (thanks giantchen) + +2009-07-30 Google Inc. + + * google-glog: version 0.3.0 + * Fix a deadlock happened when user uses glog with recent gflags. + * Suppress several unnecessary warnings (thanks keir). + * NetBSD and OpenBSD support. + * Use Win32API GetComputeNameA properly (thanks magila). + * Fix user name detection for Windows (thanks ademin). + * Fix several minor bugs. + +2009-04-10 Google Inc. + * google-glog: version 0.2.1 + * Fix timestamps of VC++ version. + * Add pkg-config support (thanks Tomasz) + * Fix build problem when building with gtest (thanks Michael) + * Add --with-gflags option for configure (thanks Michael) + * Fixes for GCC 4.4 (thanks John) + +2009-01-23 Google Inc. + * google-glog: version 0.2 + * Add initial Windows VC++ support. + * Google testing/mocking frameworks integration. + * Link pthread library automatically. + * Flush logs in signal handlers. + * Add macros LOG_TO_STRING, LOG_AT_LEVEL, DVLOG, and LOG_TO_SINK_ONLY. + * Log microseconds. + * Add --log_backtrace_at option. + * Fix some minor bugs. + +2008-11-18 Google Inc. + * google-glog: version 0.1.2 + * Add InstallFailureSignalHandler(). (satorux) + * Re-organize the way to produce stacktraces. + * Don't define unnecessary macro DISALLOW_EVIL_CONSTRUCTORS. + +2008-10-15 Google Inc. + * google-glog: version 0.1.1 + * Support symbolize for MacOSX 10.5. + * BUG FIX: --vmodule didn't work with gflags. + * BUG FIX: symbolize_unittest failed with GCC 4.3. + * Several fixes on the document. + +2008-10-07 Google Inc. + + * google-glog: initial release: + The glog package contains a library that implements application-level + logging. This library provides logging APIs based on C++-style + streams and various helper macros. diff --git a/third_party/glog/README.rst b/third_party/glog/README.rst new file mode 100644 index 0000000..0131f49 --- /dev/null +++ b/third_party/glog/README.rst @@ -0,0 +1,879 @@ +Google Logging Library +====================== + +|Linux Github actions| |Windows Github actions| |macOS Github actions| |Total alerts| |Language grade: C++| |Codecov| + +Google Logging (glog) is a C++98 library that implements application-level +logging. The library provides logging APIs based on C++-style streams and +various helper macros. + +.. role:: cmake(code) + :language: cmake + +.. role:: cmd(code) + :language: bash + +.. role:: cpp(code) + :language: cpp + +.. role:: bazel(code) + :language: starlark + + +Getting Started +--------------- + +You can log a message by simply streaming things to ``LOG``\ (`__>), e.g., + +.. code:: cpp + + #include + + int main(int argc, char* argv[]) { + // Initialize Google’s logging library. + google::InitGoogleLogging(argv[0]); + + // ... + LOG(INFO) << "Found " << num_cookies << " cookies"; + } + + +For a detailed overview of glog features and their usage, please refer +to the `user guide <#user-guide>`__. + +.. contents:: Table of Contents + + +Building from Source +-------------------- + +glog supports multiple build systems for compiling the project from +source: `Bazel <#bazel>`__, `CMake <#cmake>`__, and `vcpkg <#vcpkg>`__. + +Bazel +~~~~~ + +To use glog within a project which uses the +`Bazel `__ build tool, add the following lines to +your ``WORKSPACE`` file: + +.. code:: bazel + + load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + + http_archive( + name = "com_github_gflags_gflags", + sha256 = "34af2f15cf7367513b352bdcd2493ab14ce43692d2dcd9dfc499492966c64dcf", + strip_prefix = "gflags-2.2.2", + urls = ["https://github.com/gflags/gflags/archive/v2.2.2.tar.gz"], + ) + + http_archive( + name = "com_github_google_glog", + sha256 = "21bc744fb7f2fa701ee8db339ded7dce4f975d0d55837a97be7d46e8382dea5a", + strip_prefix = "glog-0.5.0", + urls = ["https://github.com/google/glog/archive/v0.5.0.zip"], + ) + +You can then add :bazel:`@com_github_google_glog//:glog` to the deps section +of a :bazel:`cc_binary` or :bazel:`cc_library` rule, and :code:`#include +` to include it in your source code. Here’s a simple example: + +.. code:: bazel + + cc_binary( + name = "main", + srcs = ["main.cc"], + deps = ["@com_github_google_glog//:glog"], + ) + +CMake +~~~~~ + +glog also supports CMake that can be used to build the project on a wide +range of platforms. If you don’t have CMake installed already, you can +download it for from CMake’s `official +website `__. + +CMake works by generating native makefiles or build projects that can be +used in the compiler environment of your choice. You can either build +glog with CMake as a standalone project or it can be incorporated into +an existing CMake build for another project. + +Building glog with CMake +^^^^^^^^^^^^^^^^^^^^^^^^ + +When building glog as a standalone project, on Unix-like systems with +GNU Make as build tool, the typical workflow is: + +1. Get the source code and change to it. e.g., cloning with git: + + .. code:: bash + + git clone https://github.com/google/glog.git + cd glog + +2. Run CMake to configure the build tree. + + .. code:: bash + + cmake -S . -B build -G "Unix Makefiles" + + CMake provides different generators, and by default will pick the most + relevant one to your environment. If you need a specific version of Visual + Studio, use :cmd:`cmake . -G `, and see :cmd:`cmake --help` + for the available generators. Also see :cmd:`-T `, which can + be used to request the native x64 toolchain with :cmd:`-T host=x64`. + +3. Afterwards, generated files can be used to compile the project. + + .. code:: bash + + cmake --build build + +4. Test the build software (optional). + + .. code:: bash + + cmake --build build --target test + +5. Install the built files (optional). + + .. code:: bash + + cmake --build build --target install + +Consuming glog in a CMake Project +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If you have glog installed in your system, you can use the CMake command +:cmake:`find_package` to build against glog in your CMake Project as follows: + +.. code:: cmake + + cmake_minimum_required (VERSION 3.16) + project (myproj VERSION 1.0) + + find_package (glog 0.6.0 REQUIRED) + + add_executable (myapp main.cpp) + target_link_libraries (myapp glog::glog) + +Compile definitions and options will be added automatically to your +target as needed. + +Incorporating glog into a CMake Project +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +You can also use the CMake command :cmake:`add_subdirectory` to include glog +directly from a subdirectory of your project by replacing the +:cmake:`find_package` call from the previous example by +:cmake:`add_subdirectory`. The :cmake:`glog::glog` target is in this case an +:cmake:`ALIAS` library target for the ``glog`` library target. + +Again, compile definitions and options will be added automatically to +your target as needed. + +vcpkg +~~~~~ + +You can download and install glog using the `vcpkg +`__ dependency manager: + +.. code:: bash + + git clone https://github.com/Microsoft/vcpkg.git + cd vcpkg + ./bootstrap-vcpkg.sh + ./vcpkg integrate install + ./vcpkg install glog + +The glog port in vcpkg is kept up to date by Microsoft team members and +community contributors. If the version is out of date, please create an +issue or pull request on the vcpkg repository. + +User Guide +---------- + +glog defines a series of macros that simplify many common logging tasks. +You can log messages by severity level, control logging behavior from +the command line, log based on conditionals, abort the program when +expected conditions are not met, introduce your own verbose logging +levels, customize the prefix attached to log messages, and more. + +Following sections describe the functionality supported by glog. Please note +this description may not be complete but limited to the most useful ones. If you +want to find less common features, please check header files under `src/glog +`__ directory. + +Severity Levels +~~~~~~~~~~~~~~~ + +You can specify one of the following severity levels (in increasing +order of severity): ``INFO``, ``WARNING``, ``ERROR``, and ``FATAL``. +Logging a ``FATAL`` message terminates the program (after the message is +logged). Note that messages of a given severity are logged not only in +the logfile for that severity, but also in all logfiles of lower +severity. E.g., a message of severity ``FATAL`` will be logged to the +logfiles of severity ``FATAL``, ``ERROR``, ``WARNING``, and ``INFO``. + +The ``DFATAL`` severity logs a ``FATAL`` error in debug mode (i.e., +there is no ``NDEBUG`` macro defined), but avoids halting the program in +production by automatically reducing the severity to ``ERROR``. + +Unless otherwise specified, glog writes to the filename +``/tmp/\.\.\.log.\.\-\.\`` +(e.g., +``/tmp/hello_world.example.com.hamaji.log.INFO.20080709-222411.10474``). +By default, glog copies the log messages of severity level ``ERROR`` or +``FATAL`` to standard error (``stderr``) in addition to log files. + +Setting Flags +~~~~~~~~~~~~~ + +Several flags influence glog’s output behavior. If the `Google gflags library +`__ is installed on your machine, the build +system will automatically detect and use it, allowing you to pass flags on the +command line. For example, if you want to turn the flag :cmd:`--logtostderr` on, +you can start your application with the following command line: + +.. code:: bash + + ./your_application --logtostderr=1 + +If the Google gflags library isn’t installed, you set flags via +environment variables, prefixing the flag name with ``GLOG_``, e.g., + +.. code:: bash + + GLOG_logtostderr=1 ./your_application + +The following flags are most commonly used: + +``logtostderr`` (``bool``, default=\ ``false``) + Log messages to ``stderr`` instead of logfiles. Note: you can set + binary flags to ``true`` by specifying ``1``, ``true``, or ``yes`` + (case insensitive). Also, you can set binary flags to ``false`` by + specifying ``0``, ``false``, or ``no`` (again, case insensitive). + +``stderrthreshold`` (``int``, default=2, which is ``ERROR``) + Copy log messages at or above this level to stderr in addition to + logfiles. The numbers of severity levels ``INFO``, ``WARNING``, + ``ERROR``, and ``FATAL`` are 0, 1, 2, and 3, respectively. + +``minloglevel`` (``int``, default=0, which is ``INFO``) + Log messages at or above this level. Again, the numbers of severity + levels ``INFO``, ``WARNING``, ``ERROR``, and ``FATAL`` are 0, 1, 2, + and 3, respectively. + +``log_dir`` (``string``, default="") + If specified, logfiles are written into this directory instead of the + default logging directory. + +``v`` (``int``, default=0) + Show all ``VLOG(m)`` messages for ``m`` less or equal the value of + this flag. Overridable by :cmd:`--vmodule`. See `the section about + verbose logging <#verbose-logging>`__ for more detail. + +``vmodule`` (``string``, default="") + Per-module verbose level. The argument has to contain a + comma-separated list of =. is a + glob pattern (e.g., ``gfs*`` for all modules whose name starts with + "gfs"), matched against the filename base (that is, name ignoring + .cc/.h./-inl.h). overrides any value given by :cmd:`--v`. + See also `the section about verbose logging <#verbose-logging>`__. + +There are some other flags defined in logging.cc. Please grep the source +code for ``DEFINE_`` to see a complete list of all flags. + +You can also modify flag values in your program by modifying global +variables ``FLAGS_*`` . Most settings start working immediately after +you update ``FLAGS_*`` . The exceptions are the flags related to +destination files. For example, you might want to set ``FLAGS_log_dir`` +before calling :cpp:`google::InitGoogleLogging` . Here is an example: + +.. code:: cpp + + LOG(INFO) << "file"; + // Most flags work immediately after updating values. + FLAGS_logtostderr = 1; + LOG(INFO) << "stderr"; + FLAGS_logtostderr = 0; + // This won’t change the log destination. If you want to set this + // value, you should do this before google::InitGoogleLogging . + FLAGS_log_dir = "/some/log/directory"; + LOG(INFO) << "the same file"; + +Conditional / Occasional Logging +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Sometimes, you may only want to log a message under certain conditions. +You can use the following macros to perform conditional logging: + +.. code:: cpp + + LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies"; + +The "Got lots of cookies" message is logged only when the variable +``num_cookies`` exceeds 10. If a line of code is executed many times, it +may be useful to only log a message at certain intervals. This kind of +logging is most useful for informational messages. + +.. code:: cpp + + LOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie"; + +The above line outputs a log messages on the 1st, 11th, 21st, ... times +it is executed. Note that the special ``google::COUNTER`` value is used +to identify which repetition is happening. + +You can combine conditional and occasional logging with the following +macro. + +.. code:: cpp + + LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << google::COUNTER + << "th big cookie"; + +Instead of outputting a message every nth time, you can also limit the +output to the first n occurrences: + +.. code:: cpp + + LOG_FIRST_N(INFO, 20) << "Got the " << google::COUNTER << "th cookie"; + +Outputs log messages for the first 20 times it is executed. Again, the +``google::COUNTER`` identifier indicates which repetition is happening. + +Other times, it is desired to only log a message periodically based on a time. +So for example, to log a message every 10ms: + +.. code:: cpp + + LOG_EVERY_T(INFO, 0.01) << "Got a cookie"; + +Or every 2.35s: + +.. code:: cpp + + LOG_EVERY_T(INFO, 2.35) << "Got a cookie"; + +Debug Mode Support +~~~~~~~~~~~~~~~~~~ + +Special "debug mode" logging macros only have an effect in debug mode +and are compiled away to nothing for non-debug mode compiles. Use these +macros to avoid slowing down your production application due to +excessive logging. + +.. code:: cpp + + DLOG(INFO) << "Found cookies"; + DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies"; + DLOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie"; + + +``CHECK`` Macros +~~~~~~~~~~~~~~~~ + +It is a good practice to check expected conditions in your program +frequently to detect errors as early as possible. The ``CHECK`` macro +provides the ability to abort the application when a condition is not +met, similar to the ``assert`` macro defined in the standard C library. + +``CHECK`` aborts the application if a condition is not true. Unlike +``assert``, it is \*not\* controlled by ``NDEBUG``, so the check will be +executed regardless of compilation mode. Therefore, ``fp->Write(x)`` in +the following example is always executed: + +.. code:: cpp + + CHECK(fp->Write(x) == 4) << "Write failed!"; + +There are various helper macros for equality/inequality checks - +``CHECK_EQ``, ``CHECK_NE``, ``CHECK_LE``, ``CHECK_LT``, ``CHECK_GE``, +and ``CHECK_GT``. They compare two values, and log a ``FATAL`` message +including the two values when the result is not as expected. The values +must have :cpp:`operator<<(ostream, ...)` defined. + +You may append to the error message like so: + +.. code:: cpp + + CHECK_NE(1, 2) << ": The world must be ending!"; + +We are very careful to ensure that each argument is evaluated exactly +once, and that anything which is legal to pass as a function argument is +legal here. In particular, the arguments may be temporary expressions +which will end up being destroyed at the end of the apparent statement, +for example: + +.. code:: cpp + + CHECK_EQ(string("abc")[1], ’b’); + +The compiler reports an error if one of the arguments is a pointer and the other +is :cpp:`NULL`. To work around this, simply :cpp:`static_cast` :cpp:`NULL` to +the type of the desired pointer. + +.. code:: cpp + + CHECK_EQ(some_ptr, static_cast(NULL)); + +Better yet, use the ``CHECK_NOTNULL`` macro: + +.. code:: cpp + + CHECK_NOTNULL(some_ptr); + some_ptr->DoSomething(); + +Since this macro returns the given pointer, this is very useful in +constructor initializer lists. + +.. code:: cpp + + struct S { + S(Something* ptr) : ptr_(CHECK_NOTNULL(ptr)) {} + Something* ptr_; + }; + +Note that you cannot use this macro as a C++ stream due to this feature. +Please use ``CHECK_EQ`` described above to log a custom message before +aborting the application. + +If you are comparing C strings (:cpp:`char *`), a handy set of macros performs +case sensitive as well as case insensitive comparisons - ``CHECK_STREQ``, +``CHECK_STRNE``, ``CHECK_STRCASEEQ``, and ``CHECK_STRCASENE``. The CASE versions +are case-insensitive. You can safely pass :cpp:`NULL` pointers for this macro. They +treat :cpp:`NULL` and any non-:cpp:`NULL` string as not equal. Two :cpp:`NULL`\ +s are equal. + +Note that both arguments may be temporary strings which are destructed +at the end of the current "full expression" (e.g., +:cpp:`CHECK_STREQ(Foo().c_str(), Bar().c_str())` where ``Foo`` and ``Bar`` +return C++’s :cpp:`std::string`). + +The ``CHECK_DOUBLE_EQ`` macro checks the equality of two floating point +values, accepting a small error margin. ``CHECK_NEAR`` accepts a third +floating point argument, which specifies the acceptable error margin. + +Verbose Logging +~~~~~~~~~~~~~~~ + +When you are chasing difficult bugs, thorough log messages are very useful. +However, you may want to ignore too verbose messages in usual development. For +such verbose logging, glog provides the ``VLOG`` macro, which allows you to +define your own numeric logging levels. The :cmd:`--v` command line option +controls which verbose messages are logged: + +.. code:: cpp + + VLOG(1) << "I’m printed when you run the program with --v=1 or higher"; + VLOG(2) << "I’m printed when you run the program with --v=2 or higher"; + +With ``VLOG``, the lower the verbose level, the more likely messages are to be +logged. For example, if :cmd:`--v==1`, ``VLOG(1)`` will log, but ``VLOG(2)`` +will not log. This is opposite of the severity level, where ``INFO`` is 0, and +``ERROR`` is 2. :cmd:`--minloglevel` of 1 will log ``WARNING`` and above. Though +you can specify any integers for both ``VLOG`` macro and :cmd:`--v` flag, the +common values for them are small positive integers. For example, if you write +``VLOG(0)``, you should specify :cmd:`--v=-1` or lower to silence it. This is +less useful since we may not want verbose logs by default in most cases. The +``VLOG`` macros always log at the ``INFO`` log level (when they log at all). + +Verbose logging can be controlled from the command line on a per-module +basis: + +.. code:: bash + + --vmodule=mapreduce=2,file=1,gfs*=3 --v=0 + +will: + +(a) Print ``VLOG(2)`` and lower messages from mapreduce.{h,cc} +(b) Print ``VLOG(1)`` and lower messages from file.{h,cc} +(c) Print ``VLOG(3)`` and lower messages from files prefixed with "gfs" +(d) Print ``VLOG(0)`` and lower messages from elsewhere + +The wildcarding functionality shown by (c) supports both ’*’ (matches 0 +or more characters) and ’?’ (matches any single character) wildcards. +Please also check the section about `command line flags <#setting-flags>`__. + +There’s also ``VLOG_IS_ON(n)`` "verbose level" condition macro. This +macro returns true when the :cmd:`--v` is equal or greater than ``n``. To +be used as + +.. code:: cpp + + if (VLOG_IS_ON(2)) { + // do some logging preparation and logging + // that can’t be accomplished with just VLOG(2) << ...; + } + +Verbose level condition macros ``VLOG_IF``, ``VLOG_EVERY_N`` and +``VLOG_IF_EVERY_N`` behave analogous to ``LOG_IF``, ``LOG_EVERY_N``, +``LOF_IF_EVERY``, but accept a numeric verbosity level as opposed to a +severity level. + +.. code:: cpp + + VLOG_IF(1, (size > 1024)) + << "I’m printed when size is more than 1024 and when you run the " + "program with --v=1 or more"; + VLOG_EVERY_N(1, 10) + << "I’m printed every 10th occurrence, and when you run the program " + "with --v=1 or more. Present occurence is " << google::COUNTER; + VLOG_IF_EVERY_N(1, (size > 1024), 10) + << "I’m printed on every 10th occurence of case when size is more " + " than 1024, when you run the program with --v=1 or more. "; + "Present occurence is " << google::COUNTER; + + +Custom Log Prefix Format +~~~~~~~~~~~~~~~~~~~~~~~~ + +glog supports changing the format of the prefix attached to log messages by +receiving a user-provided callback to be used to generate such strings. That +feature must be enabled at compile time by the ``WITH_CUSTOM_PREFIX`` flag. + +For each log entry, the callback will be invoked with a ``LogMessageInfo`` +struct containing the severity, filename, line number, thread ID, and time of +the event. It will also be given a reference to the output stream, whose +contents will be prepended to the actual message in the final log line. + +For example: + +.. code:: cpp + + /* This function writes a prefix that matches glog's default format. + * (The third parameter can be used to receive user-supplied data, and is + * NULL by default.) + */ + void CustomPrefix(std::ostream &s, const LogMessageInfo &l, void*) { + s << l.severity[0] + << setw(4) << 1900 + l.time.year() + << setw(2) << 1 + l.time.month() + << setw(2) << l.time.day() + << ' ' + << setw(2) << l.time.hour() << ':' + << setw(2) << l.time.min() << ':' + << setw(2) << l.time.sec() << "." + << setw(6) << l.time.usec() + << ' ' + << setfill(' ') << setw(5) + << l.thread_id << setfill('0') + << ' ' + << l.filename << ':' << l.line_number << "]"; + } + + +To enable the use of ``CustomPrefix()``, simply give glog a pointer to it +during initialization: ``InitGoogleLogging(argv[0], &CustomPrefix);``. + +Optionally, ``InitGoogleLogging()`` takes a third argument of type ``void*`` +to pass on to the callback function. + +Failure Signal Handler +~~~~~~~~~~~~~~~~~~~~~~ + +The library provides a convenient signal handler that will dump useful +information when the program crashes on certain signals such as ``SIGSEGV``. The +signal handler can be installed by :cpp:`google::InstallFailureSignalHandler()`. +The following is an example of output from the signal handler. + +:: + + *** Aborted at 1225095260 (unix time) try "date -d @1225095260" if you are using GNU date *** + *** SIGSEGV (@0x0) received by PID 17711 (TID 0x7f893090a6f0) from PID 0; stack trace: *** + PC: @ 0x412eb1 TestWaitingLogSink::send() + @ 0x7f892fb417d0 (unknown) + @ 0x412eb1 TestWaitingLogSink::send() + @ 0x7f89304f7f06 google::LogMessage::SendToLog() + @ 0x7f89304f35af google::LogMessage::Flush() + @ 0x7f89304f3739 google::LogMessage::~LogMessage() + @ 0x408cf4 TestLogSinkWaitTillSent() + @ 0x4115de main + @ 0x7f892f7ef1c4 (unknown) + @ 0x4046f9 (unknown) + +By default, the signal handler writes the failure dump to the standard +error. You can customize the destination by :cpp:`InstallFailureWriter()`. + +Performance of Messages +~~~~~~~~~~~~~~~~~~~~~~~ + +The conditional logging macros provided by glog (e.g., ``CHECK``, +``LOG_IF``, ``VLOG``, etc.) are carefully implemented and don’t execute +the right hand side expressions when the conditions are false. So, the +following check may not sacrifice the performance of your application. + +.. code:: cpp + + CHECK(obj.ok) << obj.CreatePrettyFormattedStringButVerySlow(); + +User-defined Failure Function +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``FATAL`` severity level messages or unsatisfied ``CHECK`` condition +terminate your program. You can change the behavior of the termination +by :cpp:`InstallFailureFunction`. + +.. code:: cpp + + void YourFailureFunction() { + // Reports something... + exit(EXIT_FAILURE); + } + + int main(int argc, char* argv[]) { + google::InstallFailureFunction(&YourFailureFunction); + } + +By default, glog tries to dump stacktrace and makes the program exit +with status 1. The stacktrace is produced only when you run the program +on an architecture for which glog supports stack tracing (as of +September 2008, glog supports stack tracing for x86 and x86_64). + +Raw Logging +~~~~~~~~~~~ + +The header file ```` can be used for thread-safe logging, +which does not allocate any memory or acquire any locks. Therefore, the macros +defined in this header file can be used by low-level memory allocation and +synchronization code. Please check `src/glog/raw_logging.h.in +`__ for detail. + +Google Style ``perror()`` +~~~~~~~~~~~~~~~~~~~~~~~~~ + +``PLOG()`` and ``PLOG_IF()`` and ``PCHECK()`` behave exactly like their +``LOG*`` and ``CHECK`` equivalents with the addition that they append a +description of the current state of errno to their output lines. E.g. + +.. code:: cpp + + PCHECK(write(1, NULL, 2) >= 0) << "Write NULL failed"; + +This check fails with the following error message. + +:: + + F0825 185142 test.cc:22] Check failed: write(1, NULL, 2) >= 0 Write NULL failed: Bad address [14] + +Syslog +~~~~~~ + +``SYSLOG``, ``SYSLOG_IF``, and ``SYSLOG_EVERY_N`` macros are available. +These log to syslog in addition to the normal logs. Be aware that +logging to syslog can drastically impact performance, especially if +syslog is configured for remote logging! Make sure you understand the +implications of outputting to syslog before you use these macros. In +general, it’s wise to use these macros sparingly. + +Strip Logging Messages +~~~~~~~~~~~~~~~~~~~~~~ + +Strings used in log messages can increase the size of your binary and +present a privacy concern. You can therefore instruct glog to remove all +strings which fall below a certain severity level by using the +``GOOGLE_STRIP_LOG`` macro: + +If your application has code like this: + +.. code:: cpp + + #define GOOGLE_STRIP_LOG 1 // this must go before the #include! + #include + +The compiler will remove the log messages whose severities are less than +the specified integer value. Since ``VLOG`` logs at the severity level +``INFO`` (numeric value ``0``), setting ``GOOGLE_STRIP_LOG`` to 1 or +greater removes all log messages associated with ``VLOG``\ s as well as +``INFO`` log statements. + +Automatically Remove Old Logs +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To enable the log cleaner: + +.. code:: cpp + + google::EnableLogCleaner(3); // keep your logs for 3 days + +And then glog will check if there are overdue logs whenever a flush is +performed. In this example, any log file from your project whose last +modified time is greater than 3 days will be unlink()ed. + +This feature can be disabled at any time (if it has been enabled) + +.. code:: cpp + + google::DisableLogCleaner(); + +Notes for Windows Users +~~~~~~~~~~~~~~~~~~~~~~~ + +glog defines a severity level ``ERROR``, which is also defined in +``windows.h`` . You can make glog not define ``INFO``, ``WARNING``, +``ERROR``, and ``FATAL`` by defining ``GLOG_NO_ABBREVIATED_SEVERITIES`` +before including ``glog/logging.h`` . Even with this macro, you can +still use the iostream like logging facilities: + +.. code:: cpp + + #define GLOG_NO_ABBREVIATED_SEVERITIES + #include + #include + + // ... + + LOG(ERROR) << "This should work"; + LOG_IF(ERROR, x > y) << "This should be also OK"; + +However, you cannot use ``INFO``, ``WARNING``, ``ERROR``, and ``FATAL`` +anymore for functions defined in ``glog/logging.h`` . + +.. code:: cpp + + #define GLOG_NO_ABBREVIATED_SEVERITIES + #include + #include + + // ... + + // This won’t work. + // google::FlushLogFiles(google::ERROR); + + // Use this instead. + google::FlushLogFiles(google::GLOG_ERROR); + +If you don’t need ``ERROR`` defined by ``windows.h``, there are a couple +of more workarounds which sometimes don’t work: + +- ``#define WIN32_LEAN_AND_MEAN`` or ``NOGDI`` **before** you + ``#include windows.h``. +- ``#undef ERROR`` **after** you ``#include windows.h`` . + +See `this +issue `__ for +more detail. + + +Installation Notes for 64-bit Linux Systems +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The glibc built-in stack-unwinder on 64-bit systems has some problems with glog. +(In particular, if you are using :cpp:`InstallFailureSignalHandler()`, the +signal may be raised in the middle of malloc, holding some malloc-related locks +when they invoke the stack unwinder. The built-in stack unwinder may call malloc +recursively, which may require the thread to acquire a lock it already holds: +deadlock.) + +For that reason, if you use a 64-bit system and you need +:cpp:`InstallFailureSignalHandler()`, we strongly recommend you install +``libunwind`` before trying to configure or install google glog. +libunwind can be found +`here `__. + +Even if you already have ``libunwind`` installed, you will probably +still need to install from the snapshot to get the latest version. + +Caution: if you install libunwind from the URL above, be aware that you +may have trouble if you try to statically link your binary with glog: +that is, if you link with ``gcc -static -lgcc_eh ...``. This is because +both ``libunwind`` and ``libgcc`` implement the same C++ exception +handling APIs, but they implement them differently on some platforms. +This is not likely to be a problem on ia64, but may be on x86-64. + +Also, if you link binaries statically, make sure that you add +:cmd:`-Wl,--eh-frame-hdr` to your linker options. This is required so that +``libunwind`` can find the information generated by the compiler required for +stack unwinding. + +Using :cmd:`-static` is rare, though, so unless you know this will affect you it +probably won’t. + +If you cannot or do not wish to install libunwind, you can still try to +use two kinds of stack-unwinder: 1. glibc built-in stack-unwinder and 2. +frame pointer based stack-unwinder. + +1. As we already mentioned, glibc’s unwinder has a deadlock issue. + However, if you don’t use :cpp:`InstallFailureSignalHandler()` or you + don’t worry about the rare possibilities of deadlocks, you can use + this stack-unwinder. If you specify no options and ``libunwind`` + isn’t detected on your system, the configure script chooses this + unwinder by default. + +2. The frame pointer based stack unwinder requires that your + application, the glog library, and system libraries like libc, all be + compiled with a frame pointer. This is *not* the default for x86-64. + + +How to Contribute +----------------- + +We’d love to accept your patches and contributions to this project. +There are a just a few small guidelines you need to follow. + +Contributor License Agreement (CLA) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Contributions to any Google project must be accompanied by a Contributor +License Agreement. This is not a copyright **assignment**, it simply +gives Google permission to use and redistribute your contributions as +part of the project. + +* If you are an individual writing original source code and you’re sure + you own the intellectual property, then you’ll need to sign an + `individual + CLA `__. +* If you work for a company that wants to allow you to contribute your + work, then you’ll need to sign a `corporate + CLA `__. + +You generally only need to submit a CLA once, so if you’ve already +submitted one (even if it was for a different project), you probably +don’t need to do it again. + +Once your CLA is submitted (or if you already submitted one for another +Google project), make a commit adding yourself to the +`AUTHORS <./AUTHORS>`__ and `CONTRIBUTORS <./CONTRIBUTORS>`__ files. This +commit can be part of your first `pull +request `__. + +Submitting a Patch +~~~~~~~~~~~~~~~~~~ + +1. It’s generally best to start by opening a new issue describing the + bug or feature you’re intending to fix. Even if you think it’s + relatively minor, it’s helpful to know what people are working on. + Mention in the initial issue that you are planning to work on that + bug or feature so that it can be assigned to you. +2. Follow the normal process of + `forking `__ the + project, and setup a new branch to work in. It’s important that each + group of changes be done in separate branches in order to ensure that + a pull request only includes the commits related to that bug or + feature. +3. Do your best to have `well-formed commit + messages `__ + for each change. This provides consistency throughout the project, + and ensures that commit messages are able to be formatted properly by + various git tools. +4. Finally, push the commits to your fork and submit a `pull + request `__. + + +.. |Linux Github actions| image:: https://github.com/google/glog/actions/workflows/linux.yml/badge.svg + :target: https://github.com/google/glog/actions +.. |Windows Github actions| image:: https://github.com/google/glog/actions/workflows/windows.yml/badge.svg + :target: https://github.com/google/glog/actions +.. |macOS Github actions| image:: https://github.com/google/glog/actions/workflows/macos.yml/badge.svg + :target: https://github.com/google/glog/actions +.. |Total alerts| image:: https://img.shields.io/lgtm/alerts/g/google/glog.svg?logo=lgtm&logoWidth=18 + :target: https://lgtm.com/projects/g/google/glog/alerts/ +.. |Language grade: C++| image:: https://img.shields.io/lgtm/grade/cpp/g/google/glog.svg?logo=lgtm&logoWidth=18) + :target: https://lgtm.com/projects/g/google/glog/context:cpp +.. |Codecov| image:: https://codecov.io/gh/google/glog/branch/master/graph/badge.svg?token=8an420vNju + :target: https://codecov.io/gh/google/glog diff --git a/third_party/glog/WORKSPACE b/third_party/glog/WORKSPACE new file mode 100644 index 0000000..10c89f6 --- /dev/null +++ b/third_party/glog/WORKSPACE @@ -0,0 +1,11 @@ +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + +http_archive( + name = "com_github_gflags_gflags", + sha256 = "34af2f15cf7367513b352bdcd2493ab14ce43692d2dcd9dfc499492966c64dcf", + strip_prefix = "gflags-2.2.2", + urls = [ + "https://mirror.bazel.build/github.com/gflags/gflags/archive/v2.2.2.tar.gz", + "https://github.com/gflags/gflags/archive/v2.2.2.tar.gz", + ], +) diff --git a/third_party/glog/bazel/example/BUILD.bazel b/third_party/glog/bazel/example/BUILD.bazel new file mode 100644 index 0000000..05ab0f3 --- /dev/null +++ b/third_party/glog/bazel/example/BUILD.bazel @@ -0,0 +1,9 @@ +cc_test( + name = "main", + size = "small", + srcs = ["main.cc"], + deps = [ + "//:glog", + "@com_github_gflags_gflags//:gflags", + ], +) diff --git a/third_party/glog/bazel/example/main.cc b/third_party/glog/bazel/example/main.cc new file mode 100644 index 0000000..fef01dc --- /dev/null +++ b/third_party/glog/bazel/example/main.cc @@ -0,0 +1,22 @@ +#include +#include +#include + +int main(int argc, char* argv[]) { + // Initialize Google's logging library. + google::InitGoogleLogging(argv[0]); + + // Optional: parse command line flags + gflags::ParseCommandLineFlags(&argc, &argv, true); + + LOG(INFO) << "Hello, world!"; + + // glog/stl_logging.h allows logging STL containers. + std::vector x; + x.push_back(1); + x.push_back(2); + x.push_back(3); + LOG(INFO) << "ABC, it's easy as " << x; + + return 0; +} diff --git a/third_party/glog/bazel/glog.bzl b/third_party/glog/bazel/glog.bzl new file mode 100644 index 0000000..4208d9e --- /dev/null +++ b/third_party/glog/bazel/glog.bzl @@ -0,0 +1,276 @@ +# Implement a macro glog_library() that the BUILD.bazel file can load. + +# By default, glog is built with gflags support. You can change this behavior +# by using glog_library(with_gflags=0) +# +# This file is inspired by the following sample BUILD files: +# https://github.com/google/glog/issues/61 +# https://github.com/google/glog/files/393474/BUILD.txt +# +# Known issue: the namespace parameter is not supported on Win32. + +def expand_template_impl(ctx): + ctx.actions.expand_template( + template = ctx.file.template, + output = ctx.outputs.out, + substitutions = ctx.attr.substitutions, + ) + +expand_template = rule( + implementation = expand_template_impl, + attrs = { + "template": attr.label(mandatory = True, allow_single_file = True), + "substitutions": attr.string_dict(mandatory = True), + "out": attr.output(mandatory = True), + }, +) + +def dict_union(x, y): + z = {} + z.update(x) + z.update(y) + return z + +def glog_library(namespace = "google", with_gflags = 1, **kwargs): + if native.repository_name() != "@": + repo_name = native.repository_name().lstrip("@") + gendir = "$(GENDIR)/external/" + repo_name + src_windows = "external/%s/src/windows" % repo_name + else: + gendir = "$(GENDIR)" + src_windows = "src/windows" + + # Config setting for WebAssembly target. + native.config_setting( + name = "wasm", + values = {"cpu": "wasm"}, + ) + + # Detect when building with clang-cl on Windows. + native.config_setting( + name = "clang-cl", + values = {"compiler": "clang-cl"}, + ) + + common_copts = [ + "-DGLOG_BAZEL_BUILD", + # Inject a C++ namespace. + "-DGOOGLE_NAMESPACE='%s'" % namespace, + "-DHAVE_CXX11_NULLPTR_T", + "-DHAVE_STDINT_H", + "-DHAVE_STRING_H", + "-DGLOG_CUSTOM_PREFIX_SUPPORT", + "-I%s/glog_internal" % gendir, + ] + (["-DHAVE_LIB_GFLAGS"] if with_gflags else []) + + wasm_copts = [ + # Disable warnings that exists in glog. + "-Wno-sign-compare", + "-Wno-unused-function", + "-Wno-unused-local-typedefs", + "-Wno-unused-variable", + # Allows src/base/mutex.h to include pthread.h. + "-DHAVE_PTHREAD", + # Allows src/logging.cc to determine the host name. + "-DHAVE_SYS_UTSNAME_H", + # For src/utilities.cc. + "-DHAVE_SYS_TIME_H", + "-DHAVE_UNWIND_H", + # Enable dumping stacktrace upon sigaction. + "-DHAVE_SIGACTION", + # For logging.cc. + "-DHAVE_PREAD", + "-DHAVE___ATTRIBUTE__", + ] + + linux_or_darwin_copts = wasm_copts + [ + "-DGLOG_EXPORT=__attribute__((visibility(\\\"default\\\")))", + # For src/utilities.cc. + "-DHAVE_SYS_SYSCALL_H", + # For src/logging.cc to create symlinks. + "-DHAVE_UNISTD_H", + "-fvisibility-inlines-hidden", + "-fvisibility=hidden", + ] + + freebsd_only_copts = [ + # Enable declaration of _Unwind_Backtrace + "-D_GNU_SOURCE", + ] + + darwin_only_copts = [ + # For stacktrace. + "-DHAVE_DLADDR", + # Avoid deprecated syscall(). + "-DHAVE_PTHREAD_THREADID_NP", + ] + + windows_only_copts = [ + # Override -DGLOG_EXPORT= from the cc_library's defines. + "-DGLOG_EXPORT=__declspec(dllexport)", + "-DGLOG_NO_ABBREVIATED_SEVERITIES", + "-DHAVE_SNPRINTF", + "-I" + src_windows, + ] + + clang_cl_only_copts = [ + # Allow the override of -DGLOG_EXPORT. + "-Wno-macro-redefined", + ] + + windows_only_srcs = [ + "src/glog/log_severity.h", + "src/windows/dirent.h", + "src/windows/port.cc", + "src/windows/port.h", + ] + + gflags_deps = ["@com_github_gflags_gflags//:gflags"] if with_gflags else [] + + native.cc_library( + name = "glog", + visibility = ["//visibility:public"], + srcs = [ + ":config_h", + "src/base/commandlineflags.h", + "src/base/googleinit.h", + "src/base/mutex.h", + "src/demangle.cc", + "src/demangle.h", + "src/logging.cc", + "src/raw_logging.cc", + "src/signalhandler.cc", + "src/stacktrace.h", + "src/stacktrace_generic-inl.h", + "src/stacktrace_libunwind-inl.h", + "src/stacktrace_powerpc-inl.h", + "src/stacktrace_unwind-inl.h", + "src/stacktrace_windows-inl.h", + "src/stacktrace_x86-inl.h", + "src/symbolize.cc", + "src/symbolize.h", + "src/utilities.cc", + "src/utilities.h", + "src/vlog_is_on.cc", + ] + select({ + "@bazel_tools//src/conditions:windows": windows_only_srcs, + "//conditions:default": [], + }), + hdrs = [ + "src/glog/log_severity.h", + "src/glog/platform.h", + ":logging_h", + ":raw_logging_h", + ":stl_logging_h", + ":vlog_is_on_h", + ], + strip_include_prefix = "src", + defines = select({ + # GLOG_EXPORT is normally set by export.h, but that's not + # generated for Bazel. + "@bazel_tools//src/conditions:windows": [ + "GLOG_EXPORT=", + "GLOG_DEPRECATED=__declspec(deprecated)", + "GLOG_NO_ABBREVIATED_SEVERITIES", + ], + "//conditions:default": [ + "GLOG_DEPRECATED=__attribute__((deprecated))", + "GLOG_EXPORT=__attribute__((visibility(\\\"default\\\")))", + ], + }), + copts = + select({ + "@bazel_tools//src/conditions:windows": common_copts + windows_only_copts, + "@bazel_tools//src/conditions:darwin": common_copts + linux_or_darwin_copts + darwin_only_copts, + "@bazel_tools//src/conditions:freebsd": common_copts + linux_or_darwin_copts + freebsd_only_copts, + ":wasm": common_copts + wasm_copts, + "//conditions:default": common_copts + linux_or_darwin_copts, + }) + + select({ + ":clang-cl": clang_cl_only_copts, + "//conditions:default": [] + }), + deps = gflags_deps + select({ + "@bazel_tools//src/conditions:windows": [":strip_include_prefix_hack"], + "//conditions:default": [], + }), + **kwargs + ) + + # Workaround https://github.com/bazelbuild/bazel/issues/6337 by declaring + # the dependencies without strip_include_prefix. + native.cc_library( + name = "strip_include_prefix_hack", + hdrs = [ + "src/glog/log_severity.h", + ":logging_h", + ":raw_logging_h", + ":stl_logging_h", + ":vlog_is_on_h", + ], + ) + + expand_template( + name = "config_h", + template = "src/config.h.cmake.in", + out = "glog_internal/config.h", + substitutions = {"#cmakedefine": "//cmakedefine"}, + ) + + common_config = { + "@ac_cv_cxx11_atomic@": "1", + "@ac_cv_cxx11_constexpr@": "1", + "@ac_cv_cxx11_chrono@": "1", + "@ac_cv_cxx11_nullptr_t@": "1", + "@ac_cv_cxx_using_operator@": "1", + "@ac_cv_have_inttypes_h@": "0", + "@ac_cv_have_u_int16_t@": "0", + "@ac_cv_have_glog_export@": "0", + "@ac_google_start_namespace@": "namespace google {", + "@ac_google_end_namespace@": "}", + "@ac_google_namespace@": "google", + } + + posix_config = dict_union(common_config, { + "@ac_cv_have_unistd_h@": "1", + "@ac_cv_have_stdint_h@": "1", + "@ac_cv_have_systypes_h@": "1", + "@ac_cv_have_uint16_t@": "1", + "@ac_cv_have___uint16@": "0", + "@ac_cv_have___builtin_expect@": "1", + "@ac_cv_have_libgflags@": "1" if with_gflags else "0", + "@ac_cv___attribute___noinline@": "__attribute__((noinline))", + "@ac_cv___attribute___noreturn@": "__attribute__((noreturn))", + "@ac_cv___attribute___printf_4_5@": "__attribute__((__format__(__printf__, 4, 5)))", + }) + + windows_config = dict_union(common_config, { + "@ac_cv_have_unistd_h@": "0", + "@ac_cv_have_stdint_h@": "0", + "@ac_cv_have_systypes_h@": "0", + "@ac_cv_have_uint16_t@": "0", + "@ac_cv_have___uint16@": "1", + "@ac_cv_have___builtin_expect@": "0", + "@ac_cv_have_libgflags@": "0", + "@ac_cv___attribute___noinline@": "", + "@ac_cv___attribute___noreturn@": "__declspec(noreturn)", + "@ac_cv___attribute___printf_4_5@": "", + }) + + [ + expand_template( + name = "%s_h" % f, + template = "src/glog/%s.h.in" % f, + out = "src/glog/%s.h" % f, + substitutions = select({ + "@bazel_tools//src/conditions:windows": windows_config, + "//conditions:default": posix_config, + }), + ) + for f in [ + "vlog_is_on", + "stl_logging", + "raw_logging", + "logging", + ] + ] diff --git a/third_party/glog/cmake/DetermineGflagsNamespace.cmake b/third_party/glog/cmake/DetermineGflagsNamespace.cmake new file mode 100644 index 0000000..3dde42b --- /dev/null +++ b/third_party/glog/cmake/DetermineGflagsNamespace.cmake @@ -0,0 +1,69 @@ +macro(determine_gflags_namespace VARIABLE) + if (NOT DEFINED "${VARIABLE}") + if (CMAKE_REQUIRED_INCLUDES) + set (CHECK_INCLUDE_FILE_CXX_INCLUDE_DIRS "-DINCLUDE_DIRECTORIES=${CMAKE_REQUIRED_INCLUDES}") + else () + set (CHECK_INCLUDE_FILE_CXX_INCLUDE_DIRS) + endif () + + set(MACRO_CHECK_INCLUDE_FILE_FLAGS ${CMAKE_REQUIRED_FLAGS}) + + set(_NAMESPACES gflags google) + set(_check_code +" +#include + +int main(int argc, char**argv) +{ + GLOG_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true); +} +") + if (NOT CMAKE_REQUIRED_QUIET) + message (STATUS "Looking for gflags namespace") + endif () + if (${ARGC} EQUAL 3) + set (CMAKE_CXX_FLAGS_SAVE ${CMAKE_CXX_FLAGS}) + set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${ARGV2}") + endif () + + set (_check_file + ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/DetermineGflagsNamespace.cxx) + + foreach (_namespace ${_NAMESPACES}) + file (WRITE "${_check_file}" "${_check_code}") + try_compile (${VARIABLE} + "${CMAKE_BINARY_DIR}" "${_check_file}" + COMPILE_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS}" -DGLOG_GFLAGS_NAMESPACE=${_namespace} + LINK_LIBRARIES gflags + CMAKE_FLAGS -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} + OUTPUT_VARIABLE OUTPUT) + + if (${VARIABLE}) + set (${VARIABLE} ${_namespace} CACHE INTERNAL "gflags namespace" FORCE) + break () + else () + file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log + "Determining the gflags namespace ${_namespace} failed with the following output:\n" + "${OUTPUT}\n\n") + endif () + endforeach (_namespace) + + if (${ARGC} EQUAL 3) + set (CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS_SAVE}) + endif () + + if (${VARIABLE}) + if (NOT CMAKE_REQUIRED_QUIET) + message (STATUS "Looking for gflags namespace - ${${VARIABLE}}") + endif () + file (APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log + "Determining the gflags namespace passed with the following output:\n" + "${OUTPUT}\n\n") + else () + if (NOT CMAKE_REQUIRED_QUIET) + message (STATUS "Looking for gflags namespace - failed") + endif () + set (${VARIABLE} ${_namespace} CACHE INTERNAL "gflags namespace") + endif () + endif () +endmacro () diff --git a/third_party/glog/cmake/FindUnwind.cmake b/third_party/glog/cmake/FindUnwind.cmake new file mode 100644 index 0000000..a7a976b --- /dev/null +++ b/third_party/glog/cmake/FindUnwind.cmake @@ -0,0 +1,61 @@ +# - Try to find libunwind +# Once done this will define +# +# Unwind_FOUND - system has libunwind +# unwind::unwind - cmake target for libunwind + +include (FindPackageHandleStandardArgs) + +find_path (Unwind_INCLUDE_DIR NAMES unwind.h libunwind.h DOC "unwind include directory") +find_library (Unwind_LIBRARY NAMES unwind DOC "unwind library") + +mark_as_advanced (Unwind_INCLUDE_DIR Unwind_LIBRARY) + +# Extract version information +if (Unwind_LIBRARY) + set (_Unwind_VERSION_HEADER ${Unwind_INCLUDE_DIR}/libunwind-common.h) + + if (EXISTS ${_Unwind_VERSION_HEADER}) + file (READ ${_Unwind_VERSION_HEADER} _Unwind_VERSION_CONTENTS) + + string (REGEX REPLACE ".*#define UNW_VERSION_MAJOR[ \t]+([0-9]+).*" "\\1" + Unwind_VERSION_MAJOR "${_Unwind_VERSION_CONTENTS}") + string (REGEX REPLACE ".*#define UNW_VERSION_MINOR[ \t]+([0-9]+).*" "\\1" + Unwind_VERSION_MINOR "${_Unwind_VERSION_CONTENTS}") + string (REGEX REPLACE ".*#define UNW_VERSION_EXTRA[ \t]+([0-9]+).*" "\\1" + Unwind_VERSION_PATCH "${_Unwind_VERSION_CONTENTS}") + + set (Unwind_VERSION ${Unwind_VERSION_MAJOR}.${Unwind_VERSION_MINOR}) + + if (CMAKE_MATCH_0) + # Third version component may be empty + set (Unwind_VERSION ${Unwind_VERSION}.${Unwind_VERSION_PATCH}) + set (Unwind_VERSION_COMPONENTS 3) + else (CMAKE_MATCH_0) + set (Unwind_VERSION_COMPONENTS 2) + endif (CMAKE_MATCH_0) + endif (EXISTS ${_Unwind_VERSION_HEADER}) +endif (Unwind_LIBRARY) + +# handle the QUIETLY and REQUIRED arguments and set Unwind_FOUND to TRUE +# if all listed variables are TRUE +find_package_handle_standard_args (Unwind + REQUIRED_VARS Unwind_INCLUDE_DIR Unwind_LIBRARY + VERSION_VAR Unwind_VERSION +) + +if (Unwind_FOUND) + if (NOT TARGET unwind::unwind) + add_library (unwind::unwind INTERFACE IMPORTED) + + set_property (TARGET unwind::unwind PROPERTY + INTERFACE_INCLUDE_DIRECTORIES ${Unwind_INCLUDE_DIR} + ) + set_property (TARGET unwind::unwind PROPERTY + INTERFACE_LINK_LIBRARIES ${Unwind_LIBRARY} + ) + set_property (TARGET unwind::unwind PROPERTY + IMPORTED_CONFIGURATIONS RELEASE + ) + endif (NOT TARGET unwind::unwind) +endif (Unwind_FOUND) diff --git a/third_party/glog/cmake/GetCacheVariables.cmake b/third_party/glog/cmake/GetCacheVariables.cmake new file mode 100644 index 0000000..ead3589 --- /dev/null +++ b/third_party/glog/cmake/GetCacheVariables.cmake @@ -0,0 +1,70 @@ +cmake_policy (PUSH) +cmake_policy (VERSION 3.3) + +include (CMakeParseArguments) + +function (get_cache_variables _CACHEVARS) + set (_SINGLE) + set (_MULTI EXCLUDE) + set (_OPTIONS) + + cmake_parse_arguments (_ARGS "${_OPTIONS}" "${_SINGLE}" "${_MULTI}" ${ARGS} ${ARGN}) + + get_cmake_property (_VARIABLES VARIABLES) + + set (CACHEVARS) + + foreach (_VAR ${_VARIABLES}) + if (DEFINED _ARGS_EXCLUDE) + if ("${_VAR}" IN_LIST _ARGS_EXCLUDE) + continue () + endif ("${_VAR}" IN_LIST _ARGS_EXCLUDE) + endif (DEFINED _ARGS_EXCLUDE) + + get_property (_CACHEVARTYPE CACHE ${_VAR} PROPERTY TYPE) + + if ("${_CACHEVARTYPE}" STREQUAL INTERNAL OR + "${_CACHEVARTYPE}" STREQUAL STATIC OR + "${_CACHEVARTYPE}" STREQUAL UNINITIALIZED) + continue () + endif ("${_CACHEVARTYPE}" STREQUAL INTERNAL OR + "${_CACHEVARTYPE}" STREQUAL STATIC OR + "${_CACHEVARTYPE}" STREQUAL UNINITIALIZED) + + get_property (_CACHEVARVAL CACHE ${_VAR} PROPERTY VALUE) + + if ("${_CACHEVARVAL}" STREQUAL "") + continue () + endif ("${_CACHEVARVAL}" STREQUAL "") + + get_property (_CACHEVARDOC CACHE ${_VAR} PROPERTY HELPSTRING) + + # Escape " in values + string (REPLACE "\"" "\\\"" _CACHEVARVAL "${_CACHEVARVAL}") + # Escape " in help strings + string (REPLACE "\"" "\\\"" _CACHEVARDOC "${_CACHEVARDOC}") + # Escape ; in values + string (REPLACE ";" "\\\;" _CACHEVARVAL "${_CACHEVARVAL}") + # Escape ; in help strings + string (REPLACE ";" "\\\;" _CACHEVARDOC "${_CACHEVARDOC}") + # Escape backslashes in values except those that are followed by a + # quote. + string (REGEX REPLACE "\\\\([^\"])" "\\\\\\1" _CACHEVARVAL "${_CACHEVARVAL}") + # Escape backslashes in values that are followed by a letter to avoid + # invalid escape sequence errors. + string (REGEX REPLACE "\\\\([a-zA-Z])" "\\\\\\\\1" _CACHEVARVAL "${_CACHEVARVAL}") + string (REPLACE "\\\\" "\\\\\\\\" _CACHEVARDOC "${_CACHEVARDOC}") + + if (NOT "${_CACHEVARTYPE}" STREQUAL BOOL) + set (_CACHEVARVAL "\"${_CACHEVARVAL}\"") + endif (NOT "${_CACHEVARTYPE}" STREQUAL BOOL) + + if (NOT "${_CACHEVARTYPE}" STREQUAL "" AND NOT "${_CACHEVARVAL}" STREQUAL "") + set (CACHEVARS "${CACHEVARS}set (${_VAR} ${_CACHEVARVAL} CACHE ${_CACHEVARTYPE} \"${_CACHEVARDOC}\")\n") + endif (NOT "${_CACHEVARTYPE}" STREQUAL "" AND NOT "${_CACHEVARVAL}" STREQUAL "") + endforeach (_VAR) + + set (${_CACHEVARS} ${CACHEVARS} PARENT_SCOPE) +endfunction (get_cache_variables) + +cmake_policy (POP) diff --git a/third_party/glog/cmake/RunCleanerTest1.cmake b/third_party/glog/cmake/RunCleanerTest1.cmake new file mode 100644 index 0000000..7fbf463 --- /dev/null +++ b/third_party/glog/cmake/RunCleanerTest1.cmake @@ -0,0 +1,22 @@ +set (RUNS 3) + +foreach (iter RANGE 1 ${RUNS}) + set (ENV{GOOGLE_LOG_DIR} ${TEST_DIR}) + execute_process (COMMAND ${LOGCLEANUP} RESULT_VARIABLE _RESULT) + + if (NOT _RESULT EQUAL 0) + message (FATAL_ERROR "Failed to run logcleanup_unittest (error: ${_RESULT})") + endif (NOT _RESULT EQUAL 0) + + # Ensure the log files to have different modification timestamps such that + # exactly one log file remains at the end. Otherwise all log files will be + # retained. + execute_process (COMMAND ${CMAKE_COMMAND} -E sleep 1) +endforeach (iter) + +file (GLOB LOG_FILES ${TEST_DIR}/*.foobar) +list (LENGTH LOG_FILES NUM_FILES) + +if (NOT NUM_FILES EQUAL 1) + message (SEND_ERROR "Expected 1 log file in log directory but found ${NUM_FILES}") +endif (NOT NUM_FILES EQUAL 1) diff --git a/third_party/glog/cmake/RunCleanerTest2.cmake b/third_party/glog/cmake/RunCleanerTest2.cmake new file mode 100644 index 0000000..d3b51e3 --- /dev/null +++ b/third_party/glog/cmake/RunCleanerTest2.cmake @@ -0,0 +1,22 @@ +set (RUNS 3) + +foreach (iter RANGE 1 ${RUNS}) + execute_process (COMMAND ${LOGCLEANUP} -log_dir=${TEST_DIR} + RESULT_VARIABLE _RESULT) + + if (NOT _RESULT EQUAL 0) + message (FATAL_ERROR "Failed to run logcleanup_unittest (error: ${_RESULT})") + endif (NOT _RESULT EQUAL 0) + + # Ensure the log files to have different modification timestamps such that + # exactly one log file remains at the end. Otherwise all log files will be + # retained. + execute_process (COMMAND ${CMAKE_COMMAND} -E sleep 1) +endforeach (iter) + +file (GLOB LOG_FILES ${TEST_DIR}/test_cleanup_*.barfoo) +list (LENGTH LOG_FILES NUM_FILES) + +if (NOT NUM_FILES EQUAL 1) + message (SEND_ERROR "Expected 1 log file in build directory ${TEST_DIR} but found ${NUM_FILES}") +endif (NOT NUM_FILES EQUAL 1) diff --git a/third_party/glog/cmake/RunCleanerTest3.cmake b/third_party/glog/cmake/RunCleanerTest3.cmake new file mode 100644 index 0000000..e8105d1 --- /dev/null +++ b/third_party/glog/cmake/RunCleanerTest3.cmake @@ -0,0 +1,28 @@ +set (RUNS 3) + +# Create the subdirectory required by this unit test. +file (MAKE_DIRECTORY ${TEST_DIR}/${TEST_SUBDIR}) + +foreach (iter RANGE 1 ${RUNS}) + execute_process (COMMAND ${LOGCLEANUP} -log_dir=${TEST_DIR} + RESULT_VARIABLE _RESULT) + + if (NOT _RESULT EQUAL 0) + message (FATAL_ERROR "Failed to run logcleanup_unittest (error: ${_RESULT})") + endif (NOT _RESULT EQUAL 0) + + # Ensure the log files to have different modification timestamps such that + # exactly one log file remains at the end. Otherwise all log files will be + # retained. + execute_process (COMMAND ${CMAKE_COMMAND} -E sleep 2) +endforeach (iter) + +file (GLOB LOG_FILES ${TEST_DIR}/${TEST_SUBDIR}/test_cleanup_*.relativefoo) +list (LENGTH LOG_FILES NUM_FILES) + +if (NOT NUM_FILES EQUAL 1) + message (SEND_ERROR "Expected 1 log file in build directory ${TEST_DIR}${TEST_SUBDIR} but found ${NUM_FILES}") +endif (NOT NUM_FILES EQUAL 1) + +# Remove the subdirectory required by this unit test. +file (REMOVE_RECURSE ${TEST_DIR}/${TEST_SUBDIR}) diff --git a/third_party/glog/cmake/TestInitPackageConfig.cmake b/third_party/glog/cmake/TestInitPackageConfig.cmake new file mode 100644 index 0000000..01d3a40 --- /dev/null +++ b/third_party/glog/cmake/TestInitPackageConfig.cmake @@ -0,0 +1,11 @@ +# Create the build directory +execute_process ( + COMMAND ${CMAKE_COMMAND} -E make_directory ${TEST_BINARY_DIR} + RESULT_VARIABLE _DIRECTORY_CREATED_SUCCEEDED +) + +if (NOT _DIRECTORY_CREATED_SUCCEEDED EQUAL 0) + message (FATAL_ERROR "Failed to create build directory") +endif (NOT _DIRECTORY_CREATED_SUCCEEDED EQUAL 0) + +file (WRITE ${INITIAL_CACHE} "${CACHEVARS}") diff --git a/third_party/glog/cmake/TestPackageConfig.cmake b/third_party/glog/cmake/TestPackageConfig.cmake new file mode 100644 index 0000000..97244ab --- /dev/null +++ b/third_party/glog/cmake/TestPackageConfig.cmake @@ -0,0 +1,40 @@ +# Create the build directory +execute_process ( + COMMAND ${CMAKE_COMMAND} -E make_directory ${TEST_BINARY_DIR} + RESULT_VARIABLE _DIRECTORY_CREATED_SUCCEEDED +) + +if (NOT _DIRECTORY_CREATED_SUCCEEDED EQUAL 0) + message (FATAL_ERROR "Failed to create build directory") +endif (NOT _DIRECTORY_CREATED_SUCCEEDED EQUAL 0) + +if (GENERATOR_TOOLSET) + list (APPEND _ADDITIONAL_ARGS -T ${GENERATOR_TOOLSET}) +endif (GENERATOR_TOOLSET) + +if (GENERATOR_PLATFORM) + list (APPEND _ADDITIONAL_ARGS -A ${GENERATOR_PLATFORM}) +endif (GENERATOR_PLATFORM) + +# Run CMake +execute_process ( + # Capture the PATH environment variable content set during project generation + # stage. This is required because later during the build stage the PATH is + # modified again (e.g., for MinGW AppVeyor CI builds) by adding back the + # directory containing git.exe. Incidently, the Git installation directory + # also contains sh.exe which causes MinGW Makefile generation to fail. + COMMAND ${CMAKE_COMMAND} -E env PATH=${PATH} + ${CMAKE_COMMAND} -C ${INITIAL_CACHE} + -G ${GENERATOR} + ${_ADDITIONAL_ARGS} + -DCMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY=ON + -DCMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY=ON + -DCMAKE_PREFIX_PATH=${PACKAGE_DIR} + ${SOURCE_DIR} + WORKING_DIRECTORY ${TEST_BINARY_DIR} + RESULT_VARIABLE _GENERATE_SUCCEEDED +) + +if (NOT _GENERATE_SUCCEEDED EQUAL 0) + message (FATAL_ERROR "Failed to generate project files using CMake") +endif (NOT _GENERATE_SUCCEEDED EQUAL 0) diff --git a/third_party/glog/glog-config.cmake.in b/third_party/glog/glog-config.cmake.in new file mode 100644 index 0000000..5c5c9c0 --- /dev/null +++ b/third_party/glog/glog-config.cmake.in @@ -0,0 +1,13 @@ +if (CMAKE_VERSION VERSION_LESS @glog_CMake_VERSION@) + message (FATAL_ERROR "CMake >= @glog_CMake_VERSION@ required") +endif (CMAKE_VERSION VERSION_LESS @glog_CMake_VERSION@) + +@PACKAGE_INIT@ + +include (CMakeFindDependencyMacro) +include (${CMAKE_CURRENT_LIST_DIR}/glog-modules.cmake) + +@gflags_DEPENDENCY@ +@Unwind_DEPENDENCY@ + +include (${CMAKE_CURRENT_LIST_DIR}/glog-targets.cmake) diff --git a/third_party/glog/glog-modules.cmake.in b/third_party/glog/glog-modules.cmake.in new file mode 100644 index 0000000..71c5160 --- /dev/null +++ b/third_party/glog/glog-modules.cmake.in @@ -0,0 +1,18 @@ +cmake_policy (PUSH) +cmake_policy (SET CMP0057 NEW) + +if (CMAKE_VERSION VERSION_LESS 3.3) + message (FATAL_ERROR "glog-modules.cmake requires the consumer " + "to use CMake 3.3 (or newer)") +endif (CMAKE_VERSION VERSION_LESS 3.3) + +set (glog_MODULE_PATH "@glog_FULL_CMake_DATADIR@") +list (APPEND CMAKE_MODULE_PATH ${glog_MODULE_PATH}) + +if (NOT glog_MODULE_PATH IN_LIST CMAKE_MODULE_PATH) + message (FATAL_ERROR "Cannot add '${glog_MODULE_PATH}' to " + "CMAKE_MODULE_PATH. This will cause glog-config.cmake to fail at " + "locating required find modules. Make sure CMAKE_MODULE_PATH is not a cache variable.") +endif (NOT glog_MODULE_PATH IN_LIST CMAKE_MODULE_PATH) + +cmake_policy (POP) diff --git a/third_party/glog/libglog.pc.in b/third_party/glog/libglog.pc.in new file mode 100644 index 0000000..2303e2e --- /dev/null +++ b/third_party/glog/libglog.pc.in @@ -0,0 +1,11 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: libglog +Description: Google Log (glog) C++ logging framework +Version: @VERSION@ +Libs: -L${libdir} -lglog +Libs.private: @glog_libraries_options_for_static_linking@ +Cflags: -I${includedir} diff --git a/third_party/glog/src/base/commandlineflags.h b/third_party/glog/src/base/commandlineflags.h new file mode 100644 index 0000000..bcb12de --- /dev/null +++ b/third_party/glog/src/base/commandlineflags.h @@ -0,0 +1,147 @@ +// Copyright (c) 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// --- +// This file is a compatibility layer that defines Google's version of +// command line flags that are used for configuration. +// +// We put flags into their own namespace. It is purposefully +// named in an opaque way that people should have trouble typing +// directly. The idea is that DEFINE puts the flag in the weird +// namespace, and DECLARE imports the flag from there into the +// current namespace. The net result is to force people to use +// DECLARE to get access to a flag, rather than saying +// extern bool FLAGS_logtostderr; +// or some such instead. We want this so we can put extra +// functionality (like sanity-checking) in DECLARE if we want, +// and make sure it is picked up everywhere. +// +// We also put the type of the variable in the namespace, so that +// people can't DECLARE_int32 something that they DEFINE_bool'd +// elsewhere. +#ifndef BASE_COMMANDLINEFLAGS_H__ +#define BASE_COMMANDLINEFLAGS_H__ + +#include "config.h" +#include // for getenv +#include // for memchr +#include + +#ifdef HAVE_LIB_GFLAGS + +#include + +#else + +#include + +#define DECLARE_VARIABLE(type, shorttype, name, tn) \ + namespace fL##shorttype { \ + extern GLOG_EXPORT type FLAGS_##name; \ + } \ + using fL##shorttype::FLAGS_##name +#define DEFINE_VARIABLE(type, shorttype, name, value, meaning, tn) \ + namespace fL##shorttype { \ + GLOG_EXPORT type FLAGS_##name(value); \ + char FLAGS_no##name; \ + } \ + using fL##shorttype::FLAGS_##name + +// bool specialization +#define DECLARE_bool(name) \ + DECLARE_VARIABLE(bool, B, name, bool) +#define DEFINE_bool(name, value, meaning) \ + DEFINE_VARIABLE(bool, B, name, value, meaning, bool) + +// int32 specialization +#define DECLARE_int32(name) \ + DECLARE_VARIABLE(GOOGLE_NAMESPACE::int32, I, name, int32) +#define DEFINE_int32(name, value, meaning) \ + DEFINE_VARIABLE(GOOGLE_NAMESPACE::int32, I, name, value, meaning, int32) + +// uint32 specialization +#ifndef DECLARE_uint32 +#define DECLARE_uint32(name) \ + DECLARE_VARIABLE(GOOGLE_NAMESPACE::uint32, U, name, uint32) +#endif // DECLARE_uint64 +#define DEFINE_uint32(name, value, meaning) \ + DEFINE_VARIABLE(GOOGLE_NAMESPACE::uint32, U, name, value, meaning, uint32) + +// Special case for string, because we have to specify the namespace +// std::string, which doesn't play nicely with our FLAG__namespace hackery. +#define DECLARE_string(name) \ + namespace fLS { \ + extern GLOG_EXPORT std::string& FLAGS_##name; \ + } \ + using fLS::FLAGS_##name +#define DEFINE_string(name, value, meaning) \ + namespace fLS { \ + std::string FLAGS_##name##_buf(value); \ + GLOG_EXPORT std::string& FLAGS_##name = FLAGS_##name##_buf; \ + char FLAGS_no##name; \ + } \ + using fLS::FLAGS_##name + +#endif // HAVE_LIB_GFLAGS + +// Define GLOG_DEFINE_* using DEFINE_* . By using these macros, we +// have GLOG_* environ variables even if we have gflags installed. +// +// If both an environment variable and a flag are specified, the value +// specified by a flag wins. E.g., if GLOG_v=0 and --v=1, the +// verbosity will be 1, not 0. + +#define GLOG_DEFINE_bool(name, value, meaning) \ + DEFINE_bool(name, EnvToBool("GLOG_" #name, value), meaning) + +#define GLOG_DEFINE_int32(name, value, meaning) \ + DEFINE_int32(name, EnvToInt("GLOG_" #name, value), meaning) + +#define GLOG_DEFINE_uint32(name, value, meaning) \ + DEFINE_uint32(name, EnvToUInt("GLOG_" #name, value), meaning) + +#define GLOG_DEFINE_string(name, value, meaning) \ + DEFINE_string(name, EnvToString("GLOG_" #name, value), meaning) + +// These macros (could be functions, but I don't want to bother with a .cc +// file), make it easier to initialize flags from the environment. + +#define EnvToString(envname, dflt) \ + (!getenv(envname) ? (dflt) : getenv(envname)) + +#define EnvToBool(envname, dflt) \ + (!getenv(envname) ? (dflt) : memchr("tTyY1\0", getenv(envname)[0], 6) != NULL) + +#define EnvToInt(envname, dflt) \ + (!getenv(envname) ? (dflt) : strtol(getenv(envname), NULL, 10)) + +#define EnvToUInt(envname, dflt) \ + (!getenv(envname) ? (dflt) : strtoul(getenv(envname), NULL, 10)) + +#endif // BASE_COMMANDLINEFLAGS_H__ diff --git a/third_party/glog/src/base/googleinit.h b/third_party/glog/src/base/googleinit.h new file mode 100644 index 0000000..5a8b515 --- /dev/null +++ b/third_party/glog/src/base/googleinit.h @@ -0,0 +1,51 @@ +// Copyright (c) 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// --- +// Author: Jacob Hoffman-Andrews + +#ifndef _GOOGLEINIT_H +#define _GOOGLEINIT_H + +class GoogleInitializer { + public: + typedef void (*void_function)(void); + GoogleInitializer(const char*, void_function f) { + f(); + } +}; + +#define REGISTER_MODULE_INITIALIZER(name, body) \ + namespace { \ + static void google_init_module_##name () { body; } \ + GoogleInitializer google_initializer_module_##name(#name, \ + google_init_module_##name); \ + } + +#endif /* _GOOGLEINIT_H */ diff --git a/third_party/glog/src/base/mutex.h b/third_party/glog/src/base/mutex.h new file mode 100644 index 0000000..e82c597 --- /dev/null +++ b/third_party/glog/src/base/mutex.h @@ -0,0 +1,333 @@ +// Copyright (c) 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// --- +// Author: Craig Silverstein. +// +// A simple mutex wrapper, supporting locks and read-write locks. +// You should assume the locks are *not* re-entrant. +// +// To use: you should define the following macros in your configure.ac: +// ACX_PTHREAD +// AC_RWLOCK +// The latter is defined in ../autoconf. +// +// This class is meant to be internal-only and should be wrapped by an +// internal namespace. Before you use this module, please give the +// name of your internal namespace for this module. Or, if you want +// to expose it, you'll want to move it to the Google namespace. We +// cannot put this class in global namespace because there can be some +// problems when we have multiple versions of Mutex in each shared object. +// +// NOTE: by default, we have #ifdef'ed out the TryLock() method. +// This is for two reasons: +// 1) TryLock() under Windows is a bit annoying (it requires a +// #define to be defined very early). +// 2) TryLock() is broken for NO_THREADS mode, at least in NDEBUG +// mode. +// If you need TryLock(), and either these two caveats are not a +// problem for you, or you're willing to work around them, then +// feel free to #define GMUTEX_TRYLOCK, or to remove the #ifdefs +// in the code below. +// +// CYGWIN NOTE: Cygwin support for rwlock seems to be buggy: +// http://www.cygwin.com/ml/cygwin/2008-12/msg00017.html +// Because of that, we might as well use windows locks for +// cygwin. They seem to be more reliable than the cygwin pthreads layer. +// +// TRICKY IMPLEMENTATION NOTE: +// This class is designed to be safe to use during +// dynamic-initialization -- that is, by global constructors that are +// run before main() starts. The issue in this case is that +// dynamic-initialization happens in an unpredictable order, and it +// could be that someone else's dynamic initializer could call a +// function that tries to acquire this mutex -- but that all happens +// before this mutex's constructor has run. (This can happen even if +// the mutex and the function that uses the mutex are in the same .cc +// file.) Basically, because Mutex does non-trivial work in its +// constructor, it's not, in the naive implementation, safe to use +// before dynamic initialization has run on it. +// +// The solution used here is to pair the actual mutex primitive with a +// bool that is set to true when the mutex is dynamically initialized. +// (Before that it's false.) Then we modify all mutex routines to +// look at the bool, and not try to lock/unlock until the bool makes +// it to true (which happens after the Mutex constructor has run.) +// +// This works because before main() starts -- particularly, during +// dynamic initialization -- there are no threads, so a) it's ok that +// the mutex operations are a no-op, since we don't need locking then +// anyway; and b) we can be quite confident our bool won't change +// state between a call to Lock() and a call to Unlock() (that would +// require a global constructor in one translation unit to call Lock() +// and another global constructor in another translation unit to call +// Unlock() later, which is pretty perverse). +// +// That said, it's tricky, and can conceivably fail; it's safest to +// avoid trying to acquire a mutex in a global constructor, if you +// can. One way it can fail is that a really smart compiler might +// initialize the bool to true at static-initialization time (too +// early) rather than at dynamic-initialization time. To discourage +// that, we set is_safe_ to true in code (not the constructor +// colon-initializer) and set it to true via a function that always +// evaluates to true, but that the compiler can't know always +// evaluates to true. This should be good enough. + +#ifndef GOOGLE_MUTEX_H_ +#define GOOGLE_MUTEX_H_ + +#include "config.h" // to figure out pthreads support + +#if defined(NO_THREADS) + typedef int MutexType; // to keep a lock-count +#elif defined(_WIN32) || defined(__CYGWIN__) +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN // We only need minimal includes +# endif +# ifdef GMUTEX_TRYLOCK + // We need Windows NT or later for TryEnterCriticalSection(). If you + // don't need that functionality, you can remove these _WIN32_WINNT + // lines, and change TryLock() to assert(0) or something. +# ifndef _WIN32_WINNT +# define _WIN32_WINNT 0x0400 +# endif +# endif +// To avoid macro definition of ERROR. +# ifndef NOGDI +# define NOGDI +# endif +// To avoid macro definition of min/max. +# ifndef NOMINMAX +# define NOMINMAX +# endif +# include + typedef CRITICAL_SECTION MutexType; +#elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK) + // Needed for pthread_rwlock_*. If it causes problems, you could take it + // out, but then you'd have to unset HAVE_RWLOCK (at least on linux -- it + // *does* cause problems for FreeBSD, or MacOSX, but isn't needed + // for locking there.) +# ifdef __linux__ +# ifndef _XOPEN_SOURCE // Some other header might have already set it for us. +# define _XOPEN_SOURCE 500 // may be needed to get the rwlock calls +# endif +# endif +# include + typedef pthread_rwlock_t MutexType; +#elif defined(HAVE_PTHREAD) +# include + typedef pthread_mutex_t MutexType; +#else +# error Need to implement mutex.h for your architecture, or #define NO_THREADS +#endif + +// We need to include these header files after defining _XOPEN_SOURCE +// as they may define the _XOPEN_SOURCE macro. +#include +#include // for abort() + +#define MUTEX_NAMESPACE glog_internal_namespace_ + +namespace MUTEX_NAMESPACE { + +class Mutex { + public: + // Create a Mutex that is not held by anybody. This constructor is + // typically used for Mutexes allocated on the heap or the stack. + // See below for a recommendation for constructing global Mutex + // objects. + inline Mutex(); + + // Destructor + inline ~Mutex(); + + inline void Lock(); // Block if needed until free then acquire exclusively + inline void Unlock(); // Release a lock acquired via Lock() +#ifdef GMUTEX_TRYLOCK + inline bool TryLock(); // If free, Lock() and return true, else return false +#endif + // Note that on systems that don't support read-write locks, these may + // be implemented as synonyms to Lock() and Unlock(). So you can use + // these for efficiency, but don't use them anyplace where being able + // to do shared reads is necessary to avoid deadlock. + inline void ReaderLock(); // Block until free or shared then acquire a share + inline void ReaderUnlock(); // Release a read share of this Mutex + inline void WriterLock() { Lock(); } // Acquire an exclusive lock + inline void WriterUnlock() { Unlock(); } // Release a lock from WriterLock() + + // TODO(hamaji): Do nothing, implement correctly. + inline void AssertHeld() {} + + private: + MutexType mutex_; + // We want to make sure that the compiler sets is_safe_ to true only + // when we tell it to, and never makes assumptions is_safe_ is + // always true. volatile is the most reliable way to do that. + volatile bool is_safe_; + + inline void SetIsSafe() { is_safe_ = true; } + + // Catch the error of writing Mutex when intending MutexLock. + Mutex(Mutex* /*ignored*/) {} + // Disallow "evil" constructors + Mutex(const Mutex&); + void operator=(const Mutex&); +}; + +// Now the implementation of Mutex for various systems +#if defined(NO_THREADS) + +// When we don't have threads, we can be either reading or writing, +// but not both. We can have lots of readers at once (in no-threads +// mode, that's most likely to happen in recursive function calls), +// but only one writer. We represent this by having mutex_ be -1 when +// writing and a number > 0 when reading (and 0 when no lock is held). +// +// In debug mode, we assert these invariants, while in non-debug mode +// we do nothing, for efficiency. That's why everything is in an +// assert. + +Mutex::Mutex() : mutex_(0) { } +Mutex::~Mutex() { assert(mutex_ == 0); } +void Mutex::Lock() { assert(--mutex_ == -1); } +void Mutex::Unlock() { assert(mutex_++ == -1); } +#ifdef GMUTEX_TRYLOCK +bool Mutex::TryLock() { if (mutex_) return false; Lock(); return true; } +#endif +void Mutex::ReaderLock() { assert(++mutex_ > 0); } +void Mutex::ReaderUnlock() { assert(mutex_-- > 0); } + +#elif defined(_WIN32) || defined(__CYGWIN__) + +Mutex::Mutex() { InitializeCriticalSection(&mutex_); SetIsSafe(); } +Mutex::~Mutex() { DeleteCriticalSection(&mutex_); } +void Mutex::Lock() { if (is_safe_) EnterCriticalSection(&mutex_); } +void Mutex::Unlock() { if (is_safe_) LeaveCriticalSection(&mutex_); } +#ifdef GMUTEX_TRYLOCK +bool Mutex::TryLock() { return is_safe_ ? + TryEnterCriticalSection(&mutex_) != 0 : true; } +#endif +void Mutex::ReaderLock() { Lock(); } // we don't have read-write locks +void Mutex::ReaderUnlock() { Unlock(); } + +#elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK) + +#define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \ + if (is_safe_ && fncall(&mutex_) != 0) abort(); \ +} while (0) + +Mutex::Mutex() { + SetIsSafe(); + if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort(); +} +Mutex::~Mutex() { SAFE_PTHREAD(pthread_rwlock_destroy); } +void Mutex::Lock() { SAFE_PTHREAD(pthread_rwlock_wrlock); } +void Mutex::Unlock() { SAFE_PTHREAD(pthread_rwlock_unlock); } +#ifdef GMUTEX_TRYLOCK +bool Mutex::TryLock() { return is_safe_ ? + pthread_rwlock_trywrlock(&mutex_) == 0 : + true; } +#endif +void Mutex::ReaderLock() { SAFE_PTHREAD(pthread_rwlock_rdlock); } +void Mutex::ReaderUnlock() { SAFE_PTHREAD(pthread_rwlock_unlock); } +#undef SAFE_PTHREAD + +#elif defined(HAVE_PTHREAD) + +#define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \ + if (is_safe_ && fncall(&mutex_) != 0) abort(); \ +} while (0) + +Mutex::Mutex() { + SetIsSafe(); + if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort(); +} +Mutex::~Mutex() { SAFE_PTHREAD(pthread_mutex_destroy); } +void Mutex::Lock() { SAFE_PTHREAD(pthread_mutex_lock); } +void Mutex::Unlock() { SAFE_PTHREAD(pthread_mutex_unlock); } +#ifdef GMUTEX_TRYLOCK +bool Mutex::TryLock() { return is_safe_ ? + pthread_mutex_trylock(&mutex_) == 0 : true; } +#endif +void Mutex::ReaderLock() { Lock(); } +void Mutex::ReaderUnlock() { Unlock(); } +#undef SAFE_PTHREAD + +#endif + +// -------------------------------------------------------------------------- +// Some helper classes + +// MutexLock(mu) acquires mu when constructed and releases it when destroyed. +class MutexLock { + public: + explicit MutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); } + ~MutexLock() { mu_->Unlock(); } + private: + Mutex * const mu_; + // Disallow "evil" constructors + MutexLock(const MutexLock&); + void operator=(const MutexLock&); +}; + +// ReaderMutexLock and WriterMutexLock do the same, for rwlocks +class ReaderMutexLock { + public: + explicit ReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); } + ~ReaderMutexLock() { mu_->ReaderUnlock(); } + private: + Mutex * const mu_; + // Disallow "evil" constructors + ReaderMutexLock(const ReaderMutexLock&); + void operator=(const ReaderMutexLock&); +}; + +class WriterMutexLock { + public: + explicit WriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); } + ~WriterMutexLock() { mu_->WriterUnlock(); } + private: + Mutex * const mu_; + // Disallow "evil" constructors + WriterMutexLock(const WriterMutexLock&); + void operator=(const WriterMutexLock&); +}; + +// Catch bug where variable name is omitted, e.g. MutexLock (&mu); +#define MutexLock(x) COMPILE_ASSERT(0, mutex_lock_decl_missing_var_name) +#define ReaderMutexLock(x) COMPILE_ASSERT(0, rmutex_lock_decl_missing_var_name) +#define WriterMutexLock(x) COMPILE_ASSERT(0, wmutex_lock_decl_missing_var_name) + +} // namespace MUTEX_NAMESPACE + +using namespace MUTEX_NAMESPACE; + +#undef MUTEX_NAMESPACE + +#endif /* #define GOOGLE_MUTEX_H__ */ diff --git a/third_party/glog/src/cleanup_immediately_unittest.cc b/third_party/glog/src/cleanup_immediately_unittest.cc new file mode 100644 index 0000000..89d008e --- /dev/null +++ b/third_party/glog/src/cleanup_immediately_unittest.cc @@ -0,0 +1,96 @@ +// Copyright (c) 2021, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include +#include + +#include "base/commandlineflags.h" +#include "googletest.h" + +#ifdef HAVE_LIB_GFLAGS +#include +using namespace GFLAGS_NAMESPACE; +#endif + +#ifdef HAVE_LIB_GMOCK +#include + +#include "mock-log.h" +// Introduce several symbols from gmock. +using GOOGLE_NAMESPACE::glog_testing::ScopedMockLog; +using testing::_; +using testing::AllOf; +using testing::AnyNumber; +using testing::HasSubstr; +using testing::InitGoogleMock; +using testing::StrictMock; +using testing::StrNe; +#endif + +using namespace GOOGLE_NAMESPACE; + +TEST(CleanImmediately, logging) { + google::SetLogFilenameExtension(".foobar"); + google::EnableLogCleaner(0); + + for (unsigned i = 0; i < 1000; ++i) { + LOG(INFO) << "cleanup test"; + } + + google::DisableLogCleaner(); +} + +int main(int argc, char **argv) { + FLAGS_colorlogtostderr = false; + FLAGS_timestamp_in_logfile_name = true; +#ifdef HAVE_LIB_GFLAGS + ParseCommandLineFlags(&argc, &argv, true); +#endif + // Make sure stderr is not buffered as stderr seems to be buffered + // on recent windows. + setbuf(stderr, NULL); + + // Test some basics before InitGoogleLogging: + CaptureTestStderr(); + const string early_stderr = GetCapturedTestStderr(); + + EXPECT_FALSE(IsGoogleLoggingInitialized()); + + InitGoogleLogging(argv[0]); + + EXPECT_TRUE(IsGoogleLoggingInitialized()); + + InitGoogleTest(&argc, argv); +#ifdef HAVE_LIB_GMOCK + InitGoogleMock(&argc, argv); +#endif + + // so that death tests run before we use threads + CHECK_EQ(RUN_ALL_TESTS(), 0); +} diff --git a/third_party/glog/src/cleanup_with_absolute_prefix_unittest.cc b/third_party/glog/src/cleanup_with_absolute_prefix_unittest.cc new file mode 100644 index 0000000..d4bb47e --- /dev/null +++ b/third_party/glog/src/cleanup_with_absolute_prefix_unittest.cc @@ -0,0 +1,101 @@ +// Copyright (c) 2021, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include +#include + +#include "base/commandlineflags.h" +#include "googletest.h" + +#ifdef HAVE_LIB_GFLAGS +#include +using namespace GFLAGS_NAMESPACE; +#endif + +#ifdef HAVE_LIB_GMOCK +#include + +#include "mock-log.h" +// Introduce several symbols from gmock. +using GOOGLE_NAMESPACE::glog_testing::ScopedMockLog; +using testing::_; +using testing::AllOf; +using testing::AnyNumber; +using testing::HasSubstr; +using testing::InitGoogleMock; +using testing::StrictMock; +using testing::StrNe; +#endif + +using namespace GOOGLE_NAMESPACE; + +TEST(CleanImmediatelyWithAbsolutePrefix, logging) { + google::EnableLogCleaner(0); + google::SetLogFilenameExtension(".barfoo"); + google::SetLogDestination(GLOG_INFO, "test_cleanup_"); + + for (unsigned i = 0; i < 1000; ++i) { + LOG(INFO) << "cleanup test"; + } + + for (unsigned i = 0; i < 10; ++i) { + LOG(ERROR) << "cleanup test"; + } + + google::DisableLogCleaner(); +} + +int main(int argc, char **argv) { + FLAGS_colorlogtostderr = false; + FLAGS_timestamp_in_logfile_name = true; +#ifdef HAVE_LIB_GFLAGS + ParseCommandLineFlags(&argc, &argv, true); +#endif + // Make sure stderr is not buffered as stderr seems to be buffered + // on recent windows. + setbuf(stderr, NULL); + + // Test some basics before InitGoogleLogging: + CaptureTestStderr(); + const string early_stderr = GetCapturedTestStderr(); + + EXPECT_FALSE(IsGoogleLoggingInitialized()); + + InitGoogleLogging(argv[0]); + + EXPECT_TRUE(IsGoogleLoggingInitialized()); + + InitGoogleTest(&argc, argv); +#ifdef HAVE_LIB_GMOCK + InitGoogleMock(&argc, argv); +#endif + + // so that death tests run before we use threads + CHECK_EQ(RUN_ALL_TESTS(), 0); +} diff --git a/third_party/glog/src/cleanup_with_relative_prefix_unittest.cc b/third_party/glog/src/cleanup_with_relative_prefix_unittest.cc new file mode 100644 index 0000000..330f465 --- /dev/null +++ b/third_party/glog/src/cleanup_with_relative_prefix_unittest.cc @@ -0,0 +1,97 @@ +// Copyright (c) 2021, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include +#include + +#include "base/commandlineflags.h" +#include "googletest.h" + +#ifdef HAVE_LIB_GFLAGS +#include +using namespace GFLAGS_NAMESPACE; +#endif + +#ifdef HAVE_LIB_GMOCK +#include + +#include "mock-log.h" +// Introduce several symbols from gmock. +using GOOGLE_NAMESPACE::glog_testing::ScopedMockLog; +using testing::_; +using testing::AllOf; +using testing::AnyNumber; +using testing::HasSubstr; +using testing::InitGoogleMock; +using testing::StrictMock; +using testing::StrNe; +#endif + +using namespace GOOGLE_NAMESPACE; + +TEST(CleanImmediatelyWithRelativePrefix, logging) { + google::EnableLogCleaner(0); + google::SetLogFilenameExtension(".relativefoo"); + google::SetLogDestination(GLOG_INFO, "test_subdir/test_cleanup_"); + + for (unsigned i = 0; i < 1000; ++i) { + LOG(INFO) << "cleanup test"; + } + + google::DisableLogCleaner(); +} + +int main(int argc, char **argv) { + FLAGS_colorlogtostderr = false; + FLAGS_timestamp_in_logfile_name = true; +#ifdef HAVE_LIB_GFLAGS + ParseCommandLineFlags(&argc, &argv, true); +#endif + // Make sure stderr is not buffered as stderr seems to be buffered + // on recent windows. + setbuf(stderr, NULL); + + // Test some basics before InitGoogleLogging: + CaptureTestStderr(); + const string early_stderr = GetCapturedTestStderr(); + + EXPECT_FALSE(IsGoogleLoggingInitialized()); + + InitGoogleLogging(argv[0]); + + EXPECT_TRUE(IsGoogleLoggingInitialized()); + + InitGoogleTest(&argc, argv); +#ifdef HAVE_LIB_GMOCK + InitGoogleMock(&argc, argv); +#endif + + // so that death tests run before we use threads + CHECK_EQ(RUN_ALL_TESTS(), 0); +} diff --git a/third_party/glog/src/config.h.cmake.in b/third_party/glog/src/config.h.cmake.in new file mode 100644 index 0000000..b225b7e --- /dev/null +++ b/third_party/glog/src/config.h.cmake.in @@ -0,0 +1,231 @@ +#ifndef GLOG_CONFIG_H +#define GLOG_CONFIG_H + +/* define if glog doesn't use RTTI */ +#cmakedefine DISABLE_RTTI + +/* Namespace for Google classes */ +#cmakedefine GOOGLE_NAMESPACE ${GOOGLE_NAMESPACE} + +/* Define if you have the `dladdr' function */ +#cmakedefine HAVE_DLADDR + +/* Define if you have the `snprintf' function */ +#cmakedefine HAVE_SNPRINTF + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_DLFCN_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_EXECINFO_H + +/* Define if you have the `fcntl' function */ +#cmakedefine HAVE_FCNTL + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_GLOB_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_INTTYPES_H ${HAVE_INTTYPES_H} + +/* Define to 1 if you have the `pthread' library (-lpthread). */ +#cmakedefine HAVE_LIBPTHREAD + +/* define if you have google gflags library */ +#cmakedefine HAVE_LIB_GFLAGS + +/* define if you have google gmock library */ +#cmakedefine HAVE_LIB_GMOCK + +/* define if you have google gtest library */ +#cmakedefine HAVE_LIB_GTEST + +/* define if you have dbghelp library */ +#cmakedefine HAVE_DBGHELP + +/* define if you have libunwind */ +#cmakedefine HAVE_LIB_UNWIND + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_MEMORY_H + +/* define to disable multithreading support. */ +#cmakedefine NO_THREADS + +/* define if the compiler implements namespaces */ +#cmakedefine HAVE_NAMESPACES + +/* Define if you have the 'pread' function */ +#cmakedefine HAVE_PREAD + +/* Define if you have POSIX threads libraries and header files. */ +#cmakedefine HAVE_PTHREAD + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_PWD_H + +/* Define if you have the 'pwrite' function */ +#cmakedefine HAVE_PWRITE + +/* define if the compiler implements pthread_rwlock_* */ +#cmakedefine HAVE_RWLOCK + +/* Define if you have the 'sigaction' function */ +#cmakedefine HAVE_SIGACTION + +/* Define if you have the `sigaltstack' function */ +#cmakedefine HAVE_SIGALTSTACK + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STDINT_H ${HAVE_STDINT_H} + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STRINGS_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYSCALL_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYSLOG_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_STAT_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_SYSCALL_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_TIME_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_TYPES_H ${HAVE_SYS_TYPES_H} + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_UCONTEXT_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_UTSNAME_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_WAIT_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_UCONTEXT_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_UNISTD_H ${HAVE_UNISTD_H} + +/* Define if you have the header file. */ +#cmakedefine HAVE_UNWIND_H + +/* Define if you linking to _Unwind_Backtrace is possible. */ +#cmakedefine HAVE__UNWIND_BACKTRACE + +/* define if the compiler supports using expression for operator */ +#cmakedefine HAVE_USING_OPERATOR + +/* define if your compiler has __attribute__ */ +#cmakedefine HAVE___ATTRIBUTE__ + +/* define if your compiler has __builtin_expect */ +#cmakedefine HAVE___BUILTIN_EXPECT ${HAVE___BUILTIN_EXPECT} + +/* define if your compiler has __sync_val_compare_and_swap */ +#cmakedefine HAVE___SYNC_VAL_COMPARE_AND_SWAP + +/* define if symbolize support is available */ +#cmakedefine HAVE_SYMBOLIZE + +/* define if localtime_r is available in time.h */ +#cmakedefine HAVE_LOCALTIME_R + +/* define if gmtime_r is available in time.h */ +#cmakedefine HAVE_GMTIME_R + +/* Define to the sub-directory in which libtool stores uninstalled libraries. + */ +#cmakedefine LT_OBJDIR + +/* Name of package */ +#cmakedefine PACKAGE + +/* Define to the address where bug reports for this package should be sent. */ +#cmakedefine PACKAGE_BUGREPORT + +/* Define to the full name of this package. */ +#cmakedefine PACKAGE_NAME + +/* Define to the full name and version of this package. */ +#cmakedefine PACKAGE_STRING + +/* Define to the one symbol short name of this package. */ +#cmakedefine PACKAGE_TARNAME + +/* Define to the home page for this package. */ +#cmakedefine PACKAGE_URL + +/* Define to the version of this package. */ +#cmakedefine PACKAGE_VERSION + +/* How to access the PC from a struct ucontext */ +#cmakedefine PC_FROM_UCONTEXT + +/* define if we should print file offsets in traces instead of symbolizing. */ +#cmakedefine PRINT_UNSYMBOLIZED_STACK_TRACES + +/* Define to necessary symbol if this constant uses a non-standard name on + your system. */ +#cmakedefine PTHREAD_CREATE_JOINABLE + +/* The size of `void *', as computed by sizeof. */ +#cmakedefine SIZEOF_VOID_P ${SIZEOF_VOID_P} + +/* Define to 1 if you have the ANSI C header files. */ +#cmakedefine STDC_HEADERS + +/* the namespace where STL code like vector<> is defined */ +#cmakedefine STL_NAMESPACE ${STL_NAMESPACE} + +/* location of source code */ +#cmakedefine TEST_SRC_DIR ${TEST_SRC_DIR} + +/* Define to necessary thread-local storage attribute. */ +#cmakedefine GLOG_THREAD_LOCAL_STORAGE ${GLOG_THREAD_LOCAL_STORAGE} + +/* Check whether aligned_storage and alignof present */ +#cmakedefine HAVE_ALIGNED_STORAGE ${HAVE_ALIGNED_STORAGE} + +/* Check whether C++11 atomic is available */ +#cmakedefine HAVE_CXX11_ATOMIC ${HAVE_CXX11_ATOMIC} + +/* Check whether C++11 chrono is available */ +#cmakedefine HAVE_CXX11_CHRONO ${HAVE_CXX11_CHRONO} + +/* Check whether C++11 nullptr_t is available */ +#cmakedefine HAVE_CXX11_NULLPTR_T ${HAVE_CXX11_NULLPTR_T} + +/* Version number of package */ +#cmakedefine VERSION + +#ifdef GLOG_BAZEL_BUILD + +/* TODO(rodrigoq): remove this workaround once bazel#3979 is resolved: + * https://github.com/bazelbuild/bazel/issues/3979 */ +#define _START_GOOGLE_NAMESPACE_ namespace GOOGLE_NAMESPACE { + +#define _END_GOOGLE_NAMESPACE_ } + +#else + +/* Stops putting the code inside the Google namespace */ +#cmakedefine _END_GOOGLE_NAMESPACE_ ${_END_GOOGLE_NAMESPACE_} + +/* Puts following code inside the Google namespace */ +#cmakedefine _START_GOOGLE_NAMESPACE_ ${_START_GOOGLE_NAMESPACE_} + +#endif + +/* Replacement for deprecated syscall(SYS_gettid) on macOS. */ +#cmakedefine HAVE_PTHREAD_THREADID_NP ${HAVE_PTHREAD_THREADID_NP} + +#endif // GLOG_CONFIG_H diff --git a/third_party/glog/src/demangle.cc b/third_party/glog/src/demangle.cc new file mode 100644 index 0000000..2ee9da0 --- /dev/null +++ b/third_party/glog/src/demangle.cc @@ -0,0 +1,1364 @@ +// Copyright (c) 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Satoru Takabayashi +// +// For reference check out: +// http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling +// +// Note that we only have partial C++0x support yet. + +#include // for NULL + +#include "demangle.h" +#include "utilities.h" + +#if defined(GLOG_OS_WINDOWS) +#include +#endif + +_START_GOOGLE_NAMESPACE_ + +#if !defined(GLOG_OS_WINDOWS) +typedef struct { + const char *abbrev; + const char *real_name; +} AbbrevPair; + +// List of operators from Itanium C++ ABI. +static const AbbrevPair kOperatorList[] = { + { "nw", "new" }, + { "na", "new[]" }, + { "dl", "delete" }, + { "da", "delete[]" }, + { "ps", "+" }, + { "ng", "-" }, + { "ad", "&" }, + { "de", "*" }, + { "co", "~" }, + { "pl", "+" }, + { "mi", "-" }, + { "ml", "*" }, + { "dv", "/" }, + { "rm", "%" }, + { "an", "&" }, + { "or", "|" }, + { "eo", "^" }, + { "aS", "=" }, + { "pL", "+=" }, + { "mI", "-=" }, + { "mL", "*=" }, + { "dV", "/=" }, + { "rM", "%=" }, + { "aN", "&=" }, + { "oR", "|=" }, + { "eO", "^=" }, + { "ls", "<<" }, + { "rs", ">>" }, + { "lS", "<<=" }, + { "rS", ">>=" }, + { "eq", "==" }, + { "ne", "!=" }, + { "lt", "<" }, + { "gt", ">" }, + { "le", "<=" }, + { "ge", ">=" }, + { "nt", "!" }, + { "aa", "&&" }, + { "oo", "||" }, + { "pp", "++" }, + { "mm", "--" }, + { "cm", "," }, + { "pm", "->*" }, + { "pt", "->" }, + { "cl", "()" }, + { "ix", "[]" }, + { "qu", "?" }, + { "st", "sizeof" }, + { "sz", "sizeof" }, + { NULL, NULL }, +}; + +// List of builtin types from Itanium C++ ABI. +static const AbbrevPair kBuiltinTypeList[] = { + { "v", "void" }, + { "w", "wchar_t" }, + { "b", "bool" }, + { "c", "char" }, + { "a", "signed char" }, + { "h", "unsigned char" }, + { "s", "short" }, + { "t", "unsigned short" }, + { "i", "int" }, + { "j", "unsigned int" }, + { "l", "long" }, + { "m", "unsigned long" }, + { "x", "long long" }, + { "y", "unsigned long long" }, + { "n", "__int128" }, + { "o", "unsigned __int128" }, + { "f", "float" }, + { "d", "double" }, + { "e", "long double" }, + { "g", "__float128" }, + { "z", "ellipsis" }, + { NULL, NULL } +}; + +// List of substitutions Itanium C++ ABI. +static const AbbrevPair kSubstitutionList[] = { + { "St", "" }, + { "Sa", "allocator" }, + { "Sb", "basic_string" }, + // std::basic_string,std::allocator > + { "Ss", "string"}, + // std::basic_istream > + { "Si", "istream" }, + // std::basic_ostream > + { "So", "ostream" }, + // std::basic_iostream > + { "Sd", "iostream" }, + { NULL, NULL } +}; + +// State needed for demangling. +typedef struct { + const char *mangled_cur; // Cursor of mangled name. + char *out_cur; // Cursor of output string. + const char *out_begin; // Beginning of output string. + const char *out_end; // End of output string. + const char *prev_name; // For constructors/destructors. + int prev_name_length; // For constructors/destructors. + short nest_level; // For nested names. + bool append; // Append flag. + bool overflowed; // True if output gets overflowed. +} State; + +// We don't use strlen() in libc since it's not guaranteed to be async +// signal safe. +static size_t StrLen(const char *str) { + size_t len = 0; + while (*str != '\0') { + ++str; + ++len; + } + return len; +} + +// Returns true if "str" has at least "n" characters remaining. +static bool AtLeastNumCharsRemaining(const char *str, int n) { + for (int i = 0; i < n; ++i) { + if (str[i] == '\0') { + return false; + } + } + return true; +} + +// Returns true if "str" has "prefix" as a prefix. +static bool StrPrefix(const char *str, const char *prefix) { + size_t i = 0; + while (str[i] != '\0' && prefix[i] != '\0' && + str[i] == prefix[i]) { + ++i; + } + return prefix[i] == '\0'; // Consumed everything in "prefix". +} + +static void InitState(State *state, const char *mangled, + char *out, size_t out_size) { + state->mangled_cur = mangled; + state->out_cur = out; + state->out_begin = out; + state->out_end = out + out_size; + state->prev_name = NULL; + state->prev_name_length = -1; + state->nest_level = -1; + state->append = true; + state->overflowed = false; +} + +// Returns true and advances "mangled_cur" if we find "one_char_token" +// at "mangled_cur" position. It is assumed that "one_char_token" does +// not contain '\0'. +static bool ParseOneCharToken(State *state, const char one_char_token) { + if (state->mangled_cur[0] == one_char_token) { + ++state->mangled_cur; + return true; + } + return false; +} + +// Returns true and advances "mangled_cur" if we find "two_char_token" +// at "mangled_cur" position. It is assumed that "two_char_token" does +// not contain '\0'. +static bool ParseTwoCharToken(State *state, const char *two_char_token) { + if (state->mangled_cur[0] == two_char_token[0] && + state->mangled_cur[1] == two_char_token[1]) { + state->mangled_cur += 2; + return true; + } + return false; +} + +// Returns true and advances "mangled_cur" if we find any character in +// "char_class" at "mangled_cur" position. +static bool ParseCharClass(State *state, const char *char_class) { + const char *p = char_class; + for (; *p != '\0'; ++p) { + if (state->mangled_cur[0] == *p) { + ++state->mangled_cur; + return true; + } + } + return false; +} + +// This function is used for handling an optional non-terminal. +static bool Optional(bool) { + return true; +} + +// This function is used for handling + syntax. +typedef bool (*ParseFunc)(State *); +static bool OneOrMore(ParseFunc parse_func, State *state) { + if (parse_func(state)) { + while (parse_func(state)) { + } + return true; + } + return false; +} + +// This function is used for handling * syntax. The function +// always returns true and must be followed by a termination token or a +// terminating sequence not handled by parse_func (e.g. +// ParseOneCharToken(state, 'E')). +static bool ZeroOrMore(ParseFunc parse_func, State *state) { + while (parse_func(state)) { + } + return true; +} + +// Append "str" at "out_cur". If there is an overflow, "overflowed" +// is set to true for later use. The output string is ensured to +// always terminate with '\0' as long as there is no overflow. +static void Append(State *state, const char * const str, const int length) { + int i; + for (i = 0; i < length; ++i) { + if (state->out_cur + 1 < state->out_end) { // +1 for '\0' + *state->out_cur = str[i]; + ++state->out_cur; + } else { + state->overflowed = true; + break; + } + } + if (!state->overflowed) { + *state->out_cur = '\0'; // Terminate it with '\0' + } +} + +// We don't use equivalents in libc to avoid locale issues. +static bool IsLower(char c) { + return c >= 'a' && c <= 'z'; +} + +static bool IsAlpha(char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); +} + +static bool IsDigit(char c) { + return c >= '0' && c <= '9'; +} + +// Returns true if "str" is a function clone suffix. These suffixes are used +// by GCC 4.5.x and later versions to indicate functions which have been +// cloned during optimization. We treat any sequence (.+.+)+ as +// a function clone suffix. +static bool IsFunctionCloneSuffix(const char *str) { + size_t i = 0; + while (str[i] != '\0') { + // Consume a single .+.+ sequence. + if (str[i] != '.' || !IsAlpha(str[i + 1])) { + return false; + } + i += 2; + while (IsAlpha(str[i])) { + ++i; + } + if (str[i] != '.' || !IsDigit(str[i + 1])) { + return false; + } + i += 2; + while (IsDigit(str[i])) { + ++i; + } + } + return true; // Consumed everything in "str". +} + +// Append "str" with some tweaks, iff "append" state is true. +// Returns true so that it can be placed in "if" conditions. +static void MaybeAppendWithLength(State *state, const char * const str, + const int length) { + if (state->append && length > 0) { + // Append a space if the output buffer ends with '<' and "str" + // starts with '<' to avoid <<<. + if (str[0] == '<' && state->out_begin < state->out_cur && + state->out_cur[-1] == '<') { + Append(state, " ", 1); + } + // Remember the last identifier name for ctors/dtors. + if (IsAlpha(str[0]) || str[0] == '_') { + state->prev_name = state->out_cur; + state->prev_name_length = length; + } + Append(state, str, length); + } +} + +// A convenient wrapper arount MaybeAppendWithLength(). +static bool MaybeAppend(State *state, const char * const str) { + if (state->append) { + int length = StrLen(str); + MaybeAppendWithLength(state, str, length); + } + return true; +} + +// This function is used for handling nested names. +static bool EnterNestedName(State *state) { + state->nest_level = 0; + return true; +} + +// This function is used for handling nested names. +static bool LeaveNestedName(State *state, short prev_value) { + state->nest_level = prev_value; + return true; +} + +// Disable the append mode not to print function parameters, etc. +static bool DisableAppend(State *state) { + state->append = false; + return true; +} + +// Restore the append mode to the previous state. +static bool RestoreAppend(State *state, bool prev_value) { + state->append = prev_value; + return true; +} + +// Increase the nest level for nested names. +static void MaybeIncreaseNestLevel(State *state) { + if (state->nest_level > -1) { + ++state->nest_level; + } +} + +// Appends :: for nested names if necessary. +static void MaybeAppendSeparator(State *state) { + if (state->nest_level >= 1) { + MaybeAppend(state, "::"); + } +} + +// Cancel the last separator if necessary. +static void MaybeCancelLastSeparator(State *state) { + if (state->nest_level >= 1 && state->append && + state->out_begin <= state->out_cur - 2) { + state->out_cur -= 2; + *state->out_cur = '\0'; + } +} + +// Returns true if the identifier of the given length pointed to by +// "mangled_cur" is anonymous namespace. +static bool IdentifierIsAnonymousNamespace(State *state, int length) { + static const char anon_prefix[] = "_GLOBAL__N_"; + return (length > + static_cast(sizeof(anon_prefix)) - 1 && // Should be longer. + StrPrefix(state->mangled_cur, anon_prefix)); +} + +// Forward declarations of our parsing functions. +static bool ParseMangledName(State *state); +static bool ParseEncoding(State *state); +static bool ParseName(State *state); +static bool ParseUnscopedName(State *state); +static bool ParseUnscopedTemplateName(State *state); +static bool ParseNestedName(State *state); +static bool ParsePrefix(State *state); +static bool ParseUnqualifiedName(State *state); +static bool ParseSourceName(State *state); +static bool ParseLocalSourceName(State *state); +static bool ParseNumber(State *state, int *number_out); +static bool ParseFloatNumber(State *state); +static bool ParseSeqId(State *state); +static bool ParseIdentifier(State *state, int length); +static bool ParseAbiTags(State *state); +static bool ParseAbiTag(State *state); +static bool ParseOperatorName(State *state); +static bool ParseSpecialName(State *state); +static bool ParseCallOffset(State *state); +static bool ParseNVOffset(State *state); +static bool ParseVOffset(State *state); +static bool ParseCtorDtorName(State *state); +static bool ParseType(State *state); +static bool ParseCVQualifiers(State *state); +static bool ParseBuiltinType(State *state); +static bool ParseFunctionType(State *state); +static bool ParseBareFunctionType(State *state); +static bool ParseClassEnumType(State *state); +static bool ParseArrayType(State *state); +static bool ParsePointerToMemberType(State *state); +static bool ParseTemplateParam(State *state); +static bool ParseTemplateTemplateParam(State *state); +static bool ParseTemplateArgs(State *state); +static bool ParseTemplateArg(State *state); +static bool ParseExpression(State *state); +static bool ParseExprPrimary(State *state); +static bool ParseLocalName(State *state); +static bool ParseDiscriminator(State *state); +static bool ParseSubstitution(State *state); + +// Implementation note: the following code is a straightforward +// translation of the Itanium C++ ABI defined in BNF with a couple of +// exceptions. +// +// - Support GNU extensions not defined in the Itanium C++ ABI +// - and are combined to avoid infinite loop +// - Reorder patterns to shorten the code +// - Reorder patterns to give greedier functions precedence +// We'll mark "Less greedy than" for these cases in the code +// +// Each parsing function changes the state and returns true on +// success. Otherwise, don't change the state and returns false. To +// ensure that the state isn't changed in the latter case, we save the +// original state before we call more than one parsing functions +// consecutively with &&, and restore the state if unsuccessful. See +// ParseEncoding() as an example of this convention. We follow the +// convention throughout the code. +// +// Originally we tried to do demangling without following the full ABI +// syntax but it turned out we needed to follow the full syntax to +// parse complicated cases like nested template arguments. Note that +// implementing a full-fledged demangler isn't trivial (libiberty's +// cp-demangle.c has +4300 lines). +// +// Note that (foo) in <(foo) ...> is a modifier to be ignored. +// +// Reference: +// - Itanium C++ ABI +// + +// ::= _Z +static bool ParseMangledName(State *state) { + return ParseTwoCharToken(state, "_Z") && ParseEncoding(state); +} + +// ::= <(function) name> +// ::= <(data) name> +// ::= +static bool ParseEncoding(State *state) { + State copy = *state; + if (ParseName(state) && ParseBareFunctionType(state)) { + return true; + } + *state = copy; + + if (ParseName(state) || ParseSpecialName(state)) { + return true; + } + return false; +} + +// ::= +// ::= +// ::= +// ::= +static bool ParseName(State *state) { + if (ParseNestedName(state) || ParseLocalName(state)) { + return true; + } + + State copy = *state; + if (ParseUnscopedTemplateName(state) && + ParseTemplateArgs(state)) { + return true; + } + *state = copy; + + // Less greedy than . + if (ParseUnscopedName(state)) { + return true; + } + return false; +} + +// ::= +// ::= St +static bool ParseUnscopedName(State *state) { + if (ParseUnqualifiedName(state)) { + return true; + } + + State copy = *state; + if (ParseTwoCharToken(state, "St") && + MaybeAppend(state, "std::") && + ParseUnqualifiedName(state)) { + return true; + } + *state = copy; + return false; +} + +// ::= +// ::= +static bool ParseUnscopedTemplateName(State *state) { + return ParseUnscopedName(state) || ParseSubstitution(state); +} + +// ::= N [] E +// ::= N [] E +static bool ParseNestedName(State *state) { + State copy = *state; + if (ParseOneCharToken(state, 'N') && + EnterNestedName(state) && + Optional(ParseCVQualifiers(state)) && + ParsePrefix(state) && + LeaveNestedName(state, copy.nest_level) && + ParseOneCharToken(state, 'E')) { + return true; + } + *state = copy; + return false; +} + +// This part is tricky. If we literally translate them to code, we'll +// end up infinite loop. Hence we merge them to avoid the case. +// +// ::= +// ::= +// ::= +// ::= +// ::= # empty +// ::= <(template) unqualified-name> +// ::= +// ::= +static bool ParsePrefix(State *state) { + bool has_something = false; + while (true) { + MaybeAppendSeparator(state); + if (ParseTemplateParam(state) || + ParseSubstitution(state) || + ParseUnscopedName(state)) { + has_something = true; + MaybeIncreaseNestLevel(state); + continue; + } + MaybeCancelLastSeparator(state); + if (has_something && ParseTemplateArgs(state)) { + return ParsePrefix(state); + } else { + break; + } + } + return true; +} + +// ::= +// ::= +// ::= [] +// ::= [] +static bool ParseUnqualifiedName(State *state) { + return (ParseOperatorName(state) || + ParseCtorDtorName(state) || + (ParseSourceName(state) && Optional(ParseAbiTags(state))) || + (ParseLocalSourceName(state) && Optional(ParseAbiTags(state)))); +} + +// ::= +static bool ParseSourceName(State *state) { + State copy = *state; + int length = -1; + if (ParseNumber(state, &length) && ParseIdentifier(state, length)) { + return true; + } + *state = copy; + return false; +} + +// ::= L [] +// +// References: +// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=31775 +// http://gcc.gnu.org/viewcvs?view=rev&revision=124467 +static bool ParseLocalSourceName(State *state) { + State copy = *state; + if (ParseOneCharToken(state, 'L') && ParseSourceName(state) && + Optional(ParseDiscriminator(state))) { + return true; + } + *state = copy; + return false; +} + +// ::= [n] +// If "number_out" is non-null, then *number_out is set to the value of the +// parsed number on success. +static bool ParseNumber(State *state, int *number_out) { + int sign = 1; + if (ParseOneCharToken(state, 'n')) { + sign = -1; + } + const char *p = state->mangled_cur; + int number = 0; + for (;*p != '\0'; ++p) { + if (IsDigit(*p)) { + number = number * 10 + (*p - '0'); + } else { + break; + } + } + if (p != state->mangled_cur) { // Conversion succeeded. + state->mangled_cur = p; + if (number_out != NULL) { + *number_out = number * sign; + } + return true; + } + return false; +} + +// Floating-point literals are encoded using a fixed-length lowercase +// hexadecimal string. +static bool ParseFloatNumber(State *state) { + const char *p = state->mangled_cur; + for (;*p != '\0'; ++p) { + if (!IsDigit(*p) && !(*p >= 'a' && *p <= 'f')) { + break; + } + } + if (p != state->mangled_cur) { // Conversion succeeded. + state->mangled_cur = p; + return true; + } + return false; +} + +// The is a sequence number in base 36, +// using digits and upper case letters +static bool ParseSeqId(State *state) { + const char *p = state->mangled_cur; + for (;*p != '\0'; ++p) { + if (!IsDigit(*p) && !(*p >= 'A' && *p <= 'Z')) { + break; + } + } + if (p != state->mangled_cur) { // Conversion succeeded. + state->mangled_cur = p; + return true; + } + return false; +} + +// ::= (of given length) +static bool ParseIdentifier(State *state, int length) { + if (length == -1 || + !AtLeastNumCharsRemaining(state->mangled_cur, length)) { + return false; + } + if (IdentifierIsAnonymousNamespace(state, length)) { + MaybeAppend(state, "(anonymous namespace)"); + } else { + MaybeAppendWithLength(state, state->mangled_cur, length); + } + state->mangled_cur += length; + return true; +} + +// ::= [] +static bool ParseAbiTags(State *state) { + State copy = *state; + DisableAppend(state); + if (OneOrMore(ParseAbiTag, state)) { + RestoreAppend(state, copy.append); + return true; + } + *state = copy; + return false; +} + +// ::= B +static bool ParseAbiTag(State *state) { + return ParseOneCharToken(state, 'B') && ParseSourceName(state); +} + +// ::= nw, and other two letters cases +// ::= cv # (cast) +// ::= v # vendor extended operator +static bool ParseOperatorName(State *state) { + if (!AtLeastNumCharsRemaining(state->mangled_cur, 2)) { + return false; + } + // First check with "cv" (cast) case. + State copy = *state; + if (ParseTwoCharToken(state, "cv") && + MaybeAppend(state, "operator ") && + EnterNestedName(state) && + ParseType(state) && + LeaveNestedName(state, copy.nest_level)) { + return true; + } + *state = copy; + + // Then vendor extended operators. + if (ParseOneCharToken(state, 'v') && ParseCharClass(state, "0123456789") && + ParseSourceName(state)) { + return true; + } + *state = copy; + + // Other operator names should start with a lower alphabet followed + // by a lower/upper alphabet. + if (!(IsLower(state->mangled_cur[0]) && + IsAlpha(state->mangled_cur[1]))) { + return false; + } + // We may want to perform a binary search if we really need speed. + const AbbrevPair *p; + for (p = kOperatorList; p->abbrev != NULL; ++p) { + if (state->mangled_cur[0] == p->abbrev[0] && + state->mangled_cur[1] == p->abbrev[1]) { + MaybeAppend(state, "operator"); + if (IsLower(*p->real_name)) { // new, delete, etc. + MaybeAppend(state, " "); + } + MaybeAppend(state, p->real_name); + state->mangled_cur += 2; + return true; + } + } + return false; +} + +// ::= TV +// ::= TT +// ::= TI +// ::= TS +// ::= Tc <(base) encoding> +// ::= GV <(object) name> +// ::= T <(base) encoding> +// G++ extensions: +// ::= TC <(offset) number> _ <(base) type> +// ::= TF +// ::= TJ +// ::= GR +// ::= GA +// ::= Th <(base) encoding> +// ::= Tv <(base) encoding> +// +// Note: we don't care much about them since they don't appear in +// stack traces. The are special data. +static bool ParseSpecialName(State *state) { + State copy = *state; + if (ParseOneCharToken(state, 'T') && + ParseCharClass(state, "VTIS") && + ParseType(state)) { + return true; + } + *state = copy; + + if (ParseTwoCharToken(state, "Tc") && ParseCallOffset(state) && + ParseCallOffset(state) && ParseEncoding(state)) { + return true; + } + *state = copy; + + if (ParseTwoCharToken(state, "GV") && + ParseName(state)) { + return true; + } + *state = copy; + + if (ParseOneCharToken(state, 'T') && ParseCallOffset(state) && + ParseEncoding(state)) { + return true; + } + *state = copy; + + // G++ extensions + if (ParseTwoCharToken(state, "TC") && ParseType(state) && + ParseNumber(state, NULL) && ParseOneCharToken(state, '_') && + DisableAppend(state) && + ParseType(state)) { + RestoreAppend(state, copy.append); + return true; + } + *state = copy; + + if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "FJ") && + ParseType(state)) { + return true; + } + *state = copy; + + if (ParseTwoCharToken(state, "GR") && ParseName(state)) { + return true; + } + *state = copy; + + if (ParseTwoCharToken(state, "GA") && ParseEncoding(state)) { + return true; + } + *state = copy; + + if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "hv") && + ParseCallOffset(state) && ParseEncoding(state)) { + return true; + } + *state = copy; + return false; +} + +// ::= h _ +// ::= v _ +static bool ParseCallOffset(State *state) { + State copy = *state; + if (ParseOneCharToken(state, 'h') && + ParseNVOffset(state) && ParseOneCharToken(state, '_')) { + return true; + } + *state = copy; + + if (ParseOneCharToken(state, 'v') && + ParseVOffset(state) && ParseOneCharToken(state, '_')) { + return true; + } + *state = copy; + + return false; +} + +// ::= <(offset) number> +static bool ParseNVOffset(State *state) { + return ParseNumber(state, NULL); +} + +// ::= <(offset) number> _ <(virtual offset) number> +static bool ParseVOffset(State *state) { + State copy = *state; + if (ParseNumber(state, NULL) && ParseOneCharToken(state, '_') && + ParseNumber(state, NULL)) { + return true; + } + *state = copy; + return false; +} + +// ::= C1 | C2 | C3 +// ::= D0 | D1 | D2 +static bool ParseCtorDtorName(State *state) { + State copy = *state; + if (ParseOneCharToken(state, 'C') && + ParseCharClass(state, "123")) { + const char * const prev_name = state->prev_name; + const int prev_name_length = state->prev_name_length; + MaybeAppendWithLength(state, prev_name, prev_name_length); + return true; + } + *state = copy; + + if (ParseOneCharToken(state, 'D') && + ParseCharClass(state, "012")) { + const char * const prev_name = state->prev_name; + const int prev_name_length = state->prev_name_length; + MaybeAppend(state, "~"); + MaybeAppendWithLength(state, prev_name, prev_name_length); + return true; + } + *state = copy; + return false; +} + +// ::= +// ::= P # pointer-to +// ::= R # reference-to +// ::= O # rvalue reference-to (C++0x) +// ::= C # complex pair (C 2000) +// ::= G # imaginary (C 2000) +// ::= U # vendor extended type qualifier +// ::= +// ::= +// ::= +// ::= +// ::= +// ::= +// ::= +// ::= +// ::= Dp # pack expansion of (C++0x) +// ::= Dt E # decltype of an id-expression or class +// # member access (C++0x) +// ::= DT E # decltype of an expression (C++0x) +// +static bool ParseType(State *state) { + // We should check CV-qualifers, and PRGC things first. + State copy = *state; + if (ParseCVQualifiers(state) && ParseType(state)) { + return true; + } + *state = copy; + + if (ParseCharClass(state, "OPRCG") && ParseType(state)) { + return true; + } + *state = copy; + + if (ParseTwoCharToken(state, "Dp") && ParseType(state)) { + return true; + } + *state = copy; + + if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "tT") && + ParseExpression(state) && ParseOneCharToken(state, 'E')) { + return true; + } + *state = copy; + + if (ParseOneCharToken(state, 'U') && ParseSourceName(state) && + ParseType(state)) { + return true; + } + *state = copy; + + if (ParseBuiltinType(state) || + ParseFunctionType(state) || + ParseClassEnumType(state) || + ParseArrayType(state) || + ParsePointerToMemberType(state) || + ParseSubstitution(state)) { + return true; + } + + if (ParseTemplateTemplateParam(state) && + ParseTemplateArgs(state)) { + return true; + } + *state = copy; + + // Less greedy than . + if (ParseTemplateParam(state)) { + return true; + } + + return false; +} + +// ::= [r] [V] [K] +// We don't allow empty to avoid infinite loop in +// ParseType(). +static bool ParseCVQualifiers(State *state) { + int num_cv_qualifiers = 0; + num_cv_qualifiers += ParseOneCharToken(state, 'r'); + num_cv_qualifiers += ParseOneCharToken(state, 'V'); + num_cv_qualifiers += ParseOneCharToken(state, 'K'); + return num_cv_qualifiers > 0; +} + +// ::= v, etc. +// ::= u +static bool ParseBuiltinType(State *state) { + const AbbrevPair *p; + for (p = kBuiltinTypeList; p->abbrev != NULL; ++p) { + if (state->mangled_cur[0] == p->abbrev[0]) { + MaybeAppend(state, p->real_name); + ++state->mangled_cur; + return true; + } + } + + State copy = *state; + if (ParseOneCharToken(state, 'u') && ParseSourceName(state)) { + return true; + } + *state = copy; + return false; +} + +// ::= F [Y] E +static bool ParseFunctionType(State *state) { + State copy = *state; + if (ParseOneCharToken(state, 'F') && + Optional(ParseOneCharToken(state, 'Y')) && + ParseBareFunctionType(state) && ParseOneCharToken(state, 'E')) { + return true; + } + *state = copy; + return false; +} + +// ::= <(signature) type>+ +static bool ParseBareFunctionType(State *state) { + State copy = *state; + DisableAppend(state); + if (OneOrMore(ParseType, state)) { + RestoreAppend(state, copy.append); + MaybeAppend(state, "()"); + return true; + } + *state = copy; + return false; +} + +// ::= +static bool ParseClassEnumType(State *state) { + return ParseName(state); +} + +// ::= A <(positive dimension) number> _ <(element) type> +// ::= A [<(dimension) expression>] _ <(element) type> +static bool ParseArrayType(State *state) { + State copy = *state; + if (ParseOneCharToken(state, 'A') && ParseNumber(state, NULL) && + ParseOneCharToken(state, '_') && ParseType(state)) { + return true; + } + *state = copy; + + if (ParseOneCharToken(state, 'A') && Optional(ParseExpression(state)) && + ParseOneCharToken(state, '_') && ParseType(state)) { + return true; + } + *state = copy; + return false; +} + +// ::= M <(class) type> <(member) type> +static bool ParsePointerToMemberType(State *state) { + State copy = *state; + if (ParseOneCharToken(state, 'M') && ParseType(state) && + ParseType(state)) { + return true; + } + *state = copy; + return false; +} + +// ::= T_ +// ::= T _ +static bool ParseTemplateParam(State *state) { + if (ParseTwoCharToken(state, "T_")) { + MaybeAppend(state, "?"); // We don't support template substitutions. + return true; + } + + State copy = *state; + if (ParseOneCharToken(state, 'T') && ParseNumber(state, NULL) && + ParseOneCharToken(state, '_')) { + MaybeAppend(state, "?"); // We don't support template substitutions. + return true; + } + *state = copy; + return false; +} + + +// ::= +// ::= +static bool ParseTemplateTemplateParam(State *state) { + return (ParseTemplateParam(state) || + ParseSubstitution(state)); +} + +// ::= I + E +static bool ParseTemplateArgs(State *state) { + State copy = *state; + DisableAppend(state); + if (ParseOneCharToken(state, 'I') && + OneOrMore(ParseTemplateArg, state) && + ParseOneCharToken(state, 'E')) { + RestoreAppend(state, copy.append); + MaybeAppend(state, "<>"); + return true; + } + *state = copy; + return false; +} + +// ::= +// ::= +// ::= I * E # argument pack +// ::= J * E # argument pack +// ::= X E +static bool ParseTemplateArg(State *state) { + State copy = *state; + if ((ParseOneCharToken(state, 'I') || ParseOneCharToken(state, 'J')) && + ZeroOrMore(ParseTemplateArg, state) && + ParseOneCharToken(state, 'E')) { + return true; + } + *state = copy; + + if (ParseType(state) || + ParseExprPrimary(state)) { + return true; + } + *state = copy; + + if (ParseOneCharToken(state, 'X') && ParseExpression(state) && + ParseOneCharToken(state, 'E')) { + return true; + } + *state = copy; + return false; +} + +// ::= +// ::= +// ::= +// ::= +// ::= +// +// ::= st +// ::= sr +// ::= sr +static bool ParseExpression(State *state) { + if (ParseTemplateParam(state) || ParseExprPrimary(state)) { + return true; + } + + State copy = *state; + if (ParseOperatorName(state) && + ParseExpression(state) && + ParseExpression(state) && + ParseExpression(state)) { + return true; + } + *state = copy; + + if (ParseOperatorName(state) && + ParseExpression(state) && + ParseExpression(state)) { + return true; + } + *state = copy; + + if (ParseOperatorName(state) && + ParseExpression(state)) { + return true; + } + *state = copy; + + if (ParseTwoCharToken(state, "st") && ParseType(state)) { + return true; + } + *state = copy; + + if (ParseTwoCharToken(state, "sr") && ParseType(state) && + ParseUnqualifiedName(state) && + ParseTemplateArgs(state)) { + return true; + } + *state = copy; + + if (ParseTwoCharToken(state, "sr") && ParseType(state) && + ParseUnqualifiedName(state)) { + return true; + } + *state = copy; + return false; +} + +// ::= L <(value) number> E +// ::= L <(value) float> E +// ::= L E +// // A bug in g++'s C++ ABI version 2 (-fabi-version=2). +// ::= LZ E +static bool ParseExprPrimary(State *state) { + State copy = *state; + if (ParseOneCharToken(state, 'L') && ParseType(state) && + ParseNumber(state, NULL) && + ParseOneCharToken(state, 'E')) { + return true; + } + *state = copy; + + if (ParseOneCharToken(state, 'L') && ParseType(state) && + ParseFloatNumber(state) && + ParseOneCharToken(state, 'E')) { + return true; + } + *state = copy; + + if (ParseOneCharToken(state, 'L') && ParseMangledName(state) && + ParseOneCharToken(state, 'E')) { + return true; + } + *state = copy; + + if (ParseTwoCharToken(state, "LZ") && ParseEncoding(state) && + ParseOneCharToken(state, 'E')) { + return true; + } + *state = copy; + + return false; +} + +// := Z <(function) encoding> E <(entity) name> +// [] +// := Z <(function) encoding> E s [] +static bool ParseLocalName(State *state) { + State copy = *state; + if (ParseOneCharToken(state, 'Z') && ParseEncoding(state) && + ParseOneCharToken(state, 'E') && MaybeAppend(state, "::") && + ParseName(state) && Optional(ParseDiscriminator(state))) { + return true; + } + *state = copy; + + if (ParseOneCharToken(state, 'Z') && ParseEncoding(state) && + ParseTwoCharToken(state, "Es") && Optional(ParseDiscriminator(state))) { + return true; + } + *state = copy; + return false; +} + +// := _ <(non-negative) number> +static bool ParseDiscriminator(State *state) { + State copy = *state; + if (ParseOneCharToken(state, '_') && ParseNumber(state, NULL)) { + return true; + } + *state = copy; + return false; +} + +// ::= S_ +// ::= S _ +// ::= St, etc. +static bool ParseSubstitution(State *state) { + if (ParseTwoCharToken(state, "S_")) { + MaybeAppend(state, "?"); // We don't support substitutions. + return true; + } + + State copy = *state; + if (ParseOneCharToken(state, 'S') && ParseSeqId(state) && + ParseOneCharToken(state, '_')) { + MaybeAppend(state, "?"); // We don't support substitutions. + return true; + } + *state = copy; + + // Expand abbreviations like "St" => "std". + if (ParseOneCharToken(state, 'S')) { + const AbbrevPair *p; + for (p = kSubstitutionList; p->abbrev != NULL; ++p) { + if (state->mangled_cur[0] == p->abbrev[1]) { + MaybeAppend(state, "std"); + if (p->real_name[0] != '\0') { + MaybeAppend(state, "::"); + MaybeAppend(state, p->real_name); + } + ++state->mangled_cur; + return true; + } + } + } + *state = copy; + return false; +} + +// Parse , optionally followed by either a function-clone suffix +// or version suffix. Returns true only if all of "mangled_cur" was consumed. +static bool ParseTopLevelMangledName(State *state) { + if (ParseMangledName(state)) { + if (state->mangled_cur[0] != '\0') { + // Drop trailing function clone suffix, if any. + if (IsFunctionCloneSuffix(state->mangled_cur)) { + return true; + } + // Append trailing version suffix if any. + // ex. _Z3foo@@GLIBCXX_3.4 + if (state->mangled_cur[0] == '@') { + MaybeAppend(state, state->mangled_cur); + return true; + } + return false; // Unconsumed suffix. + } + return true; + } + return false; +} +#endif + +// The demangler entry point. +bool Demangle(const char *mangled, char *out, size_t out_size) { +#if defined(GLOG_OS_WINDOWS) +#if defined(HAVE_DBGHELP) + // When built with incremental linking, the Windows debugger + // library provides a more complicated `Symbol->Name` with the + // Incremental Linking Table offset, which looks like + // `@ILT+1105(?func@Foo@@SAXH@Z)`. However, the demangler expects + // only the mangled symbol, `?func@Foo@@SAXH@Z`. Fortunately, the + // mangled symbol is guaranteed not to have parentheses, + // so we search for `(` and extract up to `)`. + // + // Since we may be in a signal handler here, we cannot use `std::string`. + char buffer[1024]; // Big enough for a sane symbol. + const char *lparen = strchr(mangled, '('); + if (lparen) { + // Extract the string `(?...)` + const char *rparen = strchr(lparen, ')'); + size_t length = static_cast(rparen - lparen) - 1; + strncpy(buffer, lparen + 1, length); + buffer[length] = '\0'; + mangled = buffer; + } // Else the symbol wasn't inside a set of parentheses + // We use the ANSI version to ensure the string type is always `char *`. + return UnDecorateSymbolName(mangled, out, out_size, UNDNAME_COMPLETE); +#else + (void)mangled; + (void)out; + (void)out_size; + return false; +#endif +#else + State state; + InitState(&state, mangled, out, out_size); + return ParseTopLevelMangledName(&state) && !state.overflowed; +#endif +} + +_END_GOOGLE_NAMESPACE_ diff --git a/third_party/glog/src/demangle.h b/third_party/glog/src/demangle.h new file mode 100644 index 0000000..f347b98 --- /dev/null +++ b/third_party/glog/src/demangle.h @@ -0,0 +1,85 @@ +// Copyright (c) 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Satoru Takabayashi +// +// An async-signal-safe and thread-safe demangler for Itanium C++ ABI +// (aka G++ V3 ABI). + +// The demangler is implemented to be used in async signal handlers to +// symbolize stack traces. We cannot use libstdc++'s +// abi::__cxa_demangle() in such signal handlers since it's not async +// signal safe (it uses malloc() internally). +// +// Note that this demangler doesn't support full demangling. More +// specifically, it doesn't print types of function parameters and +// types of template arguments. It just skips them. However, it's +// still very useful to extract basic information such as class, +// function, constructor, destructor, and operator names. +// +// See the implementation note in demangle.cc if you are interested. +// +// Example: +// +// | Mangled Name | The Demangler | abi::__cxa_demangle() +// |---------------|---------------|----------------------- +// | _Z1fv | f() | f() +// | _Z1fi | f() | f(int) +// | _Z3foo3bar | foo() | foo(bar) +// | _Z1fIiEvi | f<>() | void f(int) +// | _ZN1N1fE | N::f | N::f +// | _ZN3Foo3BarEv | Foo::Bar() | Foo::Bar() +// | _Zrm1XS_" | operator%() | operator%(X, X) +// | _ZN3FooC1Ev | Foo::Foo() | Foo::Foo() +// | _Z1fSs | f() | f(std::basic_string, +// | | | std::allocator >) +// +// See the unit test for more examples. +// +// Note: we might want to write demanglers for ABIs other than Itanium +// C++ ABI in the future. +// + +#ifndef BASE_DEMANGLE_H_ +#define BASE_DEMANGLE_H_ + +#include "config.h" +#include + +_START_GOOGLE_NAMESPACE_ + +// Demangle "mangled". On success, return true and write the +// demangled symbol name to "out". Otherwise, return false. +// "out" is modified even if demangling is unsuccessful. +bool GLOG_EXPORT Demangle(const char *mangled, char *out, size_t out_size); + +_END_GOOGLE_NAMESPACE_ + +#endif // BASE_DEMANGLE_H_ diff --git a/third_party/glog/src/demangle_unittest.cc b/third_party/glog/src/demangle_unittest.cc new file mode 100644 index 0000000..ddc90b0 --- /dev/null +++ b/third_party/glog/src/demangle_unittest.cc @@ -0,0 +1,170 @@ +// Copyright (c) 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Satoru Takabayashi +// +// Unit tests for functions in demangle.c. + +#include "utilities.h" + +#include +#include +#include +#include +#include "demangle.h" +#include "googletest.h" +#include "config.h" + +#ifdef HAVE_LIB_GFLAGS +#include +using namespace GFLAGS_NAMESPACE; +#endif + +GLOG_DEFINE_bool(demangle_filter, false, + "Run demangle_unittest in filter mode"); + +using namespace std; +using namespace GOOGLE_NAMESPACE; + +// A wrapper function for Demangle() to make the unit test simple. +static const char *DemangleIt(const char * const mangled) { + static char demangled[4096]; + if (Demangle(mangled, demangled, sizeof(demangled))) { + return demangled; + } else { + return mangled; + } +} + +#if defined(GLOG_OS_WINDOWS) + +#if defined(HAVE_DBGHELP) && !defined(NDEBUG) +TEST(Demangle, Windows) { + EXPECT_STREQ( + "public: static void __cdecl Foo::func(int)", + DemangleIt("?func@Foo@@SAXH@Z")); + EXPECT_STREQ( + "public: static void __cdecl Foo::func(int)", + DemangleIt("@ILT+1105(?func@Foo@@SAXH@Z)")); + EXPECT_STREQ( + "int __cdecl foobarArray(int * const)", + DemangleIt("?foobarArray@@YAHQAH@Z")); +} +#endif + +#else + +// Test corner cases of bounary conditions. +TEST(Demangle, CornerCases) { + const size_t size = 10; + char tmp[size] = { 0 }; + const char *demangled = "foobar()"; + const char *mangled = "_Z6foobarv"; + EXPECT_TRUE(Demangle(mangled, tmp, sizeof(tmp))); + // sizeof("foobar()") == size - 1 + EXPECT_STREQ(demangled, tmp); + EXPECT_TRUE(Demangle(mangled, tmp, size - 1)); + EXPECT_STREQ(demangled, tmp); + EXPECT_FALSE(Demangle(mangled, tmp, size - 2)); // Not enough. + EXPECT_FALSE(Demangle(mangled, tmp, 1)); + EXPECT_FALSE(Demangle(mangled, tmp, 0)); + EXPECT_FALSE(Demangle(mangled, NULL, 0)); // Should not cause SEGV. +} + +// Test handling of functions suffixed with .clone.N, which is used by GCC +// 4.5.x, and .constprop.N and .isra.N, which are used by GCC 4.6.x. These +// suffixes are used to indicate functions which have been cloned during +// optimization. We ignore these suffixes. +TEST(Demangle, Clones) { + char tmp[20]; + EXPECT_TRUE(Demangle("_ZL3Foov", tmp, sizeof(tmp))); + EXPECT_STREQ("Foo()", tmp); + EXPECT_TRUE(Demangle("_ZL3Foov.clone.3", tmp, sizeof(tmp))); + EXPECT_STREQ("Foo()", tmp); + EXPECT_TRUE(Demangle("_ZL3Foov.constprop.80", tmp, sizeof(tmp))); + EXPECT_STREQ("Foo()", tmp); + EXPECT_TRUE(Demangle("_ZL3Foov.isra.18", tmp, sizeof(tmp))); + EXPECT_STREQ("Foo()", tmp); + EXPECT_TRUE(Demangle("_ZL3Foov.isra.2.constprop.18", tmp, sizeof(tmp))); + EXPECT_STREQ("Foo()", tmp); + // Invalid (truncated), should not demangle. + EXPECT_FALSE(Demangle("_ZL3Foov.clo", tmp, sizeof(tmp))); + // Invalid (.clone. not followed by number), should not demangle. + EXPECT_FALSE(Demangle("_ZL3Foov.clone.", tmp, sizeof(tmp))); + // Invalid (.clone. followed by non-number), should not demangle. + EXPECT_FALSE(Demangle("_ZL3Foov.clone.foo", tmp, sizeof(tmp))); + // Invalid (.constprop. not followed by number), should not demangle. + EXPECT_FALSE(Demangle("_ZL3Foov.isra.2.constprop.", tmp, sizeof(tmp))); +} + +TEST(Demangle, FromFile) { + string test_file = FLAGS_test_srcdir + "/src/demangle_unittest.txt"; + ifstream f(test_file.c_str()); // The file should exist. + EXPECT_FALSE(f.fail()); + + string line; + while (getline(f, line)) { + // Lines start with '#' are considered as comments. + if (line.empty() || line[0] == '#') { + continue; + } + // Each line should contain a mangled name and a demangled name + // separated by '\t'. Example: "_Z3foo\tfoo" + string::size_type tab_pos = line.find('\t'); + EXPECT_NE(string::npos, tab_pos); + string mangled = line.substr(0, tab_pos); + string demangled = line.substr(tab_pos + 1); + EXPECT_EQ(demangled, DemangleIt(mangled.c_str())); + } +} + +#endif + +int main(int argc, char **argv) { +#ifdef HAVE_LIB_GFLAGS + ParseCommandLineFlags(&argc, &argv, true); +#endif + InitGoogleTest(&argc, argv); + + FLAGS_logtostderr = true; + InitGoogleLogging(argv[0]); + if (FLAGS_demangle_filter) { + // Read from cin and write to cout. + string line; + while (getline(cin, line, '\n')) { + cout << DemangleIt(line.c_str()) << endl; + } + return 0; + } else if (argc > 1) { + cout << DemangleIt(argv[1]) << endl; + return 0; + } else { + return RUN_ALL_TESTS(); + } +} diff --git a/third_party/glog/src/demangle_unittest.sh b/third_party/glog/src/demangle_unittest.sh new file mode 100755 index 0000000..91deee2 --- /dev/null +++ b/third_party/glog/src/demangle_unittest.sh @@ -0,0 +1,95 @@ +#! /bin/sh +# +# Copyright (c) 2006, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# Author: Satoru Takabayashi +# +# Unit tests for demangle.c with a real binary. + +set -e + +die () { + echo $1 + exit 1 +} + +BINDIR=".libs" +LIBGLOG="$BINDIR/libglog.so" + +DEMANGLER="$BINDIR/demangle_unittest" + +if test -e "$DEMANGLER"; then + # We need shared object. + export LD_LIBRARY_PATH=$BINDIR + export DYLD_LIBRARY_PATH=$BINDIR +else + # For windows + DEMANGLER="./demangle_unittest.exe" + if ! test -e "$DEMANGLER"; then + echo "We coundn't find demangle_unittest binary." + exit 1 + fi +fi + +# Extract C++ mangled symbols from libbase.so. +NM_OUTPUT="demangle.nm" +nm "$LIBGLOG" | perl -nle 'print $1 if /\s(_Z\S+$)/' > "$NM_OUTPUT" + +# Check if mangled symbols exist. If there are none, we quit. +# The binary is more likely compiled with GCC 2.95 or something old. +if ! grep --quiet '^_Z' "$NM_OUTPUT"; then + echo "PASS" + exit 0 +fi + +# Demangle the symbols using our demangler. +DM_OUTPUT="demangle.dm" +GLOG_demangle_filter=1 "$DEMANGLER" --demangle_filter < "$NM_OUTPUT" > "$DM_OUTPUT" + +# Calculate the numbers of lines. +NM_LINES=`wc -l "$NM_OUTPUT" | awk '{ print $1 }'` +DM_LINES=`wc -l "$DM_OUTPUT" | awk '{ print $1 }'` + +# Compare the numbers of lines. They must be the same. +if test "$NM_LINES" != "$DM_LINES"; then + die "$NM_OUTPUT and $DM_OUTPUT don't have the same numbers of lines" +fi + +# Check if mangled symbols exist. They must not exist. +if grep --quiet '^_Z' "$DM_OUTPUT"; then + MANGLED=`grep '^_Z' "$DM_OUTPUT" | wc -l | awk '{ print \$1 }'` + echo "Mangled symbols ($MANGLED out of $NM_LINES) found in $DM_OUTPUT:" + grep '^_Z' "$DM_OUTPUT" + die "Mangled symbols ($MANGLED out of $NM_LINES) found in $DM_OUTPUT" +fi + +# All C++ symbols are demangled successfully. +echo "PASS" +exit 0 diff --git a/third_party/glog/src/demangle_unittest.txt b/third_party/glog/src/demangle_unittest.txt new file mode 100644 index 0000000..07e28bc --- /dev/null +++ b/third_party/glog/src/demangle_unittest.txt @@ -0,0 +1,145 @@ +# Test caces for demangle_unittest. Each line consists of a +# tab-separated pair of mangled and demangled symbol names. + +# Constructors and destructors. +_ZN3FooC1Ev Foo::Foo() +_ZN3FooD1Ev Foo::~Foo() +_ZNSoD0Ev std::ostream::~ostream() + +# G++ extensions. +_ZTCN10LogMessage9LogStreamE0_So LogMessage::LogStream +_ZTv0_n12_N10LogMessage9LogStreamD0Ev LogMessage::LogStream::~LogStream() +_ZThn4_N7icu_3_410UnicodeSetD0Ev icu_3_4::UnicodeSet::~UnicodeSet() + +# A bug in g++'s C++ ABI version 2 (-fabi-version=2). +_ZN7NSSInfoI5groupjjXadL_Z10getgrgid_rEELZ19nss_getgrgid_r_nameEEC1Ei NSSInfo<>::NSSInfo() + +# C linkage symbol names. Should keep them untouched. +main main +Demangle Demangle +_ZERO _ZERO + +# Cast operator. +_Zcviv operator int() +_ZN3foocviEv foo::operator int() + +# Versioned symbols. +_Z3Foo@GLIBCXX_3.4 Foo@GLIBCXX_3.4 +_Z3Foo@@GLIBCXX_3.4 Foo@@GLIBCXX_3.4 + +# Abbreviations. +_ZNSaE std::allocator +_ZNSbE std::basic_string +_ZNSdE std::iostream +_ZNSiE std::istream +_ZNSoE std::ostream +_ZNSsE std::string + +# Substitutions. We just replace them with ?. +_ZN3fooS_E foo::? +_ZN3foo3barS0_E foo::bar::? +_ZNcvT_IiEEv operator ?<>() + +# "<< <" case. +_ZlsI3fooE operator<< <> + +# ABI tags. +_Z1AB3barB3foo A +_ZN3fooL3barB5cxx11E foo::bar + +# Random things we found interesting. +_ZN3FooISt6vectorISsSaISsEEEclEv Foo<>::operator()() +_ZTI9Callback1IiE Callback1<> +_ZN7icu_3_47UMemorynwEj icu_3_4::UMemory::operator new() +_ZNSt6vectorIbE9push_backE std::vector<>::push_back +_ZNSt6vectorIbSaIbEE9push_backEb std::vector<>::push_back() +_ZlsRSoRK15PRIVATE_Counter operator<<() +_ZSt6fill_nIPPN9__gnu_cxx15_Hashtable_nodeISt4pairIKPKcjEEEjS8_ET_SA_T0_RKT1_ std::fill_n<>() +_ZZ3FoovE3Bar Foo()::Bar +_ZGVZ7UpTimervE8up_timer UpTimer()::up_timer + +# Test cases from gcc-4.1.0/libstdc++-v3/testsuite/demangle. +# Collected by: +# % grep verify_demangle **/*.cc | perl -nle 'print $1 if /"(_Z.*?)"/' | +# sort | uniq +# +# Note that the following symbols are invalid. +# That's why they are not demangled. +# - _ZNZN1N1fEiE1X1gE +# - _ZNZN1N1fEiE1X1gEv +# - _Z1xINiEE +_Z1fA37_iPS_ f() +_Z1fAszL_ZZNK1N1A1fEvE3foo_0E_i f() +_Z1fI1APS0_PKS0_EvT_T0_T1_PA4_S3_M1CS8_ f<>() +_Z1fI1XENT_1tES2_ f<>() +_Z1fI1XEvPVN1AIT_E1TE f<>() +_Z1fILi1ELc120EEv1AIXplT_cviLd4028ae147ae147aeEEE f<>() +_Z1fILi1ELc120EEv1AIXplT_cviLf3f800000EEE f<>() +_Z1fILi5E1AEvN1CIXqugtT_Li0ELi1ELi2EEE1qE f<>() +_Z1fILi5E1AEvN1CIXstN1T1tEEXszsrS2_1tEE1qE f<>() +_Z1fILi5EEvN1AIXcvimlT_Li22EEE1qE f<>() +_Z1fIiEvi f<>() +_Z1fKPFiiE f() +_Z1fM1AFivEPS0_ f() +_Z1fM1AKFivE f() +_Z1fM1AKFvvE f() +_Z1fPFPA1_ivE f() +_Z1fPFYPFiiEiE f() +_Z1fPFvvEM1SFvvE f() +_Z1fPKM1AFivE f() +_Z1fi f() +_Z1fv f() +_Z1jM1AFivEPS1_ j() +_Z1rM1GFivEMS_KFivES_M1HFivES1_4whatIKS_E5what2IS8_ES3_ r() +_Z1sPA37_iPS0_ s() +_Z1xINiEE _Z1xINiEE +_Z3absILi11EEvv abs<>() +_Z3foo3bar foo() +_Z3foo5Hello5WorldS0_S_ foo() +_Z3fooA30_A_i foo() +_Z3fooIA6_KiEvA9_KT_rVPrS4_ foo<>() +_Z3fooILi2EEvRAplT_Li1E_i foo<>() +_Z3fooIiFvdEiEvv foo<>() +_Z3fooPM2ABi foo() +_Z3fooc foo() +_Z3fooiPiPS_PS0_PS1_PS2_PS3_PS4_PS5_PS6_PS7_PS8_PS9_PSA_PSB_PSC_ foo() +_Z3kooPA28_A30_i koo() +_Z4makeI7FactoryiET_IT0_Ev make<>() +_Z5firstI3DuoEvS0_ first<>() +_Z5firstI3DuoEvT_ first<>() +_Z9hairyfuncM1YKFPVPFrPA2_PM1XKFKPA3_ilEPcEiE hairyfunc() +_ZGVN5libcw24_GLOBAL__N_cbll.cc0ZhUKa23compiler_bug_workaroundISt6vectorINS_13omanip_id_tctINS_5debug32memblk_types_manipulator_data_ctEEESaIS6_EEE3idsE libcw::(anonymous namespace)::compiler_bug_workaround<>::ids +_ZN12libcw_app_ct10add_optionIS_EEvMT_FvPKcES3_cS3_S3_ libcw_app_ct::add_option<>() +_ZN1AIfEcvT_IiEEv A<>::operator ?<>() +_ZN1N1TIiiE2mfES0_IddE N::T<>::mf() +_ZN1N1fE N::f +_ZN1f1fE f::f +_ZN3FooIA4_iE3barE Foo<>::bar +_ZN5Arena5levelE Arena::level +_ZN5StackIiiE5levelE Stack<>::level +_ZN5libcw5debug13cwprint_usingINS_9_private_12GlobalObjectEEENS0_17cwprint_using_tctIT_EERKS5_MS5_KFvRSt7ostreamE libcw::debug::cwprint_using<>() +_ZN6System5Sound4beepEv System::Sound::beep() +_ZNKSt14priority_queueIP27timer_event_request_base_ctSt5dequeIS1_SaIS1_EE13timer_greaterE3topEv std::priority_queue<>::top() +_ZNKSt15_Deque_iteratorIP15memory_block_stRKS1_PS2_EeqERKS5_ std::_Deque_iterator<>::operator==() +_ZNKSt17__normal_iteratorIPK6optionSt6vectorIS0_SaIS0_EEEmiERKS6_ std::__normal_iterator<>::operator-() +_ZNSbIcSt11char_traitsIcEN5libcw5debug27no_alloc_checking_allocatorEE12_S_constructIPcEES6_T_S7_RKS3_ std::basic_string<>::_S_construct<>() +_ZNSt13_Alloc_traitsISbIcSt18string_char_traitsIcEN5libcw5debug9_private_17allocator_adaptorIcSt24__default_alloc_templateILb0ELi327664EELb1EEEENS5_IS9_S7_Lb1EEEE15_S_instancelessE std::_Alloc_traits<>::_S_instanceless +_ZNSt3_In4wardE std::_In::ward +_ZNZN1N1fEiE1X1gE _ZNZN1N1fEiE1X1gE +_ZNZN1N1fEiE1X1gEv _ZNZN1N1fEiE1X1gEv +_ZSt1BISt1DIP1ARKS2_PS3_ES0_IS2_RS2_PS2_ES2_ET0_T_SB_SA_PT1_ std::B<>() +_ZSt5state std::state +_ZTI7a_class a_class +_ZZN1N1fEiE1p N::f()::p +_ZZN1N1fEiEs N::f() +_ZlsRK1XS1_ operator<<() +_ZlsRKU3fooU4bart1XS0_ operator<<() +_ZlsRKU3fooU4bart1XS2_ operator<<() +_ZlsRSoRKSs operator<<() +_ZngILi42EEvN1AIXplT_Li2EEE1TE operator-<>() +_ZplR1XS0_ operator+() +_Zrm1XS_ operator%() + +# Template argument packs can start with I or J. +_Z3addIIiEEvDpT_ add<>() +_Z3addIJiEEvDpT_ add<>() diff --git a/third_party/glog/src/glog/log_severity.h b/third_party/glog/src/glog/log_severity.h new file mode 100644 index 0000000..aa48f53 --- /dev/null +++ b/third_party/glog/src/glog/log_severity.h @@ -0,0 +1,98 @@ +// Copyright (c) 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef BASE_LOG_SEVERITY_H__ +#define BASE_LOG_SEVERITY_H__ + +// The recommended semantics of the log levels are as follows: +// +// INFO: +// Use for state changes or other major events, or to aid debugging. +// WARNING: +// Use for undesired but relatively expected events, which may indicate a +// problem +// ERROR: +// Use for undesired and unexpected events that the program can recover from. +// All ERRORs should be actionable - it should be appropriate to file a bug +// whenever an ERROR occurs in production. +// FATAL: +// Use for undesired and unexpected events that the program cannot recover +// from. + +// Variables of type LogSeverity are widely taken to lie in the range +// [0, NUM_SEVERITIES-1]. Be careful to preserve this assumption if +// you ever need to change their values or add a new severity. +typedef int LogSeverity; + +const int GLOG_INFO = 0, GLOG_WARNING = 1, GLOG_ERROR = 2, GLOG_FATAL = 3, + NUM_SEVERITIES = 4; +#ifndef GLOG_NO_ABBREVIATED_SEVERITIES +# ifdef ERROR +# error ERROR macro is defined. Define GLOG_NO_ABBREVIATED_SEVERITIES before including logging.h. See the document for detail. +# endif +const int INFO = GLOG_INFO, WARNING = GLOG_WARNING, + ERROR = GLOG_ERROR, FATAL = GLOG_FATAL; +#endif + +// DFATAL is FATAL in debug mode, ERROR in normal mode +#ifdef NDEBUG +#define DFATAL_LEVEL ERROR +#else +#define DFATAL_LEVEL FATAL +#endif + +extern GLOG_EXPORT const char* const LogSeverityNames[NUM_SEVERITIES]; + +// NDEBUG usage helpers related to (RAW_)DCHECK: +// +// DEBUG_MODE is for small !NDEBUG uses like +// if (DEBUG_MODE) foo.CheckThatFoo(); +// instead of substantially more verbose +// #ifndef NDEBUG +// foo.CheckThatFoo(); +// #endif +// +// IF_DEBUG_MODE is for small !NDEBUG uses like +// IF_DEBUG_MODE( string error; ) +// DCHECK(Foo(&error)) << error; +// instead of substantially more verbose +// #ifndef NDEBUG +// string error; +// DCHECK(Foo(&error)) << error; +// #endif +// +#ifdef NDEBUG +enum { DEBUG_MODE = 0 }; +#define IF_DEBUG_MODE(x) +#else +enum { DEBUG_MODE = 1 }; +#define IF_DEBUG_MODE(x) x +#endif + +#endif // BASE_LOG_SEVERITY_H__ diff --git a/third_party/glog/src/glog/logging.h.in b/third_party/glog/src/glog/logging.h.in new file mode 100644 index 0000000..95a573b --- /dev/null +++ b/third_party/glog/src/glog/logging.h.in @@ -0,0 +1,2002 @@ +// Copyright (c) 2022, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Ray Sidney +// +// This file contains #include information about logging-related stuff. +// Pretty much everybody needs to #include this file so that they can +// log various happenings. +// +#ifndef GLOG_LOGGING_H +#define GLOG_LOGGING_H + +#if @ac_cv_cxx11_chrono@ && __cplusplus >= 201103L +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if @ac_cv_have_unistd_h@ +# include +#endif +#include + +#if defined(_MSC_VER) +#define GLOG_MSVC_PUSH_DISABLE_WARNING(n) __pragma(warning(push)) \ + __pragma(warning(disable:n)) +#define GLOG_MSVC_POP_WARNING() __pragma(warning(pop)) +#else +#define GLOG_MSVC_PUSH_DISABLE_WARNING(n) +#define GLOG_MSVC_POP_WARNING() +#endif + +#include + +#if @ac_cv_have_glog_export@ +#include +#endif + +// We care a lot about number of bits things take up. Unfortunately, +// systems define their bit-specific ints in a lot of different ways. +// We use our own way, and have a typedef to get there. +// Note: these commands below may look like "#if 1" or "#if 0", but +// that's because they were constructed that way at ./configure time. +// Look at logging.h.in to see how they're calculated (based on your config). +#if @ac_cv_have_stdint_h@ +#include // the normal place uint16_t is defined +#endif +#if @ac_cv_have_systypes_h@ +#include // the normal place u_int16_t is defined +#endif +#if @ac_cv_have_inttypes_h@ +#include // a third place for uint16_t or u_int16_t +#endif + +#if @ac_cv_have_libgflags@ +#include +#endif + +#if @ac_cv_cxx11_atomic@ && __cplusplus >= 201103L +#include +#elif defined(GLOG_OS_WINDOWS) +#include +#endif + +@ac_google_start_namespace@ + +#if @ac_cv_have_uint16_t@ // the C99 format +typedef int32_t int32; +typedef uint32_t uint32; +typedef int64_t int64; +typedef uint64_t uint64; +#elif @ac_cv_have_u_int16_t@ // the BSD format +typedef int32_t int32; +typedef u_int32_t uint32; +typedef int64_t int64; +typedef u_int64_t uint64; +#elif @ac_cv_have___uint16@ // the windows (vc7) format +typedef __int32 int32; +typedef unsigned __int32 uint32; +typedef __int64 int64; +typedef unsigned __int64 uint64; +#else +#error Do not know how to define a 32-bit integer quantity on your system +#endif + +typedef double WallTime; + +struct GLOG_EXPORT LogMessageTime { + LogMessageTime(); + LogMessageTime(std::tm t); + LogMessageTime(std::time_t timestamp, WallTime now); + + const time_t& timestamp() const { return timestamp_; } + const int& sec() const { return time_struct_.tm_sec; } + const int32_t& usec() const { return usecs_; } + const int&(min)() const { return time_struct_.tm_min; } + const int& hour() const { return time_struct_.tm_hour; } + const int& day() const { return time_struct_.tm_mday; } + const int& month() const { return time_struct_.tm_mon; } + const int& year() const { return time_struct_.tm_year; } + const int& dayOfWeek() const { return time_struct_.tm_wday; } + const int& dayInYear() const { return time_struct_.tm_yday; } + const int& dst() const { return time_struct_.tm_isdst; } + const long int& gmtoff() const { return gmtoffset_; } + const std::tm& tm() const { return time_struct_; } + + private: + void init(const std::tm& t, std::time_t timestamp, WallTime now); + std::tm time_struct_; // Time of creation of LogMessage + time_t timestamp_; // Time of creation of LogMessage in seconds + int32_t usecs_; // Time of creation of LogMessage - microseconds part + long int gmtoffset_; + + void CalcGmtOffset(); +}; + +#ifdef GLOG_CUSTOM_PREFIX_SUPPORT +struct LogMessageInfo { + explicit LogMessageInfo(const char* const severity_, + const char* const filename_, + const int& line_number_, + const int& thread_id_, + const LogMessageTime& time_): + severity(severity_), filename(filename_), line_number(line_number_), + thread_id(thread_id_), time(time_) + {} + + const char* const severity; + const char* const filename; + const int &line_number; + const int &thread_id; + const LogMessageTime& time; +}; + +typedef void(*CustomPrefixCallback)(std::ostream& s, const LogMessageInfo& l, void* data); + +#endif + +@ac_google_end_namespace@ + + +// The global value of GOOGLE_STRIP_LOG. All the messages logged to +// LOG(XXX) with severity less than GOOGLE_STRIP_LOG will not be displayed. +// If it can be determined at compile time that the message will not be +// printed, the statement will be compiled out. +// +// Example: to strip out all INFO and WARNING messages, use the value +// of 2 below. To make an exception for WARNING messages from a single +// file, add "#define GOOGLE_STRIP_LOG 1" to that file _before_ including +// base/logging.h +#ifndef GOOGLE_STRIP_LOG +#define GOOGLE_STRIP_LOG 0 +#endif + +// GCC can be told that a certain branch is not likely to be taken (for +// instance, a CHECK failure), and use that information in static analysis. +// Giving it this information can help it optimize for the common case in +// the absence of better information (ie. -fprofile-arcs). +// +#ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN +#if @ac_cv_have___builtin_expect@ +#define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) (__builtin_expect(x, 0)) +#else +#define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) x +#endif +#endif + +#ifndef GOOGLE_PREDICT_FALSE +#if @ac_cv_have___builtin_expect@ +#define GOOGLE_PREDICT_FALSE(x) (__builtin_expect(x, 0)) +#else +#define GOOGLE_PREDICT_FALSE(x) x +#endif +#endif + +#ifndef GOOGLE_PREDICT_TRUE +#if @ac_cv_have___builtin_expect@ +#define GOOGLE_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1)) +#else +#define GOOGLE_PREDICT_TRUE(x) x +#endif +#endif + + +// Make a bunch of macros for logging. The way to log things is to stream +// things to LOG(). E.g., +// +// LOG(INFO) << "Found " << num_cookies << " cookies"; +// +// You can capture log messages in a string, rather than reporting them +// immediately: +// +// vector errors; +// LOG_STRING(ERROR, &errors) << "Couldn't parse cookie #" << cookie_num; +// +// This pushes back the new error onto 'errors'; if given a NULL pointer, +// it reports the error via LOG(ERROR). +// +// You can also do conditional logging: +// +// LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies"; +// +// You can also do occasional logging (log every n'th occurrence of an +// event): +// +// LOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie"; +// +// The above will cause log messages to be output on the 1st, 11th, 21st, ... +// times it is executed. Note that the special google::COUNTER value is used +// to identify which repetition is happening. +// +// You can also do occasional conditional logging (log every n'th +// occurrence of an event, when condition is satisfied): +// +// LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << google::COUNTER +// << "th big cookie"; +// +// You can log messages the first N times your code executes a line. E.g. +// +// LOG_FIRST_N(INFO, 20) << "Got the " << google::COUNTER << "th cookie"; +// +// Outputs log messages for the first 20 times it is executed. +// +// Analogous SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macros are available. +// These log to syslog as well as to the normal logs. If you use these at +// all, you need to be aware that syslog can drastically reduce performance, +// especially if it is configured for remote logging! Don't use these +// unless you fully understand this and have a concrete need to use them. +// Even then, try to minimize your use of them. +// +// There are also "debug mode" logging macros like the ones above: +// +// DLOG(INFO) << "Found cookies"; +// +// DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies"; +// +// DLOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie"; +// +// All "debug mode" logging is compiled away to nothing for non-debug mode +// compiles. +// +// We also have +// +// LOG_ASSERT(assertion); +// DLOG_ASSERT(assertion); +// +// which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion; +// +// There are "verbose level" logging macros. They look like +// +// VLOG(1) << "I'm printed when you run the program with --v=1 or more"; +// VLOG(2) << "I'm printed when you run the program with --v=2 or more"; +// +// These always log at the INFO log level (when they log at all). +// The verbose logging can also be turned on module-by-module. For instance, +// --vmodule=mapreduce=2,file=1,gfs*=3 --v=0 +// will cause: +// a. VLOG(2) and lower messages to be printed from mapreduce.{h,cc} +// b. VLOG(1) and lower messages to be printed from file.{h,cc} +// c. VLOG(3) and lower messages to be printed from files prefixed with "gfs" +// d. VLOG(0) and lower messages to be printed from elsewhere +// +// The wildcarding functionality shown by (c) supports both '*' (match +// 0 or more characters) and '?' (match any single character) wildcards. +// +// There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as +// +// if (VLOG_IS_ON(2)) { +// // do some logging preparation and logging +// // that can't be accomplished with just VLOG(2) << ...; +// } +// +// There are also VLOG_IF, VLOG_EVERY_N and VLOG_IF_EVERY_N "verbose level" +// condition macros for sample cases, when some extra computation and +// preparation for logs is not needed. +// VLOG_IF(1, (size > 1024)) +// << "I'm printed when size is more than 1024 and when you run the " +// "program with --v=1 or more"; +// VLOG_EVERY_N(1, 10) +// << "I'm printed every 10th occurrence, and when you run the program " +// "with --v=1 or more. Present occurence is " << google::COUNTER; +// VLOG_IF_EVERY_N(1, (size > 1024), 10) +// << "I'm printed on every 10th occurence of case when size is more " +// " than 1024, when you run the program with --v=1 or more. "; +// "Present occurence is " << google::COUNTER; +// +// The supported severity levels for macros that allow you to specify one +// are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL. +// Note that messages of a given severity are logged not only in the +// logfile for that severity, but also in all logfiles of lower severity. +// E.g., a message of severity FATAL will be logged to the logfiles of +// severity FATAL, ERROR, WARNING, and INFO. +// +// There is also the special severity of DFATAL, which logs FATAL in +// debug mode, ERROR in normal mode. +// +// Very important: logging a message at the FATAL severity level causes +// the program to terminate (after the message is logged). +// +// Unless otherwise specified, logs will be written to the filename +// "...log..", followed +// by the date, time, and pid (you can't prevent the date, time, and pid +// from being in the filename). +// +// The logging code takes two flags: +// --v=# set the verbose level +// --logtostderr log all the messages to stderr instead of to logfiles + +// LOG LINE PREFIX FORMAT +// +// Log lines have this form: +// +// Lyyyymmdd hh:mm:ss.uuuuuu threadid file:line] msg... +// +// where the fields are defined as follows: +// +// L A single character, representing the log level +// (eg 'I' for INFO) +// yyyy The year +// mm The month (zero padded; ie May is '05') +// dd The day (zero padded) +// hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds +// threadid The space-padded thread ID as returned by GetTID() +// (this matches the PID on Linux) +// file The file name +// line The line number +// msg The user-supplied message +// +// Example: +// +// I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog +// I1103 11:57:31.739403 24395 google.cc:2342] Process id 24395 +// +// NOTE: although the microseconds are useful for comparing events on +// a single machine, clocks on different machines may not be well +// synchronized. Hence, use caution when comparing the low bits of +// timestamps from different machines. + +#pragma push_macro("DECLARE_VARIABLE") +#pragma push_macro("DECLARE_bool") +#pragma push_macro("DECLARE_string") +#pragma push_macro("DECLARE_int32") +#pragma push_macro("DECLARE_uint32") + +#ifdef DECLARE_VARIABLE +#undef DECLARE_VARIABLE +#endif + +#ifdef DECLARE_bool +#undef DECLARE_bool +#endif + +#ifdef DECLARE_string +#undef DECLARE_string +#endif + +#ifdef DECLARE_int32 +#undef DECLARE_int32 +#endif + +#ifdef DECLARE_uint32 +#undef DECLARE_uint32 +#endif + +#ifndef DECLARE_VARIABLE +#define DECLARE_VARIABLE(type, shorttype, name, tn) \ + namespace fL##shorttype { \ + extern GLOG_EXPORT type FLAGS_##name; \ + } \ + using fL##shorttype::FLAGS_##name + +// bool specialization +#define DECLARE_bool(name) \ + DECLARE_VARIABLE(bool, B, name, bool) + +// int32 specialization +#define DECLARE_int32(name) \ + DECLARE_VARIABLE(@ac_google_namespace@::int32, I, name, int32) + +#if !defined(DECLARE_uint32) +// uint32 specialization +#define DECLARE_uint32(name) \ + DECLARE_VARIABLE(@ac_google_namespace@::uint32, U, name, uint32) +#endif // !defined(DECLARE_uint32) && !(@ac_cv_have_libgflags@) + +// Special case for string, because we have to specify the namespace +// std::string, which doesn't play nicely with our FLAG__namespace hackery. +#define DECLARE_string(name) \ + namespace fLS { \ + extern GLOG_EXPORT std::string& FLAGS_##name; \ + } \ + using fLS::FLAGS_##name +#endif + +// Set whether appending a timestamp to the log file name +DECLARE_bool(timestamp_in_logfile_name); + +// Set whether log messages go to stdout instead of logfiles +DECLARE_bool(logtostdout); + +// Set color messages logged to stdout (if supported by terminal). +DECLARE_bool(colorlogtostdout); + +// Set whether log messages go to stderr instead of logfiles +DECLARE_bool(logtostderr); + +// Set whether log messages go to stderr in addition to logfiles. +DECLARE_bool(alsologtostderr); + +// Set color messages logged to stderr (if supported by terminal). +DECLARE_bool(colorlogtostderr); + +// Log messages at a level >= this flag are automatically sent to +// stderr in addition to log files. +DECLARE_int32(stderrthreshold); + +// Set whether the log prefix should be prepended to each line of output. +DECLARE_bool(log_prefix); + +// Set whether the year should be included in the log prefix. +DECLARE_bool(log_year_in_prefix); + +// Log messages at a level <= this flag are buffered. +// Log messages at a higher level are flushed immediately. +DECLARE_int32(logbuflevel); + +// Sets the maximum number of seconds which logs may be buffered for. +DECLARE_int32(logbufsecs); + +// Log suppression level: messages logged at a lower level than this +// are suppressed. +DECLARE_int32(minloglevel); + +// If specified, logfiles are written into this directory instead of the +// default logging directory. +DECLARE_string(log_dir); + +// Set the log file mode. +DECLARE_int32(logfile_mode); + +// Sets the path of the directory into which to put additional links +// to the log files. +DECLARE_string(log_link); + +DECLARE_int32(v); // in vlog_is_on.cc + +DECLARE_string(vmodule); // also in vlog_is_on.cc + +// Sets the maximum log file size (in MB). +DECLARE_uint32(max_log_size); + +// Sets whether to avoid logging to the disk if the disk is full. +DECLARE_bool(stop_logging_if_full_disk); + +// Use UTC time for logging +DECLARE_bool(log_utc_time); + +// Log messages below the GOOGLE_STRIP_LOG level will be compiled away for +// security reasons. See LOG(severtiy) below. + +// A few definitions of macros that don't generate much code. Since +// LOG(INFO) and its ilk are used all over our code, it's +// better to have compact code for these operations. + +#if GOOGLE_STRIP_LOG == 0 +#define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__) +#define LOG_TO_STRING_INFO(message) @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, message) +#else +#define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::NullStream() +#define LOG_TO_STRING_INFO(message) @ac_google_namespace@::NullStream() +#endif + +#if GOOGLE_STRIP_LOG <= 1 +#define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING) +#define LOG_TO_STRING_WARNING(message) @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, message) +#else +#define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::NullStream() +#define LOG_TO_STRING_WARNING(message) @ac_google_namespace@::NullStream() +#endif + +#if GOOGLE_STRIP_LOG <= 2 +#define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR) +#define LOG_TO_STRING_ERROR(message) @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, message) +#else +#define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::NullStream() +#define LOG_TO_STRING_ERROR(message) @ac_google_namespace@::NullStream() +#endif + +#if GOOGLE_STRIP_LOG <= 3 +#define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::LogMessageFatal( \ + __FILE__, __LINE__) +#define LOG_TO_STRING_FATAL(message) @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, message) +#else +#define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::NullStreamFatal() +#define LOG_TO_STRING_FATAL(message) @ac_google_namespace@::NullStreamFatal() +#endif + +#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON) +#define DCHECK_IS_ON() 0 +#else +#define DCHECK_IS_ON() 1 +#endif + +// For DFATAL, we want to use LogMessage (as opposed to +// LogMessageFatal), to be consistent with the original behavior. +#if !DCHECK_IS_ON() +#define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR +#elif GOOGLE_STRIP_LOG <= 3 +#define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL) +#else +#define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::NullStreamFatal() +#endif + +#define GOOGLE_LOG_INFO(counter) @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, counter, &@ac_google_namespace@::LogMessage::SendToLog) +#define SYSLOG_INFO(counter) \ + @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, counter, \ + &@ac_google_namespace@::LogMessage::SendToSyslogAndLog) +#define GOOGLE_LOG_WARNING(counter) \ + @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, counter, \ + &@ac_google_namespace@::LogMessage::SendToLog) +#define SYSLOG_WARNING(counter) \ + @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, counter, \ + &@ac_google_namespace@::LogMessage::SendToSyslogAndLog) +#define GOOGLE_LOG_ERROR(counter) \ + @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, counter, \ + &@ac_google_namespace@::LogMessage::SendToLog) +#define SYSLOG_ERROR(counter) \ + @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, counter, \ + &@ac_google_namespace@::LogMessage::SendToSyslogAndLog) +#define GOOGLE_LOG_FATAL(counter) \ + @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, counter, \ + &@ac_google_namespace@::LogMessage::SendToLog) +#define SYSLOG_FATAL(counter) \ + @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, counter, \ + &@ac_google_namespace@::LogMessage::SendToSyslogAndLog) +#define GOOGLE_LOG_DFATAL(counter) \ + @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \ + &@ac_google_namespace@::LogMessage::SendToLog) +#define SYSLOG_DFATAL(counter) \ + @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \ + &@ac_google_namespace@::LogMessage::SendToSyslogAndLog) + +#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(__CYGWIN32__) +// A very useful logging macro to log windows errors: +#define LOG_SYSRESULT(result) \ + if (FAILED(HRESULT_FROM_WIN32(result))) { \ + LPSTR message = NULL; \ + LPSTR msg = reinterpret_cast(&message); \ + DWORD message_length = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | \ + FORMAT_MESSAGE_FROM_SYSTEM, \ + 0, result, 0, msg, 100, NULL); \ + if (message_length > 0) { \ + @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, 0, \ + &@ac_google_namespace@::LogMessage::SendToLog).stream() \ + << reinterpret_cast(message); \ + LocalFree(message); \ + } \ + } +#endif + +// We use the preprocessor's merging operator, "##", so that, e.g., +// LOG(INFO) becomes the token GOOGLE_LOG_INFO. There's some funny +// subtle difference between ostream member streaming functions (e.g., +// ostream::operator<<(int) and ostream non-member streaming functions +// (e.g., ::operator<<(ostream&, string&): it turns out that it's +// impossible to stream something like a string directly to an unnamed +// ostream. We employ a neat hack by calling the stream() member +// function of LogMessage which seems to avoid the problem. +#define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream() +#define SYSLOG(severity) SYSLOG_ ## severity(0).stream() + +@ac_google_start_namespace@ + +// They need the definitions of integer types. +#include +#include + +// Initialize google's logging library. You will see the program name +// specified by argv0 in log outputs. +GLOG_EXPORT void InitGoogleLogging(const char* argv0); + +#ifdef GLOG_CUSTOM_PREFIX_SUPPORT +GLOG_EXPORT void InitGoogleLogging(const char* argv0, + CustomPrefixCallback prefix_callback, + void* prefix_callback_data = NULL); +#endif + +// Check if google's logging library has been initialized. +GLOG_EXPORT bool IsGoogleLoggingInitialized(); + +// Shutdown google's logging library. +GLOG_EXPORT void ShutdownGoogleLogging(); + +#if defined(__GNUC__) +typedef void (*logging_fail_func_t)() __attribute__((noreturn)); +#else +typedef void (*logging_fail_func_t)(); +#endif + +// Install a function which will be called after LOG(FATAL). +GLOG_EXPORT void InstallFailureFunction(logging_fail_func_t fail_func); + +// Enable/Disable old log cleaner. +GLOG_EXPORT void EnableLogCleaner(unsigned int overdue_days); +GLOG_EXPORT void DisableLogCleaner(); +GLOG_EXPORT void SetApplicationFingerprint(const std::string& fingerprint); + +class LogSink; // defined below + +// If a non-NULL sink pointer is given, we push this message to that sink. +// For LOG_TO_SINK we then do normal LOG(severity) logging as well. +// This is useful for capturing messages and passing/storing them +// somewhere more specific than the global log of the process. +// Argument types: +// LogSink* sink; +// LogSeverity severity; +// The cast is to disambiguate NULL arguments. +#define LOG_TO_SINK(sink, severity) \ + @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, \ + @ac_google_namespace@::GLOG_ ## severity, \ + static_cast<@ac_google_namespace@::LogSink*>(sink), true).stream() +#define LOG_TO_SINK_BUT_NOT_TO_LOGFILE(sink, severity) \ + @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, \ + @ac_google_namespace@::GLOG_ ## severity, \ + static_cast<@ac_google_namespace@::LogSink*>(sink), false).stream() + +// If a non-NULL string pointer is given, we write this message to that string. +// We then do normal LOG(severity) logging as well. +// This is useful for capturing messages and storing them somewhere more +// specific than the global log of the process. +// Argument types: +// string* message; +// LogSeverity severity; +// The cast is to disambiguate NULL arguments. +// NOTE: LOG(severity) expands to LogMessage().stream() for the specified +// severity. +#define LOG_TO_STRING(severity, message) \ + LOG_TO_STRING_##severity(static_cast(message)).stream() + +// If a non-NULL pointer is given, we push the message onto the end +// of a vector of strings; otherwise, we report it with LOG(severity). +// This is handy for capturing messages and perhaps passing them back +// to the caller, rather than reporting them immediately. +// Argument types: +// LogSeverity severity; +// vector *outvec; +// The cast is to disambiguate NULL arguments. +#define LOG_STRING(severity, outvec) \ + LOG_TO_STRING_##severity(static_cast*>(outvec)).stream() + +#define LOG_IF(severity, condition) \ + static_cast(0), \ + !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity) +#define SYSLOG_IF(severity, condition) \ + static_cast(0), \ + !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & SYSLOG(severity) + +#define LOG_ASSERT(condition) \ + LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition +#define SYSLOG_ASSERT(condition) \ + SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition + +// CHECK dies with a fatal error if condition is not true. It is *not* +// controlled by DCHECK_IS_ON(), so the check will be executed regardless of +// compilation mode. Therefore, it is safe to do things like: +// CHECK(fp->Write(x) == 4) +#define CHECK(condition) \ + LOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \ + << "Check failed: " #condition " " + +// A container for a string pointer which can be evaluated to a bool - +// true iff the pointer is NULL. +struct CheckOpString { + CheckOpString(std::string* str) : str_(str) { } + // No destructor: if str_ is non-NULL, we're about to LOG(FATAL), + // so there's no point in cleaning up str_. + operator bool() const { + return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != NULL); + } + std::string* str_; +}; + +// Function is overloaded for integral types to allow static const +// integrals declared in classes and not defined to be used as arguments to +// CHECK* macros. It's not encouraged though. +template +inline const T& GetReferenceableValue(const T& t) { return t; } +inline char GetReferenceableValue(char t) { return t; } +inline unsigned char GetReferenceableValue(unsigned char t) { return t; } +inline signed char GetReferenceableValue(signed char t) { return t; } +inline short GetReferenceableValue(short t) { return t; } +inline unsigned short GetReferenceableValue(unsigned short t) { return t; } +inline int GetReferenceableValue(int t) { return t; } +inline unsigned int GetReferenceableValue(unsigned int t) { return t; } +inline long GetReferenceableValue(long t) { return t; } +inline unsigned long GetReferenceableValue(unsigned long t) { return t; } +#if __cplusplus >= 201103L +inline long long GetReferenceableValue(long long t) { return t; } +inline unsigned long long GetReferenceableValue(unsigned long long t) { + return t; +} +#endif + +// This is a dummy class to define the following operator. +struct DummyClassToDefineOperator {}; + +@ac_google_end_namespace@ + +// Define global operator<< to declare using ::operator<<. +// This declaration will allow use to use CHECK macros for user +// defined classes which have operator<< (e.g., stl_logging.h). +inline std::ostream& operator<<( + std::ostream& out, const google::DummyClassToDefineOperator&) { + return out; +} + +@ac_google_start_namespace@ + +// This formats a value for a failing CHECK_XX statement. Ordinarily, +// it uses the definition for operator<<, with a few special cases below. +template +inline void MakeCheckOpValueString(std::ostream* os, const T& v) { + (*os) << v; +} + +// Overrides for char types provide readable values for unprintable +// characters. +template <> GLOG_EXPORT +void MakeCheckOpValueString(std::ostream* os, const char& v); +template <> GLOG_EXPORT +void MakeCheckOpValueString(std::ostream* os, const signed char& v); +template <> GLOG_EXPORT +void MakeCheckOpValueString(std::ostream* os, const unsigned char& v); + +// This is required because nullptr is only present in c++ 11 and later. +#if @ac_cv_cxx11_nullptr_t@ && __cplusplus >= 201103L +// Provide printable value for nullptr_t +template <> GLOG_EXPORT +void MakeCheckOpValueString(std::ostream* os, const std::nullptr_t& v); +#endif + +// Build the error message string. Specify no inlining for code size. +template +std::string* MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext) + @ac_cv___attribute___noinline@; + +namespace base { +namespace internal { + +// If "s" is less than base_logging::INFO, returns base_logging::INFO. +// If "s" is greater than base_logging::FATAL, returns +// base_logging::ERROR. Otherwise, returns "s". +LogSeverity NormalizeSeverity(LogSeverity s); + +} // namespace internal + +// A helper class for formatting "expr (V1 vs. V2)" in a CHECK_XX +// statement. See MakeCheckOpString for sample usage. Other +// approaches were considered: use of a template method (e.g., +// base::BuildCheckOpString(exprtext, base::Print, &v1, +// base::Print, &v2), however this approach has complications +// related to volatile arguments and function-pointer arguments). +class GLOG_EXPORT CheckOpMessageBuilder { + public: + // Inserts "exprtext" and " (" to the stream. + explicit CheckOpMessageBuilder(const char *exprtext); + // Deletes "stream_". + ~CheckOpMessageBuilder(); + // For inserting the first variable. + std::ostream* ForVar1() { return stream_; } + // For inserting the second variable (adds an intermediate " vs. "). + std::ostream* ForVar2(); + // Get the result (inserts the closing ")"). + std::string* NewString(); + + private: + std::ostringstream *stream_; +}; + +} // namespace base + +template +std::string* MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext) { + base::CheckOpMessageBuilder comb(exprtext); + MakeCheckOpValueString(comb.ForVar1(), v1); + MakeCheckOpValueString(comb.ForVar2(), v2); + return comb.NewString(); +} + +// Helper functions for CHECK_OP macro. +// The (int, int) specialization works around the issue that the compiler +// will not instantiate the template version of the function on values of +// unnamed enum type - see comment below. +#define DEFINE_CHECK_OP_IMPL(name, op) \ + template \ + inline std::string* name##Impl(const T1& v1, const T2& v2, \ + const char* exprtext) { \ + if (GOOGLE_PREDICT_TRUE(v1 op v2)) return NULL; \ + else return MakeCheckOpString(v1, v2, exprtext); \ + } \ + inline std::string* name##Impl(int v1, int v2, const char* exprtext) { \ + return name##Impl(v1, v2, exprtext); \ + } + +// We use the full name Check_EQ, Check_NE, etc. in case the file including +// base/logging.h provides its own #defines for the simpler names EQ, NE, etc. +// This happens if, for example, those are used as token names in a +// yacc grammar. +DEFINE_CHECK_OP_IMPL(Check_EQ, ==) // Compilation error with CHECK_EQ(NULL, x)? +DEFINE_CHECK_OP_IMPL(Check_NE, !=) // Use CHECK(x == NULL) instead. +DEFINE_CHECK_OP_IMPL(Check_LE, <=) +DEFINE_CHECK_OP_IMPL(Check_LT, < ) +DEFINE_CHECK_OP_IMPL(Check_GE, >=) +DEFINE_CHECK_OP_IMPL(Check_GT, > ) +#undef DEFINE_CHECK_OP_IMPL + +// Helper macro for binary operators. +// Don't use this macro directly in your code, use CHECK_EQ et al below. + +#if defined(STATIC_ANALYSIS) +// Only for static analysis tool to know that it is equivalent to assert +#define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1) op (val2)) +#elif DCHECK_IS_ON() +// In debug mode, avoid constructing CheckOpStrings if possible, +// to reduce the overhead of CHECK statments by 2x. +// Real DCHECK-heavy tests have seen 1.5x speedups. + +// The meaning of "string" might be different between now and +// when this macro gets invoked (e.g., if someone is experimenting +// with other string implementations that get defined after this +// file is included). Save the current meaning now and use it +// in the macro. +typedef std::string _Check_string; +#define CHECK_OP_LOG(name, op, val1, val2, log) \ + while (@ac_google_namespace@::_Check_string* _result = \ + @ac_google_namespace@::Check##name##Impl( \ + @ac_google_namespace@::GetReferenceableValue(val1), \ + @ac_google_namespace@::GetReferenceableValue(val2), \ + #val1 " " #op " " #val2)) \ + log(__FILE__, __LINE__, \ + @ac_google_namespace@::CheckOpString(_result)).stream() +#else +// In optimized mode, use CheckOpString to hint to compiler that +// the while condition is unlikely. +#define CHECK_OP_LOG(name, op, val1, val2, log) \ + while (@ac_google_namespace@::CheckOpString _result = \ + @ac_google_namespace@::Check##name##Impl( \ + @ac_google_namespace@::GetReferenceableValue(val1), \ + @ac_google_namespace@::GetReferenceableValue(val2), \ + #val1 " " #op " " #val2)) \ + log(__FILE__, __LINE__, _result).stream() +#endif // STATIC_ANALYSIS, DCHECK_IS_ON() + +#if GOOGLE_STRIP_LOG <= 3 +#define CHECK_OP(name, op, val1, val2) \ + CHECK_OP_LOG(name, op, val1, val2, @ac_google_namespace@::LogMessageFatal) +#else +#define CHECK_OP(name, op, val1, val2) \ + CHECK_OP_LOG(name, op, val1, val2, @ac_google_namespace@::NullStreamFatal) +#endif // STRIP_LOG <= 3 + +// Equality/Inequality checks - compare two values, and log a FATAL message +// including the two values when the result is not as expected. The values +// must have operator<<(ostream, ...) defined. +// +// You may append to the error message like so: +// CHECK_NE(1, 2) << ": The world must be ending!"; +// +// We are very careful to ensure that each argument is evaluated exactly +// once, and that anything which is legal to pass as a function argument is +// legal here. In particular, the arguments may be temporary expressions +// which will end up being destroyed at the end of the apparent statement, +// for example: +// CHECK_EQ(string("abc")[1], 'b'); +// +// WARNING: These don't compile correctly if one of the arguments is a pointer +// and the other is NULL. To work around this, simply static_cast NULL to the +// type of the desired pointer. + +#define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2) +#define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2) +#define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2) +#define CHECK_LT(val1, val2) CHECK_OP(_LT, < , val1, val2) +#define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2) +#define CHECK_GT(val1, val2) CHECK_OP(_GT, > , val1, val2) + +// Check that the input is non NULL. This very useful in constructor +// initializer lists. + +#define CHECK_NOTNULL(val) \ + @ac_google_namespace@::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val)) + +// Helper functions for string comparisons. +// To avoid bloat, the definitions are in logging.cc. +#define DECLARE_CHECK_STROP_IMPL(func, expected) \ + GLOG_EXPORT std::string* Check##func##expected##Impl( \ + const char* s1, const char* s2, const char* names); +DECLARE_CHECK_STROP_IMPL(strcmp, true) +DECLARE_CHECK_STROP_IMPL(strcmp, false) +DECLARE_CHECK_STROP_IMPL(strcasecmp, true) +DECLARE_CHECK_STROP_IMPL(strcasecmp, false) +#undef DECLARE_CHECK_STROP_IMPL + +// Helper macro for string comparisons. +// Don't use this macro directly in your code, use CHECK_STREQ et al below. +#define CHECK_STROP(func, op, expected, s1, s2) \ + while (@ac_google_namespace@::CheckOpString _result = \ + @ac_google_namespace@::Check##func##expected##Impl((s1), (s2), \ + #s1 " " #op " " #s2)) \ + LOG(FATAL) << *_result.str_ + + +// String (char*) equality/inequality checks. +// CASE versions are case-insensitive. +// +// Note that "s1" and "s2" may be temporary strings which are destroyed +// by the compiler at the end of the current "full expression" +// (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())). + +#define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2) +#define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2) +#define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2) +#define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2) + +#define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0]))) +#define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0]))) + +#define CHECK_DOUBLE_EQ(val1, val2) \ + do { \ + CHECK_LE((val1), (val2)+0.000000000000001L); \ + CHECK_GE((val1), (val2)-0.000000000000001L); \ + } while (0) + +#define CHECK_NEAR(val1, val2, margin) \ + do { \ + CHECK_LE((val1), (val2)+(margin)); \ + CHECK_GE((val1), (val2)-(margin)); \ + } while (0) + +// perror()..googly style! +// +// PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and +// CHECK equivalents with the addition that they postpend a description +// of the current state of errno to their output lines. + +#define PLOG(severity) GOOGLE_PLOG(severity, 0).stream() + +#define GOOGLE_PLOG(severity, counter) \ + @ac_google_namespace@::ErrnoLogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, counter, \ + &@ac_google_namespace@::LogMessage::SendToLog) + +#define PLOG_IF(severity, condition) \ + static_cast(0), \ + !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & PLOG(severity) + +// A CHECK() macro that postpends errno if the condition is false. E.g. +// +// if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... } +#define PCHECK(condition) \ + PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \ + << "Check failed: " #condition " " + +// A CHECK() macro that lets you assert the success of a function that +// returns -1 and sets errno in case of an error. E.g. +// +// CHECK_ERR(mkdir(path, 0700)); +// +// or +// +// int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename; +#define CHECK_ERR(invocation) \ +PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN((invocation) == -1)) \ + << #invocation + +// Use macro expansion to create, for each use of LOG_EVERY_N(), static +// variables with the __LINE__ expansion as part of the variable name. +#define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line) +#define LOG_EVERY_N_VARNAME_CONCAT(base, line) base ## line + +#define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__) +#define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__) + +#if @ac_cv_cxx11_constexpr@ && __cplusplus >= 201103L +#define GLOG_CONSTEXPR constexpr +#else +#define GLOG_CONSTEXPR const +#endif + +#define LOG_TIME_PERIOD LOG_EVERY_N_VARNAME(timePeriod_, __LINE__) +#define LOG_PREVIOUS_TIME_RAW LOG_EVERY_N_VARNAME(previousTimeRaw_, __LINE__) +#define LOG_TIME_DELTA LOG_EVERY_N_VARNAME(deltaTime_, __LINE__) +#define LOG_CURRENT_TIME LOG_EVERY_N_VARNAME(currentTime_, __LINE__) +#define LOG_PREVIOUS_TIME LOG_EVERY_N_VARNAME(previousTime_, __LINE__) + +#if defined(__has_feature) +# if __has_feature(thread_sanitizer) +# define GLOG_SANITIZE_THREAD 1 +# endif +#endif + +#if !defined(GLOG_SANITIZE_THREAD) && defined(__SANITIZE_THREAD__) && __SANITIZE_THREAD__ +# define GLOG_SANITIZE_THREAD 1 +#endif + +#if defined(GLOG_SANITIZE_THREAD) +#define GLOG_IFDEF_THREAD_SANITIZER(X) X +#else +#define GLOG_IFDEF_THREAD_SANITIZER(X) +#endif + +#if defined(GLOG_SANITIZE_THREAD) +} // namespace google + +// We need to identify the static variables as "benign" races +// to avoid noisy reports from TSAN. +extern "C" void AnnotateBenignRaceSized( + const char *file, + int line, + const volatile void *mem, + size_t size, + const char *description); + +namespace google { +#endif + +#if __cplusplus >= 201103L && @ac_cv_cxx11_chrono@ && @ac_cv_cxx11_atomic@ // Have and +#define SOME_KIND_OF_LOG_EVERY_T(severity, seconds) \ + GLOG_CONSTEXPR std::chrono::nanoseconds LOG_TIME_PERIOD = std::chrono::duration_cast(std::chrono::duration(seconds)); \ + static std::atomic<@ac_google_namespace@::int64> LOG_PREVIOUS_TIME_RAW; \ + GLOG_IFDEF_THREAD_SANITIZER( \ + AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_TIME_PERIOD, sizeof(@ac_google_namespace@::int64), "")); \ + GLOG_IFDEF_THREAD_SANITIZER( \ + AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_PREVIOUS_TIME_RAW, sizeof(@ac_google_namespace@::int64), "")); \ + const auto LOG_CURRENT_TIME = std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()); \ + const auto LOG_PREVIOUS_TIME = LOG_PREVIOUS_TIME_RAW.load(std::memory_order_relaxed); \ + const auto LOG_TIME_DELTA = LOG_CURRENT_TIME - std::chrono::nanoseconds(LOG_PREVIOUS_TIME); \ + if (LOG_TIME_DELTA > LOG_TIME_PERIOD) \ + LOG_PREVIOUS_TIME_RAW.store(std::chrono::duration_cast(LOG_CURRENT_TIME).count(), std::memory_order_relaxed); \ + if (LOG_TIME_DELTA > LOG_TIME_PERIOD) @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity).stream() +#elif defined(GLOG_OS_WINDOWS) +#define SOME_KIND_OF_LOG_EVERY_T(severity, seconds) \ + GLOG_CONSTEXPR LONGLONG LOG_TIME_PERIOD = (seconds) * LONGLONG(1000000000); \ + static LARGE_INTEGER LOG_PREVIOUS_TIME; \ + LONGLONG LOG_TIME_DELTA; \ + { \ + LARGE_INTEGER currTime; \ + LARGE_INTEGER freq; \ + QueryPerformanceCounter(&currTime); \ + QueryPerformanceFrequency(&freq); \ + InterlockedCompareExchange64(&LOG_PREVIOUS_TIME.QuadPart, currTime.QuadPart, 0); \ + LOG_TIME_DELTA = (currTime.QuadPart - LOG_PREVIOUS_TIME.QuadPart) * LONGLONG(1000000000) / freq.QuadPart; \ + if (LOG_TIME_DELTA > LOG_TIME_PERIOD) InterlockedExchange64(&LOG_PREVIOUS_TIME.QuadPart, currTime.QuadPart); \ + } \ + if (LOG_TIME_DELTA > LOG_TIME_PERIOD) \ + @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity).stream() +#else +#define SOME_KIND_OF_LOG_EVERY_T(severity, seconds) \ + GLOG_CONSTEXPR @ac_google_namespace@::int64 LOG_TIME_PERIOD(seconds * 1000000000); \ + static @ac_google_namespace@::int64 LOG_PREVIOUS_TIME; \ + @ac_google_namespace@::int64 LOG_TIME_DELTA = 0; \ + { \ + timespec currentTime = {}; \ + clock_gettime(CLOCK_MONOTONIC, ¤tTime); \ + LOG_TIME_DELTA = (currentTime.tv_sec * 1000000000 + currentTime.tv_nsec) - LOG_PREVIOUS_TIME; \ + } \ + if (LOG_TIME_DELTA > LOG_TIME_PERIOD) __sync_add_and_fetch(&LOG_PREVIOUS_TIME, LOG_TIME_DELTA); \ + if (LOG_TIME_DELTA > LOG_TIME_PERIOD) @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity).stream() +#endif + +#if @ac_cv_cxx11_atomic@ && __cplusplus >= 201103L +#define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \ + static std::atomic LOG_OCCURRENCES(0), LOG_OCCURRENCES_MOD_N(0); \ + GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_OCCURRENCES, sizeof(int), "")); \ + GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_OCCURRENCES_MOD_N, sizeof(int), "")); \ + ++LOG_OCCURRENCES; \ + if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \ + if (LOG_OCCURRENCES_MOD_N == 1) \ + @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \ + &what_to_do).stream() + +#define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \ + static std::atomic LOG_OCCURRENCES(0), LOG_OCCURRENCES_MOD_N(0); \ + GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_OCCURRENCES, sizeof(int), "")); \ + GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_OCCURRENCES_MOD_N, sizeof(int), "")); \ + ++LOG_OCCURRENCES; \ + if ((condition) && \ + ((LOG_OCCURRENCES_MOD_N=(LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \ + @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \ + &what_to_do).stream() + +#define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \ + static std::atomic LOG_OCCURRENCES(0), LOG_OCCURRENCES_MOD_N(0); \ + GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_OCCURRENCES, sizeof(int), "")); \ + GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_OCCURRENCES_MOD_N, sizeof(int), "")); \ + ++LOG_OCCURRENCES; \ + if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \ + if (LOG_OCCURRENCES_MOD_N == 1) \ + @ac_google_namespace@::ErrnoLogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \ + &what_to_do).stream() + +#define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \ + static std::atomic LOG_OCCURRENCES(0); \ + GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_OCCURRENCES, sizeof(int), "")); \ + if (LOG_OCCURRENCES <= n) \ + ++LOG_OCCURRENCES; \ + if (LOG_OCCURRENCES <= n) \ + @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \ + &what_to_do).stream() + +#elif defined(GLOG_OS_WINDOWS) + +#define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \ + static volatile unsigned LOG_OCCURRENCES = 0; \ + static volatile unsigned LOG_OCCURRENCES_MOD_N = 0; \ + InterlockedIncrement(&LOG_OCCURRENCES); \ + if (InterlockedIncrement(&LOG_OCCURRENCES_MOD_N) > n) \ + InterlockedExchangeSubtract(&LOG_OCCURRENCES_MOD_N, n); \ + if (LOG_OCCURRENCES_MOD_N == 1) \ + @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \ + &what_to_do).stream() + +#define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \ + static volatile unsigned LOG_OCCURRENCES = 0; \ + static volatile unsigned LOG_OCCURRENCES_MOD_N = 0; \ + InterlockedIncrement(&LOG_OCCURRENCES); \ + if ((condition) && \ + ((InterlockedIncrement(&LOG_OCCURRENCES_MOD_N), \ + (LOG_OCCURRENCES_MOD_N > n && InterlockedExchangeSubtract(&LOG_OCCURRENCES_MOD_N, n))), \ + LOG_OCCURRENCES_MOD_N == 1)) \ + @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \ + &what_to_do).stream() + +#define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \ + static volatile unsigned LOG_OCCURRENCES = 0; \ + static volatile unsigned LOG_OCCURRENCES_MOD_N = 0; \ + InterlockedIncrement(&LOG_OCCURRENCES); \ + if (InterlockedIncrement(&LOG_OCCURRENCES_MOD_N) > n) \ + InterlockedExchangeSubtract(&LOG_OCCURRENCES_MOD_N, n); \ + if (LOG_OCCURRENCES_MOD_N == 1) \ + @ac_google_namespace@::ErrnoLogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \ + &what_to_do).stream() + +#define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \ + static volatile unsigned LOG_OCCURRENCES = 0; \ + if (LOG_OCCURRENCES <= n) \ + InterlockedIncrement(&LOG_OCCURRENCES); \ + if (LOG_OCCURRENCES <= n) \ + @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \ + &what_to_do).stream() + +#else + +#define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \ + static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \ + __sync_add_and_fetch(&LOG_OCCURRENCES, 1); \ + if (__sync_add_and_fetch(&LOG_OCCURRENCES_MOD_N, 1) > n) \ + __sync_sub_and_fetch(&LOG_OCCURRENCES_MOD_N, n); \ + if (LOG_OCCURRENCES_MOD_N == 1) \ + @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \ + &what_to_do).stream() + +#define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \ + static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \ + __sync_add_and_fetch(&LOG_OCCURRENCES, 1); \ + if ((condition) && \ + (__sync_add_and_fetch(&LOG_OCCURRENCES_MOD_N, 1) || true) && \ + ((LOG_OCCURRENCES_MOD_N >= n && __sync_sub_and_fetch(&LOG_OCCURRENCES_MOD_N, n)) || true) && \ + LOG_OCCURRENCES_MOD_N == (1 % n)) \ + @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \ + &what_to_do).stream() + +#define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \ + static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \ + __sync_add_and_fetch(&LOG_OCCURRENCES, 1); \ + if (__sync_add_and_fetch(&LOG_OCCURRENCES_MOD_N, 1) > n) \ + __sync_sub_and_fetch(&LOG_OCCURRENCES_MOD_N, n); \ + if (LOG_OCCURRENCES_MOD_N == 1) \ + @ac_google_namespace@::ErrnoLogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \ + &what_to_do).stream() + +#define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \ + static int LOG_OCCURRENCES = 0; \ + if (LOG_OCCURRENCES <= n) \ + __sync_add_and_fetch(&LOG_OCCURRENCES, 1); \ + if (LOG_OCCURRENCES <= n) \ + @ac_google_namespace@::LogMessage( \ + __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \ + &what_to_do).stream() +#endif + +namespace glog_internal_namespace_ { +template +struct CompileAssert { +}; +struct CrashReason; + +// Returns true if FailureSignalHandler is installed. +// Needs to be exported since it's used by the signalhandler_unittest. +GLOG_EXPORT bool IsFailureSignalHandlerInstalled(); +} // namespace glog_internal_namespace_ + +#define LOG_EVERY_N(severity, n) \ + SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog) + +#define LOG_EVERY_T(severity, T) SOME_KIND_OF_LOG_EVERY_T(severity, (T)) + +#define SYSLOG_EVERY_N(severity, n) \ + SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToSyslogAndLog) + +#define PLOG_EVERY_N(severity, n) \ + SOME_KIND_OF_PLOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog) + +#define LOG_FIRST_N(severity, n) \ + SOME_KIND_OF_LOG_FIRST_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog) + +#define LOG_IF_EVERY_N(severity, condition, n) \ + SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), @ac_google_namespace@::LogMessage::SendToLog) + +// We want the special COUNTER value available for LOG_EVERY_X()'ed messages +enum PRIVATE_Counter {COUNTER}; + +#ifdef GLOG_NO_ABBREVIATED_SEVERITIES +// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets +// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us +// to keep using this syntax, we define this macro to do the same thing +// as COMPACT_GOOGLE_LOG_ERROR. +#define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR +#define SYSLOG_0 SYSLOG_ERROR +#define LOG_TO_STRING_0 LOG_TO_STRING_ERROR +// Needed for LOG_IS_ON(ERROR). +const LogSeverity GLOG_0 = GLOG_ERROR; +#else +// Users may include windows.h after logging.h without +// GLOG_NO_ABBREVIATED_SEVERITIES nor WIN32_LEAN_AND_MEAN. +// For this case, we cannot detect if ERROR is defined before users +// actually use ERROR. Let's make an undefined symbol to warn users. +# define GLOG_ERROR_MSG ERROR_macro_is_defined_Define_GLOG_NO_ABBREVIATED_SEVERITIES_before_including_logging_h_See_the_document_for_detail +# define COMPACT_GOOGLE_LOG_0 GLOG_ERROR_MSG +# define SYSLOG_0 GLOG_ERROR_MSG +# define LOG_TO_STRING_0 GLOG_ERROR_MSG +# define GLOG_0 GLOG_ERROR_MSG +#endif + +// Plus some debug-logging macros that get compiled to nothing for production + +#if DCHECK_IS_ON() + +#define DLOG(severity) LOG(severity) +#define DVLOG(verboselevel) VLOG(verboselevel) +#define DLOG_IF(severity, condition) LOG_IF(severity, condition) +#define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n) +#define DLOG_IF_EVERY_N(severity, condition, n) \ + LOG_IF_EVERY_N(severity, condition, n) +#define DLOG_ASSERT(condition) LOG_ASSERT(condition) + +// debug-only checking. executed if DCHECK_IS_ON(). +#define DCHECK(condition) CHECK(condition) +#define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2) +#define DCHECK_NE(val1, val2) CHECK_NE(val1, val2) +#define DCHECK_LE(val1, val2) CHECK_LE(val1, val2) +#define DCHECK_LT(val1, val2) CHECK_LT(val1, val2) +#define DCHECK_GE(val1, val2) CHECK_GE(val1, val2) +#define DCHECK_GT(val1, val2) CHECK_GT(val1, val2) +#define DCHECK_NOTNULL(val) CHECK_NOTNULL(val) +#define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2) +#define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2) +#define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2) +#define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2) + +#else // !DCHECK_IS_ON() + +#define DLOG(severity) \ + static_cast(0), \ + true ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity) + +#define DVLOG(verboselevel) \ + static_cast(0), \ + (true || !VLOG_IS_ON(verboselevel)) ? \ + (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(INFO) + +#define DLOG_IF(severity, condition) \ + static_cast(0), \ + (true || !(condition)) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity) + +#define DLOG_EVERY_N(severity, n) \ + static_cast(0), \ + true ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity) + +#define DLOG_IF_EVERY_N(severity, condition, n) \ + static_cast(0), \ + (true || !(condition))? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity) + +#define DLOG_ASSERT(condition) \ + static_cast(0), \ + true ? (void) 0 : LOG_ASSERT(condition) + +// MSVC warning C4127: conditional expression is constant +#define DCHECK(condition) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) \ + GLOG_MSVC_POP_WARNING() CHECK(condition) + +#define DCHECK_EQ(val1, val2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) \ + GLOG_MSVC_POP_WARNING() CHECK_EQ(val1, val2) + +#define DCHECK_NE(val1, val2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) \ + GLOG_MSVC_POP_WARNING() CHECK_NE(val1, val2) + +#define DCHECK_LE(val1, val2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) \ + GLOG_MSVC_POP_WARNING() CHECK_LE(val1, val2) + +#define DCHECK_LT(val1, val2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) \ + GLOG_MSVC_POP_WARNING() CHECK_LT(val1, val2) + +#define DCHECK_GE(val1, val2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) \ + GLOG_MSVC_POP_WARNING() CHECK_GE(val1, val2) + +#define DCHECK_GT(val1, val2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) \ + GLOG_MSVC_POP_WARNING() CHECK_GT(val1, val2) + +// You may see warnings in release mode if you don't use the return +// value of DCHECK_NOTNULL. Please just use DCHECK for such cases. +#define DCHECK_NOTNULL(val) (val) + +#define DCHECK_STREQ(str1, str2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) \ + GLOG_MSVC_POP_WARNING() CHECK_STREQ(str1, str2) + +#define DCHECK_STRCASEEQ(str1, str2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) \ + GLOG_MSVC_POP_WARNING() CHECK_STRCASEEQ(str1, str2) + +#define DCHECK_STRNE(str1, str2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) \ + GLOG_MSVC_POP_WARNING() CHECK_STRNE(str1, str2) + +#define DCHECK_STRCASENE(str1, str2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) \ + GLOG_MSVC_POP_WARNING() CHECK_STRCASENE(str1, str2) + +#endif // DCHECK_IS_ON() + +// Log only in verbose mode. + +#define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel)) + +#define VLOG_IF(verboselevel, condition) \ + LOG_IF(INFO, (condition) && VLOG_IS_ON(verboselevel)) + +#define VLOG_EVERY_N(verboselevel, n) \ + LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n) + +#define VLOG_IF_EVERY_N(verboselevel, condition, n) \ + LOG_IF_EVERY_N(INFO, (condition) && VLOG_IS_ON(verboselevel), n) + +namespace base_logging { + +// LogMessage::LogStream is a std::ostream backed by this streambuf. +// This class ignores overflow and leaves two bytes at the end of the +// buffer to allow for a '\n' and '\0'. +class GLOG_EXPORT LogStreamBuf : public std::streambuf { + public: + // REQUIREMENTS: "len" must be >= 2 to account for the '\n' and '\0'. + LogStreamBuf(char *buf, int len) { + setp(buf, buf + len - 2); + } + + // This effectively ignores overflow. + int_type overflow(int_type ch) { + return ch; + } + + // Legacy public ostrstream method. + size_t pcount() const { return static_cast(pptr() - pbase()); } + char* pbase() const { return std::streambuf::pbase(); } +}; + +} // namespace base_logging + +// +// This class more or less represents a particular log message. You +// create an instance of LogMessage and then stream stuff to it. +// When you finish streaming to it, ~LogMessage is called and the +// full message gets streamed to the appropriate destination. +// +// You shouldn't actually use LogMessage's constructor to log things, +// though. You should use the LOG() macro (and variants thereof) +// above. +class GLOG_EXPORT LogMessage { +public: + enum { + // Passing kNoLogPrefix for the line number disables the + // log-message prefix. Useful for using the LogMessage + // infrastructure as a printing utility. See also the --log_prefix + // flag for controlling the log-message prefix on an + // application-wide basis. + kNoLogPrefix = -1 + }; + + // LogStream inherit from non-DLL-exported class (std::ostrstream) + // and VC++ produces a warning for this situation. + // However, MSDN says "C4275 can be ignored in Microsoft Visual C++ + // 2005 if you are deriving from a type in the Standard C++ Library" + // http://msdn.microsoft.com/en-us/library/3tdb471s(VS.80).aspx + // Let's just ignore the warning. +GLOG_MSVC_PUSH_DISABLE_WARNING(4275) + class GLOG_EXPORT LogStream : public std::ostream { +GLOG_MSVC_POP_WARNING() + public: + LogStream(char *buf, int len, int64 ctr) + : std::ostream(NULL), + streambuf_(buf, len), + ctr_(ctr), + self_(this) { + rdbuf(&streambuf_); + } + + int64 ctr() const { return ctr_; } + void set_ctr(int64 ctr) { ctr_ = ctr; } + LogStream* self() const { return self_; } + + // Legacy std::streambuf methods. + size_t pcount() const { return streambuf_.pcount(); } + char* pbase() const { return streambuf_.pbase(); } + char* str() const { return pbase(); } + + private: + LogStream(const LogStream&); + LogStream& operator=(const LogStream&); + base_logging::LogStreamBuf streambuf_; + int64 ctr_; // Counter hack (for the LOG_EVERY_X() macro) + LogStream *self_; // Consistency check hack + }; + +public: + // icc 8 requires this typedef to avoid an internal compiler error. + typedef void (LogMessage::*SendMethod)(); + + LogMessage(const char* file, int line, LogSeverity severity, int64 ctr, + SendMethod send_method); + + // Two special constructors that generate reduced amounts of code at + // LOG call sites for common cases. + + // Used for LOG(INFO): Implied are: + // severity = INFO, ctr = 0, send_method = &LogMessage::SendToLog. + // + // Using this constructor instead of the more complex constructor above + // saves 19 bytes per call site. + LogMessage(const char* file, int line); + + // Used for LOG(severity) where severity != INFO. Implied + // are: ctr = 0, send_method = &LogMessage::SendToLog + // + // Using this constructor instead of the more complex constructor above + // saves 17 bytes per call site. + LogMessage(const char* file, int line, LogSeverity severity); + + // Constructor to log this message to a specified sink (if not NULL). + // Implied are: ctr = 0, send_method = &LogMessage::SendToSinkAndLog if + // also_send_to_log is true, send_method = &LogMessage::SendToSink otherwise. + LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink, + bool also_send_to_log); + + // Constructor where we also give a vector pointer + // for storing the messages (if the pointer is not NULL). + // Implied are: ctr = 0, send_method = &LogMessage::SaveOrSendToLog. + LogMessage(const char* file, int line, LogSeverity severity, + std::vector* outvec); + + // Constructor where we also give a string pointer for storing the + // message (if the pointer is not NULL). Implied are: ctr = 0, + // send_method = &LogMessage::WriteToStringAndLog. + LogMessage(const char* file, int line, LogSeverity severity, + std::string* message); + + // A special constructor used for check failures + LogMessage(const char* file, int line, const CheckOpString& result); + + ~LogMessage(); + + // Flush a buffered message to the sink set in the constructor. Always + // called by the destructor, it may also be called from elsewhere if + // needed. Only the first call is actioned; any later ones are ignored. + void Flush(); + + // An arbitrary limit on the length of a single log message. This + // is so that streaming can be done more efficiently. + static const size_t kMaxLogMessageLen; + + // Theses should not be called directly outside of logging.*, + // only passed as SendMethod arguments to other LogMessage methods: + void SendToLog(); // Actually dispatch to the logs + void SendToSyslogAndLog(); // Actually dispatch to syslog and the logs + + // Call abort() or similar to perform LOG(FATAL) crash. + static void @ac_cv___attribute___noreturn@ Fail(); + + std::ostream& stream(); + + int preserved_errno() const; + + // Must be called without the log_mutex held. (L < log_mutex) + static int64 num_messages(int severity); + + const LogMessageTime& getLogMessageTime() const; + + struct LogMessageData; + +private: + // Fully internal SendMethod cases: + void SendToSinkAndLog(); // Send to sink if provided and dispatch to the logs + void SendToSink(); // Send to sink if provided, do nothing otherwise. + + // Write to string if provided and dispatch to the logs. + void WriteToStringAndLog(); + + void SaveOrSendToLog(); // Save to stringvec if provided, else to logs + + void Init(const char* file, int line, LogSeverity severity, + void (LogMessage::*send_method)()); + + // Used to fill in crash information during LOG(FATAL) failures. + void RecordCrashReason(glog_internal_namespace_::CrashReason* reason); + + // Counts of messages sent at each priority: + static int64 num_messages_[NUM_SEVERITIES]; // under log_mutex + + // We keep the data in a separate struct so that each instance of + // LogMessage uses less stack space. + LogMessageData* allocated_; + LogMessageData* data_; + LogMessageTime logmsgtime_; + + friend class LogDestination; + + LogMessage(const LogMessage&); + void operator=(const LogMessage&); +}; + +// This class happens to be thread-hostile because all instances share +// a single data buffer, but since it can only be created just before +// the process dies, we don't worry so much. +class GLOG_EXPORT LogMessageFatal : public LogMessage { + public: + LogMessageFatal(const char* file, int line); + LogMessageFatal(const char* file, int line, const CheckOpString& result); + @ac_cv___attribute___noreturn@ ~LogMessageFatal(); +}; + +// A non-macro interface to the log facility; (useful +// when the logging level is not a compile-time constant). +inline void LogAtLevel(int const severity, std::string const &msg) { + LogMessage(__FILE__, __LINE__, severity).stream() << msg; +} + +// A macro alternative of LogAtLevel. New code may want to use this +// version since there are two advantages: 1. this version outputs the +// file name and the line number where this macro is put like other +// LOG macros, 2. this macro can be used as C++ stream. +#define LOG_AT_LEVEL(severity) @ac_google_namespace@::LogMessage(__FILE__, __LINE__, severity).stream() + +// Check if it's compiled in C++11 mode. +// +// GXX_EXPERIMENTAL_CXX0X is defined by gcc and clang up to at least +// gcc-4.7 and clang-3.1 (2011-12-13). __cplusplus was defined to 1 +// in gcc before 4.7 (Crosstool 16) and clang before 3.1, but is +// defined according to the language version in effect thereafter. +// Microsoft Visual Studio 14 (2015) sets __cplusplus==199711 despite +// reasonably good C++11 support, so we set LANG_CXX for it and +// newer versions (_MSC_VER >= 1900). +#if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L || \ + (defined(_MSC_VER) && _MSC_VER >= 1900)) && !defined(__UCLIBCXX_MAJOR__) +// Helper for CHECK_NOTNULL(). +// +// In C++11, all cases can be handled by a single function. Since the value +// category of the argument is preserved (also for rvalue references), +// member initializer lists like the one below will compile correctly: +// +// Foo() +// : x_(CHECK_NOTNULL(MethodReturningUniquePtr())) {} +template +T CheckNotNull(const char* file, int line, const char* names, T&& t) { + if (t == nullptr) { + LogMessageFatal(file, line, new std::string(names)); + } + return std::forward(t); +} + +#else + +// A small helper for CHECK_NOTNULL(). +template +T* CheckNotNull(const char *file, int line, const char *names, T* t) { + if (t == NULL) { + LogMessageFatal(file, line, new std::string(names)); + } + return t; +} +#endif + +// Allow folks to put a counter in the LOG_EVERY_X()'ed messages. This +// only works if ostream is a LogStream. If the ostream is not a +// LogStream you'll get an assert saying as much at runtime. +GLOG_EXPORT std::ostream& operator<<(std::ostream &os, + const PRIVATE_Counter&); + + +// Derived class for PLOG*() above. +class GLOG_EXPORT ErrnoLogMessage : public LogMessage { + public: + ErrnoLogMessage(const char* file, int line, LogSeverity severity, int64 ctr, + void (LogMessage::*send_method)()); + + // Postpends ": strerror(errno) [errno]". + ~ErrnoLogMessage(); + + private: + ErrnoLogMessage(const ErrnoLogMessage&); + void operator=(const ErrnoLogMessage&); +}; + + +// This class is used to explicitly ignore values in the conditional +// logging macros. This avoids compiler warnings like "value computed +// is not used" and "statement has no effect". + +class GLOG_EXPORT LogMessageVoidify { + public: + LogMessageVoidify() { } + // This has to be an operator with a precedence lower than << but + // higher than ?: + void operator&(std::ostream&) { } +}; + + +// Flushes all log files that contains messages that are at least of +// the specified severity level. Thread-safe. +GLOG_EXPORT void FlushLogFiles(LogSeverity min_severity); + +// Flushes all log files that contains messages that are at least of +// the specified severity level. Thread-hostile because it ignores +// locking -- used for catastrophic failures. +GLOG_EXPORT void FlushLogFilesUnsafe(LogSeverity min_severity); + +// +// Set the destination to which a particular severity level of log +// messages is sent. If base_filename is "", it means "don't log this +// severity". Thread-safe. +// +GLOG_EXPORT void SetLogDestination(LogSeverity severity, + const char* base_filename); + +// +// Set the basename of the symlink to the latest log file at a given +// severity. If symlink_basename is empty, do not make a symlink. If +// you don't call this function, the symlink basename is the +// invocation name of the program. Thread-safe. +// +GLOG_EXPORT void SetLogSymlink(LogSeverity severity, + const char* symlink_basename); + +// +// Used to send logs to some other kind of destination +// Users should subclass LogSink and override send to do whatever they want. +// Implementations must be thread-safe because a shared instance will +// be called from whichever thread ran the LOG(XXX) line. +class GLOG_EXPORT LogSink { + public: + virtual ~LogSink(); + + // Sink's logging logic (message_len is such as to exclude '\n' at the end). + // This method can't use LOG() or CHECK() as logging system mutex(s) are held + // during this call. + virtual void send(LogSeverity severity, const char* full_filename, + const char* base_filename, int line, + const LogMessageTime& logmsgtime, const char* message, + size_t message_len); + // Provide an overload for compatibility purposes + GLOG_DEPRECATED + virtual void send(LogSeverity severity, const char* full_filename, + const char* base_filename, int line, const std::tm* t, + const char* message, size_t message_len); + + // Redefine this to implement waiting for + // the sink's logging logic to complete. + // It will be called after each send() returns, + // but before that LogMessage exits or crashes. + // By default this function does nothing. + // Using this function one can implement complex logic for send() + // that itself involves logging; and do all this w/o causing deadlocks and + // inconsistent rearrangement of log messages. + // E.g. if a LogSink has thread-specific actions, the send() method + // can simply add the message to a queue and wake up another thread that + // handles real logging while itself making some LOG() calls; + // WaitTillSent() can be implemented to wait for that logic to complete. + // See our unittest for an example. + virtual void WaitTillSent(); + + // Returns the normal text output of the log message. + // Can be useful to implement send(). + static std::string ToString(LogSeverity severity, const char* file, int line, + const LogMessageTime &logmsgtime, + const char* message, size_t message_len); +}; + +// Add or remove a LogSink as a consumer of logging data. Thread-safe. +GLOG_EXPORT void AddLogSink(LogSink *destination); +GLOG_EXPORT void RemoveLogSink(LogSink *destination); + +// +// Specify an "extension" added to the filename specified via +// SetLogDestination. This applies to all severity levels. It's +// often used to append the port we're listening on to the logfile +// name. Thread-safe. +// +GLOG_EXPORT void SetLogFilenameExtension( + const char* filename_extension); + +// +// Make it so that all log messages of at least a particular severity +// are logged to stderr (in addition to logging to the usual log +// file(s)). Thread-safe. +// +GLOG_EXPORT void SetStderrLogging(LogSeverity min_severity); + +// +// Make it so that all log messages go only to stderr. Thread-safe. +// +GLOG_EXPORT void LogToStderr(); + +// +// Make it so that all log messages of at least a particular severity are +// logged via email to a list of addresses (in addition to logging to the +// usual log file(s)). The list of addresses is just a string containing +// the email addresses to send to (separated by spaces, say). Thread-safe. +// +GLOG_EXPORT void SetEmailLogging(LogSeverity min_severity, + const char* addresses); + +// A simple function that sends email. dest is a commma-separated +// list of addressess. Thread-safe. +GLOG_EXPORT bool SendEmail(const char *dest, + const char *subject, const char *body); + +GLOG_EXPORT const std::vector& GetLoggingDirectories(); + +// For tests only: Clear the internal [cached] list of logging directories to +// force a refresh the next time GetLoggingDirectories is called. +// Thread-hostile. +void TestOnly_ClearLoggingDirectoriesList(); + +// Returns a set of existing temporary directories, which will be a +// subset of the directories returned by GetLoggingDirectories(). +// Thread-safe. +GLOG_EXPORT void GetExistingTempDirectories( + std::vector* list); + +// Print any fatal message again -- useful to call from signal handler +// so that the last thing in the output is the fatal message. +// Thread-hostile, but a race is unlikely. +GLOG_EXPORT void ReprintFatalMessage(); + +// Truncate a log file that may be the append-only output of multiple +// processes and hence can't simply be renamed/reopened (typically a +// stdout/stderr). If the file "path" is > "limit" bytes, copy the +// last "keep" bytes to offset 0 and truncate the rest. Since we could +// be racing with other writers, this approach has the potential to +// lose very small amounts of data. For security, only follow symlinks +// if the path is /proc/self/fd/* +GLOG_EXPORT void TruncateLogFile(const char* path, uint64 limit, uint64 keep); + +// Truncate stdout and stderr if they are over the value specified by +// --max_log_size; keep the final 1MB. This function has the same +// race condition as TruncateLogFile. +GLOG_EXPORT void TruncateStdoutStderr(); + +// Return the string representation of the provided LogSeverity level. +// Thread-safe. +GLOG_EXPORT const char* GetLogSeverityName(LogSeverity severity); + +// --------------------------------------------------------------------- +// Implementation details that are not useful to most clients +// --------------------------------------------------------------------- + +// A Logger is the interface used by logging modules to emit entries +// to a log. A typical implementation will dump formatted data to a +// sequence of files. We also provide interfaces that will forward +// the data to another thread so that the invoker never blocks. +// Implementations should be thread-safe since the logging system +// will write to them from multiple threads. + +namespace base { + +class GLOG_EXPORT Logger { + public: + virtual ~Logger(); + + // Writes "message[0,message_len-1]" corresponding to an event that + // occurred at "timestamp". If "force_flush" is true, the log file + // is flushed immediately. + // + // The input message has already been formatted as deemed + // appropriate by the higher level logging facility. For example, + // textual log messages already contain timestamps, and the + // file:linenumber header. + virtual void Write(bool force_flush, + time_t timestamp, + const char* message, + size_t message_len) = 0; + + // Flush any buffered messages + virtual void Flush() = 0; + + // Get the current LOG file size. + // The returned value is approximate since some + // logged data may not have been flushed to disk yet. + virtual uint32 LogSize() = 0; +}; + +// Get the logger for the specified severity level. The logger +// remains the property of the logging module and should not be +// deleted by the caller. Thread-safe. +extern GLOG_EXPORT Logger* GetLogger(LogSeverity level); + +// Set the logger for the specified severity level. The logger +// becomes the property of the logging module and should not +// be deleted by the caller. Thread-safe. +extern GLOG_EXPORT void SetLogger(LogSeverity level, Logger* logger); + +} + +// glibc has traditionally implemented two incompatible versions of +// strerror_r(). There is a poorly defined convention for picking the +// version that we want, but it is not clear whether it even works with +// all versions of glibc. +// So, instead, we provide this wrapper that automatically detects the +// version that is in use, and then implements POSIX semantics. +// N.B. In addition to what POSIX says, we also guarantee that "buf" will +// be set to an empty string, if this function failed. This means, in most +// cases, you do not need to check the error code and you can directly +// use the value of "buf". It will never have an undefined value. +// DEPRECATED: Use StrError(int) instead. +GLOG_EXPORT int posix_strerror_r(int err, char *buf, size_t len); + +// A thread-safe replacement for strerror(). Returns a string describing the +// given POSIX error code. +GLOG_EXPORT std::string StrError(int err); + +// A class for which we define operator<<, which does nothing. +class GLOG_EXPORT NullStream : public LogMessage::LogStream { + public: + // Initialize the LogStream so the messages can be written somewhere + // (they'll never be actually displayed). This will be needed if a + // NullStream& is implicitly converted to LogStream&, in which case + // the overloaded NullStream::operator<< will not be invoked. + NullStream() : LogMessage::LogStream(message_buffer_, 1, 0) { } + NullStream(const char* /*file*/, int /*line*/, + const CheckOpString& /*result*/) : + LogMessage::LogStream(message_buffer_, 1, 0) { } + NullStream &stream() { return *this; } + private: + // A very short buffer for messages (which we discard anyway). This + // will be needed if NullStream& converted to LogStream& (e.g. as a + // result of a conditional expression). + char message_buffer_[2]; +}; + +// Do nothing. This operator is inline, allowing the message to be +// compiled away. The message will not be compiled away if we do +// something like (flag ? LOG(INFO) : LOG(ERROR)) << message; when +// SKIP_LOG=WARNING. In those cases, NullStream will be implicitly +// converted to LogStream and the message will be computed and then +// quietly discarded. +template +inline NullStream& operator<<(NullStream &str, const T &) { return str; } + +// Similar to NullStream, but aborts the program (without stack +// trace), like LogMessageFatal. +class GLOG_EXPORT NullStreamFatal : public NullStream { + public: + NullStreamFatal() { } + NullStreamFatal(const char* file, int line, const CheckOpString& result) : + NullStream(file, line, result) { } +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4722) +#endif // _MSC_VER + @ac_cv___attribute___noreturn@ ~NullStreamFatal() throw () { _exit(EXIT_FAILURE); } +#if defined(_MSC_VER) +#pragma warning(pop) +#endif // _MSC_VER +}; + +// Install a signal handler that will dump signal information and a stack +// trace when the program crashes on certain signals. We'll install the +// signal handler for the following signals. +// +// SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGBUS, and SIGTERM. +// +// By default, the signal handler will write the failure dump to the +// standard error. You can customize the destination by installing your +// own writer function by InstallFailureWriter() below. +// +// Note on threading: +// +// The function should be called before threads are created, if you want +// to use the failure signal handler for all threads. The stack trace +// will be shown only for the thread that receives the signal. In other +// words, stack traces of other threads won't be shown. +GLOG_EXPORT void InstallFailureSignalHandler(); + +// Installs a function that is used for writing the failure dump. "data" +// is the pointer to the beginning of a message to be written, and "size" +// is the size of the message. You should not expect the data is +// terminated with '\0'. +GLOG_EXPORT void InstallFailureWriter( + void (*writer)(const char* data, size_t size)); + +@ac_google_end_namespace@ + +#pragma pop_macro("DECLARE_VARIABLE") +#pragma pop_macro("DECLARE_bool") +#pragma pop_macro("DECLARE_string") +#pragma pop_macro("DECLARE_int32") +#pragma pop_macro("DECLARE_uint32") + +#endif // GLOG_LOGGING_H diff --git a/third_party/glog/src/glog/platform.h b/third_party/glog/src/glog/platform.h new file mode 100644 index 0000000..e614411 --- /dev/null +++ b/third_party/glog/src/glog/platform.h @@ -0,0 +1,58 @@ +// Copyright (c) 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Shinichiro Hamaji +// +// Detect supported platforms. + +#ifndef GLOG_PLATFORM_H +#define GLOG_PLATFORM_H + +#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) +#define GLOG_OS_WINDOWS +#elif defined(__CYGWIN__) || defined(__CYGWIN32__) +#define GLOG_OS_CYGWIN +#elif defined(linux) || defined(__linux) || defined(__linux__) +#ifndef GLOG_OS_LINUX +#define GLOG_OS_LINUX +#endif +#elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) +#define GLOG_OS_MACOSX +#elif defined(__FreeBSD__) +#define GLOG_OS_FREEBSD +#elif defined(__NetBSD__) +#define GLOG_OS_NETBSD +#elif defined(__OpenBSD__) +#define GLOG_OS_OPENBSD +#else +// TODO(hamaji): Add other platforms. +#error Platform not supported by glog. Please consider to contribute platform information by submitting a pull request on Github. +#endif + +#endif // GLOG_PLATFORM_H diff --git a/third_party/glog/src/glog/raw_logging.h.in b/third_party/glog/src/glog/raw_logging.h.in new file mode 100644 index 0000000..66fec91 --- /dev/null +++ b/third_party/glog/src/glog/raw_logging.h.in @@ -0,0 +1,179 @@ +// Copyright (c) 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Maxim Lifantsev +// +// Thread-safe logging routines that do not allocate any memory or +// acquire any locks, and can therefore be used by low-level memory +// allocation and synchronization code. + +#ifndef GLOG_RAW_LOGGING_H +#define GLOG_RAW_LOGGING_H + +#include + +@ac_google_start_namespace@ + +#include +#include +#include + +#if defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wvariadic-macros" +#endif + +// This is similar to LOG(severity) << format... and VLOG(level) << format.., +// but +// * it is to be used ONLY by low-level modules that can't use normal LOG() +// * it is desiged to be a low-level logger that does not allocate any +// memory and does not need any locks, hence: +// * it logs straight and ONLY to STDERR w/o buffering +// * it uses an explicit format and arguments list +// * it will silently chop off really long message strings +// Usage example: +// RAW_LOG(ERROR, "Failed foo with %i: %s", status, error); +// RAW_VLOG(3, "status is %i", status); +// These will print an almost standard log lines like this to stderr only: +// E20200821 211317 file.cc:123] RAW: Failed foo with 22: bad_file +// I20200821 211317 file.cc:142] RAW: status is 20 +#define RAW_LOG(severity, ...) \ + do { \ + switch (@ac_google_namespace@::GLOG_ ## severity) { \ + case 0: \ + RAW_LOG_INFO(__VA_ARGS__); \ + break; \ + case 1: \ + RAW_LOG_WARNING(__VA_ARGS__); \ + break; \ + case 2: \ + RAW_LOG_ERROR(__VA_ARGS__); \ + break; \ + case 3: \ + RAW_LOG_FATAL(__VA_ARGS__); \ + break; \ + default: \ + break; \ + } \ + } while (0) + +// The following STRIP_LOG testing is performed in the header file so that it's +// possible to completely compile out the logging code and the log messages. +#if !defined(STRIP_LOG) || STRIP_LOG == 0 +#define RAW_VLOG(verboselevel, ...) \ + do { \ + if (VLOG_IS_ON(verboselevel)) { \ + RAW_LOG_INFO(__VA_ARGS__); \ + } \ + } while (0) +#else +#define RAW_VLOG(verboselevel, ...) RawLogStub__(0, __VA_ARGS__) +#endif // STRIP_LOG == 0 + +#if !defined(STRIP_LOG) || STRIP_LOG == 0 +#define RAW_LOG_INFO(...) @ac_google_namespace@::RawLog__(@ac_google_namespace@::GLOG_INFO, \ + __FILE__, __LINE__, __VA_ARGS__) +#else +#define RAW_LOG_INFO(...) @ac_google_namespace@::RawLogStub__(0, __VA_ARGS__) +#endif // STRIP_LOG == 0 + +#if !defined(STRIP_LOG) || STRIP_LOG <= 1 +#define RAW_LOG_WARNING(...) @ac_google_namespace@::RawLog__(@ac_google_namespace@::GLOG_WARNING, \ + __FILE__, __LINE__, __VA_ARGS__) +#else +#define RAW_LOG_WARNING(...) @ac_google_namespace@::RawLogStub__(0, __VA_ARGS__) +#endif // STRIP_LOG <= 1 + +#if !defined(STRIP_LOG) || STRIP_LOG <= 2 +#define RAW_LOG_ERROR(...) @ac_google_namespace@::RawLog__(@ac_google_namespace@::GLOG_ERROR, \ + __FILE__, __LINE__, __VA_ARGS__) +#else +#define RAW_LOG_ERROR(...) @ac_google_namespace@::RawLogStub__(0, __VA_ARGS__) +#endif // STRIP_LOG <= 2 + +#if !defined(STRIP_LOG) || STRIP_LOG <= 3 +#define RAW_LOG_FATAL(...) @ac_google_namespace@::RawLog__(@ac_google_namespace@::GLOG_FATAL, \ + __FILE__, __LINE__, __VA_ARGS__) +#else +#define RAW_LOG_FATAL(...) \ + do { \ + @ac_google_namespace@::RawLogStub__(0, __VA_ARGS__); \ + exit(EXIT_FAILURE); \ + } while (0) +#endif // STRIP_LOG <= 3 + +// Similar to CHECK(condition) << message, +// but for low-level modules: we use only RAW_LOG that does not allocate memory. +// We do not want to provide args list here to encourage this usage: +// if (!cond) RAW_LOG(FATAL, "foo ...", hard_to_compute_args); +// so that the args are not computed when not needed. +#define RAW_CHECK(condition, message) \ + do { \ + if (!(condition)) { \ + RAW_LOG(FATAL, "Check %s failed: %s", #condition, message); \ + } \ + } while (0) + +// Debug versions of RAW_LOG and RAW_CHECK +#ifndef NDEBUG + +#define RAW_DLOG(severity, ...) RAW_LOG(severity, __VA_ARGS__) +#define RAW_DCHECK(condition, message) RAW_CHECK(condition, message) + +#else // NDEBUG + +#define RAW_DLOG(severity, ...) \ + while (false) \ + RAW_LOG(severity, __VA_ARGS__) +#define RAW_DCHECK(condition, message) \ + while (false) \ + RAW_CHECK(condition, message) + +#endif // NDEBUG + +#if defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + +// Stub log function used to work around for unused variable warnings when +// building with STRIP_LOG > 0. +static inline void RawLogStub__(int /* ignored */, ...) { +} + +// Helper function to implement RAW_LOG and RAW_VLOG +// Logs format... at "severity" level, reporting it +// as called from file:line. +// This does not allocate memory or acquire locks. +GLOG_EXPORT void RawLog__(LogSeverity severity, const char* file, int line, + const char* format, ...) + @ac_cv___attribute___printf_4_5@; + +@ac_google_end_namespace@ + +#endif // GLOG_RAW_LOGGING_H diff --git a/third_party/glog/src/glog/stl_logging.h.in b/third_party/glog/src/glog/stl_logging.h.in new file mode 100644 index 0000000..bdfdc8b --- /dev/null +++ b/third_party/glog/src/glog/stl_logging.h.in @@ -0,0 +1,220 @@ +// Copyright (c) 2003, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Stream output operators for STL containers; to be used for logging *only*. +// Inclusion of this file lets you do: +// +// list x; +// LOG(INFO) << "data: " << x; +// vector v1, v2; +// CHECK_EQ(v1, v2); +// +// If you want to use this header file with hash maps or slist, you +// need to define macros before including this file: +// +// - GLOG_STL_LOGGING_FOR_UNORDERED - and +// - GLOG_STL_LOGGING_FOR_TR1_UNORDERED - +// - GLOG_STL_LOGGING_FOR_EXT_HASH - +// - GLOG_STL_LOGGING_FOR_EXT_SLIST - +// + +#ifndef UTIL_GTL_STL_LOGGING_INL_H_ +#define UTIL_GTL_STL_LOGGING_INL_H_ + +#if !@ac_cv_cxx_using_operator@ +# error We do not support stl_logging for this compiler +#endif + +#include +#include +#include +#include +#include +#include +#include + +#if defined(GLOG_STL_LOGGING_FOR_UNORDERED) && __cplusplus >= 201103L +# include +# include +#endif + +#ifdef GLOG_STL_LOGGING_FOR_TR1_UNORDERED +# include +# include +#endif + +#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH +# include +# include +#endif +#ifdef GLOG_STL_LOGGING_FOR_EXT_SLIST +# include +#endif + +// Forward declare these two, and define them after all the container streams +// operators so that we can recurse from pair -> container -> container -> pair +// properly. +template +std::ostream& operator<<(std::ostream& out, const std::pair& p); + +@ac_google_start_namespace@ + +template +void PrintSequence(std::ostream& out, Iter begin, Iter end); + +@ac_google_end_namespace@ + +#define OUTPUT_TWO_ARG_CONTAINER(Sequence) \ +template \ +inline std::ostream& operator<<(std::ostream& out, \ + const Sequence& seq) { \ + @ac_google_namespace@::PrintSequence(out, seq.begin(), seq.end()); \ + return out; \ +} + +OUTPUT_TWO_ARG_CONTAINER(std::vector) +OUTPUT_TWO_ARG_CONTAINER(std::deque) +OUTPUT_TWO_ARG_CONTAINER(std::list) +#ifdef GLOG_STL_LOGGING_FOR_EXT_SLIST +OUTPUT_TWO_ARG_CONTAINER(__gnu_cxx::slist) +#endif + +#undef OUTPUT_TWO_ARG_CONTAINER + +#define OUTPUT_THREE_ARG_CONTAINER(Sequence) \ +template \ +inline std::ostream& operator<<(std::ostream& out, \ + const Sequence& seq) { \ + @ac_google_namespace@::PrintSequence(out, seq.begin(), seq.end()); \ + return out; \ +} + +OUTPUT_THREE_ARG_CONTAINER(std::set) +OUTPUT_THREE_ARG_CONTAINER(std::multiset) + +#undef OUTPUT_THREE_ARG_CONTAINER + +#define OUTPUT_FOUR_ARG_CONTAINER(Sequence) \ +template \ +inline std::ostream& operator<<(std::ostream& out, \ + const Sequence& seq) { \ + @ac_google_namespace@::PrintSequence(out, seq.begin(), seq.end()); \ + return out; \ +} + +OUTPUT_FOUR_ARG_CONTAINER(std::map) +OUTPUT_FOUR_ARG_CONTAINER(std::multimap) +#if defined(GLOG_STL_LOGGING_FOR_UNORDERED) && __cplusplus >= 201103L +OUTPUT_FOUR_ARG_CONTAINER(std::unordered_set) +OUTPUT_FOUR_ARG_CONTAINER(std::unordered_multiset) +#endif +#ifdef GLOG_STL_LOGGING_FOR_TR1_UNORDERED +OUTPUT_FOUR_ARG_CONTAINER(std::tr1::unordered_set) +OUTPUT_FOUR_ARG_CONTAINER(std::tr1::unordered_multiset) +#endif +#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH +OUTPUT_FOUR_ARG_CONTAINER(__gnu_cxx::hash_set) +OUTPUT_FOUR_ARG_CONTAINER(__gnu_cxx::hash_multiset) +#endif + +#undef OUTPUT_FOUR_ARG_CONTAINER + +#define OUTPUT_FIVE_ARG_CONTAINER(Sequence) \ +template \ +inline std::ostream& operator<<(std::ostream& out, \ + const Sequence& seq) { \ + @ac_google_namespace@::PrintSequence(out, seq.begin(), seq.end()); \ + return out; \ +} + +#if defined(GLOG_STL_LOGGING_FOR_UNORDERED) && __cplusplus >= 201103L +OUTPUT_FIVE_ARG_CONTAINER(std::unordered_map) +OUTPUT_FIVE_ARG_CONTAINER(std::unordered_multimap) +#endif +#ifdef GLOG_STL_LOGGING_FOR_TR1_UNORDERED +OUTPUT_FIVE_ARG_CONTAINER(std::tr1::unordered_map) +OUTPUT_FIVE_ARG_CONTAINER(std::tr1::unordered_multimap) +#endif +#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH +OUTPUT_FIVE_ARG_CONTAINER(__gnu_cxx::hash_map) +OUTPUT_FIVE_ARG_CONTAINER(__gnu_cxx::hash_multimap) +#endif + +#undef OUTPUT_FIVE_ARG_CONTAINER + +template +inline std::ostream& operator<<(std::ostream& out, + const std::pair& p) { + out << '(' << p.first << ", " << p.second << ')'; + return out; +} + +@ac_google_start_namespace@ + +template +inline void PrintSequence(std::ostream& out, Iter begin, Iter end) { + // Output at most 100 elements -- appropriate if used for logging. + for (int i = 0; begin != end && i < 100; ++i, ++begin) { + if (i > 0) out << ' '; + out << *begin; + } + if (begin != end) { + out << " ..."; + } +} + +@ac_google_end_namespace@ + +// Note that this is technically undefined behavior! We are adding things into +// the std namespace for a reason though -- we are providing new operations on +// types which are themselves defined with this namespace. Without this, these +// operator overloads cannot be found via ADL. If these definitions are not +// found via ADL, they must be #included before they're used, which requires +// this header to be included before apparently independent other headers. +// +// For example, base/logging.h defines various template functions to implement +// CHECK_EQ(x, y) and stream x and y into the log in the event the check fails. +// It does so via the function template MakeCheckOpValueString: +// template +// void MakeCheckOpValueString(strstream* ss, const T& v) { +// (*ss) << v; +// } +// Because 'glog/logging.h' is included before 'glog/stl_logging.h', +// subsequent CHECK_EQ(v1, v2) for vector<...> typed variable v1 and v2 can only +// find these operator definitions via ADL. +// +// Even this solution has problems -- it may pull unintended operators into the +// namespace as well, allowing them to also be found via ADL, and creating code +// that only works with a particular order of includes. Long term, we need to +// move all of the *definitions* into namespace std, bet we need to ensure no +// one references them first. This lets us take that step. We cannot define them +// in both because that would create ambiguous overloads when both are found. +namespace std { using ::operator<<; } + +#endif // UTIL_GTL_STL_LOGGING_INL_H_ diff --git a/third_party/glog/src/glog/vlog_is_on.h.in b/third_party/glog/src/glog/vlog_is_on.h.in new file mode 100644 index 0000000..7526fc3 --- /dev/null +++ b/third_party/glog/src/glog/vlog_is_on.h.in @@ -0,0 +1,118 @@ +// Copyright (c) 1999, 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Ray Sidney and many others +// +// Defines the VLOG_IS_ON macro that controls the variable-verbosity +// conditional logging. +// +// It's used by VLOG and VLOG_IF in logging.h +// and by RAW_VLOG in raw_logging.h to trigger the logging. +// +// It can also be used directly e.g. like this: +// if (VLOG_IS_ON(2)) { +// // do some logging preparation and logging +// // that can't be accomplished e.g. via just VLOG(2) << ...; +// } +// +// The truth value that VLOG_IS_ON(level) returns is determined by +// the three verbosity level flags: +// --v= Gives the default maximal active V-logging level; +// 0 is the default. +// Normally positive values are used for V-logging levels. +// --vmodule= Gives the per-module maximal V-logging levels to override +// the value given by --v. +// E.g. "my_module=2,foo*=3" would change the logging level +// for all code in source files "my_module.*" and "foo*.*" +// ("-inl" suffixes are also disregarded for this matching). +// +// SetVLOGLevel helper function is provided to do limited dynamic control over +// V-logging by overriding the per-module settings given via --vmodule flag. +// +// CAVEAT: --vmodule functionality is not available in non gcc compilers. +// + +#ifndef BASE_VLOG_IS_ON_H_ +#define BASE_VLOG_IS_ON_H_ + +#include + +#if defined(__GNUC__) +// We emit an anonymous static int* variable at every VLOG_IS_ON(n) site. +// (Normally) the first time every VLOG_IS_ON(n) site is hit, +// we determine what variable will dynamically control logging at this site: +// it's either FLAGS_v or an appropriate internal variable +// matching the current source file that represents results of +// parsing of --vmodule flag and/or SetVLOGLevel calls. +#define VLOG_IS_ON(verboselevel) \ + __extension__ \ + ({ static @ac_google_namespace@::SiteFlag vlocal__ = {NULL, NULL, 0, NULL}; \ + @ac_google_namespace@::int32 verbose_level__ = (verboselevel); \ + (vlocal__.level == NULL ? @ac_google_namespace@::InitVLOG3__(&vlocal__, &FLAGS_v, \ + __FILE__, verbose_level__) : *vlocal__.level >= verbose_level__); \ + }) +#else +// GNU extensions not available, so we do not support --vmodule. +// Dynamic value of FLAGS_v always controls the logging level. +#define VLOG_IS_ON(verboselevel) (FLAGS_v >= (verboselevel)) +#endif + +// Set VLOG(_IS_ON) level for module_pattern to log_level. +// This lets us dynamically control what is normally set by the --vmodule flag. +// Returns the level that previously applied to module_pattern. +// NOTE: To change the log level for VLOG(_IS_ON) sites +// that have already executed after/during InitGoogleLogging, +// one needs to supply the exact --vmodule pattern that applied to them. +// (If no --vmodule pattern applied to them +// the value of FLAGS_v will continue to control them.) +extern GLOG_EXPORT int SetVLOGLevel(const char* module_pattern, int log_level); + +// Various declarations needed for VLOG_IS_ON above: ========================= + +struct SiteFlag { + @ac_google_namespace@::int32* level; + const char* base_name; + size_t base_len; + SiteFlag* next; +}; + +// Helper routine which determines the logging info for a particalur VLOG site. +// site_flag is the address of the site-local pointer to the controlling +// verbosity level +// site_default is the default to use for *site_flag +// fname is the current source file name +// verbose_level is the argument to VLOG_IS_ON +// We will return the return value for VLOG_IS_ON +// and if possible set *site_flag appropriately. +extern GLOG_EXPORT bool InitVLOG3__( + @ac_google_namespace@::SiteFlag* site_flag, + @ac_google_namespace@::int32* site_default, const char* fname, + @ac_google_namespace@::int32 verbose_level); + +#endif // BASE_VLOG_IS_ON_H_ diff --git a/third_party/glog/src/googletest.h b/third_party/glog/src/googletest.h new file mode 100644 index 0000000..5761361 --- /dev/null +++ b/third_party/glog/src/googletest.h @@ -0,0 +1,672 @@ +// Copyright (c) 2009, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Shinichiro Hamaji +// (based on googletest: http://code.google.com/p/googletest/) + +#ifdef GOOGLETEST_H__ +#error You must not include this file twice. +#endif +#define GOOGLETEST_H__ + +#include "utilities.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#ifdef HAVE_UNISTD_H +# include +#endif + +#include "base/commandlineflags.h" + +#if __cplusplus < 201103L && !defined(_MSC_VER) +#define GOOGLE_GLOG_THROW_BAD_ALLOC throw (std::bad_alloc) +#else +#define GOOGLE_GLOG_THROW_BAD_ALLOC +#endif + +using std::map; +using std::string; +using std::vector; + +_START_GOOGLE_NAMESPACE_ + +extern GLOG_EXPORT void (*g_logging_fail_func)(); + +_END_GOOGLE_NAMESPACE_ + +#undef GLOG_EXPORT +#define GLOG_EXPORT + +static inline string GetTempDir() { + vector temp_directories_list; + google::GetExistingTempDirectories(&temp_directories_list); + + if (temp_directories_list.empty()) { + fprintf(stderr, "No temporary directory found\n"); + exit(EXIT_FAILURE); + } + + // Use first directory from list of existing temporary directories. + return temp_directories_list.front(); +} + +#if defined(GLOG_OS_WINDOWS) && defined(_MSC_VER) && !defined(TEST_SRC_DIR) +// The test will run in glog/vsproject/ +// (e.g., glog/vsproject/logging_unittest). +static const char TEST_SRC_DIR[] = "../.."; +#elif !defined(TEST_SRC_DIR) +# warning TEST_SRC_DIR should be defined in config.h +static const char TEST_SRC_DIR[] = "."; +#endif + +static const uint32_t PTR_TEST_VALUE = 0x12345678; + +DEFINE_string(test_tmpdir, GetTempDir(), "Dir we use for temp files"); +DEFINE_string(test_srcdir, TEST_SRC_DIR, + "Source-dir root, needed to find glog_unittest_flagfile"); +DEFINE_bool(run_benchmark, false, "If true, run benchmarks"); +#ifdef NDEBUG +DEFINE_int32(benchmark_iters, 100000000, "Number of iterations per benchmark"); +#else +DEFINE_int32(benchmark_iters, 100000, "Number of iterations per benchmark"); +#endif + +#ifdef HAVE_LIB_GTEST +# include +// Use our ASSERT_DEATH implementation. +# undef ASSERT_DEATH +# undef ASSERT_DEBUG_DEATH +using testing::InitGoogleTest; +#else + +_START_GOOGLE_NAMESPACE_ + +void InitGoogleTest(int*, char**); + +void InitGoogleTest(int*, char**) {} + +// The following is some bare-bones testing infrastructure + +#define EXPECT_NEAR(val1, val2, abs_error) \ + do { \ + if (abs(val1 - val2) > abs_error) { \ + fprintf(stderr, "Check failed: %s within %s of %s\n", #val1, #abs_error, \ + #val2); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) + +#define EXPECT_TRUE(cond) \ + do { \ + if (!(cond)) { \ + fprintf(stderr, "Check failed: %s\n", #cond); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) + +#define EXPECT_FALSE(cond) EXPECT_TRUE(!(cond)) + +#define EXPECT_OP(op, val1, val2) \ + do { \ + if (!((val1) op (val2))) { \ + fprintf(stderr, "Check failed: %s %s %s\n", #val1, #op, #val2); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) + +#define EXPECT_EQ(val1, val2) EXPECT_OP(==, val1, val2) +#define EXPECT_NE(val1, val2) EXPECT_OP(!=, val1, val2) +#define EXPECT_GT(val1, val2) EXPECT_OP(>, val1, val2) +#define EXPECT_LT(val1, val2) EXPECT_OP(<, val1, val2) + +#define EXPECT_NAN(arg) \ + do { \ + if (!isnan(arg)) { \ + fprintf(stderr, "Check failed: isnan(%s)\n", #arg); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) + +#define EXPECT_INF(arg) \ + do { \ + if (!isinf(arg)) { \ + fprintf(stderr, "Check failed: isinf(%s)\n", #arg); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) + +#define EXPECT_DOUBLE_EQ(val1, val2) \ + do { \ + if (((val1) < (val2) - 0.001 || (val1) > (val2) + 0.001)) { \ + fprintf(stderr, "Check failed: %s == %s\n", #val1, #val2); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) + +#define EXPECT_STREQ(val1, val2) \ + do { \ + if (strcmp((val1), (val2)) != 0) { \ + fprintf(stderr, "Check failed: streq(%s, %s)\n", #val1, #val2); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) + +vector g_testlist; // the tests to run + +#define TEST(a, b) \ + struct Test_##a##_##b { \ + Test_##a##_##b() { g_testlist.push_back(&Run); } \ + static void Run() { FlagSaver fs; RunTest(); } \ + static void RunTest(); \ + }; \ + static Test_##a##_##b g_test_##a##_##b; \ + void Test_##a##_##b::RunTest() + + +static inline int RUN_ALL_TESTS() { + vector::const_iterator it; + for (it = g_testlist.begin(); it != g_testlist.end(); ++it) { + (*it)(); + } + fprintf(stderr, "Passed %d tests\n\nPASS\n", + static_cast(g_testlist.size())); + return 0; +} + +_END_GOOGLE_NAMESPACE_ + +#endif // ! HAVE_LIB_GTEST + +_START_GOOGLE_NAMESPACE_ + +static bool g_called_abort; +static jmp_buf g_jmp_buf; +static inline void CalledAbort() { + g_called_abort = true; + longjmp(g_jmp_buf, 1); +} + +#ifdef GLOG_OS_WINDOWS +// TODO(hamaji): Death test somehow doesn't work in Windows. +#define ASSERT_DEATH(fn, msg) +#else +#define ASSERT_DEATH(fn, msg) \ + do { \ + g_called_abort = false; \ + /* in logging.cc */ \ + void (*original_logging_fail_func)() = g_logging_fail_func; \ + g_logging_fail_func = &CalledAbort; \ + if (!setjmp(g_jmp_buf)) fn; \ + /* set back to their default */ \ + g_logging_fail_func = original_logging_fail_func; \ + if (!g_called_abort) { \ + fprintf(stderr, "Function didn't die (%s): %s\n", msg, #fn); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) +#endif + +#ifdef NDEBUG +#define ASSERT_DEBUG_DEATH(fn, msg) +#else +#define ASSERT_DEBUG_DEATH(fn, msg) ASSERT_DEATH(fn, msg) +#endif // NDEBUG + +// Benchmark tools. + +#define BENCHMARK(n) static BenchmarkRegisterer __benchmark_ ## n (#n, &n); + +map g_benchlist; // the benchmarks to run + +class BenchmarkRegisterer { + public: + BenchmarkRegisterer(const char* name, void (*function)(int iters)) { + EXPECT_TRUE(g_benchlist.insert(std::make_pair(name, function)).second); + } +}; + +static inline void RunSpecifiedBenchmarks() { + if (!FLAGS_run_benchmark) { + return; + } + + int iter_cnt = FLAGS_benchmark_iters; + puts("Benchmark\tTime(ns)\tIterations"); + for (map::const_iterator iter = g_benchlist.begin(); + iter != g_benchlist.end(); + ++iter) { + clock_t start = clock(); + iter->second(iter_cnt); + double elapsed_ns = (static_cast(clock()) - start) / + CLOCKS_PER_SEC * 1000 * 1000 * 1000; +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat=" +#endif + printf("%s\t%8.2lf\t%10d\n", + iter->first.c_str(), elapsed_ns / iter_cnt, iter_cnt); +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic pop +#endif + } + puts(""); +} + +// ---------------------------------------------------------------------- +// Golden file functions +// ---------------------------------------------------------------------- + +class CapturedStream { + public: + CapturedStream(int fd, const string & filename) : + fd_(fd), + uncaptured_fd_(-1), + filename_(filename) { + Capture(); + } + + ~CapturedStream() { + if (uncaptured_fd_ != -1) { + CHECK(close(uncaptured_fd_) != -1); + } + } + + // Start redirecting output to a file + void Capture() { + // Keep original stream for later + CHECK(uncaptured_fd_ == -1) << ", Stream " << fd_ << " already captured!"; + uncaptured_fd_ = dup(fd_); + CHECK(uncaptured_fd_ != -1); + + // Open file to save stream to + int cap_fd = open(filename_.c_str(), + O_CREAT | O_TRUNC | O_WRONLY, + S_IRUSR | S_IWUSR); + CHECK(cap_fd != -1); + + // Send stdout/stderr to this file + fflush(NULL); + CHECK(dup2(cap_fd, fd_) != -1); + CHECK(close(cap_fd) != -1); + } + + // Remove output redirection + void StopCapture() { + // Restore original stream + if (uncaptured_fd_ != -1) { + fflush(NULL); + CHECK(dup2(uncaptured_fd_, fd_) != -1); + } + } + + const string & filename() const { return filename_; } + + private: + int fd_; // file descriptor being captured + int uncaptured_fd_; // where the stream was originally being sent to + string filename_; // file where stream is being saved +}; +static CapturedStream * s_captured_streams[STDERR_FILENO+1]; +// Redirect a file descriptor to a file. +// fd - Should be STDOUT_FILENO or STDERR_FILENO +// filename - File where output should be stored +static inline void CaptureTestOutput(int fd, const string & filename) { + CHECK((fd == STDOUT_FILENO) || (fd == STDERR_FILENO)); + CHECK(s_captured_streams[fd] == NULL); + s_captured_streams[fd] = new CapturedStream(fd, filename); +} +static inline void CaptureTestStdout() { + CaptureTestOutput(STDOUT_FILENO, FLAGS_test_tmpdir + "/captured.out"); +} +static inline void CaptureTestStderr() { + CaptureTestOutput(STDERR_FILENO, FLAGS_test_tmpdir + "/captured.err"); +} +// Return the size (in bytes) of a file +static inline size_t GetFileSize(FILE * file) { + fseek(file, 0, SEEK_END); + return static_cast(ftell(file)); +} +// Read the entire content of a file as a string +static inline string ReadEntireFile(FILE * file) { + const size_t file_size = GetFileSize(file); + char * const buffer = new char[file_size]; + + size_t bytes_last_read = 0; // # of bytes read in the last fread() + size_t bytes_read = 0; // # of bytes read so far + + fseek(file, 0, SEEK_SET); + + // Keep reading the file until we cannot read further or the + // pre-determined file size is reached. + do { + bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); + bytes_read += bytes_last_read; + } while (bytes_last_read > 0 && bytes_read < file_size); + + const string content = string(buffer, buffer+bytes_read); + delete[] buffer; + + return content; +} +// Get the captured stdout (when fd is STDOUT_FILENO) or stderr (when +// fd is STDERR_FILENO) as a string +static inline string GetCapturedTestOutput(int fd) { + CHECK(fd == STDOUT_FILENO || fd == STDERR_FILENO); + CapturedStream * const cap = s_captured_streams[fd]; + CHECK(cap) + << ": did you forget CaptureTestStdout() or CaptureTestStderr()?"; + + // Make sure everything is flushed. + cap->StopCapture(); + + // Read the captured file. + FILE * const file = fopen(cap->filename().c_str(), "r"); + const string content = ReadEntireFile(file); + fclose(file); + + delete cap; + s_captured_streams[fd] = NULL; + + return content; +} +// Get the captured stderr of a test as a string. +static inline string GetCapturedTestStderr() { + return GetCapturedTestOutput(STDERR_FILENO); +} + +static const std::size_t kLoggingPrefixLength = 9; + +// Check if the string is [IWEF](\d{8}|YEARDATE) +static inline bool IsLoggingPrefix(const string& s) { + if (s.size() != kLoggingPrefixLength) { + return false; + } + if (!strchr("IWEF", s[0])) return false; + for (size_t i = 1; i <= 8; ++i) { + if (!isdigit(s[i]) && s[i] != "YEARDATE"[i-1]) return false; + } + return true; +} + +// Convert log output into normalized form. +// +// Example: +// I20200102 030405 logging_unittest.cc:345] RAW: vlog -1 +// => IYEARDATE TIME__ logging_unittest.cc:LINE] RAW: vlog -1 +static inline string MungeLine(const string& line) { + string before, logcode_date, time, thread_lineinfo; + std::size_t begin_of_logging_prefix = 0; + for (; begin_of_logging_prefix + kLoggingPrefixLength < line.size(); + ++begin_of_logging_prefix) { + if (IsLoggingPrefix( + line.substr(begin_of_logging_prefix, kLoggingPrefixLength))) { + break; + } + } + if (begin_of_logging_prefix + kLoggingPrefixLength >= line.size()) { + return line; + } else if (begin_of_logging_prefix > 0) { + before = line.substr(0, begin_of_logging_prefix - 1); + } + std::istringstream iss(line.substr(begin_of_logging_prefix)); + iss >> logcode_date; + iss >> time; + iss >> thread_lineinfo; + CHECK(!thread_lineinfo.empty()); + if (thread_lineinfo[thread_lineinfo.size() - 1] != ']') { + // We found thread ID. + string tmp; + iss >> tmp; + CHECK(!tmp.empty()); + CHECK_EQ(']', tmp[tmp.size() - 1]); + thread_lineinfo = "THREADID " + tmp; + } + size_t index = thread_lineinfo.find(':'); + CHECK_NE(string::npos, index); + thread_lineinfo = thread_lineinfo.substr(0, index+1) + "LINE]"; + string rest; + std::getline(iss, rest); + return (before + logcode_date[0] + "YEARDATE TIME__ " + thread_lineinfo + + MungeLine(rest)); +} + +static inline void StringReplace(string* str, + const string& oldsub, + const string& newsub) { + size_t pos = str->find(oldsub); + if (pos != string::npos) { + str->replace(pos, oldsub.size(), newsub); + } +} + +static inline string Munge(const string& filename) { + FILE* fp = fopen(filename.c_str(), "rb"); + CHECK(fp != NULL) << filename << ": couldn't open"; + char buf[4096]; + string result; + while (fgets(buf, 4095, fp)) { + string line = MungeLine(buf); + const size_t str_size = 256; + char null_str[str_size]; + char ptr_str[str_size]; + snprintf(null_str, str_size, "%p", static_cast(NULL)); + snprintf(ptr_str, str_size, "%p", reinterpret_cast(PTR_TEST_VALUE)); + + StringReplace(&line, "__NULLP__", null_str); + StringReplace(&line, "__PTRTEST__", ptr_str); + + StringReplace(&line, "__SUCCESS__", StrError(0)); + StringReplace(&line, "__ENOENT__", StrError(ENOENT)); + StringReplace(&line, "__EINTR__", StrError(EINTR)); + StringReplace(&line, "__ENXIO__", StrError(ENXIO)); + StringReplace(&line, "__ENOEXEC__", StrError(ENOEXEC)); + result += line + "\n"; + } + fclose(fp); + return result; +} + +static inline void WriteToFile(const string& body, const string& file) { + FILE* fp = fopen(file.c_str(), "wb"); + fwrite(body.data(), 1, body.size(), fp); + fclose(fp); +} + +static inline bool MungeAndDiffTest(const string& golden_filename, + CapturedStream* cap) { + if (cap == s_captured_streams[STDOUT_FILENO]) { + CHECK(cap) << ": did you forget CaptureTestStdout()?"; + } else { + CHECK(cap) << ": did you forget CaptureTestStderr()?"; + } + + cap->StopCapture(); + + // Run munge + const string captured = Munge(cap->filename()); + const string golden = Munge(golden_filename); + if (captured != golden) { + fprintf(stderr, + "Test with golden file failed. We'll try to show the diff:\n"); + string munged_golden = golden_filename + ".munged"; + WriteToFile(golden, munged_golden); + string munged_captured = cap->filename() + ".munged"; + WriteToFile(captured, munged_captured); +#ifdef GLOG_OS_WINDOWS + string diffcmd("fc " + munged_golden + " " + munged_captured); +#else + string diffcmd("diff -u " + munged_golden + " " + munged_captured); +#endif + if (system(diffcmd.c_str()) != 0) { + fprintf(stderr, "diff command was failed.\n"); + } + unlink(munged_golden.c_str()); + unlink(munged_captured.c_str()); + return false; + } + LOG(INFO) << "Diff was successful"; + return true; +} + +static inline bool MungeAndDiffTestStderr(const string& golden_filename) { + return MungeAndDiffTest(golden_filename, s_captured_streams[STDERR_FILENO]); +} + +static inline bool MungeAndDiffTestStdout(const string& golden_filename) { + return MungeAndDiffTest(golden_filename, s_captured_streams[STDOUT_FILENO]); +} + +// Save flags used from logging_unittest.cc. +#ifndef HAVE_LIB_GFLAGS +struct FlagSaver { + FlagSaver() + : v_(FLAGS_v), + stderrthreshold_(FLAGS_stderrthreshold), + logtostderr_(FLAGS_logtostderr), + alsologtostderr_(FLAGS_alsologtostderr) {} + ~FlagSaver() { + FLAGS_v = v_; + FLAGS_stderrthreshold = stderrthreshold_; + FLAGS_logtostderr = logtostderr_; + FLAGS_alsologtostderr = alsologtostderr_; + } + int v_; + int stderrthreshold_; + bool logtostderr_; + bool alsologtostderr_; +}; +#endif + +class Thread { + public: + virtual ~Thread() {} + + void SetJoinable(bool) {} +#if defined(GLOG_OS_WINDOWS) && !defined(GLOG_OS_CYGWIN) + void Start() { + handle_ = CreateThread(NULL, + 0, + &Thread::InvokeThreadW, + this, + 0, + &th_); + CHECK(handle_) << "CreateThread"; + } + void Join() { + WaitForSingleObject(handle_, INFINITE); + } +#elif defined(HAVE_PTHREAD) + void Start() { + pthread_create(&th_, NULL, &Thread::InvokeThread, this); + } + void Join() { + pthread_join(th_, NULL); + } +#else +# error No thread implementation. +#endif + + protected: + virtual void Run() = 0; + + private: + static void* InvokeThread(void* self) { + (static_cast(self))->Run(); + return NULL; + } + +#if defined(GLOG_OS_WINDOWS) && !defined(GLOG_OS_CYGWIN) + static DWORD __stdcall InvokeThreadW(LPVOID self) { + InvokeThread(self); + return 0; + } + HANDLE handle_; + DWORD th_; +#else + pthread_t th_; +#endif +}; + +static inline void SleepForMilliseconds(unsigned t) { +#ifndef GLOG_OS_WINDOWS +# if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L + const struct timespec req = {0, t * 1000 * 1000}; + nanosleep(&req, NULL); +# else + usleep(t * 1000); +# endif +#else + Sleep(t); +#endif +} + +// Add hook for operator new to ensure there are no memory allocation. + +void (*g_new_hook)() = NULL; + +_END_GOOGLE_NAMESPACE_ + +void* operator new(size_t size) GOOGLE_GLOG_THROW_BAD_ALLOC { + if (GOOGLE_NAMESPACE::g_new_hook) { + GOOGLE_NAMESPACE::g_new_hook(); + } + return malloc(size); +} + +void* operator new[](size_t size) GOOGLE_GLOG_THROW_BAD_ALLOC { + return ::operator new(size); +} + +void operator delete(void* p) throw() { + free(p); +} + +void operator delete(void* p, size_t) throw() { + ::operator delete(p); +} + +void operator delete[](void* p) throw() { + ::operator delete(p); +} + +void operator delete[](void* p, size_t) throw() { + ::operator delete(p); +} diff --git a/third_party/glog/src/logging.cc b/third_party/glog/src/logging.cc new file mode 100644 index 0000000..4028ccc --- /dev/null +++ b/third_party/glog/src/logging.cc @@ -0,0 +1,2691 @@ +// Copyright (c) 1999, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite() + +#include "utilities.h" + +#include +#include +#include +#include +#ifdef HAVE_UNISTD_H +# include // For _exit. +#endif +#include +#include +#include +#ifdef HAVE_SYS_UTSNAME_H +# include // For uname. +#endif +#include +#include +#include +#include +#include +#include +#ifdef HAVE_PWD_H +# include +#endif +#ifdef HAVE_SYSLOG_H +# include +#endif +#include +#include // for errno +#include +#ifdef GLOG_OS_WINDOWS +#include "windows/dirent.h" +#else +#include // for automatic removal of old logs +#endif +#include "base/commandlineflags.h" // to get the program name +#include +#include +#include "base/googleinit.h" + +#ifdef HAVE_STACKTRACE +# include "stacktrace.h" +#endif + +#ifdef __ANDROID__ +#include +#endif + +using std::string; +using std::vector; +using std::setw; +using std::setfill; +using std::hex; +using std::dec; +using std::min; +using std::ostream; +using std::ostringstream; + +using std::FILE; +using std::fwrite; +using std::fclose; +using std::fflush; +using std::fprintf; +using std::perror; + +#ifdef __QNX__ +using std::fdopen; +#endif + +#ifdef _WIN32 +#define fdopen _fdopen +#endif + +// There is no thread annotation support. +#define EXCLUSIVE_LOCKS_REQUIRED(mu) + +static bool BoolFromEnv(const char *varname, bool defval) { + const char* const valstr = getenv(varname); + if (!valstr) { + return defval; + } + return memchr("tTyY1\0", valstr[0], 6) != NULL; +} + +GLOG_DEFINE_bool(timestamp_in_logfile_name, + BoolFromEnv("GOOGLE_TIMESTAMP_IN_LOGFILE_NAME", true), + "put a timestamp at the end of the log file name"); +GLOG_DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false), + "log messages go to stderr instead of logfiles"); +GLOG_DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false), + "log messages go to stderr in addition to logfiles"); +GLOG_DEFINE_bool(colorlogtostderr, false, + "color messages logged to stderr (if supported by terminal)"); +GLOG_DEFINE_bool(colorlogtostdout, false, + "color messages logged to stdout (if supported by terminal)"); +GLOG_DEFINE_bool(logtostdout, BoolFromEnv("GOOGLE_LOGTOSTDOUT", false), + "log messages go to stdout instead of logfiles"); +#ifdef GLOG_OS_LINUX +GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. " + "Logs can grow very quickly and they are rarely read before they " + "need to be evicted from memory. Instead, drop them from memory " + "as soon as they are flushed to disk."); +#endif + +// By default, errors (including fatal errors) get logged to stderr as +// well as the file. +// +// The default is ERROR instead of FATAL so that users can see problems +// when they run a program without having to look in another file. +DEFINE_int32(stderrthreshold, + GOOGLE_NAMESPACE::GLOG_ERROR, + "log messages at or above this level are copied to stderr in " + "addition to logfiles. This flag obsoletes --alsologtostderr."); + +GLOG_DEFINE_string(alsologtoemail, "", + "log messages go to these email addresses " + "in addition to logfiles"); +GLOG_DEFINE_bool(log_prefix, true, + "Prepend the log prefix to the start of each log line"); +GLOG_DEFINE_bool(log_year_in_prefix, true, + "Include the year in the log prefix"); +GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't " + "actually get logged anywhere"); +GLOG_DEFINE_int32(logbuflevel, 0, + "Buffer log messages logged at this level or lower" + " (-1 means don't buffer; 0 means buffer INFO only;" + " ...)"); +GLOG_DEFINE_int32(logbufsecs, 30, + "Buffer log messages for at most this many seconds"); + +GLOG_DEFINE_int32(logcleansecs, 60 * 5, // every 5 minutes + "Clean overdue logs every this many seconds"); + +GLOG_DEFINE_int32(logemaillevel, 999, + "Email log messages logged at this level or higher" + " (0 means email all; 3 means email FATAL only;" + " ...)"); +GLOG_DEFINE_string(logmailer, "", + "Mailer used to send logging email"); + +// Compute the default value for --log_dir +static const char* DefaultLogDir() { + const char* env; + env = getenv("GOOGLE_LOG_DIR"); + if (env != NULL && env[0] != '\0') { + return env; + } + env = getenv("TEST_TMPDIR"); + if (env != NULL && env[0] != '\0') { + return env; + } + return ""; +} + +GLOG_DEFINE_int32(logfile_mode, 0664, "Log file mode/permissions."); + +GLOG_DEFINE_string(log_dir, DefaultLogDir(), + "If specified, logfiles are written into this directory instead " + "of the default logging directory."); +GLOG_DEFINE_string(log_link, "", "Put additional links to the log " + "files in this directory"); + +GLOG_DEFINE_uint32(max_log_size, 1800, + "approx. maximum log file size (in MB). A value of 0 will " + "be silently overridden to 1."); + +GLOG_DEFINE_bool(stop_logging_if_full_disk, false, + "Stop attempting to log to disk if the disk is full."); + +GLOG_DEFINE_string(log_backtrace_at, "", + "Emit a backtrace when logging at file:linenum."); + +GLOG_DEFINE_bool(log_utc_time, false, + "Use UTC time for logging."); + +// TODO(hamaji): consider windows +#define PATH_SEPARATOR '/' + +#ifndef HAVE_PREAD +#if defined(GLOG_OS_WINDOWS) +#include +#define ssize_t SSIZE_T +#endif +static ssize_t pread(int fd, void* buf, size_t count, off_t offset) { + off_t orig_offset = lseek(fd, 0, SEEK_CUR); + if (orig_offset == (off_t)-1) + return -1; + if (lseek(fd, offset, SEEK_CUR) == (off_t)-1) + return -1; + ssize_t len = read(fd, buf, count); + if (len < 0) + return len; + if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1) + return -1; + return len; +} +#endif // !HAVE_PREAD + +#ifndef HAVE_PWRITE +static ssize_t pwrite(int fd, void* buf, size_t count, off_t offset) { + off_t orig_offset = lseek(fd, 0, SEEK_CUR); + if (orig_offset == (off_t)-1) + return -1; + if (lseek(fd, offset, SEEK_CUR) == (off_t)-1) + return -1; + ssize_t len = write(fd, buf, count); + if (len < 0) + return len; + if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1) + return -1; + return len; +} +#endif // !HAVE_PWRITE + +static void GetHostName(string* hostname) { +#if defined(HAVE_SYS_UTSNAME_H) + struct utsname buf; + if (uname(&buf) < 0) { + // ensure null termination on failure + *buf.nodename = '\0'; + } + *hostname = buf.nodename; +#elif defined(GLOG_OS_WINDOWS) + char buf[MAX_COMPUTERNAME_LENGTH + 1]; + DWORD len = MAX_COMPUTERNAME_LENGTH + 1; + if (GetComputerNameA(buf, &len)) { + *hostname = buf; + } else { + hostname->clear(); + } +#else +# warning There is no way to retrieve the host name. + *hostname = "(unknown)"; +#endif +} + +// Returns true iff terminal supports using colors in output. +static bool TerminalSupportsColor() { + bool term_supports_color = false; +#ifdef GLOG_OS_WINDOWS + // on Windows TERM variable is usually not set, but the console does + // support colors. + term_supports_color = true; +#else + // On non-Windows platforms, we rely on the TERM variable. + const char* const term = getenv("TERM"); + if (term != NULL && term[0] != '\0') { + term_supports_color = + !strcmp(term, "xterm") || + !strcmp(term, "xterm-color") || + !strcmp(term, "xterm-256color") || + !strcmp(term, "screen-256color") || + !strcmp(term, "konsole") || + !strcmp(term, "konsole-16color") || + !strcmp(term, "konsole-256color") || + !strcmp(term, "screen") || + !strcmp(term, "linux") || + !strcmp(term, "cygwin"); + } +#endif + return term_supports_color; +} + +_START_GOOGLE_NAMESPACE_ + +enum GLogColor { + COLOR_DEFAULT, + COLOR_RED, + COLOR_GREEN, + COLOR_YELLOW +}; + +static GLogColor SeverityToColor(LogSeverity severity) { + assert(severity >= 0 && severity < NUM_SEVERITIES); + GLogColor color = COLOR_DEFAULT; + switch (severity) { + case GLOG_INFO: + color = COLOR_DEFAULT; + break; + case GLOG_WARNING: + color = COLOR_YELLOW; + break; + case GLOG_ERROR: + case GLOG_FATAL: + color = COLOR_RED; + break; + default: + // should never get here. + assert(false); + } + return color; +} + +#ifdef GLOG_OS_WINDOWS + +// Returns the character attribute for the given color. +static WORD GetColorAttribute(GLogColor color) { + switch (color) { + case COLOR_RED: return FOREGROUND_RED; + case COLOR_GREEN: return FOREGROUND_GREEN; + case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; + default: return 0; + } +} + +#else + +// Returns the ANSI color code for the given color. +static const char* GetAnsiColorCode(GLogColor color) { + switch (color) { + case COLOR_RED: return "1"; + case COLOR_GREEN: return "2"; + case COLOR_YELLOW: return "3"; + case COLOR_DEFAULT: return ""; + }; + return NULL; // stop warning about return type. +} + +#endif // GLOG_OS_WINDOWS + +// Safely get max_log_size, overriding to 1 if it somehow gets defined as 0 +static uint32 MaxLogSize() { + return (FLAGS_max_log_size > 0 && FLAGS_max_log_size < 4096 + ? FLAGS_max_log_size + : 1); +} + +// An arbitrary limit on the length of a single log message. This +// is so that streaming can be done more efficiently. +const size_t LogMessage::kMaxLogMessageLen = 30000; + +struct LogMessage::LogMessageData { + LogMessageData(); + + int preserved_errno_; // preserved errno + // Buffer space; contains complete message text. + char message_text_[LogMessage::kMaxLogMessageLen+1]; + LogStream stream_; + char severity_; // What level is this LogMessage logged at? + int line_; // line number where logging call is. + void (LogMessage::*send_method_)(); // Call this in destructor to send + union { // At most one of these is used: union to keep the size low. + LogSink* sink_; // NULL or sink to send message to + std::vector* outvec_; // NULL or vector to push message onto + std::string* message_; // NULL or string to write message into + }; + size_t num_prefix_chars_; // # of chars of prefix in this message + size_t num_chars_to_log_; // # of chars of msg to send to log + size_t num_chars_to_syslog_; // # of chars of msg to send to syslog + const char* basename_; // basename of file that called LOG + const char* fullname_; // fullname of file that called LOG + bool has_been_flushed_; // false => data has not been flushed + bool first_fatal_; // true => this was first fatal msg + + private: + LogMessageData(const LogMessageData&); + void operator=(const LogMessageData&); +}; + +// A mutex that allows only one thread to log at a time, to keep things from +// getting jumbled. Some other very uncommon logging operations (like +// changing the destination file for log messages of a given severity) also +// lock this mutex. Please be sure that anybody who might possibly need to +// lock it does so. +static Mutex log_mutex; + +// Number of messages sent at each severity. Under log_mutex. +int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0}; + +// Globally disable log writing (if disk is full) +static bool stop_writing = false; + +const char*const LogSeverityNames[NUM_SEVERITIES] = { + "INFO", "WARNING", "ERROR", "FATAL" +}; + +// Has the user called SetExitOnDFatal(true)? +static bool exit_on_dfatal = true; + +const char* GetLogSeverityName(LogSeverity severity) { + return LogSeverityNames[severity]; +} + +static bool SendEmailInternal(const char*dest, const char *subject, + const char*body, bool use_logging); + +base::Logger::~Logger() { +} + +#ifdef GLOG_CUSTOM_PREFIX_SUPPORT +namespace { + // Optional user-configured callback to print custom prefixes. + CustomPrefixCallback custom_prefix_callback = NULL; + // User-provided data to pass to the callback: + void* custom_prefix_callback_data = NULL; +} +#endif + +namespace { + +// Encapsulates all file-system related state +class LogFileObject : public base::Logger { + public: + LogFileObject(LogSeverity severity, const char* base_filename); + ~LogFileObject(); + + virtual void Write(bool force_flush, // Should we force a flush here? + time_t timestamp, // Timestamp for this entry + const char* message, + size_t message_len); + + // Configuration options + void SetBasename(const char* basename); + void SetExtension(const char* ext); + void SetSymlinkBasename(const char* symlink_basename); + + // Normal flushing routine + virtual void Flush(); + + // It is the actual file length for the system loggers, + // i.e., INFO, ERROR, etc. + virtual uint32 LogSize() { + MutexLock l(&lock_); + return file_length_; + } + + // Internal flush routine. Exposed so that FlushLogFilesUnsafe() + // can avoid grabbing a lock. Usually Flush() calls it after + // acquiring lock_. + void FlushUnlocked(); + + private: + static const uint32 kRolloverAttemptFrequency = 0x20; + + Mutex lock_; + bool base_filename_selected_; + string base_filename_; + string symlink_basename_; + string filename_extension_; // option users can specify (eg to add port#) + FILE* file_; + LogSeverity severity_; + uint32 bytes_since_flush_; + uint32 dropped_mem_length_; + uint32 file_length_; + unsigned int rollover_attempt_; + int64 next_flush_time_; // cycle count at which to flush log + WallTime start_time_; + + // Actually create a logfile using the value of base_filename_ and the + // optional argument time_pid_string + // REQUIRES: lock_ is held + bool CreateLogfile(const string& time_pid_string); +}; + +// Encapsulate all log cleaner related states +class LogCleaner { + public: + LogCleaner(); + + // Setting overdue_days to 0 days will delete all logs. + void Enable(unsigned int overdue_days); + void Disable(); + + // update next_cleanup_time_ + void UpdateCleanUpTime(); + + void Run(bool base_filename_selected, + const string& base_filename, + const string& filename_extension); + + bool enabled() const { return enabled_; } + + private: + vector GetOverdueLogNames(string log_directory, unsigned int days, + const string& base_filename, + const string& filename_extension) const; + + bool IsLogFromCurrentProject(const string& filepath, + const string& base_filename, + const string& filename_extension) const; + + bool IsLogLastModifiedOver(const string& filepath, unsigned int days) const; + + bool enabled_; + unsigned int overdue_days_; + int64 next_cleanup_time_; // cycle count at which to clean overdue log +}; + +LogCleaner log_cleaner; + +} // namespace + +class LogDestination { + public: + friend class LogMessage; + friend void ReprintFatalMessage(); + friend base::Logger* base::GetLogger(LogSeverity); + friend void base::SetLogger(LogSeverity, base::Logger*); + + // These methods are just forwarded to by their global versions. + static void SetLogDestination(LogSeverity severity, + const char* base_filename); + static void SetLogSymlink(LogSeverity severity, + const char* symlink_basename); + static void AddLogSink(LogSink *destination); + static void RemoveLogSink(LogSink *destination); + static void SetLogFilenameExtension(const char* filename_extension); + static void SetStderrLogging(LogSeverity min_severity); + static void SetEmailLogging(LogSeverity min_severity, const char* addresses); + static void LogToStderr(); + // Flush all log files that are at least at the given severity level + static void FlushLogFiles(int min_severity); + static void FlushLogFilesUnsafe(int min_severity); + + // we set the maximum size of our packet to be 1400, the logic being + // to prevent fragmentation. + // Really this number is arbitrary. + static const int kNetworkBytes = 1400; + + static const string& hostname(); + static const bool& terminal_supports_color() { + return terminal_supports_color_; + } + + static void DeleteLogDestinations(); + + private: + LogDestination(LogSeverity severity, const char* base_filename); + ~LogDestination(); + + // Take a log message of a particular severity and log it to stderr + // iff it's of a high enough severity to deserve it. + static void MaybeLogToStderr(LogSeverity severity, const char* message, + size_t message_len, size_t prefix_len); + + // Take a log message of a particular severity and log it to email + // iff it's of a high enough severity to deserve it. + static void MaybeLogToEmail(LogSeverity severity, const char* message, + size_t len); + // Take a log message of a particular severity and log it to a file + // iff the base filename is not "" (which means "don't log to me") + static void MaybeLogToLogfile(LogSeverity severity, + time_t timestamp, + const char* message, size_t len); + // Take a log message of a particular severity and log it to the file + // for that severity and also for all files with severity less than + // this severity. + static void LogToAllLogfiles(LogSeverity severity, + time_t timestamp, + const char* message, size_t len); + + // Send logging info to all registered sinks. + static void LogToSinks(LogSeverity severity, const char* full_filename, + const char* base_filename, int line, + const LogMessageTime& logmsgtime, const char* message, + size_t message_len); + + // Wait for all registered sinks via WaitTillSent + // including the optional one in "data". + static void WaitForSinks(LogMessage::LogMessageData* data); + + static LogDestination* log_destination(LogSeverity severity); + + LogFileObject fileobject_; + base::Logger* logger_; // Either &fileobject_, or wrapper around it + + static LogDestination* log_destinations_[NUM_SEVERITIES]; + static LogSeverity email_logging_severity_; + static string addresses_; + static string hostname_; + static bool terminal_supports_color_; + + // arbitrary global logging destinations. + static vector* sinks_; + + // Protects the vector sinks_, + // but not the LogSink objects its elements reference. + static Mutex sink_mutex_; + + // Disallow + LogDestination(const LogDestination&); + LogDestination& operator=(const LogDestination&); +}; + +// Errors do not get logged to email by default. +LogSeverity LogDestination::email_logging_severity_ = 99999; + +string LogDestination::addresses_; +string LogDestination::hostname_; + +vector* LogDestination::sinks_ = NULL; +Mutex LogDestination::sink_mutex_; +bool LogDestination::terminal_supports_color_ = TerminalSupportsColor(); + +/* static */ +const string& LogDestination::hostname() { + if (hostname_.empty()) { + GetHostName(&hostname_); + if (hostname_.empty()) { + hostname_ = "(unknown)"; + } + } + return hostname_; +} + +LogDestination::LogDestination(LogSeverity severity, + const char* base_filename) + : fileobject_(severity, base_filename), + logger_(&fileobject_) { +} + +LogDestination::~LogDestination() { + if (logger_ && logger_ != &fileobject_) { + // Delete user-specified logger set via SetLogger(). + delete logger_; + } +} + +inline void LogDestination::FlushLogFilesUnsafe(int min_severity) { + // assume we have the log_mutex or we simply don't care + // about it + for (int i = min_severity; i < NUM_SEVERITIES; i++) { + LogDestination* log = log_destinations_[i]; + if (log != NULL) { + // Flush the base fileobject_ logger directly instead of going + // through any wrappers to reduce chance of deadlock. + log->fileobject_.FlushUnlocked(); + } + } +} + +inline void LogDestination::FlushLogFiles(int min_severity) { + // Prevent any subtle race conditions by wrapping a mutex lock around + // all this stuff. + MutexLock l(&log_mutex); + for (int i = min_severity; i < NUM_SEVERITIES; i++) { + LogDestination* log = log_destination(i); + if (log != NULL) { + log->logger_->Flush(); + } + } +} + +inline void LogDestination::SetLogDestination(LogSeverity severity, + const char* base_filename) { + assert(severity >= 0 && severity < NUM_SEVERITIES); + // Prevent any subtle race conditions by wrapping a mutex lock around + // all this stuff. + MutexLock l(&log_mutex); + log_destination(severity)->fileobject_.SetBasename(base_filename); +} + +inline void LogDestination::SetLogSymlink(LogSeverity severity, + const char* symlink_basename) { + CHECK_GE(severity, 0); + CHECK_LT(severity, NUM_SEVERITIES); + MutexLock l(&log_mutex); + log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename); +} + +inline void LogDestination::AddLogSink(LogSink *destination) { + // Prevent any subtle race conditions by wrapping a mutex lock around + // all this stuff. + MutexLock l(&sink_mutex_); + if (!sinks_) sinks_ = new vector; + sinks_->push_back(destination); +} + +inline void LogDestination::RemoveLogSink(LogSink *destination) { + // Prevent any subtle race conditions by wrapping a mutex lock around + // all this stuff. + MutexLock l(&sink_mutex_); + // This doesn't keep the sinks in order, but who cares? + if (sinks_) { + sinks_->erase(std::remove(sinks_->begin(), sinks_->end(), destination), sinks_->end()); + } +} + +inline void LogDestination::SetLogFilenameExtension(const char* ext) { + // Prevent any subtle race conditions by wrapping a mutex lock around + // all this stuff. + MutexLock l(&log_mutex); + for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) { + log_destination(severity)->fileobject_.SetExtension(ext); + } +} + +inline void LogDestination::SetStderrLogging(LogSeverity min_severity) { + assert(min_severity >= 0 && min_severity < NUM_SEVERITIES); + // Prevent any subtle race conditions by wrapping a mutex lock around + // all this stuff. + MutexLock l(&log_mutex); + FLAGS_stderrthreshold = min_severity; +} + +inline void LogDestination::LogToStderr() { + // *Don't* put this stuff in a mutex lock, since SetStderrLogging & + // SetLogDestination already do the locking! + SetStderrLogging(0); // thus everything is "also" logged to stderr + for ( int i = 0; i < NUM_SEVERITIES; ++i ) { + SetLogDestination(i, ""); // "" turns off logging to a logfile + } +} + +inline void LogDestination::SetEmailLogging(LogSeverity min_severity, + const char* addresses) { + assert(min_severity >= 0 && min_severity < NUM_SEVERITIES); + // Prevent any subtle race conditions by wrapping a mutex lock around + // all this stuff. + MutexLock l(&log_mutex); + LogDestination::email_logging_severity_ = min_severity; + LogDestination::addresses_ = addresses; +} + +static void ColoredWriteToStderrOrStdout(FILE* output, LogSeverity severity, + const char* message, size_t len) { + bool is_stdout = (output == stdout); + const GLogColor color = (LogDestination::terminal_supports_color() && + ((!is_stdout && FLAGS_colorlogtostderr) || + (is_stdout && FLAGS_colorlogtostdout))) + ? SeverityToColor(severity) + : COLOR_DEFAULT; + + // Avoid using cerr from this module since we may get called during + // exit code, and cerr may be partially or fully destroyed by then. + if (COLOR_DEFAULT == color) { + fwrite(message, len, 1, output); + return; + } +#ifdef GLOG_OS_WINDOWS + const HANDLE output_handle = + GetStdHandle(is_stdout ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE); + + // Gets the current text color. + CONSOLE_SCREEN_BUFFER_INFO buffer_info; + GetConsoleScreenBufferInfo(output_handle, &buffer_info); + const WORD old_color_attrs = buffer_info.wAttributes; + + // We need to flush the stream buffers into the console before each + // SetConsoleTextAttribute call lest it affect the text that is already + // printed but has not yet reached the console. + fflush(output); + SetConsoleTextAttribute(output_handle, + GetColorAttribute(color) | FOREGROUND_INTENSITY); + fwrite(message, len, 1, output); + fflush(output); + // Restores the text color. + SetConsoleTextAttribute(output_handle, old_color_attrs); +#else + fprintf(output, "\033[0;3%sm", GetAnsiColorCode(color)); + fwrite(message, len, 1, output); + fprintf(output, "\033[m"); // Resets the terminal to default. +#endif // GLOG_OS_WINDOWS +} + +static void ColoredWriteToStdout(LogSeverity severity, const char* message, + size_t len) { + FILE* output = stdout; + // We also need to send logs to the stderr when the severity is + // higher or equal to the stderr threshold. + if (severity >= FLAGS_stderrthreshold) { + output = stderr; + } + ColoredWriteToStderrOrStdout(output, severity, message, len); +} + +static void ColoredWriteToStderr(LogSeverity severity, const char* message, + size_t len) { + ColoredWriteToStderrOrStdout(stderr, severity, message, len); +} + +static void WriteToStderr(const char* message, size_t len) { + // Avoid using cerr from this module since we may get called during + // exit code, and cerr may be partially or fully destroyed by then. + fwrite(message, len, 1, stderr); +} + +inline void LogDestination::MaybeLogToStderr(LogSeverity severity, + const char* message, size_t message_len, size_t prefix_len) { + if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) { + ColoredWriteToStderr(severity, message, message_len); +#ifdef GLOG_OS_WINDOWS + (void) prefix_len; + // On Windows, also output to the debugger + ::OutputDebugStringA(message); +#elif defined(__ANDROID__) + // On Android, also output to logcat + const int android_log_levels[NUM_SEVERITIES] = { + ANDROID_LOG_INFO, + ANDROID_LOG_WARN, + ANDROID_LOG_ERROR, + ANDROID_LOG_FATAL, + }; + __android_log_write(android_log_levels[severity], + glog_internal_namespace_::ProgramInvocationShortName(), + message + prefix_len); +#else + (void) prefix_len; +#endif + } +} + + +inline void LogDestination::MaybeLogToEmail(LogSeverity severity, + const char* message, size_t len) { + if (severity >= email_logging_severity_ || + severity >= FLAGS_logemaillevel) { + string to(FLAGS_alsologtoemail); + if (!addresses_.empty()) { + if (!to.empty()) { + to += ","; + } + to += addresses_; + } + const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " + + glog_internal_namespace_::ProgramInvocationShortName()); + string body(hostname()); + body += "\n\n"; + body.append(message, len); + + // should NOT use SendEmail(). The caller of this function holds the + // log_mutex and SendEmail() calls LOG/VLOG which will block trying to + // acquire the log_mutex object. Use SendEmailInternal() and set + // use_logging to false. + SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false); + } +} + + +inline void LogDestination::MaybeLogToLogfile(LogSeverity severity, + time_t timestamp, + const char* message, + size_t len) { + const bool should_flush = severity > FLAGS_logbuflevel; + LogDestination* destination = log_destination(severity); + destination->logger_->Write(should_flush, timestamp, message, len); +} + +inline void LogDestination::LogToAllLogfiles(LogSeverity severity, + time_t timestamp, + const char* message, + size_t len) { + if (FLAGS_logtostdout) { // global flag: never log to file + ColoredWriteToStdout(severity, message, len); + } else if (FLAGS_logtostderr) { // global flag: never log to file + ColoredWriteToStderr(severity, message, len); + } else { + for (int i = severity; i >= 0; --i) { + LogDestination::MaybeLogToLogfile(i, timestamp, message, len); + } + } +} + +inline void LogDestination::LogToSinks(LogSeverity severity, + const char* full_filename, + const char* base_filename, int line, + const LogMessageTime& logmsgtime, + const char* message, + size_t message_len) { + ReaderMutexLock l(&sink_mutex_); + if (sinks_) { + for (size_t i = sinks_->size(); i-- > 0; ) { + (*sinks_)[i]->send(severity, full_filename, base_filename, + line, logmsgtime, message, message_len); + } + } +} + +inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) { + ReaderMutexLock l(&sink_mutex_); + if (sinks_) { + for (size_t i = sinks_->size(); i-- > 0; ) { + (*sinks_)[i]->WaitTillSent(); + } + } + const bool send_to_sink = + (data->send_method_ == &LogMessage::SendToSink) || + (data->send_method_ == &LogMessage::SendToSinkAndLog); + if (send_to_sink && data->sink_ != NULL) { + data->sink_->WaitTillSent(); + } +} + +LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES]; + +inline LogDestination* LogDestination::log_destination(LogSeverity severity) { + assert(severity >=0 && severity < NUM_SEVERITIES); + if (!log_destinations_[severity]) { + log_destinations_[severity] = new LogDestination(severity, NULL); + } + return log_destinations_[severity]; +} + +void LogDestination::DeleteLogDestinations() { + for (int severity = 0; severity < NUM_SEVERITIES; ++severity) { + delete log_destinations_[severity]; + log_destinations_[severity] = NULL; + } + MutexLock l(&sink_mutex_); + delete sinks_; + sinks_ = NULL; +} + +namespace { + +std::string g_application_fingerprint; + +} // namespace + +void SetApplicationFingerprint(const std::string& fingerprint) { + g_application_fingerprint = fingerprint; +} + +namespace { + +// Directory delimiter; Windows supports both forward slashes and backslashes +#ifdef GLOG_OS_WINDOWS +const char possible_dir_delim[] = {'\\', '/'}; +#else +const char possible_dir_delim[] = {'/'}; +#endif + +string PrettyDuration(int secs) { + std::stringstream result; + int mins = secs / 60; + int hours = mins / 60; + mins = mins % 60; + secs = secs % 60; + result.fill('0'); + result << hours << ':' << setw(2) << mins << ':' << setw(2) << secs; + return result.str(); +} + + +LogFileObject::LogFileObject(LogSeverity severity, + const char* base_filename) + : base_filename_selected_(base_filename != NULL), + base_filename_((base_filename != NULL) ? base_filename : ""), + symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()), + filename_extension_(), + file_(NULL), + severity_(severity), + bytes_since_flush_(0), + dropped_mem_length_(0), + file_length_(0), + rollover_attempt_(kRolloverAttemptFrequency-1), + next_flush_time_(0), + start_time_(WallTime_Now()) { + assert(severity >= 0); + assert(severity < NUM_SEVERITIES); +} + +LogFileObject::~LogFileObject() { + MutexLock l(&lock_); + if (file_ != NULL) { + fclose(file_); + file_ = NULL; + } +} + +void LogFileObject::SetBasename(const char* basename) { + MutexLock l(&lock_); + base_filename_selected_ = true; + if (base_filename_ != basename) { + // Get rid of old log file since we are changing names + if (file_ != NULL) { + fclose(file_); + file_ = NULL; + rollover_attempt_ = kRolloverAttemptFrequency-1; + } + base_filename_ = basename; + } +} + +void LogFileObject::SetExtension(const char* ext) { + MutexLock l(&lock_); + if (filename_extension_ != ext) { + // Get rid of old log file since we are changing names + if (file_ != NULL) { + fclose(file_); + file_ = NULL; + rollover_attempt_ = kRolloverAttemptFrequency-1; + } + filename_extension_ = ext; + } +} + +void LogFileObject::SetSymlinkBasename(const char* symlink_basename) { + MutexLock l(&lock_); + symlink_basename_ = symlink_basename; +} + +void LogFileObject::Flush() { + MutexLock l(&lock_); + FlushUnlocked(); +} + +void LogFileObject::FlushUnlocked(){ + if (file_ != NULL) { + fflush(file_); + bytes_since_flush_ = 0; + } + // Figure out when we are due for another flush. + const int64 next = (FLAGS_logbufsecs + * static_cast(1000000)); // in usec + next_flush_time_ = CycleClock_Now() + UsecToCycles(next); +} + +bool LogFileObject::CreateLogfile(const string& time_pid_string) { + string string_filename = base_filename_; + if (FLAGS_timestamp_in_logfile_name) { + string_filename += time_pid_string; + } + string_filename += filename_extension_; + const char* filename = string_filename.c_str(); + //only write to files, create if non-existant. + int flags = O_WRONLY | O_CREAT; + if (FLAGS_timestamp_in_logfile_name) { + //demand that the file is unique for our timestamp (fail if it exists). + flags = flags | O_EXCL; + } + int fd = open(filename, flags, FLAGS_logfile_mode); + if (fd == -1) return false; +#ifdef HAVE_FCNTL + // Mark the file close-on-exec. We don't really care if this fails + fcntl(fd, F_SETFD, FD_CLOEXEC); + + // Mark the file as exclusive write access to avoid two clients logging to the + // same file. This applies particularly when !FLAGS_timestamp_in_logfile_name + // (otherwise open would fail because the O_EXCL flag on similar filename). + // locks are released on unlock or close() automatically, only after log is + // released. + // This will work after a fork as it is not inherited (not stored in the fd). + // Lock will not be lost because the file is opened with exclusive lock (write) + // and we will never read from it inside the process. + // TODO windows implementation of this (as flock is not available on mingw). + static struct flock w_lock; + + w_lock.l_type = F_WRLCK; + w_lock.l_start = 0; + w_lock.l_whence = SEEK_SET; + w_lock.l_len = 0; + + int wlock_ret = fcntl(fd, F_SETLK, &w_lock); + if (wlock_ret == -1) { + close(fd); //as we are failing already, do not check errors here + return false; + } +#endif + + //fdopen in append mode so if the file exists it will fseek to the end + file_ = fdopen(fd, "a"); // Make a FILE*. + if (file_ == NULL) { // Man, we're screwed! + close(fd); + if (FLAGS_timestamp_in_logfile_name) { + unlink(filename); // Erase the half-baked evidence: an unusable log file, only if we just created it. + } + return false; + } +#ifdef GLOG_OS_WINDOWS + // https://github.com/golang/go/issues/27638 - make sure we seek to the end to append + // empirically replicated with wine over mingw build + if (!FLAGS_timestamp_in_logfile_name) { + if (fseek(file_, 0, SEEK_END) != 0) { + return false; + } + } +#endif + // We try to create a symlink called ., + // which is easier to use. (Every time we create a new logfile, + // we destroy the old symlink and create a new one, so it always + // points to the latest logfile.) If it fails, we're sad but it's + // no error. + if (!symlink_basename_.empty()) { + // take directory from filename + const char* slash = strrchr(filename, PATH_SEPARATOR); + const string linkname = + symlink_basename_ + '.' + LogSeverityNames[severity_]; + string linkpath; + if ( slash ) linkpath = string(filename, static_cast(slash-filename+1)); // get dirname + linkpath += linkname; + unlink(linkpath.c_str()); // delete old one if it exists + +#if defined(GLOG_OS_WINDOWS) + // TODO(hamaji): Create lnk file on Windows? +#elif defined(HAVE_UNISTD_H) + // We must have unistd.h. + // Make the symlink be relative (in the same dir) so that if the + // entire log directory gets relocated the link is still valid. + const char *linkdest = slash ? (slash + 1) : filename; + if (symlink(linkdest, linkpath.c_str()) != 0) { + // silently ignore failures + } + + // Make an additional link to the log file in a place specified by + // FLAGS_log_link, if indicated + if (!FLAGS_log_link.empty()) { + linkpath = FLAGS_log_link + "/" + linkname; + unlink(linkpath.c_str()); // delete old one if it exists + if (symlink(filename, linkpath.c_str()) != 0) { + // silently ignore failures + } + } +#endif + } + + return true; // Everything worked +} + +void LogFileObject::Write(bool force_flush, + time_t timestamp, + const char* message, + size_t message_len) { + MutexLock l(&lock_); + + // We don't log if the base_name_ is "" (which means "don't write") + if (base_filename_selected_ && base_filename_.empty()) { + return; + } + + if (file_length_ >> 20U >= MaxLogSize() || PidHasChanged()) { + if (file_ != NULL) fclose(file_); + file_ = NULL; + file_length_ = bytes_since_flush_ = dropped_mem_length_ = 0; + rollover_attempt_ = kRolloverAttemptFrequency - 1; + } + + // If there's no destination file, make one before outputting + if (file_ == NULL) { + // Try to rollover the log file every 32 log messages. The only time + // this could matter would be when we have trouble creating the log + // file. If that happens, we'll lose lots of log messages, of course! + if (++rollover_attempt_ != kRolloverAttemptFrequency) return; + rollover_attempt_ = 0; + + struct ::tm tm_time; + if (FLAGS_log_utc_time) { + gmtime_r(×tamp, &tm_time); + } else { + localtime_r(×tamp, &tm_time); + } + + // The logfile's filename will have the date/time & pid in it + ostringstream time_pid_stream; + time_pid_stream.fill('0'); + time_pid_stream << 1900+tm_time.tm_year + << setw(2) << 1+tm_time.tm_mon + << setw(2) << tm_time.tm_mday + << '-' + << setw(2) << tm_time.tm_hour + << setw(2) << tm_time.tm_min + << setw(2) << tm_time.tm_sec + << '.' + << GetMainThreadPid(); + const string& time_pid_string = time_pid_stream.str(); + + if (base_filename_selected_) { + if (!CreateLogfile(time_pid_string)) { + perror("Could not create log file"); + fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n", + time_pid_string.c_str()); + return; + } + } else { + // If no base filename for logs of this severity has been set, use a + // default base filename of + // "...log..". So + // logfiles will have names like + // webserver.examplehost.root.log.INFO.19990817-150000.4354, where + // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00), + // and 4354 is the pid of the logging process. The date & time reflect + // when the file was created for output. + // + // Where does the file get put? Successively try the directories + // "/tmp", and "." + string stripped_filename( + glog_internal_namespace_::ProgramInvocationShortName()); + string hostname; + GetHostName(&hostname); + + string uidname = MyUserName(); + // We should not call CHECK() here because this function can be + // called after holding on to log_mutex. We don't want to + // attempt to hold on to the same mutex, and get into a + // deadlock. Simply use a name like invalid-user. + if (uidname.empty()) uidname = "invalid-user"; + + stripped_filename = stripped_filename+'.'+hostname+'.' + +uidname+".log." + +LogSeverityNames[severity_]+'.'; + // We're going to (potentially) try to put logs in several different dirs + const vector & log_dirs = GetLoggingDirectories(); + + // Go through the list of dirs, and try to create the log file in each + // until we succeed or run out of options + bool success = false; + for (vector::const_iterator dir = log_dirs.begin(); + dir != log_dirs.end(); + ++dir) { + base_filename_ = *dir + "/" + stripped_filename; + if ( CreateLogfile(time_pid_string) ) { + success = true; + break; + } + } + // If we never succeeded, we have to give up + if ( success == false ) { + perror("Could not create logging file"); + fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!", + time_pid_string.c_str()); + return; + } + } + + // Write a header message into the log file + ostringstream file_header_stream; + file_header_stream.fill('0'); + file_header_stream << "Log file created at: " + << 1900+tm_time.tm_year << '/' + << setw(2) << 1+tm_time.tm_mon << '/' + << setw(2) << tm_time.tm_mday + << ' ' + << setw(2) << tm_time.tm_hour << ':' + << setw(2) << tm_time.tm_min << ':' + << setw(2) << tm_time.tm_sec << (FLAGS_log_utc_time ? " UTC\n" : "\n") + << "Running on machine: " + << LogDestination::hostname() << '\n'; + + if(!g_application_fingerprint.empty()) { + file_header_stream << "Application fingerprint: " << g_application_fingerprint << '\n'; + } + const char* const date_time_format = FLAGS_log_year_in_prefix + ? "yyyymmdd hh:mm:ss.uuuuuu" + : "mmdd hh:mm:ss.uuuuuu"; + file_header_stream << "Running duration (h:mm:ss): " + << PrettyDuration(static_cast(WallTime_Now() - start_time_)) << '\n' + << "Log line format: [IWEF]" << date_time_format << " " + << "threadid file:line] msg" << '\n'; + const string& file_header_string = file_header_stream.str(); + + const size_t header_len = file_header_string.size(); + fwrite(file_header_string.data(), 1, header_len, file_); + file_length_ += header_len; + bytes_since_flush_ += header_len; + } + + // Write to LOG file + if ( !stop_writing ) { + // fwrite() doesn't return an error when the disk is full, for + // messages that are less than 4096 bytes. When the disk is full, + // it returns the message length for messages that are less than + // 4096 bytes. fwrite() returns 4096 for message lengths that are + // greater than 4096, thereby indicating an error. + errno = 0; + fwrite(message, 1, message_len, file_); + if ( FLAGS_stop_logging_if_full_disk && + errno == ENOSPC ) { // disk full, stop writing to disk + stop_writing = true; // until the disk is + return; + } else { + file_length_ += message_len; + bytes_since_flush_ += message_len; + } + } else { + if (CycleClock_Now() >= next_flush_time_) { + stop_writing = false; // check to see if disk has free space. + } + return; // no need to flush + } + + // See important msgs *now*. Also, flush logs at least every 10^6 chars, + // or every "FLAGS_logbufsecs" seconds. + if ( force_flush || + (bytes_since_flush_ >= 1000000) || + (CycleClock_Now() >= next_flush_time_) ) { + FlushUnlocked(); +#ifdef GLOG_OS_LINUX + // Only consider files >= 3MiB + if (FLAGS_drop_log_memory && file_length_ >= (3U << 20U)) { + // Don't evict the most recent 1-2MiB so as not to impact a tailer + // of the log file and to avoid page rounding issue on linux < 4.7 + uint32 total_drop_length = + (file_length_ & ~((1U << 20U) - 1U)) - (1U << 20U); + uint32 this_drop_length = total_drop_length - dropped_mem_length_; + if (this_drop_length >= (2U << 20U)) { + // Only advise when >= 2MiB to drop +# if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21) + // 'posix_fadvise' introduced in API 21: + // * https://android.googlesource.com/platform/bionic/+/6880f936173081297be0dc12f687d341b86a4cfa/libc/libc.map.txt#732 +# else + posix_fadvise(fileno(file_), dropped_mem_length_, this_drop_length, + POSIX_FADV_DONTNEED); +# endif + dropped_mem_length_ = total_drop_length; + } + } +#endif + + // Remove old logs + if (log_cleaner.enabled()) { + log_cleaner.Run(base_filename_selected_, + base_filename_, + filename_extension_); + } + } +} + +LogCleaner::LogCleaner() : enabled_(false), overdue_days_(7), next_cleanup_time_(0) {} + +void LogCleaner::Enable(unsigned int overdue_days) { + enabled_ = true; + overdue_days_ = overdue_days; +} + +void LogCleaner::Disable() { + enabled_ = false; +} + +void LogCleaner::UpdateCleanUpTime() { + const int64 next = (FLAGS_logcleansecs + * 1000000); // in usec + next_cleanup_time_ = CycleClock_Now() + UsecToCycles(next); +} + +void LogCleaner::Run(bool base_filename_selected, + const string& base_filename, + const string& filename_extension) { + assert(enabled_); + assert(!base_filename_selected || !base_filename.empty()); + + // avoid scanning logs too frequently + if (CycleClock_Now() < next_cleanup_time_) { + return; + } + UpdateCleanUpTime(); + + vector dirs; + + if (!base_filename_selected) { + dirs = GetLoggingDirectories(); + } else { + size_t pos = base_filename.find_last_of(possible_dir_delim, string::npos, + sizeof(possible_dir_delim)); + if (pos != string::npos) { + string dir = base_filename.substr(0, pos + 1); + dirs.push_back(dir); + } else { + dirs.push_back("."); + } + } + + for (size_t i = 0; i < dirs.size(); i++) { + vector logs = GetOverdueLogNames(dirs[i], + overdue_days_, + base_filename, + filename_extension); + for (size_t j = 0; j < logs.size(); j++) { + static_cast(unlink(logs[j].c_str())); + } + } +} + +vector LogCleaner::GetOverdueLogNames( + string log_directory, unsigned int days, const string& base_filename, + const string& filename_extension) const { + // The names of overdue logs. + vector overdue_log_names; + + // Try to get all files within log_directory. + DIR *dir; + struct dirent *ent; + + if ((dir = opendir(log_directory.c_str()))) { + while ((ent = readdir(dir))) { + if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) { + continue; + } + + string filepath = ent->d_name; + const char* const dir_delim_end = + possible_dir_delim + sizeof(possible_dir_delim); + + if (!log_directory.empty() && + std::find(possible_dir_delim, dir_delim_end, + log_directory[log_directory.size() - 1]) != dir_delim_end) { + filepath = log_directory + filepath; + } + + if (IsLogFromCurrentProject(filepath, base_filename, filename_extension) && + IsLogLastModifiedOver(filepath, days)) { + overdue_log_names.push_back(filepath); + } + } + closedir(dir); + } + + return overdue_log_names; +} + +bool LogCleaner::IsLogFromCurrentProject(const string& filepath, + const string& base_filename, + const string& filename_extension) const { + // We should remove duplicated delimiters from `base_filename`, e.g., + // before: "/tmp//.." + // after: "/tmp/.." + string cleaned_base_filename; + + const char* const dir_delim_end = + possible_dir_delim + sizeof(possible_dir_delim); + + size_t real_filepath_size = filepath.size(); + for (size_t i = 0; i < base_filename.size(); ++i) { + const char& c = base_filename[i]; + + if (cleaned_base_filename.empty()) { + cleaned_base_filename += c; + } else if (std::find(possible_dir_delim, dir_delim_end, c) == + dir_delim_end || + (!cleaned_base_filename.empty() && + c != cleaned_base_filename[cleaned_base_filename.size() - 1])) { + cleaned_base_filename += c; + } + } + + // Return early if the filename doesn't start with `cleaned_base_filename`. + if (filepath.find(cleaned_base_filename) != 0) { + return false; + } + + // Check if in the string `filename_extension` is right next to + // `cleaned_base_filename` in `filepath` if the user + // has set a custom filename extension. + if (!filename_extension.empty()) { + if (cleaned_base_filename.size() >= real_filepath_size) { + return false; + } + // for origin version, `filename_extension` is middle of the `filepath`. + string ext = filepath.substr(cleaned_base_filename.size(), filename_extension.size()); + if (ext == filename_extension) { + cleaned_base_filename += filename_extension; + } + else { + // for new version, `filename_extension` is right of the `filepath`. + if (filename_extension.size() >= real_filepath_size) { + return false; + } + real_filepath_size = filepath.size() - filename_extension.size(); + if (filepath.substr(real_filepath_size) != filename_extension) { + return false; + } + } + } + + // The characters after `cleaned_base_filename` should match the format: + // YYYYMMDD-HHMMSS.pid + for (size_t i = cleaned_base_filename.size(); i < real_filepath_size; i++) { + const char& c = filepath[i]; + + if (i <= cleaned_base_filename.size() + 7) { // 0 ~ 7 : YYYYMMDD + if (c < '0' || c > '9') { return false; } + + } else if (i == cleaned_base_filename.size() + 8) { // 8: - + if (c != '-') { return false; } + + } else if (i <= cleaned_base_filename.size() + 14) { // 9 ~ 14: HHMMSS + if (c < '0' || c > '9') { return false; } + + } else if (i == cleaned_base_filename.size() + 15) { // 15: . + if (c != '.') { return false; } + + } else if (i >= cleaned_base_filename.size() + 16) { // 16+: pid + if (c < '0' || c > '9') { return false; } + } + } + + return true; +} + +bool LogCleaner::IsLogLastModifiedOver(const string& filepath, + unsigned int days) const { + // Try to get the last modified time of this file. + struct stat file_stat; + + if (stat(filepath.c_str(), &file_stat) == 0) { + const time_t seconds_in_a_day = 60 * 60 * 24; + time_t last_modified_time = file_stat.st_mtime; + time_t current_time = time(NULL); + return difftime(current_time, last_modified_time) > days * seconds_in_a_day; + } + + // If failed to get file stat, don't return true! + return false; +} + +} // namespace + +// Static log data space to avoid alloc failures in a LOG(FATAL) +// +// Since multiple threads may call LOG(FATAL), and we want to preserve +// the data from the first call, we allocate two sets of space. One +// for exclusive use by the first thread, and one for shared use by +// all other threads. +static Mutex fatal_msg_lock; +static CrashReason crash_reason; +static bool fatal_msg_exclusive = true; +static LogMessage::LogMessageData fatal_msg_data_exclusive; +static LogMessage::LogMessageData fatal_msg_data_shared; + +#ifdef GLOG_THREAD_LOCAL_STORAGE +// Static thread-local log data space to use, because typically at most one +// LogMessageData object exists (in this case glog makes zero heap memory +// allocations). +static GLOG_THREAD_LOCAL_STORAGE bool thread_data_available = true; + +#if defined(HAVE_ALIGNED_STORAGE) && __cplusplus >= 201103L +static GLOG_THREAD_LOCAL_STORAGE + std::aligned_storage::type thread_msg_data; +#else +static GLOG_THREAD_LOCAL_STORAGE + char thread_msg_data[sizeof(void*) + sizeof(LogMessage::LogMessageData)]; +#endif // HAVE_ALIGNED_STORAGE +#endif // defined(GLOG_THREAD_LOCAL_STORAGE) + +LogMessage::LogMessageData::LogMessageData() + : stream_(message_text_, LogMessage::kMaxLogMessageLen, 0) { +} + +LogMessage::LogMessage(const char* file, int line, LogSeverity severity, + int64 ctr, void (LogMessage::*send_method)()) + : allocated_(NULL) { + Init(file, line, severity, send_method); + data_->stream_.set_ctr(ctr); +} + +LogMessage::LogMessage(const char* file, int line, + const CheckOpString& result) + : allocated_(NULL) { + Init(file, line, GLOG_FATAL, &LogMessage::SendToLog); + stream() << "Check failed: " << (*result.str_) << " "; +} + +LogMessage::LogMessage(const char* file, int line) + : allocated_(NULL) { + Init(file, line, GLOG_INFO, &LogMessage::SendToLog); +} + +LogMessage::LogMessage(const char* file, int line, LogSeverity severity) + : allocated_(NULL) { + Init(file, line, severity, &LogMessage::SendToLog); +} + +LogMessage::LogMessage(const char* file, int line, LogSeverity severity, + LogSink* sink, bool also_send_to_log) + : allocated_(NULL) { + Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog : + &LogMessage::SendToSink); + data_->sink_ = sink; // override Init()'s setting to NULL +} + +LogMessage::LogMessage(const char* file, int line, LogSeverity severity, + vector *outvec) + : allocated_(NULL) { + Init(file, line, severity, &LogMessage::SaveOrSendToLog); + data_->outvec_ = outvec; // override Init()'s setting to NULL +} + +LogMessage::LogMessage(const char* file, int line, LogSeverity severity, + string *message) + : allocated_(NULL) { + Init(file, line, severity, &LogMessage::WriteToStringAndLog); + data_->message_ = message; // override Init()'s setting to NULL +} + +void LogMessage::Init(const char* file, + int line, + LogSeverity severity, + void (LogMessage::*send_method)()) { + allocated_ = NULL; + if (severity != GLOG_FATAL || !exit_on_dfatal) { +#ifdef GLOG_THREAD_LOCAL_STORAGE + // No need for locking, because this is thread local. + if (thread_data_available) { + thread_data_available = false; +#ifdef HAVE_ALIGNED_STORAGE + data_ = new (&thread_msg_data) LogMessageData; +#else + const uintptr_t kAlign = sizeof(void*) - 1; + + char* align_ptr = + reinterpret_cast(reinterpret_cast(thread_msg_data + kAlign) & ~kAlign); + data_ = new (align_ptr) LogMessageData; + assert(reinterpret_cast(align_ptr) % sizeof(void*) == 0); +#endif + } else { + allocated_ = new LogMessageData(); + data_ = allocated_; + } +#else // !defined(GLOG_THREAD_LOCAL_STORAGE) + allocated_ = new LogMessageData(); + data_ = allocated_; +#endif // defined(GLOG_THREAD_LOCAL_STORAGE) + data_->first_fatal_ = false; + } else { + MutexLock l(&fatal_msg_lock); + if (fatal_msg_exclusive) { + fatal_msg_exclusive = false; + data_ = &fatal_msg_data_exclusive; + data_->first_fatal_ = true; + } else { + data_ = &fatal_msg_data_shared; + data_->first_fatal_ = false; + } + } + + data_->preserved_errno_ = errno; + data_->severity_ = severity; + data_->line_ = line; + data_->send_method_ = send_method; + data_->sink_ = NULL; + data_->outvec_ = NULL; + WallTime now = WallTime_Now(); + time_t timestamp_now = static_cast(now); + logmsgtime_ = LogMessageTime(timestamp_now, now); + + data_->num_chars_to_log_ = 0; + data_->num_chars_to_syslog_ = 0; + data_->basename_ = const_basename(file); + data_->fullname_ = file; + data_->has_been_flushed_ = false; + + // If specified, prepend a prefix to each line. For example: + // I20201018 160715 f5d4fbb0 logging.cc:1153] + // (log level, GMT year, month, date, time, thread_id, file basename, line) + // We exclude the thread_id for the default thread. + if (FLAGS_log_prefix && (line != kNoLogPrefix)) { + std::ios saved_fmt(NULL); + saved_fmt.copyfmt(stream()); + stream().fill('0'); + #ifdef GLOG_CUSTOM_PREFIX_SUPPORT + if (custom_prefix_callback == NULL) { + #endif + stream() << LogSeverityNames[severity][0]; + if (FLAGS_log_year_in_prefix) { + stream() << setw(4) << 1900 + logmsgtime_.year(); + } + stream() << setw(2) << 1 + logmsgtime_.month() + << setw(2) << logmsgtime_.day() + << ' ' + << setw(2) << logmsgtime_.hour() << ':' + << setw(2) << logmsgtime_.min() << ':' + << setw(2) << logmsgtime_.sec() << "." + << setw(6) << logmsgtime_.usec() + << ' ' + << setfill(' ') << setw(5) + << static_cast(GetTID()) << setfill('0') + << ' ' + << data_->basename_ << ':' << data_->line_ << "] "; + #ifdef GLOG_CUSTOM_PREFIX_SUPPORT + } else { + custom_prefix_callback( + stream(), + LogMessageInfo(LogSeverityNames[severity], + data_->basename_, data_->line_, GetTID(), + logmsgtime_), + custom_prefix_callback_data + ); + stream() << " "; + } + #endif + stream().copyfmt(saved_fmt); + } + data_->num_prefix_chars_ = data_->stream_.pcount(); + + if (!FLAGS_log_backtrace_at.empty()) { + char fileline[128]; + snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line); +#ifdef HAVE_STACKTRACE + if (FLAGS_log_backtrace_at == fileline) { + string stacktrace; + DumpStackTraceToString(&stacktrace); + stream() << " (stacktrace:\n" << stacktrace << ") "; + } +#endif + } +} + +const LogMessageTime& LogMessage::getLogMessageTime() const { + return logmsgtime_; +} + +LogMessage::~LogMessage() { + Flush(); +#ifdef GLOG_THREAD_LOCAL_STORAGE + if (data_ == static_cast(&thread_msg_data)) { + data_->~LogMessageData(); + thread_data_available = true; + } + else { + delete allocated_; + } +#else // !defined(GLOG_THREAD_LOCAL_STORAGE) + delete allocated_; +#endif // defined(GLOG_THREAD_LOCAL_STORAGE) +} + +int LogMessage::preserved_errno() const { + return data_->preserved_errno_; +} + +ostream& LogMessage::stream() { + return data_->stream_; +} + +// Flush buffered message, called by the destructor, or any other function +// that needs to synchronize the log. +void LogMessage::Flush() { + if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel) { + return; + } + + data_->num_chars_to_log_ = data_->stream_.pcount(); + data_->num_chars_to_syslog_ = + data_->num_chars_to_log_ - data_->num_prefix_chars_; + + // Do we need to add a \n to the end of this message? + bool append_newline = + (data_->message_text_[data_->num_chars_to_log_-1] != '\n'); + char original_final_char = '\0'; + + // If we do need to add a \n, we'll do it by violating the memory of the + // ostrstream buffer. This is quick, and we'll make sure to undo our + // modification before anything else is done with the ostrstream. It + // would be preferable not to do things this way, but it seems to be + // the best way to deal with this. + if (append_newline) { + original_final_char = data_->message_text_[data_->num_chars_to_log_]; + data_->message_text_[data_->num_chars_to_log_++] = '\n'; + } + data_->message_text_[data_->num_chars_to_log_] = '\0'; + + // Prevent any subtle race conditions by wrapping a mutex lock around + // the actual logging action per se. + { + MutexLock l(&log_mutex); + (this->*(data_->send_method_))(); + ++num_messages_[static_cast(data_->severity_)]; + } + LogDestination::WaitForSinks(data_); + + if (append_newline) { + // Fix the ostrstream back how it was before we screwed with it. + // It's 99.44% certain that we don't need to worry about doing this. + data_->message_text_[data_->num_chars_to_log_-1] = original_final_char; + } + + // If errno was already set before we enter the logging call, we'll + // set it back to that value when we return from the logging call. + // It happens often that we log an error message after a syscall + // failure, which can potentially set the errno to some other + // values. We would like to preserve the original errno. + if (data_->preserved_errno_ != 0) { + errno = data_->preserved_errno_; + } + + // Note that this message is now safely logged. If we're asked to flush + // again, as a result of destruction, say, we'll do nothing on future calls. + data_->has_been_flushed_ = true; +} + +// Copy of first FATAL log message so that we can print it out again +// after all the stack traces. To preserve legacy behavior, we don't +// use fatal_msg_data_exclusive. +static time_t fatal_time; +static char fatal_message[256]; + +void ReprintFatalMessage() { + if (fatal_message[0]) { + const size_t n = strlen(fatal_message); + if (!FLAGS_logtostderr) { + // Also write to stderr (don't color to avoid terminal checks) + WriteToStderr(fatal_message, n); + } + LogDestination::LogToAllLogfiles(GLOG_ERROR, fatal_time, fatal_message, n); + } +} + +// L >= log_mutex (callers must hold the log_mutex). +void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { + static bool already_warned_before_initgoogle = false; + + log_mutex.AssertHeld(); + + RAW_DCHECK(data_->num_chars_to_log_ > 0 && + data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); + + // Messages of a given severity get logged to lower severity logs, too + + if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) { + const char w[] = "WARNING: Logging before InitGoogleLogging() is " + "written to STDERR\n"; + WriteToStderr(w, strlen(w)); + already_warned_before_initgoogle = true; + } + + // global flag: never log to file if set. Also -- don't log to a + // file if we haven't parsed the command line flags to get the + // program name. + if (FLAGS_logtostderr || FLAGS_logtostdout || !IsGoogleLoggingInitialized()) { + if (FLAGS_logtostdout) { + ColoredWriteToStdout(data_->severity_, data_->message_text_, + data_->num_chars_to_log_); + } else { + ColoredWriteToStderr(data_->severity_, data_->message_text_, + data_->num_chars_to_log_); + } + + // this could be protected by a flag if necessary. + LogDestination::LogToSinks(data_->severity_, + data_->fullname_, data_->basename_, + data_->line_, logmsgtime_, + data_->message_text_ + data_->num_prefix_chars_, + (data_->num_chars_to_log_ - + data_->num_prefix_chars_ - 1) ); + } else { + // log this message to all log files of severity <= severity_ + LogDestination::LogToAllLogfiles(data_->severity_, logmsgtime_.timestamp(), + data_->message_text_, + data_->num_chars_to_log_); + + LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_, + data_->num_chars_to_log_, + data_->num_prefix_chars_); + LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_, + data_->num_chars_to_log_); + LogDestination::LogToSinks(data_->severity_, + data_->fullname_, data_->basename_, + data_->line_, logmsgtime_, + data_->message_text_ + data_->num_prefix_chars_, + (data_->num_chars_to_log_ + - data_->num_prefix_chars_ - 1) ); + // NOTE: -1 removes trailing \n + } + + // If we log a FATAL message, flush all the log destinations, then toss + // a signal for others to catch. We leave the logs in a state that + // someone else can use them (as long as they flush afterwards) + if (data_->severity_ == GLOG_FATAL && exit_on_dfatal) { + if (data_->first_fatal_) { + // Store crash information so that it is accessible from within signal + // handlers that may be invoked later. + RecordCrashReason(&crash_reason); + SetCrashReason(&crash_reason); + + // Store shortened fatal message for other logs and GWQ status + const size_t copy = min(data_->num_chars_to_log_, + sizeof(fatal_message)-1); + memcpy(fatal_message, data_->message_text_, copy); + fatal_message[copy] = '\0'; + fatal_time = logmsgtime_.timestamp(); + } + + if (!FLAGS_logtostderr && !FLAGS_logtostdout) { + for (int i = 0; i < NUM_SEVERITIES; ++i) { + if (LogDestination::log_destinations_[i]) { + LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0); + } + } + } + + // release the lock that our caller (directly or indirectly) + // LogMessage::~LogMessage() grabbed so that signal handlers + // can use the logging facility. Alternately, we could add + // an entire unsafe logging interface to bypass locking + // for signal handlers but this seems simpler. + log_mutex.Unlock(); + LogDestination::WaitForSinks(data_); + + const char* message = "*** Check failure stack trace: ***\n"; + if (write(STDERR_FILENO, message, strlen(message)) < 0) { + // Ignore errors. + } +#if defined(__ANDROID__) + // ANDROID_LOG_FATAL as this message is of FATAL severity. + __android_log_write(ANDROID_LOG_FATAL, + glog_internal_namespace_::ProgramInvocationShortName(), + message); +#endif + Fail(); + } +} + +void LogMessage::RecordCrashReason( + glog_internal_namespace_::CrashReason* reason) { + reason->filename = fatal_msg_data_exclusive.fullname_; + reason->line_number = fatal_msg_data_exclusive.line_; + reason->message = fatal_msg_data_exclusive.message_text_ + + fatal_msg_data_exclusive.num_prefix_chars_; +#ifdef HAVE_STACKTRACE + // Retrieve the stack trace, omitting the logging frames that got us here. + reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4); +#else + reason->depth = 0; +#endif +} + +GLOG_EXPORT logging_fail_func_t g_logging_fail_func = + reinterpret_cast(&abort); + +void InstallFailureFunction(logging_fail_func_t fail_func) { + g_logging_fail_func = fail_func; +} + +void LogMessage::Fail() { + g_logging_fail_func(); +} + +// L >= log_mutex (callers must hold the log_mutex). +void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { + if (data_->sink_ != NULL) { + RAW_DCHECK(data_->num_chars_to_log_ > 0 && + data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); + data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_, + data_->line_, logmsgtime_, + data_->message_text_ + data_->num_prefix_chars_, + (data_->num_chars_to_log_ - + data_->num_prefix_chars_ - 1) ); + } +} + +// L >= log_mutex (callers must hold the log_mutex). +void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { + SendToSink(); + SendToLog(); +} + +// L >= log_mutex (callers must hold the log_mutex). +void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { + if (data_->outvec_ != NULL) { + RAW_DCHECK(data_->num_chars_to_log_ > 0 && + data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); + // Omit prefix of message and trailing newline when recording in outvec_. + const char *start = data_->message_text_ + data_->num_prefix_chars_; + size_t len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1; + data_->outvec_->push_back(string(start, len)); + } else { + SendToLog(); + } +} + +void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { + if (data_->message_ != NULL) { + RAW_DCHECK(data_->num_chars_to_log_ > 0 && + data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); + // Omit prefix of message and trailing newline when writing to message_. + const char *start = data_->message_text_ + data_->num_prefix_chars_; + size_t len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1; + data_->message_->assign(start, len); + } + SendToLog(); +} + +// L >= log_mutex (callers must hold the log_mutex). +void LogMessage::SendToSyslogAndLog() { +#ifdef HAVE_SYSLOG_H + // Before any calls to syslog(), make a single call to openlog() + static bool openlog_already_called = false; + if (!openlog_already_called) { + openlog(glog_internal_namespace_::ProgramInvocationShortName(), + LOG_CONS | LOG_NDELAY | LOG_PID, + LOG_USER); + openlog_already_called = true; + } + + // This array maps Google severity levels to syslog levels + const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG }; + syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast(data_->severity_)], "%.*s", + int(data_->num_chars_to_syslog_), + data_->message_text_ + data_->num_prefix_chars_); + SendToLog(); +#else + LOG(ERROR) << "No syslog support: message=" << data_->message_text_; +#endif +} + +base::Logger* base::GetLogger(LogSeverity severity) { + MutexLock l(&log_mutex); + return LogDestination::log_destination(severity)->logger_; +} + +void base::SetLogger(LogSeverity severity, base::Logger* logger) { + MutexLock l(&log_mutex); + LogDestination::log_destination(severity)->logger_ = logger; +} + +// L < log_mutex. Acquires and releases mutex_. +int64 LogMessage::num_messages(int severity) { + MutexLock l(&log_mutex); + return num_messages_[severity]; +} + +// Output the COUNTER value. This is only valid if ostream is a +// LogStream. +ostream& operator<<(ostream &os, const PRIVATE_Counter&) { +#ifdef DISABLE_RTTI + LogMessage::LogStream *log = static_cast(&os); +#else + LogMessage::LogStream *log = dynamic_cast(&os); +#endif + CHECK(log && log == log->self()) + << "You must not use COUNTER with non-glog ostream"; + os << log->ctr(); + return os; +} + +ErrnoLogMessage::ErrnoLogMessage(const char* file, int line, + LogSeverity severity, int64 ctr, + void (LogMessage::*send_method)()) + : LogMessage(file, line, severity, ctr, send_method) {} + +ErrnoLogMessage::~ErrnoLogMessage() { + // Don't access errno directly because it may have been altered + // while streaming the message. + stream() << ": " << StrError(preserved_errno()) << " [" + << preserved_errno() << "]"; +} + +void FlushLogFiles(LogSeverity min_severity) { + LogDestination::FlushLogFiles(min_severity); +} + +void FlushLogFilesUnsafe(LogSeverity min_severity) { + LogDestination::FlushLogFilesUnsafe(min_severity); +} + +void SetLogDestination(LogSeverity severity, const char* base_filename) { + LogDestination::SetLogDestination(severity, base_filename); +} + +void SetLogSymlink(LogSeverity severity, const char* symlink_basename) { + LogDestination::SetLogSymlink(severity, symlink_basename); +} + +LogSink::~LogSink() { +} + +void LogSink::send(LogSeverity severity, const char* full_filename, + const char* base_filename, int line, + const LogMessageTime& time, const char* message, + size_t message_len) { +#if defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#elif defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4996) +#endif // __GNUC__ + send(severity, full_filename, base_filename, line, &time.tm(), message, + message_len); +#if defined(__GNUC__) +#pragma GCC diagnostic pop +#elif defined(_MSC_VER) +#pragma warning(pop) +#endif // __GNUC__ +} + +void LogSink::send(LogSeverity severity, const char* full_filename, + const char* base_filename, int line, const std::tm* t, + const char* message, size_t message_len) { + (void)severity; + (void)full_filename; + (void)base_filename; + (void)line; + (void)t; + (void)message; + (void)message_len; +} + +void LogSink::WaitTillSent() { + // noop default +} + +string LogSink::ToString(LogSeverity severity, const char* file, int line, + const LogMessageTime& logmsgtime, const char* message, + size_t message_len) { + ostringstream stream(string(message, message_len)); + stream.fill('0'); + + stream << LogSeverityNames[severity][0] + << setw(4) << 1900 + logmsgtime.year() + << setw(2) << 1 + logmsgtime.month() + << setw(2) << logmsgtime.day() + << ' ' + << setw(2) << logmsgtime.hour() << ':' + << setw(2) << logmsgtime.min() << ':' + << setw(2) << logmsgtime.sec() << '.' + << setw(6) << logmsgtime.usec() + << ' ' + << setfill(' ') << setw(5) << GetTID() << setfill('0') + << ' ' + << file << ':' << line << "] "; + + stream << string(message, message_len); + return stream.str(); +} + +void AddLogSink(LogSink *destination) { + LogDestination::AddLogSink(destination); +} + +void RemoveLogSink(LogSink *destination) { + LogDestination::RemoveLogSink(destination); +} + +void SetLogFilenameExtension(const char* ext) { + LogDestination::SetLogFilenameExtension(ext); +} + +void SetStderrLogging(LogSeverity min_severity) { + LogDestination::SetStderrLogging(min_severity); +} + +void SetEmailLogging(LogSeverity min_severity, const char* addresses) { + LogDestination::SetEmailLogging(min_severity, addresses); +} + +void LogToStderr() { + LogDestination::LogToStderr(); +} + +namespace base { +namespace internal { + +bool GetExitOnDFatal(); +bool GetExitOnDFatal() { + MutexLock l(&log_mutex); + return exit_on_dfatal; +} + +// Determines whether we exit the program for a LOG(DFATAL) message in +// debug mode. It does this by skipping the call to Fail/FailQuietly. +// This is intended for testing only. +// +// This can have some effects on LOG(FATAL) as well. Failure messages +// are always allocated (rather than sharing a buffer), the crash +// reason is not recorded, the "gwq" status message is not updated, +// and the stack trace is not recorded. The LOG(FATAL) *will* still +// exit the program. Since this function is used only in testing, +// these differences are acceptable. +void SetExitOnDFatal(bool value); +void SetExitOnDFatal(bool value) { + MutexLock l(&log_mutex); + exit_on_dfatal = value; +} + +} // namespace internal +} // namespace base + +// Shell-escaping as we need to shell out ot /bin/mail. +static const char kDontNeedShellEscapeChars[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+-_.=/:,@"; + +static string ShellEscape(const string& src) { + string result; + if (!src.empty() && // empty string needs quotes + src.find_first_not_of(kDontNeedShellEscapeChars) == string::npos) { + // only contains chars that don't need quotes; it's fine + result.assign(src); + } else if (src.find_first_of('\'') == string::npos) { + // no single quotes; just wrap it in single quotes + result.assign("'"); + result.append(src); + result.append("'"); + } else { + // needs double quote escaping + result.assign("\""); + for (size_t i = 0; i < src.size(); ++i) { + switch (src[i]) { + case '\\': + case '$': + case '"': + case '`': + result.append("\\"); + } + result.append(src, i, 1); + } + result.append("\""); + } + return result; +} + + +// use_logging controls whether the logging functions LOG/VLOG are used +// to log errors. It should be set to false when the caller holds the +// log_mutex. +static bool SendEmailInternal(const char*dest, const char *subject, + const char*body, bool use_logging) { +#ifndef __EMSCRIPTEN__ + if (dest && *dest) { + if ( use_logging ) { + VLOG(1) << "Trying to send TITLE:" << subject + << " BODY:" << body << " to " << dest; + } else { + fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n", + subject, body, dest); + } + + string logmailer = FLAGS_logmailer; + if (logmailer.empty()) { + logmailer = "/bin/mail"; + } + string cmd = + logmailer + " -s" + + ShellEscape(subject) + " " + ShellEscape(dest); + if (use_logging) { + VLOG(4) << "Mailing command: " << cmd; + } + + FILE* pipe = popen(cmd.c_str(), "w"); + if (pipe != NULL) { + // Add the body if we have one + if (body) { + fwrite(body, sizeof(char), strlen(body), pipe); + } + bool ok = pclose(pipe) != -1; + if ( !ok ) { + if ( use_logging ) { + LOG(ERROR) << "Problems sending mail to " << dest << ": " + << StrError(errno); + } else { + fprintf(stderr, "Problems sending mail to %s: %s\n", + dest, StrError(errno).c_str()); + } + } + return ok; + } else { + if ( use_logging ) { + LOG(ERROR) << "Unable to send mail to " << dest; + } else { + fprintf(stderr, "Unable to send mail to %s\n", dest); + } + } + } +#endif + return false; +} + +bool SendEmail(const char*dest, const char *subject, const char*body){ + return SendEmailInternal(dest, subject, body, true); +} + +static void GetTempDirectories(vector* list) { + list->clear(); +#ifdef GLOG_OS_WINDOWS + // On windows we'll try to find a directory in this order: + // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is) + // C:/TMP/ + // C:/TEMP/ + // C:/WINDOWS/ or C:/WINNT/ + // . + char tmp[MAX_PATH]; + if (GetTempPathA(MAX_PATH, tmp)) + list->push_back(tmp); + list->push_back("C:\\tmp\\"); + list->push_back("C:\\temp\\"); +#else + // Directories, in order of preference. If we find a dir that + // exists, we stop adding other less-preferred dirs + const char * candidates[] = { + // Non-null only during unittest/regtest + getenv("TEST_TMPDIR"), + + // Explicitly-supplied temp dirs + getenv("TMPDIR"), getenv("TMP"), + + // If all else fails + "/tmp", + }; + + for (size_t i = 0; i < ARRAYSIZE(candidates); i++) { + const char *d = candidates[i]; + if (!d) continue; // Empty env var + + // Make sure we don't surprise anyone who's expecting a '/' + string dstr = d; + if (dstr[dstr.size() - 1] != '/') { + dstr += "/"; + } + list->push_back(dstr); + + struct stat statbuf; + if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) { + // We found a dir that exists - we're done. + return; + } + } + +#endif +} + +static vector* logging_directories_list; + +const vector& GetLoggingDirectories() { + // Not strictly thread-safe but we're called early in InitGoogle(). + if (logging_directories_list == NULL) { + logging_directories_list = new vector; + + if ( !FLAGS_log_dir.empty() ) { + // A dir was specified, we should use it + logging_directories_list->push_back(FLAGS_log_dir); + } else { + GetTempDirectories(logging_directories_list); +#ifdef GLOG_OS_WINDOWS + char tmp[MAX_PATH]; + if (GetWindowsDirectoryA(tmp, MAX_PATH)) + logging_directories_list->push_back(tmp); + logging_directories_list->push_back(".\\"); +#else + logging_directories_list->push_back("./"); +#endif + } + } + return *logging_directories_list; +} + +void TestOnly_ClearLoggingDirectoriesList() { + fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be " + "called from test code.\n"); + delete logging_directories_list; + logging_directories_list = NULL; +} + +void GetExistingTempDirectories(vector* list) { + GetTempDirectories(list); + vector::iterator i_dir = list->begin(); + while( i_dir != list->end() ) { + // zero arg to access means test for existence; no constant + // defined on windows + if ( access(i_dir->c_str(), 0) ) { + i_dir = list->erase(i_dir); + } else { + ++i_dir; + } + } +} + +void TruncateLogFile(const char *path, uint64 limit, uint64 keep) { +#ifdef HAVE_UNISTD_H + struct stat statbuf; + const int kCopyBlockSize = 8 << 10; + char copybuf[kCopyBlockSize]; + off_t read_offset, write_offset; + // Don't follow symlinks unless they're our own fd symlinks in /proc + int flags = O_RDWR; + // TODO(hamaji): Support other environments. +#ifdef GLOG_OS_LINUX + const char *procfd_prefix = "/proc/self/fd/"; + if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW; +#endif + + int fd = open(path, flags); + if (fd == -1) { + if (errno == EFBIG) { + // The log file in question has got too big for us to open. The + // real fix for this would be to compile logging.cc (or probably + // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's + // rather scary. + // Instead just truncate the file to something we can manage + if (truncate(path, 0) == -1) { + PLOG(ERROR) << "Unable to truncate " << path; + } else { + LOG(ERROR) << "Truncated " << path << " due to EFBIG error"; + } + } else { + PLOG(ERROR) << "Unable to open " << path; + } + return; + } + + if (fstat(fd, &statbuf) == -1) { + PLOG(ERROR) << "Unable to fstat()"; + goto out_close_fd; + } + + // See if the path refers to a regular file bigger than the + // specified limit + if (!S_ISREG(statbuf.st_mode)) goto out_close_fd; + if (statbuf.st_size <= static_cast(limit)) goto out_close_fd; + if (statbuf.st_size <= static_cast(keep)) goto out_close_fd; + + // This log file is too large - we need to truncate it + LOG(INFO) << "Truncating " << path << " to " << keep << " bytes"; + + // Copy the last "keep" bytes of the file to the beginning of the file + read_offset = statbuf.st_size - static_cast(keep); + write_offset = 0; + ssize_t bytesin, bytesout; + while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) { + bytesout = pwrite(fd, copybuf, static_cast(bytesin), write_offset); + if (bytesout == -1) { + PLOG(ERROR) << "Unable to write to " << path; + break; + } else if (bytesout != bytesin) { + LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout; + } + read_offset += bytesin; + write_offset += bytesout; + } + if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path; + + // Truncate the remainder of the file. If someone else writes to the + // end of the file after our last read() above, we lose their latest + // data. Too bad ... + if (ftruncate(fd, write_offset) == -1) { + PLOG(ERROR) << "Unable to truncate " << path; + } + + out_close_fd: + close(fd); +#else + LOG(ERROR) << "No log truncation support."; +#endif + } + +void TruncateStdoutStderr() { +#ifdef HAVE_UNISTD_H + uint64 limit = MaxLogSize() << 20U; + uint64 keep = 1U << 20U; + TruncateLogFile("/proc/self/fd/1", limit, keep); + TruncateLogFile("/proc/self/fd/2", limit, keep); +#else + LOG(ERROR) << "No log truncation support."; +#endif +} + + +// Helper functions for string comparisons. +#define DEFINE_CHECK_STROP_IMPL(name, func, expected) \ + string* Check##func##expected##Impl(const char* s1, const char* s2, \ + const char* names) { \ + bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \ + if (equal == expected) return NULL; \ + else { \ + ostringstream ss; \ + if (!s1) s1 = ""; \ + if (!s2) s2 = ""; \ + ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \ + return new string(ss.str()); \ + } \ + } +DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true) +DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false) +DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true) +DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false) +#undef DEFINE_CHECK_STROP_IMPL + +int posix_strerror_r(int err, char *buf, size_t len) { + // Sanity check input parameters + if (buf == NULL || len <= 0) { + errno = EINVAL; + return -1; + } + + // Reset buf and errno, and try calling whatever version of strerror_r() + // is implemented by glibc + buf[0] = '\000'; + int old_errno = errno; + errno = 0; + char *rc = reinterpret_cast(strerror_r(err, buf, len)); + + // Both versions set errno on failure + if (errno) { + // Should already be there, but better safe than sorry + buf[0] = '\000'; + return -1; + } + errno = old_errno; + + // POSIX is vague about whether the string will be terminated, although + // is indirectly implies that typically ERANGE will be returned, instead + // of truncating the string. This is different from the GNU implementation. + // We play it safe by always terminating the string explicitly. + buf[len-1] = '\000'; + + // If the function succeeded, we can use its exit code to determine the + // semantics implemented by glibc + if (!rc) { + return 0; + } else { + // GNU semantics detected + if (rc == buf) { + return 0; + } else { + buf[0] = '\000'; +#if defined(GLOG_OS_MACOSX) || defined(GLOG_OS_FREEBSD) || defined(GLOG_OS_OPENBSD) + if (reinterpret_cast(rc) < sys_nerr) { + // This means an error on MacOSX or FreeBSD. + return -1; + } +#endif + strncat(buf, rc, len-1); + return 0; + } + } +} + +string StrError(int err) { + char buf[100]; + int rc = posix_strerror_r(err, buf, sizeof(buf)); + if ((rc < 0) || (buf[0] == '\000')) { + snprintf(buf, sizeof(buf), "Error number %d", err); + } + return buf; +} + +LogMessageFatal::LogMessageFatal(const char* file, int line) : + LogMessage(file, line, GLOG_FATAL) {} + +LogMessageFatal::LogMessageFatal(const char* file, int line, + const CheckOpString& result) : + LogMessage(file, line, result) {} + +LogMessageFatal::~LogMessageFatal() { + Flush(); + LogMessage::Fail(); +} + +namespace base { + +CheckOpMessageBuilder::CheckOpMessageBuilder(const char *exprtext) + : stream_(new ostringstream) { + *stream_ << exprtext << " ("; +} + +CheckOpMessageBuilder::~CheckOpMessageBuilder() { + delete stream_; +} + +ostream* CheckOpMessageBuilder::ForVar2() { + *stream_ << " vs. "; + return stream_; +} + +string* CheckOpMessageBuilder::NewString() { + *stream_ << ")"; + return new string(stream_->str()); +} + +} // namespace base + +template <> +void MakeCheckOpValueString(std::ostream* os, const char& v) { + if (v >= 32 && v <= 126) { + (*os) << "'" << v << "'"; + } else { + (*os) << "char value " << static_cast(v); + } +} + +template <> +void MakeCheckOpValueString(std::ostream* os, const signed char& v) { + if (v >= 32 && v <= 126) { + (*os) << "'" << v << "'"; + } else { + (*os) << "signed char value " << static_cast(v); + } +} + +template <> +void MakeCheckOpValueString(std::ostream* os, const unsigned char& v) { + if (v >= 32 && v <= 126) { + (*os) << "'" << v << "'"; + } else { + (*os) << "unsigned char value " << static_cast(v); + } +} + +#if defined(HAVE_CXX11_NULLPTR_T) && __cplusplus >= 201103L +template <> +void MakeCheckOpValueString(std::ostream* os, const std::nullptr_t& /*v*/) { + (*os) << "nullptr"; +} +#endif // defined(HAVE_CXX11_NULLPTR_T) + +void InitGoogleLogging(const char* argv0) { + glog_internal_namespace_::InitGoogleLoggingUtilities(argv0); +} + +#ifdef GLOG_CUSTOM_PREFIX_SUPPORT +void InitGoogleLogging(const char* argv0, + CustomPrefixCallback prefix_callback, + void* prefix_callback_data) { + custom_prefix_callback = prefix_callback; + custom_prefix_callback_data = prefix_callback_data; + InitGoogleLogging(argv0); +} +#endif + +void ShutdownGoogleLogging() { + glog_internal_namespace_::ShutdownGoogleLoggingUtilities(); + LogDestination::DeleteLogDestinations(); + delete logging_directories_list; + logging_directories_list = NULL; +} + +void EnableLogCleaner(unsigned int overdue_days) { + log_cleaner.Enable(overdue_days); +} + +void DisableLogCleaner() { + log_cleaner.Disable(); +} + +LogMessageTime::LogMessageTime() + : time_struct_(), timestamp_(0), usecs_(0), gmtoffset_(0) {} + +LogMessageTime::LogMessageTime(std::tm t) { + std::time_t timestamp = std::mktime(&t); + init(t, timestamp, 0); +} + +LogMessageTime::LogMessageTime(std::time_t timestamp, WallTime now) { + std::tm t; + if (FLAGS_log_utc_time) + gmtime_r(×tamp, &t); + else + localtime_r(×tamp, &t); + init(t, timestamp, now); +} + +void LogMessageTime::init(const std::tm& t, std::time_t timestamp, + WallTime now) { + time_struct_ = t; + timestamp_ = timestamp; + usecs_ = static_cast((now - timestamp) * 1000000); + + CalcGmtOffset(); +} + +void LogMessageTime::CalcGmtOffset() { + std::tm gmt_struct; + int isDst = 0; + if ( FLAGS_log_utc_time ) { + localtime_r(×tamp_, &gmt_struct); + isDst = gmt_struct.tm_isdst; + gmt_struct = time_struct_; + } else { + isDst = time_struct_.tm_isdst; + gmtime_r(×tamp_, &gmt_struct); + } + + time_t gmt_sec = mktime(&gmt_struct); + const long hour_secs = 3600; + // If the Daylight Saving Time(isDst) is active subtract an hour from the current timestamp. + gmtoffset_ = static_cast(timestamp_ - gmt_sec + (isDst ? hour_secs : 0) ) ; +} + +_END_GOOGLE_NAMESPACE_ diff --git a/third_party/glog/src/logging_custom_prefix_unittest.cc b/third_party/glog/src/logging_custom_prefix_unittest.cc new file mode 100644 index 0000000..615dce7 --- /dev/null +++ b/third_party/glog/src/logging_custom_prefix_unittest.cc @@ -0,0 +1,1384 @@ +// Copyright (c) 2002, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Ray Sidney + +#include "utilities.h" + +#include +#ifdef HAVE_GLOB_H +# include +#endif +#include +#ifdef HAVE_UNISTD_H +# include +#endif +#ifdef HAVE_SYS_WAIT_H +# include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "base/commandlineflags.h" +#include +#include +#include "googletest.h" + +DECLARE_string(log_backtrace_at); // logging.cc + +#ifdef HAVE_LIB_GFLAGS +#include +using namespace GFLAGS_NAMESPACE; +#endif + +#ifdef HAVE_LIB_GMOCK +#include +#include "mock-log.h" +// Introduce several symbols from gmock. +using testing::_; +using testing::AnyNumber; +using testing::HasSubstr; +using testing::AllOf; +using testing::StrNe; +using testing::StrictMock; +using testing::InitGoogleMock; +using GOOGLE_NAMESPACE::glog_testing::ScopedMockLog; +#endif + +using namespace std; +using namespace GOOGLE_NAMESPACE; + +// Some non-advertised functions that we want to test or use. +_START_GOOGLE_NAMESPACE_ +namespace base { +namespace internal { +bool GetExitOnDFatal(); +void SetExitOnDFatal(bool value); +} // namespace internal +} // namespace base +_END_GOOGLE_NAMESPACE_ + +static void TestLogging(bool check_counts); +static void TestRawLogging(); +static void LogWithLevels(int v, int severity, bool err, bool alsoerr); +static void TestLoggingLevels(); +static void TestLogString(); +static void TestLogSink(); +static void TestLogToString(); +static void TestLogSinkWaitTillSent(); +static void TestCHECK(); +static void TestDCHECK(); +static void TestSTREQ(); +static void TestBasename(); +static void TestBasenameAppendWhenNoTimestamp(); +static void TestTwoProcessesWrite(); +static void TestSymlink(); +static void TestExtension(); +static void TestWrapper(); +static void TestErrno(); +static void TestTruncate(); +static void TestCustomLoggerDeletionOnShutdown(); + +static int x = -1; +static void BM_Check1(int n) { + while (n-- > 0) { + CHECK_GE(n, x); + CHECK_GE(n, x); + CHECK_GE(n, x); + CHECK_GE(n, x); + CHECK_GE(n, x); + CHECK_GE(n, x); + CHECK_GE(n, x); + CHECK_GE(n, x); + } +} +BENCHMARK(BM_Check1) + +static void CheckFailure(int a, int b, const char* file, int line, const char* msg); +static void BM_Check3(int n) { + while (n-- > 0) { + if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); + if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); + if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); + if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); + if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); + if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); + if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); + if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); + } +} +BENCHMARK(BM_Check3) + +static void BM_Check2(int n) { + if (n == 17) { + x = 5; + } + while (n-- > 0) { + CHECK(n >= x); + CHECK(n >= x); + CHECK(n >= x); + CHECK(n >= x); + CHECK(n >= x); + CHECK(n >= x); + CHECK(n >= x); + CHECK(n >= x); + } +} +BENCHMARK(BM_Check2) + +static void CheckFailure(int, int, const char* /* file */, int /* line */, + const char* /* msg */) { +} + +static void BM_logspeed(int n) { + while (n-- > 0) { + LOG(INFO) << "test message"; + } +} +BENCHMARK(BM_logspeed) + +static void BM_vlog(int n) { + while (n-- > 0) { + VLOG(1) << "test message"; + } +} +BENCHMARK(BM_vlog) + +// Dynamically generate a prefix using the default format and write it to the stream. +void PrefixAttacher(std::ostream &s, const LogMessageInfo &l, void* data) { + // Assert that `data` contains the expected contents before producing the + // prefix (otherwise causing the tests to fail): + if (data == NULL || *static_cast(data) != "good data") { + return; + } + + s << l.severity[0] + << setw(4) << 1900 + l.time.year() + << setw(2) << 1 + l.time.month() + << setw(2) << l.time.day() + << ' ' + << setw(2) << l.time.hour() << ':' + << setw(2) << l.time.min() << ':' + << setw(2) << l.time.sec() << "." + << setw(6) << l.time.usec() + << ' ' + << setfill(' ') << setw(5) + << l.thread_id << setfill('0') + << ' ' + << l.filename << ':' << l.line_number << "]"; +} + +int main(int argc, char **argv) { + FLAGS_colorlogtostderr = false; + FLAGS_timestamp_in_logfile_name = true; + + // Make sure stderr is not buffered as stderr seems to be buffered + // on recent windows. + setbuf(stderr, NULL); + + // Test some basics before InitGoogleLogging: + CaptureTestStderr(); + LogWithLevels(FLAGS_v, FLAGS_stderrthreshold, + FLAGS_logtostderr, FLAGS_alsologtostderr); + LogWithLevels(0, 0, 0, 0); // simulate "before global c-tors" + const string early_stderr = GetCapturedTestStderr(); + + EXPECT_FALSE(IsGoogleLoggingInitialized()); + + // Setting a custom prefix generator (it will use the default format so that + // the golden outputs can be reused): + string prefix_attacher_data = "good data"; + InitGoogleLogging(argv[0], &PrefixAttacher, static_cast(&prefix_attacher_data)); + + EXPECT_TRUE(IsGoogleLoggingInitialized()); + + RunSpecifiedBenchmarks(); + + FLAGS_logtostderr = true; + + InitGoogleTest(&argc, argv); +#ifdef HAVE_LIB_GMOCK + InitGoogleMock(&argc, argv); +#endif + +#ifdef HAVE_LIB_GFLAGS + ParseCommandLineFlags(&argc, &argv, true); +#endif + + // so that death tests run before we use threads + CHECK_EQ(RUN_ALL_TESTS(), 0); + + CaptureTestStderr(); + + // re-emit early_stderr + LogMessage("dummy", LogMessage::kNoLogPrefix, GLOG_INFO).stream() << early_stderr; + + TestLogging(true); + TestRawLogging(); + TestLoggingLevels(); + TestLogString(); + TestLogSink(); + TestLogToString(); + TestLogSinkWaitTillSent(); + TestCHECK(); + TestDCHECK(); + TestSTREQ(); + + // TODO: The golden test portion of this test is very flakey. + EXPECT_TRUE( + MungeAndDiffTestStderr(FLAGS_test_srcdir + "/src/logging_custom_prefix_unittest.err")); + + FLAGS_logtostderr = false; + + TestBasename(); + TestBasenameAppendWhenNoTimestamp(); + TestTwoProcessesWrite(); + TestSymlink(); + TestExtension(); + TestWrapper(); + TestErrno(); + TestTruncate(); + TestCustomLoggerDeletionOnShutdown(); + + fprintf(stdout, "PASS\n"); + return 0; +} + +void TestLogging(bool check_counts) { + int64 base_num_infos = LogMessage::num_messages(GLOG_INFO); + int64 base_num_warning = LogMessage::num_messages(GLOG_WARNING); + int64 base_num_errors = LogMessage::num_messages(GLOG_ERROR); + + LOG(INFO) << string("foo ") << "bar " << 10 << ' ' << 3.4; + for ( int i = 0; i < 10; ++i ) { + int old_errno = errno; + errno = i; + PLOG_EVERY_N(ERROR, 2) << "Plog every 2, iteration " << COUNTER; + errno = old_errno; + + LOG_EVERY_N(ERROR, 3) << "Log every 3, iteration " << COUNTER << endl; + LOG_EVERY_N(ERROR, 4) << "Log every 4, iteration " << COUNTER << endl; + + LOG_IF_EVERY_N(WARNING, true, 5) << "Log if every 5, iteration " << COUNTER; + LOG_IF_EVERY_N(WARNING, false, 3) + << "Log if every 3, iteration " << COUNTER; + LOG_IF_EVERY_N(INFO, true, 1) << "Log if every 1, iteration " << COUNTER; + LOG_IF_EVERY_N(ERROR, (i < 3), 2) + << "Log if less than 3 every 2, iteration " << COUNTER; + } + LOG_IF(WARNING, true) << "log_if this"; + LOG_IF(WARNING, false) << "don't log_if this"; + + char s[] = "array"; + LOG(INFO) << s; + const char const_s[] = "const array"; + LOG(INFO) << const_s; + int j = 1000; + LOG(ERROR) << string("foo") << ' '<< j << ' ' << setw(10) << j << " " + << setw(1) << hex << j; + LOG(INFO) << "foo " << std::setw(10) << 1.0; + + { + google::LogMessage outer(__FILE__, __LINE__, GLOG_ERROR); + outer.stream() << "outer"; + + LOG(ERROR) << "inner"; + } + + LogMessage("foo", LogMessage::kNoLogPrefix, GLOG_INFO).stream() << "no prefix"; + + if (check_counts) { + CHECK_EQ(base_num_infos + 15, LogMessage::num_messages(GLOG_INFO)); + CHECK_EQ(base_num_warning + 3, LogMessage::num_messages(GLOG_WARNING)); + CHECK_EQ(base_num_errors + 17, LogMessage::num_messages(GLOG_ERROR)); + } +} + +static void NoAllocNewHook() { + LOG(FATAL) << "unexpected new"; +} + +struct NewHook { + NewHook() { + g_new_hook = &NoAllocNewHook; + } + ~NewHook() { + g_new_hook = NULL; + } +}; + +TEST(DeathNoAllocNewHook, logging) { + // tests that NewHook used below works + NewHook new_hook; + ASSERT_DEATH({ + new int; + }, "unexpected new"); +} + +void TestRawLogging() { + string* foo = new string("foo "); + string huge_str(50000, 'a'); + + FlagSaver saver; + + // Check that RAW loggging does not use mallocs. + NewHook new_hook; + + RAW_LOG(INFO, "%s%s%d%c%f", foo->c_str(), "bar ", 10, ' ', 3.4); + char s[] = "array"; + RAW_LOG(WARNING, "%s", s); + const char const_s[] = "const array"; + RAW_LOG(INFO, "%s", const_s); + void* p = reinterpret_cast(PTR_TEST_VALUE); + RAW_LOG(INFO, "ptr %p", p); + p = NULL; + RAW_LOG(INFO, "ptr %p", p); + int j = 1000; + RAW_LOG(ERROR, "%s%d%c%010d%s%1x", foo->c_str(), j, ' ', j, " ", j); + RAW_VLOG(0, "foo %d", j); + +#if defined(NDEBUG) + RAW_LOG(INFO, "foo %d", j); // so that have same stderr to compare +#else + RAW_DLOG(INFO, "foo %d", j); // test RAW_DLOG in debug mode +#endif + + // test how long messages are chopped: + RAW_LOG(WARNING, "Huge string: %s", huge_str.c_str()); + RAW_VLOG(0, "Huge string: %s", huge_str.c_str()); + + FLAGS_v = 0; + RAW_LOG(INFO, "log"); + RAW_VLOG(0, "vlog 0 on"); + RAW_VLOG(1, "vlog 1 off"); + RAW_VLOG(2, "vlog 2 off"); + RAW_VLOG(3, "vlog 3 off"); + FLAGS_v = 2; + RAW_LOG(INFO, "log"); + RAW_VLOG(1, "vlog 1 on"); + RAW_VLOG(2, "vlog 2 on"); + RAW_VLOG(3, "vlog 3 off"); + +#if defined(NDEBUG) + RAW_DCHECK(1 == 2, " RAW_DCHECK's shouldn't be compiled in normal mode"); +#endif + + RAW_CHECK(1 == 1, "should be ok"); + RAW_DCHECK(true, "should be ok"); + + delete foo; +} + +void LogWithLevels(int v, int severity, bool err, bool alsoerr) { + RAW_LOG(INFO, + "Test: v=%d stderrthreshold=%d logtostderr=%d alsologtostderr=%d", + v, severity, err, alsoerr); + + FlagSaver saver; + + FLAGS_v = v; + FLAGS_stderrthreshold = severity; + FLAGS_logtostderr = err; + FLAGS_alsologtostderr = alsoerr; + + RAW_VLOG(-1, "vlog -1"); + RAW_VLOG(0, "vlog 0"); + RAW_VLOG(1, "vlog 1"); + RAW_LOG(INFO, "log info"); + RAW_LOG(WARNING, "log warning"); + RAW_LOG(ERROR, "log error"); + + VLOG(-1) << "vlog -1"; + VLOG(0) << "vlog 0"; + VLOG(1) << "vlog 1"; + LOG(INFO) << "log info"; + LOG(WARNING) << "log warning"; + LOG(ERROR) << "log error"; + + VLOG_IF(-1, true) << "vlog_if -1"; + VLOG_IF(-1, false) << "don't vlog_if -1"; + VLOG_IF(0, true) << "vlog_if 0"; + VLOG_IF(0, false) << "don't vlog_if 0"; + VLOG_IF(1, true) << "vlog_if 1"; + VLOG_IF(1, false) << "don't vlog_if 1"; + LOG_IF(INFO, true) << "log_if info"; + LOG_IF(INFO, false) << "don't log_if info"; + LOG_IF(WARNING, true) << "log_if warning"; + LOG_IF(WARNING, false) << "don't log_if warning"; + LOG_IF(ERROR, true) << "log_if error"; + LOG_IF(ERROR, false) << "don't log_if error"; + + int c; + c = 1; VLOG_IF(100, c -= 2) << "vlog_if 100 expr"; EXPECT_EQ(c, -1); + c = 1; VLOG_IF(0, c -= 2) << "vlog_if 0 expr"; EXPECT_EQ(c, -1); + c = 1; LOG_IF(INFO, c -= 2) << "log_if info expr"; EXPECT_EQ(c, -1); + c = 1; LOG_IF(ERROR, c -= 2) << "log_if error expr"; EXPECT_EQ(c, -1); + c = 2; VLOG_IF(0, c -= 2) << "don't vlog_if 0 expr"; EXPECT_EQ(c, 0); + c = 2; LOG_IF(ERROR, c -= 2) << "don't log_if error expr"; EXPECT_EQ(c, 0); + + c = 3; LOG_IF_EVERY_N(INFO, c -= 4, 1) << "log_if info every 1 expr"; + EXPECT_EQ(c, -1); + c = 3; LOG_IF_EVERY_N(ERROR, c -= 4, 1) << "log_if error every 1 expr"; + EXPECT_EQ(c, -1); + c = 4; LOG_IF_EVERY_N(ERROR, c -= 4, 3) << "don't log_if info every 3 expr"; + EXPECT_EQ(c, 0); + c = 4; LOG_IF_EVERY_N(ERROR, c -= 4, 3) << "don't log_if error every 3 expr"; + EXPECT_EQ(c, 0); + c = 5; VLOG_IF_EVERY_N(0, c -= 4, 1) << "vlog_if 0 every 1 expr"; + EXPECT_EQ(c, 1); + c = 5; VLOG_IF_EVERY_N(100, c -= 4, 3) << "vlog_if 100 every 3 expr"; + EXPECT_EQ(c, 1); + c = 6; VLOG_IF_EVERY_N(0, c -= 6, 1) << "don't vlog_if 0 every 1 expr"; + EXPECT_EQ(c, 0); + c = 6; VLOG_IF_EVERY_N(100, c -= 6, 3) << "don't vlog_if 100 every 1 expr"; + EXPECT_EQ(c, 0); +} + +void TestLoggingLevels() { + LogWithLevels(0, GLOG_INFO, false, false); + LogWithLevels(1, GLOG_INFO, false, false); + LogWithLevels(-1, GLOG_INFO, false, false); + LogWithLevels(0, GLOG_WARNING, false, false); + LogWithLevels(0, GLOG_ERROR, false, false); + LogWithLevels(0, GLOG_FATAL, false, false); + LogWithLevels(0, GLOG_FATAL, true, false); + LogWithLevels(0, GLOG_FATAL, false, true); + LogWithLevels(1, GLOG_WARNING, false, false); + LogWithLevels(1, GLOG_FATAL, false, true); +} + +TEST(DeathRawCHECK, logging) { + ASSERT_DEATH(RAW_CHECK(false, "failure 1"), + "RAW: Check false failed: failure 1"); + ASSERT_DEBUG_DEATH(RAW_DCHECK(1 == 2, "failure 2"), + "RAW: Check 1 == 2 failed: failure 2"); +} + +void TestLogString() { + vector errors; + vector *no_errors = NULL; + + LOG_STRING(INFO, &errors) << "LOG_STRING: " << "collected info"; + LOG_STRING(WARNING, &errors) << "LOG_STRING: " << "collected warning"; + LOG_STRING(ERROR, &errors) << "LOG_STRING: " << "collected error"; + + LOG_STRING(INFO, no_errors) << "LOG_STRING: " << "reported info"; + LOG_STRING(WARNING, no_errors) << "LOG_STRING: " << "reported warning"; + LOG_STRING(ERROR, NULL) << "LOG_STRING: " << "reported error"; + + for (size_t i = 0; i < errors.size(); ++i) { + LOG(INFO) << "Captured by LOG_STRING: " << errors[i]; + } +} + +void TestLogToString() { + string error; + string* no_error = NULL; + + LOG_TO_STRING(INFO, &error) << "LOG_TO_STRING: " << "collected info"; + LOG(INFO) << "Captured by LOG_TO_STRING: " << error; + LOG_TO_STRING(WARNING, &error) << "LOG_TO_STRING: " << "collected warning"; + LOG(INFO) << "Captured by LOG_TO_STRING: " << error; + LOG_TO_STRING(ERROR, &error) << "LOG_TO_STRING: " << "collected error"; + LOG(INFO) << "Captured by LOG_TO_STRING: " << error; + + LOG_TO_STRING(INFO, no_error) << "LOG_TO_STRING: " << "reported info"; + LOG_TO_STRING(WARNING, no_error) << "LOG_TO_STRING: " << "reported warning"; + LOG_TO_STRING(ERROR, NULL) << "LOG_TO_STRING: " << "reported error"; +} + +class TestLogSinkImpl : public LogSink { + public: + vector errors; + virtual void send(LogSeverity severity, const char* /* full_filename */, + const char* base_filename, int line, + const LogMessageTime &logmsgtime, + const char* message, size_t message_len) { + errors.push_back( + ToString(severity, base_filename, line, logmsgtime, message, message_len)); + } +}; + +void TestLogSink() { + TestLogSinkImpl sink; + LogSink *no_sink = NULL; + + LOG_TO_SINK(&sink, INFO) << "LOG_TO_SINK: " << "collected info"; + LOG_TO_SINK(&sink, WARNING) << "LOG_TO_SINK: " << "collected warning"; + LOG_TO_SINK(&sink, ERROR) << "LOG_TO_SINK: " << "collected error"; + + LOG_TO_SINK(no_sink, INFO) << "LOG_TO_SINK: " << "reported info"; + LOG_TO_SINK(no_sink, WARNING) << "LOG_TO_SINK: " << "reported warning"; + LOG_TO_SINK(NULL, ERROR) << "LOG_TO_SINK: " << "reported error"; + + LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, INFO) + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected info"; + LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, WARNING) + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected warning"; + LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, ERROR) + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected error"; + + LOG_TO_SINK_BUT_NOT_TO_LOGFILE(no_sink, INFO) + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed info"; + LOG_TO_SINK_BUT_NOT_TO_LOGFILE(no_sink, WARNING) + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed warning"; + LOG_TO_SINK_BUT_NOT_TO_LOGFILE(NULL, ERROR) + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed error"; + + LOG(INFO) << "Captured by LOG_TO_SINK:"; + for (size_t i = 0; i < sink.errors.size(); ++i) { + LogMessage("foo", LogMessage::kNoLogPrefix, GLOG_INFO).stream() + << sink.errors[i]; + } +} + +// For testing using CHECK*() on anonymous enums. +enum { + CASE_A, + CASE_B +}; + +void TestCHECK() { + // Tests using CHECK*() on int values. + CHECK(1 == 1); + CHECK_EQ(1, 1); + CHECK_NE(1, 2); + CHECK_GE(1, 1); + CHECK_GE(2, 1); + CHECK_LE(1, 1); + CHECK_LE(1, 2); + CHECK_GT(2, 1); + CHECK_LT(1, 2); + + // Tests using CHECK*() on anonymous enums. + // Apple's GCC doesn't like this. +#if !defined(GLOG_OS_MACOSX) + CHECK_EQ(CASE_A, CASE_A); + CHECK_NE(CASE_A, CASE_B); + CHECK_GE(CASE_A, CASE_A); + CHECK_GE(CASE_B, CASE_A); + CHECK_LE(CASE_A, CASE_A); + CHECK_LE(CASE_A, CASE_B); + CHECK_GT(CASE_B, CASE_A); + CHECK_LT(CASE_A, CASE_B); +#endif +} + +void TestDCHECK() { +#if defined(NDEBUG) + DCHECK( 1 == 2 ) << " DCHECK's shouldn't be compiled in normal mode"; +#endif + DCHECK( 1 == 1 ); + DCHECK_EQ(1, 1); + DCHECK_NE(1, 2); + DCHECK_GE(1, 1); + DCHECK_GE(2, 1); + DCHECK_LE(1, 1); + DCHECK_LE(1, 2); + DCHECK_GT(2, 1); + DCHECK_LT(1, 2); + + int64* orig_ptr = new int64; + int64* ptr = DCHECK_NOTNULL(orig_ptr); + CHECK_EQ(ptr, orig_ptr); + delete orig_ptr; +} + +void TestSTREQ() { + CHECK_STREQ("this", "this"); + CHECK_STREQ(NULL, NULL); + CHECK_STRCASEEQ("this", "tHiS"); + CHECK_STRCASEEQ(NULL, NULL); + CHECK_STRNE("this", "tHiS"); + CHECK_STRNE("this", NULL); + CHECK_STRCASENE("this", "that"); + CHECK_STRCASENE(NULL, "that"); + CHECK_STREQ((string("a")+"b").c_str(), "ab"); + CHECK_STREQ(string("test").c_str(), + (string("te") + string("st")).c_str()); +} + +TEST(DeathSTREQ, logging) { + ASSERT_DEATH(CHECK_STREQ(NULL, "this"), ""); + ASSERT_DEATH(CHECK_STREQ("this", "siht"), ""); + ASSERT_DEATH(CHECK_STRCASEEQ(NULL, "siht"), ""); + ASSERT_DEATH(CHECK_STRCASEEQ("this", "siht"), ""); + ASSERT_DEATH(CHECK_STRNE(NULL, NULL), ""); + ASSERT_DEATH(CHECK_STRNE("this", "this"), ""); + ASSERT_DEATH(CHECK_STREQ((string("a")+"b").c_str(), "abc"), ""); +} + +TEST(CheckNOTNULL, Simple) { + int64 t; + void *ptr = static_cast(&t); + void *ref = CHECK_NOTNULL(ptr); + EXPECT_EQ(ptr, ref); + CHECK_NOTNULL(reinterpret_cast(ptr)); + CHECK_NOTNULL(reinterpret_cast(ptr)); + CHECK_NOTNULL(reinterpret_cast(ptr)); + CHECK_NOTNULL(reinterpret_cast(ptr)); +} + +TEST(DeathCheckNN, Simple) { + ASSERT_DEATH(CHECK_NOTNULL(static_cast(NULL)), ""); +} + +// Get list of file names that match pattern +static void GetFiles(const string& pattern, vector* files) { + files->clear(); +#if defined(HAVE_GLOB_H) + glob_t g; + const int r = glob(pattern.c_str(), 0, NULL, &g); + CHECK((r == 0) || (r == GLOB_NOMATCH)) << ": error matching " << pattern; + for (size_t i = 0; i < g.gl_pathc; i++) { + files->push_back(string(g.gl_pathv[i])); + } + globfree(&g); +#elif defined(GLOG_OS_WINDOWS) + WIN32_FIND_DATAA data; + HANDLE handle = FindFirstFileA(pattern.c_str(), &data); + size_t index = pattern.rfind('\\'); + if (index == string::npos) { + LOG(FATAL) << "No directory separator."; + } + const string dirname = pattern.substr(0, index + 1); + if (handle == INVALID_HANDLE_VALUE) { + // Finding no files is OK. + return; + } + do { + files->push_back(dirname + data.cFileName); + } while (FindNextFileA(handle, &data)); + BOOL result = FindClose(handle); + LOG_SYSRESULT(result != 0); +#else +# error There is no way to do glob. +#endif +} + +// Delete files patching pattern +static void DeleteFiles(const string& pattern) { + vector files; + GetFiles(pattern, &files); + for (size_t i = 0; i < files.size(); i++) { + CHECK(unlink(files[i].c_str()) == 0) << ": " << strerror(errno); + } +} + +//check string is in file (or is *NOT*, depending on optional checkInFileOrNot) +static void CheckFile(const string& name, const string& expected_string, const bool checkInFileOrNot = true) { + vector files; + GetFiles(name + "*", &files); + CHECK_EQ(files.size(), 1UL); + + FILE* file = fopen(files[0].c_str(), "r"); + CHECK(file != NULL) << ": could not open " << files[0]; + char buf[1000]; + while (fgets(buf, sizeof(buf), file) != NULL) { + char* first = strstr(buf, expected_string.c_str()); + //if first == NULL, not found. + //Terser than if (checkInFileOrNot && first != NULL || !check... + if (checkInFileOrNot != (first == NULL)) { + fclose(file); + return; + } + } + fclose(file); + LOG(FATAL) << "Did " << (checkInFileOrNot? "not " : "") << "find " << expected_string << " in " << files[0]; +} + +static void TestBasename() { + fprintf(stderr, "==== Test setting log file basename\n"); + const string dest = FLAGS_test_tmpdir + "/logging_test_basename"; + DeleteFiles(dest + "*"); + + SetLogDestination(GLOG_INFO, dest.c_str()); + LOG(INFO) << "message to new base"; + FlushLogFiles(GLOG_INFO); + + CheckFile(dest, "message to new base"); + + // Release file handle for the destination file to unlock the file in Windows. + LogToStderr(); + DeleteFiles(dest + "*"); +} + +static void TestBasenameAppendWhenNoTimestamp() { + fprintf(stderr, "==== Test setting log file basename without timestamp and appending properly\n"); + const string dest = FLAGS_test_tmpdir + "/logging_test_basename_append_when_no_timestamp"; + DeleteFiles(dest + "*"); + + ofstream out(dest.c_str()); + out << "test preexisting content" << endl; + out.close(); + + CheckFile(dest, "test preexisting content"); + + FLAGS_timestamp_in_logfile_name=false; + SetLogDestination(GLOG_INFO, dest.c_str()); + LOG(INFO) << "message to new base, appending to preexisting file"; + FlushLogFiles(GLOG_INFO); + FLAGS_timestamp_in_logfile_name=true; + + //if the logging overwrites the file instead of appending it will fail. + CheckFile(dest, "test preexisting content"); + CheckFile(dest, "message to new base, appending to preexisting file"); + + // Release file handle for the destination file to unlock the file in Windows. + LogToStderr(); + DeleteFiles(dest + "*"); +} + +static void TestTwoProcessesWrite() { +// test only implemented for platforms with fork & wait; the actual implementation relies on flock +#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_UNISTD_H) && defined(HAVE_FCNTL) + fprintf(stderr, "==== Test setting log file basename and two processes writing - second should fail\n"); + const string dest = FLAGS_test_tmpdir + "/logging_test_basename_two_processes_writing"; + DeleteFiles(dest + "*"); + + //make both processes write into the same file (easier test) + FLAGS_timestamp_in_logfile_name=false; + SetLogDestination(GLOG_INFO, dest.c_str()); + LOG(INFO) << "message to new base, parent"; + FlushLogFiles(GLOG_INFO); + + pid_t pid = fork(); + CHECK_ERR(pid); + if (pid == 0) { + LOG(INFO) << "message to new base, child - should only appear on STDERR not on the file"; + ShutdownGoogleLogging(); //for children proc + exit(EXIT_SUCCESS); + } else if (pid > 0) { + wait(NULL); + } + FLAGS_timestamp_in_logfile_name=true; + + CheckFile(dest, "message to new base, parent"); + CheckFile(dest, "message to new base, child - should only appear on STDERR not on the file", false); + + // Release + LogToStderr(); + DeleteFiles(dest + "*"); +#endif +} + +static void TestSymlink() { +#ifndef GLOG_OS_WINDOWS + fprintf(stderr, "==== Test setting log file symlink\n"); + string dest = FLAGS_test_tmpdir + "/logging_test_symlink"; + string sym = FLAGS_test_tmpdir + "/symlinkbase"; + DeleteFiles(dest + "*"); + DeleteFiles(sym + "*"); + + SetLogSymlink(GLOG_INFO, "symlinkbase"); + SetLogDestination(GLOG_INFO, dest.c_str()); + LOG(INFO) << "message to new symlink"; + FlushLogFiles(GLOG_INFO); + CheckFile(sym, "message to new symlink"); + + DeleteFiles(dest + "*"); + DeleteFiles(sym + "*"); +#endif +} + +static void TestExtension() { + fprintf(stderr, "==== Test setting log file extension\n"); + string dest = FLAGS_test_tmpdir + "/logging_test_extension"; + DeleteFiles(dest + "*"); + + SetLogDestination(GLOG_INFO, dest.c_str()); + SetLogFilenameExtension("specialextension"); + LOG(INFO) << "message to new extension"; + FlushLogFiles(GLOG_INFO); + CheckFile(dest, "message to new extension"); + + // Check that file name ends with extension + vector filenames; + GetFiles(dest + "*", &filenames); + CHECK_EQ(filenames.size(), 1UL); + CHECK(strstr(filenames[0].c_str(), "specialextension") != NULL); + + // Release file handle for the destination file to unlock the file in Windows. + LogToStderr(); + DeleteFiles(dest + "*"); +} + +struct MyLogger : public base::Logger { + string data; + + virtual void Write(bool /* should_flush */, + time_t /* timestamp */, + const char* message, + size_t length) { + data.append(message, length); + } + + virtual void Flush() { } + + virtual uint32 LogSize() { return data.length(); } +}; + +static void TestWrapper() { + fprintf(stderr, "==== Test log wrapper\n"); + + MyLogger my_logger; + base::Logger* old_logger = base::GetLogger(GLOG_INFO); + base::SetLogger(GLOG_INFO, &my_logger); + LOG(INFO) << "Send to wrapped logger"; + FlushLogFiles(GLOG_INFO); + base::SetLogger(GLOG_INFO, old_logger); + + CHECK(strstr(my_logger.data.c_str(), "Send to wrapped logger") != NULL); +} + +static void TestErrno() { + fprintf(stderr, "==== Test errno preservation\n"); + + errno = ENOENT; + TestLogging(false); + CHECK_EQ(errno, ENOENT); +} + +static void TestOneTruncate(const char *path, uint64 limit, uint64 keep, + size_t dsize, size_t ksize, size_t expect) { + int fd; + CHECK_ERR(fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0600)); + + const char *discardstr = "DISCARDME!", *keepstr = "KEEPME!"; + const size_t discard_size = strlen(discardstr), keep_size = strlen(keepstr); + + // Fill the file with the requested data; first discard data, then kept data + size_t written = 0; + while (written < dsize) { + size_t bytes = min(dsize - written, discard_size); + CHECK_ERR(write(fd, discardstr, bytes)); + written += bytes; + } + written = 0; + while (written < ksize) { + size_t bytes = min(ksize - written, keep_size); + CHECK_ERR(write(fd, keepstr, bytes)); + written += bytes; + } + + TruncateLogFile(path, limit, keep); + + // File should now be shorter + struct stat statbuf; + CHECK_ERR(fstat(fd, &statbuf)); + CHECK_EQ(static_cast(statbuf.st_size), expect); + CHECK_ERR(lseek(fd, 0, SEEK_SET)); + + // File should contain the suffix of the original file + const size_t buf_size = static_cast(statbuf.st_size) + 1; + char* buf = new char[buf_size]; + memset(buf, 0, buf_size); + CHECK_ERR(read(fd, buf, buf_size)); + + const char* p = buf; + size_t checked = 0; + while (checked < expect) { + size_t bytes = min(expect - checked, keep_size); + CHECK(!memcmp(p, keepstr, bytes)); + checked += bytes; + } + close(fd); + delete[] buf; +} + +static void TestTruncate() { +#ifdef HAVE_UNISTD_H + fprintf(stderr, "==== Test log truncation\n"); + string path = FLAGS_test_tmpdir + "/truncatefilecustom"; + + // Test on a small file + TestOneTruncate(path.c_str(), 10, 10, 10, 10, 10); + + // And a big file (multiple blocks to copy) + TestOneTruncate(path.c_str(), 2U << 20U, 4U << 10U, 3U << 20U, 4U << 10U, + 4U << 10U); + + // Check edge-case limits + TestOneTruncate(path.c_str(), 10, 20, 0, 20, 20); + TestOneTruncate(path.c_str(), 10, 0, 0, 0, 0); + TestOneTruncate(path.c_str(), 10, 50, 0, 10, 10); + TestOneTruncate(path.c_str(), 50, 100, 0, 30, 30); + + // MacOSX 10.4 doesn't fail in this case. + // Windows doesn't have symlink. + // Let's just ignore this test for these cases. +#if !defined(GLOG_OS_MACOSX) && !defined(GLOG_OS_WINDOWS) + // Through a symlink should fail to truncate + string linkname = path + ".link"; + unlink(linkname.c_str()); + CHECK_ERR(symlink(path.c_str(), linkname.c_str())); + TestOneTruncate(linkname.c_str(), 10, 10, 0, 30, 30); +#endif + + // The /proc/self path makes sense only for linux. +#if defined(GLOG_OS_LINUX) + // Through an open fd symlink should work + int fd; + CHECK_ERR(fd = open(path.c_str(), O_APPEND | O_WRONLY)); + char fdpath[64]; + snprintf(fdpath, sizeof(fdpath), "/proc/self/fd/%d", fd); + TestOneTruncate(fdpath, 10, 10, 10, 10, 10); +#endif + +#endif +} + +struct RecordDeletionLogger : public base::Logger { + RecordDeletionLogger(bool* set_on_destruction, + base::Logger* wrapped_logger) : + set_on_destruction_(set_on_destruction), + wrapped_logger_(wrapped_logger) + { + *set_on_destruction_ = false; + } + virtual ~RecordDeletionLogger() { + *set_on_destruction_ = true; + } + virtual void Write(bool force_flush, + time_t timestamp, + const char* message, + size_t length) { + wrapped_logger_->Write(force_flush, timestamp, message, length); + } + virtual void Flush() { wrapped_logger_->Flush(); } + virtual uint32 LogSize() { return wrapped_logger_->LogSize(); } + private: + bool* set_on_destruction_; + base::Logger* wrapped_logger_; +}; + +static void TestCustomLoggerDeletionOnShutdown() { + bool custom_logger_deleted = false; + base::SetLogger(GLOG_INFO, + new RecordDeletionLogger(&custom_logger_deleted, + base::GetLogger(GLOG_INFO))); + EXPECT_TRUE(IsGoogleLoggingInitialized()); + ShutdownGoogleLogging(); + EXPECT_TRUE(custom_logger_deleted); + EXPECT_FALSE(IsGoogleLoggingInitialized()); +} + +_START_GOOGLE_NAMESPACE_ +namespace glog_internal_namespace_ { +extern // in logging.cc +bool SafeFNMatch_(const char* pattern, size_t patt_len, + const char* str, size_t str_len); +} // namespace glog_internal_namespace_ +using glog_internal_namespace_::SafeFNMatch_; +_END_GOOGLE_NAMESPACE_ + +static bool WrapSafeFNMatch(string pattern, string str) { + pattern += "abc"; + str += "defgh"; + return SafeFNMatch_(pattern.data(), pattern.size() - 3, + str.data(), str.size() - 5); +} + +TEST(SafeFNMatch, logging) { + CHECK(WrapSafeFNMatch("foo", "foo")); + CHECK(!WrapSafeFNMatch("foo", "bar")); + CHECK(!WrapSafeFNMatch("foo", "fo")); + CHECK(!WrapSafeFNMatch("foo", "foo2")); + CHECK(WrapSafeFNMatch("bar/foo.ext", "bar/foo.ext")); + CHECK(WrapSafeFNMatch("*ba*r/fo*o.ext*", "bar/foo.ext")); + CHECK(!WrapSafeFNMatch("bar/foo.ext", "bar/baz.ext")); + CHECK(!WrapSafeFNMatch("bar/foo.ext", "bar/foo")); + CHECK(!WrapSafeFNMatch("bar/foo.ext", "bar/foo.ext.zip")); + CHECK(WrapSafeFNMatch("ba?/*.ext", "bar/foo.ext")); + CHECK(WrapSafeFNMatch("ba?/*.ext", "baZ/FOO.ext")); + CHECK(!WrapSafeFNMatch("ba?/*.ext", "barr/foo.ext")); + CHECK(!WrapSafeFNMatch("ba?/*.ext", "bar/foo.ext2")); + CHECK(WrapSafeFNMatch("ba?/*", "bar/foo.ext2")); + CHECK(WrapSafeFNMatch("ba?/*", "bar/")); + CHECK(!WrapSafeFNMatch("ba?/?", "bar/")); + CHECK(!WrapSafeFNMatch("ba?/*", "bar")); +} + +// TestWaitingLogSink will save messages here +// No lock: Accessed only by TestLogSinkWriter thread +// and after its demise by its creator. +static vector global_messages; + +// helper for TestWaitingLogSink below. +// Thread that does the logic of TestWaitingLogSink +// It's free to use LOG() itself. +class TestLogSinkWriter : public Thread { + public: + + TestLogSinkWriter() : should_exit_(false) { + SetJoinable(true); + Start(); + } + + // Just buffer it (can't use LOG() here). + void Buffer(const string& message) { + mutex_.Lock(); + RAW_LOG(INFO, "Buffering"); + messages_.push(message); + mutex_.Unlock(); + RAW_LOG(INFO, "Buffered"); + } + + // Wait for the buffer to clear (can't use LOG() here). + void Wait() { + RAW_LOG(INFO, "Waiting"); + mutex_.Lock(); + while (!NoWork()) { + mutex_.Unlock(); + SleepForMilliseconds(1); + mutex_.Lock(); + } + RAW_LOG(INFO, "Waited"); + mutex_.Unlock(); + } + + // Trigger thread exit. + void Stop() { + MutexLock l(&mutex_); + should_exit_ = true; + } + + private: + + // helpers --------------- + + // For creating a "Condition". + bool NoWork() { return messages_.empty(); } + bool HaveWork() { return !messages_.empty() || should_exit_; } + + // Thread body; CAN use LOG() here! + virtual void Run() { + while (1) { + mutex_.Lock(); + while (!HaveWork()) { + mutex_.Unlock(); + SleepForMilliseconds(1); + mutex_.Lock(); + } + if (should_exit_ && messages_.empty()) { + mutex_.Unlock(); + break; + } + // Give the main thread time to log its message, + // so that we get a reliable log capture to compare to golden file. + // Same for the other sleep below. + SleepForMilliseconds(20); + RAW_LOG(INFO, "Sink got a messages"); // only RAW_LOG under mutex_ here + string message = messages_.front(); + messages_.pop(); + // Normally this would be some more real/involved logging logic + // where LOG() usage can't be eliminated, + // e.g. pushing the message over with an RPC: + size_t messages_left = messages_.size(); + mutex_.Unlock(); + SleepForMilliseconds(20); + // May not use LOG while holding mutex_, because Buffer() + // acquires mutex_, and Buffer is called from LOG(), + // which has its own internal mutex: + // LOG()->LogToSinks()->TestWaitingLogSink::send()->Buffer() + LOG(INFO) << "Sink is sending out a message: " << message; + LOG(INFO) << "Have " << messages_left << " left"; + global_messages.push_back(message); + } + } + + // data --------------- + + Mutex mutex_; + bool should_exit_; + queue messages_; // messages to be logged +}; + +// A log sink that exercises WaitTillSent: +// it pushes data to a buffer and wakes up another thread to do the logging +// (that other thread can than use LOG() itself), +class TestWaitingLogSink : public LogSink { + public: + + TestWaitingLogSink() { + tid_ = pthread_self(); // for thread-specific behavior + AddLogSink(this); + } + ~TestWaitingLogSink() { + RemoveLogSink(this); + writer_.Stop(); + writer_.Join(); + } + + // (re)define LogSink interface + + virtual void send(LogSeverity severity, const char* /* full_filename */, + const char* base_filename, int line, + const LogMessageTime &logmsgtime, + const char* message, size_t message_len) { + // Push it to Writer thread if we are the original logging thread. + // Note: Something like ThreadLocalLogSink is a better choice + // to do thread-specific LogSink logic for real. + if (pthread_equal(tid_, pthread_self())) { + writer_.Buffer(ToString(severity, base_filename, line, + logmsgtime, message, message_len)); + } + } + + virtual void WaitTillSent() { + // Wait for Writer thread if we are the original logging thread. + if (pthread_equal(tid_, pthread_self())) writer_.Wait(); + } + + private: + + pthread_t tid_; + TestLogSinkWriter writer_; +}; + +// Check that LogSink::WaitTillSent can be used in the advertised way. +// We also do golden-stderr comparison. +static void TestLogSinkWaitTillSent() { + { TestWaitingLogSink sink; + // Sleeps give the sink threads time to do all their work, + // so that we get a reliable log capture to compare to the golden file. + LOG(INFO) << "Message 1"; + SleepForMilliseconds(60); + LOG(ERROR) << "Message 2"; + SleepForMilliseconds(60); + LOG(WARNING) << "Message 3"; + SleepForMilliseconds(60); + } + for (size_t i = 0; i < global_messages.size(); ++i) { + LOG(INFO) << "Sink capture: " << global_messages[i]; + } + CHECK_EQ(global_messages.size(), 3UL); +} + +TEST(Strerror, logging) { + int errcode = EINTR; + char *msg = strdup(strerror(errcode)); + const size_t buf_size = strlen(msg) + 1; + char *buf = new char[buf_size]; + CHECK_EQ(posix_strerror_r(errcode, NULL, 0), -1); + buf[0] = 'A'; + CHECK_EQ(posix_strerror_r(errcode, buf, 0), -1); + CHECK_EQ(buf[0], 'A'); + CHECK_EQ(posix_strerror_r(errcode, NULL, buf_size), -1); +#if defined(GLOG_OS_MACOSX) || defined(GLOG_OS_FREEBSD) || defined(GLOG_OS_OPENBSD) + // MacOSX or FreeBSD considers this case is an error since there is + // no enough space. + CHECK_EQ(posix_strerror_r(errcode, buf, 1), -1); +#else + CHECK_EQ(posix_strerror_r(errcode, buf, 1), 0); +#endif + CHECK_STREQ(buf, ""); + CHECK_EQ(posix_strerror_r(errcode, buf, buf_size), 0); + CHECK_STREQ(buf, msg); + delete[] buf; + CHECK_EQ(msg, StrError(errcode)); + free(msg); +} + +// Simple routines to look at the sizes of generated code for LOG(FATAL) and +// CHECK(..) via objdump +/* +static void MyFatal() { + LOG(FATAL) << "Failed"; +} +static void MyCheck(bool a, bool b) { + CHECK_EQ(a, b); +} +*/ +#ifdef HAVE_LIB_GMOCK + +TEST(DVLog, Basic) { + ScopedMockLog log; + +#if defined(NDEBUG) + // We are expecting that nothing is logged. + EXPECT_CALL(log, Log(_, _, _)).Times(0); +#else + EXPECT_CALL(log, Log(GLOG_INFO, __FILE__, "debug log")); +#endif + + FLAGS_v = 1; + DVLOG(1) << "debug log"; +} + +TEST(DVLog, V0) { + ScopedMockLog log; + + // We are expecting that nothing is logged. + EXPECT_CALL(log, Log(_, _, _)).Times(0); + + FLAGS_v = 0; + DVLOG(1) << "debug log"; +} + +TEST(LogAtLevel, Basic) { + ScopedMockLog log; + + // The function version outputs "logging.h" as a file name. + EXPECT_CALL(log, Log(GLOG_WARNING, StrNe(__FILE__), "function version")); + EXPECT_CALL(log, Log(GLOG_INFO, __FILE__, "macro version")); + + int severity = GLOG_WARNING; + LogAtLevel(severity, "function version"); + + severity = GLOG_INFO; + // We can use the macro version as a C++ stream. + LOG_AT_LEVEL(severity) << "macro" << ' ' << "version"; +} + +TEST(TestExitOnDFatal, ToBeOrNotToBe) { + // Check the default setting... + EXPECT_TRUE(base::internal::GetExitOnDFatal()); + + // Turn off... + base::internal::SetExitOnDFatal(false); + EXPECT_FALSE(base::internal::GetExitOnDFatal()); + + // We don't die. + { + ScopedMockLog log; + //EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber()); + // LOG(DFATAL) has severity FATAL if debugging, but is + // downgraded to ERROR if not debugging. + const LogSeverity severity = +#if defined(NDEBUG) + GLOG_ERROR; +#else + GLOG_FATAL; +#endif + EXPECT_CALL(log, Log(severity, __FILE__, "This should not be fatal")); + LOG(DFATAL) << "This should not be fatal"; + } + + // Turn back on... + base::internal::SetExitOnDFatal(true); + EXPECT_TRUE(base::internal::GetExitOnDFatal()); + +#ifdef GTEST_HAS_DEATH_TEST + // Death comes on little cats' feet. + EXPECT_DEBUG_DEATH({ + LOG(DFATAL) << "This should be fatal in debug mode"; + }, "This should be fatal in debug mode"); +#endif +} + +#ifdef HAVE_STACKTRACE + +static void BacktraceAtHelper() { + LOG(INFO) << "Not me"; + +// The vertical spacing of the next 3 lines is significant. + LOG(INFO) << "Backtrace me"; +} +static int kBacktraceAtLine = __LINE__ - 2; // The line of the LOG(INFO) above + +TEST(LogBacktraceAt, DoesNotBacktraceWhenDisabled) { + StrictMock log; + + FLAGS_log_backtrace_at = ""; + + EXPECT_CALL(log, Log(_, _, "Backtrace me")); + EXPECT_CALL(log, Log(_, _, "Not me")); + + BacktraceAtHelper(); +} + +TEST(LogBacktraceAt, DoesBacktraceAtRightLineWhenEnabled) { + StrictMock log; + + char where[100]; + snprintf(where, 100, "%s:%d", const_basename(__FILE__), kBacktraceAtLine); + FLAGS_log_backtrace_at = where; + + // The LOG at the specified line should include a stacktrace which includes + // the name of the containing function, followed by the log message. + // We use HasSubstr()s instead of ContainsRegex() for environments + // which don't have regexp. + EXPECT_CALL(log, Log(_, _, AllOf(HasSubstr("stacktrace:"), + HasSubstr("BacktraceAtHelper"), + HasSubstr("main"), + HasSubstr("Backtrace me")))); + // Other LOGs should not include a backtrace. + EXPECT_CALL(log, Log(_, _, "Not me")); + + BacktraceAtHelper(); +} + +#endif // HAVE_STACKTRACE + +#endif // HAVE_LIB_GMOCK + +struct UserDefinedClass { + bool operator==(const UserDefinedClass&) const { return true; } +}; + +inline ostream& operator<<(ostream& out, const UserDefinedClass&) { + out << "OK"; + return out; +} + +TEST(UserDefinedClass, logging) { + UserDefinedClass u; + vector buf; + LOG_STRING(INFO, &buf) << u; + CHECK_EQ(1UL, buf.size()); + CHECK(buf[0].find("OK") != string::npos); + + // We must be able to compile this. + CHECK_EQ(u, u); +} + +TEST(LogMsgTime, gmtoff) { + /* + * Unit test for GMT offset API + * TODO: To properly test this API, we need a platform independent way to set time-zone. + * */ + google::LogMessage log_obj(__FILE__, __LINE__); + + long int nGmtOff = log_obj.getLogMessageTime().gmtoff(); + // GMT offset ranges from UTC-12:00 to UTC+14:00 + const long utc_min_offset = -43200; + const long utc_max_offset = 50400; + EXPECT_TRUE( (nGmtOff >= utc_min_offset) && (nGmtOff <= utc_max_offset) ); +} diff --git a/third_party/glog/src/logging_custom_prefix_unittest.err b/third_party/glog/src/logging_custom_prefix_unittest.err new file mode 100644 index 0000000..ccd5ba9 --- /dev/null +++ b/third_party/glog/src/logging_custom_prefix_unittest.err @@ -0,0 +1,308 @@ +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=2 logtostderr=0 alsologtostderr=0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log error +WARNING: Logging before InitGoogleLogging() is written to STDERR +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=0 logtostderr=0 alsologtostderr=0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] foo bar 10 3.4 +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Plog every 2, iteration 1: __SUCCESS__ [0] +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log every 3, iteration 1 +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log every 4, iteration 1 +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log if every 5, iteration 1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log if every 1, iteration 1 +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log if less than 3 every 2, iteration 1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log if every 1, iteration 2 +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Plog every 2, iteration 3: __ENOENT__ [2] +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log if every 1, iteration 3 +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log if less than 3 every 2, iteration 3 +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log every 3, iteration 4 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log if every 1, iteration 4 +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Plog every 2, iteration 5: __EINTR__ [4] +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log every 4, iteration 5 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log if every 1, iteration 5 +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log if every 5, iteration 6 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log if every 1, iteration 6 +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Plog every 2, iteration 7: __ENXIO__ [6] +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log every 3, iteration 7 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log if every 1, iteration 7 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log if every 1, iteration 8 +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Plog every 2, iteration 9: __ENOEXEC__ [8] +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log every 4, iteration 9 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log if every 1, iteration 9 +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log every 3, iteration 10 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Log if every 1, iteration 10 +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if this +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] array +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] const array +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] foo 1000 1000 3e8 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] foo 1 +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] inner +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] outer +no prefix +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: foo bar 10 3.400000 +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: array +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: const array +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: ptr __PTRTEST__ +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: ptr __NULLP__ +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: foo 1000 0000001000 3e8 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: foo 1000 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: foo 1000 +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: RAW_LOG ERROR: The Message was too long! +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: RAW_LOG ERROR: The Message was too long! +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog 0 on +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog 1 on +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog 2 on +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=0 logtostderr=0 alsologtostderr=0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Test: v=1 stderrthreshold=0 logtostderr=0 alsologtostderr=0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog 1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog 1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Test: v=-1 stderrthreshold=0 logtostderr=0 alsologtostderr=0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=1 logtostderr=0 alsologtostderr=0 +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log error +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log error +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=2 logtostderr=0 alsologtostderr=0 +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log error +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log error +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=3 logtostderr=0 alsologtostderr=0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=3 logtostderr=1 alsologtostderr=0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=3 logtostderr=0 alsologtostderr=1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Test: v=1 stderrthreshold=1 logtostderr=0 alsologtostderr=0 +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log error +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log error +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Test: v=1 stderrthreshold=3 logtostderr=0 alsologtostderr=1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: vlog 1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: log error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog 1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_STRING: reported info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_STRING: reported warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_STRING: reported error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Captured by LOG_STRING: LOG_STRING: collected info +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Captured by LOG_STRING: LOG_STRING: collected warning +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Captured by LOG_STRING: LOG_STRING: collected error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_SINK: collected info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_SINK: collected warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_SINK: collected error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_SINK: reported info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_SINK: reported warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_SINK: reported error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Captured by LOG_TO_SINK: +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_SINK: collected info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_SINK: collected warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_SINK: collected error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_SINK_BUT_NOT_TO_LOGFILE: collected info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_SINK_BUT_NOT_TO_LOGFILE: collected warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_SINK_BUT_NOT_TO_LOGFILE: collected error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_STRING: collected info +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Captured by LOG_TO_STRING: LOG_TO_STRING: collected info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_STRING: collected warning +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Captured by LOG_TO_STRING: LOG_TO_STRING: collected warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_STRING: collected error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Captured by LOG_TO_STRING: LOG_TO_STRING: collected error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_STRING: reported info +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_STRING: reported warning +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] LOG_TO_STRING: reported error +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Message 1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Buffering +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Buffered +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Waiting +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Sink got a messages +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Waited +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Sink is sending out a message: IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Message 1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Have 0 left +EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Message 2 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Buffering +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Buffered +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Waiting +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Sink got a messages +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Waited +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Sink is sending out a message: EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Message 2 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Have 0 left +WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Message 3 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Buffering +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Buffered +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Waiting +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Sink got a messages +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] RAW: Waited +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Sink is sending out a message: WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Message 3 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Have 0 left +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Sink capture: IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Message 1 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Sink capture: EYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Message 2 +IYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Sink capture: WYEARDATE TIME__ THREADID logging_custom_prefix_unittest.cc:LINE] Message 3 diff --git a/third_party/glog/src/logging_striplog_test.sh b/third_party/glog/src/logging_striplog_test.sh new file mode 100755 index 0000000..73492bd --- /dev/null +++ b/third_party/glog/src/logging_striplog_test.sh @@ -0,0 +1,79 @@ +#! /bin/sh +# +# Copyright (c) 2007, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# Author: Sergey Ioffe + +get_strings () { + if test -e ".libs/$1"; then + binary=".libs/$1" + elif test -e "$1.exe"; then + binary="$1.exe" + else + echo "We coundn't find $1 binary." + exit 1 + fi + + strings -n 10 $binary | sort | awk '/TESTMESSAGE/ {printf "%s ", $2}' +} + +# Die if "$1" != "$2", print $3 as death reason +check_eq () { + if [ "$1" != "$2" ]; then + echo "Check failed: '$1' == '$2' ${3:+ ($3)}" + exit 1 + fi +} + +die () { + echo $1 + exit 1 +} + +# Check that the string literals are appropriately stripped. This will +# not be the case in debug mode. + +mode=`GLOG_check_mode=1 ./logging_striptest0 2> /dev/null` +if [ "$mode" = "opt" ]; +then + echo "In OPT mode" + check_eq "`get_strings logging_striptest0`" "COND ERROR FATAL INFO USAGE WARNING " + check_eq "`get_strings logging_striptest2`" "COND ERROR FATAL USAGE " + check_eq "`get_strings logging_striptest10`" "" +else + echo "In DBG mode; not checking strings" +fi + +# Check that LOG(FATAL) aborts even for large STRIP_LOG + +./logging_striptest2 2>/dev/null && die "Did not abort for STRIP_LOG=2" +./logging_striptest10 2>/dev/null && die "Did not abort for STRIP_LOG=10" + +echo "PASS" diff --git a/third_party/glog/src/logging_striptest10.cc b/third_party/glog/src/logging_striptest10.cc new file mode 100644 index 0000000..f6e1078 --- /dev/null +++ b/third_party/glog/src/logging_striptest10.cc @@ -0,0 +1,35 @@ +// Copyright (c) 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Sergey Ioffe + +#define GOOGLE_STRIP_LOG 10 + +// Include the actual test. +#include "logging_striptest_main.cc" diff --git a/third_party/glog/src/logging_striptest2.cc b/third_party/glog/src/logging_striptest2.cc new file mode 100644 index 0000000..a64685c --- /dev/null +++ b/third_party/glog/src/logging_striptest2.cc @@ -0,0 +1,35 @@ +// Copyright (c) 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Sergey Ioffe + +#define GOOGLE_STRIP_LOG 2 + +// Include the actual test. +#include "logging_striptest_main.cc" diff --git a/third_party/glog/src/logging_striptest_main.cc b/third_party/glog/src/logging_striptest_main.cc new file mode 100644 index 0000000..27e1254 --- /dev/null +++ b/third_party/glog/src/logging_striptest_main.cc @@ -0,0 +1,73 @@ +// Copyright (c) 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Sergey Ioffe + +// The common part of the striplog tests. + +#include +#include +#include +#include +#include "base/commandlineflags.h" +#include "config.h" + +DECLARE_bool(logtostderr); +GLOG_DEFINE_bool(check_mode, false, "Prints 'opt' or 'dbg'"); + +using std::string; +using namespace GOOGLE_NAMESPACE; + +int CheckNoReturn(bool b) { + string s; + if (b) { + LOG(FATAL) << "Fatal"; + } else { + return 0; + } +} + +struct A { }; +std::ostream &operator<<(std::ostream &str, const A&) {return str;} + +int main(int, char* argv[]) { + FLAGS_logtostderr = true; + InitGoogleLogging(argv[0]); + if (FLAGS_check_mode) { + printf("%s\n", DEBUG_MODE ? "dbg" : "opt"); + return 0; + } + LOG(INFO) << "TESTMESSAGE INFO"; + LOG(WARNING) << 2 << "something" << "TESTMESSAGE WARNING" + << 1 << 'c' << A() << std::endl; + LOG(ERROR) << "TESTMESSAGE ERROR"; + bool flag = true; + (flag ? LOG(INFO) : LOG(ERROR)) << "TESTMESSAGE COND"; + LOG(FATAL) << "TESTMESSAGE FATAL"; +} diff --git a/third_party/glog/src/logging_unittest.cc b/third_party/glog/src/logging_unittest.cc new file mode 100644 index 0000000..728b5fe --- /dev/null +++ b/third_party/glog/src/logging_unittest.cc @@ -0,0 +1,1477 @@ +// Copyright (c) 2002, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Ray Sidney + +#include "config.h" +#include "utilities.h" + +#include +#ifdef HAVE_GLOB_H +# include +#endif +#include +#ifdef HAVE_UNISTD_H +# include +#endif +#ifdef HAVE_SYS_WAIT_H +# include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "base/commandlineflags.h" +#include +#include +#include "googletest.h" + +DECLARE_string(log_backtrace_at); // logging.cc + +#ifdef HAVE_LIB_GFLAGS +#include +using namespace GFLAGS_NAMESPACE; +#endif + +#ifdef HAVE_LIB_GMOCK +#include +#include "mock-log.h" +// Introduce several symbols from gmock. +using testing::_; +using testing::AnyNumber; +using testing::HasSubstr; +using testing::AllOf; +using testing::StrNe; +using testing::StrictMock; +using testing::InitGoogleMock; +using GOOGLE_NAMESPACE::glog_testing::ScopedMockLog; +#endif + +using namespace std; +using namespace GOOGLE_NAMESPACE; + +// Some non-advertised functions that we want to test or use. +_START_GOOGLE_NAMESPACE_ +namespace base { +namespace internal { +bool GetExitOnDFatal(); +void SetExitOnDFatal(bool value); +} // namespace internal +} // namespace base +_END_GOOGLE_NAMESPACE_ + +static void TestLogging(bool check_counts); +static void TestRawLogging(); +static void LogWithLevels(int v, int severity, bool err, bool alsoerr); +static void TestLoggingLevels(); +static void TestVLogModule(); +static void TestLogString(); +static void TestLogSink(); +static void TestLogToString(); +static void TestLogSinkWaitTillSent(); +static void TestCHECK(); +static void TestDCHECK(); +static void TestSTREQ(); +static void TestBasename(); +static void TestBasenameAppendWhenNoTimestamp(); +static void TestTwoProcessesWrite(); +static void TestSymlink(); +static void TestExtension(); +static void TestWrapper(); +static void TestErrno(); +static void TestTruncate(); +static void TestCustomLoggerDeletionOnShutdown(); +static void TestLogPeriodically(); + +static int x = -1; +static void BM_Check1(int n) { + while (n-- > 0) { + CHECK_GE(n, x); + CHECK_GE(n, x); + CHECK_GE(n, x); + CHECK_GE(n, x); + CHECK_GE(n, x); + CHECK_GE(n, x); + CHECK_GE(n, x); + CHECK_GE(n, x); + } +} +BENCHMARK(BM_Check1) + +static void CheckFailure(int a, int b, const char* file, int line, const char* msg); +static void BM_Check3(int n) { + while (n-- > 0) { + if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); + if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); + if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); + if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); + if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); + if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); + if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); + if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); + } +} +BENCHMARK(BM_Check3) + +static void BM_Check2(int n) { + if (n == 17) { + x = 5; + } + while (n-- > 0) { + CHECK(n >= x); + CHECK(n >= x); + CHECK(n >= x); + CHECK(n >= x); + CHECK(n >= x); + CHECK(n >= x); + CHECK(n >= x); + CHECK(n >= x); + } +} +BENCHMARK(BM_Check2) + +static void CheckFailure(int, int, const char* /* file */, int /* line */, + const char* /* msg */) { +} + +static void BM_logspeed(int n) { + while (n-- > 0) { + LOG(INFO) << "test message"; + } +} +BENCHMARK(BM_logspeed) + +static void BM_vlog(int n) { + while (n-- > 0) { + VLOG(1) << "test message"; + } +} +BENCHMARK(BM_vlog) + +int main(int argc, char **argv) { + FLAGS_colorlogtostderr = false; + FLAGS_timestamp_in_logfile_name = true; + + // Make sure stderr is not buffered as stderr seems to be buffered + // on recent windows. + setbuf(stderr, NULL); + + // Test some basics before InitGoogleLogging: + CaptureTestStderr(); + LogWithLevels(FLAGS_v, FLAGS_stderrthreshold, + FLAGS_logtostderr, FLAGS_alsologtostderr); + LogWithLevels(0, 0, 0, 0); // simulate "before global c-tors" + const string early_stderr = GetCapturedTestStderr(); + + EXPECT_FALSE(IsGoogleLoggingInitialized()); + + InitGoogleLogging(argv[0]); + + EXPECT_TRUE(IsGoogleLoggingInitialized()); + + RunSpecifiedBenchmarks(); + + FLAGS_logtostderr = true; + + InitGoogleTest(&argc, argv); +#ifdef HAVE_LIB_GMOCK + InitGoogleMock(&argc, argv); +#endif + +#ifdef HAVE_LIB_GFLAGS + ParseCommandLineFlags(&argc, &argv, true); +#endif + + // so that death tests run before we use threads + CHECK_EQ(RUN_ALL_TESTS(), 0); + + CaptureTestStderr(); + + // re-emit early_stderr + LogMessage("dummy", LogMessage::kNoLogPrefix, GLOG_INFO).stream() << early_stderr; + + TestLogging(true); + TestRawLogging(); + TestLoggingLevels(); + TestVLogModule(); + TestLogString(); + TestLogSink(); + TestLogToString(); + TestLogSinkWaitTillSent(); + TestCHECK(); + TestDCHECK(); + TestSTREQ(); + + // TODO: The golden test portion of this test is very flakey. + EXPECT_TRUE( + MungeAndDiffTestStderr(FLAGS_test_srcdir + "/src/logging_unittest.err")); + + FLAGS_logtostderr = false; + + FLAGS_logtostdout = true; + FLAGS_stderrthreshold = NUM_SEVERITIES; + CaptureTestStdout(); + TestRawLogging(); + TestLoggingLevels(); + TestLogString(); + TestLogSink(); + TestLogToString(); + TestLogSinkWaitTillSent(); + TestCHECK(); + TestDCHECK(); + TestSTREQ(); + EXPECT_TRUE( + MungeAndDiffTestStdout(FLAGS_test_srcdir + "/src/logging_unittest.out")); + FLAGS_logtostdout = false; + + TestBasename(); + TestBasenameAppendWhenNoTimestamp(); + TestTwoProcessesWrite(); + TestSymlink(); + TestExtension(); + TestWrapper(); + TestErrno(); + TestTruncate(); + TestCustomLoggerDeletionOnShutdown(); + TestLogPeriodically(); + + fprintf(stdout, "PASS\n"); + return 0; +} + +void TestLogging(bool check_counts) { + int64 base_num_infos = LogMessage::num_messages(GLOG_INFO); + int64 base_num_warning = LogMessage::num_messages(GLOG_WARNING); + int64 base_num_errors = LogMessage::num_messages(GLOG_ERROR); + + LOG(INFO) << string("foo ") << "bar " << 10 << ' ' << 3.4; + for ( int i = 0; i < 10; ++i ) { + int old_errno = errno; + errno = i; + PLOG_EVERY_N(ERROR, 2) << "Plog every 2, iteration " << COUNTER; + errno = old_errno; + + LOG_EVERY_N(ERROR, 3) << "Log every 3, iteration " << COUNTER << endl; + LOG_EVERY_N(ERROR, 4) << "Log every 4, iteration " << COUNTER << endl; + + LOG_IF_EVERY_N(WARNING, true, 5) << "Log if every 5, iteration " << COUNTER; + LOG_IF_EVERY_N(WARNING, false, 3) + << "Log if every 3, iteration " << COUNTER; + LOG_IF_EVERY_N(INFO, true, 1) << "Log if every 1, iteration " << COUNTER; + LOG_IF_EVERY_N(ERROR, (i < 3), 2) + << "Log if less than 3 every 2, iteration " << COUNTER; + } + LOG_IF(WARNING, true) << "log_if this"; + LOG_IF(WARNING, false) << "don't log_if this"; + + char s[] = "array"; + LOG(INFO) << s; + const char const_s[] = "const array"; + LOG(INFO) << const_s; + int j = 1000; + LOG(ERROR) << string("foo") << ' '<< j << ' ' << setw(10) << j << " " + << setw(1) << hex << j; + LOG(INFO) << "foo " << std::setw(10) << 1.0; + + { + google::LogMessage outer(__FILE__, __LINE__, GLOG_ERROR); + outer.stream() << "outer"; + + LOG(ERROR) << "inner"; + } + + LogMessage("foo", LogMessage::kNoLogPrefix, GLOG_INFO).stream() << "no prefix"; + + if (check_counts) { + CHECK_EQ(base_num_infos + 15, LogMessage::num_messages(GLOG_INFO)); + CHECK_EQ(base_num_warning + 3, LogMessage::num_messages(GLOG_WARNING)); + CHECK_EQ(base_num_errors + 17, LogMessage::num_messages(GLOG_ERROR)); + } +} + +static void NoAllocNewHook() { + LOG(FATAL) << "unexpected new"; +} + +struct NewHook { + NewHook() { + g_new_hook = &NoAllocNewHook; + } + ~NewHook() { + g_new_hook = NULL; + } +}; + +TEST(DeathNoAllocNewHook, logging) { + // tests that NewHook used below works + NewHook new_hook; + ASSERT_DEATH({ + new int; + }, "unexpected new"); +} + +void TestRawLogging() { + string* foo = new string("foo "); + string huge_str(50000, 'a'); + + FlagSaver saver; + + // Check that RAW loggging does not use mallocs. + NewHook new_hook; + + RAW_LOG(INFO, "%s%s%d%c%f", foo->c_str(), "bar ", 10, ' ', 3.4); + char s[] = "array"; + RAW_LOG(WARNING, "%s", s); + const char const_s[] = "const array"; + RAW_LOG(INFO, "%s", const_s); + void* p = reinterpret_cast(PTR_TEST_VALUE); + RAW_LOG(INFO, "ptr %p", p); + p = NULL; + RAW_LOG(INFO, "ptr %p", p); + int j = 1000; + RAW_LOG(ERROR, "%s%d%c%010d%s%1x", foo->c_str(), j, ' ', j, " ", j); + RAW_VLOG(0, "foo %d", j); + +#if defined(NDEBUG) + RAW_LOG(INFO, "foo %d", j); // so that have same stderr to compare +#else + RAW_DLOG(INFO, "foo %d", j); // test RAW_DLOG in debug mode +#endif + + // test how long messages are chopped: + RAW_LOG(WARNING, "Huge string: %s", huge_str.c_str()); + RAW_VLOG(0, "Huge string: %s", huge_str.c_str()); + + FLAGS_v = 0; + RAW_LOG(INFO, "log"); + RAW_VLOG(0, "vlog 0 on"); + RAW_VLOG(1, "vlog 1 off"); + RAW_VLOG(2, "vlog 2 off"); + RAW_VLOG(3, "vlog 3 off"); + FLAGS_v = 2; + RAW_LOG(INFO, "log"); + RAW_VLOG(1, "vlog 1 on"); + RAW_VLOG(2, "vlog 2 on"); + RAW_VLOG(3, "vlog 3 off"); + +#if defined(NDEBUG) + RAW_DCHECK(1 == 2, " RAW_DCHECK's shouldn't be compiled in normal mode"); +#endif + + RAW_CHECK(1 == 1, "should be ok"); + RAW_DCHECK(true, "should be ok"); + + delete foo; +} + +void LogWithLevels(int v, int severity, bool err, bool alsoerr) { + RAW_LOG(INFO, + "Test: v=%d stderrthreshold=%d logtostderr=%d alsologtostderr=%d", + v, severity, err, alsoerr); + + FlagSaver saver; + + FLAGS_v = v; + FLAGS_stderrthreshold = severity; + FLAGS_logtostderr = err; + FLAGS_alsologtostderr = alsoerr; + + RAW_VLOG(-1, "vlog -1"); + RAW_VLOG(0, "vlog 0"); + RAW_VLOG(1, "vlog 1"); + RAW_LOG(INFO, "log info"); + RAW_LOG(WARNING, "log warning"); + RAW_LOG(ERROR, "log error"); + + VLOG(-1) << "vlog -1"; + VLOG(0) << "vlog 0"; + VLOG(1) << "vlog 1"; + LOG(INFO) << "log info"; + LOG(WARNING) << "log warning"; + LOG(ERROR) << "log error"; + + VLOG_IF(-1, true) << "vlog_if -1"; + VLOG_IF(-1, false) << "don't vlog_if -1"; + VLOG_IF(0, true) << "vlog_if 0"; + VLOG_IF(0, false) << "don't vlog_if 0"; + VLOG_IF(1, true) << "vlog_if 1"; + VLOG_IF(1, false) << "don't vlog_if 1"; + LOG_IF(INFO, true) << "log_if info"; + LOG_IF(INFO, false) << "don't log_if info"; + LOG_IF(WARNING, true) << "log_if warning"; + LOG_IF(WARNING, false) << "don't log_if warning"; + LOG_IF(ERROR, true) << "log_if error"; + LOG_IF(ERROR, false) << "don't log_if error"; + + int c; + c = 1; VLOG_IF(100, c -= 2) << "vlog_if 100 expr"; EXPECT_EQ(c, -1); + c = 1; VLOG_IF(0, c -= 2) << "vlog_if 0 expr"; EXPECT_EQ(c, -1); + c = 1; LOG_IF(INFO, c -= 2) << "log_if info expr"; EXPECT_EQ(c, -1); + c = 1; LOG_IF(ERROR, c -= 2) << "log_if error expr"; EXPECT_EQ(c, -1); + c = 2; VLOG_IF(0, c -= 2) << "don't vlog_if 0 expr"; EXPECT_EQ(c, 0); + c = 2; LOG_IF(ERROR, c -= 2) << "don't log_if error expr"; EXPECT_EQ(c, 0); + + c = 3; LOG_IF_EVERY_N(INFO, c -= 4, 1) << "log_if info every 1 expr"; + EXPECT_EQ(c, -1); + c = 3; LOG_IF_EVERY_N(ERROR, c -= 4, 1) << "log_if error every 1 expr"; + EXPECT_EQ(c, -1); + c = 4; LOG_IF_EVERY_N(ERROR, c -= 4, 3) << "don't log_if info every 3 expr"; + EXPECT_EQ(c, 0); + c = 4; LOG_IF_EVERY_N(ERROR, c -= 4, 3) << "don't log_if error every 3 expr"; + EXPECT_EQ(c, 0); + c = 5; VLOG_IF_EVERY_N(0, c -= 4, 1) << "vlog_if 0 every 1 expr"; + EXPECT_EQ(c, 1); + c = 5; VLOG_IF_EVERY_N(100, c -= 4, 3) << "vlog_if 100 every 3 expr"; + EXPECT_EQ(c, 1); + c = 6; VLOG_IF_EVERY_N(0, c -= 6, 1) << "don't vlog_if 0 every 1 expr"; + EXPECT_EQ(c, 0); + c = 6; VLOG_IF_EVERY_N(100, c -= 6, 3) << "don't vlog_if 100 every 1 expr"; + EXPECT_EQ(c, 0); +} + +void TestLoggingLevels() { + LogWithLevels(0, GLOG_INFO, false, false); + LogWithLevels(1, GLOG_INFO, false, false); + LogWithLevels(-1, GLOG_INFO, false, false); + LogWithLevels(0, GLOG_WARNING, false, false); + LogWithLevels(0, GLOG_ERROR, false, false); + LogWithLevels(0, GLOG_FATAL, false, false); + LogWithLevels(0, GLOG_FATAL, true, false); + LogWithLevels(0, GLOG_FATAL, false, true); + LogWithLevels(1, GLOG_WARNING, false, false); + LogWithLevels(1, GLOG_FATAL, false, true); +} + +int TestVlogHelper() { + if (VLOG_IS_ON(1)) { + return 1; + } + return 0; +} + +void TestVLogModule() { + int c = TestVlogHelper(); + EXPECT_EQ(0, c); + +#if defined(__GNUC__) + EXPECT_EQ(0, SetVLOGLevel("logging_unittest", 1)); + c = TestVlogHelper(); + EXPECT_EQ(1, c); +#endif +} + +TEST(DeathRawCHECK, logging) { + ASSERT_DEATH(RAW_CHECK(false, "failure 1"), + "RAW: Check false failed: failure 1"); + ASSERT_DEBUG_DEATH(RAW_DCHECK(1 == 2, "failure 2"), + "RAW: Check 1 == 2 failed: failure 2"); +} + +void TestLogString() { + vector errors; + vector *no_errors = NULL; + + LOG_STRING(INFO, &errors) << "LOG_STRING: " << "collected info"; + LOG_STRING(WARNING, &errors) << "LOG_STRING: " << "collected warning"; + LOG_STRING(ERROR, &errors) << "LOG_STRING: " << "collected error"; + + LOG_STRING(INFO, no_errors) << "LOG_STRING: " << "reported info"; + LOG_STRING(WARNING, no_errors) << "LOG_STRING: " << "reported warning"; + LOG_STRING(ERROR, NULL) << "LOG_STRING: " << "reported error"; + + for (size_t i = 0; i < errors.size(); ++i) { + LOG(INFO) << "Captured by LOG_STRING: " << errors[i]; + } +} + +void TestLogToString() { + string error; + string* no_error = NULL; + + LOG_TO_STRING(INFO, &error) << "LOG_TO_STRING: " << "collected info"; + LOG(INFO) << "Captured by LOG_TO_STRING: " << error; + LOG_TO_STRING(WARNING, &error) << "LOG_TO_STRING: " << "collected warning"; + LOG(INFO) << "Captured by LOG_TO_STRING: " << error; + LOG_TO_STRING(ERROR, &error) << "LOG_TO_STRING: " << "collected error"; + LOG(INFO) << "Captured by LOG_TO_STRING: " << error; + + LOG_TO_STRING(INFO, no_error) << "LOG_TO_STRING: " << "reported info"; + LOG_TO_STRING(WARNING, no_error) << "LOG_TO_STRING: " << "reported warning"; + LOG_TO_STRING(ERROR, NULL) << "LOG_TO_STRING: " << "reported error"; +} + +class TestLogSinkImpl : public LogSink { + public: + vector errors; + virtual void send(LogSeverity severity, const char* /* full_filename */, + const char* base_filename, int line, + const LogMessageTime &logmsgtime, + const char* message, size_t message_len) { + errors.push_back( + ToString(severity, base_filename, line, logmsgtime, message, message_len)); + } +}; + +void TestLogSink() { + TestLogSinkImpl sink; + LogSink *no_sink = NULL; + + LOG_TO_SINK(&sink, INFO) << "LOG_TO_SINK: " << "collected info"; + LOG_TO_SINK(&sink, WARNING) << "LOG_TO_SINK: " << "collected warning"; + LOG_TO_SINK(&sink, ERROR) << "LOG_TO_SINK: " << "collected error"; + + LOG_TO_SINK(no_sink, INFO) << "LOG_TO_SINK: " << "reported info"; + LOG_TO_SINK(no_sink, WARNING) << "LOG_TO_SINK: " << "reported warning"; + LOG_TO_SINK(NULL, ERROR) << "LOG_TO_SINK: " << "reported error"; + + LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, INFO) + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected info"; + LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, WARNING) + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected warning"; + LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, ERROR) + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected error"; + + LOG_TO_SINK_BUT_NOT_TO_LOGFILE(no_sink, INFO) + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed info"; + LOG_TO_SINK_BUT_NOT_TO_LOGFILE(no_sink, WARNING) + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed warning"; + LOG_TO_SINK_BUT_NOT_TO_LOGFILE(NULL, ERROR) + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed error"; + + LOG(INFO) << "Captured by LOG_TO_SINK:"; + for (size_t i = 0; i < sink.errors.size(); ++i) { + LogMessage("foo", LogMessage::kNoLogPrefix, GLOG_INFO).stream() + << sink.errors[i]; + } +} + +// For testing using CHECK*() on anonymous enums. +enum { + CASE_A, + CASE_B +}; + +void TestCHECK() { + // Tests using CHECK*() on int values. + CHECK(1 == 1); + CHECK_EQ(1, 1); + CHECK_NE(1, 2); + CHECK_GE(1, 1); + CHECK_GE(2, 1); + CHECK_LE(1, 1); + CHECK_LE(1, 2); + CHECK_GT(2, 1); + CHECK_LT(1, 2); + + // Tests using CHECK*() on anonymous enums. + // Apple's GCC doesn't like this. +#if !defined(GLOG_OS_MACOSX) + CHECK_EQ(CASE_A, CASE_A); + CHECK_NE(CASE_A, CASE_B); + CHECK_GE(CASE_A, CASE_A); + CHECK_GE(CASE_B, CASE_A); + CHECK_LE(CASE_A, CASE_A); + CHECK_LE(CASE_A, CASE_B); + CHECK_GT(CASE_B, CASE_A); + CHECK_LT(CASE_A, CASE_B); +#endif +} + +void TestDCHECK() { +#if defined(NDEBUG) + DCHECK( 1 == 2 ) << " DCHECK's shouldn't be compiled in normal mode"; +#endif + DCHECK( 1 == 1 ); + DCHECK_EQ(1, 1); + DCHECK_NE(1, 2); + DCHECK_GE(1, 1); + DCHECK_GE(2, 1); + DCHECK_LE(1, 1); + DCHECK_LE(1, 2); + DCHECK_GT(2, 1); + DCHECK_LT(1, 2); + + int64* orig_ptr = new int64; + int64* ptr = DCHECK_NOTNULL(orig_ptr); + CHECK_EQ(ptr, orig_ptr); + delete orig_ptr; +} + +void TestSTREQ() { + CHECK_STREQ("this", "this"); + CHECK_STREQ(NULL, NULL); + CHECK_STRCASEEQ("this", "tHiS"); + CHECK_STRCASEEQ(NULL, NULL); + CHECK_STRNE("this", "tHiS"); + CHECK_STRNE("this", NULL); + CHECK_STRCASENE("this", "that"); + CHECK_STRCASENE(NULL, "that"); + CHECK_STREQ((string("a")+"b").c_str(), "ab"); + CHECK_STREQ(string("test").c_str(), + (string("te") + string("st")).c_str()); +} + +TEST(DeathSTREQ, logging) { + ASSERT_DEATH(CHECK_STREQ(NULL, "this"), ""); + ASSERT_DEATH(CHECK_STREQ("this", "siht"), ""); + ASSERT_DEATH(CHECK_STRCASEEQ(NULL, "siht"), ""); + ASSERT_DEATH(CHECK_STRCASEEQ("this", "siht"), ""); + ASSERT_DEATH(CHECK_STRNE(NULL, NULL), ""); + ASSERT_DEATH(CHECK_STRNE("this", "this"), ""); + ASSERT_DEATH(CHECK_STREQ((string("a")+"b").c_str(), "abc"), ""); +} + +TEST(CheckNOTNULL, Simple) { + int64 t; + void *ptr = static_cast(&t); + void *ref = CHECK_NOTNULL(ptr); + EXPECT_EQ(ptr, ref); + CHECK_NOTNULL(reinterpret_cast(ptr)); + CHECK_NOTNULL(reinterpret_cast(ptr)); + CHECK_NOTNULL(reinterpret_cast(ptr)); + CHECK_NOTNULL(reinterpret_cast(ptr)); +} + +TEST(DeathCheckNN, Simple) { + ASSERT_DEATH(CHECK_NOTNULL(static_cast(NULL)), ""); +} + +// Get list of file names that match pattern +static void GetFiles(const string& pattern, vector* files) { + files->clear(); +#if defined(HAVE_GLOB_H) + glob_t g; + const int r = glob(pattern.c_str(), 0, NULL, &g); + CHECK((r == 0) || (r == GLOB_NOMATCH)) << ": error matching " << pattern; + for (size_t i = 0; i < g.gl_pathc; i++) { + files->push_back(string(g.gl_pathv[i])); + } + globfree(&g); +#elif defined(GLOG_OS_WINDOWS) + WIN32_FIND_DATAA data; + HANDLE handle = FindFirstFileA(pattern.c_str(), &data); + size_t index = pattern.rfind('\\'); + if (index == string::npos) { + LOG(FATAL) << "No directory separator."; + } + const string dirname = pattern.substr(0, index + 1); + if (handle == INVALID_HANDLE_VALUE) { + // Finding no files is OK. + return; + } + do { + files->push_back(dirname + data.cFileName); + } while (FindNextFileA(handle, &data)); + BOOL result = FindClose(handle); + LOG_SYSRESULT(result != 0); +#else +# error There is no way to do glob. +#endif +} + +// Delete files patching pattern +static void DeleteFiles(const string& pattern) { + vector files; + GetFiles(pattern, &files); + for (size_t i = 0; i < files.size(); i++) { + CHECK(unlink(files[i].c_str()) == 0) << ": " << strerror(errno); + } +} + +//check string is in file (or is *NOT*, depending on optional checkInFileOrNot) +static void CheckFile(const string& name, const string& expected_string, const bool checkInFileOrNot = true) { + vector files; + GetFiles(name + "*", &files); + CHECK_EQ(files.size(), 1UL); + + FILE* file = fopen(files[0].c_str(), "r"); + CHECK(file != NULL) << ": could not open " << files[0]; + char buf[1000]; + while (fgets(buf, sizeof(buf), file) != NULL) { + char* first = strstr(buf, expected_string.c_str()); + //if first == NULL, not found. + //Terser than if (checkInFileOrNot && first != NULL || !check... + if (checkInFileOrNot != (first == NULL)) { + fclose(file); + return; + } + } + fclose(file); + LOG(FATAL) << "Did " << (checkInFileOrNot? "not " : "") << "find " << expected_string << " in " << files[0]; +} + +static void TestBasename() { + fprintf(stderr, "==== Test setting log file basename\n"); + const string dest = FLAGS_test_tmpdir + "/logging_test_basename"; + DeleteFiles(dest + "*"); + + SetLogDestination(GLOG_INFO, dest.c_str()); + LOG(INFO) << "message to new base"; + FlushLogFiles(GLOG_INFO); + + CheckFile(dest, "message to new base"); + + // Release file handle for the destination file to unlock the file in Windows. + LogToStderr(); + DeleteFiles(dest + "*"); +} + +static void TestBasenameAppendWhenNoTimestamp() { + fprintf(stderr, "==== Test setting log file basename without timestamp and appending properly\n"); + const string dest = FLAGS_test_tmpdir + "/logging_test_basename_append_when_no_timestamp"; + DeleteFiles(dest + "*"); + + ofstream out(dest.c_str()); + out << "test preexisting content" << endl; + out.close(); + + CheckFile(dest, "test preexisting content"); + + FLAGS_timestamp_in_logfile_name=false; + SetLogDestination(GLOG_INFO, dest.c_str()); + LOG(INFO) << "message to new base, appending to preexisting file"; + FlushLogFiles(GLOG_INFO); + FLAGS_timestamp_in_logfile_name=true; + + //if the logging overwrites the file instead of appending it will fail. + CheckFile(dest, "test preexisting content"); + CheckFile(dest, "message to new base, appending to preexisting file"); + + // Release file handle for the destination file to unlock the file in Windows. + LogToStderr(); + DeleteFiles(dest + "*"); +} + +static void TestTwoProcessesWrite() { +// test only implemented for platforms with fork & wait; the actual implementation relies on flock +#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_UNISTD_H) && defined(HAVE_FCNTL) + fprintf(stderr, "==== Test setting log file basename and two processes writing - second should fail\n"); + const string dest = FLAGS_test_tmpdir + "/logging_test_basename_two_processes_writing"; + DeleteFiles(dest + "*"); + + //make both processes write into the same file (easier test) + FLAGS_timestamp_in_logfile_name=false; + SetLogDestination(GLOG_INFO, dest.c_str()); + LOG(INFO) << "message to new base, parent"; + FlushLogFiles(GLOG_INFO); + + pid_t pid = fork(); + CHECK_ERR(pid); + if (pid == 0) { + LOG(INFO) << "message to new base, child - should only appear on STDERR not on the file"; + ShutdownGoogleLogging(); //for children proc + exit(EXIT_SUCCESS); + } else if (pid > 0) { + wait(NULL); + } + FLAGS_timestamp_in_logfile_name=true; + + CheckFile(dest, "message to new base, parent"); + CheckFile(dest, "message to new base, child - should only appear on STDERR not on the file", false); + + // Release + LogToStderr(); + DeleteFiles(dest + "*"); +#endif +} + +static void TestSymlink() { +#ifndef GLOG_OS_WINDOWS + fprintf(stderr, "==== Test setting log file symlink\n"); + string dest = FLAGS_test_tmpdir + "/logging_test_symlink"; + string sym = FLAGS_test_tmpdir + "/symlinkbase"; + DeleteFiles(dest + "*"); + DeleteFiles(sym + "*"); + + SetLogSymlink(GLOG_INFO, "symlinkbase"); + SetLogDestination(GLOG_INFO, dest.c_str()); + LOG(INFO) << "message to new symlink"; + FlushLogFiles(GLOG_INFO); + CheckFile(sym, "message to new symlink"); + + DeleteFiles(dest + "*"); + DeleteFiles(sym + "*"); +#endif +} + +static void TestExtension() { + fprintf(stderr, "==== Test setting log file extension\n"); + string dest = FLAGS_test_tmpdir + "/logging_test_extension"; + DeleteFiles(dest + "*"); + + SetLogDestination(GLOG_INFO, dest.c_str()); + SetLogFilenameExtension("specialextension"); + LOG(INFO) << "message to new extension"; + FlushLogFiles(GLOG_INFO); + CheckFile(dest, "message to new extension"); + + // Check that file name ends with extension + vector filenames; + GetFiles(dest + "*", &filenames); + CHECK_EQ(filenames.size(), 1UL); + CHECK(strstr(filenames[0].c_str(), "specialextension") != NULL); + + // Release file handle for the destination file to unlock the file in Windows. + LogToStderr(); + DeleteFiles(dest + "*"); +} + +struct MyLogger : public base::Logger { + string data; + + virtual void Write(bool /* should_flush */, + time_t /* timestamp */, + const char* message, + size_t length) { + data.append(message, length); + } + + virtual void Flush() { } + + virtual uint32 LogSize() { return data.length(); } +}; + +static void TestWrapper() { + fprintf(stderr, "==== Test log wrapper\n"); + + MyLogger my_logger; + base::Logger* old_logger = base::GetLogger(GLOG_INFO); + base::SetLogger(GLOG_INFO, &my_logger); + LOG(INFO) << "Send to wrapped logger"; + FlushLogFiles(GLOG_INFO); + base::SetLogger(GLOG_INFO, old_logger); + + CHECK(strstr(my_logger.data.c_str(), "Send to wrapped logger") != NULL); +} + +static void TestErrno() { + fprintf(stderr, "==== Test errno preservation\n"); + + errno = ENOENT; + TestLogging(false); + CHECK_EQ(errno, ENOENT); +} + +static void TestOneTruncate(const char *path, uint64 limit, uint64 keep, + size_t dsize, size_t ksize, size_t expect) { + int fd; + CHECK_ERR(fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0600)); + + const char *discardstr = "DISCARDME!", *keepstr = "KEEPME!"; + const size_t discard_size = strlen(discardstr), keep_size = strlen(keepstr); + + // Fill the file with the requested data; first discard data, then kept data + size_t written = 0; + while (written < dsize) { + size_t bytes = min(dsize - written, discard_size); + CHECK_ERR(write(fd, discardstr, bytes)); + written += bytes; + } + written = 0; + while (written < ksize) { + size_t bytes = min(ksize - written, keep_size); + CHECK_ERR(write(fd, keepstr, bytes)); + written += bytes; + } + + TruncateLogFile(path, limit, keep); + + // File should now be shorter + struct stat statbuf; + CHECK_ERR(fstat(fd, &statbuf)); + CHECK_EQ(static_cast(statbuf.st_size), expect); + CHECK_ERR(lseek(fd, 0, SEEK_SET)); + + // File should contain the suffix of the original file + const size_t buf_size = static_cast(statbuf.st_size) + 1; + char* buf = new char[buf_size]; + memset(buf, 0, buf_size); + CHECK_ERR(read(fd, buf, buf_size)); + + const char* p = buf; + size_t checked = 0; + while (checked < expect) { + size_t bytes = min(expect - checked, keep_size); + CHECK(!memcmp(p, keepstr, bytes)); + checked += bytes; + } + close(fd); + delete[] buf; +} + +static void TestTruncate() { +#ifdef HAVE_UNISTD_H + fprintf(stderr, "==== Test log truncation\n"); + string path = FLAGS_test_tmpdir + "/truncatefile"; + + // Test on a small file + TestOneTruncate(path.c_str(), 10, 10, 10, 10, 10); + + // And a big file (multiple blocks to copy) + TestOneTruncate(path.c_str(), 2U << 20U, 4U << 10U, 3U << 20U, 4U << 10U, + 4U << 10U); + + // Check edge-case limits + TestOneTruncate(path.c_str(), 10, 20, 0, 20, 20); + TestOneTruncate(path.c_str(), 10, 0, 0, 0, 0); + TestOneTruncate(path.c_str(), 10, 50, 0, 10, 10); + TestOneTruncate(path.c_str(), 50, 100, 0, 30, 30); + + // MacOSX 10.4 doesn't fail in this case. + // Windows doesn't have symlink. + // Let's just ignore this test for these cases. +#if !defined(GLOG_OS_MACOSX) && !defined(GLOG_OS_WINDOWS) + // Through a symlink should fail to truncate + string linkname = path + ".link"; + unlink(linkname.c_str()); + CHECK_ERR(symlink(path.c_str(), linkname.c_str())); + TestOneTruncate(linkname.c_str(), 10, 10, 0, 30, 30); +#endif + + // The /proc/self path makes sense only for linux. +#if defined(GLOG_OS_LINUX) + // Through an open fd symlink should work + int fd; + CHECK_ERR(fd = open(path.c_str(), O_APPEND | O_WRONLY)); + char fdpath[64]; + snprintf(fdpath, sizeof(fdpath), "/proc/self/fd/%d", fd); + TestOneTruncate(fdpath, 10, 10, 10, 10, 10); +#endif + +#endif +} + +struct RecordDeletionLogger : public base::Logger { + RecordDeletionLogger(bool* set_on_destruction, + base::Logger* wrapped_logger) : + set_on_destruction_(set_on_destruction), + wrapped_logger_(wrapped_logger) + { + *set_on_destruction_ = false; + } + virtual ~RecordDeletionLogger() { + *set_on_destruction_ = true; + } + virtual void Write(bool force_flush, + time_t timestamp, + const char* message, + size_t length) { + wrapped_logger_->Write(force_flush, timestamp, message, length); + } + virtual void Flush() { wrapped_logger_->Flush(); } + virtual uint32 LogSize() { return wrapped_logger_->LogSize(); } + private: + bool* set_on_destruction_; + base::Logger* wrapped_logger_; +}; + +static void TestCustomLoggerDeletionOnShutdown() { + bool custom_logger_deleted = false; + base::SetLogger(GLOG_INFO, + new RecordDeletionLogger(&custom_logger_deleted, + base::GetLogger(GLOG_INFO))); + EXPECT_TRUE(IsGoogleLoggingInitialized()); + ShutdownGoogleLogging(); + EXPECT_TRUE(custom_logger_deleted); + EXPECT_FALSE(IsGoogleLoggingInitialized()); +} + +namespace LogTimes { +// Log a "message" every 10ms, 10 times. These numbers are nice compromise +// between total running time of 100ms and the period of 10ms. The period is +// large enough such that any CPU and OS scheduling variation shouldn't affect +// the results from the ideal case by more than 5% (500us or 0.5ms) +GLOG_CONSTEXPR int64_t LOG_PERIOD_NS = 10000000; // 10ms +GLOG_CONSTEXPR int64_t LOG_PERIOD_TOL_NS = 500000; // 500us + +// Set an upper limit for the number of times the stream operator can be +// called. Make sure not to exceed this number of times the stream operator is +// called, since it is also the array size and will be indexed by the stream +// operator. +GLOG_CONSTEXPR size_t MAX_CALLS = 10; +} // namespace LogTimes + +#if defined(HAVE_CXX11_CHRONO) && __cplusplus >= 201103L +struct LogTimeRecorder { + LogTimeRecorder() : m_streamTimes(0) {} + size_t m_streamTimes; + std::chrono::steady_clock::time_point m_callTimes[LogTimes::MAX_CALLS]; +}; +// The stream operator is called by LOG_EVERY_T every time a logging event +// occurs. Make sure to save the times for each call as they will be used later +// to verify the time delta between each call. +std::ostream& operator<<(std::ostream& stream, LogTimeRecorder& t) { + t.m_callTimes[t.m_streamTimes++] = std::chrono::steady_clock::now(); + return stream; +} +// get elapsed time in nanoseconds +int64 elapsedTime_ns(const std::chrono::steady_clock::time_point& begin, + const std::chrono::steady_clock::time_point& end) { + return std::chrono::duration_cast((end - begin)) + .count(); +} +#elif defined(GLOG_OS_WINDOWS) +struct LogTimeRecorder { + LogTimeRecorder() : m_streamTimes(0) {} + size_t m_streamTimes; + LARGE_INTEGER m_callTimes[LogTimes::MAX_CALLS]; +}; +std::ostream& operator<<(std::ostream& stream, LogTimeRecorder& t) { + QueryPerformanceCounter(&t.m_callTimes[t.m_streamTimes++]); + return stream; +} +// get elapsed time in nanoseconds +int64 elapsedTime_ns(const LARGE_INTEGER& begin, const LARGE_INTEGER& end) { + LARGE_INTEGER freq; + QueryPerformanceFrequency(&freq); + return (end.QuadPart - begin.QuadPart) * LONGLONG(1000000000) / freq.QuadPart; +} +#else +struct LogTimeRecorder { + LogTimeRecorder() : m_streamTimes(0) {} + size_t m_streamTimes; + timespec m_callTimes[LogTimes::MAX_CALLS]; +}; +std::ostream& operator<<(std::ostream& stream, LogTimeRecorder& t) { + clock_gettime(CLOCK_MONOTONIC, &t.m_callTimes[t.m_streamTimes++]); + return stream; +} +// get elapsed time in nanoseconds +int64 elapsedTime_ns(const timespec& begin, const timespec& end) { + return (end.tv_sec - begin.tv_sec) * 1000000000 + + (end.tv_nsec - begin.tv_nsec); +} +#endif + +static void TestLogPeriodically() { + fprintf(stderr, "==== Test log periodically\n"); + + LogTimeRecorder timeLogger; + + GLOG_CONSTEXPR double LOG_PERIOD_SEC = LogTimes::LOG_PERIOD_NS * 1e-9; + + while (timeLogger.m_streamTimes < LogTimes::MAX_CALLS) { + LOG_EVERY_T(INFO, LOG_PERIOD_SEC) + << timeLogger << "Timed Message #" << timeLogger.m_streamTimes; + } + + // Calculate time between each call in nanoseconds for higher resolution to + // minimize error. + int64 nsBetweenCalls[LogTimes::MAX_CALLS - 1]; + for (size_t i = 1; i < LogTimes::MAX_CALLS; ++i) { + nsBetweenCalls[i - 1] = elapsedTime_ns( + timeLogger.m_callTimes[i - 1], timeLogger.m_callTimes[i]); + } + + for (size_t idx = 0; idx < LogTimes::MAX_CALLS - 1; ++idx) { + int64 time_ns = nsBetweenCalls[idx]; + EXPECT_NEAR(time_ns, LogTimes::LOG_PERIOD_NS, LogTimes::LOG_PERIOD_TOL_NS); + } +} + +_START_GOOGLE_NAMESPACE_ +namespace glog_internal_namespace_ { +extern // in logging.cc +bool SafeFNMatch_(const char* pattern, size_t patt_len, + const char* str, size_t str_len); +} // namespace glog_internal_namespace_ +using glog_internal_namespace_::SafeFNMatch_; +_END_GOOGLE_NAMESPACE_ + +static bool WrapSafeFNMatch(string pattern, string str) { + pattern += "abc"; + str += "defgh"; + return SafeFNMatch_(pattern.data(), pattern.size() - 3, + str.data(), str.size() - 5); +} + +TEST(SafeFNMatch, logging) { + CHECK(WrapSafeFNMatch("foo", "foo")); + CHECK(!WrapSafeFNMatch("foo", "bar")); + CHECK(!WrapSafeFNMatch("foo", "fo")); + CHECK(!WrapSafeFNMatch("foo", "foo2")); + CHECK(WrapSafeFNMatch("bar/foo.ext", "bar/foo.ext")); + CHECK(WrapSafeFNMatch("*ba*r/fo*o.ext*", "bar/foo.ext")); + CHECK(!WrapSafeFNMatch("bar/foo.ext", "bar/baz.ext")); + CHECK(!WrapSafeFNMatch("bar/foo.ext", "bar/foo")); + CHECK(!WrapSafeFNMatch("bar/foo.ext", "bar/foo.ext.zip")); + CHECK(WrapSafeFNMatch("ba?/*.ext", "bar/foo.ext")); + CHECK(WrapSafeFNMatch("ba?/*.ext", "baZ/FOO.ext")); + CHECK(!WrapSafeFNMatch("ba?/*.ext", "barr/foo.ext")); + CHECK(!WrapSafeFNMatch("ba?/*.ext", "bar/foo.ext2")); + CHECK(WrapSafeFNMatch("ba?/*", "bar/foo.ext2")); + CHECK(WrapSafeFNMatch("ba?/*", "bar/")); + CHECK(!WrapSafeFNMatch("ba?/?", "bar/")); + CHECK(!WrapSafeFNMatch("ba?/*", "bar")); +} + +// TestWaitingLogSink will save messages here +// No lock: Accessed only by TestLogSinkWriter thread +// and after its demise by its creator. +static vector global_messages; + +// helper for TestWaitingLogSink below. +// Thread that does the logic of TestWaitingLogSink +// It's free to use LOG() itself. +class TestLogSinkWriter : public Thread { + public: + + TestLogSinkWriter() : should_exit_(false) { + SetJoinable(true); + Start(); + } + + // Just buffer it (can't use LOG() here). + void Buffer(const string& message) { + mutex_.Lock(); + RAW_LOG(INFO, "Buffering"); + messages_.push(message); + mutex_.Unlock(); + RAW_LOG(INFO, "Buffered"); + } + + // Wait for the buffer to clear (can't use LOG() here). + void Wait() { + RAW_LOG(INFO, "Waiting"); + mutex_.Lock(); + while (!NoWork()) { + mutex_.Unlock(); + SleepForMilliseconds(1); + mutex_.Lock(); + } + RAW_LOG(INFO, "Waited"); + mutex_.Unlock(); + } + + // Trigger thread exit. + void Stop() { + MutexLock l(&mutex_); + should_exit_ = true; + } + + private: + + // helpers --------------- + + // For creating a "Condition". + bool NoWork() { return messages_.empty(); } + bool HaveWork() { return !messages_.empty() || should_exit_; } + + // Thread body; CAN use LOG() here! + virtual void Run() { + while (1) { + mutex_.Lock(); + while (!HaveWork()) { + mutex_.Unlock(); + SleepForMilliseconds(1); + mutex_.Lock(); + } + if (should_exit_ && messages_.empty()) { + mutex_.Unlock(); + break; + } + // Give the main thread time to log its message, + // so that we get a reliable log capture to compare to golden file. + // Same for the other sleep below. + SleepForMilliseconds(20); + RAW_LOG(INFO, "Sink got a messages"); // only RAW_LOG under mutex_ here + string message = messages_.front(); + messages_.pop(); + // Normally this would be some more real/involved logging logic + // where LOG() usage can't be eliminated, + // e.g. pushing the message over with an RPC: + size_t messages_left = messages_.size(); + mutex_.Unlock(); + SleepForMilliseconds(20); + // May not use LOG while holding mutex_, because Buffer() + // acquires mutex_, and Buffer is called from LOG(), + // which has its own internal mutex: + // LOG()->LogToSinks()->TestWaitingLogSink::send()->Buffer() + LOG(INFO) << "Sink is sending out a message: " << message; + LOG(INFO) << "Have " << messages_left << " left"; + global_messages.push_back(message); + } + } + + // data --------------- + + Mutex mutex_; + bool should_exit_; + queue messages_; // messages to be logged +}; + +// A log sink that exercises WaitTillSent: +// it pushes data to a buffer and wakes up another thread to do the logging +// (that other thread can than use LOG() itself), +class TestWaitingLogSink : public LogSink { + public: + + TestWaitingLogSink() { + tid_ = pthread_self(); // for thread-specific behavior + AddLogSink(this); + } + ~TestWaitingLogSink() { + RemoveLogSink(this); + writer_.Stop(); + writer_.Join(); + } + + // (re)define LogSink interface + + virtual void send(LogSeverity severity, const char* /* full_filename */, + const char* base_filename, int line, + const LogMessageTime &logmsgtime, + const char* message, size_t message_len) { + // Push it to Writer thread if we are the original logging thread. + // Note: Something like ThreadLocalLogSink is a better choice + // to do thread-specific LogSink logic for real. + if (pthread_equal(tid_, pthread_self())) { + writer_.Buffer(ToString(severity, base_filename, line, + logmsgtime, message, message_len)); + } + } + + virtual void WaitTillSent() { + // Wait for Writer thread if we are the original logging thread. + if (pthread_equal(tid_, pthread_self())) writer_.Wait(); + } + + private: + + pthread_t tid_; + TestLogSinkWriter writer_; +}; + +// Check that LogSink::WaitTillSent can be used in the advertised way. +// We also do golden-stderr comparison. +static void TestLogSinkWaitTillSent() { + // Clear global_messages here to make sure that this test case can be + // reentered + global_messages.clear(); + { TestWaitingLogSink sink; + // Sleeps give the sink threads time to do all their work, + // so that we get a reliable log capture to compare to the golden file. + LOG(INFO) << "Message 1"; + SleepForMilliseconds(60); + LOG(ERROR) << "Message 2"; + SleepForMilliseconds(60); + LOG(WARNING) << "Message 3"; + SleepForMilliseconds(60); + } + for (size_t i = 0; i < global_messages.size(); ++i) { + LOG(INFO) << "Sink capture: " << global_messages[i]; + } + CHECK_EQ(global_messages.size(), 3UL); +} + +TEST(Strerror, logging) { + int errcode = EINTR; + char *msg = strdup(strerror(errcode)); + const size_t buf_size = strlen(msg) + 1; + char *buf = new char[buf_size]; + CHECK_EQ(posix_strerror_r(errcode, NULL, 0), -1); + buf[0] = 'A'; + CHECK_EQ(posix_strerror_r(errcode, buf, 0), -1); + CHECK_EQ(buf[0], 'A'); + CHECK_EQ(posix_strerror_r(errcode, NULL, buf_size), -1); +#if defined(GLOG_OS_MACOSX) || defined(GLOG_OS_FREEBSD) || defined(GLOG_OS_OPENBSD) + // MacOSX or FreeBSD considers this case is an error since there is + // no enough space. + CHECK_EQ(posix_strerror_r(errcode, buf, 1), -1); +#else + CHECK_EQ(posix_strerror_r(errcode, buf, 1), 0); +#endif + CHECK_STREQ(buf, ""); + CHECK_EQ(posix_strerror_r(errcode, buf, buf_size), 0); + CHECK_STREQ(buf, msg); + delete[] buf; + CHECK_EQ(msg, StrError(errcode)); + free(msg); +} + +// Simple routines to look at the sizes of generated code for LOG(FATAL) and +// CHECK(..) via objdump +/* +static void MyFatal() { + LOG(FATAL) << "Failed"; +} +static void MyCheck(bool a, bool b) { + CHECK_EQ(a, b); +} +*/ +#ifdef HAVE_LIB_GMOCK + +TEST(DVLog, Basic) { + ScopedMockLog log; + +#if defined(NDEBUG) + // We are expecting that nothing is logged. + EXPECT_CALL(log, Log(_, _, _)).Times(0); +#else + EXPECT_CALL(log, Log(GLOG_INFO, __FILE__, "debug log")); +#endif + + FLAGS_v = 1; + DVLOG(1) << "debug log"; +} + +TEST(DVLog, V0) { + ScopedMockLog log; + + // We are expecting that nothing is logged. + EXPECT_CALL(log, Log(_, _, _)).Times(0); + + FLAGS_v = 0; + DVLOG(1) << "debug log"; +} + +TEST(LogAtLevel, Basic) { + ScopedMockLog log; + + // The function version outputs "logging.h" as a file name. + EXPECT_CALL(log, Log(GLOG_WARNING, StrNe(__FILE__), "function version")); + EXPECT_CALL(log, Log(GLOG_INFO, __FILE__, "macro version")); + + int severity = GLOG_WARNING; + LogAtLevel(severity, "function version"); + + severity = GLOG_INFO; + // We can use the macro version as a C++ stream. + LOG_AT_LEVEL(severity) << "macro" << ' ' << "version"; +} + +TEST(TestExitOnDFatal, ToBeOrNotToBe) { + // Check the default setting... + EXPECT_TRUE(base::internal::GetExitOnDFatal()); + + // Turn off... + base::internal::SetExitOnDFatal(false); + EXPECT_FALSE(base::internal::GetExitOnDFatal()); + + // We don't die. + { + ScopedMockLog log; + //EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber()); + // LOG(DFATAL) has severity FATAL if debugging, but is + // downgraded to ERROR if not debugging. + const LogSeverity severity = +#if defined(NDEBUG) + GLOG_ERROR; +#else + GLOG_FATAL; +#endif + EXPECT_CALL(log, Log(severity, __FILE__, "This should not be fatal")); + LOG(DFATAL) << "This should not be fatal"; + } + + // Turn back on... + base::internal::SetExitOnDFatal(true); + EXPECT_TRUE(base::internal::GetExitOnDFatal()); + +#ifdef GTEST_HAS_DEATH_TEST + // Death comes on little cats' feet. + EXPECT_DEBUG_DEATH({ + LOG(DFATAL) << "This should be fatal in debug mode"; + }, "This should be fatal in debug mode"); +#endif +} + +#ifdef HAVE_STACKTRACE + +static void BacktraceAtHelper() { + LOG(INFO) << "Not me"; + +// The vertical spacing of the next 3 lines is significant. + LOG(INFO) << "Backtrace me"; +} +static int kBacktraceAtLine = __LINE__ - 2; // The line of the LOG(INFO) above + +TEST(LogBacktraceAt, DoesNotBacktraceWhenDisabled) { + StrictMock log; + + FLAGS_log_backtrace_at = ""; + + EXPECT_CALL(log, Log(_, _, "Backtrace me")); + EXPECT_CALL(log, Log(_, _, "Not me")); + + BacktraceAtHelper(); +} + +TEST(LogBacktraceAt, DoesBacktraceAtRightLineWhenEnabled) { + StrictMock log; + + char where[100]; + snprintf(where, 100, "%s:%d", const_basename(__FILE__), kBacktraceAtLine); + FLAGS_log_backtrace_at = where; + + // The LOG at the specified line should include a stacktrace which includes + // the name of the containing function, followed by the log message. + // We use HasSubstr()s instead of ContainsRegex() for environments + // which don't have regexp. + EXPECT_CALL(log, Log(_, _, AllOf(HasSubstr("stacktrace:"), + HasSubstr("BacktraceAtHelper"), + HasSubstr("main"), + HasSubstr("Backtrace me")))); + // Other LOGs should not include a backtrace. + EXPECT_CALL(log, Log(_, _, "Not me")); + + BacktraceAtHelper(); +} + +#endif // HAVE_STACKTRACE + +#endif // HAVE_LIB_GMOCK + +struct UserDefinedClass { + bool operator==(const UserDefinedClass&) const { return true; } +}; + +inline ostream& operator<<(ostream& out, const UserDefinedClass&) { + out << "OK"; + return out; +} + +TEST(UserDefinedClass, logging) { + UserDefinedClass u; + vector buf; + LOG_STRING(INFO, &buf) << u; + CHECK_EQ(1UL, buf.size()); + CHECK(buf[0].find("OK") != string::npos); + + // We must be able to compile this. + CHECK_EQ(u, u); +} diff --git a/third_party/glog/src/logging_unittest.err b/third_party/glog/src/logging_unittest.err new file mode 100644 index 0000000..21517cb --- /dev/null +++ b/third_party/glog/src/logging_unittest.err @@ -0,0 +1,308 @@ +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=2 logtostderr=0 alsologtostderr=0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error +WARNING: Logging before InitGoogleLogging() is written to STDERR +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=0 logtostderr=0 alsologtostderr=0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] foo bar 10 3.4 +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Plog every 2, iteration 1: __SUCCESS__ [0] +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log every 3, iteration 1 +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log every 4, iteration 1 +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 5, iteration 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 1 +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log if less than 3 every 2, iteration 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 2 +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Plog every 2, iteration 3: __ENOENT__ [2] +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 3 +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log if less than 3 every 2, iteration 3 +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log every 3, iteration 4 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 4 +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Plog every 2, iteration 5: __EINTR__ [4] +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log every 4, iteration 5 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 5 +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 5, iteration 6 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 6 +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Plog every 2, iteration 7: __ENXIO__ [6] +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log every 3, iteration 7 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 7 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 8 +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Plog every 2, iteration 9: __ENOEXEC__ [8] +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log every 4, iteration 9 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 9 +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log every 3, iteration 10 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 10 +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if this +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] array +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] const array +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] foo 1000 1000 3e8 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] foo 1 +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] inner +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] outer +no prefix +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: foo bar 10 3.400000 +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: array +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: const array +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: ptr __PTRTEST__ +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: ptr __NULLP__ +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: foo 1000 0000001000 3e8 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: foo 1000 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: foo 1000 +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: RAW_LOG ERROR: The Message was too long! +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: RAW_LOG ERROR: The Message was too long! +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 0 on +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 1 on +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 2 on +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=0 logtostderr=0 alsologtostderr=0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=1 stderrthreshold=0 logtostderr=0 alsologtostderr=0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=-1 stderrthreshold=0 logtostderr=0 alsologtostderr=0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=1 logtostderr=0 alsologtostderr=0 +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log error +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=2 logtostderr=0 alsologtostderr=0 +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log error +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=3 logtostderr=0 alsologtostderr=0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=3 logtostderr=1 alsologtostderr=0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=3 logtostderr=0 alsologtostderr=1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=1 stderrthreshold=1 logtostderr=0 alsologtostderr=0 +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log error +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=1 stderrthreshold=3 logtostderr=0 alsologtostderr=1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_STRING: reported info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_STRING: reported warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_STRING: reported error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_STRING: LOG_STRING: collected info +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_STRING: LOG_STRING: collected warning +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_STRING: LOG_STRING: collected error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: reported info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: reported warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: reported error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_TO_SINK: +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK_BUT_NOT_TO_LOGFILE: collected info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK_BUT_NOT_TO_LOGFILE: collected warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK_BUT_NOT_TO_LOGFILE: collected error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: collected info +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_TO_STRING: LOG_TO_STRING: collected info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: collected warning +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_TO_STRING: LOG_TO_STRING: collected warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: collected error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_TO_STRING: LOG_TO_STRING: collected error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: reported info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: reported warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: reported error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Buffering +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Buffered +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Waiting +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Sink got a messages +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Waited +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Sink is sending out a message: IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Have 0 left +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 2 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Buffering +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Buffered +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Waiting +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Sink got a messages +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Waited +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Sink is sending out a message: EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 2 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Have 0 left +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 3 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Buffering +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Buffered +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Waiting +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Sink got a messages +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Waited +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Sink is sending out a message: WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 3 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Have 0 left +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Sink capture: IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Sink capture: EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 2 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Sink capture: WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 3 diff --git a/third_party/glog/src/logging_unittest.out b/third_party/glog/src/logging_unittest.out new file mode 100644 index 0000000..18795e1 --- /dev/null +++ b/third_party/glog/src/logging_unittest.out @@ -0,0 +1,150 @@ +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log info +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log warning +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log info +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_STRING: reported info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_STRING: reported warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_STRING: reported error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_STRING: LOG_STRING: collected info +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_STRING: LOG_STRING: collected warning +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_STRING: LOG_STRING: collected error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: reported info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: reported warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: reported error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_TO_SINK: +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK_BUT_NOT_TO_LOGFILE: collected info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK_BUT_NOT_TO_LOGFILE: collected warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK_BUT_NOT_TO_LOGFILE: collected error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: collected info +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_TO_STRING: LOG_TO_STRING: collected info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: collected warning +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_TO_STRING: LOG_TO_STRING: collected warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: collected error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_TO_STRING: LOG_TO_STRING: collected error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: reported info +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: reported warning +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: reported error +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Sink is sending out a message: IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Have 0 left +EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 2 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Sink is sending out a message: EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 2 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Have 0 left +WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 3 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Sink is sending out a message: WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 3 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Have 0 left +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Sink capture: IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 1 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Sink capture: EYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 2 +IYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Sink capture: WYEARDATE TIME__ THREADID logging_unittest.cc:LINE] Message 3 diff --git a/third_party/glog/src/mock-log.h b/third_party/glog/src/mock-log.h new file mode 100644 index 0000000..bdfb3c5 --- /dev/null +++ b/third_party/glog/src/mock-log.h @@ -0,0 +1,156 @@ +// Copyright (c) 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Zhanyong Wan +// +// Defines the ScopedMockLog class (using Google C++ Mocking +// Framework), which is convenient for testing code that uses LOG(). + +#ifndef GLOG_SRC_MOCK_LOG_H_ +#define GLOG_SRC_MOCK_LOG_H_ + +// For GOOGLE_NAMESPACE. This must go first so we get _XOPEN_SOURCE. +#include "utilities.h" + +#include + +#include + +#include + +_START_GOOGLE_NAMESPACE_ +namespace glog_testing { + +// A ScopedMockLog object intercepts LOG() messages issued during its +// lifespan. Using this together with Google C++ Mocking Framework, +// it's very easy to test how a piece of code calls LOG(). The +// typical usage: +// +// TEST(FooTest, LogsCorrectly) { +// ScopedMockLog log; +// +// // We expect the WARNING "Something bad!" exactly twice. +// EXPECT_CALL(log, Log(WARNING, _, "Something bad!")) +// .Times(2); +// +// // We allow foo.cc to call LOG(INFO) any number of times. +// EXPECT_CALL(log, Log(INFO, HasSubstr("/foo.cc"), _)) +// .Times(AnyNumber()); +// +// Foo(); // Exercises the code under test. +// } +class ScopedMockLog : public GOOGLE_NAMESPACE::LogSink { + public: + // When a ScopedMockLog object is constructed, it starts to + // intercept logs. + ScopedMockLog() { AddLogSink(this); } + + // When the object is destructed, it stops intercepting logs. + ~ScopedMockLog() { RemoveLogSink(this); } + + // Implements the mock method: + // + // void Log(LogSeverity severity, const string& file_path, + // const string& message); + // + // The second argument to Send() is the full path of the source file + // in which the LOG() was issued. + // + // Note, that in a multi-threaded environment, all LOG() messages from a + // single thread will be handled in sequence, but that cannot be guaranteed + // for messages from different threads. In fact, if the same or multiple + // expectations are matched on two threads concurrently, their actions will + // be executed concurrently as well and may interleave. + MOCK_METHOD3(Log, void(GOOGLE_NAMESPACE::LogSeverity severity, + const std::string& file_path, + const std::string& message)); + + private: + // Implements the send() virtual function in class LogSink. + // Whenever a LOG() statement is executed, this function will be + // invoked with information presented in the LOG(). + // + // The method argument list is long and carries much information a + // test usually doesn't care about, so we trim the list before + // forwarding the call to Log(), which is much easier to use in + // tests. + // + // We still cannot call Log() directly, as it may invoke other LOG() + // messages, either due to Invoke, or due to an error logged in + // Google C++ Mocking Framework code, which would trigger a deadlock + // since a lock is held during send(). + // + // Hence, we save the message for WaitTillSent() which will be called after + // the lock on send() is released, and we'll call Log() inside + // WaitTillSent(). Since while a single send() call may be running at a + // time, multiple WaitTillSent() calls (along with the one send() call) may + // be running simultaneously, we ensure thread-safety of the exchange between + // send() and WaitTillSent(), and that for each message, LOG(), send(), + // WaitTillSent() and Log() are executed in the same thread. + virtual void send(GOOGLE_NAMESPACE::LogSeverity severity, + const char* full_filename, + const char* /*base_filename*/, int /*line*/, + const LogMessageTime & /*logmsgtime*/, + const char* message, size_t message_len) { + // We are only interested in the log severity, full file name, and + // log message. + message_info_.severity = severity; + message_info_.file_path = full_filename; + message_info_.message = std::string(message, message_len); + } + + // Implements the WaitTillSent() virtual function in class LogSink. + // It will be executed after send() and after the global logging lock is + // released, so calls within it (or rather within the Log() method called + // within) may also issue LOG() statements. + // + // LOG(), send(), WaitTillSent() and Log() will occur in the same thread for + // a given log message. + virtual void WaitTillSent() { + // First, and very importantly, we save a copy of the message being + // processed before calling Log(), since Log() may indirectly call send() + // and WaitTillSent() in the same thread again. + MessageInfo message_info = message_info_; + Log(message_info.severity, message_info.file_path, message_info.message); + } + + // All relevant information about a logged message that needs to be passed + // from send() to WaitTillSent(). + struct MessageInfo { + GOOGLE_NAMESPACE::LogSeverity severity; + std::string file_path; + std::string message; + }; + MessageInfo message_info_; +}; + +} // namespace glog_testing +_END_GOOGLE_NAMESPACE_ + +#endif // GLOG_SRC_MOCK_LOG_H_ diff --git a/third_party/glog/src/mock-log_unittest.cc b/third_party/glog/src/mock-log_unittest.cc new file mode 100644 index 0000000..b9bef4e --- /dev/null +++ b/third_party/glog/src/mock-log_unittest.cc @@ -0,0 +1,108 @@ +// Copyright (c) 2022, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Zhanyong Wan + +// Tests the ScopedMockLog class. + +#include "mock-log.h" + +#include + +#include +#include + +namespace { + +using GOOGLE_NAMESPACE::GLOG_ERROR; +using GOOGLE_NAMESPACE::GLOG_INFO; +using GOOGLE_NAMESPACE::GLOG_WARNING; +using GOOGLE_NAMESPACE::glog_testing::ScopedMockLog; +using std::string; +using testing::_; +using testing::EndsWith; +using testing::InSequence; +using testing::InvokeWithoutArgs; + +// Tests that ScopedMockLog intercepts LOG()s when it's alive. +TEST(ScopedMockLogTest, InterceptsLog) { + ScopedMockLog log; + + InSequence s; + EXPECT_CALL(log, + Log(GLOG_WARNING, EndsWith("mock-log_unittest.cc"), "Fishy.")); + EXPECT_CALL(log, Log(GLOG_INFO, _, "Working...")) + .Times(2); + EXPECT_CALL(log, Log(GLOG_ERROR, _, "Bad!!")); + + LOG(WARNING) << "Fishy."; + LOG(INFO) << "Working..."; + LOG(INFO) << "Working..."; + LOG(ERROR) << "Bad!!"; +} + +void LogBranch() { + LOG(INFO) << "Logging a branch..."; +} + +void LogTree() { + LOG(INFO) << "Logging the whole tree..."; +} + +void LogForest() { + LOG(INFO) << "Logging the entire forest."; + LOG(INFO) << "Logging the entire forest.."; + LOG(INFO) << "Logging the entire forest..."; +} + +// The purpose of the following test is to verify that intercepting logging +// continues to work properly if a LOG statement is executed within the scope +// of a mocked call. +TEST(ScopedMockLogTest, LogDuringIntercept) { + ScopedMockLog log; + InSequence s; + EXPECT_CALL(log, Log(GLOG_INFO, __FILE__, "Logging a branch...")) + .WillOnce(InvokeWithoutArgs(LogTree)); + EXPECT_CALL(log, Log(GLOG_INFO, __FILE__, "Logging the whole tree...")) + .WillOnce(InvokeWithoutArgs(LogForest)); + EXPECT_CALL(log, Log(GLOG_INFO, __FILE__, "Logging the entire forest.")); + EXPECT_CALL(log, Log(GLOG_INFO, __FILE__, "Logging the entire forest..")); + EXPECT_CALL(log, Log(GLOG_INFO, __FILE__, "Logging the entire forest...")); + LogBranch(); +} + +} // namespace + +int main(int argc, char **argv) { + GOOGLE_NAMESPACE::InitGoogleLogging(argv[0]); + testing::InitGoogleTest(&argc, argv); + testing::InitGoogleMock(&argc, argv); + + return RUN_ALL_TESTS(); +} diff --git a/third_party/glog/src/package_config_unittest/working_config/CMakeLists.txt b/third_party/glog/src/package_config_unittest/working_config/CMakeLists.txt new file mode 100644 index 0000000..5fcfe7f --- /dev/null +++ b/third_party/glog/src/package_config_unittest/working_config/CMakeLists.txt @@ -0,0 +1,8 @@ +cmake_minimum_required (VERSION 3.16) +project (glog_package_config LANGUAGES CXX) + +find_package (glog REQUIRED NO_MODULE) + +add_executable (glog_package_config glog_package_config.cc) + +target_link_libraries (glog_package_config PRIVATE glog::glog) diff --git a/third_party/glog/src/package_config_unittest/working_config/glog_package_config.cc b/third_party/glog/src/package_config_unittest/working_config/glog_package_config.cc new file mode 100644 index 0000000..b7b5cf6 --- /dev/null +++ b/third_party/glog/src/package_config_unittest/working_config/glog_package_config.cc @@ -0,0 +1,6 @@ +#include + +int main(int /*argc*/, char** argv) +{ + google::InitGoogleLogging(argv[0]); +} diff --git a/third_party/glog/src/raw_logging.cc b/third_party/glog/src/raw_logging.cc new file mode 100644 index 0000000..4315983 --- /dev/null +++ b/third_party/glog/src/raw_logging.cc @@ -0,0 +1,178 @@ +// Copyright (c) 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Maxim Lifantsev +// +// logging_unittest.cc covers the functionality herein + +#include "utilities.h" + +#include +#include +#include +#ifdef HAVE_UNISTD_H +# include // for close() and write() +#endif +#include // for open() +#include +#include "config.h" +#include // To pick up flag settings etc. +#include +#include "base/commandlineflags.h" + +#ifdef HAVE_STACKTRACE +# include "stacktrace.h" +#endif + +#if defined(HAVE_SYSCALL_H) +#include // for syscall() +#elif defined(HAVE_SYS_SYSCALL_H) +#include // for syscall() +#endif +#ifdef HAVE_UNISTD_H +# include +#endif + +#if (defined(HAVE_SYSCALL_H) || defined(HAVE_SYS_SYSCALL_H)) && (!(defined(GLOG_OS_MACOSX))) +# define safe_write(fd, s, len) syscall(SYS_write, fd, s, len) +#else + // Not so safe, but what can you do? +# define safe_write(fd, s, len) write(fd, s, len) +#endif + +_START_GOOGLE_NAMESPACE_ + +#if defined(__GNUC__) +#define GLOG_ATTRIBUTE_FORMAT(archetype, stringIndex, firstToCheck) \ + __attribute__((format(archetype, stringIndex, firstToCheck))) +#define GLOG_ATTRIBUTE_FORMAT_ARG(stringIndex) \ + __attribute__((format_arg(stringIndex))) +#else +#define GLOG_ATTRIBUTE_FORMAT(archetype, stringIndex, firstToCheck) +#define GLOG_ATTRIBUTE_FORMAT_ARG(stringIndex) +#endif + +// CAVEAT: vsnprintf called from *DoRawLog below has some (exotic) code paths +// that invoke malloc() and getenv() that might acquire some locks. +// If this becomes a problem we should reimplement a subset of vsnprintf +// that does not need locks and malloc. + +// Helper for RawLog__ below. +// *DoRawLog writes to *buf of *size and move them past the written portion. +// It returns true iff there was no overflow or error. +GLOG_ATTRIBUTE_FORMAT(printf, 3, 4) +static bool DoRawLog(char** buf, size_t* size, const char* format, ...) { + va_list ap; + va_start(ap, format); + int n = vsnprintf(*buf, *size, format, ap); + va_end(ap); + if (n < 0 || static_cast(n) > *size) return false; + *size -= static_cast(n); + *buf += n; + return true; +} + +// Helper for RawLog__ below. +inline static bool VADoRawLog(char** buf, size_t* size, + const char* format, va_list ap) { +#if defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat-nonliteral" +#endif + int n = vsnprintf(*buf, *size, format, ap); +#if defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + if (n < 0 || static_cast(n) > *size) return false; + *size -= static_cast(n); + *buf += n; + return true; +} + +static const int kLogBufSize = 3000; +static bool crashed = false; +static CrashReason crash_reason; +static char crash_buf[kLogBufSize + 1] = { 0 }; // Will end in '\0' + +GLOG_ATTRIBUTE_FORMAT(printf, 4, 5) +void RawLog__(LogSeverity severity, const char* file, int line, + const char* format, ...) { + if (!(FLAGS_logtostdout || FLAGS_logtostderr || + severity >= FLAGS_stderrthreshold || FLAGS_alsologtostderr || + !IsGoogleLoggingInitialized())) { + return; // this stderr log message is suppressed + } + // can't call localtime_r here: it can allocate + char buffer[kLogBufSize]; + char* buf = buffer; + size_t size = sizeof(buffer); + + // NOTE: this format should match the specification in base/logging.h + DoRawLog(&buf, &size, "%c00000000 00:00:00.000000 %5u %s:%d] RAW: ", + LogSeverityNames[severity][0], + static_cast(GetTID()), + const_basename(const_cast(file)), line); + + // Record the position and size of the buffer after the prefix + const char* msg_start = buf; + const size_t msg_size = size; + + va_list ap; + va_start(ap, format); + bool no_chop = VADoRawLog(&buf, &size, format, ap); + va_end(ap); + if (no_chop) { + DoRawLog(&buf, &size, "\n"); + } else { + DoRawLog(&buf, &size, "RAW_LOG ERROR: The Message was too long!\n"); + } + // We make a raw syscall to write directly to the stderr file descriptor, + // avoiding FILE buffering (to avoid invoking malloc()), and bypassing + // libc (to side-step any libc interception). + // We write just once to avoid races with other invocations of RawLog__. + safe_write(STDERR_FILENO, buffer, strlen(buffer)); + if (severity == GLOG_FATAL) { + if (!sync_val_compare_and_swap(&crashed, false, true)) { + crash_reason.filename = file; + crash_reason.line_number = line; + memcpy(crash_buf, msg_start, msg_size); // Don't include prefix + crash_reason.message = crash_buf; +#ifdef HAVE_STACKTRACE + crash_reason.depth = + GetStackTrace(crash_reason.stack, ARRAYSIZE(crash_reason.stack), 1); +#else + crash_reason.depth = 0; +#endif + SetCrashReason(&crash_reason); + } + LogMessage::Fail(); // abort() + } +} + +_END_GOOGLE_NAMESPACE_ diff --git a/third_party/glog/src/signalhandler.cc b/third_party/glog/src/signalhandler.cc new file mode 100644 index 0000000..ebe95b1 --- /dev/null +++ b/third_party/glog/src/signalhandler.cc @@ -0,0 +1,409 @@ +// Copyright (c) 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Satoru Takabayashi +// +// Implementation of InstallFailureSignalHandler(). + +#include "utilities.h" +#include "stacktrace.h" +#include "symbolize.h" +#include + +#include +#include +#ifdef HAVE_UCONTEXT_H +# include +#endif +#ifdef HAVE_SYS_UCONTEXT_H +# include +#endif +#include + +_START_GOOGLE_NAMESPACE_ + +namespace { + +// We'll install the failure signal handler for these signals. We could +// use strsignal() to get signal names, but we don't use it to avoid +// introducing yet another #ifdef complication. +// +// The list should be synced with the comment in signalhandler.h. +const struct { + int number; + const char *name; +} kFailureSignals[] = { + { SIGSEGV, "SIGSEGV" }, + { SIGILL, "SIGILL" }, + { SIGFPE, "SIGFPE" }, + { SIGABRT, "SIGABRT" }, +#if !defined(GLOG_OS_WINDOWS) + { SIGBUS, "SIGBUS" }, +#endif + { SIGTERM, "SIGTERM" }, +}; + +static bool kFailureSignalHandlerInstalled = false; + +#if !defined(GLOG_OS_WINDOWS) +// Returns the program counter from signal context, NULL if unknown. +void* GetPC(void* ucontext_in_void) { +#if (defined(HAVE_UCONTEXT_H) || defined(HAVE_SYS_UCONTEXT_H)) && defined(PC_FROM_UCONTEXT) + if (ucontext_in_void != NULL) { + ucontext_t *context = reinterpret_cast(ucontext_in_void); + return (void*)context->PC_FROM_UCONTEXT; + } +#else + (void)ucontext_in_void; +#endif + return NULL; +} +#endif + +// The class is used for formatting error messages. We don't use printf() +// as it's not async signal safe. +class MinimalFormatter { + public: + MinimalFormatter(char *buffer, size_t size) + : buffer_(buffer), + cursor_(buffer), + end_(buffer + size) { + } + + // Returns the number of bytes written in the buffer. + std::size_t num_bytes_written() const { return static_cast(cursor_ - buffer_); } + + // Appends string from "str" and updates the internal cursor. + void AppendString(const char* str) { + ptrdiff_t i = 0; + while (str[i] != '\0' && cursor_ + i < end_) { + cursor_[i] = str[i]; + ++i; + } + cursor_ += i; + } + + // Formats "number" in "radix" and updates the internal cursor. + // Lowercase letters are used for 'a' - 'z'. + void AppendUint64(uint64 number, unsigned radix) { + unsigned i = 0; + while (cursor_ + i < end_) { + const uint64 tmp = number % radix; + number /= radix; + cursor_[i] = static_cast(tmp < 10 ? '0' + tmp : 'a' + tmp - 10); + ++i; + if (number == 0) { + break; + } + } + // Reverse the bytes written. + std::reverse(cursor_, cursor_ + i); + cursor_ += i; + } + + // Formats "number" as hexadecimal number, and updates the internal + // cursor. Padding will be added in front if needed. + void AppendHexWithPadding(uint64 number, int width) { + char* start = cursor_; + AppendString("0x"); + AppendUint64(number, 16); + // Move to right and add padding in front if needed. + if (cursor_ < start + width) { + const int64 delta = start + width - cursor_; + std::copy(start, cursor_, start + delta); + std::fill(start, start + delta, ' '); + cursor_ = start + width; + } + } + + private: + char *buffer_; + char *cursor_; + const char * const end_; +}; + +// Writes the given data with the size to the standard error. +void WriteToStderr(const char* data, size_t size) { + if (write(STDERR_FILENO, data, size) < 0) { + // Ignore errors. + } +} + +// The writer function can be changed by InstallFailureWriter(). +void (*g_failure_writer)(const char* data, size_t size) = WriteToStderr; + +// Dumps time information. We don't dump human-readable time information +// as localtime() is not guaranteed to be async signal safe. +void DumpTimeInfo() { + time_t time_in_sec = time(NULL); + char buf[256]; // Big enough for time info. + MinimalFormatter formatter(buf, sizeof(buf)); + formatter.AppendString("*** Aborted at "); + formatter.AppendUint64(static_cast(time_in_sec), 10); + formatter.AppendString(" (unix time)"); + formatter.AppendString(" try \"date -d @"); + formatter.AppendUint64(static_cast(time_in_sec), 10); + formatter.AppendString("\" if you are using GNU date ***\n"); + g_failure_writer(buf, formatter.num_bytes_written()); +} + +// TODO(hamaji): Use signal instead of sigaction? +#ifdef HAVE_SIGACTION + +// Dumps information about the signal to STDERR. +void DumpSignalInfo(int signal_number, siginfo_t *siginfo) { + // Get the signal name. + const char* signal_name = NULL; + for (size_t i = 0; i < ARRAYSIZE(kFailureSignals); ++i) { + if (signal_number == kFailureSignals[i].number) { + signal_name = kFailureSignals[i].name; + } + } + + char buf[256]; // Big enough for signal info. + MinimalFormatter formatter(buf, sizeof(buf)); + + formatter.AppendString("*** "); + if (signal_name) { + formatter.AppendString(signal_name); + } else { + // Use the signal number if the name is unknown. The signal name + // should be known, but just in case. + formatter.AppendString("Signal "); + formatter.AppendUint64(static_cast(signal_number), 10); + } + formatter.AppendString(" (@0x"); + formatter.AppendUint64(reinterpret_cast(siginfo->si_addr), 16); + formatter.AppendString(")"); + formatter.AppendString(" received by PID "); + formatter.AppendUint64(static_cast(getpid()), 10); + formatter.AppendString(" (TID 0x"); + // We assume pthread_t is an integral number or a pointer, rather + // than a complex struct. In some environments, pthread_self() + // returns an uint64 but in some other environments pthread_self() + // returns a pointer. + pthread_t id = pthread_self(); + formatter.AppendUint64( + reinterpret_cast(reinterpret_cast(id)), 16); + formatter.AppendString(") "); + // Only linux has the PID of the signal sender in si_pid. +#ifdef GLOG_OS_LINUX + formatter.AppendString("from PID "); + formatter.AppendUint64(static_cast(siginfo->si_pid), 10); + formatter.AppendString("; "); +#endif + formatter.AppendString("stack trace: ***\n"); + g_failure_writer(buf, formatter.num_bytes_written()); +} + +#endif // HAVE_SIGACTION + +// Dumps information about the stack frame to STDERR. +void DumpStackFrameInfo(const char* prefix, void* pc) { + // Get the symbol name. + const char *symbol = "(unknown)"; + char symbolized[1024]; // Big enough for a sane symbol. + // Symbolizes the previous address of pc because pc may be in the + // next function. + if (Symbolize(reinterpret_cast(pc) - 1, + symbolized, sizeof(symbolized))) { + symbol = symbolized; + } + + char buf[1024]; // Big enough for stack frame info. + MinimalFormatter formatter(buf, sizeof(buf)); + + formatter.AppendString(prefix); + formatter.AppendString("@ "); + const int width = 2 * sizeof(void*) + 2; // + 2 for "0x". + formatter.AppendHexWithPadding(reinterpret_cast(pc), width); + formatter.AppendString(" "); + formatter.AppendString(symbol); + formatter.AppendString("\n"); + g_failure_writer(buf, formatter.num_bytes_written()); +} + +// Invoke the default signal handler. +void InvokeDefaultSignalHandler(int signal_number) { +#ifdef HAVE_SIGACTION + struct sigaction sig_action; + memset(&sig_action, 0, sizeof(sig_action)); + sigemptyset(&sig_action.sa_mask); + sig_action.sa_handler = SIG_DFL; + sigaction(signal_number, &sig_action, NULL); + kill(getpid(), signal_number); +#elif defined(GLOG_OS_WINDOWS) + signal(signal_number, SIG_DFL); + raise(signal_number); +#endif +} + +// This variable is used for protecting FailureSignalHandler() from +// dumping stuff while another thread is doing it. Our policy is to let +// the first thread dump stuff and let other threads wait. +// See also comments in FailureSignalHandler(). +static pthread_t* g_entered_thread_id_pointer = NULL; + +// Dumps signal and stack frame information, and invokes the default +// signal handler once our job is done. +#if defined(GLOG_OS_WINDOWS) +void FailureSignalHandler(int signal_number) +#else +void FailureSignalHandler(int signal_number, + siginfo_t *signal_info, + void *ucontext) +#endif +{ + // First check if we've already entered the function. We use an atomic + // compare and swap operation for platforms that support it. For other + // platforms, we use a naive method that could lead to a subtle race. + + // We assume pthread_self() is async signal safe, though it's not + // officially guaranteed. + pthread_t my_thread_id = pthread_self(); + // NOTE: We could simply use pthread_t rather than pthread_t* for this, + // if pthread_self() is guaranteed to return non-zero value for thread + // ids, but there is no such guarantee. We need to distinguish if the + // old value (value returned from __sync_val_compare_and_swap) is + // different from the original value (in this case NULL). + pthread_t* old_thread_id_pointer = + glog_internal_namespace_::sync_val_compare_and_swap( + &g_entered_thread_id_pointer, + static_cast(NULL), + &my_thread_id); + if (old_thread_id_pointer != NULL) { + // We've already entered the signal handler. What should we do? + if (pthread_equal(my_thread_id, *g_entered_thread_id_pointer)) { + // It looks the current thread is reentering the signal handler. + // Something must be going wrong (maybe we are reentering by another + // type of signal?). Kill ourself by the default signal handler. + InvokeDefaultSignalHandler(signal_number); + } + // Another thread is dumping stuff. Let's wait until that thread + // finishes the job and kills the process. + while (true) { + sleep(1); + } + } + // This is the first time we enter the signal handler. We are going to + // do some interesting stuff from here. + // TODO(satorux): We might want to set timeout here using alarm(), but + // mixing alarm() and sleep() can be a bad idea. + + // First dump time info. + DumpTimeInfo(); + +#if !defined(GLOG_OS_WINDOWS) + // Get the program counter from ucontext. + void *pc = GetPC(ucontext); + DumpStackFrameInfo("PC: ", pc); +#endif + +#ifdef HAVE_STACKTRACE + // Get the stack traces. + void *stack[32]; + // +1 to exclude this function. + const int depth = GetStackTrace(stack, ARRAYSIZE(stack), 1); +# ifdef HAVE_SIGACTION + DumpSignalInfo(signal_number, signal_info); +# endif + // Dump the stack traces. + for (int i = 0; i < depth; ++i) { + DumpStackFrameInfo(" ", stack[i]); + } +#endif + + // *** TRANSITION *** + // + // BEFORE this point, all code must be async-termination-safe! + // (See WARNING above.) + // + // AFTER this point, we do unsafe things, like using LOG()! + // The process could be terminated or hung at any time. We try to + // do more useful things first and riskier things later. + + // Flush the logs before we do anything in case 'anything' + // causes problems. + FlushLogFilesUnsafe(0); + + // Kill ourself by the default signal handler. + InvokeDefaultSignalHandler(signal_number); +} + +} // namespace + +namespace glog_internal_namespace_ { + +bool IsFailureSignalHandlerInstalled() { +#ifdef HAVE_SIGACTION + // TODO(andschwa): Return kFailureSignalHandlerInstalled? + struct sigaction sig_action; + memset(&sig_action, 0, sizeof(sig_action)); + sigemptyset(&sig_action.sa_mask); + sigaction(SIGABRT, NULL, &sig_action); + if (sig_action.sa_sigaction == &FailureSignalHandler) { + return true; + } +#elif defined(GLOG_OS_WINDOWS) + return kFailureSignalHandlerInstalled; +#endif // HAVE_SIGACTION + return false; +} + +} // namespace glog_internal_namespace_ + +void InstallFailureSignalHandler() { +#ifdef HAVE_SIGACTION + // Build the sigaction struct. + struct sigaction sig_action; + memset(&sig_action, 0, sizeof(sig_action)); + sigemptyset(&sig_action.sa_mask); + sig_action.sa_flags |= SA_SIGINFO; + sig_action.sa_sigaction = &FailureSignalHandler; + + for (size_t i = 0; i < ARRAYSIZE(kFailureSignals); ++i) { + CHECK_ERR(sigaction(kFailureSignals[i].number, &sig_action, NULL)); + } + kFailureSignalHandlerInstalled = true; +#elif defined(GLOG_OS_WINDOWS) + for (size_t i = 0; i < ARRAYSIZE(kFailureSignals); ++i) { + CHECK_NE(signal(kFailureSignals[i].number, &FailureSignalHandler), + SIG_ERR); + } + kFailureSignalHandlerInstalled = true; +#endif // HAVE_SIGACTION +} + +void InstallFailureWriter(void (*writer)(const char* data, size_t size)) { +#if defined(HAVE_SIGACTION) || defined(GLOG_OS_WINDOWS) + g_failure_writer = writer; +#endif // HAVE_SIGACTION +} + +_END_GOOGLE_NAMESPACE_ diff --git a/third_party/glog/src/signalhandler_unittest.cc b/third_party/glog/src/signalhandler_unittest.cc new file mode 100644 index 0000000..c4c99cc --- /dev/null +++ b/third_party/glog/src/signalhandler_unittest.cc @@ -0,0 +1,113 @@ +// Copyright (c) 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Satoru Takabayashi +// +// This is a helper binary for testing signalhandler.cc. The actual test +// is done in signalhandler_unittest.sh. + +#include "utilities.h" + +#if defined(HAVE_PTHREAD) +# include +#endif +#include +#include +#include +#include +#include + +#ifdef HAVE_LIB_GFLAGS +#include +using namespace GFLAGS_NAMESPACE; +#endif + +using namespace GOOGLE_NAMESPACE; + +static void* DieInThread(void*) { + // We assume pthread_t is an integral number or a pointer, rather + // than a complex struct. In some environments, pthread_self() + // returns an uint64 but in some other environments pthread_self() + // returns a pointer. + fprintf( + stderr, "0x%px is dying\n", + static_cast(reinterpret_cast(pthread_self()))); + // Use volatile to prevent from these to be optimized away. + volatile int a = 0; + volatile int b = 1 / a; + fprintf(stderr, "We should have died: b=%d\n", b); + return NULL; +} + +static void WriteToStdout(const char* data, size_t size) { + if (write(STDOUT_FILENO, data, size) < 0) { + // Ignore errors. + } +} + +int main(int argc, char **argv) { +#if defined(HAVE_STACKTRACE) && defined(HAVE_SYMBOLIZE) + InitGoogleLogging(argv[0]); +#ifdef HAVE_LIB_GFLAGS + ParseCommandLineFlags(&argc, &argv, true); +#endif + InstallFailureSignalHandler(); + const std::string command = argc > 1 ? argv[1] : "none"; + if (command == "segv") { + // We'll check if this is outputted. + LOG(INFO) << "create the log file"; + LOG(INFO) << "a message before segv"; + // We assume 0xDEAD is not writable. + int *a = (int*)0xDEAD; + *a = 0; + } else if (command == "loop") { + fprintf(stderr, "looping\n"); + while (true); + } else if (command == "die_in_thread") { +#if defined(HAVE_PTHREAD) + pthread_t thread; + pthread_create(&thread, NULL, &DieInThread, NULL); + pthread_join(thread, NULL); +#else + fprintf(stderr, "no pthread\n"); + return 1; +#endif + } else if (command == "dump_to_stdout") { + InstallFailureWriter(WriteToStdout); + abort(); + } else if (command == "installed") { + fprintf(stderr, "signal handler installed: %s\n", + IsFailureSignalHandlerInstalled() ? "true" : "false"); + } else { + // Tell the shell script + puts("OK"); + } +#endif + return 0; +} diff --git a/third_party/glog/src/signalhandler_unittest.sh b/third_party/glog/src/signalhandler_unittest.sh new file mode 100755 index 0000000..265cd45 --- /dev/null +++ b/third_party/glog/src/signalhandler_unittest.sh @@ -0,0 +1,131 @@ +#! /bin/sh +# +# Copyright (c) 2008, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# Author: Satoru Takabayashi +# +# Unit tests for signalhandler.cc. + +die () { + echo $1 + exit 1 +} + +BINDIR=".libs" +LIBGLOG="$BINDIR/libglog.so" + +BINARY="$BINDIR/signalhandler_unittest" +LOG_INFO="./signalhandler_unittest.INFO" + +# Remove temporary files. +rm -f signalhandler.out* + +if test -e "$BINARY"; then + # We need shared object. + export LD_LIBRARY_PATH=$BINDIR + export DYLD_LIBRARY_PATH=$BINDIR +else + # For windows + BINARY="./signalhandler_unittest.exe" + if ! test -e "$BINARY"; then + echo "We coundn't find demangle_unittest binary." + exit 1 + fi +fi + +if [ x`$BINARY` != 'xOK' ]; then + echo "PASS (No stacktrace support. We don't run this test.)" + exit 0 +fi + +# The PC cannot be obtained in signal handlers on PowerPC correctly. +# We just skip the test for PowerPC. +if [ x`uname -p` = x"powerpc" ]; then + echo "PASS (We don't test the signal handler on PowerPC.)" + exit 0 +fi + +# Test for a case the program kills itself by SIGSEGV. +GOOGLE_LOG_DIR=. $BINARY segv 2> signalhandler.out1 +for pattern in SIGSEGV 0xdead main "Aborted at [0-9]"; do + if ! grep --quiet "$pattern" signalhandler.out1; then + die "'$pattern' should appear in the output" + fi +done +if ! grep --quiet "a message before segv" $LOG_INFO; then + die "'a message before segv' should appear in the INFO log" +fi +rm -f $LOG_INFO + +# Test for a case the program is killed by this shell script. +# $! = the process id of the last command run in the background. +# $$ = the process id of this shell. +$BINARY loop 2> signalhandler.out2 & +# Wait until "looping" is written in the file. This indicates the program +# is ready to accept signals. +while true; do + if grep --quiet looping signalhandler.out2; then + break + fi +done +kill -TERM $! +wait $! + +from_pid='' +# Only linux has the process ID of the signal sender. +if [ x`uname` = "xLinux" ]; then + from_pid="from PID $$" +fi +for pattern in SIGTERM "by PID $!" "$from_pid" main "Aborted at [0-9]"; do + if ! grep --quiet "$pattern" signalhandler.out2; then + die "'$pattern' should appear in the output" + fi +done + +# Test for a case the program dies in a non-main thread. +$BINARY die_in_thread 2> signalhandler.out3 +EXPECTED_TID="`sed 's/ .*//; q' signalhandler.out3`" + +for pattern in SIGFPE DieInThread "TID $EXPECTED_TID" "Aborted at [0-9]"; do + if ! grep --quiet "$pattern" signalhandler.out3; then + die "'$pattern' should appear in the output" + fi +done + +# Test for a case the program installs a custom failure writer that writes +# stuff to stdout instead of stderr. +$BINARY dump_to_stdout 1> signalhandler.out4 +for pattern in SIGABRT main "Aborted at [0-9]"; do + if ! grep --quiet "$pattern" signalhandler.out4; then + die "'$pattern' should appear in the output" + fi +done + +echo PASS diff --git a/third_party/glog/src/stacktrace.h b/third_party/glog/src/stacktrace.h new file mode 100644 index 0000000..55b98b2 --- /dev/null +++ b/third_party/glog/src/stacktrace.h @@ -0,0 +1,61 @@ +// Copyright (c) 2000 - 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Routines to extract the current stack trace. These functions are +// thread-safe. + +#ifndef BASE_STACKTRACE_H_ +#define BASE_STACKTRACE_H_ + +#include "config.h" +#include + +_START_GOOGLE_NAMESPACE_ + +// This is similar to the GetStackFrames routine, except that it returns +// the stack trace only, and not the stack frame sizes as well. +// Example: +// main() { foo(); } +// foo() { bar(); } +// bar() { +// void* result[10]; +// int depth = GetStackFrames(result, 10, 1); +// } +// +// This produces: +// result[0] foo +// result[1] main +// .... ... +// +// "result" must not be NULL. +GLOG_EXPORT int GetStackTrace(void** result, int max_depth, int skip_count); + +_END_GOOGLE_NAMESPACE_ + +#endif // BASE_STACKTRACE_H_ diff --git a/third_party/glog/src/stacktrace_generic-inl.h b/third_party/glog/src/stacktrace_generic-inl.h new file mode 100644 index 0000000..96397d0 --- /dev/null +++ b/third_party/glog/src/stacktrace_generic-inl.h @@ -0,0 +1,62 @@ +// Copyright (c) 2000 - 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Portable implementation - just use glibc +// +// Note: The glibc implementation may cause a call to malloc. +// This can cause a deadlock in HeapProfiler. +#include +#include +#include "stacktrace.h" + +_START_GOOGLE_NAMESPACE_ + +// If you change this function, also change GetStackFrames below. +int GetStackTrace(void** result, int max_depth, int skip_count) { + static const int kStackLength = 64; + void * stack[kStackLength]; + int size; + + size = backtrace(stack, kStackLength); + skip_count++; // we want to skip the current frame as well + int result_count = size - skip_count; + if (result_count < 0) { + result_count = 0; + } + if (result_count > max_depth) { + result_count = max_depth; + } + for (int i = 0; i < result_count; i++) { + result[i] = stack[i + skip_count]; + } + + return result_count; +} + +_END_GOOGLE_NAMESPACE_ diff --git a/third_party/glog/src/stacktrace_libunwind-inl.h b/third_party/glog/src/stacktrace_libunwind-inl.h new file mode 100644 index 0000000..0b20d23 --- /dev/null +++ b/third_party/glog/src/stacktrace_libunwind-inl.h @@ -0,0 +1,93 @@ +// Copyright (c) 2005 - 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Arun Sharma +// +// Produce stack trace using libunwind + +#include "utilities.h" + +extern "C" { +#define UNW_LOCAL_ONLY +#include +} +#include +#include "stacktrace.h" + +_START_GOOGLE_NAMESPACE_ + +// Sometimes, we can try to get a stack trace from within a stack +// trace, because libunwind can call mmap (maybe indirectly via an +// internal mmap based memory allocator), and that mmap gets trapped +// and causes a stack-trace request. If were to try to honor that +// recursive request, we'd end up with infinite recursion or deadlock. +// Luckily, it's safe to ignore those subsequent traces. In such +// cases, we return 0 to indicate the situation. +// We can use the GCC __thread syntax here since libunwind is not supported on +// Windows. +static __thread bool g_tl_entered; // Initialized to false. + +// If you change this function, also change GetStackFrames below. +int GetStackTrace(void** result, int max_depth, int skip_count) { + void *ip; + int n = 0; + unw_cursor_t cursor; + unw_context_t uc; + + if (g_tl_entered) { + return 0; + } + g_tl_entered = true; + + unw_getcontext(&uc); + RAW_CHECK(unw_init_local(&cursor, &uc) >= 0, "unw_init_local failed"); + skip_count++; // Do not include the "GetStackTrace" frame + + while (n < max_depth) { + int ret = + unw_get_reg(&cursor, UNW_REG_IP, reinterpret_cast(&ip)); + if (ret < 0) { + break; + } + if (skip_count > 0) { + skip_count--; + } else { + result[n++] = ip; + } + ret = unw_step(&cursor); + if (ret <= 0) { + break; + } + } + + g_tl_entered = false; + return n; +} + +_END_GOOGLE_NAMESPACE_ diff --git a/third_party/glog/src/stacktrace_powerpc-inl.h b/third_party/glog/src/stacktrace_powerpc-inl.h new file mode 100644 index 0000000..911970c --- /dev/null +++ b/third_party/glog/src/stacktrace_powerpc-inl.h @@ -0,0 +1,130 @@ +// Copyright (c) 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Craig Silverstein +// +// Produce stack trace. I'm guessing (hoping!) the code is much like +// for x86. For apple machines, at least, it seems to be; see +// http://developer.apple.com/documentation/mac/runtimehtml/RTArch-59.html +// http://www.linux-foundation.org/spec/ELF/ppc64/PPC-elf64abi-1.9.html#STACK +// Linux has similar code: http://patchwork.ozlabs.org/linuxppc/patch?id=8882 + +#include +#include // for uintptr_t +#include "stacktrace.h" + +_START_GOOGLE_NAMESPACE_ + +// Given a pointer to a stack frame, locate and return the calling +// stackframe, or return NULL if no stackframe can be found. Perform sanity +// checks (the strictness of which is controlled by the boolean parameter +// "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned. +template +static void **NextStackFrame(void **old_sp) { + void **new_sp = static_cast(*old_sp); + + // Check that the transition from frame pointer old_sp to frame + // pointer new_sp isn't clearly bogus + if (STRICT_UNWINDING) { + // With the stack growing downwards, older stack frame must be + // at a greater address that the current one. + if (new_sp <= old_sp) return NULL; + // Assume stack frames larger than 100,000 bytes are bogus. + if ((uintptr_t)new_sp - (uintptr_t)old_sp > 100000) return NULL; + } else { + // In the non-strict mode, allow discontiguous stack frames. + // (alternate-signal-stacks for example). + if (new_sp == old_sp) return NULL; + // And allow frames upto about 1MB. + if ((new_sp > old_sp) + && ((uintptr_t)new_sp - (uintptr_t)old_sp > 1000000)) return NULL; + } + if ((uintptr_t)new_sp & (sizeof(void *) - 1)) return NULL; + return new_sp; +} + +// This ensures that GetStackTrace stes up the Link Register properly. +void StacktracePowerPCDummyFunction() __attribute__((noinline)); +void StacktracePowerPCDummyFunction() { __asm__ volatile(""); } + +// If you change this function, also change GetStackFrames below. +int GetStackTrace(void** result, int max_depth, int skip_count) { + void **sp; + // Apple OS X uses an old version of gnu as -- both Darwin 7.9.0 (Panther) + // and Darwin 8.8.1 (Tiger) use as 1.38. This means we have to use a + // different asm syntax. I don't know quite the best way to discriminate + // systems using the old as from the new one; I've gone with __APPLE__. +#ifdef __APPLE__ + __asm__ volatile ("mr %0,r1" : "=r" (sp)); +#else + __asm__ volatile ("mr %0,1" : "=r" (sp)); +#endif + + // On PowerPC, the "Link Register" or "Link Record" (LR), is a stack + // entry that holds the return address of the subroutine call (what + // instruction we run after our function finishes). This is the + // same as the stack-pointer of our parent routine, which is what we + // want here. While the compiler will always(?) set up LR for + // subroutine calls, it may not for leaf functions (such as this one). + // This routine forces the compiler (at least gcc) to push it anyway. + StacktracePowerPCDummyFunction(); + + // The LR save area is used by the callee, so the top entry is bogus. + skip_count++; + + int n = 0; + while (sp && n < max_depth) { + if (skip_count > 0) { + skip_count--; + } else { + // PowerPC has 3 main ABIs, which say where in the stack the + // Link Register is. For DARWIN and AIX (used by apple and + // linux ppc64), it's in sp[2]. For SYSV (used by linux ppc), + // it's in sp[1]. +#if defined(_CALL_AIX) || defined(_CALL_DARWIN) + result[n++] = *(sp+2); +#elif defined(_CALL_SYSV) + result[n++] = *(sp+1); +#elif defined(__APPLE__) || ((defined(__linux) || defined(__linux__)) && defined(__PPC64__)) + // This check is in case the compiler doesn't define _CALL_AIX/etc. + result[n++] = *(sp+2); +#elif defined(__linux) || defined(__OpenBSD__) + // This check is in case the compiler doesn't define _CALL_SYSV. + result[n++] = *(sp+1); +#else +#error Need to specify the PPC ABI for your archiecture. +#endif + } + // Use strict unwinding rules. + sp = NextStackFrame(sp); + } + return n; +} + +_END_GOOGLE_NAMESPACE_ diff --git a/third_party/glog/src/stacktrace_unittest.cc b/third_party/glog/src/stacktrace_unittest.cc new file mode 100644 index 0000000..2d07c5f --- /dev/null +++ b/third_party/glog/src/stacktrace_unittest.cc @@ -0,0 +1,239 @@ +// Copyright (c) 2004, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include "utilities.h" + +#include +#include +#include "config.h" +#include "base/commandlineflags.h" +#include +#include "stacktrace.h" + +#ifdef HAVE_EXECINFO_H +# include +#endif + +using namespace GOOGLE_NAMESPACE; + +#ifdef HAVE_STACKTRACE + +// Obtain a backtrace, verify that the expected callers are present in the +// backtrace, and maybe print the backtrace to stdout. + +// The sequence of functions whose return addresses we expect to see in the +// backtrace. +const int BACKTRACE_STEPS = 6; + +struct AddressRange { + const void *start, *end; +}; + +// Expected function [start,end] range. +AddressRange expected_range[BACKTRACE_STEPS]; + +#if __GNUC__ +// Using GCC extension: address of a label can be taken with '&&label'. +// Start should be a label somewhere before recursive call, end somewhere +// after it. +#define INIT_ADDRESS_RANGE(fn, start_label, end_label, prange) \ + do { \ + (prange)->start = &&start_label; \ + (prange)->end = &&end_label; \ + CHECK_LT((prange)->start, (prange)->end); \ + } while (0) +// This macro expands into "unmovable" code (opaque to GCC), and that +// prevents GCC from moving a_label up or down in the code. +// Without it, there is no code following the 'end' label, and GCC +// (4.3.1, 4.4.0) thinks it safe to assign &&end an address that is before +// the recursive call. +#define DECLARE_ADDRESS_LABEL(a_label) \ + a_label: do { __asm__ __volatile__(""); } while (0) +// Gcc 4.4.0 may split function into multiple chunks, and the chunk +// performing recursive call may end up later in the code then the return +// instruction (this actually happens with FDO). +// Adjust function range from __builtin_return_address. +#define ADJUST_ADDRESS_RANGE_FROM_RA(prange) \ + do { \ + void *ra = __builtin_return_address(0); \ + CHECK_LT((prange)->start, ra); \ + if (ra > (prange)->end) { \ + printf("Adjusting range from %p..%p to %p..%p\n", \ + (prange)->start, (prange)->end, \ + (prange)->start, ra); \ + (prange)->end = ra; \ + } \ + } while (0) +#else +// Assume the Check* functions below are not longer than 256 bytes. +#define INIT_ADDRESS_RANGE(fn, start_label, end_label, prange) \ + do { \ + (prange)->start = reinterpret_cast(&fn); \ + (prange)->end = reinterpret_cast(&fn) + 256; \ + } while (0) +#define DECLARE_ADDRESS_LABEL(a_label) do { } while (0) +#define ADJUST_ADDRESS_RANGE_FROM_RA(prange) do { } while (0) +#endif // __GNUC__ + +//-----------------------------------------------------------------------// + +static void CheckRetAddrIsInFunction(void *ret_addr, const AddressRange &range) +{ + CHECK_GE(ret_addr, range.start); + CHECK_LE(ret_addr, range.end); +} + +//-----------------------------------------------------------------------// + +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu-label-as-value" +#endif + +void ATTRIBUTE_NOINLINE CheckStackTrace(int); +static void ATTRIBUTE_NOINLINE CheckStackTraceLeaf(void) { + const int STACK_LEN = 10; + void *stack[STACK_LEN]; + int size; + + ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[1]); + INIT_ADDRESS_RANGE(CheckStackTraceLeaf, start, end, &expected_range[0]); + DECLARE_ADDRESS_LABEL(start); + size = GetStackTrace(stack, STACK_LEN, 0); + printf("Obtained %d stack frames.\n", size); + CHECK_GE(size, 1); + CHECK_LE(size, STACK_LEN); + + if (1) { +#ifdef HAVE_EXECINFO_H + char **strings = backtrace_symbols(stack, size); + printf("Obtained %d stack frames.\n", size); + for (int i = 0; i < size; i++) { + printf("%s %p\n", strings[i], stack[i]); + } + + union { + void (*p1)(int); + void* p2; + } p = {&CheckStackTrace}; + + printf("CheckStackTrace() addr: %p\n", p.p2); + free(strings); +#endif + } + for (int i = 0; i < BACKTRACE_STEPS; i++) { + printf("Backtrace %d: expected: %p..%p actual: %p ... ", + i, expected_range[i].start, expected_range[i].end, stack[i]); + fflush(stdout); + CheckRetAddrIsInFunction(stack[i], expected_range[i]); + printf("OK\n"); + } + DECLARE_ADDRESS_LABEL(end); +} + +//-----------------------------------------------------------------------// + +/* Dummy functions to make the backtrace more interesting. */ +static void ATTRIBUTE_NOINLINE CheckStackTrace4(int i) { + ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[2]); + INIT_ADDRESS_RANGE(CheckStackTrace4, start, end, &expected_range[1]); + DECLARE_ADDRESS_LABEL(start); + for (int j = i; j >= 0; j--) { + CheckStackTraceLeaf(); + } + DECLARE_ADDRESS_LABEL(end); +} +static void ATTRIBUTE_NOINLINE CheckStackTrace3(int i) { + ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[3]); + INIT_ADDRESS_RANGE(CheckStackTrace3, start, end, &expected_range[2]); + DECLARE_ADDRESS_LABEL(start); + for (int j = i; j >= 0; j--) { + CheckStackTrace4(j); + } + DECLARE_ADDRESS_LABEL(end); +} +static void ATTRIBUTE_NOINLINE CheckStackTrace2(int i) { + ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[4]); + INIT_ADDRESS_RANGE(CheckStackTrace2, start, end, &expected_range[3]); + DECLARE_ADDRESS_LABEL(start); + for (int j = i; j >= 0; j--) { + CheckStackTrace3(j); + } + DECLARE_ADDRESS_LABEL(end); +} +static void ATTRIBUTE_NOINLINE CheckStackTrace1(int i) { + ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[5]); + INIT_ADDRESS_RANGE(CheckStackTrace1, start, end, &expected_range[4]); + DECLARE_ADDRESS_LABEL(start); + for (int j = i; j >= 0; j--) { + CheckStackTrace2(j); + } + DECLARE_ADDRESS_LABEL(end); +} + +#ifndef __GNUC__ +// On non-GNU environment, we use the address of `CheckStackTrace` to +// guess the address range of this function. This guess is wrong for +// non-static function on Windows. This is probably because +// `&CheckStackTrace` returns the address of a trampoline like PLT, +// not the actual address of `CheckStackTrace`. +// See https://github.com/google/glog/issues/421 for the detail. +static +#endif +void ATTRIBUTE_NOINLINE CheckStackTrace(int i) { + INIT_ADDRESS_RANGE(CheckStackTrace, start, end, &expected_range[5]); + DECLARE_ADDRESS_LABEL(start); + for (int j = i; j >= 0; j--) { + CheckStackTrace1(j); + } + DECLARE_ADDRESS_LABEL(end); +} + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +//-----------------------------------------------------------------------// + +int main(int, char ** argv) { + FLAGS_logtostderr = true; + InitGoogleLogging(argv[0]); + + CheckStackTrace(0); + + printf("PASS\n"); + return 0; +} + +#else +int main() { + printf("PASS (no stacktrace support)\n"); + return 0; +} +#endif // HAVE_STACKTRACE diff --git a/third_party/glog/src/stacktrace_unwind-inl.h b/third_party/glog/src/stacktrace_unwind-inl.h new file mode 100644 index 0000000..fbb5f98 --- /dev/null +++ b/third_party/glog/src/stacktrace_unwind-inl.h @@ -0,0 +1,106 @@ +// Copyright (c) 2005 - 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Arun Sharma +// +// Produce stack trace using libgcc + +#include // for NULL +#include // ABI defined unwinder + +#include "stacktrace.h" + +_START_GOOGLE_NAMESPACE_ + +typedef struct { + void **result; + int max_depth; + int skip_count; + int count; +} trace_arg_t; + + +// Workaround for the malloc() in _Unwind_Backtrace() issue. +static _Unwind_Reason_Code nop_backtrace(struct _Unwind_Context */*uc*/, void */*opq*/) { + return _URC_NO_REASON; +} + + +// This code is not considered ready to run until +// static initializers run so that we are guaranteed +// that any malloc-related initialization is done. +static bool ready_to_run = false; +class StackTraceInit { + public: + StackTraceInit() { + // Extra call to force initialization + _Unwind_Backtrace(nop_backtrace, NULL); + ready_to_run = true; + } +}; + +static StackTraceInit module_initializer; // Force initialization + +static _Unwind_Reason_Code GetOneFrame(struct _Unwind_Context *uc, void *opq) { + trace_arg_t *targ = static_cast(opq); + + if (targ->skip_count > 0) { + targ->skip_count--; + } else { + targ->result[targ->count++] = (void *) _Unwind_GetIP(uc); + } + + if (targ->count == targ->max_depth) { + return _URC_END_OF_STACK; + } + + return _URC_NO_REASON; +} + +// If you change this function, also change GetStackFrames below. +int GetStackTrace(void** result, int max_depth, int skip_count) { + if (!ready_to_run) { + return 0; + } + + trace_arg_t targ; + + skip_count += 1; // Do not include the "GetStackTrace" frame + + targ.result = result; + targ.max_depth = max_depth; + targ.skip_count = skip_count; + targ.count = 0; + + _Unwind_Backtrace(GetOneFrame, &targ); + + return targ.count; +} + +_END_GOOGLE_NAMESPACE_ diff --git a/third_party/glog/src/stacktrace_windows-inl.h b/third_party/glog/src/stacktrace_windows-inl.h new file mode 100644 index 0000000..e6af561 --- /dev/null +++ b/third_party/glog/src/stacktrace_windows-inl.h @@ -0,0 +1,50 @@ +// Copyright (c) 2000 - 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Andrew Schwartzmeyer +// +// Windows implementation - just use CaptureStackBackTrace + +#include "config.h" +#include "port.h" +#include "stacktrace.h" +#include + +_START_GOOGLE_NAMESPACE_ + +int GetStackTrace(void** result, int max_depth, int skip_count) { + if (max_depth > 64) { + max_depth = 64; + } + skip_count++; // we want to skip the current frame as well + // This API is thread-safe (moreover it walks only the current thread). + return CaptureStackBackTrace(static_cast(skip_count), static_cast(max_depth), result, NULL); +} + +_END_GOOGLE_NAMESPACE_ diff --git a/third_party/glog/src/stacktrace_x86-inl.h b/third_party/glog/src/stacktrace_x86-inl.h new file mode 100644 index 0000000..b12adc1 --- /dev/null +++ b/third_party/glog/src/stacktrace_x86-inl.h @@ -0,0 +1,147 @@ +// Copyright (c) 2000 - 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Produce stack trace + +#include // for uintptr_t + +#include "utilities.h" // for OS_* macros + +#if !defined(GLOG_OS_WINDOWS) +#include +#include +#endif + +#include // for NULL +#include "stacktrace.h" + +_START_GOOGLE_NAMESPACE_ + +// Given a pointer to a stack frame, locate and return the calling +// stackframe, or return NULL if no stackframe can be found. Perform sanity +// checks (the strictness of which is controlled by the boolean parameter +// "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned. +template +static void **NextStackFrame(void **old_sp) { + void **new_sp = static_cast(*old_sp); + + // Check that the transition from frame pointer old_sp to frame + // pointer new_sp isn't clearly bogus + if (STRICT_UNWINDING) { + // With the stack growing downwards, older stack frame must be + // at a greater address that the current one. + if (new_sp <= old_sp) return NULL; + // Assume stack frames larger than 100,000 bytes are bogus. + if ((uintptr_t)new_sp - (uintptr_t)old_sp > 100000) return NULL; + } else { + // In the non-strict mode, allow discontiguous stack frames. + // (alternate-signal-stacks for example). + if (new_sp == old_sp) return NULL; + // And allow frames upto about 1MB. + if ((new_sp > old_sp) + && ((uintptr_t)new_sp - (uintptr_t)old_sp > 1000000)) return NULL; + } + if ((uintptr_t)new_sp & (sizeof(void *) - 1)) return NULL; +#ifdef __i386__ + // On 64-bit machines, the stack pointer can be very close to + // 0xffffffff, so we explicitly check for a pointer into the + // last two pages in the address space + if ((uintptr_t)new_sp >= 0xffffe000) return NULL; +#endif +#if !defined(GLOG_OS_WINDOWS) + if (!STRICT_UNWINDING) { + // Lax sanity checks cause a crash in 32-bit tcmalloc/crash_reason_test + // on AMD-based machines with VDSO-enabled kernels. + // Make an extra sanity check to insure new_sp is readable. + // Note: NextStackFrame() is only called while the program + // is already on its last leg, so it's ok to be slow here. + static int page_size = getpagesize(); + void *new_sp_aligned = (void *)((uintptr_t)new_sp & ~(page_size - 1)); + if (msync(new_sp_aligned, page_size, MS_ASYNC) == -1) { + return NULL; + } + } +#endif + return new_sp; +} + +// If you change this function, also change GetStackFrames below. +int GetStackTrace(void** result, int max_depth, int skip_count) { + void **sp; + +#ifdef __GNUC__ +#if __GNUC__ * 100 + __GNUC_MINOR__ >= 402 +#define USE_BUILTIN_FRAME_ADDRESS +#endif +#endif + +#ifdef USE_BUILTIN_FRAME_ADDRESS + sp = reinterpret_cast(__builtin_frame_address(0)); +#elif defined(__i386__) + // Stack frame format: + // sp[0] pointer to previous frame + // sp[1] caller address + // sp[2] first argument + // ... + sp = (void **)&result - 2; +#elif defined(__x86_64__) + // __builtin_frame_address(0) can return the wrong address on gcc-4.1.0-k8 + unsigned long rbp; + // Move the value of the register %rbp into the local variable rbp. + // We need 'volatile' to prevent this instruction from getting moved + // around during optimization to before function prologue is done. + // An alternative way to achieve this + // would be (before this __asm__ instruction) to call Noop() defined as + // static void Noop() __attribute__ ((noinline)); // prevent inlining + // static void Noop() { asm(""); } // prevent optimizing-away + __asm__ volatile ("mov %%rbp, %0" : "=r" (rbp)); + // Arguments are passed in registers on x86-64, so we can't just + // offset from &result + sp = (void **) rbp; +#endif + + int n = 0; + while (sp && n < max_depth) { + if (*(sp+1) == (void *)0) { + // In 64-bit code, we often see a frame that + // points to itself and has a return address of 0. + break; + } + if (skip_count > 0) { + skip_count--; + } else { + result[n++] = *(sp+1); + } + // Use strict unwinding rules. + sp = NextStackFrame(sp); + } + return n; +} + +_END_GOOGLE_NAMESPACE_ diff --git a/third_party/glog/src/stl_logging_unittest.cc b/third_party/glog/src/stl_logging_unittest.cc new file mode 100644 index 0000000..5ab2414 --- /dev/null +++ b/third_party/glog/src/stl_logging_unittest.cc @@ -0,0 +1,207 @@ +// Copyright (c) 2003, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include "config.h" + +#ifdef HAVE_USING_OPERATOR + +#include +#include +#include +#include +#include +#include + +#ifdef __GNUC__ +// C++0x isn't enabled by default in GCC and libc++ does not have +// non-standard ext/* and tr1/unordered_*. +# if defined(_LIBCPP_VERSION) +# ifndef GLOG_STL_LOGGING_FOR_UNORDERED +# define GLOG_STL_LOGGING_FOR_UNORDERED +# endif +# else +# ifndef GLOG_STL_LOGGING_FOR_EXT_HASH +# define GLOG_STL_LOGGING_FOR_EXT_HASH +# endif +# ifndef GLOG_STL_LOGGING_FOR_EXT_SLIST +# define GLOG_STL_LOGGING_FOR_EXT_SLIST +# endif +# ifndef GLOG_STL_LOGGING_FOR_TR1_UNORDERED +# define GLOG_STL_LOGGING_FOR_TR1_UNORDERED +# endif +# endif +#endif + +#include +#include +#include "googletest.h" + +using namespace std; +#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH +using namespace __gnu_cxx; +#endif + +struct user_hash { + size_t operator()(int x) const { return static_cast(x); } +}; + +static void TestSTLLogging() { + { + // Test a sequence. + vector v; + v.push_back(10); + v.push_back(20); + v.push_back(30); + ostringstream ss; + ss << v; + EXPECT_EQ(ss.str(), "10 20 30"); + vector copied_v(v); + CHECK_EQ(v, copied_v); // This must compile. + } + + { + // Test a sorted pair associative container. + map< int, string > m; + m[20] = "twenty"; + m[10] = "ten"; + m[30] = "thirty"; + ostringstream ss; + ss << m; + EXPECT_EQ(ss.str(), "(10, ten) (20, twenty) (30, thirty)"); + map< int, string > copied_m(m); + CHECK_EQ(m, copied_m); // This must compile. + } + +#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH + { + // Test a hashed simple associative container. + hash_set hs; + hs.insert(10); + hs.insert(20); + hs.insert(30); + ostringstream ss; + ss << hs; + EXPECT_EQ(ss.str().size(), 8); + EXPECT_TRUE(ss.str().find("10") != string::npos); + EXPECT_TRUE(ss.str().find("20") != string::npos); + EXPECT_TRUE(ss.str().find("30") != string::npos); + hash_set copied_hs(hs); + CHECK_EQ(hs, copied_hs); // This must compile. + } +#endif + +#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH + { + // Test a hashed pair associative container. + hash_map hm; + hm[10] = "ten"; + hm[20] = "twenty"; + hm[30] = "thirty"; + ostringstream ss; + ss << hm; + EXPECT_EQ(ss.str().size(), 35); + EXPECT_TRUE(ss.str().find("(10, ten)") != string::npos); + EXPECT_TRUE(ss.str().find("(20, twenty)") != string::npos); + EXPECT_TRUE(ss.str().find("(30, thirty)") != string::npos); + hash_map copied_hm(hm); + CHECK_EQ(hm, copied_hm); // this must compile + } +#endif + + { + // Test a long sequence. + vector v; + string expected; + for (int i = 0; i < 100; i++) { + v.push_back(i); + if (i > 0) expected += ' '; + const size_t buf_size = 256; + char buf[buf_size]; + snprintf(buf, buf_size, "%d", i); + expected += buf; + } + v.push_back(100); + expected += " ..."; + ostringstream ss; + ss << v; + CHECK_EQ(ss.str(), expected.c_str()); + } + + { + // Test a sorted pair associative container. + // Use a non-default comparison functor. + map< int, string, greater > m; + m[20] = "twenty"; + m[10] = "ten"; + m[30] = "thirty"; + ostringstream ss; + ss << m; + EXPECT_EQ(ss.str(), "(30, thirty) (20, twenty) (10, ten)"); + map< int, string, greater > copied_m(m); + CHECK_EQ(m, copied_m); // This must compile. + } + +#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH + { + // Test a hashed simple associative container. + // Use a user defined hash function. + hash_set hs; + hs.insert(10); + hs.insert(20); + hs.insert(30); + ostringstream ss; + ss << hs; + EXPECT_EQ(ss.str().size(), 8); + EXPECT_TRUE(ss.str().find("10") != string::npos); + EXPECT_TRUE(ss.str().find("20") != string::npos); + EXPECT_TRUE(ss.str().find("30") != string::npos); + hash_set copied_hs(hs); + CHECK_EQ(hs, copied_hs); // This must compile. + } +#endif +} + +int main(int, char**) { + TestSTLLogging(); + std::cout << "PASS\n"; + return 0; +} + +#else + +#include + +int main(int, char**) { + std::cout << "We don't support stl_logging for this compiler.\n" + << "(we need compiler support of 'using ::operator<<' " + << "for this feature.)\n"; + return 0; +} + +#endif // HAVE_USING_OPERATOR diff --git a/third_party/glog/src/symbolize.cc b/third_party/glog/src/symbolize.cc new file mode 100644 index 0000000..d979b82 --- /dev/null +++ b/third_party/glog/src/symbolize.cc @@ -0,0 +1,955 @@ +// Copyright (c) 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Satoru Takabayashi +// Stack-footprint reduction work done by Raksit Ashok +// +// Implementation note: +// +// We don't use heaps but only use stacks. We want to reduce the +// stack consumption so that the symbolizer can run on small stacks. +// +// Here are some numbers collected with GCC 4.1.0 on x86: +// - sizeof(Elf32_Sym) = 16 +// - sizeof(Elf32_Shdr) = 40 +// - sizeof(Elf64_Sym) = 24 +// - sizeof(Elf64_Shdr) = 64 +// +// This implementation is intended to be async-signal-safe but uses +// some functions which are not guaranteed to be so, such as memchr() +// and memmove(). We assume they are async-signal-safe. +// +// Additional header can be specified by the GLOG_BUILD_CONFIG_INCLUDE +// macro to add platform specific defines (e.g. GLOG_OS_OPENBSD). + +#ifdef GLOG_BUILD_CONFIG_INCLUDE +#include GLOG_BUILD_CONFIG_INCLUDE +#endif // GLOG_BUILD_CONFIG_INCLUDE + +#include "utilities.h" + +#if defined(HAVE_SYMBOLIZE) + +#include + +#include +#include + +#include "symbolize.h" +#include "demangle.h" + +_START_GOOGLE_NAMESPACE_ + +// We don't use assert() since it's not guaranteed to be +// async-signal-safe. Instead we define a minimal assertion +// macro. So far, we don't need pretty printing for __FILE__, etc. + +// A wrapper for abort() to make it callable in ? :. +static int AssertFail() { + abort(); + return 0; // Should not reach. +} + +#define SAFE_ASSERT(expr) ((expr) ? 0 : AssertFail()) + +static SymbolizeCallback g_symbolize_callback = NULL; +void InstallSymbolizeCallback(SymbolizeCallback callback) { + g_symbolize_callback = callback; +} + +static SymbolizeOpenObjectFileCallback g_symbolize_open_object_file_callback = + NULL; +void InstallSymbolizeOpenObjectFileCallback( + SymbolizeOpenObjectFileCallback callback) { + g_symbolize_open_object_file_callback = callback; +} + +// This function wraps the Demangle function to provide an interface +// where the input symbol is demangled in-place. +// To keep stack consumption low, we would like this function to not +// get inlined. +static ATTRIBUTE_NOINLINE void DemangleInplace(char *out, int out_size) { + char demangled[256]; // Big enough for sane demangled symbols. + if (Demangle(out, demangled, sizeof(demangled))) { + // Demangling succeeded. Copy to out if the space allows. + size_t len = strlen(demangled); + if (len + 1 <= static_cast(out_size)) { // +1 for '\0'. + SAFE_ASSERT(len < sizeof(demangled)); + memmove(out, demangled, len + 1); + } + } +} + +_END_GOOGLE_NAMESPACE_ + +#if defined(__ELF__) + +#if defined(HAVE_DLFCN_H) +#include +#endif +#if defined(GLOG_OS_OPENBSD) +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "symbolize.h" +#include "config.h" +#include + +// Re-runs fn until it doesn't cause EINTR. +#define NO_INTR(fn) do {} while ((fn) < 0 && errno == EINTR) + +_START_GOOGLE_NAMESPACE_ + +// Read up to "count" bytes from "offset" in the file pointed by file +// descriptor "fd" into the buffer starting at "buf" while handling short reads +// and EINTR. On success, return the number of bytes read. Otherwise, return +// -1. +static ssize_t ReadFromOffset(const int fd, void *buf, const size_t count, + const size_t offset) { + SAFE_ASSERT(fd >= 0); + SAFE_ASSERT(count <= static_cast(std::numeric_limits::max())); + char *buf0 = reinterpret_cast(buf); + size_t num_bytes = 0; + while (num_bytes < count) { + ssize_t len; + NO_INTR(len = pread(fd, buf0 + num_bytes, count - num_bytes, + static_cast(offset + num_bytes))); + if (len < 0) { // There was an error other than EINTR. + return -1; + } + if (len == 0) { // Reached EOF. + break; + } + num_bytes += static_cast(len); + } + SAFE_ASSERT(num_bytes <= count); + return static_cast(num_bytes); +} + +// Try reading exactly "count" bytes from "offset" bytes in a file +// pointed by "fd" into the buffer starting at "buf" while handling +// short reads and EINTR. On success, return true. Otherwise, return +// false. +static bool ReadFromOffsetExact(const int fd, void *buf, + const size_t count, const size_t offset) { + ssize_t len = ReadFromOffset(fd, buf, count, offset); + return static_cast(len) == count; +} + +// Returns elf_header.e_type if the file pointed by fd is an ELF binary. +static int FileGetElfType(const int fd) { + ElfW(Ehdr) elf_header; + if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) { + return -1; + } + if (memcmp(elf_header.e_ident, ELFMAG, SELFMAG) != 0) { + return -1; + } + return elf_header.e_type; +} + +// Read the section headers in the given ELF binary, and if a section +// of the specified type is found, set the output to this section header +// and return true. Otherwise, return false. +// To keep stack consumption low, we would like this function to not get +// inlined. +static ATTRIBUTE_NOINLINE bool +GetSectionHeaderByType(const int fd, ElfW(Half) sh_num, const size_t sh_offset, + ElfW(Word) type, ElfW(Shdr) *out) { + // Read at most 16 section headers at a time to save read calls. + ElfW(Shdr) buf[16]; + for (size_t i = 0; i < sh_num;) { + const size_t num_bytes_left = (sh_num - i) * sizeof(buf[0]); + const size_t num_bytes_to_read = + (sizeof(buf) > num_bytes_left) ? num_bytes_left : sizeof(buf); + const ssize_t len = ReadFromOffset(fd, buf, num_bytes_to_read, + sh_offset + i * sizeof(buf[0])); + if (len == -1) { + return false; + } + SAFE_ASSERT(static_cast(len) % sizeof(buf[0]) == 0); + const size_t num_headers_in_buf = static_cast(len) / sizeof(buf[0]); + SAFE_ASSERT(num_headers_in_buf <= sizeof(buf) / sizeof(buf[0])); + for (size_t j = 0; j < num_headers_in_buf; ++j) { + if (buf[j].sh_type == type) { + *out = buf[j]; + return true; + } + } + i += num_headers_in_buf; + } + return false; +} + +// There is no particular reason to limit section name to 63 characters, +// but there has (as yet) been no need for anything longer either. +const int kMaxSectionNameLen = 64; + +// name_len should include terminating '\0'. +bool GetSectionHeaderByName(int fd, const char *name, size_t name_len, + ElfW(Shdr) *out) { + ElfW(Ehdr) elf_header; + if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) { + return false; + } + + ElfW(Shdr) shstrtab; + size_t shstrtab_offset = + (elf_header.e_shoff + static_cast(elf_header.e_shentsize) * + static_cast(elf_header.e_shstrndx)); + if (!ReadFromOffsetExact(fd, &shstrtab, sizeof(shstrtab), shstrtab_offset)) { + return false; + } + + for (size_t i = 0; i < elf_header.e_shnum; ++i) { + size_t section_header_offset = (elf_header.e_shoff + + elf_header.e_shentsize * i); + if (!ReadFromOffsetExact(fd, out, sizeof(*out), section_header_offset)) { + return false; + } + char header_name[kMaxSectionNameLen]; + if (sizeof(header_name) < name_len) { + RAW_LOG(WARNING, "Section name '%s' is too long (%" PRIuS "); " + "section will not be found (even if present).", name, name_len); + // No point in even trying. + return false; + } + size_t name_offset = shstrtab.sh_offset + out->sh_name; + ssize_t n_read = ReadFromOffset(fd, &header_name, name_len, name_offset); + if (n_read == -1) { + return false; + } else if (static_cast(n_read) != name_len) { + // Short read -- name could be at end of file. + continue; + } + if (memcmp(header_name, name, name_len) == 0) { + return true; + } + } + return false; +} + +// Read a symbol table and look for the symbol containing the +// pc. Iterate over symbols in a symbol table and look for the symbol +// containing "pc". On success, return true and write the symbol name +// to out. Otherwise, return false. +// To keep stack consumption low, we would like this function to not get +// inlined. +static ATTRIBUTE_NOINLINE bool +FindSymbol(uint64_t pc, const int fd, char *out, size_t out_size, + uint64_t symbol_offset, const ElfW(Shdr) *strtab, + const ElfW(Shdr) *symtab) { + if (symtab == NULL) { + return false; + } + const size_t num_symbols = symtab->sh_size / symtab->sh_entsize; + for (unsigned i = 0; i < num_symbols;) { + size_t offset = symtab->sh_offset + i * symtab->sh_entsize; + + // If we are reading Elf64_Sym's, we want to limit this array to + // 32 elements (to keep stack consumption low), otherwise we can + // have a 64 element Elf32_Sym array. +#if defined(__WORDSIZE) && __WORDSIZE == 64 + const size_t NUM_SYMBOLS = 32U; +#else + const size_t NUM_SYMBOLS = 64U; +#endif + + // Read at most NUM_SYMBOLS symbols at once to save read() calls. + ElfW(Sym) buf[NUM_SYMBOLS]; + size_t num_symbols_to_read = std::min(NUM_SYMBOLS, num_symbols - i); + const ssize_t len = + ReadFromOffset(fd, &buf, sizeof(buf[0]) * num_symbols_to_read, offset); + SAFE_ASSERT(static_cast(len) % sizeof(buf[0]) == 0); + const size_t num_symbols_in_buf = static_cast(len) / sizeof(buf[0]); + SAFE_ASSERT(num_symbols_in_buf <= num_symbols_to_read); + for (unsigned j = 0; j < num_symbols_in_buf; ++j) { + const ElfW(Sym)& symbol = buf[j]; + uint64_t start_address = symbol.st_value; + start_address += symbol_offset; + uint64_t end_address = start_address + symbol.st_size; + if (symbol.st_value != 0 && // Skip null value symbols. + symbol.st_shndx != 0 && // Skip undefined symbols. + start_address <= pc && pc < end_address) { + ssize_t len1 = ReadFromOffset(fd, out, out_size, + strtab->sh_offset + symbol.st_name); + if (len1 <= 0 || memchr(out, '\0', out_size) == NULL) { + memset(out, 0, out_size); + return false; + } + return true; // Obtained the symbol name. + } + } + i += num_symbols_in_buf; + } + return false; +} + +// Get the symbol name of "pc" from the file pointed by "fd". Process +// both regular and dynamic symbol tables if necessary. On success, +// write the symbol name to "out" and return true. Otherwise, return +// false. +static bool GetSymbolFromObjectFile(const int fd, + uint64_t pc, + char* out, + size_t out_size, + uint64_t base_address) { + // Read the ELF header. + ElfW(Ehdr) elf_header; + if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) { + return false; + } + + ElfW(Shdr) symtab, strtab; + + // Consult a regular symbol table first. + if (GetSectionHeaderByType(fd, elf_header.e_shnum, elf_header.e_shoff, + SHT_SYMTAB, &symtab)) { + if (!ReadFromOffsetExact(fd, &strtab, sizeof(strtab), elf_header.e_shoff + + symtab.sh_link * sizeof(symtab))) { + return false; + } + if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) { + return true; // Found the symbol in a regular symbol table. + } + } + + // If the symbol is not found, then consult a dynamic symbol table. + if (GetSectionHeaderByType(fd, elf_header.e_shnum, elf_header.e_shoff, + SHT_DYNSYM, &symtab)) { + if (!ReadFromOffsetExact(fd, &strtab, sizeof(strtab), elf_header.e_shoff + + symtab.sh_link * sizeof(symtab))) { + return false; + } + if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) { + return true; // Found the symbol in a dynamic symbol table. + } + } + + return false; +} + +namespace { +// Thin wrapper around a file descriptor so that the file descriptor +// gets closed for sure. +struct FileDescriptor { + const int fd_; + explicit FileDescriptor(int fd) : fd_(fd) {} + ~FileDescriptor() { + if (fd_ >= 0) { + close(fd_); + } + } + int get() { return fd_; } + + private: + FileDescriptor(const FileDescriptor &); + void operator=(const FileDescriptor&); +}; + +// Helper class for reading lines from file. +// +// Note: we don't use ProcMapsIterator since the object is big (it has +// a 5k array member) and uses async-unsafe functions such as sscanf() +// and snprintf(). +class LineReader { + public: + explicit LineReader(int fd, char *buf, size_t buf_len, size_t offset) + : fd_(fd), + buf_(buf), + buf_len_(buf_len), + offset_(offset), + bol_(buf), + eol_(buf), + eod_(buf) {} + + // Read '\n'-terminated line from file. On success, modify "bol" + // and "eol", then return true. Otherwise, return false. + // + // Note: if the last line doesn't end with '\n', the line will be + // dropped. It's an intentional behavior to make the code simple. + bool ReadLine(const char **bol, const char **eol) { + if (BufferIsEmpty()) { // First time. + const ssize_t num_bytes = ReadFromOffset(fd_, buf_, buf_len_, offset_); + if (num_bytes <= 0) { // EOF or error. + return false; + } + offset_ += static_cast(num_bytes); + eod_ = buf_ + num_bytes; + bol_ = buf_; + } else { + bol_ = eol_ + 1; // Advance to the next line in the buffer. + SAFE_ASSERT(bol_ <= eod_); // "bol_" can point to "eod_". + if (!HasCompleteLine()) { + const size_t incomplete_line_length = static_cast(eod_ - bol_); + // Move the trailing incomplete line to the beginning. + memmove(buf_, bol_, incomplete_line_length); + // Read text from file and append it. + char * const append_pos = buf_ + incomplete_line_length; + const size_t capacity_left = buf_len_ - incomplete_line_length; + const ssize_t num_bytes = + ReadFromOffset(fd_, append_pos, capacity_left, offset_); + if (num_bytes <= 0) { // EOF or error. + return false; + } + offset_ += static_cast(num_bytes); + eod_ = append_pos + num_bytes; + bol_ = buf_; + } + } + eol_ = FindLineFeed(); + if (eol_ == NULL) { // '\n' not found. Malformed line. + return false; + } + *eol_ = '\0'; // Replace '\n' with '\0'. + + *bol = bol_; + *eol = eol_; + return true; + } + + // Beginning of line. + const char *bol() { + return bol_; + } + + // End of line. + const char *eol() { + return eol_; + } + + private: + LineReader(const LineReader &); + void operator=(const LineReader&); + + char *FindLineFeed() { + return reinterpret_cast(memchr(bol_, '\n', static_cast(eod_ - bol_))); + } + + bool BufferIsEmpty() { + return buf_ == eod_; + } + + bool HasCompleteLine() { + return !BufferIsEmpty() && FindLineFeed() != NULL; + } + + const int fd_; + char * const buf_; + const size_t buf_len_; + size_t offset_; + char *bol_; + char *eol_; + const char *eod_; // End of data in "buf_". +}; +} // namespace + +// Place the hex number read from "start" into "*hex". The pointer to +// the first non-hex character or "end" is returned. +static char *GetHex(const char *start, const char *end, uint64_t *hex) { + *hex = 0; + const char *p; + for (p = start; p < end; ++p) { + int ch = *p; + if ((ch >= '0' && ch <= '9') || + (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f')) { + *hex = (*hex << 4U) | (ch < 'A' ? static_cast(ch - '0') : (ch & 0xF) + 9U); + } else { // Encountered the first non-hex character. + break; + } + } + SAFE_ASSERT(p <= end); + return const_cast(p); +} + +// Searches for the object file (from /proc/self/maps) that contains +// the specified pc. If found, sets |start_address| to the start address +// of where this object file is mapped in memory, sets the module base +// address into |base_address|, copies the object file name into +// |out_file_name|, and attempts to open the object file. If the object +// file is opened successfully, returns the file descriptor. Otherwise, +// returns -1. |out_file_name_size| is the size of the file name buffer +// (including the null-terminator). +static ATTRIBUTE_NOINLINE int +OpenObjectFileContainingPcAndGetStartAddress(uint64_t pc, + uint64_t &start_address, + uint64_t &base_address, + char *out_file_name, + size_t out_file_name_size) { + int object_fd; + + int maps_fd; + NO_INTR(maps_fd = open("/proc/self/maps", O_RDONLY)); + FileDescriptor wrapped_maps_fd(maps_fd); + if (wrapped_maps_fd.get() < 0) { + return -1; + } + + int mem_fd; + NO_INTR(mem_fd = open("/proc/self/mem", O_RDONLY)); + FileDescriptor wrapped_mem_fd(mem_fd); + if (wrapped_mem_fd.get() < 0) { + return -1; + } + + // Iterate over maps and look for the map containing the pc. Then + // look into the symbol tables inside. + char buf[1024]; // Big enough for line of sane /proc/self/maps + unsigned num_maps = 0; + LineReader reader(wrapped_maps_fd.get(), buf, sizeof(buf), 0); + while (true) { + num_maps++; + const char *cursor; + const char *eol; + if (!reader.ReadLine(&cursor, &eol)) { // EOF or malformed line. + return -1; + } + + // Start parsing line in /proc/self/maps. Here is an example: + // + // 08048000-0804c000 r-xp 00000000 08:01 2142121 /bin/cat + // + // We want start address (08048000), end address (0804c000), flags + // (r-xp) and file name (/bin/cat). + + // Read start address. + cursor = GetHex(cursor, eol, &start_address); + if (cursor == eol || *cursor != '-') { + return -1; // Malformed line. + } + ++cursor; // Skip '-'. + + // Read end address. + uint64_t end_address; + cursor = GetHex(cursor, eol, &end_address); + if (cursor == eol || *cursor != ' ') { + return -1; // Malformed line. + } + ++cursor; // Skip ' '. + + // Read flags. Skip flags until we encounter a space or eol. + const char * const flags_start = cursor; + while (cursor < eol && *cursor != ' ') { + ++cursor; + } + // We expect at least four letters for flags (ex. "r-xp"). + if (cursor == eol || cursor < flags_start + 4) { + return -1; // Malformed line. + } + + // Determine the base address by reading ELF headers in process memory. + ElfW(Ehdr) ehdr; + // Skip non-readable maps. + if (flags_start[0] == 'r' && + ReadFromOffsetExact(mem_fd, &ehdr, sizeof(ElfW(Ehdr)), start_address) && + memcmp(ehdr.e_ident, ELFMAG, SELFMAG) == 0) { + switch (ehdr.e_type) { + case ET_EXEC: + base_address = 0; + break; + case ET_DYN: + // Find the segment containing file offset 0. This will correspond + // to the ELF header that we just read. Normally this will have + // virtual address 0, but this is not guaranteed. We must subtract + // the virtual address from the address where the ELF header was + // mapped to get the base address. + // + // If we fail to find a segment for file offset 0, use the address + // of the ELF header as the base address. + base_address = start_address; + for (unsigned i = 0; i != ehdr.e_phnum; ++i) { + ElfW(Phdr) phdr; + if (ReadFromOffsetExact( + mem_fd, &phdr, sizeof(phdr), + start_address + ehdr.e_phoff + i * sizeof(phdr)) && + phdr.p_type == PT_LOAD && phdr.p_offset == 0) { + base_address = start_address - phdr.p_vaddr; + break; + } + } + break; + default: + // ET_REL or ET_CORE. These aren't directly executable, so they don't + // affect the base address. + break; + } + } + + // Check start and end addresses. + if (!(start_address <= pc && pc < end_address)) { + continue; // We skip this map. PC isn't in this map. + } + + // Check flags. We are only interested in "r*x" maps. + if (flags_start[0] != 'r' || flags_start[2] != 'x') { + continue; // We skip this map. + } + ++cursor; // Skip ' '. + + // Read file offset. + uint64_t file_offset; + cursor = GetHex(cursor, eol, &file_offset); + if (cursor == eol || *cursor != ' ') { + return -1; // Malformed line. + } + ++cursor; // Skip ' '. + + // Skip to file name. "cursor" now points to dev. We need to + // skip at least two spaces for dev and inode. + int num_spaces = 0; + while (cursor < eol) { + if (*cursor == ' ') { + ++num_spaces; + } else if (num_spaces >= 2) { + // The first non-space character after skipping two spaces + // is the beginning of the file name. + break; + } + ++cursor; + } + if (cursor == eol) { + return -1; // Malformed line. + } + + // Finally, "cursor" now points to file name of our interest. + NO_INTR(object_fd = open(cursor, O_RDONLY)); + if (object_fd < 0) { + // Failed to open object file. Copy the object file name to + // |out_file_name|. + strncpy(out_file_name, cursor, out_file_name_size); + // Making sure |out_file_name| is always null-terminated. + out_file_name[out_file_name_size - 1] = '\0'; + return -1; + } + return object_fd; + } +} + +// POSIX doesn't define any async-signal safe function for converting +// an integer to ASCII. We'll have to define our own version. +// itoa_r() converts an (unsigned) integer to ASCII. It returns "buf", if the +// conversion was successful or NULL otherwise. It never writes more than "sz" +// bytes. Output will be truncated as needed, and a NUL character is always +// appended. +// NOTE: code from sandbox/linux/seccomp-bpf/demo.cc. +static char *itoa_r(uintptr_t i, char *buf, size_t sz, unsigned base, size_t padding) { + // Make sure we can write at least one NUL byte. + size_t n = 1; + if (n > sz) { + return NULL; + } + + if (base < 2 || base > 16) { + buf[0] = '\000'; + return NULL; + } + + char *start = buf; + + // Loop until we have converted the entire number. Output at least one + // character (i.e. '0'). + char *ptr = start; + do { + // Make sure there is still enough space left in our output buffer. + if (++n > sz) { + buf[0] = '\000'; + return NULL; + } + + // Output the next digit. + *ptr++ = "0123456789abcdef"[i % base]; + i /= base; + + if (padding > 0) { + padding--; + } + } while (i > 0 || padding > 0); + + // Terminate the output with a NUL character. + *ptr = '\000'; + + // Conversion to ASCII actually resulted in the digits being in reverse + // order. We can't easily generate them in forward order, as we can't tell + // the number of characters needed until we are done converting. + // So, now, we reverse the string (except for the possible "-" sign). + while (--ptr > start) { + char ch = *ptr; + *ptr = *start; + *start++ = ch; + } + return buf; +} + +// Safely appends string |source| to string |dest|. Never writes past the +// buffer size |dest_size| and guarantees that |dest| is null-terminated. +static void SafeAppendString(const char* source, char* dest, size_t dest_size) { + size_t dest_string_length = strlen(dest); + SAFE_ASSERT(dest_string_length < dest_size); + dest += dest_string_length; + dest_size -= dest_string_length; + strncpy(dest, source, dest_size); + // Making sure |dest| is always null-terminated. + dest[dest_size - 1] = '\0'; +} + +// Converts a 64-bit value into a hex string, and safely appends it to |dest|. +// Never writes past the buffer size |dest_size| and guarantees that |dest| is +// null-terminated. +static void SafeAppendHexNumber(uint64_t value, char* dest, size_t dest_size) { + // 64-bit numbers in hex can have up to 16 digits. + char buf[17] = {'\0'}; + SafeAppendString(itoa_r(value, buf, sizeof(buf), 16, 0), dest, dest_size); +} + +// The implementation of our symbolization routine. If it +// successfully finds the symbol containing "pc" and obtains the +// symbol name, returns true and write the symbol name to "out". +// Otherwise, returns false. If Callback function is installed via +// InstallSymbolizeCallback(), the function is also called in this function, +// and "out" is used as its output. +// To keep stack consumption low, we would like this function to not +// get inlined. +static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out, + size_t out_size) { + uint64_t pc0 = reinterpret_cast(pc); + uint64_t start_address = 0; + uint64_t base_address = 0; + int object_fd = -1; + + if (out_size < 1) { + return false; + } + out[0] = '\0'; + SafeAppendString("(", out, out_size); + + if (g_symbolize_open_object_file_callback) { + object_fd = g_symbolize_open_object_file_callback(pc0, start_address, + base_address, out + 1, + out_size - 1); + } else { + object_fd = OpenObjectFileContainingPcAndGetStartAddress(pc0, start_address, + base_address, + out + 1, + out_size - 1); + } + + FileDescriptor wrapped_object_fd(object_fd); + +#if defined(PRINT_UNSYMBOLIZED_STACK_TRACES) + { +#else + // Check whether a file name was returned. + if (object_fd < 0) { +#endif + if (out[1]) { + // The object file containing PC was determined successfully however the + // object file was not opened successfully. This is still considered + // success because the object file name and offset are known and tools + // like asan_symbolize.py can be used for the symbolization. + out[out_size - 1] = '\0'; // Making sure |out| is always null-terminated. + SafeAppendString("+0x", out, out_size); + SafeAppendHexNumber(pc0 - base_address, out, out_size); + SafeAppendString(")", out, out_size); + return true; + } + // Failed to determine the object file containing PC. Bail out. + return false; + } + int elf_type = FileGetElfType(wrapped_object_fd.get()); + if (elf_type == -1) { + return false; + } + if (g_symbolize_callback) { + // Run the call back if it's installed. + // Note: relocation (and much of the rest of this code) will be + // wrong for prelinked shared libraries and PIE executables. + uint64_t relocation = (elf_type == ET_DYN) ? start_address : 0; + int num_bytes_written = g_symbolize_callback(wrapped_object_fd.get(), + pc, out, out_size, + relocation); + if (num_bytes_written > 0) { + out += static_cast(num_bytes_written); + out_size -= static_cast(num_bytes_written); + } + } + if (!GetSymbolFromObjectFile(wrapped_object_fd.get(), pc0, + out, out_size, base_address)) { + if (out[1] && !g_symbolize_callback) { + // The object file containing PC was opened successfully however the + // symbol was not found. The object may have been stripped. This is still + // considered success because the object file name and offset are known + // and tools like asan_symbolize.py can be used for the symbolization. + out[out_size - 1] = '\0'; // Making sure |out| is always null-terminated. + SafeAppendString("+0x", out, out_size); + SafeAppendHexNumber(pc0 - base_address, out, out_size); + SafeAppendString(")", out, out_size); + return true; + } + return false; + } + + // Symbolization succeeded. Now we try to demangle the symbol. + DemangleInplace(out, out_size); + return true; +} + +_END_GOOGLE_NAMESPACE_ + +#elif defined(GLOG_OS_MACOSX) && defined(HAVE_DLADDR) + +#include +#include + +_START_GOOGLE_NAMESPACE_ + +static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out, + size_t out_size) { + Dl_info info; + if (dladdr(pc, &info)) { + if (info.dli_sname) { + if (strlen(info.dli_sname) < out_size) { + strcpy(out, info.dli_sname); + // Symbolization succeeded. Now we try to demangle the symbol. + DemangleInplace(out, out_size); + return true; + } + } + } + return false; +} + +_END_GOOGLE_NAMESPACE_ + +#elif defined(GLOG_OS_WINDOWS) || defined(GLOG_OS_CYGWIN) + +#include +#include + +#ifdef _MSC_VER +#pragma comment(lib, "dbghelp") +#endif + +_START_GOOGLE_NAMESPACE_ + +class SymInitializer { +public: + HANDLE process; + bool ready; + SymInitializer() : process(NULL), ready(false) { + // Initialize the symbol handler. + // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680344(v=vs.85).aspx + process = GetCurrentProcess(); + // Defer symbol loading. + // We do not request undecorated symbols with SYMOPT_UNDNAME + // because the mangling library calls UnDecorateSymbolName. + SymSetOptions(SYMOPT_DEFERRED_LOADS); + if (SymInitialize(process, NULL, true)) { + ready = true; + } + } + ~SymInitializer() { + SymCleanup(process); + // We do not need to close `HANDLE process` because it's a "pseudo handle." + } +private: + SymInitializer(const SymInitializer&); + SymInitializer& operator=(const SymInitializer&); +}; + +static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out, + int out_size) { + const static SymInitializer symInitializer; + if (!symInitializer.ready) { + return false; + } + // Resolve symbol information from address. + // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680578(v=vs.85).aspx + char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME]; + SYMBOL_INFO *symbol = reinterpret_cast(buf); + symbol->SizeOfStruct = sizeof(SYMBOL_INFO); + symbol->MaxNameLen = MAX_SYM_NAME; + // We use the ANSI version to ensure the string type is always `char *`. + // This could break if a symbol has Unicode in it. + BOOL ret = SymFromAddr(symInitializer.process, + reinterpret_cast(pc), 0, symbol); + if (ret == 1 && static_cast(symbol->NameLen) < out_size) { + // `NameLen` does not include the null terminating character. + strncpy(out, symbol->Name, static_cast(symbol->NameLen) + 1); + out[static_cast(symbol->NameLen)] = '\0'; + // Symbolization succeeded. Now we try to demangle the symbol. + DemangleInplace(out, out_size); + return true; + } + return false; +} + +_END_GOOGLE_NAMESPACE_ + +#else +# error BUG: HAVE_SYMBOLIZE was wrongly set +#endif + +_START_GOOGLE_NAMESPACE_ + +bool Symbolize(void *pc, char *out, size_t out_size) { + return SymbolizeAndDemangle(pc, out, out_size); +} + +_END_GOOGLE_NAMESPACE_ + +#else /* HAVE_SYMBOLIZE */ + +#include + +#include "config.h" + +_START_GOOGLE_NAMESPACE_ + +// TODO: Support other environments. +bool Symbolize(void* /*pc*/, char* /*out*/, size_t /*out_size*/) { + assert(0); + return false; +} + +_END_GOOGLE_NAMESPACE_ + +#endif diff --git a/third_party/glog/src/symbolize.h b/third_party/glog/src/symbolize.h new file mode 100644 index 0000000..dcbb194 --- /dev/null +++ b/third_party/glog/src/symbolize.h @@ -0,0 +1,159 @@ +// Copyright (c) 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Satoru Takabayashi +// +// This library provides Symbolize() function that symbolizes program +// counters to their corresponding symbol names on linux platforms. +// This library has a minimal implementation of an ELF symbol table +// reader (i.e. it doesn't depend on libelf, etc.). +// +// The algorithm used in Symbolize() is as follows. +// +// 1. Go through a list of maps in /proc/self/maps and find the map +// containing the program counter. +// +// 2. Open the mapped file and find a regular symbol table inside. +// Iterate over symbols in the symbol table and look for the symbol +// containing the program counter. If such a symbol is found, +// obtain the symbol name, and demangle the symbol if possible. +// If the symbol isn't found in the regular symbol table (binary is +// stripped), try the same thing with a dynamic symbol table. +// +// Note that Symbolize() is originally implemented to be used in +// FailureSignalHandler() in base/google.cc. Hence it doesn't use +// malloc() and other unsafe operations. It should be both +// thread-safe and async-signal-safe. + +#ifndef BASE_SYMBOLIZE_H_ +#define BASE_SYMBOLIZE_H_ + +#include "utilities.h" +#include "config.h" +#include + +#ifdef HAVE_SYMBOLIZE + +#if defined(__ELF__) // defined by gcc +#if defined(__OpenBSD__) +#include +#else +#include +#endif + +#if !defined(ANDROID) +#include // For ElfW() macro. +#endif + +// For systems where SIZEOF_VOID_P is not defined, determine it +// based on __LP64__ (defined by gcc on 64-bit systems) +#if !defined(SIZEOF_VOID_P) +# if defined(__LP64__) +# define SIZEOF_VOID_P 8 +# else +# define SIZEOF_VOID_P 4 +# endif +#endif + +// If there is no ElfW macro, let's define it by ourself. +#ifndef ElfW +# if SIZEOF_VOID_P == 4 +# define ElfW(type) Elf32_##type +# elif SIZEOF_VOID_P == 8 +# define ElfW(type) Elf64_##type +# else +# error "Unknown sizeof(void *)" +# endif +#endif + +_START_GOOGLE_NAMESPACE_ + +// Gets the section header for the given name, if it exists. Returns true on +// success. Otherwise, returns false. +bool GetSectionHeaderByName(int fd, const char *name, size_t name_len, + ElfW(Shdr) *out); + +_END_GOOGLE_NAMESPACE_ + +#endif /* __ELF__ */ + +_START_GOOGLE_NAMESPACE_ + +// Restrictions on the callbacks that follow: +// - The callbacks must not use heaps but only use stacks. +// - The callbacks must be async-signal-safe. + +// Installs a callback function, which will be called right before a symbol name +// is printed. The callback is intended to be used for showing a file name and a +// line number preceding a symbol name. +// "fd" is a file descriptor of the object file containing the program +// counter "pc". The callback function should write output to "out" +// and return the size of the output written. On error, the callback +// function should return -1. +typedef int (*SymbolizeCallback)(int fd, + void* pc, + char* out, + size_t out_size, + uint64_t relocation); +GLOG_EXPORT +void InstallSymbolizeCallback(SymbolizeCallback callback); + +// Installs a callback function, which will be called instead of +// OpenObjectFileContainingPcAndGetStartAddress. The callback is expected +// to searches for the object file (from /proc/self/maps) that contains +// the specified pc. If found, sets |start_address| to the start address +// of where this object file is mapped in memory, sets the module base +// address into |base_address|, copies the object file name into +// |out_file_name|, and attempts to open the object file. If the object +// file is opened successfully, returns the file descriptor. Otherwise, +// returns -1. |out_file_name_size| is the size of the file name buffer +// (including the null-terminator). +typedef int (*SymbolizeOpenObjectFileCallback)(uint64_t pc, + uint64_t& start_address, + uint64_t& base_address, + char* out_file_name, + size_t out_file_name_size); +void InstallSymbolizeOpenObjectFileCallback( + SymbolizeOpenObjectFileCallback callback); + +_END_GOOGLE_NAMESPACE_ + +#endif + +_START_GOOGLE_NAMESPACE_ + +// Symbolizes a program counter. On success, returns true and write the +// symbol name to "out". The symbol name is demangled if possible +// (supports symbols generated by GCC 3.x or newer). Otherwise, +// returns false. +GLOG_EXPORT bool Symbolize(void* pc, char* out, size_t out_size); + +_END_GOOGLE_NAMESPACE_ + +#endif // BASE_SYMBOLIZE_H_ diff --git a/third_party/glog/src/symbolize_unittest.cc b/third_party/glog/src/symbolize_unittest.cc new file mode 100644 index 0000000..a50e44a --- /dev/null +++ b/third_party/glog/src/symbolize_unittest.cc @@ -0,0 +1,447 @@ +// Copyright (c) 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Satoru Takabayashi +// +// Unit tests for functions in symbolize.cc. + +#include +#include + +#include "config.h" +#include +#include "googletest.h" +#include "symbolize.h" +#include "utilities.h" + +#ifdef HAVE_LIB_GFLAGS +#include +using namespace GFLAGS_NAMESPACE; +#endif + +using namespace std; +using namespace GOOGLE_NAMESPACE; + +#if defined(HAVE_STACKTRACE) + +#define always_inline + +#if defined(__ELF__) || defined(GLOG_OS_WINDOWS) || defined(GLOG_OS_CYGWIN) +// A wrapper function for Symbolize() to make the unit test simple. +static const char *TrySymbolize(void *pc) { + static char symbol[4096]; + if (Symbolize(pc, symbol, sizeof(symbol))) { + return symbol; + } else { + return NULL; + } +} +#endif + +# if defined(__ELF__) + +// This unit tests make sense only with GCC. +// Uses lots of GCC specific features. +#if defined(__GNUC__) && !defined(__OPENCC__) +# if __GNUC__ >= 4 +# define TEST_WITH_MODERN_GCC +# if defined(__i386__) && __i386__ // always_inline isn't supported for x86_64 with GCC 4.1.0. +# undef always_inline +# define always_inline __attribute__((always_inline)) +# define HAVE_ALWAYS_INLINE +# endif // __i386__ +# else +# endif // __GNUC__ >= 4 +# if defined(__i386__) || defined(__x86_64__) +# define TEST_X86_32_AND_64 1 +# endif // defined(__i386__) || defined(__x86_64__) +#endif + +// Make them C linkage to avoid mangled names. +extern "C" { +void nonstatic_func(); +void nonstatic_func() { + volatile int a = 0; + ++a; +} + +static void static_func() { + volatile int a = 0; + ++a; +} +} + +TEST(Symbolize, Symbolize) { + // We do C-style cast since GCC 2.95.3 doesn't allow + // reinterpret_cast(&func). + + // Compilers should give us pointers to them. + EXPECT_STREQ("nonstatic_func", TrySymbolize((void *)(&nonstatic_func))); + + // The name of an internal linkage symbol is not specified; allow either a + // mangled or an unmangled name here. + const char *static_func_symbol = + TrySymbolize(reinterpret_cast(&static_func)); + +#if !defined(_MSC_VER) || !defined(NDEBUG) + CHECK(NULL != static_func_symbol); + EXPECT_TRUE(strcmp("static_func", static_func_symbol) == 0 || + strcmp("static_func()", static_func_symbol) == 0); +#endif + + EXPECT_TRUE(NULL == TrySymbolize(NULL)); +} + +struct Foo { + static void func(int x); +}; + +void ATTRIBUTE_NOINLINE Foo::func(int x) { + volatile int a = x; + ++a; +} + +// With a modern GCC, Symbolize() should return demangled symbol +// names. Function parameters should be omitted. +#ifdef TEST_WITH_MODERN_GCC +TEST(Symbolize, SymbolizeWithDemangling) { + Foo::func(100); +#if !defined(_MSC_VER) || !defined(NDEBUG) + EXPECT_STREQ("Foo::func()", TrySymbolize((void *)(&Foo::func))); +#endif +} +#endif + +// Tests that verify that Symbolize footprint is within some limit. + +// To measure the stack footprint of the Symbolize function, we create +// a signal handler (for SIGUSR1 say) that calls the Symbolize function +// on an alternate stack. This alternate stack is initialized to some +// known pattern (0x55, 0x55, 0x55, ...). We then self-send this signal, +// and after the signal handler returns, look at the alternate stack +// buffer to see what portion has been touched. +// +// This trick gives us the the stack footprint of the signal handler. +// But the signal handler, even before the call to Symbolize, consumes +// some stack already. We however only want the stack usage of the +// Symbolize function. To measure this accurately, we install two signal +// handlers: one that does nothing and just returns, and another that +// calls Symbolize. The difference between the stack consumption of these +// two signals handlers should give us the Symbolize stack foorprint. + +static void *g_pc_to_symbolize; +static char g_symbolize_buffer[4096]; +static char *g_symbolize_result; + +static void EmptySignalHandler(int /*signo*/) {} + +static void SymbolizeSignalHandler(int /*signo*/) { + if (Symbolize(g_pc_to_symbolize, g_symbolize_buffer, + sizeof(g_symbolize_buffer))) { + g_symbolize_result = g_symbolize_buffer; + } else { + g_symbolize_result = NULL; + } +} + +const int kAlternateStackSize = 8096; +const char kAlternateStackFillValue = 0x55; + +// These helper functions look at the alternate stack buffer, and figure +// out what portion of this buffer has been touched - this is the stack +// consumption of the signal handler running on this alternate stack. +static ATTRIBUTE_NOINLINE bool StackGrowsDown(int *x) { + int y; + return &y < x; +} +static int GetStackConsumption(const char* alt_stack) { + int x; + if (StackGrowsDown(&x)) { + for (int i = 0; i < kAlternateStackSize; i++) { + if (alt_stack[i] != kAlternateStackFillValue) { + return (kAlternateStackSize - i); + } + } + } else { + for (int i = (kAlternateStackSize - 1); i >= 0; i--) { + if (alt_stack[i] != kAlternateStackFillValue) { + return i; + } + } + } + return -1; +} + +#ifdef HAVE_SIGALTSTACK + +// Call Symbolize and figure out the stack footprint of this call. +static const char *SymbolizeStackConsumption(void *pc, int *stack_consumed) { + + g_pc_to_symbolize = pc; + + // The alt-signal-stack cannot be heap allocated because there is a + // bug in glibc-2.2 where some signal handler setup code looks at the + // current stack pointer to figure out what thread is currently running. + // Therefore, the alternate stack must be allocated from the main stack + // itself. + char altstack[kAlternateStackSize]; + memset(altstack, kAlternateStackFillValue, kAlternateStackSize); + + // Set up the alt-signal-stack (and save the older one). + stack_t sigstk; + memset(&sigstk, 0, sizeof(stack_t)); + stack_t old_sigstk; + sigstk.ss_sp = altstack; + sigstk.ss_size = kAlternateStackSize; + sigstk.ss_flags = 0; + CHECK_ERR(sigaltstack(&sigstk, &old_sigstk)); + + // Set up SIGUSR1 and SIGUSR2 signal handlers (and save the older ones). + struct sigaction sa; + memset(&sa, 0, sizeof(struct sigaction)); + struct sigaction old_sa1, old_sa2; + sigemptyset(&sa.sa_mask); + sa.sa_flags = SA_ONSTACK; + + // SIGUSR1 maps to EmptySignalHandler. + sa.sa_handler = EmptySignalHandler; + CHECK_ERR(sigaction(SIGUSR1, &sa, &old_sa1)); + + // SIGUSR2 maps to SymbolizeSignalHanlder. + sa.sa_handler = SymbolizeSignalHandler; + CHECK_ERR(sigaction(SIGUSR2, &sa, &old_sa2)); + + // Send SIGUSR1 signal and measure the stack consumption of the empty + // signal handler. + CHECK_ERR(kill(getpid(), SIGUSR1)); + int stack_consumption1 = GetStackConsumption(altstack); + + // Send SIGUSR2 signal and measure the stack consumption of the symbolize + // signal handler. + CHECK_ERR(kill(getpid(), SIGUSR2)); + int stack_consumption2 = GetStackConsumption(altstack); + + // The difference between the two stack consumption values is the + // stack footprint of the Symbolize function. + if (stack_consumption1 != -1 && stack_consumption2 != -1) { + *stack_consumed = stack_consumption2 - stack_consumption1; + } else { + *stack_consumed = -1; + } + + // Log the stack consumption values. + LOG(INFO) << "Stack consumption of empty signal handler: " + << stack_consumption1; + LOG(INFO) << "Stack consumption of symbolize signal handler: " + << stack_consumption2; + LOG(INFO) << "Stack consumption of Symbolize: " << *stack_consumed; + + // Now restore the old alt-signal-stack and signal handlers. + CHECK_ERR(sigaltstack(&old_sigstk, NULL)); + CHECK_ERR(sigaction(SIGUSR1, &old_sa1, NULL)); + CHECK_ERR(sigaction(SIGUSR2, &old_sa2, NULL)); + + return g_symbolize_result; +} + +#ifdef __ppc64__ +// Symbolize stack consumption should be within 4kB. +const int kStackConsumptionUpperLimit = 4096; +#else +// Symbolize stack consumption should be within 2kB. +const int kStackConsumptionUpperLimit = 2048; +#endif + +TEST(Symbolize, SymbolizeStackConsumption) { + int stack_consumed; + const char* symbol; + + symbol = SymbolizeStackConsumption(reinterpret_cast(&nonstatic_func), + &stack_consumed); + EXPECT_STREQ("nonstatic_func", symbol); + EXPECT_GT(stack_consumed, 0); + EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit); + + // The name of an internal linkage symbol is not specified; allow either a + // mangled or an unmangled name here. + symbol = SymbolizeStackConsumption(reinterpret_cast(&static_func), + &stack_consumed); + CHECK(NULL != symbol); + EXPECT_TRUE(strcmp("static_func", symbol) == 0 || + strcmp("static_func()", symbol) == 0); + EXPECT_GT(stack_consumed, 0); + EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit); +} + +#ifdef TEST_WITH_MODERN_GCC +TEST(Symbolize, SymbolizeWithDemanglingStackConsumption) { + Foo::func(100); + int stack_consumed; + const char* symbol; + + symbol = SymbolizeStackConsumption(reinterpret_cast(&Foo::func), + &stack_consumed); + + EXPECT_STREQ("Foo::func()", symbol); + EXPECT_GT(stack_consumed, 0); + EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit); +} +#endif + +#endif // HAVE_SIGALTSTACK + +// x86 specific tests. Uses some inline assembler. +extern "C" { +inline void* always_inline inline_func() { + void *pc = NULL; +#ifdef TEST_X86_32_AND_64 + __asm__ __volatile__("call 1f; 1: pop %0" : "=r"(pc)); +#endif + return pc; +} + +void* ATTRIBUTE_NOINLINE non_inline_func(); +void* ATTRIBUTE_NOINLINE non_inline_func() { + void *pc = NULL; +#ifdef TEST_X86_32_AND_64 + __asm__ __volatile__("call 1f; 1: pop %0" : "=r"(pc)); +#endif + return pc; +} + +static void ATTRIBUTE_NOINLINE TestWithPCInsideNonInlineFunction() { +#if defined(TEST_X86_32_AND_64) && defined(HAVE_ATTRIBUTE_NOINLINE) + void *pc = non_inline_func(); + const char *symbol = TrySymbolize(pc); + +#if !defined(_MSC_VER) || !defined(NDEBUG) + CHECK(symbol != NULL); + CHECK_STREQ(symbol, "non_inline_func"); +#endif + cout << "Test case TestWithPCInsideNonInlineFunction passed." << endl; +#endif +} + +static void ATTRIBUTE_NOINLINE TestWithPCInsideInlineFunction() { +#if defined(TEST_X86_32_AND_64) && defined(HAVE_ALWAYS_INLINE) + void *pc = inline_func(); // Must be inlined. + const char *symbol = TrySymbolize(pc); + +#if !defined(_MSC_VER) || !defined(NDEBUG) + CHECK(symbol != NULL); + CHECK_STREQ(symbol, __FUNCTION__); +#endif + cout << "Test case TestWithPCInsideInlineFunction passed." << endl; +#endif +} +} + +// Test with a return address. +static void ATTRIBUTE_NOINLINE TestWithReturnAddress() { +#if defined(HAVE_ATTRIBUTE_NOINLINE) + void *return_address = __builtin_return_address(0); + const char *symbol = TrySymbolize(return_address); + +#if !defined(_MSC_VER) || !defined(NDEBUG) + CHECK(symbol != NULL); + CHECK_STREQ(symbol, "main"); +#endif + cout << "Test case TestWithReturnAddress passed." << endl; +#endif +} + +# elif defined(GLOG_OS_WINDOWS) || defined(GLOG_OS_CYGWIN) + +#ifdef _MSC_VER +#include +#pragma intrinsic(_ReturnAddress) +#endif + +struct Foo { + static void func(int x); +}; + +__declspec(noinline) void Foo::func(int x) { + volatile int a = x; + ++a; +} + +TEST(Symbolize, SymbolizeWithDemangling) { + Foo::func(100); + const char* ret = TrySymbolize((void *)(&Foo::func)); + +#if defined(HAVE_DBGHELP) && !defined(NDEBUG) + EXPECT_STREQ("public: static void __cdecl Foo::func(int)", ret); +#endif +} + +__declspec(noinline) void TestWithReturnAddress() { + void *return_address = +#ifdef __GNUC__ // Cygwin and MinGW support + __builtin_return_address(0) +#else + _ReturnAddress() +#endif + ; + const char *symbol = TrySymbolize(return_address); +#if !defined(_MSC_VER) || !defined(NDEBUG) + CHECK(symbol != NULL); + CHECK_STREQ(symbol, "main"); +#endif + cout << "Test case TestWithReturnAddress passed." << endl; +} +# endif // __ELF__ +#endif // HAVE_STACKTRACE + +int main(int argc, char **argv) { + FLAGS_logtostderr = true; + InitGoogleLogging(argv[0]); + InitGoogleTest(&argc, argv); +#if defined(HAVE_SYMBOLIZE) && defined(HAVE_STACKTRACE) +# if defined(__ELF__) + // We don't want to get affected by the callback interface, that may be + // used to install some callback function at InitGoogle() time. + InstallSymbolizeCallback(NULL); + + TestWithPCInsideInlineFunction(); + TestWithPCInsideNonInlineFunction(); + TestWithReturnAddress(); + return RUN_ALL_TESTS(); +# elif defined(GLOG_OS_WINDOWS) || defined(GLOG_OS_CYGWIN) + TestWithReturnAddress(); + return RUN_ALL_TESTS(); +# else // GLOG_OS_WINDOWS + printf("PASS (no symbolize_unittest support)\n"); + return 0; +# endif // __ELF__ +#else + printf("PASS (no symbolize support)\n"); + return 0; +#endif // HAVE_SYMBOLIZE +} diff --git a/third_party/glog/src/utilities.cc b/third_party/glog/src/utilities.cc new file mode 100644 index 0000000..a332f1a --- /dev/null +++ b/third_party/glog/src/utilities.cc @@ -0,0 +1,402 @@ +// Copyright (c) 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Shinichiro Hamaji + +#include "config.h" +#include "utilities.h" + +#include +#include + +#include +#ifdef HAVE_SYS_TIME_H +# include +#endif +#include +#if defined(HAVE_SYSCALL_H) +#include // for syscall() +#elif defined(HAVE_SYS_SYSCALL_H) +#include // for syscall() +#endif +#ifdef HAVE_SYSLOG_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include // For geteuid. +#endif +#ifdef HAVE_PWD_H +# include +#endif +#ifdef __ANDROID__ +#include +#endif + +#include "base/googleinit.h" + +using std::string; + +_START_GOOGLE_NAMESPACE_ + +static const char* g_program_invocation_short_name = NULL; + +bool IsGoogleLoggingInitialized() { + return g_program_invocation_short_name != NULL; +} + +_END_GOOGLE_NAMESPACE_ + +// The following APIs are all internal. +#ifdef HAVE_STACKTRACE + +#include "stacktrace.h" +#include "symbolize.h" +#include "base/commandlineflags.h" + +GLOG_DEFINE_bool(symbolize_stacktrace, true, + "Symbolize the stack trace in the tombstone"); + +_START_GOOGLE_NAMESPACE_ + +typedef void DebugWriter(const char*, void*); + +// The %p field width for printf() functions is two characters per byte. +// For some environments, add two extra bytes for the leading "0x". +static const int kPrintfPointerFieldWidth = 2 + 2 * sizeof(void*); + +static void DebugWriteToStderr(const char* data, void *) { + // This one is signal-safe. + if (write(STDERR_FILENO, data, strlen(data)) < 0) { + // Ignore errors. + } +#if defined(__ANDROID__) + // ANDROID_LOG_FATAL as fatal error occurred and now is dumping call stack. + __android_log_write(ANDROID_LOG_FATAL, + glog_internal_namespace_::ProgramInvocationShortName(), + data); +#endif +} + +static void DebugWriteToString(const char* data, void *arg) { + reinterpret_cast(arg)->append(data); +} + +#ifdef HAVE_SYMBOLIZE +// Print a program counter and its symbol name. +static void DumpPCAndSymbol(DebugWriter *writerfn, void *arg, void *pc, + const char * const prefix) { + char tmp[1024]; + const char *symbol = "(unknown)"; + // Symbolizes the previous address of pc because pc may be in the + // next function. The overrun happens when the function ends with + // a call to a function annotated noreturn (e.g. CHECK). + if (Symbolize(reinterpret_cast(pc) - 1, tmp, sizeof(tmp))) { + symbol = tmp; + } + char buf[1024]; + snprintf(buf, sizeof(buf), "%s@ %*p %s\n", + prefix, kPrintfPointerFieldWidth, pc, symbol); + writerfn(buf, arg); +} +#endif + +static void DumpPC(DebugWriter *writerfn, void *arg, void *pc, + const char * const prefix) { + char buf[100]; + snprintf(buf, sizeof(buf), "%s@ %*p\n", + prefix, kPrintfPointerFieldWidth, pc); + writerfn(buf, arg); +} + +// Dump current stack trace as directed by writerfn +static void DumpStackTrace(int skip_count, DebugWriter *writerfn, void *arg) { + // Print stack trace + void* stack[32]; + int depth = GetStackTrace(stack, ARRAYSIZE(stack), skip_count+1); + for (int i = 0; i < depth; i++) { +#if defined(HAVE_SYMBOLIZE) + if (FLAGS_symbolize_stacktrace) { + DumpPCAndSymbol(writerfn, arg, stack[i], " "); + } else { + DumpPC(writerfn, arg, stack[i], " "); + } +#else + DumpPC(writerfn, arg, stack[i], " "); +#endif + } +} + +#if defined(__GNUC__) +__attribute__((noreturn)) +#elif defined(_MSC_VER) +__declspec(noreturn) +#endif +static void DumpStackTraceAndExit() { + DumpStackTrace(1, DebugWriteToStderr, NULL); + + // TODO(hamaji): Use signal instead of sigaction? + if (IsFailureSignalHandlerInstalled()) { + // Set the default signal handler for SIGABRT, to avoid invoking our + // own signal handler installed by InstallFailureSignalHandler(). +#ifdef HAVE_SIGACTION + struct sigaction sig_action; + memset(&sig_action, 0, sizeof(sig_action)); + sigemptyset(&sig_action.sa_mask); + sig_action.sa_handler = SIG_DFL; + sigaction(SIGABRT, &sig_action, NULL); +#elif defined(GLOG_OS_WINDOWS) + signal(SIGABRT, SIG_DFL); +#endif // HAVE_SIGACTION + } + + abort(); +} + +_END_GOOGLE_NAMESPACE_ + +#endif // HAVE_STACKTRACE + +_START_GOOGLE_NAMESPACE_ + +namespace glog_internal_namespace_ { + +const char* ProgramInvocationShortName() { + if (g_program_invocation_short_name != NULL) { + return g_program_invocation_short_name; + } else { + // TODO(hamaji): Use /proc/self/cmdline and so? + return "UNKNOWN"; + } +} + +#ifdef GLOG_OS_WINDOWS +struct timeval { + long tv_sec, tv_usec; +}; + +// Based on: http://www.google.com/codesearch/p?hl=en#dR3YEbitojA/os_win32.c&q=GetSystemTimeAsFileTime%20license:bsd +// See COPYING for copyright information. +static int gettimeofday(struct timeval *tv, void* /*tz*/) { +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wlong-long" +#endif +#define EPOCHFILETIME (116444736000000000ULL) + FILETIME ft; + ULARGE_INTEGER li; + uint64 tt; + + GetSystemTimeAsFileTime(&ft); + li.LowPart = ft.dwLowDateTime; + li.HighPart = ft.dwHighDateTime; + tt = (li.QuadPart - EPOCHFILETIME) / 10; + tv->tv_sec = tt / 1000000; + tv->tv_usec = tt % 1000000; +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + + return 0; +} +#endif + +int64 CycleClock_Now() { + // TODO(hamaji): temporary impementation - it might be too slow. + struct timeval tv; + gettimeofday(&tv, NULL); + return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; +} + +int64 UsecToCycles(int64 usec) { + return usec; +} + +WallTime WallTime_Now() { + // Now, cycle clock is retuning microseconds since the epoch. + return CycleClock_Now() * 0.000001; +} + +static int32 g_main_thread_pid = getpid(); +int32 GetMainThreadPid() { + return g_main_thread_pid; +} + +bool PidHasChanged() { + int32 pid = getpid(); + if (g_main_thread_pid == pid) { + return false; + } + g_main_thread_pid = pid; + return true; +} + +pid_t GetTID() { + // On Linux and MacOSX, we try to use gettid(). +#if defined GLOG_OS_LINUX || defined GLOG_OS_MACOSX +#ifndef __NR_gettid +#ifdef GLOG_OS_MACOSX +#define __NR_gettid SYS_gettid +#elif ! defined __i386__ +#error "Must define __NR_gettid for non-x86 platforms" +#else +#define __NR_gettid 224 +#endif +#endif + static bool lacks_gettid = false; + if (!lacks_gettid) { +#if (defined(GLOG_OS_MACOSX) && defined(HAVE_PTHREAD_THREADID_NP)) + uint64_t tid64; + const int error = pthread_threadid_np(NULL, &tid64); + pid_t tid = error ? -1 : static_cast(tid64); +#else + pid_t tid = static_cast(syscall(__NR_gettid)); +#endif + if (tid != -1) { + return tid; + } + // Technically, this variable has to be volatile, but there is a small + // performance penalty in accessing volatile variables and there should + // not be any serious adverse effect if a thread does not immediately see + // the value change to "true". + lacks_gettid = true; + } +#endif // GLOG_OS_LINUX || GLOG_OS_MACOSX + + // If gettid() could not be used, we use one of the following. +#if defined GLOG_OS_LINUX + return getpid(); // Linux: getpid returns thread ID when gettid is absent +#elif defined GLOG_OS_WINDOWS && !defined GLOG_OS_CYGWIN + return static_cast(GetCurrentThreadId()); +#elif defined(HAVE_PTHREAD) + // If none of the techniques above worked, we use pthread_self(). + return (pid_t)(uintptr_t)pthread_self(); +#else + return -1; +#endif +} + +const char* const_basename(const char* filepath) { + const char* base = strrchr(filepath, '/'); +#ifdef GLOG_OS_WINDOWS // Look for either path separator in Windows + if (!base) + base = strrchr(filepath, '\\'); +#endif + return base ? (base+1) : filepath; +} + +static string g_my_user_name; +const string& MyUserName() { + return g_my_user_name; +} +static void MyUserNameInitializer() { + // TODO(hamaji): Probably this is not portable. +#if defined(GLOG_OS_WINDOWS) + const char* user = getenv("USERNAME"); +#else + const char* user = getenv("USER"); +#endif + if (user != NULL) { + g_my_user_name = user; + } else { +#if defined(HAVE_PWD_H) && defined(HAVE_UNISTD_H) + struct passwd pwd; + struct passwd* result = NULL; + char buffer[1024] = {'\0'}; + uid_t uid = geteuid(); + int pwuid_res = getpwuid_r(uid, &pwd, buffer, sizeof(buffer), &result); + if (pwuid_res == 0 && result) { + g_my_user_name = pwd.pw_name; + } else { + snprintf(buffer, sizeof(buffer), "uid%d", uid); + g_my_user_name = buffer; + } +#endif + if (g_my_user_name.empty()) { + g_my_user_name = "invalid-user"; + } + } + +} +REGISTER_MODULE_INITIALIZER(utilities, MyUserNameInitializer()) + +#ifdef HAVE_STACKTRACE +void DumpStackTraceToString(string* stacktrace) { + DumpStackTrace(1, DebugWriteToString, stacktrace); +} +#endif + +// We use an atomic operation to prevent problems with calling CrashReason +// from inside the Mutex implementation (potentially through RAW_CHECK). +static const CrashReason* g_reason = 0; + +void SetCrashReason(const CrashReason* r) { + sync_val_compare_and_swap(&g_reason, + reinterpret_cast(0), + r); +} + +void InitGoogleLoggingUtilities(const char* argv0) { + CHECK(!IsGoogleLoggingInitialized()) + << "You called InitGoogleLogging() twice!"; + const char* slash = strrchr(argv0, '/'); +#ifdef GLOG_OS_WINDOWS + if (!slash) slash = strrchr(argv0, '\\'); +#endif + g_program_invocation_short_name = slash ? slash + 1 : argv0; + +#ifdef HAVE_STACKTRACE + InstallFailureFunction(&DumpStackTraceAndExit); +#endif +} + +void ShutdownGoogleLoggingUtilities() { + CHECK(IsGoogleLoggingInitialized()) + << "You called ShutdownGoogleLogging() without calling InitGoogleLogging() first!"; + g_program_invocation_short_name = NULL; +#ifdef HAVE_SYSLOG_H + closelog(); +#endif +} + +} // namespace glog_internal_namespace_ + +_END_GOOGLE_NAMESPACE_ + +// Make an implementation of stacktrace compiled. +#ifdef STACKTRACE_H +# include STACKTRACE_H +# if 0 +// For include scanners which can't handle macro expansions. +# include "stacktrace_libunwind-inl.h" +# include "stacktrace_x86-inl.h" +# include "stacktrace_x86_64-inl.h" +# include "stacktrace_powerpc-inl.h" +# include "stacktrace_generic-inl.h" +# endif +#endif diff --git a/third_party/glog/src/utilities.h b/third_party/glog/src/utilities.h new file mode 100644 index 0000000..1f55eff --- /dev/null +++ b/third_party/glog/src/utilities.h @@ -0,0 +1,217 @@ +// Copyright (c) 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Shinichiro Hamaji +// +// Define utilties for glog internal usage. + +#ifndef UTILITIES_H__ +#define UTILITIES_H__ + +// printf macros for size_t, in the style of inttypes.h +#ifdef _LP64 +#define __PRIS_PREFIX "z" +#else +#define __PRIS_PREFIX +#endif + +// Use these macros after a % in a printf format string +// to get correct 32/64 bit behavior, like this: +// size_t size = records.size(); +// printf("%"PRIuS"\n", size); + +#define PRIdS __PRIS_PREFIX "d" +#define PRIxS __PRIS_PREFIX "x" +#define PRIuS __PRIS_PREFIX "u" +#define PRIXS __PRIS_PREFIX "X" +#define PRIoS __PRIS_PREFIX "o" + +#include "base/mutex.h" // This must go first so we get _XOPEN_SOURCE + +#include + +#include + +#if defined(GLOG_OS_WINDOWS) +# include "port.h" +#endif + +#include "config.h" + +// There are three different ways we can try to get the stack trace: +// +// 1) The libunwind library. This is still in development, and as a +// separate library adds a new dependency, but doesn't need a frame +// pointer. It also doesn't call malloc. +// +// 2) Our hand-coded stack-unwinder. This depends on a certain stack +// layout, which is used by gcc (and those systems using a +// gcc-compatible ABI) on x86 systems, at least since gcc 2.95. +// It uses the frame pointer to do its work. +// +// 3) The gdb unwinder -- also the one used by the c++ exception code. +// It's obviously well-tested, but has a fatal flaw: it can call +// malloc() from the unwinder. This is a problem because we're +// trying to use the unwinder to instrument malloc(). +// +// 4) The Windows API CaptureStackTrace. +// +// Note: if you add a new implementation here, make sure it works +// correctly when GetStackTrace() is called with max_depth == 0. +// Some code may do that. + +#if defined(HAVE_LIB_UNWIND) +# define STACKTRACE_H "stacktrace_libunwind-inl.h" +#elif defined(HAVE__UNWIND_BACKTRACE) +# define STACKTRACE_H "stacktrace_unwind-inl.h" +#elif !defined(NO_FRAME_POINTER) +# if defined(__i386__) && __GNUC__ >= 2 +# define STACKTRACE_H "stacktrace_x86-inl.h" +# elif (defined(__ppc__) || defined(__PPC__)) && __GNUC__ >= 2 +# define STACKTRACE_H "stacktrace_powerpc-inl.h" +# elif defined(GLOG_OS_WINDOWS) +# define STACKTRACE_H "stacktrace_windows-inl.h" +# endif +#endif + +#if !defined(STACKTRACE_H) && defined(HAVE_EXECINFO_H) +# define STACKTRACE_H "stacktrace_generic-inl.h" +#endif + +#if defined(STACKTRACE_H) +# define HAVE_STACKTRACE +#endif + +#ifndef GLOG_NO_SYMBOLIZE_DETECTION +#ifndef HAVE_SYMBOLIZE +// defined by gcc +#if defined(__ELF__) && defined(GLOG_OS_LINUX) +# define HAVE_SYMBOLIZE +#elif defined(GLOG_OS_MACOSX) && defined(HAVE_DLADDR) +// Use dladdr to symbolize. +# define HAVE_SYMBOLIZE +#elif defined(GLOG_OS_WINDOWS) +// Use DbgHelp to symbolize +# define HAVE_SYMBOLIZE +#endif +#endif // !defined(HAVE_SYMBOLIZE) +#endif // !defined(GLOG_NO_SYMBOLIZE_DETECTION) + +#ifndef ARRAYSIZE +// There is a better way, but this is good enough for our purpose. +# define ARRAYSIZE(a) (sizeof(a) / sizeof(*(a))) +#endif + +_START_GOOGLE_NAMESPACE_ + +namespace glog_internal_namespace_ { + +#ifdef HAVE___ATTRIBUTE__ +# define ATTRIBUTE_NOINLINE __attribute__ ((noinline)) +# define HAVE_ATTRIBUTE_NOINLINE +#elif defined(GLOG_OS_WINDOWS) +# define ATTRIBUTE_NOINLINE __declspec(noinline) +# define HAVE_ATTRIBUTE_NOINLINE +#else +# define ATTRIBUTE_NOINLINE +#endif + +const char* ProgramInvocationShortName(); + +int64 CycleClock_Now(); + +int64 UsecToCycles(int64 usec); +WallTime WallTime_Now(); + +int32 GetMainThreadPid(); +bool PidHasChanged(); + +pid_t GetTID(); + +const std::string& MyUserName(); + +// Get the part of filepath after the last path separator. +// (Doesn't modify filepath, contrary to basename() in libgen.h.) +const char* const_basename(const char* filepath); + +// Wrapper of __sync_val_compare_and_swap. If the GCC extension isn't +// defined, we try the CPU specific logics (we only support x86 and +// x86_64 for now) first, then use a naive implementation, which has a +// race condition. +template +inline T sync_val_compare_and_swap(T* ptr, T oldval, T newval) { +#if defined(HAVE___SYNC_VAL_COMPARE_AND_SWAP) + return __sync_val_compare_and_swap(ptr, oldval, newval); +#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) + T ret; + __asm__ __volatile__("lock; cmpxchg %1, (%2);" + :"=a"(ret) + // GCC may produces %sil or %dil for + // constraint "r", but some of apple's gas + // dosn't know the 8 bit registers. + // We use "q" to avoid these registers. + :"q"(newval), "q"(ptr), "a"(oldval) + :"memory", "cc"); + return ret; +#else + T ret = *ptr; + if (ret == oldval) { + *ptr = newval; + } + return ret; +#endif +} + +void DumpStackTraceToString(std::string* stacktrace); + +struct CrashReason { + CrashReason() : filename(0), line_number(0), message(0), depth(0) {} + + const char* filename; + int line_number; + const char* message; + + // We'll also store a bit of stack trace context at the time of crash as + // it may not be available later on. + void* stack[32]; + int depth; +}; + +void SetCrashReason(const CrashReason* r); + +void InitGoogleLoggingUtilities(const char* argv0); +void ShutdownGoogleLoggingUtilities(); + +} // namespace glog_internal_namespace_ + +_END_GOOGLE_NAMESPACE_ + +using namespace GOOGLE_NAMESPACE::glog_internal_namespace_; + +#endif // UTILITIES_H__ diff --git a/third_party/glog/src/utilities_unittest.cc b/third_party/glog/src/utilities_unittest.cc new file mode 100644 index 0000000..93b1acd --- /dev/null +++ b/third_party/glog/src/utilities_unittest.cc @@ -0,0 +1,58 @@ +// Copyright (c) 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Shinichiro Hamaji +#include "utilities.h" +#include "googletest.h" +#include + +#ifdef HAVE_LIB_GFLAGS +#include +using namespace GFLAGS_NAMESPACE; +#endif + +using namespace GOOGLE_NAMESPACE; + +TEST(utilities, sync_val_compare_and_swap) { + bool now_entering = false; + EXPECT_FALSE(sync_val_compare_and_swap(&now_entering, false, true)); + EXPECT_TRUE(sync_val_compare_and_swap(&now_entering, false, true)); + EXPECT_TRUE(sync_val_compare_and_swap(&now_entering, false, true)); +} + +TEST(utilities, InitGoogleLoggingDeathTest) { + ASSERT_DEATH(InitGoogleLogging("foobar"), ""); +} + +int main(int argc, char **argv) { + InitGoogleLogging(argv[0]); + InitGoogleTest(&argc, argv); + + CHECK_EQ(RUN_ALL_TESTS(), 0); +} diff --git a/third_party/glog/src/vlog_is_on.cc b/third_party/glog/src/vlog_is_on.cc new file mode 100644 index 0000000..e478a36 --- /dev/null +++ b/third_party/glog/src/vlog_is_on.cc @@ -0,0 +1,293 @@ +// Copyright (c) 1999, 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Ray Sidney and many others +// +// Broken out from logging.cc by Soren Lassen +// logging_unittest.cc covers the functionality herein + +#include "utilities.h" + +#include +#include +#include +#include +#include +#include "base/commandlineflags.h" +#include +#include +#include "base/googleinit.h" + +// glog doesn't have annotation +#define ANNOTATE_BENIGN_RACE(address, description) + +using std::string; + +GLOG_DEFINE_int32(v, 0, "Show all VLOG(m) messages for m <= this." +" Overridable by --vmodule."); + +GLOG_DEFINE_string(vmodule, "", "per-module verbose level." +" Argument is a comma-separated list of =." +" is a glob pattern, matched against the filename base" +" (that is, name ignoring .cc/.h./-inl.h)." +" overrides any value given by --v."); + +_START_GOOGLE_NAMESPACE_ + +namespace glog_internal_namespace_ { + +// Used by logging_unittests.cc so can't make it static here. +GLOG_EXPORT bool SafeFNMatch_(const char* pattern, size_t patt_len, + const char* str, size_t str_len); + +// Implementation of fnmatch that does not need 0-termination +// of arguments and does not allocate any memory, +// but we only support "*" and "?" wildcards, not the "[...]" patterns. +// It's not a static function for the unittest. +GLOG_EXPORT bool SafeFNMatch_(const char* pattern, size_t patt_len, + const char* str, size_t str_len) { + size_t p = 0; + size_t s = 0; + while (1) { + if (p == patt_len && s == str_len) return true; + if (p == patt_len) return false; + if (s == str_len) return p+1 == patt_len && pattern[p] == '*'; + if (pattern[p] == str[s] || pattern[p] == '?') { + p += 1; + s += 1; + continue; + } + if (pattern[p] == '*') { + if (p+1 == patt_len) return true; + do { + if (SafeFNMatch_(pattern+(p+1), patt_len-(p+1), str+s, str_len-s)) { + return true; + } + s += 1; + } while (s != str_len); + return false; + } + return false; + } +} + +} // namespace glog_internal_namespace_ + +using glog_internal_namespace_::SafeFNMatch_; + +// List of per-module log levels from FLAGS_vmodule. +// Once created each element is never deleted/modified +// except for the vlog_level: other threads will read VModuleInfo blobs +// w/o locks and we'll store pointers to vlog_level at VLOG locations +// that will never go away. +// We can't use an STL struct here as we wouldn't know +// when it's safe to delete/update it: other threads need to use it w/o locks. +struct VModuleInfo { + string module_pattern; + mutable int32 vlog_level; // Conceptually this is an AtomicWord, but it's + // too much work to use AtomicWord type here + // w/o much actual benefit. + const VModuleInfo* next; +}; + +// This protects the following global variables. +static Mutex vmodule_lock; +// Pointer to head of the VModuleInfo list. +// It's a map from module pattern to logging level for those module(s). +static VModuleInfo* vmodule_list = 0; +static SiteFlag* cached_site_list = 0; + +// Boolean initialization flag. +static bool inited_vmodule = false; + +// L >= vmodule_lock. +static void VLOG2Initializer() { + vmodule_lock.AssertHeld(); + // Can now parse --vmodule flag and initialize mapping of module-specific + // logging levels. + inited_vmodule = false; + const char* vmodule = FLAGS_vmodule.c_str(); + const char* sep; + VModuleInfo* head = NULL; + VModuleInfo* tail = NULL; + while ((sep = strchr(vmodule, '=')) != NULL) { + string pattern(vmodule, static_cast(sep - vmodule)); + int module_level; + if (sscanf(sep, "=%d", &module_level) == 1) { + VModuleInfo* info = new VModuleInfo; + info->module_pattern = pattern; + info->vlog_level = module_level; + if (head) { + tail->next = info; + } else { + head = info; + } + tail = info; + } + // Skip past this entry + vmodule = strchr(sep, ','); + if (vmodule == NULL) break; + vmodule++; // Skip past "," + } + if (head) { // Put them into the list at the head: + tail->next = vmodule_list; + vmodule_list = head; + } + inited_vmodule = true; +} + +// This can be called very early, so we use SpinLock and RAW_VLOG here. +int SetVLOGLevel(const char* module_pattern, int log_level) { + int result = FLAGS_v; + size_t const pattern_len = strlen(module_pattern); + bool found = false; + { + MutexLock l(&vmodule_lock); // protect whole read-modify-write + for (const VModuleInfo* info = vmodule_list; + info != NULL; info = info->next) { + if (info->module_pattern == module_pattern) { + if (!found) { + result = info->vlog_level; + found = true; + } + info->vlog_level = log_level; + } else if (!found && + SafeFNMatch_(info->module_pattern.c_str(), + info->module_pattern.size(), + module_pattern, pattern_len)) { + result = info->vlog_level; + found = true; + } + } + if (!found) { + VModuleInfo* info = new VModuleInfo; + info->module_pattern = module_pattern; + info->vlog_level = log_level; + info->next = vmodule_list; + vmodule_list = info; + + SiteFlag** item_ptr = &cached_site_list; + SiteFlag* item = cached_site_list; + + // We traverse the list fully because the pattern can match several items + // from the list. + while (item) { + if (SafeFNMatch_(module_pattern, pattern_len, item->base_name, + item->base_len)) { + // Redirect the cached value to its module override. + item->level = &info->vlog_level; + *item_ptr = item->next; // Remove the item from the list. + } else { + item_ptr = &item->next; + } + item = *item_ptr; + } + } + } + RAW_VLOG(1, "Set VLOG level for \"%s\" to %d", module_pattern, log_level); + return result; +} + +// NOTE: Individual VLOG statements cache the integer log level pointers. +// NOTE: This function must not allocate memory or require any locks. +bool InitVLOG3__(SiteFlag* site_flag, int32* level_default, + const char* fname, int32 verbose_level) { + MutexLock l(&vmodule_lock); + bool read_vmodule_flag = inited_vmodule; + if (!read_vmodule_flag) { + VLOG2Initializer(); + } + + // protect the errno global in case someone writes: + // VLOG(..) << "The last error was " << strerror(errno) + int old_errno = errno; + + // site_default normally points to FLAGS_v + int32* site_flag_value = level_default; + + // Get basename for file + const char* base = strrchr(fname, '/'); + +#ifdef _WIN32 + if (!base) { + base = strrchr(fname, '\\'); + } +#endif + + base = base ? (base+1) : fname; + const char* base_end = strchr(base, '.'); + size_t base_length = base_end ? size_t(base_end - base) : strlen(base); + + // Trim out trailing "-inl" if any + if (base_length >= 4 && (memcmp(base+base_length-4, "-inl", 4) == 0)) { + base_length -= 4; + } + + // TODO: Trim out _unittest suffix? Perhaps it is better to have + // the extra control and just leave it there. + + // find target in vector of modules, replace site_flag_value with + // a module-specific verbose level, if any. + for (const VModuleInfo* info = vmodule_list; + info != NULL; info = info->next) { + if (SafeFNMatch_(info->module_pattern.c_str(), info->module_pattern.size(), + base, base_length)) { + site_flag_value = &info->vlog_level; + // value at info->vlog_level is now what controls + // the VLOG at the caller site forever + break; + } + } + + // Cache the vlog value pointer if --vmodule flag has been parsed. + ANNOTATE_BENIGN_RACE(site_flag, + "*site_flag may be written by several threads," + " but the value will be the same"); + if (read_vmodule_flag) { + site_flag->level = site_flag_value; + // If VLOG flag has been cached to the default site pointer, + // we want to add to the cached list in order to invalidate in case + // SetVModule is called afterwards with new modules. + // The performance penalty here is neglible, because InitVLOG3__ is called + // once per site. + if (site_flag_value == level_default && !site_flag->base_name) { + site_flag->base_name = base; + site_flag->base_len = base_length; + site_flag->next = cached_site_list; + cached_site_list = site_flag; + } + } + + // restore the errno in case something recoverable went wrong during + // the initialization of the VLOG mechanism (see above note "protect the..") + errno = old_errno; + return *site_flag_value >= verbose_level; +} + +_END_GOOGLE_NAMESPACE_ diff --git a/third_party/glog/src/windows/dirent.h b/third_party/glog/src/windows/dirent.h new file mode 100644 index 0000000..12cf00a --- /dev/null +++ b/third_party/glog/src/windows/dirent.h @@ -0,0 +1,1159 @@ +/* + * Dirent interface for Microsoft Visual Studio + * + * Copyright (C) 1998-2019 Toni Ronkko + * This file is part of dirent. Dirent may be freely distributed + * under the MIT license. For all details and documentation, see + * https://github.com/tronkko/dirent + */ +#ifndef DIRENT_H +#define DIRENT_H + +/* Hide warnings about unreferenced local functions */ +#if defined(__clang__) +# pragma clang diagnostic ignored "-Wunused-function" +#elif defined(_MSC_VER) +# pragma warning(disable:4505) +#elif defined(__GNUC__) +# pragma GCC diagnostic ignored "-Wunused-function" +#endif + +/* + * Include windows.h without Windows Sockets 1.1 to prevent conflicts with + * Windows Sockets 2.0. + */ +#ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +#endif +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +/* Indicates that d_type field is available in dirent structure */ +#define _DIRENT_HAVE_D_TYPE + +/* Indicates that d_namlen field is available in dirent structure */ +#define _DIRENT_HAVE_D_NAMLEN + +/* Entries missing from MSVC 6.0 */ +#if !defined(FILE_ATTRIBUTE_DEVICE) +# define FILE_ATTRIBUTE_DEVICE 0x40 +#endif + +/* File type and permission flags for stat(), general mask */ +#if !defined(S_IFMT) +# define S_IFMT _S_IFMT +#endif + +/* Directory bit */ +#if !defined(S_IFDIR) +# define S_IFDIR _S_IFDIR +#endif + +/* Character device bit */ +#if !defined(S_IFCHR) +# define S_IFCHR _S_IFCHR +#endif + +/* Pipe bit */ +#if !defined(S_IFFIFO) +# define S_IFFIFO _S_IFFIFO +#endif + +/* Regular file bit */ +#if !defined(S_IFREG) +# define S_IFREG _S_IFREG +#endif + +/* Read permission */ +#if !defined(S_IREAD) +# define S_IREAD _S_IREAD +#endif + +/* Write permission */ +#if !defined(S_IWRITE) +# define S_IWRITE _S_IWRITE +#endif + +/* Execute permission */ +#if !defined(S_IEXEC) +# define S_IEXEC _S_IEXEC +#endif + +/* Pipe */ +#if !defined(S_IFIFO) +# define S_IFIFO _S_IFIFO +#endif + +/* Block device */ +#if !defined(S_IFBLK) +# define S_IFBLK 0 +#endif + +/* Link */ +#if !defined(S_IFLNK) +# define S_IFLNK 0 +#endif + +/* Socket */ +#if !defined(S_IFSOCK) +# define S_IFSOCK 0 +#endif + +/* Read user permission */ +#if !defined(S_IRUSR) +# define S_IRUSR S_IREAD +#endif + +/* Write user permission */ +#if !defined(S_IWUSR) +# define S_IWUSR S_IWRITE +#endif + +/* Execute user permission */ +#if !defined(S_IXUSR) +# define S_IXUSR 0 +#endif + +/* Read group permission */ +#if !defined(S_IRGRP) +# define S_IRGRP 0 +#endif + +/* Write group permission */ +#if !defined(S_IWGRP) +# define S_IWGRP 0 +#endif + +/* Execute group permission */ +#if !defined(S_IXGRP) +# define S_IXGRP 0 +#endif + +/* Read others permission */ +#if !defined(S_IROTH) +# define S_IROTH 0 +#endif + +/* Write others permission */ +#if !defined(S_IWOTH) +# define S_IWOTH 0 +#endif + +/* Execute others permission */ +#if !defined(S_IXOTH) +# define S_IXOTH 0 +#endif + +/* Maximum length of file name */ +#if !defined(PATH_MAX) +# define PATH_MAX MAX_PATH +#endif +#if !defined(FILENAME_MAX) +# define FILENAME_MAX MAX_PATH +#endif +#if !defined(NAME_MAX) +# define NAME_MAX FILENAME_MAX +#endif + +/* File type flags for d_type */ +#define DT_UNKNOWN 0 +#define DT_REG S_IFREG +#define DT_DIR S_IFDIR +#define DT_FIFO S_IFIFO +#define DT_SOCK S_IFSOCK +#define DT_CHR S_IFCHR +#define DT_BLK S_IFBLK +#define DT_LNK S_IFLNK + +/* Macros for converting between st_mode and d_type */ +#define IFTODT(mode) ((mode) & S_IFMT) +#define DTTOIF(type) (type) + +/* + * File type macros. Note that block devices, sockets and links cannot be + * distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are + * only defined for compatibility. These macros should always return false + * on Windows. + */ +#if !defined(S_ISFIFO) +# define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO) +#endif +#if !defined(S_ISDIR) +# define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) +#endif +#if !defined(S_ISREG) +# define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) +#endif +#if !defined(S_ISLNK) +# define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK) +#endif +#if !defined(S_ISSOCK) +# define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK) +#endif +#if !defined(S_ISCHR) +# define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR) +#endif +#if !defined(S_ISBLK) +# define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK) +#endif + +/* Return the exact length of the file name without zero terminator */ +#define _D_EXACT_NAMLEN(p) ((p)->d_namlen) + +/* Return the maximum size of a file name */ +#define _D_ALLOC_NAMLEN(p) ((PATH_MAX)+1) + + +#ifdef __cplusplus +extern "C" { +#endif + + +/* Wide-character version */ +struct _wdirent { + /* Always zero */ + long d_ino; + + /* File position within stream */ + long d_off; + + /* Structure size */ + unsigned short d_reclen; + + /* Length of name without \0 */ + size_t d_namlen; + + /* File type */ + int d_type; + + /* File name */ + wchar_t d_name[PATH_MAX+1]; +}; +typedef struct _wdirent _wdirent; + +struct _WDIR { + /* Current directory entry */ + struct _wdirent ent; + + /* Private file data */ + WIN32_FIND_DATAW data; + + /* True if data is valid */ + int cached; + + /* Win32 search handle */ + HANDLE handle; + + /* Initial directory name */ + wchar_t *patt; +}; +typedef struct _WDIR _WDIR; + +/* Multi-byte character version */ +struct dirent { + /* Always zero */ + long d_ino; + + /* File position within stream */ + long d_off; + + /* Structure size */ + unsigned short d_reclen; + + /* Length of name without \0 */ + size_t d_namlen; + + /* File type */ + int d_type; + + /* File name */ + char d_name[PATH_MAX+1]; +}; +typedef struct dirent dirent; + +struct DIR { + struct dirent ent; + struct _WDIR *wdirp; +}; +typedef struct DIR DIR; + + +/* Dirent functions */ +static DIR *opendir (const char *dirname); +static _WDIR *_wopendir (const wchar_t *dirname); + +static struct dirent *readdir (DIR *dirp); +static struct _wdirent *_wreaddir (_WDIR *dirp); + +static int readdir_r( + DIR *dirp, struct dirent *entry, struct dirent **result); +static int _wreaddir_r( + _WDIR *dirp, struct _wdirent *entry, struct _wdirent **result); + +static int closedir (DIR *dirp); +static int _wclosedir (_WDIR *dirp); + +static void rewinddir (DIR* dirp); +static void _wrewinddir (_WDIR* dirp); + +static int scandir (const char *dirname, struct dirent ***namelist, + int (*filter)(const struct dirent*), + int (*compare)(const struct dirent**, const struct dirent**)); + +static int alphasort (const struct dirent **a, const struct dirent **b); + +static int versionsort (const struct dirent **a, const struct dirent **b); + + +/* For compatibility with Symbian */ +#define wdirent _wdirent +#define WDIR _WDIR +#define wopendir _wopendir +#define wreaddir _wreaddir +#define wclosedir _wclosedir +#define wrewinddir _wrewinddir + + +/* Internal utility functions */ +static WIN32_FIND_DATAW *dirent_first (_WDIR *dirp); +static WIN32_FIND_DATAW *dirent_next (_WDIR *dirp); + +static int dirent_mbstowcs_s( + size_t *pReturnValue, + wchar_t *wcstr, + size_t sizeInWords, + const char *mbstr, + size_t count); + +static int dirent_wcstombs_s( + size_t *pReturnValue, + char *mbstr, + size_t sizeInBytes, + const wchar_t *wcstr, + size_t count); + +static void dirent_set_errno (int error); + + +/* + * Open directory stream DIRNAME for read and return a pointer to the + * internal working area that is used to retrieve individual directory + * entries. + */ +static _WDIR* +_wopendir( + const wchar_t *dirname) +{ + _WDIR *dirp; + DWORD n; + wchar_t *p; + + /* Must have directory name */ + if (dirname == NULL || dirname[0] == '\0') { + dirent_set_errno (ENOENT); + return NULL; + } + + /* Allocate new _WDIR structure */ + dirp = (_WDIR*) malloc (sizeof (struct _WDIR)); + if (!dirp) { + return NULL; + } + + /* Reset _WDIR structure */ + dirp->handle = INVALID_HANDLE_VALUE; + dirp->patt = NULL; + dirp->cached = 0; + + /* + * Compute the length of full path plus zero terminator + * + * Note that on WinRT there's no way to convert relative paths + * into absolute paths, so just assume it is an absolute path. + */ +#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) + /* Desktop */ + n = GetFullPathNameW (dirname, 0, NULL, NULL); +#else + /* WinRT */ + n = wcslen (dirname); +#endif + + /* Allocate room for absolute directory name and search pattern */ + dirp->patt = (wchar_t*) malloc (sizeof (wchar_t) * n + 16); + if (dirp->patt == NULL) { + goto exit_closedir; + } + + /* + * Convert relative directory name to an absolute one. This + * allows rewinddir() to function correctly even when current + * working directory is changed between opendir() and rewinddir(). + * + * Note that on WinRT there's no way to convert relative paths + * into absolute paths, so just assume it is an absolute path. + */ +#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) + /* Desktop */ + n = GetFullPathNameW (dirname, n, dirp->patt, NULL); + if (n <= 0) { + goto exit_closedir; + } +#else + /* WinRT */ + wcsncpy_s (dirp->patt, n+1, dirname, n); +#endif + + /* Append search pattern \* to the directory name */ + p = dirp->patt + n; + switch (p[-1]) { + case '\\': + case '/': + case ':': + /* Directory ends in path separator, e.g. c:\temp\ */ + /*NOP*/; + break; + + default: + /* Directory name doesn't end in path separator */ + *p++ = '\\'; + } + *p++ = '*'; + *p = '\0'; + + /* Open directory stream and retrieve the first entry */ + if (!dirent_first (dirp)) { + goto exit_closedir; + } + + /* Success */ + return dirp; + + /* Failure */ +exit_closedir: + _wclosedir (dirp); + return NULL; +} + +/* + * Read next directory entry. + * + * Returns pointer to static directory entry which may be overwritten by + * subsequent calls to _wreaddir(). + */ +static struct _wdirent* +_wreaddir( + _WDIR *dirp) +{ + struct _wdirent *entry; + + /* + * Read directory entry to buffer. We can safely ignore the return value + * as entry will be set to NULL in case of error. + */ + (void) _wreaddir_r (dirp, &dirp->ent, &entry); + + /* Return pointer to statically allocated directory entry */ + return entry; +} + +/* + * Read next directory entry. + * + * Returns zero on success. If end of directory stream is reached, then sets + * result to NULL and returns zero. + */ +static int +_wreaddir_r( + _WDIR *dirp, + struct _wdirent *entry, + struct _wdirent **result) +{ + WIN32_FIND_DATAW *datap; + + /* Read next directory entry */ + datap = dirent_next (dirp); + if (datap) { + size_t n; + DWORD attr; + + /* + * Copy file name as wide-character string. If the file name is too + * long to fit in to the destination buffer, then truncate file name + * to PATH_MAX characters and zero-terminate the buffer. + */ + n = 0; + while (n < PATH_MAX && datap->cFileName[n] != 0) { + entry->d_name[n] = datap->cFileName[n]; + n++; + } + entry->d_name[n] = 0; + + /* Length of file name excluding zero terminator */ + entry->d_namlen = n; + + /* File type */ + attr = datap->dwFileAttributes; + if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) { + entry->d_type = DT_CHR; + } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { + entry->d_type = DT_DIR; + } else { + entry->d_type = DT_REG; + } + + /* Reset dummy fields */ + entry->d_ino = 0; + entry->d_off = 0; + entry->d_reclen = sizeof (struct _wdirent); + + /* Set result address */ + *result = entry; + + } else { + + /* Return NULL to indicate end of directory */ + *result = NULL; + + } + + return /*OK*/0; +} + +/* + * Close directory stream opened by opendir() function. This invalidates the + * DIR structure as well as any directory entry read previously by + * _wreaddir(). + */ +static int +_wclosedir( + _WDIR *dirp) +{ + int ok; + if (dirp) { + + /* Release search handle */ + if (dirp->handle != INVALID_HANDLE_VALUE) { + FindClose (dirp->handle); + } + + /* Release search pattern */ + free (dirp->patt); + + /* Release directory structure */ + free (dirp); + ok = /*success*/0; + + } else { + + /* Invalid directory stream */ + dirent_set_errno (EBADF); + ok = /*failure*/-1; + + } + return ok; +} + +/* + * Rewind directory stream such that _wreaddir() returns the very first + * file name again. + */ +static void +_wrewinddir( + _WDIR* dirp) +{ + if (dirp) { + /* Release existing search handle */ + if (dirp->handle != INVALID_HANDLE_VALUE) { + FindClose (dirp->handle); + } + + /* Open new search handle */ + dirent_first (dirp); + } +} + +/* Get first directory entry (internal) */ +static WIN32_FIND_DATAW* +dirent_first( + _WDIR *dirp) +{ + WIN32_FIND_DATAW *datap; + DWORD error; + + /* Open directory and retrieve the first entry */ + dirp->handle = FindFirstFileExW( + dirp->patt, FindExInfoStandard, &dirp->data, + FindExSearchNameMatch, NULL, 0); + if (dirp->handle != INVALID_HANDLE_VALUE) { + + /* a directory entry is now waiting in memory */ + datap = &dirp->data; + dirp->cached = 1; + + } else { + + /* Failed to open directory: no directory entry in memory */ + dirp->cached = 0; + datap = NULL; + + /* Set error code */ + error = GetLastError (); + switch (error) { + case ERROR_ACCESS_DENIED: + /* No read access to directory */ + dirent_set_errno (EACCES); + break; + + case ERROR_DIRECTORY: + /* Directory name is invalid */ + dirent_set_errno (ENOTDIR); + break; + + case ERROR_PATH_NOT_FOUND: + default: + /* Cannot find the file */ + dirent_set_errno (ENOENT); + } + + } + return datap; +} + +/* + * Get next directory entry (internal). + * + * Returns + */ +static WIN32_FIND_DATAW* +dirent_next( + _WDIR *dirp) +{ + WIN32_FIND_DATAW *p; + + /* Get next directory entry */ + if (dirp->cached != 0) { + + /* A valid directory entry already in memory */ + p = &dirp->data; + dirp->cached = 0; + + } else if (dirp->handle != INVALID_HANDLE_VALUE) { + + /* Get the next directory entry from stream */ + if (FindNextFileW (dirp->handle, &dirp->data) != FALSE) { + /* Got a file */ + p = &dirp->data; + } else { + /* The very last entry has been processed or an error occurred */ + FindClose (dirp->handle); + dirp->handle = INVALID_HANDLE_VALUE; + p = NULL; + } + + } else { + + /* End of directory stream reached */ + p = NULL; + + } + + return p; +} + +/* + * Open directory stream using plain old C-string. + */ +static DIR* +opendir( + const char *dirname) +{ + struct DIR *dirp; + + /* Must have directory name */ + if (dirname == NULL || dirname[0] == '\0') { + dirent_set_errno (ENOENT); + return NULL; + } + + /* Allocate memory for DIR structure */ + dirp = (DIR*) malloc (sizeof (struct DIR)); + if (!dirp) { + return NULL; + } + { + int error; + wchar_t wname[PATH_MAX + 1]; + size_t n; + + /* Convert directory name to wide-character string */ + error = dirent_mbstowcs_s( + &n, wname, PATH_MAX + 1, dirname, PATH_MAX + 1); + if (error) { + /* + * Cannot convert file name to wide-character string. This + * occurs if the string contains invalid multi-byte sequences or + * the output buffer is too small to contain the resulting + * string. + */ + goto exit_free; + } + + + /* Open directory stream using wide-character name */ + dirp->wdirp = _wopendir (wname); + if (!dirp->wdirp) { + goto exit_free; + } + + } + + /* Success */ + return dirp; + + /* Failure */ +exit_free: + free (dirp); + return NULL; +} + +/* + * Read next directory entry. + */ +static struct dirent* +readdir( + DIR *dirp) +{ + struct dirent *entry; + + /* + * Read directory entry to buffer. We can safely ignore the return value + * as entry will be set to NULL in case of error. + */ + (void) readdir_r (dirp, &dirp->ent, &entry); + + /* Return pointer to statically allocated directory entry */ + return entry; +} + +/* + * Read next directory entry into called-allocated buffer. + * + * Returns zero on success. If the end of directory stream is reached, then + * sets result to NULL and returns zero. + */ +static int +readdir_r( + DIR *dirp, + struct dirent *entry, + struct dirent **result) +{ + WIN32_FIND_DATAW *datap; + + /* Read next directory entry */ + datap = dirent_next (dirp->wdirp); + if (datap) { + size_t n; + int error; + + /* Attempt to convert file name to multi-byte string */ + error = dirent_wcstombs_s( + &n, entry->d_name, PATH_MAX + 1, datap->cFileName, PATH_MAX + 1); + + /* + * If the file name cannot be represented by a multi-byte string, + * then attempt to use old 8+3 file name. This allows traditional + * Unix-code to access some file names despite of unicode + * characters, although file names may seem unfamiliar to the user. + * + * Be ware that the code below cannot come up with a short file + * name unless the file system provides one. At least + * VirtualBox shared folders fail to do this. + */ + if (error && datap->cAlternateFileName[0] != '\0') { + error = dirent_wcstombs_s( + &n, entry->d_name, PATH_MAX + 1, + datap->cAlternateFileName, PATH_MAX + 1); + } + + if (!error) { + DWORD attr; + + /* Length of file name excluding zero terminator */ + entry->d_namlen = n - 1; + + /* File attributes */ + attr = datap->dwFileAttributes; + if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) { + entry->d_type = DT_CHR; + } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { + entry->d_type = DT_DIR; + } else { + entry->d_type = DT_REG; + } + + /* Reset dummy fields */ + entry->d_ino = 0; + entry->d_off = 0; + entry->d_reclen = sizeof (struct dirent); + + } else { + + /* + * Cannot convert file name to multi-byte string so construct + * an erroneous directory entry and return that. Note that + * we cannot return NULL as that would stop the processing + * of directory entries completely. + */ + entry->d_name[0] = '?'; + entry->d_name[1] = '\0'; + entry->d_namlen = 1; + entry->d_type = DT_UNKNOWN; + entry->d_ino = 0; + entry->d_off = -1; + entry->d_reclen = 0; + + } + + /* Return pointer to directory entry */ + *result = entry; + + } else { + + /* No more directory entries */ + *result = NULL; + + } + + return /*OK*/0; +} + +/* + * Close directory stream. + */ +static int +closedir( + DIR *dirp) +{ + int ok; + if (dirp) { + + /* Close wide-character directory stream */ + ok = _wclosedir (dirp->wdirp); + dirp->wdirp = NULL; + + /* Release multi-byte character version */ + free (dirp); + + } else { + + /* Invalid directory stream */ + dirent_set_errno (EBADF); + ok = /*failure*/-1; + + } + return ok; +} + +/* + * Rewind directory stream to beginning. + */ +static void +rewinddir( + DIR* dirp) +{ + /* Rewind wide-character string directory stream */ + _wrewinddir (dirp->wdirp); +} + +/* + * Scan directory for entries. + */ +static int +scandir( + const char *dirname, + struct dirent ***namelist, + int (*filter)(const struct dirent*), + int (*compare)(const struct dirent**, const struct dirent**)) +{ + struct dirent **files = NULL; + size_t size = 0; + size_t allocated = 0; + const size_t init_size = 1; + DIR *dir = NULL; + struct dirent *entry; + struct dirent *tmp = NULL; + size_t i; + int result = 0; + + /* Open directory stream */ + dir = opendir (dirname); + if (dir) { + + /* Read directory entries to memory */ + while (1) { + + /* Enlarge pointer table to make room for another pointer */ + if (size >= allocated) { + void *p; + size_t num_entries; + + /* Compute number of entries in the enlarged pointer table */ + if (size < init_size) { + /* Allocate initial pointer table */ + num_entries = init_size; + } else { + /* Double the size */ + num_entries = size * 2; + } + + /* Allocate first pointer table or enlarge existing table */ + p = realloc (files, sizeof (void*) * num_entries); + if (p != NULL) { + /* Got the memory */ + files = (dirent**) p; + allocated = num_entries; + } else { + /* Out of memory */ + result = -1; + break; + } + + } + + /* Allocate room for temporary directory entry */ + if (tmp == NULL) { + tmp = (struct dirent*) malloc (sizeof (struct dirent)); + if (tmp == NULL) { + /* Cannot allocate temporary directory entry */ + result = -1; + break; + } + } + + /* Read directory entry to temporary area */ + if (readdir_r (dir, tmp, &entry) == /*OK*/0) { + + /* Did we get an entry? */ + if (entry != NULL) { + int pass; + + /* Determine whether to include the entry in result */ + if (filter) { + /* Let the filter function decide */ + pass = filter (tmp); + } else { + /* No filter function, include everything */ + pass = 1; + } + + if (pass) { + /* Store the temporary entry to pointer table */ + files[size++] = tmp; + tmp = NULL; + + /* Keep up with the number of files */ + result++; + } + + } else { + + /* + * End of directory stream reached => sort entries and + * exit. + */ + qsort (files, size, sizeof (void*), + (int (*) (const void*, const void*)) compare); + break; + + } + + } else { + /* Error reading directory entry */ + result = /*Error*/ -1; + break; + } + + } + + } else { + /* Cannot open directory */ + result = /*Error*/ -1; + } + + /* Release temporary directory entry */ + free (tmp); + + /* Release allocated memory on error */ + if (result < 0) { + for (i = 0; i < size; i++) { + free (files[i]); + } + free (files); + files = NULL; + } + + /* Close directory stream */ + if (dir) { + closedir (dir); + } + + /* Pass pointer table to caller */ + if (namelist) { + *namelist = files; + } + return result; +} + +/* Alphabetical sorting */ +static int +alphasort( + const struct dirent **a, const struct dirent **b) +{ + return strcoll ((*a)->d_name, (*b)->d_name); +} + +/* Sort versions */ +static int +versionsort( + const struct dirent **a, const struct dirent **b) +{ + /* FIXME: implement strverscmp and use that */ + return alphasort (a, b); +} + +/* Convert multi-byte string to wide character string */ +static int +dirent_mbstowcs_s( + size_t *pReturnValue, + wchar_t *wcstr, + size_t sizeInWords, + const char *mbstr, + size_t count) +{ + int error; + +#if defined(_MSC_VER) && _MSC_VER >= 1400 + + /* Microsoft Visual Studio 2005 or later */ + error = mbstowcs_s (pReturnValue, wcstr, sizeInWords, mbstr, count); + +#else + + /* Older Visual Studio or non-Microsoft compiler */ + size_t n; + + /* Convert to wide-character string (or count characters) */ + n = mbstowcs (wcstr, mbstr, sizeInWords); + if (!wcstr || n < count) { + + /* Zero-terminate output buffer */ + if (wcstr && sizeInWords) { + if (n >= sizeInWords) { + n = sizeInWords - 1; + } + wcstr[n] = 0; + } + + /* Length of resulting multi-byte string WITH zero terminator */ + if (pReturnValue) { + *pReturnValue = n + 1; + } + + /* Success */ + error = 0; + + } else { + + /* Could not convert string */ + error = 1; + + } + +#endif + return error; +} + +/* Convert wide-character string to multi-byte string */ +static int +dirent_wcstombs_s( + size_t *pReturnValue, + char *mbstr, + size_t sizeInBytes, /* max size of mbstr */ + const wchar_t *wcstr, + size_t count) +{ + int error; + +#if defined(_MSC_VER) && _MSC_VER >= 1400 + + /* Microsoft Visual Studio 2005 or later */ + error = wcstombs_s (pReturnValue, mbstr, sizeInBytes, wcstr, count); + +#else + + /* Older Visual Studio or non-Microsoft compiler */ + size_t n; + + /* Convert to multi-byte string (or count the number of bytes needed) */ + n = wcstombs (mbstr, wcstr, sizeInBytes); + if (!mbstr || n < count) { + + /* Zero-terminate output buffer */ + if (mbstr && sizeInBytes) { + if (n >= sizeInBytes) { + n = sizeInBytes - 1; + } + mbstr[n] = '\0'; + } + + /* Length of resulting multi-bytes string WITH zero-terminator */ + if (pReturnValue) { + *pReturnValue = n + 1; + } + + /* Success */ + error = 0; + + } else { + + /* Cannot convert string */ + error = 1; + + } + +#endif + return error; +} + +/* Set errno variable */ +static void +dirent_set_errno( + int error) +{ +#if defined(_MSC_VER) && _MSC_VER >= 1400 + + /* Microsoft Visual Studio 2005 and later */ + _set_errno (error); + +#else + + /* Non-Microsoft compiler or older Microsoft compiler */ + errno = error; + +#endif +} + + +#ifdef __cplusplus +} +#endif +#endif /*DIRENT_H*/ diff --git a/third_party/glog/src/windows/port.cc b/third_party/glog/src/windows/port.cc new file mode 100755 index 0000000..f0022e7 --- /dev/null +++ b/third_party/glog/src/windows/port.cc @@ -0,0 +1,71 @@ +/* Copyright (c) 2008, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * --- + * Author: Craig Silverstein + * Copied from google-perftools and modified by Shinichiro Hamaji + */ + +#ifndef _WIN32 +# error You should only be including windows/port.cc in a windows environment! +#endif + +#include "config.h" +#include // for va_list, va_start, va_end +#include "port.h" + +// These call the windows _vsnprintf, but always NUL-terminate. +int safe_vsnprintf(char *str, size_t size, const char *format, va_list ap) { + if (size == 0) // not even room for a \0? + return -1; // not what C99 says to do, but what windows does + str[size-1] = '\0'; + return _vsnprintf(str, size-1, format, ap); +} + +#ifndef HAVE_LOCALTIME_R +struct tm* localtime_r(const time_t* timep, struct tm* result) { + localtime_s(result, timep); + return result; +} +#endif // not HAVE_LOCALTIME_R +#ifndef HAVE_GMTIME_R +struct tm* gmtime_r(const time_t* timep, struct tm* result) { + gmtime_s(result, timep); + return result; +} +#endif // not HAVE_GMTIME_R +#ifndef HAVE_SNPRINTF +int snprintf(char *str, size_t size, const char *format, ...) { + va_list ap; + va_start(ap, format); + const int r = vsnprintf(str, size, format, ap); + va_end(ap); + return r; +} +#endif diff --git a/third_party/glog/src/windows/port.h b/third_party/glog/src/windows/port.h new file mode 100755 index 0000000..a71979f --- /dev/null +++ b/third_party/glog/src/windows/port.h @@ -0,0 +1,181 @@ +/* Copyright (c) 2008, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * --- + * Author: Craig Silverstein + * Copied from google-perftools and modified by Shinichiro Hamaji + * + * These are some portability typedefs and defines to make it a bit + * easier to compile this code under VC++. + * + * Several of these are taken from glib: + * http://developer.gnome.org/doc/API/glib/glib-windows-compatability-functions.html + */ + +#ifndef CTEMPLATE_WINDOWS_PORT_H_ +#define CTEMPLATE_WINDOWS_PORT_H_ + +#include "config.h" + +#ifdef _WIN32 + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN /* We always want minimal includes */ +#endif + +#include +#include /* for gethostname */ +#include /* because we so often use open/close/etc */ +#include /* for _getcwd() */ +#include /* for _getpid() */ +#include /* template_dictionary.cc uses va_copy */ +#include /* read in vsnprintf decl. before redifining it */ +#include /* for _strnicmp(), strerror_s() */ +#include /* for localtime_s() */ +/* Note: the C++ #includes are all together at the bottom. This file is + * used by both C and C++ code, so we put all the C++ together. + */ + +#include + +#ifdef _MSC_VER + +/* 4244: otherwise we get problems when substracting two size_t's to an int + * 4251: it's complaining about a private struct I've chosen not to dllexport + * 4355: we use this in a constructor, but we do it safely + * 4715: for some reason VC++ stopped realizing you can't return after abort() + * 4800: we know we're casting ints/char*'s to bools, and we're ok with that + * 4996: Yes, we're ok using "unsafe" functions like fopen() and strerror() + * 4312: Converting uint32_t to a pointer when testing %p + * 4267: also subtracting two size_t to int + * 4722: Destructor never returns due to abort() + */ +#pragma warning(disable:4244 4251 4355 4715 4800 4996 4267 4312 4722) + +/* file I/O */ +#define PATH_MAX 1024 +#define access _access +#define getcwd _getcwd +#define open _open +#define read _read +#define write _write +#define lseek _lseek +#define close _close +#define popen _popen +#define pclose _pclose +#define R_OK 04 /* read-only (for access()) */ +#define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR) + +#define O_WRONLY _O_WRONLY +#define O_CREAT _O_CREAT +#define O_EXCL _O_EXCL + +#ifndef __MINGW32__ +enum { STDIN_FILENO = 0, STDOUT_FILENO = 1, STDERR_FILENO = 2 }; +#endif +#define S_IRUSR S_IREAD +#define S_IWUSR S_IWRITE + +/* Not quite as lightweight as a hard-link, but more than good enough for us. */ +#define link(oldpath, newpath) CopyFileA(oldpath, newpath, false) + +#define strcasecmp _stricmp +#define strncasecmp _strnicmp + +/* In windows-land, hash<> is called hash_compare<> (from xhash.h) */ +/* VC11 provides std::hash */ +#if defined(_MSC_VER) && (_MSC_VER < 1700) +#define hash hash_compare +#endif + +/* Sleep is in ms, on windows */ +#define sleep(secs) Sleep((secs) * 1000) + +/* We can't just use _vsnprintf and _snprintf as drop-in-replacements, + * because they don't always NUL-terminate. :-( We also can't use the + * name vsnprintf, since windows defines that (but not snprintf (!)). + */ +#ifndef HAVE_SNPRINTF +extern int GLOG_EXPORT snprintf(char* str, size_t size, const char* format, + ...); +#endif +extern int GLOG_EXPORT safe_vsnprintf(char* str, size_t size, + const char* format, va_list ap); +#define vsnprintf(str, size, format, ap) safe_vsnprintf(str, size, format, ap) +#ifndef va_copy +#define va_copy(dst, src) (dst) = (src) +#endif + +/* Windows doesn't support specifying the number of buckets as a + * hash_map constructor arg, so we leave this blank. + */ +#define CTEMPLATE_SMALL_HASHTABLE + +#define DEFAULT_TEMPLATE_ROOTDIR ".." + +// ----------------------------------- SYSTEM/PROCESS +typedef int pid_t; +#define getpid _getpid + +#endif // _MSC_VER + +// ----------------------------------- THREADS +#if defined(HAVE_PTHREAD) +# include +#else // no PTHREAD +typedef DWORD pthread_t; +typedef DWORD pthread_key_t; +typedef LONG pthread_once_t; +enum { PTHREAD_ONCE_INIT = 0 }; // important that this be 0! for SpinLock +#define pthread_self GetCurrentThreadId +#define pthread_equal(pthread_t_1, pthread_t_2) ((pthread_t_1)==(pthread_t_2)) +#endif // HAVE_PTHREAD + +#ifndef HAVE_LOCALTIME_R +extern GLOG_EXPORT struct tm* localtime_r(const time_t* timep, + struct tm* result); +#endif // not HAVE_LOCALTIME_R + +#ifndef HAVE_GMTIME_R +extern GLOG_EXPORT struct tm* gmtime_r(const time_t* timep, struct tm* result); +#endif // not HAVE_GMTIME_R + +inline char* strerror_r(int errnum, char* buf, size_t buflen) { + strerror_s(buf, buflen, errnum); + return buf; +} + +#ifndef __cplusplus +/* I don't see how to get inlining for C code in MSVC. Ah well. */ +#define inline +#endif + +#endif /* _WIN32 */ + +#endif /* CTEMPLATE_WINDOWS_PORT_H_ */ diff --git a/third_party/googletest/.clang-format b/third_party/googletest/.clang-format new file mode 100644 index 0000000..5b9bfe6 --- /dev/null +++ b/third_party/googletest/.clang-format @@ -0,0 +1,4 @@ +# Run manually to reformat a file: +# clang-format -i --style=file +Language: Cpp +BasedOnStyle: Google diff --git a/third_party/googletest/.gitignore b/third_party/googletest/.gitignore new file mode 100644 index 0000000..f08cb72 --- /dev/null +++ b/third_party/googletest/.gitignore @@ -0,0 +1,84 @@ +# Ignore CI build directory +build/ +xcuserdata +cmake-build-debug/ +.idea/ +bazel-bin +bazel-genfiles +bazel-googletest +bazel-out +bazel-testlogs +# python +*.pyc + +# Visual Studio files +.vs +*.sdf +*.opensdf +*.VC.opendb +*.suo +*.user +_ReSharper.Caches/ +Win32-Debug/ +Win32-Release/ +x64-Debug/ +x64-Release/ + +# Ignore autoconf / automake files +Makefile.in +aclocal.m4 +configure +build-aux/ +autom4te.cache/ +googletest/m4/libtool.m4 +googletest/m4/ltoptions.m4 +googletest/m4/ltsugar.m4 +googletest/m4/ltversion.m4 +googletest/m4/lt~obsolete.m4 +googlemock/m4 + +# Ignore generated directories. +googlemock/fused-src/ +googletest/fused-src/ + +# macOS files +.DS_Store +googletest/.DS_Store +googletest/xcode/.DS_Store + +# Ignore cmake generated directories and files. +CMakeFiles +CTestTestfile.cmake +Makefile +cmake_install.cmake +googlemock/CMakeFiles +googlemock/CTestTestfile.cmake +googlemock/Makefile +googlemock/cmake_install.cmake +googlemock/gtest +/bin +/googlemock/gmock.dir +/googlemock/gmock_main.dir +/googlemock/RUN_TESTS.vcxproj.filters +/googlemock/RUN_TESTS.vcxproj +/googlemock/INSTALL.vcxproj.filters +/googlemock/INSTALL.vcxproj +/googlemock/gmock_main.vcxproj.filters +/googlemock/gmock_main.vcxproj +/googlemock/gmock.vcxproj.filters +/googlemock/gmock.vcxproj +/googlemock/gmock.sln +/googlemock/ALL_BUILD.vcxproj.filters +/googlemock/ALL_BUILD.vcxproj +/lib +/Win32 +/ZERO_CHECK.vcxproj.filters +/ZERO_CHECK.vcxproj +/RUN_TESTS.vcxproj.filters +/RUN_TESTS.vcxproj +/INSTALL.vcxproj.filters +/INSTALL.vcxproj +/googletest-distribution.sln +/CMakeCache.txt +/ALL_BUILD.vcxproj.filters +/ALL_BUILD.vcxproj diff --git a/third_party/googletest/BUILD.bazel b/third_party/googletest/BUILD.bazel new file mode 100644 index 0000000..ac62251 --- /dev/null +++ b/third_party/googletest/BUILD.bazel @@ -0,0 +1,218 @@ +# Copyright 2017 Google Inc. +# All Rights Reserved. +# +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# Bazel Build for Google C++ Testing Framework(Google Test) + +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) + +exports_files(["LICENSE"]) + +config_setting( + name = "qnx", + constraint_values = ["@platforms//os:qnx"], +) + +config_setting( + name = "windows", + constraint_values = ["@platforms//os:windows"], +) + +config_setting( + name = "freebsd", + constraint_values = ["@platforms//os:freebsd"], +) + +config_setting( + name = "openbsd", + constraint_values = ["@platforms//os:openbsd"], +) + +config_setting( + name = "msvc_compiler", + flag_values = { + "@bazel_tools//tools/cpp:compiler": "msvc-cl", + }, + visibility = [":__subpackages__"], +) + +config_setting( + name = "has_absl", + values = {"define": "absl=1"}, +) + +# Library that defines the FRIEND_TEST macro. +cc_library( + name = "gtest_prod", + hdrs = ["googletest/include/gtest/gtest_prod.h"], + includes = ["googletest/include"], +) + +# Google Test including Google Mock +cc_library( + name = "gtest", + srcs = glob( + include = [ + "googletest/src/*.cc", + "googletest/src/*.h", + "googletest/include/gtest/**/*.h", + "googlemock/src/*.cc", + "googlemock/include/gmock/**/*.h", + ], + exclude = [ + "googletest/src/gtest-all.cc", + "googletest/src/gtest_main.cc", + "googlemock/src/gmock-all.cc", + "googlemock/src/gmock_main.cc", + ], + ), + hdrs = glob([ + "googletest/include/gtest/*.h", + "googlemock/include/gmock/*.h", + ]), + copts = select({ + ":qnx": [], + ":windows": [], + "//conditions:default": ["-pthread"], + }), + defines = select({ + ":has_absl": ["GTEST_HAS_ABSL=1"], + "//conditions:default": [], + }), + features = select({ + ":windows": ["windows_export_all_symbols"], + "//conditions:default": [], + }), + includes = [ + "googlemock", + "googlemock/include", + "googletest", + "googletest/include", + ], + linkopts = select({ + ":qnx": ["-lregex"], + ":windows": [], + ":freebsd": [ + "-lm", + "-pthread", + ], + ":openbsd": [ + "-lm", + "-pthread", + ], + "//conditions:default": ["-pthread"], + }), + deps = select({ + ":has_absl": [ + "@com_google_absl//absl/debugging:failure_signal_handler", + "@com_google_absl//absl/debugging:stacktrace", + "@com_google_absl//absl/debugging:symbolize", + "@com_google_absl//absl/flags:flag", + "@com_google_absl//absl/flags:parse", + "@com_google_absl//absl/flags:reflection", + "@com_google_absl//absl/flags:usage", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:any", + "@com_google_absl//absl/types:optional", + "@com_google_absl//absl/types:variant", + "@com_googlesource_code_re2//:re2", + ], + "//conditions:default": [], + }), +) + +cc_library( + name = "gtest_main", + srcs = ["googlemock/src/gmock_main.cc"], + features = select({ + ":windows": ["windows_export_all_symbols"], + "//conditions:default": [], + }), + deps = [":gtest"], +) + +# The following rules build samples of how to use gTest. +cc_library( + name = "gtest_sample_lib", + srcs = [ + "googletest/samples/sample1.cc", + "googletest/samples/sample2.cc", + "googletest/samples/sample4.cc", + ], + hdrs = [ + "googletest/samples/prime_tables.h", + "googletest/samples/sample1.h", + "googletest/samples/sample2.h", + "googletest/samples/sample3-inl.h", + "googletest/samples/sample4.h", + ], + features = select({ + ":windows": ["windows_export_all_symbols"], + "//conditions:default": [], + }), +) + +cc_test( + name = "gtest_samples", + size = "small", + # All Samples except: + # sample9 (main) + # sample10 (main and takes a command line option and needs to be separate) + srcs = [ + "googletest/samples/sample1_unittest.cc", + "googletest/samples/sample2_unittest.cc", + "googletest/samples/sample3_unittest.cc", + "googletest/samples/sample4_unittest.cc", + "googletest/samples/sample5_unittest.cc", + "googletest/samples/sample6_unittest.cc", + "googletest/samples/sample7_unittest.cc", + "googletest/samples/sample8_unittest.cc", + ], + linkstatic = 0, + deps = [ + "gtest_sample_lib", + ":gtest_main", + ], +) + +cc_test( + name = "sample9_unittest", + size = "small", + srcs = ["googletest/samples/sample9_unittest.cc"], + deps = [":gtest"], +) + +cc_test( + name = "sample10_unittest", + size = "small", + srcs = ["googletest/samples/sample10_unittest.cc"], + deps = [":gtest"], +) diff --git a/third_party/googletest/CMakeLists.txt b/third_party/googletest/CMakeLists.txt new file mode 100644 index 0000000..102e28c --- /dev/null +++ b/third_party/googletest/CMakeLists.txt @@ -0,0 +1,34 @@ +# Note: CMake support is community-based. The maintainers do not use CMake +# internally. + +cmake_minimum_required(VERSION 3.5) + +if (POLICY CMP0048) + cmake_policy(SET CMP0048 NEW) +endif (POLICY CMP0048) + +if (POLICY CMP0077) + cmake_policy(SET CMP0077 NEW) +endif (POLICY CMP0077) + +project(googletest-distribution) +set(GOOGLETEST_VERSION 1.12.1) + +if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX) + set(CMAKE_CXX_EXTENSIONS OFF) +endif() + +enable_testing() + +include(CMakeDependentOption) +include(GNUInstallDirs) + +#Note that googlemock target already builds googletest +option(BUILD_GMOCK "Builds the googlemock subproject" ON) +option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON) + +if(BUILD_GMOCK) + add_subdirectory( googlemock ) +else() + add_subdirectory( googletest ) +endif() diff --git a/third_party/googletest/CONTRIBUTING.md b/third_party/googletest/CONTRIBUTING.md new file mode 100644 index 0000000..b3f5043 --- /dev/null +++ b/third_party/googletest/CONTRIBUTING.md @@ -0,0 +1,131 @@ +# How to become a contributor and submit your own code + +## Contributor License Agreements + +We'd love to accept your patches! Before we can take them, we have to jump a +couple of legal hurdles. + +Please fill out either the individual or corporate Contributor License Agreement +(CLA). + +* If you are an individual writing original source code and you're sure you + own the intellectual property, then you'll need to sign an + [individual CLA](https://developers.google.com/open-source/cla/individual). +* If you work for a company that wants to allow you to contribute your work, + then you'll need to sign a + [corporate CLA](https://developers.google.com/open-source/cla/corporate). + +Follow either of the two links above to access the appropriate CLA and +instructions for how to sign and return it. Once we receive it, we'll be able to +accept your pull requests. + +## Are you a Googler? + +If you are a Googler, please make an attempt to submit an internal contribution +rather than a GitHub Pull Request. If you are not able to submit internally, a +PR is acceptable as an alternative. + +## Contributing A Patch + +1. Submit an issue describing your proposed change to the + [issue tracker](https://github.com/google/googletest/issues). +2. Please don't mix more than one logical change per submittal, because it + makes the history hard to follow. If you want to make a change that doesn't + have a corresponding issue in the issue tracker, please create one. +3. Also, coordinate with team members that are listed on the issue in question. + This ensures that work isn't being duplicated and communicating your plan + early also generally leads to better patches. +4. If your proposed change is accepted, and you haven't already done so, sign a + Contributor License Agreement + ([see details above](#contributor-license-agreements)). +5. Fork the desired repo, develop and test your code changes. +6. Ensure that your code adheres to the existing style in the sample to which + you are contributing. +7. Ensure that your code has an appropriate set of unit tests which all pass. +8. Submit a pull request. + +## The Google Test and Google Mock Communities + +The Google Test community exists primarily through the +[discussion group](http://groups.google.com/group/googletestframework) and the +GitHub repository. Likewise, the Google Mock community exists primarily through +their own [discussion group](http://groups.google.com/group/googlemock). You are +definitely encouraged to contribute to the discussion and you can also help us +to keep the effectiveness of the group high by following and promoting the +guidelines listed here. + +### Please Be Friendly + +Showing courtesy and respect to others is a vital part of the Google culture, +and we strongly encourage everyone participating in Google Test development to +join us in accepting nothing less. Of course, being courteous is not the same as +failing to constructively disagree with each other, but it does mean that we +should be respectful of each other when enumerating the 42 technical reasons +that a particular proposal may not be the best choice. There's never a reason to +be antagonistic or dismissive toward anyone who is sincerely trying to +contribute to a discussion. + +Sure, C++ testing is serious business and all that, but it's also a lot of fun. +Let's keep it that way. Let's strive to be one of the friendliest communities in +all of open source. + +As always, discuss Google Test in the official GoogleTest discussion group. You +don't have to actually submit code in order to sign up. Your participation +itself is a valuable contribution. + +## Style + +To keep the source consistent, readable, diffable and easy to merge, we use a +fairly rigid coding style, as defined by the +[google-styleguide](https://github.com/google/styleguide) project. All patches +will be expected to conform to the style outlined +[here](https://google.github.io/styleguide/cppguide.html). Use +[.clang-format](https://github.com/google/googletest/blob/master/.clang-format) +to check your formatting. + +## Requirements for Contributors + +If you plan to contribute a patch, you need to build Google Test, Google Mock, +and their own tests from a git checkout, which has further requirements: + +* [Python](https://www.python.org/) v2.3 or newer (for running some of the + tests and re-generating certain source files from templates) +* [CMake](https://cmake.org/) v2.8.12 or newer + +## Developing Google Test and Google Mock + +This section discusses how to make your own changes to the Google Test project. + +### Testing Google Test and Google Mock Themselves + +To make sure your changes work as intended and don't break existing +functionality, you'll want to compile and run Google Test and GoogleMock's own +tests. For that you can use CMake: + + mkdir mybuild + cd mybuild + cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR} + +To choose between building only Google Test or Google Mock, you may modify your +cmake command to be one of each + + cmake -Dgtest_build_tests=ON ${GTEST_DIR} # sets up Google Test tests + cmake -Dgmock_build_tests=ON ${GMOCK_DIR} # sets up Google Mock tests + +Make sure you have Python installed, as some of Google Test's tests are written +in Python. If the cmake command complains about not being able to find Python +(`Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)`), try telling it +explicitly where your Python executable can be found: + + cmake -DPYTHON_EXECUTABLE=path/to/python ... + +Next, you can build Google Test and / or Google Mock and all desired tests. On +\*nix, this is usually done by + + make + +To run the tests, do + + make test + +All tests should pass. diff --git a/third_party/googletest/CONTRIBUTORS b/third_party/googletest/CONTRIBUTORS new file mode 100644 index 0000000..77397a5 --- /dev/null +++ b/third_party/googletest/CONTRIBUTORS @@ -0,0 +1,65 @@ +# This file contains a list of people who've made non-trivial +# contribution to the Google C++ Testing Framework project. People +# who commit code to the project are encouraged to add their names +# here. Please keep the list sorted by first names. + +Ajay Joshi +Balázs Dán +Benoit Sigoure +Bharat Mediratta +Bogdan Piloca +Chandler Carruth +Chris Prince +Chris Taylor +Dan Egnor +Dave MacLachlan +David Anderson +Dean Sturtevant +Eric Roman +Gene Volovich +Hady Zalek +Hal Burch +Jeffrey Yasskin +Jim Keller +Joe Walnes +Jon Wray +Jói Sigurðsson +Keir Mierle +Keith Ray +Kenton Varda +Kostya Serebryany +Krystian Kuzniarek +Lev Makhlis +Manuel Klimek +Mario Tanev +Mark Paskin +Markus Heule +Martijn Vels +Matthew Simmons +Mika Raento +Mike Bland +Miklós Fazekas +Neal Norwitz +Nermin Ozkiranartli +Owen Carlsen +Paneendra Ba +Pasi Valminen +Patrick Hanna +Patrick Riley +Paul Menage +Peter Kaminski +Piotr Kaminski +Preston Jackson +Rainer Klaffenboeck +Russ Cox +Russ Rufer +Sean Mcafee +Sigurður Ãsgeirsson +Sverre Sundsdal +Szymon Sobik +Takeshi Yoshino +Tracy Bialik +Vadim Berman +Vlad Losev +Wolfgang Klier +Zhanyong Wan diff --git a/third_party/googletest/LICENSE b/third_party/googletest/LICENSE new file mode 100644 index 0000000..1941a11 --- /dev/null +++ b/third_party/googletest/LICENSE @@ -0,0 +1,28 @@ +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/third_party/googletest/README.md b/third_party/googletest/README.md new file mode 100644 index 0000000..30edaec --- /dev/null +++ b/third_party/googletest/README.md @@ -0,0 +1,141 @@ +# GoogleTest + +### Announcements + +#### Live at Head + +GoogleTest now follows the +[Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support). +We recommend +[updating to the latest commit in the `main` branch as often as possible](https://github.com/abseil/abseil-cpp/blob/master/FAQ.md#what-is-live-at-head-and-how-do-i-do-it). + +#### Documentation Updates + +Our documentation is now live on GitHub Pages at +https://google.github.io/googletest/. We recommend browsing the documentation on +GitHub Pages rather than directly in the repository. + +#### Release 1.11.0 + +[Release 1.11.0](https://github.com/google/googletest/releases/tag/release-1.11.0) +is now available. + +#### Coming Soon + +* We are planning to take a dependency on + [Abseil](https://github.com/abseil/abseil-cpp). +* More documentation improvements are planned. + +## Welcome to **GoogleTest**, Google's C++ test framework! + +This repository is a merger of the formerly separate GoogleTest and GoogleMock +projects. These were so closely related that it makes sense to maintain and +release them together. + +### Getting Started + +See the [GoogleTest User's Guide](https://google.github.io/googletest/) for +documentation. We recommend starting with the +[GoogleTest Primer](https://google.github.io/googletest/primer.html). + +More information about building GoogleTest can be found at +[googletest/README.md](googletest/README.md). + +## Features + +* An [xUnit](https://en.wikipedia.org/wiki/XUnit) test framework. +* Test discovery. +* A rich set of assertions. +* User-defined assertions. +* Death tests. +* Fatal and non-fatal failures. +* Value-parameterized tests. +* Type-parameterized tests. +* Various options for running the tests. +* XML test report generation. + +## Supported Platforms + +GoogleTest requires a codebase and compiler compliant with the C++11 standard or +newer. + +The GoogleTest code is officially supported on the following platforms. +Operating systems or tools not listed below are community-supported. For +community-supported platforms, patches that do not complicate the code may be +considered. + +If you notice any problems on your platform, please file an issue on the +[GoogleTest GitHub Issue Tracker](https://github.com/google/googletest/issues). +Pull requests containing fixes are welcome! + +### Operating Systems + +* Linux +* macOS +* Windows + +### Compilers + +* gcc 5.0+ +* clang 5.0+ +* MSVC 2015+ + +**macOS users:** Xcode 9.3+ provides clang 5.0+. + +### Build Systems + +* [Bazel](https://bazel.build/) +* [CMake](https://cmake.org/) + +**Note:** Bazel is the build system used by the team internally and in tests. +CMake is supported on a best-effort basis and by the community. + +## Who Is Using GoogleTest? + +In addition to many internal projects at Google, GoogleTest is also used by the +following notable projects: + +* The [Chromium projects](http://www.chromium.org/) (behind the Chrome browser + and Chrome OS). +* The [LLVM](http://llvm.org/) compiler. +* [Protocol Buffers](https://github.com/google/protobuf), Google's data + interchange format. +* The [OpenCV](http://opencv.org/) computer vision library. + +## Related Open Source Projects + +[GTest Runner](https://github.com/nholthaus/gtest-runner) is a Qt5 based +automated test-runner and Graphical User Interface with powerful features for +Windows and Linux platforms. + +[GoogleTest UI](https://github.com/ospector/gtest-gbar) is a test runner that +runs your test binary, allows you to track its progress via a progress bar, and +displays a list of test failures. Clicking on one shows failure text. GoogleTest +UI is written in C#. + +[GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event +listener for GoogleTest that implements the +[TAP protocol](https://en.wikipedia.org/wiki/Test_Anything_Protocol) for test +result output. If your test runner understands TAP, you may find it useful. + +[gtest-parallel](https://github.com/google/gtest-parallel) is a test runner that +runs tests from your binary in parallel to provide significant speed-up. + +[GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter) +is a VS Code extension allowing to view GoogleTest in a tree view and run/debug +your tests. + +[C++ TestMate](https://github.com/matepek/vscode-catch2-test-adapter) is a VS +Code extension allowing to view GoogleTest in a tree view and run/debug your +tests. + +[Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser +that generates stub code for GoogleTest. + +## Contributing Changes + +Please read +[`CONTRIBUTING.md`](https://github.com/google/googletest/blob/master/CONTRIBUTING.md) +for details on how to contribute to this project. + +Happy testing! diff --git a/third_party/googletest/WORKSPACE b/third_party/googletest/WORKSPACE new file mode 100644 index 0000000..4d7b398 --- /dev/null +++ b/third_party/googletest/WORKSPACE @@ -0,0 +1,39 @@ +workspace(name = "com_google_googletest") + +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + +http_archive( + name = "com_google_absl", + sha256 = "1a1745b5ee81392f5ea4371a4ca41e55d446eeaee122903b2eaffbd8a3b67a2b", + strip_prefix = "abseil-cpp-01cc6567cff77738e416a7ddc17de2d435a780ce", + urls = ["https://github.com/abseil/abseil-cpp/archive/01cc6567cff77738e416a7ddc17de2d435a780ce.zip"], # 2022-06-21T19:28:27Z +) + +# Note this must use a commit from the `abseil` branch of the RE2 project. +# https://github.com/google/re2/tree/abseil +http_archive( + name = "com_googlesource_code_re2", + sha256 = "0a890c2aa0bb05b2ce906a15efb520d0f5ad4c7d37b8db959c43772802991887", + strip_prefix = "re2-a427f10b9fb4622dd6d8643032600aa1b50fbd12", + urls = ["https://github.com/google/re2/archive/a427f10b9fb4622dd6d8643032600aa1b50fbd12.zip"], # 2022-06-09 +) + +http_archive( + name = "rules_python", + sha256 = "0b460f17771258341528753b1679335b629d1d25e3af28eda47d009c103a6e15", + strip_prefix = "rules_python-aef17ad72919d184e5edb7abf61509eb78e57eda", + urls = ["https://github.com/bazelbuild/rules_python/archive/aef17ad72919d184e5edb7abf61509eb78e57eda.zip"], # 2022-06-21T23:44:47Z +) + +http_archive( + name = "bazel_skylib", + urls = ["https://github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz"], + sha256 = "f7be3474d42aae265405a592bb7da8e171919d74c16f082a5457840f06054728", +) + +http_archive( + name = "platforms", + sha256 = "a879ea428c6d56ab0ec18224f976515948822451473a80d06c2e50af0bbe5121", + strip_prefix = "platforms-da5541f26b7de1dc8e04c075c99df5351742a4a2", + urls = ["https://github.com/bazelbuild/platforms/archive/da5541f26b7de1dc8e04c075c99df5351742a4a2.zip"], # 2022-05-27 +) diff --git a/third_party/googletest/docs/_config.yml b/third_party/googletest/docs/_config.yml new file mode 100644 index 0000000..d12867e --- /dev/null +++ b/third_party/googletest/docs/_config.yml @@ -0,0 +1 @@ +title: GoogleTest diff --git a/third_party/googletest/docs/_data/navigation.yml b/third_party/googletest/docs/_data/navigation.yml new file mode 100644 index 0000000..9f33327 --- /dev/null +++ b/third_party/googletest/docs/_data/navigation.yml @@ -0,0 +1,43 @@ +nav: +- section: "Get Started" + items: + - title: "Supported Platforms" + url: "/platforms.html" + - title: "Quickstart: Bazel" + url: "/quickstart-bazel.html" + - title: "Quickstart: CMake" + url: "/quickstart-cmake.html" +- section: "Guides" + items: + - title: "GoogleTest Primer" + url: "/primer.html" + - title: "Advanced Topics" + url: "/advanced.html" + - title: "Mocking for Dummies" + url: "/gmock_for_dummies.html" + - title: "Mocking Cookbook" + url: "/gmock_cook_book.html" + - title: "Mocking Cheat Sheet" + url: "/gmock_cheat_sheet.html" +- section: "References" + items: + - title: "Testing Reference" + url: "/reference/testing.html" + - title: "Mocking Reference" + url: "/reference/mocking.html" + - title: "Assertions" + url: "/reference/assertions.html" + - title: "Matchers" + url: "/reference/matchers.html" + - title: "Actions" + url: "/reference/actions.html" + - title: "Testing FAQ" + url: "/faq.html" + - title: "Mocking FAQ" + url: "/gmock_faq.html" + - title: "Code Samples" + url: "/samples.html" + - title: "Using pkg-config" + url: "/pkgconfig.html" + - title: "Community Documentation" + url: "/community_created_documentation.html" diff --git a/third_party/googletest/docs/_layouts/default.html b/third_party/googletest/docs/_layouts/default.html new file mode 100644 index 0000000..dcb42d9 --- /dev/null +++ b/third_party/googletest/docs/_layouts/default.html @@ -0,0 +1,58 @@ + + + + + + + +{% seo %} + + + + + +

wM0Wqi z@o@$){Em}i!fygO6h08-xXCL5>sULU(9D2wKTvP3W|VRPY`8cF00JTe>n^dsKlp$v zeN$oqLaqtT5EHQ&Xc2|C={K*(!A*K~vQ7ofoZ8lRu>G zHt5VSy~|;r^{DTOugD}-f|@E&MRFDpmlha>nYHgmITTWL-kG*O1iFBx`6Cb~7Rfhh2)!CI_eMeo= zbEQ|j4-!2+{pZm8Y-(!qXD5*VIM&tGVKXcNS>%5wpXhJTlUBu)7@O_5bEH>V#~_xW zp$-H=9(nq(i5V9wT_ZZLG#@QV8@`D?m;7=7T~OP(0z z4loQV=$=LDE9XZ6%A$>X7oMaI(4r|wi(kE@@>+%=V9Au^2^a5knpFN|jsKCiIPj7x zzcb6zhO5TwS%GY_-V3906BSQ7O397|s317RNy*$_iCD6emWJB&-A?Y#9(zL{%v5~G z=%pNy!L&P#+9qneR~)S!Q_UZwHP$QMsBNi|9z<zkhwOis><7sFzy6610YWSGutQN}y7 zr1ICKN{#cLO|kIbuhX=x11=yS^_-C}dX;Bqm}3XB+LSz2a}+3a08So-B{>0+B9Y|Y zb)8FxkI5jSe0MFAD&W6om^1C#7Ml&&C-=>B41w5!TWts*LaL=@dpS}%$^L^!lYEU+ z<+|OgmRdDOwf)j%>I-8piIAdyGTz5Utn+JD;bmBizL1irmAH;j+dhnWf0MmfqADvr}F z^wd>VFlzT4i?BDC8w*zQw=Ni~iHls==y|Z0N)@1IwtZ90d`2^oCW;1E@ z_d&Y*?049il>{|LD>lEZ3^fln`%t;^XtXEYJ5p0ht!n;kPQ>V-09}~m|7_mynX@^b zI+0Mk_MZlf%U)Xu$nd=NItGFF%o(e&Kujp@86Wg_9_v4yB|@*QJ~4?cT%{V&1JCj_ zn8c-Klp;=Lz9p*(f(WEY)F&kQ5^lBZ@3%xs5>0#+=Xbw+40`q=w^E~6?;KT4ipR6t z>MbJK#}2_ily-0`u9ORtU{UtnGjCj~T|>tRKT^DvTZ4w|edc-ej!40@iGb_mTb=N34^-Crsp*z(cMTtPOgO1V5QkpF1LyZ-no)0&80O-&=ZQJ;8^h3a=hRXv~Aen(WT3gm38jFfc4;2$%j52-E#M{a&9{tw z3&6Ws;5`qJQaU=#0P3}$l&y;St>a2z`+Vm)G>0X{i6WYgdB8BtiR!&7&p$Bi~c!kPse3AF`gZBS7#$ z{0B9xWljItCZw9^Lm^j1Xh;J<;sU0kdi24ECSnx$YcF=(f3sVsTL5wlLjC253utiN z6iEUbggam8k?ItI`R=E?)`H@_Og_T@| z&6grPsZff&39PUWA$5YOw~0xmJhO&;d6BXT;pxs=;11j?F>uWpZ69Ls$zxq3{28{P zD~go&IP~kYay1nz7Uo}y6F z5rf5Ch5kRXi?6ThUoa68WS40muP$zmHuVw4PLY;+wpQ$2FTMPHv*VFu=8c*2m)_CT zc9-AbTFA$ZR|b6Q{k5@pkc_#i=h}QdJub~W=7qCJwgg_mBQGXRg}(ZQf$L~p^c#WR9IEnvQNg!%&$l0vMF|tAM>p$x777} z%^l?FG?%=eR8`g2zSU?PRcu(9eI)GHIDMbFM(X|3F5nzn^BUF7y22UdaMCD(ug^_u zT<-Q&Z|HoQRazPZ;i?c6W5KfTx3k^VG!H9Y`nW-~-`0BWc{`aFHJ;xRcWGF#;6hm= zh=nYd&U_cIo}yP96a^9KmbAETZz;S_k&7y3jUODl z5^FQUu{A|=FpTHojxQJwsT61kpi`LJ9PruwrHmA47>Tu3r>`cMV3+cVc%NNo)sQv* zU2El#H76A&xUZOZDB+`sX%E%=e8T87?M$9RONshU!R0*X7L>Y$b^o=<9k5+yf_k>i z9eC?7E@f{LUo+Ld%PE(sjZLB@1?u0qlR1eD);?8qsmgIUzF6bM~Hrh7RowHKYwzzAh>lB{b(goAhg9G|B6`lqh+=1XHtfzJ%y<%f;ri zn`DBViD(yL%MBad9c_f*F*w#E33PD*)Bhd;*NO2!CH}2nbQU!zc6mzy4-WwBcU8{cx8fgxvR0sn6onluuLn}p zUjiwVjRzoryGa28NTFoP;QzMt^5~clDKx)j9593XLKy-6X2*dHAgY$v_Xq=dy{QF@ z&D>~wD`%^uVPjm&pG0d?e@|PfVqJ33b#JZs!{MsB_EC0=jN;LX`EZwG{*QC`Ip~pF zVM>jO)IT7KLLAqS9v5NhlJsAoaOLA{h!v>&V;AJ;Bp?9my~joViFT-a7;xoZ0&-tq z1^`3kca2XFz{M&X(f>0>*a~QY8KS6sJeCq%pa7}3RUqLpX%lsY?WqVZ4QEU^6z#5_CCRq~hP9hD`!&D5Nw=K{qQHwaCcy3(FTWFT}GEsbFAo7-b^Lv=r`7hVuP_K>R8DcQ|p%nmfZq8A20u<{3$2O(X-%)sJ$81Ep)bJ=dXAWxxCyKF^s~xw0^ya zDYi9WF(ht#-MxPcDf$-J9B99E3o1gGEudH5JT47er#7}mDoM}U>; zpwLa9ir@`rjHWK4X@;5r8kZVD3L1RBV36X@{Nbal0ze{g6;GaJLjofjh{e4rNd;_* z9vadQmsG0%mVi8vAXRNa5laYx0SS~#rs(r`O(TUFSZr`h$g0_s=E%qrUPjO*08cA!s5a0W-xQ2NG2dm?#fD81uy+T-pD+ zEdEms@UT+^fhPb=L;8IefgujGBqX6XoAOaRk}W^i`W|8(>GQr;=$LjVEOtC}#yHM| z>^9{`?&M#qR`!(}DnGW1YfY|~oTeS$T^XQ@6BJcnWffG{4ro=o@}<%;c9gu%Dp-*- z@EX@jk9_vd*Tqvr2ruz$tdP)keBqMTGkMSOapTuD`$7t_b%k_s8zr`nj+(phiTxzI zvK}e4{qY#fE2iN8cJS#uz0J;&v&vce%h|IlXV9H9kVi&Uzs{7e zovAcYO4SfCzNS47D$J~evXRU_{5YXCx8#uL5=y!<=d&YK=ELG#xNMq=H<89rV;teL zGrFAp?4rE>xv2+`A@JrVu9Gmt6{y^Q=phIXTDgB+9ufXK!>4J5hNN{@?To!zIjn(f0PYoZV($^m!4FaJ`>s$R}yh_18x0NBGP}pF5?)tqDMhtT5^Zqgx z6v^y|Y);tvauN`7o2h%V!y0ps%k!pbNs93WQewR85}K3qK`HNX9Sqn3_A$bfSAjK; z96J)Jue;zpJm;;)$Am(L3X_h-HEdt1{8EwZxYI%~_YW`nrQYb{%G>H>P&_&_A^;z; zfAtWNUS}%}E5?15|Jm0THmgz%zHhI@9c!MV3uJ|;BF!IVYvT&6l8RXKw*qj!kE2hV zifi0lQmQ7m+BmG*R;cG&i>oKMpo+vTMw8`Tu-1m?WHfZUwp3OT%x@v*kb`|{p{hk( z*g^r!2=JaKz_6l!2pSM%OmB_9CzzK~l3%|wU)RY>Q(LcustM*;_d-6nYSEf}&v>lM z*MR%~7N?sbgaBAlbaTT6wfe1fQj^RE>eb%F#|1Z>0=8Vm&xPyScw76+@M>ch-!j=O z8P5XGDZCUq(W+9VTG8`a*I~GuM*$BaOK3^LS7YD3-ls2)q3AO)G=}B!b@Rzn>v8_HM`{}Qh4Vm~rwR<*yH+`T+tsK4 z3HIJKS37!FAH%-~`R0W}efl|7mFnuq-qrlQW5~Tp>v09fGvLL%sjARlTiiPS6TK%( z@@y)xnTxwohSjHOXRFSPQR^gxQQNe9&bk2!1BdyKbP^zxEOpk6urRI-q&y=>i9BQf zA2b9)!GcD$VsZO54a9Uzl}1eh{hp3r2~a{1PKO~jPKS?!1_4>)Brzx?BRrjNW1O~U zptX-%9@6t2+EnBx@wse;^odO`OYCRqD`(wV{+^tNo`r1{7(0C1aqvc&V(Z=eR2d=_ zbgZka%ob~p0(3Q> zESws)YBV2maXV;E?6_salf$PA_NzeW*@3Q6sb)!|hVdxTBV`e62nRerejV3L0qtmI zbmBwLFv*CYVUpBDhzZko=s)r~k+O)QZYh9sK{g~_@;WdlI0Pu$jre6yqKz%&d`CTx zCL;m(v&sV*8|KxMNfcqgBp0Iqu;EY>f8p*tWjmN2Y_b$hz(P+^s)dXMfMNktz~43L zx^&%8P?>Rn`kf}eqh3JYJ%A(uEzbAHVJJG~3JwAQYSJkHYk(?b{(i9MNM8n9#Wzrv zp&8#6CfRluop@IkuPw`i5PijhjK5jrsUus{E%lFau=(8(qb@p`05t&|l-&<7uz^({ z&>s|Ir2awu)9$z-1~xB1@MOoG!aNml8c6j1&7^)H5Zsv|t5o0eDXFy1C06Xhn zKVEQgClg4x-|FyCERO>zJ`{a{HLe5H1(8L7cGo#Zo`_V`5U9tpzq1IH+blO+{+`?H zPu*}}e2}*j4(nrghsrObF`3s_r4nmjuUMmKdzfDNyr&D(WwWJTJoBRK%IqUoX&+j= znMi8X5G@KuWd-*Fc(#4iz@~efJ<-$wtilMC!DFGKwKjqc0%StaKVw zT{R~#@Im63lBII7!fE+h>XM*SnlH-3Nytb_*RUpj$=yd z<7RkqyGlQ&Pk5QY2@dmW!#J;}sv4}dg6@5H!8`uK+)mWZC7%+`uia!&_75YO{dm2~~ExTAyreRJG`+gGt zObqHfc$b^QMBa?Zb|XQ3f~_|Wf|O0AraZK-x}XP#S(AbYN^?-4$G1OVLnjXNhe^sU zf|xobQr022$Y^r!FUUWGsIt^Th~VUni(#re77~*A9=c;xzy%0cJPd(?U?P6BErh57 z!ig)vdmo@UQ28OW{P7qf>y_KrQE}C^3ohAKKEFiu@5nf=*$;x;NE!`7tLhwH!n~sW z=5ci5tBY@3uiT@0SjEK{4=HLJfx`ZJQQ=cG*gY^(W3GyMf*q;ZJwUjLZ&@7V$Th3oAxA}0OO!Icav%yjAcA7KA185Y;FzlJT&5DXoYIr)n1 zs2P|0hfDD@D0S}mPUepd-n-?5m~#$unRj+fURx*aI-8disDCPoQ+%j?md2VYu+lb% zgth|yNg(h~)Pa8@2uyT#glGvp^6(HfjByrv;BNdI`#UWKaJbuV=_zRaA>AJVVUq5j zRI0zM{lXo_P{aNrK`A*DcXf()D_TU4jNNeuV-!~pkp9b=ya8iJT$^v95d7=@wXC5h z!~`m_Dq!%*_7VkvqC5d06x1=r0vQKId46C3=kv2itO&zKc8c8FrHkC_ug``ruxrc; zRw8zj<8ne)&T%EUCmr9dfb71_Zep*N5z5%B3Oq6Cwp~4jt5>PRk?0H$Yu5`5dWquFYL9@1C3mI3ozMtB4 zAp(BawSg2XlmQ!*iQKXDuSxx!u~GKrYa&s;v+j7r)$NJNg`nl#1XzyJ8Ra_vuTx(` z+rC;5;*%{3M|Z<26x!n~&-0|!^i>##%w|U>`|gt#LpR9letomASkR%mE%Q*%2Y*0i1Z%; z#7HBI2wcN6@JqVn9xH0hc3S0&fJc@p{v#WokI?k9Py&bVe2Hy{Z3}J-f)w_>4V{NA zjh`boZ1FH5mPi?Xf9pg z@bi^*ON~AcbJ-$Oz)lj|aR~rHnMz{O74+J(9aWEp)0R@)h4+I))jz75>*LJr$Dd(&cP==`1WV4N z`i3@UCKgO2em&vib9;a^o>G+A6f5@5mm9s1PWnCzJL&kt(F?`ay7$1w@`5^>yv+<+G+6*K@h}dfjHlbP% zXmEr+aPMQO%i?&ecC$J6DZByt)64SOR!d@mGcG-CKoFy^G1dk!QUgtT-Oh2qZuRjn4#Z`Q zxSpb~Xi4Pfz{ft@;rqGc8XR;Qug%7Q5Lt`zX3Ob5FR&3cwWz;1)~S4ax&FHH@n78B zo)-gQZBXcZ7XLRv6OW6)!2%)#kb=_FVe80vYAT$L@*DM{$uP*q9k%;%pmx%_6FTP( z;y}qB7gcfb)OnsV6v`(%OJ9Km5HNvJ@B)}7$|=}&Q7P0T1W>tjKxOqdk|GY&X*E&i z17^JsWjYXl1ZW?mD7_)kio(wNn;itVEf1t^5TXDZSlkik=)GQ8cwDTGD;BgG{}i-U zl1$I*R-mfZ%iNuaH~3TCTe$y>FM${Vn>#Ay0FI>Zbq0*qeYu{e6Gn zGj<7WRCbE8C)w9lMI@B$BB^X+-1N{$&7VmCsbq|`&QZao&R|ceLj7@ z|KIa}{?9Xa&imeb?tS0)e$P3tbFOA#S?qF>60TYjZ1nT0mQOl5ID*ogQ@RwgIqCL% zvQdeV^~x)LRU_K{a%$D<^Z{{c*GQ~z_e-oWLN~Xia5t9yyEZWH_?V5=j?&uvmKB5g zn@4{cL`#0*y7gIKAkM7!4Eko!fR?C~t-t2-wCHZ}-!+DzmnL@TA3dg;={)4bc2#$H z{`>6)MP64bv%zt9D$wq_PzBnAhni1zBp!f?2_&_0rN~fo;*)<;kG%U&r%!41oI|$D z*B^~?>C1;88r~=^OR~wc5t>0l00cL;<4akTs@jkFWw}sM+T)%4Wk`=5abYSX<`a$47dU-e+8X;;i=m^we2sfz3 zpbSxq9lhND;`GjSmyHh!LC*MJYavEE*U_(OCqC=@t*|+m_4_wvOo{3*dy?mY&UMs1 zHHs3%we;7tMw^;Mo*WKW+yuVUr*dov)cOuiiD=9ii<0dd$8XqxC;hR1$%9dyP z1q>Pk^ca?j&$~R|J0qKn{^L=mw8(k1Qr_DmzfKaIA)s;-oXtnqVPLu$f$_AUZFvb| zAObss`|?m z6!l0m-Ut{FJwG%y1W^%s1S33@Azv^kgU43`8j{Bz1lnWxfxTP1RTSQHe-ERS+z0`+ z05{m+p(8{bzh--jl>MmgVQK%^T39}HU8#$CtgGlv=L+A{bFsP6dLA+Xvx+z0Fnpg` znXF{`-k%t9^laFeo7CA2(-?UiWj$6HZB2ZFmF!U`g5=$^9lr}hV@xmGLP4j19#+Cp z#g)u4=`p9D%6ank)2<&6Nta)@tLquvza@Opj{m(rA^p@G^TpT8OJlJemE>?K9{fW) z9r7~E73=X1GD8vfR!#f_a`t_;8dtfsz1NOq*^Ur>=y&b$6l|&>&nQ^6U`v=bK42e2 zvtmu}$z)Od6i~@Pa?k0R@)h23YbuLX+~)7US`xXSTflVw$5?Glx1YztP>gVIRzLN} zU9Y<3jORZk=N5*om5ACd1~Ic2rLUWlhBtz?u@|-QUzxz%un6n$ijjVGzd66jE5>j_ zXT+o(V>Izy;Mli6*)NlSY;%vCJOr>vTgBuF<%;Uy=7%=&VT)zT5Vqvi-KN>rLl7Im*0F9W9@rq+P@BJ zdKNhC6jwHE7K@$M9)4aRNNXG^Gl;dB(WEr??tL-lXtJ(KVI0%ghwT_&Qxr5^y&)Nv5SUV>N_;01P|f6I}l7aH)t1?jAbtWARki0KUYH)Ya;TUCF(0oAoL z>P3M8peh>BSQLy%&?CG6p$x3aNQV$B0qGO$gc)B;;Vi+730@#@lE6mz_b@=HgGPu@ z2izdkK}U#C7vLoYqgtngO#me7f& zLWEAJM}$stHBmnI6bg(&Tg_m6&;l7B^o0nWzzX97)_;Xg*pnI@E--8godqw09`fHB zq2qa)d|)Rr)2R?P4?jE#%15LtzyZMU`S}bJA}1L8IjvE+2Na^>51c+^Lg#&xtDS zNo9{QZ}{G}1Y|l$>@(t`fXIdIN-n9znL`z=*=ksyd@+Xa{QLbIGunex;<(X`FGMsc z%~;dK&6<^0EDRM24~%AA7TXZ{urc~@sYsSy-ndH4wj`Ugj!2v_q6o0-lG^b>7aLDQ z5+)YXK)|R#no$<>4D@Dr03_<*MRe#kOt<6YN4K&bf{ov_0IJ!;bi&DLCp1b6H&Q81 z?M**B)4kur(B{`){_(owQ2{Iqt=^0tUoNVnxTGo=t@TsftMw@8U#F-lU=fv?d?V^w9;!e2;J*xeE-hhYfE&qDPtxFq# z;z7e98D>+r7CimEJ=)(Lm#BWa)^ak-VrD z5i_Mb!q#so?3GVG!3=J{M0DjIm7%gHh^bhhWYomz^k47A#=hBm=bw9X@F#Vz`Ygqk zLdk~lwUPaRSNPBJ=j@+I#c^lE#nL;S0Gzq25Y>WMgn<)O^!H8E@Q$@>8be&gcWyzj zk6$0hzdRML@R(0&{G2_6@oF%#@zy5qj&NpSA zm|B(?N8GD=^Ep3BfH5NQ4Ex15A;CGB?=?~*_3z#cw*BCqq29Qo&B8A20T77!QPa4C zP|0e{@|JfRTj+i1^}Q<7H;ftI&fs)l9Lca3Ef~iuHojqXsZ;geEKWolN}Y(dfbAc* zg5zp`>}V4bIZSO694Fii<4@yt%J_P3Pde}P%dhvM(s{F5u6(r-c`DojbvRz9uMoH6 zBNBvUo88$pI5adn9Fn^RJv*Nf96&H*MEnVMor-%^g>ZmX_o@QnAfn)?&aj)l34!B) z-^)z%uUC!;6&R_v(;3`?^q_r5+u@JAR(8R*EUZzVrBAtSn~44{eQKPgJ-qLeynzmb ze_o;g%8_cYf@6+LysF#U(#4-t8Ut7C6U0O51mMyWtC~ zFB!RxugG5X&pqX_(y^*{AoFH=TfdON@7#0K6V(ToMBTOHL?-RyxPuce*33{&NveDL z^*kPV>-=Pxmd$It|HlkvF6kFbLArWZtox3v&fhFAO}j+RLqB`FZYvRLIgfvALqm$Q z5iqWnqO`A<+Kn4{j$Y77S`DpN#}RPZmj%0p1~1^#b=Hshk}9G8QL*pR^i`G2k-m_zjfh?O6DMAOJSd{dcgnFr{WArIWg+dL2+Wp0 zpp4I5LE#RHp!9dKVuk4$h)?cN_aGenSJC*GU98?n{Xf%vfh`7r6#WSiq`iyP)gI}i z*UuQbKpqol4UY+wA(~7mQ!d?IYaqdbJ0ofrk9+)KK>gaPd;hYe-(f1{l^pu|5;d*`f?l?-OH zf6EcGSuB;z z1Ew*Xt@+vipz;461^~E_j=+wHa06HeIzsRwS;-Zm)z2$SYdcoB$Jdu<)?Yof$N#F- zEV?c?;+BVlPwmaIU)^5wZ5-Te(+3Gw#|`rdIO~y-<(b}&2IgW@f`E7bs&tTE{cjUi zK(gA&zjgLKlbq&SYe>jw*zoQ0IrOb{iTHuVV}|m@#>z4+sW8v234?d3|GE6O_d}ed z{6fjdxeqz9)=~QOFLO(0TZw48n*K zhfGnjoU5{;xWGVt(u3J|U+l|gmugE6&?W@GrV-;#KtW7CCF;Gj9v*9B*(=91drU9n7gXO8L7I!E2YJRPBTq*sVZz zCDuP_66%SDG}I*2%jU;@Fh?E#*pQkOXUK1SE}g<&D}5I(@iJN_Ln&lY|Bv19UXsJnHNR4AO9F7Lop(ZKt7YuR|J4{Ba2^}V* z)y``pw?)nUm;cW7s&7ID#9-^&WL!TP@Yy_!ZN`rj-6UIRd>hFY8X$;y83r}>qd=Y4*4A-Koer-U#6UxMz|q`IRNegy?T{9+00E*fki&9FY-_ z&E5YK&P+p4E8eJnI?Y)FTES^STEW8tdq!Yh&~NUr*Wn~tsd1sJT}GiSJE}$JVKJD&95s_ z?)@a!nzCe!u*xhM6Ma>N%{P{MH%Q8UD@*;IYYQu)UpE|*g$rbT{JnF%AH6NioWI_h z{OnD{y(z1bS$ER>1O&n|j7=6k&;K~p&oRF+r=j?1ab;Xxw+w>y=%6Oap%Bm#XJfq$ zTGmyb-9O8N*2g#%^>J!>Z7Ds;mG6dar8SfPX`WlSH(#Cc6u;L+mZbDDqhfjS~QB59eQ;PrFhqU ztYGYIpzhOfh=|28H6u%1HOg`7JpeCk+l`M-Uc32_cysbX1M!#AcAUqYeWA+gqKno1 z1r^QFwq{IvWx*GQqH3EK=K#~hZ>M!JcJ=;Z49Pj(mUm5X2^5~iavAc~UQ#=+hsDkp z#PmPvAb|^zI}d2d3n1_nJ4`6LgV@|_M4#GS`0_-ttZnv{5-wlI#+6sgPukJif#VlP z(;>@qxFobTkz($m4BA&`7#M z&TCK&<-Xp^{Xx?FmjUDf^R_F^C4wu8b}}drbro)RT@%g%FGZEEwZ+Mynwd5;FXaZu z_;OXhg(aV5E)O4PcmIXr1UH+uunj+d%ltLpuMjg$!)9a7tnuzS$HiZLGYqxmYVjE) z!?r7l7Cou%^Ru+Yas^%IsO;(&SPEQ; zZO+PDay3Eq7=p+L1d;rJ%x}wQZ0c@yMI$dLZ7u>a^u<|MbQ+h+4{G!L-n=Efy~I`7 zAJj)w?A63R9@r~QavS)ZEQZ2#L@>nWp@?>BVz$32P`R9h5APV>Iz#EiTm*wSQ!!Up zfg)+*!s&#*W&NT(`u?CFPuj!wRI$9FCe{Cvz}=^fHTO7i8fF}x^9|Ox=x28-O<-#GIx7~NUaWdpw^y>K=KoC2A^GbTIL8*VFIeHNgg|Rx z6M6RmLEe4EPtp2Cn`u*V5-xt7_yp2F5hCXHI>+0{<7gWlmG+g+nQw0i%p}=YIOXq$ z*bB1bmC3_iN5JW9Kc4H$KT26A73l*Dmb?G*ryj$1+E$KT2URe9RE%opAhby!U}~Bj zm0DkP)FCIE6gCF1noYSMl(F#p<4p~IGnU|b4ZeLyM3eu-fM`nRQE>}h$s8eY8DE&w zE_&)P;qS5Nnww}Z79lg7g087>h3HQO&5N;qm;7S1DC4-Q_l z`-UP;%i&tj&9UH;>!G)Q2;D8Z((KeQlF}+&Xpw>z9%$CE6F{Y$%-ARU$my(E|a zI#d68B(g2~0y|ku_MD&~&X}ee4t&H~b`_v7LNmoa!qPU4t>Q*E={G~kDQLeq*KxXV z|FFT$e9R0B<&j(Y9+%t2NCh(4`t}_y_v0#lHyxaHJ;Tmd|L9DE$niI0C(bk&)x5)R z7%rF!q^zAtI^Eaims@4!o6Pf}!^nq13te|Ll~Ai9E*jbq8N5L3Pn2sx-yA@*>CU;0 zT~5pW#GElc?vU|il{1e$-);xv)fbI&b*r3>0dt|=krJNW*Vl`LC0%}P|K2q$d1k~| z?oGs(uBa-uo|;Er7>o_Pt-AV6Cqln?r7GKO*@0+m`^UA;UeRIfdlc20A|E50%^LKo$4{`I=q4b9X>MgX9TkSoqxr2AD-Xutm|#%dgbe2=<~ zN8&d8U({NZJZjjJkaa^qdqvA9p?J5^hX0C|?b^n0_kBI)q}bcOhjf&p>}lrX&yHQr z+u!QWH`o8Yj##w&9hbTc<%(9K*Wu3XqY67a7>A8pkgbSi$6wdYyYFAwLXVT%d>wM>?>`Ss5 zWp3$a;g31zv4xTJ`WE}&>6cA-6uzFHE*qKWCl zzvXjdPB0TSedTgW7Ju=JYO=VFe;tgx2dIiKYx#Aelk3WaWve7f}^UH@G8G2&v8hqQA0=jKSs_Bu2wKB;k)2 z4L{O(YTtNs?B>o*)yUyjyG}%3q35Lykq-Eyt6_SoS3MF;&ug}=f9x^i{J87aJK>_u z74o(xs+epnIc0eVK*@vlUXXV?v8k)MH*3E$>zKpNEEh;0A67hk>kZ4YY&Dv ztq?&~e=kqWCozbyIw2NfLJn)2ZgOXIPy69I6F4rBEA9DkTpqcFZh61=L(o`9yS~Bw zp8pf6HN+HaEMJHseDvCxbrH^i_s*R zYa#b#IzP#Z-}&MAVn-ar_TgR+fb7YAz7gKJ>~bdiI7zSZ>w$6O#t%ymy83Hg zeokHgWG3qk@I6_hg}S3}Ka9^bCuq-+{Re?AXZ54$OAwLTm?;SAYXV*!dG~KWPkIT!p9EcnyjX+ zJB{OiEs?Pn%%(J}6!s7Xh4CoXi0vBL8<=K4*))Ef2IFm?`@M<+Pnm0U^BM>^_+nE> zf3MRkN`CoIT9BRMdds(D z$g{7uBi`6&pKV7pJBep$5Hqe0pYCw6#Eg+up~tqh=OAz7%C@rgay}BfzNUa z6Hb!A3O|8#7m_O^D@d0horWX@i60V+1eP6q#KAh?^pwrrgpm@jvmFuxh+e<1n$T0? zLxIqO_?FX=w~YpgpgqF2Z_Ar85tTe2XWUZU^dfR(8oqA7A@xCOkCD%fDrzDmO;cl% zCLxVeBZGVAg*Fz1^v;uPuhlCcOO(G&{z#M-(A046-$MJVC<63SLk%8u{W|>=5T56i z9v-<`hv!7eR^#8S_qO6da&A>J3SZ2P*~NBEv>%$pRKh5}?xZ2Blcp9v)Y4Q?TmeLePRn{L9#VQ%b*hnT6%2U7aqx@%BFW9sM3 zx|K`tKjxr_ot91w96rBG()2ymvD>#heP~XAu)1BYK0WdhX504s--$1&jKYhd^L5{(AuPE?BZ>7*P#bj*p@^0KFcY<5Q; zy&`lU)jDuNjN%jc94l`R(Z6*cCF^_eGL5Mfrr}ZqUzs*b((|`8%1a~&?OZ@oxzhYd zW_+ACKgibfrCg3W?8w}MkvW+9(p2A- z|0Jq^J-n%V#)^i%ho;E?u;f{kJJX6?QHdMgisszfI+L><|IEXqfmCEj_HlT!i^XfU z?;^Uc5_GSJgMK?f0ci@VG$ad3JqUGgj8wqueA@@|>zw+EtNpX%I>XWX50XJ82!W|J z(h0<&fX4I40HF`?I)%djiNp6`VhPzhyhx7*Cf19>_z;{ExsOhAAJB@okUWWQ6Ci`7 zfoy_X5I0ua-G9HPcn=p1BSn{d8e)JA83yE#VSJ+R5&BQvCUB_=su5lN89qcDt%e-A z(@4PgNTZFP*}=DAlpC z3_u~IfQ4K@_5nw-b96{OSs4cevDpLJQVJsVko#LHc(en~FTw#zL4?5E6}S*t2X>0c zI>@;Ikp(IIzkI--*}*k#6M&2T|9M)P@P}AjG90)!{O7we+Uz^3ItmjmM6A4P%14Fs z;3uwC?-pKHcpS+wQjs%uBh6Q2B3|ELpmJ%}I)aDo%E8P@mpu)#l4(wtbm&)Y#paoL zzIOifb6&x9rC7gC7f%auO!&}L7E2S=z;7x3`>l`T%KX^aiWjcyW`SeMa<>7Ev797l zX5;}kr!p-!yxQnMa6HFW7Uvw+TD?<2&f*Zc*m#(0t0ELBCe$l!Rc!LduQcpeSn3-z zD_$GwtqYs0I_H1g?mhFJrM*ulbM~|O3tr~Nj6A;oB=Sr5MPHOBYslw*u410a=(+m| zWtN01Ll+{x{{Jay!4$VMpsl#r5usXf%el zT!F!Ogg`;j6KXut`4&HgOT}Vy{Pa|>;EO}I(aGi|reU#f0@SGQ@EiSli`_whtpg7y zs`^&ABg(DKUCd(3t^I8-&X+}$yI-5)H1JU%k*gK57DGjfU{ijfs_&mnRbPI+(w`b~ zIh;_Dq75knA9sJkN^ftGY4l6?j%nJxqIZVS`bDQKmH9Fd|t4z-zXH`z^dyJgLu8x>fqkuJYxq{+{uh9YCn$DO_SSC8XW<>Y|58QHEN0!JIgZ z?k&0Am+h!SSWkW1a^pge|#!z4mh*X6@0vqEhzef_OjWFNuuD zx>!_%?j1+AJsVAVN^2+O zsqsDS;ZM_sFUa9GA%Fcflgdet<=Kr_CEW?vK@{S5Xm+FFH?Cp(8|_ z&+I&@dMzmD;;EfG2&JqdeRRR3{x*|SyLN1@r*XD~>Xgq&+pyX6F$iO+)?# zR0JHiEV&3rHVw_ac&^=7;sGh`(wUGlbX2lIYE1vN~hX;(e{P#j_4(=Pf&ZOl3_LuV1*nwtHQa25q5KMQ^;?#nvj; z6G;u;pPilpt+OMBJy-1N79Wo)s1zbTaQER#MKv^HZ>LabPpzX-D_ZCm z;uf;=WknYTqjo+m-ZsHa0^;x+#x%6ymEwL2A&cNF- z3ADtSz1NN&LpQv#rF?;3r77~B8;k7V=I-iTPY5$D^7mbNKd&?^(}{6rYjy;~NnvpI z_7RokCEHZk-Z#=xJT!Btwv|6s`XfQ-GbbjAWEdOk@W5oS+2Mg*CC>gqP6BUCk@ z<7FmH(ky3>kZpuUHyZbul`v}(8;fj46;T=s`XY{+qA^>WI$O+c#>@n0Gyf+*fYX7U zn87oANGvh1w}VdhK+DOZh}NMY_WM|yMa6oVU5HX{0CMo5nhrTd1U)aAEakm$I0#lo za?oMm0@L|%`-5cL9+2^>VaGq+2qS%9$bA6V4QcG^!!-;&b~us?I}kV@IT8g_ac=Gt zzMDw22hf?x>@p%v!vNXj!)lQ+z2mAu1_KeVkRBiu7WAH*GJ`LOpxXqy1(MEE851D) z=g?}P+b8Vz?d-P(bXDOpK1@84wkC7!`O4x^_m>4fwEMT1u*hKb;Q(;|+skGo(La6u zU#IJzrh{Hp$RTeXon!tWGSV5(xPQ*q5jZ*oVu*OBgpkk0KZ8T0GvpKj;B5(xT3$J9 z26AIaVHvBt%8u#9!L|Gt2OQOjWp?MJn6aI7aumF3JOgxhIBtiVjQ=Mq%-(o($M^Qh z=-c7V_j0%2K|w2&J_Rqhh3z0dQKjoq=b^&z@1Vf%qC*?gZ&tg*!b+fwq~sk7yu|cx z3*@vz12CN&1%A#Pqy2O+Q?Bnva+?rCBB!_IyNA^0vwX7~YCr?M09g}YLrBJf33%KwDHtb_M}h$t1tVgEyPxAFX1Cqmt7sQ*kmrhI~FWVy=UXlp>fWj zA1}Dpw=){9Jz!3i8oyYg%9PsbDRDS%FWGX@ady~IF)hn;mHDkX+(B1aAVSJE2)sgV zEC+%N$7T2kr$UUBOArMHB0g?aZ^A3KD*yguEq!Po8UjW(xa7bKm`-KrrQfRxIzS#e zDD&Q|+SJAX)Dc0IBe-z8ff-ru%N-=2D|XIETR^)aZ3o?Ip)K;TLAUVW!yfu-uFk=V zhaCy;t$(an#GM<_s=m7INTp}i_F!v4$u3#5xG)R-!KWP8i?t|goMRrXdCZ+xA$1pe zF08Kyspk(bbr+#l#~l1)nJNU7S_O--_Db{LgbrlL67%LB`sy`Qb%dH&4b0V9Px{sz z`!#(fzgHRhHq~M<*&U~Ak6XuIs?l7z?OX%!l>Z-T(^mA@i4uwTgplJ`WzG@M#^(q( zot zK(|~}ih`zNZljm`|89F>*zp;R3>n>jQ{&Ke@$0d%g-@}6b_p7n(SP=a&V@^hbV%UJ zf}ucwEVwf^2eReIj{st95R>kOjIHyZ5H;(n8ULMvL~YXVsiG zJ{*qau15&=D@&2N{S^iTrmT@qn2;8HUmmrwVZ{S#eI3{j%s&P?HgQ;oG-?|txZ7+LOxUDhk>SlzLbklPS+(p<6J5G%DKtf ze0%i5gi|Mlm|JJGSWdH|n8~elPvg8Ml)mvTyYb%Va>kNDHba;?4%{=E1v1${jl4>Y z%y-z=%Z4*ynFhH1g@`kWmgW=JF{POwu)Zm%hR{m&*I#Hzhs-!AX7qat`|b}as1XAx z6mJl32L}2~p=HZN-AXyLuxn37-!XbT<%n#|rNm|=HQEuc&U;96Xzi9A5?GY8p1!r- zG`z%P#YS6mKi}}x#^Ur`>ig`Xe2KNYy1x0R8Ytg0Ul#jT9@Z-GD19O&uR>fb<|h-N z3x@gGurs?lrAj>S3z(NC$clfXO7o~hG6t_ZdJ0ZaVoYD7uSDOVh~{Uzy_8y|aSTNER^!hnDVFL(dvFzMxJge?(w`*6LXklvd?IBE!ip$tDnmCRlE~%r@a3>=~xXZCfN0sQ5 z^pde&e;Z2HOb}&GAQzyJn*@rkD9clkG3^|(NNtZ#5(+yAEo+}pptz0!Gm4n4W-Yar z+T)1pKgKsX`dtF%?%eO=i^uFRvn;QyB;_BDj%we$9hrTj{f5Nk^bE>lJs@p7RIg-) z5e1X?MXGg-yMOxBwbmu77enmmsq1Bm=F1AD%M$}995`>icr83DZCAM5E^Sxt`c3}% zz37#Wk5V#zT?%C(`WExKEjIS6c}8U+QVsLDH*Ijj+p2Q#oenWWkFe|vjj$q4{%b~W z=9wBRtzdT7PZRS-&VhYvXY^-_Ivnaa8->0OxuqNvZzqX~?PGErPLDjkJl5A2&=vR| z)z>xldaU)w7@zi?Z!WxX*mCZ@h9Vw=2non&>LI*Ef4PbmS_V#@yEh zV`kq!61H?A)N+1jJPW!yw^BxfhT*`*CksZ-q6NMlYwITE1noMC=a*xSaMx&s6uVqQ za~i0sv3^xvsG^Y1!iI{xJizd?iXsoR7ua`GdnnRlT1?AMji4r6+T}yW`J*m zwjvCU39doV+!9g!`fGfoeC;;8z;lT{eQLVF$bM@psn`53}bl-AC^m zWLK$Ks<5Bm{;@>kW3Xih|6_1Xia<+$Q6%-(PDJ#;Uz&h)j;Cjw3o|d_61c zr`J%})pC9NH$r<417>@Ct6Wo~PalN6V|t%{C^R#2CiMoX@oY~-;zwN za&rFE(>j!FdmPCUHQNI22)6}bW3#B~^|PqaG9ouM@38C4AMQyOIrW)Scm77Kut6|( z-{i9ccG?cHm}JQKX0wnFZAw&ivqZ;w;Y(Xvyq2Eqbtz@uujK zXV1T)kZIDOi#l;^DKD~7a4S~$*_Eczt zW&fh0G>qdHp6fia_|zZYwc8Drl9Qes!W62A7cpY~!_j*8xn&=+mjOBc)4c{u(1N86 zdO^gE62N-FIcd|nn){-`5+qaG{|c6ZZc2$GmNAvGyIkt5LgKhtcBm70O{FGm6s5b~UY< z?L++yLz&8hH%$@)$DN0(+8^Y5N;0^UsyE(a#=>t!jbUbzZZ}x8DsY~|4JB3tec-*F z!T(KQ@-4(K`k>(WLE$FxaIYUM>9>!cByR3aUBIT0gz~70ub`=kKTWDxH}o?eZlpAe z?Pl=k5w~FL*l2DaF}f|=9ORNir}!bE@zUjUl2Vg#4LA3DJe71GJxe^9X4Aa*{NM+Y zGF8vh22Ts~SlnLp2Y$iZ^rPQ>B~fmIyaCuj3O=CE#oOv=*^fAaW@L@yHl_h z&&fPz8luElR_5{ZJue~L?^{^efKNbR+=05e2h&&a(39q?M@jftGlld6K~53<(_fBZ z-_t>;q+~YLOLs!q#fR9m`{#VrE3Z+?CiR={fB)G=ZzqH2Yx-RaHF_+tXu?a0uBsFl zEqa=sr@OxBNz}(mG@kvYWex$KbeUcXS)4f%`(5MA5lPc8bk}v|1vrUibqeVg1s5F{gKB<=k$3Ma|T~^71j5_OSHD?DXWyX3SMZzgNIFa`JzgEuNvdC%R~FE#n-od zUj;>5cD$ADRbEj13%lIUhIy}KG-GX;-i9R{l*x@xcc~kjcAO3s=`Ci!89AzW zK33#%+xf}{OIyv%V=ifysKEQ-Al;5hA8$J4OwFCD6tEVg2Jcmh@jd3%JMo5(dOW*! zpD)H8uGJA9-h0vxg6vOI=RQ3KA1>FGbywHVal>)lgsw|8Cx_AbGc!LWawxc!lDndm zlC|nI@M>Z27#Dv^xXwOp$6iuO{u)0KHXZNKocXR`T9f!4M~#K(TyHdHxUu~b&gMP# zU1#EV;C0_xI8C-LvB{to$O}7J6f!NAISxsQy%UEuZ!e3Sn7VcUwmerO*J464y-}QJ zZ*eBQk;~-1RUwW`cV#`!KCJ%PllhU`BuGW`TS;lMi__#wK~7FZTXi+s3u$!ch*RNJ zrsXd$p4NU#@gx3h&&8_+i*=T}%i?}UvC=Xd{Cv}R?>%3ar2Z^60!HHe2hu`|Sf* zf9m3^ZQgzFgZFB^oJ#AhcqpUQ6ZI+j!Y_|Os`sDem6OtS-+qRhvNmb=jRMoF1@IY7 zAJ&yORe1G&-=6od&Kn&$xY?PzQ)kMf+zu%x#iSnETo21i^_fuIV8X`FuYncL@T_zx z-_~t+^-<4fO66NIF824BnI3ajDfac>7=GUIg9K}VbhFOB&{aMZGkf&qsjpAs)AnU}8T1a6?Nc+hR|bZ35p)hJQ?UdS8Z3pq#IYJVm`+L^HpRO6NYX5 zbrHi1)F$Y#cd@qY9NFpcc;>O_p8oPF;Qc;Ec=A65RIrQ6m;%-Ha)C$QR`~6M%>MVm zZI`uKEXk+$LQMf`^5xU-gn9-PZHQ3fR|ZrVL~BcmVU@Kq;_ZL(>Jm!YLp>(P6xC{R zDXJXE)k{%7Oi}pK3gOy96ecXi#bAOOS!fL6za4+`U~{1{?R^eqx)9#zJ56ll36`O< zOFO-P9=|m3UL0l1Qc-JVhH4c|cEPPs5aUm<5GEN=3)?OY)QF=-r7C8&^)o&YjJGL9 zVcuP~91r634Dy7U( ztu}hSEXYNMOARa1P?Ilmy{mb9PwQpo_k4Q;(B^NnPvfX4iKJ4UXvmFU6|^ZqVN$eD zi_tVvSX+})^NR~0_+sVr1NGgr{hGz+_AzCu=`FVJv9cDj`q_WT>XJ@nhX3c`3(=Vm z)!VIRLP+5>#?^ai1{bY_TZRnVs?oU70aQz(&7htAp=YP`33IzvIx^ptt@k~cU4$FHOu1z@PP|M>p4%8Q?f@}TG>46c z6wzS$r<-J`1toLh4-~R=)=eo@JWMJO0+Wi5z=}wsNLUhbJD61jo-jMn_ z5IuE>DCNQx(|ZWod{?r{{Ul+0< zPF&}$h_^^q>Z!OMW4^JYR4dKZe4E1l#Gs|Dsx((($PcM-E&(-d#eQ%vBQLaB5w~5I zHgSC@vKi5r9Ra7mN3s%1PyZQXz09$&y6|!5t@w0^&A>_NR5wp{tde8CLFsTNsLd+1 zcQ*#YS(Er)hAd4Oh#=KdJ{UC&XO1l?hF%qTi+IStM1Gqd^3v0uwra{@mcjRb@qWs; z@(SK5kW7m##xm&U9NkeTryLgFKO=iD<|!8hFbjX9;XdJ4(8(;imio(n8Pmu(^7U~H z`}SeAqcRnm{@0f>QZxHqNOZbP1yY{2N%_z3oWr?aTJ)CR*{?6u~5g|kcS*}mqU!DknEp^gYl5idxSUT2#Rd7 z<3S<5!Uy+Yt4uAAXJo!S#wCE*F`Y-Qo&e+FBlulmw_52HAkb~&$tuatr(@vBDsMkb zK^Z*yLHfa0=%h8^GzL0R%zrqE;`0uXE;z$3cmi7`cnZ=PNM|9bLpl%k!$UmR==bnA zJ%F^0g$H1s+5yzTajzkLrVb{7EfOrOh=*=C8hWAzw`IXw(9)J{Q+@fZ;w}8ZY{^7t z5I`GjyC>V|GZ0`$QSd3iLEOPs#e-?|l`#d_zQ5=z8v* z-E;%bFbT2(#}l@SdBVt4;93>E|a{ z?C+GnwL^wgV*+~PMRLp7`a$u8E4uu(QzkO4g1U3&Rl#=+rYeJ?nzRgfOX_1 zuw?r-CHQTw>+)dfa#x?NW9R*mR|REl1K@2o&14-3Vo!~5oF=Xx3~MEA17JKDq^=jx z$7y90iw^3Ggo%FKUHrkVv&Pc%-uejzN81pE2F=JKhZaI6(anEqyVSU%OdY+WrSBM% zV?T*wr;M8zM7V6IyF!yu9r7bbwAXEh^oS8}ND^ah;o9N;A~tj5awL04j7M3{S>`#8 zhhwdmLQl8&(Iog8b+6m$%yMFaW+ANQ*?+@Yo*&r{;VnBz%D1u(kW9A~QR2?&=OTuH zGJEmN4(&)A=lxXzElI-e*byi33V~b={c%*T21`FG_X4tYfx3SSsl)#Li2{*RCtc+~ z?_B>rx0#fW;%MXS0n!fKxs_eWYuB_!9SO2AIo`+N9S;K3lGq>#ut>v>V)s#7RR#7P{!}z5Te<|TDCTIcB3)*oX4B+$c8sA z$Qa0`i2`9n3K1j2pRYpN{jYt|Qae#CUpU7gz zfc)`)Y7M39Zy|7)CmPG@J2yZ?1)2pExT2m=8_ z69M)G##v{`feFP)^A2n7dH&Ve@y`5PLcJ=-Zcb${ba!9cc4Reh<9ka6mtWpm#?nQ9 zBoYwVZ#M#p=UVbNJQl|K7aY2bmz+yOBxL44t~)!Q_cv{eMvMD7=bZ2gdVlYyP~rxg zP@uaqfxe?yG}&^Wb_sv7<=2{bo#CJHSoX)>dod@s6;qBsCBeE^$&=o(v84lc_9~dM z0gQBy`kO>)nV{?rWB8Dy(a565`Fnv?DDli;mOQ;!8BX{c5ND-BeU4d(`u*S!ME+EV!;cWUsvE zY5OqNY&mry!>n0_eti43*b4z4BTZ=ZROqcHs{5uom#4V-C*~iA>L~h!2&W%Hw~Rl{ ztYDdt?s?$Ojw#P)#P@a57*E+#;yiNE`UM?W;VwJk|5QVG7-ZrxYoCixf<{(?V6KA( zNnVEwI}jLvI`rn&WRKK&%ZF(|Zqp9-fA;JK_P7o^`}u$O2rs&54)QI943G@u`}=)+ zAfd7?zjNsN1bHmT9fh<7P&hIum{%aX2g_jB7;CQLz3z>r!B_{Cy!5V`35VrgiX9U* z7ifvc3;^Hdv!_v@s>x^1(fR%-yIoq>>6S{kTjF1KWC|a;v9jMuYw3semBA=V+`v|n zErj5WHE4aO;{T);;jRq*0<-EhmH+)w@@JUQ>?izp_I5+GkAo+)sOEdUwx!K zTzzK_^3{jj*45{rHFg9>=u1Bi*6Dz~u?%~}#>V&C*}MH)j$D0cS`NGK>jQ@94_o(V!eAIci~4O@oLRdhk)3HhtbD<4_G>0$X4E`_gqFZvL@rS zVec7&JGq4IIp`S@ULF)GV%hZ5>W|V$HvQ;6d@f?%%bMK8ko_%h$ z2H({ziEku&Ho_~gU=$sTreuTTbUj3S48EjDK(25xf5gd-M`@iLKb~_P1u9k9g#{aD zXH`m!u4*8HOBf#`!;;+RA%6U@*G|Edf8IAH4B6xsK6>^(sl)t~j-#s}f*=)IDd{nwPK(aupHnG+K7J}dA$`26@{TyH6GpAA{ErXmnKrXI(hBeyW$BJhLIa z_VRg{?~-xynb&+&zWXtPfa^XAlH6Mh?IEL4)5@-loOdHUJ$X$8I?V9+VHzuxSm#LV zOob|a4aqpKC386B_O2)b!6m~I;;Qk}SlL6hwm=4_4i<$eb#Sb}Gp^D+;`DzgSuysM zLctEFOX9(#>}f?Cmoo*#zG!UN(KLjFA49g{{r zGo_3-O=wBs0qw|1ML-U^atAT7<7H#>Hh9mN+OXTh0G=nTw$}fslG3jU%PF2AtnNd= z^HqbDum(1<^8exNEx@X3zWs6H(9+#fA}!J_pnxDCB^`ni(jj%|5Csk`NSBC!bazR& zpmeu%H~i+{``+*S{oZ?@=l=iC!(#TVS+n-+J!emT)*2gZ4jbMpI1aQVf3UC!aCDJwH6Z?vJ8(G4-Fp zKtT+=BRLQQClJ8{V5UU`#qRoZQxsVx(1QS-pdILEK!5{L4uF{xO+|FQ0 z)GrfnK;`}F{qK%M3)=SKQlfePBkN{HO7w8SyPv@*&~**vDoM5pb8pZOTPS?)Hm4Bg z9#x?0iz%Rt^hisn><>3Znd@AW*3+1B_j;B zTpdD?%2yDhfoomxSs7QcAhAAh*cLRs@l*T)aZ&Z%`L$Y=CYqW}O+39>b=i47TeGo+ zJ^(5jg`!uDgj%I4PXdhdNZ`RTrWWwr`Qz-J-6HV=(@H(Sg86}-a-aAC@R3sD!=~AE zTU+n|bd@0Z%jV&)H1K_aQ{};j9iducZNtelxw67$1is3PBb7!H;D*|5Iat-)F>8cn zuA7*t2|M`Y?yMHD5AWY6&H_ah1`syD=JS~D(u{$dS}e24-+t1C_rWK96afzgZi7D_ zZs5};IPdn5*FWn&ORCw{Hemot4yH@8J-7H(b0PQ_O~nEF_(=}Ht6cq)^rz!e&A#op zvXpLzEg*n*T=0@OmH|s4P*Bjo==~;w_tTtjG2wGJcnqxF!2{@DJ8%LlAPG6OqZ-JA z<{m!%$PFqPu?W$X0c8L)BX|G+twRp*qX=IE%_46qAL`)TPK-bdw2=fHw#isMpfqei z=;ObI`+r`|-vyEf89-^^4;dqjqW2*dj6A?v)bj2310MDdT2&Pkj|toXjuX6f0@-;K zp^#irEd+S)Ku5#@j?22u1)oa73k13$@QPCYB>nMB^L*_k{MBxf5IIwVPHpHP1p%Ki zyZ~S@2Y)6o{{%M%gE=9cnFaZ>%fw0A*~VJWN?P_C&EaXMm6ee~|K*{1n-yLpLYs51 zbLk#$eORAM=r@**0-E2NPG+)iVC6du9~fxu9P^9$HL1=5*vi`x1cdf6G~d7wZ5);e z3q~lArSy5>IVz_yo09(;Jp3*2&*9qW%!Hmj$P5}Tpc8Hj5P540Ky?-h zy&n6fx-S4X0$4w4JjVm8XigV~p23e}bsYkxqTNzEQ_$~6im5!O?@<(zqIv(0Kzq9z z-{I~rrB~G)vYia^H&{ZmamcSQ5bu^uePRGM05T0cvT!?T56iF!YHc)vYBh6dDa7}{ zc$=;n0YK)l++iro$5eEV1yV6Ux+Ikytg{m(lc5}dwsrmHSMkbJL+mAy) zJNe)ydjEDWFo*?;_~1?}4EXmsD|=;Z?7{u`;B%QMkWVK!NFEdcOl4UC*G6{hMHeU` zn9JS@{lV9R;=zmfPpZ`bA#p`?)s$`C2(2> z42}355)(@!!7LBFG%&+6W4LV;KrZ;02%Z_NwpcBZoEXwfgBIc7s_mk!Zu zNMWwLaXWc&=KjS&$dp8S&z=9B>;77Jsf%h9PVj2Y{>;{S{f>XniTFyh=j)=U2V+PM zUONFvGtfkjy_wmYL%W;pF4~#P)#;5<9T#T-t0N13lg5PM8BW&!q$-rGYRr5#P5CzRW5nWe)xJw$8oEI1DtJS!D;yLNtt zY2BD^bM2)lj)HgW2WozZ}sPIlAoLn_ABfC!*!0mJ^)67Y~I${-~c9y~7AKFu_IK(Jym zK?XC{#6$LE=CAD#L>r%cpWg8CG!MQG&OKI1;Qeum#nk1_N&a_3rjwoqoJeR}gU#V> zJGXc*t}lk{P^4H$5LgKT2NjtzlnlRQLN6t;+M9jzGq{gefAwg7q*}epsQV2@bS*vc zeox{nj0oZJ#C!Zl=FLP%pGh|NHkBkF@zye7$~E}gKS-Kp!I3NHHZP;A^a3s>*zbeD z?R%++yLQdQ+-5oy9HAz0x-l6fuRB~*XpFg0ko?^1ppxcly+u=9*n*!X*=@JY-}C0| zLcrVWD>2Ul0h=j)J#27_x<1tL8d@K2+pK?G%w^EKP0mKXt53y^UD0FY)@WGwiS+xL zSn5n+kAL2hHsR2oT7>e&QkB4d7Vc-IFxz4J{RPP#{P8|0g9(}T!#NB$gSc!)BdH1t zT=`CWeVowEA2cx$i#4JT9CAfMJEv85sUp>uUq0TBi&}lp&V+?N&eirCUptrtZ@(x; zOm<0YXOi229bpz2xpUrK8guaN+ur_MWaOf%Rg|dny0<|svCG0vl4L-=*N2Oy)w*jT zzC^9>)WPl}dkTvb$p8^uh*@w%8_$!@g?Rc`d(ZGoT)&`ei>d{H1gu#?ynAy%_|5=lNrAM#eh<{?I9~P+=&tZJS{!IfSJ~$IlQQ4xc4|Ldi7iE{cy5 zQwy+iIex1Fzmrf(uyQE8B-_r;p|_ms*>Ua{pp^7~T!h$-jUQ;jqf77&m%lndxfGUH z&4Oe)58S>CZgRr)74yr3M-ll3`vJ;FU178iGSCcc!(;!oV-qppZ+&}D_WT|^_#=w0 z92i9>iK+QmDV>Rq-Ah#O3y4q@$F1mcPK;A!)(u2~jbzfjiUZjkvIpO-6HPn-UQE7> znz!B>#8E}f#zzEsWY|Xg%TWF?&{IjrhN@}}rVx>o$#B=^tMuAf5>FJpNXOnFnkWJ` zb(1XY<|4P>R0a5^bpKmtIMpThEgHNwXXZfusi*1KW<(QqG9Vx(aRNQ_DpBdA5O}9E zu3uqol*(l)GT99^o>#*?0uv+0_3~tijYn(R&rlV|eJ#H8R_XfFis`m1A;w;BsG&6( zARbffMr=coc8jb=@C84I)F4pBMw1|A?{FZ7_efge)=^OQXex`fVQsg=8b!bJ3i7|M zP~2Uj-%6~2UTPmlD2X!;gVFZB_F6O#Q4YP3 zbXSa0!*e+5$ihA_iiM-#`4`MG=4W#N(g1)BkFuS*2Q%9#*JENw_)7*uD2Z}fl8ACY zIgYJB*AT2$mUK_Q^AoEh&z)_$81D$4KjMHcoUI952_tQ*KIKD5QTAdkp<%}TS})3C z#lKEiCCVfYbv^mLoT$6ZZ7&ZkE;q>t^*ml4jq~0-YrSwOY`FTJ?w)zn8PB-HV7A{G zFY0g)|Liuf{KNPb8J^U|U{)d}?r;xWvHp*VGJg^=|0L%9BjOy~~`wF$s?=E&egJq@kr^%G86!61{$+ zTz>1_y2g}+Pzbvs4}u^`&pNrQ7F7v^-PaXKsay?1kj73HRVhmiaqRmW4MblPMz1%Y zk(y-EF-@vi7y2nE2DEJI#)M6dHgf0G`9J!I1hPKs(7;bLd!zxj<}nMoQ#8qJpFgwU z*=4czlOYDRppqFJnMdzD=+h1WiFIRA$VwKLr!f^T(lIToS-%0uk8nZo*b`)m0cXs` zqhJP$^>WoWPtG?ZCaH z<#tCU?yTfRfce4Hs0z!?m>Rv_o8PJpqCJAHSt!pHYHnOC#tmeP9bN`q518SeNL*g- zANK)7P@O7ekt1oqCq;ggkd-@F8#XHygu{lD{Qak{mi zqqoN)qP0^mP;-2w_aXRpaw&IjQGrnm?|sfl*>Pw_X~QW#c{eZ2*;_|YRJBfq3%crg zQ&`T?*h>82jV*4;QiW=8o2zsGjX8q3Uf`n*^h+YpD1(zCnG1rmn#9%G%&S;q&(C{Z zGndtMydR8yirTPP$?=6UoM$T z7;CLjP9AQ3b9OS}6KpHq8KY9i{%^hGtY4nx;_XObQ&V)!z^_sDaQ+fqpuOR=PYEqeHZ_aw=c?F746z}v&&*@C*k(F6 zykO4h9|$@It8RAlb&2~!Xg(FJWk1uBF}HZvlmeATb9;V0({R$6JV~&&9a=Zwlgj>? zoPM=XB)L}Bz;jqsWrZi4zk4US;01$|&LX++bpE}yw!~3xC#O}(z@>^ zVM0R1B8~rgEl^*oEG;mOohmw?*%40NB zo^El!&n7eEI2M7!OR!|0_=wMOg1)St}-sj^0D3puVb2L$CAo ziW=DxfnU>38|Q+Kk#V1fjBJt`xf`ZRyT-!JGDb8YZ7zB~3gnFXN(>;AJ2 z1xch=b==d4(nf8+`JFK}zH@wf*}f6?4IdJ=et+8L*BC_-rw?6`;l3Wa>+@&p_F5&W z=z{mZII+KYg9@R^wx!Vvmlet@Ybx2H7gh>HXLlto*}%M$r0Rt}_NHka;c=70HQij* zJm@L1F7Mj04k|WXCX%ArI*3>r37z2;QF$P^4t6Sri6Kw{oS%gPRujuInr}y2B6`!x z=jVZu$hZiUfvllaE&vM`D)5A5tB$6!;Vz3j2Fy&@Ms%1hwDK`a{9fG(HMC8HhKOh2 zj>k%T8n?k5&p>GKk?RN5jGuieMDS)*)Domph#!2@_}ZdVfVn}GTNIYp0vb>b6?s!Q zaMF4pyX@!|Es6?bMGa*2Yj*`0VHNJIt`BW+%eTy&855(LDzhM$| zKVD1ICT5KJFbID3EHUFUr0LImIDwG$Y3_3%G~p0Pl>RKhS�?eZq7Rn|692Dwevo z?trM{yX=gp@qYCFtLH4Q2JbU|?Iq(ir8;{|%0(H!wqQDW^MUfvp>Gb-;OsEal z!g15MV>3HiipH!we(xb?tpl{ip3XUJykhdKk}Fkzv%5#@>K>LI`KI;n;RgofmzRXq z&6JguqpGOGbMyc(ZCZ7YIFGv+wv& z8O|AvFuC>+BLe8cOFzjl)+k%XWQj(=n6M9wdFlhHCw0urJn^&9aAJqe>dyxD`oA_j z+||#|nsGB32~6B}vNmy=$r$fu@I2?6CFAfft=*rHnGf@LX99#l zu@y=H2m*7K!2skZBa#^)Bf=n=nXDp}nH-rm)PFyHs9$c-+$;tVBgm>VXa%m})X~32 zThEi534L{N)Q_J2+U)TlazagFGQK1l?^^*820t1N%*bRFLjCQ~i8Tk1imEu>*Z)3^ zLsPDrhu*w{SamxTy=Kvr-9<+6uw>lr;&;#_sNkQKBK5WQiMpScomVe;`8RD{QoJ+9 zw!b&q)gD|%pF3vh zRMNbO@WTF{iPZ4dTUx)u;Qy}8*ez+NuXleB96jlqIc)vKNBkwvcAbC2Y4Pnf+kuwm zt7%VOiAZwJ4kc}u?CIZk?U~kpaoH!zo-7&vWSNzRZ8(RjErKH+3z86RvVqeGn?{B# z3e8^$)Z_WpB|i`f*m-@}dhX11vm#fOw1X(OPp!-Nx0b#Qg~UWn(k8y1(+&;A<++`|A0^S0N;5T!fIEy#;4Jhm z>41O*cVCrj!&85Y_O=7X2?ZX`6x$zq3HEy)Y&r^rAi}b7$6?PyfyFE!(b=eQW@<)1 zr`mLYazs&xmqDax7$!n1wzZwI>vFJ3x#28E3dv~oE)dVJ)FTQ3!a(u`!xhj9Hek}A=P=Zvn`zmufRU3 z`{q1vpX+>do#0I5dLe7f))h<7=AK>v+Vzppa!EaAShy0 zS3-w~pdgKe6#EVWVA{F6m>PE|H17O;MmR&tkJr+E{9|B3^Z*P9ry_iO0Q}qrXo;od z5@5V*)RFB3kAbtp;Q<&A8kmR{KA3?6&w*kv5cHEG2FHUlz|#?$;5<0g8x#o+^`-=8 zlmn=@03!k%>OBPt1c!RV6aPo3H#Ww^99+mz8VP|P0Lwv%;iz-CJV2ep^}|u;bdp#} zbt+&0ueGDOX)9b?uR->1iI%5zL{e~ubt)8wFQ3S$8bviWD#qe_Jd2nY;?S3`Ms5EeUacJde_Vf(*`ZMqPG?ki7mSm*x^A)1Z z8K@ytX%Zo9`=e43&8Z;M2#uu@8F{Pvz)-COUH8qQxxvk>O-gDc=lAP5j0zEM4nEHO zBIEjg{>2<0lVUN@01?D~9lkSy?HMcDqT{g0J!z6e4CAYhX9aOB5}i`3_JkR{Z`%AO zHE0lBY(cLqYNUhimXC?jd_{Ux^mFx4X+FEcv7*fxidpHfn!SeaxQNqliYeH0;>f87Kv<1La>@v;~c-#a}u}1g7mWU@Qe}_JHU%hzb z&@`(On5eWnERqAE#nTvr;J{X?U(}jy1d=|1-=Kl4yi6f5O)_P*lCe7;@?7|kufb{0 z+rFx_b!xoiV+yHOmZL{6iYT8~bKk>gmiiT&XZ+!AlhiLTdU+#HG6{Yte+DmyK;3`- zTr-X3CnJ^Dnfws2v{S*n#d!W1u>u6~Kj(lJ!kz5+khI`7L+_L0pW$42_yOBra7R^j zvdg$jKbP4kV2fY0@_yo@GC(bT*9tn?m|vFpP(lhmDiYo|f=PqmIFK}z*7*P#>>v~v z1r9S{vYU_C38t&GzLd;-*NOp{SU_3{FtvcRofKgD0clcROOX8=V1V(8)ph`;yOM=I zY~~wg>NRKWvcY>_XEcbt@({uuCbe@e;nfaW*rKEAuO%0Z`Q5= z!bO$hk7_gNIzaqW6H@06W6nzPwlv(UG{OT_G5m_BiTx8s`66H1cM5 zc-6v6izcHernYS4A%8m(qKg|>;r4H?*Y5>7e>n$h_I_!cU!*RZcDYfkBa0Gf5@$2} zcBh|m&Hy#Lfb=ZRtF(IfCt{gKdOqrwx_P#w3u{?f4>^L)#PS^o$Cd*+xVQ^AbmkUu z{)0a_gVM6}aikP#sr+J{h0uWjf^cOI-P#mL=zBr;&^3f#1p0L%H)3)bvP-2pQNkdh za@>Oh&*Tm*F}Y`3INZsy6ORE#kSse17!#H+0^wQF`rtY6oWMx3S|3L;oHbCcHtAlC zRot*l94N!Yu1305ob+HU+h=$X_9vhgFc}AVq2fb5&O(qa4a_}?z&osgcPIiOAIbgO zLm5)nUe{9j#G>;{DWFrP_YntLp=LK(SHGO`kWCf8;I*Bn-EOG$ygIJXVKsjLVR^&z zl5y&#kaXYn(GQnXi0bo6vv#M0Y;~GG8sx0U^OFe@kPIonprD?CaMav0S3Y*~JGNM6SSw0? zI5}|haO|@V9yI%+&+(HuhaiMQ#5mx1eG9*A^F6-1oNaj8@)n(w+(Ag1nj-o;n&C?% z^J?q&gU6pAWPSwCn8@3RKJkXgIA4lR!HZm7uFeUa*jNNcZk^3-(!Kp^O`Ie8f2e>= z(~L@zbf7gbQCu@8f66$;GqQpHE_l@T(-ssD~&JS1DK{rsB z8|kekuj{yr#C~g>&1@%B0M6WQzjNVz9~Eh}YO-tFYx+RhHL5*qEBxYsXxYh8jkSp{ zNhH}VJ22R8@ocQjiUn=vlO=N10jn|l!n+uJa7AD|2K~h4Sb9Pk-u8u$a5-s`LvoTt zAmxLiWqPc%jld+5otfCDUx%E2!#g|Pr+c56J4A(6x_-Lt@1D&JfB1U=tufzm zDbazR==Nw-qImTCX8;;>#;0u4c+-$zxR`yp$EL{pC4uK*p_UWboc#1iq^I0eU7vL`D+n*q%-8gLU<|B)K& zCkC9l34h zBip#&G>}bV<;`h_A!OfSi&P&G>?$=;`$EK%VCIy#`U8jHCWF22{wp8Q;3pbNBGT~9 zMfwLtBZ(#v8D%0;qJVjOaJ+!IsX;*nq$wd@;J)chTD)8J1OWmRTZ{VuwXZi3b)Xgz z=~r)^#RC+yN-8F>AfS#fjIEU({J^ZNHQeG`g%c*aC{%V{1jhl3)Thd9Oh!j8sZ zy{a`vk zq;)OBa}b)*A72a>27bnBZDqtjK7XzF{)W`zcM|!NWS-0%M^mD={mim1^=F^v=(1rF=)SYS7Tb*jFy{x~Jv=x(i^1eEniUjV(zES9Ptp~kxin2u> zP)Yo@|J#@Tc#RREQc07#v_E~U4!Xs*MJtUtn{MV(VuUyU)E5)8vR0^J#8poV%NG~BOv*^P(s0WP-*h= zVOsrDzH86meI>3z16s=J5XZ8}_q*BIh7wVPUo9AYl;@U{>u$Cy&Q+%r%?jF4l?Bwk zdW2zbJI^Y5FKz*6SUU#46e6nY@m^{B^?t!y`qJMKtrh?N<6US}NN_ouO)^@~nlpDH zbM@CxNHF;bv92d=MCR&#n@>4ezdXt$c%|&1QtXWJQ1buRWl4Z3Q)kLjhVd4`E58)8 z#dQa)Vr}AvYfl{yFPDqT-zQ`J*x~$G%Ij^3I`{N@JlB-I*|+Zd`WSpX7^_b?<||OM zOV6_=@2S3uI(<~-xlpl4m~0kL(W7-)ca^plvd3oWvxFe%R@F25BIF1RTrGSaH_0IL zV;24N$w%7cHOfYCp|HyaHpO;@;9D5us@8-r$+ad`O$jcDe|+}trBZec|3QklcDoYI zqKr#rc2wt}q8UNUmYQ!bzd(h=L+o&mrFPFq$sM|T%8BhNHx`kio^PmZQ)9b^VaR90 zJxdlXie1A2B3z&HD@2t;meymVSAfj)@8c7va^g3R*~RJW7j8P6{_H}R zk1CWc=KDjIKZq4F?8OI)6n?a#DHXhI*;+Z7+`SO}*y%pGQwqmjsZO|d-`B#(tHD_eZE+!_BPy*>!Xr@a^_h zi9p1qWGs=9VA^gGMp@vB940t{FDtTOPP}^?$Wm>+&*ZDR4XEwQ7{Z*fJ-!d!3R$)d zdBrCdP6$$je!65`Fh6jKLFNCk70K|(1+o@~FpZy9iz<%fBnU*qbHu~c?y&MuR zCmXh(?yuFp{kr_Sd~kS~_{Rj#=kSf625PI>`1bPsEK!1n~O!s5Ig*FNA@~3=9MuQlhI5T&purf zkd5^k@k-Wdd|ePF%WDCfZvFnntR8>1i#A9bnUPLHW}|)7gprUgMhFmnf?~>~o7U%~ zn_lj{W3bbzn}>+9ir;wY)y*S_elEF$h$fNP3L=8FXw+5>ZmqyQ)E<~X@2sexnee_+O(`&PKYYbtZgB}4{BfF? zmbE7!rLbu07u!CI&H-!0(4p{VDC51p_m===nj=W;2MH7AL{XI9gk?WJaSQxca$=eb z1*4(l4xd~>#=oxWyF(33+9i30;CXRa10mlcO7>319>>8N6I1<4{_~Dbu)z#VKN5Y0 zvbBWU@?30=TV^~R88Xm#&m;L-1va^pRTX>d{g z1eR#18z|m=#*_Vf=GiK8+slfB$?c)laRQPj2_L!O+(Om=TtDU`6g$~RU7Pw_3q|0P z!3@Nj&$PF`4r9XNp8Ks98M?4k%Ei5l^+W)vgkG3jL1t2Kw!GdVak&?!+!#WKPvBlt zU~LB3mbmL$(d{-29|lY{r8$q?`3}j^R*efs3)+&=B$P8JNtp;IatB}dJF}Jzr-=~P zOpeQH3@w2nO7e&e>17rMml)l8-1H}^NO!}w>ry2r$W1Q~^WNP-~l(1nP*@ClX0 zlt`7vP`!-O;!JaX@Nt61OAGbB6-{TkyN5-eVRZ0Wl}RW5DZjfq%d6h>eN^FcHWSll zmHdO4Nffcg8g$c>kJyUJ*rhR_3J63sZlA)`g9O9huFemSbyEv4#C>h17RWSr z%8~0)&fn1H85*mhF*woH8TIeo9)r=W?DqRJKd4%aovqyrJ%0dB!2`nT^oD|h1ROedWFP$&#DxJPb8MV># zCdJ;9hfqbQ>-@wgDbjXG$JZ(z#C1FLjI;eRt7WZj?L4gq?;X7L7~|0 zVhy`WMx_)h%Be**Q5N#xDQx-t^10t6(dlVZsBNp>WU-erNI1cPUg#o~SG7lTg{j0W z+AAfk;kpuSqmDO~c*E;lc~5^f&Bwg?j!>k{4r}5rAG~X~e{$E39otUINFX~tc~At0 z(~}rMt9$v=)>wHKsU~Z}4PCWKCoeXO7^L^+!6sQDrcxIjB*|tMv{zJbZZCGLs)i9< zpV^Qh(GZt6Ih3*&xrSU25xwvEX^k#;CXFFjEsZbe20|eao=JhY6o^Y35zty07ODGI^zT#9<|FxbkQUJ0@~3-OpVW>Y>;Ej#Vijt2u*Cc zpAYEB;Q$Gfy2!j1u(79GH`eL;g6ANEG*NNAEu>E!zkUoXakVq3wW;c%=Cr&qol(_$ zM_#DOeyCti&YP7#`V|!K-!}P!S?Y=6B-Mmh1f?|C+g?Y&_xOxiIQ`YvM={wM&zi?`~;+=FKqleD(8b$QP3X>9s$taOHh)?@9pbZ`!xEfgEcFI0N1oT^jg z<5JA4isO_IFJuom$lT`R{HK@aB*d=d{GK{#&-F_KYIu9oFuk*QY+skS%!*NQ*+7h%Z;SKa(=Y@0SyuOg;L_p`GPEZ1Y-gvV(c z<#l)yU9c^!?iAGRVAP4;^a$+C&NO(P4gajb@YKZ37_cT(x_&~T`$F*C^G*gXsmWHu zRO%P>`*zM;PePt=+RtZ@U}2G#YiU&lpSOK$Yf+2G+Dgb%t?Me&Wf%RpW>(wQ((;6Z zB;^a)^0>|M!`Py|2NIt9jM!mE3eD1xws6X)c;542Nwwd_Be~BLdwwG84&;Huw{8=e?{5|I@3p*D7^ZI7ipA7l66+OL^?yvx7EI2&e&JmRq9$z`~1B+(`U8J(@ zPei3mdO0v0V72EzMRFH@-V_EUUGmfMJ1s|yc$d5=ehcEkc4}3zcC97h^iz+bkW;=q zz#DDtJi1Ftiy$xy1*dPX7AvOfv;aFR1s`c-&c5;7*}?uA6(%~Tg_a%*>z7EMOTkR5cO)j&NItVM#%hhRI~0fy~| zlb}I2I(BzWB?~X7c<6B)AOFN!2@s=fV2$D9M+f`bw*lCX1u^(0CdlgqdQ5E-|Fn8} zI)lsz$*c&;%!ssyCWD`Vu|)m1V#LAfc9{!H&0k~YUR&K1lzoNz6Y-7JSJyxFuf7?z z@+Vp)As^-hMQE3FogZC$ceNI=nB?3~YFttyUQLQwBd~Q!pbO8pyQr7Zx;oGHIyY}f z5d6frlkwx1>8_^ggqic9vI$IdcS7{_>(sHEC#a)MFQ1yR(q>>P<#4_(kD+kYlafFe zRkc&?oYa(g=o-6OJvl1`t~Z9yygdzXM3Sqy6A3fO z4`zjKhTm!u5uS@yJbyN77<#pkw-E33HvI7SrNq@`>&H8-(e>OmH<7({qDQTY0?)in zqwk*eWoqPiTk0>yHlI=HvkL;hvi<&=t7|xE`Iy#x=Gjsr*fnbD%T!_rhe{HmZ016; zg#U*NEkI#6A4T@PB7DxJfRTU`YT29Z;^jpfEDOYp_&hz14GtMZejP#TQvjssTAQ0 z(4w-0Ws8_B14DP}tzgdLpC6uvr;62xI<1O@P(>{XfhP;H!5ws1lQ9=^A}ph-!Pmi= zhHwPg1jI@UNcN;trY{dF{*{dEB<@5Ar!p{Vs&97ewk6M+h=>!4$TQ-vTTeb#&o-S<4-99r&L*Fj5tZ6_|IZ%O->rcM}y zJ`sa20xKwZe>2`UA9?y9U4>avvIoee9|gol50{$~`o%^Q0uDy{^3vl$2L~y0AtC&- zq$E5YB_#+4Gc%APe6$Kg-~_g4?r4<7!K^?1E;bQs0#=B+qwX$ z@VWp60Cl0P1evzyi4CIj+dg~Dg)0q#P2gZoSQ7bx!2KV95|D(D43gpGnZGq>T9jm) zK)Ldo;pY1IXsa@{{$`zPCl5d8ApO<38DXjD@{GZ1X`Ht6zNfcI$c({27NJXOMaDF2 za%b!4EOTH*zmX&1-7@VTUW`6iaeoU# z5!J|_j%gnIba-G}64~JW7A$nvOMT#j; z9q3T7o(ZSQnyjGbel-RYOl3IQ} z>!+wnN;+y@Ub@`any#Iga*9?q8)kZK<2kniEzRy?BdYyebwumNcpW=n+t}#&b-;Uc ztJhoY5^s|0!23eFA*ucRjDe6c+d8(UZprJ+gPaPhB`z$B!gXdh-q&|a6)(kSbt`4B z_ITFE1OpnAy7$fSX1*P%i8QGHNkn>cruV$luEtlMH@SMVWJx8CbQDKtX$h>M2; z$njk*c=6F)LnlA)od;d-wFy)u)Hr+ihuiM%VT(63cL~HQTUT@JjtJUcDMfoRw z!MsbT%9)rsooUr*m9?LQLkJB52>tI+%xZDqZP^mlT|jt$g$PdlLU-4a93Ksu$^v5* zUP*XTM)s?iDV zBWC_05YB~vEJ?_4s113gSrTSVuaJ3W4`A?nXxw+ix$UQb^j4KrH(+j8k;BvAp9?%K zk7$7plUyB>oEH;=l?N3@E(`Y5l8}A+L5@BfF=pPHqa;)X@buH4dzvi>Zx**ED~~9P zTAi{SbZhS$A|DNB^;SC%Id87!;o!B6C8LrUN}R_L$%~@U$m_iw8biybg?gXVL`isw zBP*>&?$3svEvn+MVryN?SMoUP>}0dl&_K@~8+tx$Br&XuJ>nwn@;G{m>76>NJ^DUD z#?H(o!DqxE{d8ku%F9`n?6|3T(6h&ov{_n?Mh1aq;TO3NX=0=I#nslwh+U^1H%B>Q zx5;6T9yc5e+wQj8H&{8C4rmu1C6&3Z-E3Ic@uJR&Dk+X*maPIsG1 zVYC>r%9kN0ZLbeP4yO#xn~{ndR*yf_2an+4_;xHmc&sDZaXkeqpvWoQdpaZ{{E_mp zQS|Q{B)d20K~4N`foo8>AV71-5u@Q(sgdD+3~jW!q;_50d133<(?0u*`0tfPuxM}K zU=QYSb_fqPhV6z<6LaXn(hKk=+APdxMd6KHr1orm>XZ@=|8`ikMF2ndPFN!%n0SG; zB1$4P;bTi9HDQor&guRe{%Jy7ly!;wIG7{eyNtw3l8H@iV!jEoDXQfR5dNN=SfA)< zTHh^)FHA<2o!Gu=#BT6u*msWRQ0CW57=nQ-U_u9X4k$?BeWS^D{jNUqMu7L)6dtFA zHCE1L?wt&sLeV^Uuf-|6ZJTcvDZRb-c2jXB8g3@9dR&fJ?}1J0SCcO%oV#YJzdU3v zu549lTLMls)wy%h!&&dK9jdgw3KY-%^leapD7o8$!l`gZ>`Yf_z1D?dc#(AnEF34@Ne?X3CB?b0-j4C3*VKX*M zgcR0GC@}tg3_!pX>MTHp(hXRcct~Z!>VO%Hc>0ix0WhFU1;k}u7O4z~ly{<&84wo8 zO3FJ4uHp124p$e_yalThMf*!=LQzOdjefCzWSW}Vz0O`^KE(ve1>erp# z%Tj7*Yi`55*1tf!TurPTzNqKE*9_Bdu3wPq%IJ#7D_X zIs7~@s|7pHBvl!revTFL2kHhF=Y3)Fc0V6#{GP#Zk5BNat%h1&&J)kALV0{i7cVdEZdwN_k2tyK+iOC+1t>c>eriqK#VtQaEG~B} zFr7Ap&WC3nc*u$LEx-(mm9#WGCc|K2;eDdcYItu~eHTN{P9|NBRHavW+Ru(`eq8kE zu=h_NI=eV@V7~F!*P;CAcp=Xg?tOD+E79oXda(LtIo9UQYN<7ORLG|=HIdX|FV9cP zsSR_hDX$-hoFt*K^^0M^`o;WYR#O6GR%s+N9hIdr9mCUxs+rS=s$~b)rlJ8cm^*Dh z1%%Hle8LC_ogx`Z;J!1ZCcE?T^lSP-bx@j1h==;n`c$b)Ol0%TbsrW@$bHmG6a3ZY zV6DeenOXs9D(v*>D(q5&_emlF(U}v4$N|FR4SvE12%Vyho&XR8W{i&k$WNyDJ-MO@ zK0cto;{h_o=#rWLO&xdU;>y~%8}h~O^Sm9eYfbA)#f1jJ!zzQQDovBr{9HMMP<@vt zm;Su*8?hc}4lQe|U=RCDca-|BL|m%-$-!1?UPrC>^VzD^N*9R{!_@~@k=9C=MAdse z@hg|IRwc!ao!Mvd!c(1y=KWPUH1w;Z7&;qbo>2zby0!;}G}}rWD~T5a5A?dE48^2p zS4oE!ju~#OTYLE~sw+j%c2+ATfbE^9X8Gb&sxkEG8IiJvGi&dgj^(I*iQTGS_th>g zhqB|cL*Vljf6Z(xtii8O{L)lH0s>?>2p}*WMn>K@k$25U=;_i`LLicvBp4WgiB3^2 zCkL34Kw3%)F#Uiu0bt?*>7q1kklplOj0m_C_ZXipW2a-<|3N{-Ae4jPw?hLZP3Pg0bNx0$KF8fY9%DNdrAa)>6v>f`-w z-a7wlkEdk$2 zXz)&YkFP02ABR_Z%^{6kG7h;9Z=wm)0+(0XoQ>P$@AR!Fn0o|)z4U>-1c8u9a{uq4 z_%4UXk9d3v;97D*{04tNrVDDz;_N=^bnCcTojj2cy*y!l>UTB|-Qaz?yZb)XQ0=K- zoMA&#G-T44{poIzRs^G~Mo;qjQ$N3VQINCTbVf-@>8F07AcBI;gz=CxGS^OFzU83ltug4in-!BeaFkcdDQ$+h{o8YR#^!Us zRLK*o%;?vdMYZo9*!rtX$ldEutoTG{Lt#j8KDC9od$o0y+R*6PDuEo!861?~y}zYq zN;Mvm(B)&{U|GAZ{$;~w{iV*pu$kM|Jbsh?aOY7!;|wg%&SqEp+|$OrgB97{>=o6I zVfOIA$$0gnvd-3m66C79Jl0L|$FF|uwJR3<#u4BpG^UKhtI=fs}ZLoVc|P^ec-f|ejoR8Jii2?UhpY$>yM(*kTmxCC;3j) z#l3zv-E#s)QnOdP+gr0|JZrePV?m>>+DviPT5--2CR9gcvSRHjrEA<_?m;w*UtRvb z&@BTo+`nTkYu@qpBOTv+ZF|VxYgXD`JGhY4?`nEiE9yII4q>f8=Or4)pD=wGkl)9W zH7s0iA$1GmBxu<6E9wmOHkcG$M45jV%`ybF!PB!PvSa9H!gb-+V@4MdVw%HjQL?#; z`t_Ww!(z&&z#|P&k6}&+ku-tgy6o}X%L2kFL#{c@%f3D&&X4nRRgz7_r->m*1x>TD zUu%%74d!eWAT%qOm)0a}E)_@xj~YuKHTGQYN{jJy1a8I7X3#d=%x|Y8yW7SMXUQiM zvzvPs@9}-Kp29>a@(L|{;~ndD(HzuPt2L%=)>`U^LW6x|;-PU-iaz*UqFu9GA_UX^!~_k{CU$_ncb@x#01{}3<7_h^YVhd)2yrPvbtXf)BwFka)e={LHz7#7xoqb_0^ zfAVrGxCdEdLK)x( zeKu%XU?ug?!+btp?}v4ZLA(!W9NQ*gk*ZcMtaOIQ0$wY#-P0dl)gIK`wkA)@6+9{& z7agX!k+9^dz?x_Uhu?PScyA!<(DA%3TYnAQjttvKHuW{WxO0I>c z7+8A{+M;5LHZ#sIyG^h_8k(EgrxTI(JT+RpD9g? z<~E_cxJ#6#lYW>SCD}1N2(!Dn5@5lrR1te<&ALmy+fYVTKg(DJjwgCu7QCJvx}B6P zh4&;A=C$u_y(>eBUgtt|-Oqf=+Vk=A_%*aKyTVCe%DC`+`#rj>PENK)}ESF%Vg{c_>ef zYgq6;5QyE)h^fJe_;PkkiG$E7MACi550-y3JS9+er_JnE~Na($GX7sYp<}4@XM(r{tHD0 zMWF2ikvq_@;C3-}oI5!YurHUG&iuj(}@8YYliaoYYnEg>8 z2)I4{RwgC+{v?kn!gHgzwt-f2V$w~knigM^*ku{Dx8{l#o^pRuEf7(7>DooR4(HF8 zCWeam8SNRCoT&(j%`DCG7;_)8+FAM|yzjma(|g7pBDK<}<6pqySnKA2rnjp4e7kgn zrT=aTQGOEzOi(17`HOxR>*e_q?8;PmEW|a8BF-<0IgPiz=r0Sny+~FFCV`8-3Af$E zGYhPSga6gqO})JZQh4n1?rqt(8uk00dl8UEChr79)88k*_?he4W8Z2xHv5wM<`ayG z;;uHl@6X7r1ro}Q)0<`yY8^N&PUs@<3{74cX2YsKudJr*4uOyDjY;9U9OE~pJ-vn? z{AIjdiRb>TdGcAU*FF4%lCD&4!QAZJMUe|FT>LcB6^>o%((3pvTqoGJ{a$S=sZDkY zP1s0%!QE;X!IttxuQg&pA6F*5VDIqhEW^9Hwj+84QMQ|Pm=m4Dn`jfAgHdSkVsr^a zzC>6Mq6!ytqFImn=Nvr72Q_sK=Y)LCD@JlZkN&3)+D&7vBjF^wrgU~o5v5Y=m+ zczCDGd)nP%(&>$C=t(vwvNEK7QkzgdBK-3wD`BXlQ6nZK3YdNOI8^AJIv=t>?JPg z_qaMPgkrx5DK;1WLE_W=Wl2hXmibI8 zTz$ug3@`5uiTUqO>BJKUXadJVZDO9vU-EA3rgz?ALl1uQbWc4xz_!|rM)(f0E1Hck z_zla^1q(?#V)sHs(>JY5J1U)q5`Q+v;5X&sOss6dZz2HT41QDeC0uD^diX2+y`}_S zr?L4Bl~zvGR!$Xp;@76t4>t2qTL>izw0YSA*WU3}kR62NMs-FQM_@>3|Of`f{ zTZ_5O!*?>ORrh)I)Yjo}eRL0(fnh>_>kLe>czOm#MXjxqh>Cu0k=y$>q|Xw|(Q&TW zX}z_Bnv2~J89|>aCp+%(pG5Pn?-%RsuZr#aoP0cDVGtGFKUg{DGW0XqTF+kA&?{B@ z@@}f+$GzdksQu%cveh;eUK%{5T*V!khmF^pQDrRd7nFwIw4lnYwy07nq@o%u?*2E4 zFznp?<=ZCtx8RtRskxt=|A>1o?rY);v~HciKGHIhHxZaNGV>d(_7&9M%$Xm$`#ZOa-pUFQ zUcme08Nzsm;WlK(O=^ux%VUA?uV@Y z8MX3E2AR>?+0ojW(Tq1uqhIk(Mvi%hz~&D?<{~g#gB^cASd81-=ddw1ia|+WolQ>< z^#gC^LmBt?lGFT!z{ZLR<8}C@Xa63USx(`jFuHO4 zR224)WDbf~^rRexPae)Y1AXKtYUYrdDSQh6Ah$qZ@`*JBCL+h+lO$!7*S;u_-3%kU zsX#_5{p14aE!mNt;lFK6y*gbwKrd!VwNVjLe>kx-HF_wx>vOb~W^>mhQHiOUwqnEE zX0fKT&|y=it6l5~_l|Mp!mpw6X`55#fbyK4#^iyj{!@tys~-E+bDG26mYgVWyV0GN zPkTHS2f&}h46uI-bT2#=rI}9c$x$hh>^8f7%b&aPHIpNCXLv@t?Gs%6=eJnqZ>CU7 zCQf|A{dD2!bBM&Z*y{s{BOM?Cfo@A?dySciWg}W@D$o&Cj4?&JEvbee@<{vw}gg>rVn_I$yclZJ6jy zmOPW&@VK1dus3Yf`jDwiG7TRKXds4sTX9Sb`4$4ew-5lng^2zu-zM9L`Ew6@Itmp1|S(IRt45c#H~nl6uM;t1xU-t-?X!xSTnrr`B`?6emR;;M;26}Ku{ks zL470!^^pYBH7QUZt#3 zy2e@VqA%UXg)Y>GbZn$SCjJfOCQg+mPGy;BsvEfBl*Wnh-5xL7QCSSsr!Z{f{ftn) zL2Q+#uDYYWot=}Z;3lA0L9^SNiN>}-j%eA)HX$O2G zq(pT@ufKfJ-)wn;ry;TARF1IqkX2IPCD(4;(W!vg?)Ir`Rgnf>(V`_qZ2`YNj<3PY zC+S0SUxV#W57+~`CHx~Z3nS4T@9g+y{&1usE0Q*6l_qURIUor`G6ypBosAxXUO%~|3ym0{E)+*H}52NY5zA3a>2PxR>6 zmPCv;9~hfoNAx$_q_nLX+b;A?dAV;m5}2QBkZygtD3{J8aIvM1{xTm)q2YAzguB6k(B0+PjCKRT zeS9^;%SI*Wu7gifPcApKcVeu*X*UpKB17nxF5Y@7SP)vjBwR*OZC!0c1v1i=@jWF6 zog{PnP-Z0`i}*Q6E4{MC6Kh3}+17+iYQNabF2zttvUvFd6!DgM>D*`y)(PZ z5*WGPfS;jH-58RQ`gK(fvxs$f$fBXv*eM)}Ni2l=JpK^! zUJWuX1IvHo2ea7GMJMclkQ^*qvOc;Xq$mxsbGsR z9;taAn>IS!q6!`}eb46_y2Zqjb6-fFcfMx9O?@O6C($kBg862d!lJo&=>9h?(I}>} zVf!HBJCr_u1tI&w&$}f|nh{MYypAKWzPNXkNQ1KDZ{$ViUBMsxfOsXDnedADR{-_m zFaHxZ^}tz*vF;z&z`6AnzfN1Sk;070GyhkQ)TxHd{20xBa09?6YZBD_yFX4VmYRh& zc%)v^pt?iMOGrT{gC8PI>o1$=$osfC_Qu<+7dT~Ky$RotuZwhL@)t+P-jXGYjca}- zdB2ZJMgAU*)DuoO)9!FWm#q{b0Y|n;-yP;4*AU4kF_KS0B>h{%fz2=Oy0j2J zW=K}h-h3O)6>@>&idl?A&{ZzptncWzI9Ti)%`hX2-$^s++Hky$wo%5+Bc8c}zs`Ki zJ%svcNLKFj?fLm@LWI|^$di!*1JQ%#@0m2m)8cgGz5LSi$ez}5>x`!e3x5z>#uvXw zHiOuP^~r;4UO%DxHH1g2?-3(eBhBg@MqbnS+wKJvFuKtPq(QIlWe{gw z!M_)Tn;{tv{7BC1`-D$+a=satc2p}w^1@4r?4I)3rP-C^bTO}%a68wVgJGeRPV?1e zFBsK5_RCP)pPWx0<`5g-PkOEySCVK(C^k7*;T#uMXeCrUj2*-@vcZRjunKosr}G8B z3WcpC!L{pZ(N_65`uA&isW)6lL_qd=`?I3aO2O*6l&Z-Fa$?EItQ7*mAMZiW`n^>*x{nOuD}y?3Z#x7jg9)twF+b z&~Z?m2!-F1?&w~&Pm{_Gg@@Tr{Cj!37kq=>q!DK~>KG;^6{?;T`0f<9r5vmlr(wFyu? zG5&3;12;J~qHWxFSDEmuzdJ6vh_oL)b8+zUJJQF3A`{LE@3p=~m480Ijb*|slKqC~ z6}>7M#g7011idOQ#m9e58E<15N#s`#HKz5%Z~#bxny3+#Y7kKk4uhc_lq&(UWlzW*QuPS&Rajt!iPAq1Moavx0Mq-$O;SpkXOfU-LXkJ=dSxAx7PI*}c_Qv@ z`d2j2i(eld+`b|f(;m<9t(_!1x8$k#K;3NL01Ua2(Ae6s4xKT4SB#FIo;qI81ydU z9E1Z|#*ig4H&FuSyNT6eM=LAGF5gNIS*e~b*$sH<3HVesjeRo08=;Gg6FVNgT&XMe z+C^lOuzqr3wT~$6r+H4lD3{+Hzh}upSG|^Qd#{L{3<7{O;FFmzJp4ZpzuN2Nsso4*c>|O+vi%C}pB&;6!}; zgpSN%B}Z5K=u~>0TO^;@HtC&|#|q)n_X#%~KYjd5J!#b#hg*|rjHQN+(xE#eBDc#6 zk>PXwJTaLfE<{Rma~RkLzcc7E(s|b|v#D-vdJLgtUcOET9p7Lpv3?TWi__sbjW+_*9O|$oN*Zq!drwlklaKS6&hs(g^G|Wq71n(e9(tF>ouDl0 zuSB%Zdh2zKKO zkf2)Mt9fi^vehitkv&h;szMOQc~GJ8(5&QzzVmCgAU$UbIYNEs%R6ry+A9{#Jk~z6 zN0L-6ZR6!2+0_bIy76nQD-8rVNE7Q-quaR~OEcPcNGq>xmSz+xJrwJICn^zqWE9lR zB&J2;_-$1Vmu@qFT)g@w5?|u(%kd~&9fg(hAO0T859r0P-zdB!^sgYjb>})ymIDCn zyjhg5dlbIie)=r1+hIo*lTI2Rk2FX+Mlw^J$vgH{&qMTE?k^Rp7|Xtv>j6ps+bCO4 z-SjQqmte)siK6OM+~heuO7R-%T~u^=ps!Q{DflP#J>1*)kta$*p}4-M`pp@{Ii)yj zw<|?DZ5SG+Ms{vjdSOO641*MjaHkDO$^B26$5AQ6C(EPbK6_%7K3V z51Jjl7j@=7uRpJ3F>HofbH85 zoo)|T*E^iXRw06;UVA;-oz=8~TDxIF;r;T|4xQ@y0>h*JPXy@>btSJS%y*ugHu>am zd9*SRDz@R`aBCZ3rX1Xq!KHOD#(`B_<9SL_nri=n0xkF1RSZ9Mr3n@k8GSb~;;|n| zX+Hihzr+KAmQhm^o0=1W!jp>n7t#13B@DE*1G8@*;og3EfQ`Fk|Kr+^dK+Uelu6RV z^2-Wbw~eBB<}Q)IT(?!tcx+p9<6vvQa_}AADo1j{P~{q?Le}6@&1EkWF;HrSyv7EX z)kTFdebqIv(EAYUszuo5HRc=pH()7AxfU0!?bNe%E-I7vOccnMU(VyGLAn~4)KI%D z+$PYwgYC!RFHNqJ5sF*LOm1b=tY9TEm17d&$lSf%P&mh>`;f@jNdpVU9aln9+ExHV z0-T2qruD~lV2@in4j#JmU=G^vBuu(xI=028eXUHu!WI;P*c{})%@YCf2O$g>b$ zm=XU(f%1KM!H!%ahVk(_FNed;8|if>2dIKzu`)`4q;5}p)+Uf2OoWpt`ZS@u z|FknPr_#nUsgS-{r-*Vp=+5JyI?pj$PoII{!VN384brC%9~)9SJWl>$K`cbcDK(w) zFrf9xT{5&7hqjxNX$~S6CDXQ(u2!A+aS8<+F@6~IUnUl60f|w29%7-ypW@T;Zpu_b z{ZPUkw)!zq%XaKL$Z0WVv>(_23HdS-)}a^ZHi7qy8hG$H5wxM*hYYQ;y%cW(TKAX4 zr2EiqvTu=P2>6qjv(ROVmki$LoW~raOF>ru;Kj!pi|EB6e>>+GDQTQW`Xof)GsV1r ztAt4dnIy(GE!J3Sq^j@Gi#Tx_6}&Q%m*OPv(Y!>sjdvYaBF!H&GIh7J`cS|R)@CqP)|vn zap-C;2k|O*3kR`HyeT<~pGJ#jMh`19!oC#!y^)X>nhsC8g?}sI&dO0a;d0E^9{exW z?SuHrG#{mDj1_7mr%UPlpSRkzgA^jwPqx+4f7fZ>6>Cf6Ri~!blE|wr%?GXhcA`ec zJT}=F6qjZLzFK3E6AxNP5HfxsHN&wHzb-AUVz0BO7hb za=(lOYp6R8lr#g&T%rhbELBOzcdV#foMs^pEAOHW=1{k6M#Rqv;xeN<)_ywOcr|xZ zD`2&E%ax?dCs>DGogKKO1lS>1S;%UIVd+3?Ha~&yF$Bsq`AjT%5#OUon5TGOd(NYm zW$>b}D&=yEuZ~?7F`?k2=#x!m-dkB&UQS+JLAbfCXD-PIo(_pVG`i8JzqAo0@@~{{ z@JHg}r03NPJZCXZfuECw+5Rdsg2|&@uI}<2ujs23IbP*U!Q=3~?BmqtSyohBzP|>fK z8bL)*MOH(_Sz;YpBenThZ8F&MD^~QJ6!4U zKUPelPJUdO3HMriA7@CKK&+spG*V!n@a*xLEcV%HHAVQQ>#008(Fj-Mg|SxDvGh&X z3;}OxYT=7>KHd+gg}bX6Vj3{gk5~c(Z@RJs;Kay5j8q$~s0fH&VmhXQhFUlhNMQ+R z0hy}|ohXso+Eeh-WA}mJG=Cw_P_R?m=`ZS<9?_*x;i2I2=^oK{tWi70TyAAVR&7~c z0}nqro0bs`$H*O)Cj2LYR?BlLEd~1JMx70FhQ8SUM7OW9+?eL=4wjbQ+vJ(zP7=-~ zu0YmTQ2w|(7hureN*d1DaCWMHm;j3;7hzWLO`AO2Z6(bZqSE&F;Z(>#4&(|e_%^>H zuNmh&Mk3`)pVw2_C%_^w6`ZlIDZt!azLJU`b}V`ud40IFv`8PrD$aGai&Wh3Ley6v zB>E{H@>vXndIIby$y55zIfA$SBW51fj5hk3m1+_zlI3F5Z;dgms8$vQo)4H8+#ch} zCKx@&W88r3L%Rq6fY}8fKV9w+No2*Pv{I4_N3=KA3xNNZe7Q`ga&c!cBKhRkDA=*>GaXkYAiCG5eRFr>y)l^6SYB~B^@y#aKNa`TqQz`b zXTZ$Aluqibh5J+Po(Ui8QYrDgFrF&==H)y!qgcBu9dh4OSfaA`<&zwyWB3^EIYbJ_ z&azl^#>jp5ywV}GA)geLEhI;OZ!?B(u9d|?Ga?utx3yfr(U zsrdC(dQe9NRkDpw19#lvqT#ZMHUIMA8iBLWq~U2n$a}8KWi5dletIU>xK(8(lC7-G z&!ZK>FES-k(MWRh3Iu`-&FK)f#2t0QQlpUfOw**MQmwc0FFuDjgrX@P|KVWl-%*EE zH4hNmTNnmKgJ#QrJu(^$pygiVk^;WO#_30NL-1TI|}x(Z~2K7wt;ola#Gg^h4TH|Ur4w(Zmh&%`PIkkWRgAHS&K;?(v+Uf{koA$YY zzsew9%q!rl2l%SK0L%W^{}+K|1-i{opvn0hfbP~k1na4vOFzI7lGu7FfaVq&BW00wBf!hyNFU5M*3kTRG>)j)v&2 zpL1EAbJ3i0o!OzAIMO^YHsa&5JEyy2eqZmc7Q(dSqYaxT=cy1uSp+Yo=5)FdMq$s= zkygz1BTMJ8J4e;KPjEa-G$@hLE9IucO-`lw)kY_Ps3XJGUOB3lLTH%$Yn^7rL3I?)4MbqNXcIoW?ZJQGuQ%TX%zsX*9M4 zcOgOeK(B1NXD*X9N|chzZL7+>HLI(M97?ohb;&5udvWUk6)LTYnW)9Y@wFyIoQNXH zs~l0EY+Tt;qikIB4SAAqGBmknLpc_iwUSuoy~JlhB7_FVKObSD;?AgiS)<4r)6D5%CJOrFxf{;WGInVrRV$p0=esK7b!Qy#=W5z^@+P~xAcrYL4UcKB~* zZGy6%K0pBiy$adPhZX1q75t>2Lw9x2W$9rT1Zn$6zY`mrJ+e?5Cj<-9FN9xHEh0O} zT1oRxR2#3X2VQzGU3MLrMq>lCT4RolLSjK!1Br!4s_e8WWk$ROX(+4#VmCNlH!30V z(dJoDkwE0UcsYd7O+Q>`?Gqr=D0MOH2NEv#H9J89L0AJ_YM3-YLY#l+8e~R*mJbdH z3Aem*F#S96X&UHNfLr|w^H0{l5|6KU%Rh4;f)9BJ z#7V%4cfX6Jb6zX~5a2-GBG)Pfjy;QP&cu}c=ja$XoxAFf_aS#d-qA5?fV?9BLMdSA zZ)=z;se|f$TzqzS?PBe(OewWaT`^OjXTPSqar@q2Y|Fi`3BpRM71MUH8|?bed6iUG z{!0RZ$NcA1A6TQ};8Q&EVBl9j@6u5Fd(Z!OVUx%*Lo6bGm;i+S|wDbh)~|wyIw2-k62U z`xZQT#f{E^usg}VWC;jG*Uastn&H#vPp%idm|9Ke6%^>D40SfB4!*~>bSEZ+3sTWZ z89Gn%Zso9^zItBgJG4h~(W_^zHJaf^Hzf#HdAG1UH=^F$&^#jn2`;w_UKVXYkd(%M zk|zATuI%6GC>RdxH&1p>>)gP@f_g6>xm zgz{vsp$AK!M{||Gw{$;AC)cBJK#eS$+QSA=Ml}7>FTqQ=ZS0+}n9~yLxwZ zrT(dEBT=H8whq{`wCSe1cBiQJB++|)dwX;6XW<>P*rUnC(M|2%CR&7WIzLR{HbOKV z&DKkFksBmPfU#!)Mc+Sn3!S@bPV{#+25Q4o7CEzj!EaqxCA|vwET09_K$jf12L46* zwn{h;(6F9~5y48HMK^Whx^}c)LxpZCtnG7Ye%!N7=m0*zwb2N3PXnjxz2bm$6CE z*t-b8G9qGS0&+G^o_btF#{X2%{T_5V-|p>yWJV##_qpBzER7gK4rV$+w(G zIWKf#d5K-Og(F5owKGG(b5O7x2tS;%a#98J9ox?whnKip84uN&^EgyvaP#nA5?y38 zx>%p{C<52AMvWQ0Hs?_Y?yv9pl9*~i_tSEjO5^fA6R1tFHYeL9YTP!{WAK16(qIE6Y|r+m{}|^?o1xdB5gc*gz}}n*Na1NKQnMdQ4W) z5#D-A|42G!0Pd^HlT;?Q}_0{JX133bF#ZLwV1nVOsK0WGItUQYaX<} zcl_cyqjd+xIHPuF@;f-K4R8j3CsB`=TJYuAcKO&1EXgiWDY#n&JSyhMlqM(93`)an z{&5K|T!hJ;`aS%Wf)$r?P#=P$j3iHzMvr_5KRmYx>8gbKJ~Y8yR4Ywxa8_$U-DTu8 zAO>wpPe*Pfr{jup&}&A4cQKi#-EVJL6@zsnu3qsRHy!OA| z2=01)AxrE?1#g!vEV1*`_VnZ0q^H9}9ViF=b~{sn+sKH)F|T5--p1UKXZEl7IYS6+ zI{QxEK7X9JxNI1ZUU>nwHtgy42xEkwx!Rl>g>OC4@4E!n+~8aDmaGq$*`(i1?B_%3 z-}=z5I`IueedhFc+lmi_E zOBDyhq;cp72X9i0k$)D<*okBx;mo$^<{GrZB__OUwikkqZkI1KZTw)hFOct7HGc734*95llb& zOmQNTeyOikM$Vv$RmS%rkF>zXk4G99KLYx|${kezp%pwz7=N$eG2;{eZ&vVFW1p|! zX}fT~f~V@j`3j!=3uh~MZkyfY5upnEHSzS}v(;zy)yMmZ4C7;CKAxLgK9BDYPAPXF ztiK-jkvZtE9f;)(oyKRkI?#0zkqZy^!O6RGpW@$FZ7P1g2Frh_!+Zq3pv*qo!WOk4jVP?Q2)EjNP3>DP zOnWdln>JH^ZJogO_-oV3vkk%dD%03{<9=Pj%dqom4E7Jn#K8n-?{ACtzunbc-9mk= zp(syQ-*XsEkiv#llCh-J&Fz~6P7UevO8PuB@>1g7-o4y6H;!#Pm!bzX2wAj|=s15^ zr8z08IfV=pArt2Xze8W_A>f_RpXscS+xY%)klF1wW3$=hNGF7MZF?J$ z@8bGg ziV1-`=fM4JA>6I=ENnk|e{rI-jYw}OUT;@HbQ~j5Rx#AbUIe`*0Q~2m95D)AIUyMO znQ#4WKJg&sAz*6W#U=9uCWyPF5&8`V|8k7@BPapn7ut&agn(UjF924yV#R>Af6_e< z0)JY`OOSPU%3CiC@c&tsS0?jB1g;Ae2`tNl%mK|9lAtUCa$vyAR)D%#>KMUw69aM9 zzersJsT@!MNUttr%Q@m*SCPyUFE~W^C-=8G{}561OF`LSrQn$~Bf%S`x__koe{j*_ z$7}CBiYezOtPNJu?h!1*hQY~#HB(02vS z%PP3W~U^^g4jj^;lYvS7zBd~WAoa{i|2i8f2T z&Tvs%Rw@A``5q72$w?*X7klzOranWaJ4+?ZRf3I7Zf=JY!NXDG-afmP!yckmD=*%; z>FFj~lYiiT+A()rzh{y-8rf2Ky?(lhyL$A<@_F)|J3N-7c0W7=^v!Oys8==OAQb~X zaed*Uqk|Q9rc%P-zcM5Xox1p|HZLL->D0{2SE?*(eqFHpVXe0$`p$5=I+Qjt*-`c> z-R=k@qJAMP<>X+{q5sB)eh@{Y;w2aIY{R=V_}ISH-Z8g&2|ZQ{46#Oob++w(wRrZn z*ew_T%39sbmqOp+%vWcCRjPTxMpU=aY!!NOkX-*l^vr#__SEKJL~Z+hJDKen1=QsL zLa596O%E2dS^_qwbFh70Wq!*M#9yKa$>VG+>ZQg^95o)TeY&f@k~tgJb7=X6^;24* zb3fK{amhQcx?xTJF1PB_qAr(1j!b*IF0PNLrKT-JPG*C1m2S)32)&ZD4?Ae^U&tB8 z;;*T-2fGp_hx|(?ZzEmsKh@_?jjkMjvr}A&$Fk*m&oGNv7|diWX4z?^6%^5BdjUp& z`Q9>;$<8mL$y1&C+PJn--W2E~(dj{8RCvmSjMm`hUa>7E1PsxQsaR;uyA^j?lf zz!DEcClMe#S$4&-&0l4S1Tj-~q{}P%@W$=vJ7a#o+sAB8E*c`|D=q5zQ70AxgeX_L zrM`KLhzfdj89Nt_tL9qmKg*vQ8m%O=tu?T%rSI21PGDAoFICOx7M!M)jH|)~QHQ|? zTv)dKxCF@^8Wgg6s9@hy`)|o4?|q;ms+01vAtLv zJk&u14OZpJ3}<~k+#A+U0Ad;US7!$f_nTfH~XB53jTvj>oyZ%QZGbq@xl_Ju6Jw5VLd@izUHzBv zL3HY#2QfFCGdJvdLiAYYH0P_YzXBbgPgPdB3WoDiT_KRqveL30D4DJc^o`j6PX_%7 zAvGWY)Votq2|ynYMP|KH9+GcbY#_6P4(vQY23QQf43!CtI*?g1%Y9H`2)CzpfX)B1 zM;DR>X-)uTs7wJQGw1efRY8U00=#g@P|!#qb^lO-UJoiCU2!mkJ|CH9{xE=%5O<3h z%l!p{{uf@5XeFc>|J+{7bB}|u`OM>Ba0Pn%C%p9_({F(AecqS?I+$>mC@`JFz@U8z z-wQ7CrhBdra`MEvlbe?{Ao_swn*t(icToC{ZHF6UUY|}~51(^oB;RP(8>#c`iub z-ac*4s%TaV7|U?H_ZofE#|V52jZD=z0c^opJb{onF{*gf%2=r3DfW+Iz;(J-djl$3GtFkG3{eNT0;xm>XkxXZmpMh>Tp?YS5zFmC`q3wUy!a_c2Ho( zMI}fRBlY9%hWR^4wz6+taei6!L6)Iffavc-#~*4xuMzqXj_5VIi1YI5ILLV zNdEmS4AfgCe8R~DBT=McDj6sEUZ3ahAocI9^5{N4SYM6L!Bb}$MY5F~UeQ-5IYiT| z<_bL^(q+eLg*HD7-|3L>w!W|eCb&ZKMEO5x-{O3PV<%b-)awpWYU>Z1v)67_obH0q z`u<%Dt`R8*(5|pRNXa9 zx6&Nf8%y?r|H{;KbnaBt590fxsLv?!r8k;>k2wHLH)8yj4W(YE&L7lwoXs|lhG8oy zVCoshh6eAs0>&jbY>+-2;k)~OiTz;}x5Z8Ik?;FwJ#hIZ2C}!@R4!5Xju`9=nb1iD z>+e%y)Q2w|!E6=gaDYdkIq6G)uXOCefCi@XxibjIQyC6MhJYl9snXH=d`JLn(2xMo z(2xKWK;b_m_1}jCEHH&xX{lS79+>LuB=UkU13pkkAU?1or~DN$3QXdyc$uJ`E|vg5 zfdK&Lfx(mWtiPwnTx?4Y5V<-7ee_L|3DUgUjEm$`c z&j~yQOq119N?rlD@hHcxdo^HcZ52LA@dX00k-m z;H~f^Ks=*}3w6di0MsJk21b<-LV=&@Uy&{tBXku9rYd>^VVZBeM>H;>>qY!}0|~;0 za&T?AEGsL3NNB?lkb3@{A^vZ@e-r{k4oCijRZBJxhAcmiJk`KOe$^Z=nVv4;oj*u_1*-(CZ^)PZ|I03z^lY6=`XJ?Xd2g} zJj!3N&$H$1KTXzeFnlD`W~+eX=fIslB33-gy6b1vYD(ujt|2##HZt-WHj&VY2@{NR z5=WT5!$5YJ(h>LLRC?aF|i|ZP`7h$g=Hjm1P7WlD6X7M8rXIr zkAP=Z0$>^$cL-*qV8-SC0&JSnBVw&0vONZ~n=88{#h;H60Ko47t^m+s0j{QH4L}ch z1Ogzgh&_b4P|Ux%vI{++sF!n z*(%3pDyqDE3zfy-4u>$!EO&DN`ZLY}m|a6xpn?NE=hY+{D6gD8*E$kAjDrxWjIvdL z*LQINDY}4KaBhbL-nNVZ4N$+WJEMbUb^r^_>>ydtO@az?ChM;O3Yt^)fjK4A=m7xZ zxh23{29r-PpX35lQlJv-2!z1-(?rhhMozGcZ-5KLI3O6UIu<<>3F!h(fph_4<@osVasu5l>IU=;6xO{dcTCS@zYpBzH{QKFo{MxIxZ|hS zHE)E-ztjq!#R3zu00N|XRWb$`V8qG3^zH}VMRKLOz*Y`;KPKxp+S#mpMzgh9nT6T* zN7)6925+0{DH01VSo%h8RmQNjlDLTE8ohZI{#Tp9AU`{| zgAowWK}`|>5S>8aJdVuK#YS>r@x!1QmxFjkSCKv!E?oPtY*6p`jcCpyM0I$J@mPqq6oRe3!qnD$G7STpJSACB*;d(O}~#mT%gyrrMjV>S#k zI5L~{@311pr(^=E9l!eeanpe}Hu2~f>LhdkVo0e^U^Q=&PIc^!ahWxUCxU0|p~`c; zTMdc~Gu*d77s!Y3d~+2d!KS`p_8Gife9bd2k*;d|io>4cf~w5dAY-C~6oLS?m{{Xi z3UiOCEQNzVId(pm054IDOF3$!$v=vdf0QOib6SWeZj7K*NmQcdT>}D4UMb|pQ@z8_ z*@(Uad)H?ox)$0_#sNz~Cms;dFuOnwGpOJEzE>?eF#A;(R-^Gjsde-AOp_{Jt`K(} z`ZL~U=wS=kfbpww5V^RY`6Tn9*~Oc1D9lW+M?@a#6^-imZ{9HcupTKz_p8xF6xEQK z{{knBO^Tj2Dco(%oMRp!@^GTwex~P43iSYpHGpUZ2uTKj@B)ZEfS89UAcPMZ@ zeihxQ|f}|k`3Q8P6avDH_LOk(mD_ONi$19p(X$;RAgBvmMlwiC5?{9SHjKLiPNNv2obmyof0ujM2 z0~8Y~iGY|;N#u4z>;Ct(>7rjByO>1_*w={LNgQa zcAnlvI(=vgURMU76hH;Ki|OF4XxShQ`|z5Fk>@h=mj8L-!Yy34+!#D9GxC*S_giI6 z#`6WFc|0*YP5O71Nj1nXWVT3nJ>pko0$)N;Rc|sr7~;x|%n%O5^gmlV#NFE=*xY+L zAE*1Slkcg`)G)W`&K}tALhqWyTI~3Xgl#Yf*RoON{$k{OVn*0QL`_Q8Ktq`R+vt5M z3-bj$>4{8zlu)s%ur4tgX4=a$sZ_~yo&c-+mJ-=+4<<;lPPx}uOHCoOfO0*4p&89% z%S~`^Y83fweTb9*Cl|yCwyA)gJb{PCQ}KUz@*GfMMG+(C@Gc$|aR|Ob8)w`k0h_;q z=LhOb1Zbv8Qw~7jI6xFZ#-oS3CnT@9v7nTrfJgNctR`EL9x4Ev6*3J{EY zs%-hViBHC#Tp2GVNrX+=5 ztz|7Yn^oW^HnV%}cV23=Uw`9DD>Gnu*|N@`?u;cb{2^mI3^hrO z`?-M-Jzh)c@jRsLXUd=uJa&meJe+QlvU_6yJ!+p1Pl(Kj3}XW8hZR3X#o!%z%aaX~ zVa#D0+bA+8w;i(idJM{o7;&8Vb(#`;UV7 z(<|2lK49p(G`tOHFRXz7jozgn*KC5OJLtPoh|;A2jmgXWiI+L;Nk0;AmX>(o93hj} zNW8gOJ-JvhW-a*RTJT@@FZkw$9#Ft26hv+)h>-uSAMw70^S-s(83pT#qVIzGs!{G$ zmr@QjichUtU&^o24mwY-(jwsk!I*74DVTPjFEK&*0)i9PIeC>?k>_h;U1E z;;F(YMOvg1Dh9f4m9gllYFAy!yA~y8Fp(;Bx3-K$${a3u9AtyufUk>y=fe4g$b74j zWO49Du$Z~gZl<+dY_Z0><~tAgiBNrf&`K)rTW@d?swJydnof3(II`y9ZYvs}kv}|I zctWef<;T30eGjJgISeV3&B|(aqI#bx7D)R%?sKLvpDs7)EAQ$@mENE#<}#0$6E-Tm zTg~DtR${(kC{kJegJRuoVKFc8B{~b=!%e>Tzyn+R#hy#bWUbF6Hif##C?X}~329~T zHUTz?W^c2qntfp2ZSJKQD&O@zIY!I(3W1Be60vKGme1ELd?}2Uhyay~R(csBa$qxl z78@R8Um33OL2G53)TJjeDHJ_tdfokZu?r|>J*Y5LZ(x)54}TEBM(ClDapwuw-0vH@ zw9@{emwiM}6^1|5bqL<;IESE_dBp;Xo{NN@T}rWFqWq=4Z@5{}@pdpX&wy#XB9-@p z`=2}NfQ1A$V4jH(8>dD4>(06~k>WsyNy@8Nn?K?W`*%H=n#!|&mdv{8Es#8{^XM!m z15;ZbrQ8FtuuX2BCGacHZVUG_=D?Of@CB|jU_*?_3_7Pg{;DI0cBS0`^qT7MDvA2E- zEUj4fFE^|rX2-pl62zET=Wln&dY~u23*v59{#AN3yZsrRl#@10({#^L#oIjm_@052K5@4#B zL5bAc=lWex2vmhlo1*J};+S=Gzusw%9-rj?*awRDzKOkeelsNY_f6yiX_4~PQ^0}uxidLWJi5V|0a!##AQ-S^K(#=es0|lxlS+AP_2h& zAH1GC_^KOte~wEIJ>X(#?{ym6MH<^#n(3YJpxvfR`*(5zS*nzyd%0Rx z!*w{%{yrN$6|r~2#O(0NF3I)R$`2kLJUX?*{Pt@`&W6Rki5;Tzzt6^e%{Zr4Y;o>J zar^4dyXdSCz>(W$@5igsTmm^9tJNkR*tqG{ti@Z z9`$G+`mJ7+J{I`9SZe>*O)C%768a{Y= zXwN93Hqf9wIoAH-a?$g-DXVu;)L@rZix;jdet7u>20w=WVBD5VjB>uWUEP)D_A+7C zO`{48E@*i2%jKcOVcG6W<)X&5_P~l$ONA=wWjv! z6sDKYnMqUY?}82HZzlaoW{PY9Z#PT9XKlf`*GJfsBJcfSX%{a|k{#J#Br4gKLZH`Y zaUm&rq9Z7GRpdB~{{D$m9$qw&UP7&`r~!TpG(7QDbI6 zsfH+FfFcUz0#PUd2}EH7lp%-`4k$8!(g#tf0mU221)^{P$__+{5VQQ_QZzvV zqZOdg0?K13%11!q1(efbfbtkbxd!C|QRo5XB@_jsoCOp)h!P1XH=$f03Im|zvJePp zG=p@70L28NM7dZheE6V$49@`MA%MfW6(9QT%cTb2&4c}g>ybki0yP@qA|b*z;=e2I zwZ6+)S{&UL2$gdilM!LLl|i@8`v2~@$Q3e`cxNS`E(E3CYkSpS4eF|K^y}MO`@{Pr z2R9Q+m_22TpVaU4%6VEoxY}SKzS!TNK(r=RczM?m><_Aw%xBgA^wufyAZ}smU;5hR zjHuTMI>OS?W2FpdEBv?Rnja68a>yXz+HWy6rX?3$I}CD$O@IED>SIN>KB!IopqAG; z$1*$oih+9GO=y4&uSmz0NGrO4F`m?`vxF57A;?FEJagq7J6iu*C!WmIV;O&gM|*tg z(afv(jF%YihEBA3Raslc5a{WwCak!&VosA}r%#+6pNtKXq}DXJmL8obuciw2vJz5e z74eLYbhQ+`9UyML$Rae2(J$D$TgzTZex#w6<~-t%)LdkRxFq?((a$rY6GIFxw|v%V zX>V-dwVniVEfWQf5o|TQ+UX^$$#@h7>tYN3;}~s&Y{om23G_;ivRM+Q)@+8nIV$J* zk{(0x?DUAasenSYJH+p(AeQ@agj&d0B4uue5nnIj} z4T5)k{H&9WY0NugJ$WH1@;Ueqe!DX`*GQHm+v;zM0P#xd+eEBFVAHUIRFIo16UYk6 z;@>Oq6G~jEHCz4%#($3SFN}W;I!?zVaJw^Tg_Ppd(O*U?5y*@_)p}Ce)A?|7Av|uc zx1S{5b=PuRyjgSFWwJeZa`ffKVW)^jG1mPo%Aw~*O78o6!mS*7rW$OVYa-I+?&AR) zx$oIFOLZKF(HZ`Bb1nPxdZyBgwi!d!F3P*T{V}`W-&HtayOhc$U6c<`jz=c;cpao2 z{wMZ71g<;(z^QU6!0nUTsDe;blMk;xSAl&|jgnW#m`)n!h_o!fdGhdjqfOnIw%$CI z!_!zPRtNi(4{#Q{#e_zu+yK0y!JnNDii=;|pNU{X)wZ3mvJIq9*u*G4-nJnmU{0Ot zyCXeT+C@47PCyMg7I47Y2u`SrwEp~a{vO*jx>|4|(Kv7-wuH{$M0mZxIiFCDT$aH( zO9Y?VTssMId<=aCf91-YOqbgKw{iX zo=;#1ATn*3K38k})g_ zqV>fUa~4CRZqc2Ls&q1HxB6gQ31nG4u`nw+jb`IP<1`H@x+3nYEmK)+d~$gWIDUP+ zM?)>E#_=(yK?H>p!s-d3`Gi0eca&+fkB;&Jc9!%+6bW8#Dmb3)+%lOS_Kz9@9|zgn&JX;CMpF`ja4a zLKr+DnEjbU3?*|4IB!GA6GHDNm!Dp3%GS__)O|u$75f=|xYwbN`>vaXL;kX`pLw(RXSf1^RT`pU}i5?nK8Qd)yd9oJ6!#Q<1 zRh5q6(|40*$C`5Y-*s8^7XNZuA@lw&rm|A!bA!BU!nGQP*X6w>Lywn{==)mEjAymZ z$Y-*!`qE-^Dvc3dBKxY#jS2Hde&WPQxa ztLhsa>|lj(?Ced(;7fjKH;GX_kHkf#?wyS%3YTYfVdTlR=R98l8a~ezvFWL7y9byRVV3DlX5seRypBf#~^F z?PpP2HZ>7g$_BG9sCBs;YR06sb>UQm<{8B2WGb(yVZ2EwgVt|1#-Tc-I4EE#!pKWjVhxQ}vVoR8O^8gV^d2Y>0{ zc;{L{21?z^pRZrtYM)SnevY?9iGJ=Z?uhc#Xu6TNV_{hh0yg2$kV!({C82v26oK1;SKC8klXD3dXyVAZWox0asF`TFybNoo;)kIFUt!Mpqr9ub)DscgvAlQ?(py zs@XU7r-J^=)$#|Tr~a<^7smgAf>=|nTvn9z|5rf;8YT1ghZiigLxw(EJX~uvz3H2W zuVfGR*bo1-yscB&{NwGbYNu}{g-Kme+_-WFj(ipk-U?6Kmom#bf6$wesXO#sULY8B zgpa_dF!6Z`-b*rN=hM)hSVHPD@Vl%oEYN_o@XR$>9J-C#a2 z>s3-;IJ~p=zNE9ay-Sn%UKdZ5UCfJ~^~~^Vg`Y1kWVTr(*3-KVgFL?`7xej{nVEBjd1$VFu8Wa(XA$UwZ@Z>sxRc7c4W zx&2V^&ekMrFKU5vZ)~!ZKGb4fY`w|^(+4Z0L&l)&i4ZCIWm*|2l{O0|v2(8PC{QV$ zHsDvOvSsk3oxjj7rn23~!`6zZpt&on@X+3-VMyym*KgA;4>WSPV}x#8O8ff#;JY5d ztRB}M+Cu=ts9cyvhR3;}8M~lKYw!#O-qNMN3AXEeMUB$9#DSlP@}a>J_txN~{-%(_ z>jzVZ`0jWPmIh@I+!-$ifPl@Cq6vHdVnPw+!-XK2#X}PV0)0*<1WYVN5YV9?Qsod> z3f)wN;OsH{`8qFTf+jar(z zP~d-^*bLGb_}4r{M?@>2k!$Zbu-zoV+xd$ zY;IrX7*+U_HCp5N!-9gEVCls>Lt;Fx&)m2g-=zBf733SJ%Wj^VRto;Na9A}7o&)w* z7T5$<_a=TW{dN!9IBXrMl5BTmH{D4KYh0k7c1*`BrIS{gH~( z&;Gnq%5KIf>=T%%`~bJhn=e-9oIc?tJssPSy>}TIf zagJ$tvsbC2(Z9ij;v|9j`;)(kL?A&@G<|mP2}4({*hyCcT!0@ zM&wnYO0xN-W)SAXod+Hche4>AG_@Omb=ifAm#2g73{4i)%b?L z-{3C}F0Y&!`bIkdpc=sHoIvt7+RDkzl3%JS*w{FdZ;@eW{{tz0bo?nQ7k=K;V>i?; zethnCKSF5xE3M%luel5Fs;D5^LIqrdD6}SErvO0!5EKBx8zQ^{gv)>s6o!r`01*fP zffx|>Y(a!BK*#_DWkB!;gk4G({x#OI8&eV=pV!)=gnYX249n61K@kwV0bvag#sQ%P z5d5GBoghLQAjkuPJ0Q#fLJuHh1A+n|cteC#K#&Cl7h-hgI3-fG2@t{nVb2Cc=m3Ni zK#&FmM-br$h)@a$Hc$?L;0+Oy0YMTF9soiQAiMztH7Exgl+ex>kmO51kN|{xVdye* zn5IpH#vDJ!8n9adJL=`94yMvL=Z0$Ky1ng(fz9`9;3mH0@X{HSkcGHLBI^NBYfSt6 zjz|u?bhNU4ek&GX)9N`PE?>`^_Pzg>r+XfL>hRKWdDoX5qfh@UN)+~DAoAU* zmX$ZIqVtbRh{Lsd=X)RAEv9l-mmg&(!)9k=8PIjzj(4dRlcWS#v6Gv;FwJ%KHk=Yw z@&x9$%_4DtL|4B`u!b>B+;^WOPQovt=zfoT6x!)(V~?x@(rRd(hkLyI)YDtW+y0nbG#fh2$5WC52fVF9~!d}F>w(ZKyNk5JEmLrHg<3$0!)+U@_Hyn zA}SJl=~6i95@-3{Kc=f6rBO0T=aOr#t3K~_6-tnf?Zg~#Vjey*dmNinIF7x|)iI29 zu_z&vlVj}@`nMCh+cEtI`!OAUVs1MzyBwQMPt4TnM<-j-cw%-w@n$>rUQ|0ywd%y| zc;bCx?mRJ|1jwe(nrP zdTPo^i7DObpAV^PlZ@(6LO(i10KfN%&?xdO>5I=#=#1!bXN&|@)GV(Dg;?fNvIg;! zQ3q#<-z9u;QRam3^Mnw3L_n#sQU^6dgol3;#!d*2Pa>Q@iBR?@Vf>7d?l>)IXN=+j z#slmI*bR_=;;Ja^#9h&w6Tm(J>;U5db_47NNIyvn8t@0G3ossFJiu;%-2myQfPD(s z0qO#bpTaYG2IOAQy1_C1G_X$tJ3w84@c`oib_47NNdF7ie*rr{U4Zcb;{kR9>;_0b zgJ;ArLu;fDn(hp+1B?gQ4X_&^{VedG1^xha0mcK22iOg;8zB80u+ITIKwW_Gb09w; z_kz|9j_K!teID57X_E|%P zdYX6)%*P;tE~l@$&0`U4&+q#Fs<}nPKXOi}{{VXzIW$^*-d`>C-h|`szzme{Q7#+w(?p@hMJHC+%z@Tu`67s zHS%`*{lG5}brPVR%SZd0(Hy@=c{!q@ysLqwCtNv5lS9p?tvOn@mn6?NLq0uZQLE{~1R+XTv zPElHRkAw&3kn+RihPUt=9RmbuafqQ}!ljGI*BghaReTjQSj@e^!>(KnV#H}QEiS(1 zE+#980w3OXq?iwxp6AC;X9JeK?RIRf9szTpizsZG>PnE?93OG2GU`0oUFsuhjaigv zv3pDmrxa)sOzk#Yr#oA!ZIwNo4dhvdl%=9*?cG1`L zZ17}U&8S%DgH6NIYiQp$P7a>c;bJE9Y#x5*tn9sWOHNA7rL?P@ywCt?N>piplqagx zm_p^;a=yb=y5z#;<(HydP@!UX5CJH zj4%hIhGHU~=kGCLA~P7a$J8hH7d`IsDaH^U!BhdkR35=vo0VFt6*V6X5rbj><$_sy zoN+%tX6lCiGwZ`tidw3Hu-ATz!}VKdcRJ+{o7MuW*F8tD**)w&p1;DUyG!CU)^##Y ze;1B>?iA_h@af#97NU;yW5whA4Yh`axa>i4twruz%0hRY_6u?{7!RYmB7+t_?6fN} zvLLth(E0@oM$+QDJA;S% zXE5<|z<7s-(t&F?gPhQ4)qg%vkk+zotK=~E5{iGi_23;0|3$%xG2qy^cVx8B&$r0$ zWBe{W6ZdsCGAeRtHm{<3C>W@RW^dpP+%_aan3^#zbG_>8vv9Tubl)VethNhRsdRFe z3{x`9?K6z+m>B2JTeWJB-CRK`aJ&G0W^S8$AsSth6%oO)W^v zBD}a{2~O|gn1xGfyGD`T@k%{bz3}`)6xWa5GK22N82b3A-`UjNtdhKhB zlEI`N&PYl5CQj@*Bq@(d;Ci1wj*673yljn;iu+`VdC|~P5~$mxs%rP@s@eE$`ZR8| zA!7WpTMS9Fq(|GdY7j@mWs~ckVU|TkwPG)SpF_@PPOu_pGe0iW7XD-|lE{^yCz2vZ z7F3_@lBswwQ}jd3nNzWiBwXr7dq~j}>pMJdpG#h4L{$!MKak9!NO%3USJpjW^rRzu zQbBHVPzdFV|I5{0YW7(T@-uLG4s>E2qOrDC6u}rI93{lLxfHfdg z@z8;^*>UC$nx0XJ;t3m}uLv%CN>4cQ?UWWc5k#yVDtSYfJj)P|XT zcd4KjMLM6N;1Y|cN983xIPutxFe&d`JI;ab4n|du@57*N6e&Tr&+=X5J0pcWG9BX0 z?_nyaT(|~yQYLjZ8}DMu5`+c$mTbvSMDyK8${wI&3#P3tg&B#X_k+*SvIK? z4Md#{d0*^>8xfWozg+*dDmDa9W7z8q`cx(?h~JHgP-E%>VfN0-guSNZL{;O|1=4J} zRjeg2=m~o}70Xft=cX%252o^me9wlEs8QcAoz0;$*fLMJi%QD&vS?r8G;vDlnIyX} zZXq4Uw3_Zy$6-v?j>FWQgqb>V_k`T9Sbj?l#pwH{Q)cg+@Th!_hoe?J9wzE!81<83 z-X0G#+kHGt`ONV!JHMe}U~Vxd?%F5r`6up%C+-C&?)@k3b0_ZW$5~SO9*-Uixrbs9 z?I-TGC+=k@?n5W;3suI+rS*YpeeFv+McSXU74_asVHfTeJJPmHq3wpY)lMHYr#XITuWWoQn{&|1IJHABM+#p)^7Kp)|pu9bx{5&3*E5?EkGEkBL!<5Ndxh-hZqAzZP$bk?GYkck$ch%b-2RWiAib?M#_$ zPi|YJxNm1=D9lNvtY#BjaZn7AGX4^$wkay9^Q~g0)%b%cB=_Iejsr&i@BaLHM7pIQ< z9|#4?NOv}dxv4Gx)V#a7{#c&?u6I1faLyJ5o)BEiY2(@L7j}1ZzmMw)mROu!ky^UZ z8uz(T2|@bP>;Y9pRq!MH@EiSM$-OLdTHhs{^d4UzSaiKiOt4s}dBHfumukze*t!cn zE$wz;ctXl85BpZijhQ4{?=pM7LWee!j0NdCQmI5Y>_@WJ+yQLp^0r$TPM7HQWBI9~ zm;O$p%bt&w>fh@QaQDAF4Ss{PU9+mP%*f`mmQb8QHul+~(Y?=#l4zcuk1@{qy{0sV z*2!qaL#D>(Ndk))<%KHpo{#Q(RKY@`T8N?ulDzthE}-ywb295GTf0WpJ4HjYWOUeJ zWK?q&c3}RdD?MT5TRu{!>(^7B+^Zexao7GA48giP=;1--SQ}A=M3WI9y zZWAq6s{S6eHXTiX&+hn0aCjP<?uld~yt-}kPy5*Uv7eHl@g<3!I+Syw1^&k2}t(H#|I{jMGr zW49uXi?RCm*64nKVvL}JlGOkx<+yjKJNSUYN5OW4VjNH6dpjkocA!@6I4<2}Z%0sp z!q4-ITqUER4iY)VTOrQ_H~8xJ(FxREW?#k)&VxFT>>8afsMzG$C|TtL=jJc!^A8CT z-)2bBnNa0McZzpI7I?M!eUt)To3ODq?SsDg6Z1nrM0ZK09NpXY2ziykp%yWTs`Qp!)iu|H4_g zL8;%zFtw+qlrhc+qfuN9)xK_r!gC}0J#28(s62g6>RO@7?tF;DMx*26`wrBPR9*f~v_>39fR&ocI(3Zp zwLgsa9YXmq4VDb*8bN`L=ctc+^&>g25^fv*rIhZR@!jHwgPk78x<)w(^!%Cf6+$HqMtQ?uz7uMF(xjG_{Ze8AYaEtlqx1(n zvUe(T@{@`H#dNKugPZvk27Lr$5Xdv9=(smRGBdmEr#x1fK3<4k}L3a zJjbtjhIoU4KPaRew8x}NXY>`AbqtZ=lFRdrYm&=rV1*C>S?GUIH38c$$K3_<1Ip=n zsqhi5WcTh)9mfPsZH^=rWyE&(OHNdiTwqZB!!pTyN5Rx#5_xmYSQ?B$HhHjHr2+AU zzSmcfPL(%MJp{$CF%{QUg$TWFbWzS>PczI1ZmPtWugmw2x&M^CC&OX8D5#z4;t)IJ z7B#(voV((w@3G=n81_SXoSSChPNx@(>!OwN%Egb-`Qw-sbMEQQeoHP4R+7^%x#t6_ zwMrPH8467i5@vo-P3V)>R@ z;Y@Ub-A`Yfk~7O_g-Pz>#OuTH!_%Y<*y$}3<irMzYN?y!4?xiWaDwqas3zn%yaRW~YI@>|Zr&7qq{!|F`=8uk-uA z77wcO-Un6Q`=H8u|7>v7eb3$5bsD4Mxs(v&uDaEpbKY!}g|@$wP6visCk9SlXPEyG zT`<_*icowb!)il1qH(!6rAmiO$0v=fwc6Ihu-#8*VWFp{yuhpw9@>@pX;t^3{c^%P zE=Eb$Zk-f=PzQP+{6i28y7TC?oBF}%ZMt#=CKumEyJ++_Su--+;nZ35HhweG%;Pbr z2l-i{&3|b>LT|5pM7BCCk50#`8CCk1AnEQ8G+)u-XKK07bLw%Z@dbuVj;PR&tjr}( z@Ik}-PZ*b+bI$4~r`LI=#o$CMZhW{EHvwq)6%X|>!U%HO&duq0i;nhyLN3a_flZgd%IMV+nPjWt$c zS~O3qudfm3_f#nJ*e@4_6K7UTTkowQ=eL_0leY)Eng*^Y_@CnZKHc@$L$lR9UDxib zJSkD3jX#xJ$cT~Ob$3mz?$czk&58Q0`XzF#!O!a=*Y#XqDpfaF-f)60)6Wo#(NJ%< zBJkk7MZ^9TWV^_S$jkWl^^nD$3617w2&WahH#452_vN(P_;)W$`{}Od>Rt{_6f6RX?WW z7wnz-2dGf)daf#yex*J4csGAYd1tY@dOeX$=e0N`BYoEuZ|M)~>H?(GrwPIl)z*iu zn=Zl%aJg(ZUN1cf=WTiG_n!}fZARP)ogJs@2nS}jO%xl5{!hRn-{)X)eZceZN|n2O zR%c9;HbR1bv}U8~p~J&5Z5_=0^K}aS>|fBb{h`(!cWcTHzJ`kLN^#T_PfSvxsro-Q zmqg6z*&`%6TRqqo)n!4&GoSvfm>p((f<38Q!p3{qj{nV1q+I{IgmV;Rl;J(rf;R2U ztuQB_w~{?%iPpOdB|6cn3^sQupe1VPo-_oQ}GK(fLbeJgr$ z>}T5Pw2o@ii*k>xB1amw8FhZIhJ~TGy*m+QsiJq_Caokox{kTH>v_VA3fIdfgKcrr z{@o6_S{LO4dd{}JsHsmM{e8V;vT!LUB3!I)WWhDcQlr51oBiVyJJ4xaOqh&in@pJS za7LPFd{nt@|I+K6l`tKRY5{-$`}^hC>h*c0PF-O)Jz-s8W||NlPCn1`V{)nrUd`3s z&DAmUN^o)ElDH^Mjb;_y2f1F?1mCmM%vtwQ|LSsTsQ2}!2#0?UdC--?kl$5iX(@T9 zrB3!?)9Z4>^r{CAiUZ{rV&6-Ld53u3xe_%agN(SZ;(t2AdX5_%{r)UQiB~xnP455?{3Z8{Ln8}(*d>XJfMRE=@GG{rtc`dS8DC0II+Rt<$WZGFMTcGsk8><7f z6(%e$(!xmf2FkSgMY{4!Qsldc$nBKJc;KIMl5#TX@+;%o%OzggC0XjN&NJJkkMRdy zxcv~+g&|Bk`(C)2A{}K7O*3?YFW?K3=I|=_Jhj&Q`Ns`CUV#Fmt^qL$yNNnUR_Yys&kOF z9qGI3UQJv=vq|L|?98>!ooD&re*9<{K8+TqjV8+aEQQkwaY8ujDI9Y2%(NWM3lVRQ zE9j?gY2i{Yi&;QrtoF6u1@qK2t>9gSF|eXdNY57eUi1C)T+{y(*ncjlr>s0YTHg}9 zpZ9dFV#dvRO0Ba-D?`h12a%%mE~HYDoD>KH*5NhURXQl7^k&O~cx$&qp0Avg7#x!W-&j2@0!LlZA?)&K7gR zJ-F>Q={f4>>lp|(T&A_5zHDGN-R_@4ft`Q7K5(F$D$BBl-(a|HY!KeBqe6ea_{z;f zatnj4ybp$q^?Az%p+$mz20!!vR4I`m{-!2G3;HcJeDDMdojWKH)IBvS1Mes6oKklU z)4G}|yRxj6MY1HUH|VCV8*QJG_2XXHUuX0+!w*?K&F&W$wwo;(yJUCQ&vjYXvP;Or z?9H-bePZ4@|Cof17q?a4Xe8r@_uIWCDr1ZHOvkU$zjZmtY_(IuGNa6ud_DoF;&Sam zVR5x@&Gu{h8iY{!)fRpGd5aeKhVBh{y9UDzu)^5@gU$TvKq3TWFmyj8M?;39StVj{ zP-nQ=fZpGTbg$%~UQqktIqooAzR)O87vMh6tOM^`vQg^Kwr>A^=*}M?y^G~JO^+tSVOc?m;goQ^zu*x*}i8HY}#^2 zkH`(A8GA9)Kv=1H$QUb(ZJ%jK8|=B~zVwpuHn&$l&iD>LM)l4;(Eewv;}In87^8}8 zPGIO4>Itk|vL?N7zMx@YrosK1Ge>s~(ExXy`?Vz|MELK1?mAN>N4IJCZ>Pq;8ymWx zjEF1-)LOYNwx}oi98kMR#F)=7M#%-rB-LUGJ|FW-}F0 z#9efKRn-4txbTPL(%>Ie5*x3FrK-HhO*d%61Krs8hKuEFwl;CFK^L4?(f#wqG?t5} zX_Q8-$dI4bo_JQ?`I5J$G$@JxWmpK2aL*RzplcHeV^d{z&Nospq-X!gS{bRHV83m= zR;YJ1bk0>U7`kR5>z+hi0&|~e+w=+|dGO0g6dtnz6SV?@3Ww%D)$Z6)62|TMstW&1 zYAk>B<^>WwM*jCOZYcQE%V%fhAx)IbP>5saq46YK#mezorn5X}^|GxLeCi!nSjdkj zJ%7a9R~}{etLI2MLk#xg57?Uw?2^O2?SxY=4kS+bEnkU{&nROhD>Hcgo_IL#E9i2+ zroAdwc__APN<2()TK+0?gK{Y6BP_*L=62;!k1HEQnNf2YSC~hYL*OleKXJj@L`2rw z=?lyZe8!8qizL{b&n}^7tm{oBLdi210tvJYt)eS8+Q$eUF0riD`Bxc83ArkHogbs> ziaz^wdojShghGzumm#zK8+n0P@@ng`b8mdPV@0c(yNhWRMJq#sIlE6KUy+~kxcL=c zS9R-t7nYh_uHNeDfRDcFrzCT{jc=+wZ(fu{_{dj|L`!YQUV5$N6Y}Qki?}B|^I~-I z&lTZUBFkE@Ui-F@bML|!XH~Rf!?)7f%1vbFugi?wAp%!Y1+SzET&cBVt+QcO4|v1; zGVc2?)#-%5G2*mGO55Mims8leKdf!9;kGS$|@txM|w}Xnv{S0vVFbl@5Jd7bxz2LIJpQ;SP!avnY zFa%NkrUkBMe}zk=^KfC2KYnYzk&?vs-py3mhYPQ@ntD51;fK9FGG4+gqA6Yul{-|E zgEBwv!PU(_1-&XRY2U<-F5t>%)*8hVGpY6Rn|k5shVVOf&biq>mkxIN-oIlwr?LA! zwP})}^m6THL8Gp>IAP-KUDyT2vnoh*TAAyc@ILW?e?c^20!jRtCGv&f)YTf*h-U^(j@-@emn}fafIy9k~OdGpPLzC?@ z;WZic;d=M-#H^SRF?4+_x1g>Ol`ocgnl}&XSdfxx`qo#Wj*y_RCBiN`2kI;_eJm^C z;%eCaai$G3>F^50B(0v7@2Bq2c*s1=rL$H>Ty)&KDCIaW&ut-iui?#akB?Gi*Z7@BN%Lux^|k)%vytkq zwOf_J>fO&8O64|;f3Zm_-u$v*^fPs=WcZ?a;x=47U4$;3Qz?a79QWvboA7O>v(cJq z(;T>v@ta8WGi!}E`4=%sTP{mkrVr&GS4ve^cfOA)3{Z|K93kQ2pDs*$t_MRr(<27$ z-y&8h)9UMm^j=l_0rfUilHUv`lGBHXoI@^5C`@IEsVBBT`}m|BGtq+LiNiusD3I3rh{MC~1MIc2oA85?5Er0}gaA+?<`@2-TjCAdQ3e$h{!9%(LjASTDY zg9VVYyU(V>XsXiA5^xeyF$S4AO}C-a&badw>ns?YFE+f|ob#AmRiyt{v=mly@dL4# z>r%sLxa82g{e~(gd;16FYKHc|<9B_F)f%!`G5gh(66noZ`%*W@)4KuEG50dZhEvkO z+Ld0ghNX8CqjA}vxt5{#PX$?V7AQX4JbScQ<#O8bVik87g3z59G?>EuOskt$Lwl}< zg8PYq3+aXzMy@%}WWB1VNhbnUidn+JbD365y=27(7e+4RoWk8M$+87uG3`1~mc6TVkuX#6Scu$o-bXj4{aKHXUQ>D{Yjis{R+i zTx5un1_ZR>vGI6~m5i3YjH*6(bKSdnEGAM|kz#fi2f0FiF+74cV06>wu@2xq)w+5C zWQjcwWw?nkzInK+Jn9dg5;m!rdKb?9juwWa*D4V|F8H>PN17x&yLRK2FP9|7Yw671 zyB^W^L49d?=0@uu@|YuiUVmLt#X6Uoqca9_=y4{nyElSS?>4FlKlQrd>ns!!enQP* zbKVnPgJ9_O&q$!K4-bPB0RFSWB3GqpROkPp>`maIj=KMGBwN<(dnhDi-;HFeghY`& z3WYJ2>{}GFr$W|BsAS*9ZZO79DccOjo`wly$^O5ip6B~~pYQYizW%@0>vNp@IrsfJ z_uT8V-8<);&s4(>!`Gv9t-wRaZI^=*_lS~2S)8{DaW!04Ma3oGH^J=g ze`VaDE(cLn*K~UX%+83cq^08YZ^Fumh?49lW$)Rywm$-mPw_;m@qbWHlWhnDtF=1c z$k5)bsi^Q@@0L82OX;NL3A3}a$;)I9GVRW5VM`xmJU_8#HDVanmVZvwtphdxN$WgG z0qWd{^e}}-haW{|-MXjS%_;pMCm!Pts~E_u-zHedz-ghD>5q;|-wU|Q%?+($N;OAQ zx)T^`BsYfb*e^npQj})}?tutu2M}Q zlH2-d?A7(KKpj)KP3buy7{(tXI{;=CUNI6YnReH8?Mj}}3^bdy4`VNg$P-_fpSs^{ z=2@s-;?_z3Bz)0jyqYSOOuk-4iDPEp>W4-q6i}NMs@(}izt)0^~>uFuz z^FHwQx#$s2L06n@RMKm3UL+XNr=Dw4TmpP{u@4R^wLK+mo?oVhJ--ZG@cwtcTA!2h zJLAP=q-^m4A{9H%->^kF748zcI?f+-3Wz`nL`6`R93T`yWe`O(DE+bt3EW;epzf!t zjGE-FLpIaX*xi^4Pm}NB*|M8A`tD?;K})$k_Dp0y(sOmlX&S2_m-@PHn2M}>7mEmD zwDFgG`MM7gdW5!hnwmV@Cr+HutOu>O!hLPd%AR&EylhEVck35UD|N08H%4YD)jJofm8E4;;8K(rb`45p8!d_BLN_<(5 zM3`x%OjF{G#qJHr<*W-sdsI+V;mfPf-uJvUO?4|RR zL3NU6hl`xHJ#No&Y&MB{65S{KV8`2P%p(GDr5Fpg`le*h&n}-36Lq%3crB@2NttgL zb*&;-2O7fJtUS>SIly&S;(PXY71*0QOL}U5L*}aMzn2x7?9Se9e>{geYpt_7qt1E% zR&N@jPjYk|1CJ-1BQGI+RU69RNI{KRj%eGS`&mqi2;PlxD)#uC?V=3(oSl2Q!pr|M ztJnFEQ{TO;aiki&ZiurnI9uX*VwwMV%7spXL@XDH8Npa$Rix59b>xCi} zDPMX}JT=U2OH%3;gVdK0|M=Fc ze{tN7VtEJYb`(jgF zGNyw4NKSY=sQwCm$0bylEjQAXwOu z;Q{+$u$ME+^eT5k<8KpNie^74S%v9Q=mB?k*%wR5$QQ}EOEvs@Qt>VQP~E+-IrK zdKWCc{;8ZAk_;Z0!c2u6@SbMN0MFWo+b(y@+}pz9&Tx3}-w&Xw z`w&*#4PTzltVb4Vuh@Gi-%>@7Va`4#jk<4}b&_P{apQL<(XhgS(p}oZfmIqfk%2O} zW&Yoy7Xz!axu1`MrFdQG^KEgVCfvpu=mP^v?E`n@p%TMV*7(Kj#40pFR3tbkJwd)~ z9y?>+9&d139Vt;1LS1Y$d@d4KVWSB{@u0|kdp(hmk(AWFVElf&5M0>o1~Wz!Sz>1#VW+1GSOk?nTqH0+0o`UmBm+#O`DiJjJ#~ zVYwz!bt+{F<%U9O1$B6=4R##pPK=;|hfjq41PD%54&kp!m_ijTZhPQB$mPQ19=R`V zMb(Ez^ta5(;+#8S8S7E1jf08&uObd8bwdai5pGc?{sQpuA(1CX`8qk1=_iD-oKx zW~0~s>T^Q$g*&`VW}Yg7#dF@;R$V_tJs*EDo+HZv00;oM0>Bs#04M{1CjiVv!;?V} z+qpyl-~#}0q6Q*B2>@UKfCT^$#&#|g01kEAUoFRnT^Q#kHS<;k04M-p000ECopT3( zNdWj94>WKC4GI9@3IL-309>NZ*#bZl0Js9c7#9G@1HeN7_y)YSJ~F{{i~t}T0K|zJ zhyXbNa0Y-upy4ghpaB3OL>uCO22KEw1pr3?=mmh+0B{iiY=}0*fk-}1V5AHH+yj8l zXkv_OP~35hYX?Bb12lVXXYlIUT7+KB_8UF>DjB>-;j1zW&f`C%HGc~yp;a=sFE~`m z*u$!1ARlgbJiPz;Ht^Caiu>MePW%%M|62fi(f?T-_75@HKeQIUVgik=Wm#|z9Gx({ zM|y-cir>u%dUGT)9_n#4gDecS=9LmUs4&V7p9*aX$AwDq?qOfln@t_U4x4`rz_nC) zRO)3y6AWxl%ksDeN`+XQZr(YSSb-9BJtu4E#}|#4e}${0Y7n zUn0nyg5yZ^7)bm(g4sGbN`=RFKPO3JU60zsCjHQ*yMn7ChAc2C{hBCjgaIME}+fO(}SCiE4 zuqXxH;E)uvlDThemuhu~R;eB)3iDgw{P{&LE(UeP=#%}H&!G4!)P`cYRd(P;qOcQ- zF_Sfem8nvpdBeTHH*5n{U1>&-XMNQ+ozoNI-3@5rv$?ICF(0D)DP{it0K#36dU@SV z)}K1sWgk0KV%wm0)NEXvrfeR%miU#u&A&d<$rgh3SMu4UgwTn|J_}JuQ%G-Hh$zY2 zDKH`+y1MQ((Mtojsp$u96f|lNTZ9-4cX=qY>G>p?vlw}bb|omG`U_}$xKl|;Jp(>{ zqtdZu`X-6X427%0;R9OwU+iyW?w^qCawp@Nycl-p(Fw`1KgB}t6L6a9tmwr@mR4YI~`3vVO64|A=<<9;rBX zIKZpn@oWd1n3ROW00prIK`~te)3_j0?I`tHzc2O!5|ef;mMZ?sA0^bybxf&*18JeG z#sctVY4F09ZC8Q9+LYy;%u%OcNdGX(wIV(G;GI3L5@i>9e@#-BE~jaCVQb@OGbHHI z;gR}L&K^2+@-0uey1B1Z?9NuGgw9mkhI7Tj;J6n10=fpLvGt=3wyYF9T;-@zotYMI zD@G_o`N8Uy;8_g#-A#n;LU48>eHW=8*N&pbK7M0m!ezsyUQ3a$Ze@EQ>9BXlrB{xU z`|x`6oycYblwn6}kn2uWg!gjLwe6acP>@(_pqsbf?2YZB$NoKEx#^2^QHMd-J7?jW zwgJCG*+Q4_F8k=H2YHIk6Nx*gxfP2l4Vs;*0vPxukGd0mw?osy0`_MP(TW#sn*4M` z_6`X-NAKAoFDy&v2;=SFDl`T{m%5fz2N&0K;xst+)W~;!CaML) z_k}KkkFPDpUQm7iOY+bo?zE!hyO1l*j$X?zMA%3C{FfI}HFoya-%nz41{Ubl3bzIo z(G}_2D;tCi&)c|WmfH|ELAhD)Wk>by;GM42Y4Bloru0|?$?(|Ol2FGLKDhbezK(M& zc4vHl55Jgm*KU8Z8qI!jvZ1aqB12+1qOZu4)<4Ogzuj_vp*%!7{^|b4q4!hh9-(S{ za8J2+93NDbqmP0FCO6kVbueQm3|)LznrfgjgplG|M?jEs-$@QPViUh2uF5p9waC_H zdMR^c6O?i~W-={z%=U`YE7<1_d+v~(dKdIpUk1XLr8M<1-?G<0z zy~Luh#T8{SI9Itf;`ZC=np&EO%gmVb%-HI{OFya5tR13A!|Cw#X@-TabaiLBz`=*v z=Wi3Pmw_Gm|7(YyYyFLY%hsFk%bJD$^cHeb*X+_U53?hR7L-RHZrK%%{V8Qf zxD^W2aFqk;`T&A5r>RM!(a&G!v_|}Fi8!vec|CXRMVWExJ!l5AZ65>#_j!?WdNpN*qeV{fwXMk3Oe{LKiFol+ zAa^2flDk~&uR(iibW`pXiJi@PVzv)=h1yGwcY2vDUVbRO3yaFAV^Y|&YNIsb&ot<` zf%#esJKEI^M1K1cjjjHe^mMudf|fvLeLZAOt)(xsJ@ zi%mBzMZgR~su?j>>OHVFOS?AE-k2SH8ZvfcO;yZBA>ZL(uIw(n)*@?qE5XvoF8 z@H{jJ;*mc;vsF$#J0oV)xHcE=fVa5>%N>@MvNEZQU-8PFagY8L`(e6bjj^6zo(H`6 zrF;wd+4Q14WJbNpTVtl!9fgYMx@{DRCal?&551VCuRTSL=$q)^DAxaFOsnY2?Er@~ z>PcJWsMXODmn1q-TFKiVAL)ZJdQ=fPg;F3QQW7a$cKoiiLRcB9=Vt}FcE8n)8J0oS zn-kpzemSU$&fLAx9$|94f#fS@pV6H_y1oY|hJ=7rIu>mxEs#jZS)v(Q1QO^x`~3|9 z1xaf}sB>bXsvTyh5w?aJ+0bUl+iuL^AUs0aG!+trcHE%@V(|KbzJrsx~&_VYdzf}o-2H+q)-LMnd zT0HAfE)KpdgxkwZvh+bFt2*!0iq8KmV`y`Cwch=Jp}d%G_6oOF@U`f(RbunYC&rA6 zuTyOEd|46k_C1}jy`ttCPB{EdjmX=ztmfL^i7rZ>1!B8={q*WfscBPuq2um5- zc<^%y>!HAk+_>%eHT8)%H=nV9K%?@ns6%=Zzf*pAFdkPmHL>orYiGj}L~^v5)_vmWhOVmlty5JyOhB%-&PzpLF{7DXFZ`6_&RPqV_JpLm z_|DNvR?IxbSGtrAn22ze4rrma5!TS>U16#jdlQV<@^M-?ZT8s~Ye_$+7VA0&X}gD$ zt`yt*@;-(h9g->%b2dXRrDmBP`zkJTjzcc1AEIee-C^WPA=&a^kvh-Avwlh5oQsJ9 zAsu^VMa@H(gB<;G@@~t`Ar~s(pvGA6M3We*_~1GR`J(R?3h_Sb2&^U(>(@6@R6a2u zl7ydXmYRuY%Zbs3J19J_bBn2HW%L6MmyA)MVmkM7CL0AJ#a7M3ii5mnKZR}aDOe29 zd#WTw8xB^nuQ0crG3VlpZ28(LMU~2_U&d$T#eq84VLB@;kqi4YM0Q6p-J0gxL2 z@{9;!0g(4ZTaW;9o}y*ux->ak6cJ(yARq0idM}9EedZt|(40!U05n(;HN-x{QW|By zLs+1Fo(+`^X~2viUk`FWFrXOEt5-opv-lT>jzoDg1ltEtg7`F{Cs;=ZVZ_QierL?| zTwD=3x1lDD| z?@4ED6q%}h}HQS9R6ulw>D=u?su?S0PqzB`M*HItuen&9b|8vgqINcNa>#6 zYc2tJN_^CP$0yioS2b~FA@UlB5x3Xu0&w;E#MB2&;eT%OS~sF;*%>6`>F&d)Ed#dE zl`O1!dn^dLsjqZvhm0nIWz~*3+$MsNF_g@U`NnJ9vd2XfvB)flsnd}atbt1N+eiNj zOQU~Am<5aFsJ54McV`70wcvhI|4g73yB9x>>d4z^CO%ma7iRAMc`#jn0>e3i#S?qJ zCur30>Yh@*Cfu(yB{3@P_ZZk7$o_|Bf+5u*qOIr7~AJ4YmT2z3lMlP2E-~Rd?X?g;-e^yZ1$VcCBF`F ze!GVoV-xD>r)3Xt_}=lC4hFsw(1OgwmG!dN?#@2OnSt3d$(jwXdJKm_z7yPSM}?`s z#tJ#0(Tz&L(O9*txZdt6_VmcV7wFpm@_KXM&BYr{m$pOErc4hmZ~XF_z0pe;c_?Yt z&>HW?ZT3@mW@{;38UqPb084`}bs{at6;4~Ff_A_cqqUR=g1M}3ss_xd&2Hr|R@ z-yCk#T~C~X+|G731!ae(w{mP=U|UkWE(IJ$hT6i6`%)-^=w)-uG#QH~1#23%=O3?TdwY+!v9 zY(n4+)#2Ma?jq4-(2F(+pa67(w&vcy^j{g6qW>=d5YOs%wpkj#}kJboM^-$1}{KF1HsvqO&sD` zqS9rLRL=MUcYKMd^9H+Y@9<9CK|@<+uDQ26&oByNH7^=z4b53j@i+Tz&K#02L>Pq@WF49`gVZ3jS*Pc^nD4vsg}hAUZEeh(n)i8Y5GrJ}W$sZw z<8~JQ_I%@W5m+zghuQL1a>{U31MN~o2|ToEs7$i`5aK&bwl4|(Y>l`LlTksxkWm%S zA+<5@PBQ)_@Ncnb;q(3YM_|?E9!tDG=CNIZS%TBkf&{TL`pEJjDS3_aAM(A?-Ud$1 zzY45M%oR(_Yo1S_^d;t3Qh@KC5C0ry$r zIhirLz4rMeBQbOs+{6DYX;-k74rBoY@sxBSB_CN|lLCzR5Fz#eRe}ZwV6vxB6~IPH z;sy8Le;Nem>K`*k7yChT;Fd>hwQ9ev4=}gm+T$}4j0v0p5}1JMteUMp9AJR#T#Ezg zzy^(GNAn#nj^(I_CXWBjo4&wI1S`lFz%^V4h`0NN}Y{L$`PkwpVJlA zYwncd#VjXl4H^lb4A0~dQrAhit1)()!*k79dQNG(c)Ih8yo~1@4;$<{Apu@=I$QDfCkuXFt3Q04 z#AEBPlHkf(HeDpBF!Mx0Mj@y$I$p^>)=G2g!ELEJ?^^XAgaQg3KDjb!XZyAX$D7OT zL6_Sw(`CFlbPRTZgVK#t@3{lwep``UX61c&)@gl7Zseyg30 z?k|^56B1Y$_-eP~tun@BeqC9!3pi=;G19SfWnUd`gl8$ctD@ujUYwboJ0F<#<_AvPaonFuFH~pIK_6 z#q8UBVpuD)98U%!@zss?z6BU&PVNX{h0Nov!SQ6H<4HYGm22-?6ECPRuFJ%I{uC0a z>%vm@#R5rFeY-5&t#EXLNaxv+MRqr5Uyu5&ju9C6Le>R1%Hm9zZxir`n?>E&$R8`pLomOhS& z8!e9mlmI9RP%@yGfKmXZ0ZJDy=MVDPU0m8z#bDp?GaS?*9&f*WJG~K7=Uhj^Me)*! z;mZdJR-`c<&R**d)H^^dCYNg%8Cj0`;Ht0qUWK2#X#j3Kroa+yX@Aem^_ugx-s5Qj zeY681>0CK=7H1S>?Dw-Ng^hiA?#O#HPH=D84}`Mm?0#hbCB+C8ew+z4Mcb|RT`A!` z2;gnWM_Gu8K3?86p#^JB zw}~pi&(1{Y%5OhWU<`3aG_I!VRP@{Lcf8!d!q%GSsHt1_K_E1{F98ST(I~E8;~#XW z;vPu+4((w0A&u+nOuVBAj2~0W;2p7!G(Ab#kTy;g)vuR z%l8PbDt|LB_Z&+xX`9H>^X2{uynho~bRX~4L;on5Ale6%#Yg>7)}h6zprbI5KLUOZ zUjrR<$u>ZNXE;b}Ox*rH!KYA!((}ds3fv6;o!3ME?AIqQ-ZilzxPteqyC(I06&gn~ z0-{D~hi;)i#&2DI;F@j)8|2@`+hGWP%jX)rL$fC@tjL8Lf+>Wq*#+H26-D6l~X~l=o``1Q$hEC@SKNUxyp@Kd6H;| z-`!10$fk|j!-%e5cN`4HbIjaTp$zASsL)kG9ipR_c!&@3(A{36S@fljM}$O3bML#; zvu_v0e@>dib=Y1_r}TaWuc+rrygY7u1}=+Ts12n**Q2*zt=yvr^GZpa78`zdZ-=AU zUgBCxBDVhyBs`-c2)t46fY;#>kmQ*OlR57I2S*%(!E4M*asIXy;8yVGwfaG=9t`9# z!~WNtbH`5jdbH1T*vtfPvK9a9}l_1%}=7DjKz!?l6MArwg znY;I9?>?Uw(ls3bM!AdzH}tMES@m?Z$q)?!?|49pF2hv=DJFXY)dL#iWg*VY1)PBP zu7B%&iue>5${p~w4|=8CgF5cHMaTrPTSOZz%R#@0@B2h;U@`#OpghhM-t)KezfE+B z+KCW4FpU5T!1dZovJeK3tFOe$KSm+IN&(m|4EJ3ab_2@rLEj%t&iR@F*A@^v!{4}QR2(0SJ15Knw_C_JLpx2-<;whKL{vegQ!P|8wNe5N)>DJs?;Cf=Yns4gm z-#{=81W$l~hN$EB{q=petpyyvO}6wS)9Dy1JyyvsP)Pn;xO>*g#EAEnxgKlGoXV%w z@PDuWC-C12o%so3R>`;zt>Lo{kVE{2L)H(`GMqL_qTbLOQ~o~- z_v0H3y+1SavM;NAF}^qQEWy$z>j(V)e=byiE&&xmnctoza08fVY3K!JUZ*=deHr|v z7|1P>5}kP+{>iODG$B+wZ*N+}R`RevcL)ETUt5cSU3YqQ)+BzeoE>FOq`0N`C z-Bb(e8$UjLi#t2+BG_Iic<-C`74hYtO5WWrupW*fu4S2BjAG_x?mpe^+tEp+Z;KcO z)U|6aKe^<6L7Pg~w^in{w}`lq?sltg)DN4{9~|mbOk`go7zH?ZRjVxNSDsKIoJ;QL zmRNKckN#j(r{U&(XQB`hoAj+B_{eWI300jb77A zUcM<95tsC`6DxSuXZ5|%y+789G!Qf^hg>&aBF_k&jm_h!i(7UW6yg^+7ljaafd1%` zaJYI`id)@D3a+QwWhd2>#>`>$WR9F-Q?zsEl;ma4!|?GR%E6i!9gN&Jk{jPB1a#RX zG0A)oY=0ow{!y@fh+AD@*HnD=iu=YW?nN-m%ifdh0{LIGuQ*RKcHEM7X1?yedKBVYjf9RLFH>dFnOQzTC{F+a>C$x22Pq`)+z5mQOkgm8H7+ZIQ#!N4_oTL6gHco%Feom z%!-ToJ=w3LlUc2;i{wzC@;!gECK%6U^lLd%W!68Ud3OPMVCIfLqWku>s}jTOS}{4- zS566jnfi7UHamE@|Dw6C^-6`Sm%xVDbxNa>)z?-b?fDmtmEij^8aW|K69=>SpYEeu z9##jD7?j6mYPP!JK=wDbwedR!sD6=0dj}FtkG2kW`r);Y*hJQME$o@M)dmSM!KH32u}*Z& ze#4^B%L@30tjq7ot7ATtO7OFOoKj+Etp?sOH-mFz;AY}BC8J+`ur-yua>mmv#?#<0 ztMRmatfCm3yQ%9^^>mH*Lsc;FF26rq2}ac-U4V+BTjDn8_1KZ>7>Nm={S?C@)awsv zQ@fK5DhIQD10$3Bky`GGzuxt|W5(ji|{STi21$ zPkkkgJ0y1~{n9k95z2P@f-mR=?N8fY?8l)>pk)WG{JS2OYDyi7@08-yc%%;U3^r#` z{E$0`d5Q(@h8LS5jVg`p#mQ{@Rrj2r1;V*yrXFbZ1HT>ACCxd?#nsY<8CzZbt2G}E zX(`nhShGyPO_=glg}M*UYX>emnX%r{SH{q6*)cETTY|S~^53C2ctUuZUN`1$CB0TX z1*uTrW3)t-1n`HPhRD2AeNgwIy0R`O1V8VyGnX6Ws^O+p?;OhjC(KO-Ltl5eP!*qY zs6R-qZ;ZQ**ex zQUYNLi|PY3F|3z$s_Ho zmU%@r<=~?QK4*>4n6Ld?q^0|$Zi##(tCY(*LkCB}gqclhNCqlmt<}UXgeLz)N{08L z34ci0zGcnSK8}2&eo4*J_s}1w`W4y0%*|i3(+o9y`0+&_syO7xN!nijDZ>8Avr*SG z0e-!C`4qZoFQ<0LmipBFo;;oRTD)PE6SBW7r+EhN27hp6C9t_uu}gtBqkg-UkJg&& zbn`NT1nyBvKpI#-bS|?R9)M1T1@?G9?-kwun)im2{z`1!?gdSAd}^$U?f&LisB+-K zmg8tp^|x0V_4P-n34P}+c@xDroI4`R$Q`lhurkk2gW4)|K+GQzkXIXb)=p;9dLL@4 z``zkY`rM@D8#BP?IQ8z}&Dd3|psm#h)e_?qrut-2fq@k-;GNj#l!;oC5eE>ZUDJG} zAHFT~$)O>Kmv(ZNLieTdMmagnU4sV?c1u0Xrl|VOzIP~wuc$8)GUjt?4|Z@vE9wDs z>PLBmQvXDrprV%Z;x0LISYyd}y?KS%)Nmzs z=wM<;f6fx7v3Dk97rNkL)u0u1qTP2dDv{uZdavyEJ7ao!)~GwUz<_ycHT9BUVr}zv z|EZ?ShBgm+l1wPm9-qzd)_3R>c3KqmTt1o+E$<6IuLCu4;*7*BG|8~k&YDRni-WZ% z6Eh%L%$8yCzX2ABV(1E@=?Y@#O3XD&ED+N76*YLy zHWw72a|~}h^=Fua7ZmXSD(?HR&)dkXt{Uun>Qy#j^H-y*;06BHX%cDS?BL&BNd7tv z5b=NucF99c&&amc$w40y?r*IX=s(>X+Za9A*RBzyAFwt1q`~`=aH@!aFC5OjQkOtmO9{6Rc!JMldV~ zGvDJJfnCnFFZPJu0qbgEQQv5jYFQ-Vzg6)!;ooXwNl|IrJW4fo4lU9P-1M1yB}`a| zW7}uA#xNG5*d+Mw-Nig1+EEcznG<|Nl6l7wA5cG_M%dPYj3-9-b~AmrLCEv7Ez^l2V{f6YE7Z(8yx_YRU! z%S3l#i>{gQZmZJ5nMz@QMrY|6=FDXNIwJ)}*hJwt{Y;*^Iwgo;94VmJVSz9D+Puu_ z-1GRfGX3sv?x#hhP`3Za>ZpKg1z-8_uN1#;-6%2tSQ!;K&+8>(LgDIZDrNT~HylJW zq8FSAGfY?o_XiZ11qp*NRq$Zs3xiHiS_uF6}o#;Mx-W8mz&R=FV4_BurwG5cw5cGfaY zsan5}tML|ULt@q5VnMmpl}jwfcU2%_*Gr;fZZ3C)Q68u206}$bJk5Cys&@b4mN}|h z=2tz&ACgku$*W$FI>|ADun*)n`x}`6imC;2BLp zG|is?b>p(Ul}`7iYGZ93^s4a}E*;ZKkj7_NjIE?hD4AP4<`U_$ABjbQn9!N?5(RYo+BLb-OhM$`!hs5;aukZYP zNr@EpP@eC}^pLI`4K5uhlH-I)S2ALy7jeYGazx;ZArQE$I3}kZRy4!44Z0Pa0nK88 zD>Z>^O6Cnsv+O0mSYt=FW02g($-xHlY6NJOzoHpW{I~F6bSBlRtCwJl{|Ek)k_sYZ zuB^t=<`A(+5GSnFqlX+k&*l!UR*+D9V~}7Oz)`G?9IurFKd`jKJD7$|I|R4ByLjsH zIa`pmyGfipCFl;L8jUbLNrKMf7K%!WfhKV>SMo0Q@OZnKOLkY~pV(bUQ(}aFh}7mF zR$-`_zso$ZaJg*`hCsPxt_~* zM8Nmd&EcRst6ZS{N}5V697 zu|ce`j`-eyvF;W5(iEG(8p8`m-48xs#kSBdd6%!^-;BDKQId7tT2?HGwjDVSkNN#5 z=6BX<-4p&(9vgL8IoXM8LtYP=t5+l~$SN4(JA$5+j6Z}VbXdu1JSg#g9Rd&dx`nnC zg*@Q)Js3sBs=l(erCWPapnA=D)ziPVFeD_A-8Vh8O^iU-0a%UfSImD% zi`;ySzG;;+6+i|3fsm>46^56cV1C3Kxn4Q7*imo9Ghfj|_rfn@v+kM4!mLGR;-ho@ z*J4Y*E4NFg=ilKwRqG+agN)yK*gO!ty0P`WrU1nH8Qazn3caTIm-FA;#Xnid{}S&e z>O9J`C&!0g%-EhWuYqKV44Gy*-;~4#;U(qi#G460Flj2Zch1VNUdb10^Nv15#)A`U z*i~W2-6ibA@b76pJIN_mM!#q`^!`aduhpSMlj_F(2Aw1Yv;)5y$QayqYP3?B7K_0k zFOK&aXuS&F=gQDkkgzZf;nFu>pAAr{HVCd?*|p+(bvnhMUU}4^s4|0D#`{8PpMwl1 z>@-S+CUZiMW%S+)MbiFqxs&~PAqt)V0nYU}Rir%lYJpQAUuODbJd08->LU`D{wehgVH$m!;111r@k1&`}>suxa~1tLsX zQ85mq$9v%B`a#Sbx)!sOMqP)`+I(pI%Exa2me)4_9)9)9Y*2H@qP6zG^z%oUp8_gN*J{Itk zqdd*P2X(ST7+r^aSx#g}ntskD3rFvR?{x%+TuNUl!@V+OGkSOwTeN+~{9$8M%T1g* zRf@$g0a%%z4Ay?_YzuOxD=Zf2#jj?mM!o6^1j?HzOv4ML3G`_L1@VJA6}9Q4i{JQ9 z_Afl7$TSIMf$PVj!uIx`A;V_-U({bNK}0yNt(US=Wcu=*?60_e{7D`5n43&~-?WjU zFB4)wE8u%M=4#LAZi;8~QYu{L6ehD&5d#^!qGMdw-oJYXsy>La89A;2k!3^nI4n$}%t>z~S3b{w;X3&q%<#O?aM-((A!pKjAq`!ef}vyZD{8+9%A}24 zCRF|Qe4(RO%3Ezpg`ONk=5vJw`_m%)c@Ylgw(7CkKAOo5X`WGCk{Tz@mtVEc6!i?D zx_M7Ev1&>L%`(QKT$x;|`u2I3TivwroTPX5*%Gf1`kQkQzgw0G7#Dko!OvLm6FcL6 z^=zl)#D-}3Nc&%h0AnU@X^BgCy#Jt_mO{*gIzzf+=WQl#!kY(?7%_VXJ~_8)O7`{8 zRPoEDB6BC&9W<^(N+e6R$d(nIp2yj&-*|YbKVnO?Td8Mwx!k8&)HM(@ygo@AFeFIxWAcl({l zNgeRH67lq#H|A0j;&seuVlZDWz@7Cqp9co`Ufcy@O=hBJK=>1f&QX|uoU&FzBl`7r zd|D0Fi|F&7j2>JI!9v24y*~?Ck{uRWVP$t`Zum-OJN!H@ni7lna4Ss*)(adj*z>15 z-Lka@l2mnE(}1ng!I~W%FPpFqe@7ZlSv%o&7#ip_C{+90YP$Zg+di!Ox}!`*LNWzM zo3m!i^5rlnoqq$mRE^A0&!(k$vQL;3aaTTeO7@=JxkWd6W!nnQi=SfG1jD`PlbdfB zMrc+Uv%1OYa2pJEEZ=RR>WF1TjJ1c2@kS&~RK${2G3CCAAL|GkkG=}(9YDS2Gds3& zRY!q(Cy|JUxuWA7tZs2J3ZG6RK53UykMU-J!!k&#o=b)+II5m_D0EVj`#cTPb>nEe zYnOcr&feQzcE05Hp47#`M-;NZyR)=5`&^HyM8MiXX+t#o;seoX#_xAp zf_!{+rW%jF=EBg^KE12;TCp>)DpaFdV_oz{u=F}`uPt1brpGU?rpX;<;L?N3QupY8 zO}d0e=R=}iJvLL@ab0UyHo z(%(dNY+`S>E01JRwa}?0PDGJlIybSBo3g1MD{dh|q;B3W!=LH&6NH8sg(fAWB@!$|{66j0-Y={I# z$){LDOQJ|n^Jyc2#lDFW{Bf6MLkbMR7sW!}aIdGUWRBZ?HHrki!=W`KsHr(6iFgt;@Z+6|lUlsOsk0zi?0$S~1k& z*DvozQv6^xliQZ9SA9_ttIO?7VHM~^haFdw#TMt&P4{0=qiDA_;BGaDmDYo|-E=yK z@dvBdmCsJ?e!mbx}l5K{p*W4Kc;Y(Q*ecR!Lf zf772^Z0NZ3D6owN+wX3E*TUB4?YjX8*qzqptKsp-c+P}Y5NRD)LRlP@SK zm(NTuVNcV;<-<=G-!LiFz0qpTtx4^R4Imc#!ug*3YgJJ=-={ZG!av@6sGA-ud2-*Y~#k z8p6x^rIoXoO9a0m(B|`>cZuxTA9f-hoez}C_RSgqJ#5EAF%GI-{x(`q)c99GwB(=G z5G$Z_9u>f9>p)d%-xbgTxPCy(ieASyu?awRqS61*bz76+)}R*i#vrj1%&;QR=7|9Z z95|?R(++eb<4@Fg2clY0Xv6WzWZWvv zcH+0VQWu^cp@G=?g~J3K#Y|)%!M?Lb^+Z{w=fowo#k$9S9TRNy{cvT+{Lih8hBD0M>4}zq zIbr;!v6(m^0=Ivnrsp`sDatS~G7VtoL}CU}0YPmGX#Mkl`o}4IO8^?bSjJA@Uu&bJ zv={&y_}kh#+#l>P4>(-pA;Gt7VxLCH;w_YZuP)g+%x%c7%bw#Kq3w8)Q&z;88S1o| zj@a?NTf#|FyvnOOUU+?=7V?`Cem7W>6hpj#ishF`i|GzY|H+Bvf2F_m_fvJ%Gak7*dDhd&G5@-N~go+%|&|6gUt9u9TZ9%eACB_bPPqq0;geNrn_ zqKmA{CU%kfB#*_IF*Jl3rCl|Jw)$w@S7l_^xKw83o?6>#jMSQ#!MKeT#%&m54Bz`h zyT02W-^?H9ocFxhN`q&6udfl`;l9A`@S zhJ3~M#vw|JD64RrSy(}0Hk?QE4qo*ZEGvw$fmi~U)vd)|yLZc5EwW!t=LKMk<}`fv zRtvEYq6pZG`0az;3N~0v1z-aa2l2xyqYEH9fH2PjQ$(2Kvash%-hzxFArcouRIMzTim*XSknb(a5o0D*! ze#CZ;&*}|&_eIt~!y6Y$%-nEa&r@ow^MvlR=7OLvxxZ&_YPw|Y_chHfPcq<}H~8W) zh5GvK;ypL^WbZwV>mGWY5}V}smbM97`PL%`YWOo6H+?mf@lx!s^s5+V9Oj(oVR@dd zyaf>;uSShO9fR>Z?vVo*90+x=tjycHMB=t#iR3f2B@!(qASv5QMdJ+R+O=QEF;e13 zsJ-z()|NNBqn12BKO5ntwS&W>OU`4T({$1oZxR;m4Fq{i=N%!&WPxu|UU3E`{=jtpI+uRjF(eDV%GY9HKaox{K_lS+wjmsJWvMdHZfiXk7iAh&}M#0BZ47^E&o?1H)+STEP*APUI;KUXY! z&j^~1i=Qai+<^LI4Fl5Y1o&kdr*6W?R?G{9$ zF&8_1$?-nR#$bA4jeFHByFi*VAxo=qXYx*`_)5jreh;&Vo_^QxMQ!Bf=?4L%ibh-3 zXnU3mn*O8t9Hy50IKXTqr$UWc9-xAcYtrJ=z4NhFVj?aaxeBjL zlz46}36lPJD6o_%l`InzpPn!VtcPv)@fD%XdMO9-vBCv%#9*nkKfZFVAE~hJx_t33 zcM;gEx{DvkpLpTV?u5l7XlIbt%p0)uqYW}Zr{#jGz+jK9 z#FR7)!XZ9Sg9+|7A;8WVIy6v4NtaOs(ti+4w1M7Bw*ZlD30t1PmIc7y!4Fd}*%gA@ zX!?rP!Qc=_11oR{Y5JuyCpLWPNdWGvX+CT%*LLr3ucaf-{3}oI1g@Qc1-%()0KFOF z66nnkJ(jp3y%{Y2TW=OONkq8)kE4KNV7ich>74BktC5bU2>(GUu8J8bCRTcORZp(0 z#1)-e$4*C!e_H}dc`IN9D2c&Ph4^i7h$njTs0bp4(60B5J~0L_gkCR*6Re4Jf}MIJM40Ni|1!XIKct$*V}k# zjb+6xPI@m$G7|j8!`l}VhekXpl39_Tp{-0d5ja{a8yCp@k{24MvZ{OQi zciP!@XI;>5O)1WbyE}F+x?-3>+2dnhxzD;L^W!fK?SJNMJQ4UNyiHU#5^F#Ujv}A# z$hPTi3rd`PJJm8jf^U$u>2B%}2^_;UoaGop9#`3=Il?Q3T>%XZ(y+8gkrh`ROx`$* z^oqw9{A$y!4mYOJ6ItzOVOjKCS$ms|#wC4YTSf6|ZW~B5=IL0a`-J(h747uIf!#G( z!gi6eZ~k!7#2xR3*7mXi1D`N$I>Ygjo&rvjd5o_nPx9iC$L{VE2p%*9#>`yJ&|&1@ z{b~kA=sj1x*TK9oAjY~U*-5O_Qxn_No&|cp7&YOgh3(sAEaXk!#4=dkBTCOgb?Axf zPQSMAAa>75#e(u%N%88p$nf(Xl&y1>}st6W)~N$esxSQ zwxD@)XsYN`tD<2c@mR)C{qc?i>Z>O&SjRiI;o!-9-MR%q(Hs7^*!g;Ywo}Kp6wa+Z zZ|s?Pn^&7h(KaJ&dQlk7@0;4W9*Me9T)MQUNc`+XB$dUeEm>5cj5A`{&dC`KNBB?g zZpY4RzJI8zP!}3acI20rS7#>-Uby@4q+H!}*$hn{?{zq(?rf;50)LvTDqrjuh>enc zo=|t~r@xcmz00z}s2>`ioYYFFilq0Sz(FVdK8Xo_OpXPHH5u(Qxw-=JxXow1BSB&YD1}6xvvE(v&5`C z)B?4i&kvQJL+$Om)3xU}6yEKm8^+@X)y(mrwuka*?aLheaqew}qd_rcX9}@8bn3wC z%MXn(bZUjKqT-Ij230q&+)=wm6Y+MUJxceV-{|p5f48gl#*Yd=J3dZbQ{{GaXy@de z?2PjTW`()b{DM4!$F}02fcon?230S%`cU4|+MiiJjwz>x^!7CLn=w*Gp;nyPL0 zBVO%);Qt@`T)C5+1o94`J-#>h(Kf{v9=-IF(S%A9&)z;EE$Z6T!wZX&C9*xPe8={1by847P~_ly48{-;fI|Hf?duo| literal 0 HcmV?d00001 diff --git a/third_party/date/test/tz_test/tzdata2016c.txt.zip b/third_party/date/test/tz_test/tzdata2016c.txt.zip new file mode 100644 index 0000000000000000000000000000000000000000..fcaac05428aed26be053e7d57d118efdfd5866b6 GIT binary patch literal 127331 zcmbTdcR*81(?1@1Zz@fy1(dGRyUImH1VpM55JW{<2rV>$C<01Vk=|59q=N_v(m@D4 z3PLEM1_(&+J^VK4z3+XV_x=9!)0~}ic4u~Hm$SPwpPh44mx}rrgdY6g{q*V@Yd%8YR%jra6v&3s<)4Vs^j+?YVbqVx7&KsTMu?W*%w6AIMky3^AGR@p?4?;6@h9XyWVe!Q6#s7Asqr+?lkA>7$k)!bWx_mLzpfhv9* zW|y}m2v0j|?!9-`aJYASP|iMI09UQFx3aQvLLIj9wycw6NzS91BKIbE=-MEmdW?d&#e@>xU%I?ct-M_a^An%a8L?JT<_O4t<+ zAhs-E+bE5yGp)ub#G->3b`f!Q@b! zh2|z&y#y1;rK$KW<4JUMI-;_4Yzyn*NQjkxFmGnh9oHN6a5_nX+pJ@0K8tWi6W{bL z)9FddIe_wtMIF}4f?n) zKeaiJ>60T>;CwrM@i|Uk)4Ujv4sv9HpRiO@*S<(EW6=^SsCW1_5{~xwZNaTp>=y) zn*0I#>r0!1@iK}By)Jg0m>P}h9n$h^Mbed;UxbGFh7j(EgQ*|!Zb!3EXuOe3D8# z_mP{A;_!8j9xNFveG9=bBOv@|mIgE&C^jM~=lE#) z9@SoQN&;T>c+0KUPEV%oJJIJi}`V zs@Tsm-8?gNADokD`DCOXHmMfq+0$Zc#X7#9Dr(HR7M>^`MrJkCD&~3w5t_T$J`aF4)j6qj$JOzu?V-|Qw%m- zeL7|!-=^vLngexKQ|ZAsDjl`B2qg&HkIqv(Jvts8=KaNK-q5EN#-7LmZ~CdN6EZHQ zZdXE zcFWw`tKTQrrUVt$-N$H%baK>JS58V$&sy*Fy?s8t(KIiB_eL)l0hLR`oTDoijmJ_H39zsf_PNEE!FHCktTF1? zGNTvtlqkmX%+Ds?(W)fcVyg_>!j~3>uPh30YTs0gcD~6YBQBV%u#%PRc+5Z%2RBj5 z=qplcFd56M_wIBfC}(-^t70q%N*PViaXFXAnH8g5q@VGG9RFT&va&c2zT?Zw4c(H{ zbs5uM-_o~ju%~ySQd57$qon>SDem!&f%8#l`m0V)jTYKZF7aG_rY@*J?4(zk*iol6 zm5cuQwpmEz?D*;`ms~Wp<^$u4sLRu<7755z=ToCE(^1s?AD1L3Fng6Eqe__#5G93e zDdt+koTC(d6R2|($zmCoYfWt`AC)h^Z*#GsL>Q?=AT5H$@3on5s0NFFe0<(07{`Mp zN*#l2GR8;w4_~H$fB$rHB2pf5HBx;1I;u-tDHHi_xv8<6ixJ6!m~mbHQcPKfTWFBz!oi#Rm`X1uM*(7nv5Q1Qgmj(pJnRE8i z5A`By?Zrh_P0hWPUcXvR<-Nz=TLPrkhSg*ownn2;jo)hD@ZpiiE4abMMWGR=D5kB^ zfW>{nk7}2yWKwrLwvY`K%}wixzzBJY4%FQ(d4!>fpW@m|aYz~Jm3@MPyX2b;QseHF z-pMs}?2$$~=HJOT$t`t=uPZgp@6GACQz`{N%&76oAJEjq<15P#3Q>XAzuAR?_7)b0 zNy3#_Hnz|ao8jS_;R6qJMTO7)KA|DnBCwrVXsTl+I`~~)!_@0aVNpwJ>fT0bFYL_yt5Ero2q zWa^2}4kg>?MEu59H1*@tL&OqOL-rV)u5H3-!S3NuYf6Fma9b@Xl@kB@;W9JWJ)-2o z?a1a-mtamAH^>13g8_ipp)4ra)KkbrjQ&EjFpmrAC9$P{qw?Za3Za zRP&J+f08YX|CwQux3|v;fdfAOUjeRun>$$zv#4~2gViz2t}anv|4QKG#%^fxh}}(6 z`r=*Zy;mdWKCcilV}Xx%YbKX>F=it|RtIYvG@C>WE;N0FG)8F;VDt%@L69fI!_|uPXMr#hcq)n_P@8=gT2o2){*CzKzMo7}5 zvkm*JE&cGA2j=>tA5j8w%K45qClu2fpgjYd3<6PDy?%Y_y)zHqnpLRuN z>|GJ9&LfGn_ErkBsQDC1$p%juA3s_zMz}d|vG>MCtS#+1#b(!AqffO8UZ1wkqEMwl z_aH53lw#j|FyqB)19DQetrG(%YpbSA*TN)NkHc>wGidphl|I%J*ZnG&qV4~B{1@KJ zrsC(yND6II4kX#L0I^WH=IoKF0J5;vd#hYH~a*a3rMy<07#e1#MWrl&gK7+J)Qs-?-jMV^TXX7svHb^Q_icf+TbE|erdCxA zpgt=^VSngyC5=N2)4bxpsXV!Av#9PNtK_WhWp(tZH(pd;RS(CDC#t|8`b3|(FX!yw z35ZFsBLrP$_r}}LRrQH3ZJ`|zdkAV`hR5^e6&;mk?`=@`(eX1&N-<80k%@J2IVaOU z1R1}I?mCgvd}c=2Wa1C!Pw$~%4U7o7K{_?M>q*Yiag#MhleOa})WOS7o4j9r^|-@i zsUnowU~F?dSX>%WBVBjpUD(h4)`)mt<9ExqV#M9;3CEy1$T!c(s4K$R*UrBCRT=KpBwW2cXo}12Lo-}Un2SMS zFw#mS4XVx#l-Mll7jy2+!lyU7%X)ablSk*hW z(s}-`dz-S4ua2*4Y~R0=JTAyxIHptJWgzkuIY@lyS>M6=^;xn-D}!RX)(tcw%$%bj znexN4*^fxhv5zy_bEK&NxBB^}v#+)A`tRrpi;~Uyq=YWrK=1!lxPiX(F7)kpE#v7E zZtBlMc3pFx+aZ_$6@P9Qz%Pl@DuS}rxvEp6-iJPHsUkrgh#hEjdC``8OA?CdlANm# zM|$9e{L~1ijq>f3d-e05yQyFr9~0pITx_Eo-K1FfuB2csOZSyvxR%0&(I)%!%jol} z`x=T5;K#Ml#bdtD9}ZL;DF8HXQ0fj0HT^MFV(jbO8gkH0{af7Zr7rqsgJNr=oQPG% zipkTIV;lHrk1(yQ!Hbkbe;!_sa(HnQ}}eC$ztg@!8<5 zijGbbVSLoi@|-zM{W_z%cd%fS#}^ylX-sP@mn+7}gKC3Kj91}XfR&E_{6&mlOsicA&RhbUvahsVDOY{mrjQlKV%c|QJi zOZ|h`s~c<$l2`No4DUAIifzmuOJ(Q^^si6<4Dbiupmtc<7(zD&k|<=+u&*SLQM+a> zh0{{eelk<1QV{C#oU$a@nG-RK78;D&bxrD_TOZ~0oj&~0Ggi<951rh!W z28QjL?M{MV3ZO;SQc2W*0d7JujoE+r|UBM?W zMP7ksbcFBgh_HX2I6{B>HN!K>eo*W|DIEV8T+aa8l_xJFFY}3HU2HbBse5e#m?hZV zKw~~2|rNU?v$nSXbbJljumd4Y4-a)s#`zuds{aiW%1GXJAN6HA9xu-bwallC`JT|d4S|0O$V2=6s+Z#iiy{Kxi&CTiIR$V|M=p{p~Jx zvMTgI6)A+Y5IDEnvX)j5fyvh)ZopsS_GvcD^h?C zML339n?=-Fs)&3~mmG$8MbbKLab_*UkL95;m{P`~wr zm8D$JxRbVwU}$#<-VBrITr{O#;2gE0V&&&w(Fj6n4a|DcOJ3zXvIJ+IohgnSBo}qx z=cd%ZD(y`xxO3FNplFab>qpL97(wZvO_-306ru5>QDWJ&MV%BS_)ss%TL(uOed#(! z$NN5ZW9{XrGyGfO$76Y4va%##NcTK9C1@Bb}C*!F_mCv^>X8WQ+nRM z5=#IV;-401=-v9oYA87|^pZilcG(N{93}s6dwHVM*mi6NxeN*uq!0PF8R$Cu){UYsmfx00;N#3 z)Stg3Ei+7)6;0*cXf@VVZGvYkgxinU*M|AcRnbby`a#e*9+?ScehB{xED}k0lXQCY zOZJ@_&hXOgx19@fDj&mnxV$PXnjHHV7XxXm;`gih3VDz}0uH{;Z4N1o+6t+~CKO3T ziG7%6S9*Zrqm9d_gk+uSMJSZ>rj#+Ns#eU-J8yrL>n_7POKDJK-7gRb#~=!o&bV(X zlpj^{e>e9`=YrB}nfcjuy#-9DVyIbYsF3tu0-+~~OsaVMOG9J50fMK}6M;Dgo}F^Ug!Vz5khzLIwvrEFYz9Abtpsq&dMmqOuJX&`cIMmIW7don?P0 zX?tm}e}4b2Oze?0iHvZAviA*7zjEeV{P?fLOSa45(Faeoi~9L%^TN9?TUpbF@m1)9 z_4o*1dQ%#J1WTUf~KL-cNZ!q92z>F*L(hBvNfwZ^SH8gha`c?1E43GxoI>COxnkxqC6pui33EfMnwrB_XH|-Z ztO{?N`E~q)p%+4C$%#zRA(@4Fdnq~%2d@l>^|Nj?Jo4I}_p7Rsv!FYceo(#kI$|!V z`;m;UWP+Wa6sy?qUuXI$mjkm^39jQh`|hE0_y1(%99|5n1+*tBhFZ{t_# zv5+`hFc46j6&XaDKQ<`H{XuA!D{!i9kGZ4J1~or&7b`QfP8ecCZ6=?0@amCwocGWp z=>nj*x7SKD)!8jMrqs@Cz2|OIXi(Ks3beqv<%-{(!B@mZvp^k#vujNWwbS`2b&rlJ zJ^8_RD(HtOoDv|e;tQ_ENUestcR!Fnh&XBmGDIuWvc)`i40u!${HMQ=&nz6(WW33c z>pL@~d>Z#tGBOK1>o3X0s@qrwe$F&*kjt5d@)fKV<)P6KEvhPV2H09fV%4`TY5>~u zS2JmRR#n|%0CIhiqp1RW=nT)nqa8TZ6?m_S)H=jv7W z88h_4fO*taN`Bb2xJBqJBt^}o>aSg9r>avE5a=wjGk6-9pD?T0L%<>Yf;1tuK zsIz@s4-trVq&w&Ok}&>bwOyabhB9O8FWTq|Ju3dw{@Wk0rj%Dom5-X=qNR=ycNc}X zr{_b|R5U9&KN_OH@Q(OABpP{8p241SnIVi%_)MGfgz;v} zfh)nf6~N_?XEXt*;H!IqH#x=XIwFVw9t0FRpd755MXhKQOc?PIQQ4i^AnvB4B%bg0 zEDNdTIw!m@IYO7l^*Fva&8inez(w&=@n~f~J{#X7B{NGf_*mK?z3eTt`xz0WdLKr( zst^#v4IM4BjqvNcX;m5Gf+-z(8LnFJ z#pj1UC?nY77Ozda$!sB1jTAdmBQ13_)S&j<{Zmn9n$p)Cxy{xlac8_5-`sUbnv~gh zTP?`TQ?HWvcv`xwppJ;XZB_JjqeZg9+ZfY0>%XGYA}uID9G5>0(}WF&mhR#;GDlQ^ zoxRX-r&iwR0moRB#pW1^a$$={)t6x`YNQ=;mF=k4<1hiC%x9_(UHA}zgTTT;4;|Y+ z@sFS5{BvhHSO=YfUEKbDRHxHgojO?X{bjaSvnMhiCJ1HyWG=C2Z9k`}pU69f5j)?o z_VS4A4K^_uaI#8}}IJhUTr(EzQ!N#Hr=OV6nO zSFqs89*EX5Yr`_E~1it&wON+MXs?&O5tt`C6=^fXA`)k5dj!vxj|DFr72 zQa;O@vst|hP02ffHx?Q`3G3`(hl#VHo+lg0KTFPSpukOZ`qv6nf9?3>2}XJ+3f|GI zy(1qt*kKMd{CJ*a{9_t(D9|p*zFhFu>yVi`53(yYR9O$(f8!~FpKuvfehZdkJxz-a;0yrSRK1{JkiJP%6SnSTbE zO}{(*oj5zkbqo=Xk9M8_dSCeM<>>H!q_aZ{-qH{0cXm+u3!y6p{#-`b6Dx!_uWWo1 z?yx=)JgvSovDA$)%dt$|63|O7IbU{T57DN%dcT)lCE;=0X_eWF-nWil9vqU6KGVhS z+Z$2LfZ)ep>3T2wq{2AVJxONpkNqix69?81{x*ww5^S?BTdS~trXt|;+;^(c^M=!X zoLQ{uSL^mn->|Af;yzkX{$qL$#skxHVPUOE&ssD1D!aF2gS@J`(@``I*^rQlpP~0V zIsdq$YhSU>)k!>pK4M@y?F~Xhm5XX2=(g%eOjoBJ#`hNF%KT%4>#BEG0wHCL1QtVM zDoYh@Lp^M5Hl+H}sOh^fV~9&%{-WFMW2uRsQJQpICr3MR{I$m=hjH1H+!k5ZU+Z0a8*F5Hy|6l?2 zxeF=iKu|&B_j%x!8@9F1C4vxChc5&#Jxc+v$fK)WKb&;;UjzK2Kbk`E>>B$q-{)Z7 z70`hfx<6#FBWVtU1n;y(+xp8po(Y0^1mA0^DmU25CJ`m%DYt1m=&D&}1#p({TEBlc z`=r22T`n}(yx%7eWy{tMov}H7>BZX1>d*wikBcYnE83M0eSA!{VoO8|Rm9DnC?&G1 zw^t_%RcltFNA~U^%q-ELm*>K7uUtCZ{xy7(YA#}X3-mp%ug?ZJolf_Ek|xh%iT#BO zRqc)~wZOlOQ9w%MyC7A4d&Zdp!}(Utuo_-DcU|ZeKS*c7(k=1=R#&Ea%33;p+ze2q zQIbNl8|I4DCQ+)<;f`7BQ4}CYN{)^0o$%eA?dUc7Qt@l9rFr23V{xjLG~p@JnE5Gp zLxTZ>q4Az{#(KT>?b3pFJv?O_)EH7G*3-vP6kC3ZI^~EU>yrly^b~Dq9Y~q7wpOh) z5eHFPx87t{`*>V0s1~4ZsrB9$yq+Qb5r088{s#vX2RNXiP30$mtij{cJ_?;9Z+_>U zCldhf2Hrn1?za4KhORx+vdz*rDWKMP3~Z@5d*d-qfZY++8Nn|e@ucDl6FAlh7Jq-4 z)49Rq2iS>AL--2i8RPYXxDs?xU@G;xnylFe)l`l*MoDzEO%J-ANfLnZ)Ld)tLgeDl z`Q3s}#YN)V8iv?}{Qb8`lbO6-&gO}?jyx1<1Y4L+pw&quWpvMkHgR?tXuINI;M}DrMUD&JV;ag#FUku*%i*U~Fxl-S zr8MR%RMAJ#-?$*)8nA@FkYYcl+D)9XcY1>4+yr^_38^!yYjS0f+9k-#tgK=h%D6sC z%2f*rHi(b!aSLH<#7As*cONB1iL8HGTGL@Y5c7LX)RMbG5a7(dkeUnXKQ}yktF1)y zy$=NI$icf+`OAY-&2R0%J8-6aWLu&nLM*z_KrxkGQF;sJJRh?cb#4Y3*FR8l$z14Q z(3^YSJYvH1uH}PnwwCD@qe%1U!ee6Ak+EP61 z@5c_?7J5bh3FP~#eo#n$LK#ihNz6@gBHGAB(ITht0Oh`9iT3NK(_q3RWvw$3J)MsazmKIhH$_83)l|J{@q_tPb-ik_m`|?0Ufz(pudM& z{^@UkB)I_zfVTcO;Fu@}2Hu_-PL@6XTQ+V`56Bh}4ut>+3dW!U|60_ivb-V?#3F5s zP2CE5p;{QjVu&d0emYiIYIX>9$Y;pemf5xIMlp2_G{#zH(Ne};2#j+ax%SYnccsWH zZ_Lx)2hw5)lH0hh6=a=0)kCpWyY4$QXd|R5OG0LQx}GDaHIPxrH$mQR-Ru8iN)g2f zH%1PI1cjEW(jR4NNX*pxcIfbLpSTjVo*Q6l38E%dT8w&tsu84=|@ ztDEw(SCdo6LgF z`r)HWxq?JqnMlVF>C`59*?4_I(mQhgR99TjPMo=fNuviXtDIHVIjb!A3}7wyIF7qv z0-_2)YypT%pg#@*3zpy4XLgfCx^Dt94P zO{et!VXJx8qW6S>1omqXEUz!?HVmaSpeKze>BW#=( ztnA0fgHiRV`+a}F!W*puUlpa-v<#TK(sTB|tBww^S?<2W)|Co<-Ox%8a@6#g549@D z-~UcY8rjrJ?Y7yj+5V=D_~eQTrqVD4tN#8P zwI1=Ly(1}Hc_ciRkfOjZ3&2baHO zyHaf7w`aBvz+O9s|2{RrCZ!*J&d=Gdr2EuG=DZZaVj+u|?o;%NT`o;)RpXc=L;eMg zBRexlLzI*1;P|-9{;@^pF@K)krs7gQ_~bFlT2DEy1buGj8UII^S(@S(9_U9EPBnw$ zQLD5Gop~vjA?SdK3#lz))Zk=Ls|VPxWOqt8i=FzL09*W-^GzNFXM2LcZUqjF;J^j# zNtLZoZkvy5?Mx(}8}$Jvtzgm@E`SS~J?8ro`@AZ_GK!f85$LyoDIf;SJ-z&okN1cV zh5|=fjx3vmUbv>TtQ|0d>^gxF)Sg0t8|B<=msq%6h_ z-fv%UXP!e!-tc6iYL3<*8R;+;G!A(Ob-cM)#XP|W(xE6Rth z{EL_Y>tszhgP#IrHhl@?!*2HJk;y~=^osIR6!Lh*p?*Ur|sRu#SrfX>#85O)^kSi^b(vs`cHkp|~69+@Q7Qu`8++Y}CR zzp3ON=o8+W@1t&Sv_L-{AkN~{gs{!OYO;q~y|0)aq&9gM173DyPoRZ*n_5p`Z2{t3E(jV?U#NV(n1yLrPS3wkeJa~B+eC%)t-{i}uj=(c%7PLrEe~iAM`DCZ2S=~>MZ72=Y z-t0;iL+z=MU-p!XtM-&z9t`$ow0Pi40;lbkW*SOj(OtLVf~p?!*SjwgCEe7Y1g{@H z4&?uS6pBYYKqNtWf@aWyU7sXA{XYK9Ck8nAE?`9exAS;>0Rv`>z7*9BHv1;dZY>91 zYu{_93K9fwwL$)U^6S8h1n`gg+To8nc<5<8?A2~DFglIeAl(gegJF6^MJU^h#j_ck z9j>}8hMN_7F~64WDSsX^XeBvnuiexzTNGlINe>M0-Xf8fZDwQEw}^Y&u9PQQFGkqc z1!F&~9Y0}6X-T}D9kyA4A1U?q&+1tujWzCXa$oV6Z1PHp-bsjD{FI@AsP+7LRbbtf zwID;|*QaQAxWKyMRewobub~i|=T8jdR(|A;x9U;lsjCon_;omCRYzGV=3sxjWN`ij zVkmaitSNQg$u35|iDo1}e}Ct0cQ3+R*{aWJIXGv-W2K(7Sy$8>E&8i$9-f{KACj{{Aq`kOsk_L`h8y}@cI+l!Wq8pdk6bnc2E}cd*g?9oq1eK|kqhWW7 zwyS*i&c2zin>!^Ti3<=BN)}9&HV>#J%-ihxwOf`tDi3b^_!6G3Z|bQVEFObmyN|-v z4GNL7KECT}Rqo{bv@9>y0^&^1>RM;r;t0s^tMHv0;_drsyZEcvi#X~#XQ{rizz>bC z%Eb()2F(_G0S@=2gNeQh%ou%IN8-=Su!clG{=Hl@9NrgJAcVSi;VIX~b-s&cgOFO&tu`dj9<>=kfH?Kl+p0k)~ zw_ejS`3qpoZV$hE|8OH@K9lp9nMUhkfS=swX7WuR5HaI1-LKAfcB2V_X?go|GcC#E zHC8TJB81o(vtbUca}p6U;0V);Fwi)%-DYo@n`jwmPU@>k=`BtAm^U=u^e$||yMe(h zr@LO-%)wg59pz|^#ijMuJ{>U?wd=f|w7WV|#*@nHRrlbAjatp9c9eNjSBK2j+{x-Y z5t(EkFbe)aQebqd*yEX_*+M^;Vsz#yXto92VTlFs$;?&iV~ahIvz+94GXdBJCDvYI zx;VhfDn;hy)kR^+3>HmY6fi;Es{nw#)YQdMFo}o(%pl;R4b%V@nER3fV~D@u&2nry z9Bh4EM1%i{Ia%LcbR+tckdB{(u$V52f=u6p&26fJj6(v`omW^~r6Y%&RAPnTz-I)w z>%Wzku$_S%>fUd@=&mQIONYMlw?Y@DuWA52kMI0|&%mQ19g*Fa0p zX16M|S)T(Z`Rc~$4sEpK?E*bc|9M*;Td2PRG@F+IBhj%Px3sd_4Bmg48Qj zFm0Qje3C8Pu9p@!{vs_qe@Lpdrcoek{?7L?H6cIGR~1!W8h0!DR2T0yIJ5>5P_cF= zMq6zXk>OePoosE?P&GaG0CUk%@h?`a;3>Gb%_eadzamKuZCL+KuuocTxIh6wfLK7x za&AJ*$V`7k#{ZN`%=Nl!N{2oGHpMiBL3fH!90S@rX=<;i-5-{Hof6uxk2V&e09M{v z6CLC%TJXBbkuWOZet}G=E$N zwXr#;Ykzm<^=7~}u;6lDLvXI@Z$P8Yfc*AWz-$G--&is*#ByG5lu!OM zYQKfS&;wy$j*z9wplq4q_R*?sQdK_a8h>{i^P;K?4_`sUB5yD!aJ9=^@6{(pd1$@= zmSXkuS3m#iUpjYt%i4r?XAtiv9?zdN{CvUB%ZH_$XL?0mGVIAlxrPAmz!8|vqd9k7 z>&NL9lmw*26W7|^Q;5gs}ycHZ<~+1IW4$@Zt=yU^zKo0NoIJeh?df~tVJ z3A`ohZ-68SDg&A1H2~z90a<`fOM_YgfPM`~`vnW0KF131b44IVwm$z|3;6Q_PB14$ z01H?M$ShzG$(8&al&3?kV*x{E_$Mfju4xm!3YtFt3qvO0RLTc%fm10pz$H~WNG9N9 zikx}4KGOZsn5^C39lrj10RF2-738rXcbeQDSdz#J0rL{b%^rpblC}Ax%HJ`KZ)&$R zP~_nNJ_@-rP`1O)%)SG8DDdKfJa7aR59<9t-+|x5F+z+Z_vdgZp}>$OH~3o!yaFQU zsxeYemUqoiUffYX97Cy4SXSe3`}lLIXU4LqdZe*k`)iH4yA|PAQOaID{Utnmea-RJ z62KVRpSc%wHT<>U4sA4-i2D7slj8%Tn1z5{TDChs9rR!mR8Z|76{Y2`*x;Pni@nPa zUwXYep`BD-=OWR8KM0LH<&s-RP+|lg)PXEy4tH$$c2dTePgG+m`pp_Y;A33vEiFuoo5$pu0x(g*;ld9S9X06{k@rEz&<165XK| zWmz1rCBTs|!nnw3CRr%(&#~GB4Rh_xd!@nur;z@DL#`*?n_oYGLVK$({F_ zq+hWPFKlG68_}53724Duzh{#Jaxc3-T2*wH^5MT=E(naN_%!4}3-OI|)7>q|Ie(a= z`@;0e&A4hAgB8%82?&9Y>cr}Nn}OHFGg{svST?kJ&G2g? z9X^G42HLU;CgYBj56K^&${OK!Pe2ezR+0)lpyYFGvHG%SeL^d z2nyiB*1t=D(<(C3qWudahQ;oo1#x$x9WCKNEX#-F3zg{A`k(5gSN4z=(T=Hha-?n2 zSjVc2i&gb7tex2mqdBw@{-LSGJ|7%)2+6L0>Gi!ct0P>M*1Mx)Wnti$&+ySptj-wR zWR<4DXYKRF#d1pv_7P4N9+8ZgyE!7G*|XsN{hAHLAxnpde;$s>oz_)n^jrss05M z2nY&XibMpxSN@Mj;lKyI4x@v+!$RRAC@S*0(=rc%d0k@rykXRmd$Z;xlwmaP$$Qy_ z-Y4)C5cy}V7LK8Wy}XgTFQaq$L7NqPm*pSi(D?gkhLoG?q&R~I~o%r~E+qhKG z4GlNQoD%wm2Ic65?dJKXZ4;*`!CWH~Q#|3q_H!f<)A&OBy#_E}{A z9X>b;r0J2M1QOSBm0B_;8UzB8nIX}2ox!^V=}2A9{X+4SvI z*ZOYwsH!%}ZqzEfD9)Agc%OT&J-WqknWpc!LW~!w8S~}1SfjM&!11!Wd5HB|dZ8utht0xw)Qp>f z77WK0+}p%dz;^zV4(%2OU`9is(N-}P5GT$TZ{z_n3)_L1>HnaBiv6O3Dr*B|@)O&? zk(sku(_m8tGRGHO$VK39Nah542M{E01KR$F8zUfpj2}?9pFQ=&Yl*CB2pOCKm6Oe% zl=mfADZrH+zC%w2i$L3CbBs*DzDnjL<3xb>??C%Q!L(ghvQodd>TB!gG_~!bRb_wz zTKnEsphqBVolK&B6R<^A0v%Ps_W53eyitRw_0x&W=+`%Bp*o^e1*c;u%wD%3C0Zu@ zVLGA!pt!&b7x_~THmAd)`?az6FOUrsase=u$Z}?V9TIb*Ex(Isg9QPY_uF!K-Li`( zR}L&gP&e6d0J6Yv0C{A?0py_w0ZuY3%Xi(th8-UzYwiZ@2C!cOR03E_U|3GaY?g~8 zR$`?87`x#nAH4aDgU>@b#YSl(?Iabg z!qAuE6{0FU7|So2Bmi|9@o&NBE;q^FRvv!CIIxD#H0q1YIeFHYLq6v@5L^O+e6Y%6 zK0(sXEM7Cme1md|$b!Rf#q$U`*Xk4>sSS!p;KZN<2q3x@ne)HDWE^a^R0$q^D-I=x zoWXB$WOqvPqHBe(QH5xuf!gF2d&qpeP?}$W;!>gYkDN&*fF?;9^DQLH(`|V>$ zVJ*)<6GbTh!~4X0)~@RfQ&GUuD)iB!E>FO6p#G+Omh4!yf->M{kO|qu1ep>Yk7XCG z^k=s}qI;0_;L2`*a&G&hGtd_?5Lns|eRLRC{)MCT@CTyok1Sp#UVQ7U{q!_4+3w5H zf^XLxRLz`;IrGrcRL8pfdFVknqToEMd!p*1qoOL*o|xo{9oNUDOYW4Vb=7f^zMg^Lb)2r z?Vcj*JAS^F>C%*b*7ViX8yg|-I;s4C_s~ZLWtgKVpx%I(QThSzLLInMg207fgImB* z|0?}`?)?&!ZIB%!uzA$Oj^L=EFJ|Z6b)hcl7URB130L*Q#jOA=*n|1s)(@9_kVjtJ zpkTfJgHkBIn5BSW_tAiX96iM8``nmq6)mWQ|L_ixi~&+$49Nt9HxYc1AiQacTnG5( z2jEE{!-8%9_P6z4?=;uHr;m(&Pp?|cPOfMO@5tbaI#}W8k=FQl??UIXXF^;^%{6at z*VPr$vP<%r%cPHivmG6|4Q(Cip5OXPH96g0t$)8r44~Cpq>pkrrXu#soWVU-bM`p4+OsAAvWpz5_e2UFi_3syHbV zdhoc?zuZ6S(+jh*+X-$P<(g90;^hT54SPv}8U3N(BlDaUhn5L3Z99{2l$Z=~b5^b5 zl*(5ULI4i>{n}vaUMe>2aU2t8g;=O!f%)CNcxYvhflqn=KqK2V$Bezc+c9;Csw|F^ zn1BFppWOr2gQ|HHCix*YC7bzuI+xRqa}w%QOW(s~Dy|mWQzyT!QHd^C9EZCkyFe0e??g$G}Ig#|Vgp!mvJT`Qn7 ztmy29kfG4x@e!qO0;*04cl$KFG$62MOJk&}>7L?^n)6=ADHhC^N8av^CgJVBU_DuI zL9*q!0Aj-hmEd8W;8QTF3=l!OfNk_qvcUfsktB!)+Tv8z_*aIVqa_5Kk+WB&D{5Ls zzPq3Cyj?#V+kXd~f|4URBS>*ywGriR18W+Jp11Y2@2TR+pM+V)&6N+gLZxc`=~z?5 z&b(b*ly7C2MoOG{OI479WJSACs*Hw-Qkdyqq=WvL&_H=;Ex79{o*umu5J)D~nN-iO z14>46968`s3_V8(b zP8UDWACE3AS)AqP&q?(!Eh$87NP%Y;LkKl`{cV{x1^Z}k&;S?BMev$BSR8{;z|=oE z|Gx{J=MH(C=XO6RY;>SYix*=C`V*k?yeJpU8&K~mL=<}>eZJ{=o|q+}CZd$LwDp>}a1slJ#7&&n9%-ll z{*)z5dVCjZQk?1Z=*E1iP{P?vPiGE!|32nIz)__ijbPG3A zq=d3WZEOnX==DxUIEII+qDI7y2CZL5&MIRhV-bMo4;BG9$c5Rkh@sH8=o)*rra6V3 zWP1k159&NCs5d1SrhT|R=pTh&4U}z$)y3(oRzTZERUa7vOEc}Z*SNW|}!2}ZGB}Mn8F_xcwv|tih2CUQu z2i8a763W6r1qx?ZavhF<6E+%9nFN}+5-iy3c99SNnreVpFa-occ9+Qlj^%=;?iVe9 zF<(Sx0~3H;KR9UgmIu`X^Er=PI~cda%5L^KlUoHRX=d*KQQ52wnH_*#huRT-w+Rer z@Mr>Sp%_xD{2J)LyE3_ND)_19^TNclPB}+wZ&>2w_pE?zRN6IvYoc)xPwckq54w&vjd+Qao$Xz#l0=q@S@B%+CZ zJ>+poekU$jMaGM_ANvTrRe#|G^ ziGm!9$N6#)pV@cuTVIo^6B9~jhYVH!E8+ga%8&ib<8I$5^PZ|>PFHOD_cQ0=w`Ihq zD^U7^<~s`{V&dL%D)0$BbvNk|mBt=UazuCw6%cVXlp*hKPLf6=@Ch1`>5KgV(Z_$J zA0UvF%B?>fmgS8_Du5g_>?lc&DMf|IF`*1$(*(^uiJuOZa=0$VILa5KHJj#h_A)Z5 zxN#KEjkmaMaBW>IsfdQH6D6|!tC!*M6Py2rTFQIOC!SA|b>44sm~iw4>jTg}*x~s- z!-W|9tR+WoaK_oMcj^u~-W{K0YvIP%74{h$28FC>7tS2oq`o1MT153$JU2VJo$QK@5?j z5deyDFA0J(Y-LqBkaqwAT-NhV5c1o$2J^7Z16u*IeG_h4)7vI8X7*JetX+-H5{cU|AS^rAPS9$^<_j zaus=B`^1xqd9onG83Q^#>#zN^OU8%Yyt-*0+$sD}@#CLgHgQJ%7BVJ_9p8Qw=ew`W ztyJdO`Q$T6D485T%)A;`W?^UT(XrObk12b^@6|eEyFlHqy2W_NX4xeAdQsWyz{A){ zW5Wj`ccyhGjo%k(=D6Pe`msne=;!IbvWc#vYS>L5JZqFyddLDszrsY&V{3bMzNXH=wGR^~aSIPdX+u*}L#6p9#(La*cc@%LjHK~0 z_eo!C0+u*yt2d8C?)>A+EY9c@i_Edvjt3&eMMX-5itD)9sv{l03Ew!Eis&yiB~~Rf z&Uvu5d2+vduO8+-bN9XC;Gd=4KbzXaxL&2AU;gLI8O!jq2~|7I_iCkM<3|Ubg^;c1 zU@8A0Md|0mLP5J3ZGr{wT}o7y8PiKtoi=Tx0O}GV4#{8*{5As{`S; zXPX}Lx_tGHRZXs$5L_K>Pw8*}IiTfUh-21Kd(o^NGnZK}$ZTuW!VTA=~H}hVhp}!I>YE?CQSOp(SS^MgTk}S%V${ARU@u z-SIVgR`Pn-ZX%z*@^9neR6d)=V@=q8L#w=gLl9SC=r)$|&AKX2tY7m%6tmxDc=oYg zd~T8pH^{-9n?O4LGi3OL3Q50okr5~SjvBwG37D`kV8Rwq`u9A5DQoH&j(P=L*bW}i zO_5N3V$cxbrT_shP)NIN<=#DDz5w;l1(0H4F&`lgx;=z8XfvS#tba%us0*PCF*O3Z z|I4Dee|rdBpc#S+AjX5yfVvmyaJvy=V|AiP1xquwG2A=YKgn%z+3uYU&5w6o?r-f2 zvcX{eO}2&F592ovjjxT@;eS}&$fJ{BCT#q14@6Cw;sQ}*>8DX>eL+7zG3Mih$X)w- zG$@#G!eqPfd(ae^9rO;*2}p$J1U$lXlF+cTr@$o`?KB4g1=13x31}h$H6V%1614aa z&xs;KcuuIW!*hyx7#zM7qmKG|j5iRqsMMkqg1VP|5Pm>D=s|PgNC*rO*mrdlIxopb z8FE;4aC2Pvon36$ocH~sg?G+}jGe4&n9+~buJP<*UzI{do-M}${+VUVV9_myF=`&w z_V7fo(ljz!D{su=kX-m0_fe(fAj_J|Kz3JTl<)dNCys&Ln_?;MO-sdmkI^(+O64Er z<>saJ#3FvRtG%hm?)rY#3>5A?d*)&Wm3g<>kz8d8zO7X}cw%~5)JA4mhM-nl;@ID6 zN^QQ6%VG3YRwa9+a_uFR>fz_6#UF}%WIynBF}oOwMf^BvJI3m=}hY{Xi*C1w85$MOX5eQuWwtHht)RT;Bfq3}0@x zbb2Q~;D)`&Y`gJHDE(*64%@q@Jgz(M;`#I%EuTz%)ssxMz_we&p_mgfg{D) zvI29Y0xlj}&Wm;JAO0?Vx-Q8wAlAB`sV(E6Rd{S#J(EIof`CK1+NlAI-=nI0GKMfm z8ZH4%1}=dg$t+=xY+Qoe4`tu(W(fOOdQUeHYOpedLCA}@dl|x%0Prw`6;<3bG5?AQ zdsJ0aT972d5OyB|l_UlS^M+Q+sM>*eL6leSpW$H!j>YCUDp0QGDW~4=&-!l z#Zv>jJ(oV51}bN{O%j7KNzlUu7(*PF;P6SA({+(|0%8-(ABgANc_3a6*J;0Dz-a>6 zR}3!FHZv*ce-LnxxOQsb>T3p3!&3v=0E|xEBn3}7qMr^p<5L5#ex3bkC3NRAGh2J; zs?5nKGTGCzw9`?0WKZYP+MZ+P7DVpj336AINukJHxoV1X3wj327M|sXQNibg`PWxj z*Dt%}MSNz?Zi2*`BanT`>eTmkrnW=k2Oru7Ot5wxPO=Rk9{Ma$Zo78#{9!M9$EBfJ z{{-Ka6t!-(uHwzL$sf^j93tHXX+s}s22aI%sTDGPu_#-kay8(No>bumwcGoT-cxJx zmwZ2+c3bIKzbKSt^|7t*kjPle`MK%p{VT$Gda>d&*jWC6giGJ&$!DcC+tlpkZ?ncq;~#roBi+iV8odfcKgNQWd}6iWrvV}mlL!`UUpCh zFFPp1Rwj%iIg)kPedq((>jNb)ybp(7&H_htBdh-KPN&GG8HNL!W~hQ}nxP7^X$Asu zf0^wdG=_aJBpM_K$oKw=mPI1scS_A7jab-aZd}^=0%w!$>)EgS#iypW)>cZq++VNN znC7>YV8U5T)SsPfbe8#09(U(1HJyLX=Z<&5$_DZu$~(_8F!HrbeOk(0qojRAuJ()F0&<|}9J=q5|Nl#`Cf^;7Y(B0M{{@Zxh zetQVOK|uvDz}JA$Aio`SxZMabc)MB4m$%=VZ?~k~lnHTjVR-V?QDboA2=c0RYM#Uy zgZpPgdt-_7#^7H5vAO;E;1W@QPaj`#-hcoiX=NE4>D49*B{c$(pFC0!TU#w^=eqi; zh#ah;*wR9ENpQ^cel8`xy|UzzK7?@Jm@U5!{phD$yRCEZd6F@_f=U-wQr?b z>Q5>AeBC){>vu~3Z+}i#_qD+kpGdQp5(CrGix@kxo(NZgo>}xw6|%}$H*}BFOn;^u zKTl!b)wenpE@F@BO?OWzET3le?3tUTA$+7F>f-GE)>`T_rhN+C-RC`iFs`Q6nK<7V zrG7@6tF>a@I}s9>eDCXBC1JKg-_Ve^_h|I(kF*uwMhv;<)`=V4vTv`3Yb@qJGo&OU zDb`RJQ#O77?Nu6m-88=#y|f2nsqjKdy;2(4bf{;j=}_pDBuk`8wwal$#Y|J2!> zyA#P1--;_Z4=Au0JpXY|dhP2=r02tg2 z2THH7VEpx)g^Ryfuqv1T9CO}K)}*u0{GXd1)MsQM|voY!2$vvN@s?hhccFl z7Lh_Zs2)UQvI9;R35XA2+bj4_eW4=8eh~o^zl(L0l*oTm8vyJ?V`*p+a{~ot*1un; zataKrh{e^Q_(fztObQ23w$AetjN{0r48x$DPax_L^0Zi>!Efd6&8ben_2v7^I$3=yps%$RKZaK!JQhLv%Ottmr-lAwixIbcqj}x0*zsVjx^qGh1i%x^i9}X(#(6{hB@>2h}RgWlzW?-N6+~1 z2k*Rl@wRF-Zk%W0j4B5L8oeZXn-yAvyrxw1>b|D`cb)Efg;w9< zt&AA|VN(@i*G6V1*@myQaqnoae@sWM`RU2X9Q{tITAtuzPjtYnsz1tixcbu#+n4D_ zBF@#VmQT(#t3tG_5QUf$JDY2Tl({T;d&I;;MKPJTg$y_5B)fTY_P=ea6c3Oy)<%me z>?Ran@l)r(O+5CF*4)RmV^cMK>TjE>o0ceofNi-F#iD}KDZ<9`bsNN@s>}fYOK4`V zjUj$Z#4YyK5wA9KT+ON5D7RhH?e-m6jM_I&(k{~CzSZ}$?)zlUbel1j{3e8gy-TfW zM4^4(*N{qk`UbB2lk0eAZ)GLjC*SrPX7$;RtW}3BFf+y`N(n4~js;6_-Lp2|bTmBj zp_5B&!eN88YAx9P_lf3Dfk%vppNEY@q$L~+>C4XA55{T|+?r%j!Go%J8*wy}3}mAy#JM#Q^O>C-MD{PD;*tM96%fbk zHiN1AdW-I@Skz3YkLpzNOYfP9*>&7n|3(a5y=BRw7hk_(_}%rP`ISE^Gc!YrQ;TZ+ za@K7jTRxr^F_YduL3@{zv$bA7TKZOg-D!5^;b324#Wc~d&ETzBPmt^4AL=^r+?vkzbYx}jx#t#iFl0tEp9%MbuuI|9IJ zUUAHB{tF6W)(?hYuB+?3{erq0k}yV=*@^4)dQW%VCw7eNIe&`~$5oGIC^=UH@LdhcZRy`U%IzKXYf!e1ABaek%aLHR2`J}~O%6VE)CRy=a zHaPc7`C#Y4GxK}lxQeT;^EQTXTm>yI1^wwu4B~D5{CB5vO!Fbahbi!s-tn+*91W&d z{xEs8^~ur9B8}HjZOVO;sUuk*NIWDOrq)vQIE}E8r|2qzhjql%zdWpC>#E*dU-^tC zamh;(z$NFn1jRxyrWg*Cw#DXno>`V`@J6=MVRYje`k;c&-4WKe3tH_e@+E9Ju!Ux* zv$h;9Nt30)p3c(W0BxVi4XP`YuMghwSVss|wW#lWZPtnhT3a1K8OE zcxP${_9lPCEZV@BJHU3B@c~owz#ZF61heKN?H57#FaBSWtkWJ*iDWBvN*61OLx9 zseBr8tK} z2Pp`=!qQ!+ysrENWw3R1UA@tm)Ae_J+68xJLJp31uBs$ri2i|eubu#J# zr{M5qNEl8*5QgkGdQ=6Xhw5kn2q^mMW(|`<3Z&s0rtR>iBQovq*~LXi6-=2}S|IFt zw(6O((9P<2k`Q6eGQft7J%XMKQSl(AEK6Id5*fq}kP<$}O$|0?yVzkkT@*k19h}1+pq4Ah-!`@Vo*(B)il$8KLmT z4L5`Ex5f_dL;SU_fd|>)9HZgnF0xYRHh)lUdW^sV4^QiVT-v}ixMkkel>@x(6}bt) zpa_VoRc(C|AYY~Z1W&ims-^3y6xKzyk+rVo%Tgw$DZO4z)HL>jz_y)VgDs9PgMWXD!0 zOwCs_WJooyW)S>d__SaUBqWR+X#iTE8l zZ9?RXlpjQ@j^6VE+|EM5G8+;wxZll5D&xNA{bZlYBHQ=sH)HLSj#1%~q#zxEBmqer z(jiC(A&EfR4@r;;2TuQCU?RQyQ)Qff8JPM&YAPieBkBVHZAQ!2ZDYiH+s24gR6E9q zqJC|j+I8cmi}B&}a~y=oF-U!o+M~U(qTZlL{tlT^NMATe#tmbXxTFzCLzKw7Q+JjO z5e=of0ad6}Y2-CQL2)wXLDUsKBsvSu-bU6=1 zbQ}1lTo5n)4|9d2WD8)I4Hxs1-cW*t*{M`Zl8Ea4HIj{CjyMtzJwhW2nEcSe+S;R+Dgq}$=G=_bDVr~`I5&Nx$$R?J!0QkxbDCG?lDd{S-nr?)e@e1?05_Lv zpsp3`b7*s8vAlL;@CM6dpV858Sv)F9o+J-#@0Z157Omf^4P8Bqw>G2gC*ABGbt@e< z*f_SiRN|%TBdn#97-1ut)>7TydEOeGuNSJs*5;TUen474sk{@X`{-_!`M&z2*{o*! z=JtM%Y0&Y!Ni!%gx3?x{&oj@P?k9!j_SVJd!eyX0RQMV5?3w4lyI*HJaCEuB7566h zHpT1-_q-{6O#32T?w$~`f!XCs0SbAc1ZV$^HPbz8iLd6$3yL>&WlJk>I$JuY6 z1q#_g+gwII>GL&ise67>P`UKas@~v_HLJ3>i6c^`5HdUBSdZOpJnNkDTKT^BRZ3J) z^q$Pi%;=fr%x>tW^Xig^w-&QlOX zd>xoG2P-sZZ&(%TYElqJh3qYRu2AKHP54RrE0^8}E)otTbTG>KM|W5z$83I&i@Pt^ zG&scd$o{MHu6@>xPwq;|U1z7TidO4wgy5i!iS|)5;IzGt{uPzC$gb}Z)owh+%9AHfC)G z4K|k(9*yc}?<0b+1k(tJOk&H~vzYI{7pE6;{WLL@rQ0vY<26}dg)-gsgz>i=cM`^5 z5>p-_Xj1MG_BD;*-0wHO?3hxs51wx| z*YEUu2$S1cSR{-<6^kHV{k+e59gV#VOJgP&+E7))qPmYHKSltE(r$%<^w$IF5HWi} z0LX%o!hbIkdS3O>&>ym#a_(OvB13>h;>8IvL@A7rLS%(%Nc_-KFKkJR6#_`6RivTF zB18E*`q{lc&*BHo%Uv&(=c!qx5l;9i>`NJoC8JR=0CY~!|H;V>`oAvqv-R1Mpw z+cpdhwTswdk%|zkrv+vRV)a-N{w_Cd(96m8W-u*pEfcz;OnkoLNW09f{3!96Unq;=9}5fLtZBc@ziVFd zNN+wTm#^qmkj6d>j0~^ozT}N^XAdsz=PTJa6SWYS@Xb8mVCYiNZ|WXf$A^_FSNX5! zUH%B@G)98a1n<(j!@sFRD-T3j-sEdeT1BOmzM8>Tj*(xqqzzfSL(j|n&-34pksm0x^(h;+w_Jw9J>U7E@b~-TAOaBvjmD{`FJLbd-CC|3 zCm5<7+9yslJxfW!W2}4iIN{RQM6%LnADu2A4Zwx8y^$k_+tJoe9&$zW9u2 z;gQbV^{;2>Ub};hS55uzlLrs%{i8J{DZt!=m++B)$*4ZRdkJ@p|LIWKFE3KI*GiSA z)<1D&r?9Xd&hh+D7V2zO^VBk`6%&`FK({I9jnBF@Y4P-S=PfsEO>H$1KfA6UwZ(bW zymIt2b8>P|c#8{H=940?H}xf7W~gE&dSy};BsU7j7`iw;M;TPN_Hi1yKYHHfV}fq* z>&)W!b`CT2S#VeLa6llZpuX-8G$b0iq$n1w#^D3R2t#eWXih9n?~X!ma+5=;R_fq` z80F0eF;EHgklS$>HTir?wIFTlHNlwoY&!MqGI_e&I!()ryEtHA)6_S602ZQsd|UTC zxmt)BEKBQGUKTRB>(#?o|;P3l&AbR%hpXd73qR0KJL{CCG4e2bTbC5J3 zU4Wzw=^`ZE<5hd$oRUDceGatj`w(4sDJ6+b^+OA$1fT_7L33V%3iAY3^^V{6*&Eks zdG^h{dfvH5@i?g5E8hL82*|ngfU$i*(8sTes(woFo?jKabz*?PJ}>|{_-0oC@dh2c zJ;mv%*$D|jnt%zJ_8BhQx7W!8Q>-B2Ah|*EgA@Sgk(|35Dx3@hdk5*g9~??@B2Wy* zCce+%F{G5AkG`=pR#bXc63izWpbVh^#O>X!(|i2ymqr3|cf+my>#RtwwKLc@a$&9Fp!@2W9{<2?>U z{ggv9($2g>Q}5pWi~4)KHx1WAxJPf={Zi@^blYQBgwcBH# zEu-9A7&sTdg?l#FaZ=gh{wTb*kY0_Qh;42oI}qI%G4+-3qn^BHg-(j|rQh(yT(l0x zhrGLJb*Orhk#QQk)t?wWZQ5P@-kWhlOO6=($Qc6)Ajv-QveghD*^WbSU9q~5u`*FD z5g!8SbtM~xB9YaSYkG1Jdqh%xKPN{ca@w5&>+ZZA0;T}+M<^`^$t8VxkK`lV%_ zk??LA8iGr)q-m7CMmN~5x%~L+GGeDPydxx_4X6vZ?W2k3C@}e9ySBBMW$%8LRV{?t z?a$3$IV;%1r5Z9Hd>Uankep(=zn2im`mlKj@GMRr<_`QzatO6}fzN~j#4G@S(wuwj zUu3=mR%V+9Xxfm*ya|;EMVIYDuug_(^S$+Z^kV*%CW6vvu0Y0khpMy3K z^8o>%fJA^x6Lt`&PmU@}*zG6Vu}7BMgVx7F?yp-z$PS)0i;3ADkXh?fwyFLf19u&4 zN`_R6Yj_XZ$u!}&D+%@>gN=k65c|JW{{N@zucn}qoC7M(+jr+e#3J_!N}2!67d@>C ze71vc2_bXw_uydCx2G8dw8e1OPwV?hla3T-m3J~eQ1)@(ni`A|yBoS$ff=>%q&WHX zcop+51u_BkeK({3l^ytA@tOX?XW2rFeQ$Gm50eXkml_ix^7yVEjeQh2VJ0&Co?U1R z%>z_A#Yu2t+eY)UdF)N)`+oe~+V#kPw18=sf(B2=UeiB7Vbv$EQk_KQrOe|Yw>|4e zaFv?70oAkn8P6^>F-)n(VIPIOmkx3E8Ibw+xD=OmJ>a<;D#Ub;Odz3TeO%78v)E^) z|F=N^cZfmNBhPOqpBhv#(bvHhbMkG;sDB)7SmT?V7YE_(c6@>eCtXp(6OoA#iX&mv7YudRE@ZN%2=Zb^mHfPuZPd&&x+b%MQ7i(9;f| zA?bHy8{Byq(`@**$Pev>e~lFnN|F+@V$K9u%WtCi0X*(z?Ba^K95MES0DbSK}>I?w3x zUGkMti1+93Rbsm{u^VRmzoqAL&Gk9mz2`Z-5~Q@gC^uvAI`QK7qZ?1QPz*=Jq^V&e z9U6UlVjaL%=KmpWGYM~rs43ug03iMax>%IHF1DQ*>(Dqf6anr7kYIID7$h0JXy*gJ zF>DV2*}py@^@;F%Z9C4@AfTk`=E@}4vYzq&;1?cqrf2G@w zpEy3%)|y-({M98q(~E!i22lZ2ZUVtY3}YJ%WqWzq9>|Wp1F`@j$hM(dP!AU4PcUp? z#1I<&9#uei65p8(WuDt8WKDnV4|+pHb%?|nv>lk2_dMD`oG7<}v9KVV9nu!w3eeWs zi_a3dA5sr}?0jW%d0>KM9IhmO+z@nF?9XiP*Tsos9a+;MTjPHDO$9!o* z>0|ELPW8TAQ81R~;9s!g+Z>O{*!1#rHQh?qAz(j=#cLhgcw%vU#fpPDB1mm%rZ#c9 z3)7}1|H;lwN#kDDKT~!&$VMeeiG}BFx{sb$$94&iqs!X{SS7tl{TCKGn#% z>+VY0jLGb`zEy#q6KK9;J%q0(Vy~lk-n8UrF&GmzHJUug`I5W*0<@oanE&L z1_y6aJUuF)HvAqFY~&lIc0GAkAOWAow#q1JTJm1;{1@&${gzVEoM||1b1F5cGdqd-P(GSiM!r@Hbpb;7qu7$K$GR1$P3Ww9*-LnY9-ksN7 z-5mTJrCP8y^nrOiP@ zUuhO>&1whpS^Jlg_^XHO@B>jH!`NjZt4>!xQbWl7ov-K3p_?A zhk3sYoVO|Q$EY#m)&|Z)_^*UrcwNXO`3UxCY`_L#6*dS9ENK0)17ztpf=}JUr|AHx8 z3-8nyswG^@hV_^6J2aJl6_pvg;>UNpcK)lL_mpIn@zPvD!Pfh()$H;2nd4%Vvic7@ zBaSXxNw|k*u(G;m#t5eJtHdy>tZ3Y=y>ERzU$+O}PZ$6R?6}4T!^t|LTQZ$%&ig2Gy*@|%YK7y^&r$rg00|AUE zs^D4Y1Hs&02AySzeBaxgo& zq#C2&uw>QP)HycgZq$*Uz#yHTCD)}EE}w^SIz6|GnVIa)){rNc=!rcLk`vm@qI60A zsBhYl{1GoSDUr!@}`H(Y#9wFFMU(hu8#8NDtxogD>_hk;wpnI6dn9*I5CeQKy+VRG* zJwvD3QfH%|ioX(~8>u2|2f@T~b@rcOlukF%yw{E+f{CAMB6RPP{YiMmY`^WQic3{w ze`kCT(v3{@#)NbcyG+vpT$_B0cdL%6@h>E}64W<_6E_`?E>3^kTA%2hoQx^3&PmwN z%DYW2^Vs?Z=Zu-%M8CUeUP?rq{ZW^Vi}kv)H19IjE;O7!&d@Jt$W^zpgT zlMZ$Dk5BKFo&Pc_ekOtBu~Ghqefdz~fOpPUdrh*0z0FF#xlaZ&O2v|$=xz02G4{+r zGgb%E6Yf{I3Ak^e>&qYTmu! znA8gv`6)Ion#z!|{Fb%$CjyH4++OIXuUVA*Jzna>njL67k+bmasEdOSTd*e=jq#2WE?oQF;Q>MXEnRh;a)};S$6Rc_YsC4)oT<;`*i2u~#THX$ zeP8{E6E^x8`;r)YSUxvj)F>3POgO#VeZ3mF`+AaXPLxL4oFFi08nX00icq1&i_(SR zDkD_dhcws)dsbQUV*VUQ5sBnz9Q9^lJ~dfSGT*KTVk%51*MZeq6{dE~`4kFbtTqiu zEyYvxU^C-UH5x%$WEF)W<|0-hZV&LLQv*&KJMoQl6@`0u)2h66(f|QbK@tGo73C;E z*Fw9P22mOiF`t7vhFH1tDf?mbnDtg~54`jDjYc4WUbjyOCN*0|njumqWMg)j@rh3<1dQ5ODv!V;@z1IvQca$AJt2D#|74?MZ*D zM~2maF(9`Xp?x0z3~p02?io%P?nw`ZsPUW@S40X|`WKdDB(}}9!+1%QK;#t*1R+=q zG6%qfA~OPSA7su{5-O40|J*31=;h`k9U>KAqo@s|28l32X_iC~wq_t*a5 zw`OK=?Jt!zN;#K|p}OEZI?~id#vj*C>E(2%z9&&{P0c!GQR>B^}k8GWnDA;Gs}q+G&tSC$*yKj^p{a*Tq}vO;!lAGWKel-G5x z7SRD znJIM7qgSpea8=qf!!-Uawau0uPVk@BA!-L;WR3Xq%J>fc_+v| zcbaAYRAlO*d!=p=+bK+EG z&zWnIoh~T)>3K}x51BQiFPFDEUU@R|{sful!`Z?LH}dX+@^9qwNtLfIo;mj-h(bIv z7UlNs{WpIb`uwinmAeuv`)6KVEPr+B%qu;^bm8Ou!A|fmruh7`Qk+6I$()_+>cc?FR&uhK zQDwVcmJVT^2){(~dqw8`QKv7F#n-zxW(f6Qt67D6R;UPpA1aSpyz+nlyn^bzx%8S? ztKp3y!#tdG4Do>qMl3n&u6Ag3N^4n;85j2mMWFuowv%eX3{K9U?Csp7*!HkHA0!Gjg!mPZUnYzy_jU6mV0PIJ0KPkV*_ue0HW5*l1CUl?uW zdXQQg$ND~?=meYyb?Kei?cMiCM*MsjF!4b z1E5Of@iBRq4p2<7zJK0FgYW=kSQA1M`NW? z=|&dQa5SDtdWc4zZ%NLuSo^X`7+uVE364$UtXCIyS6XuIo_9k9@ z_`)*&49hoz^~k43$?hok&*&>w>>7!XjXTLEQl}iWGq#MQU4)d+oPea_A30g_N9ob~ zy==%Q^FTVSr|#Z*F08UOt6saIYSPCm?@AQ`=)Eg-!La2v?#Lvx7OAD`Hsaq65X8XvLZI|1B*UAL*now+de@cmwh(GIYJ`>>n|Ks^s9FOA9plXs7^`rijs7hPmC&p^V$ z>AZi8o_Y1WA^*c(6m{^Sx9NLPAzW9^-N<5>7hV$Vk9>UvCF`aUom7r$HM=RW_H6 z)dOCOH#rO5z3ogYKX+m`A=2x{&y6#=4z}r$aXdZWwRhvR-kUWHxjZ}X6lpX)lFb{V z_(eSa#iI1G!Ai-2lEW_i=F>Hm-?w=CzHidthSQcWD4FEy_;ELs%Mz|wskrc&x6jgk zWXx)ObbuJk#fWHmEi1?o;ZNYK-*|(TIw7*qjS%eKH?aXSpi>w4aRGmCcNl;Vt&{zi z7^7EqPA@m$haLK2iuGMPYlSu3jvE>#`STwJAU!!;%s*TcPrqWD}bDOF=lfL z52EhB$Y=o;*?3uUBazt~+Td(a1o;TO^QlLn>RW~}=B3*Mq9@%ji0U!ZDaQ|};=9+ukF$pGe2qqs4 z_K_Ke*+HgOQ8fgaeF)d@U>ULr%0^63ReZcrc;(fX?i$YrJXjJ+Qf5`KH4<2_hENP~*)|*Hq}h!Z;3h*ahro6h-j#f4-N0&4@*i^5jaq(Ca9_7c~U#w_jFYH;)B@O ztpIWFNg9RxEgA*aT7P`$kNlC;OS zJ(e%75?K%pYJQ`N0H`g`!skP9c87O3hJuo*t*6cS0RS^w*1PD_VDx&%3W(Tz6_od@ zQi<<8jCc+P@(6lAWFc zEhy-Amq4#u1(ZlG-K;XuQWnwXf&;aAla={pP?%Cb5dTVkTJ~|<;a+l*12qctpKuc= zj}K_yI6))0&mjXerDx%mem!cjGKYrXd~GGZ_ZT}5+b5$^ng`;u6epuVt;-GC(zhf{ zF3q8R*?Kit8c^thBA0@_eSqhh+fuE19*E{WR#pc?)PARR>SR5^^2!8o2PIvpJ=Rm6 z@zS}p+k3viUw_GN+@iGewo!)2gEtqJN!#!GVe;pJ{uTMeFHdrQ7`R&`sGT>jR5;s^ zlRqD3PkSDnjyaDa=5vZuSp!fqeb5v!H1)ftV- z!`HM8)CC_jV;&O8!~cM5?}OSZeeC)QF~odyP3kFPpNM7nw(lzaKXhM@SFU#T+1Q&; zb0quE?Xe7p|NM6)pa~XB893Q|P=3u(S%!n4Jc2_$29vK?w3!=Wnx&lkQ+vI%-B~PT zkaLx8@>`Zndi|vLOQON`f)ck!T&`6r36L=@I7JLCppwbYx|Dv3cvOzzj)S?gttP%x zRL<*;eSrbS^Ef7aO$G4Yf$Er`KNst>TAvyZ8aPc_&Wz?QOm>T$=|;PrD`CL-zja1} ze5PCN!Bu{aN2gn5*G}rBhFpp1(ERF3kQp6gN0fH0lfo|CcN}ab$lC_KI1TQ`8Dlp( z23$tJ^Y*x;n(_23B3Fy4*LlF)2sz*Q)E5V8{HgZ~J4a4zGjTmSMC@k7qOhNJR4jL? z%xzP|i0Z56HBn@x?J|xv&u~=2%5^8j!cqV_A7SRd0=BSvkPdM!pnTYQ7M2PLi1znGVm=L;B%je1GQ6G| zh~hK2BlwwLzU8!)qoWoDA@U^{P|3h8IFt?UTGV%&|m;e21Z__aeyHda;yIt#b;R&3#|vuk5Z7P|EDr((8yTQ5o%zh^%v29aN{s= znEe~%e|G|Nmk<4c5*-6w13!)cP~0FBu^osRCLWo4QsCpT`hE<{>)KiwX0Y>uiolSk z!$6`s4!1y;px{Ds@H@b$`=U}GBoK={^|gf8{Y4J@tZo(*XrLeY&X{^^j`db{Y{m00 z_!q2An{<_|*)1FS7OiEtb}RdA4b?`f$r1NDn(K_K$yNRtjC@L2d+Yk{PC)v} zRms;B{Tau?A)41aZVb5w84s7x{$aCYg?ijTUnS7L&Fz1i{Q86Fgoe><<5AzKIC^P-(1`ev;$w^eBH zE|pJY(%tev%h%y2)@4gzo0jc)?8=QRFJQp;by8twv0yIrZ}d}=kSEEtp!{$VG}06x zH8>2eMo=FDba~{Fggk)jXmrOwZrlBt>3>oN9b6~Y@zXzg1lbBgc4sVz77m628;nI5 z$@U+92ldbAaS@xBkJN+x#RQB3RK!376b#uw82(aFhHNho)PD<{V7cg;l$G<$L&gFT zxk+t7MU1qCy%$0j{!q{Ze(>n}rjBH{*ZeQrg{wZkjf@oH$goRnM!DQwkF)rpp@(x=5bKwQY}#Fhdv;ItKbG^XVKl|0JV z79KB&<#+obY5Nq%^Q1biF)@xM9mLo*~IYJcgR(&|4pmo#Q9R!rIz@l!GSN1f&u)`&81Q${PLu+@F436(iXP4&=%1I z16kxh2)BD{c)4@S-PhApi~Edr&F(<@$C+lv_9VWq{WMht=E2AfFs= zr}MugOC#Ty`o%oxM)r=nssK5D*3CFII>@ z$U$;0()$I?K(al8+<$LwgyJfXzWO?3-!Lo8o z{nn0-P#yjNyWvjY4*(-WW&{QVe*lG7zxsy!D#~K~*IXGFF8E3l@ml(YQjNZR@NW2B z^8v$^6!#)hGx4)@aUb=~D=+dZ4!^I=!)q=nMxL`KhE9)tg7W} z7zd;UY3Wu85iZ>=pdbx`NJ$CO-3^Msp+t~8G!oL%DN<4gknZk=L&G;m@BQ6-zxREg z|NH-*=ge7q)~vPm?3q1#YOOUYMk+vkt>KR8!2~@TCKCT8#q03NX4~em{ZRqqsR$OZ zS0U7fi{dKpPu;9JMHeFZta68KdNXP|dD+ErXY_PMZcD$zMp+Qh0COe*1o*3Rahuxt z#iyc1oSSi3KI0+^6-?MTKT4xitt(C0GzBHO)?AXg>GwOwbw_UNLUbLoFSRd(q1}Yz^plc)2{{yS4MeyhjY7mgb4D;P zx^(}N@jLC`)tMvEziMNLP_grxnleCq&8Bd7K4aQxpbD^}P>~=%pUPxtX7&FkN`6O` zVD2+!$pQ@t^1Z)P3ajO0{4`Ofe**gFKvv`t63ub z?CwV**{RbY&&$&w&*g}qeEY~}Hpk%ogOQGOU75uI?N=H_5k?my9oTVr;Eo#f&>hv! zllW7052FC~vr9I#2ls#!pz0nYCs7R~BPP_V1iqd?$p|U^iwJ-i%`$?9gOEuT>=q#- zzG7EPqcqyO?jfLum%BOdWNr5gh$a`k8#?~K(g3n1;9hC=7}k>xIX?M%3?pxx@CZ}Bu4B(75gC<#m1oN)}R23jZx`F0Kh;A0e*Lt zf2IBPsSJ#bv37K18Rz3SKn89XXNx1xzlLm*^gq;!l}dV;t%R&q#0*^3)?=KtqwI7# z#}zYwt*QBGk(5--44U+&Qey@xVx(=LilW;wn&Kq`POk&%mjHPF2EVu9K%++B{;~W+ zA1?&%TLF4ku+64(2Qh4s>jrKWMVHJ4e{D?y9AXC!fZvL3u|jB5lIa*M&cKP#D}Dq3 zD`dZNlDQ0&c$Iz)ThwxYbzFJszdq9-hUmBu;ID7nQ;>w{xB&g%9apx}%PB5!BSgoA z$O<@MHx6-3N>{OY(s40K#k=I)!i+Hpc?y6*uI$kjg}_)sB==FbdiWi0>7 z4S2}xpDc6o0D`iidW3;!KZu8YxV1v!@&RP;A-Kao6!PEcZdCO40vuv035rAK7Z=dT zk3wV!4Cw$4p&|>we`~N35%+gS5X~6e7>uDJKz4z>3b-+1LOXD97v#@i_ImGndb{q* z@T@6mCx@Fq*N2)d@{TKaF2N_ep_3t6o$J*%R*l9cih?f3Dots^!fKX<-n37t&is-r zAzy12I+=9yc+so7qLr)FEOG2UFhcFJN66+L$cfFjCsuD=Aug04-*Qdxz5#CuzqKZ^ z{v`P4V7(DOvJwiI!P|h4*?mkG;q?tn;}<$#PaSrceT-=$zgYXAP<%7|&h4lxd-7&O z{a)Er4C7L2&&6Z-V~O`$?*j;5*!&f4J&}}U!MbmX@(0SHKMW=v? z6usO|MGuyV4pIaWR@y5s9fP(yg`yC~;$Y2eNk1JI3!ScPR2yc=#$2_E>8{eV z1yuGkWhog)WZmBtJ!Suf5@NNt#g1|-1lWs*!jKq*3n7R#GwMo10vd@W8eo_J3?lS1 zalv}k)MrM-l9@@3y4){w2#11*DD^bIsKW*!i8vKxhVEV=DJ8IIhEV&j2HA6=rq2b7 zW(Z>luxN%bhA{ur7$R+|42Tl=*V-B5?AKc+ShT;)53uNdnIA}D{xUzHL-}QXK=#}G zKmz4|Fh5YCTk^WO6LlY~n#qD^2diel3*t9yAfo&w%Iy$fvQD2K%qQ4!SHIEcYHyTw zXZN~5Eq-fOIhS|d7HGDfZ7rPtoGm=HZ1vcB9nTp!h_^f{zF6+jV<_z6jP-~IN- z>_Nku2CP-99%H?-MfTvU^sjq?nZp}p@I^@4ol#V3 z1^%lIuCts-m00Q?y3RL+F>wns-F&Ki&gnYdX?*2*;J4BeNlS8(-DN*r)g{Xng6Zz^ zQs;0A=aIviN9xq|^3Ioo<7dkbJ#23mj;(O^mj-CfcC+qL6ZbnWH%uOT&SJ#xdiMlg z{4o5mQi`^8IfEtGaKd-C0Mw`V=dY(f%r>2MPj8OuxVrFL9b51jHzf}(=O${Dmp&Wy zx@qvDFS3V1I3Oi17sG zAyrVhFgiSqPb#;>aE<5g7D>7A5g-9BLrXug3^_*O5J}Mh=M_xfqoV`c1NOr)k40F` zPRLy2pY$S^P}L)*uoFF6b} z9g+j1z~@fw6wiXO{U(i14GG_ZQ5Gp3O&v2zr=+7?7!7$~D~_4&>`r@&olC9&-Eeyv z`23yIFQt{HApk-D&YJ1^o51pSJL_7OH!TLUVj2^PBiFsrU=OEJi+Q_9}yUTBPA;h9Y z554>1>awk#PImX~$VZPx_kMq3NCY&%Yl5kxA)3RR&e_2$>25SBo=0S-%?u@ZYiA6y za_3>K$bDp@GDS}nsfbMnLz8%TS`gLfvVXMt^sC1^aRI9#$*g#c4o$HlawaS+L#FSDyKUv-3Tn9S!?%FxpRC64l!<3bfw#-t za*WWu_Q`A%?)Jx~ylIaQEHK%BMgY*5FGSRX*iu=f?)DSYhrJGsYU7saTu5L5$;b}y zU*SJwRwNUhfYJrq+5`{-!!omf@cim&Kxu=YEKK_kb2b51GuNYMDWA~FUt>pQzTWuG zMkcEMwl{VQ2(K$IE{H+gX?UbM?0R9skVjR2ks?`m6P?cLcjs8c@_;WeI0@gG_Pl1 z3um2V;t$~HMBiAlxO6V+vM)$viO4$%G_5~hSZwPtQ10-ok~H4XachW?%gX}T+ppNx z+JM&?B!Z2kNei~Ihh|mVB;}JHzdZ4RULE{?+u|w78l`~dR3*$(F|UMeEszO&%MAeV zy;F{TTL`qBJ{C}>?b6n4Gj16WE}`S)?M+&P#(|v5UCnP}mtW-ijkwHz+c)!bU9DmNF!zJX$=t)zpQ+*pMw!jADpbnlH7n}O&t zF-J8e|Mda>(A-$;IA6<$unOCWo&DT#X(2sm4g3L(Z(?$4H#HGb1V(GLf1Q&crr)aL zyp#W1zY8Z}Ouvi!RAJ3xdUz;?O^=NU+)`xK*P5Y`yJKs79%qOaklOVn7|z z_zY`{r2UX$5m%vz6d5m+rJ?$90&5IEx_`DT22!Lp$pSuFyMl~R)c$u`>>MYDcNxL@ zQ|ZlaU6i33(e>#j>B@a7S)off_tk~Yr1JJXgtFU6gXjeocjqVyX4zZKbKjL^@8v140rQa z$rmrhnp#-uKPA7|3R{i$-70u@va9cXxGeqE?^|?+a;IGAHQL#e0gf)YP@kt_YDZzQ zHHHgcl;^sU+CLs3=+pf ztp;C9OSJX8f4B*DL4~Z1UKw~_wJk$Eu2<%dEr+3@NoK+wx?$p9$uBNeBTWNEv%h{4 zaanZq(S80pi7WFNrO0k^E?gazO*9cnV8m>b+)bOR43*8@05w_OnaECLE&?Z+)%jM* z`!<4GC>`I6^K40xD1%wU!3!vCX)a=1vu~7}GhAE{p#ISY1!z(IL9HdTHH@nH$|IN+ zsNm_ps+Z)fSO`5dR#^zEY*FY~2^K|vYW2QR#{+@vFY`cCDVVizIllxP6}bsC z`Gy{VQx?Gv?8BUjZJ;J-o%9)T?qi@VN#LL7KF)w@b6HXsGW#l_SxuxB%ngp2%(|O{ z{hFlRF^;ldur1alLfK-J1*oy*hdLNsyn9!*OXCCEP0tneZ_=lN;~DgHSsv1!M=I0q zG~KK(ZztLMdbnp3Td%TXawb_}-|Z#8J2Ks)7m?Fcxjl50#KK1Kp?Z5c&hrM6oyxz; zZ|1lmi#wGP_p{Bx3U_M!r&>=%%bjA)!#OfsI>YtpXU!~R63v743E+HXBtOrZc;sep zks~PP7&NXL6Zyi8oRhBP#Ww~_5!$m}zh;;Bp>!pRqfE$Sk0c3DQ}Hez2L5bL`R3NB zPF8H7wuJBIQu75z4f)*?7Q7{NXpseEQI4<{vVr`(4#-bqafL=s5_twC9rL_wT1 zCv?D0lWkk~)4pssr0U*M35zID8|zR?M<_^XE$;@x&K$RME-SO%G z3PdH2eTDvV5Z3mT%pdI96V(#7dlsvYRc}#3_{X-Axh)ODG@}pfLRi%(?l^M`=VNz$ zd$ro5p8LlPMhE7bIlKshpUt#XjGz6*1!Prj`Pzl2pdpgD$As)#7#?^o?&;lOQg?p7sqv5;kk1olg*@vBBk=-1(_Y<)M!o zhpEm#LTL{pXC6O{YoT|??=vA6DKuDhx0|m|IvBw4t7NShPD{bw=2=q;RvOLkR`Szy z(wXdTadxWJg1{`CUz;}xSm6tO*~JlMW2X#KdMF~DTQH27GUE1D$+ZB>V}HdNhkDvw zg}x^2KmyjasCU#+m^l>ClPYvpKcMbP!Oh;tZzgMz)dOp257+0WB)y>=`dXo8w)Se= zirxv<)82-GF?;-3t+U#zd~z)#iAy4kHlol=M%eT%Uw6*!^ha7Drwbucp>KcSY?nxd zM*P5;e#Omx5l`z||79n73*yW_T`Sh7yL8`-=M&|sZ8*n?6&IYp{Gr6Z@zlqejBGILU81ZtanU4Y;A|%M&_b zip)xI;#&>&5&JEo5$7ys(;;)seA@A&FEMha6b@!xxZCr`;<3UACQ64>tPQ`V6|NF# zGyWKdJ3FcfbIy?f+qg0+6=+){?R>XTB8T|#iaIirHFXTfT?wdjrBLtIV~;zdp)0Y7 zqgwIKIUz9^3f|z`P1%*YCad}23mga18D95>1@hOV@RlTdVQSwILlQAxdeA|GbcbRw zxFQ>EF7_a>d2vAz)ev-!-#Yy<{2)>!vJt{aRwV678L=+0{QI$I%Kd$6gfd zhO8zV$qRSnR%{Z3?oYFAA)v15YDoF3l6U)*)1u<;CjDbiystGj^ zCHn6L!HlSSv1T@z>X^~#>X-x|{0+l4daRwW>A9R#Q)}MG;WJ1n0D|5KDJv4|7^!m+ zj}LUwFm=VN8YexxRB5RMlZ_RX6|A%&)zpRt;vbJ~i-$U&N+n=UTQ1#8e-;E!)RY7< zQS;|$Sf&h4utIFYACK2mv!jTASY?K(Jdhv-M0{SF%z((cMk-Y0fs}Aj6hrKL7&X5! z0U%9PK60u-`qJ!B=g0cpl9=l=F_$?pp@ta_1$Ts3Mp!)LnUj6__RV)(j~X*O6a(R! z*K;kSHsf(Ov#wRUo8y5Wa;=ESpUWJFH%=U9OV$v%4&t7W#ZZtHy!z9b1qU z<6LhT*R)VpRgJ2l56v~yi#7SIuC^2?x+C?|Cmp1$j%B2vPv^m6MqeZ89Gv4wD(KT9 zg4F*A3vtpM0nKW?SO8ynU44@nIqj8rKZk4I=*p=3-kVhsqzcrQqN~S}3WRfCp`T#X zr8Q~7Mu$N=u2wTz12L%DZt8prZ=`mEziq5FXls)+km3|%o@Bhzthk5F;524GuL+1k zV2cq%wzPT=kShmF3F&|=I;mZmwtVw$614}&gcXa}EFX}tJUCXK%k82~=dWo~G}SfU zPQd7HT$`WNQD``9|9qQ&dVQjOtzM@5qulwD;4Imr!1B6-3E4Rjx8nMi)L)DvWiD#CDSh1KwPg9Wl2rM2Ux3+UN)QNWy_LdP zAly#0b|nPiF3;r7JrLN;E2p1=@ZP+7`UT7m2mlSBaDVV@3?(3d_Mwo7EkNo<(c4f1qo%XreP(GIFojGb9;U&o_uwCcdbXs)2 zet4*@Wisu}BOXo8-l6ouHFtW0&i?-T2#0-=+{u#BFw3kwWYZ;FeNhNat0)=SCU*{w zZPUbgeZVK>g)57t}NW$hr!=~w4EUihtdQz0oyi?o@yJEd!= z54&U~QNyR^Y1v_*xvJO&22c`DskTtF@OwbW z_|L-WNc;IMID4zz8lMJQw6`59PAG7*r`itcCfe_NJ=9Sk0uh!?9EW``1(w%ANiK%P zz|c-Fug0vO@~5I852J9&5JZ?(bbBXtuj+7%a?1%7VmwZCWq1GmrdM^D)`#laL!z^3 z@%@2J<(w9EaoIYtIIC1|a<<&52FB9*^TWAe7FSgB0;!j{6L~PDz#WY>o7eHGGTkgE zI-S6Fk+PrF!*=zB-0rq$!CFJ_YwCuotHO*EIMn%Q=1xWE%w)jGfM*hn!o!tRM`m|N zy1=|VGpbjL*__*1Mdzd21bY(4b2%ed>yIAM@GnV(hMFa)lEuA6X!WB}hMu9ms)1?8y0W&CpK8jsRG!z4$O=Z6BfYc10f>*5|@ z-dG*-mE^s~tE+?ln+@QSb5gfp?musdZq2Z0WsO6grF{U$>d#Wg-(=A8N!eMIMeQw|H{L5)ssoZlK=SP;Ajt+Ktbjx&50E@>qgs1(d2e7hN8w9NszdzrMRy(l zZUK2S+{}gcc_fiKB>!CKURrf=;-aw{3zh=k1 z{<7K*zT*@0Iem4;2Cbh@b_3C=i04#q(Fl$~i4A?#{2=I70&dvn?)jlDtj$X5f;VeQ zbcV%9H;2wlV8HR65N1w*4TdoK$RlJNm7;!zkbR@cTbOrPB9xmYkt3|}KCyzhwxB_| zReL1{e&Gu~V_7QHm$(8x+0-b93!5LiKk}ALeYrQ+Q1Fr0u6V3uOTVzt-+kY?yh2p_ ze%R0E`qSDM6ExZtZ4+Pk>>IX`x5`SjEEnV_1Gg3H_3W|-zkjU6nB0uz-P2Eb|Iiw* zGM>e9u7Q(7S%o0bCE2sT*0I$ie%(` zmjuDfum4I!QPY)skEP*A9hk6TYlc&3hU=0%S07Hf2+D$@6dv22#_D@Xm5ekk=WEwC zw(8sfyR0|)wUbJ(>h(FZt^0G229=TXzdh98G}qu{)*#?%zm2^J0qZeG>Js3d=XWfx zpw+B#KG@Gl6h>XMLbIVLRzD4E_T!3nt>ihbh+(lVi4R^Xh@+*2wi)=Iz=!cT3eLo* z6={o1uapT;%T2Cq3rfWh~Vr78!WBrGFTqnYCTC*bpiyTF=BBgYSyaX_?oHTV4qg z0M*tFP=PsE?DFwnTV${miMC2u*&WRj=k8GMa=p*Ny6Z}bd@{6Q2EU!G?-!pkoOE)+ zvHOOyV7?vVnQd_8AU$}Rbck2dt+T^^(oR9XtRIUTOsp1LWzo=p2v@AfU@+C@_e zK1W~0wHxr5uNYYxO|mSemUu}r@dl<8>_Xv`E2Xe=h6Ic862q^^f)Z6MK^ZGd(ugXu z(iki5r4v<{q%&450eCNiu_7zumQ$Y$(^@h_31(J+PhKyRlp?BOt=UQ4hT?YT>C@d# z<=CsTTjpKza<$2%=y6MW_U1A=1EwKS#p4nJ9jP%)>mp_oZf(M!uIz@()R*PT>?noXyXF(S z;#1z97w6m7Uyu6m%VDEQ*H4#Q9p)0f_p>t<+pn*OYSa5RXg<~r-dd8de(T&sCbC< z)c6U6J`)p`NU0?>kG$i`SX{IBhE|7Gnyk{9C+TBK3YR(JS151mgeMb_JQEv}VR7B2c1}7QK-90g> z2QL}cG>qS+cknbJ=@dO+s1Rl8G4K7TxO3MUB$*eehJ3{iX6rInq2GVYpb@goV^)#U z9?n7%n|_gkg0ESj#qxhoND|-M$hAF=%(Kv--^o(xj7df(SqPV+?|aj;R`@Nv&*DL? zW9a+Ftk06c)ps5~R@yq5y_p5d)0Pq;&s zo2kCvKJd6$`A#*-)2s6HpWV`Jtr<#i)%lFcpBkyy9p^9yc`xWET+GnUVDn_1+fSH- z{%ym%vlV{NrhRQI9d6aWnrXs$Yx~87v5LEI1eaXOA0fGp1X?KWGQ?b6UtiEhxI6TG zFizD?VZtk>^|^$nr(%|CZCo-C$jYbm8+Wf5K<{hW3-a;Z)W%G5U5#nlbZ^9qUAcY0 zbo>!meE(aIv%U@%-=c`();axiV{t{~!8TFfM?@RyShJ7aQDegom*91~`CS4&@_bE$ zvF5BC%@l~(>ma<24!tv7i)L(@)&x}SB!D(!h|3YR<@YWp>Ua-TSU_Fr`1 z`onHxOR||WdYro?_9e1m726mlm8Yj03fzSSO{y8Vt(kdLC511L0>`Qz@)K?&Lad9p zEx3;hbL3)fktmCprvi^L|LL>c1X!9|pCa>7l&JcBK`;E|9%#0*JopT$Fu^_0XazSh zAzpzSxn$IjgxeO@Q*W_XPf2Ik+mnQ@ZfDo68sG<3P}7I}Nb)fq&xJ2PwGTea^=mG7 zC2m}#({e!;VC#5}dIx*2ddZru#AuxAL?>5|r8lU_J(I`EC_BM!yDa+!ec{K<&*uCG z-3NrLuSsHsdJ9xEDkwd1wN(d{&S&=qpW!F}20gdGXRV2$MkZ?cTRzP((L#*~QLdXAaFE2d2DgiSJ2-l6U#UP5+y*gFLjp3L&Tlx7|OCu z1szmUC+?lkFjuHv9^S^2W8NaAz^?Pud$f(8(=F*@ooGLCm3{9vKU=XUQI^lOg-4*v z#7aE!wqpMNu3D_Chd=y$tWz&J6Y@AnT+I9WiBeilG?JKqyz9aB$-~5OE}zic(*jgGs)&|>R=eZvs^>m1uR87{@wB|NQsC6y9VZDOBA<`LjJ( zkr?KJvuY6y2@M>{^=k{yr>lVh_|2hN`M%svaFS=jh2tnR{59d^2socSAmi6*5&ii1 zt&PwJd>d%KMP*H?R*Z$)5+nak7>)-Xr~3p?#JO_V(z^Ph+eO8*R2!;JsQv?G;I%dN z!IXQ8)$yLY&OPO-WF7>~bIa!3f-fpb!Vp}=+5RCTT9as+xcn~=J_oqb{f;%zYj@R(v;= z!mW9}fw+_(**`F&)hv9hI1ZppgxiTrBbVu4eQ!+CMXpbXd3EK6bB3?Wqs~=G8>vV5 z*`51->-m25eg8y$fKpI@2hoz>FJ9N66Jdn>A&BtiALQQon`YkSMeD_eLx}g|=KMy^(kx%DOgXsdy=kldsnI)T6V9 z8!wm{;AtNnRC_ZT=Ho*|)q^WI84aDk(@?8k7lmAPHlK%F`86wiry*BetwJeY};x8fPZ| zghcHNivJ`2)SvkhU`|@00f6cE>%~d_*%{3Od7Aj$Vu#4?lN*ZoU2&hY?WA`b_evcn z!y2A44B+z5RL_U<&xK@C+gC6~JV&NQ0GICr5du1ao(M2OASb+FKH4ltwf&3eIo0-R z%~?JqlT-7OYr*``HMV_Va66h&!WDHb0%@8ctqxrb#YxU@2NQOsfU!o?=zh7elhnVn zV=(O5)a&|+9~o2Jy(Hpa1>|N1Dmt%V)8(W@{wQXQ4Sc|Q(Xvh93w z&;4jx=%>T6&f59`w#7F2pwHQx;@VRjZ>YiJu*t~FDqQZ-F+To;gX;@hG561-LbNth z<5828FZAAst=skya$ls>iC^D)CzDdcoK}w&=zaPAyGlp)?BfRNI=_C7oMEIq9+QWS zm3CJSRI+$mxiRAV*RF^DnVADzdsFB5jqjsuS1Mcbd}xp(!#<$;t3RSg+5vwkJK4sM zkSu?WC^YFHMI0Y`pjYO-Vn(WKbAH>*a!{T0`( zTm9U&@?l7Guk0lm?Ftu62?T7K#!vb)1!%m|BIJs&ebvZzMaU@oJC5R;o6XQO zu@=5ak*v08lgzMa*wch-&Vxm4uiQWMn@&XustqnvQIiJ=@W*oFFp)&EvZzs%FlbTk zgz;1Pw=Uo^&8hC6oh&ZkV$9KhTxOb^uW)O{8e`VrBr5{5+HihtoBCJRD=k=DS%G-B zIO-mt>{PSf(~f8cZ=1fcNbw&tx?D6neD9(g7oF@*yP-uInnJW|mn%JVkfwKMd!r4f z!%DcJkxi$qmm<i|tWp~YYt_@UnJ6U{7Hxy#+GkN8 zL7E73D13=3c&=s5EiM&dgQt|~+57x|5g?^d`Vu+WfCSmhsHxMWv@h-9HGe0gHVo07 zVS5xyI*|N*wXJD(M8SP0@qH?SSB2%CVQ?&@spCPd)#dahF}VEq9WyM0?&=X$tWl)P zjQ+~c#Or>2q7+YeBBz~Y-0$(8?u->3L=9WZ5ZJA2;@F0I0--tHEJT!1U;2ms3@U=O zV&GZAR5!?;EPYKpzoalk%7Mc+V28)7r=cFJcC^q7f%W_-RWC~)C{G_KOD}2Kp2oTO zIbjVXNUZ)x3iG{_g9qjXoW?uLiZCVa0molbum=<4)86%^!ASv; z+kofs<;_=q?;GF*Ye;*`xfUK3!E3R_7jtUm!n4q-^2t^FcaJe(3sDlb%2b5E zW>*kTj4IaJ(N2pg;cCqR{c=_|NdEZck2_dFG;tN2L12pY3P%uSRyL9~I9yO;Mk3e6 zv?qLh1YO5py_KtyHOrII94#)+^a=g?3c6ZIwQ7{q;52R)zI`SgcV8xn+1A-(TDNEbg|NmtGsQJ_VQ48ZfVIK zs|ORk?UvKYBzDir9vgmOr$+w6wl|N>ad1)peVz@by3Fbey|~!q9}xaIg)~k<5=xG_ zx-?++lTgSZLquje!R=zYWYKuJNB{hp;%1O+BJ6z}GIt z#LdlqPl()M^7*-Q5Smq-t~u&+wxiam`U1_jjQ%9MZt`yvH>0D!(FeXHWLmv(y_HO* zusp_E4PwfbxI6pzVX-*Ch9!GM$IdydOGU*daN$rKN5O{?8KX@~JSb)IdfH>}@U@J5 zT+PvP?;Io6S5ye8|#;C zDT2(z!Hf(XmBir1`hiXO7>rnr3xQXQB-hF)N;}G^aYg$`R;8@ivrNdsg`wXLpEgtT z>Cd0so1;-)|F-$QU_?dJEtpkpcSHT~;Uk)UJI>QL!-?ye63y!wqR6?I4^fp!w}Ee{ znPJrWQz2XwN?d{Cq6daRJ*ITZ?SafL0U|o5bPIe-p8@wN?_Jr(3!ac`fmutt!r607 z5jIOSMCJmdNHW{q7`1{$S;DK_N(W*q6B9@q#=yFkzEw`>TANwEHWv-(+!wf>kUZx; z1hB`g!6@Azv^$N(`oFqT0X~eft8o$sIXejQjab+NH4th$3ijk#|4{#kXfqv)bpc*; ziZb&<{QG97uk9{Y^u9_T**RXn9!eB@Ru$el=#W;WV0qp<7HMRb*?p{0d-S*!0$lpf ziYD5&blz^F+G5AJ*aITAc^Jw@s4W0dPlK_HAI-2;aM!%<^RUnny;$zuc2W zC&(!BHtAPw?ds2M-@a-7#2F1U5jYq{U=dt;EG4#bUf+)_d(NVcs^$~gf=3R<*U?jyZG~ca-Nl` zZQWNYczH&2+M{v_wqLxTzVR`v<>Qx$R*LuhM8Urj%!l&k_GlK2VJ>4299`KZMPsje zs?tip zStX?icYQ`=es$m9N6};vqR#_UF_u6{V4dWFHB6m1R`}pT0$?OzYR0$Hv)j=n6(G1laTJuOk9hg;0RfUz5lE~737{(-V+EKc zGIM9mPF_BbJt{Th)+i`5FP{<;poUF;prHJ{LTY(t*o~?3A;lNl;|N{n&g~OA! zg!@T_2D>-$A~;E0aiQPN6vQ;``<}jM-bJ z-IpcX+f2?^aKyGp{W)AvZ^Sy!zcr>WsF`Ir*stUMQD8G88dGq+_wm(sQliv((zTPZ zvSsjCnP`jKke*0P_?543{LPO#E%DTw?Tho-^&ZH0GJfx;o4zw>QC-F-*lKC8QSG(S z)~dnX{-ZF@EUi`F<00UA5Jwr_UVSCUb$IX-kAM1)s|3Y>rP0XeUs;QtAurKa9i2+& zl1B!G@$^$Nh5w~@6z6z^1QWjcqbO~eO7VYjfeZ7z`eS3wE8@XggAZBKhF-wTCZ)VU~y-_fZ+|#97pjIdQM^wF6kn z37f-{m{kEhed=0KiSBgD^ktYL%wbK|T+oTAf~uB4=gu_hqjxqzank&fzmsucXMh9| zRzjuV=>05Brm=6N^;aZ{0>-C8IaUMTjfzi=aJ)NqG^kNrvt?Fd8yc8uj4Ew|p1Fz1 zJCz0Fl?J=JC&!o4UR}Qsx;WVrxj8(=iW@yxfp1^6Dp%PSIim_B_1G{*IexqusyA_7 z#hBdfI_WBxi)YHUr1pwyIa_l2;{DToZv#MNsoz7_&mYp#RGC_WWK&Sl9s#=G5h5KW zrO`x1OaM?HF);Nxpq8@{ zD>wQaO;GS-U_t+@Dud>S;;KqYpm@5l8bk#JqpRLclw;MZcd|f%q3dX8m*w+dF9(J- z$#T{ua1RWyNdROa>Vhd3)P>;Jf#t6Ezv=>{BI*KU08tl$1Wp~j+B9!5YgdUHL~sar z-Uu_B7pr0du=dY=0TCQzCovoXL^%3d8JN`K&}d=vDIRipF*#Z_>vewJA>LFho7ML& zW*w^7a}ew4nbNOsHr{n|1$pG*>3u(?`l5nl+h)qgwz!|hTWI&(dVq)R2GjG5t3Pm6 zbLcp$x;KPa=1OlT?>TxRI_cfSw2rtTgbg=*C!Pz;uen)=t(dO6p1Tv9=}RN;8L%=H;bAJa(p41KZu1;gy^uFQFuM z7RSw7{If}-iu&ne_uIbQbTaN&dAVFnZ%cb$*V(+jPFi?3=96$UNqf-7Gty6+FeYGK z{&V^MNmy}QODUb#x^}+*DlU|qY>XXk9?NZJhrG%123H`iqzaRY-}9}gJ*$v(vwcAo z6ukubWb$4%tAJ*Tq_W8F;j_q8H*MB(I=iXmQZ0fwLRL(wI0{yvy3WguFA!IUhboeV zPK`>HB=-r~zjv?z)!(?rGqRbF9Ix{cU*xCDChHnp_WN=Kb|SCosqysG(2&8VsM=Gs zhDG2Vv6wSei_BK#nS}+7Wb-c%f^DBw+d4G~C>1{u_{Yl<`TKQLD^e8uuF)EJ1s3F4 zcJQB`qSMaKEmC@U1xDKL?c-jPH?_>pUa!L&eKyaQTx_(yH^wn>XNMe#%@mF0gm}T% zs>)9uJKPD?=vF-F;u2V;+R}|?*ZtU}w@jt|@2^*Kprw{Qp^n2Hm!bu$ffz>#Sd60| z2)|(~-?grsLLage2$Fw7iPhv=0eylPh_+Jp^eNb0vouh6s$kwV(ij)>94CUWYKcj{ z&mY;mOAt)*9PV^ZZt^(%0Q89d$?*>61ZXVDKz^W^W+%W>^At$+3DP07$?QGb^U}JL z1Nmxu1nJCMwSu`;{Sf_A0-y%X1t8ZVl1dQ(=#wGR{@YEo9zmovg#4`$N2$!0{T3xl zR9jPuwN%M``{GlL-Y=Vwg`a7$R(%aS;8hXV`;lx(YTe;exq+k_K5b#Re>u>Ut+K$f zr?QYA)-EP+HFi-q`tfrAklaovGWN!_hc@0p#iIE@t2U){$U|Il;CQT?>HJ{v?Ca^m z*FxXCCoA2N>Zcd=eYLVbc>;v%hETKM*lh-*EAVpRZzUKJ!8{T? zsvo<&n%uQ14hqVB*_R}p-#MAO^0LqIiJLn6R+R(s_2o|8yTh9=u6H?w`H5sHDXDwV zlIoneUvZZ^_HP%B3(RG#x)eA{j5|_Rx*6#5i7WJPXVbDFZF<^3#|oa{&f~l3-jU8~ zbKL5mUdxX@r+^YSWUALlqVnZkb0FouwZpVhk2ge80)%7snn4=&`2JwsNTutvyM5N5 z|JvsGLABLo@4q(Q?~`JnFyUb!m5bq$LYfj-9Tsg-_;g7M)mwA+`H_U%V*4OX$kpnf z8ThY(+C+Nj)G4K3!(Ynm#!cva*^Yoi>0O4|km$Zj)OFxOn#2``vYI4K1(xm<(P#H1 z7ENI(!}8=eSOS7)1Y_*4bx>Twrtk$cqnW_gwel2UkDHoos-L=f>Yu(MGxtw?wH9s1 zgwGAq_xaV^`X^2)3l_{Ty?L%@0wUXIk}2X_(3|3szvEQ0j`?~!VoNw8S{r$U$<$p@12&qit)k*p71{*9*9 zZ8JIidT|*hu4_iDcQuhBXJCSW*)7yQwC+qd@SVxJhs&53HO1eAJRguch_`NQB&J<6 zuF3k4_wXI;n+`&}q%tA(z=TOGeLz+pczAgYX?- zfdJ0oIt!AebO(nhUj~?gYee`RM~L&{tZs;oUzPY1S;vB5DQ_~BP+OO2Y?WFcwev%# zNk+jbHSNAgB#aQsWR3-6bee!ORs^jP2w7hc=mZ>Lrc_=b0*)xF%dN6)j5VXlNSMWB zKM0YqxQAI|fEwr}0-|Yq?z@vdK|5!UIY4Y%6MLT`7>6|&hawpDBY9wZI3sket&(=T zSD7OClHc~?q|1KtrY-XL%7=e=*rD#?O7O=0oKiinjAgkg%5NVQHFYS(1Xea!yIweVMp446b0b zM^DR8sXOJ_)+8!*u|#7&YQq@E9UiSEvnap>HRBNKe|*%Js15OKFTsGzXVz~u>grm; zCu8eGR6@AS>Ndsp91#d;5SKlm8@UH`BTs>Dq?=?WH7HkVP)&D0HQfQ#gaN7v15{HW zbifIN7KFdzpxOdKwY7k1Yx#c=X8^MTq7VVx0zH%ZQp9b%rK!eSuZhXxf^u>@d#0z& zs}FCfmU0!S$*-m^?P}%mFAv#@Z8aI>&TNS^)VIyrs@Z<~IGYIb6h0N2*hwo;-quk5 zr6E64H}_no`;O0RqOUT$diDhwrWlbh&-kf)^YIqOqZ!^RRvni;%m&wiFQIYNmwj`O zK(y^EbmDTNVe`4nDz%7Y$D6r$%T2RA(#^|H`#&7LO1mPlkQ!XyeTj&(hJS^gwy}!8 zO*c(agn6EfZLFn^U507;;7E7#C8eG0lnoD*^@1_)q!my>D97^9V0m0QuINJgCL%bMe6xNP)=*0O^r37OP2Ko}s5cwlv7N6^%*AAWzjM1)7#&oK{f>iA z)XxwTUU;|Se4No%zC{-;)aS^ybS>m5uF~Mk;h)xd_F=1EMi0V`FNT!nKVXjv4;q`Y z$P>Ly;UlJ8d^Xo6ATB!Pdo#3s(?2uGJ84hs-gM%Hy+e&%t6%qKdOQZH-%uQ9a4yg$ z1k!-9SsEqqk}zm>2s*5%$59|$z6qUdrJ`gFxQ+7W=4Zhnbb2`9MZ#t5C%b`_725*) zo)Jh}&vJ%~I32{LXu5EE9M?B7VAXNPg3tBxyU?rA{q1VLUXkaU6VlQe3jsrrv&cF; zuY&YV{`O-y&5w&oeYSSpT;aY{@ z`Ly$`iyi9G*{k#137W8KTQQIDhcZ)jUz;YKqw8PPK|@cWrk%;t8`M!8I8}Z8_S?48 z%6^v_mp?~mXT4i}X0GshA)fXp=lz%4$??8R+C)tzHkWWk$16Ff%F?F1+%xM0J9RO? zkx)uFqeDYVvw1^5ba~POK6yD5S!W^c^`Y_YSr)dpD{kK~<-lTX$W5jDGHWe7?sU(` z{$#q!)mFdUMR!%53Xes3y+ED=^1^xQ4$BRmPm%M)&&JcES=%P|z6U6}q`QsmJbrIw z?-BFxFwkeF6JVj?LY{P*n?IJ4lx8I4qM(RYfx$w8!vDWXa3KgrtH)BZfDs!oMhyT) zv(oj5C(NVB|4X579;0yNI;4?Ds|&)Ob*_i7V@8xz4#N&*cNy^(&i62jem2Pp>E4y?-K_1Fa-Ay2BSuk2YwGHa6N)caQhV@ zq~wJKz&0M!ziZ28|AB0R_u+80#bAe~vF>`8i9Go1+}BNLx}WYg2q!=)PEFlVa3RAfQng@ZC94-S9Jg^h-5N(|maX7DDef;aKM zC*b3W1Bq;zQ3LWBQKrso@vM!tR}uon(hv6=NKbaf%Fv*%yq{4U>GPAnX=tmzzUfpk z=oN$(E0WF+HkydD2h|(KXS{WBZCQca+<0QiwK*$6tT!>tZ750!=!^PkqmW$h>e?RY zpxL+n;Ki>BH%6{5l{KxK8a5ztqV>wVSaZDEDC`c>@vHNgt*D~RE03}wm{c(v*W4!Z2uKD4Nd{EHkYtdol0@YZX zp6`9{+y8g=?Cv=|eXFZ(s@u1#ZdF(H#4jj!Sh$K-l^eP9_1e2`UK*a6dtbY?LX1V( z$aq;jTyD|6D*lWAKt{aI{8<1>4<- z|KY+MPNj)gn}YZ1oI}6+D+GFnh@Ze)Tz0GaYMq{udg$Q6PwC;L)2$spe11GMsO_|c zb2iu>ev=VU3OY#bO+iGSqKGt^Ea;Ns7>~TXveevoAnveS@3lScb%@^G#PRZxPJia} zJo1svwuq%}>`tZ;F*b&%099do(_r;RZeeu5i^Np$ed}MS<{=*5K3;v=G-g;?O8(y@=^vn0n ztn4YfNa#GSe5+l3U_Z?%r`W-4(r+n<`#a;S?5{iBn(Hme<FVXKgiZvD&`%`B22bp_qvbT0z;DhJP)Qfz1$j0galdHv^M4L?CO3E`dPX) zWmOZZ)A6J6d1i8!Pv-cnr{6(XYO%f3%Hja8vUm9#)COc8-`7v`AR633-`Wuxa zxuJ$Xm+4Q~ueXm{*VDQW=O);L3K*SPQX~&L0ti*G!~9>%-fkK1_8xL?Gj2DOG1O19SAoOQu**i+yThQ9o~uYrA!$}m zZR1TDR_3Ars_RCs6?f13kK??6@T6eH{f2(jxYd3}0^P(wRQ=tr_tW`T<+)eo1s>;F zw_j6+duu|+7_a`CMh`XHH*h4lKS`>+Th>HW4vyrwI`E-uc>#!k!nWN@b7EY_M);;! z!gh9iEm3sS@i8fFeQsIa{G0_B2Yf7u(2rtzwmD7KceirDZ$d;79x3)gwo-@weH6R* zvw;eq!9#&&$?3H60*aBG1c8u9dt|6}&}RwFyM7M~Z9nx%*-Jf}NEIb3Hbx#fgxTR^ z5+ZPr10*QKHKkBTqv=$cff7TCQ6eGKSZTDGj5>+;;hV%N0%YIDA!i`Abt>WNh zv>QJznWMbdkaZ0#y5E0PA&tmGE{4}sc-6`n!?^MiuF`TW{ZzW4X!t&3MG56L&lQd# zsyQ2qr}TW6m9K5?u3CC3J91oOnsXox{v&R$G%5Qhv5~`=F>IhF(ab2>YtnOOlcRhP z{PR(mRxoP5N(pat99uzC0260<{^A{9a=C(3a^{ksJ_ z0^=I$I3VyH-$>}Wt0n65aH)g*N2gw2%CCwAx$-FP5HiPs4s0-x_K+R3DIp=h8y(ou z@=k2w{UA$n;SLt1ksY=PCtHs^W2!rNkg;yejO`rpBL0pvF&kXxCm4{Iesd@$zua+e zzqnFJtzm7ms&{HSal^GH>^tg}Wl&qvQq`0E8{bjQR}lq+Fx33C@AlF( z%B_xq^~W@YQ1ENFd{mKBjlI0zY}E^A9O93nRo`XN<>2Gt5#qt~ zj?x#B!{lKY@2}L~ccokyu+!#A#O|Hu>@dXO)@@?(Nk&STILQX3ll1JV%Ct;4 zw>nBwl&yUz*0Pq((&lXrY3rbQv&bbyw_Y7n@vyzOZYVZ~c%PdT#@S(d#|L|<0p*~; z58pRjORWYD=vqk4E=RhRmYUtLFgtBYAjzec9~W~^d6>BVVs zwHLpz)J1HSZbdel4!%ob&P=UtG7}F=CxZu7n(R+6EiGm(b+$Y)c39sOXSp^cXe3%W zjz!jUyaa2c^A6X=v!(+l6 z$HR5*31LnI(psw8RXM0zN%sn?QFX4ob?!x`SV5y6_A5QK(aHlzYvRUJlVYTNb$zjS^wdT1^+&3Gg>J`se*A(@>si!j6=}S++sVh9Q zu#4wZpCr!{8@Wc%5@EG91DmOo=Digu%i6{971BV$wMR5quv(>Cd4RHdmPvkZe=?~1 zRhOi{;9GIxI@%G=uDJ92p*hkEv+DTdid`#3>_p$)*2O$r{j)gKS;!Ste=&Xy{=vSX z;}rS)t z+&K2j=5Z;)H&}cw)-|)#;r|4TydrsDHvPO*Mt$LB@cgARx|Fv{3zy2Mu6mvtHnZNZ zdFvfge=uR?&NdbuyRu3(rW^|a8JUl*s=s~_v$1`j;PUnk{cUe zHmlQ*?oahMS9#wx=~=x$;5Vh|yLPm1u%kNW=dm_*(0JA);Qq$y%S9c-Qmv*p6D7TB zBaN{;jh9tw?CE@TE|m%(JHXiTVhgs6%acrFB&QWyX0XAKUZEJExx?+^}y!<`RibQuX3RHaOCOgz}D{a+UTQi-c^UKJG$S7?H4{KiWheb zE3&Sv=S`)KVSLti!HWYwkJf0%557i&JNIME?KXx3Eksu~-R7?Q8t%(9*UTqh-!?8c z;cWUUW@=0idXU!_P7JHMUin^Kpe9n$0ES0Krupvi;k)e^-7dw^t?^*GnXUJ zT!x>aRD@-4Y_lLeaMtHhp3QnWvT0HXH0Ifx%r zu4i~(KKxNL>qaxKS_$MqW~l*Um~^j0fbay+iJL=Lvm&YrTYGXyF1$wn=#n7-%3=m7;YpP!r(IaX|KF^U9zOJgI-$bD5Yv}9?{!Z zUf(fts7z=Fe=(mnSfwk=6S`gZ>tH?2URIROu^xrkGdJ>PFz_*|9oZs+6)Rf{$TL$7 zU+>ll7HoXpMfljt)#h6fr7L4+RQ6{_OJbu?5w6+G>5K}=-@g!7lUap!Ke#Fq2v9iy z3R$*Y)TEPZ@TUn*pNkRLhKHE>|3UpX32?f5m}_|LbXy_1VkW zI}1w>u88J5S2a-5U|gh>pe<9JOzdHO%y-6hY)f&L@lV2Eik3vuVUGh?_MF4s-mK*a zMK-8Iuuj|Eob2@qHU&FFjt&5T$3egV69s{5m>vjei!;O{Lcua#!7@T2uq{gdeoOc@ z&-aVKFGhf00K6ia5Ei;*%Wqc9(~q3Swq!9!(QHh}T=}XP~ z6kUFm{KkY$vj_IFwIh|y!09B3_p3cBBVzykAr)J-+RKl6{n~!TI_zQ3W#B;^z#X}O zJB9&wj0LX7ssP+E5V#{Ta7S1wi(6yvJaD0l3LIf(wgeestGnRC?R{CkZ%0;XxCA~u z^4@LkU}eQk7VusODtLUBAN3F$a8Yp29pA8G8HQRIqjDUorHS0eGOiAi3GU5{P}yVs zf7uZxkBY(s)9mmKxB8_WYs!}bM>0fVI^lVijzhY5rqNREBB+HzoYDa8o}~hu(vawZ zrF@)H#mw)FhFiU`LAcg;g2EK;!W4o+V(JNkfK|?guZuF(6vz>4n4xW_V0=B^J2E@3^0*+yVWtNmJ({d{Z61|j-%#|Z_`SGMg>S}> z>1w1AJ-;1A*eMyGO+RP3F(ImV1rMvTCXa^qF}g=H%@z9GWym7EjlzD{voOzR^VEyF zFwegE%Nb+}M5iR5ASFq<=LYefX!M$CmQm+C!>`jgb5|t1g4#88f%J(`wCZ!RP>po~ z9!hBkntrelRAv7D>=pcnE!{SsxNTcd9chZ)D)vFQI9!=*F6)uibuNuEhN{{%)QPz< z&xhp{V~v?BeFV*|d8!7CT}$dFjZ3P>1g3l5qaWNHG%jF}y#9q@o!EgGd?M0-Nt^qM zg?Z7UKa0(83=kW;v3gJ#ZS9`QK`#axWl7ZB*4}?GlT$wUV8p(W7!(BG!P0y}(nyvQ z3VCJN7vGLYEpic5FKo_<2Xs-*b0b8oV#|mnr4KM2wsdFLf@l@O_Dz+$h3nZkT)$B0 zz!pC-Xy7ku`O0!y3sengkS>+O8(*Id7uz`q&n|9?>LmFxn+|~5msw@Y4Qi3jA!d$^ z^g8g#gm{HOC63!K<1T21XPvX$c#4iPp2``bl#Fc->DJGsEFmCSRmr7vz$aPNxv%2D zZRtv_x~+ko9m~34QSXsSQDeDVzQk-TXT z%%~7%17DJ}E)U_I{~=NaHY8F?^2A(n?PQUkO_xk13+$}oBDSx*F5=dwbH8QnFP zcge=)(@Q^g2ZTG7&R)24{oD`AE7dO}IYg4Yh0iKWWovJ_5Eq9pKc*{o3Q0^C&W%gI z(sJg`yOwZ;8^a8j&D)uSEL~AAX1=`55uqabubm&9kkM%)L4lC=-Bg@#$U`*?O%C2j zGCn1n2*zi0DYqFTUR>mIbbY{0GGu!flm~Ijgf?qdjZ|A0dT*D zBhUQcCV8$*@|>IG6sHJb1mlaQp1b9+*;&hk3r#n1Lm0SkU*}VT(cUj>iYlPQx$;7o zT2)*HJKJ*O%>8^a&S<2lRn{nYXE`DMg&~aRX6u3p>U(@12KaPWvAtk^f=aQyIz>rOk8|EHO zAY_MwcpMJHXgQtXKs*lIs51MwNOvBCke|9k>|eBY5r(xjq>!KRBqkhCyo6#6Y+j^$ zgGP{VPhcHo$&Is#gt{BkMQ(yw%vp{}7E1JK+?wX}UK|wF_QchxV2vzh9z%-TQN_?2e9VK zQBd_Ml1$xqv%{-`>E`%iRGe^-Dx2M*jyOp9&F&Tl9HjDMKOq2$2dHQauAva%Gi%l< z>JM`_zGZbUJWWFrwikA$RD0e54>k7-ztrz~&+vv%&&+Gn;=qm4VB5aJNB%Xw(R|k_ z;ORQW`a~$E%CxVj(K}H(IO90H3Pn1_c!rVlW~aJxJ+JrZ-K2m&r0YLXRcz*tnSa{; zX%C92Z2tT(_HM;9vm8G>2Rr%X-Fj&dm1iQG_wQZA#NK76>s4eT37X?jHWP*hj2t1R z!ZkJ*OVb(;?p*`rE41GrrRku9gLr`s-z^fwHXpv{M1s2Sd5H!YcE-MW!}JV*w#^Hc zR{&?L=KVniOl)-XrYV167?YWg=l0gpcdtXOsCBdebvB@$=Y4!hTcbTNwl7gCh3_>`LLXvt2e9GhCOuEe zD{<+zDxkg$QRf0`DoC~_pbiGq7cT&6IY7Pn6i{aY>Yr+$3bz3D;yH@fH+X;&&OnKf zr$7mDz~-GAV3TUmV9|4q=)CQDKz$id(?ZlKfZ7vKKZ676azOor8&K;2>Q@PXnio(j zK-5ox63@?pDyRV^t^+0P&H*-@5Ss-46#lqLw2}{?{=@~SB@>7ysOa8_oq)@bCh>q5 zeY^ii_9$3y`D<@4%pt{W8-A&CaH4b%_3+R+vhGm>HR>7*kKgVdcnEzjFMCd(^=6*~)bQbKddUBwMPJ`sE16CVxW2G`dz_q?MLm_T#si{(BzJ`sB;eO4)Z2%X4a zvDQQ3Nzwm)IEa=@jFV2NfGdK=;#>F`(6RBKUar2YcFU!W^_-$!l2$g zX&`&#mPGF!+v*jc<@+h_80^ zHy}|PFBQ->@5mRcu9d>WX3pZf@!nMOS|VTQjr0mc`<|xZ9d_BqenaAlWSTT8J=wxY zU(Lv(VDR`|;Og(&g0@S!-qW=%JxCHYQ;hZytTa|S&Jvn9i^>cnLQnE~klzeh)VoAm zF@ydF4U~Ya@QjW;WwwxHaDE=P z02BJ!-2Ovnfe0fprfAHIE{KOv|Gcuq;A&OtGzCB{UtfEG^t@rB3c{@?U2o}>00*4Ivbv8L@Ac&>W!l>W>HYjEep*Rp~l+PAxrwUYb`Zkvo=BavLm z8DBH9ci#++u?#*CI=!4+$LTioAoYy%(5tf&u0uA1X@o)}$mGR_&w|%fCf^P4B;sai z7R1P1TzNO@Ih23h@bHGbU=3Mgpx_7`^ZH9;AQD8`hVOUr|7(;DyZG->w#egshG0Q$ zN#fxf;KK~);|LoB+Qt?tLc$Xuz*guQVy1GX7nRf^k`XVwcpP1qZ=G?z8~yw|C7W1BSmlx%=fg}F zBiO1XCP=ZL8kbz}2JEUOHwX5@)!l1T7dT;ux{N^zi62?f6PT^5l|J~fE+ZgCCDmyU zQmQLgE2TT_*&6<*LJEn>1F*ohey`r$&+Fi<3GVC0j`7M2^1F+D)&68=zL}8)NiRL} zcBj_q)u)~#SsbE()f+Nraa#8mmV-tUT?Ao+ z>L@da|*HTt(!Jh$L#JsXoV8yWm?9RsepGH1OjZ#JHm`d?D z&Lu{)8djhG0odf;ChNV|YBE~y^=sX3%P{M*_jDBmGq29ebOwzIsNS~ujkvuyL3buCQs?&XgG za5@H@ybm|2a9a%ras2H`zUbjU%u9cxjGkluBxm~U?l0o2Aw*a31@%nv9~K6BVqYD8 zblOh2$LvtwQCPny#Q9R;#|RPl3Vqew8C;E5A8>GMFs`3A91QNUp;D&r7Ps6XB_HJa zvZI6#Gp^HOBx6~dI|r-vEclqto5)29^C<4SN6w6cy=p%-1-sg3dov|jp`^(NnBGkkQQ=;gG#690B#C+XqSYTv7<4T<+}>JHpx1nTVX z_8LB_vn@CN#`80dc6Z~k%gRADh3?eA+9Y>pX4?nB={B*vUUp}}d!cO-S%mQ&ZWnMl zXA&L+OU-yP1xw9~-ge%@({mvloQfwvESK7vi!VUzz9+@~Z3)`|f?gYvm3Fphbj=G|5BD-$dnF!^HB}z4 ziu4nHd|gxE4nK`jCc&-4#p?vqyu#PZsMcesI8^U3PiYe5MweYR-L6V6lqyq{Nj>c%wg>4qqqY zKmUd3*$@f%rD!)h9^wplV2x*hgjb`srNwnr7 zDa+vjHI*mr4%7!0%P51@8Q2AgeZ5Vp$vjM4mJ=<4+-cVJ|*#a2W*n|H$5b>i`xDQkScMVe-Mb6ys)yAsHG{Qgn;m=tzW1EeQk98 zrNxi=;E#<0Rl(g-f%q7mR@-jZ$c={BctsFEYD$r2?%RXvk^koUaTuk}=i2t_F3tT0 zP}8h8rpq57mQ4LE5E}5XV?odEl|qIg2g{=Y(gOEz%JE_S+em+Ed|XNH|7yoSDE}yz zA;%0!*rF!&j3BTIaEGWQfa9MV4yU$PI=0KP-7UCRmLO9BM>?tEur*Y5+Iyvto*LNE z6E46hAwLI4U{j#{{RUtsKn3X{SOp>8I5D_g00C5khyP}%xU`oattd*ykLH#HlC@B{ ziLX2DM_97O>93ij`!>J6*77~*><*8|FVnBoR0xkx%jr^=J!H=X5iQZFLOH&ij8dA+vbkiLq3g1; zugO?vM`PQt0k;n08<-hu;~Rq7xPrtldyqZ;&4GQb4I53ys>%u#PJqJgAQ6vS%VXf( z+xLLE&{|7cmAz8Ioh<1f@!_!1I90IrKx#Owe6mO84R`F8nZV;RiaoUfMAVkqwKZ$D z{)GQTIIS0bf@RnK!si~Gb+J+Zf5nq6^cn1prJyLel^VwA-ZLo?Qc7@GUY9Z^!M0JY zl4NRe>iBf{=pDY}n^`J7+>JBi^(slQzLqxX{Zjq_T=T3oejFxqofY5r8+dqJ4NQmk z+w^d+Q1cJbzU0T59p#0?7Qu4!fX#M|(h@JFBv^U26ddLwEX4=+w^hvKhSe+kYU$yw z*sTHPC+90I{9V-9bct4{&?Ra%NwC-}Qk($U9MZ*~E0({Zjr!7LJU4@0U_7^f8yEc2 zJN$E1?bK2=UcdI{D-Dy_4c|zd75*VO;AbDjuoEGA!FJ(je`3G^_2QiFx{F%wJlz$& zD?AZ&1*p;bjlRy8MfcVoz3S_T{bg%)*H4eYO z^n!fcCSKS3Zs*m6QFvb-Xen~Y;C3mAJ#E(&c$@3_Uj5TAo4<&LA30It>-tc>)bPGB zXvU$*#vRdl_U+!E_b(#DRqJ1Ks4!`yJuAL>XmMqIJ9m;8m!m^}k z_QGN#hk-`tx5ewnng?x%w|7b1Bz}zVS4X@RU@B`3UJEe1|B$$%Cf0Ph8EI(|sRucbC zsrprz&F2$Fero_4HiY>@V!g&;YXFAOC*TJEJ)po)!`LVg`7W%kCK~9bcf#PWI>;e~ z#rzEcT~!m%?2rC`At+Sf+J6I*+)lthjoJXn15GV{gjlW;^X=?tCUd+tQDB>A=o&j< z9?+)Q0swje2p9wqK$+J9+##|psGt4MChdftFb=}IctQnQH0X-?gz8uigJew0Ab1-( zeJJF<(36O|`PQ*D)oSD>^4_5foi($$AfipSfl%kg(9T=V`MhrnwU2(eQ;hGg4lEyb zmcL=n*`(5EgHEzsvE94G#V(W3^`jUmg?X;B&Nx+TpWyy~ox0k%%48JgW#hYd>9-vY zHj!#N<9LpZ?ZZf7fbDKK^`%h=Lo{WfwS@k#&crZxRfv5!Do5=l33*lXhW_<11XhTB1|1&{3box(JWSw|;dP zdayEEWgEh!8yTu|?@E>a84mhL&dK|?{S95{VO7(D3R#Bcb-?L8ahx+4PsiDPD~2O@ zRNUJalP@R;n&c8!MMbK#J?40Dsg=R^Y-J_C9b0zk;$72T=g&Be!j5%_Qg)bqBUal4IKP#A#Bg> zPQF&j{l7~9R~8ec_Hn+;)x#qWCH{oZ)^_KrCoBFY?#Hz+0~qh9tX~wz&ps_i2iiv~ zWi5cNw*NW^sz4g^?RP>7Ue*JpK}QYAkHK9=#NKvmUnDHLr31JyzmbtxBq^OyF#uA5 zXIDaOX;0XunJ4L(Qw5cRgkTk5k}&dD&Ob%}N(_;d^+46s z$c~1L@=pr@v4(60A{*}E@M8-ZIYU}p{9P@&lWKw37_t@=3EG|8wcuGM($!q4XFS9PvqzrF{h2;9{3R+YpHwojM3bka4wvc$$pe?&*zm^}Wts!ume{dz z3vZtZ`}hGlqqZ_CQ!?JplWA${bzz3T$ag|ar~;(Nf$==1 z?OeB3%sXiOhZ$zXd`&a4s?G?-0C)4rQ{;~Woe(cNX!a*M?XghWJeddJ3`;d!t?ZdT z)lwBLcI#57eUwx~8;xrl*R4xyph22E1-4Og#X@XL(VqAy~X(35dO>3Ci{;x#RHS0hhg8E&1XsF zSrtw6*BExcCbV`ZCrO2VD6^<-m}S^~#}%6+B(T$ZWrN^bORV*5WT(b%gW*S%^j{%)%PX|{)yDsXaG?axRsDpp5`-rbK&D?p61uqZp$oMLpm2MX3^Xk zHi$K49#DD~h(>JUPC3wtVCVI5?tRx?NW|wywGNcymJS7$!3NW4SvX27aUDCK$eUJ5 zvj|`Ey;w_c_}1hy@`4AQztyR$SZrw$zG2oQVpOmdRq6PL9*&jTrme&f^m}|3x|J*2 z4Rd(?LRl?mP{;#LzXN`XMj3J0)T~jzou%)iBM#5Mt!!Qvf){l}_{lhs8ow&9Jo+kB zU+W{2=BXW~kYM6l`^d!J}==T(nBr7$brD3mf?G=iKvX&|@@hSP z*0_^s0u-@d~WAzSmx?_g2lwc9yiUX4P(&Z>86fsO&Sm2k9*2tPse=Kcy+nbJQM%)PFjOu0%b3SU@}~Pb-vEi=vMjz7DP&nk zN1r1c?Cv2Rzz_5Pyhj1+q6UaK*tKI8M8{bJ+a_$a+A*eu;e7S#FvlDEw-`Kp)YZF- z2Y;%d4a~w1gowaDfqX7eM7xcW+@u^N(R!;DJ^M=M6wb8>zFIk2-^iPaVB(S$w~M+I z%aO>ZawdNQ#YBOp>S5A@p!CAJ1%>-RogpAL6bmQ5_d+nEQ2C7aMY6&thWziWS#e4- z!)oR46chily;07Y0-w1<1;)q)#M563?kEYgGZ5E$X0{-j`EM&z=5t<;q9W&+a@vDlOWA>-btBpTYz}?kL zIj9D$DO#bP=s>}X7=7V+Ym^)ES%r$4+DZX@xpK6gAGPCc73C&uLYRe~h58E?i!OaF zxC|JJq2P90njsZn63~d)R*L6RCJm}=3uFr2ZsyngH`Q>H#b^K(C!o3w(B&w!LVAA9 z%MxtJO)v%lwn6@a_WVm5~Ub~wbesG`O z-d->ZFWI_?0CEHCi!fx5&IkcW9J>Jkzzvw}mC@Y8!$boQxu9a0VQw)oO346nXWKGb zSTex+~eQPTmuqlLNkWJ4EN`BBgVd#224*6#yT z0;}z-?MG#I$Vz7!ItB@xzmyjYJ_=`us(c5 zCj#qijb(StG!FJ()Oke`u)e~Hzfi%cO}wz;CDj#pF;iFDnkXO$`=r-wGvk$n1=oQnaNq~_I%Oa4SN{fv}XD?8=TRW5}1VkkZZL^@6Yc%j%D z_=0BTC;PP^N36FT9j;dZpJfD}WdL7blLweKb(N%Zjq6*#vN0I-RF2l^qxReA$|fx; zTI3V^YHrKge5VQfMgigE7%=Z{O;8vP=G|R!wO{rmW%JcGdH7zded2Ew0C(W&ee1+rAWE^ZHna4<#tf8lJkCwM1 zyg-3BfG-hvU`%dM%Uve%%*(jRI)v^v4+si1>2yP!akVe-Xoe&+bdg4hlN#y+7tT|h z&F2f0qrIK`B)mxB7VgB{De+7l+++GHwKMDPc*S~;hYB=!U?U>!bqFJQCi znA~riOCkh$E%06CI0hkN@JtC7b1i+fq|X0%6U7$=zy(8E!r0QuD_oXRL8|whQ>k2R z%n1rF(P=k#Wq$COOKzOG8QQ~km>=x*v>9$S>goK>xZ}P3qUA~zatbBP%z|xsxGXb} z^z-}OC0&UxOi4{4Vpev328!=KZ*G+|bQuuBe%XJhEx=h~iZ?1Fb0nx(v6FMtBL#_+ z0gr`u6+~N&4j^;cKEP ze9sl!n#Td73H9>6Z>GJ^Q)3AOSOeuKZfA#u&vQ(PUaFZp1*q*zec#Y7wel7P%*ops zQt%c4$P8d!z>vB@z$nX7>+pBq^vg`ythI6!?~e}<6MzjLO$YZ>!LlAPyk2Ox$4d(! z^96v0gqGqjoN8Wa5l%yUJ<=~Trm#jSZ?3%0b9Y$&P_@_mXN9NTVO!$6)|^zQp~Ssn z-sx&=Usu8KQR2%sm$RJ|v{EDe2-@yEE0P;`nvtO!K8RD3Srt`=Ri8e2F+n6BJ1eh27Nq%arcMCG=~g(lgY${>=UJ%}b5?+frt`(EwTFr=Br$*3E98 zOGWj(voa~C27>es)a8B6z#63~g23SpYYbvelV`g1eC(VOs;J&3%5MERqkoMQ%kIo{ z=2SWFDyiear{*PxHSyUh^Mrb{0RwU-80Oer%r+~PpTfkaZ*0m8yxulg-oU=Er7KU< z{^c^7q(}&>Jj0d#VP@xk@Wil@u!7$$Qy&e%&26UsnQ=nLnRG*3l#8zl4kqqtAgt1w z8rzb71|OyT)CVESiu4lmO&Z8`gXcBA-J8GS>zC2qZs>2f_8uRrk3n?)aC0$s^sB=j zcA`vBjN7F2_->@QHOc{_oCxuf)xCMR`c<^(uY*m(qn1^=dWx~>m$c|dDBrrz?G*m= zt1~e|n^>URa~#Ya3qr>rG$PQUS0AL{@p@SXkzaN(&;>0r3<6;74FtfmQ{F~~)id9NBScP${_@Hky62l!5FQ^U)-IkA4R#>e0w8(<%2A`x)gu(!0H=umJOS`; z=|qt75;M2%5>U2;9%!8>Utox)1JoZzNua#QQTiJMoND?2uyd3}0^ETgp7{_swSgsY zTgR<=28ymt_!>q6`ae%|nX;uc!T_ogc$y(~@>z!=4w}-S1O}{Z2e6?fc>b-K`dgiUkU;AK6_cL;V^eXVQiDI-{vViV{ypzo zFC_i!_lL$ynP6Y-CDIMblba2h_W$U1y=m=Gw!F1G?(2c_YGg|t_3RLTsT+Vo3P z4=x4{cZ4HZut|mzUBoRMy8O16z!v>Naw$oAIk5uG{N)^hEWx@z(K{@w&6Om^~DiDJ}L^-JBtiUy-4&| z{vX;TnQf=jda$Jz|AqDs&Iy0m_U+$@8&$D(fB66JaQ;J)SFJt|f9v@#K7Zq=Dkd2r zy{}j>p4L-QOzMey(0cZ?o?F!#NF8VT4xiS`9IrcCnQR{2TV9g!K3F^$Umjc2b5XVE zm>90MD2jU|VJEYE)GXvSwCGV=y$1g<_@FY)q{H#9Dv?U@HAJdIY0<-J6rcMq7|KSo zG6ePN1s=MuY8@A?epbu6e5vZZ`v)9UK@drCzqEL?ZUzS;H9B%MY%|hZH@?y7Y3J;l ziA-kvZE>IYUK3fbrCsF@McwyNHb0Po8+Lhy4KT+6A?Me_W?e>`McI3rMKT%(DJ8pC zk)zr^8$L3RuA?)#%YWiwlL{&P4GLvoh=N@h>eat8b`8a+-l%7#70S3h$Blt7kRLYz z7Z|c-Q3rryeDF9G12XV9LEz+Z`ol*Bw0Bg`9-zu4gRt+ez1bsjGno>!{lHLHqGFgk zUuElV)V;L(X?Ui_M|(ZJa&LUsyRw9nkA53-nY7dRW~>1p)5GMNN433en?HH&*s!n3 z4at8LVup(Rz$+b-#wCZJ9(mb&X_8}$V_hr*lNx%k0qQ-on6yj*k{^=yWxqJ}zJCx1 z+KVtPb!LvGn+xwHmeR9AVB(Wj9O%ll&laRBrol0AH+|O%4<%YPH<&B zwD!&@v17q9R}9p8#JIzfcV&K{KvjQwgv~WvHKZt*IGax-RGLOVXy56@1g!T32hp}{ z=+Auoh&0u9gO5Guiep6JbBT&Ugnd5Qq^7*Ips0lE(wl7F=uN?_IZinIwt+_3E}oda_eMTSAd zOee&&-dzyB?r)sqFfu0{$N;g>6krY(f$Z(QH z0)l__Iy`4QF~6H^d@T8BJLPr1QV@fp|fZ5fY#dp8<-2 z#<4yMSq17lB-820(Bt8fT5kv`)k!``2 z4uCIua#NsA8LGXZ>~?catb;73&XRO?I#QUvQYbs}X%`Vq1wo1LVZHAq`C_)~pHCB^ zZ1!23`tFkFZ&rD7#xS@TKEtzx>3(m1@yLQ7-RB|vRuISC-wwZdN;VXC+fS3jQ(b?v z%ECY(hIw_Kd&EQ-j0DcU%Q(|Y3pQ8rG&{lH5n}HwzPyTTToxMAcrxL+ucuJ)^ao1h zke_2j%?U(qczqySC4e>G?G9PxdAnUhh+3eX$sb-0@R$bhATr=M7T0)V?3`-ikC`2$ zK+J&)Yk^#Y1W{PB?O(zWYW*<7!i+PG#qFsw$^WKC%c2S-o?8#kvB2#P3$PA5P{S~6 zKH!)k8u4!ogH8l66L@A1tHoo)^m->QL-G|4Qfz=c(L$ovKv~gz))a_WuABKV#A{c$ z7piFh6x~CDAR8oEoJK>Hf^@AsXSa()b2g?en-Q&E$#ql5Y}AMd@6wE3e}?uTE#-o(b0o`SRU zNPMoq(w1+1PQ0haW-|Y#@12f=-RIa}YhYZUF*zbrc`gu!P{YT;h*rI4xDLjI>K6=8 zmsDelp9adKHmC3%wPoTd96z^{`lo5Q5rr46s}i9FGD={`cDA!H@ke(YDJ${UaS%UW znsOjcP2>IEsPWgH2by1Lf(`pJ?(JOX z4Dxh=w8&F9P-6#yh7$lfC+G_JDjm)5%{Vz{XpHIe$t%y$`~=&PlJ0*DEsDVyiRSza zf{SuEHoQtL^=l|k1x)*bVU=1mxR^WY#9)ks(gy%wpanqw0CgZ1^(vL}c$fsh$uJ4Z zNU~Lc`fy@gX{7*G&cd*Y)Y4Y_BA|l80jl^sK8mSN(Euzi@TIKl&MgLpkx%~`nE-dst5bcY2P#E}IyJI|XlR7{yxJk#n zpdENnMUHv>HLG|7!G`SzLq}~8jR4RGoDAfE?p(Bz!chQ>O@T0-83&G(oF&RS+p!yDAM2t)3xwrm1fy z_!?+a-C;|+!tc|J8lCKyKH@mqFHM8-RjgA87>}77s#A*3Jq$$2JNosudIY0{-6>~X z784J0yVOT7CkCMATTy`C{r2a4gIE?^Bk`apv#SPWm;&L1y`x5K!q+aRCUTNaO)^!JXxu`5}UEHTve!)-MJUy?&UKnc6p zCl}46OY@+nl4K7$b~9c#ZjJT^K4;5QBplzrO2|Thy#Px)MUNl z4(}cb!aT5-t11eAR`Z={x>YYrXmF!J#Fy)9Fix@i6P|%xO=d4wp}`V|ge!b6NsY(P zG2wO17b&UYr^npo3kiTPv%%gttKs4HS5*rlygHzORY)kt z`ooXdU<=NAc(_}*6OSWSr!lJpuskXjDm)_avPFsZcJ>p|^ZESv={hYheW>)Tiy+w@f}YewAP*ta7~()&O1=YJb7i{z9#d|LxUX z1u}7CrT>e#_kfC`+qQ+Fi6RK1L=gl;ktjKX3J8jbV zNz!DAt>n-^0|F8y=kV`B&bjwH_nh8g?{2ZEz4opu(8UHcNbnq} zHOz~-UbV{4;T0Q1?4Y^%G(X@W$ZnWz>Ae=v!t*-lRGIv}YnH<8guiUiBFT!Gd{yJ} zhAX}lzqcfL?eYygX}Q5GH`s9xnoT@v9}+!oif~`DqD!^bv2an5&o3dVHi^)v%^4Og zW$Y?3xk%_&kyX;0$n}Nx16xNylUB*cr`j)xbuF3<`zD%P-R&OHrE)zg$uVR!rpNjyarQ?y~X%lt(j6mlUYm|QF-dT*Cf9=SdAbtWO5mGFHq!l3P0w7S3;x|xKv2=pR+R^xU@+5~>1NAm={sPWA z$XNpjJj}aXQt627Tg!l`1q3M|H~~=y5%qwe!eq86ONU;OUjalTAn1X@7E(Y&GaxPj zA`Hs03Wyd!a0223q=1MvKwJmJH%PGthz>xAW8NhFl8&^lg9r>DZU6uYN0TIK1Kmg(! zlw%7JBY^M%#4ktz5o3S|0tBfnP;7&*a~yn~VSwNSMBO$}Oaes=Ae14+4j`rgkq8J| zNC6QufOrFlFi5crh*>~<0K^AKu?v#UgQUfP_y#HVfMO9SP=NRaDInrEAkdgMft%}- z8B3_dua&>N7`w-4t6J@c3!m5ApOM8Hl(Crd;UA#fRi$e=H`qxkDIY!2Wy~L*>fA`xPB5%^4#Ofo@sGN$k@7z= zyzRA7ZuNu?UBF(22WK9CifAL{4@yz;V#W4kov)|?t~wFev7_L40DBfZc&C{F1RwC5D7T0*Mgvg?cblRy8Bq_<&+Kp=Z-h2HtH_(B?Rtk8kvJ*Lm24;&@`x zSLApq1GES|U7(Dc0L3vyfUv1Op!l`No8yb#iy3~+iVfRU>@Fn7Wh+ol)8!g7td6!X zw#IBJcCMHOs1Lsey(uIgkN2>`6GL*#qq2;l`59)rO2MEMD7XtmPJ399BENv__*;`h z;24xo*a|}-Pag<_23R1CQRMtvs0W}J;HXOsU2H*8NpQ6fQvI3gX@|*xAHv`fP*4Ju zzoEj97~aKJJUFBW*X58N8YF-oK-DCW8oJzCZ1urr$OIn7-rx5VoIPOSv3Er~3Yak1 zF1NUeORVmDKkv*+y3k>MhH3Q-3w{n&PzX9}oDLQx5&E4Z=OuB(0Ujc8m7W&w<7zVl zOsD({72bSRn-W@*(i|V1zu-w%8v<_B(=z>P*cJkoGR#LbndOo4VSrOsH(t}#j5Rv%R^#jM3X4i64TOlH! zO*{5+UfBINWc&gqNzQoCVupTJ5oY^$COwqL3x@ML+QbUU7(VMPviM z8AX03MI*i$L4IZ=fYTR>(%kWaE`mqy6cgYraO5o?{}}{-3<;mFgrL37dd!N343OlI zvV90=yhVt<`-UtFq5b|P$(xl|O_2#9VQ*BpA6L4CvxPv57Zl0Z0Uq}#osQm#7WF0B zIpO|G1@MReO*p5zVuLogmuY4F$pwC*b2k(E$UJAys}gFz6)6lqe;*+Dy3VT+M&^KT z>pre)Xq+#NE&RhjuBJGT`Vs|}M0@}p5?)}^R3zgL$y4s`6ws!Zu8W05d{`l8et74l zBKSLQc~(o2(JSi1giRYuvB=b(oY%`kv`pZYy?4SNFWq_1u;)+uLN>6hVB~z)i-T!Y zmLWNs_i2eg{NmMs)+v%Y=KiIo=UYXrG}kO@IudlH&=lpIG&nK`^$0LWjHWGBE(a5L ztzgRY8Uc3o_^BC&TpCRaI*_|1+9}AsU!LuF)j~X*Rkf%M3_LONPx-w7iqLpZjsR7; zn{Prv)w^Nif%OdntRw*=G`l%ZZhKtuX83+w@fLb>JPNeA0R|~@{gCs|@BB}O@1)QZ zM=(LRQJ{z_O~5z~Rx8-QbjdIT+T#Ymuf73j2byjL08O_lGaO%x1CRt|Jv1Dg9-yAs zV58f}ZJ+#^3Qzzm5?;DQ4^Q95gK7w>k>FZ>?rp~lP|uxvs|p}usGuVP57Y;pQ)u!3 zHo2KcjItsYMt2CkISWt1r$DHvi=cUh-t1uwv_@v~1i?p}1|3GW2N6RjT)gb@6has`%Qc-~(YcG#)AgPG(!d}x$Rs|^Nn^KT&l!&3-AjSvDbDFEgE zr(-b1UNFs?x8!OMx&{@106>$80HCwN-+D5~yk&zq+CMOrOMRtndc@Tyr@uGbaEHYjDiBcmDzkqvm zVP&x8-GUOVDB%L4xUIT{syM}28^vVx41E(XiopR7ajiY0!c6WII)FOpHQ`4>GhTdq z`~hY3ZM-t-Vw#{d!UaMze*8T@G$B~ex6Fe_a!Q;OO^s1u&?c8wk>=0Rx>?+?rg5K! zP(|8le*Z}@M>?`JpbjX8edHdRJ)g;{;v$Xr8s%B8(x34Dj9#;TKGOliq;RB*otEZT zmgXlt**moqcB;^xhn<#ox>Lkw`jlP|=Y4a+`{uviKU@s)JqUV?hG8P8F%f^?$9kHa z_cD1^wU&uq%WQ!5=1ZPoeprXlAFx&DbFRE+2{(t!r3q6bo?k-921N#GZlu?uA4(;J z2DwU{C5-w-V%dqj)ua+3Fgf*P-kg#!mC}qIoVD0^o3vhP7RGROnct(4m?2}}=Y1BL z5E1?-Nwoq^%UTer%H7I|yhLPnJE^$x3*=@1i96H7g!>WoU3baw^6$JM6LIVqyoqSY z)bkd&BKEo>$08lcv-xI**WQLlBXK7DQu@~CnIe{@a)a&J%#jY$_t^`qk(J;1*Fto? z3v}EUKa1c}t>byvP2CKNjau9UHqFhe7ciy{_DH(9j-e6lBQ9qZf`w_14+o3e3yLPb zBeor4_7ZT(Dsxu&nOkgFjTuUWh3xX!%$$qSXH0=j6JB9!DHopD;wcI+VyFMcAU1n5 zfp`Eld?GK{<%m{~1`%)6IS7CU%{Mc((Q)in;4f$*EN_Xz|Ts^F-$MigQ?*J#kQau+~_- z=uu6)Wnlr<1Ze`-i(!{2(!Vcx05f4J3|kiG5OSj66xBO+e%(mS-Z3O()Jere|M!?a zd4K$~<~)pQDa-ebA&LGgc-Wxfj%P+vWZ2NKs%SBId+9s>!W2Yh`Io?;bzDz;;B8cH zJbeWvpa0;kU3ZE4Xy|Ozi3?chI>h&(l!(|XaRtj;B(TwG%^5YFlNeL6Kiim=2;Lkk z?)RjYFu(~PWf6jbwSG0!NLAfdugMf6BFHc~AC!v?iE#0wTzJSYI{2vBM2YvNPAk7z zGbHoP`cpbv&3u#>FJ6~Yb^&dyn~&uC+9wr1gUH=j-#&3+A5L2MkNHAFYda`2QkqnVbT*#C#H`eN$dsx7fUxSO*i%Uq1|9s+|AGE9N7TM7(gU<^TqAuuW+LmwE)kf93iwm@PQ0PU>HD#JTN37<0dc| zAwv!ryPts}!(GoY{264H0!#(ONN_hlo#eRZq!V?zStYUWBlu(;;3IZ^ybS&{$oU;a zOx0Y!`bzESSKO>~U^YraRB?aM9o(8f%~Ew}u*#n^tyUhW_2bBPugGpmjk3{acy%=g zYs%cV-!-=y`fN{L{@`tHpl!L_mmZd(-Ow{jr71cIa_d+YpE*kZgZiYs`lQ|Z^23L? z!|M+M>E~E(FHy2@gqG}&$2FfiIQ33~ttM8dU+(AOO^sh_jBn+}pB$dLwthA5K$oFB z;1=1z9rpFB;b#}FhEp$msye*JKB#t{W6;WbM{~*N&X!M?5ua!2dtaGHeDRe!UDfHr z39YF9tANN|+IZqzq^7*(qcJjnYSJVlW@+PnMgO^`YFXBi`8)1KS6}%0->T@3n=^@C zDGc4)LxQ^@Hjt}w2bi4gVYq(E;jbyp{pdpbZkB5Q1LR)lmZ#Itz}>mYl<2ye-R*u-3f4wqGt^ZUdrRs+dZKdT*r*IV;J_41mU7UmFk&|4cAPWIj zAAOva6uO$?#KpU;$a?O$DVCQSG2yuIb;o`5WQ|ASZ_m4c%c-euny)60_ex4&pt4^4 zDx%&9JiQG)W>+qbP9yS2Nw8^Is?O!x-E=)_o2eXHrAe*X+E^4FZ`;5tEO+l@QZhr2 z-^uT->QMO+@QxlZY_v~S);BtKeraSu~xZ`yiPqg>DF=Cb|D#)?A z*%(IQm=d#n8d)k2|W_Gb+B-yPsdVkVv{4EG}o%WvU>NHx5h#ra-GW$gM zg5Ws0HbK)#8kogNn&7{sL7${?H#=$j7D%HV;%t^j{enm{%M7$lWKpZdOHYz*SF3kj zoBVc2lKFMUcCE)i!U!Z&kc0$CWPoH2l2A1T=Y~L8o&X6OkZ?Q%l2bsU3T3GSlJh{4 z2}zy;2^Wx9JtR-$IX#KCG={Q35_%x1gCx&@L=fr=l!XFhafGte0|^t5OhA%QAd!Un z0!b)=#2?B6NiH=7wZH_<+|vmIl3P$;%z@-AkVHaR8i3?7$igN7vOEWpyHH;s$vGfN zgR(#pP9V7jNy33d1L})8=q?TDZUK~~5lDENf>%gSYx4d9J`msn0(v7};$p1>_BtxT zb3x+Hm)6|#NU$^^HhgvYbLC-k&Ij;Lj2*70lCBft{PgM>XEzxBamPX?ohi#cCj{*t z2PyT~DEQxob`?144ez7z@uf;9upF$}=GE6j80KasBoMbS=e(f6O&e~!d2Y!f9$ z-8ZucG>?!G+j=LDk`RnUxXMXBx$ub@4?a|6wgnz#AL9%6Eawm>9w=yNf;DJ=aEkvv zKn~VFgiIJ?Bx3fSy{LIEA6Rmu@KL^jV*?(Mh&=akqOujrx zP5pSiSh3-f45xc$Xo{!KbJ!2px0^=ME^SLY^~f!!u{B=&7uBfxa_suu2lG9JRxi3e z&e$T$(%aII1+kmML-p$0!l9Ut1iDu(1N04;z9((kNy*}Oe9`rGqmLQ#>iLo0CzNcj{07a>oy@rL_U13bB-s;} zuGS|-KYDcLUgORC&xBaIyTGeFOx*-icl0#T!MS(iAYn2LoHvqF$!%nHk`ZQkT|X_w zg$l|3AYA$nE_7LDwX`6t^=STz173fQ2eMj@lNED)yBpVuu)as51?i_PjFJg7UtfWG z;S755rx|N*@$1@;TtF}Am#@^``$yp**@=)?yH*S8*Wa)yQt2NOFz6B;C;B^zG5rCFTh~tkudoMUu^>3jRMnsyqJpxfrO&=fHp6B?N?}V&^LD#{6fPk| zJ#0G%YIO}@CHcok;9^^Ev%JDVdJnt1Nq{0tDyeerr5#X0Wj*IW^Q!WICz4ukz>VUh zJn+F{Y1A0%S|@B)SIRPbsp;6OWDR!$D+7jKw9kzk$3P3@uEgVcc5s_v(uNv7VMM^Q zK8HYK(9Ax_+56350poIbwk$>ez_G3nTPjo6LQ8>H|h+%NBkNeF>Zx@+V3(pO}D;gN@bdXtU@0;v&=zfDxZt&>j zhyA?W4lC&>KZK!h!ix-*XITR=c-XMthYp3{+kw|*Q1dP7yxqff4WIM5i(0QG9U(zV z1~}c_vdQ{n3Cq!xdR!xtT06$rIbBB`WWR!Z=DN*SC$V2JE`3<$$sBkC#c;BL+XB#@ zfqchr;@CbFIJ^gzGV5;Zrs_&?;UiQuV7T~HLa-S6RFI(tHJ;d0n@b0~MjK%W&D*d_ z6Qp(^8}>YH<9bYH=J&PQ9J;ITP36FX@AwgxveTOqlmoP(xiVq}X*7q&qaW)?@PfA9 z%bUa2kL~?UM4rp!+eFy=du&hJdTduBHo>5W_j2}zcT*`e0Gj#x?JZysc}uw+4xXEP zyYHrpk)oxZIG?b<>SrUO@>zV`t#j;hZHh4|%y@j-ge}gzFHOc#S`?R?-4#5ZPHJ$( zFo|W@-a=^+T|OTEkX@1hW7){Oz@Mm>-#%V9`n3OYyy;Xwf&Rg_>rg>7TmcnMs7KT%pE?9Ewo%o2Rso8O#sKPg42Xv=`h`ni{r8j8`E z6R!DOF2C0SBzBNw6-Z(si8PQ*00~hvQv#P4$Wjeuxd-L+P1{jwFzD0m)NH;szvXP!=X2nFd(|p)3+W(hBtjlDGg#B$Ne`OaKWr zBoPOaI;byE4GGpK=KLd z3nXy>5@RR}Barlg?tZ!rx+?-Cc~D;>ndqVtu8aHu4k+Le2vB5iapYn=+DB}4fJ%9w z3}qGnBO{osj})&%-BM=jP)^4WUz%@mqf;dNZRD+P!+t+x^{#WezEJpx`@s|_+$4=oMV+C03Uc${R9V?V(f>F)EEjO4+{z6CpB_@!h5dUkaSkYkTcDLa2gHV4j z{`jb6YlbA-^_HBd)$#~gs!>gEzlldbW{K0+#z}A&^3wH}0#kEi)Z{MVf|SM=UZn`Z zaDj))Hb+>^bF*&tF%R=1D04P5WREhRDSAezeQS$i2>;!ysqu{?p_>NJYt#pGKPZ$Z zV#MdNBL0@SNsflXf=T;M5D}tC*qkM=60R#k@A??a{uyj%zVFSu z_DDFE1@>V_F|ih`} ziE)G>af_Xg9NU86xIOIzvbvd4CxF{nr=rXVy86I0?1hTj=l0 zUnusEO18>WJuWDfEqNZiKGpapZ&_nt?8`NSSgTet_4KcyrdNijc}rDG{0%exrE3ly z-k1atyEuOAi6K+(M14KyDvj$N_`p;3(I`n@=puPya(aAi&-xcwc2mws&*lA>ZvG_;dHO4$s|H zJ{p=IkPT4J$Lk>*c4>+^`gnnBgWC*pj8M<(q9I2GN1p)D{0=lf=nxwlldalcxhj3_ zougWSt^`u6ekX4JKC5oMV^o^ZysM9OV%&#(i-XON>3uKScw~#XXFUAt(q&sw;wA0y z(`WRp-=iPyxQF5{%Th9-c<*SzuvQ1LFi#2Nrl7r81uL}wolI&Ro2(}8?Pc{-h_e~j z5Lyb2AD)N5j1Ir^VQE_6C!u)mkYI3*B4o5hf@r$5C-t4{kkt8 za*>;llo6(@Y=mCla63mngv{rktr*m8A_& ze$&ZAzqc|X&MAo5IxPm=bf@)KDfh!hzmF_xjx|gvdutsAHgi*S$#M2Y*UI5KZB{kE z?zgxr_Q1~sET&o}qJO^fFjZKzD1IJ%g*chs*8I(XH3&rozBk-BN1#e>iH1bmDiOhI zUu*V2`->MAzAj1D`d5?Bqf+l0j`Sy3upGR#X-rRjCTX?BM;& zqaqwJkr*ecAY_;}!9#pHUib4xN!ak~`*eiJsw4sISK&rh)Kue(@iSS$#I?M?t;ogV zMIm3j0Jg-fTzuMkquL5(5f|sAr9|$ZalX*EGqdL$E~EddB5KQ_R<1~m48KhF+MevS zds0#k{JwmuVp!kCID0uAyGkWbq z3^o|nJ~LBSq4CZ0@SA68)IWQvmw2&PXMr37Ug~qFmO;~IIbq?7xmVF9C0-FA&0}*F z{<|{xa2oXz&J9A8ra~jsJ(JH~)#fY2jqxV0d|*r>>L8bZU8ecZcjkZ3GSCHuSF>@^ zf?kj)YVjOri9jA_ahQdgsJ_DGqo_sxpH4(#TxIK-JuHvuKn&EZNB9Rl&_cUsrZM*h zVd8IvN}ah=hi+D{*lr@+c|*oNN5J4>Br3f{xMdjh81nj^zf4W7HXHAg>`wP@XwD5XvkCO^Y; z6;aRN>A3lRr(w%%?RkotAEjsp>K_k8_5P&`=Q)4wXuBiBbOe8Dr@pObEjn#X-#b06 zAQzLb*7@7-qi0(Qi=1JPrJQF~I;Ap~yRF(oqt2txY*(%hFHKsA|Y@;R(vL=0|schtMxm^py3pJp}%SK&ZqgZkRA zCISx+UH>)wQDCBTI^g#;IA>(w-oOeZSW;oXFR#QfdsCE-g-lMe%B-Ng64SjF zH%CKJ>841dd-Z8fxGm?rtnmrfgsulGF?SzfYyD+hr4*&t!`lt9{-Yo&@)|b{KL%fE8)#y8(LiWyR%fD0g*GEo?vxcn<6{>XFo5+ZPK1K zHj3NgKFl^tdZYZ&<=%WS_lv7~gj~#$SIIAfi8^96<52k53~#OgDbugyq;Sv?x@~`K z))vW}#H$?n2Yaab?LD81XKE3?hlj%(`v=Gi+j~x8%Uff7TobITm`S)+L;bgA`7ywJ z9q%vj-1l|=-D<;DTfikyTfla*F$&bGj@tsQ7jfK-0RsdXKp+bQen7BAj!^u~ zfD7*ff{#ET0SVH9KpF_Z`$%JdgA8LJLm3b_Kp8rLAPop4fxrz2W`F<#1o1$?17+yM z({)S5FSHd00t66@0YMEActCxy1{pd)h7^!N6bKxEpdSc|fItW80}x0+f@B~N1_E0k zz<^F>fKG}+eSk8wQzi7N1htSmKdL75YNyg&O$2IzbLEZZn=K<5EO65Uw>?Co)im=4 zIgOEZH@@yy%RWA#{nMRN34i?C4T0)% zv^)(@61_r%jo)I2-P=&QhT~H!{)t|M8*06YE zvt(4(_kRq_zC*(^abo-|CP&+=rURbNJ6naryL?xy1~7+VerOt^c0ao5%IjlK(IR6{ zclg>pAAUXEaAM+z)cuFEvE;XToBw?Ed%>-Ot=Lv9a#V%Oc`SfGxBVYT*D;@eLgt!i z%nl&ORJi`R`=7=9NA}J};@MF+f3BlipSY#|xEG`TxREFBg%h_VtnimRq0x`IKgS-Df8>!T z@{AMt^od*Ik6ZP`9ev`SIB|=^pbz_k;=~U zSCvEW#W~&Ytd5B~aI=aWW|~J{-B_P(mB8g#%u|vMv+S)uaz69^1$NgA&!h)AP0wVU ztM3q1E0Ri&;FZ6E){wqgto7^#Iu?(lR)awhrb5O0%QWn1dtgZGr&t%LxL|| zeH_dNj@iKRWq_9fUIBOoASXahfLs8%0P+Cj0muiC58!ox*8vIw6a*+tg3c5UMQ4hF zV^MG{4p1DRBtS`k(g39a$^w)Hcmv=KfVTkN0;m8`0pM+bw*e}He99o-U2uFC9Nz0Mr4f2T%{70YC$QMj)RN$Y%nMO~A1kKr?{mq3EhQ z*kvig_{&nH@xoGPjf5*P0e%~+HNTHm$1reHLypzD(z}-V3MQ@v)Pr0vb&c{B%I^MD z`UA~o$484#i~p0P|Bp|kpX+4-wRcD9-Jdf%dXjy|;VjO_@LweV(ZIiQ?a+NtICR)` zI@+J6DO6ah(40ZWH{E%#*8MaoJZM<+T=yOKgDJVTk_--R(`$yQQ4|UFITnifR-feJ z^QLwQ9+W4{pZ40Y#}}8QAtp;@In7Jt5k54#u)lU5RTZjkmJ#Pq?)AyqC_b718E%ig zMvL*3_7W^z*VNP8m{slEa>ljg3wSp<=EY8RqWr$B(rk3s5{mEKQARW?DN0?49u(49 zsB+l9MCbH?$E5v^2N}~&TEYm^Plo8hC#pf8)7Uj|KWA{X{5ulTNUxUfwZS=rYu6bF z=n+MzQya5a6hdgk-o8yzb;OQ1+J4G;jDHo$W}lw$&bKHm5mjVSj0k z_Q-s7EE|4Yb7=RPJnamvPEmSezv*jBTd5TPWD7*=v-|wCgnD!21hs2$mnfJ@+QUm; zqpF2((GM$V;F+)xd2cQ%oW@WwF^e$b?dDNz`Q@_NF7%Yw5r3`~y0A z+IXkI9Q|kpJWIu%wkVO99x>>B9)$wfqoBw$)=cOHaOE~jh&^+hepT|f%c9DvmSs#R zaT5CCoOhYog3mv2=HBDtvg3;j3r}vdq%FE4RNgrMi`V#5Qc6bX$>>UtAi*>*`1Gkm zPg~rrkTEL)Ix$@~YBPJBIfc>YUjgSijGo%!X9@7z;h!J*gedTg*nsQ1{sHG>@NOs_ ziv!f{|BH$tBzy#p8z*q<_5gvIOJ@<5AysTdkws=ve5_mvHX7mQ*^&Z zR(BTjEBif*YJ5=#v`D9y1i(na3XLB|uJgVHJc7qK5 z0P#3vm<#17I&-(t%@FQQq{kA0N_$ZF0yRYwG`^W7o{o#x#d{`2s{K98&;*|ze%|i& zS!5OLy8D-!Y%-5R73D%RmTQOtGfzU4PVqS$*QB5glVGC6WZtA8F8;TDF=;tD7}3-0d?mU1Liq5{xM_W) zF@|BgB9QTJr@$MYXG^nHf_zoA*26#03#$uoX0qAQ@^jHTy+^Ja^ve+QSMcG3hwi}^ z3KbM(Ha)W%hMgnn=Sapz+5+G3SGUPk?dOaH%<@J`j^tjrZ+vu1a&yh#sC!DsW8NYw z#ax+}VXE_aif%%WxN|q|SO3A_tK_#W{DzwkSzQV5KO3gn_PYuN%$1R-%#^rRXQj7LH)N{)uK*z!R9Q0o#pc58B5GZ;^0`j4~x#Cde= z>|2;iu=7ydRN3{k^=MRVlmd+^Jr$|^WUcF4{1;fRboAH=tz{_LzcSBsYsl<$LTCp&l+BQLFncSNNsGlvWp}(QxkI3qvoFn)lMdmmdp7F(ZYu z(vnj>yg|PBwkocobFYSXUimJ)Qh6xs+M0V7-;%5(Qn3*vW?GX;!q+UwBJ<)|8n!^p;g`-bN1)wDFA!{o+ox9C zaPAj(4<2GVU8{BB138=~qIn~@6?ebH%ZU90`I1P4l6y!ijp}G! zL2&jY>Luq2))eA&SwX=cFc>veYnUaBJ)nI}`Zp)l5)ZKt)5!ll1wLo}dlu_1>2`MizM-7z$CFo7a2e zW{6WhUrMxVb$#5SPj%0Is=RiZhoQaf7)i5tSFvWUw1k?G-tc0H(;>N?(qaRtM73J> z=@%S2L(KBTPST|QNi)~^Cr#-Llm>*aLE*57X&%CC#`W{pd*7Zk_v4Rlm{)CU5gnOKX*PMhuJP9v3X?^e{d;tn4 zoKD_6Y2Eiv>t!e5V<+Lxn2w>;jefDffQ|m)eq?KzjAs6H*YBSn9MudvnEGRbYw|MN zJp1yqQ|1jMB;G7;2i!1EaU`UrktK{jFG~ux|1RQz7*6UtWGr9+z(NSNV@#>r>ihS3 z&XS*(WdPfMx1Il!4(iAMrvLvc@Bg!W(=@bimRXD6FW&^)b6no?NX_AJA6n=k#6X*{F-%DtX8!$CRroJz{OQFer+;3 z+3#0VrV*2?zyELPX+BE1kooOL-Cth~2pE}8B;l@XT^CXRK@wnBLa8XpfpTQHb{`Sf zeyg$Q_x5bvYv#*)DRM+|#oC=kp7Uvdp)x z4O*b0qC<_k?l#JEJ({|LnGV;n8@csu>KnNjsEdB_lm2;2pNsicvlGLr+30{7T%VyM{+ljZg%$=Rouv1r?%G z1nJ!R7wmK_^2Dq#;yT6b{Y`yBKQ%invT&<1r8j9s!%9)(*fxo&R$AymtJZO+l9X&)L zabMr#7e%?LG@pqIq&<^<+ssozJ+TwhZ6B4z_nbBzj=V3a)67heag z49k4^KvMW|5jHH`3;fX2tXyARiQ!5scaNZ`fg8PbotA96l~%sK(7rRkL`j&Co+iPP zG8v51(C(Zu55BzLouon|kr6=!yV~WZ3w$`~8}-K|QB688fiP=`xr%EmQ{TINCjaO;Lch12j~> zxwFQwckygOo~^7!C8(7Ub=WL;fXYYu&WjFEVRF>HVGN>r1u{xnK$PIL(55(uYV>QO1x;!^?c3zBtvP>_3MoBpcUY!!!1l1btYQLtw+aNdrGcX8(7grfB zTmZqwvKFRL%WXCe_8=GmT8<2A>*dWT$pyimK(H`W%PCfDOH!HVaOiNE)(`<&+www##1%8Rshv>4(46cc_T`9c$!>RB z4m0@TRO>q0>e~2yu+Qs~mkomFl!j6eyQzV+4C}?ga48wq!CG1?@FMbSE;4~37axAV zZcr~67_#KKG^<0-0>Ek^y*}l+i=Lgm95>l2)kvDc&Svt1GzkQNUU%4r=*dZkQO(>h`C4L-8id}?))qcJ|8+LbEw-b5|#4tV~#!3YkisIVCNo7tE6COtfiF*fkmoj zPBTAGYVeAUu>PZN71lwgY`XL+JZbXwtZ%q1dolc|aFr6b#VhDidohCe3J(H=!`;V$ zFdmP^+h*62C~7tO;e^xNoi_lKrOWnp+fe>*pyq*Eh7EE|7V973yNlZFDXU!Hvhp@s zniXO}DEg!`Yh6q!am}iVy+f72BSNI}BGdC7Tl25m%&Eim2>B=eNxUsVfwxy<8RHIJ zV-tE3*E8a(eip7^lucZOmS)5^(_u$1)YmU>8%JekxRU?m+(kF7^o(bw@HcKaXk1*7 z?Uajd(Y!WOl(Ww)(JpN&@l4vO=TWkRJYSmCz@usQ`OI&Qd@!Y@)B55wj(K)x-hD?1 z(KT`BRH^QNX=g}iP~&#cCgfZE#EH0ywKrltZ+82_0eQOaRleX-5jju!@zB(<` zHl*KoAJ4F_^OHw>X(g=eW17_>kG&_6gT55xS|S^O9G^dq&=f-s8+|GAvX3K9m+ZIZ zu8P|rCEQnf9O68j?NWZ;okOQp9JVHOuH!8rcTTToy(`eCC`WA4OD~(d_~5|>wW*9M z3Ixq^&(MUZRBFRgS%N5tHdXlySkan3*<;gvZ_JKTSYkgGjJ>5TO3ToU>UNGVoM>Rk znf`DQ=|#W-U&LN~ZCs_7Hy(vS@yq)r3N7u$R*K)3-ncd?iNLuP#jN=nB2sIyB1;zO z-E~3DS-fZguXdly_{`I>Rp=4!XIJK5k`J8HcO>-)e-W?CGm2|F_e6Y>jY=ICBZTiJ z8C%6dnH%=tWz>4=cL_Huo(Hbvg_FMY%T;UH;qox)S7(;Uy*M{s5sJsdbcvbT-k*XQ zRh>ES#q%_|8TYM*r{C>zsaJf|7q|C#Wp3}Y*m*B{6FJN(t0);ru96LOy@XspX^J7o zquFm@c@J=Ob-e`3d!n$}>?}(r0fBq<_OD{ya;~QjIj6)jnZGPOXc4KTax}_ za-aA!&OK~zmX*!IzCqHF8I5c*#uHcPZpY3gCTEFIr-t+AM&+8j3lehs(#+@l6!dos zYa*P)5lgCzJL zoq~nN`);8Tc_jfDG2bdR6fnc^o5c5hJJT0D*5!SdkFFW)XlQO~kY75fr-5ZIR%XAX z=IlF1M8_VPx+1ILcpp<@rF1*RNQ_1A);Q|wB(q{DKV5P8X%Cx;x_1U=?0GMNrt@M_ zD!Otm@&1x*;nU`KQL|XmQEa>6Vdp^JC%Jb?$VgnN^{9QZHpXycpV^^zO-H7N#BifZ z8}qwXN5-jl&G+BCjx>7Lw&Vg_kJMfnZfVY8DF&X;XaDrQ08U6(t}d+;-iz;QZmx*C z;Msg;tpxtbc-PBrMsP1C+E{<}E-@C<*U(!McEQ!&NQ|$!Olql_gCM;!pZcnR9eVO7 zQ(~78+<)1cBW@faDLNhZ;q)o;&~6JZt2W(c7(C#;NcX9Ji^_u%%xa0ik@&MVMr(hO zMY6Ni0&gEx4O%OU%70>r-NJrsDkB$rUScF&rTOmjut&u0tLmyhn#F47o|}w)2fy{0 zqzE1AEA5K*JGhoSUK(lr(yWlH5oJcp>-*W5WZu%}O~GU9`k$r>oqme>>o}CpOL0v+ zY%lT*#d3kQmO2{-6WInE2Ik$m8DT6l-ekb{}~+6!M#yFJZi-Sl#A2bum-p2z~vDDTHC)2Da~ zr_innQghumm<%av-5q4`qXuJc1?PLdz@sC21&f|iU7$}*<8!&;SUWh&mQW0@Rm9Ii z7goui!(|3(n3;|iks{P@TtndAu}K-D#7$)LNf8Gh&Cwf`;duSOxrnjcndaZYx~#D9 z5BgOf^s06rHG*3!dj-69%FOKqFUWGmM{^S|Y=78J(tb}U&RMp;+M*C-2v${%-8){C zwfaLL$hTu+BfRm#c|#wjZQg1>Q2{f13Gj4n4s@SOr$Ogp?Oyh3U4k%{@-1RR`E&GjK znvvW}=l5QmL9hdhHKmvyk*`aay0zr4mvR1A9dn1nv z1bewOx6JbImA3ZC{Cij6+twa_CzhpvhLD5omup{VU1#ENcZRBFq>1>KWn*@5{*f@4 zVYiL_ZWYO2fM7mZR&0vnC(@44cB1T+xo5Gv^XTJ(h|g24yt?pm7h;EUm$ui2g;;Aqivi_&upedghkaDLvfpEr3Hx+CLO)n-Ch zd+jUA?SfWJp5zxeW2|y8O~|Kfe%Z@Obv9%f|J5KAeTq3RtGRt|oE@FLTzy0~R=?=! zWHRBB2p2D1)ETvJ&I;_EGBScn@off@LbNQ-610A_<%5h&sCcd1ewyo?PPLzZ|8O4r z0>@P{mM31UIxoH&ZamEC7yUbn>#pgf!{;pRA3tNQ(XRF)U9h3eK`Bg7sFC{3;LwFM z8?=D^)Om61-_iukuDxVL%-(l~_baEzXwcb9DHTq0hcv~xdypAO)MS!M!Dl%uPq=5It5QVQbEk`n}!%RA5k0S z22xJ+&DIbi?;p`b6=0jY0}V@Z+NMW8bAG(F>`)s~cQ+`%t`%(m9;Fnu){`6OX(Fy( z`>30Jv^3UCrKh16IMN;Hs9Z!bJM#G7!*71!_gndUEQN`w!z(=-hOA%IOdmW_{{0mD z6)ZmBN=lXg`efcB_*T5np_3$K4R4$)XW@eU@}*zOq&yq@HRdiJl{()cGZZJ#mO?m? zu!16oc7$HDukQtosbq;gUvJNPa7Hy9-7`_T#vaM^E5Fn#)Uk4rz);k)$r+ARg3<0LThqa(W|A3B?HZuHa`+$slO|}X~sQXOdTaNa98}}6AQ{R>NDKq z1CRf$Ym$y@+$&(OevyD@g7oT`(c$M743;Nm1PZe-O{c~?DeUbm z;o26_9p+}PQ#j1gdLZpZxQ2}`iRZA2tArOvgYo^LNW!7~?|=qCV$0L9F^&MvsN$GrkRLH zKi-#TivX@Mg}N0}f-Ok8Mf77cdg-D?MX4O0?2WCc66|olp%s!X;c-8k$x&$pVFh-i zh|fcj4*y`zoX)MSL0u7fkBP?ZYQx#vp0^ljGkvE$9{lhRxTX0kxcs8lddwJ>)6Ei2 zLX&1v^37f*kIk~3AFugW-mH3?o?`W5L#LaSE=q5{^VQU<+hUZIX*Lr{ueCDMv1$)l zu)VkQ?Ge;*jy7tF8vCU7ds zsNtgIY5&!C&Y>P0x1P+bO+HTO-|9a)SlAq2+Nd6+>f|PLXdJ$9Q2+AZ*b&{yjqeU0J_mV^l zf=JPOjbQX%Mo19RB_wJ>5J?abW^^J9K}08J7;O-}8})Z4`F@}0eV?~IYyH>yuQea% z+S&E(8hSeA=*t1ZH zMcnBL*_^B*)|>C5wtSy{?&IAY^49HDp3X#e+039)2h~X*J!YxaGR+<$*oZhSQjqbY zCGd=1(9rSWyi|Yr+ha2K=ppx%pX`4n$7`geW$fqcLspkw-x~h1c3@Q>p>VQ#x(5i@rWlU)ZHiF*f`l-3K0F9|f{V+l0Q3F5dSrjLIWOKFMQN@*QiFmtb+ z`H&u!*WV%Ihq?WP2XP&D?U%^P*{>XG>$9lo>9b7eeC($9a2@iKY)h><+*_=Ai`MUZ z?{lVaRX(}28ZSQ%Q9Kw7Baifzdz(Zs3b{odWb9pH5CH}OUIr2E1*-^nt&$A0MlUCM zka-PjoC9F~U(+FB>$}3%e^|+_Px*8s8TFsxjn?cZD13P?B7#Jno`i9A9bJnoV%Vd$ z?ByUbePBz~S`Agfm)(!8RqHwNCU#$=@`WB3BRR-T2Q+8^IRA|l-*gCYarpQ6{}=Dy z)u#z+16p^6@tm4!KEz)x_-=DrHK;jT@U*6_H1QsV-}|~x3x+OMenqbXW=mHq1Y#kO z^mX%ZoTbdp4vo{joL3@yIbA7rd~aCeXR8mereRVV2xMd5DDd=hg0T@?L6$lg8^IMw z$AYmD1s*78?A$1cOD=z789dI>=EjFsHh~0w4Y97DiYjUUvEeN{HZsCFB7AefoQ?gL3K9k=My-_$Kqu@W7<*v0&IUjIOjvLG8tg z$lmAo%Qbv??LXFD?0qiq_aShT<6LKl*x0y!UF=Ao`j%2?A!F~J-3={wHS?u%9er}I zw)xGWZ1WQ-G^Y%bYKWPt)cC0KFs8+dMxNQL1aIF-1CMac*I$8<-Fc(sA!$1^g1JYt zo%-=@KO%M)ukMEku2r^Z{=x@xHnIe)3!x~w>qJ2rjVggxGA;!Ytk4_LsBq9rc<_k| zGMHuHnV4nZXTPtG>K!)M55+tvv-Pbu{#a`+G-g>w?_NG~Ue?5o_^21VSO|Dk68ApP=u78TXM?pskJw*o5@r{H4jFYWI-y$a#W@^ErOM zk_h&Ta`_3@h$-kF#twW3-jq>8Pg*2kCPgj4y#tIW&^4N-Oa1g7h3Cq}rH7uK$bRUT zSU*EmkD2TBUh)`Ol-Y;bCPwHw~>4CaGwGR1w^KL^ZqYQqz zt_oqf?gcEp1uh@;5+qn?1x6oV{qao!_f)_osHJ~5A?&wz3eJ~h z1@xYP3kz5x@Y~M?^v7_HDrNSYI4_pKc#%e&`^qR-i4zxpjg}s)ASiI&EU@3y!g<0R z0{=PS8-qK+fQJ6J_sgI2wznfj{^3KTjV>5ETN-YL*i4n=)>GHF1jUhE``xA%l8$&zGBkB}XiDNaNPB zt!y=nF}9b(_x-V!*Z&MY*7}(Yhva$K=U92Hh2sXN>( z;uzBRI^MH)(^Kf@Lp&A3QzChOi(BDyBQFT3_$FgHAxDqs*RLUW*}&WxMtg@777zJacdvK#a#3n+5^DRNkJ1fS$8wk1*MblY zWxDpnC$WNXn$26pa`vcqlO1Iih_zWRn8f~&Ak2I7htQ1Ot*>pb;$p$XD)^+L5ceK% z?|DD}`8KFimxZ3n%r$*>y5G0yogQf-LK5auyIXb)Z8}>!oj$c#$=@s#=PD>35ap-O z+Kr3bi$T-%gy>Mw6N%6>k!4Hz&OP{QCdZcXK zI%^DjXhGskF<#DtVg4xNIKhuO2a==5mp+}0uEIP|Ntd9#S1g;xXN}L6zgTuiL6Jvm zLs-V`%7`qyde%?_^JyeXc-Qp&Ao;i(!OQN5Q(U+ED0d6v^LYHwmT0e5kCAw<_DcfZ zMBEs$JGXt=%Mt77DrfVNn{HG!|8qhL$}Ws$xtd9psr*SOf{X~Dbw?P6q&N?Q)u3NB z#EO;c-SR)Yd>Dg{Kwt9x8{(KS`cXvGdcl(Sc-6_el?|&CqWskkoF}`f{@TZ9U}I|6 z>{LR8u%sk9crYz-cW~B6Dg`fcdp3=QdfLUi11vL&_42wyGpRS|l69lUGF~)rr=Z1( zneAreLP^%_-TWFcdj;<+7>X|jx0nyS+!l;OR%VJQE`kY$g;5xgiLa`wjr3V7@oYrPfmmoXeHl07;ceW*oJ5MPY* zBlxc0YW)6{nY6vomF&1DQ~F$7Li}s`cYHKBN46j5Y8;6Sl#)X+6n~uA*hyMnB(#9l zbg9sa8|jg<1`o*CvHS63b9*m(JfvjfrJwVH&Ba~2^vG-Gig?9{KmIxF1~UrQ=34`4 znP5ht;WMtNBJwv+&)OQ_V#_DJp&=A|xGS>eFyP0(UQ^p$DObX+P3iRrm38r6<+p7$d|fvz?Yft z11<~PoX;)evJu4YI62=3&|Uv0#q;s5NyYl)aoqFWkz8cC;C(pJlfG|tPfKJ?4iEPF zr)q;U+P6a77ncg$$&wWRVO;Es*$sX1}K-$e6@==gQ8RMI>t7yj&}qQ3If zSo5{|nbJa|WX#AZAKhv=Ie z%PM}6zWwe!6Xh9C26c>ZhEdc|PJ@K%ze`Ag@WMg( zDs{x!ulghKLY;ng75XdYPW|DitKYugVD9_}oy84)F{mZ<U1)m!UJ|kU59EV1@65Jd z$jYL!?jL%z5ml`9$V6I(r{PuUm1#gZ2Pn4yrSQuI^DO$NJLQ5|1LfzlE+I_%hpsjy zVEAGfrRAg=UKPEbUi|fh_Be74p}+r~mb7$f@}(ZgSw5%>#M~Zil*-In%dH*qTkk0< z4s{WgK`HtEkCZ3f2K#yNm4A!-Z>akR#hVRW_V*v$wXvoT>h}HIgPEIa!w)w1@=Y-Q zYTrMuS8cv0ug^(b$E*a@D+KuJo;AsMU&c!4n4D_}G1M}nmt*kqCEIKI44KV2S2Yp& z4b_|si6#eL?A!Zum~#A9tJ8Rwa_@Kf7g*(o`;1uz=oYc zKsqTHicTtt1EW*mTIeh(`xgZY7uBdMcMtM39Z2d^`g} z@SNKi_?m_{YHk6BV%seqcrbrtY!D!`^tUBpJ$P#hj&TE-=5F1QN)Zbp)ivbsf4JHj zySY`@gnk_UXVie?(Hj$@pjF!Rzb$RQqS!C(YI~y5>_WLarvK;eqEJ%HQNB zhwqe}N*}emNI6JxOhBOODzd@dnTkK3vyy$w<69E{UPS-ZWvD`3kvz;OQ>LT}&f96_)=(d(wmWP zY~qCFk6VaLFEVlh(EP9IV3xr}Mk7NiBTEfi9m_`m|4f$$T&xcFZ2y-8z5iKn>Zu$U zlnqOM)Q+JOwORER5)QCqPnGB<`G;Hj>VusQ1&VIbdjpvc>b^dsTArVMy@T8C71Wf% zbKd28guAA-L@qc@f6kq^MxzG zNP*55uAtW?h}d1VZAI#MPIwv0VL)1+zFc!SHKa9^82}x`*EyT`sCLC6q-5`Dro+jp z@-LnI`~?TA2MTaS2JbuRUvGH3y|;;Csq%j^-BDmdjja4C(aQGJ(z|DO*J=Ajz49hm zxe)yjk(^HDL*OI&l}PSNW$H{!t#3sM{PmC%EmBr)%?Yk!@p?v1zuX%*0LOPq+uI;A3J$6zh0$9_BJ!&20}e?~ zW0xdGA?x9B%UJ&l+YxT?ZQwgfDFR5$h<5cGM~QV6u?93$jrORJ_Bvb57*tE$O)lB>Ke2G;hImu3&O!{g}}iQSzk!8p$8`5^wn$>ob6k5WG!_x z*I3MLV)dMj;~HJ-IMXIOvbE0UlWHe(n%31zr=tBuuzSB0{mOg#FT;}G#}oxD2P_(L8**{KeTY4w zsJC&ksmZa@q*0+i#T+h^mCrWM4A7CSxz$uWA&auurY3@6ILRRT>eNV{u3MWEnWg&V za!#D^?Ny&vt~UMK0*q8T=Ze;-!b7}nZ%$Bwt^2@-YW!FI*ye#GRHOsF3ICyS~5yLPRX#g=O&TN%qxw5aT)+pr z@_wKOG9#I^e>Dzng_Y%nr;XD9r&{hAU2ARNRGSnhWX48g;-kn_KIf-l*|jL(^RVA& zjsUDP(^UlocR(0t1q1~^@BxImICvUZZN>{61$Eg0K^Uh2N00{uFF-&8LMtEuS3%uV zE#TOj7%B9V1>eL^4iF%KfCL1vIwO2<)z~Tw-?OXgv!zYJ&Kcx6` zE~e!X_JJtDx?h!}a|jR(`pg?I64~kCiw;Ec!FZigYw=e*B4zqV=pQHGGagY9i>65v zitcfoXWeSd#)m2FUwdewDp)7VuO{Fnr(~vh9=Y&=o;WYinpVIor0g6kJjj#DtEblH zJgbX1EXcti&Ik=c?=%?+Pdbv?GK!7kTh6sWNba!kVDUTOz97eUzssYJ$4sBj9hn%v zLWX9j@C4CxgyrdiPV>A}h}Ww4L1cFhx}>M^oY|iQHd3t2$l-7=fsNxH-=V@%4*KM? zh{@oj5NQhifNe>%T?9tqSHHBp=3SmqLPq*%6JhHbm0M5c9=Z3Fv@9v*g-GioieY>t z$SorYzxcN|zLQD{hWwfIEy=vT56V~TKFGVlxU%2)16XEEb9Dd%E zSfrUhY5BM(fpW7Ap2-p=a!q)MNx6BP&;sOFkF|g2^EW9iY0*UT&m+G%7qP*eTh4h2 z-(w~RE-HqfhSfJFO{iM2*;x~pqbk{>txio#T9T6EkM(;+@@&fx=vxo`nY_?2zpasU zqtvF-+P60_A(Db=^^sO*j9`q%`e!f_C4yb970Er`b-$~jc{c%s8Nt52K^f|^ znbw|X(J*_c`s7n^R;3p-O6Ib18z&JHX= z8?Gu(sk)zy4JKn85KC2}@TIX3d)4q#VMN|wtDV1>DJ7(SwG}FO)WE93Pl|SZHg!CA zG_k%0)o89!sh%xGLCqK_vgVr1BrAiZ=`}=t1pKj! zOpd6@s|k$vjANkRw#_d?)cgyDWGVNvf%G%a-ORP-*5<~1DqexyBp&jn==SjuMg5p8g5;D z#~oFgcpWW^I`+*`y z^U2x1+^u>8_6_B9^5D`1?0DNMecig~=mYKb4Dk!A^ADQA6zZWFc8wtkW!cl$r2EBM zV(BJn+kF921Z%np;Xze}>UUC?t_^cMvAK}%yS72!XMHZc_odu&?FmnleW%D(A}Nrj z%%%+S4UJPSuA$B2N*3KGE9g|^PZ#(!ni3tuDm`bc4w0ENP+yatv!-DgY@L-oBI=69 z2&e%8CqSqg@ zZ>#u1ZQ-o~__(Nor)5WB;Wk;)$|VXj+CBr?zFO9(`tRR`%Bu#y;y$zaSC(w^K0I+L zdE$alyED*w?2o~TfNB?A#TWc;d#?spu2lpV2lYy|gM-ok?O@8SvoYqwc(ipDX(L8q zQKs)&AJn2K+STWWGHEnMfk`@4{QjQpUk6d(t{r=Q#W(s|sZ@_Pr}yUH3klxx{Z;d& zz2K+5eJ@W(qX44ZA3dceWSl!(sd_=lUeNwiDo?EwZ!o=?3-&pOSYASI9gnZNPM8b= z`3jvuAc+YBtLM5Ilw&67A@Uf8Hhy2Wkaq0%BC<&}#i@Y46F4jD{=1a0i$c+?CSli2TFCwTr7pQw= zXo*pL6H#>cmH{R{0)#=AyLVoO4wet62y6;pqBXRPRcKw-{uS08O6=Wq$K<1(k1_Q^ zc5h|g41=$5+bTxI&}wRIe(xQTT*i5^7^Q{J$gAE9{@LZsts-pv%#bYYt5#D?zWE+8 zO3f6q4`-4TzB8>Ii;mq|$gbxw8nsiD{az~)wd~VM(&j%ue%(uNSGX;AihyM;th<|} zEq6Vgg1)(M#>qiZ)_|QQ#^T*DGo&Og_U>qVyLx_pHaX01-vO>3K`DV8KqXIuFfq@3 zbZ44WM@|BEtkdpp4K3}(S=4dJBv08pI(|5PIv`9L zKC|Np4_~?tZWbmHqcpcK5Mxo7D1m%2RmcSCVYiCGt^b;vpT@g+EW=ec6to#Yb&+sQ_dvKe7Dz=V)a!!IL?Pb8^d?EDBELvOPs&8L+l-L{0cr#M!ZY7zc4sH zoTzf-r&z<$?KA2!G|%Cgd~%E_8w7ODO0Jkm?FT5i3?Z`gh4xS>0C4V@x%O~C6`WId9@Fob37p%SrtxhP9m zZ_wdqq^21}IPv>S+N7rYMnv-WTdv_lWYEU=Yd*w6#A|fu+xK-JhF;s(KwtB{LekC* z7R>|ySrX+fv;=B*-mPJrqgLMb4LsU@wL@}t_g#&0uEsBWRn#PVxI-L2zMnFd=Uqym zt@{gunP?Y7JEf76bjK#va>g8%da2+H(b)7iZba ze{4EOSV3jm0qZ zTlv`?|B=pKkOh-v>b0#j=$+sZFBYE6j;_^Wn60Y@6H$pUSM~N+W;^N?-;h{*J^cz! z`3)mZgLBbn;D0*sLYz!=J%!vfi1ssVx)m0e+jp7jx~Sv?Te% zqEtI-;a+leTUTc$B0cpsYST-XNLmMm#A(QjW4dg`WdWrUN1*@|2%tpcD6D`oCr*^X z7Yno~0!lxQLJ24VfYOGefD!Y79Y86@QB(nC6Gx#UwB_%mQn%%&pa$efK&JglZJKo% zkjW&7GPL3VSsjp>?Wu(+XaFS+Q10L;T!6v^C>=P8HlQfrC>H@G1yItz;+f{~#I(!^ z;Iupe6g@yO!%=7fl1mh@lfbt4wOFN(l0Ll%VmUuw9Lmt`w z(wp=DD`#izR{mjCu7J81X#_{|Kdq8w*EN!;f-ED+TK!j4txL4Xz^tHME;A?mVPdSm z{UdbEN?qAD7ZJ>1e^XK9x>qPJmR!&adM-qJTM8mZ5{b1q+?e>xK+k_f*P7d0#4>Zj zS)_5>qgO(%NQ0H0O0-wMa7NDQcQz51<<)@u>p5#cP`6dT(oErBVN1gxXuuFf>=l+T z9qQj=yf)E_f5)rK*kh?qMx`vANh1H_7|IozFJ;-D2mX4&)DVtPP?^t2re|71RoQPd zJbH?IJKfNshM>aUo5GT&5KXiD-ntJ{{_8B}6e0qQgy}-PHmQMo=w( zDr#X=WL^~>&PvdneCHP^`2C8i$~@a&%RV|&o;uy#dwN7F&Fg$Py85_U2$8jBjx?xc zoyc%7d7fI&`PHV_A$DNEQ+}@az7Ja)#qP3({8R{i^D&%N2_oc$58Kt`t^d~kGVP?2 z_m1R=tYNPD34zL~#~sZ#*@b5>vSaM6n~e2pXXqghCg4VLG_dZ`gz13xDjlz*55khj zpEapyN;5M@xO(NpMdXX;nlUU-Nwd*OX0Fa~2k%XG-$D7C5Y!zBujB#^XPNnRov-Sn<;lqM@*n6>M=PmOFrw55R)MVcYF za|4dUU2sxsFpS8>uB#P24W32;W{MaP%g$Ko95pg^3L#T?%_|cq69MAogP^y#1nd7E zM>+_%lmb_spMC8t&4g<{Syw{9aO7`2$ExMO^=yiRMu+39-Sd9=xpFCBPvuciF0ddE zJb}Oh5?S^UVEx3W<(lunkR%jh8C+|X{=fc9K?zr~1Ed$Qc!5d4{At`h;>@xDdSQ;h z1YBWSzbzbR^WOw8?m7a#wtpA@$7k*DTk}6wwZ>J|_U1=WRS@)_s>-l|;VuNeuVOe0 zg=Sux{GKSk2EO%`5b)t{PR>l|koaBexJm_0AlwNmf9e)^mi|6(3#T**zMRmpEk|V{ zC|##5)l-8_m~CiFD>U`@T!A4}$ANpCIz*tVgBjvV+vgSD6;2+D17rwJwu}J_?;bX0~a6q z;(iLpg&1Pgd?M!}ESM9aE^w#m)nbtlDt21GoF zv5_;5aLRC__<|!Ij{BSD7vwRb z<}DI|{RCiKde#n?fZuG8fN|Q*0%B_1kDw+{3x3R>0=1#-b-OsH_V5N^mmG+Z3BDx1 zLu9rU5VQI+ibSFn!Q%rix*Mh}3=)bz33!cIe8!8K*gOitsjdLuI2tP8i9w>NtkGVl z*XmObP0k9rre2n9)1IAzkv)HhQ7p|o!PI!Q`$mGzVP|v&cvGr z5vdW1a0Q;eYicj)$b144{OA-OpEz3Bbq*J{rwk(NW4QT8J3CVse&h>llPh4gxU>zT z<4BT_8SzXpNX%{Jc;xdekejzxj<! zAT*ArzYac3G{h|gI&7SR^vV5AEc?xTybR25_LxjAX6o$63%+FDvS;0e9V zQ(}^r!5ymUu2B(}C~fyNA(4r$GF8hxRfx%=_dH*wD2&trJM^lvkxw>6-<>>bj7hqZ zMn;H9Mo3;TAW#tI4yV5vU4y)udZ*Q?t;{y-^E^B^O;?l!LaZ&;FnY}=B!X%Wv@kgF# zWArPFD68ALLu;bZu(7d4nM#TK_70{^q{&^?Bw3sYq{d^eQNjB$%A!-zv2!^V_LHdt zt=#)fMpb$}O1Bk*<|gHIJ)CWE(w*~l<`lgtZCffqHzD+u)8?A)bHcQYEaih=wJOY7 zt*fG{1+zG*x*1O-6du@fKd^Ve*&IhPC1CtRE}nkJpt8R4&dOSj?~HvLsNuN}w6G{u z0sA%>C@XU&R%&0{%e4<&K+-a^fa)drUA=Kx^a)w?tn~F0$?+(*OPcPFv}jlqF0{96 zdBu;BSyx823K@$NwXacLtE~4Gjkjq1&>>a1*~%!U8n(5hZQD7r!!LUFF;Sj(-oOLu zqnewv%%1z5xPiuBOgnIQ&H{V?)vw~h%+C`g99HT6G!`QO3;{G2#sC=rBLED6;20nS zU?dQqg{&cxg3kJD1}}gNfF{5_04D%{fX4vO0g3>s0onnE0p>Wz%vuV+Y^> zxD3Dvzy-h!zyrVwzz4t&AOLU$KoCF(Ko~#-KomfX#Qic8q3o>$P@MoH01SzsdI2&3 zMgSO+z%f7uzz6_CGB^gv02l#aNCC$H82}?G_$+aqkra0wLG=Up13U(J4p0P84bToS z?3jAe$_P7ypDe3DynZB>KqkQ)mXLdO(?Y$wKujO#GVw&S`W-#%W6QQA6!Q)b&|5y^!q4}s#*&COe}`e2l(!h#L3z%=tRV1a=r zoD>PBphuMJ9m@`a4xUT*VfHpd#-7Raor=iyIV1e#2-V8#pKuH~RA+Z44?{YrmL!&Y zJCn@CB(sXP;!e!CJI(;dZFfa>Fvktv zm_om$$QQfdRzC&Hvi;Th`t|#$9`Z*C3h^gRjQyjmL!C`lQ?{>ov}|^NQ_?-&El(c- z+!$j)L++nmjNsMSRt(2oQTRWlD|I5jk3kzMM&BEl8e|%y&nDYFK6lpO@!L? z&cR+Cgaah!&fuMH(I_RTpF!CtvbCIyyh{Nz$en(L+eii8Rrs8 zWRR{c31rqhH?B|2+pX=TmytX@@)sHRpRWodhu!(A4xU8N=C7V-Z!H5Sf~S!h3>5wz zWqj?7C0k1a3c#}nPR5PE;Vy=2$N=WV)^ZK*Du}7kOd$QMS>=djS_3Ol(|{$QdCl96 z@Y0Up7zO24pTa-`AIk)qRzNQkXj+wl1Q&+97nli}RygBx!Snp*Aptj}v~dK-Q9z># zwD?mKWA9}oGZ{64YnJ0WyWoygSg4k92DvMLr~=xZMm=(YwZPSN6ldS>*1r1Rm4GwF z4cr8{gSIlWCeRDnqCx)0Y60W2pc+ARL{Kf@#v$FHn}yTHL4~__5WffnXgB`5@Gcld z{bLr+aBet`f@|&p1>hTN3hq^I19Td2YAPmvs{tL2f7H@{UapI)-1Qe0;0^-2w!q-S zpX>hhPXpgn+KS)m%hG$ufUOU z=AV5j2X<%8vPLmLs%{2@J?@gyHxwaV=%*iS%^rkW+q}Qc{Pw+CwdL#iPs(ByY7;Z6 zJ*dnLn^}Y4KL5otZLCXorCeWk{XkQJl)K>!COG`u1ijz&Pj{E8x^9=M@#sB2O%bL) zRR45$0SI0K!9AP+3k0)3@B|3xae@ONm;!=eHLj<_Cvn0I`#>-O1g;l0c5a{4^-~>BB&<6wxKrnm^1lvH+4Fp%zxSl>g21>Vp009KdI2|~~CJ?j% z!8x1`oM5ASZeC=iR}LEL-#Yg83&pq=eR-GcJ1_kjqsMNa5(RJ0+5f6EdMx|y7SF`n zFWQbQ_uzaWBlE93%XE*s(^>9?=SOiAE~S5iS6lm8qrA3s`y_iEvTl7gyEgnjQ$TGv zr$MdOs$@y$t6r9e{Nw4N8Zivlifmq#4K_8em(+0TooejN97DXA^9Ck14BI74a#Z@X zWp;ni9A%Y!5>AsORuOY*^t`@DpTtg0yZg3GQ{egBQIdE3Q&XoqC#zJl{YLf^8VHpM zKE<_h*?#Z7nkPx2HTr(YDvyHMJQ24!+5Ub$#qu%0bNruq9<*%x?q)WyCrM#BV;TrH zpzZvMO}7R@(>P)q<7o=X7mS1zY`vrMl=nZ~;xJl@*jmarhAu3vCaX1uT|K!Oo6ceo zQDU83bPLA10TxQTUNL`ReOiNn82oZQ4D0?BbWm5Cse9iwOhKN_D)z?tGVQ>{+G14t zB4=+Z>y@2b4|L@HJQ(|4=}DZ6-K#aux!#xmIFm|+lFjD`?>w7szR7v3qYkM>+0jeh zi$4|ft_9YP#i{RSIj!95mY*{wpi{ge!~G;Fi|oleGG-Z?wDa}ml)2lNkdnopN$L|S zcPL7J7*zEaGIG7qzAvV6gS7uz9CaM!^+&dTLc-h{urHGKe*Er!achqfllmK}IjK<> zXrlT{@6<2+h^FRbVw34+0@pdu!d9SdSE%my-PwyKEwpBz=jRnJo_WbJvaZ^MB=yi< z$>O^twf%SaqEU+q>8+YK3>;Hv(rB42AHAW>^Lw=O$6B)WFlv?ivLWB?Q)q5~y-jJQ zy(h7lnw*l=W}8tdy)&0lSuFk{(OQxTS@_CX{DqV7IdakKx&+Z7bkB~7898~O*F1L8 znqFmA7RrV6THj)6bQbF*Te?Rhd7sPimgbE&av=|PN=-XbCl^ac`HuwNzPuoM-LmjW zN^NkPa(Vo<`thBPyz0JPG@WAjkMvQ+A`#`_k?p|Q9oj2?*>1g8c7(r351l9$omZ5- zUL4KMHhQP{mBTvcU~6jAw*Hf-q{i5rq}n0fH-rC~b&X02rvuW%?+b$&(=$K&EMgkB z^>qjofdVYqOCKV?M_?A0MzV-((J6=0SlB_XuvYt_p?Y+uQvSLO&A@vu#~&J|i@P z7W$BU^6rhnys#?NTyLG&x?jsYvIzQTy;JNF&cqANU3MbenUOgXU}Wa>W5^ zbqcb6<^$c8TM5138KJ%;(ty>of#x;G`n;cXbCF@I&ly75tZ$T6EsF+rpvtO@5tgEN zLu+B>CiNf+$&{F==@0r(S{>^VHoM%-`tP|nUS#WWM5l+$!6q-zSQcBe(l0rAT?%c@ z@y1fBzS9-5MeKBR*_z~Wk;{85M_;caH<&nlrFI>^Z{qN6i8@K9juag{w{^?P?E*xv zm6qBLe}$Fj@yIAcDw{+i(1`(WMOy^0QVu#!^}k z%$Bn36R$diaA%#~R<%9UtB*f6R1K*))$@cjgK5Ox)#VA3u_dM!n{HlNy9Z&p-xl_1 zRlX;mF$oMbYYcYPYoAGuvrgR8j>1MV`er^XrQbh|emBlhzi%CJyXs?o+7YVKu*n87 zU$S4ZZqpdNOLFq4`*9ZE2Y2X~7m%ZAxAj4MT$}Z5sAOAP%csYHad>o7Xs|E5!AcdZ z0+`Sj>yD6lN9>j9x`jY0a!%49?H&;Hf0YS@GOJnHv`=2j;Ac!`_|b- zP1a*A{4#S+8#yZ8QDP%^U_TMiWvcw}O;i6)?Ku7nD(kzk&f~Ysf;P6K)}UeV#({x1 zzG;gew@eKSpF8^RY^$k?k<9yKf1!FGw!uTTa>)|BgZYoQ_bPzvU6i4@JGZcw~o>gY0Dw$BT5xKG?lz+ zN$lBKZ#ReMbXBl&t$;FdMv1MeZKF=6+HSwea?vJk^)C+@V?FoC^su6}%3_j^2g6f`?W@_O8)Vs;p72LAdpp}M z3&LQdohH{CBJ<6Ha$PCOB5d<^Hm_tC9*l%P#0z8!l=Cm`8VE6KhKCZai41D`6mIB^ zMq$FPS`YQwynH+lX?)w=K9zTp&j5C~wyYK#soP@Qr-If(i7(tj4!vGFwD4ltw%C|A zJv*T4MFeC!w9cQQ><_0X9LJJGv8e6m3sYQqi-{ZuL@5t>F>(w&+<6 z;re^tl9B4gfZg_V`^9|@S<>-zu{>q5hzRJ5^)56Pe~{JD@O;o*tAh=M2qhuUEMGFe zMA@>N1`WpQ9%?)8p1=({u{xX)~BDI$H@~!puLoF`;YpK zc`>WWy7Gp$=Y-Zh2uRInrVU-XyU+dh`P|(@-yQ@pUJBO&D>e=VX!0YTPPt~*~gM|}E zf9ajk`-pOFkt@KomUTXL!=z(YbmLRFN;>WnYVK)P7j<&NEFC&uOIsFpiZn-!V_M5? zGbhTxSfjK>VP_+kY{)%#^7t{PyOlKbLQMCBg;;yGBG(l?3V6tWbeDX^T0@H zS#~k|$9rq*uv_OtsH9sLU}{JkmdRt55dOo%y(1+7IjeFgqZ7Zy$t7U2!_0EBYWPkp zJLD{QepfYU$s2x{v8kTd20v0ho~x?vIo;hEJ6YOW-|!tXoQfQM!y?xRt;RZqZl@mX zuC%*ya2(0we^QVQGzfK<5;|{=g4mo@{?z(15_~!8j$?^1IbohUq|W2W;iFKk0!a>% z4Qxtg_Bz()4PjgF>QuR@bauoPbhn6Js(1UPPvLJ$Fl$+7LxDr4||+?Jg-Lg*Mdoyr;Xsf~j1)$! z-7Yhf3KB+RsB?Y^5By|1sdLS9RD&H{j<8zxCCG!jdkCPeGI_Z^>5QB};>8lch>@(( z^_BtENwQ?345FAzeG+O#Uzogp-O_#RoGmC}zIL0uwuqO|K!QWTYf1lG~SFktKz13=oOh-f0#7&Udt0(V1i897Y_o23G($T=VH2i)2+76;1QLXV~MY4c- z%{06|xeq$q_ATv*mdHDwOq<-+S{{N`tRTXUO_th4wB0S>7pGV)fqoGhYJ~0-v;MX% zjVxl)irBPY`q2^T(6-+2M#Y2SQWRTrkWL7f+>M=Dt;hJWE950OHI_C*-nb(dSc{4m-L#T5|*F1 zGHs+3Ig;SEnyX6di3IN83D`T+)Rr1t4>omOE;&a(Ymy$y5Dj;gRik(G42C+33>8V}9)R@)ve>CdFR5}fp5>Rv~{bUJ1Jd#bR1E`g&{0%{^5T1MZb4=_fE!5-R9vt z&84-93pJ9L2{MCY>ENHQT5=?`NGQb$c-@WE?qyC^9xHLa$W3fOrFLx>y1wV)!#NBlM7EP5oM0tka7|H?o?rfnB_rLV|ykloIpHt6%qJEFAgZ|@ke z(<5@XR=T$wZRxh+Aq(F`{Q^F_UQ-^(bW6Z} zdCLqUl}v7`6O9R#doN(!kdMQb-?R*GYDVJzi6YHGRwbql<#&Xw!DbC0xSVR=RXN= z2xK}%Enog>7di3zDmTezQa8~Hk!`Q$-J;rn@S(PqIxQiwJYFSqjVQ3#cLoXpU6qTTz5r1p(YKAiH)EJwYUo%vNU*mwA|F5Bw9Po@l)Iz0RiEo5m>6CWm@ z2UCPU_Z@ufJJ{YzK?(8ln$6PVMs_Y|90r4k5*1G#71O}xB4#zdN1xjU~)QWszTSPgoi{xpdr?X zM<_!^db{F@SCs?k`pT?)m@VXo;ZH^_tLE|Wf#RcPuLGS>Gi&Q3EGAcQ%_ec0u;epk zQ1EF>eQ-p+=VZ936WCa9uEy{v9vEf=D$+p_PDUPg4ySNiO$&;9czucOT6{8b2lW z&bF~is;y8BJDxU7KEuu$j#$D4{av<8O#MJ}I9K5_HsHb{s{WwL+jq1(OYcY~ zpi%CDRKeE%Dw*CHys12Qq!#6UChR#+){TNI_;zF^WV6WoDS52~`d{4m$(l_AFG;4B z-${|f+pm!(*x#YS?_1toAX8Sdo}Cl0zRB7^+4!EUp%`JbiRo4>qJP+Sculhf)vJy^ z4NZs~%({3T{q)1y0Tc71}@s zcSK)4WUJVeER$k@=|s>X*JBzjlUiq@Eb)S@wV6Dn0vX^($%{pcr`*9;l-D78`yA(j zyu*&gR^60BXK*U!?yr!9sqr0BHPU|+Wxs2fH}ig?=vLdy2nIMx!284=zoqbH1RtC& zkb+D(Ysn>Q_E0H4vLf^D%00WNlG9SWmQv`|n4{_=-3l7R&u6iP`!_f4@8l7)Cr(PW z7WRiSm~!P23DX$jWq>uOdSADhK7jm496w&*a&kj(1x??kz?=%)lbUF4`T@b(2nWHw zmkfU3GS$O{>L8+=LqlN#h?1u=eF)f9ab~yMm<+zIOtcnQM(wrvwt$?n$Q=F4NRy3~ zjV+3IMkk)1#_;1co*4xxFDBNu&n-0XuXE*HrB|7Ga+j0F@YVSzL1{BOU(@NurbSTP zdG%_21TM*fpVa9K<4Vr4YbuLu2+X)fY10^9P>v7ELK}S@#G~TQV+dl}{M=Ib>g9h= zAxMsL<_n_3QGgZ$*c4=?h)GjfAE)af&_xS$nd5X3C368?beqzxfQZko1uiEJC@M;x zzxDsC2`l5lZE+>Uz^wm6)jueau{g^U{+p})gYvgQl&uv_5!=t5JgxW6+Wc4FSEwDg z@lUCp&i7&1f?+j=$f;BlpXGH_xupKC-M3Xm!~~QwY-9OjriD^z1sjrV?}_=h(fg4* z1U6J(l=8y{*$TG8yuhBdnGde6mtT?2yI!Hz(C~3DJ;21Ne7U+)Om&NYUDbk7&aC-> zPAIsxnkOISeuqWUpP+S6}YT9_=uIY z-a;&kZ*K8NjJ33WXSzB|NWUN4MtBZN!#K@gxOgGPP0h^L+P7kl#Bwdqo+2bstVp)= zq(DW3-A30V#dnm3GZ`o8Ry;?VipadpGWW^g!?n51q9Kyna%(OwP{^LXJb#L@Pj|Nj zC$uSkBTJ1|XOU49G%YNQ@;8rV=KRF^;PTw~>qJGR&qlxinc&Zh=l7N(;~L}x z0!7$8=#pjMX|vF~6=LZ>MrEhc#j$RH#@U;zb8*#`%(@RdX-7Jo1&O)(;Qz0$CxM4@ zd;1-PZg!%=xN^0iRaqM<6*pN*;zqhrSDI$A4aPR5dlfh8x=D!^MUjzgBim$2i%MCh z7!0PVETfTi#`1sOp?>|p@B4k`ec$6b&v};fobxPa7*40=tDU`uBJXVF4!qelcD%Q> zdZDwXebtj|7up9X!;u-2>LsaXl_y(kOD_y*zGTRj9lo=o)Li3~pI)JT$CdQdVC58( z?PV=#pG(6u9-P*-FnHGxPd>uE*R{jxX@QOA5eisO!&x&Y5>qs%XEE+6CFFScg@}W} zGBGDILJRle+U_b4HYrLTSPyR;o`etC!FvmokiZQ$OuU1DdWo~9f57pK$t4d?`;YBk zZ%zr>lhDy|O)mTVz?&yM=(S6*|3RpMyLOr7fqFiXDBb)d$R7xoI%~R+kNdc)zxT;e0;bUT=wL5laglvvKM%(Hiy0c$F9RFQ<^1TKm^uKEFyg z<7Hc77~YNuJyexu*eb<|GX`)ELZ48f85RR*2;gpn81PBgvM*UXSk*>?T$hNjdm3&0 zKi#w#aW2I+#{m;n4CB<0&!{e98i2dI2*Xfi#ZZ+5QG?8m<11?8i-*e6WCZ`H4ikO1 zl^@M7Z#P$>8A=29S%l$jjnEm2G((;wCvF@-96~n(@JY=Ex5!u@dYb~xkS@uQrpt_K zA*RER?)AbLGlbtTdV?a#SwWZCtcjS;sg{KyYg8t-_=>d){&aI6?j-InJ$|b-A-GYumQdQaQY)~<5%Kg_Mcf*snCHuhC-gzhg*3xm5}a3_iYN3CVh`0>6+aT>j$w@KSDB#p$vDr3?m-@F=#Q4w;%Fr|?tPb=dWIa|)n>5YRA9vReVHoG79+ak~ z0;UEb7uYDizZqL6zIyI@_&4VcN8aD{7>scmj3GtSWMG?rL7I!DEgKv?i=thfb^u82m~f$6t^A^{MgEdVI2W-us@=m+JNS1B}*odBZ*Z zgk=Uz)UqRg`W+&=W7w3MpPGagixyXmKa)2+qZ!t*j~i^SI@_=ty^UEmS4*+`dZ>2i zqO%;{?=7)noJ03&Q+0IwZE&UTs-63SKW)o2(GG0ambp&^Ws)Vk>di;G?$I<$u>oA_ zQ&pBtIs-f00KeF8+o1wDL06`^<;VqXs=F3?tx9-gPW?$mO5fAgY1`==G{bGq)$*Q- z-#gCqe_Cy)^e;IaZeP00!qY0?(~sY{T=;oaw}qJSN1u+%$od%=1dpiwBDV$mi(gNSSYm2qjv=NUzUe$;YdiLd2CQ!>sD zaC&*E&=Jxja(|e1#xhXcmjv5=Z^^)2kJl6xe)V`hN&%~)O})EcG4}hrF|jeALwF=m4q;dj$TQZ0b}qR`d5H493ph=Q4ary2OGV2WL`SC zlCvA|l5^sQAN`6ls7%!Vrh;NAYpS!ozG`YpIBq@FUvF#4xq{_QM%}6*S=5HeFX6J3 zryt;IWPO)(%jwB6s_v|>UTc=DUb)U|(|CyIW+hX0S-fr+U#>RdsjH+QB}ckPIi%gp ztcR#6Lo+-t$-MLg!`ThN=Z-(Zcx#4u`e|te7WtDKT7Kxi$a45$G=#P`GlX3`dIQK` zCOkT3+i`o2_(#hW&hwD2Oe_K{>=s}FyX82@^7S$$XhCokxkF#7Hub3j&PaTz*>=Qb z5MiGXe$WDY^}o+uWJT-Y_TK6+c2}4=Pk7Clu*?~g zOQ>3ee~pl}yYe$Uk5L<1Vxno9!XXu={B(!`XSbaq`2$Did;9#cHS-dTFqD}^+!SUo z^fM#kmfzD@gD!V-u36uTIh=OjD5qfE8%g4_wkpu_y#N2sa_a z5O3pl*uvN;$sesV@|}gqJ$#U6STUwiO39m!8l5pQ>;IIuKpRQedb?4>fsNqB*AxFM}=&XbR~MRXC(uZF96GF=mL}H(jF$XgOc>u~KgNQbUUG>y2Ln%2R4_&MOcNt=_55>tB z<+2E+6YJ7)Gj{jr16ZJd-5Li=#Iu2fkE(N<`c7nB?t5>P9R?#K&Y)GIe&-!)s=YG39dy6sHc^t#ld%c3IIWfE@V zq_F07qV@D-nTDeyZ)Hl_=_&d2Yf~O(-J$6_*mv|^C7rFhl5{ql-__;LJ^Yc&P502E zn$<5KdaKMin(Z4QFfR`I*m>P2{B?fC$9J89Cx;Tk69zj<$LD~&^~J1SihSwElox>w z9{^R#EYv%gQdBa+PrM>AsYeR^vJREO$y54$5RBw&D+H3H(Monk?yQP~)mzAAJ zJ$mR%_2t(7*yE2n^r`GUqExf1!swu8YGoa~EV zma|M$_$>b4XL@}b-+R|br@m5`^t`f0nz7MCj;x<1$MAMW=(m$Ftee3OD<$bR{Z}2W zcqc5DqJcd#2?I5%9{_dk5}q62FT4J&kH(2jK=uq$)LjosGXebcy#9X`hv)D3(3jbZ zi$kA07Kiy#XmJQY>V)VK+K2<_S?C5g@iqcqZ*~9yxljh?2Q|0?Er?|^M{hh) z;q3A<-JFb|*%pL>3eAAwHrh~{*Fd-c{92SqiZSP_cc|}{+1s*nq2m<47i}Qf;*Bu; z9itCWE}6mYsQ6D-o&Ti;s6bz055>9)Ck|-5jkE(>+%0(7;_t;M2wNcd2TP!8K-dC` zKWsa|Vdq)EhF%4ASS;26oqW9~2sQl@c^{nzl=$d8sLn7wNGB*pAjbRw9&e)vmOw+! z-V!JeKfq+grkrCy7F!Tf8fpP3uTcglw*-cp&*vBQ)=^U>iP41-cRuLW#qQs8c(vC^ z*D6tT?~9L>`xtEN#4V!BmWS_Q1IzMuFy2B$?rVIgQCjR2SVj5RMDtyhWA(U;lD2X2 zSXHSUea{sM&$NvT7?ID_x}|3CT{c3lhIk-!Yykw6bS5&(2ZqK$Y*27yp003SIyGGHP2NvcFxiHHEE zE6|of=P9u`I5zbpsq$;b^C!4y{dX2H-<%>>#645?CDO>syjy+l$kcbFH%TX;1oW1E zl!!LFvSV{WylP8LD@+N>zkX2pmM9c$#Hp(>GN5|#yhPBSIR0#*Tg0#reS%BN0eT83 zS@+!--ypC=WB}8_QxP?Q*g0C~*`T{>K9MN_*A^g!+7C4PnKY=n0HaGwRczI5Gda{f`(fU6j8 zGPIt5TrL%lnSab|93Oe^ls7g1ILu4`P6r%bu*GzHP4YV|yeXkrm{mHE}Ck%Q_g-RhN}S;;2hkvTSs!Gt5&01x}r7Kejv z9EYN!!uOe%lTAWh2x|zLGJbxNxWZ(UrkKLQQ`m!ZgYFa0@q0Vpt{`RS-Z?+|;}LSP zZHGZeeeRu?WBw#RW89fVEE~L^CiPw3;G2?~bwzoVVZyDqt9X@RIlraguX}$TTsJVw zB#k5wsRyu)ikZhYdnipD=);@-MC%udmY%{VR$ya1w0LdV2q)n4ahlKS)p}% z%O6$x>5>N@fAAq!nC*WP6}aBDndAKD3=iRaTGc7EkyuQc)_q(&BD9wve73OMpFi{O z*6h2_ZpMw4NV)7BQ*#>LfRvjR7fK&R7@_-h7cNEUSXa9pJXxcvm3D&SrArZoPjOw@djx8;nxqAB94HI*@#@jWj|GLHNv_YDY&XR3F0zB7nA%Zk70@n zryl;EEvrF~8_inavQyS`@tU=g@fyq5d8KH1SnP?gFJa2| zdTL#j!B9N|tGohEeomQ4PI#XY_w7fiI|XWaW^r!X9u@~G?|9Ipv%MdYUH3e`8Mhjm z@|w3BHx-7e4m~JTlJ9ui1Vo!$T+4-HmxrPS`a5T2ob6>~Mft&PC0{Uz&}SLqY>$yx zEUAXb!b^1bqTP=;MMMsn|Jr){6#88d_2`kHBOBLmF!5O%6dL5}E{k}XskxmnR&#T< SUm%SR!NBWRXr%-gc>V{t;N-3V literal 0 HcmV?d00001 diff --git a/third_party/date/test/tz_test/tzdata2016d.txt.zip b/third_party/date/test/tz_test/tzdata2016d.txt.zip new file mode 100644 index 0000000000000000000000000000000000000000..8af5ea150edc47bfd0f79ce26d276d9960718cc8 GIT binary patch literal 128096 zcmbTeXFwBM*C?FOixicjR2wKAm0oRNK~PjcAv94C10kV=4xz>)O+_gpASy+X08$bN zC4dkC0R^Q72!!5|-oG96ocBD>eZTwTN@lN_wbxp^%*@`ajn@qrnfM@V;P2bpv`dhG z{o{e~Lfn1s*}B`FQaq`0Pu|_j-Q@NjNO7v9Sr#~!pnQ<2a_iV$6?CqD>a~H5=Q2!Z zg3t69IgyRDTsIqH33aL;oU>zk?cV#g-ne!*aNRTZkN}~izR5u%?r6Q*u*PZSpwy9( zb-8`89UEbq^=6GOY^M_2BhJ0!zO^+SQ7JaFJzzb9=%tXp(V7hOzD4sOg9r1qGMD&GDv-se$uNg{!Nau!W}{X3lrYxK)Jm zj4?SZPW(2RP)%mSPmBdKp$((S+zBUHL1&byR#0vsddiDR`w3F|QDqZs9vs}8&w(IY*b-x+#XMNzic;Sdk7#SmbR%jRX3V1CVNBAiz zwK*THl#kT$@f&MVxXbBO*JHmtEvxXTBbVF4x=)-sIk%LZq}!b9@9O2Ty0)D|Mx=<$ z1o)Me=hY(3W~MT@XDb!AU(y6>th>-A@B33WUlJ>ID*QGoN0yf+YiRAM>Q)2B5>3mg zi2{D{?I}AiX(4Zta`ZOZk1Ozax&(L=y4rIbP30eUT8mf*+VWl%j`1B@dyCWBGlE|o zn48SSR`yr;m8{_dG~INzm*#)2#Kf1)tFD`*iXg;Q%4{}OV=DMswi{NbpZit7b2SRq z&2(a&^>q=E_C1kP3BQzfrV2KbC8z}}E&H@8ETuY!au^{!0}^VtBQVpecNf^Elx$SX zJK1(0XD><$7d{H3$vxA`EqMgl;b!7)OBl43gR(NK+2=7*)q*;fjXCpN_-y)5kn|Z< zIP!jCau|SwObA{GnGNw2LS{mIxzt!0*$5pNUuLxjq_fa=uap=O3S27}utklE3cBUh zE%;&o*u=-t$-E)*UeYG@=ue22Ps)AqanxpW!Prsl=oHl`9fb$U6TJl%(KzH-`&#mF&SEJ)5&&;08x6l^k2y7g|xV_LU>u!3A&ok5D=0X1){ z3pTmNdcU-IZPjtp${#Ly9RBKc)~-zPf=*iWQS^ABTI8J^|2#*&4+n0>+tsB69gVm< zTzeIfA!@aAVkS<&cg(w{J4KJ9?e2)TM8f9!+*V^vFOT2{lU{R5H$f`$rQn{x4|lfT z$3_zL)~ckAid`DazxNsH^$0Cim1Xn>Ue^%4^qIDglKz3wz4p8!naA6^;8~4zaCxZl z*>H8o4|--=vd!aBmU)#=LbMq-KAOJTkEQBVGDE$tB5%yCmcg%kpE>Y$*IRY~f)22QyI5r%2XQbE_EebPVjx4a6v zIrUoojvrJc4z3V%^UOg^Z(+z;>d6zRGBU4Lh2mi^FTzP=!^5*k9~)*4?zfZ!UOuOx zNY%KOGbZjgOT?L0>?{QtGtGq=mTCMed$a^js2rf!nMCG`WYKPY9XsgdCnci#l^3Ai zz4`En^gioh`L~%pB6Z2BZ*6p)&K^>8mSIyfTD!;8oF>gCR$+VMfUZne>6SVcvY+TeLHl#Gui|ZuKq~5#E%;@{osLDZ5*-CqYW$0pgH4RoP6a1 zFTv!C+>4xQU&_4dqa`6x-!O_#6vZb@I(X3ADWuxVc)qjnsctXqtygJDcy{%{+VI+g zI1UH?I=49C7WLZ6e)XAFoJm%7(JlUc4g_yMx5J+me_&Gh2cqtWwRJQSsMVQwd^i<8 zkUfQjjm~=sQ^)`MOd9{|N8ylNYc%S!p4#30uUs7jg2-w|rsnh1J@rY4J7)Lhz43m> zqPKnG?B3K={A=%Ht5RLc}wpK z^t?%AM4I#sjsrq2u&+@aw((+u*M#AaWg!!qo1^+#b@| zw~t?6*ZYxm#MR`vqC6!2feb`A%pm^t2?(9(Iv*za9KXZ~4pL6F7ab%6fdE;q&u^9X z*y`5S(LqGJ>9`EC0w#insVt>q#caz`_05bc!9{b~&Ac+$` zfu5^t1M&Di#_jQe(VCjsIWw`8{<47Wrh(ysxrvxlvDCK8zJS1;ReLuWiFL(yRy=0e zf3kNmwcIbjpWt7nm{p*;opt&<_x4LYO?iS6o-}%kHdUO$UKZ{P&*_#Vw14<%USyt) zhQi=KALf|nm=O2iiXIl3=Cprs4uaDW8|Cny+iL?OBTZX@y}eD7v*O|blyy7%RYjM$K-oR_MOEU5m`{!$`7+LcRU? zo~I^BO<1We&iI|nrJG7u>!*~4uGyR~^*r5qf@I2A%#nArY4G3_A2m)X!hybfyt|_n z0@SHk`}sY~9LQ@gYflr*=ug#IXta>Y1@4p)iPJRtR*-0INaASWGzIr&u8hj}fsLcZ zpyv7O`QYjW2BGn1Rh8s_QcNeqG9@PROqv z_nn8dn9cB~FLbrJcW6C3axwk773zQ~3g06Oj&gSMakD!+i{EM{9D}4z& z8`EJUv+c>c3+EHG7s$;0IXV8)E#ml3#oF7i53bzVwrb!vqXqYR)|=IM%k=NqN^e&9 z%y-meClQ;>n!NsUaFFF5l{5UZ9=@AU zVUwcD0nMrG4RTG3?xy?BNRvf>^JWiiVD$$faC1Ij;aFz>l#9Rr&fLg0Eq7*Td)X7( zFEW$5v$oR7y}h;!bQ0Z4?+w-279M;cv44B>lF9q&hGdxnh7HGWwGW3^zo#t-P6S-` zF@Kfp+T$sSd>P-g?yQ*!X+-uK^rciKGl-b#%chk34<|ssa=E_ZBT%1YA7k%yBpE>w z%2ZRRQTho{MxZUEK6Kc7J0lf>%q`(BAAB6bBEm<_f?ni~en02EC8n@xC$v|5FW#(E zzGzc5v+Co|h)e!Bd)Y}RwEU5k68UJ1WhI-`o*7fYR9L9i7x7tyLa1f;$mU70R>$;l z8{YkmWk>wJF4k?KQNvg9IUAOB$7h9a)E(cCOftfZ@p}0Mt4#LmIZ(e(aA~|K=Fbj^ zzcrb`Za{QxfDin5?%rx$pkw-geOp}Qb6G*hmbK{TGM9dez5 zhuKScxb5x~Onfgx6|Yac?W*pu9>U*Ux*p$j@j=0-pl&Z&75K$1CvAbGBHDB@$s@AX zabX0H_f!Zdtz28H_Hn5M#wGs0DV41}(^^pMGkFH1Z{1%@m+AADpW_EBDp<|ITKY~tx&2&x z^TlyRlLWAeM)c+y9`-f^I$~?lYVoK|NY)42U}D)Xz2mkBdzTxVBO|84mkgZOWIyn`P-## zJ@uJOn0LxPX+^f|Msvg)*`=oacaMhTo!?fcTh^Ei2!%<%8u)5iM=Fy}54dSCdpIz6i{gW7-2i*17ySsA@t~VO1EAuM9rjy*BK_J({y`D|>-uz3Rx?FN68R-@#KQI#KTHQ3tyC0W)#58m= z10pq0DrKWbaP-+rtSm`=g(RMQJj9E?IaVbzHNuZ>yvVyBpUa@O1hF@X%eYWDfWzpBxE{Gu$I&YUc};C(q z1NiC_X39WzPoz03<<@HGq9Wg^beA(RHI)HY0ms#Y zX+`cR*~$&IosMadpr=Kn@h=+su0&H?TegOLPG8O|_IfHoaCd7pc`kd_&32k^OWHBm zAl`4Q_Q*BlxU{6}Wj=^&Jslx0)IYAE_lwzJpSfBawO!3gY`U9YP z4_iswgBrN(n6kk0LQvm_c@m;8eD-Zr)_46|58fW*ft1|iVe2|kMjQe_y3qI(Tj&&D z_X%|-w~E_e0@V!<4>4!Mb1Pv(y!KQin%`Rf85`Fj1A(9?5>cR;i-+!AKF0g$-afWF zH`qgEOPJ2Z-D5axpaQCsAzvg?!I1{Yj1S#=`%S-IiuaSr?Yw*ZYXhf%(gr}j%E(_V z=g_x>7j7{g#&-rU++#fK*-0E7XF0blYnZvv-H?WzNk!%Q!S-nilme3k>)a zzphSS1?6RH;PV<2;6z(Uv~di5ymdlhRX)dZ^L<<8;>a?Y+)v}t7KsiVMZ@)}Pd)Fq zM~^Byr(~+gts-E=)tlGq)T73kvd^|Um;7|lK6))BDmB!|T;E}!TrMw}6vb#mu9{Y> zmD?({M8+GjFCLFjC0V|O3J26WYKbt*%*>;J^WfKFvwxoWXfxOO2}mcNV@`3uyH-ae zh8Pp?P-e-nU@-tT`UN6?kS{ZEDKN5P%UTXmpDeG7GBg^8F=>g^`1m-{R6tdYQdbzJ z?I~wU5O(`>+y1HID#t=;;-Fgd&Z#e6QZ|>Xte{3UTb((N>b=B*e7SC?(fD$dzMc(# zkglzL%u85gK3j@eW_o=5u`pF6TZG$8!sc`z4MRE=^&CSMVz0q<8fls{p>Od^ZMH@( zLu_bc{4LA+x_u%mww~BPpI=^Xo;&MnOVc$?b;qiLewHjm-FT!vk|_92J8}LvT=#NF zMv~SyAM?D5Km%X#uFHj^m6=ZH%<`D2WA>g8Ih}sB1!0_*l_AAz_b&jg2Tk{;0GCQ8 zaH-^(Vai!3GNf|4w(}Z#ky%Ze%b-;7Y`!jG?(fpr5xgJQn9(8jM~kQwDVPH%2j2)4}PC{-<8l3mUDL%U1u zU1w=vcMzk;kA&Cu&cw}|FK=vE2X)-9oUM~#u_^4Yl;7}IN`uL$ zYdSpWel~ULe=V=jfjU<%_ClBWL$~4zg$_;0jjI2*+ z+CJM8J!G)q;~%?GKhQMrb6^0=X-rQ0vR2LQX@1?4;DNRH&tgMo3fVF>KkXXfE9JRH z?i}Pk(&sVmG8!ScGQHBPnd^+2weGF-LT{|pMAU@Y?U~fU&$#_5JQ-mtB_633e~Q^D zot1&wtrbBPLWJSu8jEMKV~#MTwCaC~UT6mwqL;JaBsr<>tFU+ZvJ0qv^L>dkD(#)-iizT6mWJS21hfiEn1usL^w+R4?;$d!JPW zD?0ty{x*MI+Hg?nWBMrRHy~`NG-H^Z1zVoi0|*T>MTwPBKLl^y6eXP*HYl_XBO{C z7Tsh5d{g>!&D;TWtaP9EcX(t+j9J;~TX2RIA(~X5_epQ7M$*Yy6!i8ofoRi3oB4d4 zWsVRhG)w3l;^BiBrQogJ__Gub8Mrg_*d7upzk9Lb!tp%es=3E)nlZhP`BE{|lRCDT zXmSx_g4!3<{Ft}>@kqrWW4|LIBA!qy7l2y6XhTrHb1r6 zT=3=WM`J=EuoK#)Z`q2Pg$)y%XoJAPS1d&HprkuzA{{6BKg^WJd?Q}xHss>N%MtrFi%k3yNfLAudX$M+nTRIw+0?z`jS{cHZWj)me(Je2E|? zyZVw_*z9oTfy0CIxmR~Q923?27{U(=qsrD%XU&O(H@Ow+B{CVCH`-(a$IX&F@86#u zw>&9<%J<;XAvgUB{#kU*zN_}FhP>5m>@@@Q{Fs_x?qSphYC-2?@947BR{P-@f~R;p z11?cIg3Xgs%CjPfB$GS88?bq9+81m3BoJsfr&jMBqMY>Y$=m2Lx(2D9&iKOfKW4+* z_85h$)uR3ZE!dPxt}K)PDC1JfHJfVb_6fZ=?8Dbk4PO;?js7~AfqkA}>vPGQeiDD@ zx6$*(#;&fmDXiA|tE*aO@Pol$M=Dkehmb75=$T2VR_FgLiElLGA6Bh7t;l8_vbD$^xQda>||z2oXrt7>H!&v#d1I)$si!u{r}c%&uThi*<} zxZ1tLcA~W3edhWRV%FItGu3_#>Qg;kB2Iq&?fl=C&yD8rF1b;sN4+;1KmJaT=TT&IaNM$9NI(oxCS!T=LAr0xNzi6Z-O4> z)rZ3rm?$?v(sPD!X6~o6ehwopvDGsat}ox3n@>U1fgUPFIr6G5-BbGvdUq8VE66jRzgarWO-#Oiz5CebD_X zD*yf<-eNoPctQBLs-c2o-|w(i$F}lz&!D}vo`!!bu#Ys%qfu3!2_&;q(luVS`E{`n z;7T?%xvKm>STwFE_UvB9EHctRI*3g-L$=6 z^P_p?UExAk{sE-;*Y35H=V%?x_E-kRhoinXy4RlVFy@&YaC!7bXslK0@k1XLBj!0S z20Vw!I|i>BgkGj`m|5024l28vcb`!zm1#!VruO`aup3-IP$E%e65KFllFE10(0Q+~ zjTENe(V&SslPOgc9~^ZA!Tjp@%5Ax$q+WxysykPolqa1o58ejr=9L+v0z*+;Iawm*h0A^0cvC zd52xp{=BH@&vTfl-Z-r?Ec`@Vlf2bg1mk(HjUBUH?%kZ*0_y09U;%NW`sY)^=G{2I zZ-rE1QPH)O5ruCBMcMn4Z)}x{3)eeXzjol#?YcH>KzOMo=S8`3pZDa^z(|TB?+pZ{Nho zP*-G`)dC;&ZTl1~@lE42d{2EMMxJxZj0Zudb878hU_WA)Z{od{GJ}!(-2!rC-1g&1 zrv&*i&R3MtOiuS_*r1uA*z-1tn&(KT5c@FBM&Eh!8rPH|M%ta)j4|)^+YTXt-z`%y z<*Vpnn^e)g^r*@oPvCA;|ru=1(6|Pg*S5Vk1t@<^EFTUjd(Uo7wl^SxtNJXHx zW4ODpX~y%=u8Z>^@TTgYc;nNKp>@XdDKbaH(9;OYbp6p$xM1u>FWA8L+@>xfW(PkF z9UyNlb)A^G<78`|x1DMKmVoU%=Q(~{Hd|bt3t!TVk}lAVJ|6O&L}QZAXNJhw zcR889HZOYn2w5DmsnrH}278BfE$t{dh@uu`Xxz~$2qRI9A#IwH7|*1n)CsU9B#$pF zDixn0OO=v9r^_luXEc-xQfsPyS+3LGu@X=c`?xS7Pq zn;H3Ss`+EEgYNS3lKoI-<-?wAbmA#?$GZ)v{dP&e98@?)Zm^DglhCo~QOMnytTjD6 z<3^6oYkM!3MA7QwKw?RkRMF>hknv$5pDasmKPV`-RJSH};-&;U(x2MYbZ-r6DAex5 zXd>prKTA;`_d---B#y%Jdvwg|oy@=dz=TnsQ31EZLa*RZR?a9?>&xtoK1hIRq z2L^<2tcjp9t|!L{1?@oT#$C1plC;0jCGq)WHA(bewN9M1bYn+ID*lLpyVY+{V9%n% zY?~zP@636pm3*EKOuFLs*Bt?Ss|WIzvDJAa``TqylayEplGlX5kU@(JKo;;pp89jz z6kErJ2ToFYL#W+`mVS>HkkRY@J>Enhht3DayW7jjv-F{X@$UBW_jn27jezriTexmZ zMnQ2`g&1LU-tgbN!{}JR3syTi6VMFqwRXzm-(41SnVGTHt*r1Tl>D$6Y@WP#{(0|Y zq0K6M`o*rZqv=Fb!t}v~XSCo#H0plG`yfpE*VN%|)n{EPMOss$a4$=9u`{l>K+#@Q zsAU7pk~k8U~iS2;eYu)+`mqFjORJV zH_2JpxOWcI&sPj|Q(lD5^+C}GMchK!G3mW_%w@NexNm&Y(r;!!4>UCq<=qxqrP{y?r>YRr7TtPS@nuqc)h81O_2dOd^hnfwWViH`yOyQP zwM!Q986tZtDpr|Z1-qg5NX}THqMN6igp)|F_NSp_*o|V=xSZ+ZSThh?tXQ2NS&OYv z5XMeN?QF9Tc31}{FK3VQ_dM5KkvD5}SLZBqWg3{08EE@;#(MEgQyz|a1f)WB`zW~H-=P^k5K>iAe=?JD z&hZ06h<(u>iRH&8haEij=Dh;wa+Z%?Y=DvtQ2Mxx*nPQU36Z5&rps&VW=CK|P4u|4 zg?_DHLzzVM9g@OvSQ|>^HNZ4jO`jTMevx(?=ewh9k$xJ4<`!g$yP>APH<*#ZeGnBc zk8!^VE}w6ibJ8Yy>Tc1P;jikD;#Ik1hL1nI+NxBC$d(!0+}nbIb5 zclg5`hly9zyw6PQ_?+-!oRP8V`s-Ad`7?jwPHhDHcaN2D2Za=(;P!O}w3lfHnW(0( z=>VSv@QEdb_lqhd+OL?LOb%j<>X3@;kb-FdQu*XM<(vQ5f%Gf~W81PUZ9gF6Dz|T*;rZ_tM6>T$hg!}Ccu_xPn8W~pKT8nuhKG*d|ixrvvucM|DoBwK|?Dj_eo9CJR<(28r9dd{4tr`l* zTU=MX<)4qbH$JZsFpD;1hDo(R|9w#6x}B|37zsE299C(px!*!Wk~j#iPSRACuwD?r zpr7eakQeN3u9RemB}osf&sOKZM^Ea!DpRnZrC@7#dK`-JX6S^hQm^sw6NY?k!L#?K zH{T3>OIF$+VE&}Nv@K#irsc|GY1I9`tuAi6+et*TmjthY9Aq2bW#Waow|dIQsD`%uqR}ZJN|>O-tX*mZ~Dp(q*I65csV7bg~sLr@W0}yMM(f zwTsp>skh+H`9&PPuy|WygEvtlKAafN?Ij;JHA_kIqHIGWX1%=y+Z&b1h($Z8g>O5AK=2_W=c6Razfk z-P!R99EkirGQ=Zi^it7R?qNZ!@jWY<1_TrDcd{lI&R z;w)zr3U;VA+`>ydya?sQ$O==>hag3xgfn6&?aty9TouPjl)z6AnEuYg*rJn6-vP7Ktk2P8%)*arH1HxM7HCqH_ zN=&2QOP~&|DFJn8!I7lwRja-5*tcC~=1wlbAqZa11)FppGIu%J;WP2Z)_hh7xAfye zO^Uy0v;T;gkUbvsz$3b{K!e%K{x7;1nCxAwQCB4|y*E!}9%8^9$+&KGmWlGODG3IsI-T7bIvDmjVJ8mM0`2GdF}tn&518bqo916S zFOsJDf&LML5#~e3(m{!Me16Pp$>M?EyvSW%cu8*qAO(hVBLHCErCb%2=Abn@Z z=>X`?nWJFBPFdm|=JP8hrdmw;$di*BzQcfx_a`XlAx-j1P{2Ba705}q};B~i_En-`ip zFy{U3!*2Y@^rC~wT9BBdACB{swH)W6#-4arbPyS`8+X05<<-|+)*_eFG&KbMfNkym zY9#jB=fv*iL;UZ{0GN4FS3Tn`o(!7LCA)m!)1c1|9=tE(CE`i{dN`bFrtQJg3McIP zMvC?*YQOWoeU<0^ea!gbsG7ULLS+1kC^qTLp#?Z;&XC{VhfDxt_n(KAlY^)?LsoIs zHIiclmZXTRN_{_4`<=_)4D7fCQ>xaPX%)jF@^PN)zX=>!1iqhNgOvxWmHBPg4h(E; zkg++}+G(i^qZfHXPt=^wU>4MgZH0$kV0TY;NSE%Lbq(y8SV}gn+`tO1^jjZT%0JML z(wVSRsdyW`-U;n67Weo;RwqQSXT8;FuJZVCQFJLEW^vJ9>xZ$p3>B|3L7Tohlprp6 zh9p(RzNpgEF1E8W+JeAiJ3Y*rtq*z@7bF|D9}x7z7cVCT8d~(&4tv=a)Czv+Zj<8L z=x41l*L|5K16R0J)RX_xH&wV!N?@Ekjj~&J9`luKc*I8%ZHoxm55YBs_k-MOT}oMi zTc!H7^vZ`@YbS{;c+aZq1gyFVeNXiid;f} z$g^kbTIA`Q8YqEJ+Kq938zsk>2AOn-B?d?#UD0dph~WET@{pLP8?|~)!OmjxY$Us@ zZm7LUHu0H;408wCU>|##8ZW^haS4*p#;Y)h7^8PYL?@H)f96o0JWsg(P4f20;7rI( zeW4FWRABs4N4ZS)a+&EhB%Y<`c*gH*{g(cgCNBz-BJVbu>;;*WcQdbtDU268PU}YR zcz;@6$UN@yc*mzaIWE#H!`l1eo~n& zBZRTi&uCo7VegGNiLm!UNiB$2^*I^G4Xitj>KFO$m?U!RUYuo#g9R`Mqmk(d(cK#0gK4xIXEUp7h5oVK z02$qO6EnEDYr6s3`?9^jnrww44jQl$yk$k{*4sf)9oJ)62V~L$WPt>_ZI$mH+9S0{ z26qqRNVoVFtIo1c%Dw!wvSdeCa8KEREDPRQ7eL+A@0 z9nf|`$L~CzKO_Bj8qX;(MU8-+z7^A@zi~B6-*k;j*SQ}tQlcl*CjT+(L0!-2Em5FaiUptJF;2sNSvmw{ z;#>&5Lm0JcFnl1ex=5=Pv;^+ytbjUb%tEXyR!MLGcfX{V05sH=qvft=L*6wF z%33mG-qn;q%sxDWnC%Yc3d8PTIvTcA3H1KayE>eAl|=6scq{&W2~?mfCi|#p7!Mu$ zTOXmfOuzcKK0=>513(D$5qgze$NBf574p(`&?p`#7W9Dw#R7oe3fUruHuy2^nk`Q^ zQ17pFkH-BoYrmPn)B|R^IYH1IlEK~2HFN?-vL$_dn6-{sSb*7gesF>kkqI?2>id$W(+i-JN|ZXVfP*AAB_Vf zS8PO(5{lgPI}AAK3MfDpQxJ3<;H7~3M3-tdb{25=0FQbQif$-e25jI4|62-p=IE4Q zssIVlKMep0xV>~CM!?j|OET*;q|0#AmEV=I8wvVZqor6uPG$v7U)N2c0}!HOq+vja zY6MU@zwf1k=`8UUI&xPNzVxTZ|2Z=H1pL>CdUC*s=!2$ri2fJ=M$O$0!T#wDy^4!| z8+X@h`W&p3(1#xWd)Qz_1q2>29y$&vrC@*v@)m(UQ!-%H_Zi#$vHcD%{5>73I(Rw( z(8s}4n*Y89znSPObkMvuf<3aovb3CtjI`1eA^4+Tn_ne{j%%^&ie{m`<7ONbta|$` zwMv^xvYS(Csbu|%Maz@&t21vSxWweH_>2i_nLl5A;{Es$JV}JOF)gh1z&KmE5oOn%6IMyW zk~&0xuQK9VPgB^!0oqSgX2n;|dbSS7s=4^)Q`b9E_rTkN5^JDL1x`Qj*iUK{nW-h| z9<{%C1rapOlp>x$?qIkUSTDYJMU)UuM}g>*${hui>Keq;dudoD>uiQig%5CA*ZUNuW8W+(JV!ZHYs2 zAems!>y&HTe&pj?uFPcyq|?Ita$o9V+9VmW$wBz|;^uVI>b^c&9P3WwXupWn_SW2B zfE%Bk=g+n5<*6>+snCKCb<7K@&pygYP83U@9h&ib_LkDd*3-q)HyHkuXjN4()Bt_w zOL29ZvFfLYS~-~-ERwCuZ^)gT8t&SjCz$rVF7S!TgC()JcK?8TmZC$FmTzYqg&lWE zcrp2cn84z%aqvlbi?egHsO8Z1weW17%BDB)CxoeO7vb<1N%wQUvEaGea5aUa6uk0P zi(i}f*m8%~p!m@aaE?h@*bJ5N4j@IrDkWMfTXM)n?KJaige5|In^vGUj=v{ItiwD8 zt~~(If`ASXq>QZfzonVy)5A}{vqmp%sSU3sig(b=Cs8?^2yNVwQj2vAyw)e{f5hpf zh$BJmLS&t8ziyfL_Rprqj-IH*fr-`3o`9!6)YNl4V8{WxjFfisYjAD$cO7l!x=rv& z#~kIVMR|#Y3CEnJ!uI_L?HpwZ5#6aabML{QU}fZ50sD#e^Kf6%G(qf2jlbdNjthQ& z3gB=&QXx4AKN1jTv4389?+&-*pd+v~`MH$=}f5{XqHhU-Pw3qN7Y>pS6vxl)T**Jg-qq z*jL#(T5LZh{3*2OrAR*$?BFM_r^MtC5OVlZg@Mntsj{v)>ySgCX5p$}iz7I=t_o1E zAXt%Z2rN#|VXc0H-YEi~{RK{WJv8Jk5(6Lhov2C8DHh`LVO@0g~SQ z6N1lVpp;YB-RpWac#TpVd>JDh=5Lea<~w~3v4}pmn%yu=cj=yw6UYbZK+>fJC^ZVxxq$yJ$56i8t zHP-N`wxo&#bop?WX3OKgVuZGzr(RW(PpEu#f4Ye2TbrZd_U5M{RhR<9m>||lj-ges zqz5{_P!xe#+*W>mW?tH^Y)n>Ef# zm#q+mfw>OziPHDSdLW$cpt?4_DQ>anU0XWzPBi14GJ(3QLcL6>fog@gle{lxKY_ro>FAAKo?qdc!~~ip79#UV$I*+?<#a z0Ml~smk$0|EZAy+bf6c4Mu9R){zI1f_!xmo#~@BAHjP>VKK24!ae453HhKHo_&Ow@_IgUxXxg& z>R4+XD&FX@Y8FSEtI4|r;ag$jd?0m<<{dWg13rsMA-Z!AjX?^T^c#Ktr+~5V^*l&K zi$CJ>Ej?#IKKY!>b^dn1*a;Xx^jm6`CCb4fY+fVGpeGuzRvQ2J7nWH_N8u8KOkR;& zVQ_- z-AqUkc&9u3GP^mh$Xc%94zcjiR(PRlK#f_1YkTp>UaE$-7ooO$ttGjAePH#bolXPi zkkH7=Ny`vnan`2Wp)(E6uu+iQ_Y!<;k$JZ52m*XEd<5}DuNxywo}A`Yen88`4qlaRhh^8bI~Q9p7d`(rB44gy{){u*;BgJKeFJ$NYU9*Ax#&wL(P=f z32!cwM3uXkKJy#SxDnsg$00Sx!IGKS1f@T(Uq^nQ-f-n1(2r9|jL7>ctkec4ZqkdA zNua3i`U6TPLuCpsK>j1nO5`R~)cYPHHMw=LcMQq#?m9j_Md^;uL{JCz4mzMaJ^?a4 z(WS2UgyxHb)32urzdq;Lbt%1>KlR<@{qzjgK9jtx$(#Li;;MVN+E%(@N2n~1$s6-d#d6|eSL~Qylq^7CFKjO1#MtFi2=)q2Pu)q zO4!%Q2xFguB7imbuiD?95l}|~3ogC-dZ*!_4@L%6?vMCua@x%R2Dovo^rz+X5`@0G z5yW;^H-H1H+h3DVMCP~O`FoNmZ4&Ss#RGzW{6=COjMyZlABY8jq)#FM<{z-$K&U7% znShL(YJ}(#jgFX1(~TflX)k7qtuF|RtQV|kd$@Ue<$M3Ap10O{(_Krxb+s-rc&>(F z4lBl^fUxS*-F9BM@TGszrM$%3!>eSiAo>7tIrE(SjT8aDmG2`^r>(50D9^0U;aJ$C z(|crfqpmq2v9rlDcEp)B&Kae1HTw`R9c?;_%BUGnSt8V`rB!wDswwlwDVr3l&)KFW zZa24GS6j$E@jauDUV7b63X^h3-DnGTze7Wb-=E%5ed*8E`=uM*CaSAm^3j^xGwGMB zS+e%*{l8*mVjL4tXE~w@d+YnxHtR=AuIDGYdeI&))dtqrT5LU!PXgbUU~) zzA9T^8v|XN!HRU~ zN^!j?$3}-lk2b;^hM zbdnd}_+kc=q~X-*e?Vp%MB2?!lFPLIgqEi@D#uc0QkVXv?SwW3>1rx3qX(d9KYhi7}239a8*2mwQ% zHj*~Ev^{UcOO#n9<}m-xEvp%Gd2ewqUMACU*6n8e@U3ITHO|5a{Ez$fDU&&0e=<-! zsiZ_#hV^Z$x34hV1Xl(PY6JTiM&|fyM%;sa$YCaT5`7UfP#x02yPpR^k`+3bvCzO| z0Z4zWO9g;AJLA%_^~PO}0X)d`O`0Da0n{8$UU%4K!9!GyfItHPiZ^wh%bx+7dI0^Z zy}9CZPO|@B7MdFs^;K!zU1pja4;}i0!L0xw*aG zb#KHHA^i)s6Me_kA2$l6@Y&to!CAVJU&*xPrW)SvAI>Pv#}J+sFu>~XfCZrWVXB3z zDMm(JhVQ5AQ2fe35tUwHplh<4!3=7+`x6}8T8 z<;p-T(W9h~2as9(;C4a%{;YAasRoBP8#|mFRpTzehc?)*bEhj}uYT&N4u4D#qxa6R z{XD*f-mh*a)!i=BQy}TxcP%hY>(qbs73tO!s*obttL@tG}>%wj9XQEPl$^J$Qwi4e49E#kIJlqN~G) zlwf5dJYBEVVl8Y@=30pupSwQS_f`GSuZm0Rhb9EG)nCiuhAF;8azQEOAT zGZsK)&7+e6eV#5KICi|0fq3AC|45e(=51Hl^-gDct5K8~Gq?W`Hfc*I2kyq*-qC)y z34Gt+(gaZt?bRwP4fNmmHN0gimR0#_W+=2-32x(sNF4r_8L);=$)FhNj-ZVeVua71 zey0D`(Xf|Ab!nf%L_BydTNEL%F2*GyrF}$gNXK*R|6}Y;z@hBk$MG5a8YN^cijpm| zuN7?+MTHECgfIqWU#67^m94Cmq_Tx%CS(voC}bV`mhAh^|9*z|{k)&g_x)ej@4Dv9 z{haMS_p_bn-0LYkTz&hd^T|7RiBoFlW4BY|jRqal&99}qWTz}G zOd7KOu=eUapgZ999kXq(!#pwlX7^$JQv$`nTnQAzVo9L5oA>qJU8@Si40ISsWOL^_ z$m5d#P9BNv^2(;4>c+|)mMtHRav7Q7`4szqe!5K%RhVJY~$$vFo~qTLr_U6t}vn=FVtJ#6gi9^7B1N18p> zcsI@!l}BTShiDN2W1T!VUVP>&Y9TL3P=ZL&d*5wz8Flq79UBDYt`lLmclcgbyuI}A zt32_}s~rY|uD3_VIGgzhwFSLq#=`peR1fZ`Zw(rG+6k!U$sxVrTPQ@DKj;dA__}ym zSb(+5(3g)pRnHxoRcUcPr1>8)y1M^(ggO0xNjAR^fq;4mL*d#G0DPy96e8NR*5F21 zS_HVQ63r3xn@h48A_``Vqfme>ZV=G#hw&1aCn8OCGO4>`IMr=s6;jEb<<}>?hInEN zN8)W9P)4!}cyS(ZWOxKN#^u)&O=T5U$WOD-n93GZ#x)1ZT8L6bhZC`)MixU*flP$Z zZ)+kf->mwFX?4V-8jU=pGfqj;vUi)Y23JjrbNRjx%-8v-Tw7XddJ8*OuMkNr($1PAX@S%q! z;i!1d?E+h_c5c+$rX9a7VkOU~i@g6U8%)0ZYWZlyTR-2K!NH!ng)lZv^FYt9seOfS zWx_-j#>&;|9~aHp7=#F=xo*6bxtDkGcV7SHgtyZ4@l+Xa@E_nBAV>T+nJgiym2u;p zip!J6%z{RQi5tazE0^|M=(CnLzx2<)5i+lI>Qr`@sQLU*Y_xQuzst&CG;>dOA8q4~ zmtD%3`A={13d7cl-Q+wwm$oNe67DtJY&_YF=2=w5v|SoJ-$HRI~TuH>MhdYg6cwbrRGxBMDI17eEP zdB_*BHQh}tfBl*FH?fSn)HOJh6?BTlwg2(4O>E8c2 ze{HwVi}!lUYlYNuxo)rNY;WM-{QY-5-jrHS{>V%|z3sZ&#`OHL)>G}~#L0l5T9(13 zmRF_Jrb&TU8sF-NEH}QbTj8EF@d??uem;Ut#_OD_{*BoeC)ob;2UK~TOQPR>Y_@x9 zB2P23f_2?_m0N$k!@_^RpZcMc1V^s6NM^ND` zm2%9D4o*LCh^%re)w%{dWfv5Y;}sBAmhI}=Gyn$sg&9> zk&iDUKxx_Z?kE@NbUu=?;D%K8vx~Ri>8G=1D7>!@L_y1nId)Z04pR(R`kj6+@qt;9 z%-;so@9Ep+SaaJ6Ty0~7rgNHt&Brvs;OYWf-{rRfeV4&uBjdi8QU+*u%3+QLKE_#c zw$Jk%MVPju5!kIi=nR@Ul+hhvsEz_R_M#J1Ds%Hhk+;B(ZPmjAPpJY%4LTx48_JM{Fq9!WKEV5LR?dV?67uRKp@BTi z7(fkZGm!x|J0Uuzb53EVcf2+{J(fIHPVoHVJ7`)W``%s9j-25D66LoJt#vNZwpWds zJ|7;Jz1%W(N0$bt>1!^GU*X0GS|tDURei+>?e1)8~&D2iroFP@^AgAR`GcGp1;nD`89-`up! zsJV0(dlL)Ek<_iMS$|XZmxa%16BcZl+bTB5m8?*k8-qhoXWp1cso2$?|xQBZ3L|g#kXF? zse*N2oO5WhU~0ukt=+e?gI`eb#<}m#LpL(dV6d9u;jvjtDI=L}Q>iY?nZdcvi&;HZ z?LOCHm)gqYldsD>Z_93y5Y?O?8EcCI;d@(@iBR38{g?z6=OtbZ$*|DlR;`!zLKaQ1 zmZj;A8BPtr4X|7!)!4k>xt z>c`+8d?Qk^K5=E_71Cwp6{>#2@x+yrSD5d6cDNYe%^C-}^hLNLiN!Wp0;o>zG2n7npvXQyPcV<1FM5h`d- zeB`G7_vyalD@y16bF@8{+E>r*&9Y5z?L8>^r}^~sMCHCEkvzjViAikS?!d(JRWsC6 zhjl#tx+6wfh7Q)T$<2~0f`{m(h^68lCXog56ML@Zj~U^;JoE6%OcTGvXmT)zdvr2* zaIP88aU#tu1m)&4gs1j&PGZH&s;CxJ5B!G#xRWF{f4GDIXkA$9+m%(p84Y0a=t0=}7m1FRVk z6rja|-iS2=l!2rf%CHrQBS>ybYa~Hg@dGBr#u!F{P(mVCv+5+b21S<6Kn{EDXpyI1S^|h^LWm} zrxh0Z_|7NeIXxOLu0&<8JR0dK9oHx=KISC-yQlwtbj8)uYoM_0GmpGwc*Ltkw}@QqW$}f%%A%0iiG94Pg1Z!`rTs|Z{;?bQcBAM}-fi|nk7~nsw>2my z_4%u>ymM}$Tj)zE{dnb8@Wz}?->(23ch8l96u)@O7^(h==y{Bjcz1-mQ1=x2nmScQ zoCmu5=49UokKOzQy_a6=Tf2!rsI%BMuDqzd)4O|mijkB~M>fDY<5!yNGAH~BJUwT; zs@axPYt3(69j1TE^y%!9RnKTx{F^()w^cE3(lMkIei3oidORDqw|>GT~LH80Oo-Y08jbOKAos zM(|SJV%>TvRoh@z@nU%)fU zio{cVsgNupJ%L(8wG5@3Y<{I!A|7e;PZ^GKmun(|2Kll>6|zDX16_GWfI$$53i3>0 zNJNN(j0{?Cqu(znKOqoU?*xH$n66l@MqbGfxT}NW75wvpspij89ZQf2J8aKi}dR&7W0S!J}d9}qE|F=z7opOu+=Z(zRfFTP_a_8EI4yrZ(!)86hJpr-pHCEbVk-0`4vNil6 za*y;ur_~qbKUA4>)iEaHP{gU)<+8EqCJj#ozcA(4A}7Su;}ZwL88xazP*-^)&`gE< zb5mjc+7ulUy+C0#C=9$K%hboy=+sp9Q?u1Xiz#m-eYuD~$&DKg@{QKr!~U#`X@b*8 zVgfV;n+6~J*KANEA;&URntA1$TBNnbD-PQU5If75@N@6vE{Ds64N;G{7l(XWsd3-6 z>`)#I6K&4zS!{Y&k1;_+)~|JaJNM*RvD>l5QC}+^e0rN+*OW%@uK#5^y@{*1vK;r3 zj-HAN<{baFtCn@y59~Dttud2k=BkMtvvMI)ym#!a)?F_jO6%YiA9Y#V`E4b{^ViX) zoQH=@$sdQz!VXKh<~tX3hT^o^W-=zaxX4!>zp#0eh4QXMsmpLrv)eQTd?Jh=OaG-4 zx9ZSa+oV)4BWl;w_h|ouP{qE0{fE1~F0VYXdK%p2<{8(rXT5?swxg%ZEJ0th-B^#g zN%2EYmRV`J%e-mF^m1mRltR>Dqb{oI@@(2G6~)$8j3jHT*6};l3{AK9y*fCvG^;*2IXFK)uen>%zBO#a&)Yh7%y%;az{YCb zaLH?>)tggG_Xm2D$|uN|Ta8~^b_cu9&(cFYrqBL_E}sQ3aGSNzUubHJTq|wr{4E($ zk~w7MpZ%5@MeYIvWJ&B(O;AHfrp6{V)1r{zi3mud0Bq_9)01nC=G-V`ni_b*Jo@|L z1#Z%xDMK^VC%%kW{afhoVQ@Ut=hc5q-Q{X=`bjB?KUAnZLE;AlzgK_BD=8Fi~-KD2c!v!Ao=F-^cfc&v{zqK$MCDFa3(sR{C5yz>_K@Ahlu$pfOdoYnxbcDqc59j)8_NB^mS4sq)m4@2r03|J)_Yq zhhclu<8|o4Nb#-=dMjebqXDE~>CzsX ziswE@#ceCJ?7pBwpSdflUOl#H+O&sLYD|?CSmg#DlbsTY3MjJuBkt)=T6{%e6ZT01 zO{nJ#73tk~|FugJO>eR++)_lYdhQok(%K8>+HZhTWXg#a%crR&ld>( ztk#`<>rSTe3xu*r&oB^0#Uns`Mi6X06{G+d4XT4I$P9%*EcnpP2p%nTDFu}P6o2;y zTmQLp$RT`Wkv{MRMnGTP7ugB$#6z6u=$|i8i~Jb*~W%ablDxAL@^EPpJ!ey$1iI5?{8Y) zSdKSd*{Cbxcqgc%NWG%>+Ur0E%c$y;w)C5aKTK%3oWW{|qT zxxbY|rJi%1l=1yAlp(g7UtrrDKR=R!YmGn|;Y~oRdoRpii2>VDBV9oowx7lOGTL%n zI}Kak@{DyZiyu}HgBVy#X39RU_pU0va2&MfZl0U7EBrO!I+iz*UfV47C;hsa5MT42 zIo;^Yo(6+QH`IHoc#80*wTrZv!@q*qGYVo+iiuOY1ebE@?!g%8lE@foQjNUDJ@E-q z3jEuWaA2$Q9}MBq8(&a)jXo6lCmbT22=oSqFnQ2EOtm_!hUiS3U#@PTc`h^5ZBVc} zVE2IKiE9v~P)JW9ML~*zl=15LXh~KZ%gGh- zh(~xR0#Y2$zl#$3YZ*+Q+T4?9Jq*$a$5ZPph=AqkQ7s5JimiMp1W`{PT>Cj+nNydv z@nx-NeQAH5lV58>^4J6aPp)=3PFcTdr`f!Zwf#u7*X&eE#XhNU3Cb~P6HUziQ0JKZ zU^~vRdbsns^ze$|GVKDFWK~ix3ioC_;ndGg%&*kY$^)b@$$BC_pZt}6) z`ZFI~XPZtgm9dnbP#j9mPyJ-}JUU?;y{?v7Ic=%MXPnYA{(VuIe;jZX%>%Cq{TVs> zWjRmwSfspb<_-%|-K$$FBcxjasTxw9%%12sR!5}FD(*=*Lh`M+=fKG&5f6vykP0g( z0cSslF%k`JlV*2wY=wAzx#L)rG2?$iyn;N5?b+zlq3s;U%$fTfpR&%6d;YlhShA^H z&EeR$ZT41zN<#gYtcpRNq~><)n|Tsz=FbNoML4o&A<2nyWZ#7JQIumkSvgAA#ZHf| zzdruVxB3J~iD!^luk|nC@D-$_GvCsW@g?g%e+-hL@5##9Hk%TqbC)9-O}ru*m2E$6 zmum~;b=1DEpi?TlCpy&n7)X?))T`md+76giQ{wdcR#U>xszk$idE^z|#4Yl)+JAJm zdp5&EY_?5mw%uzhu}hBY5z_HH9uxBnO}r_?0b-@3SpXM}Kirh%$TswFAGQ`nV$ass z6zED_jb6#$-RW@BtWBIFGse2ZlR>JP;SBR&)*h2suZRGByxdFgc@70(Ik9plJ$>JH zr7wlw4|NP}qnp+}+0wnuzVE=8TVi`Cna;WWcDwdhfgLTn`&)WL=N8T$!Dza8e-#*t zm%916Okl);Yqymt*{|O%knaRGfN-_{Q=lq_WT0wFR;u;Ab+0{i`-!`w3Tf&tti5ky z9&kBV#5^c7n&mROK50IiHl!njdoiQ(bYmR0H=ik_y$7s|3WR)0OLiL}H<}(HNUg9V!Un|Q z9o|;6zbwa^Ts6nN*2l-ez0JUensELl{kxpjp=DS{C@PnO?b%9}qH+l+DMpHQ;}MAi z{RBbKr+O?(Z|`j+4pmC&sko#6!$-Yoxf|U&huALbPVDcF>eNRx9mxwEh|FPljRuid z%-T|6E5M zrt}KgUjNaH;!p=j=X)?pkD@iOA&}gY7Vc=e8e9pMJ1)&tRqljk2Sa_ zv&1TyjOb;KbZy9H2u##WdZ*B)CYEokM@yGyz8ud>>S?G0hgode zg4AAy1}$uWeKK^aFJfxd$V%P z)bzj*N{ayG(9}Od*?2< z{O~)XxVE?BauGHk>fWQSOc_u`9TWz0_IYoua9QK3K$HhLdhBdr)s=U9sk&#=TI|vj zNy(3GcgMXd_2z&U2OpwZ`t_x#K9N1dG+086ZahRO`R*HMDX8j(T@;Q7zC5TS|5I?W z-*u&DaMESv`^^RmVvg(NgU@74=^?3S^yq7jF*4@{>Av4VjZN?OnIHb><|S9VJ0L$?xlJ*uEf;`I{{}!hOvI@4&4TNP?;M0y{PK&-O=wd@j9w zI78_RN661?(4(&Lv&Y6<&BDE_&_-S_VVx|C2%>-ylB9LuKH4IgQQgjmxLnlp?|efK zlhJGC1Lrp7)~0{dwd=a%=*wOWJ!f9p%Z2!cg3ItT8?8~-b_ieceGie~=1o@#$}g53 zxI&OACyb3DEuGgbA>EeIaQCuV+ zLp9)P7^(QbA2hVdjgb&PfM=C^4hX4>?A|U=RwSrt48VjDv z2>2_;=^(2;SecjdQVgU4FT%UC+EaLU00{5S*MvegcW^SM-u%iPeZK=`bUha4XAxA! zcLg-&-Dxo7cZ7LdgmIIeWMMRgCJ-7TG$jjeX5rh5Q0le`yzY0bZq#+I$X7b^EwwGI z@BG|_bD(~E?B#N(aPE%uqJXDkMg`{|U6WEi+4#u)RNKk*Stp~HkB=B}^XkVmWfWvE z98c3?RyQW z;~)n%S5WwoV8e6M$y`m1T#&vn{M>eg+1`r0UqXKB4SK+}vL#35par?W({&~zA=Q0X z*!Z~()oQ%B%^P*M>}(q(_Bv1YPaE>D+K-?Qzhdv)G} z+{aDRnXNGy?jgZlt#%`88CBqzF-fTSLp>Vx{-OujY7XrYT-Ya=o4kygUi>=!=zHns z3%jpe+_h71!Ppn|=S+`tS1OzKcqY_;aa^yyxSKTNk*VjJ(C;lXRE{~UzFEb3# z-2GCyCclqrw7JavD z`Jn&d`Idkrd3$NsGb0M6^yU0)gTKogEKJsIj6(!c8csZmxub91Zby=xUw!yxarrx+ zLv}zje^b$H@OwoMt5Krj;_TgP4g)-vUMqIAr>GSw{1)d-ZY=#8TAQpypiLm=v?M*G z{p5(tdIYiDIGo`P<(@Z?Mu=JxaU7TQTxC>55=COR zi_>ctQSfUY8=-e#@o_eih?dbe7y;WH)`{kx{wE@~oQL zISEq02fx6Ri3t_-^;YI0DJZmX3Iil|NV_2Ifph@UAxKJ)jzBsEyOO+xT}v+Ezlj;+ zznyr=%E-M3(Y#a91;z=}1;Pd)LNe6an z7z5*8K`MdN3yF#e#$&oCAw+vD>KT=A$_q$u0nvS0kqn^i1Eg&HxA!+8Ek=43#TKKFH(>H29^U4<@aP8+G@RGg)@>k zFhvJvlw&HqEpSx6ZIaiKh4P~bp}kvvCkf81AG*&T`L@IR2<)8lKzldE1Yn9@+byV7 zayx_e_|CS+yR>65G(v*o6XqR_*&SnzR+-}KBgu>w(b*l*=(@g^nWEX<7H6zFe9V>N zmaem1U*lNcONX{p|Hg<}?c{Bd>b{Ez*E{S)TV_WtcN;s_Eant*PTHkWIV^G{mLDVq zx%=>@qUsv(w^OLjO|7F*D|+YzX-lQ~uV3^BBDOy(0_}yq#7ieC!JXYl!CjSqA0rB{ zMdn&y7&VL%MY9?HuwmLyJ^2D1pv;CO}tor(_a;tKB4y~S4ide_p+tG>iq#5pOvU2FUmk!hkgjKpPzH=SnvAZX_I#*W$ zq&o}0cwSr)T((l=*RL`z8*pV@5U!O?+xR_{lkUQ}V3}sI5mT2aVHKU$_G3_o(VZ0O zV(*CkBIXupS|sMC>~_mAZHZvI&&Y)nLr>HXP@tZ^;vFWaKb;R-jvF zSQW8RCT<-@ZZ!ra8#F^S`J0;!h4Veci!1Ix|MTUU4*9B}*mVjbXAL=jdBOlJhY*s3 zFM`uPgu9DEKwa~k&)&ZzheT)vYa$mYfQVNJIH?gf^A{SV_Q56&;4h(bM&FDQV1$S) z2;#qA5T#cn}2v>I)Mt^xpN3ONde^0w)6tPt{z`8 z5Td=cw&_11++78^$gNW|0<;Ri4a%n*GkCY1JnIb?vv0@3(ZdxG2wSpfd zSb6(5;Pg_grJUH+uWAI(s(#F$Lm( zWiuSkR3ABIUusHs>@r`cEISop2Ll?zcn_69a|~rfB?R7V?4-ye4Ba|=XaFIln!I_{ zS?+ygyQKV&9?4z@sD+T_Qx&v#Ys6YZ7jKoYYRGM#6196lKV;~}_f!H_0b;2H{V{y$ z0!cs`LG#~qxh@>}CdklAEp&i=x-7WJZ(*)xgj>@r^=s!VEj#xxz$R@TcTgZ zJ?#Ey)?;<9?22Ra#@}v@`-xrSWNwwdKN@|^uPl1AY^(7#N>lhoZZ#HUUP^p;-)G6+ zX##70NnCr`O4H#&U>sL^@IwRTZ)Z5l>Plup0%War1}abFTj91aDeu&Co7;<13~MGahM{BloXQU^vyF0(+dz;uTsBJXc;EUGAoEnN-Uel}gbN@)M(70^f&q;5b z=a&`shsQJ8%7_QHqU7;Ols)@dt;rmhsAfVZopL{eu~tmc$e(<0;LRFIc>s)N{vXn& zTH-VjO@;tO2mo`|*JM=2Yw|~;^1z##8Zkw@I3$pWxm2+t(w{gNQ0CY5Apl-KJ>nGd zuK$EVcjYgMh!;N7iWN6ML*kSc?GEDRz?B6v5_-#MFjJOP86GmGokI|3tFLBA(hz&O z&h!oWW2e?I)WVG8B?E!$)FYtln8N6#zJK=BA98*UqdomUsbTQC^!3=-!e{uuh6MUX z{~itQsn<6IAyF_JNZE`%v`NT+O~%>WIW;xVPToh*2FQlF1;GJxF(7Vt&bNj#(E1`( z|2nnITYe(82Dbt&q6jaA^o2PX`i{V3h73=D;d9C))gG`ZYIdlR{roLvu6?$0Z~0Sw za9gQ0X-4jov`(&{eAunE)|SqymiiH%3OC=XP!qbZS>vmUK2tv{hBIC*rK|fqKH;!! zec8lK^f*pt9;d8O6lb&`J&xV57^`79$rn0UQju>_ZZ2izUil{l{ib*t3|>r)PdVfLlKPW(8KQZI0!jCAu0vWaqH7@Fl3hvaR!ZrGUK; zzjN8GLqzP#Qg~iZxe0Mw_Q)q(NHd}LGcCrsgDQi7MH^xA@ZuS!B+h2Z?roKkup0bK zOO|YQ4B`8|y{Pwdy7S5Vso3gUrmp7&-d3j|1tBH0gaLr*B^UD$C~#}(0wzx$7@^7P zd@Ool!li>s%B>?xDz`~Z%IrqEC+2e_$_R7AaeO>xNyO~1&F;C0@r{}M%nct`Z=;Pj z`lNA7BehuDWu9vM^v_!112+ES>-i@&)iAA^O0KP_t8!+Yn%}7v{M(W$j@J@nKe5dj z&D)+n7yWw1J_bW_LtFgvqJk~c^>z#AU(=B*URxEB9kS?WT9iYKG#=_(fsux)M#x3{ zP~~@0XH9qc11uU@=&<=jq6TOQ`ZjxL1~W^%%Q%8Z0`T;-9zS50GkWJcXk4KAP`ScQ z^oscT5$4H50u1}znNSwGRs>YQ((Bfi-}>FVIHp}Qs(umXhL)(W^X{I0n1A`@#$@kY z>ih85sxj-|pF0z^>!{zeU6T4)7Dixc%$%SlmP<=T|3;#R42kgKXLk6?(~r!|h{WJo z{d)_vIX?6X3_-^FA@=Uf4px%qL%J&_uNaM^Y=J~!>7OVGT{$!x6Rf!Cx7F&(p%5Hv z4~$+iMZrNHne*ZYiJy`^%7GBZ#lAmzEEeL|>NpN6dA2_O7F`>8S-^&w7LA_Kudb2~2C zPq&-ri* z<_4+X8q77FGZP8T`s9)Q83gaOuNP$({nJ$qeC)1lG-ZQOO2 zvHSLw`@))YxqUdm@XXD$xY#qVnVR=y^z*^dWu4nK7q3cJ?ebBIR{Lhe6r|P?Ec|Y_Ml7595>(x_zd|(V zMzuKOz8IiLOFG3T{){ulW$tAE(4$WQ@Pvrd(nuIFwRQU>qwq74RH&%U0`_M`K}gX+ zk{0PMm6|QYazbirjhIlz8GryIhJs~0G)Ad;-@MdN#3VSh%(IuOPD-FO!DISm+fsWc z-ARk>mlcw7zSVAvbv#a^2gzaIicx z|2Wy${kYQ}o+^su{ks_?w-l9H18t^Srt-?2mLGk^YPGnya^&o5CoH3|=t z1Pq>W-~yITaM>>2;^i~&;Kh}Gw?0lP-3H?(3{s7j$cG>N>CO$ETlWxa71S zTD=qO#U`{m^6HK?B^V2_$+Nvfsf2q*m)QnvsxHf+cM4 z9QMHxrv28albb?((q@;pjPY4spxr$7wXKmbyRJG<0ePExqc+jezZZ4 znH&L84%ZJ&QRcUA0ygV&@RX*%L101E_E*OL0Q2wp^?WvPf_`EyabdZR zue)%4#(aagYh|Iy-_LCWeBS0SkJAh@Br`E;0;$dDjCS+|B7hd%Nq_{|;XN(tY%%eLDRP<#67&BTh1?7()M-JxNS{v|}5^Tn))c!t8m8f5}AW zP7eiE-RbE*j~3+Y9w!wyw4m>%j9KT$&EyDge^66^Rnh&q-;MXfF|14>?H49#PYXvJ z`6+4tgSlG3vy?g+BqpHMzBA3EqSKzFu(lXK(|N5^vZ_*7O6>WUu^fNQPTo_cY9zr8{`u#?d?85R$Y<`|%m%6X(%vx~s99N22i><3X@l1_M zqj9BqcJG@57~!kx^QlU1&opC(tVVcR8cuxKPcC5X^f32~v`9|-Q|&dwiM3HQxG6=P zOKYso5);3*?8v2FdTB9#y8ZJK*Vlt1c_on!M_p}QTt9WU48CzVieyP=TkqTxZ@q($ z&8B5E%BDptO4yyf$7e8qp!>0C1P~;~giVH_ziCuJXqKleZzP>St~e~J@Gtaz$-8WxXt zUmNZ~f>u)4K1#Q4q#Gh-LfAe7^_{~JXR*(Lga@^KvOtvNFD)b&`sd}D6ku)J(h-ob zS@(Zsu&-y7-WXM|B62PtbOPF{3cZu~Uy(edgEYH^KJKq)3cBaW_R+pjrX{*$2TGzaWl!c>nvMTA77hXWLMZXnY*uz z242?lXgB(8ZuG3XM99)tlF&)_R%jhE;XO;)iDDx*v>YMk1e&&5RELfDcy-&)c%#`? zkDswx>ALLgE6!fA{CK{k`}SIar-evOBWY%^Lw54eMCaHkl2)31(_+lN4`dCRE8$EP z+dr7im(n<#*11BJKY-UJNr`B~H|GdVx74qrd#@00Gmv}_3Z5jHUscPL>HNU|ltJl@ znSw$fBR^#`@kdM-AH7@Nj|!kxH2;1WU(Wo%A&=|B`7^^;hzBj-pf4Q9VK`-eq23GM zBzwp-<9RcO3{^z=NMZsDRp&U(lY)%Dah!cjFnaTzfvJx+Wa@-Qva8M^R7J#{@KgVfRcTwh5Djnk} zWw&!yp9wAww(bbQyT>?%tfh8*xZpz7y**WU;2}p}q;(!+%MUTLrr)AhbT2;1W_x_l zav5#<+i)3eaQwUG6+@MQ-RJt|ZtA4a(8wiQ(NSHZ{oEf;0!(*LaNgFlBSxV@6zkzB zX8&<)cMf|?M5qaaF{dck6*dNkH!}tI^&O(s&QpbMW0(&OG2L;T(L-bCY*8paU&Js1 zKg5Tk&laqRxGnhJl9%soXw7Km75n?o?K?_-Il6Gn-A8u5{~(~)DHp|;nOJQ5GH=R!yJ<(7 z(c2RH3o-{T$k<-kzO$T}w=cv;r~SN4vXwpi8z%R2Z-wXSV22FYK|WcTK{g?WsjqB& zkAseC%Cq_`bq2%xBOead3SVC6QYUT<&yQa=u6Dd>tIBLoYNZq2KNntC_iE9w zHEb3aORL^+f6^}6O|o<9XZX&GxifEGEdG=qf0nINN5Gb?^`Cb6&~9DV$J_n;O3{Hu z19a?C=RErM*{Z{$-AmaAeJo>l++l1HBS~4)a3DMOiXC6QF&29hW9Daeo;K~0y25og zLe2EL4cW4u?7#4r5_5nVcnZ$oa|M;QFG4Fm(yylsFY(xzFYX>);^||g zD`Gl%QD};${-;tohlHblTaUisqx~Pm;(Hlwbt*il;0aA&KRn2&B)FqBb(b7G-xpuV zo@7)z_=vm6)8WoD>iGH{`g@ptA8kK(aaYp0`_F9>j&po9UX2Wup}L{gH)*6&&hR@z zA^sSrXsufC7H#kbl2ShMKqcMo-^Yq(RUf?H#fkhr&}T4tpW9W(i&eAVY1npIBN=w_ zDp3Jo__o9i!}+OUSEdpC&e)ACMSOzy?&!;)qe($8&K>`;%jp9A&e*wk8>-A73V4ru zkZSo(rRGA9#K!8$071C~SF%S|h;m$gMxSBZEn`lwu_;|E4OZ;hSRL%>NW6hHa{XAE zRW!O=rt8o%Og%7zbpyMqD#VC+rbce^BPYFAv#wEvjkIX7s_j>aSC(;cZyV*_FqXY- zRUb|C2^uY0SK7Z&ZqZEFexZmRZ&TFYs)a%4UtnOP9Jh#fONoq9e^?Y@BK3NqZwRe!PA#T)LNIJlx!~u-6}(QG{QE5!MP+c zA~#PaOFGquV#Ci8l1SLPS7`vYrM{Aoq9X|?n46ff;Jww7tEVkdqw>h^H!QptS(q-; zgiPHj@z|SCZ~ZV!K`Cn2-S>f=N^gRUtyta*d-Xj#X!%6OwxEnJ;1PG~qhhf_kG>xf zq1NRu4!%+heJ9++Luvk&DN`oFXqVHuGsC|_tPEA6c$1I^=@IY6M;Ole7l#tmaeZYs ztZ+J}r71Th6zMK*FLXY`nbo=L!tvR1nTucVSpD$$WQg4Nt^WK;|4U$!rB3@3{b6G_ zmiLxZK4tlmsS~NG=2Z*0(Waw zF7c9^3tn7RnI!)%=yYuRY0;k-v4u(111*g|t*5?!Of0Ub+E8C|%v#yyZKH8%eS+O+ zULUV&QD)ONmF-JKek}C~opEd=Yi3tNsFAI2V7!7_&tRhm<)eOBkn&M~M30Has!(P0 zmr-NCbJ$FPC~BAGGN?fQQmHw1&nUTn+6vot^}_F~{a%l274WgD?O+~2sY2ElNDdZW z@s3~@;8u-*p%Jff2kK4VB&|OVT8L8MT@EXRyzelu;VThXQj6L`gGFj#H!ziUc3^PB zYhmNjMWhnhjqDUOh3!l>84^mr%_=Z@K(u@B1cPc7&SH7|sW4hY&OClph=lG$A`IyAD zST_V!hzJ03w=itP99A&Ez#;%yghAb=J0A;^I{dbz$%z%joU^gwa3K}p;v;H#6&8?#R*pOhs3UbpVl<8swl+- ze-qUBAR3k~HxqHFa!ypkU%$_r{LGBJ_*#fam}`^)!3h8pYA$B{vp zLMsxd7>&q__*nAdJ#nlL=`7Xi zOQdObICNi**2jqGYI+~j!}@DSh0foLX6>T zJEdEhQh#D|4dxg*%HbT!9iaPgbQV2M9p9hVp0DCqK8++@4>v{J8fY&pcM%xWe zf&mTw)3hRi_-}=vD&2+Na_feU@B<&}AI7)~-?5DQ*|WcLFqnW|*8$X}k2h7hZ}H#s zKqs5FsmV3A4R^iPGv>a#Q?0;vu6Hgt(J#X&Khct>L*)j$BA0Gzj2&r)E#_89m)}DE zijlk1AM28io^12849A~OdXi?+vn;;TAL3vOaV6g3v5(H0uKMEfv^>=H(QA9xp}l=O zpHg9nPf-Nd!$GAO(YKWXhMLq3{pC`JV6v>K5ppAioV_B^%ax}bi;4X#jmA1Z>( zJO5Sq`&q1WG#sy-9bftc#6+kFETPwOL_Syw+F%p;w*>iR0OnO0CYj1g{ z^cl7R5oiH%(cP6|5hnxl9tRg-#s*kxMPYh6AdOQXy4>@WY*7KO{# z!Y(%Ux@8gO@dVKYZ>V3{5k}w|ewkq9tn3zP^)olIIHjv8&p&pjFFjdkO@Sov^gm%g z8@%WUuPPPtG+%36a>Pp0cA=YJr<2JVX3!*jSAkp(qL7v7&#x@T!7Nd_D**GNQB zz-liHRehi=WDEmd9C{kvpwMCK>U#DbSVR3y z#mih7F?->U3TjB#|7pBQG(t-n)_4-V`V93!Xp-e_2z*$oHQ?2E4u@lmbHz zLnD$31k8Z36%as)sdWe>3y2Ae8*I@O0w0MO2C(r$?jbZpG+aOkqR@x2RN#_B4*4pb zy~mYzMr3t%eysh*!5&RHyQv&^P4XqCL#uZ;>J>A`{XZ{FES>i!6t47?b+m6hD4J_- z-|$)K=yPXdGg>F(QOrX0sg5Y0`ucg?)S4?B`oTld9sOY2vUSI0K{XGj&UWij)uolPg)j6(m?L>jyO`7Ce!c2sqSm-Xe(^=ayKj)@2)d#v&rUDl_{=s08*BHrmp;+#et5V=CStbtqx9{M(r-wm zBNo~rYcOx1!bSZW-~bH+AVxF{P=;t2kSdCKj=su7_eI-U>1~0A=WXEysh6WSQ%FilB z70f!rQt|Fz@h?E{tM_C6aDUu%YTbt_F?vkpR&w@2XY@lTs(!!!PDTY5nI1(?S6B&1 zqL@O&ZnnuIDlY(`#4b>U`&1(UmQmvrO-dXz1$&CxH9Ew)5y>Gd)*pAFmUml`suZ0=sS)cFw@_+O z%Oi_ka4U=Nlf(}5(<2K_1i;-_si53_q(9vKAtlP)huqfPSKdbGg@%ADL#YC76bBoO z)J`cVs#d_=|4%t`_n~VL3||I4;O--%!re!xqr``PxK;JfyC2`@h=q2@-B$%F;O+ws zV@^UIq zyG5=n$W6xj#U8KQL;qvmDK^`q=JG0M#?CdWkdH1uGu`e=i7g)|7|b%`41a=$+A9kX z3O{Ew3i3l^5B^mVCD)_#Q~Jk&Y0_9!&g+G8ytfr;LnH)kkDMpH9KvYmZL|H$2g7U~ zOfi2S^;)IGB2-yLkAqFk_(b#IAfB%K4W6!tHzR=D&W5l)M5eE_)`Li9u7FSh^O z{^8&B1Zr4o3~)oCfwYAMg?{jppn~(558&C=o0ot zK@rX#`5II6QeF!f7#<$D6o^?Clp!A!0RPHdD8KkQIOyl&h()ekkJmRi6ZoDWl))9@ z{{i325g~fH%Vho^1b;%2x3@*ztYYa;vzuk&hu4PCb((LlUmvJHF!ntS!9r1)*uO;7W5G)pM=^u`#x?ICv86r^_a zfkaOraWJnCsAhdXiqG~C2{vCXY(9nIhuRj^*h;bJ_B1d>aFh*72$RLxL@HXqkiKPB z=4!oe6t)TcCnvoGpn55@V^KHnE(A~1Ml*u^b3c2+_3d>2RYegh^s%%(!p8+-zm`i) z3{!TWb2}H9s_$NIZ-RRjl|%gO7GEqSaxAw`%$`F0ZaJdPN-gc12Z%Y$nODEMT`lF9 zatOyr?Twhi!$-_2+Ze!v%AdzsNVv(>XS#EG4(x?DR1l>S#_otxuvx?di#e}5;=_tC z?EYL7j>KzOSa0t#d}8WG2>6?$qDBBa5IOKP5skqlcO&CZ-M=F{gjzi%-Gfo50O;p( z<*LOMNQXLl%LOzrG#L?@6l0YvY?C4DV7vUSNX_{;90}yf+>5d9{;j5UnggYPc z@=yELOEPUVn7@bj^;u(v>?Amx^Mm;x$CDFON|8mi(QehssbCp$OWr5&xRO2`dbjjD zP)R{Vx7at~$vzgqY^O$CpP1Dy5e3Y~O@2a#b}`m`XoTmesU>ZmUV*s$IRfH6{ zFd&Fo4~_*U6t50XG;jLU2Eu-$*Va5g$``gnJ#_wS(RF#K$6D)kvO*Ki-T>~INOS<% zLIygOGi~#qmgEcLxO)XKAWZvTMW-EGdiEMwsF4f-*mx(@g&+_d2o`j1B?Kh0T7PY+1_e+tBHt}TNC&5XIoHtIf z%+3|H>@1y4<-Q$mASgNH_M{fd4qeTyELD}WR7A* zV`f;p>Bym5w+TsCu@j{Tf{Y4bW5NY%KQ4keqZjmUnXmiE!uD|PlpAn^BKc-8L7n2< znNwtY*7T9X1Uz$zB?NhSL;kFkPyVX=ryk}p+qj@md@O*&k=<`{y|_I4Y7Bhf@6|iY zu~pP){3dl=4kw<&X!VY9;GBzsSf7S#Bqb@ORMnhN8#}_XOeD|z6A#y+J*FC&IGEJoc1sCSc(Im)$De_HRbzi6@ z7|ln(r1)>t^UtmM$AFkX1MvEQAE~RD0=x}$-=NqAoo_T_;K%;isj-3K5rZCX!ovK~ z9(H7@fIR|0_k+_(a65pvu@2A*v5`a!sM-K=i~9dm{nx#a&EEzB0J4a?>|D2u_)TCd z1Ud$bIW?Dq6O;bcR&Vsq%uM|>e%y7^dQ^%?YCyh;rwc4eB(f>Qd{))p<}@w8^fc<7 z!1CBH*~{?l&BukMN51!*mQbNZ0wXKojA@QpBX{PQ6(r{s3m-HoNBOjT)He@EqCO3w zvRx=UMqG#q;H1S$VEqe3{SSs4htq#lfu|D&NgSXtPz6Q+nIImv@IE%!{k>*Pb5f;C z(pJ1`9Rv0T-j~IaKQdMOr>}I=7~U<%QPUq=%&?TPpeS0Xl78rL){Kh5{G9P9uFg4x z`gJAAGiW!_{^ONvnZDy?q-QcnuQ`QQu*O*{-tF`d0n>x~vx$rr3L}9xiZiu8inIIw zP@L6BDBLK{&R_mbaVF*h6lXwVhESZ{xlx>j{85}W|52Rn{!yGEqx_{fTau@tM_5C2 zr-%X#9m=CP1J{sb6!ehfonOdhAvlE3pd&=iIJa-?AX?C0b5?I)iJ;%Q(VWTr(VR*D zLvywq2Sha?Ghjvv2Hn^~WXe#T7SY^QIzf6D3Djdq$nSuiIkC(`i=2U1Xut?UQ%|i0 z3uxc0s?mrEfwA~J(ER}oAi{V77b6l~p>;DZ0EK?_+&uu8Lfp6wPy-@bf{1m1h)>hR zdJhpE5V5%`Iz_4goNeR0@yf&fJndtx#kHGo0k;47mu)&ERkbzS;rxY{nIum_4^)XzvwF!DDxc`ezw_m=Q( zW2(?@iBh-h9kM$IRZZJRJBz02uD`Ps4}8}VbdKa0?+B>-7ztTa6y%+QS~8BpVk2+C z48}XipndYtmqO)#lLr3Y?XCXBfxsn}B!H$z5Q3!f4gug`&i>!}0&@WnB(M!Ojyi(- z%+)>eP$$rzKv4!9^a5Gb&kIuoLjZ_wc2Ejc*wX0)BLtA{8>T-_zQOPiL;QQH(xKAPaG#fRF(uOpyDp8=9Ab&Phq-?v$2@` z1b!D^$9R;ZHohqf#!5fxD4!fkB@|kYvKsemakuxFu^RP<(x-}_ecw#^ z@FjSmrl{V%&TnUOZoeVg)6tm1Zb-Z;AbD1dKIeFbIj!N?U21x^!FT^Wta0j_U!kkD z`}Zu#-qx|=6_?Xo=3jQ4!veGZJjSnWr&v_|{I3io8&BsOX8<0T-CzEW!u~3)FTeM# zr+Jqa7t0nMgQ3w@@zPV=6Xnl!So&w9o@8tZ{p_7B?rcY<9VZA^IO6jZfGOg$DZGwh z`W_Oa`J7FLcHxEK-F;`w40DUl`}7v?%c8MF`gHp{1ec?U_AesEo2=cQN765O;8eT? zW=ju#_~x1}0e_<~zR;a(NJ{RoKlnGPtzH?J==2v6R%sJCZq;i zd?MTj&PT=Rqux>jM-SGIzOJf2sB4GSS$G+>_&lY`RNurgOW$d-I=-`d*PH6W&uU`- zkDH|BVi@N-3&pWwt(#Hv-#(t?FZqp+(mNNAjYb-oOBa`#Of8iq5C{8V3Sze3_%=2F zX=DCl;`KWzn`U9*5^esrt0}M3yx2wR5O7ZLuEqZ`)q^X{%6BLM-~t7U>yu2t&mf7^ zX*R6aR@IM?JKgW&zbY4NMa~t(h!k8JApkBn(3b&;_Ha|+QPQPKmT*yRG&(1^I$QZR zG*Yph|EZydsIz zE2Eu71IJbW&4|@0pYA997K!CSm~Gdtw{tLP8B`g4vq_UG6=M;^IckS=`}6xojS zSx3!%zc^X(y53{J`;i-brsIx$+$|58)X`-&>`yWF6T!sJka$$ax(ZCDB^Wos+vMN) zjLy}h;tESzo_F4zXDx{^D0QO994VE0J&OB`9wN?Z*-s=ga_;t)8n?;)EoUe$mPi%E zq`Xdym2-@S^!8@94n_ISPb+6iNK7jq8Q)w)yJNh?-qZ11D<2V<;_ZG?`UvZAP$k!~ zkiY;ch{`;&v7U)*hH$2`$$;v+)_>AJ*?`NAO~9EmAb<3f$T_FP1dxBU`LBj$3jIF= zpWXM)MiTML#_tIl`%3@-+tlfm| zHcxM|&cNTTO~r#36%Wkp@AZ?GnNZ*2`XsJt;}(yQr$?0qehSTq{CWbz623vn0T^Gj zwL8dJ0FNo7Hs%91<{hief;WA}jaa@${6t!~XUUVkRJMnLVLr5W@0IhcWICABFefd% z6XG>kz=>Am&rEuY`2JvfXRw&9lTO@kkfF*(nDcS23EZZRolS@d^ZD%X9vB6Jlb}DR zNZx9C1GJ>KD}W_lp?VM0mTaN~SmSMwPLzOEY?6)BMl2HDyLGb)93>h2b7Y90hVYv* z)$zFCJy;RlFhd1_^#q!0^;8~O1cF{4FUL`G`6anwgjK|l=Rw~sBb@`lcwVs#5 z5t#Nb&UKjHMl>F-J$s6wJRbP`2S3apm`=i=O$9mbDp(ft#?kd|%(gemZi(GbBH=F) zwMf))?{A~z>~JARcT3yi)>Be->#9n$;%1N251#L6GOVRWYl7D});^SN@~x#oYq}(kk~2vw!bC1H{tUuE_7e<$ zqQmvj3o6B;{)5_Ce?^ECZIP?j6k$u6YnI#?lKmi)WXw_fQ9G+v>%yHaqA`FZx%~Wo z4S9?$`(WX=T%KP2=ci;5x`6wUaW>i!&Z1}J-Ycfj2n4Rd2m;*;^yLn38p0f$Lb zACmEu%trOoKhaR@A2JjWXeh2+dy5QmAy$o05db_|E$KZTKpyMqtloWN&;Avo2|m8l zG~;v-sDJbWKIm}fiZ+!M`vOTk?E>FIBC4qUFEkWOzxf~BQ~uc-Ns<;8OokKk3d7=Sl8?&Yv1V? zk<3cbeENLUNgD4)=TVKZ^g+ zjLB1Vkf-x6mhK;me@Xkd;!vO4>1U@`#S?mZ1x1pU_0&tMG~8yU#{TEar)g&(zV@N* zue9(aE3tM+gp})pqvKieIJ~0|BWC+!xM}dkGSSHo6qXZnp8gV*X$&U7c}-KPph17r z_k|cHlg@L7Ijy{;fJJ0?i#e@assLrqs5^wh%znzgbx32ZTBf&j<))s=E>d(yl8Xrx z`WccX=eYp%mRjgKz}XZtgW!uCh#-(~oJG8FHhT=oEaic(4B(IAh1LTQB=VK=fX7i2 zXetN-qT;0ujj(H(a_NS;;%Mu&YZE02N-vJ9nARIT$g=Oxaj~0xq&*MNP5gOx5KzNK z^w2%|)(=(S@jb{#&ugK9u_vp4WniuZF&Fdir9dAuo_xSy@gc6d|cKQ($Pn(>RZ;d6KJ z?wYJmKW$>W^RQ{CJ|RGp6Dh#ECLX!TSNwnuYm6=qhJ}3YLGj>j$+H#)EOENi-hd{z zH{o|nlt)>R$GD`4&{7F5ID&sRrL=f_14q!t8cT#8ZZ(CsG?2rVuo>oJ#HG>fNHs<8 zDG(yVdGx5oi==1;?q3JBHZM-x6>tozrgPebUGa}JNzC~DxG5`XpNtm1lW#Wg)eK<% zZbE2M?Hw`Vr=|oWiPMti-64RGf!K%H;e(FaoLi7jd-C0p)%TW4*dzdGtQ`dN1kg$Z zG|EgAUn_Lx(&Q03+nZ_h|>nu@a}gfFE!Rt?0Ham@n%$Ny8g1}Na1YJRM^e* zQo)Y>t4+%~QB<4cwMpju)VlE{vr*&GOO1<9{&2aHg@fWBFITOK-qMWlz`?bX(DG*j z`yy?}!k`UONDhcw1g(8yD0rRkH2lISs?cdz;zf&cgvk6^tC%e8Iq(Bu>eNRF)$hU< znoeh)s)!|l)=J^QBEA+(kEAv`Q$@#3 z>YeeEK%H|*pzW3ACxN*1Hik4IZHx-7pJO8G6uuV#IC=W`~qG z^_lPGdk$KOlI+{Q3D~2Y-a;)PfXPBXsu!ylFA4C1$|}lB0`^o@c7A?m>)ExqmD`&Y7OPLM)WDVN9;!0l{X9?JW~l z59gfDR+l!^rttaO~t+E+REi0zzgR2`t?KE3zqZ1Hx$kWjNJ~ral{K2Z5w2o6GuLZ z1~+ka|7}tL6;WW$1OR8H*Ce?u6n|Dk9aC|{iU^j%)sqiy0EAkUnWqPFbQkhJs~K78 z|70#i>unq@H33X)>sAd~@o0Vb){@GREc_VQpe3})j4_@(G2skLvtE=C2<;~`FU)`{ zsD+nKgf58CO4{1%udo)4tp7=CbtW@_^9zxahMP41d9xkegeu|^vEXpQte zpdSH^vsn9F@scWq;r%VcpKj34Ou}ylh*KZglxGkc$mL*Vt;5$MHp4?y=)0U94@C;v zR*176Nj;!hrVvGEC#oIpcw+VuYua|{-n?SSQKGgqLmZZbjSf1tK7)%I+r3sUA}=kr zd!gKuYYcAK19At%8FR!L?E}Ei^;{H*^7k}xla-BEzA^zQ&qM-VWW$>+*!l#Xj@|rVdVMlx&_}+^Y zBR5k-k;PdhUx{<}tUSg@B1eK>!2f5G=8h3zN$>+Yj003ic}Cb(Y*L%ik3M#|u=Uya z5uYA(F?k)+FX_>D5U=bKsDCFq6a2C-`|b@pET$CN(*dU)>(wgwY-=r ze5e-^MvyqTi*i}szh$;y6=^Ez0Ykei{Gf!Wi-?ImX{`s2}zx=SkGQ;CZ!p}S9036 zYTWi$FdZe*;GS?)aB6u&fQ|I{1rnH|g6;hDr<~!#3vo$wO#&``@qmEoX&JPj`6XL( z3Ooc&6i!`Kz`9pfd-LOkW@qaQ9sIrAUC4ExbZ_;qtJ{r1aOiw5JD+_x{C#Cj(IfaU zr#YW>qmoNb#(<1+D~OoVJ{T=hPzF2FO(sa*J0nCsiC#K$OHC&8GA4a6iZx>}?(u+) z=7#|r-Fr3_Jc?kmMa(}z$z@X|q-awm2J#Xhf7kM08NDo`dDh48_Pd7Kq{OzayraeZ z;j*I~-)EEYl{f!g({xXS3Go&1-Q9<(gJZffn`oTheZXZ`Kg3vhaRC z9b@y}E_udqujt2nz9?plrtU6D|RHf1P7M=M?t32 zs>6_FqSKzwd)nc*5vxfqpR6F_v*A}mArY$vU9`aV_R;E?BL1-6K|E`aX?MhJuL{#;%KgXmee%# z(PXiquzBcXKtL7;GLn)m3QAlN8kghv$8>D&I%1>}7bftPsE7m@|8R&EgqHzE_c0Gk zU0@Abgoegxh>bL6tM#8>y#QQZgl1m?Hdm(j5V9H$WMp6yGX@Y_OCdj_UGuL0xX^X!{~aF9xJ00T1TPL*=-vFF1!!b>2^@yKRA5G}QrWVn7WI zz`azLPEPrdQ#tm&qJ6Raa(Pazz*VRfR)SM9tkpDIcMEHbqv_hm5QD!BxAX&_ehAowX6Ob8 zv_)*;-qka&ANz(BBpbd+;;0s2evXnI4)Qupqnt^lzQ|~{alN02Fq?Hyql}-2HPyfN zTK;W;$EnML?Xj_Kfmg3Byx?_?(rtv!^BEdz_ZL0~n`WBv*9 zfCSy#yC9%9GJk5esJG+@YRTx=77m125il;w$n8s2Jwhq~B>Kp{WS(Vs-;SUOVN~Rc zyuoWi*2Wh{)o+tmPSu`sFhq_#vbh6ekGsoJFh0wHXbY`x@kso=X*H+mwH^U1yTEot zAny(^Y|0iDJH~!ujHXvUyUW&a5@OQp*R5Sz;TI-wPNN(8OUt?%Y>*m&#X_p;dKM3g zR;cdR|M-{z0t2!ShR$e4Hl@JM#+T?5d)&y*V=^UUv@yqK=S8lN z_YLbISw!R2QExt-u@>CF)|{@$@=}!ut=!_$7$SHXZQXdiB2>Y5&ikp-N(#@&^3vGW zEp_0lSY5ih|51oM-UNE2egzBv??G;xpIH(a>Pc?WnetoMk)oBjl!q@=ZGILQ4tzEA zmdW(n3X-RpB%!RdBjsm%a93f|73i?Y`@d zFyo$c_N3SnU%#^wzx3yJKI!d3#r_`0M_bAg<+bh#b>AHIm%PGqqu!PGTiWeeOD51Y za@gXX4(~+l*j%18`U?`II^-lmCost3^zr=8fUS327%S&;A6Mnu$kK;RhBMvylV?g4 z3rv%hDQ2~&2SPse*>$JejgjuF`xvl}NNSE?I0non!%@$6e=@?hnC77Y*~E(hl~6ZI zmmC?T?Ng+ISRYBkiZ5v-6-#N16&C3v6<^XBEAC~GR9Iv%RxAN}?=xe?m(Qp!eR3>o z$&o4pD;o5?C&c!GM{1SY^zInAbBNDL&&H>IpDnT&D>gr2gU?B}odoRKQ9u&0Cv0^> zrzqa0WA^67hy@dY@5x7^!9)jNHD0@5*naNrGqHCW2i4$%va8Po&AvtkLAGEwWZH=@ zE~Oa@d{H)R-jW|M$|5XQ??~6^NLPQXmhix)M|l5@ksAi8%^MTOijWeb35a?}tH~2J z9>E^+*}aOcjsE`Um%ST8LcfN@WP4(7lOp&KIXmH+G zGs=u9G^%l}&`lV$?Gd(NuKfbN`P?=M{lXhqNMQM>eQ8#ad$e;1kt>&$dBF7O1Q?X*!ZY`0<)6`|!qFg1J?FBez!;M4qPIrVfhR z;*&W)IKtAe>c^7!Qmrtse?%zy}L$J1lse%Ox*>{s zsiWz^Ta*5*@_4Ivr<GN?7{Q3tE zFdbL5f9U{)!tq-em6Px0D?p8kfRMV%#(QK8R^Ttr>$BRvCwuiN_)nZE-U*`EF*64s( zr_`y7U0DH&cGb=m-9%#LWv1`3{D=8nYWl(6?_UyfKjjWi6ZaBVAns}Vwq>>(rmEq% zW|0CPn2_TJnR|jRM4!jdSSBxA;45M74nq+P-XIGWT;lIKZ5t+}eb#8l?&Ptb|DT=x7&hb4vp!B%op8O@je6^sb}m z7EnqeyN9!E3(Ohq{eYLb>#Gorain?-i0`E%Vd4q1Hf3UnJMV%OH!K*%j^88`$pBC9 z0UV>Zr#mYFNskYX(b_}B&&LyQg#wfl99A>w37*4qoXw8>O~a-W&WH~=j20^)-n-jrAnPfBDOzV{`uGs zMZWn7OQmudJq`u+LFiIEFb?TwXLU`~&G>2~bVOP5`E$xa<9t@aUE#wU@`?QQlR;lB zT7hDe(b%V*MOf6B=J(S)*{G0%3NhYVryev0nn09znHbdWr+TvC1qSW)C_TXczWvOa_+(uweCTP9$3+qgs6FNQ_gV?ox7Gwx9wT!N z2JAO7!#_WhQ|HfT3%4SZ8$@U#G!oxXAZ$=4;cWH-a)Sjx1 zn-lzt73WG%ZbS8qj^$#`lKO|JDux9cZ`l}sp}gjn^UNW)DUObuY89Dy{ODwH*nzea z`zJqf6U*+t%8akSrZ3y}SVDej^LHnlkNu_1z0j3)hk8%fm&cb8UJbm}WI>!8AIC|9 z>REC2@5MbZJM2nb!m-%ehvYQ#)*7B}JSlpZ{V>zZQq>uq7oGAKhj%PT4BNn0qw)8U zzyibKr~hx4oEgs=%2;Ypp4Ay8q_2*92+ztu3UFpGxVa?hW-kiQB&uFI3`d0K94shL zs~0azx?qkho1Q*=Slsozz#RYDl5A^>f zx+7ej$d3Dt@x_I=H>6mbhPd7YL}J*Hn&cxJAVR>Zfao@e5I5jO0wG{ajGc?IfL(N$ zh*OQz4`23#Ti=saTK6iPC_SpcdF-) zJ=xzKR?S)iMW@7*TM;RP!E+j>vBk6ktxzl9jUfUWI$z4u36SlLgT#w{bXOGV9l(x9`Ey zqbXHT_|V8xANJs$oFKP2xv z_UBY+6+JX5R%=aHZ@saTR;4Ko(>&XGJ;tYfK||!79iEjytP!e}|Inm6lBJTJaBPo_ z>mxg%9!2T((#rh#+5=aXNo@U1hpLIl02DIn!{lJ$&v}2%le5c~xKk?pM~z`zw#wPvhHD zmz_BxoWFaXAumVVA7e>VyyXfxQ~o(wihFWkrjHk+C|k8)i#y8GZhFw<$9_t(<1a)f zEK13R+FwX8pM-U41*J;=m2ug{(eZxUM`kbCrv9(DO zva%)1!SGu-J_G+hZwj7c+EECAf6Y=czyTEjz3GiFaq%wVWv5YR?1pZBDZu z88}$#cgI;gjF=?}Ja6530-SIl2l@h^_f4{j6Z9Y+CH-89$9E!O&KXA(TCy~MDef6Z zBwCGUekio~5kkoUk-!JWeBPac7LVZNHmVf|+T^>kq9^xv%WN6uqVi>ema(S(arW2C zv^Woad1qZr1v9MiVqH-?YdEmaIGN(h-tm39tJ+mMyPxSNOWjgE{d`L!Jcq$Oyu##W zUnma@ols?D?FmUMEjon6waub&MK%)Y zQ~Hzq#eg?Z11eWRg*`t`XJjMx#EYI!RR6429-zXDEl#hdyr(<(uPY-<`QitQ=?QCy zwwNDfP;?%TpLpAS?rxjyRh1t9&mL>#Z3YFTBZ`RhUH**6_h?gKuqGb#Yc%uF2VBT_ ziw|}i&0tB)f#%&*8K_3GU5M<0z?aQszY#k~5J^c7k--#RVJEBY>QI#{0V@s%d-$bcs#6V+5bn5jr_j{i|;AlHzB&%CxWP-pIE$=gDl^%)HP zz${A&jmNb$fusyj(l0SC?x<{!rdT`P!fiq+yd?*RFYzi+BB(;y|MT|xd{)Bb;~iXP zz|?vz!b)n^Llz3TwLNrh1N{__cYVOq=zm;WwJ4NBb7r}GP`{W~#Ok87d@wvVoZa}k zzm=x(-EYF2(rtbpN`sn3t0iIq*rF9_B=<{wNhE`0>SX=V?;Czf8(uNvG!g7$ z>DD$Z%Z&;{vh?$1?iN{FdH7LIX$ig^^F(i(?Q}Ak70+Bj$g9zPy-od@NvwG{zYx zKle%BhEVv_n@~6oL-=k<(r^#{8VzRrHyk9+W#^vdvC1rRUG~Il`Wo{Nemph_w4Uqx zc6W+#R66O=lA*hdj(XHDZZ39Vuwf*Rr_eiK)~alBF6S)qh&U%Deck=b9!vOC7F)PR zmPptWP!T{+Wk6mAB* zj?VrJB`%Se;5=LXL=t<@+#@>19(j^){-}87? z-mIHH@{|r8MTL9|TX@-+-m%t(po#ggh}O;fJB0J1^o-rMCiJ~prDo2)yf zW4pGgS19|_dh<>rxh|NDN%4K7u4o_QSo@fM6&;-}oPnNr2xEo>oiXb3`Oc zjZDdj;tP&7X`Wtq_uaptDO@7t=J7iH#EB7mfoJO7%lI)C zUiq}dj1N4pHUWtEC4~A1f8I6^r0zo?l6;i5XU}UGH22pd81#9qENogMBceWRT;W9w ztGV2RU}oQ09%Xl|(VV$^9!9DcE4c1@;bZStX&(PtXn58_;qDN3SNb!!n&F%$cZefY zihm$+vRwBBwrAI$>aO=qHbjhWYuxKL&#|n;m+(LnLpsZEl}Ajur-ADeQ>1dD$vdVm zraqBRV14C+yqAdxh-j(C6=KHq{2@0u8M>k2Ml$E7gn>Qpw(flkCL!_m@no=k^6K+& z?7*q)P>$y@0l*#E+fcDDp0{9Zj!H0ka7Y0SpCsOXT!xmK?LpY_Y|6D0xgyy|jRR~ArAOa{IGl>!cfYO{2*fD)y>@eoNh_U<Xj}q`I z)2%)%55kKdw^*c3SCt6qiB%pcKE76>eWgsHBsYJ-l$IyF`sGo)N9OP?PrJ}b2Z5H~ zqf&>%3h-Y)n(uj%f2`uh@Mp^MwNmgG88QBpQ?U6`xOh?nHH;|*J5VzZ7dcvK4Kq*y zM+L_d{(HGsR+;{?REm1bw2;uCiser9^f+VZ*!7P4X)$mdGQ2+fE&n>DkGi)Nd+_b) zPV&`yEk`)EFRcM<_C|l3-=6l~)5cl_FV{0&smA(PQ;!mb#VWeao^DMk>N?XiK632X zSxNn0dG#X#P>SUK!PcOcdP+O|9N8V_)(-K3&TPO$UQGYsXr4P+a7{0$y7&>fLZLh09L2nLbCDvWV$jQ1lgh-Et80R_;tC`c^Z7EKQOq{oWE!cN*b`2nA69K%8CA(s z(P>azg!R*=(AC0Ib*=kH15f{b^>RN1l{Anz%FlbPmtdLB1MpF9nK;(e) z8uMS($f9($*ocHsOOMQnELXqPFpP;8iODw+tX}9oox3`W7CP)Uy`0kBW;hTcWrfvAiGe z##(|bU*G3>Hoe|l<-PBFwmEp(xvr0yX6Yy?VrWa}3Qm9l4Tu@g39X{!|9y|u=I4|9 z8R{(3(%pbB<1i%d{cxofNl@H-5>SGjvApzXz}Z>GMnr_DA~~5*UquCti-iSnkvv=l zEQpkZ7kW#(;zO?J(qN^ww2I2|-0zoqk-hNFHy4jYMCd^?EXqo25|^A9O-T`Ym*RKt z!FTE@kQ)qMI2M*5eD=_e&Nu0Z$FTJCQ9MfycnqL7#A9$~xOoi8Sct~}Shrym-QNkN zk9|JJhtUVg+hd|{3E)TrBJt19{+p_RK2VKF-$vYa%}SCT5~)@!8Lzij4tw3x8qU}I zck+mGhchhBRvD~3I~p2Pta-{em(H(jB4&(?l~}eV?d9q+C%3l_Pc!>h3>&!;UoF#_ z_8YG}->rX9n@S4Ml&8_xM84=;LCC3-K29q)8}w3v_D$n5JPDZWZop?(U>9l}GSB(PgQ&xeXSnRQnjxqnh(QE1B_If`kM3#Gj`)l@Y( zypPav>bHFkG9=)<`(75iuy%^Hs`w84X>_WG9((y+$EoE~U7|Q*b}Z^RN_I4HZUH{< zv06ufCjJG328}vN;S+LT?@&Hkpm~jVbdw+jK?j#$^rwqP`x-oMCIuo#acg=S0z(aS zWOoRe#uN00Mc`iW9}eA~Kc|&$x^cnR`c=KPLz{?7`4drKygW%@Ks!vCve3@%vQ_Th^6yyOhx~wcfukM#;gpx=zIU&iH~w3y{xDs{!du zt4JCDdy16)vJY8$H5oNXkP4^f@e^>8W^1hUM9HRe<&aD-}ei6(i7R5ef8708z zPAResc)^aYO9T^bOCVpSPvq{JbUFJHCtDT(i4=Y_t{p8iOq*1_Q~7B(F}{SStWKPa11rq}Lhc!w@b*}gm_IQ16hh$`TwcSe~q`S~Q{BbRUq_AU>c76Lju5G6;QRWIo76yza0E4aJ zDFa+$w#gnY_t%AB&M?*g>X@rn64v~u77=(`jK84AN}i%e>PZw$cEz^N>o9D=29^mW zRrutFEeLZ2mu+JFCZKhyQ4&Tv#?fBlo(G;0|H6dRB#8khnROu~j-t{6Vh3-;g84Z} z9WY+#c*Hov({tt)x*w)66Xfy}qa-b30Yo(eKuU`sk(3xLy=ux`5=RC{)eGNE+TJI^ z(UKQV(EfN_+%#;tuB#3CE4f~)zvg;xdUo5WzA#>VJtv$we(S4!{Kd3s-Wy^n=}jipqgWR2&i9mFJf3AT zJ4~uNYYj`CI1TaQY=fX!>A+~;B6LP6wP0Y!aDQpR_P90PUszSD_N-DYQc?*)m4d}C zB==RWdbf_NbzhJly(D?%di1pD%r9s%H%j_aVIcB?_mln7V)qxS(-3(oPhb|~Ba<0f z4@|lwGX~|2fT2qoNIW(b?^Hn|=bz|c0STAVeu)Gm^hm*dY>$kwMxb{4Q;*ca{a_psKlwQ+j z3|G-*Fg=bQcs_|p{R5e1LU$+q0=TO#u~MooZ-Imbj@9>9L`6p3VUm9O&&F;8s5^-18%%;K9avC4}YW2QqmbWhEk-9$f zY4qO;1ZUNajZVTb)gF}f6FUU|hVkNBFCDe`I3V%t4f^!^X^4zBZzwt!TN#=}46qq` z63evqP{&Lfvus&$?Onl-AllA2Tj|xO&w~1L%g_+`uEA~90fWvmaK68DjOT%$U+URc z$RsuR&eCAO1{2(JOmNGC!7UF4x4aqL@@8DhtvM2q&?DV;0U~fWNM7tDL|)88I+Nz& zZMN9SYmolRgC|G>o*+JWg81MG{$Gm=vI3$INnY%P|IXIjYI8UK)%=R+at{u=>?9!oetllpF z1uIjXy<^}wJO(RdFFMj%8CY?x!Vz*91nh!<{rqLq$E{Ng_rt#Z?fT2U{TXWU?;{P> zl)8c|0d=lhg>4@VMdqN>UinVmp>9>&4L}|p=2W4W1L(31$mjwx#GIOFfLjZDj|hY9 z7K15g0({_W{L~p0*x>)pnDRwM;LNLMKtSTUkLTMXwItP&#tpS~*Xwn~MpF&7LtmCd z^c@1iRXzZ1gz8S3L*%8JK40zOSj6rb|!dC*@JFQ1W~5;|W-4+no~ zyO&>TZ1~fPt*t2W)5YF;SmPU4xu-8YVvX{$`IRCK#2p%{tf?pI1Yaa+!Dim2awttF z+_$U9g5B>!GkOb$Uru+YIs7&>ZyBsDzZRrw=R((=x=T=bhFtpVWf64R*n2)Y)8FUu zWYxQcMz{DpV;8;p*iG)lOh)sP5ciZ>t)r*w zEsDek)g;>L%ZhcUNmZ(Ve6=(ODSMbYJ_)&e> zT}St=(HovvxhNXD;PKN#kxs>Hy)|#q?dM73UPQrg!qGCzwWq58NAFJy3Tf|mGWCz>%OBI1Kcbhm zXuJEs{0B{gMBJ_P4TO}uq`MWO>K&#|xlm`M@$X9)p1Z4c?Q})gm-n9EH6n7`vC4IYjn(@8Uwh&THwCcfZJJy4H!rO1FM}4XJ*Wxo(g?t?iZA3 zo$hwu{${^(MaPTz>f)}<-&b3hRd##@(Ydlc8_d{+)t^SM>7K0Ri>$&c*BKxa@ta|O zG31*XKL@tC$EIest~uww!c>w!`bvbmYe9dOMcOjH-*XE__-b#4{;$=#_*Bw5;`( z)9{bjfmJ9$z|Ics)xqVo?G;4{zlyk>b{s(#??{Ky&!_Ub?+qqhb9krabqP?tQvKsb zX=#zEg(59>p8lSO;jCh$WzDW;yBF{hy2~@)mFVBsgQd)C^+$+rvWo@O0X+G(>?3A+ zhpDAJ+W9tYijZX3dP5%d59Qz%`ns%R3kS!SH1-$!hu_n-ulA4jQu{+h+-snZ^rRBv z6O7v$K979kTt}`p_U@4J+3PGGbZIiY^_s@&oK2tizsU)z1Rte- zO@S}sQAC=}D)uUrjCWnGUimS7h-+P8Ye)iY1Sk-PLbFqPf|0QF#9&%KD--S>ePj{@izTQH%gnVBX)V z=@ZJ|=V*5Onp<<3un;TTy=?{Uef@#ppXED?TJCm*sjXpGWX=5dJ^gYQkG9!ts;gUn z6smrI`u*V7!d%^JL)<>YkU{E7s_bZ7yX*5C_pUAO#`pgybQ@gD&Fa!2Q%ru%6e6T0 zhHH{xLs={Hozlg#ND-hZ_x&iu&(2QLJpM9+ZkgWrw@Vl}P#r`g9L z+3z;9KYtPK{fJD1$#3II1r%0SFsDdQ^aK?aKmiO0BvrJpFbl(#4qnFwlNRtaIhq$` z3Xl{$s{(-^{3HdcP+$@S@T=m@3&!}#tlBC;%rJ;~1_i!DI8dM;!hr%k{3O+j?o__5 zEmO;fZmUfLZXsgn{NvSnyA$%`?;abXSTlC|nssUl_F_Igj<7>SQ`=AZnub38mX-)mx@1lMHjqVQ!gEFs~Nd&+vY1G*w%@pC}@=&zP0lHCHgU% z;OoP~)ZiKDa+H1Dx+Z2XWft|8hsYr3F?av_fuMu8l^8kxh>Vviy~O^n^I9d(5IUmoYBuOf*v*QsCy0)Ziw+U+q+mLf zP06LVKVIuJGdp?NODZTh@{0~_XwrT8#+t6_=+1+KSenHY`@sUar(w6MX@sh4m~zO3 z<`guJ-W3*I(%-CHzZYXWC{npUynnLn5FKE2S+sH65DR4&)SCAmt%^;LnZ)-2ou8Z_2wM|x@B%Uf= zW-W`QZ|o?%pm{yKPC9;o67`f|Z zg5-?cTkbc~N~kmhedD%}<$cr-)|zoo-y4F}FysOUEys$NP`|>i1aeu0uTg{1+L8m# z$CAOZVuR>ZMjJ~mq_P8yQ)hnqSSfP8CNRAmyF^Z(3NZ< zTX%}ADd9IcaL}$-Bp;yCB+e7M`)X>&`Q@6w2m8AZ1jO6(ZR8|N&&@wLqHaFq#2cb@ z^Pj6n;UhP9Se1~A`V2cV>P@b9D2f|2`n<2u`7bW3YnS`@uDH}lam$XaJdlJJ4zpL} zdzW$+X-mS_B?9VJ)ZJDEVvP92VJo#Y6CdiNN=;US!;pK;B$Lux78lr#Muvl?XSIDp z(ssEC-N!R12;IMcZwxxq5`NMkGZbj)xz0`~G5a}7&OP!FhfPartt?Gs`iZO-Pr{w}(G~95~?=9_JsTN1EQi2jk*{AEiHz-ChUPCzt zabuOVLp>mwWu@Kd5!=^b`uPWR(8WQxM2G7ZiDX+0KUk;h58E>5F{Ut*VH*g(i)5{~ zmV1P-o8^3j5KN-jdnbxyvyb<=LD81uH8k~WqTzUxP2Se((Ev zwf^{Z?8sNm$5%YWOX(b{0&H=OxiE%Uh)U5&U--g9x&!n;GbtvC&I*RODuRQ|_h)Pr z9P5I?pP1r1s4rd)Fp^HjLJuI`_LkUn?W0F3Nilp%6k%Lhu68HP_UU|o73gXn+4do$ zZ4s9-h?iEDFhnIE4w4R~xvYclz*5Sxaq(RHHnJB*ZV7X5^UaXqXmt!$p!kM$Dds$$ zSJoG`cyzU}L2MUu>=crC+jG{1rv3XH)&WBjS+ z1B^6PvC!xW(#cs#rcXUbpDE!nxg2QpThdAVz_Fl4c+FkLPd#>@VekcQkb~IEA;p?o z<(r6+?4`HSooyzYTiw3M$$}3D_9wkzVe&_l5?%iOzs|{D_}0@x@Hjo!>jT3FUkBDf zzj&+m7dv-*MwGo%?B!1O6Jwpi9xpXpE&2~WG5Q#UFgu)GS(%J=cL)BQ*0UT_f3TIb zb%4tMfNW*|JhrF3|G}cx#)D7Fh^1y%yGWdGB8#=ZEKSGks}lR~^kxU~NHcBDZwSJ& zBVyWQYJJERtaEZjV};CcDO2aIyK}qLutLsIOiob*YWuqvV{c_xSul@pBr3P}QTaW)`ox9sLwZtk_x;NY z42Df*K|FuOWLGJ0aA(G3M+1-_lU>phrMWRP8q@utEGXfAd!K1eoIzfkK~5a|WsA5J z(Ob;E*Tlo5ylz$~&o85y3*r(UxA)!3ic7F*?=v)SOR#J2Q^m}4PsU`gueNQ_9)k_$ ztK$tUY?ISm^^vR)@bL+Wja^%(l9T(?uJ-E}A={sk$FaU4@_xTIPrAs(9q1)YT!1Ty zo3x?fd%Zo<{@){(7U{M)M|QS^6^SRsxazA3b-P5(YMn!3aSjeJ8=At z>y5vr)q#oc_Hx~>{c!H{$%k{1QZcW-*&Z~0Z$ypebL}~<*U_w&nsJVKfA@=^%zYin zq0^i z@B9XLP*z0VPofdx85M3_tv*doUd}?VAR#kO!qgi@8ChM)gh4!iBj(=V_@SN`32#u@ zpWgw}_zw&F{36(`qxtiWs1^J0^=}*ic7pIWDDfJ)e-tRNe4TimI<%WJw3|85_-&*HFiT`ozvVfK>@FTw#bgbc5TP^=Todti z%G#$>R4&6U%JUTw1bwdOVzU+jLUFEA4CB`zp|oE-4WDIcfAVD9XwwF>ca(N^#B-RPNl4Jk@t0F5}6gTl-*NOk)CMM#%f*--iwKBiV!>Rzp z2bDs^nlw)LpT@F@k$R4{Oq@9E9v`o7H?zshRM@F44P0tTY1SJr<1!dD_zM3x@446B z-D>KdR$6+bF}@>w`Tl6U>2B$l5BrRw9tS^GP0>#e3ggEQT3tuAu3BC~9M^gvmMLI{ zk$r|i;+&Q7StW$&h@)jvLOPRYPcPzvFr~EpfvC&)j`Do{a(kcWC`I;WHJkFBoqWib zQ9n|EKv??)sn}-;5@@q2+jG>plpaovV3|l${Y+f^brd;jce0>WFZ6M2C-b-^N+?m9 z9b#r3*-@A!$oV?TE&LVn2#3>W>sT3DVjzlRE9!T^h4Rt`@a#eZfrELgQHrcIAXTqJ zCp!zMpk!;zVRxW-YEu?Ms>;@$A#o0sK63Z1Y6^~^9nMgX2qmj{C94RfppGcThi&24 zyhal#6;K5sgtgV&Dt$jyIKo;j-o-d#=6npva(#?ZH$u$eruQCl7D1 zau_xNST(ARmiA*f2%|+IfTf1JGEt0_B1b=g(jvNq9wKd)P|APw8%LvfFk!M2J} zmK7o)WX@YJICNvm^H_Y=TkwHPQAPM*VdSR;9G6>4fJD($QS61fH4Bg)EUa=T>1%&(}rI zwDsvZltquqC5u)jqHTq1QKn91`X;M%oAU;k%REoZ?vb)wurhWnkqM7k%q}6!UaoA5 zQn0T~Y>d*gbM6zZOvpmnN$!)rD-K@9_tR|oDZKHse0+(>;`JD_%kUzPS>R72z1Qv6 zT!yV`meMZ0om;w^h+Dg~eNHKG6t7Os+0DXgud8~|vKM1HYS&C?va=tejX7syV3(Xi z>^2Pl@bumV_`!`pA#dM(4UBV(SHx)dFqdGErk1?>`_$`UhvuPu9P;<6T)J1)2w66R zX%*_W!nGMj3J?8M`V5`Q(&^B)2ss9~NYBd7RW)2YZYvi(bJe*ERxX+kRfR9-CZ{-l z87Iu1TZ$%>4yU2MKpeptsuHMlctJEb6W40X=Da{ucA^9yX$d#+x?vWj{RQH6RRFlH zw)7sV@;bV#;>N5TMJVk=&h3@k7MRruZ~p99)}xq@`+=LSoOCWI#z2!&8vdk1e5pCR zx$=4nhf7NJ40(v2QA&l7oN}?CK4G@=6ru85H&w`&!rV^w`B&G1`rIO~TId5+1v1+y zN5D%h!t}@nk;>$YkLWHvO1hZm!>T+FmNwB3zc5I{Zz|xj@J1+Uf2O~8;~sVBQv>7M z9Cy{b8Md3ETwN9Y6Zw>!N$lqrXuy5uFQ$?ijq-e_cM^)-g?yyT6$+G<@*z!M`ux=S z6z2^#c!n;wVm^E!;wNPZXCR1-0jA(2SIkwfWw>n7N&oe33yz_sd|2P}Um1`4ne=aT zGI9}j-n6*Q!EGCLF)uHg<4RJ!sI_X?HLows=cUg%D*VUg*hg_xYQmQu-Qh4IXVmFP zQo*N9sOZR2dXbcJ_emh*%XrD!%h+oAdO2|=;+g*#D)dc-q+Xo-5?(y!yh z?6UQOIgIw7vf8>JYH=$j*y`J@srgG%`0 z*$3tgop%)F5x!n?$N>=#7e`m9A$BX7daS=DVnC-Nc7Al!VVlAkZc6P zebAKg3nNbeSly#^A}7Rv8OFme3ovx}f#WMDrPsaD=SsugI5|;b_>3v;PP;`iA&jm{ z2@*Pxt+e+~d4t-1uoF!5rvF5CVzZXP|-F53+>{AJtUuJZMXk%-dU$yPtohXQkBhj=|+{P z_$AfifYkt+Y~A8PtkTx)@{q@OW%K3*3c|R>NfyskO>-_3Y1BBzuMcy&L-$RYa-M^D zixSMPAHQU;TOdLhJ#T#orrj&;mnb6_ILJbqw&HTiQ&=mTw&Rq_Q~sEDU;0J-6H@y0 zqQrG0!3O^pk9BQ1lEgC>l}#Z+DL=1%=p{moQYNl?=ynCz@A>%0(V;1Z%h$M5=QCs34y&m-@dMIhbAh}R-vh3{DFKn@3>)u*wf#& z)nT_^8dhK|^0_Grhy@MS-hD|R(6LMs_;ug1Gq{jbozCa&yP2kY5!@tldiOWXiy9N~ z*cSOcMRZL&gJQqGBu%+gn%DHm4p86X2hg^XYDSWRVHMQH^V!chP1C$Vi*jxf^5)$wdLtikbyvYUBjF9ZRfI1vd+g=3J zN`RUcqRs-;`!`u{ztjTM+ZQMbp7R1~H=sm*B2YpKDDmkgP$CVm8NLA6XjGV2SSR3| z6H5fte*x;}fSUF;p#A`;KXU_WLqOe{0I2x^wKhck0#IiI>cN{piQ7Pl;tN2D3qT36 z1i&U9upz!lcbo2plX;FDp#BjLs98FL*9l1s&YuBBNRu0YSLCBcyS^3SUH@NWN7L@z zbN!~EEw>n6X@y$9PB_|j-C+1VO z(7Y{SyC{6z3OE?;pfu@absEG48r&j0?MYMv9B>KM{_8CcI~F!cNErj&I5AZ0%vhhG zn-Z=JcF2hZ)+aM`wDoX!k|Tyn@O*y-bi0fzlVizcC=T851Jo*?s&uLT`_1oif5i#X z`&To)yMKd!7ME4mgpu>+?i1wlfbdOWceS+0RCjtklHtMC^dDmLJ33#sj@4weCa!%x zcW#Ms?XsG~dPrIo^UzNp?NsDT?{W@SHUVUJEvW0As#W*qX{dmjG9A<#OKJmQ)tf3;ozJ8PGHH(6kTKD z(caqhp{T~5_T(4I=qjP7I*sb`ASiu}!4mN#&cM-m;7xZsbXiJdTl+!Ny&(`GOnVkV zTmASf;%|)qErL;mv3joY5ya#FltfD8e`9)6JO8n@vC-r ziay>j`IRhDV8)fJb42v@c-NGEj%{CMVGj&-1(wh z*aufn{QiaS5jigjOD@cdt-lLFa#X&|LWv*0`88l<(b>p8@9NYxFiEe}D`gg(g_>lP zkY6YL@Z3IC)FqW7G}V!ILSw>!)o$=Ez4}Eq#n)kn35?2p(y!atD}g7PSOL#c8rWp0 z2eYwyj(_>vb25cEO1;?0qTFj_*seN_`*zACtdo_tWP3+hfi$a*{d|-?s6csSeB6F1&B#Y^x;*+=kVg4=l^VP2B$C z2{m?mqDF4w#rn73vvxG2s1FfN~Nw zEXLp_p(Jt4v8L2>!hjQ#wk*p0a)LEUgzOhPwx((HjwHetH`aL+gs5b`*nyDR|CV?Z z`)c&~=kcoiVP;*!$Kya@tgn-^tD~A>g*!GT3eQC3dt2|RYuD=>ZR~XwY}|5xUMts| ze-C?2df{M}U63M%+M%UsR2>gTIP&O<9i>Cj6A^}?76F=v0zKr${7hdsN6!x>EzH2~ z|0t4rSg?&{+?I%gxoU9D9HZ?33(yzNv?6^qUPgyqW-2E|`l_C}j&||DwSobe_Z@3( z-|vIy77D^Z;v@0TzBc;5E=^DSFrvk1?&72KZA>>GRY) zwMHfhQ;mKu^WZvgPL#_$vN)$;j>=&}X8xT);wIq`NtC|!CZR{0NiEMTl>_A)&Rh4W z9Cg3t$-p$FJi9%_xB;J)0Wpr)05QNWMy(NF|GGvSmpSNg&mmntw^#_7oLdKM?un}3 z6P@;!VAG7!A3WZO+zH0~7^PTkIB6DMosc_T5c3vNF{^AacE68c!+UUZwooH<5!)$f zQrK+#(0lb{t@uDl%v84(Dn~GMzt`{WWR5V|CK%Um)n+!A7ppNk|}MV2=B0|MGQ0X6FY4 zu_l4TcATI`EnnhaLMWGrLPTk4}38XQ?;s?)CDEYV@2l9QNcX6wJk*)I$kHj z)_&#_I~UxE5rAQ;^em*F;s#7tzD&l!+$$D+V9KN`CxaWHtA~d@h+Nk$!MCor-q;g{ zy-I!kg!HMSZk{0-_}BGh(TysmH+=Pt9;OfL8Qm8oNsOiO1NnkfXzyk{CoJZqwKZ>3 zw^f|Ze;Dn;*|*(PJSS+RMG@ethX)f%ETby#EP^$HIB!GTr|;K+KAv3!MA&Y_`B=Y$ zI|j5s-})cHxLCc|y4}>exPj|IEgqtES7D~I_7S2mbFs;yJ6|LCQmYmvdcxdS*;dEv zKOXGy_BL4UV~Q5pMk2q4#YS27A|9oE+iq^k@BPbidAVWp=7L>X>TJ=XZt-@GoL<=5 zK3?I};8m0_lCL3&SJ-h!Wye)ity(G_Ki;|NvdWjetKmGI-Vu0nf@C0t8J{yu zkOC(@SmpfPoal>vswud1q=}6|UD<>mP67oC?5L!}U-cd!p%Q`Ys~B@sx`)Ctf!w#FT2DQT?BrM2dgZc3Dwju79t%M-rDP1pVS zFZK-qj}3b@J`t@5#hmCA_b5WCPa_w@_$cl2TCwVSf84{%iFPW&USDx~i`}m(rH5tu zKCtTU7hU#|iv;|XBuT-vS$La&0dD52U(6Q!SPPj;6zc0(v+ znGxOmDlwys)*)|sJj{|~^%W+97koln$AkBLT0?wT=5Xlnzp6@`i$0Kh)2#>o)6z3I z592fn6n{Z$ttskB9@<)v-p4C(GgPkT z=6^uRL|>rYpWy*0psoRue?1fYHcK?1=SKWVKZtEt37&@uEBkq9_aE_>o2LPJz$T-A z(nBIWldN+gsfrJqAQ5VT?yvKLQaPL;d{D>ifWDe_*h@91e1KgbRY7Tu06t4LH)^%q zsO_#olGFu;AT`E<;>wQfd;_Qz}Ro zmre*#@66x^BmzTF4*tzhVW0rze0`2qV%;f>wI_-1q)H>~oCC&mp_MwGv-k+4*U~+i*dEBdPoqQul|zLQE+ zIAb9~(V6(B^ALV;2UoDfWe;Y+MHN4m3na?FYV!8mU28vRS1UNbk*dqE+*~{3zfC%B z&E}@ey4-BIVa+y}pmtE6Br_6LHPbJ*#A{L~Iuf?rk?VV3{l6lJJrX;^ddnTV^FYwE zlESw0zu_I`?L6p}my!D@_k`67eLZoG<`dm7)Xqb%IiJ2oCWD}OZU*S~YqyiS@m&t@ zBceVXpA%LC?0e_A)YoDyiD(!OUOXo1V|X95o0iYUz(6#(Mz8#ZIxF71vy|PENMTje z0Nc6&yhVAdM%czTkml_@+OJSB#Knv0&@|mCIxWB3N&?4M+so5utNH=cWNYI-q*D^eDK3m;7&g5 zSqP_cuQ|50Xz9>;t9aMqgr4oAZ!-&bO=_k(wFx4tGe_!X<&D zuhrUS!!y&1P+NREa&<={p+ot8WDmobjRS@_=9t;tx|x>VpO-lLJ}N&h`*AL@M%>hQ zQQ$9c->3Jz>7tlA(I-(&qt;> zFNtqoj>+4*k?K4Xf0gZ~bBs*FEZ37S@oED;7kZ>NZluQMNvW~k+>F0E*TMBfE@770 z^Foi>z$>oU|3Y-)FmQ-!*nhS9@$uo4Hnef&O~%dl<->Fq@0W##ES>z1icO+Q3Vh2N z%#*o}x64u)MspOsZ(n5V;BI>sr+&Z}V*KzaVNJ^rrBlQ^ju~nTWsu;eoMG+s#Ow!* zB#Gg?l8~r)h)m*$`6&g?6UAr0DPT@^W_WS7QDhv+JGz7hM3r~nPZ5Gfdw*1)Xfo>Vxrwsnc1J(?a1x|+;lsQPV-}?W7!10K`PZdad z#CryW-(@A=ccAldhoplZEzX+jRwWhQ$Qx1d0Aq`%AY=7)Z9|k5bk?~LpgIGz_sgND zbEjmWlYN$KZIJ|BTsH(5F3?3`ua=(C!)hQr>N6_3Gb*Yxs#85&JME&Dx0~H}{Xbg7 z7PMGC54|=hGiv43y3z1nVU)qyQTdoiyqu}$ODwH{e7@CONppkm;R;2A*MUT->-5=qhRTpF+x3}@(jr%-+&?!zRo3inD#MeAkiiC||7JUajg{@o zGv$`AR0BIXuSJ#i&19BRLBl>Hs#ME;@<{Cl{~A0>j-IRd zbNu?-pNXnBrhSEQM;N&Bj5ZiJ#uC~I7m{RDZy;v+=W@7X<>&=Hw`#0Ab9=8Vv-%3b zJ3v4k1PnLko%<7j2qic*p4rF4XTojiOHZCR3T*FjT^G^D<+`qrsP^1Ek5KaRu{6`A zApe&%O$|Q$OO9(lUuST_G7nF&1U&NyRi6iN#nLq0pmLar=VZ8q9U}u#H^!e)Z``0d zoW2x_Avcm8QHSCxdm=1@5?(v5LT$n7=AqbKC+y`7IvHad;+g}*wMdM~6~3Aufg z^riD*>Kx7V+Heb5u{_$z5Rddwgwto;qjg zceaaG$wYqxVU527?^Vu2VcQXS^K79pMri2zOw#P&U=a{>|t+y^L2F~E7Ty&yf~Dr(a-3eXIi#(g0U zw)f8?AcnxHIb{gEHHgXYRPP9JtJ4eOTvHei+`r#}1i(b7rsR*9f0F(cC;`40$k7sT zYk*OJ*?#u`kR)KUpucAw;FU1CjjzRJM*{o zA#M&t_9i-@)HeqNhn&acK=A()Bo1f#Ou5rXBz7X_$mG`uB`hul8EAJ(v z4au9s2_P}kg|SWYW)0VWM2P$T8!JghQ@eV`F`3CV=4F@@ACYO2MD))Rwbew6Yl(cZJLTfi z!KEd#0eqSnBGnAgJwcouW_W)PeXQ}{^}DSw65o!S_e_R|eJt)|?_8Xp|L)rIDDZJS zByWyCaevoNbVFm~%TT0rS^!NFQp2NQJGFlFB(Bzj)R&{fVqRUHRoTpNgJFLlp}j9T zDN2HYMcK@4MszEm`y}Pr$AFPvRAj#WYaMZHU;F6$>M}*P@O(C6vxOy2Q9wY@lhpS~ zCt#$k_ush5Jo{Mr?|5`<`x^_>V<)~xvvZj~2Oe6lSxZk=s0Z{9oRu9t#fpC`B^kPf2a`-V`ax1f>`#}mbOk8rPP3&$yd%4jEg}t;^(qFZD zFuh;2*SN7rR@PlhU{9;r1z|f@cxr@8C9qfTA5sq4QK*qdO%Si*=`STm@e^m@VGOXz zB_-c-W1$|iU<*we;4UHTT?l1_-^p5XtO;O+;mP#)I_w8*cfA(HE46LtFq7|UF7NG$ zo$Xy|@HzOkGwIDE=JTPuYrw{NDzkSqNdE~~+}Mf~w$JP>F#Vn#H$!i>lF?fvG~4)N z?=4n&Q`7byX~5#9fjbC91EJJDCxdJa+|KsP{2p)Wq|BAACR@ z74R6#BPjrfytMZ*cq!ZqL&}_z;D8(eL|AaTZyZD4s3Rl7Awv54T&)E~*f>OU&dDRW`OxLybFe-Un?cQ@{t+7>e5@$Wwvcr$y1 z5cGICIDX8P>F0WI{Jx!pPyb{=zi!uTQ%B0d^Mn!h)WN~`1Pil&e8mI=ILt%M93jvo zTe>QbYdr4nTdprY_7+yD_KbjAV(MFHm9O-4Tm3!cB(7{!IX&f5+NM4`Unf`4#v)>2(ebFd%G61O3m=6d z+g718uI_c3H=M-xvU!bZ3&nA-X6S)+z$b+B1BTN;2W16a>)^Udaco`d$YRd#p;>Lt z*wa#h>b9|Ul{?hB-M?4seyeuT;mMUrK&7Oh%Me=3iMIt{bi=WZ0>#w~QNUITux*~Y914Y7_|%=g|DX6y5IuIM|rq*lb(<4T3=Rp4cV8LYJB9))XI5itv=3%e; z#B zEnFuYg6kGhN>T_bHNyF|LmSB(+BXG|Q=Yn^Zj_RQrIIXq69%a`YJq%7t;NAGOk7tE z)mnw5PGmLZTXqGg@sZ@>&FDyfJ;|HQr_+C)I zQMzPIyKqt3S|;Cd`VyDJ6HA9=J-sYqOGn*{ymvyKuys8m*1;0=`^Nn5QFSiTAu&aq zg!ibpi^7q7TNgw!G90F#a62r#uxc?jv<>8|Y|{lhr)ftp;1iAJGIn^N;wBH0yFXdx zE?PUSwV>|eMyv-ldfdefNP|kr6Uf&cQvB&+AYarc-3M!g>Y7&`wq5ZE;eO31nk)_! zvAC=2vvv3b;gjk~qS4CtJR%s)hA6bWxEfm;fiZvPB zsd4tyz(I>~)xE_-{tzT{5Q8I1oP{4DJbOGBGkBa6CzhX(I_T`M)iuzenqS>oBW-cT zmh}i6t8auCHwcPe3b;1ME80kgEsGn-nxjBLg;M_PZ|+y``ZIKijs~3R$TaPU)k!nG zO`$mLMTn157D2KGwJuk?&bKbjuFdTaX3}p=WAMDzuw}cA64^seH}UYDJKMzb2pihO zBe1Y6C!vXCeOM$Jv_wY>HuE^veNWVdp`O|`P?k0wNg5hcKpT0;!A73HRdfDgi-Ts| zoo2xGA_NCf0$DkW!d@&kE)5n)!%CHokUcIi{kSSp_k_PZ zt@-HwHFT_wD$ck6cx=Y;vz57*2-yAfqPua+oCd(I#wDw(aKwwxjfX=FfRYF2Yw)`_ zta4s{yAHc!W4-c!Z}Z&a()r99X47V=vw|o{Sq##b&$T(xN#N{tm6X4?HeBsi93UsF zb0>k%O)PKKS)Ki)vggNV6I1q5|CG7+_2O^OPaSUy2~#4NSTLp6Q|b!vm=U;WEO53Z z8smkc?k;rq;&xpATt(?#(zwKmxM_@V^5&hF>$24ez1+A>qW@s`L5YtZ{?wPnZ6&|# zIpZl}hi0!2L%#PHGk9+|IR4oAa?>{n)ds%%#Mb@Op1796>eIHlp1)3<8AIse1JA&$ z(_Ko^-y-(jby`SMt^BlSnjZ17!p8_vgdNw^^lps2_=Sh``|)sBV(p_eXPX2Ap@!_sX>WdQjr-wf4TAt}0FUm-ASXGCmAJ!}aRp+}^{G=@AoA zC4Vh*UrnLyU8cdg3Gh>ZSH{>#XFqWGB`z@thOnl_w7sIiMP5(zg-f%RdW#p(y_$~F9UC03tk4Ucoq&QiW5G?QcTvfy z4gt1n2a9CK(bIx{Z1p`i`2!Xmj=Yi+*TO<3?t;O|oT9i&kE!JR0m0-+?% z_i_ljzqV_j2e1VW0^n#D1enmVw(*QWII9f+u4iByyUsIk%<3%Z&vq?%dC?g{*G00S zIIjd0JIa0oz}DdmfHn!979HeEuUo-TBwL_OUj(7ur)_;1M$fx}X@^Q^{=$M9^xupG zLAw5=*Bb~-yA?xp7(e64ZW!3_b_W9g?8yU3U{4;B4$y;kLNm{i<7FM$?S-y}vh*!> z6jJA|Y$e12Y|4X3uP+Y*Y^XUKJ;HbR0NPttm^KKhgA71&5s)rt5eAt?k=^@f!#`4g ztMd;MIQRx7vz&nsjc`+Q#NXWhADC$HvChL?W8uE$;d->J`@bJ|L;ar>mqBb=WOoKw zG4ZeWZe~kGfs<~fZ2|)CB0Wp457E`{Gx}4?wQ9jvNu2NVxJK$CcGISlnBJd^2OkvD zDJq7=-!44bd%}!H$f1a~{nIppi35WA#P!J?)JvH$Nybv3LpOQ>fMCsr97>~RJg?Uk zY{*OvCP3b5{Ei&6A!o%TG0QXxN_hm>f_eagp!U4_r@U%>1B{#wU=oB|l(=5u;Ik8S zt_l{hM2NIZhq~`*xkinBJYw|d8UMaHxk3(-Mqh1Zx`2bcX9B(}UzsXkXkM{LSV%3K z4s3_aZ*h1S(8r4b^*{-v@)P_K|2J)t-0l-H1K3L9f1v#v=ZrsW_vUZJtr{)czxn^) z;rtgx^4ooFe(U)!K7ZnLPeb+j|7(Cw&wC6>8+GDTmvd7)Jl=uzFemC1@qnn!)+`F_3s3Yg1T%l#64daTKiuS zzNKkSg9W`Bx@>i~vDzUFsD(oSwD8~f#*vHJdcI(+Jp;n!Y4k%SfAh(0gvW<}zKk|Z zS9BO=89d^uD|4b3Gm9G6=Mw7QHm<4@vUc~iT#g+3SmgO-^vK@#-Kaj*%SdndUwDs& z3)%%~$*Q}?q{pAkcx}I^qHxe55F&8YU0M3xK;bo3_Fz}SwO*(1NP}h7ZS`@Ctz6+~0I^Xv>WyMO6b3OK*7Ty+Mx#0el0-Vm(3AmmBY2ZdCQ!+H0;|t zIT)vhdPtVU=VZx%^=4rbGwwo=?*tr_hvU;bH4EP4?~RU^sA)GW{kE@jFgjWt;_ zt&69-uVu6Q<_6CZpVk0g8dz!DvK~k=4nA;{&4xjTiM^DtFyJupb_jOkKcmhf5njOg zf4sKRF!o;=We_pO`(wr(7?KI43=xx^5fgu$gYfx(Bk^#)R)2}%LJ?Pv*PJM!IW z$O2v@h!~==W1it z{}I5{sOzzA&B93HAZB{|t$HI1hDp(JFE+dJDDz&pX`-I5(6CzyIBN9 z=`_tHovCuk5Vd**K1Lhhm9}jwKxFtRoMFx9(}rmHBZ!%UJP%+F+B?p75S#RftTBJ& z4`D_LVz6Wz-c|?Oih^G5Kh*#w6%W|LZw|tYfxvc9Qji*`NiX(OhUMq~jUoG)0M$U& zH*VS&5E_G9$lE|ZI8a~(D;z>jK#lLjSV{C5rjNH9%%U4; zy_n5ods=}K#ZDW1C)25O2Z6KM8kn#_lRoG)H`VTR>e~fp$Vepsp%_$GpdHi=0?Ck* z2>>*J8+@Ifebke@>wi!N-l%GZeyxGK#-gm-A@?~}q zAb-r@HEQtI;k10;%f-PYebEOVb}V^7n)D^faHF6-n1ri#IVA#j^Y5b?f1G+CI@Cxu z_sgtvO%2|PlkR!oH6-1m=yfA~Rz&t`It_arWAv!q;#GpP4-TZyvdiXaI;XI9*D@NH zJ~)9tF?-}{mz%ydFnZkEEQUP4oCjv;J%wGX2rzWarp%ApyiS;-`W(S& ziF~1e>7!y;OyCQLFb62oNE)nF8eI!?smb5OX%tKctCy#vlOBji4_v1Jz31OYU>398 z{N|l)e-ohx_OLKEU?u^`#6a}|(YB!D0s>Hze#X}T*Rw-8|L)ix6eL>28eNm$s)6Wq z&*-2I@1YVHSmaAvLqI+AdIJIAF+kw7yGsLoH+cBRl>{G^s7fjCEdg=*Kw2ab7HHac zAOJc$2(&KiK>!R+bmy?oG|8qpXG;Hu96@vLXKm7S(!)>Bieu0wV%a}~)x|g*n(|Z2 z{hO*%0n_gxz@a&Zjn>v61ic^95CDMDC=9mAf9RbXM{0WTqp#>AqD>|M?HwCIcOI^X`>>bBrqPND=;1efbk#z zjHmav@&3!_I8Zj9>*m1ORI3AZt*MBlaLRt(eH)d3Sm7#Op{<{|1B5 zEwj=Cm+CkNqct0ox?;n_9=oQ@RG~29cBi9;VcJ8nmx-hZ7fQ*wjm{%5v36oZK9d>5 z`eo;;!rIuAPDBY`xD9jIyiX8f)Fur>gQUqMDoX(7jMIk8Rhp<~qnNCH$))do~x zsDSXn_emfCW|G_hJPu?9*pPpL>m8kdRzq^vOw2(k!-smqNrkaILg+ zBPbkf;cS>$wA?4q&~CxmCP5K#gG6xV4FbUTN*Gl`YJycR$oUqW+o4(k%5*Ms{cC>h zbYKEc8zlfA{FoL8{KSgFAOLDH1O#mm5McS)ZU^L?c@&Uv_1{tj!3;3X`G62HvvYt> z09?cXwlmNp3C#W=!~B5!7qqnaH?Kdd?#vDryk{8)8lfNnMyT1H(~9d1 ziVwJ?KqR#M0D=EFLXCojDj;AG$O1-zWI;nElqXQMP@X{1jIKI5!%zO4nho`nA5VR1 z{bdp)U#ixKV7#~(wDalni2sUpSjoAL_BIg|t7h_O`T7R$=2oTU)}N7M zk5igAhBJ%=-=1!XFLnGXmS1CaoLU9EvEIq#h=|#}r(+43G}+c&Wm1~q zyz>f^WORIpT69k(A9dFvvGRLG&gio_&EP;2kPCat!~B$o=sr>7Eo|^-FgdK%K_NwZ z3a8{MtRJPEdMnRtQ`jE+el-6|(EBU;#yR}T@k<%Ti^_IO{U6L5KHeO76DQ>1n`lic zQ&vXJLggT>SxAE~^uZri{+XMM@c!H^E6jsTGax5LV`T?BK*KJ0f*^TE9yT;fDvK?2 z1kk!H$)E!XbKGrd&h7NDSE>#wq|CTQgw(n!fqa80SrwF$x52xu0g|hxH!|kf%c+qr zeMmm-5t4h?MF1QJupFdMk%(n9n@C%JR7fU=-oxF!&LtK^!HNA>de@)6TKhQr_bmNl9*|vNsk$beJ<}%P* zz11;oI#QPf2B4a&sRkSR|03=^prUBDy>D`spb{mB2uKFWl2k+_OHKnKhzQ6qfJDit zC?H7*5(OnoQelQXB$2F0W`F@C=bYiKM((-yIrp4%?|Ij^-fu0s|GW48)vlUZGfj6@ zP4$NMQXt2tkhdiDVR7f~N3QB{QMk+|kp{7D@X)@1Ve5ToneZK29>y1C zPc&boeRIiHn|{pjyNic~D6j5hzy=K4(13A7QW1;?jqB`N8ho}59!@~3zN*c=%S)Am zkG2z-!Y@Rrr{SS_Z~}&{^uOK3#cs+7y{?%Laww=IMB8)DKa-8nJ!%Qa1&>$OYqINj zgM+(r@Hi3YwZ9_E(*eR@S_&qi-m*9|M1t|_W`Q&L-&i-i1XKxA;X~bacbdFhsaIxW zzZqEN{xEqTB8FtrZTw7Upu_}w&FE+xdZDu?C&LVp`>`+$8@#p9FH!lmm8cnn zz?hg*TrU{mnf<|(NhV6F7p0khKUY}weaK=z(*xNLgx}Prdxhg9ZUX`f2&?=0k9qRx z-Iqs36@0;}<1zJU9TLVKE-ooo?)>JwV6MRY6eTz{G0&es zR`li3)w+(fW@?#;Ov?q}_`Lpzx1}RJM;JK9A;(wX=mL(r5U~gxrNA)=90-Vj94O!z z2aZUHSOSi6kaVsit+@yyAV(!2)_kSxV}9z*3>QD*-2yZg1k;y6um%K=fCEQ1BJ9QD9K2^`mDL%BFsnG+})frAb>EFfYP5KX|r3LO4Wjy2$D1`aOZ zcn=YfqZK#=fddT@>%h?t91_5Rl?{5BzAlzP+6f%;z=0zNhz&se1diLlaS=GuA;&M^ z&;*X_5U~jyJ-}fA92O7(Ir@OZ960>tKufnkO9z1CA#l8hh%G=20S6p7&`^$T;1~uD zH{ifR1mqY64qxEFkq5*MaEyVs^F?P`^F`oDha3}t2nWP=N#KYD4hx8Y9Miy& z0v!Gju?HNpz>x_Y?;!$m%!8x_ooUTzh}Z{?ML?7S0t*q4V;MNAfdfY&=xAm)SYgCT z#K-;Ts#sqro#tS@>t>MG3iWGzWsP{x$j|u@!Q4JjN*5b<%>t>h7%gvTxoyM+Z8HrcWXSnyr6kZlbK8 z8K#=v_Q1tlt0Tuw(U_AU!&dN6p3ms(G|W`f_CbgpEQAIH`p8gVe2-;}@bnf|wvHTJ z0Gi{t4~O6H9DTckx9mv9W#RVWvpI$2Waatajt^QwCvq#_5ux;|LnmSd7|?QRZi{7H z!E!iD#+mk=0%ifYOU4QIon|#bT;GK>U0_c^cg+}oZOL?pGy@T$^RwyGC8nBR@f{sH zrcdE(lIk|#F1O443^sGiE}m8OsrWO~t0o1V?TbBN)ju1s*qQm6u~--#`j6wmA4mBo zVsJ6yrnav_<>UetSu+HEej%Lxrh|F7n4Zxh9~Fnf-U*4to^niS73dxTcLj?*Co3|S z8sejfdK8C1jnFMa1z6-wM;^zW4m0XsJ?dOeTuD`C##r|{`<~b$SVm2C!@@UeFou1( z9aBKzdG9wf)f9b+86#*7SbELYkO<*YarK$$UaYEO0$|h%+_EjU>|weJ zD6qYN2iN7<5D)tQhCmBI{~weZTy6~(d}=zJX$&o#ZRl)zGjd$}S%MftHxUy+#HJPe zhC|5w?F=lT>?i*entgeN20?~BAa~{LL<}P_4w%mHgvA-hKj;=MCk3(p2OyMv_|tn%-#r{IQsVISXAIq8#_28M z9lQ%BdjT8}+Wrj)@!o2Qfg#{vgRkqkm4Vf6Ro;2bY~5Fr->bF&?q-Bfo;CV?>{`D&OZ++!bHZ*7nLDg z+L=GmpjCEoy?@m{EF z7sc8_@yOrQ=K9I~MKUg!2vHDx4W9|i1fy~#5`zY4=KwIjGVKKg{|qR~;xmnP;K}`F z{6Qi~vJh)?o#SM9Q)dZGr2)x61qF4WQvwM1=tEKqIwg4U!Jt4IB-~)>5@ifI!jJN7?P7yLJrNz@a8)jfBU;~Uta;yt|;-O@t+6lk^H*!ADswF zJvhiVe%KpFnkG|OR~#5^Obsh-~ym&pqCjEuo46$MB5Wk-6t&>p77lm*YZ1V-GB3WZvI~5 z9=E+hvee`yrF_8-^Q3D$OD222+U!lPPpgfERy@WR43%ElOAZL^n^T^=h$yHHM0@RD zx{kh$*O9tK(yxj(z%j28j~#m9&qC=|Cdr8BCR#ui_n{5UjzWtBoxu@&zN<^Wz>V9l zg;x~qAA|FW(?S5}0%<=9+5oQ{XtCB`)x_vHBy5@7Rc zI^!)bNvwx?OHQE0t7(ViRNkk8_313YU{>NTmpvSX0@TNt;w7_i7WF9p>xvbC~Ss^fa^PlZMnIQ_<5Y$Fk zPwjC}?Z55UIzsU}L!;fz&wH4^^?>$mhm=tfiHpJ}*X7}s1)PCsUzxaIe-{xNf)3&$ z8bt1hD1+4F={0JEAa@{|=Fq=w*WkN{t;oa5B!t;Qfd4w~V}eij^*=Vo^E$WC>L{6n z0Gp7^XzF4x?#Um-kxTTTRJ(o+>yve4u34 z!rFx*Km1aO)i-}i>tVbcX;lqII|1ldC>Y{4>TPZ`yPJ~)-xPIr)x%-Z zr4%1#aIzB3*`lm4585v-1|c30`sN_5{A`{8Oolq0g3%tfUrdT(OT74_9!zubDo8Am zxN&0{$yxYmdzt@*y;{9h&vfP>)r{9-lKnXxIC}A+VgU;wSYm#p>4N0c;7>4ij~a#z zDqQzM*tIHfVD!`|hQTvkAG05pCygnC@0^tlLcz`U7^f;YsqwI1`k-uyd8w&mqVwML z>U3e^pUp9s31^dfW!s4tQYX2O3AhWp^I%n9^Ra!qLgzD5Xn}Tpu##&&9zxBL*5A}5 z4+rz4jk&83xw9Rqm8@ShuVG^?EcbDXGM-guQGUaFW%iJ07MW5-glY{|*zsL2OVz%h zVfb`uT0@ZKDSZdivBReKRkX&Y-w(&U={LCW+~c5>9?0do!YNV0`_JT2a)rzfEk$t z66pyUhMRV9@hpANZ@eI!%Hz z7ydv)475P<11iIC(0R>eigE^L^?(Izi<8-r1R+Wf-!NQl({U1|cWe-@RstFOz;K0( zZD5Eya+ayD8$`Emz=3BOVjyE4VjyE0VjyDz7@H2j7=;+f7=jqc=z|!@_ysYKfzb&u zkF8N5b^|R4+MeQ=2^|(wX~CW%V4Q)BLSP)40HXjHi;$5IjA6+51dMjb$OA?dWaI)P zA2M=)kqjBxF=NrMO&A3SvVg}2@?-+T0WvaxVFno=fuR8zAAlhT8R@_ffQ&R?ut3Ip zV4Q)BRA3w$10w}wUNi=olYwU#@+8Gf)UBS)l;mrAKEbJO552O7;3e7^MDPC$-5x#i z-c^V{*OKM8vAXe9K^Ml8c?d>7J(aw9Hs|AuJR3Hzf22CyJdQuVC)#tA7Y0+{ zdVchYW>2({WXnp4)XmuZ_-)ieQ%Ll}=gI>f_o|Oio{cub#NF6@qX9Z zi2Uq5Jl#>&rm|U<0fTLp<+y$fL}kF3v6;?=jN`G+tMZ0fy-}27b2;I`^Uk_usOP9$ zO<=hWC%AzU%-94lD)$h%F?;R)b{Z+IYnenG2QCb0F7yzoBS?ujbb}F8ICEQN3 z65)aqDIFn3M{s0X5Io!)85@cZ#0)j^143o)srxQ1{^@)cyQvR z-Z2%RCq{ii!`IjN2dX4{ltz7*{B|u3!D7(s+tt;>T;64@XmMo6y9p8sDNOb>GczaF zgCkY9sD0^O=>=Pdkumy}^+Dl*q1q{%%xEu@e0EigxAggHJJ#|kPinfe(0T%Z4XM2&tV?k_ z=$##e1ObE@Ad?V63=lbhkkv^E>r;a)ArSHmAeRBcc^@F80MUT5K*)K3w}56c5rDh|$StTXmH?pv$ZIG|1ITh2WZ{L7R{&85h&6&CRd`&7}oMK9mI@U@@lLKhgpf5CjFhM9#vx+NegWe7q}VRJ8Y7AGoVbSr;j( zT&M$aab-hxYse;y&|HDSU9eI^oGoj-iwz9Xgf((re|_=xohy0JZ3Z9?o+mH=3> z|2nwvVJjs;Qq<$3c8%5Y9Z;SQuqJnE-3T}Nug|;TSvew@^V+75aS`ipV#k+!O}n27 zpzN>IJNVmw@6`N_j2V!?kyN-wQ_wC!gc2NLz+MY@efUaX3xkQE9Gm(s29|!Gp@x6= z!a>>A1P+gaxhhL#!;`UC1`Fib3*^*>Y1PIztwbBZV)CjFD1Io0hp~HI2@nB8Y{EqS z`3;T271G@iE=CldTQNlpnP5it-)0#>y$sq4g6tyb2(>#DUG;P{K^yP8U$MeRj5*0} zbv_?-k!umCnBE=*GbATW@fe;u1-q2Z#=P&%F>7VWT4eqKcaV#daWv&zM3w}9Sh1x{ zH6||5{C@EHtJHhZ#U3|ryae0AwHe`yC95Al$mP3UQ+^8P{@{f5{u&GxXK1`iRJ)Aq z#N;Dp`)+JYov|_a9$(z8XR@f&9^k|JOc-=Y^JKmEoZs}O!Rs(}A%JzzvtzGcz9@~5 zz9)u{jaTs9%O#Pf3}g`cJu&Rh`+Z%ByZ&8-tt~h?+|Ya>%J!>^IX)yPiNZ!cGecU~ zwR+}()OvBIKfZ1Z7X*qEf)j$6G-HSNC$TZKUPf~>;vtOok77LjXn#ht>YF!XZAHA_ z|EjB}$7*j*lHJ#jjNwWiYm4X2KH-{BV#Jxe8c-`HKr8-K(`JCM$nE+KS|Nhf2z>YV z;1}9ckRmrQ2Wr=UXxN2_ze@n_yiOARP2sYCj%T{m!Rw%~HllryK}rr<0KROtb>Q21 z4tzTkia_Pd^i7y0C+{|gjC?xR6AVlKXalI?$)1$vMFS`m@DK?1_!^Pe{T z$>Qk{!qN&;yU25RkpcE zjG(=08ZI}@- z^o(SD*HhsHmAOFR#;3uLyOdyvPLU~jWu0md9)5#$7su3{badn^C%HnKa+^XWB z8ko^i;0vwy;?QIJWS=!7@6kT4l}sv?I`!7WmUfspaWh1Q!&;(9Y466vqI`|&3X5#< zheQ<_d$^UB!7^VqQKF_1GGCyFWzh^t*N{YB5Fu}nnBF7D2LAeLvvB*_fgC=9qk8{K z*&r3RoYYSh_0{zGQjnUX)(p>B7cs{ZHq6{k70+;LY)dq0lI9}CQ7?kX&t58#Tn&tn zjxu$ORgg@tAYZKS42^gm;Ep{!-M~VyxTA+6-(4A6$F#awsBc&C$&>Ci?pgURRty#BvYH!LJ`kD?}S zU;0vqXkJr(ae*5~^O=X+izX?@l?n%He9Xa?!BNnW*1a#UaEKAk6?#g^*Q%gg}U_ zGb|SivTTL}#2p}IP!<+|ECR$1LSz8a50DZFaRo>YM?I$+3!|X%EI?EtlQnaw?J|~f&#R!FC%jv9sHUAOFtg$9&gI7RDX0L-I-bZT0~kA%4?r0sl2RzQOhfi zZN*Xa$}fj?rG1Oq_iZ9)ivyKi4t_Epld!h00*k{#tck6CH3IvS*-xxV!M|CGm6!|P zlliaizm{P^5$&*!Rz8%O&}v23&kqki-?p43ag2?6bvxC2?n-LK4E~s0OcQqsT{0Xi z&E|_!oi_Jw@~G(@+3p5D9;L_m4$U%Y4xFRDh$mZ}a^g{%NFv6}@*RZT@ouP)ozWBI z&a=ve__Q5!InL)WXK6EB|LOeg1p<%npZoKbb5CkyNw3@?3VVRQLzLvNeAVJI z{_U$+0@-L>4o2ZfD(Q*U#4t~kDx^n_xXU7Dxmkv1U6fPZb zV`;|NXpU&c6mU-vup{+=5Ws1nj~7Ue!76l1qm>gA`*zjwQxUq}e(>>qgM0Lq>Ak)Q zX}mBrtLNGSf==Gh9j| zubgQ{AJa!Ajv+%Ci_DdquaE~Iw~GSM^S^KirwzW7NGuf^z9{#Zic7>Ro0% zT6wa4jl^_Lh>&g9+wd~EvaAv9PlPS(o|q8ne)vTepO73|tN1Rr(LZO*mJue( zLJ^;k5?kB7@f9!gTh?&*<%89ouM{biOQq+|9p#H|d6%&*hQy0*g;$;rNw2(r7Z!3K zyDp%p2MZBfNoSW=;V*{2a;16v%2n-?spTPA|JnIiBV@xKZ4qa$00?dJSwMl|v-5^% zC{WJXD*~8hKg+{*$qH}jh8hV>5N$)fWvUJv8nWan8O zf-`?_SS!DLA>Xu{PhE<93recE4NgvJ{O}|C{;q2<_Od(`GfF^34-aE~7>(yHZT8K7 zKl+w6+D9e*EcTMTE;jA5HYtK8l?S1Bt1Rs#8YAP`W5VG{T_ID?Pf}=e_pPJ|GZoruAzP+4%q&oQYBt)$zX!z%S~p(h=J%M2gro3hH35XL1d2efurp{=L2v7gr&5S~M6Xa{rI@zQtt zi{bcL$@Etcg~pXv?4@|KtpSmh3ig+PeN7^!;^%2$g;*j&$t$S*z#+OgH>s&u!!Mh~FNb0@=?RdP??f=w zVvX#m$;PlT%8US_T7hM23dvXrC>AS%DSlEWHT7__${J<$=8dDCGKEj-`GTh%>D}kB zseRl^sO`tK3WZu^xTW$u`|>>MdU_ctFGF&>MX|Yn_@itAeX57-9{GQBoU_n!oGsDO z^2cYPwa-YwL2iua$9UnvV!VjJhKI3FPdB{P`2JPM4H{bQFCN;(9voE}Acu&D_8jR7 zsM;dyWr$J^H`=_|BNU_wvQ!gNmBWS8Y8PMGBtYrjYJ{3+{>7upa+Rnt*8Hs(9<#VM z$R%QzZu$Fz<=?XOcR|IgF7eWVRuC)c@t$hHZ=WSBYBQR1&GEzdw*L`llhR`~11% zo%Ymw!?=^X^{qAQ5y_**o+-)sIh}c09n0RI+*^y;6imAxD7aUqP~G8meWZ0C)^Ysh z5*PQ-(u9>{*0IVs*9Rx>?v+7@!q#0+X$jXEbCyt)NW}sJoWF~(mPPH(In342NbKI; zh-aG_t1m$x?Q9~p{4uo+s=8ra93B$9F*Ec@WV~a_cbNx%<#i9~QW745xR2fCP22dD zr6gPgN8_SuOCYwR!`Gdf>fI1uufvtsWu)-cO;Jp?5%R%&)>d(d18U5V zmDNaA&od>XffEz#a;qqh_!N)Dt&w0<$~`1Zy*}9yyX};lF*eQ~*L8O_Qq>ky>m%nP zqa?c#;yO<|FR`*O)%Wx6zEsao#J*JAPsFNlY!oAbdy2wX_VmzOv8^E+I&8=X8ftgn z*V7&D31LO8N*wUteFA50lXS0NI&)jfi`8byXhbNY%u^80m1WI{fS2_eH^t=}m<=K= zvtW32swc0n%)M#~5;$lG{f-YNW1DzR`fZlt-F?*j&b}85Wi8_A(b3T6!6EX(&c37M z%J!%r?>PHf=LB4@q5gZ5;wbP`kM-rdA3SwkZn3#ko6jp!n}6waV-l&=7;V)%*b+FF z>*jtHFEjd4*J(BK39le)w7SwT+unxvhjAp^`PInW>YQoQduK%rmEjpy#7zq1#GS{b zwd*ww@mA6M4vJVSA7E4%QVFolD>l{CQ?MNKGkeMR2B$=9-UmU39V52%ORV7Uwvud^ zw`{|Ud&vHkc`l}3)P1DUlH;nmJmY(3sR#_uYS2i&^|*+N<~!qLdSm%EtoiK=RPsf4 zj)LDRiWr^PW(21i(>P^_M zl)ri?)^O%Pp04WA%b~T^izYv*k$j_>1cuJ(>;(^QDZ-jxzCcA&opIu1V;WbL5Nn8e z{OBcL*^gU-h_qKQi<-u{y}Z%{2pYu4gh}u98)-P9y5-sZizO; zEZBeyod8G$fII-a0kBPhP+DfhhV%m969A+kAO!%j0Pq07GRQCrGL!<~F_fVL0LcKj z27o63m;5F@^J+FfNLS*i7Wzg9o}ie zha7DY8|6-rWB<;wRY6>LnGxHp2i8j^IduJJ)i79h>#_GOSZ-W5<31}*+#ILtw^HSX z3=l4!*Z%z(lhM7LxwLCpvghr*`S6rVZ`OaBRLoQ5M#!{eu6DLm-KhMhSL`<;eIPQ#La zO1HoM(-z0m@Zf1!; z7aqHDn=)l7od2dP0~dJxCc95V0lojmQM02eGW_s~_3I(#c_jDd#%zl;Hp^PZ@&gqFDhN~< zs4&p0K(7K7BSxo-1*6j?z_A24mI5jT^cv7>KxKi-0+k0U5A-_F>p*V;y$SRd&|5%n z1HBFO4#;;0NP^!vIFJ)b&YoO zS1p0muF4%mld_V`g@^%BgN4e+2N&rb@A8|ssko6b?pN2&CF1a${|yMY^^8U*I4`cbp2S16m~|U3prRC0%&L+>vSC zuA-nj^ayieySUgTj=?zI!nb9?2y7Bv>I@UT6x@ z5g5%;;McChox}0elJ8&i7||$5L*Fl_g{R{MDthu#V|50Lh}gssX#! z$3i)3M6e4eYHUKq19V9MIc`DoiGw*PZh;fmoC!q0(^W8)F8FafGZqAb7oLFy#Z)Lz z-Z;8o0kK!OaY7bkn5jl9wApThCE9ixtfpd5R~S#kfEe&Rk3s?MzNN%J+C<<1boDk{ zpgrpw)84>8Mm=x*vLK-c{g6{xyXx)C|{RhHFpS}q%J}E-e=Y>4K z&rt*Kt!VT@ek%KSWRiYncx`tvuc8kuZTb{-NQZQM*BXp0_*N|2DRkUNEjg_p;S*^3 zc_F$+t5m?afb|25y4s?A?z)kOsLk_$EL z%|`;1K(hl8CiW8pVaFN&f*4IX<4yimVh5oXl_#D<<^qTUYzFyHI#`6y*19-`vEDu_=heT4zh z z$j8_)=jn#_JTDH(TZ%Ow3 zqN6Y^!h(sZu7$aTjUorPMt}P+e0Z=#GZF0ILI{ppO2mW~As+ub`EUhVlA_;xQb&3h z(b0<&JGuclYSke4oI_aHm)Vb(+M;>a=^*F2Kj(bYY8D=DY$aP$Dj9*%Rlh&M!#~0O zlVIsX!y3IWe4p=i)hK@96XYGS{la&R_tQX(c*S5){$FI&;Y(iUGV4;B0fVMs${^|| z*|fR(BwwW~_jF_7eyiW+o#S)eDLuuD9M3-)hcA{YY_8qQr@bo4>QWUrPm6gEx`&YZ zh`gIq5oP-9>rI&4NSc4Kkv0{eCi|_P^DnY%va4a{ooa%g48Rg;)uh8QLYAqI#%gaiQO3_#4VN`f29z8&p6Q32@wWAV}WM?}>W25QZGqA=4xt8bBv+~{RH8)3UoYHhP ztG=M<{Y$^{W@?rtYn4rFmeHEm{p86ig<*WI7_vw&y{*`N+l-!hw*B-;ix2C2m1O6_ z{>zH*+M1JABWn$xnpq?GeY_YEZQBos)WuB%u*Kc!EJ3=;-R=B@1O>k$7>f*H6W!-x zD!%1#&rKPTWG19PMC2LC7Vy~-xra1P41&W#W7%9GJ0hxGhnIM|ueC*`?9v10!oUZN zi#NMBn>5MfLv(1<=IwS1!)p&jE#gLBFccZyQc9NT@DIAgtMgP(kay3Z*ds@Qx6C8i zQZ0)p2NS!r&!?>&q48oTjXq=;M^f^GHw-^O(}Urer6fT(=O7q6*nWt%dL=<58+-PS zJBjAu70DP866VCK0q<~h&+w4<$DF-`r|xQW1shFmi3X#N&z$%f*@@IQKk{QiU3$7L zcuOHX$vC=ZJme_DTZBEapZ!7C;$0seaw%TA2s?FS^al%7Vv7RN$@bD*kTW0TT-C1K z%;dKa;%7yfVVGOfearmOoXKQ}sI4gi|d))xlHUJ5?s5 z)AA=uFlBOj>~*RMr&@lhgGM8tRB4Y^`Xv2)H~WVAkS$!Xzp&9=hs)WotWDdQ`=SGC za_KHFe{!*sboU(l?O!@kVHKiiLv5tDLv5t9a}jL+Tg3ro-ru>*<4wZP<4p~=6MalJ zYO4D$^V|}?yYm2S|J!>0Ck|@I|4sYFF=`QiN#~sf6#HVcIUcSROzfXRrkOaNUU%h32-!$fBy&0F6 z#0bxN8Ejq*ud*B_@@1RmHMV05{=Pf`yWHAXZ*=<`4MvYcO>Wfr^}>zS+vA!!4e-Q< zp(?&)g#zNH-J2xKs-{Ikw3jJ73LZFQH&5n_yp@}XRC~aPFeSUnfOu*hI7)}HMaKmZ zZ-vSDie`0bz(uE9H0(r?>qr**hMbmPEDr)&pEI1Vm3Yf6=~TBq#Ouj!xtqj}(!23! zDmLXV0n&b_;#S;SoH~nZ+#TyojHwB)=w|ouXFjI zX~%^7g<@6JMUm5~Td?Q0QRS|A;p7C%+J6&@_9DG5n95`N(Jsx_|9sg|aq!0VfuwwSp%^z#U z@=p$0fBsnQtV^4=@|oE+>TK-L`$UBgI=A&2z+Zj#%iySpV7=M4eACA}t`lU*qJ1KC zb8Q*i&7DnCp!<5`^6qXwGZjHxuCqKn`Q@?H4lu1}7sed<%;%a*4%4)Y$n~>Jvuzow zNu7-Y~-vZ^04eYpkfbDVJjTu6ZsK zHX88RFnS_?3EtWi^vL@brocP#EG+l)ZkPk;<)W2HEuN=w$|;``m5{q6sNd`TEk!x1 z)j&M8coMkNr$pUApP2qH?{6Od-v{VXI+2H++5>#my-`S4^g-Jo-3%GH47V=h4L198r7!C^i?uJ192C(v;)N_m0U-t%tutzJj1|u8UE2I$ze1BH7_JaiBXlG=_DndRv}}wa&E!nquM`KRn?lZZ?5xZt*Jr zrv0wx10#d7hCwVNLz9MqfvE5|X;-gj>CR)N>2EOTP^dfbTTMu1&&T$ z*^_R%9-dD1m|2TOuzXhs*2&dVyEJjI9xof?eB{-#997@89%J=={dRKZJJH`=#xIf| z%6}FN!AxC3{H~6C?lO{@J0(nZM$+YerE|+rgH~&jlgh!@Is+wamtZKKdz}wmKx-c} z;nJ6>7XRQR*ax&?FN_hvIzQetxE3%zI6snEWOHP`Q5 z8%*elB)5sE#TVkrBF1v*64qu6@#4qM-DL;UQaRDPxczr6Mt`T%;>l*%>^Z>CkZslM zvNsRzvDmE+?n+NevDnP=Y9=|^g%3J~O0JCcb_{C|G=^p{E$xKuU;P>^Jy9)G7COaoHX%PHEkNM`8^mJ{YWk#n7JFZ?nH*DP`RFrivww1A&kKvJ z?~gni$In#D-gqf0h(|+6DShsG7Dw~`YGeor?d+XS(qu)$Z+PNO*lX3nxScYNxl)(W zinG`b|6m<06@M!pgf+TYJ>ep{asGNhlTNlLMfgFhvxc%xsLkvhHDxjjHD!})U0qS& zT@3&F!v)R2{&Z+Y8LdKS~wr9LlI&XY0#Esl{>tG`H zw&tF#OWP({fg$KkyKo+3Q0wqK{cM9kL^d>`hSb2SK|t%uiy`_%sagT5D=%cu#{r|0 z`^AOlOSfK{vT9Md^AjCgEzLZ0m7yay3~)2!57V=}PeV?Mpe29)sL7HYx4@DeA8h}l zvWjbKH`Z~inDEOI6gJ+(gEihH0vq1KY_?J8a{{R!+QoDrt(wq?3IAm@3z$Cxk}ipB z|Kv-z`~fD{ybQ@UuFN*7j2h{(FJ57&eEFQf1GJ;4;w(?l%LOj z`(X@E*#ytdVqYDK=_Qk3Qv>~aaU2!#a;#NNQVm_#Y{hPr&u$WlmHgH!&m>V*)m`jd zXSU_?xOJYjTDdKxOYy<{ed&ia=BIcC&beC-vlH2O;4P+odjfAUDc;= zuS`80S#$qp5Oc`bUgd+v4+EdHLRC3`)i=KEn0QVpo$c7>Ez{ zUTBFnyo&WLJRVb6h{yXrri=o8`pV)}kyG(#uSqo~+9eb}Ge);Z zR!%<@FSSOggiVf*B{L-tmzs)QBkdGgo7q)jZCy_qi+x5~@34z)&K01QH7>~rRUq`6e3#hN>tfd0)$cVOFS&C+<;S=QrL6MT5AtUkiZ`iYO}*!^@n?9>qr93( z5Zc#yR*Xg(!fOX+FA;asB_#_wlg`t@&fg_lXql(Q6(qYtxHWkgf&lk$a!rPILLOVH=Fp{jf^ad}mU#8;+075f)~(oOg{Cdc4iIkBmAu72iHt-(9Hn4G6Y`k5xybFBY5RCCvQE)GfM zu3%Z~`|G>s=th}~8pm{fW@kr&yy>rL@0IG?xB>aIU&MVzg8m`_t{SO{YiHL?#qq?P zOjV0z`pc!3YkM09oF`-XkT7ZdQdrq!i+~}#%$ewMnR9E5X#vK0lA`}l7=##${)E?% z34ArjTNV4k6^<6c!tM$BJr32fFLba|TI}ZgYPM4rEyM=~lQ#M+CX#1VKBCEP44jwO z-BBMCect)s3@yCGIvcW79`DQ*8VlW>5x?ilV_OxHLQc}^l1YPZe9I*hT{Uygf+xcm z)&j|lp%Ex%a`{lq<1>^nwcPG`GKRNE?7;R6%F#q}#q2e#jnbTq*|V|0;e2(|whnDZ zp;PHVSMDQc6;W(i36m|Z!~R0D4O+1v`#oB5t3wnUU*b&0{KY*5H=@k$IbKBNM~5S` z^<^>(-EECwN!Met{%#-0tih9T9fiz7f5<=DeaLr;umx!h`z`kz7A{p+SPq{#vlzck{ob^zmrpjL{ z4~K2qS1b?qOiEqaIDTK6_J;RLRh*@qtU%!K1Ow(&r7g z*gdG9TqcP1I=Uw!U17%e2r?B{;wLrm7Fs=EM9>beazm91y`0gNc*|=_=Snb_mIZW$ zA9b5@qi67Qed+L4fIy(Z|kM|jZh3kIze$4kMCvIy*xLXz`R9TrPW z+r=15(v_rX_GS2?k>0e`%8xdSC36umB{wd#piSnLBHbseTOo}X>;i+NCf<99oe4-4 zSNIx|%`g}pauE&Qo)?h5zgKP`$u7?C!yKIUXLs4FHmB@K>2EY$wX&?De1c!Q+A7 zg3}EqsY;{5DTBM63$V6Mg#;=}7tL15^h0m=l}R`3Ly@8~=ap%{z0pug$(%2FK^2P` zWz3al#|60;Z{scMKPtRIOndFok9@LWGBTN4hF@xIek8vyR(!I#uRCM@z3Tdtk^|kD z8{ez1KXEjc_TGZO`O8FLAb+b|>^`n!jx&t?yU|jwdRpM4edXNo$dbamZn`YiMRx?-9ty0oeyl)*&R;0&GzKK+4)_>C4pnb#rCiDF#+#m0=m)pRJ zX@{q|#h$aq58Y6r+HHS*Q(6DnM??NKlZadr#&vSENV%O?_f-S!Wo)nMj{*$Mm9MRi zi1UN%G&;}axNe4gZc@4vvlUO0Gss#JrjOx>E1r<_irNlm?I0Y^yY#W|*7x@zkvGn< zYnOy+e+lEL`I*<&^mrq8y;Vv!82`BaKfK`2TgI z5NtgDGDgKWx)w?AwBJlBabiJ`cJ}28Ur&%7c2`q8uoc!5q~G*J;or%)5+~Co13`zd zlab`}kTDJKRGWV1ebI=V7>}qC%>9*22vvnuu6%v+T>&+3?aV#vph1h~xJ2>LUVM4l z!+R*P|D%%Fcy;q_qb+V0NdW#Re*J+Ns^(-`NJ!{>{EY9)7Knt=#(aM#Q(oVsBJ@+~&HPX=muWFQozp$f-3{#qv&*Sn{`sPh-LrYRIW? z!WHm`x)a>NXA8sJm##I-EE{I=ugwYQ-_VXg8D@Z0n;C23Oc!27=d=fsm|5t(XR=DH5cYk!qQJd=7 z=SyDg8^89tmR$~l&-v1CShYndePQD6X0&J{7E={A7gJ3U`Syb5$qVzwCohDpo?@Gt zLVEr*r-+2%q>0Q-eP?t%PnI3^p2)Z@Rb?{J)=E3AU9V74MPoIh;PC6vz~R@ZR+tIY zoZf9f6}$>{J;wjjo2+;4(BhW+nQvCpFMofU1HGTNV09tAM$wZF;T3M#SRO6wxoy>` z)zQNJrFT^^)KM~jfzjC8Nhze@sye{;|F+D2vh~4o>+^4xAGxWx4sNa82Yf_joozQw zv6KBYdVgb)_UpZ#r9C??ctao;N-OPQ}XZJgIy%;XQBcij{Hx-V80E^gV!`9IJDy zN@kuuj$obmOk*`}jB(fOO7*`}qgD9*jAsabq?wLG^=Ufj-4CBT6~E$#B=OPFjh!K~ z1PCE+Tt-+{K^N1ea5xbqk}1Q{Bi$6d^0 zSygx%4otYb$=60U1&eG3bWwr~o4Tlvy54jMp>+roOvo;u81mXHliY{;qZWQ#RoxAO zIPkc>sq=oRH8s62uBL6hRxurUvH`bC9 z1^BGd{|*dF$vP>c#pyzu6_`t^!_FnWLsgPO-%Oo~z`wg-QjF#$ z!~PpgkJ7_g{rMYmY^?giVbFjQp$ddN+9xX7GbY-TWh~G*N5Yar?^A4aWZ_qxt(R{kq=8e;VnMaX zPal4F|0JWS@8^pr8)y!6Lo0?!fs~ue;l{e#gZBpUQTpfabJ*P_*zc3<9*E30m~r5v z7dB`Gdz|(!loO@M-TF#IOu^oIR%yKz?|d&QW$Nm}TgnUXo}&FMGwr7?s4r2{?vRhR zwV-Kt@IhgyRLS?;m(Yn~Z2!40E+`5)$KSL-@G2vmPFf&1pcsC+u5Ou$W296WXqkBd z6lVFH0O(+%I3!2j|X!`4NsPt@5rrJyu#VZ$mf!WdZMc*r#X^=ju*0wt#pgu<(Cr?V7 zOygtRFVK$Cx%LtdWr40}p-i+tEahxY-`zsS2ElG0(c$`oiI1Vxd+DzCA*m6Ky#aR< zLpt&q4c|Ll43!13c^T#!s;I9!2;0e@e3xAAJ1tvKzvv{!M*JNeM2nNy&3=qPB?Om5 zX+q;WkrGzfcXSQ5`(Gs|)wY;xm>Osd|>=k{%tn5vsag>%#Rws@>BA`gVyk%hEy*0R?&M_r_EGyYtrf(Wg5h$1UQ;wNv z*O!S%yiTnLxl!VKn;Olo#gPYh!@y`*f4YR@v9|S!Qvc9dZElsmX)U7hD@pj!obCF|AXn%?>l$W z#@J5Hf=`=gkh08?fzm!U6SB--O@0nqZ${@n31<+$$y)p2(-w+Avxlg}&f&I?qAvG0 zzEtLmrauQ?1IofvK)D7eI@1IKJ)~3D_2@P2^$0X$XAA5cE}N;k(>9Z(rZJiR?EeY# z*lQsPx^*y{>%aIse9&W~J15uQR`BM8tox_s$+sGs2S1D*s=XH;4AhAwr=l~e{wvBs zi%p)twz1d$hWo!z_fHBU4jlIPKkTss_-{`5%T(6Bm_o{*`keIg?NoEvjvkC1K8i5; z(dO;$RWrd_Bb^gGl`8e}H05IfzG)qAc40IN8A2N0-^>v1`s3-C^R0RGlp0)-P_i9$ ztPZ>={wXA!|ZGBhN{WOo#Z-E<02*JnZbOcmzWz$+_49|3BfB7*T3mUNF%4D z{>R49_~?4lhz* z*7>aWesmj@rfqh0=3H#qfd zru=Q`+jwVq!+Z9$+IbDOb#+R78|_37#>IZp8L^cSPBy~&{I1ji1NUk$%DwF_(~|Sq z-@TOk5i%`??Nk3`_nRC3I#u^BF=YF!jv@P7ZkQ7n+ce@Ml5oUOhD7&59NC2Nik~&& z>tAHx1fcnE%Yjs_iwrv2R654W=68*s0{pXF?YA{K1|9|fb%8qgsxcKKN##8i5dXAw zflknD-Ib5u%Yr>Yq>Jz$q5JC&yKT}GU4oDLldY88-9}VhzPh{mHb44M`3aH!Im0>7 z{#9ehqRmt~!G-Y-(;X&K^Btzt-k$*xU?e3bp7s8S9E_xF?c|kqm`rifunh}hwYU=4 zh8|lmXpwJT6FZ&bUk&EaBC1JTtvsF@R2@wA3Le0@dp`a};kuPy-hNE7)fon|ayKh$ z(aOX@8X2!twjVlsTpIP)NHU$YFos`eDs6(l6Ol( zK^$!hzU1}Ngqesc_mVus`#~F8q=Y0Itjrj_pOMrob_GGw(SdJJ`#H`+P3s_x`E_v} zzGMZ{KAj|3CaJiR17f6&Ub!7)?7nl%_aUa>pjwt5xql)cCC}b(6&Dk^EHVP!2#i`i z@+8{{azyNa_*zNVMMDL=)cjhju}ydl@k(mO)6`P9#y?&t8s^@YzVMpq*b~f$UYQs#ojsX-_;sGx_G zy4sI_ZV9O=foN=OoHf=}4I5`o2*R#`QQ!}B#ko1CN~cEzBtR(iq*{yT?Z*VJJQnP( zfzOG;_?EY$SkxiZ#+`>zh@zJd6pcF%q7WG`bwFi53Sq;=*Zjsf9=m*|C@RMVeOQ<_ z=c|m=>BzlMZ0C!QES;WJ^nh>`&(11}gJN++b61uN#Hp9sc`GB6;)(j!qYx%X5BS}n0rRuR1E|k$3^iOu+iwb$#50Vc_ znXGdz3h}BFXaK>K>g<5PkJW%BNC5&25P&b)t0q7I;gsqaRS^6f8^ZUC1xL?A5)gn# zStk+@ssI55RH{z`LSZb>zydT#0D==B0EeDN{+8gY*;+4xq*zFu?@x z+D7OuX%|hUD75GDKVQ|BPd83ax`M`hTWqxwap95Fa(C+Ajvddz?Cv;pq?p7D3KCgu z&Ohpb58M?ug30Y43_TUrs=75I(9Q*Q-MP<;)P8=f@l%X9{o<=kyk3mqwt5RBJRP^a zR+DKnC6=8Iv1ElW<$Iw+3>|%|E#zk3F#WR^I1DFL1cI-`@dWodNLjb*(s1C?2a2Ia z@;9mlc@?g~BxMa`NRf+$^aPpSrnJ{!enlj#2p<bR zPg)b1GYF007|%6A33XYn9N~22r;y_~J-niHfr&nmJ0v!GjTm*Q#06v=;+LZH!DPbZ zfM*vk$av2|7Z(%FnO1gf^QDOaIRXK@wt3p^KA8Q9gFgN|Xwo;%Pn<&2Yey7i5wsw^ z(kCvZ^6<(C9s_;29=~a&-2E8Ir%v5@jmxr`e&U+#x$xi1yCNRZ`FDO0iT>rMz>=4I zd)ryepCrohw8?g=Ho)^JINMFcdwZ)-;ky}m^16(|$#)!~1uMy5RQZwh)xO@|+}MS$ zC#V8j%-D__%*$=KM2S3(dGqwEmmC56O;iGrZD1UpHqk*mZ3cCE;c+NlWa`m=B&xN5 zBd*CgF>9FIr=G4c6@gci5zHLEctCdlZ5iIkoFq=>lu(F)CsFa33ofL=?1J7hB@)d) z$Ovf|!!rW)^;5Oq^{g#QV_Fox)SHm+Pjc80PZ~*J{EwK(L8OCr*^tuaq#jk%QCjNw z<*-ura1)Gv9(I}gRI^7Q)4Zr1b>G305r%?$Y!4^uB-DSZ%D=PVCwk*m&7>~8XRg?m zp#)qwu$D9-aI{(_ka4=_^iWyl;R}$8}r8xvya)bw|`J*iBB0j+NWzs&rY3uup+z;`9{p0bP@sab@ zY_RySzkM!;Jey^or#|hZ;)SQWoJSh&PH4wVY-lxQ{qn639L1F8arCsu4cMB%21@r@ z0*)UT#L4A_H?N?+up+(2!_Ob?`%3$1Q8o@-YdGpWfKN@FM+G_iJGAT8oMV=EvZ?}N zs}|-K6$aLmrsD@n6HC9a8U;HGvDKvaH&4VXoWaO?9i&W(Z^3(JTRPE83k`!=)m1=<3CYPdU2t+}^QEj6tm&u40-`xM3Bi zt!nQD!jc_#N=~wZ!a}!<#-YI8ontgRw9=Pj4fAAQ$WhEY{XT52Jsmbo!2aL-jf@E_^JAVG>FH(anvroe6a2BA-@8k+W33611%H^guP7Hv#D0qwyA^c%n;-_|L>W)0 z{CdP%9W$?+mJ`+ecN@p1O6Z%`J?y)wa!WUR6-#_6{V?M<*zP5UFGw?r_cpy73s)>B z`fGz4d)AJb;i18lL7QXoRB$0P6P?ghT{ykqr6K4=$EzY}6=|;`ymO2}=}KYTp1~-M zE=^+Wl}-V^&Vmk^u98!qE$g*Gp0_OOGX>HMAfS-$rN|-(I5nw6i6Dz%%_49{`M0Y- z`F?l{s%&EVjw=1p?ei#v-m^In8qA^Bt=X-@;tNF^-w{xioSM#sKJ5`1*=ia9UL%Xw zpzFpy0fC8imMeD3FeO223&f{huXhODU%@k?Bb=iTkv23z!QijbK?o<&tt4wSn7aHcU% zCX-++=Igx_X7t&X34MBL6t-w&D#3^j$a2a*WTO{i0le)|VdR6NA7HW-^08V_kp1`+ zX^qIK;b>;tc8{7)LI;sc-k5p+TKD3?UMU)$eemkzt2`~Z8nXW^-}jU<93j}NXOM+A zleE!guOdo4gf1gKWxHv(w)fYCpsp5W+aij+SY#KjwocJZG2Csoo#pgYaF7C>KY@a? z!9d=avlf4c^&l_{3_5^%g_-2=+1V!gJl^JY4Tg(hM%A$*V6IqA1ljNWV!G{=y%lD) zza)zM(@iy)%o`T)R`@X7BOAnVf@S#0v)3-pa*~}qgd8@uD<$oH^4ux1oR9&{aZ~N} zdM!#NQIY>4b`!KDOtrtCp5+t|fZ(^cE5Sg~TVk|%T5Us<^{br|#MEdUK7>3?ijAZS z3O;FGpOA#-i^64ZHZN~;mFaA@uWU~TT}(b!qzGfE!C`PX{zDcrTJ{S?Lm_U%u(ZJn2|DP zgptu_Huu@n1eu~O5pR1%ZP;S+6YbWq{;*6GIK>a(6ba?oEzM`A%Z|?DOxkCy4bW}t z!|^}uSbKt zQu%@$o+g%=JIHh9;+k1auUwFNfeAY*=cB; zb-EF~Ts!x%gk)J*;lskyU36_0M4;;Hli?ox^rM4hMbt|^#cQzpAvH)2 zZ9kULP+0=0VnLRG9-rf{NEHJpf9#L9v~l%zI`~p{jfyzXo2bV)Xg2~r0yG`!ft`A& zzv6*1O40o~VJnjwh18A4Y(mI3N@QYh-m!L!qe{yBBO=^#y-jp>?{g(2LwUtgeqxe6 z&?<@-#{+V7fP#W@KnBiW*K1lEg<8OW+lU^OArdsYxbS+J+KH(J5)v$QB$M zsp#6K?j4tMl`D##e8RMkX-+VvfVv0O=R>s-%;o7*ch;^*;mRqV7d zSx~RJ`$ghtXqIqFZR&7pk%VIdK>JgKi3K-alIy3^5;g(PzmJL*)R1c*Zl}@_V#9R% z^M#4E#*|koum2!bLX}Qu-)6l;*c2B}>T1Y{4?J00TrH?s4+R8%kcFd?fYh83-#a@0 z<<$tqFXE!)p*aZ_)cif)=#|*$iyP}NvctRtOUqRmel+dG=LHXD7sh*7oac#N*k7<1}M^4%0)nV2`Gsz z7xdGwL^RG^!)kdBC>nrbfThp^N(!J1V6|KYTBNXAuoP`T@x@Z;0OcLlmR3Ny1}Jy1 zTA~3(mpr8PttBx(B|V_zV{K`r1_6bQ`XcxX^p}M7fQBlphD)?f91#CFLdW%S9<6q* zb90~lQZxropwzQF>!0>4)=v@Xn065J#pw!u8rm;%;=>umNT6w_w`Oq;a+k_n1#wA6 z;?CUqV0k-o@{xlSZ%&*w#2$vF5x!84F3^t=H?x*WLfshVie-2kC$~VkSEU6r*=nLj z9_#aBv(Yu}tR~sUu(r;DV+5RBMGW<-!i?nEFDbAztT|Gr$MgRawEVG zD)<8~w5nLfxQO>wIgN4q#%wFtNsfamCMy;NesQq-Iv;t)V1H6E_3YqRmzRN%3A^?d z(SMkZ0y);Acn$scPjshXW0f!>qPKQ2>CiZ?>Fg6aV?8Oo1-P7t=8`CSz zV6KN9Sk#sjA6Ys(Yq9nZt1_-B!H9x5;{R!t1iQM9NI7&BN!$dM{Y>*ziHmJ#Ei#xm z5uve>o|aEhm21^SJ6!m1tAi~Wf!i>DY{osG6nd`q*5;S(5u(T=qvOr-ub1d~Pw1L5 z8gf`>&Ny?FA2|1jNaiTB(o+fcXlBny+WfA@VyisL2v3bC%Fu}i@+~w|IM>-;Ews~s zNs7qpEZ^FczDK~eP%?jK^-J1ksfeF=xp*#$UDEu=EXsA7Z$)V?hn^a~)KCt8a4}yK zPR}&?%deCIQRn(rywvF zrXCF2qGkrW?uW-jqQI`5RM3eq@DQDsM+CCsHpJ_$fQFxCTboVg$>)pcw3Bns`m@z_ zh65@)_3qu0aWY4}xSJCdhzvLBN`dy`8{FPXQ4ROnDRXkBU>%x$b21SuDd5KD*iLJc98`eHEBe#(2 znu4s}qiBHM%vOXYzaVU4JKQl5WyXhFi!(xd?5L3m@l!n6uH8jU6k#>i;$WU^)~VBu z+PJs9`4yOm3yqKD0XrH6O(cPR*AGvAV5Q(*^izSnenHsGMz?ielo@n+hKsx|UPf>? z#5<~nqXdC6BOnGLwD-k8v9tOZ6d*bh@dO;Tt6izbP8j)**~m9oJ%@qDSjvqV3v7bK zw&okzt{o<}z#ic6a1k=YyKAYhF%KR-{li&AfwLUg|GHbCMj#cHO z|LZc0@|M>G#6;w6eezh~+H!Q~Zr#21|IkTX!pgeQR@!>^ayM*%Ss0=}W}V?+%@X)Y zpSbM*cA{Nl2k!?CxI6k!LOd@7ZEx>&MH&fn1RTp+9LEO=;i09x)nD>z4_5eYgIJ2J z4S@+xc*gjy=d)9`>ns7Tt#Jdl7 zh7f8?!28 zml0s*J_e|j1lSZknVD7yvmiu%S;+KC#pOM3;(?!4 ze!^FJITZ}(*b`XZrk`@1dBEK7WQGTcUZm)+zyd5%Q{@93Q$WzMG)d)e35l;UaVL$vO|_45!*&cD?3~ zPQO8mrxxdXOrTPH6G|>k&+ArG<4nglDiKZZRAXcPq+HHNMN2i=vcn{+4NADnAoL{X z>OoXMfbf;%Uef4vNSK_OAjc&-UoR2~HZ{SlOLWo`M@DhR@`Bg4^)s)NR|S{~&!yB> z#c{Q(mWJti=1gI3-O(z62&nBxk4Bl&u-JdQ#Ka~_n~lY0?ovhAvbh^USGRzJce3a`@bA6RL#Nl)7wK7SRxZ)A z@MI{rsY@br05kv`0b&3O z0J;EH0m$k>JAej&V|@sPvRNbHXCce3GJtA;Zvfu``T>3c%mAzaYy%tv;0jxIkpf%< zURfs6PNO1h52f0B{5F0|*0%26zRK3h)8oGe8+YHNZE3?*RP( zzl6>4Tp7QF%DfmYg8;|_+yb}_pbVf2a0fsg;2wY$zy#4906hg3Ocz?!iAvct|ue@NYpzP?TN}J#TV{M&C6#VLmoKd zt{<0rfg{ynsd?=P2w^(mW|hTJ;d_6N=1^*g^g7T z53DLT#6U^)i9f{QSn6lbJHd7td3M5TronlA@WenJd9vIVtTji3I%C9a+fq$t^;&?c zAy(#_l>zV46pJD>MUWsn30Un-w$Q}~{i{$YVFj~9D{T46{Q@BIW|B~WvHfWs+1aB0 zBPLJ&i)GYW?Rgp)h$a2$?O$uoWkiFHv#3+_v}$Yh8w*`>Z_ssSlV}wufgbwggJ#f$ zd{3EXi5(uv02auKG6Goe`9IPOF7`rSuTI0QtxZ1r%%1hxy)V}tGtZ2mnLTlAMJRvgWa2aC&f{pXPd6R*$9 z)6Z|z?YT-z7-Uz^>$iBeMybNsdNY(Wp;|KR?z8EsnTB38$fIm`hc_y)#jm@AUt&WC`kqiupODQ0DN#Se!(6L1-iq4nPdjX9z_;YUyqf7 z2}baN@N~7qh`=}mSP~oU$!8!RA-fHR7)QkDSM%HmY%Azu-vosm82*3)dQ0yWT8VD0*7 zVC@fJ-=D6P`d=480GMJ_9smYeM_`b(&E^gcixT{o%K~O*ow29&3S1WKiGu-p5>^}N zwt;hpgYgIGY5&~_Z2Cunc3^mu3HI`Ao%jF+zlUkS8tgC)s|E}ueyaiFlYd;Lf4^G#U>;pbA6!;~KDE7Z}jY%VKYlb?}0tD&Qd-xO-4zgpB3Kx48A= zV=cuFOR?-x5c|s=iz74mrzT(7`5!g~R+8C#(9GT}$iVKP8;spVgsoQkY;mvR#+%UU zW8E%#L&2_{?c;I*bTcxLFBmluptl$s`rhy<72=>l^;DEbKeE7%2sJ|IxU>No|09U$ld0uihZtY8}`?F33Wu{yAV zEx>363>vHstY8xent%YO;hyQ_x5)KOO z7;{=So=Qy*WV!Q)*-U3zwgacMC4}v`a=YC4RT=bHnJSc)4KziACYAq&C(-BHo3!Vd zw$#!79B3skrB1Y&|dOf{B>l|AgzqccbKZGeUP!=$z&anl}q$zvrDfi8&nT zA{y-VkgA%V^IqB0C-v;Y0lv~%Ngtjq&%5}qEqu((?S=ElM4sEN2uMIC!nvA!KEj_sR?R{V|ecsO<+v$0wc%?|Be8}y{{>3-9 zN9wo8t9vR`S*t7KY=4>vO3eJMd&1;DBuZKJ=E5^A^`1K)vajC$aO1YB=F^Ygij$NU zYYE{mt`{{4TJZ-qU;jGbw7c|-c$wxG8BM>U2Q?S|hj406#tG6c;=ZCUFBm6CSlB+u zT4Y;!2q_aQAKZRw?y)k6mfpRrOsuNbBdR(i8uv{#a!F@&i8`a4$@uA9=DOT-uV~`C zRpb)4-2}5|f0~xRxc&x2tG(_tm-PE#4WoHQ%Vhm@PMMH_^HVr48|Povev{=;rb>;? zEN8TSN>}P@` zC%8%FPN&&@mb#BZOEzmupcBt9s9G{cCVJcN(NpqNVy1^Q7nfr*nFDVmxqg)NTiNTB zCv{i|i=iH|}hgk0~#lzH79{4y}V4_<4Ez$D+UH(_Ijf zDNZAr&vnHiN#t{q>q93G1qTT~J35++%$iT}^P*m&#Az~gpyeg9Y9DJMzaa&(t08>}jAtstWQbT>Xmf2z<(h~&(Drzx@UVaJ{t z{ub((FUb1@K7P`GG&`d>nf#VEb>EN71=By0wYc#f`T5|Nfo8iPujj#tY{2STbytR~ z_iEvgNHW=wDY|HNsJI=2K8PW^8!tGn-S8D3jaJwE;#Vy8Z13~=G~AQ zA;SSK0Xuk6km&lF=%^&mjkqS@GnDClI^&y%AUWD?yX(9R0XH@&2gpJqCXC466yTuG zTv5?)%&^>&X-(RfYsd*K`TgRe@T)gIaNYRuWJ|SmCN^4tjX6kTQHRm^AwI}Up82dv zz;rXrU@nhpMcSAMxByAI#fPQ+4asVi+3P z;v47#2Qw*{n6*w#1)m?cXQ9o; zADsqQMQ2UP85d7d!IuQ3&-@ikAF*xYEW1?1pAU1$pUjl5yo{&T=I5x*r|c=qG2BAU z+ak{oVg5NecNeepSOGH(J(n{Z_aq@TXRB#M@6JwbUwQ3Q zh3rugv-w?UBUdb*Q4qio%2T$UjL1lV{ zje{ol<96)`leOc=w;Rw}4n>Iq?a-iehU=D&L*ovGNuw8dkJKluG$~#TeQwx`8JDC& z(MSkQ!AM%ymlu0~7+gl51`ND3{2u%W`ihgoNalNU{VnGoLxm@}IA~!sbmc)}&R$uN z>j5DWyykmObvn72pyw#0Hb1RFl&ovQPbWF10VHM+kVj`%IhYlC&I_SAFmC6hm);>h zDGltwQ4$MqR97ixiz79DU7|g#>%69Qw}GYO3!BMy%_3iKgDfMcsMI>J_ezYKy`7S) z7Ig{oAyHc}!8j95>S<^dIrgou#PGKM+)!|$EaNqU_?n)cVuYs>n|APWr8_d|Hao)G z>ygCORxnYRR@VSq$STkI_V%0Ise$vu1H|1R-y>mV$`lDdeQwJMZZ(v+7z;6W>TaqS}=B38xaFhHF>H=6*(Z$*%7CzBV(R{CSSK7!+h? zYI!!q(mU@D%a_bt=Qy5ah{yDU@0ywKnSV_1(sbT=kk|Re{MW6L%wKwNs)OX-_Zy98Yt6f7bu5s*C6yrgTc?da+rCxn2uLGcFamOPI^Z`& z;=9X_VeOnN6*nyqI@9Z@is}%XLoyffb_!1QGnVmPza5> zP5AY$v@`+9e$QzzZE9z{reW&#^(DEV_*qjJSg^Ctj>}TU((3re#yg}(6~^RshSQ#7 zfc&i&&r1}Jcl$W}5NC^TMov&U?b9npZB)LLv*?}8#NJ`ilaT?dgS_#E=3WbhKs?h# zC~_Aww2-{sqc$^A&X5-vur`a|u`r61UN7w_yk_TF6L{9{z(QiQ7)q>_kWnT~?n7C% zT)7_KR6Mu92y^q^ZAaNWV-HH8B$tE-*I4#B9S5F2Yu}!j=NpOH^4jTJjK_2r=y~7j z{azGF6;@Q#RC%Vfx-okmcyi$F+lMZBao71tDJ;0R*rhKqU~18SA3d68Ih|UQ>l`oGm@=&w}aBjULf)r#dSokec(!J<<9i2YK-zzUp(eQzma5M)G5)g zs*m!YXVZvrAzV{`C~U6xA?$*G>-fS_*9;Bnex*1brHuwH>M;$yRhOE|ijI=1%1VW{ zstS1jro3Y(IbuK0qERX7708dMtkSJ6iU$&zi7aS8Q-aYv&u`_+uuq|QaNK|2sCqYN z>=c5(@A2?;vG~1*uQSCTV*lNHI2d=_J@Y0`d~U{bH%ai!E@k}5vT8HX9~G@gOApe1 zgGVmNE}-hCkt{FXomAZFZTt`s5g+|9KuuNUbN%cGF3%sl3_^NSIx&l3mKuvIvJM(G zz}n*Z>~EgY`T6vDSU&Q{Xr}a=r5F#-YHvzvjbT5N-YEQaW4`x^c%@M_DB~_5Q{eDxvc$yLpwg z+b3huDd5q4yZnqy@}}O1wt?vNv&Y(JxeF`lfo^7 zw1sS&XQkeKK_?}5dgqI7dMS9ZW*Th~9pX`lZt4p%xJSDSgg`4*#y2*SKTr(y`l=&{ z1ARh62yt97)e6{Xw9;CmL5aU@an(rxZ(V=aXk$!Guzz~akg}QKH^_UnL(UqI5E6VZ9S;Rf7M>3j=yu%rB$#*Wu3fFJ$ zQ-gn^8dQy)%zqB!90PG{c#b3I#uC9Y#yu5RZ*oBFJD1saH6H2Wb1NPxdLvYBTOgVK zy|CY58pO>s!(g{#tn_XY^yn3D(k%@LVY0kcY6#Cy+{TKNJ$(MqBr6!{#A6~9ou3_X zNcQYat%Qa)d&4Oi5dCC!0U{fn{KT~OHEXLzr%vtKbyF`o7lQ^0&dstQ7B19`j*4sk z2fv3pRX4;J@Ee)kaZy3z0=OF8Bq7;K;LYKW<~rX;LtG!tjp@{4HL)7W@Yd(J2Px8@ z%spVg0wagkm~|5eta13Hbd@z`8z+&l&zJFUUQ4zKTfN+35iiDLs@Lqkki^^!ithxnBzfj4U<&GBpK}p+YsIDPVEhHE<0cjAD*pN>y%jj})8_x?=LDp8D zka)X7T*@7AXC~1E^>G4t$o_`C3utG;F3(yqR3*v1CC`p+``~Wp4f%EX_exNGA%`HH zMzbh-ubL@I{tseIG?o4l5-MWGm5!Rwg4QrZPl;eVQg1^c=sd6e{B&B)v3PtyZ}Bzz z%tR<*#?wmUjrepZ5i@$Y-o;TjcxSTEWIuif?N^~q243r+a8gD|@w#Ehz7+rI?6JJ; zhTcZsPSFeRn2lnHU5v|AOYz9<`PrjW_(90#X<9774`(MMU&4B$Q%u%lxCy2<_Kwhj zqgmkDPJA$CnDtjc4Z$wjO$OtunNH#(uK zl%|oBkMKaiP!)oUn5_)kb?w5>D96XFCdlF~7}OlyZ9MHTv7lqWSnNYLKRrh@I}u8M*e zASK){;BRHgkY{SU4?NBjYUwh);W;Pq__b2ksm$?^-|;O|EBbDvcu=H}*dZH|d@~ynq^1 zxZHg9D==pyiuc!fbD#fJA9254+<4WEx2V1)IWm44ZQP_N-U}Kni6J~QzU0H8?$|;b zQnRNvSvwN7=tH;7j+7+EJ%HWB@m{40^+%+Fw#ddELkO0|D4x{s+pqILfArTUS~Wqj*OzU))M(k|K|@FhoT?;-t}j z7tOw<{P|@R@BL@Wkh@z~W;&yjH@BLVQN@i(LSkI;sq*ha5zRl$;^=at^eOm*k7x)Xc@o-X8jMU{-%gGHe)SU{ZEee zH{~A&MWXbkYL9-ENeZ2uqpJ6ZBsb2t5;xe-w{3UgYK_Ku(Hk9nReJ|ey|=l?!t-7k zv+Kc>0h_B|l8t0Pm9Qa+_n#YnAF&JB#Wkb)CYu$oM5*H|kFY}=^4)yrJwnH<{eFbQ z)KvfEZcTyc$e!UG1IJNfuYwVSq(Q?W9iMMi#g(iHH`~Ny3{zBxMaIn2jx#0d1gqX; zYB%FIu^n)oi(9vtGayASK2eaVtJ>d2s)8xG+^TIJ@v3UEJ6mfLl;?#>ZYenXDw_^V z$|(!7JJZEWd{$!_dLR3QtZ|}^Yw1RkjNyOYp|1b;{l7o&`#y7?^PKbip7WmPobwt+ zPeIR_p;a^nzCva~#_p(d1n-dV9sQz*?VEe4TYpkOdmekPl~4-Tc%fZ=A;u=Cy2~Va zmHX+!g9m|$S8lE4*HtLD(LjLW`EZRAj-q|#n$>F~;}x7t39X;b>wf&PI)fnV>2)bV z8CYYNw)*aPf|nj_!mPROHpo4t-@aYJ*(zLnM~l(8+SwKRwyLhyWibn*j@+zXCW+yOBZdSJ?gbw~ynRaVkymq92sP2}WwxMpG(YU(HzBOCN z((Za}>Dc$wZH-s)QB!x1T|!MpmmcS7;rDTrb~^`qrRp_#jPE+Tf&f6HHguL&TNdAq zjc}xBmku@O{)MW8v)n`#p2Jo1Gj}`Ss^~r7Ue5TDY-&wbS+Zm09xK@J;@gPe}!3=}~@) zc52Z|BCG*l?Eet&)4$1p`DL93zU-x*FZ)REbF2% z^KF6)dk?}boqjVb4kZXVNdj+`LP@J4l`~I?2g>#t{4E1bvO@Nh5X;O;($)h*ay*rj zmW9yna=X&rAhb4EVM7pYWuRK35G&**LOZ95P<4R3U8-r#4|broiv_B=04oZi-ETEb z6E2Zf0ceL2Mil3Ovv7$iQSyos;^OsDU2i~H0><4$Xka3C1HrTJxjR0|8`i=>NZ5|5 zD{_cSH`#)YkW{F+y{i!K9#6|!gtQJg8$m(e7QKnrI_O~`=cyK!cLMCX9gJZP3Zg+l zYtU2SK-ufek4gyR?y$pNQBXj(@MYcc^}zYh&2$*vaFsjj;}>(yTA{S4)9zGyZ~ua1 zbV)zIq>%3Vqycx`r7ZdS!r-uhZ7UUb?ww}N6jn2kE;}BmCQ?z$xM-27Jl@nXmAP4t z)a&os@w=0=i|ltow7U0a(+QE5;l}A@CuCiV`13Ep6*DsLD>QzdFL`Gq`+5HQ`Jw0- zZEdHf`L>S1%r|l#hh*W;s&#rQ>4CW~`KxHhCH7#cj9;)c_t;IO{L2KIb8yvfG-l=& z#^t>|qTXkCuY&0!K2qhTP7h*9yl%PDp~O|4@6!GVq?^i?J~BCi$BuZL#dqyjz)Ax+}>6_kAG}me^+v9;hc9&y+R05wlJla+N z-7mcC^g@4$H?7{CJX)QkBhP1t1YU}wkV24r#IY|L$*bFNCP#O~PajtlKAGQskH{>+CZl5XsWf%ct88TxIr{dy%)ec1>`y(GJ&EKnUzcVUefa6n zu%CO`%1)y*Ia1e|jpc?Jg7f`k#6>FQAx+_DcE@E)ua9YxE=r7B!(Evp9ZJb?qi0<2 zTgj6nl1-}^UR9V>TLAO9WZF%F@4bU%M5V~(DvXs+MyOCJ`r~<@+m7dyPrI4T`CST8t25?sP!e-%C;*7}!a#OCd+qpKgHzVfZ3b3b|ITH$RB1vtTDe~k~0mLroU zq`ntDN?R1nK|M~eai|n_pXy;yAdg=m_Ul^kR?yf9dm0oFjm;0djS1$!fb0jP41y$V zoYAhCQz--taJ#@RYb{u0k4{)3`ER~LF84H&JT-y-3M3^jJsJ z`G=@Xr((N&PF9d(by(|8Jwa4a4{LozN^?q=C#kjOO|^&TwmTX2TmcdrFx&)kF!fLt zmRsJz%WRdP!Ht<}$H0y01Eh6fc_`r1Fabb?z!`~{_=y36cg<@OFARwSqc}_^7 zc0g?h85n)3Oi_@-uR!epQ3TZv84nzP|Aa-ZLP)|(bS8*M=uEPU0^k^^@gTG;6B9ZQuAQ&nmzJ#$(mNI=X1d~v{W`nP`~TXe zT5Z=^Q&W6vU0Cmt^3(g-`gdnib??%8=lP+B<}a9;adRQudh8tAC66&nBv)>TbMW=% z@^!PP<>|-!Z-c0%Bgs!58n+8sQt3t6xO~)|1*8`ijNIQ_vUdu&ZA4 zu^v~q$Gz8!-{`Qb!*8yuIAE?RL6@q8KQ`KVWOse&Q*!9(EYr8Ud^$}ylY~7??pnM{ zBHvWblyA6yAj;K1=8cV?vG=?}cwj@{%yr>zeW9`6d=)Tld+#ID`a*A=lrY@u!slBL z3Ngk-4|l~H|0o09WAni31j5VItppz)IQWzuC=jZ^2!ukg0wF0J2vt*6C1|~CB2HV% zk?OZ@&QH`~fgss(juKbA&_9~cCRHz)Z16`uVKbThe8BMS;KF_HG}T=%H)uPJ&v$nC zWm8WV7d&>LK0AXDk6cyo@Vq^)Y3-bv@;tJu`>9)|jUJ(d`yE<*d4nFvvHJ7V2f6Ub@EOMHN7eeP+hqUfI5mj9J(u><1`~7(hMkrs*_M8+U)O10a=*Vg+;b- z5F>3(kCrhB)EgB{1`w_Q#~sScfk=7Jb->?%3JIYbc5#!0zSzobfsP-iN73f+NsEE7dho=e;hhiE@sSV`hNR4q028`!w?)Z(`^Zu#=j z;ZOqBz({b2T4)~W(F6gz|3n}Z8~yS`G^L)5lS3`Qet<=z=1ez)eov1ZUiZw+Xkqm( zqcs?7Klc)-y#^j&A+KA)Xcf5QDmVuB!8)|!FwpIU=nYR!5c_ToJ51Irn9tp}&j|6$}NFY#;gl5qr^I%fQ>P!_Cv;>^45z86#+i9T7N͎N(;~4wBet zjhHu^XLG~76cR`|aK3Je7C-k=NMY;ao}o{duq%#Ez8ge=ZT1pGO??qD^8FPhdj+)GY?d_I5#Yb_aLi2_T+ z15jluPM`+e9GoRJs8=mLzuf_?s2y268(1?`e?V~I=@TSB6u6)qSkyObd@ISJ%7GL% z+g*ji`ER!a%5lH3t=vkL0RHEk0DR$ClbT`SnCA4vJM;9prHfrp?3pk9kK&dtwG6?S zrAt7RFZuIJYyYK-hQ~j0@ah6rAh*!27O*g*Xs91{daNUOX1BVe`NF`5ZN*;9NO}%^ zWOY{=F?RmeyrH)f$61Z(zee9S-}kA;KIVLOw&53kyScC9fSBLV_M*%w{!sedZ0IQN z%&w)Mn{@=trMm{q)pmIoEew`%raNpFDw@=;Ul*-qJ-RVFJ2AmDG$`CZX&*bk`xK8_ z_^&ThDOLRTk<|mt_RrbcL=W*d`tLjQyiT=-oN0-wubtc!>#yP5dWzv5^ZZ7gzSU{H z4mZOGfd>o!W*k=dom?_WmS$THrKbn)`g`cM_pqUDYvkmXlQBfabJoS)!^J+$$_J}# z2kbLiSkwnEHKH#wi*t)D$C*5DPW#(=w_sn7gqrcnBJI9*njLRyXmW3U5uukeUg=Y< zZf}}>HMeqnebsnmAIk{m?M_m`d3%w1n}=G^jDkFV zaQ>?%x|sJbO^U(3yvPh&C%4*xsdd~TTeD+#=s!!Y>uk}k@KCEj2l{4%pOvO); z#a-NG-I&#YO+gsNb(={G`w1m{j<}FHQF^GV(j`qSR=&c7lfF^d zj8ET&OuOz8eI}n`qn~0Um$E&UEp0qHFq?R*Bn$UA{Le|Y#UWnZpH|0%2-36B*uVt% zut-TUtAa_2FujqZA(r`q1Me)(S_&oqu1wj{(y{iKbepAqO%*c2{?sTFfq{2LZ+(9r zp^>e&tclwCdM@TElDIr$%q;f`Rr!OopsiSp2=6-%SiC4dGo@7ZM*+s_>Q*(>3hb~_XyGz zmIdtXXFRX=+kA<1!N??q^p~E{TtV59SaL#hRKldTp@D5$P}caq8qm0dNju{NFP}Su`t03uSC$VwuI-01uvE^V#sR5&d&4z!Q9eD zSjDS?<2A`0IP|0X80Tx^%!HS&4;YxY0v*3>?~>zdCsR8KbONLte4 za8}yE@$9*?Bc{hrj!2%oV-YA6u@S4XS{CEBZFSI0>ZUtFVOzEwuuwi+CAYc9*s}D_ zYWRq$`eu`z+pCW>e|IEpyIY;f2lJZuCb*-wZ`1lu*~rR7Z`}0M_S6#uK;lHpHvFu8 z8dj7Fr-cbdNE-VO?B#ZlM8v-?{>MLVqA&jgx#&0Ki;Di6+5S<)Kj05$US>qmZ$|ug hEX#4q{4Xq7%T@dz23-zog$Rlq3*RhguZ&~h`ag<}H%9;f literal 0 HcmV?d00001 diff --git a/third_party/date/test/tz_test/tzdata2016e.txt.zip b/third_party/date/test/tz_test/tzdata2016e.txt.zip new file mode 100644 index 0000000000000000000000000000000000000000..623cfb1537c8bcb2bae4248ab97566713e327eeb GIT binary patch literal 128440 zcmbTdcR*81w+9+Jf;6QlRY630?@hplG?6Z$iGT=%gc5oYM3kzcpweszg7lI=C;_Ak zC?GXJAQb7nw>QCa?m6Fg?|Xkd&7QSq&05pgduFZQtbI#|jGP%l4gUA!b=-jb>mLJz z5#r^4&(6zENA+cTF;RA+}u)rY2m-sof~p_vXuqeHr;a_viRs zs-ZI>Ymw^EqngMe9{MA%gM)?W8t%ozWpN*rJB&fx=Fnrqa3_REzWvpTncnvAjpX{_ z==%ET_`~(}&Jc;8{qY>0`_msQ@tF8S-~D`oy2HYBQ|YQt@b=hP!GT%ak=N#Y{-ag1 zMvCN+hATsXxNk*e&Rutu^MVlDlamYa>Qy_x*Tk#eu=0dFbWtl>%odIAtGz}hM^o@C zG?#Q<#x@gzVu$BIeAwZckN~=VVQdv8P8h2}Mo$Cp3FV_wj-6JFm{$D%m6o!1y0E16 zJy6Lv@wLubsbmdEbCt5LLa_#3H?~IGW)uE3f@WJF;)SQ&?(`OZ8Y~!&Aat_KkJ~SWRF4JX3l^a>n z-qd@3S(kawR@!`!mykjA&JJ}K{+e)_UyPe62al{|Dck$~+tA6@Vo&={Kwt#-5rRin zz#4;oV$gM!lZ|1MT7a#PV)0sm1AZmQrQ(-mA$dSvSqDSRjFLk4=$>`@CgX$4WQH(T>$H--FqLjmZO&YI>WRik*Y~L4ioK$n>RA|M{twvBjpQ zAzI6mK9e1=+2uo8LcStQa{rZ^*{j`!mi+R)IYJxi$OUFoqox8octc>}HtBLbdgEN{ zff}#|I578*G%dB`fIbY3j4B^|ry$;K|=^ z8e2k%+rSQUZ8}rpLxKV~4ha12`>%q32}BM>(utorYX2zSP+TJwtjwRjG?>%z_3%~a zz2u+q93Kbd_>@1Zw5#ulggBkpom8<(zNR{dO^~B{! zVX}Br5^j`Jy&E4sE*w)5{*)TG0cEi|ljm!$gVi93J39|i(8res^^neUQ1r{w6#NX0 zC3Tgx&4GX#1hKi4I3a8*B~B1)P1aEhAzhTkTa(bU!*7MkrcLuvZLxRGaZs2O{F)j# zzphk{2w?#ul@#1on*fPEADV*3HUEg|4ZsEuzl%z~nXh&JN~QIfp9aBC(7vazJG$)*w0 z>z&1_yXdC`m~;dwvR3VS_KE)K8?uo2G^c^<{+u;yBD*)@KTgw?pC#3QKFj*B$tTUh z=CfoM!;K*sIyvh*-(!5B$z3PY9vZ!Uf893PR*qHiVjGwD8TrrPx35XTCZAC3@{o{=I$>#=HgeO)?qV)ErEZVccAQ8I6f~iitwr0<$|~auH3l#@E2h zrwYunKA2T%xaQxw3I=c~hK+^cJjYIPoh*$B`f*O(*$APOv23`hor+WWN{W#yO)5cb z;ZB4QRL8{dc6C0(XpIW)0RBGnTdqTrUacskOvR*2Y z?Nw%ysOyj%8-D@tkOC%